aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMikhail Borisov <borisov.mikhail@gmail.com>2022-02-10 16:45:40 +0300
committerDaniil Cherednik <dcherednik@yandex-team.ru>2022-02-10 16:45:40 +0300
commit5d50718e66d9c037dc587a0211110b7d25a66185 (patch)
treee98df59de24d2ef7c77baed9f41e4875a2fef972
parenta6a92afe03e02795227d2641b49819b687f088f8 (diff)
downloadydb-5d50718e66d9c037dc587a0211110b7d25a66185.tar.gz
Restoring authorship annotation for Mikhail Borisov <borisov.mikhail@gmail.com>. Commit 2 of 2.
-rw-r--r--build/conf/project_specific/maps/mapkit.conf2
-rw-r--r--build/config/tests/clang_tidy/config.yaml8
-rw-r--r--build/platform.md2
-rw-r--r--build/platform/linux_sdk/ya.make10
-rw-r--r--build/platform/lld/ya.make18
-rw-r--r--build/plugins/cpp_style.py2
-rw-r--r--build/plugins/pybuild.py6
-rw-r--r--build/plugins/rodata.py12
-rw-r--r--build/plugins/yql_python_udf.py56
-rw-r--r--build/rules/contrib_python.policy2
-rw-r--r--build/rules/contrib_restricted.policy40
-rw-r--r--build/scripts/find_time_trace.py34
-rw-r--r--build/scripts/gen_yql_python_udf.py56
-rw-r--r--build/scripts/link_dyn_lib.py42
-rw-r--r--build/scripts/link_exe.py28
-rwxr-xr-xbuild/scripts/py_compile.py32
-rw-r--r--build/sysincl/android.yml28
-rw-r--r--build/sysincl/darwin.yml2
-rw-r--r--build/sysincl/linux-musl.yml2
-rw-r--r--build/sysincl/linux-ubuntu-12.yml6
-rw-r--r--build/sysincl/misc.yml40
-rw-r--r--build/sysincl/stl-to-libcxx.yml2
-rw-r--r--build/sysincl/stl-to-nothing.yml2
-rw-r--r--build/sysincl/windows.yml10
-rw-r--r--build/ya.conf.json890
-rw-r--r--build/ymake.core.conf112
-rwxr-xr-xbuild/ymake_conf.py518
-rw-r--r--contrib/README.md16
-rw-r--r--contrib/libs/cctz/tzdata/factory.cpp4
-rwxr-xr-xcontrib/libs/cctz/tzdata/update_tzdata.py12
-rw-r--r--contrib/libs/curl/lib/curl_config.h6
-rw-r--r--contrib/libs/curl/ya.make14
-rw-r--r--contrib/libs/cxxsupp/builtins/ya.make14
-rw-r--r--contrib/libs/cxxsupp/libcxx/glibcxx_eh_cxx17.cpp34
-rwxr-xr-xcontrib/libs/cxxsupp/libcxx/import6
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/__config34
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/__debug4
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/__hash_table2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/__locale2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/__string2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/__support/ibm/xlocale.h2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/__support/solaris/wchar.h2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/__threading_support4
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/__tree8
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/algorithm4
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/atomic44
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/barrier4
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/bit4
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/chrono16
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/cmath4
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/complex4
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/ctime4
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/deque6
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/experimental/functional74
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/experimental/iterator12
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/experimental/type_traits12
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/ext/hash_map10
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/ext/hash_set2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/forward_list2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/future14
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/inttypes.h2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/ios30
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/istream364
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/list88
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/locale2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/locale.h2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/map4
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/memory8
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/mutex12
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/numeric16
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/optional2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/queue20
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/random2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/regex8
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/set2
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/span22
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/sstream86
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/stack10
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/string110
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/tuple10
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/type_traits4
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/typeinfo22
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/unordered_map24
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/unordered_set12
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/use_ansi.h4
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/variant8
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/vector10
-rw-r--r--contrib/libs/cxxsupp/libcxx/include/wctype.h2
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/atomic.cpp6
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/chrono.cpp6
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/debug.cpp2
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/filesystem/directory_iterator.cpp18
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/filesystem/filesystem_common.h10
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/filesystem/operations.cpp14
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/include/refstring.h4
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/ios.cpp10
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/iostream.cpp4
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/locale.cpp2
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/mutex.cpp4
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/new.cpp14
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/optional.cpp4
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/stdexcept.cpp2
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/string.cpp2
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/support/solaris/xlocale.cpp2
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/support/win32/support.cpp12
-rw-r--r--contrib/libs/cxxsupp/libcxx/src/typeinfo.cpp2
-rw-r--r--contrib/libs/cxxsupp/libcxx/ya.make42
-rw-r--r--contrib/libs/cxxsupp/libcxxabi/src/demangle/ItaniumDemangle.h240
-rw-r--r--contrib/libs/cxxsupp/openmp/ya.make2
-rw-r--r--contrib/libs/cxxsupp/ya.make2
-rwxr-xr-xcontrib/libs/libc_compat/update.sh10
-rw-r--r--contrib/libs/libiconv/dynamic/ya.make30
-rw-r--r--contrib/libs/libiconv/static/ya.make56
-rw-r--r--contrib/libs/libiconv/ya.make30
-rw-r--r--contrib/libs/libidn/dynamic/ya.make20
-rw-r--r--contrib/libs/libidn/static/ya.make84
-rw-r--r--contrib/libs/libidn/ya.make26
-rw-r--r--contrib/libs/llvm12/include/llvm/Config/config-android.h6
-rw-r--r--contrib/libs/lz4/generated/lz4_ns.h2
-rw-r--r--contrib/libs/openssl/crypto/ya.make100
-rw-r--r--contrib/libs/openssl/include/openssl/opensslconf.h4
-rw-r--r--contrib/libs/openssl/ya.make20
-rw-r--r--contrib/libs/protoc/ya.make6
-rw-r--r--contrib/libs/ya.make32
-rw-r--r--contrib/libs/yaml/License36
-rw-r--r--contrib/libs/yaml/include/yaml.h3906
-rw-r--r--contrib/libs/yaml/src/api.c2698
-rw-r--r--contrib/libs/yaml/src/config.h2
-rw-r--r--contrib/libs/yaml/src/dumper.c782
-rw-r--r--contrib/libs/yaml/src/emitter.c4596
-rw-r--r--contrib/libs/yaml/src/loader.c672
-rw-r--r--contrib/libs/yaml/src/parser.c2720
-rw-r--r--contrib/libs/yaml/src/reader.c928
-rw-r--r--contrib/libs/yaml/src/scanner.c7042
-rw-r--r--contrib/libs/yaml/src/writer.c280
-rw-r--r--contrib/libs/yaml/src/yaml_private.h1266
-rw-r--r--contrib/libs/yaml/ya.make40
-rw-r--r--contrib/libs/zlib/ya.make2
-rw-r--r--contrib/python/PyYAML/py2/LICENSE36
-rw-r--r--contrib/python/PyYAML/py2/ya.make50
-rw-r--r--contrib/python/PyYAML/py2/yaml/__init__.py594
-rw-r--r--contrib/python/PyYAML/py2/yaml/_yaml.h44
-rw-r--r--contrib/python/PyYAML/py2/yaml/_yaml.pxd460
-rw-r--r--contrib/python/PyYAML/py2/yaml/_yaml.pyx2976
-rw-r--r--contrib/python/PyYAML/py2/yaml/composer.py274
-rw-r--r--contrib/python/PyYAML/py2/yaml/constructor.py1224
-rw-r--r--contrib/python/PyYAML/py2/yaml/cyaml.py146
-rw-r--r--contrib/python/PyYAML/py2/yaml/dumper.py106
-rw-r--r--contrib/python/PyYAML/py2/yaml/emitter.py2266
-rw-r--r--contrib/python/PyYAML/py2/yaml/error.py150
-rw-r--r--contrib/python/PyYAML/py2/yaml/events.py172
-rw-r--r--contrib/python/PyYAML/py2/yaml/loader.py78
-rw-r--r--contrib/python/PyYAML/py2/yaml/nodes.py98
-rw-r--r--contrib/python/PyYAML/py2/yaml/parser.py1178
-rw-r--r--contrib/python/PyYAML/py2/yaml/reader.py362
-rw-r--r--contrib/python/PyYAML/py2/yaml/representer.py958
-rw-r--r--contrib/python/PyYAML/py2/yaml/resolver.py442
-rw-r--r--contrib/python/PyYAML/py2/yaml/scanner.py2850
-rw-r--r--contrib/python/PyYAML/py2/yaml/serializer.py222
-rw-r--r--contrib/python/PyYAML/py2/yaml/tokens.py208
-rw-r--r--contrib/python/PyYAML/py3/LICENSE36
-rw-r--r--contrib/python/PyYAML/py3/ya.make50
-rw-r--r--contrib/python/PyYAML/py3/yaml/_yaml.h44
-rw-r--r--contrib/python/PyYAML/py3/yaml/_yaml.pxd460
-rw-r--r--contrib/python/PyYAML/py3/yaml/_yaml.pyx2976
-rw-r--r--contrib/python/PyYAML/ya.make4
-rw-r--r--contrib/python/cffi/ya.make4
-rw-r--r--contrib/python/decorator/LICENSE.txt50
-rw-r--r--contrib/python/decorator/decorator.py698
-rw-r--r--contrib/python/decorator/ya.make14
-rw-r--r--contrib/python/ipython/py2/COPYING.rst148
-rw-r--r--contrib/python/ipython/py2/IPython/__init__.py292
-rw-r--r--contrib/python/ipython/py2/IPython/__main__.py28
-rw-r--r--contrib/python/ipython/py2/IPython/config.py36
-rw-r--r--contrib/python/ipython/py2/IPython/consoleapp.py24
-rw-r--r--contrib/python/ipython/py2/IPython/core/alias.py508
-rw-r--r--contrib/python/ipython/py2/IPython/core/application.py754
-rw-r--r--contrib/python/ipython/py2/IPython/core/autocall.py140
-rw-r--r--contrib/python/ipython/py2/IPython/core/builtin_trap.py226
-rw-r--r--contrib/python/ipython/py2/IPython/core/compilerop.py286
-rw-r--r--contrib/python/ipython/py2/IPython/core/completer.py2128
-rw-r--r--contrib/python/ipython/py2/IPython/core/completerlib.py686
-rw-r--r--contrib/python/ipython/py2/IPython/core/crashhandler.py432
-rw-r--r--contrib/python/ipython/py2/IPython/core/debugger.py1070
-rw-r--r--contrib/python/ipython/py2/IPython/core/display.py1856
-rw-r--r--contrib/python/ipython/py2/IPython/core/display_trap.py140
-rw-r--r--contrib/python/ipython/py2/IPython/core/displayhook.py560
-rw-r--r--contrib/python/ipython/py2/IPython/core/displaypub.py206
-rw-r--r--contrib/python/ipython/py2/IPython/core/error.py120
-rw-r--r--contrib/python/ipython/py2/IPython/core/events.py260
-rw-r--r--contrib/python/ipython/py2/IPython/core/excolors.py290
-rw-r--r--contrib/python/ipython/py2/IPython/core/extensions.py322
-rw-r--r--contrib/python/ipython/py2/IPython/core/formatters.py1802
-rw-r--r--contrib/python/ipython/py2/IPython/core/getipython.py48
-rw-r--r--contrib/python/ipython/py2/IPython/core/history.py1686
-rw-r--r--contrib/python/ipython/py2/IPython/core/historyapp.py298
-rw-r--r--contrib/python/ipython/py2/IPython/core/hooks.py424
-rw-r--r--contrib/python/ipython/py2/IPython/core/inputsplitter.py1362
-rw-r--r--contrib/python/ipython/py2/IPython/core/inputtransformer.py1088
-rw-r--r--contrib/python/ipython/py2/IPython/core/interactiveshell.py5824
-rw-r--r--contrib/python/ipython/py2/IPython/core/latex_symbols.py2600
-rw-r--r--contrib/python/ipython/py2/IPython/core/logger.py442
-rw-r--r--contrib/python/ipython/py2/IPython/core/macro.py114
-rw-r--r--contrib/python/ipython/py2/IPython/core/magic.py1344
-rw-r--r--contrib/python/ipython/py2/IPython/core/magic_arguments.py556
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/__init__.py82
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/auto.py256
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/basic.py1094
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/code.py1420
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/config.py314
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/display.py98
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/execution.py2616
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/extension.py134
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/history.py636
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/logging.py366
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/namespace.py1408
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/osm.py1572
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/pylab.py332
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/script.py528
-rw-r--r--contrib/python/ipython/py2/IPython/core/oinspect.py1652
-rw-r--r--contrib/python/ipython/py2/IPython/core/page.py738
-rw-r--r--contrib/python/ipython/py2/IPython/core/payload.py110
-rw-r--r--contrib/python/ipython/py2/IPython/core/payloadpage.py104
-rw-r--r--contrib/python/ipython/py2/IPython/core/prefilter.py1356
-rw-r--r--contrib/python/ipython/py2/IPython/core/profile/README_STARTUP22
-rw-r--r--contrib/python/ipython/py2/IPython/core/profileapp.py606
-rw-r--r--contrib/python/ipython/py2/IPython/core/profiledir.py402
-rw-r--r--contrib/python/ipython/py2/IPython/core/prompts.py48
-rw-r--r--contrib/python/ipython/py2/IPython/core/pylabtools.py756
-rw-r--r--contrib/python/ipython/py2/IPython/core/release.py234
-rw-r--r--contrib/python/ipython/py2/IPython/core/shadowns.py2
-rw-r--r--contrib/python/ipython/py2/IPython/core/shellapp.py724
-rw-r--r--contrib/python/ipython/py2/IPython/core/splitinput.py274
-rw-r--r--contrib/python/ipython/py2/IPython/core/ultratb.py2874
-rw-r--r--contrib/python/ipython/py2/IPython/core/usage.py648
-rw-r--r--contrib/python/ipython/py2/IPython/display.py32
-rw-r--r--contrib/python/ipython/py2/IPython/extensions/__init__.py4
-rw-r--r--contrib/python/ipython/py2/IPython/extensions/autoreload.py1068
-rw-r--r--contrib/python/ipython/py2/IPython/extensions/cythonmagic.py42
-rw-r--r--contrib/python/ipython/py2/IPython/extensions/rmagic.py24
-rw-r--r--contrib/python/ipython/py2/IPython/extensions/storemagic.py448
-rw-r--r--contrib/python/ipython/py2/IPython/extensions/sympyprinting.py64
-rw-r--r--contrib/python/ipython/py2/IPython/external/__init__.py10
-rw-r--r--contrib/python/ipython/py2/IPython/external/decorators/__init__.py18
-rw-r--r--contrib/python/ipython/py2/IPython/external/decorators/_decorators.py562
-rw-r--r--contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_noseclasses.py82
-rw-r--r--contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py218
-rw-r--r--contrib/python/ipython/py2/IPython/external/mathjax.py26
-rw-r--r--contrib/python/ipython/py2/IPython/external/qt_for_kernel.py182
-rw-r--r--contrib/python/ipython/py2/IPython/external/qt_loaders.py562
-rw-r--r--contrib/python/ipython/py2/IPython/frontend.py56
-rw-r--r--contrib/python/ipython/py2/IPython/html.py54
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/__init__.py68
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/__main__.py6
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/adapter.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/channels.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/channelsabc.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/client.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/clientabc.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/connect.py4
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/kernelspec.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/kernelspecapp.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/launcher.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/manager.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/managerabc.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/multikernelmanager.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/restarter.py2
-rw-r--r--contrib/python/ipython/py2/IPython/kernel/threaded.py2
-rw-r--r--contrib/python/ipython/py2/IPython/lib/__init__.py42
-rw-r--r--contrib/python/ipython/py2/IPython/lib/backgroundjobs.py980
-rw-r--r--contrib/python/ipython/py2/IPython/lib/clipboard.py144
-rw-r--r--contrib/python/ipython/py2/IPython/lib/deepreload.py712
-rw-r--r--contrib/python/ipython/py2/IPython/lib/demo.py1136
-rw-r--r--contrib/python/ipython/py2/IPython/lib/display.py1106
-rw-r--r--contrib/python/ipython/py2/IPython/lib/editorhooks.py256
-rw-r--r--contrib/python/ipython/py2/IPython/lib/guisupport.py274
-rw-r--r--contrib/python/ipython/py2/IPython/lib/inputhook.py1096
-rw-r--r--contrib/python/ipython/py2/IPython/lib/inputhookglut.py346
-rw-r--r--contrib/python/ipython/py2/IPython/lib/inputhookgtk.py70
-rw-r--r--contrib/python/ipython/py2/IPython/lib/inputhookgtk3.py68
-rw-r--r--contrib/python/ipython/py2/IPython/lib/inputhookpyglet.py222
-rw-r--r--contrib/python/ipython/py2/IPython/lib/inputhookqt4.py360
-rw-r--r--contrib/python/ipython/py2/IPython/lib/inputhookwx.py334
-rw-r--r--contrib/python/ipython/py2/IPython/lib/kernel.py26
-rw-r--r--contrib/python/ipython/py2/IPython/lib/latextools.py380
-rw-r--r--contrib/python/ipython/py2/IPython/lib/lexers.py1000
-rw-r--r--contrib/python/ipython/py2/IPython/lib/pretty.py1626
-rw-r--r--contrib/python/ipython/py2/IPython/lib/security.py228
-rw-r--r--contrib/python/ipython/py2/IPython/nbconvert.py36
-rw-r--r--contrib/python/ipython/py2/IPython/nbformat.py36
-rw-r--r--contrib/python/ipython/py2/IPython/parallel.py38
-rw-r--r--contrib/python/ipython/py2/IPython/paths.py240
-rw-r--r--contrib/python/ipython/py2/IPython/qt.py46
-rw-r--r--contrib/python/ipython/py2/IPython/sphinxext/custom_doctests.py310
-rw-r--r--contrib/python/ipython/py2/IPython/sphinxext/ipython_console_highlighting.py56
-rw-r--r--contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py2322
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/console.py36
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/embed.py536
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/interactiveshell.py236
-rwxr-xr-xcontrib/python/ipython/py2/IPython/terminal/ipapp.py674
-rw-r--r--contrib/python/ipython/py2/IPython/testing/__init__.py76
-rw-r--r--contrib/python/ipython/py2/IPython/testing/__main__.py6
-rw-r--r--contrib/python/ipython/py2/IPython/testing/decorators.py740
-rw-r--r--contrib/python/ipython/py2/IPython/testing/globalipapp.py258
-rw-r--r--contrib/python/ipython/py2/IPython/testing/iptest.py856
-rw-r--r--contrib/python/ipython/py2/IPython/testing/iptestcontroller.py1064
-rw-r--r--contrib/python/ipython/py2/IPython/testing/ipunittest.py352
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/Makefile148
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/README.txt78
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/dtexample.py316
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py1522
-rwxr-xr-xcontrib/python/ipython/py2/IPython/testing/plugin/iptest.py38
-rwxr-xr-xcontrib/python/ipython/py2/IPython/testing/plugin/setup.py36
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/show_refs.py40
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/simple.py68
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/simplevars.py6
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/test_combo.txt72
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/test_example.txt48
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/test_exampleip.txt60
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/test_ipdoctest.py160
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/test_refs.py92
-rw-r--r--contrib/python/ipython/py2/IPython/testing/skipdoctest.py76
-rw-r--r--contrib/python/ipython/py2/IPython/testing/tools.py892
-rw-r--r--contrib/python/ipython/py2/IPython/utils/PyColorize.py680
-rw-r--r--contrib/python/ipython/py2/IPython/utils/_process_cli.py156
-rw-r--r--contrib/python/ipython/py2/IPython/utils/_process_common.py428
-rw-r--r--contrib/python/ipython/py2/IPython/utils/_process_posix.py450
-rw-r--r--contrib/python/ipython/py2/IPython/utils/_process_win32.py384
-rw-r--r--contrib/python/ipython/py2/IPython/utils/_process_win32_controller.py1154
-rw-r--r--contrib/python/ipython/py2/IPython/utils/_signatures.py1626
-rw-r--r--contrib/python/ipython/py2/IPython/utils/_sysinfo.py2
-rw-r--r--contrib/python/ipython/py2/IPython/utils/_tokenize_py2.py878
-rw-r--r--contrib/python/ipython/py2/IPython/utils/_tokenize_py3.py1190
-rw-r--r--contrib/python/ipython/py2/IPython/utils/capture.py312
-rw-r--r--contrib/python/ipython/py2/IPython/utils/coloransi.py374
-rw-r--r--contrib/python/ipython/py2/IPython/utils/contexts.py126
-rw-r--r--contrib/python/ipython/py2/IPython/utils/daemonize.py8
-rw-r--r--contrib/python/ipython/py2/IPython/utils/data.py74
-rw-r--r--contrib/python/ipython/py2/IPython/utils/decorators.py116
-rw-r--r--contrib/python/ipython/py2/IPython/utils/dir2.py90
-rw-r--r--contrib/python/ipython/py2/IPython/utils/encoding.py142
-rw-r--r--contrib/python/ipython/py2/IPython/utils/eventful.py14
-rw-r--r--contrib/python/ipython/py2/IPython/utils/frame.py196
-rw-r--r--contrib/python/ipython/py2/IPython/utils/generics.py68
-rw-r--r--contrib/python/ipython/py2/IPython/utils/importstring.py78
-rw-r--r--contrib/python/ipython/py2/IPython/utils/io.py440
-rw-r--r--contrib/python/ipython/py2/IPython/utils/ipstruct.py782
-rw-r--r--contrib/python/ipython/py2/IPython/utils/jsonutil.py10
-rw-r--r--contrib/python/ipython/py2/IPython/utils/localinterfaces.py10
-rw-r--r--contrib/python/ipython/py2/IPython/utils/log.py14
-rw-r--r--contrib/python/ipython/py2/IPython/utils/module_paths.py250
-rw-r--r--contrib/python/ipython/py2/IPython/utils/openpy.py496
-rw-r--r--contrib/python/ipython/py2/IPython/utils/path.py862
-rw-r--r--contrib/python/ipython/py2/IPython/utils/pickleutil.py10
-rw-r--r--contrib/python/ipython/py2/IPython/utils/process.py212
-rw-r--r--contrib/python/ipython/py2/IPython/utils/py3compat.py668
-rw-r--r--contrib/python/ipython/py2/IPython/utils/rlineimpl.py148
-rw-r--r--contrib/python/ipython/py2/IPython/utils/sentinel.py34
-rw-r--r--contrib/python/ipython/py2/IPython/utils/shimmodule.py184
-rw-r--r--contrib/python/ipython/py2/IPython/utils/signatures.py22
-rw-r--r--contrib/python/ipython/py2/IPython/utils/strdispatch.py136
-rw-r--r--contrib/python/ipython/py2/IPython/utils/sysinfo.py334
-rw-r--r--contrib/python/ipython/py2/IPython/utils/syspathcontext.py142
-rw-r--r--contrib/python/ipython/py2/IPython/utils/tempdir.py290
-rw-r--r--contrib/python/ipython/py2/IPython/utils/terminal.py222
-rw-r--r--contrib/python/ipython/py2/IPython/utils/text.py1552
-rw-r--r--contrib/python/ipython/py2/IPython/utils/timing.py236
-rw-r--r--contrib/python/ipython/py2/IPython/utils/tokenize2.py18
-rw-r--r--contrib/python/ipython/py2/IPython/utils/tokenutil.py254
-rw-r--r--contrib/python/ipython/py2/IPython/utils/traitlets.py14
-rw-r--r--contrib/python/ipython/py2/IPython/utils/tz.py92
-rw-r--r--contrib/python/ipython/py2/IPython/utils/ulinecache.py90
-rw-r--r--contrib/python/ipython/py2/IPython/utils/version.py72
-rw-r--r--contrib/python/ipython/py2/IPython/utils/warn.py92
-rw-r--r--contrib/python/ipython/py2/IPython/utils/wildcard.py224
-rw-r--r--contrib/python/ipython/py2/bin/ya.make10
-rw-r--r--contrib/python/ipython/ya.make4
-rw-r--r--contrib/python/jedi/LICENSE.txt42
-rw-r--r--contrib/python/jedi/jedi/__init__.py78
-rw-r--r--contrib/python/jedi/jedi/__main__.py72
-rw-r--r--contrib/python/jedi/jedi/_compatibility.py316
-rw-r--r--contrib/python/jedi/jedi/api/__init__.py456
-rw-r--r--contrib/python/jedi/jedi/api/classes.py816
-rw-r--r--contrib/python/jedi/jedi/api/helpers.py46
-rw-r--r--contrib/python/jedi/jedi/api/interpreter.py34
-rw-r--r--contrib/python/jedi/jedi/api/keywords.py106
-rw-r--r--contrib/python/jedi/jedi/api/replstartup.py48
-rw-r--r--contrib/python/jedi/jedi/cache.py182
-rw-r--r--contrib/python/jedi/jedi/debug.py134
-rw-r--r--contrib/python/jedi/jedi/evaluate/__init__.py216
-rw-r--r--contrib/python/jedi/jedi/evaluate/analysis.py276
-rw-r--r--contrib/python/jedi/jedi/evaluate/cache.py92
-rw-r--r--contrib/python/jedi/jedi/evaluate/compiled/__init__.py26
-rw-r--r--contrib/python/jedi/jedi/evaluate/compiled/fake.py56
-rw-r--r--contrib/python/jedi/jedi/evaluate/compiled/fake/_functools.pym18
-rw-r--r--contrib/python/jedi/jedi/evaluate/compiled/fake/_sqlite3.pym52
-rw-r--r--contrib/python/jedi/jedi/evaluate/compiled/fake/_sre.pym198
-rw-r--r--contrib/python/jedi/jedi/evaluate/compiled/fake/_weakref.pym14
-rw-r--r--contrib/python/jedi/jedi/evaluate/compiled/fake/builtins.pym486
-rw-r--r--contrib/python/jedi/jedi/evaluate/compiled/fake/datetime.pym8
-rw-r--r--contrib/python/jedi/jedi/evaluate/compiled/fake/io.pym12
-rw-r--r--contrib/python/jedi/jedi/evaluate/compiled/fake/posix.pym10
-rw-r--r--contrib/python/jedi/jedi/evaluate/docstrings.py264
-rw-r--r--contrib/python/jedi/jedi/evaluate/dynamic.py116
-rw-r--r--contrib/python/jedi/jedi/evaluate/finder.py176
-rw-r--r--contrib/python/jedi/jedi/evaluate/flow_analysis.py98
-rw-r--r--contrib/python/jedi/jedi/evaluate/helpers.py100
-rw-r--r--contrib/python/jedi/jedi/evaluate/imports.py490
-rw-r--r--contrib/python/jedi/jedi/evaluate/param.py122
-rw-r--r--contrib/python/jedi/jedi/evaluate/recursion.py80
-rw-r--r--contrib/python/jedi/jedi/evaluate/stdlib.py270
-rw-r--r--contrib/python/jedi/jedi/evaluate/sys_path.py202
-rw-r--r--contrib/python/jedi/jedi/refactoring.py318
-rw-r--r--contrib/python/jedi/jedi/settings.py322
-rw-r--r--contrib/python/jedi/jedi/utils.py214
-rw-r--r--contrib/python/jedi/ya.make76
-rw-r--r--contrib/python/pexpect/LICENSE30
-rw-r--r--contrib/python/pexpect/pexpect/ANSI.py702
-rw-r--r--contrib/python/pexpect/pexpect/FSM.py668
-rw-r--r--contrib/python/pexpect/pexpect/__init__.py168
-rw-r--r--contrib/python/pexpect/pexpect/_async.py114
-rw-r--r--contrib/python/pexpect/pexpect/exceptions.py70
-rw-r--r--contrib/python/pexpect/pexpect/expect.py510
-rw-r--r--contrib/python/pexpect/pexpect/fdpexpect.py222
-rw-r--r--contrib/python/pexpect/pexpect/popen_spawn.py338
-rw-r--r--contrib/python/pexpect/pexpect/pty_spawn.py1448
-rw-r--r--contrib/python/pexpect/pexpect/pxssh.py756
-rw-r--r--contrib/python/pexpect/pexpect/replwrap.py218
-rw-r--r--contrib/python/pexpect/pexpect/run.py314
-rw-r--r--contrib/python/pexpect/pexpect/screen.py858
-rw-r--r--contrib/python/pexpect/pexpect/spawnbase.py942
-rw-r--r--contrib/python/pexpect/pexpect/utils.py216
-rw-r--r--contrib/python/pexpect/ya.make46
-rw-r--r--contrib/python/pickleshare/pickleshare.py618
-rw-r--r--contrib/python/pickleshare/ya.make16
-rw-r--r--contrib/python/prompt-toolkit/py2/ya.make6
-rw-r--r--contrib/python/prompt-toolkit/ya.make2
-rw-r--r--contrib/python/ptyprocess/ptyprocess/__init__.py4
-rw-r--r--contrib/python/ptyprocess/ptyprocess/_fork_pty.py150
-rw-r--r--contrib/python/ptyprocess/ptyprocess/ptyprocess.py1594
-rw-r--r--contrib/python/ptyprocess/ptyprocess/util.py132
-rw-r--r--contrib/python/ptyprocess/ya.make20
-rw-r--r--contrib/python/py/ya.make58
-rw-r--r--contrib/python/pyparsing/py2/ya.make14
-rw-r--r--contrib/python/pyparsing/py3/ya.make12
-rw-r--r--contrib/python/pyparsing/ya.make4
-rw-r--r--contrib/python/setuptools/py2/pkg_resources/__init__.py5038
-rw-r--r--contrib/python/setuptools/py2/setuptools/__init__.py228
-rw-r--r--contrib/python/setuptools/py2/setuptools/archive_util.py324
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/__init__.py32
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/alias.py158
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/bdist_egg.py910
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/bdist_rpm.py86
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/bdist_wininst.py42
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/build_ext.py538
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/build_py.py400
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/develop.py356
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/easy_install.py4194
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/egg_info.py782
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/install.py246
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/install_egg_info.py118
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/install_lib.py236
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/install_scripts.py120
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/register.py12
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/rotate.py120
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/saveopts.py44
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/sdist.py262
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/setopt.py296
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/test.py348
-rw-r--r--contrib/python/setuptools/py2/setuptools/command/upload_docs.py274
-rw-r--r--contrib/python/setuptools/py2/setuptools/depends.py278
-rw-r--r--contrib/python/setuptools/py2/setuptools/dist.py1318
-rw-r--r--contrib/python/setuptools/py2/setuptools/extension.py92
-rw-r--r--contrib/python/setuptools/py2/setuptools/launch.py34
-rw-r--r--contrib/python/setuptools/py2/setuptools/lib2to3_ex.py116
-rw-r--r--contrib/python/setuptools/py2/setuptools/package_index.py1864
-rw-r--r--contrib/python/setuptools/py2/setuptools/py27compat.py14
-rw-r--r--contrib/python/setuptools/py2/setuptools/py31compat.py44
-rw-r--r--contrib/python/setuptools/py2/setuptools/sandbox.py796
-rw-r--r--contrib/python/setuptools/py2/setuptools/script.tmpl6
-rw-r--r--contrib/python/setuptools/py2/setuptools/site-patch.py120
-rw-r--r--contrib/python/setuptools/py2/setuptools/ssl_support.py438
-rw-r--r--contrib/python/setuptools/py2/setuptools/unicode_utils.py86
-rw-r--r--contrib/python/setuptools/py2/setuptools/windows_support.py58
-rw-r--r--contrib/python/setuptools/py2/ya.make90
-rw-r--r--contrib/python/setuptools/py3/pkg_resources/__init__.py4894
-rw-r--r--contrib/python/setuptools/py3/setuptools/__init__.py204
-rw-r--r--contrib/python/setuptools/py3/setuptools/archive_util.py258
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/__init__.py16
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/alias.py156
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/bdist_egg.py804
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/bdist_rpm.py62
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/build_ext.py530
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/build_py.py342
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/develop.py296
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/easy_install.py3800
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/egg_info.py766
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/install.py246
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/install_egg_info.py118
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/install_lib.py236
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/install_scripts.py116
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/register.py12
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/rotate.py112
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/saveopts.py44
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/sdist.py206
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/setopt.py294
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/test.py266
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/upload_docs.py258
-rw-r--r--contrib/python/setuptools/py3/setuptools/depends.py272
-rw-r--r--contrib/python/setuptools/py3/setuptools/dist.py802
-rw-r--r--contrib/python/setuptools/py3/setuptools/extension.py90
-rw-r--r--contrib/python/setuptools/py3/setuptools/launch.py34
-rw-r--r--contrib/python/setuptools/py3/setuptools/package_index.py1724
-rw-r--r--contrib/python/setuptools/py3/setuptools/sandbox.py744
-rw-r--r--contrib/python/setuptools/py3/setuptools/script.tmpl6
-rw-r--r--contrib/python/setuptools/py3/setuptools/unicode_utils.py80
-rw-r--r--contrib/python/setuptools/py3/setuptools/windows_support.py58
-rw-r--r--contrib/python/setuptools/py3/ya.make78
-rw-r--r--contrib/python/setuptools/ya.make6
-rw-r--r--contrib/python/traitlets/py2/COPYING.md124
-rw-r--r--contrib/python/traitlets/py2/traitlets/__init__.py6
-rw-r--r--contrib/python/traitlets/py2/traitlets/_version.py2
-rw-r--r--contrib/python/traitlets/py2/traitlets/config/__init__.py16
-rw-r--r--contrib/python/traitlets/py2/traitlets/config/application.py1184
-rw-r--r--contrib/python/traitlets/py2/traitlets/config/configurable.py794
-rw-r--r--contrib/python/traitlets/py2/traitlets/config/loader.py1640
-rw-r--r--contrib/python/traitlets/py2/traitlets/config/manager.py174
-rw-r--r--contrib/python/traitlets/py2/traitlets/log.py42
-rw-r--r--contrib/python/traitlets/py2/traitlets/traitlets.py4370
-rw-r--r--contrib/python/traitlets/py2/traitlets/utils/getargspec.py170
-rw-r--r--contrib/python/traitlets/py2/traitlets/utils/importstring.py80
-rw-r--r--contrib/python/traitlets/py2/traitlets/utils/sentinel.py34
-rw-r--r--contrib/python/traitlets/py2/ya.make46
-rw-r--r--contrib/python/traitlets/py3/COPYING.md124
-rw-r--r--contrib/python/traitlets/py3/traitlets/__init__.py6
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/__init__.py16
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/application.py920
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/configurable.py694
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/loader.py1134
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/manager.py166
-rw-r--r--contrib/python/traitlets/py3/traitlets/log.py42
-rw-r--r--contrib/python/traitlets/py3/traitlets/traitlets.py3822
-rw-r--r--contrib/python/traitlets/py3/traitlets/utils/getargspec.py40
-rw-r--r--contrib/python/traitlets/py3/traitlets/utils/importstring.py70
-rw-r--r--contrib/python/traitlets/py3/traitlets/utils/sentinel.py30
-rw-r--r--contrib/python/traitlets/py3/ya.make42
-rw-r--r--contrib/python/traitlets/ya.make4
-rw-r--r--contrib/python/ya.make108
-rw-r--r--contrib/restricted/boost/arcadia_test/ya.make2
-rw-r--r--contrib/restricted/boost/boost_common.inc26
-rw-r--r--contrib/restricted/boost/libs/asio/ya.make28
-rw-r--r--contrib/restricted/boost/libs/atomic/ya.make2
-rw-r--r--contrib/restricted/boost/libs/chrono/ya.make2
-rw-r--r--contrib/restricted/boost/libs/container/ya.make2
-rw-r--r--contrib/restricted/boost/libs/context/ya.make2
-rw-r--r--contrib/restricted/boost/libs/coroutine/ya.make4
-rw-r--r--contrib/restricted/boost/libs/date_time/ya.make2
-rw-r--r--contrib/restricted/boost/libs/exception/ya.make2
-rw-r--r--contrib/restricted/boost/libs/filesystem/ya.make8
-rw-r--r--contrib/restricted/boost/libs/iostreams/ya.make6
-rw-r--r--contrib/restricted/boost/libs/locale/ya.make4
-rw-r--r--contrib/restricted/boost/libs/log/ya.make4
-rw-r--r--contrib/restricted/boost/libs/program_options/ya.make2
-rw-r--r--contrib/restricted/boost/libs/python/arcadia_test/mod/ya.make2
-rw-r--r--contrib/restricted/boost/libs/python/ya.make2
-rw-r--r--contrib/restricted/boost/libs/random/ya.make2
-rw-r--r--contrib/restricted/boost/libs/regex/ya.make2
-rw-r--r--contrib/restricted/boost/libs/serialization/ya.make2
-rw-r--r--contrib/restricted/boost/libs/system/ya.make2
-rw-r--r--contrib/restricted/boost/libs/test/targets/lib/ya.make2
-rw-r--r--contrib/restricted/boost/libs/test/targets/prog/ya.make2
-rw-r--r--contrib/restricted/boost/libs/test/targets/test/ya.make2
-rw-r--r--contrib/restricted/boost/libs/thread/ya.make8
-rw-r--r--contrib/restricted/boost/libs/timer/ya.make2
-rw-r--r--contrib/restricted/boost/libs/ya.make70
-rw-r--r--contrib/restricted/boost/ya.make12
-rw-r--r--contrib/restricted/googletest/googlemock/gmock_main/ya.make26
-rw-r--r--contrib/restricted/googletest/googlemock/ya.make2
-rw-r--r--contrib/restricted/libffi/ChangeLog21450
-rw-r--r--contrib/restricted/libffi/ChangeLog.old14814
-rw-r--r--contrib/restricted/libffi/LICENSE42
-rw-r--r--contrib/restricted/libffi/LICENSE-BUILDTOOLS706
-rw-r--r--contrib/restricted/libffi/README.md944
-rw-r--r--contrib/restricted/libffi/configs/aarch64-apple-iphoneos/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include/ffitarget.h184
-rw-r--r--contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include/ffitarget.h184
-rw-r--r--contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include/ffitarget.h184
-rw-r--r--contrib/restricted/libffi/configs/armv7-apple-iphoneos/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/armv7-apple-iphoneos/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/armv7-apple-iphoneos/include/ffitarget.h178
-rw-r--r--contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include/ffitarget.h178
-rw-r--r--contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include/ffitarget.h178
-rw-r--r--contrib/restricted/libffi/configs/i386-apple-iphonesimulator/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include/ffitarget.h294
-rwxr-xr-xcontrib/restricted/libffi/configs/i386-microsoft-windows/fficonfig.h448
-rwxr-xr-xcontrib/restricted/libffi/configs/i386-microsoft-windows/include/ffi.h1042
-rwxr-xr-xcontrib/restricted/libffi/configs/i386-microsoft-windows/include/ffitarget.h320
-rw-r--r--contrib/restricted/libffi/configs/i386-microsoft-windows/sysv_intel.masm3922
-rw-r--r--contrib/restricted/libffi/configs/i686-pc-linux-android16/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/i686-pc-linux-android16/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/i686-pc-linux-android16/include/ffitarget.h294
-rw-r--r--contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include/ffitarget.h408
-rw-r--r--contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include/ffitarget.h294
-rw-r--r--contrib/restricted/libffi/configs/x86_64-apple-macosx/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/x86_64-apple-macosx/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/x86_64-apple-macosx/include/ffitarget.h294
-rwxr-xr-xcontrib/restricted/libffi/configs/x86_64-microsoft-windows/fficonfig.h448
-rwxr-xr-xcontrib/restricted/libffi/configs/x86_64-microsoft-windows/include/ffi.h1042
-rwxr-xr-xcontrib/restricted/libffi/configs/x86_64-microsoft-windows/include/ffitarget.h320
-rw-r--r--contrib/restricted/libffi/configs/x86_64-microsoft-windows/win64_intel.masm2408
-rw-r--r--contrib/restricted/libffi/configs/x86_64-pc-linux-android21/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include/ffitarget.h294
-rw-r--r--contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/fficonfig.h430
-rw-r--r--contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include/ffi.h1026
-rw-r--r--contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include/ffitarget.h294
-rw-r--r--contrib/restricted/libffi/include/ffi_cfi.h110
-rw-r--r--contrib/restricted/libffi/include/ffi_common.h70
-rw-r--r--contrib/restricted/libffi/src/aarch64/ffi.c2018
-rw-r--r--contrib/restricted/libffi/src/aarch64/ffitarget.h184
-rw-r--r--contrib/restricted/libffi/src/aarch64/internal.h134
-rw-r--r--contrib/restricted/libffi/src/aarch64/sysv.S880
-rw-r--r--contrib/restricted/libffi/src/aarch64/win64_armasm.S1012
-rw-r--r--contrib/restricted/libffi/src/arm/ffi.c1708
-rw-r--r--contrib/restricted/libffi/src/arm/ffitarget.h178
-rw-r--r--contrib/restricted/libffi/src/arm/internal.h14
-rw-r--r--contrib/restricted/libffi/src/arm/sysv.S770
-rw-r--r--contrib/restricted/libffi/src/arm/sysv_msvc_arm32.S622
-rw-r--r--contrib/restricted/libffi/src/closures.c830
-rw-r--r--contrib/restricted/libffi/src/dlmalloc.c32
-rw-r--r--contrib/restricted/libffi/src/java_raw_api.c46
-rw-r--r--contrib/restricted/libffi/src/powerpc/aix.S1132
-rw-r--r--contrib/restricted/libffi/src/powerpc/aix_closure.S1388
-rw-r--r--contrib/restricted/libffi/src/powerpc/asm.h250
-rw-r--r--contrib/restricted/libffi/src/powerpc/darwin.S756
-rw-r--r--contrib/restricted/libffi/src/powerpc/darwin_closure.S1142
-rw-r--r--contrib/restricted/libffi/src/powerpc/ffi.c350
-rw-r--r--contrib/restricted/libffi/src/powerpc/ffi_darwin.c2870
-rw-r--r--contrib/restricted/libffi/src/powerpc/ffi_linux64.c2306
-rw-r--r--contrib/restricted/libffi/src/powerpc/ffi_powerpc.h210
-rw-r--r--contrib/restricted/libffi/src/powerpc/ffi_sysv.c1846
-rw-r--r--contrib/restricted/libffi/src/powerpc/ffitarget.h408
-rw-r--r--contrib/restricted/libffi/src/powerpc/linux64.S566
-rw-r--r--contrib/restricted/libffi/src/powerpc/linux64_closure.S1104
-rw-r--r--contrib/restricted/libffi/src/powerpc/ppc_closure.S794
-rw-r--r--contrib/restricted/libffi/src/powerpc/sysv.S350
-rw-r--r--contrib/restricted/libffi/src/prep_cif.c110
-rw-r--r--contrib/restricted/libffi/src/raw_api.c36
-rw-r--r--contrib/restricted/libffi/src/types.c92
-rw-r--r--contrib/restricted/libffi/src/x86/asmnames.h60
-rw-r--r--contrib/restricted/libffi/src/x86/ffi.c1258
-rw-r--r--contrib/restricted/libffi/src/x86/ffi64.c684
-rw-r--r--contrib/restricted/libffi/src/x86/ffitarget.h98
-rw-r--r--contrib/restricted/libffi/src/x86/ffiw64.c622
-rw-r--r--contrib/restricted/libffi/src/x86/internal.h58
-rw-r--r--contrib/restricted/libffi/src/x86/internal64.h44
-rw-r--r--contrib/restricted/libffi/src/x86/sysv.S2146
-rw-r--r--contrib/restricted/libffi/src/x86/sysv_intel.S1990
-rw-r--r--contrib/restricted/libffi/src/x86/unix64.S884
-rw-r--r--contrib/restricted/libffi/src/x86/win64.S460
-rw-r--r--contrib/restricted/libffi/src/x86/win64_intel.S474
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.bhaible/alignof.h100
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.bhaible/test-call.c3490
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.bhaible/test-call/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.bhaible/test-callback.c5770
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.bhaible/test-callback/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.bhaible/testcases.c1486
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.bhaible/ya.make12
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/align_mixed.c92
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/align_mixed/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/align_stdcall.c92
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/align_stdcall/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/err_bad_typedef.c52
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/err_bad_typedef/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/ffitest.h288
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float.c118
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float1.c120
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float2.c122
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float3.c148
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float3/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float4.c122
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float4/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float_va.c214
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/float_va/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/many.c118
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/many/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/many2.c114
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/many2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/many_double.c140
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/many_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/many_mixed.c156
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/many_mixed/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/negint.c104
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/negint/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/offsets.c92
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/offsets/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/pr1172638.c252
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/pr1172638/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/promotion.c118
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/promotion/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/pyobjc-tc.c228
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/pyobjc-tc/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_dbl.c72
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_dbl/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_dbl1.c86
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_dbl1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_dbl2.c84
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_dbl2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_fl.c70
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_fl/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_fl1.c72
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_fl1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_fl2.c98
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_fl2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_fl3.c84
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_fl3/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_ldl.c68
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_ldl/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_ll.c82
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_ll/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_ll1.c86
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_ll1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_sc.c72
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_sc/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_sl.c76
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_sl/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_uc.c76
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_uc/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_ul.c76
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/return_ul/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/strlen.c88
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/strlen/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/strlen2.c98
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/strlen2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/strlen3.c98
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/strlen3/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/strlen4.c110
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/strlen4/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct1.c132
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct10.c114
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct10/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct2.c134
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct3.c118
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct3/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct4.c124
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct4/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct5.c132
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct5/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct6.c128
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct6/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct7.c148
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct7/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct8.c162
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct8/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct9.c136
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/struct9/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/uninitialized.c122
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/uninitialized/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/va_1.c392
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/va_1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/va_struct1.c242
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/va_struct1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/va_struct2.c246
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/va_struct2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/va_struct3.c250
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/va_struct3/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.call/ya.make110
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn0.c178
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn0/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn1.c162
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn2.c162
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn3.c164
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn3/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn4.c178
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn4/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn5.c184
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn5/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn6.c180
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_fn6/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_loc_fn0.c190
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_loc_fn0/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_simple.c110
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/closure_simple/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_12byte.c188
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_12byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_16byte.c190
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_16byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_18byte.c192
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_18byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_19byte.c204
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_19byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_1_1byte.c178
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_1_1byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte.c182
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte1.c186
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_24byte.c226
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_24byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_2byte.c180
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_2byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_3_1byte.c190
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_3_1byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte1.c180
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte2.c180
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_3float.c190
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_3float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_4_1byte.c196
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_4_1byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_4byte.c180
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_4byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_5_1_byte.c218
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_5_1_byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_5byte.c196
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_5byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_64byte.c248
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_64byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_6_1_byte.c226
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_6_1_byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_6byte.c198
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_6byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_7_1_byte.c234
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_7_1_byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_7byte.c194
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_7byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_8byte.c176
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_8byte/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte1.c180
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte2.c182
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_double.c186
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_float.c182
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble.c184
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c264
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c230
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_pointer.c190
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_pointer/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint16.c182
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint16/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint32.c182
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint32/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint64.c184
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint64/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint16.c182
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint16/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint32.c182
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint32/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint64.c186
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint64/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_dbls_struct.c132
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_dbls_struct/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_double.c86
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_double_va.c122
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_double_va/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_float.c84
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble.c210
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble_va.c122
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble_va/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_args.c140
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_args/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_float_double.c110
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_float_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_schar.c148
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_schar/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshort.c148
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshort/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshortchar.c172
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshortchar/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_uchar.c182
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_uchar/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushort.c148
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushort/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushortchar.c172
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushortchar/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer.c148
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer_stack.c282
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer_stack/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_schar.c88
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_schar/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_sint.c84
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_sint/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_sshort.c84
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_sshort/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_struct_va1.c228
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_struct_va1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar.c84
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar_va.c88
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar_va/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_uint.c86
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_uint/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_uint_va.c90
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_uint_va/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_ulong_va.c90
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_ulong_va/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_ulonglong.c94
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_ulonglong/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort.c86
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort_va.c88
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort_va/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/err_bad_abi.c72
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/err_bad_abi/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/ffitest.h288
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/huge_struct.c682
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/huge_struct/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct.c304
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct1.c322
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct10.c268
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct10/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct11.c242
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct11/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct2.c220
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct3.c222
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct3/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct4.c222
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct4/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct5.c224
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct5/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct6.c262
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct6/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct7.c222
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct7/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct8.c262
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct8/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct9.c262
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/nested_struct9/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/problem1.c180
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/problem1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/stret_large.c290
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/stret_large/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/stret_large2.c296
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/stret_large2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/stret_medium.c248
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/stret_medium/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/stret_medium2.c250
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/stret_medium2/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/testclosure.c140
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/testclosure/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.closures/ya.make206
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex.inc182
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_double.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_float.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_longdouble.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_longdouble/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex.inc84
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_double.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_float.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_longdouble.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_longdouble/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct.inc142
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_double.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_float.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va.inc160
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_double.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_float.c32
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_longdouble.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_longdouble/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex.inc102
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_double.inc14
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_float.inc14
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_longdouble.inc14
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex_double.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex_float.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex_float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex_int.c172
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex_int/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex_longdouble.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/complex_longdouble/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/ffitest.h2
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/many_complex.inc156
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/many_complex_double.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/many_complex_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/many_complex_float.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/many_complex_float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/many_complex_longdouble.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/many_complex_longdouble/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex.inc74
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex1.inc82
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_double.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_float.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_longdouble.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_longdouble/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex2.inc88
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_double.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_float.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_longdouble.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_longdouble/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex_double.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex_double/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex_float.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex_float/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex_longdouble.c20
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/return_complex_longdouble/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.complex/ya.make64
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.go/aa-direct.c68
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.go/aa-direct/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.go/closure1.c56
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.go/closure1/ya.make40
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.go/ffitest.h2
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.go/static-chain.h38
-rw-r--r--contrib/restricted/libffi/testsuite/libffi.go/ya.make12
-rw-r--r--contrib/restricted/libffi/testsuite/ya.make36
-rw-r--r--contrib/restricted/libffi/ya.make336
-rw-r--r--contrib/restricted/ya.make44
-rw-r--r--contrib/tools/cython/Cython/Compiler/Main.py4
-rw-r--r--contrib/tools/cython/Cython/Compiler/PyrexTypes.py16
-rw-r--r--contrib/tools/cython/Cython/Includes/numpy.pxd4
-rw-r--r--contrib/tools/cython/Cython/Utility/CppConvert.pyx158
-rw-r--r--contrib/tools/protoc/plugins/cpp_styleguide/cpp_styleguide.cpp48
-rw-r--r--contrib/tools/python3/src/Modules/ya.make4
-rw-r--r--contrib/tools/ya.make2
-rw-r--r--library/cpp/containers/stack_vector/stack_vec.h8
-rw-r--r--library/cpp/dbg_output/dumpers.h24
-rw-r--r--library/cpp/dbg_output/ut/dbg_output_ut.cpp18
-rw-r--r--library/cpp/getopt/small/completion_generator.cpp2
-rw-r--r--library/cpp/json/writer/json_value.cpp2
-rw-r--r--library/cpp/json/writer/json_value_ut.cpp52
-rw-r--r--library/cpp/resource/registry.cpp4
-rw-r--r--library/cpp/testing/common/env.cpp36
-rw-r--r--library/cpp/testing/unittest/registar.h54
-rw-r--r--library/cpp/testing/unittest/ut/main.cpp44
-rw-r--r--library/cpp/ya.make2
-rw-r--r--library/cpp/yson/node/node.cpp8
-rw-r--r--library/cpp/yson/node/node.h104
-rw-r--r--library/cpp/yson/node/node_ut.cpp52
-rw-r--r--library/cpp/yson_pull/bridge.h40
-rw-r--r--library/cpp/yson_pull/buffer.h36
-rw-r--r--library/cpp/yson_pull/consumer.cpp160
-rw-r--r--library/cpp/yson_pull/consumer.h62
-rw-r--r--library/cpp/yson_pull/cyson_enums.h94
-rw-r--r--library/cpp/yson_pull/detail/byte_reader.h38
-rw-r--r--library/cpp/yson_pull/detail/byte_writer.h40
-rw-r--r--library/cpp/yson_pull/detail/cescape.h92
-rw-r--r--library/cpp/yson_pull/detail/cescape_decode.h34
-rw-r--r--library/cpp/yson_pull/detail/cescape_encode.h38
-rw-r--r--library/cpp/yson_pull/detail/fail.h12
-rw-r--r--library/cpp/yson_pull/detail/format_string.h16
-rw-r--r--library/cpp/yson_pull/detail/input/buffered.h20
-rw-r--r--library/cpp/yson_pull/detail/input/stdio_file.h30
-rw-r--r--library/cpp/yson_pull/detail/input/stream.h116
-rw-r--r--library/cpp/yson_pull/detail/lexer_base.h132
-rw-r--r--library/cpp/yson_pull/detail/macros.h28
-rw-r--r--library/cpp/yson_pull/detail/number.h16
-rw-r--r--library/cpp/yson_pull/detail/output/buffered.h24
-rw-r--r--library/cpp/yson_pull/detail/output/stdio_file.h24
-rw-r--r--library/cpp/yson_pull/detail/output/stream.h92
-rw-r--r--library/cpp/yson_pull/detail/reader.h312
-rw-r--r--library/cpp/yson_pull/detail/stream_counter.h26
-rw-r--r--library/cpp/yson_pull/detail/symbols.h26
-rw-r--r--library/cpp/yson_pull/detail/traits.h14
-rw-r--r--library/cpp/yson_pull/detail/varint.h86
-rw-r--r--library/cpp/yson_pull/detail/writer.h386
-rw-r--r--library/cpp/yson_pull/detail/zigzag.h30
-rw-r--r--library/cpp/yson_pull/event.cpp30
-rw-r--r--library/cpp/yson_pull/event.h90
-rw-r--r--library/cpp/yson_pull/exceptions.cpp86
-rw-r--r--library/cpp/yson_pull/exceptions.h50
-rw-r--r--library/cpp/yson_pull/input.cpp58
-rw-r--r--library/cpp/yson_pull/input.h54
-rw-r--r--library/cpp/yson_pull/output.cpp50
-rw-r--r--library/cpp/yson_pull/output.h58
-rw-r--r--library/cpp/yson_pull/position_info.h26
-rw-r--r--library/cpp/yson_pull/range.h32
-rw-r--r--library/cpp/yson_pull/read_ops.cpp82
-rw-r--r--library/cpp/yson_pull/read_ops.h170
-rw-r--r--library/cpp/yson_pull/reader.cpp40
-rw-r--r--library/cpp/yson_pull/reader.h42
-rw-r--r--library/cpp/yson_pull/scalar.cpp100
-rw-r--r--library/cpp/yson_pull/scalar.h192
-rw-r--r--library/cpp/yson_pull/stream_type.h10
-rw-r--r--library/cpp/yson_pull/ut/cescape_ut.cpp34
-rw-r--r--library/cpp/yson_pull/ut/loop_ut.cpp382
-rw-r--r--library/cpp/yson_pull/ut/reader_ut.cpp332
-rw-r--r--library/cpp/yson_pull/ut/writer_ut.cpp90
-rw-r--r--library/cpp/yson_pull/ut/ya.make22
-rw-r--r--library/cpp/yson_pull/writer.cpp46
-rw-r--r--library/cpp/yson_pull/writer.h132
-rw-r--r--library/cpp/yson_pull/ya.make40
-rw-r--r--library/cpp/yson_pull/yson.h28
-rw-r--r--library/cpp/yt/memory/ref.cpp12
-rw-r--r--library/cpp/yt/yson_string/string.cpp24
-rw-r--r--library/cpp/yt/yson_string/string.h4
-rw-r--r--library/python/cores/__init__.py8
-rw-r--r--library/python/cores/ya.make2
-rw-r--r--library/python/resource/__init__.py8
-rw-r--r--library/python/resource/ut/lib/test_simple.py4
-rw-r--r--library/python/resource/ut/lib/ya.make4
-rw-r--r--library/python/runtime_py3/importer.pxi42
-rw-r--r--library/python/runtime_py3/main/main.c6
-rw-r--r--library/python/runtime_py3/main/ya.make12
-rw-r--r--library/python/runtime_py3/test/canondata/result.json4
-rw-r--r--library/python/runtime_py3/test/canondata/test_traceback.test_traceback_custom-default_/stderr.txt10
-rw-r--r--library/python/runtime_py3/test/canondata/test_traceback.test_traceback_main-default_/stderr.txt10
-rw-r--r--library/python/runtime_py3/test/test_traceback.py2
-rw-r--r--library/python/runtime_py3/test/ya.make4
-rw-r--r--library/python/testing/yatest_common/yatest/common/process.py24
-rw-r--r--library/python/ya.make26
-rw-r--r--tools/archiver/main.cpp10
-rw-r--r--tools/fix_elf/patch.cpp64
-rw-r--r--tools/fix_elf/patch.h2
-rw-r--r--tools/rescompressor/main.cpp10
-rw-r--r--tools/ya.make10
-rw-r--r--util/README.md26
-rw-r--r--util/a.yaml76
-rw-r--r--util/digest/multi_ut.pyx4
-rw-r--r--util/digest/murmur.cpp228
-rw-r--r--util/digest/murmur.h42
-rw-r--r--util/folder/path_ut.cpp136
-rw-r--r--util/generic/algorithm.h40
-rw-r--r--util/generic/algorithm_ut.cpp166
-rw-r--r--util/generic/benchmark/fastclp2/metrics/main.py2
-rw-r--r--util/generic/benchmark/log2/metrics/main.py2
-rw-r--r--util/generic/benchmark/rotate_bits/metrics/main.py2
-rw-r--r--util/generic/benchmark/string/benchmarks.h4
-rw-r--r--util/generic/benchmark/vector_count_ctor/metrics/main.py2
-rw-r--r--util/generic/flags.h6
-rw-r--r--util/generic/flags_ut.cpp20
-rw-r--r--util/generic/hash_ut.pyx20
-rw-r--r--util/generic/iterator.h18
-rw-r--r--util/generic/list_ut.pyx254
-rw-r--r--util/generic/maybe.pxd70
-rw-r--r--util/generic/maybe_ut.pyx370
-rw-r--r--util/generic/overloaded.h84
-rw-r--r--util/generic/overloaded_ut.cpp50
-rw-r--r--util/generic/ptr.h46
-rw-r--r--util/generic/strbuf_ut.cpp16
-rw-r--r--util/generic/string.h6
-rw-r--r--util/generic/string.pxd102
-rw-r--r--util/generic/string_ut.cpp14
-rw-r--r--util/generic/string_ut.pyx338
-rw-r--r--util/generic/ut/ya.make2
-rw-r--r--util/generic/vector.pxd42
-rw-r--r--util/generic/vector_ut.pyx378
-rw-r--r--util/memory/benchmark/pool/metrics/main.py2
-rw-r--r--util/memory/tempbuf.cpp24
-rw-r--r--util/random/benchmark/prng/metrics/main.py2
-rw-r--r--util/stream/format.cpp50
-rw-r--r--util/stream/format_ut.cpp84
-rw-r--r--util/stream/output.cpp2
-rw-r--r--util/string/benchmark/ascii/main.cpp70
-rw-r--r--util/string/benchmark/float_to_string/metrics/main.py2
-rw-r--r--util/string/benchmark/join/metrics/main.py2
-rw-r--r--util/string/benchmark/subst_global/metrics/main.py2
-rw-r--r--util/string/cast.h10
-rw-r--r--util/string/cast.py4
-rw-r--r--util/string/cast_ut.cpp28
-rw-r--r--util/system/benchmark/cpu_id/metrics/main.py2
-rw-r--r--util/system/benchmark/create_destroy_thread/metrics/main.py6
-rw-r--r--util/system/sanitizers.h28
-rw-r--r--util/system/sanitizers_ut.cpp22
-rw-r--r--util/system/types.pxd26
-rw-r--r--util/system/types_ut.pyx80
-rw-r--r--util/system/ut/ya.make2
-rw-r--r--util/tests/cython/test_generic.py34
-rw-r--r--util/tests/cython/test_system.py24
-rw-r--r--util/tests/cython/ya.make32
-rw-r--r--util/tests/ya.make2
-rw-r--r--util/ya.make2
-rw-r--r--util/ysaveload.h4
-rw-r--r--ydb/public/sdk/cpp/client/ydb_persqueue_core/ut/ut_utils/test_utils.h2
1212 files changed, 184058 insertions, 184058 deletions
diff --git a/build/conf/project_specific/maps/mapkit.conf b/build/conf/project_specific/maps/mapkit.conf
index 148fdb08d2..d64b41f72a 100644
--- a/build/conf/project_specific/maps/mapkit.conf
+++ b/build/conf/project_specific/maps/mapkit.conf
@@ -244,7 +244,7 @@ when ($MAPSMOBI_BUILD_TARGET && $OS_ANDROID) {
CFLAGS+=-fstrict-aliasing -mstackrealign -DTLS_STACK_PROTECTOR
}
elsewhen ($ARCH_X86_64) {
- CFLAGS+=-fstrict-aliasing -mstackrealign -march=x86-64 -msse4.2 -mpopcnt -m64 -DTLS_STACK_PROTECTOR
+ CFLAGS+=-fstrict-aliasing -mstackrealign -march=x86-64 -msse4.2 -mpopcnt -m64 -DTLS_STACK_PROTECTOR
}
otherwise {
PEERDIR+=__unsupported_architecture_for_android__
diff --git a/build/config/tests/clang_tidy/config.yaml b/build/config/tests/clang_tidy/config.yaml
index 6e93834241..d55707592c 100644
--- a/build/config/tests/clang_tidy/config.yaml
+++ b/build/config/tests/clang_tidy/config.yaml
@@ -1,8 +1,8 @@
-Checks: >
- -*,
+Checks: >
+ -*,
arcadia-typeid-name-restriction,
- bugprone-use-after-move,
- readability-identifier-naming,
+ bugprone-use-after-move,
+ readability-identifier-naming,
CheckOptions:
- key: readability-identifier-naming.ClassCase
value: CamelCase
diff --git a/build/platform.md b/build/platform.md
index dcb223f30b..deb8acfb09 100644
--- a/build/platform.md
+++ b/build/platform.md
@@ -2,7 +2,7 @@
### `default`
* `android`
* `i686`, `x86_64`, `armv7a`, `armv7a_neon`, `armv8a`
- Clang 9.0.8, Android NDK r21b. API 16 for the 32-bit platforms, API 21 for 64-bit.
+ Clang 9.0.8, Android NDK r21b. API 16 for the 32-bit platforms, API 21 for 64-bit.
* `darwin`
* `x86_64`
Clang 12.0.0, macOS SDK 10.13
diff --git a/build/platform/linux_sdk/ya.make b/build/platform/linux_sdk/ya.make
index 64d7d7d8a8..add74eee9e 100644
--- a/build/platform/linux_sdk/ya.make
+++ b/build/platform/linux_sdk/ya.make
@@ -28,7 +28,7 @@ ELSEIF (ARCH_AARCH64)
IF (OS_SDK == "ubuntu-16")
DECLARE_EXTERNAL_RESOURCE(OS_SDK_ROOT sbr:309054781)
ELSE()
- MESSAGE(FATAL_ERROR "There is no ${OS_SDK} SDK for AArch64/ARMv8 64 bit")
+ MESSAGE(FATAL_ERROR "There is no ${OS_SDK} SDK for AArch64/ARMv8 64 bit")
ENDIF()
ELSEIF (ARCH_PPC64LE)
IF (OS_SDK == "ubuntu-14")
@@ -41,12 +41,12 @@ ELSEIF (ARCH_PPC64LE)
MESSAGE(FATAL_ERROR "There is no ${OS_SDK} SDK for PPC64LE")
ENDIF()
ELSEIF (ARCH_ARM7)
- IF (ARM7_FLOAT_ABI == "hard" AND OS_SDK == "ubuntu-16")
+ IF (ARM7_FLOAT_ABI == "hard" AND OS_SDK == "ubuntu-16")
DECLARE_EXTERNAL_RESOURCE(OS_SDK_ROOT sbr:1323200692)
- ELSEIF (ARM7_FLOAT_ABI == "softfp" AND OS_SDK == "ubuntu-18")
- DECLARE_EXTERNAL_RESOURCE(OS_SDK_ROOT sbr:2402287545)
+ ELSEIF (ARM7_FLOAT_ABI == "softfp" AND OS_SDK == "ubuntu-18")
+ DECLARE_EXTERNAL_RESOURCE(OS_SDK_ROOT sbr:2402287545)
ELSE()
- MESSAGE(FATAL_ERROR "There is no ${OS_SDK} SDK for ARMv7 32 bit (float ABI: ${ARM7_FLOAT_ABI})")
+ MESSAGE(FATAL_ERROR "There is no ${OS_SDK} SDK for ARMv7 32 bit (float ABI: ${ARM7_FLOAT_ABI})")
ENDIF()
ELSE()
MESSAGE(FATAL_ERROR "Unexpected OS_SDK value: ${OS_SDK}")
diff --git a/build/platform/lld/ya.make b/build/platform/lld/ya.make
index 966f800c20..c046e89098 100644
--- a/build/platform/lld/ya.make
+++ b/build/platform/lld/ya.make
@@ -14,9 +14,9 @@ IF (USE_LTO OR USE_THINLTO)
ENDIF()
ENDIF()
-IF (OS_ANDROID)
+IF (OS_ANDROID)
# Use LLD shipped with Android NDK.
- LDFLAGS("-fuse-ld=lld")
+ LDFLAGS("-fuse-ld=lld")
ELSEIF (USE_LLD8)
IF (HOST_OS_LINUX)
IF (HOST_ARCH_PPC64LE)
@@ -41,21 +41,21 @@ ELSEIF (USE_LLD11)
ENDIF()
LDFLAGS("-fuse-ld=$LLD_ROOT_RESOURCE_GLOBAL/ld" "-Wl,--no-rosegment")
-ELSE()
- IF (HOST_OS_LINUX)
- IF (HOST_ARCH_PPC64LE)
+ELSE()
+ IF (HOST_OS_LINUX)
+ IF (HOST_ARCH_PPC64LE)
DECLARE_EXTERNAL_RESOURCE(LLD_ROOT sbr:2283417120)
- ELSE()
+ ELSE()
DECLARE_EXTERNAL_RESOURCE(LLD_ROOT sbr:2283360772)
- ENDIF()
- ELSEIF (HOST_OS_DARWIN)
+ ENDIF()
+ ELSEIF (HOST_OS_DARWIN)
IF (HOST_ARCH_ARM64)
DECLARE_EXTERNAL_RESOURCE(LLD_ROOT sbr:2283439721)
ELSE()
DECLARE_EXTERNAL_RESOURCE(LLD_ROOT sbr:2283429958)
ENDIF()
ENDIF()
-
+
LDFLAGS("-fuse-ld=$LLD_ROOT_RESOURCE_GLOBAL/ld" "-Wl,--no-rosegment")
ENDIF()
diff --git a/build/plugins/cpp_style.py b/build/plugins/cpp_style.py
index 22fa977717..3ab78b7320 100644
--- a/build/plugins/cpp_style.py
+++ b/build/plugins/cpp_style.py
@@ -14,6 +14,6 @@ def on_style(unit, *args):
continue
yield f
- yield '/cpp_style/files/' + f
+ yield '/cpp_style/files/' + f
unit.onresource(list(it()))
diff --git a/build/plugins/pybuild.py b/build/plugins/pybuild.py
index d9e09cb9dd..f32a2d39a0 100644
--- a/build/plugins/pybuild.py
+++ b/build/plugins/pybuild.py
@@ -34,7 +34,7 @@ def uniq_suffix(path, unit):
if '/' not in path:
return ''
return '.{}'.format(pathid(path)[:4])
-
+
def pb2_arg(suf, path, mod, unit):
return '{path}__int__{suf}={mod}{modsuf}'.format(
path=stripext(to_build_root(path, unit)),
@@ -42,7 +42,7 @@ def pb2_arg(suf, path, mod, unit):
mod=mod,
modsuf=stripext(suf)
)
-
+
def proto_arg(path, mod, unit):
return '{}.proto={}'.format(stripext(to_build_root(path, unit)), mod)
@@ -208,7 +208,7 @@ def onpy_srcs(unit, *args):
unit_needs_main = unit.get('MODULE_TYPE') in ('PROGRAM', 'DLL')
if unit_needs_main:
py_program(unit, py3)
-
+
py_namespace_value = unit.get('PY_NAMESPACE_VALUE')
if py_namespace_value == ".":
ns = ""
diff --git a/build/plugins/rodata.py b/build/plugins/rodata.py
index cff6481d23..3ecb0f9a83 100644
--- a/build/plugins/rodata.py
+++ b/build/plugins/rodata.py
@@ -81,7 +81,7 @@ class ROData(iw.CustomCommand):
in_file = self.resolve_path(common.get(self.input, 0))
in_file_no_ext = common.stripext(in_file)
file_name = os.path.basename(in_file_no_ext)
- file_size = os.path.getsize(in_file)
+ file_size = os.path.getsize(in_file)
tmp_file = self.resolve_path(common.get(self.output, 0) + '.asm')
parser = argparse.ArgumentParser(prog='rodata.py', add_help=False)
@@ -95,12 +95,12 @@ class ROData(iw.CustomCommand):
f.write('SECTION .rodata ALIGN=16\n')
f.write(self._prefix + file_name + ':\nincbin "' + in_file + '"\n')
f.write('align 4, db 0\n')
- f.write(self._prefix + file_name + 'Size:\ndd ' + str(file_size) + '\n')
+ f.write(self._prefix + file_name + 'Size:\ndd ' + str(file_size) + '\n')
+
+ if self._fmt.startswith('elf'):
+ f.write('size ' + self._prefix + file_name + ' ' + str(file_size) + '\n')
+ f.write('size ' + self._prefix + file_name + 'Size 4\n')
- if self._fmt.startswith('elf'):
- f.write('size ' + self._prefix + file_name + ' ' + str(file_size) + '\n')
- f.write('size ' + self._prefix + file_name + 'Size 4\n')
-
return self.do_run(binary, tmp_file)
def do_run(self, binary, path):
diff --git a/build/plugins/yql_python_udf.py b/build/plugins/yql_python_udf.py
index 1454129724..c4f949d8a9 100644
--- a/build/plugins/yql_python_udf.py
+++ b/build/plugins/yql_python_udf.py
@@ -1,42 +1,42 @@
-from _common import sort_by_keywords
-
-
-def get_or_default(kv, name, default):
- if name in kv:
- return kv[name][0]
- return default
-
-
-def onregister_yql_python_udf(unit, *args):
+from _common import sort_by_keywords
+
+
+def get_or_default(kv, name, default):
+ if name in kv:
+ return kv[name][0]
+ return default
+
+
+def onregister_yql_python_udf(unit, *args):
flat, kv = sort_by_keywords({'NAME': 1, 'RESOURCE_NAME': 1, 'ADD_LIBRA_MODULES': 1}, args)
- assert len(flat) == 0
- name = get_or_default(kv, 'NAME', 'CustomPython')
- resource_name = get_or_default(kv, 'RESOURCE_NAME', name)
+ assert len(flat) == 0
+ name = get_or_default(kv, 'NAME', 'CustomPython')
+ resource_name = get_or_default(kv, 'RESOURCE_NAME', name)
add_libra_modules = get_or_default(kv, 'ADD_LIBRA_MODULES', 'no') == 'yes'
-
- use_arcadia_python = unit.get('USE_ARCADIA_PYTHON') == 'yes'
+
+ use_arcadia_python = unit.get('USE_ARCADIA_PYTHON') == 'yes'
py3 = unit.get('PYTHON3') == 'yes'
-
+
unit.onyql_abi_version(['2', '9', '0'])
unit.onpeerdir(['yql/udfs/common/python/python_udf'])
unit.onpeerdir(['ydb/library/yql/public/udf'])
-
+
if add_libra_modules:
unit.onpeerdir(['quality/user_sessions/libra_arc/noyql'])
unit.onpeerdir(['yql/udfs/quality/libra/module'])
- if use_arcadia_python:
- flavor = 'Arcadia'
- unit.onpeerdir([
- 'library/python/runtime',
+ if use_arcadia_python:
+ flavor = 'Arcadia'
+ unit.onpeerdir([
+ 'library/python/runtime',
'yql/udfs/common/python/main'
] if not py3 else [
'library/python/runtime_py3',
'yql/udfs/common/python/main_py3'
- ])
- else:
- flavor = 'System'
-
+ ])
+ else:
+ flavor = 'System'
+
output_includes = [
'yql/udfs/common/python/python_udf/python_udf.h',
'ydb/library/yql/public/udf/udf_registrator.h',
@@ -44,12 +44,12 @@ def onregister_yql_python_udf(unit, *args):
if add_libra_modules:
output_includes.append('yql/udfs/quality/libra/module/module.h')
- path = name + '.yql_python_udf.cpp'
+ path = name + '.yql_python_udf.cpp'
libra_flag = '1' if add_libra_modules else '0'
unit.onpython([
- 'build/scripts/gen_yql_python_udf.py',
+ 'build/scripts/gen_yql_python_udf.py',
flavor, name, resource_name, path, libra_flag,
- 'OUT', path,
+ 'OUT', path,
'OUTPUT_INCLUDES',
] + output_includes
)
diff --git a/build/rules/contrib_python.policy b/build/rules/contrib_python.policy
index 0d0bd39ff2..60fd149753 100644
--- a/build/rules/contrib_python.policy
+++ b/build/rules/contrib_python.policy
@@ -549,7 +549,7 @@ ALLOW quality/functionality/turbo/forms/app/lib -> contrib/python/sqlalchemy/sql
ALLOW quality/functionality/turbo/forms/job/lib -> contrib/python/sqlalchemy/sqlalchemy-1.2
ALLOW quality/functionality/turbo/json_api/app/lib -> contrib/python/sqlalchemy/sqlalchemy-1.2
ALLOW quality/functionality/turbo/json_api/job/lib -> contrib/python/sqlalchemy/sqlalchemy-1.2
-ALLOW quasar/db/orm -> contrib/python/sqlalchemy/sqlalchemy-1.2
+ALLOW quasar/db/orm -> contrib/python/sqlalchemy/sqlalchemy-1.2
ALLOW quasar/manufacturing/jangles/app -> contrib/python/sqlalchemy/sqlalchemy-1.2
ALLOW quasar/manufacturing/jangles/blueprints -> contrib/python/sqlalchemy/sqlalchemy-1.2
ALLOW quasar/manufacturing/jangles/models -> contrib/python/sqlalchemy/sqlalchemy-1.2
diff --git a/build/rules/contrib_restricted.policy b/build/rules/contrib_restricted.policy
index ffb67177da..a83ead1904 100644
--- a/build/rules/contrib_restricted.policy
+++ b/build/rules/contrib_restricted.policy
@@ -1,8 +1,8 @@
-# == Rules for contrib/restricted section ==
-#
-# NOTE: rules should be ordered from specific to generic (first matching rule is used)
-# See rule syntax docs: https://wiki.yandex-team.ru/devrules/overall/peerdirprohibition/
-
+# == Rules for contrib/restricted section ==
+#
+# NOTE: rules should be ordered from specific to generic (first matching rule is used)
+# See rule syntax docs: https://wiki.yandex-team.ru/devrules/overall/peerdirprohibition/
+
# scale_ipp filter for ffmpeg use Intel IPP hence it is nonfree
ALLOW strm/cv/ffmpeg_adcv/toshik_filters -> contrib/restricted/ffmpeg-3-scale-ipp
@@ -44,28 +44,28 @@ ALLOW mds -> contrib/restricted/uriparser
# https://st.yandex-team.ru/CONTRIB-2020
ALLOW weather -> contrib/restricted/range-v3
-# ALSA library is LGPL
+# ALSA library is LGPL
ALLOW yandex_io -> contrib/restricted/alsa-lib
-ALLOW smart_devices -> contrib/restricted/alsa-lib
-
+ALLOW smart_devices -> contrib/restricted/alsa-lib
+
# Avahi is LGPL
ALLOW yandex_io -> contrib/restricted/avahi
-# GLib is LGPL
-ALLOW maps/libs/img -> contrib/restricted/glib
-ALLOW maps/renderer/libs/svgrenderer -> contrib/restricted/glib
+# GLib is LGPL
+ALLOW maps/libs/img -> contrib/restricted/glib
+ALLOW maps/renderer/libs/svgrenderer -> contrib/restricted/glib
ALLOW market/cataloger -> contrib/restricted/glib
ALLOW market/idx/feeds/feedparser -> contrib/restricted/glib
ALLOW metrika/core/libs/statdaemons -> contrib/restricted/glib
ALLOW metrika/core/libs/strconvert -> contrib/restricted/glib
ALLOW yandex_io -> contrib/restricted/glib
-
+
# GStreamer is LGPL
ALLOW yandex_io -> contrib/restricted/gstreamer
ALLOW yandex_io -> contrib/restricted/gst-plugins-base
ALLOW yandex_io -> contrib/restricted/gst-plugins-good
ALLOW yandex_io -> contrib/restricted/gst-plugins-bad
-ALLOW yandex_io -> contrib/restricted/patched/gst-libav
+ALLOW yandex_io -> contrib/restricted/patched/gst-libav
# mpg123 is LGPL
ALLOW extsearch/audio/kernel/recoglib -> contrib/restricted/mpg123
@@ -77,7 +77,7 @@ ALLOW speechkit -> contrib/restricted/openal-soft
# rubberband is a GPL audio stretching library
ALLOW dict/mt/video -> contrib/restricted/rubberband
-# Allowed subset of abseil is exported via library/
+# Allowed subset of abseil is exported via library/
ALLOW library/cpp/containers/absl_flat_hash -> contrib/restricted/abseil-cpp/absl/container
ALLOW library/cpp/containers/absl_tstring_flat_hash -> contrib/restricted/abseil-cpp-tstring/y_absl/container
@@ -106,14 +106,14 @@ ALLOW maps/infra/ecstatic -> contrib/restricted/libtorrent
#
# strm/common/go/pkg/murmur3 is a CGO binding to murmurhash, thus dependency is allowed
ALLOW strm/common/go/pkg/murmur3 -> contrib/restricted/murmurhash
-ALLOW clickhouse -> contrib/restricted/murmurhash
+ALLOW clickhouse -> contrib/restricted/murmurhash
# exiv2 is GPL-licensed. Only small subset of our libraries can use it.
ALLOW extsearch/images/chunks/exiftags -> contrib/restricted/exiv2
ALLOW maps/wikimap/mapspro/services/mrc/libs/common -> contrib/restricted/exiv2
ALLOW yweb/disk/ocraas -> contrib/restricted/exiv2
-# Only allow boost in yandex projects listed below
+# Only allow boost in yandex projects listed below
ALLOW adfox -> contrib/restricted/boost
ALLOW ads -> contrib/restricted/boost
ALLOW advq -> contrib/restricted/boost
@@ -156,7 +156,7 @@ ALLOW market/access/server/env -> contrib/restricted/boost
ALLOW sdg/library/cpp/ros_msg_parser -> contrib/restricted/boost
ALLOW search/meta/scatter/ant -> contrib/restricted/boost
ALLOW search/meta/scatter/ut -> contrib/restricted/boost
-
+
# use GTEST target in ya.make instead of PEERDIRing contrib/restricted/googletest
# and include <library/cpp/testing/gtest.h> instead of <gtest/gtest.h> (<gmock/gmock.h>)
ALLOW contrib -> contrib/restricted/googletest
@@ -182,9 +182,9 @@ ALLOW .* -> contrib/restricted/librseq/headeronly
# we use nfs-ganesha for Network File Store gateway
ALLOW cloud/filestore/gateway/nfs -> contrib/restricted/nfs_ganesha
-ALLOW yandex_io -> contrib/restricted/patched/hostap_client
-
-# Default policies:
+ALLOW yandex_io -> contrib/restricted/patched/hostap_client
+
+# Default policies:
#
# Do not restrict contrib
# All peerdirs to contrib/restricted from outside are prohibited
diff --git a/build/scripts/find_time_trace.py b/build/scripts/find_time_trace.py
index 3eb0854403..954d203caa 100644
--- a/build/scripts/find_time_trace.py
+++ b/build/scripts/find_time_trace.py
@@ -1,17 +1,17 @@
-import os
-import sys
-
-# /scripts/find_time_trace.py <object_file> <destination>
-# clang generates `-ftime-trace` output file path based on main output file path
-
-
-def main():
- assert len(sys.argv) == 3
- obj_path = sys.argv[1]
- trace_path = sys.argv[2]
- orig_trace_path = obj_path.rpartition('.o')[0] + '.json'
- os.rename(orig_trace_path, trace_path)
-
-
-if __name__ == '__main__':
- main()
+import os
+import sys
+
+# /scripts/find_time_trace.py <object_file> <destination>
+# clang generates `-ftime-trace` output file path based on main output file path
+
+
+def main():
+ assert len(sys.argv) == 3
+ obj_path = sys.argv[1]
+ trace_path = sys.argv[2]
+ orig_trace_path = obj_path.rpartition('.o')[0] + '.json'
+ os.rename(orig_trace_path, trace_path)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/build/scripts/gen_yql_python_udf.py b/build/scripts/gen_yql_python_udf.py
index 5613f58366..13b5898117 100644
--- a/build/scripts/gen_yql_python_udf.py
+++ b/build/scripts/gen_yql_python_udf.py
@@ -1,18 +1,18 @@
-import sys
-
-TEMPLATE="""
+import sys
+
+TEMPLATE="""
#include <yql/udfs/common/python/python_udf/python_udf.h>
-
+
#include <ydb/library/yql/public/udf/udf_registrator.h>
-
+
#if @WITH_LIBRA@
#include <yql/udfs/quality/libra/module/module.h>
#endif
-using namespace NKikimr::NUdf;
-
-#ifdef BUILD_UDF
-
+using namespace NKikimr::NUdf;
+
+#ifdef BUILD_UDF
+
#if @WITH_LIBRA@
LIBRA_MODULE(TLibraModule, "Libra@MODULE_NAME@");
#endif
@@ -23,7 +23,7 @@ extern "C" UDF_API void Register(IRegistrator& registrator, ui32 flags) {
RegisterHelper<TLibraModule>(registrator);
#endif
}
-
+
extern "C" UDF_API ui32 AbiVersion() {
return CurrentAbiVersion();
}
@@ -32,24 +32,24 @@ extern "C" UDF_API void SetBackTraceCallback(TBackTraceCallback callback) {
SetBackTraceCallbackImpl(callback);
}
-#endif
-"""
-
-
-def main():
+#endif
+"""
+
+
+def main():
assert len(sys.argv) == 6
flavor, module_name, package_name, path, libra_flag = sys.argv[1:]
- with open(path, 'w') as f:
- f.write(
- TEMPLATE
- .strip()
- .replace('@MODULE_NAME@', module_name)
- .replace('@PACKAGE_NAME@', package_name)
- .replace('@FLAVOR@', flavor)
+ with open(path, 'w') as f:
+ f.write(
+ TEMPLATE
+ .strip()
+ .replace('@MODULE_NAME@', module_name)
+ .replace('@PACKAGE_NAME@', package_name)
+ .replace('@FLAVOR@', flavor)
.replace('@WITH_LIBRA@', libra_flag)
- )
- f.write('\n')
-
-
-if __name__ == "__main__":
- main()
+ )
+ f.write('\n')
+
+
+if __name__ == "__main__":
+ main()
diff --git a/build/scripts/link_dyn_lib.py b/build/scripts/link_dyn_lib.py
index ddd3d6d658..23487f5c1e 100644
--- a/build/scripts/link_dyn_lib.py
+++ b/build/scripts/link_dyn_lib.py
@@ -4,19 +4,19 @@ import subprocess
import tempfile
import collections
import optparse
-import pipes
+import pipes
from process_whole_archive_option import ProcessWholeArchiveOption
-def shlex_join(cmd):
- # equivalent to shlex.join() in python 3
- return ' '.join(
- pipes.quote(part)
- for part in cmd
- )
-
-
+def shlex_join(cmd):
+ # equivalent to shlex.join() in python 3
+ return ' '.join(
+ pipes.quote(part)
+ for part in cmd
+ )
+
+
def parse_export_file(p):
with open(p, 'r') as f:
for l in f:
@@ -165,7 +165,7 @@ def parse_args():
parser.add_option('--target')
parser.add_option('--soname')
parser.add_option('--fix-elf')
- parser.add_option('--linker-output')
+ parser.add_option('--linker-output')
parser.add_option('--musl', action='store_true')
parser.add_option('--whole-archive-peers', action='append')
parser.add_option('--whole-archive-libs', action='append')
@@ -180,18 +180,18 @@ if __name__ == '__main__':
cmd = fix_cmd(opts.arch, opts.musl, args)
cmd = ProcessWholeArchiveOption(opts.arch, opts.whole_archive_peers, opts.whole_archive_libs).construct_cmd(cmd)
-
- if opts.linker_output:
- stdout = open(opts.linker_output, 'w')
- else:
- stdout = sys.stdout
-
- proc = subprocess.Popen(cmd, shell=False, stderr=sys.stderr, stdout=stdout)
+
+ if opts.linker_output:
+ stdout = open(opts.linker_output, 'w')
+ else:
+ stdout = sys.stdout
+
+ proc = subprocess.Popen(cmd, shell=False, stderr=sys.stderr, stdout=stdout)
proc.communicate()
if proc.returncode:
- print >>sys.stderr, 'linker has failed with retcode:', proc.returncode
- print >>sys.stderr, 'linker command:', shlex_join(cmd)
+ print >>sys.stderr, 'linker has failed with retcode:', proc.returncode
+ print >>sys.stderr, 'linker command:', shlex_join(cmd)
sys.exit(proc.returncode)
if opts.fix_elf:
@@ -200,8 +200,8 @@ if __name__ == '__main__':
proc.communicate()
if proc.returncode:
- print >>sys.stderr, 'fix_elf has failed with retcode:', proc.returncode
- print >>sys.stderr, 'fix_elf command:', shlex_join(cmd)
+ print >>sys.stderr, 'fix_elf has failed with retcode:', proc.returncode
+ print >>sys.stderr, 'fix_elf command:', shlex_join(cmd)
sys.exit(proc.returncode)
if opts.soname and opts.soname != opts.target:
diff --git a/build/scripts/link_exe.py b/build/scripts/link_exe.py
index ff0f63337e..f469e3b442 100644
--- a/build/scripts/link_exe.py
+++ b/build/scripts/link_exe.py
@@ -51,7 +51,7 @@ def parse_args():
parser.add_option('--python')
parser.add_option('--source-root')
parser.add_option('--arch')
- parser.add_option('--linker-output')
+ parser.add_option('--linker-output')
parser.add_option('--whole-archive-peers', action='append')
parser.add_option('--whole-archive-libs', action='append')
return parser.parse_args()
@@ -59,24 +59,24 @@ def parse_args():
if __name__ == '__main__':
opts, args = parse_args()
-
+
cmd = fix_cmd(opts.musl, args)
cmd = ProcessWholeArchiveOption(opts.arch, opts.whole_archive_peers, opts.whole_archive_libs).construct_cmd(cmd)
-
+
if opts.custom_step:
assert opts.python
subprocess.check_call([opts.python] + [opts.custom_step] + args)
-
- supp, cmd = get_leaks_suppressions(cmd)
- if supp:
+
+ supp, cmd = get_leaks_suppressions(cmd)
+ if supp:
src_file = "default_suppressions.cpp"
gen_default_suppressions(supp, src_file, opts.source_root)
- cmd += [src_file]
-
- if opts.linker_output:
- stdout = open(opts.linker_output, 'w')
- else:
- stdout = sys.stdout
-
- rc = subprocess.call(cmd, shell=False, stderr=sys.stderr, stdout=stdout)
+ cmd += [src_file]
+
+ if opts.linker_output:
+ stdout = open(opts.linker_output, 'w')
+ else:
+ stdout = sys.stdout
+
+ rc = subprocess.call(cmd, shell=False, stderr=sys.stderr, stdout=stdout)
sys.exit(rc)
diff --git a/build/scripts/py_compile.py b/build/scripts/py_compile.py
index 5e80045062..936dbe8816 100755
--- a/build/scripts/py_compile.py
+++ b/build/scripts/py_compile.py
@@ -1,24 +1,24 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-from __future__ import print_function, absolute_import, division
-
-import marshal
-import sys
-
-
-def main():
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from __future__ import print_function, absolute_import, division
+
+import marshal
+import sys
+
+
+def main():
srcpathx, in_fname, out_fname = sys.argv[1:]
srcpath = srcpathx[:-1]
with open(in_fname, 'r') as in_file:
- source = in_file.read()
+ source = in_file.read()
code = compile(source, srcpath, 'exec', dont_inherit=True)
with open(out_fname, 'wb') as out_file:
- marshal.dump(code, out_file)
-
-
-if __name__ == "__main__":
- main()
+ marshal.dump(code, out_file)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/build/sysincl/android.yml b/build/sysincl/android.yml
index bc3bd261ce..97cfbf38d2 100644
--- a/build/sysincl/android.yml
+++ b/build/sysincl/android.yml
@@ -14,18 +14,18 @@
- GLES2/gl2.h
- GLES2/gl2ext.h
- GLES3/gl31.h
- - SLES/OpenSLES.h
- - SLES/OpenSLES_Android.h
- - SLES/OpenSLES_AndroidConfiguration.h
- - SLES/OpenSLES_AndroidMetadata.h
- - SLES/OpenSLES_Platform.h
+ - SLES/OpenSLES.h
+ - SLES/OpenSLES_Android.h
+ - SLES/OpenSLES_AndroidConfiguration.h
+ - SLES/OpenSLES_AndroidMetadata.h
+ - SLES/OpenSLES_Platform.h
- linux/ashmem.h
-
-- source_filter: "^contrib/libs/breakpad/src"
- includes:
- - elf.h: contrib/libs/breakpad/src/common/android/include/elf.h
- - link.h: contrib/libs/breakpad/src/common/android/include/link.h
- - sys/procfs.h: contrib/libs/breakpad/src/common/android/include/sys/procfs.h
- - sys/signal.h: contrib/libs/breakpad/src/common/android/include/sys/signal.h
- - sys/user.h: contrib/libs/breakpad/src/common/android/include/sys/user.h
- - ucontext.h: contrib/libs/breakpad/src/common/android/include/ucontext.h
+
+- source_filter: "^contrib/libs/breakpad/src"
+ includes:
+ - elf.h: contrib/libs/breakpad/src/common/android/include/elf.h
+ - link.h: contrib/libs/breakpad/src/common/android/include/link.h
+ - sys/procfs.h: contrib/libs/breakpad/src/common/android/include/sys/procfs.h
+ - sys/signal.h: contrib/libs/breakpad/src/common/android/include/sys/signal.h
+ - sys/user.h: contrib/libs/breakpad/src/common/android/include/sys/user.h
+ - ucontext.h: contrib/libs/breakpad/src/common/android/include/ucontext.h
diff --git a/build/sysincl/darwin.yml b/build/sysincl/darwin.yml
index d72f425586..582c7e1202 100644
--- a/build/sysincl/darwin.yml
+++ b/build/sysincl/darwin.yml
@@ -72,7 +72,7 @@
- mach/mach_types.h
- mach/mach_vm.h
- mach/machine.h
- - mach/machine/vm_param.h
+ - mach/machine/vm_param.h
- mach/processor_info.h
- mach/semaphore.h
- mach/shared_memory_server.h
diff --git a/build/sysincl/linux-musl.yml b/build/sysincl/linux-musl.yml
index 334c45c168..2c7a11bf06 100644
--- a/build/sysincl/linux-musl.yml
+++ b/build/sysincl/linux-musl.yml
@@ -13,6 +13,6 @@
- sys/sysctl.h: contrib/libs/musl/extra/sys/sysctl.h
- xlocale.h: contrib/libs/musl/extra/xlocale.h
-- source_filter: "^contrib/restricted/boost"
+- source_filter: "^contrib/restricted/boost"
includes:
- ../include/fenv.h: contrib/libs/musl/include/fenv.h
diff --git a/build/sysincl/linux-ubuntu-12.yml b/build/sysincl/linux-ubuntu-12.yml
index 6c1be94d21..b310250e6b 100644
--- a/build/sysincl/linux-ubuntu-12.yml
+++ b/build/sysincl/linux-ubuntu-12.yml
@@ -1,3 +1,3 @@
-- source_filter: "^contrib/libs/systemd"
- includes:
- - uchar.h: contrib/libs/libc_compat/include/uchar/uchar.h
+- source_filter: "^contrib/libs/systemd"
+ includes:
+ - uchar.h: contrib/libs/libc_compat/include/uchar/uchar.h
diff --git a/build/sysincl/misc.yml b/build/sysincl/misc.yml
index 3291b4df29..e9e6095888 100644
--- a/build/sysincl/misc.yml
+++ b/build/sysincl/misc.yml
@@ -21,8 +21,8 @@
# Btw: seems that this ADDINCL should be made global and removed from projects
# that use this header
- includes:
- - iconv.h: contrib/libs/libiconv/include/iconv.h
-
+ - iconv.h: contrib/libs/libiconv/include/iconv.h
+
- includes:
- cudnn.h: contrib/libs/nvidia/cudnn/cudnn.h
@@ -229,11 +229,11 @@
- cuda.h: contrib/libs/tf/tensorflow/core/platform/cuda.h
# unused legacy include in boost
-- source_filter: "^contrib/restricted/boost"
+- source_filter: "^contrib/restricted/boost"
includes:
- - atomic.h
+ - atomic.h
- fstream.h
- - ../include/fenv.h
+ - ../include/fenv.h
- source_filter: "^contrib/restricted/boost/boost/stacktrace/detail"
includes:
@@ -255,10 +255,10 @@
- sasl/sasl.h
- sasl/saslutil.h
-- source_filter: "^contrib/libs/apr"
- includes:
- - atomic.h
-
+- source_filter: "^contrib/libs/apr"
+ includes:
+ - atomic.h
+
- source_filter: "^contrib/libs/(apr|httpd|llvm)"
includes:
- uuid.h
@@ -393,17 +393,17 @@
includes:
- mpi.h
-- source_filter: "^contrib/libs/libf2c"
- includes:
- - local.h
-
-- source_filter: "^contrib/libs/libpq"
- includes:
- - local.h
-
-- source_filter: "^contrib/libs/breakpad"
- includes:
- - stab.h
+- source_filter: "^contrib/libs/libf2c"
+ includes:
+ - local.h
+
+- source_filter: "^contrib/libs/libpq"
+ includes:
+ - local.h
+
+- source_filter: "^contrib/libs/breakpad"
+ includes:
+ - stab.h
- source_filter: "^contrib/tools/fluent-bit"
includes:
diff --git a/build/sysincl/stl-to-libcxx.yml b/build/sysincl/stl-to-libcxx.yml
index 97a019e1fa..7d9600f345 100644
--- a/build/sysincl/stl-to-libcxx.yml
+++ b/build/sysincl/stl-to-libcxx.yml
@@ -45,7 +45,7 @@
- cxxabi.h: contrib/libs/cxxsupp/libcxxabi/include/cxxabi.h
- includes:
- - __config: contrib/libs/cxxsupp/libcxx/include/__config
+ - __config: contrib/libs/cxxsupp/libcxx/include/__config
- __undef_macros: contrib/libs/cxxsupp/libcxx/include/__undef_macros
- algorithm: contrib/libs/cxxsupp/libcxx/include/algorithm
- any: contrib/libs/cxxsupp/libcxx/include/any
diff --git a/build/sysincl/stl-to-nothing.yml b/build/sysincl/stl-to-nothing.yml
index 769711be74..c7e27d1411 100644
--- a/build/sysincl/stl-to-nothing.yml
+++ b/build/sysincl/stl-to-nothing.yml
@@ -28,7 +28,7 @@
- wctype.h
- includes:
- - __config
+ - __config
- __undef_macros
- algorithm
- any
diff --git a/build/sysincl/windows.yml b/build/sysincl/windows.yml
index 046a7a4412..26ae7b5bfa 100644
--- a/build/sysincl/windows.yml
+++ b/build/sysincl/windows.yml
@@ -14,7 +14,7 @@
- bcrypt.h
- bits.h
- capi.h
- - cet.h
+ - cet.h
- cfg.h
- comdef.h
- commctrl.h
@@ -145,7 +145,7 @@
- new.h
- npapi.h
- ntdddisk.h
- - ntddk.h
+ - ntddk.h
- ntddndis.h
- ntdef.h
- ntsecapi.h
@@ -190,7 +190,7 @@
- realtimeapiset.h
- reason.h
- richedit.h
- - roapi.h
+ - roapi.h
- robuffer.h
- rpc.h
- rpcdce.h
@@ -287,7 +287,7 @@
- winsdkver.h
- winsock.h
- winsock2.h
- - winstring.h
+ - winstring.h
- winsvc.h
- winternl.h
- winuser.h
@@ -313,4 +313,4 @@
- wtypes.h
- xa.h
- xaudio2.h
- - xmllite.h
+ - xmllite.h
diff --git a/build/ya.conf.json b/build/ya.conf.json
index c4d18d0835..5f7cc875d6 100644
--- a/build/ya.conf.json
+++ b/build/ya.conf.json
@@ -15,9 +15,9 @@
"clang-tidy": {
"description": "Run Clang-Tidy source code linter"
},
- "clang-apply-replacements": {
- "description": "Run clang-apply-replacements companion for clang-tidy"
- },
+ "clang-apply-replacements": {
+ "description": "Run clang-apply-replacements companion for clang-tidy"
+ },
"cling": {
"description": "Run cling"
},
@@ -196,7 +196,7 @@
"description": "Run gcov"
},
"bloat": {
- "description": "Run bloat tool",
+ "description": "Run bloat tool",
"visible": false
},
"ipython": {
@@ -1906,16 +1906,16 @@
},
"target": {
"os": "LINUX",
- "arch": "armv7a_cortex_a9"
- },
- "default": true
- },
- {
- "host": {
- "os": "LINUX"
- },
- "target": {
- "os": "LINUX",
+ "arch": "armv7a_cortex_a9"
+ },
+ "default": true
+ },
+ {
+ "host": {
+ "os": "LINUX"
+ },
+ "target": {
+ "os": "LINUX",
"arch": "armv7ahf_cortex_a35"
},
"default": true
@@ -2346,311 +2346,311 @@
}
}
},
- "android-ndk-r23": {
- "name": "clang12",
- "tools": {
- "cc": {
- "bottle": "android-ndk-r23",
- "executable": "cc"
- },
- "c++": {
- "bottle": "android-ndk-r23",
- "executable": "c++"
- },
- "gcov": {
- "bottle": "android-ndk-r23",
- "executable": "llvm-cov"
- },
- "strip": {
- "bottle": "android-ndk-r23",
- "executable": "strip"
- },
- "objcopy": {
- "bottle": "android-ndk-r23",
- "executable": "objcopy"
- },
- "nm": {
- "bottle": "android-ndk-r23",
- "executable": "nm"
- },
- "llvm-cov": {
- "bottle": "android-ndk-r23",
- "executable": "llvm-cov"
- },
- "llvm-profdata": {
- "bottle": "android-ndk-r23",
- "executable": "llvm-profdata"
- },
- "llvm-symbolizer": {
- "bottle": "android-ndk-r23",
- "executable": "llvm-symbolizer"
- }
- },
- "platforms": [
- {
- "host": {
- "os": "LINUX"
- },
- "target": {
- "os": "ANDROID",
- "arch": "i686"
- },
- "default": true
- },
- {
- "host": {
- "os": "LINUX"
- },
- "target": {
- "os": "ANDROID",
- "arch": "x86_64"
- },
- "default": true
- },
- {
- "host": {
- "os": "LINUX"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv7a"
- },
- "default": true
- },
- {
- "host": {
- "os": "LINUX"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv7a_neon"
- },
- "default": true
- },
- {
- "host": {
- "os": "LINUX"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv8a"
- },
- "default": true
- },
- {
- "host": {
- "os": "DARWIN"
- },
- "target": {
- "os": "ANDROID",
- "arch": "i686"
- },
- "default": true
- },
- {
- "host": {
- "os": "DARWIN"
- },
- "target": {
- "os": "ANDROID",
- "arch": "x86_64"
- },
- "default": true
- },
- {
- "host": {
- "os": "DARWIN"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv7a"
- },
- "default": true
- },
- {
- "host": {
- "os": "DARWIN"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv7a_neon"
- },
- "default": true
- },
- {
- "host": {
- "os": "DARWIN"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv8a"
- },
- "default": true
- }
- ],
- "params": {
- "type": "clang",
- "match_root": "NDK",
- "ar": "$(NDK)/llvm-toolchain/bin/llvm-ar",
- "c_compiler": "$(NDK)/llvm-toolchain/bin/clang",
- "cxx_compiler": "$(NDK)/llvm-toolchain/bin/clang++",
- "objcopy": "$(NDK)/llvm-toolchain/bin/llvm-objcopy",
- "strip": "$(NDK)/llvm-toolchain/bin/llvm-strip",
- "werror_mode": "all",
- "gcc_version": "12.0",
- "android_ndk_version": 23
- }
- },
- "android-ndk-r24": {
- "name": "clang13",
- "tools": {
- "cc": {
- "bottle": "android-ndk-r24",
- "executable": "cc"
- },
- "c++": {
- "bottle": "android-ndk-r24",
- "executable": "c++"
- },
- "gcov": {
- "bottle": "android-ndk-r24",
- "executable": "llvm-cov"
- },
- "strip": {
- "bottle": "android-ndk-r24",
- "executable": "strip"
- },
- "objcopy": {
- "bottle": "android-ndk-r24",
- "executable": "objcopy"
- },
- "nm": {
- "bottle": "android-ndk-r24",
- "executable": "nm"
- },
- "llvm-cov": {
- "bottle": "android-ndk-r24",
- "executable": "llvm-cov"
- },
- "llvm-profdata": {
- "bottle": "android-ndk-r24",
- "executable": "llvm-profdata"
- },
- "llvm-symbolizer": {
- "bottle": "android-ndk-r24",
- "executable": "llvm-symbolizer"
- }
- },
- "platforms": [
- {
- "host": {
- "os": "LINUX"
- },
- "target": {
- "os": "ANDROID",
- "arch": "i686"
- }
- },
- {
- "host": {
- "os": "LINUX"
- },
- "target": {
- "os": "ANDROID",
- "arch": "x86_64"
- }
- },
- {
- "host": {
- "os": "LINUX"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv7a"
- }
- },
- {
- "host": {
- "os": "LINUX"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv7a_neon"
- }
- },
- {
- "host": {
- "os": "LINUX"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv8a"
- }
- },
- {
- "host": {
- "os": "DARWIN"
- },
- "target": {
- "os": "ANDROID",
- "arch": "i686"
- }
- },
- {
- "host": {
- "os": "DARWIN"
- },
- "target": {
- "os": "ANDROID",
- "arch": "x86_64"
- }
- },
- {
- "host": {
- "os": "DARWIN"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv7a"
- }
- },
- {
- "host": {
- "os": "DARWIN"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv7a_neon"
- }
- },
- {
- "host": {
- "os": "DARWIN"
- },
- "target": {
- "os": "ANDROID",
- "arch": "armv8a"
- }
- }
- ],
- "params": {
- "type": "clang",
- "match_root": "NDK",
- "ar": "$(NDK)/llvm-toolchain/bin/llvm-ar",
- "c_compiler": "$(NDK)/llvm-toolchain/bin/clang",
- "cxx_compiler": "$(NDK)/llvm-toolchain/bin/clang++",
- "objcopy": "$(NDK)/llvm-toolchain/bin/llvm-objcopy",
- "strip": "$(NDK)/llvm-toolchain/bin/llvm-strip",
- "werror_mode": "all",
- "gcc_version": "13.0",
- "android_ndk_version": 24
- }
- },
+ "android-ndk-r23": {
+ "name": "clang12",
+ "tools": {
+ "cc": {
+ "bottle": "android-ndk-r23",
+ "executable": "cc"
+ },
+ "c++": {
+ "bottle": "android-ndk-r23",
+ "executable": "c++"
+ },
+ "gcov": {
+ "bottle": "android-ndk-r23",
+ "executable": "llvm-cov"
+ },
+ "strip": {
+ "bottle": "android-ndk-r23",
+ "executable": "strip"
+ },
+ "objcopy": {
+ "bottle": "android-ndk-r23",
+ "executable": "objcopy"
+ },
+ "nm": {
+ "bottle": "android-ndk-r23",
+ "executable": "nm"
+ },
+ "llvm-cov": {
+ "bottle": "android-ndk-r23",
+ "executable": "llvm-cov"
+ },
+ "llvm-profdata": {
+ "bottle": "android-ndk-r23",
+ "executable": "llvm-profdata"
+ },
+ "llvm-symbolizer": {
+ "bottle": "android-ndk-r23",
+ "executable": "llvm-symbolizer"
+ }
+ },
+ "platforms": [
+ {
+ "host": {
+ "os": "LINUX"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "i686"
+ },
+ "default": true
+ },
+ {
+ "host": {
+ "os": "LINUX"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "x86_64"
+ },
+ "default": true
+ },
+ {
+ "host": {
+ "os": "LINUX"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv7a"
+ },
+ "default": true
+ },
+ {
+ "host": {
+ "os": "LINUX"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv7a_neon"
+ },
+ "default": true
+ },
+ {
+ "host": {
+ "os": "LINUX"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv8a"
+ },
+ "default": true
+ },
+ {
+ "host": {
+ "os": "DARWIN"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "i686"
+ },
+ "default": true
+ },
+ {
+ "host": {
+ "os": "DARWIN"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "x86_64"
+ },
+ "default": true
+ },
+ {
+ "host": {
+ "os": "DARWIN"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv7a"
+ },
+ "default": true
+ },
+ {
+ "host": {
+ "os": "DARWIN"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv7a_neon"
+ },
+ "default": true
+ },
+ {
+ "host": {
+ "os": "DARWIN"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv8a"
+ },
+ "default": true
+ }
+ ],
+ "params": {
+ "type": "clang",
+ "match_root": "NDK",
+ "ar": "$(NDK)/llvm-toolchain/bin/llvm-ar",
+ "c_compiler": "$(NDK)/llvm-toolchain/bin/clang",
+ "cxx_compiler": "$(NDK)/llvm-toolchain/bin/clang++",
+ "objcopy": "$(NDK)/llvm-toolchain/bin/llvm-objcopy",
+ "strip": "$(NDK)/llvm-toolchain/bin/llvm-strip",
+ "werror_mode": "all",
+ "gcc_version": "12.0",
+ "android_ndk_version": 23
+ }
+ },
+ "android-ndk-r24": {
+ "name": "clang13",
+ "tools": {
+ "cc": {
+ "bottle": "android-ndk-r24",
+ "executable": "cc"
+ },
+ "c++": {
+ "bottle": "android-ndk-r24",
+ "executable": "c++"
+ },
+ "gcov": {
+ "bottle": "android-ndk-r24",
+ "executable": "llvm-cov"
+ },
+ "strip": {
+ "bottle": "android-ndk-r24",
+ "executable": "strip"
+ },
+ "objcopy": {
+ "bottle": "android-ndk-r24",
+ "executable": "objcopy"
+ },
+ "nm": {
+ "bottle": "android-ndk-r24",
+ "executable": "nm"
+ },
+ "llvm-cov": {
+ "bottle": "android-ndk-r24",
+ "executable": "llvm-cov"
+ },
+ "llvm-profdata": {
+ "bottle": "android-ndk-r24",
+ "executable": "llvm-profdata"
+ },
+ "llvm-symbolizer": {
+ "bottle": "android-ndk-r24",
+ "executable": "llvm-symbolizer"
+ }
+ },
+ "platforms": [
+ {
+ "host": {
+ "os": "LINUX"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "i686"
+ }
+ },
+ {
+ "host": {
+ "os": "LINUX"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "x86_64"
+ }
+ },
+ {
+ "host": {
+ "os": "LINUX"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv7a"
+ }
+ },
+ {
+ "host": {
+ "os": "LINUX"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv7a_neon"
+ }
+ },
+ {
+ "host": {
+ "os": "LINUX"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv8a"
+ }
+ },
+ {
+ "host": {
+ "os": "DARWIN"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "i686"
+ }
+ },
+ {
+ "host": {
+ "os": "DARWIN"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "x86_64"
+ }
+ },
+ {
+ "host": {
+ "os": "DARWIN"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv7a"
+ }
+ },
+ {
+ "host": {
+ "os": "DARWIN"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv7a_neon"
+ }
+ },
+ {
+ "host": {
+ "os": "DARWIN"
+ },
+ "target": {
+ "os": "ANDROID",
+ "arch": "armv8a"
+ }
+ }
+ ],
+ "params": {
+ "type": "clang",
+ "match_root": "NDK",
+ "ar": "$(NDK)/llvm-toolchain/bin/llvm-ar",
+ "c_compiler": "$(NDK)/llvm-toolchain/bin/clang",
+ "cxx_compiler": "$(NDK)/llvm-toolchain/bin/clang++",
+ "objcopy": "$(NDK)/llvm-toolchain/bin/llvm-objcopy",
+ "strip": "$(NDK)/llvm-toolchain/bin/llvm-strip",
+ "werror_mode": "all",
+ "gcc_version": "13.0",
+ "android_ndk_version": 24
+ }
+ },
"bloat": {
"tools": {
"bloat": {
"bottle": "bloat",
- "executable": "bloat"
+ "executable": "bloat"
}
},
"platforms": [
@@ -2837,14 +2837,14 @@
}
]
},
- "ipython": {
- "tools": {
+ "ipython": {
+ "tools": {
"ipython": {
"bottle": "ptipython",
"executable": "ptipython"
}
- },
- "platforms": [
+ },
+ "platforms": [
{
"host": {
"os": "LINUX"
@@ -2863,16 +2863,16 @@
},
"default": true
}
- ]
- },
- "ptpython": {
- "tools": {
+ ]
+ },
+ "ptpython": {
+ "tools": {
"ptpython": {
"bottle": "ptpython",
"executable": "ptpython"
}
- },
- "platforms": [
+ },
+ "platforms": [
{
"host": {
"os": "LINUX"
@@ -2891,8 +2891,8 @@
},
"default": true
}
- ]
- },
+ ]
+ },
"wine": {
"tools": {
"wine": {
@@ -5947,13 +5947,13 @@
"bloat": {
"formula": {
"sandbox_id": [
- 801218211
+ 801218211
],
"match": "Bloat"
},
"executable": {
- "bloat": [
- "bloat"
+ "bloat": [
+ "bloat"
]
}
},
@@ -6257,51 +6257,107 @@
]
}
},
- "android-ndk-r23": {
- "formula": {
- "sandbox_id": [
- 1125103574,
- 1125105409
- ],
- "match": "NDK"
- },
- "executable": {
- "c++": [
- "llvm-toolchain",
- "bin",
- "clang++"
- ],
- "cc": [
- "llvm-toolchain",
- "bin",
- "clang"
- ],
- "strip": [
- "llvm-toolchain",
- "bin",
- "llvm-strip"
- ],
- "c++filt": [
- "llvm-toolchain",
- "bin",
- "i686-linux-android-c++filt"
- ],
- "llvm-cov": [
- "llvm-toolchain",
- "bin",
- "llvm-cov"
- ],
- "llvm-profdata": [
- "llvm-toolchain",
- "bin",
- "llvm-profdata"
- ],
- "llvm-symbolizer": [
- "llvm-toolchain",
- "bin",
- "llvm-symbolizer"
- ],
- "nm": [
+ "android-ndk-r23": {
+ "formula": {
+ "sandbox_id": [
+ 1125103574,
+ 1125105409
+ ],
+ "match": "NDK"
+ },
+ "executable": {
+ "c++": [
+ "llvm-toolchain",
+ "bin",
+ "clang++"
+ ],
+ "cc": [
+ "llvm-toolchain",
+ "bin",
+ "clang"
+ ],
+ "strip": [
+ "llvm-toolchain",
+ "bin",
+ "llvm-strip"
+ ],
+ "c++filt": [
+ "llvm-toolchain",
+ "bin",
+ "i686-linux-android-c++filt"
+ ],
+ "llvm-cov": [
+ "llvm-toolchain",
+ "bin",
+ "llvm-cov"
+ ],
+ "llvm-profdata": [
+ "llvm-toolchain",
+ "bin",
+ "llvm-profdata"
+ ],
+ "llvm-symbolizer": [
+ "llvm-toolchain",
+ "bin",
+ "llvm-symbolizer"
+ ],
+ "nm": [
+ "llvm-toolchain",
+ "bin",
+ "llvm-nm"
+ ],
+ "objcopy": [
+ "llvm-toolchain",
+ "bin",
+ "llvm-objcopy"
+ ]
+ }
+ },
+ "android-ndk-r24": {
+ "formula": {
+ "sandbox_id": [
+ 1125138634,
+ 1125141078
+ ],
+ "match": "NDK"
+ },
+ "executable": {
+ "c++": [
+ "llvm-toolchain",
+ "bin",
+ "clang++"
+ ],
+ "cc": [
+ "llvm-toolchain",
+ "bin",
+ "clang"
+ ],
+ "strip": [
+ "llvm-toolchain",
+ "bin",
+ "llvm-strip"
+ ],
+ "c++filt": [
+ "llvm-toolchain",
+ "bin",
+ "i686-linux-android-c++filt"
+ ],
+ "llvm-cov": [
+ "llvm-toolchain",
+ "bin",
+ "llvm-cov"
+ ],
+ "llvm-profdata": [
+ "llvm-toolchain",
+ "bin",
+ "llvm-profdata"
+ ],
+ "llvm-symbolizer": [
+ "llvm-toolchain",
+ "bin",
+ "llvm-symbolizer"
+ ],
+ "nm": [
"llvm-toolchain",
"bin",
"llvm-nm"
@@ -6312,62 +6368,6 @@
"llvm-objcopy"
]
}
- },
- "android-ndk-r24": {
- "formula": {
- "sandbox_id": [
- 1125138634,
- 1125141078
- ],
- "match": "NDK"
- },
- "executable": {
- "c++": [
- "llvm-toolchain",
- "bin",
- "clang++"
- ],
- "cc": [
- "llvm-toolchain",
- "bin",
- "clang"
- ],
- "strip": [
- "llvm-toolchain",
- "bin",
- "llvm-strip"
- ],
- "c++filt": [
- "llvm-toolchain",
- "bin",
- "i686-linux-android-c++filt"
- ],
- "llvm-cov": [
- "llvm-toolchain",
- "bin",
- "llvm-cov"
- ],
- "llvm-profdata": [
- "llvm-toolchain",
- "bin",
- "llvm-profdata"
- ],
- "llvm-symbolizer": [
- "llvm-toolchain",
- "bin",
- "llvm-symbolizer"
- ],
- "nm": [
- "llvm-toolchain",
- "bin",
- "llvm-nm"
- ],
- "objcopy": [
- "llvm-toolchain",
- "bin",
- "llvm-objcopy"
- ]
- }
},
"cuda": {
"formula": {
@@ -7165,7 +7165,7 @@
"sandbox_id": 121751471,
"match": "YouCompleteMe"
}
- },
+ },
"rtags": {
"formula": {
"sandbox_id": 84460170,
@@ -7217,26 +7217,26 @@
}
},
"ptpython": {
- "formula": {
- "sandbox_id": 50746186,
- "match": "PTPython"
- },
- "executable": {
+ "formula": {
+ "sandbox_id": 50746186,
+ "match": "PTPython"
+ },
+ "executable": {
"ptpython": [
"ptpython"
]
- }
- },
+ }
+ },
"ptipython": {
- "formula": {
- "sandbox_id": 50746160,
- "match": "PTIPython"
- },
- "executable": {
+ "formula": {
+ "sandbox_id": 50746160,
+ "match": "PTIPython"
+ },
+ "executable": {
"ptipython": [
"ptipython"
]
- }
+ }
},
"python3": {
"formula": {
diff --git a/build/ymake.core.conf b/build/ymake.core.conf
index 62f7fa896a..081833998b 100644
--- a/build/ymake.core.conf
+++ b/build/ymake.core.conf
@@ -11,7 +11,7 @@ FAKEID=3141592653
SANDBOX_FAKEID=${FAKEID}.7600000
CPP_FAKEID=9107927
GO_FAKEID=9056219
-ANDROID_FAKEID=8821472
+ANDROID_FAKEID=8821472
CLANG_TIDY_FAKEID=8625699
CURDIR=.
@@ -868,8 +868,8 @@ macro _CPP_PROTO_EVLOG_CMD(File) {
# process .proto as .ev
.CMD=$CPP_PROTO_CMDLINE $CPP_EV_OPTS $CPP_PROTO_OUTS ${kv;hide:"p PB"} ${kv;hide:"pc yellow"}
.PEERDIR=library/cpp/eventlog contrib/libs/protobuf
-}
-
+}
+
# tag:proto
macro _CPP_CFGPROTO_CMD(File) {
# keep extension in output just as in EV: this is hard-codeded behaviour of protoc for non-.proto extensions
@@ -1158,10 +1158,10 @@ module _BASE_UNIT: _BARE_UNIT {
otherwise {
MACRO_ALIAS(EVLOG_CMD _CPP_EVLOG_CMD)
MACRO_ALIAS(FBS_CMD _CPP_FLATC_CMD)
- when ($BUILD_PROTO_AS_EVLOG == "yes") {
+ when ($BUILD_PROTO_AS_EVLOG == "yes") {
MACRO_ALIAS(PROTO_CMD _CPP_PROTO_EVLOG_CMD)
- }
- otherwise {
+ }
+ otherwise {
MACRO_ALIAS(PROTO_CMD _CPP_PROTO_CMD)
}
when ($USE_VANILLA_PROTOC == "yes") {
@@ -1209,8 +1209,8 @@ module _BASE_UNIT: _BARE_UNIT {
LDFLAGS+=-static-libubsan
}
"thread" ? {
- PIE=yes
- LDFLAGS+=-static-libtsan
+ PIE=yes
+ LDFLAGS+=-static-libtsan
}
}
}
@@ -1218,8 +1218,8 @@ module _BASE_UNIT: _BARE_UNIT {
when ($HARDENING == "yes") {
when ($CLANG) {
CFLAGS+=-fstack-protector-all -D_hardening_enabled_
- LDFLAGS+=-z relro -z now -z noexecstack
- PIE=yes
+ LDFLAGS+=-z relro -z now -z noexecstack
+ PIE=yes
}
}
@@ -1380,29 +1380,29 @@ macro USE_LINKER_LLD() {
}
COMMON_LINK_SETTINGS=
-LINK_ADDITIONAL_SECTIONS=
-LINK_ADDITIONAL_SECTIONS_COMMAND=
+LINK_ADDITIONAL_SECTIONS=
+LINK_ADDITIONAL_SECTIONS_COMMAND=
when ($COMMON_LINK_SETTINGS == "yes") {
when ($_LINKER_ID == "lld" || $_LINKER_ID == "gold") {
LDFLAGS += -Wl,--gdb-index
}
- when ($EMBED_LINKER_CREF == "yes") {
+ when ($EMBED_LINKER_CREF == "yes") {
LDFLAGS+=-Wl,--cref ${tmp;stdout;pre=$MODULE_PREFIX;suf=.ldcref:REALPRJNAME} -Wl,--no-demangle
LINK_ADDITIONAL_SECTIONS+=--add-section=.ya.linker_cref=${tmp;pre=$MODULE_PREFIX;suf=.ldcref:REALPRJNAME}
}
- elsewhen ($DUMP_LINKER_CREF == "yes") {
+ elsewhen ($DUMP_LINKER_CREF == "yes") {
LDFLAGS+=-Wl,--cref ${output;stdout;pre=$MODULE_PREFIX;suf=.ldcref:REALPRJNAME} -Wl,--no-demangle
- }
+ }
- when ($EMBED_LINKER_MAP == "yes") {
+ when ($EMBED_LINKER_MAP == "yes") {
LDFLAGS+=-Wl,-Map=${tmp;pre=$MODULE_PREFIX;suf=.map.$_LINKER_ID:REALPRJNAME}
LINK_ADDITIONAL_SECTIONS+=--add-section=.ya.linker_map.${_LINKER_ID}=${tmp;pre=$MODULE_PREFIX;suf=.map.$_LINKER_ID:REALPRJNAME}
}
- elsewhen ($DUMP_LINKER_MAP == "yes") {
+ elsewhen ($DUMP_LINKER_MAP == "yes") {
LDFLAGS+=-Wl,-Map=${output;rootrel;pre=$MODULE_PREFIX;suf=.map.$_LINKER_ID:REALPRJNAME}
- }
+ }
when ($USE_MKL == "yes") {
NOPLATFORM=yes
@@ -1507,11 +1507,11 @@ when ($COMMON_LINK_SETTINGS == "yes") {
}
}
-when ($EMBED_LINKER_MAP == "yes" || $EMBED_LINKER_CREF == "yes") {
- LINK_ADDITIONAL_SECTIONS_COMMAND+= \
- $OBJCOPY_TOOL $LINK_ADDITIONAL_SECTIONS $TARGET
-}
-
+when ($EMBED_LINKER_MAP == "yes" || $EMBED_LINKER_CREF == "yes") {
+ LINK_ADDITIONAL_SECTIONS_COMMAND+= \
+ $OBJCOPY_TOOL $LINK_ADDITIONAL_SECTIONS $TARGET
+}
+
_SO_EXT_FILTER=${ext=.so:PEERS} ${hide;late_out;nopath;ext=.so;pre=$BINDIR/:PEERS}
when ($OS_WINDOWS == "yes") {
_SO_EXT_FILTER=${ext=.dll:PEERS} ${hide;late_out;nopath;ext=.dll;pre=$BINDIR/:PEERS}
@@ -1623,7 +1623,7 @@ module _BASE_PROGRAM: _LINK_UNIT {
MODULE_SUFFIX=.tidyjson
}
- when ($MSVC != "yes" && $NOPLATFORM != "yes" && $WITH_VALGRIND != "yes" && $USE_ASMLIB != "no" && $MIC_ARCH != "yes" && $PIC != "yes" && $PIE != "yes") {
+ when ($MSVC != "yes" && $NOPLATFORM != "yes" && $WITH_VALGRIND != "yes" && $USE_ASMLIB != "no" && $MIC_ARCH != "yes" && $PIC != "yes" && $PIE != "yes") {
PEERDIR+=contrib/libs/asmlib
}
@@ -1798,30 +1798,30 @@ module PYCR_PROGRAM: PY3_PROGRAM_BIN {
### @usage: EXPORTS_SCRIPT(exports_file)
###
-### Specify exports script within PROGRAM, DLL and DLL-derived modules.
+### Specify exports script within PROGRAM, DLL and DLL-derived modules.
### This accepts 2 kind of files: .exports with <lang symbol> pairs and JSON-line .symlist files.
-### The other option use EXPORTS parameter of the DLL module itself.
+### The other option use EXPORTS parameter of the DLL module itself.
###
### @see: [DLL](#module_DLL)
macro EXPORTS_SCRIPT(Arg) {
SET(EXPORTS_FILE $Arg)
}
-### @usage: NO_EXPORT_DYNAMIC_SYMBOLS()
-###
-### Disable exporting all non-hidden symbols as dynamic when linking a PROGRAM.
-macro NO_EXPORT_DYNAMIC_SYMBOLS() {
- ENABLE(NO_EXPORT_DYNAMIC_SYMBOLS)
-}
-
-### @usage: EXPORT_ALL_DYNAMIC_SYMBOLS()
-###
-### Export all non-hidden symbols as dynamic when linking a PROGRAM.
-macro EXPORT_ALL_DYNAMIC_SYMBOLS() {
- # Dummy: default behaviour
- ENABLE(EXPORT_ALL_DYNAMIC_SYMBOLS)
-}
-
+### @usage: NO_EXPORT_DYNAMIC_SYMBOLS()
+###
+### Disable exporting all non-hidden symbols as dynamic when linking a PROGRAM.
+macro NO_EXPORT_DYNAMIC_SYMBOLS() {
+ ENABLE(NO_EXPORT_DYNAMIC_SYMBOLS)
+}
+
+### @usage: EXPORT_ALL_DYNAMIC_SYMBOLS()
+###
+### Export all non-hidden symbols as dynamic when linking a PROGRAM.
+macro EXPORT_ALL_DYNAMIC_SYMBOLS() {
+ # Dummy: default behaviour
+ ENABLE(EXPORT_ALL_DYNAMIC_SYMBOLS)
+}
+
### @usage: CUSTOM_LINK_STEP_SCRIPT(name)
###
### Specifies name of a script for custom link step. The scripts
@@ -1874,8 +1874,8 @@ module YT_UNITTEST: _BASE_UNITTEST {
### Generic unit test module.
module UNITTEST_WITH_CUSTOM_ENTRY_POINT: _BASE_UNITTEST {
ADD_YTEST($MODULE_PREFIX$REALPRJNAME unittest.py)
-}
-
+}
+
# tag:cpp-specific tag:test
### @usage: GTEST([name])
###
@@ -5342,14 +5342,14 @@ when ($STRIP == "yes" && $NO_STRIP != "yes") {
GO_LINK_FLAGS_VALUE+=-s
}
-when ($NO_LINKER_DCE != "yes") {
- DCE_FLAG=$LD_DCE_FLAG
-}
+when ($NO_LINKER_DCE != "yes") {
+ DCE_FLAG=$LD_DCE_FLAG
+}
+
+when ($BT_MINSIZEREL == "yes" || $LINKER_ICF == "yes") {
+ ICF_FLAG=$LD_ICF_FLAG
+}
-when ($BT_MINSIZEREL == "yes" || $LINKER_ICF == "yes") {
- ICF_FLAG=$LD_ICF_FLAG
-}
-
OBJCOPY_TOOL=$OBJCOPY_TOOL_VENDOR
STRIP_TOOL=$STRIP_TOOL_VENDOR
NEED_BINUTILS_PEERDIR=
@@ -5713,11 +5713,11 @@ macro ADDINCLSELF(FOR="") {
COMPILE_OUT_SUFFIX=
_COMPILE_OUTPUTS=${output;suf=${COMPILE_OUT_SUFFIX}${OBJECT_SUF}:SRC}
-_COMPILE_TIME_TRACE_OUTPUTS=${output;noauto;suf=${COMPILE_OUT_SUFFIX}${OBJECT_SUF}.time_trace.json:SRC}
+_COMPILE_TIME_TRACE_OUTPUTS=${output;noauto;suf=${COMPILE_OUT_SUFFIX}${OBJECT_SUF}.time_trace.json:SRC}
macro SET_COMPILE_OUTPUTS_MODIFIERS(NOREL?";norel":"") {
SET(_COMPILE_OUTPUTS \${output;suf=\${OBJECT_SUF}$NOREL:SRC})
- SET(_COMPILE_TIME_TRACE_OUTPUTS \${output;noauto;suf=\${OBJECT_SUF}.time_trace.json$NOREL:SRC})
+ SET(_COMPILE_TIME_TRACE_OUTPUTS \${output;noauto;suf=\${OBJECT_SUF}.time_trace.json$NOREL:SRC})
}
_EMPTY_CMD=
@@ -6384,7 +6384,7 @@ macro _PY3_REGISTER(Func) {
macro _PY_COMPILE_BYTECODE(SrcX, Src, Dst) {
.CMD=$YMAKE_PYTHON ${input:"build/scripts/py_compile.py"} $SrcX ${input:Src} ${output;noauto:Dst.yapyc} ${requirements;hide:PY_REQUIREMENTS} ${kv;hide:"p PY"} ${kv;hide:"pc yellow"}
}
-
+
# tag:python-processing tag:internal
### @usage: _PY3_COMPILE_BYTECODE(SrcX Src) # internal
###
@@ -6450,9 +6450,9 @@ VCS_INFO_DISABLE_CACHE__NO_UID__=
YASM_DEBUG_INFO_DISABLE_CACHE__NO_UID__=
CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__=
CL_MACRO_INFO_DISABLE_CACHE__NO_UID__=
-YASM_DEBUG_INFO=
-CL_DEBUG_INFO=
-CL_MACRO_INFO=
+YASM_DEBUG_INFO=
+CL_DEBUG_INFO=
+CL_MACRO_INFO=
when ($FORCE_VCS_INFO_UPDATE == "yes") {
VCS_INFO_DISABLE_CACHE__NO_UID__=${hide;kv:"disable_cache"}
}
diff --git a/build/ymake_conf.py b/build/ymake_conf.py
index 2278c670ea..30219eb85e 100755
--- a/build/ymake_conf.py
+++ b/build/ymake_conf.py
@@ -54,22 +54,22 @@ class Platform(object):
self.is_x86_64 = self.arch in ('x86_64', 'amd64')
self.is_intel = self.is_x86 or self.is_x86_64
- self.is_armv7 = self.arch in ('armv7', 'armv7a', 'armv7a_neon', 'arm', 'armv7a_cortex_a9', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
+ self.is_armv7 = self.arch in ('armv7', 'armv7a', 'armv7a_neon', 'arm', 'armv7a_cortex_a9', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
self.is_armv8 = self.arch in ('armv8', 'armv8a', 'arm64', 'aarch64', 'armv8a_cortex_a35', 'armv8a_cortex_a53')
self.is_armv8m = self.arch in ('armv8m_cortex_m33',)
self.is_arm64 = self.arch in ('arm64',)
self.is_arm = self.is_armv7 or self.is_armv8 or self.is_armv8m
- self.is_armv7_neon = self.arch in ('armv7a_neon', 'armv7a_cortex_a9', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
- self.is_armv7hf = self.arch in ('armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
-
- self.armv7_float_abi = None
- if self.is_armv7:
- if self.is_armv7hf:
- self.armv7_float_abi = 'hard'
- else:
- self.armv7_float_abi = 'softfp'
-
- self.is_cortex_a9 = self.arch in ('armv7a_cortex_a9',)
+ self.is_armv7_neon = self.arch in ('armv7a_neon', 'armv7a_cortex_a9', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
+ self.is_armv7hf = self.arch in ('armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
+
+ self.armv7_float_abi = None
+ if self.is_armv7:
+ if self.is_armv7hf:
+ self.armv7_float_abi = 'hard'
+ else:
+ self.armv7_float_abi = 'softfp'
+
+ self.is_cortex_a9 = self.arch in ('armv7a_cortex_a9',)
self.is_cortex_a35 = self.arch in ('armv7ahf_cortex_a35', 'armv8a_cortex_a35')
self.is_cortex_a53 = self.arch in ('armv7ahf_cortex_a53', 'armv8a_cortex_a53')
self.is_cortex_m33 = self.arch in ('armv8m_cortex_m33',)
@@ -103,13 +103,13 @@ class Platform(object):
self.is_windows_x86_64 = self.is_windows and self.is_x86_64
self.is_android = self.os == 'android'
- if self.is_android:
- # This is default Android API level unless `ANDROID_API` is specified
+ if self.is_android:
+ # This is default Android API level unless `ANDROID_API` is specified
# 18 is the smallest level with OpenGL support
- # 21 is the smallest level for 64-bit platforms
+ # 21 is the smallest level for 64-bit platforms
default_android_api = 21 if self.is_64_bit else 18
- self.android_api = int(preset('ANDROID_API', default_android_api))
-
+ self.android_api = int(preset('ANDROID_API', default_android_api))
+
self.is_cygwin = self.os == 'cygwin'
self.is_yocto = self.os == 'yocto'
@@ -130,11 +130,11 @@ class Platform(object):
# 'OS_LINUX' variable
yield 'OS_{}'.format(self.os.upper())
- # yocto is linux
- if 'yocto' in self.os:
- yield 'LINUX'
- yield 'OS_LINUX'
-
+ # yocto is linux
+ if 'yocto' in self.os:
+ yield 'LINUX'
+ yield 'OS_LINUX'
+
if self.is_macos:
yield 'DARWIN'
yield 'OS_DARWIN'
@@ -542,10 +542,10 @@ class Build(object):
return self.build_type == 'fastdebug'
@property
- def is_size_optimized(self):
- return self.build_type == 'minsizerel'
-
- @property
+ def is_size_optimized(self):
+ return self.build_type == 'minsizerel'
+
+ @property
def is_coverage(self):
return self.build_type == 'coverage'
@@ -784,12 +784,12 @@ when (($USEMPROF == "yes") || ($USE_MPROF == "yes")) {
for variable in self.platform.os_variables:
emit(variable, 'yes')
- if self.platform.is_armv7:
- emit('ARM7_FLOAT_ABI', self.platform.armv7_float_abi)
-
- if self.platform.is_android:
+ if self.platform.is_armv7:
+ emit('ARM7_FLOAT_ABI', self.platform.armv7_float_abi)
+
+ if self.platform.is_android:
emit('ANDROID_API', str(self.platform.android_api))
-
+
if self.platform.is_posix:
self.print_nix_target_const()
if self.platform.is_linux:
@@ -962,11 +962,11 @@ class ToolchainOptions(object):
# default C++ standard is set here, some older toolchains might need to redefine it in ya.conf.json
self.cxx_std = self.params.get('cxx_std', 'c++20')
-
+
self._env = tc_json.get('env', {})
- self.android_ndk_version = self.params.get('android_ndk_version', None)
-
+ self.android_ndk_version = self.params.get('android_ndk_version', None)
+
logger.debug('c_compiler=%s', self.c_compiler)
logger.debug('cxx_compiler=%s', self.cxx_compiler)
@@ -1039,12 +1039,12 @@ class GnuToolchainOptions(ToolchainOptions):
if self.target.is_armv8:
return 'ubuntu-16'
- if self.target.is_armv7 and self.target.armv7_float_abi == 'hard':
+ if self.target.is_armv7 and self.target.armv7_float_abi == 'hard':
return 'ubuntu-16'
- if self.target.is_armv7 and self.target.armv7_float_abi == 'softfp':
- return 'ubuntu-18'
-
+ if self.target.is_armv7 and self.target.armv7_float_abi == 'softfp':
+ return 'ubuntu-18'
+
if self.target.is_powerpc:
return 'ubuntu-14'
@@ -1091,7 +1091,7 @@ class GnuToolchain(Toolchain):
sdk_native_version = 10.11 if not preset('EXPERIMENTAL_MACOS_M1_SUPPORT') else '11.1'
if target.is_macos:
return '$MACOS_SDK_RESOURCE_GLOBAL/MacOSX{}.sdk'.format(sdk_native_version)
- elif target.is_yocto:
+ elif target.is_yocto:
return '$YOCTO_SDK_RESOURCE_GLOBAL'
return '$OS_SDK_ROOT_RESOURCE_GLOBAL'
@@ -1160,8 +1160,8 @@ class GnuToolchain(Toolchain):
target_triple = select(default=None, selectors=[
(target.is_linux and target.is_x86_64, 'x86_64-linux-gnu'),
(target.is_linux and target.is_armv8, 'aarch64-linux-gnu'),
- (target.is_linux and target.is_armv7 and target.armv7_float_abi == 'hard', 'arm-linux-gnueabihf'),
- (target.is_linux and target.is_armv7 and target.armv7_float_abi == 'softfp', 'arm-linux-gnueabi'),
+ (target.is_linux and target.is_armv7 and target.armv7_float_abi == 'hard', 'arm-linux-gnueabihf'),
+ (target.is_linux and target.is_armv7 and target.armv7_float_abi == 'softfp', 'arm-linux-gnueabi'),
(target.is_linux and target.is_powerpc, 'powerpc64le-linux-gnu'),
(target.is_iossim and target.is_arm64, 'arm64-apple-ios{}-simulator'.format(ios_version_min)),
(target.is_apple and target.is_x86, 'i386-apple-darwin14'),
@@ -1169,18 +1169,18 @@ class GnuToolchain(Toolchain):
(target.is_apple and target.is_macos_arm64, 'arm64-apple-macos11'),
(target.is_apple and target.is_armv7, 'armv7-apple-darwin14'),
(target.is_apple and target.is_armv8, 'arm64-apple-darwin14'),
- (target.is_yocto and target.is_armv7, 'arm-poky-linux-gnueabi'),
- (target.is_android and target.is_x86, 'i686-linux-android'),
- (target.is_android and target.is_x86_64, 'x86_64-linux-android'),
- (target.is_android and target.is_armv7, 'armv7a-linux-androideabi'),
- (target.is_android and target.is_armv8, 'aarch64-linux-android'),
+ (target.is_yocto and target.is_armv7, 'arm-poky-linux-gnueabi'),
+ (target.is_android and target.is_x86, 'i686-linux-android'),
+ (target.is_android and target.is_x86_64, 'x86_64-linux-android'),
+ (target.is_android and target.is_armv7, 'armv7a-linux-androideabi'),
+ (target.is_android and target.is_armv8, 'aarch64-linux-android'),
])
- if target.is_android:
- # Android NDK allows specification of API level in target triple, e.g.:
- # armv7a-linux-androideabi16, aarch64-linux-android21
- target_triple += str(target.android_api)
-
+ if target.is_android:
+ # Android NDK allows specification of API level in target triple, e.g.:
+ # armv7a-linux-androideabi16, aarch64-linux-android21
+ target_triple += str(target.android_api)
+
if target_triple:
self.c_flags_platform.append('--target={}'.format(target_triple))
@@ -1188,12 +1188,12 @@ class GnuToolchain(Toolchain):
for root in list(self.tc.isystem):
self.c_flags_platform.extend(['-isystem', root])
- if target.is_android:
- self.c_flags_platform.extend(['-isystem', '{}/sources/cxx-stl/llvm-libc++abi/include'.format(self.tc.name_marker)])
-
- if target.is_cortex_a9:
- self.c_flags_platform.append('-mcpu=cortex-a9')
-
+ if target.is_android:
+ self.c_flags_platform.extend(['-isystem', '{}/sources/cxx-stl/llvm-libc++abi/include'.format(self.tc.name_marker)])
+
+ if target.is_cortex_a9:
+ self.c_flags_platform.append('-mcpu=cortex-a9')
+
if target.is_cortex_a35:
self.c_flags_platform.append('-mcpu=cortex-a35')
@@ -1207,15 +1207,15 @@ class GnuToolchain(Toolchain):
self.c_flags_platform.append('-mfpu=neon')
if (target.is_armv7 or target.is_armv8m) and build.is_size_optimized:
- # Enable ARM Thumb2 variable-length instruction encoding
- # to reduce code size
- self.c_flags_platform.append('-mthumb')
-
+ # Enable ARM Thumb2 variable-length instruction encoding
+ # to reduce code size
+ self.c_flags_platform.append('-mthumb')
+
if target.is_arm or target.is_powerpc:
- # On linux, ARM and PPC default to unsigned char
- # However, Arcadia requires char to be signed
- self.c_flags_platform.append('-fsigned-char')
-
+ # On linux, ARM and PPC default to unsigned char
+ # However, Arcadia requires char to be signed
+ self.c_flags_platform.append('-fsigned-char')
+
if self.tc.is_clang or self.tc.is_gcc and self.tc.version_at_least(8, 2):
target_flags = select(default=[], selectors=[
(target.is_linux and target.is_power8le, ['-mcpu=power8', '-mtune=power8', '-maltivec']),
@@ -1361,33 +1361,33 @@ class GnuCompiler(Compiler):
# Issue a warning if certain overload is hidden due to inheritance
'-Woverloaded-virtual',
]
-
+
# Disable some warnings which will fail compilation at the time
self.c_warnings += [
'-Wno-parentheses'
]
- self.c_defines = ['-DFAKEID=$CPP_FAKEID']
- if self.target.is_android:
- self.c_defines.append('-DANDROID_FAKEID=$ANDROID_FAKEID')
-
- self.c_defines.extend([
- '-DARCADIA_ROOT=${ARCADIA_ROOT}',
- '-DARCADIA_BUILD_ROOT=${ARCADIA_BUILD_ROOT}',
- ])
-
- self.c_defines.extend([
+ self.c_defines = ['-DFAKEID=$CPP_FAKEID']
+ if self.target.is_android:
+ self.c_defines.append('-DANDROID_FAKEID=$ANDROID_FAKEID')
+
+ self.c_defines.extend([
+ '-DARCADIA_ROOT=${ARCADIA_ROOT}',
+ '-DARCADIA_BUILD_ROOT=${ARCADIA_BUILD_ROOT}',
+ ])
+
+ self.c_defines.extend([
'-D_THREAD_SAFE', '-D_PTHREADS', '-D_REENTRANT', '-D_LIBCPP_ENABLE_CXX17_REMOVED_FEATURES',
'-D_LARGEFILE_SOURCE', '-D__STDC_CONSTANT_MACROS', '-D__STDC_FORMAT_MACROS',
- ])
+ ])
if not self.target.is_android:
# There is no usable _FILE_OFFSET_BITS=64 support in Androids until API 21. And it's incomplete until at least API 24.
# https://android.googlesource.com/platform/bionic/+/master/docs/32-bit-abi.md
- # Arcadia have API 16 for 32-bit Androids.
+ # Arcadia have API 16 for 32-bit Androids.
self.c_defines.append('-D_FILE_OFFSET_BITS=64')
- if self.target.is_linux or self.target.is_android or self.target.is_cygwin:
+ if self.target.is_linux or self.target.is_android or self.target.is_cygwin:
self.c_defines.append('-D_GNU_SOURCE')
if self.tc.is_clang and self.target.is_linux and self.target.is_x86_64:
@@ -1400,7 +1400,7 @@ class GnuCompiler(Compiler):
self.extra_compile_opts = []
- self.c_flags = ['$CL_DEBUG_INFO', '$CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__']
+ self.c_flags = ['$CL_DEBUG_INFO', '$CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__']
self.c_flags += self.tc.arch_opt + ['-pipe']
self.sfdl_flags = ['-E', '-C', '-x', 'c++']
@@ -1448,11 +1448,11 @@ class GnuCompiler(Compiler):
self.c_foptions.append('-fno-delete-null-pointer-checks')
self.c_foptions.append('-fabi-version=8')
- # Split all functions and data into separate sections for DCE and ICF linker passes
- # NOTE: iOS build uses -fembed-bitcode which conflicts with -ffunction-sections (only relevant for ELF targets)
- if not self.target.is_ios:
- self.c_foptions.extend(['-ffunction-sections', '-fdata-sections'])
-
+ # Split all functions and data into separate sections for DCE and ICF linker passes
+ # NOTE: iOS build uses -fembed-bitcode which conflicts with -ffunction-sections (only relevant for ELF targets)
+ if not self.target.is_ios:
+ self.c_foptions.extend(['-ffunction-sections', '-fdata-sections'])
+
def configure_build_type(self):
if self.build.is_valgrind:
self.c_defines.append('-DWITH_VALGRIND=1')
@@ -1465,18 +1465,18 @@ class GnuCompiler(Compiler):
if self.build.is_release:
self.c_flags.append('$OPTIMIZE')
- if self.build.is_size_optimized:
- # -Oz is clang's more size-aggressive version of -Os
- # For ARM specifically, clang -Oz is on par with gcc -Os:
- # https://github.com/android/ndk/issues/133#issuecomment-365763507
- if self.tc.is_clang:
- self.optimize = '-Oz'
- else:
- self.optimize = '-Os'
-
- # Generate sections with address significance tables for ICF linker pass
- if self.tc.is_clang:
- self.c_foptions.extend(['-faddrsig'])
+ if self.build.is_size_optimized:
+ # -Oz is clang's more size-aggressive version of -Os
+ # For ARM specifically, clang -Oz is on par with gcc -Os:
+ # https://github.com/android/ndk/issues/133#issuecomment-365763507
+ if self.tc.is_clang:
+ self.optimize = '-Oz'
+ else:
+ self.optimize = '-Os'
+
+ # Generate sections with address significance tables for ICF linker pass
+ if self.tc.is_clang:
+ self.c_foptions.extend(['-faddrsig'])
else:
self.optimize = '-O3'
@@ -1505,19 +1505,19 @@ class GnuCompiler(Compiler):
append('C_WARNING_OPTS', self.c_warnings)
append('CXX_WARNING_OPTS', self.cxx_warnings)
- # PIE is only valid for executables, while PIC implies a shared library
- # `-pie` with a shared library is either ignored or fails to link
+ # PIE is only valid for executables, while PIC implies a shared library
+ # `-pie` with a shared library is either ignored or fails to link
emit_big('''
- when ($PIC == "yes") {
- CFLAGS+=-fPIC
- LDFLAGS+=-fPIC
+ when ($PIC == "yes") {
+ CFLAGS+=-fPIC
+ LDFLAGS+=-fPIC
}
- elsewhen ($PIE == "yes") {
- CFLAGS+=-fPIE
- LDFLAGS+=-fPIE -pie
+ elsewhen ($PIE == "yes") {
+ CFLAGS+=-fPIE
+ LDFLAGS+=-fPIE -pie
}''')
- append('CFLAGS', self.c_flags, '$DEBUG_INFO_FLAGS', self.c_foptions, '$C_WARNING_OPTS', '$GCC_PREPROCESSOR_OPTS', '$USER_CFLAGS', '$USER_CFLAGS_GLOBAL')
+ append('CFLAGS', self.c_flags, '$DEBUG_INFO_FLAGS', self.c_foptions, '$C_WARNING_OPTS', '$GCC_PREPROCESSOR_OPTS', '$USER_CFLAGS', '$USER_CFLAGS_GLOBAL')
append('CXXFLAGS', '$CFLAGS', '-std=' + self.tc.cxx_std, '$CXX_WARNING_OPTS', '$USER_CXXFLAGS', '$USER_CXXFLAGS_GLOBAL')
append('CONLYFLAGS', '$USER_CONLYFLAGS', '$USER_CONLYFLAGS_GLOBAL')
emit('CXX_COMPILER_UNQUOTED', self.tc.cxx_compiler)
@@ -1548,26 +1548,26 @@ class GnuCompiler(Compiler):
}''')
c_builtins = [
- "-Wno-builtin-macro-redefined",
- '-D__DATE__=\\""Sep 31 2019\\""',
- '-D__TIME__=\\"00:00:00\\"',
+ "-Wno-builtin-macro-redefined",
+ '-D__DATE__=\\""Sep 31 2019\\""',
+ '-D__TIME__=\\"00:00:00\\"',
]
- compiler_supports_macro_prefix_map = (
- self.tc.is_clang and self.tc.version_at_least(10) or
- self.tc.is_gcc and self.tc.version_at_least(8)
- )
- if compiler_supports_macro_prefix_map:
- c_builtins += [
- # XXX does not support non-normalized paths
- "-fmacro-prefix-map=${ARCADIA_BUILD_ROOT}/=",
- "-fmacro-prefix-map=${ARCADIA_ROOT}/=",
- "-fmacro-prefix-map=$(TOOL_ROOT)/=",
- ]
- else:
- c_builtins += [
- # XXX this macro substitution breaks __FILE__ in included sources
- '-D__FILE__=\\""${input;qe;rootrel:SRC}\\""',
- ]
+ compiler_supports_macro_prefix_map = (
+ self.tc.is_clang and self.tc.version_at_least(10) or
+ self.tc.is_gcc and self.tc.version_at_least(8)
+ )
+ if compiler_supports_macro_prefix_map:
+ c_builtins += [
+ # XXX does not support non-normalized paths
+ "-fmacro-prefix-map=${ARCADIA_BUILD_ROOT}/=",
+ "-fmacro-prefix-map=${ARCADIA_ROOT}/=",
+ "-fmacro-prefix-map=$(TOOL_ROOT)/=",
+ ]
+ else:
+ c_builtins += [
+ # XXX this macro substitution breaks __FILE__ in included sources
+ '-D__FILE__=\\""${input;qe;rootrel:SRC}\\""',
+ ]
c_debug_map = [
# XXX does not support non-normalized paths
"-fdebug-prefix-map=${ARCADIA_BUILD_ROOT}=/-B",
@@ -1591,17 +1591,17 @@ class GnuCompiler(Compiler):
"--replace=$(TOOL_ROOT)=/-T"
]
emit_big('''
- when ($FORCE_CONSISTENT_DEBUG == "yes") {{
+ when ($FORCE_CONSISTENT_DEBUG == "yes") {{
+ when ($CLANG == "yes") {{
+ CL_DEBUG_INFO={c_debug_cl}
+ }}
+ otherwise {{
+ CL_DEBUG_INFO={c_debug}
+ }}
+ YASM_DEBUG_INFO={yasm_debug}
+ }}
+ elsewhen ($CONSISTENT_DEBUG == "yes") {{
when ($CLANG == "yes") {{
- CL_DEBUG_INFO={c_debug_cl}
- }}
- otherwise {{
- CL_DEBUG_INFO={c_debug}
- }}
- YASM_DEBUG_INFO={yasm_debug}
- }}
- elsewhen ($CONSISTENT_DEBUG == "yes") {{
- when ($CLANG == "yes") {{
CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug_cl}
}}
otherwise {{
@@ -1619,10 +1619,10 @@ class GnuCompiler(Compiler):
YASM_DEBUG_INFO_DISABLE_CACHE__NO_UID__={yasm_debug_light}
}}
- when ($FORCE_CONSISTENT_BUILD == "yes") {{
- CL_MACRO_INFO={macro}
- }}
- elsewhen ($CONSISTENT_BUILD == "yes") {{
+ when ($FORCE_CONSISTENT_BUILD == "yes") {{
+ CL_MACRO_INFO={macro}
+ }}
+ elsewhen ($CONSISTENT_BUILD == "yes") {{
CL_MACRO_INFO_DISABLE_CACHE__NO_UID__={macro}
}}
'''.format(c_debug=' '.join(c_debug_map),
@@ -1652,16 +1652,16 @@ class GnuCompiler(Compiler):
elif is_positive('DUMP_COMPILER_DEPS_FAST'):
emit('DUMP_DEPS', '-E', '-M', '-MF', '${output;noauto;suf=${OBJ_SUF}.o.d:SRC}')
- compiler_time_trace_requested = is_positive('TIME_TRACE') or is_positive('COMPILER_TIME_TRACE')
- compiler_supports_time_trace = self.tc.is_clang and self.tc.version_at_least(9)
- if compiler_time_trace_requested and compiler_supports_time_trace:
- compiler_time_trace_granularity = preset('TIME_TRACE_GRANULARITY', '500')
- emit('COMPILER_TIME_TRACE_FLAGS', '-ftime-trace -ftime-trace-granularity=' + compiler_time_trace_granularity)
- emit('COMPILER_TIME_TRACE_POSTPROCESS', '${YMAKE_PYTHON}', '${input:"build/scripts/find_time_trace.py"}', '$_COMPILE_OUTPUTS', '$_COMPILE_TIME_TRACE_OUTPUTS')
- else:
- emit('COMPILER_TIME_TRACE_FLAGS')
- emit('COMPILER_TIME_TRACE_POSTPROCESS')
-
+ compiler_time_trace_requested = is_positive('TIME_TRACE') or is_positive('COMPILER_TIME_TRACE')
+ compiler_supports_time_trace = self.tc.is_clang and self.tc.version_at_least(9)
+ if compiler_time_trace_requested and compiler_supports_time_trace:
+ compiler_time_trace_granularity = preset('TIME_TRACE_GRANULARITY', '500')
+ emit('COMPILER_TIME_TRACE_FLAGS', '-ftime-trace -ftime-trace-granularity=' + compiler_time_trace_granularity)
+ emit('COMPILER_TIME_TRACE_POSTPROCESS', '${YMAKE_PYTHON}', '${input:"build/scripts/find_time_trace.py"}', '$_COMPILE_OUTPUTS', '$_COMPILE_TIME_TRACE_OUTPUTS')
+ else:
+ emit('COMPILER_TIME_TRACE_FLAGS')
+ emit('COMPILER_TIME_TRACE_POSTPROCESS')
+
append('EXTRA_OUTPUT')
style = ['${requirements;hide:CC_REQUIREMENTS} ${hide;kv:"p CC"} ${hide;kv:"pc green"}']
@@ -1674,14 +1674,14 @@ class GnuCompiler(Compiler):
'$CXXFLAGS',
'$CL_MACRO_INFO',
'$CL_MACRO_INFO_DISABLE_CACHE__NO_UID__',
- '$COMPILER_TIME_TRACE_FLAGS',
+ '$COMPILER_TIME_TRACE_FLAGS',
'$EXTRA_OUTPUT',
'$SRCFLAGS',
'$_LANG_CFLAGS_VALUE',
'${input:SRC}',
'$TOOLCHAIN_ENV',
'$YNDEXER_OUTPUT',
- '&& $COMPILER_TIME_TRACE_POSTPROCESS',
+ '&& $COMPILER_TIME_TRACE_POSTPROCESS',
] + style
c_args = [
@@ -1694,13 +1694,13 @@ class GnuCompiler(Compiler):
'$CL_MACRO_INFO',
'$CL_MACRO_INFO_DISABLE_CACHE__NO_UID__',
'$CONLYFLAGS',
- '$COMPILER_TIME_TRACE_FLAGS',
+ '$COMPILER_TIME_TRACE_FLAGS',
'$EXTRA_OUTPUT',
'$SRCFLAGS',
'${input:SRC}',
'$TOOLCHAIN_ENV',
'$YNDEXER_OUTPUT',
- '&& $COMPILER_TIME_TRACE_POSTPROCESS',
+ '&& $COMPILER_TIME_TRACE_POSTPROCESS',
] + style
ignore_c_args_no_deps = [
@@ -1709,11 +1709,11 @@ class GnuCompiler(Compiler):
'$CLANG_TIDY_ARGS',
'$YNDEXER_ARGS',
'$YNDEXER_OUTPUT',
- '$COMPILER_TIME_TRACE_FLAGS',
+ '$COMPILER_TIME_TRACE_FLAGS',
'$EXTRA_OUTPUT',
'$CL_MACRO_INFO',
- '$CL_MACRO_INFO_DISABLE_CACHE__NO_UID__',
- '&& $COMPILER_TIME_TRACE_POSTPROCESS',
+ '$CL_MACRO_INFO_DISABLE_CACHE__NO_UID__',
+ '&& $COMPILER_TIME_TRACE_POSTPROCESS',
]
c_args_nodeps = [c if c != '$GCC_COMPILE_FLAGS' else '$EXTRA_C_FLAGS -c -o ${OUTFILE} ${SRC} ${pre=-I:INC}' for c in c_args if c not in ignore_c_args_no_deps]
@@ -1754,34 +1754,34 @@ class Linker(object):
"""
self.tc = tc
self.build = build
- self.type = self._get_default_linker_type()
-
- def _get_default_linker_type(self):
- if not self.tc.is_from_arcadia:
- # External (e.g. system) toolchain: disable linker selection logic
- return None
-
- if self.build.target.is_android:
- # Android toolchain is NDK, LLD works on all supported platforms
- return Linker.LLD
-
- elif self.build.target.is_linux:
+ self.type = self._get_default_linker_type()
+
+ def _get_default_linker_type(self):
+ if not self.tc.is_from_arcadia:
+ # External (e.g. system) toolchain: disable linker selection logic
+ return None
+
+ if self.build.target.is_android:
+ # Android toolchain is NDK, LLD works on all supported platforms
+ return Linker.LLD
+
+ elif self.build.target.is_linux:
# DEVTOOLS-6782: LLD8 fails to link LTO builds with in-memory ELF objects larger than 4 GiB
blacklist_lld = is_positive('CLANG7') and is_positive('USE_LTO') and not is_positive('MUSL')
if self.tc.is_clang and not blacklist_lld:
return Linker.LLD
else:
- # GCC et al.
+ # GCC et al.
if self.tc.is_gcc and is_positive('MUSL'):
# See MUSL_BFD comment below
return Linker.BFD
- return Linker.GOLD
+ return Linker.GOLD
+
+ # There is no linker choice on Darwin (ld64) or Windows (link.exe)
+ return None
- # There is no linker choice on Darwin (ld64) or Windows (link.exe)
- return None
-
def print_linker(self):
self._print_linker_selector()
@@ -1838,35 +1838,35 @@ class LD(Linker):
self.ld_flags = []
- # Save linker's stdout to an additional .txt output file
- # e.g. LLD writes `--print-gc-sections` or `--print-icf-sections` to stdout
- self.save_linker_output = False
-
- # Enable section-level DCE (dead code elimination):
- # remove whole unused code and data sections
- # (needs `-ffunction-sections` and `-fdata-sections` to be useful)
- #
- # NOTE: CGO linker doesn't seem to support DCE, but shares common LDFLAGS
- if target.is_macos:
- self.ld_dce_flag = '-Wl,-dead_strip'
- elif target.is_linux or target.is_android:
- self.ld_dce_flag = '-Wl,--gc-sections'
- if preset('LINKER_DCE_PRINT_SECTIONS'):
- self.save_linker_output = True
- self.ld_dce_flag += ' -Wl,--print-gc-sections'
- else:
- self.ld_dce_flag = ''
-
- if self.type == Linker.LLD:
- # Enable ICF (identical code folding pass) in safe mode
- # https://research.google/pubs/pub36912/
- self.ld_icf_flag = '-Wl,-icf=safe'
- if preset('LINKER_ICF_PRINT_SECTIONS'):
- self.save_linker_output = True
- self.ld_icf_flag += ' -Wl,--print-icf-sections'
- else:
- self.ld_icf_flag = ''
-
+ # Save linker's stdout to an additional .txt output file
+ # e.g. LLD writes `--print-gc-sections` or `--print-icf-sections` to stdout
+ self.save_linker_output = False
+
+ # Enable section-level DCE (dead code elimination):
+ # remove whole unused code and data sections
+ # (needs `-ffunction-sections` and `-fdata-sections` to be useful)
+ #
+ # NOTE: CGO linker doesn't seem to support DCE, but shares common LDFLAGS
+ if target.is_macos:
+ self.ld_dce_flag = '-Wl,-dead_strip'
+ elif target.is_linux or target.is_android:
+ self.ld_dce_flag = '-Wl,--gc-sections'
+ if preset('LINKER_DCE_PRINT_SECTIONS'):
+ self.save_linker_output = True
+ self.ld_dce_flag += ' -Wl,--print-gc-sections'
+ else:
+ self.ld_dce_flag = ''
+
+ if self.type == Linker.LLD:
+ # Enable ICF (identical code folding pass) in safe mode
+ # https://research.google/pubs/pub36912/
+ self.ld_icf_flag = '-Wl,-icf=safe'
+ if preset('LINKER_ICF_PRINT_SECTIONS'):
+ self.save_linker_output = True
+ self.ld_icf_flag += ' -Wl,--print-icf-sections'
+ else:
+ self.ld_icf_flag = ''
+
if self.musl.value:
self.ld_flags.extend(['-Wl,--no-as-needed'])
if self.tc.is_gcc:
@@ -1880,19 +1880,19 @@ class LD(Linker):
self.ld_flags.extend(('-Wl,-Bstatic', '-latomic', '-Wl,-Bdynamic'))
elif target.is_android:
self.ld_flags.extend(['-ldl', '-Wl,--no-as-needed'])
- if self.type == Linker.LLD and target.android_api < 29:
- # https://github.com/android/ndk/issues/1196
- self.ld_flags.append('-Wl,--no-rosegment')
+ if self.type == Linker.LLD and target.android_api < 29:
+ # https://github.com/android/ndk/issues/1196
+ self.ld_flags.append('-Wl,--no-rosegment')
elif target.is_macos:
self.ld_flags.append('-Wl,-no_deduplicate')
if not self.tc.is_clang:
self.ld_flags.append('-Wl,-no_compact_unwind')
self.thread_library = select([
- (target.is_linux or target.is_macos, '-lpthread'),
+ (target.is_linux or target.is_macos, '-lpthread'),
])
- self.ld_export_dynamic_flag = None
+ self.ld_export_dynamic_flag = None
self.start_group = None
self.end_group = None
self.whole_archive = None
@@ -1904,7 +1904,7 @@ class LD(Linker):
self.libresolv = '-lresolv' if target.is_linux or target.is_macos or target.is_android else None
if target.is_linux or target.is_android:
- self.ld_export_dynamic_flag = '-rdynamic'
+ self.ld_export_dynamic_flag = '-rdynamic'
self.use_stdlib = '-nodefaultlibs'
if target.is_linux or target.is_android or target.is_cygwin or target.is_none:
@@ -1947,22 +1947,22 @@ class LD(Linker):
if target.is_armv7 and self.type != Linker.LLD:
self.sys_lib.append('-Wl,--fix-cortex-a8')
- # NDK r23 onwards has stopped using libgcc:
- # - https://github.com/android/ndk/wiki/Changelog-r23#changes
- # - https://github.com/android/ndk/issues/1230
- # LLVM's libunwind is now used instead of libgcc for all architectures rather than just 32-bit Arm.
- # - https://github.com/android/ndk/issues/1231
- # LLVM's libclang_rt.builtins is now used instead of libgcc.
- if self.tc.android_ndk_version >= 23:
- # Use toolchain defaults to link with libunwind/clang_rt.builtins
- self.use_stdlib = '-nostdlib++'
- else:
- # Preserve old behaviour: specify runtime libs manually
- self.use_stdlib = '-nodefaultlibs'
- if target.is_armv7:
- self.sys_lib.append('-lunwind')
- self.sys_lib.append('-lgcc')
-
+ # NDK r23 onwards has stopped using libgcc:
+ # - https://github.com/android/ndk/wiki/Changelog-r23#changes
+ # - https://github.com/android/ndk/issues/1230
+ # LLVM's libunwind is now used instead of libgcc for all architectures rather than just 32-bit Arm.
+ # - https://github.com/android/ndk/issues/1231
+ # LLVM's libclang_rt.builtins is now used instead of libgcc.
+ if self.tc.android_ndk_version >= 23:
+ # Use toolchain defaults to link with libunwind/clang_rt.builtins
+ self.use_stdlib = '-nostdlib++'
+ else:
+ # Preserve old behaviour: specify runtime libs manually
+ self.use_stdlib = '-nodefaultlibs'
+ if target.is_armv7:
+ self.sys_lib.append('-lunwind')
+ self.sys_lib.append('-lgcc')
+
if self.tc.is_clang and not self.tc.version_at_least(4, 0) and target.is_linux_x86_64:
self.sys_lib.append('-L/usr/lib/x86_64-linux-gnu')
@@ -1981,12 +1981,12 @@ class LD(Linker):
emit('LD_STRIP_FLAG', self.ld_stripflag)
emit('STRIP_FLAG')
- emit('LD_DCE_FLAG', self.ld_dce_flag)
- emit('DCE_FLAG')
-
- emit('LD_ICF_FLAG', self.ld_icf_flag)
- emit('ICF_FLAG')
-
+ emit('LD_DCE_FLAG', self.ld_dce_flag)
+ emit('DCE_FLAG')
+
+ emit('LD_ICF_FLAG', self.ld_icf_flag)
+ emit('ICF_FLAG')
+
emit('C_LIBRARY_PATH')
emit('C_SYSTEM_LIBRARIES_INTERCEPT')
if self.musl.value:
@@ -2011,35 +2011,35 @@ class LD(Linker):
emit('DWARF_TOOL', dwarf_tool)
emit('OBJADDE')
- emit('LD_EXPORT_ALL_DYNAMIC_SYMBOLS_FLAG', self.ld_export_dynamic_flag)
+ emit('LD_EXPORT_ALL_DYNAMIC_SYMBOLS_FLAG', self.ld_export_dynamic_flag)
emit_big('''
- NO_EXPORT_DYNAMIC_SYMBOLS=
- EXPORTS_VALUE=$LD_EXPORT_ALL_DYNAMIC_SYMBOLS_FLAG
+ NO_EXPORT_DYNAMIC_SYMBOLS=
+ EXPORTS_VALUE=$LD_EXPORT_ALL_DYNAMIC_SYMBOLS_FLAG
when ($EXPORTS_FILE) {
- EXPORTS_VALUE=$LD_EXPORT_ALL_DYNAMIC_SYMBOLS_FLAG -Wl,--version-script=${input:EXPORTS_FILE}
- }
- when ($NO_EXPORT_DYNAMIC_SYMBOLS == "yes") {
- EXPORTS_VALUE=
+ EXPORTS_VALUE=$LD_EXPORT_ALL_DYNAMIC_SYMBOLS_FLAG -Wl,--version-script=${input:EXPORTS_FILE}
+ }
+ when ($NO_EXPORT_DYNAMIC_SYMBOLS == "yes") {
+ EXPORTS_VALUE=
}''')
emit('LINKER_SCRIPT_VALUE', '${ext=.ld;pre=-T:SRCS_GLOBAL}')
- linker_time_trace_requested = is_positive('TIME_TRACE') or is_positive('LINKER_TIME_TRACE')
- linker_supports_time_trace = self.type == Linker.LLD # XXX: Should really check the linker version if we had one
- if linker_time_trace_requested and linker_supports_time_trace:
- linker_time_trace_granularity = preset('TIME_TRACE_GRANULARITY', '500')
- emit('LINKER_TIME_TRACE_FLAG', ' '.join([
- '-Wl,--time-trace',
- '-Wl,--time-trace-granularity=' + linker_time_trace_granularity,
- '-Wl,--time-trace-file=${output;rootrel;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.time_trace.json:REALPRJNAME}',
- ]))
- else:
- emit('LINKER_TIME_TRACE_FLAG')
-
+ linker_time_trace_requested = is_positive('TIME_TRACE') or is_positive('LINKER_TIME_TRACE')
+ linker_supports_time_trace = self.type == Linker.LLD # XXX: Should really check the linker version if we had one
+ if linker_time_trace_requested and linker_supports_time_trace:
+ linker_time_trace_granularity = preset('TIME_TRACE_GRANULARITY', '500')
+ emit('LINKER_TIME_TRACE_FLAG', ' '.join([
+ '-Wl,--time-trace',
+ '-Wl,--time-trace-granularity=' + linker_time_trace_granularity,
+ '-Wl,--time-trace-file=${output;rootrel;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.time_trace.json:REALPRJNAME}',
+ ]))
+ else:
+ emit('LINKER_TIME_TRACE_FLAG')
+
exe_flags = [
'$C_FLAGS_PLATFORM', '$BEFORE_PEERS', self.start_group, '${rootrel:PEERS}', self.end_group, '$AFTER_PEERS',
'$EXPORTS_VALUE $LINKER_SCRIPT_VALUE $LDFLAGS $LDFLAGS_GLOBAL $OBJADDE $OBJADDE_LIB',
- '$C_LIBRARY_PATH $C_SYSTEM_LIBRARIES_INTERCEPT $C_SYSTEM_LIBRARIES $STRIP_FLAG $DCE_FLAG $ICF_FLAG $LINKER_TIME_TRACE_FLAG']
+ '$C_LIBRARY_PATH $C_SYSTEM_LIBRARIES_INTERCEPT $C_SYSTEM_LIBRARIES $STRIP_FLAG $DCE_FLAG $ICF_FLAG $LINKER_TIME_TRACE_FLAG']
arch_flag = '--arch={arch}'.format(arch=self.target.os_compat)
soname_flag = '-Wl,{option},${{_SONAME}}'.format(option=self.soname_option)
@@ -2076,7 +2076,7 @@ class LD(Linker):
emit('REAL_LINK_EXE_CMDLINE',
'$YMAKE_PYTHON ${input:"build/scripts/link_exe.py"}',
'--source-root $ARCADIA_ROOT',
- '--linker-output ${output;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.linker.txt:REALPRJNAME}' if self.save_linker_output else '',
+ '--linker-output ${output;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.linker.txt:REALPRJNAME}' if self.save_linker_output else '',
'${pre=--whole-archive-peers :WHOLE_ARCHIVE_PEERS}',
'${pre=--whole-archive-libs :_WHOLE_ARCHIVE_LIBS_VALUE_GLOBAL}',
arch_flag,
@@ -2094,7 +2094,7 @@ class LD(Linker):
emit('REAL_LINK_EXEC_DYN_LIB_CMDLINE',
'$YMAKE_PYTHON ${input:"build/scripts/link_dyn_lib.py"}',
'--target $TARGET',
- '--linker-output ${output;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.linker.txt:REALPRJNAME}' if self.save_linker_output else '',
+ '--linker-output ${output;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.linker.txt:REALPRJNAME}' if self.save_linker_output else '',
'${pre=--whole-archive-peers :WHOLE_ARCHIVE_PEERS}',
'${pre=--whole-archive-libs :_WHOLE_ARCHIVE_LIBS_VALUE_GLOBAL}',
arch_flag,
@@ -2141,7 +2141,7 @@ class LD(Linker):
emit('LINK_DYN_LIB', "$REAL_LINK_EXE")
else:
emit('LINK_DYN_LIB', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_LINK_DYN_LIB && $DWARF_COMMAND && $LINK_ADDITIONAL_SECTIONS_COMMAND')
- emit('LINK_EXEC_DYN_LIB', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_LINK_EXEC_DYN_LIB && $DWARF_COMMAND && $LINK_ADDITIONAL_SECTIONS_COMMAND')
+ emit('LINK_EXEC_DYN_LIB', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_LINK_EXEC_DYN_LIB && $DWARF_COMMAND && $LINK_ADDITIONAL_SECTIONS_COMMAND')
emit('SWIG_DLL_JAR_CMD', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_SWIG_DLL_JAR_CMD && $DWARF_COMMAND')
tail_link_lib = '$AUTO_INPUT ${requirements;hide:LIB_REQUIREMENTS} ${kv;hide:"p AR"} $TOOLCHAIN_ENV ${kv;hide:"pc light-red"} ${kv;hide:"show_out"}'
@@ -2754,12 +2754,12 @@ class MSVCLinker(MSVC, Linker):
emit('LINK_WRAPPER')
emit('LINK_WRAPPER_DYNLIB', '${YMAKE_PYTHON}', '${input:"build/scripts/link_dyn_lib.py"}', '--arch', 'WINDOWS', '--target', '$TARGET')
- emit_big('''
- EXPORTS_VALUE=
- when ($EXPORTS_FILE) {
- LINK_IMPLIB_VALUE=$LINK_IMPLIB
- EXPORTS_VALUE=/DEF:${input:EXPORTS_FILE}
- }''')
+ emit_big('''
+ EXPORTS_VALUE=
+ when ($EXPORTS_FILE) {
+ LINK_IMPLIB_VALUE=$LINK_IMPLIB
+ EXPORTS_VALUE=/DEF:${input:EXPORTS_FILE}
+ }''')
emit("GENERATE_MF_CMD", '$YMAKE_PYTHON ${input:"build/scripts/generate_mf.py"}',
'--build-root $ARCADIA_BUILD_ROOT --module-name $REALPRJNAME -o ${output;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.mf:REALPRJNAME}',
diff --git a/contrib/README.md b/contrib/README.md
index 9ca4ceb5a6..44863a0baf 100644
--- a/contrib/README.md
+++ b/contrib/README.md
@@ -25,14 +25,14 @@
Нет, `contrib/` — место для внешнего кода, которым мы (компания Яндекс) не владеем.
В случае внутренней разработки, алгоритм следующий:
-1. У библиотеки есть команда разработки. В таком случае (при наличии пользователей в Аркадии) разработка библиотеки должна переехать в Аркадию.
- Если это невозможно, команда должна обосновать, почему такой переезд невозможен, и наладить регулярную синхронизацию в Аркадию кода библиотеки
- (также можно выполнять синхронизацию кода в Аркадию на период переезда). Владельцами кода библиотеки в Аркадии становятся разработчики библиотеки.
-2. У библиотеки нет команды разработки. В таком случае автор становится мейнтейнером, либо находит мейнтейнера среди прочих пользователей библиотеки.
- Библиотеку следует положить в место для общеупотребимых библиотек (`library/`, `library/python/`) или встроить в проект-пользователь в зависимости от того,
- представляет ли она интерес широкому кругу разработчиков.
-
-Из этого правила есть де-факто исключения для библиотек, которые были помещены в `contrib/` до его введения. Впоследствии они должны быть исключены из contrib.
+1. У библиотеки есть команда разработки. В таком случае (при наличии пользователей в Аркадии) разработка библиотеки должна переехать в Аркадию.
+ Если это невозможно, команда должна обосновать, почему такой переезд невозможен, и наладить регулярную синхронизацию в Аркадию кода библиотеки
+ (также можно выполнять синхронизацию кода в Аркадию на период переезда). Владельцами кода библиотеки в Аркадии становятся разработчики библиотеки.
+2. У библиотеки нет команды разработки. В таком случае автор становится мейнтейнером, либо находит мейнтейнера среди прочих пользователей библиотеки.
+ Библиотеку следует положить в место для общеупотребимых библиотек (`library/`, `library/python/`) или встроить в проект-пользователь в зависимости от того,
+ представляет ли она интерес широкому кругу разработчиков.
+
+Из этого правила есть де-факто исключения для библиотек, которые были помещены в `contrib/` до его введения. Впоследствии они должны быть исключены из contrib.
Список таких библиотек приведён в тикете: [CONTRIB-396](https://st.yandex-team.ru/CONTRIB-396)
## Обновление библиотеки в Contrib
diff --git a/contrib/libs/cctz/tzdata/factory.cpp b/contrib/libs/cctz/tzdata/factory.cpp
index f3d244a379..5a4b4a27b6 100644
--- a/contrib/libs/cctz/tzdata/factory.cpp
+++ b/contrib/libs/cctz/tzdata/factory.cpp
@@ -4,7 +4,7 @@
#include <util/generic/string.h>
#include <util/stream/str.h>
-#include <util/string/builder.h>
+#include <util/string/builder.h>
namespace cctz_extension {
namespace {
@@ -21,7 +21,7 @@ namespace cctz_extension {
static std::unique_ptr<cctz::ZoneInfoSource> LoadZone(const std::string& zoneName) {
TString resourceName = TStringBuilder() << "/cctz/tzdata/"sv << zoneName;
TString tzData;
- if (!NResource::FindExact(resourceName, &tzData)) {
+ if (!NResource::FindExact(resourceName, &tzData)) {
return nullptr;
}
return std::unique_ptr<cctz::ZoneInfoSource>(new TZoneInfoSource(std::move(tzData)));
diff --git a/contrib/libs/cctz/tzdata/update_tzdata.py b/contrib/libs/cctz/tzdata/update_tzdata.py
index 40ae7578ad..9c3cd07352 100755
--- a/contrib/libs/cctz/tzdata/update_tzdata.py
+++ b/contrib/libs/cctz/tzdata/update_tzdata.py
@@ -37,11 +37,11 @@ def create_cmakelists(zoneinfo_dir):
with open(os.path.join(generated_dir, tz_hash), 'w') as f:
f.write(tz_content)
- yamake_template = (
- 'RESOURCE(\n'
- '{}\n'
- ')'
- )
+ yamake_template = (
+ 'RESOURCE(\n'
+ '{}\n'
+ ')'
+ )
resources = '\n'.join(' generated/{} /cctz/tzdata/{}'.format(tz_hash, tz_name) for tz_name, tz_hash in sorted(tz_to_hash.iteritems()))
all_hashes = set(tz_to_hash.values())
@@ -51,7 +51,7 @@ def create_cmakelists(zoneinfo_dir):
subprocess.check_call(['svn', cmd, '--force', fn])
with open('ya.make.resources', 'w') as f:
- print >>f, yamake_template.format(resources)
+ print >>f, yamake_template.format(resources)
def get_latest_iana_version():
index_html = urllib2.urlopen('http://www.iana.org/time-zones').read()
diff --git a/contrib/libs/curl/lib/curl_config.h b/contrib/libs/curl/lib/curl_config.h
index f1304e4bf2..e58dec7079 100644
--- a/contrib/libs/curl/lib/curl_config.h
+++ b/contrib/libs/curl/lib/curl_config.h
@@ -25,7 +25,7 @@
// Do not misrepresent host on Android and iOS.
#undef OS
#define OS "arcadia"
-
+
// c-ares resolver is known to be buggy.
//
// There is no way to configure it properly without a JVM on Android,
@@ -39,7 +39,7 @@
//
//
// On Linux it caches /etc/resolv.conf contents and does not invalidate it properly
-
+
#if defined(ARCADIA_CURL_DNS_RESOLVER_ARES)
#define USE_ARES
#elif defined(ARCADIA_CURL_DNS_RESOLVER_MULTITHREADED)
@@ -64,4 +64,4 @@
#endif
#else
#error "No dns resolver is specified or resolver specification is wrong"
-#endif
+#endif
diff --git a/contrib/libs/curl/ya.make b/contrib/libs/curl/ya.make
index 27679394bb..00027df424 100644
--- a/contrib/libs/curl/ya.make
+++ b/contrib/libs/curl/ya.make
@@ -33,13 +33,13 @@ ADDINCL(
)
IF (NOT OS_WINDOWS)
- PEERDIR(
+ PEERDIR(
contrib/libs/nghttp2
- )
-ENDIF()
-
+ )
+ENDIF()
+
NO_COMPILER_WARNINGS()
-
+
NO_RUNTIME()
IF (MAPSMOBI_BUILD_TARGET)
@@ -47,8 +47,8 @@ IF (MAPSMOBI_BUILD_TARGET)
CFLAGS(
-DMAPSMOBI_BUILD
)
-ENDIF()
-
+ENDIF()
+
DEFAULT(ARCADIA_CURL_DNS_RESOLVER ARES)
CFLAGS(
diff --git a/contrib/libs/cxxsupp/builtins/ya.make b/contrib/libs/cxxsupp/builtins/ya.make
index 6e988c13e3..d2c319c927 100644
--- a/contrib/libs/cxxsupp/builtins/ya.make
+++ b/contrib/libs/cxxsupp/builtins/ya.make
@@ -116,11 +116,11 @@ IF (OS_DARWIN OR OS_IOS)
)
ENDIF()
-IF (ARCH_ARM)
- SRCS(
- clear_cache.c
- multc3.c
- )
-ENDIF()
-
+IF (ARCH_ARM)
+ SRCS(
+ clear_cache.c
+ multc3.c
+ )
+ENDIF()
+
END()
diff --git a/contrib/libs/cxxsupp/libcxx/glibcxx_eh_cxx17.cpp b/contrib/libs/cxxsupp/libcxx/glibcxx_eh_cxx17.cpp
index cc2bd0d223..5e5ad083ba 100644
--- a/contrib/libs/cxxsupp/libcxx/glibcxx_eh_cxx17.cpp
+++ b/contrib/libs/cxxsupp/libcxx/glibcxx_eh_cxx17.cpp
@@ -1,17 +1,17 @@
-#include <cxxabi.h>
-
-/**
- * libc++ expects std::uncaught_exceptions() to be provided by C++ runtime library.
- *
- * GCC versions prior to GCC 6 did not provide this function yet, but it can be
- * implemented using its API.
- *
- * This implementation should cover ubuntu-12, ubuntu-14, ubuntu-16.
- */
-
-namespace std {
- int uncaught_exceptions() noexcept {
- const auto* globals{__cxxabiv1::__cxa_get_globals()};
- return static_cast<int>(globals->uncaughtExceptions);
- }
-}
+#include <cxxabi.h>
+
+/**
+ * libc++ expects std::uncaught_exceptions() to be provided by C++ runtime library.
+ *
+ * GCC versions prior to GCC 6 did not provide this function yet, but it can be
+ * implemented using its API.
+ *
+ * This implementation should cover ubuntu-12, ubuntu-14, ubuntu-16.
+ */
+
+namespace std {
+ int uncaught_exceptions() noexcept {
+ const auto* globals{__cxxabiv1::__cxa_get_globals()};
+ return static_cast<int>(globals->uncaughtExceptions);
+ }
+}
diff --git a/contrib/libs/cxxsupp/libcxx/import b/contrib/libs/cxxsupp/libcxx/import
index 60f276b136..9b93145897 100755
--- a/contrib/libs/cxxsupp/libcxx/import
+++ b/contrib/libs/cxxsupp/libcxx/import
@@ -17,6 +17,6 @@ cp libcxx/LICENSE.TXT ../LICENSE.TXT
cd ..
rm -rf tmp
rm src/CMakeLists.txt include/CMakeLists.txt
-
-# Fix tabs and trailing spaces
-find -type f | xargs sed -e 's/\t/ /g' -e 's/ *$//' -i
+
+# Fix tabs and trailing spaces
+find -type f | xargs sed -e 's/\t/ /g' -e 's/ *$//' -i
diff --git a/contrib/libs/cxxsupp/libcxx/include/__config b/contrib/libs/cxxsupp/libcxx/include/__config
index 723053f7d6..bdc54b92d1 100644
--- a/contrib/libs/cxxsupp/libcxx/include/__config
+++ b/contrib/libs/cxxsupp/libcxx/include/__config
@@ -418,8 +418,8 @@
(defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ >= 130000) || \
(defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ >= 60000))
# define _LIBCPP_HAS_ALIGNED_ALLOC
-# define _LIBCPP_HAS_TIMESPEC_GET
-# endif
+# define _LIBCPP_HAS_TIMESPEC_GET
+# endif
# endif // __APPLE__
#endif
#endif // __has_attribute(using_if_exists)
@@ -441,7 +441,7 @@
#endif
#if defined(__APPLE__) && !defined(__i386__) && !defined(__x86_64__) && \
(!defined(__arm__) || __ARM_ARCH_7K__ >= 2)
-# define _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
+# define _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
#endif
#if __has_feature(cxx_alignas)
@@ -458,7 +458,7 @@ typedef __char32_t char32_t;
#endif
#if !__has_feature(cxx_exceptions)
-# define _LIBCPP_NO_EXCEPTIONS
+# define _LIBCPP_NO_EXCEPTIONS
#endif
#if !(__has_feature(cxx_strong_enums))
@@ -521,7 +521,7 @@ typedef __char32_t char32_t;
#define _LIBCPP_NORETURN __attribute__((noreturn))
#if !defined(__EXCEPTIONS)
-# define _LIBCPP_NO_EXCEPTIONS
+# define _LIBCPP_NO_EXCEPTIONS
#endif
#if !defined(__SANITIZE_ADDRESS__)
@@ -633,8 +633,8 @@ typedef __char32_t char32_t;
# define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS _LIBCPP_DLL_VIS
# define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS
# else
-# define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS
-# define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS _LIBCPP_DLL_VIS
+# define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS
+# define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS _LIBCPP_DLL_VIS
# endif
# define _LIBCPP_OVERRIDABLE_FUNC_VIS _LIBCPP_DLL_VIS
# define _LIBCPP_EXPORTED_FROM_ABI __declspec(dllexport)
@@ -901,12 +901,12 @@ typedef unsigned int char32_t;
#if !defined(_LIBCPP_DEBUG)
# define _LIBCPP_DEBUG_LEVEL 0
#elif _LIBCPP_DEBUG == 0
-# define _LIBCPP_DEBUG_LEVEL 1
-#elif _LIBCPP_DEBUG == 1
-# define _LIBCPP_DEBUG_LEVEL 2
-#else
-# error Supported values for _LIBCPP_DEBUG are 0 and 1
-#endif
+# define _LIBCPP_DEBUG_LEVEL 1
+#elif _LIBCPP_DEBUG == 1
+# define _LIBCPP_DEBUG_LEVEL 2
+#else
+# error Supported values for _LIBCPP_DEBUG are 0 and 1
+#endif
// Libc++ allows disabling extern template instantiation declarations by
// means of users defining _LIBCPP_DISABLE_EXTERN_TEMPLATE.
@@ -1096,10 +1096,10 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
#if defined(_LIBCPP_COMPILER_CLANG_BASED) && !__has_feature(cxx_rtti)
# define _LIBCPP_NO_RTTI
#elif defined(__GNUC__) && !defined(__GXX_RTTI)
-# define _LIBCPP_NO_RTTI
-#elif defined(_LIBCPP_COMPILER_MSVC) && !defined(_CPPRTTI)
-# define _LIBCPP_NO_RTTI
-#endif
+# define _LIBCPP_NO_RTTI
+#elif defined(_LIBCPP_COMPILER_MSVC) && !defined(_CPPRTTI)
+# define _LIBCPP_NO_RTTI
+#endif
#ifndef _LIBCPP_WEAK
#define _LIBCPP_WEAK __attribute__((__weak__))
diff --git a/contrib/libs/cxxsupp/libcxx/include/__debug b/contrib/libs/cxxsupp/libcxx/include/__debug
index 3acd97da29..771e431632 100644
--- a/contrib/libs/cxxsupp/libcxx/include/__debug
+++ b/contrib/libs/cxxsupp/libcxx/include/__debug
@@ -34,7 +34,7 @@
# define _LIBCPP_DEBUG_ASSERT(x, m) ((void)0)
# define _LIBCPP_ASSERT_IMPL(x, m) ((x) ? (void)0 : _VSTD::__libcpp_debug_function(_VSTD::__libcpp_debug_info(__FILE__, __LINE__, #x, m)))
#elif _LIBCPP_DEBUG_LEVEL == 2
-# define _LIBCPP_DEBUG_ASSERT(x, m) _LIBCPP_ASSERT(x, m)
+# define _LIBCPP_DEBUG_ASSERT(x, m) _LIBCPP_ASSERT(x, m)
# define _LIBCPP_ASSERT_IMPL(x, m) ((x) ? (void)0 : _VSTD::__libcpp_debug_function(_VSTD::__libcpp_debug_info(__FILE__, __LINE__, #x, m)))
#else
# error _LIBCPP_DEBUG_LEVEL must be one of 0, 1, 2
@@ -221,7 +221,7 @@ public:
template <class _Cont>
_LIBCPP_INLINE_VISIBILITY static __c_node* __create_C_node(void *__mem, void *__c, __c_node *__next) {
- return ::new (__mem) _C_node<_Cont>(__c, __next);
+ return ::new (__mem) _C_node<_Cont>(__c, __next);
}
template <class _Cont>
diff --git a/contrib/libs/cxxsupp/libcxx/include/__hash_table b/contrib/libs/cxxsupp/libcxx/include/__hash_table
index 30ae07aab9..bd97027c1a 100644
--- a/contrib/libs/cxxsupp/libcxx/include/__hash_table
+++ b/contrib/libs/cxxsupp/libcxx/include/__hash_table
@@ -38,7 +38,7 @@ template <class _Tp>
struct __is_hash_value_type_imp : false_type {};
template <class _Key, class _Value>
-struct __is_hash_value_type_imp<__hash_value_type<_Key, _Value> > : true_type {};
+struct __is_hash_value_type_imp<__hash_value_type<_Key, _Value> > : true_type {};
template <class ..._Args>
struct __is_hash_value_type : false_type {};
diff --git a/contrib/libs/cxxsupp/libcxx/include/__locale b/contrib/libs/cxxsupp/libcxx/include/__locale
index 153aa812d4..38cb7a6f39 100644
--- a/contrib/libs/cxxsupp/libcxx/include/__locale
+++ b/contrib/libs/cxxsupp/libcxx/include/__locale
@@ -96,7 +96,7 @@ struct __libcpp_locale_guard {
__setlocale(__locale_all);
free(__locale_all);
}
- _configthreadlocale(__status);
+ _configthreadlocale(__status);
}
static const char* __setlocale(const char* __locale) {
const char* __new_locale = setlocale(LC_ALL, __locale);
diff --git a/contrib/libs/cxxsupp/libcxx/include/__string b/contrib/libs/cxxsupp/libcxx/include/__string
index b1a209d7bf..7074a73538 100644
--- a/contrib/libs/cxxsupp/libcxx/include/__string
+++ b/contrib/libs/cxxsupp/libcxx/include/__string
@@ -626,7 +626,7 @@ struct _LIBCPP_TEMPLATE_VIS char_traits<char8_t>
return __libcpp_is_constant_evaluated()
? _VSTD::__copy_constexpr(__s1, __s2, __n)
: __n == 0 ? __s1 : (char_type*)_VSTD::memcpy(__s1, __s2, __n);
- }
+ }
static _LIBCPP_CONSTEXPR_AFTER_CXX17
char_type* assign(char_type* __s, size_t __n, char_type __a) _NOEXCEPT
diff --git a/contrib/libs/cxxsupp/libcxx/include/__support/ibm/xlocale.h b/contrib/libs/cxxsupp/libcxx/include/__support/ibm/xlocale.h
index 4a6b86a068..15b8386dd3 100644
--- a/contrib/libs/cxxsupp/libcxx/include/__support/ibm/xlocale.h
+++ b/contrib/libs/cxxsupp/libcxx/include/__support/ibm/xlocale.h
@@ -125,7 +125,7 @@ int vasprintf(char **strp, const char *fmt, va_list ap) {
str_size = vsnprintf(*strp, str_size + 1, fmt, ap);
}
return str_size;
-}
+}
#ifdef __cplusplus
}
diff --git a/contrib/libs/cxxsupp/libcxx/include/__support/solaris/wchar.h b/contrib/libs/cxxsupp/libcxx/include/__support/solaris/wchar.h
index 9dc9ac3f00..f01fd743a2 100644
--- a/contrib/libs/cxxsupp/libcxx/include/__support/solaris/wchar.h
+++ b/contrib/libs/cxxsupp/libcxx/include/__support/solaris/wchar.h
@@ -26,7 +26,7 @@
#define wctype sun_wctype
#define _WCHAR_T 1
#include_next "wchar.h"
-#undef iswalpha
+#undef iswalpha
#undef iswupper
#undef iswlower
#undef iswdigit
diff --git a/contrib/libs/cxxsupp/libcxx/include/__threading_support b/contrib/libs/cxxsupp/libcxx/include/__threading_support
index f07b79841e..9b0de00dfc 100644
--- a/contrib/libs/cxxsupp/libcxx/include/__threading_support
+++ b/contrib/libs/cxxsupp/libcxx/include/__threading_support
@@ -83,7 +83,7 @@ typedef pthread_cond_t __libcpp_condvar_t;
#ifndef _LIBCPP_NO_NATIVE_SEMAPHORES
// Semaphore
typedef sem_t __libcpp_semaphore_t;
-# define _LIBCPP_SEMAPHORE_MAX SEM_VALUE_MAX
+# define _LIBCPP_SEMAPHORE_MAX SEM_VALUE_MAX
#endif
// Execute once
@@ -94,7 +94,7 @@ typedef pthread_once_t __libcpp_exec_once_flag;
#if defined(__MVS__)
typedef unsigned long long __libcpp_thread_id;
#else
- typedef pthread_t __libcpp_thread_id;
+ typedef pthread_t __libcpp_thread_id;
#endif
// Thread
diff --git a/contrib/libs/cxxsupp/libcxx/include/__tree b/contrib/libs/cxxsupp/libcxx/include/__tree
index fd5b429ea5..f3f2e8d15f 100644
--- a/contrib/libs/cxxsupp/libcxx/include/__tree
+++ b/contrib/libs/cxxsupp/libcxx/include/__tree
@@ -539,7 +539,7 @@ template <class _Tp>
struct __is_tree_value_type_imp : false_type {};
template <class _Key, class _Value>
-struct __is_tree_value_type_imp<__value_type<_Key, _Value> > : true_type {};
+struct __is_tree_value_type_imp<__value_type<_Key, _Value> > : true_type {};
template <class ..._Args>
struct __is_tree_value_type : false_type {};
@@ -1638,7 +1638,7 @@ __tree<_Tp, _Compare, _Allocator>::__assign_unique(_ForwardIterator __first, _Fo
for (; __cache.__get() != nullptr && __first != __last; ++__first) {
if (__node_assign_unique(*__first, __cache.__get()).second)
__cache.__advance();
- }
+ }
}
for (; __first != __last; ++__first)
__insert_unique(*__first);
@@ -2251,7 +2251,7 @@ __tree<_Tp, _Compare, _Allocator>::__remove_node_pointer(__node_pointer __ptr) _
__begin_node() = __r.__ptr_;
--size();
_VSTD::__tree_remove(__end_node()->__left_,
- static_cast<__node_base_pointer>(__ptr));
+ static_cast<__node_base_pointer>(__ptr));
return __r;
}
@@ -2727,7 +2727,7 @@ __tree<_Tp, _Compare, _Allocator>::remove(const_iterator __p) _NOEXCEPT
}
--size();
_VSTD::__tree_remove(__end_node()->__left_,
- static_cast<__node_base_pointer>(__np));
+ static_cast<__node_base_pointer>(__np));
return __node_holder(__np, _Dp(__node_alloc(), true));
}
diff --git a/contrib/libs/cxxsupp/libcxx/include/algorithm b/contrib/libs/cxxsupp/libcxx/include/algorithm
index 307c740247..3fe0c8c1c9 100644
--- a/contrib/libs/cxxsupp/libcxx/include/algorithm
+++ b/contrib/libs/cxxsupp/libcxx/include/algorithm
@@ -563,10 +563,10 @@ template<class T, class Compare>
min(initializer_list<T> t, Compare comp);
template<class T>
- constexpr const T& clamp(const T& v, const T& lo, const T& hi); // C++17
+ constexpr const T& clamp(const T& v, const T& lo, const T& hi); // C++17
template<class T, class Compare>
- constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp); // C++17
+ constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp); // C++17
template <class ForwardIterator>
constexpr ForwardIterator // constexpr in C++14
diff --git a/contrib/libs/cxxsupp/libcxx/include/atomic b/contrib/libs/cxxsupp/libcxx/include/atomic
index c9fec104ef..992c745961 100644
--- a/contrib/libs/cxxsupp/libcxx/include/atomic
+++ b/contrib/libs/cxxsupp/libcxx/include/atomic
@@ -23,10 +23,10 @@ namespace std
#define __cpp_lib_atomic_lock_free_type_aliases
#define __cpp_lib_atomic_wait
- // order and consistency
+ // order and consistency
enum memory_order: unspecified // enum class in C++20
- {
+ {
relaxed,
consume, // load-consume
acquire, // load-acquire
@@ -532,13 +532,13 @@ template <class T>
#endif
#ifdef _LIBCPP_HAS_NO_THREADS
-# error <atomic> is not supported on this single threaded system
+# error <atomic> is not supported on this single threaded system
#endif
#ifdef _LIBCPP_HAS_NO_ATOMIC_HEADER
-# error <atomic> is not implemented
+# error <atomic> is not implemented
#endif
#ifdef kill_dependency
-# error C++ standard library is incompatible with <stdatomic.h>
+# error C++ standard library is incompatible with <stdatomic.h>
#endif
#define _LIBCPP_CHECK_STORE_MEMORY_ORDER(__m) \
@@ -613,7 +613,7 @@ static_assert((is_same<underlying_type<memory_order>::type, __memory_order_under
"unexpected underlying type for std::memory_order");
#if defined(_LIBCPP_HAS_GCC_ATOMIC_IMP) || \
- defined(_LIBCPP_ATOMIC_ONLY_USE_BUILTINS)
+ defined(_LIBCPP_ATOMIC_ONLY_USE_BUILTINS)
// [atomics.types.generic]p1 guarantees _Tp is trivially copyable. Because
// the default operator= in an object is not volatile, a byte-by-byte copy
@@ -696,7 +696,7 @@ void __cxx_atomic_signal_fence(memory_order __order) {
template <typename _Tp>
_LIBCPP_INLINE_VISIBILITY
void __cxx_atomic_store(volatile __cxx_atomic_base_impl<_Tp>* __a, _Tp __val,
- memory_order __order) {
+ memory_order __order) {
__atomic_store(&__a->__a_value, &__val,
__to_gcc_order(__order));
}
@@ -704,7 +704,7 @@ void __cxx_atomic_store(volatile __cxx_atomic_base_impl<_Tp>* __a, _Tp __val,
template <typename _Tp>
_LIBCPP_INLINE_VISIBILITY
void __cxx_atomic_store(__cxx_atomic_base_impl<_Tp>* __a, _Tp __val,
- memory_order __order) {
+ memory_order __order) {
__atomic_store(&__a->__a_value, &__val,
__to_gcc_order(__order));
}
@@ -712,7 +712,7 @@ void __cxx_atomic_store(__cxx_atomic_base_impl<_Tp>* __a, _Tp __val,
template <typename _Tp>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_load(const volatile __cxx_atomic_base_impl<_Tp>* __a,
- memory_order __order) {
+ memory_order __order) {
_Tp __ret;
__atomic_load(&__a->__a_value, &__ret,
__to_gcc_order(__order));
@@ -731,7 +731,7 @@ _Tp __cxx_atomic_load(const __cxx_atomic_base_impl<_Tp>* __a, memory_order __ord
template <typename _Tp>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_exchange(volatile __cxx_atomic_base_impl<_Tp>* __a,
- _Tp __value, memory_order __order) {
+ _Tp __value, memory_order __order) {
_Tp __ret;
__atomic_exchange(&__a->__a_value, &__value, &__ret,
__to_gcc_order(__order));
@@ -741,7 +741,7 @@ _Tp __cxx_atomic_exchange(volatile __cxx_atomic_base_impl<_Tp>* __a,
template <typename _Tp>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_exchange(__cxx_atomic_base_impl<_Tp>* __a, _Tp __value,
- memory_order __order) {
+ memory_order __order) {
_Tp __ret;
__atomic_exchange(&__a->__a_value, &__value, &__ret,
__to_gcc_order(__order));
@@ -808,7 +808,7 @@ struct __skip_amt<_Tp[n]> { };
template <typename _Tp, typename _Td>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_fetch_add(volatile __cxx_atomic_base_impl<_Tp>* __a,
- _Td __delta, memory_order __order) {
+ _Td __delta, memory_order __order) {
return __atomic_fetch_add(&__a->__a_value, __delta * __skip_amt<_Tp>::value,
__to_gcc_order(__order));
}
@@ -816,7 +816,7 @@ _Tp __cxx_atomic_fetch_add(volatile __cxx_atomic_base_impl<_Tp>* __a,
template <typename _Tp, typename _Td>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_fetch_add(__cxx_atomic_base_impl<_Tp>* __a, _Td __delta,
- memory_order __order) {
+ memory_order __order) {
return __atomic_fetch_add(&__a->__a_value, __delta * __skip_amt<_Tp>::value,
__to_gcc_order(__order));
}
@@ -824,7 +824,7 @@ _Tp __cxx_atomic_fetch_add(__cxx_atomic_base_impl<_Tp>* __a, _Td __delta,
template <typename _Tp, typename _Td>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_fetch_sub(volatile __cxx_atomic_base_impl<_Tp>* __a,
- _Td __delta, memory_order __order) {
+ _Td __delta, memory_order __order) {
return __atomic_fetch_sub(&__a->__a_value, __delta * __skip_amt<_Tp>::value,
__to_gcc_order(__order));
}
@@ -832,7 +832,7 @@ _Tp __cxx_atomic_fetch_sub(volatile __cxx_atomic_base_impl<_Tp>* __a,
template <typename _Tp, typename _Td>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_fetch_sub(__cxx_atomic_base_impl<_Tp>* __a, _Td __delta,
- memory_order __order) {
+ memory_order __order) {
return __atomic_fetch_sub(&__a->__a_value, __delta * __skip_amt<_Tp>::value,
__to_gcc_order(__order));
}
@@ -840,7 +840,7 @@ _Tp __cxx_atomic_fetch_sub(__cxx_atomic_base_impl<_Tp>* __a, _Td __delta,
template <typename _Tp>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_fetch_and(volatile __cxx_atomic_base_impl<_Tp>* __a,
- _Tp __pattern, memory_order __order) {
+ _Tp __pattern, memory_order __order) {
return __atomic_fetch_and(&__a->__a_value, __pattern,
__to_gcc_order(__order));
}
@@ -848,7 +848,7 @@ _Tp __cxx_atomic_fetch_and(volatile __cxx_atomic_base_impl<_Tp>* __a,
template <typename _Tp>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_fetch_and(__cxx_atomic_base_impl<_Tp>* __a,
- _Tp __pattern, memory_order __order) {
+ _Tp __pattern, memory_order __order) {
return __atomic_fetch_and(&__a->__a_value, __pattern,
__to_gcc_order(__order));
}
@@ -856,7 +856,7 @@ _Tp __cxx_atomic_fetch_and(__cxx_atomic_base_impl<_Tp>* __a,
template <typename _Tp>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_fetch_or(volatile __cxx_atomic_base_impl<_Tp>* __a,
- _Tp __pattern, memory_order __order) {
+ _Tp __pattern, memory_order __order) {
return __atomic_fetch_or(&__a->__a_value, __pattern,
__to_gcc_order(__order));
}
@@ -864,7 +864,7 @@ _Tp __cxx_atomic_fetch_or(volatile __cxx_atomic_base_impl<_Tp>* __a,
template <typename _Tp>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_fetch_or(__cxx_atomic_base_impl<_Tp>* __a, _Tp __pattern,
- memory_order __order) {
+ memory_order __order) {
return __atomic_fetch_or(&__a->__a_value, __pattern,
__to_gcc_order(__order));
}
@@ -872,7 +872,7 @@ _Tp __cxx_atomic_fetch_or(__cxx_atomic_base_impl<_Tp>* __a, _Tp __pattern,
template <typename _Tp>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_fetch_xor(volatile __cxx_atomic_base_impl<_Tp>* __a,
- _Tp __pattern, memory_order __order) {
+ _Tp __pattern, memory_order __order) {
return __atomic_fetch_xor(&__a->__a_value, __pattern,
__to_gcc_order(__order));
}
@@ -880,7 +880,7 @@ _Tp __cxx_atomic_fetch_xor(volatile __cxx_atomic_base_impl<_Tp>* __a,
template <typename _Tp>
_LIBCPP_INLINE_VISIBILITY
_Tp __cxx_atomic_fetch_xor(__cxx_atomic_base_impl<_Tp>* __a, _Tp __pattern,
- memory_order __order) {
+ memory_order __order) {
return __atomic_fetch_xor(&__a->__a_value, __pattern,
__to_gcc_order(__order));
}
@@ -928,7 +928,7 @@ void __cxx_atomic_signal_fence(memory_order __order) _NOEXCEPT {
#pragma warning ( pop )
#endif
-template<class _Tp>
+template<class _Tp>
_LIBCPP_INLINE_VISIBILITY
void __cxx_atomic_init(__cxx_atomic_base_impl<_Tp> volatile* __a, _Tp __val) _NOEXCEPT {
__c11_atomic_init(&__a->__a_value, __val);
diff --git a/contrib/libs/cxxsupp/libcxx/include/barrier b/contrib/libs/cxxsupp/libcxx/include/barrier
index eda9433a4b..c40a1e43f3 100644
--- a/contrib/libs/cxxsupp/libcxx/include/barrier
+++ b/contrib/libs/cxxsupp/libcxx/include/barrier
@@ -308,11 +308,11 @@ public:
{
__b.wait(_VSTD::move(__phase));
}
- _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
void arrive_and_wait()
{
wait(arrive());
- }
+ }
_LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
void arrive_and_drop()
{
diff --git a/contrib/libs/cxxsupp/libcxx/include/bit b/contrib/libs/cxxsupp/libcxx/include/bit
index 5da3eaf788..eab67977a1 100644
--- a/contrib/libs/cxxsupp/libcxx/include/bit
+++ b/contrib/libs/cxxsupp/libcxx/include/bit
@@ -219,7 +219,7 @@ _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
bool __has_single_bit(_Tp __t) _NOEXCEPT
{
static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__has_single_bit requires an unsigned integer type");
- return __t != 0 && (((__t & (__t - 1)) == 0));
+ return __t != 0 && (((__t & (__t - 1)) == 0));
}
#if _LIBCPP_STD_VER > 17
@@ -261,7 +261,7 @@ _LIBCPP_INLINE_VISIBILITY constexpr
enable_if_t<__libcpp_is_unsigned_integer<_Tp>::value, int>
countr_zero(_Tp __t) noexcept
{
- return __countr_zero(__t);
+ return __countr_zero(__t);
}
template<class _Tp>
diff --git a/contrib/libs/cxxsupp/libcxx/include/chrono b/contrib/libs/cxxsupp/libcxx/include/chrono
index 45c7a495a8..db186a4fba 100644
--- a/contrib/libs/cxxsupp/libcxx/include/chrono
+++ b/contrib/libs/cxxsupp/libcxx/include/chrono
@@ -1972,7 +1972,7 @@ bool operator!=(const weekday_last& __lhs, const weekday_last& __rhs) noexcept
inline constexpr
weekday_indexed weekday::operator[](unsigned __index) const noexcept { return weekday_indexed{*this, __index}; }
-inline constexpr
+inline constexpr
weekday_last weekday::operator[](last_spec) const noexcept { return weekday_last{*this}; }
@@ -2283,7 +2283,7 @@ public:
year_month_day() = default;
inline constexpr year_month_day(
const chrono::year& __yval, const chrono::month& __mval, const chrono::day& __dval) noexcept
- : __y{__yval}, __m{__mval}, __d{__dval} {}
+ : __y{__yval}, __m{__mval}, __d{__dval} {}
constexpr year_month_day(const year_month_day_last& __ymdl) noexcept;
inline constexpr year_month_day(const sys_days& __sysd) noexcept
: year_month_day(__from_days(__sysd.time_since_epoch())) {}
@@ -2538,7 +2538,7 @@ inline constexpr year_month_day_last& year_month_day_last::operator+=(const year
inline constexpr year_month_day_last& year_month_day_last::operator-=(const years& __dy) noexcept { *this = *this - __dy; return *this; }
inline constexpr year_month_day::year_month_day(const year_month_day_last& __ymdl) noexcept
- : __y{__ymdl.year()}, __m{__ymdl.month()}, __d{__ymdl.day()} {}
+ : __y{__ymdl.year()}, __m{__ymdl.month()}, __d{__ymdl.day()} {}
inline constexpr bool year_month_day::ok() const noexcept
{
@@ -2594,7 +2594,7 @@ year_month_weekday year_month_weekday::__from_days(days __d) noexcept
const sys_days __sysd{__d};
const chrono::weekday __wd = chrono::weekday(__sysd);
const year_month_day __ymd = year_month_day(__sysd);
- return year_month_weekday{__ymd.year(), __ymd.month(),
+ return year_month_weekday{__ymd.year(), __ymd.month(),
__wd[(static_cast<unsigned>(__ymd.day())-1)/7+1]};
}
@@ -2686,9 +2686,9 @@ public:
inline constexpr operator sys_days() const noexcept { return sys_days{__to_days()}; }
inline explicit constexpr operator local_days() const noexcept { return local_days{__to_days()}; }
inline constexpr bool ok() const noexcept { return __y.ok() && __m.ok() && __wdl.ok(); }
-
+
constexpr days __to_days() const noexcept;
-
+
};
inline constexpr
@@ -2726,7 +2726,7 @@ year_month_weekday_last operator/(const month_weekday_last& __lhs, const year& _
inline constexpr
year_month_weekday_last operator/(const month_weekday_last& __lhs, int __rhs) noexcept
-{ return year(__rhs) / __lhs; }
+{ return year(__rhs) / __lhs; }
inline constexpr
@@ -2916,7 +2916,7 @@ inline namespace literals
{
return chrono::day(static_cast<unsigned>(__d));
}
-
+
constexpr chrono::year operator ""y(unsigned long long __y) noexcept
{
return chrono::year(static_cast<int>(__y));
diff --git a/contrib/libs/cxxsupp/libcxx/include/cmath b/contrib/libs/cxxsupp/libcxx/include/cmath
index a2a7dde190..e14905c57c 100644
--- a/contrib/libs/cxxsupp/libcxx/include/cmath
+++ b/contrib/libs/cxxsupp/libcxx/include/cmath
@@ -622,9 +622,9 @@ _Fp __lerp(_Fp __a, _Fp __b, _Fp __t) noexcept {
if (__t == 1) return __b;
const _Fp __x = __a + __t * (__b - __a);
if ((__t > 1) == (__b > __a))
- return __b < __x ? __x : __b;
+ return __b < __x ? __x : __b;
else
- return __x < __b ? __x : __b;
+ return __x < __b ? __x : __b;
}
constexpr float
diff --git a/contrib/libs/cxxsupp/libcxx/include/complex b/contrib/libs/cxxsupp/libcxx/include/complex
index 01c072c800..e4c59193bc 100644
--- a/contrib/libs/cxxsupp/libcxx/include/complex
+++ b/contrib/libs/cxxsupp/libcxx/include/complex
@@ -1447,10 +1447,10 @@ operator<<(basic_ostream<_CharT, _Traits>& __os, const complex<_Tp>& __x)
}
#endif // !_LIBCPP_HAS_NO_LOCALIZATION
-#if _LIBCPP_STD_VER > 11
+#if _LIBCPP_STD_VER > 11
// Literal suffix for complex number literals [complex.literals]
inline namespace literals
-{
+{
inline namespace complex_literals
{
constexpr complex<long double> operator""il(long double __im)
diff --git a/contrib/libs/cxxsupp/libcxx/include/ctime b/contrib/libs/cxxsupp/libcxx/include/ctime
index 6034bf2185..816618f6a3 100644
--- a/contrib/libs/cxxsupp/libcxx/include/ctime
+++ b/contrib/libs/cxxsupp/libcxx/include/ctime
@@ -18,7 +18,7 @@ Macros:
NULL
CLOCKS_PER_SEC
TIME_UTC // C++17
-
+
namespace std
{
@@ -29,7 +29,7 @@ Types:
time_t
tm
timespec // C++17
-
+
clock_t clock();
double difftime(time_t time1, time_t time0);
time_t mktime(tm* timeptr);
diff --git a/contrib/libs/cxxsupp/libcxx/include/deque b/contrib/libs/cxxsupp/libcxx/include/deque
index 8108abecd9..67cd6654f1 100644
--- a/contrib/libs/cxxsupp/libcxx/include/deque
+++ b/contrib/libs/cxxsupp/libcxx/include/deque
@@ -2889,7 +2889,7 @@ deque<_Tp, _Allocator>::erase(const_iterator __f, const_iterator __l)
__alloc_traits::destroy(__a, _VSTD::addressof(*__b));
__base::size() -= __n;
__base::__start_ += __n;
- while (__maybe_remove_front_spare()) {
+ while (__maybe_remove_front_spare()) {
}
}
else
@@ -2898,7 +2898,7 @@ deque<_Tp, _Allocator>::erase(const_iterator __f, const_iterator __l)
for (iterator __e = __base::end(); __i != __e; ++__i)
__alloc_traits::destroy(__a, _VSTD::addressof(*__i));
__base::size() -= __n;
- while (__maybe_remove_back_spare()) {
+ while (__maybe_remove_back_spare()) {
}
}
}
@@ -2919,7 +2919,7 @@ deque<_Tp, _Allocator>::__erase_to_end(const_iterator __f)
for (iterator __p = __b + __pos; __p != __e; ++__p)
__alloc_traits::destroy(__a, _VSTD::addressof(*__p));
__base::size() -= __n;
- while (__maybe_remove_back_spare()) {
+ while (__maybe_remove_back_spare()) {
}
}
}
diff --git a/contrib/libs/cxxsupp/libcxx/include/experimental/functional b/contrib/libs/cxxsupp/libcxx/include/experimental/functional
index 5d28714566..e3220e16ca 100644
--- a/contrib/libs/cxxsupp/libcxx/include/experimental/functional
+++ b/contrib/libs/cxxsupp/libcxx/include/experimental/functional
@@ -113,7 +113,7 @@ template<class _ForwardIterator, class _BinaryPredicate = equal_to<>>
class _LIBCPP_TEMPLATE_VIS default_searcher {
public:
_LIBCPP_INLINE_VISIBILITY
- default_searcher(_ForwardIterator __f, _ForwardIterator __l,
+ default_searcher(_ForwardIterator __f, _ForwardIterator __l,
_BinaryPredicate __p = _BinaryPredicate())
: __first_(__f), __last_(__l), __pred_(__p) {}
@@ -152,12 +152,12 @@ public: // TODO private:
const _Value __default_value_;
std::unordered_map<_Key, _Value, _Hash, _BinaryPredicate> __table;
-
+
public:
_LIBCPP_INLINE_VISIBILITY
_BMSkipTable(size_t __sz, _Value __default, _Hash __hf, _BinaryPredicate __pred)
: __default_value_(__default), __table(__sz, __hf, __pred) {}
-
+
_LIBCPP_INLINE_VISIBILITY
void insert(const key_type &__key, value_type __val)
{
@@ -172,7 +172,7 @@ public:
}
};
-
+
// Special case small numeric values; use an array
template<class _Key, typename _Value, class _Hash, class _BinaryPredicate>
class _BMSkipTable<_Key, _Value, _Hash, _BinaryPredicate, true> {
@@ -190,7 +190,7 @@ public:
{
std::fill_n(__table.begin(), __table.size(), __default);
}
-
+
_LIBCPP_INLINE_VISIBILITY
void insert(key_type __key, value_type __val)
{
@@ -205,8 +205,8 @@ public:
};
-template <class _RandomAccessIterator1,
- class _Hash = hash<typename iterator_traits<_RandomAccessIterator1>::value_type>,
+template <class _RandomAccessIterator1,
+ class _Hash = hash<typename iterator_traits<_RandomAccessIterator1>::value_type>,
class _BinaryPredicate = equal_to<>>
class _LIBCPP_TEMPLATE_VIS boyer_moore_searcher {
private:
@@ -218,9 +218,9 @@ private:
is_same<_Hash, hash<value_type>>::value &&
is_same<_BinaryPredicate, equal_to<>>::value
> skip_table_type;
-
+
public:
- boyer_moore_searcher(_RandomAccessIterator1 __f, _RandomAccessIterator1 __l,
+ boyer_moore_searcher(_RandomAccessIterator1 __f, _RandomAccessIterator1 __l,
_Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate())
: __first_(__f), __last_(__l), __pred_(__pred),
__pattern_length_(_VSTD::distance(__first_, __last_)),
@@ -233,13 +233,13 @@ public:
this->__build_suffix_table ( __first_, __last_, __pred_ );
}
-
+
template <typename _RandomAccessIterator2>
pair<_RandomAccessIterator2, _RandomAccessIterator2>
operator ()(_RandomAccessIterator2 __f, _RandomAccessIterator2 __l) const
{
static_assert ( std::is_same<
- typename std::__uncvref<typename std::iterator_traits<_RandomAccessIterator1>::value_type>::type,
+ typename std::__uncvref<typename std::iterator_traits<_RandomAccessIterator1>::value_type>::type,
typename std::__uncvref<typename std::iterator_traits<_RandomAccessIterator2>::value_type>::type
>::value,
"Corpus and Pattern iterators must point to the same type" );
@@ -251,10 +251,10 @@ public:
if ( __pattern_length_ > _VSTD::distance(__f, __l))
return make_pair(__l, __l);
- // Do the search
+ // Do the search
return this->__search(__f, __l);
}
-
+
public: // TODO private:
_RandomAccessIterator1 __first_;
_RandomAccessIterator1 __last_;
@@ -271,7 +271,7 @@ public: // TODO private:
const _RandomAccessIterator2 __last = __l - __pattern_length_;
const skip_table_type & __skip = *__skip_.get();
const vector<difference_type> & __suffix = *__suffix_.get();
-
+
while (__cur <= __last)
{
@@ -283,7 +283,7 @@ public: // TODO private:
if ( __j == 0 )
return make_pair(__cur, __cur + __pattern_length_);
}
-
+
// Since we didn't match, figure out how far to skip forward
difference_type __k = __skip[__cur [ __j - 1 ]];
difference_type __m = __j - __k - 1;
@@ -292,7 +292,7 @@ public: // TODO private:
else
__cur += __suffix[ __j ];
}
-
+
return make_pair(__l, __l); // We didn't find anything
}
@@ -301,21 +301,21 @@ public: // TODO private:
void __compute_bm_prefix ( _Iterator __f, _Iterator __l, _BinaryPredicate __pred, _Container &__prefix )
{
const size_t __count = _VSTD::distance(__f, __l);
-
+
__prefix[0] = 0;
size_t __k = 0;
for ( size_t __i = 1; __i < __count; ++__i )
{
while ( __k > 0 && !__pred ( __f[__k], __f[__i] ))
__k = __prefix [ __k - 1 ];
-
+
if ( __pred ( __f[__k], __f[__i] ))
__k++;
__prefix [ __i ] = __k;
}
}
- void __build_suffix_table(_RandomAccessIterator1 __f, _RandomAccessIterator1 __l,
+ void __build_suffix_table(_RandomAccessIterator1 __f, _RandomAccessIterator1 __l,
_BinaryPredicate __pred)
{
const size_t __count = _VSTD::distance(__f, __l);
@@ -323,19 +323,19 @@ public: // TODO private:
if (__count > 0)
{
vector<value_type> __scratch(__count);
-
+
__compute_bm_prefix(__f, __l, __pred, __scratch);
for ( size_t __i = 0; __i <= __count; __i++ )
__suffix[__i] = __count - __scratch[__count-1];
-
+
typedef reverse_iterator<_RandomAccessIterator1> _RevIter;
__compute_bm_prefix(_RevIter(__l), _RevIter(__f), __pred, __scratch);
-
+
for ( size_t __i = 0; __i < __count; __i++ )
{
const size_t __j = __count - __scratch[__i];
const difference_type __k = __i - __scratch[__i] + 1;
-
+
if (__suffix[__j] > __k)
__suffix[__j] = __k;
}
@@ -344,20 +344,20 @@ public: // TODO private:
};
-template<class _RandomAccessIterator,
- class _Hash = hash<typename iterator_traits<_RandomAccessIterator>::value_type>,
+template<class _RandomAccessIterator,
+ class _Hash = hash<typename iterator_traits<_RandomAccessIterator>::value_type>,
class _BinaryPredicate = equal_to<>>
_LIBCPP_INLINE_VISIBILITY
boyer_moore_searcher<_RandomAccessIterator, _Hash, _BinaryPredicate>
-make_boyer_moore_searcher( _RandomAccessIterator __f, _RandomAccessIterator __l,
+make_boyer_moore_searcher( _RandomAccessIterator __f, _RandomAccessIterator __l,
_Hash __hf = _Hash(), _BinaryPredicate __p = _BinaryPredicate ())
{
return boyer_moore_searcher<_RandomAccessIterator, _Hash, _BinaryPredicate>(__f, __l, __hf, __p);
}
// boyer-moore-horspool
-template <class _RandomAccessIterator1,
- class _Hash = hash<typename iterator_traits<_RandomAccessIterator1>::value_type>,
+template <class _RandomAccessIterator1,
+ class _Hash = hash<typename iterator_traits<_RandomAccessIterator1>::value_type>,
class _BinaryPredicate = equal_to<>>
class _LIBCPP_TEMPLATE_VIS boyer_moore_horspool_searcher {
private:
@@ -371,7 +371,7 @@ private:
> skip_table_type;
public:
- boyer_moore_horspool_searcher(_RandomAccessIterator1 __f, _RandomAccessIterator1 __l,
+ boyer_moore_horspool_searcher(_RandomAccessIterator1 __f, _RandomAccessIterator1 __l,
_Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate())
: __first_(__f), __last_(__l), __pred_(__pred),
__pattern_length_(_VSTD::distance(__first_, __last_)),
@@ -385,13 +385,13 @@ public:
__skip_->insert(*__f, __pattern_length_ - 1 - __i);
}
}
-
+
template <typename _RandomAccessIterator2>
pair<_RandomAccessIterator2, _RandomAccessIterator2>
operator ()(_RandomAccessIterator2 __f, _RandomAccessIterator2 __l) const
{
static_assert ( std::is_same<
- typename std::__uncvref<typename std::iterator_traits<_RandomAccessIterator1>::value_type>::type,
+ typename std::__uncvref<typename std::iterator_traits<_RandomAccessIterator1>::value_type>::type,
typename std::__uncvref<typename std::iterator_traits<_RandomAccessIterator2>::value_type>::type
>::value,
"Corpus and Pattern iterators must point to the same type" );
@@ -403,10 +403,10 @@ public:
if ( __pattern_length_ > _VSTD::distance(__f, __l))
return make_pair(__l, __l);
- // Do the search
+ // Do the search
return this->__search(__f, __l);
}
-
+
private:
_RandomAccessIterator1 __first_;
_RandomAccessIterator1 __last_;
@@ -434,17 +434,17 @@ private:
}
__cur += __skip[__cur[__pattern_length_-1]];
}
-
+
return make_pair(__l, __l);
}
};
-template<class _RandomAccessIterator,
- class _Hash = hash<typename iterator_traits<_RandomAccessIterator>::value_type>,
+template<class _RandomAccessIterator,
+ class _Hash = hash<typename iterator_traits<_RandomAccessIterator>::value_type>,
class _BinaryPredicate = equal_to<>>
_LIBCPP_INLINE_VISIBILITY
boyer_moore_horspool_searcher<_RandomAccessIterator, _Hash, _BinaryPredicate>
-make_boyer_moore_horspool_searcher( _RandomAccessIterator __f, _RandomAccessIterator __l,
+make_boyer_moore_horspool_searcher( _RandomAccessIterator __f, _RandomAccessIterator __l,
_Hash __hf = _Hash(), _BinaryPredicate __p = _BinaryPredicate ())
{
return boyer_moore_horspool_searcher<_RandomAccessIterator, _Hash, _BinaryPredicate>(__f, __l, __hf, __p);
diff --git a/contrib/libs/cxxsupp/libcxx/include/experimental/iterator b/contrib/libs/cxxsupp/libcxx/include/experimental/iterator
index 43f1bd8d7a..09ea2cbcc7 100644
--- a/contrib/libs/cxxsupp/libcxx/include/experimental/iterator
+++ b/contrib/libs/cxxsupp/libcxx/include/experimental/iterator
@@ -26,19 +26,19 @@ namespace std {
typedef void difference_type;
typedef void pointer;
typedef void reference;
-
+
ostream_joiner(ostream_type& s, const DelimT& delimiter);
ostream_joiner(ostream_type& s, DelimT&& delimiter);
- template<typename T>
+ template<typename T>
ostream_joiner& operator=(const T& value);
ostream_joiner& operator*() noexcept;
ostream_joiner& operator++() noexcept;
ostream_joiner& operator++(int) noexcept;
private:
- ostream_type* out_stream; // exposition only
- DelimT delim; // exposition only
+ ostream_type* out_stream; // exposition only
+ DelimT delim; // exposition only
bool first_element; // exposition only
};
@@ -78,11 +78,11 @@ public:
ostream_joiner(ostream_type& __os, _Delim&& __d)
: __output_iter(_VSTD::addressof(__os)), __delim(_VSTD::move(__d)), __first(true) {}
-
+
ostream_joiner(ostream_type& __os, const _Delim& __d)
: __output_iter(_VSTD::addressof(__os)), __delim(__d), __first(true) {}
-
+
template<typename _Tp>
ostream_joiner& operator=(const _Tp& __v)
{
diff --git a/contrib/libs/cxxsupp/libcxx/include/experimental/type_traits b/contrib/libs/cxxsupp/libcxx/include/experimental/type_traits
index a5e554b34a..ea1335f96a 100644
--- a/contrib/libs/cxxsupp/libcxx/include/experimental/type_traits
+++ b/contrib/libs/cxxsupp/libcxx/include/experimental/type_traits
@@ -60,7 +60,7 @@ inline namespace fundamentals_v1 {
using is_detected_convertible = is_convertible<detected_t<Op, Args...>, To>;
template <class To, template<class...> class Op, class... Args>
constexpr bool is_detected_convertible_v
- = is_detected_convertible<To, Op, Args...>::value;
+ = is_detected_convertible<To, Op, Args...>::value;
} // namespace fundamentals_v1
} // namespace experimental
@@ -106,9 +106,9 @@ using raw_invocation_type_t = typename raw_invocation_type<_Tp>::type;
template <class...> using void_t = void;
struct nonesuch : private __nat { // make nonesuch "not an aggregate"
- ~nonesuch() = delete;
- nonesuch (nonesuch const&) = delete;
- void operator=(nonesuch const&) = delete;
+ ~nonesuch() = delete;
+ nonesuch (nonesuch const&) = delete;
+ void operator=(nonesuch const&) = delete;
};
template <class _Default, class _AlwaysVoid, template <class...> class _Op, class... _Args>
@@ -123,7 +123,7 @@ struct _DETECTOR<_Default, void_t<_Op<_Args...>>, _Op, _Args...> {
using type = _Op<_Args...>;
};
-
+
template <template<class...> class _Op, class... _Args>
using is_detected = typename _DETECTOR<nonesuch, void, _Op, _Args...>::value_t;
template <template<class...> class _Op, class... _Args>
@@ -144,7 +144,7 @@ template <class Expected, template<class...> class _Op, class... _Args>
template <class To, template<class...> class _Op, class... _Args>
using is_detected_convertible = is_convertible<detected_t<_Op, _Args...>, To>;
template <class To, template<class...> class _Op, class... _Args>
- _LIBCPP_CONSTEXPR bool is_detected_convertible_v = is_detected_convertible<To, _Op, _Args...>::value;
+ _LIBCPP_CONSTEXPR bool is_detected_convertible_v = is_detected_convertible<To, _Op, _Args...>::value;
_LIBCPP_END_NAMESPACE_LFTS
diff --git a/contrib/libs/cxxsupp/libcxx/include/ext/hash_map b/contrib/libs/cxxsupp/libcxx/include/ext/hash_map
index 067f4a1ada..60e32b09e3 100644
--- a/contrib/libs/cxxsupp/libcxx/include/ext/hash_map
+++ b/contrib/libs/cxxsupp/libcxx/include/ext/hash_map
@@ -46,10 +46,10 @@ public:
template <class InputIterator>
hash_map(InputIterator f, InputIterator l);
template <class InputIterator>
- hash_map(InputIterator f, InputIterator l,
+ hash_map(InputIterator f, InputIterator l,
size_type n, const hasher& hf = hasher(),
- const key_equal& eql = key_equal(),
- const allocator_type& a = allocator_type());
+ const key_equal& eql = key_equal(),
+ const allocator_type& a = allocator_type());
hash_map(const hash_map&);
~hash_map();
hash_map& operator=(const hash_map&);
@@ -395,10 +395,10 @@ public:
return __t;
}
- friend _LIBCPP_INLINE_VISIBILITY
+ friend _LIBCPP_INLINE_VISIBILITY
bool operator==(const __hash_map_iterator& __x, const __hash_map_iterator& __y)
{return __x.__i_ == __y.__i_;}
- friend _LIBCPP_INLINE_VISIBILITY
+ friend _LIBCPP_INLINE_VISIBILITY
bool operator!=(const __hash_map_iterator& __x, const __hash_map_iterator& __y)
{return __x.__i_ != __y.__i_;}
diff --git a/contrib/libs/cxxsupp/libcxx/include/ext/hash_set b/contrib/libs/cxxsupp/libcxx/include/ext/hash_set
index d1fecdd111..af3f9c5de0 100644
--- a/contrib/libs/cxxsupp/libcxx/include/ext/hash_set
+++ b/contrib/libs/cxxsupp/libcxx/include/ext/hash_set
@@ -607,7 +607,7 @@ template <class _InputIterator>
inline
void
hash_multiset<_Value, _Hash, _Pred, _Alloc>::insert(_InputIterator __first,
- _InputIterator __last)
+ _InputIterator __last)
{
for (; __first != __last; ++__first)
__table_.__insert_multi(*__first);
diff --git a/contrib/libs/cxxsupp/libcxx/include/forward_list b/contrib/libs/cxxsupp/libcxx/include/forward_list
index 4273c2750b..3454a784a1 100644
--- a/contrib/libs/cxxsupp/libcxx/include/forward_list
+++ b/contrib/libs/cxxsupp/libcxx/include/forward_list
@@ -604,7 +604,7 @@ __forward_list_base<_Tp, _Alloc>::swap(__forward_list_base& __x)
__is_nothrow_swappable<__node_allocator>::value)
#endif
{
- _VSTD::__swap_allocator(__alloc(), __x.__alloc(),
+ _VSTD::__swap_allocator(__alloc(), __x.__alloc(),
integral_constant<bool, __node_traits::propagate_on_container_swap::value>());
using _VSTD::swap;
swap(__before_begin()->__next_, __x.__before_begin()->__next_);
diff --git a/contrib/libs/cxxsupp/libcxx/include/future b/contrib/libs/cxxsupp/libcxx/include/future
index 4761a1747d..89acdba62b 100644
--- a/contrib/libs/cxxsupp/libcxx/include/future
+++ b/contrib/libs/cxxsupp/libcxx/include/future
@@ -628,10 +628,10 @@ protected:
public:
template <class _Arg>
- void set_value(_Arg&& __arg);
+ void set_value(_Arg&& __arg);
template <class _Arg>
- void set_value_at_thread_exit(_Arg&& __arg);
+ void set_value_at_thread_exit(_Arg&& __arg);
_Rp move();
typename add_lvalue_reference<_Rp>::type copy();
@@ -1887,7 +1887,7 @@ public:
class = typename enable_if
<
!is_same<
- typename __uncvref<_Fp>::type,
+ typename __uncvref<_Fp>::type,
packaged_task
>::value
>::type
@@ -1898,7 +1898,7 @@ public:
class = typename enable_if
<
!is_same<
- typename __uncvref<_Fp>::type,
+ typename __uncvref<_Fp>::type,
packaged_task
>::value
>::type
@@ -2016,7 +2016,7 @@ public:
class = typename enable_if
<
!is_same<
- typename __uncvref<_Fp>::type,
+ typename __uncvref<_Fp>::type,
packaged_task
>::value
>::type
@@ -2027,11 +2027,11 @@ public:
class = typename enable_if
<
!is_same<
- typename __uncvref<_Fp>::type,
+ typename __uncvref<_Fp>::type,
packaged_task
>::value
>::type
- >
+ >
_LIBCPP_INLINE_VISIBILITY
packaged_task(allocator_arg_t, const _Allocator& __a, _Fp&& __f)
: __f_(allocator_arg, __a, _VSTD::forward<_Fp>(__f)),
diff --git a/contrib/libs/cxxsupp/libcxx/include/inttypes.h b/contrib/libs/cxxsupp/libcxx/include/inttypes.h
index 9b6e8eb4f1..6f8021263e 100644
--- a/contrib/libs/cxxsupp/libcxx/include/inttypes.h
+++ b/contrib/libs/cxxsupp/libcxx/include/inttypes.h
@@ -248,7 +248,7 @@ uintmax_t wcstoumax(const wchar_t* restrict nptr, wchar_t** restrict endptr, int
# define __STDC_FORMAT_MACROS
#endif
-#ifdef _LIBCPP_COMPILER_MSVC
+#ifdef _LIBCPP_COMPILER_MSVC
#include _LIBCPP_UCRT_INCLUDE(inttypes.h)
#else
#include_next <inttypes.h>
diff --git a/contrib/libs/cxxsupp/libcxx/include/ios b/contrib/libs/cxxsupp/libcxx/include/ios
index 555d34f4fe..c9230d6a94 100644
--- a/contrib/libs/cxxsupp/libcxx/include/ios
+++ b/contrib/libs/cxxsupp/libcxx/include/ios
@@ -202,8 +202,8 @@ enum class io_errc
};
concept_map ErrorCodeEnum<io_errc> { };
-error_code make_error_code(io_errc e) noexcept;
-error_condition make_error_condition(io_errc e) noexcept;
+error_code make_error_code(io_errc e) noexcept;
+error_condition make_error_condition(io_errc e) noexcept;
storage-class-specifier const error_category& iostream_category() noexcept;
} // std
@@ -635,45 +635,45 @@ public:
virtual ~basic_ios();
// 27.5.4.2 Members:
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
basic_ostream<char_type, traits_type>* tie() const;
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
basic_ostream<char_type, traits_type>* tie(basic_ostream<char_type, traits_type>* __tiestr);
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
basic_streambuf<char_type, traits_type>* rdbuf() const;
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
basic_streambuf<char_type, traits_type>* rdbuf(basic_streambuf<char_type, traits_type>* __sb);
basic_ios& copyfmt(const basic_ios& __rhs);
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
char_type fill() const;
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
char_type fill(char_type __ch);
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
locale imbue(const locale& __loc);
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
char narrow(char_type __c, char __dfault) const;
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
char_type widen(char __c) const;
protected:
_LIBCPP_INLINE_VISIBILITY
basic_ios() {// purposefully does no initialization
}
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
void init(basic_streambuf<char_type, traits_type>* __sb);
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
void move(basic_ios& __rhs);
_LIBCPP_INLINE_VISIBILITY
void move(basic_ios&& __rhs) {move(__rhs);}
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
void swap(basic_ios& __rhs) _NOEXCEPT;
- _LIBCPP_INLINE_VISIBILITY
+ _LIBCPP_INLINE_VISIBILITY
void set_rdbuf(basic_streambuf<char_type, traits_type>* __sb);
private:
basic_ostream<char_type, traits_type>* __tie_;
diff --git a/contrib/libs/cxxsupp/libcxx/include/istream b/contrib/libs/cxxsupp/libcxx/include/istream
index bf8c066dc6..6fb296f820 100644
--- a/contrib/libs/cxxsupp/libcxx/include/istream
+++ b/contrib/libs/cxxsupp/libcxx/include/istream
@@ -359,16 +359,16 @@ __input_arithmetic(basic_istream<_CharT, _Traits>& __is, _Tp& __n) {
if (__s)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
typedef istreambuf_iterator<_CharT, _Traits> _Ip;
typedef num_get<_CharT, _Ip> _Fp;
use_facet<_Fp>(__is.getloc()).get(_Ip(__is), _Ip(), __is, __state, __n);
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
__is.__setstate_nothrow(__state);
if (__is.exceptions() & ios_base::badbit)
@@ -468,8 +468,8 @@ __input_arithmetic_with_numeric_limits(basic_istream<_CharT, _Traits>& __is, _Tp
if (__s)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
typedef istreambuf_iterator<_CharT, _Traits> _Ip;
typedef num_get<_CharT, _Ip> _Fp;
@@ -488,18 +488,18 @@ __input_arithmetic_with_numeric_limits(basic_istream<_CharT, _Traits>& __is, _Tp
else
{
__n = static_cast<_Tp>(__temp);
- }
-#ifndef _LIBCPP_NO_EXCEPTIONS
+ }
+#ifndef _LIBCPP_NO_EXCEPTIONS
}
- catch (...)
- {
+ catch (...)
+ {
__state |= ios_base::badbit;
__is.__setstate_nothrow(__state);
if (__is.exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
__is.setstate(__state);
}
@@ -526,9 +526,9 @@ basic_istream<_CharT, _Traits>&
__input_c_string(basic_istream<_CharT, _Traits>& __is, _CharT* __p, size_t __n)
{
ios_base::iostate __state = ios_base::goodbit;
- typename basic_istream<_CharT, _Traits>::sentry __sen(__is);
- if (__sen)
- {
+ typename basic_istream<_CharT, _Traits>::sentry __sen(__is);
+ if (__sen)
+ {
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
@@ -554,9 +554,9 @@ __input_c_string(basic_istream<_CharT, _Traits>& __is, _CharT* __p, size_t __n)
if (__s == __p)
__state |= ios_base::failbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
__is.__setstate_nothrow(__state);
if (__is.exceptions() & ios_base::badbit)
@@ -635,9 +635,9 @@ basic_istream<_CharT, _Traits>&
operator>>(basic_istream<_CharT, _Traits>& __is, _CharT& __c)
{
ios_base::iostate __state = ios_base::goodbit;
- typename basic_istream<_CharT, _Traits>::sentry __sen(__is);
- if (__sen)
- {
+ typename basic_istream<_CharT, _Traits>::sentry __sen(__is);
+ if (__sen)
+ {
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
@@ -648,9 +648,9 @@ operator>>(basic_istream<_CharT, _Traits>& __is, _CharT& __c)
else
__c = _Traits::to_char_type(__i);
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
__is.__setstate_nothrow(__state);
if (__is.exceptions() & ios_base::badbit)
@@ -686,38 +686,38 @@ basic_istream<_CharT, _Traits>::operator>>(basic_streambuf<char_type, traits_typ
{
ios_base::iostate __state = ios_base::goodbit;
__gc_ = 0;
- sentry __s(*this, true);
- if (__s)
- {
- if (__sb)
+ sentry __s(*this, true);
+ if (__s)
+ {
+ if (__sb)
{
-#ifndef _LIBCPP_NO_EXCEPTIONS
- try
+#ifndef _LIBCPP_NO_EXCEPTIONS
+ try
{
-#endif // _LIBCPP_NO_EXCEPTIONS
- while (true)
+#endif // _LIBCPP_NO_EXCEPTIONS
+ while (true)
{
- typename traits_type::int_type __i = this->rdbuf()->sgetc();
- if (traits_type::eq_int_type(__i, _Traits::eof()))
+ typename traits_type::int_type __i = this->rdbuf()->sgetc();
+ if (traits_type::eq_int_type(__i, _Traits::eof()))
{
__state |= ios_base::eofbit;
- break;
+ break;
}
- if (traits_type::eq_int_type(
- __sb->sputc(traits_type::to_char_type(__i)),
- traits_type::eof()))
- break;
- ++__gc_;
- this->rdbuf()->sbumpc();
- }
- if (__gc_ == 0)
+ if (traits_type::eq_int_type(
+ __sb->sputc(traits_type::to_char_type(__i)),
+ traits_type::eof()))
+ break;
+ ++__gc_;
+ this->rdbuf()->sbumpc();
+ }
+ if (__gc_ == 0)
__state |= ios_base::failbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
- if (__gc_ == 0)
+ if (__gc_ == 0)
__state |= ios_base::failbit;
this->__setstate_nothrow(__state);
@@ -725,11 +725,11 @@ basic_istream<_CharT, _Traits>::operator>>(basic_streambuf<char_type, traits_typ
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
- }
- else
- {
+ }
+ else
+ {
__state |= ios_base::failbit;
}
this->setstate(__state);
@@ -744,9 +744,9 @@ basic_istream<_CharT, _Traits>::get()
ios_base::iostate __state = ios_base::goodbit;
__gc_ = 0;
int_type __r = traits_type::eof();
- sentry __s(*this, true);
- if (__s)
- {
+ sentry __s(*this, true);
+ if (__s)
+ {
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
@@ -757,9 +757,9 @@ basic_istream<_CharT, _Traits>::get()
else
__gc_ = 1;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
this->__setstate_nothrow(this->rdstate() | ios_base::badbit);
if (this->exceptions() & ios_base::badbit)
{
@@ -778,10 +778,10 @@ basic_istream<_CharT, _Traits>::get(char_type* __s, streamsize __n, char_type __
{
ios_base::iostate __state = ios_base::goodbit;
__gc_ = 0;
- sentry __sen(*this, true);
- if (__sen)
- {
- if (__n > 0)
+ sentry __sen(*this, true);
+ if (__sen)
+ {
+ if (__n > 0)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
try
@@ -805,22 +805,22 @@ basic_istream<_CharT, _Traits>::get(char_type* __s, streamsize __n, char_type __
if (__gc_ == 0)
__state |= ios_base::failbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
+ }
catch (...)
{
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
- if (__n > 0)
- *__s = char_type();
+ if (__n > 0)
+ *__s = char_type();
throw;
- }
+ }
}
#endif
}
else
- {
+ {
__state |= ios_base::failbit;
}
@@ -840,41 +840,41 @@ basic_istream<_CharT, _Traits>::get(basic_streambuf<char_type, traits_type>& __s
{
ios_base::iostate __state = ios_base::goodbit;
__gc_ = 0;
- sentry __sen(*this, true);
- if (__sen)
- {
-#ifndef _LIBCPP_NO_EXCEPTIONS
- try
+ sentry __sen(*this, true);
+ if (__sen)
+ {
+#ifndef _LIBCPP_NO_EXCEPTIONS
+ try
{
#endif // _LIBCPP_NO_EXCEPTIONS
- while (true)
+ while (true)
{
- typename traits_type::int_type __i = this->rdbuf()->sgetc();
- if (traits_type::eq_int_type(__i, traits_type::eof()))
+ typename traits_type::int_type __i = this->rdbuf()->sgetc();
+ if (traits_type::eq_int_type(__i, traits_type::eof()))
{
__state |= ios_base::eofbit;
- break;
+ break;
}
- char_type __ch = traits_type::to_char_type(__i);
- if (traits_type::eq(__ch, __dlm))
- break;
- if (traits_type::eq_int_type(__sb.sputc(__ch), traits_type::eof()))
- break;
- ++__gc_;
- this->rdbuf()->sbumpc();
- }
+ char_type __ch = traits_type::to_char_type(__i);
+ if (traits_type::eq(__ch, __dlm))
+ break;
+ if (traits_type::eq_int_type(__sb.sputc(__ch), traits_type::eof()))
+ break;
+ ++__gc_;
+ this->rdbuf()->sbumpc();
+ }
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
// according to the spec, exceptions here are caught but not rethrown
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
- if (__gc_ == 0)
+ if (__gc_ == 0)
__state |= ios_base::failbit;
this->setstate(__state);
- }
+ }
return *this;
}
@@ -888,8 +888,8 @@ basic_istream<_CharT, _Traits>::getline(char_type* __s, streamsize __n, char_typ
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
while (true)
{
@@ -916,20 +916,20 @@ basic_istream<_CharT, _Traits>::getline(char_type* __s, streamsize __n, char_typ
++__gc_;
}
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
- if (__n > 0)
- *__s = char_type();
+ if (__n > 0)
+ *__s = char_type();
if (__gc_ == 0)
__state |= ios_base::failbit;
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
}
if (__n > 0)
@@ -950,8 +950,8 @@ basic_istream<_CharT, _Traits>::ignore(streamsize __n, int_type __dlm)
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
if (__n == numeric_limits<streamsize>::max())
{
@@ -984,16 +984,16 @@ basic_istream<_CharT, _Traits>::ignore(streamsize __n, int_type __dlm)
}
}
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
this->setstate(__state);
}
@@ -1011,23 +1011,23 @@ basic_istream<_CharT, _Traits>::peek()
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
__r = this->rdbuf()->sgetc();
if (traits_type::eq_int_type(__r, traits_type::eof()))
__state |= ios_base::eofbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
this->setstate(__state);
}
@@ -1044,23 +1044,23 @@ basic_istream<_CharT, _Traits>::read(char_type* __s, streamsize __n)
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
__gc_ = this->rdbuf()->sgetn(__s, __n);
if (__gc_ != __n)
__state |= ios_base::failbit | ios_base::eofbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
}
else
@@ -1081,8 +1081,8 @@ basic_istream<_CharT, _Traits>::readsome(char_type* __s, streamsize __n)
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
streamsize __c = this->rdbuf()->in_avail();
switch (__c)
@@ -1100,16 +1100,16 @@ basic_istream<_CharT, _Traits>::readsome(char_type* __s, streamsize __n)
break;
}
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
}
else
@@ -1131,22 +1131,22 @@ basic_istream<_CharT, _Traits>::putback(char_type __c)
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
if (this->rdbuf() == nullptr || this->rdbuf()->sputbackc(__c) == traits_type::eof())
__state |= ios_base::badbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
}
else
@@ -1168,22 +1168,22 @@ basic_istream<_CharT, _Traits>::unget()
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
if (this->rdbuf() == nullptr || this->rdbuf()->sungetc() == traits_type::eof())
__state |= ios_base::badbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
}
else
@@ -1204,8 +1204,8 @@ basic_istream<_CharT, _Traits>::sync()
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
if (this->rdbuf() == nullptr)
return -1;
@@ -1215,16 +1215,16 @@ basic_istream<_CharT, _Traits>::sync()
return -1;
}
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
this->setstate(__state);
}
@@ -1241,21 +1241,21 @@ basic_istream<_CharT, _Traits>::tellg()
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
- __r = this->rdbuf()->pubseekoff(0, ios_base::cur, ios_base::in);
+ __r = this->rdbuf()->pubseekoff(0, ios_base::cur, ios_base::in);
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
this->setstate(__state);
}
@@ -1272,22 +1272,22 @@ basic_istream<_CharT, _Traits>::seekg(pos_type __pos)
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
if (this->rdbuf()->pubseekpos(__pos, ios_base::in) == pos_type(-1))
__state |= ios_base::failbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
this->setstate(__state);
}
@@ -1304,22 +1304,22 @@ basic_istream<_CharT, _Traits>::seekg(off_type __off, ios_base::seekdir __dir)
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
if (this->rdbuf()->pubseekoff(__off, __dir, ios_base::in) == pos_type(-1))
__state |= ios_base::failbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
this->__setstate_nothrow(__state);
if (this->exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
this->setstate(__state);
}
@@ -1335,8 +1335,8 @@ ws(basic_istream<_CharT, _Traits>& __is)
if (__sen)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
- try
- {
+ try
+ {
#endif // _LIBCPP_NO_EXCEPTIONS
const ctype<_CharT>& __ct = use_facet<ctype<_CharT> >(__is.getloc());
while (true)
@@ -1352,16 +1352,16 @@ ws(basic_istream<_CharT, _Traits>& __is)
__is.rdbuf()->sbumpc();
}
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
__is.__setstate_nothrow(__state);
if (__is.exceptions() & ios_base::badbit)
{
throw;
}
- }
+ }
#endif // _LIBCPP_NO_EXCEPTIONS
__is.setstate(__state);
}
@@ -1445,9 +1445,9 @@ operator>>(basic_istream<_CharT, _Traits>& __is,
basic_string<_CharT, _Traits, _Allocator>& __str)
{
ios_base::iostate __state = ios_base::goodbit;
- typename basic_istream<_CharT, _Traits>::sentry __sen(__is);
- if (__sen)
- {
+ typename basic_istream<_CharT, _Traits>::sentry __sen(__is);
+ if (__sen)
+ {
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
@@ -1479,9 +1479,9 @@ operator>>(basic_istream<_CharT, _Traits>& __is,
if (__c == 0)
__state |= ios_base::failbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
__is.__setstate_nothrow(__state);
if (__is.exceptions() & ios_base::badbit)
@@ -1501,9 +1501,9 @@ getline(basic_istream<_CharT, _Traits>& __is,
basic_string<_CharT, _Traits, _Allocator>& __str, _CharT __dlm)
{
ios_base::iostate __state = ios_base::goodbit;
- typename basic_istream<_CharT, _Traits>::sentry __sen(__is, true);
- if (__sen)
- {
+ typename basic_istream<_CharT, _Traits>::sentry __sen(__is, true);
+ if (__sen)
+ {
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
@@ -1532,9 +1532,9 @@ getline(basic_istream<_CharT, _Traits>& __is,
if (__extr == 0)
__state |= ios_base::failbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
__is.__setstate_nothrow(__state);
if (__is.exceptions() & ios_base::badbit)
@@ -1580,9 +1580,9 @@ basic_istream<_CharT, _Traits>&
operator>>(basic_istream<_CharT, _Traits>& __is, bitset<_Size>& __x)
{
ios_base::iostate __state = ios_base::goodbit;
- typename basic_istream<_CharT, _Traits>::sentry __sen(__is);
- if (__sen)
- {
+ typename basic_istream<_CharT, _Traits>::sentry __sen(__is);
+ if (__sen)
+ {
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
@@ -1611,9 +1611,9 @@ operator>>(basic_istream<_CharT, _Traits>& __is, bitset<_Size>& __x)
if (_Size > 0 && __c == 0)
__state |= ios_base::failbit;
#ifndef _LIBCPP_NO_EXCEPTIONS
- }
- catch (...)
- {
+ }
+ catch (...)
+ {
__state |= ios_base::badbit;
__is.__setstate_nothrow(__state);
if (__is.exceptions() & ios_base::badbit)
diff --git a/contrib/libs/cxxsupp/libcxx/include/list b/contrib/libs/cxxsupp/libcxx/include/list
index 8c6c95a04a..71406c6743 100644
--- a/contrib/libs/cxxsupp/libcxx/include/list
+++ b/contrib/libs/cxxsupp/libcxx/include/list
@@ -2021,22 +2021,22 @@ list<_Tp, _Alloc>::splice(const_iterator __p, list& __c)
__c.__sz() = 0;
#if _LIBCPP_DEBUG_LEVEL == 2
if (&__c != this) {
- __libcpp_db* __db = __get_db();
- __c_node* __cn1 = __db->__find_c_and_lock(this);
- __c_node* __cn2 = __db->__find_c(&__c);
- for (__i_node** __ip = __cn2->end_; __ip != __cn2->beg_;)
+ __libcpp_db* __db = __get_db();
+ __c_node* __cn1 = __db->__find_c_and_lock(this);
+ __c_node* __cn2 = __db->__find_c(&__c);
+ for (__i_node** __ip = __cn2->end_; __ip != __cn2->beg_;)
{
- --__ip;
- iterator* __i = static_cast<iterator*>((*__ip)->__i_);
- if (__i->__ptr_ != __c.__end_as_link())
- {
- __cn1->__add(*__ip);
- (*__ip)->__c_ = __cn1;
- if (--__cn2->end_ != __ip)
- memmove(__ip, __ip+1, (__cn2->end_ - __ip)*sizeof(__i_node*));
- }
+ --__ip;
+ iterator* __i = static_cast<iterator*>((*__ip)->__i_);
+ if (__i->__ptr_ != __c.__end_as_link())
+ {
+ __cn1->__add(*__ip);
+ (*__ip)->__c_ = __cn1;
+ if (--__cn2->end_ != __ip)
+ memmove(__ip, __ip+1, (__cn2->end_ - __ip)*sizeof(__i_node*));
+ }
}
- __db->unlock();
+ __db->unlock();
}
#endif
}
@@ -2066,22 +2066,22 @@ list<_Tp, _Alloc>::splice(const_iterator __p, list& __c, const_iterator __i)
++base::__sz();
#if _LIBCPP_DEBUG_LEVEL == 2
if (&__c != this) {
- __libcpp_db* __db = __get_db();
- __c_node* __cn1 = __db->__find_c_and_lock(this);
- __c_node* __cn2 = __db->__find_c(&__c);
- for (__i_node** __ip = __cn2->end_; __ip != __cn2->beg_;)
+ __libcpp_db* __db = __get_db();
+ __c_node* __cn1 = __db->__find_c_and_lock(this);
+ __c_node* __cn2 = __db->__find_c(&__c);
+ for (__i_node** __ip = __cn2->end_; __ip != __cn2->beg_;)
{
- --__ip;
- iterator* __j = static_cast<iterator*>((*__ip)->__i_);
- if (__j->__ptr_ == __f)
- {
- __cn1->__add(*__ip);
- (*__ip)->__c_ = __cn1;
- if (--__cn2->end_ != __ip)
- _VSTD::memmove(__ip, __ip+1, (__cn2->end_ - __ip)*sizeof(__i_node*));
- }
+ --__ip;
+ iterator* __j = static_cast<iterator*>((*__ip)->__i_);
+ if (__j->__ptr_ == __f)
+ {
+ __cn1->__add(*__ip);
+ (*__ip)->__c_ = __cn1;
+ if (--__cn2->end_ != __ip)
+ _VSTD::memmove(__ip, __ip+1, (__cn2->end_ - __ip)*sizeof(__i_node*));
+ }
}
- __db->unlock();
+ __db->unlock();
}
#endif
}
@@ -2125,26 +2125,26 @@ list<_Tp, _Alloc>::splice(const_iterator __p, list& __c, const_iterator __f, con
__link_nodes(__p.__ptr_, __first, __last);
#if _LIBCPP_DEBUG_LEVEL == 2
if (&__c != this) {
- __libcpp_db* __db = __get_db();
- __c_node* __cn1 = __db->__find_c_and_lock(this);
- __c_node* __cn2 = __db->__find_c(&__c);
- for (__i_node** __ip = __cn2->end_; __ip != __cn2->beg_;)
+ __libcpp_db* __db = __get_db();
+ __c_node* __cn1 = __db->__find_c_and_lock(this);
+ __c_node* __cn2 = __db->__find_c(&__c);
+ for (__i_node** __ip = __cn2->end_; __ip != __cn2->beg_;)
{
- --__ip;
- iterator* __j = static_cast<iterator*>((*__ip)->__i_);
- for (__link_pointer __k = __f.__ptr_;
- __k != __l.__ptr_; __k = __k->__next_)
+ --__ip;
+ iterator* __j = static_cast<iterator*>((*__ip)->__i_);
+ for (__link_pointer __k = __f.__ptr_;
+ __k != __l.__ptr_; __k = __k->__next_)
{
- if (__j->__ptr_ == __k)
- {
- __cn1->__add(*__ip);
- (*__ip)->__c_ = __cn1;
- if (--__cn2->end_ != __ip)
- _VSTD::memmove(__ip, __ip+1, (__cn2->end_ - __ip)*sizeof(__i_node*));
- }
+ if (__j->__ptr_ == __k)
+ {
+ __cn1->__add(*__ip);
+ (*__ip)->__c_ = __cn1;
+ if (--__cn2->end_ != __ip)
+ _VSTD::memmove(__ip, __ip+1, (__cn2->end_ - __ip)*sizeof(__i_node*));
+ }
}
}
- __db->unlock();
+ __db->unlock();
}
#endif
}
diff --git a/contrib/libs/cxxsupp/libcxx/include/locale b/contrib/libs/cxxsupp/libcxx/include/locale
index 29fc1acd27..242790a9d4 100644
--- a/contrib/libs/cxxsupp/libcxx/include/locale
+++ b/contrib/libs/cxxsupp/libcxx/include/locale
@@ -891,7 +891,7 @@ num_get<_CharT, _InputIterator>::do_get(iter_type __b, iter_type __e,
typedef typename numpunct<_CharT>::string_type string_type;
const string_type __names[2] = {__np.truename(), __np.falsename()};
const string_type* __i = _VSTD::__scan_keyword(__b, __e, __names, __names+2,
- __ct, __err);
+ __ct, __err);
__v = __i == __names;
return __b;
}
diff --git a/contrib/libs/cxxsupp/libcxx/include/locale.h b/contrib/libs/cxxsupp/libcxx/include/locale.h
index f3f0eccacf..52c452001d 100644
--- a/contrib/libs/cxxsupp/libcxx/include/locale.h
+++ b/contrib/libs/cxxsupp/libcxx/include/locale.h
@@ -40,7 +40,7 @@ Functions:
#endif
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
-# pragma GCC system_header
+# pragma GCC system_header
#endif
#ifdef _LIBCPP_COMPILER_MSVC
diff --git a/contrib/libs/cxxsupp/libcxx/include/map b/contrib/libs/cxxsupp/libcxx/include/map
index 4ecf3954d1..c78a7ee31a 100644
--- a/contrib/libs/cxxsupp/libcxx/include/map
+++ b/contrib/libs/cxxsupp/libcxx/include/map
@@ -1301,7 +1301,7 @@ public:
__r->__get_value().second = _VSTD::forward<_Vp>(__v);
return __r;
- }
+ }
template <class _Vp>
_LIBCPP_INLINE_VISIBILITY iterator insert_or_assign(const_iterator __h,
@@ -1314,7 +1314,7 @@ public:
__r->__get_value().second = _VSTD::forward<_Vp>(__v);
return __r;
- }
+ }
#endif // _LIBCPP_STD_VER > 14
diff --git a/contrib/libs/cxxsupp/libcxx/include/memory b/contrib/libs/cxxsupp/libcxx/include/memory
index 0633f1fc3a..1975092ba0 100644
--- a/contrib/libs/cxxsupp/libcxx/include/memory
+++ b/contrib/libs/cxxsupp/libcxx/include/memory
@@ -122,7 +122,7 @@ public:
typedef typename add_lvalue_reference<const T>::type
const_reference; // deprecated in C++17, removed in C++20
- typedef T value_type;
+ typedef T value_type;
template <class U> struct rebind {typedef allocator<U> other;}; // deprecated in C++17, removed in C++20
@@ -342,7 +342,7 @@ public:
pointer release() noexcept;
void reset(pointer p = pointer()) noexcept;
void reset(nullptr_t) noexcept;
- template <class U> void reset(U) = delete;
+ template <class U> void reset(U) = delete;
void swap(unique_ptr& u) noexcept;
};
@@ -567,7 +567,7 @@ template<class T> void swap(weak_ptr<T>& a, weak_ptr<T>& b) noexcept;
template<class T> struct owner_less;
template<class T>
-struct owner_less<shared_ptr<T> >
+struct owner_less<shared_ptr<T> >
: binary_function<shared_ptr<T>, shared_ptr<T>, bool>
{
typedef bool result_type;
@@ -577,7 +577,7 @@ struct owner_less<shared_ptr<T> >
};
template<class T>
-struct owner_less<weak_ptr<T> >
+struct owner_less<weak_ptr<T> >
: binary_function<weak_ptr<T>, weak_ptr<T>, bool>
{
typedef bool result_type;
diff --git a/contrib/libs/cxxsupp/libcxx/include/mutex b/contrib/libs/cxxsupp/libcxx/include/mutex
index a2edfa4240..e815dda502 100644
--- a/contrib/libs/cxxsupp/libcxx/include/mutex
+++ b/contrib/libs/cxxsupp/libcxx/include/mutex
@@ -580,14 +580,14 @@ struct _LIBCPP_TEMPLATE_VIS once_flag
_LIBCPP_INLINE_VISIBILITY
_LIBCPP_CONSTEXPR
once_flag() _NOEXCEPT : __state_(0) {}
-
+
#if defined(_LIBCPP_ABI_MICROSOFT)
- typedef uintptr_t _State_type;
+ typedef uintptr_t _State_type;
#else
- typedef unsigned long _State_type;
+ typedef unsigned long _State_type;
#endif
-
+
private:
once_flag(const once_flag&); // = delete;
once_flag& operator=(const once_flag&); // = delete;
@@ -668,10 +668,10 @@ __call_once_proxy(void* __vp)
#ifdef _LIBCPP_ABI_MICROSOFT
_LIBCPP_FUNC_VIS void __call_once(volatile atomic<once_flag::_State_type>&, void*,
- void (*)(void*));
+ void (*)(void*));
#else
_LIBCPP_FUNC_VIS void __call_once(volatile once_flag::_State_type&, void*,
- void (*)(void*));
+ void (*)(void*));
#endif
#ifndef _LIBCPP_CXX03_LANG
diff --git a/contrib/libs/cxxsupp/libcxx/include/numeric b/contrib/libs/cxxsupp/libcxx/include/numeric
index e4ab8e70f0..8ea7ecc375 100644
--- a/contrib/libs/cxxsupp/libcxx/include/numeric
+++ b/contrib/libs/cxxsupp/libcxx/include/numeric
@@ -368,7 +368,7 @@ _OutputIterator inclusive_scan(_InputIterator __first, _InputIterator __last,
for (; __first != __last; ++__first, (void) ++__result) {
__init = __b(__init, *__first);
*__result = __init;
- }
+ }
return __result;
}
@@ -382,7 +382,7 @@ _OutputIterator inclusive_scan(_InputIterator __first, _InputIterator __last,
*__result++ = __init;
if (++__first != __last)
return _VSTD::inclusive_scan(__first, __last, __result, __b, __init);
- }
+ }
return __result;
}
@@ -442,7 +442,7 @@ transform_inclusive_scan(_InputIterator __first, _InputIterator __last,
*__result++ = __init;
if (++__first != __last)
return _VSTD::transform_inclusive_scan(__first, __last, __result, __b, __u, __init);
- }
+ }
return __result;
}
@@ -513,9 +513,9 @@ struct __ct_abs<_Result, _Source, true> {
_LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY
_Result operator()(_Source __t) const noexcept
{
- if (__t >= 0) return __t;
- if (__t == numeric_limits<_Source>::min()) return -static_cast<_Result>(__t);
- return -__t;
+ if (__t >= 0) return __t;
+ if (__t == numeric_limits<_Source>::min()) return -static_cast<_Result>(__t);
+ return -__t;
}
};
@@ -614,8 +614,8 @@ _LIBCPP_INLINE_VISIBILITY constexpr
enable_if_t<is_floating_point_v<_Fp>, _Fp>
midpoint(_Fp __a, _Fp __b) noexcept
{
- constexpr _Fp __lo = numeric_limits<_Fp>::min()*2;
- constexpr _Fp __hi = numeric_limits<_Fp>::max()/2;
+ constexpr _Fp __lo = numeric_limits<_Fp>::min()*2;
+ constexpr _Fp __hi = numeric_limits<_Fp>::max()/2;
return __fp_abs(__a) <= __hi && __fp_abs(__b) <= __hi ? // typical case: overflow is impossible
(__a + __b)/2 : // always correctly rounded
__fp_abs(__a) < __lo ? __a + __b/2 : // not safe to halve a
diff --git a/contrib/libs/cxxsupp/libcxx/include/optional b/contrib/libs/cxxsupp/libcxx/include/optional
index a99ccae0e9..0f6d233051 100644
--- a/contrib/libs/cxxsupp/libcxx/include/optional
+++ b/contrib/libs/cxxsupp/libcxx/include/optional
@@ -321,7 +321,7 @@ struct __optional_storage_base : __optional_destruct_base<_Tp>
#if _LIBCPP_STD_VER > 17
_VSTD::construct_at(_VSTD::addressof(this->__val_), _VSTD::forward<_Args>(__args)...);
#else
- ::new ((void*)_VSTD::addressof(this->__val_)) value_type(_VSTD::forward<_Args>(__args)...);
+ ::new ((void*)_VSTD::addressof(this->__val_)) value_type(_VSTD::forward<_Args>(__args)...);
#endif
this->__engaged_ = true;
}
diff --git a/contrib/libs/cxxsupp/libcxx/include/queue b/contrib/libs/cxxsupp/libcxx/include/queue
index 834115900e..cbd07140a7 100644
--- a/contrib/libs/cxxsupp/libcxx/include/queue
+++ b/contrib/libs/cxxsupp/libcxx/include/queue
@@ -70,8 +70,8 @@ public:
template<class Container>
queue(Container) -> queue<typename Container::value_type, Container>; // C++17
-
-template<class Container, class Allocator>
+
+template<class Container, class Allocator>
queue(Container, Allocator) -> queue<typename Container::value_type, Container>; // C++17
template <class T, class Container>
@@ -170,13 +170,13 @@ public:
template <class Compare, class Container>
priority_queue(Compare, Container)
-> priority_queue<typename Container::value_type, Container, Compare>; // C++17
-
-template<class InputIterator,
+
+template<class InputIterator,
class Compare = less<iter-value-type<InputIterator>>,
class Container = vector<iter-value-type<InputIterator>>>
priority_queue(InputIterator, InputIterator, Compare = Compare(), Container = Container())
-> priority_queue<iter-value-type<InputIterator>, Container, Compare>; // C++17
-
+
template<class Compare, class Container, class Allocator>
priority_queue(Compare, Container, Allocator)
-> priority_queue<typename Container::value_type, Container, Compare>; // C++17
@@ -364,7 +364,7 @@ template<class _Container,
>
queue(_Container)
-> queue<typename _Container::value_type, _Container>;
-
+
template<class _Container,
class _Alloc,
class = enable_if_t<!__is_allocator<_Container>::value>,
@@ -592,8 +592,8 @@ template <class _Compare,
>
priority_queue(_Compare, _Container)
-> priority_queue<typename _Container::value_type, _Container, _Compare>;
-
-template<class _InputIterator,
+
+template<class _InputIterator,
class _Compare = less<__iter_value_type<_InputIterator>>,
class _Container = vector<__iter_value_type<_InputIterator>>,
class = enable_if_t<__is_cpp17_input_iterator<_InputIterator>::value>,
@@ -602,8 +602,8 @@ template<class _InputIterator,
>
priority_queue(_InputIterator, _InputIterator, _Compare = _Compare(), _Container = _Container())
-> priority_queue<__iter_value_type<_InputIterator>, _Container, _Compare>;
-
-template<class _Compare,
+
+template<class _Compare,
class _Container,
class _Alloc,
class = enable_if_t<!__is_allocator<_Compare>::value>,
diff --git a/contrib/libs/cxxsupp/libcxx/include/random b/contrib/libs/cxxsupp/libcxx/include/random
index e7ca4a9aa8..1320250897 100644
--- a/contrib/libs/cxxsupp/libcxx/include/random
+++ b/contrib/libs/cxxsupp/libcxx/include/random
@@ -6701,7 +6701,7 @@ public:
template<class _UnaryOperation>
param_type(size_t __nw, result_type __xmin, result_type __xmax,
_UnaryOperation __fw);
- param_type(param_type const&) = default;
+ param_type(param_type const&) = default;
param_type & operator=(const param_type& __rhs);
_LIBCPP_INLINE_VISIBILITY
diff --git a/contrib/libs/cxxsupp/libcxx/include/regex b/contrib/libs/cxxsupp/libcxx/include/regex
index a75e04fea1..c0d1edac5e 100644
--- a/contrib/libs/cxxsupp/libcxx/include/regex
+++ b/contrib/libs/cxxsupp/libcxx/include/regex
@@ -171,14 +171,14 @@ public:
// assign:
basic_regex& assign(const basic_regex& that);
basic_regex& assign(basic_regex&& that) noexcept;
- basic_regex& assign(const charT* ptr, flag_type f = regex_constants::ECMAScript);
+ basic_regex& assign(const charT* ptr, flag_type f = regex_constants::ECMAScript);
basic_regex& assign(const charT* p, size_t len, flag_type f = regex_constants::ECMAScript);
template <class string_traits, class A>
basic_regex& assign(const basic_string<charT, string_traits, A>& s,
- flag_type f = regex_constants::ECMAScript);
+ flag_type f = regex_constants::ECMAScript);
template <class InputIterator>
basic_regex& assign(InputIterator first, InputIterator last,
- flag_type f = regex_constants::ECMAScript);
+ flag_type f = regex_constants::ECMAScript);
basic_regex& assign(initializer_list<charT>, flag_type f = regex_constants::ECMAScript);
// const operations:
@@ -702,7 +702,7 @@ typedef regex_iterator<string::const_iterator> sregex_iterator;
typedef regex_iterator<wstring::const_iterator> wsregex_iterator;
template <class BidirectionalIterator,
- class charT = typename iterator_traits<BidirectionalIterator>::value_type,
+ class charT = typename iterator_traits<BidirectionalIterator>::value_type,
class traits = regex_traits<charT>>
class regex_token_iterator
{
diff --git a/contrib/libs/cxxsupp/libcxx/include/set b/contrib/libs/cxxsupp/libcxx/include/set
index 6354765c10..46b515ba53 100644
--- a/contrib/libs/cxxsupp/libcxx/include/set
+++ b/contrib/libs/cxxsupp/libcxx/include/set
@@ -156,7 +156,7 @@ public:
const_iterator find(const K& x) const; // C++14
template<typename K>
- size_type count(const K& x) const; // C++14
+ size_type count(const K& x) const; // C++14
size_type count(const key_type& k) const;
bool contains(const key_type& x) const; // C++20
diff --git a/contrib/libs/cxxsupp/libcxx/include/span b/contrib/libs/cxxsupp/libcxx/include/span
index eb1aff44c0..5d57bd693c 100644
--- a/contrib/libs/cxxsupp/libcxx/include/span
+++ b/contrib/libs/cxxsupp/libcxx/include/span
@@ -104,7 +104,7 @@ public:
constexpr reverse_iterator rend() const noexcept;
private:
- pointer data_; // exposition only
+ pointer data_; // exposition only
size_type size_; // exposition only
};
@@ -321,7 +321,7 @@ public:
template <size_t _Count>
_LIBCPP_INLINE_VISIBILITY
- constexpr span<element_type, _Count> first() const noexcept
+ constexpr span<element_type, _Count> first() const noexcept
{
static_assert(_Count <= _Extent, "Count out of range in span::first()");
return span<element_type, _Count>{data(), _Count};
@@ -329,7 +329,7 @@ public:
template <size_t _Count>
_LIBCPP_INLINE_VISIBILITY
- constexpr span<element_type, _Count> last() const noexcept
+ constexpr span<element_type, _Count> last() const noexcept
{
static_assert(_Count <= _Extent, "Count out of range in span::last()");
return span<element_type, _Count>{data() + size() - _Count, _Count};
@@ -351,7 +351,7 @@ public:
template <size_t _Offset, size_t _Count = dynamic_extent>
_LIBCPP_INLINE_VISIBILITY
- constexpr auto subspan() const noexcept
+ constexpr auto subspan() const noexcept
-> span<element_type, _Count != dynamic_extent ? _Count : _Extent - _Offset>
{
static_assert(_Offset <= _Extent, "Offset out of range in span::subspan()");
@@ -376,7 +376,7 @@ public:
_LIBCPP_INLINE_VISIBILITY constexpr size_type size() const noexcept { return _Extent; }
_LIBCPP_INLINE_VISIBILITY constexpr size_type size_bytes() const noexcept { return _Extent * sizeof(element_type); }
- _LIBCPP_INLINE_VISIBILITY constexpr bool empty() const noexcept { return _Extent == 0; }
+ _LIBCPP_INLINE_VISIBILITY constexpr bool empty() const noexcept { return _Extent == 0; }
_LIBCPP_INLINE_VISIBILITY constexpr reference operator[](size_type __idx) const noexcept
{
@@ -469,17 +469,17 @@ public:
template <size_t _Sz>
_LIBCPP_INLINE_VISIBILITY
- constexpr span(element_type (&__arr)[_Sz]) noexcept : __data{__arr}, __size{_Sz} {}
+ constexpr span(element_type (&__arr)[_Sz]) noexcept : __data{__arr}, __size{_Sz} {}
template <class _OtherElementType, size_t _Sz,
enable_if_t<is_convertible_v<_OtherElementType(*)[], element_type (*)[]>, nullptr_t> = nullptr>
_LIBCPP_INLINE_VISIBILITY
- constexpr span(array<_OtherElementType, _Sz>& __arr) noexcept : __data{__arr.data()}, __size{_Sz} {}
+ constexpr span(array<_OtherElementType, _Sz>& __arr) noexcept : __data{__arr.data()}, __size{_Sz} {}
template <class _OtherElementType, size_t _Sz,
enable_if_t<is_convertible_v<const _OtherElementType(*)[], element_type (*)[]>, nullptr_t> = nullptr>
_LIBCPP_INLINE_VISIBILITY
- constexpr span(const array<_OtherElementType, _Sz>& __arr) noexcept : __data{__arr.data()}, __size{_Sz} {}
+ constexpr span(const array<_OtherElementType, _Sz>& __arr) noexcept : __data{__arr.data()}, __size{_Sz} {}
#if !defined(_LIBCPP_HAS_NO_RANGES)
template <__span_compatible_range<element_type> _Range>
@@ -562,7 +562,7 @@ public:
_LIBCPP_INLINE_VISIBILITY constexpr size_type size() const noexcept { return __size; }
_LIBCPP_INLINE_VISIBILITY constexpr size_type size_bytes() const noexcept { return __size * sizeof(element_type); }
- _LIBCPP_INLINE_VISIBILITY constexpr bool empty() const noexcept { return __size == 0; }
+ _LIBCPP_INLINE_VISIBILITY constexpr bool empty() const noexcept { return __size == 0; }
_LIBCPP_INLINE_VISIBILITY constexpr reference operator[](size_type __idx) const noexcept
{
@@ -596,7 +596,7 @@ public:
inline _LIBCPP_INLINE_VISIBILITY span<byte, dynamic_extent> __as_writable_bytes() const noexcept;
private:
- pointer __data;
+ pointer __data;
size_type __size;
};
@@ -621,7 +621,7 @@ template <class _Tp, size_t _Extent>
_LIBCPP_INLINE_VISIBILITY
auto as_bytes(span<_Tp, _Extent> __s) noexcept
-> decltype(__s.__as_bytes())
-{ return __s.__as_bytes(); }
+{ return __s.__as_bytes(); }
template <class _Tp, size_t _Extent>
_LIBCPP_INLINE_VISIBILITY
diff --git a/contrib/libs/cxxsupp/libcxx/include/sstream b/contrib/libs/cxxsupp/libcxx/include/sstream
index a130aa97d7..fbe5ffcab4 100644
--- a/contrib/libs/cxxsupp/libcxx/include/sstream
+++ b/contrib/libs/cxxsupp/libcxx/include/sstream
@@ -256,7 +256,7 @@ protected:
virtual pos_type seekpos(pos_type __sp,
ios_base::openmode __wch = ios_base::in | ios_base::out) {
return seekoff(__sp, ios_base::beg, __wch);
- }
+ }
};
template <class _CharT, class _Traits, class _Allocator>
@@ -656,31 +656,31 @@ public:
basic_istringstream(basic_istringstream&& __rhs)
: basic_istream<_CharT, _Traits>(_VSTD::move(__rhs))
, __sb_(_VSTD::move(__rhs.__sb_))
- {
- basic_istream<_CharT, _Traits>::set_rdbuf(&__sb_);
- }
+ {
+ basic_istream<_CharT, _Traits>::set_rdbuf(&__sb_);
+ }
// 27.8.2.2 Assign and swap:
basic_istringstream& operator=(basic_istringstream&& __rhs) {
- basic_istream<char_type, traits_type>::operator=(_VSTD::move(__rhs));
- __sb_ = _VSTD::move(__rhs.__sb_);
- return *this;
- }
+ basic_istream<char_type, traits_type>::operator=(_VSTD::move(__rhs));
+ __sb_ = _VSTD::move(__rhs.__sb_);
+ return *this;
+ }
_LIBCPP_INLINE_VISIBILITY
void swap(basic_istringstream& __rhs) {
- basic_istream<char_type, traits_type>::swap(__rhs);
- __sb_.swap(__rhs.__sb_);
- }
+ basic_istream<char_type, traits_type>::swap(__rhs);
+ __sb_.swap(__rhs.__sb_);
+ }
// 27.8.2.3 Members:
_LIBCPP_INLINE_VISIBILITY
basic_stringbuf<char_type, traits_type, allocator_type>* rdbuf() const {
- return const_cast<basic_stringbuf<char_type, traits_type, allocator_type>*>(&__sb_);
- }
+ return const_cast<basic_stringbuf<char_type, traits_type, allocator_type>*>(&__sb_);
+ }
_LIBCPP_INLINE_VISIBILITY
string_type str() const {
- return __sb_.str();
- }
+ return __sb_.str();
+ }
_LIBCPP_INLINE_VISIBILITY
void str(const string_type& __s) {
__sb_.str(__s);
@@ -736,32 +736,32 @@ public:
basic_ostringstream(basic_ostringstream&& __rhs)
: basic_ostream<_CharT, _Traits>(_VSTD::move(__rhs))
, __sb_(_VSTD::move(__rhs.__sb_))
- {
- basic_ostream<_CharT, _Traits>::set_rdbuf(&__sb_);
- }
+ {
+ basic_ostream<_CharT, _Traits>::set_rdbuf(&__sb_);
+ }
// 27.8.2.2 Assign and swap:
basic_ostringstream& operator=(basic_ostringstream&& __rhs) {
- basic_ostream<char_type, traits_type>::operator=(_VSTD::move(__rhs));
- __sb_ = _VSTD::move(__rhs.__sb_);
- return *this;
- }
+ basic_ostream<char_type, traits_type>::operator=(_VSTD::move(__rhs));
+ __sb_ = _VSTD::move(__rhs.__sb_);
+ return *this;
+ }
_LIBCPP_INLINE_VISIBILITY
void swap(basic_ostringstream& __rhs) {
- basic_ostream<char_type, traits_type>::swap(__rhs);
- __sb_.swap(__rhs.__sb_);
- }
+ basic_ostream<char_type, traits_type>::swap(__rhs);
+ __sb_.swap(__rhs.__sb_);
+ }
// 27.8.2.3 Members:
_LIBCPP_INLINE_VISIBILITY
basic_stringbuf<char_type, traits_type, allocator_type>* rdbuf() const {
- return const_cast<basic_stringbuf<char_type, traits_type, allocator_type>*>(&__sb_);
- }
+ return const_cast<basic_stringbuf<char_type, traits_type, allocator_type>*>(&__sb_);
+ }
_LIBCPP_INLINE_VISIBILITY
string_type str() const {
- return __sb_.str();
- }
+ return __sb_.str();
+ }
_LIBCPP_INLINE_VISIBILITY
void str(const string_type& __s) {
__sb_.str(__s);
@@ -817,31 +817,31 @@ public:
basic_stringstream(basic_stringstream&& __rhs)
: basic_iostream<_CharT, _Traits>(_VSTD::move(__rhs))
, __sb_(_VSTD::move(__rhs.__sb_))
- {
- basic_istream<_CharT, _Traits>::set_rdbuf(&__sb_);
- }
+ {
+ basic_istream<_CharT, _Traits>::set_rdbuf(&__sb_);
+ }
// 27.8.2.2 Assign and swap:
basic_stringstream& operator=(basic_stringstream&& __rhs) {
- basic_iostream<char_type, traits_type>::operator=(_VSTD::move(__rhs));
- __sb_ = _VSTD::move(__rhs.__sb_);
- return *this;
- }
+ basic_iostream<char_type, traits_type>::operator=(_VSTD::move(__rhs));
+ __sb_ = _VSTD::move(__rhs.__sb_);
+ return *this;
+ }
_LIBCPP_INLINE_VISIBILITY
void swap(basic_stringstream& __rhs) {
- basic_iostream<char_type, traits_type>::swap(__rhs);
- __sb_.swap(__rhs.__sb_);
- }
+ basic_iostream<char_type, traits_type>::swap(__rhs);
+ __sb_.swap(__rhs.__sb_);
+ }
// 27.8.2.3 Members:
_LIBCPP_INLINE_VISIBILITY
basic_stringbuf<char_type, traits_type, allocator_type>* rdbuf() const {
- return const_cast<basic_stringbuf<char_type, traits_type, allocator_type>*>(&__sb_);
- }
+ return const_cast<basic_stringbuf<char_type, traits_type, allocator_type>*>(&__sb_);
+ }
_LIBCPP_INLINE_VISIBILITY
string_type str() const {
- return __sb_.str();
- }
+ return __sb_.str();
+ }
_LIBCPP_INLINE_VISIBILITY
void str(const string_type& __s) {
__sb_.str(__s);
diff --git a/contrib/libs/cxxsupp/libcxx/include/stack b/contrib/libs/cxxsupp/libcxx/include/stack
index 866fbd6b83..436993c6f3 100644
--- a/contrib/libs/cxxsupp/libcxx/include/stack
+++ b/contrib/libs/cxxsupp/libcxx/include/stack
@@ -62,8 +62,8 @@ public:
template<class Container>
stack(Container) -> stack<typename Container::value_type, Container>; // C++17
-
-template<class Container, class Allocator>
+
+template<class Container, class Allocator>
stack(Container, Allocator) -> stack<typename Container::value_type, Container>; // C++17
template <class T, class Container>
@@ -120,7 +120,7 @@ public:
typedef typename container_type::const_reference const_reference;
typedef typename container_type::size_type size_type;
static_assert((is_same<_Tp, value_type>::value), "" );
-
+
protected:
container_type c;
@@ -237,12 +237,12 @@ template<class _Container,
>
stack(_Container)
-> stack<typename _Container::value_type, _Container>;
-
+
template<class _Container,
class _Alloc,
class = enable_if_t<!__is_allocator<_Container>::value>,
class = enable_if_t<uses_allocator<_Container, _Alloc>::value>
- >
+ >
stack(_Container, _Alloc)
-> stack<typename _Container::value_type, _Container>;
#endif
diff --git a/contrib/libs/cxxsupp/libcxx/include/string b/contrib/libs/cxxsupp/libcxx/include/string
index 1a951b9d25..4f3309fea9 100644
--- a/contrib/libs/cxxsupp/libcxx/include/string
+++ b/contrib/libs/cxxsupp/libcxx/include/string
@@ -880,7 +880,7 @@ public:
template<class _Tp, class = __enable_if_t<__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value && !__is_same_uncvref<_Tp, basic_string>::value> >
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
basic_string(const _Tp& __t, size_type __pos, size_type __n,
- const allocator_type& __a = allocator_type());
+ const allocator_type& __a = allocator_type());
template<class _Tp, class = __enable_if_t<__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value &&
!__is_same_uncvref<_Tp, basic_string>::value> >
@@ -2379,18 +2379,18 @@ template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::__assign_external(
const value_type* __s, size_type __n) {
- size_type __cap = capacity();
+ size_type __cap = capacity();
if (__cap >= __n) {
- value_type* __p = _VSTD::__to_address(__get_pointer());
- traits_type::move(__p, __s, __n);
- traits_type::assign(__p[__n], value_type());
- __set_size(__n);
- __invalidate_iterators_past(__n);
+ value_type* __p = _VSTD::__to_address(__get_pointer());
+ traits_type::move(__p, __s, __n);
+ traits_type::assign(__p[__n], value_type());
+ __set_size(__n);
+ __invalidate_iterators_past(__n);
} else {
- size_type __sz = size();
- __grow_by_and_replace(__cap, __n - __cap, __sz, 0, __sz, __n, __s);
- }
- return *this;
+ size_type __sz = size();
+ __grow_by_and_replace(__cap, __n - __cap, __sz, 0, __sz, __n, __s);
+ }
+ return *this;
}
template <class _CharT, class _Traits, class _Allocator>
@@ -2495,7 +2495,7 @@ basic_string<_CharT, _Traits, _Allocator>::__move_assign(basic_string& __str, tr
}
#endif
}
- __move_assign_alloc(__str);
+ __move_assign_alloc(__str);
__r_.first() = __str.__r_.first();
__str.__set_short_size(0);
traits_type::assign(__str.__get_short_pointer()[0], value_type());
@@ -3219,7 +3219,7 @@ basic_string<_CharT, _Traits, _Allocator>::erase(size_type __pos,
} else {
__erase_external_with_move(__pos, __n);
}
- return *this;
+ return *this;
}
template <class _CharT, class _Traits, class _Allocator>
@@ -3386,55 +3386,55 @@ basic_string<_CharT, _Traits, _Allocator>::__shrink_or_extend(size_type __target
size_type __cap = capacity();
size_type __sz = size();
- pointer __new_data, __p;
- bool __was_long, __now_long;
+ pointer __new_data, __p;
+ bool __was_long, __now_long;
if (__target_capacity == __min_cap - 1)
- {
- __was_long = true;
- __now_long = false;
- __new_data = __get_short_pointer();
- __p = __get_long_pointer();
- }
- else
- {
- if (__target_capacity > __cap)
- __new_data = __alloc_traits::allocate(__alloc(), __target_capacity+1);
+ {
+ __was_long = true;
+ __now_long = false;
+ __new_data = __get_short_pointer();
+ __p = __get_long_pointer();
+ }
+ else
+ {
+ if (__target_capacity > __cap)
+ __new_data = __alloc_traits::allocate(__alloc(), __target_capacity+1);
else
{
- #ifndef _LIBCPP_NO_EXCEPTIONS
- try
+ #ifndef _LIBCPP_NO_EXCEPTIONS
+ try
{
#endif // _LIBCPP_NO_EXCEPTIONS
__new_data = __alloc_traits::allocate(__alloc(), __target_capacity+1);
- #ifndef _LIBCPP_NO_EXCEPTIONS
+ #ifndef _LIBCPP_NO_EXCEPTIONS
+ }
+ catch (...)
+ {
+ return;
}
- catch (...)
- {
- return;
- }
- #else // _LIBCPP_NO_EXCEPTIONS
- if (__new_data == nullptr)
- return;
+ #else // _LIBCPP_NO_EXCEPTIONS
+ if (__new_data == nullptr)
+ return;
#endif // _LIBCPP_NO_EXCEPTIONS
}
- __now_long = true;
- __was_long = __is_long();
- __p = __get_pointer();
- }
- traits_type::copy(_VSTD::__to_address(__new_data),
- _VSTD::__to_address(__p), size()+1);
- if (__was_long)
- __alloc_traits::deallocate(__alloc(), __p, __cap+1);
- if (__now_long)
- {
+ __now_long = true;
+ __was_long = __is_long();
+ __p = __get_pointer();
+ }
+ traits_type::copy(_VSTD::__to_address(__new_data),
+ _VSTD::__to_address(__p), size()+1);
+ if (__was_long)
+ __alloc_traits::deallocate(__alloc(), __p, __cap+1);
+ if (__now_long)
+ {
__set_long_cap(__target_capacity+1);
- __set_long_size(__sz);
- __set_long_pointer(__new_data);
+ __set_long_size(__sz);
+ __set_long_pointer(__new_data);
}
- else
- __set_short_size(__sz);
- __invalidate_all_iterators();
-}
+ else
+ __set_short_size(__sz);
+ __invalidate_all_iterators();
+}
template <class _CharT, class _Traits, class _Allocator>
inline
@@ -4458,8 +4458,8 @@ _LIBCPP_FUNC_VIS wstring to_wstring(long double __val);
template<class _CharT, class _Traits, class _Allocator>
_LIBCPP_TEMPLATE_DATA_VIS
-const typename basic_string<_CharT, _Traits, _Allocator>::size_type
- basic_string<_CharT, _Traits, _Allocator>::npos;
+const typename basic_string<_CharT, _Traits, _Allocator>::size_type
+ basic_string<_CharT, _Traits, _Allocator>::npos;
template <class _CharT, class _Allocator>
struct _LIBCPP_TEMPLATE_VIS
@@ -4507,7 +4507,7 @@ getline(basic_istream<_CharT, _Traits>&& __is,
basic_string<_CharT, _Traits, _Allocator>& __str);
#if _LIBCPP_STD_VER > 17
-template <class _CharT, class _Traits, class _Allocator, class _Up>
+template <class _CharT, class _Traits, class _Allocator, class _Up>
inline _LIBCPP_INLINE_VISIBILITY
typename basic_string<_CharT, _Traits, _Allocator>::size_type
erase(basic_string<_CharT, _Traits, _Allocator>& __str, const _Up& __v) {
@@ -4516,7 +4516,7 @@ inline _LIBCPP_INLINE_VISIBILITY
return __old_size - __str.size();
}
-template <class _CharT, class _Traits, class _Allocator, class _Predicate>
+template <class _CharT, class _Traits, class _Allocator, class _Predicate>
inline _LIBCPP_INLINE_VISIBILITY
typename basic_string<_CharT, _Traits, _Allocator>::size_type
erase_if(basic_string<_CharT, _Traits, _Allocator>& __str,
diff --git a/contrib/libs/cxxsupp/libcxx/include/tuple b/contrib/libs/cxxsupp/libcxx/include/tuple
index 714d289b84..9b127953b3 100644
--- a/contrib/libs/cxxsupp/libcxx/include/tuple
+++ b/contrib/libs/cxxsupp/libcxx/include/tuple
@@ -308,7 +308,7 @@ public:
_And<
_IsNotSame<__uncvref_t<_Tp>, __tuple_leaf>,
is_constructible<_Hp, _Tp>
- >::value
+ >::value
>
>
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
@@ -1202,8 +1202,8 @@ template <class _T1, class ..._Args>
struct __find_exactly_one_checked {
static constexpr bool __matches[sizeof...(_Args)] = {is_same<_T1, _Args>::value...};
static constexpr size_t value = __find_detail::__find_idx(0, __matches);
- static_assert(value != __not_found, "type not found in type list" );
- static_assert(value != __ambiguous, "type occurs more than once in type list");
+ static_assert(value != __not_found, "type not found in type list" );
+ static_assert(value != __ambiguous, "type occurs more than once in type list");
};
template <class _T1>
@@ -1489,7 +1489,7 @@ struct __tuple_cat<tuple<_Types...>, __tuple_indices<_I0...>, __tuple_indices<_J
{
return _VSTD::forward_as_tuple(
_VSTD::forward<_Types>(_VSTD::get<_I0>(__t))...,
- _VSTD::get<_J0>(_VSTD::forward<_Tuple0>(__t0))...);
+ _VSTD::get<_J0>(_VSTD::forward<_Tuple0>(__t0))...);
}
template <class _Tuple0, class _Tuple1, class ..._Tuples>
@@ -1507,7 +1507,7 @@ struct __tuple_cat<tuple<_Types...>, __tuple_indices<_I0...>, __tuple_indices<_J
tuple_size<_T0>::value>::type,
typename __make_tuple_indices<tuple_size<_T1>::value>::type>()(
_VSTD::forward_as_tuple(
- _VSTD::forward<_Types>(_VSTD::get<_I0>(__t))...,
+ _VSTD::forward<_Types>(_VSTD::get<_I0>(__t))...,
_VSTD::get<_J0>(_VSTD::forward<_Tuple0>(__t0))...),
_VSTD::forward<_Tuple1>(__t1), _VSTD::forward<_Tuples>(__tpls)...);
}
diff --git a/contrib/libs/cxxsupp/libcxx/include/type_traits b/contrib/libs/cxxsupp/libcxx/include/type_traits
index 258fdcc667..8c91522074 100644
--- a/contrib/libs/cxxsupp/libcxx/include/type_traits
+++ b/contrib/libs/cxxsupp/libcxx/include/type_traits
@@ -160,7 +160,7 @@ namespace std
template <size_t Len, size_t Align = most_stringent_alignment_requirement>
struct aligned_storage;
template <size_t Len, class... Types> struct aligned_union;
- template <class T> struct remove_cvref; // C++20
+ template <class T> struct remove_cvref; // C++20
template <class T> struct decay;
template <class... T> struct common_type;
@@ -4188,7 +4188,7 @@ struct __can_extract_key
__extract_key_fail_tag>::type {};
template <class _Pair, class _Key, class _First, class _Second>
-struct __can_extract_key<_Pair, _Key, pair<_First, _Second> >
+struct __can_extract_key<_Pair, _Key, pair<_First, _Second> >
: conditional<_IsSame<typename remove_const<_First>::type, _Key>::value,
__extract_key_first_tag, __extract_key_fail_tag>::type {};
diff --git a/contrib/libs/cxxsupp/libcxx/include/typeinfo b/contrib/libs/cxxsupp/libcxx/include/typeinfo
index e8908cb91d..80c938646b 100644
--- a/contrib/libs/cxxsupp/libcxx/include/typeinfo
+++ b/contrib/libs/cxxsupp/libcxx/include/typeinfo
@@ -279,7 +279,7 @@ struct __type_info_implementations {
static bool __is_type_name_unique(__type_name_t __lhs) _NOEXCEPT {
return !(__lhs & __non_unique_rtti_bit::value);
}
- };
+ };
typedef
#if _LIBCPP_TYPEINFO_COMPARISON_IMPLEMENTATION == 1
@@ -296,10 +296,10 @@ struct __type_info_implementations {
class _LIBCPP_EXCEPTION_ABI type_info
{
- type_info& operator=(const type_info&);
- type_info(const type_info&);
+ type_info& operator=(const type_info&);
+ type_info(const type_info&);
- protected:
+ protected:
typedef __type_info_implementations::__impl __impl;
__impl::__type_name_t __type_name;
@@ -354,10 +354,10 @@ public:
return "std::bad_cast";
}
#else
- bad_cast() _NOEXCEPT;
- bad_cast(const bad_cast&) _NOEXCEPT = default;
- virtual ~bad_cast() _NOEXCEPT;
- virtual const char* what() const _NOEXCEPT;
+ bad_cast() _NOEXCEPT;
+ bad_cast(const bad_cast&) _NOEXCEPT = default;
+ virtual ~bad_cast() _NOEXCEPT;
+ virtual const char* what() const _NOEXCEPT;
#endif
};
@@ -373,9 +373,9 @@ public:
return "std::bad_typeid";
}
#else
- bad_typeid() _NOEXCEPT;
- virtual ~bad_typeid() _NOEXCEPT;
- virtual const char* what() const _NOEXCEPT;
+ bad_typeid() _NOEXCEPT;
+ virtual ~bad_typeid() _NOEXCEPT;
+ virtual const char* what() const _NOEXCEPT;
#endif
};
diff --git a/contrib/libs/cxxsupp/libcxx/include/unordered_map b/contrib/libs/cxxsupp/libcxx/include/unordered_map
index 8d95bee83d..417180a530 100644
--- a/contrib/libs/cxxsupp/libcxx/include/unordered_map
+++ b/contrib/libs/cxxsupp/libcxx/include/unordered_map
@@ -79,12 +79,12 @@ public:
unordered_map(InputIterator f, InputIterator l, size_type n, const allocator_type& a)
: unordered_map(f, l, n, hasher(), key_equal(), a) {} // C++14
template <class InputIterator>
- unordered_map(InputIterator f, InputIterator l, size_type n, const hasher& hf,
+ unordered_map(InputIterator f, InputIterator l, size_type n, const hasher& hf,
const allocator_type& a)
: unordered_map(f, l, n, hf, key_equal(), a) {} // C++14
unordered_map(initializer_list<value_type> il, size_type n, const allocator_type& a)
: unordered_map(il, n, hasher(), key_equal(), a) {} // C++14
- unordered_map(initializer_list<value_type> il, size_type n, const hasher& hf,
+ unordered_map(initializer_list<value_type> il, size_type n, const hasher& hf,
const allocator_type& a)
: unordered_map(il, n, hf, key_equal(), a) {} // C++14
~unordered_map();
@@ -290,12 +290,12 @@ public:
unordered_multimap(InputIterator f, InputIterator l, size_type n, const allocator_type& a)
: unordered_multimap(f, l, n, hasher(), key_equal(), a) {} // C++14
template <class InputIterator>
- unordered_multimap(InputIterator f, InputIterator l, size_type n, const hasher& hf,
+ unordered_multimap(InputIterator f, InputIterator l, size_type n, const hasher& hf,
const allocator_type& a)
: unordered_multimap(f, l, n, hf, key_equal(), a) {} // C++14
unordered_multimap(initializer_list<value_type> il, size_type n, const allocator_type& a)
: unordered_multimap(il, n, hasher(), key_equal(), a) {} // C++14
- unordered_multimap(initializer_list<value_type> il, size_type n, const hasher& hf,
+ unordered_multimap(initializer_list<value_type> il, size_type n, const hasher& hf,
const allocator_type& a)
: unordered_multimap(il, n, hf, key_equal(), a) {} // C++14
~unordered_multimap();
@@ -937,11 +937,11 @@ public:
"Invalid allocator::value_type");
private:
- typedef __hash_value_type<key_type, mapped_type> __value_type;
+ typedef __hash_value_type<key_type, mapped_type> __value_type;
typedef __unordered_map_hasher<key_type, __value_type, hasher, key_equal> __hasher;
typedef __unordered_map_equal<key_type, __value_type, key_equal, hasher> __key_equal;
typedef typename __rebind_alloc_helper<allocator_traits<allocator_type>,
- __value_type>::type __allocator_type;
+ __value_type>::type __allocator_type;
typedef __hash_table<__value_type, __hasher,
__key_equal, __allocator_type> __table;
@@ -1034,14 +1034,14 @@ public:
: unordered_map(__first, __last, __n, hasher(), key_equal(), __a) {}
template <class _InputIterator>
_LIBCPP_INLINE_VISIBILITY
- unordered_map(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf,
+ unordered_map(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf,
const allocator_type& __a)
: unordered_map(__first, __last, __n, __hf, key_equal(), __a) {}
_LIBCPP_INLINE_VISIBILITY
unordered_map(initializer_list<value_type> __il, size_type __n, const allocator_type& __a)
: unordered_map(__il, __n, hasher(), key_equal(), __a) {}
_LIBCPP_INLINE_VISIBILITY
- unordered_map(initializer_list<value_type> __il, size_type __n, const hasher& __hf,
+ unordered_map(initializer_list<value_type> __il, size_type __n, const hasher& __hf,
const allocator_type& __a)
: unordered_map(__il, __n, __hf, key_equal(), __a) {}
#endif
@@ -1871,11 +1871,11 @@ public:
"Invalid allocator::value_type");
private:
- typedef __hash_value_type<key_type, mapped_type> __value_type;
+ typedef __hash_value_type<key_type, mapped_type> __value_type;
typedef __unordered_map_hasher<key_type, __value_type, hasher, key_equal> __hasher;
typedef __unordered_map_equal<key_type, __value_type, key_equal, hasher> __key_equal;
typedef typename __rebind_alloc_helper<allocator_traits<allocator_type>,
- __value_type>::type __allocator_type;
+ __value_type>::type __allocator_type;
typedef __hash_table<__value_type, __hasher,
__key_equal, __allocator_type> __table;
@@ -1966,14 +1966,14 @@ public:
: unordered_multimap(__first, __last, __n, hasher(), key_equal(), __a) {}
template <class _InputIterator>
_LIBCPP_INLINE_VISIBILITY
- unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf,
+ unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf,
const allocator_type& __a)
: unordered_multimap(__first, __last, __n, __hf, key_equal(), __a) {}
_LIBCPP_INLINE_VISIBILITY
unordered_multimap(initializer_list<value_type> __il, size_type __n, const allocator_type& __a)
: unordered_multimap(__il, __n, hasher(), key_equal(), __a) {}
_LIBCPP_INLINE_VISIBILITY
- unordered_multimap(initializer_list<value_type> __il, size_type __n, const hasher& __hf,
+ unordered_multimap(initializer_list<value_type> __il, size_type __n, const hasher& __hf,
const allocator_type& __a)
: unordered_multimap(__il, __n, __hf, key_equal(), __a) {}
#endif
diff --git a/contrib/libs/cxxsupp/libcxx/include/unordered_set b/contrib/libs/cxxsupp/libcxx/include/unordered_set
index 25432030bf..5856e4bc40 100644
--- a/contrib/libs/cxxsupp/libcxx/include/unordered_set
+++ b/contrib/libs/cxxsupp/libcxx/include/unordered_set
@@ -75,7 +75,7 @@ public:
template <class InputIterator>
unordered_set(InputIterator f, InputIterator l, size_type n, const allocator_type& a); // C++14
template <class InputIterator>
- unordered_set(InputIterator f, InputIterator l, size_type n,
+ unordered_set(InputIterator f, InputIterator l, size_type n,
const hasher& hf, const allocator_type& a); // C++14
unordered_set(initializer_list<value_type> il, size_type n, const allocator_type& a); // C++14
unordered_set(initializer_list<value_type> il, size_type n,
@@ -255,7 +255,7 @@ public:
unordered_multiset(InputIterator f, InputIterator l, size_type n,
const hasher& hf, const allocator_type& a); // C++14
unordered_multiset(initializer_list<value_type> il, size_type n, const allocator_type& a); // C++14
- unordered_multiset(initializer_list<value_type> il, size_type n,
+ unordered_multiset(initializer_list<value_type> il, size_type n,
const hasher& hf, const allocator_type& a); // C++14
~unordered_multiset();
unordered_multiset& operator=(const unordered_multiset&);
@@ -481,11 +481,11 @@ public:
#if _LIBCPP_STD_VER > 11
template <class _InputIterator>
inline _LIBCPP_INLINE_VISIBILITY
- unordered_set(_InputIterator __first, _InputIterator __last,
+ unordered_set(_InputIterator __first, _InputIterator __last,
size_type __n, const allocator_type& __a)
: unordered_set(__first, __last, __n, hasher(), key_equal(), __a) {}
template <class _InputIterator>
- unordered_set(_InputIterator __first, _InputIterator __last,
+ unordered_set(_InputIterator __first, _InputIterator __last,
size_type __n, const hasher& __hf, const allocator_type& __a)
: unordered_set(__first, __last, __n, __hf, key_equal(), __a) {}
#endif
@@ -511,7 +511,7 @@ public:
const allocator_type& __a)
: unordered_set(__il, __n, hasher(), key_equal(), __a) {}
inline _LIBCPP_INLINE_VISIBILITY
- unordered_set(initializer_list<value_type> __il, size_type __n,
+ unordered_set(initializer_list<value_type> __il, size_type __n,
const hasher& __hf, const allocator_type& __a)
: unordered_set(__il, __n, __hf, key_equal(), __a) {}
#endif
@@ -1177,7 +1177,7 @@ public:
#if _LIBCPP_STD_VER > 11
template <class _InputIterator>
inline _LIBCPP_INLINE_VISIBILITY
- unordered_multiset(_InputIterator __first, _InputIterator __last,
+ unordered_multiset(_InputIterator __first, _InputIterator __last,
size_type __n, const allocator_type& __a)
: unordered_multiset(__first, __last, __n, hasher(), key_equal(), __a) {}
template <class _InputIterator>
diff --git a/contrib/libs/cxxsupp/libcxx/include/use_ansi.h b/contrib/libs/cxxsupp/libcxx/include/use_ansi.h
index 5e58ddbf7a..2b6f36d4ef 100644
--- a/contrib/libs/cxxsupp/libcxx/include/use_ansi.h
+++ b/contrib/libs/cxxsupp/libcxx/include/use_ansi.h
@@ -1,3 +1,3 @@
-// Empty header to prevent MSVC one from inclusion.
-// This MSVC header adds Microsoft STL to the linker arguments
+// Empty header to prevent MSVC one from inclusion.
+// This MSVC header adds Microsoft STL to the linker arguments
// which causes conflicts with libc++. \ No newline at end of file
diff --git a/contrib/libs/cxxsupp/libcxx/include/variant b/contrib/libs/cxxsupp/libcxx/include/variant
index fb3ca8c220..972c18a811 100644
--- a/contrib/libs/cxxsupp/libcxx/include/variant
+++ b/contrib/libs/cxxsupp/libcxx/include/variant
@@ -814,7 +814,7 @@ class _LIBCPP_TEMPLATE_VIS __dtor;
#define _LIBCPP_VARIANT_DESTRUCTOR(destructible_trait, destructor, destroy) \
template <class... _Types> \
class _LIBCPP_TEMPLATE_VIS __dtor<__traits<_Types...>, \
- destructible_trait> \
+ destructible_trait> \
: public __base<destructible_trait, _Types...> { \
using __base_type = __base<destructible_trait, _Types...>; \
using __index_t = typename __base_type::__index_t; \
@@ -902,8 +902,8 @@ class _LIBCPP_TEMPLATE_VIS __move_constructor;
#define _LIBCPP_VARIANT_MOVE_CONSTRUCTOR(move_constructible_trait, \
move_constructor) \
template <class... _Types> \
- class _LIBCPP_TEMPLATE_VIS __move_constructor<__traits<_Types...>, \
- move_constructible_trait> \
+ class _LIBCPP_TEMPLATE_VIS __move_constructor<__traits<_Types...>, \
+ move_constructible_trait> \
: public __ctor<__traits<_Types...>> { \
using __base_type = __ctor<__traits<_Types...>>; \
\
@@ -1247,7 +1247,7 @@ struct __make_overloads_imp<__tuple_indices<_Idx...>, _Types... > {
using _Apply _LIBCPP_NODEBUG = __all_overloads<__overload<_Types, _Idx>...>;
};
-template <class ..._Types>
+template <class ..._Types>
using _MakeOverloads _LIBCPP_NODEBUG = typename __make_overloads_imp<
__make_indices_imp<_Sizeof<_Types...>::value, 0>, _Types...>::_Apply;
diff --git a/contrib/libs/cxxsupp/libcxx/include/vector b/contrib/libs/cxxsupp/libcxx/include/vector
index 3aa03b949d..c02253c751 100644
--- a/contrib/libs/cxxsupp/libcxx/include/vector
+++ b/contrib/libs/cxxsupp/libcxx/include/vector
@@ -496,8 +496,8 @@ public:
typedef typename __base::pointer iterator;
typedef typename __base::const_pointer const_iterator;
#else
- typedef __wrap_iter<pointer> iterator;
- typedef __wrap_iter<const_pointer> const_iterator;
+ typedef __wrap_iter<pointer> iterator;
+ typedef __wrap_iter<const_pointer> const_iterator;
#endif
typedef _VSTD::reverse_iterator<iterator> reverse_iterator;
typedef _VSTD::reverse_iterator<const_iterator> const_reverse_iterator;
@@ -921,7 +921,7 @@ private:
struct _ConstructTransaction {
explicit _ConstructTransaction(vector &__v, size_type __n)
- : __v_(__v), __pos_(__v.__end_), __new_end_(__v.__end_ + __n) {
+ : __v_(__v), __pos_(__v.__end_), __new_end_(__v.__end_ + __n) {
#ifndef _LIBCPP_HAS_NO_ASAN
__v_.__annotate_increase(__n);
#endif
@@ -938,7 +938,7 @@ private:
vector &__v_;
pointer __pos_;
const_pointer const __new_end_;
-
+
private:
_ConstructTransaction(_ConstructTransaction const&) = delete;
_ConstructTransaction& operator=(_ConstructTransaction const&) = delete;
@@ -1085,7 +1085,7 @@ vector<_Tp, _Allocator>::__construct_at_end(size_type __n, const_reference __x)
_ConstructTransaction __tx(*this, __n);
const_pointer __new_end = __tx.__new_end_;
for (pointer __pos = __tx.__pos_; __pos != __new_end; __tx.__pos_ = ++__pos) {
- __alloc_traits::construct(this->__alloc(), _VSTD::__to_address(__pos), __x);
+ __alloc_traits::construct(this->__alloc(), _VSTD::__to_address(__pos), __x);
}
}
diff --git a/contrib/libs/cxxsupp/libcxx/include/wctype.h b/contrib/libs/cxxsupp/libcxx/include/wctype.h
index 43a79f203d..e6f813b8b1 100644
--- a/contrib/libs/cxxsupp/libcxx/include/wctype.h
+++ b/contrib/libs/cxxsupp/libcxx/include/wctype.h
@@ -68,7 +68,7 @@ wctrans_t wctrans(const char* property);
// of these declarations (e.g. <wchar.h>), the second `using ::wint_t` with using_if_exists
// will fail because it does not refer to the same declaration.
#if __has_include_next(<wctype.h>)
-# include_next <wctype.h>
+# include_next <wctype.h>
# define _LIBCPP_INCLUDED_C_LIBRARY_WCTYPE_H
#endif
#endif
diff --git a/contrib/libs/cxxsupp/libcxx/src/atomic.cpp b/contrib/libs/cxxsupp/libcxx/src/atomic.cpp
index db7fb0dabe..9ae1fb5199 100644
--- a/contrib/libs/cxxsupp/libcxx/src/atomic.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/atomic.cpp
@@ -51,11 +51,11 @@ static void __libcpp_platform_wake_by_address(__cxx_atomic_contention_t const vo
#elif defined(__APPLE__) && defined(_LIBCPP_USE_ULOCK)
extern "C" int __ulock_wait(uint32_t operation, void *addr, uint64_t value,
- uint32_t timeout); /* timeout is specified in microseconds */
+ uint32_t timeout); /* timeout is specified in microseconds */
extern "C" int __ulock_wake(uint32_t operation, void *addr, uint64_t wake_value);
-#define UL_COMPARE_AND_WAIT 1
-#define ULF_WAKE_ALL 0x00000100
+#define UL_COMPARE_AND_WAIT 1
+#define ULF_WAKE_ALL 0x00000100
static void __libcpp_platform_wait_on_address(__cxx_atomic_contention_t const volatile* __ptr,
__cxx_contention_t __val)
diff --git a/contrib/libs/cxxsupp/libcxx/src/chrono.cpp b/contrib/libs/cxxsupp/libcxx/src/chrono.cpp
index 80fbadbab3..b18e4f7cb9 100644
--- a/contrib/libs/cxxsupp/libcxx/src/chrono.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/chrono.cpp
@@ -244,9 +244,9 @@ static steady_clock::time_point __libcpp_steady_clock_now() {
static LARGE_INTEGER
__QueryPerformanceFrequency()
{
- LARGE_INTEGER val;
- (void) QueryPerformanceFrequency(&val);
- return val;
+ LARGE_INTEGER val;
+ (void) QueryPerformanceFrequency(&val);
+ return val;
}
static steady_clock::time_point __libcpp_steady_clock_now() {
diff --git a/contrib/libs/cxxsupp/libcxx/src/debug.cpp b/contrib/libs/cxxsupp/libcxx/src/debug.cpp
index 307030eb77..dd5963fcce 100644
--- a/contrib/libs/cxxsupp/libcxx/src/debug.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/debug.cpp
@@ -200,7 +200,7 @@ __libcpp_db::__insert_c(void* __c, __libcpp_db::_InsertConstruct *__fn)
__c_node* p = __cbeg_[hc];
void *buf = malloc(sizeof(__c_node));
if (buf == nullptr)
- __throw_bad_alloc();
+ __throw_bad_alloc();
__cbeg_[hc] = __fn(buf, __c, p);
++__csz_;
diff --git a/contrib/libs/cxxsupp/libcxx/src/filesystem/directory_iterator.cpp b/contrib/libs/cxxsupp/libcxx/src/filesystem/directory_iterator.cpp
index 8ae51419dd..a098dd163b 100644
--- a/contrib/libs/cxxsupp/libcxx/src/filesystem/directory_iterator.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/filesystem/directory_iterator.cpp
@@ -153,16 +153,16 @@ public:
bool assign() {
if (!wcscmp(__data_.cFileName, L".") || !wcscmp(__data_.cFileName, L".."))
return false;
- // FIXME: Cache more of this
- //directory_entry::__cached_data cdata;
- //cdata.__type_ = get_file_type(__data_);
- //cdata.__size_ = get_file_size(__data_);
- //cdata.__write_time_ = get_write_time(__data_);
- __entry_.__assign_iter_entry(
- __root_ / __data_.cFileName,
+ // FIXME: Cache more of this
+ //directory_entry::__cached_data cdata;
+ //cdata.__type_ = get_file_type(__data_);
+ //cdata.__size_ = get_file_size(__data_);
+ //cdata.__write_time_ = get_write_time(__data_);
+ __entry_.__assign_iter_entry(
+ __root_ / __data_.cFileName,
directory_entry::__create_iter_result(detail::get_file_type(__data_)));
- return true;
- }
+ return true;
+ }
private:
error_code close() noexcept {
diff --git a/contrib/libs/cxxsupp/libcxx/src/filesystem/filesystem_common.h b/contrib/libs/cxxsupp/libcxx/src/filesystem/filesystem_common.h
index 4068f285c7..a5f5749783 100644
--- a/contrib/libs/cxxsupp/libcxx/src/filesystem/filesystem_common.h
+++ b/contrib/libs/cxxsupp/libcxx/src/filesystem/filesystem_common.h
@@ -19,11 +19,11 @@
#include "filesystem"
#if !defined(_LIBCPP_WIN32API)
-# include <unistd.h>
-# include <sys/stat.h>
-# include <sys/statvfs.h>
-# include <sys/time.h> // for ::utimes as used in __last_write_time
-# include <fcntl.h> /* values for fchmodat */
+# include <unistd.h>
+# include <sys/stat.h>
+# include <sys/statvfs.h>
+# include <sys/time.h> // for ::utimes as used in __last_write_time
+# include <fcntl.h> /* values for fchmodat */
#endif
#include "../include/apple_availability.h"
diff --git a/contrib/libs/cxxsupp/libcxx/src/filesystem/operations.cpp b/contrib/libs/cxxsupp/libcxx/src/filesystem/operations.cpp
index ee1e7c55e3..63593be223 100644
--- a/contrib/libs/cxxsupp/libcxx/src/filesystem/operations.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/filesystem/operations.cpp
@@ -24,18 +24,18 @@
# define NOMINMAX
# include <windows.h>
#else
-# include <unistd.h>
-# include <sys/stat.h>
-# include <sys/statvfs.h>
+# include <unistd.h>
+# include <sys/stat.h>
+# include <sys/statvfs.h>
#endif
#include <time.h>
#include <fcntl.h> /* values for fchmodat */
#if __has_include(<sys/sendfile.h>)
-# include <sys/sendfile.h>
+# include <sys/sendfile.h>
# define _LIBCPP_FILESYSTEM_USE_SENDFILE
#elif defined(__APPLE__) || __has_include(<copyfile.h>)
-# include <copyfile.h>
+# include <copyfile.h>
# define _LIBCPP_FILESYSTEM_USE_COPYFILE
#else
# include "fstream"
@@ -43,11 +43,11 @@
#endif
#if !defined(CLOCK_REALTIME) && !defined(_LIBCPP_WIN32API)
-# include <sys/time.h> // for gettimeofday and timeval
+# include <sys/time.h> // for gettimeofday and timeval
#endif
#if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
-# pragma comment(lib, "rt")
+# pragma comment(lib, "rt")
#endif
_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
diff --git a/contrib/libs/cxxsupp/libcxx/src/include/refstring.h b/contrib/libs/cxxsupp/libcxx/src/include/refstring.h
index f2ce0b6508..3edd240a5d 100644
--- a/contrib/libs/cxxsupp/libcxx/src/include/refstring.h
+++ b/contrib/libs/cxxsupp/libcxx/src/include/refstring.h
@@ -34,8 +34,8 @@
#if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || \
defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__)
# define _LIBCPP_CHECK_FOR_GCC_EMPTY_STRING_STORAGE
-# include <dlfcn.h>
-# include <mach-o/dyld.h>
+# include <dlfcn.h>
+# include <mach-o/dyld.h>
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
diff --git a/contrib/libs/cxxsupp/libcxx/src/ios.cpp b/contrib/libs/cxxsupp/libcxx/src/ios.cpp
index fd2cefc61e..a8a99015a9 100644
--- a/contrib/libs/cxxsupp/libcxx/src/ios.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/ios.cpp
@@ -145,11 +145,11 @@ int ios_base::__xindex_ = 0;
template <typename _Tp>
static size_t __ios_new_cap(size_t __req_size, size_t __current_cap)
{ // Precondition: __req_size > __current_cap
- const size_t mx = std::numeric_limits<size_t>::max() / sizeof(_Tp);
- if (__req_size < mx/2)
- return _VSTD::max(2 * __current_cap, __req_size);
- else
- return mx;
+ const size_t mx = std::numeric_limits<size_t>::max() / sizeof(_Tp);
+ if (__req_size < mx/2)
+ return _VSTD::max(2 * __current_cap, __req_size);
+ else
+ return mx;
}
int
diff --git a/contrib/libs/cxxsupp/libcxx/src/iostream.cpp b/contrib/libs/cxxsupp/libcxx/src/iostream.cpp
index 05f2efe54c..5c1f5ed9ee 100644
--- a/contrib/libs/cxxsupp/libcxx/src/iostream.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/iostream.cpp
@@ -156,8 +156,8 @@ static void force_locale_initialization() {
class DoIOSInit {
public:
- DoIOSInit();
- ~DoIOSInit();
+ DoIOSInit();
+ ~DoIOSInit();
};
DoIOSInit::DoIOSInit()
diff --git a/contrib/libs/cxxsupp/libcxx/src/locale.cpp b/contrib/libs/cxxsupp/libcxx/src/locale.cpp
index a989b5e716..42b5641b43 100644
--- a/contrib/libs/cxxsupp/libcxx/src/locale.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/locale.cpp
@@ -4761,7 +4761,7 @@ __check_grouping(const string& __grouping, unsigned* __g, unsigned* __g_end,
{
// if the grouping pattern is empty _or_ there are no grouping bits, then do nothing
// we always have at least a single entry in [__g, __g_end); the end of the input sequence
- if (__grouping.size() != 0 && __g_end - __g > 1)
+ if (__grouping.size() != 0 && __g_end - __g > 1)
{
reverse(__g, __g_end);
const char* __ig = __grouping.data();
diff --git a/contrib/libs/cxxsupp/libcxx/src/mutex.cpp b/contrib/libs/cxxsupp/libcxx/src/mutex.cpp
index 2701f5b33f..124d59bc64 100644
--- a/contrib/libs/cxxsupp/libcxx/src/mutex.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/mutex.cpp
@@ -204,10 +204,10 @@ _LIBCPP_SAFE_STATIC static __libcpp_condvar_t cv = _LIBCPP_CONDVAR_INITIALIZER;
#ifdef _LIBCPP_ABI_MICROSOFT
void __call_once(volatile std::atomic<once_flag::_State_type>& flag, void* arg,
- void (*func)(void*))
+ void (*func)(void*))
#else
void __call_once(volatile once_flag::_State_type& flag, void* arg,
- void (*func)(void*))
+ void (*func)(void*))
#endif
{
#if defined(_LIBCPP_HAS_NO_THREADS)
diff --git a/contrib/libs/cxxsupp/libcxx/src/new.cpp b/contrib/libs/cxxsupp/libcxx/src/new.cpp
index 2cc06b9e9a..85afe3039e 100644
--- a/contrib/libs/cxxsupp/libcxx/src/new.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/new.cpp
@@ -12,15 +12,15 @@
#if defined(_LIBCPP_ABI_MICROSOFT)
# if !defined(_LIBCPP_ABI_VCRUNTIME)
-# include "support/runtime/new_handler_fallback.ipp"
-# endif
+# include "support/runtime/new_handler_fallback.ipp"
+# endif
#elif defined(LIBCXX_BUILDING_LIBCXXABI)
-# include <cxxabi.h>
+# include <cxxabi.h>
#elif defined(LIBCXX_BUILDING_LIBCXXRT)
-# include <cxxabi.h>
-# include "support/runtime/new_handler_fallback.ipp"
+# include <cxxabi.h>
+# include "support/runtime/new_handler_fallback.ipp"
#elif defined(__GLIBCXX__)
- // nothing to do
+ // nothing to do
#else
# include "support/runtime/new_handler_fallback.ipp"
#endif
@@ -129,7 +129,7 @@ _LIBCPP_WEAK
void
operator delete(void* ptr) noexcept
{
- ::free(ptr);
+ ::free(ptr);
}
_LIBCPP_WEAK
diff --git a/contrib/libs/cxxsupp/libcxx/src/optional.cpp b/contrib/libs/cxxsupp/libcxx/src/optional.cpp
index 81660f9f4b..39405bec12 100644
--- a/contrib/libs/cxxsupp/libcxx/src/optional.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/optional.cpp
@@ -31,9 +31,9 @@ class _LIBCPP_EXCEPTION_ABI _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS bad_optiona
: public std::logic_error
{
public:
- bad_optional_access() : std::logic_error("Bad optional Access") {}
+ bad_optional_access() : std::logic_error("Bad optional Access") {}
-// Get the key function ~bad_optional_access() into the dylib
+// Get the key function ~bad_optional_access() into the dylib
virtual ~bad_optional_access() noexcept;
};
diff --git a/contrib/libs/cxxsupp/libcxx/src/stdexcept.cpp b/contrib/libs/cxxsupp/libcxx/src/stdexcept.cpp
index 71f3c98886..f8f335f34a 100644
--- a/contrib/libs/cxxsupp/libcxx/src/stdexcept.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/stdexcept.cpp
@@ -11,7 +11,7 @@
#include "string"
#include "system_error"
-
+
#ifdef _LIBCPP_ABI_VCRUNTIME
#include "support/runtime/stdexcept_vcruntime.ipp"
#else
diff --git a/contrib/libs/cxxsupp/libcxx/src/string.cpp b/contrib/libs/cxxsupp/libcxx/src/string.cpp
index 083b828df4..c8dae34272 100644
--- a/contrib/libs/cxxsupp/libcxx/src/string.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/string.cpp
@@ -193,7 +193,7 @@ as_integer( const string& func, const wstring& s, size_t* idx, int base )
// as_float
-template<typename V, typename S, typename F>
+template<typename V, typename S, typename F>
inline
V
as_float_helper(const string& func, const S& str, size_t* idx, F f )
diff --git a/contrib/libs/cxxsupp/libcxx/src/support/solaris/xlocale.cpp b/contrib/libs/cxxsupp/libcxx/src/support/solaris/xlocale.cpp
index e570201954..d25adcd21d 100644
--- a/contrib/libs/cxxsupp/libcxx/src/support/solaris/xlocale.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/support/solaris/xlocale.cpp
@@ -25,7 +25,7 @@ int iswxdigit_l(wint_t __c, locale_t __l) {
// FIXME: This disregards the locale, which is Very Wrong
#define vsnprintf_l(__s, __n, __l, __format, __va) \
- vsnprintf(__s, __n, __format, __va)
+ vsnprintf(__s, __n, __format, __va)
int snprintf_l(char *__s, size_t __n, locale_t __l, const char *__format, ...)
{
diff --git a/contrib/libs/cxxsupp/libcxx/src/support/win32/support.cpp b/contrib/libs/cxxsupp/libcxx/src/support/win32/support.cpp
index 5c2f19fd84..11702a788b 100644
--- a/contrib/libs/cxxsupp/libcxx/src/support/win32/support.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/support/win32/support.cpp
@@ -42,13 +42,13 @@ int __libcpp_vasprintf( char **sptr, const char *__restrict format, va_list ap )
return count;
}
-// Returns >= 0: the number of wide characters found in the
-// multi byte sequence src (of src_size_bytes), that fit in the buffer dst
+// Returns >= 0: the number of wide characters found in the
+// multi byte sequence src (of src_size_bytes), that fit in the buffer dst
// (of max_dest_chars elements size). The count returned excludes the
-// null terminator. When dst is NULL, no characters are copied
+// null terminator. When dst is NULL, no characters are copied
// and no "out" parameters are updated.
// Returns (size_t) -1: an incomplete sequence encountered.
-// Leaves *src pointing the next character to convert or NULL
+// Leaves *src pointing the next character to convert or NULL
// if a null character was converted from *src.
size_t mbsnrtowcs( wchar_t *__restrict dst, const char **__restrict src,
size_t src_size_bytes, size_t max_dest_chars, mbstate_t *__restrict ps )
@@ -105,7 +105,7 @@ size_t mbsnrtowcs( wchar_t *__restrict dst, const char **__restrict src,
// Returns >= 0: the number of bytes in the sequence
// converted from *src, excluding the null terminator.
// Returns size_t(-1) if an error occurs, also sets errno.
-// If dst is NULL dst_size_bytes is ignored and no bytes are copied to dst
+// If dst is NULL dst_size_bytes is ignored and no bytes are copied to dst
// and no "out" parameters are updated.
size_t wcsnrtombs( char *__restrict dst, const wchar_t **__restrict src,
size_t max_source_chars, size_t dst_size_bytes, mbstate_t *__restrict ps )
@@ -134,7 +134,7 @@ size_t wcsnrtombs( char *__restrict dst, const wchar_t **__restrict src,
result = wcrtomb_s( &char_size, dst + dest_converted, dest_remaining, c, ps);
else
result = wcrtomb_s( &char_size, NULL, 0, c, ps);
- // If result is zero there is no error and char_size contains the
+ // If result is zero there is no error and char_size contains the
// size of the multi-byte-sequence converted.
// Otherwise result indicates an errno type error.
if ( result == no_error ) {
diff --git a/contrib/libs/cxxsupp/libcxx/src/typeinfo.cpp b/contrib/libs/cxxsupp/libcxx/src/typeinfo.cpp
index 9da74c9e3b..baace5643c 100644
--- a/contrib/libs/cxxsupp/libcxx/src/typeinfo.cpp
+++ b/contrib/libs/cxxsupp/libcxx/src/typeinfo.cpp
@@ -49,7 +49,7 @@ size_t std::type_info::hash_code() const noexcept {
#if (!defined(LIBCXX_BUILDING_LIBCXXABI) && \
!defined(LIBCXX_BUILDING_LIBCXXRT) && \
!defined(__GLIBCXX__) && \
- !defined(_LIBCPP_ABI_VCRUNTIME)) || \
+ !defined(_LIBCPP_ABI_VCRUNTIME)) || \
defined(_LIBCPP_BUILDING_HAS_NO_ABI_LIBRARY)
std::type_info::~type_info()
{
diff --git a/contrib/libs/cxxsupp/libcxx/ya.make b/contrib/libs/cxxsupp/libcxx/ya.make
index 961b31241d..15403fe6d5 100644
--- a/contrib/libs/cxxsupp/libcxx/ya.make
+++ b/contrib/libs/cxxsupp/libcxx/ya.make
@@ -56,16 +56,16 @@ ELSEIF (OS_IOS)
contrib/libs/cxxsupp/builtins
)
ELSEIF (CLANG OR MUSL OR OS_DARWIN OR USE_LTO)
- IF (ARCH_ARM7)
- # XXX: libcxxrt support for ARM is currently broken
- DEFAULT(CXX_RT "glibcxx_static")
+ IF (ARCH_ARM7)
+ # XXX: libcxxrt support for ARM is currently broken
+ DEFAULT(CXX_RT "glibcxx_static")
# ARM7 OS_SDK has old libstdc++ without aligned allocation support
CFLAGS(
GLOBAL -fno-aligned-new
)
- ELSE()
- DEFAULT(CXX_RT "libcxxrt")
- ENDIF()
+ ELSE()
+ DEFAULT(CXX_RT "libcxxrt")
+ ENDIF()
IF (MUSL)
PEERDIR(
contrib/libs/musl/include
@@ -118,8 +118,8 @@ ENDIF()
DEFAULT(CXX_RT "default")
-DISABLE(NEED_GLIBCXX_CXX17_SHIMS)
-
+DISABLE(NEED_GLIBCXX_CXX17_SHIMS)
+
IF (CXX_RT == "libcxxrt")
PEERDIR(
contrib/libs/cxxsupp/libcxxabi-parts
@@ -132,9 +132,9 @@ IF (CXX_RT == "libcxxrt")
CFLAGS(
GLOBAL -DLIBCXX_BUILDING_LIBCXXRT
)
- # These builtins are equivalent to clang -rtlib=compiler_rt and
- # are needed by potentially any code generated by clang.
- # With glibcxx runtime, builtins are provided by libgcc
+ # These builtins are equivalent to clang -rtlib=compiler_rt and
+ # are needed by potentially any code generated by clang.
+ # With glibcxx runtime, builtins are provided by libgcc
ELSEIF (CXX_RT == "glibcxx" OR CXX_RT == "glibcxx_static")
LDFLAGS(
-Wl,-Bstatic
@@ -142,9 +142,9 @@ ELSEIF (CXX_RT == "glibcxx" OR CXX_RT == "glibcxx_static")
-lgcc
-lgcc_eh
-Wl,-Bdynamic
- )
+ )
CXXFLAGS(-D__GLIBCXX__=1)
- ENABLE(NEED_GLIBCXX_CXX17_SHIMS)
+ ENABLE(NEED_GLIBCXX_CXX17_SHIMS)
CFLAGS(
GLOBAL -DLIBCXX_BUILDING_LIBGCC
)
@@ -157,7 +157,7 @@ ELSEIF (CXX_RT == "glibcxx_dynamic")
CFLAGS(
GLOBAL -DLIBCXX_BUILDING_LIBGCC
)
- ENABLE(NEED_GLIBCXX_CXX17_SHIMS)
+ ENABLE(NEED_GLIBCXX_CXX17_SHIMS)
ELSEIF (CXX_RT == "glibcxx_driver")
CXXFLAGS(-D__GLIBCXX__=1)
ELSEIF (CXX_RT == "default")
@@ -166,17 +166,17 @@ ELSE()
MESSAGE(FATAL_ERROR "Unexpected CXX_RT value: ${CXX_RT}")
ENDIF()
-IF (NEED_GLIBCXX_CXX17_SHIMS)
- IF (GCC)
- # Assume GCC is bundled with a modern enough version of C++ runtime
+IF (NEED_GLIBCXX_CXX17_SHIMS)
+ IF (GCC)
+ # Assume GCC is bundled with a modern enough version of C++ runtime
ELSEIF (OS_SDK == "ubuntu-12" OR OS_SDK == "ubuntu-14" OR OS_SDK == "ubuntu-16")
- # Prior to ubuntu-18, system C++ runtime for C++17 is incomplete
+ # Prior to ubuntu-18, system C++ runtime for C++17 is incomplete
SRCS(
glibcxx_eh_cxx17.cpp
)
- ENDIF()
-ENDIF()
-
+ ENDIF()
+ENDIF()
+
NO_UTIL()
NO_RUNTIME()
diff --git a/contrib/libs/cxxsupp/libcxxabi/src/demangle/ItaniumDemangle.h b/contrib/libs/cxxsupp/libcxxabi/src/demangle/ItaniumDemangle.h
index 677ce6b24e..85e1511346 100644
--- a/contrib/libs/cxxsupp/libcxxabi/src/demangle/ItaniumDemangle.h
+++ b/contrib/libs/cxxsupp/libcxxabi/src/demangle/ItaniumDemangle.h
@@ -111,125 +111,125 @@
DEMANGLE_NAMESPACE_BEGIN
template <class T, size_t N> class PODSmallVector {
- static_assert(std::is_pod<T>::value,
- "T is required to be a plain old data type");
-
+ static_assert(std::is_pod<T>::value,
+ "T is required to be a plain old data type");
+
T *First = nullptr;
T *Last = nullptr;
T *Cap = nullptr;
- T Inline[N] = {0};
-
- bool isInline() const { return First == Inline; }
-
- void clearInline() {
- First = Inline;
- Last = Inline;
- Cap = Inline + N;
- }
-
- void reserve(size_t NewCap) {
- size_t S = size();
- if (isInline()) {
+ T Inline[N] = {0};
+
+ bool isInline() const { return First == Inline; }
+
+ void clearInline() {
+ First = Inline;
+ Last = Inline;
+ Cap = Inline + N;
+ }
+
+ void reserve(size_t NewCap) {
+ size_t S = size();
+ if (isInline()) {
auto *Tmp = static_cast<T *>(std::malloc(NewCap * sizeof(T)));
- if (Tmp == nullptr)
- std::terminate();
- std::copy(First, Last, Tmp);
- First = Tmp;
- } else {
+ if (Tmp == nullptr)
+ std::terminate();
+ std::copy(First, Last, Tmp);
+ First = Tmp;
+ } else {
First = static_cast<T *>(std::realloc(First, NewCap * sizeof(T)));
- if (First == nullptr)
- std::terminate();
- }
- Last = First + S;
- Cap = First + NewCap;
- }
-
-public:
- PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {}
-
+ if (First == nullptr)
+ std::terminate();
+ }
+ Last = First + S;
+ Cap = First + NewCap;
+ }
+
+public:
+ PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {}
+
PODSmallVector(const PODSmallVector &) = delete;
PODSmallVector &operator=(const PODSmallVector &) = delete;
-
+
PODSmallVector(PODSmallVector &&Other) : PODSmallVector() {
- if (Other.isInline()) {
- std::copy(Other.begin(), Other.end(), First);
- Last = First + Other.size();
- Other.clear();
- return;
- }
-
- First = Other.First;
- Last = Other.Last;
- Cap = Other.Cap;
- Other.clearInline();
- }
-
+ if (Other.isInline()) {
+ std::copy(Other.begin(), Other.end(), First);
+ Last = First + Other.size();
+ Other.clear();
+ return;
+ }
+
+ First = Other.First;
+ Last = Other.Last;
+ Cap = Other.Cap;
+ Other.clearInline();
+ }
+
PODSmallVector &operator=(PODSmallVector &&Other) {
- if (Other.isInline()) {
- if (!isInline()) {
- std::free(First);
- clearInline();
- }
- std::copy(Other.begin(), Other.end(), First);
- Last = First + Other.size();
- Other.clear();
- return *this;
- }
-
- if (isInline()) {
- First = Other.First;
- Last = Other.Last;
- Cap = Other.Cap;
- Other.clearInline();
- return *this;
- }
-
- std::swap(First, Other.First);
- std::swap(Last, Other.Last);
- std::swap(Cap, Other.Cap);
- Other.clear();
- return *this;
- }
-
+ if (Other.isInline()) {
+ if (!isInline()) {
+ std::free(First);
+ clearInline();
+ }
+ std::copy(Other.begin(), Other.end(), First);
+ Last = First + Other.size();
+ Other.clear();
+ return *this;
+ }
+
+ if (isInline()) {
+ First = Other.First;
+ Last = Other.Last;
+ Cap = Other.Cap;
+ Other.clearInline();
+ return *this;
+ }
+
+ std::swap(First, Other.First);
+ std::swap(Last, Other.Last);
+ std::swap(Cap, Other.Cap);
+ Other.clear();
+ return *this;
+ }
+
// NOLINTNEXTLINE(readability-identifier-naming)
void push_back(const T &Elem) {
- if (Last == Cap)
- reserve(size() * 2);
- *Last++ = Elem;
- }
-
+ if (Last == Cap)
+ reserve(size() * 2);
+ *Last++ = Elem;
+ }
+
// NOLINTNEXTLINE(readability-identifier-naming)
- void pop_back() {
- assert(Last != First && "Popping empty vector!");
- --Last;
- }
-
- void dropBack(size_t Index) {
- assert(Index <= size() && "dropBack() can't expand!");
- Last = First + Index;
- }
-
+ void pop_back() {
+ assert(Last != First && "Popping empty vector!");
+ --Last;
+ }
+
+ void dropBack(size_t Index) {
+ assert(Index <= size() && "dropBack() can't expand!");
+ Last = First + Index;
+ }
+
T *begin() { return First; }
T *end() { return Last; }
-
- bool empty() const { return First == Last; }
- size_t size() const { return static_cast<size_t>(Last - First); }
+
+ bool empty() const { return First == Last; }
+ size_t size() const { return static_cast<size_t>(Last - First); }
T &back() {
- assert(Last != First && "Calling back() on empty vector!");
- return *(Last - 1);
- }
+ assert(Last != First && "Calling back() on empty vector!");
+ return *(Last - 1);
+ }
T &operator[](size_t Index) {
- assert(Index < size() && "Invalid access!");
- return *(begin() + Index);
- }
- void clear() { Last = First; }
-
- ~PODSmallVector() {
- if (!isInline())
- std::free(First);
- }
-};
-
+ assert(Index < size() && "Invalid access!");
+ return *(begin() + Index);
+ }
+ void clear() { Last = First; }
+
+ ~PODSmallVector() {
+ if (!isInline())
+ std::free(First);
+ }
+};
+
// Base class of all AST nodes. The AST is built by the parser, then is
// traversed by the printLeft/Right functions to produce a demangled string.
class Node {
@@ -648,14 +648,14 @@ class ReferenceType : public Node {
// Dig through any refs to refs, collapsing the ReferenceTypes as we go. The
// rule here is rvalue ref to rvalue ref collapses to a rvalue ref, and any
// other combination collapses to a lvalue ref.
- //
+ //
// A combination of a TemplateForwardReference and a back-ref Substitution
- // from an ill-formed string may have created a cycle; use cycle detection to
- // avoid looping forever.
+ // from an ill-formed string may have created a cycle; use cycle detection to
+ // avoid looping forever.
std::pair<ReferenceKind, const Node *> collapse(OutputBuffer &OB) const {
auto SoFar = std::make_pair(RK, Pointee);
- // Track the chain of nodes for the Floyd's 'tortoise and hare'
- // cycle-detection algorithm, since getSyntaxNode(S) is impure
+ // Track the chain of nodes for the Floyd's 'tortoise and hare'
+ // cycle-detection algorithm, since getSyntaxNode(S) is impure
PODSmallVector<const Node *, 8> Prev;
for (;;) {
const Node *SN = SoFar.second->getSyntaxNode(OB);
@@ -664,14 +664,14 @@ class ReferenceType : public Node {
auto *RT = static_cast<const ReferenceType *>(SN);
SoFar.second = RT->Pointee;
SoFar.first = std::min(SoFar.first, RT->RK);
-
- // The middle of Prev is the 'slow' pointer moving at half speed
- Prev.push_back(SoFar.second);
- if (Prev.size() > 1 && SoFar.second == Prev[(Prev.size() - 1) / 2]) {
- // Cycle detected
- SoFar.second = nullptr;
- break;
- }
+
+ // The middle of Prev is the 'slow' pointer moving at half speed
+ Prev.push_back(SoFar.second);
+ if (Prev.size() > 1 && SoFar.second == Prev[(Prev.size() - 1) / 2]) {
+ // Cycle detected
+ SoFar.second = nullptr;
+ break;
+ }
}
return SoFar;
}
@@ -692,8 +692,8 @@ public:
return;
SwapAndRestore<bool> SavePrinting(Printing, true);
std::pair<ReferenceKind, const Node *> Collapsed = collapse(OB);
- if (!Collapsed.second)
- return;
+ if (!Collapsed.second)
+ return;
Collapsed.second->printLeft(OB);
if (Collapsed.second->hasArray(OB))
OB += " ";
@@ -707,8 +707,8 @@ public:
return;
SwapAndRestore<bool> SavePrinting(Printing, true);
std::pair<ReferenceKind, const Node *> Collapsed = collapse(OB);
- if (!Collapsed.second)
- return;
+ if (!Collapsed.second)
+ return;
if (Collapsed.second->hasArray(OB) || Collapsed.second->hasFunction(OB))
OB += ")";
Collapsed.second->printRight(OB);
diff --git a/contrib/libs/cxxsupp/openmp/ya.make b/contrib/libs/cxxsupp/openmp/ya.make
index d95c6bfa39..2c64468375 100644
--- a/contrib/libs/cxxsupp/openmp/ya.make
+++ b/contrib/libs/cxxsupp/openmp/ya.make
@@ -35,7 +35,7 @@ IF (SANITIZER_TYPE == memory)
)
ENDIF()
-COMPILE_C_AS_CXX()
+COMPILE_C_AS_CXX()
CXXFLAGS(-fno-exceptions)
diff --git a/contrib/libs/cxxsupp/ya.make b/contrib/libs/cxxsupp/ya.make
index 65176002ad..6cd299ac8a 100644
--- a/contrib/libs/cxxsupp/ya.make
+++ b/contrib/libs/cxxsupp/ya.make
@@ -26,7 +26,7 @@ ENDIF()
END()
RECURSE(
- libcxx
+ libcxx
libcxxabi
libcxxrt
)
diff --git a/contrib/libs/libc_compat/update.sh b/contrib/libs/libc_compat/update.sh
index 4c055b8b06..4cee160904 100755
--- a/contrib/libs/libc_compat/update.sh
+++ b/contrib/libs/libc_compat/update.sh
@@ -38,11 +38,11 @@ curl "https://raw.githubusercontent.com/openbsd/src/master/lib/libc/stdlib/reall
> "collate.h"
> "stdlib.h"
> "unistd.h"
-
-mkdir -p include/uchar
-curl "https://git.musl-libc.org/cgit/musl/plain/include/uchar.h" --output "include/uchar/uchar.h"
-# TODO: provide c16rtomb, mbrtoc16, c32rtomb, mbrtoc32 implementations for uchar
-# if any code actually needs them
+
+mkdir -p include/uchar
+curl "https://git.musl-libc.org/cgit/musl/plain/include/uchar.h" --output "include/uchar/uchar.h"
+# TODO: provide c16rtomb, mbrtoc16, c32rtomb, mbrtoc32 implementations for uchar
+# if any code actually needs them
mkdir -p include/random/sys
curl "https://git.musl-libc.org/cgit/musl/plain/include/sys/random.h" --output "include/random/sys/random.h"
diff --git a/contrib/libs/libiconv/dynamic/ya.make b/contrib/libs/libiconv/dynamic/ya.make
index 3e6c9f29d8..f3a979206c 100644
--- a/contrib/libs/libiconv/dynamic/ya.make
+++ b/contrib/libs/libiconv/dynamic/ya.make
@@ -1,24 +1,24 @@
DYNAMIC_LIBRARY(iconv)
-
+
OWNER(
g:contrib g:cpp-contrib
)
-
-VERSION(1.13)
-
-LICENSE(
- LGPL-2.0-only
- LGPL-2.0-or-later
-)
-
-LICENSE_TEXTS(../.yandex_meta/licenses.list.txt)
-
+
+VERSION(1.13)
+
+LICENSE(
+ LGPL-2.0-only
+ LGPL-2.0-or-later
+)
+
+LICENSE_TEXTS(../.yandex_meta/licenses.list.txt)
+
PROVIDES(libiconv)
-NO_RUNTIME()
-
+NO_RUNTIME()
+
EXPORTS_SCRIPT(libiconv.exports)
-
+
DYNAMIC_LIBRARY_FROM(contrib/libs/libiconv/static)
-END()
+END()
diff --git a/contrib/libs/libiconv/static/ya.make b/contrib/libs/libiconv/static/ya.make
index b11aef6f17..83009f7ed9 100644
--- a/contrib/libs/libiconv/static/ya.make
+++ b/contrib/libs/libiconv/static/ya.make
@@ -1,35 +1,35 @@
-OWNER(
- g:contrib
- g:cpp-contrib
-)
-
-LIBRARY()
-
-VERSION(1.13)
-
-LICENSE(
+OWNER(
+ g:contrib
+ g:cpp-contrib
+)
+
+LIBRARY()
+
+VERSION(1.13)
+
+LICENSE(
LGPL-2.0-only AND
- LGPL-2.0-or-later
-)
+ LGPL-2.0-or-later
+)
+
+LICENSE_TEXTS(../.yandex_meta/licenses.list.txt)
-LICENSE_TEXTS(../.yandex_meta/licenses.list.txt)
-
PROVIDES(libiconv)
-NO_RUNTIME()
-
-NO_COMPILER_WARNINGS()
-
-IF (ARCADIA_ICONV_NOCJK)
+NO_RUNTIME()
+
+NO_COMPILER_WARNINGS()
+
+IF (ARCADIA_ICONV_NOCJK)
CFLAGS(
-DARCADIA_ICONV_NOCJK
)
-ENDIF()
-
-SRCDIR(contrib/libs/libiconv)
-
-SRCS(
- iconv.c
-)
-
-END()
+ENDIF()
+
+SRCDIR(contrib/libs/libiconv)
+
+SRCS(
+ iconv.c
+)
+
+END()
diff --git a/contrib/libs/libiconv/ya.make b/contrib/libs/libiconv/ya.make
index 693908c78d..e7c4e35e4c 100644
--- a/contrib/libs/libiconv/ya.make
+++ b/contrib/libs/libiconv/ya.make
@@ -3,29 +3,29 @@ OWNER(
g:cpp-contrib
)
-LIBRARY()
-
+LIBRARY()
+
VERSION(1.13)
LICENSE(Service-Dll-Harness)
-WITHOUT_LICENSE_TEXTS()
+WITHOUT_LICENSE_TEXTS()
NO_RUNTIME()
-IF (USE_DYNAMIC_ICONV)
- PEERDIR(
- contrib/libs/libiconv/dynamic
+IF (USE_DYNAMIC_ICONV)
+ PEERDIR(
+ contrib/libs/libiconv/dynamic
+ )
+ELSE()
+ PEERDIR(
+ contrib/libs/libiconv/static
)
-ELSE()
- PEERDIR(
- contrib/libs/libiconv/static
- )
ENDIF()
-END()
+END()
-RECURSE(
- dynamic
- static
-)
+RECURSE(
+ dynamic
+ static
+)
diff --git a/contrib/libs/libidn/dynamic/ya.make b/contrib/libs/libidn/dynamic/ya.make
index f33f4ad69c..c307c1950f 100644
--- a/contrib/libs/libidn/dynamic/ya.make
+++ b/contrib/libs/libidn/dynamic/ya.make
@@ -4,19 +4,19 @@ OWNER(
)
DYNAMIC_LIBRARY(idn)
-
+
VERSION(1.9)
-LICENSE(
- Custom-Punycode
- Ietf
- LGPL-2.0-or-later
- LGPL-2.1-only
- LGPL-2.1-or-later
-)
+LICENSE(
+ Custom-Punycode
+ Ietf
+ LGPL-2.0-or-later
+ LGPL-2.1-only
+ LGPL-2.1-or-later
+)
+
+LICENSE_TEXTS(../.yandex_meta/licenses.list.txt)
-LICENSE_TEXTS(../.yandex_meta/licenses.list.txt)
-
VERSION(1.9)
PROVIDES(libidn)
diff --git a/contrib/libs/libidn/static/ya.make b/contrib/libs/libidn/static/ya.make
index de3988f8bd..a927d7918e 100644
--- a/contrib/libs/libidn/static/ya.make
+++ b/contrib/libs/libidn/static/ya.make
@@ -1,8 +1,8 @@
-OWNER(
- g:contrib
- g:cpp-contrib
-)
-
+OWNER(
+ g:contrib
+ g:cpp-contrib
+)
+
LIBRARY()
LICENSE(
@@ -13,7 +13,7 @@ LICENSE(
LGPL-2.1-or-later
)
-LICENSE_TEXTS(../.yandex_meta/licenses.list.txt)
+LICENSE_TEXTS(../.yandex_meta/licenses.list.txt)
VERSION(1.9)
@@ -23,50 +23,50 @@ NO_RUNTIME()
NO_COMPILER_WARNINGS()
-ADDINCL(
- contrib/libs/libidn
-)
+ADDINCL(
+ contrib/libs/libidn
+)
-CFLAGS(
- -DHAVE_CONFIG_H
-)
+CFLAGS(
+ -DHAVE_CONFIG_H
+)
-IF (OS_WINDOWS)
- CFLAGS(
- -DLIBIDN_EXPORTS
+IF (OS_WINDOWS)
+ CFLAGS(
+ -DLIBIDN_EXPORTS
)
-ENDIF()
+ENDIF()
-IF (OS_ANDROID)
+IF (OS_ANDROID)
CFLAGS(
- -DHAVE_LOCALE_H=1
+ -DHAVE_LOCALE_H=1
)
ENDIF()
-SRCDIR(contrib/libs/libidn)
+SRCDIR(contrib/libs/libidn)
-SRCS(
- idn-free.c
- idna.c
- nfkc.c
- pr29.c
- profiles.c
- punycode.c
- rfc3454.c
- strerror-idna.c
- strerror-pr29.c
- strerror-punycode.c
- strerror-stringprep.c
- strerror-tld.c
- stringprep.c
- tld.c
- tlds.c
- toutf8.c
- version.c
- strverscmp.c
- striconv.c
- c-strcasecmp.c
- c-ctype.c
-)
+SRCS(
+ idn-free.c
+ idna.c
+ nfkc.c
+ pr29.c
+ profiles.c
+ punycode.c
+ rfc3454.c
+ strerror-idna.c
+ strerror-pr29.c
+ strerror-punycode.c
+ strerror-stringprep.c
+ strerror-tld.c
+ stringprep.c
+ tld.c
+ tlds.c
+ toutf8.c
+ version.c
+ strverscmp.c
+ striconv.c
+ c-strcasecmp.c
+ c-ctype.c
+)
END()
diff --git a/contrib/libs/libidn/ya.make b/contrib/libs/libidn/ya.make
index 5e50e9e245..678a813caa 100644
--- a/contrib/libs/libidn/ya.make
+++ b/contrib/libs/libidn/ya.make
@@ -1,13 +1,13 @@
-OWNER(
- g:contrib
- g:cpp-contrib
-)
-
+OWNER(
+ g:contrib
+ g:cpp-contrib
+)
+
LIBRARY()
LICENSE(Service-Dll-Harness)
-WITHOUT_LICENSE_TEXTS()
+WITHOUT_LICENSE_TEXTS()
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
@@ -17,19 +17,19 @@ NO_RUNTIME()
NO_COMPILER_WARNINGS()
-IF (USE_DYNAMIC_IDN)
+IF (USE_DYNAMIC_IDN)
PEERDIR(
contrib/libs/libidn/dynamic
)
ELSE()
- PEERDIR(
- contrib/libs/libidn/static
+ PEERDIR(
+ contrib/libs/libidn/static
)
ENDIF()
END()
-RECURSE(
- dynamic
- static
-)
+RECURSE(
+ dynamic
+ static
+)
diff --git a/contrib/libs/llvm12/include/llvm/Config/config-android.h b/contrib/libs/llvm12/include/llvm/Config/config-android.h
index d6cfd4f30c..3dfe68c951 100644
--- a/contrib/libs/llvm12/include/llvm/Config/config-android.h
+++ b/contrib/libs/llvm12/include/llvm/Config/config-android.h
@@ -1,7 +1,7 @@
#pragma once
-
-#include "config-linux.h"
-
+
+#include "config-linux.h"
+
#undef HAVE_BACKTRACE
#undef HAVE_PTHREAD_GETNAME_NP
#undef HAVE_PTHREAD_SETNAME_NP
diff --git a/contrib/libs/lz4/generated/lz4_ns.h b/contrib/libs/lz4/generated/lz4_ns.h
index e53d70960d..2dfbbf8ccc 100644
--- a/contrib/libs/lz4/generated/lz4_ns.h
+++ b/contrib/libs/lz4/generated/lz4_ns.h
@@ -13,7 +13,7 @@ namespace LZ4_NAMESPACE {
#include "../lz4.c"
struct TLZ4Methods ytbl = {
- LZ4_compress_default,
+ LZ4_compress_default,
};
}
diff --git a/contrib/libs/openssl/crypto/ya.make b/contrib/libs/openssl/crypto/ya.make
index d9d44d9370..3acfb0cac7 100644
--- a/contrib/libs/openssl/crypto/ya.make
+++ b/contrib/libs/openssl/crypto/ya.make
@@ -31,16 +31,16 @@ ADDINCL(
contrib/libs/openssl/include
)
-IF (OS_LINUX)
- IF (ARCH_ARM64)
- SET(LINUX_ARM64 yes)
+IF (OS_LINUX)
+ IF (ARCH_ARM64)
+ SET(LINUX_ARM64 yes)
ELSEIF (ARCH_ARM7)
- SET(LINUX_ARMV7 yes)
+ SET(LINUX_ARMV7 yes)
ELSEIF (ARCH_X86_64)
- SET(LINUX_X86_64 yes)
- ENDIF()
-ENDIF()
-
+ SET(LINUX_X86_64 yes)
+ ENDIF()
+ENDIF()
+
IF (OS_IOS)
IF (ARCH_ARM64)
SET(IOS_ARM64 yes)
@@ -110,7 +110,7 @@ IF (NOT IOS_I386 AND NOT ANDROID_I686 AND NOT WINDOWS_I686)
)
ENDIF()
-IF (NOT IOS_ARMV7 AND NOT ANDROID_ARMV7 AND NOT LINUX_ARMV7)
+IF (NOT IOS_ARMV7 AND NOT ANDROID_ARMV7 AND NOT LINUX_ARMV7)
CFLAGS(
-DVPAES_ASM
)
@@ -845,7 +845,7 @@ IF (NOT IOS_ARM64 AND NOT IOS_ARMV7)
)
ENDIF()
-IF (NOT IOS_ARMV7 AND NOT ANDROID_ARMV7 AND NOT LINUX_ARMV7)
+IF (NOT IOS_ARMV7 AND NOT ANDROID_ARMV7 AND NOT LINUX_ARMV7)
SRCS(
aes/aes_core.c
)
@@ -936,50 +936,50 @@ IF (OS_DARWIN AND ARCH_ARM64)
)
ENDIF()
-IF (OS_LINUX AND ARCH_ARM7)
- IF (CLANG)
+IF (OS_LINUX AND ARCH_ARM7)
+ IF (CLANG)
# XXX: This is a workarond for 'out of range immediate fixup value'
- # error with clang integrated assembler:
- # https://github.com/openssl/openssl/issues/7878
+ # error with clang integrated assembler:
+ # https://github.com/openssl/openssl/issues/7878
CFLAGS(
-mno-thumb
)
- ENDIF()
- CFLAGS(
- -DOPENSSL_PIC
- -DOPENSSL_BN_ASM_GF2m
- -DAES_ASM
- -DBSAES_ASM
- -DGHASH_ASM
- )
- SRCS(
- ../asm/android/arm/crypto/ec/ecp_nistz256-armv4.S
- ../asm/android/arm/crypto/poly1305/poly1305-armv4.S
- ../asm/android/arm/crypto/armv4cpuid.S
- ../asm/android/arm/crypto/bn/armv4-mont.S
- ../asm/android/arm/crypto/bn/armv4-gf2m.S
- ../asm/android/arm/crypto/aes/aes-armv4.S
- ../asm/android/arm/crypto/aes/bsaes-armv7.S
- ../asm/android/arm/crypto/aes/aesv8-armx.S
- ../asm/android/arm/crypto/sha/keccak1600-armv4.S
- ../asm/android/arm/crypto/sha/sha256-armv4.S
- ../asm/android/arm/crypto/sha/sha512-armv4.S
- ../asm/android/arm/crypto/sha/sha1-armv4-large.S
- ../asm/android/arm/crypto/chacha/chacha-armv4.S
- ../asm/android/arm/crypto/modes/ghashv8-armx.S
- ../asm/android/arm/crypto/modes/ghash-armv4.S
- armcap.c
- bn/bn_asm.c
- camellia/camellia.c
- camellia/cmll_cbc.c
- dso/dso_dlfcn.c
- rand/rand_vms.c
- rc4/rc4_enc.c
- rc4/rc4_skey.c
- whrlpool/wp_block.c
- )
-ENDIF()
-
+ ENDIF()
+ CFLAGS(
+ -DOPENSSL_PIC
+ -DOPENSSL_BN_ASM_GF2m
+ -DAES_ASM
+ -DBSAES_ASM
+ -DGHASH_ASM
+ )
+ SRCS(
+ ../asm/android/arm/crypto/ec/ecp_nistz256-armv4.S
+ ../asm/android/arm/crypto/poly1305/poly1305-armv4.S
+ ../asm/android/arm/crypto/armv4cpuid.S
+ ../asm/android/arm/crypto/bn/armv4-mont.S
+ ../asm/android/arm/crypto/bn/armv4-gf2m.S
+ ../asm/android/arm/crypto/aes/aes-armv4.S
+ ../asm/android/arm/crypto/aes/bsaes-armv7.S
+ ../asm/android/arm/crypto/aes/aesv8-armx.S
+ ../asm/android/arm/crypto/sha/keccak1600-armv4.S
+ ../asm/android/arm/crypto/sha/sha256-armv4.S
+ ../asm/android/arm/crypto/sha/sha512-armv4.S
+ ../asm/android/arm/crypto/sha/sha1-armv4-large.S
+ ../asm/android/arm/crypto/chacha/chacha-armv4.S
+ ../asm/android/arm/crypto/modes/ghashv8-armx.S
+ ../asm/android/arm/crypto/modes/ghash-armv4.S
+ armcap.c
+ bn/bn_asm.c
+ camellia/camellia.c
+ camellia/cmll_cbc.c
+ dso/dso_dlfcn.c
+ rand/rand_vms.c
+ rc4/rc4_enc.c
+ rc4/rc4_skey.c
+ whrlpool/wp_block.c
+ )
+ENDIF()
+
IF (OS_LINUX AND ARCH_AARCH64)
SRCS(
../asm/aarch64/crypto/aes/aesv8-armx.S
diff --git a/contrib/libs/openssl/include/openssl/opensslconf.h b/contrib/libs/openssl/include/openssl/opensslconf.h
index 73af98ae42..ecc930a39f 100644
--- a/contrib/libs/openssl/include/openssl/opensslconf.h
+++ b/contrib/libs/openssl/include/openssl/opensslconf.h
@@ -20,8 +20,8 @@
# include "opensslconf-android-arm.h"
#elif defined(__linux__) && defined(__aarch64__)
# include "opensslconf-linux_aarch64.h"
-#elif defined(__linux__) && defined(__arm__)
-# include "opensslconf-linux_arm.h"
+#elif defined(__linux__) && defined(__arm__)
+# include "opensslconf-linux_arm.h"
#elif defined(_MSC_VER) && defined(_M_X64)
# include "opensslconf-win-x86_64.h"
#elif defined(_MSC_VER) && defined(_M_IX86)
diff --git a/contrib/libs/openssl/ya.make b/contrib/libs/openssl/ya.make
index 68f24fee46..060d069785 100644
--- a/contrib/libs/openssl/ya.make
+++ b/contrib/libs/openssl/ya.make
@@ -28,16 +28,16 @@ ADDINCL(
contrib/libs/openssl
)
-IF (OS_LINUX)
- IF (ARCH_ARM64)
- SET(LINUX_ARM64 yes)
+IF (OS_LINUX)
+ IF (ARCH_ARM64)
+ SET(LINUX_ARM64 yes)
ELSEIF (ARCH_ARM7)
- SET(LINUX_ARMV7 yes)
+ SET(LINUX_ARMV7 yes)
ELSEIF (ARCH_X86_64)
- SET(LINUX_X86_64 yes)
- ENDIF()
-ENDIF()
-
+ SET(LINUX_X86_64 yes)
+ ENDIF()
+ENDIF()
+
IF (OS_IOS)
IF (ARCH_ARM64)
SET(IOS_ARM64 yes)
@@ -225,7 +225,7 @@ SRCS(
ssl/tls_srp.c
)
-IF (NOT IOS_ARMV7 AND NOT LINUX_ARMV7)
+IF (NOT IOS_ARMV7 AND NOT LINUX_ARMV7)
CFLAGS(
-DVPAES_ASM
)
@@ -238,7 +238,7 @@ IF (NOT IOS_ARM64 AND NOT IOS_ARMV7)
)
ENDIF()
-IF (OS_LINUX AND ARCH_ARM7 OR OS_LINUX AND ARCH_AARCH64 OR OS_LINUX AND ARCH_X86_64 OR OS_LINUX AND ARCH_PPC64LE)
+IF (OS_LINUX AND ARCH_ARM7 OR OS_LINUX AND ARCH_AARCH64 OR OS_LINUX AND ARCH_X86_64 OR OS_LINUX AND ARCH_PPC64LE)
SRCS(
engines/e_afalg.c
)
diff --git a/contrib/libs/protoc/ya.make b/contrib/libs/protoc/ya.make
index 00f230bb41..af6a52de35 100644
--- a/contrib/libs/protoc/ya.make
+++ b/contrib/libs/protoc/ya.make
@@ -24,9 +24,9 @@ PEERDIR(
contrib/libs/protobuf
)
-ADDINCL(
- GLOBAL contrib/libs/protoc/src
-)
+ADDINCL(
+ GLOBAL contrib/libs/protoc/src
+)
NO_COMPILER_WARNINGS()
diff --git a/contrib/libs/ya.make b/contrib/libs/ya.make
index af922adcc3..9c4640fdcf 100644
--- a/contrib/libs/ya.make
+++ b/contrib/libs/ya.make
@@ -9,10 +9,10 @@ RECURSE(
apache
apr
apr-util
- asio
+ asio
asmlib
authparser
- avs-device-sdk
+ avs-device-sdk
aws-sdk-cpp
backtrace
base64
@@ -20,8 +20,8 @@ RECURSE(
bdb/ut
benchmark
bento4
- bluez-clean-headers
- breakpad
+ bluez-clean-headers
+ breakpad
brotli
c-ares
cairo
@@ -153,12 +153,12 @@ RECURSE(
libgit2
libgraphqlparser
libheif
- libical
+ libical
libiconv
libidn
libidn2
libjpeg-turbo
- libjwt
+ libjwt
liblinear
libm
libmagic
@@ -173,7 +173,7 @@ RECURSE(
libpng
libpq
libpqxx
- libpsl
+ libpsl
libraw
librdkafka
librosa-cpp
@@ -224,12 +224,12 @@ RECURSE(
metrohash
mimalloc
minilzo
- minizip
+ minizip
mlir11
mms
mongo-c-driver
mongo-cxx-driver
- msgpack
+ msgpack
muparser
muparser/tests
musl
@@ -272,7 +272,7 @@ RECURSE(
#pire/ut
pixman
poco
- portaudio
+ portaudio
porto_api
proj
protobuf
@@ -337,9 +337,9 @@ RECURSE(
tf-2.4/sample_python
tf-2.4/tensorflow/python
thrax
- tinyalsa
+ tinyalsa
tlsh
- trace_viewer
+ trace_viewer
tralics
tree_sitter
uatraits
@@ -351,7 +351,7 @@ RECURSE(
vmaf
wapiti
webrtc
- websocketpp
+ websocketpp
woff2
xdelta3
xmlsec
@@ -359,7 +359,7 @@ RECURSE(
xxhash
xz
yajl
- yaml
+ yaml
yaml-cpp
zeromq
zlib
@@ -402,8 +402,8 @@ IF (OS_LINUX)
libnetfilter_log
libnetfilter_conntrack
openmpi
- sdbus-cpp
- systemd
+ sdbus-cpp
+ systemd
uuid
virtiofsd
)
diff --git a/contrib/libs/yaml/License b/contrib/libs/yaml/License
index 97d5ed5837..3d82c281ee 100644
--- a/contrib/libs/yaml/License
+++ b/contrib/libs/yaml/License
@@ -1,20 +1,20 @@
Copyright (c) 2017-2020 Ingy döt Net
Copyright (c) 2006-2016 Kirill Simonov
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-of the Software, and to permit persons to whom the Software is furnished to do
-so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/contrib/libs/yaml/include/yaml.h b/contrib/libs/yaml/include/yaml.h
index bc3696f6b3..7ccd5ed97a 100644
--- a/contrib/libs/yaml/include/yaml.h
+++ b/contrib/libs/yaml/include/yaml.h
@@ -1,1531 +1,1531 @@
-/**
- * @file yaml.h
- * @brief Public interface for libyaml.
- *
- * Include the header file with the code:
- * @code
- * #include <yaml.h>
- * @endcode
- */
-
-#ifndef YAML_H
-#define YAML_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-
-/**
- * @defgroup export Export Definitions
- * @{
- */
-
-/** The public API declaration. */
-
-#define YAML_DECLARE_STATIC
-
+/**
+ * @file yaml.h
+ * @brief Public interface for libyaml.
+ *
+ * Include the header file with the code:
+ * @code
+ * #include <yaml.h>
+ * @endcode
+ */
+
+#ifndef YAML_H
+#define YAML_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+/**
+ * @defgroup export Export Definitions
+ * @{
+ */
+
+/** The public API declaration. */
+
+#define YAML_DECLARE_STATIC
+
#if defined(__MINGW32__)
# define YAML_DECLARE(type) type
#elif defined(_WIN32)
-# if defined(YAML_DECLARE_STATIC)
-# define YAML_DECLARE(type) type
-# elif defined(YAML_DECLARE_EXPORT)
-# define YAML_DECLARE(type) __declspec(dllexport) type
-# else
-# define YAML_DECLARE(type) __declspec(dllimport) type
-# endif
-#else
-# define YAML_DECLARE(type) type
-#endif
-
-/** @} */
-
-/**
- * @defgroup version Version Information
- * @{
- */
-
-/**
- * Get the library version as a string.
- *
- * @returns The function returns the pointer to a static string of the form
- * @c "X.Y.Z", where @c X is the major version number, @c Y is a minor version
- * number, and @c Z is the patch version number.
- */
-
-YAML_DECLARE(const char *)
-yaml_get_version_string(void);
-
-/**
- * Get the library version numbers.
- *
- * @param[out] major Major version number.
- * @param[out] minor Minor version number.
- * @param[out] patch Patch version number.
- */
-
-YAML_DECLARE(void)
-yaml_get_version(int *major, int *minor, int *patch);
-
-/** @} */
-
-/**
- * @defgroup basic Basic Types
- * @{
- */
-
-/** The character type (UTF-8 octet). */
-typedef unsigned char yaml_char_t;
-
-/** The version directive data. */
-typedef struct yaml_version_directive_s {
- /** The major version number. */
- int major;
- /** The minor version number. */
- int minor;
-} yaml_version_directive_t;
-
-/** The tag directive data. */
-typedef struct yaml_tag_directive_s {
- /** The tag handle. */
- yaml_char_t *handle;
- /** The tag prefix. */
- yaml_char_t *prefix;
-} yaml_tag_directive_t;
-
-/** The stream encoding. */
-typedef enum yaml_encoding_e {
- /** Let the parser choose the encoding. */
- YAML_ANY_ENCODING,
- /** The default UTF-8 encoding. */
- YAML_UTF8_ENCODING,
- /** The UTF-16-LE encoding with BOM. */
- YAML_UTF16LE_ENCODING,
- /** The UTF-16-BE encoding with BOM. */
- YAML_UTF16BE_ENCODING
-} yaml_encoding_t;
-
-/** Line break types. */
-
-typedef enum yaml_break_e {
- /** Let the parser choose the break type. */
- YAML_ANY_BREAK,
- /** Use CR for line breaks (Mac style). */
- YAML_CR_BREAK,
- /** Use LN for line breaks (Unix style). */
- YAML_LN_BREAK,
- /** Use CR LN for line breaks (DOS style). */
- YAML_CRLN_BREAK
-} yaml_break_t;
-
-/** Many bad things could happen with the parser and emitter. */
-typedef enum yaml_error_type_e {
- /** No error is produced. */
- YAML_NO_ERROR,
-
- /** Cannot allocate or reallocate a block of memory. */
- YAML_MEMORY_ERROR,
-
- /** Cannot read or decode the input stream. */
- YAML_READER_ERROR,
- /** Cannot scan the input stream. */
- YAML_SCANNER_ERROR,
- /** Cannot parse the input stream. */
- YAML_PARSER_ERROR,
- /** Cannot compose a YAML document. */
- YAML_COMPOSER_ERROR,
-
- /** Cannot write to the output stream. */
- YAML_WRITER_ERROR,
- /** Cannot emit a YAML stream. */
- YAML_EMITTER_ERROR
-} yaml_error_type_t;
-
-/** The pointer position. */
-typedef struct yaml_mark_s {
- /** The position index. */
- size_t index;
-
- /** The position line. */
- size_t line;
-
- /** The position column. */
- size_t column;
-} yaml_mark_t;
-
-/** @} */
-
-/**
- * @defgroup styles Node Styles
- * @{
- */
-
-/** Scalar styles. */
-typedef enum yaml_scalar_style_e {
- /** Let the emitter choose the style. */
- YAML_ANY_SCALAR_STYLE,
-
- /** The plain scalar style. */
- YAML_PLAIN_SCALAR_STYLE,
-
- /** The single-quoted scalar style. */
- YAML_SINGLE_QUOTED_SCALAR_STYLE,
- /** The double-quoted scalar style. */
- YAML_DOUBLE_QUOTED_SCALAR_STYLE,
-
- /** The literal scalar style. */
- YAML_LITERAL_SCALAR_STYLE,
- /** The folded scalar style. */
- YAML_FOLDED_SCALAR_STYLE
-} yaml_scalar_style_t;
-
-/** Sequence styles. */
-typedef enum yaml_sequence_style_e {
- /** Let the emitter choose the style. */
- YAML_ANY_SEQUENCE_STYLE,
-
- /** The block sequence style. */
- YAML_BLOCK_SEQUENCE_STYLE,
- /** The flow sequence style. */
- YAML_FLOW_SEQUENCE_STYLE
-} yaml_sequence_style_t;
-
-/** Mapping styles. */
-typedef enum yaml_mapping_style_e {
- /** Let the emitter choose the style. */
- YAML_ANY_MAPPING_STYLE,
-
- /** The block mapping style. */
- YAML_BLOCK_MAPPING_STYLE,
- /** The flow mapping style. */
- YAML_FLOW_MAPPING_STYLE
-/* YAML_FLOW_SET_MAPPING_STYLE */
-} yaml_mapping_style_t;
-
-/** @} */
-
-/**
- * @defgroup tokens Tokens
- * @{
- */
-
-/** Token types. */
-typedef enum yaml_token_type_e {
- /** An empty token. */
- YAML_NO_TOKEN,
-
- /** A STREAM-START token. */
- YAML_STREAM_START_TOKEN,
- /** A STREAM-END token. */
- YAML_STREAM_END_TOKEN,
-
- /** A VERSION-DIRECTIVE token. */
- YAML_VERSION_DIRECTIVE_TOKEN,
- /** A TAG-DIRECTIVE token. */
- YAML_TAG_DIRECTIVE_TOKEN,
- /** A DOCUMENT-START token. */
- YAML_DOCUMENT_START_TOKEN,
- /** A DOCUMENT-END token. */
- YAML_DOCUMENT_END_TOKEN,
-
- /** A BLOCK-SEQUENCE-START token. */
- YAML_BLOCK_SEQUENCE_START_TOKEN,
+# if defined(YAML_DECLARE_STATIC)
+# define YAML_DECLARE(type) type
+# elif defined(YAML_DECLARE_EXPORT)
+# define YAML_DECLARE(type) __declspec(dllexport) type
+# else
+# define YAML_DECLARE(type) __declspec(dllimport) type
+# endif
+#else
+# define YAML_DECLARE(type) type
+#endif
+
+/** @} */
+
+/**
+ * @defgroup version Version Information
+ * @{
+ */
+
+/**
+ * Get the library version as a string.
+ *
+ * @returns The function returns the pointer to a static string of the form
+ * @c "X.Y.Z", where @c X is the major version number, @c Y is a minor version
+ * number, and @c Z is the patch version number.
+ */
+
+YAML_DECLARE(const char *)
+yaml_get_version_string(void);
+
+/**
+ * Get the library version numbers.
+ *
+ * @param[out] major Major version number.
+ * @param[out] minor Minor version number.
+ * @param[out] patch Patch version number.
+ */
+
+YAML_DECLARE(void)
+yaml_get_version(int *major, int *minor, int *patch);
+
+/** @} */
+
+/**
+ * @defgroup basic Basic Types
+ * @{
+ */
+
+/** The character type (UTF-8 octet). */
+typedef unsigned char yaml_char_t;
+
+/** The version directive data. */
+typedef struct yaml_version_directive_s {
+ /** The major version number. */
+ int major;
+ /** The minor version number. */
+ int minor;
+} yaml_version_directive_t;
+
+/** The tag directive data. */
+typedef struct yaml_tag_directive_s {
+ /** The tag handle. */
+ yaml_char_t *handle;
+ /** The tag prefix. */
+ yaml_char_t *prefix;
+} yaml_tag_directive_t;
+
+/** The stream encoding. */
+typedef enum yaml_encoding_e {
+ /** Let the parser choose the encoding. */
+ YAML_ANY_ENCODING,
+ /** The default UTF-8 encoding. */
+ YAML_UTF8_ENCODING,
+ /** The UTF-16-LE encoding with BOM. */
+ YAML_UTF16LE_ENCODING,
+ /** The UTF-16-BE encoding with BOM. */
+ YAML_UTF16BE_ENCODING
+} yaml_encoding_t;
+
+/** Line break types. */
+
+typedef enum yaml_break_e {
+ /** Let the parser choose the break type. */
+ YAML_ANY_BREAK,
+ /** Use CR for line breaks (Mac style). */
+ YAML_CR_BREAK,
+ /** Use LN for line breaks (Unix style). */
+ YAML_LN_BREAK,
+ /** Use CR LN for line breaks (DOS style). */
+ YAML_CRLN_BREAK
+} yaml_break_t;
+
+/** Many bad things could happen with the parser and emitter. */
+typedef enum yaml_error_type_e {
+ /** No error is produced. */
+ YAML_NO_ERROR,
+
+ /** Cannot allocate or reallocate a block of memory. */
+ YAML_MEMORY_ERROR,
+
+ /** Cannot read or decode the input stream. */
+ YAML_READER_ERROR,
+ /** Cannot scan the input stream. */
+ YAML_SCANNER_ERROR,
+ /** Cannot parse the input stream. */
+ YAML_PARSER_ERROR,
+ /** Cannot compose a YAML document. */
+ YAML_COMPOSER_ERROR,
+
+ /** Cannot write to the output stream. */
+ YAML_WRITER_ERROR,
+ /** Cannot emit a YAML stream. */
+ YAML_EMITTER_ERROR
+} yaml_error_type_t;
+
+/** The pointer position. */
+typedef struct yaml_mark_s {
+ /** The position index. */
+ size_t index;
+
+ /** The position line. */
+ size_t line;
+
+ /** The position column. */
+ size_t column;
+} yaml_mark_t;
+
+/** @} */
+
+/**
+ * @defgroup styles Node Styles
+ * @{
+ */
+
+/** Scalar styles. */
+typedef enum yaml_scalar_style_e {
+ /** Let the emitter choose the style. */
+ YAML_ANY_SCALAR_STYLE,
+
+ /** The plain scalar style. */
+ YAML_PLAIN_SCALAR_STYLE,
+
+ /** The single-quoted scalar style. */
+ YAML_SINGLE_QUOTED_SCALAR_STYLE,
+ /** The double-quoted scalar style. */
+ YAML_DOUBLE_QUOTED_SCALAR_STYLE,
+
+ /** The literal scalar style. */
+ YAML_LITERAL_SCALAR_STYLE,
+ /** The folded scalar style. */
+ YAML_FOLDED_SCALAR_STYLE
+} yaml_scalar_style_t;
+
+/** Sequence styles. */
+typedef enum yaml_sequence_style_e {
+ /** Let the emitter choose the style. */
+ YAML_ANY_SEQUENCE_STYLE,
+
+ /** The block sequence style. */
+ YAML_BLOCK_SEQUENCE_STYLE,
+ /** The flow sequence style. */
+ YAML_FLOW_SEQUENCE_STYLE
+} yaml_sequence_style_t;
+
+/** Mapping styles. */
+typedef enum yaml_mapping_style_e {
+ /** Let the emitter choose the style. */
+ YAML_ANY_MAPPING_STYLE,
+
+ /** The block mapping style. */
+ YAML_BLOCK_MAPPING_STYLE,
+ /** The flow mapping style. */
+ YAML_FLOW_MAPPING_STYLE
+/* YAML_FLOW_SET_MAPPING_STYLE */
+} yaml_mapping_style_t;
+
+/** @} */
+
+/**
+ * @defgroup tokens Tokens
+ * @{
+ */
+
+/** Token types. */
+typedef enum yaml_token_type_e {
+ /** An empty token. */
+ YAML_NO_TOKEN,
+
+ /** A STREAM-START token. */
+ YAML_STREAM_START_TOKEN,
+ /** A STREAM-END token. */
+ YAML_STREAM_END_TOKEN,
+
+ /** A VERSION-DIRECTIVE token. */
+ YAML_VERSION_DIRECTIVE_TOKEN,
+ /** A TAG-DIRECTIVE token. */
+ YAML_TAG_DIRECTIVE_TOKEN,
+ /** A DOCUMENT-START token. */
+ YAML_DOCUMENT_START_TOKEN,
+ /** A DOCUMENT-END token. */
+ YAML_DOCUMENT_END_TOKEN,
+
+ /** A BLOCK-SEQUENCE-START token. */
+ YAML_BLOCK_SEQUENCE_START_TOKEN,
/** A BLOCK-MAPPING-START token. */
- YAML_BLOCK_MAPPING_START_TOKEN,
- /** A BLOCK-END token. */
- YAML_BLOCK_END_TOKEN,
-
- /** A FLOW-SEQUENCE-START token. */
- YAML_FLOW_SEQUENCE_START_TOKEN,
- /** A FLOW-SEQUENCE-END token. */
- YAML_FLOW_SEQUENCE_END_TOKEN,
- /** A FLOW-MAPPING-START token. */
- YAML_FLOW_MAPPING_START_TOKEN,
- /** A FLOW-MAPPING-END token. */
- YAML_FLOW_MAPPING_END_TOKEN,
-
- /** A BLOCK-ENTRY token. */
- YAML_BLOCK_ENTRY_TOKEN,
- /** A FLOW-ENTRY token. */
- YAML_FLOW_ENTRY_TOKEN,
- /** A KEY token. */
- YAML_KEY_TOKEN,
- /** A VALUE token. */
- YAML_VALUE_TOKEN,
-
- /** An ALIAS token. */
- YAML_ALIAS_TOKEN,
- /** An ANCHOR token. */
- YAML_ANCHOR_TOKEN,
- /** A TAG token. */
- YAML_TAG_TOKEN,
- /** A SCALAR token. */
- YAML_SCALAR_TOKEN
-} yaml_token_type_t;
-
-/** The token structure. */
-typedef struct yaml_token_s {
-
- /** The token type. */
- yaml_token_type_t type;
-
- /** The token data. */
- union {
-
- /** The stream start (for @c YAML_STREAM_START_TOKEN). */
- struct {
- /** The stream encoding. */
- yaml_encoding_t encoding;
- } stream_start;
-
- /** The alias (for @c YAML_ALIAS_TOKEN). */
- struct {
- /** The alias value. */
- yaml_char_t *value;
- } alias;
-
- /** The anchor (for @c YAML_ANCHOR_TOKEN). */
- struct {
- /** The anchor value. */
- yaml_char_t *value;
- } anchor;
-
- /** The tag (for @c YAML_TAG_TOKEN). */
- struct {
- /** The tag handle. */
- yaml_char_t *handle;
- /** The tag suffix. */
- yaml_char_t *suffix;
- } tag;
-
- /** The scalar value (for @c YAML_SCALAR_TOKEN). */
- struct {
- /** The scalar value. */
- yaml_char_t *value;
- /** The length of the scalar value. */
- size_t length;
- /** The scalar style. */
- yaml_scalar_style_t style;
- } scalar;
-
- /** The version directive (for @c YAML_VERSION_DIRECTIVE_TOKEN). */
- struct {
- /** The major version number. */
- int major;
- /** The minor version number. */
- int minor;
- } version_directive;
-
- /** The tag directive (for @c YAML_TAG_DIRECTIVE_TOKEN). */
- struct {
- /** The tag handle. */
- yaml_char_t *handle;
- /** The tag prefix. */
- yaml_char_t *prefix;
- } tag_directive;
-
- } data;
-
- /** The beginning of the token. */
- yaml_mark_t start_mark;
- /** The end of the token. */
- yaml_mark_t end_mark;
-
-} yaml_token_t;
-
-/**
- * Free any memory allocated for a token object.
- *
- * @param[in,out] token A token object.
- */
-
-YAML_DECLARE(void)
-yaml_token_delete(yaml_token_t *token);
-
-/** @} */
-
-/**
- * @defgroup events Events
- * @{
- */
-
-/** Event types. */
-typedef enum yaml_event_type_e {
- /** An empty event. */
- YAML_NO_EVENT,
-
- /** A STREAM-START event. */
- YAML_STREAM_START_EVENT,
- /** A STREAM-END event. */
- YAML_STREAM_END_EVENT,
-
- /** A DOCUMENT-START event. */
- YAML_DOCUMENT_START_EVENT,
- /** A DOCUMENT-END event. */
- YAML_DOCUMENT_END_EVENT,
-
- /** An ALIAS event. */
- YAML_ALIAS_EVENT,
- /** A SCALAR event. */
- YAML_SCALAR_EVENT,
-
- /** A SEQUENCE-START event. */
- YAML_SEQUENCE_START_EVENT,
- /** A SEQUENCE-END event. */
- YAML_SEQUENCE_END_EVENT,
-
- /** A MAPPING-START event. */
- YAML_MAPPING_START_EVENT,
- /** A MAPPING-END event. */
- YAML_MAPPING_END_EVENT
-} yaml_event_type_t;
-
-/** The event structure. */
-typedef struct yaml_event_s {
-
- /** The event type. */
- yaml_event_type_t type;
-
- /** The event data. */
- union {
+ YAML_BLOCK_MAPPING_START_TOKEN,
+ /** A BLOCK-END token. */
+ YAML_BLOCK_END_TOKEN,
+
+ /** A FLOW-SEQUENCE-START token. */
+ YAML_FLOW_SEQUENCE_START_TOKEN,
+ /** A FLOW-SEQUENCE-END token. */
+ YAML_FLOW_SEQUENCE_END_TOKEN,
+ /** A FLOW-MAPPING-START token. */
+ YAML_FLOW_MAPPING_START_TOKEN,
+ /** A FLOW-MAPPING-END token. */
+ YAML_FLOW_MAPPING_END_TOKEN,
+
+ /** A BLOCK-ENTRY token. */
+ YAML_BLOCK_ENTRY_TOKEN,
+ /** A FLOW-ENTRY token. */
+ YAML_FLOW_ENTRY_TOKEN,
+ /** A KEY token. */
+ YAML_KEY_TOKEN,
+ /** A VALUE token. */
+ YAML_VALUE_TOKEN,
+
+ /** An ALIAS token. */
+ YAML_ALIAS_TOKEN,
+ /** An ANCHOR token. */
+ YAML_ANCHOR_TOKEN,
+ /** A TAG token. */
+ YAML_TAG_TOKEN,
+ /** A SCALAR token. */
+ YAML_SCALAR_TOKEN
+} yaml_token_type_t;
+
+/** The token structure. */
+typedef struct yaml_token_s {
+
+ /** The token type. */
+ yaml_token_type_t type;
+
+ /** The token data. */
+ union {
+
+ /** The stream start (for @c YAML_STREAM_START_TOKEN). */
+ struct {
+ /** The stream encoding. */
+ yaml_encoding_t encoding;
+ } stream_start;
+
+ /** The alias (for @c YAML_ALIAS_TOKEN). */
+ struct {
+ /** The alias value. */
+ yaml_char_t *value;
+ } alias;
+
+ /** The anchor (for @c YAML_ANCHOR_TOKEN). */
+ struct {
+ /** The anchor value. */
+ yaml_char_t *value;
+ } anchor;
+
+ /** The tag (for @c YAML_TAG_TOKEN). */
+ struct {
+ /** The tag handle. */
+ yaml_char_t *handle;
+ /** The tag suffix. */
+ yaml_char_t *suffix;
+ } tag;
+
+ /** The scalar value (for @c YAML_SCALAR_TOKEN). */
+ struct {
+ /** The scalar value. */
+ yaml_char_t *value;
+ /** The length of the scalar value. */
+ size_t length;
+ /** The scalar style. */
+ yaml_scalar_style_t style;
+ } scalar;
+
+ /** The version directive (for @c YAML_VERSION_DIRECTIVE_TOKEN). */
+ struct {
+ /** The major version number. */
+ int major;
+ /** The minor version number. */
+ int minor;
+ } version_directive;
+
+ /** The tag directive (for @c YAML_TAG_DIRECTIVE_TOKEN). */
+ struct {
+ /** The tag handle. */
+ yaml_char_t *handle;
+ /** The tag prefix. */
+ yaml_char_t *prefix;
+ } tag_directive;
+
+ } data;
+
+ /** The beginning of the token. */
+ yaml_mark_t start_mark;
+ /** The end of the token. */
+ yaml_mark_t end_mark;
+
+} yaml_token_t;
+
+/**
+ * Free any memory allocated for a token object.
+ *
+ * @param[in,out] token A token object.
+ */
+
+YAML_DECLARE(void)
+yaml_token_delete(yaml_token_t *token);
+
+/** @} */
+
+/**
+ * @defgroup events Events
+ * @{
+ */
+
+/** Event types. */
+typedef enum yaml_event_type_e {
+ /** An empty event. */
+ YAML_NO_EVENT,
+
+ /** A STREAM-START event. */
+ YAML_STREAM_START_EVENT,
+ /** A STREAM-END event. */
+ YAML_STREAM_END_EVENT,
+
+ /** A DOCUMENT-START event. */
+ YAML_DOCUMENT_START_EVENT,
+ /** A DOCUMENT-END event. */
+ YAML_DOCUMENT_END_EVENT,
+
+ /** An ALIAS event. */
+ YAML_ALIAS_EVENT,
+ /** A SCALAR event. */
+ YAML_SCALAR_EVENT,
+
+ /** A SEQUENCE-START event. */
+ YAML_SEQUENCE_START_EVENT,
+ /** A SEQUENCE-END event. */
+ YAML_SEQUENCE_END_EVENT,
+
+ /** A MAPPING-START event. */
+ YAML_MAPPING_START_EVENT,
+ /** A MAPPING-END event. */
+ YAML_MAPPING_END_EVENT
+} yaml_event_type_t;
+
+/** The event structure. */
+typedef struct yaml_event_s {
+
+ /** The event type. */
+ yaml_event_type_t type;
+
+ /** The event data. */
+ union {
- /** The stream parameters (for @c YAML_STREAM_START_EVENT). */
- struct {
- /** The document encoding. */
- yaml_encoding_t encoding;
- } stream_start;
-
- /** The document parameters (for @c YAML_DOCUMENT_START_EVENT). */
- struct {
- /** The version directive. */
- yaml_version_directive_t *version_directive;
-
- /** The list of tag directives. */
- struct {
- /** The beginning of the tag directives list. */
- yaml_tag_directive_t *start;
- /** The end of the tag directives list. */
- yaml_tag_directive_t *end;
- } tag_directives;
-
- /** Is the document indicator implicit? */
- int implicit;
- } document_start;
-
- /** The document end parameters (for @c YAML_DOCUMENT_END_EVENT). */
- struct {
- /** Is the document end indicator implicit? */
- int implicit;
- } document_end;
-
- /** The alias parameters (for @c YAML_ALIAS_EVENT). */
- struct {
- /** The anchor. */
- yaml_char_t *anchor;
- } alias;
-
- /** The scalar parameters (for @c YAML_SCALAR_EVENT). */
- struct {
- /** The anchor. */
- yaml_char_t *anchor;
- /** The tag. */
- yaml_char_t *tag;
- /** The scalar value. */
- yaml_char_t *value;
- /** The length of the scalar value. */
- size_t length;
- /** Is the tag optional for the plain style? */
- int plain_implicit;
- /** Is the tag optional for any non-plain style? */
- int quoted_implicit;
- /** The scalar style. */
- yaml_scalar_style_t style;
- } scalar;
-
- /** The sequence parameters (for @c YAML_SEQUENCE_START_EVENT). */
- struct {
- /** The anchor. */
- yaml_char_t *anchor;
- /** The tag. */
- yaml_char_t *tag;
- /** Is the tag optional? */
- int implicit;
- /** The sequence style. */
- yaml_sequence_style_t style;
- } sequence_start;
-
- /** The mapping parameters (for @c YAML_MAPPING_START_EVENT). */
- struct {
- /** The anchor. */
- yaml_char_t *anchor;
- /** The tag. */
- yaml_char_t *tag;
- /** Is the tag optional? */
- int implicit;
- /** The mapping style. */
- yaml_mapping_style_t style;
- } mapping_start;
-
- } data;
-
- /** The beginning of the event. */
- yaml_mark_t start_mark;
- /** The end of the event. */
- yaml_mark_t end_mark;
-
-} yaml_event_t;
-
-/**
- * Create the STREAM-START event.
- *
- * @param[out] event An empty event object.
- * @param[in] encoding The stream encoding.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_stream_start_event_initialize(yaml_event_t *event,
- yaml_encoding_t encoding);
-
-/**
- * Create the STREAM-END event.
- *
- * @param[out] event An empty event object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_stream_end_event_initialize(yaml_event_t *event);
-
-/**
- * Create the DOCUMENT-START event.
- *
- * The @a implicit argument is considered as a stylistic parameter and may be
- * ignored by the emitter.
- *
- * @param[out] event An empty event object.
- * @param[in] version_directive The %YAML directive value or
- * @c NULL.
- * @param[in] tag_directives_start The beginning of the %TAG
- * directives list.
- * @param[in] tag_directives_end The end of the %TAG directives
- * list.
- * @param[in] implicit If the document start indicator is
- * implicit.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_document_start_event_initialize(yaml_event_t *event,
- yaml_version_directive_t *version_directive,
- yaml_tag_directive_t *tag_directives_start,
- yaml_tag_directive_t *tag_directives_end,
- int implicit);
-
-/**
- * Create the DOCUMENT-END event.
- *
- * The @a implicit argument is considered as a stylistic parameter and may be
- * ignored by the emitter.
- *
- * @param[out] event An empty event object.
- * @param[in] implicit If the document end indicator is implicit.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_document_end_event_initialize(yaml_event_t *event, int implicit);
-
-/**
- * Create an ALIAS event.
- *
- * @param[out] event An empty event object.
- * @param[in] anchor The anchor value.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
+ /** The stream parameters (for @c YAML_STREAM_START_EVENT). */
+ struct {
+ /** The document encoding. */
+ yaml_encoding_t encoding;
+ } stream_start;
+
+ /** The document parameters (for @c YAML_DOCUMENT_START_EVENT). */
+ struct {
+ /** The version directive. */
+ yaml_version_directive_t *version_directive;
+
+ /** The list of tag directives. */
+ struct {
+ /** The beginning of the tag directives list. */
+ yaml_tag_directive_t *start;
+ /** The end of the tag directives list. */
+ yaml_tag_directive_t *end;
+ } tag_directives;
+
+ /** Is the document indicator implicit? */
+ int implicit;
+ } document_start;
+
+ /** The document end parameters (for @c YAML_DOCUMENT_END_EVENT). */
+ struct {
+ /** Is the document end indicator implicit? */
+ int implicit;
+ } document_end;
+
+ /** The alias parameters (for @c YAML_ALIAS_EVENT). */
+ struct {
+ /** The anchor. */
+ yaml_char_t *anchor;
+ } alias;
+
+ /** The scalar parameters (for @c YAML_SCALAR_EVENT). */
+ struct {
+ /** The anchor. */
+ yaml_char_t *anchor;
+ /** The tag. */
+ yaml_char_t *tag;
+ /** The scalar value. */
+ yaml_char_t *value;
+ /** The length of the scalar value. */
+ size_t length;
+ /** Is the tag optional for the plain style? */
+ int plain_implicit;
+ /** Is the tag optional for any non-plain style? */
+ int quoted_implicit;
+ /** The scalar style. */
+ yaml_scalar_style_t style;
+ } scalar;
+
+ /** The sequence parameters (for @c YAML_SEQUENCE_START_EVENT). */
+ struct {
+ /** The anchor. */
+ yaml_char_t *anchor;
+ /** The tag. */
+ yaml_char_t *tag;
+ /** Is the tag optional? */
+ int implicit;
+ /** The sequence style. */
+ yaml_sequence_style_t style;
+ } sequence_start;
+
+ /** The mapping parameters (for @c YAML_MAPPING_START_EVENT). */
+ struct {
+ /** The anchor. */
+ yaml_char_t *anchor;
+ /** The tag. */
+ yaml_char_t *tag;
+ /** Is the tag optional? */
+ int implicit;
+ /** The mapping style. */
+ yaml_mapping_style_t style;
+ } mapping_start;
+
+ } data;
+
+ /** The beginning of the event. */
+ yaml_mark_t start_mark;
+ /** The end of the event. */
+ yaml_mark_t end_mark;
+
+} yaml_event_t;
+
+/**
+ * Create the STREAM-START event.
+ *
+ * @param[out] event An empty event object.
+ * @param[in] encoding The stream encoding.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_stream_start_event_initialize(yaml_event_t *event,
+ yaml_encoding_t encoding);
+
+/**
+ * Create the STREAM-END event.
+ *
+ * @param[out] event An empty event object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_stream_end_event_initialize(yaml_event_t *event);
+
+/**
+ * Create the DOCUMENT-START event.
+ *
+ * The @a implicit argument is considered as a stylistic parameter and may be
+ * ignored by the emitter.
+ *
+ * @param[out] event An empty event object.
+ * @param[in] version_directive The %YAML directive value or
+ * @c NULL.
+ * @param[in] tag_directives_start The beginning of the %TAG
+ * directives list.
+ * @param[in] tag_directives_end The end of the %TAG directives
+ * list.
+ * @param[in] implicit If the document start indicator is
+ * implicit.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_document_start_event_initialize(yaml_event_t *event,
+ yaml_version_directive_t *version_directive,
+ yaml_tag_directive_t *tag_directives_start,
+ yaml_tag_directive_t *tag_directives_end,
+ int implicit);
+
+/**
+ * Create the DOCUMENT-END event.
+ *
+ * The @a implicit argument is considered as a stylistic parameter and may be
+ * ignored by the emitter.
+ *
+ * @param[out] event An empty event object.
+ * @param[in] implicit If the document end indicator is implicit.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_document_end_event_initialize(yaml_event_t *event, int implicit);
+
+/**
+ * Create an ALIAS event.
+ *
+ * @param[out] event An empty event object.
+ * @param[in] anchor The anchor value.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
yaml_alias_event_initialize(yaml_event_t *event, const yaml_char_t *anchor);
-
-/**
- * Create a SCALAR event.
- *
- * The @a style argument may be ignored by the emitter.
- *
- * Either the @a tag attribute or one of the @a plain_implicit and
- * @a quoted_implicit flags must be set.
- *
- * @param[out] event An empty event object.
- * @param[in] anchor The scalar anchor or @c NULL.
- * @param[in] tag The scalar tag or @c NULL.
- * @param[in] value The scalar value.
- * @param[in] length The length of the scalar value.
- * @param[in] plain_implicit If the tag may be omitted for the plain
- * style.
- * @param[in] quoted_implicit If the tag may be omitted for any
- * non-plain style.
- * @param[in] style The scalar style.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_scalar_event_initialize(yaml_event_t *event,
+
+/**
+ * Create a SCALAR event.
+ *
+ * The @a style argument may be ignored by the emitter.
+ *
+ * Either the @a tag attribute or one of the @a plain_implicit and
+ * @a quoted_implicit flags must be set.
+ *
+ * @param[out] event An empty event object.
+ * @param[in] anchor The scalar anchor or @c NULL.
+ * @param[in] tag The scalar tag or @c NULL.
+ * @param[in] value The scalar value.
+ * @param[in] length The length of the scalar value.
+ * @param[in] plain_implicit If the tag may be omitted for the plain
+ * style.
+ * @param[in] quoted_implicit If the tag may be omitted for any
+ * non-plain style.
+ * @param[in] style The scalar style.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_scalar_event_initialize(yaml_event_t *event,
const yaml_char_t *anchor, const yaml_char_t *tag,
const yaml_char_t *value, int length,
- int plain_implicit, int quoted_implicit,
- yaml_scalar_style_t style);
-
-/**
- * Create a SEQUENCE-START event.
- *
- * The @a style argument may be ignored by the emitter.
- *
- * Either the @a tag attribute or the @a implicit flag must be set.
- *
- * @param[out] event An empty event object.
- * @param[in] anchor The sequence anchor or @c NULL.
- * @param[in] tag The sequence tag or @c NULL.
- * @param[in] implicit If the tag may be omitted.
- * @param[in] style The sequence style.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_sequence_start_event_initialize(yaml_event_t *event,
+ int plain_implicit, int quoted_implicit,
+ yaml_scalar_style_t style);
+
+/**
+ * Create a SEQUENCE-START event.
+ *
+ * The @a style argument may be ignored by the emitter.
+ *
+ * Either the @a tag attribute or the @a implicit flag must be set.
+ *
+ * @param[out] event An empty event object.
+ * @param[in] anchor The sequence anchor or @c NULL.
+ * @param[in] tag The sequence tag or @c NULL.
+ * @param[in] implicit If the tag may be omitted.
+ * @param[in] style The sequence style.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_sequence_start_event_initialize(yaml_event_t *event,
const yaml_char_t *anchor, const yaml_char_t *tag, int implicit,
- yaml_sequence_style_t style);
-
-/**
- * Create a SEQUENCE-END event.
- *
- * @param[out] event An empty event object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_sequence_end_event_initialize(yaml_event_t *event);
-
-/**
- * Create a MAPPING-START event.
- *
- * The @a style argument may be ignored by the emitter.
- *
- * Either the @a tag attribute or the @a implicit flag must be set.
- *
- * @param[out] event An empty event object.
- * @param[in] anchor The mapping anchor or @c NULL.
- * @param[in] tag The mapping tag or @c NULL.
- * @param[in] implicit If the tag may be omitted.
- * @param[in] style The mapping style.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_mapping_start_event_initialize(yaml_event_t *event,
+ yaml_sequence_style_t style);
+
+/**
+ * Create a SEQUENCE-END event.
+ *
+ * @param[out] event An empty event object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_sequence_end_event_initialize(yaml_event_t *event);
+
+/**
+ * Create a MAPPING-START event.
+ *
+ * The @a style argument may be ignored by the emitter.
+ *
+ * Either the @a tag attribute or the @a implicit flag must be set.
+ *
+ * @param[out] event An empty event object.
+ * @param[in] anchor The mapping anchor or @c NULL.
+ * @param[in] tag The mapping tag or @c NULL.
+ * @param[in] implicit If the tag may be omitted.
+ * @param[in] style The mapping style.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_mapping_start_event_initialize(yaml_event_t *event,
const yaml_char_t *anchor, const yaml_char_t *tag, int implicit,
- yaml_mapping_style_t style);
-
-/**
- * Create a MAPPING-END event.
- *
- * @param[out] event An empty event object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_mapping_end_event_initialize(yaml_event_t *event);
-
-/**
- * Free any memory allocated for an event object.
- *
- * @param[in,out] event An event object.
- */
-
-YAML_DECLARE(void)
-yaml_event_delete(yaml_event_t *event);
-
-/** @} */
-
-/**
- * @defgroup nodes Nodes
- * @{
- */
-
-/** The tag @c !!null with the only possible value: @c null. */
-#define YAML_NULL_TAG "tag:yaml.org,2002:null"
+ yaml_mapping_style_t style);
+
+/**
+ * Create a MAPPING-END event.
+ *
+ * @param[out] event An empty event object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_mapping_end_event_initialize(yaml_event_t *event);
+
+/**
+ * Free any memory allocated for an event object.
+ *
+ * @param[in,out] event An event object.
+ */
+
+YAML_DECLARE(void)
+yaml_event_delete(yaml_event_t *event);
+
+/** @} */
+
+/**
+ * @defgroup nodes Nodes
+ * @{
+ */
+
+/** The tag @c !!null with the only possible value: @c null. */
+#define YAML_NULL_TAG "tag:yaml.org,2002:null"
/** The tag @c !!bool with the values: @c true and @c false. */
-#define YAML_BOOL_TAG "tag:yaml.org,2002:bool"
-/** The tag @c !!str for string values. */
-#define YAML_STR_TAG "tag:yaml.org,2002:str"
-/** The tag @c !!int for integer values. */
-#define YAML_INT_TAG "tag:yaml.org,2002:int"
-/** The tag @c !!float for float values. */
-#define YAML_FLOAT_TAG "tag:yaml.org,2002:float"
-/** The tag @c !!timestamp for date and time values. */
-#define YAML_TIMESTAMP_TAG "tag:yaml.org,2002:timestamp"
-
-/** The tag @c !!seq is used to denote sequences. */
-#define YAML_SEQ_TAG "tag:yaml.org,2002:seq"
-/** The tag @c !!map is used to denote mapping. */
-#define YAML_MAP_TAG "tag:yaml.org,2002:map"
-
-/** The default scalar tag is @c !!str. */
-#define YAML_DEFAULT_SCALAR_TAG YAML_STR_TAG
-/** The default sequence tag is @c !!seq. */
-#define YAML_DEFAULT_SEQUENCE_TAG YAML_SEQ_TAG
-/** The default mapping tag is @c !!map. */
-#define YAML_DEFAULT_MAPPING_TAG YAML_MAP_TAG
-
-/** Node types. */
-typedef enum yaml_node_type_e {
- /** An empty node. */
- YAML_NO_NODE,
-
- /** A scalar node. */
- YAML_SCALAR_NODE,
- /** A sequence node. */
- YAML_SEQUENCE_NODE,
- /** A mapping node. */
- YAML_MAPPING_NODE
-} yaml_node_type_t;
-
-/** The forward definition of a document node structure. */
-typedef struct yaml_node_s yaml_node_t;
-
-/** An element of a sequence node. */
-typedef int yaml_node_item_t;
-
-/** An element of a mapping node. */
-typedef struct yaml_node_pair_s {
- /** The key of the element. */
- int key;
- /** The value of the element. */
- int value;
-} yaml_node_pair_t;
-
-/** The node structure. */
-struct yaml_node_s {
-
- /** The node type. */
- yaml_node_type_t type;
-
- /** The node tag. */
- yaml_char_t *tag;
-
- /** The node data. */
- union {
+#define YAML_BOOL_TAG "tag:yaml.org,2002:bool"
+/** The tag @c !!str for string values. */
+#define YAML_STR_TAG "tag:yaml.org,2002:str"
+/** The tag @c !!int for integer values. */
+#define YAML_INT_TAG "tag:yaml.org,2002:int"
+/** The tag @c !!float for float values. */
+#define YAML_FLOAT_TAG "tag:yaml.org,2002:float"
+/** The tag @c !!timestamp for date and time values. */
+#define YAML_TIMESTAMP_TAG "tag:yaml.org,2002:timestamp"
+
+/** The tag @c !!seq is used to denote sequences. */
+#define YAML_SEQ_TAG "tag:yaml.org,2002:seq"
+/** The tag @c !!map is used to denote mapping. */
+#define YAML_MAP_TAG "tag:yaml.org,2002:map"
+
+/** The default scalar tag is @c !!str. */
+#define YAML_DEFAULT_SCALAR_TAG YAML_STR_TAG
+/** The default sequence tag is @c !!seq. */
+#define YAML_DEFAULT_SEQUENCE_TAG YAML_SEQ_TAG
+/** The default mapping tag is @c !!map. */
+#define YAML_DEFAULT_MAPPING_TAG YAML_MAP_TAG
+
+/** Node types. */
+typedef enum yaml_node_type_e {
+ /** An empty node. */
+ YAML_NO_NODE,
+
+ /** A scalar node. */
+ YAML_SCALAR_NODE,
+ /** A sequence node. */
+ YAML_SEQUENCE_NODE,
+ /** A mapping node. */
+ YAML_MAPPING_NODE
+} yaml_node_type_t;
+
+/** The forward definition of a document node structure. */
+typedef struct yaml_node_s yaml_node_t;
+
+/** An element of a sequence node. */
+typedef int yaml_node_item_t;
+
+/** An element of a mapping node. */
+typedef struct yaml_node_pair_s {
+ /** The key of the element. */
+ int key;
+ /** The value of the element. */
+ int value;
+} yaml_node_pair_t;
+
+/** The node structure. */
+struct yaml_node_s {
+
+ /** The node type. */
+ yaml_node_type_t type;
+
+ /** The node tag. */
+ yaml_char_t *tag;
+
+ /** The node data. */
+ union {
- /** The scalar parameters (for @c YAML_SCALAR_NODE). */
- struct {
- /** The scalar value. */
- yaml_char_t *value;
- /** The length of the scalar value. */
- size_t length;
- /** The scalar style. */
- yaml_scalar_style_t style;
- } scalar;
-
- /** The sequence parameters (for @c YAML_SEQUENCE_NODE). */
- struct {
- /** The stack of sequence items. */
- struct {
- /** The beginning of the stack. */
- yaml_node_item_t *start;
- /** The end of the stack. */
- yaml_node_item_t *end;
- /** The top of the stack. */
- yaml_node_item_t *top;
- } items;
- /** The sequence style. */
- yaml_sequence_style_t style;
- } sequence;
-
- /** The mapping parameters (for @c YAML_MAPPING_NODE). */
- struct {
- /** The stack of mapping pairs (key, value). */
- struct {
- /** The beginning of the stack. */
- yaml_node_pair_t *start;
- /** The end of the stack. */
- yaml_node_pair_t *end;
- /** The top of the stack. */
- yaml_node_pair_t *top;
- } pairs;
- /** The mapping style. */
- yaml_mapping_style_t style;
- } mapping;
-
- } data;
-
- /** The beginning of the node. */
- yaml_mark_t start_mark;
- /** The end of the node. */
- yaml_mark_t end_mark;
-
-};
-
-/** The document structure. */
-typedef struct yaml_document_s {
-
- /** The document nodes. */
- struct {
- /** The beginning of the stack. */
- yaml_node_t *start;
- /** The end of the stack. */
- yaml_node_t *end;
- /** The top of the stack. */
- yaml_node_t *top;
- } nodes;
-
- /** The version directive. */
- yaml_version_directive_t *version_directive;
-
- /** The list of tag directives. */
- struct {
- /** The beginning of the tag directives list. */
- yaml_tag_directive_t *start;
- /** The end of the tag directives list. */
- yaml_tag_directive_t *end;
- } tag_directives;
-
- /** Is the document start indicator implicit? */
- int start_implicit;
- /** Is the document end indicator implicit? */
- int end_implicit;
-
- /** The beginning of the document. */
- yaml_mark_t start_mark;
- /** The end of the document. */
- yaml_mark_t end_mark;
-
-} yaml_document_t;
-
-/**
- * Create a YAML document.
- *
- * @param[out] document An empty document object.
- * @param[in] version_directive The %YAML directive value or
- * @c NULL.
- * @param[in] tag_directives_start The beginning of the %TAG
- * directives list.
- * @param[in] tag_directives_end The end of the %TAG directives
- * list.
- * @param[in] start_implicit If the document start indicator is
- * implicit.
- * @param[in] end_implicit If the document end indicator is
- * implicit.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_document_initialize(yaml_document_t *document,
- yaml_version_directive_t *version_directive,
- yaml_tag_directive_t *tag_directives_start,
- yaml_tag_directive_t *tag_directives_end,
- int start_implicit, int end_implicit);
-
-/**
- * Delete a YAML document and all its nodes.
- *
- * @param[in,out] document A document object.
- */
-
-YAML_DECLARE(void)
-yaml_document_delete(yaml_document_t *document);
-
-/**
- * Get a node of a YAML document.
- *
- * The pointer returned by this function is valid until any of the functions
- * modifying the documents are called.
- *
- * @param[in] document A document object.
- * @param[in] index The node id.
- *
- * @returns the node objct or @c NULL if @c node_id is out of range.
- */
-
-YAML_DECLARE(yaml_node_t *)
-yaml_document_get_node(yaml_document_t *document, int index);
-
-/**
- * Get the root of a YAML document node.
- *
- * The root object is the first object added to the document.
- *
- * The pointer returned by this function is valid until any of the functions
- * modifying the documents are called.
- *
- * An empty document produced by the parser signifies the end of a YAML
- * stream.
- *
- * @param[in] document A document object.
- *
- * @returns the node object or @c NULL if the document is empty.
- */
-
-YAML_DECLARE(yaml_node_t *)
-yaml_document_get_root_node(yaml_document_t *document);
-
-/**
- * Create a SCALAR node and attach it to the document.
- *
- * The @a style argument may be ignored by the emitter.
- *
- * @param[in,out] document A document object.
- * @param[in] tag The scalar tag.
- * @param[in] value The scalar value.
- * @param[in] length The length of the scalar value.
- * @param[in] style The scalar style.
- *
- * @returns the node id or @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_document_add_scalar(yaml_document_t *document,
+ /** The scalar parameters (for @c YAML_SCALAR_NODE). */
+ struct {
+ /** The scalar value. */
+ yaml_char_t *value;
+ /** The length of the scalar value. */
+ size_t length;
+ /** The scalar style. */
+ yaml_scalar_style_t style;
+ } scalar;
+
+ /** The sequence parameters (for @c YAML_SEQUENCE_NODE). */
+ struct {
+ /** The stack of sequence items. */
+ struct {
+ /** The beginning of the stack. */
+ yaml_node_item_t *start;
+ /** The end of the stack. */
+ yaml_node_item_t *end;
+ /** The top of the stack. */
+ yaml_node_item_t *top;
+ } items;
+ /** The sequence style. */
+ yaml_sequence_style_t style;
+ } sequence;
+
+ /** The mapping parameters (for @c YAML_MAPPING_NODE). */
+ struct {
+ /** The stack of mapping pairs (key, value). */
+ struct {
+ /** The beginning of the stack. */
+ yaml_node_pair_t *start;
+ /** The end of the stack. */
+ yaml_node_pair_t *end;
+ /** The top of the stack. */
+ yaml_node_pair_t *top;
+ } pairs;
+ /** The mapping style. */
+ yaml_mapping_style_t style;
+ } mapping;
+
+ } data;
+
+ /** The beginning of the node. */
+ yaml_mark_t start_mark;
+ /** The end of the node. */
+ yaml_mark_t end_mark;
+
+};
+
+/** The document structure. */
+typedef struct yaml_document_s {
+
+ /** The document nodes. */
+ struct {
+ /** The beginning of the stack. */
+ yaml_node_t *start;
+ /** The end of the stack. */
+ yaml_node_t *end;
+ /** The top of the stack. */
+ yaml_node_t *top;
+ } nodes;
+
+ /** The version directive. */
+ yaml_version_directive_t *version_directive;
+
+ /** The list of tag directives. */
+ struct {
+ /** The beginning of the tag directives list. */
+ yaml_tag_directive_t *start;
+ /** The end of the tag directives list. */
+ yaml_tag_directive_t *end;
+ } tag_directives;
+
+ /** Is the document start indicator implicit? */
+ int start_implicit;
+ /** Is the document end indicator implicit? */
+ int end_implicit;
+
+ /** The beginning of the document. */
+ yaml_mark_t start_mark;
+ /** The end of the document. */
+ yaml_mark_t end_mark;
+
+} yaml_document_t;
+
+/**
+ * Create a YAML document.
+ *
+ * @param[out] document An empty document object.
+ * @param[in] version_directive The %YAML directive value or
+ * @c NULL.
+ * @param[in] tag_directives_start The beginning of the %TAG
+ * directives list.
+ * @param[in] tag_directives_end The end of the %TAG directives
+ * list.
+ * @param[in] start_implicit If the document start indicator is
+ * implicit.
+ * @param[in] end_implicit If the document end indicator is
+ * implicit.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_document_initialize(yaml_document_t *document,
+ yaml_version_directive_t *version_directive,
+ yaml_tag_directive_t *tag_directives_start,
+ yaml_tag_directive_t *tag_directives_end,
+ int start_implicit, int end_implicit);
+
+/**
+ * Delete a YAML document and all its nodes.
+ *
+ * @param[in,out] document A document object.
+ */
+
+YAML_DECLARE(void)
+yaml_document_delete(yaml_document_t *document);
+
+/**
+ * Get a node of a YAML document.
+ *
+ * The pointer returned by this function is valid until any of the functions
+ * modifying the documents are called.
+ *
+ * @param[in] document A document object.
+ * @param[in] index The node id.
+ *
+ * @returns the node objct or @c NULL if @c node_id is out of range.
+ */
+
+YAML_DECLARE(yaml_node_t *)
+yaml_document_get_node(yaml_document_t *document, int index);
+
+/**
+ * Get the root of a YAML document node.
+ *
+ * The root object is the first object added to the document.
+ *
+ * The pointer returned by this function is valid until any of the functions
+ * modifying the documents are called.
+ *
+ * An empty document produced by the parser signifies the end of a YAML
+ * stream.
+ *
+ * @param[in] document A document object.
+ *
+ * @returns the node object or @c NULL if the document is empty.
+ */
+
+YAML_DECLARE(yaml_node_t *)
+yaml_document_get_root_node(yaml_document_t *document);
+
+/**
+ * Create a SCALAR node and attach it to the document.
+ *
+ * The @a style argument may be ignored by the emitter.
+ *
+ * @param[in,out] document A document object.
+ * @param[in] tag The scalar tag.
+ * @param[in] value The scalar value.
+ * @param[in] length The length of the scalar value.
+ * @param[in] style The scalar style.
+ *
+ * @returns the node id or @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_document_add_scalar(yaml_document_t *document,
const yaml_char_t *tag, const yaml_char_t *value, int length,
- yaml_scalar_style_t style);
-
-/**
- * Create a SEQUENCE node and attach it to the document.
- *
- * The @a style argument may be ignored by the emitter.
- *
- * @param[in,out] document A document object.
- * @param[in] tag The sequence tag.
- * @param[in] style The sequence style.
- *
- * @returns the node id or @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_document_add_sequence(yaml_document_t *document,
+ yaml_scalar_style_t style);
+
+/**
+ * Create a SEQUENCE node and attach it to the document.
+ *
+ * The @a style argument may be ignored by the emitter.
+ *
+ * @param[in,out] document A document object.
+ * @param[in] tag The sequence tag.
+ * @param[in] style The sequence style.
+ *
+ * @returns the node id or @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_document_add_sequence(yaml_document_t *document,
const yaml_char_t *tag, yaml_sequence_style_t style);
-
-/**
- * Create a MAPPING node and attach it to the document.
- *
- * The @a style argument may be ignored by the emitter.
- *
- * @param[in,out] document A document object.
- * @param[in] tag The sequence tag.
- * @param[in] style The sequence style.
- *
- * @returns the node id or @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_document_add_mapping(yaml_document_t *document,
+
+/**
+ * Create a MAPPING node and attach it to the document.
+ *
+ * The @a style argument may be ignored by the emitter.
+ *
+ * @param[in,out] document A document object.
+ * @param[in] tag The sequence tag.
+ * @param[in] style The sequence style.
+ *
+ * @returns the node id or @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_document_add_mapping(yaml_document_t *document,
const yaml_char_t *tag, yaml_mapping_style_t style);
-
-/**
- * Add an item to a SEQUENCE node.
- *
- * @param[in,out] document A document object.
- * @param[in] sequence The sequence node id.
- * @param[in] item The item node id.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_document_append_sequence_item(yaml_document_t *document,
- int sequence, int item);
-
-/**
- * Add a pair of a key and a value to a MAPPING node.
- *
- * @param[in,out] document A document object.
- * @param[in] mapping The mapping node id.
- * @param[in] key The key node id.
- * @param[in] value The value node id.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_document_append_mapping_pair(yaml_document_t *document,
- int mapping, int key, int value);
-
-/** @} */
-
-/**
- * @defgroup parser Parser Definitions
- * @{
- */
-
-/**
- * The prototype of a read handler.
- *
- * The read handler is called when the parser needs to read more bytes from the
- * source. The handler should write not more than @a size bytes to the @a
- * buffer. The number of written bytes should be set to the @a length variable.
- *
- * @param[in,out] data A pointer to an application data specified by
- * yaml_parser_set_input().
- * @param[out] buffer The buffer to write the data from the source.
- * @param[in] size The size of the buffer.
- * @param[out] size_read The actual number of bytes read from the source.
- *
- * @returns On success, the handler should return @c 1. If the handler failed,
- * the returned value should be @c 0. On EOF, the handler should set the
- * @a size_read to @c 0 and return @c 1.
- */
-
-typedef int yaml_read_handler_t(void *data, unsigned char *buffer, size_t size,
- size_t *size_read);
-
-/**
- * This structure holds information about a potential simple key.
- */
-
-typedef struct yaml_simple_key_s {
- /** Is a simple key possible? */
- int possible;
-
- /** Is a simple key required? */
- int required;
-
- /** The number of the token. */
- size_t token_number;
-
- /** The position mark. */
- yaml_mark_t mark;
-} yaml_simple_key_t;
-
-/**
- * The states of the parser.
- */
-typedef enum yaml_parser_state_e {
- /** Expect STREAM-START. */
- YAML_PARSE_STREAM_START_STATE,
- /** Expect the beginning of an implicit document. */
- YAML_PARSE_IMPLICIT_DOCUMENT_START_STATE,
- /** Expect DOCUMENT-START. */
- YAML_PARSE_DOCUMENT_START_STATE,
- /** Expect the content of a document. */
- YAML_PARSE_DOCUMENT_CONTENT_STATE,
- /** Expect DOCUMENT-END. */
- YAML_PARSE_DOCUMENT_END_STATE,
-
- /** Expect a block node. */
- YAML_PARSE_BLOCK_NODE_STATE,
- /** Expect a block node or indentless sequence. */
- YAML_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE,
- /** Expect a flow node. */
- YAML_PARSE_FLOW_NODE_STATE,
- /** Expect the first entry of a block sequence. */
- YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE,
- /** Expect an entry of a block sequence. */
- YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE,
-
- /** Expect an entry of an indentless sequence. */
- YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE,
- /** Expect the first key of a block mapping. */
- YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE,
- /** Expect a block mapping key. */
- YAML_PARSE_BLOCK_MAPPING_KEY_STATE,
- /** Expect a block mapping value. */
- YAML_PARSE_BLOCK_MAPPING_VALUE_STATE,
- /** Expect the first entry of a flow sequence. */
- YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE,
-
- /** Expect an entry of a flow sequence. */
- YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE,
- /** Expect a key of an ordered mapping. */
- YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE,
- /** Expect a value of an ordered mapping. */
- YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE,
- /** Expect the and of an ordered mapping entry. */
- YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE,
- /** Expect the first key of a flow mapping. */
- YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE,
- /** Expect a key of a flow mapping. */
-
- YAML_PARSE_FLOW_MAPPING_KEY_STATE,
- /** Expect a value of a flow mapping. */
- YAML_PARSE_FLOW_MAPPING_VALUE_STATE,
- /** Expect an empty value of a flow mapping. */
- YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE,
- /** Expect nothing. */
- YAML_PARSE_END_STATE
-} yaml_parser_state_t;
-
-/**
- * This structure holds aliases data.
- */
-
-typedef struct yaml_alias_data_s {
- /** The anchor. */
- yaml_char_t *anchor;
- /** The node id. */
- int index;
- /** The anchor mark. */
- yaml_mark_t mark;
-} yaml_alias_data_t;
-
-/**
- * The parser structure.
- *
- * All members are internal. Manage the structure using the @c yaml_parser_
- * family of functions.
- */
-
-typedef struct yaml_parser_s {
-
- /**
- * @name Error handling
- * @{
- */
-
- /** Error type. */
- yaml_error_type_t error;
- /** Error description. */
- const char *problem;
- /** The byte about which the problem occured. */
- size_t problem_offset;
- /** The problematic value (@c -1 is none). */
- int problem_value;
- /** The problem position. */
- yaml_mark_t problem_mark;
- /** The error context. */
- const char *context;
- /** The context position. */
- yaml_mark_t context_mark;
-
- /**
- * @}
- */
-
- /**
- * @name Reader stuff
- * @{
- */
-
- /** Read handler. */
- yaml_read_handler_t *read_handler;
-
- /** A pointer for passing to the read handler. */
- void *read_handler_data;
-
- /** Standard (string or file) input data. */
- union {
- /** String input data. */
- struct {
- /** The string start pointer. */
- const unsigned char *start;
- /** The string end pointer. */
- const unsigned char *end;
- /** The string current position. */
- const unsigned char *current;
- } string;
-
- /** File input data. */
- FILE *file;
- } input;
-
- /** EOF flag */
- int eof;
-
- /** The working buffer. */
- struct {
- /** The beginning of the buffer. */
- yaml_char_t *start;
- /** The end of the buffer. */
- yaml_char_t *end;
- /** The current position of the buffer. */
- yaml_char_t *pointer;
- /** The last filled position of the buffer. */
- yaml_char_t *last;
- } buffer;
-
- /* The number of unread characters in the buffer. */
- size_t unread;
-
- /** The raw buffer. */
- struct {
- /** The beginning of the buffer. */
- unsigned char *start;
- /** The end of the buffer. */
- unsigned char *end;
- /** The current position of the buffer. */
- unsigned char *pointer;
- /** The last filled position of the buffer. */
- unsigned char *last;
- } raw_buffer;
-
- /** The input encoding. */
- yaml_encoding_t encoding;
-
- /** The offset of the current position (in bytes). */
- size_t offset;
-
- /** The mark of the current position. */
- yaml_mark_t mark;
-
- /**
- * @}
- */
-
- /**
- * @name Scanner stuff
- * @{
- */
-
- /** Have we started to scan the input stream? */
- int stream_start_produced;
-
- /** Have we reached the end of the input stream? */
- int stream_end_produced;
-
- /** The number of unclosed '[' and '{' indicators. */
- int flow_level;
-
- /** The tokens queue. */
- struct {
- /** The beginning of the tokens queue. */
- yaml_token_t *start;
- /** The end of the tokens queue. */
- yaml_token_t *end;
- /** The head of the tokens queue. */
- yaml_token_t *head;
- /** The tail of the tokens queue. */
- yaml_token_t *tail;
- } tokens;
-
- /** The number of tokens fetched from the queue. */
- size_t tokens_parsed;
-
+
+/**
+ * Add an item to a SEQUENCE node.
+ *
+ * @param[in,out] document A document object.
+ * @param[in] sequence The sequence node id.
+ * @param[in] item The item node id.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_document_append_sequence_item(yaml_document_t *document,
+ int sequence, int item);
+
+/**
+ * Add a pair of a key and a value to a MAPPING node.
+ *
+ * @param[in,out] document A document object.
+ * @param[in] mapping The mapping node id.
+ * @param[in] key The key node id.
+ * @param[in] value The value node id.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_document_append_mapping_pair(yaml_document_t *document,
+ int mapping, int key, int value);
+
+/** @} */
+
+/**
+ * @defgroup parser Parser Definitions
+ * @{
+ */
+
+/**
+ * The prototype of a read handler.
+ *
+ * The read handler is called when the parser needs to read more bytes from the
+ * source. The handler should write not more than @a size bytes to the @a
+ * buffer. The number of written bytes should be set to the @a length variable.
+ *
+ * @param[in,out] data A pointer to an application data specified by
+ * yaml_parser_set_input().
+ * @param[out] buffer The buffer to write the data from the source.
+ * @param[in] size The size of the buffer.
+ * @param[out] size_read The actual number of bytes read from the source.
+ *
+ * @returns On success, the handler should return @c 1. If the handler failed,
+ * the returned value should be @c 0. On EOF, the handler should set the
+ * @a size_read to @c 0 and return @c 1.
+ */
+
+typedef int yaml_read_handler_t(void *data, unsigned char *buffer, size_t size,
+ size_t *size_read);
+
+/**
+ * This structure holds information about a potential simple key.
+ */
+
+typedef struct yaml_simple_key_s {
+ /** Is a simple key possible? */
+ int possible;
+
+ /** Is a simple key required? */
+ int required;
+
+ /** The number of the token. */
+ size_t token_number;
+
+ /** The position mark. */
+ yaml_mark_t mark;
+} yaml_simple_key_t;
+
+/**
+ * The states of the parser.
+ */
+typedef enum yaml_parser_state_e {
+ /** Expect STREAM-START. */
+ YAML_PARSE_STREAM_START_STATE,
+ /** Expect the beginning of an implicit document. */
+ YAML_PARSE_IMPLICIT_DOCUMENT_START_STATE,
+ /** Expect DOCUMENT-START. */
+ YAML_PARSE_DOCUMENT_START_STATE,
+ /** Expect the content of a document. */
+ YAML_PARSE_DOCUMENT_CONTENT_STATE,
+ /** Expect DOCUMENT-END. */
+ YAML_PARSE_DOCUMENT_END_STATE,
+
+ /** Expect a block node. */
+ YAML_PARSE_BLOCK_NODE_STATE,
+ /** Expect a block node or indentless sequence. */
+ YAML_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE,
+ /** Expect a flow node. */
+ YAML_PARSE_FLOW_NODE_STATE,
+ /** Expect the first entry of a block sequence. */
+ YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE,
+ /** Expect an entry of a block sequence. */
+ YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE,
+
+ /** Expect an entry of an indentless sequence. */
+ YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE,
+ /** Expect the first key of a block mapping. */
+ YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE,
+ /** Expect a block mapping key. */
+ YAML_PARSE_BLOCK_MAPPING_KEY_STATE,
+ /** Expect a block mapping value. */
+ YAML_PARSE_BLOCK_MAPPING_VALUE_STATE,
+ /** Expect the first entry of a flow sequence. */
+ YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE,
+
+ /** Expect an entry of a flow sequence. */
+ YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE,
+ /** Expect a key of an ordered mapping. */
+ YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE,
+ /** Expect a value of an ordered mapping. */
+ YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE,
+ /** Expect the and of an ordered mapping entry. */
+ YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE,
+ /** Expect the first key of a flow mapping. */
+ YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE,
+ /** Expect a key of a flow mapping. */
+
+ YAML_PARSE_FLOW_MAPPING_KEY_STATE,
+ /** Expect a value of a flow mapping. */
+ YAML_PARSE_FLOW_MAPPING_VALUE_STATE,
+ /** Expect an empty value of a flow mapping. */
+ YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE,
+ /** Expect nothing. */
+ YAML_PARSE_END_STATE
+} yaml_parser_state_t;
+
+/**
+ * This structure holds aliases data.
+ */
+
+typedef struct yaml_alias_data_s {
+ /** The anchor. */
+ yaml_char_t *anchor;
+ /** The node id. */
+ int index;
+ /** The anchor mark. */
+ yaml_mark_t mark;
+} yaml_alias_data_t;
+
+/**
+ * The parser structure.
+ *
+ * All members are internal. Manage the structure using the @c yaml_parser_
+ * family of functions.
+ */
+
+typedef struct yaml_parser_s {
+
+ /**
+ * @name Error handling
+ * @{
+ */
+
+ /** Error type. */
+ yaml_error_type_t error;
+ /** Error description. */
+ const char *problem;
+ /** The byte about which the problem occured. */
+ size_t problem_offset;
+ /** The problematic value (@c -1 is none). */
+ int problem_value;
+ /** The problem position. */
+ yaml_mark_t problem_mark;
+ /** The error context. */
+ const char *context;
+ /** The context position. */
+ yaml_mark_t context_mark;
+
+ /**
+ * @}
+ */
+
+ /**
+ * @name Reader stuff
+ * @{
+ */
+
+ /** Read handler. */
+ yaml_read_handler_t *read_handler;
+
+ /** A pointer for passing to the read handler. */
+ void *read_handler_data;
+
+ /** Standard (string or file) input data. */
+ union {
+ /** String input data. */
+ struct {
+ /** The string start pointer. */
+ const unsigned char *start;
+ /** The string end pointer. */
+ const unsigned char *end;
+ /** The string current position. */
+ const unsigned char *current;
+ } string;
+
+ /** File input data. */
+ FILE *file;
+ } input;
+
+ /** EOF flag */
+ int eof;
+
+ /** The working buffer. */
+ struct {
+ /** The beginning of the buffer. */
+ yaml_char_t *start;
+ /** The end of the buffer. */
+ yaml_char_t *end;
+ /** The current position of the buffer. */
+ yaml_char_t *pointer;
+ /** The last filled position of the buffer. */
+ yaml_char_t *last;
+ } buffer;
+
+ /* The number of unread characters in the buffer. */
+ size_t unread;
+
+ /** The raw buffer. */
+ struct {
+ /** The beginning of the buffer. */
+ unsigned char *start;
+ /** The end of the buffer. */
+ unsigned char *end;
+ /** The current position of the buffer. */
+ unsigned char *pointer;
+ /** The last filled position of the buffer. */
+ unsigned char *last;
+ } raw_buffer;
+
+ /** The input encoding. */
+ yaml_encoding_t encoding;
+
+ /** The offset of the current position (in bytes). */
+ size_t offset;
+
+ /** The mark of the current position. */
+ yaml_mark_t mark;
+
+ /**
+ * @}
+ */
+
+ /**
+ * @name Scanner stuff
+ * @{
+ */
+
+ /** Have we started to scan the input stream? */
+ int stream_start_produced;
+
+ /** Have we reached the end of the input stream? */
+ int stream_end_produced;
+
+ /** The number of unclosed '[' and '{' indicators. */
+ int flow_level;
+
+ /** The tokens queue. */
+ struct {
+ /** The beginning of the tokens queue. */
+ yaml_token_t *start;
+ /** The end of the tokens queue. */
+ yaml_token_t *end;
+ /** The head of the tokens queue. */
+ yaml_token_t *head;
+ /** The tail of the tokens queue. */
+ yaml_token_t *tail;
+ } tokens;
+
+ /** The number of tokens fetched from the queue. */
+ size_t tokens_parsed;
+
/** Does the tokens queue contain a token ready for dequeueing. */
- int token_available;
-
- /** The indentation levels stack. */
- struct {
- /** The beginning of the stack. */
- int *start;
- /** The end of the stack. */
- int *end;
- /** The top of the stack. */
- int *top;
- } indents;
-
- /** The current indentation level. */
- int indent;
-
- /** May a simple key occur at the current position? */
- int simple_key_allowed;
-
- /** The stack of simple keys. */
- struct {
- /** The beginning of the stack. */
- yaml_simple_key_t *start;
- /** The end of the stack. */
- yaml_simple_key_t *end;
- /** The top of the stack. */
- yaml_simple_key_t *top;
- } simple_keys;
-
- /**
- * @}
- */
-
- /**
- * @name Parser stuff
- * @{
- */
-
- /** The parser states stack. */
- struct {
- /** The beginning of the stack. */
- yaml_parser_state_t *start;
- /** The end of the stack. */
- yaml_parser_state_t *end;
- /** The top of the stack. */
- yaml_parser_state_t *top;
- } states;
-
- /** The current parser state. */
- yaml_parser_state_t state;
-
- /** The stack of marks. */
- struct {
- /** The beginning of the stack. */
- yaml_mark_t *start;
- /** The end of the stack. */
- yaml_mark_t *end;
- /** The top of the stack. */
- yaml_mark_t *top;
- } marks;
-
- /** The list of TAG directives. */
- struct {
- /** The beginning of the list. */
- yaml_tag_directive_t *start;
- /** The end of the list. */
- yaml_tag_directive_t *end;
- /** The top of the list. */
- yaml_tag_directive_t *top;
- } tag_directives;
-
- /**
- * @}
- */
-
- /**
- * @name Dumper stuff
- * @{
- */
-
- /** The alias data. */
- struct {
- /** The beginning of the list. */
- yaml_alias_data_t *start;
- /** The end of the list. */
- yaml_alias_data_t *end;
- /** The top of the list. */
- yaml_alias_data_t *top;
- } aliases;
-
- /** The currently parsed document. */
- yaml_document_t *document;
-
- /**
- * @}
- */
-
-} yaml_parser_t;
-
-/**
- * Initialize a parser.
- *
- * This function creates a new parser object. An application is responsible
- * for destroying the object using the yaml_parser_delete() function.
- *
- * @param[out] parser An empty parser object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_parser_initialize(yaml_parser_t *parser);
-
-/**
- * Destroy a parser.
- *
- * @param[in,out] parser A parser object.
- */
-
-YAML_DECLARE(void)
-yaml_parser_delete(yaml_parser_t *parser);
-
-/**
- * Set a string input.
- *
- * Note that the @a input pointer must be valid while the @a parser object
- * exists. The application is responsible for destroing @a input after
- * destroying the @a parser.
- *
- * @param[in,out] parser A parser object.
- * @param[in] input A source data.
- * @param[in] size The length of the source data in bytes.
- */
-
-YAML_DECLARE(void)
-yaml_parser_set_input_string(yaml_parser_t *parser,
- const unsigned char *input, size_t size);
-
-/**
- * Set a file input.
- *
- * @a file should be a file object open for reading. The application is
- * responsible for closing the @a file.
- *
- * @param[in,out] parser A parser object.
- * @param[in] file An open file.
- */
-
-YAML_DECLARE(void)
-yaml_parser_set_input_file(yaml_parser_t *parser, FILE *file);
-
-/**
- * Set a generic input handler.
- *
- * @param[in,out] parser A parser object.
- * @param[in] handler A read handler.
- * @param[in] data Any application data for passing to the read
- * handler.
- */
-
-YAML_DECLARE(void)
-yaml_parser_set_input(yaml_parser_t *parser,
- yaml_read_handler_t *handler, void *data);
-
-/**
- * Set the source encoding.
- *
- * @param[in,out] parser A parser object.
- * @param[in] encoding The source encoding.
- */
-
-YAML_DECLARE(void)
-yaml_parser_set_encoding(yaml_parser_t *parser, yaml_encoding_t encoding);
-
-/**
- * Scan the input stream and produce the next token.
- *
- * Call the function subsequently to produce a sequence of tokens corresponding
- * to the input stream. The initial token has the type
- * @c YAML_STREAM_START_TOKEN while the ending token has the type
- * @c YAML_STREAM_END_TOKEN.
- *
- * An application is responsible for freeing any buffers associated with the
- * produced token object using the @c yaml_token_delete function.
- *
- * An application must not alternate the calls of yaml_parser_scan() with the
- * calls of yaml_parser_parse() or yaml_parser_load(). Doing this will break
- * the parser.
- *
- * @param[in,out] parser A parser object.
- * @param[out] token An empty token object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token);
-
-/**
- * Parse the input stream and produce the next parsing event.
- *
- * Call the function subsequently to produce a sequence of events corresponding
- * to the input stream. The initial event has the type
- * @c YAML_STREAM_START_EVENT while the ending event has the type
- * @c YAML_STREAM_END_EVENT.
- *
- * An application is responsible for freeing any buffers associated with the
- * produced event object using the yaml_event_delete() function.
- *
- * An application must not alternate the calls of yaml_parser_parse() with the
- * calls of yaml_parser_scan() or yaml_parser_load(). Doing this will break the
- * parser.
- *
- * @param[in,out] parser A parser object.
- * @param[out] event An empty event object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event);
-
-/**
- * Parse the input stream and produce the next YAML document.
- *
- * Call this function subsequently to produce a sequence of documents
- * constituting the input stream.
- *
- * If the produced document has no root node, it means that the document
- * end has been reached.
- *
- * An application is responsible for freeing any data associated with the
- * produced document object using the yaml_document_delete() function.
- *
- * An application must not alternate the calls of yaml_parser_load() with the
- * calls of yaml_parser_scan() or yaml_parser_parse(). Doing this will break
- * the parser.
- *
- * @param[in,out] parser A parser object.
- * @param[out] document An empty document object.
- *
+ int token_available;
+
+ /** The indentation levels stack. */
+ struct {
+ /** The beginning of the stack. */
+ int *start;
+ /** The end of the stack. */
+ int *end;
+ /** The top of the stack. */
+ int *top;
+ } indents;
+
+ /** The current indentation level. */
+ int indent;
+
+ /** May a simple key occur at the current position? */
+ int simple_key_allowed;
+
+ /** The stack of simple keys. */
+ struct {
+ /** The beginning of the stack. */
+ yaml_simple_key_t *start;
+ /** The end of the stack. */
+ yaml_simple_key_t *end;
+ /** The top of the stack. */
+ yaml_simple_key_t *top;
+ } simple_keys;
+
+ /**
+ * @}
+ */
+
+ /**
+ * @name Parser stuff
+ * @{
+ */
+
+ /** The parser states stack. */
+ struct {
+ /** The beginning of the stack. */
+ yaml_parser_state_t *start;
+ /** The end of the stack. */
+ yaml_parser_state_t *end;
+ /** The top of the stack. */
+ yaml_parser_state_t *top;
+ } states;
+
+ /** The current parser state. */
+ yaml_parser_state_t state;
+
+ /** The stack of marks. */
+ struct {
+ /** The beginning of the stack. */
+ yaml_mark_t *start;
+ /** The end of the stack. */
+ yaml_mark_t *end;
+ /** The top of the stack. */
+ yaml_mark_t *top;
+ } marks;
+
+ /** The list of TAG directives. */
+ struct {
+ /** The beginning of the list. */
+ yaml_tag_directive_t *start;
+ /** The end of the list. */
+ yaml_tag_directive_t *end;
+ /** The top of the list. */
+ yaml_tag_directive_t *top;
+ } tag_directives;
+
+ /**
+ * @}
+ */
+
+ /**
+ * @name Dumper stuff
+ * @{
+ */
+
+ /** The alias data. */
+ struct {
+ /** The beginning of the list. */
+ yaml_alias_data_t *start;
+ /** The end of the list. */
+ yaml_alias_data_t *end;
+ /** The top of the list. */
+ yaml_alias_data_t *top;
+ } aliases;
+
+ /** The currently parsed document. */
+ yaml_document_t *document;
+
+ /**
+ * @}
+ */
+
+} yaml_parser_t;
+
+/**
+ * Initialize a parser.
+ *
+ * This function creates a new parser object. An application is responsible
+ * for destroying the object using the yaml_parser_delete() function.
+ *
+ * @param[out] parser An empty parser object.
+ *
* @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_parser_load(yaml_parser_t *parser, yaml_document_t *document);
-
-/** @} */
-
-/**
- * @defgroup emitter Emitter Definitions
- * @{
- */
-
-/**
- * The prototype of a write handler.
- *
- * The write handler is called when the emitter needs to flush the accumulated
- * characters to the output. The handler should write @a size bytes of the
- * @a buffer to the output.
- *
- * @param[in,out] data A pointer to an application data specified by
- * yaml_emitter_set_output().
- * @param[in] buffer The buffer with bytes to be written.
- * @param[in] size The size of the buffer.
- *
- * @returns On success, the handler should return @c 1. If the handler failed,
- * the returned value should be @c 0.
- */
-
-typedef int yaml_write_handler_t(void *data, unsigned char *buffer, size_t size);
-
-/** The emitter states. */
-typedef enum yaml_emitter_state_e {
- /** Expect STREAM-START. */
- YAML_EMIT_STREAM_START_STATE,
- /** Expect the first DOCUMENT-START or STREAM-END. */
- YAML_EMIT_FIRST_DOCUMENT_START_STATE,
- /** Expect DOCUMENT-START or STREAM-END. */
- YAML_EMIT_DOCUMENT_START_STATE,
- /** Expect the content of a document. */
- YAML_EMIT_DOCUMENT_CONTENT_STATE,
- /** Expect DOCUMENT-END. */
- YAML_EMIT_DOCUMENT_END_STATE,
-
- /** Expect the first item of a flow sequence. */
- YAML_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE,
- /** Expect an item of a flow sequence. */
- YAML_EMIT_FLOW_SEQUENCE_ITEM_STATE,
- /** Expect the first key of a flow mapping. */
- YAML_EMIT_FLOW_MAPPING_FIRST_KEY_STATE,
- /** Expect a key of a flow mapping. */
- YAML_EMIT_FLOW_MAPPING_KEY_STATE,
- /** Expect a value for a simple key of a flow mapping. */
- YAML_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE,
-
- /** Expect a value of a flow mapping. */
- YAML_EMIT_FLOW_MAPPING_VALUE_STATE,
- /** Expect the first item of a block sequence. */
- YAML_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE,
- /** Expect an item of a block sequence. */
- YAML_EMIT_BLOCK_SEQUENCE_ITEM_STATE,
- /** Expect the first key of a block mapping. */
- YAML_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE,
- /** Expect the key of a block mapping. */
- YAML_EMIT_BLOCK_MAPPING_KEY_STATE,
-
- /** Expect a value for a simple key of a block mapping. */
- YAML_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE,
- /** Expect a value of a block mapping. */
- YAML_EMIT_BLOCK_MAPPING_VALUE_STATE,
- /** Expect nothing. */
- YAML_EMIT_END_STATE
-} yaml_emitter_state_t;
-
+ */
+
+YAML_DECLARE(int)
+yaml_parser_initialize(yaml_parser_t *parser);
+
+/**
+ * Destroy a parser.
+ *
+ * @param[in,out] parser A parser object.
+ */
+
+YAML_DECLARE(void)
+yaml_parser_delete(yaml_parser_t *parser);
+
+/**
+ * Set a string input.
+ *
+ * Note that the @a input pointer must be valid while the @a parser object
+ * exists. The application is responsible for destroing @a input after
+ * destroying the @a parser.
+ *
+ * @param[in,out] parser A parser object.
+ * @param[in] input A source data.
+ * @param[in] size The length of the source data in bytes.
+ */
+
+YAML_DECLARE(void)
+yaml_parser_set_input_string(yaml_parser_t *parser,
+ const unsigned char *input, size_t size);
+
+/**
+ * Set a file input.
+ *
+ * @a file should be a file object open for reading. The application is
+ * responsible for closing the @a file.
+ *
+ * @param[in,out] parser A parser object.
+ * @param[in] file An open file.
+ */
+
+YAML_DECLARE(void)
+yaml_parser_set_input_file(yaml_parser_t *parser, FILE *file);
+
+/**
+ * Set a generic input handler.
+ *
+ * @param[in,out] parser A parser object.
+ * @param[in] handler A read handler.
+ * @param[in] data Any application data for passing to the read
+ * handler.
+ */
+
+YAML_DECLARE(void)
+yaml_parser_set_input(yaml_parser_t *parser,
+ yaml_read_handler_t *handler, void *data);
+
+/**
+ * Set the source encoding.
+ *
+ * @param[in,out] parser A parser object.
+ * @param[in] encoding The source encoding.
+ */
+
+YAML_DECLARE(void)
+yaml_parser_set_encoding(yaml_parser_t *parser, yaml_encoding_t encoding);
+
+/**
+ * Scan the input stream and produce the next token.
+ *
+ * Call the function subsequently to produce a sequence of tokens corresponding
+ * to the input stream. The initial token has the type
+ * @c YAML_STREAM_START_TOKEN while the ending token has the type
+ * @c YAML_STREAM_END_TOKEN.
+ *
+ * An application is responsible for freeing any buffers associated with the
+ * produced token object using the @c yaml_token_delete function.
+ *
+ * An application must not alternate the calls of yaml_parser_scan() with the
+ * calls of yaml_parser_parse() or yaml_parser_load(). Doing this will break
+ * the parser.
+ *
+ * @param[in,out] parser A parser object.
+ * @param[out] token An empty token object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token);
+
+/**
+ * Parse the input stream and produce the next parsing event.
+ *
+ * Call the function subsequently to produce a sequence of events corresponding
+ * to the input stream. The initial event has the type
+ * @c YAML_STREAM_START_EVENT while the ending event has the type
+ * @c YAML_STREAM_END_EVENT.
+ *
+ * An application is responsible for freeing any buffers associated with the
+ * produced event object using the yaml_event_delete() function.
+ *
+ * An application must not alternate the calls of yaml_parser_parse() with the
+ * calls of yaml_parser_scan() or yaml_parser_load(). Doing this will break the
+ * parser.
+ *
+ * @param[in,out] parser A parser object.
+ * @param[out] event An empty event object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event);
+
+/**
+ * Parse the input stream and produce the next YAML document.
+ *
+ * Call this function subsequently to produce a sequence of documents
+ * constituting the input stream.
+ *
+ * If the produced document has no root node, it means that the document
+ * end has been reached.
+ *
+ * An application is responsible for freeing any data associated with the
+ * produced document object using the yaml_document_delete() function.
+ *
+ * An application must not alternate the calls of yaml_parser_load() with the
+ * calls of yaml_parser_scan() or yaml_parser_parse(). Doing this will break
+ * the parser.
+ *
+ * @param[in,out] parser A parser object.
+ * @param[out] document An empty document object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_load(yaml_parser_t *parser, yaml_document_t *document);
+
+/** @} */
+
+/**
+ * @defgroup emitter Emitter Definitions
+ * @{
+ */
+
+/**
+ * The prototype of a write handler.
+ *
+ * The write handler is called when the emitter needs to flush the accumulated
+ * characters to the output. The handler should write @a size bytes of the
+ * @a buffer to the output.
+ *
+ * @param[in,out] data A pointer to an application data specified by
+ * yaml_emitter_set_output().
+ * @param[in] buffer The buffer with bytes to be written.
+ * @param[in] size The size of the buffer.
+ *
+ * @returns On success, the handler should return @c 1. If the handler failed,
+ * the returned value should be @c 0.
+ */
+
+typedef int yaml_write_handler_t(void *data, unsigned char *buffer, size_t size);
+
+/** The emitter states. */
+typedef enum yaml_emitter_state_e {
+ /** Expect STREAM-START. */
+ YAML_EMIT_STREAM_START_STATE,
+ /** Expect the first DOCUMENT-START or STREAM-END. */
+ YAML_EMIT_FIRST_DOCUMENT_START_STATE,
+ /** Expect DOCUMENT-START or STREAM-END. */
+ YAML_EMIT_DOCUMENT_START_STATE,
+ /** Expect the content of a document. */
+ YAML_EMIT_DOCUMENT_CONTENT_STATE,
+ /** Expect DOCUMENT-END. */
+ YAML_EMIT_DOCUMENT_END_STATE,
+
+ /** Expect the first item of a flow sequence. */
+ YAML_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE,
+ /** Expect an item of a flow sequence. */
+ YAML_EMIT_FLOW_SEQUENCE_ITEM_STATE,
+ /** Expect the first key of a flow mapping. */
+ YAML_EMIT_FLOW_MAPPING_FIRST_KEY_STATE,
+ /** Expect a key of a flow mapping. */
+ YAML_EMIT_FLOW_MAPPING_KEY_STATE,
+ /** Expect a value for a simple key of a flow mapping. */
+ YAML_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE,
+
+ /** Expect a value of a flow mapping. */
+ YAML_EMIT_FLOW_MAPPING_VALUE_STATE,
+ /** Expect the first item of a block sequence. */
+ YAML_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE,
+ /** Expect an item of a block sequence. */
+ YAML_EMIT_BLOCK_SEQUENCE_ITEM_STATE,
+ /** Expect the first key of a block mapping. */
+ YAML_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE,
+ /** Expect the key of a block mapping. */
+ YAML_EMIT_BLOCK_MAPPING_KEY_STATE,
+
+ /** Expect a value for a simple key of a block mapping. */
+ YAML_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE,
+ /** Expect a value of a block mapping. */
+ YAML_EMIT_BLOCK_MAPPING_VALUE_STATE,
+ /** Expect nothing. */
+ YAML_EMIT_END_STATE
+} yaml_emitter_state_t;
+
/* This is needed for C++ */
@@ -1538,450 +1538,450 @@ typedef struct yaml_anchors_s {
int serialized;
} yaml_anchors_t;
-/**
- * The emitter structure.
- *
- * All members are internal. Manage the structure using the @c yaml_emitter_
- * family of functions.
- */
-
-typedef struct yaml_emitter_s {
-
- /**
- * @name Error handling
- * @{
- */
-
- /** Error type. */
- yaml_error_type_t error;
- /** Error description. */
- const char *problem;
-
- /**
- * @}
- */
-
- /**
- * @name Writer stuff
- * @{
- */
-
- /** Write handler. */
- yaml_write_handler_t *write_handler;
-
+/**
+ * The emitter structure.
+ *
+ * All members are internal. Manage the structure using the @c yaml_emitter_
+ * family of functions.
+ */
+
+typedef struct yaml_emitter_s {
+
+ /**
+ * @name Error handling
+ * @{
+ */
+
+ /** Error type. */
+ yaml_error_type_t error;
+ /** Error description. */
+ const char *problem;
+
+ /**
+ * @}
+ */
+
+ /**
+ * @name Writer stuff
+ * @{
+ */
+
+ /** Write handler. */
+ yaml_write_handler_t *write_handler;
+
/** A pointer for passing to the write handler. */
- void *write_handler_data;
-
- /** Standard (string or file) output data. */
- union {
- /** String output data. */
- struct {
- /** The buffer pointer. */
- unsigned char *buffer;
- /** The buffer size. */
- size_t size;
- /** The number of written bytes. */
- size_t *size_written;
- } string;
-
- /** File output data. */
- FILE *file;
- } output;
-
- /** The working buffer. */
- struct {
- /** The beginning of the buffer. */
- yaml_char_t *start;
- /** The end of the buffer. */
- yaml_char_t *end;
- /** The current position of the buffer. */
- yaml_char_t *pointer;
- /** The last filled position of the buffer. */
- yaml_char_t *last;
- } buffer;
-
- /** The raw buffer. */
- struct {
- /** The beginning of the buffer. */
- unsigned char *start;
- /** The end of the buffer. */
- unsigned char *end;
- /** The current position of the buffer. */
- unsigned char *pointer;
- /** The last filled position of the buffer. */
- unsigned char *last;
- } raw_buffer;
-
- /** The stream encoding. */
- yaml_encoding_t encoding;
-
- /**
- * @}
- */
-
- /**
- * @name Emitter stuff
- * @{
- */
-
- /** If the output is in the canonical style? */
- int canonical;
- /** The number of indentation spaces. */
- int best_indent;
- /** The preferred width of the output lines. */
- int best_width;
- /** Allow unescaped non-ASCII characters? */
- int unicode;
- /** The preferred line break. */
- yaml_break_t line_break;
-
- /** The stack of states. */
- struct {
- /** The beginning of the stack. */
- yaml_emitter_state_t *start;
- /** The end of the stack. */
- yaml_emitter_state_t *end;
- /** The top of the stack. */
- yaml_emitter_state_t *top;
- } states;
-
- /** The current emitter state. */
- yaml_emitter_state_t state;
-
- /** The event queue. */
- struct {
- /** The beginning of the event queue. */
- yaml_event_t *start;
- /** The end of the event queue. */
- yaml_event_t *end;
- /** The head of the event queue. */
- yaml_event_t *head;
- /** The tail of the event queue. */
- yaml_event_t *tail;
- } events;
-
- /** The stack of indentation levels. */
- struct {
- /** The beginning of the stack. */
- int *start;
- /** The end of the stack. */
- int *end;
- /** The top of the stack. */
- int *top;
- } indents;
-
- /** The list of tag directives. */
- struct {
- /** The beginning of the list. */
- yaml_tag_directive_t *start;
- /** The end of the list. */
- yaml_tag_directive_t *end;
- /** The top of the list. */
- yaml_tag_directive_t *top;
- } tag_directives;
-
- /** The current indentation level. */
- int indent;
-
- /** The current flow level. */
- int flow_level;
-
- /** Is it the document root context? */
- int root_context;
- /** Is it a sequence context? */
- int sequence_context;
- /** Is it a mapping context? */
- int mapping_context;
- /** Is it a simple mapping key context? */
- int simple_key_context;
-
- /** The current line. */
- int line;
- /** The current column. */
- int column;
- /** If the last character was a whitespace? */
- int whitespace;
- /** If the last character was an indentation character (' ', '-', '?', ':')? */
- int indention;
- /** If an explicit document end is required? */
- int open_ended;
-
- /** Anchor analysis. */
- struct {
- /** The anchor value. */
- yaml_char_t *anchor;
- /** The anchor length. */
- size_t anchor_length;
- /** Is it an alias? */
- int alias;
- } anchor_data;
-
- /** Tag analysis. */
- struct {
- /** The tag handle. */
- yaml_char_t *handle;
- /** The tag handle length. */
- size_t handle_length;
- /** The tag suffix. */
- yaml_char_t *suffix;
- /** The tag suffix length. */
- size_t suffix_length;
- } tag_data;
-
- /** Scalar analysis. */
- struct {
- /** The scalar value. */
- yaml_char_t *value;
- /** The scalar length. */
- size_t length;
- /** Does the scalar contain line breaks? */
- int multiline;
- /** Can the scalar be expessed in the flow plain style? */
- int flow_plain_allowed;
- /** Can the scalar be expressed in the block plain style? */
- int block_plain_allowed;
- /** Can the scalar be expressed in the single quoted style? */
- int single_quoted_allowed;
- /** Can the scalar be expressed in the literal or folded styles? */
- int block_allowed;
- /** The output style. */
- yaml_scalar_style_t style;
- } scalar_data;
-
- /**
- * @}
- */
-
- /**
- * @name Dumper stuff
- * @{
- */
-
- /** If the stream was already opened? */
- int opened;
- /** If the stream was already closed? */
- int closed;
-
- /** The information associated with the document nodes. */
+ void *write_handler_data;
+
+ /** Standard (string or file) output data. */
+ union {
+ /** String output data. */
+ struct {
+ /** The buffer pointer. */
+ unsigned char *buffer;
+ /** The buffer size. */
+ size_t size;
+ /** The number of written bytes. */
+ size_t *size_written;
+ } string;
+
+ /** File output data. */
+ FILE *file;
+ } output;
+
+ /** The working buffer. */
+ struct {
+ /** The beginning of the buffer. */
+ yaml_char_t *start;
+ /** The end of the buffer. */
+ yaml_char_t *end;
+ /** The current position of the buffer. */
+ yaml_char_t *pointer;
+ /** The last filled position of the buffer. */
+ yaml_char_t *last;
+ } buffer;
+
+ /** The raw buffer. */
+ struct {
+ /** The beginning of the buffer. */
+ unsigned char *start;
+ /** The end of the buffer. */
+ unsigned char *end;
+ /** The current position of the buffer. */
+ unsigned char *pointer;
+ /** The last filled position of the buffer. */
+ unsigned char *last;
+ } raw_buffer;
+
+ /** The stream encoding. */
+ yaml_encoding_t encoding;
+
+ /**
+ * @}
+ */
+
+ /**
+ * @name Emitter stuff
+ * @{
+ */
+
+ /** If the output is in the canonical style? */
+ int canonical;
+ /** The number of indentation spaces. */
+ int best_indent;
+ /** The preferred width of the output lines. */
+ int best_width;
+ /** Allow unescaped non-ASCII characters? */
+ int unicode;
+ /** The preferred line break. */
+ yaml_break_t line_break;
+
+ /** The stack of states. */
+ struct {
+ /** The beginning of the stack. */
+ yaml_emitter_state_t *start;
+ /** The end of the stack. */
+ yaml_emitter_state_t *end;
+ /** The top of the stack. */
+ yaml_emitter_state_t *top;
+ } states;
+
+ /** The current emitter state. */
+ yaml_emitter_state_t state;
+
+ /** The event queue. */
+ struct {
+ /** The beginning of the event queue. */
+ yaml_event_t *start;
+ /** The end of the event queue. */
+ yaml_event_t *end;
+ /** The head of the event queue. */
+ yaml_event_t *head;
+ /** The tail of the event queue. */
+ yaml_event_t *tail;
+ } events;
+
+ /** The stack of indentation levels. */
+ struct {
+ /** The beginning of the stack. */
+ int *start;
+ /** The end of the stack. */
+ int *end;
+ /** The top of the stack. */
+ int *top;
+ } indents;
+
+ /** The list of tag directives. */
+ struct {
+ /** The beginning of the list. */
+ yaml_tag_directive_t *start;
+ /** The end of the list. */
+ yaml_tag_directive_t *end;
+ /** The top of the list. */
+ yaml_tag_directive_t *top;
+ } tag_directives;
+
+ /** The current indentation level. */
+ int indent;
+
+ /** The current flow level. */
+ int flow_level;
+
+ /** Is it the document root context? */
+ int root_context;
+ /** Is it a sequence context? */
+ int sequence_context;
+ /** Is it a mapping context? */
+ int mapping_context;
+ /** Is it a simple mapping key context? */
+ int simple_key_context;
+
+ /** The current line. */
+ int line;
+ /** The current column. */
+ int column;
+ /** If the last character was a whitespace? */
+ int whitespace;
+ /** If the last character was an indentation character (' ', '-', '?', ':')? */
+ int indention;
+ /** If an explicit document end is required? */
+ int open_ended;
+
+ /** Anchor analysis. */
+ struct {
+ /** The anchor value. */
+ yaml_char_t *anchor;
+ /** The anchor length. */
+ size_t anchor_length;
+ /** Is it an alias? */
+ int alias;
+ } anchor_data;
+
+ /** Tag analysis. */
+ struct {
+ /** The tag handle. */
+ yaml_char_t *handle;
+ /** The tag handle length. */
+ size_t handle_length;
+ /** The tag suffix. */
+ yaml_char_t *suffix;
+ /** The tag suffix length. */
+ size_t suffix_length;
+ } tag_data;
+
+ /** Scalar analysis. */
+ struct {
+ /** The scalar value. */
+ yaml_char_t *value;
+ /** The scalar length. */
+ size_t length;
+ /** Does the scalar contain line breaks? */
+ int multiline;
+ /** Can the scalar be expessed in the flow plain style? */
+ int flow_plain_allowed;
+ /** Can the scalar be expressed in the block plain style? */
+ int block_plain_allowed;
+ /** Can the scalar be expressed in the single quoted style? */
+ int single_quoted_allowed;
+ /** Can the scalar be expressed in the literal or folded styles? */
+ int block_allowed;
+ /** The output style. */
+ yaml_scalar_style_t style;
+ } scalar_data;
+
+ /**
+ * @}
+ */
+
+ /**
+ * @name Dumper stuff
+ * @{
+ */
+
+ /** If the stream was already opened? */
+ int opened;
+ /** If the stream was already closed? */
+ int closed;
+
+ /** The information associated with the document nodes. */
yaml_anchors_t *anchors;
-
- /** The last assigned anchor id. */
- int last_anchor_id;
-
- /** The currently emitted document. */
- yaml_document_t *document;
-
- /**
- * @}
- */
-
-} yaml_emitter_t;
-
-/**
- * Initialize an emitter.
- *
- * This function creates a new emitter object. An application is responsible
- * for destroying the object using the yaml_emitter_delete() function.
- *
- * @param[out] emitter An empty parser object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_initialize(yaml_emitter_t *emitter);
-
-/**
- * Destroy an emitter.
- *
- * @param[in,out] emitter An emitter object.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_delete(yaml_emitter_t *emitter);
-
-/**
- * Set a string output.
- *
- * The emitter will write the output characters to the @a output buffer of the
- * size @a size. The emitter will set @a size_written to the number of written
- * bytes. If the buffer is smaller than required, the emitter produces the
- * YAML_WRITE_ERROR error.
- *
- * @param[in,out] emitter An emitter object.
- * @param[in] output An output buffer.
- * @param[in] size The buffer size.
- * @param[in] size_written The pointer to save the number of written
- * bytes.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_output_string(yaml_emitter_t *emitter,
- unsigned char *output, size_t size, size_t *size_written);
-
-/**
- * Set a file output.
- *
- * @a file should be a file object open for writing. The application is
- * responsible for closing the @a file.
- *
- * @param[in,out] emitter An emitter object.
- * @param[in] file An open file.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_output_file(yaml_emitter_t *emitter, FILE *file);
-
-/**
- * Set a generic output handler.
- *
- * @param[in,out] emitter An emitter object.
- * @param[in] handler A write handler.
- * @param[in] data Any application data for passing to the write
- * handler.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_output(yaml_emitter_t *emitter,
- yaml_write_handler_t *handler, void *data);
-
-/**
- * Set the output encoding.
- *
- * @param[in,out] emitter An emitter object.
- * @param[in] encoding The output encoding.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_encoding(yaml_emitter_t *emitter, yaml_encoding_t encoding);
-
-/**
- * Set if the output should be in the "canonical" format as in the YAML
- * specification.
- *
- * @param[in,out] emitter An emitter object.
- * @param[in] canonical If the output is canonical.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_canonical(yaml_emitter_t *emitter, int canonical);
-
-/**
+
+ /** The last assigned anchor id. */
+ int last_anchor_id;
+
+ /** The currently emitted document. */
+ yaml_document_t *document;
+
+ /**
+ * @}
+ */
+
+} yaml_emitter_t;
+
+/**
+ * Initialize an emitter.
+ *
+ * This function creates a new emitter object. An application is responsible
+ * for destroying the object using the yaml_emitter_delete() function.
+ *
+ * @param[out] emitter An empty parser object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_initialize(yaml_emitter_t *emitter);
+
+/**
+ * Destroy an emitter.
+ *
+ * @param[in,out] emitter An emitter object.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_delete(yaml_emitter_t *emitter);
+
+/**
+ * Set a string output.
+ *
+ * The emitter will write the output characters to the @a output buffer of the
+ * size @a size. The emitter will set @a size_written to the number of written
+ * bytes. If the buffer is smaller than required, the emitter produces the
+ * YAML_WRITE_ERROR error.
+ *
+ * @param[in,out] emitter An emitter object.
+ * @param[in] output An output buffer.
+ * @param[in] size The buffer size.
+ * @param[in] size_written The pointer to save the number of written
+ * bytes.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_output_string(yaml_emitter_t *emitter,
+ unsigned char *output, size_t size, size_t *size_written);
+
+/**
+ * Set a file output.
+ *
+ * @a file should be a file object open for writing. The application is
+ * responsible for closing the @a file.
+ *
+ * @param[in,out] emitter An emitter object.
+ * @param[in] file An open file.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_output_file(yaml_emitter_t *emitter, FILE *file);
+
+/**
+ * Set a generic output handler.
+ *
+ * @param[in,out] emitter An emitter object.
+ * @param[in] handler A write handler.
+ * @param[in] data Any application data for passing to the write
+ * handler.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_output(yaml_emitter_t *emitter,
+ yaml_write_handler_t *handler, void *data);
+
+/**
+ * Set the output encoding.
+ *
+ * @param[in,out] emitter An emitter object.
+ * @param[in] encoding The output encoding.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_encoding(yaml_emitter_t *emitter, yaml_encoding_t encoding);
+
+/**
+ * Set if the output should be in the "canonical" format as in the YAML
+ * specification.
+ *
+ * @param[in,out] emitter An emitter object.
+ * @param[in] canonical If the output is canonical.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_canonical(yaml_emitter_t *emitter, int canonical);
+
+/**
* Set the indentation increment.
- *
- * @param[in,out] emitter An emitter object.
- * @param[in] indent The indentation increment (1 < . < 10).
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_indent(yaml_emitter_t *emitter, int indent);
-
-/**
- * Set the preferred line width. @c -1 means unlimited.
- *
- * @param[in,out] emitter An emitter object.
- * @param[in] width The preferred line width.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_width(yaml_emitter_t *emitter, int width);
-
-/**
- * Set if unescaped non-ASCII characters are allowed.
- *
- * @param[in,out] emitter An emitter object.
- * @param[in] unicode If unescaped Unicode characters are allowed.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_unicode(yaml_emitter_t *emitter, int unicode);
-
-/**
- * Set the preferred line break.
- *
- * @param[in,out] emitter An emitter object.
- * @param[in] line_break The preferred line break.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_break(yaml_emitter_t *emitter, yaml_break_t line_break);
-
-/**
- * Emit an event.
- *
- * The event object may be generated using the yaml_parser_parse() function.
- * The emitter takes the responsibility for the event object and destroys its
- * content after it is emitted. The event object is destroyed even if the
- * function fails.
- *
- * @param[in,out] emitter An emitter object.
- * @param[in,out] event An event object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event);
-
-/**
- * Start a YAML stream.
- *
- * This function should be used before yaml_emitter_dump() is called.
- *
- * @param[in,out] emitter An emitter object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_open(yaml_emitter_t *emitter);
-
-/**
- * Finish a YAML stream.
- *
- * This function should be used after yaml_emitter_dump() is called.
- *
- * @param[in,out] emitter An emitter object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_close(yaml_emitter_t *emitter);
-
-/**
- * Emit a YAML document.
- *
- * The documen object may be generated using the yaml_parser_load() function
- * or the yaml_document_initialize() function. The emitter takes the
+ *
+ * @param[in,out] emitter An emitter object.
+ * @param[in] indent The indentation increment (1 < . < 10).
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_indent(yaml_emitter_t *emitter, int indent);
+
+/**
+ * Set the preferred line width. @c -1 means unlimited.
+ *
+ * @param[in,out] emitter An emitter object.
+ * @param[in] width The preferred line width.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_width(yaml_emitter_t *emitter, int width);
+
+/**
+ * Set if unescaped non-ASCII characters are allowed.
+ *
+ * @param[in,out] emitter An emitter object.
+ * @param[in] unicode If unescaped Unicode characters are allowed.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_unicode(yaml_emitter_t *emitter, int unicode);
+
+/**
+ * Set the preferred line break.
+ *
+ * @param[in,out] emitter An emitter object.
+ * @param[in] line_break The preferred line break.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_break(yaml_emitter_t *emitter, yaml_break_t line_break);
+
+/**
+ * Emit an event.
+ *
+ * The event object may be generated using the yaml_parser_parse() function.
+ * The emitter takes the responsibility for the event object and destroys its
+ * content after it is emitted. The event object is destroyed even if the
+ * function fails.
+ *
+ * @param[in,out] emitter An emitter object.
+ * @param[in,out] event An event object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event);
+
+/**
+ * Start a YAML stream.
+ *
+ * This function should be used before yaml_emitter_dump() is called.
+ *
+ * @param[in,out] emitter An emitter object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_open(yaml_emitter_t *emitter);
+
+/**
+ * Finish a YAML stream.
+ *
+ * This function should be used after yaml_emitter_dump() is called.
+ *
+ * @param[in,out] emitter An emitter object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_close(yaml_emitter_t *emitter);
+
+/**
+ * Emit a YAML document.
+ *
+ * The documen object may be generated using the yaml_parser_load() function
+ * or the yaml_document_initialize() function. The emitter takes the
* responsibility for the document object and destroys its content after
* it is emitted. The document object is destroyed even if the function fails.
- *
- * @param[in,out] emitter An emitter object.
- * @param[in,out] document A document object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_dump(yaml_emitter_t *emitter, yaml_document_t *document);
-
-/**
- * Flush the accumulated characters to the output.
- *
- * @param[in,out] emitter An emitter object.
- *
- * @returns @c 1 if the function succeeded, @c 0 on error.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_flush(yaml_emitter_t *emitter);
-
-/** @} */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* #ifndef YAML_H */
-
+ *
+ * @param[in,out] emitter An emitter object.
+ * @param[in,out] document A document object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_dump(yaml_emitter_t *emitter, yaml_document_t *document);
+
+/**
+ * Flush the accumulated characters to the output.
+ *
+ * @param[in,out] emitter An emitter object.
+ *
+ * @returns @c 1 if the function succeeded, @c 0 on error.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_flush(yaml_emitter_t *emitter);
+
+/** @} */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* #ifndef YAML_H */
+
diff --git a/contrib/libs/yaml/src/api.c b/contrib/libs/yaml/src/api.c
index c237c83564..16f88bd762 100644
--- a/contrib/libs/yaml/src/api.c
+++ b/contrib/libs/yaml/src/api.c
@@ -1,1393 +1,1393 @@
-
-#include "yaml_private.h"
-
-/*
- * Get the library version.
- */
-
-YAML_DECLARE(const char *)
-yaml_get_version_string(void)
-{
- return YAML_VERSION_STRING;
-}
-
-/*
- * Get the library version numbers.
- */
-
-YAML_DECLARE(void)
-yaml_get_version(int *major, int *minor, int *patch)
-{
- *major = YAML_VERSION_MAJOR;
- *minor = YAML_VERSION_MINOR;
- *patch = YAML_VERSION_PATCH;
-}
-
-/*
- * Allocate a dynamic memory block.
- */
-
-YAML_DECLARE(void *)
-yaml_malloc(size_t size)
-{
- return malloc(size ? size : 1);
-}
-
-/*
- * Reallocate a dynamic memory block.
- */
-
-YAML_DECLARE(void *)
-yaml_realloc(void *ptr, size_t size)
-{
- return ptr ? realloc(ptr, size ? size : 1) : malloc(size ? size : 1);
-}
-
-/*
- * Free a dynamic memory block.
- */
-
-YAML_DECLARE(void)
-yaml_free(void *ptr)
-{
- if (ptr) free(ptr);
-}
-
-/*
- * Duplicate a string.
- */
-
-YAML_DECLARE(yaml_char_t *)
-yaml_strdup(const yaml_char_t *str)
-{
- if (!str)
- return NULL;
-
- return (yaml_char_t *)strdup((char *)str);
-}
-
-/*
- * Extend a string.
- */
-
-YAML_DECLARE(int)
-yaml_string_extend(yaml_char_t **start,
- yaml_char_t **pointer, yaml_char_t **end)
-{
+
+#include "yaml_private.h"
+
+/*
+ * Get the library version.
+ */
+
+YAML_DECLARE(const char *)
+yaml_get_version_string(void)
+{
+ return YAML_VERSION_STRING;
+}
+
+/*
+ * Get the library version numbers.
+ */
+
+YAML_DECLARE(void)
+yaml_get_version(int *major, int *minor, int *patch)
+{
+ *major = YAML_VERSION_MAJOR;
+ *minor = YAML_VERSION_MINOR;
+ *patch = YAML_VERSION_PATCH;
+}
+
+/*
+ * Allocate a dynamic memory block.
+ */
+
+YAML_DECLARE(void *)
+yaml_malloc(size_t size)
+{
+ return malloc(size ? size : 1);
+}
+
+/*
+ * Reallocate a dynamic memory block.
+ */
+
+YAML_DECLARE(void *)
+yaml_realloc(void *ptr, size_t size)
+{
+ return ptr ? realloc(ptr, size ? size : 1) : malloc(size ? size : 1);
+}
+
+/*
+ * Free a dynamic memory block.
+ */
+
+YAML_DECLARE(void)
+yaml_free(void *ptr)
+{
+ if (ptr) free(ptr);
+}
+
+/*
+ * Duplicate a string.
+ */
+
+YAML_DECLARE(yaml_char_t *)
+yaml_strdup(const yaml_char_t *str)
+{
+ if (!str)
+ return NULL;
+
+ return (yaml_char_t *)strdup((char *)str);
+}
+
+/*
+ * Extend a string.
+ */
+
+YAML_DECLARE(int)
+yaml_string_extend(yaml_char_t **start,
+ yaml_char_t **pointer, yaml_char_t **end)
+{
yaml_char_t *new_start = (yaml_char_t *)yaml_realloc((void*)*start, (*end - *start)*2);
-
- if (!new_start) return 0;
-
- memset(new_start + (*end - *start), 0, *end - *start);
-
- *pointer = new_start + (*pointer - *start);
- *end = new_start + (*end - *start)*2;
- *start = new_start;
-
- return 1;
-}
-
-/*
- * Append a string B to a string A.
- */
-
-YAML_DECLARE(int)
-yaml_string_join(
- yaml_char_t **a_start, yaml_char_t **a_pointer, yaml_char_t **a_end,
+
+ if (!new_start) return 0;
+
+ memset(new_start + (*end - *start), 0, *end - *start);
+
+ *pointer = new_start + (*pointer - *start);
+ *end = new_start + (*end - *start)*2;
+ *start = new_start;
+
+ return 1;
+}
+
+/*
+ * Append a string B to a string A.
+ */
+
+YAML_DECLARE(int)
+yaml_string_join(
+ yaml_char_t **a_start, yaml_char_t **a_pointer, yaml_char_t **a_end,
yaml_char_t **b_start, yaml_char_t **b_pointer, SHIM(yaml_char_t **b_end))
-{
+{
UNUSED_PARAM(b_end)
- if (*b_start == *b_pointer)
- return 1;
-
- while (*a_end - *a_pointer <= *b_pointer - *b_start) {
- if (!yaml_string_extend(a_start, a_pointer, a_end))
- return 0;
- }
-
- memcpy(*a_pointer, *b_start, *b_pointer - *b_start);
- *a_pointer += *b_pointer - *b_start;
-
- return 1;
-}
-
-/*
- * Extend a stack.
- */
-
-YAML_DECLARE(int)
-yaml_stack_extend(void **start, void **top, void **end)
-{
+ if (*b_start == *b_pointer)
+ return 1;
+
+ while (*a_end - *a_pointer <= *b_pointer - *b_start) {
+ if (!yaml_string_extend(a_start, a_pointer, a_end))
+ return 0;
+ }
+
+ memcpy(*a_pointer, *b_start, *b_pointer - *b_start);
+ *a_pointer += *b_pointer - *b_start;
+
+ return 1;
+}
+
+/*
+ * Extend a stack.
+ */
+
+YAML_DECLARE(int)
+yaml_stack_extend(void **start, void **top, void **end)
+{
void *new_start;
-
+
if ((char *)*end - (char *)*start >= INT_MAX / 2)
return 0;
new_start = yaml_realloc(*start, ((char *)*end - (char *)*start)*2);
- if (!new_start) return 0;
-
- *top = (char *)new_start + ((char *)*top - (char *)*start);
- *end = (char *)new_start + ((char *)*end - (char *)*start)*2;
- *start = new_start;
-
- return 1;
-}
-
-/*
- * Extend or move a queue.
- */
-
-YAML_DECLARE(int)
-yaml_queue_extend(void **start, void **head, void **tail, void **end)
-{
- /* Check if we need to resize the queue. */
-
- if (*start == *head && *tail == *end) {
- void *new_start = yaml_realloc(*start,
- ((char *)*end - (char *)*start)*2);
-
- if (!new_start) return 0;
-
- *head = (char *)new_start + ((char *)*head - (char *)*start);
- *tail = (char *)new_start + ((char *)*tail - (char *)*start);
- *end = (char *)new_start + ((char *)*end - (char *)*start)*2;
- *start = new_start;
- }
-
- /* Check if we need to move the queue at the beginning of the buffer. */
-
- if (*tail == *end) {
- if (*head != *tail) {
- memmove(*start, *head, (char *)*tail - (char *)*head);
- }
- *tail = (char *)*tail - (char *)*head + (char *)*start;
- *head = *start;
- }
-
- return 1;
-}
-
-
-/*
- * Create a new parser object.
- */
-
-YAML_DECLARE(int)
-yaml_parser_initialize(yaml_parser_t *parser)
-{
- assert(parser); /* Non-NULL parser object expected. */
-
- memset(parser, 0, sizeof(yaml_parser_t));
- if (!BUFFER_INIT(parser, parser->raw_buffer, INPUT_RAW_BUFFER_SIZE))
- goto error;
- if (!BUFFER_INIT(parser, parser->buffer, INPUT_BUFFER_SIZE))
- goto error;
+ if (!new_start) return 0;
+
+ *top = (char *)new_start + ((char *)*top - (char *)*start);
+ *end = (char *)new_start + ((char *)*end - (char *)*start)*2;
+ *start = new_start;
+
+ return 1;
+}
+
+/*
+ * Extend or move a queue.
+ */
+
+YAML_DECLARE(int)
+yaml_queue_extend(void **start, void **head, void **tail, void **end)
+{
+ /* Check if we need to resize the queue. */
+
+ if (*start == *head && *tail == *end) {
+ void *new_start = yaml_realloc(*start,
+ ((char *)*end - (char *)*start)*2);
+
+ if (!new_start) return 0;
+
+ *head = (char *)new_start + ((char *)*head - (char *)*start);
+ *tail = (char *)new_start + ((char *)*tail - (char *)*start);
+ *end = (char *)new_start + ((char *)*end - (char *)*start)*2;
+ *start = new_start;
+ }
+
+ /* Check if we need to move the queue at the beginning of the buffer. */
+
+ if (*tail == *end) {
+ if (*head != *tail) {
+ memmove(*start, *head, (char *)*tail - (char *)*head);
+ }
+ *tail = (char *)*tail - (char *)*head + (char *)*start;
+ *head = *start;
+ }
+
+ return 1;
+}
+
+
+/*
+ * Create a new parser object.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_initialize(yaml_parser_t *parser)
+{
+ assert(parser); /* Non-NULL parser object expected. */
+
+ memset(parser, 0, sizeof(yaml_parser_t));
+ if (!BUFFER_INIT(parser, parser->raw_buffer, INPUT_RAW_BUFFER_SIZE))
+ goto error;
+ if (!BUFFER_INIT(parser, parser->buffer, INPUT_BUFFER_SIZE))
+ goto error;
if (!QUEUE_INIT(parser, parser->tokens, INITIAL_QUEUE_SIZE, yaml_token_t*))
- goto error;
+ goto error;
if (!STACK_INIT(parser, parser->indents, int*))
- goto error;
+ goto error;
if (!STACK_INIT(parser, parser->simple_keys, yaml_simple_key_t*))
- goto error;
+ goto error;
if (!STACK_INIT(parser, parser->states, yaml_parser_state_t*))
- goto error;
+ goto error;
if (!STACK_INIT(parser, parser->marks, yaml_mark_t*))
- goto error;
+ goto error;
if (!STACK_INIT(parser, parser->tag_directives, yaml_tag_directive_t*))
- goto error;
-
- return 1;
-
-error:
-
- BUFFER_DEL(parser, parser->raw_buffer);
- BUFFER_DEL(parser, parser->buffer);
- QUEUE_DEL(parser, parser->tokens);
- STACK_DEL(parser, parser->indents);
- STACK_DEL(parser, parser->simple_keys);
- STACK_DEL(parser, parser->states);
- STACK_DEL(parser, parser->marks);
- STACK_DEL(parser, parser->tag_directives);
-
- return 0;
-}
-
-/*
- * Destroy a parser object.
- */
-
-YAML_DECLARE(void)
-yaml_parser_delete(yaml_parser_t *parser)
-{
- assert(parser); /* Non-NULL parser object expected. */
-
- BUFFER_DEL(parser, parser->raw_buffer);
- BUFFER_DEL(parser, parser->buffer);
- while (!QUEUE_EMPTY(parser, parser->tokens)) {
- yaml_token_delete(&DEQUEUE(parser, parser->tokens));
- }
- QUEUE_DEL(parser, parser->tokens);
- STACK_DEL(parser, parser->indents);
- STACK_DEL(parser, parser->simple_keys);
- STACK_DEL(parser, parser->states);
- STACK_DEL(parser, parser->marks);
- while (!STACK_EMPTY(parser, parser->tag_directives)) {
- yaml_tag_directive_t tag_directive = POP(parser, parser->tag_directives);
- yaml_free(tag_directive.handle);
- yaml_free(tag_directive.prefix);
- }
- STACK_DEL(parser, parser->tag_directives);
-
- memset(parser, 0, sizeof(yaml_parser_t));
-}
-
-/*
- * String read handler.
- */
-
-static int
-yaml_string_read_handler(void *data, unsigned char *buffer, size_t size,
- size_t *size_read)
-{
+ goto error;
+
+ return 1;
+
+error:
+
+ BUFFER_DEL(parser, parser->raw_buffer);
+ BUFFER_DEL(parser, parser->buffer);
+ QUEUE_DEL(parser, parser->tokens);
+ STACK_DEL(parser, parser->indents);
+ STACK_DEL(parser, parser->simple_keys);
+ STACK_DEL(parser, parser->states);
+ STACK_DEL(parser, parser->marks);
+ STACK_DEL(parser, parser->tag_directives);
+
+ return 0;
+}
+
+/*
+ * Destroy a parser object.
+ */
+
+YAML_DECLARE(void)
+yaml_parser_delete(yaml_parser_t *parser)
+{
+ assert(parser); /* Non-NULL parser object expected. */
+
+ BUFFER_DEL(parser, parser->raw_buffer);
+ BUFFER_DEL(parser, parser->buffer);
+ while (!QUEUE_EMPTY(parser, parser->tokens)) {
+ yaml_token_delete(&DEQUEUE(parser, parser->tokens));
+ }
+ QUEUE_DEL(parser, parser->tokens);
+ STACK_DEL(parser, parser->indents);
+ STACK_DEL(parser, parser->simple_keys);
+ STACK_DEL(parser, parser->states);
+ STACK_DEL(parser, parser->marks);
+ while (!STACK_EMPTY(parser, parser->tag_directives)) {
+ yaml_tag_directive_t tag_directive = POP(parser, parser->tag_directives);
+ yaml_free(tag_directive.handle);
+ yaml_free(tag_directive.prefix);
+ }
+ STACK_DEL(parser, parser->tag_directives);
+
+ memset(parser, 0, sizeof(yaml_parser_t));
+}
+
+/*
+ * String read handler.
+ */
+
+static int
+yaml_string_read_handler(void *data, unsigned char *buffer, size_t size,
+ size_t *size_read)
+{
yaml_parser_t *parser = (yaml_parser_t *)data;
-
- if (parser->input.string.current == parser->input.string.end) {
- *size_read = 0;
- return 1;
- }
-
- if (size > (size_t)(parser->input.string.end
- - parser->input.string.current)) {
- size = parser->input.string.end - parser->input.string.current;
- }
-
- memcpy(buffer, parser->input.string.current, size);
- parser->input.string.current += size;
- *size_read = size;
- return 1;
-}
-
-/*
- * File read handler.
- */
-
-static int
-yaml_file_read_handler(void *data, unsigned char *buffer, size_t size,
- size_t *size_read)
-{
+
+ if (parser->input.string.current == parser->input.string.end) {
+ *size_read = 0;
+ return 1;
+ }
+
+ if (size > (size_t)(parser->input.string.end
+ - parser->input.string.current)) {
+ size = parser->input.string.end - parser->input.string.current;
+ }
+
+ memcpy(buffer, parser->input.string.current, size);
+ parser->input.string.current += size;
+ *size_read = size;
+ return 1;
+}
+
+/*
+ * File read handler.
+ */
+
+static int
+yaml_file_read_handler(void *data, unsigned char *buffer, size_t size,
+ size_t *size_read)
+{
yaml_parser_t *parser = (yaml_parser_t *)data;
-
- *size_read = fread(buffer, 1, size, parser->input.file);
- return !ferror(parser->input.file);
-}
-
-/*
- * Set a string input.
- */
-
-YAML_DECLARE(void)
-yaml_parser_set_input_string(yaml_parser_t *parser,
- const unsigned char *input, size_t size)
-{
- assert(parser); /* Non-NULL parser object expected. */
- assert(!parser->read_handler); /* You can set the source only once. */
- assert(input); /* Non-NULL input string expected. */
-
- parser->read_handler = yaml_string_read_handler;
- parser->read_handler_data = parser;
-
- parser->input.string.start = input;
- parser->input.string.current = input;
- parser->input.string.end = input+size;
-}
-
-/*
- * Set a file input.
- */
-
-YAML_DECLARE(void)
-yaml_parser_set_input_file(yaml_parser_t *parser, FILE *file)
-{
- assert(parser); /* Non-NULL parser object expected. */
- assert(!parser->read_handler); /* You can set the source only once. */
- assert(file); /* Non-NULL file object expected. */
-
- parser->read_handler = yaml_file_read_handler;
- parser->read_handler_data = parser;
-
- parser->input.file = file;
-}
-
-/*
- * Set a generic input.
- */
-
-YAML_DECLARE(void)
-yaml_parser_set_input(yaml_parser_t *parser,
- yaml_read_handler_t *handler, void *data)
-{
- assert(parser); /* Non-NULL parser object expected. */
- assert(!parser->read_handler); /* You can set the source only once. */
- assert(handler); /* Non-NULL read handler expected. */
-
- parser->read_handler = handler;
- parser->read_handler_data = data;
-}
-
-/*
- * Set the source encoding.
- */
-
-YAML_DECLARE(void)
-yaml_parser_set_encoding(yaml_parser_t *parser, yaml_encoding_t encoding)
-{
- assert(parser); /* Non-NULL parser object expected. */
- assert(!parser->encoding); /* Encoding is already set or detected. */
-
- parser->encoding = encoding;
-}
-
-/*
- * Create a new emitter object.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_initialize(yaml_emitter_t *emitter)
-{
- assert(emitter); /* Non-NULL emitter object expected. */
-
- memset(emitter, 0, sizeof(yaml_emitter_t));
- if (!BUFFER_INIT(emitter, emitter->buffer, OUTPUT_BUFFER_SIZE))
- goto error;
- if (!BUFFER_INIT(emitter, emitter->raw_buffer, OUTPUT_RAW_BUFFER_SIZE))
- goto error;
+
+ *size_read = fread(buffer, 1, size, parser->input.file);
+ return !ferror(parser->input.file);
+}
+
+/*
+ * Set a string input.
+ */
+
+YAML_DECLARE(void)
+yaml_parser_set_input_string(yaml_parser_t *parser,
+ const unsigned char *input, size_t size)
+{
+ assert(parser); /* Non-NULL parser object expected. */
+ assert(!parser->read_handler); /* You can set the source only once. */
+ assert(input); /* Non-NULL input string expected. */
+
+ parser->read_handler = yaml_string_read_handler;
+ parser->read_handler_data = parser;
+
+ parser->input.string.start = input;
+ parser->input.string.current = input;
+ parser->input.string.end = input+size;
+}
+
+/*
+ * Set a file input.
+ */
+
+YAML_DECLARE(void)
+yaml_parser_set_input_file(yaml_parser_t *parser, FILE *file)
+{
+ assert(parser); /* Non-NULL parser object expected. */
+ assert(!parser->read_handler); /* You can set the source only once. */
+ assert(file); /* Non-NULL file object expected. */
+
+ parser->read_handler = yaml_file_read_handler;
+ parser->read_handler_data = parser;
+
+ parser->input.file = file;
+}
+
+/*
+ * Set a generic input.
+ */
+
+YAML_DECLARE(void)
+yaml_parser_set_input(yaml_parser_t *parser,
+ yaml_read_handler_t *handler, void *data)
+{
+ assert(parser); /* Non-NULL parser object expected. */
+ assert(!parser->read_handler); /* You can set the source only once. */
+ assert(handler); /* Non-NULL read handler expected. */
+
+ parser->read_handler = handler;
+ parser->read_handler_data = data;
+}
+
+/*
+ * Set the source encoding.
+ */
+
+YAML_DECLARE(void)
+yaml_parser_set_encoding(yaml_parser_t *parser, yaml_encoding_t encoding)
+{
+ assert(parser); /* Non-NULL parser object expected. */
+ assert(!parser->encoding); /* Encoding is already set or detected. */
+
+ parser->encoding = encoding;
+}
+
+/*
+ * Create a new emitter object.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_initialize(yaml_emitter_t *emitter)
+{
+ assert(emitter); /* Non-NULL emitter object expected. */
+
+ memset(emitter, 0, sizeof(yaml_emitter_t));
+ if (!BUFFER_INIT(emitter, emitter->buffer, OUTPUT_BUFFER_SIZE))
+ goto error;
+ if (!BUFFER_INIT(emitter, emitter->raw_buffer, OUTPUT_RAW_BUFFER_SIZE))
+ goto error;
if (!STACK_INIT(emitter, emitter->states, yaml_emitter_state_t*))
- goto error;
+ goto error;
if (!QUEUE_INIT(emitter, emitter->events, INITIAL_QUEUE_SIZE, yaml_event_t*))
- goto error;
+ goto error;
if (!STACK_INIT(emitter, emitter->indents, int*))
- goto error;
+ goto error;
if (!STACK_INIT(emitter, emitter->tag_directives, yaml_tag_directive_t*))
- goto error;
-
- return 1;
-
-error:
-
- BUFFER_DEL(emitter, emitter->buffer);
- BUFFER_DEL(emitter, emitter->raw_buffer);
- STACK_DEL(emitter, emitter->states);
- QUEUE_DEL(emitter, emitter->events);
- STACK_DEL(emitter, emitter->indents);
- STACK_DEL(emitter, emitter->tag_directives);
-
- return 0;
-}
-
-/*
- * Destroy an emitter object.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_delete(yaml_emitter_t *emitter)
-{
- assert(emitter); /* Non-NULL emitter object expected. */
-
- BUFFER_DEL(emitter, emitter->buffer);
- BUFFER_DEL(emitter, emitter->raw_buffer);
- STACK_DEL(emitter, emitter->states);
- while (!QUEUE_EMPTY(emitter, emitter->events)) {
- yaml_event_delete(&DEQUEUE(emitter, emitter->events));
- }
- QUEUE_DEL(emitter, emitter->events);
- STACK_DEL(emitter, emitter->indents);
- while (!STACK_EMPTY(empty, emitter->tag_directives)) {
- yaml_tag_directive_t tag_directive = POP(emitter, emitter->tag_directives);
- yaml_free(tag_directive.handle);
- yaml_free(tag_directive.prefix);
- }
- STACK_DEL(emitter, emitter->tag_directives);
- yaml_free(emitter->anchors);
-
- memset(emitter, 0, sizeof(yaml_emitter_t));
-}
-
-/*
- * String write handler.
- */
-
-static int
-yaml_string_write_handler(void *data, unsigned char *buffer, size_t size)
-{
+ goto error;
+
+ return 1;
+
+error:
+
+ BUFFER_DEL(emitter, emitter->buffer);
+ BUFFER_DEL(emitter, emitter->raw_buffer);
+ STACK_DEL(emitter, emitter->states);
+ QUEUE_DEL(emitter, emitter->events);
+ STACK_DEL(emitter, emitter->indents);
+ STACK_DEL(emitter, emitter->tag_directives);
+
+ return 0;
+}
+
+/*
+ * Destroy an emitter object.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_delete(yaml_emitter_t *emitter)
+{
+ assert(emitter); /* Non-NULL emitter object expected. */
+
+ BUFFER_DEL(emitter, emitter->buffer);
+ BUFFER_DEL(emitter, emitter->raw_buffer);
+ STACK_DEL(emitter, emitter->states);
+ while (!QUEUE_EMPTY(emitter, emitter->events)) {
+ yaml_event_delete(&DEQUEUE(emitter, emitter->events));
+ }
+ QUEUE_DEL(emitter, emitter->events);
+ STACK_DEL(emitter, emitter->indents);
+ while (!STACK_EMPTY(empty, emitter->tag_directives)) {
+ yaml_tag_directive_t tag_directive = POP(emitter, emitter->tag_directives);
+ yaml_free(tag_directive.handle);
+ yaml_free(tag_directive.prefix);
+ }
+ STACK_DEL(emitter, emitter->tag_directives);
+ yaml_free(emitter->anchors);
+
+ memset(emitter, 0, sizeof(yaml_emitter_t));
+}
+
+/*
+ * String write handler.
+ */
+
+static int
+yaml_string_write_handler(void *data, unsigned char *buffer, size_t size)
+{
yaml_emitter_t *emitter = (yaml_emitter_t *)data;
-
+
if (emitter->output.string.size - *emitter->output.string.size_written
- < size) {
- memcpy(emitter->output.string.buffer
- + *emitter->output.string.size_written,
- buffer,
- emitter->output.string.size
- - *emitter->output.string.size_written);
- *emitter->output.string.size_written = emitter->output.string.size;
- return 0;
- }
-
- memcpy(emitter->output.string.buffer
- + *emitter->output.string.size_written, buffer, size);
- *emitter->output.string.size_written += size;
- return 1;
-}
-
-/*
- * File write handler.
- */
-
-static int
-yaml_file_write_handler(void *data, unsigned char *buffer, size_t size)
-{
+ < size) {
+ memcpy(emitter->output.string.buffer
+ + *emitter->output.string.size_written,
+ buffer,
+ emitter->output.string.size
+ - *emitter->output.string.size_written);
+ *emitter->output.string.size_written = emitter->output.string.size;
+ return 0;
+ }
+
+ memcpy(emitter->output.string.buffer
+ + *emitter->output.string.size_written, buffer, size);
+ *emitter->output.string.size_written += size;
+ return 1;
+}
+
+/*
+ * File write handler.
+ */
+
+static int
+yaml_file_write_handler(void *data, unsigned char *buffer, size_t size)
+{
yaml_emitter_t *emitter = (yaml_emitter_t *)data;
-
- return (fwrite(buffer, 1, size, emitter->output.file) == size);
-}
-/*
- * Set a string output.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_output_string(yaml_emitter_t *emitter,
- unsigned char *output, size_t size, size_t *size_written)
-{
- assert(emitter); /* Non-NULL emitter object expected. */
- assert(!emitter->write_handler); /* You can set the output only once. */
- assert(output); /* Non-NULL output string expected. */
-
- emitter->write_handler = yaml_string_write_handler;
- emitter->write_handler_data = emitter;
-
- emitter->output.string.buffer = output;
- emitter->output.string.size = size;
- emitter->output.string.size_written = size_written;
- *size_written = 0;
-}
-
-/*
- * Set a file output.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_output_file(yaml_emitter_t *emitter, FILE *file)
-{
- assert(emitter); /* Non-NULL emitter object expected. */
- assert(!emitter->write_handler); /* You can set the output only once. */
- assert(file); /* Non-NULL file object expected. */
-
- emitter->write_handler = yaml_file_write_handler;
- emitter->write_handler_data = emitter;
-
- emitter->output.file = file;
-}
-
-/*
- * Set a generic output handler.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_output(yaml_emitter_t *emitter,
- yaml_write_handler_t *handler, void *data)
-{
- assert(emitter); /* Non-NULL emitter object expected. */
- assert(!emitter->write_handler); /* You can set the output only once. */
- assert(handler); /* Non-NULL handler object expected. */
-
- emitter->write_handler = handler;
- emitter->write_handler_data = data;
-}
-
-/*
- * Set the output encoding.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_encoding(yaml_emitter_t *emitter, yaml_encoding_t encoding)
-{
- assert(emitter); /* Non-NULL emitter object expected. */
- assert(!emitter->encoding); /* You can set encoding only once. */
-
- emitter->encoding = encoding;
-}
-
-/*
- * Set the canonical output style.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_canonical(yaml_emitter_t *emitter, int canonical)
-{
- assert(emitter); /* Non-NULL emitter object expected. */
-
- emitter->canonical = (canonical != 0);
-}
-
-/*
- * Set the indentation increment.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_indent(yaml_emitter_t *emitter, int indent)
-{
- assert(emitter); /* Non-NULL emitter object expected. */
-
- emitter->best_indent = (1 < indent && indent < 10) ? indent : 2;
-}
-
-/*
- * Set the preferred line width.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_width(yaml_emitter_t *emitter, int width)
-{
- assert(emitter); /* Non-NULL emitter object expected. */
-
- emitter->best_width = (width >= 0) ? width : -1;
-}
-
-/*
- * Set if unescaped non-ASCII characters are allowed.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_unicode(yaml_emitter_t *emitter, int unicode)
-{
- assert(emitter); /* Non-NULL emitter object expected. */
-
- emitter->unicode = (unicode != 0);
-}
-
-/*
- * Set the preferred line break character.
- */
-
-YAML_DECLARE(void)
-yaml_emitter_set_break(yaml_emitter_t *emitter, yaml_break_t line_break)
-{
- assert(emitter); /* Non-NULL emitter object expected. */
-
- emitter->line_break = line_break;
-}
-
-/*
- * Destroy a token object.
- */
-
-YAML_DECLARE(void)
-yaml_token_delete(yaml_token_t *token)
-{
- assert(token); /* Non-NULL token object expected. */
-
- switch (token->type)
- {
- case YAML_TAG_DIRECTIVE_TOKEN:
- yaml_free(token->data.tag_directive.handle);
- yaml_free(token->data.tag_directive.prefix);
- break;
-
- case YAML_ALIAS_TOKEN:
- yaml_free(token->data.alias.value);
- break;
-
- case YAML_ANCHOR_TOKEN:
- yaml_free(token->data.anchor.value);
- break;
-
- case YAML_TAG_TOKEN:
- yaml_free(token->data.tag.handle);
- yaml_free(token->data.tag.suffix);
- break;
-
- case YAML_SCALAR_TOKEN:
- yaml_free(token->data.scalar.value);
- break;
-
- default:
- break;
- }
-
- memset(token, 0, sizeof(yaml_token_t));
-}
-
-/*
- * Check if a string is a valid UTF-8 sequence.
- *
- * Check 'reader.c' for more details on UTF-8 encoding.
- */
-
-static int
+
+ return (fwrite(buffer, 1, size, emitter->output.file) == size);
+}
+/*
+ * Set a string output.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_output_string(yaml_emitter_t *emitter,
+ unsigned char *output, size_t size, size_t *size_written)
+{
+ assert(emitter); /* Non-NULL emitter object expected. */
+ assert(!emitter->write_handler); /* You can set the output only once. */
+ assert(output); /* Non-NULL output string expected. */
+
+ emitter->write_handler = yaml_string_write_handler;
+ emitter->write_handler_data = emitter;
+
+ emitter->output.string.buffer = output;
+ emitter->output.string.size = size;
+ emitter->output.string.size_written = size_written;
+ *size_written = 0;
+}
+
+/*
+ * Set a file output.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_output_file(yaml_emitter_t *emitter, FILE *file)
+{
+ assert(emitter); /* Non-NULL emitter object expected. */
+ assert(!emitter->write_handler); /* You can set the output only once. */
+ assert(file); /* Non-NULL file object expected. */
+
+ emitter->write_handler = yaml_file_write_handler;
+ emitter->write_handler_data = emitter;
+
+ emitter->output.file = file;
+}
+
+/*
+ * Set a generic output handler.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_output(yaml_emitter_t *emitter,
+ yaml_write_handler_t *handler, void *data)
+{
+ assert(emitter); /* Non-NULL emitter object expected. */
+ assert(!emitter->write_handler); /* You can set the output only once. */
+ assert(handler); /* Non-NULL handler object expected. */
+
+ emitter->write_handler = handler;
+ emitter->write_handler_data = data;
+}
+
+/*
+ * Set the output encoding.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_encoding(yaml_emitter_t *emitter, yaml_encoding_t encoding)
+{
+ assert(emitter); /* Non-NULL emitter object expected. */
+ assert(!emitter->encoding); /* You can set encoding only once. */
+
+ emitter->encoding = encoding;
+}
+
+/*
+ * Set the canonical output style.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_canonical(yaml_emitter_t *emitter, int canonical)
+{
+ assert(emitter); /* Non-NULL emitter object expected. */
+
+ emitter->canonical = (canonical != 0);
+}
+
+/*
+ * Set the indentation increment.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_indent(yaml_emitter_t *emitter, int indent)
+{
+ assert(emitter); /* Non-NULL emitter object expected. */
+
+ emitter->best_indent = (1 < indent && indent < 10) ? indent : 2;
+}
+
+/*
+ * Set the preferred line width.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_width(yaml_emitter_t *emitter, int width)
+{
+ assert(emitter); /* Non-NULL emitter object expected. */
+
+ emitter->best_width = (width >= 0) ? width : -1;
+}
+
+/*
+ * Set if unescaped non-ASCII characters are allowed.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_unicode(yaml_emitter_t *emitter, int unicode)
+{
+ assert(emitter); /* Non-NULL emitter object expected. */
+
+ emitter->unicode = (unicode != 0);
+}
+
+/*
+ * Set the preferred line break character.
+ */
+
+YAML_DECLARE(void)
+yaml_emitter_set_break(yaml_emitter_t *emitter, yaml_break_t line_break)
+{
+ assert(emitter); /* Non-NULL emitter object expected. */
+
+ emitter->line_break = line_break;
+}
+
+/*
+ * Destroy a token object.
+ */
+
+YAML_DECLARE(void)
+yaml_token_delete(yaml_token_t *token)
+{
+ assert(token); /* Non-NULL token object expected. */
+
+ switch (token->type)
+ {
+ case YAML_TAG_DIRECTIVE_TOKEN:
+ yaml_free(token->data.tag_directive.handle);
+ yaml_free(token->data.tag_directive.prefix);
+ break;
+
+ case YAML_ALIAS_TOKEN:
+ yaml_free(token->data.alias.value);
+ break;
+
+ case YAML_ANCHOR_TOKEN:
+ yaml_free(token->data.anchor.value);
+ break;
+
+ case YAML_TAG_TOKEN:
+ yaml_free(token->data.tag.handle);
+ yaml_free(token->data.tag.suffix);
+ break;
+
+ case YAML_SCALAR_TOKEN:
+ yaml_free(token->data.scalar.value);
+ break;
+
+ default:
+ break;
+ }
+
+ memset(token, 0, sizeof(yaml_token_t));
+}
+
+/*
+ * Check if a string is a valid UTF-8 sequence.
+ *
+ * Check 'reader.c' for more details on UTF-8 encoding.
+ */
+
+static int
yaml_check_utf8(const yaml_char_t *start, size_t length)
-{
+{
const yaml_char_t *end = start+length;
const yaml_char_t *pointer = start;
-
- while (pointer < end) {
- unsigned char octet;
- unsigned int width;
- unsigned int value;
- size_t k;
-
- octet = pointer[0];
- width = (octet & 0x80) == 0x00 ? 1 :
- (octet & 0xE0) == 0xC0 ? 2 :
- (octet & 0xF0) == 0xE0 ? 3 :
- (octet & 0xF8) == 0xF0 ? 4 : 0;
- value = (octet & 0x80) == 0x00 ? octet & 0x7F :
- (octet & 0xE0) == 0xC0 ? octet & 0x1F :
- (octet & 0xF0) == 0xE0 ? octet & 0x0F :
- (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0;
- if (!width) return 0;
- if (pointer+width > end) return 0;
- for (k = 1; k < width; k ++) {
- octet = pointer[k];
- if ((octet & 0xC0) != 0x80) return 0;
- value = (value << 6) + (octet & 0x3F);
- }
- if (!((width == 1) ||
- (width == 2 && value >= 0x80) ||
- (width == 3 && value >= 0x800) ||
- (width == 4 && value >= 0x10000))) return 0;
-
- pointer += width;
- }
-
- return 1;
-}
-
-/*
- * Create STREAM-START.
- */
-
-YAML_DECLARE(int)
-yaml_stream_start_event_initialize(yaml_event_t *event,
- yaml_encoding_t encoding)
-{
- yaml_mark_t mark = { 0, 0, 0 };
-
- assert(event); /* Non-NULL event object is expected. */
-
- STREAM_START_EVENT_INIT(*event, encoding, mark, mark);
-
- return 1;
-}
-
-/*
- * Create STREAM-END.
- */
-
-YAML_DECLARE(int)
-yaml_stream_end_event_initialize(yaml_event_t *event)
-{
- yaml_mark_t mark = { 0, 0, 0 };
-
- assert(event); /* Non-NULL event object is expected. */
-
- STREAM_END_EVENT_INIT(*event, mark, mark);
-
- return 1;
-}
-
-/*
- * Create DOCUMENT-START.
- */
-
-YAML_DECLARE(int)
-yaml_document_start_event_initialize(yaml_event_t *event,
- yaml_version_directive_t *version_directive,
- yaml_tag_directive_t *tag_directives_start,
- yaml_tag_directive_t *tag_directives_end,
- int implicit)
-{
- struct {
- yaml_error_type_t error;
- } context;
- yaml_mark_t mark = { 0, 0, 0 };
- yaml_version_directive_t *version_directive_copy = NULL;
- struct {
- yaml_tag_directive_t *start;
- yaml_tag_directive_t *end;
- yaml_tag_directive_t *top;
- } tag_directives_copy = { NULL, NULL, NULL };
- yaml_tag_directive_t value = { NULL, NULL };
-
- assert(event); /* Non-NULL event object is expected. */
- assert((tag_directives_start && tag_directives_end) ||
- (tag_directives_start == tag_directives_end));
- /* Valid tag directives are expected. */
-
- if (version_directive) {
+
+ while (pointer < end) {
+ unsigned char octet;
+ unsigned int width;
+ unsigned int value;
+ size_t k;
+
+ octet = pointer[0];
+ width = (octet & 0x80) == 0x00 ? 1 :
+ (octet & 0xE0) == 0xC0 ? 2 :
+ (octet & 0xF0) == 0xE0 ? 3 :
+ (octet & 0xF8) == 0xF0 ? 4 : 0;
+ value = (octet & 0x80) == 0x00 ? octet & 0x7F :
+ (octet & 0xE0) == 0xC0 ? octet & 0x1F :
+ (octet & 0xF0) == 0xE0 ? octet & 0x0F :
+ (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0;
+ if (!width) return 0;
+ if (pointer+width > end) return 0;
+ for (k = 1; k < width; k ++) {
+ octet = pointer[k];
+ if ((octet & 0xC0) != 0x80) return 0;
+ value = (value << 6) + (octet & 0x3F);
+ }
+ if (!((width == 1) ||
+ (width == 2 && value >= 0x80) ||
+ (width == 3 && value >= 0x800) ||
+ (width == 4 && value >= 0x10000))) return 0;
+
+ pointer += width;
+ }
+
+ return 1;
+}
+
+/*
+ * Create STREAM-START.
+ */
+
+YAML_DECLARE(int)
+yaml_stream_start_event_initialize(yaml_event_t *event,
+ yaml_encoding_t encoding)
+{
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ assert(event); /* Non-NULL event object is expected. */
+
+ STREAM_START_EVENT_INIT(*event, encoding, mark, mark);
+
+ return 1;
+}
+
+/*
+ * Create STREAM-END.
+ */
+
+YAML_DECLARE(int)
+yaml_stream_end_event_initialize(yaml_event_t *event)
+{
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ assert(event); /* Non-NULL event object is expected. */
+
+ STREAM_END_EVENT_INIT(*event, mark, mark);
+
+ return 1;
+}
+
+/*
+ * Create DOCUMENT-START.
+ */
+
+YAML_DECLARE(int)
+yaml_document_start_event_initialize(yaml_event_t *event,
+ yaml_version_directive_t *version_directive,
+ yaml_tag_directive_t *tag_directives_start,
+ yaml_tag_directive_t *tag_directives_end,
+ int implicit)
+{
+ struct {
+ yaml_error_type_t error;
+ } context;
+ yaml_mark_t mark = { 0, 0, 0 };
+ yaml_version_directive_t *version_directive_copy = NULL;
+ struct {
+ yaml_tag_directive_t *start;
+ yaml_tag_directive_t *end;
+ yaml_tag_directive_t *top;
+ } tag_directives_copy = { NULL, NULL, NULL };
+ yaml_tag_directive_t value = { NULL, NULL };
+
+ assert(event); /* Non-NULL event object is expected. */
+ assert((tag_directives_start && tag_directives_end) ||
+ (tag_directives_start == tag_directives_end));
+ /* Valid tag directives are expected. */
+
+ if (version_directive) {
version_directive_copy = YAML_MALLOC_STATIC(yaml_version_directive_t);
- if (!version_directive_copy) goto error;
- version_directive_copy->major = version_directive->major;
- version_directive_copy->minor = version_directive->minor;
- }
-
- if (tag_directives_start != tag_directives_end) {
- yaml_tag_directive_t *tag_directive;
+ if (!version_directive_copy) goto error;
+ version_directive_copy->major = version_directive->major;
+ version_directive_copy->minor = version_directive->minor;
+ }
+
+ if (tag_directives_start != tag_directives_end) {
+ yaml_tag_directive_t *tag_directive;
if (!STACK_INIT(&context, tag_directives_copy, yaml_tag_directive_t*))
- goto error;
- for (tag_directive = tag_directives_start;
- tag_directive != tag_directives_end; tag_directive ++) {
- assert(tag_directive->handle);
- assert(tag_directive->prefix);
- if (!yaml_check_utf8(tag_directive->handle,
- strlen((char *)tag_directive->handle)))
- goto error;
- if (!yaml_check_utf8(tag_directive->prefix,
- strlen((char *)tag_directive->prefix)))
- goto error;
- value.handle = yaml_strdup(tag_directive->handle);
- value.prefix = yaml_strdup(tag_directive->prefix);
- if (!value.handle || !value.prefix) goto error;
- if (!PUSH(&context, tag_directives_copy, value))
- goto error;
- value.handle = NULL;
- value.prefix = NULL;
- }
- }
-
- DOCUMENT_START_EVENT_INIT(*event, version_directive_copy,
- tag_directives_copy.start, tag_directives_copy.top,
- implicit, mark, mark);
-
- return 1;
-
-error:
- yaml_free(version_directive_copy);
- while (!STACK_EMPTY(context, tag_directives_copy)) {
- yaml_tag_directive_t value = POP(context, tag_directives_copy);
- yaml_free(value.handle);
- yaml_free(value.prefix);
- }
- STACK_DEL(context, tag_directives_copy);
- yaml_free(value.handle);
- yaml_free(value.prefix);
-
- return 0;
-}
-
-/*
- * Create DOCUMENT-END.
- */
-
-YAML_DECLARE(int)
-yaml_document_end_event_initialize(yaml_event_t *event, int implicit)
-{
- yaml_mark_t mark = { 0, 0, 0 };
-
- assert(event); /* Non-NULL emitter object is expected. */
-
- DOCUMENT_END_EVENT_INIT(*event, implicit, mark, mark);
-
- return 1;
-}
-
-/*
- * Create ALIAS.
- */
-
-YAML_DECLARE(int)
+ goto error;
+ for (tag_directive = tag_directives_start;
+ tag_directive != tag_directives_end; tag_directive ++) {
+ assert(tag_directive->handle);
+ assert(tag_directive->prefix);
+ if (!yaml_check_utf8(tag_directive->handle,
+ strlen((char *)tag_directive->handle)))
+ goto error;
+ if (!yaml_check_utf8(tag_directive->prefix,
+ strlen((char *)tag_directive->prefix)))
+ goto error;
+ value.handle = yaml_strdup(tag_directive->handle);
+ value.prefix = yaml_strdup(tag_directive->prefix);
+ if (!value.handle || !value.prefix) goto error;
+ if (!PUSH(&context, tag_directives_copy, value))
+ goto error;
+ value.handle = NULL;
+ value.prefix = NULL;
+ }
+ }
+
+ DOCUMENT_START_EVENT_INIT(*event, version_directive_copy,
+ tag_directives_copy.start, tag_directives_copy.top,
+ implicit, mark, mark);
+
+ return 1;
+
+error:
+ yaml_free(version_directive_copy);
+ while (!STACK_EMPTY(context, tag_directives_copy)) {
+ yaml_tag_directive_t value = POP(context, tag_directives_copy);
+ yaml_free(value.handle);
+ yaml_free(value.prefix);
+ }
+ STACK_DEL(context, tag_directives_copy);
+ yaml_free(value.handle);
+ yaml_free(value.prefix);
+
+ return 0;
+}
+
+/*
+ * Create DOCUMENT-END.
+ */
+
+YAML_DECLARE(int)
+yaml_document_end_event_initialize(yaml_event_t *event, int implicit)
+{
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ assert(event); /* Non-NULL emitter object is expected. */
+
+ DOCUMENT_END_EVENT_INIT(*event, implicit, mark, mark);
+
+ return 1;
+}
+
+/*
+ * Create ALIAS.
+ */
+
+YAML_DECLARE(int)
yaml_alias_event_initialize(yaml_event_t *event, const yaml_char_t *anchor)
-{
- yaml_mark_t mark = { 0, 0, 0 };
- yaml_char_t *anchor_copy = NULL;
-
- assert(event); /* Non-NULL event object is expected. */
- assert(anchor); /* Non-NULL anchor is expected. */
-
- if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0;
-
- anchor_copy = yaml_strdup(anchor);
- if (!anchor_copy)
- return 0;
-
- ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark);
-
- return 1;
-}
-
-/*
- * Create SCALAR.
- */
-
-YAML_DECLARE(int)
-yaml_scalar_event_initialize(yaml_event_t *event,
+{
+ yaml_mark_t mark = { 0, 0, 0 };
+ yaml_char_t *anchor_copy = NULL;
+
+ assert(event); /* Non-NULL event object is expected. */
+ assert(anchor); /* Non-NULL anchor is expected. */
+
+ if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0;
+
+ anchor_copy = yaml_strdup(anchor);
+ if (!anchor_copy)
+ return 0;
+
+ ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark);
+
+ return 1;
+}
+
+/*
+ * Create SCALAR.
+ */
+
+YAML_DECLARE(int)
+yaml_scalar_event_initialize(yaml_event_t *event,
const yaml_char_t *anchor, const yaml_char_t *tag,
const yaml_char_t *value, int length,
- int plain_implicit, int quoted_implicit,
- yaml_scalar_style_t style)
-{
- yaml_mark_t mark = { 0, 0, 0 };
- yaml_char_t *anchor_copy = NULL;
- yaml_char_t *tag_copy = NULL;
- yaml_char_t *value_copy = NULL;
-
- assert(event); /* Non-NULL event object is expected. */
- assert(value); /* Non-NULL anchor is expected. */
-
- if (anchor) {
- if (!yaml_check_utf8(anchor, strlen((char *)anchor))) goto error;
- anchor_copy = yaml_strdup(anchor);
- if (!anchor_copy) goto error;
- }
-
- if (tag) {
- if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
- tag_copy = yaml_strdup(tag);
- if (!tag_copy) goto error;
- }
-
- if (length < 0) {
- length = strlen((char *)value);
- }
-
- if (!yaml_check_utf8(value, length)) goto error;
+ int plain_implicit, int quoted_implicit,
+ yaml_scalar_style_t style)
+{
+ yaml_mark_t mark = { 0, 0, 0 };
+ yaml_char_t *anchor_copy = NULL;
+ yaml_char_t *tag_copy = NULL;
+ yaml_char_t *value_copy = NULL;
+
+ assert(event); /* Non-NULL event object is expected. */
+ assert(value); /* Non-NULL anchor is expected. */
+
+ if (anchor) {
+ if (!yaml_check_utf8(anchor, strlen((char *)anchor))) goto error;
+ anchor_copy = yaml_strdup(anchor);
+ if (!anchor_copy) goto error;
+ }
+
+ if (tag) {
+ if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
+ tag_copy = yaml_strdup(tag);
+ if (!tag_copy) goto error;
+ }
+
+ if (length < 0) {
+ length = strlen((char *)value);
+ }
+
+ if (!yaml_check_utf8(value, length)) goto error;
value_copy = YAML_MALLOC(length+1);
- if (!value_copy) goto error;
- memcpy(value_copy, value, length);
- value_copy[length] = '\0';
-
- SCALAR_EVENT_INIT(*event, anchor_copy, tag_copy, value_copy, length,
- plain_implicit, quoted_implicit, style, mark, mark);
-
- return 1;
-
-error:
- yaml_free(anchor_copy);
- yaml_free(tag_copy);
- yaml_free(value_copy);
-
- return 0;
-}
-
-/*
- * Create SEQUENCE-START.
- */
-
-YAML_DECLARE(int)
-yaml_sequence_start_event_initialize(yaml_event_t *event,
+ if (!value_copy) goto error;
+ memcpy(value_copy, value, length);
+ value_copy[length] = '\0';
+
+ SCALAR_EVENT_INIT(*event, anchor_copy, tag_copy, value_copy, length,
+ plain_implicit, quoted_implicit, style, mark, mark);
+
+ return 1;
+
+error:
+ yaml_free(anchor_copy);
+ yaml_free(tag_copy);
+ yaml_free(value_copy);
+
+ return 0;
+}
+
+/*
+ * Create SEQUENCE-START.
+ */
+
+YAML_DECLARE(int)
+yaml_sequence_start_event_initialize(yaml_event_t *event,
const yaml_char_t *anchor, const yaml_char_t *tag, int implicit,
- yaml_sequence_style_t style)
-{
- yaml_mark_t mark = { 0, 0, 0 };
- yaml_char_t *anchor_copy = NULL;
- yaml_char_t *tag_copy = NULL;
-
- assert(event); /* Non-NULL event object is expected. */
-
- if (anchor) {
- if (!yaml_check_utf8(anchor, strlen((char *)anchor))) goto error;
- anchor_copy = yaml_strdup(anchor);
- if (!anchor_copy) goto error;
- }
-
- if (tag) {
- if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
- tag_copy = yaml_strdup(tag);
- if (!tag_copy) goto error;
- }
-
- SEQUENCE_START_EVENT_INIT(*event, anchor_copy, tag_copy,
- implicit, style, mark, mark);
-
- return 1;
-
-error:
- yaml_free(anchor_copy);
- yaml_free(tag_copy);
-
- return 0;
-}
-
-/*
- * Create SEQUENCE-END.
- */
-
-YAML_DECLARE(int)
-yaml_sequence_end_event_initialize(yaml_event_t *event)
-{
- yaml_mark_t mark = { 0, 0, 0 };
-
- assert(event); /* Non-NULL event object is expected. */
-
- SEQUENCE_END_EVENT_INIT(*event, mark, mark);
-
- return 1;
-}
-
-/*
- * Create MAPPING-START.
- */
-
-YAML_DECLARE(int)
-yaml_mapping_start_event_initialize(yaml_event_t *event,
+ yaml_sequence_style_t style)
+{
+ yaml_mark_t mark = { 0, 0, 0 };
+ yaml_char_t *anchor_copy = NULL;
+ yaml_char_t *tag_copy = NULL;
+
+ assert(event); /* Non-NULL event object is expected. */
+
+ if (anchor) {
+ if (!yaml_check_utf8(anchor, strlen((char *)anchor))) goto error;
+ anchor_copy = yaml_strdup(anchor);
+ if (!anchor_copy) goto error;
+ }
+
+ if (tag) {
+ if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
+ tag_copy = yaml_strdup(tag);
+ if (!tag_copy) goto error;
+ }
+
+ SEQUENCE_START_EVENT_INIT(*event, anchor_copy, tag_copy,
+ implicit, style, mark, mark);
+
+ return 1;
+
+error:
+ yaml_free(anchor_copy);
+ yaml_free(tag_copy);
+
+ return 0;
+}
+
+/*
+ * Create SEQUENCE-END.
+ */
+
+YAML_DECLARE(int)
+yaml_sequence_end_event_initialize(yaml_event_t *event)
+{
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ assert(event); /* Non-NULL event object is expected. */
+
+ SEQUENCE_END_EVENT_INIT(*event, mark, mark);
+
+ return 1;
+}
+
+/*
+ * Create MAPPING-START.
+ */
+
+YAML_DECLARE(int)
+yaml_mapping_start_event_initialize(yaml_event_t *event,
const yaml_char_t *anchor, const yaml_char_t *tag, int implicit,
- yaml_mapping_style_t style)
-{
- yaml_mark_t mark = { 0, 0, 0 };
- yaml_char_t *anchor_copy = NULL;
- yaml_char_t *tag_copy = NULL;
-
- assert(event); /* Non-NULL event object is expected. */
-
- if (anchor) {
- if (!yaml_check_utf8(anchor, strlen((char *)anchor))) goto error;
- anchor_copy = yaml_strdup(anchor);
- if (!anchor_copy) goto error;
- }
-
- if (tag) {
- if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
- tag_copy = yaml_strdup(tag);
- if (!tag_copy) goto error;
- }
-
- MAPPING_START_EVENT_INIT(*event, anchor_copy, tag_copy,
- implicit, style, mark, mark);
-
- return 1;
-
-error:
- yaml_free(anchor_copy);
- yaml_free(tag_copy);
-
- return 0;
-}
-
-/*
- * Create MAPPING-END.
- */
-
-YAML_DECLARE(int)
-yaml_mapping_end_event_initialize(yaml_event_t *event)
-{
- yaml_mark_t mark = { 0, 0, 0 };
-
- assert(event); /* Non-NULL event object is expected. */
-
- MAPPING_END_EVENT_INIT(*event, mark, mark);
-
- return 1;
-}
-
-/*
- * Destroy an event object.
- */
-
-YAML_DECLARE(void)
-yaml_event_delete(yaml_event_t *event)
-{
- yaml_tag_directive_t *tag_directive;
-
- assert(event); /* Non-NULL event object expected. */
-
- switch (event->type)
- {
- case YAML_DOCUMENT_START_EVENT:
- yaml_free(event->data.document_start.version_directive);
- for (tag_directive = event->data.document_start.tag_directives.start;
- tag_directive != event->data.document_start.tag_directives.end;
- tag_directive++) {
- yaml_free(tag_directive->handle);
- yaml_free(tag_directive->prefix);
- }
- yaml_free(event->data.document_start.tag_directives.start);
- break;
-
- case YAML_ALIAS_EVENT:
- yaml_free(event->data.alias.anchor);
- break;
-
- case YAML_SCALAR_EVENT:
- yaml_free(event->data.scalar.anchor);
- yaml_free(event->data.scalar.tag);
- yaml_free(event->data.scalar.value);
- break;
-
- case YAML_SEQUENCE_START_EVENT:
- yaml_free(event->data.sequence_start.anchor);
- yaml_free(event->data.sequence_start.tag);
- break;
-
- case YAML_MAPPING_START_EVENT:
- yaml_free(event->data.mapping_start.anchor);
- yaml_free(event->data.mapping_start.tag);
- break;
-
- default:
- break;
- }
-
- memset(event, 0, sizeof(yaml_event_t));
-}
-
-/*
- * Create a document object.
- */
-
-YAML_DECLARE(int)
-yaml_document_initialize(yaml_document_t *document,
- yaml_version_directive_t *version_directive,
- yaml_tag_directive_t *tag_directives_start,
- yaml_tag_directive_t *tag_directives_end,
- int start_implicit, int end_implicit)
-{
- struct {
- yaml_error_type_t error;
- } context;
- struct {
- yaml_node_t *start;
- yaml_node_t *end;
- yaml_node_t *top;
- } nodes = { NULL, NULL, NULL };
- yaml_version_directive_t *version_directive_copy = NULL;
- struct {
- yaml_tag_directive_t *start;
- yaml_tag_directive_t *end;
- yaml_tag_directive_t *top;
- } tag_directives_copy = { NULL, NULL, NULL };
- yaml_tag_directive_t value = { NULL, NULL };
- yaml_mark_t mark = { 0, 0, 0 };
-
- assert(document); /* Non-NULL document object is expected. */
- assert((tag_directives_start && tag_directives_end) ||
- (tag_directives_start == tag_directives_end));
- /* Valid tag directives are expected. */
-
+ yaml_mapping_style_t style)
+{
+ yaml_mark_t mark = { 0, 0, 0 };
+ yaml_char_t *anchor_copy = NULL;
+ yaml_char_t *tag_copy = NULL;
+
+ assert(event); /* Non-NULL event object is expected. */
+
+ if (anchor) {
+ if (!yaml_check_utf8(anchor, strlen((char *)anchor))) goto error;
+ anchor_copy = yaml_strdup(anchor);
+ if (!anchor_copy) goto error;
+ }
+
+ if (tag) {
+ if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
+ tag_copy = yaml_strdup(tag);
+ if (!tag_copy) goto error;
+ }
+
+ MAPPING_START_EVENT_INIT(*event, anchor_copy, tag_copy,
+ implicit, style, mark, mark);
+
+ return 1;
+
+error:
+ yaml_free(anchor_copy);
+ yaml_free(tag_copy);
+
+ return 0;
+}
+
+/*
+ * Create MAPPING-END.
+ */
+
+YAML_DECLARE(int)
+yaml_mapping_end_event_initialize(yaml_event_t *event)
+{
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ assert(event); /* Non-NULL event object is expected. */
+
+ MAPPING_END_EVENT_INIT(*event, mark, mark);
+
+ return 1;
+}
+
+/*
+ * Destroy an event object.
+ */
+
+YAML_DECLARE(void)
+yaml_event_delete(yaml_event_t *event)
+{
+ yaml_tag_directive_t *tag_directive;
+
+ assert(event); /* Non-NULL event object expected. */
+
+ switch (event->type)
+ {
+ case YAML_DOCUMENT_START_EVENT:
+ yaml_free(event->data.document_start.version_directive);
+ for (tag_directive = event->data.document_start.tag_directives.start;
+ tag_directive != event->data.document_start.tag_directives.end;
+ tag_directive++) {
+ yaml_free(tag_directive->handle);
+ yaml_free(tag_directive->prefix);
+ }
+ yaml_free(event->data.document_start.tag_directives.start);
+ break;
+
+ case YAML_ALIAS_EVENT:
+ yaml_free(event->data.alias.anchor);
+ break;
+
+ case YAML_SCALAR_EVENT:
+ yaml_free(event->data.scalar.anchor);
+ yaml_free(event->data.scalar.tag);
+ yaml_free(event->data.scalar.value);
+ break;
+
+ case YAML_SEQUENCE_START_EVENT:
+ yaml_free(event->data.sequence_start.anchor);
+ yaml_free(event->data.sequence_start.tag);
+ break;
+
+ case YAML_MAPPING_START_EVENT:
+ yaml_free(event->data.mapping_start.anchor);
+ yaml_free(event->data.mapping_start.tag);
+ break;
+
+ default:
+ break;
+ }
+
+ memset(event, 0, sizeof(yaml_event_t));
+}
+
+/*
+ * Create a document object.
+ */
+
+YAML_DECLARE(int)
+yaml_document_initialize(yaml_document_t *document,
+ yaml_version_directive_t *version_directive,
+ yaml_tag_directive_t *tag_directives_start,
+ yaml_tag_directive_t *tag_directives_end,
+ int start_implicit, int end_implicit)
+{
+ struct {
+ yaml_error_type_t error;
+ } context;
+ struct {
+ yaml_node_t *start;
+ yaml_node_t *end;
+ yaml_node_t *top;
+ } nodes = { NULL, NULL, NULL };
+ yaml_version_directive_t *version_directive_copy = NULL;
+ struct {
+ yaml_tag_directive_t *start;
+ yaml_tag_directive_t *end;
+ yaml_tag_directive_t *top;
+ } tag_directives_copy = { NULL, NULL, NULL };
+ yaml_tag_directive_t value = { NULL, NULL };
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ assert(document); /* Non-NULL document object is expected. */
+ assert((tag_directives_start && tag_directives_end) ||
+ (tag_directives_start == tag_directives_end));
+ /* Valid tag directives are expected. */
+
if (!STACK_INIT(&context, nodes, yaml_node_t*)) goto error;
-
- if (version_directive) {
+
+ if (version_directive) {
version_directive_copy = YAML_MALLOC_STATIC(yaml_version_directive_t);
- if (!version_directive_copy) goto error;
- version_directive_copy->major = version_directive->major;
- version_directive_copy->minor = version_directive->minor;
- }
-
- if (tag_directives_start != tag_directives_end) {
- yaml_tag_directive_t *tag_directive;
+ if (!version_directive_copy) goto error;
+ version_directive_copy->major = version_directive->major;
+ version_directive_copy->minor = version_directive->minor;
+ }
+
+ if (tag_directives_start != tag_directives_end) {
+ yaml_tag_directive_t *tag_directive;
if (!STACK_INIT(&context, tag_directives_copy, yaml_tag_directive_t*))
- goto error;
- for (tag_directive = tag_directives_start;
- tag_directive != tag_directives_end; tag_directive ++) {
- assert(tag_directive->handle);
- assert(tag_directive->prefix);
- if (!yaml_check_utf8(tag_directive->handle,
- strlen((char *)tag_directive->handle)))
- goto error;
- if (!yaml_check_utf8(tag_directive->prefix,
- strlen((char *)tag_directive->prefix)))
- goto error;
- value.handle = yaml_strdup(tag_directive->handle);
- value.prefix = yaml_strdup(tag_directive->prefix);
- if (!value.handle || !value.prefix) goto error;
- if (!PUSH(&context, tag_directives_copy, value))
- goto error;
- value.handle = NULL;
- value.prefix = NULL;
- }
- }
-
- DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy,
- tag_directives_copy.start, tag_directives_copy.top,
- start_implicit, end_implicit, mark, mark);
-
- return 1;
-
-error:
- STACK_DEL(&context, nodes);
- yaml_free(version_directive_copy);
- while (!STACK_EMPTY(&context, tag_directives_copy)) {
- yaml_tag_directive_t value = POP(&context, tag_directives_copy);
- yaml_free(value.handle);
- yaml_free(value.prefix);
- }
- STACK_DEL(&context, tag_directives_copy);
- yaml_free(value.handle);
- yaml_free(value.prefix);
-
- return 0;
-}
-
-/*
- * Destroy a document object.
- */
-
-YAML_DECLARE(void)
-yaml_document_delete(yaml_document_t *document)
-{
- yaml_tag_directive_t *tag_directive;
-
- assert(document); /* Non-NULL document object is expected. */
-
- while (!STACK_EMPTY(&context, document->nodes)) {
- yaml_node_t node = POP(&context, document->nodes);
- yaml_free(node.tag);
- switch (node.type) {
- case YAML_SCALAR_NODE:
- yaml_free(node.data.scalar.value);
- break;
- case YAML_SEQUENCE_NODE:
- STACK_DEL(&context, node.data.sequence.items);
- break;
- case YAML_MAPPING_NODE:
- STACK_DEL(&context, node.data.mapping.pairs);
- break;
- default:
- assert(0); /* Should not happen. */
- }
- }
- STACK_DEL(&context, document->nodes);
-
- yaml_free(document->version_directive);
- for (tag_directive = document->tag_directives.start;
- tag_directive != document->tag_directives.end;
- tag_directive++) {
- yaml_free(tag_directive->handle);
- yaml_free(tag_directive->prefix);
- }
- yaml_free(document->tag_directives.start);
-
- memset(document, 0, sizeof(yaml_document_t));
-}
-
-/**
- * Get a document node.
- */
-
-YAML_DECLARE(yaml_node_t *)
-yaml_document_get_node(yaml_document_t *document, int index)
-{
- assert(document); /* Non-NULL document object is expected. */
-
- if (index > 0 && document->nodes.start + index <= document->nodes.top) {
- return document->nodes.start + index - 1;
- }
- return NULL;
-}
-
-/**
- * Get the root object.
- */
-
-YAML_DECLARE(yaml_node_t *)
-yaml_document_get_root_node(yaml_document_t *document)
-{
- assert(document); /* Non-NULL document object is expected. */
-
- if (document->nodes.top != document->nodes.start) {
- return document->nodes.start;
- }
- return NULL;
-}
-
-/*
- * Add a scalar node to a document.
- */
-
-YAML_DECLARE(int)
-yaml_document_add_scalar(yaml_document_t *document,
+ goto error;
+ for (tag_directive = tag_directives_start;
+ tag_directive != tag_directives_end; tag_directive ++) {
+ assert(tag_directive->handle);
+ assert(tag_directive->prefix);
+ if (!yaml_check_utf8(tag_directive->handle,
+ strlen((char *)tag_directive->handle)))
+ goto error;
+ if (!yaml_check_utf8(tag_directive->prefix,
+ strlen((char *)tag_directive->prefix)))
+ goto error;
+ value.handle = yaml_strdup(tag_directive->handle);
+ value.prefix = yaml_strdup(tag_directive->prefix);
+ if (!value.handle || !value.prefix) goto error;
+ if (!PUSH(&context, tag_directives_copy, value))
+ goto error;
+ value.handle = NULL;
+ value.prefix = NULL;
+ }
+ }
+
+ DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy,
+ tag_directives_copy.start, tag_directives_copy.top,
+ start_implicit, end_implicit, mark, mark);
+
+ return 1;
+
+error:
+ STACK_DEL(&context, nodes);
+ yaml_free(version_directive_copy);
+ while (!STACK_EMPTY(&context, tag_directives_copy)) {
+ yaml_tag_directive_t value = POP(&context, tag_directives_copy);
+ yaml_free(value.handle);
+ yaml_free(value.prefix);
+ }
+ STACK_DEL(&context, tag_directives_copy);
+ yaml_free(value.handle);
+ yaml_free(value.prefix);
+
+ return 0;
+}
+
+/*
+ * Destroy a document object.
+ */
+
+YAML_DECLARE(void)
+yaml_document_delete(yaml_document_t *document)
+{
+ yaml_tag_directive_t *tag_directive;
+
+ assert(document); /* Non-NULL document object is expected. */
+
+ while (!STACK_EMPTY(&context, document->nodes)) {
+ yaml_node_t node = POP(&context, document->nodes);
+ yaml_free(node.tag);
+ switch (node.type) {
+ case YAML_SCALAR_NODE:
+ yaml_free(node.data.scalar.value);
+ break;
+ case YAML_SEQUENCE_NODE:
+ STACK_DEL(&context, node.data.sequence.items);
+ break;
+ case YAML_MAPPING_NODE:
+ STACK_DEL(&context, node.data.mapping.pairs);
+ break;
+ default:
+ assert(0); /* Should not happen. */
+ }
+ }
+ STACK_DEL(&context, document->nodes);
+
+ yaml_free(document->version_directive);
+ for (tag_directive = document->tag_directives.start;
+ tag_directive != document->tag_directives.end;
+ tag_directive++) {
+ yaml_free(tag_directive->handle);
+ yaml_free(tag_directive->prefix);
+ }
+ yaml_free(document->tag_directives.start);
+
+ memset(document, 0, sizeof(yaml_document_t));
+}
+
+/**
+ * Get a document node.
+ */
+
+YAML_DECLARE(yaml_node_t *)
+yaml_document_get_node(yaml_document_t *document, int index)
+{
+ assert(document); /* Non-NULL document object is expected. */
+
+ if (index > 0 && document->nodes.start + index <= document->nodes.top) {
+ return document->nodes.start + index - 1;
+ }
+ return NULL;
+}
+
+/**
+ * Get the root object.
+ */
+
+YAML_DECLARE(yaml_node_t *)
+yaml_document_get_root_node(yaml_document_t *document)
+{
+ assert(document); /* Non-NULL document object is expected. */
+
+ if (document->nodes.top != document->nodes.start) {
+ return document->nodes.start;
+ }
+ return NULL;
+}
+
+/*
+ * Add a scalar node to a document.
+ */
+
+YAML_DECLARE(int)
+yaml_document_add_scalar(yaml_document_t *document,
const yaml_char_t *tag, const yaml_char_t *value, int length,
- yaml_scalar_style_t style)
-{
- struct {
- yaml_error_type_t error;
- } context;
- yaml_mark_t mark = { 0, 0, 0 };
- yaml_char_t *tag_copy = NULL;
- yaml_char_t *value_copy = NULL;
- yaml_node_t node;
-
- assert(document); /* Non-NULL document object is expected. */
- assert(value); /* Non-NULL value is expected. */
-
- if (!tag) {
- tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG;
- }
-
- if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
- tag_copy = yaml_strdup(tag);
- if (!tag_copy) goto error;
-
- if (length < 0) {
- length = strlen((char *)value);
- }
-
- if (!yaml_check_utf8(value, length)) goto error;
+ yaml_scalar_style_t style)
+{
+ struct {
+ yaml_error_type_t error;
+ } context;
+ yaml_mark_t mark = { 0, 0, 0 };
+ yaml_char_t *tag_copy = NULL;
+ yaml_char_t *value_copy = NULL;
+ yaml_node_t node;
+
+ assert(document); /* Non-NULL document object is expected. */
+ assert(value); /* Non-NULL value is expected. */
+
+ if (!tag) {
+ tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG;
+ }
+
+ if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
+ tag_copy = yaml_strdup(tag);
+ if (!tag_copy) goto error;
+
+ if (length < 0) {
+ length = strlen((char *)value);
+ }
+
+ if (!yaml_check_utf8(value, length)) goto error;
value_copy = YAML_MALLOC(length+1);
- if (!value_copy) goto error;
- memcpy(value_copy, value, length);
- value_copy[length] = '\0';
-
- SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark);
- if (!PUSH(&context, document->nodes, node)) goto error;
-
- return document->nodes.top - document->nodes.start;
-
-error:
- yaml_free(tag_copy);
- yaml_free(value_copy);
-
- return 0;
-}
-
-/*
- * Add a sequence node to a document.
- */
-
-YAML_DECLARE(int)
-yaml_document_add_sequence(yaml_document_t *document,
+ if (!value_copy) goto error;
+ memcpy(value_copy, value, length);
+ value_copy[length] = '\0';
+
+ SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark);
+ if (!PUSH(&context, document->nodes, node)) goto error;
+
+ return document->nodes.top - document->nodes.start;
+
+error:
+ yaml_free(tag_copy);
+ yaml_free(value_copy);
+
+ return 0;
+}
+
+/*
+ * Add a sequence node to a document.
+ */
+
+YAML_DECLARE(int)
+yaml_document_add_sequence(yaml_document_t *document,
const yaml_char_t *tag, yaml_sequence_style_t style)
-{
- struct {
- yaml_error_type_t error;
- } context;
- yaml_mark_t mark = { 0, 0, 0 };
- yaml_char_t *tag_copy = NULL;
- struct {
- yaml_node_item_t *start;
- yaml_node_item_t *end;
- yaml_node_item_t *top;
- } items = { NULL, NULL, NULL };
- yaml_node_t node;
-
- assert(document); /* Non-NULL document object is expected. */
-
- if (!tag) {
- tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG;
- }
-
- if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
- tag_copy = yaml_strdup(tag);
- if (!tag_copy) goto error;
-
+{
+ struct {
+ yaml_error_type_t error;
+ } context;
+ yaml_mark_t mark = { 0, 0, 0 };
+ yaml_char_t *tag_copy = NULL;
+ struct {
+ yaml_node_item_t *start;
+ yaml_node_item_t *end;
+ yaml_node_item_t *top;
+ } items = { NULL, NULL, NULL };
+ yaml_node_t node;
+
+ assert(document); /* Non-NULL document object is expected. */
+
+ if (!tag) {
+ tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG;
+ }
+
+ if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
+ tag_copy = yaml_strdup(tag);
+ if (!tag_copy) goto error;
+
if (!STACK_INIT(&context, items, yaml_node_item_t*)) goto error;
-
- SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end,
- style, mark, mark);
- if (!PUSH(&context, document->nodes, node)) goto error;
-
- return document->nodes.top - document->nodes.start;
-
-error:
- STACK_DEL(&context, items);
- yaml_free(tag_copy);
-
- return 0;
-}
-
-/*
- * Add a mapping node to a document.
- */
-
-YAML_DECLARE(int)
-yaml_document_add_mapping(yaml_document_t *document,
+
+ SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end,
+ style, mark, mark);
+ if (!PUSH(&context, document->nodes, node)) goto error;
+
+ return document->nodes.top - document->nodes.start;
+
+error:
+ STACK_DEL(&context, items);
+ yaml_free(tag_copy);
+
+ return 0;
+}
+
+/*
+ * Add a mapping node to a document.
+ */
+
+YAML_DECLARE(int)
+yaml_document_add_mapping(yaml_document_t *document,
const yaml_char_t *tag, yaml_mapping_style_t style)
-{
- struct {
- yaml_error_type_t error;
- } context;
- yaml_mark_t mark = { 0, 0, 0 };
- yaml_char_t *tag_copy = NULL;
- struct {
- yaml_node_pair_t *start;
- yaml_node_pair_t *end;
- yaml_node_pair_t *top;
- } pairs = { NULL, NULL, NULL };
- yaml_node_t node;
-
- assert(document); /* Non-NULL document object is expected. */
-
- if (!tag) {
- tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG;
- }
-
- if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
- tag_copy = yaml_strdup(tag);
- if (!tag_copy) goto error;
-
+{
+ struct {
+ yaml_error_type_t error;
+ } context;
+ yaml_mark_t mark = { 0, 0, 0 };
+ yaml_char_t *tag_copy = NULL;
+ struct {
+ yaml_node_pair_t *start;
+ yaml_node_pair_t *end;
+ yaml_node_pair_t *top;
+ } pairs = { NULL, NULL, NULL };
+ yaml_node_t node;
+
+ assert(document); /* Non-NULL document object is expected. */
+
+ if (!tag) {
+ tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG;
+ }
+
+ if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error;
+ tag_copy = yaml_strdup(tag);
+ if (!tag_copy) goto error;
+
if (!STACK_INIT(&context, pairs, yaml_node_pair_t*)) goto error;
-
- MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end,
- style, mark, mark);
- if (!PUSH(&context, document->nodes, node)) goto error;
-
- return document->nodes.top - document->nodes.start;
-
-error:
- STACK_DEL(&context, pairs);
- yaml_free(tag_copy);
-
- return 0;
-}
-
-/*
- * Append an item to a sequence node.
- */
-
-YAML_DECLARE(int)
-yaml_document_append_sequence_item(yaml_document_t *document,
- int sequence, int item)
-{
- struct {
- yaml_error_type_t error;
- } context;
-
- assert(document); /* Non-NULL document is required. */
- assert(sequence > 0
- && document->nodes.start + sequence <= document->nodes.top);
- /* Valid sequence id is required. */
- assert(document->nodes.start[sequence-1].type == YAML_SEQUENCE_NODE);
- /* A sequence node is required. */
- assert(item > 0 && document->nodes.start + item <= document->nodes.top);
- /* Valid item id is required. */
-
- if (!PUSH(&context,
- document->nodes.start[sequence-1].data.sequence.items, item))
- return 0;
-
- return 1;
-}
-
-/*
- * Append a pair of a key and a value to a mapping node.
- */
-
-YAML_DECLARE(int)
-yaml_document_append_mapping_pair(yaml_document_t *document,
- int mapping, int key, int value)
-{
- struct {
- yaml_error_type_t error;
- } context;
-
- yaml_node_pair_t pair;
-
- assert(document); /* Non-NULL document is required. */
- assert(mapping > 0
- && document->nodes.start + mapping <= document->nodes.top);
- /* Valid mapping id is required. */
- assert(document->nodes.start[mapping-1].type == YAML_MAPPING_NODE);
- /* A mapping node is required. */
- assert(key > 0 && document->nodes.start + key <= document->nodes.top);
- /* Valid key id is required. */
- assert(value > 0 && document->nodes.start + value <= document->nodes.top);
- /* Valid value id is required. */
-
- pair.key = key;
- pair.value = value;
-
- if (!PUSH(&context,
- document->nodes.start[mapping-1].data.mapping.pairs, pair))
- return 0;
-
- return 1;
-}
-
-
+
+ MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end,
+ style, mark, mark);
+ if (!PUSH(&context, document->nodes, node)) goto error;
+
+ return document->nodes.top - document->nodes.start;
+
+error:
+ STACK_DEL(&context, pairs);
+ yaml_free(tag_copy);
+
+ return 0;
+}
+
+/*
+ * Append an item to a sequence node.
+ */
+
+YAML_DECLARE(int)
+yaml_document_append_sequence_item(yaml_document_t *document,
+ int sequence, int item)
+{
+ struct {
+ yaml_error_type_t error;
+ } context;
+
+ assert(document); /* Non-NULL document is required. */
+ assert(sequence > 0
+ && document->nodes.start + sequence <= document->nodes.top);
+ /* Valid sequence id is required. */
+ assert(document->nodes.start[sequence-1].type == YAML_SEQUENCE_NODE);
+ /* A sequence node is required. */
+ assert(item > 0 && document->nodes.start + item <= document->nodes.top);
+ /* Valid item id is required. */
+
+ if (!PUSH(&context,
+ document->nodes.start[sequence-1].data.sequence.items, item))
+ return 0;
+
+ return 1;
+}
+
+/*
+ * Append a pair of a key and a value to a mapping node.
+ */
+
+YAML_DECLARE(int)
+yaml_document_append_mapping_pair(yaml_document_t *document,
+ int mapping, int key, int value)
+{
+ struct {
+ yaml_error_type_t error;
+ } context;
+
+ yaml_node_pair_t pair;
+
+ assert(document); /* Non-NULL document is required. */
+ assert(mapping > 0
+ && document->nodes.start + mapping <= document->nodes.top);
+ /* Valid mapping id is required. */
+ assert(document->nodes.start[mapping-1].type == YAML_MAPPING_NODE);
+ /* A mapping node is required. */
+ assert(key > 0 && document->nodes.start + key <= document->nodes.top);
+ /* Valid key id is required. */
+ assert(value > 0 && document->nodes.start + value <= document->nodes.top);
+ /* Valid value id is required. */
+
+ pair.key = key;
+ pair.value = value;
+
+ if (!PUSH(&context,
+ document->nodes.start[mapping-1].data.mapping.pairs, pair))
+ return 0;
+
+ return 1;
+}
+
+
diff --git a/contrib/libs/yaml/src/config.h b/contrib/libs/yaml/src/config.h
index 4ce4fd0a20..22a2296e5e 100644
--- a/contrib/libs/yaml/src/config.h
+++ b/contrib/libs/yaml/src/config.h
@@ -64,7 +64,7 @@
#define VERSION "0.2.5"
/* Define the major version number. */
-#define YAML_VERSION_MAJOR 0
+#define YAML_VERSION_MAJOR 0
/* Define the minor version number. */
#define YAML_VERSION_MINOR 2
diff --git a/contrib/libs/yaml/src/dumper.c b/contrib/libs/yaml/src/dumper.c
index 292d2cff12..1fe940b674 100644
--- a/contrib/libs/yaml/src/dumper.c
+++ b/contrib/libs/yaml/src/dumper.c
@@ -1,394 +1,394 @@
-
-#include "yaml_private.h"
-
-/*
- * API functions.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_open(yaml_emitter_t *emitter);
-
-YAML_DECLARE(int)
-yaml_emitter_close(yaml_emitter_t *emitter);
-
-YAML_DECLARE(int)
-yaml_emitter_dump(yaml_emitter_t *emitter, yaml_document_t *document);
-
-/*
- * Clean up functions.
- */
-
-static void
-yaml_emitter_delete_document_and_anchors(yaml_emitter_t *emitter);
-
-/*
- * Anchor functions.
- */
-
-static void
-yaml_emitter_anchor_node(yaml_emitter_t *emitter, int index);
-
-static yaml_char_t *
-yaml_emitter_generate_anchor(yaml_emitter_t *emitter, int anchor_id);
-
-
-/*
- * Serialize functions.
- */
-
-static int
-yaml_emitter_dump_node(yaml_emitter_t *emitter, int index);
-
-static int
-yaml_emitter_dump_alias(yaml_emitter_t *emitter, yaml_char_t *anchor);
-
-static int
-yaml_emitter_dump_scalar(yaml_emitter_t *emitter, yaml_node_t *node,
- yaml_char_t *anchor);
-
-static int
-yaml_emitter_dump_sequence(yaml_emitter_t *emitter, yaml_node_t *node,
- yaml_char_t *anchor);
-
-static int
-yaml_emitter_dump_mapping(yaml_emitter_t *emitter, yaml_node_t *node,
- yaml_char_t *anchor);
-
-/*
- * Issue a STREAM-START event.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_open(yaml_emitter_t *emitter)
-{
- yaml_event_t event;
- yaml_mark_t mark = { 0, 0, 0 };
-
- assert(emitter); /* Non-NULL emitter object is required. */
- assert(!emitter->opened); /* Emitter should not be opened yet. */
-
- STREAM_START_EVENT_INIT(event, YAML_ANY_ENCODING, mark, mark);
-
- if (!yaml_emitter_emit(emitter, &event)) {
- return 0;
- }
-
- emitter->opened = 1;
-
- return 1;
-}
-
-/*
- * Issue a STREAM-END event.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_close(yaml_emitter_t *emitter)
-{
- yaml_event_t event;
- yaml_mark_t mark = { 0, 0, 0 };
-
- assert(emitter); /* Non-NULL emitter object is required. */
- assert(emitter->opened); /* Emitter should be opened. */
-
- if (emitter->closed) return 1;
-
- STREAM_END_EVENT_INIT(event, mark, mark);
-
- if (!yaml_emitter_emit(emitter, &event)) {
- return 0;
- }
-
- emitter->closed = 1;
-
- return 1;
-}
-
-/*
- * Dump a YAML document.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_dump(yaml_emitter_t *emitter, yaml_document_t *document)
-{
- yaml_event_t event;
- yaml_mark_t mark = { 0, 0, 0 };
-
- assert(emitter); /* Non-NULL emitter object is required. */
- assert(document); /* Non-NULL emitter object is expected. */
-
- emitter->document = document;
-
- if (!emitter->opened) {
- if (!yaml_emitter_open(emitter)) goto error;
- }
-
- if (STACK_EMPTY(emitter, document->nodes)) {
- if (!yaml_emitter_close(emitter)) goto error;
- yaml_emitter_delete_document_and_anchors(emitter);
- return 1;
- }
-
- assert(emitter->opened); /* Emitter should be opened. */
-
+
+#include "yaml_private.h"
+
+/*
+ * API functions.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_open(yaml_emitter_t *emitter);
+
+YAML_DECLARE(int)
+yaml_emitter_close(yaml_emitter_t *emitter);
+
+YAML_DECLARE(int)
+yaml_emitter_dump(yaml_emitter_t *emitter, yaml_document_t *document);
+
+/*
+ * Clean up functions.
+ */
+
+static void
+yaml_emitter_delete_document_and_anchors(yaml_emitter_t *emitter);
+
+/*
+ * Anchor functions.
+ */
+
+static void
+yaml_emitter_anchor_node(yaml_emitter_t *emitter, int index);
+
+static yaml_char_t *
+yaml_emitter_generate_anchor(yaml_emitter_t *emitter, int anchor_id);
+
+
+/*
+ * Serialize functions.
+ */
+
+static int
+yaml_emitter_dump_node(yaml_emitter_t *emitter, int index);
+
+static int
+yaml_emitter_dump_alias(yaml_emitter_t *emitter, yaml_char_t *anchor);
+
+static int
+yaml_emitter_dump_scalar(yaml_emitter_t *emitter, yaml_node_t *node,
+ yaml_char_t *anchor);
+
+static int
+yaml_emitter_dump_sequence(yaml_emitter_t *emitter, yaml_node_t *node,
+ yaml_char_t *anchor);
+
+static int
+yaml_emitter_dump_mapping(yaml_emitter_t *emitter, yaml_node_t *node,
+ yaml_char_t *anchor);
+
+/*
+ * Issue a STREAM-START event.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_open(yaml_emitter_t *emitter)
+{
+ yaml_event_t event;
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ assert(emitter); /* Non-NULL emitter object is required. */
+ assert(!emitter->opened); /* Emitter should not be opened yet. */
+
+ STREAM_START_EVENT_INIT(event, YAML_ANY_ENCODING, mark, mark);
+
+ if (!yaml_emitter_emit(emitter, &event)) {
+ return 0;
+ }
+
+ emitter->opened = 1;
+
+ return 1;
+}
+
+/*
+ * Issue a STREAM-END event.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_close(yaml_emitter_t *emitter)
+{
+ yaml_event_t event;
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ assert(emitter); /* Non-NULL emitter object is required. */
+ assert(emitter->opened); /* Emitter should be opened. */
+
+ if (emitter->closed) return 1;
+
+ STREAM_END_EVENT_INIT(event, mark, mark);
+
+ if (!yaml_emitter_emit(emitter, &event)) {
+ return 0;
+ }
+
+ emitter->closed = 1;
+
+ return 1;
+}
+
+/*
+ * Dump a YAML document.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_dump(yaml_emitter_t *emitter, yaml_document_t *document)
+{
+ yaml_event_t event;
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ assert(emitter); /* Non-NULL emitter object is required. */
+ assert(document); /* Non-NULL emitter object is expected. */
+
+ emitter->document = document;
+
+ if (!emitter->opened) {
+ if (!yaml_emitter_open(emitter)) goto error;
+ }
+
+ if (STACK_EMPTY(emitter, document->nodes)) {
+ if (!yaml_emitter_close(emitter)) goto error;
+ yaml_emitter_delete_document_and_anchors(emitter);
+ return 1;
+ }
+
+ assert(emitter->opened); /* Emitter should be opened. */
+
emitter->anchors = (yaml_anchors_t*)yaml_malloc(sizeof(*(emitter->anchors))
- * (document->nodes.top - document->nodes.start));
- if (!emitter->anchors) goto error;
- memset(emitter->anchors, 0, sizeof(*(emitter->anchors))
- * (document->nodes.top - document->nodes.start));
-
- DOCUMENT_START_EVENT_INIT(event, document->version_directive,
- document->tag_directives.start, document->tag_directives.end,
- document->start_implicit, mark, mark);
- if (!yaml_emitter_emit(emitter, &event)) goto error;
-
- yaml_emitter_anchor_node(emitter, 1);
- if (!yaml_emitter_dump_node(emitter, 1)) goto error;
-
- DOCUMENT_END_EVENT_INIT(event, document->end_implicit, mark, mark);
- if (!yaml_emitter_emit(emitter, &event)) goto error;
-
- yaml_emitter_delete_document_and_anchors(emitter);
-
- return 1;
-
-error:
-
- yaml_emitter_delete_document_and_anchors(emitter);
-
- return 0;
-}
-
-/*
- * Clean up the emitter object after a document is dumped.
- */
-
-static void
-yaml_emitter_delete_document_and_anchors(yaml_emitter_t *emitter)
-{
- int index;
-
- if (!emitter->anchors) {
- yaml_document_delete(emitter->document);
- emitter->document = NULL;
- return;
- }
-
- for (index = 0; emitter->document->nodes.start + index
- < emitter->document->nodes.top; index ++) {
- yaml_node_t node = emitter->document->nodes.start[index];
- if (!emitter->anchors[index].serialized) {
- yaml_free(node.tag);
- if (node.type == YAML_SCALAR_NODE) {
- yaml_free(node.data.scalar.value);
- }
- }
- if (node.type == YAML_SEQUENCE_NODE) {
- STACK_DEL(emitter, node.data.sequence.items);
- }
- if (node.type == YAML_MAPPING_NODE) {
- STACK_DEL(emitter, node.data.mapping.pairs);
- }
- }
-
- STACK_DEL(emitter, emitter->document->nodes);
- yaml_free(emitter->anchors);
-
- emitter->anchors = NULL;
- emitter->last_anchor_id = 0;
- emitter->document = NULL;
-}
-
-/*
- * Check the references of a node and assign the anchor id if needed.
- */
-
-static void
-yaml_emitter_anchor_node(yaml_emitter_t *emitter, int index)
-{
- yaml_node_t *node = emitter->document->nodes.start + index - 1;
- yaml_node_item_t *item;
- yaml_node_pair_t *pair;
-
- emitter->anchors[index-1].references ++;
-
- if (emitter->anchors[index-1].references == 1) {
- switch (node->type) {
- case YAML_SEQUENCE_NODE:
- for (item = node->data.sequence.items.start;
- item < node->data.sequence.items.top; item ++) {
- yaml_emitter_anchor_node(emitter, *item);
- }
- break;
- case YAML_MAPPING_NODE:
- for (pair = node->data.mapping.pairs.start;
- pair < node->data.mapping.pairs.top; pair ++) {
- yaml_emitter_anchor_node(emitter, pair->key);
- yaml_emitter_anchor_node(emitter, pair->value);
- }
- break;
- default:
- break;
- }
- }
-
- else if (emitter->anchors[index-1].references == 2) {
- emitter->anchors[index-1].anchor = (++ emitter->last_anchor_id);
- }
-}
-
-/*
- * Generate a textual representation for an anchor.
- */
-
-#define ANCHOR_TEMPLATE "id%03d"
-#define ANCHOR_TEMPLATE_LENGTH 16
-
-static yaml_char_t *
+ * (document->nodes.top - document->nodes.start));
+ if (!emitter->anchors) goto error;
+ memset(emitter->anchors, 0, sizeof(*(emitter->anchors))
+ * (document->nodes.top - document->nodes.start));
+
+ DOCUMENT_START_EVENT_INIT(event, document->version_directive,
+ document->tag_directives.start, document->tag_directives.end,
+ document->start_implicit, mark, mark);
+ if (!yaml_emitter_emit(emitter, &event)) goto error;
+
+ yaml_emitter_anchor_node(emitter, 1);
+ if (!yaml_emitter_dump_node(emitter, 1)) goto error;
+
+ DOCUMENT_END_EVENT_INIT(event, document->end_implicit, mark, mark);
+ if (!yaml_emitter_emit(emitter, &event)) goto error;
+
+ yaml_emitter_delete_document_and_anchors(emitter);
+
+ return 1;
+
+error:
+
+ yaml_emitter_delete_document_and_anchors(emitter);
+
+ return 0;
+}
+
+/*
+ * Clean up the emitter object after a document is dumped.
+ */
+
+static void
+yaml_emitter_delete_document_and_anchors(yaml_emitter_t *emitter)
+{
+ int index;
+
+ if (!emitter->anchors) {
+ yaml_document_delete(emitter->document);
+ emitter->document = NULL;
+ return;
+ }
+
+ for (index = 0; emitter->document->nodes.start + index
+ < emitter->document->nodes.top; index ++) {
+ yaml_node_t node = emitter->document->nodes.start[index];
+ if (!emitter->anchors[index].serialized) {
+ yaml_free(node.tag);
+ if (node.type == YAML_SCALAR_NODE) {
+ yaml_free(node.data.scalar.value);
+ }
+ }
+ if (node.type == YAML_SEQUENCE_NODE) {
+ STACK_DEL(emitter, node.data.sequence.items);
+ }
+ if (node.type == YAML_MAPPING_NODE) {
+ STACK_DEL(emitter, node.data.mapping.pairs);
+ }
+ }
+
+ STACK_DEL(emitter, emitter->document->nodes);
+ yaml_free(emitter->anchors);
+
+ emitter->anchors = NULL;
+ emitter->last_anchor_id = 0;
+ emitter->document = NULL;
+}
+
+/*
+ * Check the references of a node and assign the anchor id if needed.
+ */
+
+static void
+yaml_emitter_anchor_node(yaml_emitter_t *emitter, int index)
+{
+ yaml_node_t *node = emitter->document->nodes.start + index - 1;
+ yaml_node_item_t *item;
+ yaml_node_pair_t *pair;
+
+ emitter->anchors[index-1].references ++;
+
+ if (emitter->anchors[index-1].references == 1) {
+ switch (node->type) {
+ case YAML_SEQUENCE_NODE:
+ for (item = node->data.sequence.items.start;
+ item < node->data.sequence.items.top; item ++) {
+ yaml_emitter_anchor_node(emitter, *item);
+ }
+ break;
+ case YAML_MAPPING_NODE:
+ for (pair = node->data.mapping.pairs.start;
+ pair < node->data.mapping.pairs.top; pair ++) {
+ yaml_emitter_anchor_node(emitter, pair->key);
+ yaml_emitter_anchor_node(emitter, pair->value);
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ else if (emitter->anchors[index-1].references == 2) {
+ emitter->anchors[index-1].anchor = (++ emitter->last_anchor_id);
+ }
+}
+
+/*
+ * Generate a textual representation for an anchor.
+ */
+
+#define ANCHOR_TEMPLATE "id%03d"
+#define ANCHOR_TEMPLATE_LENGTH 16
+
+static yaml_char_t *
yaml_emitter_generate_anchor(SHIM(yaml_emitter_t *emitter), int anchor_id)
-{
+{
yaml_char_t *anchor = YAML_MALLOC(ANCHOR_TEMPLATE_LENGTH);
-
- if (!anchor) return NULL;
-
- sprintf((char *)anchor, ANCHOR_TEMPLATE, anchor_id);
-
- return anchor;
-}
-
-/*
- * Serialize a node.
- */
-
-static int
-yaml_emitter_dump_node(yaml_emitter_t *emitter, int index)
-{
- yaml_node_t *node = emitter->document->nodes.start + index - 1;
- int anchor_id = emitter->anchors[index-1].anchor;
- yaml_char_t *anchor = NULL;
-
- if (anchor_id) {
- anchor = yaml_emitter_generate_anchor(emitter, anchor_id);
- if (!anchor) return 0;
- }
-
- if (emitter->anchors[index-1].serialized) {
- return yaml_emitter_dump_alias(emitter, anchor);
- }
-
- emitter->anchors[index-1].serialized = 1;
-
- switch (node->type) {
- case YAML_SCALAR_NODE:
- return yaml_emitter_dump_scalar(emitter, node, anchor);
- case YAML_SEQUENCE_NODE:
- return yaml_emitter_dump_sequence(emitter, node, anchor);
- case YAML_MAPPING_NODE:
- return yaml_emitter_dump_mapping(emitter, node, anchor);
- default:
- assert(0); /* Could not happen. */
- break;
- }
-
- return 0; /* Could not happen. */
-}
-
-/*
- * Serialize an alias.
- */
-
-static int
-yaml_emitter_dump_alias(yaml_emitter_t *emitter, yaml_char_t *anchor)
-{
- yaml_event_t event;
- yaml_mark_t mark = { 0, 0, 0 };
-
- ALIAS_EVENT_INIT(event, anchor, mark, mark);
-
- return yaml_emitter_emit(emitter, &event);
-}
-
-/*
- * Serialize a scalar.
- */
-
-static int
-yaml_emitter_dump_scalar(yaml_emitter_t *emitter, yaml_node_t *node,
- yaml_char_t *anchor)
-{
- yaml_event_t event;
- yaml_mark_t mark = { 0, 0, 0 };
-
- int plain_implicit = (strcmp((char *)node->tag,
- YAML_DEFAULT_SCALAR_TAG) == 0);
- int quoted_implicit = (strcmp((char *)node->tag,
- YAML_DEFAULT_SCALAR_TAG) == 0);
-
- SCALAR_EVENT_INIT(event, anchor, node->tag, node->data.scalar.value,
- node->data.scalar.length, plain_implicit, quoted_implicit,
- node->data.scalar.style, mark, mark);
-
- return yaml_emitter_emit(emitter, &event);
-}
-
-/*
- * Serialize a sequence.
- */
-
-static int
-yaml_emitter_dump_sequence(yaml_emitter_t *emitter, yaml_node_t *node,
- yaml_char_t *anchor)
-{
- yaml_event_t event;
- yaml_mark_t mark = { 0, 0, 0 };
-
- int implicit = (strcmp((char *)node->tag, YAML_DEFAULT_SEQUENCE_TAG) == 0);
-
- yaml_node_item_t *item;
-
- SEQUENCE_START_EVENT_INIT(event, anchor, node->tag, implicit,
- node->data.sequence.style, mark, mark);
- if (!yaml_emitter_emit(emitter, &event)) return 0;
-
- for (item = node->data.sequence.items.start;
- item < node->data.sequence.items.top; item ++) {
- if (!yaml_emitter_dump_node(emitter, *item)) return 0;
- }
-
- SEQUENCE_END_EVENT_INIT(event, mark, mark);
- if (!yaml_emitter_emit(emitter, &event)) return 0;
-
- return 1;
-}
-
-/*
- * Serialize a mapping.
- */
-
-static int
-yaml_emitter_dump_mapping(yaml_emitter_t *emitter, yaml_node_t *node,
- yaml_char_t *anchor)
-{
- yaml_event_t event;
- yaml_mark_t mark = { 0, 0, 0 };
-
- int implicit = (strcmp((char *)node->tag, YAML_DEFAULT_MAPPING_TAG) == 0);
-
- yaml_node_pair_t *pair;
-
- MAPPING_START_EVENT_INIT(event, anchor, node->tag, implicit,
- node->data.mapping.style, mark, mark);
- if (!yaml_emitter_emit(emitter, &event)) return 0;
-
- for (pair = node->data.mapping.pairs.start;
- pair < node->data.mapping.pairs.top; pair ++) {
- if (!yaml_emitter_dump_node(emitter, pair->key)) return 0;
- if (!yaml_emitter_dump_node(emitter, pair->value)) return 0;
- }
-
- MAPPING_END_EVENT_INIT(event, mark, mark);
- if (!yaml_emitter_emit(emitter, &event)) return 0;
-
- return 1;
-}
-
+
+ if (!anchor) return NULL;
+
+ sprintf((char *)anchor, ANCHOR_TEMPLATE, anchor_id);
+
+ return anchor;
+}
+
+/*
+ * Serialize a node.
+ */
+
+static int
+yaml_emitter_dump_node(yaml_emitter_t *emitter, int index)
+{
+ yaml_node_t *node = emitter->document->nodes.start + index - 1;
+ int anchor_id = emitter->anchors[index-1].anchor;
+ yaml_char_t *anchor = NULL;
+
+ if (anchor_id) {
+ anchor = yaml_emitter_generate_anchor(emitter, anchor_id);
+ if (!anchor) return 0;
+ }
+
+ if (emitter->anchors[index-1].serialized) {
+ return yaml_emitter_dump_alias(emitter, anchor);
+ }
+
+ emitter->anchors[index-1].serialized = 1;
+
+ switch (node->type) {
+ case YAML_SCALAR_NODE:
+ return yaml_emitter_dump_scalar(emitter, node, anchor);
+ case YAML_SEQUENCE_NODE:
+ return yaml_emitter_dump_sequence(emitter, node, anchor);
+ case YAML_MAPPING_NODE:
+ return yaml_emitter_dump_mapping(emitter, node, anchor);
+ default:
+ assert(0); /* Could not happen. */
+ break;
+ }
+
+ return 0; /* Could not happen. */
+}
+
+/*
+ * Serialize an alias.
+ */
+
+static int
+yaml_emitter_dump_alias(yaml_emitter_t *emitter, yaml_char_t *anchor)
+{
+ yaml_event_t event;
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ ALIAS_EVENT_INIT(event, anchor, mark, mark);
+
+ return yaml_emitter_emit(emitter, &event);
+}
+
+/*
+ * Serialize a scalar.
+ */
+
+static int
+yaml_emitter_dump_scalar(yaml_emitter_t *emitter, yaml_node_t *node,
+ yaml_char_t *anchor)
+{
+ yaml_event_t event;
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ int plain_implicit = (strcmp((char *)node->tag,
+ YAML_DEFAULT_SCALAR_TAG) == 0);
+ int quoted_implicit = (strcmp((char *)node->tag,
+ YAML_DEFAULT_SCALAR_TAG) == 0);
+
+ SCALAR_EVENT_INIT(event, anchor, node->tag, node->data.scalar.value,
+ node->data.scalar.length, plain_implicit, quoted_implicit,
+ node->data.scalar.style, mark, mark);
+
+ return yaml_emitter_emit(emitter, &event);
+}
+
+/*
+ * Serialize a sequence.
+ */
+
+static int
+yaml_emitter_dump_sequence(yaml_emitter_t *emitter, yaml_node_t *node,
+ yaml_char_t *anchor)
+{
+ yaml_event_t event;
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ int implicit = (strcmp((char *)node->tag, YAML_DEFAULT_SEQUENCE_TAG) == 0);
+
+ yaml_node_item_t *item;
+
+ SEQUENCE_START_EVENT_INIT(event, anchor, node->tag, implicit,
+ node->data.sequence.style, mark, mark);
+ if (!yaml_emitter_emit(emitter, &event)) return 0;
+
+ for (item = node->data.sequence.items.start;
+ item < node->data.sequence.items.top; item ++) {
+ if (!yaml_emitter_dump_node(emitter, *item)) return 0;
+ }
+
+ SEQUENCE_END_EVENT_INIT(event, mark, mark);
+ if (!yaml_emitter_emit(emitter, &event)) return 0;
+
+ return 1;
+}
+
+/*
+ * Serialize a mapping.
+ */
+
+static int
+yaml_emitter_dump_mapping(yaml_emitter_t *emitter, yaml_node_t *node,
+ yaml_char_t *anchor)
+{
+ yaml_event_t event;
+ yaml_mark_t mark = { 0, 0, 0 };
+
+ int implicit = (strcmp((char *)node->tag, YAML_DEFAULT_MAPPING_TAG) == 0);
+
+ yaml_node_pair_t *pair;
+
+ MAPPING_START_EVENT_INIT(event, anchor, node->tag, implicit,
+ node->data.mapping.style, mark, mark);
+ if (!yaml_emitter_emit(emitter, &event)) return 0;
+
+ for (pair = node->data.mapping.pairs.start;
+ pair < node->data.mapping.pairs.top; pair ++) {
+ if (!yaml_emitter_dump_node(emitter, pair->key)) return 0;
+ if (!yaml_emitter_dump_node(emitter, pair->value)) return 0;
+ }
+
+ MAPPING_END_EVENT_INIT(event, mark, mark);
+ if (!yaml_emitter_emit(emitter, &event)) return 0;
+
+ return 1;
+}
+
diff --git a/contrib/libs/yaml/src/emitter.c b/contrib/libs/yaml/src/emitter.c
index 283a2be745..609b28a4c6 100644
--- a/contrib/libs/yaml/src/emitter.c
+++ b/contrib/libs/yaml/src/emitter.c
@@ -1,609 +1,609 @@
-
-#include "yaml_private.h"
-
-/*
- * Flush the buffer if needed.
- */
-
-#define FLUSH(emitter) \
- ((emitter->buffer.pointer+5 < emitter->buffer.end) \
- || yaml_emitter_flush(emitter))
-
-/*
- * Put a character to the output buffer.
- */
-
-#define PUT(emitter,value) \
- (FLUSH(emitter) \
- && (*(emitter->buffer.pointer++) = (yaml_char_t)(value), \
+
+#include "yaml_private.h"
+
+/*
+ * Flush the buffer if needed.
+ */
+
+#define FLUSH(emitter) \
+ ((emitter->buffer.pointer+5 < emitter->buffer.end) \
+ || yaml_emitter_flush(emitter))
+
+/*
+ * Put a character to the output buffer.
+ */
+
+#define PUT(emitter,value) \
+ (FLUSH(emitter) \
+ && (*(emitter->buffer.pointer++) = (yaml_char_t)(value), \
emitter->column++, \
- 1))
-
-/*
- * Put a line break to the output buffer.
- */
-
-#define PUT_BREAK(emitter) \
- (FLUSH(emitter) \
- && ((emitter->line_break == YAML_CR_BREAK ? \
- (*(emitter->buffer.pointer++) = (yaml_char_t) '\r') : \
- emitter->line_break == YAML_LN_BREAK ? \
- (*(emitter->buffer.pointer++) = (yaml_char_t) '\n') : \
- emitter->line_break == YAML_CRLN_BREAK ? \
- (*(emitter->buffer.pointer++) = (yaml_char_t) '\r', \
- *(emitter->buffer.pointer++) = (yaml_char_t) '\n') : 0), \
- emitter->column = 0, \
- emitter->line ++, \
- 1))
-
-/*
- * Copy a character from a string into buffer.
- */
-
-#define WRITE(emitter,string) \
- (FLUSH(emitter) \
- && (COPY(emitter->buffer,string), \
- emitter->column ++, \
- 1))
-
-/*
- * Copy a line break character from a string into buffer.
- */
-
-#define WRITE_BREAK(emitter,string) \
- (FLUSH(emitter) \
- && (CHECK(string,'\n') ? \
- (PUT_BREAK(emitter), \
- string.pointer ++, \
- 1) : \
- (COPY(emitter->buffer,string), \
- emitter->column = 0, \
- emitter->line ++, \
- 1)))
-
-/*
- * API functions.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event);
-
-/*
- * Utility functions.
- */
-
-static int
-yaml_emitter_set_emitter_error(yaml_emitter_t *emitter, const char *problem);
-
-static int
-yaml_emitter_need_more_events(yaml_emitter_t *emitter);
-
-static int
-yaml_emitter_append_tag_directive(yaml_emitter_t *emitter,
- yaml_tag_directive_t value, int allow_duplicates);
-
-static int
-yaml_emitter_increase_indent(yaml_emitter_t *emitter,
- int flow, int indentless);
-
-/*
- * State functions.
- */
-
-static int
-yaml_emitter_state_machine(yaml_emitter_t *emitter, yaml_event_t *event);
-
-static int
-yaml_emitter_emit_stream_start(yaml_emitter_t *emitter,
- yaml_event_t *event);
-
-static int
-yaml_emitter_emit_document_start(yaml_emitter_t *emitter,
- yaml_event_t *event, int first);
-
-static int
-yaml_emitter_emit_document_content(yaml_emitter_t *emitter,
- yaml_event_t *event);
-
-static int
-yaml_emitter_emit_document_end(yaml_emitter_t *emitter,
- yaml_event_t *event);
-
-static int
-yaml_emitter_emit_flow_sequence_item(yaml_emitter_t *emitter,
- yaml_event_t *event, int first);
-
-static int
-yaml_emitter_emit_flow_mapping_key(yaml_emitter_t *emitter,
- yaml_event_t *event, int first);
-
-static int
-yaml_emitter_emit_flow_mapping_value(yaml_emitter_t *emitter,
- yaml_event_t *event, int simple);
-
-static int
-yaml_emitter_emit_block_sequence_item(yaml_emitter_t *emitter,
- yaml_event_t *event, int first);
-
-static int
-yaml_emitter_emit_block_mapping_key(yaml_emitter_t *emitter,
- yaml_event_t *event, int first);
-
-static int
-yaml_emitter_emit_block_mapping_value(yaml_emitter_t *emitter,
- yaml_event_t *event, int simple);
-
-static int
-yaml_emitter_emit_node(yaml_emitter_t *emitter, yaml_event_t *event,
- int root, int sequence, int mapping, int simple_key);
-
-static int
-yaml_emitter_emit_alias(yaml_emitter_t *emitter, yaml_event_t *event);
-
-static int
-yaml_emitter_emit_scalar(yaml_emitter_t *emitter, yaml_event_t *event);
-
-static int
-yaml_emitter_emit_sequence_start(yaml_emitter_t *emitter, yaml_event_t *event);
-
-static int
-yaml_emitter_emit_mapping_start(yaml_emitter_t *emitter, yaml_event_t *event);
-
-/*
- * Checkers.
- */
-
-static int
-yaml_emitter_check_empty_document(yaml_emitter_t *emitter);
-
-static int
-yaml_emitter_check_empty_sequence(yaml_emitter_t *emitter);
-
-static int
-yaml_emitter_check_empty_mapping(yaml_emitter_t *emitter);
-
-static int
-yaml_emitter_check_simple_key(yaml_emitter_t *emitter);
-
-static int
-yaml_emitter_select_scalar_style(yaml_emitter_t *emitter, yaml_event_t *event);
-
-/*
- * Processors.
- */
-
-static int
-yaml_emitter_process_anchor(yaml_emitter_t *emitter);
-
-static int
-yaml_emitter_process_tag(yaml_emitter_t *emitter);
-
-static int
-yaml_emitter_process_scalar(yaml_emitter_t *emitter);
-
-/*
- * Analyzers.
- */
-
-static int
-yaml_emitter_analyze_version_directive(yaml_emitter_t *emitter,
- yaml_version_directive_t version_directive);
-
-static int
-yaml_emitter_analyze_tag_directive(yaml_emitter_t *emitter,
- yaml_tag_directive_t tag_directive);
-
-static int
-yaml_emitter_analyze_anchor(yaml_emitter_t *emitter,
- yaml_char_t *anchor, int alias);
-
-static int
-yaml_emitter_analyze_tag(yaml_emitter_t *emitter,
- yaml_char_t *tag);
-
-static int
-yaml_emitter_analyze_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length);
-
-static int
-yaml_emitter_analyze_event(yaml_emitter_t *emitter,
- yaml_event_t *event);
-
-/*
- * Writers.
- */
-
-static int
-yaml_emitter_write_bom(yaml_emitter_t *emitter);
-
-static int
-yaml_emitter_write_indent(yaml_emitter_t *emitter);
-
-static int
-yaml_emitter_write_indicator(yaml_emitter_t *emitter,
+ 1))
+
+/*
+ * Put a line break to the output buffer.
+ */
+
+#define PUT_BREAK(emitter) \
+ (FLUSH(emitter) \
+ && ((emitter->line_break == YAML_CR_BREAK ? \
+ (*(emitter->buffer.pointer++) = (yaml_char_t) '\r') : \
+ emitter->line_break == YAML_LN_BREAK ? \
+ (*(emitter->buffer.pointer++) = (yaml_char_t) '\n') : \
+ emitter->line_break == YAML_CRLN_BREAK ? \
+ (*(emitter->buffer.pointer++) = (yaml_char_t) '\r', \
+ *(emitter->buffer.pointer++) = (yaml_char_t) '\n') : 0), \
+ emitter->column = 0, \
+ emitter->line ++, \
+ 1))
+
+/*
+ * Copy a character from a string into buffer.
+ */
+
+#define WRITE(emitter,string) \
+ (FLUSH(emitter) \
+ && (COPY(emitter->buffer,string), \
+ emitter->column ++, \
+ 1))
+
+/*
+ * Copy a line break character from a string into buffer.
+ */
+
+#define WRITE_BREAK(emitter,string) \
+ (FLUSH(emitter) \
+ && (CHECK(string,'\n') ? \
+ (PUT_BREAK(emitter), \
+ string.pointer ++, \
+ 1) : \
+ (COPY(emitter->buffer,string), \
+ emitter->column = 0, \
+ emitter->line ++, \
+ 1)))
+
+/*
+ * API functions.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event);
+
+/*
+ * Utility functions.
+ */
+
+static int
+yaml_emitter_set_emitter_error(yaml_emitter_t *emitter, const char *problem);
+
+static int
+yaml_emitter_need_more_events(yaml_emitter_t *emitter);
+
+static int
+yaml_emitter_append_tag_directive(yaml_emitter_t *emitter,
+ yaml_tag_directive_t value, int allow_duplicates);
+
+static int
+yaml_emitter_increase_indent(yaml_emitter_t *emitter,
+ int flow, int indentless);
+
+/*
+ * State functions.
+ */
+
+static int
+yaml_emitter_state_machine(yaml_emitter_t *emitter, yaml_event_t *event);
+
+static int
+yaml_emitter_emit_stream_start(yaml_emitter_t *emitter,
+ yaml_event_t *event);
+
+static int
+yaml_emitter_emit_document_start(yaml_emitter_t *emitter,
+ yaml_event_t *event, int first);
+
+static int
+yaml_emitter_emit_document_content(yaml_emitter_t *emitter,
+ yaml_event_t *event);
+
+static int
+yaml_emitter_emit_document_end(yaml_emitter_t *emitter,
+ yaml_event_t *event);
+
+static int
+yaml_emitter_emit_flow_sequence_item(yaml_emitter_t *emitter,
+ yaml_event_t *event, int first);
+
+static int
+yaml_emitter_emit_flow_mapping_key(yaml_emitter_t *emitter,
+ yaml_event_t *event, int first);
+
+static int
+yaml_emitter_emit_flow_mapping_value(yaml_emitter_t *emitter,
+ yaml_event_t *event, int simple);
+
+static int
+yaml_emitter_emit_block_sequence_item(yaml_emitter_t *emitter,
+ yaml_event_t *event, int first);
+
+static int
+yaml_emitter_emit_block_mapping_key(yaml_emitter_t *emitter,
+ yaml_event_t *event, int first);
+
+static int
+yaml_emitter_emit_block_mapping_value(yaml_emitter_t *emitter,
+ yaml_event_t *event, int simple);
+
+static int
+yaml_emitter_emit_node(yaml_emitter_t *emitter, yaml_event_t *event,
+ int root, int sequence, int mapping, int simple_key);
+
+static int
+yaml_emitter_emit_alias(yaml_emitter_t *emitter, yaml_event_t *event);
+
+static int
+yaml_emitter_emit_scalar(yaml_emitter_t *emitter, yaml_event_t *event);
+
+static int
+yaml_emitter_emit_sequence_start(yaml_emitter_t *emitter, yaml_event_t *event);
+
+static int
+yaml_emitter_emit_mapping_start(yaml_emitter_t *emitter, yaml_event_t *event);
+
+/*
+ * Checkers.
+ */
+
+static int
+yaml_emitter_check_empty_document(yaml_emitter_t *emitter);
+
+static int
+yaml_emitter_check_empty_sequence(yaml_emitter_t *emitter);
+
+static int
+yaml_emitter_check_empty_mapping(yaml_emitter_t *emitter);
+
+static int
+yaml_emitter_check_simple_key(yaml_emitter_t *emitter);
+
+static int
+yaml_emitter_select_scalar_style(yaml_emitter_t *emitter, yaml_event_t *event);
+
+/*
+ * Processors.
+ */
+
+static int
+yaml_emitter_process_anchor(yaml_emitter_t *emitter);
+
+static int
+yaml_emitter_process_tag(yaml_emitter_t *emitter);
+
+static int
+yaml_emitter_process_scalar(yaml_emitter_t *emitter);
+
+/*
+ * Analyzers.
+ */
+
+static int
+yaml_emitter_analyze_version_directive(yaml_emitter_t *emitter,
+ yaml_version_directive_t version_directive);
+
+static int
+yaml_emitter_analyze_tag_directive(yaml_emitter_t *emitter,
+ yaml_tag_directive_t tag_directive);
+
+static int
+yaml_emitter_analyze_anchor(yaml_emitter_t *emitter,
+ yaml_char_t *anchor, int alias);
+
+static int
+yaml_emitter_analyze_tag(yaml_emitter_t *emitter,
+ yaml_char_t *tag);
+
+static int
+yaml_emitter_analyze_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length);
+
+static int
+yaml_emitter_analyze_event(yaml_emitter_t *emitter,
+ yaml_event_t *event);
+
+/*
+ * Writers.
+ */
+
+static int
+yaml_emitter_write_bom(yaml_emitter_t *emitter);
+
+static int
+yaml_emitter_write_indent(yaml_emitter_t *emitter);
+
+static int
+yaml_emitter_write_indicator(yaml_emitter_t *emitter,
const char *indicator, int need_whitespace,
- int is_whitespace, int is_indention);
-
-static int
-yaml_emitter_write_anchor(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length);
-
-static int
-yaml_emitter_write_tag_handle(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length);
-
-static int
-yaml_emitter_write_tag_content(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length, int need_whitespace);
-
-static int
-yaml_emitter_write_plain_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length, int allow_breaks);
-
-static int
-yaml_emitter_write_single_quoted_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length, int allow_breaks);
-
-static int
-yaml_emitter_write_double_quoted_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length, int allow_breaks);
-
-static int
-yaml_emitter_write_block_scalar_hints(yaml_emitter_t *emitter,
- yaml_string_t string);
-
-static int
-yaml_emitter_write_literal_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length);
-
-static int
-yaml_emitter_write_folded_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length);
-
-/*
- * Set an emitter error and return 0.
- */
-
-static int
-yaml_emitter_set_emitter_error(yaml_emitter_t *emitter, const char *problem)
-{
- emitter->error = YAML_EMITTER_ERROR;
- emitter->problem = problem;
-
- return 0;
-}
-
-/*
- * Emit an event.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event)
-{
- if (!ENQUEUE(emitter, emitter->events, *event)) {
- yaml_event_delete(event);
- return 0;
- }
-
- while (!yaml_emitter_need_more_events(emitter)) {
- if (!yaml_emitter_analyze_event(emitter, emitter->events.head))
- return 0;
- if (!yaml_emitter_state_machine(emitter, emitter->events.head))
- return 0;
- yaml_event_delete(&DEQUEUE(emitter, emitter->events));
- }
-
- return 1;
-}
-
-/*
- * Check if we need to accumulate more events before emitting.
- *
- * We accumulate extra
- * - 1 event for DOCUMENT-START
- * - 2 events for SEQUENCE-START
- * - 3 events for MAPPING-START
- */
-
-static int
-yaml_emitter_need_more_events(yaml_emitter_t *emitter)
-{
- int level = 0;
- int accumulate = 0;
- yaml_event_t *event;
-
- if (QUEUE_EMPTY(emitter, emitter->events))
- return 1;
-
- switch (emitter->events.head->type) {
- case YAML_DOCUMENT_START_EVENT:
- accumulate = 1;
- break;
- case YAML_SEQUENCE_START_EVENT:
- accumulate = 2;
- break;
- case YAML_MAPPING_START_EVENT:
- accumulate = 3;
- break;
- default:
- return 0;
- }
-
- if (emitter->events.tail - emitter->events.head > accumulate)
- return 0;
-
- for (event = emitter->events.head; event != emitter->events.tail; event ++) {
- switch (event->type) {
- case YAML_STREAM_START_EVENT:
- case YAML_DOCUMENT_START_EVENT:
- case YAML_SEQUENCE_START_EVENT:
- case YAML_MAPPING_START_EVENT:
- level += 1;
- break;
- case YAML_STREAM_END_EVENT:
- case YAML_DOCUMENT_END_EVENT:
- case YAML_SEQUENCE_END_EVENT:
- case YAML_MAPPING_END_EVENT:
- level -= 1;
- break;
- default:
- break;
- }
- if (!level)
- return 0;
- }
-
- return 1;
-}
-
-/*
- * Append a directive to the directives stack.
- */
-
-static int
-yaml_emitter_append_tag_directive(yaml_emitter_t *emitter,
- yaml_tag_directive_t value, int allow_duplicates)
-{
- yaml_tag_directive_t *tag_directive;
- yaml_tag_directive_t copy = { NULL, NULL };
-
- for (tag_directive = emitter->tag_directives.start;
- tag_directive != emitter->tag_directives.top; tag_directive ++) {
- if (strcmp((char *)value.handle, (char *)tag_directive->handle) == 0) {
- if (allow_duplicates)
- return 1;
- return yaml_emitter_set_emitter_error(emitter,
- "duplicate %TAG directive");
- }
- }
-
- copy.handle = yaml_strdup(value.handle);
- copy.prefix = yaml_strdup(value.prefix);
- if (!copy.handle || !copy.prefix) {
- emitter->error = YAML_MEMORY_ERROR;
- goto error;
- }
-
- if (!PUSH(emitter, emitter->tag_directives, copy))
- goto error;
-
- return 1;
-
-error:
- yaml_free(copy.handle);
- yaml_free(copy.prefix);
- return 0;
-}
-
-/*
- * Increase the indentation level.
- */
-
-static int
-yaml_emitter_increase_indent(yaml_emitter_t *emitter,
- int flow, int indentless)
-{
- if (!PUSH(emitter, emitter->indents, emitter->indent))
- return 0;
-
- if (emitter->indent < 0) {
- emitter->indent = flow ? emitter->best_indent : 0;
- }
- else if (!indentless) {
- emitter->indent += emitter->best_indent;
- }
-
- return 1;
-}
-
-/*
- * State dispatcher.
- */
-
-static int
-yaml_emitter_state_machine(yaml_emitter_t *emitter, yaml_event_t *event)
-{
- switch (emitter->state)
- {
- case YAML_EMIT_STREAM_START_STATE:
- return yaml_emitter_emit_stream_start(emitter, event);
-
- case YAML_EMIT_FIRST_DOCUMENT_START_STATE:
- return yaml_emitter_emit_document_start(emitter, event, 1);
-
- case YAML_EMIT_DOCUMENT_START_STATE:
- return yaml_emitter_emit_document_start(emitter, event, 0);
-
- case YAML_EMIT_DOCUMENT_CONTENT_STATE:
- return yaml_emitter_emit_document_content(emitter, event);
-
- case YAML_EMIT_DOCUMENT_END_STATE:
- return yaml_emitter_emit_document_end(emitter, event);
-
- case YAML_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE:
- return yaml_emitter_emit_flow_sequence_item(emitter, event, 1);
-
- case YAML_EMIT_FLOW_SEQUENCE_ITEM_STATE:
- return yaml_emitter_emit_flow_sequence_item(emitter, event, 0);
-
- case YAML_EMIT_FLOW_MAPPING_FIRST_KEY_STATE:
- return yaml_emitter_emit_flow_mapping_key(emitter, event, 1);
-
- case YAML_EMIT_FLOW_MAPPING_KEY_STATE:
- return yaml_emitter_emit_flow_mapping_key(emitter, event, 0);
-
- case YAML_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE:
- return yaml_emitter_emit_flow_mapping_value(emitter, event, 1);
-
- case YAML_EMIT_FLOW_MAPPING_VALUE_STATE:
- return yaml_emitter_emit_flow_mapping_value(emitter, event, 0);
-
- case YAML_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE:
- return yaml_emitter_emit_block_sequence_item(emitter, event, 1);
-
- case YAML_EMIT_BLOCK_SEQUENCE_ITEM_STATE:
- return yaml_emitter_emit_block_sequence_item(emitter, event, 0);
-
- case YAML_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE:
- return yaml_emitter_emit_block_mapping_key(emitter, event, 1);
-
- case YAML_EMIT_BLOCK_MAPPING_KEY_STATE:
- return yaml_emitter_emit_block_mapping_key(emitter, event, 0);
-
- case YAML_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE:
- return yaml_emitter_emit_block_mapping_value(emitter, event, 1);
-
- case YAML_EMIT_BLOCK_MAPPING_VALUE_STATE:
- return yaml_emitter_emit_block_mapping_value(emitter, event, 0);
-
- case YAML_EMIT_END_STATE:
- return yaml_emitter_set_emitter_error(emitter,
- "expected nothing after STREAM-END");
-
- default:
- assert(1); /* Invalid state. */
- }
-
- return 0;
-}
-
-/*
- * Expect STREAM-START.
- */
-
-static int
-yaml_emitter_emit_stream_start(yaml_emitter_t *emitter,
- yaml_event_t *event)
-{
+ int is_whitespace, int is_indention);
+
+static int
+yaml_emitter_write_anchor(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length);
+
+static int
+yaml_emitter_write_tag_handle(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length);
+
+static int
+yaml_emitter_write_tag_content(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length, int need_whitespace);
+
+static int
+yaml_emitter_write_plain_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length, int allow_breaks);
+
+static int
+yaml_emitter_write_single_quoted_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length, int allow_breaks);
+
+static int
+yaml_emitter_write_double_quoted_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length, int allow_breaks);
+
+static int
+yaml_emitter_write_block_scalar_hints(yaml_emitter_t *emitter,
+ yaml_string_t string);
+
+static int
+yaml_emitter_write_literal_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length);
+
+static int
+yaml_emitter_write_folded_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length);
+
+/*
+ * Set an emitter error and return 0.
+ */
+
+static int
+yaml_emitter_set_emitter_error(yaml_emitter_t *emitter, const char *problem)
+{
+ emitter->error = YAML_EMITTER_ERROR;
+ emitter->problem = problem;
+
+ return 0;
+}
+
+/*
+ * Emit an event.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event)
+{
+ if (!ENQUEUE(emitter, emitter->events, *event)) {
+ yaml_event_delete(event);
+ return 0;
+ }
+
+ while (!yaml_emitter_need_more_events(emitter)) {
+ if (!yaml_emitter_analyze_event(emitter, emitter->events.head))
+ return 0;
+ if (!yaml_emitter_state_machine(emitter, emitter->events.head))
+ return 0;
+ yaml_event_delete(&DEQUEUE(emitter, emitter->events));
+ }
+
+ return 1;
+}
+
+/*
+ * Check if we need to accumulate more events before emitting.
+ *
+ * We accumulate extra
+ * - 1 event for DOCUMENT-START
+ * - 2 events for SEQUENCE-START
+ * - 3 events for MAPPING-START
+ */
+
+static int
+yaml_emitter_need_more_events(yaml_emitter_t *emitter)
+{
+ int level = 0;
+ int accumulate = 0;
+ yaml_event_t *event;
+
+ if (QUEUE_EMPTY(emitter, emitter->events))
+ return 1;
+
+ switch (emitter->events.head->type) {
+ case YAML_DOCUMENT_START_EVENT:
+ accumulate = 1;
+ break;
+ case YAML_SEQUENCE_START_EVENT:
+ accumulate = 2;
+ break;
+ case YAML_MAPPING_START_EVENT:
+ accumulate = 3;
+ break;
+ default:
+ return 0;
+ }
+
+ if (emitter->events.tail - emitter->events.head > accumulate)
+ return 0;
+
+ for (event = emitter->events.head; event != emitter->events.tail; event ++) {
+ switch (event->type) {
+ case YAML_STREAM_START_EVENT:
+ case YAML_DOCUMENT_START_EVENT:
+ case YAML_SEQUENCE_START_EVENT:
+ case YAML_MAPPING_START_EVENT:
+ level += 1;
+ break;
+ case YAML_STREAM_END_EVENT:
+ case YAML_DOCUMENT_END_EVENT:
+ case YAML_SEQUENCE_END_EVENT:
+ case YAML_MAPPING_END_EVENT:
+ level -= 1;
+ break;
+ default:
+ break;
+ }
+ if (!level)
+ return 0;
+ }
+
+ return 1;
+}
+
+/*
+ * Append a directive to the directives stack.
+ */
+
+static int
+yaml_emitter_append_tag_directive(yaml_emitter_t *emitter,
+ yaml_tag_directive_t value, int allow_duplicates)
+{
+ yaml_tag_directive_t *tag_directive;
+ yaml_tag_directive_t copy = { NULL, NULL };
+
+ for (tag_directive = emitter->tag_directives.start;
+ tag_directive != emitter->tag_directives.top; tag_directive ++) {
+ if (strcmp((char *)value.handle, (char *)tag_directive->handle) == 0) {
+ if (allow_duplicates)
+ return 1;
+ return yaml_emitter_set_emitter_error(emitter,
+ "duplicate %TAG directive");
+ }
+ }
+
+ copy.handle = yaml_strdup(value.handle);
+ copy.prefix = yaml_strdup(value.prefix);
+ if (!copy.handle || !copy.prefix) {
+ emitter->error = YAML_MEMORY_ERROR;
+ goto error;
+ }
+
+ if (!PUSH(emitter, emitter->tag_directives, copy))
+ goto error;
+
+ return 1;
+
+error:
+ yaml_free(copy.handle);
+ yaml_free(copy.prefix);
+ return 0;
+}
+
+/*
+ * Increase the indentation level.
+ */
+
+static int
+yaml_emitter_increase_indent(yaml_emitter_t *emitter,
+ int flow, int indentless)
+{
+ if (!PUSH(emitter, emitter->indents, emitter->indent))
+ return 0;
+
+ if (emitter->indent < 0) {
+ emitter->indent = flow ? emitter->best_indent : 0;
+ }
+ else if (!indentless) {
+ emitter->indent += emitter->best_indent;
+ }
+
+ return 1;
+}
+
+/*
+ * State dispatcher.
+ */
+
+static int
+yaml_emitter_state_machine(yaml_emitter_t *emitter, yaml_event_t *event)
+{
+ switch (emitter->state)
+ {
+ case YAML_EMIT_STREAM_START_STATE:
+ return yaml_emitter_emit_stream_start(emitter, event);
+
+ case YAML_EMIT_FIRST_DOCUMENT_START_STATE:
+ return yaml_emitter_emit_document_start(emitter, event, 1);
+
+ case YAML_EMIT_DOCUMENT_START_STATE:
+ return yaml_emitter_emit_document_start(emitter, event, 0);
+
+ case YAML_EMIT_DOCUMENT_CONTENT_STATE:
+ return yaml_emitter_emit_document_content(emitter, event);
+
+ case YAML_EMIT_DOCUMENT_END_STATE:
+ return yaml_emitter_emit_document_end(emitter, event);
+
+ case YAML_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE:
+ return yaml_emitter_emit_flow_sequence_item(emitter, event, 1);
+
+ case YAML_EMIT_FLOW_SEQUENCE_ITEM_STATE:
+ return yaml_emitter_emit_flow_sequence_item(emitter, event, 0);
+
+ case YAML_EMIT_FLOW_MAPPING_FIRST_KEY_STATE:
+ return yaml_emitter_emit_flow_mapping_key(emitter, event, 1);
+
+ case YAML_EMIT_FLOW_MAPPING_KEY_STATE:
+ return yaml_emitter_emit_flow_mapping_key(emitter, event, 0);
+
+ case YAML_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE:
+ return yaml_emitter_emit_flow_mapping_value(emitter, event, 1);
+
+ case YAML_EMIT_FLOW_MAPPING_VALUE_STATE:
+ return yaml_emitter_emit_flow_mapping_value(emitter, event, 0);
+
+ case YAML_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE:
+ return yaml_emitter_emit_block_sequence_item(emitter, event, 1);
+
+ case YAML_EMIT_BLOCK_SEQUENCE_ITEM_STATE:
+ return yaml_emitter_emit_block_sequence_item(emitter, event, 0);
+
+ case YAML_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE:
+ return yaml_emitter_emit_block_mapping_key(emitter, event, 1);
+
+ case YAML_EMIT_BLOCK_MAPPING_KEY_STATE:
+ return yaml_emitter_emit_block_mapping_key(emitter, event, 0);
+
+ case YAML_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE:
+ return yaml_emitter_emit_block_mapping_value(emitter, event, 1);
+
+ case YAML_EMIT_BLOCK_MAPPING_VALUE_STATE:
+ return yaml_emitter_emit_block_mapping_value(emitter, event, 0);
+
+ case YAML_EMIT_END_STATE:
+ return yaml_emitter_set_emitter_error(emitter,
+ "expected nothing after STREAM-END");
+
+ default:
+ assert(1); /* Invalid state. */
+ }
+
+ return 0;
+}
+
+/*
+ * Expect STREAM-START.
+ */
+
+static int
+yaml_emitter_emit_stream_start(yaml_emitter_t *emitter,
+ yaml_event_t *event)
+{
emitter->open_ended = 0;
- if (event->type == YAML_STREAM_START_EVENT)
- {
- if (!emitter->encoding) {
- emitter->encoding = event->data.stream_start.encoding;
- }
-
- if (!emitter->encoding) {
- emitter->encoding = YAML_UTF8_ENCODING;
- }
-
- if (emitter->best_indent < 2 || emitter->best_indent > 9) {
- emitter->best_indent = 2;
- }
-
- if (emitter->best_width >= 0
- && emitter->best_width <= emitter->best_indent*2) {
- emitter->best_width = 80;
- }
-
- if (emitter->best_width < 0) {
- emitter->best_width = INT_MAX;
- }
-
- if (!emitter->line_break) {
- emitter->line_break = YAML_LN_BREAK;
- }
-
- emitter->indent = -1;
-
- emitter->line = 0;
- emitter->column = 0;
- emitter->whitespace = 1;
- emitter->indention = 1;
-
- if (emitter->encoding != YAML_UTF8_ENCODING) {
- if (!yaml_emitter_write_bom(emitter))
- return 0;
- }
-
- emitter->state = YAML_EMIT_FIRST_DOCUMENT_START_STATE;
-
- return 1;
- }
-
- return yaml_emitter_set_emitter_error(emitter,
- "expected STREAM-START");
-}
-
-/*
- * Expect DOCUMENT-START or STREAM-END.
- */
-
-static int
-yaml_emitter_emit_document_start(yaml_emitter_t *emitter,
- yaml_event_t *event, int first)
-{
- if (event->type == YAML_DOCUMENT_START_EVENT)
- {
- yaml_tag_directive_t default_tag_directives[] = {
- {(yaml_char_t *)"!", (yaml_char_t *)"!"},
- {(yaml_char_t *)"!!", (yaml_char_t *)"tag:yaml.org,2002:"},
- {NULL, NULL}
- };
- yaml_tag_directive_t *tag_directive;
- int implicit;
-
- if (event->data.document_start.version_directive) {
- if (!yaml_emitter_analyze_version_directive(emitter,
- *event->data.document_start.version_directive))
- return 0;
- }
-
- for (tag_directive = event->data.document_start.tag_directives.start;
- tag_directive != event->data.document_start.tag_directives.end;
- tag_directive ++) {
- if (!yaml_emitter_analyze_tag_directive(emitter, *tag_directive))
- return 0;
- if (!yaml_emitter_append_tag_directive(emitter, *tag_directive, 0))
- return 0;
- }
-
- for (tag_directive = default_tag_directives;
- tag_directive->handle; tag_directive ++) {
- if (!yaml_emitter_append_tag_directive(emitter, *tag_directive, 1))
- return 0;
- }
-
- implicit = event->data.document_start.implicit;
- if (!first || emitter->canonical) {
- implicit = 0;
- }
-
- if ((event->data.document_start.version_directive ||
- (event->data.document_start.tag_directives.start
- != event->data.document_start.tag_directives.end)) &&
- emitter->open_ended)
- {
- if (!yaml_emitter_write_indicator(emitter, "...", 1, 0, 0))
- return 0;
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- }
+ if (event->type == YAML_STREAM_START_EVENT)
+ {
+ if (!emitter->encoding) {
+ emitter->encoding = event->data.stream_start.encoding;
+ }
+
+ if (!emitter->encoding) {
+ emitter->encoding = YAML_UTF8_ENCODING;
+ }
+
+ if (emitter->best_indent < 2 || emitter->best_indent > 9) {
+ emitter->best_indent = 2;
+ }
+
+ if (emitter->best_width >= 0
+ && emitter->best_width <= emitter->best_indent*2) {
+ emitter->best_width = 80;
+ }
+
+ if (emitter->best_width < 0) {
+ emitter->best_width = INT_MAX;
+ }
+
+ if (!emitter->line_break) {
+ emitter->line_break = YAML_LN_BREAK;
+ }
+
+ emitter->indent = -1;
+
+ emitter->line = 0;
+ emitter->column = 0;
+ emitter->whitespace = 1;
+ emitter->indention = 1;
+
+ if (emitter->encoding != YAML_UTF8_ENCODING) {
+ if (!yaml_emitter_write_bom(emitter))
+ return 0;
+ }
+
+ emitter->state = YAML_EMIT_FIRST_DOCUMENT_START_STATE;
+
+ return 1;
+ }
+
+ return yaml_emitter_set_emitter_error(emitter,
+ "expected STREAM-START");
+}
+
+/*
+ * Expect DOCUMENT-START or STREAM-END.
+ */
+
+static int
+yaml_emitter_emit_document_start(yaml_emitter_t *emitter,
+ yaml_event_t *event, int first)
+{
+ if (event->type == YAML_DOCUMENT_START_EVENT)
+ {
+ yaml_tag_directive_t default_tag_directives[] = {
+ {(yaml_char_t *)"!", (yaml_char_t *)"!"},
+ {(yaml_char_t *)"!!", (yaml_char_t *)"tag:yaml.org,2002:"},
+ {NULL, NULL}
+ };
+ yaml_tag_directive_t *tag_directive;
+ int implicit;
+
+ if (event->data.document_start.version_directive) {
+ if (!yaml_emitter_analyze_version_directive(emitter,
+ *event->data.document_start.version_directive))
+ return 0;
+ }
+
+ for (tag_directive = event->data.document_start.tag_directives.start;
+ tag_directive != event->data.document_start.tag_directives.end;
+ tag_directive ++) {
+ if (!yaml_emitter_analyze_tag_directive(emitter, *tag_directive))
+ return 0;
+ if (!yaml_emitter_append_tag_directive(emitter, *tag_directive, 0))
+ return 0;
+ }
+
+ for (tag_directive = default_tag_directives;
+ tag_directive->handle; tag_directive ++) {
+ if (!yaml_emitter_append_tag_directive(emitter, *tag_directive, 1))
+ return 0;
+ }
+
+ implicit = event->data.document_start.implicit;
+ if (!first || emitter->canonical) {
+ implicit = 0;
+ }
+
+ if ((event->data.document_start.version_directive ||
+ (event->data.document_start.tag_directives.start
+ != event->data.document_start.tag_directives.end)) &&
+ emitter->open_ended)
+ {
+ if (!yaml_emitter_write_indicator(emitter, "...", 1, 0, 0))
+ return 0;
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ }
emitter->open_ended = 0;
-
- if (event->data.document_start.version_directive) {
- implicit = 0;
- if (!yaml_emitter_write_indicator(emitter, "%YAML", 1, 0, 0))
- return 0;
+
+ if (event->data.document_start.version_directive) {
+ implicit = 0;
+ if (!yaml_emitter_write_indicator(emitter, "%YAML", 1, 0, 0))
+ return 0;
if (event->data.document_start.version_directive->minor == 1) {
if (!yaml_emitter_write_indicator(emitter, "1.1", 1, 0, 0))
return 0;
@@ -612,53 +612,53 @@ yaml_emitter_emit_document_start(yaml_emitter_t *emitter,
if (!yaml_emitter_write_indicator(emitter, "1.2", 1, 0, 0))
return 0;
}
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- }
-
- if (event->data.document_start.tag_directives.start
- != event->data.document_start.tag_directives.end) {
- implicit = 0;
- for (tag_directive = event->data.document_start.tag_directives.start;
- tag_directive != event->data.document_start.tag_directives.end;
- tag_directive ++) {
- if (!yaml_emitter_write_indicator(emitter, "%TAG", 1, 0, 0))
- return 0;
- if (!yaml_emitter_write_tag_handle(emitter, tag_directive->handle,
- strlen((char *)tag_directive->handle)))
- return 0;
- if (!yaml_emitter_write_tag_content(emitter, tag_directive->prefix,
- strlen((char *)tag_directive->prefix), 1))
- return 0;
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- }
- }
-
- if (yaml_emitter_check_empty_document(emitter)) {
- implicit = 0;
- }
-
- if (!implicit) {
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- if (!yaml_emitter_write_indicator(emitter, "---", 1, 0, 0))
- return 0;
- if (emitter->canonical) {
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- }
- }
-
- emitter->state = YAML_EMIT_DOCUMENT_CONTENT_STATE;
-
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ }
+
+ if (event->data.document_start.tag_directives.start
+ != event->data.document_start.tag_directives.end) {
+ implicit = 0;
+ for (tag_directive = event->data.document_start.tag_directives.start;
+ tag_directive != event->data.document_start.tag_directives.end;
+ tag_directive ++) {
+ if (!yaml_emitter_write_indicator(emitter, "%TAG", 1, 0, 0))
+ return 0;
+ if (!yaml_emitter_write_tag_handle(emitter, tag_directive->handle,
+ strlen((char *)tag_directive->handle)))
+ return 0;
+ if (!yaml_emitter_write_tag_content(emitter, tag_directive->prefix,
+ strlen((char *)tag_directive->prefix), 1))
+ return 0;
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ }
+ }
+
+ if (yaml_emitter_check_empty_document(emitter)) {
+ implicit = 0;
+ }
+
+ if (!implicit) {
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ if (!yaml_emitter_write_indicator(emitter, "---", 1, 0, 0))
+ return 0;
+ if (emitter->canonical) {
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ }
+ }
+
+ emitter->state = YAML_EMIT_DOCUMENT_CONTENT_STATE;
+
emitter->open_ended = 0;
- return 1;
- }
-
- else if (event->type == YAML_STREAM_END_EVENT)
- {
-
+ return 1;
+ }
+
+ else if (event->type == YAML_STREAM_END_EVENT)
+ {
+
/**
* This can happen if a block scalar with trailing empty lines
* is at the end of the stream
@@ -671,1260 +671,1260 @@ yaml_emitter_emit_document_start(yaml_emitter_t *emitter,
if (!yaml_emitter_write_indent(emitter))
return 0;
}
- if (!yaml_emitter_flush(emitter))
- return 0;
-
- emitter->state = YAML_EMIT_END_STATE;
-
- return 1;
- }
-
- return yaml_emitter_set_emitter_error(emitter,
- "expected DOCUMENT-START or STREAM-END");
-}
-
-/*
- * Expect the root node.
- */
-
-static int
-yaml_emitter_emit_document_content(yaml_emitter_t *emitter,
- yaml_event_t *event)
-{
- if (!PUSH(emitter, emitter->states, YAML_EMIT_DOCUMENT_END_STATE))
- return 0;
-
- return yaml_emitter_emit_node(emitter, event, 1, 0, 0, 0);
-}
-
-/*
- * Expect DOCUMENT-END.
- */
-
-static int
-yaml_emitter_emit_document_end(yaml_emitter_t *emitter,
- yaml_event_t *event)
-{
- if (event->type == YAML_DOCUMENT_END_EVENT)
- {
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- if (!event->data.document_end.implicit) {
- if (!yaml_emitter_write_indicator(emitter, "...", 1, 0, 0))
- return 0;
+ if (!yaml_emitter_flush(emitter))
+ return 0;
+
+ emitter->state = YAML_EMIT_END_STATE;
+
+ return 1;
+ }
+
+ return yaml_emitter_set_emitter_error(emitter,
+ "expected DOCUMENT-START or STREAM-END");
+}
+
+/*
+ * Expect the root node.
+ */
+
+static int
+yaml_emitter_emit_document_content(yaml_emitter_t *emitter,
+ yaml_event_t *event)
+{
+ if (!PUSH(emitter, emitter->states, YAML_EMIT_DOCUMENT_END_STATE))
+ return 0;
+
+ return yaml_emitter_emit_node(emitter, event, 1, 0, 0, 0);
+}
+
+/*
+ * Expect DOCUMENT-END.
+ */
+
+static int
+yaml_emitter_emit_document_end(yaml_emitter_t *emitter,
+ yaml_event_t *event)
+{
+ if (event->type == YAML_DOCUMENT_END_EVENT)
+ {
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ if (!event->data.document_end.implicit) {
+ if (!yaml_emitter_write_indicator(emitter, "...", 1, 0, 0))
+ return 0;
emitter->open_ended = 0;
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- }
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ }
else if (!emitter->open_ended)
emitter->open_ended = 1;
- if (!yaml_emitter_flush(emitter))
- return 0;
-
- emitter->state = YAML_EMIT_DOCUMENT_START_STATE;
-
- while (!STACK_EMPTY(emitter, emitter->tag_directives)) {
- yaml_tag_directive_t tag_directive = POP(emitter,
- emitter->tag_directives);
- yaml_free(tag_directive.handle);
- yaml_free(tag_directive.prefix);
- }
-
- return 1;
- }
-
- return yaml_emitter_set_emitter_error(emitter,
- "expected DOCUMENT-END");
-}
-
-/*
+ if (!yaml_emitter_flush(emitter))
+ return 0;
+
+ emitter->state = YAML_EMIT_DOCUMENT_START_STATE;
+
+ while (!STACK_EMPTY(emitter, emitter->tag_directives)) {
+ yaml_tag_directive_t tag_directive = POP(emitter,
+ emitter->tag_directives);
+ yaml_free(tag_directive.handle);
+ yaml_free(tag_directive.prefix);
+ }
+
+ return 1;
+ }
+
+ return yaml_emitter_set_emitter_error(emitter,
+ "expected DOCUMENT-END");
+}
+
+/*
*
- * Expect a flow item node.
- */
-
-static int
-yaml_emitter_emit_flow_sequence_item(yaml_emitter_t *emitter,
- yaml_event_t *event, int first)
-{
- if (first)
- {
- if (!yaml_emitter_write_indicator(emitter, "[", 1, 1, 0))
- return 0;
- if (!yaml_emitter_increase_indent(emitter, 1, 0))
- return 0;
- emitter->flow_level ++;
- }
-
- if (event->type == YAML_SEQUENCE_END_EVENT)
- {
- emitter->flow_level --;
- emitter->indent = POP(emitter, emitter->indents);
- if (emitter->canonical && !first) {
- if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0))
- return 0;
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- }
- if (!yaml_emitter_write_indicator(emitter, "]", 0, 0, 0))
- return 0;
- emitter->state = POP(emitter, emitter->states);
-
- return 1;
- }
-
- if (!first) {
- if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0))
- return 0;
- }
-
- if (emitter->canonical || emitter->column > emitter->best_width) {
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- }
- if (!PUSH(emitter, emitter->states, YAML_EMIT_FLOW_SEQUENCE_ITEM_STATE))
- return 0;
-
- return yaml_emitter_emit_node(emitter, event, 0, 1, 0, 0);
-}
-
-/*
- * Expect a flow key node.
- */
-
-static int
-yaml_emitter_emit_flow_mapping_key(yaml_emitter_t *emitter,
- yaml_event_t *event, int first)
-{
- if (first)
- {
- if (!yaml_emitter_write_indicator(emitter, "{", 1, 1, 0))
- return 0;
- if (!yaml_emitter_increase_indent(emitter, 1, 0))
- return 0;
- emitter->flow_level ++;
- }
-
- if (event->type == YAML_MAPPING_END_EVENT)
- {
- emitter->flow_level --;
- emitter->indent = POP(emitter, emitter->indents);
- if (emitter->canonical && !first) {
- if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0))
- return 0;
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- }
- if (!yaml_emitter_write_indicator(emitter, "}", 0, 0, 0))
- return 0;
- emitter->state = POP(emitter, emitter->states);
-
- return 1;
- }
-
- if (!first) {
- if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0))
- return 0;
- }
- if (emitter->canonical || emitter->column > emitter->best_width) {
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- }
-
- if (!emitter->canonical && yaml_emitter_check_simple_key(emitter))
- {
- if (!PUSH(emitter, emitter->states,
- YAML_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE))
- return 0;
-
- return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 1);
- }
- else
- {
- if (!yaml_emitter_write_indicator(emitter, "?", 1, 0, 0))
- return 0;
- if (!PUSH(emitter, emitter->states,
- YAML_EMIT_FLOW_MAPPING_VALUE_STATE))
- return 0;
-
- return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0);
- }
-}
-
-/*
- * Expect a flow value node.
- */
-
-static int
-yaml_emitter_emit_flow_mapping_value(yaml_emitter_t *emitter,
- yaml_event_t *event, int simple)
-{
- if (simple) {
- if (!yaml_emitter_write_indicator(emitter, ":", 0, 0, 0))
- return 0;
- }
- else {
- if (emitter->canonical || emitter->column > emitter->best_width) {
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- }
- if (!yaml_emitter_write_indicator(emitter, ":", 1, 0, 0))
- return 0;
- }
- if (!PUSH(emitter, emitter->states, YAML_EMIT_FLOW_MAPPING_KEY_STATE))
- return 0;
- return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0);
-}
-
-/*
- * Expect a block item node.
- */
-
-static int
-yaml_emitter_emit_block_sequence_item(yaml_emitter_t *emitter,
- yaml_event_t *event, int first)
-{
- if (first)
- {
- if (!yaml_emitter_increase_indent(emitter, 0,
- (emitter->mapping_context && !emitter->indention)))
- return 0;
- }
-
- if (event->type == YAML_SEQUENCE_END_EVENT)
- {
- emitter->indent = POP(emitter, emitter->indents);
- emitter->state = POP(emitter, emitter->states);
-
- return 1;
- }
-
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- if (!yaml_emitter_write_indicator(emitter, "-", 1, 0, 1))
- return 0;
- if (!PUSH(emitter, emitter->states,
- YAML_EMIT_BLOCK_SEQUENCE_ITEM_STATE))
- return 0;
-
- return yaml_emitter_emit_node(emitter, event, 0, 1, 0, 0);
-}
-
-/*
- * Expect a block key node.
- */
-
-static int
-yaml_emitter_emit_block_mapping_key(yaml_emitter_t *emitter,
- yaml_event_t *event, int first)
-{
- if (first)
- {
- if (!yaml_emitter_increase_indent(emitter, 0, 0))
- return 0;
- }
-
- if (event->type == YAML_MAPPING_END_EVENT)
- {
- emitter->indent = POP(emitter, emitter->indents);
- emitter->state = POP(emitter, emitter->states);
-
- return 1;
- }
-
- if (!yaml_emitter_write_indent(emitter))
- return 0;
-
- if (yaml_emitter_check_simple_key(emitter))
- {
- if (!PUSH(emitter, emitter->states,
- YAML_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE))
- return 0;
-
- return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 1);
- }
- else
- {
- if (!yaml_emitter_write_indicator(emitter, "?", 1, 0, 1))
- return 0;
- if (!PUSH(emitter, emitter->states,
- YAML_EMIT_BLOCK_MAPPING_VALUE_STATE))
- return 0;
-
- return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0);
- }
-}
-
-/*
- * Expect a block value node.
- */
-
-static int
-yaml_emitter_emit_block_mapping_value(yaml_emitter_t *emitter,
- yaml_event_t *event, int simple)
-{
- if (simple) {
- if (!yaml_emitter_write_indicator(emitter, ":", 0, 0, 0))
- return 0;
- }
- else {
- if (!yaml_emitter_write_indent(emitter))
- return 0;
- if (!yaml_emitter_write_indicator(emitter, ":", 1, 0, 1))
- return 0;
- }
- if (!PUSH(emitter, emitter->states,
- YAML_EMIT_BLOCK_MAPPING_KEY_STATE))
- return 0;
-
- return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0);
-}
-
-/*
- * Expect a node.
- */
-
-static int
-yaml_emitter_emit_node(yaml_emitter_t *emitter, yaml_event_t *event,
- int root, int sequence, int mapping, int simple_key)
-{
- emitter->root_context = root;
- emitter->sequence_context = sequence;
- emitter->mapping_context = mapping;
- emitter->simple_key_context = simple_key;
-
- switch (event->type)
- {
- case YAML_ALIAS_EVENT:
- return yaml_emitter_emit_alias(emitter, event);
-
- case YAML_SCALAR_EVENT:
- return yaml_emitter_emit_scalar(emitter, event);
-
- case YAML_SEQUENCE_START_EVENT:
- return yaml_emitter_emit_sequence_start(emitter, event);
-
- case YAML_MAPPING_START_EVENT:
- return yaml_emitter_emit_mapping_start(emitter, event);
-
- default:
- return yaml_emitter_set_emitter_error(emitter,
- "expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS");
- }
-
- return 0;
-}
-
-/*
- * Expect ALIAS.
- */
-
-static int
+ * Expect a flow item node.
+ */
+
+static int
+yaml_emitter_emit_flow_sequence_item(yaml_emitter_t *emitter,
+ yaml_event_t *event, int first)
+{
+ if (first)
+ {
+ if (!yaml_emitter_write_indicator(emitter, "[", 1, 1, 0))
+ return 0;
+ if (!yaml_emitter_increase_indent(emitter, 1, 0))
+ return 0;
+ emitter->flow_level ++;
+ }
+
+ if (event->type == YAML_SEQUENCE_END_EVENT)
+ {
+ emitter->flow_level --;
+ emitter->indent = POP(emitter, emitter->indents);
+ if (emitter->canonical && !first) {
+ if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0))
+ return 0;
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ }
+ if (!yaml_emitter_write_indicator(emitter, "]", 0, 0, 0))
+ return 0;
+ emitter->state = POP(emitter, emitter->states);
+
+ return 1;
+ }
+
+ if (!first) {
+ if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0))
+ return 0;
+ }
+
+ if (emitter->canonical || emitter->column > emitter->best_width) {
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ }
+ if (!PUSH(emitter, emitter->states, YAML_EMIT_FLOW_SEQUENCE_ITEM_STATE))
+ return 0;
+
+ return yaml_emitter_emit_node(emitter, event, 0, 1, 0, 0);
+}
+
+/*
+ * Expect a flow key node.
+ */
+
+static int
+yaml_emitter_emit_flow_mapping_key(yaml_emitter_t *emitter,
+ yaml_event_t *event, int first)
+{
+ if (first)
+ {
+ if (!yaml_emitter_write_indicator(emitter, "{", 1, 1, 0))
+ return 0;
+ if (!yaml_emitter_increase_indent(emitter, 1, 0))
+ return 0;
+ emitter->flow_level ++;
+ }
+
+ if (event->type == YAML_MAPPING_END_EVENT)
+ {
+ emitter->flow_level --;
+ emitter->indent = POP(emitter, emitter->indents);
+ if (emitter->canonical && !first) {
+ if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0))
+ return 0;
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ }
+ if (!yaml_emitter_write_indicator(emitter, "}", 0, 0, 0))
+ return 0;
+ emitter->state = POP(emitter, emitter->states);
+
+ return 1;
+ }
+
+ if (!first) {
+ if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0))
+ return 0;
+ }
+ if (emitter->canonical || emitter->column > emitter->best_width) {
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ }
+
+ if (!emitter->canonical && yaml_emitter_check_simple_key(emitter))
+ {
+ if (!PUSH(emitter, emitter->states,
+ YAML_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE))
+ return 0;
+
+ return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 1);
+ }
+ else
+ {
+ if (!yaml_emitter_write_indicator(emitter, "?", 1, 0, 0))
+ return 0;
+ if (!PUSH(emitter, emitter->states,
+ YAML_EMIT_FLOW_MAPPING_VALUE_STATE))
+ return 0;
+
+ return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0);
+ }
+}
+
+/*
+ * Expect a flow value node.
+ */
+
+static int
+yaml_emitter_emit_flow_mapping_value(yaml_emitter_t *emitter,
+ yaml_event_t *event, int simple)
+{
+ if (simple) {
+ if (!yaml_emitter_write_indicator(emitter, ":", 0, 0, 0))
+ return 0;
+ }
+ else {
+ if (emitter->canonical || emitter->column > emitter->best_width) {
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ }
+ if (!yaml_emitter_write_indicator(emitter, ":", 1, 0, 0))
+ return 0;
+ }
+ if (!PUSH(emitter, emitter->states, YAML_EMIT_FLOW_MAPPING_KEY_STATE))
+ return 0;
+ return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0);
+}
+
+/*
+ * Expect a block item node.
+ */
+
+static int
+yaml_emitter_emit_block_sequence_item(yaml_emitter_t *emitter,
+ yaml_event_t *event, int first)
+{
+ if (first)
+ {
+ if (!yaml_emitter_increase_indent(emitter, 0,
+ (emitter->mapping_context && !emitter->indention)))
+ return 0;
+ }
+
+ if (event->type == YAML_SEQUENCE_END_EVENT)
+ {
+ emitter->indent = POP(emitter, emitter->indents);
+ emitter->state = POP(emitter, emitter->states);
+
+ return 1;
+ }
+
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ if (!yaml_emitter_write_indicator(emitter, "-", 1, 0, 1))
+ return 0;
+ if (!PUSH(emitter, emitter->states,
+ YAML_EMIT_BLOCK_SEQUENCE_ITEM_STATE))
+ return 0;
+
+ return yaml_emitter_emit_node(emitter, event, 0, 1, 0, 0);
+}
+
+/*
+ * Expect a block key node.
+ */
+
+static int
+yaml_emitter_emit_block_mapping_key(yaml_emitter_t *emitter,
+ yaml_event_t *event, int first)
+{
+ if (first)
+ {
+ if (!yaml_emitter_increase_indent(emitter, 0, 0))
+ return 0;
+ }
+
+ if (event->type == YAML_MAPPING_END_EVENT)
+ {
+ emitter->indent = POP(emitter, emitter->indents);
+ emitter->state = POP(emitter, emitter->states);
+
+ return 1;
+ }
+
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+
+ if (yaml_emitter_check_simple_key(emitter))
+ {
+ if (!PUSH(emitter, emitter->states,
+ YAML_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE))
+ return 0;
+
+ return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 1);
+ }
+ else
+ {
+ if (!yaml_emitter_write_indicator(emitter, "?", 1, 0, 1))
+ return 0;
+ if (!PUSH(emitter, emitter->states,
+ YAML_EMIT_BLOCK_MAPPING_VALUE_STATE))
+ return 0;
+
+ return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0);
+ }
+}
+
+/*
+ * Expect a block value node.
+ */
+
+static int
+yaml_emitter_emit_block_mapping_value(yaml_emitter_t *emitter,
+ yaml_event_t *event, int simple)
+{
+ if (simple) {
+ if (!yaml_emitter_write_indicator(emitter, ":", 0, 0, 0))
+ return 0;
+ }
+ else {
+ if (!yaml_emitter_write_indent(emitter))
+ return 0;
+ if (!yaml_emitter_write_indicator(emitter, ":", 1, 0, 1))
+ return 0;
+ }
+ if (!PUSH(emitter, emitter->states,
+ YAML_EMIT_BLOCK_MAPPING_KEY_STATE))
+ return 0;
+
+ return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0);
+}
+
+/*
+ * Expect a node.
+ */
+
+static int
+yaml_emitter_emit_node(yaml_emitter_t *emitter, yaml_event_t *event,
+ int root, int sequence, int mapping, int simple_key)
+{
+ emitter->root_context = root;
+ emitter->sequence_context = sequence;
+ emitter->mapping_context = mapping;
+ emitter->simple_key_context = simple_key;
+
+ switch (event->type)
+ {
+ case YAML_ALIAS_EVENT:
+ return yaml_emitter_emit_alias(emitter, event);
+
+ case YAML_SCALAR_EVENT:
+ return yaml_emitter_emit_scalar(emitter, event);
+
+ case YAML_SEQUENCE_START_EVENT:
+ return yaml_emitter_emit_sequence_start(emitter, event);
+
+ case YAML_MAPPING_START_EVENT:
+ return yaml_emitter_emit_mapping_start(emitter, event);
+
+ default:
+ return yaml_emitter_set_emitter_error(emitter,
+ "expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS");
+ }
+
+ return 0;
+}
+
+/*
+ * Expect ALIAS.
+ */
+
+static int
yaml_emitter_emit_alias(yaml_emitter_t *emitter, SHIM(yaml_event_t *event))
-{
- if (!yaml_emitter_process_anchor(emitter))
- return 0;
+{
+ if (!yaml_emitter_process_anchor(emitter))
+ return 0;
if (emitter->simple_key_context)
if (!PUT(emitter, ' ')) return 0;
- emitter->state = POP(emitter, emitter->states);
-
- return 1;
-}
-
-/*
- * Expect SCALAR.
- */
-
-static int
-yaml_emitter_emit_scalar(yaml_emitter_t *emitter, yaml_event_t *event)
-{
- if (!yaml_emitter_select_scalar_style(emitter, event))
- return 0;
- if (!yaml_emitter_process_anchor(emitter))
- return 0;
- if (!yaml_emitter_process_tag(emitter))
- return 0;
- if (!yaml_emitter_increase_indent(emitter, 1, 0))
- return 0;
- if (!yaml_emitter_process_scalar(emitter))
- return 0;
- emitter->indent = POP(emitter, emitter->indents);
- emitter->state = POP(emitter, emitter->states);
-
- return 1;
-}
-
-/*
- * Expect SEQUENCE-START.
- */
-
-static int
-yaml_emitter_emit_sequence_start(yaml_emitter_t *emitter, yaml_event_t *event)
-{
- if (!yaml_emitter_process_anchor(emitter))
- return 0;
- if (!yaml_emitter_process_tag(emitter))
- return 0;
-
- if (emitter->flow_level || emitter->canonical
- || event->data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE
- || yaml_emitter_check_empty_sequence(emitter)) {
- emitter->state = YAML_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE;
- }
- else {
- emitter->state = YAML_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE;
- }
-
- return 1;
-}
-
-/*
- * Expect MAPPING-START.
- */
-
-static int
-yaml_emitter_emit_mapping_start(yaml_emitter_t *emitter, yaml_event_t *event)
-{
- if (!yaml_emitter_process_anchor(emitter))
- return 0;
- if (!yaml_emitter_process_tag(emitter))
- return 0;
-
- if (emitter->flow_level || emitter->canonical
- || event->data.mapping_start.style == YAML_FLOW_MAPPING_STYLE
- || yaml_emitter_check_empty_mapping(emitter)) {
- emitter->state = YAML_EMIT_FLOW_MAPPING_FIRST_KEY_STATE;
- }
- else {
- emitter->state = YAML_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE;
- }
-
- return 1;
-}
-
-/*
- * Check if the document content is an empty scalar.
- */
-
-static int
+ emitter->state = POP(emitter, emitter->states);
+
+ return 1;
+}
+
+/*
+ * Expect SCALAR.
+ */
+
+static int
+yaml_emitter_emit_scalar(yaml_emitter_t *emitter, yaml_event_t *event)
+{
+ if (!yaml_emitter_select_scalar_style(emitter, event))
+ return 0;
+ if (!yaml_emitter_process_anchor(emitter))
+ return 0;
+ if (!yaml_emitter_process_tag(emitter))
+ return 0;
+ if (!yaml_emitter_increase_indent(emitter, 1, 0))
+ return 0;
+ if (!yaml_emitter_process_scalar(emitter))
+ return 0;
+ emitter->indent = POP(emitter, emitter->indents);
+ emitter->state = POP(emitter, emitter->states);
+
+ return 1;
+}
+
+/*
+ * Expect SEQUENCE-START.
+ */
+
+static int
+yaml_emitter_emit_sequence_start(yaml_emitter_t *emitter, yaml_event_t *event)
+{
+ if (!yaml_emitter_process_anchor(emitter))
+ return 0;
+ if (!yaml_emitter_process_tag(emitter))
+ return 0;
+
+ if (emitter->flow_level || emitter->canonical
+ || event->data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE
+ || yaml_emitter_check_empty_sequence(emitter)) {
+ emitter->state = YAML_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE;
+ }
+ else {
+ emitter->state = YAML_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE;
+ }
+
+ return 1;
+}
+
+/*
+ * Expect MAPPING-START.
+ */
+
+static int
+yaml_emitter_emit_mapping_start(yaml_emitter_t *emitter, yaml_event_t *event)
+{
+ if (!yaml_emitter_process_anchor(emitter))
+ return 0;
+ if (!yaml_emitter_process_tag(emitter))
+ return 0;
+
+ if (emitter->flow_level || emitter->canonical
+ || event->data.mapping_start.style == YAML_FLOW_MAPPING_STYLE
+ || yaml_emitter_check_empty_mapping(emitter)) {
+ emitter->state = YAML_EMIT_FLOW_MAPPING_FIRST_KEY_STATE;
+ }
+ else {
+ emitter->state = YAML_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE;
+ }
+
+ return 1;
+}
+
+/*
+ * Check if the document content is an empty scalar.
+ */
+
+static int
yaml_emitter_check_empty_document(SHIM(yaml_emitter_t *emitter))
-{
- return 0;
-}
-
-/*
- * Check if the next events represent an empty sequence.
- */
-
-static int
-yaml_emitter_check_empty_sequence(yaml_emitter_t *emitter)
-{
- if (emitter->events.tail - emitter->events.head < 2)
- return 0;
-
- return (emitter->events.head[0].type == YAML_SEQUENCE_START_EVENT
- && emitter->events.head[1].type == YAML_SEQUENCE_END_EVENT);
-}
-
-/*
- * Check if the next events represent an empty mapping.
- */
-
-static int
-yaml_emitter_check_empty_mapping(yaml_emitter_t *emitter)
-{
- if (emitter->events.tail - emitter->events.head < 2)
- return 0;
-
- return (emitter->events.head[0].type == YAML_MAPPING_START_EVENT
- && emitter->events.head[1].type == YAML_MAPPING_END_EVENT);
-}
-
-/*
- * Check if the next node can be expressed as a simple key.
- */
-
-static int
-yaml_emitter_check_simple_key(yaml_emitter_t *emitter)
-{
- yaml_event_t *event = emitter->events.head;
- size_t length = 0;
-
- switch (event->type)
- {
- case YAML_ALIAS_EVENT:
- length += emitter->anchor_data.anchor_length;
- break;
-
- case YAML_SCALAR_EVENT:
- if (emitter->scalar_data.multiline)
- return 0;
- length += emitter->anchor_data.anchor_length
- + emitter->tag_data.handle_length
- + emitter->tag_data.suffix_length
- + emitter->scalar_data.length;
- break;
-
- case YAML_SEQUENCE_START_EVENT:
- if (!yaml_emitter_check_empty_sequence(emitter))
- return 0;
- length += emitter->anchor_data.anchor_length
- + emitter->tag_data.handle_length
- + emitter->tag_data.suffix_length;
- break;
-
- case YAML_MAPPING_START_EVENT:
- if (!yaml_emitter_check_empty_mapping(emitter))
- return 0;
- length += emitter->anchor_data.anchor_length
- + emitter->tag_data.handle_length
- + emitter->tag_data.suffix_length;
- break;
-
- default:
- return 0;
- }
-
- if (length > 128)
- return 0;
-
- return 1;
-}
-
-/*
- * Determine an acceptable scalar style.
- */
-
-static int
-yaml_emitter_select_scalar_style(yaml_emitter_t *emitter, yaml_event_t *event)
-{
- yaml_scalar_style_t style = event->data.scalar.style;
- int no_tag = (!emitter->tag_data.handle && !emitter->tag_data.suffix);
-
- if (no_tag && !event->data.scalar.plain_implicit
- && !event->data.scalar.quoted_implicit) {
- return yaml_emitter_set_emitter_error(emitter,
- "neither tag nor implicit flags are specified");
- }
-
- if (style == YAML_ANY_SCALAR_STYLE)
- style = YAML_PLAIN_SCALAR_STYLE;
-
- if (emitter->canonical)
- style = YAML_DOUBLE_QUOTED_SCALAR_STYLE;
-
- if (emitter->simple_key_context && emitter->scalar_data.multiline)
- style = YAML_DOUBLE_QUOTED_SCALAR_STYLE;
-
- if (style == YAML_PLAIN_SCALAR_STYLE)
- {
- if ((emitter->flow_level && !emitter->scalar_data.flow_plain_allowed)
- || (!emitter->flow_level && !emitter->scalar_data.block_plain_allowed))
- style = YAML_SINGLE_QUOTED_SCALAR_STYLE;
- if (!emitter->scalar_data.length
- && (emitter->flow_level || emitter->simple_key_context))
- style = YAML_SINGLE_QUOTED_SCALAR_STYLE;
- if (no_tag && !event->data.scalar.plain_implicit)
- style = YAML_SINGLE_QUOTED_SCALAR_STYLE;
- }
-
- if (style == YAML_SINGLE_QUOTED_SCALAR_STYLE)
- {
- if (!emitter->scalar_data.single_quoted_allowed)
- style = YAML_DOUBLE_QUOTED_SCALAR_STYLE;
- }
-
- if (style == YAML_LITERAL_SCALAR_STYLE || style == YAML_FOLDED_SCALAR_STYLE)
- {
- if (!emitter->scalar_data.block_allowed
- || emitter->flow_level || emitter->simple_key_context)
- style = YAML_DOUBLE_QUOTED_SCALAR_STYLE;
- }
-
- if (no_tag && !event->data.scalar.quoted_implicit
- && style != YAML_PLAIN_SCALAR_STYLE)
- {
- emitter->tag_data.handle = (yaml_char_t *)"!";
- emitter->tag_data.handle_length = 1;
- }
-
- emitter->scalar_data.style = style;
-
- return 1;
-}
-
-/*
+{
+ return 0;
+}
+
+/*
+ * Check if the next events represent an empty sequence.
+ */
+
+static int
+yaml_emitter_check_empty_sequence(yaml_emitter_t *emitter)
+{
+ if (emitter->events.tail - emitter->events.head < 2)
+ return 0;
+
+ return (emitter->events.head[0].type == YAML_SEQUENCE_START_EVENT
+ && emitter->events.head[1].type == YAML_SEQUENCE_END_EVENT);
+}
+
+/*
+ * Check if the next events represent an empty mapping.
+ */
+
+static int
+yaml_emitter_check_empty_mapping(yaml_emitter_t *emitter)
+{
+ if (emitter->events.tail - emitter->events.head < 2)
+ return 0;
+
+ return (emitter->events.head[0].type == YAML_MAPPING_START_EVENT
+ && emitter->events.head[1].type == YAML_MAPPING_END_EVENT);
+}
+
+/*
+ * Check if the next node can be expressed as a simple key.
+ */
+
+static int
+yaml_emitter_check_simple_key(yaml_emitter_t *emitter)
+{
+ yaml_event_t *event = emitter->events.head;
+ size_t length = 0;
+
+ switch (event->type)
+ {
+ case YAML_ALIAS_EVENT:
+ length += emitter->anchor_data.anchor_length;
+ break;
+
+ case YAML_SCALAR_EVENT:
+ if (emitter->scalar_data.multiline)
+ return 0;
+ length += emitter->anchor_data.anchor_length
+ + emitter->tag_data.handle_length
+ + emitter->tag_data.suffix_length
+ + emitter->scalar_data.length;
+ break;
+
+ case YAML_SEQUENCE_START_EVENT:
+ if (!yaml_emitter_check_empty_sequence(emitter))
+ return 0;
+ length += emitter->anchor_data.anchor_length
+ + emitter->tag_data.handle_length
+ + emitter->tag_data.suffix_length;
+ break;
+
+ case YAML_MAPPING_START_EVENT:
+ if (!yaml_emitter_check_empty_mapping(emitter))
+ return 0;
+ length += emitter->anchor_data.anchor_length
+ + emitter->tag_data.handle_length
+ + emitter->tag_data.suffix_length;
+ break;
+
+ default:
+ return 0;
+ }
+
+ if (length > 128)
+ return 0;
+
+ return 1;
+}
+
+/*
+ * Determine an acceptable scalar style.
+ */
+
+static int
+yaml_emitter_select_scalar_style(yaml_emitter_t *emitter, yaml_event_t *event)
+{
+ yaml_scalar_style_t style = event->data.scalar.style;
+ int no_tag = (!emitter->tag_data.handle && !emitter->tag_data.suffix);
+
+ if (no_tag && !event->data.scalar.plain_implicit
+ && !event->data.scalar.quoted_implicit) {
+ return yaml_emitter_set_emitter_error(emitter,
+ "neither tag nor implicit flags are specified");
+ }
+
+ if (style == YAML_ANY_SCALAR_STYLE)
+ style = YAML_PLAIN_SCALAR_STYLE;
+
+ if (emitter->canonical)
+ style = YAML_DOUBLE_QUOTED_SCALAR_STYLE;
+
+ if (emitter->simple_key_context && emitter->scalar_data.multiline)
+ style = YAML_DOUBLE_QUOTED_SCALAR_STYLE;
+
+ if (style == YAML_PLAIN_SCALAR_STYLE)
+ {
+ if ((emitter->flow_level && !emitter->scalar_data.flow_plain_allowed)
+ || (!emitter->flow_level && !emitter->scalar_data.block_plain_allowed))
+ style = YAML_SINGLE_QUOTED_SCALAR_STYLE;
+ if (!emitter->scalar_data.length
+ && (emitter->flow_level || emitter->simple_key_context))
+ style = YAML_SINGLE_QUOTED_SCALAR_STYLE;
+ if (no_tag && !event->data.scalar.plain_implicit)
+ style = YAML_SINGLE_QUOTED_SCALAR_STYLE;
+ }
+
+ if (style == YAML_SINGLE_QUOTED_SCALAR_STYLE)
+ {
+ if (!emitter->scalar_data.single_quoted_allowed)
+ style = YAML_DOUBLE_QUOTED_SCALAR_STYLE;
+ }
+
+ if (style == YAML_LITERAL_SCALAR_STYLE || style == YAML_FOLDED_SCALAR_STYLE)
+ {
+ if (!emitter->scalar_data.block_allowed
+ || emitter->flow_level || emitter->simple_key_context)
+ style = YAML_DOUBLE_QUOTED_SCALAR_STYLE;
+ }
+
+ if (no_tag && !event->data.scalar.quoted_implicit
+ && style != YAML_PLAIN_SCALAR_STYLE)
+ {
+ emitter->tag_data.handle = (yaml_char_t *)"!";
+ emitter->tag_data.handle_length = 1;
+ }
+
+ emitter->scalar_data.style = style;
+
+ return 1;
+}
+
+/*
* Write an anchor.
- */
-
-static int
-yaml_emitter_process_anchor(yaml_emitter_t *emitter)
-{
- if (!emitter->anchor_data.anchor)
- return 1;
-
- if (!yaml_emitter_write_indicator(emitter,
- (emitter->anchor_data.alias ? "*" : "&"), 1, 0, 0))
- return 0;
-
- return yaml_emitter_write_anchor(emitter,
- emitter->anchor_data.anchor, emitter->anchor_data.anchor_length);
-}
-
-/*
- * Write a tag.
- */
-
-static int
-yaml_emitter_process_tag(yaml_emitter_t *emitter)
-{
- if (!emitter->tag_data.handle && !emitter->tag_data.suffix)
- return 1;
-
- if (emitter->tag_data.handle)
- {
- if (!yaml_emitter_write_tag_handle(emitter, emitter->tag_data.handle,
- emitter->tag_data.handle_length))
- return 0;
- if (emitter->tag_data.suffix) {
- if (!yaml_emitter_write_tag_content(emitter, emitter->tag_data.suffix,
- emitter->tag_data.suffix_length, 0))
- return 0;
- }
- }
- else
- {
- if (!yaml_emitter_write_indicator(emitter, "!<", 1, 0, 0))
- return 0;
- if (!yaml_emitter_write_tag_content(emitter, emitter->tag_data.suffix,
- emitter->tag_data.suffix_length, 0))
- return 0;
- if (!yaml_emitter_write_indicator(emitter, ">", 0, 0, 0))
- return 0;
- }
-
- return 1;
-}
-
-/*
- * Write a scalar.
- */
-
-static int
-yaml_emitter_process_scalar(yaml_emitter_t *emitter)
-{
- switch (emitter->scalar_data.style)
- {
- case YAML_PLAIN_SCALAR_STYLE:
- return yaml_emitter_write_plain_scalar(emitter,
- emitter->scalar_data.value, emitter->scalar_data.length,
- !emitter->simple_key_context);
-
- case YAML_SINGLE_QUOTED_SCALAR_STYLE:
- return yaml_emitter_write_single_quoted_scalar(emitter,
- emitter->scalar_data.value, emitter->scalar_data.length,
- !emitter->simple_key_context);
-
- case YAML_DOUBLE_QUOTED_SCALAR_STYLE:
- return yaml_emitter_write_double_quoted_scalar(emitter,
- emitter->scalar_data.value, emitter->scalar_data.length,
- !emitter->simple_key_context);
-
- case YAML_LITERAL_SCALAR_STYLE:
- return yaml_emitter_write_literal_scalar(emitter,
- emitter->scalar_data.value, emitter->scalar_data.length);
-
- case YAML_FOLDED_SCALAR_STYLE:
- return yaml_emitter_write_folded_scalar(emitter,
- emitter->scalar_data.value, emitter->scalar_data.length);
-
- default:
- assert(1); /* Impossible. */
- }
-
- return 0;
-}
-
-/*
- * Check if a %YAML directive is valid.
- */
-
-static int
-yaml_emitter_analyze_version_directive(yaml_emitter_t *emitter,
- yaml_version_directive_t version_directive)
-{
+ */
+
+static int
+yaml_emitter_process_anchor(yaml_emitter_t *emitter)
+{
+ if (!emitter->anchor_data.anchor)
+ return 1;
+
+ if (!yaml_emitter_write_indicator(emitter,
+ (emitter->anchor_data.alias ? "*" : "&"), 1, 0, 0))
+ return 0;
+
+ return yaml_emitter_write_anchor(emitter,
+ emitter->anchor_data.anchor, emitter->anchor_data.anchor_length);
+}
+
+/*
+ * Write a tag.
+ */
+
+static int
+yaml_emitter_process_tag(yaml_emitter_t *emitter)
+{
+ if (!emitter->tag_data.handle && !emitter->tag_data.suffix)
+ return 1;
+
+ if (emitter->tag_data.handle)
+ {
+ if (!yaml_emitter_write_tag_handle(emitter, emitter->tag_data.handle,
+ emitter->tag_data.handle_length))
+ return 0;
+ if (emitter->tag_data.suffix) {
+ if (!yaml_emitter_write_tag_content(emitter, emitter->tag_data.suffix,
+ emitter->tag_data.suffix_length, 0))
+ return 0;
+ }
+ }
+ else
+ {
+ if (!yaml_emitter_write_indicator(emitter, "!<", 1, 0, 0))
+ return 0;
+ if (!yaml_emitter_write_tag_content(emitter, emitter->tag_data.suffix,
+ emitter->tag_data.suffix_length, 0))
+ return 0;
+ if (!yaml_emitter_write_indicator(emitter, ">", 0, 0, 0))
+ return 0;
+ }
+
+ return 1;
+}
+
+/*
+ * Write a scalar.
+ */
+
+static int
+yaml_emitter_process_scalar(yaml_emitter_t *emitter)
+{
+ switch (emitter->scalar_data.style)
+ {
+ case YAML_PLAIN_SCALAR_STYLE:
+ return yaml_emitter_write_plain_scalar(emitter,
+ emitter->scalar_data.value, emitter->scalar_data.length,
+ !emitter->simple_key_context);
+
+ case YAML_SINGLE_QUOTED_SCALAR_STYLE:
+ return yaml_emitter_write_single_quoted_scalar(emitter,
+ emitter->scalar_data.value, emitter->scalar_data.length,
+ !emitter->simple_key_context);
+
+ case YAML_DOUBLE_QUOTED_SCALAR_STYLE:
+ return yaml_emitter_write_double_quoted_scalar(emitter,
+ emitter->scalar_data.value, emitter->scalar_data.length,
+ !emitter->simple_key_context);
+
+ case YAML_LITERAL_SCALAR_STYLE:
+ return yaml_emitter_write_literal_scalar(emitter,
+ emitter->scalar_data.value, emitter->scalar_data.length);
+
+ case YAML_FOLDED_SCALAR_STYLE:
+ return yaml_emitter_write_folded_scalar(emitter,
+ emitter->scalar_data.value, emitter->scalar_data.length);
+
+ default:
+ assert(1); /* Impossible. */
+ }
+
+ return 0;
+}
+
+/*
+ * Check if a %YAML directive is valid.
+ */
+
+static int
+yaml_emitter_analyze_version_directive(yaml_emitter_t *emitter,
+ yaml_version_directive_t version_directive)
+{
if (version_directive.major != 1 || (
version_directive.minor != 1
&& version_directive.minor != 2
)) {
- return yaml_emitter_set_emitter_error(emitter,
- "incompatible %YAML directive");
- }
-
- return 1;
-}
-
-/*
- * Check if a %TAG directive is valid.
- */
-
-static int
-yaml_emitter_analyze_tag_directive(yaml_emitter_t *emitter,
- yaml_tag_directive_t tag_directive)
-{
- yaml_string_t handle;
- yaml_string_t prefix;
- size_t handle_length;
- size_t prefix_length;
-
- handle_length = strlen((char *)tag_directive.handle);
- prefix_length = strlen((char *)tag_directive.prefix);
- STRING_ASSIGN(handle, tag_directive.handle, handle_length);
- STRING_ASSIGN(prefix, tag_directive.prefix, prefix_length);
-
- if (handle.start == handle.end) {
- return yaml_emitter_set_emitter_error(emitter,
- "tag handle must not be empty");
- }
-
- if (handle.start[0] != '!') {
- return yaml_emitter_set_emitter_error(emitter,
- "tag handle must start with '!'");
- }
-
- if (handle.end[-1] != '!') {
- return yaml_emitter_set_emitter_error(emitter,
- "tag handle must end with '!'");
- }
-
- handle.pointer ++;
-
- while (handle.pointer < handle.end-1) {
- if (!IS_ALPHA(handle)) {
- return yaml_emitter_set_emitter_error(emitter,
- "tag handle must contain alphanumerical characters only");
- }
- MOVE(handle);
- }
-
- if (prefix.start == prefix.end) {
- return yaml_emitter_set_emitter_error(emitter,
- "tag prefix must not be empty");
- }
-
- return 1;
-}
-
-/*
- * Check if an anchor is valid.
- */
-
-static int
-yaml_emitter_analyze_anchor(yaml_emitter_t *emitter,
- yaml_char_t *anchor, int alias)
-{
- size_t anchor_length;
- yaml_string_t string;
-
- anchor_length = strlen((char *)anchor);
- STRING_ASSIGN(string, anchor, anchor_length);
-
- if (string.start == string.end) {
- return yaml_emitter_set_emitter_error(emitter, alias ?
- "alias value must not be empty" :
- "anchor value must not be empty");
- }
-
- while (string.pointer != string.end) {
- if (!IS_ALPHA(string)) {
- return yaml_emitter_set_emitter_error(emitter, alias ?
- "alias value must contain alphanumerical characters only" :
- "anchor value must contain alphanumerical characters only");
- }
- MOVE(string);
- }
-
- emitter->anchor_data.anchor = string.start;
- emitter->anchor_data.anchor_length = string.end - string.start;
- emitter->anchor_data.alias = alias;
-
- return 1;
-}
-
-/*
- * Check if a tag is valid.
- */
-
-static int
-yaml_emitter_analyze_tag(yaml_emitter_t *emitter,
- yaml_char_t *tag)
-{
- size_t tag_length;
- yaml_string_t string;
- yaml_tag_directive_t *tag_directive;
-
- tag_length = strlen((char *)tag);
- STRING_ASSIGN(string, tag, tag_length);
-
- if (string.start == string.end) {
- return yaml_emitter_set_emitter_error(emitter,
- "tag value must not be empty");
- }
-
- for (tag_directive = emitter->tag_directives.start;
- tag_directive != emitter->tag_directives.top; tag_directive ++) {
- size_t prefix_length = strlen((char *)tag_directive->prefix);
- if (prefix_length < (size_t)(string.end - string.start)
- && strncmp((char *)tag_directive->prefix, (char *)string.start,
- prefix_length) == 0)
- {
- emitter->tag_data.handle = tag_directive->handle;
- emitter->tag_data.handle_length =
- strlen((char *)tag_directive->handle);
- emitter->tag_data.suffix = string.start + prefix_length;
- emitter->tag_data.suffix_length =
- (string.end - string.start) - prefix_length;
- return 1;
- }
- }
-
- emitter->tag_data.suffix = string.start;
- emitter->tag_data.suffix_length = string.end - string.start;
-
- return 1;
-}
-
-/*
- * Check if a scalar is valid.
- */
-
-static int
-yaml_emitter_analyze_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length)
-{
- yaml_string_t string;
-
- int block_indicators = 0;
- int flow_indicators = 0;
- int line_breaks = 0;
- int special_characters = 0;
-
- int leading_space = 0;
- int leading_break = 0;
- int trailing_space = 0;
- int trailing_break = 0;
- int break_space = 0;
- int space_break = 0;
-
+ return yaml_emitter_set_emitter_error(emitter,
+ "incompatible %YAML directive");
+ }
+
+ return 1;
+}
+
+/*
+ * Check if a %TAG directive is valid.
+ */
+
+static int
+yaml_emitter_analyze_tag_directive(yaml_emitter_t *emitter,
+ yaml_tag_directive_t tag_directive)
+{
+ yaml_string_t handle;
+ yaml_string_t prefix;
+ size_t handle_length;
+ size_t prefix_length;
+
+ handle_length = strlen((char *)tag_directive.handle);
+ prefix_length = strlen((char *)tag_directive.prefix);
+ STRING_ASSIGN(handle, tag_directive.handle, handle_length);
+ STRING_ASSIGN(prefix, tag_directive.prefix, prefix_length);
+
+ if (handle.start == handle.end) {
+ return yaml_emitter_set_emitter_error(emitter,
+ "tag handle must not be empty");
+ }
+
+ if (handle.start[0] != '!') {
+ return yaml_emitter_set_emitter_error(emitter,
+ "tag handle must start with '!'");
+ }
+
+ if (handle.end[-1] != '!') {
+ return yaml_emitter_set_emitter_error(emitter,
+ "tag handle must end with '!'");
+ }
+
+ handle.pointer ++;
+
+ while (handle.pointer < handle.end-1) {
+ if (!IS_ALPHA(handle)) {
+ return yaml_emitter_set_emitter_error(emitter,
+ "tag handle must contain alphanumerical characters only");
+ }
+ MOVE(handle);
+ }
+
+ if (prefix.start == prefix.end) {
+ return yaml_emitter_set_emitter_error(emitter,
+ "tag prefix must not be empty");
+ }
+
+ return 1;
+}
+
+/*
+ * Check if an anchor is valid.
+ */
+
+static int
+yaml_emitter_analyze_anchor(yaml_emitter_t *emitter,
+ yaml_char_t *anchor, int alias)
+{
+ size_t anchor_length;
+ yaml_string_t string;
+
+ anchor_length = strlen((char *)anchor);
+ STRING_ASSIGN(string, anchor, anchor_length);
+
+ if (string.start == string.end) {
+ return yaml_emitter_set_emitter_error(emitter, alias ?
+ "alias value must not be empty" :
+ "anchor value must not be empty");
+ }
+
+ while (string.pointer != string.end) {
+ if (!IS_ALPHA(string)) {
+ return yaml_emitter_set_emitter_error(emitter, alias ?
+ "alias value must contain alphanumerical characters only" :
+ "anchor value must contain alphanumerical characters only");
+ }
+ MOVE(string);
+ }
+
+ emitter->anchor_data.anchor = string.start;
+ emitter->anchor_data.anchor_length = string.end - string.start;
+ emitter->anchor_data.alias = alias;
+
+ return 1;
+}
+
+/*
+ * Check if a tag is valid.
+ */
+
+static int
+yaml_emitter_analyze_tag(yaml_emitter_t *emitter,
+ yaml_char_t *tag)
+{
+ size_t tag_length;
+ yaml_string_t string;
+ yaml_tag_directive_t *tag_directive;
+
+ tag_length = strlen((char *)tag);
+ STRING_ASSIGN(string, tag, tag_length);
+
+ if (string.start == string.end) {
+ return yaml_emitter_set_emitter_error(emitter,
+ "tag value must not be empty");
+ }
+
+ for (tag_directive = emitter->tag_directives.start;
+ tag_directive != emitter->tag_directives.top; tag_directive ++) {
+ size_t prefix_length = strlen((char *)tag_directive->prefix);
+ if (prefix_length < (size_t)(string.end - string.start)
+ && strncmp((char *)tag_directive->prefix, (char *)string.start,
+ prefix_length) == 0)
+ {
+ emitter->tag_data.handle = tag_directive->handle;
+ emitter->tag_data.handle_length =
+ strlen((char *)tag_directive->handle);
+ emitter->tag_data.suffix = string.start + prefix_length;
+ emitter->tag_data.suffix_length =
+ (string.end - string.start) - prefix_length;
+ return 1;
+ }
+ }
+
+ emitter->tag_data.suffix = string.start;
+ emitter->tag_data.suffix_length = string.end - string.start;
+
+ return 1;
+}
+
+/*
+ * Check if a scalar is valid.
+ */
+
+static int
+yaml_emitter_analyze_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length)
+{
+ yaml_string_t string;
+
+ int block_indicators = 0;
+ int flow_indicators = 0;
+ int line_breaks = 0;
+ int special_characters = 0;
+
+ int leading_space = 0;
+ int leading_break = 0;
+ int trailing_space = 0;
+ int trailing_break = 0;
+ int break_space = 0;
+ int space_break = 0;
+
int preceded_by_whitespace = 0;
- int followed_by_whitespace = 0;
- int previous_space = 0;
- int previous_break = 0;
-
- STRING_ASSIGN(string, value, length);
-
- emitter->scalar_data.value = value;
- emitter->scalar_data.length = length;
-
- if (string.start == string.end)
- {
- emitter->scalar_data.multiline = 0;
- emitter->scalar_data.flow_plain_allowed = 0;
- emitter->scalar_data.block_plain_allowed = 1;
- emitter->scalar_data.single_quoted_allowed = 1;
- emitter->scalar_data.block_allowed = 0;
-
- return 1;
- }
-
- if ((CHECK_AT(string, '-', 0)
- && CHECK_AT(string, '-', 1)
- && CHECK_AT(string, '-', 2))
- || (CHECK_AT(string, '.', 0)
- && CHECK_AT(string, '.', 1)
- && CHECK_AT(string, '.', 2))) {
- block_indicators = 1;
- flow_indicators = 1;
- }
-
+ int followed_by_whitespace = 0;
+ int previous_space = 0;
+ int previous_break = 0;
+
+ STRING_ASSIGN(string, value, length);
+
+ emitter->scalar_data.value = value;
+ emitter->scalar_data.length = length;
+
+ if (string.start == string.end)
+ {
+ emitter->scalar_data.multiline = 0;
+ emitter->scalar_data.flow_plain_allowed = 0;
+ emitter->scalar_data.block_plain_allowed = 1;
+ emitter->scalar_data.single_quoted_allowed = 1;
+ emitter->scalar_data.block_allowed = 0;
+
+ return 1;
+ }
+
+ if ((CHECK_AT(string, '-', 0)
+ && CHECK_AT(string, '-', 1)
+ && CHECK_AT(string, '-', 2))
+ || (CHECK_AT(string, '.', 0)
+ && CHECK_AT(string, '.', 1)
+ && CHECK_AT(string, '.', 2))) {
+ block_indicators = 1;
+ flow_indicators = 1;
+ }
+
preceded_by_whitespace = 1;
- followed_by_whitespace = IS_BLANKZ_AT(string, WIDTH(string));
-
- while (string.pointer != string.end)
- {
- if (string.start == string.pointer)
- {
- if (CHECK(string, '#') || CHECK(string, ',')
- || CHECK(string, '[') || CHECK(string, ']')
- || CHECK(string, '{') || CHECK(string, '}')
- || CHECK(string, '&') || CHECK(string, '*')
- || CHECK(string, '!') || CHECK(string, '|')
- || CHECK(string, '>') || CHECK(string, '\'')
- || CHECK(string, '"') || CHECK(string, '%')
- || CHECK(string, '@') || CHECK(string, '`')) {
- flow_indicators = 1;
- block_indicators = 1;
- }
-
- if (CHECK(string, '?') || CHECK(string, ':')) {
- flow_indicators = 1;
- if (followed_by_whitespace) {
- block_indicators = 1;
- }
- }
-
- if (CHECK(string, '-') && followed_by_whitespace) {
- flow_indicators = 1;
- block_indicators = 1;
- }
- }
- else
- {
- if (CHECK(string, ',') || CHECK(string, '?')
- || CHECK(string, '[') || CHECK(string, ']')
- || CHECK(string, '{') || CHECK(string, '}')) {
- flow_indicators = 1;
- }
-
- if (CHECK(string, ':')) {
- flow_indicators = 1;
- if (followed_by_whitespace) {
- block_indicators = 1;
- }
- }
-
+ followed_by_whitespace = IS_BLANKZ_AT(string, WIDTH(string));
+
+ while (string.pointer != string.end)
+ {
+ if (string.start == string.pointer)
+ {
+ if (CHECK(string, '#') || CHECK(string, ',')
+ || CHECK(string, '[') || CHECK(string, ']')
+ || CHECK(string, '{') || CHECK(string, '}')
+ || CHECK(string, '&') || CHECK(string, '*')
+ || CHECK(string, '!') || CHECK(string, '|')
+ || CHECK(string, '>') || CHECK(string, '\'')
+ || CHECK(string, '"') || CHECK(string, '%')
+ || CHECK(string, '@') || CHECK(string, '`')) {
+ flow_indicators = 1;
+ block_indicators = 1;
+ }
+
+ if (CHECK(string, '?') || CHECK(string, ':')) {
+ flow_indicators = 1;
+ if (followed_by_whitespace) {
+ block_indicators = 1;
+ }
+ }
+
+ if (CHECK(string, '-') && followed_by_whitespace) {
+ flow_indicators = 1;
+ block_indicators = 1;
+ }
+ }
+ else
+ {
+ if (CHECK(string, ',') || CHECK(string, '?')
+ || CHECK(string, '[') || CHECK(string, ']')
+ || CHECK(string, '{') || CHECK(string, '}')) {
+ flow_indicators = 1;
+ }
+
+ if (CHECK(string, ':')) {
+ flow_indicators = 1;
+ if (followed_by_whitespace) {
+ block_indicators = 1;
+ }
+ }
+
if (CHECK(string, '#') && preceded_by_whitespace) {
- flow_indicators = 1;
- block_indicators = 1;
- }
- }
-
- if (!IS_PRINTABLE(string)
- || (!IS_ASCII(string) && !emitter->unicode)) {
- special_characters = 1;
- }
-
- if (IS_BREAK(string)) {
- line_breaks = 1;
- }
-
- if (IS_SPACE(string))
- {
- if (string.start == string.pointer) {
- leading_space = 1;
- }
- if (string.pointer+WIDTH(string) == string.end) {
- trailing_space = 1;
- }
- if (previous_break) {
- break_space = 1;
- }
- previous_space = 1;
- previous_break = 0;
- }
- else if (IS_BREAK(string))
- {
- if (string.start == string.pointer) {
- leading_break = 1;
- }
- if (string.pointer+WIDTH(string) == string.end) {
- trailing_break = 1;
- }
- if (previous_space) {
- space_break = 1;
- }
- previous_space = 0;
- previous_break = 1;
- }
- else
- {
- previous_space = 0;
- previous_break = 0;
- }
-
+ flow_indicators = 1;
+ block_indicators = 1;
+ }
+ }
+
+ if (!IS_PRINTABLE(string)
+ || (!IS_ASCII(string) && !emitter->unicode)) {
+ special_characters = 1;
+ }
+
+ if (IS_BREAK(string)) {
+ line_breaks = 1;
+ }
+
+ if (IS_SPACE(string))
+ {
+ if (string.start == string.pointer) {
+ leading_space = 1;
+ }
+ if (string.pointer+WIDTH(string) == string.end) {
+ trailing_space = 1;
+ }
+ if (previous_break) {
+ break_space = 1;
+ }
+ previous_space = 1;
+ previous_break = 0;
+ }
+ else if (IS_BREAK(string))
+ {
+ if (string.start == string.pointer) {
+ leading_break = 1;
+ }
+ if (string.pointer+WIDTH(string) == string.end) {
+ trailing_break = 1;
+ }
+ if (previous_space) {
+ space_break = 1;
+ }
+ previous_space = 0;
+ previous_break = 1;
+ }
+ else
+ {
+ previous_space = 0;
+ previous_break = 0;
+ }
+
preceded_by_whitespace = IS_BLANKZ(string);
- MOVE(string);
- if (string.pointer != string.end) {
- followed_by_whitespace = IS_BLANKZ_AT(string, WIDTH(string));
- }
- }
-
- emitter->scalar_data.multiline = line_breaks;
-
- emitter->scalar_data.flow_plain_allowed = 1;
- emitter->scalar_data.block_plain_allowed = 1;
- emitter->scalar_data.single_quoted_allowed = 1;
- emitter->scalar_data.block_allowed = 1;
-
- if (leading_space || leading_break || trailing_space || trailing_break) {
- emitter->scalar_data.flow_plain_allowed = 0;
- emitter->scalar_data.block_plain_allowed = 0;
- }
-
- if (trailing_space) {
- emitter->scalar_data.block_allowed = 0;
- }
-
- if (break_space) {
- emitter->scalar_data.flow_plain_allowed = 0;
- emitter->scalar_data.block_plain_allowed = 0;
- emitter->scalar_data.single_quoted_allowed = 0;
- }
-
- if (space_break || special_characters) {
- emitter->scalar_data.flow_plain_allowed = 0;
- emitter->scalar_data.block_plain_allowed = 0;
- emitter->scalar_data.single_quoted_allowed = 0;
- emitter->scalar_data.block_allowed = 0;
- }
-
- if (line_breaks) {
- emitter->scalar_data.flow_plain_allowed = 0;
- emitter->scalar_data.block_plain_allowed = 0;
- }
-
- if (flow_indicators) {
- emitter->scalar_data.flow_plain_allowed = 0;
- }
-
- if (block_indicators) {
- emitter->scalar_data.block_plain_allowed = 0;
- }
-
- return 1;
-}
-
-/*
- * Check if the event data is valid.
- */
-
-static int
-yaml_emitter_analyze_event(yaml_emitter_t *emitter,
- yaml_event_t *event)
-{
- emitter->anchor_data.anchor = NULL;
- emitter->anchor_data.anchor_length = 0;
- emitter->tag_data.handle = NULL;
- emitter->tag_data.handle_length = 0;
- emitter->tag_data.suffix = NULL;
- emitter->tag_data.suffix_length = 0;
- emitter->scalar_data.value = NULL;
- emitter->scalar_data.length = 0;
-
- switch (event->type)
- {
- case YAML_ALIAS_EVENT:
- if (!yaml_emitter_analyze_anchor(emitter,
- event->data.alias.anchor, 1))
- return 0;
- return 1;
-
- case YAML_SCALAR_EVENT:
- if (event->data.scalar.anchor) {
- if (!yaml_emitter_analyze_anchor(emitter,
- event->data.scalar.anchor, 0))
- return 0;
- }
- if (event->data.scalar.tag && (emitter->canonical ||
- (!event->data.scalar.plain_implicit
- && !event->data.scalar.quoted_implicit))) {
- if (!yaml_emitter_analyze_tag(emitter, event->data.scalar.tag))
- return 0;
- }
- if (!yaml_emitter_analyze_scalar(emitter,
- event->data.scalar.value, event->data.scalar.length))
- return 0;
- return 1;
-
- case YAML_SEQUENCE_START_EVENT:
- if (event->data.sequence_start.anchor) {
- if (!yaml_emitter_analyze_anchor(emitter,
- event->data.sequence_start.anchor, 0))
- return 0;
- }
- if (event->data.sequence_start.tag && (emitter->canonical ||
- !event->data.sequence_start.implicit)) {
- if (!yaml_emitter_analyze_tag(emitter,
- event->data.sequence_start.tag))
- return 0;
- }
- return 1;
-
- case YAML_MAPPING_START_EVENT:
- if (event->data.mapping_start.anchor) {
- if (!yaml_emitter_analyze_anchor(emitter,
- event->data.mapping_start.anchor, 0))
- return 0;
- }
- if (event->data.mapping_start.tag && (emitter->canonical ||
- !event->data.mapping_start.implicit)) {
- if (!yaml_emitter_analyze_tag(emitter,
- event->data.mapping_start.tag))
- return 0;
- }
- return 1;
-
- default:
- return 1;
- }
-}
-
-/*
- * Write the BOM character.
- */
-
-static int
-yaml_emitter_write_bom(yaml_emitter_t *emitter)
-{
- if (!FLUSH(emitter)) return 0;
-
- *(emitter->buffer.pointer++) = (yaml_char_t) '\xEF';
- *(emitter->buffer.pointer++) = (yaml_char_t) '\xBB';
- *(emitter->buffer.pointer++) = (yaml_char_t) '\xBF';
-
- return 1;
-}
-
-static int
-yaml_emitter_write_indent(yaml_emitter_t *emitter)
-{
- int indent = (emitter->indent >= 0) ? emitter->indent : 0;
-
- if (!emitter->indention || emitter->column > indent
- || (emitter->column == indent && !emitter->whitespace)) {
- if (!PUT_BREAK(emitter)) return 0;
- }
-
- while (emitter->column < indent) {
- if (!PUT(emitter, ' ')) return 0;
- }
-
- emitter->whitespace = 1;
- emitter->indention = 1;
-
- return 1;
-}
-
-static int
-yaml_emitter_write_indicator(yaml_emitter_t *emitter,
+ MOVE(string);
+ if (string.pointer != string.end) {
+ followed_by_whitespace = IS_BLANKZ_AT(string, WIDTH(string));
+ }
+ }
+
+ emitter->scalar_data.multiline = line_breaks;
+
+ emitter->scalar_data.flow_plain_allowed = 1;
+ emitter->scalar_data.block_plain_allowed = 1;
+ emitter->scalar_data.single_quoted_allowed = 1;
+ emitter->scalar_data.block_allowed = 1;
+
+ if (leading_space || leading_break || trailing_space || trailing_break) {
+ emitter->scalar_data.flow_plain_allowed = 0;
+ emitter->scalar_data.block_plain_allowed = 0;
+ }
+
+ if (trailing_space) {
+ emitter->scalar_data.block_allowed = 0;
+ }
+
+ if (break_space) {
+ emitter->scalar_data.flow_plain_allowed = 0;
+ emitter->scalar_data.block_plain_allowed = 0;
+ emitter->scalar_data.single_quoted_allowed = 0;
+ }
+
+ if (space_break || special_characters) {
+ emitter->scalar_data.flow_plain_allowed = 0;
+ emitter->scalar_data.block_plain_allowed = 0;
+ emitter->scalar_data.single_quoted_allowed = 0;
+ emitter->scalar_data.block_allowed = 0;
+ }
+
+ if (line_breaks) {
+ emitter->scalar_data.flow_plain_allowed = 0;
+ emitter->scalar_data.block_plain_allowed = 0;
+ }
+
+ if (flow_indicators) {
+ emitter->scalar_data.flow_plain_allowed = 0;
+ }
+
+ if (block_indicators) {
+ emitter->scalar_data.block_plain_allowed = 0;
+ }
+
+ return 1;
+}
+
+/*
+ * Check if the event data is valid.
+ */
+
+static int
+yaml_emitter_analyze_event(yaml_emitter_t *emitter,
+ yaml_event_t *event)
+{
+ emitter->anchor_data.anchor = NULL;
+ emitter->anchor_data.anchor_length = 0;
+ emitter->tag_data.handle = NULL;
+ emitter->tag_data.handle_length = 0;
+ emitter->tag_data.suffix = NULL;
+ emitter->tag_data.suffix_length = 0;
+ emitter->scalar_data.value = NULL;
+ emitter->scalar_data.length = 0;
+
+ switch (event->type)
+ {
+ case YAML_ALIAS_EVENT:
+ if (!yaml_emitter_analyze_anchor(emitter,
+ event->data.alias.anchor, 1))
+ return 0;
+ return 1;
+
+ case YAML_SCALAR_EVENT:
+ if (event->data.scalar.anchor) {
+ if (!yaml_emitter_analyze_anchor(emitter,
+ event->data.scalar.anchor, 0))
+ return 0;
+ }
+ if (event->data.scalar.tag && (emitter->canonical ||
+ (!event->data.scalar.plain_implicit
+ && !event->data.scalar.quoted_implicit))) {
+ if (!yaml_emitter_analyze_tag(emitter, event->data.scalar.tag))
+ return 0;
+ }
+ if (!yaml_emitter_analyze_scalar(emitter,
+ event->data.scalar.value, event->data.scalar.length))
+ return 0;
+ return 1;
+
+ case YAML_SEQUENCE_START_EVENT:
+ if (event->data.sequence_start.anchor) {
+ if (!yaml_emitter_analyze_anchor(emitter,
+ event->data.sequence_start.anchor, 0))
+ return 0;
+ }
+ if (event->data.sequence_start.tag && (emitter->canonical ||
+ !event->data.sequence_start.implicit)) {
+ if (!yaml_emitter_analyze_tag(emitter,
+ event->data.sequence_start.tag))
+ return 0;
+ }
+ return 1;
+
+ case YAML_MAPPING_START_EVENT:
+ if (event->data.mapping_start.anchor) {
+ if (!yaml_emitter_analyze_anchor(emitter,
+ event->data.mapping_start.anchor, 0))
+ return 0;
+ }
+ if (event->data.mapping_start.tag && (emitter->canonical ||
+ !event->data.mapping_start.implicit)) {
+ if (!yaml_emitter_analyze_tag(emitter,
+ event->data.mapping_start.tag))
+ return 0;
+ }
+ return 1;
+
+ default:
+ return 1;
+ }
+}
+
+/*
+ * Write the BOM character.
+ */
+
+static int
+yaml_emitter_write_bom(yaml_emitter_t *emitter)
+{
+ if (!FLUSH(emitter)) return 0;
+
+ *(emitter->buffer.pointer++) = (yaml_char_t) '\xEF';
+ *(emitter->buffer.pointer++) = (yaml_char_t) '\xBB';
+ *(emitter->buffer.pointer++) = (yaml_char_t) '\xBF';
+
+ return 1;
+}
+
+static int
+yaml_emitter_write_indent(yaml_emitter_t *emitter)
+{
+ int indent = (emitter->indent >= 0) ? emitter->indent : 0;
+
+ if (!emitter->indention || emitter->column > indent
+ || (emitter->column == indent && !emitter->whitespace)) {
+ if (!PUT_BREAK(emitter)) return 0;
+ }
+
+ while (emitter->column < indent) {
+ if (!PUT(emitter, ' ')) return 0;
+ }
+
+ emitter->whitespace = 1;
+ emitter->indention = 1;
+
+ return 1;
+}
+
+static int
+yaml_emitter_write_indicator(yaml_emitter_t *emitter,
const char *indicator, int need_whitespace,
- int is_whitespace, int is_indention)
-{
- size_t indicator_length;
- yaml_string_t string;
-
- indicator_length = strlen(indicator);
- STRING_ASSIGN(string, (yaml_char_t *)indicator, indicator_length);
-
- if (need_whitespace && !emitter->whitespace) {
- if (!PUT(emitter, ' ')) return 0;
- }
-
- while (string.pointer != string.end) {
- if (!WRITE(emitter, string)) return 0;
- }
-
- emitter->whitespace = is_whitespace;
- emitter->indention = (emitter->indention && is_indention);
-
- return 1;
-}
-
-static int
-yaml_emitter_write_anchor(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length)
-{
- yaml_string_t string;
- STRING_ASSIGN(string, value, length);
-
- while (string.pointer != string.end) {
- if (!WRITE(emitter, string)) return 0;
- }
-
- emitter->whitespace = 0;
- emitter->indention = 0;
-
- return 1;
-}
-
-static int
-yaml_emitter_write_tag_handle(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length)
-{
- yaml_string_t string;
- STRING_ASSIGN(string, value, length);
-
- if (!emitter->whitespace) {
- if (!PUT(emitter, ' ')) return 0;
- }
-
- while (string.pointer != string.end) {
- if (!WRITE(emitter, string)) return 0;
- }
-
- emitter->whitespace = 0;
- emitter->indention = 0;
-
- return 1;
-}
-
-static int
-yaml_emitter_write_tag_content(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length,
- int need_whitespace)
-{
- yaml_string_t string;
- STRING_ASSIGN(string, value, length);
-
- if (need_whitespace && !emitter->whitespace) {
- if (!PUT(emitter, ' ')) return 0;
- }
-
- while (string.pointer != string.end) {
- if (IS_ALPHA(string)
- || CHECK(string, ';') || CHECK(string, '/')
- || CHECK(string, '?') || CHECK(string, ':')
- || CHECK(string, '@') || CHECK(string, '&')
- || CHECK(string, '=') || CHECK(string, '+')
- || CHECK(string, '$') || CHECK(string, ',')
- || CHECK(string, '_') || CHECK(string, '.')
- || CHECK(string, '~') || CHECK(string, '*')
- || CHECK(string, '\'') || CHECK(string, '(')
- || CHECK(string, ')') || CHECK(string, '[')
- || CHECK(string, ']')) {
- if (!WRITE(emitter, string)) return 0;
- }
- else {
- int width = WIDTH(string);
- unsigned int value;
- while (width --) {
- value = *(string.pointer++);
- if (!PUT(emitter, '%')) return 0;
- if (!PUT(emitter, (value >> 4)
- + ((value >> 4) < 10 ? '0' : 'A' - 10)))
- return 0;
- if (!PUT(emitter, (value & 0x0F)
- + ((value & 0x0F) < 10 ? '0' : 'A' - 10)))
- return 0;
- }
- }
- }
-
- emitter->whitespace = 0;
- emitter->indention = 0;
-
- return 1;
-}
-
-static int
-yaml_emitter_write_plain_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length, int allow_breaks)
-{
- yaml_string_t string;
- int spaces = 0;
- int breaks = 0;
-
- STRING_ASSIGN(string, value, length);
-
+ int is_whitespace, int is_indention)
+{
+ size_t indicator_length;
+ yaml_string_t string;
+
+ indicator_length = strlen(indicator);
+ STRING_ASSIGN(string, (yaml_char_t *)indicator, indicator_length);
+
+ if (need_whitespace && !emitter->whitespace) {
+ if (!PUT(emitter, ' ')) return 0;
+ }
+
+ while (string.pointer != string.end) {
+ if (!WRITE(emitter, string)) return 0;
+ }
+
+ emitter->whitespace = is_whitespace;
+ emitter->indention = (emitter->indention && is_indention);
+
+ return 1;
+}
+
+static int
+yaml_emitter_write_anchor(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length)
+{
+ yaml_string_t string;
+ STRING_ASSIGN(string, value, length);
+
+ while (string.pointer != string.end) {
+ if (!WRITE(emitter, string)) return 0;
+ }
+
+ emitter->whitespace = 0;
+ emitter->indention = 0;
+
+ return 1;
+}
+
+static int
+yaml_emitter_write_tag_handle(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length)
+{
+ yaml_string_t string;
+ STRING_ASSIGN(string, value, length);
+
+ if (!emitter->whitespace) {
+ if (!PUT(emitter, ' ')) return 0;
+ }
+
+ while (string.pointer != string.end) {
+ if (!WRITE(emitter, string)) return 0;
+ }
+
+ emitter->whitespace = 0;
+ emitter->indention = 0;
+
+ return 1;
+}
+
+static int
+yaml_emitter_write_tag_content(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length,
+ int need_whitespace)
+{
+ yaml_string_t string;
+ STRING_ASSIGN(string, value, length);
+
+ if (need_whitespace && !emitter->whitespace) {
+ if (!PUT(emitter, ' ')) return 0;
+ }
+
+ while (string.pointer != string.end) {
+ if (IS_ALPHA(string)
+ || CHECK(string, ';') || CHECK(string, '/')
+ || CHECK(string, '?') || CHECK(string, ':')
+ || CHECK(string, '@') || CHECK(string, '&')
+ || CHECK(string, '=') || CHECK(string, '+')
+ || CHECK(string, '$') || CHECK(string, ',')
+ || CHECK(string, '_') || CHECK(string, '.')
+ || CHECK(string, '~') || CHECK(string, '*')
+ || CHECK(string, '\'') || CHECK(string, '(')
+ || CHECK(string, ')') || CHECK(string, '[')
+ || CHECK(string, ']')) {
+ if (!WRITE(emitter, string)) return 0;
+ }
+ else {
+ int width = WIDTH(string);
+ unsigned int value;
+ while (width --) {
+ value = *(string.pointer++);
+ if (!PUT(emitter, '%')) return 0;
+ if (!PUT(emitter, (value >> 4)
+ + ((value >> 4) < 10 ? '0' : 'A' - 10)))
+ return 0;
+ if (!PUT(emitter, (value & 0x0F)
+ + ((value & 0x0F) < 10 ? '0' : 'A' - 10)))
+ return 0;
+ }
+ }
+ }
+
+ emitter->whitespace = 0;
+ emitter->indention = 0;
+
+ return 1;
+}
+
+static int
+yaml_emitter_write_plain_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length, int allow_breaks)
+{
+ yaml_string_t string;
+ int spaces = 0;
+ int breaks = 0;
+
+ STRING_ASSIGN(string, value, length);
+
/**
* Avoid trailing spaces for empty values in block mode.
* In flow mode, we still want the space to prevent ambiguous things
@@ -1936,423 +1936,423 @@ yaml_emitter_write_plain_scalar(yaml_emitter_t *emitter,
* the check for flow_level is already here.
*/
if (!emitter->whitespace && (length || emitter->flow_level)) {
- if (!PUT(emitter, ' ')) return 0;
- }
-
- while (string.pointer != string.end)
- {
- if (IS_SPACE(string))
- {
- if (allow_breaks && !spaces
- && emitter->column > emitter->best_width
- && !IS_SPACE_AT(string, 1)) {
- if (!yaml_emitter_write_indent(emitter)) return 0;
- MOVE(string);
- }
- else {
- if (!WRITE(emitter, string)) return 0;
- }
- spaces = 1;
- }
- else if (IS_BREAK(string))
- {
- if (!breaks && CHECK(string, '\n')) {
- if (!PUT_BREAK(emitter)) return 0;
- }
- if (!WRITE_BREAK(emitter, string)) return 0;
- emitter->indention = 1;
- breaks = 1;
- }
- else
- {
- if (breaks) {
- if (!yaml_emitter_write_indent(emitter)) return 0;
- }
- if (!WRITE(emitter, string)) return 0;
- emitter->indention = 0;
- spaces = 0;
- breaks = 0;
- }
- }
-
- emitter->whitespace = 0;
- emitter->indention = 0;
-
- return 1;
-}
-
-static int
-yaml_emitter_write_single_quoted_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length, int allow_breaks)
-{
- yaml_string_t string;
- int spaces = 0;
- int breaks = 0;
-
- STRING_ASSIGN(string, value, length);
-
- if (!yaml_emitter_write_indicator(emitter, "'", 1, 0, 0))
- return 0;
-
- while (string.pointer != string.end)
- {
- if (IS_SPACE(string))
- {
- if (allow_breaks && !spaces
- && emitter->column > emitter->best_width
- && string.pointer != string.start
- && string.pointer != string.end - 1
- && !IS_SPACE_AT(string, 1)) {
- if (!yaml_emitter_write_indent(emitter)) return 0;
- MOVE(string);
- }
- else {
- if (!WRITE(emitter, string)) return 0;
- }
- spaces = 1;
- }
- else if (IS_BREAK(string))
- {
- if (!breaks && CHECK(string, '\n')) {
- if (!PUT_BREAK(emitter)) return 0;
- }
- if (!WRITE_BREAK(emitter, string)) return 0;
- emitter->indention = 1;
- breaks = 1;
- }
- else
- {
- if (breaks) {
- if (!yaml_emitter_write_indent(emitter)) return 0;
- }
- if (CHECK(string, '\'')) {
- if (!PUT(emitter, '\'')) return 0;
- }
- if (!WRITE(emitter, string)) return 0;
- emitter->indention = 0;
- spaces = 0;
- breaks = 0;
- }
- }
-
+ if (!PUT(emitter, ' ')) return 0;
+ }
+
+ while (string.pointer != string.end)
+ {
+ if (IS_SPACE(string))
+ {
+ if (allow_breaks && !spaces
+ && emitter->column > emitter->best_width
+ && !IS_SPACE_AT(string, 1)) {
+ if (!yaml_emitter_write_indent(emitter)) return 0;
+ MOVE(string);
+ }
+ else {
+ if (!WRITE(emitter, string)) return 0;
+ }
+ spaces = 1;
+ }
+ else if (IS_BREAK(string))
+ {
+ if (!breaks && CHECK(string, '\n')) {
+ if (!PUT_BREAK(emitter)) return 0;
+ }
+ if (!WRITE_BREAK(emitter, string)) return 0;
+ emitter->indention = 1;
+ breaks = 1;
+ }
+ else
+ {
+ if (breaks) {
+ if (!yaml_emitter_write_indent(emitter)) return 0;
+ }
+ if (!WRITE(emitter, string)) return 0;
+ emitter->indention = 0;
+ spaces = 0;
+ breaks = 0;
+ }
+ }
+
+ emitter->whitespace = 0;
+ emitter->indention = 0;
+
+ return 1;
+}
+
+static int
+yaml_emitter_write_single_quoted_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length, int allow_breaks)
+{
+ yaml_string_t string;
+ int spaces = 0;
+ int breaks = 0;
+
+ STRING_ASSIGN(string, value, length);
+
+ if (!yaml_emitter_write_indicator(emitter, "'", 1, 0, 0))
+ return 0;
+
+ while (string.pointer != string.end)
+ {
+ if (IS_SPACE(string))
+ {
+ if (allow_breaks && !spaces
+ && emitter->column > emitter->best_width
+ && string.pointer != string.start
+ && string.pointer != string.end - 1
+ && !IS_SPACE_AT(string, 1)) {
+ if (!yaml_emitter_write_indent(emitter)) return 0;
+ MOVE(string);
+ }
+ else {
+ if (!WRITE(emitter, string)) return 0;
+ }
+ spaces = 1;
+ }
+ else if (IS_BREAK(string))
+ {
+ if (!breaks && CHECK(string, '\n')) {
+ if (!PUT_BREAK(emitter)) return 0;
+ }
+ if (!WRITE_BREAK(emitter, string)) return 0;
+ emitter->indention = 1;
+ breaks = 1;
+ }
+ else
+ {
+ if (breaks) {
+ if (!yaml_emitter_write_indent(emitter)) return 0;
+ }
+ if (CHECK(string, '\'')) {
+ if (!PUT(emitter, '\'')) return 0;
+ }
+ if (!WRITE(emitter, string)) return 0;
+ emitter->indention = 0;
+ spaces = 0;
+ breaks = 0;
+ }
+ }
+
if (breaks)
if (!yaml_emitter_write_indent(emitter)) return 0;
- if (!yaml_emitter_write_indicator(emitter, "'", 0, 0, 0))
- return 0;
-
- emitter->whitespace = 0;
- emitter->indention = 0;
-
- return 1;
-}
-
-static int
-yaml_emitter_write_double_quoted_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length, int allow_breaks)
-{
- yaml_string_t string;
- int spaces = 0;
-
- STRING_ASSIGN(string, value, length);
-
- if (!yaml_emitter_write_indicator(emitter, "\"", 1, 0, 0))
- return 0;
-
- while (string.pointer != string.end)
- {
- if (!IS_PRINTABLE(string) || (!emitter->unicode && !IS_ASCII(string))
- || IS_BOM(string) || IS_BREAK(string)
- || CHECK(string, '"') || CHECK(string, '\\'))
- {
- unsigned char octet;
- unsigned int width;
- unsigned int value;
- int k;
-
- octet = string.pointer[0];
- width = (octet & 0x80) == 0x00 ? 1 :
- (octet & 0xE0) == 0xC0 ? 2 :
- (octet & 0xF0) == 0xE0 ? 3 :
- (octet & 0xF8) == 0xF0 ? 4 : 0;
- value = (octet & 0x80) == 0x00 ? octet & 0x7F :
- (octet & 0xE0) == 0xC0 ? octet & 0x1F :
- (octet & 0xF0) == 0xE0 ? octet & 0x0F :
- (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0;
- for (k = 1; k < (int)width; k ++) {
- octet = string.pointer[k];
- value = (value << 6) + (octet & 0x3F);
- }
- string.pointer += width;
-
- if (!PUT(emitter, '\\')) return 0;
-
- switch (value)
- {
- case 0x00:
- if (!PUT(emitter, '0')) return 0;
- break;
-
- case 0x07:
- if (!PUT(emitter, 'a')) return 0;
- break;
-
- case 0x08:
- if (!PUT(emitter, 'b')) return 0;
- break;
-
- case 0x09:
- if (!PUT(emitter, 't')) return 0;
- break;
-
- case 0x0A:
- if (!PUT(emitter, 'n')) return 0;
- break;
-
- case 0x0B:
- if (!PUT(emitter, 'v')) return 0;
- break;
-
- case 0x0C:
- if (!PUT(emitter, 'f')) return 0;
- break;
-
- case 0x0D:
- if (!PUT(emitter, 'r')) return 0;
- break;
-
- case 0x1B:
- if (!PUT(emitter, 'e')) return 0;
- break;
-
- case 0x22:
- if (!PUT(emitter, '\"')) return 0;
- break;
-
- case 0x5C:
- if (!PUT(emitter, '\\')) return 0;
- break;
-
- case 0x85:
- if (!PUT(emitter, 'N')) return 0;
- break;
-
- case 0xA0:
- if (!PUT(emitter, '_')) return 0;
- break;
-
- case 0x2028:
- if (!PUT(emitter, 'L')) return 0;
- break;
-
- case 0x2029:
- if (!PUT(emitter, 'P')) return 0;
- break;
-
- default:
- if (value <= 0xFF) {
- if (!PUT(emitter, 'x')) return 0;
- width = 2;
- }
- else if (value <= 0xFFFF) {
- if (!PUT(emitter, 'u')) return 0;
- width = 4;
- }
- else {
- if (!PUT(emitter, 'U')) return 0;
- width = 8;
- }
- for (k = (width-1)*4; k >= 0; k -= 4) {
- int digit = (value >> k) & 0x0F;
- if (!PUT(emitter, digit + (digit < 10 ? '0' : 'A'-10)))
- return 0;
- }
- }
- spaces = 0;
- }
- else if (IS_SPACE(string))
- {
- if (allow_breaks && !spaces
- && emitter->column > emitter->best_width
- && string.pointer != string.start
- && string.pointer != string.end - 1) {
- if (!yaml_emitter_write_indent(emitter)) return 0;
- if (IS_SPACE_AT(string, 1)) {
- if (!PUT(emitter, '\\')) return 0;
- }
- MOVE(string);
- }
- else {
- if (!WRITE(emitter, string)) return 0;
- }
- spaces = 1;
- }
- else
- {
- if (!WRITE(emitter, string)) return 0;
- spaces = 0;
- }
- }
-
- if (!yaml_emitter_write_indicator(emitter, "\"", 0, 0, 0))
- return 0;
-
- emitter->whitespace = 0;
- emitter->indention = 0;
-
- return 1;
-}
-
-static int
-yaml_emitter_write_block_scalar_hints(yaml_emitter_t *emitter,
- yaml_string_t string)
-{
- char indent_hint[2];
+ if (!yaml_emitter_write_indicator(emitter, "'", 0, 0, 0))
+ return 0;
+
+ emitter->whitespace = 0;
+ emitter->indention = 0;
+
+ return 1;
+}
+
+static int
+yaml_emitter_write_double_quoted_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length, int allow_breaks)
+{
+ yaml_string_t string;
+ int spaces = 0;
+
+ STRING_ASSIGN(string, value, length);
+
+ if (!yaml_emitter_write_indicator(emitter, "\"", 1, 0, 0))
+ return 0;
+
+ while (string.pointer != string.end)
+ {
+ if (!IS_PRINTABLE(string) || (!emitter->unicode && !IS_ASCII(string))
+ || IS_BOM(string) || IS_BREAK(string)
+ || CHECK(string, '"') || CHECK(string, '\\'))
+ {
+ unsigned char octet;
+ unsigned int width;
+ unsigned int value;
+ int k;
+
+ octet = string.pointer[0];
+ width = (octet & 0x80) == 0x00 ? 1 :
+ (octet & 0xE0) == 0xC0 ? 2 :
+ (octet & 0xF0) == 0xE0 ? 3 :
+ (octet & 0xF8) == 0xF0 ? 4 : 0;
+ value = (octet & 0x80) == 0x00 ? octet & 0x7F :
+ (octet & 0xE0) == 0xC0 ? octet & 0x1F :
+ (octet & 0xF0) == 0xE0 ? octet & 0x0F :
+ (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0;
+ for (k = 1; k < (int)width; k ++) {
+ octet = string.pointer[k];
+ value = (value << 6) + (octet & 0x3F);
+ }
+ string.pointer += width;
+
+ if (!PUT(emitter, '\\')) return 0;
+
+ switch (value)
+ {
+ case 0x00:
+ if (!PUT(emitter, '0')) return 0;
+ break;
+
+ case 0x07:
+ if (!PUT(emitter, 'a')) return 0;
+ break;
+
+ case 0x08:
+ if (!PUT(emitter, 'b')) return 0;
+ break;
+
+ case 0x09:
+ if (!PUT(emitter, 't')) return 0;
+ break;
+
+ case 0x0A:
+ if (!PUT(emitter, 'n')) return 0;
+ break;
+
+ case 0x0B:
+ if (!PUT(emitter, 'v')) return 0;
+ break;
+
+ case 0x0C:
+ if (!PUT(emitter, 'f')) return 0;
+ break;
+
+ case 0x0D:
+ if (!PUT(emitter, 'r')) return 0;
+ break;
+
+ case 0x1B:
+ if (!PUT(emitter, 'e')) return 0;
+ break;
+
+ case 0x22:
+ if (!PUT(emitter, '\"')) return 0;
+ break;
+
+ case 0x5C:
+ if (!PUT(emitter, '\\')) return 0;
+ break;
+
+ case 0x85:
+ if (!PUT(emitter, 'N')) return 0;
+ break;
+
+ case 0xA0:
+ if (!PUT(emitter, '_')) return 0;
+ break;
+
+ case 0x2028:
+ if (!PUT(emitter, 'L')) return 0;
+ break;
+
+ case 0x2029:
+ if (!PUT(emitter, 'P')) return 0;
+ break;
+
+ default:
+ if (value <= 0xFF) {
+ if (!PUT(emitter, 'x')) return 0;
+ width = 2;
+ }
+ else if (value <= 0xFFFF) {
+ if (!PUT(emitter, 'u')) return 0;
+ width = 4;
+ }
+ else {
+ if (!PUT(emitter, 'U')) return 0;
+ width = 8;
+ }
+ for (k = (width-1)*4; k >= 0; k -= 4) {
+ int digit = (value >> k) & 0x0F;
+ if (!PUT(emitter, digit + (digit < 10 ? '0' : 'A'-10)))
+ return 0;
+ }
+ }
+ spaces = 0;
+ }
+ else if (IS_SPACE(string))
+ {
+ if (allow_breaks && !spaces
+ && emitter->column > emitter->best_width
+ && string.pointer != string.start
+ && string.pointer != string.end - 1) {
+ if (!yaml_emitter_write_indent(emitter)) return 0;
+ if (IS_SPACE_AT(string, 1)) {
+ if (!PUT(emitter, '\\')) return 0;
+ }
+ MOVE(string);
+ }
+ else {
+ if (!WRITE(emitter, string)) return 0;
+ }
+ spaces = 1;
+ }
+ else
+ {
+ if (!WRITE(emitter, string)) return 0;
+ spaces = 0;
+ }
+ }
+
+ if (!yaml_emitter_write_indicator(emitter, "\"", 0, 0, 0))
+ return 0;
+
+ emitter->whitespace = 0;
+ emitter->indention = 0;
+
+ return 1;
+}
+
+static int
+yaml_emitter_write_block_scalar_hints(yaml_emitter_t *emitter,
+ yaml_string_t string)
+{
+ char indent_hint[2];
const char *chomp_hint = NULL;
-
- if (IS_SPACE(string) || IS_BREAK(string))
- {
- indent_hint[0] = '0' + (char)emitter->best_indent;
- indent_hint[1] = '\0';
- if (!yaml_emitter_write_indicator(emitter, indent_hint, 0, 0, 0))
- return 0;
- }
-
- emitter->open_ended = 0;
-
- string.pointer = string.end;
- if (string.start == string.pointer)
- {
- chomp_hint = "-";
- }
- else
- {
- do {
- string.pointer --;
- } while ((*string.pointer & 0xC0) == 0x80);
- if (!IS_BREAK(string))
- {
- chomp_hint = "-";
- }
- else if (string.start == string.pointer)
- {
- chomp_hint = "+";
+
+ if (IS_SPACE(string) || IS_BREAK(string))
+ {
+ indent_hint[0] = '0' + (char)emitter->best_indent;
+ indent_hint[1] = '\0';
+ if (!yaml_emitter_write_indicator(emitter, indent_hint, 0, 0, 0))
+ return 0;
+ }
+
+ emitter->open_ended = 0;
+
+ string.pointer = string.end;
+ if (string.start == string.pointer)
+ {
+ chomp_hint = "-";
+ }
+ else
+ {
+ do {
+ string.pointer --;
+ } while ((*string.pointer & 0xC0) == 0x80);
+ if (!IS_BREAK(string))
+ {
+ chomp_hint = "-";
+ }
+ else if (string.start == string.pointer)
+ {
+ chomp_hint = "+";
emitter->open_ended = 2;
- }
- else
- {
- do {
- string.pointer --;
- } while ((*string.pointer & 0xC0) == 0x80);
- if (IS_BREAK(string))
- {
- chomp_hint = "+";
+ }
+ else
+ {
+ do {
+ string.pointer --;
+ } while ((*string.pointer & 0xC0) == 0x80);
+ if (IS_BREAK(string))
+ {
+ chomp_hint = "+";
emitter->open_ended = 2;
- }
- }
- }
-
- if (chomp_hint)
- {
- if (!yaml_emitter_write_indicator(emitter, chomp_hint, 0, 0, 0))
- return 0;
- }
-
- return 1;
-}
-
-static int
-yaml_emitter_write_literal_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length)
-{
- yaml_string_t string;
- int breaks = 1;
-
- STRING_ASSIGN(string, value, length);
-
- if (!yaml_emitter_write_indicator(emitter, "|", 1, 0, 0))
- return 0;
- if (!yaml_emitter_write_block_scalar_hints(emitter, string))
- return 0;
- if (!PUT_BREAK(emitter)) return 0;
- emitter->indention = 1;
- emitter->whitespace = 1;
-
- while (string.pointer != string.end)
- {
- if (IS_BREAK(string))
- {
- if (!WRITE_BREAK(emitter, string)) return 0;
- emitter->indention = 1;
- breaks = 1;
- }
- else
- {
- if (breaks) {
- if (!yaml_emitter_write_indent(emitter)) return 0;
- }
- if (!WRITE(emitter, string)) return 0;
- emitter->indention = 0;
- breaks = 0;
- }
- }
-
- return 1;
-}
-
-static int
-yaml_emitter_write_folded_scalar(yaml_emitter_t *emitter,
- yaml_char_t *value, size_t length)
-{
- yaml_string_t string;
- int breaks = 1;
- int leading_spaces = 1;
-
- STRING_ASSIGN(string, value, length);
-
- if (!yaml_emitter_write_indicator(emitter, ">", 1, 0, 0))
- return 0;
- if (!yaml_emitter_write_block_scalar_hints(emitter, string))
- return 0;
- if (!PUT_BREAK(emitter)) return 0;
- emitter->indention = 1;
- emitter->whitespace = 1;
-
- while (string.pointer != string.end)
- {
- if (IS_BREAK(string))
- {
- if (!breaks && !leading_spaces && CHECK(string, '\n')) {
- int k = 0;
- while (IS_BREAK_AT(string, k)) {
- k += WIDTH_AT(string, k);
- }
- if (!IS_BLANKZ_AT(string, k)) {
- if (!PUT_BREAK(emitter)) return 0;
- }
- }
- if (!WRITE_BREAK(emitter, string)) return 0;
- emitter->indention = 1;
- breaks = 1;
- }
- else
- {
- if (breaks) {
- if (!yaml_emitter_write_indent(emitter)) return 0;
- leading_spaces = IS_BLANK(string);
- }
- if (!breaks && IS_SPACE(string) && !IS_SPACE_AT(string, 1)
- && emitter->column > emitter->best_width) {
- if (!yaml_emitter_write_indent(emitter)) return 0;
- MOVE(string);
- }
- else {
- if (!WRITE(emitter, string)) return 0;
- }
- emitter->indention = 0;
- breaks = 0;
- }
- }
-
- return 1;
-}
+ }
+ }
+ }
+
+ if (chomp_hint)
+ {
+ if (!yaml_emitter_write_indicator(emitter, chomp_hint, 0, 0, 0))
+ return 0;
+ }
+
+ return 1;
+}
+
+static int
+yaml_emitter_write_literal_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length)
+{
+ yaml_string_t string;
+ int breaks = 1;
+
+ STRING_ASSIGN(string, value, length);
+
+ if (!yaml_emitter_write_indicator(emitter, "|", 1, 0, 0))
+ return 0;
+ if (!yaml_emitter_write_block_scalar_hints(emitter, string))
+ return 0;
+ if (!PUT_BREAK(emitter)) return 0;
+ emitter->indention = 1;
+ emitter->whitespace = 1;
+
+ while (string.pointer != string.end)
+ {
+ if (IS_BREAK(string))
+ {
+ if (!WRITE_BREAK(emitter, string)) return 0;
+ emitter->indention = 1;
+ breaks = 1;
+ }
+ else
+ {
+ if (breaks) {
+ if (!yaml_emitter_write_indent(emitter)) return 0;
+ }
+ if (!WRITE(emitter, string)) return 0;
+ emitter->indention = 0;
+ breaks = 0;
+ }
+ }
+
+ return 1;
+}
+
+static int
+yaml_emitter_write_folded_scalar(yaml_emitter_t *emitter,
+ yaml_char_t *value, size_t length)
+{
+ yaml_string_t string;
+ int breaks = 1;
+ int leading_spaces = 1;
+
+ STRING_ASSIGN(string, value, length);
+
+ if (!yaml_emitter_write_indicator(emitter, ">", 1, 0, 0))
+ return 0;
+ if (!yaml_emitter_write_block_scalar_hints(emitter, string))
+ return 0;
+ if (!PUT_BREAK(emitter)) return 0;
+ emitter->indention = 1;
+ emitter->whitespace = 1;
+
+ while (string.pointer != string.end)
+ {
+ if (IS_BREAK(string))
+ {
+ if (!breaks && !leading_spaces && CHECK(string, '\n')) {
+ int k = 0;
+ while (IS_BREAK_AT(string, k)) {
+ k += WIDTH_AT(string, k);
+ }
+ if (!IS_BLANKZ_AT(string, k)) {
+ if (!PUT_BREAK(emitter)) return 0;
+ }
+ }
+ if (!WRITE_BREAK(emitter, string)) return 0;
+ emitter->indention = 1;
+ breaks = 1;
+ }
+ else
+ {
+ if (breaks) {
+ if (!yaml_emitter_write_indent(emitter)) return 0;
+ leading_spaces = IS_BLANK(string);
+ }
+ if (!breaks && IS_SPACE(string) && !IS_SPACE_AT(string, 1)
+ && emitter->column > emitter->best_width) {
+ if (!yaml_emitter_write_indent(emitter)) return 0;
+ MOVE(string);
+ }
+ else {
+ if (!WRITE(emitter, string)) return 0;
+ }
+ emitter->indention = 0;
+ breaks = 0;
+ }
+ }
+
+ return 1;
+}
diff --git a/contrib/libs/yaml/src/loader.c b/contrib/libs/yaml/src/loader.c
index e77b07b43f..dea8ac428c 100644
--- a/contrib/libs/yaml/src/loader.c
+++ b/contrib/libs/yaml/src/loader.c
@@ -1,43 +1,43 @@
-
-#include "yaml_private.h"
-
-/*
- * API functions.
- */
-
-YAML_DECLARE(int)
-yaml_parser_load(yaml_parser_t *parser, yaml_document_t *document);
-
-/*
- * Error handling.
- */
-
-static int
-yaml_parser_set_composer_error(yaml_parser_t *parser,
- const char *problem, yaml_mark_t problem_mark);
-
-static int
-yaml_parser_set_composer_error_context(yaml_parser_t *parser,
- const char *context, yaml_mark_t context_mark,
- const char *problem, yaml_mark_t problem_mark);
-
-
-/*
- * Alias handling.
- */
-
-static int
-yaml_parser_register_anchor(yaml_parser_t *parser,
- int index, yaml_char_t *anchor);
-
-/*
- * Clean up functions.
- */
-
-static void
-yaml_parser_delete_aliases(yaml_parser_t *parser);
-
-/*
+
+#include "yaml_private.h"
+
+/*
+ * API functions.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_load(yaml_parser_t *parser, yaml_document_t *document);
+
+/*
+ * Error handling.
+ */
+
+static int
+yaml_parser_set_composer_error(yaml_parser_t *parser,
+ const char *problem, yaml_mark_t problem_mark);
+
+static int
+yaml_parser_set_composer_error_context(yaml_parser_t *parser,
+ const char *context, yaml_mark_t context_mark,
+ const char *problem, yaml_mark_t problem_mark);
+
+
+/*
+ * Alias handling.
+ */
+
+static int
+yaml_parser_register_anchor(yaml_parser_t *parser,
+ int index, yaml_char_t *anchor);
+
+/*
+ * Clean up functions.
+ */
+
+static void
+yaml_parser_delete_aliases(yaml_parser_t *parser);
+
+/*
* Document loading context.
*/
struct loader_ctx {
@@ -47,177 +47,177 @@ struct loader_ctx {
};
/*
- * Composer functions.
- */
+ * Composer functions.
+ */
static int
yaml_parser_load_nodes(yaml_parser_t *parser, struct loader_ctx *ctx);
-
-static int
+
+static int
yaml_parser_load_document(yaml_parser_t *parser, yaml_event_t *event);
-
-static int
+
+static int
yaml_parser_load_alias(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx);
-
-static int
+
+static int
yaml_parser_load_scalar(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx);
-
-static int
+
+static int
yaml_parser_load_sequence(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx);
-
-static int
+
+static int
yaml_parser_load_mapping(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx);
-
-static int
+
+static int
yaml_parser_load_sequence_end(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx);
-
+
static int
yaml_parser_load_mapping_end(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx);
-/*
- * Load the next document of the stream.
- */
-
-YAML_DECLARE(int)
-yaml_parser_load(yaml_parser_t *parser, yaml_document_t *document)
-{
- yaml_event_t event;
-
- assert(parser); /* Non-NULL parser object is expected. */
- assert(document); /* Non-NULL document object is expected. */
-
- memset(document, 0, sizeof(yaml_document_t));
+/*
+ * Load the next document of the stream.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_load(yaml_parser_t *parser, yaml_document_t *document)
+{
+ yaml_event_t event;
+
+ assert(parser); /* Non-NULL parser object is expected. */
+ assert(document); /* Non-NULL document object is expected. */
+
+ memset(document, 0, sizeof(yaml_document_t));
if (!STACK_INIT(parser, document->nodes, yaml_node_t*))
- goto error;
-
- if (!parser->stream_start_produced) {
- if (!yaml_parser_parse(parser, &event)) goto error;
- assert(event.type == YAML_STREAM_START_EVENT);
- /* STREAM-START is expected. */
- }
-
- if (parser->stream_end_produced) {
- return 1;
- }
-
- if (!yaml_parser_parse(parser, &event)) goto error;
- if (event.type == YAML_STREAM_END_EVENT) {
- return 1;
- }
-
+ goto error;
+
+ if (!parser->stream_start_produced) {
+ if (!yaml_parser_parse(parser, &event)) goto error;
+ assert(event.type == YAML_STREAM_START_EVENT);
+ /* STREAM-START is expected. */
+ }
+
+ if (parser->stream_end_produced) {
+ return 1;
+ }
+
+ if (!yaml_parser_parse(parser, &event)) goto error;
+ if (event.type == YAML_STREAM_END_EVENT) {
+ return 1;
+ }
+
if (!STACK_INIT(parser, parser->aliases, yaml_alias_data_t*))
- goto error;
-
- parser->document = document;
-
- if (!yaml_parser_load_document(parser, &event)) goto error;
-
- yaml_parser_delete_aliases(parser);
- parser->document = NULL;
-
- return 1;
-
-error:
-
- yaml_parser_delete_aliases(parser);
- yaml_document_delete(document);
- parser->document = NULL;
-
- return 0;
-}
-
-/*
- * Set composer error.
- */
-
-static int
-yaml_parser_set_composer_error(yaml_parser_t *parser,
- const char *problem, yaml_mark_t problem_mark)
-{
- parser->error = YAML_COMPOSER_ERROR;
- parser->problem = problem;
- parser->problem_mark = problem_mark;
-
- return 0;
-}
-
-/*
- * Set composer error with context.
- */
-
-static int
-yaml_parser_set_composer_error_context(yaml_parser_t *parser,
- const char *context, yaml_mark_t context_mark,
- const char *problem, yaml_mark_t problem_mark)
-{
- parser->error = YAML_COMPOSER_ERROR;
- parser->context = context;
- parser->context_mark = context_mark;
- parser->problem = problem;
- parser->problem_mark = problem_mark;
-
- return 0;
-}
-
-/*
- * Delete the stack of aliases.
- */
-
-static void
-yaml_parser_delete_aliases(yaml_parser_t *parser)
-{
- while (!STACK_EMPTY(parser, parser->aliases)) {
- yaml_free(POP(parser, parser->aliases).anchor);
- }
- STACK_DEL(parser, parser->aliases);
-}
-
-/*
- * Compose a document object.
- */
-
-static int
+ goto error;
+
+ parser->document = document;
+
+ if (!yaml_parser_load_document(parser, &event)) goto error;
+
+ yaml_parser_delete_aliases(parser);
+ parser->document = NULL;
+
+ return 1;
+
+error:
+
+ yaml_parser_delete_aliases(parser);
+ yaml_document_delete(document);
+ parser->document = NULL;
+
+ return 0;
+}
+
+/*
+ * Set composer error.
+ */
+
+static int
+yaml_parser_set_composer_error(yaml_parser_t *parser,
+ const char *problem, yaml_mark_t problem_mark)
+{
+ parser->error = YAML_COMPOSER_ERROR;
+ parser->problem = problem;
+ parser->problem_mark = problem_mark;
+
+ return 0;
+}
+
+/*
+ * Set composer error with context.
+ */
+
+static int
+yaml_parser_set_composer_error_context(yaml_parser_t *parser,
+ const char *context, yaml_mark_t context_mark,
+ const char *problem, yaml_mark_t problem_mark)
+{
+ parser->error = YAML_COMPOSER_ERROR;
+ parser->context = context;
+ parser->context_mark = context_mark;
+ parser->problem = problem;
+ parser->problem_mark = problem_mark;
+
+ return 0;
+}
+
+/*
+ * Delete the stack of aliases.
+ */
+
+static void
+yaml_parser_delete_aliases(yaml_parser_t *parser)
+{
+ while (!STACK_EMPTY(parser, parser->aliases)) {
+ yaml_free(POP(parser, parser->aliases).anchor);
+ }
+ STACK_DEL(parser, parser->aliases);
+}
+
+/*
+ * Compose a document object.
+ */
+
+static int
yaml_parser_load_document(yaml_parser_t *parser, yaml_event_t *event)
-{
+{
struct loader_ctx ctx = { NULL, NULL, NULL };
-
+
assert(event->type == YAML_DOCUMENT_START_EVENT);
- /* DOCUMENT-START is expected. */
-
- parser->document->version_directive
+ /* DOCUMENT-START is expected. */
+
+ parser->document->version_directive
= event->data.document_start.version_directive;
- parser->document->tag_directives.start
+ parser->document->tag_directives.start
= event->data.document_start.tag_directives.start;
- parser->document->tag_directives.end
+ parser->document->tag_directives.end
= event->data.document_start.tag_directives.end;
- parser->document->start_implicit
+ parser->document->start_implicit
= event->data.document_start.implicit;
parser->document->start_mark = event->start_mark;
-
+
if (!STACK_INIT(parser, ctx, int*)) return 0;
if (!yaml_parser_load_nodes(parser, &ctx)) {
STACK_DEL(parser, ctx);
return 0;
}
STACK_DEL(parser, ctx);
-
- return 1;
-}
-
-/*
+
+ return 1;
+}
+
+/*
* Compose a node tree.
- */
-
-static int
+ */
+
+static int
yaml_parser_load_nodes(yaml_parser_t *parser, struct loader_ctx *ctx)
-{
+{
yaml_event_t event;
-
+
do {
if (!yaml_parser_parse(parser, &event)) return 0;
@@ -254,44 +254,44 @@ yaml_parser_load_nodes(yaml_parser_t *parser, struct loader_ctx *ctx)
parser->document->end_mark = event.end_mark;
return 1;
-}
-
-/*
- * Add an anchor.
- */
-
-static int
-yaml_parser_register_anchor(yaml_parser_t *parser,
- int index, yaml_char_t *anchor)
-{
- yaml_alias_data_t data;
- yaml_alias_data_t *alias_data;
-
- if (!anchor) return 1;
-
- data.anchor = anchor;
- data.index = index;
- data.mark = parser->document->nodes.start[index-1].start_mark;
-
- for (alias_data = parser->aliases.start;
- alias_data != parser->aliases.top; alias_data ++) {
- if (strcmp((char *)alias_data->anchor, (char *)anchor) == 0) {
- yaml_free(anchor);
- return yaml_parser_set_composer_error_context(parser,
+}
+
+/*
+ * Add an anchor.
+ */
+
+static int
+yaml_parser_register_anchor(yaml_parser_t *parser,
+ int index, yaml_char_t *anchor)
+{
+ yaml_alias_data_t data;
+ yaml_alias_data_t *alias_data;
+
+ if (!anchor) return 1;
+
+ data.anchor = anchor;
+ data.index = index;
+ data.mark = parser->document->nodes.start[index-1].start_mark;
+
+ for (alias_data = parser->aliases.start;
+ alias_data != parser->aliases.top; alias_data ++) {
+ if (strcmp((char *)alias_data->anchor, (char *)anchor) == 0) {
+ yaml_free(anchor);
+ return yaml_parser_set_composer_error_context(parser,
"found duplicate anchor; first occurrence",
alias_data->mark, "second occurrence", data.mark);
- }
- }
-
- if (!PUSH(parser, parser->aliases, data)) {
- yaml_free(anchor);
- return 0;
- }
-
- return 1;
-}
-
-/*
+ }
+ }
+
+ if (!PUSH(parser, parser->aliases, data)) {
+ yaml_free(anchor);
+ return 0;
+ }
+
+ return 1;
+}
+
+/*
* Compose node into its parent in the stree.
*/
@@ -344,120 +344,120 @@ yaml_parser_load_node_add(yaml_parser_t *parser, struct loader_ctx *ctx,
}
/*
- * Compose a node corresponding to an alias.
- */
-
-static int
+ * Compose a node corresponding to an alias.
+ */
+
+static int
yaml_parser_load_alias(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx)
-{
+{
yaml_char_t *anchor = event->data.alias.anchor;
- yaml_alias_data_t *alias_data;
-
- for (alias_data = parser->aliases.start;
- alias_data != parser->aliases.top; alias_data ++) {
- if (strcmp((char *)alias_data->anchor, (char *)anchor) == 0) {
- yaml_free(anchor);
+ yaml_alias_data_t *alias_data;
+
+ for (alias_data = parser->aliases.start;
+ alias_data != parser->aliases.top; alias_data ++) {
+ if (strcmp((char *)alias_data->anchor, (char *)anchor) == 0) {
+ yaml_free(anchor);
return yaml_parser_load_node_add(parser, ctx, alias_data->index);
- }
- }
-
- yaml_free(anchor);
- return yaml_parser_set_composer_error(parser, "found undefined alias",
+ }
+ }
+
+ yaml_free(anchor);
+ return yaml_parser_set_composer_error(parser, "found undefined alias",
event->start_mark);
-}
-
-/*
- * Compose a scalar node.
- */
-
-static int
+}
+
+/*
+ * Compose a scalar node.
+ */
+
+static int
yaml_parser_load_scalar(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx)
-{
- yaml_node_t node;
- int index;
+{
+ yaml_node_t node;
+ int index;
yaml_char_t *tag = event->data.scalar.tag;
-
- if (!STACK_LIMIT(parser, parser->document->nodes, INT_MAX-1)) goto error;
-
- if (!tag || strcmp((char *)tag, "!") == 0) {
- yaml_free(tag);
- tag = yaml_strdup((yaml_char_t *)YAML_DEFAULT_SCALAR_TAG);
- if (!tag) goto error;
- }
-
+
+ if (!STACK_LIMIT(parser, parser->document->nodes, INT_MAX-1)) goto error;
+
+ if (!tag || strcmp((char *)tag, "!") == 0) {
+ yaml_free(tag);
+ tag = yaml_strdup((yaml_char_t *)YAML_DEFAULT_SCALAR_TAG);
+ if (!tag) goto error;
+ }
+
SCALAR_NODE_INIT(node, tag, event->data.scalar.value,
event->data.scalar.length, event->data.scalar.style,
event->start_mark, event->end_mark);
-
- if (!PUSH(parser, parser->document->nodes, node)) goto error;
-
- index = parser->document->nodes.top - parser->document->nodes.start;
-
- if (!yaml_parser_register_anchor(parser, index,
+
+ if (!PUSH(parser, parser->document->nodes, node)) goto error;
+
+ index = parser->document->nodes.top - parser->document->nodes.start;
+
+ if (!yaml_parser_register_anchor(parser, index,
event->data.scalar.anchor)) return 0;
-
+
return yaml_parser_load_node_add(parser, ctx, index);
-
-error:
- yaml_free(tag);
+
+error:
+ yaml_free(tag);
yaml_free(event->data.scalar.anchor);
yaml_free(event->data.scalar.value);
- return 0;
-}
-
-/*
- * Compose a sequence node.
- */
-
-static int
+ return 0;
+}
+
+/*
+ * Compose a sequence node.
+ */
+
+static int
yaml_parser_load_sequence(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx)
-{
- yaml_node_t node;
- struct {
- yaml_node_item_t *start;
- yaml_node_item_t *end;
- yaml_node_item_t *top;
- } items = { NULL, NULL, NULL };
+{
+ yaml_node_t node;
+ struct {
+ yaml_node_item_t *start;
+ yaml_node_item_t *end;
+ yaml_node_item_t *top;
+ } items = { NULL, NULL, NULL };
int index;
yaml_char_t *tag = event->data.sequence_start.tag;
-
- if (!STACK_LIMIT(parser, parser->document->nodes, INT_MAX-1)) goto error;
-
- if (!tag || strcmp((char *)tag, "!") == 0) {
- yaml_free(tag);
- tag = yaml_strdup((yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG);
- if (!tag) goto error;
- }
-
+
+ if (!STACK_LIMIT(parser, parser->document->nodes, INT_MAX-1)) goto error;
+
+ if (!tag || strcmp((char *)tag, "!") == 0) {
+ yaml_free(tag);
+ tag = yaml_strdup((yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG);
+ if (!tag) goto error;
+ }
+
if (!STACK_INIT(parser, items, yaml_node_item_t*)) goto error;
-
- SEQUENCE_NODE_INIT(node, tag, items.start, items.end,
+
+ SEQUENCE_NODE_INIT(node, tag, items.start, items.end,
event->data.sequence_start.style,
event->start_mark, event->end_mark);
-
- if (!PUSH(parser, parser->document->nodes, node)) goto error;
-
- index = parser->document->nodes.top - parser->document->nodes.start;
-
- if (!yaml_parser_register_anchor(parser, index,
+
+ if (!PUSH(parser, parser->document->nodes, node)) goto error;
+
+ index = parser->document->nodes.top - parser->document->nodes.start;
+
+ if (!yaml_parser_register_anchor(parser, index,
event->data.sequence_start.anchor)) return 0;
-
+
if (!yaml_parser_load_node_add(parser, ctx, index)) return 0;
-
+
if (!STACK_LIMIT(parser, *ctx, INT_MAX-1)) return 0;
if (!PUSH(parser, *ctx, index)) return 0;
-
+
return 1;
-
-error:
- yaml_free(tag);
+
+error:
+ yaml_free(tag);
yaml_free(event->data.sequence_start.anchor);
- return 0;
-}
-
+ return 0;
+}
+
static int
yaml_parser_load_sequence_end(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx)
@@ -475,57 +475,57 @@ yaml_parser_load_sequence_end(yaml_parser_t *parser, yaml_event_t *event,
return 1;
}
-/*
- * Compose a mapping node.
- */
-
-static int
+/*
+ * Compose a mapping node.
+ */
+
+static int
yaml_parser_load_mapping(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx)
-{
- yaml_node_t node;
- struct {
- yaml_node_pair_t *start;
- yaml_node_pair_t *end;
- yaml_node_pair_t *top;
- } pairs = { NULL, NULL, NULL };
- int index;
+{
+ yaml_node_t node;
+ struct {
+ yaml_node_pair_t *start;
+ yaml_node_pair_t *end;
+ yaml_node_pair_t *top;
+ } pairs = { NULL, NULL, NULL };
+ int index;
yaml_char_t *tag = event->data.mapping_start.tag;
-
- if (!STACK_LIMIT(parser, parser->document->nodes, INT_MAX-1)) goto error;
-
- if (!tag || strcmp((char *)tag, "!") == 0) {
- yaml_free(tag);
- tag = yaml_strdup((yaml_char_t *)YAML_DEFAULT_MAPPING_TAG);
- if (!tag) goto error;
- }
-
+
+ if (!STACK_LIMIT(parser, parser->document->nodes, INT_MAX-1)) goto error;
+
+ if (!tag || strcmp((char *)tag, "!") == 0) {
+ yaml_free(tag);
+ tag = yaml_strdup((yaml_char_t *)YAML_DEFAULT_MAPPING_TAG);
+ if (!tag) goto error;
+ }
+
if (!STACK_INIT(parser, pairs, yaml_node_pair_t*)) goto error;
-
- MAPPING_NODE_INIT(node, tag, pairs.start, pairs.end,
+
+ MAPPING_NODE_INIT(node, tag, pairs.start, pairs.end,
event->data.mapping_start.style,
event->start_mark, event->end_mark);
-
- if (!PUSH(parser, parser->document->nodes, node)) goto error;
-
- index = parser->document->nodes.top - parser->document->nodes.start;
-
- if (!yaml_parser_register_anchor(parser, index,
+
+ if (!PUSH(parser, parser->document->nodes, node)) goto error;
+
+ index = parser->document->nodes.top - parser->document->nodes.start;
+
+ if (!yaml_parser_register_anchor(parser, index,
event->data.mapping_start.anchor)) return 0;
-
+
if (!yaml_parser_load_node_add(parser, ctx, index)) return 0;
-
+
if (!STACK_LIMIT(parser, *ctx, INT_MAX-1)) return 0;
if (!PUSH(parser, *ctx, index)) return 0;
-
+
return 1;
-
-error:
- yaml_free(tag);
+
+error:
+ yaml_free(tag);
yaml_free(event->data.mapping_start.anchor);
- return 0;
-}
-
+ return 0;
+}
+
static int
yaml_parser_load_mapping_end(yaml_parser_t *parser, yaml_event_t *event,
struct loader_ctx *ctx)
diff --git a/contrib/libs/yaml/src/parser.c b/contrib/libs/yaml/src/parser.c
index 320ed703b4..ec2f8d3e05 100644
--- a/contrib/libs/yaml/src/parser.c
+++ b/contrib/libs/yaml/src/parser.c
@@ -1,1375 +1,1375 @@
-
-/*
- * The parser implements the following grammar:
- *
- * stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
- * implicit_document ::= block_node DOCUMENT-END*
- * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
- * block_node_or_indentless_sequence ::=
- * ALIAS
- * | properties (block_content | indentless_block_sequence)?
- * | block_content
- * | indentless_block_sequence
- * block_node ::= ALIAS
- * | properties block_content?
- * | block_content
- * flow_node ::= ALIAS
- * | properties flow_content?
- * | flow_content
- * properties ::= TAG ANCHOR? | ANCHOR TAG?
- * block_content ::= block_collection | flow_collection | SCALAR
- * flow_content ::= flow_collection | SCALAR
- * block_collection ::= block_sequence | block_mapping
- * flow_collection ::= flow_sequence | flow_mapping
- * block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
- * indentless_sequence ::= (BLOCK-ENTRY block_node?)+
- * block_mapping ::= BLOCK-MAPPING_START
- * ((KEY block_node_or_indentless_sequence?)?
- * (VALUE block_node_or_indentless_sequence?)?)*
- * BLOCK-END
- * flow_sequence ::= FLOW-SEQUENCE-START
- * (flow_sequence_entry FLOW-ENTRY)*
- * flow_sequence_entry?
- * FLOW-SEQUENCE-END
- * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
- * flow_mapping ::= FLOW-MAPPING-START
- * (flow_mapping_entry FLOW-ENTRY)*
- * flow_mapping_entry?
- * FLOW-MAPPING-END
- * flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
- */
-
-#include "yaml_private.h"
-
-/*
- * Peek the next token in the token queue.
- */
-
-#define PEEK_TOKEN(parser) \
- ((parser->token_available || yaml_parser_fetch_more_tokens(parser)) ? \
- parser->tokens.head : NULL)
-
-/*
- * Remove the next token from the queue (must be called after PEEK_TOKEN).
- */
-
-#define SKIP_TOKEN(parser) \
- (parser->token_available = 0, \
- parser->tokens_parsed ++, \
- parser->stream_end_produced = \
- (parser->tokens.head->type == YAML_STREAM_END_TOKEN), \
- parser->tokens.head ++)
-
-/*
- * Public API declarations.
- */
-
-YAML_DECLARE(int)
-yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event);
-
-/*
- * Error handling.
- */
-
-static int
-yaml_parser_set_parser_error(yaml_parser_t *parser,
- const char *problem, yaml_mark_t problem_mark);
-
-static int
-yaml_parser_set_parser_error_context(yaml_parser_t *parser,
- const char *context, yaml_mark_t context_mark,
- const char *problem, yaml_mark_t problem_mark);
-
-/*
- * State functions.
- */
-
-static int
-yaml_parser_state_machine(yaml_parser_t *parser, yaml_event_t *event);
-
-static int
-yaml_parser_parse_stream_start(yaml_parser_t *parser, yaml_event_t *event);
-
-static int
-yaml_parser_parse_document_start(yaml_parser_t *parser, yaml_event_t *event,
- int implicit);
-
-static int
-yaml_parser_parse_document_content(yaml_parser_t *parser, yaml_event_t *event);
-
-static int
-yaml_parser_parse_document_end(yaml_parser_t *parser, yaml_event_t *event);
-
-static int
-yaml_parser_parse_node(yaml_parser_t *parser, yaml_event_t *event,
- int block, int indentless_sequence);
-
-static int
-yaml_parser_parse_block_sequence_entry(yaml_parser_t *parser,
- yaml_event_t *event, int first);
-
-static int
-yaml_parser_parse_indentless_sequence_entry(yaml_parser_t *parser,
- yaml_event_t *event);
-
-static int
-yaml_parser_parse_block_mapping_key(yaml_parser_t *parser,
- yaml_event_t *event, int first);
-
-static int
-yaml_parser_parse_block_mapping_value(yaml_parser_t *parser,
- yaml_event_t *event);
-
-static int
-yaml_parser_parse_flow_sequence_entry(yaml_parser_t *parser,
- yaml_event_t *event, int first);
-
-static int
-yaml_parser_parse_flow_sequence_entry_mapping_key(yaml_parser_t *parser,
- yaml_event_t *event);
-
-static int
-yaml_parser_parse_flow_sequence_entry_mapping_value(yaml_parser_t *parser,
- yaml_event_t *event);
-
-static int
-yaml_parser_parse_flow_sequence_entry_mapping_end(yaml_parser_t *parser,
- yaml_event_t *event);
-
-static int
-yaml_parser_parse_flow_mapping_key(yaml_parser_t *parser,
- yaml_event_t *event, int first);
-
-static int
-yaml_parser_parse_flow_mapping_value(yaml_parser_t *parser,
- yaml_event_t *event, int empty);
-
-/*
- * Utility functions.
- */
-
-static int
-yaml_parser_process_empty_scalar(yaml_parser_t *parser,
- yaml_event_t *event, yaml_mark_t mark);
-
-static int
-yaml_parser_process_directives(yaml_parser_t *parser,
- yaml_version_directive_t **version_directive_ref,
- yaml_tag_directive_t **tag_directives_start_ref,
- yaml_tag_directive_t **tag_directives_end_ref);
-
-static int
-yaml_parser_append_tag_directive(yaml_parser_t *parser,
- yaml_tag_directive_t value, int allow_duplicates, yaml_mark_t mark);
-
-/*
- * Get the next event.
- */
-
-YAML_DECLARE(int)
-yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event)
-{
- assert(parser); /* Non-NULL parser object is expected. */
- assert(event); /* Non-NULL event object is expected. */
-
- /* Erase the event object. */
-
- memset(event, 0, sizeof(yaml_event_t));
-
- /* No events after the end of the stream or error. */
-
- if (parser->stream_end_produced || parser->error ||
- parser->state == YAML_PARSE_END_STATE) {
- return 1;
- }
-
- /* Generate the next event. */
-
- return yaml_parser_state_machine(parser, event);
-}
-
-/*
- * Set parser error.
- */
-
-static int
-yaml_parser_set_parser_error(yaml_parser_t *parser,
- const char *problem, yaml_mark_t problem_mark)
-{
- parser->error = YAML_PARSER_ERROR;
- parser->problem = problem;
- parser->problem_mark = problem_mark;
-
- return 0;
-}
-
-static int
-yaml_parser_set_parser_error_context(yaml_parser_t *parser,
- const char *context, yaml_mark_t context_mark,
- const char *problem, yaml_mark_t problem_mark)
-{
- parser->error = YAML_PARSER_ERROR;
- parser->context = context;
- parser->context_mark = context_mark;
- parser->problem = problem;
- parser->problem_mark = problem_mark;
-
- return 0;
-}
-
-
-/*
- * State dispatcher.
- */
-
-static int
-yaml_parser_state_machine(yaml_parser_t *parser, yaml_event_t *event)
-{
- switch (parser->state)
- {
- case YAML_PARSE_STREAM_START_STATE:
- return yaml_parser_parse_stream_start(parser, event);
-
- case YAML_PARSE_IMPLICIT_DOCUMENT_START_STATE:
- return yaml_parser_parse_document_start(parser, event, 1);
-
- case YAML_PARSE_DOCUMENT_START_STATE:
- return yaml_parser_parse_document_start(parser, event, 0);
-
- case YAML_PARSE_DOCUMENT_CONTENT_STATE:
- return yaml_parser_parse_document_content(parser, event);
-
- case YAML_PARSE_DOCUMENT_END_STATE:
- return yaml_parser_parse_document_end(parser, event);
-
- case YAML_PARSE_BLOCK_NODE_STATE:
- return yaml_parser_parse_node(parser, event, 1, 0);
-
- case YAML_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE:
- return yaml_parser_parse_node(parser, event, 1, 1);
-
- case YAML_PARSE_FLOW_NODE_STATE:
- return yaml_parser_parse_node(parser, event, 0, 0);
-
- case YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE:
- return yaml_parser_parse_block_sequence_entry(parser, event, 1);
-
- case YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE:
- return yaml_parser_parse_block_sequence_entry(parser, event, 0);
-
- case YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE:
- return yaml_parser_parse_indentless_sequence_entry(parser, event);
-
- case YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE:
- return yaml_parser_parse_block_mapping_key(parser, event, 1);
-
- case YAML_PARSE_BLOCK_MAPPING_KEY_STATE:
- return yaml_parser_parse_block_mapping_key(parser, event, 0);
-
- case YAML_PARSE_BLOCK_MAPPING_VALUE_STATE:
- return yaml_parser_parse_block_mapping_value(parser, event);
-
- case YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE:
- return yaml_parser_parse_flow_sequence_entry(parser, event, 1);
-
- case YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE:
- return yaml_parser_parse_flow_sequence_entry(parser, event, 0);
-
- case YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE:
- return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event);
-
- case YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE:
- return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event);
-
- case YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE:
- return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event);
-
- case YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE:
- return yaml_parser_parse_flow_mapping_key(parser, event, 1);
-
- case YAML_PARSE_FLOW_MAPPING_KEY_STATE:
- return yaml_parser_parse_flow_mapping_key(parser, event, 0);
-
- case YAML_PARSE_FLOW_MAPPING_VALUE_STATE:
- return yaml_parser_parse_flow_mapping_value(parser, event, 0);
-
- case YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE:
- return yaml_parser_parse_flow_mapping_value(parser, event, 1);
-
- default:
- assert(1); /* Invalid state. */
- }
-
- return 0;
-}
-
-/*
- * Parse the production:
- * stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
- * ************
- */
-
-static int
-yaml_parser_parse_stream_start(yaml_parser_t *parser, yaml_event_t *event)
-{
- yaml_token_t *token;
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (token->type != YAML_STREAM_START_TOKEN) {
- return yaml_parser_set_parser_error(parser,
- "did not find expected <stream-start>", token->start_mark);
- }
-
- parser->state = YAML_PARSE_IMPLICIT_DOCUMENT_START_STATE;
- STREAM_START_EVENT_INIT(*event, token->data.stream_start.encoding,
- token->start_mark, token->start_mark);
- SKIP_TOKEN(parser);
-
- return 1;
-}
-
-/*
- * Parse the productions:
- * implicit_document ::= block_node DOCUMENT-END*
- * *
- * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
- * *************************
- */
-
-static int
-yaml_parser_parse_document_start(yaml_parser_t *parser, yaml_event_t *event,
- int implicit)
-{
- yaml_token_t *token;
- yaml_version_directive_t *version_directive = NULL;
- struct {
- yaml_tag_directive_t *start;
- yaml_tag_directive_t *end;
- } tag_directives = { NULL, NULL };
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- /* Parse extra document end indicators. */
-
- if (!implicit)
- {
- while (token->type == YAML_DOCUMENT_END_TOKEN) {
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
- }
- }
-
- /* Parse an implicit document. */
-
- if (implicit && token->type != YAML_VERSION_DIRECTIVE_TOKEN &&
- token->type != YAML_TAG_DIRECTIVE_TOKEN &&
- token->type != YAML_DOCUMENT_START_TOKEN &&
- token->type != YAML_STREAM_END_TOKEN)
- {
- if (!yaml_parser_process_directives(parser, NULL, NULL, NULL))
- return 0;
- if (!PUSH(parser, parser->states, YAML_PARSE_DOCUMENT_END_STATE))
- return 0;
- parser->state = YAML_PARSE_BLOCK_NODE_STATE;
- DOCUMENT_START_EVENT_INIT(*event, NULL, NULL, NULL, 1,
- token->start_mark, token->start_mark);
- return 1;
- }
-
- /* Parse an explicit document. */
-
- else if (token->type != YAML_STREAM_END_TOKEN)
- {
- yaml_mark_t start_mark, end_mark;
- start_mark = token->start_mark;
- if (!yaml_parser_process_directives(parser, &version_directive,
- &tag_directives.start, &tag_directives.end))
- return 0;
- token = PEEK_TOKEN(parser);
- if (!token) goto error;
- if (token->type != YAML_DOCUMENT_START_TOKEN) {
- yaml_parser_set_parser_error(parser,
- "did not find expected <document start>", token->start_mark);
- goto error;
- }
- if (!PUSH(parser, parser->states, YAML_PARSE_DOCUMENT_END_STATE))
- goto error;
- parser->state = YAML_PARSE_DOCUMENT_CONTENT_STATE;
- end_mark = token->end_mark;
- DOCUMENT_START_EVENT_INIT(*event, version_directive,
- tag_directives.start, tag_directives.end, 0,
- start_mark, end_mark);
- SKIP_TOKEN(parser);
- version_directive = NULL;
- tag_directives.start = tag_directives.end = NULL;
- return 1;
- }
-
- /* Parse the stream end. */
-
- else
- {
- parser->state = YAML_PARSE_END_STATE;
- STREAM_END_EVENT_INIT(*event, token->start_mark, token->end_mark);
- SKIP_TOKEN(parser);
- return 1;
- }
-
-error:
- yaml_free(version_directive);
- while (tag_directives.start != tag_directives.end) {
- yaml_free(tag_directives.end[-1].handle);
- yaml_free(tag_directives.end[-1].prefix);
- tag_directives.end --;
- }
- yaml_free(tag_directives.start);
- return 0;
-}
-
-/*
- * Parse the productions:
- * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
- * ***********
- */
-
-static int
-yaml_parser_parse_document_content(yaml_parser_t *parser, yaml_event_t *event)
-{
- yaml_token_t *token;
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (token->type == YAML_VERSION_DIRECTIVE_TOKEN ||
- token->type == YAML_TAG_DIRECTIVE_TOKEN ||
- token->type == YAML_DOCUMENT_START_TOKEN ||
- token->type == YAML_DOCUMENT_END_TOKEN ||
- token->type == YAML_STREAM_END_TOKEN) {
- parser->state = POP(parser, parser->states);
- return yaml_parser_process_empty_scalar(parser, event,
- token->start_mark);
- }
- else {
- return yaml_parser_parse_node(parser, event, 1, 0);
- }
-}
-
-/*
- * Parse the productions:
- * implicit_document ::= block_node DOCUMENT-END*
- * *************
- * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
- * *************
- */
-
-static int
-yaml_parser_parse_document_end(yaml_parser_t *parser, yaml_event_t *event)
-{
- yaml_token_t *token;
- yaml_mark_t start_mark, end_mark;
- int implicit = 1;
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- start_mark = end_mark = token->start_mark;
-
- if (token->type == YAML_DOCUMENT_END_TOKEN) {
- end_mark = token->end_mark;
- SKIP_TOKEN(parser);
- implicit = 0;
- }
-
- while (!STACK_EMPTY(parser, parser->tag_directives)) {
- yaml_tag_directive_t tag_directive = POP(parser, parser->tag_directives);
- yaml_free(tag_directive.handle);
- yaml_free(tag_directive.prefix);
- }
-
- parser->state = YAML_PARSE_DOCUMENT_START_STATE;
- DOCUMENT_END_EVENT_INIT(*event, implicit, start_mark, end_mark);
-
- return 1;
-}
-
-/*
- * Parse the productions:
- * block_node_or_indentless_sequence ::=
- * ALIAS
- * *****
- * | properties (block_content | indentless_block_sequence)?
- * ********** *
- * | block_content | indentless_block_sequence
- * *
- * block_node ::= ALIAS
- * *****
- * | properties block_content?
- * ********** *
- * | block_content
- * *
- * flow_node ::= ALIAS
- * *****
- * | properties flow_content?
- * ********** *
- * | flow_content
- * *
- * properties ::= TAG ANCHOR? | ANCHOR TAG?
- * *************************
- * block_content ::= block_collection | flow_collection | SCALAR
- * ******
- * flow_content ::= flow_collection | SCALAR
- * ******
- */
-
-static int
-yaml_parser_parse_node(yaml_parser_t *parser, yaml_event_t *event,
- int block, int indentless_sequence)
-{
- yaml_token_t *token;
- yaml_char_t *anchor = NULL;
- yaml_char_t *tag_handle = NULL;
- yaml_char_t *tag_suffix = NULL;
- yaml_char_t *tag = NULL;
- yaml_mark_t start_mark, end_mark, tag_mark;
- int implicit;
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (token->type == YAML_ALIAS_TOKEN)
- {
- parser->state = POP(parser, parser->states);
- ALIAS_EVENT_INIT(*event, token->data.alias.value,
- token->start_mark, token->end_mark);
- SKIP_TOKEN(parser);
- return 1;
- }
-
- else
- {
- start_mark = end_mark = token->start_mark;
-
- if (token->type == YAML_ANCHOR_TOKEN)
- {
- anchor = token->data.anchor.value;
- start_mark = token->start_mark;
- end_mark = token->end_mark;
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) goto error;
- if (token->type == YAML_TAG_TOKEN)
- {
- tag_handle = token->data.tag.handle;
- tag_suffix = token->data.tag.suffix;
- tag_mark = token->start_mark;
- end_mark = token->end_mark;
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) goto error;
- }
- }
- else if (token->type == YAML_TAG_TOKEN)
- {
- tag_handle = token->data.tag.handle;
- tag_suffix = token->data.tag.suffix;
- start_mark = tag_mark = token->start_mark;
- end_mark = token->end_mark;
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) goto error;
- if (token->type == YAML_ANCHOR_TOKEN)
- {
- anchor = token->data.anchor.value;
- end_mark = token->end_mark;
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) goto error;
- }
- }
-
- if (tag_handle) {
- if (!*tag_handle) {
- tag = tag_suffix;
- yaml_free(tag_handle);
- tag_handle = tag_suffix = NULL;
- }
- else {
- yaml_tag_directive_t *tag_directive;
- for (tag_directive = parser->tag_directives.start;
- tag_directive != parser->tag_directives.top;
- tag_directive ++) {
- if (strcmp((char *)tag_directive->handle, (char *)tag_handle) == 0) {
- size_t prefix_len = strlen((char *)tag_directive->prefix);
- size_t suffix_len = strlen((char *)tag_suffix);
+
+/*
+ * The parser implements the following grammar:
+ *
+ * stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
+ * implicit_document ::= block_node DOCUMENT-END*
+ * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
+ * block_node_or_indentless_sequence ::=
+ * ALIAS
+ * | properties (block_content | indentless_block_sequence)?
+ * | block_content
+ * | indentless_block_sequence
+ * block_node ::= ALIAS
+ * | properties block_content?
+ * | block_content
+ * flow_node ::= ALIAS
+ * | properties flow_content?
+ * | flow_content
+ * properties ::= TAG ANCHOR? | ANCHOR TAG?
+ * block_content ::= block_collection | flow_collection | SCALAR
+ * flow_content ::= flow_collection | SCALAR
+ * block_collection ::= block_sequence | block_mapping
+ * flow_collection ::= flow_sequence | flow_mapping
+ * block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
+ * indentless_sequence ::= (BLOCK-ENTRY block_node?)+
+ * block_mapping ::= BLOCK-MAPPING_START
+ * ((KEY block_node_or_indentless_sequence?)?
+ * (VALUE block_node_or_indentless_sequence?)?)*
+ * BLOCK-END
+ * flow_sequence ::= FLOW-SEQUENCE-START
+ * (flow_sequence_entry FLOW-ENTRY)*
+ * flow_sequence_entry?
+ * FLOW-SEQUENCE-END
+ * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+ * flow_mapping ::= FLOW-MAPPING-START
+ * (flow_mapping_entry FLOW-ENTRY)*
+ * flow_mapping_entry?
+ * FLOW-MAPPING-END
+ * flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+ */
+
+#include "yaml_private.h"
+
+/*
+ * Peek the next token in the token queue.
+ */
+
+#define PEEK_TOKEN(parser) \
+ ((parser->token_available || yaml_parser_fetch_more_tokens(parser)) ? \
+ parser->tokens.head : NULL)
+
+/*
+ * Remove the next token from the queue (must be called after PEEK_TOKEN).
+ */
+
+#define SKIP_TOKEN(parser) \
+ (parser->token_available = 0, \
+ parser->tokens_parsed ++, \
+ parser->stream_end_produced = \
+ (parser->tokens.head->type == YAML_STREAM_END_TOKEN), \
+ parser->tokens.head ++)
+
+/*
+ * Public API declarations.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event);
+
+/*
+ * Error handling.
+ */
+
+static int
+yaml_parser_set_parser_error(yaml_parser_t *parser,
+ const char *problem, yaml_mark_t problem_mark);
+
+static int
+yaml_parser_set_parser_error_context(yaml_parser_t *parser,
+ const char *context, yaml_mark_t context_mark,
+ const char *problem, yaml_mark_t problem_mark);
+
+/*
+ * State functions.
+ */
+
+static int
+yaml_parser_state_machine(yaml_parser_t *parser, yaml_event_t *event);
+
+static int
+yaml_parser_parse_stream_start(yaml_parser_t *parser, yaml_event_t *event);
+
+static int
+yaml_parser_parse_document_start(yaml_parser_t *parser, yaml_event_t *event,
+ int implicit);
+
+static int
+yaml_parser_parse_document_content(yaml_parser_t *parser, yaml_event_t *event);
+
+static int
+yaml_parser_parse_document_end(yaml_parser_t *parser, yaml_event_t *event);
+
+static int
+yaml_parser_parse_node(yaml_parser_t *parser, yaml_event_t *event,
+ int block, int indentless_sequence);
+
+static int
+yaml_parser_parse_block_sequence_entry(yaml_parser_t *parser,
+ yaml_event_t *event, int first);
+
+static int
+yaml_parser_parse_indentless_sequence_entry(yaml_parser_t *parser,
+ yaml_event_t *event);
+
+static int
+yaml_parser_parse_block_mapping_key(yaml_parser_t *parser,
+ yaml_event_t *event, int first);
+
+static int
+yaml_parser_parse_block_mapping_value(yaml_parser_t *parser,
+ yaml_event_t *event);
+
+static int
+yaml_parser_parse_flow_sequence_entry(yaml_parser_t *parser,
+ yaml_event_t *event, int first);
+
+static int
+yaml_parser_parse_flow_sequence_entry_mapping_key(yaml_parser_t *parser,
+ yaml_event_t *event);
+
+static int
+yaml_parser_parse_flow_sequence_entry_mapping_value(yaml_parser_t *parser,
+ yaml_event_t *event);
+
+static int
+yaml_parser_parse_flow_sequence_entry_mapping_end(yaml_parser_t *parser,
+ yaml_event_t *event);
+
+static int
+yaml_parser_parse_flow_mapping_key(yaml_parser_t *parser,
+ yaml_event_t *event, int first);
+
+static int
+yaml_parser_parse_flow_mapping_value(yaml_parser_t *parser,
+ yaml_event_t *event, int empty);
+
+/*
+ * Utility functions.
+ */
+
+static int
+yaml_parser_process_empty_scalar(yaml_parser_t *parser,
+ yaml_event_t *event, yaml_mark_t mark);
+
+static int
+yaml_parser_process_directives(yaml_parser_t *parser,
+ yaml_version_directive_t **version_directive_ref,
+ yaml_tag_directive_t **tag_directives_start_ref,
+ yaml_tag_directive_t **tag_directives_end_ref);
+
+static int
+yaml_parser_append_tag_directive(yaml_parser_t *parser,
+ yaml_tag_directive_t value, int allow_duplicates, yaml_mark_t mark);
+
+/*
+ * Get the next event.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event)
+{
+ assert(parser); /* Non-NULL parser object is expected. */
+ assert(event); /* Non-NULL event object is expected. */
+
+ /* Erase the event object. */
+
+ memset(event, 0, sizeof(yaml_event_t));
+
+ /* No events after the end of the stream or error. */
+
+ if (parser->stream_end_produced || parser->error ||
+ parser->state == YAML_PARSE_END_STATE) {
+ return 1;
+ }
+
+ /* Generate the next event. */
+
+ return yaml_parser_state_machine(parser, event);
+}
+
+/*
+ * Set parser error.
+ */
+
+static int
+yaml_parser_set_parser_error(yaml_parser_t *parser,
+ const char *problem, yaml_mark_t problem_mark)
+{
+ parser->error = YAML_PARSER_ERROR;
+ parser->problem = problem;
+ parser->problem_mark = problem_mark;
+
+ return 0;
+}
+
+static int
+yaml_parser_set_parser_error_context(yaml_parser_t *parser,
+ const char *context, yaml_mark_t context_mark,
+ const char *problem, yaml_mark_t problem_mark)
+{
+ parser->error = YAML_PARSER_ERROR;
+ parser->context = context;
+ parser->context_mark = context_mark;
+ parser->problem = problem;
+ parser->problem_mark = problem_mark;
+
+ return 0;
+}
+
+
+/*
+ * State dispatcher.
+ */
+
+static int
+yaml_parser_state_machine(yaml_parser_t *parser, yaml_event_t *event)
+{
+ switch (parser->state)
+ {
+ case YAML_PARSE_STREAM_START_STATE:
+ return yaml_parser_parse_stream_start(parser, event);
+
+ case YAML_PARSE_IMPLICIT_DOCUMENT_START_STATE:
+ return yaml_parser_parse_document_start(parser, event, 1);
+
+ case YAML_PARSE_DOCUMENT_START_STATE:
+ return yaml_parser_parse_document_start(parser, event, 0);
+
+ case YAML_PARSE_DOCUMENT_CONTENT_STATE:
+ return yaml_parser_parse_document_content(parser, event);
+
+ case YAML_PARSE_DOCUMENT_END_STATE:
+ return yaml_parser_parse_document_end(parser, event);
+
+ case YAML_PARSE_BLOCK_NODE_STATE:
+ return yaml_parser_parse_node(parser, event, 1, 0);
+
+ case YAML_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE:
+ return yaml_parser_parse_node(parser, event, 1, 1);
+
+ case YAML_PARSE_FLOW_NODE_STATE:
+ return yaml_parser_parse_node(parser, event, 0, 0);
+
+ case YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE:
+ return yaml_parser_parse_block_sequence_entry(parser, event, 1);
+
+ case YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE:
+ return yaml_parser_parse_block_sequence_entry(parser, event, 0);
+
+ case YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE:
+ return yaml_parser_parse_indentless_sequence_entry(parser, event);
+
+ case YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE:
+ return yaml_parser_parse_block_mapping_key(parser, event, 1);
+
+ case YAML_PARSE_BLOCK_MAPPING_KEY_STATE:
+ return yaml_parser_parse_block_mapping_key(parser, event, 0);
+
+ case YAML_PARSE_BLOCK_MAPPING_VALUE_STATE:
+ return yaml_parser_parse_block_mapping_value(parser, event);
+
+ case YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE:
+ return yaml_parser_parse_flow_sequence_entry(parser, event, 1);
+
+ case YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE:
+ return yaml_parser_parse_flow_sequence_entry(parser, event, 0);
+
+ case YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE:
+ return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event);
+
+ case YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE:
+ return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event);
+
+ case YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE:
+ return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event);
+
+ case YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE:
+ return yaml_parser_parse_flow_mapping_key(parser, event, 1);
+
+ case YAML_PARSE_FLOW_MAPPING_KEY_STATE:
+ return yaml_parser_parse_flow_mapping_key(parser, event, 0);
+
+ case YAML_PARSE_FLOW_MAPPING_VALUE_STATE:
+ return yaml_parser_parse_flow_mapping_value(parser, event, 0);
+
+ case YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE:
+ return yaml_parser_parse_flow_mapping_value(parser, event, 1);
+
+ default:
+ assert(1); /* Invalid state. */
+ }
+
+ return 0;
+}
+
+/*
+ * Parse the production:
+ * stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
+ * ************
+ */
+
+static int
+yaml_parser_parse_stream_start(yaml_parser_t *parser, yaml_event_t *event)
+{
+ yaml_token_t *token;
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (token->type != YAML_STREAM_START_TOKEN) {
+ return yaml_parser_set_parser_error(parser,
+ "did not find expected <stream-start>", token->start_mark);
+ }
+
+ parser->state = YAML_PARSE_IMPLICIT_DOCUMENT_START_STATE;
+ STREAM_START_EVENT_INIT(*event, token->data.stream_start.encoding,
+ token->start_mark, token->start_mark);
+ SKIP_TOKEN(parser);
+
+ return 1;
+}
+
+/*
+ * Parse the productions:
+ * implicit_document ::= block_node DOCUMENT-END*
+ * *
+ * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
+ * *************************
+ */
+
+static int
+yaml_parser_parse_document_start(yaml_parser_t *parser, yaml_event_t *event,
+ int implicit)
+{
+ yaml_token_t *token;
+ yaml_version_directive_t *version_directive = NULL;
+ struct {
+ yaml_tag_directive_t *start;
+ yaml_tag_directive_t *end;
+ } tag_directives = { NULL, NULL };
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ /* Parse extra document end indicators. */
+
+ if (!implicit)
+ {
+ while (token->type == YAML_DOCUMENT_END_TOKEN) {
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+ }
+ }
+
+ /* Parse an implicit document. */
+
+ if (implicit && token->type != YAML_VERSION_DIRECTIVE_TOKEN &&
+ token->type != YAML_TAG_DIRECTIVE_TOKEN &&
+ token->type != YAML_DOCUMENT_START_TOKEN &&
+ token->type != YAML_STREAM_END_TOKEN)
+ {
+ if (!yaml_parser_process_directives(parser, NULL, NULL, NULL))
+ return 0;
+ if (!PUSH(parser, parser->states, YAML_PARSE_DOCUMENT_END_STATE))
+ return 0;
+ parser->state = YAML_PARSE_BLOCK_NODE_STATE;
+ DOCUMENT_START_EVENT_INIT(*event, NULL, NULL, NULL, 1,
+ token->start_mark, token->start_mark);
+ return 1;
+ }
+
+ /* Parse an explicit document. */
+
+ else if (token->type != YAML_STREAM_END_TOKEN)
+ {
+ yaml_mark_t start_mark, end_mark;
+ start_mark = token->start_mark;
+ if (!yaml_parser_process_directives(parser, &version_directive,
+ &tag_directives.start, &tag_directives.end))
+ return 0;
+ token = PEEK_TOKEN(parser);
+ if (!token) goto error;
+ if (token->type != YAML_DOCUMENT_START_TOKEN) {
+ yaml_parser_set_parser_error(parser,
+ "did not find expected <document start>", token->start_mark);
+ goto error;
+ }
+ if (!PUSH(parser, parser->states, YAML_PARSE_DOCUMENT_END_STATE))
+ goto error;
+ parser->state = YAML_PARSE_DOCUMENT_CONTENT_STATE;
+ end_mark = token->end_mark;
+ DOCUMENT_START_EVENT_INIT(*event, version_directive,
+ tag_directives.start, tag_directives.end, 0,
+ start_mark, end_mark);
+ SKIP_TOKEN(parser);
+ version_directive = NULL;
+ tag_directives.start = tag_directives.end = NULL;
+ return 1;
+ }
+
+ /* Parse the stream end. */
+
+ else
+ {
+ parser->state = YAML_PARSE_END_STATE;
+ STREAM_END_EVENT_INIT(*event, token->start_mark, token->end_mark);
+ SKIP_TOKEN(parser);
+ return 1;
+ }
+
+error:
+ yaml_free(version_directive);
+ while (tag_directives.start != tag_directives.end) {
+ yaml_free(tag_directives.end[-1].handle);
+ yaml_free(tag_directives.end[-1].prefix);
+ tag_directives.end --;
+ }
+ yaml_free(tag_directives.start);
+ return 0;
+}
+
+/*
+ * Parse the productions:
+ * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
+ * ***********
+ */
+
+static int
+yaml_parser_parse_document_content(yaml_parser_t *parser, yaml_event_t *event)
+{
+ yaml_token_t *token;
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (token->type == YAML_VERSION_DIRECTIVE_TOKEN ||
+ token->type == YAML_TAG_DIRECTIVE_TOKEN ||
+ token->type == YAML_DOCUMENT_START_TOKEN ||
+ token->type == YAML_DOCUMENT_END_TOKEN ||
+ token->type == YAML_STREAM_END_TOKEN) {
+ parser->state = POP(parser, parser->states);
+ return yaml_parser_process_empty_scalar(parser, event,
+ token->start_mark);
+ }
+ else {
+ return yaml_parser_parse_node(parser, event, 1, 0);
+ }
+}
+
+/*
+ * Parse the productions:
+ * implicit_document ::= block_node DOCUMENT-END*
+ * *************
+ * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
+ * *************
+ */
+
+static int
+yaml_parser_parse_document_end(yaml_parser_t *parser, yaml_event_t *event)
+{
+ yaml_token_t *token;
+ yaml_mark_t start_mark, end_mark;
+ int implicit = 1;
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ start_mark = end_mark = token->start_mark;
+
+ if (token->type == YAML_DOCUMENT_END_TOKEN) {
+ end_mark = token->end_mark;
+ SKIP_TOKEN(parser);
+ implicit = 0;
+ }
+
+ while (!STACK_EMPTY(parser, parser->tag_directives)) {
+ yaml_tag_directive_t tag_directive = POP(parser, parser->tag_directives);
+ yaml_free(tag_directive.handle);
+ yaml_free(tag_directive.prefix);
+ }
+
+ parser->state = YAML_PARSE_DOCUMENT_START_STATE;
+ DOCUMENT_END_EVENT_INIT(*event, implicit, start_mark, end_mark);
+
+ return 1;
+}
+
+/*
+ * Parse the productions:
+ * block_node_or_indentless_sequence ::=
+ * ALIAS
+ * *****
+ * | properties (block_content | indentless_block_sequence)?
+ * ********** *
+ * | block_content | indentless_block_sequence
+ * *
+ * block_node ::= ALIAS
+ * *****
+ * | properties block_content?
+ * ********** *
+ * | block_content
+ * *
+ * flow_node ::= ALIAS
+ * *****
+ * | properties flow_content?
+ * ********** *
+ * | flow_content
+ * *
+ * properties ::= TAG ANCHOR? | ANCHOR TAG?
+ * *************************
+ * block_content ::= block_collection | flow_collection | SCALAR
+ * ******
+ * flow_content ::= flow_collection | SCALAR
+ * ******
+ */
+
+static int
+yaml_parser_parse_node(yaml_parser_t *parser, yaml_event_t *event,
+ int block, int indentless_sequence)
+{
+ yaml_token_t *token;
+ yaml_char_t *anchor = NULL;
+ yaml_char_t *tag_handle = NULL;
+ yaml_char_t *tag_suffix = NULL;
+ yaml_char_t *tag = NULL;
+ yaml_mark_t start_mark, end_mark, tag_mark;
+ int implicit;
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (token->type == YAML_ALIAS_TOKEN)
+ {
+ parser->state = POP(parser, parser->states);
+ ALIAS_EVENT_INIT(*event, token->data.alias.value,
+ token->start_mark, token->end_mark);
+ SKIP_TOKEN(parser);
+ return 1;
+ }
+
+ else
+ {
+ start_mark = end_mark = token->start_mark;
+
+ if (token->type == YAML_ANCHOR_TOKEN)
+ {
+ anchor = token->data.anchor.value;
+ start_mark = token->start_mark;
+ end_mark = token->end_mark;
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) goto error;
+ if (token->type == YAML_TAG_TOKEN)
+ {
+ tag_handle = token->data.tag.handle;
+ tag_suffix = token->data.tag.suffix;
+ tag_mark = token->start_mark;
+ end_mark = token->end_mark;
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) goto error;
+ }
+ }
+ else if (token->type == YAML_TAG_TOKEN)
+ {
+ tag_handle = token->data.tag.handle;
+ tag_suffix = token->data.tag.suffix;
+ start_mark = tag_mark = token->start_mark;
+ end_mark = token->end_mark;
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) goto error;
+ if (token->type == YAML_ANCHOR_TOKEN)
+ {
+ anchor = token->data.anchor.value;
+ end_mark = token->end_mark;
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) goto error;
+ }
+ }
+
+ if (tag_handle) {
+ if (!*tag_handle) {
+ tag = tag_suffix;
+ yaml_free(tag_handle);
+ tag_handle = tag_suffix = NULL;
+ }
+ else {
+ yaml_tag_directive_t *tag_directive;
+ for (tag_directive = parser->tag_directives.start;
+ tag_directive != parser->tag_directives.top;
+ tag_directive ++) {
+ if (strcmp((char *)tag_directive->handle, (char *)tag_handle) == 0) {
+ size_t prefix_len = strlen((char *)tag_directive->prefix);
+ size_t suffix_len = strlen((char *)tag_suffix);
tag = YAML_MALLOC(prefix_len+suffix_len+1);
- if (!tag) {
- parser->error = YAML_MEMORY_ERROR;
- goto error;
- }
- memcpy(tag, tag_directive->prefix, prefix_len);
- memcpy(tag+prefix_len, tag_suffix, suffix_len);
- tag[prefix_len+suffix_len] = '\0';
- yaml_free(tag_handle);
- yaml_free(tag_suffix);
- tag_handle = tag_suffix = NULL;
- break;
- }
- }
- if (!tag) {
- yaml_parser_set_parser_error_context(parser,
- "while parsing a node", start_mark,
- "found undefined tag handle", tag_mark);
- goto error;
- }
- }
- }
-
- implicit = (!tag || !*tag);
- if (indentless_sequence && token->type == YAML_BLOCK_ENTRY_TOKEN) {
- end_mark = token->end_mark;
- parser->state = YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE;
- SEQUENCE_START_EVENT_INIT(*event, anchor, tag, implicit,
- YAML_BLOCK_SEQUENCE_STYLE, start_mark, end_mark);
- return 1;
- }
- else {
- if (token->type == YAML_SCALAR_TOKEN) {
- int plain_implicit = 0;
- int quoted_implicit = 0;
- end_mark = token->end_mark;
- if ((token->data.scalar.style == YAML_PLAIN_SCALAR_STYLE && !tag)
- || (tag && strcmp((char *)tag, "!") == 0)) {
- plain_implicit = 1;
- }
- else if (!tag) {
- quoted_implicit = 1;
- }
- parser->state = POP(parser, parser->states);
- SCALAR_EVENT_INIT(*event, anchor, tag,
- token->data.scalar.value, token->data.scalar.length,
- plain_implicit, quoted_implicit,
- token->data.scalar.style, start_mark, end_mark);
- SKIP_TOKEN(parser);
- return 1;
- }
- else if (token->type == YAML_FLOW_SEQUENCE_START_TOKEN) {
- end_mark = token->end_mark;
- parser->state = YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE;
- SEQUENCE_START_EVENT_INIT(*event, anchor, tag, implicit,
- YAML_FLOW_SEQUENCE_STYLE, start_mark, end_mark);
- return 1;
- }
- else if (token->type == YAML_FLOW_MAPPING_START_TOKEN) {
- end_mark = token->end_mark;
- parser->state = YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE;
- MAPPING_START_EVENT_INIT(*event, anchor, tag, implicit,
- YAML_FLOW_MAPPING_STYLE, start_mark, end_mark);
- return 1;
- }
- else if (block && token->type == YAML_BLOCK_SEQUENCE_START_TOKEN) {
- end_mark = token->end_mark;
- parser->state = YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE;
- SEQUENCE_START_EVENT_INIT(*event, anchor, tag, implicit,
- YAML_BLOCK_SEQUENCE_STYLE, start_mark, end_mark);
- return 1;
- }
- else if (block && token->type == YAML_BLOCK_MAPPING_START_TOKEN) {
- end_mark = token->end_mark;
- parser->state = YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE;
- MAPPING_START_EVENT_INIT(*event, anchor, tag, implicit,
- YAML_BLOCK_MAPPING_STYLE, start_mark, end_mark);
- return 1;
- }
- else if (anchor || tag) {
+ if (!tag) {
+ parser->error = YAML_MEMORY_ERROR;
+ goto error;
+ }
+ memcpy(tag, tag_directive->prefix, prefix_len);
+ memcpy(tag+prefix_len, tag_suffix, suffix_len);
+ tag[prefix_len+suffix_len] = '\0';
+ yaml_free(tag_handle);
+ yaml_free(tag_suffix);
+ tag_handle = tag_suffix = NULL;
+ break;
+ }
+ }
+ if (!tag) {
+ yaml_parser_set_parser_error_context(parser,
+ "while parsing a node", start_mark,
+ "found undefined tag handle", tag_mark);
+ goto error;
+ }
+ }
+ }
+
+ implicit = (!tag || !*tag);
+ if (indentless_sequence && token->type == YAML_BLOCK_ENTRY_TOKEN) {
+ end_mark = token->end_mark;
+ parser->state = YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE;
+ SEQUENCE_START_EVENT_INIT(*event, anchor, tag, implicit,
+ YAML_BLOCK_SEQUENCE_STYLE, start_mark, end_mark);
+ return 1;
+ }
+ else {
+ if (token->type == YAML_SCALAR_TOKEN) {
+ int plain_implicit = 0;
+ int quoted_implicit = 0;
+ end_mark = token->end_mark;
+ if ((token->data.scalar.style == YAML_PLAIN_SCALAR_STYLE && !tag)
+ || (tag && strcmp((char *)tag, "!") == 0)) {
+ plain_implicit = 1;
+ }
+ else if (!tag) {
+ quoted_implicit = 1;
+ }
+ parser->state = POP(parser, parser->states);
+ SCALAR_EVENT_INIT(*event, anchor, tag,
+ token->data.scalar.value, token->data.scalar.length,
+ plain_implicit, quoted_implicit,
+ token->data.scalar.style, start_mark, end_mark);
+ SKIP_TOKEN(parser);
+ return 1;
+ }
+ else if (token->type == YAML_FLOW_SEQUENCE_START_TOKEN) {
+ end_mark = token->end_mark;
+ parser->state = YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE;
+ SEQUENCE_START_EVENT_INIT(*event, anchor, tag, implicit,
+ YAML_FLOW_SEQUENCE_STYLE, start_mark, end_mark);
+ return 1;
+ }
+ else if (token->type == YAML_FLOW_MAPPING_START_TOKEN) {
+ end_mark = token->end_mark;
+ parser->state = YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE;
+ MAPPING_START_EVENT_INIT(*event, anchor, tag, implicit,
+ YAML_FLOW_MAPPING_STYLE, start_mark, end_mark);
+ return 1;
+ }
+ else if (block && token->type == YAML_BLOCK_SEQUENCE_START_TOKEN) {
+ end_mark = token->end_mark;
+ parser->state = YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE;
+ SEQUENCE_START_EVENT_INIT(*event, anchor, tag, implicit,
+ YAML_BLOCK_SEQUENCE_STYLE, start_mark, end_mark);
+ return 1;
+ }
+ else if (block && token->type == YAML_BLOCK_MAPPING_START_TOKEN) {
+ end_mark = token->end_mark;
+ parser->state = YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE;
+ MAPPING_START_EVENT_INIT(*event, anchor, tag, implicit,
+ YAML_BLOCK_MAPPING_STYLE, start_mark, end_mark);
+ return 1;
+ }
+ else if (anchor || tag) {
yaml_char_t *value = YAML_MALLOC(1);
- if (!value) {
- parser->error = YAML_MEMORY_ERROR;
- goto error;
- }
- value[0] = '\0';
- parser->state = POP(parser, parser->states);
- SCALAR_EVENT_INIT(*event, anchor, tag, value, 0,
- implicit, 0, YAML_PLAIN_SCALAR_STYLE,
- start_mark, end_mark);
- return 1;
- }
- else {
- yaml_parser_set_parser_error_context(parser,
- (block ? "while parsing a block node"
- : "while parsing a flow node"), start_mark,
- "did not find expected node content", token->start_mark);
- goto error;
- }
- }
- }
-
-error:
- yaml_free(anchor);
- yaml_free(tag_handle);
- yaml_free(tag_suffix);
- yaml_free(tag);
-
- return 0;
-}
-
-/*
- * Parse the productions:
- * block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
- * ******************** *********** * *********
- */
-
-static int
-yaml_parser_parse_block_sequence_entry(yaml_parser_t *parser,
- yaml_event_t *event, int first)
-{
- yaml_token_t *token;
-
- if (first) {
- token = PEEK_TOKEN(parser);
- if (!PUSH(parser, parser->marks, token->start_mark))
- return 0;
- SKIP_TOKEN(parser);
- }
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (token->type == YAML_BLOCK_ENTRY_TOKEN)
- {
- yaml_mark_t mark = token->end_mark;
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
- if (token->type != YAML_BLOCK_ENTRY_TOKEN &&
- token->type != YAML_BLOCK_END_TOKEN) {
- if (!PUSH(parser, parser->states,
- YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE))
- return 0;
- return yaml_parser_parse_node(parser, event, 1, 0);
- }
- else {
- parser->state = YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE;
- return yaml_parser_process_empty_scalar(parser, event, mark);
- }
- }
-
- else if (token->type == YAML_BLOCK_END_TOKEN)
- {
- parser->state = POP(parser, parser->states);
+ if (!value) {
+ parser->error = YAML_MEMORY_ERROR;
+ goto error;
+ }
+ value[0] = '\0';
+ parser->state = POP(parser, parser->states);
+ SCALAR_EVENT_INIT(*event, anchor, tag, value, 0,
+ implicit, 0, YAML_PLAIN_SCALAR_STYLE,
+ start_mark, end_mark);
+ return 1;
+ }
+ else {
+ yaml_parser_set_parser_error_context(parser,
+ (block ? "while parsing a block node"
+ : "while parsing a flow node"), start_mark,
+ "did not find expected node content", token->start_mark);
+ goto error;
+ }
+ }
+ }
+
+error:
+ yaml_free(anchor);
+ yaml_free(tag_handle);
+ yaml_free(tag_suffix);
+ yaml_free(tag);
+
+ return 0;
+}
+
+/*
+ * Parse the productions:
+ * block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
+ * ******************** *********** * *********
+ */
+
+static int
+yaml_parser_parse_block_sequence_entry(yaml_parser_t *parser,
+ yaml_event_t *event, int first)
+{
+ yaml_token_t *token;
+
+ if (first) {
+ token = PEEK_TOKEN(parser);
+ if (!PUSH(parser, parser->marks, token->start_mark))
+ return 0;
+ SKIP_TOKEN(parser);
+ }
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (token->type == YAML_BLOCK_ENTRY_TOKEN)
+ {
+ yaml_mark_t mark = token->end_mark;
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+ if (token->type != YAML_BLOCK_ENTRY_TOKEN &&
+ token->type != YAML_BLOCK_END_TOKEN) {
+ if (!PUSH(parser, parser->states,
+ YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE))
+ return 0;
+ return yaml_parser_parse_node(parser, event, 1, 0);
+ }
+ else {
+ parser->state = YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE;
+ return yaml_parser_process_empty_scalar(parser, event, mark);
+ }
+ }
+
+ else if (token->type == YAML_BLOCK_END_TOKEN)
+ {
+ parser->state = POP(parser, parser->states);
(void)POP(parser, parser->marks);
- SEQUENCE_END_EVENT_INIT(*event, token->start_mark, token->end_mark);
- SKIP_TOKEN(parser);
- return 1;
- }
-
- else
- {
- return yaml_parser_set_parser_error_context(parser,
- "while parsing a block collection", POP(parser, parser->marks),
- "did not find expected '-' indicator", token->start_mark);
- }
-}
-
-/*
- * Parse the productions:
- * indentless_sequence ::= (BLOCK-ENTRY block_node?)+
- * *********** *
- */
-
-static int
-yaml_parser_parse_indentless_sequence_entry(yaml_parser_t *parser,
- yaml_event_t *event)
-{
- yaml_token_t *token;
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (token->type == YAML_BLOCK_ENTRY_TOKEN)
- {
- yaml_mark_t mark = token->end_mark;
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
- if (token->type != YAML_BLOCK_ENTRY_TOKEN &&
- token->type != YAML_KEY_TOKEN &&
- token->type != YAML_VALUE_TOKEN &&
- token->type != YAML_BLOCK_END_TOKEN) {
- if (!PUSH(parser, parser->states,
- YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE))
- return 0;
- return yaml_parser_parse_node(parser, event, 1, 0);
- }
- else {
- parser->state = YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE;
- return yaml_parser_process_empty_scalar(parser, event, mark);
- }
- }
-
- else
- {
- parser->state = POP(parser, parser->states);
- SEQUENCE_END_EVENT_INIT(*event, token->start_mark, token->start_mark);
- return 1;
- }
-}
-
-/*
- * Parse the productions:
- * block_mapping ::= BLOCK-MAPPING_START
- * *******************
- * ((KEY block_node_or_indentless_sequence?)?
- * *** *
- * (VALUE block_node_or_indentless_sequence?)?)*
- *
- * BLOCK-END
- * *********
- */
-
-static int
-yaml_parser_parse_block_mapping_key(yaml_parser_t *parser,
- yaml_event_t *event, int first)
-{
- yaml_token_t *token;
-
- if (first) {
- token = PEEK_TOKEN(parser);
- if (!PUSH(parser, parser->marks, token->start_mark))
- return 0;
- SKIP_TOKEN(parser);
- }
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (token->type == YAML_KEY_TOKEN)
- {
- yaml_mark_t mark = token->end_mark;
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
- if (token->type != YAML_KEY_TOKEN &&
- token->type != YAML_VALUE_TOKEN &&
- token->type != YAML_BLOCK_END_TOKEN) {
- if (!PUSH(parser, parser->states,
- YAML_PARSE_BLOCK_MAPPING_VALUE_STATE))
- return 0;
- return yaml_parser_parse_node(parser, event, 1, 1);
- }
- else {
- parser->state = YAML_PARSE_BLOCK_MAPPING_VALUE_STATE;
- return yaml_parser_process_empty_scalar(parser, event, mark);
- }
- }
-
- else if (token->type == YAML_BLOCK_END_TOKEN)
- {
- parser->state = POP(parser, parser->states);
+ SEQUENCE_END_EVENT_INIT(*event, token->start_mark, token->end_mark);
+ SKIP_TOKEN(parser);
+ return 1;
+ }
+
+ else
+ {
+ return yaml_parser_set_parser_error_context(parser,
+ "while parsing a block collection", POP(parser, parser->marks),
+ "did not find expected '-' indicator", token->start_mark);
+ }
+}
+
+/*
+ * Parse the productions:
+ * indentless_sequence ::= (BLOCK-ENTRY block_node?)+
+ * *********** *
+ */
+
+static int
+yaml_parser_parse_indentless_sequence_entry(yaml_parser_t *parser,
+ yaml_event_t *event)
+{
+ yaml_token_t *token;
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (token->type == YAML_BLOCK_ENTRY_TOKEN)
+ {
+ yaml_mark_t mark = token->end_mark;
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+ if (token->type != YAML_BLOCK_ENTRY_TOKEN &&
+ token->type != YAML_KEY_TOKEN &&
+ token->type != YAML_VALUE_TOKEN &&
+ token->type != YAML_BLOCK_END_TOKEN) {
+ if (!PUSH(parser, parser->states,
+ YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE))
+ return 0;
+ return yaml_parser_parse_node(parser, event, 1, 0);
+ }
+ else {
+ parser->state = YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE;
+ return yaml_parser_process_empty_scalar(parser, event, mark);
+ }
+ }
+
+ else
+ {
+ parser->state = POP(parser, parser->states);
+ SEQUENCE_END_EVENT_INIT(*event, token->start_mark, token->start_mark);
+ return 1;
+ }
+}
+
+/*
+ * Parse the productions:
+ * block_mapping ::= BLOCK-MAPPING_START
+ * *******************
+ * ((KEY block_node_or_indentless_sequence?)?
+ * *** *
+ * (VALUE block_node_or_indentless_sequence?)?)*
+ *
+ * BLOCK-END
+ * *********
+ */
+
+static int
+yaml_parser_parse_block_mapping_key(yaml_parser_t *parser,
+ yaml_event_t *event, int first)
+{
+ yaml_token_t *token;
+
+ if (first) {
+ token = PEEK_TOKEN(parser);
+ if (!PUSH(parser, parser->marks, token->start_mark))
+ return 0;
+ SKIP_TOKEN(parser);
+ }
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (token->type == YAML_KEY_TOKEN)
+ {
+ yaml_mark_t mark = token->end_mark;
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+ if (token->type != YAML_KEY_TOKEN &&
+ token->type != YAML_VALUE_TOKEN &&
+ token->type != YAML_BLOCK_END_TOKEN) {
+ if (!PUSH(parser, parser->states,
+ YAML_PARSE_BLOCK_MAPPING_VALUE_STATE))
+ return 0;
+ return yaml_parser_parse_node(parser, event, 1, 1);
+ }
+ else {
+ parser->state = YAML_PARSE_BLOCK_MAPPING_VALUE_STATE;
+ return yaml_parser_process_empty_scalar(parser, event, mark);
+ }
+ }
+
+ else if (token->type == YAML_BLOCK_END_TOKEN)
+ {
+ parser->state = POP(parser, parser->states);
(void)POP(parser, parser->marks);
- MAPPING_END_EVENT_INIT(*event, token->start_mark, token->end_mark);
- SKIP_TOKEN(parser);
- return 1;
- }
-
- else
- {
- return yaml_parser_set_parser_error_context(parser,
- "while parsing a block mapping", POP(parser, parser->marks),
- "did not find expected key", token->start_mark);
- }
-}
-
-/*
- * Parse the productions:
- * block_mapping ::= BLOCK-MAPPING_START
- *
- * ((KEY block_node_or_indentless_sequence?)?
- *
- * (VALUE block_node_or_indentless_sequence?)?)*
- * ***** *
- * BLOCK-END
- *
- */
-
-static int
-yaml_parser_parse_block_mapping_value(yaml_parser_t *parser,
- yaml_event_t *event)
-{
- yaml_token_t *token;
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (token->type == YAML_VALUE_TOKEN)
- {
- yaml_mark_t mark = token->end_mark;
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
- if (token->type != YAML_KEY_TOKEN &&
- token->type != YAML_VALUE_TOKEN &&
- token->type != YAML_BLOCK_END_TOKEN) {
- if (!PUSH(parser, parser->states,
- YAML_PARSE_BLOCK_MAPPING_KEY_STATE))
- return 0;
- return yaml_parser_parse_node(parser, event, 1, 1);
- }
- else {
- parser->state = YAML_PARSE_BLOCK_MAPPING_KEY_STATE;
- return yaml_parser_process_empty_scalar(parser, event, mark);
- }
- }
-
- else
- {
- parser->state = YAML_PARSE_BLOCK_MAPPING_KEY_STATE;
- return yaml_parser_process_empty_scalar(parser, event, token->start_mark);
- }
-}
-
-/*
- * Parse the productions:
- * flow_sequence ::= FLOW-SEQUENCE-START
- * *******************
- * (flow_sequence_entry FLOW-ENTRY)*
- * * **********
- * flow_sequence_entry?
- * *
- * FLOW-SEQUENCE-END
- * *****************
- * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
- * *
- */
-
-static int
-yaml_parser_parse_flow_sequence_entry(yaml_parser_t *parser,
- yaml_event_t *event, int first)
-{
- yaml_token_t *token;
-
- if (first) {
- token = PEEK_TOKEN(parser);
- if (!PUSH(parser, parser->marks, token->start_mark))
- return 0;
- SKIP_TOKEN(parser);
- }
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (token->type != YAML_FLOW_SEQUENCE_END_TOKEN)
- {
- if (!first) {
- if (token->type == YAML_FLOW_ENTRY_TOKEN) {
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
- }
- else {
- return yaml_parser_set_parser_error_context(parser,
- "while parsing a flow sequence", POP(parser, parser->marks),
- "did not find expected ',' or ']'", token->start_mark);
- }
- }
-
- if (token->type == YAML_KEY_TOKEN) {
- parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE;
- MAPPING_START_EVENT_INIT(*event, NULL, NULL,
- 1, YAML_FLOW_MAPPING_STYLE,
- token->start_mark, token->end_mark);
- SKIP_TOKEN(parser);
- return 1;
- }
-
- else if (token->type != YAML_FLOW_SEQUENCE_END_TOKEN) {
- if (!PUSH(parser, parser->states,
- YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE))
- return 0;
- return yaml_parser_parse_node(parser, event, 0, 0);
- }
- }
-
- parser->state = POP(parser, parser->states);
+ MAPPING_END_EVENT_INIT(*event, token->start_mark, token->end_mark);
+ SKIP_TOKEN(parser);
+ return 1;
+ }
+
+ else
+ {
+ return yaml_parser_set_parser_error_context(parser,
+ "while parsing a block mapping", POP(parser, parser->marks),
+ "did not find expected key", token->start_mark);
+ }
+}
+
+/*
+ * Parse the productions:
+ * block_mapping ::= BLOCK-MAPPING_START
+ *
+ * ((KEY block_node_or_indentless_sequence?)?
+ *
+ * (VALUE block_node_or_indentless_sequence?)?)*
+ * ***** *
+ * BLOCK-END
+ *
+ */
+
+static int
+yaml_parser_parse_block_mapping_value(yaml_parser_t *parser,
+ yaml_event_t *event)
+{
+ yaml_token_t *token;
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (token->type == YAML_VALUE_TOKEN)
+ {
+ yaml_mark_t mark = token->end_mark;
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+ if (token->type != YAML_KEY_TOKEN &&
+ token->type != YAML_VALUE_TOKEN &&
+ token->type != YAML_BLOCK_END_TOKEN) {
+ if (!PUSH(parser, parser->states,
+ YAML_PARSE_BLOCK_MAPPING_KEY_STATE))
+ return 0;
+ return yaml_parser_parse_node(parser, event, 1, 1);
+ }
+ else {
+ parser->state = YAML_PARSE_BLOCK_MAPPING_KEY_STATE;
+ return yaml_parser_process_empty_scalar(parser, event, mark);
+ }
+ }
+
+ else
+ {
+ parser->state = YAML_PARSE_BLOCK_MAPPING_KEY_STATE;
+ return yaml_parser_process_empty_scalar(parser, event, token->start_mark);
+ }
+}
+
+/*
+ * Parse the productions:
+ * flow_sequence ::= FLOW-SEQUENCE-START
+ * *******************
+ * (flow_sequence_entry FLOW-ENTRY)*
+ * * **********
+ * flow_sequence_entry?
+ * *
+ * FLOW-SEQUENCE-END
+ * *****************
+ * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+ * *
+ */
+
+static int
+yaml_parser_parse_flow_sequence_entry(yaml_parser_t *parser,
+ yaml_event_t *event, int first)
+{
+ yaml_token_t *token;
+
+ if (first) {
+ token = PEEK_TOKEN(parser);
+ if (!PUSH(parser, parser->marks, token->start_mark))
+ return 0;
+ SKIP_TOKEN(parser);
+ }
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (token->type != YAML_FLOW_SEQUENCE_END_TOKEN)
+ {
+ if (!first) {
+ if (token->type == YAML_FLOW_ENTRY_TOKEN) {
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+ }
+ else {
+ return yaml_parser_set_parser_error_context(parser,
+ "while parsing a flow sequence", POP(parser, parser->marks),
+ "did not find expected ',' or ']'", token->start_mark);
+ }
+ }
+
+ if (token->type == YAML_KEY_TOKEN) {
+ parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE;
+ MAPPING_START_EVENT_INIT(*event, NULL, NULL,
+ 1, YAML_FLOW_MAPPING_STYLE,
+ token->start_mark, token->end_mark);
+ SKIP_TOKEN(parser);
+ return 1;
+ }
+
+ else if (token->type != YAML_FLOW_SEQUENCE_END_TOKEN) {
+ if (!PUSH(parser, parser->states,
+ YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE))
+ return 0;
+ return yaml_parser_parse_node(parser, event, 0, 0);
+ }
+ }
+
+ parser->state = POP(parser, parser->states);
(void)POP(parser, parser->marks);
- SEQUENCE_END_EVENT_INIT(*event, token->start_mark, token->end_mark);
- SKIP_TOKEN(parser);
- return 1;
-}
-
-/*
- * Parse the productions:
- * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
- * *** *
- */
-
-static int
-yaml_parser_parse_flow_sequence_entry_mapping_key(yaml_parser_t *parser,
- yaml_event_t *event)
-{
- yaml_token_t *token;
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (token->type != YAML_VALUE_TOKEN && token->type != YAML_FLOW_ENTRY_TOKEN
- && token->type != YAML_FLOW_SEQUENCE_END_TOKEN) {
- if (!PUSH(parser, parser->states,
- YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE))
- return 0;
- return yaml_parser_parse_node(parser, event, 0, 0);
- }
- else {
- yaml_mark_t mark = token->end_mark;
- SKIP_TOKEN(parser);
- parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE;
- return yaml_parser_process_empty_scalar(parser, event, mark);
- }
-}
-
-/*
- * Parse the productions:
- * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
- * ***** *
- */
-
-static int
-yaml_parser_parse_flow_sequence_entry_mapping_value(yaml_parser_t *parser,
- yaml_event_t *event)
-{
- yaml_token_t *token;
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (token->type == YAML_VALUE_TOKEN) {
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
- if (token->type != YAML_FLOW_ENTRY_TOKEN
- && token->type != YAML_FLOW_SEQUENCE_END_TOKEN) {
- if (!PUSH(parser, parser->states,
- YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE))
- return 0;
- return yaml_parser_parse_node(parser, event, 0, 0);
- }
- }
- parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE;
- return yaml_parser_process_empty_scalar(parser, event, token->start_mark);
-}
-
-/*
- * Parse the productions:
- * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
- * *
- */
-
-static int
-yaml_parser_parse_flow_sequence_entry_mapping_end(yaml_parser_t *parser,
- yaml_event_t *event)
-{
- yaml_token_t *token;
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE;
-
- MAPPING_END_EVENT_INIT(*event, token->start_mark, token->start_mark);
- return 1;
-}
-
-/*
- * Parse the productions:
- * flow_mapping ::= FLOW-MAPPING-START
- * ******************
- * (flow_mapping_entry FLOW-ENTRY)*
- * * **********
- * flow_mapping_entry?
- * ******************
- * FLOW-MAPPING-END
- * ****************
- * flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
- * * *** *
- */
-
-static int
-yaml_parser_parse_flow_mapping_key(yaml_parser_t *parser,
- yaml_event_t *event, int first)
-{
- yaml_token_t *token;
-
- if (first) {
- token = PEEK_TOKEN(parser);
- if (!PUSH(parser, parser->marks, token->start_mark))
- return 0;
- SKIP_TOKEN(parser);
- }
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (token->type != YAML_FLOW_MAPPING_END_TOKEN)
- {
- if (!first) {
- if (token->type == YAML_FLOW_ENTRY_TOKEN) {
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
- }
- else {
- return yaml_parser_set_parser_error_context(parser,
- "while parsing a flow mapping", POP(parser, parser->marks),
- "did not find expected ',' or '}'", token->start_mark);
- }
- }
-
- if (token->type == YAML_KEY_TOKEN) {
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
- if (token->type != YAML_VALUE_TOKEN
- && token->type != YAML_FLOW_ENTRY_TOKEN
- && token->type != YAML_FLOW_MAPPING_END_TOKEN) {
- if (!PUSH(parser, parser->states,
- YAML_PARSE_FLOW_MAPPING_VALUE_STATE))
- return 0;
- return yaml_parser_parse_node(parser, event, 0, 0);
- }
- else {
- parser->state = YAML_PARSE_FLOW_MAPPING_VALUE_STATE;
- return yaml_parser_process_empty_scalar(parser, event,
- token->start_mark);
- }
- }
- else if (token->type != YAML_FLOW_MAPPING_END_TOKEN) {
- if (!PUSH(parser, parser->states,
- YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE))
- return 0;
- return yaml_parser_parse_node(parser, event, 0, 0);
- }
- }
-
- parser->state = POP(parser, parser->states);
+ SEQUENCE_END_EVENT_INIT(*event, token->start_mark, token->end_mark);
+ SKIP_TOKEN(parser);
+ return 1;
+}
+
+/*
+ * Parse the productions:
+ * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+ * *** *
+ */
+
+static int
+yaml_parser_parse_flow_sequence_entry_mapping_key(yaml_parser_t *parser,
+ yaml_event_t *event)
+{
+ yaml_token_t *token;
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (token->type != YAML_VALUE_TOKEN && token->type != YAML_FLOW_ENTRY_TOKEN
+ && token->type != YAML_FLOW_SEQUENCE_END_TOKEN) {
+ if (!PUSH(parser, parser->states,
+ YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE))
+ return 0;
+ return yaml_parser_parse_node(parser, event, 0, 0);
+ }
+ else {
+ yaml_mark_t mark = token->end_mark;
+ SKIP_TOKEN(parser);
+ parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE;
+ return yaml_parser_process_empty_scalar(parser, event, mark);
+ }
+}
+
+/*
+ * Parse the productions:
+ * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+ * ***** *
+ */
+
+static int
+yaml_parser_parse_flow_sequence_entry_mapping_value(yaml_parser_t *parser,
+ yaml_event_t *event)
+{
+ yaml_token_t *token;
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (token->type == YAML_VALUE_TOKEN) {
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+ if (token->type != YAML_FLOW_ENTRY_TOKEN
+ && token->type != YAML_FLOW_SEQUENCE_END_TOKEN) {
+ if (!PUSH(parser, parser->states,
+ YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE))
+ return 0;
+ return yaml_parser_parse_node(parser, event, 0, 0);
+ }
+ }
+ parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE;
+ return yaml_parser_process_empty_scalar(parser, event, token->start_mark);
+}
+
+/*
+ * Parse the productions:
+ * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+ * *
+ */
+
+static int
+yaml_parser_parse_flow_sequence_entry_mapping_end(yaml_parser_t *parser,
+ yaml_event_t *event)
+{
+ yaml_token_t *token;
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE;
+
+ MAPPING_END_EVENT_INIT(*event, token->start_mark, token->start_mark);
+ return 1;
+}
+
+/*
+ * Parse the productions:
+ * flow_mapping ::= FLOW-MAPPING-START
+ * ******************
+ * (flow_mapping_entry FLOW-ENTRY)*
+ * * **********
+ * flow_mapping_entry?
+ * ******************
+ * FLOW-MAPPING-END
+ * ****************
+ * flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+ * * *** *
+ */
+
+static int
+yaml_parser_parse_flow_mapping_key(yaml_parser_t *parser,
+ yaml_event_t *event, int first)
+{
+ yaml_token_t *token;
+
+ if (first) {
+ token = PEEK_TOKEN(parser);
+ if (!PUSH(parser, parser->marks, token->start_mark))
+ return 0;
+ SKIP_TOKEN(parser);
+ }
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (token->type != YAML_FLOW_MAPPING_END_TOKEN)
+ {
+ if (!first) {
+ if (token->type == YAML_FLOW_ENTRY_TOKEN) {
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+ }
+ else {
+ return yaml_parser_set_parser_error_context(parser,
+ "while parsing a flow mapping", POP(parser, parser->marks),
+ "did not find expected ',' or '}'", token->start_mark);
+ }
+ }
+
+ if (token->type == YAML_KEY_TOKEN) {
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+ if (token->type != YAML_VALUE_TOKEN
+ && token->type != YAML_FLOW_ENTRY_TOKEN
+ && token->type != YAML_FLOW_MAPPING_END_TOKEN) {
+ if (!PUSH(parser, parser->states,
+ YAML_PARSE_FLOW_MAPPING_VALUE_STATE))
+ return 0;
+ return yaml_parser_parse_node(parser, event, 0, 0);
+ }
+ else {
+ parser->state = YAML_PARSE_FLOW_MAPPING_VALUE_STATE;
+ return yaml_parser_process_empty_scalar(parser, event,
+ token->start_mark);
+ }
+ }
+ else if (token->type != YAML_FLOW_MAPPING_END_TOKEN) {
+ if (!PUSH(parser, parser->states,
+ YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE))
+ return 0;
+ return yaml_parser_parse_node(parser, event, 0, 0);
+ }
+ }
+
+ parser->state = POP(parser, parser->states);
(void)POP(parser, parser->marks);
- MAPPING_END_EVENT_INIT(*event, token->start_mark, token->end_mark);
- SKIP_TOKEN(parser);
- return 1;
-}
-
-/*
- * Parse the productions:
- * flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
- * * ***** *
- */
-
-static int
-yaml_parser_parse_flow_mapping_value(yaml_parser_t *parser,
- yaml_event_t *event, int empty)
-{
- yaml_token_t *token;
-
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
-
- if (empty) {
- parser->state = YAML_PARSE_FLOW_MAPPING_KEY_STATE;
- return yaml_parser_process_empty_scalar(parser, event,
- token->start_mark);
- }
-
- if (token->type == YAML_VALUE_TOKEN) {
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) return 0;
- if (token->type != YAML_FLOW_ENTRY_TOKEN
- && token->type != YAML_FLOW_MAPPING_END_TOKEN) {
- if (!PUSH(parser, parser->states,
- YAML_PARSE_FLOW_MAPPING_KEY_STATE))
- return 0;
- return yaml_parser_parse_node(parser, event, 0, 0);
- }
- }
-
- parser->state = YAML_PARSE_FLOW_MAPPING_KEY_STATE;
- return yaml_parser_process_empty_scalar(parser, event, token->start_mark);
-}
-
-/*
- * Generate an empty scalar event.
- */
-
-static int
-yaml_parser_process_empty_scalar(yaml_parser_t *parser, yaml_event_t *event,
- yaml_mark_t mark)
-{
- yaml_char_t *value;
-
+ MAPPING_END_EVENT_INIT(*event, token->start_mark, token->end_mark);
+ SKIP_TOKEN(parser);
+ return 1;
+}
+
+/*
+ * Parse the productions:
+ * flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+ * * ***** *
+ */
+
+static int
+yaml_parser_parse_flow_mapping_value(yaml_parser_t *parser,
+ yaml_event_t *event, int empty)
+{
+ yaml_token_t *token;
+
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+
+ if (empty) {
+ parser->state = YAML_PARSE_FLOW_MAPPING_KEY_STATE;
+ return yaml_parser_process_empty_scalar(parser, event,
+ token->start_mark);
+ }
+
+ if (token->type == YAML_VALUE_TOKEN) {
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) return 0;
+ if (token->type != YAML_FLOW_ENTRY_TOKEN
+ && token->type != YAML_FLOW_MAPPING_END_TOKEN) {
+ if (!PUSH(parser, parser->states,
+ YAML_PARSE_FLOW_MAPPING_KEY_STATE))
+ return 0;
+ return yaml_parser_parse_node(parser, event, 0, 0);
+ }
+ }
+
+ parser->state = YAML_PARSE_FLOW_MAPPING_KEY_STATE;
+ return yaml_parser_process_empty_scalar(parser, event, token->start_mark);
+}
+
+/*
+ * Generate an empty scalar event.
+ */
+
+static int
+yaml_parser_process_empty_scalar(yaml_parser_t *parser, yaml_event_t *event,
+ yaml_mark_t mark)
+{
+ yaml_char_t *value;
+
value = YAML_MALLOC(1);
- if (!value) {
- parser->error = YAML_MEMORY_ERROR;
- return 0;
- }
- value[0] = '\0';
-
- SCALAR_EVENT_INIT(*event, NULL, NULL, value, 0,
- 1, 0, YAML_PLAIN_SCALAR_STYLE, mark, mark);
-
- return 1;
-}
-
-/*
- * Parse directives.
- */
-
-static int
-yaml_parser_process_directives(yaml_parser_t *parser,
- yaml_version_directive_t **version_directive_ref,
- yaml_tag_directive_t **tag_directives_start_ref,
- yaml_tag_directive_t **tag_directives_end_ref)
-{
- yaml_tag_directive_t default_tag_directives[] = {
- {(yaml_char_t *)"!", (yaml_char_t *)"!"},
- {(yaml_char_t *)"!!", (yaml_char_t *)"tag:yaml.org,2002:"},
- {NULL, NULL}
- };
- yaml_tag_directive_t *default_tag_directive;
- yaml_version_directive_t *version_directive = NULL;
- struct {
- yaml_tag_directive_t *start;
- yaml_tag_directive_t *end;
- yaml_tag_directive_t *top;
- } tag_directives = { NULL, NULL, NULL };
- yaml_token_t *token;
-
+ if (!value) {
+ parser->error = YAML_MEMORY_ERROR;
+ return 0;
+ }
+ value[0] = '\0';
+
+ SCALAR_EVENT_INIT(*event, NULL, NULL, value, 0,
+ 1, 0, YAML_PLAIN_SCALAR_STYLE, mark, mark);
+
+ return 1;
+}
+
+/*
+ * Parse directives.
+ */
+
+static int
+yaml_parser_process_directives(yaml_parser_t *parser,
+ yaml_version_directive_t **version_directive_ref,
+ yaml_tag_directive_t **tag_directives_start_ref,
+ yaml_tag_directive_t **tag_directives_end_ref)
+{
+ yaml_tag_directive_t default_tag_directives[] = {
+ {(yaml_char_t *)"!", (yaml_char_t *)"!"},
+ {(yaml_char_t *)"!!", (yaml_char_t *)"tag:yaml.org,2002:"},
+ {NULL, NULL}
+ };
+ yaml_tag_directive_t *default_tag_directive;
+ yaml_version_directive_t *version_directive = NULL;
+ struct {
+ yaml_tag_directive_t *start;
+ yaml_tag_directive_t *end;
+ yaml_tag_directive_t *top;
+ } tag_directives = { NULL, NULL, NULL };
+ yaml_token_t *token;
+
if (!STACK_INIT(parser, tag_directives, yaml_tag_directive_t*))
- goto error;
-
- token = PEEK_TOKEN(parser);
- if (!token) goto error;
-
- while (token->type == YAML_VERSION_DIRECTIVE_TOKEN ||
- token->type == YAML_TAG_DIRECTIVE_TOKEN)
- {
- if (token->type == YAML_VERSION_DIRECTIVE_TOKEN) {
- if (version_directive) {
- yaml_parser_set_parser_error(parser,
- "found duplicate %YAML directive", token->start_mark);
- goto error;
- }
- if (token->data.version_directive.major != 1
+ goto error;
+
+ token = PEEK_TOKEN(parser);
+ if (!token) goto error;
+
+ while (token->type == YAML_VERSION_DIRECTIVE_TOKEN ||
+ token->type == YAML_TAG_DIRECTIVE_TOKEN)
+ {
+ if (token->type == YAML_VERSION_DIRECTIVE_TOKEN) {
+ if (version_directive) {
+ yaml_parser_set_parser_error(parser,
+ "found duplicate %YAML directive", token->start_mark);
+ goto error;
+ }
+ if (token->data.version_directive.major != 1
|| (
token->data.version_directive.minor != 1
&& token->data.version_directive.minor != 2
)) {
- yaml_parser_set_parser_error(parser,
- "found incompatible YAML document", token->start_mark);
- goto error;
- }
+ yaml_parser_set_parser_error(parser,
+ "found incompatible YAML document", token->start_mark);
+ goto error;
+ }
version_directive = YAML_MALLOC_STATIC(yaml_version_directive_t);
- if (!version_directive) {
- parser->error = YAML_MEMORY_ERROR;
- goto error;
- }
- version_directive->major = token->data.version_directive.major;
- version_directive->minor = token->data.version_directive.minor;
- }
-
- else if (token->type == YAML_TAG_DIRECTIVE_TOKEN) {
- yaml_tag_directive_t value;
- value.handle = token->data.tag_directive.handle;
- value.prefix = token->data.tag_directive.prefix;
-
- if (!yaml_parser_append_tag_directive(parser, value, 0,
- token->start_mark))
- goto error;
- if (!PUSH(parser, tag_directives, value))
- goto error;
- }
-
- SKIP_TOKEN(parser);
- token = PEEK_TOKEN(parser);
- if (!token) goto error;
- }
-
- for (default_tag_directive = default_tag_directives;
- default_tag_directive->handle; default_tag_directive++) {
- if (!yaml_parser_append_tag_directive(parser, *default_tag_directive, 1,
- token->start_mark))
- goto error;
- }
-
- if (version_directive_ref) {
- *version_directive_ref = version_directive;
- }
- if (tag_directives_start_ref) {
- if (STACK_EMPTY(parser, tag_directives)) {
- *tag_directives_start_ref = *tag_directives_end_ref = NULL;
- STACK_DEL(parser, tag_directives);
- }
- else {
- *tag_directives_start_ref = tag_directives.start;
- *tag_directives_end_ref = tag_directives.top;
- }
- }
- else {
- STACK_DEL(parser, tag_directives);
- }
-
+ if (!version_directive) {
+ parser->error = YAML_MEMORY_ERROR;
+ goto error;
+ }
+ version_directive->major = token->data.version_directive.major;
+ version_directive->minor = token->data.version_directive.minor;
+ }
+
+ else if (token->type == YAML_TAG_DIRECTIVE_TOKEN) {
+ yaml_tag_directive_t value;
+ value.handle = token->data.tag_directive.handle;
+ value.prefix = token->data.tag_directive.prefix;
+
+ if (!yaml_parser_append_tag_directive(parser, value, 0,
+ token->start_mark))
+ goto error;
+ if (!PUSH(parser, tag_directives, value))
+ goto error;
+ }
+
+ SKIP_TOKEN(parser);
+ token = PEEK_TOKEN(parser);
+ if (!token) goto error;
+ }
+
+ for (default_tag_directive = default_tag_directives;
+ default_tag_directive->handle; default_tag_directive++) {
+ if (!yaml_parser_append_tag_directive(parser, *default_tag_directive, 1,
+ token->start_mark))
+ goto error;
+ }
+
+ if (version_directive_ref) {
+ *version_directive_ref = version_directive;
+ }
+ if (tag_directives_start_ref) {
+ if (STACK_EMPTY(parser, tag_directives)) {
+ *tag_directives_start_ref = *tag_directives_end_ref = NULL;
+ STACK_DEL(parser, tag_directives);
+ }
+ else {
+ *tag_directives_start_ref = tag_directives.start;
+ *tag_directives_end_ref = tag_directives.top;
+ }
+ }
+ else {
+ STACK_DEL(parser, tag_directives);
+ }
+
if (!version_directive_ref)
yaml_free(version_directive);
- return 1;
-
-error:
- yaml_free(version_directive);
- while (!STACK_EMPTY(parser, tag_directives)) {
- yaml_tag_directive_t tag_directive = POP(parser, tag_directives);
- yaml_free(tag_directive.handle);
- yaml_free(tag_directive.prefix);
- }
- STACK_DEL(parser, tag_directives);
- return 0;
-}
-
-/*
- * Append a tag directive to the directives stack.
- */
-
-static int
-yaml_parser_append_tag_directive(yaml_parser_t *parser,
- yaml_tag_directive_t value, int allow_duplicates, yaml_mark_t mark)
-{
- yaml_tag_directive_t *tag_directive;
- yaml_tag_directive_t copy = { NULL, NULL };
-
- for (tag_directive = parser->tag_directives.start;
- tag_directive != parser->tag_directives.top; tag_directive ++) {
- if (strcmp((char *)value.handle, (char *)tag_directive->handle) == 0) {
- if (allow_duplicates)
- return 1;
- return yaml_parser_set_parser_error(parser,
- "found duplicate %TAG directive", mark);
- }
- }
-
- copy.handle = yaml_strdup(value.handle);
- copy.prefix = yaml_strdup(value.prefix);
- if (!copy.handle || !copy.prefix) {
- parser->error = YAML_MEMORY_ERROR;
- goto error;
- }
-
- if (!PUSH(parser, parser->tag_directives, copy))
- goto error;
-
- return 1;
-
-error:
- yaml_free(copy.handle);
- yaml_free(copy.prefix);
- return 0;
-}
-
+ return 1;
+
+error:
+ yaml_free(version_directive);
+ while (!STACK_EMPTY(parser, tag_directives)) {
+ yaml_tag_directive_t tag_directive = POP(parser, tag_directives);
+ yaml_free(tag_directive.handle);
+ yaml_free(tag_directive.prefix);
+ }
+ STACK_DEL(parser, tag_directives);
+ return 0;
+}
+
+/*
+ * Append a tag directive to the directives stack.
+ */
+
+static int
+yaml_parser_append_tag_directive(yaml_parser_t *parser,
+ yaml_tag_directive_t value, int allow_duplicates, yaml_mark_t mark)
+{
+ yaml_tag_directive_t *tag_directive;
+ yaml_tag_directive_t copy = { NULL, NULL };
+
+ for (tag_directive = parser->tag_directives.start;
+ tag_directive != parser->tag_directives.top; tag_directive ++) {
+ if (strcmp((char *)value.handle, (char *)tag_directive->handle) == 0) {
+ if (allow_duplicates)
+ return 1;
+ return yaml_parser_set_parser_error(parser,
+ "found duplicate %TAG directive", mark);
+ }
+ }
+
+ copy.handle = yaml_strdup(value.handle);
+ copy.prefix = yaml_strdup(value.prefix);
+ if (!copy.handle || !copy.prefix) {
+ parser->error = YAML_MEMORY_ERROR;
+ goto error;
+ }
+
+ if (!PUSH(parser, parser->tag_directives, copy))
+ goto error;
+
+ return 1;
+
+error:
+ yaml_free(copy.handle);
+ yaml_free(copy.prefix);
+ return 0;
+}
+
diff --git a/contrib/libs/yaml/src/reader.c b/contrib/libs/yaml/src/reader.c
index 798770bb3f..f3ac54c251 100644
--- a/contrib/libs/yaml/src/reader.c
+++ b/contrib/libs/yaml/src/reader.c
@@ -1,469 +1,469 @@
-
-#include "yaml_private.h"
-
-/*
- * Declarations.
- */
-
-static int
-yaml_parser_set_reader_error(yaml_parser_t *parser, const char *problem,
- size_t offset, int value);
-
-static int
-yaml_parser_update_raw_buffer(yaml_parser_t *parser);
-
-static int
-yaml_parser_determine_encoding(yaml_parser_t *parser);
-
-YAML_DECLARE(int)
-yaml_parser_update_buffer(yaml_parser_t *parser, size_t length);
-
-/*
- * Set the reader error and return 0.
- */
-
-static int
-yaml_parser_set_reader_error(yaml_parser_t *parser, const char *problem,
- size_t offset, int value)
-{
- parser->error = YAML_READER_ERROR;
- parser->problem = problem;
- parser->problem_offset = offset;
- parser->problem_value = value;
-
- return 0;
-}
-
-/*
- * Byte order marks.
- */
-
-#define BOM_UTF8 "\xef\xbb\xbf"
-#define BOM_UTF16LE "\xff\xfe"
-#define BOM_UTF16BE "\xfe\xff"
-
-/*
- * Determine the input stream encoding by checking the BOM symbol. If no BOM is
- * found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure.
- */
-
-static int
-yaml_parser_determine_encoding(yaml_parser_t *parser)
-{
- /* Ensure that we had enough bytes in the raw buffer. */
-
+
+#include "yaml_private.h"
+
+/*
+ * Declarations.
+ */
+
+static int
+yaml_parser_set_reader_error(yaml_parser_t *parser, const char *problem,
+ size_t offset, int value);
+
+static int
+yaml_parser_update_raw_buffer(yaml_parser_t *parser);
+
+static int
+yaml_parser_determine_encoding(yaml_parser_t *parser);
+
+YAML_DECLARE(int)
+yaml_parser_update_buffer(yaml_parser_t *parser, size_t length);
+
+/*
+ * Set the reader error and return 0.
+ */
+
+static int
+yaml_parser_set_reader_error(yaml_parser_t *parser, const char *problem,
+ size_t offset, int value)
+{
+ parser->error = YAML_READER_ERROR;
+ parser->problem = problem;
+ parser->problem_offset = offset;
+ parser->problem_value = value;
+
+ return 0;
+}
+
+/*
+ * Byte order marks.
+ */
+
+#define BOM_UTF8 "\xef\xbb\xbf"
+#define BOM_UTF16LE "\xff\xfe"
+#define BOM_UTF16BE "\xfe\xff"
+
+/*
+ * Determine the input stream encoding by checking the BOM symbol. If no BOM is
+ * found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure.
+ */
+
+static int
+yaml_parser_determine_encoding(yaml_parser_t *parser)
+{
+ /* Ensure that we had enough bytes in the raw buffer. */
+
while (!parser->eof
- && parser->raw_buffer.last - parser->raw_buffer.pointer < 3) {
- if (!yaml_parser_update_raw_buffer(parser)) {
- return 0;
- }
- }
-
- /* Determine the encoding. */
-
- if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 2
- && !memcmp(parser->raw_buffer.pointer, BOM_UTF16LE, 2)) {
- parser->encoding = YAML_UTF16LE_ENCODING;
- parser->raw_buffer.pointer += 2;
- parser->offset += 2;
- }
- else if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 2
- && !memcmp(parser->raw_buffer.pointer, BOM_UTF16BE, 2)) {
- parser->encoding = YAML_UTF16BE_ENCODING;
- parser->raw_buffer.pointer += 2;
- parser->offset += 2;
- }
- else if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 3
- && !memcmp(parser->raw_buffer.pointer, BOM_UTF8, 3)) {
- parser->encoding = YAML_UTF8_ENCODING;
- parser->raw_buffer.pointer += 3;
- parser->offset += 3;
- }
- else {
- parser->encoding = YAML_UTF8_ENCODING;
- }
-
- return 1;
-}
-
-/*
- * Update the raw buffer.
- */
-
-static int
-yaml_parser_update_raw_buffer(yaml_parser_t *parser)
-{
- size_t size_read = 0;
-
- /* Return if the raw buffer is full. */
-
- if (parser->raw_buffer.start == parser->raw_buffer.pointer
- && parser->raw_buffer.last == parser->raw_buffer.end)
- return 1;
-
- /* Return on EOF. */
-
- if (parser->eof) return 1;
-
- /* Move the remaining bytes in the raw buffer to the beginning. */
-
- if (parser->raw_buffer.start < parser->raw_buffer.pointer
- && parser->raw_buffer.pointer < parser->raw_buffer.last) {
- memmove(parser->raw_buffer.start, parser->raw_buffer.pointer,
- parser->raw_buffer.last - parser->raw_buffer.pointer);
- }
- parser->raw_buffer.last -=
- parser->raw_buffer.pointer - parser->raw_buffer.start;
- parser->raw_buffer.pointer = parser->raw_buffer.start;
-
- /* Call the read handler to fill the buffer. */
-
- if (!parser->read_handler(parser->read_handler_data, parser->raw_buffer.last,
- parser->raw_buffer.end - parser->raw_buffer.last, &size_read)) {
- return yaml_parser_set_reader_error(parser, "input error",
- parser->offset, -1);
- }
- parser->raw_buffer.last += size_read;
- if (!size_read) {
- parser->eof = 1;
- }
-
- return 1;
-}
-
-/*
- * Ensure that the buffer contains at least `length` characters.
- * Return 1 on success, 0 on failure.
- *
- * The length is supposed to be significantly less that the buffer size.
- */
-
-YAML_DECLARE(int)
-yaml_parser_update_buffer(yaml_parser_t *parser, size_t length)
-{
- int first = 1;
-
- assert(parser->read_handler); /* Read handler must be set. */
-
- /* If the EOF flag is set and the raw buffer is empty, do nothing. */
-
- if (parser->eof && parser->raw_buffer.pointer == parser->raw_buffer.last)
- return 1;
-
- /* Return if the buffer contains enough characters. */
-
- if (parser->unread >= length)
- return 1;
-
- /* Determine the input encoding if it is not known yet. */
-
- if (!parser->encoding) {
- if (!yaml_parser_determine_encoding(parser))
- return 0;
- }
-
- /* Move the unread characters to the beginning of the buffer. */
-
- if (parser->buffer.start < parser->buffer.pointer
- && parser->buffer.pointer < parser->buffer.last) {
- size_t size = parser->buffer.last - parser->buffer.pointer;
- memmove(parser->buffer.start, parser->buffer.pointer, size);
- parser->buffer.pointer = parser->buffer.start;
- parser->buffer.last = parser->buffer.start + size;
- }
- else if (parser->buffer.pointer == parser->buffer.last) {
- parser->buffer.pointer = parser->buffer.start;
- parser->buffer.last = parser->buffer.start;
- }
-
- /* Fill the buffer until it has enough characters. */
-
- while (parser->unread < length)
- {
- /* Fill the raw buffer if necessary. */
-
- if (!first || parser->raw_buffer.pointer == parser->raw_buffer.last) {
- if (!yaml_parser_update_raw_buffer(parser)) return 0;
- }
- first = 0;
-
- /* Decode the raw buffer. */
-
- while (parser->raw_buffer.pointer != parser->raw_buffer.last)
- {
- unsigned int value = 0, value2 = 0;
- int incomplete = 0;
- unsigned char octet;
- unsigned int width = 0;
- int low, high;
- size_t k;
- size_t raw_unread = parser->raw_buffer.last - parser->raw_buffer.pointer;
-
- /* Decode the next character. */
-
- switch (parser->encoding)
- {
- case YAML_UTF8_ENCODING:
-
- /*
- * Decode a UTF-8 character. Check RFC 3629
- * (http://www.ietf.org/rfc/rfc3629.txt) for more details.
- *
- * The following table (taken from the RFC) is used for
- * decoding.
- *
- * Char. number range | UTF-8 octet sequence
- * (hexadecimal) | (binary)
- * --------------------+------------------------------------
- * 0000 0000-0000 007F | 0xxxxxxx
- * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
- * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
- * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
- *
- * Additionally, the characters in the range 0xD800-0xDFFF
- * are prohibited as they are reserved for use with UTF-16
- * surrogate pairs.
- */
-
- /* Determine the length of the UTF-8 sequence. */
-
- octet = parser->raw_buffer.pointer[0];
- width = (octet & 0x80) == 0x00 ? 1 :
- (octet & 0xE0) == 0xC0 ? 2 :
- (octet & 0xF0) == 0xE0 ? 3 :
- (octet & 0xF8) == 0xF0 ? 4 : 0;
-
- /* Check if the leading octet is valid. */
-
- if (!width)
- return yaml_parser_set_reader_error(parser,
- "invalid leading UTF-8 octet",
- parser->offset, octet);
-
- /* Check if the raw buffer contains an incomplete character. */
-
- if (width > raw_unread) {
- if (parser->eof) {
- return yaml_parser_set_reader_error(parser,
- "incomplete UTF-8 octet sequence",
- parser->offset, -1);
- }
- incomplete = 1;
- break;
- }
-
- /* Decode the leading octet. */
-
- value = (octet & 0x80) == 0x00 ? octet & 0x7F :
- (octet & 0xE0) == 0xC0 ? octet & 0x1F :
- (octet & 0xF0) == 0xE0 ? octet & 0x0F :
- (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0;
-
- /* Check and decode the trailing octets. */
-
- for (k = 1; k < width; k ++)
- {
- octet = parser->raw_buffer.pointer[k];
-
- /* Check if the octet is valid. */
-
- if ((octet & 0xC0) != 0x80)
- return yaml_parser_set_reader_error(parser,
- "invalid trailing UTF-8 octet",
- parser->offset+k, octet);
-
- /* Decode the octet. */
-
- value = (value << 6) + (octet & 0x3F);
- }
-
- /* Check the length of the sequence against the value. */
-
- if (!((width == 1) ||
- (width == 2 && value >= 0x80) ||
- (width == 3 && value >= 0x800) ||
- (width == 4 && value >= 0x10000)))
- return yaml_parser_set_reader_error(parser,
- "invalid length of a UTF-8 sequence",
- parser->offset, -1);
-
- /* Check the range of the value. */
-
- if ((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF)
- return yaml_parser_set_reader_error(parser,
- "invalid Unicode character",
- parser->offset, value);
-
- break;
-
- case YAML_UTF16LE_ENCODING:
- case YAML_UTF16BE_ENCODING:
-
- low = (parser->encoding == YAML_UTF16LE_ENCODING ? 0 : 1);
- high = (parser->encoding == YAML_UTF16LE_ENCODING ? 1 : 0);
-
- /*
- * The UTF-16 encoding is not as simple as one might
- * naively think. Check RFC 2781
- * (http://www.ietf.org/rfc/rfc2781.txt).
- *
- * Normally, two subsequent bytes describe a Unicode
- * character. However a special technique (called a
- * surrogate pair) is used for specifying character
- * values larger than 0xFFFF.
- *
- * A surrogate pair consists of two pseudo-characters:
- * high surrogate area (0xD800-0xDBFF)
- * low surrogate area (0xDC00-0xDFFF)
- *
- * The following formulas are used for decoding
- * and encoding characters using surrogate pairs:
+ && parser->raw_buffer.last - parser->raw_buffer.pointer < 3) {
+ if (!yaml_parser_update_raw_buffer(parser)) {
+ return 0;
+ }
+ }
+
+ /* Determine the encoding. */
+
+ if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 2
+ && !memcmp(parser->raw_buffer.pointer, BOM_UTF16LE, 2)) {
+ parser->encoding = YAML_UTF16LE_ENCODING;
+ parser->raw_buffer.pointer += 2;
+ parser->offset += 2;
+ }
+ else if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 2
+ && !memcmp(parser->raw_buffer.pointer, BOM_UTF16BE, 2)) {
+ parser->encoding = YAML_UTF16BE_ENCODING;
+ parser->raw_buffer.pointer += 2;
+ parser->offset += 2;
+ }
+ else if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 3
+ && !memcmp(parser->raw_buffer.pointer, BOM_UTF8, 3)) {
+ parser->encoding = YAML_UTF8_ENCODING;
+ parser->raw_buffer.pointer += 3;
+ parser->offset += 3;
+ }
+ else {
+ parser->encoding = YAML_UTF8_ENCODING;
+ }
+
+ return 1;
+}
+
+/*
+ * Update the raw buffer.
+ */
+
+static int
+yaml_parser_update_raw_buffer(yaml_parser_t *parser)
+{
+ size_t size_read = 0;
+
+ /* Return if the raw buffer is full. */
+
+ if (parser->raw_buffer.start == parser->raw_buffer.pointer
+ && parser->raw_buffer.last == parser->raw_buffer.end)
+ return 1;
+
+ /* Return on EOF. */
+
+ if (parser->eof) return 1;
+
+ /* Move the remaining bytes in the raw buffer to the beginning. */
+
+ if (parser->raw_buffer.start < parser->raw_buffer.pointer
+ && parser->raw_buffer.pointer < parser->raw_buffer.last) {
+ memmove(parser->raw_buffer.start, parser->raw_buffer.pointer,
+ parser->raw_buffer.last - parser->raw_buffer.pointer);
+ }
+ parser->raw_buffer.last -=
+ parser->raw_buffer.pointer - parser->raw_buffer.start;
+ parser->raw_buffer.pointer = parser->raw_buffer.start;
+
+ /* Call the read handler to fill the buffer. */
+
+ if (!parser->read_handler(parser->read_handler_data, parser->raw_buffer.last,
+ parser->raw_buffer.end - parser->raw_buffer.last, &size_read)) {
+ return yaml_parser_set_reader_error(parser, "input error",
+ parser->offset, -1);
+ }
+ parser->raw_buffer.last += size_read;
+ if (!size_read) {
+ parser->eof = 1;
+ }
+
+ return 1;
+}
+
+/*
+ * Ensure that the buffer contains at least `length` characters.
+ * Return 1 on success, 0 on failure.
+ *
+ * The length is supposed to be significantly less that the buffer size.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_update_buffer(yaml_parser_t *parser, size_t length)
+{
+ int first = 1;
+
+ assert(parser->read_handler); /* Read handler must be set. */
+
+ /* If the EOF flag is set and the raw buffer is empty, do nothing. */
+
+ if (parser->eof && parser->raw_buffer.pointer == parser->raw_buffer.last)
+ return 1;
+
+ /* Return if the buffer contains enough characters. */
+
+ if (parser->unread >= length)
+ return 1;
+
+ /* Determine the input encoding if it is not known yet. */
+
+ if (!parser->encoding) {
+ if (!yaml_parser_determine_encoding(parser))
+ return 0;
+ }
+
+ /* Move the unread characters to the beginning of the buffer. */
+
+ if (parser->buffer.start < parser->buffer.pointer
+ && parser->buffer.pointer < parser->buffer.last) {
+ size_t size = parser->buffer.last - parser->buffer.pointer;
+ memmove(parser->buffer.start, parser->buffer.pointer, size);
+ parser->buffer.pointer = parser->buffer.start;
+ parser->buffer.last = parser->buffer.start + size;
+ }
+ else if (parser->buffer.pointer == parser->buffer.last) {
+ parser->buffer.pointer = parser->buffer.start;
+ parser->buffer.last = parser->buffer.start;
+ }
+
+ /* Fill the buffer until it has enough characters. */
+
+ while (parser->unread < length)
+ {
+ /* Fill the raw buffer if necessary. */
+
+ if (!first || parser->raw_buffer.pointer == parser->raw_buffer.last) {
+ if (!yaml_parser_update_raw_buffer(parser)) return 0;
+ }
+ first = 0;
+
+ /* Decode the raw buffer. */
+
+ while (parser->raw_buffer.pointer != parser->raw_buffer.last)
+ {
+ unsigned int value = 0, value2 = 0;
+ int incomplete = 0;
+ unsigned char octet;
+ unsigned int width = 0;
+ int low, high;
+ size_t k;
+ size_t raw_unread = parser->raw_buffer.last - parser->raw_buffer.pointer;
+
+ /* Decode the next character. */
+
+ switch (parser->encoding)
+ {
+ case YAML_UTF8_ENCODING:
+
+ /*
+ * Decode a UTF-8 character. Check RFC 3629
+ * (http://www.ietf.org/rfc/rfc3629.txt) for more details.
+ *
+ * The following table (taken from the RFC) is used for
+ * decoding.
+ *
+ * Char. number range | UTF-8 octet sequence
+ * (hexadecimal) | (binary)
+ * --------------------+------------------------------------
+ * 0000 0000-0000 007F | 0xxxxxxx
+ * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
+ * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
+ * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+ *
+ * Additionally, the characters in the range 0xD800-0xDFFF
+ * are prohibited as they are reserved for use with UTF-16
+ * surrogate pairs.
+ */
+
+ /* Determine the length of the UTF-8 sequence. */
+
+ octet = parser->raw_buffer.pointer[0];
+ width = (octet & 0x80) == 0x00 ? 1 :
+ (octet & 0xE0) == 0xC0 ? 2 :
+ (octet & 0xF0) == 0xE0 ? 3 :
+ (octet & 0xF8) == 0xF0 ? 4 : 0;
+
+ /* Check if the leading octet is valid. */
+
+ if (!width)
+ return yaml_parser_set_reader_error(parser,
+ "invalid leading UTF-8 octet",
+ parser->offset, octet);
+
+ /* Check if the raw buffer contains an incomplete character. */
+
+ if (width > raw_unread) {
+ if (parser->eof) {
+ return yaml_parser_set_reader_error(parser,
+ "incomplete UTF-8 octet sequence",
+ parser->offset, -1);
+ }
+ incomplete = 1;
+ break;
+ }
+
+ /* Decode the leading octet. */
+
+ value = (octet & 0x80) == 0x00 ? octet & 0x7F :
+ (octet & 0xE0) == 0xC0 ? octet & 0x1F :
+ (octet & 0xF0) == 0xE0 ? octet & 0x0F :
+ (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0;
+
+ /* Check and decode the trailing octets. */
+
+ for (k = 1; k < width; k ++)
+ {
+ octet = parser->raw_buffer.pointer[k];
+
+ /* Check if the octet is valid. */
+
+ if ((octet & 0xC0) != 0x80)
+ return yaml_parser_set_reader_error(parser,
+ "invalid trailing UTF-8 octet",
+ parser->offset+k, octet);
+
+ /* Decode the octet. */
+
+ value = (value << 6) + (octet & 0x3F);
+ }
+
+ /* Check the length of the sequence against the value. */
+
+ if (!((width == 1) ||
+ (width == 2 && value >= 0x80) ||
+ (width == 3 && value >= 0x800) ||
+ (width == 4 && value >= 0x10000)))
+ return yaml_parser_set_reader_error(parser,
+ "invalid length of a UTF-8 sequence",
+ parser->offset, -1);
+
+ /* Check the range of the value. */
+
+ if ((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF)
+ return yaml_parser_set_reader_error(parser,
+ "invalid Unicode character",
+ parser->offset, value);
+
+ break;
+
+ case YAML_UTF16LE_ENCODING:
+ case YAML_UTF16BE_ENCODING:
+
+ low = (parser->encoding == YAML_UTF16LE_ENCODING ? 0 : 1);
+ high = (parser->encoding == YAML_UTF16LE_ENCODING ? 1 : 0);
+
+ /*
+ * The UTF-16 encoding is not as simple as one might
+ * naively think. Check RFC 2781
+ * (http://www.ietf.org/rfc/rfc2781.txt).
+ *
+ * Normally, two subsequent bytes describe a Unicode
+ * character. However a special technique (called a
+ * surrogate pair) is used for specifying character
+ * values larger than 0xFFFF.
+ *
+ * A surrogate pair consists of two pseudo-characters:
+ * high surrogate area (0xD800-0xDBFF)
+ * low surrogate area (0xDC00-0xDFFF)
*
- * U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF)
- * U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF)
- * W1 = 110110yyyyyyyyyy
- * W2 = 110111xxxxxxxxxx
- *
- * where U is the character value, W1 is the high surrogate
- * area, W2 is the low surrogate area.
- */
-
- /* Check for incomplete UTF-16 character. */
-
- if (raw_unread < 2) {
- if (parser->eof) {
- return yaml_parser_set_reader_error(parser,
- "incomplete UTF-16 character",
- parser->offset, -1);
- }
- incomplete = 1;
- break;
- }
-
- /* Get the character. */
-
- value = parser->raw_buffer.pointer[low]
- + (parser->raw_buffer.pointer[high] << 8);
-
- /* Check for unexpected low surrogate area. */
-
- if ((value & 0xFC00) == 0xDC00)
- return yaml_parser_set_reader_error(parser,
- "unexpected low surrogate area",
- parser->offset, value);
-
- /* Check for a high surrogate area. */
-
- if ((value & 0xFC00) == 0xD800) {
-
- width = 4;
-
- /* Check for incomplete surrogate pair. */
-
- if (raw_unread < 4) {
- if (parser->eof) {
- return yaml_parser_set_reader_error(parser,
- "incomplete UTF-16 surrogate pair",
- parser->offset, -1);
- }
- incomplete = 1;
- break;
- }
-
- /* Get the next character. */
-
- value2 = parser->raw_buffer.pointer[low+2]
- + (parser->raw_buffer.pointer[high+2] << 8);
-
- /* Check for a low surrogate area. */
-
- if ((value2 & 0xFC00) != 0xDC00)
- return yaml_parser_set_reader_error(parser,
- "expected low surrogate area",
- parser->offset+2, value2);
-
- /* Generate the value of the surrogate pair. */
-
- value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF);
- }
-
- else {
- width = 2;
- }
-
- break;
-
- default:
- assert(1); /* Impossible. */
- }
-
- /* Check if the raw buffer contains enough bytes to form a character. */
-
- if (incomplete) break;
-
- /*
- * Check if the character is in the allowed range:
- * #x9 | #xA | #xD | [#x20-#x7E] (8 bit)
- * | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit)
- * | [#x10000-#x10FFFF] (32 bit)
- */
-
- if (! (value == 0x09 || value == 0x0A || value == 0x0D
- || (value >= 0x20 && value <= 0x7E)
- || (value == 0x85) || (value >= 0xA0 && value <= 0xD7FF)
- || (value >= 0xE000 && value <= 0xFFFD)
- || (value >= 0x10000 && value <= 0x10FFFF)))
- return yaml_parser_set_reader_error(parser,
- "control characters are not allowed",
- parser->offset, value);
-
- /* Move the raw pointers. */
-
- parser->raw_buffer.pointer += width;
- parser->offset += width;
-
- /* Finally put the character into the buffer. */
-
- /* 0000 0000-0000 007F -> 0xxxxxxx */
- if (value <= 0x7F) {
- *(parser->buffer.last++) = value;
- }
- /* 0000 0080-0000 07FF -> 110xxxxx 10xxxxxx */
- else if (value <= 0x7FF) {
- *(parser->buffer.last++) = 0xC0 + (value >> 6);
- *(parser->buffer.last++) = 0x80 + (value & 0x3F);
- }
- /* 0000 0800-0000 FFFF -> 1110xxxx 10xxxxxx 10xxxxxx */
- else if (value <= 0xFFFF) {
- *(parser->buffer.last++) = 0xE0 + (value >> 12);
- *(parser->buffer.last++) = 0x80 + ((value >> 6) & 0x3F);
- *(parser->buffer.last++) = 0x80 + (value & 0x3F);
- }
- /* 0001 0000-0010 FFFF -> 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
- else {
- *(parser->buffer.last++) = 0xF0 + (value >> 18);
- *(parser->buffer.last++) = 0x80 + ((value >> 12) & 0x3F);
- *(parser->buffer.last++) = 0x80 + ((value >> 6) & 0x3F);
- *(parser->buffer.last++) = 0x80 + (value & 0x3F);
- }
-
- parser->unread ++;
- }
-
- /* On EOF, put NUL into the buffer and return. */
-
- if (parser->eof) {
- *(parser->buffer.last++) = '\0';
- parser->unread ++;
- return 1;
- }
-
- }
-
+ * The following formulas are used for decoding
+ * and encoding characters using surrogate pairs:
+ *
+ * U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF)
+ * U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF)
+ * W1 = 110110yyyyyyyyyy
+ * W2 = 110111xxxxxxxxxx
+ *
+ * where U is the character value, W1 is the high surrogate
+ * area, W2 is the low surrogate area.
+ */
+
+ /* Check for incomplete UTF-16 character. */
+
+ if (raw_unread < 2) {
+ if (parser->eof) {
+ return yaml_parser_set_reader_error(parser,
+ "incomplete UTF-16 character",
+ parser->offset, -1);
+ }
+ incomplete = 1;
+ break;
+ }
+
+ /* Get the character. */
+
+ value = parser->raw_buffer.pointer[low]
+ + (parser->raw_buffer.pointer[high] << 8);
+
+ /* Check for unexpected low surrogate area. */
+
+ if ((value & 0xFC00) == 0xDC00)
+ return yaml_parser_set_reader_error(parser,
+ "unexpected low surrogate area",
+ parser->offset, value);
+
+ /* Check for a high surrogate area. */
+
+ if ((value & 0xFC00) == 0xD800) {
+
+ width = 4;
+
+ /* Check for incomplete surrogate pair. */
+
+ if (raw_unread < 4) {
+ if (parser->eof) {
+ return yaml_parser_set_reader_error(parser,
+ "incomplete UTF-16 surrogate pair",
+ parser->offset, -1);
+ }
+ incomplete = 1;
+ break;
+ }
+
+ /* Get the next character. */
+
+ value2 = parser->raw_buffer.pointer[low+2]
+ + (parser->raw_buffer.pointer[high+2] << 8);
+
+ /* Check for a low surrogate area. */
+
+ if ((value2 & 0xFC00) != 0xDC00)
+ return yaml_parser_set_reader_error(parser,
+ "expected low surrogate area",
+ parser->offset+2, value2);
+
+ /* Generate the value of the surrogate pair. */
+
+ value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF);
+ }
+
+ else {
+ width = 2;
+ }
+
+ break;
+
+ default:
+ assert(1); /* Impossible. */
+ }
+
+ /* Check if the raw buffer contains enough bytes to form a character. */
+
+ if (incomplete) break;
+
+ /*
+ * Check if the character is in the allowed range:
+ * #x9 | #xA | #xD | [#x20-#x7E] (8 bit)
+ * | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit)
+ * | [#x10000-#x10FFFF] (32 bit)
+ */
+
+ if (! (value == 0x09 || value == 0x0A || value == 0x0D
+ || (value >= 0x20 && value <= 0x7E)
+ || (value == 0x85) || (value >= 0xA0 && value <= 0xD7FF)
+ || (value >= 0xE000 && value <= 0xFFFD)
+ || (value >= 0x10000 && value <= 0x10FFFF)))
+ return yaml_parser_set_reader_error(parser,
+ "control characters are not allowed",
+ parser->offset, value);
+
+ /* Move the raw pointers. */
+
+ parser->raw_buffer.pointer += width;
+ parser->offset += width;
+
+ /* Finally put the character into the buffer. */
+
+ /* 0000 0000-0000 007F -> 0xxxxxxx */
+ if (value <= 0x7F) {
+ *(parser->buffer.last++) = value;
+ }
+ /* 0000 0080-0000 07FF -> 110xxxxx 10xxxxxx */
+ else if (value <= 0x7FF) {
+ *(parser->buffer.last++) = 0xC0 + (value >> 6);
+ *(parser->buffer.last++) = 0x80 + (value & 0x3F);
+ }
+ /* 0000 0800-0000 FFFF -> 1110xxxx 10xxxxxx 10xxxxxx */
+ else if (value <= 0xFFFF) {
+ *(parser->buffer.last++) = 0xE0 + (value >> 12);
+ *(parser->buffer.last++) = 0x80 + ((value >> 6) & 0x3F);
+ *(parser->buffer.last++) = 0x80 + (value & 0x3F);
+ }
+ /* 0001 0000-0010 FFFF -> 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
+ else {
+ *(parser->buffer.last++) = 0xF0 + (value >> 18);
+ *(parser->buffer.last++) = 0x80 + ((value >> 12) & 0x3F);
+ *(parser->buffer.last++) = 0x80 + ((value >> 6) & 0x3F);
+ *(parser->buffer.last++) = 0x80 + (value & 0x3F);
+ }
+
+ parser->unread ++;
+ }
+
+ /* On EOF, put NUL into the buffer and return. */
+
+ if (parser->eof) {
+ *(parser->buffer.last++) = '\0';
+ parser->unread ++;
+ return 1;
+ }
+
+ }
+
if (parser->offset >= MAX_FILE_SIZE) {
- return yaml_parser_set_reader_error(parser, "input is too long",
+ return yaml_parser_set_reader_error(parser, "input is too long",
parser->offset, -1);
}
-
- return 1;
-}
+
+ return 1;
+}
diff --git a/contrib/libs/yaml/src/scanner.c b/contrib/libs/yaml/src/scanner.c
index e252398e5c..c6b4987656 100644
--- a/contrib/libs/yaml/src/scanner.c
+++ b/contrib/libs/yaml/src/scanner.c
@@ -1,3451 +1,3451 @@
-
-/*
- * Introduction
- * ************
- *
- * The following notes assume that you are familiar with the YAML specification
- * (http://yaml.org/spec/cvs/current.html). We mostly follow it, although in
- * some cases we are less restrictive that it requires.
- *
- * The process of transforming a YAML stream into a sequence of events is
- * divided on two steps: Scanning and Parsing.
- *
- * The Scanner transforms the input stream into a sequence of tokens, while the
- * parser transform the sequence of tokens produced by the Scanner into a
- * sequence of parsing events.
- *
- * The Scanner is rather clever and complicated. The Parser, on the contrary,
- * is a straightforward implementation of a recursive-descendant parser (or,
- * LL(1) parser, as it is usually called).
- *
- * Actually there are two issues of Scanning that might be called "clever", the
- * rest is quite straightforward. The issues are "block collection start" and
- * "simple keys". Both issues are explained below in details.
- *
- * Here the Scanning step is explained and implemented. We start with the list
- * of all the tokens produced by the Scanner together with short descriptions.
- *
- * Now, tokens:
- *
- * STREAM-START(encoding) # The stream start.
- * STREAM-END # The stream end.
- * VERSION-DIRECTIVE(major,minor) # The '%YAML' directive.
- * TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive.
- * DOCUMENT-START # '---'
- * DOCUMENT-END # '...'
- * BLOCK-SEQUENCE-START # Indentation increase denoting a block
- * BLOCK-MAPPING-START # sequence or a block mapping.
- * BLOCK-END # Indentation decrease.
- * FLOW-SEQUENCE-START # '['
- * FLOW-SEQUENCE-END # ']'
+
+/*
+ * Introduction
+ * ************
+ *
+ * The following notes assume that you are familiar with the YAML specification
+ * (http://yaml.org/spec/cvs/current.html). We mostly follow it, although in
+ * some cases we are less restrictive that it requires.
+ *
+ * The process of transforming a YAML stream into a sequence of events is
+ * divided on two steps: Scanning and Parsing.
+ *
+ * The Scanner transforms the input stream into a sequence of tokens, while the
+ * parser transform the sequence of tokens produced by the Scanner into a
+ * sequence of parsing events.
+ *
+ * The Scanner is rather clever and complicated. The Parser, on the contrary,
+ * is a straightforward implementation of a recursive-descendant parser (or,
+ * LL(1) parser, as it is usually called).
+ *
+ * Actually there are two issues of Scanning that might be called "clever", the
+ * rest is quite straightforward. The issues are "block collection start" and
+ * "simple keys". Both issues are explained below in details.
+ *
+ * Here the Scanning step is explained and implemented. We start with the list
+ * of all the tokens produced by the Scanner together with short descriptions.
+ *
+ * Now, tokens:
+ *
+ * STREAM-START(encoding) # The stream start.
+ * STREAM-END # The stream end.
+ * VERSION-DIRECTIVE(major,minor) # The '%YAML' directive.
+ * TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive.
+ * DOCUMENT-START # '---'
+ * DOCUMENT-END # '...'
+ * BLOCK-SEQUENCE-START # Indentation increase denoting a block
+ * BLOCK-MAPPING-START # sequence or a block mapping.
+ * BLOCK-END # Indentation decrease.
+ * FLOW-SEQUENCE-START # '['
+ * FLOW-SEQUENCE-END # ']'
* FLOW-MAPPING-START # '{'
* FLOW-MAPPING-END # '}'
- * BLOCK-ENTRY # '-'
- * FLOW-ENTRY # ','
- * KEY # '?' or nothing (simple keys).
- * VALUE # ':'
- * ALIAS(anchor) # '*anchor'
- * ANCHOR(anchor) # '&anchor'
- * TAG(handle,suffix) # '!handle!suffix'
- * SCALAR(value,style) # A scalar.
- *
- * The following two tokens are "virtual" tokens denoting the beginning and the
- * end of the stream:
- *
- * STREAM-START(encoding)
- * STREAM-END
- *
- * We pass the information about the input stream encoding with the
- * STREAM-START token.
- *
- * The next two tokens are responsible for tags:
- *
- * VERSION-DIRECTIVE(major,minor)
- * TAG-DIRECTIVE(handle,prefix)
- *
- * Example:
- *
- * %YAML 1.1
- * %TAG ! !foo
- * %TAG !yaml! tag:yaml.org,2002:
- * ---
- *
+ * BLOCK-ENTRY # '-'
+ * FLOW-ENTRY # ','
+ * KEY # '?' or nothing (simple keys).
+ * VALUE # ':'
+ * ALIAS(anchor) # '*anchor'
+ * ANCHOR(anchor) # '&anchor'
+ * TAG(handle,suffix) # '!handle!suffix'
+ * SCALAR(value,style) # A scalar.
+ *
+ * The following two tokens are "virtual" tokens denoting the beginning and the
+ * end of the stream:
+ *
+ * STREAM-START(encoding)
+ * STREAM-END
+ *
+ * We pass the information about the input stream encoding with the
+ * STREAM-START token.
+ *
+ * The next two tokens are responsible for tags:
+ *
+ * VERSION-DIRECTIVE(major,minor)
+ * TAG-DIRECTIVE(handle,prefix)
+ *
+ * Example:
+ *
+ * %YAML 1.1
+ * %TAG ! !foo
+ * %TAG !yaml! tag:yaml.org,2002:
+ * ---
+ *
* The corresponding sequence of tokens:
- *
- * STREAM-START(utf-8)
- * VERSION-DIRECTIVE(1,1)
- * TAG-DIRECTIVE("!","!foo")
- * TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:")
- * DOCUMENT-START
- * STREAM-END
- *
- * Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole
- * line.
- *
- * The document start and end indicators are represented by:
- *
- * DOCUMENT-START
- * DOCUMENT-END
- *
- * Note that if a YAML stream contains an implicit document (without '---'
- * and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be
- * produced.
- *
- * In the following examples, we present whole documents together with the
- * produced tokens.
- *
- * 1. An implicit document:
- *
- * 'a scalar'
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * SCALAR("a scalar",single-quoted)
- * STREAM-END
- *
- * 2. An explicit document:
- *
- * ---
- * 'a scalar'
- * ...
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * DOCUMENT-START
- * SCALAR("a scalar",single-quoted)
- * DOCUMENT-END
- * STREAM-END
- *
- * 3. Several documents in a stream:
- *
- * 'a scalar'
- * ---
- * 'another scalar'
- * ---
- * 'yet another scalar'
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * SCALAR("a scalar",single-quoted)
- * DOCUMENT-START
- * SCALAR("another scalar",single-quoted)
- * DOCUMENT-START
- * SCALAR("yet another scalar",single-quoted)
- * STREAM-END
- *
- * We have already introduced the SCALAR token above. The following tokens are
- * used to describe aliases, anchors, tag, and scalars:
- *
- * ALIAS(anchor)
- * ANCHOR(anchor)
- * TAG(handle,suffix)
- * SCALAR(value,style)
- *
- * The following series of examples illustrate the usage of these tokens:
- *
- * 1. A recursive sequence:
- *
- * &A [ *A ]
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * ANCHOR("A")
- * FLOW-SEQUENCE-START
- * ALIAS("A")
- * FLOW-SEQUENCE-END
- * STREAM-END
- *
- * 2. A tagged scalar:
- *
- * !!float "3.14" # A good approximation.
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * TAG("!!","float")
- * SCALAR("3.14",double-quoted)
- * STREAM-END
- *
- * 3. Various scalar styles:
- *
- * --- # Implicit empty plain scalars do not produce tokens.
- * --- a plain scalar
- * --- 'a single-quoted scalar'
- * --- "a double-quoted scalar"
- * --- |-
- * a literal scalar
- * --- >-
- * a folded
- * scalar
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * DOCUMENT-START
- * DOCUMENT-START
- * SCALAR("a plain scalar",plain)
- * DOCUMENT-START
- * SCALAR("a single-quoted scalar",single-quoted)
- * DOCUMENT-START
- * SCALAR("a double-quoted scalar",double-quoted)
- * DOCUMENT-START
- * SCALAR("a literal scalar",literal)
- * DOCUMENT-START
- * SCALAR("a folded scalar",folded)
- * STREAM-END
- *
- * Now it's time to review collection-related tokens. We will start with
- * flow collections:
- *
- * FLOW-SEQUENCE-START
- * FLOW-SEQUENCE-END
- * FLOW-MAPPING-START
- * FLOW-MAPPING-END
- * FLOW-ENTRY
- * KEY
- * VALUE
- *
- * The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and
- * FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}'
- * correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the
- * indicators '?' and ':', which are used for denoting mapping keys and values,
- * are represented by the KEY and VALUE tokens.
- *
- * The following examples show flow collections:
- *
- * 1. A flow sequence:
- *
- * [item 1, item 2, item 3]
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * FLOW-SEQUENCE-START
- * SCALAR("item 1",plain)
- * FLOW-ENTRY
- * SCALAR("item 2",plain)
- * FLOW-ENTRY
- * SCALAR("item 3",plain)
- * FLOW-SEQUENCE-END
- * STREAM-END
- *
- * 2. A flow mapping:
- *
- * {
- * a simple key: a value, # Note that the KEY token is produced.
- * ? a complex key: another value,
- * }
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * FLOW-MAPPING-START
- * KEY
- * SCALAR("a simple key",plain)
- * VALUE
- * SCALAR("a value",plain)
- * FLOW-ENTRY
- * KEY
- * SCALAR("a complex key",plain)
- * VALUE
- * SCALAR("another value",plain)
- * FLOW-ENTRY
- * FLOW-MAPPING-END
- * STREAM-END
- *
- * A simple key is a key which is not denoted by the '?' indicator. Note that
- * the Scanner still produce the KEY token whenever it encounters a simple key.
- *
- * For scanning block collections, the following tokens are used (note that we
- * repeat KEY and VALUE here):
- *
- * BLOCK-SEQUENCE-START
- * BLOCK-MAPPING-START
- * BLOCK-END
- * BLOCK-ENTRY
- * KEY
- * VALUE
- *
- * The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation
- * increase that precedes a block collection (cf. the INDENT token in Python).
- * The token BLOCK-END denote indentation decrease that ends a block collection
- * (cf. the DEDENT token in Python). However YAML has some syntax pecularities
- * that makes detections of these tokens more complex.
- *
- * The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators
- * '-', '?', and ':' correspondingly.
- *
- * The following examples show how the tokens BLOCK-SEQUENCE-START,
- * BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner:
- *
- * 1. Block sequences:
- *
- * - item 1
- * - item 2
- * -
- * - item 3.1
- * - item 3.2
- * -
- * key 1: value 1
- * key 2: value 2
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * BLOCK-SEQUENCE-START
- * BLOCK-ENTRY
- * SCALAR("item 1",plain)
- * BLOCK-ENTRY
- * SCALAR("item 2",plain)
- * BLOCK-ENTRY
- * BLOCK-SEQUENCE-START
- * BLOCK-ENTRY
- * SCALAR("item 3.1",plain)
- * BLOCK-ENTRY
- * SCALAR("item 3.2",plain)
- * BLOCK-END
- * BLOCK-ENTRY
- * BLOCK-MAPPING-START
- * KEY
- * SCALAR("key 1",plain)
- * VALUE
- * SCALAR("value 1",plain)
- * KEY
- * SCALAR("key 2",plain)
- * VALUE
- * SCALAR("value 2",plain)
- * BLOCK-END
- * BLOCK-END
- * STREAM-END
- *
- * 2. Block mappings:
- *
- * a simple key: a value # The KEY token is produced here.
- * ? a complex key
- * : another value
- * a mapping:
- * key 1: value 1
- * key 2: value 2
- * a sequence:
- * - item 1
- * - item 2
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * BLOCK-MAPPING-START
- * KEY
- * SCALAR("a simple key",plain)
- * VALUE
- * SCALAR("a value",plain)
- * KEY
- * SCALAR("a complex key",plain)
- * VALUE
- * SCALAR("another value",plain)
- * KEY
- * SCALAR("a mapping",plain)
+ *
+ * STREAM-START(utf-8)
+ * VERSION-DIRECTIVE(1,1)
+ * TAG-DIRECTIVE("!","!foo")
+ * TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:")
+ * DOCUMENT-START
+ * STREAM-END
+ *
+ * Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole
+ * line.
+ *
+ * The document start and end indicators are represented by:
+ *
+ * DOCUMENT-START
+ * DOCUMENT-END
+ *
+ * Note that if a YAML stream contains an implicit document (without '---'
+ * and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be
+ * produced.
+ *
+ * In the following examples, we present whole documents together with the
+ * produced tokens.
+ *
+ * 1. An implicit document:
+ *
+ * 'a scalar'
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * SCALAR("a scalar",single-quoted)
+ * STREAM-END
+ *
+ * 2. An explicit document:
+ *
+ * ---
+ * 'a scalar'
+ * ...
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * DOCUMENT-START
+ * SCALAR("a scalar",single-quoted)
+ * DOCUMENT-END
+ * STREAM-END
+ *
+ * 3. Several documents in a stream:
+ *
+ * 'a scalar'
+ * ---
+ * 'another scalar'
+ * ---
+ * 'yet another scalar'
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * SCALAR("a scalar",single-quoted)
+ * DOCUMENT-START
+ * SCALAR("another scalar",single-quoted)
+ * DOCUMENT-START
+ * SCALAR("yet another scalar",single-quoted)
+ * STREAM-END
+ *
+ * We have already introduced the SCALAR token above. The following tokens are
+ * used to describe aliases, anchors, tag, and scalars:
+ *
+ * ALIAS(anchor)
+ * ANCHOR(anchor)
+ * TAG(handle,suffix)
+ * SCALAR(value,style)
+ *
+ * The following series of examples illustrate the usage of these tokens:
+ *
+ * 1. A recursive sequence:
+ *
+ * &A [ *A ]
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * ANCHOR("A")
+ * FLOW-SEQUENCE-START
+ * ALIAS("A")
+ * FLOW-SEQUENCE-END
+ * STREAM-END
+ *
+ * 2. A tagged scalar:
+ *
+ * !!float "3.14" # A good approximation.
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * TAG("!!","float")
+ * SCALAR("3.14",double-quoted)
+ * STREAM-END
+ *
+ * 3. Various scalar styles:
+ *
+ * --- # Implicit empty plain scalars do not produce tokens.
+ * --- a plain scalar
+ * --- 'a single-quoted scalar'
+ * --- "a double-quoted scalar"
+ * --- |-
+ * a literal scalar
+ * --- >-
+ * a folded
+ * scalar
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * DOCUMENT-START
+ * DOCUMENT-START
+ * SCALAR("a plain scalar",plain)
+ * DOCUMENT-START
+ * SCALAR("a single-quoted scalar",single-quoted)
+ * DOCUMENT-START
+ * SCALAR("a double-quoted scalar",double-quoted)
+ * DOCUMENT-START
+ * SCALAR("a literal scalar",literal)
+ * DOCUMENT-START
+ * SCALAR("a folded scalar",folded)
+ * STREAM-END
+ *
+ * Now it's time to review collection-related tokens. We will start with
+ * flow collections:
+ *
+ * FLOW-SEQUENCE-START
+ * FLOW-SEQUENCE-END
+ * FLOW-MAPPING-START
+ * FLOW-MAPPING-END
+ * FLOW-ENTRY
+ * KEY
+ * VALUE
+ *
+ * The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and
+ * FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}'
+ * correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the
+ * indicators '?' and ':', which are used for denoting mapping keys and values,
+ * are represented by the KEY and VALUE tokens.
+ *
+ * The following examples show flow collections:
+ *
+ * 1. A flow sequence:
+ *
+ * [item 1, item 2, item 3]
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * FLOW-SEQUENCE-START
+ * SCALAR("item 1",plain)
+ * FLOW-ENTRY
+ * SCALAR("item 2",plain)
+ * FLOW-ENTRY
+ * SCALAR("item 3",plain)
+ * FLOW-SEQUENCE-END
+ * STREAM-END
+ *
+ * 2. A flow mapping:
+ *
+ * {
+ * a simple key: a value, # Note that the KEY token is produced.
+ * ? a complex key: another value,
+ * }
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * FLOW-MAPPING-START
+ * KEY
+ * SCALAR("a simple key",plain)
+ * VALUE
+ * SCALAR("a value",plain)
+ * FLOW-ENTRY
+ * KEY
+ * SCALAR("a complex key",plain)
+ * VALUE
+ * SCALAR("another value",plain)
+ * FLOW-ENTRY
+ * FLOW-MAPPING-END
+ * STREAM-END
+ *
+ * A simple key is a key which is not denoted by the '?' indicator. Note that
+ * the Scanner still produce the KEY token whenever it encounters a simple key.
+ *
+ * For scanning block collections, the following tokens are used (note that we
+ * repeat KEY and VALUE here):
+ *
+ * BLOCK-SEQUENCE-START
+ * BLOCK-MAPPING-START
+ * BLOCK-END
+ * BLOCK-ENTRY
+ * KEY
+ * VALUE
+ *
+ * The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation
+ * increase that precedes a block collection (cf. the INDENT token in Python).
+ * The token BLOCK-END denote indentation decrease that ends a block collection
+ * (cf. the DEDENT token in Python). However YAML has some syntax pecularities
+ * that makes detections of these tokens more complex.
+ *
+ * The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators
+ * '-', '?', and ':' correspondingly.
+ *
+ * The following examples show how the tokens BLOCK-SEQUENCE-START,
+ * BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner:
+ *
+ * 1. Block sequences:
+ *
+ * - item 1
+ * - item 2
+ * -
+ * - item 3.1
+ * - item 3.2
+ * -
+ * key 1: value 1
+ * key 2: value 2
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * BLOCK-SEQUENCE-START
+ * BLOCK-ENTRY
+ * SCALAR("item 1",plain)
+ * BLOCK-ENTRY
+ * SCALAR("item 2",plain)
+ * BLOCK-ENTRY
+ * BLOCK-SEQUENCE-START
+ * BLOCK-ENTRY
+ * SCALAR("item 3.1",plain)
+ * BLOCK-ENTRY
+ * SCALAR("item 3.2",plain)
+ * BLOCK-END
+ * BLOCK-ENTRY
+ * BLOCK-MAPPING-START
+ * KEY
+ * SCALAR("key 1",plain)
+ * VALUE
+ * SCALAR("value 1",plain)
+ * KEY
+ * SCALAR("key 2",plain)
+ * VALUE
+ * SCALAR("value 2",plain)
+ * BLOCK-END
+ * BLOCK-END
+ * STREAM-END
+ *
+ * 2. Block mappings:
+ *
+ * a simple key: a value # The KEY token is produced here.
+ * ? a complex key
+ * : another value
+ * a mapping:
+ * key 1: value 1
+ * key 2: value 2
+ * a sequence:
+ * - item 1
+ * - item 2
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * BLOCK-MAPPING-START
+ * KEY
+ * SCALAR("a simple key",plain)
+ * VALUE
+ * SCALAR("a value",plain)
+ * KEY
+ * SCALAR("a complex key",plain)
+ * VALUE
+ * SCALAR("another value",plain)
+ * KEY
+ * SCALAR("a mapping",plain)
+ * VALUE
+ * BLOCK-MAPPING-START
+ * KEY
+ * SCALAR("key 1",plain)
+ * VALUE
+ * SCALAR("value 1",plain)
+ * KEY
+ * SCALAR("key 2",plain)
+ * VALUE
+ * SCALAR("value 2",plain)
+ * BLOCK-END
+ * KEY
+ * SCALAR("a sequence",plain)
+ * VALUE
+ * BLOCK-SEQUENCE-START
+ * BLOCK-ENTRY
+ * SCALAR("item 1",plain)
+ * BLOCK-ENTRY
+ * SCALAR("item 2",plain)
+ * BLOCK-END
+ * BLOCK-END
+ * STREAM-END
+ *
+ * YAML does not always require to start a new block collection from a new
+ * line. If the current line contains only '-', '?', and ':' indicators, a new
+ * block collection may start at the current line. The following examples
+ * illustrate this case:
+ *
+ * 1. Collections in a sequence:
+ *
+ * - - item 1
+ * - item 2
+ * - key 1: value 1
+ * key 2: value 2
+ * - ? complex key
+ * : complex value
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * BLOCK-SEQUENCE-START
+ * BLOCK-ENTRY
+ * BLOCK-SEQUENCE-START
+ * BLOCK-ENTRY
+ * SCALAR("item 1",plain)
+ * BLOCK-ENTRY
+ * SCALAR("item 2",plain)
+ * BLOCK-END
+ * BLOCK-ENTRY
+ * BLOCK-MAPPING-START
+ * KEY
+ * SCALAR("key 1",plain)
+ * VALUE
+ * SCALAR("value 1",plain)
+ * KEY
+ * SCALAR("key 2",plain)
+ * VALUE
+ * SCALAR("value 2",plain)
+ * BLOCK-END
+ * BLOCK-ENTRY
+ * BLOCK-MAPPING-START
+ * KEY
+ * SCALAR("complex key")
+ * VALUE
+ * SCALAR("complex value")
+ * BLOCK-END
+ * BLOCK-END
+ * STREAM-END
+ *
+ * 2. Collections in a mapping:
+ *
+ * ? a sequence
+ * : - item 1
+ * - item 2
+ * ? a mapping
+ * : key 1: value 1
+ * key 2: value 2
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * BLOCK-MAPPING-START
+ * KEY
+ * SCALAR("a sequence",plain)
+ * VALUE
+ * BLOCK-SEQUENCE-START
+ * BLOCK-ENTRY
+ * SCALAR("item 1",plain)
+ * BLOCK-ENTRY
+ * SCALAR("item 2",plain)
+ * BLOCK-END
+ * KEY
+ * SCALAR("a mapping",plain)
+ * VALUE
+ * BLOCK-MAPPING-START
+ * KEY
+ * SCALAR("key 1",plain)
* VALUE
- * BLOCK-MAPPING-START
- * KEY
- * SCALAR("key 1",plain)
- * VALUE
- * SCALAR("value 1",plain)
- * KEY
- * SCALAR("key 2",plain)
- * VALUE
- * SCALAR("value 2",plain)
- * BLOCK-END
- * KEY
- * SCALAR("a sequence",plain)
- * VALUE
- * BLOCK-SEQUENCE-START
- * BLOCK-ENTRY
- * SCALAR("item 1",plain)
- * BLOCK-ENTRY
- * SCALAR("item 2",plain)
- * BLOCK-END
- * BLOCK-END
- * STREAM-END
- *
- * YAML does not always require to start a new block collection from a new
- * line. If the current line contains only '-', '?', and ':' indicators, a new
- * block collection may start at the current line. The following examples
- * illustrate this case:
- *
- * 1. Collections in a sequence:
- *
- * - - item 1
- * - item 2
- * - key 1: value 1
- * key 2: value 2
- * - ? complex key
- * : complex value
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * BLOCK-SEQUENCE-START
- * BLOCK-ENTRY
- * BLOCK-SEQUENCE-START
- * BLOCK-ENTRY
- * SCALAR("item 1",plain)
- * BLOCK-ENTRY
- * SCALAR("item 2",plain)
- * BLOCK-END
- * BLOCK-ENTRY
- * BLOCK-MAPPING-START
- * KEY
- * SCALAR("key 1",plain)
- * VALUE
- * SCALAR("value 1",plain)
- * KEY
- * SCALAR("key 2",plain)
- * VALUE
- * SCALAR("value 2",plain)
- * BLOCK-END
- * BLOCK-ENTRY
- * BLOCK-MAPPING-START
- * KEY
- * SCALAR("complex key")
- * VALUE
- * SCALAR("complex value")
- * BLOCK-END
- * BLOCK-END
- * STREAM-END
- *
- * 2. Collections in a mapping:
- *
- * ? a sequence
- * : - item 1
- * - item 2
- * ? a mapping
- * : key 1: value 1
- * key 2: value 2
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * BLOCK-MAPPING-START
- * KEY
- * SCALAR("a sequence",plain)
- * VALUE
- * BLOCK-SEQUENCE-START
- * BLOCK-ENTRY
- * SCALAR("item 1",plain)
- * BLOCK-ENTRY
- * SCALAR("item 2",plain)
- * BLOCK-END
- * KEY
- * SCALAR("a mapping",plain)
- * VALUE
- * BLOCK-MAPPING-START
- * KEY
- * SCALAR("key 1",plain)
- * VALUE
- * SCALAR("value 1",plain)
- * KEY
- * SCALAR("key 2",plain)
- * VALUE
- * SCALAR("value 2",plain)
- * BLOCK-END
- * BLOCK-END
- * STREAM-END
- *
- * YAML also permits non-indented sequences if they are included into a block
- * mapping. In this case, the token BLOCK-SEQUENCE-START is not produced:
- *
- * key:
- * - item 1 # BLOCK-SEQUENCE-START is NOT produced here.
- * - item 2
- *
- * Tokens:
- *
- * STREAM-START(utf-8)
- * BLOCK-MAPPING-START
- * KEY
- * SCALAR("key",plain)
- * VALUE
- * BLOCK-ENTRY
- * SCALAR("item 1",plain)
- * BLOCK-ENTRY
- * SCALAR("item 2",plain)
- * BLOCK-END
- */
-
-#include "yaml_private.h"
-
-/*
- * Ensure that the buffer contains the required number of characters.
- * Return 1 on success, 0 on failure (reader error or memory error).
- */
-
-#define CACHE(parser,length) \
- (parser->unread >= (length) \
- ? 1 \
- : yaml_parser_update_buffer(parser, (length)))
-
-/*
- * Advance the buffer pointer.
- */
-
-#define SKIP(parser) \
- (parser->mark.index ++, \
- parser->mark.column ++, \
- parser->unread --, \
- parser->buffer.pointer += WIDTH(parser->buffer))
-
-#define SKIP_LINE(parser) \
- (IS_CRLF(parser->buffer) ? \
- (parser->mark.index += 2, \
- parser->mark.column = 0, \
- parser->mark.line ++, \
- parser->unread -= 2, \
- parser->buffer.pointer += 2) : \
- IS_BREAK(parser->buffer) ? \
- (parser->mark.index ++, \
- parser->mark.column = 0, \
- parser->mark.line ++, \
- parser->unread --, \
- parser->buffer.pointer += WIDTH(parser->buffer)) : 0)
-
-/*
- * Copy a character to a string buffer and advance pointers.
- */
-
-#define READ(parser,string) \
- (STRING_EXTEND(parser,string) ? \
- (COPY(string,parser->buffer), \
- parser->mark.index ++, \
- parser->mark.column ++, \
- parser->unread --, \
- 1) : 0)
-
-/*
- * Copy a line break character to a string buffer and advance pointers.
- */
-
-#define READ_LINE(parser,string) \
- (STRING_EXTEND(parser,string) ? \
- (((CHECK_AT(parser->buffer,'\r',0) \
- && CHECK_AT(parser->buffer,'\n',1)) ? /* CR LF -> LF */ \
- (*((string).pointer++) = (yaml_char_t) '\n', \
- parser->buffer.pointer += 2, \
- parser->mark.index += 2, \
- parser->mark.column = 0, \
- parser->mark.line ++, \
- parser->unread -= 2) : \
- (CHECK_AT(parser->buffer,'\r',0) \
- || CHECK_AT(parser->buffer,'\n',0)) ? /* CR|LF -> LF */ \
- (*((string).pointer++) = (yaml_char_t) '\n', \
- parser->buffer.pointer ++, \
- parser->mark.index ++, \
- parser->mark.column = 0, \
- parser->mark.line ++, \
- parser->unread --) : \
- (CHECK_AT(parser->buffer,'\xC2',0) \
- && CHECK_AT(parser->buffer,'\x85',1)) ? /* NEL -> LF */ \
- (*((string).pointer++) = (yaml_char_t) '\n', \
- parser->buffer.pointer += 2, \
- parser->mark.index ++, \
- parser->mark.column = 0, \
- parser->mark.line ++, \
- parser->unread --) : \
- (CHECK_AT(parser->buffer,'\xE2',0) && \
- CHECK_AT(parser->buffer,'\x80',1) && \
- (CHECK_AT(parser->buffer,'\xA8',2) || \
- CHECK_AT(parser->buffer,'\xA9',2))) ? /* LS|PS -> LS|PS */ \
- (*((string).pointer++) = *(parser->buffer.pointer++), \
- *((string).pointer++) = *(parser->buffer.pointer++), \
- *((string).pointer++) = *(parser->buffer.pointer++), \
- parser->mark.index ++, \
- parser->mark.column = 0, \
- parser->mark.line ++, \
- parser->unread --) : 0), \
- 1) : 0)
-
-/*
- * Public API declarations.
- */
-
-YAML_DECLARE(int)
-yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token);
-
-/*
- * Error handling.
- */
-
-static int
-yaml_parser_set_scanner_error(yaml_parser_t *parser, const char *context,
- yaml_mark_t context_mark, const char *problem);
-
-/*
- * High-level token API.
- */
-
-YAML_DECLARE(int)
-yaml_parser_fetch_more_tokens(yaml_parser_t *parser);
-
-static int
-yaml_parser_fetch_next_token(yaml_parser_t *parser);
-
-/*
- * Potential simple keys.
- */
-
-static int
-yaml_parser_stale_simple_keys(yaml_parser_t *parser);
-
-static int
-yaml_parser_save_simple_key(yaml_parser_t *parser);
-
-static int
-yaml_parser_remove_simple_key(yaml_parser_t *parser);
-
-static int
-yaml_parser_increase_flow_level(yaml_parser_t *parser);
-
-static int
-yaml_parser_decrease_flow_level(yaml_parser_t *parser);
-
-/*
- * Indentation treatment.
- */
-
-static int
-yaml_parser_roll_indent(yaml_parser_t *parser, ptrdiff_t column,
- ptrdiff_t number, yaml_token_type_t type, yaml_mark_t mark);
-
-static int
-yaml_parser_unroll_indent(yaml_parser_t *parser, ptrdiff_t column);
-
-/*
- * Token fetchers.
- */
-
-static int
-yaml_parser_fetch_stream_start(yaml_parser_t *parser);
-
-static int
-yaml_parser_fetch_stream_end(yaml_parser_t *parser);
-
-static int
-yaml_parser_fetch_directive(yaml_parser_t *parser);
-
-static int
-yaml_parser_fetch_document_indicator(yaml_parser_t *parser,
- yaml_token_type_t type);
-
-static int
-yaml_parser_fetch_flow_collection_start(yaml_parser_t *parser,
- yaml_token_type_t type);
-
-static int
-yaml_parser_fetch_flow_collection_end(yaml_parser_t *parser,
- yaml_token_type_t type);
-
-static int
-yaml_parser_fetch_flow_entry(yaml_parser_t *parser);
-
-static int
-yaml_parser_fetch_block_entry(yaml_parser_t *parser);
-
-static int
-yaml_parser_fetch_key(yaml_parser_t *parser);
-
-static int
-yaml_parser_fetch_value(yaml_parser_t *parser);
-
-static int
-yaml_parser_fetch_anchor(yaml_parser_t *parser, yaml_token_type_t type);
-
-static int
-yaml_parser_fetch_tag(yaml_parser_t *parser);
-
-static int
-yaml_parser_fetch_block_scalar(yaml_parser_t *parser, int literal);
-
-static int
-yaml_parser_fetch_flow_scalar(yaml_parser_t *parser, int single);
-
-static int
-yaml_parser_fetch_plain_scalar(yaml_parser_t *parser);
-
-/*
- * Token scanners.
- */
-
-static int
-yaml_parser_scan_to_next_token(yaml_parser_t *parser);
-
-static int
-yaml_parser_scan_directive(yaml_parser_t *parser, yaml_token_t *token);
-
-static int
-yaml_parser_scan_directive_name(yaml_parser_t *parser,
- yaml_mark_t start_mark, yaml_char_t **name);
-
-static int
-yaml_parser_scan_version_directive_value(yaml_parser_t *parser,
- yaml_mark_t start_mark, int *major, int *minor);
-
-static int
-yaml_parser_scan_version_directive_number(yaml_parser_t *parser,
- yaml_mark_t start_mark, int *number);
-
-static int
-yaml_parser_scan_tag_directive_value(yaml_parser_t *parser,
- yaml_mark_t mark, yaml_char_t **handle, yaml_char_t **prefix);
-
-static int
-yaml_parser_scan_anchor(yaml_parser_t *parser, yaml_token_t *token,
- yaml_token_type_t type);
-
-static int
-yaml_parser_scan_tag(yaml_parser_t *parser, yaml_token_t *token);
-
-static int
-yaml_parser_scan_tag_handle(yaml_parser_t *parser, int directive,
- yaml_mark_t start_mark, yaml_char_t **handle);
-
-static int
+ * SCALAR("value 1",plain)
+ * KEY
+ * SCALAR("key 2",plain)
+ * VALUE
+ * SCALAR("value 2",plain)
+ * BLOCK-END
+ * BLOCK-END
+ * STREAM-END
+ *
+ * YAML also permits non-indented sequences if they are included into a block
+ * mapping. In this case, the token BLOCK-SEQUENCE-START is not produced:
+ *
+ * key:
+ * - item 1 # BLOCK-SEQUENCE-START is NOT produced here.
+ * - item 2
+ *
+ * Tokens:
+ *
+ * STREAM-START(utf-8)
+ * BLOCK-MAPPING-START
+ * KEY
+ * SCALAR("key",plain)
+ * VALUE
+ * BLOCK-ENTRY
+ * SCALAR("item 1",plain)
+ * BLOCK-ENTRY
+ * SCALAR("item 2",plain)
+ * BLOCK-END
+ */
+
+#include "yaml_private.h"
+
+/*
+ * Ensure that the buffer contains the required number of characters.
+ * Return 1 on success, 0 on failure (reader error or memory error).
+ */
+
+#define CACHE(parser,length) \
+ (parser->unread >= (length) \
+ ? 1 \
+ : yaml_parser_update_buffer(parser, (length)))
+
+/*
+ * Advance the buffer pointer.
+ */
+
+#define SKIP(parser) \
+ (parser->mark.index ++, \
+ parser->mark.column ++, \
+ parser->unread --, \
+ parser->buffer.pointer += WIDTH(parser->buffer))
+
+#define SKIP_LINE(parser) \
+ (IS_CRLF(parser->buffer) ? \
+ (parser->mark.index += 2, \
+ parser->mark.column = 0, \
+ parser->mark.line ++, \
+ parser->unread -= 2, \
+ parser->buffer.pointer += 2) : \
+ IS_BREAK(parser->buffer) ? \
+ (parser->mark.index ++, \
+ parser->mark.column = 0, \
+ parser->mark.line ++, \
+ parser->unread --, \
+ parser->buffer.pointer += WIDTH(parser->buffer)) : 0)
+
+/*
+ * Copy a character to a string buffer and advance pointers.
+ */
+
+#define READ(parser,string) \
+ (STRING_EXTEND(parser,string) ? \
+ (COPY(string,parser->buffer), \
+ parser->mark.index ++, \
+ parser->mark.column ++, \
+ parser->unread --, \
+ 1) : 0)
+
+/*
+ * Copy a line break character to a string buffer and advance pointers.
+ */
+
+#define READ_LINE(parser,string) \
+ (STRING_EXTEND(parser,string) ? \
+ (((CHECK_AT(parser->buffer,'\r',0) \
+ && CHECK_AT(parser->buffer,'\n',1)) ? /* CR LF -> LF */ \
+ (*((string).pointer++) = (yaml_char_t) '\n', \
+ parser->buffer.pointer += 2, \
+ parser->mark.index += 2, \
+ parser->mark.column = 0, \
+ parser->mark.line ++, \
+ parser->unread -= 2) : \
+ (CHECK_AT(parser->buffer,'\r',0) \
+ || CHECK_AT(parser->buffer,'\n',0)) ? /* CR|LF -> LF */ \
+ (*((string).pointer++) = (yaml_char_t) '\n', \
+ parser->buffer.pointer ++, \
+ parser->mark.index ++, \
+ parser->mark.column = 0, \
+ parser->mark.line ++, \
+ parser->unread --) : \
+ (CHECK_AT(parser->buffer,'\xC2',0) \
+ && CHECK_AT(parser->buffer,'\x85',1)) ? /* NEL -> LF */ \
+ (*((string).pointer++) = (yaml_char_t) '\n', \
+ parser->buffer.pointer += 2, \
+ parser->mark.index ++, \
+ parser->mark.column = 0, \
+ parser->mark.line ++, \
+ parser->unread --) : \
+ (CHECK_AT(parser->buffer,'\xE2',0) && \
+ CHECK_AT(parser->buffer,'\x80',1) && \
+ (CHECK_AT(parser->buffer,'\xA8',2) || \
+ CHECK_AT(parser->buffer,'\xA9',2))) ? /* LS|PS -> LS|PS */ \
+ (*((string).pointer++) = *(parser->buffer.pointer++), \
+ *((string).pointer++) = *(parser->buffer.pointer++), \
+ *((string).pointer++) = *(parser->buffer.pointer++), \
+ parser->mark.index ++, \
+ parser->mark.column = 0, \
+ parser->mark.line ++, \
+ parser->unread --) : 0), \
+ 1) : 0)
+
+/*
+ * Public API declarations.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token);
+
+/*
+ * Error handling.
+ */
+
+static int
+yaml_parser_set_scanner_error(yaml_parser_t *parser, const char *context,
+ yaml_mark_t context_mark, const char *problem);
+
+/*
+ * High-level token API.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_fetch_more_tokens(yaml_parser_t *parser);
+
+static int
+yaml_parser_fetch_next_token(yaml_parser_t *parser);
+
+/*
+ * Potential simple keys.
+ */
+
+static int
+yaml_parser_stale_simple_keys(yaml_parser_t *parser);
+
+static int
+yaml_parser_save_simple_key(yaml_parser_t *parser);
+
+static int
+yaml_parser_remove_simple_key(yaml_parser_t *parser);
+
+static int
+yaml_parser_increase_flow_level(yaml_parser_t *parser);
+
+static int
+yaml_parser_decrease_flow_level(yaml_parser_t *parser);
+
+/*
+ * Indentation treatment.
+ */
+
+static int
+yaml_parser_roll_indent(yaml_parser_t *parser, ptrdiff_t column,
+ ptrdiff_t number, yaml_token_type_t type, yaml_mark_t mark);
+
+static int
+yaml_parser_unroll_indent(yaml_parser_t *parser, ptrdiff_t column);
+
+/*
+ * Token fetchers.
+ */
+
+static int
+yaml_parser_fetch_stream_start(yaml_parser_t *parser);
+
+static int
+yaml_parser_fetch_stream_end(yaml_parser_t *parser);
+
+static int
+yaml_parser_fetch_directive(yaml_parser_t *parser);
+
+static int
+yaml_parser_fetch_document_indicator(yaml_parser_t *parser,
+ yaml_token_type_t type);
+
+static int
+yaml_parser_fetch_flow_collection_start(yaml_parser_t *parser,
+ yaml_token_type_t type);
+
+static int
+yaml_parser_fetch_flow_collection_end(yaml_parser_t *parser,
+ yaml_token_type_t type);
+
+static int
+yaml_parser_fetch_flow_entry(yaml_parser_t *parser);
+
+static int
+yaml_parser_fetch_block_entry(yaml_parser_t *parser);
+
+static int
+yaml_parser_fetch_key(yaml_parser_t *parser);
+
+static int
+yaml_parser_fetch_value(yaml_parser_t *parser);
+
+static int
+yaml_parser_fetch_anchor(yaml_parser_t *parser, yaml_token_type_t type);
+
+static int
+yaml_parser_fetch_tag(yaml_parser_t *parser);
+
+static int
+yaml_parser_fetch_block_scalar(yaml_parser_t *parser, int literal);
+
+static int
+yaml_parser_fetch_flow_scalar(yaml_parser_t *parser, int single);
+
+static int
+yaml_parser_fetch_plain_scalar(yaml_parser_t *parser);
+
+/*
+ * Token scanners.
+ */
+
+static int
+yaml_parser_scan_to_next_token(yaml_parser_t *parser);
+
+static int
+yaml_parser_scan_directive(yaml_parser_t *parser, yaml_token_t *token);
+
+static int
+yaml_parser_scan_directive_name(yaml_parser_t *parser,
+ yaml_mark_t start_mark, yaml_char_t **name);
+
+static int
+yaml_parser_scan_version_directive_value(yaml_parser_t *parser,
+ yaml_mark_t start_mark, int *major, int *minor);
+
+static int
+yaml_parser_scan_version_directive_number(yaml_parser_t *parser,
+ yaml_mark_t start_mark, int *number);
+
+static int
+yaml_parser_scan_tag_directive_value(yaml_parser_t *parser,
+ yaml_mark_t mark, yaml_char_t **handle, yaml_char_t **prefix);
+
+static int
+yaml_parser_scan_anchor(yaml_parser_t *parser, yaml_token_t *token,
+ yaml_token_type_t type);
+
+static int
+yaml_parser_scan_tag(yaml_parser_t *parser, yaml_token_t *token);
+
+static int
+yaml_parser_scan_tag_handle(yaml_parser_t *parser, int directive,
+ yaml_mark_t start_mark, yaml_char_t **handle);
+
+static int
yaml_parser_scan_tag_uri(yaml_parser_t *parser, int uri_char, int directive,
- yaml_char_t *head, yaml_mark_t start_mark, yaml_char_t **uri);
-
-static int
-yaml_parser_scan_uri_escapes(yaml_parser_t *parser, int directive,
- yaml_mark_t start_mark, yaml_string_t *string);
-
-static int
-yaml_parser_scan_block_scalar(yaml_parser_t *parser, yaml_token_t *token,
- int literal);
-
-static int
-yaml_parser_scan_block_scalar_breaks(yaml_parser_t *parser,
- int *indent, yaml_string_t *breaks,
- yaml_mark_t start_mark, yaml_mark_t *end_mark);
-
-static int
-yaml_parser_scan_flow_scalar(yaml_parser_t *parser, yaml_token_t *token,
- int single);
-
-static int
-yaml_parser_scan_plain_scalar(yaml_parser_t *parser, yaml_token_t *token);
-
-/*
- * Get the next token.
- */
-
-YAML_DECLARE(int)
-yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token)
-{
- assert(parser); /* Non-NULL parser object is expected. */
- assert(token); /* Non-NULL token object is expected. */
-
- /* Erase the token object. */
-
- memset(token, 0, sizeof(yaml_token_t));
-
- /* No tokens after STREAM-END or error. */
-
- if (parser->stream_end_produced || parser->error) {
- return 1;
- }
-
- /* Ensure that the tokens queue contains enough tokens. */
-
- if (!parser->token_available) {
- if (!yaml_parser_fetch_more_tokens(parser))
- return 0;
- }
-
- /* Fetch the next token from the queue. */
-
- *token = DEQUEUE(parser, parser->tokens);
- parser->token_available = 0;
- parser->tokens_parsed ++;
-
- if (token->type == YAML_STREAM_END_TOKEN) {
- parser->stream_end_produced = 1;
- }
-
- return 1;
-}
-
-/*
- * Set the scanner error and return 0.
- */
-
-static int
-yaml_parser_set_scanner_error(yaml_parser_t *parser, const char *context,
- yaml_mark_t context_mark, const char *problem)
-{
- parser->error = YAML_SCANNER_ERROR;
- parser->context = context;
- parser->context_mark = context_mark;
- parser->problem = problem;
- parser->problem_mark = parser->mark;
-
- return 0;
-}
-
-/*
- * Ensure that the tokens queue contains at least one token which can be
- * returned to the Parser.
- */
-
-YAML_DECLARE(int)
-yaml_parser_fetch_more_tokens(yaml_parser_t *parser)
-{
- int need_more_tokens;
-
- /* While we need more tokens to fetch, do it. */
-
- while (1)
- {
- /*
- * Check if we really need to fetch more tokens.
- */
-
- need_more_tokens = 0;
-
- if (parser->tokens.head == parser->tokens.tail)
- {
- /* Queue is empty. */
-
- need_more_tokens = 1;
- }
- else
- {
- yaml_simple_key_t *simple_key;
-
- /* Check if any potential simple key may occupy the head position. */
-
- if (!yaml_parser_stale_simple_keys(parser))
- return 0;
-
- for (simple_key = parser->simple_keys.start;
- simple_key != parser->simple_keys.top; simple_key++) {
- if (simple_key->possible
- && simple_key->token_number == parser->tokens_parsed) {
- need_more_tokens = 1;
- break;
- }
- }
- }
-
- /* We are finished. */
-
- if (!need_more_tokens)
- break;
-
- /* Fetch the next token. */
-
- if (!yaml_parser_fetch_next_token(parser))
- return 0;
- }
-
- parser->token_available = 1;
-
- return 1;
-}
-
-/*
- * The dispatcher for token fetchers.
- */
-
-static int
-yaml_parser_fetch_next_token(yaml_parser_t *parser)
-{
- /* Ensure that the buffer is initialized. */
-
- if (!CACHE(parser, 1))
- return 0;
-
- /* Check if we just started scanning. Fetch STREAM-START then. */
-
- if (!parser->stream_start_produced)
- return yaml_parser_fetch_stream_start(parser);
-
- /* Eat whitespaces and comments until we reach the next token. */
-
- if (!yaml_parser_scan_to_next_token(parser))
- return 0;
-
- /* Remove obsolete potential simple keys. */
-
- if (!yaml_parser_stale_simple_keys(parser))
- return 0;
-
- /* Check the indentation level against the current column. */
-
- if (!yaml_parser_unroll_indent(parser, parser->mark.column))
- return 0;
-
- /*
- * Ensure that the buffer contains at least 4 characters. 4 is the length
- * of the longest indicators ('--- ' and '... ').
- */
-
- if (!CACHE(parser, 4))
- return 0;
-
- /* Is it the end of the stream? */
-
- if (IS_Z(parser->buffer))
- return yaml_parser_fetch_stream_end(parser);
-
- /* Is it a directive? */
-
- if (parser->mark.column == 0 && CHECK(parser->buffer, '%'))
- return yaml_parser_fetch_directive(parser);
-
- /* Is it the document start indicator? */
-
- if (parser->mark.column == 0
- && CHECK_AT(parser->buffer, '-', 0)
- && CHECK_AT(parser->buffer, '-', 1)
- && CHECK_AT(parser->buffer, '-', 2)
- && IS_BLANKZ_AT(parser->buffer, 3))
- return yaml_parser_fetch_document_indicator(parser,
- YAML_DOCUMENT_START_TOKEN);
-
- /* Is it the document end indicator? */
-
- if (parser->mark.column == 0
- && CHECK_AT(parser->buffer, '.', 0)
- && CHECK_AT(parser->buffer, '.', 1)
- && CHECK_AT(parser->buffer, '.', 2)
- && IS_BLANKZ_AT(parser->buffer, 3))
- return yaml_parser_fetch_document_indicator(parser,
- YAML_DOCUMENT_END_TOKEN);
-
- /* Is it the flow sequence start indicator? */
-
- if (CHECK(parser->buffer, '['))
- return yaml_parser_fetch_flow_collection_start(parser,
- YAML_FLOW_SEQUENCE_START_TOKEN);
-
- /* Is it the flow mapping start indicator? */
-
- if (CHECK(parser->buffer, '{'))
- return yaml_parser_fetch_flow_collection_start(parser,
- YAML_FLOW_MAPPING_START_TOKEN);
-
- /* Is it the flow sequence end indicator? */
-
- if (CHECK(parser->buffer, ']'))
- return yaml_parser_fetch_flow_collection_end(parser,
- YAML_FLOW_SEQUENCE_END_TOKEN);
-
- /* Is it the flow mapping end indicator? */
-
- if (CHECK(parser->buffer, '}'))
- return yaml_parser_fetch_flow_collection_end(parser,
- YAML_FLOW_MAPPING_END_TOKEN);
-
- /* Is it the flow entry indicator? */
-
- if (CHECK(parser->buffer, ','))
- return yaml_parser_fetch_flow_entry(parser);
-
- /* Is it the block entry indicator? */
-
- if (CHECK(parser->buffer, '-') && IS_BLANKZ_AT(parser->buffer, 1))
- return yaml_parser_fetch_block_entry(parser);
-
- /* Is it the key indicator? */
-
- if (CHECK(parser->buffer, '?')
- && (parser->flow_level || IS_BLANKZ_AT(parser->buffer, 1)))
- return yaml_parser_fetch_key(parser);
-
- /* Is it the value indicator? */
-
- if (CHECK(parser->buffer, ':')
- && (parser->flow_level || IS_BLANKZ_AT(parser->buffer, 1)))
- return yaml_parser_fetch_value(parser);
-
- /* Is it an alias? */
-
- if (CHECK(parser->buffer, '*'))
- return yaml_parser_fetch_anchor(parser, YAML_ALIAS_TOKEN);
-
- /* Is it an anchor? */
-
- if (CHECK(parser->buffer, '&'))
- return yaml_parser_fetch_anchor(parser, YAML_ANCHOR_TOKEN);
-
- /* Is it a tag? */
-
- if (CHECK(parser->buffer, '!'))
- return yaml_parser_fetch_tag(parser);
-
- /* Is it a literal scalar? */
-
- if (CHECK(parser->buffer, '|') && !parser->flow_level)
- return yaml_parser_fetch_block_scalar(parser, 1);
-
- /* Is it a folded scalar? */
-
- if (CHECK(parser->buffer, '>') && !parser->flow_level)
- return yaml_parser_fetch_block_scalar(parser, 0);
-
- /* Is it a single-quoted scalar? */
-
- if (CHECK(parser->buffer, '\''))
- return yaml_parser_fetch_flow_scalar(parser, 1);
-
- /* Is it a double-quoted scalar? */
-
- if (CHECK(parser->buffer, '"'))
- return yaml_parser_fetch_flow_scalar(parser, 0);
-
- /*
- * Is it a plain scalar?
- *
- * A plain scalar may start with any non-blank characters except
- *
- * '-', '?', ':', ',', '[', ']', '{', '}',
- * '#', '&', '*', '!', '|', '>', '\'', '\"',
- * '%', '@', '`'.
- *
- * In the block context (and, for the '-' indicator, in the flow context
- * too), it may also start with the characters
- *
- * '-', '?', ':'
- *
- * if it is followed by a non-space character.
- *
- * The last rule is more restrictive than the specification requires.
- */
-
- if (!(IS_BLANKZ(parser->buffer) || CHECK(parser->buffer, '-')
- || CHECK(parser->buffer, '?') || CHECK(parser->buffer, ':')
- || CHECK(parser->buffer, ',') || CHECK(parser->buffer, '[')
- || CHECK(parser->buffer, ']') || CHECK(parser->buffer, '{')
- || CHECK(parser->buffer, '}') || CHECK(parser->buffer, '#')
- || CHECK(parser->buffer, '&') || CHECK(parser->buffer, '*')
- || CHECK(parser->buffer, '!') || CHECK(parser->buffer, '|')
- || CHECK(parser->buffer, '>') || CHECK(parser->buffer, '\'')
- || CHECK(parser->buffer, '"') || CHECK(parser->buffer, '%')
- || CHECK(parser->buffer, '@') || CHECK(parser->buffer, '`')) ||
- (CHECK(parser->buffer, '-') && !IS_BLANK_AT(parser->buffer, 1)) ||
- (!parser->flow_level &&
- (CHECK(parser->buffer, '?') || CHECK(parser->buffer, ':'))
- && !IS_BLANKZ_AT(parser->buffer, 1)))
- return yaml_parser_fetch_plain_scalar(parser);
-
- /*
- * If we don't determine the token type so far, it is an error.
- */
-
- return yaml_parser_set_scanner_error(parser,
- "while scanning for the next token", parser->mark,
- "found character that cannot start any token");
-}
-
-/*
- * Check the list of potential simple keys and remove the positions that
- * cannot contain simple keys anymore.
- */
-
-static int
-yaml_parser_stale_simple_keys(yaml_parser_t *parser)
-{
- yaml_simple_key_t *simple_key;
-
- /* Check for a potential simple key for each flow level. */
-
- for (simple_key = parser->simple_keys.start;
- simple_key != parser->simple_keys.top; simple_key ++)
- {
- /*
- * The specification requires that a simple key
- *
- * - is limited to a single line,
- * - is shorter than 1024 characters.
- */
-
- if (simple_key->possible
- && (simple_key->mark.line < parser->mark.line
- || simple_key->mark.index+1024 < parser->mark.index)) {
-
- /* Check if the potential simple key to be removed is required. */
-
- if (simple_key->required) {
- return yaml_parser_set_scanner_error(parser,
- "while scanning a simple key", simple_key->mark,
- "could not find expected ':'");
- }
-
- simple_key->possible = 0;
- }
- }
-
- return 1;
-}
-
-/*
- * Check if a simple key may start at the current position and add it if
- * needed.
- */
-
-static int
-yaml_parser_save_simple_key(yaml_parser_t *parser)
-{
- /*
- * A simple key is required at the current position if the scanner is in
- * the block context and the current column coincides with the indentation
- * level.
- */
-
- int required = (!parser->flow_level
- && parser->indent == (ptrdiff_t)parser->mark.column);
-
- /*
- * If the current position may start a simple key, save it.
- */
-
- if (parser->simple_key_allowed)
- {
- yaml_simple_key_t simple_key;
- simple_key.possible = 1;
- simple_key.required = required;
+ yaml_char_t *head, yaml_mark_t start_mark, yaml_char_t **uri);
+
+static int
+yaml_parser_scan_uri_escapes(yaml_parser_t *parser, int directive,
+ yaml_mark_t start_mark, yaml_string_t *string);
+
+static int
+yaml_parser_scan_block_scalar(yaml_parser_t *parser, yaml_token_t *token,
+ int literal);
+
+static int
+yaml_parser_scan_block_scalar_breaks(yaml_parser_t *parser,
+ int *indent, yaml_string_t *breaks,
+ yaml_mark_t start_mark, yaml_mark_t *end_mark);
+
+static int
+yaml_parser_scan_flow_scalar(yaml_parser_t *parser, yaml_token_t *token,
+ int single);
+
+static int
+yaml_parser_scan_plain_scalar(yaml_parser_t *parser, yaml_token_t *token);
+
+/*
+ * Get the next token.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token)
+{
+ assert(parser); /* Non-NULL parser object is expected. */
+ assert(token); /* Non-NULL token object is expected. */
+
+ /* Erase the token object. */
+
+ memset(token, 0, sizeof(yaml_token_t));
+
+ /* No tokens after STREAM-END or error. */
+
+ if (parser->stream_end_produced || parser->error) {
+ return 1;
+ }
+
+ /* Ensure that the tokens queue contains enough tokens. */
+
+ if (!parser->token_available) {
+ if (!yaml_parser_fetch_more_tokens(parser))
+ return 0;
+ }
+
+ /* Fetch the next token from the queue. */
+
+ *token = DEQUEUE(parser, parser->tokens);
+ parser->token_available = 0;
+ parser->tokens_parsed ++;
+
+ if (token->type == YAML_STREAM_END_TOKEN) {
+ parser->stream_end_produced = 1;
+ }
+
+ return 1;
+}
+
+/*
+ * Set the scanner error and return 0.
+ */
+
+static int
+yaml_parser_set_scanner_error(yaml_parser_t *parser, const char *context,
+ yaml_mark_t context_mark, const char *problem)
+{
+ parser->error = YAML_SCANNER_ERROR;
+ parser->context = context;
+ parser->context_mark = context_mark;
+ parser->problem = problem;
+ parser->problem_mark = parser->mark;
+
+ return 0;
+}
+
+/*
+ * Ensure that the tokens queue contains at least one token which can be
+ * returned to the Parser.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_fetch_more_tokens(yaml_parser_t *parser)
+{
+ int need_more_tokens;
+
+ /* While we need more tokens to fetch, do it. */
+
+ while (1)
+ {
+ /*
+ * Check if we really need to fetch more tokens.
+ */
+
+ need_more_tokens = 0;
+
+ if (parser->tokens.head == parser->tokens.tail)
+ {
+ /* Queue is empty. */
+
+ need_more_tokens = 1;
+ }
+ else
+ {
+ yaml_simple_key_t *simple_key;
+
+ /* Check if any potential simple key may occupy the head position. */
+
+ if (!yaml_parser_stale_simple_keys(parser))
+ return 0;
+
+ for (simple_key = parser->simple_keys.start;
+ simple_key != parser->simple_keys.top; simple_key++) {
+ if (simple_key->possible
+ && simple_key->token_number == parser->tokens_parsed) {
+ need_more_tokens = 1;
+ break;
+ }
+ }
+ }
+
+ /* We are finished. */
+
+ if (!need_more_tokens)
+ break;
+
+ /* Fetch the next token. */
+
+ if (!yaml_parser_fetch_next_token(parser))
+ return 0;
+ }
+
+ parser->token_available = 1;
+
+ return 1;
+}
+
+/*
+ * The dispatcher for token fetchers.
+ */
+
+static int
+yaml_parser_fetch_next_token(yaml_parser_t *parser)
+{
+ /* Ensure that the buffer is initialized. */
+
+ if (!CACHE(parser, 1))
+ return 0;
+
+ /* Check if we just started scanning. Fetch STREAM-START then. */
+
+ if (!parser->stream_start_produced)
+ return yaml_parser_fetch_stream_start(parser);
+
+ /* Eat whitespaces and comments until we reach the next token. */
+
+ if (!yaml_parser_scan_to_next_token(parser))
+ return 0;
+
+ /* Remove obsolete potential simple keys. */
+
+ if (!yaml_parser_stale_simple_keys(parser))
+ return 0;
+
+ /* Check the indentation level against the current column. */
+
+ if (!yaml_parser_unroll_indent(parser, parser->mark.column))
+ return 0;
+
+ /*
+ * Ensure that the buffer contains at least 4 characters. 4 is the length
+ * of the longest indicators ('--- ' and '... ').
+ */
+
+ if (!CACHE(parser, 4))
+ return 0;
+
+ /* Is it the end of the stream? */
+
+ if (IS_Z(parser->buffer))
+ return yaml_parser_fetch_stream_end(parser);
+
+ /* Is it a directive? */
+
+ if (parser->mark.column == 0 && CHECK(parser->buffer, '%'))
+ return yaml_parser_fetch_directive(parser);
+
+ /* Is it the document start indicator? */
+
+ if (parser->mark.column == 0
+ && CHECK_AT(parser->buffer, '-', 0)
+ && CHECK_AT(parser->buffer, '-', 1)
+ && CHECK_AT(parser->buffer, '-', 2)
+ && IS_BLANKZ_AT(parser->buffer, 3))
+ return yaml_parser_fetch_document_indicator(parser,
+ YAML_DOCUMENT_START_TOKEN);
+
+ /* Is it the document end indicator? */
+
+ if (parser->mark.column == 0
+ && CHECK_AT(parser->buffer, '.', 0)
+ && CHECK_AT(parser->buffer, '.', 1)
+ && CHECK_AT(parser->buffer, '.', 2)
+ && IS_BLANKZ_AT(parser->buffer, 3))
+ return yaml_parser_fetch_document_indicator(parser,
+ YAML_DOCUMENT_END_TOKEN);
+
+ /* Is it the flow sequence start indicator? */
+
+ if (CHECK(parser->buffer, '['))
+ return yaml_parser_fetch_flow_collection_start(parser,
+ YAML_FLOW_SEQUENCE_START_TOKEN);
+
+ /* Is it the flow mapping start indicator? */
+
+ if (CHECK(parser->buffer, '{'))
+ return yaml_parser_fetch_flow_collection_start(parser,
+ YAML_FLOW_MAPPING_START_TOKEN);
+
+ /* Is it the flow sequence end indicator? */
+
+ if (CHECK(parser->buffer, ']'))
+ return yaml_parser_fetch_flow_collection_end(parser,
+ YAML_FLOW_SEQUENCE_END_TOKEN);
+
+ /* Is it the flow mapping end indicator? */
+
+ if (CHECK(parser->buffer, '}'))
+ return yaml_parser_fetch_flow_collection_end(parser,
+ YAML_FLOW_MAPPING_END_TOKEN);
+
+ /* Is it the flow entry indicator? */
+
+ if (CHECK(parser->buffer, ','))
+ return yaml_parser_fetch_flow_entry(parser);
+
+ /* Is it the block entry indicator? */
+
+ if (CHECK(parser->buffer, '-') && IS_BLANKZ_AT(parser->buffer, 1))
+ return yaml_parser_fetch_block_entry(parser);
+
+ /* Is it the key indicator? */
+
+ if (CHECK(parser->buffer, '?')
+ && (parser->flow_level || IS_BLANKZ_AT(parser->buffer, 1)))
+ return yaml_parser_fetch_key(parser);
+
+ /* Is it the value indicator? */
+
+ if (CHECK(parser->buffer, ':')
+ && (parser->flow_level || IS_BLANKZ_AT(parser->buffer, 1)))
+ return yaml_parser_fetch_value(parser);
+
+ /* Is it an alias? */
+
+ if (CHECK(parser->buffer, '*'))
+ return yaml_parser_fetch_anchor(parser, YAML_ALIAS_TOKEN);
+
+ /* Is it an anchor? */
+
+ if (CHECK(parser->buffer, '&'))
+ return yaml_parser_fetch_anchor(parser, YAML_ANCHOR_TOKEN);
+
+ /* Is it a tag? */
+
+ if (CHECK(parser->buffer, '!'))
+ return yaml_parser_fetch_tag(parser);
+
+ /* Is it a literal scalar? */
+
+ if (CHECK(parser->buffer, '|') && !parser->flow_level)
+ return yaml_parser_fetch_block_scalar(parser, 1);
+
+ /* Is it a folded scalar? */
+
+ if (CHECK(parser->buffer, '>') && !parser->flow_level)
+ return yaml_parser_fetch_block_scalar(parser, 0);
+
+ /* Is it a single-quoted scalar? */
+
+ if (CHECK(parser->buffer, '\''))
+ return yaml_parser_fetch_flow_scalar(parser, 1);
+
+ /* Is it a double-quoted scalar? */
+
+ if (CHECK(parser->buffer, '"'))
+ return yaml_parser_fetch_flow_scalar(parser, 0);
+
+ /*
+ * Is it a plain scalar?
+ *
+ * A plain scalar may start with any non-blank characters except
+ *
+ * '-', '?', ':', ',', '[', ']', '{', '}',
+ * '#', '&', '*', '!', '|', '>', '\'', '\"',
+ * '%', '@', '`'.
+ *
+ * In the block context (and, for the '-' indicator, in the flow context
+ * too), it may also start with the characters
+ *
+ * '-', '?', ':'
+ *
+ * if it is followed by a non-space character.
+ *
+ * The last rule is more restrictive than the specification requires.
+ */
+
+ if (!(IS_BLANKZ(parser->buffer) || CHECK(parser->buffer, '-')
+ || CHECK(parser->buffer, '?') || CHECK(parser->buffer, ':')
+ || CHECK(parser->buffer, ',') || CHECK(parser->buffer, '[')
+ || CHECK(parser->buffer, ']') || CHECK(parser->buffer, '{')
+ || CHECK(parser->buffer, '}') || CHECK(parser->buffer, '#')
+ || CHECK(parser->buffer, '&') || CHECK(parser->buffer, '*')
+ || CHECK(parser->buffer, '!') || CHECK(parser->buffer, '|')
+ || CHECK(parser->buffer, '>') || CHECK(parser->buffer, '\'')
+ || CHECK(parser->buffer, '"') || CHECK(parser->buffer, '%')
+ || CHECK(parser->buffer, '@') || CHECK(parser->buffer, '`')) ||
+ (CHECK(parser->buffer, '-') && !IS_BLANK_AT(parser->buffer, 1)) ||
+ (!parser->flow_level &&
+ (CHECK(parser->buffer, '?') || CHECK(parser->buffer, ':'))
+ && !IS_BLANKZ_AT(parser->buffer, 1)))
+ return yaml_parser_fetch_plain_scalar(parser);
+
+ /*
+ * If we don't determine the token type so far, it is an error.
+ */
+
+ return yaml_parser_set_scanner_error(parser,
+ "while scanning for the next token", parser->mark,
+ "found character that cannot start any token");
+}
+
+/*
+ * Check the list of potential simple keys and remove the positions that
+ * cannot contain simple keys anymore.
+ */
+
+static int
+yaml_parser_stale_simple_keys(yaml_parser_t *parser)
+{
+ yaml_simple_key_t *simple_key;
+
+ /* Check for a potential simple key for each flow level. */
+
+ for (simple_key = parser->simple_keys.start;
+ simple_key != parser->simple_keys.top; simple_key ++)
+ {
+ /*
+ * The specification requires that a simple key
+ *
+ * - is limited to a single line,
+ * - is shorter than 1024 characters.
+ */
+
+ if (simple_key->possible
+ && (simple_key->mark.line < parser->mark.line
+ || simple_key->mark.index+1024 < parser->mark.index)) {
+
+ /* Check if the potential simple key to be removed is required. */
+
+ if (simple_key->required) {
+ return yaml_parser_set_scanner_error(parser,
+ "while scanning a simple key", simple_key->mark,
+ "could not find expected ':'");
+ }
+
+ simple_key->possible = 0;
+ }
+ }
+
+ return 1;
+}
+
+/*
+ * Check if a simple key may start at the current position and add it if
+ * needed.
+ */
+
+static int
+yaml_parser_save_simple_key(yaml_parser_t *parser)
+{
+ /*
+ * A simple key is required at the current position if the scanner is in
+ * the block context and the current column coincides with the indentation
+ * level.
+ */
+
+ int required = (!parser->flow_level
+ && parser->indent == (ptrdiff_t)parser->mark.column);
+
+ /*
+ * If the current position may start a simple key, save it.
+ */
+
+ if (parser->simple_key_allowed)
+ {
+ yaml_simple_key_t simple_key;
+ simple_key.possible = 1;
+ simple_key.required = required;
simple_key.token_number =
- parser->tokens_parsed + (parser->tokens.tail - parser->tokens.head);
- simple_key.mark = parser->mark;
-
- if (!yaml_parser_remove_simple_key(parser)) return 0;
-
- *(parser->simple_keys.top-1) = simple_key;
- }
-
- return 1;
-}
-
-/*
- * Remove a potential simple key at the current flow level.
- */
-
-static int
-yaml_parser_remove_simple_key(yaml_parser_t *parser)
-{
- yaml_simple_key_t *simple_key = parser->simple_keys.top-1;
-
- if (simple_key->possible)
- {
- /* If the key is required, it is an error. */
-
- if (simple_key->required) {
- return yaml_parser_set_scanner_error(parser,
- "while scanning a simple key", simple_key->mark,
- "could not find expected ':'");
- }
- }
-
- /* Remove the key from the stack. */
-
- simple_key->possible = 0;
-
- return 1;
-}
-
-/*
- * Increase the flow level and resize the simple key list if needed.
- */
-
-static int
-yaml_parser_increase_flow_level(yaml_parser_t *parser)
-{
- yaml_simple_key_t empty_simple_key = { 0, 0, 0, { 0, 0, 0 } };
-
- /* Reset the simple key on the next level. */
-
- if (!PUSH(parser, parser->simple_keys, empty_simple_key))
- return 0;
-
- /* Increase the flow level. */
-
- if (parser->flow_level == INT_MAX) {
- parser->error = YAML_MEMORY_ERROR;
- return 0;
- }
-
- parser->flow_level++;
-
- return 1;
-}
-
-/*
- * Decrease the flow level.
- */
-
-static int
-yaml_parser_decrease_flow_level(yaml_parser_t *parser)
-{
- if (parser->flow_level) {
- parser->flow_level --;
+ parser->tokens_parsed + (parser->tokens.tail - parser->tokens.head);
+ simple_key.mark = parser->mark;
+
+ if (!yaml_parser_remove_simple_key(parser)) return 0;
+
+ *(parser->simple_keys.top-1) = simple_key;
+ }
+
+ return 1;
+}
+
+/*
+ * Remove a potential simple key at the current flow level.
+ */
+
+static int
+yaml_parser_remove_simple_key(yaml_parser_t *parser)
+{
+ yaml_simple_key_t *simple_key = parser->simple_keys.top-1;
+
+ if (simple_key->possible)
+ {
+ /* If the key is required, it is an error. */
+
+ if (simple_key->required) {
+ return yaml_parser_set_scanner_error(parser,
+ "while scanning a simple key", simple_key->mark,
+ "could not find expected ':'");
+ }
+ }
+
+ /* Remove the key from the stack. */
+
+ simple_key->possible = 0;
+
+ return 1;
+}
+
+/*
+ * Increase the flow level and resize the simple key list if needed.
+ */
+
+static int
+yaml_parser_increase_flow_level(yaml_parser_t *parser)
+{
+ yaml_simple_key_t empty_simple_key = { 0, 0, 0, { 0, 0, 0 } };
+
+ /* Reset the simple key on the next level. */
+
+ if (!PUSH(parser, parser->simple_keys, empty_simple_key))
+ return 0;
+
+ /* Increase the flow level. */
+
+ if (parser->flow_level == INT_MAX) {
+ parser->error = YAML_MEMORY_ERROR;
+ return 0;
+ }
+
+ parser->flow_level++;
+
+ return 1;
+}
+
+/*
+ * Decrease the flow level.
+ */
+
+static int
+yaml_parser_decrease_flow_level(yaml_parser_t *parser)
+{
+ if (parser->flow_level) {
+ parser->flow_level --;
(void)POP(parser, parser->simple_keys);
- }
-
- return 1;
-}
-
-/*
- * Push the current indentation level to the stack and set the new level
- * the current column is greater than the indentation level. In this case,
- * append or insert the specified token into the token queue.
- *
- */
-
-static int
-yaml_parser_roll_indent(yaml_parser_t *parser, ptrdiff_t column,
- ptrdiff_t number, yaml_token_type_t type, yaml_mark_t mark)
-{
- yaml_token_t token;
-
- /* In the flow context, do nothing. */
-
- if (parser->flow_level)
- return 1;
-
- if (parser->indent < column)
- {
- /*
- * Push the current indentation level to the stack and set the new
- * indentation level.
- */
-
- if (!PUSH(parser, parser->indents, parser->indent))
- return 0;
-
- if (column > INT_MAX) {
- parser->error = YAML_MEMORY_ERROR;
- return 0;
- }
-
- parser->indent = column;
-
- /* Create a token and insert it into the queue. */
-
- TOKEN_INIT(token, type, mark, mark);
-
- if (number == -1) {
- if (!ENQUEUE(parser, parser->tokens, token))
- return 0;
- }
- else {
- if (!QUEUE_INSERT(parser,
- parser->tokens, number - parser->tokens_parsed, token))
- return 0;
- }
- }
-
- return 1;
-}
-
-/*
- * Pop indentation levels from the indents stack until the current level
+ }
+
+ return 1;
+}
+
+/*
+ * Push the current indentation level to the stack and set the new level
+ * the current column is greater than the indentation level. In this case,
+ * append or insert the specified token into the token queue.
+ *
+ */
+
+static int
+yaml_parser_roll_indent(yaml_parser_t *parser, ptrdiff_t column,
+ ptrdiff_t number, yaml_token_type_t type, yaml_mark_t mark)
+{
+ yaml_token_t token;
+
+ /* In the flow context, do nothing. */
+
+ if (parser->flow_level)
+ return 1;
+
+ if (parser->indent < column)
+ {
+ /*
+ * Push the current indentation level to the stack and set the new
+ * indentation level.
+ */
+
+ if (!PUSH(parser, parser->indents, parser->indent))
+ return 0;
+
+ if (column > INT_MAX) {
+ parser->error = YAML_MEMORY_ERROR;
+ return 0;
+ }
+
+ parser->indent = column;
+
+ /* Create a token and insert it into the queue. */
+
+ TOKEN_INIT(token, type, mark, mark);
+
+ if (number == -1) {
+ if (!ENQUEUE(parser, parser->tokens, token))
+ return 0;
+ }
+ else {
+ if (!QUEUE_INSERT(parser,
+ parser->tokens, number - parser->tokens_parsed, token))
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+/*
+ * Pop indentation levels from the indents stack until the current level
* becomes less or equal to the column. For each indentation level, append
- * the BLOCK-END token.
- */
-
-
-static int
-yaml_parser_unroll_indent(yaml_parser_t *parser, ptrdiff_t column)
-{
- yaml_token_t token;
-
- /* In the flow context, do nothing. */
-
- if (parser->flow_level)
- return 1;
-
+ * the BLOCK-END token.
+ */
+
+
+static int
+yaml_parser_unroll_indent(yaml_parser_t *parser, ptrdiff_t column)
+{
+ yaml_token_t token;
+
+ /* In the flow context, do nothing. */
+
+ if (parser->flow_level)
+ return 1;
+
/* Loop through the indentation levels in the stack. */
-
- while (parser->indent > column)
- {
- /* Create a token and append it to the queue. */
-
- TOKEN_INIT(token, YAML_BLOCK_END_TOKEN, parser->mark, parser->mark);
-
- if (!ENQUEUE(parser, parser->tokens, token))
- return 0;
-
- /* Pop the indentation level. */
-
- parser->indent = POP(parser, parser->indents);
- }
-
- return 1;
-}
-
-/*
- * Initialize the scanner and produce the STREAM-START token.
- */
-
-static int
-yaml_parser_fetch_stream_start(yaml_parser_t *parser)
-{
- yaml_simple_key_t simple_key = { 0, 0, 0, { 0, 0, 0 } };
- yaml_token_t token;
-
- /* Set the initial indentation. */
-
- parser->indent = -1;
-
- /* Initialize the simple key stack. */
-
- if (!PUSH(parser, parser->simple_keys, simple_key))
- return 0;
-
- /* A simple key is allowed at the beginning of the stream. */
-
- parser->simple_key_allowed = 1;
-
- /* We have started. */
-
- parser->stream_start_produced = 1;
-
- /* Create the STREAM-START token and append it to the queue. */
-
- STREAM_START_TOKEN_INIT(token, parser->encoding,
- parser->mark, parser->mark);
-
- if (!ENQUEUE(parser, parser->tokens, token))
- return 0;
-
- return 1;
-}
-
-/*
- * Produce the STREAM-END token and shut down the scanner.
- */
-
-static int
-yaml_parser_fetch_stream_end(yaml_parser_t *parser)
-{
- yaml_token_t token;
-
- /* Force new line. */
-
- if (parser->mark.column != 0) {
- parser->mark.column = 0;
- parser->mark.line ++;
- }
-
- /* Reset the indentation level. */
-
- if (!yaml_parser_unroll_indent(parser, -1))
- return 0;
-
- /* Reset simple keys. */
-
- if (!yaml_parser_remove_simple_key(parser))
- return 0;
-
- parser->simple_key_allowed = 0;
-
- /* Create the STREAM-END token and append it to the queue. */
-
- STREAM_END_TOKEN_INIT(token, parser->mark, parser->mark);
-
- if (!ENQUEUE(parser, parser->tokens, token))
- return 0;
-
- return 1;
-}
-
-/*
- * Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token.
- */
-
-static int
-yaml_parser_fetch_directive(yaml_parser_t *parser)
-{
- yaml_token_t token;
-
- /* Reset the indentation level. */
-
- if (!yaml_parser_unroll_indent(parser, -1))
- return 0;
-
- /* Reset simple keys. */
-
- if (!yaml_parser_remove_simple_key(parser))
- return 0;
-
- parser->simple_key_allowed = 0;
-
- /* Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. */
-
- if (!yaml_parser_scan_directive(parser, &token))
- return 0;
-
- /* Append the token to the queue. */
-
- if (!ENQUEUE(parser, parser->tokens, token)) {
- yaml_token_delete(&token);
- return 0;
- }
-
- return 1;
-}
-
-/*
- * Produce the DOCUMENT-START or DOCUMENT-END token.
- */
-
-static int
-yaml_parser_fetch_document_indicator(yaml_parser_t *parser,
- yaml_token_type_t type)
-{
- yaml_mark_t start_mark, end_mark;
- yaml_token_t token;
-
- /* Reset the indentation level. */
-
- if (!yaml_parser_unroll_indent(parser, -1))
- return 0;
-
- /* Reset simple keys. */
-
- if (!yaml_parser_remove_simple_key(parser))
- return 0;
-
- parser->simple_key_allowed = 0;
-
- /* Consume the token. */
-
- start_mark = parser->mark;
-
- SKIP(parser);
- SKIP(parser);
- SKIP(parser);
-
- end_mark = parser->mark;
-
- /* Create the DOCUMENT-START or DOCUMENT-END token. */
-
- TOKEN_INIT(token, type, start_mark, end_mark);
-
- /* Append the token to the queue. */
-
- if (!ENQUEUE(parser, parser->tokens, token))
- return 0;
-
- return 1;
-}
-
-/*
- * Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token.
- */
-
-static int
-yaml_parser_fetch_flow_collection_start(yaml_parser_t *parser,
- yaml_token_type_t type)
-{
- yaml_mark_t start_mark, end_mark;
- yaml_token_t token;
-
- /* The indicators '[' and '{' may start a simple key. */
-
- if (!yaml_parser_save_simple_key(parser))
- return 0;
-
- /* Increase the flow level. */
-
- if (!yaml_parser_increase_flow_level(parser))
- return 0;
-
- /* A simple key may follow the indicators '[' and '{'. */
-
- parser->simple_key_allowed = 1;
-
- /* Consume the token. */
-
- start_mark = parser->mark;
- SKIP(parser);
- end_mark = parser->mark;
-
- /* Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. */
-
- TOKEN_INIT(token, type, start_mark, end_mark);
-
- /* Append the token to the queue. */
-
- if (!ENQUEUE(parser, parser->tokens, token))
- return 0;
-
- return 1;
-}
-
-/*
- * Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token.
- */
-
-static int
-yaml_parser_fetch_flow_collection_end(yaml_parser_t *parser,
- yaml_token_type_t type)
-{
- yaml_mark_t start_mark, end_mark;
- yaml_token_t token;
-
- /* Reset any potential simple key on the current flow level. */
-
- if (!yaml_parser_remove_simple_key(parser))
- return 0;
-
- /* Decrease the flow level. */
-
- if (!yaml_parser_decrease_flow_level(parser))
- return 0;
-
- /* No simple keys after the indicators ']' and '}'. */
-
- parser->simple_key_allowed = 0;
-
- /* Consume the token. */
-
- start_mark = parser->mark;
- SKIP(parser);
- end_mark = parser->mark;
-
- /* Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. */
-
- TOKEN_INIT(token, type, start_mark, end_mark);
-
- /* Append the token to the queue. */
-
- if (!ENQUEUE(parser, parser->tokens, token))
- return 0;
-
- return 1;
-}
-
-/*
- * Produce the FLOW-ENTRY token.
- */
-
-static int
-yaml_parser_fetch_flow_entry(yaml_parser_t *parser)
-{
- yaml_mark_t start_mark, end_mark;
- yaml_token_t token;
-
- /* Reset any potential simple keys on the current flow level. */
-
- if (!yaml_parser_remove_simple_key(parser))
- return 0;
-
- /* Simple keys are allowed after ','. */
-
- parser->simple_key_allowed = 1;
-
- /* Consume the token. */
-
- start_mark = parser->mark;
- SKIP(parser);
- end_mark = parser->mark;
-
- /* Create the FLOW-ENTRY token and append it to the queue. */
-
- TOKEN_INIT(token, YAML_FLOW_ENTRY_TOKEN, start_mark, end_mark);
-
- if (!ENQUEUE(parser, parser->tokens, token))
- return 0;
-
- return 1;
-}
-
-/*
- * Produce the BLOCK-ENTRY token.
- */
-
-static int
-yaml_parser_fetch_block_entry(yaml_parser_t *parser)
-{
- yaml_mark_t start_mark, end_mark;
- yaml_token_t token;
-
- /* Check if the scanner is in the block context. */
-
- if (!parser->flow_level)
- {
- /* Check if we are allowed to start a new entry. */
-
- if (!parser->simple_key_allowed) {
- return yaml_parser_set_scanner_error(parser, NULL, parser->mark,
- "block sequence entries are not allowed in this context");
- }
-
- /* Add the BLOCK-SEQUENCE-START token if needed. */
-
- if (!yaml_parser_roll_indent(parser, parser->mark.column, -1,
- YAML_BLOCK_SEQUENCE_START_TOKEN, parser->mark))
- return 0;
- }
- else
- {
- /*
- * It is an error for the '-' indicator to occur in the flow context,
- * but we let the Parser detect and report about it because the Parser
- * is able to point to the context.
- */
- }
-
- /* Reset any potential simple keys on the current flow level. */
-
- if (!yaml_parser_remove_simple_key(parser))
- return 0;
-
- /* Simple keys are allowed after '-'. */
-
- parser->simple_key_allowed = 1;
-
- /* Consume the token. */
-
- start_mark = parser->mark;
- SKIP(parser);
- end_mark = parser->mark;
-
- /* Create the BLOCK-ENTRY token and append it to the queue. */
-
- TOKEN_INIT(token, YAML_BLOCK_ENTRY_TOKEN, start_mark, end_mark);
-
- if (!ENQUEUE(parser, parser->tokens, token))
- return 0;
-
- return 1;
-}
-
-/*
- * Produce the KEY token.
- */
-
-static int
-yaml_parser_fetch_key(yaml_parser_t *parser)
-{
- yaml_mark_t start_mark, end_mark;
- yaml_token_t token;
-
- /* In the block context, additional checks are required. */
-
- if (!parser->flow_level)
- {
+
+ while (parser->indent > column)
+ {
+ /* Create a token and append it to the queue. */
+
+ TOKEN_INIT(token, YAML_BLOCK_END_TOKEN, parser->mark, parser->mark);
+
+ if (!ENQUEUE(parser, parser->tokens, token))
+ return 0;
+
+ /* Pop the indentation level. */
+
+ parser->indent = POP(parser, parser->indents);
+ }
+
+ return 1;
+}
+
+/*
+ * Initialize the scanner and produce the STREAM-START token.
+ */
+
+static int
+yaml_parser_fetch_stream_start(yaml_parser_t *parser)
+{
+ yaml_simple_key_t simple_key = { 0, 0, 0, { 0, 0, 0 } };
+ yaml_token_t token;
+
+ /* Set the initial indentation. */
+
+ parser->indent = -1;
+
+ /* Initialize the simple key stack. */
+
+ if (!PUSH(parser, parser->simple_keys, simple_key))
+ return 0;
+
+ /* A simple key is allowed at the beginning of the stream. */
+
+ parser->simple_key_allowed = 1;
+
+ /* We have started. */
+
+ parser->stream_start_produced = 1;
+
+ /* Create the STREAM-START token and append it to the queue. */
+
+ STREAM_START_TOKEN_INIT(token, parser->encoding,
+ parser->mark, parser->mark);
+
+ if (!ENQUEUE(parser, parser->tokens, token))
+ return 0;
+
+ return 1;
+}
+
+/*
+ * Produce the STREAM-END token and shut down the scanner.
+ */
+
+static int
+yaml_parser_fetch_stream_end(yaml_parser_t *parser)
+{
+ yaml_token_t token;
+
+ /* Force new line. */
+
+ if (parser->mark.column != 0) {
+ parser->mark.column = 0;
+ parser->mark.line ++;
+ }
+
+ /* Reset the indentation level. */
+
+ if (!yaml_parser_unroll_indent(parser, -1))
+ return 0;
+
+ /* Reset simple keys. */
+
+ if (!yaml_parser_remove_simple_key(parser))
+ return 0;
+
+ parser->simple_key_allowed = 0;
+
+ /* Create the STREAM-END token and append it to the queue. */
+
+ STREAM_END_TOKEN_INIT(token, parser->mark, parser->mark);
+
+ if (!ENQUEUE(parser, parser->tokens, token))
+ return 0;
+
+ return 1;
+}
+
+/*
+ * Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token.
+ */
+
+static int
+yaml_parser_fetch_directive(yaml_parser_t *parser)
+{
+ yaml_token_t token;
+
+ /* Reset the indentation level. */
+
+ if (!yaml_parser_unroll_indent(parser, -1))
+ return 0;
+
+ /* Reset simple keys. */
+
+ if (!yaml_parser_remove_simple_key(parser))
+ return 0;
+
+ parser->simple_key_allowed = 0;
+
+ /* Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. */
+
+ if (!yaml_parser_scan_directive(parser, &token))
+ return 0;
+
+ /* Append the token to the queue. */
+
+ if (!ENQUEUE(parser, parser->tokens, token)) {
+ yaml_token_delete(&token);
+ return 0;
+ }
+
+ return 1;
+}
+
+/*
+ * Produce the DOCUMENT-START or DOCUMENT-END token.
+ */
+
+static int
+yaml_parser_fetch_document_indicator(yaml_parser_t *parser,
+ yaml_token_type_t type)
+{
+ yaml_mark_t start_mark, end_mark;
+ yaml_token_t token;
+
+ /* Reset the indentation level. */
+
+ if (!yaml_parser_unroll_indent(parser, -1))
+ return 0;
+
+ /* Reset simple keys. */
+
+ if (!yaml_parser_remove_simple_key(parser))
+ return 0;
+
+ parser->simple_key_allowed = 0;
+
+ /* Consume the token. */
+
+ start_mark = parser->mark;
+
+ SKIP(parser);
+ SKIP(parser);
+ SKIP(parser);
+
+ end_mark = parser->mark;
+
+ /* Create the DOCUMENT-START or DOCUMENT-END token. */
+
+ TOKEN_INIT(token, type, start_mark, end_mark);
+
+ /* Append the token to the queue. */
+
+ if (!ENQUEUE(parser, parser->tokens, token))
+ return 0;
+
+ return 1;
+}
+
+/*
+ * Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token.
+ */
+
+static int
+yaml_parser_fetch_flow_collection_start(yaml_parser_t *parser,
+ yaml_token_type_t type)
+{
+ yaml_mark_t start_mark, end_mark;
+ yaml_token_t token;
+
+ /* The indicators '[' and '{' may start a simple key. */
+
+ if (!yaml_parser_save_simple_key(parser))
+ return 0;
+
+ /* Increase the flow level. */
+
+ if (!yaml_parser_increase_flow_level(parser))
+ return 0;
+
+ /* A simple key may follow the indicators '[' and '{'. */
+
+ parser->simple_key_allowed = 1;
+
+ /* Consume the token. */
+
+ start_mark = parser->mark;
+ SKIP(parser);
+ end_mark = parser->mark;
+
+ /* Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. */
+
+ TOKEN_INIT(token, type, start_mark, end_mark);
+
+ /* Append the token to the queue. */
+
+ if (!ENQUEUE(parser, parser->tokens, token))
+ return 0;
+
+ return 1;
+}
+
+/*
+ * Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token.
+ */
+
+static int
+yaml_parser_fetch_flow_collection_end(yaml_parser_t *parser,
+ yaml_token_type_t type)
+{
+ yaml_mark_t start_mark, end_mark;
+ yaml_token_t token;
+
+ /* Reset any potential simple key on the current flow level. */
+
+ if (!yaml_parser_remove_simple_key(parser))
+ return 0;
+
+ /* Decrease the flow level. */
+
+ if (!yaml_parser_decrease_flow_level(parser))
+ return 0;
+
+ /* No simple keys after the indicators ']' and '}'. */
+
+ parser->simple_key_allowed = 0;
+
+ /* Consume the token. */
+
+ start_mark = parser->mark;
+ SKIP(parser);
+ end_mark = parser->mark;
+
+ /* Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. */
+
+ TOKEN_INIT(token, type, start_mark, end_mark);
+
+ /* Append the token to the queue. */
+
+ if (!ENQUEUE(parser, parser->tokens, token))
+ return 0;
+
+ return 1;
+}
+
+/*
+ * Produce the FLOW-ENTRY token.
+ */
+
+static int
+yaml_parser_fetch_flow_entry(yaml_parser_t *parser)
+{
+ yaml_mark_t start_mark, end_mark;
+ yaml_token_t token;
+
+ /* Reset any potential simple keys on the current flow level. */
+
+ if (!yaml_parser_remove_simple_key(parser))
+ return 0;
+
+ /* Simple keys are allowed after ','. */
+
+ parser->simple_key_allowed = 1;
+
+ /* Consume the token. */
+
+ start_mark = parser->mark;
+ SKIP(parser);
+ end_mark = parser->mark;
+
+ /* Create the FLOW-ENTRY token and append it to the queue. */
+
+ TOKEN_INIT(token, YAML_FLOW_ENTRY_TOKEN, start_mark, end_mark);
+
+ if (!ENQUEUE(parser, parser->tokens, token))
+ return 0;
+
+ return 1;
+}
+
+/*
+ * Produce the BLOCK-ENTRY token.
+ */
+
+static int
+yaml_parser_fetch_block_entry(yaml_parser_t *parser)
+{
+ yaml_mark_t start_mark, end_mark;
+ yaml_token_t token;
+
+ /* Check if the scanner is in the block context. */
+
+ if (!parser->flow_level)
+ {
+ /* Check if we are allowed to start a new entry. */
+
+ if (!parser->simple_key_allowed) {
+ return yaml_parser_set_scanner_error(parser, NULL, parser->mark,
+ "block sequence entries are not allowed in this context");
+ }
+
+ /* Add the BLOCK-SEQUENCE-START token if needed. */
+
+ if (!yaml_parser_roll_indent(parser, parser->mark.column, -1,
+ YAML_BLOCK_SEQUENCE_START_TOKEN, parser->mark))
+ return 0;
+ }
+ else
+ {
+ /*
+ * It is an error for the '-' indicator to occur in the flow context,
+ * but we let the Parser detect and report about it because the Parser
+ * is able to point to the context.
+ */
+ }
+
+ /* Reset any potential simple keys on the current flow level. */
+
+ if (!yaml_parser_remove_simple_key(parser))
+ return 0;
+
+ /* Simple keys are allowed after '-'. */
+
+ parser->simple_key_allowed = 1;
+
+ /* Consume the token. */
+
+ start_mark = parser->mark;
+ SKIP(parser);
+ end_mark = parser->mark;
+
+ /* Create the BLOCK-ENTRY token and append it to the queue. */
+
+ TOKEN_INIT(token, YAML_BLOCK_ENTRY_TOKEN, start_mark, end_mark);
+
+ if (!ENQUEUE(parser, parser->tokens, token))
+ return 0;
+
+ return 1;
+}
+
+/*
+ * Produce the KEY token.
+ */
+
+static int
+yaml_parser_fetch_key(yaml_parser_t *parser)
+{
+ yaml_mark_t start_mark, end_mark;
+ yaml_token_t token;
+
+ /* In the block context, additional checks are required. */
+
+ if (!parser->flow_level)
+ {
/* Check if we are allowed to start a new key (not necessary simple). */
-
- if (!parser->simple_key_allowed) {
- return yaml_parser_set_scanner_error(parser, NULL, parser->mark,
- "mapping keys are not allowed in this context");
- }
-
- /* Add the BLOCK-MAPPING-START token if needed. */
-
- if (!yaml_parser_roll_indent(parser, parser->mark.column, -1,
- YAML_BLOCK_MAPPING_START_TOKEN, parser->mark))
- return 0;
- }
-
- /* Reset any potential simple keys on the current flow level. */
-
- if (!yaml_parser_remove_simple_key(parser))
- return 0;
-
- /* Simple keys are allowed after '?' in the block context. */
-
- parser->simple_key_allowed = (!parser->flow_level);
-
- /* Consume the token. */
-
- start_mark = parser->mark;
- SKIP(parser);
- end_mark = parser->mark;
-
- /* Create the KEY token and append it to the queue. */
-
- TOKEN_INIT(token, YAML_KEY_TOKEN, start_mark, end_mark);
-
- if (!ENQUEUE(parser, parser->tokens, token))
- return 0;
-
- return 1;
-}
-
-/*
- * Produce the VALUE token.
- */
-
-static int
-yaml_parser_fetch_value(yaml_parser_t *parser)
-{
- yaml_mark_t start_mark, end_mark;
- yaml_token_t token;
- yaml_simple_key_t *simple_key = parser->simple_keys.top-1;
-
- /* Have we found a simple key? */
-
- if (simple_key->possible)
- {
-
- /* Create the KEY token and insert it into the queue. */
-
- TOKEN_INIT(token, YAML_KEY_TOKEN, simple_key->mark, simple_key->mark);
-
- if (!QUEUE_INSERT(parser, parser->tokens,
- simple_key->token_number - parser->tokens_parsed, token))
- return 0;
-
- /* In the block context, we may need to add the BLOCK-MAPPING-START token. */
-
- if (!yaml_parser_roll_indent(parser, simple_key->mark.column,
- simple_key->token_number,
- YAML_BLOCK_MAPPING_START_TOKEN, simple_key->mark))
- return 0;
-
- /* Remove the simple key. */
-
- simple_key->possible = 0;
-
- /* A simple key cannot follow another simple key. */
-
- parser->simple_key_allowed = 0;
- }
- else
- {
- /* The ':' indicator follows a complex key. */
-
- /* In the block context, extra checks are required. */
-
- if (!parser->flow_level)
- {
- /* Check if we are allowed to start a complex value. */
-
- if (!parser->simple_key_allowed) {
- return yaml_parser_set_scanner_error(parser, NULL, parser->mark,
- "mapping values are not allowed in this context");
- }
-
- /* Add the BLOCK-MAPPING-START token if needed. */
-
- if (!yaml_parser_roll_indent(parser, parser->mark.column, -1,
- YAML_BLOCK_MAPPING_START_TOKEN, parser->mark))
- return 0;
- }
-
- /* Simple keys after ':' are allowed in the block context. */
-
- parser->simple_key_allowed = (!parser->flow_level);
- }
-
- /* Consume the token. */
-
- start_mark = parser->mark;
- SKIP(parser);
- end_mark = parser->mark;
-
- /* Create the VALUE token and append it to the queue. */
-
- TOKEN_INIT(token, YAML_VALUE_TOKEN, start_mark, end_mark);
-
- if (!ENQUEUE(parser, parser->tokens, token))
- return 0;
-
- return 1;
-}
-
-/*
- * Produce the ALIAS or ANCHOR token.
- */
-
-static int
-yaml_parser_fetch_anchor(yaml_parser_t *parser, yaml_token_type_t type)
-{
- yaml_token_t token;
-
- /* An anchor or an alias could be a simple key. */
-
- if (!yaml_parser_save_simple_key(parser))
- return 0;
-
- /* A simple key cannot follow an anchor or an alias. */
-
- parser->simple_key_allowed = 0;
-
- /* Create the ALIAS or ANCHOR token and append it to the queue. */
-
- if (!yaml_parser_scan_anchor(parser, &token, type))
- return 0;
-
- if (!ENQUEUE(parser, parser->tokens, token)) {
- yaml_token_delete(&token);
- return 0;
- }
- return 1;
-}
-
-/*
- * Produce the TAG token.
- */
-
-static int
-yaml_parser_fetch_tag(yaml_parser_t *parser)
-{
- yaml_token_t token;
-
- /* A tag could be a simple key. */
-
- if (!yaml_parser_save_simple_key(parser))
- return 0;
-
- /* A simple key cannot follow a tag. */
-
- parser->simple_key_allowed = 0;
-
- /* Create the TAG token and append it to the queue. */
-
- if (!yaml_parser_scan_tag(parser, &token))
- return 0;
-
- if (!ENQUEUE(parser, parser->tokens, token)) {
- yaml_token_delete(&token);
- return 0;
- }
-
- return 1;
-}
-
-/*
- * Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens.
- */
-
-static int
-yaml_parser_fetch_block_scalar(yaml_parser_t *parser, int literal)
-{
- yaml_token_t token;
-
- /* Remove any potential simple keys. */
-
- if (!yaml_parser_remove_simple_key(parser))
- return 0;
-
- /* A simple key may follow a block scalar. */
-
- parser->simple_key_allowed = 1;
-
- /* Create the SCALAR token and append it to the queue. */
-
- if (!yaml_parser_scan_block_scalar(parser, &token, literal))
- return 0;
-
- if (!ENQUEUE(parser, parser->tokens, token)) {
- yaml_token_delete(&token);
- return 0;
- }
-
- return 1;
-}
-
-/*
- * Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens.
- */
-
-static int
-yaml_parser_fetch_flow_scalar(yaml_parser_t *parser, int single)
-{
- yaml_token_t token;
-
- /* A plain scalar could be a simple key. */
-
- if (!yaml_parser_save_simple_key(parser))
- return 0;
-
- /* A simple key cannot follow a flow scalar. */
-
- parser->simple_key_allowed = 0;
-
- /* Create the SCALAR token and append it to the queue. */
-
- if (!yaml_parser_scan_flow_scalar(parser, &token, single))
- return 0;
-
- if (!ENQUEUE(parser, parser->tokens, token)) {
- yaml_token_delete(&token);
- return 0;
- }
-
- return 1;
-}
-
-/*
- * Produce the SCALAR(...,plain) token.
- */
-
-static int
-yaml_parser_fetch_plain_scalar(yaml_parser_t *parser)
-{
- yaml_token_t token;
-
- /* A plain scalar could be a simple key. */
-
- if (!yaml_parser_save_simple_key(parser))
- return 0;
-
- /* A simple key cannot follow a flow scalar. */
-
- parser->simple_key_allowed = 0;
-
- /* Create the SCALAR token and append it to the queue. */
-
- if (!yaml_parser_scan_plain_scalar(parser, &token))
- return 0;
-
- if (!ENQUEUE(parser, parser->tokens, token)) {
- yaml_token_delete(&token);
- return 0;
- }
-
- return 1;
-}
-
-/*
- * Eat whitespaces and comments until the next token is found.
- */
-
-static int
-yaml_parser_scan_to_next_token(yaml_parser_t *parser)
-{
- /* Until the next token is not found. */
-
- while (1)
- {
- /* Allow the BOM mark to start a line. */
-
- if (!CACHE(parser, 1)) return 0;
-
- if (parser->mark.column == 0 && IS_BOM(parser->buffer))
- SKIP(parser);
-
- /*
- * Eat whitespaces.
- *
- * Tabs are allowed:
- *
- * - in the flow context;
- * - in the block context, but not at the beginning of the line or
+
+ if (!parser->simple_key_allowed) {
+ return yaml_parser_set_scanner_error(parser, NULL, parser->mark,
+ "mapping keys are not allowed in this context");
+ }
+
+ /* Add the BLOCK-MAPPING-START token if needed. */
+
+ if (!yaml_parser_roll_indent(parser, parser->mark.column, -1,
+ YAML_BLOCK_MAPPING_START_TOKEN, parser->mark))
+ return 0;
+ }
+
+ /* Reset any potential simple keys on the current flow level. */
+
+ if (!yaml_parser_remove_simple_key(parser))
+ return 0;
+
+ /* Simple keys are allowed after '?' in the block context. */
+
+ parser->simple_key_allowed = (!parser->flow_level);
+
+ /* Consume the token. */
+
+ start_mark = parser->mark;
+ SKIP(parser);
+ end_mark = parser->mark;
+
+ /* Create the KEY token and append it to the queue. */
+
+ TOKEN_INIT(token, YAML_KEY_TOKEN, start_mark, end_mark);
+
+ if (!ENQUEUE(parser, parser->tokens, token))
+ return 0;
+
+ return 1;
+}
+
+/*
+ * Produce the VALUE token.
+ */
+
+static int
+yaml_parser_fetch_value(yaml_parser_t *parser)
+{
+ yaml_mark_t start_mark, end_mark;
+ yaml_token_t token;
+ yaml_simple_key_t *simple_key = parser->simple_keys.top-1;
+
+ /* Have we found a simple key? */
+
+ if (simple_key->possible)
+ {
+
+ /* Create the KEY token and insert it into the queue. */
+
+ TOKEN_INIT(token, YAML_KEY_TOKEN, simple_key->mark, simple_key->mark);
+
+ if (!QUEUE_INSERT(parser, parser->tokens,
+ simple_key->token_number - parser->tokens_parsed, token))
+ return 0;
+
+ /* In the block context, we may need to add the BLOCK-MAPPING-START token. */
+
+ if (!yaml_parser_roll_indent(parser, simple_key->mark.column,
+ simple_key->token_number,
+ YAML_BLOCK_MAPPING_START_TOKEN, simple_key->mark))
+ return 0;
+
+ /* Remove the simple key. */
+
+ simple_key->possible = 0;
+
+ /* A simple key cannot follow another simple key. */
+
+ parser->simple_key_allowed = 0;
+ }
+ else
+ {
+ /* The ':' indicator follows a complex key. */
+
+ /* In the block context, extra checks are required. */
+
+ if (!parser->flow_level)
+ {
+ /* Check if we are allowed to start a complex value. */
+
+ if (!parser->simple_key_allowed) {
+ return yaml_parser_set_scanner_error(parser, NULL, parser->mark,
+ "mapping values are not allowed in this context");
+ }
+
+ /* Add the BLOCK-MAPPING-START token if needed. */
+
+ if (!yaml_parser_roll_indent(parser, parser->mark.column, -1,
+ YAML_BLOCK_MAPPING_START_TOKEN, parser->mark))
+ return 0;
+ }
+
+ /* Simple keys after ':' are allowed in the block context. */
+
+ parser->simple_key_allowed = (!parser->flow_level);
+ }
+
+ /* Consume the token. */
+
+ start_mark = parser->mark;
+ SKIP(parser);
+ end_mark = parser->mark;
+
+ /* Create the VALUE token and append it to the queue. */
+
+ TOKEN_INIT(token, YAML_VALUE_TOKEN, start_mark, end_mark);
+
+ if (!ENQUEUE(parser, parser->tokens, token))
+ return 0;
+
+ return 1;
+}
+
+/*
+ * Produce the ALIAS or ANCHOR token.
+ */
+
+static int
+yaml_parser_fetch_anchor(yaml_parser_t *parser, yaml_token_type_t type)
+{
+ yaml_token_t token;
+
+ /* An anchor or an alias could be a simple key. */
+
+ if (!yaml_parser_save_simple_key(parser))
+ return 0;
+
+ /* A simple key cannot follow an anchor or an alias. */
+
+ parser->simple_key_allowed = 0;
+
+ /* Create the ALIAS or ANCHOR token and append it to the queue. */
+
+ if (!yaml_parser_scan_anchor(parser, &token, type))
+ return 0;
+
+ if (!ENQUEUE(parser, parser->tokens, token)) {
+ yaml_token_delete(&token);
+ return 0;
+ }
+ return 1;
+}
+
+/*
+ * Produce the TAG token.
+ */
+
+static int
+yaml_parser_fetch_tag(yaml_parser_t *parser)
+{
+ yaml_token_t token;
+
+ /* A tag could be a simple key. */
+
+ if (!yaml_parser_save_simple_key(parser))
+ return 0;
+
+ /* A simple key cannot follow a tag. */
+
+ parser->simple_key_allowed = 0;
+
+ /* Create the TAG token and append it to the queue. */
+
+ if (!yaml_parser_scan_tag(parser, &token))
+ return 0;
+
+ if (!ENQUEUE(parser, parser->tokens, token)) {
+ yaml_token_delete(&token);
+ return 0;
+ }
+
+ return 1;
+}
+
+/*
+ * Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens.
+ */
+
+static int
+yaml_parser_fetch_block_scalar(yaml_parser_t *parser, int literal)
+{
+ yaml_token_t token;
+
+ /* Remove any potential simple keys. */
+
+ if (!yaml_parser_remove_simple_key(parser))
+ return 0;
+
+ /* A simple key may follow a block scalar. */
+
+ parser->simple_key_allowed = 1;
+
+ /* Create the SCALAR token and append it to the queue. */
+
+ if (!yaml_parser_scan_block_scalar(parser, &token, literal))
+ return 0;
+
+ if (!ENQUEUE(parser, parser->tokens, token)) {
+ yaml_token_delete(&token);
+ return 0;
+ }
+
+ return 1;
+}
+
+/*
+ * Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens.
+ */
+
+static int
+yaml_parser_fetch_flow_scalar(yaml_parser_t *parser, int single)
+{
+ yaml_token_t token;
+
+ /* A plain scalar could be a simple key. */
+
+ if (!yaml_parser_save_simple_key(parser))
+ return 0;
+
+ /* A simple key cannot follow a flow scalar. */
+
+ parser->simple_key_allowed = 0;
+
+ /* Create the SCALAR token and append it to the queue. */
+
+ if (!yaml_parser_scan_flow_scalar(parser, &token, single))
+ return 0;
+
+ if (!ENQUEUE(parser, parser->tokens, token)) {
+ yaml_token_delete(&token);
+ return 0;
+ }
+
+ return 1;
+}
+
+/*
+ * Produce the SCALAR(...,plain) token.
+ */
+
+static int
+yaml_parser_fetch_plain_scalar(yaml_parser_t *parser)
+{
+ yaml_token_t token;
+
+ /* A plain scalar could be a simple key. */
+
+ if (!yaml_parser_save_simple_key(parser))
+ return 0;
+
+ /* A simple key cannot follow a flow scalar. */
+
+ parser->simple_key_allowed = 0;
+
+ /* Create the SCALAR token and append it to the queue. */
+
+ if (!yaml_parser_scan_plain_scalar(parser, &token))
+ return 0;
+
+ if (!ENQUEUE(parser, parser->tokens, token)) {
+ yaml_token_delete(&token);
+ return 0;
+ }
+
+ return 1;
+}
+
+/*
+ * Eat whitespaces and comments until the next token is found.
+ */
+
+static int
+yaml_parser_scan_to_next_token(yaml_parser_t *parser)
+{
+ /* Until the next token is not found. */
+
+ while (1)
+ {
+ /* Allow the BOM mark to start a line. */
+
+ if (!CACHE(parser, 1)) return 0;
+
+ if (parser->mark.column == 0 && IS_BOM(parser->buffer))
+ SKIP(parser);
+
+ /*
+ * Eat whitespaces.
+ *
+ * Tabs are allowed:
+ *
+ * - in the flow context;
+ * - in the block context, but not at the beginning of the line or
* after '-', '?', or ':' (complex value).
- */
-
- if (!CACHE(parser, 1)) return 0;
-
- while (CHECK(parser->buffer,' ') ||
- ((parser->flow_level || !parser->simple_key_allowed) &&
- CHECK(parser->buffer, '\t'))) {
- SKIP(parser);
- if (!CACHE(parser, 1)) return 0;
- }
-
- /* Eat a comment until a line break. */
-
- if (CHECK(parser->buffer, '#')) {
- while (!IS_BREAKZ(parser->buffer)) {
- SKIP(parser);
- if (!CACHE(parser, 1)) return 0;
- }
- }
-
- /* If it is a line break, eat it. */
-
- if (IS_BREAK(parser->buffer))
- {
- if (!CACHE(parser, 2)) return 0;
- SKIP_LINE(parser);
-
- /* In the block context, a new line may start a simple key. */
-
- if (!parser->flow_level) {
- parser->simple_key_allowed = 1;
- }
- }
- else
- {
- /* We have found a token. */
-
- break;
- }
- }
-
- return 1;
-}
-
-/*
- * Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token.
- *
- * Scope:
- * %YAML 1.1 # a comment \n
- * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- * %TAG !yaml! tag:yaml.org,2002: \n
- * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- */
-
-int
-yaml_parser_scan_directive(yaml_parser_t *parser, yaml_token_t *token)
-{
- yaml_mark_t start_mark, end_mark;
- yaml_char_t *name = NULL;
- int major, minor;
- yaml_char_t *handle = NULL, *prefix = NULL;
-
- /* Eat '%'. */
-
- start_mark = parser->mark;
-
- SKIP(parser);
-
- /* Scan the directive name. */
-
- if (!yaml_parser_scan_directive_name(parser, start_mark, &name))
- goto error;
-
- /* Is it a YAML directive? */
-
- if (strcmp((char *)name, "YAML") == 0)
- {
- /* Scan the VERSION directive value. */
-
- if (!yaml_parser_scan_version_directive_value(parser, start_mark,
- &major, &minor))
- goto error;
-
- end_mark = parser->mark;
-
- /* Create a VERSION-DIRECTIVE token. */
-
- VERSION_DIRECTIVE_TOKEN_INIT(*token, major, minor,
- start_mark, end_mark);
- }
-
- /* Is it a TAG directive? */
-
- else if (strcmp((char *)name, "TAG") == 0)
- {
- /* Scan the TAG directive value. */
-
- if (!yaml_parser_scan_tag_directive_value(parser, start_mark,
- &handle, &prefix))
- goto error;
-
- end_mark = parser->mark;
-
- /* Create a TAG-DIRECTIVE token. */
-
- TAG_DIRECTIVE_TOKEN_INIT(*token, handle, prefix,
- start_mark, end_mark);
- }
-
- /* Unknown directive. */
-
- else
- {
- yaml_parser_set_scanner_error(parser, "while scanning a directive",
+ */
+
+ if (!CACHE(parser, 1)) return 0;
+
+ while (CHECK(parser->buffer,' ') ||
+ ((parser->flow_level || !parser->simple_key_allowed) &&
+ CHECK(parser->buffer, '\t'))) {
+ SKIP(parser);
+ if (!CACHE(parser, 1)) return 0;
+ }
+
+ /* Eat a comment until a line break. */
+
+ if (CHECK(parser->buffer, '#')) {
+ while (!IS_BREAKZ(parser->buffer)) {
+ SKIP(parser);
+ if (!CACHE(parser, 1)) return 0;
+ }
+ }
+
+ /* If it is a line break, eat it. */
+
+ if (IS_BREAK(parser->buffer))
+ {
+ if (!CACHE(parser, 2)) return 0;
+ SKIP_LINE(parser);
+
+ /* In the block context, a new line may start a simple key. */
+
+ if (!parser->flow_level) {
+ parser->simple_key_allowed = 1;
+ }
+ }
+ else
+ {
+ /* We have found a token. */
+
+ break;
+ }
+ }
+
+ return 1;
+}
+
+/*
+ * Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token.
+ *
+ * Scope:
+ * %YAML 1.1 # a comment \n
+ * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ * %TAG !yaml! tag:yaml.org,2002: \n
+ * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ */
+
+int
+yaml_parser_scan_directive(yaml_parser_t *parser, yaml_token_t *token)
+{
+ yaml_mark_t start_mark, end_mark;
+ yaml_char_t *name = NULL;
+ int major, minor;
+ yaml_char_t *handle = NULL, *prefix = NULL;
+
+ /* Eat '%'. */
+
+ start_mark = parser->mark;
+
+ SKIP(parser);
+
+ /* Scan the directive name. */
+
+ if (!yaml_parser_scan_directive_name(parser, start_mark, &name))
+ goto error;
+
+ /* Is it a YAML directive? */
+
+ if (strcmp((char *)name, "YAML") == 0)
+ {
+ /* Scan the VERSION directive value. */
+
+ if (!yaml_parser_scan_version_directive_value(parser, start_mark,
+ &major, &minor))
+ goto error;
+
+ end_mark = parser->mark;
+
+ /* Create a VERSION-DIRECTIVE token. */
+
+ VERSION_DIRECTIVE_TOKEN_INIT(*token, major, minor,
+ start_mark, end_mark);
+ }
+
+ /* Is it a TAG directive? */
+
+ else if (strcmp((char *)name, "TAG") == 0)
+ {
+ /* Scan the TAG directive value. */
+
+ if (!yaml_parser_scan_tag_directive_value(parser, start_mark,
+ &handle, &prefix))
+ goto error;
+
+ end_mark = parser->mark;
+
+ /* Create a TAG-DIRECTIVE token. */
+
+ TAG_DIRECTIVE_TOKEN_INIT(*token, handle, prefix,
+ start_mark, end_mark);
+ }
+
+ /* Unknown directive. */
+
+ else
+ {
+ yaml_parser_set_scanner_error(parser, "while scanning a directive",
start_mark, "found unknown directive name");
- goto error;
- }
-
- /* Eat the rest of the line including any comments. */
-
- if (!CACHE(parser, 1)) goto error;
-
- while (IS_BLANK(parser->buffer)) {
- SKIP(parser);
- if (!CACHE(parser, 1)) goto error;
- }
-
- if (CHECK(parser->buffer, '#')) {
- while (!IS_BREAKZ(parser->buffer)) {
- SKIP(parser);
- if (!CACHE(parser, 1)) goto error;
- }
- }
-
- /* Check if we are at the end of the line. */
-
- if (!IS_BREAKZ(parser->buffer)) {
- yaml_parser_set_scanner_error(parser, "while scanning a directive",
- start_mark, "did not find expected comment or line break");
- goto error;
- }
-
- /* Eat a line break. */
-
- if (IS_BREAK(parser->buffer)) {
- if (!CACHE(parser, 2)) goto error;
- SKIP_LINE(parser);
- }
-
- yaml_free(name);
-
- return 1;
-
-error:
- yaml_free(prefix);
- yaml_free(handle);
- yaml_free(name);
- return 0;
-}
-
-/*
- * Scan the directive name.
- *
- * Scope:
- * %YAML 1.1 # a comment \n
- * ^^^^
- * %TAG !yaml! tag:yaml.org,2002: \n
- * ^^^
- */
-
-static int
-yaml_parser_scan_directive_name(yaml_parser_t *parser,
- yaml_mark_t start_mark, yaml_char_t **name)
-{
- yaml_string_t string = NULL_STRING;
-
- if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
-
- /* Consume the directive name. */
-
- if (!CACHE(parser, 1)) goto error;
-
- while (IS_ALPHA(parser->buffer))
- {
- if (!READ(parser, string)) goto error;
- if (!CACHE(parser, 1)) goto error;
- }
-
- /* Check if the name is empty. */
-
- if (string.start == string.pointer) {
- yaml_parser_set_scanner_error(parser, "while scanning a directive",
- start_mark, "could not find expected directive name");
- goto error;
- }
-
- /* Check for an blank character after the name. */
-
- if (!IS_BLANKZ(parser->buffer)) {
- yaml_parser_set_scanner_error(parser, "while scanning a directive",
- start_mark, "found unexpected non-alphabetical character");
- goto error;
- }
-
- *name = string.start;
-
- return 1;
-
-error:
- STRING_DEL(parser, string);
- return 0;
-}
-
-/*
- * Scan the value of VERSION-DIRECTIVE.
- *
- * Scope:
- * %YAML 1.1 # a comment \n
- * ^^^^^^
- */
-
-static int
-yaml_parser_scan_version_directive_value(yaml_parser_t *parser,
- yaml_mark_t start_mark, int *major, int *minor)
-{
- /* Eat whitespaces. */
-
- if (!CACHE(parser, 1)) return 0;
-
- while (IS_BLANK(parser->buffer)) {
- SKIP(parser);
- if (!CACHE(parser, 1)) return 0;
- }
-
- /* Consume the major version number. */
-
- if (!yaml_parser_scan_version_directive_number(parser, start_mark, major))
- return 0;
-
- /* Eat '.'. */
-
- if (!CHECK(parser->buffer, '.')) {
- return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
- start_mark, "did not find expected digit or '.' character");
- }
-
- SKIP(parser);
-
- /* Consume the minor version number. */
-
- if (!yaml_parser_scan_version_directive_number(parser, start_mark, minor))
- return 0;
-
- return 1;
-}
-
-#define MAX_NUMBER_LENGTH 9
-
-/*
- * Scan the version number of VERSION-DIRECTIVE.
- *
- * Scope:
- * %YAML 1.1 # a comment \n
- * ^
- * %YAML 1.1 # a comment \n
- * ^
- */
-
-static int
-yaml_parser_scan_version_directive_number(yaml_parser_t *parser,
- yaml_mark_t start_mark, int *number)
-{
- int value = 0;
- size_t length = 0;
-
- /* Repeat while the next character is digit. */
-
- if (!CACHE(parser, 1)) return 0;
-
- while (IS_DIGIT(parser->buffer))
- {
- /* Check if the number is too long. */
-
- if (++length > MAX_NUMBER_LENGTH) {
- return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
- start_mark, "found extremely long version number");
- }
-
- value = value*10 + AS_DIGIT(parser->buffer);
-
- SKIP(parser);
-
- if (!CACHE(parser, 1)) return 0;
- }
-
- /* Check if the number was present. */
-
- if (!length) {
- return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
- start_mark, "did not find expected version number");
- }
-
- *number = value;
-
- return 1;
-}
-
-/*
- * Scan the value of a TAG-DIRECTIVE token.
- *
- * Scope:
- * %TAG !yaml! tag:yaml.org,2002: \n
- * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- */
-
-static int
-yaml_parser_scan_tag_directive_value(yaml_parser_t *parser,
- yaml_mark_t start_mark, yaml_char_t **handle, yaml_char_t **prefix)
-{
- yaml_char_t *handle_value = NULL;
- yaml_char_t *prefix_value = NULL;
-
- /* Eat whitespaces. */
-
- if (!CACHE(parser, 1)) goto error;
-
- while (IS_BLANK(parser->buffer)) {
- SKIP(parser);
- if (!CACHE(parser, 1)) goto error;
- }
-
- /* Scan a handle. */
-
- if (!yaml_parser_scan_tag_handle(parser, 1, start_mark, &handle_value))
- goto error;
-
- /* Expect a whitespace. */
-
- if (!CACHE(parser, 1)) goto error;
-
- if (!IS_BLANK(parser->buffer)) {
- yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive",
- start_mark, "did not find expected whitespace");
- goto error;
- }
-
- /* Eat whitespaces. */
-
- while (IS_BLANK(parser->buffer)) {
- SKIP(parser);
- if (!CACHE(parser, 1)) goto error;
- }
-
- /* Scan a prefix. */
-
+ goto error;
+ }
+
+ /* Eat the rest of the line including any comments. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ while (IS_BLANK(parser->buffer)) {
+ SKIP(parser);
+ if (!CACHE(parser, 1)) goto error;
+ }
+
+ if (CHECK(parser->buffer, '#')) {
+ while (!IS_BREAKZ(parser->buffer)) {
+ SKIP(parser);
+ if (!CACHE(parser, 1)) goto error;
+ }
+ }
+
+ /* Check if we are at the end of the line. */
+
+ if (!IS_BREAKZ(parser->buffer)) {
+ yaml_parser_set_scanner_error(parser, "while scanning a directive",
+ start_mark, "did not find expected comment or line break");
+ goto error;
+ }
+
+ /* Eat a line break. */
+
+ if (IS_BREAK(parser->buffer)) {
+ if (!CACHE(parser, 2)) goto error;
+ SKIP_LINE(parser);
+ }
+
+ yaml_free(name);
+
+ return 1;
+
+error:
+ yaml_free(prefix);
+ yaml_free(handle);
+ yaml_free(name);
+ return 0;
+}
+
+/*
+ * Scan the directive name.
+ *
+ * Scope:
+ * %YAML 1.1 # a comment \n
+ * ^^^^
+ * %TAG !yaml! tag:yaml.org,2002: \n
+ * ^^^
+ */
+
+static int
+yaml_parser_scan_directive_name(yaml_parser_t *parser,
+ yaml_mark_t start_mark, yaml_char_t **name)
+{
+ yaml_string_t string = NULL_STRING;
+
+ if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
+
+ /* Consume the directive name. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ while (IS_ALPHA(parser->buffer))
+ {
+ if (!READ(parser, string)) goto error;
+ if (!CACHE(parser, 1)) goto error;
+ }
+
+ /* Check if the name is empty. */
+
+ if (string.start == string.pointer) {
+ yaml_parser_set_scanner_error(parser, "while scanning a directive",
+ start_mark, "could not find expected directive name");
+ goto error;
+ }
+
+ /* Check for an blank character after the name. */
+
+ if (!IS_BLANKZ(parser->buffer)) {
+ yaml_parser_set_scanner_error(parser, "while scanning a directive",
+ start_mark, "found unexpected non-alphabetical character");
+ goto error;
+ }
+
+ *name = string.start;
+
+ return 1;
+
+error:
+ STRING_DEL(parser, string);
+ return 0;
+}
+
+/*
+ * Scan the value of VERSION-DIRECTIVE.
+ *
+ * Scope:
+ * %YAML 1.1 # a comment \n
+ * ^^^^^^
+ */
+
+static int
+yaml_parser_scan_version_directive_value(yaml_parser_t *parser,
+ yaml_mark_t start_mark, int *major, int *minor)
+{
+ /* Eat whitespaces. */
+
+ if (!CACHE(parser, 1)) return 0;
+
+ while (IS_BLANK(parser->buffer)) {
+ SKIP(parser);
+ if (!CACHE(parser, 1)) return 0;
+ }
+
+ /* Consume the major version number. */
+
+ if (!yaml_parser_scan_version_directive_number(parser, start_mark, major))
+ return 0;
+
+ /* Eat '.'. */
+
+ if (!CHECK(parser->buffer, '.')) {
+ return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
+ start_mark, "did not find expected digit or '.' character");
+ }
+
+ SKIP(parser);
+
+ /* Consume the minor version number. */
+
+ if (!yaml_parser_scan_version_directive_number(parser, start_mark, minor))
+ return 0;
+
+ return 1;
+}
+
+#define MAX_NUMBER_LENGTH 9
+
+/*
+ * Scan the version number of VERSION-DIRECTIVE.
+ *
+ * Scope:
+ * %YAML 1.1 # a comment \n
+ * ^
+ * %YAML 1.1 # a comment \n
+ * ^
+ */
+
+static int
+yaml_parser_scan_version_directive_number(yaml_parser_t *parser,
+ yaml_mark_t start_mark, int *number)
+{
+ int value = 0;
+ size_t length = 0;
+
+ /* Repeat while the next character is digit. */
+
+ if (!CACHE(parser, 1)) return 0;
+
+ while (IS_DIGIT(parser->buffer))
+ {
+ /* Check if the number is too long. */
+
+ if (++length > MAX_NUMBER_LENGTH) {
+ return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
+ start_mark, "found extremely long version number");
+ }
+
+ value = value*10 + AS_DIGIT(parser->buffer);
+
+ SKIP(parser);
+
+ if (!CACHE(parser, 1)) return 0;
+ }
+
+ /* Check if the number was present. */
+
+ if (!length) {
+ return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
+ start_mark, "did not find expected version number");
+ }
+
+ *number = value;
+
+ return 1;
+}
+
+/*
+ * Scan the value of a TAG-DIRECTIVE token.
+ *
+ * Scope:
+ * %TAG !yaml! tag:yaml.org,2002: \n
+ * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ */
+
+static int
+yaml_parser_scan_tag_directive_value(yaml_parser_t *parser,
+ yaml_mark_t start_mark, yaml_char_t **handle, yaml_char_t **prefix)
+{
+ yaml_char_t *handle_value = NULL;
+ yaml_char_t *prefix_value = NULL;
+
+ /* Eat whitespaces. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ while (IS_BLANK(parser->buffer)) {
+ SKIP(parser);
+ if (!CACHE(parser, 1)) goto error;
+ }
+
+ /* Scan a handle. */
+
+ if (!yaml_parser_scan_tag_handle(parser, 1, start_mark, &handle_value))
+ goto error;
+
+ /* Expect a whitespace. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ if (!IS_BLANK(parser->buffer)) {
+ yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive",
+ start_mark, "did not find expected whitespace");
+ goto error;
+ }
+
+ /* Eat whitespaces. */
+
+ while (IS_BLANK(parser->buffer)) {
+ SKIP(parser);
+ if (!CACHE(parser, 1)) goto error;
+ }
+
+ /* Scan a prefix. */
+
if (!yaml_parser_scan_tag_uri(parser, 1, 1, NULL, start_mark, &prefix_value))
- goto error;
-
- /* Expect a whitespace or line break. */
-
- if (!CACHE(parser, 1)) goto error;
-
- if (!IS_BLANKZ(parser->buffer)) {
- yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive",
- start_mark, "did not find expected whitespace or line break");
- goto error;
- }
-
- *handle = handle_value;
- *prefix = prefix_value;
-
- return 1;
-
-error:
- yaml_free(handle_value);
- yaml_free(prefix_value);
- return 0;
-}
-
-static int
-yaml_parser_scan_anchor(yaml_parser_t *parser, yaml_token_t *token,
- yaml_token_type_t type)
-{
- int length = 0;
- yaml_mark_t start_mark, end_mark;
- yaml_string_t string = NULL_STRING;
-
- if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
-
- /* Eat the indicator character. */
-
- start_mark = parser->mark;
-
- SKIP(parser);
-
- /* Consume the value. */
-
- if (!CACHE(parser, 1)) goto error;
-
- while (IS_ALPHA(parser->buffer)) {
- if (!READ(parser, string)) goto error;
- if (!CACHE(parser, 1)) goto error;
- length ++;
- }
-
- end_mark = parser->mark;
-
- /*
- * Check if length of the anchor is greater than 0 and it is followed by
- * a whitespace character or one of the indicators:
- *
- * '?', ':', ',', ']', '}', '%', '@', '`'.
- */
-
- if (!length || !(IS_BLANKZ(parser->buffer) || CHECK(parser->buffer, '?')
- || CHECK(parser->buffer, ':') || CHECK(parser->buffer, ',')
- || CHECK(parser->buffer, ']') || CHECK(parser->buffer, '}')
- || CHECK(parser->buffer, '%') || CHECK(parser->buffer, '@')
- || CHECK(parser->buffer, '`'))) {
- yaml_parser_set_scanner_error(parser, type == YAML_ANCHOR_TOKEN ?
- "while scanning an anchor" : "while scanning an alias", start_mark,
- "did not find expected alphabetic or numeric character");
- goto error;
- }
-
- /* Create a token. */
-
- if (type == YAML_ANCHOR_TOKEN) {
- ANCHOR_TOKEN_INIT(*token, string.start, start_mark, end_mark);
- }
- else {
- ALIAS_TOKEN_INIT(*token, string.start, start_mark, end_mark);
- }
-
- return 1;
-
-error:
- STRING_DEL(parser, string);
- return 0;
-}
-
-/*
- * Scan a TAG token.
- */
-
-static int
-yaml_parser_scan_tag(yaml_parser_t *parser, yaml_token_t *token)
-{
- yaml_char_t *handle = NULL;
- yaml_char_t *suffix = NULL;
- yaml_mark_t start_mark, end_mark;
-
- start_mark = parser->mark;
-
- /* Check if the tag is in the canonical form. */
-
- if (!CACHE(parser, 2)) goto error;
-
- if (CHECK_AT(parser->buffer, '<', 1))
- {
- /* Set the handle to '' */
-
+ goto error;
+
+ /* Expect a whitespace or line break. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ if (!IS_BLANKZ(parser->buffer)) {
+ yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive",
+ start_mark, "did not find expected whitespace or line break");
+ goto error;
+ }
+
+ *handle = handle_value;
+ *prefix = prefix_value;
+
+ return 1;
+
+error:
+ yaml_free(handle_value);
+ yaml_free(prefix_value);
+ return 0;
+}
+
+static int
+yaml_parser_scan_anchor(yaml_parser_t *parser, yaml_token_t *token,
+ yaml_token_type_t type)
+{
+ int length = 0;
+ yaml_mark_t start_mark, end_mark;
+ yaml_string_t string = NULL_STRING;
+
+ if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
+
+ /* Eat the indicator character. */
+
+ start_mark = parser->mark;
+
+ SKIP(parser);
+
+ /* Consume the value. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ while (IS_ALPHA(parser->buffer)) {
+ if (!READ(parser, string)) goto error;
+ if (!CACHE(parser, 1)) goto error;
+ length ++;
+ }
+
+ end_mark = parser->mark;
+
+ /*
+ * Check if length of the anchor is greater than 0 and it is followed by
+ * a whitespace character or one of the indicators:
+ *
+ * '?', ':', ',', ']', '}', '%', '@', '`'.
+ */
+
+ if (!length || !(IS_BLANKZ(parser->buffer) || CHECK(parser->buffer, '?')
+ || CHECK(parser->buffer, ':') || CHECK(parser->buffer, ',')
+ || CHECK(parser->buffer, ']') || CHECK(parser->buffer, '}')
+ || CHECK(parser->buffer, '%') || CHECK(parser->buffer, '@')
+ || CHECK(parser->buffer, '`'))) {
+ yaml_parser_set_scanner_error(parser, type == YAML_ANCHOR_TOKEN ?
+ "while scanning an anchor" : "while scanning an alias", start_mark,
+ "did not find expected alphabetic or numeric character");
+ goto error;
+ }
+
+ /* Create a token. */
+
+ if (type == YAML_ANCHOR_TOKEN) {
+ ANCHOR_TOKEN_INIT(*token, string.start, start_mark, end_mark);
+ }
+ else {
+ ALIAS_TOKEN_INIT(*token, string.start, start_mark, end_mark);
+ }
+
+ return 1;
+
+error:
+ STRING_DEL(parser, string);
+ return 0;
+}
+
+/*
+ * Scan a TAG token.
+ */
+
+static int
+yaml_parser_scan_tag(yaml_parser_t *parser, yaml_token_t *token)
+{
+ yaml_char_t *handle = NULL;
+ yaml_char_t *suffix = NULL;
+ yaml_mark_t start_mark, end_mark;
+
+ start_mark = parser->mark;
+
+ /* Check if the tag is in the canonical form. */
+
+ if (!CACHE(parser, 2)) goto error;
+
+ if (CHECK_AT(parser->buffer, '<', 1))
+ {
+ /* Set the handle to '' */
+
handle = YAML_MALLOC(1);
- if (!handle) goto error;
- handle[0] = '\0';
-
- /* Eat '!<' */
-
- SKIP(parser);
- SKIP(parser);
-
- /* Consume the tag value. */
-
+ if (!handle) goto error;
+ handle[0] = '\0';
+
+ /* Eat '!<' */
+
+ SKIP(parser);
+ SKIP(parser);
+
+ /* Consume the tag value. */
+
if (!yaml_parser_scan_tag_uri(parser, 1, 0, NULL, start_mark, &suffix))
- goto error;
-
- /* Check for '>' and eat it. */
-
- if (!CHECK(parser->buffer, '>')) {
- yaml_parser_set_scanner_error(parser, "while scanning a tag",
- start_mark, "did not find the expected '>'");
- goto error;
- }
-
- SKIP(parser);
- }
- else
- {
- /* The tag has either the '!suffix' or the '!handle!suffix' form. */
-
- /* First, try to scan a handle. */
-
- if (!yaml_parser_scan_tag_handle(parser, 0, start_mark, &handle))
- goto error;
-
- /* Check if it is, indeed, handle. */
-
- if (handle[0] == '!' && handle[1] != '\0' && handle[strlen((char *)handle)-1] == '!')
- {
- /* Scan the suffix now. */
-
+ goto error;
+
+ /* Check for '>' and eat it. */
+
+ if (!CHECK(parser->buffer, '>')) {
+ yaml_parser_set_scanner_error(parser, "while scanning a tag",
+ start_mark, "did not find the expected '>'");
+ goto error;
+ }
+
+ SKIP(parser);
+ }
+ else
+ {
+ /* The tag has either the '!suffix' or the '!handle!suffix' form. */
+
+ /* First, try to scan a handle. */
+
+ if (!yaml_parser_scan_tag_handle(parser, 0, start_mark, &handle))
+ goto error;
+
+ /* Check if it is, indeed, handle. */
+
+ if (handle[0] == '!' && handle[1] != '\0' && handle[strlen((char *)handle)-1] == '!')
+ {
+ /* Scan the suffix now. */
+
if (!yaml_parser_scan_tag_uri(parser, 0, 0, NULL, start_mark, &suffix))
- goto error;
- }
- else
- {
- /* It wasn't a handle after all. Scan the rest of the tag. */
-
+ goto error;
+ }
+ else
+ {
+ /* It wasn't a handle after all. Scan the rest of the tag. */
+
if (!yaml_parser_scan_tag_uri(parser, 0, 0, handle, start_mark, &suffix))
- goto error;
-
- /* Set the handle to '!'. */
-
- yaml_free(handle);
+ goto error;
+
+ /* Set the handle to '!'. */
+
+ yaml_free(handle);
handle = YAML_MALLOC(2);
- if (!handle) goto error;
- handle[0] = '!';
- handle[1] = '\0';
-
- /*
- * A special case: the '!' tag. Set the handle to '' and the
- * suffix to '!'.
- */
-
- if (suffix[0] == '\0') {
- yaml_char_t *tmp = handle;
- handle = suffix;
- suffix = tmp;
- }
- }
- }
-
- /* Check the character which ends the tag. */
-
- if (!CACHE(parser, 1)) goto error;
-
- if (!IS_BLANKZ(parser->buffer)) {
+ if (!handle) goto error;
+ handle[0] = '!';
+ handle[1] = '\0';
+
+ /*
+ * A special case: the '!' tag. Set the handle to '' and the
+ * suffix to '!'.
+ */
+
+ if (suffix[0] == '\0') {
+ yaml_char_t *tmp = handle;
+ handle = suffix;
+ suffix = tmp;
+ }
+ }
+ }
+
+ /* Check the character which ends the tag. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ if (!IS_BLANKZ(parser->buffer)) {
if (!parser->flow_level || !CHECK(parser->buffer, ',') ) {
yaml_parser_set_scanner_error(parser, "while scanning a tag",
start_mark, "did not find expected whitespace or line break");
goto error;
}
- }
-
- end_mark = parser->mark;
-
- /* Create a token. */
-
- TAG_TOKEN_INIT(*token, handle, suffix, start_mark, end_mark);
-
- return 1;
-
-error:
- yaml_free(handle);
- yaml_free(suffix);
- return 0;
-}
-
-/*
- * Scan a tag handle.
- */
-
-static int
-yaml_parser_scan_tag_handle(yaml_parser_t *parser, int directive,
- yaml_mark_t start_mark, yaml_char_t **handle)
-{
- yaml_string_t string = NULL_STRING;
-
- if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
-
- /* Check the initial '!' character. */
-
- if (!CACHE(parser, 1)) goto error;
-
- if (!CHECK(parser->buffer, '!')) {
- yaml_parser_set_scanner_error(parser, directive ?
- "while scanning a tag directive" : "while scanning a tag",
- start_mark, "did not find expected '!'");
- goto error;
- }
-
- /* Copy the '!' character. */
-
- if (!READ(parser, string)) goto error;
-
- /* Copy all subsequent alphabetical and numerical characters. */
-
- if (!CACHE(parser, 1)) goto error;
-
- while (IS_ALPHA(parser->buffer))
- {
- if (!READ(parser, string)) goto error;
- if (!CACHE(parser, 1)) goto error;
- }
-
- /* Check if the trailing character is '!' and copy it. */
-
- if (CHECK(parser->buffer, '!'))
- {
- if (!READ(parser, string)) goto error;
- }
- else
- {
- /*
- * It's either the '!' tag or not really a tag handle. If it's a %TAG
- * directive, it's an error. If it's a tag token, it must be a part of
- * URI.
- */
-
- if (directive && !(string.start[0] == '!' && string.start[1] == '\0')) {
- yaml_parser_set_scanner_error(parser, "while parsing a tag directive",
- start_mark, "did not find expected '!'");
- goto error;
- }
- }
-
- *handle = string.start;
-
- return 1;
-
-error:
- STRING_DEL(parser, string);
- return 0;
-}
-
-/*
- * Scan a tag.
- */
-
-static int
+ }
+
+ end_mark = parser->mark;
+
+ /* Create a token. */
+
+ TAG_TOKEN_INIT(*token, handle, suffix, start_mark, end_mark);
+
+ return 1;
+
+error:
+ yaml_free(handle);
+ yaml_free(suffix);
+ return 0;
+}
+
+/*
+ * Scan a tag handle.
+ */
+
+static int
+yaml_parser_scan_tag_handle(yaml_parser_t *parser, int directive,
+ yaml_mark_t start_mark, yaml_char_t **handle)
+{
+ yaml_string_t string = NULL_STRING;
+
+ if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
+
+ /* Check the initial '!' character. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ if (!CHECK(parser->buffer, '!')) {
+ yaml_parser_set_scanner_error(parser, directive ?
+ "while scanning a tag directive" : "while scanning a tag",
+ start_mark, "did not find expected '!'");
+ goto error;
+ }
+
+ /* Copy the '!' character. */
+
+ if (!READ(parser, string)) goto error;
+
+ /* Copy all subsequent alphabetical and numerical characters. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ while (IS_ALPHA(parser->buffer))
+ {
+ if (!READ(parser, string)) goto error;
+ if (!CACHE(parser, 1)) goto error;
+ }
+
+ /* Check if the trailing character is '!' and copy it. */
+
+ if (CHECK(parser->buffer, '!'))
+ {
+ if (!READ(parser, string)) goto error;
+ }
+ else
+ {
+ /*
+ * It's either the '!' tag or not really a tag handle. If it's a %TAG
+ * directive, it's an error. If it's a tag token, it must be a part of
+ * URI.
+ */
+
+ if (directive && !(string.start[0] == '!' && string.start[1] == '\0')) {
+ yaml_parser_set_scanner_error(parser, "while parsing a tag directive",
+ start_mark, "did not find expected '!'");
+ goto error;
+ }
+ }
+
+ *handle = string.start;
+
+ return 1;
+
+error:
+ STRING_DEL(parser, string);
+ return 0;
+}
+
+/*
+ * Scan a tag.
+ */
+
+static int
yaml_parser_scan_tag_uri(yaml_parser_t *parser, int uri_char, int directive,
- yaml_char_t *head, yaml_mark_t start_mark, yaml_char_t **uri)
-{
- size_t length = head ? strlen((char *)head) : 0;
- yaml_string_t string = NULL_STRING;
-
- if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
-
- /* Resize the string to include the head. */
-
- while ((size_t)(string.end - string.start) <= length) {
- if (!yaml_string_extend(&string.start, &string.pointer, &string.end)) {
- parser->error = YAML_MEMORY_ERROR;
- goto error;
- }
- }
-
- /*
- * Copy the head if needed.
- *
- * Note that we don't copy the leading '!' character.
- */
-
- if (length > 1) {
- memcpy(string.start, head+1, length-1);
- string.pointer += length-1;
- }
-
- /* Scan the tag. */
-
- if (!CACHE(parser, 1)) goto error;
-
- /*
- * The set of characters that may appear in URI is as follows:
- *
- * '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&',
+ yaml_char_t *head, yaml_mark_t start_mark, yaml_char_t **uri)
+{
+ size_t length = head ? strlen((char *)head) : 0;
+ yaml_string_t string = NULL_STRING;
+
+ if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
+
+ /* Resize the string to include the head. */
+
+ while ((size_t)(string.end - string.start) <= length) {
+ if (!yaml_string_extend(&string.start, &string.pointer, &string.end)) {
+ parser->error = YAML_MEMORY_ERROR;
+ goto error;
+ }
+ }
+
+ /*
+ * Copy the head if needed.
+ *
+ * Note that we don't copy the leading '!' character.
+ */
+
+ if (length > 1) {
+ memcpy(string.start, head+1, length-1);
+ string.pointer += length-1;
+ }
+
+ /* Scan the tag. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ /*
+ * The set of characters that may appear in URI is as follows:
+ *
+ * '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&',
* '=', '+', '$', '.', '!', '~', '*', '\'', '(', ')', '%'.
*
* If we are inside a verbatim tag <...> (parameter uri_char is true)
* then also the following flow indicators are allowed:
* ',', '[', ']'
- */
-
- while (IS_ALPHA(parser->buffer) || CHECK(parser->buffer, ';')
- || CHECK(parser->buffer, '/') || CHECK(parser->buffer, '?')
- || CHECK(parser->buffer, ':') || CHECK(parser->buffer, '@')
- || CHECK(parser->buffer, '&') || CHECK(parser->buffer, '=')
- || CHECK(parser->buffer, '+') || CHECK(parser->buffer, '$')
+ */
+
+ while (IS_ALPHA(parser->buffer) || CHECK(parser->buffer, ';')
+ || CHECK(parser->buffer, '/') || CHECK(parser->buffer, '?')
+ || CHECK(parser->buffer, ':') || CHECK(parser->buffer, '@')
+ || CHECK(parser->buffer, '&') || CHECK(parser->buffer, '=')
+ || CHECK(parser->buffer, '+') || CHECK(parser->buffer, '$')
|| CHECK(parser->buffer, '.') || CHECK(parser->buffer, '%')
- || CHECK(parser->buffer, '!') || CHECK(parser->buffer, '~')
- || CHECK(parser->buffer, '*') || CHECK(parser->buffer, '\'')
- || CHECK(parser->buffer, '(') || CHECK(parser->buffer, ')')
+ || CHECK(parser->buffer, '!') || CHECK(parser->buffer, '~')
+ || CHECK(parser->buffer, '*') || CHECK(parser->buffer, '\'')
+ || CHECK(parser->buffer, '(') || CHECK(parser->buffer, ')')
|| (uri_char && (
CHECK(parser->buffer, ',')
|| CHECK(parser->buffer, '[') || CHECK(parser->buffer, ']')
)
))
- {
- /* Check if it is a URI-escape sequence. */
-
- if (CHECK(parser->buffer, '%')) {
+ {
+ /* Check if it is a URI-escape sequence. */
+
+ if (CHECK(parser->buffer, '%')) {
if (!STRING_EXTEND(parser, string))
goto error;
- if (!yaml_parser_scan_uri_escapes(parser,
- directive, start_mark, &string)) goto error;
- }
- else {
- if (!READ(parser, string)) goto error;
- }
-
- length ++;
- if (!CACHE(parser, 1)) goto error;
- }
-
- /* Check if the tag is non-empty. */
-
- if (!length) {
- if (!STRING_EXTEND(parser, string))
- goto error;
-
- yaml_parser_set_scanner_error(parser, directive ?
- "while parsing a %TAG directive" : "while parsing a tag",
- start_mark, "did not find expected tag URI");
- goto error;
- }
-
- *uri = string.start;
-
- return 1;
-
-error:
- STRING_DEL(parser, string);
- return 0;
-}
-
-/*
- * Decode an URI-escape sequence corresponding to a single UTF-8 character.
- */
-
-static int
-yaml_parser_scan_uri_escapes(yaml_parser_t *parser, int directive,
- yaml_mark_t start_mark, yaml_string_t *string)
-{
- int width = 0;
-
- /* Decode the required number of characters. */
-
- do {
-
- unsigned char octet = 0;
-
- /* Check for a URI-escaped octet. */
-
- if (!CACHE(parser, 3)) return 0;
-
- if (!(CHECK(parser->buffer, '%')
- && IS_HEX_AT(parser->buffer, 1)
- && IS_HEX_AT(parser->buffer, 2))) {
- return yaml_parser_set_scanner_error(parser, directive ?
- "while parsing a %TAG directive" : "while parsing a tag",
- start_mark, "did not find URI escaped octet");
- }
-
- /* Get the octet. */
-
- octet = (AS_HEX_AT(parser->buffer, 1) << 4) + AS_HEX_AT(parser->buffer, 2);
-
- /* If it is the leading octet, determine the length of the UTF-8 sequence. */
-
- if (!width)
- {
- width = (octet & 0x80) == 0x00 ? 1 :
- (octet & 0xE0) == 0xC0 ? 2 :
- (octet & 0xF0) == 0xE0 ? 3 :
- (octet & 0xF8) == 0xF0 ? 4 : 0;
- if (!width) {
- return yaml_parser_set_scanner_error(parser, directive ?
- "while parsing a %TAG directive" : "while parsing a tag",
- start_mark, "found an incorrect leading UTF-8 octet");
- }
- }
- else
- {
- /* Check if the trailing octet is correct. */
-
- if ((octet & 0xC0) != 0x80) {
- return yaml_parser_set_scanner_error(parser, directive ?
- "while parsing a %TAG directive" : "while parsing a tag",
- start_mark, "found an incorrect trailing UTF-8 octet");
- }
- }
-
- /* Copy the octet and move the pointers. */
-
- *(string->pointer++) = octet;
- SKIP(parser);
- SKIP(parser);
- SKIP(parser);
-
- } while (--width);
-
- return 1;
-}
-
-/*
- * Scan a block scalar.
- */
-
-static int
-yaml_parser_scan_block_scalar(yaml_parser_t *parser, yaml_token_t *token,
- int literal)
-{
- yaml_mark_t start_mark;
- yaml_mark_t end_mark;
- yaml_string_t string = NULL_STRING;
- yaml_string_t leading_break = NULL_STRING;
- yaml_string_t trailing_breaks = NULL_STRING;
- int chomping = 0;
- int increment = 0;
- int indent = 0;
- int leading_blank = 0;
- int trailing_blank = 0;
-
- if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
- if (!STRING_INIT(parser, leading_break, INITIAL_STRING_SIZE)) goto error;
- if (!STRING_INIT(parser, trailing_breaks, INITIAL_STRING_SIZE)) goto error;
-
- /* Eat the indicator '|' or '>'. */
-
- start_mark = parser->mark;
-
- SKIP(parser);
-
- /* Scan the additional block scalar indicators. */
-
- if (!CACHE(parser, 1)) goto error;
-
- /* Check for a chomping indicator. */
-
- if (CHECK(parser->buffer, '+') || CHECK(parser->buffer, '-'))
- {
- /* Set the chomping method and eat the indicator. */
-
- chomping = CHECK(parser->buffer, '+') ? +1 : -1;
-
- SKIP(parser);
-
- /* Check for an indentation indicator. */
-
- if (!CACHE(parser, 1)) goto error;
-
- if (IS_DIGIT(parser->buffer))
- {
+ if (!yaml_parser_scan_uri_escapes(parser,
+ directive, start_mark, &string)) goto error;
+ }
+ else {
+ if (!READ(parser, string)) goto error;
+ }
+
+ length ++;
+ if (!CACHE(parser, 1)) goto error;
+ }
+
+ /* Check if the tag is non-empty. */
+
+ if (!length) {
+ if (!STRING_EXTEND(parser, string))
+ goto error;
+
+ yaml_parser_set_scanner_error(parser, directive ?
+ "while parsing a %TAG directive" : "while parsing a tag",
+ start_mark, "did not find expected tag URI");
+ goto error;
+ }
+
+ *uri = string.start;
+
+ return 1;
+
+error:
+ STRING_DEL(parser, string);
+ return 0;
+}
+
+/*
+ * Decode an URI-escape sequence corresponding to a single UTF-8 character.
+ */
+
+static int
+yaml_parser_scan_uri_escapes(yaml_parser_t *parser, int directive,
+ yaml_mark_t start_mark, yaml_string_t *string)
+{
+ int width = 0;
+
+ /* Decode the required number of characters. */
+
+ do {
+
+ unsigned char octet = 0;
+
+ /* Check for a URI-escaped octet. */
+
+ if (!CACHE(parser, 3)) return 0;
+
+ if (!(CHECK(parser->buffer, '%')
+ && IS_HEX_AT(parser->buffer, 1)
+ && IS_HEX_AT(parser->buffer, 2))) {
+ return yaml_parser_set_scanner_error(parser, directive ?
+ "while parsing a %TAG directive" : "while parsing a tag",
+ start_mark, "did not find URI escaped octet");
+ }
+
+ /* Get the octet. */
+
+ octet = (AS_HEX_AT(parser->buffer, 1) << 4) + AS_HEX_AT(parser->buffer, 2);
+
+ /* If it is the leading octet, determine the length of the UTF-8 sequence. */
+
+ if (!width)
+ {
+ width = (octet & 0x80) == 0x00 ? 1 :
+ (octet & 0xE0) == 0xC0 ? 2 :
+ (octet & 0xF0) == 0xE0 ? 3 :
+ (octet & 0xF8) == 0xF0 ? 4 : 0;
+ if (!width) {
+ return yaml_parser_set_scanner_error(parser, directive ?
+ "while parsing a %TAG directive" : "while parsing a tag",
+ start_mark, "found an incorrect leading UTF-8 octet");
+ }
+ }
+ else
+ {
+ /* Check if the trailing octet is correct. */
+
+ if ((octet & 0xC0) != 0x80) {
+ return yaml_parser_set_scanner_error(parser, directive ?
+ "while parsing a %TAG directive" : "while parsing a tag",
+ start_mark, "found an incorrect trailing UTF-8 octet");
+ }
+ }
+
+ /* Copy the octet and move the pointers. */
+
+ *(string->pointer++) = octet;
+ SKIP(parser);
+ SKIP(parser);
+ SKIP(parser);
+
+ } while (--width);
+
+ return 1;
+}
+
+/*
+ * Scan a block scalar.
+ */
+
+static int
+yaml_parser_scan_block_scalar(yaml_parser_t *parser, yaml_token_t *token,
+ int literal)
+{
+ yaml_mark_t start_mark;
+ yaml_mark_t end_mark;
+ yaml_string_t string = NULL_STRING;
+ yaml_string_t leading_break = NULL_STRING;
+ yaml_string_t trailing_breaks = NULL_STRING;
+ int chomping = 0;
+ int increment = 0;
+ int indent = 0;
+ int leading_blank = 0;
+ int trailing_blank = 0;
+
+ if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
+ if (!STRING_INIT(parser, leading_break, INITIAL_STRING_SIZE)) goto error;
+ if (!STRING_INIT(parser, trailing_breaks, INITIAL_STRING_SIZE)) goto error;
+
+ /* Eat the indicator '|' or '>'. */
+
+ start_mark = parser->mark;
+
+ SKIP(parser);
+
+ /* Scan the additional block scalar indicators. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ /* Check for a chomping indicator. */
+
+ if (CHECK(parser->buffer, '+') || CHECK(parser->buffer, '-'))
+ {
+ /* Set the chomping method and eat the indicator. */
+
+ chomping = CHECK(parser->buffer, '+') ? +1 : -1;
+
+ SKIP(parser);
+
+ /* Check for an indentation indicator. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ if (IS_DIGIT(parser->buffer))
+ {
/* Check that the indentation is greater than 0. */
-
- if (CHECK(parser->buffer, '0')) {
- yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
+
+ if (CHECK(parser->buffer, '0')) {
+ yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
start_mark, "found an indentation indicator equal to 0");
- goto error;
- }
-
+ goto error;
+ }
+
/* Get the indentation level and eat the indicator. */
-
- increment = AS_DIGIT(parser->buffer);
-
- SKIP(parser);
- }
- }
-
- /* Do the same as above, but in the opposite order. */
-
- else if (IS_DIGIT(parser->buffer))
- {
- if (CHECK(parser->buffer, '0')) {
- yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
+
+ increment = AS_DIGIT(parser->buffer);
+
+ SKIP(parser);
+ }
+ }
+
+ /* Do the same as above, but in the opposite order. */
+
+ else if (IS_DIGIT(parser->buffer))
+ {
+ if (CHECK(parser->buffer, '0')) {
+ yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
start_mark, "found an indentation indicator equal to 0");
- goto error;
- }
-
- increment = AS_DIGIT(parser->buffer);
-
- SKIP(parser);
-
- if (!CACHE(parser, 1)) goto error;
-
- if (CHECK(parser->buffer, '+') || CHECK(parser->buffer, '-')) {
- chomping = CHECK(parser->buffer, '+') ? +1 : -1;
-
- SKIP(parser);
- }
- }
-
- /* Eat whitespaces and comments to the end of the line. */
-
- if (!CACHE(parser, 1)) goto error;
-
- while (IS_BLANK(parser->buffer)) {
- SKIP(parser);
- if (!CACHE(parser, 1)) goto error;
- }
-
- if (CHECK(parser->buffer, '#')) {
- while (!IS_BREAKZ(parser->buffer)) {
- SKIP(parser);
- if (!CACHE(parser, 1)) goto error;
- }
- }
-
- /* Check if we are at the end of the line. */
-
- if (!IS_BREAKZ(parser->buffer)) {
- yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
- start_mark, "did not find expected comment or line break");
- goto error;
- }
-
- /* Eat a line break. */
-
- if (IS_BREAK(parser->buffer)) {
- if (!CACHE(parser, 2)) goto error;
- SKIP_LINE(parser);
- }
-
- end_mark = parser->mark;
-
+ goto error;
+ }
+
+ increment = AS_DIGIT(parser->buffer);
+
+ SKIP(parser);
+
+ if (!CACHE(parser, 1)) goto error;
+
+ if (CHECK(parser->buffer, '+') || CHECK(parser->buffer, '-')) {
+ chomping = CHECK(parser->buffer, '+') ? +1 : -1;
+
+ SKIP(parser);
+ }
+ }
+
+ /* Eat whitespaces and comments to the end of the line. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ while (IS_BLANK(parser->buffer)) {
+ SKIP(parser);
+ if (!CACHE(parser, 1)) goto error;
+ }
+
+ if (CHECK(parser->buffer, '#')) {
+ while (!IS_BREAKZ(parser->buffer)) {
+ SKIP(parser);
+ if (!CACHE(parser, 1)) goto error;
+ }
+ }
+
+ /* Check if we are at the end of the line. */
+
+ if (!IS_BREAKZ(parser->buffer)) {
+ yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
+ start_mark, "did not find expected comment or line break");
+ goto error;
+ }
+
+ /* Eat a line break. */
+
+ if (IS_BREAK(parser->buffer)) {
+ if (!CACHE(parser, 2)) goto error;
+ SKIP_LINE(parser);
+ }
+
+ end_mark = parser->mark;
+
/* Set the indentation level if it was specified. */
-
- if (increment) {
- indent = parser->indent >= 0 ? parser->indent+increment : increment;
- }
-
- /* Scan the leading line breaks and determine the indentation level if needed. */
-
- if (!yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks,
- start_mark, &end_mark)) goto error;
-
- /* Scan the block scalar content. */
-
- if (!CACHE(parser, 1)) goto error;
-
+
+ if (increment) {
+ indent = parser->indent >= 0 ? parser->indent+increment : increment;
+ }
+
+ /* Scan the leading line breaks and determine the indentation level if needed. */
+
+ if (!yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks,
+ start_mark, &end_mark)) goto error;
+
+ /* Scan the block scalar content. */
+
+ if (!CACHE(parser, 1)) goto error;
+
while ((int)parser->mark.column == indent && !(IS_Z(parser->buffer)))
- {
- /*
- * We are at the beginning of a non-empty line.
- */
-
- /* Is it a trailing whitespace? */
-
- trailing_blank = IS_BLANK(parser->buffer);
-
- /* Check if we need to fold the leading line break. */
-
- if (!literal && (*leading_break.start == '\n')
- && !leading_blank && !trailing_blank)
- {
- /* Do we need to join the lines by space? */
-
- if (*trailing_breaks.start == '\0') {
- if (!STRING_EXTEND(parser, string)) goto error;
- *(string.pointer ++) = ' ';
- }
-
- CLEAR(parser, leading_break);
- }
- else {
- if (!JOIN(parser, string, leading_break)) goto error;
- CLEAR(parser, leading_break);
- }
-
- /* Append the remaining line breaks. */
-
- if (!JOIN(parser, string, trailing_breaks)) goto error;
- CLEAR(parser, trailing_breaks);
-
- /* Is it a leading whitespace? */
-
- leading_blank = IS_BLANK(parser->buffer);
-
- /* Consume the current line. */
-
- while (!IS_BREAKZ(parser->buffer)) {
- if (!READ(parser, string)) goto error;
- if (!CACHE(parser, 1)) goto error;
- }
-
- /* Consume the line break. */
-
- if (!CACHE(parser, 2)) goto error;
-
- if (!READ_LINE(parser, leading_break)) goto error;
-
+ {
+ /*
+ * We are at the beginning of a non-empty line.
+ */
+
+ /* Is it a trailing whitespace? */
+
+ trailing_blank = IS_BLANK(parser->buffer);
+
+ /* Check if we need to fold the leading line break. */
+
+ if (!literal && (*leading_break.start == '\n')
+ && !leading_blank && !trailing_blank)
+ {
+ /* Do we need to join the lines by space? */
+
+ if (*trailing_breaks.start == '\0') {
+ if (!STRING_EXTEND(parser, string)) goto error;
+ *(string.pointer ++) = ' ';
+ }
+
+ CLEAR(parser, leading_break);
+ }
+ else {
+ if (!JOIN(parser, string, leading_break)) goto error;
+ CLEAR(parser, leading_break);
+ }
+
+ /* Append the remaining line breaks. */
+
+ if (!JOIN(parser, string, trailing_breaks)) goto error;
+ CLEAR(parser, trailing_breaks);
+
+ /* Is it a leading whitespace? */
+
+ leading_blank = IS_BLANK(parser->buffer);
+
+ /* Consume the current line. */
+
+ while (!IS_BREAKZ(parser->buffer)) {
+ if (!READ(parser, string)) goto error;
+ if (!CACHE(parser, 1)) goto error;
+ }
+
+ /* Consume the line break. */
+
+ if (!CACHE(parser, 2)) goto error;
+
+ if (!READ_LINE(parser, leading_break)) goto error;
+
/* Eat the following indentation spaces and line breaks. */
-
- if (!yaml_parser_scan_block_scalar_breaks(parser,
- &indent, &trailing_breaks, start_mark, &end_mark)) goto error;
- }
-
- /* Chomp the tail. */
-
- if (chomping != -1) {
- if (!JOIN(parser, string, leading_break)) goto error;
- }
- if (chomping == 1) {
- if (!JOIN(parser, string, trailing_breaks)) goto error;
- }
-
- /* Create a token. */
-
- SCALAR_TOKEN_INIT(*token, string.start, string.pointer-string.start,
- literal ? YAML_LITERAL_SCALAR_STYLE : YAML_FOLDED_SCALAR_STYLE,
- start_mark, end_mark);
-
- STRING_DEL(parser, leading_break);
- STRING_DEL(parser, trailing_breaks);
-
- return 1;
-
-error:
- STRING_DEL(parser, string);
- STRING_DEL(parser, leading_break);
- STRING_DEL(parser, trailing_breaks);
-
- return 0;
-}
-
-/*
+
+ if (!yaml_parser_scan_block_scalar_breaks(parser,
+ &indent, &trailing_breaks, start_mark, &end_mark)) goto error;
+ }
+
+ /* Chomp the tail. */
+
+ if (chomping != -1) {
+ if (!JOIN(parser, string, leading_break)) goto error;
+ }
+ if (chomping == 1) {
+ if (!JOIN(parser, string, trailing_breaks)) goto error;
+ }
+
+ /* Create a token. */
+
+ SCALAR_TOKEN_INIT(*token, string.start, string.pointer-string.start,
+ literal ? YAML_LITERAL_SCALAR_STYLE : YAML_FOLDED_SCALAR_STYLE,
+ start_mark, end_mark);
+
+ STRING_DEL(parser, leading_break);
+ STRING_DEL(parser, trailing_breaks);
+
+ return 1;
+
+error:
+ STRING_DEL(parser, string);
+ STRING_DEL(parser, leading_break);
+ STRING_DEL(parser, trailing_breaks);
+
+ return 0;
+}
+
+/*
* Scan indentation spaces and line breaks for a block scalar. Determine the
* indentation level if needed.
- */
-
-static int
-yaml_parser_scan_block_scalar_breaks(yaml_parser_t *parser,
- int *indent, yaml_string_t *breaks,
- yaml_mark_t start_mark, yaml_mark_t *end_mark)
-{
- int max_indent = 0;
-
- *end_mark = parser->mark;
-
+ */
+
+static int
+yaml_parser_scan_block_scalar_breaks(yaml_parser_t *parser,
+ int *indent, yaml_string_t *breaks,
+ yaml_mark_t start_mark, yaml_mark_t *end_mark)
+{
+ int max_indent = 0;
+
+ *end_mark = parser->mark;
+
/* Eat the indentation spaces and line breaks. */
-
- while (1)
- {
+
+ while (1)
+ {
/* Eat the indentation spaces. */
-
- if (!CACHE(parser, 1)) return 0;
-
- while ((!*indent || (int)parser->mark.column < *indent)
- && IS_SPACE(parser->buffer)) {
- SKIP(parser);
- if (!CACHE(parser, 1)) return 0;
- }
-
- if ((int)parser->mark.column > max_indent)
- max_indent = (int)parser->mark.column;
-
+
+ if (!CACHE(parser, 1)) return 0;
+
+ while ((!*indent || (int)parser->mark.column < *indent)
+ && IS_SPACE(parser->buffer)) {
+ SKIP(parser);
+ if (!CACHE(parser, 1)) return 0;
+ }
+
+ if ((int)parser->mark.column > max_indent)
+ max_indent = (int)parser->mark.column;
+
/* Check for a tab character messing the indentation. */
-
- if ((!*indent || (int)parser->mark.column < *indent)
- && IS_TAB(parser->buffer)) {
- return yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
+
+ if ((!*indent || (int)parser->mark.column < *indent)
+ && IS_TAB(parser->buffer)) {
+ return yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
start_mark, "found a tab character where an indentation space is expected");
- }
-
- /* Have we found a non-empty line? */
-
- if (!IS_BREAK(parser->buffer)) break;
-
- /* Consume the line break. */
-
- if (!CACHE(parser, 2)) return 0;
- if (!READ_LINE(parser, *breaks)) return 0;
- *end_mark = parser->mark;
- }
-
- /* Determine the indentation level if needed. */
-
- if (!*indent) {
- *indent = max_indent;
- if (*indent < parser->indent + 1)
- *indent = parser->indent + 1;
- if (*indent < 1)
- *indent = 1;
- }
-
+ }
+
+ /* Have we found a non-empty line? */
+
+ if (!IS_BREAK(parser->buffer)) break;
+
+ /* Consume the line break. */
+
+ if (!CACHE(parser, 2)) return 0;
+ if (!READ_LINE(parser, *breaks)) return 0;
+ *end_mark = parser->mark;
+ }
+
+ /* Determine the indentation level if needed. */
+
+ if (!*indent) {
+ *indent = max_indent;
+ if (*indent < parser->indent + 1)
+ *indent = parser->indent + 1;
+ if (*indent < 1)
+ *indent = 1;
+ }
+
return 1;
-}
-
-/*
- * Scan a quoted scalar.
- */
-
-static int
-yaml_parser_scan_flow_scalar(yaml_parser_t *parser, yaml_token_t *token,
- int single)
-{
- yaml_mark_t start_mark;
- yaml_mark_t end_mark;
- yaml_string_t string = NULL_STRING;
- yaml_string_t leading_break = NULL_STRING;
- yaml_string_t trailing_breaks = NULL_STRING;
- yaml_string_t whitespaces = NULL_STRING;
- int leading_blanks;
-
- if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
- if (!STRING_INIT(parser, leading_break, INITIAL_STRING_SIZE)) goto error;
- if (!STRING_INIT(parser, trailing_breaks, INITIAL_STRING_SIZE)) goto error;
- if (!STRING_INIT(parser, whitespaces, INITIAL_STRING_SIZE)) goto error;
-
- /* Eat the left quote. */
-
- start_mark = parser->mark;
-
- SKIP(parser);
-
- /* Consume the content of the quoted scalar. */
-
- while (1)
- {
- /* Check that there are no document indicators at the beginning of the line. */
-
- if (!CACHE(parser, 4)) goto error;
-
- if (parser->mark.column == 0 &&
- ((CHECK_AT(parser->buffer, '-', 0) &&
- CHECK_AT(parser->buffer, '-', 1) &&
- CHECK_AT(parser->buffer, '-', 2)) ||
- (CHECK_AT(parser->buffer, '.', 0) &&
- CHECK_AT(parser->buffer, '.', 1) &&
- CHECK_AT(parser->buffer, '.', 2))) &&
- IS_BLANKZ_AT(parser->buffer, 3))
- {
- yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar",
- start_mark, "found unexpected document indicator");
- goto error;
- }
-
- /* Check for EOF. */
-
- if (IS_Z(parser->buffer)) {
- yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar",
- start_mark, "found unexpected end of stream");
- goto error;
- }
-
- /* Consume non-blank characters. */
-
- if (!CACHE(parser, 2)) goto error;
-
- leading_blanks = 0;
-
- while (!IS_BLANKZ(parser->buffer))
- {
- /* Check for an escaped single quote. */
-
- if (single && CHECK_AT(parser->buffer, '\'', 0)
- && CHECK_AT(parser->buffer, '\'', 1))
- {
- if (!STRING_EXTEND(parser, string)) goto error;
- *(string.pointer++) = '\'';
- SKIP(parser);
- SKIP(parser);
- }
-
- /* Check for the right quote. */
-
- else if (CHECK(parser->buffer, single ? '\'' : '"'))
- {
- break;
- }
-
- /* Check for an escaped line break. */
-
- else if (!single && CHECK(parser->buffer, '\\')
- && IS_BREAK_AT(parser->buffer, 1))
- {
- if (!CACHE(parser, 3)) goto error;
- SKIP(parser);
- SKIP_LINE(parser);
- leading_blanks = 1;
- break;
- }
-
- /* Check for an escape sequence. */
-
- else if (!single && CHECK(parser->buffer, '\\'))
- {
- size_t code_length = 0;
-
- if (!STRING_EXTEND(parser, string)) goto error;
-
- /* Check the escape character. */
-
- switch (parser->buffer.pointer[1])
- {
- case '0':
- *(string.pointer++) = '\0';
- break;
-
- case 'a':
- *(string.pointer++) = '\x07';
- break;
-
- case 'b':
- *(string.pointer++) = '\x08';
- break;
-
- case 't':
- case '\t':
- *(string.pointer++) = '\x09';
- break;
-
- case 'n':
- *(string.pointer++) = '\x0A';
- break;
-
- case 'v':
- *(string.pointer++) = '\x0B';
- break;
-
- case 'f':
- *(string.pointer++) = '\x0C';
- break;
-
- case 'r':
- *(string.pointer++) = '\x0D';
- break;
-
- case 'e':
- *(string.pointer++) = '\x1B';
- break;
-
- case ' ':
- *(string.pointer++) = '\x20';
- break;
-
- case '"':
- *(string.pointer++) = '"';
- break;
-
+}
+
+/*
+ * Scan a quoted scalar.
+ */
+
+static int
+yaml_parser_scan_flow_scalar(yaml_parser_t *parser, yaml_token_t *token,
+ int single)
+{
+ yaml_mark_t start_mark;
+ yaml_mark_t end_mark;
+ yaml_string_t string = NULL_STRING;
+ yaml_string_t leading_break = NULL_STRING;
+ yaml_string_t trailing_breaks = NULL_STRING;
+ yaml_string_t whitespaces = NULL_STRING;
+ int leading_blanks;
+
+ if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
+ if (!STRING_INIT(parser, leading_break, INITIAL_STRING_SIZE)) goto error;
+ if (!STRING_INIT(parser, trailing_breaks, INITIAL_STRING_SIZE)) goto error;
+ if (!STRING_INIT(parser, whitespaces, INITIAL_STRING_SIZE)) goto error;
+
+ /* Eat the left quote. */
+
+ start_mark = parser->mark;
+
+ SKIP(parser);
+
+ /* Consume the content of the quoted scalar. */
+
+ while (1)
+ {
+ /* Check that there are no document indicators at the beginning of the line. */
+
+ if (!CACHE(parser, 4)) goto error;
+
+ if (parser->mark.column == 0 &&
+ ((CHECK_AT(parser->buffer, '-', 0) &&
+ CHECK_AT(parser->buffer, '-', 1) &&
+ CHECK_AT(parser->buffer, '-', 2)) ||
+ (CHECK_AT(parser->buffer, '.', 0) &&
+ CHECK_AT(parser->buffer, '.', 1) &&
+ CHECK_AT(parser->buffer, '.', 2))) &&
+ IS_BLANKZ_AT(parser->buffer, 3))
+ {
+ yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar",
+ start_mark, "found unexpected document indicator");
+ goto error;
+ }
+
+ /* Check for EOF. */
+
+ if (IS_Z(parser->buffer)) {
+ yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar",
+ start_mark, "found unexpected end of stream");
+ goto error;
+ }
+
+ /* Consume non-blank characters. */
+
+ if (!CACHE(parser, 2)) goto error;
+
+ leading_blanks = 0;
+
+ while (!IS_BLANKZ(parser->buffer))
+ {
+ /* Check for an escaped single quote. */
+
+ if (single && CHECK_AT(parser->buffer, '\'', 0)
+ && CHECK_AT(parser->buffer, '\'', 1))
+ {
+ if (!STRING_EXTEND(parser, string)) goto error;
+ *(string.pointer++) = '\'';
+ SKIP(parser);
+ SKIP(parser);
+ }
+
+ /* Check for the right quote. */
+
+ else if (CHECK(parser->buffer, single ? '\'' : '"'))
+ {
+ break;
+ }
+
+ /* Check for an escaped line break. */
+
+ else if (!single && CHECK(parser->buffer, '\\')
+ && IS_BREAK_AT(parser->buffer, 1))
+ {
+ if (!CACHE(parser, 3)) goto error;
+ SKIP(parser);
+ SKIP_LINE(parser);
+ leading_blanks = 1;
+ break;
+ }
+
+ /* Check for an escape sequence. */
+
+ else if (!single && CHECK(parser->buffer, '\\'))
+ {
+ size_t code_length = 0;
+
+ if (!STRING_EXTEND(parser, string)) goto error;
+
+ /* Check the escape character. */
+
+ switch (parser->buffer.pointer[1])
+ {
+ case '0':
+ *(string.pointer++) = '\0';
+ break;
+
+ case 'a':
+ *(string.pointer++) = '\x07';
+ break;
+
+ case 'b':
+ *(string.pointer++) = '\x08';
+ break;
+
+ case 't':
+ case '\t':
+ *(string.pointer++) = '\x09';
+ break;
+
+ case 'n':
+ *(string.pointer++) = '\x0A';
+ break;
+
+ case 'v':
+ *(string.pointer++) = '\x0B';
+ break;
+
+ case 'f':
+ *(string.pointer++) = '\x0C';
+ break;
+
+ case 'r':
+ *(string.pointer++) = '\x0D';
+ break;
+
+ case 'e':
+ *(string.pointer++) = '\x1B';
+ break;
+
+ case ' ':
+ *(string.pointer++) = '\x20';
+ break;
+
+ case '"':
+ *(string.pointer++) = '"';
+ break;
+
case '/':
*(string.pointer++) = '/';
- break;
-
- case '\\':
- *(string.pointer++) = '\\';
- break;
-
- case 'N': /* NEL (#x85) */
- *(string.pointer++) = '\xC2';
- *(string.pointer++) = '\x85';
- break;
-
- case '_': /* #xA0 */
- *(string.pointer++) = '\xC2';
- *(string.pointer++) = '\xA0';
- break;
-
- case 'L': /* LS (#x2028) */
- *(string.pointer++) = '\xE2';
- *(string.pointer++) = '\x80';
- *(string.pointer++) = '\xA8';
- break;
-
- case 'P': /* PS (#x2029) */
- *(string.pointer++) = '\xE2';
- *(string.pointer++) = '\x80';
- *(string.pointer++) = '\xA9';
- break;
-
- case 'x':
- code_length = 2;
- break;
-
- case 'u':
- code_length = 4;
- break;
-
- case 'U':
- code_length = 8;
- break;
-
- default:
- yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
- start_mark, "found unknown escape character");
- goto error;
- }
-
- SKIP(parser);
- SKIP(parser);
-
- /* Consume an arbitrary escape code. */
-
- if (code_length)
- {
- unsigned int value = 0;
- size_t k;
-
- /* Scan the character value. */
-
- if (!CACHE(parser, code_length)) goto error;
-
- for (k = 0; k < code_length; k ++) {
- if (!IS_HEX_AT(parser->buffer, k)) {
- yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
- start_mark, "did not find expected hexdecimal number");
- goto error;
- }
- value = (value << 4) + AS_HEX_AT(parser->buffer, k);
- }
-
- /* Check the value and write the character. */
-
- if ((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) {
- yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
- start_mark, "found invalid Unicode character escape code");
- goto error;
- }
-
- if (value <= 0x7F) {
- *(string.pointer++) = value;
- }
- else if (value <= 0x7FF) {
- *(string.pointer++) = 0xC0 + (value >> 6);
- *(string.pointer++) = 0x80 + (value & 0x3F);
- }
- else if (value <= 0xFFFF) {
- *(string.pointer++) = 0xE0 + (value >> 12);
- *(string.pointer++) = 0x80 + ((value >> 6) & 0x3F);
- *(string.pointer++) = 0x80 + (value & 0x3F);
- }
- else {
- *(string.pointer++) = 0xF0 + (value >> 18);
- *(string.pointer++) = 0x80 + ((value >> 12) & 0x3F);
- *(string.pointer++) = 0x80 + ((value >> 6) & 0x3F);
- *(string.pointer++) = 0x80 + (value & 0x3F);
- }
-
- /* Advance the pointer. */
-
- for (k = 0; k < code_length; k ++) {
- SKIP(parser);
- }
- }
- }
-
- else
- {
- /* It is a non-escaped non-blank character. */
-
- if (!READ(parser, string)) goto error;
- }
-
- if (!CACHE(parser, 2)) goto error;
- }
-
- /* Check if we are at the end of the scalar. */
-
+ break;
+
+ case '\\':
+ *(string.pointer++) = '\\';
+ break;
+
+ case 'N': /* NEL (#x85) */
+ *(string.pointer++) = '\xC2';
+ *(string.pointer++) = '\x85';
+ break;
+
+ case '_': /* #xA0 */
+ *(string.pointer++) = '\xC2';
+ *(string.pointer++) = '\xA0';
+ break;
+
+ case 'L': /* LS (#x2028) */
+ *(string.pointer++) = '\xE2';
+ *(string.pointer++) = '\x80';
+ *(string.pointer++) = '\xA8';
+ break;
+
+ case 'P': /* PS (#x2029) */
+ *(string.pointer++) = '\xE2';
+ *(string.pointer++) = '\x80';
+ *(string.pointer++) = '\xA9';
+ break;
+
+ case 'x':
+ code_length = 2;
+ break;
+
+ case 'u':
+ code_length = 4;
+ break;
+
+ case 'U':
+ code_length = 8;
+ break;
+
+ default:
+ yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
+ start_mark, "found unknown escape character");
+ goto error;
+ }
+
+ SKIP(parser);
+ SKIP(parser);
+
+ /* Consume an arbitrary escape code. */
+
+ if (code_length)
+ {
+ unsigned int value = 0;
+ size_t k;
+
+ /* Scan the character value. */
+
+ if (!CACHE(parser, code_length)) goto error;
+
+ for (k = 0; k < code_length; k ++) {
+ if (!IS_HEX_AT(parser->buffer, k)) {
+ yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
+ start_mark, "did not find expected hexdecimal number");
+ goto error;
+ }
+ value = (value << 4) + AS_HEX_AT(parser->buffer, k);
+ }
+
+ /* Check the value and write the character. */
+
+ if ((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) {
+ yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
+ start_mark, "found invalid Unicode character escape code");
+ goto error;
+ }
+
+ if (value <= 0x7F) {
+ *(string.pointer++) = value;
+ }
+ else if (value <= 0x7FF) {
+ *(string.pointer++) = 0xC0 + (value >> 6);
+ *(string.pointer++) = 0x80 + (value & 0x3F);
+ }
+ else if (value <= 0xFFFF) {
+ *(string.pointer++) = 0xE0 + (value >> 12);
+ *(string.pointer++) = 0x80 + ((value >> 6) & 0x3F);
+ *(string.pointer++) = 0x80 + (value & 0x3F);
+ }
+ else {
+ *(string.pointer++) = 0xF0 + (value >> 18);
+ *(string.pointer++) = 0x80 + ((value >> 12) & 0x3F);
+ *(string.pointer++) = 0x80 + ((value >> 6) & 0x3F);
+ *(string.pointer++) = 0x80 + (value & 0x3F);
+ }
+
+ /* Advance the pointer. */
+
+ for (k = 0; k < code_length; k ++) {
+ SKIP(parser);
+ }
+ }
+ }
+
+ else
+ {
+ /* It is a non-escaped non-blank character. */
+
+ if (!READ(parser, string)) goto error;
+ }
+
+ if (!CACHE(parser, 2)) goto error;
+ }
+
+ /* Check if we are at the end of the scalar. */
+
/* Fix for crash unitialized value crash
* Credit for the bug and input is to OSS Fuzz
* Credit for the fix to Alex Gaynor
*/
if (!CACHE(parser, 1)) goto error;
- if (CHECK(parser->buffer, single ? '\'' : '"'))
- break;
-
- /* Consume blank characters. */
-
- if (!CACHE(parser, 1)) goto error;
-
- while (IS_BLANK(parser->buffer) || IS_BREAK(parser->buffer))
- {
- if (IS_BLANK(parser->buffer))
- {
- /* Consume a space or a tab character. */
-
- if (!leading_blanks) {
- if (!READ(parser, whitespaces)) goto error;
- }
- else {
- SKIP(parser);
- }
- }
- else
- {
- if (!CACHE(parser, 2)) goto error;
-
- /* Check if it is a first line break. */
-
- if (!leading_blanks)
- {
- CLEAR(parser, whitespaces);
- if (!READ_LINE(parser, leading_break)) goto error;
- leading_blanks = 1;
- }
- else
- {
- if (!READ_LINE(parser, trailing_breaks)) goto error;
- }
- }
- if (!CACHE(parser, 1)) goto error;
- }
-
- /* Join the whitespaces or fold line breaks. */
-
- if (leading_blanks)
- {
- /* Do we need to fold line breaks? */
-
- if (leading_break.start[0] == '\n') {
- if (trailing_breaks.start[0] == '\0') {
- if (!STRING_EXTEND(parser, string)) goto error;
- *(string.pointer++) = ' ';
- }
- else {
- if (!JOIN(parser, string, trailing_breaks)) goto error;
- CLEAR(parser, trailing_breaks);
- }
- CLEAR(parser, leading_break);
- }
- else {
- if (!JOIN(parser, string, leading_break)) goto error;
- if (!JOIN(parser, string, trailing_breaks)) goto error;
- CLEAR(parser, leading_break);
- CLEAR(parser, trailing_breaks);
- }
- }
- else
- {
- if (!JOIN(parser, string, whitespaces)) goto error;
- CLEAR(parser, whitespaces);
- }
- }
-
- /* Eat the right quote. */
-
- SKIP(parser);
-
- end_mark = parser->mark;
-
- /* Create a token. */
-
- SCALAR_TOKEN_INIT(*token, string.start, string.pointer-string.start,
- single ? YAML_SINGLE_QUOTED_SCALAR_STYLE : YAML_DOUBLE_QUOTED_SCALAR_STYLE,
- start_mark, end_mark);
-
- STRING_DEL(parser, leading_break);
- STRING_DEL(parser, trailing_breaks);
- STRING_DEL(parser, whitespaces);
-
- return 1;
-
-error:
- STRING_DEL(parser, string);
- STRING_DEL(parser, leading_break);
- STRING_DEL(parser, trailing_breaks);
- STRING_DEL(parser, whitespaces);
-
- return 0;
-}
-
-/*
- * Scan a plain scalar.
- */
-
-static int
-yaml_parser_scan_plain_scalar(yaml_parser_t *parser, yaml_token_t *token)
-{
- yaml_mark_t start_mark;
- yaml_mark_t end_mark;
- yaml_string_t string = NULL_STRING;
- yaml_string_t leading_break = NULL_STRING;
- yaml_string_t trailing_breaks = NULL_STRING;
- yaml_string_t whitespaces = NULL_STRING;
- int leading_blanks = 0;
- int indent = parser->indent+1;
-
- if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
- if (!STRING_INIT(parser, leading_break, INITIAL_STRING_SIZE)) goto error;
- if (!STRING_INIT(parser, trailing_breaks, INITIAL_STRING_SIZE)) goto error;
- if (!STRING_INIT(parser, whitespaces, INITIAL_STRING_SIZE)) goto error;
-
- start_mark = end_mark = parser->mark;
-
- /* Consume the content of the plain scalar. */
-
- while (1)
- {
- /* Check for a document indicator. */
-
- if (!CACHE(parser, 4)) goto error;
-
- if (parser->mark.column == 0 &&
- ((CHECK_AT(parser->buffer, '-', 0) &&
- CHECK_AT(parser->buffer, '-', 1) &&
- CHECK_AT(parser->buffer, '-', 2)) ||
- (CHECK_AT(parser->buffer, '.', 0) &&
- CHECK_AT(parser->buffer, '.', 1) &&
- CHECK_AT(parser->buffer, '.', 2))) &&
- IS_BLANKZ_AT(parser->buffer, 3)) break;
-
- /* Check for a comment. */
-
- if (CHECK(parser->buffer, '#'))
- break;
-
- /* Consume non-blank characters. */
-
- while (!IS_BLANKZ(parser->buffer))
- {
+ if (CHECK(parser->buffer, single ? '\'' : '"'))
+ break;
+
+ /* Consume blank characters. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ while (IS_BLANK(parser->buffer) || IS_BREAK(parser->buffer))
+ {
+ if (IS_BLANK(parser->buffer))
+ {
+ /* Consume a space or a tab character. */
+
+ if (!leading_blanks) {
+ if (!READ(parser, whitespaces)) goto error;
+ }
+ else {
+ SKIP(parser);
+ }
+ }
+ else
+ {
+ if (!CACHE(parser, 2)) goto error;
+
+ /* Check if it is a first line break. */
+
+ if (!leading_blanks)
+ {
+ CLEAR(parser, whitespaces);
+ if (!READ_LINE(parser, leading_break)) goto error;
+ leading_blanks = 1;
+ }
+ else
+ {
+ if (!READ_LINE(parser, trailing_breaks)) goto error;
+ }
+ }
+ if (!CACHE(parser, 1)) goto error;
+ }
+
+ /* Join the whitespaces or fold line breaks. */
+
+ if (leading_blanks)
+ {
+ /* Do we need to fold line breaks? */
+
+ if (leading_break.start[0] == '\n') {
+ if (trailing_breaks.start[0] == '\0') {
+ if (!STRING_EXTEND(parser, string)) goto error;
+ *(string.pointer++) = ' ';
+ }
+ else {
+ if (!JOIN(parser, string, trailing_breaks)) goto error;
+ CLEAR(parser, trailing_breaks);
+ }
+ CLEAR(parser, leading_break);
+ }
+ else {
+ if (!JOIN(parser, string, leading_break)) goto error;
+ if (!JOIN(parser, string, trailing_breaks)) goto error;
+ CLEAR(parser, leading_break);
+ CLEAR(parser, trailing_breaks);
+ }
+ }
+ else
+ {
+ if (!JOIN(parser, string, whitespaces)) goto error;
+ CLEAR(parser, whitespaces);
+ }
+ }
+
+ /* Eat the right quote. */
+
+ SKIP(parser);
+
+ end_mark = parser->mark;
+
+ /* Create a token. */
+
+ SCALAR_TOKEN_INIT(*token, string.start, string.pointer-string.start,
+ single ? YAML_SINGLE_QUOTED_SCALAR_STYLE : YAML_DOUBLE_QUOTED_SCALAR_STYLE,
+ start_mark, end_mark);
+
+ STRING_DEL(parser, leading_break);
+ STRING_DEL(parser, trailing_breaks);
+ STRING_DEL(parser, whitespaces);
+
+ return 1;
+
+error:
+ STRING_DEL(parser, string);
+ STRING_DEL(parser, leading_break);
+ STRING_DEL(parser, trailing_breaks);
+ STRING_DEL(parser, whitespaces);
+
+ return 0;
+}
+
+/*
+ * Scan a plain scalar.
+ */
+
+static int
+yaml_parser_scan_plain_scalar(yaml_parser_t *parser, yaml_token_t *token)
+{
+ yaml_mark_t start_mark;
+ yaml_mark_t end_mark;
+ yaml_string_t string = NULL_STRING;
+ yaml_string_t leading_break = NULL_STRING;
+ yaml_string_t trailing_breaks = NULL_STRING;
+ yaml_string_t whitespaces = NULL_STRING;
+ int leading_blanks = 0;
+ int indent = parser->indent+1;
+
+ if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error;
+ if (!STRING_INIT(parser, leading_break, INITIAL_STRING_SIZE)) goto error;
+ if (!STRING_INIT(parser, trailing_breaks, INITIAL_STRING_SIZE)) goto error;
+ if (!STRING_INIT(parser, whitespaces, INITIAL_STRING_SIZE)) goto error;
+
+ start_mark = end_mark = parser->mark;
+
+ /* Consume the content of the plain scalar. */
+
+ while (1)
+ {
+ /* Check for a document indicator. */
+
+ if (!CACHE(parser, 4)) goto error;
+
+ if (parser->mark.column == 0 &&
+ ((CHECK_AT(parser->buffer, '-', 0) &&
+ CHECK_AT(parser->buffer, '-', 1) &&
+ CHECK_AT(parser->buffer, '-', 2)) ||
+ (CHECK_AT(parser->buffer, '.', 0) &&
+ CHECK_AT(parser->buffer, '.', 1) &&
+ CHECK_AT(parser->buffer, '.', 2))) &&
+ IS_BLANKZ_AT(parser->buffer, 3)) break;
+
+ /* Check for a comment. */
+
+ if (CHECK(parser->buffer, '#'))
+ break;
+
+ /* Consume non-blank characters. */
+
+ while (!IS_BLANKZ(parser->buffer))
+ {
/* Check for "x:" + one of ',?[]{}' in the flow context. TODO: Fix the test "spec-08-13".
* This is not completely according to the spec
* See http://yaml.org/spec/1.1/#id907281 9.1.3. Plain
*/
-
- if (parser->flow_level
- && CHECK(parser->buffer, ':')
+
+ if (parser->flow_level
+ && CHECK(parser->buffer, ':')
&& (
CHECK_AT(parser->buffer, ',', 1)
|| CHECK_AT(parser->buffer, '?', 1)
@@ -3455,144 +3455,144 @@ yaml_parser_scan_plain_scalar(yaml_parser_t *parser, yaml_token_t *token)
|| CHECK_AT(parser->buffer, '}', 1)
)
) {
- yaml_parser_set_scanner_error(parser, "while scanning a plain scalar",
- start_mark, "found unexpected ':'");
- goto error;
- }
-
- /* Check for indicators that may end a plain scalar. */
-
- if ((CHECK(parser->buffer, ':') && IS_BLANKZ_AT(parser->buffer, 1))
- || (parser->flow_level &&
+ yaml_parser_set_scanner_error(parser, "while scanning a plain scalar",
+ start_mark, "found unexpected ':'");
+ goto error;
+ }
+
+ /* Check for indicators that may end a plain scalar. */
+
+ if ((CHECK(parser->buffer, ':') && IS_BLANKZ_AT(parser->buffer, 1))
+ || (parser->flow_level &&
(CHECK(parser->buffer, ',')
|| CHECK(parser->buffer, '[')
- || CHECK(parser->buffer, ']') || CHECK(parser->buffer, '{')
- || CHECK(parser->buffer, '}'))))
- break;
-
- /* Check if we need to join whitespaces and breaks. */
-
- if (leading_blanks || whitespaces.start != whitespaces.pointer)
- {
- if (leading_blanks)
- {
- /* Do we need to fold line breaks? */
-
- if (leading_break.start[0] == '\n') {
- if (trailing_breaks.start[0] == '\0') {
- if (!STRING_EXTEND(parser, string)) goto error;
- *(string.pointer++) = ' ';
- }
- else {
- if (!JOIN(parser, string, trailing_breaks)) goto error;
- CLEAR(parser, trailing_breaks);
- }
- CLEAR(parser, leading_break);
- }
- else {
- if (!JOIN(parser, string, leading_break)) goto error;
- if (!JOIN(parser, string, trailing_breaks)) goto error;
- CLEAR(parser, leading_break);
- CLEAR(parser, trailing_breaks);
- }
-
- leading_blanks = 0;
- }
- else
- {
- if (!JOIN(parser, string, whitespaces)) goto error;
- CLEAR(parser, whitespaces);
- }
- }
-
- /* Copy the character. */
-
- if (!READ(parser, string)) goto error;
-
- end_mark = parser->mark;
-
- if (!CACHE(parser, 2)) goto error;
- }
-
- /* Is it the end? */
-
- if (!(IS_BLANK(parser->buffer) || IS_BREAK(parser->buffer)))
- break;
-
- /* Consume blank characters. */
-
- if (!CACHE(parser, 1)) goto error;
-
- while (IS_BLANK(parser->buffer) || IS_BREAK(parser->buffer))
- {
- if (IS_BLANK(parser->buffer))
- {
+ || CHECK(parser->buffer, ']') || CHECK(parser->buffer, '{')
+ || CHECK(parser->buffer, '}'))))
+ break;
+
+ /* Check if we need to join whitespaces and breaks. */
+
+ if (leading_blanks || whitespaces.start != whitespaces.pointer)
+ {
+ if (leading_blanks)
+ {
+ /* Do we need to fold line breaks? */
+
+ if (leading_break.start[0] == '\n') {
+ if (trailing_breaks.start[0] == '\0') {
+ if (!STRING_EXTEND(parser, string)) goto error;
+ *(string.pointer++) = ' ';
+ }
+ else {
+ if (!JOIN(parser, string, trailing_breaks)) goto error;
+ CLEAR(parser, trailing_breaks);
+ }
+ CLEAR(parser, leading_break);
+ }
+ else {
+ if (!JOIN(parser, string, leading_break)) goto error;
+ if (!JOIN(parser, string, trailing_breaks)) goto error;
+ CLEAR(parser, leading_break);
+ CLEAR(parser, trailing_breaks);
+ }
+
+ leading_blanks = 0;
+ }
+ else
+ {
+ if (!JOIN(parser, string, whitespaces)) goto error;
+ CLEAR(parser, whitespaces);
+ }
+ }
+
+ /* Copy the character. */
+
+ if (!READ(parser, string)) goto error;
+
+ end_mark = parser->mark;
+
+ if (!CACHE(parser, 2)) goto error;
+ }
+
+ /* Is it the end? */
+
+ if (!(IS_BLANK(parser->buffer) || IS_BREAK(parser->buffer)))
+ break;
+
+ /* Consume blank characters. */
+
+ if (!CACHE(parser, 1)) goto error;
+
+ while (IS_BLANK(parser->buffer) || IS_BREAK(parser->buffer))
+ {
+ if (IS_BLANK(parser->buffer))
+ {
/* Check for tab characters that abuse indentation. */
-
- if (leading_blanks && (int)parser->mark.column < indent
- && IS_TAB(parser->buffer)) {
- yaml_parser_set_scanner_error(parser, "while scanning a plain scalar",
+
+ if (leading_blanks && (int)parser->mark.column < indent
+ && IS_TAB(parser->buffer)) {
+ yaml_parser_set_scanner_error(parser, "while scanning a plain scalar",
start_mark, "found a tab character that violates indentation");
- goto error;
- }
-
- /* Consume a space or a tab character. */
-
- if (!leading_blanks) {
- if (!READ(parser, whitespaces)) goto error;
- }
- else {
- SKIP(parser);
- }
- }
- else
- {
- if (!CACHE(parser, 2)) goto error;
-
- /* Check if it is a first line break. */
-
- if (!leading_blanks)
- {
- CLEAR(parser, whitespaces);
- if (!READ_LINE(parser, leading_break)) goto error;
- leading_blanks = 1;
- }
- else
- {
- if (!READ_LINE(parser, trailing_breaks)) goto error;
- }
- }
- if (!CACHE(parser, 1)) goto error;
- }
-
+ goto error;
+ }
+
+ /* Consume a space or a tab character. */
+
+ if (!leading_blanks) {
+ if (!READ(parser, whitespaces)) goto error;
+ }
+ else {
+ SKIP(parser);
+ }
+ }
+ else
+ {
+ if (!CACHE(parser, 2)) goto error;
+
+ /* Check if it is a first line break. */
+
+ if (!leading_blanks)
+ {
+ CLEAR(parser, whitespaces);
+ if (!READ_LINE(parser, leading_break)) goto error;
+ leading_blanks = 1;
+ }
+ else
+ {
+ if (!READ_LINE(parser, trailing_breaks)) goto error;
+ }
+ }
+ if (!CACHE(parser, 1)) goto error;
+ }
+
/* Check indentation level. */
-
- if (!parser->flow_level && (int)parser->mark.column < indent)
- break;
- }
-
- /* Create a token. */
-
- SCALAR_TOKEN_INIT(*token, string.start, string.pointer-string.start,
- YAML_PLAIN_SCALAR_STYLE, start_mark, end_mark);
-
- /* Note that we change the 'simple_key_allowed' flag. */
-
- if (leading_blanks) {
- parser->simple_key_allowed = 1;
- }
-
- STRING_DEL(parser, leading_break);
- STRING_DEL(parser, trailing_breaks);
- STRING_DEL(parser, whitespaces);
-
- return 1;
-
-error:
- STRING_DEL(parser, string);
- STRING_DEL(parser, leading_break);
- STRING_DEL(parser, trailing_breaks);
- STRING_DEL(parser, whitespaces);
-
- return 0;
-}
+
+ if (!parser->flow_level && (int)parser->mark.column < indent)
+ break;
+ }
+
+ /* Create a token. */
+
+ SCALAR_TOKEN_INIT(*token, string.start, string.pointer-string.start,
+ YAML_PLAIN_SCALAR_STYLE, start_mark, end_mark);
+
+ /* Note that we change the 'simple_key_allowed' flag. */
+
+ if (leading_blanks) {
+ parser->simple_key_allowed = 1;
+ }
+
+ STRING_DEL(parser, leading_break);
+ STRING_DEL(parser, trailing_breaks);
+ STRING_DEL(parser, whitespaces);
+
+ return 1;
+
+error:
+ STRING_DEL(parser, string);
+ STRING_DEL(parser, leading_break);
+ STRING_DEL(parser, trailing_breaks);
+ STRING_DEL(parser, whitespaces);
+
+ return 0;
+}
diff --git a/contrib/libs/yaml/src/writer.c b/contrib/libs/yaml/src/writer.c
index aa01469de3..5d57f392f1 100644
--- a/contrib/libs/yaml/src/writer.c
+++ b/contrib/libs/yaml/src/writer.c
@@ -1,141 +1,141 @@
-
-#include "yaml_private.h"
-
-/*
- * Declarations.
- */
-
-static int
-yaml_emitter_set_writer_error(yaml_emitter_t *emitter, const char *problem);
-
-YAML_DECLARE(int)
-yaml_emitter_flush(yaml_emitter_t *emitter);
-
-/*
- * Set the writer error and return 0.
- */
-
-static int
-yaml_emitter_set_writer_error(yaml_emitter_t *emitter, const char *problem)
-{
- emitter->error = YAML_WRITER_ERROR;
- emitter->problem = problem;
-
- return 0;
-}
-
-/*
- * Flush the output buffer.
- */
-
-YAML_DECLARE(int)
-yaml_emitter_flush(yaml_emitter_t *emitter)
-{
- int low, high;
-
- assert(emitter); /* Non-NULL emitter object is expected. */
- assert(emitter->write_handler); /* Write handler must be set. */
- assert(emitter->encoding); /* Output encoding must be set. */
-
- emitter->buffer.last = emitter->buffer.pointer;
- emitter->buffer.pointer = emitter->buffer.start;
-
- /* Check if the buffer is empty. */
-
- if (emitter->buffer.start == emitter->buffer.last) {
- return 1;
- }
-
- /* If the output encoding is UTF-8, we don't need to recode the buffer. */
-
- if (emitter->encoding == YAML_UTF8_ENCODING)
- {
- if (emitter->write_handler(emitter->write_handler_data,
- emitter->buffer.start,
- emitter->buffer.last - emitter->buffer.start)) {
- emitter->buffer.last = emitter->buffer.start;
- emitter->buffer.pointer = emitter->buffer.start;
- return 1;
- }
- else {
- return yaml_emitter_set_writer_error(emitter, "write error");
- }
- }
-
- /* Recode the buffer into the raw buffer. */
-
- low = (emitter->encoding == YAML_UTF16LE_ENCODING ? 0 : 1);
- high = (emitter->encoding == YAML_UTF16LE_ENCODING ? 1 : 0);
-
- while (emitter->buffer.pointer != emitter->buffer.last)
- {
- unsigned char octet;
- unsigned int width;
- unsigned int value;
- size_t k;
-
+
+#include "yaml_private.h"
+
+/*
+ * Declarations.
+ */
+
+static int
+yaml_emitter_set_writer_error(yaml_emitter_t *emitter, const char *problem);
+
+YAML_DECLARE(int)
+yaml_emitter_flush(yaml_emitter_t *emitter);
+
+/*
+ * Set the writer error and return 0.
+ */
+
+static int
+yaml_emitter_set_writer_error(yaml_emitter_t *emitter, const char *problem)
+{
+ emitter->error = YAML_WRITER_ERROR;
+ emitter->problem = problem;
+
+ return 0;
+}
+
+/*
+ * Flush the output buffer.
+ */
+
+YAML_DECLARE(int)
+yaml_emitter_flush(yaml_emitter_t *emitter)
+{
+ int low, high;
+
+ assert(emitter); /* Non-NULL emitter object is expected. */
+ assert(emitter->write_handler); /* Write handler must be set. */
+ assert(emitter->encoding); /* Output encoding must be set. */
+
+ emitter->buffer.last = emitter->buffer.pointer;
+ emitter->buffer.pointer = emitter->buffer.start;
+
+ /* Check if the buffer is empty. */
+
+ if (emitter->buffer.start == emitter->buffer.last) {
+ return 1;
+ }
+
+ /* If the output encoding is UTF-8, we don't need to recode the buffer. */
+
+ if (emitter->encoding == YAML_UTF8_ENCODING)
+ {
+ if (emitter->write_handler(emitter->write_handler_data,
+ emitter->buffer.start,
+ emitter->buffer.last - emitter->buffer.start)) {
+ emitter->buffer.last = emitter->buffer.start;
+ emitter->buffer.pointer = emitter->buffer.start;
+ return 1;
+ }
+ else {
+ return yaml_emitter_set_writer_error(emitter, "write error");
+ }
+ }
+
+ /* Recode the buffer into the raw buffer. */
+
+ low = (emitter->encoding == YAML_UTF16LE_ENCODING ? 0 : 1);
+ high = (emitter->encoding == YAML_UTF16LE_ENCODING ? 1 : 0);
+
+ while (emitter->buffer.pointer != emitter->buffer.last)
+ {
+ unsigned char octet;
+ unsigned int width;
+ unsigned int value;
+ size_t k;
+
/*
- * See the "reader.c" code for more details on UTF-8 encoding. Note
- * that we assume that the buffer contains a valid UTF-8 sequence.
- */
-
- /* Read the next UTF-8 character. */
-
- octet = emitter->buffer.pointer[0];
-
- width = (octet & 0x80) == 0x00 ? 1 :
- (octet & 0xE0) == 0xC0 ? 2 :
- (octet & 0xF0) == 0xE0 ? 3 :
- (octet & 0xF8) == 0xF0 ? 4 : 0;
-
- value = (octet & 0x80) == 0x00 ? octet & 0x7F :
- (octet & 0xE0) == 0xC0 ? octet & 0x1F :
- (octet & 0xF0) == 0xE0 ? octet & 0x0F :
- (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0;
-
- for (k = 1; k < width; k ++) {
- octet = emitter->buffer.pointer[k];
- value = (value << 6) + (octet & 0x3F);
- }
-
- emitter->buffer.pointer += width;
-
- /* Write the character. */
-
- if (value < 0x10000)
- {
- emitter->raw_buffer.last[high] = value >> 8;
- emitter->raw_buffer.last[low] = value & 0xFF;
-
- emitter->raw_buffer.last += 2;
- }
- else
- {
- /* Write the character using a surrogate pair (check "reader.c"). */
-
- value -= 0x10000;
- emitter->raw_buffer.last[high] = 0xD8 + (value >> 18);
- emitter->raw_buffer.last[low] = (value >> 10) & 0xFF;
- emitter->raw_buffer.last[high+2] = 0xDC + ((value >> 8) & 0xFF);
- emitter->raw_buffer.last[low+2] = value & 0xFF;
-
- emitter->raw_buffer.last += 4;
- }
- }
-
- /* Write the raw buffer. */
-
- if (emitter->write_handler(emitter->write_handler_data,
- emitter->raw_buffer.start,
- emitter->raw_buffer.last - emitter->raw_buffer.start)) {
- emitter->buffer.last = emitter->buffer.start;
- emitter->buffer.pointer = emitter->buffer.start;
- emitter->raw_buffer.last = emitter->raw_buffer.start;
- emitter->raw_buffer.pointer = emitter->raw_buffer.start;
- return 1;
- }
- else {
- return yaml_emitter_set_writer_error(emitter, "write error");
- }
-}
-
+ * See the "reader.c" code for more details on UTF-8 encoding. Note
+ * that we assume that the buffer contains a valid UTF-8 sequence.
+ */
+
+ /* Read the next UTF-8 character. */
+
+ octet = emitter->buffer.pointer[0];
+
+ width = (octet & 0x80) == 0x00 ? 1 :
+ (octet & 0xE0) == 0xC0 ? 2 :
+ (octet & 0xF0) == 0xE0 ? 3 :
+ (octet & 0xF8) == 0xF0 ? 4 : 0;
+
+ value = (octet & 0x80) == 0x00 ? octet & 0x7F :
+ (octet & 0xE0) == 0xC0 ? octet & 0x1F :
+ (octet & 0xF0) == 0xE0 ? octet & 0x0F :
+ (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0;
+
+ for (k = 1; k < width; k ++) {
+ octet = emitter->buffer.pointer[k];
+ value = (value << 6) + (octet & 0x3F);
+ }
+
+ emitter->buffer.pointer += width;
+
+ /* Write the character. */
+
+ if (value < 0x10000)
+ {
+ emitter->raw_buffer.last[high] = value >> 8;
+ emitter->raw_buffer.last[low] = value & 0xFF;
+
+ emitter->raw_buffer.last += 2;
+ }
+ else
+ {
+ /* Write the character using a surrogate pair (check "reader.c"). */
+
+ value -= 0x10000;
+ emitter->raw_buffer.last[high] = 0xD8 + (value >> 18);
+ emitter->raw_buffer.last[low] = (value >> 10) & 0xFF;
+ emitter->raw_buffer.last[high+2] = 0xDC + ((value >> 8) & 0xFF);
+ emitter->raw_buffer.last[low+2] = value & 0xFF;
+
+ emitter->raw_buffer.last += 4;
+ }
+ }
+
+ /* Write the raw buffer. */
+
+ if (emitter->write_handler(emitter->write_handler_data,
+ emitter->raw_buffer.start,
+ emitter->raw_buffer.last - emitter->raw_buffer.start)) {
+ emitter->buffer.last = emitter->buffer.start;
+ emitter->buffer.pointer = emitter->buffer.start;
+ emitter->raw_buffer.last = emitter->raw_buffer.start;
+ emitter->raw_buffer.pointer = emitter->raw_buffer.start;
+ return 1;
+ }
+ else {
+ return yaml_emitter_set_writer_error(emitter, "write error");
+ }
+}
+
diff --git a/contrib/libs/yaml/src/yaml_private.h b/contrib/libs/yaml/src/yaml_private.h
index d449b470ff..b3351c4165 100644
--- a/contrib/libs/yaml/src/yaml_private.h
+++ b/contrib/libs/yaml/src/yaml_private.h
@@ -1,72 +1,72 @@
#if HAVE_CONFIG_H
-#include "config.h"
+#include "config.h"
#endif
-
-#include <yaml.h>
-
-#include <assert.h>
-#include <limits.h>
-#include <stddef.h>
-
-/*
- * Memory management.
- */
-
-YAML_DECLARE(void *)
-yaml_malloc(size_t size);
-
-YAML_DECLARE(void *)
-yaml_realloc(void *ptr, size_t size);
-
-YAML_DECLARE(void)
-yaml_free(void *ptr);
-
-YAML_DECLARE(yaml_char_t *)
-yaml_strdup(const yaml_char_t *);
-
-/*
- * Reader: Ensure that the buffer contains at least `length` characters.
- */
-
-YAML_DECLARE(int)
-yaml_parser_update_buffer(yaml_parser_t *parser, size_t length);
-
-/*
- * Scanner: Ensure that the token stack contains at least one token ready.
- */
-
-YAML_DECLARE(int)
-yaml_parser_fetch_more_tokens(yaml_parser_t *parser);
-
-/*
- * The size of the input raw buffer.
- */
-
-#define INPUT_RAW_BUFFER_SIZE 16384
-
-/*
- * The size of the input buffer.
- *
- * It should be possible to decode the whole raw buffer.
- */
-
-#define INPUT_BUFFER_SIZE (INPUT_RAW_BUFFER_SIZE*3)
-
-/*
- * The size of the output buffer.
- */
-
-#define OUTPUT_BUFFER_SIZE 16384
-
-/*
- * The size of the output raw buffer.
- *
- * It should be possible to encode the whole output buffer.
- */
-
-#define OUTPUT_RAW_BUFFER_SIZE (OUTPUT_BUFFER_SIZE*2+2)
-
-/*
+
+#include <yaml.h>
+
+#include <assert.h>
+#include <limits.h>
+#include <stddef.h>
+
+/*
+ * Memory management.
+ */
+
+YAML_DECLARE(void *)
+yaml_malloc(size_t size);
+
+YAML_DECLARE(void *)
+yaml_realloc(void *ptr, size_t size);
+
+YAML_DECLARE(void)
+yaml_free(void *ptr);
+
+YAML_DECLARE(yaml_char_t *)
+yaml_strdup(const yaml_char_t *);
+
+/*
+ * Reader: Ensure that the buffer contains at least `length` characters.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_update_buffer(yaml_parser_t *parser, size_t length);
+
+/*
+ * Scanner: Ensure that the token stack contains at least one token ready.
+ */
+
+YAML_DECLARE(int)
+yaml_parser_fetch_more_tokens(yaml_parser_t *parser);
+
+/*
+ * The size of the input raw buffer.
+ */
+
+#define INPUT_RAW_BUFFER_SIZE 16384
+
+/*
+ * The size of the input buffer.
+ *
+ * It should be possible to decode the whole raw buffer.
+ */
+
+#define INPUT_BUFFER_SIZE (INPUT_RAW_BUFFER_SIZE*3)
+
+/*
+ * The size of the output buffer.
+ */
+
+#define OUTPUT_BUFFER_SIZE 16384
+
+/*
+ * The size of the output raw buffer.
+ *
+ * It should be possible to encode the whole output buffer.
+ */
+
+#define OUTPUT_RAW_BUFFER_SIZE (OUTPUT_BUFFER_SIZE*2+2)
+
+/*
* The maximum size of a YAML input file.
* This used to be PTRDIFF_MAX, but that's not entirely portable
* because stdint.h isn't available on all platforms.
@@ -78,586 +78,586 @@ yaml_parser_fetch_more_tokens(yaml_parser_t *parser);
/*
- * The size of other stacks and queues.
- */
-
-#define INITIAL_STACK_SIZE 16
-#define INITIAL_QUEUE_SIZE 16
-#define INITIAL_STRING_SIZE 16
-
-/*
- * Buffer management.
- */
-
-#define BUFFER_INIT(context,buffer,size) \
+ * The size of other stacks and queues.
+ */
+
+#define INITIAL_STACK_SIZE 16
+#define INITIAL_QUEUE_SIZE 16
+#define INITIAL_STRING_SIZE 16
+
+/*
+ * Buffer management.
+ */
+
+#define BUFFER_INIT(context,buffer,size) \
(((buffer).start = (yaml_char_t *)yaml_malloc(size)) ? \
- ((buffer).last = (buffer).pointer = (buffer).start, \
- (buffer).end = (buffer).start+(size), \
- 1) : \
- ((context)->error = YAML_MEMORY_ERROR, \
- 0))
-
-#define BUFFER_DEL(context,buffer) \
- (yaml_free((buffer).start), \
- (buffer).start = (buffer).pointer = (buffer).end = 0)
-
-/*
- * String management.
- */
-
-typedef struct {
- yaml_char_t *start;
- yaml_char_t *end;
- yaml_char_t *pointer;
-} yaml_string_t;
-
-YAML_DECLARE(int)
-yaml_string_extend(yaml_char_t **start,
- yaml_char_t **pointer, yaml_char_t **end);
-
-YAML_DECLARE(int)
-yaml_string_join(
- yaml_char_t **a_start, yaml_char_t **a_pointer, yaml_char_t **a_end,
- yaml_char_t **b_start, yaml_char_t **b_pointer, yaml_char_t **b_end);
-
-#define NULL_STRING { NULL, NULL, NULL }
-
-#define STRING(string,length) { (string), (string)+(length), (string) }
-
-#define STRING_ASSIGN(value,string,length) \
- ((value).start = (string), \
- (value).end = (string)+(length), \
- (value).pointer = (string))
-
-#define STRING_INIT(context,string,size) \
+ ((buffer).last = (buffer).pointer = (buffer).start, \
+ (buffer).end = (buffer).start+(size), \
+ 1) : \
+ ((context)->error = YAML_MEMORY_ERROR, \
+ 0))
+
+#define BUFFER_DEL(context,buffer) \
+ (yaml_free((buffer).start), \
+ (buffer).start = (buffer).pointer = (buffer).end = 0)
+
+/*
+ * String management.
+ */
+
+typedef struct {
+ yaml_char_t *start;
+ yaml_char_t *end;
+ yaml_char_t *pointer;
+} yaml_string_t;
+
+YAML_DECLARE(int)
+yaml_string_extend(yaml_char_t **start,
+ yaml_char_t **pointer, yaml_char_t **end);
+
+YAML_DECLARE(int)
+yaml_string_join(
+ yaml_char_t **a_start, yaml_char_t **a_pointer, yaml_char_t **a_end,
+ yaml_char_t **b_start, yaml_char_t **b_pointer, yaml_char_t **b_end);
+
+#define NULL_STRING { NULL, NULL, NULL }
+
+#define STRING(string,length) { (string), (string)+(length), (string) }
+
+#define STRING_ASSIGN(value,string,length) \
+ ((value).start = (string), \
+ (value).end = (string)+(length), \
+ (value).pointer = (string))
+
+#define STRING_INIT(context,string,size) \
(((string).start = YAML_MALLOC(size)) ? \
- ((string).pointer = (string).start, \
- (string).end = (string).start+(size), \
- memset((string).start, 0, (size)), \
- 1) : \
- ((context)->error = YAML_MEMORY_ERROR, \
- 0))
-
-#define STRING_DEL(context,string) \
- (yaml_free((string).start), \
- (string).start = (string).pointer = (string).end = 0)
-
-#define STRING_EXTEND(context,string) \
+ ((string).pointer = (string).start, \
+ (string).end = (string).start+(size), \
+ memset((string).start, 0, (size)), \
+ 1) : \
+ ((context)->error = YAML_MEMORY_ERROR, \
+ 0))
+
+#define STRING_DEL(context,string) \
+ (yaml_free((string).start), \
+ (string).start = (string).pointer = (string).end = 0)
+
+#define STRING_EXTEND(context,string) \
((((string).pointer+5 < (string).end) \
- || yaml_string_extend(&(string).start, \
+ || yaml_string_extend(&(string).start, \
&(string).pointer, &(string).end)) ? \
1 : \
((context)->error = YAML_MEMORY_ERROR, \
0))
-
-#define CLEAR(context,string) \
- ((string).pointer = (string).start, \
- memset((string).start, 0, (string).end-(string).start))
-
-#define JOIN(context,string_a,string_b) \
- ((yaml_string_join(&(string_a).start, &(string_a).pointer, \
- &(string_a).end, &(string_b).start, \
- &(string_b).pointer, &(string_b).end)) ? \
- ((string_b).pointer = (string_b).start, \
- 1) : \
- ((context)->error = YAML_MEMORY_ERROR, \
- 0))
-
-/*
- * String check operations.
- */
-
-/*
- * Check the octet at the specified position.
- */
-
+
+#define CLEAR(context,string) \
+ ((string).pointer = (string).start, \
+ memset((string).start, 0, (string).end-(string).start))
+
+#define JOIN(context,string_a,string_b) \
+ ((yaml_string_join(&(string_a).start, &(string_a).pointer, \
+ &(string_a).end, &(string_b).start, \
+ &(string_b).pointer, &(string_b).end)) ? \
+ ((string_b).pointer = (string_b).start, \
+ 1) : \
+ ((context)->error = YAML_MEMORY_ERROR, \
+ 0))
+
+/*
+ * String check operations.
+ */
+
+/*
+ * Check the octet at the specified position.
+ */
+
#define CHECK_AT(string,octet,offset) \
- ((string).pointer[offset] == (yaml_char_t)(octet))
-
-/*
- * Check the current octet in the buffer.
- */
-
+ ((string).pointer[offset] == (yaml_char_t)(octet))
+
+/*
+ * Check the current octet in the buffer.
+ */
+
#define CHECK(string,octet) (CHECK_AT((string),(octet),0))
-
-/*
- * Check if the character at the specified position is an alphabetical
- * character, a digit, '_', or '-'.
- */
-
-#define IS_ALPHA_AT(string,offset) \
- (((string).pointer[offset] >= (yaml_char_t) '0' && \
- (string).pointer[offset] <= (yaml_char_t) '9') || \
- ((string).pointer[offset] >= (yaml_char_t) 'A' && \
- (string).pointer[offset] <= (yaml_char_t) 'Z') || \
- ((string).pointer[offset] >= (yaml_char_t) 'a' && \
- (string).pointer[offset] <= (yaml_char_t) 'z') || \
- (string).pointer[offset] == '_' || \
- (string).pointer[offset] == '-')
-
-#define IS_ALPHA(string) IS_ALPHA_AT((string),0)
-
-/*
- * Check if the character at the specified position is a digit.
- */
-
-#define IS_DIGIT_AT(string,offset) \
- (((string).pointer[offset] >= (yaml_char_t) '0' && \
- (string).pointer[offset] <= (yaml_char_t) '9'))
-
-#define IS_DIGIT(string) IS_DIGIT_AT((string),0)
-
-/*
- * Get the value of a digit.
- */
-
-#define AS_DIGIT_AT(string,offset) \
- ((string).pointer[offset] - (yaml_char_t) '0')
-
-#define AS_DIGIT(string) AS_DIGIT_AT((string),0)
-
-/*
- * Check if the character at the specified position is a hex-digit.
- */
-
-#define IS_HEX_AT(string,offset) \
- (((string).pointer[offset] >= (yaml_char_t) '0' && \
- (string).pointer[offset] <= (yaml_char_t) '9') || \
- ((string).pointer[offset] >= (yaml_char_t) 'A' && \
- (string).pointer[offset] <= (yaml_char_t) 'F') || \
- ((string).pointer[offset] >= (yaml_char_t) 'a' && \
- (string).pointer[offset] <= (yaml_char_t) 'f'))
-
-#define IS_HEX(string) IS_HEX_AT((string),0)
-
-/*
- * Get the value of a hex-digit.
- */
-
-#define AS_HEX_AT(string,offset) \
- (((string).pointer[offset] >= (yaml_char_t) 'A' && \
- (string).pointer[offset] <= (yaml_char_t) 'F') ? \
- ((string).pointer[offset] - (yaml_char_t) 'A' + 10) : \
- ((string).pointer[offset] >= (yaml_char_t) 'a' && \
- (string).pointer[offset] <= (yaml_char_t) 'f') ? \
- ((string).pointer[offset] - (yaml_char_t) 'a' + 10) : \
- ((string).pointer[offset] - (yaml_char_t) '0'))
-
-#define AS_HEX(string) AS_HEX_AT((string),0)
-
-/*
- * Check if the character is ASCII.
- */
-
-#define IS_ASCII_AT(string,offset) \
- ((string).pointer[offset] <= (yaml_char_t) '\x7F')
-
-#define IS_ASCII(string) IS_ASCII_AT((string),0)
-
-/*
- * Check if the character can be printed unescaped.
- */
-
-#define IS_PRINTABLE_AT(string,offset) \
- (((string).pointer[offset] == 0x0A) /* . == #x0A */ \
- || ((string).pointer[offset] >= 0x20 /* #x20 <= . <= #x7E */ \
- && (string).pointer[offset] <= 0x7E) \
- || ((string).pointer[offset] == 0xC2 /* #0xA0 <= . <= #xD7FF */ \
- && (string).pointer[offset+1] >= 0xA0) \
- || ((string).pointer[offset] > 0xC2 \
- && (string).pointer[offset] < 0xED) \
- || ((string).pointer[offset] == 0xED \
- && (string).pointer[offset+1] < 0xA0) \
- || ((string).pointer[offset] == 0xEE) \
- || ((string).pointer[offset] == 0xEF /* #xE000 <= . <= #xFFFD */ \
- && !((string).pointer[offset+1] == 0xBB /* && . != #xFEFF */ \
- && (string).pointer[offset+2] == 0xBF) \
- && !((string).pointer[offset+1] == 0xBF \
- && ((string).pointer[offset+2] == 0xBE \
- || (string).pointer[offset+2] == 0xBF))))
-
-#define IS_PRINTABLE(string) IS_PRINTABLE_AT((string),0)
-
-/*
- * Check if the character at the specified position is NUL.
- */
-
-#define IS_Z_AT(string,offset) CHECK_AT((string),'\0',(offset))
-
-#define IS_Z(string) IS_Z_AT((string),0)
-
-/*
- * Check if the character at the specified position is BOM.
- */
-
-#define IS_BOM_AT(string,offset) \
- (CHECK_AT((string),'\xEF',(offset)) \
- && CHECK_AT((string),'\xBB',(offset)+1) \
- && CHECK_AT((string),'\xBF',(offset)+2)) /* BOM (#xFEFF) */
-
-#define IS_BOM(string) IS_BOM_AT(string,0)
-
-/*
- * Check if the character at the specified position is space.
- */
-
-#define IS_SPACE_AT(string,offset) CHECK_AT((string),' ',(offset))
-
-#define IS_SPACE(string) IS_SPACE_AT((string),0)
-
-/*
- * Check if the character at the specified position is tab.
- */
-
-#define IS_TAB_AT(string,offset) CHECK_AT((string),'\t',(offset))
-
-#define IS_TAB(string) IS_TAB_AT((string),0)
-
-/*
- * Check if the character at the specified position is blank (space or tab).
- */
-
-#define IS_BLANK_AT(string,offset) \
- (IS_SPACE_AT((string),(offset)) || IS_TAB_AT((string),(offset)))
-
-#define IS_BLANK(string) IS_BLANK_AT((string),0)
-
-/*
- * Check if the character at the specified position is a line break.
- */
-
-#define IS_BREAK_AT(string,offset) \
- (CHECK_AT((string),'\r',(offset)) /* CR (#xD)*/ \
- || CHECK_AT((string),'\n',(offset)) /* LF (#xA) */ \
- || (CHECK_AT((string),'\xC2',(offset)) \
- && CHECK_AT((string),'\x85',(offset)+1)) /* NEL (#x85) */ \
- || (CHECK_AT((string),'\xE2',(offset)) \
- && CHECK_AT((string),'\x80',(offset)+1) \
- && CHECK_AT((string),'\xA8',(offset)+2)) /* LS (#x2028) */ \
- || (CHECK_AT((string),'\xE2',(offset)) \
- && CHECK_AT((string),'\x80',(offset)+1) \
- && CHECK_AT((string),'\xA9',(offset)+2))) /* PS (#x2029) */
-
-#define IS_BREAK(string) IS_BREAK_AT((string),0)
-
-#define IS_CRLF_AT(string,offset) \
- (CHECK_AT((string),'\r',(offset)) && CHECK_AT((string),'\n',(offset)+1))
-
-#define IS_CRLF(string) IS_CRLF_AT((string),0)
-
-/*
- * Check if the character is a line break or NUL.
- */
-
-#define IS_BREAKZ_AT(string,offset) \
- (IS_BREAK_AT((string),(offset)) || IS_Z_AT((string),(offset)))
-
-#define IS_BREAKZ(string) IS_BREAKZ_AT((string),0)
-
-/*
- * Check if the character is a line break, space, or NUL.
- */
-
-#define IS_SPACEZ_AT(string,offset) \
- (IS_SPACE_AT((string),(offset)) || IS_BREAKZ_AT((string),(offset)))
-
-#define IS_SPACEZ(string) IS_SPACEZ_AT((string),0)
-
-/*
- * Check if the character is a line break, space, tab, or NUL.
- */
-
-#define IS_BLANKZ_AT(string,offset) \
- (IS_BLANK_AT((string),(offset)) || IS_BREAKZ_AT((string),(offset)))
-
-#define IS_BLANKZ(string) IS_BLANKZ_AT((string),0)
-
-/*
- * Determine the width of the character.
- */
-
-#define WIDTH_AT(string,offset) \
- (((string).pointer[offset] & 0x80) == 0x00 ? 1 : \
- ((string).pointer[offset] & 0xE0) == 0xC0 ? 2 : \
- ((string).pointer[offset] & 0xF0) == 0xE0 ? 3 : \
- ((string).pointer[offset] & 0xF8) == 0xF0 ? 4 : 0)
-
-#define WIDTH(string) WIDTH_AT((string),0)
-
-/*
- * Move the string pointer to the next character.
- */
-
-#define MOVE(string) ((string).pointer += WIDTH((string)))
-
-/*
- * Copy a character and move the pointers of both strings.
- */
-
-#define COPY(string_a,string_b) \
- ((*(string_b).pointer & 0x80) == 0x00 ? \
- (*((string_a).pointer++) = *((string_b).pointer++)) : \
- (*(string_b).pointer & 0xE0) == 0xC0 ? \
- (*((string_a).pointer++) = *((string_b).pointer++), \
- *((string_a).pointer++) = *((string_b).pointer++)) : \
- (*(string_b).pointer & 0xF0) == 0xE0 ? \
- (*((string_a).pointer++) = *((string_b).pointer++), \
- *((string_a).pointer++) = *((string_b).pointer++), \
- *((string_a).pointer++) = *((string_b).pointer++)) : \
- (*(string_b).pointer & 0xF8) == 0xF0 ? \
- (*((string_a).pointer++) = *((string_b).pointer++), \
- *((string_a).pointer++) = *((string_b).pointer++), \
- *((string_a).pointer++) = *((string_b).pointer++), \
- *((string_a).pointer++) = *((string_b).pointer++)) : 0)
-
-/*
- * Stack and queue management.
- */
-
-YAML_DECLARE(int)
-yaml_stack_extend(void **start, void **top, void **end);
-
-YAML_DECLARE(int)
-yaml_queue_extend(void **start, void **head, void **tail, void **end);
-
+
+/*
+ * Check if the character at the specified position is an alphabetical
+ * character, a digit, '_', or '-'.
+ */
+
+#define IS_ALPHA_AT(string,offset) \
+ (((string).pointer[offset] >= (yaml_char_t) '0' && \
+ (string).pointer[offset] <= (yaml_char_t) '9') || \
+ ((string).pointer[offset] >= (yaml_char_t) 'A' && \
+ (string).pointer[offset] <= (yaml_char_t) 'Z') || \
+ ((string).pointer[offset] >= (yaml_char_t) 'a' && \
+ (string).pointer[offset] <= (yaml_char_t) 'z') || \
+ (string).pointer[offset] == '_' || \
+ (string).pointer[offset] == '-')
+
+#define IS_ALPHA(string) IS_ALPHA_AT((string),0)
+
+/*
+ * Check if the character at the specified position is a digit.
+ */
+
+#define IS_DIGIT_AT(string,offset) \
+ (((string).pointer[offset] >= (yaml_char_t) '0' && \
+ (string).pointer[offset] <= (yaml_char_t) '9'))
+
+#define IS_DIGIT(string) IS_DIGIT_AT((string),0)
+
+/*
+ * Get the value of a digit.
+ */
+
+#define AS_DIGIT_AT(string,offset) \
+ ((string).pointer[offset] - (yaml_char_t) '0')
+
+#define AS_DIGIT(string) AS_DIGIT_AT((string),0)
+
+/*
+ * Check if the character at the specified position is a hex-digit.
+ */
+
+#define IS_HEX_AT(string,offset) \
+ (((string).pointer[offset] >= (yaml_char_t) '0' && \
+ (string).pointer[offset] <= (yaml_char_t) '9') || \
+ ((string).pointer[offset] >= (yaml_char_t) 'A' && \
+ (string).pointer[offset] <= (yaml_char_t) 'F') || \
+ ((string).pointer[offset] >= (yaml_char_t) 'a' && \
+ (string).pointer[offset] <= (yaml_char_t) 'f'))
+
+#define IS_HEX(string) IS_HEX_AT((string),0)
+
+/*
+ * Get the value of a hex-digit.
+ */
+
+#define AS_HEX_AT(string,offset) \
+ (((string).pointer[offset] >= (yaml_char_t) 'A' && \
+ (string).pointer[offset] <= (yaml_char_t) 'F') ? \
+ ((string).pointer[offset] - (yaml_char_t) 'A' + 10) : \
+ ((string).pointer[offset] >= (yaml_char_t) 'a' && \
+ (string).pointer[offset] <= (yaml_char_t) 'f') ? \
+ ((string).pointer[offset] - (yaml_char_t) 'a' + 10) : \
+ ((string).pointer[offset] - (yaml_char_t) '0'))
+
+#define AS_HEX(string) AS_HEX_AT((string),0)
+
+/*
+ * Check if the character is ASCII.
+ */
+
+#define IS_ASCII_AT(string,offset) \
+ ((string).pointer[offset] <= (yaml_char_t) '\x7F')
+
+#define IS_ASCII(string) IS_ASCII_AT((string),0)
+
+/*
+ * Check if the character can be printed unescaped.
+ */
+
+#define IS_PRINTABLE_AT(string,offset) \
+ (((string).pointer[offset] == 0x0A) /* . == #x0A */ \
+ || ((string).pointer[offset] >= 0x20 /* #x20 <= . <= #x7E */ \
+ && (string).pointer[offset] <= 0x7E) \
+ || ((string).pointer[offset] == 0xC2 /* #0xA0 <= . <= #xD7FF */ \
+ && (string).pointer[offset+1] >= 0xA0) \
+ || ((string).pointer[offset] > 0xC2 \
+ && (string).pointer[offset] < 0xED) \
+ || ((string).pointer[offset] == 0xED \
+ && (string).pointer[offset+1] < 0xA0) \
+ || ((string).pointer[offset] == 0xEE) \
+ || ((string).pointer[offset] == 0xEF /* #xE000 <= . <= #xFFFD */ \
+ && !((string).pointer[offset+1] == 0xBB /* && . != #xFEFF */ \
+ && (string).pointer[offset+2] == 0xBF) \
+ && !((string).pointer[offset+1] == 0xBF \
+ && ((string).pointer[offset+2] == 0xBE \
+ || (string).pointer[offset+2] == 0xBF))))
+
+#define IS_PRINTABLE(string) IS_PRINTABLE_AT((string),0)
+
+/*
+ * Check if the character at the specified position is NUL.
+ */
+
+#define IS_Z_AT(string,offset) CHECK_AT((string),'\0',(offset))
+
+#define IS_Z(string) IS_Z_AT((string),0)
+
+/*
+ * Check if the character at the specified position is BOM.
+ */
+
+#define IS_BOM_AT(string,offset) \
+ (CHECK_AT((string),'\xEF',(offset)) \
+ && CHECK_AT((string),'\xBB',(offset)+1) \
+ && CHECK_AT((string),'\xBF',(offset)+2)) /* BOM (#xFEFF) */
+
+#define IS_BOM(string) IS_BOM_AT(string,0)
+
+/*
+ * Check if the character at the specified position is space.
+ */
+
+#define IS_SPACE_AT(string,offset) CHECK_AT((string),' ',(offset))
+
+#define IS_SPACE(string) IS_SPACE_AT((string),0)
+
+/*
+ * Check if the character at the specified position is tab.
+ */
+
+#define IS_TAB_AT(string,offset) CHECK_AT((string),'\t',(offset))
+
+#define IS_TAB(string) IS_TAB_AT((string),0)
+
+/*
+ * Check if the character at the specified position is blank (space or tab).
+ */
+
+#define IS_BLANK_AT(string,offset) \
+ (IS_SPACE_AT((string),(offset)) || IS_TAB_AT((string),(offset)))
+
+#define IS_BLANK(string) IS_BLANK_AT((string),0)
+
+/*
+ * Check if the character at the specified position is a line break.
+ */
+
+#define IS_BREAK_AT(string,offset) \
+ (CHECK_AT((string),'\r',(offset)) /* CR (#xD)*/ \
+ || CHECK_AT((string),'\n',(offset)) /* LF (#xA) */ \
+ || (CHECK_AT((string),'\xC2',(offset)) \
+ && CHECK_AT((string),'\x85',(offset)+1)) /* NEL (#x85) */ \
+ || (CHECK_AT((string),'\xE2',(offset)) \
+ && CHECK_AT((string),'\x80',(offset)+1) \
+ && CHECK_AT((string),'\xA8',(offset)+2)) /* LS (#x2028) */ \
+ || (CHECK_AT((string),'\xE2',(offset)) \
+ && CHECK_AT((string),'\x80',(offset)+1) \
+ && CHECK_AT((string),'\xA9',(offset)+2))) /* PS (#x2029) */
+
+#define IS_BREAK(string) IS_BREAK_AT((string),0)
+
+#define IS_CRLF_AT(string,offset) \
+ (CHECK_AT((string),'\r',(offset)) && CHECK_AT((string),'\n',(offset)+1))
+
+#define IS_CRLF(string) IS_CRLF_AT((string),0)
+
+/*
+ * Check if the character is a line break or NUL.
+ */
+
+#define IS_BREAKZ_AT(string,offset) \
+ (IS_BREAK_AT((string),(offset)) || IS_Z_AT((string),(offset)))
+
+#define IS_BREAKZ(string) IS_BREAKZ_AT((string),0)
+
+/*
+ * Check if the character is a line break, space, or NUL.
+ */
+
+#define IS_SPACEZ_AT(string,offset) \
+ (IS_SPACE_AT((string),(offset)) || IS_BREAKZ_AT((string),(offset)))
+
+#define IS_SPACEZ(string) IS_SPACEZ_AT((string),0)
+
+/*
+ * Check if the character is a line break, space, tab, or NUL.
+ */
+
+#define IS_BLANKZ_AT(string,offset) \
+ (IS_BLANK_AT((string),(offset)) || IS_BREAKZ_AT((string),(offset)))
+
+#define IS_BLANKZ(string) IS_BLANKZ_AT((string),0)
+
+/*
+ * Determine the width of the character.
+ */
+
+#define WIDTH_AT(string,offset) \
+ (((string).pointer[offset] & 0x80) == 0x00 ? 1 : \
+ ((string).pointer[offset] & 0xE0) == 0xC0 ? 2 : \
+ ((string).pointer[offset] & 0xF0) == 0xE0 ? 3 : \
+ ((string).pointer[offset] & 0xF8) == 0xF0 ? 4 : 0)
+
+#define WIDTH(string) WIDTH_AT((string),0)
+
+/*
+ * Move the string pointer to the next character.
+ */
+
+#define MOVE(string) ((string).pointer += WIDTH((string)))
+
+/*
+ * Copy a character and move the pointers of both strings.
+ */
+
+#define COPY(string_a,string_b) \
+ ((*(string_b).pointer & 0x80) == 0x00 ? \
+ (*((string_a).pointer++) = *((string_b).pointer++)) : \
+ (*(string_b).pointer & 0xE0) == 0xC0 ? \
+ (*((string_a).pointer++) = *((string_b).pointer++), \
+ *((string_a).pointer++) = *((string_b).pointer++)) : \
+ (*(string_b).pointer & 0xF0) == 0xE0 ? \
+ (*((string_a).pointer++) = *((string_b).pointer++), \
+ *((string_a).pointer++) = *((string_b).pointer++), \
+ *((string_a).pointer++) = *((string_b).pointer++)) : \
+ (*(string_b).pointer & 0xF8) == 0xF0 ? \
+ (*((string_a).pointer++) = *((string_b).pointer++), \
+ *((string_a).pointer++) = *((string_b).pointer++), \
+ *((string_a).pointer++) = *((string_b).pointer++), \
+ *((string_a).pointer++) = *((string_b).pointer++)) : 0)
+
+/*
+ * Stack and queue management.
+ */
+
+YAML_DECLARE(int)
+yaml_stack_extend(void **start, void **top, void **end);
+
+YAML_DECLARE(int)
+yaml_queue_extend(void **start, void **head, void **tail, void **end);
+
#define STACK_INIT(context,stack,type) \
(((stack).start = (type)yaml_malloc(INITIAL_STACK_SIZE*sizeof(*(stack).start))) ? \
- ((stack).top = (stack).start, \
+ ((stack).top = (stack).start, \
(stack).end = (stack).start+INITIAL_STACK_SIZE, \
- 1) : \
- ((context)->error = YAML_MEMORY_ERROR, \
- 0))
-
-#define STACK_DEL(context,stack) \
- (yaml_free((stack).start), \
- (stack).start = (stack).top = (stack).end = 0)
-
-#define STACK_EMPTY(context,stack) \
- ((stack).start == (stack).top)
-
-#define STACK_LIMIT(context,stack,size) \
- ((stack).top - (stack).start < (size) ? \
- 1 : \
- ((context)->error = YAML_MEMORY_ERROR, \
- 0))
-
-#define PUSH(context,stack,value) \
- (((stack).top != (stack).end \
- || yaml_stack_extend((void **)&(stack).start, \
- (void **)&(stack).top, (void **)&(stack).end)) ? \
- (*((stack).top++) = value, \
- 1) : \
- ((context)->error = YAML_MEMORY_ERROR, \
- 0))
-
-#define POP(context,stack) \
- (*(--(stack).top))
-
+ 1) : \
+ ((context)->error = YAML_MEMORY_ERROR, \
+ 0))
+
+#define STACK_DEL(context,stack) \
+ (yaml_free((stack).start), \
+ (stack).start = (stack).top = (stack).end = 0)
+
+#define STACK_EMPTY(context,stack) \
+ ((stack).start == (stack).top)
+
+#define STACK_LIMIT(context,stack,size) \
+ ((stack).top - (stack).start < (size) ? \
+ 1 : \
+ ((context)->error = YAML_MEMORY_ERROR, \
+ 0))
+
+#define PUSH(context,stack,value) \
+ (((stack).top != (stack).end \
+ || yaml_stack_extend((void **)&(stack).start, \
+ (void **)&(stack).top, (void **)&(stack).end)) ? \
+ (*((stack).top++) = value, \
+ 1) : \
+ ((context)->error = YAML_MEMORY_ERROR, \
+ 0))
+
+#define POP(context,stack) \
+ (*(--(stack).top))
+
#define QUEUE_INIT(context,queue,size,type) \
(((queue).start = (type)yaml_malloc((size)*sizeof(*(queue).start))) ? \
- ((queue).head = (queue).tail = (queue).start, \
- (queue).end = (queue).start+(size), \
- 1) : \
- ((context)->error = YAML_MEMORY_ERROR, \
- 0))
-
-#define QUEUE_DEL(context,queue) \
- (yaml_free((queue).start), \
- (queue).start = (queue).head = (queue).tail = (queue).end = 0)
-
-#define QUEUE_EMPTY(context,queue) \
- ((queue).head == (queue).tail)
-
-#define ENQUEUE(context,queue,value) \
- (((queue).tail != (queue).end \
- || yaml_queue_extend((void **)&(queue).start, (void **)&(queue).head, \
- (void **)&(queue).tail, (void **)&(queue).end)) ? \
- (*((queue).tail++) = value, \
- 1) : \
- ((context)->error = YAML_MEMORY_ERROR, \
- 0))
-
-#define DEQUEUE(context,queue) \
- (*((queue).head++))
-
-#define QUEUE_INSERT(context,queue,index,value) \
- (((queue).tail != (queue).end \
- || yaml_queue_extend((void **)&(queue).start, (void **)&(queue).head, \
- (void **)&(queue).tail, (void **)&(queue).end)) ? \
- (memmove((queue).head+(index)+1,(queue).head+(index), \
- ((queue).tail-(queue).head-(index))*sizeof(*(queue).start)), \
- *((queue).head+(index)) = value, \
- (queue).tail++, \
- 1) : \
- ((context)->error = YAML_MEMORY_ERROR, \
- 0))
-
-/*
- * Token initializers.
- */
-
-#define TOKEN_INIT(token,token_type,token_start_mark,token_end_mark) \
- (memset(&(token), 0, sizeof(yaml_token_t)), \
- (token).type = (token_type), \
- (token).start_mark = (token_start_mark), \
- (token).end_mark = (token_end_mark))
-
-#define STREAM_START_TOKEN_INIT(token,token_encoding,start_mark,end_mark) \
- (TOKEN_INIT((token),YAML_STREAM_START_TOKEN,(start_mark),(end_mark)), \
- (token).data.stream_start.encoding = (token_encoding))
-
-#define STREAM_END_TOKEN_INIT(token,start_mark,end_mark) \
- (TOKEN_INIT((token),YAML_STREAM_END_TOKEN,(start_mark),(end_mark)))
-
-#define ALIAS_TOKEN_INIT(token,token_value,start_mark,end_mark) \
- (TOKEN_INIT((token),YAML_ALIAS_TOKEN,(start_mark),(end_mark)), \
- (token).data.alias.value = (token_value))
-
-#define ANCHOR_TOKEN_INIT(token,token_value,start_mark,end_mark) \
- (TOKEN_INIT((token),YAML_ANCHOR_TOKEN,(start_mark),(end_mark)), \
- (token).data.anchor.value = (token_value))
-
-#define TAG_TOKEN_INIT(token,token_handle,token_suffix,start_mark,end_mark) \
- (TOKEN_INIT((token),YAML_TAG_TOKEN,(start_mark),(end_mark)), \
- (token).data.tag.handle = (token_handle), \
- (token).data.tag.suffix = (token_suffix))
-
-#define SCALAR_TOKEN_INIT(token,token_value,token_length,token_style,start_mark,end_mark) \
- (TOKEN_INIT((token),YAML_SCALAR_TOKEN,(start_mark),(end_mark)), \
- (token).data.scalar.value = (token_value), \
- (token).data.scalar.length = (token_length), \
- (token).data.scalar.style = (token_style))
-
-#define VERSION_DIRECTIVE_TOKEN_INIT(token,token_major,token_minor,start_mark,end_mark) \
- (TOKEN_INIT((token),YAML_VERSION_DIRECTIVE_TOKEN,(start_mark),(end_mark)), \
- (token).data.version_directive.major = (token_major), \
- (token).data.version_directive.minor = (token_minor))
-
-#define TAG_DIRECTIVE_TOKEN_INIT(token,token_handle,token_prefix,start_mark,end_mark) \
- (TOKEN_INIT((token),YAML_TAG_DIRECTIVE_TOKEN,(start_mark),(end_mark)), \
- (token).data.tag_directive.handle = (token_handle), \
- (token).data.tag_directive.prefix = (token_prefix))
-
-/*
- * Event initializers.
- */
-
-#define EVENT_INIT(event,event_type,event_start_mark,event_end_mark) \
- (memset(&(event), 0, sizeof(yaml_event_t)), \
- (event).type = (event_type), \
- (event).start_mark = (event_start_mark), \
- (event).end_mark = (event_end_mark))
-
-#define STREAM_START_EVENT_INIT(event,event_encoding,start_mark,end_mark) \
- (EVENT_INIT((event),YAML_STREAM_START_EVENT,(start_mark),(end_mark)), \
- (event).data.stream_start.encoding = (event_encoding))
-
-#define STREAM_END_EVENT_INIT(event,start_mark,end_mark) \
- (EVENT_INIT((event),YAML_STREAM_END_EVENT,(start_mark),(end_mark)))
-
-#define DOCUMENT_START_EVENT_INIT(event,event_version_directive, \
- event_tag_directives_start,event_tag_directives_end,event_implicit,start_mark,end_mark) \
- (EVENT_INIT((event),YAML_DOCUMENT_START_EVENT,(start_mark),(end_mark)), \
- (event).data.document_start.version_directive = (event_version_directive), \
- (event).data.document_start.tag_directives.start = (event_tag_directives_start), \
- (event).data.document_start.tag_directives.end = (event_tag_directives_end), \
- (event).data.document_start.implicit = (event_implicit))
-
-#define DOCUMENT_END_EVENT_INIT(event,event_implicit,start_mark,end_mark) \
- (EVENT_INIT((event),YAML_DOCUMENT_END_EVENT,(start_mark),(end_mark)), \
- (event).data.document_end.implicit = (event_implicit))
-
-#define ALIAS_EVENT_INIT(event,event_anchor,start_mark,end_mark) \
- (EVENT_INIT((event),YAML_ALIAS_EVENT,(start_mark),(end_mark)), \
- (event).data.alias.anchor = (event_anchor))
-
-#define SCALAR_EVENT_INIT(event,event_anchor,event_tag,event_value,event_length, \
- event_plain_implicit, event_quoted_implicit,event_style,start_mark,end_mark) \
- (EVENT_INIT((event),YAML_SCALAR_EVENT,(start_mark),(end_mark)), \
- (event).data.scalar.anchor = (event_anchor), \
- (event).data.scalar.tag = (event_tag), \
- (event).data.scalar.value = (event_value), \
- (event).data.scalar.length = (event_length), \
- (event).data.scalar.plain_implicit = (event_plain_implicit), \
- (event).data.scalar.quoted_implicit = (event_quoted_implicit), \
- (event).data.scalar.style = (event_style))
-
-#define SEQUENCE_START_EVENT_INIT(event,event_anchor,event_tag, \
- event_implicit,event_style,start_mark,end_mark) \
- (EVENT_INIT((event),YAML_SEQUENCE_START_EVENT,(start_mark),(end_mark)), \
- (event).data.sequence_start.anchor = (event_anchor), \
- (event).data.sequence_start.tag = (event_tag), \
- (event).data.sequence_start.implicit = (event_implicit), \
- (event).data.sequence_start.style = (event_style))
-
-#define SEQUENCE_END_EVENT_INIT(event,start_mark,end_mark) \
- (EVENT_INIT((event),YAML_SEQUENCE_END_EVENT,(start_mark),(end_mark)))
-
-#define MAPPING_START_EVENT_INIT(event,event_anchor,event_tag, \
- event_implicit,event_style,start_mark,end_mark) \
- (EVENT_INIT((event),YAML_MAPPING_START_EVENT,(start_mark),(end_mark)), \
- (event).data.mapping_start.anchor = (event_anchor), \
- (event).data.mapping_start.tag = (event_tag), \
- (event).data.mapping_start.implicit = (event_implicit), \
- (event).data.mapping_start.style = (event_style))
-
-#define MAPPING_END_EVENT_INIT(event,start_mark,end_mark) \
- (EVENT_INIT((event),YAML_MAPPING_END_EVENT,(start_mark),(end_mark)))
-
-/*
- * Document initializer.
- */
-
-#define DOCUMENT_INIT(document,document_nodes_start,document_nodes_end, \
- document_version_directive,document_tag_directives_start, \
- document_tag_directives_end,document_start_implicit, \
- document_end_implicit,document_start_mark,document_end_mark) \
- (memset(&(document), 0, sizeof(yaml_document_t)), \
- (document).nodes.start = (document_nodes_start), \
- (document).nodes.end = (document_nodes_end), \
- (document).nodes.top = (document_nodes_start), \
- (document).version_directive = (document_version_directive), \
- (document).tag_directives.start = (document_tag_directives_start), \
- (document).tag_directives.end = (document_tag_directives_end), \
- (document).start_implicit = (document_start_implicit), \
- (document).end_implicit = (document_end_implicit), \
- (document).start_mark = (document_start_mark), \
- (document).end_mark = (document_end_mark))
-
-/*
- * Node initializers.
- */
-
-#define NODE_INIT(node,node_type,node_tag,node_start_mark,node_end_mark) \
- (memset(&(node), 0, sizeof(yaml_node_t)), \
- (node).type = (node_type), \
- (node).tag = (node_tag), \
- (node).start_mark = (node_start_mark), \
- (node).end_mark = (node_end_mark))
-
-#define SCALAR_NODE_INIT(node,node_tag,node_value,node_length, \
- node_style,start_mark,end_mark) \
- (NODE_INIT((node),YAML_SCALAR_NODE,(node_tag),(start_mark),(end_mark)), \
- (node).data.scalar.value = (node_value), \
- (node).data.scalar.length = (node_length), \
- (node).data.scalar.style = (node_style))
-
-#define SEQUENCE_NODE_INIT(node,node_tag,node_items_start,node_items_end, \
- node_style,start_mark,end_mark) \
- (NODE_INIT((node),YAML_SEQUENCE_NODE,(node_tag),(start_mark),(end_mark)), \
- (node).data.sequence.items.start = (node_items_start), \
- (node).data.sequence.items.end = (node_items_end), \
- (node).data.sequence.items.top = (node_items_start), \
- (node).data.sequence.style = (node_style))
-
-#define MAPPING_NODE_INIT(node,node_tag,node_pairs_start,node_pairs_end, \
- node_style,start_mark,end_mark) \
- (NODE_INIT((node),YAML_MAPPING_NODE,(node_tag),(start_mark),(end_mark)), \
- (node).data.mapping.pairs.start = (node_pairs_start), \
- (node).data.mapping.pairs.end = (node_pairs_end), \
- (node).data.mapping.pairs.top = (node_pairs_start), \
- (node).data.mapping.style = (node_style))
-
+ ((queue).head = (queue).tail = (queue).start, \
+ (queue).end = (queue).start+(size), \
+ 1) : \
+ ((context)->error = YAML_MEMORY_ERROR, \
+ 0))
+
+#define QUEUE_DEL(context,queue) \
+ (yaml_free((queue).start), \
+ (queue).start = (queue).head = (queue).tail = (queue).end = 0)
+
+#define QUEUE_EMPTY(context,queue) \
+ ((queue).head == (queue).tail)
+
+#define ENQUEUE(context,queue,value) \
+ (((queue).tail != (queue).end \
+ || yaml_queue_extend((void **)&(queue).start, (void **)&(queue).head, \
+ (void **)&(queue).tail, (void **)&(queue).end)) ? \
+ (*((queue).tail++) = value, \
+ 1) : \
+ ((context)->error = YAML_MEMORY_ERROR, \
+ 0))
+
+#define DEQUEUE(context,queue) \
+ (*((queue).head++))
+
+#define QUEUE_INSERT(context,queue,index,value) \
+ (((queue).tail != (queue).end \
+ || yaml_queue_extend((void **)&(queue).start, (void **)&(queue).head, \
+ (void **)&(queue).tail, (void **)&(queue).end)) ? \
+ (memmove((queue).head+(index)+1,(queue).head+(index), \
+ ((queue).tail-(queue).head-(index))*sizeof(*(queue).start)), \
+ *((queue).head+(index)) = value, \
+ (queue).tail++, \
+ 1) : \
+ ((context)->error = YAML_MEMORY_ERROR, \
+ 0))
+
+/*
+ * Token initializers.
+ */
+
+#define TOKEN_INIT(token,token_type,token_start_mark,token_end_mark) \
+ (memset(&(token), 0, sizeof(yaml_token_t)), \
+ (token).type = (token_type), \
+ (token).start_mark = (token_start_mark), \
+ (token).end_mark = (token_end_mark))
+
+#define STREAM_START_TOKEN_INIT(token,token_encoding,start_mark,end_mark) \
+ (TOKEN_INIT((token),YAML_STREAM_START_TOKEN,(start_mark),(end_mark)), \
+ (token).data.stream_start.encoding = (token_encoding))
+
+#define STREAM_END_TOKEN_INIT(token,start_mark,end_mark) \
+ (TOKEN_INIT((token),YAML_STREAM_END_TOKEN,(start_mark),(end_mark)))
+
+#define ALIAS_TOKEN_INIT(token,token_value,start_mark,end_mark) \
+ (TOKEN_INIT((token),YAML_ALIAS_TOKEN,(start_mark),(end_mark)), \
+ (token).data.alias.value = (token_value))
+
+#define ANCHOR_TOKEN_INIT(token,token_value,start_mark,end_mark) \
+ (TOKEN_INIT((token),YAML_ANCHOR_TOKEN,(start_mark),(end_mark)), \
+ (token).data.anchor.value = (token_value))
+
+#define TAG_TOKEN_INIT(token,token_handle,token_suffix,start_mark,end_mark) \
+ (TOKEN_INIT((token),YAML_TAG_TOKEN,(start_mark),(end_mark)), \
+ (token).data.tag.handle = (token_handle), \
+ (token).data.tag.suffix = (token_suffix))
+
+#define SCALAR_TOKEN_INIT(token,token_value,token_length,token_style,start_mark,end_mark) \
+ (TOKEN_INIT((token),YAML_SCALAR_TOKEN,(start_mark),(end_mark)), \
+ (token).data.scalar.value = (token_value), \
+ (token).data.scalar.length = (token_length), \
+ (token).data.scalar.style = (token_style))
+
+#define VERSION_DIRECTIVE_TOKEN_INIT(token,token_major,token_minor,start_mark,end_mark) \
+ (TOKEN_INIT((token),YAML_VERSION_DIRECTIVE_TOKEN,(start_mark),(end_mark)), \
+ (token).data.version_directive.major = (token_major), \
+ (token).data.version_directive.minor = (token_minor))
+
+#define TAG_DIRECTIVE_TOKEN_INIT(token,token_handle,token_prefix,start_mark,end_mark) \
+ (TOKEN_INIT((token),YAML_TAG_DIRECTIVE_TOKEN,(start_mark),(end_mark)), \
+ (token).data.tag_directive.handle = (token_handle), \
+ (token).data.tag_directive.prefix = (token_prefix))
+
+/*
+ * Event initializers.
+ */
+
+#define EVENT_INIT(event,event_type,event_start_mark,event_end_mark) \
+ (memset(&(event), 0, sizeof(yaml_event_t)), \
+ (event).type = (event_type), \
+ (event).start_mark = (event_start_mark), \
+ (event).end_mark = (event_end_mark))
+
+#define STREAM_START_EVENT_INIT(event,event_encoding,start_mark,end_mark) \
+ (EVENT_INIT((event),YAML_STREAM_START_EVENT,(start_mark),(end_mark)), \
+ (event).data.stream_start.encoding = (event_encoding))
+
+#define STREAM_END_EVENT_INIT(event,start_mark,end_mark) \
+ (EVENT_INIT((event),YAML_STREAM_END_EVENT,(start_mark),(end_mark)))
+
+#define DOCUMENT_START_EVENT_INIT(event,event_version_directive, \
+ event_tag_directives_start,event_tag_directives_end,event_implicit,start_mark,end_mark) \
+ (EVENT_INIT((event),YAML_DOCUMENT_START_EVENT,(start_mark),(end_mark)), \
+ (event).data.document_start.version_directive = (event_version_directive), \
+ (event).data.document_start.tag_directives.start = (event_tag_directives_start), \
+ (event).data.document_start.tag_directives.end = (event_tag_directives_end), \
+ (event).data.document_start.implicit = (event_implicit))
+
+#define DOCUMENT_END_EVENT_INIT(event,event_implicit,start_mark,end_mark) \
+ (EVENT_INIT((event),YAML_DOCUMENT_END_EVENT,(start_mark),(end_mark)), \
+ (event).data.document_end.implicit = (event_implicit))
+
+#define ALIAS_EVENT_INIT(event,event_anchor,start_mark,end_mark) \
+ (EVENT_INIT((event),YAML_ALIAS_EVENT,(start_mark),(end_mark)), \
+ (event).data.alias.anchor = (event_anchor))
+
+#define SCALAR_EVENT_INIT(event,event_anchor,event_tag,event_value,event_length, \
+ event_plain_implicit, event_quoted_implicit,event_style,start_mark,end_mark) \
+ (EVENT_INIT((event),YAML_SCALAR_EVENT,(start_mark),(end_mark)), \
+ (event).data.scalar.anchor = (event_anchor), \
+ (event).data.scalar.tag = (event_tag), \
+ (event).data.scalar.value = (event_value), \
+ (event).data.scalar.length = (event_length), \
+ (event).data.scalar.plain_implicit = (event_plain_implicit), \
+ (event).data.scalar.quoted_implicit = (event_quoted_implicit), \
+ (event).data.scalar.style = (event_style))
+
+#define SEQUENCE_START_EVENT_INIT(event,event_anchor,event_tag, \
+ event_implicit,event_style,start_mark,end_mark) \
+ (EVENT_INIT((event),YAML_SEQUENCE_START_EVENT,(start_mark),(end_mark)), \
+ (event).data.sequence_start.anchor = (event_anchor), \
+ (event).data.sequence_start.tag = (event_tag), \
+ (event).data.sequence_start.implicit = (event_implicit), \
+ (event).data.sequence_start.style = (event_style))
+
+#define SEQUENCE_END_EVENT_INIT(event,start_mark,end_mark) \
+ (EVENT_INIT((event),YAML_SEQUENCE_END_EVENT,(start_mark),(end_mark)))
+
+#define MAPPING_START_EVENT_INIT(event,event_anchor,event_tag, \
+ event_implicit,event_style,start_mark,end_mark) \
+ (EVENT_INIT((event),YAML_MAPPING_START_EVENT,(start_mark),(end_mark)), \
+ (event).data.mapping_start.anchor = (event_anchor), \
+ (event).data.mapping_start.tag = (event_tag), \
+ (event).data.mapping_start.implicit = (event_implicit), \
+ (event).data.mapping_start.style = (event_style))
+
+#define MAPPING_END_EVENT_INIT(event,start_mark,end_mark) \
+ (EVENT_INIT((event),YAML_MAPPING_END_EVENT,(start_mark),(end_mark)))
+
+/*
+ * Document initializer.
+ */
+
+#define DOCUMENT_INIT(document,document_nodes_start,document_nodes_end, \
+ document_version_directive,document_tag_directives_start, \
+ document_tag_directives_end,document_start_implicit, \
+ document_end_implicit,document_start_mark,document_end_mark) \
+ (memset(&(document), 0, sizeof(yaml_document_t)), \
+ (document).nodes.start = (document_nodes_start), \
+ (document).nodes.end = (document_nodes_end), \
+ (document).nodes.top = (document_nodes_start), \
+ (document).version_directive = (document_version_directive), \
+ (document).tag_directives.start = (document_tag_directives_start), \
+ (document).tag_directives.end = (document_tag_directives_end), \
+ (document).start_implicit = (document_start_implicit), \
+ (document).end_implicit = (document_end_implicit), \
+ (document).start_mark = (document_start_mark), \
+ (document).end_mark = (document_end_mark))
+
+/*
+ * Node initializers.
+ */
+
+#define NODE_INIT(node,node_type,node_tag,node_start_mark,node_end_mark) \
+ (memset(&(node), 0, sizeof(yaml_node_t)), \
+ (node).type = (node_type), \
+ (node).tag = (node_tag), \
+ (node).start_mark = (node_start_mark), \
+ (node).end_mark = (node_end_mark))
+
+#define SCALAR_NODE_INIT(node,node_tag,node_value,node_length, \
+ node_style,start_mark,end_mark) \
+ (NODE_INIT((node),YAML_SCALAR_NODE,(node_tag),(start_mark),(end_mark)), \
+ (node).data.scalar.value = (node_value), \
+ (node).data.scalar.length = (node_length), \
+ (node).data.scalar.style = (node_style))
+
+#define SEQUENCE_NODE_INIT(node,node_tag,node_items_start,node_items_end, \
+ node_style,start_mark,end_mark) \
+ (NODE_INIT((node),YAML_SEQUENCE_NODE,(node_tag),(start_mark),(end_mark)), \
+ (node).data.sequence.items.start = (node_items_start), \
+ (node).data.sequence.items.end = (node_items_end), \
+ (node).data.sequence.items.top = (node_items_start), \
+ (node).data.sequence.style = (node_style))
+
+#define MAPPING_NODE_INIT(node,node_tag,node_pairs_start,node_pairs_end, \
+ node_style,start_mark,end_mark) \
+ (NODE_INIT((node),YAML_MAPPING_NODE,(node_tag),(start_mark),(end_mark)), \
+ (node).data.mapping.pairs.start = (node_pairs_start), \
+ (node).data.mapping.pairs.end = (node_pairs_end), \
+ (node).data.mapping.pairs.top = (node_pairs_start), \
+ (node).data.mapping.style = (node_style))
+
/* Strict C compiler warning helpers */
#if defined(__clang__) || defined(__GNUC__)
diff --git a/contrib/libs/yaml/ya.make b/contrib/libs/yaml/ya.make
index 04261e8373..547a2b2a63 100644
--- a/contrib/libs/yaml/ya.make
+++ b/contrib/libs/yaml/ya.make
@@ -1,7 +1,7 @@
# Generated by devtools/yamaker from nixpkgs 21.11.
-LIBRARY()
-
+LIBRARY()
+
OWNER(
borman
g:cpp-contrib
@@ -15,28 +15,28 @@ LICENSE(MIT)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-ADDINCL(
- GLOBAL contrib/libs/yaml/include
+ADDINCL(
+ GLOBAL contrib/libs/yaml/include
contrib/libs/yaml/src
-)
-
-NO_COMPILER_WARNINGS()
-
+)
+
+NO_COMPILER_WARNINGS()
+
NO_RUNTIME()
CFLAGS(
-DHAVE_CONFIG_H
)
-SRCS(
- src/api.c
- src/dumper.c
- src/emitter.c
- src/loader.c
- src/parser.c
- src/reader.c
- src/scanner.c
- src/writer.c
-)
-
-END()
+SRCS(
+ src/api.c
+ src/dumper.c
+ src/emitter.c
+ src/loader.c
+ src/parser.c
+ src/reader.c
+ src/scanner.c
+ src/writer.c
+)
+
+END()
diff --git a/contrib/libs/zlib/ya.make b/contrib/libs/zlib/ya.make
index 5c9e47a1e3..ced6573475 100644
--- a/contrib/libs/zlib/ya.make
+++ b/contrib/libs/zlib/ya.make
@@ -16,7 +16,7 @@ OPENSOURCE_EXPORT_REPLACEMENT(
LICENSE(Zlib)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
+
ADDINCL(
GLOBAL contrib/libs/zlib/include
)
diff --git a/contrib/python/PyYAML/py2/LICENSE b/contrib/python/PyYAML/py2/LICENSE
index 63edc20f2f..2f1b8e15e5 100644
--- a/contrib/python/PyYAML/py2/LICENSE
+++ b/contrib/python/PyYAML/py2/LICENSE
@@ -1,20 +1,20 @@
Copyright (c) 2017-2021 Ingy döt Net
Copyright (c) 2006-2016 Kirill Simonov
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-of the Software, and to permit persons to whom the Software is furnished to do
-so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/contrib/python/PyYAML/py2/ya.make b/contrib/python/PyYAML/py2/ya.make
index ca2ec858c2..1ec5c0c301 100644
--- a/contrib/python/PyYAML/py2/ya.make
+++ b/contrib/python/PyYAML/py2/ya.make
@@ -1,43 +1,43 @@
PY2_LIBRARY()
-
+
LICENSE(MIT)
VERSION(5.4.1)
OWNER(g:python-contrib borman g:testenv)
-
+
PEERDIR(
contrib/libs/yaml
)
-
+
ADDINCL(
contrib/python/PyYAML/py2/yaml
)
-PY_SRCS(
- TOP_LEVEL
+PY_SRCS(
+ TOP_LEVEL
_yaml/__init__.py
- yaml/__init__.py
- yaml/composer.py
- yaml/constructor.py
- yaml/cyaml.py
- yaml/dumper.py
- yaml/emitter.py
- yaml/error.py
- yaml/events.py
- yaml/loader.py
- yaml/nodes.py
- yaml/parser.py
- yaml/reader.py
- yaml/representer.py
- yaml/resolver.py
- yaml/scanner.py
- yaml/serializer.py
- yaml/tokens.py
+ yaml/__init__.py
+ yaml/composer.py
+ yaml/constructor.py
+ yaml/cyaml.py
+ yaml/dumper.py
+ yaml/emitter.py
+ yaml/error.py
+ yaml/events.py
+ yaml/loader.py
+ yaml/nodes.py
+ yaml/parser.py
+ yaml/reader.py
+ yaml/representer.py
+ yaml/resolver.py
+ yaml/scanner.py
+ yaml/serializer.py
+ yaml/tokens.py
CYTHON_C
yaml/_yaml.pyx
-)
-
+)
+
RESOURCE_FILES(
PREFIX contrib/python/PyYAML/
.dist-info/METADATA
@@ -48,4 +48,4 @@ NO_LINT()
NO_COMPILER_WARNINGS()
-END()
+END()
diff --git a/contrib/python/PyYAML/py2/yaml/__init__.py b/contrib/python/PyYAML/py2/yaml/__init__.py
index fcdf708064..3c988198d5 100644
--- a/contrib/python/PyYAML/py2/yaml/__init__.py
+++ b/contrib/python/PyYAML/py2/yaml/__init__.py
@@ -1,21 +1,21 @@
-
-from error import *
-
-from tokens import *
-from events import *
-from nodes import *
-
-from loader import *
-from dumper import *
-
+
+from error import *
+
+from tokens import *
+from events import *
+from nodes import *
+
+from loader import *
+from dumper import *
+
__version__ = '5.4.1'
-
-try:
- from cyaml import *
- __with_libyaml__ = True
-except ImportError:
- __with_libyaml__ = False
-
+
+try:
+ from cyaml import *
+ __with_libyaml__ = True
+except ImportError:
+ __with_libyaml__ = False
+
#------------------------------------------------------------------------------
# Warnings control
@@ -55,82 +55,82 @@ def load_warning(method):
warnings.warn(message, YAMLLoadWarning, stacklevel=3)
#------------------------------------------------------------------------------
-def scan(stream, Loader=Loader):
- """
- Scan a YAML stream and produce scanning tokens.
- """
- loader = Loader(stream)
- try:
- while loader.check_token():
- yield loader.get_token()
- finally:
- loader.dispose()
-
-def parse(stream, Loader=Loader):
- """
- Parse a YAML stream and produce parsing events.
- """
- loader = Loader(stream)
- try:
- while loader.check_event():
- yield loader.get_event()
- finally:
- loader.dispose()
-
-def compose(stream, Loader=Loader):
- """
- Parse the first YAML document in a stream
- and produce the corresponding representation tree.
- """
- loader = Loader(stream)
- try:
- return loader.get_single_node()
- finally:
- loader.dispose()
-
-def compose_all(stream, Loader=Loader):
- """
- Parse all YAML documents in a stream
- and produce corresponding representation trees.
- """
- loader = Loader(stream)
- try:
- while loader.check_node():
- yield loader.get_node()
- finally:
- loader.dispose()
-
+def scan(stream, Loader=Loader):
+ """
+ Scan a YAML stream and produce scanning tokens.
+ """
+ loader = Loader(stream)
+ try:
+ while loader.check_token():
+ yield loader.get_token()
+ finally:
+ loader.dispose()
+
+def parse(stream, Loader=Loader):
+ """
+ Parse a YAML stream and produce parsing events.
+ """
+ loader = Loader(stream)
+ try:
+ while loader.check_event():
+ yield loader.get_event()
+ finally:
+ loader.dispose()
+
+def compose(stream, Loader=Loader):
+ """
+ Parse the first YAML document in a stream
+ and produce the corresponding representation tree.
+ """
+ loader = Loader(stream)
+ try:
+ return loader.get_single_node()
+ finally:
+ loader.dispose()
+
+def compose_all(stream, Loader=Loader):
+ """
+ Parse all YAML documents in a stream
+ and produce corresponding representation trees.
+ """
+ loader = Loader(stream)
+ try:
+ while loader.check_node():
+ yield loader.get_node()
+ finally:
+ loader.dispose()
+
def load(stream, Loader=None):
- """
- Parse the first YAML document in a stream
- and produce the corresponding Python object.
- """
+ """
+ Parse the first YAML document in a stream
+ and produce the corresponding Python object.
+ """
if Loader is None:
load_warning('load')
Loader = FullLoader
- loader = Loader(stream)
- try:
- return loader.get_single_data()
- finally:
- loader.dispose()
-
+ loader = Loader(stream)
+ try:
+ return loader.get_single_data()
+ finally:
+ loader.dispose()
+
def load_all(stream, Loader=None):
- """
- Parse all YAML documents in a stream
- and produce corresponding Python objects.
- """
+ """
+ Parse all YAML documents in a stream
+ and produce corresponding Python objects.
+ """
if Loader is None:
load_warning('load_all')
Loader = FullLoader
- loader = Loader(stream)
- try:
- while loader.check_data():
- yield loader.get_data()
- finally:
- loader.dispose()
-
+ loader = Loader(stream)
+ try:
+ while loader.check_data():
+ yield loader.get_data()
+ finally:
+ loader.dispose()
+
def full_load(stream):
"""
Parse the first YAML document in a stream
@@ -151,26 +151,26 @@ def full_load_all(stream):
"""
return load_all(stream, FullLoader)
-def safe_load(stream):
- """
- Parse the first YAML document in a stream
- and produce the corresponding Python object.
+def safe_load(stream):
+ """
+ Parse the first YAML document in a stream
+ and produce the corresponding Python object.
Resolve only basic YAML tags. This is known
to be safe for untrusted input.
- """
- return load(stream, SafeLoader)
-
-def safe_load_all(stream):
- """
- Parse all YAML documents in a stream
- and produce corresponding Python objects.
+ """
+ return load(stream, SafeLoader)
+
+def safe_load_all(stream):
+ """
+ Parse all YAML documents in a stream
+ and produce corresponding Python objects.
Resolve only basic YAML tags. This is known
to be safe for untrusted input.
- """
- return load_all(stream, SafeLoader)
-
+ """
+ return load_all(stream, SafeLoader)
+
def unsafe_load(stream):
"""
Parse the first YAML document in a stream
@@ -191,241 +191,241 @@ def unsafe_load_all(stream):
"""
return load_all(stream, UnsafeLoader)
-def emit(events, stream=None, Dumper=Dumper,
- canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None):
- """
- Emit YAML parsing events into a stream.
- If stream is None, return the produced string instead.
- """
- getvalue = None
- if stream is None:
- from StringIO import StringIO
- stream = StringIO()
- getvalue = stream.getvalue
- dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
- allow_unicode=allow_unicode, line_break=line_break)
- try:
- for event in events:
- dumper.emit(event)
- finally:
- dumper.dispose()
- if getvalue:
- return getvalue()
-
-def serialize_all(nodes, stream=None, Dumper=Dumper,
- canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None,
- encoding='utf-8', explicit_start=None, explicit_end=None,
- version=None, tags=None):
- """
- Serialize a sequence of representation trees into a YAML stream.
- If stream is None, return the produced string instead.
- """
- getvalue = None
- if stream is None:
- if encoding is None:
- from StringIO import StringIO
- else:
- from cStringIO import StringIO
- stream = StringIO()
- getvalue = stream.getvalue
- dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
- allow_unicode=allow_unicode, line_break=line_break,
- encoding=encoding, version=version, tags=tags,
- explicit_start=explicit_start, explicit_end=explicit_end)
- try:
- dumper.open()
- for node in nodes:
- dumper.serialize(node)
- dumper.close()
- finally:
- dumper.dispose()
- if getvalue:
- return getvalue()
-
-def serialize(node, stream=None, Dumper=Dumper, **kwds):
- """
- Serialize a representation tree into a YAML stream.
- If stream is None, return the produced string instead.
- """
- return serialize_all([node], stream, Dumper=Dumper, **kwds)
-
-def dump_all(documents, stream=None, Dumper=Dumper,
+def emit(events, stream=None, Dumper=Dumper,
+ canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None):
+ """
+ Emit YAML parsing events into a stream.
+ If stream is None, return the produced string instead.
+ """
+ getvalue = None
+ if stream is None:
+ from StringIO import StringIO
+ stream = StringIO()
+ getvalue = stream.getvalue
+ dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
+ allow_unicode=allow_unicode, line_break=line_break)
+ try:
+ for event in events:
+ dumper.emit(event)
+ finally:
+ dumper.dispose()
+ if getvalue:
+ return getvalue()
+
+def serialize_all(nodes, stream=None, Dumper=Dumper,
+ canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None,
+ encoding='utf-8', explicit_start=None, explicit_end=None,
+ version=None, tags=None):
+ """
+ Serialize a sequence of representation trees into a YAML stream.
+ If stream is None, return the produced string instead.
+ """
+ getvalue = None
+ if stream is None:
+ if encoding is None:
+ from StringIO import StringIO
+ else:
+ from cStringIO import StringIO
+ stream = StringIO()
+ getvalue = stream.getvalue
+ dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
+ allow_unicode=allow_unicode, line_break=line_break,
+ encoding=encoding, version=version, tags=tags,
+ explicit_start=explicit_start, explicit_end=explicit_end)
+ try:
+ dumper.open()
+ for node in nodes:
+ dumper.serialize(node)
+ dumper.close()
+ finally:
+ dumper.dispose()
+ if getvalue:
+ return getvalue()
+
+def serialize(node, stream=None, Dumper=Dumper, **kwds):
+ """
+ Serialize a representation tree into a YAML stream.
+ If stream is None, return the produced string instead.
+ """
+ return serialize_all([node], stream, Dumper=Dumper, **kwds)
+
+def dump_all(documents, stream=None, Dumper=Dumper,
default_style=None, default_flow_style=False,
- canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None,
- encoding='utf-8', explicit_start=None, explicit_end=None,
+ canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None,
+ encoding='utf-8', explicit_start=None, explicit_end=None,
version=None, tags=None, sort_keys=True):
- """
- Serialize a sequence of Python objects into a YAML stream.
- If stream is None, return the produced string instead.
- """
- getvalue = None
- if stream is None:
- if encoding is None:
- from StringIO import StringIO
- else:
- from cStringIO import StringIO
- stream = StringIO()
- getvalue = stream.getvalue
- dumper = Dumper(stream, default_style=default_style,
- default_flow_style=default_flow_style,
- canonical=canonical, indent=indent, width=width,
- allow_unicode=allow_unicode, line_break=line_break,
- encoding=encoding, version=version, tags=tags,
+ """
+ Serialize a sequence of Python objects into a YAML stream.
+ If stream is None, return the produced string instead.
+ """
+ getvalue = None
+ if stream is None:
+ if encoding is None:
+ from StringIO import StringIO
+ else:
+ from cStringIO import StringIO
+ stream = StringIO()
+ getvalue = stream.getvalue
+ dumper = Dumper(stream, default_style=default_style,
+ default_flow_style=default_flow_style,
+ canonical=canonical, indent=indent, width=width,
+ allow_unicode=allow_unicode, line_break=line_break,
+ encoding=encoding, version=version, tags=tags,
explicit_start=explicit_start, explicit_end=explicit_end, sort_keys=sort_keys)
- try:
- dumper.open()
- for data in documents:
- dumper.represent(data)
- dumper.close()
- finally:
- dumper.dispose()
- if getvalue:
- return getvalue()
-
-def dump(data, stream=None, Dumper=Dumper, **kwds):
- """
- Serialize a Python object into a YAML stream.
- If stream is None, return the produced string instead.
- """
- return dump_all([data], stream, Dumper=Dumper, **kwds)
-
-def safe_dump_all(documents, stream=None, **kwds):
- """
- Serialize a sequence of Python objects into a YAML stream.
- Produce only basic YAML tags.
- If stream is None, return the produced string instead.
- """
- return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
-
-def safe_dump(data, stream=None, **kwds):
- """
- Serialize a Python object into a YAML stream.
- Produce only basic YAML tags.
- If stream is None, return the produced string instead.
- """
- return dump_all([data], stream, Dumper=SafeDumper, **kwds)
-
-def add_implicit_resolver(tag, regexp, first=None,
+ try:
+ dumper.open()
+ for data in documents:
+ dumper.represent(data)
+ dumper.close()
+ finally:
+ dumper.dispose()
+ if getvalue:
+ return getvalue()
+
+def dump(data, stream=None, Dumper=Dumper, **kwds):
+ """
+ Serialize a Python object into a YAML stream.
+ If stream is None, return the produced string instead.
+ """
+ return dump_all([data], stream, Dumper=Dumper, **kwds)
+
+def safe_dump_all(documents, stream=None, **kwds):
+ """
+ Serialize a sequence of Python objects into a YAML stream.
+ Produce only basic YAML tags.
+ If stream is None, return the produced string instead.
+ """
+ return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
+
+def safe_dump(data, stream=None, **kwds):
+ """
+ Serialize a Python object into a YAML stream.
+ Produce only basic YAML tags.
+ If stream is None, return the produced string instead.
+ """
+ return dump_all([data], stream, Dumper=SafeDumper, **kwds)
+
+def add_implicit_resolver(tag, regexp, first=None,
Loader=None, Dumper=Dumper):
- """
- Add an implicit scalar detector.
- If an implicit scalar value matches the given regexp,
- the corresponding tag is assigned to the scalar.
- first is a sequence of possible initial characters or None.
- """
+ """
+ Add an implicit scalar detector.
+ If an implicit scalar value matches the given regexp,
+ the corresponding tag is assigned to the scalar.
+ first is a sequence of possible initial characters or None.
+ """
if Loader is None:
loader.Loader.add_implicit_resolver(tag, regexp, first)
loader.FullLoader.add_implicit_resolver(tag, regexp, first)
loader.UnsafeLoader.add_implicit_resolver(tag, regexp, first)
else:
Loader.add_implicit_resolver(tag, regexp, first)
- Dumper.add_implicit_resolver(tag, regexp, first)
-
+ Dumper.add_implicit_resolver(tag, regexp, first)
+
def add_path_resolver(tag, path, kind=None, Loader=None, Dumper=Dumper):
- """
- Add a path based resolver for the given tag.
- A path is a list of keys that forms a path
- to a node in the representation tree.
- Keys can be string values, integers, or None.
- """
+ """
+ Add a path based resolver for the given tag.
+ A path is a list of keys that forms a path
+ to a node in the representation tree.
+ Keys can be string values, integers, or None.
+ """
if Loader is None:
loader.Loader.add_path_resolver(tag, path, kind)
loader.FullLoader.add_path_resolver(tag, path, kind)
loader.UnsafeLoader.add_path_resolver(tag, path, kind)
else:
Loader.add_path_resolver(tag, path, kind)
- Dumper.add_path_resolver(tag, path, kind)
-
+ Dumper.add_path_resolver(tag, path, kind)
+
def add_constructor(tag, constructor, Loader=None):
- """
- Add a constructor for the given tag.
- Constructor is a function that accepts a Loader instance
- and a node object and produces the corresponding Python object.
- """
+ """
+ Add a constructor for the given tag.
+ Constructor is a function that accepts a Loader instance
+ and a node object and produces the corresponding Python object.
+ """
if Loader is None:
loader.Loader.add_constructor(tag, constructor)
loader.FullLoader.add_constructor(tag, constructor)
loader.UnsafeLoader.add_constructor(tag, constructor)
else:
Loader.add_constructor(tag, constructor)
-
+
def add_multi_constructor(tag_prefix, multi_constructor, Loader=None):
- """
- Add a multi-constructor for the given tag prefix.
- Multi-constructor is called for a node if its tag starts with tag_prefix.
- Multi-constructor accepts a Loader instance, a tag suffix,
- and a node object and produces the corresponding Python object.
- """
+ """
+ Add a multi-constructor for the given tag prefix.
+ Multi-constructor is called for a node if its tag starts with tag_prefix.
+ Multi-constructor accepts a Loader instance, a tag suffix,
+ and a node object and produces the corresponding Python object.
+ """
if Loader is None:
loader.Loader.add_multi_constructor(tag_prefix, multi_constructor)
loader.FullLoader.add_multi_constructor(tag_prefix, multi_constructor)
loader.UnsafeLoader.add_multi_constructor(tag_prefix, multi_constructor)
else:
Loader.add_multi_constructor(tag_prefix, multi_constructor)
-
-def add_representer(data_type, representer, Dumper=Dumper):
- """
- Add a representer for the given type.
- Representer is a function accepting a Dumper instance
- and an instance of the given data type
- and producing the corresponding representation node.
- """
- Dumper.add_representer(data_type, representer)
-
-def add_multi_representer(data_type, multi_representer, Dumper=Dumper):
- """
- Add a representer for the given type.
- Multi-representer is a function accepting a Dumper instance
- and an instance of the given data type or subtype
- and producing the corresponding representation node.
- """
- Dumper.add_multi_representer(data_type, multi_representer)
-
-class YAMLObjectMetaclass(type):
- """
- The metaclass for YAMLObject.
- """
- def __init__(cls, name, bases, kwds):
- super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds)
- if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None:
+
+def add_representer(data_type, representer, Dumper=Dumper):
+ """
+ Add a representer for the given type.
+ Representer is a function accepting a Dumper instance
+ and an instance of the given data type
+ and producing the corresponding representation node.
+ """
+ Dumper.add_representer(data_type, representer)
+
+def add_multi_representer(data_type, multi_representer, Dumper=Dumper):
+ """
+ Add a representer for the given type.
+ Multi-representer is a function accepting a Dumper instance
+ and an instance of the given data type or subtype
+ and producing the corresponding representation node.
+ """
+ Dumper.add_multi_representer(data_type, multi_representer)
+
+class YAMLObjectMetaclass(type):
+ """
+ The metaclass for YAMLObject.
+ """
+ def __init__(cls, name, bases, kwds):
+ super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds)
+ if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None:
if isinstance(cls.yaml_loader, list):
for loader in cls.yaml_loader:
loader.add_constructor(cls.yaml_tag, cls.from_yaml)
else:
cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml)
- cls.yaml_dumper.add_representer(cls, cls.to_yaml)
-
-class YAMLObject(object):
- """
- An object that can dump itself to a YAML stream
- and load itself from a YAML stream.
- """
-
- __metaclass__ = YAMLObjectMetaclass
- __slots__ = () # no direct instantiation, so allow immutable subclasses
-
+ cls.yaml_dumper.add_representer(cls, cls.to_yaml)
+
+class YAMLObject(object):
+ """
+ An object that can dump itself to a YAML stream
+ and load itself from a YAML stream.
+ """
+
+ __metaclass__ = YAMLObjectMetaclass
+ __slots__ = () # no direct instantiation, so allow immutable subclasses
+
yaml_loader = [Loader, FullLoader, UnsafeLoader]
- yaml_dumper = Dumper
-
- yaml_tag = None
- yaml_flow_style = None
-
- def from_yaml(cls, loader, node):
- """
- Convert a representation node to a Python object.
- """
- return loader.construct_yaml_object(node, cls)
- from_yaml = classmethod(from_yaml)
-
- def to_yaml(cls, dumper, data):
- """
- Convert a Python object to a representation node.
- """
- return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
- flow_style=cls.yaml_flow_style)
- to_yaml = classmethod(to_yaml)
-
+ yaml_dumper = Dumper
+
+ yaml_tag = None
+ yaml_flow_style = None
+
+ def from_yaml(cls, loader, node):
+ """
+ Convert a representation node to a Python object.
+ """
+ return loader.construct_yaml_object(node, cls)
+ from_yaml = classmethod(from_yaml)
+
+ def to_yaml(cls, dumper, data):
+ """
+ Convert a Python object to a representation node.
+ """
+ return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
+ flow_style=cls.yaml_flow_style)
+ to_yaml = classmethod(to_yaml)
+
diff --git a/contrib/python/PyYAML/py2/yaml/_yaml.h b/contrib/python/PyYAML/py2/yaml/_yaml.h
index 622cfc561a..21fd6a991b 100644
--- a/contrib/python/PyYAML/py2/yaml/_yaml.h
+++ b/contrib/python/PyYAML/py2/yaml/_yaml.h
@@ -1,23 +1,23 @@
-
-#include <yaml.h>
-
-#if PY_MAJOR_VERSION < 3
-
+
+#include <yaml.h>
+
+#if PY_MAJOR_VERSION < 3
+
#define PyUnicode_FromString(s) PyUnicode_DecodeUTF8((s), strlen(s), "strict")
-
-#else
-
-#define PyString_CheckExact PyBytes_CheckExact
-#define PyString_AS_STRING PyBytes_AS_STRING
-#define PyString_GET_SIZE PyBytes_GET_SIZE
-#define PyString_FromStringAndSize PyBytes_FromStringAndSize
-
-#endif
-
-#ifdef _MSC_VER /* MS Visual C++ 6.0 */
-#if _MSC_VER == 1200
-
-#define PyLong_FromUnsignedLongLong(z) PyInt_FromLong(i)
-
-#endif
-#endif
+
+#else
+
+#define PyString_CheckExact PyBytes_CheckExact
+#define PyString_AS_STRING PyBytes_AS_STRING
+#define PyString_GET_SIZE PyBytes_GET_SIZE
+#define PyString_FromStringAndSize PyBytes_FromStringAndSize
+
+#endif
+
+#ifdef _MSC_VER /* MS Visual C++ 6.0 */
+#if _MSC_VER == 1200
+
+#define PyLong_FromUnsignedLongLong(z) PyInt_FromLong(i)
+
+#endif
+#endif
diff --git a/contrib/python/PyYAML/py2/yaml/_yaml.pxd b/contrib/python/PyYAML/py2/yaml/_yaml.pxd
index b6629e26ae..7937c9db51 100644
--- a/contrib/python/PyYAML/py2/yaml/_yaml.pxd
+++ b/contrib/python/PyYAML/py2/yaml/_yaml.pxd
@@ -1,251 +1,251 @@
-
+
cdef extern from "_yaml.h":
-
- void malloc(int l)
- void memcpy(char *d, char *s, int l)
- int strlen(char *s)
- int PyString_CheckExact(object o)
- int PyUnicode_CheckExact(object o)
- char *PyString_AS_STRING(object o)
- int PyString_GET_SIZE(object o)
- object PyString_FromStringAndSize(char *v, int l)
- object PyUnicode_FromString(char *u)
- object PyUnicode_DecodeUTF8(char *u, int s, char *e)
- object PyUnicode_AsUTF8String(object o)
- int PY_MAJOR_VERSION
-
- ctypedef enum:
- SIZEOF_VOID_P
- ctypedef enum yaml_encoding_t:
- YAML_ANY_ENCODING
- YAML_UTF8_ENCODING
- YAML_UTF16LE_ENCODING
- YAML_UTF16BE_ENCODING
- ctypedef enum yaml_break_t:
- YAML_ANY_BREAK
- YAML_CR_BREAK
- YAML_LN_BREAK
- YAML_CRLN_BREAK
- ctypedef enum yaml_error_type_t:
- YAML_NO_ERROR
- YAML_MEMORY_ERROR
- YAML_READER_ERROR
- YAML_SCANNER_ERROR
- YAML_PARSER_ERROR
- YAML_WRITER_ERROR
- YAML_EMITTER_ERROR
- ctypedef enum yaml_scalar_style_t:
- YAML_ANY_SCALAR_STYLE
- YAML_PLAIN_SCALAR_STYLE
- YAML_SINGLE_QUOTED_SCALAR_STYLE
- YAML_DOUBLE_QUOTED_SCALAR_STYLE
- YAML_LITERAL_SCALAR_STYLE
- YAML_FOLDED_SCALAR_STYLE
- ctypedef enum yaml_sequence_style_t:
- YAML_ANY_SEQUENCE_STYLE
- YAML_BLOCK_SEQUENCE_STYLE
- YAML_FLOW_SEQUENCE_STYLE
- ctypedef enum yaml_mapping_style_t:
- YAML_ANY_MAPPING_STYLE
- YAML_BLOCK_MAPPING_STYLE
- YAML_FLOW_MAPPING_STYLE
- ctypedef enum yaml_token_type_t:
- YAML_NO_TOKEN
- YAML_STREAM_START_TOKEN
- YAML_STREAM_END_TOKEN
- YAML_VERSION_DIRECTIVE_TOKEN
- YAML_TAG_DIRECTIVE_TOKEN
- YAML_DOCUMENT_START_TOKEN
- YAML_DOCUMENT_END_TOKEN
- YAML_BLOCK_SEQUENCE_START_TOKEN
- YAML_BLOCK_MAPPING_START_TOKEN
- YAML_BLOCK_END_TOKEN
- YAML_FLOW_SEQUENCE_START_TOKEN
- YAML_FLOW_SEQUENCE_END_TOKEN
- YAML_FLOW_MAPPING_START_TOKEN
- YAML_FLOW_MAPPING_END_TOKEN
- YAML_BLOCK_ENTRY_TOKEN
- YAML_FLOW_ENTRY_TOKEN
- YAML_KEY_TOKEN
- YAML_VALUE_TOKEN
- YAML_ALIAS_TOKEN
- YAML_ANCHOR_TOKEN
- YAML_TAG_TOKEN
- YAML_SCALAR_TOKEN
- ctypedef enum yaml_event_type_t:
- YAML_NO_EVENT
- YAML_STREAM_START_EVENT
- YAML_STREAM_END_EVENT
- YAML_DOCUMENT_START_EVENT
- YAML_DOCUMENT_END_EVENT
- YAML_ALIAS_EVENT
- YAML_SCALAR_EVENT
- YAML_SEQUENCE_START_EVENT
- YAML_SEQUENCE_END_EVENT
- YAML_MAPPING_START_EVENT
- YAML_MAPPING_END_EVENT
-
+
+ void malloc(int l)
+ void memcpy(char *d, char *s, int l)
+ int strlen(char *s)
+ int PyString_CheckExact(object o)
+ int PyUnicode_CheckExact(object o)
+ char *PyString_AS_STRING(object o)
+ int PyString_GET_SIZE(object o)
+ object PyString_FromStringAndSize(char *v, int l)
+ object PyUnicode_FromString(char *u)
+ object PyUnicode_DecodeUTF8(char *u, int s, char *e)
+ object PyUnicode_AsUTF8String(object o)
+ int PY_MAJOR_VERSION
+
+ ctypedef enum:
+ SIZEOF_VOID_P
+ ctypedef enum yaml_encoding_t:
+ YAML_ANY_ENCODING
+ YAML_UTF8_ENCODING
+ YAML_UTF16LE_ENCODING
+ YAML_UTF16BE_ENCODING
+ ctypedef enum yaml_break_t:
+ YAML_ANY_BREAK
+ YAML_CR_BREAK
+ YAML_LN_BREAK
+ YAML_CRLN_BREAK
+ ctypedef enum yaml_error_type_t:
+ YAML_NO_ERROR
+ YAML_MEMORY_ERROR
+ YAML_READER_ERROR
+ YAML_SCANNER_ERROR
+ YAML_PARSER_ERROR
+ YAML_WRITER_ERROR
+ YAML_EMITTER_ERROR
+ ctypedef enum yaml_scalar_style_t:
+ YAML_ANY_SCALAR_STYLE
+ YAML_PLAIN_SCALAR_STYLE
+ YAML_SINGLE_QUOTED_SCALAR_STYLE
+ YAML_DOUBLE_QUOTED_SCALAR_STYLE
+ YAML_LITERAL_SCALAR_STYLE
+ YAML_FOLDED_SCALAR_STYLE
+ ctypedef enum yaml_sequence_style_t:
+ YAML_ANY_SEQUENCE_STYLE
+ YAML_BLOCK_SEQUENCE_STYLE
+ YAML_FLOW_SEQUENCE_STYLE
+ ctypedef enum yaml_mapping_style_t:
+ YAML_ANY_MAPPING_STYLE
+ YAML_BLOCK_MAPPING_STYLE
+ YAML_FLOW_MAPPING_STYLE
+ ctypedef enum yaml_token_type_t:
+ YAML_NO_TOKEN
+ YAML_STREAM_START_TOKEN
+ YAML_STREAM_END_TOKEN
+ YAML_VERSION_DIRECTIVE_TOKEN
+ YAML_TAG_DIRECTIVE_TOKEN
+ YAML_DOCUMENT_START_TOKEN
+ YAML_DOCUMENT_END_TOKEN
+ YAML_BLOCK_SEQUENCE_START_TOKEN
+ YAML_BLOCK_MAPPING_START_TOKEN
+ YAML_BLOCK_END_TOKEN
+ YAML_FLOW_SEQUENCE_START_TOKEN
+ YAML_FLOW_SEQUENCE_END_TOKEN
+ YAML_FLOW_MAPPING_START_TOKEN
+ YAML_FLOW_MAPPING_END_TOKEN
+ YAML_BLOCK_ENTRY_TOKEN
+ YAML_FLOW_ENTRY_TOKEN
+ YAML_KEY_TOKEN
+ YAML_VALUE_TOKEN
+ YAML_ALIAS_TOKEN
+ YAML_ANCHOR_TOKEN
+ YAML_TAG_TOKEN
+ YAML_SCALAR_TOKEN
+ ctypedef enum yaml_event_type_t:
+ YAML_NO_EVENT
+ YAML_STREAM_START_EVENT
+ YAML_STREAM_END_EVENT
+ YAML_DOCUMENT_START_EVENT
+ YAML_DOCUMENT_END_EVENT
+ YAML_ALIAS_EVENT
+ YAML_SCALAR_EVENT
+ YAML_SEQUENCE_START_EVENT
+ YAML_SEQUENCE_END_EVENT
+ YAML_MAPPING_START_EVENT
+ YAML_MAPPING_END_EVENT
+
ctypedef int yaml_read_handler_t(void *data, char *buffer,
- size_t size, size_t *size_read) except 0
-
+ size_t size, size_t *size_read) except 0
+
ctypedef int yaml_write_handler_t(void *data, char *buffer,
- size_t size) except 0
-
- ctypedef struct yaml_mark_t:
+ size_t size) except 0
+
+ ctypedef struct yaml_mark_t:
size_t index
size_t line
size_t column
- ctypedef struct yaml_version_directive_t:
- int major
- int minor
- ctypedef struct yaml_tag_directive_t:
+ ctypedef struct yaml_version_directive_t:
+ int major
+ int minor
+ ctypedef struct yaml_tag_directive_t:
char *handle
char *prefix
-
- ctypedef struct _yaml_token_stream_start_data_t:
- yaml_encoding_t encoding
- ctypedef struct _yaml_token_alias_data_t:
- char *value
- ctypedef struct _yaml_token_anchor_data_t:
- char *value
- ctypedef struct _yaml_token_tag_data_t:
+
+ ctypedef struct _yaml_token_stream_start_data_t:
+ yaml_encoding_t encoding
+ ctypedef struct _yaml_token_alias_data_t:
+ char *value
+ ctypedef struct _yaml_token_anchor_data_t:
+ char *value
+ ctypedef struct _yaml_token_tag_data_t:
char *handle
char *suffix
- ctypedef struct _yaml_token_scalar_data_t:
- char *value
+ ctypedef struct _yaml_token_scalar_data_t:
+ char *value
size_t length
- yaml_scalar_style_t style
- ctypedef struct _yaml_token_version_directive_data_t:
- int major
- int minor
- ctypedef struct _yaml_token_tag_directive_data_t:
+ yaml_scalar_style_t style
+ ctypedef struct _yaml_token_version_directive_data_t:
+ int major
+ int minor
+ ctypedef struct _yaml_token_tag_directive_data_t:
char *handle
char *prefix
- ctypedef union _yaml_token_data_t:
- _yaml_token_stream_start_data_t stream_start
- _yaml_token_alias_data_t alias
- _yaml_token_anchor_data_t anchor
- _yaml_token_tag_data_t tag
- _yaml_token_scalar_data_t scalar
- _yaml_token_version_directive_data_t version_directive
- _yaml_token_tag_directive_data_t tag_directive
- ctypedef struct yaml_token_t:
- yaml_token_type_t type
- _yaml_token_data_t data
- yaml_mark_t start_mark
- yaml_mark_t end_mark
-
- ctypedef struct _yaml_event_stream_start_data_t:
- yaml_encoding_t encoding
- ctypedef struct _yaml_event_document_start_data_tag_directives_t:
- yaml_tag_directive_t *start
- yaml_tag_directive_t *end
- ctypedef struct _yaml_event_document_start_data_t:
- yaml_version_directive_t *version_directive
- _yaml_event_document_start_data_tag_directives_t tag_directives
- int implicit
- ctypedef struct _yaml_event_document_end_data_t:
- int implicit
- ctypedef struct _yaml_event_alias_data_t:
- char *anchor
- ctypedef struct _yaml_event_scalar_data_t:
- char *anchor
- char *tag
- char *value
+ ctypedef union _yaml_token_data_t:
+ _yaml_token_stream_start_data_t stream_start
+ _yaml_token_alias_data_t alias
+ _yaml_token_anchor_data_t anchor
+ _yaml_token_tag_data_t tag
+ _yaml_token_scalar_data_t scalar
+ _yaml_token_version_directive_data_t version_directive
+ _yaml_token_tag_directive_data_t tag_directive
+ ctypedef struct yaml_token_t:
+ yaml_token_type_t type
+ _yaml_token_data_t data
+ yaml_mark_t start_mark
+ yaml_mark_t end_mark
+
+ ctypedef struct _yaml_event_stream_start_data_t:
+ yaml_encoding_t encoding
+ ctypedef struct _yaml_event_document_start_data_tag_directives_t:
+ yaml_tag_directive_t *start
+ yaml_tag_directive_t *end
+ ctypedef struct _yaml_event_document_start_data_t:
+ yaml_version_directive_t *version_directive
+ _yaml_event_document_start_data_tag_directives_t tag_directives
+ int implicit
+ ctypedef struct _yaml_event_document_end_data_t:
+ int implicit
+ ctypedef struct _yaml_event_alias_data_t:
+ char *anchor
+ ctypedef struct _yaml_event_scalar_data_t:
+ char *anchor
+ char *tag
+ char *value
size_t length
- int plain_implicit
- int quoted_implicit
- yaml_scalar_style_t style
- ctypedef struct _yaml_event_sequence_start_data_t:
- char *anchor
- char *tag
- int implicit
- yaml_sequence_style_t style
- ctypedef struct _yaml_event_mapping_start_data_t:
- char *anchor
- char *tag
- int implicit
- yaml_mapping_style_t style
- ctypedef union _yaml_event_data_t:
- _yaml_event_stream_start_data_t stream_start
- _yaml_event_document_start_data_t document_start
- _yaml_event_document_end_data_t document_end
- _yaml_event_alias_data_t alias
- _yaml_event_scalar_data_t scalar
- _yaml_event_sequence_start_data_t sequence_start
- _yaml_event_mapping_start_data_t mapping_start
- ctypedef struct yaml_event_t:
- yaml_event_type_t type
- _yaml_event_data_t data
- yaml_mark_t start_mark
- yaml_mark_t end_mark
-
- ctypedef struct yaml_parser_t:
- yaml_error_type_t error
- char *problem
+ int plain_implicit
+ int quoted_implicit
+ yaml_scalar_style_t style
+ ctypedef struct _yaml_event_sequence_start_data_t:
+ char *anchor
+ char *tag
+ int implicit
+ yaml_sequence_style_t style
+ ctypedef struct _yaml_event_mapping_start_data_t:
+ char *anchor
+ char *tag
+ int implicit
+ yaml_mapping_style_t style
+ ctypedef union _yaml_event_data_t:
+ _yaml_event_stream_start_data_t stream_start
+ _yaml_event_document_start_data_t document_start
+ _yaml_event_document_end_data_t document_end
+ _yaml_event_alias_data_t alias
+ _yaml_event_scalar_data_t scalar
+ _yaml_event_sequence_start_data_t sequence_start
+ _yaml_event_mapping_start_data_t mapping_start
+ ctypedef struct yaml_event_t:
+ yaml_event_type_t type
+ _yaml_event_data_t data
+ yaml_mark_t start_mark
+ yaml_mark_t end_mark
+
+ ctypedef struct yaml_parser_t:
+ yaml_error_type_t error
+ char *problem
size_t problem_offset
- int problem_value
- yaml_mark_t problem_mark
- char *context
- yaml_mark_t context_mark
-
- ctypedef struct yaml_emitter_t:
- yaml_error_type_t error
- char *problem
-
- char *yaml_get_version_string()
- void yaml_get_version(int *major, int *minor, int *patch)
-
- void yaml_token_delete(yaml_token_t *token)
-
- int yaml_stream_start_event_initialize(yaml_event_t *event,
- yaml_encoding_t encoding)
- int yaml_stream_end_event_initialize(yaml_event_t *event)
- int yaml_document_start_event_initialize(yaml_event_t *event,
- yaml_version_directive_t *version_directive,
- yaml_tag_directive_t *tag_directives_start,
- yaml_tag_directive_t *tag_directives_end,
- int implicit)
- int yaml_document_end_event_initialize(yaml_event_t *event,
- int implicit)
+ int problem_value
+ yaml_mark_t problem_mark
+ char *context
+ yaml_mark_t context_mark
+
+ ctypedef struct yaml_emitter_t:
+ yaml_error_type_t error
+ char *problem
+
+ char *yaml_get_version_string()
+ void yaml_get_version(int *major, int *minor, int *patch)
+
+ void yaml_token_delete(yaml_token_t *token)
+
+ int yaml_stream_start_event_initialize(yaml_event_t *event,
+ yaml_encoding_t encoding)
+ int yaml_stream_end_event_initialize(yaml_event_t *event)
+ int yaml_document_start_event_initialize(yaml_event_t *event,
+ yaml_version_directive_t *version_directive,
+ yaml_tag_directive_t *tag_directives_start,
+ yaml_tag_directive_t *tag_directives_end,
+ int implicit)
+ int yaml_document_end_event_initialize(yaml_event_t *event,
+ int implicit)
int yaml_alias_event_initialize(yaml_event_t *event, char *anchor)
- int yaml_scalar_event_initialize(yaml_event_t *event,
+ int yaml_scalar_event_initialize(yaml_event_t *event,
char *anchor, char *tag, char *value, size_t length,
- int plain_implicit, int quoted_implicit,
- yaml_scalar_style_t style)
- int yaml_sequence_start_event_initialize(yaml_event_t *event,
+ int plain_implicit, int quoted_implicit,
+ yaml_scalar_style_t style)
+ int yaml_sequence_start_event_initialize(yaml_event_t *event,
char *anchor, char *tag, int implicit, yaml_sequence_style_t style)
- int yaml_sequence_end_event_initialize(yaml_event_t *event)
- int yaml_mapping_start_event_initialize(yaml_event_t *event,
+ int yaml_sequence_end_event_initialize(yaml_event_t *event)
+ int yaml_mapping_start_event_initialize(yaml_event_t *event,
char *anchor, char *tag, int implicit, yaml_mapping_style_t style)
- int yaml_mapping_end_event_initialize(yaml_event_t *event)
- void yaml_event_delete(yaml_event_t *event)
-
- int yaml_parser_initialize(yaml_parser_t *parser)
- void yaml_parser_delete(yaml_parser_t *parser)
- void yaml_parser_set_input_string(yaml_parser_t *parser,
+ int yaml_mapping_end_event_initialize(yaml_event_t *event)
+ void yaml_event_delete(yaml_event_t *event)
+
+ int yaml_parser_initialize(yaml_parser_t *parser)
+ void yaml_parser_delete(yaml_parser_t *parser)
+ void yaml_parser_set_input_string(yaml_parser_t *parser,
char *input, size_t size)
- void yaml_parser_set_input(yaml_parser_t *parser,
- yaml_read_handler_t *handler, void *data)
- void yaml_parser_set_encoding(yaml_parser_t *parser,
- yaml_encoding_t encoding)
- int yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token) except *
- int yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event) except *
-
- int yaml_emitter_initialize(yaml_emitter_t *emitter)
- void yaml_emitter_delete(yaml_emitter_t *emitter)
- void yaml_emitter_set_output_string(yaml_emitter_t *emitter,
+ void yaml_parser_set_input(yaml_parser_t *parser,
+ yaml_read_handler_t *handler, void *data)
+ void yaml_parser_set_encoding(yaml_parser_t *parser,
+ yaml_encoding_t encoding)
+ int yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token) except *
+ int yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event) except *
+
+ int yaml_emitter_initialize(yaml_emitter_t *emitter)
+ void yaml_emitter_delete(yaml_emitter_t *emitter)
+ void yaml_emitter_set_output_string(yaml_emitter_t *emitter,
char *output, size_t size, size_t *size_written)
- void yaml_emitter_set_output(yaml_emitter_t *emitter,
- yaml_write_handler_t *handler, void *data)
- void yaml_emitter_set_encoding(yaml_emitter_t *emitter,
- yaml_encoding_t encoding)
- void yaml_emitter_set_canonical(yaml_emitter_t *emitter, int canonical)
- void yaml_emitter_set_indent(yaml_emitter_t *emitter, int indent)
- void yaml_emitter_set_width(yaml_emitter_t *emitter, int width)
- void yaml_emitter_set_unicode(yaml_emitter_t *emitter, int unicode)
- void yaml_emitter_set_break(yaml_emitter_t *emitter,
- yaml_break_t line_break)
- int yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event) except *
- int yaml_emitter_flush(yaml_emitter_t *emitter)
-
+ void yaml_emitter_set_output(yaml_emitter_t *emitter,
+ yaml_write_handler_t *handler, void *data)
+ void yaml_emitter_set_encoding(yaml_emitter_t *emitter,
+ yaml_encoding_t encoding)
+ void yaml_emitter_set_canonical(yaml_emitter_t *emitter, int canonical)
+ void yaml_emitter_set_indent(yaml_emitter_t *emitter, int indent)
+ void yaml_emitter_set_width(yaml_emitter_t *emitter, int width)
+ void yaml_emitter_set_unicode(yaml_emitter_t *emitter, int unicode)
+ void yaml_emitter_set_break(yaml_emitter_t *emitter,
+ yaml_break_t line_break)
+ int yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event) except *
+ int yaml_emitter_flush(yaml_emitter_t *emitter)
+
diff --git a/contrib/python/PyYAML/py2/yaml/_yaml.pyx b/contrib/python/PyYAML/py2/yaml/_yaml.pyx
index efdb347aff..ff4efe80b5 100644
--- a/contrib/python/PyYAML/py2/yaml/_yaml.pyx
+++ b/contrib/python/PyYAML/py2/yaml/_yaml.pyx
@@ -1,1527 +1,1527 @@
-
-import yaml
-
-def get_version_string():
+
+import yaml
+
+def get_version_string():
cdef char *value
- value = yaml_get_version_string()
- if PY_MAJOR_VERSION < 3:
- return value
- else:
- return PyUnicode_FromString(value)
-
-def get_version():
- cdef int major, minor, patch
- yaml_get_version(&major, &minor, &patch)
- return (major, minor, patch)
-
-#Mark = yaml.error.Mark
-YAMLError = yaml.error.YAMLError
-ReaderError = yaml.reader.ReaderError
-ScannerError = yaml.scanner.ScannerError
-ParserError = yaml.parser.ParserError
-ComposerError = yaml.composer.ComposerError
-ConstructorError = yaml.constructor.ConstructorError
-EmitterError = yaml.emitter.EmitterError
-SerializerError = yaml.serializer.SerializerError
-RepresenterError = yaml.representer.RepresenterError
-
-StreamStartToken = yaml.tokens.StreamStartToken
-StreamEndToken = yaml.tokens.StreamEndToken
-DirectiveToken = yaml.tokens.DirectiveToken
-DocumentStartToken = yaml.tokens.DocumentStartToken
-DocumentEndToken = yaml.tokens.DocumentEndToken
-BlockSequenceStartToken = yaml.tokens.BlockSequenceStartToken
-BlockMappingStartToken = yaml.tokens.BlockMappingStartToken
-BlockEndToken = yaml.tokens.BlockEndToken
-FlowSequenceStartToken = yaml.tokens.FlowSequenceStartToken
-FlowMappingStartToken = yaml.tokens.FlowMappingStartToken
-FlowSequenceEndToken = yaml.tokens.FlowSequenceEndToken
-FlowMappingEndToken = yaml.tokens.FlowMappingEndToken
-KeyToken = yaml.tokens.KeyToken
-ValueToken = yaml.tokens.ValueToken
-BlockEntryToken = yaml.tokens.BlockEntryToken
-FlowEntryToken = yaml.tokens.FlowEntryToken
-AliasToken = yaml.tokens.AliasToken
-AnchorToken = yaml.tokens.AnchorToken
-TagToken = yaml.tokens.TagToken
-ScalarToken = yaml.tokens.ScalarToken
-
-StreamStartEvent = yaml.events.StreamStartEvent
-StreamEndEvent = yaml.events.StreamEndEvent
-DocumentStartEvent = yaml.events.DocumentStartEvent
-DocumentEndEvent = yaml.events.DocumentEndEvent
-AliasEvent = yaml.events.AliasEvent
-ScalarEvent = yaml.events.ScalarEvent
-SequenceStartEvent = yaml.events.SequenceStartEvent
-SequenceEndEvent = yaml.events.SequenceEndEvent
-MappingStartEvent = yaml.events.MappingStartEvent
-MappingEndEvent = yaml.events.MappingEndEvent
-
-ScalarNode = yaml.nodes.ScalarNode
-SequenceNode = yaml.nodes.SequenceNode
-MappingNode = yaml.nodes.MappingNode
-
-cdef class Mark:
- cdef readonly object name
+ value = yaml_get_version_string()
+ if PY_MAJOR_VERSION < 3:
+ return value
+ else:
+ return PyUnicode_FromString(value)
+
+def get_version():
+ cdef int major, minor, patch
+ yaml_get_version(&major, &minor, &patch)
+ return (major, minor, patch)
+
+#Mark = yaml.error.Mark
+YAMLError = yaml.error.YAMLError
+ReaderError = yaml.reader.ReaderError
+ScannerError = yaml.scanner.ScannerError
+ParserError = yaml.parser.ParserError
+ComposerError = yaml.composer.ComposerError
+ConstructorError = yaml.constructor.ConstructorError
+EmitterError = yaml.emitter.EmitterError
+SerializerError = yaml.serializer.SerializerError
+RepresenterError = yaml.representer.RepresenterError
+
+StreamStartToken = yaml.tokens.StreamStartToken
+StreamEndToken = yaml.tokens.StreamEndToken
+DirectiveToken = yaml.tokens.DirectiveToken
+DocumentStartToken = yaml.tokens.DocumentStartToken
+DocumentEndToken = yaml.tokens.DocumentEndToken
+BlockSequenceStartToken = yaml.tokens.BlockSequenceStartToken
+BlockMappingStartToken = yaml.tokens.BlockMappingStartToken
+BlockEndToken = yaml.tokens.BlockEndToken
+FlowSequenceStartToken = yaml.tokens.FlowSequenceStartToken
+FlowMappingStartToken = yaml.tokens.FlowMappingStartToken
+FlowSequenceEndToken = yaml.tokens.FlowSequenceEndToken
+FlowMappingEndToken = yaml.tokens.FlowMappingEndToken
+KeyToken = yaml.tokens.KeyToken
+ValueToken = yaml.tokens.ValueToken
+BlockEntryToken = yaml.tokens.BlockEntryToken
+FlowEntryToken = yaml.tokens.FlowEntryToken
+AliasToken = yaml.tokens.AliasToken
+AnchorToken = yaml.tokens.AnchorToken
+TagToken = yaml.tokens.TagToken
+ScalarToken = yaml.tokens.ScalarToken
+
+StreamStartEvent = yaml.events.StreamStartEvent
+StreamEndEvent = yaml.events.StreamEndEvent
+DocumentStartEvent = yaml.events.DocumentStartEvent
+DocumentEndEvent = yaml.events.DocumentEndEvent
+AliasEvent = yaml.events.AliasEvent
+ScalarEvent = yaml.events.ScalarEvent
+SequenceStartEvent = yaml.events.SequenceStartEvent
+SequenceEndEvent = yaml.events.SequenceEndEvent
+MappingStartEvent = yaml.events.MappingStartEvent
+MappingEndEvent = yaml.events.MappingEndEvent
+
+ScalarNode = yaml.nodes.ScalarNode
+SequenceNode = yaml.nodes.SequenceNode
+MappingNode = yaml.nodes.MappingNode
+
+cdef class Mark:
+ cdef readonly object name
cdef readonly size_t index
cdef readonly size_t line
cdef readonly size_t column
- cdef readonly buffer
- cdef readonly pointer
-
+ cdef readonly buffer
+ cdef readonly pointer
+
def __init__(self, object name, size_t index, size_t line, size_t column,
- object buffer, object pointer):
- self.name = name
- self.index = index
- self.line = line
- self.column = column
- self.buffer = buffer
- self.pointer = pointer
-
- def get_snippet(self):
- return None
-
- def __str__(self):
- where = " in \"%s\", line %d, column %d" \
- % (self.name, self.line+1, self.column+1)
- return where
-
-#class YAMLError(Exception):
-# pass
-#
-#class MarkedYAMLError(YAMLError):
-#
-# def __init__(self, context=None, context_mark=None,
-# problem=None, problem_mark=None, note=None):
-# self.context = context
-# self.context_mark = context_mark
-# self.problem = problem
-# self.problem_mark = problem_mark
-# self.note = note
-#
-# def __str__(self):
-# lines = []
-# if self.context is not None:
-# lines.append(self.context)
-# if self.context_mark is not None \
-# and (self.problem is None or self.problem_mark is None
-# or self.context_mark.name != self.problem_mark.name
-# or self.context_mark.line != self.problem_mark.line
-# or self.context_mark.column != self.problem_mark.column):
-# lines.append(str(self.context_mark))
-# if self.problem is not None:
-# lines.append(self.problem)
-# if self.problem_mark is not None:
-# lines.append(str(self.problem_mark))
-# if self.note is not None:
-# lines.append(self.note)
-# return '\n'.join(lines)
-#
-#class ReaderError(YAMLError):
-#
-# def __init__(self, name, position, character, encoding, reason):
-# self.name = name
-# self.character = character
-# self.position = position
-# self.encoding = encoding
-# self.reason = reason
-#
-# def __str__(self):
-# if isinstance(self.character, str):
-# return "'%s' codec can't decode byte #x%02x: %s\n" \
-# " in \"%s\", position %d" \
-# % (self.encoding, ord(self.character), self.reason,
-# self.name, self.position)
-# else:
-# return "unacceptable character #x%04x: %s\n" \
-# " in \"%s\", position %d" \
-# % (ord(self.character), self.reason,
-# self.name, self.position)
-#
-#class ScannerError(MarkedYAMLError):
-# pass
-#
-#class ParserError(MarkedYAMLError):
-# pass
-#
-#class EmitterError(YAMLError):
-# pass
-#
-#cdef class Token:
-# cdef readonly Mark start_mark
-# cdef readonly Mark end_mark
-# def __init__(self, Mark start_mark, Mark end_mark):
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-#
-#cdef class StreamStartToken(Token):
-# cdef readonly object encoding
-# def __init__(self, Mark start_mark, Mark end_mark, encoding):
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-# self.encoding = encoding
-#
-#cdef class StreamEndToken(Token):
-# pass
-#
-#cdef class DirectiveToken(Token):
-# cdef readonly object name
-# cdef readonly object value
-# def __init__(self, name, value, Mark start_mark, Mark end_mark):
-# self.name = name
-# self.value = value
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-#
-#cdef class DocumentStartToken(Token):
-# pass
-#
-#cdef class DocumentEndToken(Token):
-# pass
-#
-#cdef class BlockSequenceStartToken(Token):
-# pass
-#
-#cdef class BlockMappingStartToken(Token):
-# pass
-#
-#cdef class BlockEndToken(Token):
-# pass
-#
-#cdef class FlowSequenceStartToken(Token):
-# pass
-#
-#cdef class FlowMappingStartToken(Token):
-# pass
-#
-#cdef class FlowSequenceEndToken(Token):
-# pass
-#
-#cdef class FlowMappingEndToken(Token):
-# pass
-#
-#cdef class KeyToken(Token):
-# pass
-#
-#cdef class ValueToken(Token):
-# pass
-#
-#cdef class BlockEntryToken(Token):
-# pass
-#
-#cdef class FlowEntryToken(Token):
-# pass
-#
-#cdef class AliasToken(Token):
-# cdef readonly object value
-# def __init__(self, value, Mark start_mark, Mark end_mark):
-# self.value = value
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-#
-#cdef class AnchorToken(Token):
-# cdef readonly object value
-# def __init__(self, value, Mark start_mark, Mark end_mark):
-# self.value = value
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-#
-#cdef class TagToken(Token):
-# cdef readonly object value
-# def __init__(self, value, Mark start_mark, Mark end_mark):
-# self.value = value
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-#
-#cdef class ScalarToken(Token):
-# cdef readonly object value
-# cdef readonly object plain
-# cdef readonly object style
-# def __init__(self, value, plain, Mark start_mark, Mark end_mark, style=None):
-# self.value = value
-# self.plain = plain
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-# self.style = style
-
-cdef class CParser:
-
- cdef yaml_parser_t parser
- cdef yaml_event_t parsed_event
-
- cdef object stream
- cdef object stream_name
- cdef object current_token
- cdef object current_event
- cdef object anchors
- cdef object stream_cache
+ object buffer, object pointer):
+ self.name = name
+ self.index = index
+ self.line = line
+ self.column = column
+ self.buffer = buffer
+ self.pointer = pointer
+
+ def get_snippet(self):
+ return None
+
+ def __str__(self):
+ where = " in \"%s\", line %d, column %d" \
+ % (self.name, self.line+1, self.column+1)
+ return where
+
+#class YAMLError(Exception):
+# pass
+#
+#class MarkedYAMLError(YAMLError):
+#
+# def __init__(self, context=None, context_mark=None,
+# problem=None, problem_mark=None, note=None):
+# self.context = context
+# self.context_mark = context_mark
+# self.problem = problem
+# self.problem_mark = problem_mark
+# self.note = note
+#
+# def __str__(self):
+# lines = []
+# if self.context is not None:
+# lines.append(self.context)
+# if self.context_mark is not None \
+# and (self.problem is None or self.problem_mark is None
+# or self.context_mark.name != self.problem_mark.name
+# or self.context_mark.line != self.problem_mark.line
+# or self.context_mark.column != self.problem_mark.column):
+# lines.append(str(self.context_mark))
+# if self.problem is not None:
+# lines.append(self.problem)
+# if self.problem_mark is not None:
+# lines.append(str(self.problem_mark))
+# if self.note is not None:
+# lines.append(self.note)
+# return '\n'.join(lines)
+#
+#class ReaderError(YAMLError):
+#
+# def __init__(self, name, position, character, encoding, reason):
+# self.name = name
+# self.character = character
+# self.position = position
+# self.encoding = encoding
+# self.reason = reason
+#
+# def __str__(self):
+# if isinstance(self.character, str):
+# return "'%s' codec can't decode byte #x%02x: %s\n" \
+# " in \"%s\", position %d" \
+# % (self.encoding, ord(self.character), self.reason,
+# self.name, self.position)
+# else:
+# return "unacceptable character #x%04x: %s\n" \
+# " in \"%s\", position %d" \
+# % (ord(self.character), self.reason,
+# self.name, self.position)
+#
+#class ScannerError(MarkedYAMLError):
+# pass
+#
+#class ParserError(MarkedYAMLError):
+# pass
+#
+#class EmitterError(YAMLError):
+# pass
+#
+#cdef class Token:
+# cdef readonly Mark start_mark
+# cdef readonly Mark end_mark
+# def __init__(self, Mark start_mark, Mark end_mark):
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+#
+#cdef class StreamStartToken(Token):
+# cdef readonly object encoding
+# def __init__(self, Mark start_mark, Mark end_mark, encoding):
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+# self.encoding = encoding
+#
+#cdef class StreamEndToken(Token):
+# pass
+#
+#cdef class DirectiveToken(Token):
+# cdef readonly object name
+# cdef readonly object value
+# def __init__(self, name, value, Mark start_mark, Mark end_mark):
+# self.name = name
+# self.value = value
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+#
+#cdef class DocumentStartToken(Token):
+# pass
+#
+#cdef class DocumentEndToken(Token):
+# pass
+#
+#cdef class BlockSequenceStartToken(Token):
+# pass
+#
+#cdef class BlockMappingStartToken(Token):
+# pass
+#
+#cdef class BlockEndToken(Token):
+# pass
+#
+#cdef class FlowSequenceStartToken(Token):
+# pass
+#
+#cdef class FlowMappingStartToken(Token):
+# pass
+#
+#cdef class FlowSequenceEndToken(Token):
+# pass
+#
+#cdef class FlowMappingEndToken(Token):
+# pass
+#
+#cdef class KeyToken(Token):
+# pass
+#
+#cdef class ValueToken(Token):
+# pass
+#
+#cdef class BlockEntryToken(Token):
+# pass
+#
+#cdef class FlowEntryToken(Token):
+# pass
+#
+#cdef class AliasToken(Token):
+# cdef readonly object value
+# def __init__(self, value, Mark start_mark, Mark end_mark):
+# self.value = value
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+#
+#cdef class AnchorToken(Token):
+# cdef readonly object value
+# def __init__(self, value, Mark start_mark, Mark end_mark):
+# self.value = value
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+#
+#cdef class TagToken(Token):
+# cdef readonly object value
+# def __init__(self, value, Mark start_mark, Mark end_mark):
+# self.value = value
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+#
+#cdef class ScalarToken(Token):
+# cdef readonly object value
+# cdef readonly object plain
+# cdef readonly object style
+# def __init__(self, value, plain, Mark start_mark, Mark end_mark, style=None):
+# self.value = value
+# self.plain = plain
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+# self.style = style
+
+cdef class CParser:
+
+ cdef yaml_parser_t parser
+ cdef yaml_event_t parsed_event
+
+ cdef object stream
+ cdef object stream_name
+ cdef object current_token
+ cdef object current_event
+ cdef object anchors
+ cdef object stream_cache
cdef int stream_cache_len
cdef int stream_cache_pos
- cdef int unicode_source
-
- def __init__(self, stream):
- cdef is_readable
- if yaml_parser_initialize(&self.parser) == 0:
- raise MemoryError
- self.parsed_event.type = YAML_NO_EVENT
- is_readable = 1
- try:
- stream.read
- except AttributeError:
- is_readable = 0
- self.unicode_source = 0
- if is_readable:
- self.stream = stream
- try:
- self.stream_name = stream.name
- except AttributeError:
- if PY_MAJOR_VERSION < 3:
- self.stream_name = '<file>'
- else:
- self.stream_name = u'<file>'
- self.stream_cache = None
- self.stream_cache_len = 0
- self.stream_cache_pos = 0
- yaml_parser_set_input(&self.parser, input_handler, <void *>self)
- else:
- if PyUnicode_CheckExact(stream) != 0:
- stream = PyUnicode_AsUTF8String(stream)
- if PY_MAJOR_VERSION < 3:
- self.stream_name = '<unicode string>'
- else:
- self.stream_name = u'<unicode string>'
- self.unicode_source = 1
- else:
- if PY_MAJOR_VERSION < 3:
- self.stream_name = '<byte string>'
- else:
- self.stream_name = u'<byte string>'
- if PyString_CheckExact(stream) == 0:
- if PY_MAJOR_VERSION < 3:
- raise TypeError("a string or stream input is required")
- else:
- raise TypeError(u"a string or stream input is required")
- self.stream = stream
+ cdef int unicode_source
+
+ def __init__(self, stream):
+ cdef is_readable
+ if yaml_parser_initialize(&self.parser) == 0:
+ raise MemoryError
+ self.parsed_event.type = YAML_NO_EVENT
+ is_readable = 1
+ try:
+ stream.read
+ except AttributeError:
+ is_readable = 0
+ self.unicode_source = 0
+ if is_readable:
+ self.stream = stream
+ try:
+ self.stream_name = stream.name
+ except AttributeError:
+ if PY_MAJOR_VERSION < 3:
+ self.stream_name = '<file>'
+ else:
+ self.stream_name = u'<file>'
+ self.stream_cache = None
+ self.stream_cache_len = 0
+ self.stream_cache_pos = 0
+ yaml_parser_set_input(&self.parser, input_handler, <void *>self)
+ else:
+ if PyUnicode_CheckExact(stream) != 0:
+ stream = PyUnicode_AsUTF8String(stream)
+ if PY_MAJOR_VERSION < 3:
+ self.stream_name = '<unicode string>'
+ else:
+ self.stream_name = u'<unicode string>'
+ self.unicode_source = 1
+ else:
+ if PY_MAJOR_VERSION < 3:
+ self.stream_name = '<byte string>'
+ else:
+ self.stream_name = u'<byte string>'
+ if PyString_CheckExact(stream) == 0:
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("a string or stream input is required")
+ else:
+ raise TypeError(u"a string or stream input is required")
+ self.stream = stream
yaml_parser_set_input_string(&self.parser, PyString_AS_STRING(stream), PyString_GET_SIZE(stream))
- self.current_token = None
- self.current_event = None
- self.anchors = {}
-
- def __dealloc__(self):
- yaml_parser_delete(&self.parser)
- yaml_event_delete(&self.parsed_event)
-
- def dispose(self):
- pass
-
- cdef object _parser_error(self):
- if self.parser.error == YAML_MEMORY_ERROR:
- return MemoryError
- elif self.parser.error == YAML_READER_ERROR:
- if PY_MAJOR_VERSION < 3:
- return ReaderError(self.stream_name, self.parser.problem_offset,
- self.parser.problem_value, '?', self.parser.problem)
- else:
- return ReaderError(self.stream_name, self.parser.problem_offset,
- self.parser.problem_value, u'?', PyUnicode_FromString(self.parser.problem))
- elif self.parser.error == YAML_SCANNER_ERROR \
- or self.parser.error == YAML_PARSER_ERROR:
- context_mark = None
- problem_mark = None
- if self.parser.context != NULL:
- context_mark = Mark(self.stream_name,
- self.parser.context_mark.index,
- self.parser.context_mark.line,
- self.parser.context_mark.column, None, None)
- if self.parser.problem != NULL:
- problem_mark = Mark(self.stream_name,
- self.parser.problem_mark.index,
- self.parser.problem_mark.line,
- self.parser.problem_mark.column, None, None)
- context = None
- if self.parser.context != NULL:
- if PY_MAJOR_VERSION < 3:
- context = self.parser.context
- else:
- context = PyUnicode_FromString(self.parser.context)
- if PY_MAJOR_VERSION < 3:
- problem = self.parser.problem
- else:
- problem = PyUnicode_FromString(self.parser.problem)
- if self.parser.error == YAML_SCANNER_ERROR:
- return ScannerError(context, context_mark, problem, problem_mark)
- else:
- return ParserError(context, context_mark, problem, problem_mark)
- if PY_MAJOR_VERSION < 3:
- raise ValueError("no parser error")
- else:
- raise ValueError(u"no parser error")
-
- def raw_scan(self):
- cdef yaml_token_t token
- cdef int done
- cdef int count
- count = 0
- done = 0
- while done == 0:
- if yaml_parser_scan(&self.parser, &token) == 0:
- error = self._parser_error()
- raise error
- if token.type == YAML_NO_TOKEN:
- done = 1
- else:
- count = count+1
- yaml_token_delete(&token)
- return count
-
- cdef object _scan(self):
- cdef yaml_token_t token
- if yaml_parser_scan(&self.parser, &token) == 0:
- error = self._parser_error()
- raise error
- token_object = self._token_to_object(&token)
- yaml_token_delete(&token)
- return token_object
-
- cdef object _token_to_object(self, yaml_token_t *token):
- start_mark = Mark(self.stream_name,
- token.start_mark.index,
- token.start_mark.line,
- token.start_mark.column,
- None, None)
- end_mark = Mark(self.stream_name,
- token.end_mark.index,
- token.end_mark.line,
- token.end_mark.column,
- None, None)
- if token.type == YAML_NO_TOKEN:
- return None
- elif token.type == YAML_STREAM_START_TOKEN:
- encoding = None
- if token.data.stream_start.encoding == YAML_UTF8_ENCODING:
- if self.unicode_source == 0:
- encoding = u"utf-8"
- elif token.data.stream_start.encoding == YAML_UTF16LE_ENCODING:
- encoding = u"utf-16-le"
- elif token.data.stream_start.encoding == YAML_UTF16BE_ENCODING:
- encoding = u"utf-16-be"
- return StreamStartToken(start_mark, end_mark, encoding)
- elif token.type == YAML_STREAM_END_TOKEN:
- return StreamEndToken(start_mark, end_mark)
- elif token.type == YAML_VERSION_DIRECTIVE_TOKEN:
- return DirectiveToken(u"YAML",
- (token.data.version_directive.major,
- token.data.version_directive.minor),
- start_mark, end_mark)
- elif token.type == YAML_TAG_DIRECTIVE_TOKEN:
+ self.current_token = None
+ self.current_event = None
+ self.anchors = {}
+
+ def __dealloc__(self):
+ yaml_parser_delete(&self.parser)
+ yaml_event_delete(&self.parsed_event)
+
+ def dispose(self):
+ pass
+
+ cdef object _parser_error(self):
+ if self.parser.error == YAML_MEMORY_ERROR:
+ return MemoryError
+ elif self.parser.error == YAML_READER_ERROR:
+ if PY_MAJOR_VERSION < 3:
+ return ReaderError(self.stream_name, self.parser.problem_offset,
+ self.parser.problem_value, '?', self.parser.problem)
+ else:
+ return ReaderError(self.stream_name, self.parser.problem_offset,
+ self.parser.problem_value, u'?', PyUnicode_FromString(self.parser.problem))
+ elif self.parser.error == YAML_SCANNER_ERROR \
+ or self.parser.error == YAML_PARSER_ERROR:
+ context_mark = None
+ problem_mark = None
+ if self.parser.context != NULL:
+ context_mark = Mark(self.stream_name,
+ self.parser.context_mark.index,
+ self.parser.context_mark.line,
+ self.parser.context_mark.column, None, None)
+ if self.parser.problem != NULL:
+ problem_mark = Mark(self.stream_name,
+ self.parser.problem_mark.index,
+ self.parser.problem_mark.line,
+ self.parser.problem_mark.column, None, None)
+ context = None
+ if self.parser.context != NULL:
+ if PY_MAJOR_VERSION < 3:
+ context = self.parser.context
+ else:
+ context = PyUnicode_FromString(self.parser.context)
+ if PY_MAJOR_VERSION < 3:
+ problem = self.parser.problem
+ else:
+ problem = PyUnicode_FromString(self.parser.problem)
+ if self.parser.error == YAML_SCANNER_ERROR:
+ return ScannerError(context, context_mark, problem, problem_mark)
+ else:
+ return ParserError(context, context_mark, problem, problem_mark)
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("no parser error")
+ else:
+ raise ValueError(u"no parser error")
+
+ def raw_scan(self):
+ cdef yaml_token_t token
+ cdef int done
+ cdef int count
+ count = 0
+ done = 0
+ while done == 0:
+ if yaml_parser_scan(&self.parser, &token) == 0:
+ error = self._parser_error()
+ raise error
+ if token.type == YAML_NO_TOKEN:
+ done = 1
+ else:
+ count = count+1
+ yaml_token_delete(&token)
+ return count
+
+ cdef object _scan(self):
+ cdef yaml_token_t token
+ if yaml_parser_scan(&self.parser, &token) == 0:
+ error = self._parser_error()
+ raise error
+ token_object = self._token_to_object(&token)
+ yaml_token_delete(&token)
+ return token_object
+
+ cdef object _token_to_object(self, yaml_token_t *token):
+ start_mark = Mark(self.stream_name,
+ token.start_mark.index,
+ token.start_mark.line,
+ token.start_mark.column,
+ None, None)
+ end_mark = Mark(self.stream_name,
+ token.end_mark.index,
+ token.end_mark.line,
+ token.end_mark.column,
+ None, None)
+ if token.type == YAML_NO_TOKEN:
+ return None
+ elif token.type == YAML_STREAM_START_TOKEN:
+ encoding = None
+ if token.data.stream_start.encoding == YAML_UTF8_ENCODING:
+ if self.unicode_source == 0:
+ encoding = u"utf-8"
+ elif token.data.stream_start.encoding == YAML_UTF16LE_ENCODING:
+ encoding = u"utf-16-le"
+ elif token.data.stream_start.encoding == YAML_UTF16BE_ENCODING:
+ encoding = u"utf-16-be"
+ return StreamStartToken(start_mark, end_mark, encoding)
+ elif token.type == YAML_STREAM_END_TOKEN:
+ return StreamEndToken(start_mark, end_mark)
+ elif token.type == YAML_VERSION_DIRECTIVE_TOKEN:
+ return DirectiveToken(u"YAML",
+ (token.data.version_directive.major,
+ token.data.version_directive.minor),
+ start_mark, end_mark)
+ elif token.type == YAML_TAG_DIRECTIVE_TOKEN:
handle = PyUnicode_FromString(token.data.tag_directive.handle)
prefix = PyUnicode_FromString(token.data.tag_directive.prefix)
- return DirectiveToken(u"TAG", (handle, prefix),
- start_mark, end_mark)
- elif token.type == YAML_DOCUMENT_START_TOKEN:
- return DocumentStartToken(start_mark, end_mark)
- elif token.type == YAML_DOCUMENT_END_TOKEN:
- return DocumentEndToken(start_mark, end_mark)
- elif token.type == YAML_BLOCK_SEQUENCE_START_TOKEN:
- return BlockSequenceStartToken(start_mark, end_mark)
- elif token.type == YAML_BLOCK_MAPPING_START_TOKEN:
- return BlockMappingStartToken(start_mark, end_mark)
- elif token.type == YAML_BLOCK_END_TOKEN:
- return BlockEndToken(start_mark, end_mark)
- elif token.type == YAML_FLOW_SEQUENCE_START_TOKEN:
- return FlowSequenceStartToken(start_mark, end_mark)
- elif token.type == YAML_FLOW_SEQUENCE_END_TOKEN:
- return FlowSequenceEndToken(start_mark, end_mark)
- elif token.type == YAML_FLOW_MAPPING_START_TOKEN:
- return FlowMappingStartToken(start_mark, end_mark)
- elif token.type == YAML_FLOW_MAPPING_END_TOKEN:
- return FlowMappingEndToken(start_mark, end_mark)
- elif token.type == YAML_BLOCK_ENTRY_TOKEN:
- return BlockEntryToken(start_mark, end_mark)
- elif token.type == YAML_FLOW_ENTRY_TOKEN:
- return FlowEntryToken(start_mark, end_mark)
- elif token.type == YAML_KEY_TOKEN:
- return KeyToken(start_mark, end_mark)
- elif token.type == YAML_VALUE_TOKEN:
- return ValueToken(start_mark, end_mark)
- elif token.type == YAML_ALIAS_TOKEN:
- value = PyUnicode_FromString(token.data.alias.value)
- return AliasToken(value, start_mark, end_mark)
- elif token.type == YAML_ANCHOR_TOKEN:
- value = PyUnicode_FromString(token.data.anchor.value)
- return AnchorToken(value, start_mark, end_mark)
- elif token.type == YAML_TAG_TOKEN:
+ return DirectiveToken(u"TAG", (handle, prefix),
+ start_mark, end_mark)
+ elif token.type == YAML_DOCUMENT_START_TOKEN:
+ return DocumentStartToken(start_mark, end_mark)
+ elif token.type == YAML_DOCUMENT_END_TOKEN:
+ return DocumentEndToken(start_mark, end_mark)
+ elif token.type == YAML_BLOCK_SEQUENCE_START_TOKEN:
+ return BlockSequenceStartToken(start_mark, end_mark)
+ elif token.type == YAML_BLOCK_MAPPING_START_TOKEN:
+ return BlockMappingStartToken(start_mark, end_mark)
+ elif token.type == YAML_BLOCK_END_TOKEN:
+ return BlockEndToken(start_mark, end_mark)
+ elif token.type == YAML_FLOW_SEQUENCE_START_TOKEN:
+ return FlowSequenceStartToken(start_mark, end_mark)
+ elif token.type == YAML_FLOW_SEQUENCE_END_TOKEN:
+ return FlowSequenceEndToken(start_mark, end_mark)
+ elif token.type == YAML_FLOW_MAPPING_START_TOKEN:
+ return FlowMappingStartToken(start_mark, end_mark)
+ elif token.type == YAML_FLOW_MAPPING_END_TOKEN:
+ return FlowMappingEndToken(start_mark, end_mark)
+ elif token.type == YAML_BLOCK_ENTRY_TOKEN:
+ return BlockEntryToken(start_mark, end_mark)
+ elif token.type == YAML_FLOW_ENTRY_TOKEN:
+ return FlowEntryToken(start_mark, end_mark)
+ elif token.type == YAML_KEY_TOKEN:
+ return KeyToken(start_mark, end_mark)
+ elif token.type == YAML_VALUE_TOKEN:
+ return ValueToken(start_mark, end_mark)
+ elif token.type == YAML_ALIAS_TOKEN:
+ value = PyUnicode_FromString(token.data.alias.value)
+ return AliasToken(value, start_mark, end_mark)
+ elif token.type == YAML_ANCHOR_TOKEN:
+ value = PyUnicode_FromString(token.data.anchor.value)
+ return AnchorToken(value, start_mark, end_mark)
+ elif token.type == YAML_TAG_TOKEN:
handle = PyUnicode_FromString(token.data.tag.handle)
suffix = PyUnicode_FromString(token.data.tag.suffix)
- if not handle:
- handle = None
- return TagToken((handle, suffix), start_mark, end_mark)
- elif token.type == YAML_SCALAR_TOKEN:
+ if not handle:
+ handle = None
+ return TagToken((handle, suffix), start_mark, end_mark)
+ elif token.type == YAML_SCALAR_TOKEN:
value = PyUnicode_DecodeUTF8(token.data.scalar.value,
- token.data.scalar.length, 'strict')
- plain = False
- style = None
- if token.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
- plain = True
- style = u''
- elif token.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
- style = u'\''
- elif token.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
- style = u'"'
- elif token.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
- style = u'|'
- elif token.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
- style = u'>'
- return ScalarToken(value, plain,
- start_mark, end_mark, style)
- else:
- if PY_MAJOR_VERSION < 3:
- raise ValueError("unknown token type")
- else:
- raise ValueError(u"unknown token type")
-
- def get_token(self):
- if self.current_token is not None:
- value = self.current_token
- self.current_token = None
- else:
- value = self._scan()
- return value
-
- def peek_token(self):
- if self.current_token is None:
- self.current_token = self._scan()
- return self.current_token
-
- def check_token(self, *choices):
- if self.current_token is None:
- self.current_token = self._scan()
- if self.current_token is None:
- return False
- if not choices:
- return True
- token_class = self.current_token.__class__
- for choice in choices:
- if token_class is choice:
- return True
- return False
-
- def raw_parse(self):
- cdef yaml_event_t event
- cdef int done
- cdef int count
- count = 0
- done = 0
- while done == 0:
- if yaml_parser_parse(&self.parser, &event) == 0:
- error = self._parser_error()
- raise error
- if event.type == YAML_NO_EVENT:
- done = 1
- else:
- count = count+1
- yaml_event_delete(&event)
- return count
-
- cdef object _parse(self):
- cdef yaml_event_t event
- if yaml_parser_parse(&self.parser, &event) == 0:
- error = self._parser_error()
- raise error
- event_object = self._event_to_object(&event)
- yaml_event_delete(&event)
- return event_object
-
- cdef object _event_to_object(self, yaml_event_t *event):
- cdef yaml_tag_directive_t *tag_directive
- start_mark = Mark(self.stream_name,
- event.start_mark.index,
- event.start_mark.line,
- event.start_mark.column,
- None, None)
- end_mark = Mark(self.stream_name,
- event.end_mark.index,
- event.end_mark.line,
- event.end_mark.column,
- None, None)
- if event.type == YAML_NO_EVENT:
- return None
- elif event.type == YAML_STREAM_START_EVENT:
- encoding = None
- if event.data.stream_start.encoding == YAML_UTF8_ENCODING:
- if self.unicode_source == 0:
- encoding = u"utf-8"
- elif event.data.stream_start.encoding == YAML_UTF16LE_ENCODING:
- encoding = u"utf-16-le"
- elif event.data.stream_start.encoding == YAML_UTF16BE_ENCODING:
- encoding = u"utf-16-be"
- return StreamStartEvent(start_mark, end_mark, encoding)
- elif event.type == YAML_STREAM_END_EVENT:
- return StreamEndEvent(start_mark, end_mark)
- elif event.type == YAML_DOCUMENT_START_EVENT:
- explicit = False
- if event.data.document_start.implicit == 0:
- explicit = True
- version = None
- if event.data.document_start.version_directive != NULL:
- version = (event.data.document_start.version_directive.major,
- event.data.document_start.version_directive.minor)
- tags = None
- if event.data.document_start.tag_directives.start != NULL:
- tags = {}
- tag_directive = event.data.document_start.tag_directives.start
- while tag_directive != event.data.document_start.tag_directives.end:
+ token.data.scalar.length, 'strict')
+ plain = False
+ style = None
+ if token.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
+ plain = True
+ style = u''
+ elif token.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
+ style = u'\''
+ elif token.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
+ style = u'"'
+ elif token.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
+ style = u'|'
+ elif token.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
+ style = u'>'
+ return ScalarToken(value, plain,
+ start_mark, end_mark, style)
+ else:
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("unknown token type")
+ else:
+ raise ValueError(u"unknown token type")
+
+ def get_token(self):
+ if self.current_token is not None:
+ value = self.current_token
+ self.current_token = None
+ else:
+ value = self._scan()
+ return value
+
+ def peek_token(self):
+ if self.current_token is None:
+ self.current_token = self._scan()
+ return self.current_token
+
+ def check_token(self, *choices):
+ if self.current_token is None:
+ self.current_token = self._scan()
+ if self.current_token is None:
+ return False
+ if not choices:
+ return True
+ token_class = self.current_token.__class__
+ for choice in choices:
+ if token_class is choice:
+ return True
+ return False
+
+ def raw_parse(self):
+ cdef yaml_event_t event
+ cdef int done
+ cdef int count
+ count = 0
+ done = 0
+ while done == 0:
+ if yaml_parser_parse(&self.parser, &event) == 0:
+ error = self._parser_error()
+ raise error
+ if event.type == YAML_NO_EVENT:
+ done = 1
+ else:
+ count = count+1
+ yaml_event_delete(&event)
+ return count
+
+ cdef object _parse(self):
+ cdef yaml_event_t event
+ if yaml_parser_parse(&self.parser, &event) == 0:
+ error = self._parser_error()
+ raise error
+ event_object = self._event_to_object(&event)
+ yaml_event_delete(&event)
+ return event_object
+
+ cdef object _event_to_object(self, yaml_event_t *event):
+ cdef yaml_tag_directive_t *tag_directive
+ start_mark = Mark(self.stream_name,
+ event.start_mark.index,
+ event.start_mark.line,
+ event.start_mark.column,
+ None, None)
+ end_mark = Mark(self.stream_name,
+ event.end_mark.index,
+ event.end_mark.line,
+ event.end_mark.column,
+ None, None)
+ if event.type == YAML_NO_EVENT:
+ return None
+ elif event.type == YAML_STREAM_START_EVENT:
+ encoding = None
+ if event.data.stream_start.encoding == YAML_UTF8_ENCODING:
+ if self.unicode_source == 0:
+ encoding = u"utf-8"
+ elif event.data.stream_start.encoding == YAML_UTF16LE_ENCODING:
+ encoding = u"utf-16-le"
+ elif event.data.stream_start.encoding == YAML_UTF16BE_ENCODING:
+ encoding = u"utf-16-be"
+ return StreamStartEvent(start_mark, end_mark, encoding)
+ elif event.type == YAML_STREAM_END_EVENT:
+ return StreamEndEvent(start_mark, end_mark)
+ elif event.type == YAML_DOCUMENT_START_EVENT:
+ explicit = False
+ if event.data.document_start.implicit == 0:
+ explicit = True
+ version = None
+ if event.data.document_start.version_directive != NULL:
+ version = (event.data.document_start.version_directive.major,
+ event.data.document_start.version_directive.minor)
+ tags = None
+ if event.data.document_start.tag_directives.start != NULL:
+ tags = {}
+ tag_directive = event.data.document_start.tag_directives.start
+ while tag_directive != event.data.document_start.tag_directives.end:
handle = PyUnicode_FromString(tag_directive.handle)
prefix = PyUnicode_FromString(tag_directive.prefix)
- tags[handle] = prefix
- tag_directive = tag_directive+1
- return DocumentStartEvent(start_mark, end_mark,
- explicit, version, tags)
- elif event.type == YAML_DOCUMENT_END_EVENT:
- explicit = False
- if event.data.document_end.implicit == 0:
- explicit = True
- return DocumentEndEvent(start_mark, end_mark, explicit)
- elif event.type == YAML_ALIAS_EVENT:
- anchor = PyUnicode_FromString(event.data.alias.anchor)
- return AliasEvent(anchor, start_mark, end_mark)
- elif event.type == YAML_SCALAR_EVENT:
- anchor = None
- if event.data.scalar.anchor != NULL:
- anchor = PyUnicode_FromString(event.data.scalar.anchor)
- tag = None
- if event.data.scalar.tag != NULL:
- tag = PyUnicode_FromString(event.data.scalar.tag)
+ tags[handle] = prefix
+ tag_directive = tag_directive+1
+ return DocumentStartEvent(start_mark, end_mark,
+ explicit, version, tags)
+ elif event.type == YAML_DOCUMENT_END_EVENT:
+ explicit = False
+ if event.data.document_end.implicit == 0:
+ explicit = True
+ return DocumentEndEvent(start_mark, end_mark, explicit)
+ elif event.type == YAML_ALIAS_EVENT:
+ anchor = PyUnicode_FromString(event.data.alias.anchor)
+ return AliasEvent(anchor, start_mark, end_mark)
+ elif event.type == YAML_SCALAR_EVENT:
+ anchor = None
+ if event.data.scalar.anchor != NULL:
+ anchor = PyUnicode_FromString(event.data.scalar.anchor)
+ tag = None
+ if event.data.scalar.tag != NULL:
+ tag = PyUnicode_FromString(event.data.scalar.tag)
value = PyUnicode_DecodeUTF8(event.data.scalar.value,
- event.data.scalar.length, 'strict')
- plain_implicit = False
- if event.data.scalar.plain_implicit == 1:
- plain_implicit = True
- quoted_implicit = False
- if event.data.scalar.quoted_implicit == 1:
- quoted_implicit = True
- style = None
- if event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
- style = u''
- elif event.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
- style = u'\''
- elif event.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
- style = u'"'
- elif event.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
- style = u'|'
- elif event.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
- style = u'>'
- return ScalarEvent(anchor, tag,
- (plain_implicit, quoted_implicit),
- value, start_mark, end_mark, style)
- elif event.type == YAML_SEQUENCE_START_EVENT:
- anchor = None
- if event.data.sequence_start.anchor != NULL:
- anchor = PyUnicode_FromString(event.data.sequence_start.anchor)
- tag = None
- if event.data.sequence_start.tag != NULL:
- tag = PyUnicode_FromString(event.data.sequence_start.tag)
- implicit = False
- if event.data.sequence_start.implicit == 1:
- implicit = True
- flow_style = None
- if event.data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE:
- flow_style = True
- elif event.data.sequence_start.style == YAML_BLOCK_SEQUENCE_STYLE:
- flow_style = False
- return SequenceStartEvent(anchor, tag, implicit,
- start_mark, end_mark, flow_style)
- elif event.type == YAML_MAPPING_START_EVENT:
- anchor = None
- if event.data.mapping_start.anchor != NULL:
- anchor = PyUnicode_FromString(event.data.mapping_start.anchor)
- tag = None
- if event.data.mapping_start.tag != NULL:
- tag = PyUnicode_FromString(event.data.mapping_start.tag)
- implicit = False
- if event.data.mapping_start.implicit == 1:
- implicit = True
- flow_style = None
- if event.data.mapping_start.style == YAML_FLOW_MAPPING_STYLE:
- flow_style = True
- elif event.data.mapping_start.style == YAML_BLOCK_MAPPING_STYLE:
- flow_style = False
- return MappingStartEvent(anchor, tag, implicit,
- start_mark, end_mark, flow_style)
- elif event.type == YAML_SEQUENCE_END_EVENT:
- return SequenceEndEvent(start_mark, end_mark)
- elif event.type == YAML_MAPPING_END_EVENT:
- return MappingEndEvent(start_mark, end_mark)
- else:
- if PY_MAJOR_VERSION < 3:
- raise ValueError("unknown event type")
- else:
- raise ValueError(u"unknown event type")
-
- def get_event(self):
- if self.current_event is not None:
- value = self.current_event
- self.current_event = None
- else:
- value = self._parse()
- return value
-
- def peek_event(self):
- if self.current_event is None:
- self.current_event = self._parse()
- return self.current_event
-
- def check_event(self, *choices):
- if self.current_event is None:
- self.current_event = self._parse()
- if self.current_event is None:
- return False
- if not choices:
- return True
- event_class = self.current_event.__class__
- for choice in choices:
- if event_class is choice:
- return True
- return False
-
- def check_node(self):
- self._parse_next_event()
- if self.parsed_event.type == YAML_STREAM_START_EVENT:
- yaml_event_delete(&self.parsed_event)
- self._parse_next_event()
- if self.parsed_event.type != YAML_STREAM_END_EVENT:
- return True
- return False
-
- def get_node(self):
- self._parse_next_event()
- if self.parsed_event.type != YAML_STREAM_END_EVENT:
- return self._compose_document()
-
- def get_single_node(self):
- self._parse_next_event()
- yaml_event_delete(&self.parsed_event)
- self._parse_next_event()
- document = None
- if self.parsed_event.type != YAML_STREAM_END_EVENT:
- document = self._compose_document()
- self._parse_next_event()
- if self.parsed_event.type != YAML_STREAM_END_EVENT:
- mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- if PY_MAJOR_VERSION < 3:
- raise ComposerError("expected a single document in the stream",
- document.start_mark, "but found another document", mark)
- else:
- raise ComposerError(u"expected a single document in the stream",
- document.start_mark, u"but found another document", mark)
- return document
-
- cdef object _compose_document(self):
- yaml_event_delete(&self.parsed_event)
- node = self._compose_node(None, None)
- self._parse_next_event()
- yaml_event_delete(&self.parsed_event)
- self.anchors = {}
- return node
-
- cdef object _compose_node(self, object parent, object index):
- self._parse_next_event()
- if self.parsed_event.type == YAML_ALIAS_EVENT:
- anchor = PyUnicode_FromString(self.parsed_event.data.alias.anchor)
- if anchor not in self.anchors:
- mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- if PY_MAJOR_VERSION < 3:
- raise ComposerError(None, None, "found undefined alias", mark)
- else:
- raise ComposerError(None, None, u"found undefined alias", mark)
- yaml_event_delete(&self.parsed_event)
- return self.anchors[anchor]
- anchor = None
- if self.parsed_event.type == YAML_SCALAR_EVENT \
- and self.parsed_event.data.scalar.anchor != NULL:
- anchor = PyUnicode_FromString(self.parsed_event.data.scalar.anchor)
- elif self.parsed_event.type == YAML_SEQUENCE_START_EVENT \
- and self.parsed_event.data.sequence_start.anchor != NULL:
- anchor = PyUnicode_FromString(self.parsed_event.data.sequence_start.anchor)
- elif self.parsed_event.type == YAML_MAPPING_START_EVENT \
- and self.parsed_event.data.mapping_start.anchor != NULL:
- anchor = PyUnicode_FromString(self.parsed_event.data.mapping_start.anchor)
- if anchor is not None:
- if anchor in self.anchors:
- mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- if PY_MAJOR_VERSION < 3:
+ event.data.scalar.length, 'strict')
+ plain_implicit = False
+ if event.data.scalar.plain_implicit == 1:
+ plain_implicit = True
+ quoted_implicit = False
+ if event.data.scalar.quoted_implicit == 1:
+ quoted_implicit = True
+ style = None
+ if event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
+ style = u''
+ elif event.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
+ style = u'\''
+ elif event.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
+ style = u'"'
+ elif event.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
+ style = u'|'
+ elif event.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
+ style = u'>'
+ return ScalarEvent(anchor, tag,
+ (plain_implicit, quoted_implicit),
+ value, start_mark, end_mark, style)
+ elif event.type == YAML_SEQUENCE_START_EVENT:
+ anchor = None
+ if event.data.sequence_start.anchor != NULL:
+ anchor = PyUnicode_FromString(event.data.sequence_start.anchor)
+ tag = None
+ if event.data.sequence_start.tag != NULL:
+ tag = PyUnicode_FromString(event.data.sequence_start.tag)
+ implicit = False
+ if event.data.sequence_start.implicit == 1:
+ implicit = True
+ flow_style = None
+ if event.data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE:
+ flow_style = True
+ elif event.data.sequence_start.style == YAML_BLOCK_SEQUENCE_STYLE:
+ flow_style = False
+ return SequenceStartEvent(anchor, tag, implicit,
+ start_mark, end_mark, flow_style)
+ elif event.type == YAML_MAPPING_START_EVENT:
+ anchor = None
+ if event.data.mapping_start.anchor != NULL:
+ anchor = PyUnicode_FromString(event.data.mapping_start.anchor)
+ tag = None
+ if event.data.mapping_start.tag != NULL:
+ tag = PyUnicode_FromString(event.data.mapping_start.tag)
+ implicit = False
+ if event.data.mapping_start.implicit == 1:
+ implicit = True
+ flow_style = None
+ if event.data.mapping_start.style == YAML_FLOW_MAPPING_STYLE:
+ flow_style = True
+ elif event.data.mapping_start.style == YAML_BLOCK_MAPPING_STYLE:
+ flow_style = False
+ return MappingStartEvent(anchor, tag, implicit,
+ start_mark, end_mark, flow_style)
+ elif event.type == YAML_SEQUENCE_END_EVENT:
+ return SequenceEndEvent(start_mark, end_mark)
+ elif event.type == YAML_MAPPING_END_EVENT:
+ return MappingEndEvent(start_mark, end_mark)
+ else:
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("unknown event type")
+ else:
+ raise ValueError(u"unknown event type")
+
+ def get_event(self):
+ if self.current_event is not None:
+ value = self.current_event
+ self.current_event = None
+ else:
+ value = self._parse()
+ return value
+
+ def peek_event(self):
+ if self.current_event is None:
+ self.current_event = self._parse()
+ return self.current_event
+
+ def check_event(self, *choices):
+ if self.current_event is None:
+ self.current_event = self._parse()
+ if self.current_event is None:
+ return False
+ if not choices:
+ return True
+ event_class = self.current_event.__class__
+ for choice in choices:
+ if event_class is choice:
+ return True
+ return False
+
+ def check_node(self):
+ self._parse_next_event()
+ if self.parsed_event.type == YAML_STREAM_START_EVENT:
+ yaml_event_delete(&self.parsed_event)
+ self._parse_next_event()
+ if self.parsed_event.type != YAML_STREAM_END_EVENT:
+ return True
+ return False
+
+ def get_node(self):
+ self._parse_next_event()
+ if self.parsed_event.type != YAML_STREAM_END_EVENT:
+ return self._compose_document()
+
+ def get_single_node(self):
+ self._parse_next_event()
+ yaml_event_delete(&self.parsed_event)
+ self._parse_next_event()
+ document = None
+ if self.parsed_event.type != YAML_STREAM_END_EVENT:
+ document = self._compose_document()
+ self._parse_next_event()
+ if self.parsed_event.type != YAML_STREAM_END_EVENT:
+ mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ if PY_MAJOR_VERSION < 3:
+ raise ComposerError("expected a single document in the stream",
+ document.start_mark, "but found another document", mark)
+ else:
+ raise ComposerError(u"expected a single document in the stream",
+ document.start_mark, u"but found another document", mark)
+ return document
+
+ cdef object _compose_document(self):
+ yaml_event_delete(&self.parsed_event)
+ node = self._compose_node(None, None)
+ self._parse_next_event()
+ yaml_event_delete(&self.parsed_event)
+ self.anchors = {}
+ return node
+
+ cdef object _compose_node(self, object parent, object index):
+ self._parse_next_event()
+ if self.parsed_event.type == YAML_ALIAS_EVENT:
+ anchor = PyUnicode_FromString(self.parsed_event.data.alias.anchor)
+ if anchor not in self.anchors:
+ mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ if PY_MAJOR_VERSION < 3:
+ raise ComposerError(None, None, "found undefined alias", mark)
+ else:
+ raise ComposerError(None, None, u"found undefined alias", mark)
+ yaml_event_delete(&self.parsed_event)
+ return self.anchors[anchor]
+ anchor = None
+ if self.parsed_event.type == YAML_SCALAR_EVENT \
+ and self.parsed_event.data.scalar.anchor != NULL:
+ anchor = PyUnicode_FromString(self.parsed_event.data.scalar.anchor)
+ elif self.parsed_event.type == YAML_SEQUENCE_START_EVENT \
+ and self.parsed_event.data.sequence_start.anchor != NULL:
+ anchor = PyUnicode_FromString(self.parsed_event.data.sequence_start.anchor)
+ elif self.parsed_event.type == YAML_MAPPING_START_EVENT \
+ and self.parsed_event.data.mapping_start.anchor != NULL:
+ anchor = PyUnicode_FromString(self.parsed_event.data.mapping_start.anchor)
+ if anchor is not None:
+ if anchor in self.anchors:
+ mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ if PY_MAJOR_VERSION < 3:
raise ComposerError("found duplicate anchor; first occurrence",
self.anchors[anchor].start_mark, "second occurrence", mark)
- else:
+ else:
raise ComposerError(u"found duplicate anchor; first occurrence",
self.anchors[anchor].start_mark, u"second occurrence", mark)
- self.descend_resolver(parent, index)
- if self.parsed_event.type == YAML_SCALAR_EVENT:
- node = self._compose_scalar_node(anchor)
- elif self.parsed_event.type == YAML_SEQUENCE_START_EVENT:
- node = self._compose_sequence_node(anchor)
- elif self.parsed_event.type == YAML_MAPPING_START_EVENT:
- node = self._compose_mapping_node(anchor)
- self.ascend_resolver()
- return node
-
- cdef _compose_scalar_node(self, object anchor):
- start_mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- end_mark = Mark(self.stream_name,
- self.parsed_event.end_mark.index,
- self.parsed_event.end_mark.line,
- self.parsed_event.end_mark.column,
- None, None)
+ self.descend_resolver(parent, index)
+ if self.parsed_event.type == YAML_SCALAR_EVENT:
+ node = self._compose_scalar_node(anchor)
+ elif self.parsed_event.type == YAML_SEQUENCE_START_EVENT:
+ node = self._compose_sequence_node(anchor)
+ elif self.parsed_event.type == YAML_MAPPING_START_EVENT:
+ node = self._compose_mapping_node(anchor)
+ self.ascend_resolver()
+ return node
+
+ cdef _compose_scalar_node(self, object anchor):
+ start_mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ end_mark = Mark(self.stream_name,
+ self.parsed_event.end_mark.index,
+ self.parsed_event.end_mark.line,
+ self.parsed_event.end_mark.column,
+ None, None)
value = PyUnicode_DecodeUTF8(self.parsed_event.data.scalar.value,
- self.parsed_event.data.scalar.length, 'strict')
- plain_implicit = False
- if self.parsed_event.data.scalar.plain_implicit == 1:
- plain_implicit = True
- quoted_implicit = False
- if self.parsed_event.data.scalar.quoted_implicit == 1:
- quoted_implicit = True
- if self.parsed_event.data.scalar.tag == NULL \
- or (self.parsed_event.data.scalar.tag[0] == c'!'
- and self.parsed_event.data.scalar.tag[1] == c'\0'):
- tag = self.resolve(ScalarNode, value, (plain_implicit, quoted_implicit))
- else:
- tag = PyUnicode_FromString(self.parsed_event.data.scalar.tag)
- style = None
- if self.parsed_event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
- style = u''
- elif self.parsed_event.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
- style = u'\''
- elif self.parsed_event.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
- style = u'"'
- elif self.parsed_event.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
- style = u'|'
- elif self.parsed_event.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
- style = u'>'
- node = ScalarNode(tag, value, start_mark, end_mark, style)
- if anchor is not None:
- self.anchors[anchor] = node
- yaml_event_delete(&self.parsed_event)
- return node
-
- cdef _compose_sequence_node(self, object anchor):
- cdef int index
- start_mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- implicit = False
- if self.parsed_event.data.sequence_start.implicit == 1:
- implicit = True
- if self.parsed_event.data.sequence_start.tag == NULL \
- or (self.parsed_event.data.sequence_start.tag[0] == c'!'
- and self.parsed_event.data.sequence_start.tag[1] == c'\0'):
- tag = self.resolve(SequenceNode, None, implicit)
- else:
- tag = PyUnicode_FromString(self.parsed_event.data.sequence_start.tag)
- flow_style = None
- if self.parsed_event.data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE:
- flow_style = True
- elif self.parsed_event.data.sequence_start.style == YAML_BLOCK_SEQUENCE_STYLE:
- flow_style = False
- value = []
- node = SequenceNode(tag, value, start_mark, None, flow_style)
- if anchor is not None:
- self.anchors[anchor] = node
- yaml_event_delete(&self.parsed_event)
- index = 0
- self._parse_next_event()
- while self.parsed_event.type != YAML_SEQUENCE_END_EVENT:
- value.append(self._compose_node(node, index))
- index = index+1
- self._parse_next_event()
- node.end_mark = Mark(self.stream_name,
- self.parsed_event.end_mark.index,
- self.parsed_event.end_mark.line,
- self.parsed_event.end_mark.column,
- None, None)
- yaml_event_delete(&self.parsed_event)
- return node
-
- cdef _compose_mapping_node(self, object anchor):
- start_mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- implicit = False
- if self.parsed_event.data.mapping_start.implicit == 1:
- implicit = True
- if self.parsed_event.data.mapping_start.tag == NULL \
- or (self.parsed_event.data.mapping_start.tag[0] == c'!'
- and self.parsed_event.data.mapping_start.tag[1] == c'\0'):
- tag = self.resolve(MappingNode, None, implicit)
- else:
- tag = PyUnicode_FromString(self.parsed_event.data.mapping_start.tag)
- flow_style = None
- if self.parsed_event.data.mapping_start.style == YAML_FLOW_MAPPING_STYLE:
- flow_style = True
- elif self.parsed_event.data.mapping_start.style == YAML_BLOCK_MAPPING_STYLE:
- flow_style = False
- value = []
- node = MappingNode(tag, value, start_mark, None, flow_style)
- if anchor is not None:
- self.anchors[anchor] = node
- yaml_event_delete(&self.parsed_event)
- self._parse_next_event()
- while self.parsed_event.type != YAML_MAPPING_END_EVENT:
- item_key = self._compose_node(node, None)
- item_value = self._compose_node(node, item_key)
- value.append((item_key, item_value))
- self._parse_next_event()
- node.end_mark = Mark(self.stream_name,
- self.parsed_event.end_mark.index,
- self.parsed_event.end_mark.line,
- self.parsed_event.end_mark.column,
- None, None)
- yaml_event_delete(&self.parsed_event)
- return node
-
- cdef int _parse_next_event(self) except 0:
- if self.parsed_event.type == YAML_NO_EVENT:
- if yaml_parser_parse(&self.parser, &self.parsed_event) == 0:
- error = self._parser_error()
- raise error
- return 1
-
+ self.parsed_event.data.scalar.length, 'strict')
+ plain_implicit = False
+ if self.parsed_event.data.scalar.plain_implicit == 1:
+ plain_implicit = True
+ quoted_implicit = False
+ if self.parsed_event.data.scalar.quoted_implicit == 1:
+ quoted_implicit = True
+ if self.parsed_event.data.scalar.tag == NULL \
+ or (self.parsed_event.data.scalar.tag[0] == c'!'
+ and self.parsed_event.data.scalar.tag[1] == c'\0'):
+ tag = self.resolve(ScalarNode, value, (plain_implicit, quoted_implicit))
+ else:
+ tag = PyUnicode_FromString(self.parsed_event.data.scalar.tag)
+ style = None
+ if self.parsed_event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
+ style = u''
+ elif self.parsed_event.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
+ style = u'\''
+ elif self.parsed_event.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
+ style = u'"'
+ elif self.parsed_event.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
+ style = u'|'
+ elif self.parsed_event.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
+ style = u'>'
+ node = ScalarNode(tag, value, start_mark, end_mark, style)
+ if anchor is not None:
+ self.anchors[anchor] = node
+ yaml_event_delete(&self.parsed_event)
+ return node
+
+ cdef _compose_sequence_node(self, object anchor):
+ cdef int index
+ start_mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ implicit = False
+ if self.parsed_event.data.sequence_start.implicit == 1:
+ implicit = True
+ if self.parsed_event.data.sequence_start.tag == NULL \
+ or (self.parsed_event.data.sequence_start.tag[0] == c'!'
+ and self.parsed_event.data.sequence_start.tag[1] == c'\0'):
+ tag = self.resolve(SequenceNode, None, implicit)
+ else:
+ tag = PyUnicode_FromString(self.parsed_event.data.sequence_start.tag)
+ flow_style = None
+ if self.parsed_event.data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE:
+ flow_style = True
+ elif self.parsed_event.data.sequence_start.style == YAML_BLOCK_SEQUENCE_STYLE:
+ flow_style = False
+ value = []
+ node = SequenceNode(tag, value, start_mark, None, flow_style)
+ if anchor is not None:
+ self.anchors[anchor] = node
+ yaml_event_delete(&self.parsed_event)
+ index = 0
+ self._parse_next_event()
+ while self.parsed_event.type != YAML_SEQUENCE_END_EVENT:
+ value.append(self._compose_node(node, index))
+ index = index+1
+ self._parse_next_event()
+ node.end_mark = Mark(self.stream_name,
+ self.parsed_event.end_mark.index,
+ self.parsed_event.end_mark.line,
+ self.parsed_event.end_mark.column,
+ None, None)
+ yaml_event_delete(&self.parsed_event)
+ return node
+
+ cdef _compose_mapping_node(self, object anchor):
+ start_mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ implicit = False
+ if self.parsed_event.data.mapping_start.implicit == 1:
+ implicit = True
+ if self.parsed_event.data.mapping_start.tag == NULL \
+ or (self.parsed_event.data.mapping_start.tag[0] == c'!'
+ and self.parsed_event.data.mapping_start.tag[1] == c'\0'):
+ tag = self.resolve(MappingNode, None, implicit)
+ else:
+ tag = PyUnicode_FromString(self.parsed_event.data.mapping_start.tag)
+ flow_style = None
+ if self.parsed_event.data.mapping_start.style == YAML_FLOW_MAPPING_STYLE:
+ flow_style = True
+ elif self.parsed_event.data.mapping_start.style == YAML_BLOCK_MAPPING_STYLE:
+ flow_style = False
+ value = []
+ node = MappingNode(tag, value, start_mark, None, flow_style)
+ if anchor is not None:
+ self.anchors[anchor] = node
+ yaml_event_delete(&self.parsed_event)
+ self._parse_next_event()
+ while self.parsed_event.type != YAML_MAPPING_END_EVENT:
+ item_key = self._compose_node(node, None)
+ item_value = self._compose_node(node, item_key)
+ value.append((item_key, item_value))
+ self._parse_next_event()
+ node.end_mark = Mark(self.stream_name,
+ self.parsed_event.end_mark.index,
+ self.parsed_event.end_mark.line,
+ self.parsed_event.end_mark.column,
+ None, None)
+ yaml_event_delete(&self.parsed_event)
+ return node
+
+ cdef int _parse_next_event(self) except 0:
+ if self.parsed_event.type == YAML_NO_EVENT:
+ if yaml_parser_parse(&self.parser, &self.parsed_event) == 0:
+ error = self._parser_error()
+ raise error
+ return 1
+
cdef int input_handler(void *data, char *buffer, size_t size, size_t *read) except 0:
- cdef CParser parser
- parser = <CParser>data
- if parser.stream_cache is None:
- value = parser.stream.read(size)
- if PyUnicode_CheckExact(value) != 0:
- value = PyUnicode_AsUTF8String(value)
- parser.unicode_source = 1
- if PyString_CheckExact(value) == 0:
- if PY_MAJOR_VERSION < 3:
- raise TypeError("a string value is expected")
- else:
- raise TypeError(u"a string value is expected")
- parser.stream_cache = value
- parser.stream_cache_pos = 0
- parser.stream_cache_len = PyString_GET_SIZE(value)
- if (parser.stream_cache_len - parser.stream_cache_pos) < size:
- size = parser.stream_cache_len - parser.stream_cache_pos
- if size > 0:
+ cdef CParser parser
+ parser = <CParser>data
+ if parser.stream_cache is None:
+ value = parser.stream.read(size)
+ if PyUnicode_CheckExact(value) != 0:
+ value = PyUnicode_AsUTF8String(value)
+ parser.unicode_source = 1
+ if PyString_CheckExact(value) == 0:
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("a string value is expected")
+ else:
+ raise TypeError(u"a string value is expected")
+ parser.stream_cache = value
+ parser.stream_cache_pos = 0
+ parser.stream_cache_len = PyString_GET_SIZE(value)
+ if (parser.stream_cache_len - parser.stream_cache_pos) < size:
+ size = parser.stream_cache_len - parser.stream_cache_pos
+ if size > 0:
memcpy(buffer, PyString_AS_STRING(parser.stream_cache)
- + parser.stream_cache_pos, size)
- read[0] = size
- parser.stream_cache_pos += size
- if parser.stream_cache_pos == parser.stream_cache_len:
- parser.stream_cache = None
- return 1
-
-cdef class CEmitter:
-
- cdef yaml_emitter_t emitter
-
- cdef object stream
-
- cdef int document_start_implicit
- cdef int document_end_implicit
- cdef object use_version
- cdef object use_tags
-
- cdef object serialized_nodes
- cdef object anchors
- cdef int last_alias_id
- cdef int closed
- cdef int dump_unicode
- cdef object use_encoding
-
- def __init__(self, stream, canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None, encoding=None,
- explicit_start=None, explicit_end=None, version=None, tags=None):
- if yaml_emitter_initialize(&self.emitter) == 0:
- raise MemoryError
- self.stream = stream
- self.dump_unicode = 0
- if PY_MAJOR_VERSION < 3:
- if getattr3(stream, 'encoding', None):
- self.dump_unicode = 1
- else:
- if hasattr(stream, u'encoding'):
- self.dump_unicode = 1
- self.use_encoding = encoding
+ + parser.stream_cache_pos, size)
+ read[0] = size
+ parser.stream_cache_pos += size
+ if parser.stream_cache_pos == parser.stream_cache_len:
+ parser.stream_cache = None
+ return 1
+
+cdef class CEmitter:
+
+ cdef yaml_emitter_t emitter
+
+ cdef object stream
+
+ cdef int document_start_implicit
+ cdef int document_end_implicit
+ cdef object use_version
+ cdef object use_tags
+
+ cdef object serialized_nodes
+ cdef object anchors
+ cdef int last_alias_id
+ cdef int closed
+ cdef int dump_unicode
+ cdef object use_encoding
+
+ def __init__(self, stream, canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None, encoding=None,
+ explicit_start=None, explicit_end=None, version=None, tags=None):
+ if yaml_emitter_initialize(&self.emitter) == 0:
+ raise MemoryError
+ self.stream = stream
+ self.dump_unicode = 0
+ if PY_MAJOR_VERSION < 3:
+ if getattr3(stream, 'encoding', None):
+ self.dump_unicode = 1
+ else:
+ if hasattr(stream, u'encoding'):
+ self.dump_unicode = 1
+ self.use_encoding = encoding
yaml_emitter_set_output(&self.emitter, output_handler, <void *>self)
- if canonical:
- yaml_emitter_set_canonical(&self.emitter, 1)
- if indent is not None:
- yaml_emitter_set_indent(&self.emitter, indent)
- if width is not None:
- yaml_emitter_set_width(&self.emitter, width)
- if allow_unicode:
- yaml_emitter_set_unicode(&self.emitter, 1)
- if line_break is not None:
- if line_break == '\r':
- yaml_emitter_set_break(&self.emitter, YAML_CR_BREAK)
- elif line_break == '\n':
- yaml_emitter_set_break(&self.emitter, YAML_LN_BREAK)
- elif line_break == '\r\n':
- yaml_emitter_set_break(&self.emitter, YAML_CRLN_BREAK)
- self.document_start_implicit = 1
- if explicit_start:
- self.document_start_implicit = 0
- self.document_end_implicit = 1
- if explicit_end:
- self.document_end_implicit = 0
- self.use_version = version
- self.use_tags = tags
- self.serialized_nodes = {}
- self.anchors = {}
- self.last_alias_id = 0
- self.closed = -1
-
- def __dealloc__(self):
- yaml_emitter_delete(&self.emitter)
-
- def dispose(self):
- pass
-
- cdef object _emitter_error(self):
- if self.emitter.error == YAML_MEMORY_ERROR:
- return MemoryError
- elif self.emitter.error == YAML_EMITTER_ERROR:
- if PY_MAJOR_VERSION < 3:
- problem = self.emitter.problem
- else:
- problem = PyUnicode_FromString(self.emitter.problem)
- return EmitterError(problem)
- if PY_MAJOR_VERSION < 3:
- raise ValueError("no emitter error")
- else:
- raise ValueError(u"no emitter error")
-
- cdef int _object_to_event(self, object event_object, yaml_event_t *event) except 0:
- cdef yaml_encoding_t encoding
- cdef yaml_version_directive_t version_directive_value
- cdef yaml_version_directive_t *version_directive
- cdef yaml_tag_directive_t tag_directives_value[128]
- cdef yaml_tag_directive_t *tag_directives_start
- cdef yaml_tag_directive_t *tag_directives_end
- cdef int implicit
- cdef int plain_implicit
- cdef int quoted_implicit
- cdef char *anchor
- cdef char *tag
- cdef char *value
- cdef int length
- cdef yaml_scalar_style_t scalar_style
- cdef yaml_sequence_style_t sequence_style
- cdef yaml_mapping_style_t mapping_style
- event_class = event_object.__class__
- if event_class is StreamStartEvent:
- encoding = YAML_UTF8_ENCODING
- if event_object.encoding == u'utf-16-le' or event_object.encoding == 'utf-16-le':
- encoding = YAML_UTF16LE_ENCODING
- elif event_object.encoding == u'utf-16-be' or event_object.encoding == 'utf-16-be':
- encoding = YAML_UTF16BE_ENCODING
- if event_object.encoding is None:
- self.dump_unicode = 1
- if self.dump_unicode == 1:
- encoding = YAML_UTF8_ENCODING
- yaml_stream_start_event_initialize(event, encoding)
- elif event_class is StreamEndEvent:
- yaml_stream_end_event_initialize(event)
- elif event_class is DocumentStartEvent:
- version_directive = NULL
- if event_object.version:
- version_directive_value.major = event_object.version[0]
- version_directive_value.minor = event_object.version[1]
- version_directive = &version_directive_value
- tag_directives_start = NULL
- tag_directives_end = NULL
- if event_object.tags:
- if len(event_object.tags) > 128:
- if PY_MAJOR_VERSION < 3:
- raise ValueError("too many tags")
- else:
- raise ValueError(u"too many tags")
- tag_directives_start = tag_directives_value
- tag_directives_end = tag_directives_value
- cache = []
- for handle in event_object.tags:
- prefix = event_object.tags[handle]
- if PyUnicode_CheckExact(handle):
- handle = PyUnicode_AsUTF8String(handle)
- cache.append(handle)
- if not PyString_CheckExact(handle):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag handle must be a string")
- else:
- raise TypeError(u"tag handle must be a string")
+ if canonical:
+ yaml_emitter_set_canonical(&self.emitter, 1)
+ if indent is not None:
+ yaml_emitter_set_indent(&self.emitter, indent)
+ if width is not None:
+ yaml_emitter_set_width(&self.emitter, width)
+ if allow_unicode:
+ yaml_emitter_set_unicode(&self.emitter, 1)
+ if line_break is not None:
+ if line_break == '\r':
+ yaml_emitter_set_break(&self.emitter, YAML_CR_BREAK)
+ elif line_break == '\n':
+ yaml_emitter_set_break(&self.emitter, YAML_LN_BREAK)
+ elif line_break == '\r\n':
+ yaml_emitter_set_break(&self.emitter, YAML_CRLN_BREAK)
+ self.document_start_implicit = 1
+ if explicit_start:
+ self.document_start_implicit = 0
+ self.document_end_implicit = 1
+ if explicit_end:
+ self.document_end_implicit = 0
+ self.use_version = version
+ self.use_tags = tags
+ self.serialized_nodes = {}
+ self.anchors = {}
+ self.last_alias_id = 0
+ self.closed = -1
+
+ def __dealloc__(self):
+ yaml_emitter_delete(&self.emitter)
+
+ def dispose(self):
+ pass
+
+ cdef object _emitter_error(self):
+ if self.emitter.error == YAML_MEMORY_ERROR:
+ return MemoryError
+ elif self.emitter.error == YAML_EMITTER_ERROR:
+ if PY_MAJOR_VERSION < 3:
+ problem = self.emitter.problem
+ else:
+ problem = PyUnicode_FromString(self.emitter.problem)
+ return EmitterError(problem)
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("no emitter error")
+ else:
+ raise ValueError(u"no emitter error")
+
+ cdef int _object_to_event(self, object event_object, yaml_event_t *event) except 0:
+ cdef yaml_encoding_t encoding
+ cdef yaml_version_directive_t version_directive_value
+ cdef yaml_version_directive_t *version_directive
+ cdef yaml_tag_directive_t tag_directives_value[128]
+ cdef yaml_tag_directive_t *tag_directives_start
+ cdef yaml_tag_directive_t *tag_directives_end
+ cdef int implicit
+ cdef int plain_implicit
+ cdef int quoted_implicit
+ cdef char *anchor
+ cdef char *tag
+ cdef char *value
+ cdef int length
+ cdef yaml_scalar_style_t scalar_style
+ cdef yaml_sequence_style_t sequence_style
+ cdef yaml_mapping_style_t mapping_style
+ event_class = event_object.__class__
+ if event_class is StreamStartEvent:
+ encoding = YAML_UTF8_ENCODING
+ if event_object.encoding == u'utf-16-le' or event_object.encoding == 'utf-16-le':
+ encoding = YAML_UTF16LE_ENCODING
+ elif event_object.encoding == u'utf-16-be' or event_object.encoding == 'utf-16-be':
+ encoding = YAML_UTF16BE_ENCODING
+ if event_object.encoding is None:
+ self.dump_unicode = 1
+ if self.dump_unicode == 1:
+ encoding = YAML_UTF8_ENCODING
+ yaml_stream_start_event_initialize(event, encoding)
+ elif event_class is StreamEndEvent:
+ yaml_stream_end_event_initialize(event)
+ elif event_class is DocumentStartEvent:
+ version_directive = NULL
+ if event_object.version:
+ version_directive_value.major = event_object.version[0]
+ version_directive_value.minor = event_object.version[1]
+ version_directive = &version_directive_value
+ tag_directives_start = NULL
+ tag_directives_end = NULL
+ if event_object.tags:
+ if len(event_object.tags) > 128:
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("too many tags")
+ else:
+ raise ValueError(u"too many tags")
+ tag_directives_start = tag_directives_value
+ tag_directives_end = tag_directives_value
+ cache = []
+ for handle in event_object.tags:
+ prefix = event_object.tags[handle]
+ if PyUnicode_CheckExact(handle):
+ handle = PyUnicode_AsUTF8String(handle)
+ cache.append(handle)
+ if not PyString_CheckExact(handle):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag handle must be a string")
+ else:
+ raise TypeError(u"tag handle must be a string")
tag_directives_end.handle = PyString_AS_STRING(handle)
- if PyUnicode_CheckExact(prefix):
- prefix = PyUnicode_AsUTF8String(prefix)
- cache.append(prefix)
- if not PyString_CheckExact(prefix):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag prefix must be a string")
- else:
- raise TypeError(u"tag prefix must be a string")
+ if PyUnicode_CheckExact(prefix):
+ prefix = PyUnicode_AsUTF8String(prefix)
+ cache.append(prefix)
+ if not PyString_CheckExact(prefix):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag prefix must be a string")
+ else:
+ raise TypeError(u"tag prefix must be a string")
tag_directives_end.prefix = PyString_AS_STRING(prefix)
- tag_directives_end = tag_directives_end+1
- implicit = 1
- if event_object.explicit:
- implicit = 0
- if yaml_document_start_event_initialize(event, version_directive,
- tag_directives_start, tag_directives_end, implicit) == 0:
- raise MemoryError
- elif event_class is DocumentEndEvent:
- implicit = 1
- if event_object.explicit:
- implicit = 0
- yaml_document_end_event_initialize(event, implicit)
- elif event_class is AliasEvent:
- anchor = NULL
- anchor_object = event_object.anchor
- if PyUnicode_CheckExact(anchor_object):
- anchor_object = PyUnicode_AsUTF8String(anchor_object)
- if not PyString_CheckExact(anchor_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("anchor must be a string")
- else:
- raise TypeError(u"anchor must be a string")
- anchor = PyString_AS_STRING(anchor_object)
+ tag_directives_end = tag_directives_end+1
+ implicit = 1
+ if event_object.explicit:
+ implicit = 0
+ if yaml_document_start_event_initialize(event, version_directive,
+ tag_directives_start, tag_directives_end, implicit) == 0:
+ raise MemoryError
+ elif event_class is DocumentEndEvent:
+ implicit = 1
+ if event_object.explicit:
+ implicit = 0
+ yaml_document_end_event_initialize(event, implicit)
+ elif event_class is AliasEvent:
+ anchor = NULL
+ anchor_object = event_object.anchor
+ if PyUnicode_CheckExact(anchor_object):
+ anchor_object = PyUnicode_AsUTF8String(anchor_object)
+ if not PyString_CheckExact(anchor_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("anchor must be a string")
+ else:
+ raise TypeError(u"anchor must be a string")
+ anchor = PyString_AS_STRING(anchor_object)
if yaml_alias_event_initialize(event, anchor) == 0:
- raise MemoryError
- elif event_class is ScalarEvent:
- anchor = NULL
- anchor_object = event_object.anchor
- if anchor_object is not None:
- if PyUnicode_CheckExact(anchor_object):
- anchor_object = PyUnicode_AsUTF8String(anchor_object)
- if not PyString_CheckExact(anchor_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("anchor must be a string")
- else:
- raise TypeError(u"anchor must be a string")
- anchor = PyString_AS_STRING(anchor_object)
- tag = NULL
- tag_object = event_object.tag
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- value_object = event_object.value
- if PyUnicode_CheckExact(value_object):
- value_object = PyUnicode_AsUTF8String(value_object)
- if not PyString_CheckExact(value_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("value must be a string")
- else:
- raise TypeError(u"value must be a string")
- value = PyString_AS_STRING(value_object)
- length = PyString_GET_SIZE(value_object)
- plain_implicit = 0
- quoted_implicit = 0
- if event_object.implicit is not None:
- plain_implicit = event_object.implicit[0]
- quoted_implicit = event_object.implicit[1]
- style_object = event_object.style
- scalar_style = YAML_PLAIN_SCALAR_STYLE
- if style_object == "'" or style_object == u"'":
- scalar_style = YAML_SINGLE_QUOTED_SCALAR_STYLE
- elif style_object == "\"" or style_object == u"\"":
- scalar_style = YAML_DOUBLE_QUOTED_SCALAR_STYLE
- elif style_object == "|" or style_object == u"|":
- scalar_style = YAML_LITERAL_SCALAR_STYLE
- elif style_object == ">" or style_object == u">":
- scalar_style = YAML_FOLDED_SCALAR_STYLE
+ raise MemoryError
+ elif event_class is ScalarEvent:
+ anchor = NULL
+ anchor_object = event_object.anchor
+ if anchor_object is not None:
+ if PyUnicode_CheckExact(anchor_object):
+ anchor_object = PyUnicode_AsUTF8String(anchor_object)
+ if not PyString_CheckExact(anchor_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("anchor must be a string")
+ else:
+ raise TypeError(u"anchor must be a string")
+ anchor = PyString_AS_STRING(anchor_object)
+ tag = NULL
+ tag_object = event_object.tag
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ value_object = event_object.value
+ if PyUnicode_CheckExact(value_object):
+ value_object = PyUnicode_AsUTF8String(value_object)
+ if not PyString_CheckExact(value_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("value must be a string")
+ else:
+ raise TypeError(u"value must be a string")
+ value = PyString_AS_STRING(value_object)
+ length = PyString_GET_SIZE(value_object)
+ plain_implicit = 0
+ quoted_implicit = 0
+ if event_object.implicit is not None:
+ plain_implicit = event_object.implicit[0]
+ quoted_implicit = event_object.implicit[1]
+ style_object = event_object.style
+ scalar_style = YAML_PLAIN_SCALAR_STYLE
+ if style_object == "'" or style_object == u"'":
+ scalar_style = YAML_SINGLE_QUOTED_SCALAR_STYLE
+ elif style_object == "\"" or style_object == u"\"":
+ scalar_style = YAML_DOUBLE_QUOTED_SCALAR_STYLE
+ elif style_object == "|" or style_object == u"|":
+ scalar_style = YAML_LITERAL_SCALAR_STYLE
+ elif style_object == ">" or style_object == u">":
+ scalar_style = YAML_FOLDED_SCALAR_STYLE
if yaml_scalar_event_initialize(event, anchor, tag, value, length,
- plain_implicit, quoted_implicit, scalar_style) == 0:
- raise MemoryError
- elif event_class is SequenceStartEvent:
- anchor = NULL
- anchor_object = event_object.anchor
- if anchor_object is not None:
- if PyUnicode_CheckExact(anchor_object):
- anchor_object = PyUnicode_AsUTF8String(anchor_object)
- if not PyString_CheckExact(anchor_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("anchor must be a string")
- else:
- raise TypeError(u"anchor must be a string")
- anchor = PyString_AS_STRING(anchor_object)
- tag = NULL
- tag_object = event_object.tag
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- implicit = 0
- if event_object.implicit:
- implicit = 1
- sequence_style = YAML_BLOCK_SEQUENCE_STYLE
- if event_object.flow_style:
- sequence_style = YAML_FLOW_SEQUENCE_STYLE
+ plain_implicit, quoted_implicit, scalar_style) == 0:
+ raise MemoryError
+ elif event_class is SequenceStartEvent:
+ anchor = NULL
+ anchor_object = event_object.anchor
+ if anchor_object is not None:
+ if PyUnicode_CheckExact(anchor_object):
+ anchor_object = PyUnicode_AsUTF8String(anchor_object)
+ if not PyString_CheckExact(anchor_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("anchor must be a string")
+ else:
+ raise TypeError(u"anchor must be a string")
+ anchor = PyString_AS_STRING(anchor_object)
+ tag = NULL
+ tag_object = event_object.tag
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ implicit = 0
+ if event_object.implicit:
+ implicit = 1
+ sequence_style = YAML_BLOCK_SEQUENCE_STYLE
+ if event_object.flow_style:
+ sequence_style = YAML_FLOW_SEQUENCE_STYLE
if yaml_sequence_start_event_initialize(event, anchor, tag,
- implicit, sequence_style) == 0:
- raise MemoryError
- elif event_class is MappingStartEvent:
- anchor = NULL
- anchor_object = event_object.anchor
- if anchor_object is not None:
- if PyUnicode_CheckExact(anchor_object):
- anchor_object = PyUnicode_AsUTF8String(anchor_object)
- if not PyString_CheckExact(anchor_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("anchor must be a string")
- else:
- raise TypeError(u"anchor must be a string")
- anchor = PyString_AS_STRING(anchor_object)
- tag = NULL
- tag_object = event_object.tag
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- implicit = 0
- if event_object.implicit:
- implicit = 1
- mapping_style = YAML_BLOCK_MAPPING_STYLE
- if event_object.flow_style:
- mapping_style = YAML_FLOW_MAPPING_STYLE
+ implicit, sequence_style) == 0:
+ raise MemoryError
+ elif event_class is MappingStartEvent:
+ anchor = NULL
+ anchor_object = event_object.anchor
+ if anchor_object is not None:
+ if PyUnicode_CheckExact(anchor_object):
+ anchor_object = PyUnicode_AsUTF8String(anchor_object)
+ if not PyString_CheckExact(anchor_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("anchor must be a string")
+ else:
+ raise TypeError(u"anchor must be a string")
+ anchor = PyString_AS_STRING(anchor_object)
+ tag = NULL
+ tag_object = event_object.tag
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ implicit = 0
+ if event_object.implicit:
+ implicit = 1
+ mapping_style = YAML_BLOCK_MAPPING_STYLE
+ if event_object.flow_style:
+ mapping_style = YAML_FLOW_MAPPING_STYLE
if yaml_mapping_start_event_initialize(event, anchor, tag,
- implicit, mapping_style) == 0:
- raise MemoryError
- elif event_class is SequenceEndEvent:
- yaml_sequence_end_event_initialize(event)
- elif event_class is MappingEndEvent:
- yaml_mapping_end_event_initialize(event)
- else:
- if PY_MAJOR_VERSION < 3:
- raise TypeError("invalid event %s" % event_object)
- else:
- raise TypeError(u"invalid event %s" % event_object)
- return 1
-
- def emit(self, event_object):
- cdef yaml_event_t event
- self._object_to_event(event_object, &event)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
-
- def open(self):
- cdef yaml_event_t event
- cdef yaml_encoding_t encoding
- if self.closed == -1:
- if self.use_encoding == u'utf-16-le' or self.use_encoding == 'utf-16-le':
- encoding = YAML_UTF16LE_ENCODING
- elif self.use_encoding == u'utf-16-be' or self.use_encoding == 'utf-16-be':
- encoding = YAML_UTF16BE_ENCODING
- else:
- encoding = YAML_UTF8_ENCODING
- if self.use_encoding is None:
- self.dump_unicode = 1
- if self.dump_unicode == 1:
- encoding = YAML_UTF8_ENCODING
- yaml_stream_start_event_initialize(&event, encoding)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- self.closed = 0
- elif self.closed == 1:
- if PY_MAJOR_VERSION < 3:
- raise SerializerError("serializer is closed")
- else:
- raise SerializerError(u"serializer is closed")
- else:
- if PY_MAJOR_VERSION < 3:
- raise SerializerError("serializer is already opened")
- else:
- raise SerializerError(u"serializer is already opened")
-
- def close(self):
- cdef yaml_event_t event
- if self.closed == -1:
- if PY_MAJOR_VERSION < 3:
- raise SerializerError("serializer is not opened")
- else:
- raise SerializerError(u"serializer is not opened")
- elif self.closed == 0:
- yaml_stream_end_event_initialize(&event)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- self.closed = 1
-
- def serialize(self, node):
- cdef yaml_event_t event
- cdef yaml_version_directive_t version_directive_value
- cdef yaml_version_directive_t *version_directive
- cdef yaml_tag_directive_t tag_directives_value[128]
- cdef yaml_tag_directive_t *tag_directives_start
- cdef yaml_tag_directive_t *tag_directives_end
- if self.closed == -1:
- if PY_MAJOR_VERSION < 3:
- raise SerializerError("serializer is not opened")
- else:
- raise SerializerError(u"serializer is not opened")
- elif self.closed == 1:
- if PY_MAJOR_VERSION < 3:
- raise SerializerError("serializer is closed")
- else:
- raise SerializerError(u"serializer is closed")
- cache = []
- version_directive = NULL
- if self.use_version:
- version_directive_value.major = self.use_version[0]
- version_directive_value.minor = self.use_version[1]
- version_directive = &version_directive_value
- tag_directives_start = NULL
- tag_directives_end = NULL
- if self.use_tags:
- if len(self.use_tags) > 128:
- if PY_MAJOR_VERSION < 3:
- raise ValueError("too many tags")
- else:
- raise ValueError(u"too many tags")
- tag_directives_start = tag_directives_value
- tag_directives_end = tag_directives_value
- for handle in self.use_tags:
- prefix = self.use_tags[handle]
- if PyUnicode_CheckExact(handle):
- handle = PyUnicode_AsUTF8String(handle)
- cache.append(handle)
- if not PyString_CheckExact(handle):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag handle must be a string")
- else:
- raise TypeError(u"tag handle must be a string")
+ implicit, mapping_style) == 0:
+ raise MemoryError
+ elif event_class is SequenceEndEvent:
+ yaml_sequence_end_event_initialize(event)
+ elif event_class is MappingEndEvent:
+ yaml_mapping_end_event_initialize(event)
+ else:
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("invalid event %s" % event_object)
+ else:
+ raise TypeError(u"invalid event %s" % event_object)
+ return 1
+
+ def emit(self, event_object):
+ cdef yaml_event_t event
+ self._object_to_event(event_object, &event)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+
+ def open(self):
+ cdef yaml_event_t event
+ cdef yaml_encoding_t encoding
+ if self.closed == -1:
+ if self.use_encoding == u'utf-16-le' or self.use_encoding == 'utf-16-le':
+ encoding = YAML_UTF16LE_ENCODING
+ elif self.use_encoding == u'utf-16-be' or self.use_encoding == 'utf-16-be':
+ encoding = YAML_UTF16BE_ENCODING
+ else:
+ encoding = YAML_UTF8_ENCODING
+ if self.use_encoding is None:
+ self.dump_unicode = 1
+ if self.dump_unicode == 1:
+ encoding = YAML_UTF8_ENCODING
+ yaml_stream_start_event_initialize(&event, encoding)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ self.closed = 0
+ elif self.closed == 1:
+ if PY_MAJOR_VERSION < 3:
+ raise SerializerError("serializer is closed")
+ else:
+ raise SerializerError(u"serializer is closed")
+ else:
+ if PY_MAJOR_VERSION < 3:
+ raise SerializerError("serializer is already opened")
+ else:
+ raise SerializerError(u"serializer is already opened")
+
+ def close(self):
+ cdef yaml_event_t event
+ if self.closed == -1:
+ if PY_MAJOR_VERSION < 3:
+ raise SerializerError("serializer is not opened")
+ else:
+ raise SerializerError(u"serializer is not opened")
+ elif self.closed == 0:
+ yaml_stream_end_event_initialize(&event)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ self.closed = 1
+
+ def serialize(self, node):
+ cdef yaml_event_t event
+ cdef yaml_version_directive_t version_directive_value
+ cdef yaml_version_directive_t *version_directive
+ cdef yaml_tag_directive_t tag_directives_value[128]
+ cdef yaml_tag_directive_t *tag_directives_start
+ cdef yaml_tag_directive_t *tag_directives_end
+ if self.closed == -1:
+ if PY_MAJOR_VERSION < 3:
+ raise SerializerError("serializer is not opened")
+ else:
+ raise SerializerError(u"serializer is not opened")
+ elif self.closed == 1:
+ if PY_MAJOR_VERSION < 3:
+ raise SerializerError("serializer is closed")
+ else:
+ raise SerializerError(u"serializer is closed")
+ cache = []
+ version_directive = NULL
+ if self.use_version:
+ version_directive_value.major = self.use_version[0]
+ version_directive_value.minor = self.use_version[1]
+ version_directive = &version_directive_value
+ tag_directives_start = NULL
+ tag_directives_end = NULL
+ if self.use_tags:
+ if len(self.use_tags) > 128:
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("too many tags")
+ else:
+ raise ValueError(u"too many tags")
+ tag_directives_start = tag_directives_value
+ tag_directives_end = tag_directives_value
+ for handle in self.use_tags:
+ prefix = self.use_tags[handle]
+ if PyUnicode_CheckExact(handle):
+ handle = PyUnicode_AsUTF8String(handle)
+ cache.append(handle)
+ if not PyString_CheckExact(handle):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag handle must be a string")
+ else:
+ raise TypeError(u"tag handle must be a string")
tag_directives_end.handle = PyString_AS_STRING(handle)
- if PyUnicode_CheckExact(prefix):
- prefix = PyUnicode_AsUTF8String(prefix)
- cache.append(prefix)
- if not PyString_CheckExact(prefix):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag prefix must be a string")
- else:
- raise TypeError(u"tag prefix must be a string")
+ if PyUnicode_CheckExact(prefix):
+ prefix = PyUnicode_AsUTF8String(prefix)
+ cache.append(prefix)
+ if not PyString_CheckExact(prefix):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag prefix must be a string")
+ else:
+ raise TypeError(u"tag prefix must be a string")
tag_directives_end.prefix = PyString_AS_STRING(prefix)
- tag_directives_end = tag_directives_end+1
- if yaml_document_start_event_initialize(&event, version_directive,
- tag_directives_start, tag_directives_end,
- self.document_start_implicit) == 0:
- raise MemoryError
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- self._anchor_node(node)
- self._serialize_node(node, None, None)
- yaml_document_end_event_initialize(&event, self.document_end_implicit)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- self.serialized_nodes = {}
- self.anchors = {}
- self.last_alias_id = 0
-
- cdef int _anchor_node(self, object node) except 0:
- if node in self.anchors:
- if self.anchors[node] is None:
- self.last_alias_id = self.last_alias_id+1
- self.anchors[node] = u"id%03d" % self.last_alias_id
- else:
- self.anchors[node] = None
- node_class = node.__class__
- if node_class is SequenceNode:
- for item in node.value:
- self._anchor_node(item)
- elif node_class is MappingNode:
- for key, value in node.value:
- self._anchor_node(key)
- self._anchor_node(value)
- return 1
-
- cdef int _serialize_node(self, object node, object parent, object index) except 0:
- cdef yaml_event_t event
- cdef int implicit
- cdef int plain_implicit
- cdef int quoted_implicit
- cdef char *anchor
- cdef char *tag
- cdef char *value
- cdef int length
- cdef int item_index
- cdef yaml_scalar_style_t scalar_style
- cdef yaml_sequence_style_t sequence_style
- cdef yaml_mapping_style_t mapping_style
- anchor_object = self.anchors[node]
- anchor = NULL
- if anchor_object is not None:
- if PyUnicode_CheckExact(anchor_object):
- anchor_object = PyUnicode_AsUTF8String(anchor_object)
- if not PyString_CheckExact(anchor_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("anchor must be a string")
- else:
- raise TypeError(u"anchor must be a string")
- anchor = PyString_AS_STRING(anchor_object)
- if node in self.serialized_nodes:
+ tag_directives_end = tag_directives_end+1
+ if yaml_document_start_event_initialize(&event, version_directive,
+ tag_directives_start, tag_directives_end,
+ self.document_start_implicit) == 0:
+ raise MemoryError
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ self._anchor_node(node)
+ self._serialize_node(node, None, None)
+ yaml_document_end_event_initialize(&event, self.document_end_implicit)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ self.serialized_nodes = {}
+ self.anchors = {}
+ self.last_alias_id = 0
+
+ cdef int _anchor_node(self, object node) except 0:
+ if node in self.anchors:
+ if self.anchors[node] is None:
+ self.last_alias_id = self.last_alias_id+1
+ self.anchors[node] = u"id%03d" % self.last_alias_id
+ else:
+ self.anchors[node] = None
+ node_class = node.__class__
+ if node_class is SequenceNode:
+ for item in node.value:
+ self._anchor_node(item)
+ elif node_class is MappingNode:
+ for key, value in node.value:
+ self._anchor_node(key)
+ self._anchor_node(value)
+ return 1
+
+ cdef int _serialize_node(self, object node, object parent, object index) except 0:
+ cdef yaml_event_t event
+ cdef int implicit
+ cdef int plain_implicit
+ cdef int quoted_implicit
+ cdef char *anchor
+ cdef char *tag
+ cdef char *value
+ cdef int length
+ cdef int item_index
+ cdef yaml_scalar_style_t scalar_style
+ cdef yaml_sequence_style_t sequence_style
+ cdef yaml_mapping_style_t mapping_style
+ anchor_object = self.anchors[node]
+ anchor = NULL
+ if anchor_object is not None:
+ if PyUnicode_CheckExact(anchor_object):
+ anchor_object = PyUnicode_AsUTF8String(anchor_object)
+ if not PyString_CheckExact(anchor_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("anchor must be a string")
+ else:
+ raise TypeError(u"anchor must be a string")
+ anchor = PyString_AS_STRING(anchor_object)
+ if node in self.serialized_nodes:
if yaml_alias_event_initialize(&event, anchor) == 0:
- raise MemoryError
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- else:
- node_class = node.__class__
- self.serialized_nodes[node] = True
- self.descend_resolver(parent, index)
- if node_class is ScalarNode:
- plain_implicit = 0
- quoted_implicit = 0
- tag_object = node.tag
- if self.resolve(ScalarNode, node.value, (True, False)) == tag_object:
- plain_implicit = 1
- if self.resolve(ScalarNode, node.value, (False, True)) == tag_object:
- quoted_implicit = 1
- tag = NULL
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- value_object = node.value
- if PyUnicode_CheckExact(value_object):
- value_object = PyUnicode_AsUTF8String(value_object)
- if not PyString_CheckExact(value_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("value must be a string")
- else:
- raise TypeError(u"value must be a string")
- value = PyString_AS_STRING(value_object)
- length = PyString_GET_SIZE(value_object)
- style_object = node.style
- scalar_style = YAML_PLAIN_SCALAR_STYLE
- if style_object == "'" or style_object == u"'":
- scalar_style = YAML_SINGLE_QUOTED_SCALAR_STYLE
- elif style_object == "\"" or style_object == u"\"":
- scalar_style = YAML_DOUBLE_QUOTED_SCALAR_STYLE
- elif style_object == "|" or style_object == u"|":
- scalar_style = YAML_LITERAL_SCALAR_STYLE
- elif style_object == ">" or style_object == u">":
- scalar_style = YAML_FOLDED_SCALAR_STYLE
+ raise MemoryError
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ else:
+ node_class = node.__class__
+ self.serialized_nodes[node] = True
+ self.descend_resolver(parent, index)
+ if node_class is ScalarNode:
+ plain_implicit = 0
+ quoted_implicit = 0
+ tag_object = node.tag
+ if self.resolve(ScalarNode, node.value, (True, False)) == tag_object:
+ plain_implicit = 1
+ if self.resolve(ScalarNode, node.value, (False, True)) == tag_object:
+ quoted_implicit = 1
+ tag = NULL
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ value_object = node.value
+ if PyUnicode_CheckExact(value_object):
+ value_object = PyUnicode_AsUTF8String(value_object)
+ if not PyString_CheckExact(value_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("value must be a string")
+ else:
+ raise TypeError(u"value must be a string")
+ value = PyString_AS_STRING(value_object)
+ length = PyString_GET_SIZE(value_object)
+ style_object = node.style
+ scalar_style = YAML_PLAIN_SCALAR_STYLE
+ if style_object == "'" or style_object == u"'":
+ scalar_style = YAML_SINGLE_QUOTED_SCALAR_STYLE
+ elif style_object == "\"" or style_object == u"\"":
+ scalar_style = YAML_DOUBLE_QUOTED_SCALAR_STYLE
+ elif style_object == "|" or style_object == u"|":
+ scalar_style = YAML_LITERAL_SCALAR_STYLE
+ elif style_object == ">" or style_object == u">":
+ scalar_style = YAML_FOLDED_SCALAR_STYLE
if yaml_scalar_event_initialize(&event, anchor, tag, value, length,
- plain_implicit, quoted_implicit, scalar_style) == 0:
- raise MemoryError
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- elif node_class is SequenceNode:
- implicit = 0
- tag_object = node.tag
- if self.resolve(SequenceNode, node.value, True) == tag_object:
- implicit = 1
- tag = NULL
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- sequence_style = YAML_BLOCK_SEQUENCE_STYLE
- if node.flow_style:
- sequence_style = YAML_FLOW_SEQUENCE_STYLE
+ plain_implicit, quoted_implicit, scalar_style) == 0:
+ raise MemoryError
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ elif node_class is SequenceNode:
+ implicit = 0
+ tag_object = node.tag
+ if self.resolve(SequenceNode, node.value, True) == tag_object:
+ implicit = 1
+ tag = NULL
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ sequence_style = YAML_BLOCK_SEQUENCE_STYLE
+ if node.flow_style:
+ sequence_style = YAML_FLOW_SEQUENCE_STYLE
if yaml_sequence_start_event_initialize(&event, anchor, tag,
- implicit, sequence_style) == 0:
- raise MemoryError
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- item_index = 0
- for item in node.value:
- self._serialize_node(item, node, item_index)
- item_index = item_index+1
- yaml_sequence_end_event_initialize(&event)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- elif node_class is MappingNode:
- implicit = 0
- tag_object = node.tag
- if self.resolve(MappingNode, node.value, True) == tag_object:
- implicit = 1
- tag = NULL
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- mapping_style = YAML_BLOCK_MAPPING_STYLE
- if node.flow_style:
- mapping_style = YAML_FLOW_MAPPING_STYLE
+ implicit, sequence_style) == 0:
+ raise MemoryError
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ item_index = 0
+ for item in node.value:
+ self._serialize_node(item, node, item_index)
+ item_index = item_index+1
+ yaml_sequence_end_event_initialize(&event)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ elif node_class is MappingNode:
+ implicit = 0
+ tag_object = node.tag
+ if self.resolve(MappingNode, node.value, True) == tag_object:
+ implicit = 1
+ tag = NULL
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ mapping_style = YAML_BLOCK_MAPPING_STYLE
+ if node.flow_style:
+ mapping_style = YAML_FLOW_MAPPING_STYLE
if yaml_mapping_start_event_initialize(&event, anchor, tag,
- implicit, mapping_style) == 0:
- raise MemoryError
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- for item_key, item_value in node.value:
- self._serialize_node(item_key, node, None)
- self._serialize_node(item_value, node, item_key)
- yaml_mapping_end_event_initialize(&event)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- self.ascend_resolver()
- return 1
-
+ implicit, mapping_style) == 0:
+ raise MemoryError
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ for item_key, item_value in node.value:
+ self._serialize_node(item_key, node, None)
+ self._serialize_node(item_value, node, item_key)
+ yaml_mapping_end_event_initialize(&event)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ self.ascend_resolver()
+ return 1
+
cdef int output_handler(void *data, char *buffer, size_t size) except 0:
- cdef CEmitter emitter
- emitter = <CEmitter>data
- if emitter.dump_unicode == 0:
+ cdef CEmitter emitter
+ emitter = <CEmitter>data
+ if emitter.dump_unicode == 0:
value = PyString_FromStringAndSize(buffer, size)
- else:
+ else:
value = PyUnicode_DecodeUTF8(buffer, size, 'strict')
- emitter.stream.write(value)
- return 1
-
+ emitter.stream.write(value)
+ return 1
+
diff --git a/contrib/python/PyYAML/py2/yaml/composer.py b/contrib/python/PyYAML/py2/yaml/composer.py
index 8e9c68ae43..df85ef653b 100644
--- a/contrib/python/PyYAML/py2/yaml/composer.py
+++ b/contrib/python/PyYAML/py2/yaml/composer.py
@@ -1,139 +1,139 @@
-
-__all__ = ['Composer', 'ComposerError']
-
-from error import MarkedYAMLError
-from events import *
-from nodes import *
-
-class ComposerError(MarkedYAMLError):
- pass
-
-class Composer(object):
-
- def __init__(self):
- self.anchors = {}
-
- def check_node(self):
- # Drop the STREAM-START event.
- if self.check_event(StreamStartEvent):
- self.get_event()
-
- # If there are more documents available?
- return not self.check_event(StreamEndEvent)
-
- def get_node(self):
- # Get the root node of the next document.
- if not self.check_event(StreamEndEvent):
- return self.compose_document()
-
- def get_single_node(self):
- # Drop the STREAM-START event.
- self.get_event()
-
- # Compose a document if the stream is not empty.
- document = None
- if not self.check_event(StreamEndEvent):
- document = self.compose_document()
-
- # Ensure that the stream contains no more documents.
- if not self.check_event(StreamEndEvent):
- event = self.get_event()
- raise ComposerError("expected a single document in the stream",
- document.start_mark, "but found another document",
- event.start_mark)
-
- # Drop the STREAM-END event.
- self.get_event()
-
- return document
-
- def compose_document(self):
- # Drop the DOCUMENT-START event.
- self.get_event()
-
- # Compose the root node.
- node = self.compose_node(None, None)
-
- # Drop the DOCUMENT-END event.
- self.get_event()
-
- self.anchors = {}
- return node
-
- def compose_node(self, parent, index):
- if self.check_event(AliasEvent):
- event = self.get_event()
- anchor = event.anchor
- if anchor not in self.anchors:
- raise ComposerError(None, None, "found undefined alias %r"
- % anchor.encode('utf-8'), event.start_mark)
- return self.anchors[anchor]
- event = self.peek_event()
- anchor = event.anchor
- if anchor is not None:
- if anchor in self.anchors:
+
+__all__ = ['Composer', 'ComposerError']
+
+from error import MarkedYAMLError
+from events import *
+from nodes import *
+
+class ComposerError(MarkedYAMLError):
+ pass
+
+class Composer(object):
+
+ def __init__(self):
+ self.anchors = {}
+
+ def check_node(self):
+ # Drop the STREAM-START event.
+ if self.check_event(StreamStartEvent):
+ self.get_event()
+
+ # If there are more documents available?
+ return not self.check_event(StreamEndEvent)
+
+ def get_node(self):
+ # Get the root node of the next document.
+ if not self.check_event(StreamEndEvent):
+ return self.compose_document()
+
+ def get_single_node(self):
+ # Drop the STREAM-START event.
+ self.get_event()
+
+ # Compose a document if the stream is not empty.
+ document = None
+ if not self.check_event(StreamEndEvent):
+ document = self.compose_document()
+
+ # Ensure that the stream contains no more documents.
+ if not self.check_event(StreamEndEvent):
+ event = self.get_event()
+ raise ComposerError("expected a single document in the stream",
+ document.start_mark, "but found another document",
+ event.start_mark)
+
+ # Drop the STREAM-END event.
+ self.get_event()
+
+ return document
+
+ def compose_document(self):
+ # Drop the DOCUMENT-START event.
+ self.get_event()
+
+ # Compose the root node.
+ node = self.compose_node(None, None)
+
+ # Drop the DOCUMENT-END event.
+ self.get_event()
+
+ self.anchors = {}
+ return node
+
+ def compose_node(self, parent, index):
+ if self.check_event(AliasEvent):
+ event = self.get_event()
+ anchor = event.anchor
+ if anchor not in self.anchors:
+ raise ComposerError(None, None, "found undefined alias %r"
+ % anchor.encode('utf-8'), event.start_mark)
+ return self.anchors[anchor]
+ event = self.peek_event()
+ anchor = event.anchor
+ if anchor is not None:
+ if anchor in self.anchors:
raise ComposerError("found duplicate anchor %r; first occurrence"
- % anchor.encode('utf-8'), self.anchors[anchor].start_mark,
+ % anchor.encode('utf-8'), self.anchors[anchor].start_mark,
"second occurrence", event.start_mark)
- self.descend_resolver(parent, index)
- if self.check_event(ScalarEvent):
- node = self.compose_scalar_node(anchor)
- elif self.check_event(SequenceStartEvent):
- node = self.compose_sequence_node(anchor)
- elif self.check_event(MappingStartEvent):
- node = self.compose_mapping_node(anchor)
- self.ascend_resolver()
- return node
-
- def compose_scalar_node(self, anchor):
- event = self.get_event()
- tag = event.tag
- if tag is None or tag == u'!':
- tag = self.resolve(ScalarNode, event.value, event.implicit)
- node = ScalarNode(tag, event.value,
- event.start_mark, event.end_mark, style=event.style)
- if anchor is not None:
- self.anchors[anchor] = node
- return node
-
- def compose_sequence_node(self, anchor):
- start_event = self.get_event()
- tag = start_event.tag
- if tag is None or tag == u'!':
- tag = self.resolve(SequenceNode, None, start_event.implicit)
- node = SequenceNode(tag, [],
- start_event.start_mark, None,
- flow_style=start_event.flow_style)
- if anchor is not None:
- self.anchors[anchor] = node
- index = 0
- while not self.check_event(SequenceEndEvent):
- node.value.append(self.compose_node(node, index))
- index += 1
- end_event = self.get_event()
- node.end_mark = end_event.end_mark
- return node
-
- def compose_mapping_node(self, anchor):
- start_event = self.get_event()
- tag = start_event.tag
- if tag is None or tag == u'!':
- tag = self.resolve(MappingNode, None, start_event.implicit)
- node = MappingNode(tag, [],
- start_event.start_mark, None,
- flow_style=start_event.flow_style)
- if anchor is not None:
- self.anchors[anchor] = node
- while not self.check_event(MappingEndEvent):
- #key_event = self.peek_event()
- item_key = self.compose_node(node, None)
- #if item_key in node.value:
- # raise ComposerError("while composing a mapping", start_event.start_mark,
- # "found duplicate key", key_event.start_mark)
- item_value = self.compose_node(node, item_key)
- #node.value[item_key] = item_value
- node.value.append((item_key, item_value))
- end_event = self.get_event()
- node.end_mark = end_event.end_mark
- return node
-
+ self.descend_resolver(parent, index)
+ if self.check_event(ScalarEvent):
+ node = self.compose_scalar_node(anchor)
+ elif self.check_event(SequenceStartEvent):
+ node = self.compose_sequence_node(anchor)
+ elif self.check_event(MappingStartEvent):
+ node = self.compose_mapping_node(anchor)
+ self.ascend_resolver()
+ return node
+
+ def compose_scalar_node(self, anchor):
+ event = self.get_event()
+ tag = event.tag
+ if tag is None or tag == u'!':
+ tag = self.resolve(ScalarNode, event.value, event.implicit)
+ node = ScalarNode(tag, event.value,
+ event.start_mark, event.end_mark, style=event.style)
+ if anchor is not None:
+ self.anchors[anchor] = node
+ return node
+
+ def compose_sequence_node(self, anchor):
+ start_event = self.get_event()
+ tag = start_event.tag
+ if tag is None or tag == u'!':
+ tag = self.resolve(SequenceNode, None, start_event.implicit)
+ node = SequenceNode(tag, [],
+ start_event.start_mark, None,
+ flow_style=start_event.flow_style)
+ if anchor is not None:
+ self.anchors[anchor] = node
+ index = 0
+ while not self.check_event(SequenceEndEvent):
+ node.value.append(self.compose_node(node, index))
+ index += 1
+ end_event = self.get_event()
+ node.end_mark = end_event.end_mark
+ return node
+
+ def compose_mapping_node(self, anchor):
+ start_event = self.get_event()
+ tag = start_event.tag
+ if tag is None or tag == u'!':
+ tag = self.resolve(MappingNode, None, start_event.implicit)
+ node = MappingNode(tag, [],
+ start_event.start_mark, None,
+ flow_style=start_event.flow_style)
+ if anchor is not None:
+ self.anchors[anchor] = node
+ while not self.check_event(MappingEndEvent):
+ #key_event = self.peek_event()
+ item_key = self.compose_node(node, None)
+ #if item_key in node.value:
+ # raise ComposerError("while composing a mapping", start_event.start_mark,
+ # "found duplicate key", key_event.start_mark)
+ item_value = self.compose_node(node, item_key)
+ #node.value[item_key] = item_value
+ node.value.append((item_key, item_value))
+ end_event = self.get_event()
+ node.end_mark = end_event.end_mark
+ return node
+
diff --git a/contrib/python/PyYAML/py2/yaml/constructor.py b/contrib/python/PyYAML/py2/yaml/constructor.py
index f4dd7b0054..ff4e36828e 100644
--- a/contrib/python/PyYAML/py2/yaml/constructor.py
+++ b/contrib/python/PyYAML/py2/yaml/constructor.py
@@ -1,4 +1,4 @@
-
+
__all__ = [
'BaseConstructor',
'SafeConstructor',
@@ -7,17 +7,17 @@ __all__ = [
'Constructor',
'ConstructorError'
]
-
-from error import *
-from nodes import *
-
-import datetime
-
-import binascii, re, sys, types
-
-class ConstructorError(MarkedYAMLError):
- pass
-
+
+from error import *
+from nodes import *
+
+import datetime
+
+import binascii, re, sys, types
+
+class ConstructorError(MarkedYAMLError):
+ pass
+
class timezone(datetime.tzinfo):
def __init__(self, offset):
@@ -47,21 +47,21 @@ class timezone(datetime.tzinfo):
__repr__ = __str__ = tzname
-class BaseConstructor(object):
-
- yaml_constructors = {}
- yaml_multi_constructors = {}
-
- def __init__(self):
- self.constructed_objects = {}
- self.recursive_objects = {}
- self.state_generators = []
- self.deep_construct = False
-
- def check_data(self):
- # If there are more documents available?
- return self.check_node()
-
+class BaseConstructor(object):
+
+ yaml_constructors = {}
+ yaml_multi_constructors = {}
+
+ def __init__(self):
+ self.constructed_objects = {}
+ self.recursive_objects = {}
+ self.state_generators = []
+ self.deep_construct = False
+
+ def check_data(self):
+ # If there are more documents available?
+ return self.check_node()
+
def check_state_key(self, key):
"""Block special attributes/methods from being set in a newly created
object, to prevent user-controlled methods from being called during
@@ -70,475 +70,475 @@ class BaseConstructor(object):
raise ConstructorError(None, None,
"blacklisted key '%s' in instance state found" % (key,), None)
- def get_data(self):
- # Construct and return the next document.
- if self.check_node():
- return self.construct_document(self.get_node())
-
- def get_single_data(self):
- # Ensure that the stream contains a single document and construct it.
- node = self.get_single_node()
- if node is not None:
- return self.construct_document(node)
- return None
-
- def construct_document(self, node):
- data = self.construct_object(node)
- while self.state_generators:
- state_generators = self.state_generators
- self.state_generators = []
- for generator in state_generators:
- for dummy in generator:
- pass
- self.constructed_objects = {}
- self.recursive_objects = {}
- self.deep_construct = False
- return data
-
- def construct_object(self, node, deep=False):
- if node in self.constructed_objects:
- return self.constructed_objects[node]
- if deep:
- old_deep = self.deep_construct
- self.deep_construct = True
- if node in self.recursive_objects:
- raise ConstructorError(None, None,
- "found unconstructable recursive node", node.start_mark)
- self.recursive_objects[node] = None
- constructor = None
- tag_suffix = None
- if node.tag in self.yaml_constructors:
- constructor = self.yaml_constructors[node.tag]
- else:
- for tag_prefix in self.yaml_multi_constructors:
+ def get_data(self):
+ # Construct and return the next document.
+ if self.check_node():
+ return self.construct_document(self.get_node())
+
+ def get_single_data(self):
+ # Ensure that the stream contains a single document and construct it.
+ node = self.get_single_node()
+ if node is not None:
+ return self.construct_document(node)
+ return None
+
+ def construct_document(self, node):
+ data = self.construct_object(node)
+ while self.state_generators:
+ state_generators = self.state_generators
+ self.state_generators = []
+ for generator in state_generators:
+ for dummy in generator:
+ pass
+ self.constructed_objects = {}
+ self.recursive_objects = {}
+ self.deep_construct = False
+ return data
+
+ def construct_object(self, node, deep=False):
+ if node in self.constructed_objects:
+ return self.constructed_objects[node]
+ if deep:
+ old_deep = self.deep_construct
+ self.deep_construct = True
+ if node in self.recursive_objects:
+ raise ConstructorError(None, None,
+ "found unconstructable recursive node", node.start_mark)
+ self.recursive_objects[node] = None
+ constructor = None
+ tag_suffix = None
+ if node.tag in self.yaml_constructors:
+ constructor = self.yaml_constructors[node.tag]
+ else:
+ for tag_prefix in self.yaml_multi_constructors:
if tag_prefix is not None and node.tag.startswith(tag_prefix):
- tag_suffix = node.tag[len(tag_prefix):]
- constructor = self.yaml_multi_constructors[tag_prefix]
- break
- else:
- if None in self.yaml_multi_constructors:
- tag_suffix = node.tag
- constructor = self.yaml_multi_constructors[None]
- elif None in self.yaml_constructors:
- constructor = self.yaml_constructors[None]
- elif isinstance(node, ScalarNode):
- constructor = self.__class__.construct_scalar
- elif isinstance(node, SequenceNode):
- constructor = self.__class__.construct_sequence
- elif isinstance(node, MappingNode):
- constructor = self.__class__.construct_mapping
- if tag_suffix is None:
- data = constructor(self, node)
- else:
- data = constructor(self, tag_suffix, node)
- if isinstance(data, types.GeneratorType):
- generator = data
- data = generator.next()
- if self.deep_construct:
- for dummy in generator:
- pass
- else:
- self.state_generators.append(generator)
- self.constructed_objects[node] = data
- del self.recursive_objects[node]
- if deep:
- self.deep_construct = old_deep
- return data
-
- def construct_scalar(self, node):
- if not isinstance(node, ScalarNode):
- raise ConstructorError(None, None,
- "expected a scalar node, but found %s" % node.id,
- node.start_mark)
- return node.value
-
- def construct_sequence(self, node, deep=False):
- if not isinstance(node, SequenceNode):
- raise ConstructorError(None, None,
- "expected a sequence node, but found %s" % node.id,
- node.start_mark)
- return [self.construct_object(child, deep=deep)
- for child in node.value]
-
- def construct_mapping(self, node, deep=False):
- if not isinstance(node, MappingNode):
- raise ConstructorError(None, None,
- "expected a mapping node, but found %s" % node.id,
- node.start_mark)
- mapping = {}
- for key_node, value_node in node.value:
- key = self.construct_object(key_node, deep=deep)
- try:
- hash(key)
- except TypeError, exc:
- raise ConstructorError("while constructing a mapping", node.start_mark,
- "found unacceptable key (%s)" % exc, key_node.start_mark)
- value = self.construct_object(value_node, deep=deep)
- mapping[key] = value
- return mapping
-
- def construct_pairs(self, node, deep=False):
- if not isinstance(node, MappingNode):
- raise ConstructorError(None, None,
- "expected a mapping node, but found %s" % node.id,
- node.start_mark)
- pairs = []
- for key_node, value_node in node.value:
- key = self.construct_object(key_node, deep=deep)
- value = self.construct_object(value_node, deep=deep)
- pairs.append((key, value))
- return pairs
-
- def add_constructor(cls, tag, constructor):
- if not 'yaml_constructors' in cls.__dict__:
- cls.yaml_constructors = cls.yaml_constructors.copy()
- cls.yaml_constructors[tag] = constructor
- add_constructor = classmethod(add_constructor)
-
- def add_multi_constructor(cls, tag_prefix, multi_constructor):
- if not 'yaml_multi_constructors' in cls.__dict__:
- cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy()
- cls.yaml_multi_constructors[tag_prefix] = multi_constructor
- add_multi_constructor = classmethod(add_multi_constructor)
-
-class SafeConstructor(BaseConstructor):
-
- def construct_scalar(self, node):
- if isinstance(node, MappingNode):
- for key_node, value_node in node.value:
- if key_node.tag == u'tag:yaml.org,2002:value':
- return self.construct_scalar(value_node)
- return BaseConstructor.construct_scalar(self, node)
-
- def flatten_mapping(self, node):
- merge = []
- index = 0
- while index < len(node.value):
- key_node, value_node = node.value[index]
- if key_node.tag == u'tag:yaml.org,2002:merge':
- del node.value[index]
- if isinstance(value_node, MappingNode):
- self.flatten_mapping(value_node)
- merge.extend(value_node.value)
- elif isinstance(value_node, SequenceNode):
- submerge = []
- for subnode in value_node.value:
- if not isinstance(subnode, MappingNode):
- raise ConstructorError("while constructing a mapping",
- node.start_mark,
- "expected a mapping for merging, but found %s"
- % subnode.id, subnode.start_mark)
- self.flatten_mapping(subnode)
- submerge.append(subnode.value)
- submerge.reverse()
- for value in submerge:
- merge.extend(value)
- else:
- raise ConstructorError("while constructing a mapping", node.start_mark,
- "expected a mapping or list of mappings for merging, but found %s"
- % value_node.id, value_node.start_mark)
- elif key_node.tag == u'tag:yaml.org,2002:value':
- key_node.tag = u'tag:yaml.org,2002:str'
- index += 1
- else:
- index += 1
- if merge:
- node.value = merge + node.value
-
- def construct_mapping(self, node, deep=False):
- if isinstance(node, MappingNode):
- self.flatten_mapping(node)
- return BaseConstructor.construct_mapping(self, node, deep=deep)
-
- def construct_yaml_null(self, node):
- self.construct_scalar(node)
- return None
-
- bool_values = {
- u'yes': True,
- u'no': False,
- u'true': True,
- u'false': False,
- u'on': True,
- u'off': False,
- }
-
- def construct_yaml_bool(self, node):
- value = self.construct_scalar(node)
- return self.bool_values[value.lower()]
-
- def construct_yaml_int(self, node):
- value = str(self.construct_scalar(node))
- value = value.replace('_', '')
- sign = +1
- if value[0] == '-':
- sign = -1
- if value[0] in '+-':
- value = value[1:]
- if value == '0':
- return 0
- elif value.startswith('0b'):
- return sign*int(value[2:], 2)
- elif value.startswith('0x'):
- return sign*int(value[2:], 16)
- elif value[0] == '0':
- return sign*int(value, 8)
- elif ':' in value:
- digits = [int(part) for part in value.split(':')]
- digits.reverse()
- base = 1
- value = 0
- for digit in digits:
- value += digit*base
- base *= 60
- return sign*value
- else:
- return sign*int(value)
-
- inf_value = 1e300
- while inf_value != inf_value*inf_value:
- inf_value *= inf_value
- nan_value = -inf_value/inf_value # Trying to make a quiet NaN (like C99).
-
- def construct_yaml_float(self, node):
- value = str(self.construct_scalar(node))
- value = value.replace('_', '').lower()
- sign = +1
- if value[0] == '-':
- sign = -1
- if value[0] in '+-':
- value = value[1:]
- if value == '.inf':
- return sign*self.inf_value
- elif value == '.nan':
- return self.nan_value
- elif ':' in value:
- digits = [float(part) for part in value.split(':')]
- digits.reverse()
- base = 1
- value = 0.0
- for digit in digits:
- value += digit*base
- base *= 60
- return sign*value
- else:
- return sign*float(value)
-
- def construct_yaml_binary(self, node):
- value = self.construct_scalar(node)
- try:
- return str(value).decode('base64')
- except (binascii.Error, UnicodeEncodeError), exc:
- raise ConstructorError(None, None,
+ tag_suffix = node.tag[len(tag_prefix):]
+ constructor = self.yaml_multi_constructors[tag_prefix]
+ break
+ else:
+ if None in self.yaml_multi_constructors:
+ tag_suffix = node.tag
+ constructor = self.yaml_multi_constructors[None]
+ elif None in self.yaml_constructors:
+ constructor = self.yaml_constructors[None]
+ elif isinstance(node, ScalarNode):
+ constructor = self.__class__.construct_scalar
+ elif isinstance(node, SequenceNode):
+ constructor = self.__class__.construct_sequence
+ elif isinstance(node, MappingNode):
+ constructor = self.__class__.construct_mapping
+ if tag_suffix is None:
+ data = constructor(self, node)
+ else:
+ data = constructor(self, tag_suffix, node)
+ if isinstance(data, types.GeneratorType):
+ generator = data
+ data = generator.next()
+ if self.deep_construct:
+ for dummy in generator:
+ pass
+ else:
+ self.state_generators.append(generator)
+ self.constructed_objects[node] = data
+ del self.recursive_objects[node]
+ if deep:
+ self.deep_construct = old_deep
+ return data
+
+ def construct_scalar(self, node):
+ if not isinstance(node, ScalarNode):
+ raise ConstructorError(None, None,
+ "expected a scalar node, but found %s" % node.id,
+ node.start_mark)
+ return node.value
+
+ def construct_sequence(self, node, deep=False):
+ if not isinstance(node, SequenceNode):
+ raise ConstructorError(None, None,
+ "expected a sequence node, but found %s" % node.id,
+ node.start_mark)
+ return [self.construct_object(child, deep=deep)
+ for child in node.value]
+
+ def construct_mapping(self, node, deep=False):
+ if not isinstance(node, MappingNode):
+ raise ConstructorError(None, None,
+ "expected a mapping node, but found %s" % node.id,
+ node.start_mark)
+ mapping = {}
+ for key_node, value_node in node.value:
+ key = self.construct_object(key_node, deep=deep)
+ try:
+ hash(key)
+ except TypeError, exc:
+ raise ConstructorError("while constructing a mapping", node.start_mark,
+ "found unacceptable key (%s)" % exc, key_node.start_mark)
+ value = self.construct_object(value_node, deep=deep)
+ mapping[key] = value
+ return mapping
+
+ def construct_pairs(self, node, deep=False):
+ if not isinstance(node, MappingNode):
+ raise ConstructorError(None, None,
+ "expected a mapping node, but found %s" % node.id,
+ node.start_mark)
+ pairs = []
+ for key_node, value_node in node.value:
+ key = self.construct_object(key_node, deep=deep)
+ value = self.construct_object(value_node, deep=deep)
+ pairs.append((key, value))
+ return pairs
+
+ def add_constructor(cls, tag, constructor):
+ if not 'yaml_constructors' in cls.__dict__:
+ cls.yaml_constructors = cls.yaml_constructors.copy()
+ cls.yaml_constructors[tag] = constructor
+ add_constructor = classmethod(add_constructor)
+
+ def add_multi_constructor(cls, tag_prefix, multi_constructor):
+ if not 'yaml_multi_constructors' in cls.__dict__:
+ cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy()
+ cls.yaml_multi_constructors[tag_prefix] = multi_constructor
+ add_multi_constructor = classmethod(add_multi_constructor)
+
+class SafeConstructor(BaseConstructor):
+
+ def construct_scalar(self, node):
+ if isinstance(node, MappingNode):
+ for key_node, value_node in node.value:
+ if key_node.tag == u'tag:yaml.org,2002:value':
+ return self.construct_scalar(value_node)
+ return BaseConstructor.construct_scalar(self, node)
+
+ def flatten_mapping(self, node):
+ merge = []
+ index = 0
+ while index < len(node.value):
+ key_node, value_node = node.value[index]
+ if key_node.tag == u'tag:yaml.org,2002:merge':
+ del node.value[index]
+ if isinstance(value_node, MappingNode):
+ self.flatten_mapping(value_node)
+ merge.extend(value_node.value)
+ elif isinstance(value_node, SequenceNode):
+ submerge = []
+ for subnode in value_node.value:
+ if not isinstance(subnode, MappingNode):
+ raise ConstructorError("while constructing a mapping",
+ node.start_mark,
+ "expected a mapping for merging, but found %s"
+ % subnode.id, subnode.start_mark)
+ self.flatten_mapping(subnode)
+ submerge.append(subnode.value)
+ submerge.reverse()
+ for value in submerge:
+ merge.extend(value)
+ else:
+ raise ConstructorError("while constructing a mapping", node.start_mark,
+ "expected a mapping or list of mappings for merging, but found %s"
+ % value_node.id, value_node.start_mark)
+ elif key_node.tag == u'tag:yaml.org,2002:value':
+ key_node.tag = u'tag:yaml.org,2002:str'
+ index += 1
+ else:
+ index += 1
+ if merge:
+ node.value = merge + node.value
+
+ def construct_mapping(self, node, deep=False):
+ if isinstance(node, MappingNode):
+ self.flatten_mapping(node)
+ return BaseConstructor.construct_mapping(self, node, deep=deep)
+
+ def construct_yaml_null(self, node):
+ self.construct_scalar(node)
+ return None
+
+ bool_values = {
+ u'yes': True,
+ u'no': False,
+ u'true': True,
+ u'false': False,
+ u'on': True,
+ u'off': False,
+ }
+
+ def construct_yaml_bool(self, node):
+ value = self.construct_scalar(node)
+ return self.bool_values[value.lower()]
+
+ def construct_yaml_int(self, node):
+ value = str(self.construct_scalar(node))
+ value = value.replace('_', '')
+ sign = +1
+ if value[0] == '-':
+ sign = -1
+ if value[0] in '+-':
+ value = value[1:]
+ if value == '0':
+ return 0
+ elif value.startswith('0b'):
+ return sign*int(value[2:], 2)
+ elif value.startswith('0x'):
+ return sign*int(value[2:], 16)
+ elif value[0] == '0':
+ return sign*int(value, 8)
+ elif ':' in value:
+ digits = [int(part) for part in value.split(':')]
+ digits.reverse()
+ base = 1
+ value = 0
+ for digit in digits:
+ value += digit*base
+ base *= 60
+ return sign*value
+ else:
+ return sign*int(value)
+
+ inf_value = 1e300
+ while inf_value != inf_value*inf_value:
+ inf_value *= inf_value
+ nan_value = -inf_value/inf_value # Trying to make a quiet NaN (like C99).
+
+ def construct_yaml_float(self, node):
+ value = str(self.construct_scalar(node))
+ value = value.replace('_', '').lower()
+ sign = +1
+ if value[0] == '-':
+ sign = -1
+ if value[0] in '+-':
+ value = value[1:]
+ if value == '.inf':
+ return sign*self.inf_value
+ elif value == '.nan':
+ return self.nan_value
+ elif ':' in value:
+ digits = [float(part) for part in value.split(':')]
+ digits.reverse()
+ base = 1
+ value = 0.0
+ for digit in digits:
+ value += digit*base
+ base *= 60
+ return sign*value
+ else:
+ return sign*float(value)
+
+ def construct_yaml_binary(self, node):
+ value = self.construct_scalar(node)
+ try:
+ return str(value).decode('base64')
+ except (binascii.Error, UnicodeEncodeError), exc:
+ raise ConstructorError(None, None,
"failed to decode base64 data: %s" % exc, node.start_mark)
-
- timestamp_regexp = re.compile(
- ur'''^(?P<year>[0-9][0-9][0-9][0-9])
- -(?P<month>[0-9][0-9]?)
- -(?P<day>[0-9][0-9]?)
- (?:(?:[Tt]|[ \t]+)
- (?P<hour>[0-9][0-9]?)
- :(?P<minute>[0-9][0-9])
- :(?P<second>[0-9][0-9])
- (?:\.(?P<fraction>[0-9]*))?
- (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
- (?::(?P<tz_minute>[0-9][0-9]))?))?)?$''', re.X)
-
- def construct_yaml_timestamp(self, node):
- value = self.construct_scalar(node)
- match = self.timestamp_regexp.match(node.value)
- values = match.groupdict()
- year = int(values['year'])
- month = int(values['month'])
- day = int(values['day'])
- if not values['hour']:
- return datetime.date(year, month, day)
- hour = int(values['hour'])
- minute = int(values['minute'])
- second = int(values['second'])
- fraction = 0
+
+ timestamp_regexp = re.compile(
+ ur'''^(?P<year>[0-9][0-9][0-9][0-9])
+ -(?P<month>[0-9][0-9]?)
+ -(?P<day>[0-9][0-9]?)
+ (?:(?:[Tt]|[ \t]+)
+ (?P<hour>[0-9][0-9]?)
+ :(?P<minute>[0-9][0-9])
+ :(?P<second>[0-9][0-9])
+ (?:\.(?P<fraction>[0-9]*))?
+ (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
+ (?::(?P<tz_minute>[0-9][0-9]))?))?)?$''', re.X)
+
+ def construct_yaml_timestamp(self, node):
+ value = self.construct_scalar(node)
+ match = self.timestamp_regexp.match(node.value)
+ values = match.groupdict()
+ year = int(values['year'])
+ month = int(values['month'])
+ day = int(values['day'])
+ if not values['hour']:
+ return datetime.date(year, month, day)
+ hour = int(values['hour'])
+ minute = int(values['minute'])
+ second = int(values['second'])
+ fraction = 0
tzinfo = None
- if values['fraction']:
- fraction = values['fraction'][:6]
- while len(fraction) < 6:
- fraction += '0'
- fraction = int(fraction)
- if values['tz_sign']:
- tz_hour = int(values['tz_hour'])
- tz_minute = int(values['tz_minute'] or 0)
- delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute)
- if values['tz_sign'] == '-':
- delta = -delta
+ if values['fraction']:
+ fraction = values['fraction'][:6]
+ while len(fraction) < 6:
+ fraction += '0'
+ fraction = int(fraction)
+ if values['tz_sign']:
+ tz_hour = int(values['tz_hour'])
+ tz_minute = int(values['tz_minute'] or 0)
+ delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute)
+ if values['tz_sign'] == '-':
+ delta = -delta
tzinfo = timezone(delta)
elif values['tz']:
tzinfo = timezone(datetime.timedelta(0))
return datetime.datetime(year, month, day, hour, minute, second, fraction,
tzinfo=tzinfo)
-
- def construct_yaml_omap(self, node):
- # Note: we do not check for duplicate keys, because it's too
- # CPU-expensive.
- omap = []
- yield omap
- if not isinstance(node, SequenceNode):
- raise ConstructorError("while constructing an ordered map", node.start_mark,
- "expected a sequence, but found %s" % node.id, node.start_mark)
- for subnode in node.value:
- if not isinstance(subnode, MappingNode):
- raise ConstructorError("while constructing an ordered map", node.start_mark,
- "expected a mapping of length 1, but found %s" % subnode.id,
- subnode.start_mark)
- if len(subnode.value) != 1:
- raise ConstructorError("while constructing an ordered map", node.start_mark,
- "expected a single mapping item, but found %d items" % len(subnode.value),
- subnode.start_mark)
- key_node, value_node = subnode.value[0]
- key = self.construct_object(key_node)
- value = self.construct_object(value_node)
- omap.append((key, value))
-
- def construct_yaml_pairs(self, node):
- # Note: the same code as `construct_yaml_omap`.
- pairs = []
- yield pairs
- if not isinstance(node, SequenceNode):
- raise ConstructorError("while constructing pairs", node.start_mark,
- "expected a sequence, but found %s" % node.id, node.start_mark)
- for subnode in node.value:
- if not isinstance(subnode, MappingNode):
- raise ConstructorError("while constructing pairs", node.start_mark,
- "expected a mapping of length 1, but found %s" % subnode.id,
- subnode.start_mark)
- if len(subnode.value) != 1:
- raise ConstructorError("while constructing pairs", node.start_mark,
- "expected a single mapping item, but found %d items" % len(subnode.value),
- subnode.start_mark)
- key_node, value_node = subnode.value[0]
- key = self.construct_object(key_node)
- value = self.construct_object(value_node)
- pairs.append((key, value))
-
- def construct_yaml_set(self, node):
- data = set()
- yield data
- value = self.construct_mapping(node)
- data.update(value)
-
- def construct_yaml_str(self, node):
- value = self.construct_scalar(node)
- try:
- return value.encode('ascii')
- except UnicodeEncodeError:
- return value
-
- def construct_yaml_seq(self, node):
- data = []
- yield data
- data.extend(self.construct_sequence(node))
-
- def construct_yaml_map(self, node):
- data = {}
- yield data
- value = self.construct_mapping(node)
- data.update(value)
-
- def construct_yaml_object(self, node, cls):
- data = cls.__new__(cls)
- yield data
- if hasattr(data, '__setstate__'):
- state = self.construct_mapping(node, deep=True)
- data.__setstate__(state)
- else:
- state = self.construct_mapping(node)
- data.__dict__.update(state)
-
- def construct_undefined(self, node):
- raise ConstructorError(None, None,
- "could not determine a constructor for the tag %r" % node.tag.encode('utf-8'),
- node.start_mark)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:null',
- SafeConstructor.construct_yaml_null)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:bool',
- SafeConstructor.construct_yaml_bool)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:int',
- SafeConstructor.construct_yaml_int)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:float',
- SafeConstructor.construct_yaml_float)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:binary',
- SafeConstructor.construct_yaml_binary)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:timestamp',
- SafeConstructor.construct_yaml_timestamp)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:omap',
- SafeConstructor.construct_yaml_omap)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:pairs',
- SafeConstructor.construct_yaml_pairs)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:set',
- SafeConstructor.construct_yaml_set)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:str',
- SafeConstructor.construct_yaml_str)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:seq',
- SafeConstructor.construct_yaml_seq)
-
-SafeConstructor.add_constructor(
- u'tag:yaml.org,2002:map',
- SafeConstructor.construct_yaml_map)
-
-SafeConstructor.add_constructor(None,
- SafeConstructor.construct_undefined)
-
+
+ def construct_yaml_omap(self, node):
+ # Note: we do not check for duplicate keys, because it's too
+ # CPU-expensive.
+ omap = []
+ yield omap
+ if not isinstance(node, SequenceNode):
+ raise ConstructorError("while constructing an ordered map", node.start_mark,
+ "expected a sequence, but found %s" % node.id, node.start_mark)
+ for subnode in node.value:
+ if not isinstance(subnode, MappingNode):
+ raise ConstructorError("while constructing an ordered map", node.start_mark,
+ "expected a mapping of length 1, but found %s" % subnode.id,
+ subnode.start_mark)
+ if len(subnode.value) != 1:
+ raise ConstructorError("while constructing an ordered map", node.start_mark,
+ "expected a single mapping item, but found %d items" % len(subnode.value),
+ subnode.start_mark)
+ key_node, value_node = subnode.value[0]
+ key = self.construct_object(key_node)
+ value = self.construct_object(value_node)
+ omap.append((key, value))
+
+ def construct_yaml_pairs(self, node):
+ # Note: the same code as `construct_yaml_omap`.
+ pairs = []
+ yield pairs
+ if not isinstance(node, SequenceNode):
+ raise ConstructorError("while constructing pairs", node.start_mark,
+ "expected a sequence, but found %s" % node.id, node.start_mark)
+ for subnode in node.value:
+ if not isinstance(subnode, MappingNode):
+ raise ConstructorError("while constructing pairs", node.start_mark,
+ "expected a mapping of length 1, but found %s" % subnode.id,
+ subnode.start_mark)
+ if len(subnode.value) != 1:
+ raise ConstructorError("while constructing pairs", node.start_mark,
+ "expected a single mapping item, but found %d items" % len(subnode.value),
+ subnode.start_mark)
+ key_node, value_node = subnode.value[0]
+ key = self.construct_object(key_node)
+ value = self.construct_object(value_node)
+ pairs.append((key, value))
+
+ def construct_yaml_set(self, node):
+ data = set()
+ yield data
+ value = self.construct_mapping(node)
+ data.update(value)
+
+ def construct_yaml_str(self, node):
+ value = self.construct_scalar(node)
+ try:
+ return value.encode('ascii')
+ except UnicodeEncodeError:
+ return value
+
+ def construct_yaml_seq(self, node):
+ data = []
+ yield data
+ data.extend(self.construct_sequence(node))
+
+ def construct_yaml_map(self, node):
+ data = {}
+ yield data
+ value = self.construct_mapping(node)
+ data.update(value)
+
+ def construct_yaml_object(self, node, cls):
+ data = cls.__new__(cls)
+ yield data
+ if hasattr(data, '__setstate__'):
+ state = self.construct_mapping(node, deep=True)
+ data.__setstate__(state)
+ else:
+ state = self.construct_mapping(node)
+ data.__dict__.update(state)
+
+ def construct_undefined(self, node):
+ raise ConstructorError(None, None,
+ "could not determine a constructor for the tag %r" % node.tag.encode('utf-8'),
+ node.start_mark)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:null',
+ SafeConstructor.construct_yaml_null)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:bool',
+ SafeConstructor.construct_yaml_bool)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:int',
+ SafeConstructor.construct_yaml_int)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:float',
+ SafeConstructor.construct_yaml_float)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:binary',
+ SafeConstructor.construct_yaml_binary)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:timestamp',
+ SafeConstructor.construct_yaml_timestamp)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:omap',
+ SafeConstructor.construct_yaml_omap)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:pairs',
+ SafeConstructor.construct_yaml_pairs)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:set',
+ SafeConstructor.construct_yaml_set)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:str',
+ SafeConstructor.construct_yaml_str)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:seq',
+ SafeConstructor.construct_yaml_seq)
+
+SafeConstructor.add_constructor(
+ u'tag:yaml.org,2002:map',
+ SafeConstructor.construct_yaml_map)
+
+SafeConstructor.add_constructor(None,
+ SafeConstructor.construct_undefined)
+
class FullConstructor(SafeConstructor):
# 'extend' is blacklisted because it is used by
# construct_python_object_apply to add `listitems` to a newly generate
# python instance
def get_state_keys_blacklist(self):
return ['^extend$', '^__.*__$']
-
+
def get_state_keys_blacklist_regexp(self):
if not hasattr(self, 'state_keys_blacklist_regexp'):
self.state_keys_blacklist_regexp = re.compile('(' + '|'.join(self.get_state_keys_blacklist()) + ')')
return self.state_keys_blacklist_regexp
- def construct_python_str(self, node):
- return self.construct_scalar(node).encode('utf-8')
-
- def construct_python_unicode(self, node):
- return self.construct_scalar(node)
-
- def construct_python_long(self, node):
- return long(self.construct_yaml_int(node))
-
- def construct_python_complex(self, node):
- return complex(self.construct_scalar(node))
-
- def construct_python_tuple(self, node):
- return tuple(self.construct_sequence(node))
-
+ def construct_python_str(self, node):
+ return self.construct_scalar(node).encode('utf-8')
+
+ def construct_python_unicode(self, node):
+ return self.construct_scalar(node)
+
+ def construct_python_long(self, node):
+ return long(self.construct_yaml_int(node))
+
+ def construct_python_complex(self, node):
+ return complex(self.construct_scalar(node))
+
+ def construct_python_tuple(self, node):
+ return tuple(self.construct_sequence(node))
+
def find_python_module(self, name, mark, unsafe=False):
- if not name:
- raise ConstructorError("while constructing a Python module", mark,
- "expected non-empty name appended to the tag", mark)
+ if not name:
+ raise ConstructorError("while constructing a Python module", mark,
+ "expected non-empty name appended to the tag", mark)
if unsafe:
try:
__import__(name)
@@ -546,19 +546,19 @@ class FullConstructor(SafeConstructor):
raise ConstructorError("while constructing a Python module", mark,
"cannot find module %r (%s)" % (name.encode('utf-8'), exc), mark)
if name not in sys.modules:
- raise ConstructorError("while constructing a Python module", mark,
+ raise ConstructorError("while constructing a Python module", mark,
"module %r is not imported" % name.encode('utf-8'), mark)
- return sys.modules[name]
-
+ return sys.modules[name]
+
def find_python_name(self, name, mark, unsafe=False):
- if not name:
- raise ConstructorError("while constructing a Python object", mark,
- "expected non-empty name appended to the tag", mark)
- if u'.' in name:
- module_name, object_name = name.rsplit('.', 1)
- else:
- module_name = '__builtin__'
- object_name = name
+ if not name:
+ raise ConstructorError("while constructing a Python object", mark,
+ "expected non-empty name appended to the tag", mark)
+ if u'.' in name:
+ module_name, object_name = name.rsplit('.', 1)
+ else:
+ module_name = '__builtin__'
+ object_name = name
if unsafe:
try:
__import__(module_name)
@@ -566,168 +566,168 @@ class FullConstructor(SafeConstructor):
raise ConstructorError("while constructing a Python object", mark,
"cannot find module %r (%s)" % (module_name.encode('utf-8'), exc), mark)
if module_name not in sys.modules:
- raise ConstructorError("while constructing a Python object", mark,
+ raise ConstructorError("while constructing a Python object", mark,
"module %r is not imported" % module_name.encode('utf-8'), mark)
- module = sys.modules[module_name]
- if not hasattr(module, object_name):
- raise ConstructorError("while constructing a Python object", mark,
- "cannot find %r in the module %r" % (object_name.encode('utf-8'),
- module.__name__), mark)
- return getattr(module, object_name)
-
- def construct_python_name(self, suffix, node):
- value = self.construct_scalar(node)
- if value:
- raise ConstructorError("while constructing a Python name", node.start_mark,
- "expected the empty value, but found %r" % value.encode('utf-8'),
- node.start_mark)
- return self.find_python_name(suffix, node.start_mark)
-
- def construct_python_module(self, suffix, node):
- value = self.construct_scalar(node)
- if value:
- raise ConstructorError("while constructing a Python module", node.start_mark,
- "expected the empty value, but found %r" % value.encode('utf-8'),
- node.start_mark)
- return self.find_python_module(suffix, node.start_mark)
-
- class classobj: pass
-
- def make_python_instance(self, suffix, node,
+ module = sys.modules[module_name]
+ if not hasattr(module, object_name):
+ raise ConstructorError("while constructing a Python object", mark,
+ "cannot find %r in the module %r" % (object_name.encode('utf-8'),
+ module.__name__), mark)
+ return getattr(module, object_name)
+
+ def construct_python_name(self, suffix, node):
+ value = self.construct_scalar(node)
+ if value:
+ raise ConstructorError("while constructing a Python name", node.start_mark,
+ "expected the empty value, but found %r" % value.encode('utf-8'),
+ node.start_mark)
+ return self.find_python_name(suffix, node.start_mark)
+
+ def construct_python_module(self, suffix, node):
+ value = self.construct_scalar(node)
+ if value:
+ raise ConstructorError("while constructing a Python module", node.start_mark,
+ "expected the empty value, but found %r" % value.encode('utf-8'),
+ node.start_mark)
+ return self.find_python_module(suffix, node.start_mark)
+
+ class classobj: pass
+
+ def make_python_instance(self, suffix, node,
args=None, kwds=None, newobj=False, unsafe=False):
- if not args:
- args = []
- if not kwds:
- kwds = {}
- cls = self.find_python_name(suffix, node.start_mark)
+ if not args:
+ args = []
+ if not kwds:
+ kwds = {}
+ cls = self.find_python_name(suffix, node.start_mark)
if not (unsafe or isinstance(cls, type) or isinstance(cls, type(self.classobj))):
raise ConstructorError("while constructing a Python instance", node.start_mark,
"expected a class, but found %r" % type(cls),
node.start_mark)
- if newobj and isinstance(cls, type(self.classobj)) \
- and not args and not kwds:
- instance = self.classobj()
- instance.__class__ = cls
- return instance
- elif newobj and isinstance(cls, type):
- return cls.__new__(cls, *args, **kwds)
- else:
- return cls(*args, **kwds)
-
+ if newobj and isinstance(cls, type(self.classobj)) \
+ and not args and not kwds:
+ instance = self.classobj()
+ instance.__class__ = cls
+ return instance
+ elif newobj and isinstance(cls, type):
+ return cls.__new__(cls, *args, **kwds)
+ else:
+ return cls(*args, **kwds)
+
def set_python_instance_state(self, instance, state, unsafe=False):
- if hasattr(instance, '__setstate__'):
- instance.__setstate__(state)
- else:
- slotstate = {}
- if isinstance(state, tuple) and len(state) == 2:
- state, slotstate = state
- if hasattr(instance, '__dict__'):
+ if hasattr(instance, '__setstate__'):
+ instance.__setstate__(state)
+ else:
+ slotstate = {}
+ if isinstance(state, tuple) and len(state) == 2:
+ state, slotstate = state
+ if hasattr(instance, '__dict__'):
if not unsafe and state:
for key in state.keys():
self.check_state_key(key)
- instance.__dict__.update(state)
- elif state:
- slotstate.update(state)
- for key, value in slotstate.items():
+ instance.__dict__.update(state)
+ elif state:
+ slotstate.update(state)
+ for key, value in slotstate.items():
if not unsafe:
self.check_state_key(key)
setattr(instance, key, value)
-
- def construct_python_object(self, suffix, node):
- # Format:
- # !!python/object:module.name { ... state ... }
- instance = self.make_python_instance(suffix, node, newobj=True)
- yield instance
- deep = hasattr(instance, '__setstate__')
- state = self.construct_mapping(node, deep=deep)
- self.set_python_instance_state(instance, state)
-
- def construct_python_object_apply(self, suffix, node, newobj=False):
- # Format:
- # !!python/object/apply # (or !!python/object/new)
- # args: [ ... arguments ... ]
- # kwds: { ... keywords ... }
- # state: ... state ...
- # listitems: [ ... listitems ... ]
- # dictitems: { ... dictitems ... }
- # or short format:
- # !!python/object/apply [ ... arguments ... ]
- # The difference between !!python/object/apply and !!python/object/new
- # is how an object is created, check make_python_instance for details.
- if isinstance(node, SequenceNode):
- args = self.construct_sequence(node, deep=True)
- kwds = {}
- state = {}
- listitems = []
- dictitems = {}
- else:
- value = self.construct_mapping(node, deep=True)
- args = value.get('args', [])
- kwds = value.get('kwds', {})
- state = value.get('state', {})
- listitems = value.get('listitems', [])
- dictitems = value.get('dictitems', {})
- instance = self.make_python_instance(suffix, node, args, kwds, newobj)
- if state:
- self.set_python_instance_state(instance, state)
- if listitems:
- instance.extend(listitems)
- if dictitems:
- for key in dictitems:
- instance[key] = dictitems[key]
- return instance
-
- def construct_python_object_new(self, suffix, node):
- return self.construct_python_object_apply(suffix, node, newobj=True)
-
+
+ def construct_python_object(self, suffix, node):
+ # Format:
+ # !!python/object:module.name { ... state ... }
+ instance = self.make_python_instance(suffix, node, newobj=True)
+ yield instance
+ deep = hasattr(instance, '__setstate__')
+ state = self.construct_mapping(node, deep=deep)
+ self.set_python_instance_state(instance, state)
+
+ def construct_python_object_apply(self, suffix, node, newobj=False):
+ # Format:
+ # !!python/object/apply # (or !!python/object/new)
+ # args: [ ... arguments ... ]
+ # kwds: { ... keywords ... }
+ # state: ... state ...
+ # listitems: [ ... listitems ... ]
+ # dictitems: { ... dictitems ... }
+ # or short format:
+ # !!python/object/apply [ ... arguments ... ]
+ # The difference between !!python/object/apply and !!python/object/new
+ # is how an object is created, check make_python_instance for details.
+ if isinstance(node, SequenceNode):
+ args = self.construct_sequence(node, deep=True)
+ kwds = {}
+ state = {}
+ listitems = []
+ dictitems = {}
+ else:
+ value = self.construct_mapping(node, deep=True)
+ args = value.get('args', [])
+ kwds = value.get('kwds', {})
+ state = value.get('state', {})
+ listitems = value.get('listitems', [])
+ dictitems = value.get('dictitems', {})
+ instance = self.make_python_instance(suffix, node, args, kwds, newobj)
+ if state:
+ self.set_python_instance_state(instance, state)
+ if listitems:
+ instance.extend(listitems)
+ if dictitems:
+ for key in dictitems:
+ instance[key] = dictitems[key]
+ return instance
+
+ def construct_python_object_new(self, suffix, node):
+ return self.construct_python_object_apply(suffix, node, newobj=True)
+
FullConstructor.add_constructor(
- u'tag:yaml.org,2002:python/none',
+ u'tag:yaml.org,2002:python/none',
FullConstructor.construct_yaml_null)
-
+
FullConstructor.add_constructor(
- u'tag:yaml.org,2002:python/bool',
+ u'tag:yaml.org,2002:python/bool',
FullConstructor.construct_yaml_bool)
-
+
FullConstructor.add_constructor(
- u'tag:yaml.org,2002:python/str',
+ u'tag:yaml.org,2002:python/str',
FullConstructor.construct_python_str)
-
+
FullConstructor.add_constructor(
- u'tag:yaml.org,2002:python/unicode',
+ u'tag:yaml.org,2002:python/unicode',
FullConstructor.construct_python_unicode)
-
+
FullConstructor.add_constructor(
- u'tag:yaml.org,2002:python/int',
+ u'tag:yaml.org,2002:python/int',
FullConstructor.construct_yaml_int)
-
+
FullConstructor.add_constructor(
- u'tag:yaml.org,2002:python/long',
+ u'tag:yaml.org,2002:python/long',
FullConstructor.construct_python_long)
-
+
FullConstructor.add_constructor(
- u'tag:yaml.org,2002:python/float',
+ u'tag:yaml.org,2002:python/float',
FullConstructor.construct_yaml_float)
-
+
FullConstructor.add_constructor(
- u'tag:yaml.org,2002:python/complex',
+ u'tag:yaml.org,2002:python/complex',
FullConstructor.construct_python_complex)
-
+
FullConstructor.add_constructor(
- u'tag:yaml.org,2002:python/list',
+ u'tag:yaml.org,2002:python/list',
FullConstructor.construct_yaml_seq)
-
+
FullConstructor.add_constructor(
- u'tag:yaml.org,2002:python/tuple',
+ u'tag:yaml.org,2002:python/tuple',
FullConstructor.construct_python_tuple)
-
+
FullConstructor.add_constructor(
- u'tag:yaml.org,2002:python/dict',
+ u'tag:yaml.org,2002:python/dict',
FullConstructor.construct_yaml_map)
-
+
FullConstructor.add_multi_constructor(
- u'tag:yaml.org,2002:python/name:',
+ u'tag:yaml.org,2002:python/name:',
FullConstructor.construct_python_name)
-
+
class UnsafeConstructor(FullConstructor):
def find_python_module(self, name, mark):
diff --git a/contrib/python/PyYAML/py2/yaml/cyaml.py b/contrib/python/PyYAML/py2/yaml/cyaml.py
index 3abdfb054f..768b49d6b9 100644
--- a/contrib/python/PyYAML/py2/yaml/cyaml.py
+++ b/contrib/python/PyYAML/py2/yaml/cyaml.py
@@ -1,32 +1,32 @@
-
+
__all__ = [
'CBaseLoader', 'CSafeLoader', 'CFullLoader', 'CUnsafeLoader', 'CLoader',
'CBaseDumper', 'CSafeDumper', 'CDumper'
]
-
+
from yaml._yaml import CParser, CEmitter
-
-from constructor import *
-
-from serializer import *
-from representer import *
-
-from resolver import *
-
-class CBaseLoader(CParser, BaseConstructor, BaseResolver):
-
- def __init__(self, stream):
- CParser.__init__(self, stream)
- BaseConstructor.__init__(self)
- BaseResolver.__init__(self)
-
-class CSafeLoader(CParser, SafeConstructor, Resolver):
-
- def __init__(self, stream):
- CParser.__init__(self, stream)
- SafeConstructor.__init__(self)
- Resolver.__init__(self)
-
+
+from constructor import *
+
+from serializer import *
+from representer import *
+
+from resolver import *
+
+class CBaseLoader(CParser, BaseConstructor, BaseResolver):
+
+ def __init__(self, stream):
+ CParser.__init__(self, stream)
+ BaseConstructor.__init__(self)
+ BaseResolver.__init__(self)
+
+class CSafeLoader(CParser, SafeConstructor, Resolver):
+
+ def __init__(self, stream):
+ CParser.__init__(self, stream)
+ SafeConstructor.__init__(self)
+ Resolver.__init__(self)
+
class CFullLoader(CParser, FullConstructor, Resolver):
def __init__(self, stream):
@@ -41,61 +41,61 @@ class CUnsafeLoader(CParser, UnsafeConstructor, Resolver):
UnsafeConstructor.__init__(self)
Resolver.__init__(self)
-class CLoader(CParser, Constructor, Resolver):
-
- def __init__(self, stream):
- CParser.__init__(self, stream)
- Constructor.__init__(self)
- Resolver.__init__(self)
-
-class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver):
-
- def __init__(self, stream,
+class CLoader(CParser, Constructor, Resolver):
+
+ def __init__(self, stream):
+ CParser.__init__(self, stream)
+ Constructor.__init__(self)
+ Resolver.__init__(self)
+
+class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver):
+
+ def __init__(self, stream,
default_style=None, default_flow_style=False,
- canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None,
- encoding=None, explicit_start=None, explicit_end=None,
+ canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None,
+ encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None, sort_keys=True):
- CEmitter.__init__(self, stream, canonical=canonical,
- indent=indent, width=width, encoding=encoding,
- allow_unicode=allow_unicode, line_break=line_break,
- explicit_start=explicit_start, explicit_end=explicit_end,
- version=version, tags=tags)
- Representer.__init__(self, default_style=default_style,
+ CEmitter.__init__(self, stream, canonical=canonical,
+ indent=indent, width=width, encoding=encoding,
+ allow_unicode=allow_unicode, line_break=line_break,
+ explicit_start=explicit_start, explicit_end=explicit_end,
+ version=version, tags=tags)
+ Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style, sort_keys=sort_keys)
- Resolver.__init__(self)
-
-class CSafeDumper(CEmitter, SafeRepresenter, Resolver):
-
- def __init__(self, stream,
+ Resolver.__init__(self)
+
+class CSafeDumper(CEmitter, SafeRepresenter, Resolver):
+
+ def __init__(self, stream,
default_style=None, default_flow_style=False,
- canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None,
- encoding=None, explicit_start=None, explicit_end=None,
+ canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None,
+ encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None, sort_keys=True):
- CEmitter.__init__(self, stream, canonical=canonical,
- indent=indent, width=width, encoding=encoding,
- allow_unicode=allow_unicode, line_break=line_break,
- explicit_start=explicit_start, explicit_end=explicit_end,
- version=version, tags=tags)
- SafeRepresenter.__init__(self, default_style=default_style,
+ CEmitter.__init__(self, stream, canonical=canonical,
+ indent=indent, width=width, encoding=encoding,
+ allow_unicode=allow_unicode, line_break=line_break,
+ explicit_start=explicit_start, explicit_end=explicit_end,
+ version=version, tags=tags)
+ SafeRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style, sort_keys=sort_keys)
- Resolver.__init__(self)
-
-class CDumper(CEmitter, Serializer, Representer, Resolver):
-
- def __init__(self, stream,
+ Resolver.__init__(self)
+
+class CDumper(CEmitter, Serializer, Representer, Resolver):
+
+ def __init__(self, stream,
default_style=None, default_flow_style=False,
- canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None,
- encoding=None, explicit_start=None, explicit_end=None,
+ canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None,
+ encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None, sort_keys=True):
- CEmitter.__init__(self, stream, canonical=canonical,
- indent=indent, width=width, encoding=encoding,
- allow_unicode=allow_unicode, line_break=line_break,
- explicit_start=explicit_start, explicit_end=explicit_end,
- version=version, tags=tags)
- Representer.__init__(self, default_style=default_style,
+ CEmitter.__init__(self, stream, canonical=canonical,
+ indent=indent, width=width, encoding=encoding,
+ allow_unicode=allow_unicode, line_break=line_break,
+ explicit_start=explicit_start, explicit_end=explicit_end,
+ version=version, tags=tags)
+ Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style, sort_keys=sort_keys)
- Resolver.__init__(self)
-
+ Resolver.__init__(self)
+
diff --git a/contrib/python/PyYAML/py2/yaml/dumper.py b/contrib/python/PyYAML/py2/yaml/dumper.py
index 42cc2d48b7..f9cd49fda5 100644
--- a/contrib/python/PyYAML/py2/yaml/dumper.py
+++ b/contrib/python/PyYAML/py2/yaml/dumper.py
@@ -1,62 +1,62 @@
-
-__all__ = ['BaseDumper', 'SafeDumper', 'Dumper']
-
-from emitter import *
-from serializer import *
-from representer import *
-from resolver import *
-
-class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver):
-
- def __init__(self, stream,
+
+__all__ = ['BaseDumper', 'SafeDumper', 'Dumper']
+
+from emitter import *
+from serializer import *
+from representer import *
+from resolver import *
+
+class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver):
+
+ def __init__(self, stream,
default_style=None, default_flow_style=False,
- canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None,
- encoding=None, explicit_start=None, explicit_end=None,
+ canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None,
+ encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None, sort_keys=True):
- Emitter.__init__(self, stream, canonical=canonical,
- indent=indent, width=width,
- allow_unicode=allow_unicode, line_break=line_break)
- Serializer.__init__(self, encoding=encoding,
- explicit_start=explicit_start, explicit_end=explicit_end,
- version=version, tags=tags)
- Representer.__init__(self, default_style=default_style,
+ Emitter.__init__(self, stream, canonical=canonical,
+ indent=indent, width=width,
+ allow_unicode=allow_unicode, line_break=line_break)
+ Serializer.__init__(self, encoding=encoding,
+ explicit_start=explicit_start, explicit_end=explicit_end,
+ version=version, tags=tags)
+ Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style, sort_keys=sort_keys)
- Resolver.__init__(self)
-
-class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver):
-
- def __init__(self, stream,
+ Resolver.__init__(self)
+
+class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver):
+
+ def __init__(self, stream,
default_style=None, default_flow_style=False,
- canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None,
- encoding=None, explicit_start=None, explicit_end=None,
+ canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None,
+ encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None, sort_keys=True):
- Emitter.__init__(self, stream, canonical=canonical,
- indent=indent, width=width,
- allow_unicode=allow_unicode, line_break=line_break)
- Serializer.__init__(self, encoding=encoding,
- explicit_start=explicit_start, explicit_end=explicit_end,
- version=version, tags=tags)
- SafeRepresenter.__init__(self, default_style=default_style,
+ Emitter.__init__(self, stream, canonical=canonical,
+ indent=indent, width=width,
+ allow_unicode=allow_unicode, line_break=line_break)
+ Serializer.__init__(self, encoding=encoding,
+ explicit_start=explicit_start, explicit_end=explicit_end,
+ version=version, tags=tags)
+ SafeRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style, sort_keys=sort_keys)
- Resolver.__init__(self)
-
-class Dumper(Emitter, Serializer, Representer, Resolver):
-
- def __init__(self, stream,
+ Resolver.__init__(self)
+
+class Dumper(Emitter, Serializer, Representer, Resolver):
+
+ def __init__(self, stream,
default_style=None, default_flow_style=False,
- canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None,
- encoding=None, explicit_start=None, explicit_end=None,
+ canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None,
+ encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None, sort_keys=True):
- Emitter.__init__(self, stream, canonical=canonical,
- indent=indent, width=width,
- allow_unicode=allow_unicode, line_break=line_break)
- Serializer.__init__(self, encoding=encoding,
- explicit_start=explicit_start, explicit_end=explicit_end,
- version=version, tags=tags)
- Representer.__init__(self, default_style=default_style,
+ Emitter.__init__(self, stream, canonical=canonical,
+ indent=indent, width=width,
+ allow_unicode=allow_unicode, line_break=line_break)
+ Serializer.__init__(self, encoding=encoding,
+ explicit_start=explicit_start, explicit_end=explicit_end,
+ version=version, tags=tags)
+ Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style, sort_keys=sort_keys)
- Resolver.__init__(self)
-
+ Resolver.__init__(self)
+
diff --git a/contrib/python/PyYAML/py2/yaml/emitter.py b/contrib/python/PyYAML/py2/yaml/emitter.py
index d7207037be..23c25ca80a 100644
--- a/contrib/python/PyYAML/py2/yaml/emitter.py
+++ b/contrib/python/PyYAML/py2/yaml/emitter.py
@@ -1,1144 +1,1144 @@
-
-# Emitter expects events obeying the following grammar:
-# stream ::= STREAM-START document* STREAM-END
-# document ::= DOCUMENT-START node DOCUMENT-END
-# node ::= SCALAR | sequence | mapping
-# sequence ::= SEQUENCE-START node* SEQUENCE-END
-# mapping ::= MAPPING-START (node node)* MAPPING-END
-
-__all__ = ['Emitter', 'EmitterError']
-
+
+# Emitter expects events obeying the following grammar:
+# stream ::= STREAM-START document* STREAM-END
+# document ::= DOCUMENT-START node DOCUMENT-END
+# node ::= SCALAR | sequence | mapping
+# sequence ::= SEQUENCE-START node* SEQUENCE-END
+# mapping ::= MAPPING-START (node node)* MAPPING-END
+
+__all__ = ['Emitter', 'EmitterError']
+
import sys
-from error import YAMLError
-from events import *
-
+from error import YAMLError
+from events import *
+
has_ucs4 = sys.maxunicode > 0xffff
-class EmitterError(YAMLError):
- pass
-
-class ScalarAnalysis(object):
- def __init__(self, scalar, empty, multiline,
- allow_flow_plain, allow_block_plain,
- allow_single_quoted, allow_double_quoted,
- allow_block):
- self.scalar = scalar
- self.empty = empty
- self.multiline = multiline
- self.allow_flow_plain = allow_flow_plain
- self.allow_block_plain = allow_block_plain
- self.allow_single_quoted = allow_single_quoted
- self.allow_double_quoted = allow_double_quoted
- self.allow_block = allow_block
-
-class Emitter(object):
-
- DEFAULT_TAG_PREFIXES = {
- u'!' : u'!',
- u'tag:yaml.org,2002:' : u'!!',
- }
-
- def __init__(self, stream, canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None):
-
- # The stream should have the methods `write` and possibly `flush`.
- self.stream = stream
-
+class EmitterError(YAMLError):
+ pass
+
+class ScalarAnalysis(object):
+ def __init__(self, scalar, empty, multiline,
+ allow_flow_plain, allow_block_plain,
+ allow_single_quoted, allow_double_quoted,
+ allow_block):
+ self.scalar = scalar
+ self.empty = empty
+ self.multiline = multiline
+ self.allow_flow_plain = allow_flow_plain
+ self.allow_block_plain = allow_block_plain
+ self.allow_single_quoted = allow_single_quoted
+ self.allow_double_quoted = allow_double_quoted
+ self.allow_block = allow_block
+
+class Emitter(object):
+
+ DEFAULT_TAG_PREFIXES = {
+ u'!' : u'!',
+ u'tag:yaml.org,2002:' : u'!!',
+ }
+
+ def __init__(self, stream, canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None):
+
+ # The stream should have the methods `write` and possibly `flush`.
+ self.stream = stream
+
# Encoding can be overridden by STREAM-START.
- self.encoding = None
-
- # Emitter is a state machine with a stack of states to handle nested
- # structures.
- self.states = []
- self.state = self.expect_stream_start
-
- # Current event and the event queue.
- self.events = []
- self.event = None
-
- # The current indentation level and the stack of previous indents.
- self.indents = []
- self.indent = None
-
- # Flow level.
- self.flow_level = 0
-
- # Contexts.
- self.root_context = False
- self.sequence_context = False
- self.mapping_context = False
- self.simple_key_context = False
-
- # Characteristics of the last emitted character:
- # - current position.
- # - is it a whitespace?
- # - is it an indention character
- # (indentation space, '-', '?', or ':')?
- self.line = 0
- self.column = 0
- self.whitespace = True
- self.indention = True
-
- # Whether the document requires an explicit document indicator
- self.open_ended = False
-
- # Formatting details.
- self.canonical = canonical
- self.allow_unicode = allow_unicode
- self.best_indent = 2
- if indent and 1 < indent < 10:
- self.best_indent = indent
- self.best_width = 80
- if width and width > self.best_indent*2:
- self.best_width = width
- self.best_line_break = u'\n'
- if line_break in [u'\r', u'\n', u'\r\n']:
- self.best_line_break = line_break
-
- # Tag prefixes.
- self.tag_prefixes = None
-
- # Prepared anchor and tag.
- self.prepared_anchor = None
- self.prepared_tag = None
-
- # Scalar analysis and style.
- self.analysis = None
- self.style = None
-
- def dispose(self):
- # Reset the state attributes (to clear self-references)
- self.states = []
- self.state = None
-
- def emit(self, event):
- self.events.append(event)
- while not self.need_more_events():
- self.event = self.events.pop(0)
- self.state()
- self.event = None
-
- # In some cases, we wait for a few next events before emitting.
-
- def need_more_events(self):
- if not self.events:
- return True
- event = self.events[0]
- if isinstance(event, DocumentStartEvent):
- return self.need_events(1)
- elif isinstance(event, SequenceStartEvent):
- return self.need_events(2)
- elif isinstance(event, MappingStartEvent):
- return self.need_events(3)
- else:
- return False
-
- def need_events(self, count):
- level = 0
- for event in self.events[1:]:
- if isinstance(event, (DocumentStartEvent, CollectionStartEvent)):
- level += 1
- elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)):
- level -= 1
- elif isinstance(event, StreamEndEvent):
- level = -1
- if level < 0:
- return False
- return (len(self.events) < count+1)
-
- def increase_indent(self, flow=False, indentless=False):
- self.indents.append(self.indent)
- if self.indent is None:
- if flow:
- self.indent = self.best_indent
- else:
- self.indent = 0
- elif not indentless:
- self.indent += self.best_indent
-
- # States.
-
- # Stream handlers.
-
- def expect_stream_start(self):
- if isinstance(self.event, StreamStartEvent):
- if self.event.encoding and not getattr(self.stream, 'encoding', None):
- self.encoding = self.event.encoding
- self.write_stream_start()
- self.state = self.expect_first_document_start
- else:
- raise EmitterError("expected StreamStartEvent, but got %s"
- % self.event)
-
- def expect_nothing(self):
- raise EmitterError("expected nothing, but got %s" % self.event)
-
- # Document handlers.
-
- def expect_first_document_start(self):
- return self.expect_document_start(first=True)
-
- def expect_document_start(self, first=False):
- if isinstance(self.event, DocumentStartEvent):
- if (self.event.version or self.event.tags) and self.open_ended:
- self.write_indicator(u'...', True)
- self.write_indent()
- if self.event.version:
- version_text = self.prepare_version(self.event.version)
- self.write_version_directive(version_text)
- self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy()
- if self.event.tags:
- handles = self.event.tags.keys()
- handles.sort()
- for handle in handles:
- prefix = self.event.tags[handle]
- self.tag_prefixes[prefix] = handle
- handle_text = self.prepare_tag_handle(handle)
- prefix_text = self.prepare_tag_prefix(prefix)
- self.write_tag_directive(handle_text, prefix_text)
- implicit = (first and not self.event.explicit and not self.canonical
- and not self.event.version and not self.event.tags
- and not self.check_empty_document())
- if not implicit:
- self.write_indent()
- self.write_indicator(u'---', True)
- if self.canonical:
- self.write_indent()
- self.state = self.expect_document_root
- elif isinstance(self.event, StreamEndEvent):
- if self.open_ended:
- self.write_indicator(u'...', True)
- self.write_indent()
- self.write_stream_end()
- self.state = self.expect_nothing
- else:
- raise EmitterError("expected DocumentStartEvent, but got %s"
- % self.event)
-
- def expect_document_end(self):
- if isinstance(self.event, DocumentEndEvent):
- self.write_indent()
- if self.event.explicit:
- self.write_indicator(u'...', True)
- self.write_indent()
- self.flush_stream()
- self.state = self.expect_document_start
- else:
- raise EmitterError("expected DocumentEndEvent, but got %s"
- % self.event)
-
- def expect_document_root(self):
- self.states.append(self.expect_document_end)
- self.expect_node(root=True)
-
- # Node handlers.
-
- def expect_node(self, root=False, sequence=False, mapping=False,
- simple_key=False):
- self.root_context = root
- self.sequence_context = sequence
- self.mapping_context = mapping
- self.simple_key_context = simple_key
- if isinstance(self.event, AliasEvent):
- self.expect_alias()
- elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)):
- self.process_anchor(u'&')
- self.process_tag()
- if isinstance(self.event, ScalarEvent):
- self.expect_scalar()
- elif isinstance(self.event, SequenceStartEvent):
- if self.flow_level or self.canonical or self.event.flow_style \
- or self.check_empty_sequence():
- self.expect_flow_sequence()
- else:
- self.expect_block_sequence()
- elif isinstance(self.event, MappingStartEvent):
- if self.flow_level or self.canonical or self.event.flow_style \
- or self.check_empty_mapping():
- self.expect_flow_mapping()
- else:
- self.expect_block_mapping()
- else:
- raise EmitterError("expected NodeEvent, but got %s" % self.event)
-
- def expect_alias(self):
- if self.event.anchor is None:
- raise EmitterError("anchor is not specified for alias")
- self.process_anchor(u'*')
- self.state = self.states.pop()
-
- def expect_scalar(self):
- self.increase_indent(flow=True)
- self.process_scalar()
- self.indent = self.indents.pop()
- self.state = self.states.pop()
-
- # Flow sequence handlers.
-
- def expect_flow_sequence(self):
- self.write_indicator(u'[', True, whitespace=True)
- self.flow_level += 1
- self.increase_indent(flow=True)
- self.state = self.expect_first_flow_sequence_item
-
- def expect_first_flow_sequence_item(self):
- if isinstance(self.event, SequenceEndEvent):
- self.indent = self.indents.pop()
- self.flow_level -= 1
- self.write_indicator(u']', False)
- self.state = self.states.pop()
- else:
- if self.canonical or self.column > self.best_width:
- self.write_indent()
- self.states.append(self.expect_flow_sequence_item)
- self.expect_node(sequence=True)
-
- def expect_flow_sequence_item(self):
- if isinstance(self.event, SequenceEndEvent):
- self.indent = self.indents.pop()
- self.flow_level -= 1
- if self.canonical:
- self.write_indicator(u',', False)
- self.write_indent()
- self.write_indicator(u']', False)
- self.state = self.states.pop()
- else:
- self.write_indicator(u',', False)
- if self.canonical or self.column > self.best_width:
- self.write_indent()
- self.states.append(self.expect_flow_sequence_item)
- self.expect_node(sequence=True)
-
- # Flow mapping handlers.
-
- def expect_flow_mapping(self):
- self.write_indicator(u'{', True, whitespace=True)
- self.flow_level += 1
- self.increase_indent(flow=True)
- self.state = self.expect_first_flow_mapping_key
-
- def expect_first_flow_mapping_key(self):
- if isinstance(self.event, MappingEndEvent):
- self.indent = self.indents.pop()
- self.flow_level -= 1
- self.write_indicator(u'}', False)
- self.state = self.states.pop()
- else:
- if self.canonical or self.column > self.best_width:
- self.write_indent()
- if not self.canonical and self.check_simple_key():
- self.states.append(self.expect_flow_mapping_simple_value)
- self.expect_node(mapping=True, simple_key=True)
- else:
- self.write_indicator(u'?', True)
- self.states.append(self.expect_flow_mapping_value)
- self.expect_node(mapping=True)
-
- def expect_flow_mapping_key(self):
- if isinstance(self.event, MappingEndEvent):
- self.indent = self.indents.pop()
- self.flow_level -= 1
- if self.canonical:
- self.write_indicator(u',', False)
- self.write_indent()
- self.write_indicator(u'}', False)
- self.state = self.states.pop()
- else:
- self.write_indicator(u',', False)
- if self.canonical or self.column > self.best_width:
- self.write_indent()
- if not self.canonical and self.check_simple_key():
- self.states.append(self.expect_flow_mapping_simple_value)
- self.expect_node(mapping=True, simple_key=True)
- else:
- self.write_indicator(u'?', True)
- self.states.append(self.expect_flow_mapping_value)
- self.expect_node(mapping=True)
-
- def expect_flow_mapping_simple_value(self):
- self.write_indicator(u':', False)
- self.states.append(self.expect_flow_mapping_key)
- self.expect_node(mapping=True)
-
- def expect_flow_mapping_value(self):
- if self.canonical or self.column > self.best_width:
- self.write_indent()
- self.write_indicator(u':', True)
- self.states.append(self.expect_flow_mapping_key)
- self.expect_node(mapping=True)
-
- # Block sequence handlers.
-
- def expect_block_sequence(self):
- indentless = (self.mapping_context and not self.indention)
- self.increase_indent(flow=False, indentless=indentless)
- self.state = self.expect_first_block_sequence_item
-
- def expect_first_block_sequence_item(self):
- return self.expect_block_sequence_item(first=True)
-
- def expect_block_sequence_item(self, first=False):
- if not first and isinstance(self.event, SequenceEndEvent):
- self.indent = self.indents.pop()
- self.state = self.states.pop()
- else:
- self.write_indent()
- self.write_indicator(u'-', True, indention=True)
- self.states.append(self.expect_block_sequence_item)
- self.expect_node(sequence=True)
-
- # Block mapping handlers.
-
- def expect_block_mapping(self):
- self.increase_indent(flow=False)
- self.state = self.expect_first_block_mapping_key
-
- def expect_first_block_mapping_key(self):
- return self.expect_block_mapping_key(first=True)
-
- def expect_block_mapping_key(self, first=False):
- if not first and isinstance(self.event, MappingEndEvent):
- self.indent = self.indents.pop()
- self.state = self.states.pop()
- else:
- self.write_indent()
- if self.check_simple_key():
- self.states.append(self.expect_block_mapping_simple_value)
- self.expect_node(mapping=True, simple_key=True)
- else:
- self.write_indicator(u'?', True, indention=True)
- self.states.append(self.expect_block_mapping_value)
- self.expect_node(mapping=True)
-
- def expect_block_mapping_simple_value(self):
- self.write_indicator(u':', False)
- self.states.append(self.expect_block_mapping_key)
- self.expect_node(mapping=True)
-
- def expect_block_mapping_value(self):
- self.write_indent()
- self.write_indicator(u':', True, indention=True)
- self.states.append(self.expect_block_mapping_key)
- self.expect_node(mapping=True)
-
- # Checkers.
-
- def check_empty_sequence(self):
- return (isinstance(self.event, SequenceStartEvent) and self.events
- and isinstance(self.events[0], SequenceEndEvent))
-
- def check_empty_mapping(self):
- return (isinstance(self.event, MappingStartEvent) and self.events
- and isinstance(self.events[0], MappingEndEvent))
-
- def check_empty_document(self):
- if not isinstance(self.event, DocumentStartEvent) or not self.events:
- return False
- event = self.events[0]
- return (isinstance(event, ScalarEvent) and event.anchor is None
- and event.tag is None and event.implicit and event.value == u'')
-
- def check_simple_key(self):
- length = 0
- if isinstance(self.event, NodeEvent) and self.event.anchor is not None:
- if self.prepared_anchor is None:
- self.prepared_anchor = self.prepare_anchor(self.event.anchor)
- length += len(self.prepared_anchor)
- if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \
- and self.event.tag is not None:
- if self.prepared_tag is None:
- self.prepared_tag = self.prepare_tag(self.event.tag)
- length += len(self.prepared_tag)
- if isinstance(self.event, ScalarEvent):
- if self.analysis is None:
- self.analysis = self.analyze_scalar(self.event.value)
- length += len(self.analysis.scalar)
- return (length < 128 and (isinstance(self.event, AliasEvent)
- or (isinstance(self.event, ScalarEvent)
- and not self.analysis.empty and not self.analysis.multiline)
- or self.check_empty_sequence() or self.check_empty_mapping()))
-
- # Anchor, Tag, and Scalar processors.
-
- def process_anchor(self, indicator):
- if self.event.anchor is None:
- self.prepared_anchor = None
- return
- if self.prepared_anchor is None:
- self.prepared_anchor = self.prepare_anchor(self.event.anchor)
- if self.prepared_anchor:
- self.write_indicator(indicator+self.prepared_anchor, True)
- self.prepared_anchor = None
-
- def process_tag(self):
- tag = self.event.tag
- if isinstance(self.event, ScalarEvent):
- if self.style is None:
- self.style = self.choose_scalar_style()
- if ((not self.canonical or tag is None) and
- ((self.style == '' and self.event.implicit[0])
- or (self.style != '' and self.event.implicit[1]))):
- self.prepared_tag = None
- return
- if self.event.implicit[0] and tag is None:
- tag = u'!'
- self.prepared_tag = None
- else:
- if (not self.canonical or tag is None) and self.event.implicit:
- self.prepared_tag = None
- return
- if tag is None:
- raise EmitterError("tag is not specified")
- if self.prepared_tag is None:
- self.prepared_tag = self.prepare_tag(tag)
- if self.prepared_tag:
- self.write_indicator(self.prepared_tag, True)
- self.prepared_tag = None
-
- def choose_scalar_style(self):
- if self.analysis is None:
- self.analysis = self.analyze_scalar(self.event.value)
- if self.event.style == '"' or self.canonical:
- return '"'
- if not self.event.style and self.event.implicit[0]:
- if (not (self.simple_key_context and
- (self.analysis.empty or self.analysis.multiline))
- and (self.flow_level and self.analysis.allow_flow_plain
- or (not self.flow_level and self.analysis.allow_block_plain))):
- return ''
- if self.event.style and self.event.style in '|>':
- if (not self.flow_level and not self.simple_key_context
- and self.analysis.allow_block):
- return self.event.style
- if not self.event.style or self.event.style == '\'':
- if (self.analysis.allow_single_quoted and
- not (self.simple_key_context and self.analysis.multiline)):
- return '\''
- return '"'
-
- def process_scalar(self):
- if self.analysis is None:
- self.analysis = self.analyze_scalar(self.event.value)
- if self.style is None:
- self.style = self.choose_scalar_style()
- split = (not self.simple_key_context)
- #if self.analysis.multiline and split \
- # and (not self.style or self.style in '\'\"'):
- # self.write_indent()
- if self.style == '"':
- self.write_double_quoted(self.analysis.scalar, split)
- elif self.style == '\'':
- self.write_single_quoted(self.analysis.scalar, split)
- elif self.style == '>':
- self.write_folded(self.analysis.scalar)
- elif self.style == '|':
- self.write_literal(self.analysis.scalar)
- else:
- self.write_plain(self.analysis.scalar, split)
- self.analysis = None
- self.style = None
-
- # Analyzers.
-
- def prepare_version(self, version):
- major, minor = version
- if major != 1:
- raise EmitterError("unsupported YAML version: %d.%d" % (major, minor))
- return u'%d.%d' % (major, minor)
-
- def prepare_tag_handle(self, handle):
- if not handle:
- raise EmitterError("tag handle must not be empty")
- if handle[0] != u'!' or handle[-1] != u'!':
- raise EmitterError("tag handle must start and end with '!': %r"
- % (handle.encode('utf-8')))
- for ch in handle[1:-1]:
- if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
- or ch in u'-_'):
- raise EmitterError("invalid character %r in the tag handle: %r"
- % (ch.encode('utf-8'), handle.encode('utf-8')))
- return handle
-
- def prepare_tag_prefix(self, prefix):
- if not prefix:
- raise EmitterError("tag prefix must not be empty")
- chunks = []
- start = end = 0
- if prefix[0] == u'!':
- end = 1
- while end < len(prefix):
- ch = prefix[end]
- if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
- or ch in u'-;/?!:@&=+$,_.~*\'()[]':
- end += 1
- else:
- if start < end:
- chunks.append(prefix[start:end])
- start = end = end+1
- data = ch.encode('utf-8')
- for ch in data:
- chunks.append(u'%%%02X' % ord(ch))
- if start < end:
- chunks.append(prefix[start:end])
- return u''.join(chunks)
-
- def prepare_tag(self, tag):
- if not tag:
- raise EmitterError("tag must not be empty")
- if tag == u'!':
- return tag
- handle = None
- suffix = tag
- prefixes = self.tag_prefixes.keys()
- prefixes.sort()
- for prefix in prefixes:
- if tag.startswith(prefix) \
- and (prefix == u'!' or len(prefix) < len(tag)):
- handle = self.tag_prefixes[prefix]
- suffix = tag[len(prefix):]
- chunks = []
- start = end = 0
- while end < len(suffix):
- ch = suffix[end]
- if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
- or ch in u'-;/?:@&=+$,_.~*\'()[]' \
- or (ch == u'!' and handle != u'!'):
- end += 1
- else:
- if start < end:
- chunks.append(suffix[start:end])
- start = end = end+1
- data = ch.encode('utf-8')
- for ch in data:
- chunks.append(u'%%%02X' % ord(ch))
- if start < end:
- chunks.append(suffix[start:end])
- suffix_text = u''.join(chunks)
- if handle:
- return u'%s%s' % (handle, suffix_text)
- else:
- return u'!<%s>' % suffix_text
-
- def prepare_anchor(self, anchor):
- if not anchor:
- raise EmitterError("anchor must not be empty")
- for ch in anchor:
- if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
- or ch in u'-_'):
- raise EmitterError("invalid character %r in the anchor: %r"
- % (ch.encode('utf-8'), anchor.encode('utf-8')))
- return anchor
-
- def analyze_scalar(self, scalar):
-
- # Empty scalar is a special case.
- if not scalar:
- return ScalarAnalysis(scalar=scalar, empty=True, multiline=False,
- allow_flow_plain=False, allow_block_plain=True,
- allow_single_quoted=True, allow_double_quoted=True,
- allow_block=False)
-
- # Indicators and special characters.
- block_indicators = False
- flow_indicators = False
- line_breaks = False
- special_characters = False
-
- # Important whitespace combinations.
- leading_space = False
- leading_break = False
- trailing_space = False
- trailing_break = False
- break_space = False
- space_break = False
-
- # Check document indicators.
- if scalar.startswith(u'---') or scalar.startswith(u'...'):
- block_indicators = True
- flow_indicators = True
-
- # First character or preceded by a whitespace.
+ self.encoding = None
+
+ # Emitter is a state machine with a stack of states to handle nested
+ # structures.
+ self.states = []
+ self.state = self.expect_stream_start
+
+ # Current event and the event queue.
+ self.events = []
+ self.event = None
+
+ # The current indentation level and the stack of previous indents.
+ self.indents = []
+ self.indent = None
+
+ # Flow level.
+ self.flow_level = 0
+
+ # Contexts.
+ self.root_context = False
+ self.sequence_context = False
+ self.mapping_context = False
+ self.simple_key_context = False
+
+ # Characteristics of the last emitted character:
+ # - current position.
+ # - is it a whitespace?
+ # - is it an indention character
+ # (indentation space, '-', '?', or ':')?
+ self.line = 0
+ self.column = 0
+ self.whitespace = True
+ self.indention = True
+
+ # Whether the document requires an explicit document indicator
+ self.open_ended = False
+
+ # Formatting details.
+ self.canonical = canonical
+ self.allow_unicode = allow_unicode
+ self.best_indent = 2
+ if indent and 1 < indent < 10:
+ self.best_indent = indent
+ self.best_width = 80
+ if width and width > self.best_indent*2:
+ self.best_width = width
+ self.best_line_break = u'\n'
+ if line_break in [u'\r', u'\n', u'\r\n']:
+ self.best_line_break = line_break
+
+ # Tag prefixes.
+ self.tag_prefixes = None
+
+ # Prepared anchor and tag.
+ self.prepared_anchor = None
+ self.prepared_tag = None
+
+ # Scalar analysis and style.
+ self.analysis = None
+ self.style = None
+
+ def dispose(self):
+ # Reset the state attributes (to clear self-references)
+ self.states = []
+ self.state = None
+
+ def emit(self, event):
+ self.events.append(event)
+ while not self.need_more_events():
+ self.event = self.events.pop(0)
+ self.state()
+ self.event = None
+
+ # In some cases, we wait for a few next events before emitting.
+
+ def need_more_events(self):
+ if not self.events:
+ return True
+ event = self.events[0]
+ if isinstance(event, DocumentStartEvent):
+ return self.need_events(1)
+ elif isinstance(event, SequenceStartEvent):
+ return self.need_events(2)
+ elif isinstance(event, MappingStartEvent):
+ return self.need_events(3)
+ else:
+ return False
+
+ def need_events(self, count):
+ level = 0
+ for event in self.events[1:]:
+ if isinstance(event, (DocumentStartEvent, CollectionStartEvent)):
+ level += 1
+ elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)):
+ level -= 1
+ elif isinstance(event, StreamEndEvent):
+ level = -1
+ if level < 0:
+ return False
+ return (len(self.events) < count+1)
+
+ def increase_indent(self, flow=False, indentless=False):
+ self.indents.append(self.indent)
+ if self.indent is None:
+ if flow:
+ self.indent = self.best_indent
+ else:
+ self.indent = 0
+ elif not indentless:
+ self.indent += self.best_indent
+
+ # States.
+
+ # Stream handlers.
+
+ def expect_stream_start(self):
+ if isinstance(self.event, StreamStartEvent):
+ if self.event.encoding and not getattr(self.stream, 'encoding', None):
+ self.encoding = self.event.encoding
+ self.write_stream_start()
+ self.state = self.expect_first_document_start
+ else:
+ raise EmitterError("expected StreamStartEvent, but got %s"
+ % self.event)
+
+ def expect_nothing(self):
+ raise EmitterError("expected nothing, but got %s" % self.event)
+
+ # Document handlers.
+
+ def expect_first_document_start(self):
+ return self.expect_document_start(first=True)
+
+ def expect_document_start(self, first=False):
+ if isinstance(self.event, DocumentStartEvent):
+ if (self.event.version or self.event.tags) and self.open_ended:
+ self.write_indicator(u'...', True)
+ self.write_indent()
+ if self.event.version:
+ version_text = self.prepare_version(self.event.version)
+ self.write_version_directive(version_text)
+ self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy()
+ if self.event.tags:
+ handles = self.event.tags.keys()
+ handles.sort()
+ for handle in handles:
+ prefix = self.event.tags[handle]
+ self.tag_prefixes[prefix] = handle
+ handle_text = self.prepare_tag_handle(handle)
+ prefix_text = self.prepare_tag_prefix(prefix)
+ self.write_tag_directive(handle_text, prefix_text)
+ implicit = (first and not self.event.explicit and not self.canonical
+ and not self.event.version and not self.event.tags
+ and not self.check_empty_document())
+ if not implicit:
+ self.write_indent()
+ self.write_indicator(u'---', True)
+ if self.canonical:
+ self.write_indent()
+ self.state = self.expect_document_root
+ elif isinstance(self.event, StreamEndEvent):
+ if self.open_ended:
+ self.write_indicator(u'...', True)
+ self.write_indent()
+ self.write_stream_end()
+ self.state = self.expect_nothing
+ else:
+ raise EmitterError("expected DocumentStartEvent, but got %s"
+ % self.event)
+
+ def expect_document_end(self):
+ if isinstance(self.event, DocumentEndEvent):
+ self.write_indent()
+ if self.event.explicit:
+ self.write_indicator(u'...', True)
+ self.write_indent()
+ self.flush_stream()
+ self.state = self.expect_document_start
+ else:
+ raise EmitterError("expected DocumentEndEvent, but got %s"
+ % self.event)
+
+ def expect_document_root(self):
+ self.states.append(self.expect_document_end)
+ self.expect_node(root=True)
+
+ # Node handlers.
+
+ def expect_node(self, root=False, sequence=False, mapping=False,
+ simple_key=False):
+ self.root_context = root
+ self.sequence_context = sequence
+ self.mapping_context = mapping
+ self.simple_key_context = simple_key
+ if isinstance(self.event, AliasEvent):
+ self.expect_alias()
+ elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)):
+ self.process_anchor(u'&')
+ self.process_tag()
+ if isinstance(self.event, ScalarEvent):
+ self.expect_scalar()
+ elif isinstance(self.event, SequenceStartEvent):
+ if self.flow_level or self.canonical or self.event.flow_style \
+ or self.check_empty_sequence():
+ self.expect_flow_sequence()
+ else:
+ self.expect_block_sequence()
+ elif isinstance(self.event, MappingStartEvent):
+ if self.flow_level or self.canonical or self.event.flow_style \
+ or self.check_empty_mapping():
+ self.expect_flow_mapping()
+ else:
+ self.expect_block_mapping()
+ else:
+ raise EmitterError("expected NodeEvent, but got %s" % self.event)
+
+ def expect_alias(self):
+ if self.event.anchor is None:
+ raise EmitterError("anchor is not specified for alias")
+ self.process_anchor(u'*')
+ self.state = self.states.pop()
+
+ def expect_scalar(self):
+ self.increase_indent(flow=True)
+ self.process_scalar()
+ self.indent = self.indents.pop()
+ self.state = self.states.pop()
+
+ # Flow sequence handlers.
+
+ def expect_flow_sequence(self):
+ self.write_indicator(u'[', True, whitespace=True)
+ self.flow_level += 1
+ self.increase_indent(flow=True)
+ self.state = self.expect_first_flow_sequence_item
+
+ def expect_first_flow_sequence_item(self):
+ if isinstance(self.event, SequenceEndEvent):
+ self.indent = self.indents.pop()
+ self.flow_level -= 1
+ self.write_indicator(u']', False)
+ self.state = self.states.pop()
+ else:
+ if self.canonical or self.column > self.best_width:
+ self.write_indent()
+ self.states.append(self.expect_flow_sequence_item)
+ self.expect_node(sequence=True)
+
+ def expect_flow_sequence_item(self):
+ if isinstance(self.event, SequenceEndEvent):
+ self.indent = self.indents.pop()
+ self.flow_level -= 1
+ if self.canonical:
+ self.write_indicator(u',', False)
+ self.write_indent()
+ self.write_indicator(u']', False)
+ self.state = self.states.pop()
+ else:
+ self.write_indicator(u',', False)
+ if self.canonical or self.column > self.best_width:
+ self.write_indent()
+ self.states.append(self.expect_flow_sequence_item)
+ self.expect_node(sequence=True)
+
+ # Flow mapping handlers.
+
+ def expect_flow_mapping(self):
+ self.write_indicator(u'{', True, whitespace=True)
+ self.flow_level += 1
+ self.increase_indent(flow=True)
+ self.state = self.expect_first_flow_mapping_key
+
+ def expect_first_flow_mapping_key(self):
+ if isinstance(self.event, MappingEndEvent):
+ self.indent = self.indents.pop()
+ self.flow_level -= 1
+ self.write_indicator(u'}', False)
+ self.state = self.states.pop()
+ else:
+ if self.canonical or self.column > self.best_width:
+ self.write_indent()
+ if not self.canonical and self.check_simple_key():
+ self.states.append(self.expect_flow_mapping_simple_value)
+ self.expect_node(mapping=True, simple_key=True)
+ else:
+ self.write_indicator(u'?', True)
+ self.states.append(self.expect_flow_mapping_value)
+ self.expect_node(mapping=True)
+
+ def expect_flow_mapping_key(self):
+ if isinstance(self.event, MappingEndEvent):
+ self.indent = self.indents.pop()
+ self.flow_level -= 1
+ if self.canonical:
+ self.write_indicator(u',', False)
+ self.write_indent()
+ self.write_indicator(u'}', False)
+ self.state = self.states.pop()
+ else:
+ self.write_indicator(u',', False)
+ if self.canonical or self.column > self.best_width:
+ self.write_indent()
+ if not self.canonical and self.check_simple_key():
+ self.states.append(self.expect_flow_mapping_simple_value)
+ self.expect_node(mapping=True, simple_key=True)
+ else:
+ self.write_indicator(u'?', True)
+ self.states.append(self.expect_flow_mapping_value)
+ self.expect_node(mapping=True)
+
+ def expect_flow_mapping_simple_value(self):
+ self.write_indicator(u':', False)
+ self.states.append(self.expect_flow_mapping_key)
+ self.expect_node(mapping=True)
+
+ def expect_flow_mapping_value(self):
+ if self.canonical or self.column > self.best_width:
+ self.write_indent()
+ self.write_indicator(u':', True)
+ self.states.append(self.expect_flow_mapping_key)
+ self.expect_node(mapping=True)
+
+ # Block sequence handlers.
+
+ def expect_block_sequence(self):
+ indentless = (self.mapping_context and not self.indention)
+ self.increase_indent(flow=False, indentless=indentless)
+ self.state = self.expect_first_block_sequence_item
+
+ def expect_first_block_sequence_item(self):
+ return self.expect_block_sequence_item(first=True)
+
+ def expect_block_sequence_item(self, first=False):
+ if not first and isinstance(self.event, SequenceEndEvent):
+ self.indent = self.indents.pop()
+ self.state = self.states.pop()
+ else:
+ self.write_indent()
+ self.write_indicator(u'-', True, indention=True)
+ self.states.append(self.expect_block_sequence_item)
+ self.expect_node(sequence=True)
+
+ # Block mapping handlers.
+
+ def expect_block_mapping(self):
+ self.increase_indent(flow=False)
+ self.state = self.expect_first_block_mapping_key
+
+ def expect_first_block_mapping_key(self):
+ return self.expect_block_mapping_key(first=True)
+
+ def expect_block_mapping_key(self, first=False):
+ if not first and isinstance(self.event, MappingEndEvent):
+ self.indent = self.indents.pop()
+ self.state = self.states.pop()
+ else:
+ self.write_indent()
+ if self.check_simple_key():
+ self.states.append(self.expect_block_mapping_simple_value)
+ self.expect_node(mapping=True, simple_key=True)
+ else:
+ self.write_indicator(u'?', True, indention=True)
+ self.states.append(self.expect_block_mapping_value)
+ self.expect_node(mapping=True)
+
+ def expect_block_mapping_simple_value(self):
+ self.write_indicator(u':', False)
+ self.states.append(self.expect_block_mapping_key)
+ self.expect_node(mapping=True)
+
+ def expect_block_mapping_value(self):
+ self.write_indent()
+ self.write_indicator(u':', True, indention=True)
+ self.states.append(self.expect_block_mapping_key)
+ self.expect_node(mapping=True)
+
+ # Checkers.
+
+ def check_empty_sequence(self):
+ return (isinstance(self.event, SequenceStartEvent) and self.events
+ and isinstance(self.events[0], SequenceEndEvent))
+
+ def check_empty_mapping(self):
+ return (isinstance(self.event, MappingStartEvent) and self.events
+ and isinstance(self.events[0], MappingEndEvent))
+
+ def check_empty_document(self):
+ if not isinstance(self.event, DocumentStartEvent) or not self.events:
+ return False
+ event = self.events[0]
+ return (isinstance(event, ScalarEvent) and event.anchor is None
+ and event.tag is None and event.implicit and event.value == u'')
+
+ def check_simple_key(self):
+ length = 0
+ if isinstance(self.event, NodeEvent) and self.event.anchor is not None:
+ if self.prepared_anchor is None:
+ self.prepared_anchor = self.prepare_anchor(self.event.anchor)
+ length += len(self.prepared_anchor)
+ if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \
+ and self.event.tag is not None:
+ if self.prepared_tag is None:
+ self.prepared_tag = self.prepare_tag(self.event.tag)
+ length += len(self.prepared_tag)
+ if isinstance(self.event, ScalarEvent):
+ if self.analysis is None:
+ self.analysis = self.analyze_scalar(self.event.value)
+ length += len(self.analysis.scalar)
+ return (length < 128 and (isinstance(self.event, AliasEvent)
+ or (isinstance(self.event, ScalarEvent)
+ and not self.analysis.empty and not self.analysis.multiline)
+ or self.check_empty_sequence() or self.check_empty_mapping()))
+
+ # Anchor, Tag, and Scalar processors.
+
+ def process_anchor(self, indicator):
+ if self.event.anchor is None:
+ self.prepared_anchor = None
+ return
+ if self.prepared_anchor is None:
+ self.prepared_anchor = self.prepare_anchor(self.event.anchor)
+ if self.prepared_anchor:
+ self.write_indicator(indicator+self.prepared_anchor, True)
+ self.prepared_anchor = None
+
+ def process_tag(self):
+ tag = self.event.tag
+ if isinstance(self.event, ScalarEvent):
+ if self.style is None:
+ self.style = self.choose_scalar_style()
+ if ((not self.canonical or tag is None) and
+ ((self.style == '' and self.event.implicit[0])
+ or (self.style != '' and self.event.implicit[1]))):
+ self.prepared_tag = None
+ return
+ if self.event.implicit[0] and tag is None:
+ tag = u'!'
+ self.prepared_tag = None
+ else:
+ if (not self.canonical or tag is None) and self.event.implicit:
+ self.prepared_tag = None
+ return
+ if tag is None:
+ raise EmitterError("tag is not specified")
+ if self.prepared_tag is None:
+ self.prepared_tag = self.prepare_tag(tag)
+ if self.prepared_tag:
+ self.write_indicator(self.prepared_tag, True)
+ self.prepared_tag = None
+
+ def choose_scalar_style(self):
+ if self.analysis is None:
+ self.analysis = self.analyze_scalar(self.event.value)
+ if self.event.style == '"' or self.canonical:
+ return '"'
+ if not self.event.style and self.event.implicit[0]:
+ if (not (self.simple_key_context and
+ (self.analysis.empty or self.analysis.multiline))
+ and (self.flow_level and self.analysis.allow_flow_plain
+ or (not self.flow_level and self.analysis.allow_block_plain))):
+ return ''
+ if self.event.style and self.event.style in '|>':
+ if (not self.flow_level and not self.simple_key_context
+ and self.analysis.allow_block):
+ return self.event.style
+ if not self.event.style or self.event.style == '\'':
+ if (self.analysis.allow_single_quoted and
+ not (self.simple_key_context and self.analysis.multiline)):
+ return '\''
+ return '"'
+
+ def process_scalar(self):
+ if self.analysis is None:
+ self.analysis = self.analyze_scalar(self.event.value)
+ if self.style is None:
+ self.style = self.choose_scalar_style()
+ split = (not self.simple_key_context)
+ #if self.analysis.multiline and split \
+ # and (not self.style or self.style in '\'\"'):
+ # self.write_indent()
+ if self.style == '"':
+ self.write_double_quoted(self.analysis.scalar, split)
+ elif self.style == '\'':
+ self.write_single_quoted(self.analysis.scalar, split)
+ elif self.style == '>':
+ self.write_folded(self.analysis.scalar)
+ elif self.style == '|':
+ self.write_literal(self.analysis.scalar)
+ else:
+ self.write_plain(self.analysis.scalar, split)
+ self.analysis = None
+ self.style = None
+
+ # Analyzers.
+
+ def prepare_version(self, version):
+ major, minor = version
+ if major != 1:
+ raise EmitterError("unsupported YAML version: %d.%d" % (major, minor))
+ return u'%d.%d' % (major, minor)
+
+ def prepare_tag_handle(self, handle):
+ if not handle:
+ raise EmitterError("tag handle must not be empty")
+ if handle[0] != u'!' or handle[-1] != u'!':
+ raise EmitterError("tag handle must start and end with '!': %r"
+ % (handle.encode('utf-8')))
+ for ch in handle[1:-1]:
+ if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
+ or ch in u'-_'):
+ raise EmitterError("invalid character %r in the tag handle: %r"
+ % (ch.encode('utf-8'), handle.encode('utf-8')))
+ return handle
+
+ def prepare_tag_prefix(self, prefix):
+ if not prefix:
+ raise EmitterError("tag prefix must not be empty")
+ chunks = []
+ start = end = 0
+ if prefix[0] == u'!':
+ end = 1
+ while end < len(prefix):
+ ch = prefix[end]
+ if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
+ or ch in u'-;/?!:@&=+$,_.~*\'()[]':
+ end += 1
+ else:
+ if start < end:
+ chunks.append(prefix[start:end])
+ start = end = end+1
+ data = ch.encode('utf-8')
+ for ch in data:
+ chunks.append(u'%%%02X' % ord(ch))
+ if start < end:
+ chunks.append(prefix[start:end])
+ return u''.join(chunks)
+
+ def prepare_tag(self, tag):
+ if not tag:
+ raise EmitterError("tag must not be empty")
+ if tag == u'!':
+ return tag
+ handle = None
+ suffix = tag
+ prefixes = self.tag_prefixes.keys()
+ prefixes.sort()
+ for prefix in prefixes:
+ if tag.startswith(prefix) \
+ and (prefix == u'!' or len(prefix) < len(tag)):
+ handle = self.tag_prefixes[prefix]
+ suffix = tag[len(prefix):]
+ chunks = []
+ start = end = 0
+ while end < len(suffix):
+ ch = suffix[end]
+ if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
+ or ch in u'-;/?:@&=+$,_.~*\'()[]' \
+ or (ch == u'!' and handle != u'!'):
+ end += 1
+ else:
+ if start < end:
+ chunks.append(suffix[start:end])
+ start = end = end+1
+ data = ch.encode('utf-8')
+ for ch in data:
+ chunks.append(u'%%%02X' % ord(ch))
+ if start < end:
+ chunks.append(suffix[start:end])
+ suffix_text = u''.join(chunks)
+ if handle:
+ return u'%s%s' % (handle, suffix_text)
+ else:
+ return u'!<%s>' % suffix_text
+
+ def prepare_anchor(self, anchor):
+ if not anchor:
+ raise EmitterError("anchor must not be empty")
+ for ch in anchor:
+ if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
+ or ch in u'-_'):
+ raise EmitterError("invalid character %r in the anchor: %r"
+ % (ch.encode('utf-8'), anchor.encode('utf-8')))
+ return anchor
+
+ def analyze_scalar(self, scalar):
+
+ # Empty scalar is a special case.
+ if not scalar:
+ return ScalarAnalysis(scalar=scalar, empty=True, multiline=False,
+ allow_flow_plain=False, allow_block_plain=True,
+ allow_single_quoted=True, allow_double_quoted=True,
+ allow_block=False)
+
+ # Indicators and special characters.
+ block_indicators = False
+ flow_indicators = False
+ line_breaks = False
+ special_characters = False
+
+ # Important whitespace combinations.
+ leading_space = False
+ leading_break = False
+ trailing_space = False
+ trailing_break = False
+ break_space = False
+ space_break = False
+
+ # Check document indicators.
+ if scalar.startswith(u'---') or scalar.startswith(u'...'):
+ block_indicators = True
+ flow_indicators = True
+
+ # First character or preceded by a whitespace.
preceded_by_whitespace = True
-
- # Last character or followed by a whitespace.
- followed_by_whitespace = (len(scalar) == 1 or
- scalar[1] in u'\0 \t\r\n\x85\u2028\u2029')
-
- # The previous character is a space.
- previous_space = False
-
- # The previous character is a break.
- previous_break = False
-
- index = 0
- while index < len(scalar):
- ch = scalar[index]
-
- # Check for indicators.
- if index == 0:
- # Leading indicators are special characters.
+
+ # Last character or followed by a whitespace.
+ followed_by_whitespace = (len(scalar) == 1 or
+ scalar[1] in u'\0 \t\r\n\x85\u2028\u2029')
+
+ # The previous character is a space.
+ previous_space = False
+
+ # The previous character is a break.
+ previous_break = False
+
+ index = 0
+ while index < len(scalar):
+ ch = scalar[index]
+
+ # Check for indicators.
+ if index == 0:
+ # Leading indicators are special characters.
if ch in u'#,[]{}&*!|>\'\"%@`':
- flow_indicators = True
- block_indicators = True
- if ch in u'?:':
- flow_indicators = True
- if followed_by_whitespace:
- block_indicators = True
- if ch == u'-' and followed_by_whitespace:
- flow_indicators = True
- block_indicators = True
- else:
- # Some indicators cannot appear within a scalar as well.
- if ch in u',?[]{}':
- flow_indicators = True
- if ch == u':':
- flow_indicators = True
- if followed_by_whitespace:
- block_indicators = True
+ flow_indicators = True
+ block_indicators = True
+ if ch in u'?:':
+ flow_indicators = True
+ if followed_by_whitespace:
+ block_indicators = True
+ if ch == u'-' and followed_by_whitespace:
+ flow_indicators = True
+ block_indicators = True
+ else:
+ # Some indicators cannot appear within a scalar as well.
+ if ch in u',?[]{}':
+ flow_indicators = True
+ if ch == u':':
+ flow_indicators = True
+ if followed_by_whitespace:
+ block_indicators = True
if ch == u'#' and preceded_by_whitespace:
- flow_indicators = True
- block_indicators = True
-
- # Check for line breaks, special, and unicode characters.
- if ch in u'\n\x85\u2028\u2029':
- line_breaks = True
- if not (ch == u'\n' or u'\x20' <= ch <= u'\x7E'):
- if (ch == u'\x85' or u'\xA0' <= ch <= u'\uD7FF'
+ flow_indicators = True
+ block_indicators = True
+
+ # Check for line breaks, special, and unicode characters.
+ if ch in u'\n\x85\u2028\u2029':
+ line_breaks = True
+ if not (ch == u'\n' or u'\x20' <= ch <= u'\x7E'):
+ if (ch == u'\x85' or u'\xA0' <= ch <= u'\uD7FF'
or u'\uE000' <= ch <= u'\uFFFD'
or (u'\U00010000' <= ch < u'\U0010ffff')) and ch != u'\uFEFF':
- unicode_characters = True
- if not self.allow_unicode:
- special_characters = True
- else:
- special_characters = True
-
- # Detect important whitespace combinations.
- if ch == u' ':
- if index == 0:
- leading_space = True
- if index == len(scalar)-1:
- trailing_space = True
- if previous_break:
- break_space = True
- previous_space = True
- previous_break = False
- elif ch in u'\n\x85\u2028\u2029':
- if index == 0:
- leading_break = True
- if index == len(scalar)-1:
- trailing_break = True
- if previous_space:
- space_break = True
- previous_space = False
- previous_break = True
- else:
- previous_space = False
- previous_break = False
-
- # Prepare for the next character.
- index += 1
+ unicode_characters = True
+ if not self.allow_unicode:
+ special_characters = True
+ else:
+ special_characters = True
+
+ # Detect important whitespace combinations.
+ if ch == u' ':
+ if index == 0:
+ leading_space = True
+ if index == len(scalar)-1:
+ trailing_space = True
+ if previous_break:
+ break_space = True
+ previous_space = True
+ previous_break = False
+ elif ch in u'\n\x85\u2028\u2029':
+ if index == 0:
+ leading_break = True
+ if index == len(scalar)-1:
+ trailing_break = True
+ if previous_space:
+ space_break = True
+ previous_space = False
+ previous_break = True
+ else:
+ previous_space = False
+ previous_break = False
+
+ # Prepare for the next character.
+ index += 1
preceded_by_whitespace = (ch in u'\0 \t\r\n\x85\u2028\u2029')
- followed_by_whitespace = (index+1 >= len(scalar) or
- scalar[index+1] in u'\0 \t\r\n\x85\u2028\u2029')
-
- # Let's decide what styles are allowed.
- allow_flow_plain = True
- allow_block_plain = True
- allow_single_quoted = True
- allow_double_quoted = True
- allow_block = True
-
- # Leading and trailing whitespaces are bad for plain scalars.
- if (leading_space or leading_break
- or trailing_space or trailing_break):
- allow_flow_plain = allow_block_plain = False
-
- # We do not permit trailing spaces for block scalars.
- if trailing_space:
- allow_block = False
-
- # Spaces at the beginning of a new line are only acceptable for block
- # scalars.
- if break_space:
- allow_flow_plain = allow_block_plain = allow_single_quoted = False
-
- # Spaces followed by breaks, as well as special character are only
- # allowed for double quoted scalars.
- if space_break or special_characters:
- allow_flow_plain = allow_block_plain = \
- allow_single_quoted = allow_block = False
-
- # Although the plain scalar writer supports breaks, we never emit
- # multiline plain scalars.
- if line_breaks:
- allow_flow_plain = allow_block_plain = False
-
- # Flow indicators are forbidden for flow plain scalars.
- if flow_indicators:
- allow_flow_plain = False
-
- # Block indicators are forbidden for block plain scalars.
- if block_indicators:
- allow_block_plain = False
-
- return ScalarAnalysis(scalar=scalar,
- empty=False, multiline=line_breaks,
- allow_flow_plain=allow_flow_plain,
- allow_block_plain=allow_block_plain,
- allow_single_quoted=allow_single_quoted,
- allow_double_quoted=allow_double_quoted,
- allow_block=allow_block)
-
- # Writers.
-
- def flush_stream(self):
- if hasattr(self.stream, 'flush'):
- self.stream.flush()
-
- def write_stream_start(self):
- # Write BOM if needed.
- if self.encoding and self.encoding.startswith('utf-16'):
- self.stream.write(u'\uFEFF'.encode(self.encoding))
-
- def write_stream_end(self):
- self.flush_stream()
-
- def write_indicator(self, indicator, need_whitespace,
- whitespace=False, indention=False):
- if self.whitespace or not need_whitespace:
- data = indicator
- else:
- data = u' '+indicator
- self.whitespace = whitespace
- self.indention = self.indention and indention
- self.column += len(data)
- self.open_ended = False
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
-
- def write_indent(self):
- indent = self.indent or 0
- if not self.indention or self.column > indent \
- or (self.column == indent and not self.whitespace):
- self.write_line_break()
- if self.column < indent:
- self.whitespace = True
- data = u' '*(indent-self.column)
- self.column = indent
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
-
- def write_line_break(self, data=None):
- if data is None:
- data = self.best_line_break
- self.whitespace = True
- self.indention = True
- self.line += 1
- self.column = 0
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
-
- def write_version_directive(self, version_text):
- data = u'%%YAML %s' % version_text
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- self.write_line_break()
-
- def write_tag_directive(self, handle_text, prefix_text):
- data = u'%%TAG %s %s' % (handle_text, prefix_text)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- self.write_line_break()
-
- # Scalar streams.
-
- def write_single_quoted(self, text, split=True):
- self.write_indicator(u'\'', True)
- spaces = False
- breaks = False
- start = end = 0
- while end <= len(text):
- ch = None
- if end < len(text):
- ch = text[end]
- if spaces:
- if ch is None or ch != u' ':
- if start+1 == end and self.column > self.best_width and split \
- and start != 0 and end != len(text):
- self.write_indent()
- else:
- data = text[start:end]
- self.column += len(data)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- start = end
- elif breaks:
- if ch is None or ch not in u'\n\x85\u2028\u2029':
- if text[start] == u'\n':
- self.write_line_break()
- for br in text[start:end]:
- if br == u'\n':
- self.write_line_break()
- else:
- self.write_line_break(br)
- self.write_indent()
- start = end
- else:
- if ch is None or ch in u' \n\x85\u2028\u2029' or ch == u'\'':
- if start < end:
- data = text[start:end]
- self.column += len(data)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- start = end
- if ch == u'\'':
- data = u'\'\''
- self.column += 2
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- start = end + 1
- if ch is not None:
- spaces = (ch == u' ')
- breaks = (ch in u'\n\x85\u2028\u2029')
- end += 1
- self.write_indicator(u'\'', False)
-
- ESCAPE_REPLACEMENTS = {
- u'\0': u'0',
- u'\x07': u'a',
- u'\x08': u'b',
- u'\x09': u't',
- u'\x0A': u'n',
- u'\x0B': u'v',
- u'\x0C': u'f',
- u'\x0D': u'r',
- u'\x1B': u'e',
- u'\"': u'\"',
- u'\\': u'\\',
- u'\x85': u'N',
- u'\xA0': u'_',
- u'\u2028': u'L',
- u'\u2029': u'P',
- }
-
- def write_double_quoted(self, text, split=True):
- self.write_indicator(u'"', True)
- start = end = 0
- while end <= len(text):
- ch = None
- if end < len(text):
- ch = text[end]
- if ch is None or ch in u'"\\\x85\u2028\u2029\uFEFF' \
- or not (u'\x20' <= ch <= u'\x7E'
- or (self.allow_unicode
- and (u'\xA0' <= ch <= u'\uD7FF'
- or u'\uE000' <= ch <= u'\uFFFD'))):
- if start < end:
- data = text[start:end]
- self.column += len(data)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- start = end
- if ch is not None:
- if ch in self.ESCAPE_REPLACEMENTS:
- data = u'\\'+self.ESCAPE_REPLACEMENTS[ch]
- elif ch <= u'\xFF':
- data = u'\\x%02X' % ord(ch)
- elif ch <= u'\uFFFF':
- data = u'\\u%04X' % ord(ch)
- else:
- data = u'\\U%08X' % ord(ch)
- self.column += len(data)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- start = end+1
- if 0 < end < len(text)-1 and (ch == u' ' or start >= end) \
- and self.column+(end-start) > self.best_width and split:
- data = text[start:end]+u'\\'
- if start < end:
- start = end
- self.column += len(data)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- self.write_indent()
- self.whitespace = False
- self.indention = False
- if text[start] == u' ':
- data = u'\\'
- self.column += len(data)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- end += 1
- self.write_indicator(u'"', False)
-
- def determine_block_hints(self, text):
- hints = u''
- if text:
- if text[0] in u' \n\x85\u2028\u2029':
- hints += unicode(self.best_indent)
- if text[-1] not in u'\n\x85\u2028\u2029':
- hints += u'-'
- elif len(text) == 1 or text[-2] in u'\n\x85\u2028\u2029':
- hints += u'+'
- return hints
-
- def write_folded(self, text):
- hints = self.determine_block_hints(text)
- self.write_indicator(u'>'+hints, True)
- if hints[-1:] == u'+':
- self.open_ended = True
- self.write_line_break()
- leading_space = True
- spaces = False
- breaks = True
- start = end = 0
- while end <= len(text):
- ch = None
- if end < len(text):
- ch = text[end]
- if breaks:
- if ch is None or ch not in u'\n\x85\u2028\u2029':
- if not leading_space and ch is not None and ch != u' ' \
- and text[start] == u'\n':
- self.write_line_break()
- leading_space = (ch == u' ')
- for br in text[start:end]:
- if br == u'\n':
- self.write_line_break()
- else:
- self.write_line_break(br)
- if ch is not None:
- self.write_indent()
- start = end
- elif spaces:
- if ch != u' ':
- if start+1 == end and self.column > self.best_width:
- self.write_indent()
- else:
- data = text[start:end]
- self.column += len(data)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- start = end
- else:
- if ch is None or ch in u' \n\x85\u2028\u2029':
- data = text[start:end]
- self.column += len(data)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- if ch is None:
- self.write_line_break()
- start = end
- if ch is not None:
- breaks = (ch in u'\n\x85\u2028\u2029')
- spaces = (ch == u' ')
- end += 1
-
- def write_literal(self, text):
- hints = self.determine_block_hints(text)
- self.write_indicator(u'|'+hints, True)
- if hints[-1:] == u'+':
- self.open_ended = True
- self.write_line_break()
- breaks = True
- start = end = 0
- while end <= len(text):
- ch = None
- if end < len(text):
- ch = text[end]
- if breaks:
- if ch is None or ch not in u'\n\x85\u2028\u2029':
- for br in text[start:end]:
- if br == u'\n':
- self.write_line_break()
- else:
- self.write_line_break(br)
- if ch is not None:
- self.write_indent()
- start = end
- else:
- if ch is None or ch in u'\n\x85\u2028\u2029':
- data = text[start:end]
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- if ch is None:
- self.write_line_break()
- start = end
- if ch is not None:
- breaks = (ch in u'\n\x85\u2028\u2029')
- end += 1
-
- def write_plain(self, text, split=True):
- if self.root_context:
- self.open_ended = True
- if not text:
- return
- if not self.whitespace:
- data = u' '
- self.column += len(data)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- self.whitespace = False
- self.indention = False
- spaces = False
- breaks = False
- start = end = 0
- while end <= len(text):
- ch = None
- if end < len(text):
- ch = text[end]
- if spaces:
- if ch != u' ':
- if start+1 == end and self.column > self.best_width and split:
- self.write_indent()
- self.whitespace = False
- self.indention = False
- else:
- data = text[start:end]
- self.column += len(data)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- start = end
- elif breaks:
- if ch not in u'\n\x85\u2028\u2029':
- if text[start] == u'\n':
- self.write_line_break()
- for br in text[start:end]:
- if br == u'\n':
- self.write_line_break()
- else:
- self.write_line_break(br)
- self.write_indent()
- self.whitespace = False
- self.indention = False
- start = end
- else:
- if ch is None or ch in u' \n\x85\u2028\u2029':
- data = text[start:end]
- self.column += len(data)
- if self.encoding:
- data = data.encode(self.encoding)
- self.stream.write(data)
- start = end
- if ch is not None:
- spaces = (ch == u' ')
- breaks = (ch in u'\n\x85\u2028\u2029')
- end += 1
+ followed_by_whitespace = (index+1 >= len(scalar) or
+ scalar[index+1] in u'\0 \t\r\n\x85\u2028\u2029')
+
+ # Let's decide what styles are allowed.
+ allow_flow_plain = True
+ allow_block_plain = True
+ allow_single_quoted = True
+ allow_double_quoted = True
+ allow_block = True
+
+ # Leading and trailing whitespaces are bad for plain scalars.
+ if (leading_space or leading_break
+ or trailing_space or trailing_break):
+ allow_flow_plain = allow_block_plain = False
+
+ # We do not permit trailing spaces for block scalars.
+ if trailing_space:
+ allow_block = False
+
+ # Spaces at the beginning of a new line are only acceptable for block
+ # scalars.
+ if break_space:
+ allow_flow_plain = allow_block_plain = allow_single_quoted = False
+
+ # Spaces followed by breaks, as well as special character are only
+ # allowed for double quoted scalars.
+ if space_break or special_characters:
+ allow_flow_plain = allow_block_plain = \
+ allow_single_quoted = allow_block = False
+
+ # Although the plain scalar writer supports breaks, we never emit
+ # multiline plain scalars.
+ if line_breaks:
+ allow_flow_plain = allow_block_plain = False
+
+ # Flow indicators are forbidden for flow plain scalars.
+ if flow_indicators:
+ allow_flow_plain = False
+
+ # Block indicators are forbidden for block plain scalars.
+ if block_indicators:
+ allow_block_plain = False
+
+ return ScalarAnalysis(scalar=scalar,
+ empty=False, multiline=line_breaks,
+ allow_flow_plain=allow_flow_plain,
+ allow_block_plain=allow_block_plain,
+ allow_single_quoted=allow_single_quoted,
+ allow_double_quoted=allow_double_quoted,
+ allow_block=allow_block)
+
+ # Writers.
+
+ def flush_stream(self):
+ if hasattr(self.stream, 'flush'):
+ self.stream.flush()
+
+ def write_stream_start(self):
+ # Write BOM if needed.
+ if self.encoding and self.encoding.startswith('utf-16'):
+ self.stream.write(u'\uFEFF'.encode(self.encoding))
+
+ def write_stream_end(self):
+ self.flush_stream()
+
+ def write_indicator(self, indicator, need_whitespace,
+ whitespace=False, indention=False):
+ if self.whitespace or not need_whitespace:
+ data = indicator
+ else:
+ data = u' '+indicator
+ self.whitespace = whitespace
+ self.indention = self.indention and indention
+ self.column += len(data)
+ self.open_ended = False
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+
+ def write_indent(self):
+ indent = self.indent or 0
+ if not self.indention or self.column > indent \
+ or (self.column == indent and not self.whitespace):
+ self.write_line_break()
+ if self.column < indent:
+ self.whitespace = True
+ data = u' '*(indent-self.column)
+ self.column = indent
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+
+ def write_line_break(self, data=None):
+ if data is None:
+ data = self.best_line_break
+ self.whitespace = True
+ self.indention = True
+ self.line += 1
+ self.column = 0
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+
+ def write_version_directive(self, version_text):
+ data = u'%%YAML %s' % version_text
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ self.write_line_break()
+
+ def write_tag_directive(self, handle_text, prefix_text):
+ data = u'%%TAG %s %s' % (handle_text, prefix_text)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ self.write_line_break()
+
+ # Scalar streams.
+
+ def write_single_quoted(self, text, split=True):
+ self.write_indicator(u'\'', True)
+ spaces = False
+ breaks = False
+ start = end = 0
+ while end <= len(text):
+ ch = None
+ if end < len(text):
+ ch = text[end]
+ if spaces:
+ if ch is None or ch != u' ':
+ if start+1 == end and self.column > self.best_width and split \
+ and start != 0 and end != len(text):
+ self.write_indent()
+ else:
+ data = text[start:end]
+ self.column += len(data)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ start = end
+ elif breaks:
+ if ch is None or ch not in u'\n\x85\u2028\u2029':
+ if text[start] == u'\n':
+ self.write_line_break()
+ for br in text[start:end]:
+ if br == u'\n':
+ self.write_line_break()
+ else:
+ self.write_line_break(br)
+ self.write_indent()
+ start = end
+ else:
+ if ch is None or ch in u' \n\x85\u2028\u2029' or ch == u'\'':
+ if start < end:
+ data = text[start:end]
+ self.column += len(data)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ start = end
+ if ch == u'\'':
+ data = u'\'\''
+ self.column += 2
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ start = end + 1
+ if ch is not None:
+ spaces = (ch == u' ')
+ breaks = (ch in u'\n\x85\u2028\u2029')
+ end += 1
+ self.write_indicator(u'\'', False)
+
+ ESCAPE_REPLACEMENTS = {
+ u'\0': u'0',
+ u'\x07': u'a',
+ u'\x08': u'b',
+ u'\x09': u't',
+ u'\x0A': u'n',
+ u'\x0B': u'v',
+ u'\x0C': u'f',
+ u'\x0D': u'r',
+ u'\x1B': u'e',
+ u'\"': u'\"',
+ u'\\': u'\\',
+ u'\x85': u'N',
+ u'\xA0': u'_',
+ u'\u2028': u'L',
+ u'\u2029': u'P',
+ }
+
+ def write_double_quoted(self, text, split=True):
+ self.write_indicator(u'"', True)
+ start = end = 0
+ while end <= len(text):
+ ch = None
+ if end < len(text):
+ ch = text[end]
+ if ch is None or ch in u'"\\\x85\u2028\u2029\uFEFF' \
+ or not (u'\x20' <= ch <= u'\x7E'
+ or (self.allow_unicode
+ and (u'\xA0' <= ch <= u'\uD7FF'
+ or u'\uE000' <= ch <= u'\uFFFD'))):
+ if start < end:
+ data = text[start:end]
+ self.column += len(data)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ start = end
+ if ch is not None:
+ if ch in self.ESCAPE_REPLACEMENTS:
+ data = u'\\'+self.ESCAPE_REPLACEMENTS[ch]
+ elif ch <= u'\xFF':
+ data = u'\\x%02X' % ord(ch)
+ elif ch <= u'\uFFFF':
+ data = u'\\u%04X' % ord(ch)
+ else:
+ data = u'\\U%08X' % ord(ch)
+ self.column += len(data)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ start = end+1
+ if 0 < end < len(text)-1 and (ch == u' ' or start >= end) \
+ and self.column+(end-start) > self.best_width and split:
+ data = text[start:end]+u'\\'
+ if start < end:
+ start = end
+ self.column += len(data)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ self.write_indent()
+ self.whitespace = False
+ self.indention = False
+ if text[start] == u' ':
+ data = u'\\'
+ self.column += len(data)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ end += 1
+ self.write_indicator(u'"', False)
+
+ def determine_block_hints(self, text):
+ hints = u''
+ if text:
+ if text[0] in u' \n\x85\u2028\u2029':
+ hints += unicode(self.best_indent)
+ if text[-1] not in u'\n\x85\u2028\u2029':
+ hints += u'-'
+ elif len(text) == 1 or text[-2] in u'\n\x85\u2028\u2029':
+ hints += u'+'
+ return hints
+
+ def write_folded(self, text):
+ hints = self.determine_block_hints(text)
+ self.write_indicator(u'>'+hints, True)
+ if hints[-1:] == u'+':
+ self.open_ended = True
+ self.write_line_break()
+ leading_space = True
+ spaces = False
+ breaks = True
+ start = end = 0
+ while end <= len(text):
+ ch = None
+ if end < len(text):
+ ch = text[end]
+ if breaks:
+ if ch is None or ch not in u'\n\x85\u2028\u2029':
+ if not leading_space and ch is not None and ch != u' ' \
+ and text[start] == u'\n':
+ self.write_line_break()
+ leading_space = (ch == u' ')
+ for br in text[start:end]:
+ if br == u'\n':
+ self.write_line_break()
+ else:
+ self.write_line_break(br)
+ if ch is not None:
+ self.write_indent()
+ start = end
+ elif spaces:
+ if ch != u' ':
+ if start+1 == end and self.column > self.best_width:
+ self.write_indent()
+ else:
+ data = text[start:end]
+ self.column += len(data)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ start = end
+ else:
+ if ch is None or ch in u' \n\x85\u2028\u2029':
+ data = text[start:end]
+ self.column += len(data)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ if ch is None:
+ self.write_line_break()
+ start = end
+ if ch is not None:
+ breaks = (ch in u'\n\x85\u2028\u2029')
+ spaces = (ch == u' ')
+ end += 1
+
+ def write_literal(self, text):
+ hints = self.determine_block_hints(text)
+ self.write_indicator(u'|'+hints, True)
+ if hints[-1:] == u'+':
+ self.open_ended = True
+ self.write_line_break()
+ breaks = True
+ start = end = 0
+ while end <= len(text):
+ ch = None
+ if end < len(text):
+ ch = text[end]
+ if breaks:
+ if ch is None or ch not in u'\n\x85\u2028\u2029':
+ for br in text[start:end]:
+ if br == u'\n':
+ self.write_line_break()
+ else:
+ self.write_line_break(br)
+ if ch is not None:
+ self.write_indent()
+ start = end
+ else:
+ if ch is None or ch in u'\n\x85\u2028\u2029':
+ data = text[start:end]
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ if ch is None:
+ self.write_line_break()
+ start = end
+ if ch is not None:
+ breaks = (ch in u'\n\x85\u2028\u2029')
+ end += 1
+
+ def write_plain(self, text, split=True):
+ if self.root_context:
+ self.open_ended = True
+ if not text:
+ return
+ if not self.whitespace:
+ data = u' '
+ self.column += len(data)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ self.whitespace = False
+ self.indention = False
+ spaces = False
+ breaks = False
+ start = end = 0
+ while end <= len(text):
+ ch = None
+ if end < len(text):
+ ch = text[end]
+ if spaces:
+ if ch != u' ':
+ if start+1 == end and self.column > self.best_width and split:
+ self.write_indent()
+ self.whitespace = False
+ self.indention = False
+ else:
+ data = text[start:end]
+ self.column += len(data)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ start = end
+ elif breaks:
+ if ch not in u'\n\x85\u2028\u2029':
+ if text[start] == u'\n':
+ self.write_line_break()
+ for br in text[start:end]:
+ if br == u'\n':
+ self.write_line_break()
+ else:
+ self.write_line_break(br)
+ self.write_indent()
+ self.whitespace = False
+ self.indention = False
+ start = end
+ else:
+ if ch is None or ch in u' \n\x85\u2028\u2029':
+ data = text[start:end]
+ self.column += len(data)
+ if self.encoding:
+ data = data.encode(self.encoding)
+ self.stream.write(data)
+ start = end
+ if ch is not None:
+ spaces = (ch == u' ')
+ breaks = (ch in u'\n\x85\u2028\u2029')
+ end += 1
diff --git a/contrib/python/PyYAML/py2/yaml/error.py b/contrib/python/PyYAML/py2/yaml/error.py
index 905e265ab1..577686db5f 100644
--- a/contrib/python/PyYAML/py2/yaml/error.py
+++ b/contrib/python/PyYAML/py2/yaml/error.py
@@ -1,75 +1,75 @@
-
-__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError']
-
-class Mark(object):
-
- def __init__(self, name, index, line, column, buffer, pointer):
- self.name = name
- self.index = index
- self.line = line
- self.column = column
- self.buffer = buffer
- self.pointer = pointer
-
- def get_snippet(self, indent=4, max_length=75):
- if self.buffer is None:
- return None
- head = ''
- start = self.pointer
- while start > 0 and self.buffer[start-1] not in u'\0\r\n\x85\u2028\u2029':
- start -= 1
- if self.pointer-start > max_length/2-1:
- head = ' ... '
- start += 5
- break
- tail = ''
- end = self.pointer
- while end < len(self.buffer) and self.buffer[end] not in u'\0\r\n\x85\u2028\u2029':
- end += 1
- if end-self.pointer > max_length/2-1:
- tail = ' ... '
- end -= 5
- break
- snippet = self.buffer[start:end].encode('utf-8')
- return ' '*indent + head + snippet + tail + '\n' \
- + ' '*(indent+self.pointer-start+len(head)) + '^'
-
- def __str__(self):
- snippet = self.get_snippet()
- where = " in \"%s\", line %d, column %d" \
- % (self.name, self.line+1, self.column+1)
- if snippet is not None:
- where += ":\n"+snippet
- return where
-
-class YAMLError(Exception):
- pass
-
-class MarkedYAMLError(YAMLError):
-
- def __init__(self, context=None, context_mark=None,
- problem=None, problem_mark=None, note=None):
- self.context = context
- self.context_mark = context_mark
- self.problem = problem
- self.problem_mark = problem_mark
- self.note = note
-
- def __str__(self):
- lines = []
- if self.context is not None:
- lines.append(self.context)
- if self.context_mark is not None \
- and (self.problem is None or self.problem_mark is None
- or self.context_mark.name != self.problem_mark.name
- or self.context_mark.line != self.problem_mark.line
- or self.context_mark.column != self.problem_mark.column):
- lines.append(str(self.context_mark))
- if self.problem is not None:
- lines.append(self.problem)
- if self.problem_mark is not None:
- lines.append(str(self.problem_mark))
- if self.note is not None:
- lines.append(self.note)
- return '\n'.join(lines)
-
+
+__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError']
+
+class Mark(object):
+
+ def __init__(self, name, index, line, column, buffer, pointer):
+ self.name = name
+ self.index = index
+ self.line = line
+ self.column = column
+ self.buffer = buffer
+ self.pointer = pointer
+
+ def get_snippet(self, indent=4, max_length=75):
+ if self.buffer is None:
+ return None
+ head = ''
+ start = self.pointer
+ while start > 0 and self.buffer[start-1] not in u'\0\r\n\x85\u2028\u2029':
+ start -= 1
+ if self.pointer-start > max_length/2-1:
+ head = ' ... '
+ start += 5
+ break
+ tail = ''
+ end = self.pointer
+ while end < len(self.buffer) and self.buffer[end] not in u'\0\r\n\x85\u2028\u2029':
+ end += 1
+ if end-self.pointer > max_length/2-1:
+ tail = ' ... '
+ end -= 5
+ break
+ snippet = self.buffer[start:end].encode('utf-8')
+ return ' '*indent + head + snippet + tail + '\n' \
+ + ' '*(indent+self.pointer-start+len(head)) + '^'
+
+ def __str__(self):
+ snippet = self.get_snippet()
+ where = " in \"%s\", line %d, column %d" \
+ % (self.name, self.line+1, self.column+1)
+ if snippet is not None:
+ where += ":\n"+snippet
+ return where
+
+class YAMLError(Exception):
+ pass
+
+class MarkedYAMLError(YAMLError):
+
+ def __init__(self, context=None, context_mark=None,
+ problem=None, problem_mark=None, note=None):
+ self.context = context
+ self.context_mark = context_mark
+ self.problem = problem
+ self.problem_mark = problem_mark
+ self.note = note
+
+ def __str__(self):
+ lines = []
+ if self.context is not None:
+ lines.append(self.context)
+ if self.context_mark is not None \
+ and (self.problem is None or self.problem_mark is None
+ or self.context_mark.name != self.problem_mark.name
+ or self.context_mark.line != self.problem_mark.line
+ or self.context_mark.column != self.problem_mark.column):
+ lines.append(str(self.context_mark))
+ if self.problem is not None:
+ lines.append(self.problem)
+ if self.problem_mark is not None:
+ lines.append(str(self.problem_mark))
+ if self.note is not None:
+ lines.append(self.note)
+ return '\n'.join(lines)
+
diff --git a/contrib/python/PyYAML/py2/yaml/events.py b/contrib/python/PyYAML/py2/yaml/events.py
index 6325aedb77..f79ad389cb 100644
--- a/contrib/python/PyYAML/py2/yaml/events.py
+++ b/contrib/python/PyYAML/py2/yaml/events.py
@@ -1,86 +1,86 @@
-
-# Abstract classes.
-
-class Event(object):
- def __init__(self, start_mark=None, end_mark=None):
- self.start_mark = start_mark
- self.end_mark = end_mark
- def __repr__(self):
- attributes = [key for key in ['anchor', 'tag', 'implicit', 'value']
- if hasattr(self, key)]
- arguments = ', '.join(['%s=%r' % (key, getattr(self, key))
- for key in attributes])
- return '%s(%s)' % (self.__class__.__name__, arguments)
-
-class NodeEvent(Event):
- def __init__(self, anchor, start_mark=None, end_mark=None):
- self.anchor = anchor
- self.start_mark = start_mark
- self.end_mark = end_mark
-
-class CollectionStartEvent(NodeEvent):
- def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None,
- flow_style=None):
- self.anchor = anchor
- self.tag = tag
- self.implicit = implicit
- self.start_mark = start_mark
- self.end_mark = end_mark
- self.flow_style = flow_style
-
-class CollectionEndEvent(Event):
- pass
-
-# Implementations.
-
-class StreamStartEvent(Event):
- def __init__(self, start_mark=None, end_mark=None, encoding=None):
- self.start_mark = start_mark
- self.end_mark = end_mark
- self.encoding = encoding
-
-class StreamEndEvent(Event):
- pass
-
-class DocumentStartEvent(Event):
- def __init__(self, start_mark=None, end_mark=None,
- explicit=None, version=None, tags=None):
- self.start_mark = start_mark
- self.end_mark = end_mark
- self.explicit = explicit
- self.version = version
- self.tags = tags
-
-class DocumentEndEvent(Event):
- def __init__(self, start_mark=None, end_mark=None,
- explicit=None):
- self.start_mark = start_mark
- self.end_mark = end_mark
- self.explicit = explicit
-
-class AliasEvent(NodeEvent):
- pass
-
-class ScalarEvent(NodeEvent):
- def __init__(self, anchor, tag, implicit, value,
- start_mark=None, end_mark=None, style=None):
- self.anchor = anchor
- self.tag = tag
- self.implicit = implicit
- self.value = value
- self.start_mark = start_mark
- self.end_mark = end_mark
- self.style = style
-
-class SequenceStartEvent(CollectionStartEvent):
- pass
-
-class SequenceEndEvent(CollectionEndEvent):
- pass
-
-class MappingStartEvent(CollectionStartEvent):
- pass
-
-class MappingEndEvent(CollectionEndEvent):
- pass
-
+
+# Abstract classes.
+
+class Event(object):
+ def __init__(self, start_mark=None, end_mark=None):
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ def __repr__(self):
+ attributes = [key for key in ['anchor', 'tag', 'implicit', 'value']
+ if hasattr(self, key)]
+ arguments = ', '.join(['%s=%r' % (key, getattr(self, key))
+ for key in attributes])
+ return '%s(%s)' % (self.__class__.__name__, arguments)
+
+class NodeEvent(Event):
+ def __init__(self, anchor, start_mark=None, end_mark=None):
+ self.anchor = anchor
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+
+class CollectionStartEvent(NodeEvent):
+ def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None,
+ flow_style=None):
+ self.anchor = anchor
+ self.tag = tag
+ self.implicit = implicit
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ self.flow_style = flow_style
+
+class CollectionEndEvent(Event):
+ pass
+
+# Implementations.
+
+class StreamStartEvent(Event):
+ def __init__(self, start_mark=None, end_mark=None, encoding=None):
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ self.encoding = encoding
+
+class StreamEndEvent(Event):
+ pass
+
+class DocumentStartEvent(Event):
+ def __init__(self, start_mark=None, end_mark=None,
+ explicit=None, version=None, tags=None):
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ self.explicit = explicit
+ self.version = version
+ self.tags = tags
+
+class DocumentEndEvent(Event):
+ def __init__(self, start_mark=None, end_mark=None,
+ explicit=None):
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ self.explicit = explicit
+
+class AliasEvent(NodeEvent):
+ pass
+
+class ScalarEvent(NodeEvent):
+ def __init__(self, anchor, tag, implicit, value,
+ start_mark=None, end_mark=None, style=None):
+ self.anchor = anchor
+ self.tag = tag
+ self.implicit = implicit
+ self.value = value
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ self.style = style
+
+class SequenceStartEvent(CollectionStartEvent):
+ pass
+
+class SequenceEndEvent(CollectionEndEvent):
+ pass
+
+class MappingStartEvent(CollectionStartEvent):
+ pass
+
+class MappingEndEvent(CollectionEndEvent):
+ pass
+
diff --git a/contrib/python/PyYAML/py2/yaml/loader.py b/contrib/python/PyYAML/py2/yaml/loader.py
index 5ffedac258..4d773c3cc1 100644
--- a/contrib/python/PyYAML/py2/yaml/loader.py
+++ b/contrib/python/PyYAML/py2/yaml/loader.py
@@ -1,23 +1,23 @@
-
+
__all__ = ['BaseLoader', 'FullLoader', 'SafeLoader', 'Loader', 'UnsafeLoader']
-
-from reader import *
-from scanner import *
-from parser import *
-from composer import *
-from constructor import *
-from resolver import *
-
-class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver):
-
- def __init__(self, stream):
- Reader.__init__(self, stream)
- Scanner.__init__(self)
- Parser.__init__(self)
- Composer.__init__(self)
- BaseConstructor.__init__(self)
- BaseResolver.__init__(self)
-
+
+from reader import *
+from scanner import *
+from parser import *
+from composer import *
+from constructor import *
+from resolver import *
+
+class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver):
+
+ def __init__(self, stream):
+ Reader.__init__(self, stream)
+ Scanner.__init__(self)
+ Parser.__init__(self)
+ Composer.__init__(self)
+ BaseConstructor.__init__(self)
+ BaseResolver.__init__(self)
+
class FullLoader(Reader, Scanner, Parser, Composer, FullConstructor, Resolver):
def __init__(self, stream):
@@ -28,26 +28,26 @@ class FullLoader(Reader, Scanner, Parser, Composer, FullConstructor, Resolver):
FullConstructor.__init__(self)
Resolver.__init__(self)
-class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver):
-
- def __init__(self, stream):
- Reader.__init__(self, stream)
- Scanner.__init__(self)
- Parser.__init__(self)
- Composer.__init__(self)
- SafeConstructor.__init__(self)
- Resolver.__init__(self)
-
-class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
-
- def __init__(self, stream):
- Reader.__init__(self, stream)
- Scanner.__init__(self)
- Parser.__init__(self)
- Composer.__init__(self)
- Constructor.__init__(self)
- Resolver.__init__(self)
-
+class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver):
+
+ def __init__(self, stream):
+ Reader.__init__(self, stream)
+ Scanner.__init__(self)
+ Parser.__init__(self)
+ Composer.__init__(self)
+ SafeConstructor.__init__(self)
+ Resolver.__init__(self)
+
+class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
+
+ def __init__(self, stream):
+ Reader.__init__(self, stream)
+ Scanner.__init__(self)
+ Parser.__init__(self)
+ Composer.__init__(self)
+ Constructor.__init__(self)
+ Resolver.__init__(self)
+
# UnsafeLoader is the same as Loader (which is and was always unsafe on
# untrusted input). Use of either Loader or UnsafeLoader should be rare, since
# FullLoad should be able to load almost all YAML safely. Loader is left intact
diff --git a/contrib/python/PyYAML/py2/yaml/nodes.py b/contrib/python/PyYAML/py2/yaml/nodes.py
index a7858b88e1..c4f070c41e 100644
--- a/contrib/python/PyYAML/py2/yaml/nodes.py
+++ b/contrib/python/PyYAML/py2/yaml/nodes.py
@@ -1,49 +1,49 @@
-
-class Node(object):
- def __init__(self, tag, value, start_mark, end_mark):
- self.tag = tag
- self.value = value
- self.start_mark = start_mark
- self.end_mark = end_mark
- def __repr__(self):
- value = self.value
- #if isinstance(value, list):
- # if len(value) == 0:
- # value = '<empty>'
- # elif len(value) == 1:
- # value = '<1 item>'
- # else:
- # value = '<%d items>' % len(value)
- #else:
- # if len(value) > 75:
- # value = repr(value[:70]+u' ... ')
- # else:
- # value = repr(value)
- value = repr(value)
- return '%s(tag=%r, value=%s)' % (self.__class__.__name__, self.tag, value)
-
-class ScalarNode(Node):
- id = 'scalar'
- def __init__(self, tag, value,
- start_mark=None, end_mark=None, style=None):
- self.tag = tag
- self.value = value
- self.start_mark = start_mark
- self.end_mark = end_mark
- self.style = style
-
-class CollectionNode(Node):
- def __init__(self, tag, value,
- start_mark=None, end_mark=None, flow_style=None):
- self.tag = tag
- self.value = value
- self.start_mark = start_mark
- self.end_mark = end_mark
- self.flow_style = flow_style
-
-class SequenceNode(CollectionNode):
- id = 'sequence'
-
-class MappingNode(CollectionNode):
- id = 'mapping'
-
+
+class Node(object):
+ def __init__(self, tag, value, start_mark, end_mark):
+ self.tag = tag
+ self.value = value
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ def __repr__(self):
+ value = self.value
+ #if isinstance(value, list):
+ # if len(value) == 0:
+ # value = '<empty>'
+ # elif len(value) == 1:
+ # value = '<1 item>'
+ # else:
+ # value = '<%d items>' % len(value)
+ #else:
+ # if len(value) > 75:
+ # value = repr(value[:70]+u' ... ')
+ # else:
+ # value = repr(value)
+ value = repr(value)
+ return '%s(tag=%r, value=%s)' % (self.__class__.__name__, self.tag, value)
+
+class ScalarNode(Node):
+ id = 'scalar'
+ def __init__(self, tag, value,
+ start_mark=None, end_mark=None, style=None):
+ self.tag = tag
+ self.value = value
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ self.style = style
+
+class CollectionNode(Node):
+ def __init__(self, tag, value,
+ start_mark=None, end_mark=None, flow_style=None):
+ self.tag = tag
+ self.value = value
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ self.flow_style = flow_style
+
+class SequenceNode(CollectionNode):
+ id = 'sequence'
+
+class MappingNode(CollectionNode):
+ id = 'mapping'
+
diff --git a/contrib/python/PyYAML/py2/yaml/parser.py b/contrib/python/PyYAML/py2/yaml/parser.py
index 3e7deb45f4..f9e3057f33 100644
--- a/contrib/python/PyYAML/py2/yaml/parser.py
+++ b/contrib/python/PyYAML/py2/yaml/parser.py
@@ -1,589 +1,589 @@
-
-# The following YAML grammar is LL(1) and is parsed by a recursive descent
-# parser.
-#
-# stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
-# implicit_document ::= block_node DOCUMENT-END*
-# explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
-# block_node_or_indentless_sequence ::=
-# ALIAS
-# | properties (block_content | indentless_block_sequence)?
-# | block_content
-# | indentless_block_sequence
-# block_node ::= ALIAS
-# | properties block_content?
-# | block_content
-# flow_node ::= ALIAS
-# | properties flow_content?
-# | flow_content
-# properties ::= TAG ANCHOR? | ANCHOR TAG?
-# block_content ::= block_collection | flow_collection | SCALAR
-# flow_content ::= flow_collection | SCALAR
-# block_collection ::= block_sequence | block_mapping
-# flow_collection ::= flow_sequence | flow_mapping
-# block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
-# indentless_sequence ::= (BLOCK-ENTRY block_node?)+
-# block_mapping ::= BLOCK-MAPPING_START
-# ((KEY block_node_or_indentless_sequence?)?
-# (VALUE block_node_or_indentless_sequence?)?)*
-# BLOCK-END
-# flow_sequence ::= FLOW-SEQUENCE-START
-# (flow_sequence_entry FLOW-ENTRY)*
-# flow_sequence_entry?
-# FLOW-SEQUENCE-END
-# flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
-# flow_mapping ::= FLOW-MAPPING-START
-# (flow_mapping_entry FLOW-ENTRY)*
-# flow_mapping_entry?
-# FLOW-MAPPING-END
-# flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
-#
-# FIRST sets:
-#
-# stream: { STREAM-START }
-# explicit_document: { DIRECTIVE DOCUMENT-START }
-# implicit_document: FIRST(block_node)
-# block_node: { ALIAS TAG ANCHOR SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START }
-# flow_node: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START }
-# block_content: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }
-# flow_content: { FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }
-# block_collection: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START }
-# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }
-# block_sequence: { BLOCK-SEQUENCE-START }
-# block_mapping: { BLOCK-MAPPING-START }
-# block_node_or_indentless_sequence: { ALIAS ANCHOR TAG SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START BLOCK-ENTRY }
-# indentless_sequence: { ENTRY }
-# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }
-# flow_sequence: { FLOW-SEQUENCE-START }
-# flow_mapping: { FLOW-MAPPING-START }
-# flow_sequence_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }
-# flow_mapping_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }
-
-__all__ = ['Parser', 'ParserError']
-
-from error import MarkedYAMLError
-from tokens import *
-from events import *
-from scanner import *
-
-class ParserError(MarkedYAMLError):
- pass
-
-class Parser(object):
- # Since writing a recursive-descendant parser is a straightforward task, we
- # do not give many comments here.
-
- DEFAULT_TAGS = {
- u'!': u'!',
- u'!!': u'tag:yaml.org,2002:',
- }
-
- def __init__(self):
- self.current_event = None
- self.yaml_version = None
- self.tag_handles = {}
- self.states = []
- self.marks = []
- self.state = self.parse_stream_start
-
- def dispose(self):
- # Reset the state attributes (to clear self-references)
- self.states = []
- self.state = None
-
- def check_event(self, *choices):
- # Check the type of the next event.
- if self.current_event is None:
- if self.state:
- self.current_event = self.state()
- if self.current_event is not None:
- if not choices:
- return True
- for choice in choices:
- if isinstance(self.current_event, choice):
- return True
- return False
-
- def peek_event(self):
- # Get the next event.
- if self.current_event is None:
- if self.state:
- self.current_event = self.state()
- return self.current_event
-
- def get_event(self):
- # Get the next event and proceed further.
- if self.current_event is None:
- if self.state:
- self.current_event = self.state()
- value = self.current_event
- self.current_event = None
- return value
-
- # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
- # implicit_document ::= block_node DOCUMENT-END*
- # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
-
- def parse_stream_start(self):
-
- # Parse the stream start.
- token = self.get_token()
- event = StreamStartEvent(token.start_mark, token.end_mark,
- encoding=token.encoding)
-
- # Prepare the next state.
- self.state = self.parse_implicit_document_start
-
- return event
-
- def parse_implicit_document_start(self):
-
- # Parse an implicit document.
- if not self.check_token(DirectiveToken, DocumentStartToken,
- StreamEndToken):
- self.tag_handles = self.DEFAULT_TAGS
- token = self.peek_token()
- start_mark = end_mark = token.start_mark
- event = DocumentStartEvent(start_mark, end_mark,
- explicit=False)
-
- # Prepare the next state.
- self.states.append(self.parse_document_end)
- self.state = self.parse_block_node
-
- return event
-
- else:
- return self.parse_document_start()
-
- def parse_document_start(self):
-
- # Parse any extra document end indicators.
- while self.check_token(DocumentEndToken):
- self.get_token()
-
- # Parse an explicit document.
- if not self.check_token(StreamEndToken):
- token = self.peek_token()
- start_mark = token.start_mark
- version, tags = self.process_directives()
- if not self.check_token(DocumentStartToken):
- raise ParserError(None, None,
- "expected '<document start>', but found %r"
- % self.peek_token().id,
- self.peek_token().start_mark)
- token = self.get_token()
- end_mark = token.end_mark
- event = DocumentStartEvent(start_mark, end_mark,
- explicit=True, version=version, tags=tags)
- self.states.append(self.parse_document_end)
- self.state = self.parse_document_content
- else:
- # Parse the end of the stream.
- token = self.get_token()
- event = StreamEndEvent(token.start_mark, token.end_mark)
- assert not self.states
- assert not self.marks
- self.state = None
- return event
-
- def parse_document_end(self):
-
- # Parse the document end.
- token = self.peek_token()
- start_mark = end_mark = token.start_mark
- explicit = False
- if self.check_token(DocumentEndToken):
- token = self.get_token()
- end_mark = token.end_mark
- explicit = True
- event = DocumentEndEvent(start_mark, end_mark,
- explicit=explicit)
-
- # Prepare the next state.
- self.state = self.parse_document_start
-
- return event
-
- def parse_document_content(self):
- if self.check_token(DirectiveToken,
- DocumentStartToken, DocumentEndToken, StreamEndToken):
- event = self.process_empty_scalar(self.peek_token().start_mark)
- self.state = self.states.pop()
- return event
- else:
- return self.parse_block_node()
-
- def process_directives(self):
- self.yaml_version = None
- self.tag_handles = {}
- while self.check_token(DirectiveToken):
- token = self.get_token()
- if token.name == u'YAML':
- if self.yaml_version is not None:
- raise ParserError(None, None,
- "found duplicate YAML directive", token.start_mark)
- major, minor = token.value
- if major != 1:
- raise ParserError(None, None,
- "found incompatible YAML document (version 1.* is required)",
- token.start_mark)
- self.yaml_version = token.value
- elif token.name == u'TAG':
- handle, prefix = token.value
- if handle in self.tag_handles:
- raise ParserError(None, None,
- "duplicate tag handle %r" % handle.encode('utf-8'),
- token.start_mark)
- self.tag_handles[handle] = prefix
- if self.tag_handles:
- value = self.yaml_version, self.tag_handles.copy()
- else:
- value = self.yaml_version, None
- for key in self.DEFAULT_TAGS:
- if key not in self.tag_handles:
- self.tag_handles[key] = self.DEFAULT_TAGS[key]
- return value
-
- # block_node_or_indentless_sequence ::= ALIAS
- # | properties (block_content | indentless_block_sequence)?
- # | block_content
- # | indentless_block_sequence
- # block_node ::= ALIAS
- # | properties block_content?
- # | block_content
- # flow_node ::= ALIAS
- # | properties flow_content?
- # | flow_content
- # properties ::= TAG ANCHOR? | ANCHOR TAG?
- # block_content ::= block_collection | flow_collection | SCALAR
- # flow_content ::= flow_collection | SCALAR
- # block_collection ::= block_sequence | block_mapping
- # flow_collection ::= flow_sequence | flow_mapping
-
- def parse_block_node(self):
- return self.parse_node(block=True)
-
- def parse_flow_node(self):
- return self.parse_node()
-
- def parse_block_node_or_indentless_sequence(self):
- return self.parse_node(block=True, indentless_sequence=True)
-
- def parse_node(self, block=False, indentless_sequence=False):
- if self.check_token(AliasToken):
- token = self.get_token()
- event = AliasEvent(token.value, token.start_mark, token.end_mark)
- self.state = self.states.pop()
- else:
- anchor = None
- tag = None
- start_mark = end_mark = tag_mark = None
- if self.check_token(AnchorToken):
- token = self.get_token()
- start_mark = token.start_mark
- end_mark = token.end_mark
- anchor = token.value
- if self.check_token(TagToken):
- token = self.get_token()
- tag_mark = token.start_mark
- end_mark = token.end_mark
- tag = token.value
- elif self.check_token(TagToken):
- token = self.get_token()
- start_mark = tag_mark = token.start_mark
- end_mark = token.end_mark
- tag = token.value
- if self.check_token(AnchorToken):
- token = self.get_token()
- end_mark = token.end_mark
- anchor = token.value
- if tag is not None:
- handle, suffix = tag
- if handle is not None:
- if handle not in self.tag_handles:
- raise ParserError("while parsing a node", start_mark,
- "found undefined tag handle %r" % handle.encode('utf-8'),
- tag_mark)
- tag = self.tag_handles[handle]+suffix
- else:
- tag = suffix
- #if tag == u'!':
- # raise ParserError("while parsing a node", start_mark,
- # "found non-specific tag '!'", tag_mark,
- # "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.")
- if start_mark is None:
- start_mark = end_mark = self.peek_token().start_mark
- event = None
- implicit = (tag is None or tag == u'!')
- if indentless_sequence and self.check_token(BlockEntryToken):
- end_mark = self.peek_token().end_mark
- event = SequenceStartEvent(anchor, tag, implicit,
- start_mark, end_mark)
- self.state = self.parse_indentless_sequence_entry
- else:
- if self.check_token(ScalarToken):
- token = self.get_token()
- end_mark = token.end_mark
- if (token.plain and tag is None) or tag == u'!':
- implicit = (True, False)
- elif tag is None:
- implicit = (False, True)
- else:
- implicit = (False, False)
- event = ScalarEvent(anchor, tag, implicit, token.value,
- start_mark, end_mark, style=token.style)
- self.state = self.states.pop()
- elif self.check_token(FlowSequenceStartToken):
- end_mark = self.peek_token().end_mark
- event = SequenceStartEvent(anchor, tag, implicit,
- start_mark, end_mark, flow_style=True)
- self.state = self.parse_flow_sequence_first_entry
- elif self.check_token(FlowMappingStartToken):
- end_mark = self.peek_token().end_mark
- event = MappingStartEvent(anchor, tag, implicit,
- start_mark, end_mark, flow_style=True)
- self.state = self.parse_flow_mapping_first_key
- elif block and self.check_token(BlockSequenceStartToken):
- end_mark = self.peek_token().start_mark
- event = SequenceStartEvent(anchor, tag, implicit,
- start_mark, end_mark, flow_style=False)
- self.state = self.parse_block_sequence_first_entry
- elif block and self.check_token(BlockMappingStartToken):
- end_mark = self.peek_token().start_mark
- event = MappingStartEvent(anchor, tag, implicit,
- start_mark, end_mark, flow_style=False)
- self.state = self.parse_block_mapping_first_key
- elif anchor is not None or tag is not None:
- # Empty scalars are allowed even if a tag or an anchor is
- # specified.
- event = ScalarEvent(anchor, tag, (implicit, False), u'',
- start_mark, end_mark)
- self.state = self.states.pop()
- else:
- if block:
- node = 'block'
- else:
- node = 'flow'
- token = self.peek_token()
- raise ParserError("while parsing a %s node" % node, start_mark,
- "expected the node content, but found %r" % token.id,
- token.start_mark)
- return event
-
- # block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
-
- def parse_block_sequence_first_entry(self):
- token = self.get_token()
- self.marks.append(token.start_mark)
- return self.parse_block_sequence_entry()
-
- def parse_block_sequence_entry(self):
- if self.check_token(BlockEntryToken):
- token = self.get_token()
- if not self.check_token(BlockEntryToken, BlockEndToken):
- self.states.append(self.parse_block_sequence_entry)
- return self.parse_block_node()
- else:
- self.state = self.parse_block_sequence_entry
- return self.process_empty_scalar(token.end_mark)
- if not self.check_token(BlockEndToken):
- token = self.peek_token()
- raise ParserError("while parsing a block collection", self.marks[-1],
- "expected <block end>, but found %r" % token.id, token.start_mark)
- token = self.get_token()
- event = SequenceEndEvent(token.start_mark, token.end_mark)
- self.state = self.states.pop()
- self.marks.pop()
- return event
-
- # indentless_sequence ::= (BLOCK-ENTRY block_node?)+
-
- def parse_indentless_sequence_entry(self):
- if self.check_token(BlockEntryToken):
- token = self.get_token()
- if not self.check_token(BlockEntryToken,
- KeyToken, ValueToken, BlockEndToken):
- self.states.append(self.parse_indentless_sequence_entry)
- return self.parse_block_node()
- else:
- self.state = self.parse_indentless_sequence_entry
- return self.process_empty_scalar(token.end_mark)
- token = self.peek_token()
- event = SequenceEndEvent(token.start_mark, token.start_mark)
- self.state = self.states.pop()
- return event
-
- # block_mapping ::= BLOCK-MAPPING_START
- # ((KEY block_node_or_indentless_sequence?)?
- # (VALUE block_node_or_indentless_sequence?)?)*
- # BLOCK-END
-
- def parse_block_mapping_first_key(self):
- token = self.get_token()
- self.marks.append(token.start_mark)
- return self.parse_block_mapping_key()
-
- def parse_block_mapping_key(self):
- if self.check_token(KeyToken):
- token = self.get_token()
- if not self.check_token(KeyToken, ValueToken, BlockEndToken):
- self.states.append(self.parse_block_mapping_value)
- return self.parse_block_node_or_indentless_sequence()
- else:
- self.state = self.parse_block_mapping_value
- return self.process_empty_scalar(token.end_mark)
- if not self.check_token(BlockEndToken):
- token = self.peek_token()
- raise ParserError("while parsing a block mapping", self.marks[-1],
- "expected <block end>, but found %r" % token.id, token.start_mark)
- token = self.get_token()
- event = MappingEndEvent(token.start_mark, token.end_mark)
- self.state = self.states.pop()
- self.marks.pop()
- return event
-
- def parse_block_mapping_value(self):
- if self.check_token(ValueToken):
- token = self.get_token()
- if not self.check_token(KeyToken, ValueToken, BlockEndToken):
- self.states.append(self.parse_block_mapping_key)
- return self.parse_block_node_or_indentless_sequence()
- else:
- self.state = self.parse_block_mapping_key
- return self.process_empty_scalar(token.end_mark)
- else:
- self.state = self.parse_block_mapping_key
- token = self.peek_token()
- return self.process_empty_scalar(token.start_mark)
-
- # flow_sequence ::= FLOW-SEQUENCE-START
- # (flow_sequence_entry FLOW-ENTRY)*
- # flow_sequence_entry?
- # FLOW-SEQUENCE-END
- # flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
- #
- # Note that while production rules for both flow_sequence_entry and
- # flow_mapping_entry are equal, their interpretations are different.
- # For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?`
- # generate an inline mapping (set syntax).
-
- def parse_flow_sequence_first_entry(self):
- token = self.get_token()
- self.marks.append(token.start_mark)
- return self.parse_flow_sequence_entry(first=True)
-
- def parse_flow_sequence_entry(self, first=False):
- if not self.check_token(FlowSequenceEndToken):
- if not first:
- if self.check_token(FlowEntryToken):
- self.get_token()
- else:
- token = self.peek_token()
- raise ParserError("while parsing a flow sequence", self.marks[-1],
- "expected ',' or ']', but got %r" % token.id, token.start_mark)
-
- if self.check_token(KeyToken):
- token = self.peek_token()
- event = MappingStartEvent(None, None, True,
- token.start_mark, token.end_mark,
- flow_style=True)
- self.state = self.parse_flow_sequence_entry_mapping_key
- return event
- elif not self.check_token(FlowSequenceEndToken):
- self.states.append(self.parse_flow_sequence_entry)
- return self.parse_flow_node()
- token = self.get_token()
- event = SequenceEndEvent(token.start_mark, token.end_mark)
- self.state = self.states.pop()
- self.marks.pop()
- return event
-
- def parse_flow_sequence_entry_mapping_key(self):
- token = self.get_token()
- if not self.check_token(ValueToken,
- FlowEntryToken, FlowSequenceEndToken):
- self.states.append(self.parse_flow_sequence_entry_mapping_value)
- return self.parse_flow_node()
- else:
- self.state = self.parse_flow_sequence_entry_mapping_value
- return self.process_empty_scalar(token.end_mark)
-
- def parse_flow_sequence_entry_mapping_value(self):
- if self.check_token(ValueToken):
- token = self.get_token()
- if not self.check_token(FlowEntryToken, FlowSequenceEndToken):
- self.states.append(self.parse_flow_sequence_entry_mapping_end)
- return self.parse_flow_node()
- else:
- self.state = self.parse_flow_sequence_entry_mapping_end
- return self.process_empty_scalar(token.end_mark)
- else:
- self.state = self.parse_flow_sequence_entry_mapping_end
- token = self.peek_token()
- return self.process_empty_scalar(token.start_mark)
-
- def parse_flow_sequence_entry_mapping_end(self):
- self.state = self.parse_flow_sequence_entry
- token = self.peek_token()
- return MappingEndEvent(token.start_mark, token.start_mark)
-
- # flow_mapping ::= FLOW-MAPPING-START
- # (flow_mapping_entry FLOW-ENTRY)*
- # flow_mapping_entry?
- # FLOW-MAPPING-END
- # flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
-
- def parse_flow_mapping_first_key(self):
- token = self.get_token()
- self.marks.append(token.start_mark)
- return self.parse_flow_mapping_key(first=True)
-
- def parse_flow_mapping_key(self, first=False):
- if not self.check_token(FlowMappingEndToken):
- if not first:
- if self.check_token(FlowEntryToken):
- self.get_token()
- else:
- token = self.peek_token()
- raise ParserError("while parsing a flow mapping", self.marks[-1],
- "expected ',' or '}', but got %r" % token.id, token.start_mark)
- if self.check_token(KeyToken):
- token = self.get_token()
- if not self.check_token(ValueToken,
- FlowEntryToken, FlowMappingEndToken):
- self.states.append(self.parse_flow_mapping_value)
- return self.parse_flow_node()
- else:
- self.state = self.parse_flow_mapping_value
- return self.process_empty_scalar(token.end_mark)
- elif not self.check_token(FlowMappingEndToken):
- self.states.append(self.parse_flow_mapping_empty_value)
- return self.parse_flow_node()
- token = self.get_token()
- event = MappingEndEvent(token.start_mark, token.end_mark)
- self.state = self.states.pop()
- self.marks.pop()
- return event
-
- def parse_flow_mapping_value(self):
- if self.check_token(ValueToken):
- token = self.get_token()
- if not self.check_token(FlowEntryToken, FlowMappingEndToken):
- self.states.append(self.parse_flow_mapping_key)
- return self.parse_flow_node()
- else:
- self.state = self.parse_flow_mapping_key
- return self.process_empty_scalar(token.end_mark)
- else:
- self.state = self.parse_flow_mapping_key
- token = self.peek_token()
- return self.process_empty_scalar(token.start_mark)
-
- def parse_flow_mapping_empty_value(self):
- self.state = self.parse_flow_mapping_key
- return self.process_empty_scalar(self.peek_token().start_mark)
-
- def process_empty_scalar(self, mark):
- return ScalarEvent(None, None, (True, False), u'', mark, mark)
-
+
+# The following YAML grammar is LL(1) and is parsed by a recursive descent
+# parser.
+#
+# stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
+# implicit_document ::= block_node DOCUMENT-END*
+# explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
+# block_node_or_indentless_sequence ::=
+# ALIAS
+# | properties (block_content | indentless_block_sequence)?
+# | block_content
+# | indentless_block_sequence
+# block_node ::= ALIAS
+# | properties block_content?
+# | block_content
+# flow_node ::= ALIAS
+# | properties flow_content?
+# | flow_content
+# properties ::= TAG ANCHOR? | ANCHOR TAG?
+# block_content ::= block_collection | flow_collection | SCALAR
+# flow_content ::= flow_collection | SCALAR
+# block_collection ::= block_sequence | block_mapping
+# flow_collection ::= flow_sequence | flow_mapping
+# block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
+# indentless_sequence ::= (BLOCK-ENTRY block_node?)+
+# block_mapping ::= BLOCK-MAPPING_START
+# ((KEY block_node_or_indentless_sequence?)?
+# (VALUE block_node_or_indentless_sequence?)?)*
+# BLOCK-END
+# flow_sequence ::= FLOW-SEQUENCE-START
+# (flow_sequence_entry FLOW-ENTRY)*
+# flow_sequence_entry?
+# FLOW-SEQUENCE-END
+# flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+# flow_mapping ::= FLOW-MAPPING-START
+# (flow_mapping_entry FLOW-ENTRY)*
+# flow_mapping_entry?
+# FLOW-MAPPING-END
+# flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+#
+# FIRST sets:
+#
+# stream: { STREAM-START }
+# explicit_document: { DIRECTIVE DOCUMENT-START }
+# implicit_document: FIRST(block_node)
+# block_node: { ALIAS TAG ANCHOR SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START }
+# flow_node: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START }
+# block_content: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }
+# flow_content: { FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }
+# block_collection: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START }
+# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }
+# block_sequence: { BLOCK-SEQUENCE-START }
+# block_mapping: { BLOCK-MAPPING-START }
+# block_node_or_indentless_sequence: { ALIAS ANCHOR TAG SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START BLOCK-ENTRY }
+# indentless_sequence: { ENTRY }
+# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }
+# flow_sequence: { FLOW-SEQUENCE-START }
+# flow_mapping: { FLOW-MAPPING-START }
+# flow_sequence_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }
+# flow_mapping_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }
+
+__all__ = ['Parser', 'ParserError']
+
+from error import MarkedYAMLError
+from tokens import *
+from events import *
+from scanner import *
+
+class ParserError(MarkedYAMLError):
+ pass
+
+class Parser(object):
+ # Since writing a recursive-descendant parser is a straightforward task, we
+ # do not give many comments here.
+
+ DEFAULT_TAGS = {
+ u'!': u'!',
+ u'!!': u'tag:yaml.org,2002:',
+ }
+
+ def __init__(self):
+ self.current_event = None
+ self.yaml_version = None
+ self.tag_handles = {}
+ self.states = []
+ self.marks = []
+ self.state = self.parse_stream_start
+
+ def dispose(self):
+ # Reset the state attributes (to clear self-references)
+ self.states = []
+ self.state = None
+
+ def check_event(self, *choices):
+ # Check the type of the next event.
+ if self.current_event is None:
+ if self.state:
+ self.current_event = self.state()
+ if self.current_event is not None:
+ if not choices:
+ return True
+ for choice in choices:
+ if isinstance(self.current_event, choice):
+ return True
+ return False
+
+ def peek_event(self):
+ # Get the next event.
+ if self.current_event is None:
+ if self.state:
+ self.current_event = self.state()
+ return self.current_event
+
+ def get_event(self):
+ # Get the next event and proceed further.
+ if self.current_event is None:
+ if self.state:
+ self.current_event = self.state()
+ value = self.current_event
+ self.current_event = None
+ return value
+
+ # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
+ # implicit_document ::= block_node DOCUMENT-END*
+ # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
+
+ def parse_stream_start(self):
+
+ # Parse the stream start.
+ token = self.get_token()
+ event = StreamStartEvent(token.start_mark, token.end_mark,
+ encoding=token.encoding)
+
+ # Prepare the next state.
+ self.state = self.parse_implicit_document_start
+
+ return event
+
+ def parse_implicit_document_start(self):
+
+ # Parse an implicit document.
+ if not self.check_token(DirectiveToken, DocumentStartToken,
+ StreamEndToken):
+ self.tag_handles = self.DEFAULT_TAGS
+ token = self.peek_token()
+ start_mark = end_mark = token.start_mark
+ event = DocumentStartEvent(start_mark, end_mark,
+ explicit=False)
+
+ # Prepare the next state.
+ self.states.append(self.parse_document_end)
+ self.state = self.parse_block_node
+
+ return event
+
+ else:
+ return self.parse_document_start()
+
+ def parse_document_start(self):
+
+ # Parse any extra document end indicators.
+ while self.check_token(DocumentEndToken):
+ self.get_token()
+
+ # Parse an explicit document.
+ if not self.check_token(StreamEndToken):
+ token = self.peek_token()
+ start_mark = token.start_mark
+ version, tags = self.process_directives()
+ if not self.check_token(DocumentStartToken):
+ raise ParserError(None, None,
+ "expected '<document start>', but found %r"
+ % self.peek_token().id,
+ self.peek_token().start_mark)
+ token = self.get_token()
+ end_mark = token.end_mark
+ event = DocumentStartEvent(start_mark, end_mark,
+ explicit=True, version=version, tags=tags)
+ self.states.append(self.parse_document_end)
+ self.state = self.parse_document_content
+ else:
+ # Parse the end of the stream.
+ token = self.get_token()
+ event = StreamEndEvent(token.start_mark, token.end_mark)
+ assert not self.states
+ assert not self.marks
+ self.state = None
+ return event
+
+ def parse_document_end(self):
+
+ # Parse the document end.
+ token = self.peek_token()
+ start_mark = end_mark = token.start_mark
+ explicit = False
+ if self.check_token(DocumentEndToken):
+ token = self.get_token()
+ end_mark = token.end_mark
+ explicit = True
+ event = DocumentEndEvent(start_mark, end_mark,
+ explicit=explicit)
+
+ # Prepare the next state.
+ self.state = self.parse_document_start
+
+ return event
+
+ def parse_document_content(self):
+ if self.check_token(DirectiveToken,
+ DocumentStartToken, DocumentEndToken, StreamEndToken):
+ event = self.process_empty_scalar(self.peek_token().start_mark)
+ self.state = self.states.pop()
+ return event
+ else:
+ return self.parse_block_node()
+
+ def process_directives(self):
+ self.yaml_version = None
+ self.tag_handles = {}
+ while self.check_token(DirectiveToken):
+ token = self.get_token()
+ if token.name == u'YAML':
+ if self.yaml_version is not None:
+ raise ParserError(None, None,
+ "found duplicate YAML directive", token.start_mark)
+ major, minor = token.value
+ if major != 1:
+ raise ParserError(None, None,
+ "found incompatible YAML document (version 1.* is required)",
+ token.start_mark)
+ self.yaml_version = token.value
+ elif token.name == u'TAG':
+ handle, prefix = token.value
+ if handle in self.tag_handles:
+ raise ParserError(None, None,
+ "duplicate tag handle %r" % handle.encode('utf-8'),
+ token.start_mark)
+ self.tag_handles[handle] = prefix
+ if self.tag_handles:
+ value = self.yaml_version, self.tag_handles.copy()
+ else:
+ value = self.yaml_version, None
+ for key in self.DEFAULT_TAGS:
+ if key not in self.tag_handles:
+ self.tag_handles[key] = self.DEFAULT_TAGS[key]
+ return value
+
+ # block_node_or_indentless_sequence ::= ALIAS
+ # | properties (block_content | indentless_block_sequence)?
+ # | block_content
+ # | indentless_block_sequence
+ # block_node ::= ALIAS
+ # | properties block_content?
+ # | block_content
+ # flow_node ::= ALIAS
+ # | properties flow_content?
+ # | flow_content
+ # properties ::= TAG ANCHOR? | ANCHOR TAG?
+ # block_content ::= block_collection | flow_collection | SCALAR
+ # flow_content ::= flow_collection | SCALAR
+ # block_collection ::= block_sequence | block_mapping
+ # flow_collection ::= flow_sequence | flow_mapping
+
+ def parse_block_node(self):
+ return self.parse_node(block=True)
+
+ def parse_flow_node(self):
+ return self.parse_node()
+
+ def parse_block_node_or_indentless_sequence(self):
+ return self.parse_node(block=True, indentless_sequence=True)
+
+ def parse_node(self, block=False, indentless_sequence=False):
+ if self.check_token(AliasToken):
+ token = self.get_token()
+ event = AliasEvent(token.value, token.start_mark, token.end_mark)
+ self.state = self.states.pop()
+ else:
+ anchor = None
+ tag = None
+ start_mark = end_mark = tag_mark = None
+ if self.check_token(AnchorToken):
+ token = self.get_token()
+ start_mark = token.start_mark
+ end_mark = token.end_mark
+ anchor = token.value
+ if self.check_token(TagToken):
+ token = self.get_token()
+ tag_mark = token.start_mark
+ end_mark = token.end_mark
+ tag = token.value
+ elif self.check_token(TagToken):
+ token = self.get_token()
+ start_mark = tag_mark = token.start_mark
+ end_mark = token.end_mark
+ tag = token.value
+ if self.check_token(AnchorToken):
+ token = self.get_token()
+ end_mark = token.end_mark
+ anchor = token.value
+ if tag is not None:
+ handle, suffix = tag
+ if handle is not None:
+ if handle not in self.tag_handles:
+ raise ParserError("while parsing a node", start_mark,
+ "found undefined tag handle %r" % handle.encode('utf-8'),
+ tag_mark)
+ tag = self.tag_handles[handle]+suffix
+ else:
+ tag = suffix
+ #if tag == u'!':
+ # raise ParserError("while parsing a node", start_mark,
+ # "found non-specific tag '!'", tag_mark,
+ # "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.")
+ if start_mark is None:
+ start_mark = end_mark = self.peek_token().start_mark
+ event = None
+ implicit = (tag is None or tag == u'!')
+ if indentless_sequence and self.check_token(BlockEntryToken):
+ end_mark = self.peek_token().end_mark
+ event = SequenceStartEvent(anchor, tag, implicit,
+ start_mark, end_mark)
+ self.state = self.parse_indentless_sequence_entry
+ else:
+ if self.check_token(ScalarToken):
+ token = self.get_token()
+ end_mark = token.end_mark
+ if (token.plain and tag is None) or tag == u'!':
+ implicit = (True, False)
+ elif tag is None:
+ implicit = (False, True)
+ else:
+ implicit = (False, False)
+ event = ScalarEvent(anchor, tag, implicit, token.value,
+ start_mark, end_mark, style=token.style)
+ self.state = self.states.pop()
+ elif self.check_token(FlowSequenceStartToken):
+ end_mark = self.peek_token().end_mark
+ event = SequenceStartEvent(anchor, tag, implicit,
+ start_mark, end_mark, flow_style=True)
+ self.state = self.parse_flow_sequence_first_entry
+ elif self.check_token(FlowMappingStartToken):
+ end_mark = self.peek_token().end_mark
+ event = MappingStartEvent(anchor, tag, implicit,
+ start_mark, end_mark, flow_style=True)
+ self.state = self.parse_flow_mapping_first_key
+ elif block and self.check_token(BlockSequenceStartToken):
+ end_mark = self.peek_token().start_mark
+ event = SequenceStartEvent(anchor, tag, implicit,
+ start_mark, end_mark, flow_style=False)
+ self.state = self.parse_block_sequence_first_entry
+ elif block and self.check_token(BlockMappingStartToken):
+ end_mark = self.peek_token().start_mark
+ event = MappingStartEvent(anchor, tag, implicit,
+ start_mark, end_mark, flow_style=False)
+ self.state = self.parse_block_mapping_first_key
+ elif anchor is not None or tag is not None:
+ # Empty scalars are allowed even if a tag or an anchor is
+ # specified.
+ event = ScalarEvent(anchor, tag, (implicit, False), u'',
+ start_mark, end_mark)
+ self.state = self.states.pop()
+ else:
+ if block:
+ node = 'block'
+ else:
+ node = 'flow'
+ token = self.peek_token()
+ raise ParserError("while parsing a %s node" % node, start_mark,
+ "expected the node content, but found %r" % token.id,
+ token.start_mark)
+ return event
+
+ # block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
+
+ def parse_block_sequence_first_entry(self):
+ token = self.get_token()
+ self.marks.append(token.start_mark)
+ return self.parse_block_sequence_entry()
+
+ def parse_block_sequence_entry(self):
+ if self.check_token(BlockEntryToken):
+ token = self.get_token()
+ if not self.check_token(BlockEntryToken, BlockEndToken):
+ self.states.append(self.parse_block_sequence_entry)
+ return self.parse_block_node()
+ else:
+ self.state = self.parse_block_sequence_entry
+ return self.process_empty_scalar(token.end_mark)
+ if not self.check_token(BlockEndToken):
+ token = self.peek_token()
+ raise ParserError("while parsing a block collection", self.marks[-1],
+ "expected <block end>, but found %r" % token.id, token.start_mark)
+ token = self.get_token()
+ event = SequenceEndEvent(token.start_mark, token.end_mark)
+ self.state = self.states.pop()
+ self.marks.pop()
+ return event
+
+ # indentless_sequence ::= (BLOCK-ENTRY block_node?)+
+
+ def parse_indentless_sequence_entry(self):
+ if self.check_token(BlockEntryToken):
+ token = self.get_token()
+ if not self.check_token(BlockEntryToken,
+ KeyToken, ValueToken, BlockEndToken):
+ self.states.append(self.parse_indentless_sequence_entry)
+ return self.parse_block_node()
+ else:
+ self.state = self.parse_indentless_sequence_entry
+ return self.process_empty_scalar(token.end_mark)
+ token = self.peek_token()
+ event = SequenceEndEvent(token.start_mark, token.start_mark)
+ self.state = self.states.pop()
+ return event
+
+ # block_mapping ::= BLOCK-MAPPING_START
+ # ((KEY block_node_or_indentless_sequence?)?
+ # (VALUE block_node_or_indentless_sequence?)?)*
+ # BLOCK-END
+
+ def parse_block_mapping_first_key(self):
+ token = self.get_token()
+ self.marks.append(token.start_mark)
+ return self.parse_block_mapping_key()
+
+ def parse_block_mapping_key(self):
+ if self.check_token(KeyToken):
+ token = self.get_token()
+ if not self.check_token(KeyToken, ValueToken, BlockEndToken):
+ self.states.append(self.parse_block_mapping_value)
+ return self.parse_block_node_or_indentless_sequence()
+ else:
+ self.state = self.parse_block_mapping_value
+ return self.process_empty_scalar(token.end_mark)
+ if not self.check_token(BlockEndToken):
+ token = self.peek_token()
+ raise ParserError("while parsing a block mapping", self.marks[-1],
+ "expected <block end>, but found %r" % token.id, token.start_mark)
+ token = self.get_token()
+ event = MappingEndEvent(token.start_mark, token.end_mark)
+ self.state = self.states.pop()
+ self.marks.pop()
+ return event
+
+ def parse_block_mapping_value(self):
+ if self.check_token(ValueToken):
+ token = self.get_token()
+ if not self.check_token(KeyToken, ValueToken, BlockEndToken):
+ self.states.append(self.parse_block_mapping_key)
+ return self.parse_block_node_or_indentless_sequence()
+ else:
+ self.state = self.parse_block_mapping_key
+ return self.process_empty_scalar(token.end_mark)
+ else:
+ self.state = self.parse_block_mapping_key
+ token = self.peek_token()
+ return self.process_empty_scalar(token.start_mark)
+
+ # flow_sequence ::= FLOW-SEQUENCE-START
+ # (flow_sequence_entry FLOW-ENTRY)*
+ # flow_sequence_entry?
+ # FLOW-SEQUENCE-END
+ # flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+ #
+ # Note that while production rules for both flow_sequence_entry and
+ # flow_mapping_entry are equal, their interpretations are different.
+ # For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?`
+ # generate an inline mapping (set syntax).
+
+ def parse_flow_sequence_first_entry(self):
+ token = self.get_token()
+ self.marks.append(token.start_mark)
+ return self.parse_flow_sequence_entry(first=True)
+
+ def parse_flow_sequence_entry(self, first=False):
+ if not self.check_token(FlowSequenceEndToken):
+ if not first:
+ if self.check_token(FlowEntryToken):
+ self.get_token()
+ else:
+ token = self.peek_token()
+ raise ParserError("while parsing a flow sequence", self.marks[-1],
+ "expected ',' or ']', but got %r" % token.id, token.start_mark)
+
+ if self.check_token(KeyToken):
+ token = self.peek_token()
+ event = MappingStartEvent(None, None, True,
+ token.start_mark, token.end_mark,
+ flow_style=True)
+ self.state = self.parse_flow_sequence_entry_mapping_key
+ return event
+ elif not self.check_token(FlowSequenceEndToken):
+ self.states.append(self.parse_flow_sequence_entry)
+ return self.parse_flow_node()
+ token = self.get_token()
+ event = SequenceEndEvent(token.start_mark, token.end_mark)
+ self.state = self.states.pop()
+ self.marks.pop()
+ return event
+
+ def parse_flow_sequence_entry_mapping_key(self):
+ token = self.get_token()
+ if not self.check_token(ValueToken,
+ FlowEntryToken, FlowSequenceEndToken):
+ self.states.append(self.parse_flow_sequence_entry_mapping_value)
+ return self.parse_flow_node()
+ else:
+ self.state = self.parse_flow_sequence_entry_mapping_value
+ return self.process_empty_scalar(token.end_mark)
+
+ def parse_flow_sequence_entry_mapping_value(self):
+ if self.check_token(ValueToken):
+ token = self.get_token()
+ if not self.check_token(FlowEntryToken, FlowSequenceEndToken):
+ self.states.append(self.parse_flow_sequence_entry_mapping_end)
+ return self.parse_flow_node()
+ else:
+ self.state = self.parse_flow_sequence_entry_mapping_end
+ return self.process_empty_scalar(token.end_mark)
+ else:
+ self.state = self.parse_flow_sequence_entry_mapping_end
+ token = self.peek_token()
+ return self.process_empty_scalar(token.start_mark)
+
+ def parse_flow_sequence_entry_mapping_end(self):
+ self.state = self.parse_flow_sequence_entry
+ token = self.peek_token()
+ return MappingEndEvent(token.start_mark, token.start_mark)
+
+ # flow_mapping ::= FLOW-MAPPING-START
+ # (flow_mapping_entry FLOW-ENTRY)*
+ # flow_mapping_entry?
+ # FLOW-MAPPING-END
+ # flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+
+ def parse_flow_mapping_first_key(self):
+ token = self.get_token()
+ self.marks.append(token.start_mark)
+ return self.parse_flow_mapping_key(first=True)
+
+ def parse_flow_mapping_key(self, first=False):
+ if not self.check_token(FlowMappingEndToken):
+ if not first:
+ if self.check_token(FlowEntryToken):
+ self.get_token()
+ else:
+ token = self.peek_token()
+ raise ParserError("while parsing a flow mapping", self.marks[-1],
+ "expected ',' or '}', but got %r" % token.id, token.start_mark)
+ if self.check_token(KeyToken):
+ token = self.get_token()
+ if not self.check_token(ValueToken,
+ FlowEntryToken, FlowMappingEndToken):
+ self.states.append(self.parse_flow_mapping_value)
+ return self.parse_flow_node()
+ else:
+ self.state = self.parse_flow_mapping_value
+ return self.process_empty_scalar(token.end_mark)
+ elif not self.check_token(FlowMappingEndToken):
+ self.states.append(self.parse_flow_mapping_empty_value)
+ return self.parse_flow_node()
+ token = self.get_token()
+ event = MappingEndEvent(token.start_mark, token.end_mark)
+ self.state = self.states.pop()
+ self.marks.pop()
+ return event
+
+ def parse_flow_mapping_value(self):
+ if self.check_token(ValueToken):
+ token = self.get_token()
+ if not self.check_token(FlowEntryToken, FlowMappingEndToken):
+ self.states.append(self.parse_flow_mapping_key)
+ return self.parse_flow_node()
+ else:
+ self.state = self.parse_flow_mapping_key
+ return self.process_empty_scalar(token.end_mark)
+ else:
+ self.state = self.parse_flow_mapping_key
+ token = self.peek_token()
+ return self.process_empty_scalar(token.start_mark)
+
+ def parse_flow_mapping_empty_value(self):
+ self.state = self.parse_flow_mapping_key
+ return self.process_empty_scalar(self.peek_token().start_mark)
+
+ def process_empty_scalar(self, mark):
+ return ScalarEvent(None, None, (True, False), u'', mark, mark)
+
diff --git a/contrib/python/PyYAML/py2/yaml/reader.py b/contrib/python/PyYAML/py2/yaml/reader.py
index 9ebce06eff..4c42150989 100644
--- a/contrib/python/PyYAML/py2/yaml/reader.py
+++ b/contrib/python/PyYAML/py2/yaml/reader.py
@@ -1,141 +1,141 @@
-# This module contains abstractions for the input stream. You don't have to
-# looks further, there are no pretty code.
-#
-# We define two classes here.
-#
-# Mark(source, line, column)
-# It's just a record and its only use is producing nice error messages.
-# Parser does not use it for any other purposes.
-#
-# Reader(source, data)
-# Reader determines the encoding of `data` and converts it to unicode.
-# Reader provides the following methods and attributes:
-# reader.peek(length=1) - return the next `length` characters
-# reader.forward(length=1) - move the current position to `length` characters.
-# reader.index - the number of the current character.
-# reader.line, stream.column - the line and the column of the current character.
-
-__all__ = ['Reader', 'ReaderError']
-
-from error import YAMLError, Mark
-
+# This module contains abstractions for the input stream. You don't have to
+# looks further, there are no pretty code.
+#
+# We define two classes here.
+#
+# Mark(source, line, column)
+# It's just a record and its only use is producing nice error messages.
+# Parser does not use it for any other purposes.
+#
+# Reader(source, data)
+# Reader determines the encoding of `data` and converts it to unicode.
+# Reader provides the following methods and attributes:
+# reader.peek(length=1) - return the next `length` characters
+# reader.forward(length=1) - move the current position to `length` characters.
+# reader.index - the number of the current character.
+# reader.line, stream.column - the line and the column of the current character.
+
+__all__ = ['Reader', 'ReaderError']
+
+from error import YAMLError, Mark
+
import codecs, re, sys
-
+
has_ucs4 = sys.maxunicode > 0xffff
-class ReaderError(YAMLError):
-
- def __init__(self, name, position, character, encoding, reason):
- self.name = name
- self.character = character
- self.position = position
- self.encoding = encoding
- self.reason = reason
-
- def __str__(self):
- if isinstance(self.character, str):
- return "'%s' codec can't decode byte #x%02x: %s\n" \
- " in \"%s\", position %d" \
- % (self.encoding, ord(self.character), self.reason,
- self.name, self.position)
- else:
- return "unacceptable character #x%04x: %s\n" \
- " in \"%s\", position %d" \
- % (self.character, self.reason,
- self.name, self.position)
-
-class Reader(object):
- # Reader:
- # - determines the data encoding and converts it to unicode,
- # - checks if characters are in allowed range,
- # - adds '\0' to the end.
-
- # Reader accepts
- # - a `str` object,
- # - a `unicode` object,
- # - a file-like object with its `read` method returning `str`,
- # - a file-like object with its `read` method returning `unicode`.
-
- # Yeah, it's ugly and slow.
-
- def __init__(self, stream):
- self.name = None
- self.stream = None
- self.stream_pointer = 0
- self.eof = True
- self.buffer = u''
- self.pointer = 0
- self.raw_buffer = None
- self.raw_decode = None
- self.encoding = None
- self.index = 0
- self.line = 0
- self.column = 0
- if isinstance(stream, unicode):
- self.name = "<unicode string>"
- self.check_printable(stream)
- self.buffer = stream+u'\0'
- elif isinstance(stream, str):
- self.name = "<string>"
- self.raw_buffer = stream
- self.determine_encoding()
- else:
- self.stream = stream
- self.name = getattr(stream, 'name', "<file>")
- self.eof = False
- self.raw_buffer = ''
- self.determine_encoding()
-
- def peek(self, index=0):
- try:
- return self.buffer[self.pointer+index]
- except IndexError:
- self.update(index+1)
- return self.buffer[self.pointer+index]
-
- def prefix(self, length=1):
- if self.pointer+length >= len(self.buffer):
- self.update(length)
- return self.buffer[self.pointer:self.pointer+length]
-
- def forward(self, length=1):
- if self.pointer+length+1 >= len(self.buffer):
- self.update(length+1)
- while length:
- ch = self.buffer[self.pointer]
- self.pointer += 1
- self.index += 1
- if ch in u'\n\x85\u2028\u2029' \
- or (ch == u'\r' and self.buffer[self.pointer] != u'\n'):
- self.line += 1
- self.column = 0
- elif ch != u'\uFEFF':
- self.column += 1
- length -= 1
-
- def get_mark(self):
- if self.stream is None:
- return Mark(self.name, self.index, self.line, self.column,
- self.buffer, self.pointer)
- else:
- return Mark(self.name, self.index, self.line, self.column,
- None, None)
-
- def determine_encoding(self):
- while not self.eof and len(self.raw_buffer) < 2:
- self.update_raw()
- if not isinstance(self.raw_buffer, unicode):
- if self.raw_buffer.startswith(codecs.BOM_UTF16_LE):
- self.raw_decode = codecs.utf_16_le_decode
- self.encoding = 'utf-16-le'
- elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE):
- self.raw_decode = codecs.utf_16_be_decode
- self.encoding = 'utf-16-be'
- else:
- self.raw_decode = codecs.utf_8_decode
- self.encoding = 'utf-8'
- self.update(1)
-
+class ReaderError(YAMLError):
+
+ def __init__(self, name, position, character, encoding, reason):
+ self.name = name
+ self.character = character
+ self.position = position
+ self.encoding = encoding
+ self.reason = reason
+
+ def __str__(self):
+ if isinstance(self.character, str):
+ return "'%s' codec can't decode byte #x%02x: %s\n" \
+ " in \"%s\", position %d" \
+ % (self.encoding, ord(self.character), self.reason,
+ self.name, self.position)
+ else:
+ return "unacceptable character #x%04x: %s\n" \
+ " in \"%s\", position %d" \
+ % (self.character, self.reason,
+ self.name, self.position)
+
+class Reader(object):
+ # Reader:
+ # - determines the data encoding and converts it to unicode,
+ # - checks if characters are in allowed range,
+ # - adds '\0' to the end.
+
+ # Reader accepts
+ # - a `str` object,
+ # - a `unicode` object,
+ # - a file-like object with its `read` method returning `str`,
+ # - a file-like object with its `read` method returning `unicode`.
+
+ # Yeah, it's ugly and slow.
+
+ def __init__(self, stream):
+ self.name = None
+ self.stream = None
+ self.stream_pointer = 0
+ self.eof = True
+ self.buffer = u''
+ self.pointer = 0
+ self.raw_buffer = None
+ self.raw_decode = None
+ self.encoding = None
+ self.index = 0
+ self.line = 0
+ self.column = 0
+ if isinstance(stream, unicode):
+ self.name = "<unicode string>"
+ self.check_printable(stream)
+ self.buffer = stream+u'\0'
+ elif isinstance(stream, str):
+ self.name = "<string>"
+ self.raw_buffer = stream
+ self.determine_encoding()
+ else:
+ self.stream = stream
+ self.name = getattr(stream, 'name', "<file>")
+ self.eof = False
+ self.raw_buffer = ''
+ self.determine_encoding()
+
+ def peek(self, index=0):
+ try:
+ return self.buffer[self.pointer+index]
+ except IndexError:
+ self.update(index+1)
+ return self.buffer[self.pointer+index]
+
+ def prefix(self, length=1):
+ if self.pointer+length >= len(self.buffer):
+ self.update(length)
+ return self.buffer[self.pointer:self.pointer+length]
+
+ def forward(self, length=1):
+ if self.pointer+length+1 >= len(self.buffer):
+ self.update(length+1)
+ while length:
+ ch = self.buffer[self.pointer]
+ self.pointer += 1
+ self.index += 1
+ if ch in u'\n\x85\u2028\u2029' \
+ or (ch == u'\r' and self.buffer[self.pointer] != u'\n'):
+ self.line += 1
+ self.column = 0
+ elif ch != u'\uFEFF':
+ self.column += 1
+ length -= 1
+
+ def get_mark(self):
+ if self.stream is None:
+ return Mark(self.name, self.index, self.line, self.column,
+ self.buffer, self.pointer)
+ else:
+ return Mark(self.name, self.index, self.line, self.column,
+ None, None)
+
+ def determine_encoding(self):
+ while not self.eof and len(self.raw_buffer) < 2:
+ self.update_raw()
+ if not isinstance(self.raw_buffer, unicode):
+ if self.raw_buffer.startswith(codecs.BOM_UTF16_LE):
+ self.raw_decode = codecs.utf_16_le_decode
+ self.encoding = 'utf-16-le'
+ elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE):
+ self.raw_decode = codecs.utf_16_be_decode
+ self.encoding = 'utf-16-be'
+ else:
+ self.raw_decode = codecs.utf_8_decode
+ self.encoding = 'utf-8'
+ self.update(1)
+
if has_ucs4:
NON_PRINTABLE = u'[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]'
elif sys.platform.startswith('java'):
@@ -145,49 +145,49 @@ class Reader(object):
# Need to use eval here due to the above Jython issue
NON_PRINTABLE = eval(r"u'[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uFFFD]|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF](?:[^\uDC00-\uDFFF]|$)'")
NON_PRINTABLE = re.compile(NON_PRINTABLE)
- def check_printable(self, data):
- match = self.NON_PRINTABLE.search(data)
- if match:
- character = match.group()
- position = self.index+(len(self.buffer)-self.pointer)+match.start()
- raise ReaderError(self.name, position, ord(character),
- 'unicode', "special characters are not allowed")
-
- def update(self, length):
- if self.raw_buffer is None:
- return
- self.buffer = self.buffer[self.pointer:]
- self.pointer = 0
- while len(self.buffer) < length:
- if not self.eof:
- self.update_raw()
- if self.raw_decode is not None:
- try:
- data, converted = self.raw_decode(self.raw_buffer,
- 'strict', self.eof)
- except UnicodeDecodeError, exc:
- character = exc.object[exc.start]
- if self.stream is not None:
- position = self.stream_pointer-len(self.raw_buffer)+exc.start
- else:
- position = exc.start
- raise ReaderError(self.name, position, character,
- exc.encoding, exc.reason)
- else:
- data = self.raw_buffer
- converted = len(data)
- self.check_printable(data)
- self.buffer += data
- self.raw_buffer = self.raw_buffer[converted:]
- if self.eof:
- self.buffer += u'\0'
- self.raw_buffer = None
- break
-
- def update_raw(self, size=1024):
- data = self.stream.read(size)
- if data:
- self.raw_buffer += data
- self.stream_pointer += len(data)
- else:
- self.eof = True
+ def check_printable(self, data):
+ match = self.NON_PRINTABLE.search(data)
+ if match:
+ character = match.group()
+ position = self.index+(len(self.buffer)-self.pointer)+match.start()
+ raise ReaderError(self.name, position, ord(character),
+ 'unicode', "special characters are not allowed")
+
+ def update(self, length):
+ if self.raw_buffer is None:
+ return
+ self.buffer = self.buffer[self.pointer:]
+ self.pointer = 0
+ while len(self.buffer) < length:
+ if not self.eof:
+ self.update_raw()
+ if self.raw_decode is not None:
+ try:
+ data, converted = self.raw_decode(self.raw_buffer,
+ 'strict', self.eof)
+ except UnicodeDecodeError, exc:
+ character = exc.object[exc.start]
+ if self.stream is not None:
+ position = self.stream_pointer-len(self.raw_buffer)+exc.start
+ else:
+ position = exc.start
+ raise ReaderError(self.name, position, character,
+ exc.encoding, exc.reason)
+ else:
+ data = self.raw_buffer
+ converted = len(data)
+ self.check_printable(data)
+ self.buffer += data
+ self.raw_buffer = self.raw_buffer[converted:]
+ if self.eof:
+ self.buffer += u'\0'
+ self.raw_buffer = None
+ break
+
+ def update_raw(self, size=1024):
+ data = self.stream.read(size)
+ if data:
+ self.raw_buffer += data
+ self.stream_pointer += len(data)
+ else:
+ self.eof = True
diff --git a/contrib/python/PyYAML/py2/yaml/representer.py b/contrib/python/PyYAML/py2/yaml/representer.py
index da01788100..93e09b67b3 100644
--- a/contrib/python/PyYAML/py2/yaml/representer.py
+++ b/contrib/python/PyYAML/py2/yaml/representer.py
@@ -1,489 +1,489 @@
-
-__all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer',
- 'RepresenterError']
-
-from error import *
-
-from nodes import *
-
-import datetime
-
+
+__all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer',
+ 'RepresenterError']
+
+from error import *
+
+from nodes import *
+
+import datetime
+
import copy_reg, types
-
-class RepresenterError(YAMLError):
- pass
-
-class BaseRepresenter(object):
-
- yaml_representers = {}
- yaml_multi_representers = {}
-
+
+class RepresenterError(YAMLError):
+ pass
+
+class BaseRepresenter(object):
+
+ yaml_representers = {}
+ yaml_multi_representers = {}
+
def __init__(self, default_style=None, default_flow_style=False, sort_keys=True):
- self.default_style = default_style
- self.default_flow_style = default_flow_style
+ self.default_style = default_style
+ self.default_flow_style = default_flow_style
self.sort_keys = sort_keys
- self.represented_objects = {}
- self.object_keeper = []
- self.alias_key = None
-
- def represent(self, data):
- node = self.represent_data(data)
- self.serialize(node)
- self.represented_objects = {}
- self.object_keeper = []
- self.alias_key = None
-
- def get_classobj_bases(self, cls):
- bases = [cls]
- for base in cls.__bases__:
- bases.extend(self.get_classobj_bases(base))
- return bases
-
- def represent_data(self, data):
- if self.ignore_aliases(data):
- self.alias_key = None
- else:
- self.alias_key = id(data)
- if self.alias_key is not None:
- if self.alias_key in self.represented_objects:
- node = self.represented_objects[self.alias_key]
- #if node is None:
- # raise RepresenterError("recursive objects are not allowed: %r" % data)
- return node
- #self.represented_objects[alias_key] = None
- self.object_keeper.append(data)
- data_types = type(data).__mro__
- if type(data) is types.InstanceType:
- data_types = self.get_classobj_bases(data.__class__)+list(data_types)
- if data_types[0] in self.yaml_representers:
- node = self.yaml_representers[data_types[0]](self, data)
- else:
- for data_type in data_types:
- if data_type in self.yaml_multi_representers:
- node = self.yaml_multi_representers[data_type](self, data)
- break
- else:
- if None in self.yaml_multi_representers:
- node = self.yaml_multi_representers[None](self, data)
- elif None in self.yaml_representers:
- node = self.yaml_representers[None](self, data)
- else:
- node = ScalarNode(None, unicode(data))
- #if alias_key is not None:
- # self.represented_objects[alias_key] = node
- return node
-
- def add_representer(cls, data_type, representer):
- if not 'yaml_representers' in cls.__dict__:
- cls.yaml_representers = cls.yaml_representers.copy()
- cls.yaml_representers[data_type] = representer
- add_representer = classmethod(add_representer)
-
- def add_multi_representer(cls, data_type, representer):
- if not 'yaml_multi_representers' in cls.__dict__:
- cls.yaml_multi_representers = cls.yaml_multi_representers.copy()
- cls.yaml_multi_representers[data_type] = representer
- add_multi_representer = classmethod(add_multi_representer)
-
- def represent_scalar(self, tag, value, style=None):
- if style is None:
- style = self.default_style
- node = ScalarNode(tag, value, style=style)
- if self.alias_key is not None:
- self.represented_objects[self.alias_key] = node
- return node
-
- def represent_sequence(self, tag, sequence, flow_style=None):
- value = []
- node = SequenceNode(tag, value, flow_style=flow_style)
- if self.alias_key is not None:
- self.represented_objects[self.alias_key] = node
- best_style = True
- for item in sequence:
- node_item = self.represent_data(item)
- if not (isinstance(node_item, ScalarNode) and not node_item.style):
- best_style = False
- value.append(node_item)
- if flow_style is None:
- if self.default_flow_style is not None:
- node.flow_style = self.default_flow_style
- else:
- node.flow_style = best_style
- return node
-
- def represent_mapping(self, tag, mapping, flow_style=None):
- value = []
- node = MappingNode(tag, value, flow_style=flow_style)
- if self.alias_key is not None:
- self.represented_objects[self.alias_key] = node
- best_style = True
- if hasattr(mapping, 'items'):
- mapping = mapping.items()
+ self.represented_objects = {}
+ self.object_keeper = []
+ self.alias_key = None
+
+ def represent(self, data):
+ node = self.represent_data(data)
+ self.serialize(node)
+ self.represented_objects = {}
+ self.object_keeper = []
+ self.alias_key = None
+
+ def get_classobj_bases(self, cls):
+ bases = [cls]
+ for base in cls.__bases__:
+ bases.extend(self.get_classobj_bases(base))
+ return bases
+
+ def represent_data(self, data):
+ if self.ignore_aliases(data):
+ self.alias_key = None
+ else:
+ self.alias_key = id(data)
+ if self.alias_key is not None:
+ if self.alias_key in self.represented_objects:
+ node = self.represented_objects[self.alias_key]
+ #if node is None:
+ # raise RepresenterError("recursive objects are not allowed: %r" % data)
+ return node
+ #self.represented_objects[alias_key] = None
+ self.object_keeper.append(data)
+ data_types = type(data).__mro__
+ if type(data) is types.InstanceType:
+ data_types = self.get_classobj_bases(data.__class__)+list(data_types)
+ if data_types[0] in self.yaml_representers:
+ node = self.yaml_representers[data_types[0]](self, data)
+ else:
+ for data_type in data_types:
+ if data_type in self.yaml_multi_representers:
+ node = self.yaml_multi_representers[data_type](self, data)
+ break
+ else:
+ if None in self.yaml_multi_representers:
+ node = self.yaml_multi_representers[None](self, data)
+ elif None in self.yaml_representers:
+ node = self.yaml_representers[None](self, data)
+ else:
+ node = ScalarNode(None, unicode(data))
+ #if alias_key is not None:
+ # self.represented_objects[alias_key] = node
+ return node
+
+ def add_representer(cls, data_type, representer):
+ if not 'yaml_representers' in cls.__dict__:
+ cls.yaml_representers = cls.yaml_representers.copy()
+ cls.yaml_representers[data_type] = representer
+ add_representer = classmethod(add_representer)
+
+ def add_multi_representer(cls, data_type, representer):
+ if not 'yaml_multi_representers' in cls.__dict__:
+ cls.yaml_multi_representers = cls.yaml_multi_representers.copy()
+ cls.yaml_multi_representers[data_type] = representer
+ add_multi_representer = classmethod(add_multi_representer)
+
+ def represent_scalar(self, tag, value, style=None):
+ if style is None:
+ style = self.default_style
+ node = ScalarNode(tag, value, style=style)
+ if self.alias_key is not None:
+ self.represented_objects[self.alias_key] = node
+ return node
+
+ def represent_sequence(self, tag, sequence, flow_style=None):
+ value = []
+ node = SequenceNode(tag, value, flow_style=flow_style)
+ if self.alias_key is not None:
+ self.represented_objects[self.alias_key] = node
+ best_style = True
+ for item in sequence:
+ node_item = self.represent_data(item)
+ if not (isinstance(node_item, ScalarNode) and not node_item.style):
+ best_style = False
+ value.append(node_item)
+ if flow_style is None:
+ if self.default_flow_style is not None:
+ node.flow_style = self.default_flow_style
+ else:
+ node.flow_style = best_style
+ return node
+
+ def represent_mapping(self, tag, mapping, flow_style=None):
+ value = []
+ node = MappingNode(tag, value, flow_style=flow_style)
+ if self.alias_key is not None:
+ self.represented_objects[self.alias_key] = node
+ best_style = True
+ if hasattr(mapping, 'items'):
+ mapping = mapping.items()
if self.sort_keys:
mapping.sort()
- for item_key, item_value in mapping:
- node_key = self.represent_data(item_key)
- node_value = self.represent_data(item_value)
- if not (isinstance(node_key, ScalarNode) and not node_key.style):
- best_style = False
- if not (isinstance(node_value, ScalarNode) and not node_value.style):
- best_style = False
- value.append((node_key, node_value))
- if flow_style is None:
- if self.default_flow_style is not None:
- node.flow_style = self.default_flow_style
- else:
- node.flow_style = best_style
- return node
-
- def ignore_aliases(self, data):
- return False
-
-class SafeRepresenter(BaseRepresenter):
-
- def ignore_aliases(self, data):
+ for item_key, item_value in mapping:
+ node_key = self.represent_data(item_key)
+ node_value = self.represent_data(item_value)
+ if not (isinstance(node_key, ScalarNode) and not node_key.style):
+ best_style = False
+ if not (isinstance(node_value, ScalarNode) and not node_value.style):
+ best_style = False
+ value.append((node_key, node_value))
+ if flow_style is None:
+ if self.default_flow_style is not None:
+ node.flow_style = self.default_flow_style
+ else:
+ node.flow_style = best_style
+ return node
+
+ def ignore_aliases(self, data):
+ return False
+
+class SafeRepresenter(BaseRepresenter):
+
+ def ignore_aliases(self, data):
if data is None:
- return True
+ return True
if isinstance(data, tuple) and data == ():
return True
- if isinstance(data, (str, unicode, bool, int, float)):
- return True
-
- def represent_none(self, data):
- return self.represent_scalar(u'tag:yaml.org,2002:null',
- u'null')
-
- def represent_str(self, data):
- tag = None
- style = None
- try:
- data = unicode(data, 'ascii')
- tag = u'tag:yaml.org,2002:str'
- except UnicodeDecodeError:
- try:
- data = unicode(data, 'utf-8')
- tag = u'tag:yaml.org,2002:str'
- except UnicodeDecodeError:
- data = data.encode('base64')
- tag = u'tag:yaml.org,2002:binary'
- style = '|'
- return self.represent_scalar(tag, data, style=style)
-
- def represent_unicode(self, data):
- return self.represent_scalar(u'tag:yaml.org,2002:str', data)
-
- def represent_bool(self, data):
- if data:
- value = u'true'
- else:
- value = u'false'
- return self.represent_scalar(u'tag:yaml.org,2002:bool', value)
-
- def represent_int(self, data):
- return self.represent_scalar(u'tag:yaml.org,2002:int', unicode(data))
-
- def represent_long(self, data):
- return self.represent_scalar(u'tag:yaml.org,2002:int', unicode(data))
-
- inf_value = 1e300
- while repr(inf_value) != repr(inf_value*inf_value):
- inf_value *= inf_value
-
- def represent_float(self, data):
- if data != data or (data == 0.0 and data == 1.0):
- value = u'.nan'
- elif data == self.inf_value:
- value = u'.inf'
- elif data == -self.inf_value:
- value = u'-.inf'
- else:
- value = unicode(repr(data)).lower()
- # Note that in some cases `repr(data)` represents a float number
- # without the decimal parts. For instance:
- # >>> repr(1e17)
- # '1e17'
- # Unfortunately, this is not a valid float representation according
- # to the definition of the `!!float` tag. We fix this by adding
- # '.0' before the 'e' symbol.
- if u'.' not in value and u'e' in value:
- value = value.replace(u'e', u'.0e', 1)
- return self.represent_scalar(u'tag:yaml.org,2002:float', value)
-
- def represent_list(self, data):
- #pairs = (len(data) > 0 and isinstance(data, list))
- #if pairs:
- # for item in data:
- # if not isinstance(item, tuple) or len(item) != 2:
- # pairs = False
- # break
- #if not pairs:
- return self.represent_sequence(u'tag:yaml.org,2002:seq', data)
- #value = []
- #for item_key, item_value in data:
- # value.append(self.represent_mapping(u'tag:yaml.org,2002:map',
- # [(item_key, item_value)]))
- #return SequenceNode(u'tag:yaml.org,2002:pairs', value)
-
- def represent_dict(self, data):
- return self.represent_mapping(u'tag:yaml.org,2002:map', data)
-
- def represent_set(self, data):
- value = {}
- for key in data:
- value[key] = None
- return self.represent_mapping(u'tag:yaml.org,2002:set', value)
-
- def represent_date(self, data):
- value = unicode(data.isoformat())
- return self.represent_scalar(u'tag:yaml.org,2002:timestamp', value)
-
- def represent_datetime(self, data):
- value = unicode(data.isoformat(' '))
- return self.represent_scalar(u'tag:yaml.org,2002:timestamp', value)
-
- def represent_yaml_object(self, tag, data, cls, flow_style=None):
- if hasattr(data, '__getstate__'):
- state = data.__getstate__()
- else:
- state = data.__dict__.copy()
- return self.represent_mapping(tag, state, flow_style=flow_style)
-
- def represent_undefined(self, data):
+ if isinstance(data, (str, unicode, bool, int, float)):
+ return True
+
+ def represent_none(self, data):
+ return self.represent_scalar(u'tag:yaml.org,2002:null',
+ u'null')
+
+ def represent_str(self, data):
+ tag = None
+ style = None
+ try:
+ data = unicode(data, 'ascii')
+ tag = u'tag:yaml.org,2002:str'
+ except UnicodeDecodeError:
+ try:
+ data = unicode(data, 'utf-8')
+ tag = u'tag:yaml.org,2002:str'
+ except UnicodeDecodeError:
+ data = data.encode('base64')
+ tag = u'tag:yaml.org,2002:binary'
+ style = '|'
+ return self.represent_scalar(tag, data, style=style)
+
+ def represent_unicode(self, data):
+ return self.represent_scalar(u'tag:yaml.org,2002:str', data)
+
+ def represent_bool(self, data):
+ if data:
+ value = u'true'
+ else:
+ value = u'false'
+ return self.represent_scalar(u'tag:yaml.org,2002:bool', value)
+
+ def represent_int(self, data):
+ return self.represent_scalar(u'tag:yaml.org,2002:int', unicode(data))
+
+ def represent_long(self, data):
+ return self.represent_scalar(u'tag:yaml.org,2002:int', unicode(data))
+
+ inf_value = 1e300
+ while repr(inf_value) != repr(inf_value*inf_value):
+ inf_value *= inf_value
+
+ def represent_float(self, data):
+ if data != data or (data == 0.0 and data == 1.0):
+ value = u'.nan'
+ elif data == self.inf_value:
+ value = u'.inf'
+ elif data == -self.inf_value:
+ value = u'-.inf'
+ else:
+ value = unicode(repr(data)).lower()
+ # Note that in some cases `repr(data)` represents a float number
+ # without the decimal parts. For instance:
+ # >>> repr(1e17)
+ # '1e17'
+ # Unfortunately, this is not a valid float representation according
+ # to the definition of the `!!float` tag. We fix this by adding
+ # '.0' before the 'e' symbol.
+ if u'.' not in value and u'e' in value:
+ value = value.replace(u'e', u'.0e', 1)
+ return self.represent_scalar(u'tag:yaml.org,2002:float', value)
+
+ def represent_list(self, data):
+ #pairs = (len(data) > 0 and isinstance(data, list))
+ #if pairs:
+ # for item in data:
+ # if not isinstance(item, tuple) or len(item) != 2:
+ # pairs = False
+ # break
+ #if not pairs:
+ return self.represent_sequence(u'tag:yaml.org,2002:seq', data)
+ #value = []
+ #for item_key, item_value in data:
+ # value.append(self.represent_mapping(u'tag:yaml.org,2002:map',
+ # [(item_key, item_value)]))
+ #return SequenceNode(u'tag:yaml.org,2002:pairs', value)
+
+ def represent_dict(self, data):
+ return self.represent_mapping(u'tag:yaml.org,2002:map', data)
+
+ def represent_set(self, data):
+ value = {}
+ for key in data:
+ value[key] = None
+ return self.represent_mapping(u'tag:yaml.org,2002:set', value)
+
+ def represent_date(self, data):
+ value = unicode(data.isoformat())
+ return self.represent_scalar(u'tag:yaml.org,2002:timestamp', value)
+
+ def represent_datetime(self, data):
+ value = unicode(data.isoformat(' '))
+ return self.represent_scalar(u'tag:yaml.org,2002:timestamp', value)
+
+ def represent_yaml_object(self, tag, data, cls, flow_style=None):
+ if hasattr(data, '__getstate__'):
+ state = data.__getstate__()
+ else:
+ state = data.__dict__.copy()
+ return self.represent_mapping(tag, state, flow_style=flow_style)
+
+ def represent_undefined(self, data):
raise RepresenterError("cannot represent an object", data)
-
-SafeRepresenter.add_representer(type(None),
- SafeRepresenter.represent_none)
-
-SafeRepresenter.add_representer(str,
- SafeRepresenter.represent_str)
-
-SafeRepresenter.add_representer(unicode,
- SafeRepresenter.represent_unicode)
-
-SafeRepresenter.add_representer(bool,
- SafeRepresenter.represent_bool)
-
-SafeRepresenter.add_representer(int,
- SafeRepresenter.represent_int)
-
-SafeRepresenter.add_representer(long,
- SafeRepresenter.represent_long)
-
-SafeRepresenter.add_representer(float,
- SafeRepresenter.represent_float)
-
-SafeRepresenter.add_representer(list,
- SafeRepresenter.represent_list)
-
-SafeRepresenter.add_representer(tuple,
- SafeRepresenter.represent_list)
-
-SafeRepresenter.add_representer(dict,
- SafeRepresenter.represent_dict)
-
-SafeRepresenter.add_representer(set,
- SafeRepresenter.represent_set)
-
-SafeRepresenter.add_representer(datetime.date,
- SafeRepresenter.represent_date)
-
-SafeRepresenter.add_representer(datetime.datetime,
- SafeRepresenter.represent_datetime)
-
-SafeRepresenter.add_representer(None,
- SafeRepresenter.represent_undefined)
-
-class Representer(SafeRepresenter):
-
- def represent_str(self, data):
- tag = None
- style = None
- try:
- data = unicode(data, 'ascii')
- tag = u'tag:yaml.org,2002:str'
- except UnicodeDecodeError:
- try:
- data = unicode(data, 'utf-8')
- tag = u'tag:yaml.org,2002:python/str'
- except UnicodeDecodeError:
- data = data.encode('base64')
- tag = u'tag:yaml.org,2002:binary'
- style = '|'
- return self.represent_scalar(tag, data, style=style)
-
- def represent_unicode(self, data):
- tag = None
- try:
- data.encode('ascii')
- tag = u'tag:yaml.org,2002:python/unicode'
- except UnicodeEncodeError:
- tag = u'tag:yaml.org,2002:str'
- return self.represent_scalar(tag, data)
-
- def represent_long(self, data):
- tag = u'tag:yaml.org,2002:int'
- if int(data) is not data:
- tag = u'tag:yaml.org,2002:python/long'
- return self.represent_scalar(tag, unicode(data))
-
- def represent_complex(self, data):
- if data.imag == 0.0:
- data = u'%r' % data.real
- elif data.real == 0.0:
- data = u'%rj' % data.imag
- elif data.imag > 0:
- data = u'%r+%rj' % (data.real, data.imag)
- else:
- data = u'%r%rj' % (data.real, data.imag)
- return self.represent_scalar(u'tag:yaml.org,2002:python/complex', data)
-
- def represent_tuple(self, data):
- return self.represent_sequence(u'tag:yaml.org,2002:python/tuple', data)
-
- def represent_name(self, data):
- name = u'%s.%s' % (data.__module__, data.__name__)
- return self.represent_scalar(u'tag:yaml.org,2002:python/name:'+name, u'')
-
- def represent_module(self, data):
- return self.represent_scalar(
- u'tag:yaml.org,2002:python/module:'+data.__name__, u'')
-
- def represent_instance(self, data):
- # For instances of classic classes, we use __getinitargs__ and
- # __getstate__ to serialize the data.
-
- # If data.__getinitargs__ exists, the object must be reconstructed by
- # calling cls(**args), where args is a tuple returned by
- # __getinitargs__. Otherwise, the cls.__init__ method should never be
- # called and the class instance is created by instantiating a trivial
- # class and assigning to the instance's __class__ variable.
-
- # If data.__getstate__ exists, it returns the state of the object.
- # Otherwise, the state of the object is data.__dict__.
-
- # We produce either a !!python/object or !!python/object/new node.
- # If data.__getinitargs__ does not exist and state is a dictionary, we
- # produce a !!python/object node . Otherwise we produce a
- # !!python/object/new node.
-
- cls = data.__class__
- class_name = u'%s.%s' % (cls.__module__, cls.__name__)
- args = None
- state = None
- if hasattr(data, '__getinitargs__'):
- args = list(data.__getinitargs__())
- if hasattr(data, '__getstate__'):
- state = data.__getstate__()
- else:
- state = data.__dict__
- if args is None and isinstance(state, dict):
- return self.represent_mapping(
- u'tag:yaml.org,2002:python/object:'+class_name, state)
- if isinstance(state, dict) and not state:
- return self.represent_sequence(
- u'tag:yaml.org,2002:python/object/new:'+class_name, args)
- value = {}
- if args:
- value['args'] = args
- value['state'] = state
- return self.represent_mapping(
- u'tag:yaml.org,2002:python/object/new:'+class_name, value)
-
- def represent_object(self, data):
- # We use __reduce__ API to save the data. data.__reduce__ returns
- # a tuple of length 2-5:
- # (function, args, state, listitems, dictitems)
-
- # For reconstructing, we calls function(*args), then set its state,
- # listitems, and dictitems if they are not None.
-
- # A special case is when function.__name__ == '__newobj__'. In this
- # case we create the object with args[0].__new__(*args).
-
- # Another special case is when __reduce__ returns a string - we don't
- # support it.
-
- # We produce a !!python/object, !!python/object/new or
- # !!python/object/apply node.
-
- cls = type(data)
- if cls in copy_reg.dispatch_table:
- reduce = copy_reg.dispatch_table[cls](data)
- elif hasattr(data, '__reduce_ex__'):
- reduce = data.__reduce_ex__(2)
- elif hasattr(data, '__reduce__'):
- reduce = data.__reduce__()
- else:
+
+SafeRepresenter.add_representer(type(None),
+ SafeRepresenter.represent_none)
+
+SafeRepresenter.add_representer(str,
+ SafeRepresenter.represent_str)
+
+SafeRepresenter.add_representer(unicode,
+ SafeRepresenter.represent_unicode)
+
+SafeRepresenter.add_representer(bool,
+ SafeRepresenter.represent_bool)
+
+SafeRepresenter.add_representer(int,
+ SafeRepresenter.represent_int)
+
+SafeRepresenter.add_representer(long,
+ SafeRepresenter.represent_long)
+
+SafeRepresenter.add_representer(float,
+ SafeRepresenter.represent_float)
+
+SafeRepresenter.add_representer(list,
+ SafeRepresenter.represent_list)
+
+SafeRepresenter.add_representer(tuple,
+ SafeRepresenter.represent_list)
+
+SafeRepresenter.add_representer(dict,
+ SafeRepresenter.represent_dict)
+
+SafeRepresenter.add_representer(set,
+ SafeRepresenter.represent_set)
+
+SafeRepresenter.add_representer(datetime.date,
+ SafeRepresenter.represent_date)
+
+SafeRepresenter.add_representer(datetime.datetime,
+ SafeRepresenter.represent_datetime)
+
+SafeRepresenter.add_representer(None,
+ SafeRepresenter.represent_undefined)
+
+class Representer(SafeRepresenter):
+
+ def represent_str(self, data):
+ tag = None
+ style = None
+ try:
+ data = unicode(data, 'ascii')
+ tag = u'tag:yaml.org,2002:str'
+ except UnicodeDecodeError:
+ try:
+ data = unicode(data, 'utf-8')
+ tag = u'tag:yaml.org,2002:python/str'
+ except UnicodeDecodeError:
+ data = data.encode('base64')
+ tag = u'tag:yaml.org,2002:binary'
+ style = '|'
+ return self.represent_scalar(tag, data, style=style)
+
+ def represent_unicode(self, data):
+ tag = None
+ try:
+ data.encode('ascii')
+ tag = u'tag:yaml.org,2002:python/unicode'
+ except UnicodeEncodeError:
+ tag = u'tag:yaml.org,2002:str'
+ return self.represent_scalar(tag, data)
+
+ def represent_long(self, data):
+ tag = u'tag:yaml.org,2002:int'
+ if int(data) is not data:
+ tag = u'tag:yaml.org,2002:python/long'
+ return self.represent_scalar(tag, unicode(data))
+
+ def represent_complex(self, data):
+ if data.imag == 0.0:
+ data = u'%r' % data.real
+ elif data.real == 0.0:
+ data = u'%rj' % data.imag
+ elif data.imag > 0:
+ data = u'%r+%rj' % (data.real, data.imag)
+ else:
+ data = u'%r%rj' % (data.real, data.imag)
+ return self.represent_scalar(u'tag:yaml.org,2002:python/complex', data)
+
+ def represent_tuple(self, data):
+ return self.represent_sequence(u'tag:yaml.org,2002:python/tuple', data)
+
+ def represent_name(self, data):
+ name = u'%s.%s' % (data.__module__, data.__name__)
+ return self.represent_scalar(u'tag:yaml.org,2002:python/name:'+name, u'')
+
+ def represent_module(self, data):
+ return self.represent_scalar(
+ u'tag:yaml.org,2002:python/module:'+data.__name__, u'')
+
+ def represent_instance(self, data):
+ # For instances of classic classes, we use __getinitargs__ and
+ # __getstate__ to serialize the data.
+
+ # If data.__getinitargs__ exists, the object must be reconstructed by
+ # calling cls(**args), where args is a tuple returned by
+ # __getinitargs__. Otherwise, the cls.__init__ method should never be
+ # called and the class instance is created by instantiating a trivial
+ # class and assigning to the instance's __class__ variable.
+
+ # If data.__getstate__ exists, it returns the state of the object.
+ # Otherwise, the state of the object is data.__dict__.
+
+ # We produce either a !!python/object or !!python/object/new node.
+ # If data.__getinitargs__ does not exist and state is a dictionary, we
+ # produce a !!python/object node . Otherwise we produce a
+ # !!python/object/new node.
+
+ cls = data.__class__
+ class_name = u'%s.%s' % (cls.__module__, cls.__name__)
+ args = None
+ state = None
+ if hasattr(data, '__getinitargs__'):
+ args = list(data.__getinitargs__())
+ if hasattr(data, '__getstate__'):
+ state = data.__getstate__()
+ else:
+ state = data.__dict__
+ if args is None and isinstance(state, dict):
+ return self.represent_mapping(
+ u'tag:yaml.org,2002:python/object:'+class_name, state)
+ if isinstance(state, dict) and not state:
+ return self.represent_sequence(
+ u'tag:yaml.org,2002:python/object/new:'+class_name, args)
+ value = {}
+ if args:
+ value['args'] = args
+ value['state'] = state
+ return self.represent_mapping(
+ u'tag:yaml.org,2002:python/object/new:'+class_name, value)
+
+ def represent_object(self, data):
+ # We use __reduce__ API to save the data. data.__reduce__ returns
+ # a tuple of length 2-5:
+ # (function, args, state, listitems, dictitems)
+
+ # For reconstructing, we calls function(*args), then set its state,
+ # listitems, and dictitems if they are not None.
+
+ # A special case is when function.__name__ == '__newobj__'. In this
+ # case we create the object with args[0].__new__(*args).
+
+ # Another special case is when __reduce__ returns a string - we don't
+ # support it.
+
+ # We produce a !!python/object, !!python/object/new or
+ # !!python/object/apply node.
+
+ cls = type(data)
+ if cls in copy_reg.dispatch_table:
+ reduce = copy_reg.dispatch_table[cls](data)
+ elif hasattr(data, '__reduce_ex__'):
+ reduce = data.__reduce_ex__(2)
+ elif hasattr(data, '__reduce__'):
+ reduce = data.__reduce__()
+ else:
raise RepresenterError("cannot represent an object", data)
- reduce = (list(reduce)+[None]*5)[:5]
- function, args, state, listitems, dictitems = reduce
- args = list(args)
- if state is None:
- state = {}
- if listitems is not None:
- listitems = list(listitems)
- if dictitems is not None:
- dictitems = dict(dictitems)
- if function.__name__ == '__newobj__':
- function = args[0]
- args = args[1:]
- tag = u'tag:yaml.org,2002:python/object/new:'
- newobj = True
- else:
- tag = u'tag:yaml.org,2002:python/object/apply:'
- newobj = False
- function_name = u'%s.%s' % (function.__module__, function.__name__)
- if not args and not listitems and not dictitems \
- and isinstance(state, dict) and newobj:
- return self.represent_mapping(
- u'tag:yaml.org,2002:python/object:'+function_name, state)
- if not listitems and not dictitems \
- and isinstance(state, dict) and not state:
- return self.represent_sequence(tag+function_name, args)
- value = {}
- if args:
- value['args'] = args
- if state or not isinstance(state, dict):
- value['state'] = state
- if listitems:
- value['listitems'] = listitems
- if dictitems:
- value['dictitems'] = dictitems
- return self.represent_mapping(tag+function_name, value)
-
-Representer.add_representer(str,
- Representer.represent_str)
-
-Representer.add_representer(unicode,
- Representer.represent_unicode)
-
-Representer.add_representer(long,
- Representer.represent_long)
-
-Representer.add_representer(complex,
- Representer.represent_complex)
-
-Representer.add_representer(tuple,
- Representer.represent_tuple)
-
-Representer.add_representer(type,
- Representer.represent_name)
-
-Representer.add_representer(types.ClassType,
- Representer.represent_name)
-
-Representer.add_representer(types.FunctionType,
- Representer.represent_name)
-
-Representer.add_representer(types.BuiltinFunctionType,
- Representer.represent_name)
-
-Representer.add_representer(types.ModuleType,
- Representer.represent_module)
-
-Representer.add_multi_representer(types.InstanceType,
- Representer.represent_instance)
-
-Representer.add_multi_representer(object,
- Representer.represent_object)
-
+ reduce = (list(reduce)+[None]*5)[:5]
+ function, args, state, listitems, dictitems = reduce
+ args = list(args)
+ if state is None:
+ state = {}
+ if listitems is not None:
+ listitems = list(listitems)
+ if dictitems is not None:
+ dictitems = dict(dictitems)
+ if function.__name__ == '__newobj__':
+ function = args[0]
+ args = args[1:]
+ tag = u'tag:yaml.org,2002:python/object/new:'
+ newobj = True
+ else:
+ tag = u'tag:yaml.org,2002:python/object/apply:'
+ newobj = False
+ function_name = u'%s.%s' % (function.__module__, function.__name__)
+ if not args and not listitems and not dictitems \
+ and isinstance(state, dict) and newobj:
+ return self.represent_mapping(
+ u'tag:yaml.org,2002:python/object:'+function_name, state)
+ if not listitems and not dictitems \
+ and isinstance(state, dict) and not state:
+ return self.represent_sequence(tag+function_name, args)
+ value = {}
+ if args:
+ value['args'] = args
+ if state or not isinstance(state, dict):
+ value['state'] = state
+ if listitems:
+ value['listitems'] = listitems
+ if dictitems:
+ value['dictitems'] = dictitems
+ return self.represent_mapping(tag+function_name, value)
+
+Representer.add_representer(str,
+ Representer.represent_str)
+
+Representer.add_representer(unicode,
+ Representer.represent_unicode)
+
+Representer.add_representer(long,
+ Representer.represent_long)
+
+Representer.add_representer(complex,
+ Representer.represent_complex)
+
+Representer.add_representer(tuple,
+ Representer.represent_tuple)
+
+Representer.add_representer(type,
+ Representer.represent_name)
+
+Representer.add_representer(types.ClassType,
+ Representer.represent_name)
+
+Representer.add_representer(types.FunctionType,
+ Representer.represent_name)
+
+Representer.add_representer(types.BuiltinFunctionType,
+ Representer.represent_name)
+
+Representer.add_representer(types.ModuleType,
+ Representer.represent_module)
+
+Representer.add_multi_representer(types.InstanceType,
+ Representer.represent_instance)
+
+Representer.add_multi_representer(object,
+ Representer.represent_object)
+
diff --git a/contrib/python/PyYAML/py2/yaml/resolver.py b/contrib/python/PyYAML/py2/yaml/resolver.py
index a665d04bcf..ba9aeab21d 100644
--- a/contrib/python/PyYAML/py2/yaml/resolver.py
+++ b/contrib/python/PyYAML/py2/yaml/resolver.py
@@ -1,227 +1,227 @@
-
-__all__ = ['BaseResolver', 'Resolver']
-
-from error import *
-from nodes import *
-
-import re
-
-class ResolverError(YAMLError):
- pass
-
-class BaseResolver(object):
-
- DEFAULT_SCALAR_TAG = u'tag:yaml.org,2002:str'
- DEFAULT_SEQUENCE_TAG = u'tag:yaml.org,2002:seq'
- DEFAULT_MAPPING_TAG = u'tag:yaml.org,2002:map'
-
- yaml_implicit_resolvers = {}
- yaml_path_resolvers = {}
-
- def __init__(self):
- self.resolver_exact_paths = []
- self.resolver_prefix_paths = []
-
- def add_implicit_resolver(cls, tag, regexp, first):
- if not 'yaml_implicit_resolvers' in cls.__dict__:
+
+__all__ = ['BaseResolver', 'Resolver']
+
+from error import *
+from nodes import *
+
+import re
+
+class ResolverError(YAMLError):
+ pass
+
+class BaseResolver(object):
+
+ DEFAULT_SCALAR_TAG = u'tag:yaml.org,2002:str'
+ DEFAULT_SEQUENCE_TAG = u'tag:yaml.org,2002:seq'
+ DEFAULT_MAPPING_TAG = u'tag:yaml.org,2002:map'
+
+ yaml_implicit_resolvers = {}
+ yaml_path_resolvers = {}
+
+ def __init__(self):
+ self.resolver_exact_paths = []
+ self.resolver_prefix_paths = []
+
+ def add_implicit_resolver(cls, tag, regexp, first):
+ if not 'yaml_implicit_resolvers' in cls.__dict__:
implicit_resolvers = {}
for key in cls.yaml_implicit_resolvers:
implicit_resolvers[key] = cls.yaml_implicit_resolvers[key][:]
cls.yaml_implicit_resolvers = implicit_resolvers
- if first is None:
- first = [None]
- for ch in first:
- cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp))
- add_implicit_resolver = classmethod(add_implicit_resolver)
-
- def add_path_resolver(cls, tag, path, kind=None):
- # Note: `add_path_resolver` is experimental. The API could be changed.
- # `new_path` is a pattern that is matched against the path from the
- # root to the node that is being considered. `node_path` elements are
- # tuples `(node_check, index_check)`. `node_check` is a node class:
- # `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None`
- # matches any kind of a node. `index_check` could be `None`, a boolean
- # value, a string value, or a number. `None` and `False` match against
- # any _value_ of sequence and mapping nodes. `True` matches against
- # any _key_ of a mapping node. A string `index_check` matches against
- # a mapping value that corresponds to a scalar key which content is
- # equal to the `index_check` value. An integer `index_check` matches
- # against a sequence value with the index equal to `index_check`.
- if not 'yaml_path_resolvers' in cls.__dict__:
- cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy()
- new_path = []
- for element in path:
- if isinstance(element, (list, tuple)):
- if len(element) == 2:
- node_check, index_check = element
- elif len(element) == 1:
- node_check = element[0]
- index_check = True
- else:
- raise ResolverError("Invalid path element: %s" % element)
- else:
- node_check = None
- index_check = element
- if node_check is str:
- node_check = ScalarNode
- elif node_check is list:
- node_check = SequenceNode
- elif node_check is dict:
- node_check = MappingNode
- elif node_check not in [ScalarNode, SequenceNode, MappingNode] \
- and not isinstance(node_check, basestring) \
- and node_check is not None:
- raise ResolverError("Invalid node checker: %s" % node_check)
- if not isinstance(index_check, (basestring, int)) \
- and index_check is not None:
- raise ResolverError("Invalid index checker: %s" % index_check)
- new_path.append((node_check, index_check))
- if kind is str:
- kind = ScalarNode
- elif kind is list:
- kind = SequenceNode
- elif kind is dict:
- kind = MappingNode
- elif kind not in [ScalarNode, SequenceNode, MappingNode] \
- and kind is not None:
- raise ResolverError("Invalid node kind: %s" % kind)
- cls.yaml_path_resolvers[tuple(new_path), kind] = tag
- add_path_resolver = classmethod(add_path_resolver)
-
- def descend_resolver(self, current_node, current_index):
- if not self.yaml_path_resolvers:
- return
- exact_paths = {}
- prefix_paths = []
- if current_node:
- depth = len(self.resolver_prefix_paths)
- for path, kind in self.resolver_prefix_paths[-1]:
- if self.check_resolver_prefix(depth, path, kind,
- current_node, current_index):
- if len(path) > depth:
- prefix_paths.append((path, kind))
- else:
- exact_paths[kind] = self.yaml_path_resolvers[path, kind]
- else:
- for path, kind in self.yaml_path_resolvers:
- if not path:
- exact_paths[kind] = self.yaml_path_resolvers[path, kind]
- else:
- prefix_paths.append((path, kind))
- self.resolver_exact_paths.append(exact_paths)
- self.resolver_prefix_paths.append(prefix_paths)
-
- def ascend_resolver(self):
- if not self.yaml_path_resolvers:
- return
- self.resolver_exact_paths.pop()
- self.resolver_prefix_paths.pop()
-
- def check_resolver_prefix(self, depth, path, kind,
- current_node, current_index):
- node_check, index_check = path[depth-1]
- if isinstance(node_check, basestring):
- if current_node.tag != node_check:
- return
- elif node_check is not None:
- if not isinstance(current_node, node_check):
- return
- if index_check is True and current_index is not None:
- return
- if (index_check is False or index_check is None) \
- and current_index is None:
- return
- if isinstance(index_check, basestring):
- if not (isinstance(current_index, ScalarNode)
- and index_check == current_index.value):
- return
- elif isinstance(index_check, int) and not isinstance(index_check, bool):
- if index_check != current_index:
- return
- return True
-
- def resolve(self, kind, value, implicit):
- if kind is ScalarNode and implicit[0]:
- if value == u'':
- resolvers = self.yaml_implicit_resolvers.get(u'', [])
- else:
- resolvers = self.yaml_implicit_resolvers.get(value[0], [])
+ if first is None:
+ first = [None]
+ for ch in first:
+ cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp))
+ add_implicit_resolver = classmethod(add_implicit_resolver)
+
+ def add_path_resolver(cls, tag, path, kind=None):
+ # Note: `add_path_resolver` is experimental. The API could be changed.
+ # `new_path` is a pattern that is matched against the path from the
+ # root to the node that is being considered. `node_path` elements are
+ # tuples `(node_check, index_check)`. `node_check` is a node class:
+ # `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None`
+ # matches any kind of a node. `index_check` could be `None`, a boolean
+ # value, a string value, or a number. `None` and `False` match against
+ # any _value_ of sequence and mapping nodes. `True` matches against
+ # any _key_ of a mapping node. A string `index_check` matches against
+ # a mapping value that corresponds to a scalar key which content is
+ # equal to the `index_check` value. An integer `index_check` matches
+ # against a sequence value with the index equal to `index_check`.
+ if not 'yaml_path_resolvers' in cls.__dict__:
+ cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy()
+ new_path = []
+ for element in path:
+ if isinstance(element, (list, tuple)):
+ if len(element) == 2:
+ node_check, index_check = element
+ elif len(element) == 1:
+ node_check = element[0]
+ index_check = True
+ else:
+ raise ResolverError("Invalid path element: %s" % element)
+ else:
+ node_check = None
+ index_check = element
+ if node_check is str:
+ node_check = ScalarNode
+ elif node_check is list:
+ node_check = SequenceNode
+ elif node_check is dict:
+ node_check = MappingNode
+ elif node_check not in [ScalarNode, SequenceNode, MappingNode] \
+ and not isinstance(node_check, basestring) \
+ and node_check is not None:
+ raise ResolverError("Invalid node checker: %s" % node_check)
+ if not isinstance(index_check, (basestring, int)) \
+ and index_check is not None:
+ raise ResolverError("Invalid index checker: %s" % index_check)
+ new_path.append((node_check, index_check))
+ if kind is str:
+ kind = ScalarNode
+ elif kind is list:
+ kind = SequenceNode
+ elif kind is dict:
+ kind = MappingNode
+ elif kind not in [ScalarNode, SequenceNode, MappingNode] \
+ and kind is not None:
+ raise ResolverError("Invalid node kind: %s" % kind)
+ cls.yaml_path_resolvers[tuple(new_path), kind] = tag
+ add_path_resolver = classmethod(add_path_resolver)
+
+ def descend_resolver(self, current_node, current_index):
+ if not self.yaml_path_resolvers:
+ return
+ exact_paths = {}
+ prefix_paths = []
+ if current_node:
+ depth = len(self.resolver_prefix_paths)
+ for path, kind in self.resolver_prefix_paths[-1]:
+ if self.check_resolver_prefix(depth, path, kind,
+ current_node, current_index):
+ if len(path) > depth:
+ prefix_paths.append((path, kind))
+ else:
+ exact_paths[kind] = self.yaml_path_resolvers[path, kind]
+ else:
+ for path, kind in self.yaml_path_resolvers:
+ if not path:
+ exact_paths[kind] = self.yaml_path_resolvers[path, kind]
+ else:
+ prefix_paths.append((path, kind))
+ self.resolver_exact_paths.append(exact_paths)
+ self.resolver_prefix_paths.append(prefix_paths)
+
+ def ascend_resolver(self):
+ if not self.yaml_path_resolvers:
+ return
+ self.resolver_exact_paths.pop()
+ self.resolver_prefix_paths.pop()
+
+ def check_resolver_prefix(self, depth, path, kind,
+ current_node, current_index):
+ node_check, index_check = path[depth-1]
+ if isinstance(node_check, basestring):
+ if current_node.tag != node_check:
+ return
+ elif node_check is not None:
+ if not isinstance(current_node, node_check):
+ return
+ if index_check is True and current_index is not None:
+ return
+ if (index_check is False or index_check is None) \
+ and current_index is None:
+ return
+ if isinstance(index_check, basestring):
+ if not (isinstance(current_index, ScalarNode)
+ and index_check == current_index.value):
+ return
+ elif isinstance(index_check, int) and not isinstance(index_check, bool):
+ if index_check != current_index:
+ return
+ return True
+
+ def resolve(self, kind, value, implicit):
+ if kind is ScalarNode and implicit[0]:
+ if value == u'':
+ resolvers = self.yaml_implicit_resolvers.get(u'', [])
+ else:
+ resolvers = self.yaml_implicit_resolvers.get(value[0], [])
wildcard_resolvers = self.yaml_implicit_resolvers.get(None, [])
for tag, regexp in resolvers + wildcard_resolvers:
- if regexp.match(value):
- return tag
- implicit = implicit[1]
- if self.yaml_path_resolvers:
- exact_paths = self.resolver_exact_paths[-1]
- if kind in exact_paths:
- return exact_paths[kind]
- if None in exact_paths:
- return exact_paths[None]
- if kind is ScalarNode:
- return self.DEFAULT_SCALAR_TAG
- elif kind is SequenceNode:
- return self.DEFAULT_SEQUENCE_TAG
- elif kind is MappingNode:
- return self.DEFAULT_MAPPING_TAG
-
-class Resolver(BaseResolver):
- pass
-
-Resolver.add_implicit_resolver(
- u'tag:yaml.org,2002:bool',
- re.compile(ur'''^(?:yes|Yes|YES|no|No|NO
- |true|True|TRUE|false|False|FALSE
- |on|On|ON|off|Off|OFF)$''', re.X),
- list(u'yYnNtTfFoO'))
-
-Resolver.add_implicit_resolver(
- u'tag:yaml.org,2002:float',
- re.compile(ur'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?
- |\.[0-9_]+(?:[eE][-+][0-9]+)?
- |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
- |[-+]?\.(?:inf|Inf|INF)
- |\.(?:nan|NaN|NAN))$''', re.X),
- list(u'-+0123456789.'))
-
-Resolver.add_implicit_resolver(
- u'tag:yaml.org,2002:int',
- re.compile(ur'''^(?:[-+]?0b[0-1_]+
- |[-+]?0[0-7_]+
- |[-+]?(?:0|[1-9][0-9_]*)
- |[-+]?0x[0-9a-fA-F_]+
- |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X),
- list(u'-+0123456789'))
-
-Resolver.add_implicit_resolver(
- u'tag:yaml.org,2002:merge',
- re.compile(ur'^(?:<<)$'),
- [u'<'])
-
-Resolver.add_implicit_resolver(
- u'tag:yaml.org,2002:null',
- re.compile(ur'''^(?: ~
- |null|Null|NULL
- | )$''', re.X),
- [u'~', u'n', u'N', u''])
-
-Resolver.add_implicit_resolver(
- u'tag:yaml.org,2002:timestamp',
- re.compile(ur'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
- |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]?
- (?:[Tt]|[ \t]+)[0-9][0-9]?
- :[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)?
- (?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X),
- list(u'0123456789'))
-
-Resolver.add_implicit_resolver(
- u'tag:yaml.org,2002:value',
- re.compile(ur'^(?:=)$'),
- [u'='])
-
-# The following resolver is only for documentation purposes. It cannot work
-# because plain scalars cannot start with '!', '&', or '*'.
-Resolver.add_implicit_resolver(
- u'tag:yaml.org,2002:yaml',
- re.compile(ur'^(?:!|&|\*)$'),
- list(u'!&*'))
-
+ if regexp.match(value):
+ return tag
+ implicit = implicit[1]
+ if self.yaml_path_resolvers:
+ exact_paths = self.resolver_exact_paths[-1]
+ if kind in exact_paths:
+ return exact_paths[kind]
+ if None in exact_paths:
+ return exact_paths[None]
+ if kind is ScalarNode:
+ return self.DEFAULT_SCALAR_TAG
+ elif kind is SequenceNode:
+ return self.DEFAULT_SEQUENCE_TAG
+ elif kind is MappingNode:
+ return self.DEFAULT_MAPPING_TAG
+
+class Resolver(BaseResolver):
+ pass
+
+Resolver.add_implicit_resolver(
+ u'tag:yaml.org,2002:bool',
+ re.compile(ur'''^(?:yes|Yes|YES|no|No|NO
+ |true|True|TRUE|false|False|FALSE
+ |on|On|ON|off|Off|OFF)$''', re.X),
+ list(u'yYnNtTfFoO'))
+
+Resolver.add_implicit_resolver(
+ u'tag:yaml.org,2002:float',
+ re.compile(ur'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?
+ |\.[0-9_]+(?:[eE][-+][0-9]+)?
+ |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
+ |[-+]?\.(?:inf|Inf|INF)
+ |\.(?:nan|NaN|NAN))$''', re.X),
+ list(u'-+0123456789.'))
+
+Resolver.add_implicit_resolver(
+ u'tag:yaml.org,2002:int',
+ re.compile(ur'''^(?:[-+]?0b[0-1_]+
+ |[-+]?0[0-7_]+
+ |[-+]?(?:0|[1-9][0-9_]*)
+ |[-+]?0x[0-9a-fA-F_]+
+ |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X),
+ list(u'-+0123456789'))
+
+Resolver.add_implicit_resolver(
+ u'tag:yaml.org,2002:merge',
+ re.compile(ur'^(?:<<)$'),
+ [u'<'])
+
+Resolver.add_implicit_resolver(
+ u'tag:yaml.org,2002:null',
+ re.compile(ur'''^(?: ~
+ |null|Null|NULL
+ | )$''', re.X),
+ [u'~', u'n', u'N', u''])
+
+Resolver.add_implicit_resolver(
+ u'tag:yaml.org,2002:timestamp',
+ re.compile(ur'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
+ |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]?
+ (?:[Tt]|[ \t]+)[0-9][0-9]?
+ :[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)?
+ (?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X),
+ list(u'0123456789'))
+
+Resolver.add_implicit_resolver(
+ u'tag:yaml.org,2002:value',
+ re.compile(ur'^(?:=)$'),
+ [u'='])
+
+# The following resolver is only for documentation purposes. It cannot work
+# because plain scalars cannot start with '!', '&', or '*'.
+Resolver.add_implicit_resolver(
+ u'tag:yaml.org,2002:yaml',
+ re.compile(ur'^(?:!|&|\*)$'),
+ list(u'!&*'))
+
diff --git a/contrib/python/PyYAML/py2/yaml/scanner.py b/contrib/python/PyYAML/py2/yaml/scanner.py
index a307d9a55a..587b73d8b4 100644
--- a/contrib/python/PyYAML/py2/yaml/scanner.py
+++ b/contrib/python/PyYAML/py2/yaml/scanner.py
@@ -1,1449 +1,1449 @@
-
-# Scanner produces tokens of the following types:
-# STREAM-START
-# STREAM-END
-# DIRECTIVE(name, value)
-# DOCUMENT-START
-# DOCUMENT-END
-# BLOCK-SEQUENCE-START
-# BLOCK-MAPPING-START
-# BLOCK-END
-# FLOW-SEQUENCE-START
-# FLOW-MAPPING-START
-# FLOW-SEQUENCE-END
-# FLOW-MAPPING-END
-# BLOCK-ENTRY
-# FLOW-ENTRY
-# KEY
-# VALUE
-# ALIAS(value)
-# ANCHOR(value)
-# TAG(value)
-# SCALAR(value, plain, style)
-#
-# Read comments in the Scanner code for more details.
-#
-
-__all__ = ['Scanner', 'ScannerError']
-
+
+# Scanner produces tokens of the following types:
+# STREAM-START
+# STREAM-END
+# DIRECTIVE(name, value)
+# DOCUMENT-START
+# DOCUMENT-END
+# BLOCK-SEQUENCE-START
+# BLOCK-MAPPING-START
+# BLOCK-END
+# FLOW-SEQUENCE-START
+# FLOW-MAPPING-START
+# FLOW-SEQUENCE-END
+# FLOW-MAPPING-END
+# BLOCK-ENTRY
+# FLOW-ENTRY
+# KEY
+# VALUE
+# ALIAS(value)
+# ANCHOR(value)
+# TAG(value)
+# SCALAR(value, plain, style)
+#
+# Read comments in the Scanner code for more details.
+#
+
+__all__ = ['Scanner', 'ScannerError']
+
import sys
-from error import MarkedYAMLError
-from tokens import *
-
-class ScannerError(MarkedYAMLError):
- pass
-
-class SimpleKey(object):
- # See below simple keys treatment.
-
- def __init__(self, token_number, required, index, line, column, mark):
- self.token_number = token_number
- self.required = required
- self.index = index
- self.line = line
- self.column = column
- self.mark = mark
-
-class Scanner(object):
-
- def __init__(self):
- """Initialize the scanner."""
- # It is assumed that Scanner and Reader will have a common descendant.
- # Reader do the dirty work of checking for BOM and converting the
- # input data to Unicode. It also adds NUL to the end.
- #
- # Reader supports the following methods
- # self.peek(i=0) # peek the next i-th character
- # self.prefix(l=1) # peek the next l characters
- # self.forward(l=1) # read the next l characters and move the pointer.
-
- # Had we reached the end of the stream?
- self.done = False
-
- # The number of unclosed '{' and '['. `flow_level == 0` means block
- # context.
- self.flow_level = 0
-
- # List of processed tokens that are not yet emitted.
- self.tokens = []
-
- # Add the STREAM-START token.
- self.fetch_stream_start()
-
- # Number of tokens that were emitted through the `get_token` method.
- self.tokens_taken = 0
-
- # The current indentation level.
- self.indent = -1
-
- # Past indentation levels.
- self.indents = []
-
- # Variables related to simple keys treatment.
-
- # A simple key is a key that is not denoted by the '?' indicator.
- # Example of simple keys:
- # ---
- # block simple key: value
- # ? not a simple key:
- # : { flow simple key: value }
- # We emit the KEY token before all keys, so when we find a potential
- # simple key, we try to locate the corresponding ':' indicator.
- # Simple keys should be limited to a single line and 1024 characters.
-
- # Can a simple key start at the current position? A simple key may
- # start:
- # - at the beginning of the line, not counting indentation spaces
- # (in block context),
- # - after '{', '[', ',' (in the flow context),
- # - after '?', ':', '-' (in the block context).
- # In the block context, this flag also signifies if a block collection
- # may start at the current position.
- self.allow_simple_key = True
-
- # Keep track of possible simple keys. This is a dictionary. The key
- # is `flow_level`; there can be no more that one possible simple key
- # for each level. The value is a SimpleKey record:
- # (token_number, required, index, line, column, mark)
- # A simple key may start with ALIAS, ANCHOR, TAG, SCALAR(flow),
- # '[', or '{' tokens.
- self.possible_simple_keys = {}
-
- # Public methods.
-
- def check_token(self, *choices):
- # Check if the next token is one of the given types.
- while self.need_more_tokens():
- self.fetch_more_tokens()
- if self.tokens:
- if not choices:
- return True
- for choice in choices:
- if isinstance(self.tokens[0], choice):
- return True
- return False
-
- def peek_token(self):
- # Return the next token, but do not delete if from the queue.
+from error import MarkedYAMLError
+from tokens import *
+
+class ScannerError(MarkedYAMLError):
+ pass
+
+class SimpleKey(object):
+ # See below simple keys treatment.
+
+ def __init__(self, token_number, required, index, line, column, mark):
+ self.token_number = token_number
+ self.required = required
+ self.index = index
+ self.line = line
+ self.column = column
+ self.mark = mark
+
+class Scanner(object):
+
+ def __init__(self):
+ """Initialize the scanner."""
+ # It is assumed that Scanner and Reader will have a common descendant.
+ # Reader do the dirty work of checking for BOM and converting the
+ # input data to Unicode. It also adds NUL to the end.
+ #
+ # Reader supports the following methods
+ # self.peek(i=0) # peek the next i-th character
+ # self.prefix(l=1) # peek the next l characters
+ # self.forward(l=1) # read the next l characters and move the pointer.
+
+ # Had we reached the end of the stream?
+ self.done = False
+
+ # The number of unclosed '{' and '['. `flow_level == 0` means block
+ # context.
+ self.flow_level = 0
+
+ # List of processed tokens that are not yet emitted.
+ self.tokens = []
+
+ # Add the STREAM-START token.
+ self.fetch_stream_start()
+
+ # Number of tokens that were emitted through the `get_token` method.
+ self.tokens_taken = 0
+
+ # The current indentation level.
+ self.indent = -1
+
+ # Past indentation levels.
+ self.indents = []
+
+ # Variables related to simple keys treatment.
+
+ # A simple key is a key that is not denoted by the '?' indicator.
+ # Example of simple keys:
+ # ---
+ # block simple key: value
+ # ? not a simple key:
+ # : { flow simple key: value }
+ # We emit the KEY token before all keys, so when we find a potential
+ # simple key, we try to locate the corresponding ':' indicator.
+ # Simple keys should be limited to a single line and 1024 characters.
+
+ # Can a simple key start at the current position? A simple key may
+ # start:
+ # - at the beginning of the line, not counting indentation spaces
+ # (in block context),
+ # - after '{', '[', ',' (in the flow context),
+ # - after '?', ':', '-' (in the block context).
+ # In the block context, this flag also signifies if a block collection
+ # may start at the current position.
+ self.allow_simple_key = True
+
+ # Keep track of possible simple keys. This is a dictionary. The key
+ # is `flow_level`; there can be no more that one possible simple key
+ # for each level. The value is a SimpleKey record:
+ # (token_number, required, index, line, column, mark)
+ # A simple key may start with ALIAS, ANCHOR, TAG, SCALAR(flow),
+ # '[', or '{' tokens.
+ self.possible_simple_keys = {}
+
+ # Public methods.
+
+ def check_token(self, *choices):
+ # Check if the next token is one of the given types.
+ while self.need_more_tokens():
+ self.fetch_more_tokens()
+ if self.tokens:
+ if not choices:
+ return True
+ for choice in choices:
+ if isinstance(self.tokens[0], choice):
+ return True
+ return False
+
+ def peek_token(self):
+ # Return the next token, but do not delete if from the queue.
# Return None if no more tokens.
- while self.need_more_tokens():
- self.fetch_more_tokens()
- if self.tokens:
- return self.tokens[0]
+ while self.need_more_tokens():
+ self.fetch_more_tokens()
+ if self.tokens:
+ return self.tokens[0]
else:
return None
-
- def get_token(self):
- # Return the next token.
- while self.need_more_tokens():
- self.fetch_more_tokens()
- if self.tokens:
- self.tokens_taken += 1
- return self.tokens.pop(0)
-
- # Private methods.
-
- def need_more_tokens(self):
- if self.done:
- return False
- if not self.tokens:
- return True
- # The current token may be a potential simple key, so we
- # need to look further.
- self.stale_possible_simple_keys()
- if self.next_possible_simple_key() == self.tokens_taken:
- return True
-
- def fetch_more_tokens(self):
-
- # Eat whitespaces and comments until we reach the next token.
- self.scan_to_next_token()
-
- # Remove obsolete possible simple keys.
- self.stale_possible_simple_keys()
-
- # Compare the current indentation and column. It may add some tokens
- # and decrease the current indentation level.
- self.unwind_indent(self.column)
-
- # Peek the next character.
- ch = self.peek()
-
- # Is it the end of stream?
- if ch == u'\0':
- return self.fetch_stream_end()
-
- # Is it a directive?
- if ch == u'%' and self.check_directive():
- return self.fetch_directive()
-
- # Is it the document start?
- if ch == u'-' and self.check_document_start():
- return self.fetch_document_start()
-
- # Is it the document end?
- if ch == u'.' and self.check_document_end():
- return self.fetch_document_end()
-
- # TODO: support for BOM within a stream.
- #if ch == u'\uFEFF':
- # return self.fetch_bom() <-- issue BOMToken
-
- # Note: the order of the following checks is NOT significant.
-
- # Is it the flow sequence start indicator?
- if ch == u'[':
- return self.fetch_flow_sequence_start()
-
- # Is it the flow mapping start indicator?
- if ch == u'{':
- return self.fetch_flow_mapping_start()
-
- # Is it the flow sequence end indicator?
- if ch == u']':
- return self.fetch_flow_sequence_end()
-
- # Is it the flow mapping end indicator?
- if ch == u'}':
- return self.fetch_flow_mapping_end()
-
- # Is it the flow entry indicator?
- if ch == u',':
- return self.fetch_flow_entry()
-
- # Is it the block entry indicator?
- if ch == u'-' and self.check_block_entry():
- return self.fetch_block_entry()
-
- # Is it the key indicator?
- if ch == u'?' and self.check_key():
- return self.fetch_key()
-
- # Is it the value indicator?
- if ch == u':' and self.check_value():
- return self.fetch_value()
-
- # Is it an alias?
- if ch == u'*':
- return self.fetch_alias()
-
- # Is it an anchor?
- if ch == u'&':
- return self.fetch_anchor()
-
- # Is it a tag?
- if ch == u'!':
- return self.fetch_tag()
-
- # Is it a literal scalar?
- if ch == u'|' and not self.flow_level:
- return self.fetch_literal()
-
- # Is it a folded scalar?
- if ch == u'>' and not self.flow_level:
- return self.fetch_folded()
-
- # Is it a single quoted scalar?
- if ch == u'\'':
- return self.fetch_single()
-
- # Is it a double quoted scalar?
- if ch == u'\"':
- return self.fetch_double()
-
- # It must be a plain scalar then.
- if self.check_plain():
- return self.fetch_plain()
-
- # No? It's an error. Let's produce a nice error message.
- raise ScannerError("while scanning for the next token", None,
- "found character %r that cannot start any token"
- % ch.encode('utf-8'), self.get_mark())
-
- # Simple keys treatment.
-
- def next_possible_simple_key(self):
- # Return the number of the nearest possible simple key. Actually we
- # don't need to loop through the whole dictionary. We may replace it
- # with the following code:
- # if not self.possible_simple_keys:
- # return None
- # return self.possible_simple_keys[
- # min(self.possible_simple_keys.keys())].token_number
- min_token_number = None
- for level in self.possible_simple_keys:
- key = self.possible_simple_keys[level]
- if min_token_number is None or key.token_number < min_token_number:
- min_token_number = key.token_number
- return min_token_number
-
- def stale_possible_simple_keys(self):
- # Remove entries that are no longer possible simple keys. According to
- # the YAML specification, simple keys
- # - should be limited to a single line,
- # - should be no longer than 1024 characters.
- # Disabling this procedure will allow simple keys of any length and
- # height (may cause problems if indentation is broken though).
- for level in self.possible_simple_keys.keys():
- key = self.possible_simple_keys[level]
- if key.line != self.line \
- or self.index-key.index > 1024:
- if key.required:
- raise ScannerError("while scanning a simple key", key.mark,
+
+ def get_token(self):
+ # Return the next token.
+ while self.need_more_tokens():
+ self.fetch_more_tokens()
+ if self.tokens:
+ self.tokens_taken += 1
+ return self.tokens.pop(0)
+
+ # Private methods.
+
+ def need_more_tokens(self):
+ if self.done:
+ return False
+ if not self.tokens:
+ return True
+ # The current token may be a potential simple key, so we
+ # need to look further.
+ self.stale_possible_simple_keys()
+ if self.next_possible_simple_key() == self.tokens_taken:
+ return True
+
+ def fetch_more_tokens(self):
+
+ # Eat whitespaces and comments until we reach the next token.
+ self.scan_to_next_token()
+
+ # Remove obsolete possible simple keys.
+ self.stale_possible_simple_keys()
+
+ # Compare the current indentation and column. It may add some tokens
+ # and decrease the current indentation level.
+ self.unwind_indent(self.column)
+
+ # Peek the next character.
+ ch = self.peek()
+
+ # Is it the end of stream?
+ if ch == u'\0':
+ return self.fetch_stream_end()
+
+ # Is it a directive?
+ if ch == u'%' and self.check_directive():
+ return self.fetch_directive()
+
+ # Is it the document start?
+ if ch == u'-' and self.check_document_start():
+ return self.fetch_document_start()
+
+ # Is it the document end?
+ if ch == u'.' and self.check_document_end():
+ return self.fetch_document_end()
+
+ # TODO: support for BOM within a stream.
+ #if ch == u'\uFEFF':
+ # return self.fetch_bom() <-- issue BOMToken
+
+ # Note: the order of the following checks is NOT significant.
+
+ # Is it the flow sequence start indicator?
+ if ch == u'[':
+ return self.fetch_flow_sequence_start()
+
+ # Is it the flow mapping start indicator?
+ if ch == u'{':
+ return self.fetch_flow_mapping_start()
+
+ # Is it the flow sequence end indicator?
+ if ch == u']':
+ return self.fetch_flow_sequence_end()
+
+ # Is it the flow mapping end indicator?
+ if ch == u'}':
+ return self.fetch_flow_mapping_end()
+
+ # Is it the flow entry indicator?
+ if ch == u',':
+ return self.fetch_flow_entry()
+
+ # Is it the block entry indicator?
+ if ch == u'-' and self.check_block_entry():
+ return self.fetch_block_entry()
+
+ # Is it the key indicator?
+ if ch == u'?' and self.check_key():
+ return self.fetch_key()
+
+ # Is it the value indicator?
+ if ch == u':' and self.check_value():
+ return self.fetch_value()
+
+ # Is it an alias?
+ if ch == u'*':
+ return self.fetch_alias()
+
+ # Is it an anchor?
+ if ch == u'&':
+ return self.fetch_anchor()
+
+ # Is it a tag?
+ if ch == u'!':
+ return self.fetch_tag()
+
+ # Is it a literal scalar?
+ if ch == u'|' and not self.flow_level:
+ return self.fetch_literal()
+
+ # Is it a folded scalar?
+ if ch == u'>' and not self.flow_level:
+ return self.fetch_folded()
+
+ # Is it a single quoted scalar?
+ if ch == u'\'':
+ return self.fetch_single()
+
+ # Is it a double quoted scalar?
+ if ch == u'\"':
+ return self.fetch_double()
+
+ # It must be a plain scalar then.
+ if self.check_plain():
+ return self.fetch_plain()
+
+ # No? It's an error. Let's produce a nice error message.
+ raise ScannerError("while scanning for the next token", None,
+ "found character %r that cannot start any token"
+ % ch.encode('utf-8'), self.get_mark())
+
+ # Simple keys treatment.
+
+ def next_possible_simple_key(self):
+ # Return the number of the nearest possible simple key. Actually we
+ # don't need to loop through the whole dictionary. We may replace it
+ # with the following code:
+ # if not self.possible_simple_keys:
+ # return None
+ # return self.possible_simple_keys[
+ # min(self.possible_simple_keys.keys())].token_number
+ min_token_number = None
+ for level in self.possible_simple_keys:
+ key = self.possible_simple_keys[level]
+ if min_token_number is None or key.token_number < min_token_number:
+ min_token_number = key.token_number
+ return min_token_number
+
+ def stale_possible_simple_keys(self):
+ # Remove entries that are no longer possible simple keys. According to
+ # the YAML specification, simple keys
+ # - should be limited to a single line,
+ # - should be no longer than 1024 characters.
+ # Disabling this procedure will allow simple keys of any length and
+ # height (may cause problems if indentation is broken though).
+ for level in self.possible_simple_keys.keys():
+ key = self.possible_simple_keys[level]
+ if key.line != self.line \
+ or self.index-key.index > 1024:
+ if key.required:
+ raise ScannerError("while scanning a simple key", key.mark,
"could not find expected ':'", self.get_mark())
- del self.possible_simple_keys[level]
-
- def save_possible_simple_key(self):
- # The next token may start a simple key. We check if it's possible
- # and save its position. This function is called for
- # ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'.
-
- # Check if a simple key is required at the current position.
- required = not self.flow_level and self.indent == self.column
-
- # The next token might be a simple key. Let's save it's number and
- # position.
- if self.allow_simple_key:
- self.remove_possible_simple_key()
- token_number = self.tokens_taken+len(self.tokens)
- key = SimpleKey(token_number, required,
- self.index, self.line, self.column, self.get_mark())
- self.possible_simple_keys[self.flow_level] = key
-
- def remove_possible_simple_key(self):
- # Remove the saved possible key position at the current flow level.
- if self.flow_level in self.possible_simple_keys:
- key = self.possible_simple_keys[self.flow_level]
-
- if key.required:
- raise ScannerError("while scanning a simple key", key.mark,
+ del self.possible_simple_keys[level]
+
+ def save_possible_simple_key(self):
+ # The next token may start a simple key. We check if it's possible
+ # and save its position. This function is called for
+ # ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'.
+
+ # Check if a simple key is required at the current position.
+ required = not self.flow_level and self.indent == self.column
+
+ # The next token might be a simple key. Let's save it's number and
+ # position.
+ if self.allow_simple_key:
+ self.remove_possible_simple_key()
+ token_number = self.tokens_taken+len(self.tokens)
+ key = SimpleKey(token_number, required,
+ self.index, self.line, self.column, self.get_mark())
+ self.possible_simple_keys[self.flow_level] = key
+
+ def remove_possible_simple_key(self):
+ # Remove the saved possible key position at the current flow level.
+ if self.flow_level in self.possible_simple_keys:
+ key = self.possible_simple_keys[self.flow_level]
+
+ if key.required:
+ raise ScannerError("while scanning a simple key", key.mark,
"could not find expected ':'", self.get_mark())
-
- del self.possible_simple_keys[self.flow_level]
-
- # Indentation functions.
-
- def unwind_indent(self, column):
-
- ## In flow context, tokens should respect indentation.
- ## Actually the condition should be `self.indent >= column` according to
- ## the spec. But this condition will prohibit intuitively correct
- ## constructions such as
- ## key : {
- ## }
- #if self.flow_level and self.indent > column:
- # raise ScannerError(None, None,
+
+ del self.possible_simple_keys[self.flow_level]
+
+ # Indentation functions.
+
+ def unwind_indent(self, column):
+
+ ## In flow context, tokens should respect indentation.
+ ## Actually the condition should be `self.indent >= column` according to
+ ## the spec. But this condition will prohibit intuitively correct
+ ## constructions such as
+ ## key : {
+ ## }
+ #if self.flow_level and self.indent > column:
+ # raise ScannerError(None, None,
# "invalid indentation or unclosed '[' or '{'",
- # self.get_mark())
-
- # In the flow context, indentation is ignored. We make the scanner less
- # restrictive then specification requires.
- if self.flow_level:
- return
-
- # In block context, we may need to issue the BLOCK-END tokens.
- while self.indent > column:
- mark = self.get_mark()
- self.indent = self.indents.pop()
- self.tokens.append(BlockEndToken(mark, mark))
-
- def add_indent(self, column):
- # Check if we need to increase indentation.
- if self.indent < column:
- self.indents.append(self.indent)
- self.indent = column
- return True
- return False
-
- # Fetchers.
-
- def fetch_stream_start(self):
- # We always add STREAM-START as the first token and STREAM-END as the
- # last token.
-
- # Read the token.
- mark = self.get_mark()
-
- # Add STREAM-START.
- self.tokens.append(StreamStartToken(mark, mark,
- encoding=self.encoding))
-
-
- def fetch_stream_end(self):
-
+ # self.get_mark())
+
+ # In the flow context, indentation is ignored. We make the scanner less
+ # restrictive then specification requires.
+ if self.flow_level:
+ return
+
+ # In block context, we may need to issue the BLOCK-END tokens.
+ while self.indent > column:
+ mark = self.get_mark()
+ self.indent = self.indents.pop()
+ self.tokens.append(BlockEndToken(mark, mark))
+
+ def add_indent(self, column):
+ # Check if we need to increase indentation.
+ if self.indent < column:
+ self.indents.append(self.indent)
+ self.indent = column
+ return True
+ return False
+
+ # Fetchers.
+
+ def fetch_stream_start(self):
+ # We always add STREAM-START as the first token and STREAM-END as the
+ # last token.
+
+ # Read the token.
+ mark = self.get_mark()
+
+ # Add STREAM-START.
+ self.tokens.append(StreamStartToken(mark, mark,
+ encoding=self.encoding))
+
+
+ def fetch_stream_end(self):
+
# Set the current indentation to -1.
- self.unwind_indent(-1)
-
- # Reset simple keys.
- self.remove_possible_simple_key()
- self.allow_simple_key = False
- self.possible_simple_keys = {}
-
- # Read the token.
- mark = self.get_mark()
-
- # Add STREAM-END.
- self.tokens.append(StreamEndToken(mark, mark))
-
- # The steam is finished.
- self.done = True
-
- def fetch_directive(self):
-
+ self.unwind_indent(-1)
+
+ # Reset simple keys.
+ self.remove_possible_simple_key()
+ self.allow_simple_key = False
+ self.possible_simple_keys = {}
+
+ # Read the token.
+ mark = self.get_mark()
+
+ # Add STREAM-END.
+ self.tokens.append(StreamEndToken(mark, mark))
+
+ # The steam is finished.
+ self.done = True
+
+ def fetch_directive(self):
+
# Set the current indentation to -1.
- self.unwind_indent(-1)
-
- # Reset simple keys.
- self.remove_possible_simple_key()
- self.allow_simple_key = False
-
- # Scan and add DIRECTIVE.
- self.tokens.append(self.scan_directive())
-
- def fetch_document_start(self):
- self.fetch_document_indicator(DocumentStartToken)
-
- def fetch_document_end(self):
- self.fetch_document_indicator(DocumentEndToken)
-
- def fetch_document_indicator(self, TokenClass):
-
+ self.unwind_indent(-1)
+
+ # Reset simple keys.
+ self.remove_possible_simple_key()
+ self.allow_simple_key = False
+
+ # Scan and add DIRECTIVE.
+ self.tokens.append(self.scan_directive())
+
+ def fetch_document_start(self):
+ self.fetch_document_indicator(DocumentStartToken)
+
+ def fetch_document_end(self):
+ self.fetch_document_indicator(DocumentEndToken)
+
+ def fetch_document_indicator(self, TokenClass):
+
# Set the current indentation to -1.
- self.unwind_indent(-1)
-
- # Reset simple keys. Note that there could not be a block collection
- # after '---'.
- self.remove_possible_simple_key()
- self.allow_simple_key = False
-
- # Add DOCUMENT-START or DOCUMENT-END.
- start_mark = self.get_mark()
- self.forward(3)
- end_mark = self.get_mark()
- self.tokens.append(TokenClass(start_mark, end_mark))
-
- def fetch_flow_sequence_start(self):
- self.fetch_flow_collection_start(FlowSequenceStartToken)
-
- def fetch_flow_mapping_start(self):
- self.fetch_flow_collection_start(FlowMappingStartToken)
-
- def fetch_flow_collection_start(self, TokenClass):
-
- # '[' and '{' may start a simple key.
- self.save_possible_simple_key()
-
- # Increase the flow level.
- self.flow_level += 1
-
- # Simple keys are allowed after '[' and '{'.
- self.allow_simple_key = True
-
- # Add FLOW-SEQUENCE-START or FLOW-MAPPING-START.
- start_mark = self.get_mark()
- self.forward()
- end_mark = self.get_mark()
- self.tokens.append(TokenClass(start_mark, end_mark))
-
- def fetch_flow_sequence_end(self):
- self.fetch_flow_collection_end(FlowSequenceEndToken)
-
- def fetch_flow_mapping_end(self):
- self.fetch_flow_collection_end(FlowMappingEndToken)
-
- def fetch_flow_collection_end(self, TokenClass):
-
- # Reset possible simple key on the current level.
- self.remove_possible_simple_key()
-
- # Decrease the flow level.
- self.flow_level -= 1
-
- # No simple keys after ']' or '}'.
- self.allow_simple_key = False
-
- # Add FLOW-SEQUENCE-END or FLOW-MAPPING-END.
- start_mark = self.get_mark()
- self.forward()
- end_mark = self.get_mark()
- self.tokens.append(TokenClass(start_mark, end_mark))
-
- def fetch_flow_entry(self):
-
- # Simple keys are allowed after ','.
- self.allow_simple_key = True
-
- # Reset possible simple key on the current level.
- self.remove_possible_simple_key()
-
- # Add FLOW-ENTRY.
- start_mark = self.get_mark()
- self.forward()
- end_mark = self.get_mark()
- self.tokens.append(FlowEntryToken(start_mark, end_mark))
-
- def fetch_block_entry(self):
-
- # Block context needs additional checks.
- if not self.flow_level:
-
- # Are we allowed to start a new entry?
- if not self.allow_simple_key:
- raise ScannerError(None, None,
- "sequence entries are not allowed here",
- self.get_mark())
-
- # We may need to add BLOCK-SEQUENCE-START.
- if self.add_indent(self.column):
- mark = self.get_mark()
- self.tokens.append(BlockSequenceStartToken(mark, mark))
-
- # It's an error for the block entry to occur in the flow context,
- # but we let the parser detect this.
- else:
- pass
-
- # Simple keys are allowed after '-'.
- self.allow_simple_key = True
-
- # Reset possible simple key on the current level.
- self.remove_possible_simple_key()
-
- # Add BLOCK-ENTRY.
- start_mark = self.get_mark()
- self.forward()
- end_mark = self.get_mark()
- self.tokens.append(BlockEntryToken(start_mark, end_mark))
-
- def fetch_key(self):
-
- # Block context needs additional checks.
- if not self.flow_level:
-
+ self.unwind_indent(-1)
+
+ # Reset simple keys. Note that there could not be a block collection
+ # after '---'.
+ self.remove_possible_simple_key()
+ self.allow_simple_key = False
+
+ # Add DOCUMENT-START or DOCUMENT-END.
+ start_mark = self.get_mark()
+ self.forward(3)
+ end_mark = self.get_mark()
+ self.tokens.append(TokenClass(start_mark, end_mark))
+
+ def fetch_flow_sequence_start(self):
+ self.fetch_flow_collection_start(FlowSequenceStartToken)
+
+ def fetch_flow_mapping_start(self):
+ self.fetch_flow_collection_start(FlowMappingStartToken)
+
+ def fetch_flow_collection_start(self, TokenClass):
+
+ # '[' and '{' may start a simple key.
+ self.save_possible_simple_key()
+
+ # Increase the flow level.
+ self.flow_level += 1
+
+ # Simple keys are allowed after '[' and '{'.
+ self.allow_simple_key = True
+
+ # Add FLOW-SEQUENCE-START or FLOW-MAPPING-START.
+ start_mark = self.get_mark()
+ self.forward()
+ end_mark = self.get_mark()
+ self.tokens.append(TokenClass(start_mark, end_mark))
+
+ def fetch_flow_sequence_end(self):
+ self.fetch_flow_collection_end(FlowSequenceEndToken)
+
+ def fetch_flow_mapping_end(self):
+ self.fetch_flow_collection_end(FlowMappingEndToken)
+
+ def fetch_flow_collection_end(self, TokenClass):
+
+ # Reset possible simple key on the current level.
+ self.remove_possible_simple_key()
+
+ # Decrease the flow level.
+ self.flow_level -= 1
+
+ # No simple keys after ']' or '}'.
+ self.allow_simple_key = False
+
+ # Add FLOW-SEQUENCE-END or FLOW-MAPPING-END.
+ start_mark = self.get_mark()
+ self.forward()
+ end_mark = self.get_mark()
+ self.tokens.append(TokenClass(start_mark, end_mark))
+
+ def fetch_flow_entry(self):
+
+ # Simple keys are allowed after ','.
+ self.allow_simple_key = True
+
+ # Reset possible simple key on the current level.
+ self.remove_possible_simple_key()
+
+ # Add FLOW-ENTRY.
+ start_mark = self.get_mark()
+ self.forward()
+ end_mark = self.get_mark()
+ self.tokens.append(FlowEntryToken(start_mark, end_mark))
+
+ def fetch_block_entry(self):
+
+ # Block context needs additional checks.
+ if not self.flow_level:
+
+ # Are we allowed to start a new entry?
+ if not self.allow_simple_key:
+ raise ScannerError(None, None,
+ "sequence entries are not allowed here",
+ self.get_mark())
+
+ # We may need to add BLOCK-SEQUENCE-START.
+ if self.add_indent(self.column):
+ mark = self.get_mark()
+ self.tokens.append(BlockSequenceStartToken(mark, mark))
+
+ # It's an error for the block entry to occur in the flow context,
+ # but we let the parser detect this.
+ else:
+ pass
+
+ # Simple keys are allowed after '-'.
+ self.allow_simple_key = True
+
+ # Reset possible simple key on the current level.
+ self.remove_possible_simple_key()
+
+ # Add BLOCK-ENTRY.
+ start_mark = self.get_mark()
+ self.forward()
+ end_mark = self.get_mark()
+ self.tokens.append(BlockEntryToken(start_mark, end_mark))
+
+ def fetch_key(self):
+
+ # Block context needs additional checks.
+ if not self.flow_level:
+
# Are we allowed to start a key (not necessary a simple)?
- if not self.allow_simple_key:
- raise ScannerError(None, None,
- "mapping keys are not allowed here",
- self.get_mark())
-
- # We may need to add BLOCK-MAPPING-START.
- if self.add_indent(self.column):
- mark = self.get_mark()
- self.tokens.append(BlockMappingStartToken(mark, mark))
-
- # Simple keys are allowed after '?' in the block context.
- self.allow_simple_key = not self.flow_level
-
- # Reset possible simple key on the current level.
- self.remove_possible_simple_key()
-
- # Add KEY.
- start_mark = self.get_mark()
- self.forward()
- end_mark = self.get_mark()
- self.tokens.append(KeyToken(start_mark, end_mark))
-
- def fetch_value(self):
-
- # Do we determine a simple key?
- if self.flow_level in self.possible_simple_keys:
-
- # Add KEY.
- key = self.possible_simple_keys[self.flow_level]
- del self.possible_simple_keys[self.flow_level]
- self.tokens.insert(key.token_number-self.tokens_taken,
- KeyToken(key.mark, key.mark))
-
- # If this key starts a new block mapping, we need to add
- # BLOCK-MAPPING-START.
- if not self.flow_level:
- if self.add_indent(key.column):
- self.tokens.insert(key.token_number-self.tokens_taken,
- BlockMappingStartToken(key.mark, key.mark))
-
- # There cannot be two simple keys one after another.
- self.allow_simple_key = False
-
- # It must be a part of a complex key.
- else:
-
- # Block context needs additional checks.
+ if not self.allow_simple_key:
+ raise ScannerError(None, None,
+ "mapping keys are not allowed here",
+ self.get_mark())
+
+ # We may need to add BLOCK-MAPPING-START.
+ if self.add_indent(self.column):
+ mark = self.get_mark()
+ self.tokens.append(BlockMappingStartToken(mark, mark))
+
+ # Simple keys are allowed after '?' in the block context.
+ self.allow_simple_key = not self.flow_level
+
+ # Reset possible simple key on the current level.
+ self.remove_possible_simple_key()
+
+ # Add KEY.
+ start_mark = self.get_mark()
+ self.forward()
+ end_mark = self.get_mark()
+ self.tokens.append(KeyToken(start_mark, end_mark))
+
+ def fetch_value(self):
+
+ # Do we determine a simple key?
+ if self.flow_level in self.possible_simple_keys:
+
+ # Add KEY.
+ key = self.possible_simple_keys[self.flow_level]
+ del self.possible_simple_keys[self.flow_level]
+ self.tokens.insert(key.token_number-self.tokens_taken,
+ KeyToken(key.mark, key.mark))
+
+ # If this key starts a new block mapping, we need to add
+ # BLOCK-MAPPING-START.
+ if not self.flow_level:
+ if self.add_indent(key.column):
+ self.tokens.insert(key.token_number-self.tokens_taken,
+ BlockMappingStartToken(key.mark, key.mark))
+
+ # There cannot be two simple keys one after another.
+ self.allow_simple_key = False
+
+ # It must be a part of a complex key.
+ else:
+
+ # Block context needs additional checks.
# (Do we really need them? They will be caught by the parser
- # anyway.)
- if not self.flow_level:
-
- # We are allowed to start a complex value if and only if
- # we can start a simple key.
- if not self.allow_simple_key:
- raise ScannerError(None, None,
- "mapping values are not allowed here",
- self.get_mark())
-
- # If this value starts a new block mapping, we need to add
- # BLOCK-MAPPING-START. It will be detected as an error later by
- # the parser.
- if not self.flow_level:
- if self.add_indent(self.column):
- mark = self.get_mark()
- self.tokens.append(BlockMappingStartToken(mark, mark))
-
- # Simple keys are allowed after ':' in the block context.
- self.allow_simple_key = not self.flow_level
-
- # Reset possible simple key on the current level.
- self.remove_possible_simple_key()
-
- # Add VALUE.
- start_mark = self.get_mark()
- self.forward()
- end_mark = self.get_mark()
- self.tokens.append(ValueToken(start_mark, end_mark))
-
- def fetch_alias(self):
-
- # ALIAS could be a simple key.
- self.save_possible_simple_key()
-
- # No simple keys after ALIAS.
- self.allow_simple_key = False
-
- # Scan and add ALIAS.
- self.tokens.append(self.scan_anchor(AliasToken))
-
- def fetch_anchor(self):
-
- # ANCHOR could start a simple key.
- self.save_possible_simple_key()
-
- # No simple keys after ANCHOR.
- self.allow_simple_key = False
-
- # Scan and add ANCHOR.
- self.tokens.append(self.scan_anchor(AnchorToken))
-
- def fetch_tag(self):
-
- # TAG could start a simple key.
- self.save_possible_simple_key()
-
- # No simple keys after TAG.
- self.allow_simple_key = False
-
- # Scan and add TAG.
- self.tokens.append(self.scan_tag())
-
- def fetch_literal(self):
- self.fetch_block_scalar(style='|')
-
- def fetch_folded(self):
- self.fetch_block_scalar(style='>')
-
- def fetch_block_scalar(self, style):
-
- # A simple key may follow a block scalar.
- self.allow_simple_key = True
-
- # Reset possible simple key on the current level.
- self.remove_possible_simple_key()
-
- # Scan and add SCALAR.
- self.tokens.append(self.scan_block_scalar(style))
-
- def fetch_single(self):
- self.fetch_flow_scalar(style='\'')
-
- def fetch_double(self):
- self.fetch_flow_scalar(style='"')
-
- def fetch_flow_scalar(self, style):
-
- # A flow scalar could be a simple key.
- self.save_possible_simple_key()
-
- # No simple keys after flow scalars.
- self.allow_simple_key = False
-
- # Scan and add SCALAR.
- self.tokens.append(self.scan_flow_scalar(style))
-
- def fetch_plain(self):
-
- # A plain scalar could be a simple key.
- self.save_possible_simple_key()
-
- # No simple keys after plain scalars. But note that `scan_plain` will
- # change this flag if the scan is finished at the beginning of the
- # line.
- self.allow_simple_key = False
-
- # Scan and add SCALAR. May change `allow_simple_key`.
- self.tokens.append(self.scan_plain())
-
- # Checkers.
-
- def check_directive(self):
-
- # DIRECTIVE: ^ '%' ...
- # The '%' indicator is already checked.
- if self.column == 0:
- return True
-
- def check_document_start(self):
-
- # DOCUMENT-START: ^ '---' (' '|'\n')
- if self.column == 0:
- if self.prefix(3) == u'---' \
- and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
- return True
-
- def check_document_end(self):
-
- # DOCUMENT-END: ^ '...' (' '|'\n')
- if self.column == 0:
- if self.prefix(3) == u'...' \
- and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
- return True
-
- def check_block_entry(self):
-
- # BLOCK-ENTRY: '-' (' '|'\n')
- return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029'
-
- def check_key(self):
-
- # KEY(flow context): '?'
- if self.flow_level:
- return True
-
- # KEY(block context): '?' (' '|'\n')
- else:
- return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029'
-
- def check_value(self):
-
- # VALUE(flow context): ':'
- if self.flow_level:
- return True
-
- # VALUE(block context): ':' (' '|'\n')
- else:
- return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029'
-
- def check_plain(self):
-
- # A plain scalar may start with any non-space character except:
- # '-', '?', ':', ',', '[', ']', '{', '}',
- # '#', '&', '*', '!', '|', '>', '\'', '\"',
- # '%', '@', '`'.
- #
- # It may also start with
- # '-', '?', ':'
- # if it is followed by a non-space character.
- #
- # Note that we limit the last rule to the block context (except the
- # '-' character) because we want the flow context to be space
- # independent.
- ch = self.peek()
- return ch not in u'\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`' \
- or (self.peek(1) not in u'\0 \t\r\n\x85\u2028\u2029'
- and (ch == u'-' or (not self.flow_level and ch in u'?:')))
-
- # Scanners.
-
- def scan_to_next_token(self):
- # We ignore spaces, line breaks and comments.
- # If we find a line break in the block context, we set the flag
- # `allow_simple_key` on.
- # The byte order mark is stripped if it's the first character in the
- # stream. We do not yet support BOM inside the stream as the
- # specification requires. Any such mark will be considered as a part
- # of the document.
- #
- # TODO: We need to make tab handling rules more sane. A good rule is
- # Tabs cannot precede tokens
- # BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END,
- # KEY(block), VALUE(block), BLOCK-ENTRY
- # So the checking code is
- # if <TAB>:
- # self.allow_simple_keys = False
- # We also need to add the check for `allow_simple_keys == True` to
- # `unwind_indent` before issuing BLOCK-END.
- # Scanners for block, flow, and plain scalars need to be modified.
-
- if self.index == 0 and self.peek() == u'\uFEFF':
- self.forward()
- found = False
- while not found:
- while self.peek() == u' ':
- self.forward()
- if self.peek() == u'#':
- while self.peek() not in u'\0\r\n\x85\u2028\u2029':
- self.forward()
- if self.scan_line_break():
- if not self.flow_level:
- self.allow_simple_key = True
- else:
- found = True
-
- def scan_directive(self):
- # See the specification for details.
- start_mark = self.get_mark()
- self.forward()
- name = self.scan_directive_name(start_mark)
- value = None
- if name == u'YAML':
- value = self.scan_yaml_directive_value(start_mark)
- end_mark = self.get_mark()
- elif name == u'TAG':
- value = self.scan_tag_directive_value(start_mark)
- end_mark = self.get_mark()
- else:
- end_mark = self.get_mark()
- while self.peek() not in u'\0\r\n\x85\u2028\u2029':
- self.forward()
- self.scan_directive_ignored_line(start_mark)
- return DirectiveToken(name, value, start_mark, end_mark)
-
- def scan_directive_name(self, start_mark):
- # See the specification for details.
- length = 0
- ch = self.peek(length)
- while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
- or ch in u'-_':
- length += 1
- ch = self.peek(length)
- if not length:
- raise ScannerError("while scanning a directive", start_mark,
- "expected alphabetic or numeric character, but found %r"
- % ch.encode('utf-8'), self.get_mark())
- value = self.prefix(length)
- self.forward(length)
- ch = self.peek()
- if ch not in u'\0 \r\n\x85\u2028\u2029':
- raise ScannerError("while scanning a directive", start_mark,
- "expected alphabetic or numeric character, but found %r"
- % ch.encode('utf-8'), self.get_mark())
- return value
-
- def scan_yaml_directive_value(self, start_mark):
- # See the specification for details.
- while self.peek() == u' ':
- self.forward()
- major = self.scan_yaml_directive_number(start_mark)
- if self.peek() != '.':
- raise ScannerError("while scanning a directive", start_mark,
- "expected a digit or '.', but found %r"
- % self.peek().encode('utf-8'),
- self.get_mark())
- self.forward()
- minor = self.scan_yaml_directive_number(start_mark)
- if self.peek() not in u'\0 \r\n\x85\u2028\u2029':
- raise ScannerError("while scanning a directive", start_mark,
- "expected a digit or ' ', but found %r"
- % self.peek().encode('utf-8'),
- self.get_mark())
- return (major, minor)
-
- def scan_yaml_directive_number(self, start_mark):
- # See the specification for details.
- ch = self.peek()
- if not (u'0' <= ch <= u'9'):
- raise ScannerError("while scanning a directive", start_mark,
- "expected a digit, but found %r" % ch.encode('utf-8'),
- self.get_mark())
- length = 0
- while u'0' <= self.peek(length) <= u'9':
- length += 1
- value = int(self.prefix(length))
- self.forward(length)
- return value
-
- def scan_tag_directive_value(self, start_mark):
- # See the specification for details.
- while self.peek() == u' ':
- self.forward()
- handle = self.scan_tag_directive_handle(start_mark)
- while self.peek() == u' ':
- self.forward()
- prefix = self.scan_tag_directive_prefix(start_mark)
- return (handle, prefix)
-
- def scan_tag_directive_handle(self, start_mark):
- # See the specification for details.
- value = self.scan_tag_handle('directive', start_mark)
- ch = self.peek()
- if ch != u' ':
- raise ScannerError("while scanning a directive", start_mark,
- "expected ' ', but found %r" % ch.encode('utf-8'),
- self.get_mark())
- return value
-
- def scan_tag_directive_prefix(self, start_mark):
- # See the specification for details.
- value = self.scan_tag_uri('directive', start_mark)
- ch = self.peek()
- if ch not in u'\0 \r\n\x85\u2028\u2029':
- raise ScannerError("while scanning a directive", start_mark,
- "expected ' ', but found %r" % ch.encode('utf-8'),
- self.get_mark())
- return value
-
- def scan_directive_ignored_line(self, start_mark):
- # See the specification for details.
- while self.peek() == u' ':
- self.forward()
- if self.peek() == u'#':
- while self.peek() not in u'\0\r\n\x85\u2028\u2029':
- self.forward()
- ch = self.peek()
- if ch not in u'\0\r\n\x85\u2028\u2029':
- raise ScannerError("while scanning a directive", start_mark,
- "expected a comment or a line break, but found %r"
- % ch.encode('utf-8'), self.get_mark())
- self.scan_line_break()
-
- def scan_anchor(self, TokenClass):
- # The specification does not restrict characters for anchors and
- # aliases. This may lead to problems, for instance, the document:
- # [ *alias, value ]
+ # anyway.)
+ if not self.flow_level:
+
+ # We are allowed to start a complex value if and only if
+ # we can start a simple key.
+ if not self.allow_simple_key:
+ raise ScannerError(None, None,
+ "mapping values are not allowed here",
+ self.get_mark())
+
+ # If this value starts a new block mapping, we need to add
+ # BLOCK-MAPPING-START. It will be detected as an error later by
+ # the parser.
+ if not self.flow_level:
+ if self.add_indent(self.column):
+ mark = self.get_mark()
+ self.tokens.append(BlockMappingStartToken(mark, mark))
+
+ # Simple keys are allowed after ':' in the block context.
+ self.allow_simple_key = not self.flow_level
+
+ # Reset possible simple key on the current level.
+ self.remove_possible_simple_key()
+
+ # Add VALUE.
+ start_mark = self.get_mark()
+ self.forward()
+ end_mark = self.get_mark()
+ self.tokens.append(ValueToken(start_mark, end_mark))
+
+ def fetch_alias(self):
+
+ # ALIAS could be a simple key.
+ self.save_possible_simple_key()
+
+ # No simple keys after ALIAS.
+ self.allow_simple_key = False
+
+ # Scan and add ALIAS.
+ self.tokens.append(self.scan_anchor(AliasToken))
+
+ def fetch_anchor(self):
+
+ # ANCHOR could start a simple key.
+ self.save_possible_simple_key()
+
+ # No simple keys after ANCHOR.
+ self.allow_simple_key = False
+
+ # Scan and add ANCHOR.
+ self.tokens.append(self.scan_anchor(AnchorToken))
+
+ def fetch_tag(self):
+
+ # TAG could start a simple key.
+ self.save_possible_simple_key()
+
+ # No simple keys after TAG.
+ self.allow_simple_key = False
+
+ # Scan and add TAG.
+ self.tokens.append(self.scan_tag())
+
+ def fetch_literal(self):
+ self.fetch_block_scalar(style='|')
+
+ def fetch_folded(self):
+ self.fetch_block_scalar(style='>')
+
+ def fetch_block_scalar(self, style):
+
+ # A simple key may follow a block scalar.
+ self.allow_simple_key = True
+
+ # Reset possible simple key on the current level.
+ self.remove_possible_simple_key()
+
+ # Scan and add SCALAR.
+ self.tokens.append(self.scan_block_scalar(style))
+
+ def fetch_single(self):
+ self.fetch_flow_scalar(style='\'')
+
+ def fetch_double(self):
+ self.fetch_flow_scalar(style='"')
+
+ def fetch_flow_scalar(self, style):
+
+ # A flow scalar could be a simple key.
+ self.save_possible_simple_key()
+
+ # No simple keys after flow scalars.
+ self.allow_simple_key = False
+
+ # Scan and add SCALAR.
+ self.tokens.append(self.scan_flow_scalar(style))
+
+ def fetch_plain(self):
+
+ # A plain scalar could be a simple key.
+ self.save_possible_simple_key()
+
+ # No simple keys after plain scalars. But note that `scan_plain` will
+ # change this flag if the scan is finished at the beginning of the
+ # line.
+ self.allow_simple_key = False
+
+ # Scan and add SCALAR. May change `allow_simple_key`.
+ self.tokens.append(self.scan_plain())
+
+ # Checkers.
+
+ def check_directive(self):
+
+ # DIRECTIVE: ^ '%' ...
+ # The '%' indicator is already checked.
+ if self.column == 0:
+ return True
+
+ def check_document_start(self):
+
+ # DOCUMENT-START: ^ '---' (' '|'\n')
+ if self.column == 0:
+ if self.prefix(3) == u'---' \
+ and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
+ return True
+
+ def check_document_end(self):
+
+ # DOCUMENT-END: ^ '...' (' '|'\n')
+ if self.column == 0:
+ if self.prefix(3) == u'...' \
+ and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
+ return True
+
+ def check_block_entry(self):
+
+ # BLOCK-ENTRY: '-' (' '|'\n')
+ return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029'
+
+ def check_key(self):
+
+ # KEY(flow context): '?'
+ if self.flow_level:
+ return True
+
+ # KEY(block context): '?' (' '|'\n')
+ else:
+ return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029'
+
+ def check_value(self):
+
+ # VALUE(flow context): ':'
+ if self.flow_level:
+ return True
+
+ # VALUE(block context): ':' (' '|'\n')
+ else:
+ return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029'
+
+ def check_plain(self):
+
+ # A plain scalar may start with any non-space character except:
+ # '-', '?', ':', ',', '[', ']', '{', '}',
+ # '#', '&', '*', '!', '|', '>', '\'', '\"',
+ # '%', '@', '`'.
+ #
+ # It may also start with
+ # '-', '?', ':'
+ # if it is followed by a non-space character.
+ #
+ # Note that we limit the last rule to the block context (except the
+ # '-' character) because we want the flow context to be space
+ # independent.
+ ch = self.peek()
+ return ch not in u'\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`' \
+ or (self.peek(1) not in u'\0 \t\r\n\x85\u2028\u2029'
+ and (ch == u'-' or (not self.flow_level and ch in u'?:')))
+
+ # Scanners.
+
+ def scan_to_next_token(self):
+ # We ignore spaces, line breaks and comments.
+ # If we find a line break in the block context, we set the flag
+ # `allow_simple_key` on.
+ # The byte order mark is stripped if it's the first character in the
+ # stream. We do not yet support BOM inside the stream as the
+ # specification requires. Any such mark will be considered as a part
+ # of the document.
+ #
+ # TODO: We need to make tab handling rules more sane. A good rule is
+ # Tabs cannot precede tokens
+ # BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END,
+ # KEY(block), VALUE(block), BLOCK-ENTRY
+ # So the checking code is
+ # if <TAB>:
+ # self.allow_simple_keys = False
+ # We also need to add the check for `allow_simple_keys == True` to
+ # `unwind_indent` before issuing BLOCK-END.
+ # Scanners for block, flow, and plain scalars need to be modified.
+
+ if self.index == 0 and self.peek() == u'\uFEFF':
+ self.forward()
+ found = False
+ while not found:
+ while self.peek() == u' ':
+ self.forward()
+ if self.peek() == u'#':
+ while self.peek() not in u'\0\r\n\x85\u2028\u2029':
+ self.forward()
+ if self.scan_line_break():
+ if not self.flow_level:
+ self.allow_simple_key = True
+ else:
+ found = True
+
+ def scan_directive(self):
+ # See the specification for details.
+ start_mark = self.get_mark()
+ self.forward()
+ name = self.scan_directive_name(start_mark)
+ value = None
+ if name == u'YAML':
+ value = self.scan_yaml_directive_value(start_mark)
+ end_mark = self.get_mark()
+ elif name == u'TAG':
+ value = self.scan_tag_directive_value(start_mark)
+ end_mark = self.get_mark()
+ else:
+ end_mark = self.get_mark()
+ while self.peek() not in u'\0\r\n\x85\u2028\u2029':
+ self.forward()
+ self.scan_directive_ignored_line(start_mark)
+ return DirectiveToken(name, value, start_mark, end_mark)
+
+ def scan_directive_name(self, start_mark):
+ # See the specification for details.
+ length = 0
+ ch = self.peek(length)
+ while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
+ or ch in u'-_':
+ length += 1
+ ch = self.peek(length)
+ if not length:
+ raise ScannerError("while scanning a directive", start_mark,
+ "expected alphabetic or numeric character, but found %r"
+ % ch.encode('utf-8'), self.get_mark())
+ value = self.prefix(length)
+ self.forward(length)
+ ch = self.peek()
+ if ch not in u'\0 \r\n\x85\u2028\u2029':
+ raise ScannerError("while scanning a directive", start_mark,
+ "expected alphabetic or numeric character, but found %r"
+ % ch.encode('utf-8'), self.get_mark())
+ return value
+
+ def scan_yaml_directive_value(self, start_mark):
+ # See the specification for details.
+ while self.peek() == u' ':
+ self.forward()
+ major = self.scan_yaml_directive_number(start_mark)
+ if self.peek() != '.':
+ raise ScannerError("while scanning a directive", start_mark,
+ "expected a digit or '.', but found %r"
+ % self.peek().encode('utf-8'),
+ self.get_mark())
+ self.forward()
+ minor = self.scan_yaml_directive_number(start_mark)
+ if self.peek() not in u'\0 \r\n\x85\u2028\u2029':
+ raise ScannerError("while scanning a directive", start_mark,
+ "expected a digit or ' ', but found %r"
+ % self.peek().encode('utf-8'),
+ self.get_mark())
+ return (major, minor)
+
+ def scan_yaml_directive_number(self, start_mark):
+ # See the specification for details.
+ ch = self.peek()
+ if not (u'0' <= ch <= u'9'):
+ raise ScannerError("while scanning a directive", start_mark,
+ "expected a digit, but found %r" % ch.encode('utf-8'),
+ self.get_mark())
+ length = 0
+ while u'0' <= self.peek(length) <= u'9':
+ length += 1
+ value = int(self.prefix(length))
+ self.forward(length)
+ return value
+
+ def scan_tag_directive_value(self, start_mark):
+ # See the specification for details.
+ while self.peek() == u' ':
+ self.forward()
+ handle = self.scan_tag_directive_handle(start_mark)
+ while self.peek() == u' ':
+ self.forward()
+ prefix = self.scan_tag_directive_prefix(start_mark)
+ return (handle, prefix)
+
+ def scan_tag_directive_handle(self, start_mark):
+ # See the specification for details.
+ value = self.scan_tag_handle('directive', start_mark)
+ ch = self.peek()
+ if ch != u' ':
+ raise ScannerError("while scanning a directive", start_mark,
+ "expected ' ', but found %r" % ch.encode('utf-8'),
+ self.get_mark())
+ return value
+
+ def scan_tag_directive_prefix(self, start_mark):
+ # See the specification for details.
+ value = self.scan_tag_uri('directive', start_mark)
+ ch = self.peek()
+ if ch not in u'\0 \r\n\x85\u2028\u2029':
+ raise ScannerError("while scanning a directive", start_mark,
+ "expected ' ', but found %r" % ch.encode('utf-8'),
+ self.get_mark())
+ return value
+
+ def scan_directive_ignored_line(self, start_mark):
+ # See the specification for details.
+ while self.peek() == u' ':
+ self.forward()
+ if self.peek() == u'#':
+ while self.peek() not in u'\0\r\n\x85\u2028\u2029':
+ self.forward()
+ ch = self.peek()
+ if ch not in u'\0\r\n\x85\u2028\u2029':
+ raise ScannerError("while scanning a directive", start_mark,
+ "expected a comment or a line break, but found %r"
+ % ch.encode('utf-8'), self.get_mark())
+ self.scan_line_break()
+
+ def scan_anchor(self, TokenClass):
+ # The specification does not restrict characters for anchors and
+ # aliases. This may lead to problems, for instance, the document:
+ # [ *alias, value ]
# can be interpreted in two ways, as
- # [ "value" ]
- # and
- # [ *alias , "value" ]
- # Therefore we restrict aliases to numbers and ASCII letters.
- start_mark = self.get_mark()
- indicator = self.peek()
- if indicator == u'*':
- name = 'alias'
- else:
- name = 'anchor'
- self.forward()
- length = 0
- ch = self.peek(length)
- while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
- or ch in u'-_':
- length += 1
- ch = self.peek(length)
- if not length:
- raise ScannerError("while scanning an %s" % name, start_mark,
- "expected alphabetic or numeric character, but found %r"
- % ch.encode('utf-8'), self.get_mark())
- value = self.prefix(length)
- self.forward(length)
- ch = self.peek()
- if ch not in u'\0 \t\r\n\x85\u2028\u2029?:,]}%@`':
- raise ScannerError("while scanning an %s" % name, start_mark,
- "expected alphabetic or numeric character, but found %r"
- % ch.encode('utf-8'), self.get_mark())
- end_mark = self.get_mark()
- return TokenClass(value, start_mark, end_mark)
-
- def scan_tag(self):
- # See the specification for details.
- start_mark = self.get_mark()
- ch = self.peek(1)
- if ch == u'<':
- handle = None
- self.forward(2)
- suffix = self.scan_tag_uri('tag', start_mark)
- if self.peek() != u'>':
- raise ScannerError("while parsing a tag", start_mark,
- "expected '>', but found %r" % self.peek().encode('utf-8'),
- self.get_mark())
- self.forward()
- elif ch in u'\0 \t\r\n\x85\u2028\u2029':
- handle = None
- suffix = u'!'
- self.forward()
- else:
- length = 1
- use_handle = False
- while ch not in u'\0 \r\n\x85\u2028\u2029':
- if ch == u'!':
- use_handle = True
- break
- length += 1
- ch = self.peek(length)
- handle = u'!'
- if use_handle:
- handle = self.scan_tag_handle('tag', start_mark)
- else:
- handle = u'!'
- self.forward()
- suffix = self.scan_tag_uri('tag', start_mark)
- ch = self.peek()
- if ch not in u'\0 \r\n\x85\u2028\u2029':
- raise ScannerError("while scanning a tag", start_mark,
- "expected ' ', but found %r" % ch.encode('utf-8'),
- self.get_mark())
- value = (handle, suffix)
- end_mark = self.get_mark()
- return TagToken(value, start_mark, end_mark)
-
- def scan_block_scalar(self, style):
- # See the specification for details.
-
- if style == '>':
- folded = True
- else:
- folded = False
-
- chunks = []
- start_mark = self.get_mark()
-
- # Scan the header.
- self.forward()
- chomping, increment = self.scan_block_scalar_indicators(start_mark)
- self.scan_block_scalar_ignored_line(start_mark)
-
- # Determine the indentation level and go to the first non-empty line.
- min_indent = self.indent+1
- if min_indent < 1:
- min_indent = 1
- if increment is None:
- breaks, max_indent, end_mark = self.scan_block_scalar_indentation()
- indent = max(min_indent, max_indent)
- else:
- indent = min_indent+increment-1
- breaks, end_mark = self.scan_block_scalar_breaks(indent)
- line_break = u''
-
- # Scan the inner part of the block scalar.
- while self.column == indent and self.peek() != u'\0':
- chunks.extend(breaks)
- leading_non_space = self.peek() not in u' \t'
- length = 0
- while self.peek(length) not in u'\0\r\n\x85\u2028\u2029':
- length += 1
- chunks.append(self.prefix(length))
- self.forward(length)
- line_break = self.scan_line_break()
- breaks, end_mark = self.scan_block_scalar_breaks(indent)
- if self.column == indent and self.peek() != u'\0':
-
- # Unfortunately, folding rules are ambiguous.
- #
- # This is the folding according to the specification:
-
- if folded and line_break == u'\n' \
- and leading_non_space and self.peek() not in u' \t':
- if not breaks:
- chunks.append(u' ')
- else:
- chunks.append(line_break)
-
- # This is Clark Evans's interpretation (also in the spec
- # examples):
- #
- #if folded and line_break == u'\n':
- # if not breaks:
- # if self.peek() not in ' \t':
- # chunks.append(u' ')
- # else:
- # chunks.append(line_break)
- #else:
- # chunks.append(line_break)
- else:
- break
-
- # Chomp the tail.
- if chomping is not False:
- chunks.append(line_break)
- if chomping is True:
- chunks.extend(breaks)
-
- # We are done.
- return ScalarToken(u''.join(chunks), False, start_mark, end_mark,
- style)
-
- def scan_block_scalar_indicators(self, start_mark):
- # See the specification for details.
- chomping = None
- increment = None
- ch = self.peek()
- if ch in u'+-':
- if ch == '+':
- chomping = True
- else:
- chomping = False
- self.forward()
- ch = self.peek()
- if ch in u'0123456789':
- increment = int(ch)
- if increment == 0:
- raise ScannerError("while scanning a block scalar", start_mark,
- "expected indentation indicator in the range 1-9, but found 0",
- self.get_mark())
- self.forward()
- elif ch in u'0123456789':
- increment = int(ch)
- if increment == 0:
- raise ScannerError("while scanning a block scalar", start_mark,
- "expected indentation indicator in the range 1-9, but found 0",
- self.get_mark())
- self.forward()
- ch = self.peek()
- if ch in u'+-':
- if ch == '+':
- chomping = True
- else:
- chomping = False
- self.forward()
- ch = self.peek()
- if ch not in u'\0 \r\n\x85\u2028\u2029':
- raise ScannerError("while scanning a block scalar", start_mark,
- "expected chomping or indentation indicators, but found %r"
- % ch.encode('utf-8'), self.get_mark())
- return chomping, increment
-
- def scan_block_scalar_ignored_line(self, start_mark):
- # See the specification for details.
- while self.peek() == u' ':
- self.forward()
- if self.peek() == u'#':
- while self.peek() not in u'\0\r\n\x85\u2028\u2029':
- self.forward()
- ch = self.peek()
- if ch not in u'\0\r\n\x85\u2028\u2029':
- raise ScannerError("while scanning a block scalar", start_mark,
- "expected a comment or a line break, but found %r"
- % ch.encode('utf-8'), self.get_mark())
- self.scan_line_break()
-
- def scan_block_scalar_indentation(self):
- # See the specification for details.
- chunks = []
- max_indent = 0
- end_mark = self.get_mark()
- while self.peek() in u' \r\n\x85\u2028\u2029':
- if self.peek() != u' ':
- chunks.append(self.scan_line_break())
- end_mark = self.get_mark()
- else:
- self.forward()
- if self.column > max_indent:
- max_indent = self.column
- return chunks, max_indent, end_mark
-
- def scan_block_scalar_breaks(self, indent):
- # See the specification for details.
- chunks = []
- end_mark = self.get_mark()
- while self.column < indent and self.peek() == u' ':
- self.forward()
- while self.peek() in u'\r\n\x85\u2028\u2029':
- chunks.append(self.scan_line_break())
- end_mark = self.get_mark()
- while self.column < indent and self.peek() == u' ':
- self.forward()
- return chunks, end_mark
-
- def scan_flow_scalar(self, style):
- # See the specification for details.
- # Note that we loose indentation rules for quoted scalars. Quoted
- # scalars don't need to adhere indentation because " and ' clearly
- # mark the beginning and the end of them. Therefore we are less
- # restrictive then the specification requires. We only need to check
- # that document separators are not included in scalars.
- if style == '"':
- double = True
- else:
- double = False
- chunks = []
- start_mark = self.get_mark()
- quote = self.peek()
- self.forward()
- chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark))
- while self.peek() != quote:
- chunks.extend(self.scan_flow_scalar_spaces(double, start_mark))
- chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark))
- self.forward()
- end_mark = self.get_mark()
- return ScalarToken(u''.join(chunks), False, start_mark, end_mark,
- style)
-
- ESCAPE_REPLACEMENTS = {
- u'0': u'\0',
- u'a': u'\x07',
- u'b': u'\x08',
- u't': u'\x09',
- u'\t': u'\x09',
- u'n': u'\x0A',
- u'v': u'\x0B',
- u'f': u'\x0C',
- u'r': u'\x0D',
- u'e': u'\x1B',
- u' ': u'\x20',
- u'\"': u'\"',
- u'\\': u'\\',
+ # [ "value" ]
+ # and
+ # [ *alias , "value" ]
+ # Therefore we restrict aliases to numbers and ASCII letters.
+ start_mark = self.get_mark()
+ indicator = self.peek()
+ if indicator == u'*':
+ name = 'alias'
+ else:
+ name = 'anchor'
+ self.forward()
+ length = 0
+ ch = self.peek(length)
+ while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
+ or ch in u'-_':
+ length += 1
+ ch = self.peek(length)
+ if not length:
+ raise ScannerError("while scanning an %s" % name, start_mark,
+ "expected alphabetic or numeric character, but found %r"
+ % ch.encode('utf-8'), self.get_mark())
+ value = self.prefix(length)
+ self.forward(length)
+ ch = self.peek()
+ if ch not in u'\0 \t\r\n\x85\u2028\u2029?:,]}%@`':
+ raise ScannerError("while scanning an %s" % name, start_mark,
+ "expected alphabetic or numeric character, but found %r"
+ % ch.encode('utf-8'), self.get_mark())
+ end_mark = self.get_mark()
+ return TokenClass(value, start_mark, end_mark)
+
+ def scan_tag(self):
+ # See the specification for details.
+ start_mark = self.get_mark()
+ ch = self.peek(1)
+ if ch == u'<':
+ handle = None
+ self.forward(2)
+ suffix = self.scan_tag_uri('tag', start_mark)
+ if self.peek() != u'>':
+ raise ScannerError("while parsing a tag", start_mark,
+ "expected '>', but found %r" % self.peek().encode('utf-8'),
+ self.get_mark())
+ self.forward()
+ elif ch in u'\0 \t\r\n\x85\u2028\u2029':
+ handle = None
+ suffix = u'!'
+ self.forward()
+ else:
+ length = 1
+ use_handle = False
+ while ch not in u'\0 \r\n\x85\u2028\u2029':
+ if ch == u'!':
+ use_handle = True
+ break
+ length += 1
+ ch = self.peek(length)
+ handle = u'!'
+ if use_handle:
+ handle = self.scan_tag_handle('tag', start_mark)
+ else:
+ handle = u'!'
+ self.forward()
+ suffix = self.scan_tag_uri('tag', start_mark)
+ ch = self.peek()
+ if ch not in u'\0 \r\n\x85\u2028\u2029':
+ raise ScannerError("while scanning a tag", start_mark,
+ "expected ' ', but found %r" % ch.encode('utf-8'),
+ self.get_mark())
+ value = (handle, suffix)
+ end_mark = self.get_mark()
+ return TagToken(value, start_mark, end_mark)
+
+ def scan_block_scalar(self, style):
+ # See the specification for details.
+
+ if style == '>':
+ folded = True
+ else:
+ folded = False
+
+ chunks = []
+ start_mark = self.get_mark()
+
+ # Scan the header.
+ self.forward()
+ chomping, increment = self.scan_block_scalar_indicators(start_mark)
+ self.scan_block_scalar_ignored_line(start_mark)
+
+ # Determine the indentation level and go to the first non-empty line.
+ min_indent = self.indent+1
+ if min_indent < 1:
+ min_indent = 1
+ if increment is None:
+ breaks, max_indent, end_mark = self.scan_block_scalar_indentation()
+ indent = max(min_indent, max_indent)
+ else:
+ indent = min_indent+increment-1
+ breaks, end_mark = self.scan_block_scalar_breaks(indent)
+ line_break = u''
+
+ # Scan the inner part of the block scalar.
+ while self.column == indent and self.peek() != u'\0':
+ chunks.extend(breaks)
+ leading_non_space = self.peek() not in u' \t'
+ length = 0
+ while self.peek(length) not in u'\0\r\n\x85\u2028\u2029':
+ length += 1
+ chunks.append(self.prefix(length))
+ self.forward(length)
+ line_break = self.scan_line_break()
+ breaks, end_mark = self.scan_block_scalar_breaks(indent)
+ if self.column == indent and self.peek() != u'\0':
+
+ # Unfortunately, folding rules are ambiguous.
+ #
+ # This is the folding according to the specification:
+
+ if folded and line_break == u'\n' \
+ and leading_non_space and self.peek() not in u' \t':
+ if not breaks:
+ chunks.append(u' ')
+ else:
+ chunks.append(line_break)
+
+ # This is Clark Evans's interpretation (also in the spec
+ # examples):
+ #
+ #if folded and line_break == u'\n':
+ # if not breaks:
+ # if self.peek() not in ' \t':
+ # chunks.append(u' ')
+ # else:
+ # chunks.append(line_break)
+ #else:
+ # chunks.append(line_break)
+ else:
+ break
+
+ # Chomp the tail.
+ if chomping is not False:
+ chunks.append(line_break)
+ if chomping is True:
+ chunks.extend(breaks)
+
+ # We are done.
+ return ScalarToken(u''.join(chunks), False, start_mark, end_mark,
+ style)
+
+ def scan_block_scalar_indicators(self, start_mark):
+ # See the specification for details.
+ chomping = None
+ increment = None
+ ch = self.peek()
+ if ch in u'+-':
+ if ch == '+':
+ chomping = True
+ else:
+ chomping = False
+ self.forward()
+ ch = self.peek()
+ if ch in u'0123456789':
+ increment = int(ch)
+ if increment == 0:
+ raise ScannerError("while scanning a block scalar", start_mark,
+ "expected indentation indicator in the range 1-9, but found 0",
+ self.get_mark())
+ self.forward()
+ elif ch in u'0123456789':
+ increment = int(ch)
+ if increment == 0:
+ raise ScannerError("while scanning a block scalar", start_mark,
+ "expected indentation indicator in the range 1-9, but found 0",
+ self.get_mark())
+ self.forward()
+ ch = self.peek()
+ if ch in u'+-':
+ if ch == '+':
+ chomping = True
+ else:
+ chomping = False
+ self.forward()
+ ch = self.peek()
+ if ch not in u'\0 \r\n\x85\u2028\u2029':
+ raise ScannerError("while scanning a block scalar", start_mark,
+ "expected chomping or indentation indicators, but found %r"
+ % ch.encode('utf-8'), self.get_mark())
+ return chomping, increment
+
+ def scan_block_scalar_ignored_line(self, start_mark):
+ # See the specification for details.
+ while self.peek() == u' ':
+ self.forward()
+ if self.peek() == u'#':
+ while self.peek() not in u'\0\r\n\x85\u2028\u2029':
+ self.forward()
+ ch = self.peek()
+ if ch not in u'\0\r\n\x85\u2028\u2029':
+ raise ScannerError("while scanning a block scalar", start_mark,
+ "expected a comment or a line break, but found %r"
+ % ch.encode('utf-8'), self.get_mark())
+ self.scan_line_break()
+
+ def scan_block_scalar_indentation(self):
+ # See the specification for details.
+ chunks = []
+ max_indent = 0
+ end_mark = self.get_mark()
+ while self.peek() in u' \r\n\x85\u2028\u2029':
+ if self.peek() != u' ':
+ chunks.append(self.scan_line_break())
+ end_mark = self.get_mark()
+ else:
+ self.forward()
+ if self.column > max_indent:
+ max_indent = self.column
+ return chunks, max_indent, end_mark
+
+ def scan_block_scalar_breaks(self, indent):
+ # See the specification for details.
+ chunks = []
+ end_mark = self.get_mark()
+ while self.column < indent and self.peek() == u' ':
+ self.forward()
+ while self.peek() in u'\r\n\x85\u2028\u2029':
+ chunks.append(self.scan_line_break())
+ end_mark = self.get_mark()
+ while self.column < indent and self.peek() == u' ':
+ self.forward()
+ return chunks, end_mark
+
+ def scan_flow_scalar(self, style):
+ # See the specification for details.
+ # Note that we loose indentation rules for quoted scalars. Quoted
+ # scalars don't need to adhere indentation because " and ' clearly
+ # mark the beginning and the end of them. Therefore we are less
+ # restrictive then the specification requires. We only need to check
+ # that document separators are not included in scalars.
+ if style == '"':
+ double = True
+ else:
+ double = False
+ chunks = []
+ start_mark = self.get_mark()
+ quote = self.peek()
+ self.forward()
+ chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark))
+ while self.peek() != quote:
+ chunks.extend(self.scan_flow_scalar_spaces(double, start_mark))
+ chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark))
+ self.forward()
+ end_mark = self.get_mark()
+ return ScalarToken(u''.join(chunks), False, start_mark, end_mark,
+ style)
+
+ ESCAPE_REPLACEMENTS = {
+ u'0': u'\0',
+ u'a': u'\x07',
+ u'b': u'\x08',
+ u't': u'\x09',
+ u'\t': u'\x09',
+ u'n': u'\x0A',
+ u'v': u'\x0B',
+ u'f': u'\x0C',
+ u'r': u'\x0D',
+ u'e': u'\x1B',
+ u' ': u'\x20',
+ u'\"': u'\"',
+ u'\\': u'\\',
u'/': u'/',
- u'N': u'\x85',
- u'_': u'\xA0',
- u'L': u'\u2028',
- u'P': u'\u2029',
- }
-
- ESCAPE_CODES = {
- u'x': 2,
- u'u': 4,
- u'U': 8,
- }
-
- def scan_flow_scalar_non_spaces(self, double, start_mark):
- # See the specification for details.
- chunks = []
- while True:
- length = 0
- while self.peek(length) not in u'\'\"\\\0 \t\r\n\x85\u2028\u2029':
- length += 1
- if length:
- chunks.append(self.prefix(length))
- self.forward(length)
- ch = self.peek()
- if not double and ch == u'\'' and self.peek(1) == u'\'':
- chunks.append(u'\'')
- self.forward(2)
- elif (double and ch == u'\'') or (not double and ch in u'\"\\'):
- chunks.append(ch)
- self.forward()
- elif double and ch == u'\\':
- self.forward()
- ch = self.peek()
- if ch in self.ESCAPE_REPLACEMENTS:
- chunks.append(self.ESCAPE_REPLACEMENTS[ch])
- self.forward()
- elif ch in self.ESCAPE_CODES:
- length = self.ESCAPE_CODES[ch]
- self.forward()
- for k in range(length):
- if self.peek(k) not in u'0123456789ABCDEFabcdef':
- raise ScannerError("while scanning a double-quoted scalar", start_mark,
- "expected escape sequence of %d hexdecimal numbers, but found %r" %
- (length, self.peek(k).encode('utf-8')), self.get_mark())
- code = int(self.prefix(length), 16)
+ u'N': u'\x85',
+ u'_': u'\xA0',
+ u'L': u'\u2028',
+ u'P': u'\u2029',
+ }
+
+ ESCAPE_CODES = {
+ u'x': 2,
+ u'u': 4,
+ u'U': 8,
+ }
+
+ def scan_flow_scalar_non_spaces(self, double, start_mark):
+ # See the specification for details.
+ chunks = []
+ while True:
+ length = 0
+ while self.peek(length) not in u'\'\"\\\0 \t\r\n\x85\u2028\u2029':
+ length += 1
+ if length:
+ chunks.append(self.prefix(length))
+ self.forward(length)
+ ch = self.peek()
+ if not double and ch == u'\'' and self.peek(1) == u'\'':
+ chunks.append(u'\'')
+ self.forward(2)
+ elif (double and ch == u'\'') or (not double and ch in u'\"\\'):
+ chunks.append(ch)
+ self.forward()
+ elif double and ch == u'\\':
+ self.forward()
+ ch = self.peek()
+ if ch in self.ESCAPE_REPLACEMENTS:
+ chunks.append(self.ESCAPE_REPLACEMENTS[ch])
+ self.forward()
+ elif ch in self.ESCAPE_CODES:
+ length = self.ESCAPE_CODES[ch]
+ self.forward()
+ for k in range(length):
+ if self.peek(k) not in u'0123456789ABCDEFabcdef':
+ raise ScannerError("while scanning a double-quoted scalar", start_mark,
+ "expected escape sequence of %d hexdecimal numbers, but found %r" %
+ (length, self.peek(k).encode('utf-8')), self.get_mark())
+ code = int(self.prefix(length), 16)
if code <= sys.maxunicode:
chunks.append(unichr(code))
else:
chunks.append(('\\U%08x' % code).decode('unicode-escape'))
- self.forward(length)
- elif ch in u'\r\n\x85\u2028\u2029':
- self.scan_line_break()
- chunks.extend(self.scan_flow_scalar_breaks(double, start_mark))
- else:
- raise ScannerError("while scanning a double-quoted scalar", start_mark,
- "found unknown escape character %r" % ch.encode('utf-8'), self.get_mark())
- else:
- return chunks
-
- def scan_flow_scalar_spaces(self, double, start_mark):
- # See the specification for details.
- chunks = []
- length = 0
- while self.peek(length) in u' \t':
- length += 1
- whitespaces = self.prefix(length)
- self.forward(length)
- ch = self.peek()
- if ch == u'\0':
- raise ScannerError("while scanning a quoted scalar", start_mark,
- "found unexpected end of stream", self.get_mark())
- elif ch in u'\r\n\x85\u2028\u2029':
- line_break = self.scan_line_break()
- breaks = self.scan_flow_scalar_breaks(double, start_mark)
- if line_break != u'\n':
- chunks.append(line_break)
- elif not breaks:
- chunks.append(u' ')
- chunks.extend(breaks)
- else:
- chunks.append(whitespaces)
- return chunks
-
- def scan_flow_scalar_breaks(self, double, start_mark):
- # See the specification for details.
- chunks = []
- while True:
- # Instead of checking indentation, we check for document
- # separators.
- prefix = self.prefix(3)
- if (prefix == u'---' or prefix == u'...') \
- and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
- raise ScannerError("while scanning a quoted scalar", start_mark,
- "found unexpected document separator", self.get_mark())
- while self.peek() in u' \t':
- self.forward()
- if self.peek() in u'\r\n\x85\u2028\u2029':
- chunks.append(self.scan_line_break())
- else:
- return chunks
-
- def scan_plain(self):
- # See the specification for details.
- # We add an additional restriction for the flow context:
+ self.forward(length)
+ elif ch in u'\r\n\x85\u2028\u2029':
+ self.scan_line_break()
+ chunks.extend(self.scan_flow_scalar_breaks(double, start_mark))
+ else:
+ raise ScannerError("while scanning a double-quoted scalar", start_mark,
+ "found unknown escape character %r" % ch.encode('utf-8'), self.get_mark())
+ else:
+ return chunks
+
+ def scan_flow_scalar_spaces(self, double, start_mark):
+ # See the specification for details.
+ chunks = []
+ length = 0
+ while self.peek(length) in u' \t':
+ length += 1
+ whitespaces = self.prefix(length)
+ self.forward(length)
+ ch = self.peek()
+ if ch == u'\0':
+ raise ScannerError("while scanning a quoted scalar", start_mark,
+ "found unexpected end of stream", self.get_mark())
+ elif ch in u'\r\n\x85\u2028\u2029':
+ line_break = self.scan_line_break()
+ breaks = self.scan_flow_scalar_breaks(double, start_mark)
+ if line_break != u'\n':
+ chunks.append(line_break)
+ elif not breaks:
+ chunks.append(u' ')
+ chunks.extend(breaks)
+ else:
+ chunks.append(whitespaces)
+ return chunks
+
+ def scan_flow_scalar_breaks(self, double, start_mark):
+ # See the specification for details.
+ chunks = []
+ while True:
+ # Instead of checking indentation, we check for document
+ # separators.
+ prefix = self.prefix(3)
+ if (prefix == u'---' or prefix == u'...') \
+ and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
+ raise ScannerError("while scanning a quoted scalar", start_mark,
+ "found unexpected document separator", self.get_mark())
+ while self.peek() in u' \t':
+ self.forward()
+ if self.peek() in u'\r\n\x85\u2028\u2029':
+ chunks.append(self.scan_line_break())
+ else:
+ return chunks
+
+ def scan_plain(self):
+ # See the specification for details.
+ # We add an additional restriction for the flow context:
# plain scalars in the flow context cannot contain ',' or '?'.
- # We also keep track of the `allow_simple_key` flag here.
- # Indentation rules are loosed for the flow context.
- chunks = []
- start_mark = self.get_mark()
- end_mark = start_mark
- indent = self.indent+1
- # We allow zero indentation for scalars, but then we need to check for
- # document separators at the beginning of the line.
- #if indent == 0:
- # indent = 1
- spaces = []
- while True:
- length = 0
- if self.peek() == u'#':
- break
- while True:
- ch = self.peek(length)
- if ch in u'\0 \t\r\n\x85\u2028\u2029' \
+ # We also keep track of the `allow_simple_key` flag here.
+ # Indentation rules are loosed for the flow context.
+ chunks = []
+ start_mark = self.get_mark()
+ end_mark = start_mark
+ indent = self.indent+1
+ # We allow zero indentation for scalars, but then we need to check for
+ # document separators at the beginning of the line.
+ #if indent == 0:
+ # indent = 1
+ spaces = []
+ while True:
+ length = 0
+ if self.peek() == u'#':
+ break
+ while True:
+ ch = self.peek(length)
+ if ch in u'\0 \t\r\n\x85\u2028\u2029' \
or (ch == u':' and
self.peek(length+1) in u'\0 \t\r\n\x85\u2028\u2029'
+ (u',[]{}' if self.flow_level else u''))\
or (self.flow_level and ch in u',?[]{}'):
- break
- length += 1
- if length == 0:
- break
- self.allow_simple_key = False
- chunks.extend(spaces)
- chunks.append(self.prefix(length))
- self.forward(length)
- end_mark = self.get_mark()
- spaces = self.scan_plain_spaces(indent, start_mark)
- if not spaces or self.peek() == u'#' \
- or (not self.flow_level and self.column < indent):
- break
- return ScalarToken(u''.join(chunks), True, start_mark, end_mark)
-
- def scan_plain_spaces(self, indent, start_mark):
- # See the specification for details.
- # The specification is really confusing about tabs in plain scalars.
- # We just forbid them completely. Do not use tabs in YAML!
- chunks = []
- length = 0
- while self.peek(length) in u' ':
- length += 1
- whitespaces = self.prefix(length)
- self.forward(length)
- ch = self.peek()
- if ch in u'\r\n\x85\u2028\u2029':
- line_break = self.scan_line_break()
- self.allow_simple_key = True
- prefix = self.prefix(3)
- if (prefix == u'---' or prefix == u'...') \
- and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
- return
- breaks = []
- while self.peek() in u' \r\n\x85\u2028\u2029':
- if self.peek() == ' ':
- self.forward()
- else:
- breaks.append(self.scan_line_break())
- prefix = self.prefix(3)
- if (prefix == u'---' or prefix == u'...') \
- and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
- return
- if line_break != u'\n':
- chunks.append(line_break)
- elif not breaks:
- chunks.append(u' ')
- chunks.extend(breaks)
- elif whitespaces:
- chunks.append(whitespaces)
- return chunks
-
- def scan_tag_handle(self, name, start_mark):
- # See the specification for details.
- # For some strange reasons, the specification does not allow '_' in
- # tag handles. I have allowed it anyway.
- ch = self.peek()
- if ch != u'!':
- raise ScannerError("while scanning a %s" % name, start_mark,
- "expected '!', but found %r" % ch.encode('utf-8'),
- self.get_mark())
- length = 1
- ch = self.peek(length)
- if ch != u' ':
- while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
- or ch in u'-_':
- length += 1
- ch = self.peek(length)
- if ch != u'!':
- self.forward(length)
- raise ScannerError("while scanning a %s" % name, start_mark,
- "expected '!', but found %r" % ch.encode('utf-8'),
- self.get_mark())
- length += 1
- value = self.prefix(length)
- self.forward(length)
- return value
-
- def scan_tag_uri(self, name, start_mark):
- # See the specification for details.
- # Note: we do not check if URI is well-formed.
- chunks = []
- length = 0
- ch = self.peek(length)
- while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
- or ch in u'-;/?:@&=+$,_.!~*\'()[]%':
- if ch == u'%':
- chunks.append(self.prefix(length))
- self.forward(length)
- length = 0
- chunks.append(self.scan_uri_escapes(name, start_mark))
- else:
- length += 1
- ch = self.peek(length)
- if length:
- chunks.append(self.prefix(length))
- self.forward(length)
- length = 0
- if not chunks:
- raise ScannerError("while parsing a %s" % name, start_mark,
- "expected URI, but found %r" % ch.encode('utf-8'),
- self.get_mark())
- return u''.join(chunks)
-
- def scan_uri_escapes(self, name, start_mark):
- # See the specification for details.
- bytes = []
- mark = self.get_mark()
- while self.peek() == u'%':
- self.forward()
- for k in range(2):
- if self.peek(k) not in u'0123456789ABCDEFabcdef':
- raise ScannerError("while scanning a %s" % name, start_mark,
- "expected URI escape sequence of 2 hexdecimal numbers, but found %r" %
- (self.peek(k).encode('utf-8')), self.get_mark())
- bytes.append(chr(int(self.prefix(2), 16)))
- self.forward(2)
- try:
- value = unicode(''.join(bytes), 'utf-8')
- except UnicodeDecodeError, exc:
- raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark)
- return value
-
- def scan_line_break(self):
- # Transforms:
- # '\r\n' : '\n'
- # '\r' : '\n'
- # '\n' : '\n'
- # '\x85' : '\n'
- # '\u2028' : '\u2028'
- # '\u2029 : '\u2029'
- # default : ''
- ch = self.peek()
- if ch in u'\r\n\x85':
- if self.prefix(2) == u'\r\n':
- self.forward(2)
- else:
- self.forward()
- return u'\n'
- elif ch in u'\u2028\u2029':
- self.forward()
- return ch
- return u''
+ break
+ length += 1
+ if length == 0:
+ break
+ self.allow_simple_key = False
+ chunks.extend(spaces)
+ chunks.append(self.prefix(length))
+ self.forward(length)
+ end_mark = self.get_mark()
+ spaces = self.scan_plain_spaces(indent, start_mark)
+ if not spaces or self.peek() == u'#' \
+ or (not self.flow_level and self.column < indent):
+ break
+ return ScalarToken(u''.join(chunks), True, start_mark, end_mark)
+
+ def scan_plain_spaces(self, indent, start_mark):
+ # See the specification for details.
+ # The specification is really confusing about tabs in plain scalars.
+ # We just forbid them completely. Do not use tabs in YAML!
+ chunks = []
+ length = 0
+ while self.peek(length) in u' ':
+ length += 1
+ whitespaces = self.prefix(length)
+ self.forward(length)
+ ch = self.peek()
+ if ch in u'\r\n\x85\u2028\u2029':
+ line_break = self.scan_line_break()
+ self.allow_simple_key = True
+ prefix = self.prefix(3)
+ if (prefix == u'---' or prefix == u'...') \
+ and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
+ return
+ breaks = []
+ while self.peek() in u' \r\n\x85\u2028\u2029':
+ if self.peek() == ' ':
+ self.forward()
+ else:
+ breaks.append(self.scan_line_break())
+ prefix = self.prefix(3)
+ if (prefix == u'---' or prefix == u'...') \
+ and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029':
+ return
+ if line_break != u'\n':
+ chunks.append(line_break)
+ elif not breaks:
+ chunks.append(u' ')
+ chunks.extend(breaks)
+ elif whitespaces:
+ chunks.append(whitespaces)
+ return chunks
+
+ def scan_tag_handle(self, name, start_mark):
+ # See the specification for details.
+ # For some strange reasons, the specification does not allow '_' in
+ # tag handles. I have allowed it anyway.
+ ch = self.peek()
+ if ch != u'!':
+ raise ScannerError("while scanning a %s" % name, start_mark,
+ "expected '!', but found %r" % ch.encode('utf-8'),
+ self.get_mark())
+ length = 1
+ ch = self.peek(length)
+ if ch != u' ':
+ while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
+ or ch in u'-_':
+ length += 1
+ ch = self.peek(length)
+ if ch != u'!':
+ self.forward(length)
+ raise ScannerError("while scanning a %s" % name, start_mark,
+ "expected '!', but found %r" % ch.encode('utf-8'),
+ self.get_mark())
+ length += 1
+ value = self.prefix(length)
+ self.forward(length)
+ return value
+
+ def scan_tag_uri(self, name, start_mark):
+ # See the specification for details.
+ # Note: we do not check if URI is well-formed.
+ chunks = []
+ length = 0
+ ch = self.peek(length)
+ while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
+ or ch in u'-;/?:@&=+$,_.!~*\'()[]%':
+ if ch == u'%':
+ chunks.append(self.prefix(length))
+ self.forward(length)
+ length = 0
+ chunks.append(self.scan_uri_escapes(name, start_mark))
+ else:
+ length += 1
+ ch = self.peek(length)
+ if length:
+ chunks.append(self.prefix(length))
+ self.forward(length)
+ length = 0
+ if not chunks:
+ raise ScannerError("while parsing a %s" % name, start_mark,
+ "expected URI, but found %r" % ch.encode('utf-8'),
+ self.get_mark())
+ return u''.join(chunks)
+
+ def scan_uri_escapes(self, name, start_mark):
+ # See the specification for details.
+ bytes = []
+ mark = self.get_mark()
+ while self.peek() == u'%':
+ self.forward()
+ for k in range(2):
+ if self.peek(k) not in u'0123456789ABCDEFabcdef':
+ raise ScannerError("while scanning a %s" % name, start_mark,
+ "expected URI escape sequence of 2 hexdecimal numbers, but found %r" %
+ (self.peek(k).encode('utf-8')), self.get_mark())
+ bytes.append(chr(int(self.prefix(2), 16)))
+ self.forward(2)
+ try:
+ value = unicode(''.join(bytes), 'utf-8')
+ except UnicodeDecodeError, exc:
+ raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark)
+ return value
+
+ def scan_line_break(self):
+ # Transforms:
+ # '\r\n' : '\n'
+ # '\r' : '\n'
+ # '\n' : '\n'
+ # '\x85' : '\n'
+ # '\u2028' : '\u2028'
+ # '\u2029 : '\u2029'
+ # default : ''
+ ch = self.peek()
+ if ch in u'\r\n\x85':
+ if self.prefix(2) == u'\r\n':
+ self.forward(2)
+ else:
+ self.forward()
+ return u'\n'
+ elif ch in u'\u2028\u2029':
+ self.forward()
+ return ch
+ return u''
diff --git a/contrib/python/PyYAML/py2/yaml/serializer.py b/contrib/python/PyYAML/py2/yaml/serializer.py
index fc8321150f..0bf1e96dc1 100644
--- a/contrib/python/PyYAML/py2/yaml/serializer.py
+++ b/contrib/python/PyYAML/py2/yaml/serializer.py
@@ -1,111 +1,111 @@
-
-__all__ = ['Serializer', 'SerializerError']
-
-from error import YAMLError
-from events import *
-from nodes import *
-
-class SerializerError(YAMLError):
- pass
-
-class Serializer(object):
-
- ANCHOR_TEMPLATE = u'id%03d'
-
- def __init__(self, encoding=None,
- explicit_start=None, explicit_end=None, version=None, tags=None):
- self.use_encoding = encoding
- self.use_explicit_start = explicit_start
- self.use_explicit_end = explicit_end
- self.use_version = version
- self.use_tags = tags
- self.serialized_nodes = {}
- self.anchors = {}
- self.last_anchor_id = 0
- self.closed = None
-
- def open(self):
- if self.closed is None:
- self.emit(StreamStartEvent(encoding=self.use_encoding))
- self.closed = False
- elif self.closed:
- raise SerializerError("serializer is closed")
- else:
- raise SerializerError("serializer is already opened")
-
- def close(self):
- if self.closed is None:
- raise SerializerError("serializer is not opened")
- elif not self.closed:
- self.emit(StreamEndEvent())
- self.closed = True
-
- #def __del__(self):
- # self.close()
-
- def serialize(self, node):
- if self.closed is None:
- raise SerializerError("serializer is not opened")
- elif self.closed:
- raise SerializerError("serializer is closed")
- self.emit(DocumentStartEvent(explicit=self.use_explicit_start,
- version=self.use_version, tags=self.use_tags))
- self.anchor_node(node)
- self.serialize_node(node, None, None)
- self.emit(DocumentEndEvent(explicit=self.use_explicit_end))
- self.serialized_nodes = {}
- self.anchors = {}
- self.last_anchor_id = 0
-
- def anchor_node(self, node):
- if node in self.anchors:
- if self.anchors[node] is None:
- self.anchors[node] = self.generate_anchor(node)
- else:
- self.anchors[node] = None
- if isinstance(node, SequenceNode):
- for item in node.value:
- self.anchor_node(item)
- elif isinstance(node, MappingNode):
- for key, value in node.value:
- self.anchor_node(key)
- self.anchor_node(value)
-
- def generate_anchor(self, node):
- self.last_anchor_id += 1
- return self.ANCHOR_TEMPLATE % self.last_anchor_id
-
- def serialize_node(self, node, parent, index):
- alias = self.anchors[node]
- if node in self.serialized_nodes:
- self.emit(AliasEvent(alias))
- else:
- self.serialized_nodes[node] = True
- self.descend_resolver(parent, index)
- if isinstance(node, ScalarNode):
- detected_tag = self.resolve(ScalarNode, node.value, (True, False))
- default_tag = self.resolve(ScalarNode, node.value, (False, True))
- implicit = (node.tag == detected_tag), (node.tag == default_tag)
- self.emit(ScalarEvent(alias, node.tag, implicit, node.value,
- style=node.style))
- elif isinstance(node, SequenceNode):
- implicit = (node.tag
- == self.resolve(SequenceNode, node.value, True))
- self.emit(SequenceStartEvent(alias, node.tag, implicit,
- flow_style=node.flow_style))
- index = 0
- for item in node.value:
- self.serialize_node(item, node, index)
- index += 1
- self.emit(SequenceEndEvent())
- elif isinstance(node, MappingNode):
- implicit = (node.tag
- == self.resolve(MappingNode, node.value, True))
- self.emit(MappingStartEvent(alias, node.tag, implicit,
- flow_style=node.flow_style))
- for key, value in node.value:
- self.serialize_node(key, node, None)
- self.serialize_node(value, node, key)
- self.emit(MappingEndEvent())
- self.ascend_resolver()
-
+
+__all__ = ['Serializer', 'SerializerError']
+
+from error import YAMLError
+from events import *
+from nodes import *
+
+class SerializerError(YAMLError):
+ pass
+
+class Serializer(object):
+
+ ANCHOR_TEMPLATE = u'id%03d'
+
+ def __init__(self, encoding=None,
+ explicit_start=None, explicit_end=None, version=None, tags=None):
+ self.use_encoding = encoding
+ self.use_explicit_start = explicit_start
+ self.use_explicit_end = explicit_end
+ self.use_version = version
+ self.use_tags = tags
+ self.serialized_nodes = {}
+ self.anchors = {}
+ self.last_anchor_id = 0
+ self.closed = None
+
+ def open(self):
+ if self.closed is None:
+ self.emit(StreamStartEvent(encoding=self.use_encoding))
+ self.closed = False
+ elif self.closed:
+ raise SerializerError("serializer is closed")
+ else:
+ raise SerializerError("serializer is already opened")
+
+ def close(self):
+ if self.closed is None:
+ raise SerializerError("serializer is not opened")
+ elif not self.closed:
+ self.emit(StreamEndEvent())
+ self.closed = True
+
+ #def __del__(self):
+ # self.close()
+
+ def serialize(self, node):
+ if self.closed is None:
+ raise SerializerError("serializer is not opened")
+ elif self.closed:
+ raise SerializerError("serializer is closed")
+ self.emit(DocumentStartEvent(explicit=self.use_explicit_start,
+ version=self.use_version, tags=self.use_tags))
+ self.anchor_node(node)
+ self.serialize_node(node, None, None)
+ self.emit(DocumentEndEvent(explicit=self.use_explicit_end))
+ self.serialized_nodes = {}
+ self.anchors = {}
+ self.last_anchor_id = 0
+
+ def anchor_node(self, node):
+ if node in self.anchors:
+ if self.anchors[node] is None:
+ self.anchors[node] = self.generate_anchor(node)
+ else:
+ self.anchors[node] = None
+ if isinstance(node, SequenceNode):
+ for item in node.value:
+ self.anchor_node(item)
+ elif isinstance(node, MappingNode):
+ for key, value in node.value:
+ self.anchor_node(key)
+ self.anchor_node(value)
+
+ def generate_anchor(self, node):
+ self.last_anchor_id += 1
+ return self.ANCHOR_TEMPLATE % self.last_anchor_id
+
+ def serialize_node(self, node, parent, index):
+ alias = self.anchors[node]
+ if node in self.serialized_nodes:
+ self.emit(AliasEvent(alias))
+ else:
+ self.serialized_nodes[node] = True
+ self.descend_resolver(parent, index)
+ if isinstance(node, ScalarNode):
+ detected_tag = self.resolve(ScalarNode, node.value, (True, False))
+ default_tag = self.resolve(ScalarNode, node.value, (False, True))
+ implicit = (node.tag == detected_tag), (node.tag == default_tag)
+ self.emit(ScalarEvent(alias, node.tag, implicit, node.value,
+ style=node.style))
+ elif isinstance(node, SequenceNode):
+ implicit = (node.tag
+ == self.resolve(SequenceNode, node.value, True))
+ self.emit(SequenceStartEvent(alias, node.tag, implicit,
+ flow_style=node.flow_style))
+ index = 0
+ for item in node.value:
+ self.serialize_node(item, node, index)
+ index += 1
+ self.emit(SequenceEndEvent())
+ elif isinstance(node, MappingNode):
+ implicit = (node.tag
+ == self.resolve(MappingNode, node.value, True))
+ self.emit(MappingStartEvent(alias, node.tag, implicit,
+ flow_style=node.flow_style))
+ for key, value in node.value:
+ self.serialize_node(key, node, None)
+ self.serialize_node(value, node, key)
+ self.emit(MappingEndEvent())
+ self.ascend_resolver()
+
diff --git a/contrib/python/PyYAML/py2/yaml/tokens.py b/contrib/python/PyYAML/py2/yaml/tokens.py
index 34da1025dd..4d0b48a394 100644
--- a/contrib/python/PyYAML/py2/yaml/tokens.py
+++ b/contrib/python/PyYAML/py2/yaml/tokens.py
@@ -1,104 +1,104 @@
-
-class Token(object):
- def __init__(self, start_mark, end_mark):
- self.start_mark = start_mark
- self.end_mark = end_mark
- def __repr__(self):
- attributes = [key for key in self.__dict__
- if not key.endswith('_mark')]
- attributes.sort()
- arguments = ', '.join(['%s=%r' % (key, getattr(self, key))
- for key in attributes])
- return '%s(%s)' % (self.__class__.__name__, arguments)
-
-#class BOMToken(Token):
-# id = '<byte order mark>'
-
-class DirectiveToken(Token):
- id = '<directive>'
- def __init__(self, name, value, start_mark, end_mark):
- self.name = name
- self.value = value
- self.start_mark = start_mark
- self.end_mark = end_mark
-
-class DocumentStartToken(Token):
- id = '<document start>'
-
-class DocumentEndToken(Token):
- id = '<document end>'
-
-class StreamStartToken(Token):
- id = '<stream start>'
- def __init__(self, start_mark=None, end_mark=None,
- encoding=None):
- self.start_mark = start_mark
- self.end_mark = end_mark
- self.encoding = encoding
-
-class StreamEndToken(Token):
- id = '<stream end>'
-
-class BlockSequenceStartToken(Token):
- id = '<block sequence start>'
-
-class BlockMappingStartToken(Token):
- id = '<block mapping start>'
-
-class BlockEndToken(Token):
- id = '<block end>'
-
-class FlowSequenceStartToken(Token):
- id = '['
-
-class FlowMappingStartToken(Token):
- id = '{'
-
-class FlowSequenceEndToken(Token):
- id = ']'
-
-class FlowMappingEndToken(Token):
- id = '}'
-
-class KeyToken(Token):
- id = '?'
-
-class ValueToken(Token):
- id = ':'
-
-class BlockEntryToken(Token):
- id = '-'
-
-class FlowEntryToken(Token):
- id = ','
-
-class AliasToken(Token):
- id = '<alias>'
- def __init__(self, value, start_mark, end_mark):
- self.value = value
- self.start_mark = start_mark
- self.end_mark = end_mark
-
-class AnchorToken(Token):
- id = '<anchor>'
- def __init__(self, value, start_mark, end_mark):
- self.value = value
- self.start_mark = start_mark
- self.end_mark = end_mark
-
-class TagToken(Token):
- id = '<tag>'
- def __init__(self, value, start_mark, end_mark):
- self.value = value
- self.start_mark = start_mark
- self.end_mark = end_mark
-
-class ScalarToken(Token):
- id = '<scalar>'
- def __init__(self, value, plain, start_mark, end_mark, style=None):
- self.value = value
- self.plain = plain
- self.start_mark = start_mark
- self.end_mark = end_mark
- self.style = style
-
+
+class Token(object):
+ def __init__(self, start_mark, end_mark):
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ def __repr__(self):
+ attributes = [key for key in self.__dict__
+ if not key.endswith('_mark')]
+ attributes.sort()
+ arguments = ', '.join(['%s=%r' % (key, getattr(self, key))
+ for key in attributes])
+ return '%s(%s)' % (self.__class__.__name__, arguments)
+
+#class BOMToken(Token):
+# id = '<byte order mark>'
+
+class DirectiveToken(Token):
+ id = '<directive>'
+ def __init__(self, name, value, start_mark, end_mark):
+ self.name = name
+ self.value = value
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+
+class DocumentStartToken(Token):
+ id = '<document start>'
+
+class DocumentEndToken(Token):
+ id = '<document end>'
+
+class StreamStartToken(Token):
+ id = '<stream start>'
+ def __init__(self, start_mark=None, end_mark=None,
+ encoding=None):
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ self.encoding = encoding
+
+class StreamEndToken(Token):
+ id = '<stream end>'
+
+class BlockSequenceStartToken(Token):
+ id = '<block sequence start>'
+
+class BlockMappingStartToken(Token):
+ id = '<block mapping start>'
+
+class BlockEndToken(Token):
+ id = '<block end>'
+
+class FlowSequenceStartToken(Token):
+ id = '['
+
+class FlowMappingStartToken(Token):
+ id = '{'
+
+class FlowSequenceEndToken(Token):
+ id = ']'
+
+class FlowMappingEndToken(Token):
+ id = '}'
+
+class KeyToken(Token):
+ id = '?'
+
+class ValueToken(Token):
+ id = ':'
+
+class BlockEntryToken(Token):
+ id = '-'
+
+class FlowEntryToken(Token):
+ id = ','
+
+class AliasToken(Token):
+ id = '<alias>'
+ def __init__(self, value, start_mark, end_mark):
+ self.value = value
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+
+class AnchorToken(Token):
+ id = '<anchor>'
+ def __init__(self, value, start_mark, end_mark):
+ self.value = value
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+
+class TagToken(Token):
+ id = '<tag>'
+ def __init__(self, value, start_mark, end_mark):
+ self.value = value
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+
+class ScalarToken(Token):
+ id = '<scalar>'
+ def __init__(self, value, plain, start_mark, end_mark, style=None):
+ self.value = value
+ self.plain = plain
+ self.start_mark = start_mark
+ self.end_mark = end_mark
+ self.style = style
+
diff --git a/contrib/python/PyYAML/py3/LICENSE b/contrib/python/PyYAML/py3/LICENSE
index 63edc20f2f..2f1b8e15e5 100644
--- a/contrib/python/PyYAML/py3/LICENSE
+++ b/contrib/python/PyYAML/py3/LICENSE
@@ -1,20 +1,20 @@
Copyright (c) 2017-2021 Ingy döt Net
Copyright (c) 2006-2016 Kirill Simonov
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-of the Software, and to permit persons to whom the Software is furnished to do
-so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/contrib/python/PyYAML/py3/ya.make b/contrib/python/PyYAML/py3/ya.make
index 628977356a..0401c04651 100644
--- a/contrib/python/PyYAML/py3/ya.make
+++ b/contrib/python/PyYAML/py3/ya.make
@@ -1,43 +1,43 @@
PY3_LIBRARY()
-
+
LICENSE(MIT)
VERSION(5.4.1)
OWNER(g:python-contrib borman g:testenv)
-
+
PEERDIR(
contrib/libs/yaml
)
-
+
ADDINCL(
contrib/python/PyYAML/py3/yaml
)
-PY_SRCS(
- TOP_LEVEL
+PY_SRCS(
+ TOP_LEVEL
_yaml/__init__.py
- yaml/__init__.py
- yaml/composer.py
- yaml/constructor.py
- yaml/cyaml.py
- yaml/dumper.py
- yaml/emitter.py
- yaml/error.py
- yaml/events.py
- yaml/loader.py
- yaml/nodes.py
- yaml/parser.py
- yaml/reader.py
- yaml/representer.py
- yaml/resolver.py
- yaml/scanner.py
- yaml/serializer.py
- yaml/tokens.py
+ yaml/__init__.py
+ yaml/composer.py
+ yaml/constructor.py
+ yaml/cyaml.py
+ yaml/dumper.py
+ yaml/emitter.py
+ yaml/error.py
+ yaml/events.py
+ yaml/loader.py
+ yaml/nodes.py
+ yaml/parser.py
+ yaml/reader.py
+ yaml/representer.py
+ yaml/resolver.py
+ yaml/scanner.py
+ yaml/serializer.py
+ yaml/tokens.py
CYTHON_C
yaml/_yaml.pyx
-)
-
+)
+
RESOURCE_FILES(
PREFIX contrib/python/PyYAML/
.dist-info/METADATA
@@ -48,4 +48,4 @@ NO_LINT()
NO_COMPILER_WARNINGS()
-END()
+END()
diff --git a/contrib/python/PyYAML/py3/yaml/_yaml.h b/contrib/python/PyYAML/py3/yaml/_yaml.h
index 622cfc561a..21fd6a991b 100644
--- a/contrib/python/PyYAML/py3/yaml/_yaml.h
+++ b/contrib/python/PyYAML/py3/yaml/_yaml.h
@@ -1,23 +1,23 @@
-
-#include <yaml.h>
-
-#if PY_MAJOR_VERSION < 3
-
+
+#include <yaml.h>
+
+#if PY_MAJOR_VERSION < 3
+
#define PyUnicode_FromString(s) PyUnicode_DecodeUTF8((s), strlen(s), "strict")
-
-#else
-
-#define PyString_CheckExact PyBytes_CheckExact
-#define PyString_AS_STRING PyBytes_AS_STRING
-#define PyString_GET_SIZE PyBytes_GET_SIZE
-#define PyString_FromStringAndSize PyBytes_FromStringAndSize
-
-#endif
-
-#ifdef _MSC_VER /* MS Visual C++ 6.0 */
-#if _MSC_VER == 1200
-
-#define PyLong_FromUnsignedLongLong(z) PyInt_FromLong(i)
-
-#endif
-#endif
+
+#else
+
+#define PyString_CheckExact PyBytes_CheckExact
+#define PyString_AS_STRING PyBytes_AS_STRING
+#define PyString_GET_SIZE PyBytes_GET_SIZE
+#define PyString_FromStringAndSize PyBytes_FromStringAndSize
+
+#endif
+
+#ifdef _MSC_VER /* MS Visual C++ 6.0 */
+#if _MSC_VER == 1200
+
+#define PyLong_FromUnsignedLongLong(z) PyInt_FromLong(i)
+
+#endif
+#endif
diff --git a/contrib/python/PyYAML/py3/yaml/_yaml.pxd b/contrib/python/PyYAML/py3/yaml/_yaml.pxd
index b6629e26ae..7937c9db51 100644
--- a/contrib/python/PyYAML/py3/yaml/_yaml.pxd
+++ b/contrib/python/PyYAML/py3/yaml/_yaml.pxd
@@ -1,251 +1,251 @@
-
+
cdef extern from "_yaml.h":
-
- void malloc(int l)
- void memcpy(char *d, char *s, int l)
- int strlen(char *s)
- int PyString_CheckExact(object o)
- int PyUnicode_CheckExact(object o)
- char *PyString_AS_STRING(object o)
- int PyString_GET_SIZE(object o)
- object PyString_FromStringAndSize(char *v, int l)
- object PyUnicode_FromString(char *u)
- object PyUnicode_DecodeUTF8(char *u, int s, char *e)
- object PyUnicode_AsUTF8String(object o)
- int PY_MAJOR_VERSION
-
- ctypedef enum:
- SIZEOF_VOID_P
- ctypedef enum yaml_encoding_t:
- YAML_ANY_ENCODING
- YAML_UTF8_ENCODING
- YAML_UTF16LE_ENCODING
- YAML_UTF16BE_ENCODING
- ctypedef enum yaml_break_t:
- YAML_ANY_BREAK
- YAML_CR_BREAK
- YAML_LN_BREAK
- YAML_CRLN_BREAK
- ctypedef enum yaml_error_type_t:
- YAML_NO_ERROR
- YAML_MEMORY_ERROR
- YAML_READER_ERROR
- YAML_SCANNER_ERROR
- YAML_PARSER_ERROR
- YAML_WRITER_ERROR
- YAML_EMITTER_ERROR
- ctypedef enum yaml_scalar_style_t:
- YAML_ANY_SCALAR_STYLE
- YAML_PLAIN_SCALAR_STYLE
- YAML_SINGLE_QUOTED_SCALAR_STYLE
- YAML_DOUBLE_QUOTED_SCALAR_STYLE
- YAML_LITERAL_SCALAR_STYLE
- YAML_FOLDED_SCALAR_STYLE
- ctypedef enum yaml_sequence_style_t:
- YAML_ANY_SEQUENCE_STYLE
- YAML_BLOCK_SEQUENCE_STYLE
- YAML_FLOW_SEQUENCE_STYLE
- ctypedef enum yaml_mapping_style_t:
- YAML_ANY_MAPPING_STYLE
- YAML_BLOCK_MAPPING_STYLE
- YAML_FLOW_MAPPING_STYLE
- ctypedef enum yaml_token_type_t:
- YAML_NO_TOKEN
- YAML_STREAM_START_TOKEN
- YAML_STREAM_END_TOKEN
- YAML_VERSION_DIRECTIVE_TOKEN
- YAML_TAG_DIRECTIVE_TOKEN
- YAML_DOCUMENT_START_TOKEN
- YAML_DOCUMENT_END_TOKEN
- YAML_BLOCK_SEQUENCE_START_TOKEN
- YAML_BLOCK_MAPPING_START_TOKEN
- YAML_BLOCK_END_TOKEN
- YAML_FLOW_SEQUENCE_START_TOKEN
- YAML_FLOW_SEQUENCE_END_TOKEN
- YAML_FLOW_MAPPING_START_TOKEN
- YAML_FLOW_MAPPING_END_TOKEN
- YAML_BLOCK_ENTRY_TOKEN
- YAML_FLOW_ENTRY_TOKEN
- YAML_KEY_TOKEN
- YAML_VALUE_TOKEN
- YAML_ALIAS_TOKEN
- YAML_ANCHOR_TOKEN
- YAML_TAG_TOKEN
- YAML_SCALAR_TOKEN
- ctypedef enum yaml_event_type_t:
- YAML_NO_EVENT
- YAML_STREAM_START_EVENT
- YAML_STREAM_END_EVENT
- YAML_DOCUMENT_START_EVENT
- YAML_DOCUMENT_END_EVENT
- YAML_ALIAS_EVENT
- YAML_SCALAR_EVENT
- YAML_SEQUENCE_START_EVENT
- YAML_SEQUENCE_END_EVENT
- YAML_MAPPING_START_EVENT
- YAML_MAPPING_END_EVENT
-
+
+ void malloc(int l)
+ void memcpy(char *d, char *s, int l)
+ int strlen(char *s)
+ int PyString_CheckExact(object o)
+ int PyUnicode_CheckExact(object o)
+ char *PyString_AS_STRING(object o)
+ int PyString_GET_SIZE(object o)
+ object PyString_FromStringAndSize(char *v, int l)
+ object PyUnicode_FromString(char *u)
+ object PyUnicode_DecodeUTF8(char *u, int s, char *e)
+ object PyUnicode_AsUTF8String(object o)
+ int PY_MAJOR_VERSION
+
+ ctypedef enum:
+ SIZEOF_VOID_P
+ ctypedef enum yaml_encoding_t:
+ YAML_ANY_ENCODING
+ YAML_UTF8_ENCODING
+ YAML_UTF16LE_ENCODING
+ YAML_UTF16BE_ENCODING
+ ctypedef enum yaml_break_t:
+ YAML_ANY_BREAK
+ YAML_CR_BREAK
+ YAML_LN_BREAK
+ YAML_CRLN_BREAK
+ ctypedef enum yaml_error_type_t:
+ YAML_NO_ERROR
+ YAML_MEMORY_ERROR
+ YAML_READER_ERROR
+ YAML_SCANNER_ERROR
+ YAML_PARSER_ERROR
+ YAML_WRITER_ERROR
+ YAML_EMITTER_ERROR
+ ctypedef enum yaml_scalar_style_t:
+ YAML_ANY_SCALAR_STYLE
+ YAML_PLAIN_SCALAR_STYLE
+ YAML_SINGLE_QUOTED_SCALAR_STYLE
+ YAML_DOUBLE_QUOTED_SCALAR_STYLE
+ YAML_LITERAL_SCALAR_STYLE
+ YAML_FOLDED_SCALAR_STYLE
+ ctypedef enum yaml_sequence_style_t:
+ YAML_ANY_SEQUENCE_STYLE
+ YAML_BLOCK_SEQUENCE_STYLE
+ YAML_FLOW_SEQUENCE_STYLE
+ ctypedef enum yaml_mapping_style_t:
+ YAML_ANY_MAPPING_STYLE
+ YAML_BLOCK_MAPPING_STYLE
+ YAML_FLOW_MAPPING_STYLE
+ ctypedef enum yaml_token_type_t:
+ YAML_NO_TOKEN
+ YAML_STREAM_START_TOKEN
+ YAML_STREAM_END_TOKEN
+ YAML_VERSION_DIRECTIVE_TOKEN
+ YAML_TAG_DIRECTIVE_TOKEN
+ YAML_DOCUMENT_START_TOKEN
+ YAML_DOCUMENT_END_TOKEN
+ YAML_BLOCK_SEQUENCE_START_TOKEN
+ YAML_BLOCK_MAPPING_START_TOKEN
+ YAML_BLOCK_END_TOKEN
+ YAML_FLOW_SEQUENCE_START_TOKEN
+ YAML_FLOW_SEQUENCE_END_TOKEN
+ YAML_FLOW_MAPPING_START_TOKEN
+ YAML_FLOW_MAPPING_END_TOKEN
+ YAML_BLOCK_ENTRY_TOKEN
+ YAML_FLOW_ENTRY_TOKEN
+ YAML_KEY_TOKEN
+ YAML_VALUE_TOKEN
+ YAML_ALIAS_TOKEN
+ YAML_ANCHOR_TOKEN
+ YAML_TAG_TOKEN
+ YAML_SCALAR_TOKEN
+ ctypedef enum yaml_event_type_t:
+ YAML_NO_EVENT
+ YAML_STREAM_START_EVENT
+ YAML_STREAM_END_EVENT
+ YAML_DOCUMENT_START_EVENT
+ YAML_DOCUMENT_END_EVENT
+ YAML_ALIAS_EVENT
+ YAML_SCALAR_EVENT
+ YAML_SEQUENCE_START_EVENT
+ YAML_SEQUENCE_END_EVENT
+ YAML_MAPPING_START_EVENT
+ YAML_MAPPING_END_EVENT
+
ctypedef int yaml_read_handler_t(void *data, char *buffer,
- size_t size, size_t *size_read) except 0
-
+ size_t size, size_t *size_read) except 0
+
ctypedef int yaml_write_handler_t(void *data, char *buffer,
- size_t size) except 0
-
- ctypedef struct yaml_mark_t:
+ size_t size) except 0
+
+ ctypedef struct yaml_mark_t:
size_t index
size_t line
size_t column
- ctypedef struct yaml_version_directive_t:
- int major
- int minor
- ctypedef struct yaml_tag_directive_t:
+ ctypedef struct yaml_version_directive_t:
+ int major
+ int minor
+ ctypedef struct yaml_tag_directive_t:
char *handle
char *prefix
-
- ctypedef struct _yaml_token_stream_start_data_t:
- yaml_encoding_t encoding
- ctypedef struct _yaml_token_alias_data_t:
- char *value
- ctypedef struct _yaml_token_anchor_data_t:
- char *value
- ctypedef struct _yaml_token_tag_data_t:
+
+ ctypedef struct _yaml_token_stream_start_data_t:
+ yaml_encoding_t encoding
+ ctypedef struct _yaml_token_alias_data_t:
+ char *value
+ ctypedef struct _yaml_token_anchor_data_t:
+ char *value
+ ctypedef struct _yaml_token_tag_data_t:
char *handle
char *suffix
- ctypedef struct _yaml_token_scalar_data_t:
- char *value
+ ctypedef struct _yaml_token_scalar_data_t:
+ char *value
size_t length
- yaml_scalar_style_t style
- ctypedef struct _yaml_token_version_directive_data_t:
- int major
- int minor
- ctypedef struct _yaml_token_tag_directive_data_t:
+ yaml_scalar_style_t style
+ ctypedef struct _yaml_token_version_directive_data_t:
+ int major
+ int minor
+ ctypedef struct _yaml_token_tag_directive_data_t:
char *handle
char *prefix
- ctypedef union _yaml_token_data_t:
- _yaml_token_stream_start_data_t stream_start
- _yaml_token_alias_data_t alias
- _yaml_token_anchor_data_t anchor
- _yaml_token_tag_data_t tag
- _yaml_token_scalar_data_t scalar
- _yaml_token_version_directive_data_t version_directive
- _yaml_token_tag_directive_data_t tag_directive
- ctypedef struct yaml_token_t:
- yaml_token_type_t type
- _yaml_token_data_t data
- yaml_mark_t start_mark
- yaml_mark_t end_mark
-
- ctypedef struct _yaml_event_stream_start_data_t:
- yaml_encoding_t encoding
- ctypedef struct _yaml_event_document_start_data_tag_directives_t:
- yaml_tag_directive_t *start
- yaml_tag_directive_t *end
- ctypedef struct _yaml_event_document_start_data_t:
- yaml_version_directive_t *version_directive
- _yaml_event_document_start_data_tag_directives_t tag_directives
- int implicit
- ctypedef struct _yaml_event_document_end_data_t:
- int implicit
- ctypedef struct _yaml_event_alias_data_t:
- char *anchor
- ctypedef struct _yaml_event_scalar_data_t:
- char *anchor
- char *tag
- char *value
+ ctypedef union _yaml_token_data_t:
+ _yaml_token_stream_start_data_t stream_start
+ _yaml_token_alias_data_t alias
+ _yaml_token_anchor_data_t anchor
+ _yaml_token_tag_data_t tag
+ _yaml_token_scalar_data_t scalar
+ _yaml_token_version_directive_data_t version_directive
+ _yaml_token_tag_directive_data_t tag_directive
+ ctypedef struct yaml_token_t:
+ yaml_token_type_t type
+ _yaml_token_data_t data
+ yaml_mark_t start_mark
+ yaml_mark_t end_mark
+
+ ctypedef struct _yaml_event_stream_start_data_t:
+ yaml_encoding_t encoding
+ ctypedef struct _yaml_event_document_start_data_tag_directives_t:
+ yaml_tag_directive_t *start
+ yaml_tag_directive_t *end
+ ctypedef struct _yaml_event_document_start_data_t:
+ yaml_version_directive_t *version_directive
+ _yaml_event_document_start_data_tag_directives_t tag_directives
+ int implicit
+ ctypedef struct _yaml_event_document_end_data_t:
+ int implicit
+ ctypedef struct _yaml_event_alias_data_t:
+ char *anchor
+ ctypedef struct _yaml_event_scalar_data_t:
+ char *anchor
+ char *tag
+ char *value
size_t length
- int plain_implicit
- int quoted_implicit
- yaml_scalar_style_t style
- ctypedef struct _yaml_event_sequence_start_data_t:
- char *anchor
- char *tag
- int implicit
- yaml_sequence_style_t style
- ctypedef struct _yaml_event_mapping_start_data_t:
- char *anchor
- char *tag
- int implicit
- yaml_mapping_style_t style
- ctypedef union _yaml_event_data_t:
- _yaml_event_stream_start_data_t stream_start
- _yaml_event_document_start_data_t document_start
- _yaml_event_document_end_data_t document_end
- _yaml_event_alias_data_t alias
- _yaml_event_scalar_data_t scalar
- _yaml_event_sequence_start_data_t sequence_start
- _yaml_event_mapping_start_data_t mapping_start
- ctypedef struct yaml_event_t:
- yaml_event_type_t type
- _yaml_event_data_t data
- yaml_mark_t start_mark
- yaml_mark_t end_mark
-
- ctypedef struct yaml_parser_t:
- yaml_error_type_t error
- char *problem
+ int plain_implicit
+ int quoted_implicit
+ yaml_scalar_style_t style
+ ctypedef struct _yaml_event_sequence_start_data_t:
+ char *anchor
+ char *tag
+ int implicit
+ yaml_sequence_style_t style
+ ctypedef struct _yaml_event_mapping_start_data_t:
+ char *anchor
+ char *tag
+ int implicit
+ yaml_mapping_style_t style
+ ctypedef union _yaml_event_data_t:
+ _yaml_event_stream_start_data_t stream_start
+ _yaml_event_document_start_data_t document_start
+ _yaml_event_document_end_data_t document_end
+ _yaml_event_alias_data_t alias
+ _yaml_event_scalar_data_t scalar
+ _yaml_event_sequence_start_data_t sequence_start
+ _yaml_event_mapping_start_data_t mapping_start
+ ctypedef struct yaml_event_t:
+ yaml_event_type_t type
+ _yaml_event_data_t data
+ yaml_mark_t start_mark
+ yaml_mark_t end_mark
+
+ ctypedef struct yaml_parser_t:
+ yaml_error_type_t error
+ char *problem
size_t problem_offset
- int problem_value
- yaml_mark_t problem_mark
- char *context
- yaml_mark_t context_mark
-
- ctypedef struct yaml_emitter_t:
- yaml_error_type_t error
- char *problem
-
- char *yaml_get_version_string()
- void yaml_get_version(int *major, int *minor, int *patch)
-
- void yaml_token_delete(yaml_token_t *token)
-
- int yaml_stream_start_event_initialize(yaml_event_t *event,
- yaml_encoding_t encoding)
- int yaml_stream_end_event_initialize(yaml_event_t *event)
- int yaml_document_start_event_initialize(yaml_event_t *event,
- yaml_version_directive_t *version_directive,
- yaml_tag_directive_t *tag_directives_start,
- yaml_tag_directive_t *tag_directives_end,
- int implicit)
- int yaml_document_end_event_initialize(yaml_event_t *event,
- int implicit)
+ int problem_value
+ yaml_mark_t problem_mark
+ char *context
+ yaml_mark_t context_mark
+
+ ctypedef struct yaml_emitter_t:
+ yaml_error_type_t error
+ char *problem
+
+ char *yaml_get_version_string()
+ void yaml_get_version(int *major, int *minor, int *patch)
+
+ void yaml_token_delete(yaml_token_t *token)
+
+ int yaml_stream_start_event_initialize(yaml_event_t *event,
+ yaml_encoding_t encoding)
+ int yaml_stream_end_event_initialize(yaml_event_t *event)
+ int yaml_document_start_event_initialize(yaml_event_t *event,
+ yaml_version_directive_t *version_directive,
+ yaml_tag_directive_t *tag_directives_start,
+ yaml_tag_directive_t *tag_directives_end,
+ int implicit)
+ int yaml_document_end_event_initialize(yaml_event_t *event,
+ int implicit)
int yaml_alias_event_initialize(yaml_event_t *event, char *anchor)
- int yaml_scalar_event_initialize(yaml_event_t *event,
+ int yaml_scalar_event_initialize(yaml_event_t *event,
char *anchor, char *tag, char *value, size_t length,
- int plain_implicit, int quoted_implicit,
- yaml_scalar_style_t style)
- int yaml_sequence_start_event_initialize(yaml_event_t *event,
+ int plain_implicit, int quoted_implicit,
+ yaml_scalar_style_t style)
+ int yaml_sequence_start_event_initialize(yaml_event_t *event,
char *anchor, char *tag, int implicit, yaml_sequence_style_t style)
- int yaml_sequence_end_event_initialize(yaml_event_t *event)
- int yaml_mapping_start_event_initialize(yaml_event_t *event,
+ int yaml_sequence_end_event_initialize(yaml_event_t *event)
+ int yaml_mapping_start_event_initialize(yaml_event_t *event,
char *anchor, char *tag, int implicit, yaml_mapping_style_t style)
- int yaml_mapping_end_event_initialize(yaml_event_t *event)
- void yaml_event_delete(yaml_event_t *event)
-
- int yaml_parser_initialize(yaml_parser_t *parser)
- void yaml_parser_delete(yaml_parser_t *parser)
- void yaml_parser_set_input_string(yaml_parser_t *parser,
+ int yaml_mapping_end_event_initialize(yaml_event_t *event)
+ void yaml_event_delete(yaml_event_t *event)
+
+ int yaml_parser_initialize(yaml_parser_t *parser)
+ void yaml_parser_delete(yaml_parser_t *parser)
+ void yaml_parser_set_input_string(yaml_parser_t *parser,
char *input, size_t size)
- void yaml_parser_set_input(yaml_parser_t *parser,
- yaml_read_handler_t *handler, void *data)
- void yaml_parser_set_encoding(yaml_parser_t *parser,
- yaml_encoding_t encoding)
- int yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token) except *
- int yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event) except *
-
- int yaml_emitter_initialize(yaml_emitter_t *emitter)
- void yaml_emitter_delete(yaml_emitter_t *emitter)
- void yaml_emitter_set_output_string(yaml_emitter_t *emitter,
+ void yaml_parser_set_input(yaml_parser_t *parser,
+ yaml_read_handler_t *handler, void *data)
+ void yaml_parser_set_encoding(yaml_parser_t *parser,
+ yaml_encoding_t encoding)
+ int yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token) except *
+ int yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event) except *
+
+ int yaml_emitter_initialize(yaml_emitter_t *emitter)
+ void yaml_emitter_delete(yaml_emitter_t *emitter)
+ void yaml_emitter_set_output_string(yaml_emitter_t *emitter,
char *output, size_t size, size_t *size_written)
- void yaml_emitter_set_output(yaml_emitter_t *emitter,
- yaml_write_handler_t *handler, void *data)
- void yaml_emitter_set_encoding(yaml_emitter_t *emitter,
- yaml_encoding_t encoding)
- void yaml_emitter_set_canonical(yaml_emitter_t *emitter, int canonical)
- void yaml_emitter_set_indent(yaml_emitter_t *emitter, int indent)
- void yaml_emitter_set_width(yaml_emitter_t *emitter, int width)
- void yaml_emitter_set_unicode(yaml_emitter_t *emitter, int unicode)
- void yaml_emitter_set_break(yaml_emitter_t *emitter,
- yaml_break_t line_break)
- int yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event) except *
- int yaml_emitter_flush(yaml_emitter_t *emitter)
-
+ void yaml_emitter_set_output(yaml_emitter_t *emitter,
+ yaml_write_handler_t *handler, void *data)
+ void yaml_emitter_set_encoding(yaml_emitter_t *emitter,
+ yaml_encoding_t encoding)
+ void yaml_emitter_set_canonical(yaml_emitter_t *emitter, int canonical)
+ void yaml_emitter_set_indent(yaml_emitter_t *emitter, int indent)
+ void yaml_emitter_set_width(yaml_emitter_t *emitter, int width)
+ void yaml_emitter_set_unicode(yaml_emitter_t *emitter, int unicode)
+ void yaml_emitter_set_break(yaml_emitter_t *emitter,
+ yaml_break_t line_break)
+ int yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event) except *
+ int yaml_emitter_flush(yaml_emitter_t *emitter)
+
diff --git a/contrib/python/PyYAML/py3/yaml/_yaml.pyx b/contrib/python/PyYAML/py3/yaml/_yaml.pyx
index efdb347aff..ff4efe80b5 100644
--- a/contrib/python/PyYAML/py3/yaml/_yaml.pyx
+++ b/contrib/python/PyYAML/py3/yaml/_yaml.pyx
@@ -1,1527 +1,1527 @@
-
-import yaml
-
-def get_version_string():
+
+import yaml
+
+def get_version_string():
cdef char *value
- value = yaml_get_version_string()
- if PY_MAJOR_VERSION < 3:
- return value
- else:
- return PyUnicode_FromString(value)
-
-def get_version():
- cdef int major, minor, patch
- yaml_get_version(&major, &minor, &patch)
- return (major, minor, patch)
-
-#Mark = yaml.error.Mark
-YAMLError = yaml.error.YAMLError
-ReaderError = yaml.reader.ReaderError
-ScannerError = yaml.scanner.ScannerError
-ParserError = yaml.parser.ParserError
-ComposerError = yaml.composer.ComposerError
-ConstructorError = yaml.constructor.ConstructorError
-EmitterError = yaml.emitter.EmitterError
-SerializerError = yaml.serializer.SerializerError
-RepresenterError = yaml.representer.RepresenterError
-
-StreamStartToken = yaml.tokens.StreamStartToken
-StreamEndToken = yaml.tokens.StreamEndToken
-DirectiveToken = yaml.tokens.DirectiveToken
-DocumentStartToken = yaml.tokens.DocumentStartToken
-DocumentEndToken = yaml.tokens.DocumentEndToken
-BlockSequenceStartToken = yaml.tokens.BlockSequenceStartToken
-BlockMappingStartToken = yaml.tokens.BlockMappingStartToken
-BlockEndToken = yaml.tokens.BlockEndToken
-FlowSequenceStartToken = yaml.tokens.FlowSequenceStartToken
-FlowMappingStartToken = yaml.tokens.FlowMappingStartToken
-FlowSequenceEndToken = yaml.tokens.FlowSequenceEndToken
-FlowMappingEndToken = yaml.tokens.FlowMappingEndToken
-KeyToken = yaml.tokens.KeyToken
-ValueToken = yaml.tokens.ValueToken
-BlockEntryToken = yaml.tokens.BlockEntryToken
-FlowEntryToken = yaml.tokens.FlowEntryToken
-AliasToken = yaml.tokens.AliasToken
-AnchorToken = yaml.tokens.AnchorToken
-TagToken = yaml.tokens.TagToken
-ScalarToken = yaml.tokens.ScalarToken
-
-StreamStartEvent = yaml.events.StreamStartEvent
-StreamEndEvent = yaml.events.StreamEndEvent
-DocumentStartEvent = yaml.events.DocumentStartEvent
-DocumentEndEvent = yaml.events.DocumentEndEvent
-AliasEvent = yaml.events.AliasEvent
-ScalarEvent = yaml.events.ScalarEvent
-SequenceStartEvent = yaml.events.SequenceStartEvent
-SequenceEndEvent = yaml.events.SequenceEndEvent
-MappingStartEvent = yaml.events.MappingStartEvent
-MappingEndEvent = yaml.events.MappingEndEvent
-
-ScalarNode = yaml.nodes.ScalarNode
-SequenceNode = yaml.nodes.SequenceNode
-MappingNode = yaml.nodes.MappingNode
-
-cdef class Mark:
- cdef readonly object name
+ value = yaml_get_version_string()
+ if PY_MAJOR_VERSION < 3:
+ return value
+ else:
+ return PyUnicode_FromString(value)
+
+def get_version():
+ cdef int major, minor, patch
+ yaml_get_version(&major, &minor, &patch)
+ return (major, minor, patch)
+
+#Mark = yaml.error.Mark
+YAMLError = yaml.error.YAMLError
+ReaderError = yaml.reader.ReaderError
+ScannerError = yaml.scanner.ScannerError
+ParserError = yaml.parser.ParserError
+ComposerError = yaml.composer.ComposerError
+ConstructorError = yaml.constructor.ConstructorError
+EmitterError = yaml.emitter.EmitterError
+SerializerError = yaml.serializer.SerializerError
+RepresenterError = yaml.representer.RepresenterError
+
+StreamStartToken = yaml.tokens.StreamStartToken
+StreamEndToken = yaml.tokens.StreamEndToken
+DirectiveToken = yaml.tokens.DirectiveToken
+DocumentStartToken = yaml.tokens.DocumentStartToken
+DocumentEndToken = yaml.tokens.DocumentEndToken
+BlockSequenceStartToken = yaml.tokens.BlockSequenceStartToken
+BlockMappingStartToken = yaml.tokens.BlockMappingStartToken
+BlockEndToken = yaml.tokens.BlockEndToken
+FlowSequenceStartToken = yaml.tokens.FlowSequenceStartToken
+FlowMappingStartToken = yaml.tokens.FlowMappingStartToken
+FlowSequenceEndToken = yaml.tokens.FlowSequenceEndToken
+FlowMappingEndToken = yaml.tokens.FlowMappingEndToken
+KeyToken = yaml.tokens.KeyToken
+ValueToken = yaml.tokens.ValueToken
+BlockEntryToken = yaml.tokens.BlockEntryToken
+FlowEntryToken = yaml.tokens.FlowEntryToken
+AliasToken = yaml.tokens.AliasToken
+AnchorToken = yaml.tokens.AnchorToken
+TagToken = yaml.tokens.TagToken
+ScalarToken = yaml.tokens.ScalarToken
+
+StreamStartEvent = yaml.events.StreamStartEvent
+StreamEndEvent = yaml.events.StreamEndEvent
+DocumentStartEvent = yaml.events.DocumentStartEvent
+DocumentEndEvent = yaml.events.DocumentEndEvent
+AliasEvent = yaml.events.AliasEvent
+ScalarEvent = yaml.events.ScalarEvent
+SequenceStartEvent = yaml.events.SequenceStartEvent
+SequenceEndEvent = yaml.events.SequenceEndEvent
+MappingStartEvent = yaml.events.MappingStartEvent
+MappingEndEvent = yaml.events.MappingEndEvent
+
+ScalarNode = yaml.nodes.ScalarNode
+SequenceNode = yaml.nodes.SequenceNode
+MappingNode = yaml.nodes.MappingNode
+
+cdef class Mark:
+ cdef readonly object name
cdef readonly size_t index
cdef readonly size_t line
cdef readonly size_t column
- cdef readonly buffer
- cdef readonly pointer
-
+ cdef readonly buffer
+ cdef readonly pointer
+
def __init__(self, object name, size_t index, size_t line, size_t column,
- object buffer, object pointer):
- self.name = name
- self.index = index
- self.line = line
- self.column = column
- self.buffer = buffer
- self.pointer = pointer
-
- def get_snippet(self):
- return None
-
- def __str__(self):
- where = " in \"%s\", line %d, column %d" \
- % (self.name, self.line+1, self.column+1)
- return where
-
-#class YAMLError(Exception):
-# pass
-#
-#class MarkedYAMLError(YAMLError):
-#
-# def __init__(self, context=None, context_mark=None,
-# problem=None, problem_mark=None, note=None):
-# self.context = context
-# self.context_mark = context_mark
-# self.problem = problem
-# self.problem_mark = problem_mark
-# self.note = note
-#
-# def __str__(self):
-# lines = []
-# if self.context is not None:
-# lines.append(self.context)
-# if self.context_mark is not None \
-# and (self.problem is None or self.problem_mark is None
-# or self.context_mark.name != self.problem_mark.name
-# or self.context_mark.line != self.problem_mark.line
-# or self.context_mark.column != self.problem_mark.column):
-# lines.append(str(self.context_mark))
-# if self.problem is not None:
-# lines.append(self.problem)
-# if self.problem_mark is not None:
-# lines.append(str(self.problem_mark))
-# if self.note is not None:
-# lines.append(self.note)
-# return '\n'.join(lines)
-#
-#class ReaderError(YAMLError):
-#
-# def __init__(self, name, position, character, encoding, reason):
-# self.name = name
-# self.character = character
-# self.position = position
-# self.encoding = encoding
-# self.reason = reason
-#
-# def __str__(self):
-# if isinstance(self.character, str):
-# return "'%s' codec can't decode byte #x%02x: %s\n" \
-# " in \"%s\", position %d" \
-# % (self.encoding, ord(self.character), self.reason,
-# self.name, self.position)
-# else:
-# return "unacceptable character #x%04x: %s\n" \
-# " in \"%s\", position %d" \
-# % (ord(self.character), self.reason,
-# self.name, self.position)
-#
-#class ScannerError(MarkedYAMLError):
-# pass
-#
-#class ParserError(MarkedYAMLError):
-# pass
-#
-#class EmitterError(YAMLError):
-# pass
-#
-#cdef class Token:
-# cdef readonly Mark start_mark
-# cdef readonly Mark end_mark
-# def __init__(self, Mark start_mark, Mark end_mark):
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-#
-#cdef class StreamStartToken(Token):
-# cdef readonly object encoding
-# def __init__(self, Mark start_mark, Mark end_mark, encoding):
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-# self.encoding = encoding
-#
-#cdef class StreamEndToken(Token):
-# pass
-#
-#cdef class DirectiveToken(Token):
-# cdef readonly object name
-# cdef readonly object value
-# def __init__(self, name, value, Mark start_mark, Mark end_mark):
-# self.name = name
-# self.value = value
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-#
-#cdef class DocumentStartToken(Token):
-# pass
-#
-#cdef class DocumentEndToken(Token):
-# pass
-#
-#cdef class BlockSequenceStartToken(Token):
-# pass
-#
-#cdef class BlockMappingStartToken(Token):
-# pass
-#
-#cdef class BlockEndToken(Token):
-# pass
-#
-#cdef class FlowSequenceStartToken(Token):
-# pass
-#
-#cdef class FlowMappingStartToken(Token):
-# pass
-#
-#cdef class FlowSequenceEndToken(Token):
-# pass
-#
-#cdef class FlowMappingEndToken(Token):
-# pass
-#
-#cdef class KeyToken(Token):
-# pass
-#
-#cdef class ValueToken(Token):
-# pass
-#
-#cdef class BlockEntryToken(Token):
-# pass
-#
-#cdef class FlowEntryToken(Token):
-# pass
-#
-#cdef class AliasToken(Token):
-# cdef readonly object value
-# def __init__(self, value, Mark start_mark, Mark end_mark):
-# self.value = value
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-#
-#cdef class AnchorToken(Token):
-# cdef readonly object value
-# def __init__(self, value, Mark start_mark, Mark end_mark):
-# self.value = value
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-#
-#cdef class TagToken(Token):
-# cdef readonly object value
-# def __init__(self, value, Mark start_mark, Mark end_mark):
-# self.value = value
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-#
-#cdef class ScalarToken(Token):
-# cdef readonly object value
-# cdef readonly object plain
-# cdef readonly object style
-# def __init__(self, value, plain, Mark start_mark, Mark end_mark, style=None):
-# self.value = value
-# self.plain = plain
-# self.start_mark = start_mark
-# self.end_mark = end_mark
-# self.style = style
-
-cdef class CParser:
-
- cdef yaml_parser_t parser
- cdef yaml_event_t parsed_event
-
- cdef object stream
- cdef object stream_name
- cdef object current_token
- cdef object current_event
- cdef object anchors
- cdef object stream_cache
+ object buffer, object pointer):
+ self.name = name
+ self.index = index
+ self.line = line
+ self.column = column
+ self.buffer = buffer
+ self.pointer = pointer
+
+ def get_snippet(self):
+ return None
+
+ def __str__(self):
+ where = " in \"%s\", line %d, column %d" \
+ % (self.name, self.line+1, self.column+1)
+ return where
+
+#class YAMLError(Exception):
+# pass
+#
+#class MarkedYAMLError(YAMLError):
+#
+# def __init__(self, context=None, context_mark=None,
+# problem=None, problem_mark=None, note=None):
+# self.context = context
+# self.context_mark = context_mark
+# self.problem = problem
+# self.problem_mark = problem_mark
+# self.note = note
+#
+# def __str__(self):
+# lines = []
+# if self.context is not None:
+# lines.append(self.context)
+# if self.context_mark is not None \
+# and (self.problem is None or self.problem_mark is None
+# or self.context_mark.name != self.problem_mark.name
+# or self.context_mark.line != self.problem_mark.line
+# or self.context_mark.column != self.problem_mark.column):
+# lines.append(str(self.context_mark))
+# if self.problem is not None:
+# lines.append(self.problem)
+# if self.problem_mark is not None:
+# lines.append(str(self.problem_mark))
+# if self.note is not None:
+# lines.append(self.note)
+# return '\n'.join(lines)
+#
+#class ReaderError(YAMLError):
+#
+# def __init__(self, name, position, character, encoding, reason):
+# self.name = name
+# self.character = character
+# self.position = position
+# self.encoding = encoding
+# self.reason = reason
+#
+# def __str__(self):
+# if isinstance(self.character, str):
+# return "'%s' codec can't decode byte #x%02x: %s\n" \
+# " in \"%s\", position %d" \
+# % (self.encoding, ord(self.character), self.reason,
+# self.name, self.position)
+# else:
+# return "unacceptable character #x%04x: %s\n" \
+# " in \"%s\", position %d" \
+# % (ord(self.character), self.reason,
+# self.name, self.position)
+#
+#class ScannerError(MarkedYAMLError):
+# pass
+#
+#class ParserError(MarkedYAMLError):
+# pass
+#
+#class EmitterError(YAMLError):
+# pass
+#
+#cdef class Token:
+# cdef readonly Mark start_mark
+# cdef readonly Mark end_mark
+# def __init__(self, Mark start_mark, Mark end_mark):
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+#
+#cdef class StreamStartToken(Token):
+# cdef readonly object encoding
+# def __init__(self, Mark start_mark, Mark end_mark, encoding):
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+# self.encoding = encoding
+#
+#cdef class StreamEndToken(Token):
+# pass
+#
+#cdef class DirectiveToken(Token):
+# cdef readonly object name
+# cdef readonly object value
+# def __init__(self, name, value, Mark start_mark, Mark end_mark):
+# self.name = name
+# self.value = value
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+#
+#cdef class DocumentStartToken(Token):
+# pass
+#
+#cdef class DocumentEndToken(Token):
+# pass
+#
+#cdef class BlockSequenceStartToken(Token):
+# pass
+#
+#cdef class BlockMappingStartToken(Token):
+# pass
+#
+#cdef class BlockEndToken(Token):
+# pass
+#
+#cdef class FlowSequenceStartToken(Token):
+# pass
+#
+#cdef class FlowMappingStartToken(Token):
+# pass
+#
+#cdef class FlowSequenceEndToken(Token):
+# pass
+#
+#cdef class FlowMappingEndToken(Token):
+# pass
+#
+#cdef class KeyToken(Token):
+# pass
+#
+#cdef class ValueToken(Token):
+# pass
+#
+#cdef class BlockEntryToken(Token):
+# pass
+#
+#cdef class FlowEntryToken(Token):
+# pass
+#
+#cdef class AliasToken(Token):
+# cdef readonly object value
+# def __init__(self, value, Mark start_mark, Mark end_mark):
+# self.value = value
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+#
+#cdef class AnchorToken(Token):
+# cdef readonly object value
+# def __init__(self, value, Mark start_mark, Mark end_mark):
+# self.value = value
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+#
+#cdef class TagToken(Token):
+# cdef readonly object value
+# def __init__(self, value, Mark start_mark, Mark end_mark):
+# self.value = value
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+#
+#cdef class ScalarToken(Token):
+# cdef readonly object value
+# cdef readonly object plain
+# cdef readonly object style
+# def __init__(self, value, plain, Mark start_mark, Mark end_mark, style=None):
+# self.value = value
+# self.plain = plain
+# self.start_mark = start_mark
+# self.end_mark = end_mark
+# self.style = style
+
+cdef class CParser:
+
+ cdef yaml_parser_t parser
+ cdef yaml_event_t parsed_event
+
+ cdef object stream
+ cdef object stream_name
+ cdef object current_token
+ cdef object current_event
+ cdef object anchors
+ cdef object stream_cache
cdef int stream_cache_len
cdef int stream_cache_pos
- cdef int unicode_source
-
- def __init__(self, stream):
- cdef is_readable
- if yaml_parser_initialize(&self.parser) == 0:
- raise MemoryError
- self.parsed_event.type = YAML_NO_EVENT
- is_readable = 1
- try:
- stream.read
- except AttributeError:
- is_readable = 0
- self.unicode_source = 0
- if is_readable:
- self.stream = stream
- try:
- self.stream_name = stream.name
- except AttributeError:
- if PY_MAJOR_VERSION < 3:
- self.stream_name = '<file>'
- else:
- self.stream_name = u'<file>'
- self.stream_cache = None
- self.stream_cache_len = 0
- self.stream_cache_pos = 0
- yaml_parser_set_input(&self.parser, input_handler, <void *>self)
- else:
- if PyUnicode_CheckExact(stream) != 0:
- stream = PyUnicode_AsUTF8String(stream)
- if PY_MAJOR_VERSION < 3:
- self.stream_name = '<unicode string>'
- else:
- self.stream_name = u'<unicode string>'
- self.unicode_source = 1
- else:
- if PY_MAJOR_VERSION < 3:
- self.stream_name = '<byte string>'
- else:
- self.stream_name = u'<byte string>'
- if PyString_CheckExact(stream) == 0:
- if PY_MAJOR_VERSION < 3:
- raise TypeError("a string or stream input is required")
- else:
- raise TypeError(u"a string or stream input is required")
- self.stream = stream
+ cdef int unicode_source
+
+ def __init__(self, stream):
+ cdef is_readable
+ if yaml_parser_initialize(&self.parser) == 0:
+ raise MemoryError
+ self.parsed_event.type = YAML_NO_EVENT
+ is_readable = 1
+ try:
+ stream.read
+ except AttributeError:
+ is_readable = 0
+ self.unicode_source = 0
+ if is_readable:
+ self.stream = stream
+ try:
+ self.stream_name = stream.name
+ except AttributeError:
+ if PY_MAJOR_VERSION < 3:
+ self.stream_name = '<file>'
+ else:
+ self.stream_name = u'<file>'
+ self.stream_cache = None
+ self.stream_cache_len = 0
+ self.stream_cache_pos = 0
+ yaml_parser_set_input(&self.parser, input_handler, <void *>self)
+ else:
+ if PyUnicode_CheckExact(stream) != 0:
+ stream = PyUnicode_AsUTF8String(stream)
+ if PY_MAJOR_VERSION < 3:
+ self.stream_name = '<unicode string>'
+ else:
+ self.stream_name = u'<unicode string>'
+ self.unicode_source = 1
+ else:
+ if PY_MAJOR_VERSION < 3:
+ self.stream_name = '<byte string>'
+ else:
+ self.stream_name = u'<byte string>'
+ if PyString_CheckExact(stream) == 0:
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("a string or stream input is required")
+ else:
+ raise TypeError(u"a string or stream input is required")
+ self.stream = stream
yaml_parser_set_input_string(&self.parser, PyString_AS_STRING(stream), PyString_GET_SIZE(stream))
- self.current_token = None
- self.current_event = None
- self.anchors = {}
-
- def __dealloc__(self):
- yaml_parser_delete(&self.parser)
- yaml_event_delete(&self.parsed_event)
-
- def dispose(self):
- pass
-
- cdef object _parser_error(self):
- if self.parser.error == YAML_MEMORY_ERROR:
- return MemoryError
- elif self.parser.error == YAML_READER_ERROR:
- if PY_MAJOR_VERSION < 3:
- return ReaderError(self.stream_name, self.parser.problem_offset,
- self.parser.problem_value, '?', self.parser.problem)
- else:
- return ReaderError(self.stream_name, self.parser.problem_offset,
- self.parser.problem_value, u'?', PyUnicode_FromString(self.parser.problem))
- elif self.parser.error == YAML_SCANNER_ERROR \
- or self.parser.error == YAML_PARSER_ERROR:
- context_mark = None
- problem_mark = None
- if self.parser.context != NULL:
- context_mark = Mark(self.stream_name,
- self.parser.context_mark.index,
- self.parser.context_mark.line,
- self.parser.context_mark.column, None, None)
- if self.parser.problem != NULL:
- problem_mark = Mark(self.stream_name,
- self.parser.problem_mark.index,
- self.parser.problem_mark.line,
- self.parser.problem_mark.column, None, None)
- context = None
- if self.parser.context != NULL:
- if PY_MAJOR_VERSION < 3:
- context = self.parser.context
- else:
- context = PyUnicode_FromString(self.parser.context)
- if PY_MAJOR_VERSION < 3:
- problem = self.parser.problem
- else:
- problem = PyUnicode_FromString(self.parser.problem)
- if self.parser.error == YAML_SCANNER_ERROR:
- return ScannerError(context, context_mark, problem, problem_mark)
- else:
- return ParserError(context, context_mark, problem, problem_mark)
- if PY_MAJOR_VERSION < 3:
- raise ValueError("no parser error")
- else:
- raise ValueError(u"no parser error")
-
- def raw_scan(self):
- cdef yaml_token_t token
- cdef int done
- cdef int count
- count = 0
- done = 0
- while done == 0:
- if yaml_parser_scan(&self.parser, &token) == 0:
- error = self._parser_error()
- raise error
- if token.type == YAML_NO_TOKEN:
- done = 1
- else:
- count = count+1
- yaml_token_delete(&token)
- return count
-
- cdef object _scan(self):
- cdef yaml_token_t token
- if yaml_parser_scan(&self.parser, &token) == 0:
- error = self._parser_error()
- raise error
- token_object = self._token_to_object(&token)
- yaml_token_delete(&token)
- return token_object
-
- cdef object _token_to_object(self, yaml_token_t *token):
- start_mark = Mark(self.stream_name,
- token.start_mark.index,
- token.start_mark.line,
- token.start_mark.column,
- None, None)
- end_mark = Mark(self.stream_name,
- token.end_mark.index,
- token.end_mark.line,
- token.end_mark.column,
- None, None)
- if token.type == YAML_NO_TOKEN:
- return None
- elif token.type == YAML_STREAM_START_TOKEN:
- encoding = None
- if token.data.stream_start.encoding == YAML_UTF8_ENCODING:
- if self.unicode_source == 0:
- encoding = u"utf-8"
- elif token.data.stream_start.encoding == YAML_UTF16LE_ENCODING:
- encoding = u"utf-16-le"
- elif token.data.stream_start.encoding == YAML_UTF16BE_ENCODING:
- encoding = u"utf-16-be"
- return StreamStartToken(start_mark, end_mark, encoding)
- elif token.type == YAML_STREAM_END_TOKEN:
- return StreamEndToken(start_mark, end_mark)
- elif token.type == YAML_VERSION_DIRECTIVE_TOKEN:
- return DirectiveToken(u"YAML",
- (token.data.version_directive.major,
- token.data.version_directive.minor),
- start_mark, end_mark)
- elif token.type == YAML_TAG_DIRECTIVE_TOKEN:
+ self.current_token = None
+ self.current_event = None
+ self.anchors = {}
+
+ def __dealloc__(self):
+ yaml_parser_delete(&self.parser)
+ yaml_event_delete(&self.parsed_event)
+
+ def dispose(self):
+ pass
+
+ cdef object _parser_error(self):
+ if self.parser.error == YAML_MEMORY_ERROR:
+ return MemoryError
+ elif self.parser.error == YAML_READER_ERROR:
+ if PY_MAJOR_VERSION < 3:
+ return ReaderError(self.stream_name, self.parser.problem_offset,
+ self.parser.problem_value, '?', self.parser.problem)
+ else:
+ return ReaderError(self.stream_name, self.parser.problem_offset,
+ self.parser.problem_value, u'?', PyUnicode_FromString(self.parser.problem))
+ elif self.parser.error == YAML_SCANNER_ERROR \
+ or self.parser.error == YAML_PARSER_ERROR:
+ context_mark = None
+ problem_mark = None
+ if self.parser.context != NULL:
+ context_mark = Mark(self.stream_name,
+ self.parser.context_mark.index,
+ self.parser.context_mark.line,
+ self.parser.context_mark.column, None, None)
+ if self.parser.problem != NULL:
+ problem_mark = Mark(self.stream_name,
+ self.parser.problem_mark.index,
+ self.parser.problem_mark.line,
+ self.parser.problem_mark.column, None, None)
+ context = None
+ if self.parser.context != NULL:
+ if PY_MAJOR_VERSION < 3:
+ context = self.parser.context
+ else:
+ context = PyUnicode_FromString(self.parser.context)
+ if PY_MAJOR_VERSION < 3:
+ problem = self.parser.problem
+ else:
+ problem = PyUnicode_FromString(self.parser.problem)
+ if self.parser.error == YAML_SCANNER_ERROR:
+ return ScannerError(context, context_mark, problem, problem_mark)
+ else:
+ return ParserError(context, context_mark, problem, problem_mark)
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("no parser error")
+ else:
+ raise ValueError(u"no parser error")
+
+ def raw_scan(self):
+ cdef yaml_token_t token
+ cdef int done
+ cdef int count
+ count = 0
+ done = 0
+ while done == 0:
+ if yaml_parser_scan(&self.parser, &token) == 0:
+ error = self._parser_error()
+ raise error
+ if token.type == YAML_NO_TOKEN:
+ done = 1
+ else:
+ count = count+1
+ yaml_token_delete(&token)
+ return count
+
+ cdef object _scan(self):
+ cdef yaml_token_t token
+ if yaml_parser_scan(&self.parser, &token) == 0:
+ error = self._parser_error()
+ raise error
+ token_object = self._token_to_object(&token)
+ yaml_token_delete(&token)
+ return token_object
+
+ cdef object _token_to_object(self, yaml_token_t *token):
+ start_mark = Mark(self.stream_name,
+ token.start_mark.index,
+ token.start_mark.line,
+ token.start_mark.column,
+ None, None)
+ end_mark = Mark(self.stream_name,
+ token.end_mark.index,
+ token.end_mark.line,
+ token.end_mark.column,
+ None, None)
+ if token.type == YAML_NO_TOKEN:
+ return None
+ elif token.type == YAML_STREAM_START_TOKEN:
+ encoding = None
+ if token.data.stream_start.encoding == YAML_UTF8_ENCODING:
+ if self.unicode_source == 0:
+ encoding = u"utf-8"
+ elif token.data.stream_start.encoding == YAML_UTF16LE_ENCODING:
+ encoding = u"utf-16-le"
+ elif token.data.stream_start.encoding == YAML_UTF16BE_ENCODING:
+ encoding = u"utf-16-be"
+ return StreamStartToken(start_mark, end_mark, encoding)
+ elif token.type == YAML_STREAM_END_TOKEN:
+ return StreamEndToken(start_mark, end_mark)
+ elif token.type == YAML_VERSION_DIRECTIVE_TOKEN:
+ return DirectiveToken(u"YAML",
+ (token.data.version_directive.major,
+ token.data.version_directive.minor),
+ start_mark, end_mark)
+ elif token.type == YAML_TAG_DIRECTIVE_TOKEN:
handle = PyUnicode_FromString(token.data.tag_directive.handle)
prefix = PyUnicode_FromString(token.data.tag_directive.prefix)
- return DirectiveToken(u"TAG", (handle, prefix),
- start_mark, end_mark)
- elif token.type == YAML_DOCUMENT_START_TOKEN:
- return DocumentStartToken(start_mark, end_mark)
- elif token.type == YAML_DOCUMENT_END_TOKEN:
- return DocumentEndToken(start_mark, end_mark)
- elif token.type == YAML_BLOCK_SEQUENCE_START_TOKEN:
- return BlockSequenceStartToken(start_mark, end_mark)
- elif token.type == YAML_BLOCK_MAPPING_START_TOKEN:
- return BlockMappingStartToken(start_mark, end_mark)
- elif token.type == YAML_BLOCK_END_TOKEN:
- return BlockEndToken(start_mark, end_mark)
- elif token.type == YAML_FLOW_SEQUENCE_START_TOKEN:
- return FlowSequenceStartToken(start_mark, end_mark)
- elif token.type == YAML_FLOW_SEQUENCE_END_TOKEN:
- return FlowSequenceEndToken(start_mark, end_mark)
- elif token.type == YAML_FLOW_MAPPING_START_TOKEN:
- return FlowMappingStartToken(start_mark, end_mark)
- elif token.type == YAML_FLOW_MAPPING_END_TOKEN:
- return FlowMappingEndToken(start_mark, end_mark)
- elif token.type == YAML_BLOCK_ENTRY_TOKEN:
- return BlockEntryToken(start_mark, end_mark)
- elif token.type == YAML_FLOW_ENTRY_TOKEN:
- return FlowEntryToken(start_mark, end_mark)
- elif token.type == YAML_KEY_TOKEN:
- return KeyToken(start_mark, end_mark)
- elif token.type == YAML_VALUE_TOKEN:
- return ValueToken(start_mark, end_mark)
- elif token.type == YAML_ALIAS_TOKEN:
- value = PyUnicode_FromString(token.data.alias.value)
- return AliasToken(value, start_mark, end_mark)
- elif token.type == YAML_ANCHOR_TOKEN:
- value = PyUnicode_FromString(token.data.anchor.value)
- return AnchorToken(value, start_mark, end_mark)
- elif token.type == YAML_TAG_TOKEN:
+ return DirectiveToken(u"TAG", (handle, prefix),
+ start_mark, end_mark)
+ elif token.type == YAML_DOCUMENT_START_TOKEN:
+ return DocumentStartToken(start_mark, end_mark)
+ elif token.type == YAML_DOCUMENT_END_TOKEN:
+ return DocumentEndToken(start_mark, end_mark)
+ elif token.type == YAML_BLOCK_SEQUENCE_START_TOKEN:
+ return BlockSequenceStartToken(start_mark, end_mark)
+ elif token.type == YAML_BLOCK_MAPPING_START_TOKEN:
+ return BlockMappingStartToken(start_mark, end_mark)
+ elif token.type == YAML_BLOCK_END_TOKEN:
+ return BlockEndToken(start_mark, end_mark)
+ elif token.type == YAML_FLOW_SEQUENCE_START_TOKEN:
+ return FlowSequenceStartToken(start_mark, end_mark)
+ elif token.type == YAML_FLOW_SEQUENCE_END_TOKEN:
+ return FlowSequenceEndToken(start_mark, end_mark)
+ elif token.type == YAML_FLOW_MAPPING_START_TOKEN:
+ return FlowMappingStartToken(start_mark, end_mark)
+ elif token.type == YAML_FLOW_MAPPING_END_TOKEN:
+ return FlowMappingEndToken(start_mark, end_mark)
+ elif token.type == YAML_BLOCK_ENTRY_TOKEN:
+ return BlockEntryToken(start_mark, end_mark)
+ elif token.type == YAML_FLOW_ENTRY_TOKEN:
+ return FlowEntryToken(start_mark, end_mark)
+ elif token.type == YAML_KEY_TOKEN:
+ return KeyToken(start_mark, end_mark)
+ elif token.type == YAML_VALUE_TOKEN:
+ return ValueToken(start_mark, end_mark)
+ elif token.type == YAML_ALIAS_TOKEN:
+ value = PyUnicode_FromString(token.data.alias.value)
+ return AliasToken(value, start_mark, end_mark)
+ elif token.type == YAML_ANCHOR_TOKEN:
+ value = PyUnicode_FromString(token.data.anchor.value)
+ return AnchorToken(value, start_mark, end_mark)
+ elif token.type == YAML_TAG_TOKEN:
handle = PyUnicode_FromString(token.data.tag.handle)
suffix = PyUnicode_FromString(token.data.tag.suffix)
- if not handle:
- handle = None
- return TagToken((handle, suffix), start_mark, end_mark)
- elif token.type == YAML_SCALAR_TOKEN:
+ if not handle:
+ handle = None
+ return TagToken((handle, suffix), start_mark, end_mark)
+ elif token.type == YAML_SCALAR_TOKEN:
value = PyUnicode_DecodeUTF8(token.data.scalar.value,
- token.data.scalar.length, 'strict')
- plain = False
- style = None
- if token.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
- plain = True
- style = u''
- elif token.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
- style = u'\''
- elif token.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
- style = u'"'
- elif token.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
- style = u'|'
- elif token.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
- style = u'>'
- return ScalarToken(value, plain,
- start_mark, end_mark, style)
- else:
- if PY_MAJOR_VERSION < 3:
- raise ValueError("unknown token type")
- else:
- raise ValueError(u"unknown token type")
-
- def get_token(self):
- if self.current_token is not None:
- value = self.current_token
- self.current_token = None
- else:
- value = self._scan()
- return value
-
- def peek_token(self):
- if self.current_token is None:
- self.current_token = self._scan()
- return self.current_token
-
- def check_token(self, *choices):
- if self.current_token is None:
- self.current_token = self._scan()
- if self.current_token is None:
- return False
- if not choices:
- return True
- token_class = self.current_token.__class__
- for choice in choices:
- if token_class is choice:
- return True
- return False
-
- def raw_parse(self):
- cdef yaml_event_t event
- cdef int done
- cdef int count
- count = 0
- done = 0
- while done == 0:
- if yaml_parser_parse(&self.parser, &event) == 0:
- error = self._parser_error()
- raise error
- if event.type == YAML_NO_EVENT:
- done = 1
- else:
- count = count+1
- yaml_event_delete(&event)
- return count
-
- cdef object _parse(self):
- cdef yaml_event_t event
- if yaml_parser_parse(&self.parser, &event) == 0:
- error = self._parser_error()
- raise error
- event_object = self._event_to_object(&event)
- yaml_event_delete(&event)
- return event_object
-
- cdef object _event_to_object(self, yaml_event_t *event):
- cdef yaml_tag_directive_t *tag_directive
- start_mark = Mark(self.stream_name,
- event.start_mark.index,
- event.start_mark.line,
- event.start_mark.column,
- None, None)
- end_mark = Mark(self.stream_name,
- event.end_mark.index,
- event.end_mark.line,
- event.end_mark.column,
- None, None)
- if event.type == YAML_NO_EVENT:
- return None
- elif event.type == YAML_STREAM_START_EVENT:
- encoding = None
- if event.data.stream_start.encoding == YAML_UTF8_ENCODING:
- if self.unicode_source == 0:
- encoding = u"utf-8"
- elif event.data.stream_start.encoding == YAML_UTF16LE_ENCODING:
- encoding = u"utf-16-le"
- elif event.data.stream_start.encoding == YAML_UTF16BE_ENCODING:
- encoding = u"utf-16-be"
- return StreamStartEvent(start_mark, end_mark, encoding)
- elif event.type == YAML_STREAM_END_EVENT:
- return StreamEndEvent(start_mark, end_mark)
- elif event.type == YAML_DOCUMENT_START_EVENT:
- explicit = False
- if event.data.document_start.implicit == 0:
- explicit = True
- version = None
- if event.data.document_start.version_directive != NULL:
- version = (event.data.document_start.version_directive.major,
- event.data.document_start.version_directive.minor)
- tags = None
- if event.data.document_start.tag_directives.start != NULL:
- tags = {}
- tag_directive = event.data.document_start.tag_directives.start
- while tag_directive != event.data.document_start.tag_directives.end:
+ token.data.scalar.length, 'strict')
+ plain = False
+ style = None
+ if token.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
+ plain = True
+ style = u''
+ elif token.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
+ style = u'\''
+ elif token.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
+ style = u'"'
+ elif token.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
+ style = u'|'
+ elif token.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
+ style = u'>'
+ return ScalarToken(value, plain,
+ start_mark, end_mark, style)
+ else:
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("unknown token type")
+ else:
+ raise ValueError(u"unknown token type")
+
+ def get_token(self):
+ if self.current_token is not None:
+ value = self.current_token
+ self.current_token = None
+ else:
+ value = self._scan()
+ return value
+
+ def peek_token(self):
+ if self.current_token is None:
+ self.current_token = self._scan()
+ return self.current_token
+
+ def check_token(self, *choices):
+ if self.current_token is None:
+ self.current_token = self._scan()
+ if self.current_token is None:
+ return False
+ if not choices:
+ return True
+ token_class = self.current_token.__class__
+ for choice in choices:
+ if token_class is choice:
+ return True
+ return False
+
+ def raw_parse(self):
+ cdef yaml_event_t event
+ cdef int done
+ cdef int count
+ count = 0
+ done = 0
+ while done == 0:
+ if yaml_parser_parse(&self.parser, &event) == 0:
+ error = self._parser_error()
+ raise error
+ if event.type == YAML_NO_EVENT:
+ done = 1
+ else:
+ count = count+1
+ yaml_event_delete(&event)
+ return count
+
+ cdef object _parse(self):
+ cdef yaml_event_t event
+ if yaml_parser_parse(&self.parser, &event) == 0:
+ error = self._parser_error()
+ raise error
+ event_object = self._event_to_object(&event)
+ yaml_event_delete(&event)
+ return event_object
+
+ cdef object _event_to_object(self, yaml_event_t *event):
+ cdef yaml_tag_directive_t *tag_directive
+ start_mark = Mark(self.stream_name,
+ event.start_mark.index,
+ event.start_mark.line,
+ event.start_mark.column,
+ None, None)
+ end_mark = Mark(self.stream_name,
+ event.end_mark.index,
+ event.end_mark.line,
+ event.end_mark.column,
+ None, None)
+ if event.type == YAML_NO_EVENT:
+ return None
+ elif event.type == YAML_STREAM_START_EVENT:
+ encoding = None
+ if event.data.stream_start.encoding == YAML_UTF8_ENCODING:
+ if self.unicode_source == 0:
+ encoding = u"utf-8"
+ elif event.data.stream_start.encoding == YAML_UTF16LE_ENCODING:
+ encoding = u"utf-16-le"
+ elif event.data.stream_start.encoding == YAML_UTF16BE_ENCODING:
+ encoding = u"utf-16-be"
+ return StreamStartEvent(start_mark, end_mark, encoding)
+ elif event.type == YAML_STREAM_END_EVENT:
+ return StreamEndEvent(start_mark, end_mark)
+ elif event.type == YAML_DOCUMENT_START_EVENT:
+ explicit = False
+ if event.data.document_start.implicit == 0:
+ explicit = True
+ version = None
+ if event.data.document_start.version_directive != NULL:
+ version = (event.data.document_start.version_directive.major,
+ event.data.document_start.version_directive.minor)
+ tags = None
+ if event.data.document_start.tag_directives.start != NULL:
+ tags = {}
+ tag_directive = event.data.document_start.tag_directives.start
+ while tag_directive != event.data.document_start.tag_directives.end:
handle = PyUnicode_FromString(tag_directive.handle)
prefix = PyUnicode_FromString(tag_directive.prefix)
- tags[handle] = prefix
- tag_directive = tag_directive+1
- return DocumentStartEvent(start_mark, end_mark,
- explicit, version, tags)
- elif event.type == YAML_DOCUMENT_END_EVENT:
- explicit = False
- if event.data.document_end.implicit == 0:
- explicit = True
- return DocumentEndEvent(start_mark, end_mark, explicit)
- elif event.type == YAML_ALIAS_EVENT:
- anchor = PyUnicode_FromString(event.data.alias.anchor)
- return AliasEvent(anchor, start_mark, end_mark)
- elif event.type == YAML_SCALAR_EVENT:
- anchor = None
- if event.data.scalar.anchor != NULL:
- anchor = PyUnicode_FromString(event.data.scalar.anchor)
- tag = None
- if event.data.scalar.tag != NULL:
- tag = PyUnicode_FromString(event.data.scalar.tag)
+ tags[handle] = prefix
+ tag_directive = tag_directive+1
+ return DocumentStartEvent(start_mark, end_mark,
+ explicit, version, tags)
+ elif event.type == YAML_DOCUMENT_END_EVENT:
+ explicit = False
+ if event.data.document_end.implicit == 0:
+ explicit = True
+ return DocumentEndEvent(start_mark, end_mark, explicit)
+ elif event.type == YAML_ALIAS_EVENT:
+ anchor = PyUnicode_FromString(event.data.alias.anchor)
+ return AliasEvent(anchor, start_mark, end_mark)
+ elif event.type == YAML_SCALAR_EVENT:
+ anchor = None
+ if event.data.scalar.anchor != NULL:
+ anchor = PyUnicode_FromString(event.data.scalar.anchor)
+ tag = None
+ if event.data.scalar.tag != NULL:
+ tag = PyUnicode_FromString(event.data.scalar.tag)
value = PyUnicode_DecodeUTF8(event.data.scalar.value,
- event.data.scalar.length, 'strict')
- plain_implicit = False
- if event.data.scalar.plain_implicit == 1:
- plain_implicit = True
- quoted_implicit = False
- if event.data.scalar.quoted_implicit == 1:
- quoted_implicit = True
- style = None
- if event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
- style = u''
- elif event.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
- style = u'\''
- elif event.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
- style = u'"'
- elif event.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
- style = u'|'
- elif event.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
- style = u'>'
- return ScalarEvent(anchor, tag,
- (plain_implicit, quoted_implicit),
- value, start_mark, end_mark, style)
- elif event.type == YAML_SEQUENCE_START_EVENT:
- anchor = None
- if event.data.sequence_start.anchor != NULL:
- anchor = PyUnicode_FromString(event.data.sequence_start.anchor)
- tag = None
- if event.data.sequence_start.tag != NULL:
- tag = PyUnicode_FromString(event.data.sequence_start.tag)
- implicit = False
- if event.data.sequence_start.implicit == 1:
- implicit = True
- flow_style = None
- if event.data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE:
- flow_style = True
- elif event.data.sequence_start.style == YAML_BLOCK_SEQUENCE_STYLE:
- flow_style = False
- return SequenceStartEvent(anchor, tag, implicit,
- start_mark, end_mark, flow_style)
- elif event.type == YAML_MAPPING_START_EVENT:
- anchor = None
- if event.data.mapping_start.anchor != NULL:
- anchor = PyUnicode_FromString(event.data.mapping_start.anchor)
- tag = None
- if event.data.mapping_start.tag != NULL:
- tag = PyUnicode_FromString(event.data.mapping_start.tag)
- implicit = False
- if event.data.mapping_start.implicit == 1:
- implicit = True
- flow_style = None
- if event.data.mapping_start.style == YAML_FLOW_MAPPING_STYLE:
- flow_style = True
- elif event.data.mapping_start.style == YAML_BLOCK_MAPPING_STYLE:
- flow_style = False
- return MappingStartEvent(anchor, tag, implicit,
- start_mark, end_mark, flow_style)
- elif event.type == YAML_SEQUENCE_END_EVENT:
- return SequenceEndEvent(start_mark, end_mark)
- elif event.type == YAML_MAPPING_END_EVENT:
- return MappingEndEvent(start_mark, end_mark)
- else:
- if PY_MAJOR_VERSION < 3:
- raise ValueError("unknown event type")
- else:
- raise ValueError(u"unknown event type")
-
- def get_event(self):
- if self.current_event is not None:
- value = self.current_event
- self.current_event = None
- else:
- value = self._parse()
- return value
-
- def peek_event(self):
- if self.current_event is None:
- self.current_event = self._parse()
- return self.current_event
-
- def check_event(self, *choices):
- if self.current_event is None:
- self.current_event = self._parse()
- if self.current_event is None:
- return False
- if not choices:
- return True
- event_class = self.current_event.__class__
- for choice in choices:
- if event_class is choice:
- return True
- return False
-
- def check_node(self):
- self._parse_next_event()
- if self.parsed_event.type == YAML_STREAM_START_EVENT:
- yaml_event_delete(&self.parsed_event)
- self._parse_next_event()
- if self.parsed_event.type != YAML_STREAM_END_EVENT:
- return True
- return False
-
- def get_node(self):
- self._parse_next_event()
- if self.parsed_event.type != YAML_STREAM_END_EVENT:
- return self._compose_document()
-
- def get_single_node(self):
- self._parse_next_event()
- yaml_event_delete(&self.parsed_event)
- self._parse_next_event()
- document = None
- if self.parsed_event.type != YAML_STREAM_END_EVENT:
- document = self._compose_document()
- self._parse_next_event()
- if self.parsed_event.type != YAML_STREAM_END_EVENT:
- mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- if PY_MAJOR_VERSION < 3:
- raise ComposerError("expected a single document in the stream",
- document.start_mark, "but found another document", mark)
- else:
- raise ComposerError(u"expected a single document in the stream",
- document.start_mark, u"but found another document", mark)
- return document
-
- cdef object _compose_document(self):
- yaml_event_delete(&self.parsed_event)
- node = self._compose_node(None, None)
- self._parse_next_event()
- yaml_event_delete(&self.parsed_event)
- self.anchors = {}
- return node
-
- cdef object _compose_node(self, object parent, object index):
- self._parse_next_event()
- if self.parsed_event.type == YAML_ALIAS_EVENT:
- anchor = PyUnicode_FromString(self.parsed_event.data.alias.anchor)
- if anchor not in self.anchors:
- mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- if PY_MAJOR_VERSION < 3:
- raise ComposerError(None, None, "found undefined alias", mark)
- else:
- raise ComposerError(None, None, u"found undefined alias", mark)
- yaml_event_delete(&self.parsed_event)
- return self.anchors[anchor]
- anchor = None
- if self.parsed_event.type == YAML_SCALAR_EVENT \
- and self.parsed_event.data.scalar.anchor != NULL:
- anchor = PyUnicode_FromString(self.parsed_event.data.scalar.anchor)
- elif self.parsed_event.type == YAML_SEQUENCE_START_EVENT \
- and self.parsed_event.data.sequence_start.anchor != NULL:
- anchor = PyUnicode_FromString(self.parsed_event.data.sequence_start.anchor)
- elif self.parsed_event.type == YAML_MAPPING_START_EVENT \
- and self.parsed_event.data.mapping_start.anchor != NULL:
- anchor = PyUnicode_FromString(self.parsed_event.data.mapping_start.anchor)
- if anchor is not None:
- if anchor in self.anchors:
- mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- if PY_MAJOR_VERSION < 3:
+ event.data.scalar.length, 'strict')
+ plain_implicit = False
+ if event.data.scalar.plain_implicit == 1:
+ plain_implicit = True
+ quoted_implicit = False
+ if event.data.scalar.quoted_implicit == 1:
+ quoted_implicit = True
+ style = None
+ if event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
+ style = u''
+ elif event.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
+ style = u'\''
+ elif event.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
+ style = u'"'
+ elif event.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
+ style = u'|'
+ elif event.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
+ style = u'>'
+ return ScalarEvent(anchor, tag,
+ (plain_implicit, quoted_implicit),
+ value, start_mark, end_mark, style)
+ elif event.type == YAML_SEQUENCE_START_EVENT:
+ anchor = None
+ if event.data.sequence_start.anchor != NULL:
+ anchor = PyUnicode_FromString(event.data.sequence_start.anchor)
+ tag = None
+ if event.data.sequence_start.tag != NULL:
+ tag = PyUnicode_FromString(event.data.sequence_start.tag)
+ implicit = False
+ if event.data.sequence_start.implicit == 1:
+ implicit = True
+ flow_style = None
+ if event.data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE:
+ flow_style = True
+ elif event.data.sequence_start.style == YAML_BLOCK_SEQUENCE_STYLE:
+ flow_style = False
+ return SequenceStartEvent(anchor, tag, implicit,
+ start_mark, end_mark, flow_style)
+ elif event.type == YAML_MAPPING_START_EVENT:
+ anchor = None
+ if event.data.mapping_start.anchor != NULL:
+ anchor = PyUnicode_FromString(event.data.mapping_start.anchor)
+ tag = None
+ if event.data.mapping_start.tag != NULL:
+ tag = PyUnicode_FromString(event.data.mapping_start.tag)
+ implicit = False
+ if event.data.mapping_start.implicit == 1:
+ implicit = True
+ flow_style = None
+ if event.data.mapping_start.style == YAML_FLOW_MAPPING_STYLE:
+ flow_style = True
+ elif event.data.mapping_start.style == YAML_BLOCK_MAPPING_STYLE:
+ flow_style = False
+ return MappingStartEvent(anchor, tag, implicit,
+ start_mark, end_mark, flow_style)
+ elif event.type == YAML_SEQUENCE_END_EVENT:
+ return SequenceEndEvent(start_mark, end_mark)
+ elif event.type == YAML_MAPPING_END_EVENT:
+ return MappingEndEvent(start_mark, end_mark)
+ else:
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("unknown event type")
+ else:
+ raise ValueError(u"unknown event type")
+
+ def get_event(self):
+ if self.current_event is not None:
+ value = self.current_event
+ self.current_event = None
+ else:
+ value = self._parse()
+ return value
+
+ def peek_event(self):
+ if self.current_event is None:
+ self.current_event = self._parse()
+ return self.current_event
+
+ def check_event(self, *choices):
+ if self.current_event is None:
+ self.current_event = self._parse()
+ if self.current_event is None:
+ return False
+ if not choices:
+ return True
+ event_class = self.current_event.__class__
+ for choice in choices:
+ if event_class is choice:
+ return True
+ return False
+
+ def check_node(self):
+ self._parse_next_event()
+ if self.parsed_event.type == YAML_STREAM_START_EVENT:
+ yaml_event_delete(&self.parsed_event)
+ self._parse_next_event()
+ if self.parsed_event.type != YAML_STREAM_END_EVENT:
+ return True
+ return False
+
+ def get_node(self):
+ self._parse_next_event()
+ if self.parsed_event.type != YAML_STREAM_END_EVENT:
+ return self._compose_document()
+
+ def get_single_node(self):
+ self._parse_next_event()
+ yaml_event_delete(&self.parsed_event)
+ self._parse_next_event()
+ document = None
+ if self.parsed_event.type != YAML_STREAM_END_EVENT:
+ document = self._compose_document()
+ self._parse_next_event()
+ if self.parsed_event.type != YAML_STREAM_END_EVENT:
+ mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ if PY_MAJOR_VERSION < 3:
+ raise ComposerError("expected a single document in the stream",
+ document.start_mark, "but found another document", mark)
+ else:
+ raise ComposerError(u"expected a single document in the stream",
+ document.start_mark, u"but found another document", mark)
+ return document
+
+ cdef object _compose_document(self):
+ yaml_event_delete(&self.parsed_event)
+ node = self._compose_node(None, None)
+ self._parse_next_event()
+ yaml_event_delete(&self.parsed_event)
+ self.anchors = {}
+ return node
+
+ cdef object _compose_node(self, object parent, object index):
+ self._parse_next_event()
+ if self.parsed_event.type == YAML_ALIAS_EVENT:
+ anchor = PyUnicode_FromString(self.parsed_event.data.alias.anchor)
+ if anchor not in self.anchors:
+ mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ if PY_MAJOR_VERSION < 3:
+ raise ComposerError(None, None, "found undefined alias", mark)
+ else:
+ raise ComposerError(None, None, u"found undefined alias", mark)
+ yaml_event_delete(&self.parsed_event)
+ return self.anchors[anchor]
+ anchor = None
+ if self.parsed_event.type == YAML_SCALAR_EVENT \
+ and self.parsed_event.data.scalar.anchor != NULL:
+ anchor = PyUnicode_FromString(self.parsed_event.data.scalar.anchor)
+ elif self.parsed_event.type == YAML_SEQUENCE_START_EVENT \
+ and self.parsed_event.data.sequence_start.anchor != NULL:
+ anchor = PyUnicode_FromString(self.parsed_event.data.sequence_start.anchor)
+ elif self.parsed_event.type == YAML_MAPPING_START_EVENT \
+ and self.parsed_event.data.mapping_start.anchor != NULL:
+ anchor = PyUnicode_FromString(self.parsed_event.data.mapping_start.anchor)
+ if anchor is not None:
+ if anchor in self.anchors:
+ mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ if PY_MAJOR_VERSION < 3:
raise ComposerError("found duplicate anchor; first occurrence",
self.anchors[anchor].start_mark, "second occurrence", mark)
- else:
+ else:
raise ComposerError(u"found duplicate anchor; first occurrence",
self.anchors[anchor].start_mark, u"second occurrence", mark)
- self.descend_resolver(parent, index)
- if self.parsed_event.type == YAML_SCALAR_EVENT:
- node = self._compose_scalar_node(anchor)
- elif self.parsed_event.type == YAML_SEQUENCE_START_EVENT:
- node = self._compose_sequence_node(anchor)
- elif self.parsed_event.type == YAML_MAPPING_START_EVENT:
- node = self._compose_mapping_node(anchor)
- self.ascend_resolver()
- return node
-
- cdef _compose_scalar_node(self, object anchor):
- start_mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- end_mark = Mark(self.stream_name,
- self.parsed_event.end_mark.index,
- self.parsed_event.end_mark.line,
- self.parsed_event.end_mark.column,
- None, None)
+ self.descend_resolver(parent, index)
+ if self.parsed_event.type == YAML_SCALAR_EVENT:
+ node = self._compose_scalar_node(anchor)
+ elif self.parsed_event.type == YAML_SEQUENCE_START_EVENT:
+ node = self._compose_sequence_node(anchor)
+ elif self.parsed_event.type == YAML_MAPPING_START_EVENT:
+ node = self._compose_mapping_node(anchor)
+ self.ascend_resolver()
+ return node
+
+ cdef _compose_scalar_node(self, object anchor):
+ start_mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ end_mark = Mark(self.stream_name,
+ self.parsed_event.end_mark.index,
+ self.parsed_event.end_mark.line,
+ self.parsed_event.end_mark.column,
+ None, None)
value = PyUnicode_DecodeUTF8(self.parsed_event.data.scalar.value,
- self.parsed_event.data.scalar.length, 'strict')
- plain_implicit = False
- if self.parsed_event.data.scalar.plain_implicit == 1:
- plain_implicit = True
- quoted_implicit = False
- if self.parsed_event.data.scalar.quoted_implicit == 1:
- quoted_implicit = True
- if self.parsed_event.data.scalar.tag == NULL \
- or (self.parsed_event.data.scalar.tag[0] == c'!'
- and self.parsed_event.data.scalar.tag[1] == c'\0'):
- tag = self.resolve(ScalarNode, value, (plain_implicit, quoted_implicit))
- else:
- tag = PyUnicode_FromString(self.parsed_event.data.scalar.tag)
- style = None
- if self.parsed_event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
- style = u''
- elif self.parsed_event.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
- style = u'\''
- elif self.parsed_event.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
- style = u'"'
- elif self.parsed_event.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
- style = u'|'
- elif self.parsed_event.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
- style = u'>'
- node = ScalarNode(tag, value, start_mark, end_mark, style)
- if anchor is not None:
- self.anchors[anchor] = node
- yaml_event_delete(&self.parsed_event)
- return node
-
- cdef _compose_sequence_node(self, object anchor):
- cdef int index
- start_mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- implicit = False
- if self.parsed_event.data.sequence_start.implicit == 1:
- implicit = True
- if self.parsed_event.data.sequence_start.tag == NULL \
- or (self.parsed_event.data.sequence_start.tag[0] == c'!'
- and self.parsed_event.data.sequence_start.tag[1] == c'\0'):
- tag = self.resolve(SequenceNode, None, implicit)
- else:
- tag = PyUnicode_FromString(self.parsed_event.data.sequence_start.tag)
- flow_style = None
- if self.parsed_event.data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE:
- flow_style = True
- elif self.parsed_event.data.sequence_start.style == YAML_BLOCK_SEQUENCE_STYLE:
- flow_style = False
- value = []
- node = SequenceNode(tag, value, start_mark, None, flow_style)
- if anchor is not None:
- self.anchors[anchor] = node
- yaml_event_delete(&self.parsed_event)
- index = 0
- self._parse_next_event()
- while self.parsed_event.type != YAML_SEQUENCE_END_EVENT:
- value.append(self._compose_node(node, index))
- index = index+1
- self._parse_next_event()
- node.end_mark = Mark(self.stream_name,
- self.parsed_event.end_mark.index,
- self.parsed_event.end_mark.line,
- self.parsed_event.end_mark.column,
- None, None)
- yaml_event_delete(&self.parsed_event)
- return node
-
- cdef _compose_mapping_node(self, object anchor):
- start_mark = Mark(self.stream_name,
- self.parsed_event.start_mark.index,
- self.parsed_event.start_mark.line,
- self.parsed_event.start_mark.column,
- None, None)
- implicit = False
- if self.parsed_event.data.mapping_start.implicit == 1:
- implicit = True
- if self.parsed_event.data.mapping_start.tag == NULL \
- or (self.parsed_event.data.mapping_start.tag[0] == c'!'
- and self.parsed_event.data.mapping_start.tag[1] == c'\0'):
- tag = self.resolve(MappingNode, None, implicit)
- else:
- tag = PyUnicode_FromString(self.parsed_event.data.mapping_start.tag)
- flow_style = None
- if self.parsed_event.data.mapping_start.style == YAML_FLOW_MAPPING_STYLE:
- flow_style = True
- elif self.parsed_event.data.mapping_start.style == YAML_BLOCK_MAPPING_STYLE:
- flow_style = False
- value = []
- node = MappingNode(tag, value, start_mark, None, flow_style)
- if anchor is not None:
- self.anchors[anchor] = node
- yaml_event_delete(&self.parsed_event)
- self._parse_next_event()
- while self.parsed_event.type != YAML_MAPPING_END_EVENT:
- item_key = self._compose_node(node, None)
- item_value = self._compose_node(node, item_key)
- value.append((item_key, item_value))
- self._parse_next_event()
- node.end_mark = Mark(self.stream_name,
- self.parsed_event.end_mark.index,
- self.parsed_event.end_mark.line,
- self.parsed_event.end_mark.column,
- None, None)
- yaml_event_delete(&self.parsed_event)
- return node
-
- cdef int _parse_next_event(self) except 0:
- if self.parsed_event.type == YAML_NO_EVENT:
- if yaml_parser_parse(&self.parser, &self.parsed_event) == 0:
- error = self._parser_error()
- raise error
- return 1
-
+ self.parsed_event.data.scalar.length, 'strict')
+ plain_implicit = False
+ if self.parsed_event.data.scalar.plain_implicit == 1:
+ plain_implicit = True
+ quoted_implicit = False
+ if self.parsed_event.data.scalar.quoted_implicit == 1:
+ quoted_implicit = True
+ if self.parsed_event.data.scalar.tag == NULL \
+ or (self.parsed_event.data.scalar.tag[0] == c'!'
+ and self.parsed_event.data.scalar.tag[1] == c'\0'):
+ tag = self.resolve(ScalarNode, value, (plain_implicit, quoted_implicit))
+ else:
+ tag = PyUnicode_FromString(self.parsed_event.data.scalar.tag)
+ style = None
+ if self.parsed_event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE:
+ style = u''
+ elif self.parsed_event.data.scalar.style == YAML_SINGLE_QUOTED_SCALAR_STYLE:
+ style = u'\''
+ elif self.parsed_event.data.scalar.style == YAML_DOUBLE_QUOTED_SCALAR_STYLE:
+ style = u'"'
+ elif self.parsed_event.data.scalar.style == YAML_LITERAL_SCALAR_STYLE:
+ style = u'|'
+ elif self.parsed_event.data.scalar.style == YAML_FOLDED_SCALAR_STYLE:
+ style = u'>'
+ node = ScalarNode(tag, value, start_mark, end_mark, style)
+ if anchor is not None:
+ self.anchors[anchor] = node
+ yaml_event_delete(&self.parsed_event)
+ return node
+
+ cdef _compose_sequence_node(self, object anchor):
+ cdef int index
+ start_mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ implicit = False
+ if self.parsed_event.data.sequence_start.implicit == 1:
+ implicit = True
+ if self.parsed_event.data.sequence_start.tag == NULL \
+ or (self.parsed_event.data.sequence_start.tag[0] == c'!'
+ and self.parsed_event.data.sequence_start.tag[1] == c'\0'):
+ tag = self.resolve(SequenceNode, None, implicit)
+ else:
+ tag = PyUnicode_FromString(self.parsed_event.data.sequence_start.tag)
+ flow_style = None
+ if self.parsed_event.data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE:
+ flow_style = True
+ elif self.parsed_event.data.sequence_start.style == YAML_BLOCK_SEQUENCE_STYLE:
+ flow_style = False
+ value = []
+ node = SequenceNode(tag, value, start_mark, None, flow_style)
+ if anchor is not None:
+ self.anchors[anchor] = node
+ yaml_event_delete(&self.parsed_event)
+ index = 0
+ self._parse_next_event()
+ while self.parsed_event.type != YAML_SEQUENCE_END_EVENT:
+ value.append(self._compose_node(node, index))
+ index = index+1
+ self._parse_next_event()
+ node.end_mark = Mark(self.stream_name,
+ self.parsed_event.end_mark.index,
+ self.parsed_event.end_mark.line,
+ self.parsed_event.end_mark.column,
+ None, None)
+ yaml_event_delete(&self.parsed_event)
+ return node
+
+ cdef _compose_mapping_node(self, object anchor):
+ start_mark = Mark(self.stream_name,
+ self.parsed_event.start_mark.index,
+ self.parsed_event.start_mark.line,
+ self.parsed_event.start_mark.column,
+ None, None)
+ implicit = False
+ if self.parsed_event.data.mapping_start.implicit == 1:
+ implicit = True
+ if self.parsed_event.data.mapping_start.tag == NULL \
+ or (self.parsed_event.data.mapping_start.tag[0] == c'!'
+ and self.parsed_event.data.mapping_start.tag[1] == c'\0'):
+ tag = self.resolve(MappingNode, None, implicit)
+ else:
+ tag = PyUnicode_FromString(self.parsed_event.data.mapping_start.tag)
+ flow_style = None
+ if self.parsed_event.data.mapping_start.style == YAML_FLOW_MAPPING_STYLE:
+ flow_style = True
+ elif self.parsed_event.data.mapping_start.style == YAML_BLOCK_MAPPING_STYLE:
+ flow_style = False
+ value = []
+ node = MappingNode(tag, value, start_mark, None, flow_style)
+ if anchor is not None:
+ self.anchors[anchor] = node
+ yaml_event_delete(&self.parsed_event)
+ self._parse_next_event()
+ while self.parsed_event.type != YAML_MAPPING_END_EVENT:
+ item_key = self._compose_node(node, None)
+ item_value = self._compose_node(node, item_key)
+ value.append((item_key, item_value))
+ self._parse_next_event()
+ node.end_mark = Mark(self.stream_name,
+ self.parsed_event.end_mark.index,
+ self.parsed_event.end_mark.line,
+ self.parsed_event.end_mark.column,
+ None, None)
+ yaml_event_delete(&self.parsed_event)
+ return node
+
+ cdef int _parse_next_event(self) except 0:
+ if self.parsed_event.type == YAML_NO_EVENT:
+ if yaml_parser_parse(&self.parser, &self.parsed_event) == 0:
+ error = self._parser_error()
+ raise error
+ return 1
+
cdef int input_handler(void *data, char *buffer, size_t size, size_t *read) except 0:
- cdef CParser parser
- parser = <CParser>data
- if parser.stream_cache is None:
- value = parser.stream.read(size)
- if PyUnicode_CheckExact(value) != 0:
- value = PyUnicode_AsUTF8String(value)
- parser.unicode_source = 1
- if PyString_CheckExact(value) == 0:
- if PY_MAJOR_VERSION < 3:
- raise TypeError("a string value is expected")
- else:
- raise TypeError(u"a string value is expected")
- parser.stream_cache = value
- parser.stream_cache_pos = 0
- parser.stream_cache_len = PyString_GET_SIZE(value)
- if (parser.stream_cache_len - parser.stream_cache_pos) < size:
- size = parser.stream_cache_len - parser.stream_cache_pos
- if size > 0:
+ cdef CParser parser
+ parser = <CParser>data
+ if parser.stream_cache is None:
+ value = parser.stream.read(size)
+ if PyUnicode_CheckExact(value) != 0:
+ value = PyUnicode_AsUTF8String(value)
+ parser.unicode_source = 1
+ if PyString_CheckExact(value) == 0:
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("a string value is expected")
+ else:
+ raise TypeError(u"a string value is expected")
+ parser.stream_cache = value
+ parser.stream_cache_pos = 0
+ parser.stream_cache_len = PyString_GET_SIZE(value)
+ if (parser.stream_cache_len - parser.stream_cache_pos) < size:
+ size = parser.stream_cache_len - parser.stream_cache_pos
+ if size > 0:
memcpy(buffer, PyString_AS_STRING(parser.stream_cache)
- + parser.stream_cache_pos, size)
- read[0] = size
- parser.stream_cache_pos += size
- if parser.stream_cache_pos == parser.stream_cache_len:
- parser.stream_cache = None
- return 1
-
-cdef class CEmitter:
-
- cdef yaml_emitter_t emitter
-
- cdef object stream
-
- cdef int document_start_implicit
- cdef int document_end_implicit
- cdef object use_version
- cdef object use_tags
-
- cdef object serialized_nodes
- cdef object anchors
- cdef int last_alias_id
- cdef int closed
- cdef int dump_unicode
- cdef object use_encoding
-
- def __init__(self, stream, canonical=None, indent=None, width=None,
- allow_unicode=None, line_break=None, encoding=None,
- explicit_start=None, explicit_end=None, version=None, tags=None):
- if yaml_emitter_initialize(&self.emitter) == 0:
- raise MemoryError
- self.stream = stream
- self.dump_unicode = 0
- if PY_MAJOR_VERSION < 3:
- if getattr3(stream, 'encoding', None):
- self.dump_unicode = 1
- else:
- if hasattr(stream, u'encoding'):
- self.dump_unicode = 1
- self.use_encoding = encoding
+ + parser.stream_cache_pos, size)
+ read[0] = size
+ parser.stream_cache_pos += size
+ if parser.stream_cache_pos == parser.stream_cache_len:
+ parser.stream_cache = None
+ return 1
+
+cdef class CEmitter:
+
+ cdef yaml_emitter_t emitter
+
+ cdef object stream
+
+ cdef int document_start_implicit
+ cdef int document_end_implicit
+ cdef object use_version
+ cdef object use_tags
+
+ cdef object serialized_nodes
+ cdef object anchors
+ cdef int last_alias_id
+ cdef int closed
+ cdef int dump_unicode
+ cdef object use_encoding
+
+ def __init__(self, stream, canonical=None, indent=None, width=None,
+ allow_unicode=None, line_break=None, encoding=None,
+ explicit_start=None, explicit_end=None, version=None, tags=None):
+ if yaml_emitter_initialize(&self.emitter) == 0:
+ raise MemoryError
+ self.stream = stream
+ self.dump_unicode = 0
+ if PY_MAJOR_VERSION < 3:
+ if getattr3(stream, 'encoding', None):
+ self.dump_unicode = 1
+ else:
+ if hasattr(stream, u'encoding'):
+ self.dump_unicode = 1
+ self.use_encoding = encoding
yaml_emitter_set_output(&self.emitter, output_handler, <void *>self)
- if canonical:
- yaml_emitter_set_canonical(&self.emitter, 1)
- if indent is not None:
- yaml_emitter_set_indent(&self.emitter, indent)
- if width is not None:
- yaml_emitter_set_width(&self.emitter, width)
- if allow_unicode:
- yaml_emitter_set_unicode(&self.emitter, 1)
- if line_break is not None:
- if line_break == '\r':
- yaml_emitter_set_break(&self.emitter, YAML_CR_BREAK)
- elif line_break == '\n':
- yaml_emitter_set_break(&self.emitter, YAML_LN_BREAK)
- elif line_break == '\r\n':
- yaml_emitter_set_break(&self.emitter, YAML_CRLN_BREAK)
- self.document_start_implicit = 1
- if explicit_start:
- self.document_start_implicit = 0
- self.document_end_implicit = 1
- if explicit_end:
- self.document_end_implicit = 0
- self.use_version = version
- self.use_tags = tags
- self.serialized_nodes = {}
- self.anchors = {}
- self.last_alias_id = 0
- self.closed = -1
-
- def __dealloc__(self):
- yaml_emitter_delete(&self.emitter)
-
- def dispose(self):
- pass
-
- cdef object _emitter_error(self):
- if self.emitter.error == YAML_MEMORY_ERROR:
- return MemoryError
- elif self.emitter.error == YAML_EMITTER_ERROR:
- if PY_MAJOR_VERSION < 3:
- problem = self.emitter.problem
- else:
- problem = PyUnicode_FromString(self.emitter.problem)
- return EmitterError(problem)
- if PY_MAJOR_VERSION < 3:
- raise ValueError("no emitter error")
- else:
- raise ValueError(u"no emitter error")
-
- cdef int _object_to_event(self, object event_object, yaml_event_t *event) except 0:
- cdef yaml_encoding_t encoding
- cdef yaml_version_directive_t version_directive_value
- cdef yaml_version_directive_t *version_directive
- cdef yaml_tag_directive_t tag_directives_value[128]
- cdef yaml_tag_directive_t *tag_directives_start
- cdef yaml_tag_directive_t *tag_directives_end
- cdef int implicit
- cdef int plain_implicit
- cdef int quoted_implicit
- cdef char *anchor
- cdef char *tag
- cdef char *value
- cdef int length
- cdef yaml_scalar_style_t scalar_style
- cdef yaml_sequence_style_t sequence_style
- cdef yaml_mapping_style_t mapping_style
- event_class = event_object.__class__
- if event_class is StreamStartEvent:
- encoding = YAML_UTF8_ENCODING
- if event_object.encoding == u'utf-16-le' or event_object.encoding == 'utf-16-le':
- encoding = YAML_UTF16LE_ENCODING
- elif event_object.encoding == u'utf-16-be' or event_object.encoding == 'utf-16-be':
- encoding = YAML_UTF16BE_ENCODING
- if event_object.encoding is None:
- self.dump_unicode = 1
- if self.dump_unicode == 1:
- encoding = YAML_UTF8_ENCODING
- yaml_stream_start_event_initialize(event, encoding)
- elif event_class is StreamEndEvent:
- yaml_stream_end_event_initialize(event)
- elif event_class is DocumentStartEvent:
- version_directive = NULL
- if event_object.version:
- version_directive_value.major = event_object.version[0]
- version_directive_value.minor = event_object.version[1]
- version_directive = &version_directive_value
- tag_directives_start = NULL
- tag_directives_end = NULL
- if event_object.tags:
- if len(event_object.tags) > 128:
- if PY_MAJOR_VERSION < 3:
- raise ValueError("too many tags")
- else:
- raise ValueError(u"too many tags")
- tag_directives_start = tag_directives_value
- tag_directives_end = tag_directives_value
- cache = []
- for handle in event_object.tags:
- prefix = event_object.tags[handle]
- if PyUnicode_CheckExact(handle):
- handle = PyUnicode_AsUTF8String(handle)
- cache.append(handle)
- if not PyString_CheckExact(handle):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag handle must be a string")
- else:
- raise TypeError(u"tag handle must be a string")
+ if canonical:
+ yaml_emitter_set_canonical(&self.emitter, 1)
+ if indent is not None:
+ yaml_emitter_set_indent(&self.emitter, indent)
+ if width is not None:
+ yaml_emitter_set_width(&self.emitter, width)
+ if allow_unicode:
+ yaml_emitter_set_unicode(&self.emitter, 1)
+ if line_break is not None:
+ if line_break == '\r':
+ yaml_emitter_set_break(&self.emitter, YAML_CR_BREAK)
+ elif line_break == '\n':
+ yaml_emitter_set_break(&self.emitter, YAML_LN_BREAK)
+ elif line_break == '\r\n':
+ yaml_emitter_set_break(&self.emitter, YAML_CRLN_BREAK)
+ self.document_start_implicit = 1
+ if explicit_start:
+ self.document_start_implicit = 0
+ self.document_end_implicit = 1
+ if explicit_end:
+ self.document_end_implicit = 0
+ self.use_version = version
+ self.use_tags = tags
+ self.serialized_nodes = {}
+ self.anchors = {}
+ self.last_alias_id = 0
+ self.closed = -1
+
+ def __dealloc__(self):
+ yaml_emitter_delete(&self.emitter)
+
+ def dispose(self):
+ pass
+
+ cdef object _emitter_error(self):
+ if self.emitter.error == YAML_MEMORY_ERROR:
+ return MemoryError
+ elif self.emitter.error == YAML_EMITTER_ERROR:
+ if PY_MAJOR_VERSION < 3:
+ problem = self.emitter.problem
+ else:
+ problem = PyUnicode_FromString(self.emitter.problem)
+ return EmitterError(problem)
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("no emitter error")
+ else:
+ raise ValueError(u"no emitter error")
+
+ cdef int _object_to_event(self, object event_object, yaml_event_t *event) except 0:
+ cdef yaml_encoding_t encoding
+ cdef yaml_version_directive_t version_directive_value
+ cdef yaml_version_directive_t *version_directive
+ cdef yaml_tag_directive_t tag_directives_value[128]
+ cdef yaml_tag_directive_t *tag_directives_start
+ cdef yaml_tag_directive_t *tag_directives_end
+ cdef int implicit
+ cdef int plain_implicit
+ cdef int quoted_implicit
+ cdef char *anchor
+ cdef char *tag
+ cdef char *value
+ cdef int length
+ cdef yaml_scalar_style_t scalar_style
+ cdef yaml_sequence_style_t sequence_style
+ cdef yaml_mapping_style_t mapping_style
+ event_class = event_object.__class__
+ if event_class is StreamStartEvent:
+ encoding = YAML_UTF8_ENCODING
+ if event_object.encoding == u'utf-16-le' or event_object.encoding == 'utf-16-le':
+ encoding = YAML_UTF16LE_ENCODING
+ elif event_object.encoding == u'utf-16-be' or event_object.encoding == 'utf-16-be':
+ encoding = YAML_UTF16BE_ENCODING
+ if event_object.encoding is None:
+ self.dump_unicode = 1
+ if self.dump_unicode == 1:
+ encoding = YAML_UTF8_ENCODING
+ yaml_stream_start_event_initialize(event, encoding)
+ elif event_class is StreamEndEvent:
+ yaml_stream_end_event_initialize(event)
+ elif event_class is DocumentStartEvent:
+ version_directive = NULL
+ if event_object.version:
+ version_directive_value.major = event_object.version[0]
+ version_directive_value.minor = event_object.version[1]
+ version_directive = &version_directive_value
+ tag_directives_start = NULL
+ tag_directives_end = NULL
+ if event_object.tags:
+ if len(event_object.tags) > 128:
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("too many tags")
+ else:
+ raise ValueError(u"too many tags")
+ tag_directives_start = tag_directives_value
+ tag_directives_end = tag_directives_value
+ cache = []
+ for handle in event_object.tags:
+ prefix = event_object.tags[handle]
+ if PyUnicode_CheckExact(handle):
+ handle = PyUnicode_AsUTF8String(handle)
+ cache.append(handle)
+ if not PyString_CheckExact(handle):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag handle must be a string")
+ else:
+ raise TypeError(u"tag handle must be a string")
tag_directives_end.handle = PyString_AS_STRING(handle)
- if PyUnicode_CheckExact(prefix):
- prefix = PyUnicode_AsUTF8String(prefix)
- cache.append(prefix)
- if not PyString_CheckExact(prefix):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag prefix must be a string")
- else:
- raise TypeError(u"tag prefix must be a string")
+ if PyUnicode_CheckExact(prefix):
+ prefix = PyUnicode_AsUTF8String(prefix)
+ cache.append(prefix)
+ if not PyString_CheckExact(prefix):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag prefix must be a string")
+ else:
+ raise TypeError(u"tag prefix must be a string")
tag_directives_end.prefix = PyString_AS_STRING(prefix)
- tag_directives_end = tag_directives_end+1
- implicit = 1
- if event_object.explicit:
- implicit = 0
- if yaml_document_start_event_initialize(event, version_directive,
- tag_directives_start, tag_directives_end, implicit) == 0:
- raise MemoryError
- elif event_class is DocumentEndEvent:
- implicit = 1
- if event_object.explicit:
- implicit = 0
- yaml_document_end_event_initialize(event, implicit)
- elif event_class is AliasEvent:
- anchor = NULL
- anchor_object = event_object.anchor
- if PyUnicode_CheckExact(anchor_object):
- anchor_object = PyUnicode_AsUTF8String(anchor_object)
- if not PyString_CheckExact(anchor_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("anchor must be a string")
- else:
- raise TypeError(u"anchor must be a string")
- anchor = PyString_AS_STRING(anchor_object)
+ tag_directives_end = tag_directives_end+1
+ implicit = 1
+ if event_object.explicit:
+ implicit = 0
+ if yaml_document_start_event_initialize(event, version_directive,
+ tag_directives_start, tag_directives_end, implicit) == 0:
+ raise MemoryError
+ elif event_class is DocumentEndEvent:
+ implicit = 1
+ if event_object.explicit:
+ implicit = 0
+ yaml_document_end_event_initialize(event, implicit)
+ elif event_class is AliasEvent:
+ anchor = NULL
+ anchor_object = event_object.anchor
+ if PyUnicode_CheckExact(anchor_object):
+ anchor_object = PyUnicode_AsUTF8String(anchor_object)
+ if not PyString_CheckExact(anchor_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("anchor must be a string")
+ else:
+ raise TypeError(u"anchor must be a string")
+ anchor = PyString_AS_STRING(anchor_object)
if yaml_alias_event_initialize(event, anchor) == 0:
- raise MemoryError
- elif event_class is ScalarEvent:
- anchor = NULL
- anchor_object = event_object.anchor
- if anchor_object is not None:
- if PyUnicode_CheckExact(anchor_object):
- anchor_object = PyUnicode_AsUTF8String(anchor_object)
- if not PyString_CheckExact(anchor_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("anchor must be a string")
- else:
- raise TypeError(u"anchor must be a string")
- anchor = PyString_AS_STRING(anchor_object)
- tag = NULL
- tag_object = event_object.tag
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- value_object = event_object.value
- if PyUnicode_CheckExact(value_object):
- value_object = PyUnicode_AsUTF8String(value_object)
- if not PyString_CheckExact(value_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("value must be a string")
- else:
- raise TypeError(u"value must be a string")
- value = PyString_AS_STRING(value_object)
- length = PyString_GET_SIZE(value_object)
- plain_implicit = 0
- quoted_implicit = 0
- if event_object.implicit is not None:
- plain_implicit = event_object.implicit[0]
- quoted_implicit = event_object.implicit[1]
- style_object = event_object.style
- scalar_style = YAML_PLAIN_SCALAR_STYLE
- if style_object == "'" or style_object == u"'":
- scalar_style = YAML_SINGLE_QUOTED_SCALAR_STYLE
- elif style_object == "\"" or style_object == u"\"":
- scalar_style = YAML_DOUBLE_QUOTED_SCALAR_STYLE
- elif style_object == "|" or style_object == u"|":
- scalar_style = YAML_LITERAL_SCALAR_STYLE
- elif style_object == ">" or style_object == u">":
- scalar_style = YAML_FOLDED_SCALAR_STYLE
+ raise MemoryError
+ elif event_class is ScalarEvent:
+ anchor = NULL
+ anchor_object = event_object.anchor
+ if anchor_object is not None:
+ if PyUnicode_CheckExact(anchor_object):
+ anchor_object = PyUnicode_AsUTF8String(anchor_object)
+ if not PyString_CheckExact(anchor_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("anchor must be a string")
+ else:
+ raise TypeError(u"anchor must be a string")
+ anchor = PyString_AS_STRING(anchor_object)
+ tag = NULL
+ tag_object = event_object.tag
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ value_object = event_object.value
+ if PyUnicode_CheckExact(value_object):
+ value_object = PyUnicode_AsUTF8String(value_object)
+ if not PyString_CheckExact(value_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("value must be a string")
+ else:
+ raise TypeError(u"value must be a string")
+ value = PyString_AS_STRING(value_object)
+ length = PyString_GET_SIZE(value_object)
+ plain_implicit = 0
+ quoted_implicit = 0
+ if event_object.implicit is not None:
+ plain_implicit = event_object.implicit[0]
+ quoted_implicit = event_object.implicit[1]
+ style_object = event_object.style
+ scalar_style = YAML_PLAIN_SCALAR_STYLE
+ if style_object == "'" or style_object == u"'":
+ scalar_style = YAML_SINGLE_QUOTED_SCALAR_STYLE
+ elif style_object == "\"" or style_object == u"\"":
+ scalar_style = YAML_DOUBLE_QUOTED_SCALAR_STYLE
+ elif style_object == "|" or style_object == u"|":
+ scalar_style = YAML_LITERAL_SCALAR_STYLE
+ elif style_object == ">" or style_object == u">":
+ scalar_style = YAML_FOLDED_SCALAR_STYLE
if yaml_scalar_event_initialize(event, anchor, tag, value, length,
- plain_implicit, quoted_implicit, scalar_style) == 0:
- raise MemoryError
- elif event_class is SequenceStartEvent:
- anchor = NULL
- anchor_object = event_object.anchor
- if anchor_object is not None:
- if PyUnicode_CheckExact(anchor_object):
- anchor_object = PyUnicode_AsUTF8String(anchor_object)
- if not PyString_CheckExact(anchor_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("anchor must be a string")
- else:
- raise TypeError(u"anchor must be a string")
- anchor = PyString_AS_STRING(anchor_object)
- tag = NULL
- tag_object = event_object.tag
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- implicit = 0
- if event_object.implicit:
- implicit = 1
- sequence_style = YAML_BLOCK_SEQUENCE_STYLE
- if event_object.flow_style:
- sequence_style = YAML_FLOW_SEQUENCE_STYLE
+ plain_implicit, quoted_implicit, scalar_style) == 0:
+ raise MemoryError
+ elif event_class is SequenceStartEvent:
+ anchor = NULL
+ anchor_object = event_object.anchor
+ if anchor_object is not None:
+ if PyUnicode_CheckExact(anchor_object):
+ anchor_object = PyUnicode_AsUTF8String(anchor_object)
+ if not PyString_CheckExact(anchor_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("anchor must be a string")
+ else:
+ raise TypeError(u"anchor must be a string")
+ anchor = PyString_AS_STRING(anchor_object)
+ tag = NULL
+ tag_object = event_object.tag
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ implicit = 0
+ if event_object.implicit:
+ implicit = 1
+ sequence_style = YAML_BLOCK_SEQUENCE_STYLE
+ if event_object.flow_style:
+ sequence_style = YAML_FLOW_SEQUENCE_STYLE
if yaml_sequence_start_event_initialize(event, anchor, tag,
- implicit, sequence_style) == 0:
- raise MemoryError
- elif event_class is MappingStartEvent:
- anchor = NULL
- anchor_object = event_object.anchor
- if anchor_object is not None:
- if PyUnicode_CheckExact(anchor_object):
- anchor_object = PyUnicode_AsUTF8String(anchor_object)
- if not PyString_CheckExact(anchor_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("anchor must be a string")
- else:
- raise TypeError(u"anchor must be a string")
- anchor = PyString_AS_STRING(anchor_object)
- tag = NULL
- tag_object = event_object.tag
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- implicit = 0
- if event_object.implicit:
- implicit = 1
- mapping_style = YAML_BLOCK_MAPPING_STYLE
- if event_object.flow_style:
- mapping_style = YAML_FLOW_MAPPING_STYLE
+ implicit, sequence_style) == 0:
+ raise MemoryError
+ elif event_class is MappingStartEvent:
+ anchor = NULL
+ anchor_object = event_object.anchor
+ if anchor_object is not None:
+ if PyUnicode_CheckExact(anchor_object):
+ anchor_object = PyUnicode_AsUTF8String(anchor_object)
+ if not PyString_CheckExact(anchor_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("anchor must be a string")
+ else:
+ raise TypeError(u"anchor must be a string")
+ anchor = PyString_AS_STRING(anchor_object)
+ tag = NULL
+ tag_object = event_object.tag
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ implicit = 0
+ if event_object.implicit:
+ implicit = 1
+ mapping_style = YAML_BLOCK_MAPPING_STYLE
+ if event_object.flow_style:
+ mapping_style = YAML_FLOW_MAPPING_STYLE
if yaml_mapping_start_event_initialize(event, anchor, tag,
- implicit, mapping_style) == 0:
- raise MemoryError
- elif event_class is SequenceEndEvent:
- yaml_sequence_end_event_initialize(event)
- elif event_class is MappingEndEvent:
- yaml_mapping_end_event_initialize(event)
- else:
- if PY_MAJOR_VERSION < 3:
- raise TypeError("invalid event %s" % event_object)
- else:
- raise TypeError(u"invalid event %s" % event_object)
- return 1
-
- def emit(self, event_object):
- cdef yaml_event_t event
- self._object_to_event(event_object, &event)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
-
- def open(self):
- cdef yaml_event_t event
- cdef yaml_encoding_t encoding
- if self.closed == -1:
- if self.use_encoding == u'utf-16-le' or self.use_encoding == 'utf-16-le':
- encoding = YAML_UTF16LE_ENCODING
- elif self.use_encoding == u'utf-16-be' or self.use_encoding == 'utf-16-be':
- encoding = YAML_UTF16BE_ENCODING
- else:
- encoding = YAML_UTF8_ENCODING
- if self.use_encoding is None:
- self.dump_unicode = 1
- if self.dump_unicode == 1:
- encoding = YAML_UTF8_ENCODING
- yaml_stream_start_event_initialize(&event, encoding)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- self.closed = 0
- elif self.closed == 1:
- if PY_MAJOR_VERSION < 3:
- raise SerializerError("serializer is closed")
- else:
- raise SerializerError(u"serializer is closed")
- else:
- if PY_MAJOR_VERSION < 3:
- raise SerializerError("serializer is already opened")
- else:
- raise SerializerError(u"serializer is already opened")
-
- def close(self):
- cdef yaml_event_t event
- if self.closed == -1:
- if PY_MAJOR_VERSION < 3:
- raise SerializerError("serializer is not opened")
- else:
- raise SerializerError(u"serializer is not opened")
- elif self.closed == 0:
- yaml_stream_end_event_initialize(&event)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- self.closed = 1
-
- def serialize(self, node):
- cdef yaml_event_t event
- cdef yaml_version_directive_t version_directive_value
- cdef yaml_version_directive_t *version_directive
- cdef yaml_tag_directive_t tag_directives_value[128]
- cdef yaml_tag_directive_t *tag_directives_start
- cdef yaml_tag_directive_t *tag_directives_end
- if self.closed == -1:
- if PY_MAJOR_VERSION < 3:
- raise SerializerError("serializer is not opened")
- else:
- raise SerializerError(u"serializer is not opened")
- elif self.closed == 1:
- if PY_MAJOR_VERSION < 3:
- raise SerializerError("serializer is closed")
- else:
- raise SerializerError(u"serializer is closed")
- cache = []
- version_directive = NULL
- if self.use_version:
- version_directive_value.major = self.use_version[0]
- version_directive_value.minor = self.use_version[1]
- version_directive = &version_directive_value
- tag_directives_start = NULL
- tag_directives_end = NULL
- if self.use_tags:
- if len(self.use_tags) > 128:
- if PY_MAJOR_VERSION < 3:
- raise ValueError("too many tags")
- else:
- raise ValueError(u"too many tags")
- tag_directives_start = tag_directives_value
- tag_directives_end = tag_directives_value
- for handle in self.use_tags:
- prefix = self.use_tags[handle]
- if PyUnicode_CheckExact(handle):
- handle = PyUnicode_AsUTF8String(handle)
- cache.append(handle)
- if not PyString_CheckExact(handle):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag handle must be a string")
- else:
- raise TypeError(u"tag handle must be a string")
+ implicit, mapping_style) == 0:
+ raise MemoryError
+ elif event_class is SequenceEndEvent:
+ yaml_sequence_end_event_initialize(event)
+ elif event_class is MappingEndEvent:
+ yaml_mapping_end_event_initialize(event)
+ else:
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("invalid event %s" % event_object)
+ else:
+ raise TypeError(u"invalid event %s" % event_object)
+ return 1
+
+ def emit(self, event_object):
+ cdef yaml_event_t event
+ self._object_to_event(event_object, &event)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+
+ def open(self):
+ cdef yaml_event_t event
+ cdef yaml_encoding_t encoding
+ if self.closed == -1:
+ if self.use_encoding == u'utf-16-le' or self.use_encoding == 'utf-16-le':
+ encoding = YAML_UTF16LE_ENCODING
+ elif self.use_encoding == u'utf-16-be' or self.use_encoding == 'utf-16-be':
+ encoding = YAML_UTF16BE_ENCODING
+ else:
+ encoding = YAML_UTF8_ENCODING
+ if self.use_encoding is None:
+ self.dump_unicode = 1
+ if self.dump_unicode == 1:
+ encoding = YAML_UTF8_ENCODING
+ yaml_stream_start_event_initialize(&event, encoding)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ self.closed = 0
+ elif self.closed == 1:
+ if PY_MAJOR_VERSION < 3:
+ raise SerializerError("serializer is closed")
+ else:
+ raise SerializerError(u"serializer is closed")
+ else:
+ if PY_MAJOR_VERSION < 3:
+ raise SerializerError("serializer is already opened")
+ else:
+ raise SerializerError(u"serializer is already opened")
+
+ def close(self):
+ cdef yaml_event_t event
+ if self.closed == -1:
+ if PY_MAJOR_VERSION < 3:
+ raise SerializerError("serializer is not opened")
+ else:
+ raise SerializerError(u"serializer is not opened")
+ elif self.closed == 0:
+ yaml_stream_end_event_initialize(&event)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ self.closed = 1
+
+ def serialize(self, node):
+ cdef yaml_event_t event
+ cdef yaml_version_directive_t version_directive_value
+ cdef yaml_version_directive_t *version_directive
+ cdef yaml_tag_directive_t tag_directives_value[128]
+ cdef yaml_tag_directive_t *tag_directives_start
+ cdef yaml_tag_directive_t *tag_directives_end
+ if self.closed == -1:
+ if PY_MAJOR_VERSION < 3:
+ raise SerializerError("serializer is not opened")
+ else:
+ raise SerializerError(u"serializer is not opened")
+ elif self.closed == 1:
+ if PY_MAJOR_VERSION < 3:
+ raise SerializerError("serializer is closed")
+ else:
+ raise SerializerError(u"serializer is closed")
+ cache = []
+ version_directive = NULL
+ if self.use_version:
+ version_directive_value.major = self.use_version[0]
+ version_directive_value.minor = self.use_version[1]
+ version_directive = &version_directive_value
+ tag_directives_start = NULL
+ tag_directives_end = NULL
+ if self.use_tags:
+ if len(self.use_tags) > 128:
+ if PY_MAJOR_VERSION < 3:
+ raise ValueError("too many tags")
+ else:
+ raise ValueError(u"too many tags")
+ tag_directives_start = tag_directives_value
+ tag_directives_end = tag_directives_value
+ for handle in self.use_tags:
+ prefix = self.use_tags[handle]
+ if PyUnicode_CheckExact(handle):
+ handle = PyUnicode_AsUTF8String(handle)
+ cache.append(handle)
+ if not PyString_CheckExact(handle):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag handle must be a string")
+ else:
+ raise TypeError(u"tag handle must be a string")
tag_directives_end.handle = PyString_AS_STRING(handle)
- if PyUnicode_CheckExact(prefix):
- prefix = PyUnicode_AsUTF8String(prefix)
- cache.append(prefix)
- if not PyString_CheckExact(prefix):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag prefix must be a string")
- else:
- raise TypeError(u"tag prefix must be a string")
+ if PyUnicode_CheckExact(prefix):
+ prefix = PyUnicode_AsUTF8String(prefix)
+ cache.append(prefix)
+ if not PyString_CheckExact(prefix):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag prefix must be a string")
+ else:
+ raise TypeError(u"tag prefix must be a string")
tag_directives_end.prefix = PyString_AS_STRING(prefix)
- tag_directives_end = tag_directives_end+1
- if yaml_document_start_event_initialize(&event, version_directive,
- tag_directives_start, tag_directives_end,
- self.document_start_implicit) == 0:
- raise MemoryError
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- self._anchor_node(node)
- self._serialize_node(node, None, None)
- yaml_document_end_event_initialize(&event, self.document_end_implicit)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- self.serialized_nodes = {}
- self.anchors = {}
- self.last_alias_id = 0
-
- cdef int _anchor_node(self, object node) except 0:
- if node in self.anchors:
- if self.anchors[node] is None:
- self.last_alias_id = self.last_alias_id+1
- self.anchors[node] = u"id%03d" % self.last_alias_id
- else:
- self.anchors[node] = None
- node_class = node.__class__
- if node_class is SequenceNode:
- for item in node.value:
- self._anchor_node(item)
- elif node_class is MappingNode:
- for key, value in node.value:
- self._anchor_node(key)
- self._anchor_node(value)
- return 1
-
- cdef int _serialize_node(self, object node, object parent, object index) except 0:
- cdef yaml_event_t event
- cdef int implicit
- cdef int plain_implicit
- cdef int quoted_implicit
- cdef char *anchor
- cdef char *tag
- cdef char *value
- cdef int length
- cdef int item_index
- cdef yaml_scalar_style_t scalar_style
- cdef yaml_sequence_style_t sequence_style
- cdef yaml_mapping_style_t mapping_style
- anchor_object = self.anchors[node]
- anchor = NULL
- if anchor_object is not None:
- if PyUnicode_CheckExact(anchor_object):
- anchor_object = PyUnicode_AsUTF8String(anchor_object)
- if not PyString_CheckExact(anchor_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("anchor must be a string")
- else:
- raise TypeError(u"anchor must be a string")
- anchor = PyString_AS_STRING(anchor_object)
- if node in self.serialized_nodes:
+ tag_directives_end = tag_directives_end+1
+ if yaml_document_start_event_initialize(&event, version_directive,
+ tag_directives_start, tag_directives_end,
+ self.document_start_implicit) == 0:
+ raise MemoryError
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ self._anchor_node(node)
+ self._serialize_node(node, None, None)
+ yaml_document_end_event_initialize(&event, self.document_end_implicit)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ self.serialized_nodes = {}
+ self.anchors = {}
+ self.last_alias_id = 0
+
+ cdef int _anchor_node(self, object node) except 0:
+ if node in self.anchors:
+ if self.anchors[node] is None:
+ self.last_alias_id = self.last_alias_id+1
+ self.anchors[node] = u"id%03d" % self.last_alias_id
+ else:
+ self.anchors[node] = None
+ node_class = node.__class__
+ if node_class is SequenceNode:
+ for item in node.value:
+ self._anchor_node(item)
+ elif node_class is MappingNode:
+ for key, value in node.value:
+ self._anchor_node(key)
+ self._anchor_node(value)
+ return 1
+
+ cdef int _serialize_node(self, object node, object parent, object index) except 0:
+ cdef yaml_event_t event
+ cdef int implicit
+ cdef int plain_implicit
+ cdef int quoted_implicit
+ cdef char *anchor
+ cdef char *tag
+ cdef char *value
+ cdef int length
+ cdef int item_index
+ cdef yaml_scalar_style_t scalar_style
+ cdef yaml_sequence_style_t sequence_style
+ cdef yaml_mapping_style_t mapping_style
+ anchor_object = self.anchors[node]
+ anchor = NULL
+ if anchor_object is not None:
+ if PyUnicode_CheckExact(anchor_object):
+ anchor_object = PyUnicode_AsUTF8String(anchor_object)
+ if not PyString_CheckExact(anchor_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("anchor must be a string")
+ else:
+ raise TypeError(u"anchor must be a string")
+ anchor = PyString_AS_STRING(anchor_object)
+ if node in self.serialized_nodes:
if yaml_alias_event_initialize(&event, anchor) == 0:
- raise MemoryError
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- else:
- node_class = node.__class__
- self.serialized_nodes[node] = True
- self.descend_resolver(parent, index)
- if node_class is ScalarNode:
- plain_implicit = 0
- quoted_implicit = 0
- tag_object = node.tag
- if self.resolve(ScalarNode, node.value, (True, False)) == tag_object:
- plain_implicit = 1
- if self.resolve(ScalarNode, node.value, (False, True)) == tag_object:
- quoted_implicit = 1
- tag = NULL
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- value_object = node.value
- if PyUnicode_CheckExact(value_object):
- value_object = PyUnicode_AsUTF8String(value_object)
- if not PyString_CheckExact(value_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("value must be a string")
- else:
- raise TypeError(u"value must be a string")
- value = PyString_AS_STRING(value_object)
- length = PyString_GET_SIZE(value_object)
- style_object = node.style
- scalar_style = YAML_PLAIN_SCALAR_STYLE
- if style_object == "'" or style_object == u"'":
- scalar_style = YAML_SINGLE_QUOTED_SCALAR_STYLE
- elif style_object == "\"" or style_object == u"\"":
- scalar_style = YAML_DOUBLE_QUOTED_SCALAR_STYLE
- elif style_object == "|" or style_object == u"|":
- scalar_style = YAML_LITERAL_SCALAR_STYLE
- elif style_object == ">" or style_object == u">":
- scalar_style = YAML_FOLDED_SCALAR_STYLE
+ raise MemoryError
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ else:
+ node_class = node.__class__
+ self.serialized_nodes[node] = True
+ self.descend_resolver(parent, index)
+ if node_class is ScalarNode:
+ plain_implicit = 0
+ quoted_implicit = 0
+ tag_object = node.tag
+ if self.resolve(ScalarNode, node.value, (True, False)) == tag_object:
+ plain_implicit = 1
+ if self.resolve(ScalarNode, node.value, (False, True)) == tag_object:
+ quoted_implicit = 1
+ tag = NULL
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ value_object = node.value
+ if PyUnicode_CheckExact(value_object):
+ value_object = PyUnicode_AsUTF8String(value_object)
+ if not PyString_CheckExact(value_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("value must be a string")
+ else:
+ raise TypeError(u"value must be a string")
+ value = PyString_AS_STRING(value_object)
+ length = PyString_GET_SIZE(value_object)
+ style_object = node.style
+ scalar_style = YAML_PLAIN_SCALAR_STYLE
+ if style_object == "'" or style_object == u"'":
+ scalar_style = YAML_SINGLE_QUOTED_SCALAR_STYLE
+ elif style_object == "\"" or style_object == u"\"":
+ scalar_style = YAML_DOUBLE_QUOTED_SCALAR_STYLE
+ elif style_object == "|" or style_object == u"|":
+ scalar_style = YAML_LITERAL_SCALAR_STYLE
+ elif style_object == ">" or style_object == u">":
+ scalar_style = YAML_FOLDED_SCALAR_STYLE
if yaml_scalar_event_initialize(&event, anchor, tag, value, length,
- plain_implicit, quoted_implicit, scalar_style) == 0:
- raise MemoryError
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- elif node_class is SequenceNode:
- implicit = 0
- tag_object = node.tag
- if self.resolve(SequenceNode, node.value, True) == tag_object:
- implicit = 1
- tag = NULL
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- sequence_style = YAML_BLOCK_SEQUENCE_STYLE
- if node.flow_style:
- sequence_style = YAML_FLOW_SEQUENCE_STYLE
+ plain_implicit, quoted_implicit, scalar_style) == 0:
+ raise MemoryError
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ elif node_class is SequenceNode:
+ implicit = 0
+ tag_object = node.tag
+ if self.resolve(SequenceNode, node.value, True) == tag_object:
+ implicit = 1
+ tag = NULL
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ sequence_style = YAML_BLOCK_SEQUENCE_STYLE
+ if node.flow_style:
+ sequence_style = YAML_FLOW_SEQUENCE_STYLE
if yaml_sequence_start_event_initialize(&event, anchor, tag,
- implicit, sequence_style) == 0:
- raise MemoryError
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- item_index = 0
- for item in node.value:
- self._serialize_node(item, node, item_index)
- item_index = item_index+1
- yaml_sequence_end_event_initialize(&event)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- elif node_class is MappingNode:
- implicit = 0
- tag_object = node.tag
- if self.resolve(MappingNode, node.value, True) == tag_object:
- implicit = 1
- tag = NULL
- if tag_object is not None:
- if PyUnicode_CheckExact(tag_object):
- tag_object = PyUnicode_AsUTF8String(tag_object)
- if not PyString_CheckExact(tag_object):
- if PY_MAJOR_VERSION < 3:
- raise TypeError("tag must be a string")
- else:
- raise TypeError(u"tag must be a string")
- tag = PyString_AS_STRING(tag_object)
- mapping_style = YAML_BLOCK_MAPPING_STYLE
- if node.flow_style:
- mapping_style = YAML_FLOW_MAPPING_STYLE
+ implicit, sequence_style) == 0:
+ raise MemoryError
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ item_index = 0
+ for item in node.value:
+ self._serialize_node(item, node, item_index)
+ item_index = item_index+1
+ yaml_sequence_end_event_initialize(&event)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ elif node_class is MappingNode:
+ implicit = 0
+ tag_object = node.tag
+ if self.resolve(MappingNode, node.value, True) == tag_object:
+ implicit = 1
+ tag = NULL
+ if tag_object is not None:
+ if PyUnicode_CheckExact(tag_object):
+ tag_object = PyUnicode_AsUTF8String(tag_object)
+ if not PyString_CheckExact(tag_object):
+ if PY_MAJOR_VERSION < 3:
+ raise TypeError("tag must be a string")
+ else:
+ raise TypeError(u"tag must be a string")
+ tag = PyString_AS_STRING(tag_object)
+ mapping_style = YAML_BLOCK_MAPPING_STYLE
+ if node.flow_style:
+ mapping_style = YAML_FLOW_MAPPING_STYLE
if yaml_mapping_start_event_initialize(&event, anchor, tag,
- implicit, mapping_style) == 0:
- raise MemoryError
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- for item_key, item_value in node.value:
- self._serialize_node(item_key, node, None)
- self._serialize_node(item_value, node, item_key)
- yaml_mapping_end_event_initialize(&event)
- if yaml_emitter_emit(&self.emitter, &event) == 0:
- error = self._emitter_error()
- raise error
- self.ascend_resolver()
- return 1
-
+ implicit, mapping_style) == 0:
+ raise MemoryError
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ for item_key, item_value in node.value:
+ self._serialize_node(item_key, node, None)
+ self._serialize_node(item_value, node, item_key)
+ yaml_mapping_end_event_initialize(&event)
+ if yaml_emitter_emit(&self.emitter, &event) == 0:
+ error = self._emitter_error()
+ raise error
+ self.ascend_resolver()
+ return 1
+
cdef int output_handler(void *data, char *buffer, size_t size) except 0:
- cdef CEmitter emitter
- emitter = <CEmitter>data
- if emitter.dump_unicode == 0:
+ cdef CEmitter emitter
+ emitter = <CEmitter>data
+ if emitter.dump_unicode == 0:
value = PyString_FromStringAndSize(buffer, size)
- else:
+ else:
value = PyUnicode_DecodeUTF8(buffer, size, 'strict')
- emitter.stream.write(value)
- return 1
-
+ emitter.stream.write(value)
+ return 1
+
diff --git a/contrib/python/PyYAML/ya.make b/contrib/python/PyYAML/ya.make
index ae05873a52..a604fce51f 100644
--- a/contrib/python/PyYAML/ya.make
+++ b/contrib/python/PyYAML/ya.make
@@ -1,5 +1,5 @@
PY23_LIBRARY()
-
+
LICENSE(MIT)
OWNER(g:python-contrib)
@@ -13,7 +13,7 @@ ELSE()
contrib/python/PyYAML/py3
)
ENDIF()
-
+
NO_LINT()
END()
diff --git a/contrib/python/cffi/ya.make b/contrib/python/cffi/ya.make
index 2c9e58e0b4..7bff9477f9 100644
--- a/contrib/python/cffi/ya.make
+++ b/contrib/python/cffi/ya.make
@@ -7,12 +7,12 @@ OWNER(g:python-contrib)
VERSION(1.15.0)
PEERDIR(
- contrib/restricted/libffi
+ contrib/restricted/libffi
contrib/python/pycparser
)
ADDINCL(
- contrib/restricted/libffi/include
+ contrib/restricted/libffi/include
)
NO_COMPILER_WARNINGS()
diff --git a/contrib/python/decorator/LICENSE.txt b/contrib/python/decorator/LICENSE.txt
index 9d8e5641c5..b0ade0487e 100644
--- a/contrib/python/decorator/LICENSE.txt
+++ b/contrib/python/decorator/LICENSE.txt
@@ -1,26 +1,26 @@
Copyright (c) 2005-2018, Michele Simionato
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- Redistributions in bytecode form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the
- distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
-OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
-TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
-USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGE.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ Redistributions in bytecode form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGE.
diff --git a/contrib/python/decorator/decorator.py b/contrib/python/decorator/decorator.py
index 5f595c7014..b1f8b567e9 100644
--- a/contrib/python/decorator/decorator.py
+++ b/contrib/python/decorator/decorator.py
@@ -1,64 +1,64 @@
-# ######################### LICENSE ############################ #
-
+# ######################### LICENSE ############################ #
+
# Copyright (c) 2005-2018, Michele Simionato
-# All rights reserved.
-
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-
-# Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# Redistributions in bytecode form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in
-# the documentation and/or other materials provided with the
-# distribution.
-
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
-# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
-# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
-# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
-# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
-# DAMAGE.
-
-"""
-Decorator module, see http://pypi.python.org/pypi/decorator
-for the documentation.
-"""
-from __future__ import print_function
-
-import re
-import sys
-import inspect
-import operator
-import itertools
-import collections
-
+# All rights reserved.
+
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+
+# Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# Redistributions in bytecode form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+# DAMAGE.
+
+"""
+Decorator module, see http://pypi.python.org/pypi/decorator
+for the documentation.
+"""
+from __future__ import print_function
+
+import re
+import sys
+import inspect
+import operator
+import itertools
+import collections
+
__version__ = '4.4.2'
-
+
if sys.version_info >= (3,):
- from inspect import getfullargspec
-
- def get_init(cls):
- return cls.__init__
-else:
+ from inspect import getfullargspec
+
+ def get_init(cls):
+ return cls.__init__
+else:
FullArgSpec = collections.namedtuple(
'FullArgSpec', 'args varargs varkw defaults '
'kwonlyargs kwonlydefaults annotations')
def getfullargspec(f):
- "A quick and dirty replacement for getfullargspec for Python 2.X"
+ "A quick and dirty replacement for getfullargspec for Python 2.X"
return FullArgSpec._make(inspect.getargspec(f) + ([], None, {}))
-
- def get_init(cls):
- return cls.__init__.__func__
-
+
+ def get_init(cls):
+ return cls.__init__.__func__
+
try:
iscoroutinefunction = inspect.iscoroutinefunction
except AttributeError:
@@ -71,43 +71,43 @@ except ImportError:
# assume no generator function in old Python versions
def isgeneratorfunction(caller):
return False
-
-
+
+
DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
-
-
-# basic functionality
-class FunctionMaker(object):
- """
- An object with the ability to create functions with a given signature.
- It has attributes name, doc, module, signature, defaults, dict and
- methods update and make.
- """
-
- # Atomic get-and-increment provided by the GIL
- _compile_count = itertools.count()
-
+
+
+# basic functionality
+class FunctionMaker(object):
+ """
+ An object with the ability to create functions with a given signature.
+ It has attributes name, doc, module, signature, defaults, dict and
+ methods update and make.
+ """
+
+ # Atomic get-and-increment provided by the GIL
+ _compile_count = itertools.count()
+
# make pylint happy
args = varargs = varkw = defaults = kwonlyargs = kwonlydefaults = ()
- def __init__(self, func=None, name=None, signature=None,
- defaults=None, doc=None, module=None, funcdict=None):
- self.shortsignature = signature
- if func:
- # func can be a class or a callable, but not an instance method
- self.name = func.__name__
- if self.name == '<lambda>': # small hack for lambda functions
- self.name = '_lambda_'
- self.doc = func.__doc__
- self.module = func.__module__
- if inspect.isfunction(func):
- argspec = getfullargspec(func)
- self.annotations = getattr(func, '__annotations__', {})
- for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
- 'kwonlydefaults'):
- setattr(self, a, getattr(argspec, a))
- for i, arg in enumerate(self.args):
- setattr(self, 'arg%d' % i, arg)
+ def __init__(self, func=None, name=None, signature=None,
+ defaults=None, doc=None, module=None, funcdict=None):
+ self.shortsignature = signature
+ if func:
+ # func can be a class or a callable, but not an instance method
+ self.name = func.__name__
+ if self.name == '<lambda>': # small hack for lambda functions
+ self.name = '_lambda_'
+ self.doc = func.__doc__
+ self.module = func.__module__
+ if inspect.isfunction(func):
+ argspec = getfullargspec(func)
+ self.annotations = getattr(func, '__annotations__', {})
+ for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
+ 'kwonlydefaults'):
+ setattr(self, a, getattr(argspec, a))
+ for i, arg in enumerate(self.args):
+ setattr(self, 'arg%d' % i, arg)
allargs = list(self.args)
allshortargs = list(self.args)
if self.varargs:
@@ -123,95 +123,95 @@ class FunctionMaker(object):
allshortargs.append('**' + self.varkw)
self.signature = ', '.join(allargs)
self.shortsignature = ', '.join(allshortargs)
- self.dict = func.__dict__.copy()
- # func=None happens when decorating a caller
- if name:
- self.name = name
- if signature is not None:
- self.signature = signature
- if defaults:
- self.defaults = defaults
- if doc:
- self.doc = doc
- if module:
- self.module = module
- if funcdict:
- self.dict = funcdict
- # check existence required attributes
- assert hasattr(self, 'name')
- if not hasattr(self, 'signature'):
- raise TypeError('You are decorating a non function: %s' % func)
-
- def update(self, func, **kw):
- "Update the signature of func with the data in self"
- func.__name__ = self.name
- func.__doc__ = getattr(self, 'doc', None)
- func.__dict__ = getattr(self, 'dict', {})
+ self.dict = func.__dict__.copy()
+ # func=None happens when decorating a caller
+ if name:
+ self.name = name
+ if signature is not None:
+ self.signature = signature
+ if defaults:
+ self.defaults = defaults
+ if doc:
+ self.doc = doc
+ if module:
+ self.module = module
+ if funcdict:
+ self.dict = funcdict
+ # check existence required attributes
+ assert hasattr(self, 'name')
+ if not hasattr(self, 'signature'):
+ raise TypeError('You are decorating a non function: %s' % func)
+
+ def update(self, func, **kw):
+ "Update the signature of func with the data in self"
+ func.__name__ = self.name
+ func.__doc__ = getattr(self, 'doc', None)
+ func.__dict__ = getattr(self, 'dict', {})
func.__defaults__ = self.defaults
func.__kwdefaults__ = self.kwonlydefaults or None
- func.__annotations__ = getattr(self, 'annotations', None)
- try:
- frame = sys._getframe(3)
- except AttributeError: # for IronPython and similar implementations
- callermodule = '?'
- else:
- callermodule = frame.f_globals.get('__name__', '?')
- func.__module__ = getattr(self, 'module', callermodule)
- func.__dict__.update(kw)
-
- def make(self, src_templ, evaldict=None, addsource=False, **attrs):
- "Make a new function from a given template and update the signature"
- src = src_templ % vars(self) # expand name and signature
- evaldict = evaldict or {}
+ func.__annotations__ = getattr(self, 'annotations', None)
+ try:
+ frame = sys._getframe(3)
+ except AttributeError: # for IronPython and similar implementations
+ callermodule = '?'
+ else:
+ callermodule = frame.f_globals.get('__name__', '?')
+ func.__module__ = getattr(self, 'module', callermodule)
+ func.__dict__.update(kw)
+
+ def make(self, src_templ, evaldict=None, addsource=False, **attrs):
+ "Make a new function from a given template and update the signature"
+ src = src_templ % vars(self) # expand name and signature
+ evaldict = evaldict or {}
mo = DEF.search(src)
- if mo is None:
- raise SyntaxError('not a valid function template\n%s' % src)
- name = mo.group(1) # extract the function name
- names = set([name] + [arg.strip(' *') for arg in
- self.shortsignature.split(',')])
- for n in names:
- if n in ('_func_', '_call_'):
- raise NameError('%s is overridden in\n%s' % (n, src))
-
+ if mo is None:
+ raise SyntaxError('not a valid function template\n%s' % src)
+ name = mo.group(1) # extract the function name
+ names = set([name] + [arg.strip(' *') for arg in
+ self.shortsignature.split(',')])
+ for n in names:
+ if n in ('_func_', '_call_'):
+ raise NameError('%s is overridden in\n%s' % (n, src))
+
if not src.endswith('\n'): # add a newline for old Pythons
src += '\n'
- # Ensure each generated function has a unique filename for profilers
- # (such as cProfile) that depend on the tuple of (<filename>,
- # <definition line>, <function name>) being unique.
+ # Ensure each generated function has a unique filename for profilers
+ # (such as cProfile) that depend on the tuple of (<filename>,
+ # <definition line>, <function name>) being unique.
filename = '<decorator-gen-%d>' % next(self._compile_count)
- try:
- code = compile(src, filename, 'single')
- exec(code, evaldict)
+ try:
+ code = compile(src, filename, 'single')
+ exec(code, evaldict)
except Exception:
- print('Error in generated code:', file=sys.stderr)
- print(src, file=sys.stderr)
- raise
- func = evaldict[name]
- if addsource:
- attrs['__source__'] = src
- self.update(func, **attrs)
- return func
-
- @classmethod
- def create(cls, obj, body, evaldict, defaults=None,
- doc=None, module=None, addsource=True, **attrs):
- """
- Create a function from the strings name, signature and body.
- evaldict is the evaluation dictionary. If addsource is true an
- attribute __source__ is added to the result. The attributes attrs
- are added, if any.
- """
- if isinstance(obj, str): # "name(signature)"
- name, rest = obj.strip().split('(', 1)
- signature = rest[:-1] # strip a right parens
- func = None
- else: # a function
- name = None
- signature = None
- func = obj
- self = cls(func, name, signature, defaults, doc, module)
- ibody = '\n'.join(' ' + line for line in body.splitlines())
+ print('Error in generated code:', file=sys.stderr)
+ print(src, file=sys.stderr)
+ raise
+ func = evaldict[name]
+ if addsource:
+ attrs['__source__'] = src
+ self.update(func, **attrs)
+ return func
+
+ @classmethod
+ def create(cls, obj, body, evaldict, defaults=None,
+ doc=None, module=None, addsource=True, **attrs):
+ """
+ Create a function from the strings name, signature and body.
+ evaldict is the evaluation dictionary. If addsource is true an
+ attribute __source__ is added to the result. The attributes attrs
+ are added, if any.
+ """
+ if isinstance(obj, str): # "name(signature)"
+ name, rest = obj.strip().split('(', 1)
+ signature = rest[:-1] # strip a right parens
+ func = None
+ else: # a function
+ name = None
+ signature = None
+ func = obj
+ self = cls(func, name, signature, defaults, doc, module)
+ ibody = '\n'.join(' ' + line for line in body.splitlines())
caller = evaldict.get('_call_') # when called from `decorate`
if caller and iscoroutinefunction(caller):
body = ('async def %(name)s(%(signature)s):\n' + ibody).replace(
@@ -219,15 +219,15 @@ class FunctionMaker(object):
else:
body = 'def %(name)s(%(signature)s):\n' + ibody
return self.make(body, evaldict, addsource, **attrs)
-
-
+
+
def decorate(func, caller, extras=()):
- """
- decorate(func, caller) decorates a function using a caller.
+ """
+ decorate(func, caller) decorates a function using a caller.
If the caller is a generator function, the resulting function
will be a generator function.
- """
- evaldict = dict(_call_=caller, _func_=func)
+ """
+ evaldict = dict(_call_=caller, _func_=func)
es = ''
for i, extra in enumerate(extras):
ex = '_e%d_' % i
@@ -250,37 +250,37 @@ def decorate(func, caller, extras=()):
fun = FunctionMaker.create(
func, "return _call_(_func_, %s%%(shortsignature)s)" % es,
evaldict, __wrapped__=func)
- if hasattr(func, '__qualname__'):
- fun.__qualname__ = func.__qualname__
- return fun
-
-
-def decorator(caller, _func=None):
- """decorator(caller) converts a caller function into a decorator"""
- if _func is not None: # return a decorated function
- # this is obsolete behavior; you should use decorate instead
- return decorate(_func, caller)
- # else return a decorator function
+ if hasattr(func, '__qualname__'):
+ fun.__qualname__ = func.__qualname__
+ return fun
+
+
+def decorator(caller, _func=None):
+ """decorator(caller) converts a caller function into a decorator"""
+ if _func is not None: # return a decorated function
+ # this is obsolete behavior; you should use decorate instead
+ return decorate(_func, caller)
+ # else return a decorator function
defaultargs, defaults = '', ()
- if inspect.isclass(caller):
- name = caller.__name__.lower()
- doc = 'decorator(%s) converts functions/generators into ' \
- 'factories of %s objects' % (caller.__name__, caller.__name__)
- elif inspect.isfunction(caller):
- if caller.__name__ == '<lambda>':
- name = '_lambda_'
- else:
- name = caller.__name__
- doc = caller.__doc__
+ if inspect.isclass(caller):
+ name = caller.__name__.lower()
+ doc = 'decorator(%s) converts functions/generators into ' \
+ 'factories of %s objects' % (caller.__name__, caller.__name__)
+ elif inspect.isfunction(caller):
+ if caller.__name__ == '<lambda>':
+ name = '_lambda_'
+ else:
+ name = caller.__name__
+ doc = caller.__doc__
nargs = caller.__code__.co_argcount
ndefs = len(caller.__defaults__ or ())
defaultargs = ', '.join(caller.__code__.co_varnames[nargs-ndefs:nargs])
if defaultargs:
defaultargs += ','
defaults = caller.__defaults__
- else: # assume caller is an object with a __call__ method
- name = caller.__class__.__name__.lower()
- doc = caller.__call__.__doc__
+ else: # assume caller is an object with a __call__ method
+ name = caller.__class__.__name__.lower()
+ doc = caller.__call__.__doc__
evaldict = dict(_call=caller, _decorate_=decorate)
dec = FunctionMaker.create(
'%s(func, %s)' % (name, defaultargs),
@@ -290,165 +290,165 @@ def decorator(caller, _func=None):
if defaults:
dec.__defaults__ = (None,) + defaults
return dec
-
-
-# ####################### contextmanager ####################### #
-
-try: # Python >= 3.2
- from contextlib import _GeneratorContextManager
-except ImportError: # Python >= 2.5
- from contextlib import GeneratorContextManager as _GeneratorContextManager
-
-
-class ContextManager(_GeneratorContextManager):
- def __call__(self, func):
- """Context manager decorator"""
- return FunctionMaker.create(
- func, "with _self_: return _func_(%(shortsignature)s)",
- dict(_self_=self, _func_=func), __wrapped__=func)
-
-
-init = getfullargspec(_GeneratorContextManager.__init__)
-n_args = len(init.args)
-if n_args == 2 and not init.varargs: # (self, genobj) Python 2.7
- def __init__(self, g, *a, **k):
- return _GeneratorContextManager.__init__(self, g(*a, **k))
- ContextManager.__init__ = __init__
-elif n_args == 2 and init.varargs: # (self, gen, *a, **k) Python 3.4
- pass
-elif n_args == 4: # (self, gen, args, kwds) Python 3.5
- def __init__(self, g, *a, **k):
- return _GeneratorContextManager.__init__(self, g, a, k)
- ContextManager.__init__ = __init__
-
+
+
+# ####################### contextmanager ####################### #
+
+try: # Python >= 3.2
+ from contextlib import _GeneratorContextManager
+except ImportError: # Python >= 2.5
+ from contextlib import GeneratorContextManager as _GeneratorContextManager
+
+
+class ContextManager(_GeneratorContextManager):
+ def __call__(self, func):
+ """Context manager decorator"""
+ return FunctionMaker.create(
+ func, "with _self_: return _func_(%(shortsignature)s)",
+ dict(_self_=self, _func_=func), __wrapped__=func)
+
+
+init = getfullargspec(_GeneratorContextManager.__init__)
+n_args = len(init.args)
+if n_args == 2 and not init.varargs: # (self, genobj) Python 2.7
+ def __init__(self, g, *a, **k):
+ return _GeneratorContextManager.__init__(self, g(*a, **k))
+ ContextManager.__init__ = __init__
+elif n_args == 2 and init.varargs: # (self, gen, *a, **k) Python 3.4
+ pass
+elif n_args == 4: # (self, gen, args, kwds) Python 3.5
+ def __init__(self, g, *a, **k):
+ return _GeneratorContextManager.__init__(self, g, a, k)
+ ContextManager.__init__ = __init__
+
_contextmanager = decorator(ContextManager)
-
-
+
+
def contextmanager(func):
# Enable Pylint config: contextmanager-decorators=decorator.contextmanager
return _contextmanager(func)
-# ############################ dispatch_on ############################ #
-
-def append(a, vancestors):
- """
- Append ``a`` to the list of the virtual ancestors, unless it is already
- included.
- """
- add = True
- for j, va in enumerate(vancestors):
- if issubclass(va, a):
- add = False
- break
- if issubclass(a, va):
- vancestors[j] = a
- add = False
- if add:
- vancestors.append(a)
-
-
-# inspired from simplegeneric by P.J. Eby and functools.singledispatch
-def dispatch_on(*dispatch_args):
- """
- Factory of decorators turning a function into a generic function
- dispatching on the given arguments.
- """
- assert dispatch_args, 'No dispatch args passed'
- dispatch_str = '(%s,)' % ', '.join(dispatch_args)
-
- def check(arguments, wrong=operator.ne, msg=''):
- """Make sure one passes the expected number of arguments"""
- if wrong(len(arguments), len(dispatch_args)):
- raise TypeError('Expected %d arguments, got %d%s' %
- (len(dispatch_args), len(arguments), msg))
-
- def gen_func_dec(func):
- """Decorator turning a function into a generic function"""
-
- # first check the dispatch arguments
- argset = set(getfullargspec(func).args)
- if not set(dispatch_args) <= argset:
- raise NameError('Unknown dispatch arguments %s' % dispatch_str)
-
- typemap = {}
-
- def vancestors(*types):
- """
- Get a list of sets of virtual ancestors for the given types
- """
- check(types)
- ras = [[] for _ in range(len(dispatch_args))]
- for types_ in typemap:
- for t, type_, ra in zip(types, types_, ras):
+# ############################ dispatch_on ############################ #
+
+def append(a, vancestors):
+ """
+ Append ``a`` to the list of the virtual ancestors, unless it is already
+ included.
+ """
+ add = True
+ for j, va in enumerate(vancestors):
+ if issubclass(va, a):
+ add = False
+ break
+ if issubclass(a, va):
+ vancestors[j] = a
+ add = False
+ if add:
+ vancestors.append(a)
+
+
+# inspired from simplegeneric by P.J. Eby and functools.singledispatch
+def dispatch_on(*dispatch_args):
+ """
+ Factory of decorators turning a function into a generic function
+ dispatching on the given arguments.
+ """
+ assert dispatch_args, 'No dispatch args passed'
+ dispatch_str = '(%s,)' % ', '.join(dispatch_args)
+
+ def check(arguments, wrong=operator.ne, msg=''):
+ """Make sure one passes the expected number of arguments"""
+ if wrong(len(arguments), len(dispatch_args)):
+ raise TypeError('Expected %d arguments, got %d%s' %
+ (len(dispatch_args), len(arguments), msg))
+
+ def gen_func_dec(func):
+ """Decorator turning a function into a generic function"""
+
+ # first check the dispatch arguments
+ argset = set(getfullargspec(func).args)
+ if not set(dispatch_args) <= argset:
+ raise NameError('Unknown dispatch arguments %s' % dispatch_str)
+
+ typemap = {}
+
+ def vancestors(*types):
+ """
+ Get a list of sets of virtual ancestors for the given types
+ """
+ check(types)
+ ras = [[] for _ in range(len(dispatch_args))]
+ for types_ in typemap:
+ for t, type_, ra in zip(types, types_, ras):
if issubclass(t, type_) and type_ not in t.mro():
- append(type_, ra)
- return [set(ra) for ra in ras]
-
- def ancestors(*types):
- """
- Get a list of virtual MROs, one for each type
- """
- check(types)
- lists = []
- for t, vas in zip(types, vancestors(*types)):
- n_vas = len(vas)
- if n_vas > 1:
- raise RuntimeError(
- 'Ambiguous dispatch for %s: %s' % (t, vas))
- elif n_vas == 1:
- va, = vas
+ append(type_, ra)
+ return [set(ra) for ra in ras]
+
+ def ancestors(*types):
+ """
+ Get a list of virtual MROs, one for each type
+ """
+ check(types)
+ lists = []
+ for t, vas in zip(types, vancestors(*types)):
+ n_vas = len(vas)
+ if n_vas > 1:
+ raise RuntimeError(
+ 'Ambiguous dispatch for %s: %s' % (t, vas))
+ elif n_vas == 1:
+ va, = vas
mro = type('t', (t, va), {}).mro()[1:]
- else:
+ else:
mro = t.mro()
- lists.append(mro[:-1]) # discard t and object
- return lists
-
- def register(*types):
- """
- Decorator to register an implementation for the given types
- """
- check(types)
-
- def dec(f):
- check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
- typemap[types] = f
- return f
- return dec
-
- def dispatch_info(*types):
- """
- An utility to introspect the dispatch algorithm
- """
- check(types)
- lst = []
- for anc in itertools.product(*ancestors(*types)):
- lst.append(tuple(a.__name__ for a in anc))
- return lst
-
- def _dispatch(dispatch_args, *args, **kw):
- types = tuple(type(arg) for arg in dispatch_args)
- try: # fast path
- f = typemap[types]
- except KeyError:
- pass
- else:
- return f(*args, **kw)
- combinations = itertools.product(*ancestors(*types))
- next(combinations) # the first one has been already tried
- for types_ in combinations:
- f = typemap.get(types_)
- if f is not None:
- return f(*args, **kw)
-
- # else call the default implementation
- return func(*args, **kw)
-
- return FunctionMaker.create(
- func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str,
- dict(_f_=_dispatch), register=register, default=func,
- typemap=typemap, vancestors=vancestors, ancestors=ancestors,
- dispatch_info=dispatch_info, __wrapped__=func)
-
- gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
- return gen_func_dec
+ lists.append(mro[:-1]) # discard t and object
+ return lists
+
+ def register(*types):
+ """
+ Decorator to register an implementation for the given types
+ """
+ check(types)
+
+ def dec(f):
+ check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
+ typemap[types] = f
+ return f
+ return dec
+
+ def dispatch_info(*types):
+ """
+ An utility to introspect the dispatch algorithm
+ """
+ check(types)
+ lst = []
+ for anc in itertools.product(*ancestors(*types)):
+ lst.append(tuple(a.__name__ for a in anc))
+ return lst
+
+ def _dispatch(dispatch_args, *args, **kw):
+ types = tuple(type(arg) for arg in dispatch_args)
+ try: # fast path
+ f = typemap[types]
+ except KeyError:
+ pass
+ else:
+ return f(*args, **kw)
+ combinations = itertools.product(*ancestors(*types))
+ next(combinations) # the first one has been already tried
+ for types_ in combinations:
+ f = typemap.get(types_)
+ if f is not None:
+ return f(*args, **kw)
+
+ # else call the default implementation
+ return func(*args, **kw)
+
+ return FunctionMaker.create(
+ func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str,
+ dict(_f_=_dispatch), register=register, default=func,
+ typemap=typemap, vancestors=vancestors, ancestors=ancestors,
+ dispatch_info=dispatch_info, __wrapped__=func)
+
+ gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
+ return gen_func_dec
diff --git a/contrib/python/decorator/ya.make b/contrib/python/decorator/ya.make
index 6eccf23147..fbb7ebf626 100644
--- a/contrib/python/decorator/ya.make
+++ b/contrib/python/decorator/ya.make
@@ -3,23 +3,23 @@ PY23_LIBRARY()
LICENSE(BSD-3-Clause)
OWNER(g:python-contrib borman)
-
+
VERSION(4.4.2)
NO_LINT()
-PY_SRCS(
- TOP_LEVEL
- decorator.py
-)
-
+PY_SRCS(
+ TOP_LEVEL
+ decorator.py
+)
+
RESOURCE_FILES(
PREFIX contrib/python/decorator/
.dist-info/METADATA
.dist-info/top_level.txt
)
-END()
+END()
RECURSE_FOR_TESTS(
tests
diff --git a/contrib/python/ipython/py2/COPYING.rst b/contrib/python/ipython/py2/COPYING.rst
index 2a973f9dcb..59674acdc8 100644
--- a/contrib/python/ipython/py2/COPYING.rst
+++ b/contrib/python/ipython/py2/COPYING.rst
@@ -1,74 +1,74 @@
-=============================
- The IPython licensing terms
-=============================
-
-IPython is licensed under the terms of the Modified BSD License (also known as
-New or Revised or 3-Clause BSD), as follows:
-
-- Copyright (c) 2008-2014, IPython Development Team
-- Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
-- Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
-- Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
-
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-Redistributions of source code must retain the above copyright notice, this
-list of conditions and the following disclaimer.
-
-Redistributions in binary form must reproduce the above copyright notice, this
-list of conditions and the following disclaimer in the documentation and/or
-other materials provided with the distribution.
-
-Neither the name of the IPython Development Team nor the names of its
-contributors may be used to endorse or promote products derived from this
-software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-About the IPython Development Team
-----------------------------------
-
-Fernando Perez began IPython in 2001 based on code from Janko Hauser
-<jhauser@zscout.de> and Nathaniel Gray <n8gray@caltech.edu>. Fernando is still
-the project lead.
-
-The IPython Development Team is the set of all contributors to the IPython
-project. This includes all of the IPython subprojects. A full list with
-details is kept in the documentation directory, in the file
-``about/credits.txt``.
-
-The core team that coordinates development on GitHub can be found here:
-https://github.com/ipython/.
-
-Our Copyright Policy
---------------------
-
-IPython uses a shared copyright model. Each contributor maintains copyright
-over their contributions to IPython. But, it is important to note that these
-contributions are typically only changes to the repositories. Thus, the IPython
-source code, in its entirety is not the copyright of any single person or
-institution. Instead, it is the collective copyright of the entire IPython
-Development Team. If individual contributors want to maintain a record of what
-changes/contributions they have specific copyright on, they should indicate
-their copyright in the commit message of the change, when they commit the
-change to one of the IPython repositories.
-
-With this in mind, the following banner should be used in any source code file
-to indicate the copyright and license terms:
-
-::
-
- # Copyright (c) IPython Development Team.
- # Distributed under the terms of the Modified BSD License.
+=============================
+ The IPython licensing terms
+=============================
+
+IPython is licensed under the terms of the Modified BSD License (also known as
+New or Revised or 3-Clause BSD), as follows:
+
+- Copyright (c) 2008-2014, IPython Development Team
+- Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
+- Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
+- Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+
+Redistributions in binary form must reproduce the above copyright notice, this
+list of conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution.
+
+Neither the name of the IPython Development Team nor the names of its
+contributors may be used to endorse or promote products derived from this
+software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+About the IPython Development Team
+----------------------------------
+
+Fernando Perez began IPython in 2001 based on code from Janko Hauser
+<jhauser@zscout.de> and Nathaniel Gray <n8gray@caltech.edu>. Fernando is still
+the project lead.
+
+The IPython Development Team is the set of all contributors to the IPython
+project. This includes all of the IPython subprojects. A full list with
+details is kept in the documentation directory, in the file
+``about/credits.txt``.
+
+The core team that coordinates development on GitHub can be found here:
+https://github.com/ipython/.
+
+Our Copyright Policy
+--------------------
+
+IPython uses a shared copyright model. Each contributor maintains copyright
+over their contributions to IPython. But, it is important to note that these
+contributions are typically only changes to the repositories. Thus, the IPython
+source code, in its entirety is not the copyright of any single person or
+institution. Instead, it is the collective copyright of the entire IPython
+Development Team. If individual contributors want to maintain a record of what
+changes/contributions they have specific copyright on, they should indicate
+their copyright in the commit message of the change, when they commit the
+change to one of the IPython repositories.
+
+With this in mind, the following banner should be used in any source code file
+to indicate the copyright and license terms:
+
+::
+
+ # Copyright (c) IPython Development Team.
+ # Distributed under the terms of the Modified BSD License.
diff --git a/contrib/python/ipython/py2/IPython/__init__.py b/contrib/python/ipython/py2/IPython/__init__.py
index aa5121da24..9b450da6a0 100644
--- a/contrib/python/ipython/py2/IPython/__init__.py
+++ b/contrib/python/ipython/py2/IPython/__init__.py
@@ -1,146 +1,146 @@
-# encoding: utf-8
-"""
-IPython: tools for interactive and parallel computing in Python.
-
-http://ipython.org
-"""
-#-----------------------------------------------------------------------------
-# Copyright (c) 2008-2011, IPython Development Team.
-# Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
-# Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
-# Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-from __future__ import absolute_import
-
-import os
-import sys
-import warnings
-
-#-----------------------------------------------------------------------------
-# Setup everything
-#-----------------------------------------------------------------------------
-
-# Don't forget to also update setup.py when this changes!
-v = sys.version_info
-if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
- raise ImportError('IPython requires Python version 2.7 or 3.3 or above.')
-del v
-
-# Make it easy to import extensions - they are always directly on pythonpath.
-# Therefore, non-IPython modules can be added to extensions directory.
-# This should probably be in ipapp.py.
-sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
-
-#-----------------------------------------------------------------------------
-# Setup the top level names
-#-----------------------------------------------------------------------------
-
-from .core.getipython import get_ipython
-from .core import release
-from .core.application import Application
-from .terminal.embed import embed
-
-from .core.interactiveshell import InteractiveShell
-from .testing import test
-from .utils.sysinfo import sys_info
-from .utils.frame import extract_module_locals
-
-# Release data
-__author__ = '%s <%s>' % (release.author, release.author_email)
-__license__ = release.license
-__version__ = release.version
-version_info = release.version_info
-
-def embed_kernel(module=None, local_ns=None, **kwargs):
- """Embed and start an IPython kernel in a given scope.
-
- If you don't want the kernel to initialize the namespace
- from the scope of the surrounding function,
- and/or you want to load full IPython configuration,
- you probably want `IPython.start_kernel()` instead.
-
- Parameters
- ----------
- module : ModuleType, optional
- The module to load into IPython globals (default: caller)
- local_ns : dict, optional
- The namespace to load into IPython user namespace (default: caller)
-
- kwargs : various, optional
- Further keyword args are relayed to the IPKernelApp constructor,
- allowing configuration of the Kernel. Will only have an effect
- on the first embed_kernel call for a given process.
- """
-
- (caller_module, caller_locals) = extract_module_locals(1)
- if module is None:
- module = caller_module
- if local_ns is None:
- local_ns = caller_locals
-
- # Only import .zmq when we really need it
- from ipykernel.embed import embed_kernel as real_embed_kernel
- real_embed_kernel(module=module, local_ns=local_ns, **kwargs)
-
-def start_ipython(argv=None, **kwargs):
- """Launch a normal IPython instance (as opposed to embedded)
-
- `IPython.embed()` puts a shell in a particular calling scope,
- such as a function or method for debugging purposes,
- which is often not desirable.
-
- `start_ipython()` does full, regular IPython initialization,
- including loading startup files, configuration, etc.
- much of which is skipped by `embed()`.
-
- This is a public API method, and will survive implementation changes.
-
- Parameters
- ----------
-
- argv : list or None, optional
- If unspecified or None, IPython will parse command-line options from sys.argv.
- To prevent any command-line parsing, pass an empty list: `argv=[]`.
- user_ns : dict, optional
- specify this dictionary to initialize the IPython user namespace with particular values.
- kwargs : various, optional
- Any other kwargs will be passed to the Application constructor,
- such as `config`.
- """
- from IPython.terminal.ipapp import launch_new_instance
- return launch_new_instance(argv=argv, **kwargs)
-
-def start_kernel(argv=None, **kwargs):
- """Launch a normal IPython kernel instance (as opposed to embedded)
-
- `IPython.embed_kernel()` puts a shell in a particular calling scope,
- such as a function or method for debugging purposes,
- which is often not desirable.
-
- `start_kernel()` does full, regular IPython initialization,
- including loading startup files, configuration, etc.
- much of which is skipped by `embed()`.
-
- Parameters
- ----------
-
- argv : list or None, optional
- If unspecified or None, IPython will parse command-line options from sys.argv.
- To prevent any command-line parsing, pass an empty list: `argv=[]`.
- user_ns : dict, optional
- specify this dictionary to initialize the IPython user namespace with particular values.
- kwargs : various, optional
- Any other kwargs will be passed to the Application constructor,
- such as `config`.
- """
- from IPython.kernel.zmq.kernelapp import launch_new_instance
- return launch_new_instance(argv=argv, **kwargs)
-
+# encoding: utf-8
+"""
+IPython: tools for interactive and parallel computing in Python.
+
+http://ipython.org
+"""
+#-----------------------------------------------------------------------------
+# Copyright (c) 2008-2011, IPython Development Team.
+# Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
+# Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
+# Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+from __future__ import absolute_import
+
+import os
+import sys
+import warnings
+
+#-----------------------------------------------------------------------------
+# Setup everything
+#-----------------------------------------------------------------------------
+
+# Don't forget to also update setup.py when this changes!
+v = sys.version_info
+if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
+ raise ImportError('IPython requires Python version 2.7 or 3.3 or above.')
+del v
+
+# Make it easy to import extensions - they are always directly on pythonpath.
+# Therefore, non-IPython modules can be added to extensions directory.
+# This should probably be in ipapp.py.
+sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
+
+#-----------------------------------------------------------------------------
+# Setup the top level names
+#-----------------------------------------------------------------------------
+
+from .core.getipython import get_ipython
+from .core import release
+from .core.application import Application
+from .terminal.embed import embed
+
+from .core.interactiveshell import InteractiveShell
+from .testing import test
+from .utils.sysinfo import sys_info
+from .utils.frame import extract_module_locals
+
+# Release data
+__author__ = '%s <%s>' % (release.author, release.author_email)
+__license__ = release.license
+__version__ = release.version
+version_info = release.version_info
+
+def embed_kernel(module=None, local_ns=None, **kwargs):
+ """Embed and start an IPython kernel in a given scope.
+
+ If you don't want the kernel to initialize the namespace
+ from the scope of the surrounding function,
+ and/or you want to load full IPython configuration,
+ you probably want `IPython.start_kernel()` instead.
+
+ Parameters
+ ----------
+ module : ModuleType, optional
+ The module to load into IPython globals (default: caller)
+ local_ns : dict, optional
+ The namespace to load into IPython user namespace (default: caller)
+
+ kwargs : various, optional
+ Further keyword args are relayed to the IPKernelApp constructor,
+ allowing configuration of the Kernel. Will only have an effect
+ on the first embed_kernel call for a given process.
+ """
+
+ (caller_module, caller_locals) = extract_module_locals(1)
+ if module is None:
+ module = caller_module
+ if local_ns is None:
+ local_ns = caller_locals
+
+ # Only import .zmq when we really need it
+ from ipykernel.embed import embed_kernel as real_embed_kernel
+ real_embed_kernel(module=module, local_ns=local_ns, **kwargs)
+
+def start_ipython(argv=None, **kwargs):
+ """Launch a normal IPython instance (as opposed to embedded)
+
+ `IPython.embed()` puts a shell in a particular calling scope,
+ such as a function or method for debugging purposes,
+ which is often not desirable.
+
+ `start_ipython()` does full, regular IPython initialization,
+ including loading startup files, configuration, etc.
+ much of which is skipped by `embed()`.
+
+ This is a public API method, and will survive implementation changes.
+
+ Parameters
+ ----------
+
+ argv : list or None, optional
+ If unspecified or None, IPython will parse command-line options from sys.argv.
+ To prevent any command-line parsing, pass an empty list: `argv=[]`.
+ user_ns : dict, optional
+ specify this dictionary to initialize the IPython user namespace with particular values.
+ kwargs : various, optional
+ Any other kwargs will be passed to the Application constructor,
+ such as `config`.
+ """
+ from IPython.terminal.ipapp import launch_new_instance
+ return launch_new_instance(argv=argv, **kwargs)
+
+def start_kernel(argv=None, **kwargs):
+ """Launch a normal IPython kernel instance (as opposed to embedded)
+
+ `IPython.embed_kernel()` puts a shell in a particular calling scope,
+ such as a function or method for debugging purposes,
+ which is often not desirable.
+
+ `start_kernel()` does full, regular IPython initialization,
+ including loading startup files, configuration, etc.
+ much of which is skipped by `embed()`.
+
+ Parameters
+ ----------
+
+ argv : list or None, optional
+ If unspecified or None, IPython will parse command-line options from sys.argv.
+ To prevent any command-line parsing, pass an empty list: `argv=[]`.
+ user_ns : dict, optional
+ specify this dictionary to initialize the IPython user namespace with particular values.
+ kwargs : various, optional
+ Any other kwargs will be passed to the Application constructor,
+ such as `config`.
+ """
+ from IPython.kernel.zmq.kernelapp import launch_new_instance
+ return launch_new_instance(argv=argv, **kwargs)
+
diff --git a/contrib/python/ipython/py2/IPython/__main__.py b/contrib/python/ipython/py2/IPython/__main__.py
index 2e142249b5..d5123f33a2 100644
--- a/contrib/python/ipython/py2/IPython/__main__.py
+++ b/contrib/python/ipython/py2/IPython/__main__.py
@@ -1,14 +1,14 @@
-# encoding: utf-8
-"""Terminal-based IPython entry point.
-"""
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012, IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-from IPython import start_ipython
-
-start_ipython()
+# encoding: utf-8
+"""Terminal-based IPython entry point.
+"""
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012, IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+from IPython import start_ipython
+
+start_ipython()
diff --git a/contrib/python/ipython/py2/IPython/config.py b/contrib/python/ipython/py2/IPython/config.py
index ac8d0aa4bd..cf2bacafad 100644
--- a/contrib/python/ipython/py2/IPython/config.py
+++ b/contrib/python/ipython/py2/IPython/config.py
@@ -1,19 +1,19 @@
-"""
-Shim to maintain backwards compatibility with old IPython.config imports.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import sys
-from warnings import warn
-
-from IPython.utils.shimmodule import ShimModule, ShimWarning
-
+"""
+Shim to maintain backwards compatibility with old IPython.config imports.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import sys
+from warnings import warn
+
+from IPython.utils.shimmodule import ShimModule, ShimWarning
+
warn("The `IPython.config` package has been deprecated since IPython 4.0. "
- "You should import from traitlets.config instead.", ShimWarning)
-
-
-# Unconditionally insert the shim into sys.modules so that further import calls
-# trigger the custom attribute access above
-
-sys.modules['IPython.config'] = ShimModule(src='IPython.config', mirror='traitlets.config')
+ "You should import from traitlets.config instead.", ShimWarning)
+
+
+# Unconditionally insert the shim into sys.modules so that further import calls
+# trigger the custom attribute access above
+
+sys.modules['IPython.config'] = ShimModule(src='IPython.config', mirror='traitlets.config')
diff --git a/contrib/python/ipython/py2/IPython/consoleapp.py b/contrib/python/ipython/py2/IPython/consoleapp.py
index e2ffbbf664..14903bdc74 100644
--- a/contrib/python/ipython/py2/IPython/consoleapp.py
+++ b/contrib/python/ipython/py2/IPython/consoleapp.py
@@ -1,12 +1,12 @@
-"""
-Shim to maintain backwards compatibility with old IPython.consoleapp imports.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from warnings import warn
-
-warn("The `IPython.consoleapp` package has been deprecated. "
- "You should import from jupyter_client.consoleapp instead.")
-
-from jupyter_client.consoleapp import *
+"""
+Shim to maintain backwards compatibility with old IPython.consoleapp imports.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from warnings import warn
+
+warn("The `IPython.consoleapp` package has been deprecated. "
+ "You should import from jupyter_client.consoleapp instead.")
+
+from jupyter_client.consoleapp import *
diff --git a/contrib/python/ipython/py2/IPython/core/alias.py b/contrib/python/ipython/py2/IPython/core/alias.py
index 66ba986b40..28a9ccb00d 100644
--- a/contrib/python/ipython/py2/IPython/core/alias.py
+++ b/contrib/python/ipython/py2/IPython/core/alias.py
@@ -1,257 +1,257 @@
-# encoding: utf-8
-"""
-System command aliases.
-
-Authors:
-
-* Fernando Perez
-* Brian Granger
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import os
-import re
-import sys
-
-from traitlets.config.configurable import Configurable
-from IPython.core.error import UsageError
-
-from IPython.utils.py3compat import string_types
-from traitlets import List, Instance
+# encoding: utf-8
+"""
+System command aliases.
+
+Authors:
+
+* Fernando Perez
+* Brian Granger
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import os
+import re
+import sys
+
+from traitlets.config.configurable import Configurable
+from IPython.core.error import UsageError
+
+from IPython.utils.py3compat import string_types
+from traitlets import List, Instance
from logging import error
-
-#-----------------------------------------------------------------------------
-# Utilities
-#-----------------------------------------------------------------------------
-
-# This is used as the pattern for calls to split_user_input.
-shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
-
-def default_aliases():
- """Return list of shell aliases to auto-define.
- """
- # Note: the aliases defined here should be safe to use on a kernel
- # regardless of what frontend it is attached to. Frontends that use a
- # kernel in-process can define additional aliases that will only work in
- # their case. For example, things like 'less' or 'clear' that manipulate
- # the terminal should NOT be declared here, as they will only work if the
- # kernel is running inside a true terminal, and not over the network.
-
- if os.name == 'posix':
- default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
- ('mv', 'mv'), ('rm', 'rm'), ('cp', 'cp'),
- ('cat', 'cat'),
- ]
- # Useful set of ls aliases. The GNU and BSD options are a little
- # different, so we make aliases that provide as similar as possible
- # behavior in ipython, by passing the right flags for each platform
- if sys.platform.startswith('linux'):
- ls_aliases = [('ls', 'ls -F --color'),
- # long ls
- ('ll', 'ls -F -o --color'),
- # ls normal files only
- ('lf', 'ls -F -o --color %l | grep ^-'),
- # ls symbolic links
- ('lk', 'ls -F -o --color %l | grep ^l'),
- # directories or links to directories,
- ('ldir', 'ls -F -o --color %l | grep /$'),
- # things which are executable
- ('lx', 'ls -F -o --color %l | grep ^-..x'),
- ]
- elif sys.platform.startswith('openbsd') or sys.platform.startswith('netbsd'):
- # OpenBSD, NetBSD. The ls implementation on these platforms do not support
- # the -G switch and lack the ability to use colorized output.
- ls_aliases = [('ls', 'ls -F'),
- # long ls
- ('ll', 'ls -F -l'),
- # ls normal files only
- ('lf', 'ls -F -l %l | grep ^-'),
- # ls symbolic links
- ('lk', 'ls -F -l %l | grep ^l'),
- # directories or links to directories,
- ('ldir', 'ls -F -l %l | grep /$'),
- # things which are executable
- ('lx', 'ls -F -l %l | grep ^-..x'),
- ]
- else:
- # BSD, OSX, etc.
- ls_aliases = [('ls', 'ls -F -G'),
- # long ls
- ('ll', 'ls -F -l -G'),
- # ls normal files only
- ('lf', 'ls -F -l -G %l | grep ^-'),
- # ls symbolic links
- ('lk', 'ls -F -l -G %l | grep ^l'),
- # directories or links to directories,
- ('ldir', 'ls -F -G -l %l | grep /$'),
- # things which are executable
- ('lx', 'ls -F -l -G %l | grep ^-..x'),
- ]
- default_aliases = default_aliases + ls_aliases
- elif os.name in ['nt', 'dos']:
- default_aliases = [('ls', 'dir /on'),
- ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
- ('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
- ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
- ]
- else:
- default_aliases = []
-
- return default_aliases
-
-
-class AliasError(Exception):
- pass
-
-
-class InvalidAliasError(AliasError):
- pass
-
-class Alias(object):
- """Callable object storing the details of one alias.
-
- Instances are registered as magic functions to allow use of aliases.
- """
-
- # Prepare blacklist
- blacklist = {'cd','popd','pushd','dhist','alias','unalias'}
-
- def __init__(self, shell, name, cmd):
- self.shell = shell
- self.name = name
- self.cmd = cmd
- self.__doc__ = "Alias for `!{}`".format(cmd)
- self.nargs = self.validate()
-
- def validate(self):
- """Validate the alias, and return the number of arguments."""
- if self.name in self.blacklist:
- raise InvalidAliasError("The name %s can't be aliased "
- "because it is a keyword or builtin." % self.name)
- try:
- caller = self.shell.magics_manager.magics['line'][self.name]
- except KeyError:
- pass
- else:
- if not isinstance(caller, Alias):
- raise InvalidAliasError("The name %s can't be aliased "
- "because it is another magic command." % self.name)
-
- if not (isinstance(self.cmd, string_types)):
- raise InvalidAliasError("An alias command must be a string, "
- "got: %r" % self.cmd)
-
- nargs = self.cmd.count('%s') - self.cmd.count('%%s')
-
- if (nargs > 0) and (self.cmd.find('%l') >= 0):
- raise InvalidAliasError('The %s and %l specifiers are mutually '
- 'exclusive in alias definitions.')
-
- return nargs
-
- def __repr__(self):
- return "<alias {} for {!r}>".format(self.name, self.cmd)
-
- def __call__(self, rest=''):
- cmd = self.cmd
- nargs = self.nargs
- # Expand the %l special to be the user's input line
- if cmd.find('%l') >= 0:
- cmd = cmd.replace('%l', rest)
- rest = ''
-
- if nargs==0:
- if cmd.find('%%s') >= 1:
- cmd = cmd.replace('%%s', '%s')
- # Simple, argument-less aliases
- cmd = '%s %s' % (cmd, rest)
- else:
- # Handle aliases with positional arguments
- args = rest.split(None, nargs)
- if len(args) < nargs:
- raise UsageError('Alias <%s> requires %s arguments, %s given.' %
- (self.name, nargs, len(args)))
- cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
-
- self.shell.system(cmd)
-
-#-----------------------------------------------------------------------------
-# Main AliasManager class
-#-----------------------------------------------------------------------------
-
-class AliasManager(Configurable):
-
+
+#-----------------------------------------------------------------------------
+# Utilities
+#-----------------------------------------------------------------------------
+
+# This is used as the pattern for calls to split_user_input.
+shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
+
+def default_aliases():
+ """Return list of shell aliases to auto-define.
+ """
+ # Note: the aliases defined here should be safe to use on a kernel
+ # regardless of what frontend it is attached to. Frontends that use a
+ # kernel in-process can define additional aliases that will only work in
+ # their case. For example, things like 'less' or 'clear' that manipulate
+ # the terminal should NOT be declared here, as they will only work if the
+ # kernel is running inside a true terminal, and not over the network.
+
+ if os.name == 'posix':
+ default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
+ ('mv', 'mv'), ('rm', 'rm'), ('cp', 'cp'),
+ ('cat', 'cat'),
+ ]
+ # Useful set of ls aliases. The GNU and BSD options are a little
+ # different, so we make aliases that provide as similar as possible
+ # behavior in ipython, by passing the right flags for each platform
+ if sys.platform.startswith('linux'):
+ ls_aliases = [('ls', 'ls -F --color'),
+ # long ls
+ ('ll', 'ls -F -o --color'),
+ # ls normal files only
+ ('lf', 'ls -F -o --color %l | grep ^-'),
+ # ls symbolic links
+ ('lk', 'ls -F -o --color %l | grep ^l'),
+ # directories or links to directories,
+ ('ldir', 'ls -F -o --color %l | grep /$'),
+ # things which are executable
+ ('lx', 'ls -F -o --color %l | grep ^-..x'),
+ ]
+ elif sys.platform.startswith('openbsd') or sys.platform.startswith('netbsd'):
+ # OpenBSD, NetBSD. The ls implementation on these platforms do not support
+ # the -G switch and lack the ability to use colorized output.
+ ls_aliases = [('ls', 'ls -F'),
+ # long ls
+ ('ll', 'ls -F -l'),
+ # ls normal files only
+ ('lf', 'ls -F -l %l | grep ^-'),
+ # ls symbolic links
+ ('lk', 'ls -F -l %l | grep ^l'),
+ # directories or links to directories,
+ ('ldir', 'ls -F -l %l | grep /$'),
+ # things which are executable
+ ('lx', 'ls -F -l %l | grep ^-..x'),
+ ]
+ else:
+ # BSD, OSX, etc.
+ ls_aliases = [('ls', 'ls -F -G'),
+ # long ls
+ ('ll', 'ls -F -l -G'),
+ # ls normal files only
+ ('lf', 'ls -F -l -G %l | grep ^-'),
+ # ls symbolic links
+ ('lk', 'ls -F -l -G %l | grep ^l'),
+ # directories or links to directories,
+ ('ldir', 'ls -F -G -l %l | grep /$'),
+ # things which are executable
+ ('lx', 'ls -F -l -G %l | grep ^-..x'),
+ ]
+ default_aliases = default_aliases + ls_aliases
+ elif os.name in ['nt', 'dos']:
+ default_aliases = [('ls', 'dir /on'),
+ ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
+ ('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
+ ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
+ ]
+ else:
+ default_aliases = []
+
+ return default_aliases
+
+
+class AliasError(Exception):
+ pass
+
+
+class InvalidAliasError(AliasError):
+ pass
+
+class Alias(object):
+ """Callable object storing the details of one alias.
+
+ Instances are registered as magic functions to allow use of aliases.
+ """
+
+ # Prepare blacklist
+ blacklist = {'cd','popd','pushd','dhist','alias','unalias'}
+
+ def __init__(self, shell, name, cmd):
+ self.shell = shell
+ self.name = name
+ self.cmd = cmd
+ self.__doc__ = "Alias for `!{}`".format(cmd)
+ self.nargs = self.validate()
+
+ def validate(self):
+ """Validate the alias, and return the number of arguments."""
+ if self.name in self.blacklist:
+ raise InvalidAliasError("The name %s can't be aliased "
+ "because it is a keyword or builtin." % self.name)
+ try:
+ caller = self.shell.magics_manager.magics['line'][self.name]
+ except KeyError:
+ pass
+ else:
+ if not isinstance(caller, Alias):
+ raise InvalidAliasError("The name %s can't be aliased "
+ "because it is another magic command." % self.name)
+
+ if not (isinstance(self.cmd, string_types)):
+ raise InvalidAliasError("An alias command must be a string, "
+ "got: %r" % self.cmd)
+
+ nargs = self.cmd.count('%s') - self.cmd.count('%%s')
+
+ if (nargs > 0) and (self.cmd.find('%l') >= 0):
+ raise InvalidAliasError('The %s and %l specifiers are mutually '
+ 'exclusive in alias definitions.')
+
+ return nargs
+
+ def __repr__(self):
+ return "<alias {} for {!r}>".format(self.name, self.cmd)
+
+ def __call__(self, rest=''):
+ cmd = self.cmd
+ nargs = self.nargs
+ # Expand the %l special to be the user's input line
+ if cmd.find('%l') >= 0:
+ cmd = cmd.replace('%l', rest)
+ rest = ''
+
+ if nargs==0:
+ if cmd.find('%%s') >= 1:
+ cmd = cmd.replace('%%s', '%s')
+ # Simple, argument-less aliases
+ cmd = '%s %s' % (cmd, rest)
+ else:
+ # Handle aliases with positional arguments
+ args = rest.split(None, nargs)
+ if len(args) < nargs:
+ raise UsageError('Alias <%s> requires %s arguments, %s given.' %
+ (self.name, nargs, len(args)))
+ cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
+
+ self.shell.system(cmd)
+
+#-----------------------------------------------------------------------------
+# Main AliasManager class
+#-----------------------------------------------------------------------------
+
+class AliasManager(Configurable):
+
default_aliases = List(default_aliases()).tag(config=True)
user_aliases = List(default_value=[]).tag(config=True)
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
-
- def __init__(self, shell=None, **kwargs):
- super(AliasManager, self).__init__(shell=shell, **kwargs)
- # For convenient access
- self.linemagics = self.shell.magics_manager.magics['line']
- self.init_aliases()
-
- def init_aliases(self):
- # Load default & user aliases
- for name, cmd in self.default_aliases + self.user_aliases:
- self.soft_define_alias(name, cmd)
-
- @property
- def aliases(self):
- return [(n, func.cmd) for (n, func) in self.linemagics.items()
- if isinstance(func, Alias)]
-
- def soft_define_alias(self, name, cmd):
- """Define an alias, but don't raise on an AliasError."""
- try:
- self.define_alias(name, cmd)
- except AliasError as e:
- error("Invalid alias: %s" % e)
-
- def define_alias(self, name, cmd):
- """Define a new alias after validating it.
-
- This will raise an :exc:`AliasError` if there are validation
- problems.
- """
- caller = Alias(shell=self.shell, name=name, cmd=cmd)
- self.shell.magics_manager.register_function(caller, magic_kind='line',
- magic_name=name)
-
- def get_alias(self, name):
- """Return an alias, or None if no alias by that name exists."""
- aname = self.linemagics.get(name, None)
- return aname if isinstance(aname, Alias) else None
-
- def is_alias(self, name):
- """Return whether or not a given name has been defined as an alias"""
- return self.get_alias(name) is not None
-
- def undefine_alias(self, name):
- if self.is_alias(name):
- del self.linemagics[name]
- else:
- raise ValueError('%s is not an alias' % name)
-
- def clear_aliases(self):
- for name, cmd in self.aliases:
- self.undefine_alias(name)
-
- def retrieve_alias(self, name):
- """Retrieve the command to which an alias expands."""
- caller = self.get_alias(name)
- if caller:
- return caller.cmd
- else:
- raise ValueError('%s is not an alias' % name)
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
+
+ def __init__(self, shell=None, **kwargs):
+ super(AliasManager, self).__init__(shell=shell, **kwargs)
+ # For convenient access
+ self.linemagics = self.shell.magics_manager.magics['line']
+ self.init_aliases()
+
+ def init_aliases(self):
+ # Load default & user aliases
+ for name, cmd in self.default_aliases + self.user_aliases:
+ self.soft_define_alias(name, cmd)
+
+ @property
+ def aliases(self):
+ return [(n, func.cmd) for (n, func) in self.linemagics.items()
+ if isinstance(func, Alias)]
+
+ def soft_define_alias(self, name, cmd):
+ """Define an alias, but don't raise on an AliasError."""
+ try:
+ self.define_alias(name, cmd)
+ except AliasError as e:
+ error("Invalid alias: %s" % e)
+
+ def define_alias(self, name, cmd):
+ """Define a new alias after validating it.
+
+ This will raise an :exc:`AliasError` if there are validation
+ problems.
+ """
+ caller = Alias(shell=self.shell, name=name, cmd=cmd)
+ self.shell.magics_manager.register_function(caller, magic_kind='line',
+ magic_name=name)
+
+ def get_alias(self, name):
+ """Return an alias, or None if no alias by that name exists."""
+ aname = self.linemagics.get(name, None)
+ return aname if isinstance(aname, Alias) else None
+
+ def is_alias(self, name):
+ """Return whether or not a given name has been defined as an alias"""
+ return self.get_alias(name) is not None
+
+ def undefine_alias(self, name):
+ if self.is_alias(name):
+ del self.linemagics[name]
+ else:
+ raise ValueError('%s is not an alias' % name)
+
+ def clear_aliases(self):
+ for name, cmd in self.aliases:
+ self.undefine_alias(name)
+
+ def retrieve_alias(self, name):
+ """Retrieve the command to which an alias expands."""
+ caller = self.get_alias(name)
+ if caller:
+ return caller.cmd
+ else:
+ raise ValueError('%s is not an alias' % name)
diff --git a/contrib/python/ipython/py2/IPython/core/application.py b/contrib/python/ipython/py2/IPython/core/application.py
index 99e94a342a..af28133945 100644
--- a/contrib/python/ipython/py2/IPython/core/application.py
+++ b/contrib/python/ipython/py2/IPython/core/application.py
@@ -1,49 +1,49 @@
-# encoding: utf-8
-"""
-An application for IPython.
-
-All top-level applications should use the classes in this module for
-handling configuration and creating configurables.
-
-The job of an :class:`Application` is to create the master configuration
-object and then create the configurable objects, passing the config to them.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import atexit
+# encoding: utf-8
+"""
+An application for IPython.
+
+All top-level applications should use the classes in this module for
+handling configuration and creating configurables.
+
+The job of an :class:`Application` is to create the master configuration
+object and then create the configurable objects, passing the config to them.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import atexit
from copy import deepcopy
-import glob
-import logging
-import os
-import shutil
-import sys
-
-from traitlets.config.application import Application, catch_config_error
-from traitlets.config.loader import ConfigFileNotFound, PyFileConfigLoader
-from IPython.core import release, crashhandler
-from IPython.core.profiledir import ProfileDir, ProfileDirError
-from IPython.paths import get_ipython_dir, get_ipython_package_dir
-from IPython.utils.path import ensure_dir_exists
-from IPython.utils import py3compat
+import glob
+import logging
+import os
+import shutil
+import sys
+
+from traitlets.config.application import Application, catch_config_error
+from traitlets.config.loader import ConfigFileNotFound, PyFileConfigLoader
+from IPython.core import release, crashhandler
+from IPython.core.profiledir import ProfileDir, ProfileDirError
+from IPython.paths import get_ipython_dir, get_ipython_package_dir
+from IPython.utils.path import ensure_dir_exists
+from IPython.utils import py3compat
from traitlets import (
List, Unicode, Type, Bool, Dict, Set, Instance, Undefined,
default, observe,
)
-
-if os.name == 'nt':
- programdata = os.environ.get('PROGRAMDATA', None)
- if programdata:
- SYSTEM_CONFIG_DIRS = [os.path.join(programdata, 'ipython')]
- else: # PROGRAMDATA is not defined by default on XP.
- SYSTEM_CONFIG_DIRS = []
-else:
- SYSTEM_CONFIG_DIRS = [
- "/usr/local/etc/ipython",
- "/etc/ipython",
- ]
-
+
+if os.name == 'nt':
+ programdata = os.environ.get('PROGRAMDATA', None)
+ if programdata:
+ SYSTEM_CONFIG_DIRS = [os.path.join(programdata, 'ipython')]
+ else: # PROGRAMDATA is not defined by default on XP.
+ SYSTEM_CONFIG_DIRS = []
+else:
+ SYSTEM_CONFIG_DIRS = [
+ "/usr/local/etc/ipython",
+ "/etc/ipython",
+ ]
+
ENV_CONFIG_DIRS = []
_env_config_dir = os.path.join(sys.prefix, 'etc', 'ipython')
@@ -62,241 +62,241 @@ else:
IPYTHON_SUPPRESS_CONFIG_ERRORS = False
else:
sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
-
-# aliases and flags
-
-base_aliases = {
- 'profile-dir' : 'ProfileDir.location',
- 'profile' : 'BaseIPythonApplication.profile',
- 'ipython-dir' : 'BaseIPythonApplication.ipython_dir',
- 'log-level' : 'Application.log_level',
- 'config' : 'BaseIPythonApplication.extra_config_file',
-}
-
-base_flags = dict(
- debug = ({'Application' : {'log_level' : logging.DEBUG}},
- "set log level to logging.DEBUG (maximize logging output)"),
- quiet = ({'Application' : {'log_level' : logging.CRITICAL}},
- "set log level to logging.CRITICAL (minimize logging output)"),
- init = ({'BaseIPythonApplication' : {
- 'copy_config_files' : True,
- 'auto_create' : True}
- }, """Initialize profile with default config files. This is equivalent
- to running `ipython profile create <profile>` prior to startup.
- """)
-)
-
-class ProfileAwareConfigLoader(PyFileConfigLoader):
- """A Python file config loader that is aware of IPython profiles."""
- def load_subconfig(self, fname, path=None, profile=None):
- if profile is not None:
- try:
- profile_dir = ProfileDir.find_profile_dir_by_name(
- get_ipython_dir(),
- profile,
- )
- except ProfileDirError:
- return
- path = profile_dir.location
- return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path)
-
-class BaseIPythonApplication(Application):
-
- name = Unicode(u'ipython')
- description = Unicode(u'IPython: an enhanced interactive Python shell.')
- version = Unicode(release.version)
-
- aliases = Dict(base_aliases)
- flags = Dict(base_flags)
- classes = List([ProfileDir])
-
- # enable `load_subconfig('cfg.py', profile='name')`
- python_config_loader_class = ProfileAwareConfigLoader
-
- # Track whether the config_file has changed,
- # because some logic happens only if we aren't using the default.
- config_file_specified = Set()
-
- config_file_name = Unicode()
+
+# aliases and flags
+
+base_aliases = {
+ 'profile-dir' : 'ProfileDir.location',
+ 'profile' : 'BaseIPythonApplication.profile',
+ 'ipython-dir' : 'BaseIPythonApplication.ipython_dir',
+ 'log-level' : 'Application.log_level',
+ 'config' : 'BaseIPythonApplication.extra_config_file',
+}
+
+base_flags = dict(
+ debug = ({'Application' : {'log_level' : logging.DEBUG}},
+ "set log level to logging.DEBUG (maximize logging output)"),
+ quiet = ({'Application' : {'log_level' : logging.CRITICAL}},
+ "set log level to logging.CRITICAL (minimize logging output)"),
+ init = ({'BaseIPythonApplication' : {
+ 'copy_config_files' : True,
+ 'auto_create' : True}
+ }, """Initialize profile with default config files. This is equivalent
+ to running `ipython profile create <profile>` prior to startup.
+ """)
+)
+
+class ProfileAwareConfigLoader(PyFileConfigLoader):
+ """A Python file config loader that is aware of IPython profiles."""
+ def load_subconfig(self, fname, path=None, profile=None):
+ if profile is not None:
+ try:
+ profile_dir = ProfileDir.find_profile_dir_by_name(
+ get_ipython_dir(),
+ profile,
+ )
+ except ProfileDirError:
+ return
+ path = profile_dir.location
+ return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path)
+
+class BaseIPythonApplication(Application):
+
+ name = Unicode(u'ipython')
+ description = Unicode(u'IPython: an enhanced interactive Python shell.')
+ version = Unicode(release.version)
+
+ aliases = Dict(base_aliases)
+ flags = Dict(base_flags)
+ classes = List([ProfileDir])
+
+ # enable `load_subconfig('cfg.py', profile='name')`
+ python_config_loader_class = ProfileAwareConfigLoader
+
+ # Track whether the config_file has changed,
+ # because some logic happens only if we aren't using the default.
+ config_file_specified = Set()
+
+ config_file_name = Unicode()
@default('config_file_name')
- def _config_file_name_default(self):
- return self.name.replace('-','_') + u'_config.py'
+ def _config_file_name_default(self):
+ return self.name.replace('-','_') + u'_config.py'
@observe('config_file_name')
def _config_file_name_changed(self, change):
if change['new'] != change['old']:
self.config_file_specified.add(change['new'])
-
- # The directory that contains IPython's builtin profiles.
- builtin_profile_dir = Unicode(
- os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
- )
-
- config_file_paths = List(Unicode())
+
+ # The directory that contains IPython's builtin profiles.
+ builtin_profile_dir = Unicode(
+ os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
+ )
+
+ config_file_paths = List(Unicode())
@default('config_file_paths')
- def _config_file_paths_default(self):
- return [py3compat.getcwd()]
-
+ def _config_file_paths_default(self):
+ return [py3compat.getcwd()]
+
extra_config_file = Unicode(
- help="""Path to an extra config file to load.
-
- If specified, load this config file in addition to any other IPython config.
+ help="""Path to an extra config file to load.
+
+ If specified, load this config file in addition to any other IPython config.
""").tag(config=True)
@observe('extra_config_file')
def _extra_config_file_changed(self, change):
old = change['old']
new = change['new']
- try:
- self.config_files.remove(old)
- except ValueError:
- pass
- self.config_file_specified.add(new)
- self.config_files.append(new)
-
+ try:
+ self.config_files.remove(old)
+ except ValueError:
+ pass
+ self.config_file_specified.add(new)
+ self.config_files.append(new)
+
profile = Unicode(u'default',
- help="""The IPython profile to use."""
+ help="""The IPython profile to use."""
).tag(config=True)
@observe('profile')
def _profile_changed(self, change):
- self.builtin_profile_dir = os.path.join(
+ self.builtin_profile_dir = os.path.join(
get_ipython_package_dir(), u'config', u'profile', change['new']
- )
-
+ )
+
ipython_dir = Unicode(
- help="""
- The name of the IPython directory. This directory is used for logging
- configuration (through profiles), history storage, etc. The default
- is usually $HOME/.ipython. This option can also be specified through
- the environment variable IPYTHONDIR.
- """
+ help="""
+ The name of the IPython directory. This directory is used for logging
+ configuration (through profiles), history storage, etc. The default
+ is usually $HOME/.ipython. This option can also be specified through
+ the environment variable IPYTHONDIR.
+ """
).tag(config=True)
@default('ipython_dir')
- def _ipython_dir_default(self):
- d = get_ipython_dir()
+ def _ipython_dir_default(self):
+ d = get_ipython_dir()
self._ipython_dir_changed({
'name': 'ipython_dir',
'old': d,
'new': d,
})
- return d
-
- _in_init_profile_dir = False
- profile_dir = Instance(ProfileDir, allow_none=True)
+ return d
+
+ _in_init_profile_dir = False
+ profile_dir = Instance(ProfileDir, allow_none=True)
@default('profile_dir')
- def _profile_dir_default(self):
- # avoid recursion
- if self._in_init_profile_dir:
- return
- # profile_dir requested early, force initialization
- self.init_profile_dir()
- return self.profile_dir
-
+ def _profile_dir_default(self):
+ # avoid recursion
+ if self._in_init_profile_dir:
+ return
+ # profile_dir requested early, force initialization
+ self.init_profile_dir()
+ return self.profile_dir
+
overwrite = Bool(False,
help="""Whether to overwrite existing config files when copying"""
).tag(config=True)
auto_create = Bool(False,
help="""Whether to create profile dir if it doesn't exist"""
).tag(config=True)
-
- config_files = List(Unicode())
+
+ config_files = List(Unicode())
@default('config_files')
- def _config_files_default(self):
- return [self.config_file_name]
-
+ def _config_files_default(self):
+ return [self.config_file_name]
+
copy_config_files = Bool(False,
- help="""Whether to install the default config files into the profile dir.
- If a new profile is being created, and IPython contains config files for that
- profile, then they will be staged into the new directory. Otherwise,
- default config files will be automatically generated.
+ help="""Whether to install the default config files into the profile dir.
+ If a new profile is being created, and IPython contains config files for that
+ profile, then they will be staged into the new directory. Otherwise,
+ default config files will be automatically generated.
""").tag(config=True)
-
+
verbose_crash = Bool(False,
- help="""Create a massive crash report when IPython encounters what may be an
- internal error. The default is to append a short message to the
+ help="""Create a massive crash report when IPython encounters what may be an
+ internal error. The default is to append a short message to the
usual traceback""").tag(config=True)
-
- # The class to use as the crash handler.
- crash_handler_class = Type(crashhandler.CrashHandler)
-
- @catch_config_error
- def __init__(self, **kwargs):
- super(BaseIPythonApplication, self).__init__(**kwargs)
- # ensure current working directory exists
- try:
- py3compat.getcwd()
- except:
- # exit if cwd doesn't exist
- self.log.error("Current working directory doesn't exist.")
- self.exit(1)
-
- #-------------------------------------------------------------------------
- # Various stages of Application creation
- #-------------------------------------------------------------------------
-
- deprecated_subcommands = {}
-
- def initialize_subcommand(self, subc, argv=None):
- if subc in self.deprecated_subcommands:
- self.log.warning("Subcommand `ipython {sub}` is deprecated and will be removed "
- "in future versions.".format(sub=subc))
+
+ # The class to use as the crash handler.
+ crash_handler_class = Type(crashhandler.CrashHandler)
+
+ @catch_config_error
+ def __init__(self, **kwargs):
+ super(BaseIPythonApplication, self).__init__(**kwargs)
+ # ensure current working directory exists
+ try:
+ py3compat.getcwd()
+ except:
+ # exit if cwd doesn't exist
+ self.log.error("Current working directory doesn't exist.")
+ self.exit(1)
+
+ #-------------------------------------------------------------------------
+ # Various stages of Application creation
+ #-------------------------------------------------------------------------
+
+ deprecated_subcommands = {}
+
+ def initialize_subcommand(self, subc, argv=None):
+ if subc in self.deprecated_subcommands:
+ self.log.warning("Subcommand `ipython {sub}` is deprecated and will be removed "
+ "in future versions.".format(sub=subc))
self.log.warning("You likely want to use `jupyter {sub}` in the "
"future".format(sub=subc))
- return super(BaseIPythonApplication, self).initialize_subcommand(subc, argv)
-
- def init_crash_handler(self):
- """Create a crash handler, typically setting sys.excepthook to it."""
- self.crash_handler = self.crash_handler_class(self)
- sys.excepthook = self.excepthook
- def unset_crashhandler():
- sys.excepthook = sys.__excepthook__
- atexit.register(unset_crashhandler)
-
- def excepthook(self, etype, evalue, tb):
- """this is sys.excepthook after init_crashhandler
-
- set self.verbose_crash=True to use our full crashhandler, instead of
- a regular traceback with a short message (crash_handler_lite)
- """
-
- if self.verbose_crash:
- return self.crash_handler(etype, evalue, tb)
- else:
- return crashhandler.crash_handler_lite(etype, evalue, tb)
+ return super(BaseIPythonApplication, self).initialize_subcommand(subc, argv)
+
+ def init_crash_handler(self):
+ """Create a crash handler, typically setting sys.excepthook to it."""
+ self.crash_handler = self.crash_handler_class(self)
+ sys.excepthook = self.excepthook
+ def unset_crashhandler():
+ sys.excepthook = sys.__excepthook__
+ atexit.register(unset_crashhandler)
+
+ def excepthook(self, etype, evalue, tb):
+ """this is sys.excepthook after init_crashhandler
+
+ set self.verbose_crash=True to use our full crashhandler, instead of
+ a regular traceback with a short message (crash_handler_lite)
+ """
+
+ if self.verbose_crash:
+ return self.crash_handler(etype, evalue, tb)
+ else:
+ return crashhandler.crash_handler_lite(etype, evalue, tb)
@observe('ipython_dir')
def _ipython_dir_changed(self, change):
old = change['old']
new = change['new']
- if old is not Undefined:
- str_old = py3compat.cast_bytes_py2(os.path.abspath(old),
- sys.getfilesystemencoding()
- )
- if str_old in sys.path:
- sys.path.remove(str_old)
- str_path = py3compat.cast_bytes_py2(os.path.abspath(new),
- sys.getfilesystemencoding()
- )
- sys.path.append(str_path)
- ensure_dir_exists(new)
- readme = os.path.join(new, 'README')
- readme_src = os.path.join(get_ipython_package_dir(), u'config', u'profile', 'README')
- if not os.path.exists(readme) and os.path.exists(readme_src):
- shutil.copy(readme_src, readme)
- for d in ('extensions', 'nbextensions'):
- path = os.path.join(new, d)
- try:
- ensure_dir_exists(path)
- except OSError as e:
- # this will not be EEXIST
- self.log.error("couldn't create path %s: %s", path, e)
- self.log.debug("IPYTHONDIR set to: %s" % new)
-
+ if old is not Undefined:
+ str_old = py3compat.cast_bytes_py2(os.path.abspath(old),
+ sys.getfilesystemencoding()
+ )
+ if str_old in sys.path:
+ sys.path.remove(str_old)
+ str_path = py3compat.cast_bytes_py2(os.path.abspath(new),
+ sys.getfilesystemencoding()
+ )
+ sys.path.append(str_path)
+ ensure_dir_exists(new)
+ readme = os.path.join(new, 'README')
+ readme_src = os.path.join(get_ipython_package_dir(), u'config', u'profile', 'README')
+ if not os.path.exists(readme) and os.path.exists(readme_src):
+ shutil.copy(readme_src, readme)
+ for d in ('extensions', 'nbextensions'):
+ path = os.path.join(new, d)
+ try:
+ ensure_dir_exists(path)
+ except OSError as e:
+ # this will not be EEXIST
+ self.log.error("couldn't create path %s: %s", path, e)
+ self.log.debug("IPYTHONDIR set to: %s" % new)
+
def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS):
- """Load the config file.
-
- By default, errors in loading config are handled, and a warning
- printed on screen. For testing, the suppress_errors option is set
- to False, so errors will make tests fail.
+ """Load the config file.
+
+ By default, errors in loading config are handled, and a warning
+ printed on screen. For testing, the suppress_errors option is set
+ to False, so errors will make tests fail.
`supress_errors` default value is to be `None` in which case the
behavior default to the one of `traitlets.Application`.
@@ -307,161 +307,161 @@ class BaseIPythonApplication(Application):
- to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset.
Any other value are invalid, and will make IPython exit with a non-zero return code.
- """
+ """
- self.log.debug("Searching path %s for config files", self.config_file_paths)
- base_config = 'ipython_config.py'
- self.log.debug("Attempting to load config file: %s" %
- base_config)
- try:
+ self.log.debug("Searching path %s for config files", self.config_file_paths)
+ base_config = 'ipython_config.py'
+ self.log.debug("Attempting to load config file: %s" %
+ base_config)
+ try:
if suppress_errors is not None:
old_value = Application.raise_config_file_errors
Application.raise_config_file_errors = not suppress_errors;
- Application.load_config_file(
- self,
- base_config,
- path=self.config_file_paths
- )
- except ConfigFileNotFound:
- # ignore errors loading parent
- self.log.debug("Config file %s not found", base_config)
- pass
+ Application.load_config_file(
+ self,
+ base_config,
+ path=self.config_file_paths
+ )
+ except ConfigFileNotFound:
+ # ignore errors loading parent
+ self.log.debug("Config file %s not found", base_config)
+ pass
if suppress_errors is not None:
Application.raise_config_file_errors = old_value
-
- for config_file_name in self.config_files:
- if not config_file_name or config_file_name == base_config:
- continue
- self.log.debug("Attempting to load config file: %s" %
- self.config_file_name)
- try:
- Application.load_config_file(
- self,
- config_file_name,
- path=self.config_file_paths
- )
- except ConfigFileNotFound:
- # Only warn if the default config file was NOT being used.
- if config_file_name in self.config_file_specified:
- msg = self.log.warning
- else:
- msg = self.log.debug
- msg("Config file not found, skipping: %s", config_file_name)
- except Exception:
- # For testing purposes.
- if not suppress_errors:
- raise
- self.log.warning("Error loading config file: %s" %
- self.config_file_name, exc_info=True)
-
- def init_profile_dir(self):
- """initialize the profile dir"""
- self._in_init_profile_dir = True
- if self.profile_dir is not None:
- # already ran
- return
- if 'ProfileDir.location' not in self.config:
- # location not specified, find by profile name
- try:
- p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
- except ProfileDirError:
- # not found, maybe create it (always create default profile)
- if self.auto_create or self.profile == 'default':
- try:
- p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
- except ProfileDirError:
- self.log.fatal("Could not create profile: %r"%self.profile)
- self.exit(1)
- else:
- self.log.info("Created profile dir: %r"%p.location)
- else:
- self.log.fatal("Profile %r not found."%self.profile)
- self.exit(1)
- else:
- self.log.debug("Using existing profile dir: %r"%p.location)
- else:
- location = self.config.ProfileDir.location
- # location is fully specified
- try:
- p = ProfileDir.find_profile_dir(location, self.config)
- except ProfileDirError:
- # not found, maybe create it
- if self.auto_create:
- try:
- p = ProfileDir.create_profile_dir(location, self.config)
- except ProfileDirError:
- self.log.fatal("Could not create profile directory: %r"%location)
- self.exit(1)
- else:
- self.log.debug("Creating new profile dir: %r"%location)
- else:
- self.log.fatal("Profile directory %r not found."%location)
- self.exit(1)
- else:
- self.log.info("Using existing profile dir: %r"%location)
- # if profile_dir is specified explicitly, set profile name
- dir_name = os.path.basename(p.location)
- if dir_name.startswith('profile_'):
- self.profile = dir_name[8:]
-
- self.profile_dir = p
- self.config_file_paths.append(p.location)
- self._in_init_profile_dir = False
-
- def init_config_files(self):
- """[optionally] copy default config files into profile dir."""
+
+ for config_file_name in self.config_files:
+ if not config_file_name or config_file_name == base_config:
+ continue
+ self.log.debug("Attempting to load config file: %s" %
+ self.config_file_name)
+ try:
+ Application.load_config_file(
+ self,
+ config_file_name,
+ path=self.config_file_paths
+ )
+ except ConfigFileNotFound:
+ # Only warn if the default config file was NOT being used.
+ if config_file_name in self.config_file_specified:
+ msg = self.log.warning
+ else:
+ msg = self.log.debug
+ msg("Config file not found, skipping: %s", config_file_name)
+ except Exception:
+ # For testing purposes.
+ if not suppress_errors:
+ raise
+ self.log.warning("Error loading config file: %s" %
+ self.config_file_name, exc_info=True)
+
+ def init_profile_dir(self):
+ """initialize the profile dir"""
+ self._in_init_profile_dir = True
+ if self.profile_dir is not None:
+ # already ran
+ return
+ if 'ProfileDir.location' not in self.config:
+ # location not specified, find by profile name
+ try:
+ p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
+ except ProfileDirError:
+ # not found, maybe create it (always create default profile)
+ if self.auto_create or self.profile == 'default':
+ try:
+ p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
+ except ProfileDirError:
+ self.log.fatal("Could not create profile: %r"%self.profile)
+ self.exit(1)
+ else:
+ self.log.info("Created profile dir: %r"%p.location)
+ else:
+ self.log.fatal("Profile %r not found."%self.profile)
+ self.exit(1)
+ else:
+ self.log.debug("Using existing profile dir: %r"%p.location)
+ else:
+ location = self.config.ProfileDir.location
+ # location is fully specified
+ try:
+ p = ProfileDir.find_profile_dir(location, self.config)
+ except ProfileDirError:
+ # not found, maybe create it
+ if self.auto_create:
+ try:
+ p = ProfileDir.create_profile_dir(location, self.config)
+ except ProfileDirError:
+ self.log.fatal("Could not create profile directory: %r"%location)
+ self.exit(1)
+ else:
+ self.log.debug("Creating new profile dir: %r"%location)
+ else:
+ self.log.fatal("Profile directory %r not found."%location)
+ self.exit(1)
+ else:
+ self.log.info("Using existing profile dir: %r"%location)
+ # if profile_dir is specified explicitly, set profile name
+ dir_name = os.path.basename(p.location)
+ if dir_name.startswith('profile_'):
+ self.profile = dir_name[8:]
+
+ self.profile_dir = p
+ self.config_file_paths.append(p.location)
+ self._in_init_profile_dir = False
+
+ def init_config_files(self):
+ """[optionally] copy default config files into profile dir."""
self.config_file_paths.extend(ENV_CONFIG_DIRS)
- self.config_file_paths.extend(SYSTEM_CONFIG_DIRS)
- # copy config files
- path = self.builtin_profile_dir
- if self.copy_config_files:
- src = self.profile
-
- cfg = self.config_file_name
- if path and os.path.exists(os.path.join(path, cfg)):
- self.log.warning("Staging %r from %s into %r [overwrite=%s]"%(
- cfg, src, self.profile_dir.location, self.overwrite)
- )
- self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
- else:
- self.stage_default_config_file()
- else:
- # Still stage *bundled* config files, but not generated ones
- # This is necessary for `ipython profile=sympy` to load the profile
- # on the first go
- files = glob.glob(os.path.join(path, '*.py'))
- for fullpath in files:
- cfg = os.path.basename(fullpath)
- if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
- # file was copied
- self.log.warning("Staging bundled %s from %s into %r"%(
- cfg, self.profile, self.profile_dir.location)
- )
-
-
- def stage_default_config_file(self):
- """auto generate default config file, and stage it into the profile."""
- s = self.generate_config_file()
- fname = os.path.join(self.profile_dir.location, self.config_file_name)
- if self.overwrite or not os.path.exists(fname):
- self.log.warning("Generating default config file: %r"%(fname))
- with open(fname, 'w') as f:
- f.write(s)
-
- @catch_config_error
- def initialize(self, argv=None):
- # don't hook up crash handler before parsing command-line
- self.parse_command_line(argv)
- self.init_crash_handler()
- if self.subapp is not None:
- # stop here if subapp is taking over
- return
+ self.config_file_paths.extend(SYSTEM_CONFIG_DIRS)
+ # copy config files
+ path = self.builtin_profile_dir
+ if self.copy_config_files:
+ src = self.profile
+
+ cfg = self.config_file_name
+ if path and os.path.exists(os.path.join(path, cfg)):
+ self.log.warning("Staging %r from %s into %r [overwrite=%s]"%(
+ cfg, src, self.profile_dir.location, self.overwrite)
+ )
+ self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
+ else:
+ self.stage_default_config_file()
+ else:
+ # Still stage *bundled* config files, but not generated ones
+ # This is necessary for `ipython profile=sympy` to load the profile
+ # on the first go
+ files = glob.glob(os.path.join(path, '*.py'))
+ for fullpath in files:
+ cfg = os.path.basename(fullpath)
+ if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
+ # file was copied
+ self.log.warning("Staging bundled %s from %s into %r"%(
+ cfg, self.profile, self.profile_dir.location)
+ )
+
+
+ def stage_default_config_file(self):
+ """auto generate default config file, and stage it into the profile."""
+ s = self.generate_config_file()
+ fname = os.path.join(self.profile_dir.location, self.config_file_name)
+ if self.overwrite or not os.path.exists(fname):
+ self.log.warning("Generating default config file: %r"%(fname))
+ with open(fname, 'w') as f:
+ f.write(s)
+
+ @catch_config_error
+ def initialize(self, argv=None):
+ # don't hook up crash handler before parsing command-line
+ self.parse_command_line(argv)
+ self.init_crash_handler()
+ if self.subapp is not None:
+ # stop here if subapp is taking over
+ return
# save a copy of CLI config to re-load after config files
# so that it has highest priority
cl_config = deepcopy(self.config)
- self.init_profile_dir()
- self.init_config_files()
- self.load_config_file()
- # enforce cl-opts override configfile opts:
- self.update_config(cl_config)
+ self.init_profile_dir()
+ self.init_config_files()
+ self.load_config_file()
+ # enforce cl-opts override configfile opts:
+ self.update_config(cl_config)
diff --git a/contrib/python/ipython/py2/IPython/core/autocall.py b/contrib/python/ipython/py2/IPython/core/autocall.py
index 4ef2bce59c..bab7f859c9 100644
--- a/contrib/python/ipython/py2/IPython/core/autocall.py
+++ b/contrib/python/ipython/py2/IPython/core/autocall.py
@@ -1,70 +1,70 @@
-# encoding: utf-8
-"""
-Autocall capabilities for IPython.core.
-
-Authors:
-
-* Brian Granger
-* Fernando Perez
-* Thomas Kluyver
-
-Notes
------
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-class IPyAutocall(object):
- """ Instances of this class are always autocalled
-
- This happens regardless of 'autocall' variable state. Use this to
- develop macro-like mechanisms.
- """
- _ip = None
- rewrite = True
- def __init__(self, ip=None):
- self._ip = ip
-
- def set_ip(self, ip):
- """ Will be used to set _ip point to current ipython instance b/f call
-
- Override this method if you don't want this to happen.
-
- """
- self._ip = ip
-
-
-class ExitAutocall(IPyAutocall):
- """An autocallable object which will be added to the user namespace so that
- exit, exit(), quit or quit() are all valid ways to close the shell."""
- rewrite = False
-
- def __call__(self):
- self._ip.ask_exit()
-
-class ZMQExitAutocall(ExitAutocall):
- """Exit IPython. Autocallable, so it needn't be explicitly called.
-
- Parameters
- ----------
- keep_kernel : bool
- If True, leave the kernel alive. Otherwise, tell the kernel to exit too
- (default).
- """
- def __call__(self, keep_kernel=False):
- self._ip.keepkernel_on_exit = keep_kernel
- self._ip.ask_exit()
+# encoding: utf-8
+"""
+Autocall capabilities for IPython.core.
+
+Authors:
+
+* Brian Granger
+* Fernando Perez
+* Thomas Kluyver
+
+Notes
+-----
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+class IPyAutocall(object):
+ """ Instances of this class are always autocalled
+
+ This happens regardless of 'autocall' variable state. Use this to
+ develop macro-like mechanisms.
+ """
+ _ip = None
+ rewrite = True
+ def __init__(self, ip=None):
+ self._ip = ip
+
+ def set_ip(self, ip):
+ """ Will be used to set _ip point to current ipython instance b/f call
+
+ Override this method if you don't want this to happen.
+
+ """
+ self._ip = ip
+
+
+class ExitAutocall(IPyAutocall):
+ """An autocallable object which will be added to the user namespace so that
+ exit, exit(), quit or quit() are all valid ways to close the shell."""
+ rewrite = False
+
+ def __call__(self):
+ self._ip.ask_exit()
+
+class ZMQExitAutocall(ExitAutocall):
+ """Exit IPython. Autocallable, so it needn't be explicitly called.
+
+ Parameters
+ ----------
+ keep_kernel : bool
+ If True, leave the kernel alive. Otherwise, tell the kernel to exit too
+ (default).
+ """
+ def __call__(self, keep_kernel=False):
+ self._ip.keepkernel_on_exit = keep_kernel
+ self._ip.ask_exit()
diff --git a/contrib/python/ipython/py2/IPython/core/builtin_trap.py b/contrib/python/ipython/py2/IPython/core/builtin_trap.py
index 011362599c..909a555c73 100644
--- a/contrib/python/ipython/py2/IPython/core/builtin_trap.py
+++ b/contrib/python/ipython/py2/IPython/core/builtin_trap.py
@@ -1,114 +1,114 @@
-"""
-A context manager for managing things injected into :mod:`__builtin__`.
-
-Authors:
-
-* Brian Granger
-* Fernando Perez
-"""
-#-----------------------------------------------------------------------------
-# Copyright (C) 2010-2011 The IPython Development Team.
-#
-# Distributed under the terms of the BSD License.
-#
-# Complete license in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from traitlets.config.configurable import Configurable
-
-from IPython.utils.py3compat import builtin_mod, iteritems
-from traitlets import Instance
-
-#-----------------------------------------------------------------------------
-# Classes and functions
-#-----------------------------------------------------------------------------
-
-class __BuiltinUndefined(object): pass
-BuiltinUndefined = __BuiltinUndefined()
-
-class __HideBuiltin(object): pass
-HideBuiltin = __HideBuiltin()
-
-
-class BuiltinTrap(Configurable):
-
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
- allow_none=True)
-
- def __init__(self, shell=None):
- super(BuiltinTrap, self).__init__(shell=shell, config=None)
- self._orig_builtins = {}
- # We define this to track if a single BuiltinTrap is nested.
- # Only turn off the trap when the outermost call to __exit__ is made.
- self._nested_level = 0
- self.shell = shell
- # builtins we always add - if set to HideBuiltin, they will just
- # be removed instead of being replaced by something else
- self.auto_builtins = {'exit': HideBuiltin,
- 'quit': HideBuiltin,
- 'get_ipython': self.shell.get_ipython,
- }
- # Recursive reload function
- try:
- from IPython.lib import deepreload
- if self.shell.deep_reload:
- from warnings import warn
+"""
+A context manager for managing things injected into :mod:`__builtin__`.
+
+Authors:
+
+* Brian Granger
+* Fernando Perez
+"""
+#-----------------------------------------------------------------------------
+# Copyright (C) 2010-2011 The IPython Development Team.
+#
+# Distributed under the terms of the BSD License.
+#
+# Complete license in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+from traitlets.config.configurable import Configurable
+
+from IPython.utils.py3compat import builtin_mod, iteritems
+from traitlets import Instance
+
+#-----------------------------------------------------------------------------
+# Classes and functions
+#-----------------------------------------------------------------------------
+
+class __BuiltinUndefined(object): pass
+BuiltinUndefined = __BuiltinUndefined()
+
+class __HideBuiltin(object): pass
+HideBuiltin = __HideBuiltin()
+
+
+class BuiltinTrap(Configurable):
+
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
+ allow_none=True)
+
+ def __init__(self, shell=None):
+ super(BuiltinTrap, self).__init__(shell=shell, config=None)
+ self._orig_builtins = {}
+ # We define this to track if a single BuiltinTrap is nested.
+ # Only turn off the trap when the outermost call to __exit__ is made.
+ self._nested_level = 0
+ self.shell = shell
+ # builtins we always add - if set to HideBuiltin, they will just
+ # be removed instead of being replaced by something else
+ self.auto_builtins = {'exit': HideBuiltin,
+ 'quit': HideBuiltin,
+ 'get_ipython': self.shell.get_ipython,
+ }
+ # Recursive reload function
+ try:
+ from IPython.lib import deepreload
+ if self.shell.deep_reload:
+ from warnings import warn
warn("Automatically replacing builtin `reload` by `deepreload.reload` is deprecated since IPython 4.0, please import `reload` explicitly from `IPython.lib.deepreload", DeprecationWarning)
- self.auto_builtins['reload'] = deepreload._dreload
- else:
- self.auto_builtins['dreload']= deepreload._dreload
- except ImportError:
- pass
-
- def __enter__(self):
- if self._nested_level == 0:
- self.activate()
- self._nested_level += 1
- # I return self, so callers can use add_builtin in a with clause.
- return self
-
- def __exit__(self, type, value, traceback):
- if self._nested_level == 1:
- self.deactivate()
- self._nested_level -= 1
- # Returning False will cause exceptions to propagate
- return False
-
- def add_builtin(self, key, value):
- """Add a builtin and save the original."""
- bdict = builtin_mod.__dict__
- orig = bdict.get(key, BuiltinUndefined)
- if value is HideBuiltin:
- if orig is not BuiltinUndefined: #same as 'key in bdict'
- self._orig_builtins[key] = orig
- del bdict[key]
- else:
- self._orig_builtins[key] = orig
- bdict[key] = value
-
- def remove_builtin(self, key, orig):
- """Remove an added builtin and re-set the original."""
- if orig is BuiltinUndefined:
- del builtin_mod.__dict__[key]
- else:
- builtin_mod.__dict__[key] = orig
-
- def activate(self):
- """Store ipython references in the __builtin__ namespace."""
-
- add_builtin = self.add_builtin
- for name, func in iteritems(self.auto_builtins):
- add_builtin(name, func)
-
- def deactivate(self):
- """Remove any builtins which might have been added by add_builtins, or
- restore overwritten ones to their previous values."""
- remove_builtin = self.remove_builtin
- for key, val in iteritems(self._orig_builtins):
- remove_builtin(key, val)
- self._orig_builtins.clear()
- self._builtins_added = False
+ self.auto_builtins['reload'] = deepreload._dreload
+ else:
+ self.auto_builtins['dreload']= deepreload._dreload
+ except ImportError:
+ pass
+
+ def __enter__(self):
+ if self._nested_level == 0:
+ self.activate()
+ self._nested_level += 1
+ # I return self, so callers can use add_builtin in a with clause.
+ return self
+
+ def __exit__(self, type, value, traceback):
+ if self._nested_level == 1:
+ self.deactivate()
+ self._nested_level -= 1
+ # Returning False will cause exceptions to propagate
+ return False
+
+ def add_builtin(self, key, value):
+ """Add a builtin and save the original."""
+ bdict = builtin_mod.__dict__
+ orig = bdict.get(key, BuiltinUndefined)
+ if value is HideBuiltin:
+ if orig is not BuiltinUndefined: #same as 'key in bdict'
+ self._orig_builtins[key] = orig
+ del bdict[key]
+ else:
+ self._orig_builtins[key] = orig
+ bdict[key] = value
+
+ def remove_builtin(self, key, orig):
+ """Remove an added builtin and re-set the original."""
+ if orig is BuiltinUndefined:
+ del builtin_mod.__dict__[key]
+ else:
+ builtin_mod.__dict__[key] = orig
+
+ def activate(self):
+ """Store ipython references in the __builtin__ namespace."""
+
+ add_builtin = self.add_builtin
+ for name, func in iteritems(self.auto_builtins):
+ add_builtin(name, func)
+
+ def deactivate(self):
+ """Remove any builtins which might have been added by add_builtins, or
+ restore overwritten ones to their previous values."""
+ remove_builtin = self.remove_builtin
+ for key, val in iteritems(self._orig_builtins):
+ remove_builtin(key, val)
+ self._orig_builtins.clear()
+ self._builtins_added = False
diff --git a/contrib/python/ipython/py2/IPython/core/compilerop.py b/contrib/python/ipython/py2/IPython/core/compilerop.py
index f662e37e96..f529eb5224 100644
--- a/contrib/python/ipython/py2/IPython/core/compilerop.py
+++ b/contrib/python/ipython/py2/IPython/core/compilerop.py
@@ -1,144 +1,144 @@
-"""Compiler tools with improved interactive support.
-
-Provides compilation machinery similar to codeop, but with caching support so
-we can provide interactive tracebacks.
-
-Authors
--------
-* Robert Kern
-* Fernando Perez
-* Thomas Kluyver
-"""
-
-# Note: though it might be more natural to name this module 'compiler', that
-# name is in the stdlib and name collisions with the stdlib tend to produce
-# weird problems (often with third-party tools).
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2010-2011 The IPython Development Team.
-#
-# Distributed under the terms of the BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-from __future__ import print_function
-
-# Stdlib imports
-import __future__
-from ast import PyCF_ONLY_AST
-import codeop
-import functools
-import hashlib
-import linecache
-import operator
-import time
-
-#-----------------------------------------------------------------------------
-# Constants
-#-----------------------------------------------------------------------------
-
-# Roughtly equal to PyCF_MASK | PyCF_MASK_OBSOLETE as defined in pythonrun.h,
-# this is used as a bitmask to extract future-related code flags.
-PyCF_MASK = functools.reduce(operator.or_,
- (getattr(__future__, fname).compiler_flag
- for fname in __future__.all_feature_names))
-
-#-----------------------------------------------------------------------------
-# Local utilities
-#-----------------------------------------------------------------------------
-
-def code_name(code, number=0):
- """ Compute a (probably) unique name for code for caching.
-
- This now expects code to be unicode.
- """
+"""Compiler tools with improved interactive support.
+
+Provides compilation machinery similar to codeop, but with caching support so
+we can provide interactive tracebacks.
+
+Authors
+-------
+* Robert Kern
+* Fernando Perez
+* Thomas Kluyver
+"""
+
+# Note: though it might be more natural to name this module 'compiler', that
+# name is in the stdlib and name collisions with the stdlib tend to produce
+# weird problems (often with third-party tools).
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2010-2011 The IPython Development Team.
+#
+# Distributed under the terms of the BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+from __future__ import print_function
+
+# Stdlib imports
+import __future__
+from ast import PyCF_ONLY_AST
+import codeop
+import functools
+import hashlib
+import linecache
+import operator
+import time
+
+#-----------------------------------------------------------------------------
+# Constants
+#-----------------------------------------------------------------------------
+
+# Roughtly equal to PyCF_MASK | PyCF_MASK_OBSOLETE as defined in pythonrun.h,
+# this is used as a bitmask to extract future-related code flags.
+PyCF_MASK = functools.reduce(operator.or_,
+ (getattr(__future__, fname).compiler_flag
+ for fname in __future__.all_feature_names))
+
+#-----------------------------------------------------------------------------
+# Local utilities
+#-----------------------------------------------------------------------------
+
+def code_name(code, number=0):
+ """ Compute a (probably) unique name for code for caching.
+
+ This now expects code to be unicode.
+ """
hash_digest = hashlib.sha1(code.encode("utf-8")).hexdigest()
- # Include the number and 12 characters of the hash in the name. It's
- # pretty much impossible that in a single session we'll have collisions
- # even with truncated hashes, and the full one makes tracebacks too long
- return '<ipython-input-{0}-{1}>'.format(number, hash_digest[:12])
-
-#-----------------------------------------------------------------------------
-# Classes and functions
-#-----------------------------------------------------------------------------
-
-class CachingCompiler(codeop.Compile):
- """A compiler that caches code compiled from interactive statements.
- """
-
- def __init__(self):
- codeop.Compile.__init__(self)
-
- # This is ugly, but it must be done this way to allow multiple
- # simultaneous ipython instances to coexist. Since Python itself
- # directly accesses the data structures in the linecache module, and
- # the cache therein is global, we must work with that data structure.
- # We must hold a reference to the original checkcache routine and call
- # that in our own check_cache() below, but the special IPython cache
- # must also be shared by all IPython instances. If we were to hold
- # separate caches (one in each CachingCompiler instance), any call made
- # by Python itself to linecache.checkcache() would obliterate the
- # cached data from the other IPython instances.
- if not hasattr(linecache, '_ipython_cache'):
- linecache._ipython_cache = {}
- if not hasattr(linecache, '_checkcache_ori'):
- linecache._checkcache_ori = linecache.checkcache
- # Now, we must monkeypatch the linecache directly so that parts of the
- # stdlib that call it outside our control go through our codepath
- # (otherwise we'd lose our tracebacks).
- linecache.checkcache = check_linecache_ipython
-
- def ast_parse(self, source, filename='<unknown>', symbol='exec'):
- """Parse code to an AST with the current compiler flags active.
-
- Arguments are exactly the same as ast.parse (in the standard library),
- and are passed to the built-in compile function."""
- return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
-
- def reset_compiler_flags(self):
- """Reset compiler flags to default state."""
- # This value is copied from codeop.Compile.__init__, so if that ever
- # changes, it will need to be updated.
- self.flags = codeop.PyCF_DONT_IMPLY_DEDENT
-
- @property
- def compiler_flags(self):
- """Flags currently active in the compilation process.
- """
- return self.flags
-
- def cache(self, code, number=0):
- """Make a name for a block of code, and cache the code.
-
- Parameters
- ----------
- code : str
- The Python source code to cache.
- number : int
- A number which forms part of the code's name. Used for the execution
- counter.
-
- Returns
- -------
- The name of the cached code (as a string). Pass this as the filename
- argument to compilation, so that tracebacks are correctly hooked up.
- """
- name = code_name(code, number)
- entry = (len(code), time.time(),
- [line+'\n' for line in code.splitlines()], name)
- linecache.cache[name] = entry
- linecache._ipython_cache[name] = entry
- return name
-
-def check_linecache_ipython(*args):
- """Call linecache.checkcache() safely protecting our cached values.
- """
- # First call the orignal checkcache as intended
- linecache._checkcache_ori(*args)
- # Then, update back the cache with our data, so that tracebacks related
- # to our compiled codes can be produced.
- linecache.cache.update(linecache._ipython_cache)
+ # Include the number and 12 characters of the hash in the name. It's
+ # pretty much impossible that in a single session we'll have collisions
+ # even with truncated hashes, and the full one makes tracebacks too long
+ return '<ipython-input-{0}-{1}>'.format(number, hash_digest[:12])
+
+#-----------------------------------------------------------------------------
+# Classes and functions
+#-----------------------------------------------------------------------------
+
+class CachingCompiler(codeop.Compile):
+ """A compiler that caches code compiled from interactive statements.
+ """
+
+ def __init__(self):
+ codeop.Compile.__init__(self)
+
+ # This is ugly, but it must be done this way to allow multiple
+ # simultaneous ipython instances to coexist. Since Python itself
+ # directly accesses the data structures in the linecache module, and
+ # the cache therein is global, we must work with that data structure.
+ # We must hold a reference to the original checkcache routine and call
+ # that in our own check_cache() below, but the special IPython cache
+ # must also be shared by all IPython instances. If we were to hold
+ # separate caches (one in each CachingCompiler instance), any call made
+ # by Python itself to linecache.checkcache() would obliterate the
+ # cached data from the other IPython instances.
+ if not hasattr(linecache, '_ipython_cache'):
+ linecache._ipython_cache = {}
+ if not hasattr(linecache, '_checkcache_ori'):
+ linecache._checkcache_ori = linecache.checkcache
+ # Now, we must monkeypatch the linecache directly so that parts of the
+ # stdlib that call it outside our control go through our codepath
+ # (otherwise we'd lose our tracebacks).
+ linecache.checkcache = check_linecache_ipython
+
+ def ast_parse(self, source, filename='<unknown>', symbol='exec'):
+ """Parse code to an AST with the current compiler flags active.
+
+ Arguments are exactly the same as ast.parse (in the standard library),
+ and are passed to the built-in compile function."""
+ return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
+
+ def reset_compiler_flags(self):
+ """Reset compiler flags to default state."""
+ # This value is copied from codeop.Compile.__init__, so if that ever
+ # changes, it will need to be updated.
+ self.flags = codeop.PyCF_DONT_IMPLY_DEDENT
+
+ @property
+ def compiler_flags(self):
+ """Flags currently active in the compilation process.
+ """
+ return self.flags
+
+ def cache(self, code, number=0):
+ """Make a name for a block of code, and cache the code.
+
+ Parameters
+ ----------
+ code : str
+ The Python source code to cache.
+ number : int
+ A number which forms part of the code's name. Used for the execution
+ counter.
+
+ Returns
+ -------
+ The name of the cached code (as a string). Pass this as the filename
+ argument to compilation, so that tracebacks are correctly hooked up.
+ """
+ name = code_name(code, number)
+ entry = (len(code), time.time(),
+ [line+'\n' for line in code.splitlines()], name)
+ linecache.cache[name] = entry
+ linecache._ipython_cache[name] = entry
+ return name
+
+def check_linecache_ipython(*args):
+ """Call linecache.checkcache() safely protecting our cached values.
+ """
+ # First call the orignal checkcache as intended
+ linecache._checkcache_ori(*args)
+ # Then, update back the cache with our data, so that tracebacks related
+ # to our compiled codes can be produced.
+ linecache.cache.update(linecache._ipython_cache)
diff --git a/contrib/python/ipython/py2/IPython/core/completer.py b/contrib/python/ipython/py2/IPython/core/completer.py
index 46003de8d4..b386945e54 100644
--- a/contrib/python/ipython/py2/IPython/core/completer.py
+++ b/contrib/python/ipython/py2/IPython/core/completer.py
@@ -1,79 +1,79 @@
-# encoding: utf-8
-"""Word completion for IPython.
-
+# encoding: utf-8
+"""Word completion for IPython.
+
This module started as fork of the rlcompleter module in the Python standard
-library. The original enhancements made to rlcompleter have been sent
+library. The original enhancements made to rlcompleter have been sent
upstream and were accepted as of Python 2.3,
-
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-#
-# Some of this code originated from rlcompleter in the Python standard library
-# Copyright (C) 2001 Python Software Foundation, www.python.org
-
+
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+#
+# Some of this code originated from rlcompleter in the Python standard library
+# Copyright (C) 2001 Python Software Foundation, www.python.org
+
from __future__ import print_function
-import __main__
-import glob
-import inspect
-import itertools
-import keyword
-import os
-import re
-import sys
-import unicodedata
-import string
+import __main__
+import glob
+import inspect
+import itertools
+import keyword
+import os
+import re
+import sys
+import unicodedata
+import string
import warnings
-
+
from traitlets.config.configurable import Configurable
-from IPython.core.error import TryNext
-from IPython.core.inputsplitter import ESC_MAGIC
-from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
-from IPython.utils import generics
-from IPython.utils.decorators import undoc
+from IPython.core.error import TryNext
+from IPython.core.inputsplitter import ESC_MAGIC
+from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
+from IPython.utils import generics
+from IPython.utils.decorators import undoc
from IPython.utils.dir2 import dir2, get_real_method
-from IPython.utils.process import arg_split
+from IPython.utils.process import arg_split
from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
from traitlets import Bool, Enum, observe
-
-
-# Public API
-__all__ = ['Completer','IPCompleter']
-
-if sys.platform == 'win32':
- PROTECTABLES = ' '
-else:
- PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
-
+
+
+# Public API
+__all__ = ['Completer','IPCompleter']
+
+if sys.platform == 'win32':
+ PROTECTABLES = ' '
+else:
+ PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
+
# Protect against returning an enormous number of completions which the frontend
# may have trouble processing.
MATCHES_LIMIT = 500
-
-def has_open_quotes(s):
- """Return whether a string has open quotes.
-
- This simply counts whether the number of quote characters of either type in
- the string is odd.
-
- Returns
- -------
- If there is an open quote, the quote character is returned. Else, return
- False.
- """
- # We check " first, then ', so complex cases with nested quotes will get
- # the " to take precedence.
- if s.count('"') % 2:
- return '"'
- elif s.count("'") % 2:
- return "'"
- else:
- return False
-
-
-def protect_filename(s):
- """Escape a string to protect certain characters."""
+
+def has_open_quotes(s):
+ """Return whether a string has open quotes.
+
+ This simply counts whether the number of quote characters of either type in
+ the string is odd.
+
+ Returns
+ -------
+ If there is an open quote, the quote character is returned. Else, return
+ False.
+ """
+ # We check " first, then ', so complex cases with nested quotes will get
+ # the " to take precedence.
+ if s.count('"') % 2:
+ return '"'
+ elif s.count("'") % 2:
+ return "'"
+ else:
+ return False
+
+
+def protect_filename(s):
+ """Escape a string to protect certain characters."""
if set(s) & set(PROTECTABLES):
if sys.platform == "win32":
return '"' + s + '"'
@@ -81,62 +81,62 @@ def protect_filename(s):
return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
else:
return s
-
-
-def expand_user(path):
- """Expand '~'-style usernames in strings.
-
- This is similar to :func:`os.path.expanduser`, but it computes and returns
- extra information that will be useful if the input was being used in
- computing completions, and you wish to return the completions with the
- original '~' instead of its expanded value.
-
- Parameters
- ----------
- path : str
- String to be expanded. If no ~ is present, the output is the same as the
- input.
-
- Returns
- -------
- newpath : str
- Result of ~ expansion in the input path.
- tilde_expand : bool
- Whether any expansion was performed or not.
- tilde_val : str
- The value that ~ was replaced with.
- """
- # Default values
- tilde_expand = False
- tilde_val = ''
- newpath = path
-
- if path.startswith('~'):
- tilde_expand = True
- rest = len(path)-1
- newpath = os.path.expanduser(path)
- if rest:
- tilde_val = newpath[:-rest]
- else:
- tilde_val = newpath
-
- return newpath, tilde_expand, tilde_val
-
-
-def compress_user(path, tilde_expand, tilde_val):
- """Does the opposite of expand_user, with its outputs.
- """
- if tilde_expand:
- return path.replace(tilde_val, '~')
- else:
- return path
-
-
+
+
+def expand_user(path):
+ """Expand '~'-style usernames in strings.
+
+ This is similar to :func:`os.path.expanduser`, but it computes and returns
+ extra information that will be useful if the input was being used in
+ computing completions, and you wish to return the completions with the
+ original '~' instead of its expanded value.
+
+ Parameters
+ ----------
+ path : str
+ String to be expanded. If no ~ is present, the output is the same as the
+ input.
+
+ Returns
+ -------
+ newpath : str
+ Result of ~ expansion in the input path.
+ tilde_expand : bool
+ Whether any expansion was performed or not.
+ tilde_val : str
+ The value that ~ was replaced with.
+ """
+ # Default values
+ tilde_expand = False
+ tilde_val = ''
+ newpath = path
+
+ if path.startswith('~'):
+ tilde_expand = True
+ rest = len(path)-1
+ newpath = os.path.expanduser(path)
+ if rest:
+ tilde_val = newpath[:-rest]
+ else:
+ tilde_val = newpath
+
+ return newpath, tilde_expand, tilde_val
+
+
+def compress_user(path, tilde_expand, tilde_val):
+ """Does the opposite of expand_user, with its outputs.
+ """
+ if tilde_expand:
+ return path.replace(tilde_val, '~')
+ else:
+ return path
+
+
def completions_sorting_key(word):
"""key for sorting completions
-
+
This does several things:
-
+
- Lowercase all completions, so they are sorted alphabetically with
upper and lower case words mingled
- Demote any completions starting with underscores to the end
@@ -145,410 +145,410 @@ def completions_sorting_key(word):
"""
# Case insensitive sort
word = word.lower()
-
+
prio1, prio2 = 0, 0
-
+
if word.startswith('__'):
prio1 = 2
elif word.startswith('_'):
prio1 = 1
-
+
if word.endswith('='):
prio1 = -1
-
+
if word.startswith('%%'):
# If there's another % in there, this is something else, so leave it alone
- if not "%" in word[2:]:
+ if not "%" in word[2:]:
word = word[2:]
prio2 = 2
elif word.startswith('%'):
- if not "%" in word[1:]:
+ if not "%" in word[1:]:
word = word[1:]
prio2 = 1
-
+
return prio1, word, prio2
-
-@undoc
-class Bunch(object): pass
-
-
+
+@undoc
+class Bunch(object): pass
+
+
if sys.platform == 'win32':
DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
else:
DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
-GREEDY_DELIMS = ' =\r\n'
-
-
-class CompletionSplitter(object):
- """An object to split an input line in a manner similar to readline.
-
- By having our own implementation, we can expose readline-like completion in
- a uniform manner to all frontends. This object only needs to be given the
- line of text to be split and the cursor position on said line, and it
- returns the 'word' to be completed on at the cursor after splitting the
- entire line.
-
- What characters are used as splitting delimiters can be controlled by
- setting the `delims` attribute (this is a property that internally
- automatically builds the necessary regular expression)"""
-
- # Private interface
-
- # A string of delimiter characters. The default value makes sense for
- # IPython's most typical usage patterns.
- _delims = DELIMS
-
- # The expression (a normal string) to be compiled into a regular expression
- # for actual splitting. We store it as an attribute mostly for ease of
- # debugging, since this type of code can be so tricky to debug.
- _delim_expr = None
-
- # The regular expression that does the actual splitting
- _delim_re = None
-
- def __init__(self, delims=None):
- delims = CompletionSplitter._delims if delims is None else delims
- self.delims = delims
-
- @property
- def delims(self):
- """Return the string of delimiter characters."""
- return self._delims
-
- @delims.setter
- def delims(self, delims):
- """Set the delimiters for line splitting."""
- expr = '[' + ''.join('\\'+ c for c in delims) + ']'
- self._delim_re = re.compile(expr)
- self._delims = delims
- self._delim_expr = expr
-
- def split_line(self, line, cursor_pos=None):
- """Split a line of text with a cursor at the given position.
- """
- l = line if cursor_pos is None else line[:cursor_pos]
- return self._delim_re.split(l)[-1]
-
-
-class Completer(Configurable):
-
+GREEDY_DELIMS = ' =\r\n'
+
+
+class CompletionSplitter(object):
+ """An object to split an input line in a manner similar to readline.
+
+ By having our own implementation, we can expose readline-like completion in
+ a uniform manner to all frontends. This object only needs to be given the
+ line of text to be split and the cursor position on said line, and it
+ returns the 'word' to be completed on at the cursor after splitting the
+ entire line.
+
+ What characters are used as splitting delimiters can be controlled by
+ setting the `delims` attribute (this is a property that internally
+ automatically builds the necessary regular expression)"""
+
+ # Private interface
+
+ # A string of delimiter characters. The default value makes sense for
+ # IPython's most typical usage patterns.
+ _delims = DELIMS
+
+ # The expression (a normal string) to be compiled into a regular expression
+ # for actual splitting. We store it as an attribute mostly for ease of
+ # debugging, since this type of code can be so tricky to debug.
+ _delim_expr = None
+
+ # The regular expression that does the actual splitting
+ _delim_re = None
+
+ def __init__(self, delims=None):
+ delims = CompletionSplitter._delims if delims is None else delims
+ self.delims = delims
+
+ @property
+ def delims(self):
+ """Return the string of delimiter characters."""
+ return self._delims
+
+ @delims.setter
+ def delims(self, delims):
+ """Set the delimiters for line splitting."""
+ expr = '[' + ''.join('\\'+ c for c in delims) + ']'
+ self._delim_re = re.compile(expr)
+ self._delims = delims
+ self._delim_expr = expr
+
+ def split_line(self, line, cursor_pos=None):
+ """Split a line of text with a cursor at the given position.
+ """
+ l = line if cursor_pos is None else line[:cursor_pos]
+ return self._delim_re.split(l)[-1]
+
+
+class Completer(Configurable):
+
greedy = Bool(False,
- help="""Activate greedy completion
+ help="""Activate greedy completion
PENDING DEPRECTION. this is now mostly taken care of with Jedi.
-
- This will enable completion on elements of lists, results of function calls, etc.,
- but can be unsafe because the code is actually evaluated on TAB.
- """
+
+ This will enable completion on elements of lists, results of function calls, etc.,
+ but can be unsafe because the code is actually evaluated on TAB.
+ """
).tag(config=True)
-
+
backslash_combining_completions = Bool(True,
help="Enable unicode completions, e.g. \\alpha<tab> . "
"Includes completion of latex commands, unicode names, and expanding "
"unicode characters back to latex commands.").tag(config=True)
- def __init__(self, namespace=None, global_namespace=None, **kwargs):
- """Create a new completer for the command line.
-
+ def __init__(self, namespace=None, global_namespace=None, **kwargs):
+ """Create a new completer for the command line.
+
Completer(namespace=ns, global_namespace=ns2) -> completer instance.
-
- If unspecified, the default namespace where completions are performed
- is __main__ (technically, __main__.__dict__). Namespaces should be
- given as dictionaries.
-
- An optional second namespace can be given. This allows the completer
- to handle cases where both the local and global scopes need to be
- distinguished.
-
- Completer instances should be used as the completion mechanism of
- readline via the set_completer() call:
-
- readline.set_completer(Completer(my_namespace).complete)
- """
-
- # Don't bind to namespace quite yet, but flag whether the user wants a
- # specific namespace or to use __main__.__dict__. This will allow us
- # to bind to __main__.__dict__ at completion time, not now.
- if namespace is None:
- self.use_main_ns = 1
- else:
- self.use_main_ns = 0
- self.namespace = namespace
-
- # The global namespace, if given, can be bound directly
- if global_namespace is None:
- self.global_namespace = {}
- else:
- self.global_namespace = global_namespace
-
- super(Completer, self).__init__(**kwargs)
-
- def complete(self, text, state):
- """Return the next possible completion for 'text'.
-
- This is called successively with state == 0, 1, 2, ... until it
- returns None. The completion should begin with 'text'.
-
- """
- if self.use_main_ns:
- self.namespace = __main__.__dict__
-
- if state == 0:
- if "." in text:
- self.matches = self.attr_matches(text)
- else:
- self.matches = self.global_matches(text)
- try:
- return self.matches[state]
- except IndexError:
- return None
-
- def global_matches(self, text):
- """Compute matches when text is a simple name.
-
- Return a list of all keywords, built-in functions and names currently
- defined in self.namespace or self.global_namespace that match.
-
- """
- matches = []
- match_append = matches.append
- n = len(text)
- for lst in [keyword.kwlist,
- builtin_mod.__dict__.keys(),
- self.namespace.keys(),
- self.global_namespace.keys()]:
- for word in lst:
- if word[:n] == text and word != "__builtins__":
- match_append(word)
+
+ If unspecified, the default namespace where completions are performed
+ is __main__ (technically, __main__.__dict__). Namespaces should be
+ given as dictionaries.
+
+ An optional second namespace can be given. This allows the completer
+ to handle cases where both the local and global scopes need to be
+ distinguished.
+
+ Completer instances should be used as the completion mechanism of
+ readline via the set_completer() call:
+
+ readline.set_completer(Completer(my_namespace).complete)
+ """
+
+ # Don't bind to namespace quite yet, but flag whether the user wants a
+ # specific namespace or to use __main__.__dict__. This will allow us
+ # to bind to __main__.__dict__ at completion time, not now.
+ if namespace is None:
+ self.use_main_ns = 1
+ else:
+ self.use_main_ns = 0
+ self.namespace = namespace
+
+ # The global namespace, if given, can be bound directly
+ if global_namespace is None:
+ self.global_namespace = {}
+ else:
+ self.global_namespace = global_namespace
+
+ super(Completer, self).__init__(**kwargs)
+
+ def complete(self, text, state):
+ """Return the next possible completion for 'text'.
+
+ This is called successively with state == 0, 1, 2, ... until it
+ returns None. The completion should begin with 'text'.
+
+ """
+ if self.use_main_ns:
+ self.namespace = __main__.__dict__
+
+ if state == 0:
+ if "." in text:
+ self.matches = self.attr_matches(text)
+ else:
+ self.matches = self.global_matches(text)
+ try:
+ return self.matches[state]
+ except IndexError:
+ return None
+
+ def global_matches(self, text):
+ """Compute matches when text is a simple name.
+
+ Return a list of all keywords, built-in functions and names currently
+ defined in self.namespace or self.global_namespace that match.
+
+ """
+ matches = []
+ match_append = matches.append
+ n = len(text)
+ for lst in [keyword.kwlist,
+ builtin_mod.__dict__.keys(),
+ self.namespace.keys(),
+ self.global_namespace.keys()]:
+ for word in lst:
+ if word[:n] == text and word != "__builtins__":
+ match_append(word)
return [cast_unicode_py2(m) for m in matches]
-
- def attr_matches(self, text):
- """Compute matches when text contains a dot.
-
- Assuming the text is of the form NAME.NAME....[NAME], and is
- evaluatable in self.namespace or self.global_namespace, it will be
- evaluated and its attributes (as revealed by dir()) are used as
- possible completions. (For class instances, class members are are
- also considered.)
-
- WARNING: this can still invoke arbitrary C code, if an object
- with a __getattr__ hook is evaluated.
-
- """
-
- # Another option, seems to work great. Catches things like ''.<tab>
- m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
-
- if m:
- expr, attr = m.group(1, 3)
- elif self.greedy:
- m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
- if not m2:
- return []
- expr, attr = m2.group(1,2)
+
+ def attr_matches(self, text):
+ """Compute matches when text contains a dot.
+
+ Assuming the text is of the form NAME.NAME....[NAME], and is
+ evaluatable in self.namespace or self.global_namespace, it will be
+ evaluated and its attributes (as revealed by dir()) are used as
+ possible completions. (For class instances, class members are are
+ also considered.)
+
+ WARNING: this can still invoke arbitrary C code, if an object
+ with a __getattr__ hook is evaluated.
+
+ """
+
+ # Another option, seems to work great. Catches things like ''.<tab>
+ m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
+
+ if m:
+ expr, attr = m.group(1, 3)
+ elif self.greedy:
+ m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
+ if not m2:
+ return []
+ expr, attr = m2.group(1,2)
+ else:
+ return []
+
+ try:
+ obj = eval(expr, self.namespace)
+ except:
+ try:
+ obj = eval(expr, self.global_namespace)
+ except:
+ return []
+
+ if self.limit_to__all__ and hasattr(obj, '__all__'):
+ words = get__all__entries(obj)
else:
- return []
-
- try:
- obj = eval(expr, self.namespace)
- except:
- try:
- obj = eval(expr, self.global_namespace)
- except:
- return []
-
- if self.limit_to__all__ and hasattr(obj, '__all__'):
- words = get__all__entries(obj)
- else:
- words = dir2(obj)
-
- try:
- words = generics.complete_object(obj, words)
- except TryNext:
- pass
- except Exception:
- # Silence errors from completion function
- #raise # dbg
- pass
- # Build match list to return
- n = len(attr)
+ words = dir2(obj)
+
+ try:
+ words = generics.complete_object(obj, words)
+ except TryNext:
+ pass
+ except Exception:
+ # Silence errors from completion function
+ #raise # dbg
+ pass
+ # Build match list to return
+ n = len(attr)
return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
-
-
-def get__all__entries(obj):
- """returns the strings in the __all__ attribute"""
- try:
- words = getattr(obj, '__all__')
- except:
- return []
-
+
+
+def get__all__entries(obj):
+ """returns the strings in the __all__ attribute"""
+ try:
+ words = getattr(obj, '__all__')
+ except:
+ return []
+
return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
-
-
-def match_dict_keys(keys, prefix, delims):
- """Used by dict_key_matches, matching the prefix to a list of keys"""
- if not prefix:
- return None, 0, [repr(k) for k in keys
- if isinstance(k, (string_types, bytes))]
- quote_match = re.search('["\']', prefix)
- quote = quote_match.group()
- try:
- prefix_str = eval(prefix + quote, {})
- except Exception:
- return None, 0, []
-
- pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
- token_match = re.search(pattern, prefix, re.UNICODE)
- token_start = token_match.start()
- token_prefix = token_match.group()
-
- # TODO: support bytes in Py3k
- matched = []
- for key in keys:
- try:
- if not key.startswith(prefix_str):
- continue
- except (AttributeError, TypeError, UnicodeError):
- # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
- continue
-
- # reformat remainder of key to begin with prefix
- rem = key[len(prefix_str):]
- # force repr wrapped in '
- rem_repr = repr(rem + '"')
- if rem_repr.startswith('u') and prefix[0] not in 'uU':
- # Found key is unicode, but prefix is Py2 string.
- # Therefore attempt to interpret key as string.
- try:
- rem_repr = repr(rem.encode('ascii') + '"')
- except UnicodeEncodeError:
- continue
-
- rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
- if quote == '"':
- # The entered prefix is quoted with ",
- # but the match is quoted with '.
- # A contained " hence needs escaping for comparison:
- rem_repr = rem_repr.replace('"', '\\"')
-
- # then reinsert prefix from start of token
- matched.append('%s%s' % (token_prefix, rem_repr))
- return quote, token_start, matched
-
-
-def _safe_isinstance(obj, module, class_name):
- """Checks if obj is an instance of module.class_name if loaded
- """
- return (module in sys.modules and
- isinstance(obj, getattr(__import__(module), class_name)))
-
-
-def back_unicode_name_matches(text):
- u"""Match unicode characters back to unicode name
-
- This does ☃ -> \\snowman
-
- Note that snowman is not a valid python3 combining character but will be expanded.
- Though it will not recombine back to the snowman character by the completion machinery.
-
- This will not either back-complete standard sequences like \\n, \\b ...
-
- Used on Python 3 only.
- """
- if len(text)<2:
- return u'', ()
- maybe_slash = text[-2]
- if maybe_slash != '\\':
- return u'', ()
-
- char = text[-1]
- # no expand on quote for completion in strings.
- # nor backcomplete standard ascii keys
- if char in string.ascii_letters or char in ['"',"'"]:
- return u'', ()
- try :
- unic = unicodedata.name(char)
- return '\\'+char,['\\'+unic]
+
+
+def match_dict_keys(keys, prefix, delims):
+ """Used by dict_key_matches, matching the prefix to a list of keys"""
+ if not prefix:
+ return None, 0, [repr(k) for k in keys
+ if isinstance(k, (string_types, bytes))]
+ quote_match = re.search('["\']', prefix)
+ quote = quote_match.group()
+ try:
+ prefix_str = eval(prefix + quote, {})
+ except Exception:
+ return None, 0, []
+
+ pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
+ token_match = re.search(pattern, prefix, re.UNICODE)
+ token_start = token_match.start()
+ token_prefix = token_match.group()
+
+ # TODO: support bytes in Py3k
+ matched = []
+ for key in keys:
+ try:
+ if not key.startswith(prefix_str):
+ continue
+ except (AttributeError, TypeError, UnicodeError):
+ # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
+ continue
+
+ # reformat remainder of key to begin with prefix
+ rem = key[len(prefix_str):]
+ # force repr wrapped in '
+ rem_repr = repr(rem + '"')
+ if rem_repr.startswith('u') and prefix[0] not in 'uU':
+ # Found key is unicode, but prefix is Py2 string.
+ # Therefore attempt to interpret key as string.
+ try:
+ rem_repr = repr(rem.encode('ascii') + '"')
+ except UnicodeEncodeError:
+ continue
+
+ rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
+ if quote == '"':
+ # The entered prefix is quoted with ",
+ # but the match is quoted with '.
+ # A contained " hence needs escaping for comparison:
+ rem_repr = rem_repr.replace('"', '\\"')
+
+ # then reinsert prefix from start of token
+ matched.append('%s%s' % (token_prefix, rem_repr))
+ return quote, token_start, matched
+
+
+def _safe_isinstance(obj, module, class_name):
+ """Checks if obj is an instance of module.class_name if loaded
+ """
+ return (module in sys.modules and
+ isinstance(obj, getattr(__import__(module), class_name)))
+
+
+def back_unicode_name_matches(text):
+ u"""Match unicode characters back to unicode name
+
+ This does ☃ -> \\snowman
+
+ Note that snowman is not a valid python3 combining character but will be expanded.
+ Though it will not recombine back to the snowman character by the completion machinery.
+
+ This will not either back-complete standard sequences like \\n, \\b ...
+
+ Used on Python 3 only.
+ """
+ if len(text)<2:
+ return u'', ()
+ maybe_slash = text[-2]
+ if maybe_slash != '\\':
+ return u'', ()
+
+ char = text[-1]
+ # no expand on quote for completion in strings.
+ # nor backcomplete standard ascii keys
+ if char in string.ascii_letters or char in ['"',"'"]:
+ return u'', ()
+ try :
+ unic = unicodedata.name(char)
+ return '\\'+char,['\\'+unic]
except KeyError:
- pass
- return u'', ()
-
-def back_latex_name_matches(text):
- u"""Match latex characters back to unicode name
-
- This does ->\\sqrt
-
- Used on Python 3 only.
- """
- if len(text)<2:
- return u'', ()
- maybe_slash = text[-2]
- if maybe_slash != '\\':
- return u'', ()
-
-
- char = text[-1]
- # no expand on quote for completion in strings.
- # nor backcomplete standard ascii keys
- if char in string.ascii_letters or char in ['"',"'"]:
- return u'', ()
- try :
- latex = reverse_latex_symbol[char]
- # '\\' replace the \ as well
- return '\\'+char,[latex]
+ pass
+ return u'', ()
+
+def back_latex_name_matches(text):
+ u"""Match latex characters back to unicode name
+
+ This does ->\\sqrt
+
+ Used on Python 3 only.
+ """
+ if len(text)<2:
+ return u'', ()
+ maybe_slash = text[-2]
+ if maybe_slash != '\\':
+ return u'', ()
+
+
+ char = text[-1]
+ # no expand on quote for completion in strings.
+ # nor backcomplete standard ascii keys
+ if char in string.ascii_letters or char in ['"',"'"]:
+ return u'', ()
+ try :
+ latex = reverse_latex_symbol[char]
+ # '\\' replace the \ as well
+ return '\\'+char,[latex]
except KeyError:
- pass
- return u'', ()
-
-
-class IPCompleter(Completer):
- """Extension of the completer class with IPython-specific features"""
+ pass
+ return u'', ()
+
+
+class IPCompleter(Completer):
+ """Extension of the completer class with IPython-specific features"""
@observe('greedy')
def _greedy_changed(self, change):
- """update the splitter and readline delims when greedy is changed"""
+ """update the splitter and readline delims when greedy is changed"""
if change['new']:
- self.splitter.delims = GREEDY_DELIMS
- else:
- self.splitter.delims = DELIMS
-
- if self.readline:
- self.readline.set_completer_delims(self.splitter.delims)
-
+ self.splitter.delims = GREEDY_DELIMS
+ else:
+ self.splitter.delims = DELIMS
+
+ if self.readline:
+ self.readline.set_completer_delims(self.splitter.delims)
+
merge_completions = Bool(True,
- help="""Whether to merge completion results into a single list
-
- If False, only the completion results from the first non-empty
- completer will be returned.
- """
+ help="""Whether to merge completion results into a single list
+
+ If False, only the completion results from the first non-empty
+ completer will be returned.
+ """
).tag(config=True)
omit__names = Enum((0,1,2), default_value=2,
- help="""Instruct the completer to omit private method names
-
- Specifically, when completing on ``object.<tab>``.
-
- When 2 [default]: all names that start with '_' will be excluded.
-
- When 1: all 'magic' names (``__foo__``) will be excluded.
-
- When 0: nothing will be excluded.
- """
+ help="""Instruct the completer to omit private method names
+
+ Specifically, when completing on ``object.<tab>``.
+
+ When 2 [default]: all names that start with '_' will be excluded.
+
+ When 1: all 'magic' names (``__foo__``) will be excluded.
+
+ When 0: nothing will be excluded.
+ """
).tag(config=True)
limit_to__all__ = Bool(False,
help="""
DEPRECATED as of version 5.0.
-
+
Instruct the completer to use __all__ for the completion
- Specifically, when completing on ``object.<tab>``.
-
- When True: only those names in obj.__all__ will be included.
-
- When False [default]: the __all__ attribute is ignored
+ Specifically, when completing on ``object.<tab>``.
+
+ When True: only those names in obj.__all__ will be included.
+
+ When False [default]: the __all__ attribute is ignored
""",
).tag(config=True)
-
+
@observe('limit_to__all__')
def _limit_to_all_changed(self, change):
warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
@@ -556,352 +556,352 @@ class IPCompleter(Completer):
'no effects and then removed in future version of IPython.',
UserWarning)
- def __init__(self, shell=None, namespace=None, global_namespace=None,
- use_readline=True, config=None, **kwargs):
- """IPCompleter() -> completer
-
- Return a completer object suitable for use by the readline library
- via readline.set_completer().
-
- Inputs:
-
- - shell: a pointer to the ipython shell itself. This is needed
- because this completer knows about magic functions, and those can
- only be accessed via the ipython instance.
-
- - namespace: an optional dict where completions are performed.
-
- - global_namespace: secondary optional dict for completions, to
- handle cases (such as IPython embedded inside functions) where
- both Python scopes are visible.
-
- use_readline : bool, optional
- If true, use the readline library. This completer can still function
- without readline, though in that case callers must provide some extra
- information on each call about the current line."""
-
- self.magic_escape = ESC_MAGIC
- self.splitter = CompletionSplitter()
-
- # Readline configuration, only used by the rlcompleter method.
- if use_readline:
- # We store the right version of readline so that later code
- import IPython.utils.rlineimpl as readline
- self.readline = readline
- else:
- self.readline = None
-
- # _greedy_changed() depends on splitter and readline being defined:
- Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
- config=config, **kwargs)
-
- # List where completion matches will be stored
- self.matches = []
- self.shell = shell
- # Regexp to split filenames with spaces in them
- self.space_name_re = re.compile(r'([^\\] )')
- # Hold a local ref. to glob.glob for speed
- self.glob = glob.glob
-
- # Determine if we are running on 'dumb' terminals, like (X)Emacs
- # buffers, to avoid completion problems.
- term = os.environ.get('TERM','xterm')
- self.dumb_terminal = term in ['dumb','emacs']
-
- # Special handling of backslashes needed in win32 platforms
- if sys.platform == "win32":
- self.clean_glob = self._clean_glob_win32
- else:
- self.clean_glob = self._clean_glob
-
- #regexp to parse docstring for function signature
- self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
- self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
- #use this if positional argument name is also needed
- #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
-
- # All active matcher routines for completion
+ def __init__(self, shell=None, namespace=None, global_namespace=None,
+ use_readline=True, config=None, **kwargs):
+ """IPCompleter() -> completer
+
+ Return a completer object suitable for use by the readline library
+ via readline.set_completer().
+
+ Inputs:
+
+ - shell: a pointer to the ipython shell itself. This is needed
+ because this completer knows about magic functions, and those can
+ only be accessed via the ipython instance.
+
+ - namespace: an optional dict where completions are performed.
+
+ - global_namespace: secondary optional dict for completions, to
+ handle cases (such as IPython embedded inside functions) where
+ both Python scopes are visible.
+
+ use_readline : bool, optional
+ If true, use the readline library. This completer can still function
+ without readline, though in that case callers must provide some extra
+ information on each call about the current line."""
+
+ self.magic_escape = ESC_MAGIC
+ self.splitter = CompletionSplitter()
+
+ # Readline configuration, only used by the rlcompleter method.
+ if use_readline:
+ # We store the right version of readline so that later code
+ import IPython.utils.rlineimpl as readline
+ self.readline = readline
+ else:
+ self.readline = None
+
+ # _greedy_changed() depends on splitter and readline being defined:
+ Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
+ config=config, **kwargs)
+
+ # List where completion matches will be stored
+ self.matches = []
+ self.shell = shell
+ # Regexp to split filenames with spaces in them
+ self.space_name_re = re.compile(r'([^\\] )')
+ # Hold a local ref. to glob.glob for speed
+ self.glob = glob.glob
+
+ # Determine if we are running on 'dumb' terminals, like (X)Emacs
+ # buffers, to avoid completion problems.
+ term = os.environ.get('TERM','xterm')
+ self.dumb_terminal = term in ['dumb','emacs']
+
+ # Special handling of backslashes needed in win32 platforms
+ if sys.platform == "win32":
+ self.clean_glob = self._clean_glob_win32
+ else:
+ self.clean_glob = self._clean_glob
+
+ #regexp to parse docstring for function signature
+ self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
+ self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
+ #use this if positional argument name is also needed
+ #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
+
+ # All active matcher routines for completion
self.matchers = [
self.python_matches,
- self.file_matches,
- self.magic_matches,
- self.python_func_kw_matches,
- self.dict_key_matches,
- ]
-
+ self.file_matches,
+ self.magic_matches,
+ self.python_func_kw_matches,
+ self.dict_key_matches,
+ ]
+
# This is set externally by InteractiveShell
self.custom_completers = None
- def all_completions(self, text):
- """
+ def all_completions(self, text):
+ """
Wrapper around the complete method for the benefit of emacs.
- """
- return self.complete(text)[1]
-
+ """
+ return self.complete(text)[1]
+
def _clean_glob(self, text):
- return self.glob("%s*" % text)
-
- def _clean_glob_win32(self,text):
- return [f.replace("\\","/")
- for f in self.glob("%s*" % text)]
-
- def file_matches(self, text):
- """Match filenames, expanding ~USER type strings.
-
- Most of the seemingly convoluted logic in this completer is an
- attempt to handle filenames with spaces in them. And yet it's not
- quite perfect, because Python's readline doesn't expose all of the
- GNU readline details needed for this to be done correctly.
-
- For a filename with a space in it, the printed completions will be
- only the parts after what's already been typed (instead of the
- full completions, as is normally done). I don't think with the
- current (as of Python 2.3) Python readline it's possible to do
- better."""
-
- # chars that require escaping with backslash - i.e. chars
- # that readline treats incorrectly as delimiters, but we
- # don't want to treat as delimiters in filename matching
- # when escaped with backslash
- if text.startswith('!'):
- text = text[1:]
+ return self.glob("%s*" % text)
+
+ def _clean_glob_win32(self,text):
+ return [f.replace("\\","/")
+ for f in self.glob("%s*" % text)]
+
+ def file_matches(self, text):
+ """Match filenames, expanding ~USER type strings.
+
+ Most of the seemingly convoluted logic in this completer is an
+ attempt to handle filenames with spaces in them. And yet it's not
+ quite perfect, because Python's readline doesn't expose all of the
+ GNU readline details needed for this to be done correctly.
+
+ For a filename with a space in it, the printed completions will be
+ only the parts after what's already been typed (instead of the
+ full completions, as is normally done). I don't think with the
+ current (as of Python 2.3) Python readline it's possible to do
+ better."""
+
+ # chars that require escaping with backslash - i.e. chars
+ # that readline treats incorrectly as delimiters, but we
+ # don't want to treat as delimiters in filename matching
+ # when escaped with backslash
+ if text.startswith('!'):
+ text = text[1:]
text_prefix = u'!'
- else:
+ else:
text_prefix = u''
-
- text_until_cursor = self.text_until_cursor
- # track strings with open quotes
- open_quotes = has_open_quotes(text_until_cursor)
-
- if '(' in text_until_cursor or '[' in text_until_cursor:
- lsplit = text
- else:
- try:
- # arg_split ~ shlex.split, but with unicode bugs fixed by us
- lsplit = arg_split(text_until_cursor)[-1]
- except ValueError:
- # typically an unmatched ", or backslash without escaped char.
- if open_quotes:
- lsplit = text_until_cursor.split(open_quotes)[-1]
- else:
- return []
- except IndexError:
- # tab pressed on empty line
- lsplit = ""
-
- if not open_quotes and lsplit != protect_filename(lsplit):
- # if protectables are found, do matching on the whole escaped name
- has_protectables = True
- text0,text = text,lsplit
- else:
- has_protectables = False
- text = os.path.expanduser(text)
-
- if text == "":
+
+ text_until_cursor = self.text_until_cursor
+ # track strings with open quotes
+ open_quotes = has_open_quotes(text_until_cursor)
+
+ if '(' in text_until_cursor or '[' in text_until_cursor:
+ lsplit = text
+ else:
+ try:
+ # arg_split ~ shlex.split, but with unicode bugs fixed by us
+ lsplit = arg_split(text_until_cursor)[-1]
+ except ValueError:
+ # typically an unmatched ", or backslash without escaped char.
+ if open_quotes:
+ lsplit = text_until_cursor.split(open_quotes)[-1]
+ else:
+ return []
+ except IndexError:
+ # tab pressed on empty line
+ lsplit = ""
+
+ if not open_quotes and lsplit != protect_filename(lsplit):
+ # if protectables are found, do matching on the whole escaped name
+ has_protectables = True
+ text0,text = text,lsplit
+ else:
+ has_protectables = False
+ text = os.path.expanduser(text)
+
+ if text == "":
return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
-
- # Compute the matches from the filesystem
+
+ # Compute the matches from the filesystem
if sys.platform == 'win32':
m0 = self.clean_glob(text)
else:
m0 = self.clean_glob(text.replace('\\', ''))
-
- if has_protectables:
- # If we had protectables, we need to revert our changes to the
- # beginning of filename so that we don't double-write the part
- # of the filename we have so far
- len_lsplit = len(lsplit)
- matches = [text_prefix + text0 +
- protect_filename(f[len_lsplit:]) for f in m0]
- else:
- if open_quotes:
- # if we have a string with an open quote, we don't need to
- # protect the names at all (and we _shouldn't_, as it
- # would cause bugs when the filesystem call is made).
- matches = m0
- else:
- matches = [text_prefix +
- protect_filename(f) for f in m0]
-
- # Mark directories in input list by appending '/' to their names.
+
+ if has_protectables:
+ # If we had protectables, we need to revert our changes to the
+ # beginning of filename so that we don't double-write the part
+ # of the filename we have so far
+ len_lsplit = len(lsplit)
+ matches = [text_prefix + text0 +
+ protect_filename(f[len_lsplit:]) for f in m0]
+ else:
+ if open_quotes:
+ # if we have a string with an open quote, we don't need to
+ # protect the names at all (and we _shouldn't_, as it
+ # would cause bugs when the filesystem call is made).
+ matches = m0
+ else:
+ matches = [text_prefix +
+ protect_filename(f) for f in m0]
+
+ # Mark directories in input list by appending '/' to their names.
return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
-
- def magic_matches(self, text):
- """Match magics"""
- # Get all shell magics now rather than statically, so magics loaded at
- # runtime show up too.
- lsm = self.shell.magics_manager.lsmagic()
- line_magics = lsm['line']
- cell_magics = lsm['cell']
- pre = self.magic_escape
- pre2 = pre+pre
-
- # Completion logic:
- # - user gives %%: only do cell magics
- # - user gives %: do both line and cell magics
- # - no prefix: do both
- # In other words, line magics are skipped if the user gives %% explicitly
- bare_text = text.lstrip(pre)
- comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
- if not text.startswith(pre2):
- comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
+
+ def magic_matches(self, text):
+ """Match magics"""
+ # Get all shell magics now rather than statically, so magics loaded at
+ # runtime show up too.
+ lsm = self.shell.magics_manager.lsmagic()
+ line_magics = lsm['line']
+ cell_magics = lsm['cell']
+ pre = self.magic_escape
+ pre2 = pre+pre
+
+ # Completion logic:
+ # - user gives %%: only do cell magics
+ # - user gives %: do both line and cell magics
+ # - no prefix: do both
+ # In other words, line magics are skipped if the user gives %% explicitly
+ bare_text = text.lstrip(pre)
+ comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
+ if not text.startswith(pre2):
+ comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
return [cast_unicode_py2(c) for c in comp]
-
+
def python_matches(self, text):
- """Match attributes or global python names"""
- if "." in text:
- try:
- matches = self.attr_matches(text)
- if text.endswith('.') and self.omit__names:
- if self.omit__names == 1:
- # true if txt is _not_ a __ name, false otherwise:
- no__name = (lambda txt:
- re.match(r'.*\.__.*?__',txt) is None)
- else:
- # true if txt is _not_ a _ name, false otherwise:
- no__name = (lambda txt:
- re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
- matches = filter(no__name, matches)
- except NameError:
- # catches <undefined attributes>.<tab>
- matches = []
- else:
- matches = self.global_matches(text)
- return matches
-
- def _default_arguments_from_docstring(self, doc):
- """Parse the first line of docstring for call signature.
-
- Docstring should be of the form 'min(iterable[, key=func])\n'.
- It can also parse cython docstring of the form
- 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
- """
- if doc is None:
- return []
-
- #care only the firstline
- line = doc.lstrip().splitlines()[0]
-
- #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
- #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
- sig = self.docstring_sig_re.search(line)
- if sig is None:
- return []
- # iterable[, key=func]' -> ['iterable[' ,' key=func]']
- sig = sig.groups()[0].split(',')
- ret = []
- for s in sig:
- #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
- ret += self.docstring_kwd_re.findall(s)
- return ret
-
- def _default_arguments(self, obj):
- """Return the list of default arguments of obj if it is callable,
- or empty list otherwise."""
- call_obj = obj
- ret = []
- if inspect.isbuiltin(obj):
- pass
- elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
- if inspect.isclass(obj):
- #for cython embededsignature=True the constructor docstring
- #belongs to the object itself not __init__
- ret += self._default_arguments_from_docstring(
- getattr(obj, '__doc__', ''))
- # for classes, check for __init__,__new__
- call_obj = (getattr(obj, '__init__', None) or
- getattr(obj, '__new__', None))
- # for all others, check if they are __call__able
- elif hasattr(obj, '__call__'):
- call_obj = obj.__call__
- ret += self._default_arguments_from_docstring(
- getattr(call_obj, '__doc__', ''))
-
- if PY3:
- _keeps = (inspect.Parameter.KEYWORD_ONLY,
- inspect.Parameter.POSITIONAL_OR_KEYWORD)
- signature = inspect.signature
- else:
- import IPython.utils.signatures
- _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
- IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
- signature = IPython.utils.signatures.signature
-
- try:
- sig = signature(call_obj)
- ret.extend(k for k, v in sig.parameters.items() if
- v.kind in _keeps)
- except ValueError:
- pass
-
- return list(set(ret))
-
- def python_func_kw_matches(self,text):
- """Match named parameters (kwargs) of the last open function"""
-
- if "." in text: # a parameter cannot be dotted
- return []
- try: regexp = self.__funcParamsRegex
- except AttributeError:
- regexp = self.__funcParamsRegex = re.compile(r'''
- '.*?(?<!\\)' | # single quoted strings or
- ".*?(?<!\\)" | # double quoted strings or
- \w+ | # identifier
- \S # other characters
- ''', re.VERBOSE | re.DOTALL)
- # 1. find the nearest identifier that comes before an unclosed
- # parenthesis before the cursor
- # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
- tokens = regexp.findall(self.text_until_cursor)
- tokens.reverse()
- iterTokens = iter(tokens); openPar = 0
-
- for token in iterTokens:
- if token == ')':
- openPar -= 1
- elif token == '(':
- openPar += 1
- if openPar > 0:
- # found the last unclosed parenthesis
- break
- else:
- return []
- # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
- ids = []
- isId = re.compile(r'\w+$').match
-
- while True:
- try:
- ids.append(next(iterTokens))
- if not isId(ids[-1]):
- ids.pop(); break
- if not next(iterTokens) == '.':
- break
- except StopIteration:
- break
- # lookup the candidate callable matches either using global_matches
- # or attr_matches for dotted names
- if len(ids) == 1:
- callableMatches = self.global_matches(ids[0])
- else:
- callableMatches = self.attr_matches('.'.join(ids[::-1]))
- argMatches = []
- for callableMatch in callableMatches:
- try:
- namedArgs = self._default_arguments(eval(callableMatch,
- self.namespace))
- except:
- continue
-
- for namedArg in namedArgs:
- if namedArg.startswith(text):
+ """Match attributes or global python names"""
+ if "." in text:
+ try:
+ matches = self.attr_matches(text)
+ if text.endswith('.') and self.omit__names:
+ if self.omit__names == 1:
+ # true if txt is _not_ a __ name, false otherwise:
+ no__name = (lambda txt:
+ re.match(r'.*\.__.*?__',txt) is None)
+ else:
+ # true if txt is _not_ a _ name, false otherwise:
+ no__name = (lambda txt:
+ re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
+ matches = filter(no__name, matches)
+ except NameError:
+ # catches <undefined attributes>.<tab>
+ matches = []
+ else:
+ matches = self.global_matches(text)
+ return matches
+
+ def _default_arguments_from_docstring(self, doc):
+ """Parse the first line of docstring for call signature.
+
+ Docstring should be of the form 'min(iterable[, key=func])\n'.
+ It can also parse cython docstring of the form
+ 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
+ """
+ if doc is None:
+ return []
+
+ #care only the firstline
+ line = doc.lstrip().splitlines()[0]
+
+ #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
+ #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
+ sig = self.docstring_sig_re.search(line)
+ if sig is None:
+ return []
+ # iterable[, key=func]' -> ['iterable[' ,' key=func]']
+ sig = sig.groups()[0].split(',')
+ ret = []
+ for s in sig:
+ #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
+ ret += self.docstring_kwd_re.findall(s)
+ return ret
+
+ def _default_arguments(self, obj):
+ """Return the list of default arguments of obj if it is callable,
+ or empty list otherwise."""
+ call_obj = obj
+ ret = []
+ if inspect.isbuiltin(obj):
+ pass
+ elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
+ if inspect.isclass(obj):
+ #for cython embededsignature=True the constructor docstring
+ #belongs to the object itself not __init__
+ ret += self._default_arguments_from_docstring(
+ getattr(obj, '__doc__', ''))
+ # for classes, check for __init__,__new__
+ call_obj = (getattr(obj, '__init__', None) or
+ getattr(obj, '__new__', None))
+ # for all others, check if they are __call__able
+ elif hasattr(obj, '__call__'):
+ call_obj = obj.__call__
+ ret += self._default_arguments_from_docstring(
+ getattr(call_obj, '__doc__', ''))
+
+ if PY3:
+ _keeps = (inspect.Parameter.KEYWORD_ONLY,
+ inspect.Parameter.POSITIONAL_OR_KEYWORD)
+ signature = inspect.signature
+ else:
+ import IPython.utils.signatures
+ _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
+ IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
+ signature = IPython.utils.signatures.signature
+
+ try:
+ sig = signature(call_obj)
+ ret.extend(k for k, v in sig.parameters.items() if
+ v.kind in _keeps)
+ except ValueError:
+ pass
+
+ return list(set(ret))
+
+ def python_func_kw_matches(self,text):
+ """Match named parameters (kwargs) of the last open function"""
+
+ if "." in text: # a parameter cannot be dotted
+ return []
+ try: regexp = self.__funcParamsRegex
+ except AttributeError:
+ regexp = self.__funcParamsRegex = re.compile(r'''
+ '.*?(?<!\\)' | # single quoted strings or
+ ".*?(?<!\\)" | # double quoted strings or
+ \w+ | # identifier
+ \S # other characters
+ ''', re.VERBOSE | re.DOTALL)
+ # 1. find the nearest identifier that comes before an unclosed
+ # parenthesis before the cursor
+ # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
+ tokens = regexp.findall(self.text_until_cursor)
+ tokens.reverse()
+ iterTokens = iter(tokens); openPar = 0
+
+ for token in iterTokens:
+ if token == ')':
+ openPar -= 1
+ elif token == '(':
+ openPar += 1
+ if openPar > 0:
+ # found the last unclosed parenthesis
+ break
+ else:
+ return []
+ # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
+ ids = []
+ isId = re.compile(r'\w+$').match
+
+ while True:
+ try:
+ ids.append(next(iterTokens))
+ if not isId(ids[-1]):
+ ids.pop(); break
+ if not next(iterTokens) == '.':
+ break
+ except StopIteration:
+ break
+ # lookup the candidate callable matches either using global_matches
+ # or attr_matches for dotted names
+ if len(ids) == 1:
+ callableMatches = self.global_matches(ids[0])
+ else:
+ callableMatches = self.attr_matches('.'.join(ids[::-1]))
+ argMatches = []
+ for callableMatch in callableMatches:
+ try:
+ namedArgs = self._default_arguments(eval(callableMatch,
+ self.namespace))
+ except:
+ continue
+
+ for namedArg in namedArgs:
+ if namedArg.startswith(text):
argMatches.append(u"%s=" %namedArg)
- return argMatches
-
- def dict_key_matches(self, text):
- "Match string keys in a dictionary, after e.g. 'foo[' "
- def get_keys(obj):
+ return argMatches
+
+ def dict_key_matches(self, text):
+ "Match string keys in a dictionary, after e.g. 'foo[' "
+ def get_keys(obj):
# Objects can define their own completions by defining an
# _ipy_key_completions_() method.
method = get_real_method(obj, '_ipython_key_completions_')
@@ -909,289 +909,289 @@ class IPCompleter(Completer):
return method()
# Special case some common in-memory dict-like types
- if isinstance(obj, dict) or\
- _safe_isinstance(obj, 'pandas', 'DataFrame'):
- try:
- return list(obj.keys())
- except Exception:
- return []
- elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
- _safe_isinstance(obj, 'numpy', 'void'):
- return obj.dtype.names or []
- return []
-
- try:
- regexps = self.__dict_key_regexps
- except AttributeError:
- dict_key_re_fmt = r'''(?x)
- ( # match dict-referring expression wrt greedy setting
- %s
- )
- \[ # open bracket
- \s* # and optional whitespace
- ([uUbB]? # string prefix (r not handled)
- (?: # unclosed string
- '(?:[^']|(?<!\\)\\')*
- |
- "(?:[^"]|(?<!\\)\\")*
- )
- )?
- $
- '''
- regexps = self.__dict_key_regexps = {
- False: re.compile(dict_key_re_fmt % '''
- # identifiers separated by .
- (?!\d)\w+
- (?:\.(?!\d)\w+)*
- '''),
- True: re.compile(dict_key_re_fmt % '''
- .+
- ''')
- }
-
- match = regexps[self.greedy].search(self.text_until_cursor)
- if match is None:
- return []
-
- expr, prefix = match.groups()
- try:
- obj = eval(expr, self.namespace)
- except Exception:
- try:
- obj = eval(expr, self.global_namespace)
- except Exception:
- return []
-
- keys = get_keys(obj)
- if not keys:
- return keys
- closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
- if not matches:
- return matches
-
- # get the cursor position of
- # - the text being completed
- # - the start of the key text
- # - the start of the completion
- text_start = len(self.text_until_cursor) - len(text)
- if prefix:
- key_start = match.start(2)
- completion_start = key_start + token_offset
- else:
- key_start = completion_start = match.end()
-
- # grab the leading prefix, to make sure all completions start with `text`
- if text_start > key_start:
- leading = ''
- else:
- leading = text[text_start:completion_start]
-
- # the index of the `[` character
- bracket_idx = match.end(1)
-
- # append closing quote and bracket as appropriate
- # this is *not* appropriate if the opening quote or bracket is outside
- # the text given to this method
- suf = ''
- continuation = self.line_buffer[len(self.text_until_cursor):]
- if key_start > text_start and closing_quote:
- # quotes were opened inside text, maybe close them
- if continuation.startswith(closing_quote):
- continuation = continuation[len(closing_quote):]
- else:
- suf += closing_quote
- if bracket_idx > text_start:
- # brackets were opened inside text, maybe close them
- if not continuation.startswith(']'):
- suf += ']'
-
- return [leading + k + suf for k in matches]
-
- def unicode_name_matches(self, text):
- u"""Match Latex-like syntax for unicode characters base
- on the name of the character.
-
- This does \\GREEK SMALL LETTER ETA -> η
-
- Works only on valid python 3 identifier, or on combining characters that
- will combine to form a valid identifier.
-
- Used on Python 3 only.
- """
- slashpos = text.rfind('\\')
- if slashpos > -1:
- s = text[slashpos+1:]
- try :
- unic = unicodedata.lookup(s)
- # allow combining chars
- if ('a'+unic).isidentifier():
- return '\\'+s,[unic]
+ if isinstance(obj, dict) or\
+ _safe_isinstance(obj, 'pandas', 'DataFrame'):
+ try:
+ return list(obj.keys())
+ except Exception:
+ return []
+ elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
+ _safe_isinstance(obj, 'numpy', 'void'):
+ return obj.dtype.names or []
+ return []
+
+ try:
+ regexps = self.__dict_key_regexps
+ except AttributeError:
+ dict_key_re_fmt = r'''(?x)
+ ( # match dict-referring expression wrt greedy setting
+ %s
+ )
+ \[ # open bracket
+ \s* # and optional whitespace
+ ([uUbB]? # string prefix (r not handled)
+ (?: # unclosed string
+ '(?:[^']|(?<!\\)\\')*
+ |
+ "(?:[^"]|(?<!\\)\\")*
+ )
+ )?
+ $
+ '''
+ regexps = self.__dict_key_regexps = {
+ False: re.compile(dict_key_re_fmt % '''
+ # identifiers separated by .
+ (?!\d)\w+
+ (?:\.(?!\d)\w+)*
+ '''),
+ True: re.compile(dict_key_re_fmt % '''
+ .+
+ ''')
+ }
+
+ match = regexps[self.greedy].search(self.text_until_cursor)
+ if match is None:
+ return []
+
+ expr, prefix = match.groups()
+ try:
+ obj = eval(expr, self.namespace)
+ except Exception:
+ try:
+ obj = eval(expr, self.global_namespace)
+ except Exception:
+ return []
+
+ keys = get_keys(obj)
+ if not keys:
+ return keys
+ closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
+ if not matches:
+ return matches
+
+ # get the cursor position of
+ # - the text being completed
+ # - the start of the key text
+ # - the start of the completion
+ text_start = len(self.text_until_cursor) - len(text)
+ if prefix:
+ key_start = match.start(2)
+ completion_start = key_start + token_offset
+ else:
+ key_start = completion_start = match.end()
+
+ # grab the leading prefix, to make sure all completions start with `text`
+ if text_start > key_start:
+ leading = ''
+ else:
+ leading = text[text_start:completion_start]
+
+ # the index of the `[` character
+ bracket_idx = match.end(1)
+
+ # append closing quote and bracket as appropriate
+ # this is *not* appropriate if the opening quote or bracket is outside
+ # the text given to this method
+ suf = ''
+ continuation = self.line_buffer[len(self.text_until_cursor):]
+ if key_start > text_start and closing_quote:
+ # quotes were opened inside text, maybe close them
+ if continuation.startswith(closing_quote):
+ continuation = continuation[len(closing_quote):]
+ else:
+ suf += closing_quote
+ if bracket_idx > text_start:
+ # brackets were opened inside text, maybe close them
+ if not continuation.startswith(']'):
+ suf += ']'
+
+ return [leading + k + suf for k in matches]
+
+ def unicode_name_matches(self, text):
+ u"""Match Latex-like syntax for unicode characters base
+ on the name of the character.
+
+ This does \\GREEK SMALL LETTER ETA -> η
+
+ Works only on valid python 3 identifier, or on combining characters that
+ will combine to form a valid identifier.
+
+ Used on Python 3 only.
+ """
+ slashpos = text.rfind('\\')
+ if slashpos > -1:
+ s = text[slashpos+1:]
+ try :
+ unic = unicodedata.lookup(s)
+ # allow combining chars
+ if ('a'+unic).isidentifier():
+ return '\\'+s,[unic]
except KeyError:
- pass
- return u'', []
-
-
-
-
- def latex_matches(self, text):
- u"""Match Latex syntax for unicode characters.
-
- This does both \\alp -> \\alpha and \\alpha -> α
-
- Used on Python 3 only.
- """
- slashpos = text.rfind('\\')
- if slashpos > -1:
- s = text[slashpos:]
- if s in latex_symbols:
- # Try to complete a full latex symbol to unicode
- # \\alpha -> α
- return s, [latex_symbols[s]]
- else:
- # If a user has partially typed a latex symbol, give them
- # a full list of options \al -> [\aleph, \alpha]
- matches = [k for k in latex_symbols if k.startswith(s)]
- return s, matches
- return u'', []
-
- def dispatch_custom_completer(self, text):
+ pass
+ return u'', []
+
+
+
+
+ def latex_matches(self, text):
+ u"""Match Latex syntax for unicode characters.
+
+ This does both \\alp -> \\alpha and \\alpha -> α
+
+ Used on Python 3 only.
+ """
+ slashpos = text.rfind('\\')
+ if slashpos > -1:
+ s = text[slashpos:]
+ if s in latex_symbols:
+ # Try to complete a full latex symbol to unicode
+ # \\alpha -> α
+ return s, [latex_symbols[s]]
+ else:
+ # If a user has partially typed a latex symbol, give them
+ # a full list of options \al -> [\aleph, \alpha]
+ matches = [k for k in latex_symbols if k.startswith(s)]
+ return s, matches
+ return u'', []
+
+ def dispatch_custom_completer(self, text):
if not self.custom_completers:
return
- line = self.line_buffer
- if not line.strip():
- return None
-
- # Create a little structure to pass all the relevant information about
- # the current completion to any custom completer.
- event = Bunch()
- event.line = line
- event.symbol = text
- cmd = line.split(None,1)[0]
- event.command = cmd
- event.text_until_cursor = self.text_until_cursor
-
- # for foo etc, try also to find completer for %foo
- if not cmd.startswith(self.magic_escape):
- try_magic = self.custom_completers.s_matches(
- self.magic_escape + cmd)
- else:
- try_magic = []
-
- for c in itertools.chain(self.custom_completers.s_matches(cmd),
- try_magic,
- self.custom_completers.flat_matches(self.text_until_cursor)):
- try:
- res = c(event)
- if res:
- # first, try case sensitive match
+ line = self.line_buffer
+ if not line.strip():
+ return None
+
+ # Create a little structure to pass all the relevant information about
+ # the current completion to any custom completer.
+ event = Bunch()
+ event.line = line
+ event.symbol = text
+ cmd = line.split(None,1)[0]
+ event.command = cmd
+ event.text_until_cursor = self.text_until_cursor
+
+ # for foo etc, try also to find completer for %foo
+ if not cmd.startswith(self.magic_escape):
+ try_magic = self.custom_completers.s_matches(
+ self.magic_escape + cmd)
+ else:
+ try_magic = []
+
+ for c in itertools.chain(self.custom_completers.s_matches(cmd),
+ try_magic,
+ self.custom_completers.flat_matches(self.text_until_cursor)):
+ try:
+ res = c(event)
+ if res:
+ # first, try case sensitive match
withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
- if withcase:
- return withcase
- # if none, then case insensitive ones are ok too
- text_low = text.lower()
+ if withcase:
+ return withcase
+ # if none, then case insensitive ones are ok too
+ text_low = text.lower()
return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
- except TryNext:
- pass
+ except TryNext:
+ pass
except KeyboardInterrupt:
"""
If custom completer take too long,
let keyboard interrupt abort and return nothing.
"""
break
-
- return None
-
- def complete(self, text=None, line_buffer=None, cursor_pos=None):
- """Find completions for the given text and line context.
-
- Note that both the text and the line_buffer are optional, but at least
- one of them must be given.
-
- Parameters
- ----------
- text : string, optional
- Text to perform the completion on. If not given, the line buffer
- is split using the instance's CompletionSplitter object.
-
- line_buffer : string, optional
- If not given, the completer attempts to obtain the current line
- buffer via readline. This keyword allows clients which are
- requesting for text completions in non-readline contexts to inform
- the completer of the entire text.
-
- cursor_pos : int, optional
- Index of the cursor in the full line buffer. Should be provided by
- remote frontends where kernel has no access to frontend state.
-
- Returns
- -------
- text : str
- Text that was actually used in the completion.
-
- matches : list
- A list of completion matches.
- """
- # if the cursor position isn't given, the only sane assumption we can
- # make is that it's at the end of the line (the common case)
- if cursor_pos is None:
- cursor_pos = len(line_buffer) if text is None else len(text)
-
+
+ return None
+
+ def complete(self, text=None, line_buffer=None, cursor_pos=None):
+ """Find completions for the given text and line context.
+
+ Note that both the text and the line_buffer are optional, but at least
+ one of them must be given.
+
+ Parameters
+ ----------
+ text : string, optional
+ Text to perform the completion on. If not given, the line buffer
+ is split using the instance's CompletionSplitter object.
+
+ line_buffer : string, optional
+ If not given, the completer attempts to obtain the current line
+ buffer via readline. This keyword allows clients which are
+ requesting for text completions in non-readline contexts to inform
+ the completer of the entire text.
+
+ cursor_pos : int, optional
+ Index of the cursor in the full line buffer. Should be provided by
+ remote frontends where kernel has no access to frontend state.
+
+ Returns
+ -------
+ text : str
+ Text that was actually used in the completion.
+
+ matches : list
+ A list of completion matches.
+ """
+ # if the cursor position isn't given, the only sane assumption we can
+ # make is that it's at the end of the line (the common case)
+ if cursor_pos is None:
+ cursor_pos = len(line_buffer) if text is None else len(text)
+
if self.use_main_ns:
self.namespace = __main__.__dict__
-
+
if PY3 and self.backslash_combining_completions:
- base_text = text if not line_buffer else line_buffer[:cursor_pos]
- latex_text, latex_matches = self.latex_matches(base_text)
- if latex_matches:
+ base_text = text if not line_buffer else line_buffer[:cursor_pos]
+ latex_text, latex_matches = self.latex_matches(base_text)
+ if latex_matches:
return latex_text, latex_matches
- name_text = ''
- name_matches = []
- for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
- name_text, name_matches = meth(base_text)
- if name_text:
+ name_text = ''
+ name_matches = []
+ for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
+ name_text, name_matches = meth(base_text)
+ if name_text:
return name_text, name_matches[:MATCHES_LIMIT]
-
- # if text is either None or an empty string, rely on the line buffer
- if not text:
- text = self.splitter.split_line(line_buffer, cursor_pos)
-
- # If no line buffer is given, assume the input text is all there was
- if line_buffer is None:
- line_buffer = text
-
- self.line_buffer = line_buffer
- self.text_until_cursor = self.line_buffer[:cursor_pos]
-
- # Start with a clean slate of completions
- self.matches[:] = []
- custom_res = self.dispatch_custom_completer(text)
- if custom_res is not None:
- # did custom completers produce something?
- self.matches = custom_res
- else:
- # Extend the list of completions with the results of each
- # matcher, so we return results to the user from all
- # namespaces.
- if self.merge_completions:
- self.matches = []
- for matcher in self.matchers:
- try:
- self.matches.extend(matcher(text))
- except:
- # Show the ugly traceback if the matcher causes an
- # exception, but do NOT crash the kernel!
- sys.excepthook(*sys.exc_info())
- else:
- for matcher in self.matchers:
- self.matches = matcher(text)
- if self.matches:
- break
- # FIXME: we should extend our api to return a dict with completions for
- # different types of objects. The rlcomplete() method could then
- # simply collapse the dict into a list for readline, but we'd have
- # richer completion semantics in other evironments.
+
+ # if text is either None or an empty string, rely on the line buffer
+ if not text:
+ text = self.splitter.split_line(line_buffer, cursor_pos)
+
+ # If no line buffer is given, assume the input text is all there was
+ if line_buffer is None:
+ line_buffer = text
+
+ self.line_buffer = line_buffer
+ self.text_until_cursor = self.line_buffer[:cursor_pos]
+
+ # Start with a clean slate of completions
+ self.matches[:] = []
+ custom_res = self.dispatch_custom_completer(text)
+ if custom_res is not None:
+ # did custom completers produce something?
+ self.matches = custom_res
+ else:
+ # Extend the list of completions with the results of each
+ # matcher, so we return results to the user from all
+ # namespaces.
+ if self.merge_completions:
+ self.matches = []
+ for matcher in self.matchers:
+ try:
+ self.matches.extend(matcher(text))
+ except:
+ # Show the ugly traceback if the matcher causes an
+ # exception, but do NOT crash the kernel!
+ sys.excepthook(*sys.exc_info())
+ else:
+ for matcher in self.matchers:
+ self.matches = matcher(text)
+ if self.matches:
+ break
+ # FIXME: we should extend our api to return a dict with completions for
+ # different types of objects. The rlcomplete() method could then
+ # simply collapse the dict into a list for readline, but we'd have
+ # richer completion semantics in other evironments.
self.matches = sorted(set(self.matches), key=completions_sorting_key)[:MATCHES_LIMIT]
-
- return text, self.matches
+
+ return text, self.matches
diff --git a/contrib/python/ipython/py2/IPython/core/completerlib.py b/contrib/python/ipython/py2/IPython/core/completerlib.py
index 4e7ae41941..e736ca73d1 100644
--- a/contrib/python/ipython/py2/IPython/core/completerlib.py
+++ b/contrib/python/ipython/py2/IPython/core/completerlib.py
@@ -1,76 +1,76 @@
-# encoding: utf-8
-"""Implementations for various useful completers.
-
-These are all loaded by default by IPython.
-"""
-#-----------------------------------------------------------------------------
-# Copyright (C) 2010-2011 The IPython Development Team.
-#
-# Distributed under the terms of the BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-from __future__ import print_function
-
-# Stdlib imports
-import glob
-import inspect
+# encoding: utf-8
+"""Implementations for various useful completers.
+
+These are all loaded by default by IPython.
+"""
+#-----------------------------------------------------------------------------
+# Copyright (C) 2010-2011 The IPython Development Team.
+#
+# Distributed under the terms of the BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+from __future__ import print_function
+
+# Stdlib imports
+import glob
+import inspect
import itertools
-import os
-import re
-import sys
-
-try:
- # Python >= 3.3
- from importlib.machinery import all_suffixes
- _suffixes = all_suffixes()
-except ImportError:
- from imp import get_suffixes
- _suffixes = [ s[0] for s in get_suffixes() ]
-
-# Third-party imports
-from time import time
-from zipimport import zipimporter
-
-# Our own imports
-from IPython.core.completer import expand_user, compress_user
-from IPython.core.error import TryNext
-from IPython.utils._process_common import arg_split
-from IPython.utils.py3compat import string_types
-
-# FIXME: this should be pulled in with the right call via the component system
-from IPython import get_ipython
-
+import os
+import re
+import sys
+
+try:
+ # Python >= 3.3
+ from importlib.machinery import all_suffixes
+ _suffixes = all_suffixes()
+except ImportError:
+ from imp import get_suffixes
+ _suffixes = [ s[0] for s in get_suffixes() ]
+
+# Third-party imports
+from time import time
+from zipimport import zipimporter
+
+# Our own imports
+from IPython.core.completer import expand_user, compress_user
+from IPython.core.error import TryNext
+from IPython.utils._process_common import arg_split
+from IPython.utils.py3compat import string_types
+
+# FIXME: this should be pulled in with the right call via the component system
+from IPython import get_ipython
+
from __res import importer
-#-----------------------------------------------------------------------------
-# Globals and constants
-#-----------------------------------------------------------------------------
-
-# Time in seconds after which the rootmodules will be stored permanently in the
-# ipython ip.db database (kept in the user's .ipython dir).
-TIMEOUT_STORAGE = 2
-
-# Time in seconds after which we give up
-TIMEOUT_GIVEUP = 20
-
-# Regular expression for the python import statement
-import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'
- r'(?P<package>[/\\]__init__)?'
- r'(?P<suffix>%s)$' %
- r'|'.join(re.escape(s) for s in _suffixes))
-
-# RE for the ipython %run command (python + ipython scripts)
-magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$')
-
-#-----------------------------------------------------------------------------
-# Local utilities
-#-----------------------------------------------------------------------------
-
+#-----------------------------------------------------------------------------
+# Globals and constants
+#-----------------------------------------------------------------------------
+
+# Time in seconds after which the rootmodules will be stored permanently in the
+# ipython ip.db database (kept in the user's .ipython dir).
+TIMEOUT_STORAGE = 2
+
+# Time in seconds after which we give up
+TIMEOUT_GIVEUP = 20
+
+# Regular expression for the python import statement
+import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'
+ r'(?P<package>[/\\]__init__)?'
+ r'(?P<suffix>%s)$' %
+ r'|'.join(re.escape(s) for s in _suffixes))
+
+# RE for the ipython %run command (python + ipython scripts)
+magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$')
+
+#-----------------------------------------------------------------------------
+# Local utilities
+#-----------------------------------------------------------------------------
+
arcadia_rootmodules_cache = None
arcadia_modules_cache = None
@@ -116,291 +116,291 @@ def arcadia_get_root_modules():
-def module_list(path):
- """
- Return the list containing the names of the modules available in the given
- folder.
- """
- # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
- if path == '':
- path = '.'
-
- # A few local constants to be used in loops below
- pjoin = os.path.join
-
- if os.path.isdir(path):
- # Build a list of all files in the directory and all files
- # in its subdirectories. For performance reasons, do not
- # recurse more than one level into subdirectories.
- files = []
- for root, dirs, nondirs in os.walk(path, followlinks=True):
- subdir = root[len(path)+1:]
- if subdir:
- files.extend(pjoin(subdir, f) for f in nondirs)
- dirs[:] = [] # Do not recurse into additional subdirectories.
- else:
- files.extend(nondirs)
-
- else:
- try:
- files = list(zipimporter(path)._files.keys())
- except:
- files = []
-
- # Build a list of modules which match the import_re regex.
- modules = []
- for f in files:
- m = import_re.match(f)
- if m:
- modules.append(m.group('name'))
- return list(set(modules))
-
-
-def get_root_modules():
- """
- Returns a list containing the names of all the modules available in the
- folders of the pythonpath.
-
- ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
- """
- ip = get_ipython()
+def module_list(path):
+ """
+ Return the list containing the names of the modules available in the given
+ folder.
+ """
+ # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
+ if path == '':
+ path = '.'
+
+ # A few local constants to be used in loops below
+ pjoin = os.path.join
+
+ if os.path.isdir(path):
+ # Build a list of all files in the directory and all files
+ # in its subdirectories. For performance reasons, do not
+ # recurse more than one level into subdirectories.
+ files = []
+ for root, dirs, nondirs in os.walk(path, followlinks=True):
+ subdir = root[len(path)+1:]
+ if subdir:
+ files.extend(pjoin(subdir, f) for f in nondirs)
+ dirs[:] = [] # Do not recurse into additional subdirectories.
+ else:
+ files.extend(nondirs)
+
+ else:
+ try:
+ files = list(zipimporter(path)._files.keys())
+ except:
+ files = []
+
+ # Build a list of modules which match the import_re regex.
+ modules = []
+ for f in files:
+ m = import_re.match(f)
+ if m:
+ modules.append(m.group('name'))
+ return list(set(modules))
+
+
+def get_root_modules():
+ """
+ Returns a list containing the names of all the modules available in the
+ folders of the pythonpath.
+
+ ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
+ """
+ ip = get_ipython()
if ip is None:
# No global shell instance to store cached list of modules.
# Don't try to scan for modules every time.
return list(sys.builtin_module_names)
- rootmodules_cache = ip.db.get('rootmodules_cache', {})
- rootmodules = list(sys.builtin_module_names)
- start_time = time()
- store = False
- for path in sys.path:
- try:
- modules = rootmodules_cache[path]
- except KeyError:
- modules = module_list(path)
- try:
- modules.remove('__init__')
- except ValueError:
- pass
- if path not in ('', '.'): # cwd modules should not be cached
- rootmodules_cache[path] = modules
- if time() - start_time > TIMEOUT_STORAGE and not store:
- store = True
- print("\nCaching the list of root modules, please wait!")
- print("(This will only be done once - type '%rehashx' to "
- "reset cache!)\n")
- sys.stdout.flush()
- if time() - start_time > TIMEOUT_GIVEUP:
- print("This is taking too long, we give up.\n")
- return []
- rootmodules.extend(modules)
- if store:
- ip.db['rootmodules_cache'] = rootmodules_cache
+ rootmodules_cache = ip.db.get('rootmodules_cache', {})
+ rootmodules = list(sys.builtin_module_names)
+ start_time = time()
+ store = False
+ for path in sys.path:
+ try:
+ modules = rootmodules_cache[path]
+ except KeyError:
+ modules = module_list(path)
+ try:
+ modules.remove('__init__')
+ except ValueError:
+ pass
+ if path not in ('', '.'): # cwd modules should not be cached
+ rootmodules_cache[path] = modules
+ if time() - start_time > TIMEOUT_STORAGE and not store:
+ store = True
+ print("\nCaching the list of root modules, please wait!")
+ print("(This will only be done once - type '%rehashx' to "
+ "reset cache!)\n")
+ sys.stdout.flush()
+ if time() - start_time > TIMEOUT_GIVEUP:
+ print("This is taking too long, we give up.\n")
+ return []
+ rootmodules.extend(modules)
+ if store:
+ ip.db['rootmodules_cache'] = rootmodules_cache
rootmodules = list(set(rootmodules))
- return rootmodules
-
-
-def is_importable(module, attr, only_modules):
- if only_modules:
- return inspect.ismodule(getattr(module, attr))
- else:
- return not(attr[:2] == '__' and attr[-2:] == '__')
-
-def try_import(mod, only_modules=False):
+ return rootmodules
+
+
+def is_importable(module, attr, only_modules):
+ if only_modules:
+ return inspect.ismodule(getattr(module, attr))
+ else:
+ return not(attr[:2] == '__' and attr[-2:] == '__')
+
+def try_import(mod, only_modules=False):
mod = mod.rstrip('.')
- try:
- m = __import__(mod)
- except:
- return []
- mods = mod.split('.')
- for module in mods[1:]:
- m = getattr(m, module)
-
+ try:
+ m = __import__(mod)
+ except:
+ return []
+ mods = mod.split('.')
+ for module in mods[1:]:
+ m = getattr(m, module)
+
filename = getattr(m, '__file__', '')
m_is_init = '__init__' in (filename or '') or filename == mod
-
- completions = []
- if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
- completions.extend( [attr for attr in dir(m) if
- is_importable(m, attr, only_modules)])
-
- completions.extend(getattr(m, '__all__', []))
- if m_is_init:
+
+ completions = []
+ if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
+ completions.extend( [attr for attr in dir(m) if
+ is_importable(m, attr, only_modules)])
+
+ completions.extend(getattr(m, '__all__', []))
+ if m_is_init:
completions.extend(arcadia_module_list(mod))
completions = {c for c in completions if isinstance(c, string_types)}
completions.discard('__init__')
return sorted(completions)
-
-
-#-----------------------------------------------------------------------------
-# Completion-related functions.
-#-----------------------------------------------------------------------------
-
-def quick_completer(cmd, completions):
- """ Easily create a trivial completer for a command.
-
- Takes either a list of completions, or all completions in string (that will
- be split on whitespace).
-
- Example::
-
- [d:\ipython]|1> import ipy_completers
- [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
- [d:\ipython]|3> foo b<TAB>
- bar baz
- [d:\ipython]|3> foo ba
- """
-
- if isinstance(completions, string_types):
- completions = completions.split()
-
- def do_complete(self, event):
- return completions
-
- get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
-
-def module_completion(line):
- """
- Returns a list containing the completion possibilities for an import line.
-
- The line looks like this :
- 'import xml.d'
- 'from xml.dom import'
- """
-
- words = line.split(' ')
- nwords = len(words)
-
- # from whatever <tab> -> 'import '
- if nwords == 3 and words[0] == 'from':
- return ['import ']
-
- # 'from xy<tab>' or 'import xy<tab>'
- if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) :
- if nwords == 1:
+
+
+#-----------------------------------------------------------------------------
+# Completion-related functions.
+#-----------------------------------------------------------------------------
+
+def quick_completer(cmd, completions):
+ """ Easily create a trivial completer for a command.
+
+ Takes either a list of completions, or all completions in string (that will
+ be split on whitespace).
+
+ Example::
+
+ [d:\ipython]|1> import ipy_completers
+ [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
+ [d:\ipython]|3> foo b<TAB>
+ bar baz
+ [d:\ipython]|3> foo ba
+ """
+
+ if isinstance(completions, string_types):
+ completions = completions.split()
+
+ def do_complete(self, event):
+ return completions
+
+ get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
+
+def module_completion(line):
+ """
+ Returns a list containing the completion possibilities for an import line.
+
+ The line looks like this :
+ 'import xml.d'
+ 'from xml.dom import'
+ """
+
+ words = line.split(' ')
+ nwords = len(words)
+
+ # from whatever <tab> -> 'import '
+ if nwords == 3 and words[0] == 'from':
+ return ['import ']
+
+ # 'from xy<tab>' or 'import xy<tab>'
+ if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) :
+ if nwords == 1:
return arcadia_get_root_modules()
- mod = words[1].split('.')
- if len(mod) < 2:
+ mod = words[1].split('.')
+ if len(mod) < 2:
return arcadia_get_root_modules()
- completion_list = try_import('.'.join(mod[:-1]), True)
- return ['.'.join(mod[:-1] + [el]) for el in completion_list]
-
- # 'from xyz import abc<tab>'
- if nwords >= 3 and words[0] == 'from':
- mod = words[1]
- return try_import(mod)
-
-#-----------------------------------------------------------------------------
-# Completers
-#-----------------------------------------------------------------------------
-# These all have the func(self, event) signature to be used as custom
-# completers
-
-def module_completer(self,event):
- """Give completions after user has typed 'import ...' or 'from ...'"""
-
- # This works in all versions of python. While 2.5 has
- # pkgutil.walk_packages(), that particular routine is fairly dangerous,
- # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
- # of possibly problematic side effects.
- # This search the folders in the sys.path for available modules.
-
- return module_completion(event.line)
-
-# FIXME: there's a lot of logic common to the run, cd and builtin file
-# completers, that is currently reimplemented in each.
-
-def magic_run_completer(self, event):
- """Complete files that end in .py or .ipy or .ipynb for the %run command.
- """
- comps = arg_split(event.line, strict=False)
- # relpath should be the current token that we need to complete.
- if (len(comps) > 1) and (not event.line.endswith(' ')):
- relpath = comps[-1].strip("'\"")
- else:
- relpath = ''
-
- #print("\nev=", event) # dbg
- #print("rp=", relpath) # dbg
- #print('comps=', comps) # dbg
-
- lglob = glob.glob
- isdir = os.path.isdir
- relpath, tilde_expand, tilde_val = expand_user(relpath)
-
- # Find if the user has already typed the first filename, after which we
- # should complete on all files, since after the first one other files may
- # be arguments to the input script.
-
- if any(magic_run_re.match(c) for c in comps):
- matches = [f.replace('\\','/') + ('/' if isdir(f) else '')
- for f in lglob(relpath+'*')]
- else:
- dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
- pys = [f.replace('\\','/')
- for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
- lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
-
- matches = dirs + pys
-
- #print('run comp:', dirs+pys) # dbg
- return [compress_user(p, tilde_expand, tilde_val) for p in matches]
-
-
-def cd_completer(self, event):
- """Completer function for cd, which only returns directories."""
- ip = get_ipython()
- relpath = event.symbol
-
- #print(event) # dbg
- if event.line.endswith('-b') or ' -b ' in event.line:
- # return only bookmark completions
- bkms = self.db.get('bookmarks', None)
- if bkms:
- return bkms.keys()
- else:
- return []
-
- if event.symbol == '-':
- width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
- # jump in directory history by number
- fmt = '-%0' + width_dh +'d [%s]'
- ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
- if len(ents) > 1:
- return ents
- return []
-
- if event.symbol.startswith('--'):
- return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
-
- # Expand ~ in path and normalize directory separators.
- relpath, tilde_expand, tilde_val = expand_user(relpath)
- relpath = relpath.replace('\\','/')
-
- found = []
- for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
- if os.path.isdir(f)]:
- if ' ' in d:
- # we don't want to deal with any of that, complex code
- # for this is elsewhere
- raise TryNext
-
- found.append(d)
-
- if not found:
- if os.path.isdir(relpath):
- return [compress_user(relpath, tilde_expand, tilde_val)]
-
- # if no completions so far, try bookmarks
- bks = self.db.get('bookmarks',{})
- bkmatches = [s for s in bks if s.startswith(event.symbol)]
- if bkmatches:
- return bkmatches
-
- raise TryNext
-
- return [compress_user(p, tilde_expand, tilde_val) for p in found]
-
-def reset_completer(self, event):
- "A completer for %reset magic"
- return '-f -s in out array dhist'.split()
+ completion_list = try_import('.'.join(mod[:-1]), True)
+ return ['.'.join(mod[:-1] + [el]) for el in completion_list]
+
+ # 'from xyz import abc<tab>'
+ if nwords >= 3 and words[0] == 'from':
+ mod = words[1]
+ return try_import(mod)
+
+#-----------------------------------------------------------------------------
+# Completers
+#-----------------------------------------------------------------------------
+# These all have the func(self, event) signature to be used as custom
+# completers
+
+def module_completer(self,event):
+ """Give completions after user has typed 'import ...' or 'from ...'"""
+
+ # This works in all versions of python. While 2.5 has
+ # pkgutil.walk_packages(), that particular routine is fairly dangerous,
+ # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
+ # of possibly problematic side effects.
+ # This search the folders in the sys.path for available modules.
+
+ return module_completion(event.line)
+
+# FIXME: there's a lot of logic common to the run, cd and builtin file
+# completers, that is currently reimplemented in each.
+
+def magic_run_completer(self, event):
+ """Complete files that end in .py or .ipy or .ipynb for the %run command.
+ """
+ comps = arg_split(event.line, strict=False)
+ # relpath should be the current token that we need to complete.
+ if (len(comps) > 1) and (not event.line.endswith(' ')):
+ relpath = comps[-1].strip("'\"")
+ else:
+ relpath = ''
+
+ #print("\nev=", event) # dbg
+ #print("rp=", relpath) # dbg
+ #print('comps=', comps) # dbg
+
+ lglob = glob.glob
+ isdir = os.path.isdir
+ relpath, tilde_expand, tilde_val = expand_user(relpath)
+
+ # Find if the user has already typed the first filename, after which we
+ # should complete on all files, since after the first one other files may
+ # be arguments to the input script.
+
+ if any(magic_run_re.match(c) for c in comps):
+ matches = [f.replace('\\','/') + ('/' if isdir(f) else '')
+ for f in lglob(relpath+'*')]
+ else:
+ dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
+ pys = [f.replace('\\','/')
+ for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
+ lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
+
+ matches = dirs + pys
+
+ #print('run comp:', dirs+pys) # dbg
+ return [compress_user(p, tilde_expand, tilde_val) for p in matches]
+
+
+def cd_completer(self, event):
+ """Completer function for cd, which only returns directories."""
+ ip = get_ipython()
+ relpath = event.symbol
+
+ #print(event) # dbg
+ if event.line.endswith('-b') or ' -b ' in event.line:
+ # return only bookmark completions
+ bkms = self.db.get('bookmarks', None)
+ if bkms:
+ return bkms.keys()
+ else:
+ return []
+
+ if event.symbol == '-':
+ width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
+ # jump in directory history by number
+ fmt = '-%0' + width_dh +'d [%s]'
+ ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
+ if len(ents) > 1:
+ return ents
+ return []
+
+ if event.symbol.startswith('--'):
+ return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
+
+ # Expand ~ in path and normalize directory separators.
+ relpath, tilde_expand, tilde_val = expand_user(relpath)
+ relpath = relpath.replace('\\','/')
+
+ found = []
+ for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
+ if os.path.isdir(f)]:
+ if ' ' in d:
+ # we don't want to deal with any of that, complex code
+ # for this is elsewhere
+ raise TryNext
+
+ found.append(d)
+
+ if not found:
+ if os.path.isdir(relpath):
+ return [compress_user(relpath, tilde_expand, tilde_val)]
+
+ # if no completions so far, try bookmarks
+ bks = self.db.get('bookmarks',{})
+ bkmatches = [s for s in bks if s.startswith(event.symbol)]
+ if bkmatches:
+ return bkmatches
+
+ raise TryNext
+
+ return [compress_user(p, tilde_expand, tilde_val) for p in found]
+
+def reset_completer(self, event):
+ "A completer for %reset magic"
+ return '-f -s in out array dhist'.split()
diff --git a/contrib/python/ipython/py2/IPython/core/crashhandler.py b/contrib/python/ipython/py2/IPython/core/crashhandler.py
index 8341a61db8..22bbd7ae81 100644
--- a/contrib/python/ipython/py2/IPython/core/crashhandler.py
+++ b/contrib/python/ipython/py2/IPython/core/crashhandler.py
@@ -1,59 +1,59 @@
-# encoding: utf-8
-"""sys.excepthook for IPython itself, leaves a detailed report on disk.
-
-Authors:
-
-* Fernando Perez
-* Brian E. Granger
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-from __future__ import print_function
-
-import os
-import sys
-import traceback
-from pprint import pformat
-
-from IPython.core import ultratb
-from IPython.core.release import author_email
-from IPython.utils.sysinfo import sys_info
-from IPython.utils.py3compat import input, getcwd
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-# Template for the user message.
-_default_message_template = """\
-Oops, {app_name} crashed. We do our best to make it stable, but...
-
-A crash report was automatically generated with the following information:
- - A verbatim copy of the crash traceback.
- - A copy of your input history during this session.
- - Data on your current {app_name} configuration.
-
-It was left in the file named:
-\t'{crash_report_fname}'
-If you can email this file to the developers, the information in it will help
-them in understanding and correcting the problem.
-
-You can mail it to: {contact_name} at {contact_email}
-with the subject '{app_name} Crash Report'.
-
-If you want to do it now, the following command will work (under Unix):
-mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
-
+# encoding: utf-8
+"""sys.excepthook for IPython itself, leaves a detailed report on disk.
+
+Authors:
+
+* Fernando Perez
+* Brian E. Granger
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+from __future__ import print_function
+
+import os
+import sys
+import traceback
+from pprint import pformat
+
+from IPython.core import ultratb
+from IPython.core.release import author_email
+from IPython.utils.sysinfo import sys_info
+from IPython.utils.py3compat import input, getcwd
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+# Template for the user message.
+_default_message_template = """\
+Oops, {app_name} crashed. We do our best to make it stable, but...
+
+A crash report was automatically generated with the following information:
+ - A verbatim copy of the crash traceback.
+ - A copy of your input history during this session.
+ - Data on your current {app_name} configuration.
+
+It was left in the file named:
+\t'{crash_report_fname}'
+If you can email this file to the developers, the information in it will help
+them in understanding and correcting the problem.
+
+You can mail it to: {contact_name} at {contact_email}
+with the subject '{app_name} Crash Report'.
+
+If you want to do it now, the following command will work (under Unix):
+mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
+
In your email, please also include information about:
- The operating system under which the crash happened: Linux, macOS, Windows,
other, and which exact version (for example: Ubuntu 16.04.3, macOS 10.13.2,
@@ -64,163 +64,163 @@ In your email, please also include information about:
input to get the same crash? Ideally, find a minimal yet complete sequence
of instructions that yields the crash.
-To ensure accurate tracking of this issue, please file a report about it at:
-{bug_tracker}
-"""
-
-_lite_message_template = """
-If you suspect this is an IPython bug, please report it at:
- https://github.com/ipython/ipython/issues
-or send an email to the mailing list at {email}
-
-You can print a more detailed traceback right now with "%tb", or use "%debug"
-to interactively debug it.
-
-Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
- {config}Application.verbose_crash=True
-"""
-
-
-class CrashHandler(object):
- """Customizable crash handlers for IPython applications.
-
- Instances of this class provide a :meth:`__call__` method which can be
- used as a ``sys.excepthook``. The :meth:`__call__` signature is::
-
- def __call__(self, etype, evalue, etb)
- """
-
- message_template = _default_message_template
- section_sep = '\n\n'+'*'*75+'\n\n'
-
- def __init__(self, app, contact_name=None, contact_email=None,
- bug_tracker=None, show_crash_traceback=True, call_pdb=False):
- """Create a new crash handler
-
- Parameters
- ----------
- app : Application
- A running :class:`Application` instance, which will be queried at
- crash time for internal information.
-
- contact_name : str
- A string with the name of the person to contact.
-
- contact_email : str
- A string with the email address of the contact.
-
- bug_tracker : str
- A string with the URL for your project's bug tracker.
-
- show_crash_traceback : bool
- If false, don't print the crash traceback on stderr, only generate
- the on-disk report
-
- Non-argument instance attributes:
-
- These instances contain some non-argument attributes which allow for
- further customization of the crash handler's behavior. Please see the
- source for further details.
- """
- self.crash_report_fname = "Crash_report_%s.txt" % app.name
- self.app = app
- self.call_pdb = call_pdb
- #self.call_pdb = True # dbg
- self.show_crash_traceback = show_crash_traceback
- self.info = dict(app_name = app.name,
- contact_name = contact_name,
- contact_email = contact_email,
- bug_tracker = bug_tracker,
- crash_report_fname = self.crash_report_fname)
-
-
- def __call__(self, etype, evalue, etb):
- """Handle an exception, call for compatible with sys.excepthook"""
-
- # do not allow the crash handler to be called twice without reinstalling it
- # this prevents unlikely errors in the crash handling from entering an
- # infinite loop.
- sys.excepthook = sys.__excepthook__
-
- # Report tracebacks shouldn't use color in general (safer for users)
- color_scheme = 'NoColor'
-
- # Use this ONLY for developer debugging (keep commented out for release)
- #color_scheme = 'Linux' # dbg
- try:
- rptdir = self.app.ipython_dir
- except:
- rptdir = getcwd()
- if rptdir is None or not os.path.isdir(rptdir):
- rptdir = getcwd()
- report_name = os.path.join(rptdir,self.crash_report_fname)
- # write the report filename into the instance dict so it can get
- # properly expanded out in the user message template
- self.crash_report_fname = report_name
- self.info['crash_report_fname'] = report_name
- TBhandler = ultratb.VerboseTB(
- color_scheme=color_scheme,
- long_header=1,
- call_pdb=self.call_pdb,
- )
- if self.call_pdb:
- TBhandler(etype,evalue,etb)
- return
- else:
- traceback = TBhandler.text(etype,evalue,etb,context=31)
-
- # print traceback to screen
- if self.show_crash_traceback:
- print(traceback, file=sys.stderr)
-
- # and generate a complete report on disk
- try:
- report = open(report_name,'w')
- except:
- print('Could not create crash report on disk.', file=sys.stderr)
- return
-
- # Inform user on stderr of what happened
- print('\n'+'*'*70+'\n', file=sys.stderr)
- print(self.message_template.format(**self.info), file=sys.stderr)
-
- # Construct report on disk
- report.write(self.make_report(traceback))
- report.close()
- input("Hit <Enter> to quit (your terminal may close):")
-
- def make_report(self,traceback):
- """Return a string containing a crash report."""
-
- sec_sep = self.section_sep
-
- report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
- rpt_add = report.append
- rpt_add(sys_info())
-
- try:
- config = pformat(self.app.config)
- rpt_add(sec_sep)
- rpt_add('Application name: %s\n\n' % self.app_name)
- rpt_add('Current user configuration structure:\n\n')
- rpt_add(config)
- except:
- pass
- rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
-
- return ''.join(report)
-
-
-def crash_handler_lite(etype, evalue, tb):
- """a light excepthook, adding a small message to the usual traceback"""
- traceback.print_exception(etype, evalue, tb)
-
- from IPython.core.interactiveshell import InteractiveShell
- if InteractiveShell.initialized():
- # we are in a Shell environment, give %magic example
- config = "%config "
- else:
- # we are not in a shell, show generic config
- config = "c."
- print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr)
-
+To ensure accurate tracking of this issue, please file a report about it at:
+{bug_tracker}
+"""
+
+_lite_message_template = """
+If you suspect this is an IPython bug, please report it at:
+ https://github.com/ipython/ipython/issues
+or send an email to the mailing list at {email}
+
+You can print a more detailed traceback right now with "%tb", or use "%debug"
+to interactively debug it.
+
+Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
+ {config}Application.verbose_crash=True
+"""
+
+
+class CrashHandler(object):
+ """Customizable crash handlers for IPython applications.
+
+ Instances of this class provide a :meth:`__call__` method which can be
+ used as a ``sys.excepthook``. The :meth:`__call__` signature is::
+
+ def __call__(self, etype, evalue, etb)
+ """
+
+ message_template = _default_message_template
+ section_sep = '\n\n'+'*'*75+'\n\n'
+
+ def __init__(self, app, contact_name=None, contact_email=None,
+ bug_tracker=None, show_crash_traceback=True, call_pdb=False):
+ """Create a new crash handler
+
+ Parameters
+ ----------
+ app : Application
+ A running :class:`Application` instance, which will be queried at
+ crash time for internal information.
+
+ contact_name : str
+ A string with the name of the person to contact.
+
+ contact_email : str
+ A string with the email address of the contact.
+
+ bug_tracker : str
+ A string with the URL for your project's bug tracker.
+
+ show_crash_traceback : bool
+ If false, don't print the crash traceback on stderr, only generate
+ the on-disk report
+
+ Non-argument instance attributes:
+
+ These instances contain some non-argument attributes which allow for
+ further customization of the crash handler's behavior. Please see the
+ source for further details.
+ """
+ self.crash_report_fname = "Crash_report_%s.txt" % app.name
+ self.app = app
+ self.call_pdb = call_pdb
+ #self.call_pdb = True # dbg
+ self.show_crash_traceback = show_crash_traceback
+ self.info = dict(app_name = app.name,
+ contact_name = contact_name,
+ contact_email = contact_email,
+ bug_tracker = bug_tracker,
+ crash_report_fname = self.crash_report_fname)
+
+
+ def __call__(self, etype, evalue, etb):
+ """Handle an exception, call for compatible with sys.excepthook"""
+
+ # do not allow the crash handler to be called twice without reinstalling it
+ # this prevents unlikely errors in the crash handling from entering an
+ # infinite loop.
+ sys.excepthook = sys.__excepthook__
+
+ # Report tracebacks shouldn't use color in general (safer for users)
+ color_scheme = 'NoColor'
+
+ # Use this ONLY for developer debugging (keep commented out for release)
+ #color_scheme = 'Linux' # dbg
+ try:
+ rptdir = self.app.ipython_dir
+ except:
+ rptdir = getcwd()
+ if rptdir is None or not os.path.isdir(rptdir):
+ rptdir = getcwd()
+ report_name = os.path.join(rptdir,self.crash_report_fname)
+ # write the report filename into the instance dict so it can get
+ # properly expanded out in the user message template
+ self.crash_report_fname = report_name
+ self.info['crash_report_fname'] = report_name
+ TBhandler = ultratb.VerboseTB(
+ color_scheme=color_scheme,
+ long_header=1,
+ call_pdb=self.call_pdb,
+ )
+ if self.call_pdb:
+ TBhandler(etype,evalue,etb)
+ return
+ else:
+ traceback = TBhandler.text(etype,evalue,etb,context=31)
+
+ # print traceback to screen
+ if self.show_crash_traceback:
+ print(traceback, file=sys.stderr)
+
+ # and generate a complete report on disk
+ try:
+ report = open(report_name,'w')
+ except:
+ print('Could not create crash report on disk.', file=sys.stderr)
+ return
+
+ # Inform user on stderr of what happened
+ print('\n'+'*'*70+'\n', file=sys.stderr)
+ print(self.message_template.format(**self.info), file=sys.stderr)
+
+ # Construct report on disk
+ report.write(self.make_report(traceback))
+ report.close()
+ input("Hit <Enter> to quit (your terminal may close):")
+
+ def make_report(self,traceback):
+ """Return a string containing a crash report."""
+
+ sec_sep = self.section_sep
+
+ report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
+ rpt_add = report.append
+ rpt_add(sys_info())
+
+ try:
+ config = pformat(self.app.config)
+ rpt_add(sec_sep)
+ rpt_add('Application name: %s\n\n' % self.app_name)
+ rpt_add('Current user configuration structure:\n\n')
+ rpt_add(config)
+ except:
+ pass
+ rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
+
+ return ''.join(report)
+
+
+def crash_handler_lite(etype, evalue, tb):
+ """a light excepthook, adding a small message to the usual traceback"""
+ traceback.print_exception(etype, evalue, tb)
+
+ from IPython.core.interactiveshell import InteractiveShell
+ if InteractiveShell.initialized():
+ # we are in a Shell environment, give %magic example
+ config = "%config "
+ else:
+ # we are not in a shell, show generic config
+ config = "c."
+ print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr)
+
diff --git a/contrib/python/ipython/py2/IPython/core/debugger.py b/contrib/python/ipython/py2/IPython/core/debugger.py
index c5a443eb5b..f08cfb1a78 100644
--- a/contrib/python/ipython/py2/IPython/core/debugger.py
+++ b/contrib/python/ipython/py2/IPython/core/debugger.py
@@ -1,53 +1,53 @@
-# -*- coding: utf-8 -*-
-"""
-Pdb debugger class.
-
-Modified from the standard pdb.Pdb class to avoid including readline, so that
-the command line completion of other programs which include this isn't
-damaged.
-
-In the future, this class will be expanded with improvements over the standard
-pdb.
-
-The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
-changes. Licensing should therefore be under the standard Python terms. For
-details on the PSF (Python Software Foundation) standard license, see:
-
+# -*- coding: utf-8 -*-
+"""
+Pdb debugger class.
+
+Modified from the standard pdb.Pdb class to avoid including readline, so that
+the command line completion of other programs which include this isn't
+damaged.
+
+In the future, this class will be expanded with improvements over the standard
+pdb.
+
+The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
+changes. Licensing should therefore be under the standard Python terms. For
+details on the PSF (Python Software Foundation) standard license, see:
+
https://docs.python.org/2/license.html
"""
-
-#*****************************************************************************
-#
-# This file is licensed under the PSF license.
-#
-# Copyright (C) 2001 Python Software Foundation, www.python.org
-# Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
-#
-#
-#*****************************************************************************
-from __future__ import print_function
-
-import bdb
-import functools
-import inspect
-import sys
+
+#*****************************************************************************
+#
+# This file is licensed under the PSF license.
+#
+# Copyright (C) 2001 Python Software Foundation, www.python.org
+# Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
+#
+#
+#*****************************************************************************
+from __future__ import print_function
+
+import bdb
+import functools
+import inspect
+import sys
import warnings
-
-from IPython import get_ipython
-from IPython.utils import PyColorize, ulinecache
+
+from IPython import get_ipython
+from IPython.utils import PyColorize, ulinecache
from IPython.utils import coloransi, py3compat
-from IPython.core.excolors import exception_colors
-from IPython.testing.skipdoctest import skip_doctest
-
+from IPython.core.excolors import exception_colors
+from IPython.testing.skipdoctest import skip_doctest
+
-prompt = 'ipdb> '
+prompt = 'ipdb> '
-#We have to check this directly from sys.argv, config struct not yet available
+#We have to check this directly from sys.argv, config struct not yet available
from pdb import Pdb as OldPdb
-
-# Allow the set_trace code to operate outside of an ipython instance, even if
-# it does so with some limitations. The rest of this support is implemented in
-# the Tracer constructor.
+
+# Allow the set_trace code to operate outside of an ipython instance, even if
+# it does so with some limitations. The rest of this support is implemented in
+# the Tracer constructor.
def make_arrow(pad):
"""generate the leading arrow in front of traceback or debugger"""
@@ -58,555 +58,555 @@ def make_arrow(pad):
return ''
-def BdbQuit_excepthook(et, ev, tb, excepthook=None):
- """Exception hook which handles `BdbQuit` exceptions.
-
- All other exceptions are processed using the `excepthook`
- parameter.
- """
+def BdbQuit_excepthook(et, ev, tb, excepthook=None):
+ """Exception hook which handles `BdbQuit` exceptions.
+
+ All other exceptions are processed using the `excepthook`
+ parameter.
+ """
warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
DeprecationWarning, stacklevel=2)
- if et==bdb.BdbQuit:
- print('Exiting Debugger.')
- elif excepthook is not None:
- excepthook(et, ev, tb)
- else:
- # Backwards compatibility. Raise deprecation warning?
- BdbQuit_excepthook.excepthook_ori(et,ev,tb)
-
-
-def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
+ if et==bdb.BdbQuit:
+ print('Exiting Debugger.')
+ elif excepthook is not None:
+ excepthook(et, ev, tb)
+ else:
+ # Backwards compatibility. Raise deprecation warning?
+ BdbQuit_excepthook.excepthook_ori(et,ev,tb)
+
+
+def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
warnings.warn(
"`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
DeprecationWarning, stacklevel=2)
- print('Exiting Debugger.')
-
-
-class Tracer(object):
+ print('Exiting Debugger.')
+
+
+class Tracer(object):
"""
DEPRECATED
-
+
Class for local debugging, similar to pdb.set_trace.
- Instances of this class, when called, behave like pdb.set_trace, but
- providing IPython's enhanced capabilities.
-
- This is implemented as a class which must be initialized in your own code
- and not as a standalone function because we need to detect at runtime
- whether IPython is already active or not. That detection is done in the
- constructor, ensuring that this code plays nicely with a running IPython,
- while functioning acceptably (though with limitations) if outside of it.
- """
-
- @skip_doctest
- def __init__(self, colors=None):
+ Instances of this class, when called, behave like pdb.set_trace, but
+ providing IPython's enhanced capabilities.
+
+ This is implemented as a class which must be initialized in your own code
+ and not as a standalone function because we need to detect at runtime
+ whether IPython is already active or not. That detection is done in the
+ constructor, ensuring that this code plays nicely with a running IPython,
+ while functioning acceptably (though with limitations) if outside of it.
+ """
+
+ @skip_doctest
+ def __init__(self, colors=None):
"""
DEPRECATED
-
+
Create a local debugger instance.
- Parameters
- ----------
-
- colors : str, optional
- The name of the color scheme to use, it must be one of IPython's
- valid color schemes. If not given, the function will default to
- the current IPython scheme when running inside IPython, and to
- 'NoColor' otherwise.
-
- Examples
- --------
- ::
-
- from IPython.core.debugger import Tracer; debug_here = Tracer()
-
- Later in your code::
-
- debug_here() # -> will open up the debugger at that point.
-
- Once the debugger activates, you can use all of its regular commands to
- step through code, set breakpoints, etc. See the pdb documentation
- from the Python standard library for usage details.
- """
+ Parameters
+ ----------
+
+ colors : str, optional
+ The name of the color scheme to use, it must be one of IPython's
+ valid color schemes. If not given, the function will default to
+ the current IPython scheme when running inside IPython, and to
+ 'NoColor' otherwise.
+
+ Examples
+ --------
+ ::
+
+ from IPython.core.debugger import Tracer; debug_here = Tracer()
+
+ Later in your code::
+
+ debug_here() # -> will open up the debugger at that point.
+
+ Once the debugger activates, you can use all of its regular commands to
+ step through code, set breakpoints, etc. See the pdb documentation
+ from the Python standard library for usage details.
+ """
warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
"`IPython.core.debugger.Pdb.set_trace()`",
DeprecationWarning, stacklevel=2)
-
- ip = get_ipython()
- if ip is None:
- # Outside of ipython, we set our own exception hook manually
- sys.excepthook = functools.partial(BdbQuit_excepthook,
- excepthook=sys.excepthook)
- def_colors = 'NoColor'
- else:
- # In ipython, we use its custom exception handler mechanism
- def_colors = ip.colors
- ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
-
- if colors is None:
- colors = def_colors
-
- # The stdlib debugger internally uses a modified repr from the `repr`
- # module, that limits the length of printed strings to a hardcoded
- # limit of 30 characters. That much trimming is too aggressive, let's
- # at least raise that limit to 80 chars, which should be enough for
- # most interactive uses.
- try:
- try:
- from reprlib import aRepr # Py 3
- except ImportError:
- from repr import aRepr # Py 2
- aRepr.maxstring = 80
- except:
- # This is only a user-facing convenience, so any error we encounter
- # here can be warned about but can be otherwise ignored. These
- # printouts will tell us about problems if this API changes
- import traceback
- traceback.print_exc()
-
- self.debugger = Pdb(colors)
-
- def __call__(self):
- """Starts an interactive debugger at the point where called.
-
- This is similar to the pdb.set_trace() function from the std lib, but
- using IPython's enhanced debugger."""
-
- self.debugger.set_trace(sys._getframe().f_back)
-
-
-def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
- """Make new_fn have old_fn's doc string. This is particularly useful
- for the ``do_...`` commands that hook into the help system.
- Adapted from from a comp.lang.python posting
- by Duncan Booth."""
- def wrapper(*args, **kw):
- return new_fn(*args, **kw)
- if old_fn.__doc__:
- wrapper.__doc__ = old_fn.__doc__ + additional_text
- return wrapper
-
-
-def _file_lines(fname):
- """Return the contents of a named file as a list of lines.
-
- This function never raises an IOError exception: if the file can't be
- read, it simply returns an empty list."""
-
- try:
- outfile = open(fname)
- except IOError:
- return []
- else:
- out = outfile.readlines()
- outfile.close()
- return out
-
-
+
+ ip = get_ipython()
+ if ip is None:
+ # Outside of ipython, we set our own exception hook manually
+ sys.excepthook = functools.partial(BdbQuit_excepthook,
+ excepthook=sys.excepthook)
+ def_colors = 'NoColor'
+ else:
+ # In ipython, we use its custom exception handler mechanism
+ def_colors = ip.colors
+ ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
+
+ if colors is None:
+ colors = def_colors
+
+ # The stdlib debugger internally uses a modified repr from the `repr`
+ # module, that limits the length of printed strings to a hardcoded
+ # limit of 30 characters. That much trimming is too aggressive, let's
+ # at least raise that limit to 80 chars, which should be enough for
+ # most interactive uses.
+ try:
+ try:
+ from reprlib import aRepr # Py 3
+ except ImportError:
+ from repr import aRepr # Py 2
+ aRepr.maxstring = 80
+ except:
+ # This is only a user-facing convenience, so any error we encounter
+ # here can be warned about but can be otherwise ignored. These
+ # printouts will tell us about problems if this API changes
+ import traceback
+ traceback.print_exc()
+
+ self.debugger = Pdb(colors)
+
+ def __call__(self):
+ """Starts an interactive debugger at the point where called.
+
+ This is similar to the pdb.set_trace() function from the std lib, but
+ using IPython's enhanced debugger."""
+
+ self.debugger.set_trace(sys._getframe().f_back)
+
+
+def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
+ """Make new_fn have old_fn's doc string. This is particularly useful
+ for the ``do_...`` commands that hook into the help system.
+ Adapted from from a comp.lang.python posting
+ by Duncan Booth."""
+ def wrapper(*args, **kw):
+ return new_fn(*args, **kw)
+ if old_fn.__doc__:
+ wrapper.__doc__ = old_fn.__doc__ + additional_text
+ return wrapper
+
+
+def _file_lines(fname):
+ """Return the contents of a named file as a list of lines.
+
+ This function never raises an IOError exception: if the file can't be
+ read, it simply returns an empty list."""
+
+ try:
+ outfile = open(fname)
+ except IOError:
+ return []
+ else:
+ out = outfile.readlines()
+ outfile.close()
+ return out
+
+
class Pdb(OldPdb):
"""Modified Pdb class, does not load readline.
-
+
for a standalone version that uses prompt_toolkit, see
`IPython.terminal.debugger.TerminalPdb` and
`IPython.terminal.debugger.set_trace()`
"""
def __init__(self, color_scheme=None, completekey=None,
- stdin=None, stdout=None, context=5):
-
- # Parent constructor:
- try:
+ stdin=None, stdout=None, context=5):
+
+ # Parent constructor:
+ try:
self.context = int(context)
- if self.context <= 0:
- raise ValueError("Context must be a positive integer")
- except (TypeError, ValueError):
- raise ValueError("Context must be a positive integer")
-
+ if self.context <= 0:
+ raise ValueError("Context must be a positive integer")
+ except (TypeError, ValueError):
+ raise ValueError("Context must be a positive integer")
+
OldPdb.__init__(self, completekey, stdin, stdout)
-
- # IPython changes...
- self.shell = get_ipython()
-
- if self.shell is None:
+
+ # IPython changes...
+ self.shell = get_ipython()
+
+ if self.shell is None:
save_main = sys.modules['__main__']
- # No IPython instance running, we must create one
- from IPython.terminal.interactiveshell import \
- TerminalInteractiveShell
- self.shell = TerminalInteractiveShell.instance()
+ # No IPython instance running, we must create one
+ from IPython.terminal.interactiveshell import \
+ TerminalInteractiveShell
+ self.shell = TerminalInteractiveShell.instance()
# needed by any code which calls __import__("__main__") after
# the debugger was entered. See also #9941.
sys.modules['__main__'] = save_main
-
+
if color_scheme is not None:
warnings.warn(
"The `color_scheme` argument is deprecated since version 5.1",
DeprecationWarning)
else:
color_scheme = self.shell.colors
-
- self.aliases = {}
-
- # Create color table: we copy the default one from the traceback
- # module and add a few attributes needed for debugging
- self.color_scheme_table = exception_colors()
-
- # shorthands
- C = coloransi.TermColors
- cst = self.color_scheme_table
-
- cst['NoColor'].colors.prompt = C.NoColor
- cst['NoColor'].colors.breakpoint_enabled = C.NoColor
- cst['NoColor'].colors.breakpoint_disabled = C.NoColor
-
- cst['Linux'].colors.prompt = C.Green
- cst['Linux'].colors.breakpoint_enabled = C.LightRed
- cst['Linux'].colors.breakpoint_disabled = C.Red
-
- cst['LightBG'].colors.prompt = C.Blue
- cst['LightBG'].colors.breakpoint_enabled = C.LightRed
- cst['LightBG'].colors.breakpoint_disabled = C.Red
-
+
+ self.aliases = {}
+
+ # Create color table: we copy the default one from the traceback
+ # module and add a few attributes needed for debugging
+ self.color_scheme_table = exception_colors()
+
+ # shorthands
+ C = coloransi.TermColors
+ cst = self.color_scheme_table
+
+ cst['NoColor'].colors.prompt = C.NoColor
+ cst['NoColor'].colors.breakpoint_enabled = C.NoColor
+ cst['NoColor'].colors.breakpoint_disabled = C.NoColor
+
+ cst['Linux'].colors.prompt = C.Green
+ cst['Linux'].colors.breakpoint_enabled = C.LightRed
+ cst['Linux'].colors.breakpoint_disabled = C.Red
+
+ cst['LightBG'].colors.prompt = C.Blue
+ cst['LightBG'].colors.breakpoint_enabled = C.LightRed
+ cst['LightBG'].colors.breakpoint_disabled = C.Red
+
cst['Neutral'].colors.prompt = C.Blue
cst['Neutral'].colors.breakpoint_enabled = C.LightRed
cst['Neutral'].colors.breakpoint_disabled = C.Red
- self.set_colors(color_scheme)
-
- # Add a python parser so we can syntax highlight source while
- # debugging.
- self.parser = PyColorize.Parser()
-
+ self.set_colors(color_scheme)
+
+ # Add a python parser so we can syntax highlight source while
+ # debugging.
+ self.parser = PyColorize.Parser()
+
# Set the prompt - the default prompt is '(Pdb)'
self.prompt = prompt
-
- def set_colors(self, scheme):
- """Shorthand access to the color table scheme selector method."""
- self.color_scheme_table.set_active_scheme(scheme)
-
- def interaction(self, frame, traceback):
+
+ def set_colors(self, scheme):
+ """Shorthand access to the color table scheme selector method."""
+ self.color_scheme_table.set_active_scheme(scheme)
+
+ def interaction(self, frame, traceback):
try:
OldPdb.interaction(self, frame, traceback)
except KeyboardInterrupt:
sys.stdout.write('\n' + self.shell.get_exception_only())
-
- def new_do_up(self, arg):
- OldPdb.do_up(self, arg)
- do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
-
- def new_do_down(self, arg):
- OldPdb.do_down(self, arg)
-
- do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
-
- def new_do_frame(self, arg):
- OldPdb.do_frame(self, arg)
-
- def new_do_quit(self, arg):
-
- if hasattr(self, 'old_all_completions'):
- self.shell.Completer.all_completions=self.old_all_completions
-
- return OldPdb.do_quit(self, arg)
-
- do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
-
- def new_do_restart(self, arg):
- """Restart command. In the context of ipython this is exactly the same
- thing as 'quit'."""
- self.msg("Restart doesn't make sense here. Using 'quit' instead.")
- return self.do_quit(arg)
-
- def print_stack_trace(self, context=None):
- if context is None:
- context = self.context
- try:
- context=int(context)
- if context <= 0:
- raise ValueError("Context must be a positive integer")
- except (TypeError, ValueError):
- raise ValueError("Context must be a positive integer")
- try:
- for frame_lineno in self.stack:
- self.print_stack_entry(frame_lineno, context=context)
- except KeyboardInterrupt:
- pass
-
+
+ def new_do_up(self, arg):
+ OldPdb.do_up(self, arg)
+ do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
+
+ def new_do_down(self, arg):
+ OldPdb.do_down(self, arg)
+
+ do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
+
+ def new_do_frame(self, arg):
+ OldPdb.do_frame(self, arg)
+
+ def new_do_quit(self, arg):
+
+ if hasattr(self, 'old_all_completions'):
+ self.shell.Completer.all_completions=self.old_all_completions
+
+ return OldPdb.do_quit(self, arg)
+
+ do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
+
+ def new_do_restart(self, arg):
+ """Restart command. In the context of ipython this is exactly the same
+ thing as 'quit'."""
+ self.msg("Restart doesn't make sense here. Using 'quit' instead.")
+ return self.do_quit(arg)
+
+ def print_stack_trace(self, context=None):
+ if context is None:
+ context = self.context
+ try:
+ context=int(context)
+ if context <= 0:
+ raise ValueError("Context must be a positive integer")
+ except (TypeError, ValueError):
+ raise ValueError("Context must be a positive integer")
+ try:
+ for frame_lineno in self.stack:
+ self.print_stack_entry(frame_lineno, context=context)
+ except KeyboardInterrupt:
+ pass
+
def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
- context=None):
- if context is None:
- context = self.context
- try:
- context=int(context)
- if context <= 0:
- raise ValueError("Context must be a positive integer")
- except (TypeError, ValueError):
- raise ValueError("Context must be a positive integer")
+ context=None):
+ if context is None:
+ context = self.context
+ try:
+ context=int(context)
+ if context <= 0:
+ raise ValueError("Context must be a positive integer")
+ except (TypeError, ValueError):
+ raise ValueError("Context must be a positive integer")
print(self.format_stack_entry(frame_lineno, '', context))
-
- # vds: >>
- frame, lineno = frame_lineno
- filename = frame.f_code.co_filename
- self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
- # vds: <<
-
- def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
- if context is None:
- context = self.context
- try:
- context=int(context)
- if context <= 0:
- print("Context must be a positive integer")
- except (TypeError, ValueError):
- print("Context must be a positive integer")
- try:
- import reprlib # Py 3
- except ImportError:
- import repr as reprlib # Py 2
-
- ret = []
-
- Colors = self.color_scheme_table.active_colors
- ColorsNormal = Colors.Normal
- tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
- tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
- tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
- tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
- ColorsNormal)
-
- frame, lineno = frame_lineno
-
- return_value = ''
- if '__return__' in frame.f_locals:
- rv = frame.f_locals['__return__']
- #return_value += '->'
- return_value += reprlib.repr(rv) + '\n'
- ret.append(return_value)
-
- #s = filename + '(' + `lineno` + ')'
- filename = self.canonic(frame.f_code.co_filename)
- link = tpl_link % py3compat.cast_unicode(filename)
-
- if frame.f_code.co_name:
- func = frame.f_code.co_name
- else:
- func = "<lambda>"
-
- call = ''
- if func != '?':
- if '__args__' in frame.f_locals:
- args = reprlib.repr(frame.f_locals['__args__'])
- else:
- args = '()'
- call = tpl_call % (func, args)
-
- # The level info should be generated in the same format pdb uses, to
- # avoid breaking the pdbtrack functionality of python-mode in *emacs.
- if frame is self.curframe:
- ret.append('> ')
- else:
- ret.append(' ')
- ret.append(u'%s(%s)%s\n' % (link,lineno,call))
-
- start = lineno - 1 - context//2
- lines = ulinecache.getlines(filename)
- start = min(start, len(lines) - context)
- start = max(start, 0)
- lines = lines[start : start + context]
-
- for i,line in enumerate(lines):
- show_arrow = (start + 1 + i == lineno)
- linetpl = (frame is self.curframe or show_arrow) \
- and tpl_line_em \
- or tpl_line
- ret.append(self.__format_line(linetpl, filename,
- start + 1 + i, line,
- arrow = show_arrow) )
- return ''.join(ret)
-
- def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
- bp_mark = ""
- bp_mark_color = ""
-
- scheme = self.color_scheme_table.active_scheme_name
- new_line, err = self.parser.format2(line, 'str', scheme)
- if not err: line = new_line
-
- bp = None
- if lineno in self.get_file_breaks(filename):
- bps = self.get_breaks(filename, lineno)
- bp = bps[-1]
-
- if bp:
- Colors = self.color_scheme_table.active_colors
- bp_mark = str(bp.number)
- bp_mark_color = Colors.breakpoint_enabled
- if not bp.enabled:
- bp_mark_color = Colors.breakpoint_disabled
-
- numbers_width = 7
- if arrow:
- # This is the line with the error
- pad = numbers_width - len(str(lineno)) - len(bp_mark)
+
+ # vds: >>
+ frame, lineno = frame_lineno
+ filename = frame.f_code.co_filename
+ self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
+ # vds: <<
+
+ def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
+ if context is None:
+ context = self.context
+ try:
+ context=int(context)
+ if context <= 0:
+ print("Context must be a positive integer")
+ except (TypeError, ValueError):
+ print("Context must be a positive integer")
+ try:
+ import reprlib # Py 3
+ except ImportError:
+ import repr as reprlib # Py 2
+
+ ret = []
+
+ Colors = self.color_scheme_table.active_colors
+ ColorsNormal = Colors.Normal
+ tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
+ tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
+ tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
+ tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
+ ColorsNormal)
+
+ frame, lineno = frame_lineno
+
+ return_value = ''
+ if '__return__' in frame.f_locals:
+ rv = frame.f_locals['__return__']
+ #return_value += '->'
+ return_value += reprlib.repr(rv) + '\n'
+ ret.append(return_value)
+
+ #s = filename + '(' + `lineno` + ')'
+ filename = self.canonic(frame.f_code.co_filename)
+ link = tpl_link % py3compat.cast_unicode(filename)
+
+ if frame.f_code.co_name:
+ func = frame.f_code.co_name
+ else:
+ func = "<lambda>"
+
+ call = ''
+ if func != '?':
+ if '__args__' in frame.f_locals:
+ args = reprlib.repr(frame.f_locals['__args__'])
+ else:
+ args = '()'
+ call = tpl_call % (func, args)
+
+ # The level info should be generated in the same format pdb uses, to
+ # avoid breaking the pdbtrack functionality of python-mode in *emacs.
+ if frame is self.curframe:
+ ret.append('> ')
+ else:
+ ret.append(' ')
+ ret.append(u'%s(%s)%s\n' % (link,lineno,call))
+
+ start = lineno - 1 - context//2
+ lines = ulinecache.getlines(filename)
+ start = min(start, len(lines) - context)
+ start = max(start, 0)
+ lines = lines[start : start + context]
+
+ for i,line in enumerate(lines):
+ show_arrow = (start + 1 + i == lineno)
+ linetpl = (frame is self.curframe or show_arrow) \
+ and tpl_line_em \
+ or tpl_line
+ ret.append(self.__format_line(linetpl, filename,
+ start + 1 + i, line,
+ arrow = show_arrow) )
+ return ''.join(ret)
+
+ def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
+ bp_mark = ""
+ bp_mark_color = ""
+
+ scheme = self.color_scheme_table.active_scheme_name
+ new_line, err = self.parser.format2(line, 'str', scheme)
+ if not err: line = new_line
+
+ bp = None
+ if lineno in self.get_file_breaks(filename):
+ bps = self.get_breaks(filename, lineno)
+ bp = bps[-1]
+
+ if bp:
+ Colors = self.color_scheme_table.active_colors
+ bp_mark = str(bp.number)
+ bp_mark_color = Colors.breakpoint_enabled
+ if not bp.enabled:
+ bp_mark_color = Colors.breakpoint_disabled
+
+ numbers_width = 7
+ if arrow:
+ # This is the line with the error
+ pad = numbers_width - len(str(lineno)) - len(bp_mark)
num = '%s%s' % (make_arrow(pad), str(lineno))
- else:
- num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
-
+ else:
+ num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
+
return tpl_line % (bp_mark_color + bp_mark, num, line)
-
-
- def print_list_lines(self, filename, first, last):
- """The printing (as opposed to the parsing part of a 'list'
- command."""
- try:
- Colors = self.color_scheme_table.active_colors
- ColorsNormal = Colors.Normal
- tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
- tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
- src = []
- if filename == "<string>" and hasattr(self, "_exec_filename"):
- filename = self._exec_filename
-
- for lineno in range(first, last+1):
- line = ulinecache.getline(filename, lineno)
- if not line:
- break
-
- if lineno == self.curframe.f_lineno:
- line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
- else:
- line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
-
- src.append(line)
- self.lineno = lineno
-
+
+
+ def print_list_lines(self, filename, first, last):
+ """The printing (as opposed to the parsing part of a 'list'
+ command."""
+ try:
+ Colors = self.color_scheme_table.active_colors
+ ColorsNormal = Colors.Normal
+ tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
+ tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
+ src = []
+ if filename == "<string>" and hasattr(self, "_exec_filename"):
+ filename = self._exec_filename
+
+ for lineno in range(first, last+1):
+ line = ulinecache.getline(filename, lineno)
+ if not line:
+ break
+
+ if lineno == self.curframe.f_lineno:
+ line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
+ else:
+ line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
+
+ src.append(line)
+ self.lineno = lineno
+
print(''.join(src))
-
- except KeyboardInterrupt:
- pass
-
- def do_list(self, arg):
+
+ except KeyboardInterrupt:
+ pass
+
+ def do_list(self, arg):
"""Print lines of code from the current stack frame
"""
- self.lastcmd = 'list'
- last = None
- if arg:
- try:
- x = eval(arg, {}, {})
- if type(x) == type(()):
- first, last = x
- first = int(first)
- last = int(last)
- if last < first:
- # Assume it's a count
- last = first + last
- else:
- first = max(1, int(x) - 5)
- except:
- print('*** Error in argument:', repr(arg))
- return
- elif self.lineno is None:
- first = max(1, self.curframe.f_lineno - 5)
- else:
- first = self.lineno + 1
- if last is None:
- last = first + 10
- self.print_list_lines(self.curframe.f_code.co_filename, first, last)
-
- # vds: >>
- lineno = first
- filename = self.curframe.f_code.co_filename
- self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
- # vds: <<
-
- do_l = do_list
-
- def getsourcelines(self, obj):
- lines, lineno = inspect.findsource(obj)
- if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
- # must be a module frame: do not try to cut a block out of it
- return lines, 1
- elif inspect.ismodule(obj):
- return lines, 1
- return inspect.getblock(lines[lineno:]), lineno+1
-
- def do_longlist(self, arg):
+ self.lastcmd = 'list'
+ last = None
+ if arg:
+ try:
+ x = eval(arg, {}, {})
+ if type(x) == type(()):
+ first, last = x
+ first = int(first)
+ last = int(last)
+ if last < first:
+ # Assume it's a count
+ last = first + last
+ else:
+ first = max(1, int(x) - 5)
+ except:
+ print('*** Error in argument:', repr(arg))
+ return
+ elif self.lineno is None:
+ first = max(1, self.curframe.f_lineno - 5)
+ else:
+ first = self.lineno + 1
+ if last is None:
+ last = first + 10
+ self.print_list_lines(self.curframe.f_code.co_filename, first, last)
+
+ # vds: >>
+ lineno = first
+ filename = self.curframe.f_code.co_filename
+ self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
+ # vds: <<
+
+ do_l = do_list
+
+ def getsourcelines(self, obj):
+ lines, lineno = inspect.findsource(obj)
+ if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
+ # must be a module frame: do not try to cut a block out of it
+ return lines, 1
+ elif inspect.ismodule(obj):
+ return lines, 1
+ return inspect.getblock(lines[lineno:]), lineno+1
+
+ def do_longlist(self, arg):
"""Print lines of code from the current stack frame.
Shows more lines than 'list' does.
"""
- self.lastcmd = 'longlist'
- try:
- lines, lineno = self.getsourcelines(self.curframe)
- except OSError as err:
- self.error(err)
- return
- last = lineno + len(lines)
- self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
- do_ll = do_longlist
-
- def do_pdef(self, arg):
- """Print the call signature for any callable object.
-
- The debugger interface to %pdef"""
- namespaces = [('Locals', self.curframe.f_locals),
- ('Globals', self.curframe.f_globals)]
- self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
-
- def do_pdoc(self, arg):
- """Print the docstring for an object.
-
- The debugger interface to %pdoc."""
- namespaces = [('Locals', self.curframe.f_locals),
- ('Globals', self.curframe.f_globals)]
- self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
-
- def do_pfile(self, arg):
- """Print (or run through pager) the file where an object is defined.
-
- The debugger interface to %pfile.
- """
- namespaces = [('Locals', self.curframe.f_locals),
- ('Globals', self.curframe.f_globals)]
- self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
-
- def do_pinfo(self, arg):
- """Provide detailed information about an object.
-
- The debugger interface to %pinfo, i.e., obj?."""
- namespaces = [('Locals', self.curframe.f_locals),
- ('Globals', self.curframe.f_globals)]
- self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
-
- def do_pinfo2(self, arg):
- """Provide extra detailed information about an object.
-
- The debugger interface to %pinfo2, i.e., obj??."""
- namespaces = [('Locals', self.curframe.f_locals),
- ('Globals', self.curframe.f_globals)]
- self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
-
- def do_psource(self, arg):
- """Print (or run through pager) the source code for an object."""
- namespaces = [('Locals', self.curframe.f_locals),
- ('Globals', self.curframe.f_globals)]
- self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
-
- if sys.version_info > (3, ):
- def do_where(self, arg):
- """w(here)
- Print a stack trace, with the most recent frame at the bottom.
- An arrow indicates the "current frame", which determines the
- context of most commands. 'bt' is an alias for this command.
-
- Take a number as argument as an (optional) number of context line to
- print"""
- if arg:
- context = int(arg)
- self.print_stack_trace(context)
- else:
- self.print_stack_trace()
-
- do_w = do_where
+ self.lastcmd = 'longlist'
+ try:
+ lines, lineno = self.getsourcelines(self.curframe)
+ except OSError as err:
+ self.error(err)
+ return
+ last = lineno + len(lines)
+ self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
+ do_ll = do_longlist
+
+ def do_pdef(self, arg):
+ """Print the call signature for any callable object.
+
+ The debugger interface to %pdef"""
+ namespaces = [('Locals', self.curframe.f_locals),
+ ('Globals', self.curframe.f_globals)]
+ self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
+
+ def do_pdoc(self, arg):
+ """Print the docstring for an object.
+
+ The debugger interface to %pdoc."""
+ namespaces = [('Locals', self.curframe.f_locals),
+ ('Globals', self.curframe.f_globals)]
+ self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
+
+ def do_pfile(self, arg):
+ """Print (or run through pager) the file where an object is defined.
+
+ The debugger interface to %pfile.
+ """
+ namespaces = [('Locals', self.curframe.f_locals),
+ ('Globals', self.curframe.f_globals)]
+ self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
+
+ def do_pinfo(self, arg):
+ """Provide detailed information about an object.
+
+ The debugger interface to %pinfo, i.e., obj?."""
+ namespaces = [('Locals', self.curframe.f_locals),
+ ('Globals', self.curframe.f_globals)]
+ self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
+
+ def do_pinfo2(self, arg):
+ """Provide extra detailed information about an object.
+
+ The debugger interface to %pinfo2, i.e., obj??."""
+ namespaces = [('Locals', self.curframe.f_locals),
+ ('Globals', self.curframe.f_globals)]
+ self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
+
+ def do_psource(self, arg):
+ """Print (or run through pager) the source code for an object."""
+ namespaces = [('Locals', self.curframe.f_locals),
+ ('Globals', self.curframe.f_globals)]
+ self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
+
+ if sys.version_info > (3, ):
+ def do_where(self, arg):
+ """w(here)
+ Print a stack trace, with the most recent frame at the bottom.
+ An arrow indicates the "current frame", which determines the
+ context of most commands. 'bt' is an alias for this command.
+
+ Take a number as argument as an (optional) number of context line to
+ print"""
+ if arg:
+ context = int(arg)
+ self.print_stack_trace(context)
+ else:
+ self.print_stack_trace()
+
+ do_w = do_where
def set_trace(frame=None):
diff --git a/contrib/python/ipython/py2/IPython/core/display.py b/contrib/python/ipython/py2/IPython/core/display.py
index 2c38b32933..5c82a57b31 100644
--- a/contrib/python/ipython/py2/IPython/core/display.py
+++ b/contrib/python/ipython/py2/IPython/core/display.py
@@ -1,124 +1,124 @@
-# -*- coding: utf-8 -*-
-"""Top-level display functions for displaying object in different formats."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
+# -*- coding: utf-8 -*-
+"""Top-level display functions for displaying object in different formats."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
try:
from base64 import encodebytes as base64_encode
except ImportError:
from base64 import encodestring as base64_encode
from binascii import b2a_hex, hexlify
-import json
-import mimetypes
-import os
-import struct
+import json
+import mimetypes
+import os
+import struct
import sys
-import warnings
-
-from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
- unicode_type)
-from IPython.testing.skipdoctest import skip_doctest
-
-__all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
-'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
-'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
+import warnings
+
+from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
+ unicode_type)
+from IPython.testing.skipdoctest import skip_doctest
+
+__all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
+'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
+'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'ProgressBar', 'JSON', 'Javascript',
-'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
+'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
'publish_display_data', 'update_display', 'DisplayHandle']
-
-#-----------------------------------------------------------------------------
-# utility functions
-#-----------------------------------------------------------------------------
-
-def _safe_exists(path):
- """Check path, but don't let exceptions raise"""
- try:
- return os.path.exists(path)
- except Exception:
- return False
-
-def _merge(d1, d2):
- """Like update, but merges sub-dicts instead of clobbering at the top level.
-
- Updates d1 in-place
- """
-
- if not isinstance(d2, dict) or not isinstance(d1, dict):
- return d2
- for key, value in d2.items():
- d1[key] = _merge(d1.get(key), value)
- return d1
-
-def _display_mimetype(mimetype, objs, raw=False, metadata=None):
- """internal implementation of all display_foo methods
-
- Parameters
- ----------
- mimetype : str
- The mimetype to be published (e.g. 'image/png')
- objs : tuple of objects
- The Python objects to display, or if raw=True raw text data to
- display.
- raw : bool
- Are the data objects raw data or Python objects that need to be
- formatted before display? [default: False]
- metadata : dict (optional)
- Metadata to be associated with the specific mimetype output.
- """
- if metadata:
- metadata = {mimetype: metadata}
- if raw:
- # turn list of pngdata into list of { 'image/png': pngdata }
- objs = [ {mimetype: obj} for obj in objs ]
- display(*objs, raw=raw, metadata=metadata, include=[mimetype])
-
-#-----------------------------------------------------------------------------
-# Main functions
-#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# utility functions
+#-----------------------------------------------------------------------------
+
+def _safe_exists(path):
+ """Check path, but don't let exceptions raise"""
+ try:
+ return os.path.exists(path)
+ except Exception:
+ return False
+
+def _merge(d1, d2):
+ """Like update, but merges sub-dicts instead of clobbering at the top level.
+
+ Updates d1 in-place
+ """
+
+ if not isinstance(d2, dict) or not isinstance(d1, dict):
+ return d2
+ for key, value in d2.items():
+ d1[key] = _merge(d1.get(key), value)
+ return d1
+
+def _display_mimetype(mimetype, objs, raw=False, metadata=None):
+ """internal implementation of all display_foo methods
+
+ Parameters
+ ----------
+ mimetype : str
+ The mimetype to be published (e.g. 'image/png')
+ objs : tuple of objects
+ The Python objects to display, or if raw=True raw text data to
+ display.
+ raw : bool
+ Are the data objects raw data or Python objects that need to be
+ formatted before display? [default: False]
+ metadata : dict (optional)
+ Metadata to be associated with the specific mimetype output.
+ """
+ if metadata:
+ metadata = {mimetype: metadata}
+ if raw:
+ # turn list of pngdata into list of { 'image/png': pngdata }
+ objs = [ {mimetype: obj} for obj in objs ]
+ display(*objs, raw=raw, metadata=metadata, include=[mimetype])
+
+#-----------------------------------------------------------------------------
+# Main functions
+#-----------------------------------------------------------------------------
# use * to indicate transient is keyword-only
def publish_display_data(data, metadata=None, source=None, **kwargs):
- """Publish data and metadata to all frontends.
-
- See the ``display_data`` message in the messaging documentation for
- more details about this message type.
-
- The following MIME types are currently implemented:
-
- * text/plain
- * text/html
- * text/markdown
- * text/latex
- * application/json
- * application/javascript
- * image/png
- * image/jpeg
- * image/svg+xml
-
- Parameters
- ----------
- data : dict
- A dictionary having keys that are valid MIME types (like
- 'text/plain' or 'image/svg+xml') and values that are the data for
- that MIME type. The data itself must be a JSON'able data
- structure. Minimally all data should have the 'text/plain' data,
- which can be displayed by all frontends. If more than the plain
- text is given, it is up to the frontend to decide which
- representation to use.
- metadata : dict
- A dictionary for metadata related to the data. This can contain
- arbitrary key, value pairs that frontends can use to interpret
- the data. mime-type keys matching those in data can be used
- to specify metadata about particular representations.
- source : str, deprecated
- Unused.
+ """Publish data and metadata to all frontends.
+
+ See the ``display_data`` message in the messaging documentation for
+ more details about this message type.
+
+ The following MIME types are currently implemented:
+
+ * text/plain
+ * text/html
+ * text/markdown
+ * text/latex
+ * application/json
+ * application/javascript
+ * image/png
+ * image/jpeg
+ * image/svg+xml
+
+ Parameters
+ ----------
+ data : dict
+ A dictionary having keys that are valid MIME types (like
+ 'text/plain' or 'image/svg+xml') and values that are the data for
+ that MIME type. The data itself must be a JSON'able data
+ structure. Minimally all data should have the 'text/plain' data,
+ which can be displayed by all frontends. If more than the plain
+ text is given, it is up to the frontend to decide which
+ representation to use.
+ metadata : dict
+ A dictionary for metadata related to the data. This can contain
+ arbitrary key, value pairs that frontends can use to interpret
+ the data. mime-type keys matching those in data can be used
+ to specify metadata about particular representations.
+ source : str, deprecated
+ Unused.
transient : dict, keyword-only
A dictionary of transient data, such as display_id.
- """
- from IPython.core.interactiveshell import InteractiveShell
+ """
+ from IPython.core.interactiveshell import InteractiveShell
display_pub = InteractiveShell.instance().display_pub
@@ -127,45 +127,45 @@ def publish_display_data(data, metadata=None, source=None, **kwargs):
# TODO: We could check for ipykernel version and provide a detailed upgrade message.
display_pub.publish(
- data=data,
- metadata=metadata,
+ data=data,
+ metadata=metadata,
**kwargs
- )
-
+ )
+
def _new_id():
"""Generate a new random text id with urandom"""
return b2a_hex(os.urandom(16)).decode('ascii')
-def display(*objs, **kwargs):
- """Display a Python object in all frontends.
-
- By default all representations will be computed and sent to the frontends.
- Frontends can decide which representation is used and how.
-
+def display(*objs, **kwargs):
+ """Display a Python object in all frontends.
+
+ By default all representations will be computed and sent to the frontends.
+ Frontends can decide which representation is used and how.
+
In terminal IPython this will be similar to using :func:`print`, for use in richer
frontends see Jupyter notebook examples with rich display logic.
- Parameters
- ----------
- objs : tuple of objects
- The Python objects to display.
- raw : bool, optional
- Are the objects to be displayed already mimetype-keyed dicts of raw display data,
- or Python objects that need to be formatted before display? [default: False]
+ Parameters
+ ----------
+ objs : tuple of objects
+ The Python objects to display.
+ raw : bool, optional
+ Are the objects to be displayed already mimetype-keyed dicts of raw display data,
+ or Python objects that need to be formatted before display? [default: False]
include : list, tuple or set, optional
- A list of format type strings (MIME types) to include in the
- format data dict. If this is set *only* the format types included
- in this list will be computed.
+ A list of format type strings (MIME types) to include in the
+ format data dict. If this is set *only* the format types included
+ in this list will be computed.
exclude : list, tuple or set, optional
- A list of format type strings (MIME types) to exclude in the format
- data dict. If this is set all format types will be computed,
- except for those included in this argument.
- metadata : dict, optional
- A dictionary of metadata to associate with the output.
- mime-type keys in this dictionary will be associated with the individual
- representation formats, if they exist.
+ A list of format type strings (MIME types) to exclude in the format
+ data dict. If this is set all format types will be computed,
+ except for those included in this argument.
+ metadata : dict, optional
+ A dictionary of metadata to associate with the output.
+ mime-type keys in this dictionary will be associated with the individual
+ representation formats, if they exist.
transient : dict, optional
A dictionary of transient data to associate with the output.
Data in this dict should not be persisted to files (e.g. notebooks).
@@ -276,8 +276,8 @@ def display(*objs, **kwargs):
from IPython.display import display
- """
- from IPython.core.interactiveshell import InteractiveShell
+ """
+ from IPython.core.interactiveshell import InteractiveShell
if not InteractiveShell.initialized():
# Directly print objects.
@@ -300,26 +300,26 @@ def display(*objs, **kwargs):
raise TypeError('display_id required for update_display')
if transient:
kwargs['transient'] = transient
-
- if not raw:
- format = InteractiveShell.instance().display_formatter.format
-
- for obj in objs:
- if raw:
+
+ if not raw:
+ format = InteractiveShell.instance().display_formatter.format
+
+ for obj in objs:
+ if raw:
publish_display_data(data=obj, metadata=metadata, **kwargs)
- else:
- format_dict, md_dict = format(obj, include=include, exclude=exclude)
- if not format_dict:
- # nothing to display (e.g. _ipython_display_ took over)
- continue
- if metadata:
- # kwarg-specified metadata gets precedence
- _merge(md_dict, metadata)
+ else:
+ format_dict, md_dict = format(obj, include=include, exclude=exclude)
+ if not format_dict:
+ # nothing to display (e.g. _ipython_display_ took over)
+ continue
+ if metadata:
+ # kwarg-specified metadata gets precedence
+ _merge(md_dict, metadata)
publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
if display_id:
return DisplayHandle(display_id)
-
-
+
+
# use * for keyword-only display_id arg
def update_display(obj, **kwargs):
"""Update an existing display by id
@@ -395,346 +395,346 @@ class DisplayHandle(object):
update_display(obj, display_id=self.display_id, **kwargs)
-def display_pretty(*objs, **kwargs):
- """Display the pretty (default) representation of an object.
-
- Parameters
- ----------
- objs : tuple of objects
- The Python objects to display, or if raw=True raw text data to
- display.
- raw : bool
- Are the data objects raw data or Python objects that need to be
- formatted before display? [default: False]
- metadata : dict (optional)
- Metadata to be associated with the specific mimetype output.
- """
- _display_mimetype('text/plain', objs, **kwargs)
-
-
-def display_html(*objs, **kwargs):
- """Display the HTML representation of an object.
-
- Note: If raw=False and the object does not have a HTML
- representation, no HTML will be shown.
-
- Parameters
- ----------
- objs : tuple of objects
- The Python objects to display, or if raw=True raw HTML data to
- display.
- raw : bool
- Are the data objects raw data or Python objects that need to be
- formatted before display? [default: False]
- metadata : dict (optional)
- Metadata to be associated with the specific mimetype output.
- """
- _display_mimetype('text/html', objs, **kwargs)
-
-
-def display_markdown(*objs, **kwargs):
- """Displays the Markdown representation of an object.
-
- Parameters
- ----------
- objs : tuple of objects
- The Python objects to display, or if raw=True raw markdown data to
- display.
- raw : bool
- Are the data objects raw data or Python objects that need to be
- formatted before display? [default: False]
- metadata : dict (optional)
- Metadata to be associated with the specific mimetype output.
- """
-
- _display_mimetype('text/markdown', objs, **kwargs)
-
-
-def display_svg(*objs, **kwargs):
- """Display the SVG representation of an object.
-
- Parameters
- ----------
- objs : tuple of objects
- The Python objects to display, or if raw=True raw svg data to
- display.
- raw : bool
- Are the data objects raw data or Python objects that need to be
- formatted before display? [default: False]
- metadata : dict (optional)
- Metadata to be associated with the specific mimetype output.
- """
- _display_mimetype('image/svg+xml', objs, **kwargs)
-
-
-def display_png(*objs, **kwargs):
- """Display the PNG representation of an object.
-
- Parameters
- ----------
- objs : tuple of objects
- The Python objects to display, or if raw=True raw png data to
- display.
- raw : bool
- Are the data objects raw data or Python objects that need to be
- formatted before display? [default: False]
- metadata : dict (optional)
- Metadata to be associated with the specific mimetype output.
- """
- _display_mimetype('image/png', objs, **kwargs)
-
-
-def display_jpeg(*objs, **kwargs):
- """Display the JPEG representation of an object.
-
- Parameters
- ----------
- objs : tuple of objects
- The Python objects to display, or if raw=True raw JPEG data to
- display.
- raw : bool
- Are the data objects raw data or Python objects that need to be
- formatted before display? [default: False]
- metadata : dict (optional)
- Metadata to be associated with the specific mimetype output.
- """
- _display_mimetype('image/jpeg', objs, **kwargs)
-
-
-def display_latex(*objs, **kwargs):
- """Display the LaTeX representation of an object.
-
- Parameters
- ----------
- objs : tuple of objects
- The Python objects to display, or if raw=True raw latex data to
- display.
- raw : bool
- Are the data objects raw data or Python objects that need to be
- formatted before display? [default: False]
- metadata : dict (optional)
- Metadata to be associated with the specific mimetype output.
- """
- _display_mimetype('text/latex', objs, **kwargs)
-
-
-def display_json(*objs, **kwargs):
- """Display the JSON representation of an object.
-
- Note that not many frontends support displaying JSON.
-
- Parameters
- ----------
- objs : tuple of objects
- The Python objects to display, or if raw=True raw json data to
- display.
- raw : bool
- Are the data objects raw data or Python objects that need to be
- formatted before display? [default: False]
- metadata : dict (optional)
- Metadata to be associated with the specific mimetype output.
- """
- _display_mimetype('application/json', objs, **kwargs)
-
-
-def display_javascript(*objs, **kwargs):
- """Display the Javascript representation of an object.
-
- Parameters
- ----------
- objs : tuple of objects
- The Python objects to display, or if raw=True raw javascript data to
- display.
- raw : bool
- Are the data objects raw data or Python objects that need to be
- formatted before display? [default: False]
- metadata : dict (optional)
- Metadata to be associated with the specific mimetype output.
- """
- _display_mimetype('application/javascript', objs, **kwargs)
-
-
-def display_pdf(*objs, **kwargs):
- """Display the PDF representation of an object.
-
- Parameters
- ----------
- objs : tuple of objects
- The Python objects to display, or if raw=True raw javascript data to
- display.
- raw : bool
- Are the data objects raw data or Python objects that need to be
- formatted before display? [default: False]
- metadata : dict (optional)
- Metadata to be associated with the specific mimetype output.
- """
- _display_mimetype('application/pdf', objs, **kwargs)
-
-
-#-----------------------------------------------------------------------------
-# Smart classes
-#-----------------------------------------------------------------------------
-
-
-class DisplayObject(object):
- """An object that wraps data to be displayed."""
-
- _read_flags = 'r'
- _show_mem_addr = False
-
- def __init__(self, data=None, url=None, filename=None):
- """Create a display object given raw data.
-
- When this object is returned by an expression or passed to the
- display function, it will result in the data being displayed
- in the frontend. The MIME type of the data should match the
- subclasses used, so the Png subclass should be used for 'image/png'
- data. If the data is a URL, the data will first be downloaded
- and then displayed. If
-
- Parameters
- ----------
- data : unicode, str or bytes
- The raw data or a URL or file to load the data from
- url : unicode
- A URL to download the data from.
- filename : unicode
- Path to a local file to load the data from.
- """
- if data is not None and isinstance(data, string_types):
- if data.startswith('http') and url is None:
- url = data
- filename = None
- data = None
- elif _safe_exists(data) and filename is None:
- url = None
- filename = data
- data = None
-
- self.data = data
- self.url = url
- self.filename = None if filename is None else unicode_type(filename)
-
- self.reload()
- self._check_data()
-
- def __repr__(self):
- if not self._show_mem_addr:
- cls = self.__class__
- r = "<%s.%s object>" % (cls.__module__, cls.__name__)
- else:
- r = super(DisplayObject, self).__repr__()
- return r
-
- def _check_data(self):
- """Override in subclasses if there's something to check."""
- pass
-
- def reload(self):
- """Reload the raw data from file or URL."""
- if self.filename is not None:
- with open(self.filename, self._read_flags) as f:
- self.data = f.read()
- elif self.url is not None:
- try:
- try:
- from urllib.request import urlopen # Py3
- except ImportError:
- from urllib2 import urlopen
- response = urlopen(self.url)
- self.data = response.read()
- # extract encoding from header, if there is one:
- encoding = None
- for sub in response.headers['content-type'].split(';'):
- sub = sub.strip()
- if sub.startswith('charset'):
- encoding = sub.split('=')[-1].strip()
- break
- # decode data, if an encoding was specified
- if encoding:
- self.data = self.data.decode(encoding, 'replace')
- except:
- self.data = None
-
-class TextDisplayObject(DisplayObject):
- """Validate that display data is text"""
- def _check_data(self):
- if self.data is not None and not isinstance(self.data, string_types):
- raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
-
-class Pretty(TextDisplayObject):
-
+def display_pretty(*objs, **kwargs):
+ """Display the pretty (default) representation of an object.
+
+ Parameters
+ ----------
+ objs : tuple of objects
+ The Python objects to display, or if raw=True raw text data to
+ display.
+ raw : bool
+ Are the data objects raw data or Python objects that need to be
+ formatted before display? [default: False]
+ metadata : dict (optional)
+ Metadata to be associated with the specific mimetype output.
+ """
+ _display_mimetype('text/plain', objs, **kwargs)
+
+
+def display_html(*objs, **kwargs):
+ """Display the HTML representation of an object.
+
+ Note: If raw=False and the object does not have a HTML
+ representation, no HTML will be shown.
+
+ Parameters
+ ----------
+ objs : tuple of objects
+ The Python objects to display, or if raw=True raw HTML data to
+ display.
+ raw : bool
+ Are the data objects raw data or Python objects that need to be
+ formatted before display? [default: False]
+ metadata : dict (optional)
+ Metadata to be associated with the specific mimetype output.
+ """
+ _display_mimetype('text/html', objs, **kwargs)
+
+
+def display_markdown(*objs, **kwargs):
+ """Displays the Markdown representation of an object.
+
+ Parameters
+ ----------
+ objs : tuple of objects
+ The Python objects to display, or if raw=True raw markdown data to
+ display.
+ raw : bool
+ Are the data objects raw data or Python objects that need to be
+ formatted before display? [default: False]
+ metadata : dict (optional)
+ Metadata to be associated with the specific mimetype output.
+ """
+
+ _display_mimetype('text/markdown', objs, **kwargs)
+
+
+def display_svg(*objs, **kwargs):
+ """Display the SVG representation of an object.
+
+ Parameters
+ ----------
+ objs : tuple of objects
+ The Python objects to display, or if raw=True raw svg data to
+ display.
+ raw : bool
+ Are the data objects raw data or Python objects that need to be
+ formatted before display? [default: False]
+ metadata : dict (optional)
+ Metadata to be associated with the specific mimetype output.
+ """
+ _display_mimetype('image/svg+xml', objs, **kwargs)
+
+
+def display_png(*objs, **kwargs):
+ """Display the PNG representation of an object.
+
+ Parameters
+ ----------
+ objs : tuple of objects
+ The Python objects to display, or if raw=True raw png data to
+ display.
+ raw : bool
+ Are the data objects raw data or Python objects that need to be
+ formatted before display? [default: False]
+ metadata : dict (optional)
+ Metadata to be associated with the specific mimetype output.
+ """
+ _display_mimetype('image/png', objs, **kwargs)
+
+
+def display_jpeg(*objs, **kwargs):
+ """Display the JPEG representation of an object.
+
+ Parameters
+ ----------
+ objs : tuple of objects
+ The Python objects to display, or if raw=True raw JPEG data to
+ display.
+ raw : bool
+ Are the data objects raw data or Python objects that need to be
+ formatted before display? [default: False]
+ metadata : dict (optional)
+ Metadata to be associated with the specific mimetype output.
+ """
+ _display_mimetype('image/jpeg', objs, **kwargs)
+
+
+def display_latex(*objs, **kwargs):
+ """Display the LaTeX representation of an object.
+
+ Parameters
+ ----------
+ objs : tuple of objects
+ The Python objects to display, or if raw=True raw latex data to
+ display.
+ raw : bool
+ Are the data objects raw data or Python objects that need to be
+ formatted before display? [default: False]
+ metadata : dict (optional)
+ Metadata to be associated with the specific mimetype output.
+ """
+ _display_mimetype('text/latex', objs, **kwargs)
+
+
+def display_json(*objs, **kwargs):
+ """Display the JSON representation of an object.
+
+ Note that not many frontends support displaying JSON.
+
+ Parameters
+ ----------
+ objs : tuple of objects
+ The Python objects to display, or if raw=True raw json data to
+ display.
+ raw : bool
+ Are the data objects raw data or Python objects that need to be
+ formatted before display? [default: False]
+ metadata : dict (optional)
+ Metadata to be associated with the specific mimetype output.
+ """
+ _display_mimetype('application/json', objs, **kwargs)
+
+
+def display_javascript(*objs, **kwargs):
+ """Display the Javascript representation of an object.
+
+ Parameters
+ ----------
+ objs : tuple of objects
+ The Python objects to display, or if raw=True raw javascript data to
+ display.
+ raw : bool
+ Are the data objects raw data or Python objects that need to be
+ formatted before display? [default: False]
+ metadata : dict (optional)
+ Metadata to be associated with the specific mimetype output.
+ """
+ _display_mimetype('application/javascript', objs, **kwargs)
+
+
+def display_pdf(*objs, **kwargs):
+ """Display the PDF representation of an object.
+
+ Parameters
+ ----------
+ objs : tuple of objects
+ The Python objects to display, or if raw=True raw javascript data to
+ display.
+ raw : bool
+ Are the data objects raw data or Python objects that need to be
+ formatted before display? [default: False]
+ metadata : dict (optional)
+ Metadata to be associated with the specific mimetype output.
+ """
+ _display_mimetype('application/pdf', objs, **kwargs)
+
+
+#-----------------------------------------------------------------------------
+# Smart classes
+#-----------------------------------------------------------------------------
+
+
+class DisplayObject(object):
+ """An object that wraps data to be displayed."""
+
+ _read_flags = 'r'
+ _show_mem_addr = False
+
+ def __init__(self, data=None, url=None, filename=None):
+ """Create a display object given raw data.
+
+ When this object is returned by an expression or passed to the
+ display function, it will result in the data being displayed
+ in the frontend. The MIME type of the data should match the
+ subclasses used, so the Png subclass should be used for 'image/png'
+ data. If the data is a URL, the data will first be downloaded
+ and then displayed. If
+
+ Parameters
+ ----------
+ data : unicode, str or bytes
+ The raw data or a URL or file to load the data from
+ url : unicode
+ A URL to download the data from.
+ filename : unicode
+ Path to a local file to load the data from.
+ """
+ if data is not None and isinstance(data, string_types):
+ if data.startswith('http') and url is None:
+ url = data
+ filename = None
+ data = None
+ elif _safe_exists(data) and filename is None:
+ url = None
+ filename = data
+ data = None
+
+ self.data = data
+ self.url = url
+ self.filename = None if filename is None else unicode_type(filename)
+
+ self.reload()
+ self._check_data()
+
+ def __repr__(self):
+ if not self._show_mem_addr:
+ cls = self.__class__
+ r = "<%s.%s object>" % (cls.__module__, cls.__name__)
+ else:
+ r = super(DisplayObject, self).__repr__()
+ return r
+
+ def _check_data(self):
+ """Override in subclasses if there's something to check."""
+ pass
+
+ def reload(self):
+ """Reload the raw data from file or URL."""
+ if self.filename is not None:
+ with open(self.filename, self._read_flags) as f:
+ self.data = f.read()
+ elif self.url is not None:
+ try:
+ try:
+ from urllib.request import urlopen # Py3
+ except ImportError:
+ from urllib2 import urlopen
+ response = urlopen(self.url)
+ self.data = response.read()
+ # extract encoding from header, if there is one:
+ encoding = None
+ for sub in response.headers['content-type'].split(';'):
+ sub = sub.strip()
+ if sub.startswith('charset'):
+ encoding = sub.split('=')[-1].strip()
+ break
+ # decode data, if an encoding was specified
+ if encoding:
+ self.data = self.data.decode(encoding, 'replace')
+ except:
+ self.data = None
+
+class TextDisplayObject(DisplayObject):
+ """Validate that display data is text"""
+ def _check_data(self):
+ if self.data is not None and not isinstance(self.data, string_types):
+ raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
+
+class Pretty(TextDisplayObject):
+
def _repr_pretty_(self, pp, cycle):
return pp.text(self.data)
-
-
-class HTML(TextDisplayObject):
-
- def _repr_html_(self):
- return self.data
-
- def __html__(self):
- """
- This method exists to inform other HTML-using modules (e.g. Markupsafe,
- htmltag, etc) that this object is HTML and does not need things like
- special characters (<>&) escaped.
- """
- return self._repr_html_()
-
-
-class Markdown(TextDisplayObject):
-
- def _repr_markdown_(self):
- return self.data
-
-
-class Math(TextDisplayObject):
-
- def _repr_latex_(self):
- s = self.data.strip('$')
- return "$$%s$$" % s
-
-
-class Latex(TextDisplayObject):
-
- def _repr_latex_(self):
- return self.data
-
-
-class SVG(DisplayObject):
-
+
+
+class HTML(TextDisplayObject):
+
+ def _repr_html_(self):
+ return self.data
+
+ def __html__(self):
+ """
+ This method exists to inform other HTML-using modules (e.g. Markupsafe,
+ htmltag, etc) that this object is HTML and does not need things like
+ special characters (<>&) escaped.
+ """
+ return self._repr_html_()
+
+
+class Markdown(TextDisplayObject):
+
+ def _repr_markdown_(self):
+ return self.data
+
+
+class Math(TextDisplayObject):
+
+ def _repr_latex_(self):
+ s = self.data.strip('$')
+ return "$$%s$$" % s
+
+
+class Latex(TextDisplayObject):
+
+ def _repr_latex_(self):
+ return self.data
+
+
+class SVG(DisplayObject):
+
_read_flags = 'rb'
- # wrap data in a property, which extracts the <svg> tag, discarding
- # document headers
- _data = None
-
- @property
- def data(self):
- return self._data
-
- @data.setter
- def data(self, svg):
- if svg is None:
- self._data = None
- return
- # parse into dom object
- from xml.dom import minidom
- svg = cast_bytes_py2(svg)
- x = minidom.parseString(svg)
- # get svg tag (should be 1)
- found_svg = x.getElementsByTagName('svg')
- if found_svg:
- svg = found_svg[0].toxml()
- else:
- # fallback on the input, trust the user
- # but this is probably an error.
- pass
- svg = cast_unicode(svg)
- self._data = svg
-
- def _repr_svg_(self):
- return self.data
-
+ # wrap data in a property, which extracts the <svg> tag, discarding
+ # document headers
+ _data = None
+
+ @property
+ def data(self):
+ return self._data
+
+ @data.setter
+ def data(self, svg):
+ if svg is None:
+ self._data = None
+ return
+ # parse into dom object
+ from xml.dom import minidom
+ svg = cast_bytes_py2(svg)
+ x = minidom.parseString(svg)
+ # get svg tag (should be 1)
+ found_svg = x.getElementsByTagName('svg')
+ if found_svg:
+ svg = found_svg[0].toxml()
+ else:
+ # fallback on the input, trust the user
+ # but this is probably an error.
+ pass
+ svg = cast_unicode(svg)
+ self._data = svg
+
+ def _repr_svg_(self):
+ return self.data
+
class ProgressBar(DisplayObject):
"""Progressbar supports displaying a progressbar like element
"""
@@ -751,7 +751,7 @@ class ProgressBar(DisplayObject):
self.html_width = '60ex'
self.text_width = 60
self._display_id = hexlify(os.urandom(8)).decode('ascii')
-
+
def __repr__(self):
fraction = self.progress / self.total
filled = '=' * int(fraction * self.text_width)
@@ -797,367 +797,367 @@ class ProgressBar(DisplayObject):
"""Python 2 compatibility"""
return self.__next__()
-class JSON(DisplayObject):
- """JSON expects a JSON-able dict or list
-
- not an already-serialized JSON string.
-
- Scalar types (None, number, string) are not allowed, only dict or list containers.
- """
- # wrap data in a property, which warns about passing already-serialized JSON
- _data = None
- def _check_data(self):
- if self.data is not None and not isinstance(self.data, (dict, list)):
- raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
-
- @property
- def data(self):
- return self._data
-
- @data.setter
- def data(self, data):
- if isinstance(data, string_types):
- warnings.warn("JSON expects JSONable dict or list, not JSON strings")
- data = json.loads(data)
- self._data = data
-
- def _repr_json_(self):
- return self.data
-
-css_t = """$("head").append($("<link/>").attr({
- rel: "stylesheet",
- type: "text/css",
- href: "%s"
-}));
-"""
-
-lib_t1 = """$.getScript("%s", function () {
-"""
-lib_t2 = """});
-"""
-
-class Javascript(TextDisplayObject):
-
- def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
- """Create a Javascript display object given raw data.
-
- When this object is returned by an expression or passed to the
- display function, it will result in the data being displayed
- in the frontend. If the data is a URL, the data will first be
- downloaded and then displayed.
-
- In the Notebook, the containing element will be available as `element`,
- and jQuery will be available. Content appended to `element` will be
- visible in the output area.
-
- Parameters
- ----------
- data : unicode, str or bytes
- The Javascript source code or a URL to download it from.
- url : unicode
- A URL to download the data from.
- filename : unicode
- Path to a local file to load the data from.
- lib : list or str
- A sequence of Javascript library URLs to load asynchronously before
- running the source code. The full URLs of the libraries should
- be given. A single Javascript library URL can also be given as a
- string.
- css: : list or str
- A sequence of css files to load before running the source code.
- The full URLs of the css files should be given. A single css URL
- can also be given as a string.
- """
- if isinstance(lib, string_types):
- lib = [lib]
- elif lib is None:
- lib = []
- if isinstance(css, string_types):
- css = [css]
- elif css is None:
- css = []
- if not isinstance(lib, (list,tuple)):
- raise TypeError('expected sequence, got: %r' % lib)
- if not isinstance(css, (list,tuple)):
- raise TypeError('expected sequence, got: %r' % css)
- self.lib = lib
- self.css = css
- super(Javascript, self).__init__(data=data, url=url, filename=filename)
-
- def _repr_javascript_(self):
- r = ''
- for c in self.css:
- r += css_t % c
- for l in self.lib:
- r += lib_t1 % l
- r += self.data
- r += lib_t2*len(self.lib)
- return r
-
-# constants for identifying png/jpeg data
-_PNG = b'\x89PNG\r\n\x1a\n'
-_JPEG = b'\xff\xd8'
-
-def _pngxy(data):
- """read the (width, height) from a PNG header"""
- ihdr = data.index(b'IHDR')
- # next 8 bytes are width/height
- w4h4 = data[ihdr+4:ihdr+12]
- return struct.unpack('>ii', w4h4)
-
-def _jpegxy(data):
- """read the (width, height) from a JPEG header"""
- # adapted from http://www.64lines.com/jpeg-width-height
-
- idx = 4
- while True:
- block_size = struct.unpack('>H', data[idx:idx+2])[0]
- idx = idx + block_size
- if data[idx:idx+2] == b'\xFF\xC0':
- # found Start of Frame
- iSOF = idx
- break
- else:
- # read another block
- idx += 2
-
- h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
- return w, h
-
-class Image(DisplayObject):
-
- _read_flags = 'rb'
- _FMT_JPEG = u'jpeg'
- _FMT_PNG = u'png'
- _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
-
- def __init__(self, data=None, url=None, filename=None, format=None,
- embed=None, width=None, height=None, retina=False,
- unconfined=False, metadata=None):
- """Create a PNG/JPEG image object given raw data.
-
- When this object is returned by an input cell or passed to the
- display function, it will result in the image being displayed
- in the frontend.
-
- Parameters
- ----------
- data : unicode, str or bytes
- The raw image data or a URL or filename to load the data from.
- This always results in embedded image data.
- url : unicode
- A URL to download the data from. If you specify `url=`,
- the image data will not be embedded unless you also specify `embed=True`.
- filename : unicode
- Path to a local file to load the data from.
- Images from a file are always embedded.
- format : unicode
- The format of the image data (png/jpeg/jpg). If a filename or URL is given
- for format will be inferred from the filename extension.
- embed : bool
- Should the image data be embedded using a data URI (True) or be
- loaded using an <img> tag. Set this to True if you want the image
- to be viewable later with no internet connection in the notebook.
-
- Default is `True`, unless the keyword argument `url` is set, then
- default value is `False`.
-
- Note that QtConsole is not able to display images if `embed` is set to `False`
- width : int
+class JSON(DisplayObject):
+ """JSON expects a JSON-able dict or list
+
+ not an already-serialized JSON string.
+
+ Scalar types (None, number, string) are not allowed, only dict or list containers.
+ """
+ # wrap data in a property, which warns about passing already-serialized JSON
+ _data = None
+ def _check_data(self):
+ if self.data is not None and not isinstance(self.data, (dict, list)):
+ raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
+
+ @property
+ def data(self):
+ return self._data
+
+ @data.setter
+ def data(self, data):
+ if isinstance(data, string_types):
+ warnings.warn("JSON expects JSONable dict or list, not JSON strings")
+ data = json.loads(data)
+ self._data = data
+
+ def _repr_json_(self):
+ return self.data
+
+css_t = """$("head").append($("<link/>").attr({
+ rel: "stylesheet",
+ type: "text/css",
+ href: "%s"
+}));
+"""
+
+lib_t1 = """$.getScript("%s", function () {
+"""
+lib_t2 = """});
+"""
+
+class Javascript(TextDisplayObject):
+
+ def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
+ """Create a Javascript display object given raw data.
+
+ When this object is returned by an expression or passed to the
+ display function, it will result in the data being displayed
+ in the frontend. If the data is a URL, the data will first be
+ downloaded and then displayed.
+
+ In the Notebook, the containing element will be available as `element`,
+ and jQuery will be available. Content appended to `element` will be
+ visible in the output area.
+
+ Parameters
+ ----------
+ data : unicode, str or bytes
+ The Javascript source code or a URL to download it from.
+ url : unicode
+ A URL to download the data from.
+ filename : unicode
+ Path to a local file to load the data from.
+ lib : list or str
+ A sequence of Javascript library URLs to load asynchronously before
+ running the source code. The full URLs of the libraries should
+ be given. A single Javascript library URL can also be given as a
+ string.
+ css: : list or str
+ A sequence of css files to load before running the source code.
+ The full URLs of the css files should be given. A single css URL
+ can also be given as a string.
+ """
+ if isinstance(lib, string_types):
+ lib = [lib]
+ elif lib is None:
+ lib = []
+ if isinstance(css, string_types):
+ css = [css]
+ elif css is None:
+ css = []
+ if not isinstance(lib, (list,tuple)):
+ raise TypeError('expected sequence, got: %r' % lib)
+ if not isinstance(css, (list,tuple)):
+ raise TypeError('expected sequence, got: %r' % css)
+ self.lib = lib
+ self.css = css
+ super(Javascript, self).__init__(data=data, url=url, filename=filename)
+
+ def _repr_javascript_(self):
+ r = ''
+ for c in self.css:
+ r += css_t % c
+ for l in self.lib:
+ r += lib_t1 % l
+ r += self.data
+ r += lib_t2*len(self.lib)
+ return r
+
+# constants for identifying png/jpeg data
+_PNG = b'\x89PNG\r\n\x1a\n'
+_JPEG = b'\xff\xd8'
+
+def _pngxy(data):
+ """read the (width, height) from a PNG header"""
+ ihdr = data.index(b'IHDR')
+ # next 8 bytes are width/height
+ w4h4 = data[ihdr+4:ihdr+12]
+ return struct.unpack('>ii', w4h4)
+
+def _jpegxy(data):
+ """read the (width, height) from a JPEG header"""
+ # adapted from http://www.64lines.com/jpeg-width-height
+
+ idx = 4
+ while True:
+ block_size = struct.unpack('>H', data[idx:idx+2])[0]
+ idx = idx + block_size
+ if data[idx:idx+2] == b'\xFF\xC0':
+ # found Start of Frame
+ iSOF = idx
+ break
+ else:
+ # read another block
+ idx += 2
+
+ h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
+ return w, h
+
+class Image(DisplayObject):
+
+ _read_flags = 'rb'
+ _FMT_JPEG = u'jpeg'
+ _FMT_PNG = u'png'
+ _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
+
+ def __init__(self, data=None, url=None, filename=None, format=None,
+ embed=None, width=None, height=None, retina=False,
+ unconfined=False, metadata=None):
+ """Create a PNG/JPEG image object given raw data.
+
+ When this object is returned by an input cell or passed to the
+ display function, it will result in the image being displayed
+ in the frontend.
+
+ Parameters
+ ----------
+ data : unicode, str or bytes
+ The raw image data or a URL or filename to load the data from.
+ This always results in embedded image data.
+ url : unicode
+ A URL to download the data from. If you specify `url=`,
+ the image data will not be embedded unless you also specify `embed=True`.
+ filename : unicode
+ Path to a local file to load the data from.
+ Images from a file are always embedded.
+ format : unicode
+ The format of the image data (png/jpeg/jpg). If a filename or URL is given
+ for format will be inferred from the filename extension.
+ embed : bool
+ Should the image data be embedded using a data URI (True) or be
+ loaded using an <img> tag. Set this to True if you want the image
+ to be viewable later with no internet connection in the notebook.
+
+ Default is `True`, unless the keyword argument `url` is set, then
+ default value is `False`.
+
+ Note that QtConsole is not able to display images if `embed` is set to `False`
+ width : int
Width in pixels to which to constrain the image in html
- height : int
+ height : int
Height in pixels to which to constrain the image in html
- retina : bool
- Automatically set the width and height to half of the measured
- width and height.
- This only works for embedded images because it reads the width/height
- from image data.
- For non-embedded images, you can just set the desired display width
- and height directly.
- unconfined: bool
- Set unconfined=True to disable max-width confinement of the image.
- metadata: dict
- Specify extra metadata to attach to the image.
-
- Examples
- --------
- # embedded image data, works in qtconsole and notebook
- # when passed positionally, the first arg can be any of raw image data,
- # a URL, or a filename from which to load image data.
- # The result is always embedding image data for inline images.
- Image('http://www.google.fr/images/srpr/logo3w.png')
- Image('/path/to/image.jpg')
- Image(b'RAW_PNG_DATA...')
-
- # Specifying Image(url=...) does not embed the image data,
- # it only generates `<img>` tag with a link to the source.
- # This will not work in the qtconsole or offline.
- Image(url='http://www.google.fr/images/srpr/logo3w.png')
-
- """
- if filename is not None:
- ext = self._find_ext(filename)
- elif url is not None:
- ext = self._find_ext(url)
- elif data is None:
- raise ValueError("No image data found. Expecting filename, url, or data.")
- elif isinstance(data, string_types) and (
- data.startswith('http') or _safe_exists(data)
- ):
- ext = self._find_ext(data)
- else:
- ext = None
-
- if format is None:
- if ext is not None:
- if ext == u'jpg' or ext == u'jpeg':
- format = self._FMT_JPEG
+ retina : bool
+ Automatically set the width and height to half of the measured
+ width and height.
+ This only works for embedded images because it reads the width/height
+ from image data.
+ For non-embedded images, you can just set the desired display width
+ and height directly.
+ unconfined: bool
+ Set unconfined=True to disable max-width confinement of the image.
+ metadata: dict
+ Specify extra metadata to attach to the image.
+
+ Examples
+ --------
+ # embedded image data, works in qtconsole and notebook
+ # when passed positionally, the first arg can be any of raw image data,
+ # a URL, or a filename from which to load image data.
+ # The result is always embedding image data for inline images.
+ Image('http://www.google.fr/images/srpr/logo3w.png')
+ Image('/path/to/image.jpg')
+ Image(b'RAW_PNG_DATA...')
+
+ # Specifying Image(url=...) does not embed the image data,
+ # it only generates `<img>` tag with a link to the source.
+ # This will not work in the qtconsole or offline.
+ Image(url='http://www.google.fr/images/srpr/logo3w.png')
+
+ """
+ if filename is not None:
+ ext = self._find_ext(filename)
+ elif url is not None:
+ ext = self._find_ext(url)
+ elif data is None:
+ raise ValueError("No image data found. Expecting filename, url, or data.")
+ elif isinstance(data, string_types) and (
+ data.startswith('http') or _safe_exists(data)
+ ):
+ ext = self._find_ext(data)
+ else:
+ ext = None
+
+ if format is None:
+ if ext is not None:
+ if ext == u'jpg' or ext == u'jpeg':
+ format = self._FMT_JPEG
elif ext == u'png':
- format = self._FMT_PNG
- else:
- format = ext.lower()
- elif isinstance(data, bytes):
- # infer image type from image data header,
- # only if format has not been specified.
- if data[:2] == _JPEG:
- format = self._FMT_JPEG
-
- # failed to detect format, default png
- if format is None:
- format = 'png'
-
- if format.lower() == 'jpg':
- # jpg->jpeg
- format = self._FMT_JPEG
-
- self.format = unicode_type(format).lower()
- self.embed = embed if embed is not None else (url is None)
-
- if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
- raise ValueError("Cannot embed the '%s' image format" % (self.format))
- self.width = width
- self.height = height
- self.retina = retina
- self.unconfined = unconfined
- self.metadata = metadata
- super(Image, self).__init__(data=data, url=url, filename=filename)
-
- if retina:
- self._retina_shape()
-
- def _retina_shape(self):
- """load pixel-doubled width and height from image data"""
- if not self.embed:
- return
- if self.format == 'png':
- w, h = _pngxy(self.data)
- elif self.format == 'jpeg':
- w, h = _jpegxy(self.data)
- else:
- # retina only supports png
- return
- self.width = w // 2
- self.height = h // 2
-
- def reload(self):
- """Reload the raw data from file or URL."""
- if self.embed:
- super(Image,self).reload()
- if self.retina:
- self._retina_shape()
-
- def _repr_html_(self):
- if not self.embed:
- width = height = klass = ''
- if self.width:
- width = ' width="%d"' % self.width
- if self.height:
- height = ' height="%d"' % self.height
- if self.unconfined:
- klass = ' class="unconfined"'
- return u'<img src="{url}"{width}{height}{klass}/>'.format(
- url=self.url,
- width=width,
- height=height,
- klass=klass,
- )
-
- def _data_and_metadata(self):
- """shortcut for returning metadata with shape information, if defined"""
- md = {}
- if self.width:
- md['width'] = self.width
- if self.height:
- md['height'] = self.height
- if self.unconfined:
- md['unconfined'] = self.unconfined
- if self.metadata:
- md.update(self.metadata)
- if md:
- return self.data, md
- else:
- return self.data
-
- def _repr_png_(self):
- if self.embed and self.format == u'png':
- return self._data_and_metadata()
-
- def _repr_jpeg_(self):
- if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
- return self._data_and_metadata()
-
- def _find_ext(self, s):
- return unicode_type(s.split('.')[-1].lower())
-
-class Video(DisplayObject):
-
+ format = self._FMT_PNG
+ else:
+ format = ext.lower()
+ elif isinstance(data, bytes):
+ # infer image type from image data header,
+ # only if format has not been specified.
+ if data[:2] == _JPEG:
+ format = self._FMT_JPEG
+
+ # failed to detect format, default png
+ if format is None:
+ format = 'png'
+
+ if format.lower() == 'jpg':
+ # jpg->jpeg
+ format = self._FMT_JPEG
+
+ self.format = unicode_type(format).lower()
+ self.embed = embed if embed is not None else (url is None)
+
+ if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
+ raise ValueError("Cannot embed the '%s' image format" % (self.format))
+ self.width = width
+ self.height = height
+ self.retina = retina
+ self.unconfined = unconfined
+ self.metadata = metadata
+ super(Image, self).__init__(data=data, url=url, filename=filename)
+
+ if retina:
+ self._retina_shape()
+
+ def _retina_shape(self):
+ """load pixel-doubled width and height from image data"""
+ if not self.embed:
+ return
+ if self.format == 'png':
+ w, h = _pngxy(self.data)
+ elif self.format == 'jpeg':
+ w, h = _jpegxy(self.data)
+ else:
+ # retina only supports png
+ return
+ self.width = w // 2
+ self.height = h // 2
+
+ def reload(self):
+ """Reload the raw data from file or URL."""
+ if self.embed:
+ super(Image,self).reload()
+ if self.retina:
+ self._retina_shape()
+
+ def _repr_html_(self):
+ if not self.embed:
+ width = height = klass = ''
+ if self.width:
+ width = ' width="%d"' % self.width
+ if self.height:
+ height = ' height="%d"' % self.height
+ if self.unconfined:
+ klass = ' class="unconfined"'
+ return u'<img src="{url}"{width}{height}{klass}/>'.format(
+ url=self.url,
+ width=width,
+ height=height,
+ klass=klass,
+ )
+
+ def _data_and_metadata(self):
+ """shortcut for returning metadata with shape information, if defined"""
+ md = {}
+ if self.width:
+ md['width'] = self.width
+ if self.height:
+ md['height'] = self.height
+ if self.unconfined:
+ md['unconfined'] = self.unconfined
+ if self.metadata:
+ md.update(self.metadata)
+ if md:
+ return self.data, md
+ else:
+ return self.data
+
+ def _repr_png_(self):
+ if self.embed and self.format == u'png':
+ return self._data_and_metadata()
+
+ def _repr_jpeg_(self):
+ if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
+ return self._data_and_metadata()
+
+ def _find_ext(self, s):
+ return unicode_type(s.split('.')[-1].lower())
+
+class Video(DisplayObject):
+
def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
- """Create a video object given raw data or an URL.
-
- When this object is returned by an input cell or passed to the
- display function, it will result in the video being displayed
- in the frontend.
-
- Parameters
- ----------
- data : unicode, str or bytes
+ """Create a video object given raw data or an URL.
+
+ When this object is returned by an input cell or passed to the
+ display function, it will result in the video being displayed
+ in the frontend.
+
+ Parameters
+ ----------
+ data : unicode, str or bytes
The raw video data or a URL or filename to load the data from.
Raw data will require passing `embed=True`.
- url : unicode
+ url : unicode
A URL for the video. If you specify `url=`,
the image data will not be embedded.
- filename : unicode
+ filename : unicode
Path to a local file containing the video.
Will be interpreted as a local URL unless `embed=True`.
- embed : bool
+ embed : bool
Should the video be embedded using a data URI (True) or be
loaded using a <video> tag (False).
-
+
Since videos are large, embedding them should be avoided, if possible.
You must confirm embedding as your intention by passing `embed=True`.
-
+
Local files can be displayed with URLs without embedding the content, via::
Video('./video.mp4')
- mimetype: unicode
+ mimetype: unicode
Specify the mimetype for embedded videos.
Default will be guessed from file extension, if available.
- Examples
- --------
+ Examples
+ --------
- Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
- Video('path/to/video.mp4')
+ Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
+ Video('path/to/video.mp4')
Video('path/to/video.mp4', embed=True)
Video(b'raw-videodata', embed=True)
- """
+ """
if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')):
- url = data
- data = None
- elif os.path.exists(data):
- filename = data
- data = None
+ url = data
+ data = None
+ elif os.path.exists(data):
+ filename = data
+ data = None
if data and not embed:
msg = ''.join([
@@ -1166,30 +1166,30 @@ class Video(DisplayObject):
"Consider passing Video(url='...')",
])
raise ValueError(msg)
-
- self.mimetype = mimetype
+
+ self.mimetype = mimetype
self.embed = embed
- super(Video, self).__init__(data=data, url=url, filename=filename)
-
- def _repr_html_(self):
- # External URLs and potentially local files are not embedded into the
- # notebook output.
- if not self.embed:
- url = self.url if self.url is not None else self.filename
- output = """<video src="{0}" controls>
- Your browser does not support the <code>video</code> element.
- </video>""".format(url)
- return output
+ super(Video, self).__init__(data=data, url=url, filename=filename)
+
+ def _repr_html_(self):
+ # External URLs and potentially local files are not embedded into the
+ # notebook output.
+ if not self.embed:
+ url = self.url if self.url is not None else self.filename
+ output = """<video src="{0}" controls>
+ Your browser does not support the <code>video</code> element.
+ </video>""".format(url)
+ return output
# Embedded videos are base64-encoded.
mimetype = self.mimetype
- if self.filename is not None:
+ if self.filename is not None:
if not mimetype:
mimetype, _ = mimetypes.guess_type(self.filename)
with open(self.filename, 'rb') as f:
video = f.read()
- else:
+ else:
video = self.data
if isinstance(video, unicode_type):
# unicode input is already b64-encoded
@@ -1197,94 +1197,94 @@ class Video(DisplayObject):
else:
b64_video = base64_encode(video).decode('ascii').rstrip()
- output = """<video controls>
- <source src="data:{0};base64,{1}" type="{0}">
- Your browser does not support the video tag.
+ output = """<video controls>
+ <source src="data:{0};base64,{1}" type="{0}">
+ Your browser does not support the video tag.
</video>""".format(mimetype, b64_video)
- return output
-
- def reload(self):
- # TODO
- pass
-
- def _repr_png_(self):
- # TODO
- pass
- def _repr_jpeg_(self):
- # TODO
- pass
-
-def clear_output(wait=False):
- """Clear the output of the current cell receiving output.
-
- Parameters
- ----------
- wait : bool [default: false]
- Wait to clear the output until new output is available to replace it."""
- from IPython.core.interactiveshell import InteractiveShell
- if InteractiveShell.initialized():
- InteractiveShell.instance().display_pub.clear_output(wait)
- else:
+ return output
+
+ def reload(self):
+ # TODO
+ pass
+
+ def _repr_png_(self):
+ # TODO
+ pass
+ def _repr_jpeg_(self):
+ # TODO
+ pass
+
+def clear_output(wait=False):
+ """Clear the output of the current cell receiving output.
+
+ Parameters
+ ----------
+ wait : bool [default: false]
+ Wait to clear the output until new output is available to replace it."""
+ from IPython.core.interactiveshell import InteractiveShell
+ if InteractiveShell.initialized():
+ InteractiveShell.instance().display_pub.clear_output(wait)
+ else:
print('\033[2K\r', end='')
sys.stdout.flush()
print('\033[2K\r', end='')
sys.stderr.flush()
-
-
-@skip_doctest
-def set_matplotlib_formats(*formats, **kwargs):
- """Select figure formats for the inline backend. Optionally pass quality for JPEG.
-
- For example, this enables PNG and JPEG output with a JPEG quality of 90%::
-
- In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
-
- To set this in your config files use the following::
-
- c.InlineBackend.figure_formats = {'png', 'jpeg'}
- c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
-
- Parameters
- ----------
- *formats : strs
- One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
- **kwargs :
- Keyword args will be relayed to ``figure.canvas.print_figure``.
- """
- from IPython.core.interactiveshell import InteractiveShell
- from IPython.core.pylabtools import select_figure_formats
- # build kwargs, starting with InlineBackend config
- kw = {}
- from ipykernel.pylab.config import InlineBackend
- cfg = InlineBackend.instance()
- kw.update(cfg.print_figure_kwargs)
- kw.update(**kwargs)
- shell = InteractiveShell.instance()
- select_figure_formats(shell, formats, **kw)
-
-@skip_doctest
-def set_matplotlib_close(close=True):
- """Set whether the inline backend closes all figures automatically or not.
-
- By default, the inline backend used in the IPython Notebook will close all
- matplotlib figures automatically after each cell is run. This means that
- plots in different cells won't interfere. Sometimes, you may want to make
- a plot in one cell and then refine it in later cells. This can be accomplished
- by::
-
- In [1]: set_matplotlib_close(False)
-
- To set this in your config files use the following::
-
- c.InlineBackend.close_figures = False
-
- Parameters
- ----------
- close : bool
- Should all matplotlib figures be automatically closed after each cell is
- run?
- """
- from ipykernel.pylab.config import InlineBackend
- cfg = InlineBackend.instance()
- cfg.close_figures = close
-
+
+
+@skip_doctest
+def set_matplotlib_formats(*formats, **kwargs):
+ """Select figure formats for the inline backend. Optionally pass quality for JPEG.
+
+ For example, this enables PNG and JPEG output with a JPEG quality of 90%::
+
+ In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
+
+ To set this in your config files use the following::
+
+ c.InlineBackend.figure_formats = {'png', 'jpeg'}
+ c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
+
+ Parameters
+ ----------
+ *formats : strs
+ One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
+ **kwargs :
+ Keyword args will be relayed to ``figure.canvas.print_figure``.
+ """
+ from IPython.core.interactiveshell import InteractiveShell
+ from IPython.core.pylabtools import select_figure_formats
+ # build kwargs, starting with InlineBackend config
+ kw = {}
+ from ipykernel.pylab.config import InlineBackend
+ cfg = InlineBackend.instance()
+ kw.update(cfg.print_figure_kwargs)
+ kw.update(**kwargs)
+ shell = InteractiveShell.instance()
+ select_figure_formats(shell, formats, **kw)
+
+@skip_doctest
+def set_matplotlib_close(close=True):
+ """Set whether the inline backend closes all figures automatically or not.
+
+ By default, the inline backend used in the IPython Notebook will close all
+ matplotlib figures automatically after each cell is run. This means that
+ plots in different cells won't interfere. Sometimes, you may want to make
+ a plot in one cell and then refine it in later cells. This can be accomplished
+ by::
+
+ In [1]: set_matplotlib_close(False)
+
+ To set this in your config files use the following::
+
+ c.InlineBackend.close_figures = False
+
+ Parameters
+ ----------
+ close : bool
+ Should all matplotlib figures be automatically closed after each cell is
+ run?
+ """
+ from ipykernel.pylab.config import InlineBackend
+ cfg = InlineBackend.instance()
+ cfg.close_figures = close
+
diff --git a/contrib/python/ipython/py2/IPython/core/display_trap.py b/contrib/python/ipython/py2/IPython/core/display_trap.py
index 7a48a5e119..9931dfe2df 100644
--- a/contrib/python/ipython/py2/IPython/core/display_trap.py
+++ b/contrib/python/ipython/py2/IPython/core/display_trap.py
@@ -1,70 +1,70 @@
-# encoding: utf-8
-"""
-A context manager for handling sys.displayhook.
-
-Authors:
-
-* Robert Kern
-* Brian Granger
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import sys
-
-from traitlets.config.configurable import Configurable
-from traitlets import Any
-
-#-----------------------------------------------------------------------------
-# Classes and functions
-#-----------------------------------------------------------------------------
-
-
-class DisplayTrap(Configurable):
- """Object to manage sys.displayhook.
-
- This came from IPython.core.kernel.display_hook, but is simplified
- (no callbacks or formatters) until more of the core is refactored.
- """
-
- hook = Any()
-
- def __init__(self, hook=None):
- super(DisplayTrap, self).__init__(hook=hook, config=None)
- self.old_hook = None
- # We define this to track if a single BuiltinTrap is nested.
- # Only turn off the trap when the outermost call to __exit__ is made.
- self._nested_level = 0
-
- def __enter__(self):
- if self._nested_level == 0:
- self.set()
- self._nested_level += 1
- return self
-
- def __exit__(self, type, value, traceback):
- if self._nested_level == 1:
- self.unset()
- self._nested_level -= 1
- # Returning False will cause exceptions to propagate
- return False
-
- def set(self):
- """Set the hook."""
- if sys.displayhook is not self.hook:
- self.old_hook = sys.displayhook
- sys.displayhook = self.hook
-
- def unset(self):
- """Unset the hook."""
- sys.displayhook = self.old_hook
-
+# encoding: utf-8
+"""
+A context manager for handling sys.displayhook.
+
+Authors:
+
+* Robert Kern
+* Brian Granger
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import sys
+
+from traitlets.config.configurable import Configurable
+from traitlets import Any
+
+#-----------------------------------------------------------------------------
+# Classes and functions
+#-----------------------------------------------------------------------------
+
+
+class DisplayTrap(Configurable):
+ """Object to manage sys.displayhook.
+
+ This came from IPython.core.kernel.display_hook, but is simplified
+ (no callbacks or formatters) until more of the core is refactored.
+ """
+
+ hook = Any()
+
+ def __init__(self, hook=None):
+ super(DisplayTrap, self).__init__(hook=hook, config=None)
+ self.old_hook = None
+ # We define this to track if a single BuiltinTrap is nested.
+ # Only turn off the trap when the outermost call to __exit__ is made.
+ self._nested_level = 0
+
+ def __enter__(self):
+ if self._nested_level == 0:
+ self.set()
+ self._nested_level += 1
+ return self
+
+ def __exit__(self, type, value, traceback):
+ if self._nested_level == 1:
+ self.unset()
+ self._nested_level -= 1
+ # Returning False will cause exceptions to propagate
+ return False
+
+ def set(self):
+ """Set the hook."""
+ if sys.displayhook is not self.hook:
+ self.old_hook = sys.displayhook
+ sys.displayhook = self.hook
+
+ def unset(self):
+ """Unset the hook."""
+ sys.displayhook = self.old_hook
+
diff --git a/contrib/python/ipython/py2/IPython/core/displayhook.py b/contrib/python/ipython/py2/IPython/core/displayhook.py
index e2a6b0547d..cce7c83d16 100644
--- a/contrib/python/ipython/py2/IPython/core/displayhook.py
+++ b/contrib/python/ipython/py2/IPython/core/displayhook.py
@@ -1,298 +1,298 @@
-# -*- coding: utf-8 -*-
-"""Displayhook for IPython.
-
-This defines a callable class that IPython uses for `sys.displayhook`.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
-import sys
-import io as _io
-import tokenize
-
-from traitlets.config.configurable import Configurable
-from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
-from traitlets import Instance, Float
+# -*- coding: utf-8 -*-
+"""Displayhook for IPython.
+
+This defines a callable class that IPython uses for `sys.displayhook`.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
+import sys
+import io as _io
+import tokenize
+
+from traitlets.config.configurable import Configurable
+from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
+from traitlets import Instance, Float
from warnings import warn
-
-# TODO: Move the various attributes (cache_size, [others now moved]). Some
-# of these are also attributes of InteractiveShell. They should be on ONE object
-# only and the other objects should ask that one object for their values.
-
-class DisplayHook(Configurable):
- """The custom IPython displayhook to replace sys.displayhook.
-
- This class does many things, but the basic idea is that it is a callable
- that gets called anytime user code returns a value.
- """
-
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
- allow_none=True)
- exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
- allow_none=True)
- cull_fraction = Float(0.2)
-
- def __init__(self, shell=None, cache_size=1000, **kwargs):
- super(DisplayHook, self).__init__(shell=shell, **kwargs)
- cache_size_min = 3
- if cache_size <= 0:
- self.do_full_cache = 0
- cache_size = 0
- elif cache_size < cache_size_min:
- self.do_full_cache = 0
- cache_size = 0
- warn('caching was disabled (min value for cache size is %s).' %
+
+# TODO: Move the various attributes (cache_size, [others now moved]). Some
+# of these are also attributes of InteractiveShell. They should be on ONE object
+# only and the other objects should ask that one object for their values.
+
+class DisplayHook(Configurable):
+ """The custom IPython displayhook to replace sys.displayhook.
+
+ This class does many things, but the basic idea is that it is a callable
+ that gets called anytime user code returns a value.
+ """
+
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
+ allow_none=True)
+ exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
+ allow_none=True)
+ cull_fraction = Float(0.2)
+
+ def __init__(self, shell=None, cache_size=1000, **kwargs):
+ super(DisplayHook, self).__init__(shell=shell, **kwargs)
+ cache_size_min = 3
+ if cache_size <= 0:
+ self.do_full_cache = 0
+ cache_size = 0
+ elif cache_size < cache_size_min:
+ self.do_full_cache = 0
+ cache_size = 0
+ warn('caching was disabled (min value for cache size is %s).' %
cache_size_min,stacklevel=3)
- else:
- self.do_full_cache = 1
-
- self.cache_size = cache_size
-
- # we need a reference to the user-level namespace
- self.shell = shell
-
- self._,self.__,self.___ = '','',''
-
- # these are deliberately global:
- to_user_ns = {'_':self._,'__':self.__,'___':self.___}
- self.shell.user_ns.update(to_user_ns)
-
- @property
- def prompt_count(self):
- return self.shell.execution_count
-
- #-------------------------------------------------------------------------
- # Methods used in __call__. Override these methods to modify the behavior
- # of the displayhook.
- #-------------------------------------------------------------------------
-
- def check_for_underscore(self):
- """Check if the user has set the '_' variable by hand."""
- # If something injected a '_' variable in __builtin__, delete
- # ipython's automatic one so we don't clobber that. gettext() in
- # particular uses _, so we need to stay away from it.
- if '_' in builtin_mod.__dict__:
- try:
- del self.shell.user_ns['_']
- except KeyError:
- pass
-
- def quiet(self):
- """Should we silence the display hook because of ';'?"""
- # do not print output if input ends in ';'
-
- try:
- cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1])
- except IndexError:
- # some uses of ipshellembed may fail here
- return False
-
- sio = _io.StringIO(cell)
- tokens = list(tokenize.generate_tokens(sio.readline))
-
- for token in reversed(tokens):
+ else:
+ self.do_full_cache = 1
+
+ self.cache_size = cache_size
+
+ # we need a reference to the user-level namespace
+ self.shell = shell
+
+ self._,self.__,self.___ = '','',''
+
+ # these are deliberately global:
+ to_user_ns = {'_':self._,'__':self.__,'___':self.___}
+ self.shell.user_ns.update(to_user_ns)
+
+ @property
+ def prompt_count(self):
+ return self.shell.execution_count
+
+ #-------------------------------------------------------------------------
+ # Methods used in __call__. Override these methods to modify the behavior
+ # of the displayhook.
+ #-------------------------------------------------------------------------
+
+ def check_for_underscore(self):
+ """Check if the user has set the '_' variable by hand."""
+ # If something injected a '_' variable in __builtin__, delete
+ # ipython's automatic one so we don't clobber that. gettext() in
+ # particular uses _, so we need to stay away from it.
+ if '_' in builtin_mod.__dict__:
+ try:
+ del self.shell.user_ns['_']
+ except KeyError:
+ pass
+
+ def quiet(self):
+ """Should we silence the display hook because of ';'?"""
+ # do not print output if input ends in ';'
+
+ try:
+ cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1])
+ except IndexError:
+ # some uses of ipshellembed may fail here
+ return False
+
+ sio = _io.StringIO(cell)
+ tokens = list(tokenize.generate_tokens(sio.readline))
+
+ for token in reversed(tokens):
if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
- continue
- if (token[0] == tokenize.OP) and (token[1] == ';'):
- return True
- else:
- return False
-
- def start_displayhook(self):
- """Start the displayhook, initializing resources."""
- pass
-
- def write_output_prompt(self):
- """Write the output prompt.
-
- The default implementation simply writes the prompt to
+ continue
+ if (token[0] == tokenize.OP) and (token[1] == ';'):
+ return True
+ else:
+ return False
+
+ def start_displayhook(self):
+ """Start the displayhook, initializing resources."""
+ pass
+
+ def write_output_prompt(self):
+ """Write the output prompt.
+
+ The default implementation simply writes the prompt to
``sys.stdout``.
- """
- # Use write, not print which adds an extra space.
+ """
+ # Use write, not print which adds an extra space.
sys.stdout.write(self.shell.separate_out)
outprompt = 'Out[{}]: '.format(self.shell.execution_count)
- if self.do_full_cache:
+ if self.do_full_cache:
sys.stdout.write(outprompt)
-
- def compute_format_data(self, result):
- """Compute format data of the object to be displayed.
-
- The format data is a generalization of the :func:`repr` of an object.
- In the default implementation the format data is a :class:`dict` of
- key value pair where the keys are valid MIME types and the values
- are JSON'able data structure containing the raw data for that MIME
- type. It is up to frontends to determine pick a MIME to to use and
- display that data in an appropriate manner.
-
- This method only computes the format data for the object and should
- NOT actually print or write that to a stream.
-
- Parameters
- ----------
- result : object
- The Python object passed to the display hook, whose format will be
- computed.
-
- Returns
- -------
- (format_dict, md_dict) : dict
- format_dict is a :class:`dict` whose keys are valid MIME types and values are
- JSON'able raw data for that MIME type. It is recommended that
- all return values of this should always include the "text/plain"
- MIME type representation of the object.
- md_dict is a :class:`dict` with the same MIME type keys
- of metadata associated with each output.
-
- """
- return self.shell.display_formatter.format(result)
-
+
+ def compute_format_data(self, result):
+ """Compute format data of the object to be displayed.
+
+ The format data is a generalization of the :func:`repr` of an object.
+ In the default implementation the format data is a :class:`dict` of
+ key value pair where the keys are valid MIME types and the values
+ are JSON'able data structure containing the raw data for that MIME
+ type. It is up to frontends to determine pick a MIME to to use and
+ display that data in an appropriate manner.
+
+ This method only computes the format data for the object and should
+ NOT actually print or write that to a stream.
+
+ Parameters
+ ----------
+ result : object
+ The Python object passed to the display hook, whose format will be
+ computed.
+
+ Returns
+ -------
+ (format_dict, md_dict) : dict
+ format_dict is a :class:`dict` whose keys are valid MIME types and values are
+ JSON'able raw data for that MIME type. It is recommended that
+ all return values of this should always include the "text/plain"
+ MIME type representation of the object.
+ md_dict is a :class:`dict` with the same MIME type keys
+ of metadata associated with each output.
+
+ """
+ return self.shell.display_formatter.format(result)
+
# This can be set to True by the write_output_prompt method in a subclass
prompt_end_newline = False
- def write_format_data(self, format_dict, md_dict=None):
- """Write the format data dict to the frontend.
-
- This default version of this method simply writes the plain text
+ def write_format_data(self, format_dict, md_dict=None):
+ """Write the format data dict to the frontend.
+
+ This default version of this method simply writes the plain text
representation of the object to ``sys.stdout``. Subclasses should
- override this method to send the entire `format_dict` to the
- frontends.
-
- Parameters
- ----------
- format_dict : dict
- The format dict for the object passed to `sys.displayhook`.
- md_dict : dict (optional)
- The metadata dict to be associated with the display data.
- """
- if 'text/plain' not in format_dict:
- # nothing to do
- return
- # We want to print because we want to always make sure we have a
- # newline, even if all the prompt separators are ''. This is the
- # standard IPython behavior.
- result_repr = format_dict['text/plain']
- if '\n' in result_repr:
- # So that multi-line strings line up with the left column of
- # the screen, instead of having the output prompt mess up
- # their first line.
- # We use the prompt template instead of the expanded prompt
- # because the expansion may add ANSI escapes that will interfere
- # with our ability to determine whether or not we should add
- # a newline.
+ override this method to send the entire `format_dict` to the
+ frontends.
+
+ Parameters
+ ----------
+ format_dict : dict
+ The format dict for the object passed to `sys.displayhook`.
+ md_dict : dict (optional)
+ The metadata dict to be associated with the display data.
+ """
+ if 'text/plain' not in format_dict:
+ # nothing to do
+ return
+ # We want to print because we want to always make sure we have a
+ # newline, even if all the prompt separators are ''. This is the
+ # standard IPython behavior.
+ result_repr = format_dict['text/plain']
+ if '\n' in result_repr:
+ # So that multi-line strings line up with the left column of
+ # the screen, instead of having the output prompt mess up
+ # their first line.
+ # We use the prompt template instead of the expanded prompt
+ # because the expansion may add ANSI escapes that will interfere
+ # with our ability to determine whether or not we should add
+ # a newline.
if not self.prompt_end_newline:
- # But avoid extraneous empty lines.
- result_repr = '\n' + result_repr
-
+ # But avoid extraneous empty lines.
+ result_repr = '\n' + result_repr
+
print(result_repr)
-
- def update_user_ns(self, result):
- """Update user_ns with various things like _, __, _1, etc."""
-
- # Avoid recursive reference when displaying _oh/Out
- if result is not self.shell.user_ns['_oh']:
- if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
- self.cull_cache()
- # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
- # we cause buggy behavior for things like gettext).
-
- if '_' not in builtin_mod.__dict__:
- self.___ = self.__
- self.__ = self._
- self._ = result
- self.shell.push({'_':self._,
- '__':self.__,
- '___':self.___}, interactive=False)
-
- # hackish access to top-level namespace to create _1,_2... dynamically
- to_main = {}
- if self.do_full_cache:
- new_result = '_'+repr(self.prompt_count)
- to_main[new_result] = result
- self.shell.push(to_main, interactive=False)
- self.shell.user_ns['_oh'][self.prompt_count] = result
-
- def fill_exec_result(self, result):
- if self.exec_result is not None:
- self.exec_result.result = result
-
- def log_output(self, format_dict):
- """Log the output."""
- if 'text/plain' not in format_dict:
- # nothing to do
- return
- if self.shell.logger.log_output:
- self.shell.logger.log_write(format_dict['text/plain'], 'output')
- self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
- format_dict['text/plain']
-
- def finish_displayhook(self):
- """Finish up all displayhook activities."""
+
+ def update_user_ns(self, result):
+ """Update user_ns with various things like _, __, _1, etc."""
+
+ # Avoid recursive reference when displaying _oh/Out
+ if result is not self.shell.user_ns['_oh']:
+ if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
+ self.cull_cache()
+ # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
+ # we cause buggy behavior for things like gettext).
+
+ if '_' not in builtin_mod.__dict__:
+ self.___ = self.__
+ self.__ = self._
+ self._ = result
+ self.shell.push({'_':self._,
+ '__':self.__,
+ '___':self.___}, interactive=False)
+
+ # hackish access to top-level namespace to create _1,_2... dynamically
+ to_main = {}
+ if self.do_full_cache:
+ new_result = '_'+repr(self.prompt_count)
+ to_main[new_result] = result
+ self.shell.push(to_main, interactive=False)
+ self.shell.user_ns['_oh'][self.prompt_count] = result
+
+ def fill_exec_result(self, result):
+ if self.exec_result is not None:
+ self.exec_result.result = result
+
+ def log_output(self, format_dict):
+ """Log the output."""
+ if 'text/plain' not in format_dict:
+ # nothing to do
+ return
+ if self.shell.logger.log_output:
+ self.shell.logger.log_write(format_dict['text/plain'], 'output')
+ self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
+ format_dict['text/plain']
+
+ def finish_displayhook(self):
+ """Finish up all displayhook activities."""
sys.stdout.write(self.shell.separate_out2)
sys.stdout.flush()
-
- def __call__(self, result=None):
- """Printing with history cache management.
-
- This is invoked everytime the interpreter needs to print, and is
- activated by setting the variable sys.displayhook to it.
- """
- self.check_for_underscore()
- if result is not None and not self.quiet():
- self.start_displayhook()
- self.write_output_prompt()
- format_dict, md_dict = self.compute_format_data(result)
- self.update_user_ns(result)
- self.fill_exec_result(result)
- if format_dict:
- self.write_format_data(format_dict, md_dict)
- self.log_output(format_dict)
- self.finish_displayhook()
-
- def cull_cache(self):
- """Output cache is full, cull the oldest entries"""
- oh = self.shell.user_ns.get('_oh', {})
- sz = len(oh)
- cull_count = max(int(sz * self.cull_fraction), 2)
- warn('Output cache limit (currently {sz} entries) hit.\n'
- 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
-
- for i, n in enumerate(sorted(oh)):
- if i >= cull_count:
- break
- self.shell.user_ns.pop('_%i' % n, None)
- oh.pop(n, None)
-
-
- def flush(self):
- if not self.do_full_cache:
- raise ValueError("You shouldn't have reached the cache flush "
- "if full caching is not enabled!")
- # delete auto-generated vars from global namespace
-
- for n in range(1,self.prompt_count + 1):
- key = '_'+repr(n)
- try:
- del self.shell.user_ns[key]
- except: pass
- # In some embedded circumstances, the user_ns doesn't have the
- # '_oh' key set up.
- oh = self.shell.user_ns.get('_oh', None)
- if oh is not None:
- oh.clear()
-
- # Release our own references to objects:
- self._, self.__, self.___ = '', '', ''
-
- if '_' not in builtin_mod.__dict__:
- self.shell.user_ns.update({'_':None,'__':None, '___':None})
- import gc
- # TODO: Is this really needed?
- # IronPython blocks here forever
- if sys.platform != "cli":
- gc.collect()
+
+ def __call__(self, result=None):
+ """Printing with history cache management.
+
+ This is invoked everytime the interpreter needs to print, and is
+ activated by setting the variable sys.displayhook to it.
+ """
+ self.check_for_underscore()
+ if result is not None and not self.quiet():
+ self.start_displayhook()
+ self.write_output_prompt()
+ format_dict, md_dict = self.compute_format_data(result)
+ self.update_user_ns(result)
+ self.fill_exec_result(result)
+ if format_dict:
+ self.write_format_data(format_dict, md_dict)
+ self.log_output(format_dict)
+ self.finish_displayhook()
+
+ def cull_cache(self):
+ """Output cache is full, cull the oldest entries"""
+ oh = self.shell.user_ns.get('_oh', {})
+ sz = len(oh)
+ cull_count = max(int(sz * self.cull_fraction), 2)
+ warn('Output cache limit (currently {sz} entries) hit.\n'
+ 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
+
+ for i, n in enumerate(sorted(oh)):
+ if i >= cull_count:
+ break
+ self.shell.user_ns.pop('_%i' % n, None)
+ oh.pop(n, None)
+
+
+ def flush(self):
+ if not self.do_full_cache:
+ raise ValueError("You shouldn't have reached the cache flush "
+ "if full caching is not enabled!")
+ # delete auto-generated vars from global namespace
+
+ for n in range(1,self.prompt_count + 1):
+ key = '_'+repr(n)
+ try:
+ del self.shell.user_ns[key]
+ except: pass
+ # In some embedded circumstances, the user_ns doesn't have the
+ # '_oh' key set up.
+ oh = self.shell.user_ns.get('_oh', None)
+ if oh is not None:
+ oh.clear()
+
+ # Release our own references to objects:
+ self._, self.__, self.___ = '', '', ''
+
+ if '_' not in builtin_mod.__dict__:
+ self.shell.user_ns.update({'_':None,'__':None, '___':None})
+ import gc
+ # TODO: Is this really needed?
+ # IronPython blocks here forever
+ if sys.platform != "cli":
+ gc.collect()
class CapturingDisplayHook(object):
diff --git a/contrib/python/ipython/py2/IPython/core/displaypub.py b/contrib/python/ipython/py2/IPython/core/displaypub.py
index b417aab40f..82a859ae15 100644
--- a/contrib/python/ipython/py2/IPython/core/displaypub.py
+++ b/contrib/python/ipython/py2/IPython/core/displaypub.py
@@ -1,95 +1,95 @@
-"""An interface for publishing rich data to frontends.
-
-There are two components of the display system:
-
-* Display formatters, which take a Python object and compute the
- representation of the object in various formats (text, HTML, SVG, etc.).
-* The display publisher that is used to send the representation data to the
- various frontends.
-
-This module defines the logic display publishing. The display publisher uses
-the ``display_data`` message type that is defined in the IPython messaging
-spec.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
+"""An interface for publishing rich data to frontends.
+
+There are two components of the display system:
+
+* Display formatters, which take a Python object and compute the
+ representation of the object in various formats (text, HTML, SVG, etc.).
+* The display publisher that is used to send the representation data to the
+ various frontends.
+
+This module defines the logic display publishing. The display publisher uses
+the ``display_data`` message type that is defined in the IPython messaging
+spec.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
import sys
-from traitlets.config.configurable import Configurable
-from traitlets import List
-
-# This used to be defined here - it is imported for backwards compatibility
-from .display import publish_display_data
-
-#-----------------------------------------------------------------------------
-# Main payload class
-#-----------------------------------------------------------------------------
-
-class DisplayPublisher(Configurable):
- """A traited class that publishes display data to frontends.
-
- Instances of this class are created by the main IPython object and should
- be accessed there.
- """
-
- def _validate_data(self, data, metadata=None):
- """Validate the display data.
-
- Parameters
- ----------
- data : dict
- The formata data dictionary.
- metadata : dict
- Any metadata for the data.
- """
-
- if not isinstance(data, dict):
- raise TypeError('data must be a dict, got: %r' % data)
- if metadata is not None:
- if not isinstance(metadata, dict):
- raise TypeError('metadata must be a dict, got: %r' % data)
-
+from traitlets.config.configurable import Configurable
+from traitlets import List
+
+# This used to be defined here - it is imported for backwards compatibility
+from .display import publish_display_data
+
+#-----------------------------------------------------------------------------
+# Main payload class
+#-----------------------------------------------------------------------------
+
+class DisplayPublisher(Configurable):
+ """A traited class that publishes display data to frontends.
+
+ Instances of this class are created by the main IPython object and should
+ be accessed there.
+ """
+
+ def _validate_data(self, data, metadata=None):
+ """Validate the display data.
+
+ Parameters
+ ----------
+ data : dict
+ The formata data dictionary.
+ metadata : dict
+ Any metadata for the data.
+ """
+
+ if not isinstance(data, dict):
+ raise TypeError('data must be a dict, got: %r' % data)
+ if metadata is not None:
+ if not isinstance(metadata, dict):
+ raise TypeError('metadata must be a dict, got: %r' % data)
+
# use * to indicate transient, update are keyword-only
def publish(self, data, metadata=None, source=None, **kwargs):
- """Publish data and metadata to all frontends.
-
- See the ``display_data`` message in the messaging documentation for
- more details about this message type.
-
- The following MIME types are currently implemented:
-
- * text/plain
- * text/html
- * text/markdown
- * text/latex
- * application/json
- * application/javascript
- * image/png
- * image/jpeg
- * image/svg+xml
-
- Parameters
- ----------
- data : dict
- A dictionary having keys that are valid MIME types (like
- 'text/plain' or 'image/svg+xml') and values that are the data for
- that MIME type. The data itself must be a JSON'able data
- structure. Minimally all data should have the 'text/plain' data,
- which can be displayed by all frontends. If more than the plain
- text is given, it is up to the frontend to decide which
- representation to use.
- metadata : dict
- A dictionary for metadata related to the data. This can contain
- arbitrary key, value pairs that frontends can use to interpret
- the data. Metadata specific to each mime-type can be specified
- in the metadata dict with the same mime-type keys as
- the data itself.
- source : str, deprecated
- Unused.
+ """Publish data and metadata to all frontends.
+
+ See the ``display_data`` message in the messaging documentation for
+ more details about this message type.
+
+ The following MIME types are currently implemented:
+
+ * text/plain
+ * text/html
+ * text/markdown
+ * text/latex
+ * application/json
+ * application/javascript
+ * image/png
+ * image/jpeg
+ * image/svg+xml
+
+ Parameters
+ ----------
+ data : dict
+ A dictionary having keys that are valid MIME types (like
+ 'text/plain' or 'image/svg+xml') and values that are the data for
+ that MIME type. The data itself must be a JSON'able data
+ structure. Minimally all data should have the 'text/plain' data,
+ which can be displayed by all frontends. If more than the plain
+ text is given, it is up to the frontend to decide which
+ representation to use.
+ metadata : dict
+ A dictionary for metadata related to the data. This can contain
+ arbitrary key, value pairs that frontends can use to interpret
+ the data. Metadata specific to each mime-type can be specified
+ in the metadata dict with the same mime-type keys as
+ the data itself.
+ source : str, deprecated
+ Unused.
transient: dict, keyword-only
A dictionary for transient data.
Data in this dictionary should not be persisted as part of saving this output.
@@ -97,8 +97,8 @@ class DisplayPublisher(Configurable):
update: bool, keyword-only, default: False
If True, only update existing outputs with the same display_id,
rather than creating a new output.
- """
-
+ """
+
# These are kwargs only on Python 3, not used there.
# For consistency and avoid code divergence we leave them here to
# simplify potential backport
@@ -106,21 +106,21 @@ class DisplayPublisher(Configurable):
update = kwargs.pop('update', False)
# The default is to simply write the plain text data using sys.stdout.
- if 'text/plain' in data:
+ if 'text/plain' in data:
print(data['text/plain'])
-
- def clear_output(self, wait=False):
- """Clear the output of the cell receiving output."""
+
+ def clear_output(self, wait=False):
+ """Clear the output of the cell receiving output."""
print('\033[2K\r', end='')
sys.stdout.flush()
print('\033[2K\r', end='')
sys.stderr.flush()
-
-
-class CapturingDisplayPublisher(DisplayPublisher):
- """A DisplayPublisher that stores"""
- outputs = List()
-
+
+
+class CapturingDisplayPublisher(DisplayPublisher):
+ """A DisplayPublisher that stores"""
+ outputs = List()
+
def publish(self, data, metadata=None, source=None, **kwargs):
# These are kwargs only on Python 3, not used there.
@@ -132,8 +132,8 @@ class CapturingDisplayPublisher(DisplayPublisher):
self.outputs.append({'data':data, 'metadata':metadata,
'transient':transient, 'update':update})
- def clear_output(self, wait=False):
- super(CapturingDisplayPublisher, self).clear_output(wait)
+ def clear_output(self, wait=False):
+ super(CapturingDisplayPublisher, self).clear_output(wait)
- # empty the list, *do not* reassign a new list
+ # empty the list, *do not* reassign a new list
self.outputs.clear()
diff --git a/contrib/python/ipython/py2/IPython/core/error.py b/contrib/python/ipython/py2/IPython/core/error.py
index 66d67a6ba6..684cbc8da6 100644
--- a/contrib/python/ipython/py2/IPython/core/error.py
+++ b/contrib/python/ipython/py2/IPython/core/error.py
@@ -1,60 +1,60 @@
-# encoding: utf-8
-"""
-Global exception classes for IPython.core.
-
-Authors:
-
-* Brian Granger
-* Fernando Perez
-* Min Ragan-Kelley
-
-Notes
------
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Exception classes
-#-----------------------------------------------------------------------------
-
-class IPythonCoreError(Exception):
- pass
-
-
-class TryNext(IPythonCoreError):
- """Try next hook exception.
-
- Raise this in your hook function to indicate that the next hook handler
- should be used to handle the operation.
- """
-
-class UsageError(IPythonCoreError):
- """Error in magic function arguments, etc.
-
- Something that probably won't warrant a full traceback, but should
- nevertheless interrupt a macro / batch file.
- """
-
-class StdinNotImplementedError(IPythonCoreError, NotImplementedError):
- """raw_input was requested in a context where it is not supported
-
- For use in IPython kernels, where only some frontends may support
- stdin requests.
- """
-
-class InputRejected(Exception):
- """Input rejected by ast transformer.
-
- Raise this in your NodeTransformer to indicate that InteractiveShell should
- not execute the supplied input.
- """
+# encoding: utf-8
+"""
+Global exception classes for IPython.core.
+
+Authors:
+
+* Brian Granger
+* Fernando Perez
+* Min Ragan-Kelley
+
+Notes
+-----
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Exception classes
+#-----------------------------------------------------------------------------
+
+class IPythonCoreError(Exception):
+ pass
+
+
+class TryNext(IPythonCoreError):
+ """Try next hook exception.
+
+ Raise this in your hook function to indicate that the next hook handler
+ should be used to handle the operation.
+ """
+
+class UsageError(IPythonCoreError):
+ """Error in magic function arguments, etc.
+
+ Something that probably won't warrant a full traceback, but should
+ nevertheless interrupt a macro / batch file.
+ """
+
+class StdinNotImplementedError(IPythonCoreError, NotImplementedError):
+ """raw_input was requested in a context where it is not supported
+
+ For use in IPython kernels, where only some frontends may support
+ stdin requests.
+ """
+
+class InputRejected(Exception):
+ """Input rejected by ast transformer.
+
+ Raise this in your NodeTransformer to indicate that InteractiveShell should
+ not execute the supplied input.
+ """
diff --git a/contrib/python/ipython/py2/IPython/core/events.py b/contrib/python/ipython/py2/IPython/core/events.py
index dc289ee9a1..bfd09fec6a 100644
--- a/contrib/python/ipython/py2/IPython/core/events.py
+++ b/contrib/python/ipython/py2/IPython/core/events.py
@@ -1,131 +1,131 @@
-"""Infrastructure for registering and firing callbacks on application events.
-
-Unlike :mod:`IPython.core.hooks`, which lets end users set single functions to
-be called at specific times, or a collection of alternative methods to try,
-callbacks are designed to be used by extension authors. A number of callbacks
-can be registered for the same event without needing to be aware of one another.
-
-The functions defined in this module are no-ops indicating the names of available
-events and the arguments which will be passed to them.
-
-.. note::
-
- This API is experimental in IPython 2.0, and may be revised in future versions.
-"""
-from __future__ import print_function
-
-class EventManager(object):
- """Manage a collection of events and a sequence of callbacks for each.
-
- This is attached to :class:`~IPython.core.interactiveshell.InteractiveShell`
- instances as an ``events`` attribute.
-
- .. note::
-
- This API is experimental in IPython 2.0, and may be revised in future versions.
- """
- def __init__(self, shell, available_events):
- """Initialise the :class:`CallbackManager`.
-
- Parameters
- ----------
- shell
- The :class:`~IPython.core.interactiveshell.InteractiveShell` instance
- available_callbacks
- An iterable of names for callback events.
- """
- self.shell = shell
- self.callbacks = {n:[] for n in available_events}
-
- def register(self, event, function):
- """Register a new event callback
-
- Parameters
- ----------
- event : str
- The event for which to register this callback.
- function : callable
- A function to be called on the given event. It should take the same
- parameters as the appropriate callback prototype.
-
- Raises
- ------
- TypeError
- If ``function`` is not callable.
- KeyError
- If ``event`` is not one of the known events.
- """
- if not callable(function):
- raise TypeError('Need a callable, got %r' % function)
- self.callbacks[event].append(function)
-
- def unregister(self, event, function):
- """Remove a callback from the given event."""
- self.callbacks[event].remove(function)
-
- def trigger(self, event, *args, **kwargs):
- """Call callbacks for ``event``.
-
- Any additional arguments are passed to all callbacks registered for this
- event. Exceptions raised by callbacks are caught, and a message printed.
- """
+"""Infrastructure for registering and firing callbacks on application events.
+
+Unlike :mod:`IPython.core.hooks`, which lets end users set single functions to
+be called at specific times, or a collection of alternative methods to try,
+callbacks are designed to be used by extension authors. A number of callbacks
+can be registered for the same event without needing to be aware of one another.
+
+The functions defined in this module are no-ops indicating the names of available
+events and the arguments which will be passed to them.
+
+.. note::
+
+ This API is experimental in IPython 2.0, and may be revised in future versions.
+"""
+from __future__ import print_function
+
+class EventManager(object):
+ """Manage a collection of events and a sequence of callbacks for each.
+
+ This is attached to :class:`~IPython.core.interactiveshell.InteractiveShell`
+ instances as an ``events`` attribute.
+
+ .. note::
+
+ This API is experimental in IPython 2.0, and may be revised in future versions.
+ """
+ def __init__(self, shell, available_events):
+ """Initialise the :class:`CallbackManager`.
+
+ Parameters
+ ----------
+ shell
+ The :class:`~IPython.core.interactiveshell.InteractiveShell` instance
+ available_callbacks
+ An iterable of names for callback events.
+ """
+ self.shell = shell
+ self.callbacks = {n:[] for n in available_events}
+
+ def register(self, event, function):
+ """Register a new event callback
+
+ Parameters
+ ----------
+ event : str
+ The event for which to register this callback.
+ function : callable
+ A function to be called on the given event. It should take the same
+ parameters as the appropriate callback prototype.
+
+ Raises
+ ------
+ TypeError
+ If ``function`` is not callable.
+ KeyError
+ If ``event`` is not one of the known events.
+ """
+ if not callable(function):
+ raise TypeError('Need a callable, got %r' % function)
+ self.callbacks[event].append(function)
+
+ def unregister(self, event, function):
+ """Remove a callback from the given event."""
+ self.callbacks[event].remove(function)
+
+ def trigger(self, event, *args, **kwargs):
+ """Call callbacks for ``event``.
+
+ Any additional arguments are passed to all callbacks registered for this
+ event. Exceptions raised by callbacks are caught, and a message printed.
+ """
for func in self.callbacks[event][:]:
- try:
- func(*args, **kwargs)
- except Exception:
- print("Error in callback {} (for {}):".format(func, event))
- self.shell.showtraceback()
-
-# event_name -> prototype mapping
-available_events = {}
-
-def _define_event(callback_proto):
- available_events[callback_proto.__name__] = callback_proto
- return callback_proto
-
-# ------------------------------------------------------------------------------
-# Callback prototypes
-#
-# No-op functions which describe the names of available events and the
-# signatures of callbacks for those events.
-# ------------------------------------------------------------------------------
-
-@_define_event
-def pre_execute():
- """Fires before code is executed in response to user/frontend action.
-
- This includes comm and widget messages and silent execution, as well as user
- code cells."""
- pass
-
-@_define_event
-def pre_run_cell():
- """Fires before user-entered code runs."""
- pass
-
-@_define_event
-def post_execute():
- """Fires after code is executed in response to user/frontend action.
-
- This includes comm and widget messages and silent execution, as well as user
- code cells."""
- pass
-
-@_define_event
-def post_run_cell():
- """Fires after user-entered code runs."""
- pass
-
-@_define_event
-def shell_initialized(ip):
- """Fires after initialisation of :class:`~IPython.core.interactiveshell.InteractiveShell`.
-
- This is before extensions and startup scripts are loaded, so it can only be
- set by subclassing.
-
- Parameters
- ----------
- ip : :class:`~IPython.core.interactiveshell.InteractiveShell`
- The newly initialised shell.
- """
- pass
+ try:
+ func(*args, **kwargs)
+ except Exception:
+ print("Error in callback {} (for {}):".format(func, event))
+ self.shell.showtraceback()
+
+# event_name -> prototype mapping
+available_events = {}
+
+def _define_event(callback_proto):
+ available_events[callback_proto.__name__] = callback_proto
+ return callback_proto
+
+# ------------------------------------------------------------------------------
+# Callback prototypes
+#
+# No-op functions which describe the names of available events and the
+# signatures of callbacks for those events.
+# ------------------------------------------------------------------------------
+
+@_define_event
+def pre_execute():
+ """Fires before code is executed in response to user/frontend action.
+
+ This includes comm and widget messages and silent execution, as well as user
+ code cells."""
+ pass
+
+@_define_event
+def pre_run_cell():
+ """Fires before user-entered code runs."""
+ pass
+
+@_define_event
+def post_execute():
+ """Fires after code is executed in response to user/frontend action.
+
+ This includes comm and widget messages and silent execution, as well as user
+ code cells."""
+ pass
+
+@_define_event
+def post_run_cell():
+ """Fires after user-entered code runs."""
+ pass
+
+@_define_event
+def shell_initialized(ip):
+ """Fires after initialisation of :class:`~IPython.core.interactiveshell.InteractiveShell`.
+
+ This is before extensions and startup scripts are loaded, so it can only be
+ set by subclassing.
+
+ Parameters
+ ----------
+ ip : :class:`~IPython.core.interactiveshell.InteractiveShell`
+ The newly initialised shell.
+ """
+ pass
diff --git a/contrib/python/ipython/py2/IPython/core/excolors.py b/contrib/python/ipython/py2/IPython/core/excolors.py
index 7546b4b263..487bde18c8 100644
--- a/contrib/python/ipython/py2/IPython/core/excolors.py
+++ b/contrib/python/ipython/py2/IPython/core/excolors.py
@@ -1,133 +1,133 @@
-# -*- coding: utf-8 -*-
-"""
-Color schemes for exception handling code in IPython.
-"""
-
+# -*- coding: utf-8 -*-
+"""
+Color schemes for exception handling code in IPython.
+"""
+
import os
-import warnings
-
-#*****************************************************************************
-# Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#*****************************************************************************
-
-from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme
-
-def exception_colors():
- """Return a color table with fields for exception reporting.
-
- The table is an instance of ColorSchemeTable with schemes added for
+import warnings
+
+#*****************************************************************************
+# Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#*****************************************************************************
+
+from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme
+
+def exception_colors():
+ """Return a color table with fields for exception reporting.
+
+ The table is an instance of ColorSchemeTable with schemes added for
'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
- in.
-
- Examples:
-
- >>> ec = exception_colors()
- >>> ec.active_scheme_name
- ''
- >>> print(ec.active_colors)
- None
-
- Now we activate a color scheme:
- >>> ec.set_active_scheme('NoColor')
- >>> ec.active_scheme_name
- 'NoColor'
- >>> sorted(ec.active_colors.keys())
- ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line',
- 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName',
- 'val', 'valEm']
- """
-
- ex_colors = ColorSchemeTable()
-
- # Populate it with color schemes
- C = TermColors # shorthand and local lookup
- ex_colors.add_scheme(ColorScheme(
- 'NoColor',
- # The color to be used for the top line
- topline = C.NoColor,
-
- # The colors to be used in the traceback
- filename = C.NoColor,
- lineno = C.NoColor,
- name = C.NoColor,
- vName = C.NoColor,
- val = C.NoColor,
- em = C.NoColor,
-
- # Emphasized colors for the last frame of the traceback
- normalEm = C.NoColor,
- filenameEm = C.NoColor,
- linenoEm = C.NoColor,
- nameEm = C.NoColor,
- valEm = C.NoColor,
-
- # Colors for printing the exception
- excName = C.NoColor,
- line = C.NoColor,
- caret = C.NoColor,
- Normal = C.NoColor
- ))
-
- # make some schemes as instances so we can copy them for modification easily
- ex_colors.add_scheme(ColorScheme(
- 'Linux',
- # The color to be used for the top line
- topline = C.LightRed,
-
- # The colors to be used in the traceback
- filename = C.Green,
- lineno = C.Green,
- name = C.Purple,
- vName = C.Cyan,
- val = C.Green,
- em = C.LightCyan,
-
- # Emphasized colors for the last frame of the traceback
- normalEm = C.LightCyan,
- filenameEm = C.LightGreen,
- linenoEm = C.LightGreen,
- nameEm = C.LightPurple,
- valEm = C.LightBlue,
-
- # Colors for printing the exception
- excName = C.LightRed,
- line = C.Yellow,
- caret = C.White,
- Normal = C.Normal
- ))
-
- # For light backgrounds, swap dark/light colors
- ex_colors.add_scheme(ColorScheme(
- 'LightBG',
- # The color to be used for the top line
- topline = C.Red,
-
- # The colors to be used in the traceback
- filename = C.LightGreen,
- lineno = C.LightGreen,
- name = C.LightPurple,
- vName = C.Cyan,
- val = C.LightGreen,
- em = C.Cyan,
-
- # Emphasized colors for the last frame of the traceback
- normalEm = C.Cyan,
- filenameEm = C.Green,
- linenoEm = C.Green,
- nameEm = C.Purple,
- valEm = C.Blue,
-
- # Colors for printing the exception
- excName = C.Red,
- #line = C.Brown, # brown often is displayed as yellow
- line = C.Red,
- caret = C.Normal,
- Normal = C.Normal,
- ))
-
+ in.
+
+ Examples:
+
+ >>> ec = exception_colors()
+ >>> ec.active_scheme_name
+ ''
+ >>> print(ec.active_colors)
+ None
+
+ Now we activate a color scheme:
+ >>> ec.set_active_scheme('NoColor')
+ >>> ec.active_scheme_name
+ 'NoColor'
+ >>> sorted(ec.active_colors.keys())
+ ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line',
+ 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName',
+ 'val', 'valEm']
+ """
+
+ ex_colors = ColorSchemeTable()
+
+ # Populate it with color schemes
+ C = TermColors # shorthand and local lookup
+ ex_colors.add_scheme(ColorScheme(
+ 'NoColor',
+ # The color to be used for the top line
+ topline = C.NoColor,
+
+ # The colors to be used in the traceback
+ filename = C.NoColor,
+ lineno = C.NoColor,
+ name = C.NoColor,
+ vName = C.NoColor,
+ val = C.NoColor,
+ em = C.NoColor,
+
+ # Emphasized colors for the last frame of the traceback
+ normalEm = C.NoColor,
+ filenameEm = C.NoColor,
+ linenoEm = C.NoColor,
+ nameEm = C.NoColor,
+ valEm = C.NoColor,
+
+ # Colors for printing the exception
+ excName = C.NoColor,
+ line = C.NoColor,
+ caret = C.NoColor,
+ Normal = C.NoColor
+ ))
+
+ # make some schemes as instances so we can copy them for modification easily
+ ex_colors.add_scheme(ColorScheme(
+ 'Linux',
+ # The color to be used for the top line
+ topline = C.LightRed,
+
+ # The colors to be used in the traceback
+ filename = C.Green,
+ lineno = C.Green,
+ name = C.Purple,
+ vName = C.Cyan,
+ val = C.Green,
+ em = C.LightCyan,
+
+ # Emphasized colors for the last frame of the traceback
+ normalEm = C.LightCyan,
+ filenameEm = C.LightGreen,
+ linenoEm = C.LightGreen,
+ nameEm = C.LightPurple,
+ valEm = C.LightBlue,
+
+ # Colors for printing the exception
+ excName = C.LightRed,
+ line = C.Yellow,
+ caret = C.White,
+ Normal = C.Normal
+ ))
+
+ # For light backgrounds, swap dark/light colors
+ ex_colors.add_scheme(ColorScheme(
+ 'LightBG',
+ # The color to be used for the top line
+ topline = C.Red,
+
+ # The colors to be used in the traceback
+ filename = C.LightGreen,
+ lineno = C.LightGreen,
+ name = C.LightPurple,
+ vName = C.Cyan,
+ val = C.LightGreen,
+ em = C.Cyan,
+
+ # Emphasized colors for the last frame of the traceback
+ normalEm = C.Cyan,
+ filenameEm = C.Green,
+ linenoEm = C.Green,
+ nameEm = C.Purple,
+ valEm = C.Blue,
+
+ # Colors for printing the exception
+ excName = C.Red,
+ #line = C.Brown, # brown often is displayed as yellow
+ line = C.Red,
+ caret = C.Normal,
+ Normal = C.Normal,
+ ))
+
ex_colors.add_scheme(ColorScheme(
'Neutral',
# The color to be used for the top line
@@ -163,22 +163,22 @@ def exception_colors():
if os.name == "nt":
ex_colors.add_scheme(ex_colors['Linux'].copy('Neutral'))
- return ex_colors
-
-class Deprec(object):
-
- def __init__(self, wrapped_obj):
- self.wrapped=wrapped_obj
-
- def __getattr__(self, name):
- val = getattr(self.wrapped, name)
+ return ex_colors
+
+class Deprec(object):
+
+ def __init__(self, wrapped_obj):
+ self.wrapped=wrapped_obj
+
+ def __getattr__(self, name):
+ val = getattr(self.wrapped, name)
warnings.warn("Using ExceptionColors global is deprecated and will be removed in IPython 6.0",
DeprecationWarning, stacklevel=2)
- # using getattr after warnings break ipydoctest in weird way for 3.5
- return val
-
-# For backwards compatibility, keep around a single global object. Note that
-# this should NOT be used, the factory function should be used instead, since
-# these objects are stateful and it's very easy to get strange bugs if any code
-# modifies the module-level object's state.
-ExceptionColors = Deprec(exception_colors())
+ # using getattr after warnings break ipydoctest in weird way for 3.5
+ return val
+
+# For backwards compatibility, keep around a single global object. Note that
+# this should NOT be used, the factory function should be used instead, since
+# these objects are stateful and it's very easy to get strange bugs if any code
+# modifies the module-level object's state.
+ExceptionColors = Deprec(exception_colors())
diff --git a/contrib/python/ipython/py2/IPython/core/extensions.py b/contrib/python/ipython/py2/IPython/core/extensions.py
index e20b485e97..58855466f1 100644
--- a/contrib/python/ipython/py2/IPython/core/extensions.py
+++ b/contrib/python/ipython/py2/IPython/core/extensions.py
@@ -1,173 +1,173 @@
-# encoding: utf-8
-"""A class for managing IPython extensions."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import os
-from shutil import copyfile
-import sys
-
-from traitlets.config.configurable import Configurable
-from IPython.utils.path import ensure_dir_exists
-from traitlets import Instance
-
-try:
- from importlib import reload
-except ImportError :
- ## deprecated since 3.4
- from imp import reload
-
-#-----------------------------------------------------------------------------
-# Main class
-#-----------------------------------------------------------------------------
-
-class ExtensionManager(Configurable):
- """A class to manage IPython extensions.
-
- An IPython extension is an importable Python module that has
- a function with the signature::
-
- def load_ipython_extension(ipython):
- # Do things with ipython
-
- This function is called after your extension is imported and the
- currently active :class:`InteractiveShell` instance is passed as
- the only argument. You can do anything you want with IPython at
- that point, including defining new magic and aliases, adding new
- components, etc.
+# encoding: utf-8
+"""A class for managing IPython extensions."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import os
+from shutil import copyfile
+import sys
+
+from traitlets.config.configurable import Configurable
+from IPython.utils.path import ensure_dir_exists
+from traitlets import Instance
+
+try:
+ from importlib import reload
+except ImportError :
+ ## deprecated since 3.4
+ from imp import reload
+
+#-----------------------------------------------------------------------------
+# Main class
+#-----------------------------------------------------------------------------
+
+class ExtensionManager(Configurable):
+ """A class to manage IPython extensions.
+
+ An IPython extension is an importable Python module that has
+ a function with the signature::
+
+ def load_ipython_extension(ipython):
+ # Do things with ipython
+
+ This function is called after your extension is imported and the
+ currently active :class:`InteractiveShell` instance is passed as
+ the only argument. You can do anything you want with IPython at
+ that point, including defining new magic and aliases, adding new
+ components, etc.
- You can also optionally define an :func:`unload_ipython_extension(ipython)`
- function, which will be called if the user unloads or reloads the extension.
- The extension manager will only call :func:`load_ipython_extension` again
- if the extension is reloaded.
-
- You can put your extension modules anywhere you want, as long as
- they can be imported by Python's standard import mechanism. However,
- to make it easy to write extensions, you can also put your extensions
- in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
- is added to ``sys.path`` automatically.
- """
-
+ You can also optionally define an :func:`unload_ipython_extension(ipython)`
+ function, which will be called if the user unloads or reloads the extension.
+ The extension manager will only call :func:`load_ipython_extension` again
+ if the extension is reloaded.
+
+ You can put your extension modules anywhere you want, as long as
+ they can be imported by Python's standard import mechanism. However,
+ to make it easy to write extensions, you can also put your extensions
+ in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
+ is added to ``sys.path`` automatically.
+ """
+
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
-
- def __init__(self, shell=None, **kwargs):
- super(ExtensionManager, self).__init__(shell=shell, **kwargs)
+
+ def __init__(self, shell=None, **kwargs):
+ super(ExtensionManager, self).__init__(shell=shell, **kwargs)
self.shell.observe(
self._on_ipython_dir_changed, names=('ipython_dir',)
- )
- self.loaded = set()
-
- @property
- def ipython_extension_dir(self):
- return os.path.join(self.shell.ipython_dir, u'extensions')
-
+ )
+ self.loaded = set()
+
+ @property
+ def ipython_extension_dir(self):
+ return os.path.join(self.shell.ipython_dir, u'extensions')
+
def _on_ipython_dir_changed(self, change):
- ensure_dir_exists(self.ipython_extension_dir)
-
- def load_extension(self, module_str):
- """Load an IPython extension by its module name.
-
- Returns the string "already loaded" if the extension is already loaded,
- "no load function" if the module doesn't have a load_ipython_extension
- function, or None if it succeeded.
- """
- if module_str in self.loaded:
- return "already loaded"
+ ensure_dir_exists(self.ipython_extension_dir)
+
+ def load_extension(self, module_str):
+ """Load an IPython extension by its module name.
+
+ Returns the string "already loaded" if the extension is already loaded,
+ "no load function" if the module doesn't have a load_ipython_extension
+ function, or None if it succeeded.
+ """
+ if module_str in self.loaded:
+ return "already loaded"
- with self.shell.builtin_trap:
- if module_str not in sys.modules:
+ with self.shell.builtin_trap:
+ if module_str not in sys.modules:
try:
sys.modules[module_str] = __import__('IPython.extensions.' + module_str)
except ImportError:
- __import__(module_str)
- mod = sys.modules[module_str]
- if self._call_load_ipython_extension(mod):
- self.loaded.add(module_str)
- else:
- return "no load function"
-
- def unload_extension(self, module_str):
- """Unload an IPython extension by its module name.
-
- This function looks up the extension's name in ``sys.modules`` and
- simply calls ``mod.unload_ipython_extension(self)``.
+ __import__(module_str)
+ mod = sys.modules[module_str]
+ if self._call_load_ipython_extension(mod):
+ self.loaded.add(module_str)
+ else:
+ return "no load function"
+
+ def unload_extension(self, module_str):
+ """Unload an IPython extension by its module name.
+
+ This function looks up the extension's name in ``sys.modules`` and
+ simply calls ``mod.unload_ipython_extension(self)``.
- Returns the string "no unload function" if the extension doesn't define
- a function to unload itself, "not loaded" if the extension isn't loaded,
- otherwise None.
- """
- if module_str not in self.loaded:
- return "not loaded"
+ Returns the string "no unload function" if the extension doesn't define
+ a function to unload itself, "not loaded" if the extension isn't loaded,
+ otherwise None.
+ """
+ if module_str not in self.loaded:
+ return "not loaded"
- if module_str in sys.modules:
- mod = sys.modules[module_str]
- if self._call_unload_ipython_extension(mod):
- self.loaded.discard(module_str)
- else:
- return "no unload function"
-
- def reload_extension(self, module_str):
- """Reload an IPython extension by calling reload.
-
- If the module has not been loaded before,
- :meth:`InteractiveShell.load_extension` is called. Otherwise
- :func:`reload` is called and then the :func:`load_ipython_extension`
- function of the module, if it exists is called.
- """
- from IPython.utils.syspathcontext import prepended_to_syspath
-
- if (module_str in self.loaded) and (module_str in sys.modules):
- self.unload_extension(module_str)
- mod = sys.modules[module_str]
- with prepended_to_syspath(self.ipython_extension_dir):
- reload(mod)
- if self._call_load_ipython_extension(mod):
- self.loaded.add(module_str)
- else:
- self.load_extension(module_str)
-
- def _call_load_ipython_extension(self, mod):
- if hasattr(mod, 'load_ipython_extension'):
- mod.load_ipython_extension(self.shell)
- return True
-
- def _call_unload_ipython_extension(self, mod):
- if hasattr(mod, 'unload_ipython_extension'):
- mod.unload_ipython_extension(self.shell)
- return True
-
- def install_extension(self, url, filename=None):
+ if module_str in sys.modules:
+ mod = sys.modules[module_str]
+ if self._call_unload_ipython_extension(mod):
+ self.loaded.discard(module_str)
+ else:
+ return "no unload function"
+
+ def reload_extension(self, module_str):
+ """Reload an IPython extension by calling reload.
+
+ If the module has not been loaded before,
+ :meth:`InteractiveShell.load_extension` is called. Otherwise
+ :func:`reload` is called and then the :func:`load_ipython_extension`
+ function of the module, if it exists is called.
+ """
+ from IPython.utils.syspathcontext import prepended_to_syspath
+
+ if (module_str in self.loaded) and (module_str in sys.modules):
+ self.unload_extension(module_str)
+ mod = sys.modules[module_str]
+ with prepended_to_syspath(self.ipython_extension_dir):
+ reload(mod)
+ if self._call_load_ipython_extension(mod):
+ self.loaded.add(module_str)
+ else:
+ self.load_extension(module_str)
+
+ def _call_load_ipython_extension(self, mod):
+ if hasattr(mod, 'load_ipython_extension'):
+ mod.load_ipython_extension(self.shell)
+ return True
+
+ def _call_unload_ipython_extension(self, mod):
+ if hasattr(mod, 'unload_ipython_extension'):
+ mod.unload_ipython_extension(self.shell)
+ return True
+
+ def install_extension(self, url, filename=None):
"""Download and install an IPython extension.
-
- If filename is given, the file will be so named (inside the extension
- directory). Otherwise, the name from the URL will be used. The file must
- have a .py or .zip extension; otherwise, a ValueError will be raised.
-
- Returns the full path to the installed file.
- """
- # Ensure the extension directory exists
- ensure_dir_exists(self.ipython_extension_dir)
-
- if os.path.isfile(url):
- src_filename = os.path.basename(url)
- copy = copyfile
- else:
- # Deferred imports
- try:
- from urllib.parse import urlparse # Py3
- from urllib.request import urlretrieve
- except ImportError:
- from urlparse import urlparse
- from urllib import urlretrieve
- src_filename = urlparse(url).path.split('/')[-1]
- copy = urlretrieve
-
- if filename is None:
- filename = src_filename
- if os.path.splitext(filename)[1] not in ('.py', '.zip'):
- raise ValueError("The file must have a .py or .zip extension", filename)
-
- filename = os.path.join(self.ipython_extension_dir, filename)
- copy(url, filename)
- return filename
+
+ If filename is given, the file will be so named (inside the extension
+ directory). Otherwise, the name from the URL will be used. The file must
+ have a .py or .zip extension; otherwise, a ValueError will be raised.
+
+ Returns the full path to the installed file.
+ """
+ # Ensure the extension directory exists
+ ensure_dir_exists(self.ipython_extension_dir)
+
+ if os.path.isfile(url):
+ src_filename = os.path.basename(url)
+ copy = copyfile
+ else:
+ # Deferred imports
+ try:
+ from urllib.parse import urlparse # Py3
+ from urllib.request import urlretrieve
+ except ImportError:
+ from urlparse import urlparse
+ from urllib import urlretrieve
+ src_filename = urlparse(url).path.split('/')[-1]
+ copy = urlretrieve
+
+ if filename is None:
+ filename = src_filename
+ if os.path.splitext(filename)[1] not in ('.py', '.zip'):
+ raise ValueError("The file must have a .py or .zip extension", filename)
+
+ filename = os.path.join(self.ipython_extension_dir, filename)
+ copy(url, filename)
+ return filename
diff --git a/contrib/python/ipython/py2/IPython/core/formatters.py b/contrib/python/ipython/py2/IPython/core/formatters.py
index 31ed25a4b0..d990619f27 100644
--- a/contrib/python/ipython/py2/IPython/core/formatters.py
+++ b/contrib/python/ipython/py2/IPython/core/formatters.py
@@ -1,137 +1,137 @@
-# -*- coding: utf-8 -*-
-"""Display formatters.
-
-Inheritance diagram:
-
-.. inheritance-diagram:: IPython.core.formatters
- :parts: 3
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import abc
-import json
-import sys
-import traceback
-import warnings
-
-from decorator import decorator
-
-from traitlets.config.configurable import Configurable
-from IPython.core.getipython import get_ipython
-from IPython.utils.sentinel import Sentinel
+# -*- coding: utf-8 -*-
+"""Display formatters.
+
+Inheritance diagram:
+
+.. inheritance-diagram:: IPython.core.formatters
+ :parts: 3
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import abc
+import json
+import sys
+import traceback
+import warnings
+
+from decorator import decorator
+
+from traitlets.config.configurable import Configurable
+from IPython.core.getipython import get_ipython
+from IPython.utils.sentinel import Sentinel
from IPython.utils.dir2 import get_real_method
-from IPython.lib import pretty
-from traitlets import (
- Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
- ForwardDeclaredInstance,
+from IPython.lib import pretty
+from traitlets import (
+ Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
+ ForwardDeclaredInstance,
default, observe,
-)
-from IPython.utils.py3compat import (
- with_metaclass, string_types, unicode_type,
-)
-
-
-class DisplayFormatter(Configurable):
-
+)
+from IPython.utils.py3compat import (
+ with_metaclass, string_types, unicode_type,
+)
+
+
+class DisplayFormatter(Configurable):
+
active_types = List(Unicode(),
- help="""List of currently active mime-types to display.
- You can use this to set a white-list for formats to display.
-
- Most users will not need to change this value.
+ help="""List of currently active mime-types to display.
+ You can use this to set a white-list for formats to display.
+
+ Most users will not need to change this value.
""").tag(config=True)
@default('active_types')
- def _active_types_default(self):
- return self.format_types
+ def _active_types_default(self):
+ return self.format_types
@observe('active_types')
def _active_types_changed(self, change):
- for key, formatter in self.formatters.items():
+ for key, formatter in self.formatters.items():
if key in change['new']:
- formatter.enabled = True
- else:
- formatter.enabled = False
+ formatter.enabled = True
+ else:
+ formatter.enabled = False
- ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
+ ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
@default('ipython_display_formatter')
def _default_formatter(self):
- return IPythonDisplayFormatter(parent=self)
+ return IPythonDisplayFormatter(parent=self)
mimebundle_formatter = ForwardDeclaredInstance('FormatterABC')
@default('mimebundle_formatter')
def _default_mime_formatter(self):
return MimeBundleFormatter(parent=self)
- # A dict of formatter whose keys are format types (MIME types) and whose
- # values are subclasses of BaseFormatter.
- formatters = Dict()
+ # A dict of formatter whose keys are format types (MIME types) and whose
+ # values are subclasses of BaseFormatter.
+ formatters = Dict()
@default('formatters')
- def _formatters_default(self):
- """Activate the default formatters."""
- formatter_classes = [
- PlainTextFormatter,
- HTMLFormatter,
- MarkdownFormatter,
- SVGFormatter,
- PNGFormatter,
- PDFFormatter,
- JPEGFormatter,
- LatexFormatter,
- JSONFormatter,
- JavascriptFormatter
- ]
- d = {}
- for cls in formatter_classes:
- f = cls(parent=self)
- d[f.format_type] = f
- return d
-
- def format(self, obj, include=None, exclude=None):
- """Return a format data dict for an object.
-
- By default all format types will be computed.
-
+ def _formatters_default(self):
+ """Activate the default formatters."""
+ formatter_classes = [
+ PlainTextFormatter,
+ HTMLFormatter,
+ MarkdownFormatter,
+ SVGFormatter,
+ PNGFormatter,
+ PDFFormatter,
+ JPEGFormatter,
+ LatexFormatter,
+ JSONFormatter,
+ JavascriptFormatter
+ ]
+ d = {}
+ for cls in formatter_classes:
+ f = cls(parent=self)
+ d[f.format_type] = f
+ return d
+
+ def format(self, obj, include=None, exclude=None):
+ """Return a format data dict for an object.
+
+ By default all format types will be computed.
+
The following MIME types are usually implemented:
-
- * text/plain
- * text/html
- * text/markdown
- * text/latex
- * application/json
- * application/javascript
- * application/pdf
- * image/png
- * image/jpeg
- * image/svg+xml
-
- Parameters
- ----------
- obj : object
- The Python object whose format data will be computed.
+
+ * text/plain
+ * text/html
+ * text/markdown
+ * text/latex
+ * application/json
+ * application/javascript
+ * application/pdf
+ * image/png
+ * image/jpeg
+ * image/svg+xml
+
+ Parameters
+ ----------
+ obj : object
+ The Python object whose format data will be computed.
include : list, tuple or set; optional
- A list of format type strings (MIME types) to include in the
- format data dict. If this is set *only* the format types included
- in this list will be computed.
+ A list of format type strings (MIME types) to include in the
+ format data dict. If this is set *only* the format types included
+ in this list will be computed.
exclude : list, tuple or set; optional
- A list of format type string (MIME types) to exclude in the format
- data dict. If this is set all format types will be computed,
- except for those included in this argument.
+ A list of format type string (MIME types) to exclude in the format
+ data dict. If this is set all format types will be computed,
+ except for those included in this argument.
Mimetypes present in exclude will take precedence over the ones in include
-
- Returns
- -------
- (format_dict, metadata_dict) : tuple of two dicts
-
- format_dict is a dictionary of key/value pairs, one of each format that was
- generated for the object. The keys are the format types, which
- will usually be MIME type strings and the values and JSON'able
- data structure containing the raw data for the representation in
- that format.
-
- metadata_dict is a dictionary of metadata about each mime-type output.
- Its keys will be a strict subset of the keys in format_dict.
+
+ Returns
+ -------
+ (format_dict, metadata_dict) : tuple of two dicts
+
+ format_dict is a dictionary of key/value pairs, one of each format that was
+ generated for the object. The keys are the format types, which
+ will usually be MIME type strings and the values and JSON'able
+ data structure containing the raw data for the representation in
+ that format.
+
+ metadata_dict is a dictionary of metadata about each mime-type output.
+ Its keys will be a strict subset of the keys in format_dict.
Notes
-----
@@ -141,13 +141,13 @@ class DisplayFormatter(Configurable):
precedence and the corresponding `_repr_*_` for this mimetype will
not be called.
- """
- format_dict = {}
- md_dict = {}
-
- if self.ipython_display_formatter(obj):
- # object handled itself, don't proceed
- return {}, {}
+ """
+ format_dict = {}
+ md_dict = {}
+
+ if self.ipython_display_formatter(obj):
+ # object handled itself, don't proceed
+ return {}, {}
format_dict, md_dict = self.mimebundle_formatter(obj, include=include, exclude=exclude)
@@ -159,733 +159,733 @@ class DisplayFormatter(Configurable):
format_dict = {k:v for k,v in format_dict.items() if k not in exclude}
md_dict = {k:v for k,v in md_dict.items() if k not in exclude}
- for format_type, formatter in self.formatters.items():
+ for format_type, formatter in self.formatters.items():
if format_type in format_dict:
# already got it from mimebundle, don't render again
continue
- if include and format_type not in include:
- continue
- if exclude and format_type in exclude:
- continue
-
- md = None
- try:
- data = formatter(obj)
- except:
- # FIXME: log the exception
- raise
-
- # formatters can return raw data or (data, metadata)
- if isinstance(data, tuple) and len(data) == 2:
- data, md = data
-
- if data is not None:
- format_dict[format_type] = data
- if md is not None:
- md_dict[format_type] = md
- return format_dict, md_dict
-
- @property
- def format_types(self):
- """Return the format types (MIME types) of the active formatters."""
- return list(self.formatters.keys())
-
-
-#-----------------------------------------------------------------------------
-# Formatters for specific format types (text, html, svg, etc.)
-#-----------------------------------------------------------------------------
-
-
-def _safe_repr(obj):
- """Try to return a repr of an object
-
- always returns a string, at least.
- """
- try:
- return repr(obj)
- except Exception as e:
- return "un-repr-able object (%r)" % e
-
-
-class FormatterWarning(UserWarning):
- """Warning class for errors in formatters"""
-
-@decorator
-def catch_format_error(method, self, *args, **kwargs):
- """show traceback on failed format call"""
- try:
- r = method(self, *args, **kwargs)
- except NotImplementedError:
- # don't warn on NotImplementedErrors
+ if include and format_type not in include:
+ continue
+ if exclude and format_type in exclude:
+ continue
+
+ md = None
+ try:
+ data = formatter(obj)
+ except:
+ # FIXME: log the exception
+ raise
+
+ # formatters can return raw data or (data, metadata)
+ if isinstance(data, tuple) and len(data) == 2:
+ data, md = data
+
+ if data is not None:
+ format_dict[format_type] = data
+ if md is not None:
+ md_dict[format_type] = md
+ return format_dict, md_dict
+
+ @property
+ def format_types(self):
+ """Return the format types (MIME types) of the active formatters."""
+ return list(self.formatters.keys())
+
+
+#-----------------------------------------------------------------------------
+# Formatters for specific format types (text, html, svg, etc.)
+#-----------------------------------------------------------------------------
+
+
+def _safe_repr(obj):
+ """Try to return a repr of an object
+
+ always returns a string, at least.
+ """
+ try:
+ return repr(obj)
+ except Exception as e:
+ return "un-repr-able object (%r)" % e
+
+
+class FormatterWarning(UserWarning):
+ """Warning class for errors in formatters"""
+
+@decorator
+def catch_format_error(method, self, *args, **kwargs):
+ """show traceback on failed format call"""
+ try:
+ r = method(self, *args, **kwargs)
+ except NotImplementedError:
+ # don't warn on NotImplementedErrors
return self._check_return(None, args[0])
- except Exception:
- exc_info = sys.exc_info()
- ip = get_ipython()
- if ip is not None:
- ip.showtraceback(exc_info)
- else:
- traceback.print_exception(*exc_info)
+ except Exception:
+ exc_info = sys.exc_info()
+ ip = get_ipython()
+ if ip is not None:
+ ip.showtraceback(exc_info)
+ else:
+ traceback.print_exception(*exc_info)
return self._check_return(None, args[0])
- return self._check_return(r, args[0])
-
-
-class FormatterABC(with_metaclass(abc.ABCMeta, object)):
- """ Abstract base class for Formatters.
-
- A formatter is a callable class that is responsible for computing the
- raw format data for a particular format type (MIME type). For example,
- an HTML formatter would have a format type of `text/html` and would return
- the HTML representation of the object when called.
- """
-
- # The format type of the data returned, usually a MIME type.
- format_type = 'text/plain'
-
- # Is the formatter enabled...
- enabled = True
-
- @abc.abstractmethod
- def __call__(self, obj):
- """Return a JSON'able representation of the object.
-
- If the object cannot be formatted by this formatter,
- warn and return None.
- """
- return repr(obj)
-
-
-def _mod_name_key(typ):
- """Return a (__module__, __name__) tuple for a type.
-
- Used as key in Formatter.deferred_printers.
- """
- module = getattr(typ, '__module__', None)
- name = getattr(typ, '__name__', None)
- return (module, name)
-
-
-def _get_type(obj):
- """Return the type of an instance (old and new-style)"""
- return getattr(obj, '__class__', None) or type(obj)
-
-
-_raise_key_error = Sentinel('_raise_key_error', __name__,
-"""
-Special value to raise a KeyError
-
-Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
-""")
-
-
-class BaseFormatter(Configurable):
- """A base formatter class that is configurable.
-
- This formatter should usually be used as the base class of all formatters.
- It is a traited :class:`Configurable` class and includes an extensible
- API for users to determine how their objects are formatted. The following
- logic is used to find a function to format an given object.
-
- 1. The object is introspected to see if it has a method with the name
- :attr:`print_method`. If is does, that object is passed to that method
- for formatting.
- 2. If no print method is found, three internal dictionaries are consulted
- to find print method: :attr:`singleton_printers`, :attr:`type_printers`
- and :attr:`deferred_printers`.
-
- Users should use these dictionaries to register functions that will be
- used to compute the format data for their objects (if those objects don't
- have the special print methods). The easiest way of using these
- dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
- methods.
-
- If no function/callable is found to compute the format data, ``None`` is
- returned and this format type is not used.
- """
-
- format_type = Unicode('text/plain')
- _return_type = string_types
-
+ return self._check_return(r, args[0])
+
+
+class FormatterABC(with_metaclass(abc.ABCMeta, object)):
+ """ Abstract base class for Formatters.
+
+ A formatter is a callable class that is responsible for computing the
+ raw format data for a particular format type (MIME type). For example,
+ an HTML formatter would have a format type of `text/html` and would return
+ the HTML representation of the object when called.
+ """
+
+ # The format type of the data returned, usually a MIME type.
+ format_type = 'text/plain'
+
+ # Is the formatter enabled...
+ enabled = True
+
+ @abc.abstractmethod
+ def __call__(self, obj):
+ """Return a JSON'able representation of the object.
+
+ If the object cannot be formatted by this formatter,
+ warn and return None.
+ """
+ return repr(obj)
+
+
+def _mod_name_key(typ):
+ """Return a (__module__, __name__) tuple for a type.
+
+ Used as key in Formatter.deferred_printers.
+ """
+ module = getattr(typ, '__module__', None)
+ name = getattr(typ, '__name__', None)
+ return (module, name)
+
+
+def _get_type(obj):
+ """Return the type of an instance (old and new-style)"""
+ return getattr(obj, '__class__', None) or type(obj)
+
+
+_raise_key_error = Sentinel('_raise_key_error', __name__,
+"""
+Special value to raise a KeyError
+
+Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
+""")
+
+
+class BaseFormatter(Configurable):
+ """A base formatter class that is configurable.
+
+ This formatter should usually be used as the base class of all formatters.
+ It is a traited :class:`Configurable` class and includes an extensible
+ API for users to determine how their objects are formatted. The following
+ logic is used to find a function to format an given object.
+
+ 1. The object is introspected to see if it has a method with the name
+ :attr:`print_method`. If is does, that object is passed to that method
+ for formatting.
+ 2. If no print method is found, three internal dictionaries are consulted
+ to find print method: :attr:`singleton_printers`, :attr:`type_printers`
+ and :attr:`deferred_printers`.
+
+ Users should use these dictionaries to register functions that will be
+ used to compute the format data for their objects (if those objects don't
+ have the special print methods). The easiest way of using these
+ dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
+ methods.
+
+ If no function/callable is found to compute the format data, ``None`` is
+ returned and this format type is not used.
+ """
+
+ format_type = Unicode('text/plain')
+ _return_type = string_types
+
enabled = Bool(True).tag(config=True)
-
- print_method = ObjectName('__repr__')
-
- # The singleton printers.
- # Maps the IDs of the builtin singleton objects to the format functions.
+
+ print_method = ObjectName('__repr__')
+
+ # The singleton printers.
+ # Maps the IDs of the builtin singleton objects to the format functions.
singleton_printers = Dict().tag(config=True)
-
- # The type-specific printers.
- # Map type objects to the format functions.
+
+ # The type-specific printers.
+ # Map type objects to the format functions.
type_printers = Dict().tag(config=True)
-
- # The deferred-import type-specific printers.
- # Map (modulename, classname) pairs to the format functions.
+
+ # The deferred-import type-specific printers.
+ # Map (modulename, classname) pairs to the format functions.
deferred_printers = Dict().tag(config=True)
-
- @catch_format_error
- def __call__(self, obj):
- """Compute the format for an object."""
- if self.enabled:
- # lookup registered printer
- try:
- printer = self.lookup(obj)
- except KeyError:
- pass
- else:
- return printer(obj)
- # Finally look for special method names
+
+ @catch_format_error
+ def __call__(self, obj):
+ """Compute the format for an object."""
+ if self.enabled:
+ # lookup registered printer
+ try:
+ printer = self.lookup(obj)
+ except KeyError:
+ pass
+ else:
+ return printer(obj)
+ # Finally look for special method names
method = get_real_method(obj, self.print_method)
- if method is not None:
- return method()
- return None
- else:
- return None
-
- def __contains__(self, typ):
- """map in to lookup_by_type"""
- try:
- self.lookup_by_type(typ)
- except KeyError:
- return False
- else:
- return True
-
- def _check_return(self, r, obj):
- """Check that a return value is appropriate
-
- Return the value if so, None otherwise, warning if invalid.
- """
- if r is None or isinstance(r, self._return_type) or \
- (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
- return r
- else:
- warnings.warn(
- "%s formatter returned invalid type %s (expected %s) for object: %s" % \
- (self.format_type, type(r), self._return_type, _safe_repr(obj)),
- FormatterWarning
- )
-
- def lookup(self, obj):
- """Look up the formatter for a given instance.
-
- Parameters
- ----------
- obj : object instance
-
- Returns
- -------
- f : callable
- The registered formatting callable for the type.
-
- Raises
- ------
- KeyError if the type has not been registered.
- """
- # look for singleton first
- obj_id = id(obj)
- if obj_id in self.singleton_printers:
- return self.singleton_printers[obj_id]
- # then lookup by type
- return self.lookup_by_type(_get_type(obj))
-
- def lookup_by_type(self, typ):
- """Look up the registered formatter for a type.
-
- Parameters
- ----------
- typ : type or '__module__.__name__' string for a type
-
- Returns
- -------
- f : callable
- The registered formatting callable for the type.
-
- Raises
- ------
- KeyError if the type has not been registered.
- """
- if isinstance(typ, string_types):
- typ_key = tuple(typ.rsplit('.',1))
- if typ_key not in self.deferred_printers:
- # We may have it cached in the type map. We will have to
- # iterate over all of the types to check.
- for cls in self.type_printers:
- if _mod_name_key(cls) == typ_key:
- return self.type_printers[cls]
- else:
- return self.deferred_printers[typ_key]
- else:
- for cls in pretty._get_mro(typ):
- if cls in self.type_printers or self._in_deferred_types(cls):
- return self.type_printers[cls]
-
- # If we have reached here, the lookup failed.
- raise KeyError("No registered printer for {0!r}".format(typ))
-
- def for_type(self, typ, func=None):
- """Add a format function for a given type.
-
- Parameters
- -----------
- typ : type or '__module__.__name__' string for a type
- The class of the object that will be formatted using `func`.
- func : callable
- A callable for computing the format data.
- `func` will be called with the object to be formatted,
- and will return the raw data in this formatter's format.
- Subclasses may use a different call signature for the
- `func` argument.
-
- If `func` is None or not specified, there will be no change,
- only returning the current value.
-
- Returns
- -------
- oldfunc : callable
- The currently registered callable.
- If you are registering a new formatter,
- this will be the previous value (to enable restoring later).
- """
- # if string given, interpret as 'pkg.module.class_name'
- if isinstance(typ, string_types):
- type_module, type_name = typ.rsplit('.', 1)
- return self.for_type_by_name(type_module, type_name, func)
-
- try:
- oldfunc = self.lookup_by_type(typ)
- except KeyError:
- oldfunc = None
-
- if func is not None:
- self.type_printers[typ] = func
-
- return oldfunc
-
- def for_type_by_name(self, type_module, type_name, func=None):
- """Add a format function for a type specified by the full dotted
- module and name of the type, rather than the type of the object.
-
- Parameters
- ----------
- type_module : str
- The full dotted name of the module the type is defined in, like
- ``numpy``.
- type_name : str
- The name of the type (the class name), like ``dtype``
- func : callable
- A callable for computing the format data.
- `func` will be called with the object to be formatted,
- and will return the raw data in this formatter's format.
- Subclasses may use a different call signature for the
- `func` argument.
-
- If `func` is None or unspecified, there will be no change,
- only returning the current value.
-
- Returns
- -------
- oldfunc : callable
- The currently registered callable.
- If you are registering a new formatter,
- this will be the previous value (to enable restoring later).
- """
- key = (type_module, type_name)
-
- try:
- oldfunc = self.lookup_by_type("%s.%s" % key)
- except KeyError:
- oldfunc = None
-
- if func is not None:
- self.deferred_printers[key] = func
- return oldfunc
-
- def pop(self, typ, default=_raise_key_error):
- """Pop a formatter for the given type.
-
- Parameters
- ----------
- typ : type or '__module__.__name__' string for a type
- default : object
- value to be returned if no formatter is registered for typ.
-
- Returns
- -------
- obj : object
- The last registered object for the type.
-
- Raises
- ------
- KeyError if the type is not registered and default is not specified.
- """
-
- if isinstance(typ, string_types):
- typ_key = tuple(typ.rsplit('.',1))
- if typ_key not in self.deferred_printers:
- # We may have it cached in the type map. We will have to
- # iterate over all of the types to check.
- for cls in self.type_printers:
- if _mod_name_key(cls) == typ_key:
- old = self.type_printers.pop(cls)
- break
- else:
- old = default
- else:
- old = self.deferred_printers.pop(typ_key)
- else:
- if typ in self.type_printers:
- old = self.type_printers.pop(typ)
- else:
- old = self.deferred_printers.pop(_mod_name_key(typ), default)
- if old is _raise_key_error:
- raise KeyError("No registered value for {0!r}".format(typ))
- return old
-
- def _in_deferred_types(self, cls):
- """
- Check if the given class is specified in the deferred type registry.
-
- Successful matches will be moved to the regular type registry for future use.
- """
- mod = getattr(cls, '__module__', None)
- name = getattr(cls, '__name__', None)
- key = (mod, name)
- if key in self.deferred_printers:
- # Move the printer over to the regular registry.
- printer = self.deferred_printers.pop(key)
- self.type_printers[cls] = printer
- return True
- return False
-
-
-class PlainTextFormatter(BaseFormatter):
- """The default pretty-printer.
-
- This uses :mod:`IPython.lib.pretty` to compute the format data of
- the object. If the object cannot be pretty printed, :func:`repr` is used.
- See the documentation of :mod:`IPython.lib.pretty` for details on
- how to write pretty printers. Here is a simple example::
-
- def dtype_pprinter(obj, p, cycle):
- if cycle:
- return p.text('dtype(...)')
- if hasattr(obj, 'fields'):
- if obj.fields is None:
- p.text(repr(obj))
- else:
- p.begin_group(7, 'dtype([')
- for i, field in enumerate(obj.descr):
- if i > 0:
- p.text(',')
- p.breakable()
- p.pretty(field)
- p.end_group(7, '])')
- """
-
- # The format type of data returned.
- format_type = Unicode('text/plain')
-
- # This subclass ignores this attribute as it always need to return
- # something.
+ if method is not None:
+ return method()
+ return None
+ else:
+ return None
+
+ def __contains__(self, typ):
+ """map in to lookup_by_type"""
+ try:
+ self.lookup_by_type(typ)
+ except KeyError:
+ return False
+ else:
+ return True
+
+ def _check_return(self, r, obj):
+ """Check that a return value is appropriate
+
+ Return the value if so, None otherwise, warning if invalid.
+ """
+ if r is None or isinstance(r, self._return_type) or \
+ (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
+ return r
+ else:
+ warnings.warn(
+ "%s formatter returned invalid type %s (expected %s) for object: %s" % \
+ (self.format_type, type(r), self._return_type, _safe_repr(obj)),
+ FormatterWarning
+ )
+
+ def lookup(self, obj):
+ """Look up the formatter for a given instance.
+
+ Parameters
+ ----------
+ obj : object instance
+
+ Returns
+ -------
+ f : callable
+ The registered formatting callable for the type.
+
+ Raises
+ ------
+ KeyError if the type has not been registered.
+ """
+ # look for singleton first
+ obj_id = id(obj)
+ if obj_id in self.singleton_printers:
+ return self.singleton_printers[obj_id]
+ # then lookup by type
+ return self.lookup_by_type(_get_type(obj))
+
+ def lookup_by_type(self, typ):
+ """Look up the registered formatter for a type.
+
+ Parameters
+ ----------
+ typ : type or '__module__.__name__' string for a type
+
+ Returns
+ -------
+ f : callable
+ The registered formatting callable for the type.
+
+ Raises
+ ------
+ KeyError if the type has not been registered.
+ """
+ if isinstance(typ, string_types):
+ typ_key = tuple(typ.rsplit('.',1))
+ if typ_key not in self.deferred_printers:
+ # We may have it cached in the type map. We will have to
+ # iterate over all of the types to check.
+ for cls in self.type_printers:
+ if _mod_name_key(cls) == typ_key:
+ return self.type_printers[cls]
+ else:
+ return self.deferred_printers[typ_key]
+ else:
+ for cls in pretty._get_mro(typ):
+ if cls in self.type_printers or self._in_deferred_types(cls):
+ return self.type_printers[cls]
+
+ # If we have reached here, the lookup failed.
+ raise KeyError("No registered printer for {0!r}".format(typ))
+
+ def for_type(self, typ, func=None):
+ """Add a format function for a given type.
+
+ Parameters
+ -----------
+ typ : type or '__module__.__name__' string for a type
+ The class of the object that will be formatted using `func`.
+ func : callable
+ A callable for computing the format data.
+ `func` will be called with the object to be formatted,
+ and will return the raw data in this formatter's format.
+ Subclasses may use a different call signature for the
+ `func` argument.
+
+ If `func` is None or not specified, there will be no change,
+ only returning the current value.
+
+ Returns
+ -------
+ oldfunc : callable
+ The currently registered callable.
+ If you are registering a new formatter,
+ this will be the previous value (to enable restoring later).
+ """
+ # if string given, interpret as 'pkg.module.class_name'
+ if isinstance(typ, string_types):
+ type_module, type_name = typ.rsplit('.', 1)
+ return self.for_type_by_name(type_module, type_name, func)
+
+ try:
+ oldfunc = self.lookup_by_type(typ)
+ except KeyError:
+ oldfunc = None
+
+ if func is not None:
+ self.type_printers[typ] = func
+
+ return oldfunc
+
+ def for_type_by_name(self, type_module, type_name, func=None):
+ """Add a format function for a type specified by the full dotted
+ module and name of the type, rather than the type of the object.
+
+ Parameters
+ ----------
+ type_module : str
+ The full dotted name of the module the type is defined in, like
+ ``numpy``.
+ type_name : str
+ The name of the type (the class name), like ``dtype``
+ func : callable
+ A callable for computing the format data.
+ `func` will be called with the object to be formatted,
+ and will return the raw data in this formatter's format.
+ Subclasses may use a different call signature for the
+ `func` argument.
+
+ If `func` is None or unspecified, there will be no change,
+ only returning the current value.
+
+ Returns
+ -------
+ oldfunc : callable
+ The currently registered callable.
+ If you are registering a new formatter,
+ this will be the previous value (to enable restoring later).
+ """
+ key = (type_module, type_name)
+
+ try:
+ oldfunc = self.lookup_by_type("%s.%s" % key)
+ except KeyError:
+ oldfunc = None
+
+ if func is not None:
+ self.deferred_printers[key] = func
+ return oldfunc
+
+ def pop(self, typ, default=_raise_key_error):
+ """Pop a formatter for the given type.
+
+ Parameters
+ ----------
+ typ : type or '__module__.__name__' string for a type
+ default : object
+ value to be returned if no formatter is registered for typ.
+
+ Returns
+ -------
+ obj : object
+ The last registered object for the type.
+
+ Raises
+ ------
+ KeyError if the type is not registered and default is not specified.
+ """
+
+ if isinstance(typ, string_types):
+ typ_key = tuple(typ.rsplit('.',1))
+ if typ_key not in self.deferred_printers:
+ # We may have it cached in the type map. We will have to
+ # iterate over all of the types to check.
+ for cls in self.type_printers:
+ if _mod_name_key(cls) == typ_key:
+ old = self.type_printers.pop(cls)
+ break
+ else:
+ old = default
+ else:
+ old = self.deferred_printers.pop(typ_key)
+ else:
+ if typ in self.type_printers:
+ old = self.type_printers.pop(typ)
+ else:
+ old = self.deferred_printers.pop(_mod_name_key(typ), default)
+ if old is _raise_key_error:
+ raise KeyError("No registered value for {0!r}".format(typ))
+ return old
+
+ def _in_deferred_types(self, cls):
+ """
+ Check if the given class is specified in the deferred type registry.
+
+ Successful matches will be moved to the regular type registry for future use.
+ """
+ mod = getattr(cls, '__module__', None)
+ name = getattr(cls, '__name__', None)
+ key = (mod, name)
+ if key in self.deferred_printers:
+ # Move the printer over to the regular registry.
+ printer = self.deferred_printers.pop(key)
+ self.type_printers[cls] = printer
+ return True
+ return False
+
+
+class PlainTextFormatter(BaseFormatter):
+ """The default pretty-printer.
+
+ This uses :mod:`IPython.lib.pretty` to compute the format data of
+ the object. If the object cannot be pretty printed, :func:`repr` is used.
+ See the documentation of :mod:`IPython.lib.pretty` for details on
+ how to write pretty printers. Here is a simple example::
+
+ def dtype_pprinter(obj, p, cycle):
+ if cycle:
+ return p.text('dtype(...)')
+ if hasattr(obj, 'fields'):
+ if obj.fields is None:
+ p.text(repr(obj))
+ else:
+ p.begin_group(7, 'dtype([')
+ for i, field in enumerate(obj.descr):
+ if i > 0:
+ p.text(',')
+ p.breakable()
+ p.pretty(field)
+ p.end_group(7, '])')
+ """
+
+ # The format type of data returned.
+ format_type = Unicode('text/plain')
+
+ # This subclass ignores this attribute as it always need to return
+ # something.
enabled = Bool(True).tag(config=False)
-
+
max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
- help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
-
- Set to 0 to disable truncation.
- """
+ help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
+
+ Set to 0 to disable truncation.
+ """
).tag(config=True)
-
- # Look for a _repr_pretty_ methods to use for pretty printing.
- print_method = ObjectName('_repr_pretty_')
-
- # Whether to pretty-print or not.
+
+ # Look for a _repr_pretty_ methods to use for pretty printing.
+ print_method = ObjectName('_repr_pretty_')
+
+ # Whether to pretty-print or not.
pprint = Bool(True).tag(config=True)
-
- # Whether to be verbose or not.
+
+ # Whether to be verbose or not.
verbose = Bool(False).tag(config=True)
-
- # The maximum width.
+
+ # The maximum width.
max_width = Integer(79).tag(config=True)
-
- # The newline character.
+
+ # The newline character.
newline = Unicode('\n').tag(config=True)
-
- # format-string for pprinting floats
- float_format = Unicode('%r')
- # setter for float precision, either int or direct format-string
+
+ # format-string for pprinting floats
+ float_format = Unicode('%r')
+ # setter for float precision, either int or direct format-string
float_precision = CUnicode('').tag(config=True)
-
+
@observe('float_precision')
def _float_precision_changed(self, change):
- """float_precision changed, set float_format accordingly.
-
- float_precision can be set by int or str.
- This will set float_format, after interpreting input.
- If numpy has been imported, numpy print precision will also be set.
-
- integer `n` sets format to '%.nf', otherwise, format set directly.
-
- An empty string returns to defaults (repr for float, 8 for numpy).
-
- This parameter can be set via the '%precision' magic.
- """
-
+ """float_precision changed, set float_format accordingly.
+
+ float_precision can be set by int or str.
+ This will set float_format, after interpreting input.
+ If numpy has been imported, numpy print precision will also be set.
+
+ integer `n` sets format to '%.nf', otherwise, format set directly.
+
+ An empty string returns to defaults (repr for float, 8 for numpy).
+
+ This parameter can be set via the '%precision' magic.
+ """
+
new = change['new']
- if '%' in new:
- # got explicit format string
- fmt = new
- try:
- fmt%3.14159
- except Exception:
- raise ValueError("Precision must be int or format string, not %r"%new)
- elif new:
- # otherwise, should be an int
- try:
- i = int(new)
- assert i >= 0
- except ValueError:
- raise ValueError("Precision must be int or format string, not %r"%new)
- except AssertionError:
- raise ValueError("int precision must be non-negative, not %r"%i)
-
- fmt = '%%.%if'%i
- if 'numpy' in sys.modules:
- # set numpy precision if it has been imported
- import numpy
- numpy.set_printoptions(precision=i)
- else:
- # default back to repr
- fmt = '%r'
- if 'numpy' in sys.modules:
- import numpy
- # numpy default is 8
- numpy.set_printoptions(precision=8)
- self.float_format = fmt
-
- # Use the default pretty printers from IPython.lib.pretty.
+ if '%' in new:
+ # got explicit format string
+ fmt = new
+ try:
+ fmt%3.14159
+ except Exception:
+ raise ValueError("Precision must be int or format string, not %r"%new)
+ elif new:
+ # otherwise, should be an int
+ try:
+ i = int(new)
+ assert i >= 0
+ except ValueError:
+ raise ValueError("Precision must be int or format string, not %r"%new)
+ except AssertionError:
+ raise ValueError("int precision must be non-negative, not %r"%i)
+
+ fmt = '%%.%if'%i
+ if 'numpy' in sys.modules:
+ # set numpy precision if it has been imported
+ import numpy
+ numpy.set_printoptions(precision=i)
+ else:
+ # default back to repr
+ fmt = '%r'
+ if 'numpy' in sys.modules:
+ import numpy
+ # numpy default is 8
+ numpy.set_printoptions(precision=8)
+ self.float_format = fmt
+
+ # Use the default pretty printers from IPython.lib.pretty.
@default('singleton_printers')
- def _singleton_printers_default(self):
- return pretty._singleton_pprinters.copy()
-
+ def _singleton_printers_default(self):
+ return pretty._singleton_pprinters.copy()
+
@default('type_printers')
- def _type_printers_default(self):
- d = pretty._type_pprinters.copy()
- d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
- return d
-
+ def _type_printers_default(self):
+ d = pretty._type_pprinters.copy()
+ d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
+ return d
+
@default('deferred_printers')
- def _deferred_printers_default(self):
- return pretty._deferred_type_pprinters.copy()
-
- #### FormatterABC interface ####
-
- @catch_format_error
- def __call__(self, obj):
- """Compute the pretty representation of the object."""
- if not self.pprint:
- return repr(obj)
- else:
- # handle str and unicode on Python 2
- # io.StringIO only accepts unicode,
- # cStringIO doesn't handle unicode on py2,
- # StringIO allows str, unicode but only ascii str
- stream = pretty.CUnicodeIO()
- printer = pretty.RepresentationPrinter(stream, self.verbose,
- self.max_width, self.newline,
- max_seq_length=self.max_seq_length,
- singleton_pprinters=self.singleton_printers,
- type_pprinters=self.type_printers,
- deferred_pprinters=self.deferred_printers)
- printer.pretty(obj)
- printer.flush()
- return stream.getvalue()
-
-
-class HTMLFormatter(BaseFormatter):
- """An HTML formatter.
-
- To define the callables that compute the HTML representation of your
- objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
- or :meth:`for_type_by_name` methods to register functions that handle
- this.
-
- The return value of this formatter should be a valid HTML snippet that
- could be injected into an existing DOM. It should *not* include the
- ```<html>`` or ```<body>`` tags.
- """
- format_type = Unicode('text/html')
-
- print_method = ObjectName('_repr_html_')
-
-
-class MarkdownFormatter(BaseFormatter):
- """A Markdown formatter.
-
- To define the callables that compute the Markdown representation of your
- objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
- or :meth:`for_type_by_name` methods to register functions that handle
- this.
-
- The return value of this formatter should be a valid Markdown.
- """
- format_type = Unicode('text/markdown')
-
- print_method = ObjectName('_repr_markdown_')
-
-class SVGFormatter(BaseFormatter):
- """An SVG formatter.
-
- To define the callables that compute the SVG representation of your
- objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
- or :meth:`for_type_by_name` methods to register functions that handle
- this.
-
- The return value of this formatter should be valid SVG enclosed in
- ```<svg>``` tags, that could be injected into an existing DOM. It should
- *not* include the ```<html>`` or ```<body>`` tags.
- """
- format_type = Unicode('image/svg+xml')
-
- print_method = ObjectName('_repr_svg_')
-
-
-class PNGFormatter(BaseFormatter):
- """A PNG formatter.
-
- To define the callables that compute the PNG representation of your
- objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
- or :meth:`for_type_by_name` methods to register functions that handle
- this.
-
- The return value of this formatter should be raw PNG data, *not*
- base64 encoded.
- """
- format_type = Unicode('image/png')
-
- print_method = ObjectName('_repr_png_')
-
- _return_type = (bytes, unicode_type)
-
-
-class JPEGFormatter(BaseFormatter):
- """A JPEG formatter.
-
- To define the callables that compute the JPEG representation of your
- objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
- or :meth:`for_type_by_name` methods to register functions that handle
- this.
-
- The return value of this formatter should be raw JPEG data, *not*
- base64 encoded.
- """
- format_type = Unicode('image/jpeg')
-
- print_method = ObjectName('_repr_jpeg_')
-
- _return_type = (bytes, unicode_type)
-
-
-class LatexFormatter(BaseFormatter):
- """A LaTeX formatter.
-
- To define the callables that compute the LaTeX representation of your
- objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
- or :meth:`for_type_by_name` methods to register functions that handle
- this.
-
- The return value of this formatter should be a valid LaTeX equation,
- enclosed in either ```$```, ```$$``` or another LaTeX equation
- environment.
- """
- format_type = Unicode('text/latex')
-
- print_method = ObjectName('_repr_latex_')
-
-
-class JSONFormatter(BaseFormatter):
- """A JSON string formatter.
-
- To define the callables that compute the JSONable representation of
- your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
- or :meth:`for_type_by_name` methods to register functions that handle
- this.
-
- The return value of this formatter should be a JSONable list or dict.
- JSON scalars (None, number, string) are not allowed, only dict or list containers.
- """
- format_type = Unicode('application/json')
- _return_type = (list, dict)
-
- print_method = ObjectName('_repr_json_')
-
- def _check_return(self, r, obj):
- """Check that a return value is appropriate
-
- Return the value if so, None otherwise, warning if invalid.
- """
- if r is None:
- return
- md = None
- if isinstance(r, tuple):
- # unpack data, metadata tuple for type checking on first element
- r, md = r
-
- # handle deprecated JSON-as-string form from IPython < 3
- if isinstance(r, string_types):
- warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
- FormatterWarning)
- r = json.loads(r)
-
- if md is not None:
- # put the tuple back together
- r = (r, md)
- return super(JSONFormatter, self)._check_return(r, obj)
-
-
-class JavascriptFormatter(BaseFormatter):
- """A Javascript formatter.
-
- To define the callables that compute the Javascript representation of
- your objects, define a :meth:`_repr_javascript_` method or use the
- :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
- that handle this.
-
- The return value of this formatter should be valid Javascript code and
- should *not* be enclosed in ```<script>``` tags.
- """
- format_type = Unicode('application/javascript')
-
- print_method = ObjectName('_repr_javascript_')
-
-
-class PDFFormatter(BaseFormatter):
- """A PDF formatter.
-
- To define the callables that compute the PDF representation of your
- objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
- or :meth:`for_type_by_name` methods to register functions that handle
- this.
-
- The return value of this formatter should be raw PDF data, *not*
- base64 encoded.
- """
- format_type = Unicode('application/pdf')
-
- print_method = ObjectName('_repr_pdf_')
-
- _return_type = (bytes, unicode_type)
-
-class IPythonDisplayFormatter(BaseFormatter):
+ def _deferred_printers_default(self):
+ return pretty._deferred_type_pprinters.copy()
+
+ #### FormatterABC interface ####
+
+ @catch_format_error
+ def __call__(self, obj):
+ """Compute the pretty representation of the object."""
+ if not self.pprint:
+ return repr(obj)
+ else:
+ # handle str and unicode on Python 2
+ # io.StringIO only accepts unicode,
+ # cStringIO doesn't handle unicode on py2,
+ # StringIO allows str, unicode but only ascii str
+ stream = pretty.CUnicodeIO()
+ printer = pretty.RepresentationPrinter(stream, self.verbose,
+ self.max_width, self.newline,
+ max_seq_length=self.max_seq_length,
+ singleton_pprinters=self.singleton_printers,
+ type_pprinters=self.type_printers,
+ deferred_pprinters=self.deferred_printers)
+ printer.pretty(obj)
+ printer.flush()
+ return stream.getvalue()
+
+
+class HTMLFormatter(BaseFormatter):
+ """An HTML formatter.
+
+ To define the callables that compute the HTML representation of your
+ objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
+ or :meth:`for_type_by_name` methods to register functions that handle
+ this.
+
+ The return value of this formatter should be a valid HTML snippet that
+ could be injected into an existing DOM. It should *not* include the
+ ```<html>`` or ```<body>`` tags.
+ """
+ format_type = Unicode('text/html')
+
+ print_method = ObjectName('_repr_html_')
+
+
+class MarkdownFormatter(BaseFormatter):
+ """A Markdown formatter.
+
+ To define the callables that compute the Markdown representation of your
+ objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
+ or :meth:`for_type_by_name` methods to register functions that handle
+ this.
+
+ The return value of this formatter should be a valid Markdown.
+ """
+ format_type = Unicode('text/markdown')
+
+ print_method = ObjectName('_repr_markdown_')
+
+class SVGFormatter(BaseFormatter):
+ """An SVG formatter.
+
+ To define the callables that compute the SVG representation of your
+ objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
+ or :meth:`for_type_by_name` methods to register functions that handle
+ this.
+
+ The return value of this formatter should be valid SVG enclosed in
+ ```<svg>``` tags, that could be injected into an existing DOM. It should
+ *not* include the ```<html>`` or ```<body>`` tags.
+ """
+ format_type = Unicode('image/svg+xml')
+
+ print_method = ObjectName('_repr_svg_')
+
+
+class PNGFormatter(BaseFormatter):
+ """A PNG formatter.
+
+ To define the callables that compute the PNG representation of your
+ objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
+ or :meth:`for_type_by_name` methods to register functions that handle
+ this.
+
+ The return value of this formatter should be raw PNG data, *not*
+ base64 encoded.
+ """
+ format_type = Unicode('image/png')
+
+ print_method = ObjectName('_repr_png_')
+
+ _return_type = (bytes, unicode_type)
+
+
+class JPEGFormatter(BaseFormatter):
+ """A JPEG formatter.
+
+ To define the callables that compute the JPEG representation of your
+ objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
+ or :meth:`for_type_by_name` methods to register functions that handle
+ this.
+
+ The return value of this formatter should be raw JPEG data, *not*
+ base64 encoded.
+ """
+ format_type = Unicode('image/jpeg')
+
+ print_method = ObjectName('_repr_jpeg_')
+
+ _return_type = (bytes, unicode_type)
+
+
+class LatexFormatter(BaseFormatter):
+ """A LaTeX formatter.
+
+ To define the callables that compute the LaTeX representation of your
+ objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
+ or :meth:`for_type_by_name` methods to register functions that handle
+ this.
+
+ The return value of this formatter should be a valid LaTeX equation,
+ enclosed in either ```$```, ```$$``` or another LaTeX equation
+ environment.
+ """
+ format_type = Unicode('text/latex')
+
+ print_method = ObjectName('_repr_latex_')
+
+
+class JSONFormatter(BaseFormatter):
+ """A JSON string formatter.
+
+ To define the callables that compute the JSONable representation of
+ your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
+ or :meth:`for_type_by_name` methods to register functions that handle
+ this.
+
+ The return value of this formatter should be a JSONable list or dict.
+ JSON scalars (None, number, string) are not allowed, only dict or list containers.
+ """
+ format_type = Unicode('application/json')
+ _return_type = (list, dict)
+
+ print_method = ObjectName('_repr_json_')
+
+ def _check_return(self, r, obj):
+ """Check that a return value is appropriate
+
+ Return the value if so, None otherwise, warning if invalid.
+ """
+ if r is None:
+ return
+ md = None
+ if isinstance(r, tuple):
+ # unpack data, metadata tuple for type checking on first element
+ r, md = r
+
+ # handle deprecated JSON-as-string form from IPython < 3
+ if isinstance(r, string_types):
+ warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
+ FormatterWarning)
+ r = json.loads(r)
+
+ if md is not None:
+ # put the tuple back together
+ r = (r, md)
+ return super(JSONFormatter, self)._check_return(r, obj)
+
+
+class JavascriptFormatter(BaseFormatter):
+ """A Javascript formatter.
+
+ To define the callables that compute the Javascript representation of
+ your objects, define a :meth:`_repr_javascript_` method or use the
+ :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
+ that handle this.
+
+ The return value of this formatter should be valid Javascript code and
+ should *not* be enclosed in ```<script>``` tags.
+ """
+ format_type = Unicode('application/javascript')
+
+ print_method = ObjectName('_repr_javascript_')
+
+
+class PDFFormatter(BaseFormatter):
+ """A PDF formatter.
+
+ To define the callables that compute the PDF representation of your
+ objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
+ or :meth:`for_type_by_name` methods to register functions that handle
+ this.
+
+ The return value of this formatter should be raw PDF data, *not*
+ base64 encoded.
+ """
+ format_type = Unicode('application/pdf')
+
+ print_method = ObjectName('_repr_pdf_')
+
+ _return_type = (bytes, unicode_type)
+
+class IPythonDisplayFormatter(BaseFormatter):
"""An escape-hatch Formatter for objects that know how to display themselves.
-
- To define the callables that compute the representation of your
- objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
- or :meth:`for_type_by_name` methods to register functions that handle
- this. Unlike mime-type displays, this method should not return anything,
- instead calling any appropriate display methods itself.
-
- This display formatter has highest priority.
- If it fires, no other display formatter will be called.
+
+ To define the callables that compute the representation of your
+ objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
+ or :meth:`for_type_by_name` methods to register functions that handle
+ this. Unlike mime-type displays, this method should not return anything,
+ instead calling any appropriate display methods itself.
+
+ This display formatter has highest priority.
+ If it fires, no other display formatter will be called.
Prior to IPython 6.1, `_ipython_display_` was the only way to display custom mime-types
without registering a new Formatter.
@@ -893,29 +893,29 @@ class IPythonDisplayFormatter(BaseFormatter):
IPython 6.1 introduces `_repr_mimebundle_` for displaying custom mime-types,
so `_ipython_display_` should only be used for objects that require unusual
display patterns, such as multiple display calls.
- """
- print_method = ObjectName('_ipython_display_')
- _return_type = (type(None), bool)
-
- @catch_format_error
- def __call__(self, obj):
- """Compute the format for an object."""
- if self.enabled:
- # lookup registered printer
- try:
- printer = self.lookup(obj)
- except KeyError:
- pass
- else:
- printer(obj)
- return True
- # Finally look for special method names
+ """
+ print_method = ObjectName('_ipython_display_')
+ _return_type = (type(None), bool)
+
+ @catch_format_error
+ def __call__(self, obj):
+ """Compute the format for an object."""
+ if self.enabled:
+ # lookup registered printer
+ try:
+ printer = self.lookup(obj)
+ except KeyError:
+ pass
+ else:
+ printer(obj)
+ return True
+ # Finally look for special method names
method = get_real_method(obj, self.print_method)
- if method is not None:
- method()
- return True
-
-
+ if method is not None:
+ method()
+ return True
+
+
class MimeBundleFormatter(BaseFormatter):
"""A Formatter for arbitrary mime-types.
@@ -973,65 +973,65 @@ class MimeBundleFormatter(BaseFormatter):
return None
-FormatterABC.register(BaseFormatter)
-FormatterABC.register(PlainTextFormatter)
-FormatterABC.register(HTMLFormatter)
-FormatterABC.register(MarkdownFormatter)
-FormatterABC.register(SVGFormatter)
-FormatterABC.register(PNGFormatter)
-FormatterABC.register(PDFFormatter)
-FormatterABC.register(JPEGFormatter)
-FormatterABC.register(LatexFormatter)
-FormatterABC.register(JSONFormatter)
-FormatterABC.register(JavascriptFormatter)
-FormatterABC.register(IPythonDisplayFormatter)
+FormatterABC.register(BaseFormatter)
+FormatterABC.register(PlainTextFormatter)
+FormatterABC.register(HTMLFormatter)
+FormatterABC.register(MarkdownFormatter)
+FormatterABC.register(SVGFormatter)
+FormatterABC.register(PNGFormatter)
+FormatterABC.register(PDFFormatter)
+FormatterABC.register(JPEGFormatter)
+FormatterABC.register(LatexFormatter)
+FormatterABC.register(JSONFormatter)
+FormatterABC.register(JavascriptFormatter)
+FormatterABC.register(IPythonDisplayFormatter)
FormatterABC.register(MimeBundleFormatter)
-
-
-def format_display_data(obj, include=None, exclude=None):
- """Return a format data dict for an object.
-
- By default all format types will be computed.
-
- The following MIME types are currently implemented:
-
- * text/plain
- * text/html
- * text/markdown
- * text/latex
- * application/json
- * application/javascript
- * application/pdf
- * image/png
- * image/jpeg
- * image/svg+xml
-
- Parameters
- ----------
- obj : object
- The Python object whose format data will be computed.
-
- Returns
- -------
- format_dict : dict
- A dictionary of key/value pairs, one or each format that was
- generated for the object. The keys are the format types, which
- will usually be MIME type strings and the values and JSON'able
- data structure containing the raw data for the representation in
- that format.
- include : list or tuple, optional
- A list of format type strings (MIME types) to include in the
- format data dict. If this is set *only* the format types included
- in this list will be computed.
- exclude : list or tuple, optional
- A list of format type string (MIME types) to exclue in the format
- data dict. If this is set all format types will be computed,
- except for those included in this argument.
- """
- from IPython.core.interactiveshell import InteractiveShell
-
+
+
+def format_display_data(obj, include=None, exclude=None):
+ """Return a format data dict for an object.
+
+ By default all format types will be computed.
+
+ The following MIME types are currently implemented:
+
+ * text/plain
+ * text/html
+ * text/markdown
+ * text/latex
+ * application/json
+ * application/javascript
+ * application/pdf
+ * image/png
+ * image/jpeg
+ * image/svg+xml
+
+ Parameters
+ ----------
+ obj : object
+ The Python object whose format data will be computed.
+
+ Returns
+ -------
+ format_dict : dict
+ A dictionary of key/value pairs, one or each format that was
+ generated for the object. The keys are the format types, which
+ will usually be MIME type strings and the values and JSON'able
+ data structure containing the raw data for the representation in
+ that format.
+ include : list or tuple, optional
+ A list of format type strings (MIME types) to include in the
+ format data dict. If this is set *only* the format types included
+ in this list will be computed.
+ exclude : list or tuple, optional
+ A list of format type string (MIME types) to exclue in the format
+ data dict. If this is set all format types will be computed,
+ except for those included in this argument.
+ """
+ from IPython.core.interactiveshell import InteractiveShell
+
return InteractiveShell.instance().display_formatter.format(
- obj,
- include,
- exclude
- )
+ obj,
+ include,
+ exclude
+ )
diff --git a/contrib/python/ipython/py2/IPython/core/getipython.py b/contrib/python/ipython/py2/IPython/core/getipython.py
index 9a127418ad..e6d8a4c91d 100644
--- a/contrib/python/ipython/py2/IPython/core/getipython.py
+++ b/contrib/python/ipython/py2/IPython/core/getipython.py
@@ -1,24 +1,24 @@
-# encoding: utf-8
-"""Simple function to call to get the current InteractiveShell instance
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2013 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Classes and functions
-#-----------------------------------------------------------------------------
-
-
-def get_ipython():
- """Get the global InteractiveShell instance.
-
- Returns None if no InteractiveShell instance is registered.
- """
- from IPython.core.interactiveshell import InteractiveShell
- if InteractiveShell.initialized():
- return InteractiveShell.instance()
+# encoding: utf-8
+"""Simple function to call to get the current InteractiveShell instance
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2013 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Classes and functions
+#-----------------------------------------------------------------------------
+
+
+def get_ipython():
+ """Get the global InteractiveShell instance.
+
+ Returns None if no InteractiveShell instance is registered.
+ """
+ from IPython.core.interactiveshell import InteractiveShell
+ if InteractiveShell.initialized():
+ return InteractiveShell.instance()
diff --git a/contrib/python/ipython/py2/IPython/core/history.py b/contrib/python/ipython/py2/IPython/core/history.py
index df5965695b..2e7fdbc845 100644
--- a/contrib/python/ipython/py2/IPython/core/history.py
+++ b/contrib/python/ipython/py2/IPython/core/history.py
@@ -1,92 +1,92 @@
-""" History related magics and functionality """
-
+""" History related magics and functionality """
+
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
-from __future__ import print_function
-
-import atexit
-import datetime
-import os
-import re
-try:
- import sqlite3
-except ImportError:
- try:
- from pysqlite2 import dbapi2 as sqlite3
- except ImportError:
- sqlite3 = None
-import threading
-
+from __future__ import print_function
+
+import atexit
+import datetime
+import os
+import re
+try:
+ import sqlite3
+except ImportError:
+ try:
+ from pysqlite2 import dbapi2 as sqlite3
+ except ImportError:
+ sqlite3 = None
+import threading
+
from traitlets.config.configurable import LoggingConfigurable
-from decorator import decorator
-from IPython.utils.decorators import undoc
+from decorator import decorator
+from IPython.utils.decorators import undoc
from IPython.paths import locate_profile
-from IPython.utils import py3compat
-from traitlets import (
- Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
+from IPython.utils import py3compat
+from traitlets import (
+ Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
default, observe,
-)
+)
from warnings import warn
-
-#-----------------------------------------------------------------------------
-# Classes and functions
-#-----------------------------------------------------------------------------
-
-@undoc
-class DummyDB(object):
- """Dummy DB that will act as a black hole for history.
-
- Only used in the absence of sqlite"""
- def execute(*args, **kwargs):
- return []
-
- def commit(self, *args, **kwargs):
- pass
-
- def __enter__(self, *args, **kwargs):
- pass
-
- def __exit__(self, *args, **kwargs):
- pass
-
-
-@decorator
-def needs_sqlite(f, self, *a, **kw):
- """Decorator: return an empty list in the absence of sqlite."""
- if sqlite3 is None or not self.enabled:
- return []
- else:
- return f(self, *a, **kw)
-
-
-if sqlite3 is not None:
- DatabaseError = sqlite3.DatabaseError
- OperationalError = sqlite3.OperationalError
-else:
- @undoc
- class DatabaseError(Exception):
- "Dummy exception when sqlite could not be imported. Should never occur."
-
- @undoc
- class OperationalError(Exception):
- "Dummy exception when sqlite could not be imported. Should never occur."
-
+
+#-----------------------------------------------------------------------------
+# Classes and functions
+#-----------------------------------------------------------------------------
+
+@undoc
+class DummyDB(object):
+ """Dummy DB that will act as a black hole for history.
+
+ Only used in the absence of sqlite"""
+ def execute(*args, **kwargs):
+ return []
+
+ def commit(self, *args, **kwargs):
+ pass
+
+ def __enter__(self, *args, **kwargs):
+ pass
+
+ def __exit__(self, *args, **kwargs):
+ pass
+
+
+@decorator
+def needs_sqlite(f, self, *a, **kw):
+ """Decorator: return an empty list in the absence of sqlite."""
+ if sqlite3 is None or not self.enabled:
+ return []
+ else:
+ return f(self, *a, **kw)
+
+
+if sqlite3 is not None:
+ DatabaseError = sqlite3.DatabaseError
+ OperationalError = sqlite3.OperationalError
+else:
+ @undoc
+ class DatabaseError(Exception):
+ "Dummy exception when sqlite could not be imported. Should never occur."
+
+ @undoc
+ class OperationalError(Exception):
+ "Dummy exception when sqlite could not be imported. Should never occur."
+
# use 16kB as threshold for whether a corrupt history db should be saved
# that should be at least 100 entries or so
_SAVE_DB_SIZE = 16384
-@decorator
-def catch_corrupt_db(f, self, *a, **kw):
- """A decorator which wraps HistoryAccessor method calls to catch errors from
- a corrupt SQLite database, move the old database out of the way, and create
- a new one.
+@decorator
+def catch_corrupt_db(f, self, *a, **kw):
+ """A decorator which wraps HistoryAccessor method calls to catch errors from
+ a corrupt SQLite database, move the old database out of the way, and create
+ a new one.
We avoid clobbering larger databases because this may be triggered due to filesystem issues,
not just a corrupt file.
- """
- try:
- return f(self, *a, **kw)
+ """
+ try:
+ return f(self, *a, **kw)
except (DatabaseError, OperationalError) as e:
self._corrupt_db_counter += 1
self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
@@ -114,799 +114,799 @@ def catch_corrupt_db(f, self, *a, **kw):
newpath = base + '-corrupt' + ext
os.rename(self.hist_file, newpath)
self.log.error("History file was moved to %s and a new file created.", newpath)
- self.init_db()
- return []
- else:
+ self.init_db()
+ return []
+ else:
# Failed with :memory:, something serious is wrong
- raise
-
+ raise
+
class HistoryAccessorBase(LoggingConfigurable):
- """An abstract class for History Accessors """
-
- def get_tail(self, n=10, raw=True, output=False, include_latest=False):
- raise NotImplementedError
-
- def search(self, pattern="*", raw=True, search_raw=True,
- output=False, n=None, unique=False):
- raise NotImplementedError
-
- def get_range(self, session, start=1, stop=None, raw=True,output=False):
- raise NotImplementedError
-
- def get_range_by_str(self, rangestr, raw=True, output=False):
- raise NotImplementedError
-
-
-class HistoryAccessor(HistoryAccessorBase):
- """Access the history database without adding to it.
-
- This is intended for use by standalone history tools. IPython shells use
- HistoryManager, below, which is a subclass of this."""
-
+ """An abstract class for History Accessors """
+
+ def get_tail(self, n=10, raw=True, output=False, include_latest=False):
+ raise NotImplementedError
+
+ def search(self, pattern="*", raw=True, search_raw=True,
+ output=False, n=None, unique=False):
+ raise NotImplementedError
+
+ def get_range(self, session, start=1, stop=None, raw=True,output=False):
+ raise NotImplementedError
+
+ def get_range_by_str(self, rangestr, raw=True, output=False):
+ raise NotImplementedError
+
+
+class HistoryAccessor(HistoryAccessorBase):
+ """Access the history database without adding to it.
+
+ This is intended for use by standalone history tools. IPython shells use
+ HistoryManager, below, which is a subclass of this."""
+
# counter for init_db retries, so we don't keep trying over and over
_corrupt_db_counter = 0
# after two failures, fallback on :memory:
_corrupt_db_limit = 2
- # String holding the path to the history file
+ # String holding the path to the history file
hist_file = Unicode(
- help="""Path to file to use for SQLite history database.
-
- By default, IPython will put the history database in the IPython
- profile directory. If you would rather share one history among
- profiles, you can set this value in each, so that they are consistent.
-
- Due to an issue with fcntl, SQLite is known to misbehave on some NFS
- mounts. If you see IPython hanging, try setting this to something on a
- local disk, e.g::
-
- ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
+ help="""Path to file to use for SQLite history database.
+
+ By default, IPython will put the history database in the IPython
+ profile directory. If you would rather share one history among
+ profiles, you can set this value in each, so that they are consistent.
+
+ Due to an issue with fcntl, SQLite is known to misbehave on some NFS
+ mounts. If you see IPython hanging, try setting this to something on a
+ local disk, e.g::
+
+ ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
you can also use the specific value `:memory:` (including the colon
at both end but not the back ticks), to avoid creating an history file.
-
+
""").tag(config=True)
-
+
enabled = Bool(True,
- help="""enable the SQLite history
-
- set enabled=False to disable the SQLite history,
- in which case there will be no stored history, no SQLite connection,
- and no background saving thread. This may be necessary in some
- threaded environments where IPython is embedded.
- """
+ help="""enable the SQLite history
+
+ set enabled=False to disable the SQLite history,
+ in which case there will be no stored history, no SQLite connection,
+ and no background saving thread. This may be necessary in some
+ threaded environments where IPython is embedded.
+ """
).tag(config=True)
-
+
connection_options = Dict(
- help="""Options for configuring the SQLite connection
-
- These options are passed as keyword args to sqlite3.connect
- when establishing database conenctions.
- """
+ help="""Options for configuring the SQLite connection
+
+ These options are passed as keyword args to sqlite3.connect
+ when establishing database conenctions.
+ """
).tag(config=True)
-
- # The SQLite database
- db = Any()
+
+ # The SQLite database
+ db = Any()
@observe('db')
def _db_changed(self, change):
- """validate the db, since it can be an Instance of two different types"""
+ """validate the db, since it can be an Instance of two different types"""
new = change['new']
- connection_types = (DummyDB,)
- if sqlite3 is not None:
- connection_types = (DummyDB, sqlite3.Connection)
- if not isinstance(new, connection_types):
- msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
- (self.__class__.__name__, new)
- raise TraitError(msg)
-
- def __init__(self, profile='default', hist_file=u'', **traits):
- """Create a new history accessor.
-
- Parameters
- ----------
- profile : str
- The name of the profile from which to open history.
- hist_file : str
- Path to an SQLite history database stored by IPython. If specified,
- hist_file overrides profile.
- config : :class:`~traitlets.config.loader.Config`
- Config object. hist_file can also be set through this.
- """
- # We need a pointer back to the shell for various tasks.
- super(HistoryAccessor, self).__init__(**traits)
- # defer setting hist_file from kwarg until after init,
- # otherwise the default kwarg value would clobber any value
- # set by config
- if hist_file:
- self.hist_file = hist_file
-
- if self.hist_file == u'':
- # No one has set the hist_file, yet.
- self.hist_file = self._get_hist_file_name(profile)
-
- if sqlite3 is None and self.enabled:
- warn("IPython History requires SQLite, your history will not be saved")
- self.enabled = False
-
- self.init_db()
-
- def _get_hist_file_name(self, profile='default'):
- """Find the history file for the given profile name.
-
- This is overridden by the HistoryManager subclass, to use the shell's
- active profile.
-
- Parameters
- ----------
- profile : str
- The name of a profile which has a history file.
- """
- return os.path.join(locate_profile(profile), 'history.sqlite')
-
- @catch_corrupt_db
- def init_db(self):
- """Connect to the database, and create tables if necessary."""
- if not self.enabled:
- self.db = DummyDB()
- return
-
- # use detect_types so that timestamps return datetime objects
- kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
- kwargs.update(self.connection_options)
- self.db = sqlite3.connect(self.hist_file, **kwargs)
- self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
- primary key autoincrement, start timestamp,
- end timestamp, num_cmds integer, remark text)""")
- self.db.execute("""CREATE TABLE IF NOT EXISTS history
- (session integer, line integer, source text, source_raw text,
- PRIMARY KEY (session, line))""")
- # Output history is optional, but ensure the table's there so it can be
- # enabled later.
- self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
- (session integer, line integer, output text,
- PRIMARY KEY (session, line))""")
- self.db.commit()
+ connection_types = (DummyDB,)
+ if sqlite3 is not None:
+ connection_types = (DummyDB, sqlite3.Connection)
+ if not isinstance(new, connection_types):
+ msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
+ (self.__class__.__name__, new)
+ raise TraitError(msg)
+
+ def __init__(self, profile='default', hist_file=u'', **traits):
+ """Create a new history accessor.
+
+ Parameters
+ ----------
+ profile : str
+ The name of the profile from which to open history.
+ hist_file : str
+ Path to an SQLite history database stored by IPython. If specified,
+ hist_file overrides profile.
+ config : :class:`~traitlets.config.loader.Config`
+ Config object. hist_file can also be set through this.
+ """
+ # We need a pointer back to the shell for various tasks.
+ super(HistoryAccessor, self).__init__(**traits)
+ # defer setting hist_file from kwarg until after init,
+ # otherwise the default kwarg value would clobber any value
+ # set by config
+ if hist_file:
+ self.hist_file = hist_file
+
+ if self.hist_file == u'':
+ # No one has set the hist_file, yet.
+ self.hist_file = self._get_hist_file_name(profile)
+
+ if sqlite3 is None and self.enabled:
+ warn("IPython History requires SQLite, your history will not be saved")
+ self.enabled = False
+
+ self.init_db()
+
+ def _get_hist_file_name(self, profile='default'):
+ """Find the history file for the given profile name.
+
+ This is overridden by the HistoryManager subclass, to use the shell's
+ active profile.
+
+ Parameters
+ ----------
+ profile : str
+ The name of a profile which has a history file.
+ """
+ return os.path.join(locate_profile(profile), 'history.sqlite')
+
+ @catch_corrupt_db
+ def init_db(self):
+ """Connect to the database, and create tables if necessary."""
+ if not self.enabled:
+ self.db = DummyDB()
+ return
+
+ # use detect_types so that timestamps return datetime objects
+ kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
+ kwargs.update(self.connection_options)
+ self.db = sqlite3.connect(self.hist_file, **kwargs)
+ self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
+ primary key autoincrement, start timestamp,
+ end timestamp, num_cmds integer, remark text)""")
+ self.db.execute("""CREATE TABLE IF NOT EXISTS history
+ (session integer, line integer, source text, source_raw text,
+ PRIMARY KEY (session, line))""")
+ # Output history is optional, but ensure the table's there so it can be
+ # enabled later.
+ self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
+ (session integer, line integer, output text,
+ PRIMARY KEY (session, line))""")
+ self.db.commit()
# success! reset corrupt db count
self._corrupt_db_counter = 0
-
- def writeout_cache(self):
- """Overridden by HistoryManager to dump the cache before certain
- database lookups."""
- pass
-
- ## -------------------------------
- ## Methods for retrieving history:
- ## -------------------------------
- def _run_sql(self, sql, params, raw=True, output=False):
- """Prepares and runs an SQL query for the history database.
-
- Parameters
- ----------
- sql : str
- Any filtering expressions to go after SELECT ... FROM ...
- params : tuple
- Parameters passed to the SQL query (to replace "?")
- raw, output : bool
- See :meth:`get_range`
-
- Returns
- -------
- Tuples as :meth:`get_range`
- """
- toget = 'source_raw' if raw else 'source'
- sqlfrom = "history"
- if output:
- sqlfrom = "history LEFT JOIN output_history USING (session, line)"
- toget = "history.%s, output_history.output" % toget
- cur = self.db.execute("SELECT session, line, %s FROM %s " %\
- (toget, sqlfrom) + sql, params)
- if output: # Regroup into 3-tuples, and parse JSON
+
+ def writeout_cache(self):
+ """Overridden by HistoryManager to dump the cache before certain
+ database lookups."""
+ pass
+
+ ## -------------------------------
+ ## Methods for retrieving history:
+ ## -------------------------------
+ def _run_sql(self, sql, params, raw=True, output=False):
+ """Prepares and runs an SQL query for the history database.
+
+ Parameters
+ ----------
+ sql : str
+ Any filtering expressions to go after SELECT ... FROM ...
+ params : tuple
+ Parameters passed to the SQL query (to replace "?")
+ raw, output : bool
+ See :meth:`get_range`
+
+ Returns
+ -------
+ Tuples as :meth:`get_range`
+ """
+ toget = 'source_raw' if raw else 'source'
+ sqlfrom = "history"
+ if output:
+ sqlfrom = "history LEFT JOIN output_history USING (session, line)"
+ toget = "history.%s, output_history.output" % toget
+ cur = self.db.execute("SELECT session, line, %s FROM %s " %\
+ (toget, sqlfrom) + sql, params)
+ if output: # Regroup into 3-tuples, and parse JSON
return ((ses, lin, (py3compat.cast_unicode_py2(inp), py3compat.cast_unicode_py2(out)))
for ses, lin, inp, out in cur)
- return cur
-
- @needs_sqlite
- @catch_corrupt_db
- def get_session_info(self, session):
- """Get info about a session.
-
- Parameters
- ----------
-
- session : int
- Session number to retrieve.
-
- Returns
- -------
-
- session_id : int
- Session ID number
- start : datetime
- Timestamp for the start of the session.
- end : datetime
- Timestamp for the end of the session, or None if IPython crashed.
- num_cmds : int
- Number of commands run, or None if IPython crashed.
- remark : unicode
- A manually set description.
- """
- query = "SELECT * from sessions where session == ?"
- return self.db.execute(query, (session,)).fetchone()
-
- @catch_corrupt_db
- def get_last_session_id(self):
- """Get the last session ID currently in the database.
-
- Within IPython, this should be the same as the value stored in
- :attr:`HistoryManager.session_number`.
- """
- for record in self.get_tail(n=1, include_latest=True):
- return record[0]
-
- @catch_corrupt_db
- def get_tail(self, n=10, raw=True, output=False, include_latest=False):
- """Get the last n lines from the history database.
-
- Parameters
- ----------
- n : int
- The number of lines to get
- raw, output : bool
- See :meth:`get_range`
- include_latest : bool
- If False (default), n+1 lines are fetched, and the latest one
- is discarded. This is intended to be used where the function
- is called by a user command, which it should not return.
-
- Returns
- -------
- Tuples as :meth:`get_range`
- """
- self.writeout_cache()
- if not include_latest:
- n += 1
- cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
- (n,), raw=raw, output=output)
- if not include_latest:
- return reversed(list(cur)[1:])
- return reversed(list(cur))
-
- @catch_corrupt_db
- def search(self, pattern="*", raw=True, search_raw=True,
- output=False, n=None, unique=False):
- """Search the database using unix glob-style matching (wildcards
- * and ?).
-
- Parameters
- ----------
- pattern : str
- The wildcarded pattern to match when searching
- search_raw : bool
- If True, search the raw input, otherwise, the parsed input
- raw, output : bool
- See :meth:`get_range`
- n : None or int
- If an integer is given, it defines the limit of
- returned entries.
- unique : bool
- When it is true, return only unique entries.
-
- Returns
- -------
- Tuples as :meth:`get_range`
- """
- tosearch = "source_raw" if search_raw else "source"
- if output:
- tosearch = "history." + tosearch
- self.writeout_cache()
- sqlform = "WHERE %s GLOB ?" % tosearch
- params = (pattern,)
- if unique:
- sqlform += ' GROUP BY {0}'.format(tosearch)
- if n is not None:
- sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
- params += (n,)
- elif unique:
- sqlform += " ORDER BY session, line"
- cur = self._run_sql(sqlform, params, raw=raw, output=output)
- if n is not None:
- return reversed(list(cur))
- return cur
-
- @catch_corrupt_db
- def get_range(self, session, start=1, stop=None, raw=True,output=False):
- """Retrieve input by session.
-
- Parameters
- ----------
- session : int
- Session number to retrieve.
- start : int
- First line to retrieve.
- stop : int
- End of line range (excluded from output itself). If None, retrieve
- to the end of the session.
- raw : bool
- If True, return untranslated input
- output : bool
- If True, attempt to include output. This will be 'real' Python
- objects for the current session, or text reprs from previous
- sessions if db_log_output was enabled at the time. Where no output
- is found, None is used.
-
- Returns
- -------
- entries
- An iterator over the desired lines. Each line is a 3-tuple, either
- (session, line, input) if output is False, or
- (session, line, (input, output)) if output is True.
- """
- if stop:
- lineclause = "line >= ? AND line < ?"
- params = (session, start, stop)
- else:
- lineclause = "line>=?"
- params = (session, start)
-
- return self._run_sql("WHERE session==? AND %s" % lineclause,
- params, raw=raw, output=output)
-
- def get_range_by_str(self, rangestr, raw=True, output=False):
- """Get lines of history from a string of ranges, as used by magic
- commands %hist, %save, %macro, etc.
-
- Parameters
- ----------
- rangestr : str
- A string specifying ranges, e.g. "5 ~2/1-4". See
- :func:`magic_history` for full details.
- raw, output : bool
- As :meth:`get_range`
-
- Returns
- -------
- Tuples as :meth:`get_range`
- """
- for sess, s, e in extract_hist_ranges(rangestr):
- for line in self.get_range(sess, s, e, raw=raw, output=output):
- yield line
-
-
-class HistoryManager(HistoryAccessor):
- """A class to organize all history-related functionality in one place.
- """
- # Public interface
-
- # An instance of the IPython shell we are attached to
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
- allow_none=True)
- # Lists to hold processed and raw history. These start with a blank entry
- # so that we can index them starting from 1
- input_hist_parsed = List([""])
- input_hist_raw = List([""])
- # A list of directories visited during session
- dir_hist = List()
+ return cur
+
+ @needs_sqlite
+ @catch_corrupt_db
+ def get_session_info(self, session):
+ """Get info about a session.
+
+ Parameters
+ ----------
+
+ session : int
+ Session number to retrieve.
+
+ Returns
+ -------
+
+ session_id : int
+ Session ID number
+ start : datetime
+ Timestamp for the start of the session.
+ end : datetime
+ Timestamp for the end of the session, or None if IPython crashed.
+ num_cmds : int
+ Number of commands run, or None if IPython crashed.
+ remark : unicode
+ A manually set description.
+ """
+ query = "SELECT * from sessions where session == ?"
+ return self.db.execute(query, (session,)).fetchone()
+
+ @catch_corrupt_db
+ def get_last_session_id(self):
+ """Get the last session ID currently in the database.
+
+ Within IPython, this should be the same as the value stored in
+ :attr:`HistoryManager.session_number`.
+ """
+ for record in self.get_tail(n=1, include_latest=True):
+ return record[0]
+
+ @catch_corrupt_db
+ def get_tail(self, n=10, raw=True, output=False, include_latest=False):
+ """Get the last n lines from the history database.
+
+ Parameters
+ ----------
+ n : int
+ The number of lines to get
+ raw, output : bool
+ See :meth:`get_range`
+ include_latest : bool
+ If False (default), n+1 lines are fetched, and the latest one
+ is discarded. This is intended to be used where the function
+ is called by a user command, which it should not return.
+
+ Returns
+ -------
+ Tuples as :meth:`get_range`
+ """
+ self.writeout_cache()
+ if not include_latest:
+ n += 1
+ cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
+ (n,), raw=raw, output=output)
+ if not include_latest:
+ return reversed(list(cur)[1:])
+ return reversed(list(cur))
+
+ @catch_corrupt_db
+ def search(self, pattern="*", raw=True, search_raw=True,
+ output=False, n=None, unique=False):
+ """Search the database using unix glob-style matching (wildcards
+ * and ?).
+
+ Parameters
+ ----------
+ pattern : str
+ The wildcarded pattern to match when searching
+ search_raw : bool
+ If True, search the raw input, otherwise, the parsed input
+ raw, output : bool
+ See :meth:`get_range`
+ n : None or int
+ If an integer is given, it defines the limit of
+ returned entries.
+ unique : bool
+ When it is true, return only unique entries.
+
+ Returns
+ -------
+ Tuples as :meth:`get_range`
+ """
+ tosearch = "source_raw" if search_raw else "source"
+ if output:
+ tosearch = "history." + tosearch
+ self.writeout_cache()
+ sqlform = "WHERE %s GLOB ?" % tosearch
+ params = (pattern,)
+ if unique:
+ sqlform += ' GROUP BY {0}'.format(tosearch)
+ if n is not None:
+ sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
+ params += (n,)
+ elif unique:
+ sqlform += " ORDER BY session, line"
+ cur = self._run_sql(sqlform, params, raw=raw, output=output)
+ if n is not None:
+ return reversed(list(cur))
+ return cur
+
+ @catch_corrupt_db
+ def get_range(self, session, start=1, stop=None, raw=True,output=False):
+ """Retrieve input by session.
+
+ Parameters
+ ----------
+ session : int
+ Session number to retrieve.
+ start : int
+ First line to retrieve.
+ stop : int
+ End of line range (excluded from output itself). If None, retrieve
+ to the end of the session.
+ raw : bool
+ If True, return untranslated input
+ output : bool
+ If True, attempt to include output. This will be 'real' Python
+ objects for the current session, or text reprs from previous
+ sessions if db_log_output was enabled at the time. Where no output
+ is found, None is used.
+
+ Returns
+ -------
+ entries
+ An iterator over the desired lines. Each line is a 3-tuple, either
+ (session, line, input) if output is False, or
+ (session, line, (input, output)) if output is True.
+ """
+ if stop:
+ lineclause = "line >= ? AND line < ?"
+ params = (session, start, stop)
+ else:
+ lineclause = "line>=?"
+ params = (session, start)
+
+ return self._run_sql("WHERE session==? AND %s" % lineclause,
+ params, raw=raw, output=output)
+
+ def get_range_by_str(self, rangestr, raw=True, output=False):
+ """Get lines of history from a string of ranges, as used by magic
+ commands %hist, %save, %macro, etc.
+
+ Parameters
+ ----------
+ rangestr : str
+ A string specifying ranges, e.g. "5 ~2/1-4". See
+ :func:`magic_history` for full details.
+ raw, output : bool
+ As :meth:`get_range`
+
+ Returns
+ -------
+ Tuples as :meth:`get_range`
+ """
+ for sess, s, e in extract_hist_ranges(rangestr):
+ for line in self.get_range(sess, s, e, raw=raw, output=output):
+ yield line
+
+
+class HistoryManager(HistoryAccessor):
+ """A class to organize all history-related functionality in one place.
+ """
+ # Public interface
+
+ # An instance of the IPython shell we are attached to
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
+ allow_none=True)
+ # Lists to hold processed and raw history. These start with a blank entry
+ # so that we can index them starting from 1
+ input_hist_parsed = List([""])
+ input_hist_raw = List([""])
+ # A list of directories visited during session
+ dir_hist = List()
@default('dir_hist')
- def _dir_hist_default(self):
- try:
- return [py3compat.getcwd()]
- except OSError:
- return []
-
- # A dict of output history, keyed with ints from the shell's
- # execution count.
- output_hist = Dict()
- # The text/plain repr of outputs.
- output_hist_reprs = Dict()
-
- # The number of the current session in the history database
- session_number = Integer()
-
+ def _dir_hist_default(self):
+ try:
+ return [py3compat.getcwd()]
+ except OSError:
+ return []
+
+ # A dict of output history, keyed with ints from the shell's
+ # execution count.
+ output_hist = Dict()
+ # The text/plain repr of outputs.
+ output_hist_reprs = Dict()
+
+ # The number of the current session in the history database
+ session_number = Integer()
+
db_log_output = Bool(False,
- help="Should the history database include output? (default: no)"
+ help="Should the history database include output? (default: no)"
).tag(config=True)
db_cache_size = Integer(0,
- help="Write to database every x commands (higher values save disk access & power).\n"
- "Values of 1 or less effectively disable caching."
+ help="Write to database every x commands (higher values save disk access & power).\n"
+ "Values of 1 or less effectively disable caching."
).tag(config=True)
- # The input and output caches
- db_input_cache = List()
- db_output_cache = List()
-
- # History saving in separate thread
- save_thread = Instance('IPython.core.history.HistorySavingThread',
- allow_none=True)
- try: # Event is a function returning an instance of _Event...
- save_flag = Instance(threading._Event, allow_none=True)
- except AttributeError: # ...until Python 3.3, when it's a class.
- save_flag = Instance(threading.Event, allow_none=True)
-
- # Private interface
- # Variables used to store the three last inputs from the user. On each new
- # history update, we populate the user's namespace with these, shifted as
- # necessary.
- _i00 = Unicode(u'')
- _i = Unicode(u'')
- _ii = Unicode(u'')
- _iii = Unicode(u'')
-
- # A regex matching all forms of the exit command, so that we don't store
- # them in the history (it's annoying to rewind the first entry and land on
- # an exit call).
- _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
-
- def __init__(self, shell=None, config=None, **traits):
- """Create a new history manager associated with a shell instance.
- """
- # We need a pointer back to the shell for various tasks.
- super(HistoryManager, self).__init__(shell=shell, config=config,
- **traits)
- self.save_flag = threading.Event()
- self.db_input_cache_lock = threading.Lock()
- self.db_output_cache_lock = threading.Lock()
-
- try:
- self.new_session()
- except OperationalError:
- self.log.error("Failed to create history session in %s. History will not be saved.",
- self.hist_file, exc_info=True)
- self.hist_file = ':memory:'
-
- if self.enabled and self.hist_file != ':memory:':
- self.save_thread = HistorySavingThread(self)
- self.save_thread.start()
-
- def _get_hist_file_name(self, profile=None):
- """Get default history file name based on the Shell's profile.
-
- The profile parameter is ignored, but must exist for compatibility with
- the parent class."""
- profile_dir = self.shell.profile_dir.location
- return os.path.join(profile_dir, 'history.sqlite')
-
- @needs_sqlite
- def new_session(self, conn=None):
- """Get a new session number."""
- if conn is None:
- conn = self.db
-
- with conn:
- cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
- NULL, "") """, (datetime.datetime.now(),))
- self.session_number = cur.lastrowid
-
- def end_session(self):
- """Close the database session, filling in the end time and line count."""
- self.writeout_cache()
- with self.db:
- self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
- session==?""", (datetime.datetime.now(),
- len(self.input_hist_parsed)-1, self.session_number))
- self.session_number = 0
-
- def name_session(self, name):
- """Give the current session a name in the history database."""
- with self.db:
- self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
- (name, self.session_number))
-
- def reset(self, new_session=True):
- """Clear the session history, releasing all object references, and
- optionally open a new session."""
- self.output_hist.clear()
- # The directory history can't be completely empty
- self.dir_hist[:] = [py3compat.getcwd()]
-
- if new_session:
- if self.session_number:
- self.end_session()
- self.input_hist_parsed[:] = [""]
- self.input_hist_raw[:] = [""]
- self.new_session()
-
- # ------------------------------
- # Methods for retrieving history
- # ------------------------------
- def get_session_info(self, session=0):
- """Get info about a session.
-
- Parameters
- ----------
-
- session : int
- Session number to retrieve. The current session is 0, and negative
- numbers count back from current session, so -1 is the previous session.
-
- Returns
- -------
-
- session_id : int
- Session ID number
- start : datetime
- Timestamp for the start of the session.
- end : datetime
- Timestamp for the end of the session, or None if IPython crashed.
- num_cmds : int
- Number of commands run, or None if IPython crashed.
- remark : unicode
- A manually set description.
- """
- if session <= 0:
- session += self.session_number
-
- return super(HistoryManager, self).get_session_info(session=session)
-
- def _get_range_session(self, start=1, stop=None, raw=True, output=False):
- """Get input and output history from the current session. Called by
- get_range, and takes similar parameters."""
- input_hist = self.input_hist_raw if raw else self.input_hist_parsed
-
- n = len(input_hist)
- if start < 0:
- start += n
- if not stop or (stop > n):
- stop = n
- elif stop < 0:
- stop += n
-
- for i in range(start, stop):
- if output:
- line = (input_hist[i], self.output_hist_reprs.get(i))
- else:
- line = input_hist[i]
- yield (0, i, line)
-
- def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
- """Retrieve input by session.
-
- Parameters
- ----------
- session : int
- Session number to retrieve. The current session is 0, and negative
- numbers count back from current session, so -1 is previous session.
- start : int
- First line to retrieve.
- stop : int
- End of line range (excluded from output itself). If None, retrieve
- to the end of the session.
- raw : bool
- If True, return untranslated input
- output : bool
- If True, attempt to include output. This will be 'real' Python
- objects for the current session, or text reprs from previous
- sessions if db_log_output was enabled at the time. Where no output
- is found, None is used.
-
- Returns
- -------
- entries
- An iterator over the desired lines. Each line is a 3-tuple, either
- (session, line, input) if output is False, or
- (session, line, (input, output)) if output is True.
- """
- if session <= 0:
- session += self.session_number
- if session==self.session_number: # Current session
- return self._get_range_session(start, stop, raw, output)
- return super(HistoryManager, self).get_range(session, start, stop, raw,
- output)
-
- ## ----------------------------
- ## Methods for storing history:
- ## ----------------------------
- def store_inputs(self, line_num, source, source_raw=None):
- """Store source and raw input in history and create input cache
- variables ``_i*``.
-
- Parameters
- ----------
- line_num : int
- The prompt number of this input.
-
- source : str
- Python input.
-
- source_raw : str, optional
- If given, this is the raw input without any IPython transformations
- applied to it. If not given, ``source`` is used.
- """
- if source_raw is None:
- source_raw = source
- source = source.rstrip('\n')
- source_raw = source_raw.rstrip('\n')
-
- # do not store exit/quit commands
- if self._exit_re.match(source_raw.strip()):
- return
-
- self.input_hist_parsed.append(source)
- self.input_hist_raw.append(source_raw)
-
- with self.db_input_cache_lock:
- self.db_input_cache.append((line_num, source, source_raw))
- # Trigger to flush cache and write to DB.
- if len(self.db_input_cache) >= self.db_cache_size:
- self.save_flag.set()
-
- # update the auto _i variables
- self._iii = self._ii
- self._ii = self._i
- self._i = self._i00
- self._i00 = source_raw
-
- # hackish access to user namespace to create _i1,_i2... dynamically
- new_i = '_i%s' % line_num
- to_main = {'_i': self._i,
- '_ii': self._ii,
- '_iii': self._iii,
- new_i : self._i00 }
-
- if self.shell is not None:
- self.shell.push(to_main, interactive=False)
-
- def store_output(self, line_num):
- """If database output logging is enabled, this saves all the
- outputs from the indicated prompt number to the database. It's
- called by run_cell after code has been executed.
-
- Parameters
- ----------
- line_num : int
- The line number from which to save outputs
- """
- if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
- return
- output = self.output_hist_reprs[line_num]
-
- with self.db_output_cache_lock:
- self.db_output_cache.append((line_num, output))
- if self.db_cache_size <= 1:
- self.save_flag.set()
-
- def _writeout_input_cache(self, conn):
- with conn:
- for line in self.db_input_cache:
- conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
- (self.session_number,)+line)
-
- def _writeout_output_cache(self, conn):
- with conn:
- for line in self.db_output_cache:
- conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
- (self.session_number,)+line)
-
- @needs_sqlite
- def writeout_cache(self, conn=None):
- """Write any entries in the cache to the database."""
- if conn is None:
- conn = self.db
-
- with self.db_input_cache_lock:
- try:
- self._writeout_input_cache(conn)
- except sqlite3.IntegrityError:
- self.new_session(conn)
- print("ERROR! Session/line number was not unique in",
- "database. History logging moved to new session",
- self.session_number)
- try:
- # Try writing to the new session. If this fails, don't
- # recurse
- self._writeout_input_cache(conn)
- except sqlite3.IntegrityError:
- pass
- finally:
- self.db_input_cache = []
-
- with self.db_output_cache_lock:
- try:
- self._writeout_output_cache(conn)
- except sqlite3.IntegrityError:
- print("!! Session/line number for output was not unique",
- "in database. Output will not be stored.")
- finally:
- self.db_output_cache = []
-
-
-class HistorySavingThread(threading.Thread):
- """This thread takes care of writing history to the database, so that
- the UI isn't held up while that happens.
-
- It waits for the HistoryManager's save_flag to be set, then writes out
- the history cache. The main thread is responsible for setting the flag when
- the cache size reaches a defined threshold."""
- daemon = True
- stop_now = False
- enabled = True
- def __init__(self, history_manager):
- super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread")
- self.history_manager = history_manager
- self.enabled = history_manager.enabled
- atexit.register(self.stop)
-
- @needs_sqlite
- def run(self):
- # We need a separate db connection per thread:
- try:
- self.db = sqlite3.connect(self.history_manager.hist_file,
- **self.history_manager.connection_options
- )
- while True:
- self.history_manager.save_flag.wait()
- if self.stop_now:
- self.db.close()
- return
- self.history_manager.save_flag.clear()
- self.history_manager.writeout_cache(self.db)
- except Exception as e:
- print(("The history saving thread hit an unexpected error (%s)."
- "History will not be written to the database.") % repr(e))
-
- def stop(self):
- """This can be called from the main thread to safely stop this thread.
-
- Note that it does not attempt to write out remaining history before
- exiting. That should be done by calling the HistoryManager's
- end_session method."""
- self.stop_now = True
- self.history_manager.save_flag.set()
- self.join()
-
-
-# To match, e.g. ~5/8-~2/3
-range_re = re.compile(r"""
-((?P<startsess>~?\d+)/)?
-(?P<start>\d+)?
-((?P<sep>[\-:])
- ((?P<endsess>~?\d+)/)?
- (?P<end>\d+))?
-$""", re.VERBOSE)
-
-
-def extract_hist_ranges(ranges_str):
- """Turn a string of history ranges into 3-tuples of (session, start, stop).
-
- Examples
- --------
- >>> list(extract_hist_ranges("~8/5-~7/4 2"))
- [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]
- """
- for range_str in ranges_str.split():
- rmatch = range_re.match(range_str)
- if not rmatch:
- continue
- start = rmatch.group("start")
- if start:
- start = int(start)
- end = rmatch.group("end")
- # If no end specified, get (a, a + 1)
- end = int(end) if end else start + 1
- else: # start not specified
- if not rmatch.group('startsess'): # no startsess
- continue
- start = 1
- end = None # provide the entire session hist
-
- if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
- end += 1
- startsess = rmatch.group("startsess") or "0"
- endsess = rmatch.group("endsess") or startsess
- startsess = int(startsess.replace("~","-"))
- endsess = int(endsess.replace("~","-"))
- assert endsess >= startsess, "start session must be earlier than end session"
-
- if endsess == startsess:
- yield (startsess, start, end)
- continue
- # Multiple sessions in one range:
- yield (startsess, start, None)
- for sess in range(startsess+1, endsess):
- yield (sess, 1, None)
- yield (endsess, 1, end)
-
-
-def _format_lineno(session, line):
- """Helper function to format line numbers properly."""
- if session == 0:
- return str(line)
- return "%s#%s" % (session, line)
+ # The input and output caches
+ db_input_cache = List()
+ db_output_cache = List()
+
+ # History saving in separate thread
+ save_thread = Instance('IPython.core.history.HistorySavingThread',
+ allow_none=True)
+ try: # Event is a function returning an instance of _Event...
+ save_flag = Instance(threading._Event, allow_none=True)
+ except AttributeError: # ...until Python 3.3, when it's a class.
+ save_flag = Instance(threading.Event, allow_none=True)
+
+ # Private interface
+ # Variables used to store the three last inputs from the user. On each new
+ # history update, we populate the user's namespace with these, shifted as
+ # necessary.
+ _i00 = Unicode(u'')
+ _i = Unicode(u'')
+ _ii = Unicode(u'')
+ _iii = Unicode(u'')
+
+ # A regex matching all forms of the exit command, so that we don't store
+ # them in the history (it's annoying to rewind the first entry and land on
+ # an exit call).
+ _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
+
+ def __init__(self, shell=None, config=None, **traits):
+ """Create a new history manager associated with a shell instance.
+ """
+ # We need a pointer back to the shell for various tasks.
+ super(HistoryManager, self).__init__(shell=shell, config=config,
+ **traits)
+ self.save_flag = threading.Event()
+ self.db_input_cache_lock = threading.Lock()
+ self.db_output_cache_lock = threading.Lock()
+
+ try:
+ self.new_session()
+ except OperationalError:
+ self.log.error("Failed to create history session in %s. History will not be saved.",
+ self.hist_file, exc_info=True)
+ self.hist_file = ':memory:'
+
+ if self.enabled and self.hist_file != ':memory:':
+ self.save_thread = HistorySavingThread(self)
+ self.save_thread.start()
+
+ def _get_hist_file_name(self, profile=None):
+ """Get default history file name based on the Shell's profile.
+
+ The profile parameter is ignored, but must exist for compatibility with
+ the parent class."""
+ profile_dir = self.shell.profile_dir.location
+ return os.path.join(profile_dir, 'history.sqlite')
+
+ @needs_sqlite
+ def new_session(self, conn=None):
+ """Get a new session number."""
+ if conn is None:
+ conn = self.db
+
+ with conn:
+ cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
+ NULL, "") """, (datetime.datetime.now(),))
+ self.session_number = cur.lastrowid
+
+ def end_session(self):
+ """Close the database session, filling in the end time and line count."""
+ self.writeout_cache()
+ with self.db:
+ self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
+ session==?""", (datetime.datetime.now(),
+ len(self.input_hist_parsed)-1, self.session_number))
+ self.session_number = 0
+
+ def name_session(self, name):
+ """Give the current session a name in the history database."""
+ with self.db:
+ self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
+ (name, self.session_number))
+
+ def reset(self, new_session=True):
+ """Clear the session history, releasing all object references, and
+ optionally open a new session."""
+ self.output_hist.clear()
+ # The directory history can't be completely empty
+ self.dir_hist[:] = [py3compat.getcwd()]
+
+ if new_session:
+ if self.session_number:
+ self.end_session()
+ self.input_hist_parsed[:] = [""]
+ self.input_hist_raw[:] = [""]
+ self.new_session()
+
+ # ------------------------------
+ # Methods for retrieving history
+ # ------------------------------
+ def get_session_info(self, session=0):
+ """Get info about a session.
+
+ Parameters
+ ----------
+
+ session : int
+ Session number to retrieve. The current session is 0, and negative
+ numbers count back from current session, so -1 is the previous session.
+
+ Returns
+ -------
+
+ session_id : int
+ Session ID number
+ start : datetime
+ Timestamp for the start of the session.
+ end : datetime
+ Timestamp for the end of the session, or None if IPython crashed.
+ num_cmds : int
+ Number of commands run, or None if IPython crashed.
+ remark : unicode
+ A manually set description.
+ """
+ if session <= 0:
+ session += self.session_number
+
+ return super(HistoryManager, self).get_session_info(session=session)
+
+ def _get_range_session(self, start=1, stop=None, raw=True, output=False):
+ """Get input and output history from the current session. Called by
+ get_range, and takes similar parameters."""
+ input_hist = self.input_hist_raw if raw else self.input_hist_parsed
+
+ n = len(input_hist)
+ if start < 0:
+ start += n
+ if not stop or (stop > n):
+ stop = n
+ elif stop < 0:
+ stop += n
+
+ for i in range(start, stop):
+ if output:
+ line = (input_hist[i], self.output_hist_reprs.get(i))
+ else:
+ line = input_hist[i]
+ yield (0, i, line)
+
+ def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
+ """Retrieve input by session.
+
+ Parameters
+ ----------
+ session : int
+ Session number to retrieve. The current session is 0, and negative
+ numbers count back from current session, so -1 is previous session.
+ start : int
+ First line to retrieve.
+ stop : int
+ End of line range (excluded from output itself). If None, retrieve
+ to the end of the session.
+ raw : bool
+ If True, return untranslated input
+ output : bool
+ If True, attempt to include output. This will be 'real' Python
+ objects for the current session, or text reprs from previous
+ sessions if db_log_output was enabled at the time. Where no output
+ is found, None is used.
+
+ Returns
+ -------
+ entries
+ An iterator over the desired lines. Each line is a 3-tuple, either
+ (session, line, input) if output is False, or
+ (session, line, (input, output)) if output is True.
+ """
+ if session <= 0:
+ session += self.session_number
+ if session==self.session_number: # Current session
+ return self._get_range_session(start, stop, raw, output)
+ return super(HistoryManager, self).get_range(session, start, stop, raw,
+ output)
+
+ ## ----------------------------
+ ## Methods for storing history:
+ ## ----------------------------
+ def store_inputs(self, line_num, source, source_raw=None):
+ """Store source and raw input in history and create input cache
+ variables ``_i*``.
+
+ Parameters
+ ----------
+ line_num : int
+ The prompt number of this input.
+
+ source : str
+ Python input.
+
+ source_raw : str, optional
+ If given, this is the raw input without any IPython transformations
+ applied to it. If not given, ``source`` is used.
+ """
+ if source_raw is None:
+ source_raw = source
+ source = source.rstrip('\n')
+ source_raw = source_raw.rstrip('\n')
+
+ # do not store exit/quit commands
+ if self._exit_re.match(source_raw.strip()):
+ return
+
+ self.input_hist_parsed.append(source)
+ self.input_hist_raw.append(source_raw)
+
+ with self.db_input_cache_lock:
+ self.db_input_cache.append((line_num, source, source_raw))
+ # Trigger to flush cache and write to DB.
+ if len(self.db_input_cache) >= self.db_cache_size:
+ self.save_flag.set()
+
+ # update the auto _i variables
+ self._iii = self._ii
+ self._ii = self._i
+ self._i = self._i00
+ self._i00 = source_raw
+
+ # hackish access to user namespace to create _i1,_i2... dynamically
+ new_i = '_i%s' % line_num
+ to_main = {'_i': self._i,
+ '_ii': self._ii,
+ '_iii': self._iii,
+ new_i : self._i00 }
+
+ if self.shell is not None:
+ self.shell.push(to_main, interactive=False)
+
+ def store_output(self, line_num):
+ """If database output logging is enabled, this saves all the
+ outputs from the indicated prompt number to the database. It's
+ called by run_cell after code has been executed.
+
+ Parameters
+ ----------
+ line_num : int
+ The line number from which to save outputs
+ """
+ if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
+ return
+ output = self.output_hist_reprs[line_num]
+
+ with self.db_output_cache_lock:
+ self.db_output_cache.append((line_num, output))
+ if self.db_cache_size <= 1:
+ self.save_flag.set()
+
+ def _writeout_input_cache(self, conn):
+ with conn:
+ for line in self.db_input_cache:
+ conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
+ (self.session_number,)+line)
+
+ def _writeout_output_cache(self, conn):
+ with conn:
+ for line in self.db_output_cache:
+ conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
+ (self.session_number,)+line)
+
+ @needs_sqlite
+ def writeout_cache(self, conn=None):
+ """Write any entries in the cache to the database."""
+ if conn is None:
+ conn = self.db
+
+ with self.db_input_cache_lock:
+ try:
+ self._writeout_input_cache(conn)
+ except sqlite3.IntegrityError:
+ self.new_session(conn)
+ print("ERROR! Session/line number was not unique in",
+ "database. History logging moved to new session",
+ self.session_number)
+ try:
+ # Try writing to the new session. If this fails, don't
+ # recurse
+ self._writeout_input_cache(conn)
+ except sqlite3.IntegrityError:
+ pass
+ finally:
+ self.db_input_cache = []
+
+ with self.db_output_cache_lock:
+ try:
+ self._writeout_output_cache(conn)
+ except sqlite3.IntegrityError:
+ print("!! Session/line number for output was not unique",
+ "in database. Output will not be stored.")
+ finally:
+ self.db_output_cache = []
+
+
+class HistorySavingThread(threading.Thread):
+ """This thread takes care of writing history to the database, so that
+ the UI isn't held up while that happens.
+
+ It waits for the HistoryManager's save_flag to be set, then writes out
+ the history cache. The main thread is responsible for setting the flag when
+ the cache size reaches a defined threshold."""
+ daemon = True
+ stop_now = False
+ enabled = True
+ def __init__(self, history_manager):
+ super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread")
+ self.history_manager = history_manager
+ self.enabled = history_manager.enabled
+ atexit.register(self.stop)
+
+ @needs_sqlite
+ def run(self):
+ # We need a separate db connection per thread:
+ try:
+ self.db = sqlite3.connect(self.history_manager.hist_file,
+ **self.history_manager.connection_options
+ )
+ while True:
+ self.history_manager.save_flag.wait()
+ if self.stop_now:
+ self.db.close()
+ return
+ self.history_manager.save_flag.clear()
+ self.history_manager.writeout_cache(self.db)
+ except Exception as e:
+ print(("The history saving thread hit an unexpected error (%s)."
+ "History will not be written to the database.") % repr(e))
+
+ def stop(self):
+ """This can be called from the main thread to safely stop this thread.
+
+ Note that it does not attempt to write out remaining history before
+ exiting. That should be done by calling the HistoryManager's
+ end_session method."""
+ self.stop_now = True
+ self.history_manager.save_flag.set()
+ self.join()
+
+
+# To match, e.g. ~5/8-~2/3
+range_re = re.compile(r"""
+((?P<startsess>~?\d+)/)?
+(?P<start>\d+)?
+((?P<sep>[\-:])
+ ((?P<endsess>~?\d+)/)?
+ (?P<end>\d+))?
+$""", re.VERBOSE)
+
+
+def extract_hist_ranges(ranges_str):
+ """Turn a string of history ranges into 3-tuples of (session, start, stop).
+
+ Examples
+ --------
+ >>> list(extract_hist_ranges("~8/5-~7/4 2"))
+ [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]
+ """
+ for range_str in ranges_str.split():
+ rmatch = range_re.match(range_str)
+ if not rmatch:
+ continue
+ start = rmatch.group("start")
+ if start:
+ start = int(start)
+ end = rmatch.group("end")
+ # If no end specified, get (a, a + 1)
+ end = int(end) if end else start + 1
+ else: # start not specified
+ if not rmatch.group('startsess'): # no startsess
+ continue
+ start = 1
+ end = None # provide the entire session hist
+
+ if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
+ end += 1
+ startsess = rmatch.group("startsess") or "0"
+ endsess = rmatch.group("endsess") or startsess
+ startsess = int(startsess.replace("~","-"))
+ endsess = int(endsess.replace("~","-"))
+ assert endsess >= startsess, "start session must be earlier than end session"
+
+ if endsess == startsess:
+ yield (startsess, start, end)
+ continue
+ # Multiple sessions in one range:
+ yield (startsess, start, None)
+ for sess in range(startsess+1, endsess):
+ yield (sess, 1, None)
+ yield (endsess, 1, end)
+
+
+def _format_lineno(session, line):
+ """Helper function to format line numbers properly."""
+ if session == 0:
+ return str(line)
+ return "%s#%s" % (session, line)
diff --git a/contrib/python/ipython/py2/IPython/core/historyapp.py b/contrib/python/ipython/py2/IPython/core/historyapp.py
index b693cbc0d8..d51426d2ca 100644
--- a/contrib/python/ipython/py2/IPython/core/historyapp.py
+++ b/contrib/python/ipython/py2/IPython/core/historyapp.py
@@ -1,162 +1,162 @@
-# encoding: utf-8
-"""
-An application for managing IPython history.
-
-To be invoked as the `ipython history` subcommand.
-"""
-from __future__ import print_function
-
-import os
-import sqlite3
-
-from traitlets.config.application import Application
-from IPython.core.application import BaseIPythonApplication
-from traitlets import Bool, Int, Dict
-from IPython.utils.io import ask_yes_no
-
-trim_hist_help = """Trim the IPython history database to the last 1000 entries.
-
-This actually copies the last 1000 entries to a new database, and then replaces
-the old file with the new. Use the `--keep=` argument to specify a number
-other than 1000.
-"""
-
-clear_hist_help = """Clear the IPython history database, deleting all entries.
-
-Because this is a destructive operation, IPython will prompt the user if they
-really want to do this. Passing a `-f` flag will force clearing without a
-prompt.
-
-This is an handy alias to `ipython history trim --keep=0`
-"""
-
-
-class HistoryTrim(BaseIPythonApplication):
- description = trim_hist_help
-
+# encoding: utf-8
+"""
+An application for managing IPython history.
+
+To be invoked as the `ipython history` subcommand.
+"""
+from __future__ import print_function
+
+import os
+import sqlite3
+
+from traitlets.config.application import Application
+from IPython.core.application import BaseIPythonApplication
+from traitlets import Bool, Int, Dict
+from IPython.utils.io import ask_yes_no
+
+trim_hist_help = """Trim the IPython history database to the last 1000 entries.
+
+This actually copies the last 1000 entries to a new database, and then replaces
+the old file with the new. Use the `--keep=` argument to specify a number
+other than 1000.
+"""
+
+clear_hist_help = """Clear the IPython history database, deleting all entries.
+
+Because this is a destructive operation, IPython will prompt the user if they
+really want to do this. Passing a `-f` flag will force clearing without a
+prompt.
+
+This is an handy alias to `ipython history trim --keep=0`
+"""
+
+
+class HistoryTrim(BaseIPythonApplication):
+ description = trim_hist_help
+
backup = Bool(False,
help="Keep the old history file as history.sqlite.<N>"
).tag(config=True)
-
+
keep = Int(1000,
help="Number of recent lines to keep in the database."
).tag(config=True)
-
- flags = Dict(dict(
- backup = ({'HistoryTrim' : {'backup' : True}},
+
+ flags = Dict(dict(
+ backup = ({'HistoryTrim' : {'backup' : True}},
backup.help
- )
- ))
-
- aliases=Dict(dict(
- keep = 'HistoryTrim.keep'
- ))
-
- def start(self):
- profile_dir = self.profile_dir.location
- hist_file = os.path.join(profile_dir, 'history.sqlite')
- con = sqlite3.connect(hist_file)
-
- # Grab the recent history from the current database.
- inputs = list(con.execute('SELECT session, line, source, source_raw FROM '
- 'history ORDER BY session DESC, line DESC LIMIT ?', (self.keep+1,)))
- if len(inputs) <= self.keep:
- print("There are already at most %d entries in the history database." % self.keep)
- print("Not doing anything. Use --keep= argument to keep fewer entries")
- return
-
- print("Trimming history to the most recent %d entries." % self.keep)
-
- inputs.pop() # Remove the extra element we got to check the length.
- inputs.reverse()
- if inputs:
- first_session = inputs[0][0]
- outputs = list(con.execute('SELECT session, line, output FROM '
- 'output_history WHERE session >= ?', (first_session,)))
- sessions = list(con.execute('SELECT session, start, end, num_cmds, remark FROM '
- 'sessions WHERE session >= ?', (first_session,)))
- con.close()
-
- # Create the new history database.
- new_hist_file = os.path.join(profile_dir, 'history.sqlite.new')
- i = 0
- while os.path.exists(new_hist_file):
- # Make sure we don't interfere with an existing file.
- i += 1
- new_hist_file = os.path.join(profile_dir, 'history.sqlite.new'+str(i))
- new_db = sqlite3.connect(new_hist_file)
- new_db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
- primary key autoincrement, start timestamp,
- end timestamp, num_cmds integer, remark text)""")
- new_db.execute("""CREATE TABLE IF NOT EXISTS history
- (session integer, line integer, source text, source_raw text,
- PRIMARY KEY (session, line))""")
- new_db.execute("""CREATE TABLE IF NOT EXISTS output_history
- (session integer, line integer, output text,
- PRIMARY KEY (session, line))""")
- new_db.commit()
-
-
- if inputs:
- with new_db:
- # Add the recent history into the new database.
- new_db.executemany('insert into sessions values (?,?,?,?,?)', sessions)
- new_db.executemany('insert into history values (?,?,?,?)', inputs)
- new_db.executemany('insert into output_history values (?,?,?)', outputs)
- new_db.close()
-
- if self.backup:
- i = 1
- backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
- while os.path.exists(backup_hist_file):
- i += 1
- backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
- os.rename(hist_file, backup_hist_file)
- print("Backed up longer history file to", backup_hist_file)
- else:
- os.remove(hist_file)
-
- os.rename(new_hist_file, hist_file)
-
-class HistoryClear(HistoryTrim):
- description = clear_hist_help
+ )
+ ))
+
+ aliases=Dict(dict(
+ keep = 'HistoryTrim.keep'
+ ))
+
+ def start(self):
+ profile_dir = self.profile_dir.location
+ hist_file = os.path.join(profile_dir, 'history.sqlite')
+ con = sqlite3.connect(hist_file)
+
+ # Grab the recent history from the current database.
+ inputs = list(con.execute('SELECT session, line, source, source_raw FROM '
+ 'history ORDER BY session DESC, line DESC LIMIT ?', (self.keep+1,)))
+ if len(inputs) <= self.keep:
+ print("There are already at most %d entries in the history database." % self.keep)
+ print("Not doing anything. Use --keep= argument to keep fewer entries")
+ return
+
+ print("Trimming history to the most recent %d entries." % self.keep)
+
+ inputs.pop() # Remove the extra element we got to check the length.
+ inputs.reverse()
+ if inputs:
+ first_session = inputs[0][0]
+ outputs = list(con.execute('SELECT session, line, output FROM '
+ 'output_history WHERE session >= ?', (first_session,)))
+ sessions = list(con.execute('SELECT session, start, end, num_cmds, remark FROM '
+ 'sessions WHERE session >= ?', (first_session,)))
+ con.close()
+
+ # Create the new history database.
+ new_hist_file = os.path.join(profile_dir, 'history.sqlite.new')
+ i = 0
+ while os.path.exists(new_hist_file):
+ # Make sure we don't interfere with an existing file.
+ i += 1
+ new_hist_file = os.path.join(profile_dir, 'history.sqlite.new'+str(i))
+ new_db = sqlite3.connect(new_hist_file)
+ new_db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
+ primary key autoincrement, start timestamp,
+ end timestamp, num_cmds integer, remark text)""")
+ new_db.execute("""CREATE TABLE IF NOT EXISTS history
+ (session integer, line integer, source text, source_raw text,
+ PRIMARY KEY (session, line))""")
+ new_db.execute("""CREATE TABLE IF NOT EXISTS output_history
+ (session integer, line integer, output text,
+ PRIMARY KEY (session, line))""")
+ new_db.commit()
+
+
+ if inputs:
+ with new_db:
+ # Add the recent history into the new database.
+ new_db.executemany('insert into sessions values (?,?,?,?,?)', sessions)
+ new_db.executemany('insert into history values (?,?,?,?)', inputs)
+ new_db.executemany('insert into output_history values (?,?,?)', outputs)
+ new_db.close()
+
+ if self.backup:
+ i = 1
+ backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
+ while os.path.exists(backup_hist_file):
+ i += 1
+ backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
+ os.rename(hist_file, backup_hist_file)
+ print("Backed up longer history file to", backup_hist_file)
+ else:
+ os.remove(hist_file)
+
+ os.rename(new_hist_file, hist_file)
+
+class HistoryClear(HistoryTrim):
+ description = clear_hist_help
keep = Int(0,
- help="Number of recent lines to keep in the database.")
-
+ help="Number of recent lines to keep in the database.")
+
force = Bool(False,
help="Don't prompt user for confirmation"
).tag(config=True)
-
- flags = Dict(dict(
- force = ({'HistoryClear' : {'force' : True}},
+
+ flags = Dict(dict(
+ force = ({'HistoryClear' : {'force' : True}},
force.help),
- f = ({'HistoryTrim' : {'force' : True}},
+ f = ({'HistoryTrim' : {'force' : True}},
force.help
- )
- ))
- aliases = Dict()
-
- def start(self):
- if self.force or ask_yes_no("Really delete all ipython history? ",
- default="no", interrupt="no"):
- HistoryTrim.start(self)
-
-class HistoryApp(Application):
- name = u'ipython-history'
- description = "Manage the IPython history database."
-
- subcommands = Dict(dict(
- trim = (HistoryTrim, HistoryTrim.description.splitlines()[0]),
- clear = (HistoryClear, HistoryClear.description.splitlines()[0]),
- ))
-
- def start(self):
- if self.subapp is None:
- print("No subcommand specified. Must specify one of: %s" % \
- (self.subcommands.keys()))
- print()
- self.print_description()
- self.print_subcommands()
- self.exit(1)
- else:
- return self.subapp.start()
+ )
+ ))
+ aliases = Dict()
+
+ def start(self):
+ if self.force or ask_yes_no("Really delete all ipython history? ",
+ default="no", interrupt="no"):
+ HistoryTrim.start(self)
+
+class HistoryApp(Application):
+ name = u'ipython-history'
+ description = "Manage the IPython history database."
+
+ subcommands = Dict(dict(
+ trim = (HistoryTrim, HistoryTrim.description.splitlines()[0]),
+ clear = (HistoryClear, HistoryClear.description.splitlines()[0]),
+ ))
+
+ def start(self):
+ if self.subapp is None:
+ print("No subcommand specified. Must specify one of: %s" % \
+ (self.subcommands.keys()))
+ print()
+ self.print_description()
+ self.print_subcommands()
+ self.exit(1)
+ else:
+ return self.subapp.start()
diff --git a/contrib/python/ipython/py2/IPython/core/hooks.py b/contrib/python/ipython/py2/IPython/core/hooks.py
index 374ccb4b0f..e6fc84087f 100644
--- a/contrib/python/ipython/py2/IPython/core/hooks.py
+++ b/contrib/python/ipython/py2/IPython/core/hooks.py
@@ -1,98 +1,98 @@
-"""Hooks for IPython.
-
-In Python, it is possible to overwrite any method of any object if you really
-want to. But IPython exposes a few 'hooks', methods which are *designed* to
-be overwritten by users for customization purposes. This module defines the
-default versions of all such hooks, which get used by IPython if not
-overridden by the user.
-
-Hooks are simple functions, but they should be declared with ``self`` as their
-first argument, because when activated they are registered into IPython as
-instance methods. The self argument will be the IPython running instance
-itself, so hooks have full access to the entire IPython object.
-
-If you wish to define a new hook and activate it, you can make an :doc:`extension
-</config/extensions/index>` or a :ref:`startup script <startup_files>`. For
-example, you could use a startup file like this::
-
- import os
-
- def calljed(self,filename, linenum):
- "My editor hook calls the jed editor directly."
- print "Calling my own editor, jed ..."
- if os.system('jed +%d %s' % (linenum,filename)) != 0:
- raise TryNext()
-
- def load_ipython_extension(ip):
- ip.set_hook('editor', calljed)
-
-"""
-
-#*****************************************************************************
-# Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#*****************************************************************************
-
-import os
-import subprocess
+"""Hooks for IPython.
+
+In Python, it is possible to overwrite any method of any object if you really
+want to. But IPython exposes a few 'hooks', methods which are *designed* to
+be overwritten by users for customization purposes. This module defines the
+default versions of all such hooks, which get used by IPython if not
+overridden by the user.
+
+Hooks are simple functions, but they should be declared with ``self`` as their
+first argument, because when activated they are registered into IPython as
+instance methods. The self argument will be the IPython running instance
+itself, so hooks have full access to the entire IPython object.
+
+If you wish to define a new hook and activate it, you can make an :doc:`extension
+</config/extensions/index>` or a :ref:`startup script <startup_files>`. For
+example, you could use a startup file like this::
+
+ import os
+
+ def calljed(self,filename, linenum):
+ "My editor hook calls the jed editor directly."
+ print "Calling my own editor, jed ..."
+ if os.system('jed +%d %s' % (linenum,filename)) != 0:
+ raise TryNext()
+
+ def load_ipython_extension(ip):
+ ip.set_hook('editor', calljed)
+
+"""
+
+#*****************************************************************************
+# Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#*****************************************************************************
+
+import os
+import subprocess
import warnings
-import sys
-
-from IPython.core.error import TryNext
-
-# List here all the default hooks. For now it's just the editor functions
-# but over time we'll move here all the public API for user-accessible things.
-
-__all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
- 'shutdown_hook', 'late_startup_hook',
- 'show_in_pager','pre_prompt_hook',
- 'pre_run_code_hook', 'clipboard_get']
-
-deprecated = {'pre_run_code_hook': "a callback for the 'pre_execute' or 'pre_run_cell' event",
- 'late_startup_hook': "a callback for the 'shell_initialized' event",
- 'shutdown_hook': "the atexit module",
- }
-
-def editor(self, filename, linenum=None, wait=True):
- """Open the default editor at the given filename and linenumber.
-
- This is IPython's default editor hook, you can use it as an example to
- write your own modified one. To set your own editor function as the
- new editor hook, call ip.set_hook('editor',yourfunc)."""
-
- # IPython configures a default editor at startup by reading $EDITOR from
- # the environment, and falling back on vi (unix) or notepad (win32).
- editor = self.editor
-
- # marker for at which line to open the file (for existing objects)
- if linenum is None or editor=='notepad':
- linemark = ''
- else:
- linemark = '+%d' % int(linenum)
-
- # Enclose in quotes if necessary and legal
- if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
- editor = '"%s"' % editor
-
- # Call the actual editor
- proc = subprocess.Popen('%s %s %s' % (editor, linemark, filename),
- shell=True)
- if wait and proc.wait() != 0:
- raise TryNext()
-
-import tempfile
-def fix_error_editor(self,filename,linenum,column,msg):
+import sys
+
+from IPython.core.error import TryNext
+
+# List here all the default hooks. For now it's just the editor functions
+# but over time we'll move here all the public API for user-accessible things.
+
+__all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
+ 'shutdown_hook', 'late_startup_hook',
+ 'show_in_pager','pre_prompt_hook',
+ 'pre_run_code_hook', 'clipboard_get']
+
+deprecated = {'pre_run_code_hook': "a callback for the 'pre_execute' or 'pre_run_cell' event",
+ 'late_startup_hook': "a callback for the 'shell_initialized' event",
+ 'shutdown_hook': "the atexit module",
+ }
+
+def editor(self, filename, linenum=None, wait=True):
+ """Open the default editor at the given filename and linenumber.
+
+ This is IPython's default editor hook, you can use it as an example to
+ write your own modified one. To set your own editor function as the
+ new editor hook, call ip.set_hook('editor',yourfunc)."""
+
+ # IPython configures a default editor at startup by reading $EDITOR from
+ # the environment, and falling back on vi (unix) or notepad (win32).
+ editor = self.editor
+
+ # marker for at which line to open the file (for existing objects)
+ if linenum is None or editor=='notepad':
+ linemark = ''
+ else:
+ linemark = '+%d' % int(linenum)
+
+ # Enclose in quotes if necessary and legal
+ if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
+ editor = '"%s"' % editor
+
+ # Call the actual editor
+ proc = subprocess.Popen('%s %s %s' % (editor, linemark, filename),
+ shell=True)
+ if wait and proc.wait() != 0:
+ raise TryNext()
+
+import tempfile
+def fix_error_editor(self,filename,linenum,column,msg):
"""DEPRECATED
Open the editor at the given filename, linenumber, column and
- show an error message. This is used for correcting syntax errors.
- The current implementation only has special support for the VIM editor,
- and falls back on the 'editor' hook if VIM is not used.
-
+ show an error message. This is used for correcting syntax errors.
+ The current implementation only has special support for the VIM editor,
+ and falls back on the 'editor' hook if VIM is not used.
+
Call ip.set_hook('fix_error_editor',yourfunc) to use your own function,
- """
+ """
warnings.warn("""
`fix_error_editor` is pending deprecation as of IPython 5.0 and will be removed
@@ -102,125 +102,125 @@ happend to use this function and still need it please make your voice heard on
the mailing list ipython-dev@python.org , or on the GitHub Issue tracker:
https://github.com/ipython/ipython/issues/9649 """, UserWarning)
- def vim_quickfix_file():
- t = tempfile.NamedTemporaryFile()
- t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
- t.flush()
- return t
- if os.path.basename(self.editor) != 'vim':
- self.hooks.editor(filename,linenum)
- return
- t = vim_quickfix_file()
- try:
- if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
- raise TryNext()
- finally:
- t.close()
-
-
-def synchronize_with_editor(self, filename, linenum, column):
- pass
-
-
-class CommandChainDispatcher:
- """ Dispatch calls to a chain of commands until some func can handle it
-
- Usage: instantiate, execute "add" to add commands (with optional
- priority), execute normally via f() calling mechanism.
-
- """
- def __init__(self,commands=None):
- if commands is None:
- self.chain = []
- else:
- self.chain = commands
-
-
- def __call__(self,*args, **kw):
- """ Command chain is called just like normal func.
-
- This will call all funcs in chain with the same args as were given to
- this function, and return the result of first func that didn't raise
- TryNext"""
- last_exc = TryNext()
- for prio,cmd in self.chain:
- #print "prio",prio,"cmd",cmd #dbg
- try:
- return cmd(*args, **kw)
- except TryNext as exc:
- last_exc = exc
- # if no function will accept it, raise TryNext up to the caller
- raise last_exc
-
- def __str__(self):
- return str(self.chain)
-
- def add(self, func, priority=0):
- """ Add a func to the cmd chain with given priority """
- self.chain.append((priority, func))
- self.chain.sort(key=lambda x: x[0])
-
- def __iter__(self):
- """ Return all objects in chain.
-
- Handy if the objects are not callable.
- """
- return iter(self.chain)
-
-
-def shutdown_hook(self):
- """ default shutdown hook
-
- Typically, shotdown hooks should raise TryNext so all shutdown ops are done
- """
-
- #print "default shutdown hook ok" # dbg
- return
-
-
-def late_startup_hook(self):
- """ Executed after ipython has been constructed and configured
-
- """
- #print "default startup hook ok" # dbg
-
-
-def show_in_pager(self, data, start, screen_lines):
- """ Run a string through pager """
- # raising TryNext here will use the default paging functionality
- raise TryNext
-
-
-def pre_prompt_hook(self):
- """ Run before displaying the next prompt
-
- Use this e.g. to display output from asynchronous operations (in order
- to not mess up text entry)
- """
-
- return None
-
-
-def pre_run_code_hook(self):
- """ Executed before running the (prefiltered) code in IPython """
- return None
-
-
-def clipboard_get(self):
- """ Get text from the clipboard.
- """
- from IPython.lib.clipboard import (
- osx_clipboard_get, tkinter_clipboard_get,
- win32_clipboard_get
- )
- if sys.platform == 'win32':
- chain = [win32_clipboard_get, tkinter_clipboard_get]
- elif sys.platform == 'darwin':
- chain = [osx_clipboard_get, tkinter_clipboard_get]
- else:
- chain = [tkinter_clipboard_get]
- dispatcher = CommandChainDispatcher()
- for func in chain:
- dispatcher.add(func)
- text = dispatcher()
- return text
+ def vim_quickfix_file():
+ t = tempfile.NamedTemporaryFile()
+ t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
+ t.flush()
+ return t
+ if os.path.basename(self.editor) != 'vim':
+ self.hooks.editor(filename,linenum)
+ return
+ t = vim_quickfix_file()
+ try:
+ if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
+ raise TryNext()
+ finally:
+ t.close()
+
+
+def synchronize_with_editor(self, filename, linenum, column):
+ pass
+
+
+class CommandChainDispatcher:
+ """ Dispatch calls to a chain of commands until some func can handle it
+
+ Usage: instantiate, execute "add" to add commands (with optional
+ priority), execute normally via f() calling mechanism.
+
+ """
+ def __init__(self,commands=None):
+ if commands is None:
+ self.chain = []
+ else:
+ self.chain = commands
+
+
+ def __call__(self,*args, **kw):
+ """ Command chain is called just like normal func.
+
+ This will call all funcs in chain with the same args as were given to
+ this function, and return the result of first func that didn't raise
+ TryNext"""
+ last_exc = TryNext()
+ for prio,cmd in self.chain:
+ #print "prio",prio,"cmd",cmd #dbg
+ try:
+ return cmd(*args, **kw)
+ except TryNext as exc:
+ last_exc = exc
+ # if no function will accept it, raise TryNext up to the caller
+ raise last_exc
+
+ def __str__(self):
+ return str(self.chain)
+
+ def add(self, func, priority=0):
+ """ Add a func to the cmd chain with given priority """
+ self.chain.append((priority, func))
+ self.chain.sort(key=lambda x: x[0])
+
+ def __iter__(self):
+ """ Return all objects in chain.
+
+ Handy if the objects are not callable.
+ """
+ return iter(self.chain)
+
+
+def shutdown_hook(self):
+ """ default shutdown hook
+
+ Typically, shotdown hooks should raise TryNext so all shutdown ops are done
+ """
+
+ #print "default shutdown hook ok" # dbg
+ return
+
+
+def late_startup_hook(self):
+ """ Executed after ipython has been constructed and configured
+
+ """
+ #print "default startup hook ok" # dbg
+
+
+def show_in_pager(self, data, start, screen_lines):
+ """ Run a string through pager """
+ # raising TryNext here will use the default paging functionality
+ raise TryNext
+
+
+def pre_prompt_hook(self):
+ """ Run before displaying the next prompt
+
+ Use this e.g. to display output from asynchronous operations (in order
+ to not mess up text entry)
+ """
+
+ return None
+
+
+def pre_run_code_hook(self):
+ """ Executed before running the (prefiltered) code in IPython """
+ return None
+
+
+def clipboard_get(self):
+ """ Get text from the clipboard.
+ """
+ from IPython.lib.clipboard import (
+ osx_clipboard_get, tkinter_clipboard_get,
+ win32_clipboard_get
+ )
+ if sys.platform == 'win32':
+ chain = [win32_clipboard_get, tkinter_clipboard_get]
+ elif sys.platform == 'darwin':
+ chain = [osx_clipboard_get, tkinter_clipboard_get]
+ else:
+ chain = [tkinter_clipboard_get]
+ dispatcher = CommandChainDispatcher()
+ for func in chain:
+ dispatcher.add(func)
+ text = dispatcher()
+ return text
diff --git a/contrib/python/ipython/py2/IPython/core/inputsplitter.py b/contrib/python/ipython/py2/IPython/core/inputsplitter.py
index 2c7125f88d..ac14747d69 100644
--- a/contrib/python/ipython/py2/IPython/core/inputsplitter.py
+++ b/contrib/python/ipython/py2/IPython/core/inputsplitter.py
@@ -1,681 +1,681 @@
-"""Input handling and transformation machinery.
-
-The first class in this module, :class:`InputSplitter`, is designed to tell when
-input from a line-oriented frontend is complete and should be executed, and when
-the user should be prompted for another line of code instead. The name 'input
-splitter' is largely for historical reasons.
-
-A companion, :class:`IPythonInputSplitter`, provides the same functionality but
-with full support for the extended IPython syntax (magics, system calls, etc).
-The code to actually do these transformations is in :mod:`IPython.core.inputtransformer`.
-:class:`IPythonInputSplitter` feeds the raw code to the transformers in order
-and stores the results.
-
-For more details, see the class docstrings below.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-import ast
-import codeop
-import re
-import sys
-import warnings
-
-from IPython.utils.py3compat import cast_unicode
-from IPython.core.inputtransformer import (leading_indent,
- classic_prompt,
- ipy_prompt,
- strip_encoding_cookie,
- cellmagic,
- assemble_logical_lines,
- help_end,
- escaped_commands,
- assign_from_magic,
- assign_from_system,
- assemble_python_lines,
- )
-
-# These are available in this module for backwards compatibility.
-from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP,
- ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,
- ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES)
-
-#-----------------------------------------------------------------------------
-# Utilities
-#-----------------------------------------------------------------------------
-
-# FIXME: These are general-purpose utilities that later can be moved to the
-# general ward. Kept here for now because we're being very strict about test
-# coverage with this code, and this lets us ensure that we keep 100% coverage
-# while developing.
-
-# compiled regexps for autoindent management
-dedent_re = re.compile('|'.join([
- r'^\s+raise(\s.*)?$', # raise statement (+ space + other stuff, maybe)
- r'^\s+raise\([^\)]*\).*$', # wacky raise with immediate open paren
- r'^\s+return(\s.*)?$', # normal return (+ space + other stuff, maybe)
- r'^\s+return\([^\)]*\).*$', # wacky return with immediate open paren
- r'^\s+pass\s*$', # pass (optionally followed by trailing spaces)
- r'^\s+break\s*$', # break (optionally followed by trailing spaces)
- r'^\s+continue\s*$', # continue (optionally followed by trailing spaces)
-]))
-ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)')
-
-# regexp to match pure comment lines so we don't accidentally insert 'if 1:'
-# before pure comments
-comment_line_re = re.compile('^\s*\#')
-
-
-def num_ini_spaces(s):
- """Return the number of initial spaces in a string.
-
- Note that tabs are counted as a single space. For now, we do *not* support
- mixing of tabs and spaces in the user's input.
-
- Parameters
- ----------
- s : string
-
- Returns
- -------
- n : int
- """
-
- ini_spaces = ini_spaces_re.match(s)
- if ini_spaces:
- return ini_spaces.end()
- else:
- return 0
-
-def last_blank(src):
- """Determine if the input source ends in a blank.
-
- A blank is either a newline or a line consisting of whitespace.
-
- Parameters
- ----------
- src : string
- A single or multiline string.
- """
- if not src: return False
- ll = src.splitlines()[-1]
- return (ll == '') or ll.isspace()
-
-
-last_two_blanks_re = re.compile(r'\n\s*\n\s*$', re.MULTILINE)
-last_two_blanks_re2 = re.compile(r'.+\n\s*\n\s+$', re.MULTILINE)
-
-def last_two_blanks(src):
- """Determine if the input source ends in two blanks.
-
- A blank is either a newline or a line consisting of whitespace.
-
- Parameters
- ----------
- src : string
- A single or multiline string.
- """
- if not src: return False
- # The logic here is tricky: I couldn't get a regexp to work and pass all
- # the tests, so I took a different approach: split the source by lines,
- # grab the last two and prepend '###\n' as a stand-in for whatever was in
- # the body before the last two lines. Then, with that structure, it's
- # possible to analyze with two regexps. Not the most elegant solution, but
- # it works. If anyone tries to change this logic, make sure to validate
- # the whole test suite first!
- new_src = '\n'.join(['###\n'] + src.splitlines()[-2:])
- return (bool(last_two_blanks_re.match(new_src)) or
- bool(last_two_blanks_re2.match(new_src)) )
-
-
-def remove_comments(src):
- """Remove all comments from input source.
-
- Note: comments are NOT recognized inside of strings!
-
- Parameters
- ----------
- src : string
- A single or multiline input string.
-
- Returns
- -------
- String with all Python comments removed.
- """
-
- return re.sub('#.*', '', src)
-
-
-def get_input_encoding():
- """Return the default standard input encoding.
-
- If sys.stdin has no encoding, 'ascii' is returned."""
- # There are strange environments for which sys.stdin.encoding is None. We
- # ensure that a valid encoding is returned.
- encoding = getattr(sys.stdin, 'encoding', None)
- if encoding is None:
- encoding = 'ascii'
- return encoding
-
-#-----------------------------------------------------------------------------
-# Classes and functions for normal Python syntax handling
-#-----------------------------------------------------------------------------
-
-class InputSplitter(object):
- r"""An object that can accumulate lines of Python source before execution.
-
- This object is designed to be fed python source line-by-line, using
- :meth:`push`. It will return on each push whether the currently pushed
- code could be executed already. In addition, it provides a method called
- :meth:`push_accepts_more` that can be used to query whether more input
- can be pushed into a single interactive block.
-
- This is a simple example of how an interactive terminal-based client can use
- this tool::
-
- isp = InputSplitter()
- while isp.push_accepts_more():
- indent = ' '*isp.indent_spaces
- prompt = '>>> ' + indent
- line = indent + raw_input(prompt)
- isp.push(line)
- print 'Input source was:\n', isp.source_reset(),
- """
- # Number of spaces of indentation computed from input that has been pushed
- # so far. This is the attributes callers should query to get the current
- # indentation level, in order to provide auto-indent facilities.
- indent_spaces = 0
- # String, indicating the default input encoding. It is computed by default
- # at initialization time via get_input_encoding(), but it can be reset by a
- # client with specific knowledge of the encoding.
- encoding = ''
- # String where the current full source input is stored, properly encoded.
- # Reading this attribute is the normal way of querying the currently pushed
- # source code, that has been properly encoded.
- source = ''
- # Code object corresponding to the current source. It is automatically
- # synced to the source, so it can be queried at any time to obtain the code
- # object; it will be None if the source doesn't compile to valid Python.
- code = None
-
- # Private attributes
-
- # List with lines of input accumulated so far
- _buffer = None
- # Command compiler
- _compile = None
- # Mark when input has changed indentation all the way back to flush-left
- _full_dedent = False
- # Boolean indicating whether the current block is complete
- _is_complete = None
- # Boolean indicating whether the current block has an unrecoverable syntax error
- _is_invalid = False
-
- def __init__(self):
- """Create a new InputSplitter instance.
- """
- self._buffer = []
- self._compile = codeop.CommandCompiler()
- self.encoding = get_input_encoding()
-
- def reset(self):
- """Reset the input buffer and associated state."""
- self.indent_spaces = 0
- self._buffer[:] = []
- self.source = ''
- self.code = None
- self._is_complete = False
- self._is_invalid = False
- self._full_dedent = False
-
- def source_reset(self):
- """Return the input source and perform a full reset.
- """
- out = self.source
- self.reset()
- return out
-
- def check_complete(self, source):
- """Return whether a block of code is ready to execute, or should be continued
-
- This is a non-stateful API, and will reset the state of this InputSplitter.
-
- Parameters
- ----------
- source : string
- Python input code, which can be multiline.
-
- Returns
- -------
- status : str
- One of 'complete', 'incomplete', or 'invalid' if source is not a
- prefix of valid code.
- indent_spaces : int or None
- The number of spaces by which to indent the next line of code. If
- status is not 'incomplete', this is None.
- """
- self.reset()
- try:
- self.push(source)
- except SyntaxError:
- # Transformers in IPythonInputSplitter can raise SyntaxError,
- # which push() will not catch.
- return 'invalid', None
- else:
- if self._is_invalid:
- return 'invalid', None
- elif self.push_accepts_more():
- return 'incomplete', self.indent_spaces
- else:
- return 'complete', None
- finally:
- self.reset()
-
- def push(self, lines):
- """Push one or more lines of input.
-
- This stores the given lines and returns a status code indicating
- whether the code forms a complete Python block or not.
-
- Any exceptions generated in compilation are swallowed, but if an
- exception was produced, the method returns True.
-
- Parameters
- ----------
- lines : string
- One or more lines of Python input.
-
- Returns
- -------
- is_complete : boolean
- True if the current input source (the result of the current input
- plus prior inputs) forms a complete Python execution block. Note that
- this value is also stored as a private attribute (``_is_complete``), so it
- can be queried at any time.
- """
- self._store(lines)
- source = self.source
-
- # Before calling _compile(), reset the code object to None so that if an
- # exception is raised in compilation, we don't mislead by having
- # inconsistent code/source attributes.
- self.code, self._is_complete = None, None
- self._is_invalid = False
-
- # Honor termination lines properly
- if source.endswith('\\\n'):
- return False
-
- self._update_indent(lines)
- try:
- with warnings.catch_warnings():
- warnings.simplefilter('error', SyntaxWarning)
- self.code = self._compile(source, symbol="exec")
- # Invalid syntax can produce any of a number of different errors from
- # inside the compiler, so we have to catch them all. Syntax errors
- # immediately produce a 'ready' block, so the invalid Python can be
- # sent to the kernel for evaluation with possible ipython
- # special-syntax conversion.
- except (SyntaxError, OverflowError, ValueError, TypeError,
- MemoryError, SyntaxWarning):
- self._is_complete = True
- self._is_invalid = True
- else:
- # Compilation didn't produce any exceptions (though it may not have
- # given a complete code object)
- self._is_complete = self.code is not None
-
- return self._is_complete
-
- def push_accepts_more(self):
- """Return whether a block of interactive input can accept more input.
-
- This method is meant to be used by line-oriented frontends, who need to
- guess whether a block is complete or not based solely on prior and
- current input lines. The InputSplitter considers it has a complete
- interactive block and will not accept more input when either:
-
- * A SyntaxError is raised
-
- * The code is complete and consists of a single line or a single
- non-compound statement
-
- * The code is complete and has a blank line at the end
-
- If the current input produces a syntax error, this method immediately
- returns False but does *not* raise the syntax error exception, as
- typically clients will want to send invalid syntax to an execution
- backend which might convert the invalid syntax into valid Python via
- one of the dynamic IPython mechanisms.
- """
-
- # With incomplete input, unconditionally accept more
- # A syntax error also sets _is_complete to True - see push()
- if not self._is_complete:
- #print("Not complete") # debug
- return True
-
- # The user can make any (complete) input execute by leaving a blank line
- last_line = self.source.splitlines()[-1]
- if (not last_line) or last_line.isspace():
- #print("Blank line") # debug
- return False
-
- # If there's just a single line or AST node, and we're flush left, as is
- # the case after a simple statement such as 'a=1', we want to execute it
- # straight away.
- if self.indent_spaces==0:
- if len(self.source.splitlines()) <= 1:
- return False
-
- try:
- code_ast = ast.parse(u''.join(self._buffer))
- except Exception:
- #print("Can't parse AST") # debug
- return False
- else:
- if len(code_ast.body) == 1 and \
- not hasattr(code_ast.body[0], 'body'):
- #print("Simple statement") # debug
- return False
-
- # General fallback - accept more code
- return True
-
- #------------------------------------------------------------------------
- # Private interface
- #------------------------------------------------------------------------
-
- def _find_indent(self, line):
- """Compute the new indentation level for a single line.
-
- Parameters
- ----------
- line : str
- A single new line of non-whitespace, non-comment Python input.
-
- Returns
- -------
- indent_spaces : int
- New value for the indent level (it may be equal to self.indent_spaces
- if indentation doesn't change.
-
- full_dedent : boolean
- Whether the new line causes a full flush-left dedent.
- """
- indent_spaces = self.indent_spaces
- full_dedent = self._full_dedent
-
- inisp = num_ini_spaces(line)
- if inisp < indent_spaces:
- indent_spaces = inisp
- if indent_spaces <= 0:
- #print 'Full dedent in text',self.source # dbg
- full_dedent = True
-
- if line.rstrip()[-1] == ':':
- indent_spaces += 4
- elif dedent_re.match(line):
- indent_spaces -= 4
- if indent_spaces <= 0:
- full_dedent = True
-
- # Safety
- if indent_spaces < 0:
- indent_spaces = 0
- #print 'safety' # dbg
-
- return indent_spaces, full_dedent
-
- def _update_indent(self, lines):
- for line in remove_comments(lines).splitlines():
- if line and not line.isspace():
- self.indent_spaces, self._full_dedent = self._find_indent(line)
-
- def _store(self, lines, buffer=None, store='source'):
- """Store one or more lines of input.
-
- If input lines are not newline-terminated, a newline is automatically
- appended."""
-
- if buffer is None:
- buffer = self._buffer
-
- if lines.endswith('\n'):
- buffer.append(lines)
- else:
- buffer.append(lines+'\n')
- setattr(self, store, self._set_source(buffer))
-
- def _set_source(self, buffer):
- return u''.join(buffer)
-
-
-class IPythonInputSplitter(InputSplitter):
- """An input splitter that recognizes all of IPython's special syntax."""
-
- # String with raw, untransformed input.
- source_raw = ''
-
- # Flag to track when a transformer has stored input that it hasn't given
- # back yet.
- transformer_accumulating = False
-
- # Flag to track when assemble_python_lines has stored input that it hasn't
- # given back yet.
- within_python_line = False
-
- # Private attributes
-
- # List with lines of raw input accumulated so far.
- _buffer_raw = None
-
- def __init__(self, line_input_checker=True, physical_line_transforms=None,
- logical_line_transforms=None, python_line_transforms=None):
- super(IPythonInputSplitter, self).__init__()
- self._buffer_raw = []
- self._validate = True
-
- if physical_line_transforms is not None:
- self.physical_line_transforms = physical_line_transforms
- else:
- self.physical_line_transforms = [
- leading_indent(),
- classic_prompt(),
- ipy_prompt(),
- cellmagic(end_on_blank_line=line_input_checker),
- strip_encoding_cookie(),
- ]
-
- self.assemble_logical_lines = assemble_logical_lines()
- if logical_line_transforms is not None:
- self.logical_line_transforms = logical_line_transforms
- else:
- self.logical_line_transforms = [
- help_end(),
- escaped_commands(),
- assign_from_magic(),
- assign_from_system(),
- ]
-
- self.assemble_python_lines = assemble_python_lines()
- if python_line_transforms is not None:
- self.python_line_transforms = python_line_transforms
- else:
- # We don't use any of these at present
- self.python_line_transforms = []
-
- @property
- def transforms(self):
- "Quick access to all transformers."
- return self.physical_line_transforms + \
- [self.assemble_logical_lines] + self.logical_line_transforms + \
- [self.assemble_python_lines] + self.python_line_transforms
-
- @property
- def transforms_in_use(self):
- """Transformers, excluding logical line transformers if we're in a
- Python line."""
- t = self.physical_line_transforms[:]
- if not self.within_python_line:
- t += [self.assemble_logical_lines] + self.logical_line_transforms
- return t + [self.assemble_python_lines] + self.python_line_transforms
-
- def reset(self):
- """Reset the input buffer and associated state."""
- super(IPythonInputSplitter, self).reset()
- self._buffer_raw[:] = []
- self.source_raw = ''
- self.transformer_accumulating = False
- self.within_python_line = False
-
- for t in self.transforms:
- try:
- t.reset()
- except SyntaxError:
- # Nothing that calls reset() expects to handle transformer
- # errors
- pass
-
- def flush_transformers(self):
- def _flush(transform, outs):
- """yield transformed lines
-
- always strings, never None
-
- transform: the current transform
- outs: an iterable of previously transformed inputs.
- Each may be multiline, which will be passed
- one line at a time to transform.
- """
- for out in outs:
- for line in out.splitlines():
- # push one line at a time
- tmp = transform.push(line)
- if tmp is not None:
- yield tmp
-
- # reset the transform
- tmp = transform.reset()
- if tmp is not None:
- yield tmp
-
- out = []
- for t in self.transforms_in_use:
- out = _flush(t, out)
-
- out = list(out)
- if out:
- self._store('\n'.join(out))
-
- def raw_reset(self):
- """Return raw input only and perform a full reset.
- """
- out = self.source_raw
- self.reset()
- return out
-
- def source_reset(self):
- try:
- self.flush_transformers()
- return self.source
- finally:
- self.reset()
-
- def push_accepts_more(self):
- if self.transformer_accumulating:
- return True
- else:
- return super(IPythonInputSplitter, self).push_accepts_more()
-
- def transform_cell(self, cell):
- """Process and translate a cell of input.
- """
- self.reset()
- try:
- self.push(cell)
- self.flush_transformers()
- return self.source
- finally:
- self.reset()
-
- def push(self, lines):
- """Push one or more lines of IPython input.
-
- This stores the given lines and returns a status code indicating
- whether the code forms a complete Python block or not, after processing
- all input lines for special IPython syntax.
-
- Any exceptions generated in compilation are swallowed, but if an
- exception was produced, the method returns True.
-
- Parameters
- ----------
- lines : string
- One or more lines of Python input.
-
- Returns
- -------
- is_complete : boolean
- True if the current input source (the result of the current input
- plus prior inputs) forms a complete Python execution block. Note that
- this value is also stored as a private attribute (_is_complete), so it
- can be queried at any time.
- """
-
- # We must ensure all input is pure unicode
- lines = cast_unicode(lines, self.encoding)
- # ''.splitlines() --> [], but we need to push the empty line to transformers
- lines_list = lines.splitlines()
- if not lines_list:
- lines_list = ['']
-
- # Store raw source before applying any transformations to it. Note
- # that this must be done *after* the reset() call that would otherwise
- # flush the buffer.
- self._store(lines, self._buffer_raw, 'source_raw')
-
- for line in lines_list:
- out = self.push_line(line)
-
- return out
-
- def push_line(self, line):
- buf = self._buffer
-
- def _accumulating(dbg):
- #print(dbg)
- self.transformer_accumulating = True
- return False
-
- for transformer in self.physical_line_transforms:
- line = transformer.push(line)
- if line is None:
- return _accumulating(transformer)
-
- if not self.within_python_line:
- line = self.assemble_logical_lines.push(line)
- if line is None:
- return _accumulating('acc logical line')
-
- for transformer in self.logical_line_transforms:
- line = transformer.push(line)
- if line is None:
- return _accumulating(transformer)
-
- line = self.assemble_python_lines.push(line)
- if line is None:
- self.within_python_line = True
- return _accumulating('acc python line')
- else:
- self.within_python_line = False
-
- for transformer in self.python_line_transforms:
- line = transformer.push(line)
- if line is None:
- return _accumulating(transformer)
-
- #print("transformers clear") #debug
- self.transformer_accumulating = False
- return super(IPythonInputSplitter, self).push(line)
+"""Input handling and transformation machinery.
+
+The first class in this module, :class:`InputSplitter`, is designed to tell when
+input from a line-oriented frontend is complete and should be executed, and when
+the user should be prompted for another line of code instead. The name 'input
+splitter' is largely for historical reasons.
+
+A companion, :class:`IPythonInputSplitter`, provides the same functionality but
+with full support for the extended IPython syntax (magics, system calls, etc).
+The code to actually do these transformations is in :mod:`IPython.core.inputtransformer`.
+:class:`IPythonInputSplitter` feeds the raw code to the transformers in order
+and stores the results.
+
+For more details, see the class docstrings below.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+import ast
+import codeop
+import re
+import sys
+import warnings
+
+from IPython.utils.py3compat import cast_unicode
+from IPython.core.inputtransformer import (leading_indent,
+ classic_prompt,
+ ipy_prompt,
+ strip_encoding_cookie,
+ cellmagic,
+ assemble_logical_lines,
+ help_end,
+ escaped_commands,
+ assign_from_magic,
+ assign_from_system,
+ assemble_python_lines,
+ )
+
+# These are available in this module for backwards compatibility.
+from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP,
+ ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,
+ ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES)
+
+#-----------------------------------------------------------------------------
+# Utilities
+#-----------------------------------------------------------------------------
+
+# FIXME: These are general-purpose utilities that later can be moved to the
+# general ward. Kept here for now because we're being very strict about test
+# coverage with this code, and this lets us ensure that we keep 100% coverage
+# while developing.
+
+# compiled regexps for autoindent management
+dedent_re = re.compile('|'.join([
+ r'^\s+raise(\s.*)?$', # raise statement (+ space + other stuff, maybe)
+ r'^\s+raise\([^\)]*\).*$', # wacky raise with immediate open paren
+ r'^\s+return(\s.*)?$', # normal return (+ space + other stuff, maybe)
+ r'^\s+return\([^\)]*\).*$', # wacky return with immediate open paren
+ r'^\s+pass\s*$', # pass (optionally followed by trailing spaces)
+ r'^\s+break\s*$', # break (optionally followed by trailing spaces)
+ r'^\s+continue\s*$', # continue (optionally followed by trailing spaces)
+]))
+ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)')
+
+# regexp to match pure comment lines so we don't accidentally insert 'if 1:'
+# before pure comments
+comment_line_re = re.compile('^\s*\#')
+
+
+def num_ini_spaces(s):
+ """Return the number of initial spaces in a string.
+
+ Note that tabs are counted as a single space. For now, we do *not* support
+ mixing of tabs and spaces in the user's input.
+
+ Parameters
+ ----------
+ s : string
+
+ Returns
+ -------
+ n : int
+ """
+
+ ini_spaces = ini_spaces_re.match(s)
+ if ini_spaces:
+ return ini_spaces.end()
+ else:
+ return 0
+
+def last_blank(src):
+ """Determine if the input source ends in a blank.
+
+ A blank is either a newline or a line consisting of whitespace.
+
+ Parameters
+ ----------
+ src : string
+ A single or multiline string.
+ """
+ if not src: return False
+ ll = src.splitlines()[-1]
+ return (ll == '') or ll.isspace()
+
+
+last_two_blanks_re = re.compile(r'\n\s*\n\s*$', re.MULTILINE)
+last_two_blanks_re2 = re.compile(r'.+\n\s*\n\s+$', re.MULTILINE)
+
+def last_two_blanks(src):
+ """Determine if the input source ends in two blanks.
+
+ A blank is either a newline or a line consisting of whitespace.
+
+ Parameters
+ ----------
+ src : string
+ A single or multiline string.
+ """
+ if not src: return False
+ # The logic here is tricky: I couldn't get a regexp to work and pass all
+ # the tests, so I took a different approach: split the source by lines,
+ # grab the last two and prepend '###\n' as a stand-in for whatever was in
+ # the body before the last two lines. Then, with that structure, it's
+ # possible to analyze with two regexps. Not the most elegant solution, but
+ # it works. If anyone tries to change this logic, make sure to validate
+ # the whole test suite first!
+ new_src = '\n'.join(['###\n'] + src.splitlines()[-2:])
+ return (bool(last_two_blanks_re.match(new_src)) or
+ bool(last_two_blanks_re2.match(new_src)) )
+
+
+def remove_comments(src):
+ """Remove all comments from input source.
+
+ Note: comments are NOT recognized inside of strings!
+
+ Parameters
+ ----------
+ src : string
+ A single or multiline input string.
+
+ Returns
+ -------
+ String with all Python comments removed.
+ """
+
+ return re.sub('#.*', '', src)
+
+
+def get_input_encoding():
+ """Return the default standard input encoding.
+
+ If sys.stdin has no encoding, 'ascii' is returned."""
+ # There are strange environments for which sys.stdin.encoding is None. We
+ # ensure that a valid encoding is returned.
+ encoding = getattr(sys.stdin, 'encoding', None)
+ if encoding is None:
+ encoding = 'ascii'
+ return encoding
+
+#-----------------------------------------------------------------------------
+# Classes and functions for normal Python syntax handling
+#-----------------------------------------------------------------------------
+
+class InputSplitter(object):
+ r"""An object that can accumulate lines of Python source before execution.
+
+ This object is designed to be fed python source line-by-line, using
+ :meth:`push`. It will return on each push whether the currently pushed
+ code could be executed already. In addition, it provides a method called
+ :meth:`push_accepts_more` that can be used to query whether more input
+ can be pushed into a single interactive block.
+
+ This is a simple example of how an interactive terminal-based client can use
+ this tool::
+
+ isp = InputSplitter()
+ while isp.push_accepts_more():
+ indent = ' '*isp.indent_spaces
+ prompt = '>>> ' + indent
+ line = indent + raw_input(prompt)
+ isp.push(line)
+ print 'Input source was:\n', isp.source_reset(),
+ """
+ # Number of spaces of indentation computed from input that has been pushed
+ # so far. This is the attributes callers should query to get the current
+ # indentation level, in order to provide auto-indent facilities.
+ indent_spaces = 0
+ # String, indicating the default input encoding. It is computed by default
+ # at initialization time via get_input_encoding(), but it can be reset by a
+ # client with specific knowledge of the encoding.
+ encoding = ''
+ # String where the current full source input is stored, properly encoded.
+ # Reading this attribute is the normal way of querying the currently pushed
+ # source code, that has been properly encoded.
+ source = ''
+ # Code object corresponding to the current source. It is automatically
+ # synced to the source, so it can be queried at any time to obtain the code
+ # object; it will be None if the source doesn't compile to valid Python.
+ code = None
+
+ # Private attributes
+
+ # List with lines of input accumulated so far
+ _buffer = None
+ # Command compiler
+ _compile = None
+ # Mark when input has changed indentation all the way back to flush-left
+ _full_dedent = False
+ # Boolean indicating whether the current block is complete
+ _is_complete = None
+ # Boolean indicating whether the current block has an unrecoverable syntax error
+ _is_invalid = False
+
+ def __init__(self):
+ """Create a new InputSplitter instance.
+ """
+ self._buffer = []
+ self._compile = codeop.CommandCompiler()
+ self.encoding = get_input_encoding()
+
+ def reset(self):
+ """Reset the input buffer and associated state."""
+ self.indent_spaces = 0
+ self._buffer[:] = []
+ self.source = ''
+ self.code = None
+ self._is_complete = False
+ self._is_invalid = False
+ self._full_dedent = False
+
+ def source_reset(self):
+ """Return the input source and perform a full reset.
+ """
+ out = self.source
+ self.reset()
+ return out
+
+ def check_complete(self, source):
+ """Return whether a block of code is ready to execute, or should be continued
+
+ This is a non-stateful API, and will reset the state of this InputSplitter.
+
+ Parameters
+ ----------
+ source : string
+ Python input code, which can be multiline.
+
+ Returns
+ -------
+ status : str
+ One of 'complete', 'incomplete', or 'invalid' if source is not a
+ prefix of valid code.
+ indent_spaces : int or None
+ The number of spaces by which to indent the next line of code. If
+ status is not 'incomplete', this is None.
+ """
+ self.reset()
+ try:
+ self.push(source)
+ except SyntaxError:
+ # Transformers in IPythonInputSplitter can raise SyntaxError,
+ # which push() will not catch.
+ return 'invalid', None
+ else:
+ if self._is_invalid:
+ return 'invalid', None
+ elif self.push_accepts_more():
+ return 'incomplete', self.indent_spaces
+ else:
+ return 'complete', None
+ finally:
+ self.reset()
+
+ def push(self, lines):
+ """Push one or more lines of input.
+
+ This stores the given lines and returns a status code indicating
+ whether the code forms a complete Python block or not.
+
+ Any exceptions generated in compilation are swallowed, but if an
+ exception was produced, the method returns True.
+
+ Parameters
+ ----------
+ lines : string
+ One or more lines of Python input.
+
+ Returns
+ -------
+ is_complete : boolean
+ True if the current input source (the result of the current input
+ plus prior inputs) forms a complete Python execution block. Note that
+ this value is also stored as a private attribute (``_is_complete``), so it
+ can be queried at any time.
+ """
+ self._store(lines)
+ source = self.source
+
+ # Before calling _compile(), reset the code object to None so that if an
+ # exception is raised in compilation, we don't mislead by having
+ # inconsistent code/source attributes.
+ self.code, self._is_complete = None, None
+ self._is_invalid = False
+
+ # Honor termination lines properly
+ if source.endswith('\\\n'):
+ return False
+
+ self._update_indent(lines)
+ try:
+ with warnings.catch_warnings():
+ warnings.simplefilter('error', SyntaxWarning)
+ self.code = self._compile(source, symbol="exec")
+ # Invalid syntax can produce any of a number of different errors from
+ # inside the compiler, so we have to catch them all. Syntax errors
+ # immediately produce a 'ready' block, so the invalid Python can be
+ # sent to the kernel for evaluation with possible ipython
+ # special-syntax conversion.
+ except (SyntaxError, OverflowError, ValueError, TypeError,
+ MemoryError, SyntaxWarning):
+ self._is_complete = True
+ self._is_invalid = True
+ else:
+ # Compilation didn't produce any exceptions (though it may not have
+ # given a complete code object)
+ self._is_complete = self.code is not None
+
+ return self._is_complete
+
+ def push_accepts_more(self):
+ """Return whether a block of interactive input can accept more input.
+
+ This method is meant to be used by line-oriented frontends, who need to
+ guess whether a block is complete or not based solely on prior and
+ current input lines. The InputSplitter considers it has a complete
+ interactive block and will not accept more input when either:
+
+ * A SyntaxError is raised
+
+ * The code is complete and consists of a single line or a single
+ non-compound statement
+
+ * The code is complete and has a blank line at the end
+
+ If the current input produces a syntax error, this method immediately
+ returns False but does *not* raise the syntax error exception, as
+ typically clients will want to send invalid syntax to an execution
+ backend which might convert the invalid syntax into valid Python via
+ one of the dynamic IPython mechanisms.
+ """
+
+ # With incomplete input, unconditionally accept more
+ # A syntax error also sets _is_complete to True - see push()
+ if not self._is_complete:
+ #print("Not complete") # debug
+ return True
+
+ # The user can make any (complete) input execute by leaving a blank line
+ last_line = self.source.splitlines()[-1]
+ if (not last_line) or last_line.isspace():
+ #print("Blank line") # debug
+ return False
+
+ # If there's just a single line or AST node, and we're flush left, as is
+ # the case after a simple statement such as 'a=1', we want to execute it
+ # straight away.
+ if self.indent_spaces==0:
+ if len(self.source.splitlines()) <= 1:
+ return False
+
+ try:
+ code_ast = ast.parse(u''.join(self._buffer))
+ except Exception:
+ #print("Can't parse AST") # debug
+ return False
+ else:
+ if len(code_ast.body) == 1 and \
+ not hasattr(code_ast.body[0], 'body'):
+ #print("Simple statement") # debug
+ return False
+
+ # General fallback - accept more code
+ return True
+
+ #------------------------------------------------------------------------
+ # Private interface
+ #------------------------------------------------------------------------
+
+ def _find_indent(self, line):
+ """Compute the new indentation level for a single line.
+
+ Parameters
+ ----------
+ line : str
+ A single new line of non-whitespace, non-comment Python input.
+
+ Returns
+ -------
+ indent_spaces : int
+ New value for the indent level (it may be equal to self.indent_spaces
+ if indentation doesn't change.
+
+ full_dedent : boolean
+ Whether the new line causes a full flush-left dedent.
+ """
+ indent_spaces = self.indent_spaces
+ full_dedent = self._full_dedent
+
+ inisp = num_ini_spaces(line)
+ if inisp < indent_spaces:
+ indent_spaces = inisp
+ if indent_spaces <= 0:
+ #print 'Full dedent in text',self.source # dbg
+ full_dedent = True
+
+ if line.rstrip()[-1] == ':':
+ indent_spaces += 4
+ elif dedent_re.match(line):
+ indent_spaces -= 4
+ if indent_spaces <= 0:
+ full_dedent = True
+
+ # Safety
+ if indent_spaces < 0:
+ indent_spaces = 0
+ #print 'safety' # dbg
+
+ return indent_spaces, full_dedent
+
+ def _update_indent(self, lines):
+ for line in remove_comments(lines).splitlines():
+ if line and not line.isspace():
+ self.indent_spaces, self._full_dedent = self._find_indent(line)
+
+ def _store(self, lines, buffer=None, store='source'):
+ """Store one or more lines of input.
+
+ If input lines are not newline-terminated, a newline is automatically
+ appended."""
+
+ if buffer is None:
+ buffer = self._buffer
+
+ if lines.endswith('\n'):
+ buffer.append(lines)
+ else:
+ buffer.append(lines+'\n')
+ setattr(self, store, self._set_source(buffer))
+
+ def _set_source(self, buffer):
+ return u''.join(buffer)
+
+
+class IPythonInputSplitter(InputSplitter):
+ """An input splitter that recognizes all of IPython's special syntax."""
+
+ # String with raw, untransformed input.
+ source_raw = ''
+
+ # Flag to track when a transformer has stored input that it hasn't given
+ # back yet.
+ transformer_accumulating = False
+
+ # Flag to track when assemble_python_lines has stored input that it hasn't
+ # given back yet.
+ within_python_line = False
+
+ # Private attributes
+
+ # List with lines of raw input accumulated so far.
+ _buffer_raw = None
+
+ def __init__(self, line_input_checker=True, physical_line_transforms=None,
+ logical_line_transforms=None, python_line_transforms=None):
+ super(IPythonInputSplitter, self).__init__()
+ self._buffer_raw = []
+ self._validate = True
+
+ if physical_line_transforms is not None:
+ self.physical_line_transforms = physical_line_transforms
+ else:
+ self.physical_line_transforms = [
+ leading_indent(),
+ classic_prompt(),
+ ipy_prompt(),
+ cellmagic(end_on_blank_line=line_input_checker),
+ strip_encoding_cookie(),
+ ]
+
+ self.assemble_logical_lines = assemble_logical_lines()
+ if logical_line_transforms is not None:
+ self.logical_line_transforms = logical_line_transforms
+ else:
+ self.logical_line_transforms = [
+ help_end(),
+ escaped_commands(),
+ assign_from_magic(),
+ assign_from_system(),
+ ]
+
+ self.assemble_python_lines = assemble_python_lines()
+ if python_line_transforms is not None:
+ self.python_line_transforms = python_line_transforms
+ else:
+ # We don't use any of these at present
+ self.python_line_transforms = []
+
+ @property
+ def transforms(self):
+ "Quick access to all transformers."
+ return self.physical_line_transforms + \
+ [self.assemble_logical_lines] + self.logical_line_transforms + \
+ [self.assemble_python_lines] + self.python_line_transforms
+
+ @property
+ def transforms_in_use(self):
+ """Transformers, excluding logical line transformers if we're in a
+ Python line."""
+ t = self.physical_line_transforms[:]
+ if not self.within_python_line:
+ t += [self.assemble_logical_lines] + self.logical_line_transforms
+ return t + [self.assemble_python_lines] + self.python_line_transforms
+
+ def reset(self):
+ """Reset the input buffer and associated state."""
+ super(IPythonInputSplitter, self).reset()
+ self._buffer_raw[:] = []
+ self.source_raw = ''
+ self.transformer_accumulating = False
+ self.within_python_line = False
+
+ for t in self.transforms:
+ try:
+ t.reset()
+ except SyntaxError:
+ # Nothing that calls reset() expects to handle transformer
+ # errors
+ pass
+
+ def flush_transformers(self):
+ def _flush(transform, outs):
+ """yield transformed lines
+
+ always strings, never None
+
+ transform: the current transform
+ outs: an iterable of previously transformed inputs.
+ Each may be multiline, which will be passed
+ one line at a time to transform.
+ """
+ for out in outs:
+ for line in out.splitlines():
+ # push one line at a time
+ tmp = transform.push(line)
+ if tmp is not None:
+ yield tmp
+
+ # reset the transform
+ tmp = transform.reset()
+ if tmp is not None:
+ yield tmp
+
+ out = []
+ for t in self.transforms_in_use:
+ out = _flush(t, out)
+
+ out = list(out)
+ if out:
+ self._store('\n'.join(out))
+
+ def raw_reset(self):
+ """Return raw input only and perform a full reset.
+ """
+ out = self.source_raw
+ self.reset()
+ return out
+
+ def source_reset(self):
+ try:
+ self.flush_transformers()
+ return self.source
+ finally:
+ self.reset()
+
+ def push_accepts_more(self):
+ if self.transformer_accumulating:
+ return True
+ else:
+ return super(IPythonInputSplitter, self).push_accepts_more()
+
+ def transform_cell(self, cell):
+ """Process and translate a cell of input.
+ """
+ self.reset()
+ try:
+ self.push(cell)
+ self.flush_transformers()
+ return self.source
+ finally:
+ self.reset()
+
+ def push(self, lines):
+ """Push one or more lines of IPython input.
+
+ This stores the given lines and returns a status code indicating
+ whether the code forms a complete Python block or not, after processing
+ all input lines for special IPython syntax.
+
+ Any exceptions generated in compilation are swallowed, but if an
+ exception was produced, the method returns True.
+
+ Parameters
+ ----------
+ lines : string
+ One or more lines of Python input.
+
+ Returns
+ -------
+ is_complete : boolean
+ True if the current input source (the result of the current input
+ plus prior inputs) forms a complete Python execution block. Note that
+ this value is also stored as a private attribute (_is_complete), so it
+ can be queried at any time.
+ """
+
+ # We must ensure all input is pure unicode
+ lines = cast_unicode(lines, self.encoding)
+ # ''.splitlines() --> [], but we need to push the empty line to transformers
+ lines_list = lines.splitlines()
+ if not lines_list:
+ lines_list = ['']
+
+ # Store raw source before applying any transformations to it. Note
+ # that this must be done *after* the reset() call that would otherwise
+ # flush the buffer.
+ self._store(lines, self._buffer_raw, 'source_raw')
+
+ for line in lines_list:
+ out = self.push_line(line)
+
+ return out
+
+ def push_line(self, line):
+ buf = self._buffer
+
+ def _accumulating(dbg):
+ #print(dbg)
+ self.transformer_accumulating = True
+ return False
+
+ for transformer in self.physical_line_transforms:
+ line = transformer.push(line)
+ if line is None:
+ return _accumulating(transformer)
+
+ if not self.within_python_line:
+ line = self.assemble_logical_lines.push(line)
+ if line is None:
+ return _accumulating('acc logical line')
+
+ for transformer in self.logical_line_transforms:
+ line = transformer.push(line)
+ if line is None:
+ return _accumulating(transformer)
+
+ line = self.assemble_python_lines.push(line)
+ if line is None:
+ self.within_python_line = True
+ return _accumulating('acc python line')
+ else:
+ self.within_python_line = False
+
+ for transformer in self.python_line_transforms:
+ line = transformer.push(line)
+ if line is None:
+ return _accumulating(transformer)
+
+ #print("transformers clear") #debug
+ self.transformer_accumulating = False
+ return super(IPythonInputSplitter, self).push(line)
diff --git a/contrib/python/ipython/py2/IPython/core/inputtransformer.py b/contrib/python/ipython/py2/IPython/core/inputtransformer.py
index a67d93e1a4..3ba49b951d 100644
--- a/contrib/python/ipython/py2/IPython/core/inputtransformer.py
+++ b/contrib/python/ipython/py2/IPython/core/inputtransformer.py
@@ -1,555 +1,555 @@
-"""Input transformer classes to support IPython special syntax.
-
-This includes the machinery to recognise and transform ``%magic`` commands,
-``!system`` commands, ``help?`` querying, prompt stripping, and so forth.
-"""
-import abc
-import functools
-import re
-
-from IPython.core.splitinput import LineInfo
-from IPython.utils import tokenize2
-from IPython.utils.openpy import cookie_comment_re
-from IPython.utils.py3compat import with_metaclass, PY3
-from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError
-
-if PY3:
- from io import StringIO
-else:
- from StringIO import StringIO
-
-#-----------------------------------------------------------------------------
-# Globals
-#-----------------------------------------------------------------------------
-
-# The escape sequences that define the syntax transformations IPython will
-# apply to user input. These can NOT be just changed here: many regular
-# expressions and other parts of the code may use their hardcoded values, and
-# for all intents and purposes they constitute the 'IPython syntax', so they
-# should be considered fixed.
-
-ESC_SHELL = '!' # Send line to underlying system shell
-ESC_SH_CAP = '!!' # Send line to system shell and capture output
-ESC_HELP = '?' # Find information about object
-ESC_HELP2 = '??' # Find extra-detailed information about object
-ESC_MAGIC = '%' # Call magic function
-ESC_MAGIC2 = '%%' # Call cell-magic function
-ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
-ESC_QUOTE2 = ';' # Quote all args as a single string, call
-ESC_PAREN = '/' # Call first argument with rest of line as arguments
-
-ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\
- ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\
- ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]
-
-
-class InputTransformer(with_metaclass(abc.ABCMeta, object)):
- """Abstract base class for line-based input transformers."""
-
- @abc.abstractmethod
- def push(self, line):
- """Send a line of input to the transformer, returning the transformed
- input or None if the transformer is waiting for more input.
-
- Must be overridden by subclasses.
-
- Implementations may raise ``SyntaxError`` if the input is invalid. No
- other exceptions may be raised.
- """
- pass
-
- @abc.abstractmethod
- def reset(self):
- """Return, transformed any lines that the transformer has accumulated,
- and reset its internal state.
-
- Must be overridden by subclasses.
- """
- pass
-
- @classmethod
- def wrap(cls, func):
- """Can be used by subclasses as a decorator, to return a factory that
- will allow instantiation with the decorated object.
- """
- @functools.wraps(func)
- def transformer_factory(**kwargs):
- return cls(func, **kwargs)
-
- return transformer_factory
-
-class StatelessInputTransformer(InputTransformer):
- """Wrapper for a stateless input transformer implemented as a function."""
- def __init__(self, func):
- self.func = func
-
- def __repr__(self):
- return "StatelessInputTransformer(func={0!r})".format(self.func)
-
- def push(self, line):
- """Send a line of input to the transformer, returning the
- transformed input."""
- return self.func(line)
-
- def reset(self):
- """No-op - exists for compatibility."""
- pass
-
-class CoroutineInputTransformer(InputTransformer):
- """Wrapper for an input transformer implemented as a coroutine."""
- def __init__(self, coro, **kwargs):
- # Prime it
- self.coro = coro(**kwargs)
- next(self.coro)
-
- def __repr__(self):
- return "CoroutineInputTransformer(coro={0!r})".format(self.coro)
-
- def push(self, line):
- """Send a line of input to the transformer, returning the
- transformed input or None if the transformer is waiting for more
- input.
- """
- return self.coro.send(line)
-
- def reset(self):
- """Return, transformed any lines that the transformer has
- accumulated, and reset its internal state.
- """
- return self.coro.send(None)
-
-class TokenInputTransformer(InputTransformer):
- """Wrapper for a token-based input transformer.
-
- func should accept a list of tokens (5-tuples, see tokenize docs), and
- return an iterable which can be passed to tokenize.untokenize().
- """
- def __init__(self, func):
- self.func = func
+"""Input transformer classes to support IPython special syntax.
+
+This includes the machinery to recognise and transform ``%magic`` commands,
+``!system`` commands, ``help?`` querying, prompt stripping, and so forth.
+"""
+import abc
+import functools
+import re
+
+from IPython.core.splitinput import LineInfo
+from IPython.utils import tokenize2
+from IPython.utils.openpy import cookie_comment_re
+from IPython.utils.py3compat import with_metaclass, PY3
+from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError
+
+if PY3:
+ from io import StringIO
+else:
+ from StringIO import StringIO
+
+#-----------------------------------------------------------------------------
+# Globals
+#-----------------------------------------------------------------------------
+
+# The escape sequences that define the syntax transformations IPython will
+# apply to user input. These can NOT be just changed here: many regular
+# expressions and other parts of the code may use their hardcoded values, and
+# for all intents and purposes they constitute the 'IPython syntax', so they
+# should be considered fixed.
+
+ESC_SHELL = '!' # Send line to underlying system shell
+ESC_SH_CAP = '!!' # Send line to system shell and capture output
+ESC_HELP = '?' # Find information about object
+ESC_HELP2 = '??' # Find extra-detailed information about object
+ESC_MAGIC = '%' # Call magic function
+ESC_MAGIC2 = '%%' # Call cell-magic function
+ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
+ESC_QUOTE2 = ';' # Quote all args as a single string, call
+ESC_PAREN = '/' # Call first argument with rest of line as arguments
+
+ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\
+ ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\
+ ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]
+
+
+class InputTransformer(with_metaclass(abc.ABCMeta, object)):
+ """Abstract base class for line-based input transformers."""
+
+ @abc.abstractmethod
+ def push(self, line):
+ """Send a line of input to the transformer, returning the transformed
+ input or None if the transformer is waiting for more input.
+
+ Must be overridden by subclasses.
+
+ Implementations may raise ``SyntaxError`` if the input is invalid. No
+ other exceptions may be raised.
+ """
+ pass
+
+ @abc.abstractmethod
+ def reset(self):
+ """Return, transformed any lines that the transformer has accumulated,
+ and reset its internal state.
+
+ Must be overridden by subclasses.
+ """
+ pass
+
+ @classmethod
+ def wrap(cls, func):
+ """Can be used by subclasses as a decorator, to return a factory that
+ will allow instantiation with the decorated object.
+ """
+ @functools.wraps(func)
+ def transformer_factory(**kwargs):
+ return cls(func, **kwargs)
+
+ return transformer_factory
+
+class StatelessInputTransformer(InputTransformer):
+ """Wrapper for a stateless input transformer implemented as a function."""
+ def __init__(self, func):
+ self.func = func
+
+ def __repr__(self):
+ return "StatelessInputTransformer(func={0!r})".format(self.func)
+
+ def push(self, line):
+ """Send a line of input to the transformer, returning the
+ transformed input."""
+ return self.func(line)
+
+ def reset(self):
+ """No-op - exists for compatibility."""
+ pass
+
+class CoroutineInputTransformer(InputTransformer):
+ """Wrapper for an input transformer implemented as a coroutine."""
+ def __init__(self, coro, **kwargs):
+ # Prime it
+ self.coro = coro(**kwargs)
+ next(self.coro)
+
+ def __repr__(self):
+ return "CoroutineInputTransformer(coro={0!r})".format(self.coro)
+
+ def push(self, line):
+ """Send a line of input to the transformer, returning the
+ transformed input or None if the transformer is waiting for more
+ input.
+ """
+ return self.coro.send(line)
+
+ def reset(self):
+ """Return, transformed any lines that the transformer has
+ accumulated, and reset its internal state.
+ """
+ return self.coro.send(None)
+
+class TokenInputTransformer(InputTransformer):
+ """Wrapper for a token-based input transformer.
+
+ func should accept a list of tokens (5-tuples, see tokenize docs), and
+ return an iterable which can be passed to tokenize.untokenize().
+ """
+ def __init__(self, func):
+ self.func = func
self.buf = []
- self.reset_tokenizer()
+ self.reset_tokenizer()
- def reset_tokenizer(self):
+ def reset_tokenizer(self):
it = iter(self.buf)
nxt = it.__next__ if PY3 else it.next
self.tokenizer = generate_tokens(nxt)
- def push(self, line):
+ def push(self, line):
self.buf.append(line + '\n')
if all(l.isspace() for l in self.buf):
- return self.reset()
-
- tokens = []
- stop_at_NL = False
- try:
- for intok in self.tokenizer:
- tokens.append(intok)
- t = intok[0]
- if t == tokenize2.NEWLINE or (stop_at_NL and t == tokenize2.NL):
- # Stop before we try to pull a line we don't have yet
- break
- elif t == tokenize2.ERRORTOKEN:
- stop_at_NL = True
- except TokenError:
- # Multi-line statement - stop and try again with the next line
- self.reset_tokenizer()
- return None
-
- return self.output(tokens)
-
- def output(self, tokens):
+ return self.reset()
+
+ tokens = []
+ stop_at_NL = False
+ try:
+ for intok in self.tokenizer:
+ tokens.append(intok)
+ t = intok[0]
+ if t == tokenize2.NEWLINE or (stop_at_NL and t == tokenize2.NL):
+ # Stop before we try to pull a line we don't have yet
+ break
+ elif t == tokenize2.ERRORTOKEN:
+ stop_at_NL = True
+ except TokenError:
+ # Multi-line statement - stop and try again with the next line
+ self.reset_tokenizer()
+ return None
+
+ return self.output(tokens)
+
+ def output(self, tokens):
self.buf[:] = []
- self.reset_tokenizer()
- return untokenize(self.func(tokens)).rstrip('\n')
-
- def reset(self):
+ self.reset_tokenizer()
+ return untokenize(self.func(tokens)).rstrip('\n')
+
+ def reset(self):
l = ''.join(self.buf)
self.buf[:] = []
- self.reset_tokenizer()
- if l:
- return l.rstrip('\n')
-
-class assemble_python_lines(TokenInputTransformer):
- def __init__(self):
- super(assemble_python_lines, self).__init__(None)
-
- def output(self, tokens):
- return self.reset()
-
-@CoroutineInputTransformer.wrap
-def assemble_logical_lines():
- """Join lines following explicit line continuations (\)"""
- line = ''
- while True:
- line = (yield line)
- if not line or line.isspace():
- continue
-
- parts = []
- while line is not None:
- if line.endswith('\\') and (not has_comment(line)):
- parts.append(line[:-1])
- line = (yield None) # Get another line
- else:
- parts.append(line)
- break
-
- # Output
- line = ''.join(parts)
-
-# Utilities
-def _make_help_call(target, esc, lspace, next_input=None):
- """Prepares a pinfo(2)/psearch call from a target name and the escape
- (i.e. ? or ??)"""
- method = 'pinfo2' if esc == '??' \
- else 'psearch' if '*' in target \
- else 'pinfo'
- arg = " ".join([method, target])
- if next_input is None:
- return '%sget_ipython().magic(%r)' % (lspace, arg)
- else:
- return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \
- (lspace, next_input, arg)
-
-# These define the transformations for the different escape characters.
-def _tr_system(line_info):
- "Translate lines escaped with: !"
- cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
- return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
-
-def _tr_system2(line_info):
- "Translate lines escaped with: !!"
- cmd = line_info.line.lstrip()[2:]
- return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
-
-def _tr_help(line_info):
- "Translate lines escaped with: ?/??"
- # A naked help line should just fire the intro help screen
- if not line_info.line[1:]:
- return 'get_ipython().show_usage()'
-
- return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
-
-def _tr_magic(line_info):
- "Translate lines escaped with: %"
- tpl = '%sget_ipython().magic(%r)'
- if line_info.line.startswith(ESC_MAGIC2):
- return line_info.line
- cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip()
- return tpl % (line_info.pre, cmd)
-
-def _tr_quote(line_info):
- "Translate lines escaped with: ,"
- return '%s%s("%s")' % (line_info.pre, line_info.ifun,
- '", "'.join(line_info.the_rest.split()) )
-
-def _tr_quote2(line_info):
- "Translate lines escaped with: ;"
- return '%s%s("%s")' % (line_info.pre, line_info.ifun,
- line_info.the_rest)
-
-def _tr_paren(line_info):
- "Translate lines escaped with: /"
- return '%s%s(%s)' % (line_info.pre, line_info.ifun,
- ", ".join(line_info.the_rest.split()))
-
-tr = { ESC_SHELL : _tr_system,
- ESC_SH_CAP : _tr_system2,
- ESC_HELP : _tr_help,
- ESC_HELP2 : _tr_help,
- ESC_MAGIC : _tr_magic,
- ESC_QUOTE : _tr_quote,
- ESC_QUOTE2 : _tr_quote2,
- ESC_PAREN : _tr_paren }
-
-@StatelessInputTransformer.wrap
-def escaped_commands(line):
- """Transform escaped commands - %magic, !system, ?help + various autocalls.
- """
- if not line or line.isspace():
- return line
- lineinf = LineInfo(line)
- if lineinf.esc not in tr:
- return line
-
- return tr[lineinf.esc](lineinf)
-
-_initial_space_re = re.compile(r'\s*')
-
-_help_end_re = re.compile(r"""(%{0,2}
- [a-zA-Z_*][\w*]* # Variable name
- (\.[a-zA-Z_*][\w*]*)* # .etc.etc
- )
- (\?\??)$ # ? or ??
- """,
- re.VERBOSE)
-
-# Extra pseudotokens for multiline strings and data structures
-_MULTILINE_STRING = object()
-_MULTILINE_STRUCTURE = object()
-
-def _line_tokens(line):
- """Helper for has_comment and ends_in_comment_or_string."""
- readline = StringIO(line).readline
- toktypes = set()
- try:
- for t in generate_tokens(readline):
- toktypes.add(t[0])
- except TokenError as e:
- # There are only two cases where a TokenError is raised.
- if 'multi-line string' in e.args[0]:
- toktypes.add(_MULTILINE_STRING)
- else:
- toktypes.add(_MULTILINE_STRUCTURE)
- return toktypes
-
-def has_comment(src):
- """Indicate whether an input line has (i.e. ends in, or is) a comment.
-
- This uses tokenize, so it can distinguish comments from # inside strings.
-
- Parameters
- ----------
- src : string
- A single line input string.
-
- Returns
- -------
- comment : bool
- True if source has a comment.
- """
- return (tokenize2.COMMENT in _line_tokens(src))
-
-def ends_in_comment_or_string(src):
- """Indicates whether or not an input line ends in a comment or within
- a multiline string.
-
- Parameters
- ----------
- src : string
- A single line input string.
-
- Returns
- -------
- comment : bool
- True if source ends in a comment or multiline string.
- """
- toktypes = _line_tokens(src)
- return (tokenize2.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes)
-
-
-@StatelessInputTransformer.wrap
-def help_end(line):
- """Translate lines with ?/?? at the end"""
- m = _help_end_re.search(line)
- if m is None or ends_in_comment_or_string(line):
- return line
- target = m.group(1)
- esc = m.group(3)
- lspace = _initial_space_re.match(line).group(0)
-
- # If we're mid-command, put it back on the next prompt for the user.
- next_input = line.rstrip('?') if line.strip() != m.group(0) else None
-
- return _make_help_call(target, esc, lspace, next_input)
-
-
-@CoroutineInputTransformer.wrap
-def cellmagic(end_on_blank_line=False):
- """Captures & transforms cell magics.
-
- After a cell magic is started, this stores up any lines it gets until it is
- reset (sent None).
- """
- tpl = 'get_ipython().run_cell_magic(%r, %r, %r)'
- cellmagic_help_re = re.compile('%%\w+\?')
- line = ''
- while True:
- line = (yield line)
- # consume leading empty lines
- while not line:
- line = (yield line)
-
- if not line.startswith(ESC_MAGIC2):
- # This isn't a cell magic, idle waiting for reset then start over
- while line is not None:
- line = (yield line)
- continue
-
- if cellmagic_help_re.match(line):
- # This case will be handled by help_end
- continue
-
- first = line
- body = []
- line = (yield None)
- while (line is not None) and \
- ((line.strip() != '') or not end_on_blank_line):
- body.append(line)
- line = (yield None)
-
- # Output
- magic_name, _, first = first.partition(' ')
- magic_name = magic_name.lstrip(ESC_MAGIC2)
- line = tpl % (magic_name, first, u'\n'.join(body))
-
-
-def _strip_prompts(prompt_re, initial_re=None, turnoff_re=None):
- """Remove matching input prompts from a block of input.
-
- Parameters
- ----------
- prompt_re : regular expression
- A regular expression matching any input prompt (including continuation)
- initial_re : regular expression, optional
- A regular expression matching only the initial prompt, but not continuation.
- If no initial expression is given, prompt_re will be used everywhere.
- Used mainly for plain Python prompts, where the continuation prompt
- ``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
-
- If initial_re and prompt_re differ,
- only initial_re will be tested against the first line.
- If any prompt is found on the first two lines,
- prompts will be stripped from the rest of the block.
- """
- if initial_re is None:
- initial_re = prompt_re
- line = ''
- while True:
- line = (yield line)
-
- # First line of cell
- if line is None:
- continue
- out, n1 = initial_re.subn('', line, count=1)
- if turnoff_re and not n1:
- if turnoff_re.match(line):
- # We're in e.g. a cell magic; disable this transformer for
- # the rest of the cell.
- while line is not None:
- line = (yield line)
- continue
-
- line = (yield out)
-
- if line is None:
- continue
- # check for any prompt on the second line of the cell,
- # because people often copy from just after the first prompt,
- # so we might not see it in the first line.
- out, n2 = prompt_re.subn('', line, count=1)
- line = (yield out)
-
- if n1 or n2:
- # Found a prompt in the first two lines - check for it in
- # the rest of the cell as well.
- while line is not None:
- line = (yield prompt_re.sub('', line, count=1))
-
- else:
- # Prompts not in input - wait for reset
- while line is not None:
- line = (yield line)
-
-@CoroutineInputTransformer.wrap
-def classic_prompt():
- """Strip the >>>/... prompts of the Python interactive shell."""
- # FIXME: non-capturing version (?:...) usable?
- prompt_re = re.compile(r'^(>>>|\.\.\.)( |$)')
- initial_re = re.compile(r'^>>>( |$)')
- # Any %magic/!system is IPython syntax, so we needn't look for >>> prompts
- turnoff_re = re.compile(r'^[%!]')
- return _strip_prompts(prompt_re, initial_re, turnoff_re)
-
-@CoroutineInputTransformer.wrap
-def ipy_prompt():
- """Strip IPython's In [1]:/...: prompts."""
- # FIXME: non-capturing version (?:...) usable?
- prompt_re = re.compile(r'^(In \[\d+\]: |\s*\.{3,}: ?)')
- # Disable prompt stripping inside cell magics
- turnoff_re = re.compile(r'^%%')
- return _strip_prompts(prompt_re, turnoff_re=turnoff_re)
-
-
-@CoroutineInputTransformer.wrap
-def leading_indent():
- """Remove leading indentation.
-
- If the first line starts with a spaces or tabs, the same whitespace will be
- removed from each following line until it is reset.
- """
- space_re = re.compile(r'^[ \t]+')
- line = ''
- while True:
- line = (yield line)
-
- if line is None:
- continue
-
- m = space_re.match(line)
- if m:
- space = m.group(0)
- while line is not None:
- if line.startswith(space):
- line = line[len(space):]
- line = (yield line)
- else:
- # No leading spaces - wait for reset
- while line is not None:
- line = (yield line)
-
-
-@CoroutineInputTransformer.wrap
-def strip_encoding_cookie():
- """Remove encoding comment if found in first two lines
-
- If the first or second line has the `# coding: utf-8` comment,
- it will be removed.
- """
- line = ''
- while True:
- line = (yield line)
- # check comment on first two lines
- for i in range(2):
- if line is None:
- break
- if cookie_comment_re.match(line):
- line = (yield "")
- else:
- line = (yield line)
-
- # no-op on the rest of the cell
- while line is not None:
- line = (yield line)
-
-_assign_pat = \
-r'''(?P<lhs>(\s*)
- ([\w\.]+) # Initial identifier
- (\s*,\s*
- \*?[\w\.]+)* # Further identifiers for unpacking
- \s*?,? # Trailing comma
- )
- \s*=\s*
-'''
-
-assign_system_re = re.compile(r'{}!\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
-assign_system_template = '%s = get_ipython().getoutput(%r)'
-@StatelessInputTransformer.wrap
-def assign_from_system(line):
- """Transform assignment from system commands (e.g. files = !ls)"""
- m = assign_system_re.match(line)
- if m is None:
- return line
-
- return assign_system_template % m.group('lhs', 'cmd')
-
-assign_magic_re = re.compile(r'{}%\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
-assign_magic_template = '%s = get_ipython().magic(%r)'
-@StatelessInputTransformer.wrap
-def assign_from_magic(line):
- """Transform assignment from magic commands (e.g. a = %who_ls)"""
- m = assign_magic_re.match(line)
- if m is None:
- return line
-
- return assign_magic_template % m.group('lhs', 'cmd')
+ self.reset_tokenizer()
+ if l:
+ return l.rstrip('\n')
+
+class assemble_python_lines(TokenInputTransformer):
+ def __init__(self):
+ super(assemble_python_lines, self).__init__(None)
+
+ def output(self, tokens):
+ return self.reset()
+
+@CoroutineInputTransformer.wrap
+def assemble_logical_lines():
+ """Join lines following explicit line continuations (\)"""
+ line = ''
+ while True:
+ line = (yield line)
+ if not line or line.isspace():
+ continue
+
+ parts = []
+ while line is not None:
+ if line.endswith('\\') and (not has_comment(line)):
+ parts.append(line[:-1])
+ line = (yield None) # Get another line
+ else:
+ parts.append(line)
+ break
+
+ # Output
+ line = ''.join(parts)
+
+# Utilities
+def _make_help_call(target, esc, lspace, next_input=None):
+ """Prepares a pinfo(2)/psearch call from a target name and the escape
+ (i.e. ? or ??)"""
+ method = 'pinfo2' if esc == '??' \
+ else 'psearch' if '*' in target \
+ else 'pinfo'
+ arg = " ".join([method, target])
+ if next_input is None:
+ return '%sget_ipython().magic(%r)' % (lspace, arg)
+ else:
+ return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \
+ (lspace, next_input, arg)
+
+# These define the transformations for the different escape characters.
+def _tr_system(line_info):
+ "Translate lines escaped with: !"
+ cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
+ return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
+
+def _tr_system2(line_info):
+ "Translate lines escaped with: !!"
+ cmd = line_info.line.lstrip()[2:]
+ return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
+
+def _tr_help(line_info):
+ "Translate lines escaped with: ?/??"
+ # A naked help line should just fire the intro help screen
+ if not line_info.line[1:]:
+ return 'get_ipython().show_usage()'
+
+ return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
+
+def _tr_magic(line_info):
+ "Translate lines escaped with: %"
+ tpl = '%sget_ipython().magic(%r)'
+ if line_info.line.startswith(ESC_MAGIC2):
+ return line_info.line
+ cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip()
+ return tpl % (line_info.pre, cmd)
+
+def _tr_quote(line_info):
+ "Translate lines escaped with: ,"
+ return '%s%s("%s")' % (line_info.pre, line_info.ifun,
+ '", "'.join(line_info.the_rest.split()) )
+
+def _tr_quote2(line_info):
+ "Translate lines escaped with: ;"
+ return '%s%s("%s")' % (line_info.pre, line_info.ifun,
+ line_info.the_rest)
+
+def _tr_paren(line_info):
+ "Translate lines escaped with: /"
+ return '%s%s(%s)' % (line_info.pre, line_info.ifun,
+ ", ".join(line_info.the_rest.split()))
+
+tr = { ESC_SHELL : _tr_system,
+ ESC_SH_CAP : _tr_system2,
+ ESC_HELP : _tr_help,
+ ESC_HELP2 : _tr_help,
+ ESC_MAGIC : _tr_magic,
+ ESC_QUOTE : _tr_quote,
+ ESC_QUOTE2 : _tr_quote2,
+ ESC_PAREN : _tr_paren }
+
+@StatelessInputTransformer.wrap
+def escaped_commands(line):
+ """Transform escaped commands - %magic, !system, ?help + various autocalls.
+ """
+ if not line or line.isspace():
+ return line
+ lineinf = LineInfo(line)
+ if lineinf.esc not in tr:
+ return line
+
+ return tr[lineinf.esc](lineinf)
+
+_initial_space_re = re.compile(r'\s*')
+
+_help_end_re = re.compile(r"""(%{0,2}
+ [a-zA-Z_*][\w*]* # Variable name
+ (\.[a-zA-Z_*][\w*]*)* # .etc.etc
+ )
+ (\?\??)$ # ? or ??
+ """,
+ re.VERBOSE)
+
+# Extra pseudotokens for multiline strings and data structures
+_MULTILINE_STRING = object()
+_MULTILINE_STRUCTURE = object()
+
+def _line_tokens(line):
+ """Helper for has_comment and ends_in_comment_or_string."""
+ readline = StringIO(line).readline
+ toktypes = set()
+ try:
+ for t in generate_tokens(readline):
+ toktypes.add(t[0])
+ except TokenError as e:
+ # There are only two cases where a TokenError is raised.
+ if 'multi-line string' in e.args[0]:
+ toktypes.add(_MULTILINE_STRING)
+ else:
+ toktypes.add(_MULTILINE_STRUCTURE)
+ return toktypes
+
+def has_comment(src):
+ """Indicate whether an input line has (i.e. ends in, or is) a comment.
+
+ This uses tokenize, so it can distinguish comments from # inside strings.
+
+ Parameters
+ ----------
+ src : string
+ A single line input string.
+
+ Returns
+ -------
+ comment : bool
+ True if source has a comment.
+ """
+ return (tokenize2.COMMENT in _line_tokens(src))
+
+def ends_in_comment_or_string(src):
+ """Indicates whether or not an input line ends in a comment or within
+ a multiline string.
+
+ Parameters
+ ----------
+ src : string
+ A single line input string.
+
+ Returns
+ -------
+ comment : bool
+ True if source ends in a comment or multiline string.
+ """
+ toktypes = _line_tokens(src)
+ return (tokenize2.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes)
+
+
+@StatelessInputTransformer.wrap
+def help_end(line):
+ """Translate lines with ?/?? at the end"""
+ m = _help_end_re.search(line)
+ if m is None or ends_in_comment_or_string(line):
+ return line
+ target = m.group(1)
+ esc = m.group(3)
+ lspace = _initial_space_re.match(line).group(0)
+
+ # If we're mid-command, put it back on the next prompt for the user.
+ next_input = line.rstrip('?') if line.strip() != m.group(0) else None
+
+ return _make_help_call(target, esc, lspace, next_input)
+
+
+@CoroutineInputTransformer.wrap
+def cellmagic(end_on_blank_line=False):
+ """Captures & transforms cell magics.
+
+ After a cell magic is started, this stores up any lines it gets until it is
+ reset (sent None).
+ """
+ tpl = 'get_ipython().run_cell_magic(%r, %r, %r)'
+ cellmagic_help_re = re.compile('%%\w+\?')
+ line = ''
+ while True:
+ line = (yield line)
+ # consume leading empty lines
+ while not line:
+ line = (yield line)
+
+ if not line.startswith(ESC_MAGIC2):
+ # This isn't a cell magic, idle waiting for reset then start over
+ while line is not None:
+ line = (yield line)
+ continue
+
+ if cellmagic_help_re.match(line):
+ # This case will be handled by help_end
+ continue
+
+ first = line
+ body = []
+ line = (yield None)
+ while (line is not None) and \
+ ((line.strip() != '') or not end_on_blank_line):
+ body.append(line)
+ line = (yield None)
+
+ # Output
+ magic_name, _, first = first.partition(' ')
+ magic_name = magic_name.lstrip(ESC_MAGIC2)
+ line = tpl % (magic_name, first, u'\n'.join(body))
+
+
+def _strip_prompts(prompt_re, initial_re=None, turnoff_re=None):
+ """Remove matching input prompts from a block of input.
+
+ Parameters
+ ----------
+ prompt_re : regular expression
+ A regular expression matching any input prompt (including continuation)
+ initial_re : regular expression, optional
+ A regular expression matching only the initial prompt, but not continuation.
+ If no initial expression is given, prompt_re will be used everywhere.
+ Used mainly for plain Python prompts, where the continuation prompt
+ ``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
+
+ If initial_re and prompt_re differ,
+ only initial_re will be tested against the first line.
+ If any prompt is found on the first two lines,
+ prompts will be stripped from the rest of the block.
+ """
+ if initial_re is None:
+ initial_re = prompt_re
+ line = ''
+ while True:
+ line = (yield line)
+
+ # First line of cell
+ if line is None:
+ continue
+ out, n1 = initial_re.subn('', line, count=1)
+ if turnoff_re and not n1:
+ if turnoff_re.match(line):
+ # We're in e.g. a cell magic; disable this transformer for
+ # the rest of the cell.
+ while line is not None:
+ line = (yield line)
+ continue
+
+ line = (yield out)
+
+ if line is None:
+ continue
+ # check for any prompt on the second line of the cell,
+ # because people often copy from just after the first prompt,
+ # so we might not see it in the first line.
+ out, n2 = prompt_re.subn('', line, count=1)
+ line = (yield out)
+
+ if n1 or n2:
+ # Found a prompt in the first two lines - check for it in
+ # the rest of the cell as well.
+ while line is not None:
+ line = (yield prompt_re.sub('', line, count=1))
+
+ else:
+ # Prompts not in input - wait for reset
+ while line is not None:
+ line = (yield line)
+
+@CoroutineInputTransformer.wrap
+def classic_prompt():
+ """Strip the >>>/... prompts of the Python interactive shell."""
+ # FIXME: non-capturing version (?:...) usable?
+ prompt_re = re.compile(r'^(>>>|\.\.\.)( |$)')
+ initial_re = re.compile(r'^>>>( |$)')
+ # Any %magic/!system is IPython syntax, so we needn't look for >>> prompts
+ turnoff_re = re.compile(r'^[%!]')
+ return _strip_prompts(prompt_re, initial_re, turnoff_re)
+
+@CoroutineInputTransformer.wrap
+def ipy_prompt():
+ """Strip IPython's In [1]:/...: prompts."""
+ # FIXME: non-capturing version (?:...) usable?
+ prompt_re = re.compile(r'^(In \[\d+\]: |\s*\.{3,}: ?)')
+ # Disable prompt stripping inside cell magics
+ turnoff_re = re.compile(r'^%%')
+ return _strip_prompts(prompt_re, turnoff_re=turnoff_re)
+
+
+@CoroutineInputTransformer.wrap
+def leading_indent():
+ """Remove leading indentation.
+
+ If the first line starts with a spaces or tabs, the same whitespace will be
+ removed from each following line until it is reset.
+ """
+ space_re = re.compile(r'^[ \t]+')
+ line = ''
+ while True:
+ line = (yield line)
+
+ if line is None:
+ continue
+
+ m = space_re.match(line)
+ if m:
+ space = m.group(0)
+ while line is not None:
+ if line.startswith(space):
+ line = line[len(space):]
+ line = (yield line)
+ else:
+ # No leading spaces - wait for reset
+ while line is not None:
+ line = (yield line)
+
+
+@CoroutineInputTransformer.wrap
+def strip_encoding_cookie():
+ """Remove encoding comment if found in first two lines
+
+ If the first or second line has the `# coding: utf-8` comment,
+ it will be removed.
+ """
+ line = ''
+ while True:
+ line = (yield line)
+ # check comment on first two lines
+ for i in range(2):
+ if line is None:
+ break
+ if cookie_comment_re.match(line):
+ line = (yield "")
+ else:
+ line = (yield line)
+
+ # no-op on the rest of the cell
+ while line is not None:
+ line = (yield line)
+
+_assign_pat = \
+r'''(?P<lhs>(\s*)
+ ([\w\.]+) # Initial identifier
+ (\s*,\s*
+ \*?[\w\.]+)* # Further identifiers for unpacking
+ \s*?,? # Trailing comma
+ )
+ \s*=\s*
+'''
+
+assign_system_re = re.compile(r'{}!\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
+assign_system_template = '%s = get_ipython().getoutput(%r)'
+@StatelessInputTransformer.wrap
+def assign_from_system(line):
+ """Transform assignment from system commands (e.g. files = !ls)"""
+ m = assign_system_re.match(line)
+ if m is None:
+ return line
+
+ return assign_system_template % m.group('lhs', 'cmd')
+
+assign_magic_re = re.compile(r'{}%\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
+assign_magic_template = '%s = get_ipython().magic(%r)'
+@StatelessInputTransformer.wrap
+def assign_from_magic(line):
+ """Transform assignment from magic commands (e.g. a = %who_ls)"""
+ m = assign_magic_re.match(line)
+ if m is None:
+ return line
+
+ return assign_magic_template % m.group('lhs', 'cmd')
diff --git a/contrib/python/ipython/py2/IPython/core/interactiveshell.py b/contrib/python/ipython/py2/IPython/core/interactiveshell.py
index ba96cb0676..ad8824b606 100644
--- a/contrib/python/ipython/py2/IPython/core/interactiveshell.py
+++ b/contrib/python/ipython/py2/IPython/core/interactiveshell.py
@@ -1,78 +1,78 @@
-# -*- coding: utf-8 -*-
-"""Main IPython class."""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
-# Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-from __future__ import absolute_import, print_function
-
-import __future__
-import abc
-import ast
-import atexit
-import functools
-import os
-import re
-import runpy
-import sys
-import tempfile
-import traceback
-import types
-import subprocess
-import warnings
-from io import open as io_open
-
-from pickleshare import PickleShareDB
-
-from traitlets.config.configurable import SingletonConfigurable
+# -*- coding: utf-8 -*-
+"""Main IPython class."""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
+# Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+from __future__ import absolute_import, print_function
+
+import __future__
+import abc
+import ast
+import atexit
+import functools
+import os
+import re
+import runpy
+import sys
+import tempfile
+import traceback
+import types
+import subprocess
+import warnings
+from io import open as io_open
+
+from pickleshare import PickleShareDB
+
+from traitlets.config.configurable import SingletonConfigurable
from IPython.core import oinspect
-from IPython.core import magic
-from IPython.core import page
-from IPython.core import prefilter
-from IPython.core import shadowns
-from IPython.core import ultratb
-from IPython.core.alias import Alias, AliasManager
-from IPython.core.autocall import ExitAutocall
-from IPython.core.builtin_trap import BuiltinTrap
-from IPython.core.events import EventManager, available_events
-from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
+from IPython.core import magic
+from IPython.core import page
+from IPython.core import prefilter
+from IPython.core import shadowns
+from IPython.core import ultratb
+from IPython.core.alias import Alias, AliasManager
+from IPython.core.autocall import ExitAutocall
+from IPython.core.builtin_trap import BuiltinTrap
+from IPython.core.events import EventManager, available_events
+from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
from IPython.core.debugger import Pdb
-from IPython.core.display_trap import DisplayTrap
-from IPython.core.displayhook import DisplayHook
-from IPython.core.displaypub import DisplayPublisher
-from IPython.core.error import InputRejected, UsageError
-from IPython.core.extensions import ExtensionManager
-from IPython.core.formatters import DisplayFormatter
-from IPython.core.history import HistoryManager
+from IPython.core.display_trap import DisplayTrap
+from IPython.core.displayhook import DisplayHook
+from IPython.core.displaypub import DisplayPublisher
+from IPython.core.error import InputRejected, UsageError
+from IPython.core.extensions import ExtensionManager
+from IPython.core.formatters import DisplayFormatter
+from IPython.core.history import HistoryManager
from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
-from IPython.core.logger import Logger
-from IPython.core.macro import Macro
-from IPython.core.payload import PayloadManager
-from IPython.core.prefilter import PrefilterManager
-from IPython.core.profiledir import ProfileDir
-from IPython.core.usage import default_banner
+from IPython.core.logger import Logger
+from IPython.core.macro import Macro
+from IPython.core.payload import PayloadManager
+from IPython.core.prefilter import PrefilterManager
+from IPython.core.profiledir import ProfileDir
+from IPython.core.usage import default_banner
from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
from IPython.display import display
-from IPython.utils import PyColorize
-from IPython.utils import io
-from IPython.utils import py3compat
-from IPython.utils import openpy
-from IPython.utils.decorators import undoc
-from IPython.utils.io import ask_yes_no
-from IPython.utils.ipstruct import Struct
-from IPython.paths import get_ipython_dir
+from IPython.utils import PyColorize
+from IPython.utils import io
+from IPython.utils import py3compat
+from IPython.utils import openpy
+from IPython.utils.decorators import undoc
+from IPython.utils.io import ask_yes_no
+from IPython.utils.ipstruct import Struct
+from IPython.paths import get_ipython_dir
from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
-from IPython.utils.process import system, getoutput
-from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
- with_metaclass, iteritems)
-from IPython.utils.strdispatch import StrDispatch
-from IPython.utils.syspathcontext import prepended_to_syspath
+from IPython.utils.process import system, getoutput
+from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
+ with_metaclass, iteritems)
+from IPython.utils.strdispatch import StrDispatch
+from IPython.utils.syspathcontext import prepended_to_syspath
from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
from IPython.utils.tempdir import TemporaryDirectory
from traitlets import (
@@ -81,8 +81,8 @@ from traitlets import (
)
from warnings import warn
from logging import error
-import IPython.core.hooks
-
+import IPython.core.hooks
+
# NoOpContext is deprecated, but ipykernel imports it from here.
# See https://github.com/ipython/ipykernel/issues/157
from IPython.utils.contexts import NoOpContext
@@ -106,87 +106,87 @@ class ProvisionalWarning(DeprecationWarning):
"""
pass
-#-----------------------------------------------------------------------------
-# Globals
-#-----------------------------------------------------------------------------
-
-# compiled regexps for autoindent management
-dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
-
-#-----------------------------------------------------------------------------
-# Utilities
-#-----------------------------------------------------------------------------
-
-@undoc
-def softspace(file, newvalue):
- """Copied from code.py, to remove the dependency"""
-
- oldvalue = 0
- try:
- oldvalue = file.softspace
- except AttributeError:
- pass
- try:
- file.softspace = newvalue
- except (AttributeError, TypeError):
- # "attribute-less object" or "read-only attributes"
- pass
- return oldvalue
-
-@undoc
-def no_op(*a, **kw): pass
-
-
-class SpaceInInput(Exception): pass
-
-
-def get_default_colors():
+#-----------------------------------------------------------------------------
+# Globals
+#-----------------------------------------------------------------------------
+
+# compiled regexps for autoindent management
+dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
+
+#-----------------------------------------------------------------------------
+# Utilities
+#-----------------------------------------------------------------------------
+
+@undoc
+def softspace(file, newvalue):
+ """Copied from code.py, to remove the dependency"""
+
+ oldvalue = 0
+ try:
+ oldvalue = file.softspace
+ except AttributeError:
+ pass
+ try:
+ file.softspace = newvalue
+ except (AttributeError, TypeError):
+ # "attribute-less object" or "read-only attributes"
+ pass
+ return oldvalue
+
+@undoc
+def no_op(*a, **kw): pass
+
+
+class SpaceInInput(Exception): pass
+
+
+def get_default_colors():
"DEPRECATED"
warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
DeprecationWarning, stacklevel=2)
return 'Neutral'
-
-
-class SeparateUnicode(Unicode):
- r"""A Unicode subclass to validate separate_in, separate_out, etc.
-
- This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
- """
-
- def validate(self, obj, value):
- if value == '0': value = ''
- value = value.replace('\\n','\n')
- return super(SeparateUnicode, self).validate(obj, value)
-
-
-@undoc
-class DummyMod(object):
- """A dummy module used for IPython's interactive module when
- a namespace must be assigned to the module's __dict__."""
- pass
-
-
-class ExecutionResult(object):
- """The result of a call to :meth:`InteractiveShell.run_cell`
-
- Stores information about what took place.
- """
- execution_count = None
- error_before_exec = None
- error_in_exec = None
- result = None
-
- @property
- def success(self):
- return (self.error_before_exec is None) and (self.error_in_exec is None)
-
- def raise_error(self):
- """Reraises error if `success` is `False`, otherwise does nothing"""
- if self.error_before_exec is not None:
- raise self.error_before_exec
- if self.error_in_exec is not None:
- raise self.error_in_exec
-
+
+
+class SeparateUnicode(Unicode):
+ r"""A Unicode subclass to validate separate_in, separate_out, etc.
+
+ This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
+ """
+
+ def validate(self, obj, value):
+ if value == '0': value = ''
+ value = value.replace('\\n','\n')
+ return super(SeparateUnicode, self).validate(obj, value)
+
+
+@undoc
+class DummyMod(object):
+ """A dummy module used for IPython's interactive module when
+ a namespace must be assigned to the module's __dict__."""
+ pass
+
+
+class ExecutionResult(object):
+ """The result of a call to :meth:`InteractiveShell.run_cell`
+
+ Stores information about what took place.
+ """
+ execution_count = None
+ error_before_exec = None
+ error_in_exec = None
+ result = None
+
+ @property
+ def success(self):
+ return (self.error_before_exec is None) and (self.error_in_exec is None)
+
+ def raise_error(self):
+ """Reraises error if `success` is `False`, otherwise does nothing"""
+ if self.error_before_exec is not None:
+ raise self.error_before_exec
+ if self.error_in_exec is not None:
+ raise self.error_in_exec
+
def __repr__(self):
if sys.version_info > (3,):
name = self.__class__.__qualname__
@@ -194,67 +194,67 @@ class ExecutionResult(object):
name = self.__class__.__name__
return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
(name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
-
-class InteractiveShell(SingletonConfigurable):
- """An enhanced, interactive shell for Python."""
-
- _instance = None
+
+class InteractiveShell(SingletonConfigurable):
+ """An enhanced, interactive shell for Python."""
+
+ _instance = None
ast_transformers = List([], help=
- """
- A list of ast.NodeTransformer subclass instances, which will be applied
- to user input before code is run.
- """
+ """
+ A list of ast.NodeTransformer subclass instances, which will be applied
+ to user input before code is run.
+ """
).tag(config=True)
-
+
autocall = Enum((0,1,2), default_value=0, help=
- """
- Make IPython automatically call any callable object even if you didn't
- type explicit parentheses. For example, 'str 43' becomes 'str(43)'
- automatically. The value can be '0' to disable the feature, '1' for
- 'smart' autocall, where it is not applied if there are no more
- arguments on the line, and '2' for 'full' autocall, where all callable
- objects are automatically called (even if no arguments are present).
- """
+ """
+ Make IPython automatically call any callable object even if you didn't
+ type explicit parentheses. For example, 'str 43' becomes 'str(43)'
+ automatically. The value can be '0' to disable the feature, '1' for
+ 'smart' autocall, where it is not applied if there are no more
+ arguments on the line, and '2' for 'full' autocall, where all callable
+ objects are automatically called (even if no arguments are present).
+ """
).tag(config=True)
- # TODO: remove all autoindent logic and put into frontends.
- # We can't do this yet because even runlines uses the autoindent.
+ # TODO: remove all autoindent logic and put into frontends.
+ # We can't do this yet because even runlines uses the autoindent.
autoindent = Bool(True, help=
- """
- Autoindent IPython code entered interactively.
- """
+ """
+ Autoindent IPython code entered interactively.
+ """
).tag(config=True)
automagic = Bool(True, help=
- """
- Enable magic commands to be called without the leading %.
- """
+ """
+ Enable magic commands to be called without the leading %.
+ """
).tag(config=True)
banner1 = Unicode(default_banner,
- help="""The part of the banner to be printed before the profile"""
+ help="""The part of the banner to be printed before the profile"""
).tag(config=True)
banner2 = Unicode('',
- help="""The part of the banner to be printed after the profile"""
+ help="""The part of the banner to be printed after the profile"""
).tag(config=True)
-
+
cache_size = Integer(1000, help=
- """
- Set the size of the output cache. The default is 1000, you can
- change it permanently in your config file. Setting it to 0 completely
- disables the caching system, and the minimum value accepted is 20 (if
- you provide a value less than 20, it is reset to 0 and a warning is
- issued). This limit is defined because otherwise you'll spend more
- time re-flushing a too small cache than working
- """
+ """
+ Set the size of the output cache. The default is 1000, you can
+ change it permanently in your config file. Setting it to 0 completely
+ disables the caching system, and the minimum value accepted is 20 (if
+ you provide a value less than 20, it is reset to 0 and a warning is
+ issued). This limit is defined because otherwise you'll spend more
+ time re-flushing a too small cache than working
+ """
).tag(config=True)
color_info = Bool(True, help=
- """
- Use colors for displaying information about objects. Because this
- information is passed through a pager (like 'less'), and some pagers
- get confused with color codes, this capability can be turned off.
- """
+ """
+ Use colors for displaying information about objects. Because this
+ information is passed through a pager (like 'less'), and some pagers
+ get confused with color codes, this capability can be turned off.
+ """
).tag(config=True)
colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
default_value='Neutral',
@@ -262,26 +262,26 @@ class InteractiveShell(SingletonConfigurable):
).tag(config=True)
debug = Bool(False).tag(config=True)
deep_reload = Bool(False, help=
- """
- **Deprecated**
-
- Will be removed in IPython 6.0
-
- Enable deep (recursive) reloading by default. IPython can use the
- deep_reload module which reloads changes in modules recursively (it
- replaces the reload() function, so you don't need to change anything to
- use it). `deep_reload` forces a full reload of modules whose code may
- have changed, which the default reload() function does not. When
- deep_reload is off, IPython will use the normal reload(), but
- deep_reload will still be available as dreload().
- """
+ """
+ **Deprecated**
+
+ Will be removed in IPython 6.0
+
+ Enable deep (recursive) reloading by default. IPython can use the
+ deep_reload module which reloads changes in modules recursively (it
+ replaces the reload() function, so you don't need to change anything to
+ use it). `deep_reload` forces a full reload of modules whose code may
+ have changed, which the default reload() function does not. When
+ deep_reload is off, IPython will use the normal reload(), but
+ deep_reload will still be available as dreload().
+ """
).tag(config=True)
disable_failing_post_execute = Bool(False,
- help="Don't call post-execute functions that have failed in the past."
+ help="Don't call post-execute functions that have failed in the past."
).tag(config=True)
- display_formatter = Instance(DisplayFormatter, allow_none=True)
- displayhook_class = Type(DisplayHook)
- display_pub_class = Type(DisplayPublisher)
+ display_formatter = Instance(DisplayFormatter, allow_none=True)
+ displayhook_class = Type(DisplayHook)
+ display_pub_class = Type(DisplayPublisher)
sphinxify_docstring = Bool(False, help=
"""
@@ -305,58 +305,58 @@ class InteractiveShell(SingletonConfigurable):
if change['new']:
warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
- data_pub_class = None
-
+ data_pub_class = None
+
exit_now = Bool(False)
- exiter = Instance(ExitAutocall)
+ exiter = Instance(ExitAutocall)
@default('exiter')
- def _exiter_default(self):
- return ExitAutocall(self)
- # Monotonically increasing execution counter
- execution_count = Integer(1)
- filename = Unicode("<ipython console>")
+ def _exiter_default(self):
+ return ExitAutocall(self)
+ # Monotonically increasing execution counter
+ execution_count = Integer(1)
+ filename = Unicode("<ipython console>")
ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
-
- # Input splitter, to transform input line by line and detect when a block
- # is ready to be executed.
- input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
- (), {'line_input_checker': True})
-
- # This InputSplitter instance is used to transform completed cells before
- # running them. It allows cell magics to contain blank lines.
- input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
- (), {'line_input_checker': False})
-
+
+ # Input splitter, to transform input line by line and detect when a block
+ # is ready to be executed.
+ input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
+ (), {'line_input_checker': True})
+
+ # This InputSplitter instance is used to transform completed cells before
+ # running them. It allows cell magics to contain blank lines.
+ input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
+ (), {'line_input_checker': False})
+
logstart = Bool(False, help=
- """
- Start logging to the default log file in overwrite mode.
- Use `logappend` to specify a log file to **append** logs to.
- """
+ """
+ Start logging to the default log file in overwrite mode.
+ Use `logappend` to specify a log file to **append** logs to.
+ """
).tag(config=True)
logfile = Unicode('', help=
- """
- The name of the logfile to use.
- """
+ """
+ The name of the logfile to use.
+ """
).tag(config=True)
logappend = Unicode('', help=
- """
- Start logging to the given file in append mode.
- Use `logfile` to specify a log file to **overwrite** logs to.
- """
+ """
+ Start logging to the given file in append mode.
+ Use `logfile` to specify a log file to **overwrite** logs to.
+ """
).tag(config=True)
- object_info_string_level = Enum((0,1,2), default_value=0,
+ object_info_string_level = Enum((0,1,2), default_value=0,
).tag(config=True)
pdb = Bool(False, help=
- """
- Automatically call the pdb debugger after every exception.
- """
+ """
+ Automatically call the pdb debugger after every exception.
+ """
).tag(config=True)
display_page = Bool(False,
- help="""If True, anything that would be passed to the pager
- will be displayed as regular output instead."""
+ help="""If True, anything that would be passed to the pager
+ will be displayed as regular output instead."""
).tag(config=True)
-
- # deprecated prompt traits:
+
+ # deprecated prompt traits:
prompt_in1 = Unicode('In [\\#]: ',
help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
@@ -376,1183 +376,1183 @@ class InteractiveShell(SingletonConfigurable):
name = change['name']
warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
name=name)
- )
- # protect against weird cases where self.config may not exist:
-
+ )
+ # protect against weird cases where self.config may not exist:
+
show_rewritten_input = Bool(True,
- help="Show rewritten input, e.g. for autocall."
+ help="Show rewritten input, e.g. for autocall."
).tag(config=True)
-
+
quiet = Bool(False).tag(config=True)
-
+
history_length = Integer(10000,
help='Total length of command history'
).tag(config=True)
-
+
history_load_length = Integer(1000, help=
- """
- The number of saved history entries to be loaded
+ """
+ The number of saved history entries to be loaded
into the history buffer at startup.
- """
+ """
).tag(config=True)
-
- ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
+
+ ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
default_value='last_expr',
- help="""
- 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
+ help="""
+ 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
run interactively (displaying output from expressions)."""
).tag(config=True)
-
- # TODO: this part of prompt management should be moved to the frontends.
- # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
+
+ # TODO: this part of prompt management should be moved to the frontends.
+ # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
separate_in = SeparateUnicode('\n').tag(config=True)
separate_out = SeparateUnicode('').tag(config=True)
separate_out2 = SeparateUnicode('').tag(config=True)
wildcards_case_sensitive = Bool(True).tag(config=True)
- xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
+ xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
default_value='Context').tag(config=True)
-
- # Subcomponents of InteractiveShell
- alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
- prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
- builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
- display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
- extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
- payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
- history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
- magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
-
- profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
- @property
- def profile(self):
- if self.profile_dir is not None:
- name = os.path.basename(self.profile_dir.location)
- return name.replace('profile_','')
-
-
- # Private interface
- _post_execute = Dict()
-
- # Tracks any GUI loop loaded for pylab
- pylab_gui_select = None
-
+
+ # Subcomponents of InteractiveShell
+ alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
+ prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
+ builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
+ display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
+ extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
+ payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
+ history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
+ magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
+
+ profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
+ @property
+ def profile(self):
+ if self.profile_dir is not None:
+ name = os.path.basename(self.profile_dir.location)
+ return name.replace('profile_','')
+
+
+ # Private interface
+ _post_execute = Dict()
+
+ # Tracks any GUI loop loaded for pylab
+ pylab_gui_select = None
+
last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
- def __init__(self, ipython_dir=None, profile_dir=None,
- user_module=None, user_ns=None,
- custom_exceptions=((), None), **kwargs):
-
- # This is where traits with a config_key argument are updated
- # from the values on config.
- super(InteractiveShell, self).__init__(**kwargs)
+ def __init__(self, ipython_dir=None, profile_dir=None,
+ user_module=None, user_ns=None,
+ custom_exceptions=((), None), **kwargs):
+
+ # This is where traits with a config_key argument are updated
+ # from the values on config.
+ super(InteractiveShell, self).__init__(**kwargs)
if 'PromptManager' in self.config:
warn('As of IPython 5.0 `PromptManager` config will have no effect'
' and has been replaced by TerminalInteractiveShell.prompts_class')
- self.configurables = [self]
-
- # These are relatively independent and stateless
- self.init_ipython_dir(ipython_dir)
- self.init_profile_dir(profile_dir)
- self.init_instance_attrs()
- self.init_environment()
+ self.configurables = [self]
+
+ # These are relatively independent and stateless
+ self.init_ipython_dir(ipython_dir)
+ self.init_profile_dir(profile_dir)
+ self.init_instance_attrs()
+ self.init_environment()
- # Check if we're in a virtualenv, and set up sys.path.
- self.init_virtualenv()
-
- # Create namespaces (user_ns, user_global_ns, etc.)
- self.init_create_namespaces(user_module, user_ns)
- # This has to be done after init_create_namespaces because it uses
- # something in self.user_ns, but before init_sys_modules, which
- # is the first thing to modify sys.
- # TODO: When we override sys.stdout and sys.stderr before this class
- # is created, we are saving the overridden ones here. Not sure if this
- # is what we want to do.
- self.save_sys_module_state()
- self.init_sys_modules()
-
- # While we're trying to have each part of the code directly access what
- # it needs without keeping redundant references to objects, we have too
- # much legacy code that expects ip.db to exist.
- self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
-
- self.init_history()
- self.init_encoding()
- self.init_prefilter()
-
- self.init_syntax_highlighting()
- self.init_hooks()
- self.init_events()
- self.init_pushd_popd_magic()
- self.init_user_ns()
- self.init_logger()
- self.init_builtins()
-
- # The following was in post_config_initialization
- self.init_inspector()
- if py3compat.PY3:
- self.raw_input_original = input
- else:
- self.raw_input_original = raw_input
- self.init_completer()
- # TODO: init_io() needs to happen before init_traceback handlers
- # because the traceback handlers hardcode the stdout/stderr streams.
- # This logic in in debugger.Pdb and should eventually be changed.
- self.init_io()
- self.init_traceback_handlers(custom_exceptions)
- self.init_prompts()
- self.init_display_formatter()
- self.init_display_pub()
- self.init_data_pub()
- self.init_displayhook()
- self.init_magics()
- self.init_alias()
- self.init_logstart()
- self.init_pdb()
- self.init_extension_manager()
- self.init_payload()
- self.init_deprecation_warnings()
- self.hooks.late_startup_hook()
- self.events.trigger('shell_initialized', self)
- atexit.register(self.atexit_operations)
-
- def get_ipython(self):
- """Return the currently running IPython instance."""
- return self
-
- #-------------------------------------------------------------------------
- # Trait changed handlers
- #-------------------------------------------------------------------------
+ # Check if we're in a virtualenv, and set up sys.path.
+ self.init_virtualenv()
+
+ # Create namespaces (user_ns, user_global_ns, etc.)
+ self.init_create_namespaces(user_module, user_ns)
+ # This has to be done after init_create_namespaces because it uses
+ # something in self.user_ns, but before init_sys_modules, which
+ # is the first thing to modify sys.
+ # TODO: When we override sys.stdout and sys.stderr before this class
+ # is created, we are saving the overridden ones here. Not sure if this
+ # is what we want to do.
+ self.save_sys_module_state()
+ self.init_sys_modules()
+
+ # While we're trying to have each part of the code directly access what
+ # it needs without keeping redundant references to objects, we have too
+ # much legacy code that expects ip.db to exist.
+ self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
+
+ self.init_history()
+ self.init_encoding()
+ self.init_prefilter()
+
+ self.init_syntax_highlighting()
+ self.init_hooks()
+ self.init_events()
+ self.init_pushd_popd_magic()
+ self.init_user_ns()
+ self.init_logger()
+ self.init_builtins()
+
+ # The following was in post_config_initialization
+ self.init_inspector()
+ if py3compat.PY3:
+ self.raw_input_original = input
+ else:
+ self.raw_input_original = raw_input
+ self.init_completer()
+ # TODO: init_io() needs to happen before init_traceback handlers
+ # because the traceback handlers hardcode the stdout/stderr streams.
+ # This logic in in debugger.Pdb and should eventually be changed.
+ self.init_io()
+ self.init_traceback_handlers(custom_exceptions)
+ self.init_prompts()
+ self.init_display_formatter()
+ self.init_display_pub()
+ self.init_data_pub()
+ self.init_displayhook()
+ self.init_magics()
+ self.init_alias()
+ self.init_logstart()
+ self.init_pdb()
+ self.init_extension_manager()
+ self.init_payload()
+ self.init_deprecation_warnings()
+ self.hooks.late_startup_hook()
+ self.events.trigger('shell_initialized', self)
+ atexit.register(self.atexit_operations)
+
+ def get_ipython(self):
+ """Return the currently running IPython instance."""
+ return self
+
+ #-------------------------------------------------------------------------
+ # Trait changed handlers
+ #-------------------------------------------------------------------------
@observe('ipython_dir')
def _ipython_dir_changed(self, change):
ensure_dir_exists(change['new'])
-
- def set_autoindent(self,value=None):
+
+ def set_autoindent(self,value=None):
"""Set the autoindent flag.
-
- If called with no arguments, it acts as a toggle."""
- if value is None:
- self.autoindent = not self.autoindent
- else:
- self.autoindent = value
-
- #-------------------------------------------------------------------------
- # init_* methods called by __init__
- #-------------------------------------------------------------------------
-
- def init_ipython_dir(self, ipython_dir):
- if ipython_dir is not None:
- self.ipython_dir = ipython_dir
- return
-
- self.ipython_dir = get_ipython_dir()
-
- def init_profile_dir(self, profile_dir):
- if profile_dir is not None:
- self.profile_dir = profile_dir
- return
- self.profile_dir =\
- ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
-
- def init_instance_attrs(self):
- self.more = False
-
- # command compiler
- self.compile = CachingCompiler()
-
- # Make an empty namespace, which extension writers can rely on both
- # existing and NEVER being used by ipython itself. This gives them a
- # convenient location for storing additional information and state
- # their extensions may require, without fear of collisions with other
- # ipython names that may develop later.
- self.meta = Struct()
-
- # Temporary files used for various purposes. Deleted at exit.
- self.tempfiles = []
- self.tempdirs = []
-
- # keep track of where we started running (mainly for crash post-mortem)
- # This is not being used anywhere currently.
- self.starting_dir = py3compat.getcwd()
-
- # Indentation management
- self.indent_current_nsp = 0
-
- # Dict to track post-execution functions that have been registered
- self._post_execute = {}
-
- def init_environment(self):
- """Any changes we need to make to the user's environment."""
- pass
-
- def init_encoding(self):
- # Get system encoding at startup time. Certain terminals (like Emacs
- # under Win32 have it set to None, and we need to have a known valid
- # encoding to use in the raw_input() method
- try:
- self.stdin_encoding = sys.stdin.encoding or 'ascii'
- except AttributeError:
- self.stdin_encoding = 'ascii'
-
- def init_syntax_highlighting(self):
- # Python source parser/formatter for syntax highlighting
- pyformat = PyColorize.Parser().format
- self.pycolorize = lambda src: pyformat(src,'str',self.colors)
-
+
+ If called with no arguments, it acts as a toggle."""
+ if value is None:
+ self.autoindent = not self.autoindent
+ else:
+ self.autoindent = value
+
+ #-------------------------------------------------------------------------
+ # init_* methods called by __init__
+ #-------------------------------------------------------------------------
+
+ def init_ipython_dir(self, ipython_dir):
+ if ipython_dir is not None:
+ self.ipython_dir = ipython_dir
+ return
+
+ self.ipython_dir = get_ipython_dir()
+
+ def init_profile_dir(self, profile_dir):
+ if profile_dir is not None:
+ self.profile_dir = profile_dir
+ return
+ self.profile_dir =\
+ ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
+
+ def init_instance_attrs(self):
+ self.more = False
+
+ # command compiler
+ self.compile = CachingCompiler()
+
+ # Make an empty namespace, which extension writers can rely on both
+ # existing and NEVER being used by ipython itself. This gives them a
+ # convenient location for storing additional information and state
+ # their extensions may require, without fear of collisions with other
+ # ipython names that may develop later.
+ self.meta = Struct()
+
+ # Temporary files used for various purposes. Deleted at exit.
+ self.tempfiles = []
+ self.tempdirs = []
+
+ # keep track of where we started running (mainly for crash post-mortem)
+ # This is not being used anywhere currently.
+ self.starting_dir = py3compat.getcwd()
+
+ # Indentation management
+ self.indent_current_nsp = 0
+
+ # Dict to track post-execution functions that have been registered
+ self._post_execute = {}
+
+ def init_environment(self):
+ """Any changes we need to make to the user's environment."""
+ pass
+
+ def init_encoding(self):
+ # Get system encoding at startup time. Certain terminals (like Emacs
+ # under Win32 have it set to None, and we need to have a known valid
+ # encoding to use in the raw_input() method
+ try:
+ self.stdin_encoding = sys.stdin.encoding or 'ascii'
+ except AttributeError:
+ self.stdin_encoding = 'ascii'
+
+ def init_syntax_highlighting(self):
+ # Python source parser/formatter for syntax highlighting
+ pyformat = PyColorize.Parser().format
+ self.pycolorize = lambda src: pyformat(src,'str',self.colors)
+
def refresh_style(self):
# No-op here, used in subclass
pass
- def init_pushd_popd_magic(self):
- # for pushd/popd management
- self.home_dir = get_home_dir()
-
- self.dir_stack = []
-
- def init_logger(self):
- self.logger = Logger(self.home_dir, logfname='ipython_log.py',
- logmode='rotate')
-
- def init_logstart(self):
- """Initialize logging in case it was requested at the command line.
- """
- if self.logappend:
- self.magic('logstart %s append' % self.logappend)
- elif self.logfile:
- self.magic('logstart %s' % self.logfile)
- elif self.logstart:
- self.magic('logstart')
-
- def init_deprecation_warnings(self):
- """
- register default filter for deprecation warning.
-
- This will allow deprecation warning of function used interactively to show
- warning to users, and still hide deprecation warning from libraries import.
- """
- warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
-
- def init_builtins(self):
- # A single, static flag that we set to True. Its presence indicates
- # that an IPython shell has been created, and we make no attempts at
- # removing on exit or representing the existence of more than one
- # IPython at a time.
- builtin_mod.__dict__['__IPYTHON__'] = True
+ def init_pushd_popd_magic(self):
+ # for pushd/popd management
+ self.home_dir = get_home_dir()
+
+ self.dir_stack = []
+
+ def init_logger(self):
+ self.logger = Logger(self.home_dir, logfname='ipython_log.py',
+ logmode='rotate')
+
+ def init_logstart(self):
+ """Initialize logging in case it was requested at the command line.
+ """
+ if self.logappend:
+ self.magic('logstart %s append' % self.logappend)
+ elif self.logfile:
+ self.magic('logstart %s' % self.logfile)
+ elif self.logstart:
+ self.magic('logstart')
+
+ def init_deprecation_warnings(self):
+ """
+ register default filter for deprecation warning.
+
+ This will allow deprecation warning of function used interactively to show
+ warning to users, and still hide deprecation warning from libraries import.
+ """
+ warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
+
+ def init_builtins(self):
+ # A single, static flag that we set to True. Its presence indicates
+ # that an IPython shell has been created, and we make no attempts at
+ # removing on exit or representing the existence of more than one
+ # IPython at a time.
+ builtin_mod.__dict__['__IPYTHON__'] = True
builtin_mod.__dict__['display'] = display
-
- self.builtin_trap = BuiltinTrap(shell=self)
-
- def init_inspector(self):
- # Object inspector
- self.inspector = oinspect.Inspector(oinspect.InspectColors,
- PyColorize.ANSICodeColors,
- 'NoColor',
- self.object_info_string_level)
-
- def init_io(self):
- # This will just use sys.stdout and sys.stderr. If you want to
- # override sys.stdout and sys.stderr themselves, you need to do that
- # *before* instantiating this class, because io holds onto
- # references to the underlying streams.
+
+ self.builtin_trap = BuiltinTrap(shell=self)
+
+ def init_inspector(self):
+ # Object inspector
+ self.inspector = oinspect.Inspector(oinspect.InspectColors,
+ PyColorize.ANSICodeColors,
+ 'NoColor',
+ self.object_info_string_level)
+
+ def init_io(self):
+ # This will just use sys.stdout and sys.stderr. If you want to
+ # override sys.stdout and sys.stderr themselves, you need to do that
+ # *before* instantiating this class, because io holds onto
+ # references to the underlying streams.
# io.std* are deprecated, but don't show our own deprecation warnings
# during initialization of the deprecated API.
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
- io.stdout = io.IOStream(sys.stdout)
- io.stderr = io.IOStream(sys.stderr)
-
- def init_prompts(self):
- # Set system prompts, so that scripts can decide if they are running
- # interactively.
- sys.ps1 = 'In : '
- sys.ps2 = '...: '
- sys.ps3 = 'Out: '
-
- def init_display_formatter(self):
- self.display_formatter = DisplayFormatter(parent=self)
- self.configurables.append(self.display_formatter)
-
- def init_display_pub(self):
- self.display_pub = self.display_pub_class(parent=self)
- self.configurables.append(self.display_pub)
-
- def init_data_pub(self):
- if not self.data_pub_class:
- self.data_pub = None
- return
- self.data_pub = self.data_pub_class(parent=self)
- self.configurables.append(self.data_pub)
-
- def init_displayhook(self):
- # Initialize displayhook, set in/out prompts and printing system
- self.displayhook = self.displayhook_class(
- parent=self,
- shell=self,
- cache_size=self.cache_size,
- )
- self.configurables.append(self.displayhook)
- # This is a context manager that installs/revmoes the displayhook at
- # the appropriate time.
- self.display_trap = DisplayTrap(hook=self.displayhook)
-
- def init_virtualenv(self):
- """Add a virtualenv to sys.path so the user can import modules from it.
- This isn't perfect: it doesn't use the Python interpreter with which the
- virtualenv was built, and it ignores the --no-site-packages option. A
- warning will appear suggesting the user installs IPython in the
- virtualenv, but for many cases, it probably works well enough.
+ io.stdout = io.IOStream(sys.stdout)
+ io.stderr = io.IOStream(sys.stderr)
+
+ def init_prompts(self):
+ # Set system prompts, so that scripts can decide if they are running
+ # interactively.
+ sys.ps1 = 'In : '
+ sys.ps2 = '...: '
+ sys.ps3 = 'Out: '
+
+ def init_display_formatter(self):
+ self.display_formatter = DisplayFormatter(parent=self)
+ self.configurables.append(self.display_formatter)
+
+ def init_display_pub(self):
+ self.display_pub = self.display_pub_class(parent=self)
+ self.configurables.append(self.display_pub)
+
+ def init_data_pub(self):
+ if not self.data_pub_class:
+ self.data_pub = None
+ return
+ self.data_pub = self.data_pub_class(parent=self)
+ self.configurables.append(self.data_pub)
+
+ def init_displayhook(self):
+ # Initialize displayhook, set in/out prompts and printing system
+ self.displayhook = self.displayhook_class(
+ parent=self,
+ shell=self,
+ cache_size=self.cache_size,
+ )
+ self.configurables.append(self.displayhook)
+ # This is a context manager that installs/revmoes the displayhook at
+ # the appropriate time.
+ self.display_trap = DisplayTrap(hook=self.displayhook)
+
+ def init_virtualenv(self):
+ """Add a virtualenv to sys.path so the user can import modules from it.
+ This isn't perfect: it doesn't use the Python interpreter with which the
+ virtualenv was built, and it ignores the --no-site-packages option. A
+ warning will appear suggesting the user installs IPython in the
+ virtualenv, but for many cases, it probably works well enough.
- Adapted from code snippets online.
+ Adapted from code snippets online.
- http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
- """
- if 'VIRTUAL_ENV' not in os.environ:
- # Not in a virtualenv
- return
+ http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
+ """
+ if 'VIRTUAL_ENV' not in os.environ:
+ # Not in a virtualenv
+ return
- # venv detection:
- # stdlib venv may symlink sys.executable, so we can't use realpath.
- # but others can symlink *to* the venv Python, so we can't just use sys.executable.
- # So we just check every item in the symlink tree (generally <= 3)
- p = os.path.normcase(sys.executable)
- paths = [p]
- while os.path.islink(p):
- p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
- paths.append(p)
- p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
- if any(p.startswith(p_venv) for p in paths):
- # Running properly in the virtualenv, don't need to do anything
- return
+ # venv detection:
+ # stdlib venv may symlink sys.executable, so we can't use realpath.
+ # but others can symlink *to* the venv Python, so we can't just use sys.executable.
+ # So we just check every item in the symlink tree (generally <= 3)
+ p = os.path.normcase(sys.executable)
+ paths = [p]
+ while os.path.islink(p):
+ p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
+ paths.append(p)
+ p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
+ if any(p.startswith(p_venv) for p in paths):
+ # Running properly in the virtualenv, don't need to do anything
+ return
- warn("Attempting to work in a virtualenv. If you encounter problems, please "
- "install IPython inside the virtualenv.")
- if sys.platform == "win32":
+ warn("Attempting to work in a virtualenv. If you encounter problems, please "
+ "install IPython inside the virtualenv.")
+ if sys.platform == "win32":
virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
- else:
- virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
- 'python%d.%d' % sys.version_info[:2], 'site-packages')
+ else:
+ virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
+ 'python%d.%d' % sys.version_info[:2], 'site-packages')
- import site
- sys.path.insert(0, virtual_env)
- site.addsitedir(virtual_env)
-
- #-------------------------------------------------------------------------
- # Things related to injections into the sys module
- #-------------------------------------------------------------------------
-
- def save_sys_module_state(self):
- """Save the state of hooks in the sys module.
-
- This has to be called after self.user_module is created.
- """
- self._orig_sys_module_state = {'stdin': sys.stdin,
- 'stdout': sys.stdout,
- 'stderr': sys.stderr,
- 'excepthook': sys.excepthook}
- self._orig_sys_modules_main_name = self.user_module.__name__
- self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
-
- def restore_sys_module_state(self):
- """Restore the state of the sys module."""
- try:
- for k, v in iteritems(self._orig_sys_module_state):
- setattr(sys, k, v)
- except AttributeError:
- pass
- # Reset what what done in self.init_sys_modules
- if self._orig_sys_modules_main_mod is not None:
- sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
-
- #-------------------------------------------------------------------------
- # Things related to the banner
- #-------------------------------------------------------------------------
+ import site
+ sys.path.insert(0, virtual_env)
+ site.addsitedir(virtual_env)
+
+ #-------------------------------------------------------------------------
+ # Things related to injections into the sys module
+ #-------------------------------------------------------------------------
+
+ def save_sys_module_state(self):
+ """Save the state of hooks in the sys module.
+
+ This has to be called after self.user_module is created.
+ """
+ self._orig_sys_module_state = {'stdin': sys.stdin,
+ 'stdout': sys.stdout,
+ 'stderr': sys.stderr,
+ 'excepthook': sys.excepthook}
+ self._orig_sys_modules_main_name = self.user_module.__name__
+ self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
+
+ def restore_sys_module_state(self):
+ """Restore the state of the sys module."""
+ try:
+ for k, v in iteritems(self._orig_sys_module_state):
+ setattr(sys, k, v)
+ except AttributeError:
+ pass
+ # Reset what what done in self.init_sys_modules
+ if self._orig_sys_modules_main_mod is not None:
+ sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
+
+ #-------------------------------------------------------------------------
+ # Things related to the banner
+ #-------------------------------------------------------------------------
- @property
- def banner(self):
- banner = self.banner1
- if self.profile and self.profile != 'default':
- banner += '\nIPython profile: %s\n' % self.profile
- if self.banner2:
- banner += '\n' + self.banner2
- return banner
-
- def show_banner(self, banner=None):
- if banner is None:
- banner = self.banner
+ @property
+ def banner(self):
+ banner = self.banner1
+ if self.profile and self.profile != 'default':
+ banner += '\nIPython profile: %s\n' % self.profile
+ if self.banner2:
+ banner += '\n' + self.banner2
+ return banner
+
+ def show_banner(self, banner=None):
+ if banner is None:
+ banner = self.banner
sys.stdout.write(banner)
- #-------------------------------------------------------------------------
- # Things related to hooks
- #-------------------------------------------------------------------------
-
- def init_hooks(self):
- # hooks holds pointers used for user-side customizations
- self.hooks = Struct()
-
- self.strdispatchers = {}
-
- # Set all default hooks, defined in the IPython.hooks module.
- hooks = IPython.core.hooks
- for hook_name in hooks.__all__:
- # default hooks have priority 100, i.e. low; user hooks should have
- # 0-100 priority
- self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
+ #-------------------------------------------------------------------------
+ # Things related to hooks
+ #-------------------------------------------------------------------------
+
+ def init_hooks(self):
+ # hooks holds pointers used for user-side customizations
+ self.hooks = Struct()
+
+ self.strdispatchers = {}
+
+ # Set all default hooks, defined in the IPython.hooks module.
+ hooks = IPython.core.hooks
+ for hook_name in hooks.__all__:
+ # default hooks have priority 100, i.e. low; user hooks should have
+ # 0-100 priority
+ self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
- if self.display_page:
- self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
+ if self.display_page:
+ self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
- def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
- _warn_deprecated=True):
- """set_hook(name,hook) -> sets an internal IPython hook.
-
- IPython exposes some of its internal API as user-modifiable hooks. By
- adding your function to one of these hooks, you can modify IPython's
- behavior to call at runtime your own routines."""
-
- # At some point in the future, this should validate the hook before it
- # accepts it. Probably at least check that the hook takes the number
- # of args it's supposed to.
-
- f = types.MethodType(hook,self)
-
- # check if the hook is for strdispatcher first
- if str_key is not None:
- sdp = self.strdispatchers.get(name, StrDispatch())
- sdp.add_s(str_key, f, priority )
- self.strdispatchers[name] = sdp
- return
- if re_key is not None:
- sdp = self.strdispatchers.get(name, StrDispatch())
- sdp.add_re(re.compile(re_key), f, priority )
- self.strdispatchers[name] = sdp
- return
-
- dp = getattr(self.hooks, name, None)
- if name not in IPython.core.hooks.__all__:
- print("Warning! Hook '%s' is not one of %s" % \
- (name, IPython.core.hooks.__all__ ))
-
- if _warn_deprecated and (name in IPython.core.hooks.deprecated):
- alternative = IPython.core.hooks.deprecated[name]
- warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
-
- if not dp:
- dp = IPython.core.hooks.CommandChainDispatcher()
-
- try:
- dp.add(f,priority)
- except AttributeError:
- # it was not commandchain, plain old func - replace
- dp = f
-
- setattr(self.hooks,name, dp)
-
- #-------------------------------------------------------------------------
- # Things related to events
- #-------------------------------------------------------------------------
-
- def init_events(self):
- self.events = EventManager(self, available_events)
-
- self.events.register("pre_execute", self._clear_warning_registry)
-
- def register_post_execute(self, func):
- """DEPRECATED: Use ip.events.register('post_run_cell', func)
+ def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
+ _warn_deprecated=True):
+ """set_hook(name,hook) -> sets an internal IPython hook.
+
+ IPython exposes some of its internal API as user-modifiable hooks. By
+ adding your function to one of these hooks, you can modify IPython's
+ behavior to call at runtime your own routines."""
+
+ # At some point in the future, this should validate the hook before it
+ # accepts it. Probably at least check that the hook takes the number
+ # of args it's supposed to.
+
+ f = types.MethodType(hook,self)
+
+ # check if the hook is for strdispatcher first
+ if str_key is not None:
+ sdp = self.strdispatchers.get(name, StrDispatch())
+ sdp.add_s(str_key, f, priority )
+ self.strdispatchers[name] = sdp
+ return
+ if re_key is not None:
+ sdp = self.strdispatchers.get(name, StrDispatch())
+ sdp.add_re(re.compile(re_key), f, priority )
+ self.strdispatchers[name] = sdp
+ return
+
+ dp = getattr(self.hooks, name, None)
+ if name not in IPython.core.hooks.__all__:
+ print("Warning! Hook '%s' is not one of %s" % \
+ (name, IPython.core.hooks.__all__ ))
+
+ if _warn_deprecated and (name in IPython.core.hooks.deprecated):
+ alternative = IPython.core.hooks.deprecated[name]
+ warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
+
+ if not dp:
+ dp = IPython.core.hooks.CommandChainDispatcher()
+
+ try:
+ dp.add(f,priority)
+ except AttributeError:
+ # it was not commandchain, plain old func - replace
+ dp = f
+
+ setattr(self.hooks,name, dp)
+
+ #-------------------------------------------------------------------------
+ # Things related to events
+ #-------------------------------------------------------------------------
+
+ def init_events(self):
+ self.events = EventManager(self, available_events)
+
+ self.events.register("pre_execute", self._clear_warning_registry)
+
+ def register_post_execute(self, func):
+ """DEPRECATED: Use ip.events.register('post_run_cell', func)
- Register a function for calling after code execution.
- """
- warn("ip.register_post_execute is deprecated, use "
- "ip.events.register('post_run_cell', func) instead.")
- self.events.register('post_run_cell', func)
+ Register a function for calling after code execution.
+ """
+ warn("ip.register_post_execute is deprecated, use "
+ "ip.events.register('post_run_cell', func) instead.")
+ self.events.register('post_run_cell', func)
- def _clear_warning_registry(self):
- # clear the warning registry, so that different code blocks with
- # overlapping line number ranges don't cause spurious suppression of
- # warnings (see gh-6611 for details)
- if "__warningregistry__" in self.user_global_ns:
- del self.user_global_ns["__warningregistry__"]
-
- #-------------------------------------------------------------------------
- # Things related to the "main" module
- #-------------------------------------------------------------------------
-
- def new_main_mod(self, filename, modname):
- """Return a new 'main' module object for user code execution.
+ def _clear_warning_registry(self):
+ # clear the warning registry, so that different code blocks with
+ # overlapping line number ranges don't cause spurious suppression of
+ # warnings (see gh-6611 for details)
+ if "__warningregistry__" in self.user_global_ns:
+ del self.user_global_ns["__warningregistry__"]
+
+ #-------------------------------------------------------------------------
+ # Things related to the "main" module
+ #-------------------------------------------------------------------------
+
+ def new_main_mod(self, filename, modname):
+ """Return a new 'main' module object for user code execution.
- ``filename`` should be the path of the script which will be run in the
- module. Requests with the same filename will get the same module, with
- its namespace cleared.
+ ``filename`` should be the path of the script which will be run in the
+ module. Requests with the same filename will get the same module, with
+ its namespace cleared.
- ``modname`` should be the module name - normally either '__main__' or
- the basename of the file without the extension.
+ ``modname`` should be the module name - normally either '__main__' or
+ the basename of the file without the extension.
- When scripts are executed via %run, we must keep a reference to their
- __main__ module around so that Python doesn't
- clear it, rendering references to module globals useless.
-
- This method keeps said reference in a private dict, keyed by the
- absolute path of the script. This way, for multiple executions of the
- same script we only keep one copy of the namespace (the last one),
- thus preventing memory leaks from old references while allowing the
- objects from the last execution to be accessible.
- """
- filename = os.path.abspath(filename)
- try:
- main_mod = self._main_mod_cache[filename]
- except KeyError:
- main_mod = self._main_mod_cache[filename] = types.ModuleType(
- py3compat.cast_bytes_py2(modname),
- doc="Module created for script run in IPython")
- else:
- main_mod.__dict__.clear()
- main_mod.__name__ = modname
+ When scripts are executed via %run, we must keep a reference to their
+ __main__ module around so that Python doesn't
+ clear it, rendering references to module globals useless.
+
+ This method keeps said reference in a private dict, keyed by the
+ absolute path of the script. This way, for multiple executions of the
+ same script we only keep one copy of the namespace (the last one),
+ thus preventing memory leaks from old references while allowing the
+ objects from the last execution to be accessible.
+ """
+ filename = os.path.abspath(filename)
+ try:
+ main_mod = self._main_mod_cache[filename]
+ except KeyError:
+ main_mod = self._main_mod_cache[filename] = types.ModuleType(
+ py3compat.cast_bytes_py2(modname),
+ doc="Module created for script run in IPython")
+ else:
+ main_mod.__dict__.clear()
+ main_mod.__name__ = modname
- main_mod.__file__ = filename
- # It seems pydoc (and perhaps others) needs any module instance to
- # implement a __nonzero__ method
- main_mod.__nonzero__ = lambda : True
+ main_mod.__file__ = filename
+ # It seems pydoc (and perhaps others) needs any module instance to
+ # implement a __nonzero__ method
+ main_mod.__nonzero__ = lambda : True
- return main_mod
-
- def clear_main_mod_cache(self):
- """Clear the cache of main modules.
-
- Mainly for use by utilities like %reset.
-
- Examples
- --------
-
- In [15]: import IPython
-
- In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
-
- In [17]: len(_ip._main_mod_cache) > 0
- Out[17]: True
-
- In [18]: _ip.clear_main_mod_cache()
-
- In [19]: len(_ip._main_mod_cache) == 0
- Out[19]: True
- """
- self._main_mod_cache.clear()
-
- #-------------------------------------------------------------------------
- # Things related to debugging
- #-------------------------------------------------------------------------
-
- def init_pdb(self):
- # Set calling of pdb on exceptions
- # self.call_pdb is a property
- self.call_pdb = self.pdb
-
- def _get_call_pdb(self):
- return self._call_pdb
-
- def _set_call_pdb(self,val):
-
- if val not in (0,1,False,True):
- raise ValueError('new call_pdb value must be boolean')
-
- # store value in instance
- self._call_pdb = val
-
- # notify the actual exception handlers
- self.InteractiveTB.call_pdb = val
-
- call_pdb = property(_get_call_pdb,_set_call_pdb,None,
- 'Control auto-activation of pdb at exceptions')
-
- def debugger(self,force=False):
+ return main_mod
+
+ def clear_main_mod_cache(self):
+ """Clear the cache of main modules.
+
+ Mainly for use by utilities like %reset.
+
+ Examples
+ --------
+
+ In [15]: import IPython
+
+ In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
+
+ In [17]: len(_ip._main_mod_cache) > 0
+ Out[17]: True
+
+ In [18]: _ip.clear_main_mod_cache()
+
+ In [19]: len(_ip._main_mod_cache) == 0
+ Out[19]: True
+ """
+ self._main_mod_cache.clear()
+
+ #-------------------------------------------------------------------------
+ # Things related to debugging
+ #-------------------------------------------------------------------------
+
+ def init_pdb(self):
+ # Set calling of pdb on exceptions
+ # self.call_pdb is a property
+ self.call_pdb = self.pdb
+
+ def _get_call_pdb(self):
+ return self._call_pdb
+
+ def _set_call_pdb(self,val):
+
+ if val not in (0,1,False,True):
+ raise ValueError('new call_pdb value must be boolean')
+
+ # store value in instance
+ self._call_pdb = val
+
+ # notify the actual exception handlers
+ self.InteractiveTB.call_pdb = val
+
+ call_pdb = property(_get_call_pdb,_set_call_pdb,None,
+ 'Control auto-activation of pdb at exceptions')
+
+ def debugger(self,force=False):
"""Call the pdb debugger.
-
- Keywords:
-
- - force(False): by default, this routine checks the instance call_pdb
- flag and does not actually invoke the debugger if the flag is false.
- The 'force' option forces the debugger to activate even if the flag
- is false.
- """
-
- if not (force or self.call_pdb):
- return
-
- if not hasattr(sys,'last_traceback'):
- error('No traceback has been produced, nothing to debug.')
- return
-
+
+ Keywords:
+
+ - force(False): by default, this routine checks the instance call_pdb
+ flag and does not actually invoke the debugger if the flag is false.
+ The 'force' option forces the debugger to activate even if the flag
+ is false.
+ """
+
+ if not (force or self.call_pdb):
+ return
+
+ if not hasattr(sys,'last_traceback'):
+ error('No traceback has been produced, nothing to debug.')
+ return
+
self.InteractiveTB.debugger(force=True)
-
- #-------------------------------------------------------------------------
- # Things related to IPython's various namespaces
- #-------------------------------------------------------------------------
- default_user_namespaces = True
-
- def init_create_namespaces(self, user_module=None, user_ns=None):
- # Create the namespace where the user will operate. user_ns is
- # normally the only one used, and it is passed to the exec calls as
- # the locals argument. But we do carry a user_global_ns namespace
- # given as the exec 'globals' argument, This is useful in embedding
- # situations where the ipython shell opens in a context where the
- # distinction between locals and globals is meaningful. For
- # non-embedded contexts, it is just the same object as the user_ns dict.
-
- # FIXME. For some strange reason, __builtins__ is showing up at user
- # level as a dict instead of a module. This is a manual fix, but I
- # should really track down where the problem is coming from. Alex
- # Schmolck reported this problem first.
-
- # A useful post by Alex Martelli on this topic:
- # Re: inconsistent value from __builtins__
- # Von: Alex Martelli <aleaxit@yahoo.com>
- # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
- # Gruppen: comp.lang.python
-
- # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
- # > >>> print type(builtin_check.get_global_binding('__builtins__'))
- # > <type 'dict'>
- # > >>> print type(__builtins__)
- # > <type 'module'>
- # > Is this difference in return value intentional?
-
- # Well, it's documented that '__builtins__' can be either a dictionary
- # or a module, and it's been that way for a long time. Whether it's
- # intentional (or sensible), I don't know. In any case, the idea is
- # that if you need to access the built-in namespace directly, you
- # should start with "import __builtin__" (note, no 's') which will
- # definitely give you a module. Yeah, it's somewhat confusing:-(.
-
- # These routines return a properly built module and dict as needed by
- # the rest of the code, and can also be used by extension writers to
- # generate properly initialized namespaces.
- if (user_ns is not None) or (user_module is not None):
- self.default_user_namespaces = False
- self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
-
- # A record of hidden variables we have added to the user namespace, so
- # we can list later only variables defined in actual interactive use.
- self.user_ns_hidden = {}
-
- # Now that FakeModule produces a real module, we've run into a nasty
- # problem: after script execution (via %run), the module where the user
- # code ran is deleted. Now that this object is a true module (needed
- # so doctest and other tools work correctly), the Python module
- # teardown mechanism runs over it, and sets to None every variable
- # present in that module. Top-level references to objects from the
- # script survive, because the user_ns is updated with them. However,
- # calling functions defined in the script that use other things from
- # the script will fail, because the function's closure had references
- # to the original objects, which are now all None. So we must protect
- # these modules from deletion by keeping a cache.
- #
- # To avoid keeping stale modules around (we only need the one from the
- # last run), we use a dict keyed with the full path to the script, so
- # only the last version of the module is held in the cache. Note,
- # however, that we must cache the module *namespace contents* (their
- # __dict__). Because if we try to cache the actual modules, old ones
- # (uncached) could be destroyed while still holding references (such as
- # those held by GUI objects that tend to be long-lived)>
- #
- # The %reset command will flush this cache. See the cache_main_mod()
- # and clear_main_mod_cache() methods for details on use.
-
- # This is the cache used for 'main' namespaces
- self._main_mod_cache = {}
-
- # A table holding all the namespaces IPython deals with, so that
- # introspection facilities can search easily.
- self.ns_table = {'user_global':self.user_module.__dict__,
- 'user_local':self.user_ns,
- 'builtin':builtin_mod.__dict__
- }
+
+ #-------------------------------------------------------------------------
+ # Things related to IPython's various namespaces
+ #-------------------------------------------------------------------------
+ default_user_namespaces = True
+
+ def init_create_namespaces(self, user_module=None, user_ns=None):
+ # Create the namespace where the user will operate. user_ns is
+ # normally the only one used, and it is passed to the exec calls as
+ # the locals argument. But we do carry a user_global_ns namespace
+ # given as the exec 'globals' argument, This is useful in embedding
+ # situations where the ipython shell opens in a context where the
+ # distinction between locals and globals is meaningful. For
+ # non-embedded contexts, it is just the same object as the user_ns dict.
+
+ # FIXME. For some strange reason, __builtins__ is showing up at user
+ # level as a dict instead of a module. This is a manual fix, but I
+ # should really track down where the problem is coming from. Alex
+ # Schmolck reported this problem first.
+
+ # A useful post by Alex Martelli on this topic:
+ # Re: inconsistent value from __builtins__
+ # Von: Alex Martelli <aleaxit@yahoo.com>
+ # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
+ # Gruppen: comp.lang.python
+
+ # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
+ # > >>> print type(builtin_check.get_global_binding('__builtins__'))
+ # > <type 'dict'>
+ # > >>> print type(__builtins__)
+ # > <type 'module'>
+ # > Is this difference in return value intentional?
+
+ # Well, it's documented that '__builtins__' can be either a dictionary
+ # or a module, and it's been that way for a long time. Whether it's
+ # intentional (or sensible), I don't know. In any case, the idea is
+ # that if you need to access the built-in namespace directly, you
+ # should start with "import __builtin__" (note, no 's') which will
+ # definitely give you a module. Yeah, it's somewhat confusing:-(.
+
+ # These routines return a properly built module and dict as needed by
+ # the rest of the code, and can also be used by extension writers to
+ # generate properly initialized namespaces.
+ if (user_ns is not None) or (user_module is not None):
+ self.default_user_namespaces = False
+ self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
+
+ # A record of hidden variables we have added to the user namespace, so
+ # we can list later only variables defined in actual interactive use.
+ self.user_ns_hidden = {}
+
+ # Now that FakeModule produces a real module, we've run into a nasty
+ # problem: after script execution (via %run), the module where the user
+ # code ran is deleted. Now that this object is a true module (needed
+ # so doctest and other tools work correctly), the Python module
+ # teardown mechanism runs over it, and sets to None every variable
+ # present in that module. Top-level references to objects from the
+ # script survive, because the user_ns is updated with them. However,
+ # calling functions defined in the script that use other things from
+ # the script will fail, because the function's closure had references
+ # to the original objects, which are now all None. So we must protect
+ # these modules from deletion by keeping a cache.
+ #
+ # To avoid keeping stale modules around (we only need the one from the
+ # last run), we use a dict keyed with the full path to the script, so
+ # only the last version of the module is held in the cache. Note,
+ # however, that we must cache the module *namespace contents* (their
+ # __dict__). Because if we try to cache the actual modules, old ones
+ # (uncached) could be destroyed while still holding references (such as
+ # those held by GUI objects that tend to be long-lived)>
+ #
+ # The %reset command will flush this cache. See the cache_main_mod()
+ # and clear_main_mod_cache() methods for details on use.
+
+ # This is the cache used for 'main' namespaces
+ self._main_mod_cache = {}
+
+ # A table holding all the namespaces IPython deals with, so that
+ # introspection facilities can search easily.
+ self.ns_table = {'user_global':self.user_module.__dict__,
+ 'user_local':self.user_ns,
+ 'builtin':builtin_mod.__dict__
+ }
- @property
- def user_global_ns(self):
- return self.user_module.__dict__
-
- def prepare_user_module(self, user_module=None, user_ns=None):
- """Prepare the module and namespace in which user code will be run.
+ @property
+ def user_global_ns(self):
+ return self.user_module.__dict__
+
+ def prepare_user_module(self, user_module=None, user_ns=None):
+ """Prepare the module and namespace in which user code will be run.
- When IPython is started normally, both parameters are None: a new module
- is created automatically, and its __dict__ used as the namespace.
+ When IPython is started normally, both parameters are None: a new module
+ is created automatically, and its __dict__ used as the namespace.
- If only user_module is provided, its __dict__ is used as the namespace.
- If only user_ns is provided, a dummy module is created, and user_ns
- becomes the global namespace. If both are provided (as they may be
- when embedding), user_ns is the local namespace, and user_module
- provides the global namespace.
-
- Parameters
- ----------
- user_module : module, optional
- The current user module in which IPython is being run. If None,
- a clean module will be created.
- user_ns : dict, optional
- A namespace in which to run interactive commands.
-
- Returns
- -------
- A tuple of user_module and user_ns, each properly initialised.
- """
- if user_module is None and user_ns is not None:
- user_ns.setdefault("__name__", "__main__")
- user_module = DummyMod()
- user_module.__dict__ = user_ns
+ If only user_module is provided, its __dict__ is used as the namespace.
+ If only user_ns is provided, a dummy module is created, and user_ns
+ becomes the global namespace. If both are provided (as they may be
+ when embedding), user_ns is the local namespace, and user_module
+ provides the global namespace.
+
+ Parameters
+ ----------
+ user_module : module, optional
+ The current user module in which IPython is being run. If None,
+ a clean module will be created.
+ user_ns : dict, optional
+ A namespace in which to run interactive commands.
+
+ Returns
+ -------
+ A tuple of user_module and user_ns, each properly initialised.
+ """
+ if user_module is None and user_ns is not None:
+ user_ns.setdefault("__name__", "__main__")
+ user_module = DummyMod()
+ user_module.__dict__ = user_ns
- if user_module is None:
- user_module = types.ModuleType("__main__",
- doc="Automatically created module for IPython interactive environment")
+ if user_module is None:
+ user_module = types.ModuleType("__main__",
+ doc="Automatically created module for IPython interactive environment")
- # We must ensure that __builtin__ (without the final 's') is always
- # available and pointing to the __builtin__ *module*. For more details:
- # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
- user_module.__dict__.setdefault('__builtin__', builtin_mod)
- user_module.__dict__.setdefault('__builtins__', builtin_mod)
+ # We must ensure that __builtin__ (without the final 's') is always
+ # available and pointing to the __builtin__ *module*. For more details:
+ # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
+ user_module.__dict__.setdefault('__builtin__', builtin_mod)
+ user_module.__dict__.setdefault('__builtins__', builtin_mod)
- if user_ns is None:
- user_ns = user_module.__dict__
-
- return user_module, user_ns
-
- def init_sys_modules(self):
- # We need to insert into sys.modules something that looks like a
- # module but which accesses the IPython namespace, for shelve and
- # pickle to work interactively. Normally they rely on getting
- # everything out of __main__, but for embedding purposes each IPython
- # instance has its own private namespace, so we can't go shoving
- # everything into __main__.
-
- # note, however, that we should only do this for non-embedded
- # ipythons, which really mimic the __main__.__dict__ with their own
- # namespace. Embedded instances, on the other hand, should not do
- # this because they need to manage the user local/global namespaces
- # only, but they live within a 'normal' __main__ (meaning, they
- # shouldn't overtake the execution environment of the script they're
- # embedded in).
-
- # This is overridden in the InteractiveShellEmbed subclass to a no-op.
- main_name = self.user_module.__name__
- sys.modules[main_name] = self.user_module
-
- def init_user_ns(self):
- """Initialize all user-visible namespaces to their minimum defaults.
-
- Certain history lists are also initialized here, as they effectively
- act as user namespaces.
-
- Notes
- -----
- All data structures here are only filled in, they are NOT reset by this
- method. If they were not empty before, data will simply be added to
- therm.
- """
- # This function works in two parts: first we put a few things in
- # user_ns, and we sync that contents into user_ns_hidden so that these
- # initial variables aren't shown by %who. After the sync, we add the
- # rest of what we *do* want the user to see with %who even on a new
- # session (probably nothing, so they really only see their own stuff)
-
- # The user dict must *always* have a __builtin__ reference to the
- # Python standard __builtin__ namespace, which must be imported.
- # This is so that certain operations in prompt evaluation can be
- # reliably executed with builtins. Note that we can NOT use
- # __builtins__ (note the 's'), because that can either be a dict or a
- # module, and can even mutate at runtime, depending on the context
- # (Python makes no guarantees on it). In contrast, __builtin__ is
- # always a module object, though it must be explicitly imported.
-
- # For more details:
- # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
- ns = dict()
+ if user_ns is None:
+ user_ns = user_module.__dict__
+
+ return user_module, user_ns
+
+ def init_sys_modules(self):
+ # We need to insert into sys.modules something that looks like a
+ # module but which accesses the IPython namespace, for shelve and
+ # pickle to work interactively. Normally they rely on getting
+ # everything out of __main__, but for embedding purposes each IPython
+ # instance has its own private namespace, so we can't go shoving
+ # everything into __main__.
+
+ # note, however, that we should only do this for non-embedded
+ # ipythons, which really mimic the __main__.__dict__ with their own
+ # namespace. Embedded instances, on the other hand, should not do
+ # this because they need to manage the user local/global namespaces
+ # only, but they live within a 'normal' __main__ (meaning, they
+ # shouldn't overtake the execution environment of the script they're
+ # embedded in).
+
+ # This is overridden in the InteractiveShellEmbed subclass to a no-op.
+ main_name = self.user_module.__name__
+ sys.modules[main_name] = self.user_module
+
+ def init_user_ns(self):
+ """Initialize all user-visible namespaces to their minimum defaults.
+
+ Certain history lists are also initialized here, as they effectively
+ act as user namespaces.
+
+ Notes
+ -----
+ All data structures here are only filled in, they are NOT reset by this
+ method. If they were not empty before, data will simply be added to
+ therm.
+ """
+ # This function works in two parts: first we put a few things in
+ # user_ns, and we sync that contents into user_ns_hidden so that these
+ # initial variables aren't shown by %who. After the sync, we add the
+ # rest of what we *do* want the user to see with %who even on a new
+ # session (probably nothing, so they really only see their own stuff)
+
+ # The user dict must *always* have a __builtin__ reference to the
+ # Python standard __builtin__ namespace, which must be imported.
+ # This is so that certain operations in prompt evaluation can be
+ # reliably executed with builtins. Note that we can NOT use
+ # __builtins__ (note the 's'), because that can either be a dict or a
+ # module, and can even mutate at runtime, depending on the context
+ # (Python makes no guarantees on it). In contrast, __builtin__ is
+ # always a module object, though it must be explicitly imported.
+
+ # For more details:
+ # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
+ ns = dict()
- # make global variables for user access to the histories
- ns['_ih'] = self.history_manager.input_hist_parsed
- ns['_oh'] = self.history_manager.output_hist
- ns['_dh'] = self.history_manager.dir_hist
-
- ns['_sh'] = shadowns
-
- # user aliases to input and output histories. These shouldn't show up
- # in %who, as they can have very large reprs.
- ns['In'] = self.history_manager.input_hist_parsed
- ns['Out'] = self.history_manager.output_hist
-
- # Store myself as the public api!!!
- ns['get_ipython'] = self.get_ipython
+ # make global variables for user access to the histories
+ ns['_ih'] = self.history_manager.input_hist_parsed
+ ns['_oh'] = self.history_manager.output_hist
+ ns['_dh'] = self.history_manager.dir_hist
+
+ ns['_sh'] = shadowns
+
+ # user aliases to input and output histories. These shouldn't show up
+ # in %who, as they can have very large reprs.
+ ns['In'] = self.history_manager.input_hist_parsed
+ ns['Out'] = self.history_manager.output_hist
+
+ # Store myself as the public api!!!
+ ns['get_ipython'] = self.get_ipython
- ns['exit'] = self.exiter
- ns['quit'] = self.exiter
-
- # Sync what we've added so far to user_ns_hidden so these aren't seen
- # by %who
- self.user_ns_hidden.update(ns)
-
- # Anything put into ns now would show up in %who. Think twice before
- # putting anything here, as we really want %who to show the user their
- # stuff, not our variables.
-
- # Finally, update the real user's namespace
- self.user_ns.update(ns)
+ ns['exit'] = self.exiter
+ ns['quit'] = self.exiter
+
+ # Sync what we've added so far to user_ns_hidden so these aren't seen
+ # by %who
+ self.user_ns_hidden.update(ns)
+
+ # Anything put into ns now would show up in %who. Think twice before
+ # putting anything here, as we really want %who to show the user their
+ # stuff, not our variables.
+
+ # Finally, update the real user's namespace
+ self.user_ns.update(ns)
- @property
- def all_ns_refs(self):
- """Get a list of references to all the namespace dictionaries in which
- IPython might store a user-created object.
+ @property
+ def all_ns_refs(self):
+ """Get a list of references to all the namespace dictionaries in which
+ IPython might store a user-created object.
- Note that this does not include the displayhook, which also caches
- objects from the output."""
- return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
- [m.__dict__ for m in self._main_mod_cache.values()]
-
- def reset(self, new_session=True):
- """Clear all internal namespaces, and attempt to release references to
- user objects.
-
- If new_session is True, a new history session will be opened.
- """
- # Clear histories
- self.history_manager.reset(new_session)
- # Reset counter used to index all histories
- if new_session:
- self.execution_count = 1
-
- # Flush cached output items
- if self.displayhook.do_full_cache:
- self.displayhook.flush()
-
- # The main execution namespaces must be cleared very carefully,
- # skipping the deletion of the builtin-related keys, because doing so
- # would cause errors in many object's __del__ methods.
- if self.user_ns is not self.user_global_ns:
- self.user_ns.clear()
- ns = self.user_global_ns
- drop_keys = set(ns.keys())
- drop_keys.discard('__builtin__')
- drop_keys.discard('__builtins__')
- drop_keys.discard('__name__')
- for k in drop_keys:
- del ns[k]
+ Note that this does not include the displayhook, which also caches
+ objects from the output."""
+ return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
+ [m.__dict__ for m in self._main_mod_cache.values()]
+
+ def reset(self, new_session=True):
+ """Clear all internal namespaces, and attempt to release references to
+ user objects.
+
+ If new_session is True, a new history session will be opened.
+ """
+ # Clear histories
+ self.history_manager.reset(new_session)
+ # Reset counter used to index all histories
+ if new_session:
+ self.execution_count = 1
+
+ # Flush cached output items
+ if self.displayhook.do_full_cache:
+ self.displayhook.flush()
+
+ # The main execution namespaces must be cleared very carefully,
+ # skipping the deletion of the builtin-related keys, because doing so
+ # would cause errors in many object's __del__ methods.
+ if self.user_ns is not self.user_global_ns:
+ self.user_ns.clear()
+ ns = self.user_global_ns
+ drop_keys = set(ns.keys())
+ drop_keys.discard('__builtin__')
+ drop_keys.discard('__builtins__')
+ drop_keys.discard('__name__')
+ for k in drop_keys:
+ del ns[k]
- self.user_ns_hidden.clear()
+ self.user_ns_hidden.clear()
- # Restore the user namespaces to minimal usability
- self.init_user_ns()
-
- # Restore the default and user aliases
- self.alias_manager.clear_aliases()
- self.alias_manager.init_aliases()
-
- # Flush the private list of module references kept for script
- # execution protection
- self.clear_main_mod_cache()
-
- def del_var(self, varname, by_name=False):
- """Delete a variable from the various namespaces, so that, as
- far as possible, we're not keeping any hidden references to it.
-
- Parameters
- ----------
- varname : str
- The name of the variable to delete.
- by_name : bool
- If True, delete variables with the given name in each
- namespace. If False (default), find the variable in the user
- namespace, and delete references to it.
- """
- if varname in ('__builtin__', '__builtins__'):
- raise ValueError("Refusing to delete %s" % varname)
-
- ns_refs = self.all_ns_refs
+ # Restore the user namespaces to minimal usability
+ self.init_user_ns()
+
+ # Restore the default and user aliases
+ self.alias_manager.clear_aliases()
+ self.alias_manager.init_aliases()
+
+ # Flush the private list of module references kept for script
+ # execution protection
+ self.clear_main_mod_cache()
+
+ def del_var(self, varname, by_name=False):
+ """Delete a variable from the various namespaces, so that, as
+ far as possible, we're not keeping any hidden references to it.
+
+ Parameters
+ ----------
+ varname : str
+ The name of the variable to delete.
+ by_name : bool
+ If True, delete variables with the given name in each
+ namespace. If False (default), find the variable in the user
+ namespace, and delete references to it.
+ """
+ if varname in ('__builtin__', '__builtins__'):
+ raise ValueError("Refusing to delete %s" % varname)
+
+ ns_refs = self.all_ns_refs
- if by_name: # Delete by name
- for ns in ns_refs:
- try:
- del ns[varname]
- except KeyError:
- pass
- else: # Delete by object
- try:
- obj = self.user_ns[varname]
- except KeyError:
- raise NameError("name '%s' is not defined" % varname)
- # Also check in output history
- ns_refs.append(self.history_manager.output_hist)
- for ns in ns_refs:
- to_delete = [n for n, o in iteritems(ns) if o is obj]
- for name in to_delete:
- del ns[name]
-
- # displayhook keeps extra references, but not in a dictionary
- for name in ('_', '__', '___'):
- if getattr(self.displayhook, name) is obj:
- setattr(self.displayhook, name, None)
-
- def reset_selective(self, regex=None):
- """Clear selective variables from internal namespaces based on a
- specified regular expression.
-
- Parameters
- ----------
- regex : string or compiled pattern, optional
- A regular expression pattern that will be used in searching
- variable names in the users namespaces.
- """
- if regex is not None:
- try:
- m = re.compile(regex)
- except TypeError:
- raise TypeError('regex must be a string or compiled pattern')
- # Search for keys in each namespace that match the given regex
- # If a match is found, delete the key/value pair.
- for ns in self.all_ns_refs:
- for var in ns:
- if m.search(var):
- del ns[var]
-
- def push(self, variables, interactive=True):
- """Inject a group of variables into the IPython user namespace.
-
- Parameters
- ----------
- variables : dict, str or list/tuple of str
- The variables to inject into the user's namespace. If a dict, a
- simple update is done. If a str, the string is assumed to have
- variable names separated by spaces. A list/tuple of str can also
- be used to give the variable names. If just the variable names are
- give (list/tuple/str) then the variable values looked up in the
- callers frame.
- interactive : bool
- If True (default), the variables will be listed with the ``who``
- magic.
- """
- vdict = None
-
- # We need a dict of name/value pairs to do namespace updates.
- if isinstance(variables, dict):
- vdict = variables
- elif isinstance(variables, string_types+(list, tuple)):
- if isinstance(variables, string_types):
- vlist = variables.split()
- else:
- vlist = variables
- vdict = {}
- cf = sys._getframe(1)
- for name in vlist:
- try:
- vdict[name] = eval(name, cf.f_globals, cf.f_locals)
- except:
- print('Could not get variable %s from %s' %
- (name,cf.f_code.co_name))
- else:
- raise ValueError('variables must be a dict/str/list/tuple')
-
- # Propagate variables to user namespace
- self.user_ns.update(vdict)
-
- # And configure interactive visibility
- user_ns_hidden = self.user_ns_hidden
- if interactive:
- for name in vdict:
- user_ns_hidden.pop(name, None)
- else:
- user_ns_hidden.update(vdict)
-
- def drop_by_id(self, variables):
- """Remove a dict of variables from the user namespace, if they are the
- same as the values in the dictionary.
+ if by_name: # Delete by name
+ for ns in ns_refs:
+ try:
+ del ns[varname]
+ except KeyError:
+ pass
+ else: # Delete by object
+ try:
+ obj = self.user_ns[varname]
+ except KeyError:
+ raise NameError("name '%s' is not defined" % varname)
+ # Also check in output history
+ ns_refs.append(self.history_manager.output_hist)
+ for ns in ns_refs:
+ to_delete = [n for n, o in iteritems(ns) if o is obj]
+ for name in to_delete:
+ del ns[name]
+
+ # displayhook keeps extra references, but not in a dictionary
+ for name in ('_', '__', '___'):
+ if getattr(self.displayhook, name) is obj:
+ setattr(self.displayhook, name, None)
+
+ def reset_selective(self, regex=None):
+ """Clear selective variables from internal namespaces based on a
+ specified regular expression.
+
+ Parameters
+ ----------
+ regex : string or compiled pattern, optional
+ A regular expression pattern that will be used in searching
+ variable names in the users namespaces.
+ """
+ if regex is not None:
+ try:
+ m = re.compile(regex)
+ except TypeError:
+ raise TypeError('regex must be a string or compiled pattern')
+ # Search for keys in each namespace that match the given regex
+ # If a match is found, delete the key/value pair.
+ for ns in self.all_ns_refs:
+ for var in ns:
+ if m.search(var):
+ del ns[var]
+
+ def push(self, variables, interactive=True):
+ """Inject a group of variables into the IPython user namespace.
+
+ Parameters
+ ----------
+ variables : dict, str or list/tuple of str
+ The variables to inject into the user's namespace. If a dict, a
+ simple update is done. If a str, the string is assumed to have
+ variable names separated by spaces. A list/tuple of str can also
+ be used to give the variable names. If just the variable names are
+ give (list/tuple/str) then the variable values looked up in the
+ callers frame.
+ interactive : bool
+ If True (default), the variables will be listed with the ``who``
+ magic.
+ """
+ vdict = None
+
+ # We need a dict of name/value pairs to do namespace updates.
+ if isinstance(variables, dict):
+ vdict = variables
+ elif isinstance(variables, string_types+(list, tuple)):
+ if isinstance(variables, string_types):
+ vlist = variables.split()
+ else:
+ vlist = variables
+ vdict = {}
+ cf = sys._getframe(1)
+ for name in vlist:
+ try:
+ vdict[name] = eval(name, cf.f_globals, cf.f_locals)
+ except:
+ print('Could not get variable %s from %s' %
+ (name,cf.f_code.co_name))
+ else:
+ raise ValueError('variables must be a dict/str/list/tuple')
+
+ # Propagate variables to user namespace
+ self.user_ns.update(vdict)
+
+ # And configure interactive visibility
+ user_ns_hidden = self.user_ns_hidden
+ if interactive:
+ for name in vdict:
+ user_ns_hidden.pop(name, None)
+ else:
+ user_ns_hidden.update(vdict)
+
+ def drop_by_id(self, variables):
+ """Remove a dict of variables from the user namespace, if they are the
+ same as the values in the dictionary.
- This is intended for use by extensions: variables that they've added can
- be taken back out if they are unloaded, without removing any that the
- user has overwritten.
+ This is intended for use by extensions: variables that they've added can
+ be taken back out if they are unloaded, without removing any that the
+ user has overwritten.
- Parameters
- ----------
- variables : dict
- A dictionary mapping object names (as strings) to the objects.
- """
- for name, obj in iteritems(variables):
- if name in self.user_ns and self.user_ns[name] is obj:
- del self.user_ns[name]
- self.user_ns_hidden.pop(name, None)
-
- #-------------------------------------------------------------------------
- # Things related to object introspection
- #-------------------------------------------------------------------------
-
- def _ofind(self, oname, namespaces=None):
- """Find an object in the available namespaces.
-
- self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
-
- Has special code to detect magic functions.
- """
- oname = oname.strip()
- #print '1- oname: <%r>' % oname # dbg
- if not oname.startswith(ESC_MAGIC) and \
- not oname.startswith(ESC_MAGIC2) and \
- not py3compat.isidentifier(oname, dotted=True):
- return dict(found=False)
-
- if namespaces is None:
- # Namespaces to search in:
- # Put them in a list. The order is important so that we
- # find things in the same order that Python finds them.
- namespaces = [ ('Interactive', self.user_ns),
- ('Interactive (global)', self.user_global_ns),
- ('Python builtin', builtin_mod.__dict__),
- ]
-
- # initialize results to 'null'
- found = False; obj = None; ospace = None;
- ismagic = False; isalias = False; parent = None
-
- # We need to special-case 'print', which as of python2.6 registers as a
- # function but should only be treated as one if print_function was
- # loaded with a future import. In this case, just bail.
- if (oname == 'print' and not py3compat.PY3 and not \
- (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
- return {'found':found, 'obj':obj, 'namespace':ospace,
- 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
-
- # Look for the given name by splitting it in parts. If the head is
- # found, then we look for all the remaining parts as members, and only
- # declare success if we can find them all.
- oname_parts = oname.split('.')
- oname_head, oname_rest = oname_parts[0],oname_parts[1:]
- for nsname,ns in namespaces:
- try:
- obj = ns[oname_head]
- except KeyError:
- continue
- else:
- #print 'oname_rest:', oname_rest # dbg
- for idx, part in enumerate(oname_rest):
- try:
- parent = obj
- # The last part is looked up in a special way to avoid
- # descriptor invocation as it may raise or have side
- # effects.
- if idx == len(oname_rest) - 1:
- obj = self._getattr_property(obj, part)
- else:
- obj = getattr(obj, part)
- except:
- # Blanket except b/c some badly implemented objects
- # allow __getattr__ to raise exceptions other than
- # AttributeError, which then crashes IPython.
- break
- else:
- # If we finish the for loop (no break), we got all members
- found = True
- ospace = nsname
- break # namespace loop
-
- # Try to see if it's magic
- if not found:
- obj = None
- if oname.startswith(ESC_MAGIC2):
- oname = oname.lstrip(ESC_MAGIC2)
- obj = self.find_cell_magic(oname)
- elif oname.startswith(ESC_MAGIC):
- oname = oname.lstrip(ESC_MAGIC)
- obj = self.find_line_magic(oname)
- else:
- # search without prefix, so run? will find %run?
- obj = self.find_line_magic(oname)
- if obj is None:
- obj = self.find_cell_magic(oname)
- if obj is not None:
- found = True
- ospace = 'IPython internal'
- ismagic = True
- isalias = isinstance(obj, Alias)
-
- # Last try: special-case some literals like '', [], {}, etc:
- if not found and oname_head in ["''",'""','[]','{}','()']:
- obj = eval(oname_head)
- found = True
- ospace = 'Interactive'
-
- return {'found':found, 'obj':obj, 'namespace':ospace,
- 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
-
- @staticmethod
- def _getattr_property(obj, attrname):
- """Property-aware getattr to use in object finding.
-
- If attrname represents a property, return it unevaluated (in case it has
- side effects or raises an error.
-
- """
- if not isinstance(obj, type):
- try:
- # `getattr(type(obj), attrname)` is not guaranteed to return
- # `obj`, but does so for property:
- #
- # property.__get__(self, None, cls) -> self
- #
- # The universal alternative is to traverse the mro manually
- # searching for attrname in class dicts.
- attr = getattr(type(obj), attrname)
- except AttributeError:
- pass
- else:
- # This relies on the fact that data descriptors (with both
- # __get__ & __set__ magic methods) take precedence over
- # instance-level attributes:
- #
- # class A(object):
- # @property
- # def foobar(self): return 123
- # a = A()
- # a.__dict__['foobar'] = 345
- # a.foobar # == 123
- #
- # So, a property may be returned right away.
- if isinstance(attr, property):
- return attr
-
- # Nothing helped, fall back.
- return getattr(obj, attrname)
-
- def _object_find(self, oname, namespaces=None):
- """Find an object and return a struct with info about it."""
- return Struct(self._ofind(oname, namespaces))
-
- def _inspect(self, meth, oname, namespaces=None, **kw):
- """Generic interface to the inspector system.
-
+ Parameters
+ ----------
+ variables : dict
+ A dictionary mapping object names (as strings) to the objects.
+ """
+ for name, obj in iteritems(variables):
+ if name in self.user_ns and self.user_ns[name] is obj:
+ del self.user_ns[name]
+ self.user_ns_hidden.pop(name, None)
+
+ #-------------------------------------------------------------------------
+ # Things related to object introspection
+ #-------------------------------------------------------------------------
+
+ def _ofind(self, oname, namespaces=None):
+ """Find an object in the available namespaces.
+
+ self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
+
+ Has special code to detect magic functions.
+ """
+ oname = oname.strip()
+ #print '1- oname: <%r>' % oname # dbg
+ if not oname.startswith(ESC_MAGIC) and \
+ not oname.startswith(ESC_MAGIC2) and \
+ not py3compat.isidentifier(oname, dotted=True):
+ return dict(found=False)
+
+ if namespaces is None:
+ # Namespaces to search in:
+ # Put them in a list. The order is important so that we
+ # find things in the same order that Python finds them.
+ namespaces = [ ('Interactive', self.user_ns),
+ ('Interactive (global)', self.user_global_ns),
+ ('Python builtin', builtin_mod.__dict__),
+ ]
+
+ # initialize results to 'null'
+ found = False; obj = None; ospace = None;
+ ismagic = False; isalias = False; parent = None
+
+ # We need to special-case 'print', which as of python2.6 registers as a
+ # function but should only be treated as one if print_function was
+ # loaded with a future import. In this case, just bail.
+ if (oname == 'print' and not py3compat.PY3 and not \
+ (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
+ return {'found':found, 'obj':obj, 'namespace':ospace,
+ 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
+
+ # Look for the given name by splitting it in parts. If the head is
+ # found, then we look for all the remaining parts as members, and only
+ # declare success if we can find them all.
+ oname_parts = oname.split('.')
+ oname_head, oname_rest = oname_parts[0],oname_parts[1:]
+ for nsname,ns in namespaces:
+ try:
+ obj = ns[oname_head]
+ except KeyError:
+ continue
+ else:
+ #print 'oname_rest:', oname_rest # dbg
+ for idx, part in enumerate(oname_rest):
+ try:
+ parent = obj
+ # The last part is looked up in a special way to avoid
+ # descriptor invocation as it may raise or have side
+ # effects.
+ if idx == len(oname_rest) - 1:
+ obj = self._getattr_property(obj, part)
+ else:
+ obj = getattr(obj, part)
+ except:
+ # Blanket except b/c some badly implemented objects
+ # allow __getattr__ to raise exceptions other than
+ # AttributeError, which then crashes IPython.
+ break
+ else:
+ # If we finish the for loop (no break), we got all members
+ found = True
+ ospace = nsname
+ break # namespace loop
+
+ # Try to see if it's magic
+ if not found:
+ obj = None
+ if oname.startswith(ESC_MAGIC2):
+ oname = oname.lstrip(ESC_MAGIC2)
+ obj = self.find_cell_magic(oname)
+ elif oname.startswith(ESC_MAGIC):
+ oname = oname.lstrip(ESC_MAGIC)
+ obj = self.find_line_magic(oname)
+ else:
+ # search without prefix, so run? will find %run?
+ obj = self.find_line_magic(oname)
+ if obj is None:
+ obj = self.find_cell_magic(oname)
+ if obj is not None:
+ found = True
+ ospace = 'IPython internal'
+ ismagic = True
+ isalias = isinstance(obj, Alias)
+
+ # Last try: special-case some literals like '', [], {}, etc:
+ if not found and oname_head in ["''",'""','[]','{}','()']:
+ obj = eval(oname_head)
+ found = True
+ ospace = 'Interactive'
+
+ return {'found':found, 'obj':obj, 'namespace':ospace,
+ 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
+
+ @staticmethod
+ def _getattr_property(obj, attrname):
+ """Property-aware getattr to use in object finding.
+
+ If attrname represents a property, return it unevaluated (in case it has
+ side effects or raises an error.
+
+ """
+ if not isinstance(obj, type):
+ try:
+ # `getattr(type(obj), attrname)` is not guaranteed to return
+ # `obj`, but does so for property:
+ #
+ # property.__get__(self, None, cls) -> self
+ #
+ # The universal alternative is to traverse the mro manually
+ # searching for attrname in class dicts.
+ attr = getattr(type(obj), attrname)
+ except AttributeError:
+ pass
+ else:
+ # This relies on the fact that data descriptors (with both
+ # __get__ & __set__ magic methods) take precedence over
+ # instance-level attributes:
+ #
+ # class A(object):
+ # @property
+ # def foobar(self): return 123
+ # a = A()
+ # a.__dict__['foobar'] = 345
+ # a.foobar # == 123
+ #
+ # So, a property may be returned right away.
+ if isinstance(attr, property):
+ return attr
+
+ # Nothing helped, fall back.
+ return getattr(obj, attrname)
+
+ def _object_find(self, oname, namespaces=None):
+ """Find an object and return a struct with info about it."""
+ return Struct(self._ofind(oname, namespaces))
+
+ def _inspect(self, meth, oname, namespaces=None, **kw):
+ """Generic interface to the inspector system.
+
This function is meant to be called by pdef, pdoc & friends.
"""
- info = self._object_find(oname, namespaces)
+ info = self._object_find(oname, namespaces)
docformat = sphinxify if self.sphinxify_docstring else None
- if info.found:
- pmethod = getattr(self.inspector, meth)
+ if info.found:
+ pmethod = getattr(self.inspector, meth)
# TODO: only apply format_screen to the plain/text repr of the mime
# bundle.
formatter = format_screen if info.ismagic else docformat
- if meth == 'pdoc':
- pmethod(info.obj, oname, formatter)
- elif meth == 'pinfo':
+ if meth == 'pdoc':
+ pmethod(info.obj, oname, formatter)
+ elif meth == 'pinfo':
pmethod(info.obj, oname, formatter, info,
enable_html_pager=self.enable_html_pager, **kw)
- else:
- pmethod(info.obj, oname)
- else:
- print('Object `%s` not found.' % oname)
- return 'not found' # so callers can take other action
-
- def object_inspect(self, oname, detail_level=0):
- """Get object info about oname"""
- with self.builtin_trap:
- info = self._object_find(oname)
- if info.found:
- return self.inspector.info(info.obj, oname, info=info,
- detail_level=detail_level
- )
- else:
- return oinspect.object_info(name=oname, found=False)
-
- def object_inspect_text(self, oname, detail_level=0):
- """Get object info as formatted text"""
+ else:
+ pmethod(info.obj, oname)
+ else:
+ print('Object `%s` not found.' % oname)
+ return 'not found' # so callers can take other action
+
+ def object_inspect(self, oname, detail_level=0):
+ """Get object info about oname"""
+ with self.builtin_trap:
+ info = self._object_find(oname)
+ if info.found:
+ return self.inspector.info(info.obj, oname, info=info,
+ detail_level=detail_level
+ )
+ else:
+ return oinspect.object_info(name=oname, found=False)
+
+ def object_inspect_text(self, oname, detail_level=0):
+ """Get object info as formatted text"""
return self.object_inspect_mime(oname, detail_level)['text/plain']
def object_inspect_mime(self, oname, detail_level=0):
@@ -1561,1345 +1561,1345 @@ class InteractiveShell(SingletonConfigurable):
A mimebundle is a dictionary, keyed by mime-type.
It must always have the key `'text/plain'`.
"""
- with self.builtin_trap:
- info = self._object_find(oname)
- if info.found:
+ with self.builtin_trap:
+ info = self._object_find(oname)
+ if info.found:
return self.inspector._get_info(info.obj, oname, info=info,
- detail_level=detail_level
- )
- else:
- raise KeyError(oname)
-
- #-------------------------------------------------------------------------
- # Things related to history management
- #-------------------------------------------------------------------------
-
- def init_history(self):
- """Sets up the command history, and starts regular autosaves."""
- self.history_manager = HistoryManager(shell=self, parent=self)
- self.configurables.append(self.history_manager)
-
- #-------------------------------------------------------------------------
- # Things related to exception handling and tracebacks (not debugging)
- #-------------------------------------------------------------------------
-
+ detail_level=detail_level
+ )
+ else:
+ raise KeyError(oname)
+
+ #-------------------------------------------------------------------------
+ # Things related to history management
+ #-------------------------------------------------------------------------
+
+ def init_history(self):
+ """Sets up the command history, and starts regular autosaves."""
+ self.history_manager = HistoryManager(shell=self, parent=self)
+ self.configurables.append(self.history_manager)
+
+ #-------------------------------------------------------------------------
+ # Things related to exception handling and tracebacks (not debugging)
+ #-------------------------------------------------------------------------
+
debugger_cls = Pdb
- def init_traceback_handlers(self, custom_exceptions):
- # Syntax error handler.
- self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
-
- # The interactive one is initialized with an offset, meaning we always
- # want to remove the topmost item in the traceback, which is our own
- # internal code. Valid modes: ['Plain','Context','Verbose']
- self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
- color_scheme='NoColor',
- tb_offset = 1,
+ def init_traceback_handlers(self, custom_exceptions):
+ # Syntax error handler.
+ self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
+
+ # The interactive one is initialized with an offset, meaning we always
+ # want to remove the topmost item in the traceback, which is our own
+ # internal code. Valid modes: ['Plain','Context','Verbose']
+ self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
+ color_scheme='NoColor',
+ tb_offset = 1,
check_cache=check_linecache_ipython,
debugger_cls=self.debugger_cls)
-
- # The instance will store a pointer to the system-wide exception hook,
- # so that runtime code (such as magics) can access it. This is because
- # during the read-eval loop, it may get temporarily overwritten.
- self.sys_excepthook = sys.excepthook
-
- # and add any custom exception handlers the user may have specified
- self.set_custom_exc(*custom_exceptions)
-
- # Set the exception mode
- self.InteractiveTB.set_mode(mode=self.xmode)
-
- def set_custom_exc(self, exc_tuple, handler):
+
+ # The instance will store a pointer to the system-wide exception hook,
+ # so that runtime code (such as magics) can access it. This is because
+ # during the read-eval loop, it may get temporarily overwritten.
+ self.sys_excepthook = sys.excepthook
+
+ # and add any custom exception handlers the user may have specified
+ self.set_custom_exc(*custom_exceptions)
+
+ # Set the exception mode
+ self.InteractiveTB.set_mode(mode=self.xmode)
+
+ def set_custom_exc(self, exc_tuple, handler):
"""set_custom_exc(exc_tuple, handler)
-
- Set a custom exception handler, which will be called if any of the
- exceptions in exc_tuple occur in the mainloop (specifically, in the
- run_code() method).
-
- Parameters
- ----------
-
- exc_tuple : tuple of exception classes
- A *tuple* of exception classes, for which to call the defined
- handler. It is very important that you use a tuple, and NOT A
- LIST here, because of the way Python's except statement works. If
- you only want to trap a single exception, use a singleton tuple::
-
- exc_tuple == (MyCustomException,)
-
- handler : callable
- handler must have the following signature::
-
- def my_handler(self, etype, value, tb, tb_offset=None):
- ...
- return structured_traceback
-
- Your handler must return a structured traceback (a list of strings),
- or None.
-
- This will be made into an instance method (via types.MethodType)
- of IPython itself, and it will be called if any of the exceptions
- listed in the exc_tuple are caught. If the handler is None, an
- internal basic one is used, which just prints basic info.
-
- To protect IPython from crashes, if your handler ever raises an
- exception or returns an invalid result, it will be immediately
- disabled.
-
- WARNING: by putting in your own exception handler into IPython's main
- execution loop, you run a very good chance of nasty crashes. This
- facility should only be used if you really know what you are doing."""
-
- assert type(exc_tuple)==type(()) , \
- "The custom exceptions must be given AS A TUPLE."
-
+
+ Set a custom exception handler, which will be called if any of the
+ exceptions in exc_tuple occur in the mainloop (specifically, in the
+ run_code() method).
+
+ Parameters
+ ----------
+
+ exc_tuple : tuple of exception classes
+ A *tuple* of exception classes, for which to call the defined
+ handler. It is very important that you use a tuple, and NOT A
+ LIST here, because of the way Python's except statement works. If
+ you only want to trap a single exception, use a singleton tuple::
+
+ exc_tuple == (MyCustomException,)
+
+ handler : callable
+ handler must have the following signature::
+
+ def my_handler(self, etype, value, tb, tb_offset=None):
+ ...
+ return structured_traceback
+
+ Your handler must return a structured traceback (a list of strings),
+ or None.
+
+ This will be made into an instance method (via types.MethodType)
+ of IPython itself, and it will be called if any of the exceptions
+ listed in the exc_tuple are caught. If the handler is None, an
+ internal basic one is used, which just prints basic info.
+
+ To protect IPython from crashes, if your handler ever raises an
+ exception or returns an invalid result, it will be immediately
+ disabled.
+
+ WARNING: by putting in your own exception handler into IPython's main
+ execution loop, you run a very good chance of nasty crashes. This
+ facility should only be used if you really know what you are doing."""
+
+ assert type(exc_tuple)==type(()) , \
+ "The custom exceptions must be given AS A TUPLE."
+
def dummy_handler(self, etype, value, tb, tb_offset=None):
- print('*** Simple custom exception handler ***')
- print('Exception type :',etype)
- print('Exception value:',value)
- print('Traceback :',tb)
- #print 'Source code :','\n'.join(self.buffer)
+ print('*** Simple custom exception handler ***')
+ print('Exception type :',etype)
+ print('Exception value:',value)
+ print('Traceback :',tb)
+ #print 'Source code :','\n'.join(self.buffer)
- def validate_stb(stb):
- """validate structured traceback return type
+ def validate_stb(stb):
+ """validate structured traceback return type
- return type of CustomTB *should* be a list of strings, but allow
- single strings or None, which are harmless.
+ return type of CustomTB *should* be a list of strings, but allow
+ single strings or None, which are harmless.
- This function will *always* return a list of strings,
- and will raise a TypeError if stb is inappropriate.
- """
- msg = "CustomTB must return list of strings, not %r" % stb
- if stb is None:
- return []
- elif isinstance(stb, string_types):
- return [stb]
- elif not isinstance(stb, list):
- raise TypeError(msg)
- # it's a list
- for line in stb:
- # check every element
- if not isinstance(line, string_types):
- raise TypeError(msg)
- return stb
-
- if handler is None:
- wrapped = dummy_handler
- else:
- def wrapped(self,etype,value,tb,tb_offset=None):
- """wrap CustomTB handler, to protect IPython from user code
+ This function will *always* return a list of strings,
+ and will raise a TypeError if stb is inappropriate.
+ """
+ msg = "CustomTB must return list of strings, not %r" % stb
+ if stb is None:
+ return []
+ elif isinstance(stb, string_types):
+ return [stb]
+ elif not isinstance(stb, list):
+ raise TypeError(msg)
+ # it's a list
+ for line in stb:
+ # check every element
+ if not isinstance(line, string_types):
+ raise TypeError(msg)
+ return stb
+
+ if handler is None:
+ wrapped = dummy_handler
+ else:
+ def wrapped(self,etype,value,tb,tb_offset=None):
+ """wrap CustomTB handler, to protect IPython from user code
- This makes it harder (but not impossible) for custom exception
- handlers to crash IPython.
- """
- try:
- stb = handler(self,etype,value,tb,tb_offset=tb_offset)
- return validate_stb(stb)
- except:
- # clear custom handler immediately
- self.set_custom_exc((), None)
+ This makes it harder (but not impossible) for custom exception
+ handlers to crash IPython.
+ """
+ try:
+ stb = handler(self,etype,value,tb,tb_offset=tb_offset)
+ return validate_stb(stb)
+ except:
+ # clear custom handler immediately
+ self.set_custom_exc((), None)
print("Custom TB Handler failed, unregistering", file=sys.stderr)
- # show the exception in handler first
- stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
+ # show the exception in handler first
+ stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
print(self.InteractiveTB.stb2text(stb))
print("The original exception:")
- stb = self.InteractiveTB.structured_traceback(
- (etype,value,tb), tb_offset=tb_offset
- )
- return stb
-
- self.CustomTB = types.MethodType(wrapped,self)
- self.custom_exceptions = exc_tuple
-
- def excepthook(self, etype, value, tb):
- """One more defense for GUI apps that call sys.excepthook.
-
- GUI frameworks like wxPython trap exceptions and call
- sys.excepthook themselves. I guess this is a feature that
- enables them to keep running after exceptions that would
- otherwise kill their mainloop. This is a bother for IPython
- which excepts to catch all of the program exceptions with a try:
- except: statement.
-
- Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
- any app directly invokes sys.excepthook, it will look to the user like
- IPython crashed. In order to work around this, we can disable the
- CrashHandler and replace it with this excepthook instead, which prints a
- regular traceback using our InteractiveTB. In this fashion, apps which
- call sys.excepthook will generate a regular-looking exception from
- IPython, and the CrashHandler will only be triggered by real IPython
- crashes.
-
- This hook should be used sparingly, only in places which are not likely
- to be true IPython errors.
- """
- self.showtraceback((etype, value, tb), tb_offset=0)
-
- def _get_exc_info(self, exc_tuple=None):
- """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
+ stb = self.InteractiveTB.structured_traceback(
+ (etype,value,tb), tb_offset=tb_offset
+ )
+ return stb
+
+ self.CustomTB = types.MethodType(wrapped,self)
+ self.custom_exceptions = exc_tuple
+
+ def excepthook(self, etype, value, tb):
+ """One more defense for GUI apps that call sys.excepthook.
+
+ GUI frameworks like wxPython trap exceptions and call
+ sys.excepthook themselves. I guess this is a feature that
+ enables them to keep running after exceptions that would
+ otherwise kill their mainloop. This is a bother for IPython
+ which excepts to catch all of the program exceptions with a try:
+ except: statement.
+
+ Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
+ any app directly invokes sys.excepthook, it will look to the user like
+ IPython crashed. In order to work around this, we can disable the
+ CrashHandler and replace it with this excepthook instead, which prints a
+ regular traceback using our InteractiveTB. In this fashion, apps which
+ call sys.excepthook will generate a regular-looking exception from
+ IPython, and the CrashHandler will only be triggered by real IPython
+ crashes.
+
+ This hook should be used sparingly, only in places which are not likely
+ to be true IPython errors.
+ """
+ self.showtraceback((etype, value, tb), tb_offset=0)
+
+ def _get_exc_info(self, exc_tuple=None):
+ """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
- Ensures sys.last_type,value,traceback hold the exc_info we found,
- from whichever source.
+ Ensures sys.last_type,value,traceback hold the exc_info we found,
+ from whichever source.
- raises ValueError if none of these contain any information
- """
- if exc_tuple is None:
- etype, value, tb = sys.exc_info()
- else:
- etype, value, tb = exc_tuple
-
- if etype is None:
- if hasattr(sys, 'last_type'):
- etype, value, tb = sys.last_type, sys.last_value, \
- sys.last_traceback
+ raises ValueError if none of these contain any information
+ """
+ if exc_tuple is None:
+ etype, value, tb = sys.exc_info()
+ else:
+ etype, value, tb = exc_tuple
+
+ if etype is None:
+ if hasattr(sys, 'last_type'):
+ etype, value, tb = sys.last_type, sys.last_value, \
+ sys.last_traceback
- if etype is None:
- raise ValueError("No exception to find")
+ if etype is None:
+ raise ValueError("No exception to find")
- # Now store the exception info in sys.last_type etc.
- # WARNING: these variables are somewhat deprecated and not
- # necessarily safe to use in a threaded environment, but tools
- # like pdb depend on their existence, so let's set them. If we
- # find problems in the field, we'll need to revisit their use.
- sys.last_type = etype
- sys.last_value = value
- sys.last_traceback = tb
+ # Now store the exception info in sys.last_type etc.
+ # WARNING: these variables are somewhat deprecated and not
+ # necessarily safe to use in a threaded environment, but tools
+ # like pdb depend on their existence, so let's set them. If we
+ # find problems in the field, we'll need to revisit their use.
+ sys.last_type = etype
+ sys.last_value = value
+ sys.last_traceback = tb
- return etype, value, tb
+ return etype, value, tb
- def show_usage_error(self, exc):
- """Show a short message for UsageErrors
+ def show_usage_error(self, exc):
+ """Show a short message for UsageErrors
- These are special exceptions that shouldn't show a traceback.
- """
+ These are special exceptions that shouldn't show a traceback.
+ """
print("UsageError: %s" % exc, file=sys.stderr)
- def get_exception_only(self, exc_tuple=None):
- """
- Return as a string (ending with a newline) the exception that
- just occurred, without any traceback.
- """
- etype, value, tb = self._get_exc_info(exc_tuple)
- msg = traceback.format_exception_only(etype, value)
- return ''.join(msg)
-
- def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
- exception_only=False):
- """Display the exception that just occurred.
-
- If nothing is known about the exception, this is the method which
- should be used throughout the code for presenting user tracebacks,
- rather than directly invoking the InteractiveTB object.
-
- A specific showsyntaxerror() also exists, but this method can take
- care of calling it if needed, so unless you are explicitly catching a
- SyntaxError exception, don't try to analyze the stack manually and
- simply call this method."""
-
- try:
- try:
- etype, value, tb = self._get_exc_info(exc_tuple)
- except ValueError:
+ def get_exception_only(self, exc_tuple=None):
+ """
+ Return as a string (ending with a newline) the exception that
+ just occurred, without any traceback.
+ """
+ etype, value, tb = self._get_exc_info(exc_tuple)
+ msg = traceback.format_exception_only(etype, value)
+ return ''.join(msg)
+
+ def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
+ exception_only=False):
+ """Display the exception that just occurred.
+
+ If nothing is known about the exception, this is the method which
+ should be used throughout the code for presenting user tracebacks,
+ rather than directly invoking the InteractiveTB object.
+
+ A specific showsyntaxerror() also exists, but this method can take
+ care of calling it if needed, so unless you are explicitly catching a
+ SyntaxError exception, don't try to analyze the stack manually and
+ simply call this method."""
+
+ try:
+ try:
+ etype, value, tb = self._get_exc_info(exc_tuple)
+ except ValueError:
print('No traceback available to show.', file=sys.stderr)
- return
+ return
- if issubclass(etype, SyntaxError):
- # Though this won't be called by syntax errors in the input
- # line, there may be SyntaxError cases with imported code.
- self.showsyntaxerror(filename)
- elif etype is UsageError:
- self.show_usage_error(value)
- else:
- if exception_only:
- stb = ['An exception has occurred, use %tb to see '
- 'the full traceback.\n']
- stb.extend(self.InteractiveTB.get_exception_only(etype,
- value))
- else:
- try:
- # Exception classes can customise their traceback - we
- # use this in IPython.parallel for exceptions occurring
- # in the engines. This should return a list of strings.
- stb = value._render_traceback_()
- except Exception:
- stb = self.InteractiveTB.structured_traceback(etype,
- value, tb, tb_offset=tb_offset)
-
- self._showtraceback(etype, value, stb)
- if self.call_pdb:
- # drop into debugger
- self.debugger(force=True)
- return
-
- # Actually show the traceback
- self._showtraceback(etype, value, stb)
-
- except KeyboardInterrupt:
+ if issubclass(etype, SyntaxError):
+ # Though this won't be called by syntax errors in the input
+ # line, there may be SyntaxError cases with imported code.
+ self.showsyntaxerror(filename)
+ elif etype is UsageError:
+ self.show_usage_error(value)
+ else:
+ if exception_only:
+ stb = ['An exception has occurred, use %tb to see '
+ 'the full traceback.\n']
+ stb.extend(self.InteractiveTB.get_exception_only(etype,
+ value))
+ else:
+ try:
+ # Exception classes can customise their traceback - we
+ # use this in IPython.parallel for exceptions occurring
+ # in the engines. This should return a list of strings.
+ stb = value._render_traceback_()
+ except Exception:
+ stb = self.InteractiveTB.structured_traceback(etype,
+ value, tb, tb_offset=tb_offset)
+
+ self._showtraceback(etype, value, stb)
+ if self.call_pdb:
+ # drop into debugger
+ self.debugger(force=True)
+ return
+
+ # Actually show the traceback
+ self._showtraceback(etype, value, stb)
+
+ except KeyboardInterrupt:
print('\n' + self.get_exception_only(), file=sys.stderr)
-
- def _showtraceback(self, etype, evalue, stb):
- """Actually show a traceback.
-
- Subclasses may override this method to put the traceback on a different
- place, like a side channel.
- """
+
+ def _showtraceback(self, etype, evalue, stb):
+ """Actually show a traceback.
+
+ Subclasses may override this method to put the traceback on a different
+ place, like a side channel.
+ """
print(self.InteractiveTB.stb2text(stb))
-
- def showsyntaxerror(self, filename=None):
- """Display the syntax error that just occurred.
-
- This doesn't display a stack trace because there isn't one.
-
- If a filename is given, it is stuffed in the exception instead
- of what was there before (because Python's parser always uses
- "<string>" when reading from a string).
- """
- etype, value, last_traceback = self._get_exc_info()
-
- if filename and issubclass(etype, SyntaxError):
- try:
- value.filename = filename
- except:
- # Not the format we expect; leave it alone
- pass
+
+ def showsyntaxerror(self, filename=None):
+ """Display the syntax error that just occurred.
+
+ This doesn't display a stack trace because there isn't one.
+
+ If a filename is given, it is stuffed in the exception instead
+ of what was there before (because Python's parser always uses
+ "<string>" when reading from a string).
+ """
+ etype, value, last_traceback = self._get_exc_info()
+
+ if filename and issubclass(etype, SyntaxError):
+ try:
+ value.filename = filename
+ except:
+ # Not the format we expect; leave it alone
+ pass
- stb = self.SyntaxTB.structured_traceback(etype, value, [])
- self._showtraceback(etype, value, stb)
-
- # This is overridden in TerminalInteractiveShell to show a message about
- # the %paste magic.
- def showindentationerror(self):
- """Called by run_cell when there's an IndentationError in code entered
- at the prompt.
-
- This is overridden in TerminalInteractiveShell to show a message about
- the %paste magic."""
- self.showsyntaxerror()
-
- #-------------------------------------------------------------------------
- # Things related to readline
- #-------------------------------------------------------------------------
-
- def init_readline(self):
+ stb = self.SyntaxTB.structured_traceback(etype, value, [])
+ self._showtraceback(etype, value, stb)
+
+ # This is overridden in TerminalInteractiveShell to show a message about
+ # the %paste magic.
+ def showindentationerror(self):
+ """Called by run_cell when there's an IndentationError in code entered
+ at the prompt.
+
+ This is overridden in TerminalInteractiveShell to show a message about
+ the %paste magic."""
+ self.showsyntaxerror()
+
+ #-------------------------------------------------------------------------
+ # Things related to readline
+ #-------------------------------------------------------------------------
+
+ def init_readline(self):
"""DEPRECATED
Moved to terminal subclass, here only to simplify the init logic."""
- # Set a number of methods that depend on readline to be no-op
+ # Set a number of methods that depend on readline to be no-op
warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
DeprecationWarning, stacklevel=2)
- self.set_custom_completer = no_op
-
- @skip_doctest
- def set_next_input(self, s, replace=False):
- """ Sets the 'default' input string for the next command line.
-
- Example::
-
- In [1]: _ip.set_next_input("Hello Word")
- In [2]: Hello Word_ # cursor is here
- """
- self.rl_next_input = py3compat.cast_bytes_py2(s)
-
- def _indent_current_str(self):
- """return the current level of indentation as a string"""
- return self.input_splitter.indent_spaces * ' '
-
- #-------------------------------------------------------------------------
- # Things related to text completion
- #-------------------------------------------------------------------------
-
- def init_completer(self):
- """Initialize the completion machinery.
-
- This creates completion machinery that can be used by client code,
- either interactively in-process (typically triggered by the readline
- library), programmatically (such as in test suites) or out-of-process
- (typically over the network by remote frontends).
- """
- from IPython.core.completer import IPCompleter
- from IPython.core.completerlib import (module_completer,
- magic_run_completer, cd_completer, reset_completer)
-
- self.Completer = IPCompleter(shell=self,
- namespace=self.user_ns,
- global_namespace=self.user_global_ns,
+ self.set_custom_completer = no_op
+
+ @skip_doctest
+ def set_next_input(self, s, replace=False):
+ """ Sets the 'default' input string for the next command line.
+
+ Example::
+
+ In [1]: _ip.set_next_input("Hello Word")
+ In [2]: Hello Word_ # cursor is here
+ """
+ self.rl_next_input = py3compat.cast_bytes_py2(s)
+
+ def _indent_current_str(self):
+ """return the current level of indentation as a string"""
+ return self.input_splitter.indent_spaces * ' '
+
+ #-------------------------------------------------------------------------
+ # Things related to text completion
+ #-------------------------------------------------------------------------
+
+ def init_completer(self):
+ """Initialize the completion machinery.
+
+ This creates completion machinery that can be used by client code,
+ either interactively in-process (typically triggered by the readline
+ library), programmatically (such as in test suites) or out-of-process
+ (typically over the network by remote frontends).
+ """
+ from IPython.core.completer import IPCompleter
+ from IPython.core.completerlib import (module_completer,
+ magic_run_completer, cd_completer, reset_completer)
+
+ self.Completer = IPCompleter(shell=self,
+ namespace=self.user_ns,
+ global_namespace=self.user_global_ns,
use_readline=False,
- parent=self,
- )
- self.configurables.append(self.Completer)
-
- # Add custom completers to the basic ones built into IPCompleter
- sdisp = self.strdispatchers.get('complete_command', StrDispatch())
- self.strdispatchers['complete_command'] = sdisp
- self.Completer.custom_completers = sdisp
-
- self.set_hook('complete_command', module_completer, str_key = 'import')
- self.set_hook('complete_command', module_completer, str_key = 'from')
- self.set_hook('complete_command', module_completer, str_key = '%aimport')
- self.set_hook('complete_command', magic_run_completer, str_key = '%run')
- self.set_hook('complete_command', cd_completer, str_key = '%cd')
- self.set_hook('complete_command', reset_completer, str_key = '%reset')
-
-
+ parent=self,
+ )
+ self.configurables.append(self.Completer)
+
+ # Add custom completers to the basic ones built into IPCompleter
+ sdisp = self.strdispatchers.get('complete_command', StrDispatch())
+ self.strdispatchers['complete_command'] = sdisp
+ self.Completer.custom_completers = sdisp
+
+ self.set_hook('complete_command', module_completer, str_key = 'import')
+ self.set_hook('complete_command', module_completer, str_key = 'from')
+ self.set_hook('complete_command', module_completer, str_key = '%aimport')
+ self.set_hook('complete_command', magic_run_completer, str_key = '%run')
+ self.set_hook('complete_command', cd_completer, str_key = '%cd')
+ self.set_hook('complete_command', reset_completer, str_key = '%reset')
+
+
@skip_doctest_py2
- def complete(self, text, line=None, cursor_pos=None):
- """Return the completed text and a list of completions.
-
- Parameters
- ----------
-
- text : string
- A string of text to be completed on. It can be given as empty and
- instead a line/position pair are given. In this case, the
- completer itself will split the line like readline does.
-
- line : string, optional
- The complete line that text is part of.
-
- cursor_pos : int, optional
- The position of the cursor on the input line.
-
- Returns
- -------
- text : string
- The actual text that was completed.
-
- matches : list
- A sorted list with all possible completions.
-
- The optional arguments allow the completion to take more context into
- account, and are part of the low-level completion API.
-
- This is a wrapper around the completion mechanism, similar to what
- readline does at the command line when the TAB key is hit. By
- exposing it as a method, it can be used by other non-readline
- environments (such as GUIs) for text completion.
-
- Simple usage example:
-
- In [1]: x = 'hello'
-
- In [2]: _ip.complete('x.l')
- Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
- """
-
- # Inject names into __builtin__ so we can complete on the added names.
- with self.builtin_trap:
- return self.Completer.complete(text, line, cursor_pos)
-
- def set_custom_completer(self, completer, pos=0):
- """Adds a new custom completer function.
-
- The position argument (defaults to 0) is the index in the completers
- list where you want the completer to be inserted."""
-
- newcomp = types.MethodType(completer,self.Completer)
- self.Completer.matchers.insert(pos,newcomp)
-
- def set_completer_frame(self, frame=None):
- """Set the frame of the completer."""
- if frame:
- self.Completer.namespace = frame.f_locals
- self.Completer.global_namespace = frame.f_globals
- else:
- self.Completer.namespace = self.user_ns
- self.Completer.global_namespace = self.user_global_ns
-
- #-------------------------------------------------------------------------
- # Things related to magics
- #-------------------------------------------------------------------------
-
- def init_magics(self):
- from IPython.core import magics as m
- self.magics_manager = magic.MagicsManager(shell=self,
- parent=self,
- user_magics=m.UserMagics(self))
- self.configurables.append(self.magics_manager)
-
- # Expose as public API from the magics manager
- self.register_magics = self.magics_manager.register
-
- self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
+ def complete(self, text, line=None, cursor_pos=None):
+ """Return the completed text and a list of completions.
+
+ Parameters
+ ----------
+
+ text : string
+ A string of text to be completed on. It can be given as empty and
+ instead a line/position pair are given. In this case, the
+ completer itself will split the line like readline does.
+
+ line : string, optional
+ The complete line that text is part of.
+
+ cursor_pos : int, optional
+ The position of the cursor on the input line.
+
+ Returns
+ -------
+ text : string
+ The actual text that was completed.
+
+ matches : list
+ A sorted list with all possible completions.
+
+ The optional arguments allow the completion to take more context into
+ account, and are part of the low-level completion API.
+
+ This is a wrapper around the completion mechanism, similar to what
+ readline does at the command line when the TAB key is hit. By
+ exposing it as a method, it can be used by other non-readline
+ environments (such as GUIs) for text completion.
+
+ Simple usage example:
+
+ In [1]: x = 'hello'
+
+ In [2]: _ip.complete('x.l')
+ Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
+ """
+
+ # Inject names into __builtin__ so we can complete on the added names.
+ with self.builtin_trap:
+ return self.Completer.complete(text, line, cursor_pos)
+
+ def set_custom_completer(self, completer, pos=0):
+ """Adds a new custom completer function.
+
+ The position argument (defaults to 0) is the index in the completers
+ list where you want the completer to be inserted."""
+
+ newcomp = types.MethodType(completer,self.Completer)
+ self.Completer.matchers.insert(pos,newcomp)
+
+ def set_completer_frame(self, frame=None):
+ """Set the frame of the completer."""
+ if frame:
+ self.Completer.namespace = frame.f_locals
+ self.Completer.global_namespace = frame.f_globals
+ else:
+ self.Completer.namespace = self.user_ns
+ self.Completer.global_namespace = self.user_global_ns
+
+ #-------------------------------------------------------------------------
+ # Things related to magics
+ #-------------------------------------------------------------------------
+
+ def init_magics(self):
+ from IPython.core import magics as m
+ self.magics_manager = magic.MagicsManager(shell=self,
+ parent=self,
+ user_magics=m.UserMagics(self))
+ self.configurables.append(self.magics_manager)
+
+ # Expose as public API from the magics manager
+ self.register_magics = self.magics_manager.register
+
+ self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
- m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
- m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
- )
-
- # Register Magic Aliases
- mman = self.magics_manager
- # FIXME: magic aliases should be defined by the Magics classes
- # or in MagicsManager, not here
- mman.register_alias('ed', 'edit')
- mman.register_alias('hist', 'history')
- mman.register_alias('rep', 'recall')
- mman.register_alias('SVG', 'svg', 'cell')
- mman.register_alias('HTML', 'html', 'cell')
- mman.register_alias('file', 'writefile', 'cell')
-
- # FIXME: Move the color initialization to the DisplayHook, which
- # should be split into a prompt manager and displayhook. We probably
- # even need a centralize colors management object.
- self.magic('colors %s' % self.colors)
+ m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
+ m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
+ )
+
+ # Register Magic Aliases
+ mman = self.magics_manager
+ # FIXME: magic aliases should be defined by the Magics classes
+ # or in MagicsManager, not here
+ mman.register_alias('ed', 'edit')
+ mman.register_alias('hist', 'history')
+ mman.register_alias('rep', 'recall')
+ mman.register_alias('SVG', 'svg', 'cell')
+ mman.register_alias('HTML', 'html', 'cell')
+ mman.register_alias('file', 'writefile', 'cell')
+
+ # FIXME: Move the color initialization to the DisplayHook, which
+ # should be split into a prompt manager and displayhook. We probably
+ # even need a centralize colors management object.
+ self.magic('colors %s' % self.colors)
- # Defined here so that it's included in the documentation
- @functools.wraps(magic.MagicsManager.register_function)
- def register_magic_function(self, func, magic_kind='line', magic_name=None):
+ # Defined here so that it's included in the documentation
+ @functools.wraps(magic.MagicsManager.register_function)
+ def register_magic_function(self, func, magic_kind='line', magic_name=None):
self.magics_manager.register_function(func,
- magic_kind=magic_kind, magic_name=magic_name)
-
- def run_line_magic(self, magic_name, line):
- """Execute the given line magic.
-
- Parameters
- ----------
- magic_name : str
- Name of the desired magic function, without '%' prefix.
-
- line : str
- The rest of the input line as a single string.
- """
- fn = self.find_line_magic(magic_name)
- if fn is None:
- cm = self.find_cell_magic(magic_name)
- etpl = "Line magic function `%%%s` not found%s."
- extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
- 'did you mean that instead?)' % magic_name )
+ magic_kind=magic_kind, magic_name=magic_name)
+
+ def run_line_magic(self, magic_name, line):
+ """Execute the given line magic.
+
+ Parameters
+ ----------
+ magic_name : str
+ Name of the desired magic function, without '%' prefix.
+
+ line : str
+ The rest of the input line as a single string.
+ """
+ fn = self.find_line_magic(magic_name)
+ if fn is None:
+ cm = self.find_cell_magic(magic_name)
+ etpl = "Line magic function `%%%s` not found%s."
+ extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
+ 'did you mean that instead?)' % magic_name )
raise UsageError(etpl % (magic_name, extra))
- else:
- # Note: this is the distance in the stack to the user's frame.
- # This will need to be updated if the internal calling logic gets
- # refactored, or else we'll be expanding the wrong variables.
- stack_depth = 2
- magic_arg_s = self.var_expand(line, stack_depth)
- # Put magic args in a list so we can call with f(*a) syntax
- args = [magic_arg_s]
- kwargs = {}
- # Grab local namespace if we need it:
- if getattr(fn, "needs_local_scope", False):
- kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
- with self.builtin_trap:
- result = fn(*args,**kwargs)
- return result
-
- def run_cell_magic(self, magic_name, line, cell):
- """Execute the given cell magic.
+ else:
+ # Note: this is the distance in the stack to the user's frame.
+ # This will need to be updated if the internal calling logic gets
+ # refactored, or else we'll be expanding the wrong variables.
+ stack_depth = 2
+ magic_arg_s = self.var_expand(line, stack_depth)
+ # Put magic args in a list so we can call with f(*a) syntax
+ args = [magic_arg_s]
+ kwargs = {}
+ # Grab local namespace if we need it:
+ if getattr(fn, "needs_local_scope", False):
+ kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
+ with self.builtin_trap:
+ result = fn(*args,**kwargs)
+ return result
+
+ def run_cell_magic(self, magic_name, line, cell):
+ """Execute the given cell magic.
- Parameters
- ----------
- magic_name : str
- Name of the desired magic function, without '%' prefix.
-
- line : str
- The rest of the first input line as a single string.
-
- cell : str
- The body of the cell as a (possibly multiline) string.
- """
- fn = self.find_cell_magic(magic_name)
- if fn is None:
- lm = self.find_line_magic(magic_name)
- etpl = "Cell magic `%%{0}` not found{1}."
- extra = '' if lm is None else (' (But line magic `%{0}` exists, '
- 'did you mean that instead?)'.format(magic_name))
+ Parameters
+ ----------
+ magic_name : str
+ Name of the desired magic function, without '%' prefix.
+
+ line : str
+ The rest of the first input line as a single string.
+
+ cell : str
+ The body of the cell as a (possibly multiline) string.
+ """
+ fn = self.find_cell_magic(magic_name)
+ if fn is None:
+ lm = self.find_line_magic(magic_name)
+ etpl = "Cell magic `%%{0}` not found{1}."
+ extra = '' if lm is None else (' (But line magic `%{0}` exists, '
+ 'did you mean that instead?)'.format(magic_name))
raise UsageError(etpl.format(magic_name, extra))
- elif cell == '':
- message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
- if self.find_line_magic(magic_name) is not None:
- message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
- raise UsageError(message)
- else:
- # Note: this is the distance in the stack to the user's frame.
- # This will need to be updated if the internal calling logic gets
- # refactored, or else we'll be expanding the wrong variables.
- stack_depth = 2
- magic_arg_s = self.var_expand(line, stack_depth)
- with self.builtin_trap:
- result = fn(magic_arg_s, cell)
- return result
-
- def find_line_magic(self, magic_name):
- """Find and return a line magic by name.
-
- Returns None if the magic isn't found."""
- return self.magics_manager.magics['line'].get(magic_name)
-
- def find_cell_magic(self, magic_name):
- """Find and return a cell magic by name.
-
- Returns None if the magic isn't found."""
- return self.magics_manager.magics['cell'].get(magic_name)
-
- def find_magic(self, magic_name, magic_kind='line'):
- """Find and return a magic of the given type by name.
-
- Returns None if the magic isn't found."""
- return self.magics_manager.magics[magic_kind].get(magic_name)
-
- def magic(self, arg_s):
- """DEPRECATED. Use run_line_magic() instead.
-
- Call a magic function by name.
-
- Input: a string containing the name of the magic function to call and
- any additional arguments to be passed to the magic.
-
- magic('name -opt foo bar') is equivalent to typing at the ipython
- prompt:
-
- In[1]: %name -opt foo bar
-
- To call a magic without arguments, simply use magic('name').
-
- This provides a proper Python function to call IPython's magics in any
- valid Python code you can type at the interpreter, including loops and
- compound statements.
- """
- # TODO: should we issue a loud deprecation warning here?
- magic_name, _, magic_arg_s = arg_s.partition(' ')
- magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
- return self.run_line_magic(magic_name, magic_arg_s)
-
- #-------------------------------------------------------------------------
- # Things related to macros
- #-------------------------------------------------------------------------
-
- def define_macro(self, name, themacro):
- """Define a new macro
-
- Parameters
- ----------
- name : str
- The name of the macro.
- themacro : str or Macro
- The action to do upon invoking the macro. If a string, a new
- Macro object is created by passing the string to it.
- """
-
- from IPython.core import macro
-
- if isinstance(themacro, string_types):
- themacro = macro.Macro(themacro)
- if not isinstance(themacro, macro.Macro):
- raise ValueError('A macro must be a string or a Macro instance.')
- self.user_ns[name] = themacro
-
- #-------------------------------------------------------------------------
- # Things related to the running of system commands
- #-------------------------------------------------------------------------
-
- def system_piped(self, cmd):
- """Call the given cmd in a subprocess, piping stdout/err
-
- Parameters
- ----------
- cmd : str
- Command to execute (can not end in '&', as background processes are
- not supported. Should not be a command that expects input
- other than simple text.
- """
- if cmd.rstrip().endswith('&'):
- # this is *far* from a rigorous test
- # We do not support backgrounding processes because we either use
- # pexpect or pipes to read from. Users can always just call
- # os.system() or use ip.system=ip.system_raw
- # if they really want a background process.
- raise OSError("Background processes not supported.")
-
- # we explicitly do NOT return the subprocess status code, because
- # a non-None value would trigger :func:`sys.displayhook` calls.
- # Instead, we store the exit_code in user_ns.
- self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
-
- def system_raw(self, cmd):
- """Call the given cmd in a subprocess using os.system on Windows or
- subprocess.call using the system shell on other platforms.
-
- Parameters
- ----------
- cmd : str
- Command to execute.
- """
- cmd = self.var_expand(cmd, depth=1)
- # protect os.system from UNC paths on Windows, which it can't handle:
- if sys.platform == 'win32':
- from IPython.utils._process_win32 import AvoidUNCPath
- with AvoidUNCPath() as path:
- if path is not None:
- cmd = '"pushd %s &&"%s' % (path, cmd)
- cmd = py3compat.unicode_to_str(cmd)
- try:
- ec = os.system(cmd)
- except KeyboardInterrupt:
+ elif cell == '':
+ message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
+ if self.find_line_magic(magic_name) is not None:
+ message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
+ raise UsageError(message)
+ else:
+ # Note: this is the distance in the stack to the user's frame.
+ # This will need to be updated if the internal calling logic gets
+ # refactored, or else we'll be expanding the wrong variables.
+ stack_depth = 2
+ magic_arg_s = self.var_expand(line, stack_depth)
+ with self.builtin_trap:
+ result = fn(magic_arg_s, cell)
+ return result
+
+ def find_line_magic(self, magic_name):
+ """Find and return a line magic by name.
+
+ Returns None if the magic isn't found."""
+ return self.magics_manager.magics['line'].get(magic_name)
+
+ def find_cell_magic(self, magic_name):
+ """Find and return a cell magic by name.
+
+ Returns None if the magic isn't found."""
+ return self.magics_manager.magics['cell'].get(magic_name)
+
+ def find_magic(self, magic_name, magic_kind='line'):
+ """Find and return a magic of the given type by name.
+
+ Returns None if the magic isn't found."""
+ return self.magics_manager.magics[magic_kind].get(magic_name)
+
+ def magic(self, arg_s):
+ """DEPRECATED. Use run_line_magic() instead.
+
+ Call a magic function by name.
+
+ Input: a string containing the name of the magic function to call and
+ any additional arguments to be passed to the magic.
+
+ magic('name -opt foo bar') is equivalent to typing at the ipython
+ prompt:
+
+ In[1]: %name -opt foo bar
+
+ To call a magic without arguments, simply use magic('name').
+
+ This provides a proper Python function to call IPython's magics in any
+ valid Python code you can type at the interpreter, including loops and
+ compound statements.
+ """
+ # TODO: should we issue a loud deprecation warning here?
+ magic_name, _, magic_arg_s = arg_s.partition(' ')
+ magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
+ return self.run_line_magic(magic_name, magic_arg_s)
+
+ #-------------------------------------------------------------------------
+ # Things related to macros
+ #-------------------------------------------------------------------------
+
+ def define_macro(self, name, themacro):
+ """Define a new macro
+
+ Parameters
+ ----------
+ name : str
+ The name of the macro.
+ themacro : str or Macro
+ The action to do upon invoking the macro. If a string, a new
+ Macro object is created by passing the string to it.
+ """
+
+ from IPython.core import macro
+
+ if isinstance(themacro, string_types):
+ themacro = macro.Macro(themacro)
+ if not isinstance(themacro, macro.Macro):
+ raise ValueError('A macro must be a string or a Macro instance.')
+ self.user_ns[name] = themacro
+
+ #-------------------------------------------------------------------------
+ # Things related to the running of system commands
+ #-------------------------------------------------------------------------
+
+ def system_piped(self, cmd):
+ """Call the given cmd in a subprocess, piping stdout/err
+
+ Parameters
+ ----------
+ cmd : str
+ Command to execute (can not end in '&', as background processes are
+ not supported. Should not be a command that expects input
+ other than simple text.
+ """
+ if cmd.rstrip().endswith('&'):
+ # this is *far* from a rigorous test
+ # We do not support backgrounding processes because we either use
+ # pexpect or pipes to read from. Users can always just call
+ # os.system() or use ip.system=ip.system_raw
+ # if they really want a background process.
+ raise OSError("Background processes not supported.")
+
+ # we explicitly do NOT return the subprocess status code, because
+ # a non-None value would trigger :func:`sys.displayhook` calls.
+ # Instead, we store the exit_code in user_ns.
+ self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
+
+ def system_raw(self, cmd):
+ """Call the given cmd in a subprocess using os.system on Windows or
+ subprocess.call using the system shell on other platforms.
+
+ Parameters
+ ----------
+ cmd : str
+ Command to execute.
+ """
+ cmd = self.var_expand(cmd, depth=1)
+ # protect os.system from UNC paths on Windows, which it can't handle:
+ if sys.platform == 'win32':
+ from IPython.utils._process_win32 import AvoidUNCPath
+ with AvoidUNCPath() as path:
+ if path is not None:
+ cmd = '"pushd %s &&"%s' % (path, cmd)
+ cmd = py3compat.unicode_to_str(cmd)
+ try:
+ ec = os.system(cmd)
+ except KeyboardInterrupt:
print('\n' + self.get_exception_only(), file=sys.stderr)
- ec = -2
- else:
- cmd = py3compat.unicode_to_str(cmd)
- # For posix the result of the subprocess.call() below is an exit
- # code, which by convention is zero for success, positive for
- # program failure. Exit codes above 128 are reserved for signals,
- # and the formula for converting a signal to an exit code is usually
- # signal_number+128. To more easily differentiate between exit
- # codes and signals, ipython uses negative numbers. For instance
- # since control-c is signal 2 but exit code 130, ipython's
- # _exit_code variable will read -2. Note that some shells like
- # csh and fish don't follow sh/bash conventions for exit codes.
- executable = os.environ.get('SHELL', None)
- try:
- # Use env shell instead of default /bin/sh
- ec = subprocess.call(cmd, shell=True, executable=executable)
- except KeyboardInterrupt:
- # intercept control-C; a long traceback is not useful here
+ ec = -2
+ else:
+ cmd = py3compat.unicode_to_str(cmd)
+ # For posix the result of the subprocess.call() below is an exit
+ # code, which by convention is zero for success, positive for
+ # program failure. Exit codes above 128 are reserved for signals,
+ # and the formula for converting a signal to an exit code is usually
+ # signal_number+128. To more easily differentiate between exit
+ # codes and signals, ipython uses negative numbers. For instance
+ # since control-c is signal 2 but exit code 130, ipython's
+ # _exit_code variable will read -2. Note that some shells like
+ # csh and fish don't follow sh/bash conventions for exit codes.
+ executable = os.environ.get('SHELL', None)
+ try:
+ # Use env shell instead of default /bin/sh
+ ec = subprocess.call(cmd, shell=True, executable=executable)
+ except KeyboardInterrupt:
+ # intercept control-C; a long traceback is not useful here
print('\n' + self.get_exception_only(), file=sys.stderr)
- ec = 130
- if ec > 128:
- ec = -(ec - 128)
+ ec = 130
+ if ec > 128:
+ ec = -(ec - 128)
- # We explicitly do NOT return the subprocess status code, because
- # a non-None value would trigger :func:`sys.displayhook` calls.
- # Instead, we store the exit_code in user_ns. Note the semantics
- # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
- # but raising SystemExit(_exit_code) will give status 254!
- self.user_ns['_exit_code'] = ec
-
- # use piped system by default, because it is better behaved
- system = system_piped
-
- def getoutput(self, cmd, split=True, depth=0):
- """Get output (possibly including stderr) from a subprocess.
-
- Parameters
- ----------
- cmd : str
- Command to execute (can not end in '&', as background processes are
- not supported.
- split : bool, optional
- If True, split the output into an IPython SList. Otherwise, an
- IPython LSString is returned. These are objects similar to normal
- lists and strings, with a few convenience attributes for easier
- manipulation of line-based output. You can use '?' on them for
- details.
- depth : int, optional
- How many frames above the caller are the local variables which should
- be expanded in the command string? The default (0) assumes that the
- expansion variables are in the stack frame calling this function.
- """
- if cmd.rstrip().endswith('&'):
- # this is *far* from a rigorous test
- raise OSError("Background processes not supported.")
- out = getoutput(self.var_expand(cmd, depth=depth+1))
- if split:
- out = SList(out.splitlines())
- else:
- out = LSString(out)
- return out
-
- #-------------------------------------------------------------------------
- # Things related to aliases
- #-------------------------------------------------------------------------
-
- def init_alias(self):
- self.alias_manager = AliasManager(shell=self, parent=self)
- self.configurables.append(self.alias_manager)
-
- #-------------------------------------------------------------------------
- # Things related to extensions
- #-------------------------------------------------------------------------
-
- def init_extension_manager(self):
- self.extension_manager = ExtensionManager(shell=self, parent=self)
- self.configurables.append(self.extension_manager)
-
- #-------------------------------------------------------------------------
- # Things related to payloads
- #-------------------------------------------------------------------------
-
- def init_payload(self):
- self.payload_manager = PayloadManager(parent=self)
- self.configurables.append(self.payload_manager)
+ # We explicitly do NOT return the subprocess status code, because
+ # a non-None value would trigger :func:`sys.displayhook` calls.
+ # Instead, we store the exit_code in user_ns. Note the semantics
+ # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
+ # but raising SystemExit(_exit_code) will give status 254!
+ self.user_ns['_exit_code'] = ec
+
+ # use piped system by default, because it is better behaved
+ system = system_piped
+
+ def getoutput(self, cmd, split=True, depth=0):
+ """Get output (possibly including stderr) from a subprocess.
+
+ Parameters
+ ----------
+ cmd : str
+ Command to execute (can not end in '&', as background processes are
+ not supported.
+ split : bool, optional
+ If True, split the output into an IPython SList. Otherwise, an
+ IPython LSString is returned. These are objects similar to normal
+ lists and strings, with a few convenience attributes for easier
+ manipulation of line-based output. You can use '?' on them for
+ details.
+ depth : int, optional
+ How many frames above the caller are the local variables which should
+ be expanded in the command string? The default (0) assumes that the
+ expansion variables are in the stack frame calling this function.
+ """
+ if cmd.rstrip().endswith('&'):
+ # this is *far* from a rigorous test
+ raise OSError("Background processes not supported.")
+ out = getoutput(self.var_expand(cmd, depth=depth+1))
+ if split:
+ out = SList(out.splitlines())
+ else:
+ out = LSString(out)
+ return out
+
+ #-------------------------------------------------------------------------
+ # Things related to aliases
+ #-------------------------------------------------------------------------
+
+ def init_alias(self):
+ self.alias_manager = AliasManager(shell=self, parent=self)
+ self.configurables.append(self.alias_manager)
+
+ #-------------------------------------------------------------------------
+ # Things related to extensions
+ #-------------------------------------------------------------------------
+
+ def init_extension_manager(self):
+ self.extension_manager = ExtensionManager(shell=self, parent=self)
+ self.configurables.append(self.extension_manager)
+
+ #-------------------------------------------------------------------------
+ # Things related to payloads
+ #-------------------------------------------------------------------------
+
+ def init_payload(self):
+ self.payload_manager = PayloadManager(parent=self)
+ self.configurables.append(self.payload_manager)
- #-------------------------------------------------------------------------
- # Things related to the prefilter
- #-------------------------------------------------------------------------
-
- def init_prefilter(self):
- self.prefilter_manager = PrefilterManager(shell=self, parent=self)
- self.configurables.append(self.prefilter_manager)
- # Ultimately this will be refactored in the new interpreter code, but
- # for now, we should expose the main prefilter method (there's legacy
- # code out there that may rely on this).
- self.prefilter = self.prefilter_manager.prefilter_lines
-
- def auto_rewrite_input(self, cmd):
- """Print to the screen the rewritten form of the user's command.
-
- This shows visual feedback by rewriting input lines that cause
- automatic calling to kick in, like::
-
- /f x
-
- into::
-
- ------> f(x)
-
- after the user's input prompt. This helps the user understand that the
- input line was transformed automatically by IPython.
- """
- if not self.show_rewritten_input:
- return
-
+ #-------------------------------------------------------------------------
+ # Things related to the prefilter
+ #-------------------------------------------------------------------------
+
+ def init_prefilter(self):
+ self.prefilter_manager = PrefilterManager(shell=self, parent=self)
+ self.configurables.append(self.prefilter_manager)
+ # Ultimately this will be refactored in the new interpreter code, but
+ # for now, we should expose the main prefilter method (there's legacy
+ # code out there that may rely on this).
+ self.prefilter = self.prefilter_manager.prefilter_lines
+
+ def auto_rewrite_input(self, cmd):
+ """Print to the screen the rewritten form of the user's command.
+
+ This shows visual feedback by rewriting input lines that cause
+ automatic calling to kick in, like::
+
+ /f x
+
+ into::
+
+ ------> f(x)
+
+ after the user's input prompt. This helps the user understand that the
+ input line was transformed automatically by IPython.
+ """
+ if not self.show_rewritten_input:
+ return
+
# This is overridden in TerminalInteractiveShell to use fancy prompts
print("------> " + cmd)
-
- #-------------------------------------------------------------------------
- # Things related to extracting values/expressions from kernel and user_ns
- #-------------------------------------------------------------------------
-
- def _user_obj_error(self):
- """return simple exception dict
+
+ #-------------------------------------------------------------------------
+ # Things related to extracting values/expressions from kernel and user_ns
+ #-------------------------------------------------------------------------
+
+ def _user_obj_error(self):
+ """return simple exception dict
- for use in user_expressions
- """
+ for use in user_expressions
+ """
- etype, evalue, tb = self._get_exc_info()
- stb = self.InteractiveTB.get_exception_only(etype, evalue)
+ etype, evalue, tb = self._get_exc_info()
+ stb = self.InteractiveTB.get_exception_only(etype, evalue)
- exc_info = {
- u'status' : 'error',
- u'traceback' : stb,
- u'ename' : unicode_type(etype.__name__),
- u'evalue' : py3compat.safe_unicode(evalue),
- }
-
- return exc_info
+ exc_info = {
+ u'status' : 'error',
+ u'traceback' : stb,
+ u'ename' : unicode_type(etype.__name__),
+ u'evalue' : py3compat.safe_unicode(evalue),
+ }
+
+ return exc_info
- def _format_user_obj(self, obj):
- """format a user object to display dict
+ def _format_user_obj(self, obj):
+ """format a user object to display dict
- for use in user_expressions
- """
+ for use in user_expressions
+ """
- data, md = self.display_formatter.format(obj)
- value = {
- 'status' : 'ok',
- 'data' : data,
- 'metadata' : md,
- }
- return value
+ data, md = self.display_formatter.format(obj)
+ value = {
+ 'status' : 'ok',
+ 'data' : data,
+ 'metadata' : md,
+ }
+ return value
- def user_expressions(self, expressions):
- """Evaluate a dict of expressions in the user's namespace.
-
- Parameters
- ----------
- expressions : dict
- A dict with string keys and string values. The expression values
- should be valid Python expressions, each of which will be evaluated
- in the user namespace.
-
- Returns
- -------
- A dict, keyed like the input expressions dict, with the rich mime-typed
- display_data of each value.
- """
- out = {}
- user_ns = self.user_ns
- global_ns = self.user_global_ns
+ def user_expressions(self, expressions):
+ """Evaluate a dict of expressions in the user's namespace.
+
+ Parameters
+ ----------
+ expressions : dict
+ A dict with string keys and string values. The expression values
+ should be valid Python expressions, each of which will be evaluated
+ in the user namespace.
+
+ Returns
+ -------
+ A dict, keyed like the input expressions dict, with the rich mime-typed
+ display_data of each value.
+ """
+ out = {}
+ user_ns = self.user_ns
+ global_ns = self.user_global_ns
- for key, expr in iteritems(expressions):
- try:
- value = self._format_user_obj(eval(expr, global_ns, user_ns))
- except:
- value = self._user_obj_error()
- out[key] = value
- return out
-
- #-------------------------------------------------------------------------
- # Things related to the running of code
- #-------------------------------------------------------------------------
-
- def ex(self, cmd):
- """Execute a normal python statement in user namespace."""
- with self.builtin_trap:
- exec(cmd, self.user_global_ns, self.user_ns)
-
- def ev(self, expr):
- """Evaluate python expression expr in user namespace.
-
- Returns the result of evaluation
- """
- with self.builtin_trap:
- return eval(expr, self.user_global_ns, self.user_ns)
-
- def safe_execfile(self, fname, *where, **kw):
- """A safe version of the builtin execfile().
-
- This version will never throw an exception, but instead print
- helpful error messages to the screen. This only works on pure
- Python files with the .py extension.
-
- Parameters
- ----------
- fname : string
- The name of the file to be executed.
- where : tuple
- One or two namespaces, passed to execfile() as (globals,locals).
- If only one is given, it is passed as both.
- exit_ignore : bool (False)
- If True, then silence SystemExit for non-zero status (it is always
- silenced for zero status, as it is so common).
- raise_exceptions : bool (False)
- If True raise exceptions everywhere. Meant for testing.
- shell_futures : bool (False)
- If True, the code will share future statements with the interactive
- shell. It will both be affected by previous __future__ imports, and
- any __future__ imports in the code will affect the shell. If False,
- __future__ imports are not shared in either direction.
-
- """
- kw.setdefault('exit_ignore', False)
- kw.setdefault('raise_exceptions', False)
- kw.setdefault('shell_futures', False)
-
- fname = os.path.abspath(os.path.expanduser(fname))
-
- # Make sure we can open the file
- try:
- with open(fname):
- pass
- except:
- warn('Could not open file <%s> for safe execution.' % fname)
- return
-
- # Find things also in current directory. This is needed to mimic the
- # behavior of running a script from the system command line, where
- # Python inserts the script's directory into sys.path
- dname = os.path.dirname(fname)
-
+ for key, expr in iteritems(expressions):
+ try:
+ value = self._format_user_obj(eval(expr, global_ns, user_ns))
+ except:
+ value = self._user_obj_error()
+ out[key] = value
+ return out
+
+ #-------------------------------------------------------------------------
+ # Things related to the running of code
+ #-------------------------------------------------------------------------
+
+ def ex(self, cmd):
+ """Execute a normal python statement in user namespace."""
+ with self.builtin_trap:
+ exec(cmd, self.user_global_ns, self.user_ns)
+
+ def ev(self, expr):
+ """Evaluate python expression expr in user namespace.
+
+ Returns the result of evaluation
+ """
+ with self.builtin_trap:
+ return eval(expr, self.user_global_ns, self.user_ns)
+
+ def safe_execfile(self, fname, *where, **kw):
+ """A safe version of the builtin execfile().
+
+ This version will never throw an exception, but instead print
+ helpful error messages to the screen. This only works on pure
+ Python files with the .py extension.
+
+ Parameters
+ ----------
+ fname : string
+ The name of the file to be executed.
+ where : tuple
+ One or two namespaces, passed to execfile() as (globals,locals).
+ If only one is given, it is passed as both.
+ exit_ignore : bool (False)
+ If True, then silence SystemExit for non-zero status (it is always
+ silenced for zero status, as it is so common).
+ raise_exceptions : bool (False)
+ If True raise exceptions everywhere. Meant for testing.
+ shell_futures : bool (False)
+ If True, the code will share future statements with the interactive
+ shell. It will both be affected by previous __future__ imports, and
+ any __future__ imports in the code will affect the shell. If False,
+ __future__ imports are not shared in either direction.
+
+ """
+ kw.setdefault('exit_ignore', False)
+ kw.setdefault('raise_exceptions', False)
+ kw.setdefault('shell_futures', False)
+
+ fname = os.path.abspath(os.path.expanduser(fname))
+
+ # Make sure we can open the file
+ try:
+ with open(fname):
+ pass
+ except:
+ warn('Could not open file <%s> for safe execution.' % fname)
+ return
+
+ # Find things also in current directory. This is needed to mimic the
+ # behavior of running a script from the system command line, where
+ # Python inserts the script's directory into sys.path
+ dname = os.path.dirname(fname)
+
with prepended_to_syspath(dname), self.builtin_trap:
- try:
- glob, loc = (where + (None, ))[:2]
- py3compat.execfile(
- fname, glob, loc,
- self.compile if kw['shell_futures'] else None)
- except SystemExit as status:
- # If the call was made with 0 or None exit status (sys.exit(0)
- # or sys.exit() ), don't bother showing a traceback, as both of
- # these are considered normal by the OS:
- # > python -c'import sys;sys.exit(0)'; echo $?
- # 0
- # > python -c'import sys;sys.exit()'; echo $?
- # 0
- # For other exit status, we show the exception unless
- # explicitly silenced, but only in short form.
- if status.code:
- if kw['raise_exceptions']:
- raise
- if not kw['exit_ignore']:
- self.showtraceback(exception_only=True)
- except:
- if kw['raise_exceptions']:
- raise
- # tb offset is 2 because we wrap execfile
- self.showtraceback(tb_offset=2)
-
- def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
- """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
-
- Parameters
- ----------
- fname : str
- The name of the file to execute. The filename must have a
- .ipy or .ipynb extension.
- shell_futures : bool (False)
- If True, the code will share future statements with the interactive
- shell. It will both be affected by previous __future__ imports, and
- any __future__ imports in the code will affect the shell. If False,
- __future__ imports are not shared in either direction.
- raise_exceptions : bool (False)
- If True raise exceptions everywhere. Meant for testing.
- """
- fname = os.path.abspath(os.path.expanduser(fname))
-
- # Make sure we can open the file
- try:
- with open(fname):
- pass
- except:
- warn('Could not open file <%s> for safe execution.' % fname)
- return
-
- # Find things also in current directory. This is needed to mimic the
- # behavior of running a script from the system command line, where
- # Python inserts the script's directory into sys.path
- dname = os.path.dirname(fname)
+ try:
+ glob, loc = (where + (None, ))[:2]
+ py3compat.execfile(
+ fname, glob, loc,
+ self.compile if kw['shell_futures'] else None)
+ except SystemExit as status:
+ # If the call was made with 0 or None exit status (sys.exit(0)
+ # or sys.exit() ), don't bother showing a traceback, as both of
+ # these are considered normal by the OS:
+ # > python -c'import sys;sys.exit(0)'; echo $?
+ # 0
+ # > python -c'import sys;sys.exit()'; echo $?
+ # 0
+ # For other exit status, we show the exception unless
+ # explicitly silenced, but only in short form.
+ if status.code:
+ if kw['raise_exceptions']:
+ raise
+ if not kw['exit_ignore']:
+ self.showtraceback(exception_only=True)
+ except:
+ if kw['raise_exceptions']:
+ raise
+ # tb offset is 2 because we wrap execfile
+ self.showtraceback(tb_offset=2)
+
+ def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
+ """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
+
+ Parameters
+ ----------
+ fname : str
+ The name of the file to execute. The filename must have a
+ .ipy or .ipynb extension.
+ shell_futures : bool (False)
+ If True, the code will share future statements with the interactive
+ shell. It will both be affected by previous __future__ imports, and
+ any __future__ imports in the code will affect the shell. If False,
+ __future__ imports are not shared in either direction.
+ raise_exceptions : bool (False)
+ If True raise exceptions everywhere. Meant for testing.
+ """
+ fname = os.path.abspath(os.path.expanduser(fname))
+
+ # Make sure we can open the file
+ try:
+ with open(fname):
+ pass
+ except:
+ warn('Could not open file <%s> for safe execution.' % fname)
+ return
+
+ # Find things also in current directory. This is needed to mimic the
+ # behavior of running a script from the system command line, where
+ # Python inserts the script's directory into sys.path
+ dname = os.path.dirname(fname)
- def get_cells():
- """generator for sequence of code blocks to run"""
- if fname.endswith('.ipynb'):
- from nbformat import read
+ def get_cells():
+ """generator for sequence of code blocks to run"""
+ if fname.endswith('.ipynb'):
+ from nbformat import read
nb = read(fname, as_version=4)
if not nb.cells:
return
for cell in nb.cells:
if cell.cell_type == 'code':
yield cell.source
- else:
- with open(fname) as f:
- yield f.read()
-
- with prepended_to_syspath(dname):
- try:
- for cell in get_cells():
- result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
- if raise_exceptions:
- result.raise_error()
- elif not result.success:
- break
- except:
- if raise_exceptions:
- raise
- self.showtraceback()
- warn('Unknown failure executing file: <%s>' % fname)
-
- def safe_run_module(self, mod_name, where):
- """A safe version of runpy.run_module().
-
- This version will never throw an exception, but instead print
- helpful error messages to the screen.
-
- `SystemExit` exceptions with status code 0 or None are ignored.
-
- Parameters
- ----------
- mod_name : string
- The name of the module to be executed.
- where : dict
- The globals namespace.
- """
- try:
- try:
- where.update(
- runpy.run_module(str(mod_name), run_name="__main__",
- alter_sys=True)
- )
- except SystemExit as status:
- if status.code:
- raise
- except:
- self.showtraceback()
- warn('Unknown failure executing module: <%s>' % mod_name)
-
- def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
- """Run a complete IPython cell.
-
- Parameters
- ----------
- raw_cell : str
- The code (including IPython code such as %magic functions) to run.
- store_history : bool
- If True, the raw and translated cell will be stored in IPython's
- history. For user code calling back into IPython's machinery, this
- should be set to False.
- silent : bool
- If True, avoid side-effects, such as implicit displayhooks and
- and logging. silent=True forces store_history=False.
- shell_futures : bool
- If True, the code will share future statements with the interactive
- shell. It will both be affected by previous __future__ imports, and
- any __future__ imports in the code will affect the shell. If False,
- __future__ imports are not shared in either direction.
-
- Returns
- -------
- result : :class:`ExecutionResult`
- """
- result = ExecutionResult()
-
- if (not raw_cell) or raw_cell.isspace():
+ else:
+ with open(fname) as f:
+ yield f.read()
+
+ with prepended_to_syspath(dname):
+ try:
+ for cell in get_cells():
+ result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
+ if raise_exceptions:
+ result.raise_error()
+ elif not result.success:
+ break
+ except:
+ if raise_exceptions:
+ raise
+ self.showtraceback()
+ warn('Unknown failure executing file: <%s>' % fname)
+
+ def safe_run_module(self, mod_name, where):
+ """A safe version of runpy.run_module().
+
+ This version will never throw an exception, but instead print
+ helpful error messages to the screen.
+
+ `SystemExit` exceptions with status code 0 or None are ignored.
+
+ Parameters
+ ----------
+ mod_name : string
+ The name of the module to be executed.
+ where : dict
+ The globals namespace.
+ """
+ try:
+ try:
+ where.update(
+ runpy.run_module(str(mod_name), run_name="__main__",
+ alter_sys=True)
+ )
+ except SystemExit as status:
+ if status.code:
+ raise
+ except:
+ self.showtraceback()
+ warn('Unknown failure executing module: <%s>' % mod_name)
+
+ def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
+ """Run a complete IPython cell.
+
+ Parameters
+ ----------
+ raw_cell : str
+ The code (including IPython code such as %magic functions) to run.
+ store_history : bool
+ If True, the raw and translated cell will be stored in IPython's
+ history. For user code calling back into IPython's machinery, this
+ should be set to False.
+ silent : bool
+ If True, avoid side-effects, such as implicit displayhooks and
+ and logging. silent=True forces store_history=False.
+ shell_futures : bool
+ If True, the code will share future statements with the interactive
+ shell. It will both be affected by previous __future__ imports, and
+ any __future__ imports in the code will affect the shell. If False,
+ __future__ imports are not shared in either direction.
+
+ Returns
+ -------
+ result : :class:`ExecutionResult`
+ """
+ result = ExecutionResult()
+
+ if (not raw_cell) or raw_cell.isspace():
self.last_execution_succeeded = True
- return result
+ return result
- if silent:
- store_history = False
-
- if store_history:
- result.execution_count = self.execution_count
-
- def error_before_exec(value):
+ if silent:
+ store_history = False
+
+ if store_history:
+ result.execution_count = self.execution_count
+
+ def error_before_exec(value):
if store_history:
self.execution_count += 1
- result.error_before_exec = value
+ result.error_before_exec = value
self.last_execution_succeeded = False
- return result
-
- self.events.trigger('pre_execute')
- if not silent:
- self.events.trigger('pre_run_cell')
-
- # If any of our input transformation (input_transformer_manager or
- # prefilter_manager) raises an exception, we store it in this variable
- # so that we can display the error after logging the input and storing
- # it in the history.
- preprocessing_exc_tuple = None
- try:
- # Static input transformations
- cell = self.input_transformer_manager.transform_cell(raw_cell)
- except SyntaxError:
- preprocessing_exc_tuple = sys.exc_info()
- cell = raw_cell # cell has to exist so it can be stored/logged
- else:
- if len(cell.splitlines()) == 1:
- # Dynamic transformations - only applied for single line commands
- with self.builtin_trap:
- try:
- # use prefilter_lines to handle trailing newlines
- # restore trailing newline for ast.parse
- cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
- except Exception:
- # don't allow prefilter errors to crash IPython
- preprocessing_exc_tuple = sys.exc_info()
-
- # Store raw and processed history
- if store_history:
- self.history_manager.store_inputs(self.execution_count,
- cell, raw_cell)
- if not silent:
- self.logger.log(cell, raw_cell)
-
- # Display the exception if input processing failed.
- if preprocessing_exc_tuple is not None:
- self.showtraceback(preprocessing_exc_tuple)
- if store_history:
- self.execution_count += 1
- return error_before_exec(preprocessing_exc_tuple[2])
-
- # Our own compiler remembers the __future__ environment. If we want to
- # run code with a separate __future__ environment, use the default
- # compiler
- compiler = self.compile if shell_futures else CachingCompiler()
-
- with self.builtin_trap:
- cell_name = self.compile.cache(cell, self.execution_count)
-
- with self.display_trap:
- # Compile to bytecode
- try:
- code_ast = compiler.ast_parse(cell, filename=cell_name)
+ return result
+
+ self.events.trigger('pre_execute')
+ if not silent:
+ self.events.trigger('pre_run_cell')
+
+ # If any of our input transformation (input_transformer_manager or
+ # prefilter_manager) raises an exception, we store it in this variable
+ # so that we can display the error after logging the input and storing
+ # it in the history.
+ preprocessing_exc_tuple = None
+ try:
+ # Static input transformations
+ cell = self.input_transformer_manager.transform_cell(raw_cell)
+ except SyntaxError:
+ preprocessing_exc_tuple = sys.exc_info()
+ cell = raw_cell # cell has to exist so it can be stored/logged
+ else:
+ if len(cell.splitlines()) == 1:
+ # Dynamic transformations - only applied for single line commands
+ with self.builtin_trap:
+ try:
+ # use prefilter_lines to handle trailing newlines
+ # restore trailing newline for ast.parse
+ cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
+ except Exception:
+ # don't allow prefilter errors to crash IPython
+ preprocessing_exc_tuple = sys.exc_info()
+
+ # Store raw and processed history
+ if store_history:
+ self.history_manager.store_inputs(self.execution_count,
+ cell, raw_cell)
+ if not silent:
+ self.logger.log(cell, raw_cell)
+
+ # Display the exception if input processing failed.
+ if preprocessing_exc_tuple is not None:
+ self.showtraceback(preprocessing_exc_tuple)
+ if store_history:
+ self.execution_count += 1
+ return error_before_exec(preprocessing_exc_tuple[2])
+
+ # Our own compiler remembers the __future__ environment. If we want to
+ # run code with a separate __future__ environment, use the default
+ # compiler
+ compiler = self.compile if shell_futures else CachingCompiler()
+
+ with self.builtin_trap:
+ cell_name = self.compile.cache(cell, self.execution_count)
+
+ with self.display_trap:
+ # Compile to bytecode
+ try:
+ code_ast = compiler.ast_parse(cell, filename=cell_name)
except self.custom_exceptions as e:
etype, value, tb = sys.exc_info()
self.CustomTB(etype, value, tb)
return error_before_exec(e)
- except IndentationError as e:
- self.showindentationerror()
- return error_before_exec(e)
- except (OverflowError, SyntaxError, ValueError, TypeError,
- MemoryError) as e:
- self.showsyntaxerror()
- return error_before_exec(e)
-
- # Apply AST transformations
- try:
- code_ast = self.transform_ast(code_ast)
- except InputRejected as e:
- self.showtraceback()
- return error_before_exec(e)
-
- # Give the displayhook a reference to our ExecutionResult so it
- # can fill in the output value.
- self.displayhook.exec_result = result
-
- # Execute the user code
- interactivity = "none" if silent else self.ast_node_interactivity
+ except IndentationError as e:
+ self.showindentationerror()
+ return error_before_exec(e)
+ except (OverflowError, SyntaxError, ValueError, TypeError,
+ MemoryError) as e:
+ self.showsyntaxerror()
+ return error_before_exec(e)
+
+ # Apply AST transformations
+ try:
+ code_ast = self.transform_ast(code_ast)
+ except InputRejected as e:
+ self.showtraceback()
+ return error_before_exec(e)
+
+ # Give the displayhook a reference to our ExecutionResult so it
+ # can fill in the output value.
+ self.displayhook.exec_result = result
+
+ # Execute the user code
+ interactivity = "none" if silent else self.ast_node_interactivity
has_raised = self.run_ast_nodes(code_ast.body, cell_name,
- interactivity=interactivity, compiler=compiler, result=result)
+ interactivity=interactivity, compiler=compiler, result=result)
self.last_execution_succeeded = not has_raised
-
- # Reset this so later displayed values do not modify the
- # ExecutionResult
- self.displayhook.exec_result = None
-
- self.events.trigger('post_execute')
- if not silent:
- self.events.trigger('post_run_cell')
-
- if store_history:
- # Write output to the database. Does nothing unless
- # history output logging is enabled.
- self.history_manager.store_output(self.execution_count)
- # Each cell is a *single* input, regardless of how many lines it has
- self.execution_count += 1
-
- return result
+
+ # Reset this so later displayed values do not modify the
+ # ExecutionResult
+ self.displayhook.exec_result = None
+
+ self.events.trigger('post_execute')
+ if not silent:
+ self.events.trigger('post_run_cell')
+
+ if store_history:
+ # Write output to the database. Does nothing unless
+ # history output logging is enabled.
+ self.history_manager.store_output(self.execution_count)
+ # Each cell is a *single* input, regardless of how many lines it has
+ self.execution_count += 1
+
+ return result
- def transform_ast(self, node):
- """Apply the AST transformations from self.ast_transformers
+ def transform_ast(self, node):
+ """Apply the AST transformations from self.ast_transformers
- Parameters
- ----------
- node : ast.Node
- The root node to be transformed. Typically called with the ast.Module
- produced by parsing user input.
+ Parameters
+ ----------
+ node : ast.Node
+ The root node to be transformed. Typically called with the ast.Module
+ produced by parsing user input.
- Returns
- -------
- An ast.Node corresponding to the node it was called with. Note that it
- may also modify the passed object, so don't rely on references to the
- original AST.
- """
- for transformer in self.ast_transformers:
- try:
- node = transformer.visit(node)
- except InputRejected:
- # User-supplied AST transformers can reject an input by raising
- # an InputRejected. Short-circuit in this case so that we
- # don't unregister the transform.
- raise
- except Exception:
- warn("AST transformer %r threw an error. It will be unregistered." % transformer)
- self.ast_transformers.remove(transformer)
+ Returns
+ -------
+ An ast.Node corresponding to the node it was called with. Note that it
+ may also modify the passed object, so don't rely on references to the
+ original AST.
+ """
+ for transformer in self.ast_transformers:
+ try:
+ node = transformer.visit(node)
+ except InputRejected:
+ # User-supplied AST transformers can reject an input by raising
+ # an InputRejected. Short-circuit in this case so that we
+ # don't unregister the transform.
+ raise
+ except Exception:
+ warn("AST transformer %r threw an error. It will be unregistered." % transformer)
+ self.ast_transformers.remove(transformer)
- if self.ast_transformers:
- ast.fix_missing_locations(node)
- return node
+ if self.ast_transformers:
+ ast.fix_missing_locations(node)
+ return node
-
- def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
- compiler=compile, result=None):
- """Run a sequence of AST nodes. The execution mode depends on the
- interactivity parameter.
-
- Parameters
- ----------
- nodelist : list
- A sequence of AST nodes to run.
- cell_name : str
- Will be passed to the compiler as the filename of the cell. Typically
- the value returned by ip.compile.cache(cell).
- interactivity : str
- 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
- run interactively (displaying output from expressions). 'last_expr'
- will run the last node interactively only if it is an expression (i.e.
- expressions in loops or other blocks are not displayed. Other values
- for this parameter will raise a ValueError.
- compiler : callable
- A function with the same interface as the built-in compile(), to turn
- the AST nodes into code objects. Default is the built-in compile().
- result : ExecutionResult, optional
- An object to store exceptions that occur during execution.
-
- Returns
- -------
- True if an exception occurred while running code, False if it finished
- running.
- """
- if not nodelist:
- return
-
- if interactivity == 'last_expr':
- if isinstance(nodelist[-1], ast.Expr):
- interactivity = "last"
- else:
- interactivity = "none"
-
- if interactivity == 'none':
- to_run_exec, to_run_interactive = nodelist, []
- elif interactivity == 'last':
- to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
- elif interactivity == 'all':
- to_run_exec, to_run_interactive = [], nodelist
- else:
- raise ValueError("Interactivity was %r" % interactivity)
-
- try:
- for i, node in enumerate(to_run_exec):
- mod = ast.Module([node])
- code = compiler(mod, cell_name, "exec")
- if self.run_code(code, result):
- return True
-
- for i, node in enumerate(to_run_interactive):
- mod = ast.Interactive([node])
- code = compiler(mod, cell_name, "single")
- if self.run_code(code, result):
- return True
-
- # Flush softspace
- if softspace(sys.stdout, 0):
- print()
-
- except:
- # It's possible to have exceptions raised here, typically by
- # compilation of odd code (such as a naked 'return' outside a
- # function) that did parse but isn't valid. Typically the exception
- # is a SyntaxError, but it's safest just to catch anything and show
- # the user a traceback.
-
- # We do only one try/except outside the loop to minimize the impact
- # on runtime, and also because if any node in the node list is
- # broken, we should stop execution completely.
- if result:
- result.error_before_exec = sys.exc_info()[1]
- self.showtraceback()
- return True
-
- return False
-
- def run_code(self, code_obj, result=None):
- """Execute a code object.
-
- When an exception occurs, self.showtraceback() is called to display a
- traceback.
-
- Parameters
- ----------
- code_obj : code object
- A compiled code object, to be executed
- result : ExecutionResult, optional
- An object to store exceptions that occur during execution.
-
- Returns
- -------
- False : successful execution.
- True : an error occurred.
- """
- # Set our own excepthook in case the user code tries to call it
- # directly, so that the IPython crash handler doesn't get triggered
- old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
-
- # we save the original sys.excepthook in the instance, in case config
- # code (such as magics) needs access to it.
- self.sys_excepthook = old_excepthook
- outflag = 1 # happens in more places, so it's easier as default
- try:
- try:
- self.hooks.pre_run_code_hook()
- #rprint('Running code', repr(code_obj)) # dbg
- exec(code_obj, self.user_global_ns, self.user_ns)
- finally:
- # Reset our crash handler in place
- sys.excepthook = old_excepthook
- except SystemExit as e:
- if result is not None:
- result.error_in_exec = e
- self.showtraceback(exception_only=True)
+
+ def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
+ compiler=compile, result=None):
+ """Run a sequence of AST nodes. The execution mode depends on the
+ interactivity parameter.
+
+ Parameters
+ ----------
+ nodelist : list
+ A sequence of AST nodes to run.
+ cell_name : str
+ Will be passed to the compiler as the filename of the cell. Typically
+ the value returned by ip.compile.cache(cell).
+ interactivity : str
+ 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
+ run interactively (displaying output from expressions). 'last_expr'
+ will run the last node interactively only if it is an expression (i.e.
+ expressions in loops or other blocks are not displayed. Other values
+ for this parameter will raise a ValueError.
+ compiler : callable
+ A function with the same interface as the built-in compile(), to turn
+ the AST nodes into code objects. Default is the built-in compile().
+ result : ExecutionResult, optional
+ An object to store exceptions that occur during execution.
+
+ Returns
+ -------
+ True if an exception occurred while running code, False if it finished
+ running.
+ """
+ if not nodelist:
+ return
+
+ if interactivity == 'last_expr':
+ if isinstance(nodelist[-1], ast.Expr):
+ interactivity = "last"
+ else:
+ interactivity = "none"
+
+ if interactivity == 'none':
+ to_run_exec, to_run_interactive = nodelist, []
+ elif interactivity == 'last':
+ to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
+ elif interactivity == 'all':
+ to_run_exec, to_run_interactive = [], nodelist
+ else:
+ raise ValueError("Interactivity was %r" % interactivity)
+
+ try:
+ for i, node in enumerate(to_run_exec):
+ mod = ast.Module([node])
+ code = compiler(mod, cell_name, "exec")
+ if self.run_code(code, result):
+ return True
+
+ for i, node in enumerate(to_run_interactive):
+ mod = ast.Interactive([node])
+ code = compiler(mod, cell_name, "single")
+ if self.run_code(code, result):
+ return True
+
+ # Flush softspace
+ if softspace(sys.stdout, 0):
+ print()
+
+ except:
+ # It's possible to have exceptions raised here, typically by
+ # compilation of odd code (such as a naked 'return' outside a
+ # function) that did parse but isn't valid. Typically the exception
+ # is a SyntaxError, but it's safest just to catch anything and show
+ # the user a traceback.
+
+ # We do only one try/except outside the loop to minimize the impact
+ # on runtime, and also because if any node in the node list is
+ # broken, we should stop execution completely.
+ if result:
+ result.error_before_exec = sys.exc_info()[1]
+ self.showtraceback()
+ return True
+
+ return False
+
+ def run_code(self, code_obj, result=None):
+ """Execute a code object.
+
+ When an exception occurs, self.showtraceback() is called to display a
+ traceback.
+
+ Parameters
+ ----------
+ code_obj : code object
+ A compiled code object, to be executed
+ result : ExecutionResult, optional
+ An object to store exceptions that occur during execution.
+
+ Returns
+ -------
+ False : successful execution.
+ True : an error occurred.
+ """
+ # Set our own excepthook in case the user code tries to call it
+ # directly, so that the IPython crash handler doesn't get triggered
+ old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
+
+ # we save the original sys.excepthook in the instance, in case config
+ # code (such as magics) needs access to it.
+ self.sys_excepthook = old_excepthook
+ outflag = 1 # happens in more places, so it's easier as default
+ try:
+ try:
+ self.hooks.pre_run_code_hook()
+ #rprint('Running code', repr(code_obj)) # dbg
+ exec(code_obj, self.user_global_ns, self.user_ns)
+ finally:
+ # Reset our crash handler in place
+ sys.excepthook = old_excepthook
+ except SystemExit as e:
+ if result is not None:
+ result.error_in_exec = e
+ self.showtraceback(exception_only=True)
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
- except self.custom_exceptions:
- etype, value, tb = sys.exc_info()
- if result is not None:
- result.error_in_exec = value
- self.CustomTB(etype, value, tb)
- except:
- if result is not None:
- result.error_in_exec = sys.exc_info()[1]
- self.showtraceback()
- else:
- outflag = 0
- return outflag
-
- # For backwards compatibility
- runcode = run_code
-
+ except self.custom_exceptions:
+ etype, value, tb = sys.exc_info()
+ if result is not None:
+ result.error_in_exec = value
+ self.CustomTB(etype, value, tb)
+ except:
+ if result is not None:
+ result.error_in_exec = sys.exc_info()[1]
+ self.showtraceback()
+ else:
+ outflag = 0
+ return outflag
+
+ # For backwards compatibility
+ runcode = run_code
+
def check_complete(self, code):
"""Return whether a block of code is ready to execute, or should be continued
@@ -2920,345 +2920,345 @@ class InteractiveShell(SingletonConfigurable):
status, nspaces = self.input_splitter.check_complete(code)
return status, ' ' * (nspaces or 0)
- #-------------------------------------------------------------------------
- # Things related to GUI support and pylab
- #-------------------------------------------------------------------------
-
+ #-------------------------------------------------------------------------
+ # Things related to GUI support and pylab
+ #-------------------------------------------------------------------------
+
active_eventloop = None
- def enable_gui(self, gui=None):
- raise NotImplementedError('Implement enable_gui in a subclass')
+ def enable_gui(self, gui=None):
+ raise NotImplementedError('Implement enable_gui in a subclass')
- def enable_matplotlib(self, gui=None):
- """Enable interactive matplotlib and inline figure support.
+ def enable_matplotlib(self, gui=None):
+ """Enable interactive matplotlib and inline figure support.
- This takes the following steps:
+ This takes the following steps:
- 1. select the appropriate eventloop and matplotlib backend
- 2. set up matplotlib for interactive use with that backend
- 3. configure formatters for inline figure display
- 4. enable the selected gui eventloop
+ 1. select the appropriate eventloop and matplotlib backend
+ 2. set up matplotlib for interactive use with that backend
+ 3. configure formatters for inline figure display
+ 4. enable the selected gui eventloop
- Parameters
- ----------
- gui : optional, string
- If given, dictates the choice of matplotlib GUI backend to use
- (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
- 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
- matplotlib (as dictated by the matplotlib build-time options plus the
- user's matplotlibrc configuration file). Note that not all backends
- make sense in all contexts, for example a terminal ipython can't
- display figures inline.
- """
- from IPython.core import pylabtools as pt
- gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
+ Parameters
+ ----------
+ gui : optional, string
+ If given, dictates the choice of matplotlib GUI backend to use
+ (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
+ 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
+ matplotlib (as dictated by the matplotlib build-time options plus the
+ user's matplotlibrc configuration file). Note that not all backends
+ make sense in all contexts, for example a terminal ipython can't
+ display figures inline.
+ """
+ from IPython.core import pylabtools as pt
+ gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
- if gui != 'inline':
- # If we have our first gui selection, store it
- if self.pylab_gui_select is None:
- self.pylab_gui_select = gui
- # Otherwise if they are different
- elif gui != self.pylab_gui_select:
- print ('Warning: Cannot change to a different GUI toolkit: %s.'
- ' Using %s instead.' % (gui, self.pylab_gui_select))
- gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
+ if gui != 'inline':
+ # If we have our first gui selection, store it
+ if self.pylab_gui_select is None:
+ self.pylab_gui_select = gui
+ # Otherwise if they are different
+ elif gui != self.pylab_gui_select:
+ print ('Warning: Cannot change to a different GUI toolkit: %s.'
+ ' Using %s instead.' % (gui, self.pylab_gui_select))
+ gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
- pt.activate_matplotlib(backend)
- pt.configure_inline_support(self, backend)
+ pt.activate_matplotlib(backend)
+ pt.configure_inline_support(self, backend)
- # Now we must activate the gui pylab wants to use, and fix %run to take
- # plot updates into account
- self.enable_gui(gui)
- self.magics_manager.registry['ExecutionMagics'].default_runner = \
- pt.mpl_runner(self.safe_execfile)
+ # Now we must activate the gui pylab wants to use, and fix %run to take
+ # plot updates into account
+ self.enable_gui(gui)
+ self.magics_manager.registry['ExecutionMagics'].default_runner = \
+ pt.mpl_runner(self.safe_execfile)
- return gui, backend
-
- def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
- """Activate pylab support at runtime.
-
- This turns on support for matplotlib, preloads into the interactive
- namespace all of numpy and pylab, and configures IPython to correctly
- interact with the GUI event loop. The GUI backend to be used can be
- optionally selected with the optional ``gui`` argument.
+ return gui, backend
+
+ def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
+ """Activate pylab support at runtime.
+
+ This turns on support for matplotlib, preloads into the interactive
+ namespace all of numpy and pylab, and configures IPython to correctly
+ interact with the GUI event loop. The GUI backend to be used can be
+ optionally selected with the optional ``gui`` argument.
- This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
-
- Parameters
- ----------
- gui : optional, string
- If given, dictates the choice of matplotlib GUI backend to use
- (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
- 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
- matplotlib (as dictated by the matplotlib build-time options plus the
- user's matplotlibrc configuration file). Note that not all backends
- make sense in all contexts, for example a terminal ipython can't
- display figures inline.
- import_all : optional, bool, default: True
- Whether to do `from numpy import *` and `from pylab import *`
- in addition to module imports.
- welcome_message : deprecated
- This argument is ignored, no welcome message will be displayed.
- """
- from IPython.core.pylabtools import import_pylab
+ This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
+
+ Parameters
+ ----------
+ gui : optional, string
+ If given, dictates the choice of matplotlib GUI backend to use
+ (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
+ 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
+ matplotlib (as dictated by the matplotlib build-time options plus the
+ user's matplotlibrc configuration file). Note that not all backends
+ make sense in all contexts, for example a terminal ipython can't
+ display figures inline.
+ import_all : optional, bool, default: True
+ Whether to do `from numpy import *` and `from pylab import *`
+ in addition to module imports.
+ welcome_message : deprecated
+ This argument is ignored, no welcome message will be displayed.
+ """
+ from IPython.core.pylabtools import import_pylab
- gui, backend = self.enable_matplotlib(gui)
+ gui, backend = self.enable_matplotlib(gui)
- # We want to prevent the loading of pylab to pollute the user's
- # namespace as shown by the %who* magics, so we execute the activation
- # code in an empty namespace, and we update *both* user_ns and
- # user_ns_hidden with this information.
- ns = {}
- import_pylab(ns, import_all)
- # warn about clobbered names
- ignored = {"__builtins__"}
- both = set(ns).intersection(self.user_ns).difference(ignored)
- clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
- self.user_ns.update(ns)
- self.user_ns_hidden.update(ns)
- return gui, backend, clobbered
-
- #-------------------------------------------------------------------------
- # Utilities
- #-------------------------------------------------------------------------
-
- def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
- """Expand python variables in a string.
-
- The depth argument indicates how many frames above the caller should
- be walked to look for the local namespace where to expand variables.
-
- The global namespace for expansion is always the user's interactive
- namespace.
- """
- ns = self.user_ns.copy()
- try:
- frame = sys._getframe(depth+1)
- except ValueError:
- # This is thrown if there aren't that many frames on the stack,
- # e.g. if a script called run_line_magic() directly.
- pass
- else:
- ns.update(frame.f_locals)
-
- try:
- # We have to use .vformat() here, because 'self' is a valid and common
- # name, and expanding **ns for .format() would make it collide with
- # the 'self' argument of the method.
- cmd = formatter.vformat(cmd, args=[], kwargs=ns)
- except Exception:
- # if formatter couldn't format, just let it go untransformed
- pass
- return cmd
-
- def mktempfile(self, data=None, prefix='ipython_edit_'):
- """Make a new tempfile and return its filename.
-
- This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
- but it registers the created filename internally so ipython cleans it up
- at exit time.
-
- Optional inputs:
-
- - data(None): if data is given, it gets written out to the temp file
- immediately, and the file is closed again."""
-
- dirname = tempfile.mkdtemp(prefix=prefix)
- self.tempdirs.append(dirname)
-
- handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
- os.close(handle) # On Windows, there can only be one open handle on a file
- self.tempfiles.append(filename)
-
- if data:
- tmp_file = open(filename,'w')
- tmp_file.write(data)
- tmp_file.close()
- return filename
-
+ # We want to prevent the loading of pylab to pollute the user's
+ # namespace as shown by the %who* magics, so we execute the activation
+ # code in an empty namespace, and we update *both* user_ns and
+ # user_ns_hidden with this information.
+ ns = {}
+ import_pylab(ns, import_all)
+ # warn about clobbered names
+ ignored = {"__builtins__"}
+ both = set(ns).intersection(self.user_ns).difference(ignored)
+ clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
+ self.user_ns.update(ns)
+ self.user_ns_hidden.update(ns)
+ return gui, backend, clobbered
+
+ #-------------------------------------------------------------------------
+ # Utilities
+ #-------------------------------------------------------------------------
+
+ def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
+ """Expand python variables in a string.
+
+ The depth argument indicates how many frames above the caller should
+ be walked to look for the local namespace where to expand variables.
+
+ The global namespace for expansion is always the user's interactive
+ namespace.
+ """
+ ns = self.user_ns.copy()
+ try:
+ frame = sys._getframe(depth+1)
+ except ValueError:
+ # This is thrown if there aren't that many frames on the stack,
+ # e.g. if a script called run_line_magic() directly.
+ pass
+ else:
+ ns.update(frame.f_locals)
+
+ try:
+ # We have to use .vformat() here, because 'self' is a valid and common
+ # name, and expanding **ns for .format() would make it collide with
+ # the 'self' argument of the method.
+ cmd = formatter.vformat(cmd, args=[], kwargs=ns)
+ except Exception:
+ # if formatter couldn't format, just let it go untransformed
+ pass
+ return cmd
+
+ def mktempfile(self, data=None, prefix='ipython_edit_'):
+ """Make a new tempfile and return its filename.
+
+ This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
+ but it registers the created filename internally so ipython cleans it up
+ at exit time.
+
+ Optional inputs:
+
+ - data(None): if data is given, it gets written out to the temp file
+ immediately, and the file is closed again."""
+
+ dirname = tempfile.mkdtemp(prefix=prefix)
+ self.tempdirs.append(dirname)
+
+ handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
+ os.close(handle) # On Windows, there can only be one open handle on a file
+ self.tempfiles.append(filename)
+
+ if data:
+ tmp_file = open(filename,'w')
+ tmp_file.write(data)
+ tmp_file.close()
+ return filename
+
@undoc
- def write(self,data):
+ def write(self,data):
"""DEPRECATED: Write a string to the default output"""
warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
DeprecationWarning, stacklevel=2)
sys.stdout.write(data)
-
+
@undoc
- def write_err(self,data):
+ def write_err(self,data):
"""DEPRECATED: Write a string to the default error output"""
warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
DeprecationWarning, stacklevel=2)
sys.stderr.write(data)
-
- def ask_yes_no(self, prompt, default=None, interrupt=None):
- if self.quiet:
- return True
- return ask_yes_no(prompt,default,interrupt)
-
- def show_usage(self):
- """Show a usage message"""
- page.page(IPython.core.usage.interactive_usage)
-
- def extract_input_lines(self, range_str, raw=False):
- """Return as a string a set of input history slices.
-
- Parameters
- ----------
- range_str : string
- The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
- since this function is for use by magic functions which get their
- arguments as strings. The number before the / is the session
- number: ~n goes n back from the current session.
-
- raw : bool, optional
- By default, the processed input is used. If this is true, the raw
- input history is used instead.
-
- Notes
- -----
-
- Slices can be described with two notations:
-
- * ``N:M`` -> standard python form, means including items N...(M-1).
- * ``N-M`` -> include items N..M (closed endpoint).
- """
- lines = self.history_manager.get_range_by_str(range_str, raw=raw)
- return "\n".join(x for _, _, x in lines)
-
- def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
- """Get a code string from history, file, url, or a string or macro.
-
- This is mainly used by magic functions.
-
- Parameters
- ----------
-
- target : str
-
- A string specifying code to retrieve. This will be tried respectively
- as: ranges of input history (see %history for syntax), url,
- corresponding .py file, filename, or an expression evaluating to a
- string or Macro in the user namespace.
-
- raw : bool
- If true (default), retrieve raw history. Has no effect on the other
- retrieval mechanisms.
-
- py_only : bool (default False)
- Only try to fetch python code, do not try alternative methods to decode file
- if unicode fails.
-
- Returns
- -------
- A string of code.
-
- ValueError is raised if nothing is found, and TypeError if it evaluates
- to an object of another type. In each case, .args[0] is a printable
- message.
- """
- code = self.extract_input_lines(target, raw=raw) # Grab history
- if code:
- return code
- try:
+
+ def ask_yes_no(self, prompt, default=None, interrupt=None):
+ if self.quiet:
+ return True
+ return ask_yes_no(prompt,default,interrupt)
+
+ def show_usage(self):
+ """Show a usage message"""
+ page.page(IPython.core.usage.interactive_usage)
+
+ def extract_input_lines(self, range_str, raw=False):
+ """Return as a string a set of input history slices.
+
+ Parameters
+ ----------
+ range_str : string
+ The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
+ since this function is for use by magic functions which get their
+ arguments as strings. The number before the / is the session
+ number: ~n goes n back from the current session.
+
+ raw : bool, optional
+ By default, the processed input is used. If this is true, the raw
+ input history is used instead.
+
+ Notes
+ -----
+
+ Slices can be described with two notations:
+
+ * ``N:M`` -> standard python form, means including items N...(M-1).
+ * ``N-M`` -> include items N..M (closed endpoint).
+ """
+ lines = self.history_manager.get_range_by_str(range_str, raw=raw)
+ return "\n".join(x for _, _, x in lines)
+
+ def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
+ """Get a code string from history, file, url, or a string or macro.
+
+ This is mainly used by magic functions.
+
+ Parameters
+ ----------
+
+ target : str
+
+ A string specifying code to retrieve. This will be tried respectively
+ as: ranges of input history (see %history for syntax), url,
+ corresponding .py file, filename, or an expression evaluating to a
+ string or Macro in the user namespace.
+
+ raw : bool
+ If true (default), retrieve raw history. Has no effect on the other
+ retrieval mechanisms.
+
+ py_only : bool (default False)
+ Only try to fetch python code, do not try alternative methods to decode file
+ if unicode fails.
+
+ Returns
+ -------
+ A string of code.
+
+ ValueError is raised if nothing is found, and TypeError if it evaluates
+ to an object of another type. In each case, .args[0] is a printable
+ message.
+ """
+ code = self.extract_input_lines(target, raw=raw) # Grab history
+ if code:
+ return code
+ try:
if target.startswith(('http://', 'https://')):
return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
- except UnicodeDecodeError:
- if not py_only :
- # Deferred import
- try:
- from urllib.request import urlopen # Py3
- except ImportError:
- from urllib import urlopen
- response = urlopen(target)
- return response.read().decode('latin1')
+ except UnicodeDecodeError:
+ if not py_only :
+ # Deferred import
+ try:
+ from urllib.request import urlopen # Py3
+ except ImportError:
+ from urllib import urlopen
+ response = urlopen(target)
+ return response.read().decode('latin1')
raise ValueError(("'%s' seem to be unreadable.") % target)
-
- potential_target = [target]
- try :
- potential_target.insert(0,get_py_filename(target))
- except IOError:
- pass
-
- for tgt in potential_target :
- if os.path.isfile(tgt): # Read file
- try :
- return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
- except UnicodeDecodeError :
- if not py_only :
- with io_open(tgt,'r', encoding='latin1') as f :
- return f.read()
- raise ValueError(("'%s' seem to be unreadable.") % target)
- elif os.path.isdir(os.path.expanduser(tgt)):
- raise ValueError("'%s' is a directory, not a regular file." % target)
-
- if search_ns:
- # Inspect namespace to load object source
- object_info = self.object_inspect(target, detail_level=1)
- if object_info['found'] and object_info['source']:
- return object_info['source']
-
- try: # User namespace
- codeobj = eval(target, self.user_ns)
- except Exception:
- raise ValueError(("'%s' was not found in history, as a file, url, "
- "nor in the user namespace.") % target)
-
- if isinstance(codeobj, string_types):
- return codeobj
- elif isinstance(codeobj, Macro):
- return codeobj.value
-
- raise TypeError("%s is neither a string nor a macro." % target,
- codeobj)
-
- #-------------------------------------------------------------------------
- # Things related to IPython exiting
- #-------------------------------------------------------------------------
- def atexit_operations(self):
- """This will be executed at the time of exit.
-
- Cleanup operations and saving of persistent data that is done
- unconditionally by IPython should be performed here.
-
- For things that may depend on startup flags or platform specifics (such
- as having readline or not), register a separate atexit function in the
- code that has the appropriate information, rather than trying to
- clutter
- """
- # Close the history session (this stores the end time and line count)
- # this must be *before* the tempfile cleanup, in case of temporary
- # history db
- self.history_manager.end_session()
-
- # Cleanup all tempfiles and folders left around
- for tfile in self.tempfiles:
- try:
- os.unlink(tfile)
- except OSError:
- pass
-
- for tdir in self.tempdirs:
- try:
- os.rmdir(tdir)
- except OSError:
- pass
-
- # Clear all user namespaces to release all references cleanly.
- self.reset(new_session=False)
-
- # Run user hooks
- self.hooks.shutdown_hook()
-
- def cleanup(self):
- self.restore_sys_module_state()
-
-
+
+ potential_target = [target]
+ try :
+ potential_target.insert(0,get_py_filename(target))
+ except IOError:
+ pass
+
+ for tgt in potential_target :
+ if os.path.isfile(tgt): # Read file
+ try :
+ return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
+ except UnicodeDecodeError :
+ if not py_only :
+ with io_open(tgt,'r', encoding='latin1') as f :
+ return f.read()
+ raise ValueError(("'%s' seem to be unreadable.") % target)
+ elif os.path.isdir(os.path.expanduser(tgt)):
+ raise ValueError("'%s' is a directory, not a regular file." % target)
+
+ if search_ns:
+ # Inspect namespace to load object source
+ object_info = self.object_inspect(target, detail_level=1)
+ if object_info['found'] and object_info['source']:
+ return object_info['source']
+
+ try: # User namespace
+ codeobj = eval(target, self.user_ns)
+ except Exception:
+ raise ValueError(("'%s' was not found in history, as a file, url, "
+ "nor in the user namespace.") % target)
+
+ if isinstance(codeobj, string_types):
+ return codeobj
+ elif isinstance(codeobj, Macro):
+ return codeobj.value
+
+ raise TypeError("%s is neither a string nor a macro." % target,
+ codeobj)
+
+ #-------------------------------------------------------------------------
+ # Things related to IPython exiting
+ #-------------------------------------------------------------------------
+ def atexit_operations(self):
+ """This will be executed at the time of exit.
+
+ Cleanup operations and saving of persistent data that is done
+ unconditionally by IPython should be performed here.
+
+ For things that may depend on startup flags or platform specifics (such
+ as having readline or not), register a separate atexit function in the
+ code that has the appropriate information, rather than trying to
+ clutter
+ """
+ # Close the history session (this stores the end time and line count)
+ # this must be *before* the tempfile cleanup, in case of temporary
+ # history db
+ self.history_manager.end_session()
+
+ # Cleanup all tempfiles and folders left around
+ for tfile in self.tempfiles:
+ try:
+ os.unlink(tfile)
+ except OSError:
+ pass
+
+ for tdir in self.tempdirs:
+ try:
+ os.rmdir(tdir)
+ except OSError:
+ pass
+
+ # Clear all user namespaces to release all references cleanly.
+ self.reset(new_session=False)
+
+ # Run user hooks
+ self.hooks.shutdown_hook()
+
+ def cleanup(self):
+ self.restore_sys_module_state()
+
+
# Overridden in terminal subclass to change prompts
def switch_doctest_mode(self, mode):
pass
-class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
- """An abstract base class for InteractiveShell."""
-
-InteractiveShellABC.register(InteractiveShell)
+class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
+ """An abstract base class for InteractiveShell."""
+
+InteractiveShellABC.register(InteractiveShell)
diff --git a/contrib/python/ipython/py2/IPython/core/latex_symbols.py b/contrib/python/ipython/py2/IPython/core/latex_symbols.py
index 0319b99ff8..ca7200bb59 100644
--- a/contrib/python/ipython/py2/IPython/core/latex_symbols.py
+++ b/contrib/python/ipython/py2/IPython/core/latex_symbols.py
@@ -1,1300 +1,1300 @@
-# encoding: utf-8
-
-# DO NOT EDIT THIS FILE BY HAND.
-
-# To update this file, run the script /tools/gen_latex_symbols.py using Python 3
-
-# This file is autogenerated from the file:
-# https://raw.githubusercontent.com/JuliaLang/julia/master/base/latex_symbols.jl
-# This original list is filtered to remove any unicode characters that are not valid
-# Python identifiers.
-
-latex_symbols = {
-
- "\\^a" : "ᵃ",
- "\\^b" : "ᵇ",
- "\\^c" : "ᶜ",
- "\\^d" : "ᵈ",
- "\\^e" : "ᵉ",
- "\\^f" : "ᶠ",
- "\\^g" : "ᵍ",
- "\\^h" : "ʰ",
- "\\^i" : "ⁱ",
- "\\^j" : "ʲ",
- "\\^k" : "ᵏ",
- "\\^l" : "ˡ",
- "\\^m" : "ᵐ",
- "\\^n" : "ⁿ",
- "\\^o" : "ᵒ",
- "\\^p" : "ᵖ",
- "\\^r" : "ʳ",
- "\\^s" : "ˢ",
- "\\^t" : "ᵗ",
- "\\^u" : "ᵘ",
- "\\^v" : "ᵛ",
- "\\^w" : "ʷ",
- "\\^x" : "ˣ",
- "\\^y" : "ʸ",
- "\\^z" : "ᶻ",
- "\\^A" : "ᴬ",
- "\\^B" : "ᴮ",
- "\\^D" : "ᴰ",
- "\\^E" : "ᴱ",
- "\\^G" : "ᴳ",
- "\\^H" : "ᴴ",
- "\\^I" : "ᴵ",
- "\\^J" : "ᴶ",
- "\\^K" : "ᴷ",
- "\\^L" : "ᴸ",
- "\\^M" : "ᴹ",
- "\\^N" : "ᴺ",
- "\\^O" : "ᴼ",
- "\\^P" : "ᴾ",
- "\\^R" : "ᴿ",
- "\\^T" : "ᵀ",
- "\\^U" : "ᵁ",
- "\\^V" : "ⱽ",
- "\\^W" : "ᵂ",
- "\\^alpha" : "ᵅ",
- "\\^beta" : "ᵝ",
- "\\^gamma" : "ᵞ",
- "\\^delta" : "ᵟ",
- "\\^epsilon" : "ᵋ",
- "\\^theta" : "ᶿ",
- "\\^iota" : "ᶥ",
- "\\^phi" : "ᵠ",
- "\\^chi" : "ᵡ",
- "\\^Phi" : "ᶲ",
- "\\_a" : "ₐ",
- "\\_e" : "ₑ",
- "\\_h" : "ₕ",
- "\\_i" : "ᵢ",
- "\\_j" : "ⱼ",
- "\\_k" : "ₖ",
- "\\_l" : "ₗ",
- "\\_m" : "ₘ",
- "\\_n" : "ₙ",
- "\\_o" : "ₒ",
- "\\_p" : "ₚ",
- "\\_r" : "ᵣ",
- "\\_s" : "ₛ",
- "\\_t" : "ₜ",
- "\\_u" : "ᵤ",
- "\\_v" : "ᵥ",
- "\\_x" : "ₓ",
- "\\_schwa" : "ₔ",
- "\\_beta" : "ᵦ",
- "\\_gamma" : "ᵧ",
- "\\_rho" : "ᵨ",
- "\\_phi" : "ᵩ",
- "\\_chi" : "ᵪ",
- "\\hbar" : "ħ",
- "\\sout" : "̶",
- "\\textordfeminine" : "ª",
- "\\cdotp" : "·",
- "\\textordmasculine" : "º",
- "\\AA" : "Å",
- "\\AE" : "Æ",
- "\\DH" : "Ð",
- "\\O" : "Ø",
- "\\TH" : "Þ",
- "\\ss" : "ß",
- "\\aa" : "å",
- "\\ae" : "æ",
- "\\eth" : "ð",
- "\\o" : "ø",
- "\\th" : "þ",
- "\\DJ" : "Đ",
- "\\dj" : "đ",
- "\\Elzxh" : "ħ",
- "\\imath" : "ı",
- "\\L" : "Ł",
- "\\l" : "ł",
- "\\NG" : "Ŋ",
- "\\ng" : "ŋ",
- "\\OE" : "Œ",
- "\\oe" : "œ",
- "\\texthvlig" : "ƕ",
- "\\textnrleg" : "ƞ",
- "\\textdoublepipe" : "ǂ",
- "\\Elztrna" : "ɐ",
- "\\Elztrnsa" : "ɒ",
- "\\Elzopeno" : "ɔ",
- "\\Elzrtld" : "ɖ",
- "\\Elzschwa" : "ə",
- "\\varepsilon" : "ɛ",
- "\\Elzpgamma" : "ɣ",
- "\\Elzpbgam" : "ɤ",
- "\\Elztrnh" : "ɥ",
- "\\Elzbtdl" : "ɬ",
- "\\Elzrtll" : "ɭ",
- "\\Elztrnm" : "ɯ",
- "\\Elztrnmlr" : "ɰ",
- "\\Elzltlmr" : "ɱ",
- "\\Elzltln" : "ɲ",
- "\\Elzrtln" : "ɳ",
- "\\Elzclomeg" : "ɷ",
- "\\textphi" : "ɸ",
- "\\Elztrnr" : "ɹ",
- "\\Elztrnrl" : "ɺ",
- "\\Elzrttrnr" : "ɻ",
- "\\Elzrl" : "ɼ",
- "\\Elzrtlr" : "ɽ",
- "\\Elzfhr" : "ɾ",
- "\\Elzrtls" : "ʂ",
- "\\Elzesh" : "ʃ",
- "\\Elztrnt" : "ʇ",
- "\\Elzrtlt" : "ʈ",
- "\\Elzpupsil" : "ʊ",
- "\\Elzpscrv" : "ʋ",
- "\\Elzinvv" : "ʌ",
- "\\Elzinvw" : "ʍ",
- "\\Elztrny" : "ʎ",
- "\\Elzrtlz" : "ʐ",
- "\\Elzyogh" : "ʒ",
- "\\Elzglst" : "ʔ",
- "\\Elzreglst" : "ʕ",
- "\\Elzinglst" : "ʖ",
- "\\textturnk" : "ʞ",
- "\\Elzdyogh" : "ʤ",
- "\\Elztesh" : "ʧ",
- "\\rasp" : "ʼ",
- "\\textasciicaron" : "ˇ",
- "\\Elzverts" : "ˈ",
- "\\Elzverti" : "ˌ",
- "\\Elzlmrk" : "ː",
- "\\Elzhlmrk" : "ˑ",
- "\\grave" : "̀",
- "\\acute" : "́",
- "\\hat" : "̂",
- "\\tilde" : "̃",
- "\\bar" : "̄",
- "\\breve" : "̆",
- "\\dot" : "̇",
- "\\ddot" : "̈",
- "\\ocirc" : "̊",
- "\\H" : "̋",
- "\\check" : "̌",
- "\\Elzpalh" : "̡",
- "\\Elzrh" : "̢",
- "\\c" : "̧",
- "\\k" : "̨",
- "\\Elzsbbrg" : "̪",
- "\\Elzxl" : "̵",
- "\\Elzbar" : "̶",
- "\\Alpha" : "Α",
- "\\Beta" : "Β",
- "\\Gamma" : "Γ",
- "\\Delta" : "Δ",
- "\\Epsilon" : "Ε",
- "\\Zeta" : "Ζ",
- "\\Eta" : "Η",
- "\\Theta" : "Θ",
- "\\Iota" : "Ι",
- "\\Kappa" : "Κ",
- "\\Lambda" : "Λ",
- "\\Xi" : "Ξ",
- "\\Pi" : "Π",
- "\\Rho" : "Ρ",
- "\\Sigma" : "Σ",
- "\\Tau" : "Τ",
- "\\Upsilon" : "Υ",
- "\\Phi" : "Φ",
- "\\Chi" : "Χ",
- "\\Psi" : "Ψ",
- "\\Omega" : "Ω",
- "\\alpha" : "α",
- "\\beta" : "β",
- "\\gamma" : "γ",
- "\\delta" : "δ",
- "\\zeta" : "ζ",
- "\\eta" : "η",
- "\\theta" : "θ",
- "\\iota" : "ι",
- "\\kappa" : "κ",
- "\\lambda" : "λ",
- "\\mu" : "μ",
- "\\nu" : "ν",
- "\\xi" : "ξ",
- "\\pi" : "π",
- "\\rho" : "ρ",
- "\\varsigma" : "ς",
- "\\sigma" : "σ",
- "\\tau" : "τ",
- "\\upsilon" : "υ",
- "\\varphi" : "φ",
- "\\chi" : "χ",
- "\\psi" : "ψ",
- "\\omega" : "ω",
- "\\vartheta" : "ϑ",
- "\\phi" : "ϕ",
- "\\varpi" : "ϖ",
- "\\Stigma" : "Ϛ",
- "\\Digamma" : "Ϝ",
- "\\digamma" : "ϝ",
- "\\Koppa" : "Ϟ",
- "\\Sampi" : "Ϡ",
- "\\varkappa" : "ϰ",
- "\\varrho" : "ϱ",
- "\\textTheta" : "ϴ",
- "\\epsilon" : "ϵ",
- "\\dddot" : "⃛",
- "\\ddddot" : "⃜",
- "\\hslash" : "ℏ",
- "\\Im" : "ℑ",
- "\\ell" : "ℓ",
- "\\wp" : "℘",
- "\\Re" : "ℜ",
- "\\aleph" : "ℵ",
- "\\beth" : "ℶ",
- "\\gimel" : "ℷ",
- "\\daleth" : "ℸ",
- "\\BbbPi" : "ℿ",
- "\\Zbar" : "Ƶ",
- "\\overbar" : "̅",
- "\\ovhook" : "̉",
- "\\candra" : "̐",
- "\\oturnedcomma" : "̒",
- "\\ocommatopright" : "̕",
- "\\droang" : "̚",
- "\\wideutilde" : "̰",
- "\\underbar" : "̱",
- "\\not" : "̸",
- "\\upMu" : "Μ",
- "\\upNu" : "Ν",
- "\\upOmicron" : "Ο",
- "\\upepsilon" : "ε",
- "\\upomicron" : "ο",
- "\\upvarbeta" : "ϐ",
- "\\upoldKoppa" : "Ϙ",
- "\\upoldkoppa" : "ϙ",
- "\\upstigma" : "ϛ",
- "\\upkoppa" : "ϟ",
- "\\upsampi" : "ϡ",
- "\\tieconcat" : "⁀",
- "\\leftharpoonaccent" : "⃐",
- "\\rightharpoonaccent" : "⃑",
- "\\vertoverlay" : "⃒",
- "\\overleftarrow" : "⃖",
- "\\vec" : "⃗",
- "\\overleftrightarrow" : "⃡",
- "\\annuity" : "⃧",
- "\\threeunderdot" : "⃨",
- "\\widebridgeabove" : "⃩",
- "\\BbbC" : "ℂ",
- "\\Eulerconst" : "ℇ",
- "\\mscrg" : "ℊ",
- "\\mscrH" : "ℋ",
- "\\mfrakH" : "ℌ",
- "\\BbbH" : "ℍ",
- "\\Planckconst" : "ℎ",
- "\\mscrI" : "ℐ",
- "\\mscrL" : "ℒ",
- "\\BbbN" : "ℕ",
- "\\BbbP" : "ℙ",
- "\\BbbQ" : "ℚ",
- "\\mscrR" : "ℛ",
- "\\BbbR" : "ℝ",
- "\\BbbZ" : "ℤ",
- "\\mfrakZ" : "ℨ",
- "\\Angstrom" : "Å",
- "\\mscrB" : "ℬ",
- "\\mfrakC" : "ℭ",
- "\\mscre" : "ℯ",
- "\\mscrE" : "ℰ",
- "\\mscrF" : "ℱ",
- "\\Finv" : "Ⅎ",
- "\\mscrM" : "ℳ",
- "\\mscro" : "ℴ",
- "\\Bbbgamma" : "ℽ",
- "\\BbbGamma" : "ℾ",
- "\\mitBbbD" : "ⅅ",
- "\\mitBbbd" : "ⅆ",
- "\\mitBbbe" : "ⅇ",
- "\\mitBbbi" : "ⅈ",
- "\\mitBbbj" : "ⅉ",
- "\\mbfA" : "𝐀",
- "\\mbfB" : "𝐁",
- "\\mbfC" : "𝐂",
- "\\mbfD" : "𝐃",
- "\\mbfE" : "𝐄",
- "\\mbfF" : "𝐅",
- "\\mbfG" : "𝐆",
- "\\mbfH" : "𝐇",
- "\\mbfI" : "𝐈",
- "\\mbfJ" : "𝐉",
- "\\mbfK" : "𝐊",
- "\\mbfL" : "𝐋",
- "\\mbfM" : "𝐌",
- "\\mbfN" : "𝐍",
- "\\mbfO" : "𝐎",
- "\\mbfP" : "𝐏",
- "\\mbfQ" : "𝐐",
- "\\mbfR" : "𝐑",
- "\\mbfS" : "𝐒",
- "\\mbfT" : "𝐓",
- "\\mbfU" : "𝐔",
- "\\mbfV" : "𝐕",
- "\\mbfW" : "𝐖",
- "\\mbfX" : "𝐗",
- "\\mbfY" : "𝐘",
- "\\mbfZ" : "𝐙",
- "\\mbfa" : "𝐚",
- "\\mbfb" : "𝐛",
- "\\mbfc" : "𝐜",
- "\\mbfd" : "𝐝",
- "\\mbfe" : "𝐞",
- "\\mbff" : "𝐟",
- "\\mbfg" : "𝐠",
- "\\mbfh" : "𝐡",
- "\\mbfi" : "𝐢",
- "\\mbfj" : "𝐣",
- "\\mbfk" : "𝐤",
- "\\mbfl" : "𝐥",
- "\\mbfm" : "𝐦",
- "\\mbfn" : "𝐧",
- "\\mbfo" : "𝐨",
- "\\mbfp" : "𝐩",
- "\\mbfq" : "𝐪",
- "\\mbfr" : "𝐫",
- "\\mbfs" : "𝐬",
- "\\mbft" : "𝐭",
- "\\mbfu" : "𝐮",
- "\\mbfv" : "𝐯",
- "\\mbfw" : "𝐰",
- "\\mbfx" : "𝐱",
- "\\mbfy" : "𝐲",
- "\\mbfz" : "𝐳",
- "\\mitA" : "𝐴",
- "\\mitB" : "𝐵",
- "\\mitC" : "𝐶",
- "\\mitD" : "𝐷",
- "\\mitE" : "𝐸",
- "\\mitF" : "𝐹",
- "\\mitG" : "𝐺",
- "\\mitH" : "𝐻",
- "\\mitI" : "𝐼",
- "\\mitJ" : "𝐽",
- "\\mitK" : "𝐾",
- "\\mitL" : "𝐿",
- "\\mitM" : "𝑀",
- "\\mitN" : "𝑁",
- "\\mitO" : "𝑂",
- "\\mitP" : "𝑃",
- "\\mitQ" : "𝑄",
- "\\mitR" : "𝑅",
- "\\mitS" : "𝑆",
- "\\mitT" : "𝑇",
- "\\mitU" : "𝑈",
- "\\mitV" : "𝑉",
- "\\mitW" : "𝑊",
- "\\mitX" : "𝑋",
- "\\mitY" : "𝑌",
- "\\mitZ" : "𝑍",
- "\\mita" : "𝑎",
- "\\mitb" : "𝑏",
- "\\mitc" : "𝑐",
- "\\mitd" : "𝑑",
- "\\mite" : "𝑒",
- "\\mitf" : "𝑓",
- "\\mitg" : "𝑔",
- "\\miti" : "𝑖",
- "\\mitj" : "𝑗",
- "\\mitk" : "𝑘",
- "\\mitl" : "𝑙",
- "\\mitm" : "𝑚",
- "\\mitn" : "𝑛",
- "\\mito" : "𝑜",
- "\\mitp" : "𝑝",
- "\\mitq" : "𝑞",
- "\\mitr" : "𝑟",
- "\\mits" : "𝑠",
- "\\mitt" : "𝑡",
- "\\mitu" : "𝑢",
- "\\mitv" : "𝑣",
- "\\mitw" : "𝑤",
- "\\mitx" : "𝑥",
- "\\mity" : "𝑦",
- "\\mitz" : "𝑧",
- "\\mbfitA" : "𝑨",
- "\\mbfitB" : "𝑩",
- "\\mbfitC" : "𝑪",
- "\\mbfitD" : "𝑫",
- "\\mbfitE" : "𝑬",
- "\\mbfitF" : "𝑭",
- "\\mbfitG" : "𝑮",
- "\\mbfitH" : "𝑯",
- "\\mbfitI" : "𝑰",
- "\\mbfitJ" : "𝑱",
- "\\mbfitK" : "𝑲",
- "\\mbfitL" : "𝑳",
- "\\mbfitM" : "𝑴",
- "\\mbfitN" : "𝑵",
- "\\mbfitO" : "𝑶",
- "\\mbfitP" : "𝑷",
- "\\mbfitQ" : "𝑸",
- "\\mbfitR" : "𝑹",
- "\\mbfitS" : "𝑺",
- "\\mbfitT" : "𝑻",
- "\\mbfitU" : "𝑼",
- "\\mbfitV" : "𝑽",
- "\\mbfitW" : "𝑾",
- "\\mbfitX" : "𝑿",
- "\\mbfitY" : "𝒀",
- "\\mbfitZ" : "𝒁",
- "\\mbfita" : "𝒂",
- "\\mbfitb" : "𝒃",
- "\\mbfitc" : "𝒄",
- "\\mbfitd" : "𝒅",
- "\\mbfite" : "𝒆",
- "\\mbfitf" : "𝒇",
- "\\mbfitg" : "𝒈",
- "\\mbfith" : "𝒉",
- "\\mbfiti" : "𝒊",
- "\\mbfitj" : "𝒋",
- "\\mbfitk" : "𝒌",
- "\\mbfitl" : "𝒍",
- "\\mbfitm" : "𝒎",
- "\\mbfitn" : "𝒏",
- "\\mbfito" : "𝒐",
- "\\mbfitp" : "𝒑",
- "\\mbfitq" : "𝒒",
- "\\mbfitr" : "𝒓",
- "\\mbfits" : "𝒔",
- "\\mbfitt" : "𝒕",
- "\\mbfitu" : "𝒖",
- "\\mbfitv" : "𝒗",
- "\\mbfitw" : "𝒘",
- "\\mbfitx" : "𝒙",
- "\\mbfity" : "𝒚",
- "\\mbfitz" : "𝒛",
- "\\mscrA" : "𝒜",
- "\\mscrC" : "𝒞",
- "\\mscrD" : "𝒟",
- "\\mscrG" : "𝒢",
- "\\mscrJ" : "𝒥",
- "\\mscrK" : "𝒦",
- "\\mscrN" : "𝒩",
- "\\mscrO" : "𝒪",
- "\\mscrP" : "𝒫",
- "\\mscrQ" : "𝒬",
- "\\mscrS" : "𝒮",
- "\\mscrT" : "𝒯",
- "\\mscrU" : "𝒰",
- "\\mscrV" : "𝒱",
- "\\mscrW" : "𝒲",
- "\\mscrX" : "𝒳",
- "\\mscrY" : "𝒴",
- "\\mscrZ" : "𝒵",
- "\\mscra" : "𝒶",
- "\\mscrb" : "𝒷",
- "\\mscrc" : "𝒸",
- "\\mscrd" : "𝒹",
- "\\mscrf" : "𝒻",
- "\\mscrh" : "𝒽",
- "\\mscri" : "𝒾",
- "\\mscrj" : "𝒿",
- "\\mscrk" : "𝓀",
- "\\mscrm" : "𝓂",
- "\\mscrn" : "𝓃",
- "\\mscrp" : "𝓅",
- "\\mscrq" : "𝓆",
- "\\mscrr" : "𝓇",
- "\\mscrs" : "𝓈",
- "\\mscrt" : "𝓉",
- "\\mscru" : "𝓊",
- "\\mscrv" : "𝓋",
- "\\mscrw" : "𝓌",
- "\\mscrx" : "𝓍",
- "\\mscry" : "𝓎",
- "\\mscrz" : "𝓏",
- "\\mbfscrA" : "𝓐",
- "\\mbfscrB" : "𝓑",
- "\\mbfscrC" : "𝓒",
- "\\mbfscrD" : "𝓓",
- "\\mbfscrE" : "𝓔",
- "\\mbfscrF" : "𝓕",
- "\\mbfscrG" : "𝓖",
- "\\mbfscrH" : "𝓗",
- "\\mbfscrI" : "𝓘",
- "\\mbfscrJ" : "𝓙",
- "\\mbfscrK" : "𝓚",
- "\\mbfscrL" : "𝓛",
- "\\mbfscrM" : "𝓜",
- "\\mbfscrN" : "𝓝",
- "\\mbfscrO" : "𝓞",
- "\\mbfscrP" : "𝓟",
- "\\mbfscrQ" : "𝓠",
- "\\mbfscrR" : "𝓡",
- "\\mbfscrS" : "𝓢",
- "\\mbfscrT" : "𝓣",
- "\\mbfscrU" : "𝓤",
- "\\mbfscrV" : "𝓥",
- "\\mbfscrW" : "𝓦",
- "\\mbfscrX" : "𝓧",
- "\\mbfscrY" : "𝓨",
- "\\mbfscrZ" : "𝓩",
- "\\mbfscra" : "𝓪",
- "\\mbfscrb" : "𝓫",
- "\\mbfscrc" : "𝓬",
- "\\mbfscrd" : "𝓭",
- "\\mbfscre" : "𝓮",
- "\\mbfscrf" : "𝓯",
- "\\mbfscrg" : "𝓰",
- "\\mbfscrh" : "𝓱",
- "\\mbfscri" : "𝓲",
- "\\mbfscrj" : "𝓳",
- "\\mbfscrk" : "𝓴",
- "\\mbfscrl" : "𝓵",
- "\\mbfscrm" : "𝓶",
- "\\mbfscrn" : "𝓷",
- "\\mbfscro" : "𝓸",
- "\\mbfscrp" : "𝓹",
- "\\mbfscrq" : "𝓺",
- "\\mbfscrr" : "𝓻",
- "\\mbfscrs" : "𝓼",
- "\\mbfscrt" : "𝓽",
- "\\mbfscru" : "𝓾",
- "\\mbfscrv" : "𝓿",
- "\\mbfscrw" : "𝔀",
- "\\mbfscrx" : "𝔁",
- "\\mbfscry" : "𝔂",
- "\\mbfscrz" : "𝔃",
- "\\mfrakA" : "𝔄",
- "\\mfrakB" : "𝔅",
- "\\mfrakD" : "𝔇",
- "\\mfrakE" : "𝔈",
- "\\mfrakF" : "𝔉",
- "\\mfrakG" : "𝔊",
- "\\mfrakJ" : "𝔍",
- "\\mfrakK" : "𝔎",
- "\\mfrakL" : "𝔏",
- "\\mfrakM" : "𝔐",
- "\\mfrakN" : "𝔑",
- "\\mfrakO" : "𝔒",
- "\\mfrakP" : "𝔓",
- "\\mfrakQ" : "𝔔",
- "\\mfrakS" : "𝔖",
- "\\mfrakT" : "𝔗",
- "\\mfrakU" : "𝔘",
- "\\mfrakV" : "𝔙",
- "\\mfrakW" : "𝔚",
- "\\mfrakX" : "𝔛",
- "\\mfrakY" : "𝔜",
- "\\mfraka" : "𝔞",
- "\\mfrakb" : "𝔟",
- "\\mfrakc" : "𝔠",
- "\\mfrakd" : "𝔡",
- "\\mfrake" : "𝔢",
- "\\mfrakf" : "𝔣",
- "\\mfrakg" : "𝔤",
- "\\mfrakh" : "𝔥",
- "\\mfraki" : "𝔦",
- "\\mfrakj" : "𝔧",
- "\\mfrakk" : "𝔨",
- "\\mfrakl" : "𝔩",
- "\\mfrakm" : "𝔪",
- "\\mfrakn" : "𝔫",
- "\\mfrako" : "𝔬",
- "\\mfrakp" : "𝔭",
- "\\mfrakq" : "𝔮",
- "\\mfrakr" : "𝔯",
- "\\mfraks" : "𝔰",
- "\\mfrakt" : "𝔱",
- "\\mfraku" : "𝔲",
- "\\mfrakv" : "𝔳",
- "\\mfrakw" : "𝔴",
- "\\mfrakx" : "𝔵",
- "\\mfraky" : "𝔶",
- "\\mfrakz" : "𝔷",
- "\\BbbA" : "𝔸",
- "\\BbbB" : "𝔹",
- "\\BbbD" : "𝔻",
- "\\BbbE" : "𝔼",
- "\\BbbF" : "𝔽",
- "\\BbbG" : "𝔾",
- "\\BbbI" : "𝕀",
- "\\BbbJ" : "𝕁",
- "\\BbbK" : "𝕂",
- "\\BbbL" : "𝕃",
- "\\BbbM" : "𝕄",
- "\\BbbO" : "𝕆",
- "\\BbbS" : "𝕊",
- "\\BbbT" : "𝕋",
- "\\BbbU" : "𝕌",
- "\\BbbV" : "𝕍",
- "\\BbbW" : "𝕎",
- "\\BbbX" : "𝕏",
- "\\BbbY" : "𝕐",
- "\\Bbba" : "𝕒",
- "\\Bbbb" : "𝕓",
- "\\Bbbc" : "𝕔",
- "\\Bbbd" : "𝕕",
- "\\Bbbe" : "𝕖",
- "\\Bbbf" : "𝕗",
- "\\Bbbg" : "𝕘",
- "\\Bbbh" : "𝕙",
- "\\Bbbi" : "𝕚",
- "\\Bbbj" : "𝕛",
- "\\Bbbk" : "𝕜",
- "\\Bbbl" : "𝕝",
- "\\Bbbm" : "𝕞",
- "\\Bbbn" : "𝕟",
- "\\Bbbo" : "𝕠",
- "\\Bbbp" : "𝕡",
- "\\Bbbq" : "𝕢",
- "\\Bbbr" : "𝕣",
- "\\Bbbs" : "𝕤",
- "\\Bbbt" : "𝕥",
- "\\Bbbu" : "𝕦",
- "\\Bbbv" : "𝕧",
- "\\Bbbw" : "𝕨",
- "\\Bbbx" : "𝕩",
- "\\Bbby" : "𝕪",
- "\\Bbbz" : "𝕫",
- "\\mbffrakA" : "𝕬",
- "\\mbffrakB" : "𝕭",
- "\\mbffrakC" : "𝕮",
- "\\mbffrakD" : "𝕯",
- "\\mbffrakE" : "𝕰",
- "\\mbffrakF" : "𝕱",
- "\\mbffrakG" : "𝕲",
- "\\mbffrakH" : "𝕳",
- "\\mbffrakI" : "𝕴",
- "\\mbffrakJ" : "𝕵",
- "\\mbffrakK" : "𝕶",
- "\\mbffrakL" : "𝕷",
- "\\mbffrakM" : "𝕸",
- "\\mbffrakN" : "𝕹",
- "\\mbffrakO" : "𝕺",
- "\\mbffrakP" : "𝕻",
- "\\mbffrakQ" : "𝕼",
- "\\mbffrakR" : "𝕽",
- "\\mbffrakS" : "𝕾",
- "\\mbffrakT" : "𝕿",
- "\\mbffrakU" : "𝖀",
- "\\mbffrakV" : "𝖁",
- "\\mbffrakW" : "𝖂",
- "\\mbffrakX" : "𝖃",
- "\\mbffrakY" : "𝖄",
- "\\mbffrakZ" : "𝖅",
- "\\mbffraka" : "𝖆",
- "\\mbffrakb" : "𝖇",
- "\\mbffrakc" : "𝖈",
- "\\mbffrakd" : "𝖉",
- "\\mbffrake" : "𝖊",
- "\\mbffrakf" : "𝖋",
- "\\mbffrakg" : "𝖌",
- "\\mbffrakh" : "𝖍",
- "\\mbffraki" : "𝖎",
- "\\mbffrakj" : "𝖏",
- "\\mbffrakk" : "𝖐",
- "\\mbffrakl" : "𝖑",
- "\\mbffrakm" : "𝖒",
- "\\mbffrakn" : "𝖓",
- "\\mbffrako" : "𝖔",
- "\\mbffrakp" : "𝖕",
- "\\mbffrakq" : "𝖖",
- "\\mbffrakr" : "𝖗",
- "\\mbffraks" : "𝖘",
- "\\mbffrakt" : "𝖙",
- "\\mbffraku" : "𝖚",
- "\\mbffrakv" : "𝖛",
- "\\mbffrakw" : "𝖜",
- "\\mbffrakx" : "𝖝",
- "\\mbffraky" : "𝖞",
- "\\mbffrakz" : "𝖟",
- "\\msansA" : "𝖠",
- "\\msansB" : "𝖡",
- "\\msansC" : "𝖢",
- "\\msansD" : "𝖣",
- "\\msansE" : "𝖤",
- "\\msansF" : "𝖥",
- "\\msansG" : "𝖦",
- "\\msansH" : "𝖧",
- "\\msansI" : "𝖨",
- "\\msansJ" : "𝖩",
- "\\msansK" : "𝖪",
- "\\msansL" : "𝖫",
- "\\msansM" : "𝖬",
- "\\msansN" : "𝖭",
- "\\msansO" : "𝖮",
- "\\msansP" : "𝖯",
- "\\msansQ" : "𝖰",
- "\\msansR" : "𝖱",
- "\\msansS" : "𝖲",
- "\\msansT" : "𝖳",
- "\\msansU" : "𝖴",
- "\\msansV" : "𝖵",
- "\\msansW" : "𝖶",
- "\\msansX" : "𝖷",
- "\\msansY" : "𝖸",
- "\\msansZ" : "𝖹",
- "\\msansa" : "𝖺",
- "\\msansb" : "𝖻",
- "\\msansc" : "𝖼",
- "\\msansd" : "𝖽",
- "\\msanse" : "𝖾",
- "\\msansf" : "𝖿",
- "\\msansg" : "𝗀",
- "\\msansh" : "𝗁",
- "\\msansi" : "𝗂",
- "\\msansj" : "𝗃",
- "\\msansk" : "𝗄",
- "\\msansl" : "𝗅",
- "\\msansm" : "𝗆",
- "\\msansn" : "𝗇",
- "\\msanso" : "𝗈",
- "\\msansp" : "𝗉",
- "\\msansq" : "𝗊",
- "\\msansr" : "𝗋",
- "\\msanss" : "𝗌",
- "\\msanst" : "𝗍",
- "\\msansu" : "𝗎",
- "\\msansv" : "𝗏",
- "\\msansw" : "𝗐",
- "\\msansx" : "𝗑",
- "\\msansy" : "𝗒",
- "\\msansz" : "𝗓",
- "\\mbfsansA" : "𝗔",
- "\\mbfsansB" : "𝗕",
- "\\mbfsansC" : "𝗖",
- "\\mbfsansD" : "𝗗",
- "\\mbfsansE" : "𝗘",
- "\\mbfsansF" : "𝗙",
- "\\mbfsansG" : "𝗚",
- "\\mbfsansH" : "𝗛",
- "\\mbfsansI" : "𝗜",
- "\\mbfsansJ" : "𝗝",
- "\\mbfsansK" : "𝗞",
- "\\mbfsansL" : "𝗟",
- "\\mbfsansM" : "𝗠",
- "\\mbfsansN" : "𝗡",
- "\\mbfsansO" : "𝗢",
- "\\mbfsansP" : "𝗣",
- "\\mbfsansQ" : "𝗤",
- "\\mbfsansR" : "𝗥",
- "\\mbfsansS" : "𝗦",
- "\\mbfsansT" : "𝗧",
- "\\mbfsansU" : "𝗨",
- "\\mbfsansV" : "𝗩",
- "\\mbfsansW" : "𝗪",
- "\\mbfsansX" : "𝗫",
- "\\mbfsansY" : "𝗬",
- "\\mbfsansZ" : "𝗭",
- "\\mbfsansa" : "𝗮",
- "\\mbfsansb" : "𝗯",
- "\\mbfsansc" : "𝗰",
- "\\mbfsansd" : "𝗱",
- "\\mbfsanse" : "𝗲",
- "\\mbfsansf" : "𝗳",
- "\\mbfsansg" : "𝗴",
- "\\mbfsansh" : "𝗵",
- "\\mbfsansi" : "𝗶",
- "\\mbfsansj" : "𝗷",
- "\\mbfsansk" : "𝗸",
- "\\mbfsansl" : "𝗹",
- "\\mbfsansm" : "𝗺",
- "\\mbfsansn" : "𝗻",
- "\\mbfsanso" : "𝗼",
- "\\mbfsansp" : "𝗽",
- "\\mbfsansq" : "𝗾",
- "\\mbfsansr" : "𝗿",
- "\\mbfsanss" : "𝘀",
- "\\mbfsanst" : "𝘁",
- "\\mbfsansu" : "𝘂",
- "\\mbfsansv" : "𝘃",
- "\\mbfsansw" : "𝘄",
- "\\mbfsansx" : "𝘅",
- "\\mbfsansy" : "𝘆",
- "\\mbfsansz" : "𝘇",
- "\\mitsansA" : "𝘈",
- "\\mitsansB" : "𝘉",
- "\\mitsansC" : "𝘊",
- "\\mitsansD" : "𝘋",
- "\\mitsansE" : "𝘌",
- "\\mitsansF" : "𝘍",
- "\\mitsansG" : "𝘎",
- "\\mitsansH" : "𝘏",
- "\\mitsansI" : "𝘐",
- "\\mitsansJ" : "𝘑",
- "\\mitsansK" : "𝘒",
- "\\mitsansL" : "𝘓",
- "\\mitsansM" : "𝘔",
- "\\mitsansN" : "𝘕",
- "\\mitsansO" : "𝘖",
- "\\mitsansP" : "𝘗",
- "\\mitsansQ" : "𝘘",
- "\\mitsansR" : "𝘙",
- "\\mitsansS" : "𝘚",
- "\\mitsansT" : "𝘛",
- "\\mitsansU" : "𝘜",
- "\\mitsansV" : "𝘝",
- "\\mitsansW" : "𝘞",
- "\\mitsansX" : "𝘟",
- "\\mitsansY" : "𝘠",
- "\\mitsansZ" : "𝘡",
- "\\mitsansa" : "𝘢",
- "\\mitsansb" : "𝘣",
- "\\mitsansc" : "𝘤",
- "\\mitsansd" : "𝘥",
- "\\mitsanse" : "𝘦",
- "\\mitsansf" : "𝘧",
- "\\mitsansg" : "𝘨",
- "\\mitsansh" : "𝘩",
- "\\mitsansi" : "𝘪",
- "\\mitsansj" : "𝘫",
- "\\mitsansk" : "𝘬",
- "\\mitsansl" : "𝘭",
- "\\mitsansm" : "𝘮",
- "\\mitsansn" : "𝘯",
- "\\mitsanso" : "𝘰",
- "\\mitsansp" : "𝘱",
- "\\mitsansq" : "𝘲",
- "\\mitsansr" : "𝘳",
- "\\mitsanss" : "𝘴",
- "\\mitsanst" : "𝘵",
- "\\mitsansu" : "𝘶",
- "\\mitsansv" : "𝘷",
- "\\mitsansw" : "𝘸",
- "\\mitsansx" : "𝘹",
- "\\mitsansy" : "𝘺",
- "\\mitsansz" : "𝘻",
- "\\mbfitsansA" : "𝘼",
- "\\mbfitsansB" : "𝘽",
- "\\mbfitsansC" : "𝘾",
- "\\mbfitsansD" : "𝘿",
- "\\mbfitsansE" : "𝙀",
- "\\mbfitsansF" : "𝙁",
- "\\mbfitsansG" : "𝙂",
- "\\mbfitsansH" : "𝙃",
- "\\mbfitsansI" : "𝙄",
- "\\mbfitsansJ" : "𝙅",
- "\\mbfitsansK" : "𝙆",
- "\\mbfitsansL" : "𝙇",
- "\\mbfitsansM" : "𝙈",
- "\\mbfitsansN" : "𝙉",
- "\\mbfitsansO" : "𝙊",
- "\\mbfitsansP" : "𝙋",
- "\\mbfitsansQ" : "𝙌",
- "\\mbfitsansR" : "𝙍",
- "\\mbfitsansS" : "𝙎",
- "\\mbfitsansT" : "𝙏",
- "\\mbfitsansU" : "𝙐",
- "\\mbfitsansV" : "𝙑",
- "\\mbfitsansW" : "𝙒",
- "\\mbfitsansX" : "𝙓",
- "\\mbfitsansY" : "𝙔",
- "\\mbfitsansZ" : "𝙕",
- "\\mbfitsansa" : "𝙖",
- "\\mbfitsansb" : "𝙗",
- "\\mbfitsansc" : "𝙘",
- "\\mbfitsansd" : "𝙙",
- "\\mbfitsanse" : "𝙚",
- "\\mbfitsansf" : "𝙛",
- "\\mbfitsansg" : "𝙜",
- "\\mbfitsansh" : "𝙝",
- "\\mbfitsansi" : "𝙞",
- "\\mbfitsansj" : "𝙟",
- "\\mbfitsansk" : "𝙠",
- "\\mbfitsansl" : "𝙡",
- "\\mbfitsansm" : "𝙢",
- "\\mbfitsansn" : "𝙣",
- "\\mbfitsanso" : "𝙤",
- "\\mbfitsansp" : "𝙥",
- "\\mbfitsansq" : "𝙦",
- "\\mbfitsansr" : "𝙧",
- "\\mbfitsanss" : "𝙨",
- "\\mbfitsanst" : "𝙩",
- "\\mbfitsansu" : "𝙪",
- "\\mbfitsansv" : "𝙫",
- "\\mbfitsansw" : "𝙬",
- "\\mbfitsansx" : "𝙭",
- "\\mbfitsansy" : "𝙮",
- "\\mbfitsansz" : "𝙯",
- "\\mttA" : "𝙰",
- "\\mttB" : "𝙱",
- "\\mttC" : "𝙲",
- "\\mttD" : "𝙳",
- "\\mttE" : "𝙴",
- "\\mttF" : "𝙵",
- "\\mttG" : "𝙶",
- "\\mttH" : "𝙷",
- "\\mttI" : "𝙸",
- "\\mttJ" : "𝙹",
- "\\mttK" : "𝙺",
- "\\mttL" : "𝙻",
- "\\mttM" : "𝙼",
- "\\mttN" : "𝙽",
- "\\mttO" : "𝙾",
- "\\mttP" : "𝙿",
- "\\mttQ" : "𝚀",
- "\\mttR" : "𝚁",
- "\\mttS" : "𝚂",
- "\\mttT" : "𝚃",
- "\\mttU" : "𝚄",
- "\\mttV" : "𝚅",
- "\\mttW" : "𝚆",
- "\\mttX" : "𝚇",
- "\\mttY" : "𝚈",
- "\\mttZ" : "𝚉",
- "\\mtta" : "𝚊",
- "\\mttb" : "𝚋",
- "\\mttc" : "𝚌",
- "\\mttd" : "𝚍",
- "\\mtte" : "𝚎",
- "\\mttf" : "𝚏",
- "\\mttg" : "𝚐",
- "\\mtth" : "𝚑",
- "\\mtti" : "𝚒",
- "\\mttj" : "𝚓",
- "\\mttk" : "𝚔",
- "\\mttl" : "𝚕",
- "\\mttm" : "𝚖",
- "\\mttn" : "𝚗",
- "\\mtto" : "𝚘",
- "\\mttp" : "𝚙",
- "\\mttq" : "𝚚",
- "\\mttr" : "𝚛",
- "\\mtts" : "𝚜",
- "\\mttt" : "𝚝",
- "\\mttu" : "𝚞",
- "\\mttv" : "𝚟",
- "\\mttw" : "𝚠",
- "\\mttx" : "𝚡",
- "\\mtty" : "𝚢",
- "\\mttz" : "𝚣",
- "\\mbfAlpha" : "𝚨",
- "\\mbfBeta" : "𝚩",
- "\\mbfGamma" : "𝚪",
- "\\mbfDelta" : "𝚫",
- "\\mbfEpsilon" : "𝚬",
- "\\mbfZeta" : "𝚭",
- "\\mbfEta" : "𝚮",
- "\\mbfTheta" : "𝚯",
- "\\mbfIota" : "𝚰",
- "\\mbfKappa" : "𝚱",
- "\\mbfLambda" : "𝚲",
- "\\mbfMu" : "𝚳",
- "\\mbfNu" : "𝚴",
- "\\mbfXi" : "𝚵",
- "\\mbfOmicron" : "𝚶",
- "\\mbfPi" : "𝚷",
- "\\mbfRho" : "𝚸",
- "\\mbfvarTheta" : "𝚹",
- "\\mbfSigma" : "𝚺",
- "\\mbfTau" : "𝚻",
- "\\mbfUpsilon" : "𝚼",
- "\\mbfPhi" : "𝚽",
- "\\mbfChi" : "𝚾",
- "\\mbfPsi" : "𝚿",
- "\\mbfOmega" : "𝛀",
- "\\mbfalpha" : "𝛂",
- "\\mbfbeta" : "𝛃",
- "\\mbfgamma" : "𝛄",
- "\\mbfdelta" : "𝛅",
- "\\mbfepsilon" : "𝛆",
- "\\mbfzeta" : "𝛇",
- "\\mbfeta" : "𝛈",
- "\\mbftheta" : "𝛉",
- "\\mbfiota" : "𝛊",
- "\\mbfkappa" : "𝛋",
- "\\mbflambda" : "𝛌",
- "\\mbfmu" : "𝛍",
- "\\mbfnu" : "𝛎",
- "\\mbfxi" : "𝛏",
- "\\mbfomicron" : "𝛐",
- "\\mbfpi" : "𝛑",
- "\\mbfrho" : "𝛒",
- "\\mbfvarsigma" : "𝛓",
- "\\mbfsigma" : "𝛔",
- "\\mbftau" : "𝛕",
- "\\mbfupsilon" : "𝛖",
- "\\mbfvarphi" : "𝛗",
- "\\mbfchi" : "𝛘",
- "\\mbfpsi" : "𝛙",
- "\\mbfomega" : "𝛚",
- "\\mbfvarepsilon" : "𝛜",
- "\\mbfvartheta" : "𝛝",
- "\\mbfvarkappa" : "𝛞",
- "\\mbfphi" : "𝛟",
- "\\mbfvarrho" : "𝛠",
- "\\mbfvarpi" : "𝛡",
- "\\mitAlpha" : "𝛢",
- "\\mitBeta" : "𝛣",
- "\\mitGamma" : "𝛤",
- "\\mitDelta" : "𝛥",
- "\\mitEpsilon" : "𝛦",
- "\\mitZeta" : "𝛧",
- "\\mitEta" : "𝛨",
- "\\mitTheta" : "𝛩",
- "\\mitIota" : "𝛪",
- "\\mitKappa" : "𝛫",
- "\\mitLambda" : "𝛬",
- "\\mitMu" : "𝛭",
- "\\mitNu" : "𝛮",
- "\\mitXi" : "𝛯",
- "\\mitOmicron" : "𝛰",
- "\\mitPi" : "𝛱",
- "\\mitRho" : "𝛲",
- "\\mitvarTheta" : "𝛳",
- "\\mitSigma" : "𝛴",
- "\\mitTau" : "𝛵",
- "\\mitUpsilon" : "𝛶",
- "\\mitPhi" : "𝛷",
- "\\mitChi" : "𝛸",
- "\\mitPsi" : "𝛹",
- "\\mitOmega" : "𝛺",
- "\\mitalpha" : "𝛼",
- "\\mitbeta" : "𝛽",
- "\\mitgamma" : "𝛾",
- "\\mitdelta" : "𝛿",
- "\\mitepsilon" : "𝜀",
- "\\mitzeta" : "𝜁",
- "\\miteta" : "𝜂",
- "\\mittheta" : "𝜃",
- "\\mitiota" : "𝜄",
- "\\mitkappa" : "𝜅",
- "\\mitlambda" : "𝜆",
- "\\mitmu" : "𝜇",
- "\\mitnu" : "𝜈",
- "\\mitxi" : "𝜉",
- "\\mitomicron" : "𝜊",
- "\\mitpi" : "𝜋",
- "\\mitrho" : "𝜌",
- "\\mitvarsigma" : "𝜍",
- "\\mitsigma" : "𝜎",
- "\\mittau" : "𝜏",
- "\\mitupsilon" : "𝜐",
- "\\mitphi" : "𝜑",
- "\\mitchi" : "𝜒",
- "\\mitpsi" : "𝜓",
- "\\mitomega" : "𝜔",
- "\\mitvarepsilon" : "𝜖",
- "\\mitvartheta" : "𝜗",
- "\\mitvarkappa" : "𝜘",
- "\\mitvarphi" : "𝜙",
- "\\mitvarrho" : "𝜚",
- "\\mitvarpi" : "𝜛",
- "\\mbfitAlpha" : "𝜜",
- "\\mbfitBeta" : "𝜝",
- "\\mbfitGamma" : "𝜞",
- "\\mbfitDelta" : "𝜟",
- "\\mbfitEpsilon" : "𝜠",
- "\\mbfitZeta" : "𝜡",
- "\\mbfitEta" : "𝜢",
- "\\mbfitTheta" : "𝜣",
- "\\mbfitIota" : "𝜤",
- "\\mbfitKappa" : "𝜥",
- "\\mbfitLambda" : "𝜦",
- "\\mbfitMu" : "𝜧",
- "\\mbfitNu" : "𝜨",
- "\\mbfitXi" : "𝜩",
- "\\mbfitOmicron" : "𝜪",
- "\\mbfitPi" : "𝜫",
- "\\mbfitRho" : "𝜬",
- "\\mbfitvarTheta" : "𝜭",
- "\\mbfitSigma" : "𝜮",
- "\\mbfitTau" : "𝜯",
- "\\mbfitUpsilon" : "𝜰",
- "\\mbfitPhi" : "𝜱",
- "\\mbfitChi" : "𝜲",
- "\\mbfitPsi" : "𝜳",
- "\\mbfitOmega" : "𝜴",
- "\\mbfitalpha" : "𝜶",
- "\\mbfitbeta" : "𝜷",
- "\\mbfitgamma" : "𝜸",
- "\\mbfitdelta" : "𝜹",
- "\\mbfitepsilon" : "𝜺",
- "\\mbfitzeta" : "𝜻",
- "\\mbfiteta" : "𝜼",
- "\\mbfittheta" : "𝜽",
- "\\mbfitiota" : "𝜾",
- "\\mbfitkappa" : "𝜿",
- "\\mbfitlambda" : "𝝀",
- "\\mbfitmu" : "𝝁",
- "\\mbfitnu" : "𝝂",
- "\\mbfitxi" : "𝝃",
- "\\mbfitomicron" : "𝝄",
- "\\mbfitpi" : "𝝅",
- "\\mbfitrho" : "𝝆",
- "\\mbfitvarsigma" : "𝝇",
- "\\mbfitsigma" : "𝝈",
- "\\mbfittau" : "𝝉",
- "\\mbfitupsilon" : "𝝊",
- "\\mbfitphi" : "𝝋",
- "\\mbfitchi" : "𝝌",
- "\\mbfitpsi" : "𝝍",
- "\\mbfitomega" : "𝝎",
- "\\mbfitvarepsilon" : "𝝐",
- "\\mbfitvartheta" : "𝝑",
- "\\mbfitvarkappa" : "𝝒",
- "\\mbfitvarphi" : "𝝓",
- "\\mbfitvarrho" : "𝝔",
- "\\mbfitvarpi" : "𝝕",
- "\\mbfsansAlpha" : "𝝖",
- "\\mbfsansBeta" : "𝝗",
- "\\mbfsansGamma" : "𝝘",
- "\\mbfsansDelta" : "𝝙",
- "\\mbfsansEpsilon" : "𝝚",
- "\\mbfsansZeta" : "𝝛",
- "\\mbfsansEta" : "𝝜",
- "\\mbfsansTheta" : "𝝝",
- "\\mbfsansIota" : "𝝞",
- "\\mbfsansKappa" : "𝝟",
- "\\mbfsansLambda" : "𝝠",
- "\\mbfsansMu" : "𝝡",
- "\\mbfsansNu" : "𝝢",
- "\\mbfsansXi" : "𝝣",
- "\\mbfsansOmicron" : "𝝤",
- "\\mbfsansPi" : "𝝥",
- "\\mbfsansRho" : "𝝦",
- "\\mbfsansvarTheta" : "𝝧",
- "\\mbfsansSigma" : "𝝨",
- "\\mbfsansTau" : "𝝩",
- "\\mbfsansUpsilon" : "𝝪",
- "\\mbfsansPhi" : "𝝫",
- "\\mbfsansChi" : "𝝬",
- "\\mbfsansPsi" : "𝝭",
- "\\mbfsansOmega" : "𝝮",
- "\\mbfsansalpha" : "𝝰",
- "\\mbfsansbeta" : "𝝱",
- "\\mbfsansgamma" : "𝝲",
- "\\mbfsansdelta" : "𝝳",
- "\\mbfsansepsilon" : "𝝴",
- "\\mbfsanszeta" : "𝝵",
- "\\mbfsanseta" : "𝝶",
- "\\mbfsanstheta" : "𝝷",
- "\\mbfsansiota" : "𝝸",
- "\\mbfsanskappa" : "𝝹",
- "\\mbfsanslambda" : "𝝺",
- "\\mbfsansmu" : "𝝻",
- "\\mbfsansnu" : "𝝼",
- "\\mbfsansxi" : "𝝽",
- "\\mbfsansomicron" : "𝝾",
- "\\mbfsanspi" : "𝝿",
- "\\mbfsansrho" : "𝞀",
- "\\mbfsansvarsigma" : "𝞁",
- "\\mbfsanssigma" : "𝞂",
- "\\mbfsanstau" : "𝞃",
- "\\mbfsansupsilon" : "𝞄",
- "\\mbfsansphi" : "𝞅",
- "\\mbfsanschi" : "𝞆",
- "\\mbfsanspsi" : "𝞇",
- "\\mbfsansomega" : "𝞈",
- "\\mbfsansvarepsilon" : "𝞊",
- "\\mbfsansvartheta" : "𝞋",
- "\\mbfsansvarkappa" : "𝞌",
- "\\mbfsansvarphi" : "𝞍",
- "\\mbfsansvarrho" : "𝞎",
- "\\mbfsansvarpi" : "𝞏",
- "\\mbfitsansAlpha" : "𝞐",
- "\\mbfitsansBeta" : "𝞑",
- "\\mbfitsansGamma" : "𝞒",
- "\\mbfitsansDelta" : "𝞓",
- "\\mbfitsansEpsilon" : "𝞔",
- "\\mbfitsansZeta" : "𝞕",
- "\\mbfitsansEta" : "𝞖",
- "\\mbfitsansTheta" : "𝞗",
- "\\mbfitsansIota" : "𝞘",
- "\\mbfitsansKappa" : "𝞙",
- "\\mbfitsansLambda" : "𝞚",
- "\\mbfitsansMu" : "𝞛",
- "\\mbfitsansNu" : "𝞜",
- "\\mbfitsansXi" : "𝞝",
- "\\mbfitsansOmicron" : "𝞞",
- "\\mbfitsansPi" : "𝞟",
- "\\mbfitsansRho" : "𝞠",
- "\\mbfitsansvarTheta" : "𝞡",
- "\\mbfitsansSigma" : "𝞢",
- "\\mbfitsansTau" : "𝞣",
- "\\mbfitsansUpsilon" : "𝞤",
- "\\mbfitsansPhi" : "𝞥",
- "\\mbfitsansChi" : "𝞦",
- "\\mbfitsansPsi" : "𝞧",
- "\\mbfitsansOmega" : "𝞨",
- "\\mbfitsansalpha" : "𝞪",
- "\\mbfitsansbeta" : "𝞫",
- "\\mbfitsansgamma" : "𝞬",
- "\\mbfitsansdelta" : "𝞭",
- "\\mbfitsansepsilon" : "𝞮",
- "\\mbfitsanszeta" : "𝞯",
- "\\mbfitsanseta" : "𝞰",
- "\\mbfitsanstheta" : "𝞱",
- "\\mbfitsansiota" : "𝞲",
- "\\mbfitsanskappa" : "𝞳",
- "\\mbfitsanslambda" : "𝞴",
- "\\mbfitsansmu" : "𝞵",
- "\\mbfitsansnu" : "𝞶",
- "\\mbfitsansxi" : "𝞷",
- "\\mbfitsansomicron" : "𝞸",
- "\\mbfitsanspi" : "𝞹",
- "\\mbfitsansrho" : "𝞺",
- "\\mbfitsansvarsigma" : "𝞻",
- "\\mbfitsanssigma" : "𝞼",
- "\\mbfitsanstau" : "𝞽",
- "\\mbfitsansupsilon" : "𝞾",
- "\\mbfitsansphi" : "𝞿",
- "\\mbfitsanschi" : "𝟀",
- "\\mbfitsanspsi" : "𝟁",
- "\\mbfitsansomega" : "𝟂",
- "\\mbfitsansvarepsilon" : "𝟄",
- "\\mbfitsansvartheta" : "𝟅",
- "\\mbfitsansvarkappa" : "𝟆",
- "\\mbfitsansvarphi" : "𝟇",
- "\\mbfitsansvarrho" : "𝟈",
- "\\mbfitsansvarpi" : "𝟉",
- "\\mbfzero" : "𝟎",
- "\\mbfone" : "𝟏",
- "\\mbftwo" : "𝟐",
- "\\mbfthree" : "𝟑",
- "\\mbffour" : "𝟒",
- "\\mbffive" : "𝟓",
- "\\mbfsix" : "𝟔",
- "\\mbfseven" : "𝟕",
- "\\mbfeight" : "𝟖",
- "\\mbfnine" : "𝟗",
- "\\Bbbzero" : "𝟘",
- "\\Bbbone" : "𝟙",
- "\\Bbbtwo" : "𝟚",
- "\\Bbbthree" : "𝟛",
- "\\Bbbfour" : "𝟜",
- "\\Bbbfive" : "𝟝",
- "\\Bbbsix" : "𝟞",
- "\\Bbbseven" : "𝟟",
- "\\Bbbeight" : "𝟠",
- "\\Bbbnine" : "𝟡",
- "\\msanszero" : "𝟢",
- "\\msansone" : "𝟣",
- "\\msanstwo" : "𝟤",
- "\\msansthree" : "𝟥",
- "\\msansfour" : "𝟦",
- "\\msansfive" : "𝟧",
- "\\msanssix" : "𝟨",
- "\\msansseven" : "𝟩",
- "\\msanseight" : "𝟪",
- "\\msansnine" : "𝟫",
- "\\mbfsanszero" : "𝟬",
- "\\mbfsansone" : "𝟭",
- "\\mbfsanstwo" : "𝟮",
- "\\mbfsansthree" : "𝟯",
- "\\mbfsansfour" : "𝟰",
- "\\mbfsansfive" : "𝟱",
- "\\mbfsanssix" : "𝟲",
- "\\mbfsansseven" : "𝟳",
- "\\mbfsanseight" : "𝟴",
- "\\mbfsansnine" : "𝟵",
- "\\mttzero" : "𝟶",
- "\\mttone" : "𝟷",
- "\\mtttwo" : "𝟸",
- "\\mttthree" : "𝟹",
- "\\mttfour" : "𝟺",
- "\\mttfive" : "𝟻",
- "\\mttsix" : "𝟼",
- "\\mttseven" : "𝟽",
- "\\mtteight" : "𝟾",
- "\\mttnine" : "𝟿",
-}
-
-
-reverse_latex_symbol = { v:k for k,v in latex_symbols.items()}
+# encoding: utf-8
+
+# DO NOT EDIT THIS FILE BY HAND.
+
+# To update this file, run the script /tools/gen_latex_symbols.py using Python 3
+
+# This file is autogenerated from the file:
+# https://raw.githubusercontent.com/JuliaLang/julia/master/base/latex_symbols.jl
+# This original list is filtered to remove any unicode characters that are not valid
+# Python identifiers.
+
+latex_symbols = {
+
+ "\\^a" : "ᵃ",
+ "\\^b" : "ᵇ",
+ "\\^c" : "ᶜ",
+ "\\^d" : "ᵈ",
+ "\\^e" : "ᵉ",
+ "\\^f" : "ᶠ",
+ "\\^g" : "ᵍ",
+ "\\^h" : "ʰ",
+ "\\^i" : "ⁱ",
+ "\\^j" : "ʲ",
+ "\\^k" : "ᵏ",
+ "\\^l" : "ˡ",
+ "\\^m" : "ᵐ",
+ "\\^n" : "ⁿ",
+ "\\^o" : "ᵒ",
+ "\\^p" : "ᵖ",
+ "\\^r" : "ʳ",
+ "\\^s" : "ˢ",
+ "\\^t" : "ᵗ",
+ "\\^u" : "ᵘ",
+ "\\^v" : "ᵛ",
+ "\\^w" : "ʷ",
+ "\\^x" : "ˣ",
+ "\\^y" : "ʸ",
+ "\\^z" : "ᶻ",
+ "\\^A" : "ᴬ",
+ "\\^B" : "ᴮ",
+ "\\^D" : "ᴰ",
+ "\\^E" : "ᴱ",
+ "\\^G" : "ᴳ",
+ "\\^H" : "ᴴ",
+ "\\^I" : "ᴵ",
+ "\\^J" : "ᴶ",
+ "\\^K" : "ᴷ",
+ "\\^L" : "ᴸ",
+ "\\^M" : "ᴹ",
+ "\\^N" : "ᴺ",
+ "\\^O" : "ᴼ",
+ "\\^P" : "ᴾ",
+ "\\^R" : "ᴿ",
+ "\\^T" : "ᵀ",
+ "\\^U" : "ᵁ",
+ "\\^V" : "ⱽ",
+ "\\^W" : "ᵂ",
+ "\\^alpha" : "ᵅ",
+ "\\^beta" : "ᵝ",
+ "\\^gamma" : "ᵞ",
+ "\\^delta" : "ᵟ",
+ "\\^epsilon" : "ᵋ",
+ "\\^theta" : "ᶿ",
+ "\\^iota" : "ᶥ",
+ "\\^phi" : "ᵠ",
+ "\\^chi" : "ᵡ",
+ "\\^Phi" : "ᶲ",
+ "\\_a" : "ₐ",
+ "\\_e" : "ₑ",
+ "\\_h" : "ₕ",
+ "\\_i" : "ᵢ",
+ "\\_j" : "ⱼ",
+ "\\_k" : "ₖ",
+ "\\_l" : "ₗ",
+ "\\_m" : "ₘ",
+ "\\_n" : "ₙ",
+ "\\_o" : "ₒ",
+ "\\_p" : "ₚ",
+ "\\_r" : "ᵣ",
+ "\\_s" : "ₛ",
+ "\\_t" : "ₜ",
+ "\\_u" : "ᵤ",
+ "\\_v" : "ᵥ",
+ "\\_x" : "ₓ",
+ "\\_schwa" : "ₔ",
+ "\\_beta" : "ᵦ",
+ "\\_gamma" : "ᵧ",
+ "\\_rho" : "ᵨ",
+ "\\_phi" : "ᵩ",
+ "\\_chi" : "ᵪ",
+ "\\hbar" : "ħ",
+ "\\sout" : "̶",
+ "\\textordfeminine" : "ª",
+ "\\cdotp" : "·",
+ "\\textordmasculine" : "º",
+ "\\AA" : "Å",
+ "\\AE" : "Æ",
+ "\\DH" : "Ð",
+ "\\O" : "Ø",
+ "\\TH" : "Þ",
+ "\\ss" : "ß",
+ "\\aa" : "å",
+ "\\ae" : "æ",
+ "\\eth" : "ð",
+ "\\o" : "ø",
+ "\\th" : "þ",
+ "\\DJ" : "Đ",
+ "\\dj" : "đ",
+ "\\Elzxh" : "ħ",
+ "\\imath" : "ı",
+ "\\L" : "Ł",
+ "\\l" : "ł",
+ "\\NG" : "Ŋ",
+ "\\ng" : "ŋ",
+ "\\OE" : "Œ",
+ "\\oe" : "œ",
+ "\\texthvlig" : "ƕ",
+ "\\textnrleg" : "ƞ",
+ "\\textdoublepipe" : "ǂ",
+ "\\Elztrna" : "ɐ",
+ "\\Elztrnsa" : "ɒ",
+ "\\Elzopeno" : "ɔ",
+ "\\Elzrtld" : "ɖ",
+ "\\Elzschwa" : "ə",
+ "\\varepsilon" : "ɛ",
+ "\\Elzpgamma" : "ɣ",
+ "\\Elzpbgam" : "ɤ",
+ "\\Elztrnh" : "ɥ",
+ "\\Elzbtdl" : "ɬ",
+ "\\Elzrtll" : "ɭ",
+ "\\Elztrnm" : "ɯ",
+ "\\Elztrnmlr" : "ɰ",
+ "\\Elzltlmr" : "ɱ",
+ "\\Elzltln" : "ɲ",
+ "\\Elzrtln" : "ɳ",
+ "\\Elzclomeg" : "ɷ",
+ "\\textphi" : "ɸ",
+ "\\Elztrnr" : "ɹ",
+ "\\Elztrnrl" : "ɺ",
+ "\\Elzrttrnr" : "ɻ",
+ "\\Elzrl" : "ɼ",
+ "\\Elzrtlr" : "ɽ",
+ "\\Elzfhr" : "ɾ",
+ "\\Elzrtls" : "ʂ",
+ "\\Elzesh" : "ʃ",
+ "\\Elztrnt" : "ʇ",
+ "\\Elzrtlt" : "ʈ",
+ "\\Elzpupsil" : "ʊ",
+ "\\Elzpscrv" : "ʋ",
+ "\\Elzinvv" : "ʌ",
+ "\\Elzinvw" : "ʍ",
+ "\\Elztrny" : "ʎ",
+ "\\Elzrtlz" : "ʐ",
+ "\\Elzyogh" : "ʒ",
+ "\\Elzglst" : "ʔ",
+ "\\Elzreglst" : "ʕ",
+ "\\Elzinglst" : "ʖ",
+ "\\textturnk" : "ʞ",
+ "\\Elzdyogh" : "ʤ",
+ "\\Elztesh" : "ʧ",
+ "\\rasp" : "ʼ",
+ "\\textasciicaron" : "ˇ",
+ "\\Elzverts" : "ˈ",
+ "\\Elzverti" : "ˌ",
+ "\\Elzlmrk" : "ː",
+ "\\Elzhlmrk" : "ˑ",
+ "\\grave" : "̀",
+ "\\acute" : "́",
+ "\\hat" : "̂",
+ "\\tilde" : "̃",
+ "\\bar" : "̄",
+ "\\breve" : "̆",
+ "\\dot" : "̇",
+ "\\ddot" : "̈",
+ "\\ocirc" : "̊",
+ "\\H" : "̋",
+ "\\check" : "̌",
+ "\\Elzpalh" : "̡",
+ "\\Elzrh" : "̢",
+ "\\c" : "̧",
+ "\\k" : "̨",
+ "\\Elzsbbrg" : "̪",
+ "\\Elzxl" : "̵",
+ "\\Elzbar" : "̶",
+ "\\Alpha" : "Α",
+ "\\Beta" : "Β",
+ "\\Gamma" : "Γ",
+ "\\Delta" : "Δ",
+ "\\Epsilon" : "Ε",
+ "\\Zeta" : "Ζ",
+ "\\Eta" : "Η",
+ "\\Theta" : "Θ",
+ "\\Iota" : "Ι",
+ "\\Kappa" : "Κ",
+ "\\Lambda" : "Λ",
+ "\\Xi" : "Ξ",
+ "\\Pi" : "Π",
+ "\\Rho" : "Ρ",
+ "\\Sigma" : "Σ",
+ "\\Tau" : "Τ",
+ "\\Upsilon" : "Υ",
+ "\\Phi" : "Φ",
+ "\\Chi" : "Χ",
+ "\\Psi" : "Ψ",
+ "\\Omega" : "Ω",
+ "\\alpha" : "α",
+ "\\beta" : "β",
+ "\\gamma" : "γ",
+ "\\delta" : "δ",
+ "\\zeta" : "ζ",
+ "\\eta" : "η",
+ "\\theta" : "θ",
+ "\\iota" : "ι",
+ "\\kappa" : "κ",
+ "\\lambda" : "λ",
+ "\\mu" : "μ",
+ "\\nu" : "ν",
+ "\\xi" : "ξ",
+ "\\pi" : "π",
+ "\\rho" : "ρ",
+ "\\varsigma" : "ς",
+ "\\sigma" : "σ",
+ "\\tau" : "τ",
+ "\\upsilon" : "υ",
+ "\\varphi" : "φ",
+ "\\chi" : "χ",
+ "\\psi" : "ψ",
+ "\\omega" : "ω",
+ "\\vartheta" : "ϑ",
+ "\\phi" : "ϕ",
+ "\\varpi" : "ϖ",
+ "\\Stigma" : "Ϛ",
+ "\\Digamma" : "Ϝ",
+ "\\digamma" : "ϝ",
+ "\\Koppa" : "Ϟ",
+ "\\Sampi" : "Ϡ",
+ "\\varkappa" : "ϰ",
+ "\\varrho" : "ϱ",
+ "\\textTheta" : "ϴ",
+ "\\epsilon" : "ϵ",
+ "\\dddot" : "⃛",
+ "\\ddddot" : "⃜",
+ "\\hslash" : "ℏ",
+ "\\Im" : "ℑ",
+ "\\ell" : "ℓ",
+ "\\wp" : "℘",
+ "\\Re" : "ℜ",
+ "\\aleph" : "ℵ",
+ "\\beth" : "ℶ",
+ "\\gimel" : "ℷ",
+ "\\daleth" : "ℸ",
+ "\\BbbPi" : "ℿ",
+ "\\Zbar" : "Ƶ",
+ "\\overbar" : "̅",
+ "\\ovhook" : "̉",
+ "\\candra" : "̐",
+ "\\oturnedcomma" : "̒",
+ "\\ocommatopright" : "̕",
+ "\\droang" : "̚",
+ "\\wideutilde" : "̰",
+ "\\underbar" : "̱",
+ "\\not" : "̸",
+ "\\upMu" : "Μ",
+ "\\upNu" : "Ν",
+ "\\upOmicron" : "Ο",
+ "\\upepsilon" : "ε",
+ "\\upomicron" : "ο",
+ "\\upvarbeta" : "ϐ",
+ "\\upoldKoppa" : "Ϙ",
+ "\\upoldkoppa" : "ϙ",
+ "\\upstigma" : "ϛ",
+ "\\upkoppa" : "ϟ",
+ "\\upsampi" : "ϡ",
+ "\\tieconcat" : "⁀",
+ "\\leftharpoonaccent" : "⃐",
+ "\\rightharpoonaccent" : "⃑",
+ "\\vertoverlay" : "⃒",
+ "\\overleftarrow" : "⃖",
+ "\\vec" : "⃗",
+ "\\overleftrightarrow" : "⃡",
+ "\\annuity" : "⃧",
+ "\\threeunderdot" : "⃨",
+ "\\widebridgeabove" : "⃩",
+ "\\BbbC" : "ℂ",
+ "\\Eulerconst" : "ℇ",
+ "\\mscrg" : "ℊ",
+ "\\mscrH" : "ℋ",
+ "\\mfrakH" : "ℌ",
+ "\\BbbH" : "ℍ",
+ "\\Planckconst" : "ℎ",
+ "\\mscrI" : "ℐ",
+ "\\mscrL" : "ℒ",
+ "\\BbbN" : "ℕ",
+ "\\BbbP" : "ℙ",
+ "\\BbbQ" : "ℚ",
+ "\\mscrR" : "ℛ",
+ "\\BbbR" : "ℝ",
+ "\\BbbZ" : "ℤ",
+ "\\mfrakZ" : "ℨ",
+ "\\Angstrom" : "Å",
+ "\\mscrB" : "ℬ",
+ "\\mfrakC" : "ℭ",
+ "\\mscre" : "ℯ",
+ "\\mscrE" : "ℰ",
+ "\\mscrF" : "ℱ",
+ "\\Finv" : "Ⅎ",
+ "\\mscrM" : "ℳ",
+ "\\mscro" : "ℴ",
+ "\\Bbbgamma" : "ℽ",
+ "\\BbbGamma" : "ℾ",
+ "\\mitBbbD" : "ⅅ",
+ "\\mitBbbd" : "ⅆ",
+ "\\mitBbbe" : "ⅇ",
+ "\\mitBbbi" : "ⅈ",
+ "\\mitBbbj" : "ⅉ",
+ "\\mbfA" : "𝐀",
+ "\\mbfB" : "𝐁",
+ "\\mbfC" : "𝐂",
+ "\\mbfD" : "𝐃",
+ "\\mbfE" : "𝐄",
+ "\\mbfF" : "𝐅",
+ "\\mbfG" : "𝐆",
+ "\\mbfH" : "𝐇",
+ "\\mbfI" : "𝐈",
+ "\\mbfJ" : "𝐉",
+ "\\mbfK" : "𝐊",
+ "\\mbfL" : "𝐋",
+ "\\mbfM" : "𝐌",
+ "\\mbfN" : "𝐍",
+ "\\mbfO" : "𝐎",
+ "\\mbfP" : "𝐏",
+ "\\mbfQ" : "𝐐",
+ "\\mbfR" : "𝐑",
+ "\\mbfS" : "𝐒",
+ "\\mbfT" : "𝐓",
+ "\\mbfU" : "𝐔",
+ "\\mbfV" : "𝐕",
+ "\\mbfW" : "𝐖",
+ "\\mbfX" : "𝐗",
+ "\\mbfY" : "𝐘",
+ "\\mbfZ" : "𝐙",
+ "\\mbfa" : "𝐚",
+ "\\mbfb" : "𝐛",
+ "\\mbfc" : "𝐜",
+ "\\mbfd" : "𝐝",
+ "\\mbfe" : "𝐞",
+ "\\mbff" : "𝐟",
+ "\\mbfg" : "𝐠",
+ "\\mbfh" : "𝐡",
+ "\\mbfi" : "𝐢",
+ "\\mbfj" : "𝐣",
+ "\\mbfk" : "𝐤",
+ "\\mbfl" : "𝐥",
+ "\\mbfm" : "𝐦",
+ "\\mbfn" : "𝐧",
+ "\\mbfo" : "𝐨",
+ "\\mbfp" : "𝐩",
+ "\\mbfq" : "𝐪",
+ "\\mbfr" : "𝐫",
+ "\\mbfs" : "𝐬",
+ "\\mbft" : "𝐭",
+ "\\mbfu" : "𝐮",
+ "\\mbfv" : "𝐯",
+ "\\mbfw" : "𝐰",
+ "\\mbfx" : "𝐱",
+ "\\mbfy" : "𝐲",
+ "\\mbfz" : "𝐳",
+ "\\mitA" : "𝐴",
+ "\\mitB" : "𝐵",
+ "\\mitC" : "𝐶",
+ "\\mitD" : "𝐷",
+ "\\mitE" : "𝐸",
+ "\\mitF" : "𝐹",
+ "\\mitG" : "𝐺",
+ "\\mitH" : "𝐻",
+ "\\mitI" : "𝐼",
+ "\\mitJ" : "𝐽",
+ "\\mitK" : "𝐾",
+ "\\mitL" : "𝐿",
+ "\\mitM" : "𝑀",
+ "\\mitN" : "𝑁",
+ "\\mitO" : "𝑂",
+ "\\mitP" : "𝑃",
+ "\\mitQ" : "𝑄",
+ "\\mitR" : "𝑅",
+ "\\mitS" : "𝑆",
+ "\\mitT" : "𝑇",
+ "\\mitU" : "𝑈",
+ "\\mitV" : "𝑉",
+ "\\mitW" : "𝑊",
+ "\\mitX" : "𝑋",
+ "\\mitY" : "𝑌",
+ "\\mitZ" : "𝑍",
+ "\\mita" : "𝑎",
+ "\\mitb" : "𝑏",
+ "\\mitc" : "𝑐",
+ "\\mitd" : "𝑑",
+ "\\mite" : "𝑒",
+ "\\mitf" : "𝑓",
+ "\\mitg" : "𝑔",
+ "\\miti" : "𝑖",
+ "\\mitj" : "𝑗",
+ "\\mitk" : "𝑘",
+ "\\mitl" : "𝑙",
+ "\\mitm" : "𝑚",
+ "\\mitn" : "𝑛",
+ "\\mito" : "𝑜",
+ "\\mitp" : "𝑝",
+ "\\mitq" : "𝑞",
+ "\\mitr" : "𝑟",
+ "\\mits" : "𝑠",
+ "\\mitt" : "𝑡",
+ "\\mitu" : "𝑢",
+ "\\mitv" : "𝑣",
+ "\\mitw" : "𝑤",
+ "\\mitx" : "𝑥",
+ "\\mity" : "𝑦",
+ "\\mitz" : "𝑧",
+ "\\mbfitA" : "𝑨",
+ "\\mbfitB" : "𝑩",
+ "\\mbfitC" : "𝑪",
+ "\\mbfitD" : "𝑫",
+ "\\mbfitE" : "𝑬",
+ "\\mbfitF" : "𝑭",
+ "\\mbfitG" : "𝑮",
+ "\\mbfitH" : "𝑯",
+ "\\mbfitI" : "𝑰",
+ "\\mbfitJ" : "𝑱",
+ "\\mbfitK" : "𝑲",
+ "\\mbfitL" : "𝑳",
+ "\\mbfitM" : "𝑴",
+ "\\mbfitN" : "𝑵",
+ "\\mbfitO" : "𝑶",
+ "\\mbfitP" : "𝑷",
+ "\\mbfitQ" : "𝑸",
+ "\\mbfitR" : "𝑹",
+ "\\mbfitS" : "𝑺",
+ "\\mbfitT" : "𝑻",
+ "\\mbfitU" : "𝑼",
+ "\\mbfitV" : "𝑽",
+ "\\mbfitW" : "𝑾",
+ "\\mbfitX" : "𝑿",
+ "\\mbfitY" : "𝒀",
+ "\\mbfitZ" : "𝒁",
+ "\\mbfita" : "𝒂",
+ "\\mbfitb" : "𝒃",
+ "\\mbfitc" : "𝒄",
+ "\\mbfitd" : "𝒅",
+ "\\mbfite" : "𝒆",
+ "\\mbfitf" : "𝒇",
+ "\\mbfitg" : "𝒈",
+ "\\mbfith" : "𝒉",
+ "\\mbfiti" : "𝒊",
+ "\\mbfitj" : "𝒋",
+ "\\mbfitk" : "𝒌",
+ "\\mbfitl" : "𝒍",
+ "\\mbfitm" : "𝒎",
+ "\\mbfitn" : "𝒏",
+ "\\mbfito" : "𝒐",
+ "\\mbfitp" : "𝒑",
+ "\\mbfitq" : "𝒒",
+ "\\mbfitr" : "𝒓",
+ "\\mbfits" : "𝒔",
+ "\\mbfitt" : "𝒕",
+ "\\mbfitu" : "𝒖",
+ "\\mbfitv" : "𝒗",
+ "\\mbfitw" : "𝒘",
+ "\\mbfitx" : "𝒙",
+ "\\mbfity" : "𝒚",
+ "\\mbfitz" : "𝒛",
+ "\\mscrA" : "𝒜",
+ "\\mscrC" : "𝒞",
+ "\\mscrD" : "𝒟",
+ "\\mscrG" : "𝒢",
+ "\\mscrJ" : "𝒥",
+ "\\mscrK" : "𝒦",
+ "\\mscrN" : "𝒩",
+ "\\mscrO" : "𝒪",
+ "\\mscrP" : "𝒫",
+ "\\mscrQ" : "𝒬",
+ "\\mscrS" : "𝒮",
+ "\\mscrT" : "𝒯",
+ "\\mscrU" : "𝒰",
+ "\\mscrV" : "𝒱",
+ "\\mscrW" : "𝒲",
+ "\\mscrX" : "𝒳",
+ "\\mscrY" : "𝒴",
+ "\\mscrZ" : "𝒵",
+ "\\mscra" : "𝒶",
+ "\\mscrb" : "𝒷",
+ "\\mscrc" : "𝒸",
+ "\\mscrd" : "𝒹",
+ "\\mscrf" : "𝒻",
+ "\\mscrh" : "𝒽",
+ "\\mscri" : "𝒾",
+ "\\mscrj" : "𝒿",
+ "\\mscrk" : "𝓀",
+ "\\mscrm" : "𝓂",
+ "\\mscrn" : "𝓃",
+ "\\mscrp" : "𝓅",
+ "\\mscrq" : "𝓆",
+ "\\mscrr" : "𝓇",
+ "\\mscrs" : "𝓈",
+ "\\mscrt" : "𝓉",
+ "\\mscru" : "𝓊",
+ "\\mscrv" : "𝓋",
+ "\\mscrw" : "𝓌",
+ "\\mscrx" : "𝓍",
+ "\\mscry" : "𝓎",
+ "\\mscrz" : "𝓏",
+ "\\mbfscrA" : "𝓐",
+ "\\mbfscrB" : "𝓑",
+ "\\mbfscrC" : "𝓒",
+ "\\mbfscrD" : "𝓓",
+ "\\mbfscrE" : "𝓔",
+ "\\mbfscrF" : "𝓕",
+ "\\mbfscrG" : "𝓖",
+ "\\mbfscrH" : "𝓗",
+ "\\mbfscrI" : "𝓘",
+ "\\mbfscrJ" : "𝓙",
+ "\\mbfscrK" : "𝓚",
+ "\\mbfscrL" : "𝓛",
+ "\\mbfscrM" : "𝓜",
+ "\\mbfscrN" : "𝓝",
+ "\\mbfscrO" : "𝓞",
+ "\\mbfscrP" : "𝓟",
+ "\\mbfscrQ" : "𝓠",
+ "\\mbfscrR" : "𝓡",
+ "\\mbfscrS" : "𝓢",
+ "\\mbfscrT" : "𝓣",
+ "\\mbfscrU" : "𝓤",
+ "\\mbfscrV" : "𝓥",
+ "\\mbfscrW" : "𝓦",
+ "\\mbfscrX" : "𝓧",
+ "\\mbfscrY" : "𝓨",
+ "\\mbfscrZ" : "𝓩",
+ "\\mbfscra" : "𝓪",
+ "\\mbfscrb" : "𝓫",
+ "\\mbfscrc" : "𝓬",
+ "\\mbfscrd" : "𝓭",
+ "\\mbfscre" : "𝓮",
+ "\\mbfscrf" : "𝓯",
+ "\\mbfscrg" : "𝓰",
+ "\\mbfscrh" : "𝓱",
+ "\\mbfscri" : "𝓲",
+ "\\mbfscrj" : "𝓳",
+ "\\mbfscrk" : "𝓴",
+ "\\mbfscrl" : "𝓵",
+ "\\mbfscrm" : "𝓶",
+ "\\mbfscrn" : "𝓷",
+ "\\mbfscro" : "𝓸",
+ "\\mbfscrp" : "𝓹",
+ "\\mbfscrq" : "𝓺",
+ "\\mbfscrr" : "𝓻",
+ "\\mbfscrs" : "𝓼",
+ "\\mbfscrt" : "𝓽",
+ "\\mbfscru" : "𝓾",
+ "\\mbfscrv" : "𝓿",
+ "\\mbfscrw" : "𝔀",
+ "\\mbfscrx" : "𝔁",
+ "\\mbfscry" : "𝔂",
+ "\\mbfscrz" : "𝔃",
+ "\\mfrakA" : "𝔄",
+ "\\mfrakB" : "𝔅",
+ "\\mfrakD" : "𝔇",
+ "\\mfrakE" : "𝔈",
+ "\\mfrakF" : "𝔉",
+ "\\mfrakG" : "𝔊",
+ "\\mfrakJ" : "𝔍",
+ "\\mfrakK" : "𝔎",
+ "\\mfrakL" : "𝔏",
+ "\\mfrakM" : "𝔐",
+ "\\mfrakN" : "𝔑",
+ "\\mfrakO" : "𝔒",
+ "\\mfrakP" : "𝔓",
+ "\\mfrakQ" : "𝔔",
+ "\\mfrakS" : "𝔖",
+ "\\mfrakT" : "𝔗",
+ "\\mfrakU" : "𝔘",
+ "\\mfrakV" : "𝔙",
+ "\\mfrakW" : "𝔚",
+ "\\mfrakX" : "𝔛",
+ "\\mfrakY" : "𝔜",
+ "\\mfraka" : "𝔞",
+ "\\mfrakb" : "𝔟",
+ "\\mfrakc" : "𝔠",
+ "\\mfrakd" : "𝔡",
+ "\\mfrake" : "𝔢",
+ "\\mfrakf" : "𝔣",
+ "\\mfrakg" : "𝔤",
+ "\\mfrakh" : "𝔥",
+ "\\mfraki" : "𝔦",
+ "\\mfrakj" : "𝔧",
+ "\\mfrakk" : "𝔨",
+ "\\mfrakl" : "𝔩",
+ "\\mfrakm" : "𝔪",
+ "\\mfrakn" : "𝔫",
+ "\\mfrako" : "𝔬",
+ "\\mfrakp" : "𝔭",
+ "\\mfrakq" : "𝔮",
+ "\\mfrakr" : "𝔯",
+ "\\mfraks" : "𝔰",
+ "\\mfrakt" : "𝔱",
+ "\\mfraku" : "𝔲",
+ "\\mfrakv" : "𝔳",
+ "\\mfrakw" : "𝔴",
+ "\\mfrakx" : "𝔵",
+ "\\mfraky" : "𝔶",
+ "\\mfrakz" : "𝔷",
+ "\\BbbA" : "𝔸",
+ "\\BbbB" : "𝔹",
+ "\\BbbD" : "𝔻",
+ "\\BbbE" : "𝔼",
+ "\\BbbF" : "𝔽",
+ "\\BbbG" : "𝔾",
+ "\\BbbI" : "𝕀",
+ "\\BbbJ" : "𝕁",
+ "\\BbbK" : "𝕂",
+ "\\BbbL" : "𝕃",
+ "\\BbbM" : "𝕄",
+ "\\BbbO" : "𝕆",
+ "\\BbbS" : "𝕊",
+ "\\BbbT" : "𝕋",
+ "\\BbbU" : "𝕌",
+ "\\BbbV" : "𝕍",
+ "\\BbbW" : "𝕎",
+ "\\BbbX" : "𝕏",
+ "\\BbbY" : "𝕐",
+ "\\Bbba" : "𝕒",
+ "\\Bbbb" : "𝕓",
+ "\\Bbbc" : "𝕔",
+ "\\Bbbd" : "𝕕",
+ "\\Bbbe" : "𝕖",
+ "\\Bbbf" : "𝕗",
+ "\\Bbbg" : "𝕘",
+ "\\Bbbh" : "𝕙",
+ "\\Bbbi" : "𝕚",
+ "\\Bbbj" : "𝕛",
+ "\\Bbbk" : "𝕜",
+ "\\Bbbl" : "𝕝",
+ "\\Bbbm" : "𝕞",
+ "\\Bbbn" : "𝕟",
+ "\\Bbbo" : "𝕠",
+ "\\Bbbp" : "𝕡",
+ "\\Bbbq" : "𝕢",
+ "\\Bbbr" : "𝕣",
+ "\\Bbbs" : "𝕤",
+ "\\Bbbt" : "𝕥",
+ "\\Bbbu" : "𝕦",
+ "\\Bbbv" : "𝕧",
+ "\\Bbbw" : "𝕨",
+ "\\Bbbx" : "𝕩",
+ "\\Bbby" : "𝕪",
+ "\\Bbbz" : "𝕫",
+ "\\mbffrakA" : "𝕬",
+ "\\mbffrakB" : "𝕭",
+ "\\mbffrakC" : "𝕮",
+ "\\mbffrakD" : "𝕯",
+ "\\mbffrakE" : "𝕰",
+ "\\mbffrakF" : "𝕱",
+ "\\mbffrakG" : "𝕲",
+ "\\mbffrakH" : "𝕳",
+ "\\mbffrakI" : "𝕴",
+ "\\mbffrakJ" : "𝕵",
+ "\\mbffrakK" : "𝕶",
+ "\\mbffrakL" : "𝕷",
+ "\\mbffrakM" : "𝕸",
+ "\\mbffrakN" : "𝕹",
+ "\\mbffrakO" : "𝕺",
+ "\\mbffrakP" : "𝕻",
+ "\\mbffrakQ" : "𝕼",
+ "\\mbffrakR" : "𝕽",
+ "\\mbffrakS" : "𝕾",
+ "\\mbffrakT" : "𝕿",
+ "\\mbffrakU" : "𝖀",
+ "\\mbffrakV" : "𝖁",
+ "\\mbffrakW" : "𝖂",
+ "\\mbffrakX" : "𝖃",
+ "\\mbffrakY" : "𝖄",
+ "\\mbffrakZ" : "𝖅",
+ "\\mbffraka" : "𝖆",
+ "\\mbffrakb" : "𝖇",
+ "\\mbffrakc" : "𝖈",
+ "\\mbffrakd" : "𝖉",
+ "\\mbffrake" : "𝖊",
+ "\\mbffrakf" : "𝖋",
+ "\\mbffrakg" : "𝖌",
+ "\\mbffrakh" : "𝖍",
+ "\\mbffraki" : "𝖎",
+ "\\mbffrakj" : "𝖏",
+ "\\mbffrakk" : "𝖐",
+ "\\mbffrakl" : "𝖑",
+ "\\mbffrakm" : "𝖒",
+ "\\mbffrakn" : "𝖓",
+ "\\mbffrako" : "𝖔",
+ "\\mbffrakp" : "𝖕",
+ "\\mbffrakq" : "𝖖",
+ "\\mbffrakr" : "𝖗",
+ "\\mbffraks" : "𝖘",
+ "\\mbffrakt" : "𝖙",
+ "\\mbffraku" : "𝖚",
+ "\\mbffrakv" : "𝖛",
+ "\\mbffrakw" : "𝖜",
+ "\\mbffrakx" : "𝖝",
+ "\\mbffraky" : "𝖞",
+ "\\mbffrakz" : "𝖟",
+ "\\msansA" : "𝖠",
+ "\\msansB" : "𝖡",
+ "\\msansC" : "𝖢",
+ "\\msansD" : "𝖣",
+ "\\msansE" : "𝖤",
+ "\\msansF" : "𝖥",
+ "\\msansG" : "𝖦",
+ "\\msansH" : "𝖧",
+ "\\msansI" : "𝖨",
+ "\\msansJ" : "𝖩",
+ "\\msansK" : "𝖪",
+ "\\msansL" : "𝖫",
+ "\\msansM" : "𝖬",
+ "\\msansN" : "𝖭",
+ "\\msansO" : "𝖮",
+ "\\msansP" : "𝖯",
+ "\\msansQ" : "𝖰",
+ "\\msansR" : "𝖱",
+ "\\msansS" : "𝖲",
+ "\\msansT" : "𝖳",
+ "\\msansU" : "𝖴",
+ "\\msansV" : "𝖵",
+ "\\msansW" : "𝖶",
+ "\\msansX" : "𝖷",
+ "\\msansY" : "𝖸",
+ "\\msansZ" : "𝖹",
+ "\\msansa" : "𝖺",
+ "\\msansb" : "𝖻",
+ "\\msansc" : "𝖼",
+ "\\msansd" : "𝖽",
+ "\\msanse" : "𝖾",
+ "\\msansf" : "𝖿",
+ "\\msansg" : "𝗀",
+ "\\msansh" : "𝗁",
+ "\\msansi" : "𝗂",
+ "\\msansj" : "𝗃",
+ "\\msansk" : "𝗄",
+ "\\msansl" : "𝗅",
+ "\\msansm" : "𝗆",
+ "\\msansn" : "𝗇",
+ "\\msanso" : "𝗈",
+ "\\msansp" : "𝗉",
+ "\\msansq" : "𝗊",
+ "\\msansr" : "𝗋",
+ "\\msanss" : "𝗌",
+ "\\msanst" : "𝗍",
+ "\\msansu" : "𝗎",
+ "\\msansv" : "𝗏",
+ "\\msansw" : "𝗐",
+ "\\msansx" : "𝗑",
+ "\\msansy" : "𝗒",
+ "\\msansz" : "𝗓",
+ "\\mbfsansA" : "𝗔",
+ "\\mbfsansB" : "𝗕",
+ "\\mbfsansC" : "𝗖",
+ "\\mbfsansD" : "𝗗",
+ "\\mbfsansE" : "𝗘",
+ "\\mbfsansF" : "𝗙",
+ "\\mbfsansG" : "𝗚",
+ "\\mbfsansH" : "𝗛",
+ "\\mbfsansI" : "𝗜",
+ "\\mbfsansJ" : "𝗝",
+ "\\mbfsansK" : "𝗞",
+ "\\mbfsansL" : "𝗟",
+ "\\mbfsansM" : "𝗠",
+ "\\mbfsansN" : "𝗡",
+ "\\mbfsansO" : "𝗢",
+ "\\mbfsansP" : "𝗣",
+ "\\mbfsansQ" : "𝗤",
+ "\\mbfsansR" : "𝗥",
+ "\\mbfsansS" : "𝗦",
+ "\\mbfsansT" : "𝗧",
+ "\\mbfsansU" : "𝗨",
+ "\\mbfsansV" : "𝗩",
+ "\\mbfsansW" : "𝗪",
+ "\\mbfsansX" : "𝗫",
+ "\\mbfsansY" : "𝗬",
+ "\\mbfsansZ" : "𝗭",
+ "\\mbfsansa" : "𝗮",
+ "\\mbfsansb" : "𝗯",
+ "\\mbfsansc" : "𝗰",
+ "\\mbfsansd" : "𝗱",
+ "\\mbfsanse" : "𝗲",
+ "\\mbfsansf" : "𝗳",
+ "\\mbfsansg" : "𝗴",
+ "\\mbfsansh" : "𝗵",
+ "\\mbfsansi" : "𝗶",
+ "\\mbfsansj" : "𝗷",
+ "\\mbfsansk" : "𝗸",
+ "\\mbfsansl" : "𝗹",
+ "\\mbfsansm" : "𝗺",
+ "\\mbfsansn" : "𝗻",
+ "\\mbfsanso" : "𝗼",
+ "\\mbfsansp" : "𝗽",
+ "\\mbfsansq" : "𝗾",
+ "\\mbfsansr" : "𝗿",
+ "\\mbfsanss" : "𝘀",
+ "\\mbfsanst" : "𝘁",
+ "\\mbfsansu" : "𝘂",
+ "\\mbfsansv" : "𝘃",
+ "\\mbfsansw" : "𝘄",
+ "\\mbfsansx" : "𝘅",
+ "\\mbfsansy" : "𝘆",
+ "\\mbfsansz" : "𝘇",
+ "\\mitsansA" : "𝘈",
+ "\\mitsansB" : "𝘉",
+ "\\mitsansC" : "𝘊",
+ "\\mitsansD" : "𝘋",
+ "\\mitsansE" : "𝘌",
+ "\\mitsansF" : "𝘍",
+ "\\mitsansG" : "𝘎",
+ "\\mitsansH" : "𝘏",
+ "\\mitsansI" : "𝘐",
+ "\\mitsansJ" : "𝘑",
+ "\\mitsansK" : "𝘒",
+ "\\mitsansL" : "𝘓",
+ "\\mitsansM" : "𝘔",
+ "\\mitsansN" : "𝘕",
+ "\\mitsansO" : "𝘖",
+ "\\mitsansP" : "𝘗",
+ "\\mitsansQ" : "𝘘",
+ "\\mitsansR" : "𝘙",
+ "\\mitsansS" : "𝘚",
+ "\\mitsansT" : "𝘛",
+ "\\mitsansU" : "𝘜",
+ "\\mitsansV" : "𝘝",
+ "\\mitsansW" : "𝘞",
+ "\\mitsansX" : "𝘟",
+ "\\mitsansY" : "𝘠",
+ "\\mitsansZ" : "𝘡",
+ "\\mitsansa" : "𝘢",
+ "\\mitsansb" : "𝘣",
+ "\\mitsansc" : "𝘤",
+ "\\mitsansd" : "𝘥",
+ "\\mitsanse" : "𝘦",
+ "\\mitsansf" : "𝘧",
+ "\\mitsansg" : "𝘨",
+ "\\mitsansh" : "𝘩",
+ "\\mitsansi" : "𝘪",
+ "\\mitsansj" : "𝘫",
+ "\\mitsansk" : "𝘬",
+ "\\mitsansl" : "𝘭",
+ "\\mitsansm" : "𝘮",
+ "\\mitsansn" : "𝘯",
+ "\\mitsanso" : "𝘰",
+ "\\mitsansp" : "𝘱",
+ "\\mitsansq" : "𝘲",
+ "\\mitsansr" : "𝘳",
+ "\\mitsanss" : "𝘴",
+ "\\mitsanst" : "𝘵",
+ "\\mitsansu" : "𝘶",
+ "\\mitsansv" : "𝘷",
+ "\\mitsansw" : "𝘸",
+ "\\mitsansx" : "𝘹",
+ "\\mitsansy" : "𝘺",
+ "\\mitsansz" : "𝘻",
+ "\\mbfitsansA" : "𝘼",
+ "\\mbfitsansB" : "𝘽",
+ "\\mbfitsansC" : "𝘾",
+ "\\mbfitsansD" : "𝘿",
+ "\\mbfitsansE" : "𝙀",
+ "\\mbfitsansF" : "𝙁",
+ "\\mbfitsansG" : "𝙂",
+ "\\mbfitsansH" : "𝙃",
+ "\\mbfitsansI" : "𝙄",
+ "\\mbfitsansJ" : "𝙅",
+ "\\mbfitsansK" : "𝙆",
+ "\\mbfitsansL" : "𝙇",
+ "\\mbfitsansM" : "𝙈",
+ "\\mbfitsansN" : "𝙉",
+ "\\mbfitsansO" : "𝙊",
+ "\\mbfitsansP" : "𝙋",
+ "\\mbfitsansQ" : "𝙌",
+ "\\mbfitsansR" : "𝙍",
+ "\\mbfitsansS" : "𝙎",
+ "\\mbfitsansT" : "𝙏",
+ "\\mbfitsansU" : "𝙐",
+ "\\mbfitsansV" : "𝙑",
+ "\\mbfitsansW" : "𝙒",
+ "\\mbfitsansX" : "𝙓",
+ "\\mbfitsansY" : "𝙔",
+ "\\mbfitsansZ" : "𝙕",
+ "\\mbfitsansa" : "𝙖",
+ "\\mbfitsansb" : "𝙗",
+ "\\mbfitsansc" : "𝙘",
+ "\\mbfitsansd" : "𝙙",
+ "\\mbfitsanse" : "𝙚",
+ "\\mbfitsansf" : "𝙛",
+ "\\mbfitsansg" : "𝙜",
+ "\\mbfitsansh" : "𝙝",
+ "\\mbfitsansi" : "𝙞",
+ "\\mbfitsansj" : "𝙟",
+ "\\mbfitsansk" : "𝙠",
+ "\\mbfitsansl" : "𝙡",
+ "\\mbfitsansm" : "𝙢",
+ "\\mbfitsansn" : "𝙣",
+ "\\mbfitsanso" : "𝙤",
+ "\\mbfitsansp" : "𝙥",
+ "\\mbfitsansq" : "𝙦",
+ "\\mbfitsansr" : "𝙧",
+ "\\mbfitsanss" : "𝙨",
+ "\\mbfitsanst" : "𝙩",
+ "\\mbfitsansu" : "𝙪",
+ "\\mbfitsansv" : "𝙫",
+ "\\mbfitsansw" : "𝙬",
+ "\\mbfitsansx" : "𝙭",
+ "\\mbfitsansy" : "𝙮",
+ "\\mbfitsansz" : "𝙯",
+ "\\mttA" : "𝙰",
+ "\\mttB" : "𝙱",
+ "\\mttC" : "𝙲",
+ "\\mttD" : "𝙳",
+ "\\mttE" : "𝙴",
+ "\\mttF" : "𝙵",
+ "\\mttG" : "𝙶",
+ "\\mttH" : "𝙷",
+ "\\mttI" : "𝙸",
+ "\\mttJ" : "𝙹",
+ "\\mttK" : "𝙺",
+ "\\mttL" : "𝙻",
+ "\\mttM" : "𝙼",
+ "\\mttN" : "𝙽",
+ "\\mttO" : "𝙾",
+ "\\mttP" : "𝙿",
+ "\\mttQ" : "𝚀",
+ "\\mttR" : "𝚁",
+ "\\mttS" : "𝚂",
+ "\\mttT" : "𝚃",
+ "\\mttU" : "𝚄",
+ "\\mttV" : "𝚅",
+ "\\mttW" : "𝚆",
+ "\\mttX" : "𝚇",
+ "\\mttY" : "𝚈",
+ "\\mttZ" : "𝚉",
+ "\\mtta" : "𝚊",
+ "\\mttb" : "𝚋",
+ "\\mttc" : "𝚌",
+ "\\mttd" : "𝚍",
+ "\\mtte" : "𝚎",
+ "\\mttf" : "𝚏",
+ "\\mttg" : "𝚐",
+ "\\mtth" : "𝚑",
+ "\\mtti" : "𝚒",
+ "\\mttj" : "𝚓",
+ "\\mttk" : "𝚔",
+ "\\mttl" : "𝚕",
+ "\\mttm" : "𝚖",
+ "\\mttn" : "𝚗",
+ "\\mtto" : "𝚘",
+ "\\mttp" : "𝚙",
+ "\\mttq" : "𝚚",
+ "\\mttr" : "𝚛",
+ "\\mtts" : "𝚜",
+ "\\mttt" : "𝚝",
+ "\\mttu" : "𝚞",
+ "\\mttv" : "𝚟",
+ "\\mttw" : "𝚠",
+ "\\mttx" : "𝚡",
+ "\\mtty" : "𝚢",
+ "\\mttz" : "𝚣",
+ "\\mbfAlpha" : "𝚨",
+ "\\mbfBeta" : "𝚩",
+ "\\mbfGamma" : "𝚪",
+ "\\mbfDelta" : "𝚫",
+ "\\mbfEpsilon" : "𝚬",
+ "\\mbfZeta" : "𝚭",
+ "\\mbfEta" : "𝚮",
+ "\\mbfTheta" : "𝚯",
+ "\\mbfIota" : "𝚰",
+ "\\mbfKappa" : "𝚱",
+ "\\mbfLambda" : "𝚲",
+ "\\mbfMu" : "𝚳",
+ "\\mbfNu" : "𝚴",
+ "\\mbfXi" : "𝚵",
+ "\\mbfOmicron" : "𝚶",
+ "\\mbfPi" : "𝚷",
+ "\\mbfRho" : "𝚸",
+ "\\mbfvarTheta" : "𝚹",
+ "\\mbfSigma" : "𝚺",
+ "\\mbfTau" : "𝚻",
+ "\\mbfUpsilon" : "𝚼",
+ "\\mbfPhi" : "𝚽",
+ "\\mbfChi" : "𝚾",
+ "\\mbfPsi" : "𝚿",
+ "\\mbfOmega" : "𝛀",
+ "\\mbfalpha" : "𝛂",
+ "\\mbfbeta" : "𝛃",
+ "\\mbfgamma" : "𝛄",
+ "\\mbfdelta" : "𝛅",
+ "\\mbfepsilon" : "𝛆",
+ "\\mbfzeta" : "𝛇",
+ "\\mbfeta" : "𝛈",
+ "\\mbftheta" : "𝛉",
+ "\\mbfiota" : "𝛊",
+ "\\mbfkappa" : "𝛋",
+ "\\mbflambda" : "𝛌",
+ "\\mbfmu" : "𝛍",
+ "\\mbfnu" : "𝛎",
+ "\\mbfxi" : "𝛏",
+ "\\mbfomicron" : "𝛐",
+ "\\mbfpi" : "𝛑",
+ "\\mbfrho" : "𝛒",
+ "\\mbfvarsigma" : "𝛓",
+ "\\mbfsigma" : "𝛔",
+ "\\mbftau" : "𝛕",
+ "\\mbfupsilon" : "𝛖",
+ "\\mbfvarphi" : "𝛗",
+ "\\mbfchi" : "𝛘",
+ "\\mbfpsi" : "𝛙",
+ "\\mbfomega" : "𝛚",
+ "\\mbfvarepsilon" : "𝛜",
+ "\\mbfvartheta" : "𝛝",
+ "\\mbfvarkappa" : "𝛞",
+ "\\mbfphi" : "𝛟",
+ "\\mbfvarrho" : "𝛠",
+ "\\mbfvarpi" : "𝛡",
+ "\\mitAlpha" : "𝛢",
+ "\\mitBeta" : "𝛣",
+ "\\mitGamma" : "𝛤",
+ "\\mitDelta" : "𝛥",
+ "\\mitEpsilon" : "𝛦",
+ "\\mitZeta" : "𝛧",
+ "\\mitEta" : "𝛨",
+ "\\mitTheta" : "𝛩",
+ "\\mitIota" : "𝛪",
+ "\\mitKappa" : "𝛫",
+ "\\mitLambda" : "𝛬",
+ "\\mitMu" : "𝛭",
+ "\\mitNu" : "𝛮",
+ "\\mitXi" : "𝛯",
+ "\\mitOmicron" : "𝛰",
+ "\\mitPi" : "𝛱",
+ "\\mitRho" : "𝛲",
+ "\\mitvarTheta" : "𝛳",
+ "\\mitSigma" : "𝛴",
+ "\\mitTau" : "𝛵",
+ "\\mitUpsilon" : "𝛶",
+ "\\mitPhi" : "𝛷",
+ "\\mitChi" : "𝛸",
+ "\\mitPsi" : "𝛹",
+ "\\mitOmega" : "𝛺",
+ "\\mitalpha" : "𝛼",
+ "\\mitbeta" : "𝛽",
+ "\\mitgamma" : "𝛾",
+ "\\mitdelta" : "𝛿",
+ "\\mitepsilon" : "𝜀",
+ "\\mitzeta" : "𝜁",
+ "\\miteta" : "𝜂",
+ "\\mittheta" : "𝜃",
+ "\\mitiota" : "𝜄",
+ "\\mitkappa" : "𝜅",
+ "\\mitlambda" : "𝜆",
+ "\\mitmu" : "𝜇",
+ "\\mitnu" : "𝜈",
+ "\\mitxi" : "𝜉",
+ "\\mitomicron" : "𝜊",
+ "\\mitpi" : "𝜋",
+ "\\mitrho" : "𝜌",
+ "\\mitvarsigma" : "𝜍",
+ "\\mitsigma" : "𝜎",
+ "\\mittau" : "𝜏",
+ "\\mitupsilon" : "𝜐",
+ "\\mitphi" : "𝜑",
+ "\\mitchi" : "𝜒",
+ "\\mitpsi" : "𝜓",
+ "\\mitomega" : "𝜔",
+ "\\mitvarepsilon" : "𝜖",
+ "\\mitvartheta" : "𝜗",
+ "\\mitvarkappa" : "𝜘",
+ "\\mitvarphi" : "𝜙",
+ "\\mitvarrho" : "𝜚",
+ "\\mitvarpi" : "𝜛",
+ "\\mbfitAlpha" : "𝜜",
+ "\\mbfitBeta" : "𝜝",
+ "\\mbfitGamma" : "𝜞",
+ "\\mbfitDelta" : "𝜟",
+ "\\mbfitEpsilon" : "𝜠",
+ "\\mbfitZeta" : "𝜡",
+ "\\mbfitEta" : "𝜢",
+ "\\mbfitTheta" : "𝜣",
+ "\\mbfitIota" : "𝜤",
+ "\\mbfitKappa" : "𝜥",
+ "\\mbfitLambda" : "𝜦",
+ "\\mbfitMu" : "𝜧",
+ "\\mbfitNu" : "𝜨",
+ "\\mbfitXi" : "𝜩",
+ "\\mbfitOmicron" : "𝜪",
+ "\\mbfitPi" : "𝜫",
+ "\\mbfitRho" : "𝜬",
+ "\\mbfitvarTheta" : "𝜭",
+ "\\mbfitSigma" : "𝜮",
+ "\\mbfitTau" : "𝜯",
+ "\\mbfitUpsilon" : "𝜰",
+ "\\mbfitPhi" : "𝜱",
+ "\\mbfitChi" : "𝜲",
+ "\\mbfitPsi" : "𝜳",
+ "\\mbfitOmega" : "𝜴",
+ "\\mbfitalpha" : "𝜶",
+ "\\mbfitbeta" : "𝜷",
+ "\\mbfitgamma" : "𝜸",
+ "\\mbfitdelta" : "𝜹",
+ "\\mbfitepsilon" : "𝜺",
+ "\\mbfitzeta" : "𝜻",
+ "\\mbfiteta" : "𝜼",
+ "\\mbfittheta" : "𝜽",
+ "\\mbfitiota" : "𝜾",
+ "\\mbfitkappa" : "𝜿",
+ "\\mbfitlambda" : "𝝀",
+ "\\mbfitmu" : "𝝁",
+ "\\mbfitnu" : "𝝂",
+ "\\mbfitxi" : "𝝃",
+ "\\mbfitomicron" : "𝝄",
+ "\\mbfitpi" : "𝝅",
+ "\\mbfitrho" : "𝝆",
+ "\\mbfitvarsigma" : "𝝇",
+ "\\mbfitsigma" : "𝝈",
+ "\\mbfittau" : "𝝉",
+ "\\mbfitupsilon" : "𝝊",
+ "\\mbfitphi" : "𝝋",
+ "\\mbfitchi" : "𝝌",
+ "\\mbfitpsi" : "𝝍",
+ "\\mbfitomega" : "𝝎",
+ "\\mbfitvarepsilon" : "𝝐",
+ "\\mbfitvartheta" : "𝝑",
+ "\\mbfitvarkappa" : "𝝒",
+ "\\mbfitvarphi" : "𝝓",
+ "\\mbfitvarrho" : "𝝔",
+ "\\mbfitvarpi" : "𝝕",
+ "\\mbfsansAlpha" : "𝝖",
+ "\\mbfsansBeta" : "𝝗",
+ "\\mbfsansGamma" : "𝝘",
+ "\\mbfsansDelta" : "𝝙",
+ "\\mbfsansEpsilon" : "𝝚",
+ "\\mbfsansZeta" : "𝝛",
+ "\\mbfsansEta" : "𝝜",
+ "\\mbfsansTheta" : "𝝝",
+ "\\mbfsansIota" : "𝝞",
+ "\\mbfsansKappa" : "𝝟",
+ "\\mbfsansLambda" : "𝝠",
+ "\\mbfsansMu" : "𝝡",
+ "\\mbfsansNu" : "𝝢",
+ "\\mbfsansXi" : "𝝣",
+ "\\mbfsansOmicron" : "𝝤",
+ "\\mbfsansPi" : "𝝥",
+ "\\mbfsansRho" : "𝝦",
+ "\\mbfsansvarTheta" : "𝝧",
+ "\\mbfsansSigma" : "𝝨",
+ "\\mbfsansTau" : "𝝩",
+ "\\mbfsansUpsilon" : "𝝪",
+ "\\mbfsansPhi" : "𝝫",
+ "\\mbfsansChi" : "𝝬",
+ "\\mbfsansPsi" : "𝝭",
+ "\\mbfsansOmega" : "𝝮",
+ "\\mbfsansalpha" : "𝝰",
+ "\\mbfsansbeta" : "𝝱",
+ "\\mbfsansgamma" : "𝝲",
+ "\\mbfsansdelta" : "𝝳",
+ "\\mbfsansepsilon" : "𝝴",
+ "\\mbfsanszeta" : "𝝵",
+ "\\mbfsanseta" : "𝝶",
+ "\\mbfsanstheta" : "𝝷",
+ "\\mbfsansiota" : "𝝸",
+ "\\mbfsanskappa" : "𝝹",
+ "\\mbfsanslambda" : "𝝺",
+ "\\mbfsansmu" : "𝝻",
+ "\\mbfsansnu" : "𝝼",
+ "\\mbfsansxi" : "𝝽",
+ "\\mbfsansomicron" : "𝝾",
+ "\\mbfsanspi" : "𝝿",
+ "\\mbfsansrho" : "𝞀",
+ "\\mbfsansvarsigma" : "𝞁",
+ "\\mbfsanssigma" : "𝞂",
+ "\\mbfsanstau" : "𝞃",
+ "\\mbfsansupsilon" : "𝞄",
+ "\\mbfsansphi" : "𝞅",
+ "\\mbfsanschi" : "𝞆",
+ "\\mbfsanspsi" : "𝞇",
+ "\\mbfsansomega" : "𝞈",
+ "\\mbfsansvarepsilon" : "𝞊",
+ "\\mbfsansvartheta" : "𝞋",
+ "\\mbfsansvarkappa" : "𝞌",
+ "\\mbfsansvarphi" : "𝞍",
+ "\\mbfsansvarrho" : "𝞎",
+ "\\mbfsansvarpi" : "𝞏",
+ "\\mbfitsansAlpha" : "𝞐",
+ "\\mbfitsansBeta" : "𝞑",
+ "\\mbfitsansGamma" : "𝞒",
+ "\\mbfitsansDelta" : "𝞓",
+ "\\mbfitsansEpsilon" : "𝞔",
+ "\\mbfitsansZeta" : "𝞕",
+ "\\mbfitsansEta" : "𝞖",
+ "\\mbfitsansTheta" : "𝞗",
+ "\\mbfitsansIota" : "𝞘",
+ "\\mbfitsansKappa" : "𝞙",
+ "\\mbfitsansLambda" : "𝞚",
+ "\\mbfitsansMu" : "𝞛",
+ "\\mbfitsansNu" : "𝞜",
+ "\\mbfitsansXi" : "𝞝",
+ "\\mbfitsansOmicron" : "𝞞",
+ "\\mbfitsansPi" : "𝞟",
+ "\\mbfitsansRho" : "𝞠",
+ "\\mbfitsansvarTheta" : "𝞡",
+ "\\mbfitsansSigma" : "𝞢",
+ "\\mbfitsansTau" : "𝞣",
+ "\\mbfitsansUpsilon" : "𝞤",
+ "\\mbfitsansPhi" : "𝞥",
+ "\\mbfitsansChi" : "𝞦",
+ "\\mbfitsansPsi" : "𝞧",
+ "\\mbfitsansOmega" : "𝞨",
+ "\\mbfitsansalpha" : "𝞪",
+ "\\mbfitsansbeta" : "𝞫",
+ "\\mbfitsansgamma" : "𝞬",
+ "\\mbfitsansdelta" : "𝞭",
+ "\\mbfitsansepsilon" : "𝞮",
+ "\\mbfitsanszeta" : "𝞯",
+ "\\mbfitsanseta" : "𝞰",
+ "\\mbfitsanstheta" : "𝞱",
+ "\\mbfitsansiota" : "𝞲",
+ "\\mbfitsanskappa" : "𝞳",
+ "\\mbfitsanslambda" : "𝞴",
+ "\\mbfitsansmu" : "𝞵",
+ "\\mbfitsansnu" : "𝞶",
+ "\\mbfitsansxi" : "𝞷",
+ "\\mbfitsansomicron" : "𝞸",
+ "\\mbfitsanspi" : "𝞹",
+ "\\mbfitsansrho" : "𝞺",
+ "\\mbfitsansvarsigma" : "𝞻",
+ "\\mbfitsanssigma" : "𝞼",
+ "\\mbfitsanstau" : "𝞽",
+ "\\mbfitsansupsilon" : "𝞾",
+ "\\mbfitsansphi" : "𝞿",
+ "\\mbfitsanschi" : "𝟀",
+ "\\mbfitsanspsi" : "𝟁",
+ "\\mbfitsansomega" : "𝟂",
+ "\\mbfitsansvarepsilon" : "𝟄",
+ "\\mbfitsansvartheta" : "𝟅",
+ "\\mbfitsansvarkappa" : "𝟆",
+ "\\mbfitsansvarphi" : "𝟇",
+ "\\mbfitsansvarrho" : "𝟈",
+ "\\mbfitsansvarpi" : "𝟉",
+ "\\mbfzero" : "𝟎",
+ "\\mbfone" : "𝟏",
+ "\\mbftwo" : "𝟐",
+ "\\mbfthree" : "𝟑",
+ "\\mbffour" : "𝟒",
+ "\\mbffive" : "𝟓",
+ "\\mbfsix" : "𝟔",
+ "\\mbfseven" : "𝟕",
+ "\\mbfeight" : "𝟖",
+ "\\mbfnine" : "𝟗",
+ "\\Bbbzero" : "𝟘",
+ "\\Bbbone" : "𝟙",
+ "\\Bbbtwo" : "𝟚",
+ "\\Bbbthree" : "𝟛",
+ "\\Bbbfour" : "𝟜",
+ "\\Bbbfive" : "𝟝",
+ "\\Bbbsix" : "𝟞",
+ "\\Bbbseven" : "𝟟",
+ "\\Bbbeight" : "𝟠",
+ "\\Bbbnine" : "𝟡",
+ "\\msanszero" : "𝟢",
+ "\\msansone" : "𝟣",
+ "\\msanstwo" : "𝟤",
+ "\\msansthree" : "𝟥",
+ "\\msansfour" : "𝟦",
+ "\\msansfive" : "𝟧",
+ "\\msanssix" : "𝟨",
+ "\\msansseven" : "𝟩",
+ "\\msanseight" : "𝟪",
+ "\\msansnine" : "𝟫",
+ "\\mbfsanszero" : "𝟬",
+ "\\mbfsansone" : "𝟭",
+ "\\mbfsanstwo" : "𝟮",
+ "\\mbfsansthree" : "𝟯",
+ "\\mbfsansfour" : "𝟰",
+ "\\mbfsansfive" : "𝟱",
+ "\\mbfsanssix" : "𝟲",
+ "\\mbfsansseven" : "𝟳",
+ "\\mbfsanseight" : "𝟴",
+ "\\mbfsansnine" : "𝟵",
+ "\\mttzero" : "𝟶",
+ "\\mttone" : "𝟷",
+ "\\mtttwo" : "𝟸",
+ "\\mttthree" : "𝟹",
+ "\\mttfour" : "𝟺",
+ "\\mttfive" : "𝟻",
+ "\\mttsix" : "𝟼",
+ "\\mttseven" : "𝟽",
+ "\\mtteight" : "𝟾",
+ "\\mttnine" : "𝟿",
+}
+
+
+reverse_latex_symbol = { v:k for k,v in latex_symbols.items()}
diff --git a/contrib/python/ipython/py2/IPython/core/logger.py b/contrib/python/ipython/py2/IPython/core/logger.py
index ba5a88a73a..0e41db598f 100644
--- a/contrib/python/ipython/py2/IPython/core/logger.py
+++ b/contrib/python/ipython/py2/IPython/core/logger.py
@@ -1,221 +1,221 @@
-"""Logger class for IPython's logging facilities.
-"""
-from __future__ import print_function
-
-#*****************************************************************************
-# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
-# Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#*****************************************************************************
-
-#****************************************************************************
-# Modules and globals
-
-# Python standard modules
-import glob
-import io
-import os
-import time
-
-from IPython.utils.py3compat import str_to_unicode
-
-#****************************************************************************
-# FIXME: This class isn't a mixin anymore, but it still needs attributes from
-# ipython and does input cache management. Finish cleanup later...
-
-class Logger(object):
- """A Logfile class with different policies for file creation"""
-
- def __init__(self, home_dir, logfname='Logger.log', loghead=u'',
- logmode='over'):
-
- # this is the full ipython instance, we need some attributes from it
- # which won't exist until later. What a mess, clean up later...
- self.home_dir = home_dir
-
- self.logfname = logfname
- self.loghead = loghead
- self.logmode = logmode
- self.logfile = None
-
- # Whether to log raw or processed input
- self.log_raw_input = False
-
- # whether to also log output
- self.log_output = False
-
- # whether to put timestamps before each log entry
- self.timestamp = False
-
- # activity control flags
- self.log_active = False
-
- # logmode is a validated property
- def _set_mode(self,mode):
- if mode not in ['append','backup','global','over','rotate']:
- raise ValueError('invalid log mode %s given' % mode)
- self._logmode = mode
-
- def _get_mode(self):
- return self._logmode
-
- logmode = property(_get_mode,_set_mode)
-
- def logstart(self, logfname=None, loghead=None, logmode=None,
- log_output=False, timestamp=False, log_raw_input=False):
- """Generate a new log-file with a default header.
-
- Raises RuntimeError if the log has already been started"""
-
- if self.logfile is not None:
- raise RuntimeError('Log file is already active: %s' %
- self.logfname)
-
- # The parameters can override constructor defaults
- if logfname is not None: self.logfname = logfname
- if loghead is not None: self.loghead = loghead
- if logmode is not None: self.logmode = logmode
-
- # Parameters not part of the constructor
- self.timestamp = timestamp
- self.log_output = log_output
- self.log_raw_input = log_raw_input
-
- # init depending on the log mode requested
- isfile = os.path.isfile
- logmode = self.logmode
-
- if logmode == 'append':
- self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
-
- elif logmode == 'backup':
- if isfile(self.logfname):
- backup_logname = self.logfname+'~'
- # Manually remove any old backup, since os.rename may fail
- # under Windows.
- if isfile(backup_logname):
- os.remove(backup_logname)
- os.rename(self.logfname,backup_logname)
- self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
-
- elif logmode == 'global':
- self.logfname = os.path.join(self.home_dir,self.logfname)
- self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
-
- elif logmode == 'over':
- if isfile(self.logfname):
- os.remove(self.logfname)
- self.logfile = io.open(self.logfname,'w', encoding='utf-8')
-
- elif logmode == 'rotate':
- if isfile(self.logfname):
- if isfile(self.logfname+'.001~'):
- old = glob.glob(self.logfname+'.*~')
- old.sort()
- old.reverse()
- for f in old:
- root, ext = os.path.splitext(f)
- num = int(ext[1:-1])+1
- os.rename(f, root+'.'+repr(num).zfill(3)+'~')
- os.rename(self.logfname, self.logfname+'.001~')
- self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
-
- if logmode != 'append':
- self.logfile.write(self.loghead)
-
- self.logfile.flush()
- self.log_active = True
-
- def switch_log(self,val):
- """Switch logging on/off. val should be ONLY a boolean."""
-
- if val not in [False,True,0,1]:
- raise ValueError('Call switch_log ONLY with a boolean argument, '
- 'not with: %s' % val)
-
- label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
-
- if self.logfile is None:
- print("""
-Logging hasn't been started yet (use logstart for that).
-
-%logon/%logoff are for temporarily starting and stopping logging for a logfile
-which already exists. But you must first start the logging process with
-%logstart (optionally giving a logfile name).""")
-
- else:
- if self.log_active == val:
- print('Logging is already',label[val])
- else:
- print('Switching logging',label[val])
- self.log_active = not self.log_active
- self.log_active_out = self.log_active
-
- def logstate(self):
- """Print a status message about the logger."""
- if self.logfile is None:
- print('Logging has not been activated.')
- else:
- state = self.log_active and 'active' or 'temporarily suspended'
- print('Filename :', self.logfname)
- print('Mode :', self.logmode)
- print('Output logging :', self.log_output)
- print('Raw input log :', self.log_raw_input)
- print('Timestamping :', self.timestamp)
- print('State :', state)
-
- def log(self, line_mod, line_ori):
- """Write the sources to a log.
-
- Inputs:
-
- - line_mod: possibly modified input, such as the transformations made
- by input prefilters or input handlers of various kinds. This should
- always be valid Python.
-
- - line_ori: unmodified input line from the user. This is not
- necessarily valid Python.
- """
-
- # Write the log line, but decide which one according to the
- # log_raw_input flag, set when the log is started.
- if self.log_raw_input:
- self.log_write(line_ori)
- else:
- self.log_write(line_mod)
-
- def log_write(self, data, kind='input'):
- """Write data to the log file, if active"""
-
- #print 'data: %r' % data # dbg
- if self.log_active and data:
- write = self.logfile.write
- if kind=='input':
- if self.timestamp:
- write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
- time.localtime())))
- write(data)
- elif kind=='output' and self.log_output:
- odata = u'\n'.join([u'#[Out]# %s' % s
- for s in data.splitlines()])
- write(u'%s\n' % odata)
- self.logfile.flush()
-
- def logstop(self):
- """Fully stop logging and close log file.
-
- In order to start logging again, a new logstart() call needs to be
- made, possibly (though not necessarily) with a new filename, mode and
- other options."""
-
- if self.logfile is not None:
- self.logfile.close()
- self.logfile = None
- else:
- print("Logging hadn't been started.")
- self.log_active = False
-
- # For backwards compatibility, in case anyone was using this.
- close_log = logstop
+"""Logger class for IPython's logging facilities.
+"""
+from __future__ import print_function
+
+#*****************************************************************************
+# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
+# Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#*****************************************************************************
+
+#****************************************************************************
+# Modules and globals
+
+# Python standard modules
+import glob
+import io
+import os
+import time
+
+from IPython.utils.py3compat import str_to_unicode
+
+#****************************************************************************
+# FIXME: This class isn't a mixin anymore, but it still needs attributes from
+# ipython and does input cache management. Finish cleanup later...
+
+class Logger(object):
+ """A Logfile class with different policies for file creation"""
+
+ def __init__(self, home_dir, logfname='Logger.log', loghead=u'',
+ logmode='over'):
+
+ # this is the full ipython instance, we need some attributes from it
+ # which won't exist until later. What a mess, clean up later...
+ self.home_dir = home_dir
+
+ self.logfname = logfname
+ self.loghead = loghead
+ self.logmode = logmode
+ self.logfile = None
+
+ # Whether to log raw or processed input
+ self.log_raw_input = False
+
+ # whether to also log output
+ self.log_output = False
+
+ # whether to put timestamps before each log entry
+ self.timestamp = False
+
+ # activity control flags
+ self.log_active = False
+
+ # logmode is a validated property
+ def _set_mode(self,mode):
+ if mode not in ['append','backup','global','over','rotate']:
+ raise ValueError('invalid log mode %s given' % mode)
+ self._logmode = mode
+
+ def _get_mode(self):
+ return self._logmode
+
+ logmode = property(_get_mode,_set_mode)
+
+ def logstart(self, logfname=None, loghead=None, logmode=None,
+ log_output=False, timestamp=False, log_raw_input=False):
+ """Generate a new log-file with a default header.
+
+ Raises RuntimeError if the log has already been started"""
+
+ if self.logfile is not None:
+ raise RuntimeError('Log file is already active: %s' %
+ self.logfname)
+
+ # The parameters can override constructor defaults
+ if logfname is not None: self.logfname = logfname
+ if loghead is not None: self.loghead = loghead
+ if logmode is not None: self.logmode = logmode
+
+ # Parameters not part of the constructor
+ self.timestamp = timestamp
+ self.log_output = log_output
+ self.log_raw_input = log_raw_input
+
+ # init depending on the log mode requested
+ isfile = os.path.isfile
+ logmode = self.logmode
+
+ if logmode == 'append':
+ self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
+
+ elif logmode == 'backup':
+ if isfile(self.logfname):
+ backup_logname = self.logfname+'~'
+ # Manually remove any old backup, since os.rename may fail
+ # under Windows.
+ if isfile(backup_logname):
+ os.remove(backup_logname)
+ os.rename(self.logfname,backup_logname)
+ self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
+
+ elif logmode == 'global':
+ self.logfname = os.path.join(self.home_dir,self.logfname)
+ self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
+
+ elif logmode == 'over':
+ if isfile(self.logfname):
+ os.remove(self.logfname)
+ self.logfile = io.open(self.logfname,'w', encoding='utf-8')
+
+ elif logmode == 'rotate':
+ if isfile(self.logfname):
+ if isfile(self.logfname+'.001~'):
+ old = glob.glob(self.logfname+'.*~')
+ old.sort()
+ old.reverse()
+ for f in old:
+ root, ext = os.path.splitext(f)
+ num = int(ext[1:-1])+1
+ os.rename(f, root+'.'+repr(num).zfill(3)+'~')
+ os.rename(self.logfname, self.logfname+'.001~')
+ self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
+
+ if logmode != 'append':
+ self.logfile.write(self.loghead)
+
+ self.logfile.flush()
+ self.log_active = True
+
+ def switch_log(self,val):
+ """Switch logging on/off. val should be ONLY a boolean."""
+
+ if val not in [False,True,0,1]:
+ raise ValueError('Call switch_log ONLY with a boolean argument, '
+ 'not with: %s' % val)
+
+ label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
+
+ if self.logfile is None:
+ print("""
+Logging hasn't been started yet (use logstart for that).
+
+%logon/%logoff are for temporarily starting and stopping logging for a logfile
+which already exists. But you must first start the logging process with
+%logstart (optionally giving a logfile name).""")
+
+ else:
+ if self.log_active == val:
+ print('Logging is already',label[val])
+ else:
+ print('Switching logging',label[val])
+ self.log_active = not self.log_active
+ self.log_active_out = self.log_active
+
+ def logstate(self):
+ """Print a status message about the logger."""
+ if self.logfile is None:
+ print('Logging has not been activated.')
+ else:
+ state = self.log_active and 'active' or 'temporarily suspended'
+ print('Filename :', self.logfname)
+ print('Mode :', self.logmode)
+ print('Output logging :', self.log_output)
+ print('Raw input log :', self.log_raw_input)
+ print('Timestamping :', self.timestamp)
+ print('State :', state)
+
+ def log(self, line_mod, line_ori):
+ """Write the sources to a log.
+
+ Inputs:
+
+ - line_mod: possibly modified input, such as the transformations made
+ by input prefilters or input handlers of various kinds. This should
+ always be valid Python.
+
+ - line_ori: unmodified input line from the user. This is not
+ necessarily valid Python.
+ """
+
+ # Write the log line, but decide which one according to the
+ # log_raw_input flag, set when the log is started.
+ if self.log_raw_input:
+ self.log_write(line_ori)
+ else:
+ self.log_write(line_mod)
+
+ def log_write(self, data, kind='input'):
+ """Write data to the log file, if active"""
+
+ #print 'data: %r' % data # dbg
+ if self.log_active and data:
+ write = self.logfile.write
+ if kind=='input':
+ if self.timestamp:
+ write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
+ time.localtime())))
+ write(data)
+ elif kind=='output' and self.log_output:
+ odata = u'\n'.join([u'#[Out]# %s' % s
+ for s in data.splitlines()])
+ write(u'%s\n' % odata)
+ self.logfile.flush()
+
+ def logstop(self):
+ """Fully stop logging and close log file.
+
+ In order to start logging again, a new logstart() call needs to be
+ made, possibly (though not necessarily) with a new filename, mode and
+ other options."""
+
+ if self.logfile is not None:
+ self.logfile.close()
+ self.logfile = None
+ else:
+ print("Logging hadn't been started.")
+ self.log_active = False
+
+ # For backwards compatibility, in case anyone was using this.
+ close_log = logstop
diff --git a/contrib/python/ipython/py2/IPython/core/macro.py b/contrib/python/ipython/py2/IPython/core/macro.py
index 803236ffe5..9032706d2b 100644
--- a/contrib/python/ipython/py2/IPython/core/macro.py
+++ b/contrib/python/ipython/py2/IPython/core/macro.py
@@ -1,57 +1,57 @@
-"""Support for interactive macros in IPython"""
-
-#*****************************************************************************
-# Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#*****************************************************************************
-
-import re
-
-from IPython.utils import py3compat
-from IPython.utils.encoding import DEFAULT_ENCODING
-
-coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
-
-class Macro(object):
- """Simple class to store the value of macros as strings.
-
- Macro is just a callable that executes a string of IPython
- input when called.
- """
-
- def __init__(self,code):
- """store the macro value, as a single string which can be executed"""
- lines = []
- enc = None
- for line in code.splitlines():
- coding_match = coding_declaration.match(line)
- if coding_match:
- enc = coding_match.group(1)
- else:
- lines.append(line)
- code = "\n".join(lines)
- if isinstance(code, bytes):
- code = code.decode(enc or DEFAULT_ENCODING)
- self.value = code + '\n'
-
- def __str__(self):
- return py3compat.unicode_to_str(self.value)
-
- def __unicode__(self):
- return self.value
-
- def __repr__(self):
- return 'IPython.macro.Macro(%s)' % repr(self.value)
-
- def __getstate__(self):
- """ needed for safe pickling via %store """
- return {'value': self.value}
-
- def __add__(self, other):
- if isinstance(other, Macro):
- return Macro(self.value + other.value)
- elif isinstance(other, py3compat.string_types):
- return Macro(self.value + other)
- raise TypeError
+"""Support for interactive macros in IPython"""
+
+#*****************************************************************************
+# Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#*****************************************************************************
+
+import re
+
+from IPython.utils import py3compat
+from IPython.utils.encoding import DEFAULT_ENCODING
+
+coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
+
+class Macro(object):
+ """Simple class to store the value of macros as strings.
+
+ Macro is just a callable that executes a string of IPython
+ input when called.
+ """
+
+ def __init__(self,code):
+ """store the macro value, as a single string which can be executed"""
+ lines = []
+ enc = None
+ for line in code.splitlines():
+ coding_match = coding_declaration.match(line)
+ if coding_match:
+ enc = coding_match.group(1)
+ else:
+ lines.append(line)
+ code = "\n".join(lines)
+ if isinstance(code, bytes):
+ code = code.decode(enc or DEFAULT_ENCODING)
+ self.value = code + '\n'
+
+ def __str__(self):
+ return py3compat.unicode_to_str(self.value)
+
+ def __unicode__(self):
+ return self.value
+
+ def __repr__(self):
+ return 'IPython.macro.Macro(%s)' % repr(self.value)
+
+ def __getstate__(self):
+ """ needed for safe pickling via %store """
+ return {'value': self.value}
+
+ def __add__(self, other):
+ if isinstance(other, Macro):
+ return Macro(self.value + other.value)
+ elif isinstance(other, py3compat.string_types):
+ return Macro(self.value + other)
+ raise TypeError
diff --git a/contrib/python/ipython/py2/IPython/core/magic.py b/contrib/python/ipython/py2/IPython/core/magic.py
index 97e7b4291e..61a929fd23 100644
--- a/contrib/python/ipython/py2/IPython/core/magic.py
+++ b/contrib/python/ipython/py2/IPython/core/magic.py
@@ -1,680 +1,680 @@
-# encoding: utf-8
-"""Magic functions for InteractiveShell.
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
-# Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
-# Copyright (C) 2008 The IPython Development Team
-
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-import os
-import re
-import sys
-import types
-from getopt import getopt, GetoptError
-
-from traitlets.config.configurable import Configurable
-from IPython.core import oinspect
-from IPython.core.error import UsageError
-from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
-from decorator import decorator
-from IPython.utils.ipstruct import Struct
-from IPython.utils.process import arg_split
-from IPython.utils.py3compat import string_types, iteritems
-from IPython.utils.text import dedent
+# encoding: utf-8
+"""Magic functions for InteractiveShell.
+"""
+from __future__ import print_function
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
+# Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
+# Copyright (C) 2008 The IPython Development Team
+
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+import os
+import re
+import sys
+import types
+from getopt import getopt, GetoptError
+
+from traitlets.config.configurable import Configurable
+from IPython.core import oinspect
+from IPython.core.error import UsageError
+from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
+from decorator import decorator
+from IPython.utils.ipstruct import Struct
+from IPython.utils.process import arg_split
+from IPython.utils.py3compat import string_types, iteritems
+from IPython.utils.text import dedent
from traitlets import Bool, Dict, Instance, observe
from logging import error
-
-#-----------------------------------------------------------------------------
-# Globals
-#-----------------------------------------------------------------------------
-
-# A dict we'll use for each class that has magics, used as temporary storage to
-# pass information between the @line/cell_magic method decorators and the
-# @magics_class class decorator, because the method decorators have no
-# access to the class when they run. See for more details:
-# http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
-
-magics = dict(line={}, cell={})
-
-magic_kinds = ('line', 'cell')
-magic_spec = ('line', 'cell', 'line_cell')
-magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
-
-#-----------------------------------------------------------------------------
-# Utility classes and functions
-#-----------------------------------------------------------------------------
-
-class Bunch: pass
-
-
-def on_off(tag):
- """Return an ON/OFF string for a 1/0 input. Simple utility function."""
- return ['OFF','ON'][tag]
-
-
-def compress_dhist(dh):
- """Compress a directory history into a new one with at most 20 entries.
-
- Return a new list made from the first and last 10 elements of dhist after
- removal of duplicates.
- """
- head, tail = dh[:-10], dh[-10:]
-
- newhead = []
- done = set()
- for h in head:
- if h in done:
- continue
- newhead.append(h)
- done.add(h)
-
- return newhead + tail
-
-
-def needs_local_scope(func):
- """Decorator to mark magic functions which need to local scope to run."""
- func.needs_local_scope = True
- return func
-
-#-----------------------------------------------------------------------------
-# Class and method decorators for registering magics
-#-----------------------------------------------------------------------------
-
-def magics_class(cls):
- """Class decorator for all subclasses of the main Magics class.
-
- Any class that subclasses Magics *must* also apply this decorator, to
- ensure that all the methods that have been decorated as line/cell magics
- get correctly registered in the class instance. This is necessary because
- when method decorators run, the class does not exist yet, so they
- temporarily store their information into a module global. Application of
- this class decorator copies that global data to the class instance and
- clears the global.
-
- Obviously, this mechanism is not thread-safe, which means that the
- *creation* of subclasses of Magic should only be done in a single-thread
- context. Instantiation of the classes has no restrictions. Given that
- these classes are typically created at IPython startup time and before user
- application code becomes active, in practice this should not pose any
- problems.
- """
- cls.registered = True
- cls.magics = dict(line = magics['line'],
- cell = magics['cell'])
- magics['line'] = {}
- magics['cell'] = {}
- return cls
-
-
-def record_magic(dct, magic_kind, magic_name, func):
- """Utility function to store a function as a magic of a specific kind.
-
- Parameters
- ----------
- dct : dict
- A dictionary with 'line' and 'cell' subdicts.
-
- magic_kind : str
- Kind of magic to be stored.
-
- magic_name : str
- Key to store the magic as.
-
- func : function
- Callable object to store.
- """
- if magic_kind == 'line_cell':
- dct['line'][magic_name] = dct['cell'][magic_name] = func
- else:
- dct[magic_kind][magic_name] = func
-
-
-def validate_type(magic_kind):
- """Ensure that the given magic_kind is valid.
-
- Check that the given magic_kind is one of the accepted spec types (stored
- in the global `magic_spec`), raise ValueError otherwise.
- """
- if magic_kind not in magic_spec:
- raise ValueError('magic_kind must be one of %s, %s given' %
- magic_kinds, magic_kind)
-
-
-# The docstrings for the decorator below will be fairly similar for the two
-# types (method and function), so we generate them here once and reuse the
-# templates below.
-_docstring_template = \
-"""Decorate the given {0} as {1} magic.
-
-The decorator can be used with or without arguments, as follows.
-
-i) without arguments: it will create a {1} magic named as the {0} being
-decorated::
-
- @deco
- def foo(...)
-
-will create a {1} magic named `foo`.
-
-ii) with one string argument: which will be used as the actual name of the
-resulting magic::
-
- @deco('bar')
- def foo(...)
-
-will create a {1} magic named `bar`.
-"""
-
-# These two are decorator factories. While they are conceptually very similar,
-# there are enough differences in the details that it's simpler to have them
-# written as completely standalone functions rather than trying to share code
-# and make a single one with convoluted logic.
-
-def _method_magic_marker(magic_kind):
- """Decorator factory for methods in Magics subclasses.
- """
-
- validate_type(magic_kind)
-
- # This is a closure to capture the magic_kind. We could also use a class,
- # but it's overkill for just that one bit of state.
- def magic_deco(arg):
- call = lambda f, *a, **k: f(*a, **k)
-
- if callable(arg):
- # "Naked" decorator call (just @foo, no args)
- func = arg
- name = func.__name__
- retval = decorator(call, func)
- record_magic(magics, magic_kind, name, name)
- elif isinstance(arg, string_types):
- # Decorator called with arguments (@foo('bar'))
- name = arg
- def mark(func, *a, **kw):
- record_magic(magics, magic_kind, name, func.__name__)
- return decorator(call, func)
- retval = mark
- else:
- raise TypeError("Decorator can only be called with "
- "string or function")
- return retval
-
- # Ensure the resulting decorator has a usable docstring
- magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
- return magic_deco
-
-
-def _function_magic_marker(magic_kind):
- """Decorator factory for standalone functions.
- """
- validate_type(magic_kind)
-
- # This is a closure to capture the magic_kind. We could also use a class,
- # but it's overkill for just that one bit of state.
- def magic_deco(arg):
- call = lambda f, *a, **k: f(*a, **k)
-
- # Find get_ipython() in the caller's namespace
- caller = sys._getframe(1)
- for ns in ['f_locals', 'f_globals', 'f_builtins']:
- get_ipython = getattr(caller, ns).get('get_ipython')
- if get_ipython is not None:
- break
- else:
- raise NameError('Decorator can only run in context where '
- '`get_ipython` exists')
-
- ip = get_ipython()
-
- if callable(arg):
- # "Naked" decorator call (just @foo, no args)
- func = arg
- name = func.__name__
- ip.register_magic_function(func, magic_kind, name)
- retval = decorator(call, func)
- elif isinstance(arg, string_types):
- # Decorator called with arguments (@foo('bar'))
- name = arg
- def mark(func, *a, **kw):
- ip.register_magic_function(func, magic_kind, name)
- return decorator(call, func)
- retval = mark
- else:
- raise TypeError("Decorator can only be called with "
- "string or function")
- return retval
-
- # Ensure the resulting decorator has a usable docstring
- ds = _docstring_template.format('function', magic_kind)
-
- ds += dedent("""
- Note: this decorator can only be used in a context where IPython is already
- active, so that the `get_ipython()` call succeeds. You can therefore use
- it in your startup files loaded after IPython initializes, but *not* in the
- IPython configuration file itself, which is executed before IPython is
- fully up and running. Any file located in the `startup` subdirectory of
- your configuration profile will be OK in this sense.
- """)
-
- magic_deco.__doc__ = ds
- return magic_deco
-
-
-# Create the actual decorators for public use
-
-# These three are used to decorate methods in class definitions
-line_magic = _method_magic_marker('line')
-cell_magic = _method_magic_marker('cell')
-line_cell_magic = _method_magic_marker('line_cell')
-
-# These three decorate standalone functions and perform the decoration
-# immediately. They can only run where get_ipython() works
-register_line_magic = _function_magic_marker('line')
-register_cell_magic = _function_magic_marker('cell')
-register_line_cell_magic = _function_magic_marker('line_cell')
-
-#-----------------------------------------------------------------------------
-# Core Magic classes
-#-----------------------------------------------------------------------------
-
-class MagicsManager(Configurable):
- """Object that handles all magic-related functionality for IPython.
- """
- # Non-configurable class attributes
-
- # A two-level dict, first keyed by magic type, then by magic function, and
- # holding the actual callable object as value. This is the dict used for
- # magic function dispatch
- magics = Dict()
-
- # A registry of the original objects that we've been given holding magics.
- registry = Dict()
-
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
-
+
+#-----------------------------------------------------------------------------
+# Globals
+#-----------------------------------------------------------------------------
+
+# A dict we'll use for each class that has magics, used as temporary storage to
+# pass information between the @line/cell_magic method decorators and the
+# @magics_class class decorator, because the method decorators have no
+# access to the class when they run. See for more details:
+# http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
+
+magics = dict(line={}, cell={})
+
+magic_kinds = ('line', 'cell')
+magic_spec = ('line', 'cell', 'line_cell')
+magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
+
+#-----------------------------------------------------------------------------
+# Utility classes and functions
+#-----------------------------------------------------------------------------
+
+class Bunch: pass
+
+
+def on_off(tag):
+ """Return an ON/OFF string for a 1/0 input. Simple utility function."""
+ return ['OFF','ON'][tag]
+
+
+def compress_dhist(dh):
+ """Compress a directory history into a new one with at most 20 entries.
+
+ Return a new list made from the first and last 10 elements of dhist after
+ removal of duplicates.
+ """
+ head, tail = dh[:-10], dh[-10:]
+
+ newhead = []
+ done = set()
+ for h in head:
+ if h in done:
+ continue
+ newhead.append(h)
+ done.add(h)
+
+ return newhead + tail
+
+
+def needs_local_scope(func):
+ """Decorator to mark magic functions which need to local scope to run."""
+ func.needs_local_scope = True
+ return func
+
+#-----------------------------------------------------------------------------
+# Class and method decorators for registering magics
+#-----------------------------------------------------------------------------
+
+def magics_class(cls):
+ """Class decorator for all subclasses of the main Magics class.
+
+ Any class that subclasses Magics *must* also apply this decorator, to
+ ensure that all the methods that have been decorated as line/cell magics
+ get correctly registered in the class instance. This is necessary because
+ when method decorators run, the class does not exist yet, so they
+ temporarily store their information into a module global. Application of
+ this class decorator copies that global data to the class instance and
+ clears the global.
+
+ Obviously, this mechanism is not thread-safe, which means that the
+ *creation* of subclasses of Magic should only be done in a single-thread
+ context. Instantiation of the classes has no restrictions. Given that
+ these classes are typically created at IPython startup time and before user
+ application code becomes active, in practice this should not pose any
+ problems.
+ """
+ cls.registered = True
+ cls.magics = dict(line = magics['line'],
+ cell = magics['cell'])
+ magics['line'] = {}
+ magics['cell'] = {}
+ return cls
+
+
+def record_magic(dct, magic_kind, magic_name, func):
+ """Utility function to store a function as a magic of a specific kind.
+
+ Parameters
+ ----------
+ dct : dict
+ A dictionary with 'line' and 'cell' subdicts.
+
+ magic_kind : str
+ Kind of magic to be stored.
+
+ magic_name : str
+ Key to store the magic as.
+
+ func : function
+ Callable object to store.
+ """
+ if magic_kind == 'line_cell':
+ dct['line'][magic_name] = dct['cell'][magic_name] = func
+ else:
+ dct[magic_kind][magic_name] = func
+
+
+def validate_type(magic_kind):
+ """Ensure that the given magic_kind is valid.
+
+ Check that the given magic_kind is one of the accepted spec types (stored
+ in the global `magic_spec`), raise ValueError otherwise.
+ """
+ if magic_kind not in magic_spec:
+ raise ValueError('magic_kind must be one of %s, %s given' %
+ magic_kinds, magic_kind)
+
+
+# The docstrings for the decorator below will be fairly similar for the two
+# types (method and function), so we generate them here once and reuse the
+# templates below.
+_docstring_template = \
+"""Decorate the given {0} as {1} magic.
+
+The decorator can be used with or without arguments, as follows.
+
+i) without arguments: it will create a {1} magic named as the {0} being
+decorated::
+
+ @deco
+ def foo(...)
+
+will create a {1} magic named `foo`.
+
+ii) with one string argument: which will be used as the actual name of the
+resulting magic::
+
+ @deco('bar')
+ def foo(...)
+
+will create a {1} magic named `bar`.
+"""
+
+# These two are decorator factories. While they are conceptually very similar,
+# there are enough differences in the details that it's simpler to have them
+# written as completely standalone functions rather than trying to share code
+# and make a single one with convoluted logic.
+
+def _method_magic_marker(magic_kind):
+ """Decorator factory for methods in Magics subclasses.
+ """
+
+ validate_type(magic_kind)
+
+ # This is a closure to capture the magic_kind. We could also use a class,
+ # but it's overkill for just that one bit of state.
+ def magic_deco(arg):
+ call = lambda f, *a, **k: f(*a, **k)
+
+ if callable(arg):
+ # "Naked" decorator call (just @foo, no args)
+ func = arg
+ name = func.__name__
+ retval = decorator(call, func)
+ record_magic(magics, magic_kind, name, name)
+ elif isinstance(arg, string_types):
+ # Decorator called with arguments (@foo('bar'))
+ name = arg
+ def mark(func, *a, **kw):
+ record_magic(magics, magic_kind, name, func.__name__)
+ return decorator(call, func)
+ retval = mark
+ else:
+ raise TypeError("Decorator can only be called with "
+ "string or function")
+ return retval
+
+ # Ensure the resulting decorator has a usable docstring
+ magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
+ return magic_deco
+
+
+def _function_magic_marker(magic_kind):
+ """Decorator factory for standalone functions.
+ """
+ validate_type(magic_kind)
+
+ # This is a closure to capture the magic_kind. We could also use a class,
+ # but it's overkill for just that one bit of state.
+ def magic_deco(arg):
+ call = lambda f, *a, **k: f(*a, **k)
+
+ # Find get_ipython() in the caller's namespace
+ caller = sys._getframe(1)
+ for ns in ['f_locals', 'f_globals', 'f_builtins']:
+ get_ipython = getattr(caller, ns).get('get_ipython')
+ if get_ipython is not None:
+ break
+ else:
+ raise NameError('Decorator can only run in context where '
+ '`get_ipython` exists')
+
+ ip = get_ipython()
+
+ if callable(arg):
+ # "Naked" decorator call (just @foo, no args)
+ func = arg
+ name = func.__name__
+ ip.register_magic_function(func, magic_kind, name)
+ retval = decorator(call, func)
+ elif isinstance(arg, string_types):
+ # Decorator called with arguments (@foo('bar'))
+ name = arg
+ def mark(func, *a, **kw):
+ ip.register_magic_function(func, magic_kind, name)
+ return decorator(call, func)
+ retval = mark
+ else:
+ raise TypeError("Decorator can only be called with "
+ "string or function")
+ return retval
+
+ # Ensure the resulting decorator has a usable docstring
+ ds = _docstring_template.format('function', magic_kind)
+
+ ds += dedent("""
+ Note: this decorator can only be used in a context where IPython is already
+ active, so that the `get_ipython()` call succeeds. You can therefore use
+ it in your startup files loaded after IPython initializes, but *not* in the
+ IPython configuration file itself, which is executed before IPython is
+ fully up and running. Any file located in the `startup` subdirectory of
+ your configuration profile will be OK in this sense.
+ """)
+
+ magic_deco.__doc__ = ds
+ return magic_deco
+
+
+# Create the actual decorators for public use
+
+# These three are used to decorate methods in class definitions
+line_magic = _method_magic_marker('line')
+cell_magic = _method_magic_marker('cell')
+line_cell_magic = _method_magic_marker('line_cell')
+
+# These three decorate standalone functions and perform the decoration
+# immediately. They can only run where get_ipython() works
+register_line_magic = _function_magic_marker('line')
+register_cell_magic = _function_magic_marker('cell')
+register_line_cell_magic = _function_magic_marker('line_cell')
+
+#-----------------------------------------------------------------------------
+# Core Magic classes
+#-----------------------------------------------------------------------------
+
+class MagicsManager(Configurable):
+ """Object that handles all magic-related functionality for IPython.
+ """
+ # Non-configurable class attributes
+
+ # A two-level dict, first keyed by magic type, then by magic function, and
+ # holding the actual callable object as value. This is the dict used for
+ # magic function dispatch
+ magics = Dict()
+
+ # A registry of the original objects that we've been given holding magics.
+ registry = Dict()
+
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
+
auto_magic = Bool(True, help=
"Automatically call line magics without requiring explicit % prefix"
).tag(config=True)
@observe('auto_magic')
def _auto_magic_changed(self, change):
self.shell.automagic = change['new']
-
- _auto_status = [
- 'Automagic is OFF, % prefix IS needed for line magics.',
- 'Automagic is ON, % prefix IS NOT needed for line magics.']
-
- user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
-
- def __init__(self, shell=None, config=None, user_magics=None, **traits):
-
- super(MagicsManager, self).__init__(shell=shell, config=config,
- user_magics=user_magics, **traits)
- self.magics = dict(line={}, cell={})
- # Let's add the user_magics to the registry for uniformity, so *all*
- # registered magic containers can be found there.
- self.registry[user_magics.__class__.__name__] = user_magics
-
- def auto_status(self):
- """Return descriptive string with automagic status."""
- return self._auto_status[self.auto_magic]
-
- def lsmagic(self):
- """Return a dict of currently available magic functions.
-
- The return dict has the keys 'line' and 'cell', corresponding to the
- two types of magics we support. Each value is a list of names.
- """
- return self.magics
-
- def lsmagic_docs(self, brief=False, missing=''):
- """Return dict of documentation of magic functions.
-
- The return dict has the keys 'line' and 'cell', corresponding to the
- two types of magics we support. Each value is a dict keyed by magic
- name whose value is the function docstring. If a docstring is
- unavailable, the value of `missing` is used instead.
-
- If brief is True, only the first line of each docstring will be returned.
- """
- docs = {}
- for m_type in self.magics:
- m_docs = {}
- for m_name, m_func in iteritems(self.magics[m_type]):
- if m_func.__doc__:
- if brief:
- m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
- else:
- m_docs[m_name] = m_func.__doc__.rstrip()
- else:
- m_docs[m_name] = missing
- docs[m_type] = m_docs
- return docs
-
- def register(self, *magic_objects):
- """Register one or more instances of Magics.
-
- Take one or more classes or instances of classes that subclass the main
- `core.Magic` class, and register them with IPython to use the magic
- functions they provide. The registration process will then ensure that
- any methods that have decorated to provide line and/or cell magics will
- be recognized with the `%x`/`%%x` syntax as a line/cell magic
- respectively.
-
- If classes are given, they will be instantiated with the default
- constructor. If your classes need a custom constructor, you should
- instanitate them first and pass the instance.
-
- The provided arguments can be an arbitrary mix of classes and instances.
-
- Parameters
- ----------
- magic_objects : one or more classes or instances
- """
- # Start by validating them to ensure they have all had their magic
- # methods registered at the instance level
- for m in magic_objects:
- if not m.registered:
- raise ValueError("Class of magics %r was constructed without "
- "the @register_magics class decorator")
- if isinstance(m, type):
- # If we're given an uninstantiated class
- m = m(shell=self.shell)
-
- # Now that we have an instance, we can register it and update the
- # table of callables
- self.registry[m.__class__.__name__] = m
- for mtype in magic_kinds:
- self.magics[mtype].update(m.magics[mtype])
-
- def register_function(self, func, magic_kind='line', magic_name=None):
- """Expose a standalone function as magic function for IPython.
-
- This will create an IPython magic (line, cell or both) from a
- standalone function. The functions should have the following
- signatures:
-
- * For line magics: `def f(line)`
- * For cell magics: `def f(line, cell)`
- * For a function that does both: `def f(line, cell=None)`
-
- In the latter case, the function will be called with `cell==None` when
- invoked as `%f`, and with cell as a string when invoked as `%%f`.
-
- Parameters
- ----------
- func : callable
- Function to be registered as a magic.
-
- magic_kind : str
- Kind of magic, one of 'line', 'cell' or 'line_cell'
-
- magic_name : optional str
- If given, the name the magic will have in the IPython namespace. By
- default, the name of the function itself is used.
- """
-
- # Create the new method in the user_magics and register it in the
- # global table
- validate_type(magic_kind)
- magic_name = func.__name__ if magic_name is None else magic_name
- setattr(self.user_magics, magic_name, func)
- record_magic(self.magics, magic_kind, magic_name, func)
-
- def register_alias(self, alias_name, magic_name, magic_kind='line'):
- """Register an alias to a magic function.
-
- The alias is an instance of :class:`MagicAlias`, which holds the
- name and kind of the magic it should call. Binding is done at
- call time, so if the underlying magic function is changed the alias
- will call the new function.
-
- Parameters
- ----------
- alias_name : str
- The name of the magic to be registered.
-
- magic_name : str
- The name of an existing magic.
-
- magic_kind : str
- Kind of magic, one of 'line' or 'cell'
- """
-
- # `validate_type` is too permissive, as it allows 'line_cell'
- # which we do not handle.
- if magic_kind not in magic_kinds:
- raise ValueError('magic_kind must be one of %s, %s given' %
- magic_kinds, magic_kind)
-
- alias = MagicAlias(self.shell, magic_name, magic_kind)
- setattr(self.user_magics, alias_name, alias)
- record_magic(self.magics, magic_kind, alias_name, alias)
-
-# Key base class that provides the central functionality for magics.
-
-
-class Magics(Configurable):
- """Base class for implementing magic functions.
-
- Shell functions which can be reached as %function_name. All magic
- functions should accept a string, which they can parse for their own
- needs. This can make some functions easier to type, eg `%cd ../`
- vs. `%cd("../")`
-
- Classes providing magic functions need to subclass this class, and they
- MUST:
-
- - Use the method decorators `@line_magic` and `@cell_magic` to decorate
- individual methods as magic functions, AND
-
- - Use the class decorator `@magics_class` to ensure that the magic
- methods are properly registered at the instance level upon instance
- initialization.
-
- See :mod:`magic_functions` for examples of actual implementation classes.
- """
- # Dict holding all command-line options for each magic.
- options_table = None
- # Dict for the mapping of magic names to methods, set by class decorator
- magics = None
- # Flag to check that the class decorator was properly applied
- registered = False
- # Instance of IPython shell
- shell = None
-
- def __init__(self, shell=None, **kwargs):
- if not(self.__class__.registered):
- raise ValueError('Magics subclass without registration - '
- 'did you forget to apply @magics_class?')
- if shell is not None:
- if hasattr(shell, 'configurables'):
- shell.configurables.append(self)
- if hasattr(shell, 'config'):
- kwargs.setdefault('parent', shell)
-
- self.shell = shell
- self.options_table = {}
- # The method decorators are run when the instance doesn't exist yet, so
- # they can only record the names of the methods they are supposed to
- # grab. Only now, that the instance exists, can we create the proper
- # mapping to bound methods. So we read the info off the original names
- # table and replace each method name by the actual bound method.
- # But we mustn't clobber the *class* mapping, in case of multiple instances.
- class_magics = self.magics
- self.magics = {}
- for mtype in magic_kinds:
- tab = self.magics[mtype] = {}
- cls_tab = class_magics[mtype]
- for magic_name, meth_name in iteritems(cls_tab):
- if isinstance(meth_name, string_types):
- # it's a method name, grab it
- tab[magic_name] = getattr(self, meth_name)
- else:
- # it's the real thing
- tab[magic_name] = meth_name
- # Configurable **needs** to be initiated at the end or the config
- # magics get screwed up.
- super(Magics, self).__init__(**kwargs)
-
- def arg_err(self,func):
- """Print docstring if incorrect arguments were passed"""
- print('Error in arguments:')
- print(oinspect.getdoc(func))
-
- def format_latex(self, strng):
- """Format a string for latex inclusion."""
-
- # Characters that need to be escaped for latex:
- escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
- # Magic command names as headers:
- cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
- re.MULTILINE)
- # Magic commands
- cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
- re.MULTILINE)
- # Paragraph continue
- par_re = re.compile(r'\\$',re.MULTILINE)
-
- # The "\n" symbol
- newline_re = re.compile(r'\\n')
-
- # Now build the string for output:
- #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
- strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
- strng)
- strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
- strng = par_re.sub(r'\\\\',strng)
- strng = escape_re.sub(r'\\\1',strng)
- strng = newline_re.sub(r'\\textbackslash{}n',strng)
- return strng
-
- def parse_options(self, arg_str, opt_str, *long_opts, **kw):
- """Parse options passed to an argument string.
-
- The interface is similar to that of :func:`getopt.getopt`, but it
- returns a :class:`~IPython.utils.struct.Struct` with the options as keys
- and the stripped argument string still as a string.
-
- arg_str is quoted as a true sys.argv vector by using shlex.split.
- This allows us to easily expand variables, glob files, quote
- arguments, etc.
-
- Parameters
- ----------
-
- arg_str : str
- The arguments to parse.
-
- opt_str : str
- The options specification.
-
- mode : str, default 'string'
- If given as 'list', the argument string is returned as a list (split
- on whitespace) instead of a string.
-
- list_all : bool, default False
- Put all option values in lists. Normally only options
- appearing more than once are put in a list.
-
- posix : bool, default True
- Whether to split the input line in POSIX mode or not, as per the
- conventions outlined in the :mod:`shlex` module from the standard
- library.
- """
-
- # inject default options at the beginning of the input line
- caller = sys._getframe(1).f_code.co_name
- arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
-
- mode = kw.get('mode','string')
- if mode not in ['string','list']:
- raise ValueError('incorrect mode given: %s' % mode)
- # Get options
- list_all = kw.get('list_all',0)
- posix = kw.get('posix', os.name == 'posix')
- strict = kw.get('strict', True)
-
- # Check if we have more than one argument to warrant extra processing:
- odict = {} # Dictionary with options
- args = arg_str.split()
- if len(args) >= 1:
- # If the list of inputs only has 0 or 1 thing in it, there's no
- # need to look for options
- argv = arg_split(arg_str, posix, strict)
- # Do regular option processing
- try:
- opts,args = getopt(argv, opt_str, long_opts)
- except GetoptError as e:
- raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
- " ".join(long_opts)))
- for o,a in opts:
- if o.startswith('--'):
- o = o[2:]
- else:
- o = o[1:]
- try:
- odict[o].append(a)
- except AttributeError:
- odict[o] = [odict[o],a]
- except KeyError:
- if list_all:
- odict[o] = [a]
- else:
- odict[o] = a
-
- # Prepare opts,args for return
- opts = Struct(odict)
- if mode == 'string':
- args = ' '.join(args)
-
- return opts,args
-
- def default_option(self, fn, optstr):
- """Make an entry in the options_table for fn, with value optstr"""
-
- if fn not in self.lsmagic():
- error("%s is not a magic function" % fn)
- self.options_table[fn] = optstr
-
-
-class MagicAlias(object):
- """An alias to another magic function.
-
- An alias is determined by its magic name and magic kind. Lookup
- is done at call time, so if the underlying magic changes the alias
- will call the new function.
-
- Use the :meth:`MagicsManager.register_alias` method or the
- `%alias_magic` magic function to create and register a new alias.
- """
- def __init__(self, shell, magic_name, magic_kind):
- self.shell = shell
- self.magic_name = magic_name
- self.magic_kind = magic_kind
-
- self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
- self.__doc__ = "Alias for `%s`." % self.pretty_target
-
- self._in_call = False
-
- def __call__(self, *args, **kwargs):
- """Call the magic alias."""
- fn = self.shell.find_magic(self.magic_name, self.magic_kind)
- if fn is None:
- raise UsageError("Magic `%s` not found." % self.pretty_target)
-
- # Protect against infinite recursion.
- if self._in_call:
- raise UsageError("Infinite recursion detected; "
- "magic aliases cannot call themselves.")
- self._in_call = True
- try:
- return fn(*args, **kwargs)
- finally:
- self._in_call = False
+
+ _auto_status = [
+ 'Automagic is OFF, % prefix IS needed for line magics.',
+ 'Automagic is ON, % prefix IS NOT needed for line magics.']
+
+ user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
+
+ def __init__(self, shell=None, config=None, user_magics=None, **traits):
+
+ super(MagicsManager, self).__init__(shell=shell, config=config,
+ user_magics=user_magics, **traits)
+ self.magics = dict(line={}, cell={})
+ # Let's add the user_magics to the registry for uniformity, so *all*
+ # registered magic containers can be found there.
+ self.registry[user_magics.__class__.__name__] = user_magics
+
+ def auto_status(self):
+ """Return descriptive string with automagic status."""
+ return self._auto_status[self.auto_magic]
+
+ def lsmagic(self):
+ """Return a dict of currently available magic functions.
+
+ The return dict has the keys 'line' and 'cell', corresponding to the
+ two types of magics we support. Each value is a list of names.
+ """
+ return self.magics
+
+ def lsmagic_docs(self, brief=False, missing=''):
+ """Return dict of documentation of magic functions.
+
+ The return dict has the keys 'line' and 'cell', corresponding to the
+ two types of magics we support. Each value is a dict keyed by magic
+ name whose value is the function docstring. If a docstring is
+ unavailable, the value of `missing` is used instead.
+
+ If brief is True, only the first line of each docstring will be returned.
+ """
+ docs = {}
+ for m_type in self.magics:
+ m_docs = {}
+ for m_name, m_func in iteritems(self.magics[m_type]):
+ if m_func.__doc__:
+ if brief:
+ m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
+ else:
+ m_docs[m_name] = m_func.__doc__.rstrip()
+ else:
+ m_docs[m_name] = missing
+ docs[m_type] = m_docs
+ return docs
+
+ def register(self, *magic_objects):
+ """Register one or more instances of Magics.
+
+ Take one or more classes or instances of classes that subclass the main
+ `core.Magic` class, and register them with IPython to use the magic
+ functions they provide. The registration process will then ensure that
+ any methods that have decorated to provide line and/or cell magics will
+ be recognized with the `%x`/`%%x` syntax as a line/cell magic
+ respectively.
+
+ If classes are given, they will be instantiated with the default
+ constructor. If your classes need a custom constructor, you should
+ instanitate them first and pass the instance.
+
+ The provided arguments can be an arbitrary mix of classes and instances.
+
+ Parameters
+ ----------
+ magic_objects : one or more classes or instances
+ """
+ # Start by validating them to ensure they have all had their magic
+ # methods registered at the instance level
+ for m in magic_objects:
+ if not m.registered:
+ raise ValueError("Class of magics %r was constructed without "
+ "the @register_magics class decorator")
+ if isinstance(m, type):
+ # If we're given an uninstantiated class
+ m = m(shell=self.shell)
+
+ # Now that we have an instance, we can register it and update the
+ # table of callables
+ self.registry[m.__class__.__name__] = m
+ for mtype in magic_kinds:
+ self.magics[mtype].update(m.magics[mtype])
+
+ def register_function(self, func, magic_kind='line', magic_name=None):
+ """Expose a standalone function as magic function for IPython.
+
+ This will create an IPython magic (line, cell or both) from a
+ standalone function. The functions should have the following
+ signatures:
+
+ * For line magics: `def f(line)`
+ * For cell magics: `def f(line, cell)`
+ * For a function that does both: `def f(line, cell=None)`
+
+ In the latter case, the function will be called with `cell==None` when
+ invoked as `%f`, and with cell as a string when invoked as `%%f`.
+
+ Parameters
+ ----------
+ func : callable
+ Function to be registered as a magic.
+
+ magic_kind : str
+ Kind of magic, one of 'line', 'cell' or 'line_cell'
+
+ magic_name : optional str
+ If given, the name the magic will have in the IPython namespace. By
+ default, the name of the function itself is used.
+ """
+
+ # Create the new method in the user_magics and register it in the
+ # global table
+ validate_type(magic_kind)
+ magic_name = func.__name__ if magic_name is None else magic_name
+ setattr(self.user_magics, magic_name, func)
+ record_magic(self.magics, magic_kind, magic_name, func)
+
+ def register_alias(self, alias_name, magic_name, magic_kind='line'):
+ """Register an alias to a magic function.
+
+ The alias is an instance of :class:`MagicAlias`, which holds the
+ name and kind of the magic it should call. Binding is done at
+ call time, so if the underlying magic function is changed the alias
+ will call the new function.
+
+ Parameters
+ ----------
+ alias_name : str
+ The name of the magic to be registered.
+
+ magic_name : str
+ The name of an existing magic.
+
+ magic_kind : str
+ Kind of magic, one of 'line' or 'cell'
+ """
+
+ # `validate_type` is too permissive, as it allows 'line_cell'
+ # which we do not handle.
+ if magic_kind not in magic_kinds:
+ raise ValueError('magic_kind must be one of %s, %s given' %
+ magic_kinds, magic_kind)
+
+ alias = MagicAlias(self.shell, magic_name, magic_kind)
+ setattr(self.user_magics, alias_name, alias)
+ record_magic(self.magics, magic_kind, alias_name, alias)
+
+# Key base class that provides the central functionality for magics.
+
+
+class Magics(Configurable):
+ """Base class for implementing magic functions.
+
+ Shell functions which can be reached as %function_name. All magic
+ functions should accept a string, which they can parse for their own
+ needs. This can make some functions easier to type, eg `%cd ../`
+ vs. `%cd("../")`
+
+ Classes providing magic functions need to subclass this class, and they
+ MUST:
+
+ - Use the method decorators `@line_magic` and `@cell_magic` to decorate
+ individual methods as magic functions, AND
+
+ - Use the class decorator `@magics_class` to ensure that the magic
+ methods are properly registered at the instance level upon instance
+ initialization.
+
+ See :mod:`magic_functions` for examples of actual implementation classes.
+ """
+ # Dict holding all command-line options for each magic.
+ options_table = None
+ # Dict for the mapping of magic names to methods, set by class decorator
+ magics = None
+ # Flag to check that the class decorator was properly applied
+ registered = False
+ # Instance of IPython shell
+ shell = None
+
+ def __init__(self, shell=None, **kwargs):
+ if not(self.__class__.registered):
+ raise ValueError('Magics subclass without registration - '
+ 'did you forget to apply @magics_class?')
+ if shell is not None:
+ if hasattr(shell, 'configurables'):
+ shell.configurables.append(self)
+ if hasattr(shell, 'config'):
+ kwargs.setdefault('parent', shell)
+
+ self.shell = shell
+ self.options_table = {}
+ # The method decorators are run when the instance doesn't exist yet, so
+ # they can only record the names of the methods they are supposed to
+ # grab. Only now, that the instance exists, can we create the proper
+ # mapping to bound methods. So we read the info off the original names
+ # table and replace each method name by the actual bound method.
+ # But we mustn't clobber the *class* mapping, in case of multiple instances.
+ class_magics = self.magics
+ self.magics = {}
+ for mtype in magic_kinds:
+ tab = self.magics[mtype] = {}
+ cls_tab = class_magics[mtype]
+ for magic_name, meth_name in iteritems(cls_tab):
+ if isinstance(meth_name, string_types):
+ # it's a method name, grab it
+ tab[magic_name] = getattr(self, meth_name)
+ else:
+ # it's the real thing
+ tab[magic_name] = meth_name
+ # Configurable **needs** to be initiated at the end or the config
+ # magics get screwed up.
+ super(Magics, self).__init__(**kwargs)
+
+ def arg_err(self,func):
+ """Print docstring if incorrect arguments were passed"""
+ print('Error in arguments:')
+ print(oinspect.getdoc(func))
+
+ def format_latex(self, strng):
+ """Format a string for latex inclusion."""
+
+ # Characters that need to be escaped for latex:
+ escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
+ # Magic command names as headers:
+ cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
+ re.MULTILINE)
+ # Magic commands
+ cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
+ re.MULTILINE)
+ # Paragraph continue
+ par_re = re.compile(r'\\$',re.MULTILINE)
+
+ # The "\n" symbol
+ newline_re = re.compile(r'\\n')
+
+ # Now build the string for output:
+ #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
+ strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
+ strng)
+ strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
+ strng = par_re.sub(r'\\\\',strng)
+ strng = escape_re.sub(r'\\\1',strng)
+ strng = newline_re.sub(r'\\textbackslash{}n',strng)
+ return strng
+
+ def parse_options(self, arg_str, opt_str, *long_opts, **kw):
+ """Parse options passed to an argument string.
+
+ The interface is similar to that of :func:`getopt.getopt`, but it
+ returns a :class:`~IPython.utils.struct.Struct` with the options as keys
+ and the stripped argument string still as a string.
+
+ arg_str is quoted as a true sys.argv vector by using shlex.split.
+ This allows us to easily expand variables, glob files, quote
+ arguments, etc.
+
+ Parameters
+ ----------
+
+ arg_str : str
+ The arguments to parse.
+
+ opt_str : str
+ The options specification.
+
+ mode : str, default 'string'
+ If given as 'list', the argument string is returned as a list (split
+ on whitespace) instead of a string.
+
+ list_all : bool, default False
+ Put all option values in lists. Normally only options
+ appearing more than once are put in a list.
+
+ posix : bool, default True
+ Whether to split the input line in POSIX mode or not, as per the
+ conventions outlined in the :mod:`shlex` module from the standard
+ library.
+ """
+
+ # inject default options at the beginning of the input line
+ caller = sys._getframe(1).f_code.co_name
+ arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
+
+ mode = kw.get('mode','string')
+ if mode not in ['string','list']:
+ raise ValueError('incorrect mode given: %s' % mode)
+ # Get options
+ list_all = kw.get('list_all',0)
+ posix = kw.get('posix', os.name == 'posix')
+ strict = kw.get('strict', True)
+
+ # Check if we have more than one argument to warrant extra processing:
+ odict = {} # Dictionary with options
+ args = arg_str.split()
+ if len(args) >= 1:
+ # If the list of inputs only has 0 or 1 thing in it, there's no
+ # need to look for options
+ argv = arg_split(arg_str, posix, strict)
+ # Do regular option processing
+ try:
+ opts,args = getopt(argv, opt_str, long_opts)
+ except GetoptError as e:
+ raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
+ " ".join(long_opts)))
+ for o,a in opts:
+ if o.startswith('--'):
+ o = o[2:]
+ else:
+ o = o[1:]
+ try:
+ odict[o].append(a)
+ except AttributeError:
+ odict[o] = [odict[o],a]
+ except KeyError:
+ if list_all:
+ odict[o] = [a]
+ else:
+ odict[o] = a
+
+ # Prepare opts,args for return
+ opts = Struct(odict)
+ if mode == 'string':
+ args = ' '.join(args)
+
+ return opts,args
+
+ def default_option(self, fn, optstr):
+ """Make an entry in the options_table for fn, with value optstr"""
+
+ if fn not in self.lsmagic():
+ error("%s is not a magic function" % fn)
+ self.options_table[fn] = optstr
+
+
+class MagicAlias(object):
+ """An alias to another magic function.
+
+ An alias is determined by its magic name and magic kind. Lookup
+ is done at call time, so if the underlying magic changes the alias
+ will call the new function.
+
+ Use the :meth:`MagicsManager.register_alias` method or the
+ `%alias_magic` magic function to create and register a new alias.
+ """
+ def __init__(self, shell, magic_name, magic_kind):
+ self.shell = shell
+ self.magic_name = magic_name
+ self.magic_kind = magic_kind
+
+ self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
+ self.__doc__ = "Alias for `%s`." % self.pretty_target
+
+ self._in_call = False
+
+ def __call__(self, *args, **kwargs):
+ """Call the magic alias."""
+ fn = self.shell.find_magic(self.magic_name, self.magic_kind)
+ if fn is None:
+ raise UsageError("Magic `%s` not found." % self.pretty_target)
+
+ # Protect against infinite recursion.
+ if self._in_call:
+ raise UsageError("Infinite recursion detected; "
+ "magic aliases cannot call themselves.")
+ self._in_call = True
+ try:
+ return fn(*args, **kwargs)
+ finally:
+ self._in_call = False
diff --git a/contrib/python/ipython/py2/IPython/core/magic_arguments.py b/contrib/python/ipython/py2/IPython/core/magic_arguments.py
index 38e03aa176..9231609572 100644
--- a/contrib/python/ipython/py2/IPython/core/magic_arguments.py
+++ b/contrib/python/ipython/py2/IPython/core/magic_arguments.py
@@ -1,278 +1,278 @@
-''' A decorator-based method of constructing IPython magics with `argparse`
-option handling.
-
-New magic functions can be defined like so::
-
- from IPython.core.magic_arguments import (argument, magic_arguments,
- parse_argstring)
-
- @magic_arguments()
- @argument('-o', '--option', help='An optional argument.')
- @argument('arg', type=int, help='An integer positional argument.')
- def magic_cool(self, arg):
- """ A really cool magic command.
-
- """
- args = parse_argstring(magic_cool, arg)
- ...
-
-The `@magic_arguments` decorator marks the function as having argparse arguments.
-The `@argument` decorator adds an argument using the same syntax as argparse's
-`add_argument()` method. More sophisticated uses may also require the
-`@argument_group` or `@kwds` decorator to customize the formatting and the
-parsing.
-
-Help text for the magic is automatically generated from the docstring and the
-arguments::
-
- In[1]: %cool?
- %cool [-o OPTION] arg
-
- A really cool magic command.
-
- positional arguments:
- arg An integer positional argument.
-
- optional arguments:
- -o OPTION, --option OPTION
- An optional argument.
-
-Inheritance diagram:
-
-.. inheritance-diagram:: IPython.core.magic_arguments
- :parts: 3
-
-'''
-#-----------------------------------------------------------------------------
-# Copyright (C) 2010-2011, IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-import argparse
-import re
-
-# Our own imports
-from IPython.core.error import UsageError
-from IPython.utils.decorators import undoc
-from IPython.utils.process import arg_split
-from IPython.utils.text import dedent
-
-NAME_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9_-]*$")
-
-@undoc
-class MagicHelpFormatter(argparse.RawDescriptionHelpFormatter):
- """A HelpFormatter with a couple of changes to meet our needs.
- """
- # Modified to dedent text.
- def _fill_text(self, text, width, indent):
- return argparse.RawDescriptionHelpFormatter._fill_text(self, dedent(text), width, indent)
-
- # Modified to wrap argument placeholders in <> where necessary.
- def _format_action_invocation(self, action):
- if not action.option_strings:
- metavar, = self._metavar_formatter(action, action.dest)(1)
- return metavar
-
- else:
- parts = []
-
- # if the Optional doesn't take a value, format is:
- # -s, --long
- if action.nargs == 0:
- parts.extend(action.option_strings)
-
- # if the Optional takes a value, format is:
- # -s ARGS, --long ARGS
- else:
- default = action.dest.upper()
- args_string = self._format_args(action, default)
- # IPYTHON MODIFICATION: If args_string is not a plain name, wrap
- # it in <> so it's valid RST.
- if not NAME_RE.match(args_string):
- args_string = "<%s>" % args_string
- for option_string in action.option_strings:
- parts.append('%s %s' % (option_string, args_string))
-
- return ', '.join(parts)
-
- # Override the default prefix ('usage') to our % magic escape,
- # in a code block.
- def add_usage(self, usage, actions, groups, prefix="::\n\n %"):
- super(MagicHelpFormatter, self).add_usage(usage, actions, groups, prefix)
-
-class MagicArgumentParser(argparse.ArgumentParser):
- """ An ArgumentParser tweaked for use by IPython magics.
- """
- def __init__(self,
- prog=None,
- usage=None,
- description=None,
- epilog=None,
- parents=None,
- formatter_class=MagicHelpFormatter,
- prefix_chars='-',
- argument_default=None,
- conflict_handler='error',
- add_help=False):
- if parents is None:
- parents = []
- super(MagicArgumentParser, self).__init__(prog=prog, usage=usage,
- description=description, epilog=epilog,
- parents=parents, formatter_class=formatter_class,
- prefix_chars=prefix_chars, argument_default=argument_default,
- conflict_handler=conflict_handler, add_help=add_help)
-
- def error(self, message):
- """ Raise a catchable error instead of exiting.
- """
- raise UsageError(message)
-
- def parse_argstring(self, argstring):
- """ Split a string into an argument list and parse that argument list.
- """
- argv = arg_split(argstring)
- return self.parse_args(argv)
-
-
-def construct_parser(magic_func):
- """ Construct an argument parser using the function decorations.
- """
- kwds = getattr(magic_func, 'argcmd_kwds', {})
- if 'description' not in kwds:
- kwds['description'] = getattr(magic_func, '__doc__', None)
- arg_name = real_name(magic_func)
- parser = MagicArgumentParser(arg_name, **kwds)
- # Reverse the list of decorators in order to apply them in the
- # order in which they appear in the source.
- group = None
- for deco in magic_func.decorators[::-1]:
- result = deco.add_to_parser(parser, group)
- if result is not None:
- group = result
-
- # Replace the magic function's docstring with the full help text.
- magic_func.__doc__ = parser.format_help()
-
- return parser
-
-
-def parse_argstring(magic_func, argstring):
- """ Parse the string of arguments for the given magic function.
- """
- return magic_func.parser.parse_argstring(argstring)
-
-
-def real_name(magic_func):
- """ Find the real name of the magic.
- """
- magic_name = magic_func.__name__
- if magic_name.startswith('magic_'):
- magic_name = magic_name[len('magic_'):]
- return getattr(magic_func, 'argcmd_name', magic_name)
-
-
-class ArgDecorator(object):
- """ Base class for decorators to add ArgumentParser information to a method.
- """
-
- def __call__(self, func):
- if not getattr(func, 'has_arguments', False):
- func.has_arguments = True
- func.decorators = []
- func.decorators.append(self)
- return func
-
- def add_to_parser(self, parser, group):
- """ Add this object's information to the parser, if necessary.
- """
- pass
-
-
-class magic_arguments(ArgDecorator):
- """ Mark the magic as having argparse arguments and possibly adjust the
- name.
- """
-
- def __init__(self, name=None):
- self.name = name
-
- def __call__(self, func):
- if not getattr(func, 'has_arguments', False):
- func.has_arguments = True
- func.decorators = []
- if self.name is not None:
- func.argcmd_name = self.name
- # This should be the first decorator in the list of decorators, thus the
- # last to execute. Build the parser.
- func.parser = construct_parser(func)
- return func
-
-
-class ArgMethodWrapper(ArgDecorator):
-
- """
- Base class to define a wrapper for ArgumentParser method.
-
- Child class must define either `_method_name` or `add_to_parser`.
-
- """
-
- _method_name = None
-
- def __init__(self, *args, **kwds):
- self.args = args
- self.kwds = kwds
-
- def add_to_parser(self, parser, group):
- """ Add this object's information to the parser.
- """
- if group is not None:
- parser = group
- getattr(parser, self._method_name)(*self.args, **self.kwds)
- return None
-
-
-class argument(ArgMethodWrapper):
- """ Store arguments and keywords to pass to add_argument().
-
- Instances also serve to decorate command methods.
- """
- _method_name = 'add_argument'
-
-
-class defaults(ArgMethodWrapper):
- """ Store arguments and keywords to pass to set_defaults().
-
- Instances also serve to decorate command methods.
- """
- _method_name = 'set_defaults'
-
-
-class argument_group(ArgMethodWrapper):
- """ Store arguments and keywords to pass to add_argument_group().
-
- Instances also serve to decorate command methods.
- """
-
- def add_to_parser(self, parser, group):
- """ Add this object's information to the parser.
- """
- return parser.add_argument_group(*self.args, **self.kwds)
-
-
-class kwds(ArgDecorator):
- """ Provide other keywords to the sub-parser constructor.
- """
- def __init__(self, **kwds):
- self.kwds = kwds
-
- def __call__(self, func):
- func = super(kwds, self).__call__(func)
- func.argcmd_kwds = self.kwds
- return func
-
-
-__all__ = ['magic_arguments', 'argument', 'argument_group', 'kwds',
- 'parse_argstring']
+''' A decorator-based method of constructing IPython magics with `argparse`
+option handling.
+
+New magic functions can be defined like so::
+
+ from IPython.core.magic_arguments import (argument, magic_arguments,
+ parse_argstring)
+
+ @magic_arguments()
+ @argument('-o', '--option', help='An optional argument.')
+ @argument('arg', type=int, help='An integer positional argument.')
+ def magic_cool(self, arg):
+ """ A really cool magic command.
+
+ """
+ args = parse_argstring(magic_cool, arg)
+ ...
+
+The `@magic_arguments` decorator marks the function as having argparse arguments.
+The `@argument` decorator adds an argument using the same syntax as argparse's
+`add_argument()` method. More sophisticated uses may also require the
+`@argument_group` or `@kwds` decorator to customize the formatting and the
+parsing.
+
+Help text for the magic is automatically generated from the docstring and the
+arguments::
+
+ In[1]: %cool?
+ %cool [-o OPTION] arg
+
+ A really cool magic command.
+
+ positional arguments:
+ arg An integer positional argument.
+
+ optional arguments:
+ -o OPTION, --option OPTION
+ An optional argument.
+
+Inheritance diagram:
+
+.. inheritance-diagram:: IPython.core.magic_arguments
+ :parts: 3
+
+'''
+#-----------------------------------------------------------------------------
+# Copyright (C) 2010-2011, IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+import argparse
+import re
+
+# Our own imports
+from IPython.core.error import UsageError
+from IPython.utils.decorators import undoc
+from IPython.utils.process import arg_split
+from IPython.utils.text import dedent
+
+NAME_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9_-]*$")
+
+@undoc
+class MagicHelpFormatter(argparse.RawDescriptionHelpFormatter):
+ """A HelpFormatter with a couple of changes to meet our needs.
+ """
+ # Modified to dedent text.
+ def _fill_text(self, text, width, indent):
+ return argparse.RawDescriptionHelpFormatter._fill_text(self, dedent(text), width, indent)
+
+ # Modified to wrap argument placeholders in <> where necessary.
+ def _format_action_invocation(self, action):
+ if not action.option_strings:
+ metavar, = self._metavar_formatter(action, action.dest)(1)
+ return metavar
+
+ else:
+ parts = []
+
+ # if the Optional doesn't take a value, format is:
+ # -s, --long
+ if action.nargs == 0:
+ parts.extend(action.option_strings)
+
+ # if the Optional takes a value, format is:
+ # -s ARGS, --long ARGS
+ else:
+ default = action.dest.upper()
+ args_string = self._format_args(action, default)
+ # IPYTHON MODIFICATION: If args_string is not a plain name, wrap
+ # it in <> so it's valid RST.
+ if not NAME_RE.match(args_string):
+ args_string = "<%s>" % args_string
+ for option_string in action.option_strings:
+ parts.append('%s %s' % (option_string, args_string))
+
+ return ', '.join(parts)
+
+ # Override the default prefix ('usage') to our % magic escape,
+ # in a code block.
+ def add_usage(self, usage, actions, groups, prefix="::\n\n %"):
+ super(MagicHelpFormatter, self).add_usage(usage, actions, groups, prefix)
+
+class MagicArgumentParser(argparse.ArgumentParser):
+ """ An ArgumentParser tweaked for use by IPython magics.
+ """
+ def __init__(self,
+ prog=None,
+ usage=None,
+ description=None,
+ epilog=None,
+ parents=None,
+ formatter_class=MagicHelpFormatter,
+ prefix_chars='-',
+ argument_default=None,
+ conflict_handler='error',
+ add_help=False):
+ if parents is None:
+ parents = []
+ super(MagicArgumentParser, self).__init__(prog=prog, usage=usage,
+ description=description, epilog=epilog,
+ parents=parents, formatter_class=formatter_class,
+ prefix_chars=prefix_chars, argument_default=argument_default,
+ conflict_handler=conflict_handler, add_help=add_help)
+
+ def error(self, message):
+ """ Raise a catchable error instead of exiting.
+ """
+ raise UsageError(message)
+
+ def parse_argstring(self, argstring):
+ """ Split a string into an argument list and parse that argument list.
+ """
+ argv = arg_split(argstring)
+ return self.parse_args(argv)
+
+
+def construct_parser(magic_func):
+ """ Construct an argument parser using the function decorations.
+ """
+ kwds = getattr(magic_func, 'argcmd_kwds', {})
+ if 'description' not in kwds:
+ kwds['description'] = getattr(magic_func, '__doc__', None)
+ arg_name = real_name(magic_func)
+ parser = MagicArgumentParser(arg_name, **kwds)
+ # Reverse the list of decorators in order to apply them in the
+ # order in which they appear in the source.
+ group = None
+ for deco in magic_func.decorators[::-1]:
+ result = deco.add_to_parser(parser, group)
+ if result is not None:
+ group = result
+
+ # Replace the magic function's docstring with the full help text.
+ magic_func.__doc__ = parser.format_help()
+
+ return parser
+
+
+def parse_argstring(magic_func, argstring):
+ """ Parse the string of arguments for the given magic function.
+ """
+ return magic_func.parser.parse_argstring(argstring)
+
+
+def real_name(magic_func):
+ """ Find the real name of the magic.
+ """
+ magic_name = magic_func.__name__
+ if magic_name.startswith('magic_'):
+ magic_name = magic_name[len('magic_'):]
+ return getattr(magic_func, 'argcmd_name', magic_name)
+
+
+class ArgDecorator(object):
+ """ Base class for decorators to add ArgumentParser information to a method.
+ """
+
+ def __call__(self, func):
+ if not getattr(func, 'has_arguments', False):
+ func.has_arguments = True
+ func.decorators = []
+ func.decorators.append(self)
+ return func
+
+ def add_to_parser(self, parser, group):
+ """ Add this object's information to the parser, if necessary.
+ """
+ pass
+
+
+class magic_arguments(ArgDecorator):
+ """ Mark the magic as having argparse arguments and possibly adjust the
+ name.
+ """
+
+ def __init__(self, name=None):
+ self.name = name
+
+ def __call__(self, func):
+ if not getattr(func, 'has_arguments', False):
+ func.has_arguments = True
+ func.decorators = []
+ if self.name is not None:
+ func.argcmd_name = self.name
+ # This should be the first decorator in the list of decorators, thus the
+ # last to execute. Build the parser.
+ func.parser = construct_parser(func)
+ return func
+
+
+class ArgMethodWrapper(ArgDecorator):
+
+ """
+ Base class to define a wrapper for ArgumentParser method.
+
+ Child class must define either `_method_name` or `add_to_parser`.
+
+ """
+
+ _method_name = None
+
+ def __init__(self, *args, **kwds):
+ self.args = args
+ self.kwds = kwds
+
+ def add_to_parser(self, parser, group):
+ """ Add this object's information to the parser.
+ """
+ if group is not None:
+ parser = group
+ getattr(parser, self._method_name)(*self.args, **self.kwds)
+ return None
+
+
+class argument(ArgMethodWrapper):
+ """ Store arguments and keywords to pass to add_argument().
+
+ Instances also serve to decorate command methods.
+ """
+ _method_name = 'add_argument'
+
+
+class defaults(ArgMethodWrapper):
+ """ Store arguments and keywords to pass to set_defaults().
+
+ Instances also serve to decorate command methods.
+ """
+ _method_name = 'set_defaults'
+
+
+class argument_group(ArgMethodWrapper):
+ """ Store arguments and keywords to pass to add_argument_group().
+
+ Instances also serve to decorate command methods.
+ """
+
+ def add_to_parser(self, parser, group):
+ """ Add this object's information to the parser.
+ """
+ return parser.add_argument_group(*self.args, **self.kwds)
+
+
+class kwds(ArgDecorator):
+ """ Provide other keywords to the sub-parser constructor.
+ """
+ def __init__(self, **kwds):
+ self.kwds = kwds
+
+ def __call__(self, func):
+ func = super(kwds, self).__call__(func)
+ func.argcmd_kwds = self.kwds
+ return func
+
+
+__all__ = ['magic_arguments', 'argument', 'argument_group', 'kwds',
+ 'parse_argstring']
diff --git a/contrib/python/ipython/py2/IPython/core/magics/__init__.py b/contrib/python/ipython/py2/IPython/core/magics/__init__.py
index 78d4a45aa0..d2fd5a6cfb 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/__init__.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/__init__.py
@@ -1,41 +1,41 @@
-"""Implementation of all the magic functions built into IPython.
-"""
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012 The IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from ..magic import Magics, magics_class
-from .auto import AutoMagics
-from .basic import BasicMagics
-from .code import CodeMagics, MacroToEdit
-from .config import ConfigMagics
-from .display import DisplayMagics
-from .execution import ExecutionMagics
-from .extension import ExtensionMagics
-from .history import HistoryMagics
-from .logging import LoggingMagics
-from .namespace import NamespaceMagics
-from .osm import OSMagics
-from .pylab import PylabMagics
-from .script import ScriptMagics
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-
-@magics_class
-class UserMagics(Magics):
- """Placeholder for user-defined magics to be added at runtime.
-
- All magics are eventually merged into a single namespace at runtime, but we
- use this class to isolate the magics defined dynamically by the user into
- their own class.
- """
+"""Implementation of all the magic functions built into IPython.
+"""
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012 The IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+from ..magic import Magics, magics_class
+from .auto import AutoMagics
+from .basic import BasicMagics
+from .code import CodeMagics, MacroToEdit
+from .config import ConfigMagics
+from .display import DisplayMagics
+from .execution import ExecutionMagics
+from .extension import ExtensionMagics
+from .history import HistoryMagics
+from .logging import LoggingMagics
+from .namespace import NamespaceMagics
+from .osm import OSMagics
+from .pylab import PylabMagics
+from .script import ScriptMagics
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+
+@magics_class
+class UserMagics(Magics):
+ """Placeholder for user-defined magics to be added at runtime.
+
+ All magics are eventually merged into a single namespace at runtime, but we
+ use this class to isolate the magics defined dynamically by the user into
+ their own class.
+ """
diff --git a/contrib/python/ipython/py2/IPython/core/magics/auto.py b/contrib/python/ipython/py2/IPython/core/magics/auto.py
index be6b218854..f87bafdeb1 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/auto.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/auto.py
@@ -1,130 +1,130 @@
-"""Implementation of magic functions that control various automatic behaviors.
-"""
-from __future__ import print_function
+"""Implementation of magic functions that control various automatic behaviors.
+"""
+from __future__ import print_function
from __future__ import absolute_import
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012 The IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Our own packages
-from IPython.core.magic import Bunch, Magics, magics_class, line_magic
-from IPython.testing.skipdoctest import skip_doctest
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012 The IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Our own packages
+from IPython.core.magic import Bunch, Magics, magics_class, line_magic
+from IPython.testing.skipdoctest import skip_doctest
from logging import error
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-
-@magics_class
-class AutoMagics(Magics):
- """Magics that control various autoX behaviors."""
-
- def __init__(self, shell):
- super(AutoMagics, self).__init__(shell)
- # namespace for holding state we may need
- self._magic_state = Bunch()
-
- @line_magic
- def automagic(self, parameter_s=''):
- """Make magic functions callable without having to type the initial %.
-
- Without argumentsl toggles on/off (when off, you must call it as
- %automagic, of course). With arguments it sets the value, and you can
- use any of (case insensitive):
-
- - on, 1, True: to activate
-
- - off, 0, False: to deactivate.
-
- Note that magic functions have lowest priority, so if there's a
- variable whose name collides with that of a magic fn, automagic won't
- work for that function (you get the variable instead). However, if you
- delete the variable (del var), the previously shadowed magic function
- becomes visible to automagic again."""
-
- arg = parameter_s.lower()
- mman = self.shell.magics_manager
- if arg in ('on', '1', 'true'):
- val = True
- elif arg in ('off', '0', 'false'):
- val = False
- else:
- val = not mman.auto_magic
- mman.auto_magic = val
- print('\n' + self.shell.magics_manager.auto_status())
-
- @skip_doctest
- @line_magic
- def autocall(self, parameter_s=''):
- """Make functions callable without having to type parentheses.
-
- Usage:
-
- %autocall [mode]
-
- The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
- value is toggled on and off (remembering the previous state).
-
- In more detail, these values mean:
-
- 0 -> fully disabled
-
- 1 -> active, but do not apply if there are no arguments on the line.
-
- In this mode, you get::
-
- In [1]: callable
- Out[1]: <built-in function callable>
-
- In [2]: callable 'hello'
- ------> callable('hello')
- Out[2]: False
-
- 2 -> Active always. Even if no arguments are present, the callable
- object is called::
-
- In [2]: float
- ------> float()
- Out[2]: 0.0
-
- Note that even with autocall off, you can still use '/' at the start of
- a line to treat the first argument on the command line as a function
- and add parentheses to it::
-
- In [8]: /str 43
- ------> str(43)
- Out[8]: '43'
-
- # all-random (note for auto-testing)
- """
-
- if parameter_s:
- arg = int(parameter_s)
- else:
- arg = 'toggle'
-
- if not arg in (0, 1, 2, 'toggle'):
- error('Valid modes: (0->Off, 1->Smart, 2->Full')
- return
-
- if arg in (0, 1, 2):
- self.shell.autocall = arg
- else: # toggle
- if self.shell.autocall:
- self._magic_state.autocall_save = self.shell.autocall
- self.shell.autocall = 0
- else:
- try:
- self.shell.autocall = self._magic_state.autocall_save
- except AttributeError:
- self.shell.autocall = self._magic_state.autocall_save = 1
-
- print("Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall])
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+
+@magics_class
+class AutoMagics(Magics):
+ """Magics that control various autoX behaviors."""
+
+ def __init__(self, shell):
+ super(AutoMagics, self).__init__(shell)
+ # namespace for holding state we may need
+ self._magic_state = Bunch()
+
+ @line_magic
+ def automagic(self, parameter_s=''):
+ """Make magic functions callable without having to type the initial %.
+
+ Without argumentsl toggles on/off (when off, you must call it as
+ %automagic, of course). With arguments it sets the value, and you can
+ use any of (case insensitive):
+
+ - on, 1, True: to activate
+
+ - off, 0, False: to deactivate.
+
+ Note that magic functions have lowest priority, so if there's a
+ variable whose name collides with that of a magic fn, automagic won't
+ work for that function (you get the variable instead). However, if you
+ delete the variable (del var), the previously shadowed magic function
+ becomes visible to automagic again."""
+
+ arg = parameter_s.lower()
+ mman = self.shell.magics_manager
+ if arg in ('on', '1', 'true'):
+ val = True
+ elif arg in ('off', '0', 'false'):
+ val = False
+ else:
+ val = not mman.auto_magic
+ mman.auto_magic = val
+ print('\n' + self.shell.magics_manager.auto_status())
+
+ @skip_doctest
+ @line_magic
+ def autocall(self, parameter_s=''):
+ """Make functions callable without having to type parentheses.
+
+ Usage:
+
+ %autocall [mode]
+
+ The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
+ value is toggled on and off (remembering the previous state).
+
+ In more detail, these values mean:
+
+ 0 -> fully disabled
+
+ 1 -> active, but do not apply if there are no arguments on the line.
+
+ In this mode, you get::
+
+ In [1]: callable
+ Out[1]: <built-in function callable>
+
+ In [2]: callable 'hello'
+ ------> callable('hello')
+ Out[2]: False
+
+ 2 -> Active always. Even if no arguments are present, the callable
+ object is called::
+
+ In [2]: float
+ ------> float()
+ Out[2]: 0.0
+
+ Note that even with autocall off, you can still use '/' at the start of
+ a line to treat the first argument on the command line as a function
+ and add parentheses to it::
+
+ In [8]: /str 43
+ ------> str(43)
+ Out[8]: '43'
+
+ # all-random (note for auto-testing)
+ """
+
+ if parameter_s:
+ arg = int(parameter_s)
+ else:
+ arg = 'toggle'
+
+ if not arg in (0, 1, 2, 'toggle'):
+ error('Valid modes: (0->Off, 1->Smart, 2->Full')
+ return
+
+ if arg in (0, 1, 2):
+ self.shell.autocall = arg
+ else: # toggle
+ if self.shell.autocall:
+ self._magic_state.autocall_save = self.shell.autocall
+ self.shell.autocall = 0
+ else:
+ try:
+ self.shell.autocall = self._magic_state.autocall_save
+ except AttributeError:
+ self.shell.autocall = self._magic_state.autocall_save = 1
+
+ print("Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall])
diff --git a/contrib/python/ipython/py2/IPython/core/magics/basic.py b/contrib/python/ipython/py2/IPython/core/magics/basic.py
index 75b1275211..ca69e2e698 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/basic.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/basic.py
@@ -1,575 +1,575 @@
-"""Implementation of basic magic functions."""
-
-from __future__ import print_function
+"""Implementation of basic magic functions."""
+
+from __future__ import print_function
from __future__ import absolute_import
-
+
import argparse
-import io
-import sys
-from pprint import pformat
-
-from IPython.core import magic_arguments, page
-from IPython.core.error import UsageError
-from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
-from IPython.utils.text import format_screen, dedent, indent
-from IPython.testing.skipdoctest import skip_doctest
-from IPython.utils.ipstruct import Struct
-from IPython.utils.py3compat import unicode_type
+import io
+import sys
+from pprint import pformat
+
+from IPython.core import magic_arguments, page
+from IPython.core.error import UsageError
+from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
+from IPython.utils.text import format_screen, dedent, indent
+from IPython.testing.skipdoctest import skip_doctest
+from IPython.utils.ipstruct import Struct
+from IPython.utils.py3compat import unicode_type
from warnings import warn
from logging import error
-
-
-class MagicsDisplay(object):
- def __init__(self, magics_manager):
- self.magics_manager = magics_manager
-
- def _lsmagic(self):
- """The main implementation of the %lsmagic"""
- mesc = magic_escapes['line']
- cesc = magic_escapes['cell']
- mman = self.magics_manager
- magics = mman.lsmagic()
- out = ['Available line magics:',
- mesc + (' '+mesc).join(sorted(magics['line'])),
- '',
- 'Available cell magics:',
- cesc + (' '+cesc).join(sorted(magics['cell'])),
- '',
- mman.auto_status()]
- return '\n'.join(out)
-
- def _repr_pretty_(self, p, cycle):
- p.text(self._lsmagic())
-
- def __str__(self):
- return self._lsmagic()
-
- def _jsonable(self):
- """turn magics dict into jsonable dict of the same structure
-
- replaces object instances with their class names as strings
- """
- magic_dict = {}
- mman = self.magics_manager
- magics = mman.lsmagic()
- for key, subdict in magics.items():
- d = {}
- magic_dict[key] = d
- for name, obj in subdict.items():
- try:
- classname = obj.__self__.__class__.__name__
- except AttributeError:
- classname = 'Other'
-
- d[name] = classname
- return magic_dict
-
- def _repr_json_(self):
- return self._jsonable()
-
-
-@magics_class
-class BasicMagics(Magics):
- """Magics that provide central IPython functionality.
-
- These are various magics that don't fit into specific categories but that
- are all part of the base 'IPython experience'."""
-
- @magic_arguments.magic_arguments()
- @magic_arguments.argument(
- '-l', '--line', action='store_true',
- help="""Create a line magic alias."""
- )
- @magic_arguments.argument(
- '-c', '--cell', action='store_true',
- help="""Create a cell magic alias."""
- )
- @magic_arguments.argument(
- 'name',
- help="""Name of the magic to be created."""
- )
- @magic_arguments.argument(
- 'target',
- help="""Name of the existing line or cell magic."""
- )
- @line_magic
- def alias_magic(self, line=''):
- """Create an alias for an existing line or cell magic.
-
- Examples
- --------
- ::
-
- In [1]: %alias_magic t timeit
- Created `%t` as an alias for `%timeit`.
- Created `%%t` as an alias for `%%timeit`.
-
- In [2]: %t -n1 pass
- 1 loops, best of 3: 954 ns per loop
-
- In [3]: %%t -n1
- ...: pass
- ...:
- 1 loops, best of 3: 954 ns per loop
-
- In [4]: %alias_magic --cell whereami pwd
- UsageError: Cell magic function `%%pwd` not found.
- In [5]: %alias_magic --line whereami pwd
- Created `%whereami` as an alias for `%pwd`.
-
- In [6]: %whereami
- Out[6]: u'/home/testuser'
- """
- args = magic_arguments.parse_argstring(self.alias_magic, line)
- shell = self.shell
- mman = self.shell.magics_manager
- escs = ''.join(magic_escapes.values())
-
- target = args.target.lstrip(escs)
- name = args.name.lstrip(escs)
-
- # Find the requested magics.
- m_line = shell.find_magic(target, 'line')
- m_cell = shell.find_magic(target, 'cell')
- if args.line and m_line is None:
- raise UsageError('Line magic function `%s%s` not found.' %
- (magic_escapes['line'], target))
- if args.cell and m_cell is None:
- raise UsageError('Cell magic function `%s%s` not found.' %
- (magic_escapes['cell'], target))
-
- # If --line and --cell are not specified, default to the ones
- # that are available.
- if not args.line and not args.cell:
- if not m_line and not m_cell:
- raise UsageError(
- 'No line or cell magic with name `%s` found.' % target
- )
- args.line = bool(m_line)
- args.cell = bool(m_cell)
-
- if args.line:
- mman.register_alias(name, target, 'line')
- print('Created `%s%s` as an alias for `%s%s`.' % (
- magic_escapes['line'], name,
- magic_escapes['line'], target))
-
- if args.cell:
- mman.register_alias(name, target, 'cell')
- print('Created `%s%s` as an alias for `%s%s`.' % (
- magic_escapes['cell'], name,
- magic_escapes['cell'], target))
-
- @line_magic
- def lsmagic(self, parameter_s=''):
- """List currently available magic functions."""
- return MagicsDisplay(self.shell.magics_manager)
-
- def _magic_docs(self, brief=False, rest=False):
- """Return docstrings from magic functions."""
- mman = self.shell.magics_manager
- docs = mman.lsmagic_docs(brief, missing='No documentation')
-
- if rest:
- format_string = '**%s%s**::\n\n%s\n\n'
- else:
- format_string = '%s%s:\n%s\n'
-
- return ''.join(
- [format_string % (magic_escapes['line'], fname,
- indent(dedent(fndoc)))
- for fname, fndoc in sorted(docs['line'].items())]
- +
- [format_string % (magic_escapes['cell'], fname,
- indent(dedent(fndoc)))
- for fname, fndoc in sorted(docs['cell'].items())]
- )
-
- @line_magic
- def magic(self, parameter_s=''):
- """Print information about the magic function system.
-
- Supported formats: -latex, -brief, -rest
- """
-
- mode = ''
- try:
- mode = parameter_s.split()[0][1:]
- except IndexError:
- pass
-
- brief = (mode == 'brief')
- rest = (mode == 'rest')
- magic_docs = self._magic_docs(brief, rest)
-
- if mode == 'latex':
- print(self.format_latex(magic_docs))
- return
- else:
- magic_docs = format_screen(magic_docs)
-
- out = ["""
-IPython's 'magic' functions
-===========================
-
-The magic function system provides a series of functions which allow you to
-control the behavior of IPython itself, plus a lot of system-type
-features. There are two kinds of magics, line-oriented and cell-oriented.
-
-Line magics are prefixed with the % character and work much like OS
-command-line calls: they get as an argument the rest of the line, where
-arguments are passed without parentheses or quotes. For example, this will
-time the given statement::
-
- %timeit range(1000)
-
-Cell magics are prefixed with a double %%, and they are functions that get as
-an argument not only the rest of the line, but also the lines below it in a
-separate argument. These magics are called with two arguments: the rest of the
-call line and the body of the cell, consisting of the lines below the first.
-For example::
-
- %%timeit x = numpy.random.randn((100, 100))
- numpy.linalg.svd(x)
-
-will time the execution of the numpy svd routine, running the assignment of x
-as part of the setup phase, which is not timed.
-
-In a line-oriented client (the terminal or Qt console IPython), starting a new
-input with %% will automatically enter cell mode, and IPython will continue
-reading input until a blank line is given. In the notebook, simply type the
-whole cell as one entity, but keep in mind that the %% escape can only be at
-the very start of the cell.
-
-NOTE: If you have 'automagic' enabled (via the command line option or with the
-%automagic function), you don't need to type in the % explicitly for line
-magics; cell magics always require an explicit '%%' escape. By default,
-IPython ships with automagic on, so you should only rarely need the % escape.
-
-Example: typing '%cd mydir' (without the quotes) changes your working directory
-to 'mydir', if it exists.
-
-For a list of the available magic functions, use %lsmagic. For a description
-of any of them, type %magic_name?, e.g. '%cd?'.
-
-Currently the magic system has the following functions:""",
- magic_docs,
- "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
- str(self.lsmagic()),
- ]
- page.page('\n'.join(out))
-
-
- @line_magic
- def page(self, parameter_s=''):
- """Pretty print the object and display it through a pager.
-
- %page [options] OBJECT
-
- If no object is given, use _ (last output).
-
- Options:
-
- -r: page str(object), don't pretty-print it."""
-
- # After a function contributed by Olivier Aubert, slightly modified.
-
- # Process options/args
- opts, args = self.parse_options(parameter_s, 'r')
- raw = 'r' in opts
-
- oname = args and args or '_'
- info = self.shell._ofind(oname)
- if info['found']:
- txt = (raw and str or pformat)( info['obj'] )
- page.page(txt)
- else:
- print('Object `%s` not found' % oname)
-
- @line_magic
- def profile(self, parameter_s=''):
+
+
+class MagicsDisplay(object):
+ def __init__(self, magics_manager):
+ self.magics_manager = magics_manager
+
+ def _lsmagic(self):
+ """The main implementation of the %lsmagic"""
+ mesc = magic_escapes['line']
+ cesc = magic_escapes['cell']
+ mman = self.magics_manager
+ magics = mman.lsmagic()
+ out = ['Available line magics:',
+ mesc + (' '+mesc).join(sorted(magics['line'])),
+ '',
+ 'Available cell magics:',
+ cesc + (' '+cesc).join(sorted(magics['cell'])),
+ '',
+ mman.auto_status()]
+ return '\n'.join(out)
+
+ def _repr_pretty_(self, p, cycle):
+ p.text(self._lsmagic())
+
+ def __str__(self):
+ return self._lsmagic()
+
+ def _jsonable(self):
+ """turn magics dict into jsonable dict of the same structure
+
+ replaces object instances with their class names as strings
+ """
+ magic_dict = {}
+ mman = self.magics_manager
+ magics = mman.lsmagic()
+ for key, subdict in magics.items():
+ d = {}
+ magic_dict[key] = d
+ for name, obj in subdict.items():
+ try:
+ classname = obj.__self__.__class__.__name__
+ except AttributeError:
+ classname = 'Other'
+
+ d[name] = classname
+ return magic_dict
+
+ def _repr_json_(self):
+ return self._jsonable()
+
+
+@magics_class
+class BasicMagics(Magics):
+ """Magics that provide central IPython functionality.
+
+ These are various magics that don't fit into specific categories but that
+ are all part of the base 'IPython experience'."""
+
+ @magic_arguments.magic_arguments()
+ @magic_arguments.argument(
+ '-l', '--line', action='store_true',
+ help="""Create a line magic alias."""
+ )
+ @magic_arguments.argument(
+ '-c', '--cell', action='store_true',
+ help="""Create a cell magic alias."""
+ )
+ @magic_arguments.argument(
+ 'name',
+ help="""Name of the magic to be created."""
+ )
+ @magic_arguments.argument(
+ 'target',
+ help="""Name of the existing line or cell magic."""
+ )
+ @line_magic
+ def alias_magic(self, line=''):
+ """Create an alias for an existing line or cell magic.
+
+ Examples
+ --------
+ ::
+
+ In [1]: %alias_magic t timeit
+ Created `%t` as an alias for `%timeit`.
+ Created `%%t` as an alias for `%%timeit`.
+
+ In [2]: %t -n1 pass
+ 1 loops, best of 3: 954 ns per loop
+
+ In [3]: %%t -n1
+ ...: pass
+ ...:
+ 1 loops, best of 3: 954 ns per loop
+
+ In [4]: %alias_magic --cell whereami pwd
+ UsageError: Cell magic function `%%pwd` not found.
+ In [5]: %alias_magic --line whereami pwd
+ Created `%whereami` as an alias for `%pwd`.
+
+ In [6]: %whereami
+ Out[6]: u'/home/testuser'
+ """
+ args = magic_arguments.parse_argstring(self.alias_magic, line)
+ shell = self.shell
+ mman = self.shell.magics_manager
+ escs = ''.join(magic_escapes.values())
+
+ target = args.target.lstrip(escs)
+ name = args.name.lstrip(escs)
+
+ # Find the requested magics.
+ m_line = shell.find_magic(target, 'line')
+ m_cell = shell.find_magic(target, 'cell')
+ if args.line and m_line is None:
+ raise UsageError('Line magic function `%s%s` not found.' %
+ (magic_escapes['line'], target))
+ if args.cell and m_cell is None:
+ raise UsageError('Cell magic function `%s%s` not found.' %
+ (magic_escapes['cell'], target))
+
+ # If --line and --cell are not specified, default to the ones
+ # that are available.
+ if not args.line and not args.cell:
+ if not m_line and not m_cell:
+ raise UsageError(
+ 'No line or cell magic with name `%s` found.' % target
+ )
+ args.line = bool(m_line)
+ args.cell = bool(m_cell)
+
+ if args.line:
+ mman.register_alias(name, target, 'line')
+ print('Created `%s%s` as an alias for `%s%s`.' % (
+ magic_escapes['line'], name,
+ magic_escapes['line'], target))
+
+ if args.cell:
+ mman.register_alias(name, target, 'cell')
+ print('Created `%s%s` as an alias for `%s%s`.' % (
+ magic_escapes['cell'], name,
+ magic_escapes['cell'], target))
+
+ @line_magic
+ def lsmagic(self, parameter_s=''):
+ """List currently available magic functions."""
+ return MagicsDisplay(self.shell.magics_manager)
+
+ def _magic_docs(self, brief=False, rest=False):
+ """Return docstrings from magic functions."""
+ mman = self.shell.magics_manager
+ docs = mman.lsmagic_docs(brief, missing='No documentation')
+
+ if rest:
+ format_string = '**%s%s**::\n\n%s\n\n'
+ else:
+ format_string = '%s%s:\n%s\n'
+
+ return ''.join(
+ [format_string % (magic_escapes['line'], fname,
+ indent(dedent(fndoc)))
+ for fname, fndoc in sorted(docs['line'].items())]
+ +
+ [format_string % (magic_escapes['cell'], fname,
+ indent(dedent(fndoc)))
+ for fname, fndoc in sorted(docs['cell'].items())]
+ )
+
+ @line_magic
+ def magic(self, parameter_s=''):
+ """Print information about the magic function system.
+
+ Supported formats: -latex, -brief, -rest
+ """
+
+ mode = ''
+ try:
+ mode = parameter_s.split()[0][1:]
+ except IndexError:
+ pass
+
+ brief = (mode == 'brief')
+ rest = (mode == 'rest')
+ magic_docs = self._magic_docs(brief, rest)
+
+ if mode == 'latex':
+ print(self.format_latex(magic_docs))
+ return
+ else:
+ magic_docs = format_screen(magic_docs)
+
+ out = ["""
+IPython's 'magic' functions
+===========================
+
+The magic function system provides a series of functions which allow you to
+control the behavior of IPython itself, plus a lot of system-type
+features. There are two kinds of magics, line-oriented and cell-oriented.
+
+Line magics are prefixed with the % character and work much like OS
+command-line calls: they get as an argument the rest of the line, where
+arguments are passed without parentheses or quotes. For example, this will
+time the given statement::
+
+ %timeit range(1000)
+
+Cell magics are prefixed with a double %%, and they are functions that get as
+an argument not only the rest of the line, but also the lines below it in a
+separate argument. These magics are called with two arguments: the rest of the
+call line and the body of the cell, consisting of the lines below the first.
+For example::
+
+ %%timeit x = numpy.random.randn((100, 100))
+ numpy.linalg.svd(x)
+
+will time the execution of the numpy svd routine, running the assignment of x
+as part of the setup phase, which is not timed.
+
+In a line-oriented client (the terminal or Qt console IPython), starting a new
+input with %% will automatically enter cell mode, and IPython will continue
+reading input until a blank line is given. In the notebook, simply type the
+whole cell as one entity, but keep in mind that the %% escape can only be at
+the very start of the cell.
+
+NOTE: If you have 'automagic' enabled (via the command line option or with the
+%automagic function), you don't need to type in the % explicitly for line
+magics; cell magics always require an explicit '%%' escape. By default,
+IPython ships with automagic on, so you should only rarely need the % escape.
+
+Example: typing '%cd mydir' (without the quotes) changes your working directory
+to 'mydir', if it exists.
+
+For a list of the available magic functions, use %lsmagic. For a description
+of any of them, type %magic_name?, e.g. '%cd?'.
+
+Currently the magic system has the following functions:""",
+ magic_docs,
+ "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
+ str(self.lsmagic()),
+ ]
+ page.page('\n'.join(out))
+
+
+ @line_magic
+ def page(self, parameter_s=''):
+ """Pretty print the object and display it through a pager.
+
+ %page [options] OBJECT
+
+ If no object is given, use _ (last output).
+
+ Options:
+
+ -r: page str(object), don't pretty-print it."""
+
+ # After a function contributed by Olivier Aubert, slightly modified.
+
+ # Process options/args
+ opts, args = self.parse_options(parameter_s, 'r')
+ raw = 'r' in opts
+
+ oname = args and args or '_'
+ info = self.shell._ofind(oname)
+ if info['found']:
+ txt = (raw and str or pformat)( info['obj'] )
+ page.page(txt)
+ else:
+ print('Object `%s` not found' % oname)
+
+ @line_magic
+ def profile(self, parameter_s=''):
"""DEPRECATED since IPython 2.0.
-
+
Raise `UsageError`. To profile code use the :magic:`prun` magic.
- See Also
- --------
+ See Also
+ --------
prun : run code using the Python profiler (:magic:`prun`)
- """
- warn("%profile is now deprecated. Please use get_ipython().profile instead.")
- from IPython.core.application import BaseIPythonApplication
- if BaseIPythonApplication.initialized():
- print(BaseIPythonApplication.instance().profile)
- else:
- error("profile is an application-level value, but you don't appear to be in an IPython application")
-
- @line_magic
- def pprint(self, parameter_s=''):
- """Toggle pretty printing on/off."""
- ptformatter = self.shell.display_formatter.formatters['text/plain']
- ptformatter.pprint = bool(1 - ptformatter.pprint)
- print('Pretty printing has been turned',
- ['OFF','ON'][ptformatter.pprint])
-
- @line_magic
- def colors(self, parameter_s=''):
- """Switch color scheme for prompts, info system and exception handlers.
-
- Currently implemented schemes: NoColor, Linux, LightBG.
-
- Color scheme names are not case-sensitive.
-
- Examples
- --------
- To get a plain black and white terminal::
-
- %colors nocolor
- """
- def color_switch_err(name):
- warn('Error changing %s color schemes.\n%s' %
+ """
+ warn("%profile is now deprecated. Please use get_ipython().profile instead.")
+ from IPython.core.application import BaseIPythonApplication
+ if BaseIPythonApplication.initialized():
+ print(BaseIPythonApplication.instance().profile)
+ else:
+ error("profile is an application-level value, but you don't appear to be in an IPython application")
+
+ @line_magic
+ def pprint(self, parameter_s=''):
+ """Toggle pretty printing on/off."""
+ ptformatter = self.shell.display_formatter.formatters['text/plain']
+ ptformatter.pprint = bool(1 - ptformatter.pprint)
+ print('Pretty printing has been turned',
+ ['OFF','ON'][ptformatter.pprint])
+
+ @line_magic
+ def colors(self, parameter_s=''):
+ """Switch color scheme for prompts, info system and exception handlers.
+
+ Currently implemented schemes: NoColor, Linux, LightBG.
+
+ Color scheme names are not case-sensitive.
+
+ Examples
+ --------
+ To get a plain black and white terminal::
+
+ %colors nocolor
+ """
+ def color_switch_err(name):
+ warn('Error changing %s color schemes.\n%s' %
(name, sys.exc_info()[1]), stacklevel=2)
-
-
- new_scheme = parameter_s.strip()
- if not new_scheme:
- raise UsageError(
- "%colors: you must specify a color scheme. See '%colors?'")
- # local shortcut
- shell = self.shell
-
+
+
+ new_scheme = parameter_s.strip()
+ if not new_scheme:
+ raise UsageError(
+ "%colors: you must specify a color scheme. See '%colors?'")
+ # local shortcut
+ shell = self.shell
+
# Set shell colour scheme
- try:
+ try:
shell.colors = new_scheme
shell.refresh_style()
- except:
+ except:
color_switch_err('shell')
- # Set exception colors
- try:
- shell.InteractiveTB.set_colors(scheme = new_scheme)
- shell.SyntaxTB.set_colors(scheme = new_scheme)
- except:
- color_switch_err('exception')
-
- # Set info (for 'object?') colors
- if shell.color_info:
- try:
- shell.inspector.set_active_scheme(new_scheme)
- except:
- color_switch_err('object inspector')
- else:
- shell.inspector.set_active_scheme('NoColor')
-
- @line_magic
- def xmode(self, parameter_s=''):
- """Switch modes for the exception handlers.
-
- Valid modes: Plain, Context and Verbose.
-
- If called without arguments, acts as a toggle."""
-
- def xmode_switch_err(name):
- warn('Error changing %s exception modes.\n%s' %
- (name,sys.exc_info()[1]))
-
- shell = self.shell
- new_mode = parameter_s.strip().capitalize()
- try:
- shell.InteractiveTB.set_mode(mode=new_mode)
- print('Exception reporting mode:',shell.InteractiveTB.mode)
- except:
- xmode_switch_err('user')
-
- @line_magic
- def quickref(self,arg):
- """ Show a quick reference sheet """
- from IPython.core.usage import quick_reference
- qr = quick_reference + self._magic_docs(brief=True)
- page.page(qr)
-
- @line_magic
- def doctest_mode(self, parameter_s=''):
- """Toggle doctest mode on and off.
-
- This mode is intended to make IPython behave as much as possible like a
- plain Python shell, from the perspective of how its prompts, exceptions
- and output look. This makes it easy to copy and paste parts of a
- session into doctests. It does so by:
-
- - Changing the prompts to the classic ``>>>`` ones.
- - Changing the exception reporting mode to 'Plain'.
- - Disabling pretty-printing of output.
-
- Note that IPython also supports the pasting of code snippets that have
- leading '>>>' and '...' prompts in them. This means that you can paste
- doctests from files or docstrings (even if they have leading
- whitespace), and the code will execute correctly. You can then use
- '%history -t' to see the translated history; this will give you the
- input after removal of all the leading prompts and whitespace, which
- can be pasted back into an editor.
-
- With these features, you can switch into this mode easily whenever you
- need to do testing and changes to doctests, without having to leave
- your existing IPython session.
- """
-
- # Shorthands
- shell = self.shell
- meta = shell.meta
- disp_formatter = self.shell.display_formatter
- ptformatter = disp_formatter.formatters['text/plain']
- # dstore is a data store kept in the instance metadata bag to track any
- # changes we make, so we can undo them later.
- dstore = meta.setdefault('doctest_mode',Struct())
- save_dstore = dstore.setdefault
-
- # save a few values we'll need to recover later
- mode = save_dstore('mode',False)
- save_dstore('rc_pprint',ptformatter.pprint)
- save_dstore('xmode',shell.InteractiveTB.mode)
- save_dstore('rc_separate_out',shell.separate_out)
- save_dstore('rc_separate_out2',shell.separate_out2)
- save_dstore('rc_separate_in',shell.separate_in)
- save_dstore('rc_active_types',disp_formatter.active_types)
-
- if not mode:
- # turn on
-
- # Prompt separators like plain python
- shell.separate_in = ''
- shell.separate_out = ''
- shell.separate_out2 = ''
-
-
- ptformatter.pprint = False
- disp_formatter.active_types = ['text/plain']
-
- shell.magic('xmode Plain')
- else:
- # turn off
- shell.separate_in = dstore.rc_separate_in
-
- shell.separate_out = dstore.rc_separate_out
- shell.separate_out2 = dstore.rc_separate_out2
-
- ptformatter.pprint = dstore.rc_pprint
- disp_formatter.active_types = dstore.rc_active_types
-
- shell.magic('xmode ' + dstore.xmode)
-
+ # Set exception colors
+ try:
+ shell.InteractiveTB.set_colors(scheme = new_scheme)
+ shell.SyntaxTB.set_colors(scheme = new_scheme)
+ except:
+ color_switch_err('exception')
+
+ # Set info (for 'object?') colors
+ if shell.color_info:
+ try:
+ shell.inspector.set_active_scheme(new_scheme)
+ except:
+ color_switch_err('object inspector')
+ else:
+ shell.inspector.set_active_scheme('NoColor')
+
+ @line_magic
+ def xmode(self, parameter_s=''):
+ """Switch modes for the exception handlers.
+
+ Valid modes: Plain, Context and Verbose.
+
+ If called without arguments, acts as a toggle."""
+
+ def xmode_switch_err(name):
+ warn('Error changing %s exception modes.\n%s' %
+ (name,sys.exc_info()[1]))
+
+ shell = self.shell
+ new_mode = parameter_s.strip().capitalize()
+ try:
+ shell.InteractiveTB.set_mode(mode=new_mode)
+ print('Exception reporting mode:',shell.InteractiveTB.mode)
+ except:
+ xmode_switch_err('user')
+
+ @line_magic
+ def quickref(self,arg):
+ """ Show a quick reference sheet """
+ from IPython.core.usage import quick_reference
+ qr = quick_reference + self._magic_docs(brief=True)
+ page.page(qr)
+
+ @line_magic
+ def doctest_mode(self, parameter_s=''):
+ """Toggle doctest mode on and off.
+
+ This mode is intended to make IPython behave as much as possible like a
+ plain Python shell, from the perspective of how its prompts, exceptions
+ and output look. This makes it easy to copy and paste parts of a
+ session into doctests. It does so by:
+
+ - Changing the prompts to the classic ``>>>`` ones.
+ - Changing the exception reporting mode to 'Plain'.
+ - Disabling pretty-printing of output.
+
+ Note that IPython also supports the pasting of code snippets that have
+ leading '>>>' and '...' prompts in them. This means that you can paste
+ doctests from files or docstrings (even if they have leading
+ whitespace), and the code will execute correctly. You can then use
+ '%history -t' to see the translated history; this will give you the
+ input after removal of all the leading prompts and whitespace, which
+ can be pasted back into an editor.
+
+ With these features, you can switch into this mode easily whenever you
+ need to do testing and changes to doctests, without having to leave
+ your existing IPython session.
+ """
+
+ # Shorthands
+ shell = self.shell
+ meta = shell.meta
+ disp_formatter = self.shell.display_formatter
+ ptformatter = disp_formatter.formatters['text/plain']
+ # dstore is a data store kept in the instance metadata bag to track any
+ # changes we make, so we can undo them later.
+ dstore = meta.setdefault('doctest_mode',Struct())
+ save_dstore = dstore.setdefault
+
+ # save a few values we'll need to recover later
+ mode = save_dstore('mode',False)
+ save_dstore('rc_pprint',ptformatter.pprint)
+ save_dstore('xmode',shell.InteractiveTB.mode)
+ save_dstore('rc_separate_out',shell.separate_out)
+ save_dstore('rc_separate_out2',shell.separate_out2)
+ save_dstore('rc_separate_in',shell.separate_in)
+ save_dstore('rc_active_types',disp_formatter.active_types)
+
+ if not mode:
+ # turn on
+
+ # Prompt separators like plain python
+ shell.separate_in = ''
+ shell.separate_out = ''
+ shell.separate_out2 = ''
+
+
+ ptformatter.pprint = False
+ disp_formatter.active_types = ['text/plain']
+
+ shell.magic('xmode Plain')
+ else:
+ # turn off
+ shell.separate_in = dstore.rc_separate_in
+
+ shell.separate_out = dstore.rc_separate_out
+ shell.separate_out2 = dstore.rc_separate_out2
+
+ ptformatter.pprint = dstore.rc_pprint
+ disp_formatter.active_types = dstore.rc_active_types
+
+ shell.magic('xmode ' + dstore.xmode)
+
# mode here is the state before we switch; switch_doctest_mode takes
# the mode we're switching to.
shell.switch_doctest_mode(not mode)
- # Store new mode and inform
+ # Store new mode and inform
dstore.mode = bool(not mode)
- mode_label = ['OFF','ON'][dstore.mode]
- print('Doctest mode is:', mode_label)
-
- @line_magic
- def gui(self, parameter_s=''):
- """Enable or disable IPython GUI event loop integration.
-
- %gui [GUINAME]
-
- This magic replaces IPython's threaded shells that were activated
- using the (pylab/wthread/etc.) command line flags. GUI toolkits
- can now be enabled at runtime and keyboard
- interrupts should work without any problems. The following toolkits
- are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
-
- %gui wx # enable wxPython event loop integration
- %gui qt4|qt # enable PyQt4 event loop integration
- %gui qt5 # enable PyQt5 event loop integration
- %gui gtk # enable PyGTK event loop integration
- %gui gtk3 # enable Gtk3 event loop integration
- %gui tk # enable Tk event loop integration
- %gui osx # enable Cocoa event loop integration
- # (requires %matplotlib 1.1)
- %gui # disable all event loop integration
-
- WARNING: after any of these has been called you can simply create
- an application object, but DO NOT start the event loop yourself, as
- we have already handled that.
- """
- opts, arg = self.parse_options(parameter_s, '')
- if arg=='': arg = None
- try:
- return self.shell.enable_gui(arg)
- except Exception as e:
- # print simple error message, rather than traceback if we can't
- # hook up the GUI
- error(str(e))
-
- @skip_doctest
- @line_magic
- def precision(self, s=''):
- """Set floating point precision for pretty printing.
-
- Can set either integer precision or a format string.
-
- If numpy has been imported and precision is an int,
- numpy display precision will also be set, via ``numpy.set_printoptions``.
-
- If no argument is given, defaults will be restored.
-
- Examples
- --------
- ::
-
- In [1]: from math import pi
-
- In [2]: %precision 3
- Out[2]: u'%.3f'
-
- In [3]: pi
- Out[3]: 3.142
-
- In [4]: %precision %i
- Out[4]: u'%i'
-
- In [5]: pi
- Out[5]: 3
-
- In [6]: %precision %e
- Out[6]: u'%e'
-
- In [7]: pi**10
- Out[7]: 9.364805e+04
-
- In [8]: %precision
- Out[8]: u'%r'
-
- In [9]: pi**10
- Out[9]: 93648.047476082982
- """
- ptformatter = self.shell.display_formatter.formatters['text/plain']
- ptformatter.float_precision = s
- return ptformatter.float_format
-
- @magic_arguments.magic_arguments()
- @magic_arguments.argument(
- '-e', '--export', action='store_true', default=False,
+ mode_label = ['OFF','ON'][dstore.mode]
+ print('Doctest mode is:', mode_label)
+
+ @line_magic
+ def gui(self, parameter_s=''):
+ """Enable or disable IPython GUI event loop integration.
+
+ %gui [GUINAME]
+
+ This magic replaces IPython's threaded shells that were activated
+ using the (pylab/wthread/etc.) command line flags. GUI toolkits
+ can now be enabled at runtime and keyboard
+ interrupts should work without any problems. The following toolkits
+ are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
+
+ %gui wx # enable wxPython event loop integration
+ %gui qt4|qt # enable PyQt4 event loop integration
+ %gui qt5 # enable PyQt5 event loop integration
+ %gui gtk # enable PyGTK event loop integration
+ %gui gtk3 # enable Gtk3 event loop integration
+ %gui tk # enable Tk event loop integration
+ %gui osx # enable Cocoa event loop integration
+ # (requires %matplotlib 1.1)
+ %gui # disable all event loop integration
+
+ WARNING: after any of these has been called you can simply create
+ an application object, but DO NOT start the event loop yourself, as
+ we have already handled that.
+ """
+ opts, arg = self.parse_options(parameter_s, '')
+ if arg=='': arg = None
+ try:
+ return self.shell.enable_gui(arg)
+ except Exception as e:
+ # print simple error message, rather than traceback if we can't
+ # hook up the GUI
+ error(str(e))
+
+ @skip_doctest
+ @line_magic
+ def precision(self, s=''):
+ """Set floating point precision for pretty printing.
+
+ Can set either integer precision or a format string.
+
+ If numpy has been imported and precision is an int,
+ numpy display precision will also be set, via ``numpy.set_printoptions``.
+
+ If no argument is given, defaults will be restored.
+
+ Examples
+ --------
+ ::
+
+ In [1]: from math import pi
+
+ In [2]: %precision 3
+ Out[2]: u'%.3f'
+
+ In [3]: pi
+ Out[3]: 3.142
+
+ In [4]: %precision %i
+ Out[4]: u'%i'
+
+ In [5]: pi
+ Out[5]: 3
+
+ In [6]: %precision %e
+ Out[6]: u'%e'
+
+ In [7]: pi**10
+ Out[7]: 9.364805e+04
+
+ In [8]: %precision
+ Out[8]: u'%r'
+
+ In [9]: pi**10
+ Out[9]: 93648.047476082982
+ """
+ ptformatter = self.shell.display_formatter.formatters['text/plain']
+ ptformatter.float_precision = s
+ return ptformatter.float_format
+
+ @magic_arguments.magic_arguments()
+ @magic_arguments.argument(
+ '-e', '--export', action='store_true', default=False,
help=argparse.SUPPRESS
- )
- @magic_arguments.argument(
- 'filename', type=unicode_type,
- help='Notebook name or filename'
- )
- @line_magic
- def notebook(self, s):
- """Export and convert IPython notebooks.
-
- This function can export the current IPython history to a notebook file.
+ )
+ @magic_arguments.argument(
+ 'filename', type=unicode_type,
+ help='Notebook name or filename'
+ )
+ @line_magic
+ def notebook(self, s):
+ """Export and convert IPython notebooks.
+
+ This function can export the current IPython history to a notebook file.
For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
The -e or --export flag is deprecated in IPython 5.2, and will be
removed in the future.
- """
- args = magic_arguments.parse_argstring(self.notebook, s)
-
- from nbformat import write, v4
+ """
+ args = magic_arguments.parse_argstring(self.notebook, s)
+
+ from nbformat import write, v4
cells = []
hist = list(self.shell.history_manager.get_range())
diff --git a/contrib/python/ipython/py2/IPython/core/magics/code.py b/contrib/python/ipython/py2/IPython/core/magics/code.py
index 4f17cda0c0..4c1a40f197 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/code.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/code.py
@@ -1,146 +1,146 @@
-"""Implementation of code management magic functions.
-"""
-from __future__ import print_function
+"""Implementation of code management magic functions.
+"""
+from __future__ import print_function
from __future__ import absolute_import
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012 The IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Stdlib
-import inspect
-import io
-import os
-import re
-import sys
-import ast
-from itertools import chain
-
-# Our own packages
-from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
-from IPython.core.macro import Macro
-from IPython.core.magic import Magics, magics_class, line_magic
-from IPython.core.oinspect import find_file, find_source_lines
-from IPython.testing.skipdoctest import skip_doctest
-from IPython.utils import py3compat
-from IPython.utils.py3compat import string_types
-from IPython.utils.contexts import preserve_keys
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012 The IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Stdlib
+import inspect
+import io
+import os
+import re
+import sys
+import ast
+from itertools import chain
+
+# Our own packages
+from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
+from IPython.core.macro import Macro
+from IPython.core.magic import Magics, magics_class, line_magic
+from IPython.core.oinspect import find_file, find_source_lines
+from IPython.testing.skipdoctest import skip_doctest
+from IPython.utils import py3compat
+from IPython.utils.py3compat import string_types
+from IPython.utils.contexts import preserve_keys
from IPython.utils.path import get_py_filename
from warnings import warn
from logging import error
-from IPython.utils.text import get_text_list
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-
-# Used for exception handling in magic_edit
-class MacroToEdit(ValueError): pass
-
-ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
-
-# To match, e.g. 8-10 1:5 :10 3-
-range_re = re.compile(r"""
-(?P<start>\d+)?
-((?P<sep>[\-:])
- (?P<end>\d+)?)?
-$""", re.VERBOSE)
-
-
-def extract_code_ranges(ranges_str):
- """Turn a string of range for %%load into 2-tuples of (start, stop)
- ready to use as a slice of the content splitted by lines.
-
- Examples
- --------
- list(extract_input_ranges("5-10 2"))
- [(4, 10), (1, 2)]
- """
- for range_str in ranges_str.split():
- rmatch = range_re.match(range_str)
- if not rmatch:
- continue
- sep = rmatch.group("sep")
- start = rmatch.group("start")
- end = rmatch.group("end")
-
- if sep == '-':
- start = int(start) - 1 if start else None
- end = int(end) if end else None
- elif sep == ':':
- start = int(start) - 1 if start else None
- end = int(end) - 1 if end else None
- else:
- end = int(start)
- start = int(start) - 1
- yield (start, end)
-
-
-@skip_doctest
-def extract_symbols(code, symbols):
- """
- Return a tuple (blocks, not_found)
- where ``blocks`` is a list of code fragments
- for each symbol parsed from code, and ``not_found`` are
- symbols not found in the code.
-
- For example::
-
- >>> code = '''a = 10
-
- def b(): return 42
-
- class A: pass'''
-
- >>> extract_symbols(code, 'A,b,z')
- (["class A: pass", "def b(): return 42"], ['z'])
- """
- symbols = symbols.split(',')
-
- # this will raise SyntaxError if code isn't valid Python
- py_code = ast.parse(code)
-
- marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body]
- code = code.split('\n')
-
- symbols_lines = {}
-
- # we already know the start_lineno of each symbol (marks).
- # To find each end_lineno, we traverse in reverse order until each
- # non-blank line
- end = len(code)
- for name, start in reversed(marks):
- while not code[end - 1].strip():
- end -= 1
- if name:
- symbols_lines[name] = (start - 1, end)
- end = start - 1
-
- # Now symbols_lines is a map
- # {'symbol_name': (start_lineno, end_lineno), ...}
-
- # fill a list with chunks of codes for each requested symbol
- blocks = []
- not_found = []
- for symbol in symbols:
- if symbol in symbols_lines:
- start, end = symbols_lines[symbol]
- blocks.append('\n'.join(code[start:end]) + '\n')
- else:
- not_found.append(symbol)
-
- return blocks, not_found
-
+from IPython.utils.text import get_text_list
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+
+# Used for exception handling in magic_edit
+class MacroToEdit(ValueError): pass
+
+ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
+
+# To match, e.g. 8-10 1:5 :10 3-
+range_re = re.compile(r"""
+(?P<start>\d+)?
+((?P<sep>[\-:])
+ (?P<end>\d+)?)?
+$""", re.VERBOSE)
+
+
+def extract_code_ranges(ranges_str):
+ """Turn a string of range for %%load into 2-tuples of (start, stop)
+ ready to use as a slice of the content splitted by lines.
+
+ Examples
+ --------
+ list(extract_input_ranges("5-10 2"))
+ [(4, 10), (1, 2)]
+ """
+ for range_str in ranges_str.split():
+ rmatch = range_re.match(range_str)
+ if not rmatch:
+ continue
+ sep = rmatch.group("sep")
+ start = rmatch.group("start")
+ end = rmatch.group("end")
+
+ if sep == '-':
+ start = int(start) - 1 if start else None
+ end = int(end) if end else None
+ elif sep == ':':
+ start = int(start) - 1 if start else None
+ end = int(end) - 1 if end else None
+ else:
+ end = int(start)
+ start = int(start) - 1
+ yield (start, end)
+
+
+@skip_doctest
+def extract_symbols(code, symbols):
+ """
+ Return a tuple (blocks, not_found)
+ where ``blocks`` is a list of code fragments
+ for each symbol parsed from code, and ``not_found`` are
+ symbols not found in the code.
+
+ For example::
+
+ >>> code = '''a = 10
+
+ def b(): return 42
+
+ class A: pass'''
+
+ >>> extract_symbols(code, 'A,b,z')
+ (["class A: pass", "def b(): return 42"], ['z'])
+ """
+ symbols = symbols.split(',')
+
+ # this will raise SyntaxError if code isn't valid Python
+ py_code = ast.parse(code)
+
+ marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body]
+ code = code.split('\n')
+
+ symbols_lines = {}
+
+ # we already know the start_lineno of each symbol (marks).
+ # To find each end_lineno, we traverse in reverse order until each
+ # non-blank line
+ end = len(code)
+ for name, start in reversed(marks):
+ while not code[end - 1].strip():
+ end -= 1
+ if name:
+ symbols_lines[name] = (start - 1, end)
+ end = start - 1
+
+ # Now symbols_lines is a map
+ # {'symbol_name': (start_lineno, end_lineno), ...}
+
+ # fill a list with chunks of codes for each requested symbol
+ blocks = []
+ not_found = []
+ for symbol in symbols:
+ if symbol in symbols_lines:
+ start, end = symbols_lines[symbol]
+ blocks.append('\n'.join(code[start:end]) + '\n')
+ else:
+ not_found.append(symbol)
+
+ return blocks, not_found
+
def strip_initial_indent(lines):
"""For %load, strip indent from lines until finding an unindented line.
-
+
https://github.com/ipython/ipython/issues/9775
"""
indent_re = re.compile(r'\s+')
@@ -169,578 +169,578 @@ def strip_initial_indent(lines):
yield line
-class InteractivelyDefined(Exception):
- """Exception for interactively defined variable in magic_edit"""
- def __init__(self, index):
- self.index = index
-
-
-@magics_class
-class CodeMagics(Magics):
- """Magics related to code management (loading, saving, editing, ...)."""
-
- def __init__(self, *args, **kwargs):
- self._knowntemps = set()
- super(CodeMagics, self).__init__(*args, **kwargs)
-
- @line_magic
- def save(self, parameter_s=''):
- """Save a set of lines or a macro to a given filename.
-
- Usage:\\
- %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
-
- Options:
-
- -r: use 'raw' input. By default, the 'processed' history is used,
- so that magics are loaded in their transformed version to valid
- Python. If this option is given, the raw input as typed as the
- command line is used instead.
-
- -f: force overwrite. If file exists, %save will prompt for overwrite
- unless -f is given.
-
- -a: append to the file instead of overwriting it.
-
- This function uses the same syntax as %history for input ranges,
- then saves the lines to the filename you specify.
-
- It adds a '.py' extension to the file if you don't do so yourself, and
- it asks for confirmation before overwriting existing files.
-
- If `-r` option is used, the default extension is `.ipy`.
- """
-
- opts,args = self.parse_options(parameter_s,'fra',mode='list')
- if not args:
- raise UsageError('Missing filename.')
- raw = 'r' in opts
- force = 'f' in opts
- append = 'a' in opts
- mode = 'a' if append else 'w'
- ext = u'.ipy' if raw else u'.py'
+class InteractivelyDefined(Exception):
+ """Exception for interactively defined variable in magic_edit"""
+ def __init__(self, index):
+ self.index = index
+
+
+@magics_class
+class CodeMagics(Magics):
+ """Magics related to code management (loading, saving, editing, ...)."""
+
+ def __init__(self, *args, **kwargs):
+ self._knowntemps = set()
+ super(CodeMagics, self).__init__(*args, **kwargs)
+
+ @line_magic
+ def save(self, parameter_s=''):
+ """Save a set of lines or a macro to a given filename.
+
+ Usage:\\
+ %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
+
+ Options:
+
+ -r: use 'raw' input. By default, the 'processed' history is used,
+ so that magics are loaded in their transformed version to valid
+ Python. If this option is given, the raw input as typed as the
+ command line is used instead.
+
+ -f: force overwrite. If file exists, %save will prompt for overwrite
+ unless -f is given.
+
+ -a: append to the file instead of overwriting it.
+
+ This function uses the same syntax as %history for input ranges,
+ then saves the lines to the filename you specify.
+
+ It adds a '.py' extension to the file if you don't do so yourself, and
+ it asks for confirmation before overwriting existing files.
+
+ If `-r` option is used, the default extension is `.ipy`.
+ """
+
+ opts,args = self.parse_options(parameter_s,'fra',mode='list')
+ if not args:
+ raise UsageError('Missing filename.')
+ raw = 'r' in opts
+ force = 'f' in opts
+ append = 'a' in opts
+ mode = 'a' if append else 'w'
+ ext = u'.ipy' if raw else u'.py'
fname, codefrom = args[0], " ".join(args[1:])
- if not fname.endswith((u'.py',u'.ipy')):
- fname += ext
- file_exists = os.path.isfile(fname)
- if file_exists and not force and not append:
- try:
- overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
- except StdinNotImplementedError:
- print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
- return
- if not overwrite :
- print('Operation cancelled.')
- return
- try:
- cmds = self.shell.find_user_code(codefrom,raw)
- except (TypeError, ValueError) as e:
- print(e.args[0])
- return
- out = py3compat.cast_unicode(cmds)
- with io.open(fname, mode, encoding="utf-8") as f:
- if not file_exists or not append:
- f.write(u"# coding: utf-8\n")
- f.write(out)
- # make sure we end on a newline
- if not out.endswith(u'\n'):
- f.write(u'\n')
- print('The following commands were written to file `%s`:' % fname)
- print(cmds)
-
- @line_magic
- def pastebin(self, parameter_s=''):
- """Upload code to Github's Gist paste bin, returning the URL.
-
- Usage:\\
- %pastebin [-d "Custom description"] 1-7
-
- The argument can be an input history range, a filename, or the name of a
- string or macro.
-
- Options:
-
- -d: Pass a custom description for the gist. The default will say
- "Pasted from IPython".
- """
- opts, args = self.parse_options(parameter_s, 'd:')
-
- try:
- code = self.shell.find_user_code(args)
- except (ValueError, TypeError) as e:
- print(e.args[0])
- return
-
- # Deferred import
- try:
- from urllib.request import urlopen # Py 3
- except ImportError:
- from urllib2 import urlopen
- import json
- post_data = json.dumps({
- "description": opts.get('d', "Pasted from IPython"),
- "public": True,
- "files": {
- "file1.py": {
- "content": code
- }
- }
- }).encode('utf-8')
-
- response = urlopen("https://api.github.com/gists", post_data)
- response_data = json.loads(response.read().decode('utf-8'))
- return response_data['html_url']
-
- @line_magic
- def loadpy(self, arg_s):
- """Alias of `%load`
-
- `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
- extension. So it has been renamed simply into %load. You can look at
- `%load`'s docstring for more info.
- """
- self.load(arg_s)
-
- @line_magic
- def load(self, arg_s):
- """Load code into the current frontend.
-
- Usage:\\
- %load [options] source
-
- where source can be a filename, URL, input history range, macro, or
- element in the user namespace
-
- Options:
-
- -r <lines>: Specify lines or ranges of lines to load from the source.
- Ranges could be specified as x-y (x..y) or in python-style x:y
- (x..(y-1)). Both limits x and y can be left blank (meaning the
- beginning and end of the file, respectively).
-
- -s <symbols>: Specify function or classes to load from python source.
-
- -y : Don't ask confirmation for loading source above 200 000 characters.
-
- -n : Include the user's namespace when searching for source code.
-
- This magic command can either take a local filename, a URL, an history
- range (see %history) or a macro as argument, it will prompt for
- confirmation before loading source with more than 200 000 characters, unless
- -y flag is passed or if the frontend does not support raw_input::
-
- %load myscript.py
- %load 7-27
- %load myMacro
- %load http://www.example.com/myscript.py
- %load -r 5-10 myscript.py
- %load -r 10-20,30,40: foo.py
- %load -s MyClass,wonder_function myscript.py
- %load -n MyClass
- %load -n my_module.wonder_function
- """
- opts,args = self.parse_options(arg_s,'yns:r:')
-
- if not args:
- raise UsageError('Missing filename, URL, input history range, '
- 'macro, or element in the user namespace.')
-
- search_ns = 'n' in opts
-
- contents = self.shell.find_user_code(args, search_ns=search_ns)
-
- if 's' in opts:
- try:
- blocks, not_found = extract_symbols(contents, opts['s'])
- except SyntaxError:
- # non python code
- error("Unable to parse the input as valid Python code")
- return
-
- if len(not_found) == 1:
- warn('The symbol `%s` was not found' % not_found[0])
- elif len(not_found) > 1:
- warn('The symbols %s were not found' % get_text_list(not_found,
- wrap_item_with='`')
- )
-
- contents = '\n'.join(blocks)
-
- if 'r' in opts:
- ranges = opts['r'].replace(',', ' ')
- lines = contents.split('\n')
- slices = extract_code_ranges(ranges)
- contents = [lines[slice(*slc)] for slc in slices]
+ if not fname.endswith((u'.py',u'.ipy')):
+ fname += ext
+ file_exists = os.path.isfile(fname)
+ if file_exists and not force and not append:
+ try:
+ overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
+ except StdinNotImplementedError:
+ print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
+ return
+ if not overwrite :
+ print('Operation cancelled.')
+ return
+ try:
+ cmds = self.shell.find_user_code(codefrom,raw)
+ except (TypeError, ValueError) as e:
+ print(e.args[0])
+ return
+ out = py3compat.cast_unicode(cmds)
+ with io.open(fname, mode, encoding="utf-8") as f:
+ if not file_exists or not append:
+ f.write(u"# coding: utf-8\n")
+ f.write(out)
+ # make sure we end on a newline
+ if not out.endswith(u'\n'):
+ f.write(u'\n')
+ print('The following commands were written to file `%s`:' % fname)
+ print(cmds)
+
+ @line_magic
+ def pastebin(self, parameter_s=''):
+ """Upload code to Github's Gist paste bin, returning the URL.
+
+ Usage:\\
+ %pastebin [-d "Custom description"] 1-7
+
+ The argument can be an input history range, a filename, or the name of a
+ string or macro.
+
+ Options:
+
+ -d: Pass a custom description for the gist. The default will say
+ "Pasted from IPython".
+ """
+ opts, args = self.parse_options(parameter_s, 'd:')
+
+ try:
+ code = self.shell.find_user_code(args)
+ except (ValueError, TypeError) as e:
+ print(e.args[0])
+ return
+
+ # Deferred import
+ try:
+ from urllib.request import urlopen # Py 3
+ except ImportError:
+ from urllib2 import urlopen
+ import json
+ post_data = json.dumps({
+ "description": opts.get('d', "Pasted from IPython"),
+ "public": True,
+ "files": {
+ "file1.py": {
+ "content": code
+ }
+ }
+ }).encode('utf-8')
+
+ response = urlopen("https://api.github.com/gists", post_data)
+ response_data = json.loads(response.read().decode('utf-8'))
+ return response_data['html_url']
+
+ @line_magic
+ def loadpy(self, arg_s):
+ """Alias of `%load`
+
+ `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
+ extension. So it has been renamed simply into %load. You can look at
+ `%load`'s docstring for more info.
+ """
+ self.load(arg_s)
+
+ @line_magic
+ def load(self, arg_s):
+ """Load code into the current frontend.
+
+ Usage:\\
+ %load [options] source
+
+ where source can be a filename, URL, input history range, macro, or
+ element in the user namespace
+
+ Options:
+
+ -r <lines>: Specify lines or ranges of lines to load from the source.
+ Ranges could be specified as x-y (x..y) or in python-style x:y
+ (x..(y-1)). Both limits x and y can be left blank (meaning the
+ beginning and end of the file, respectively).
+
+ -s <symbols>: Specify function or classes to load from python source.
+
+ -y : Don't ask confirmation for loading source above 200 000 characters.
+
+ -n : Include the user's namespace when searching for source code.
+
+ This magic command can either take a local filename, a URL, an history
+ range (see %history) or a macro as argument, it will prompt for
+ confirmation before loading source with more than 200 000 characters, unless
+ -y flag is passed or if the frontend does not support raw_input::
+
+ %load myscript.py
+ %load 7-27
+ %load myMacro
+ %load http://www.example.com/myscript.py
+ %load -r 5-10 myscript.py
+ %load -r 10-20,30,40: foo.py
+ %load -s MyClass,wonder_function myscript.py
+ %load -n MyClass
+ %load -n my_module.wonder_function
+ """
+ opts,args = self.parse_options(arg_s,'yns:r:')
+
+ if not args:
+ raise UsageError('Missing filename, URL, input history range, '
+ 'macro, or element in the user namespace.')
+
+ search_ns = 'n' in opts
+
+ contents = self.shell.find_user_code(args, search_ns=search_ns)
+
+ if 's' in opts:
+ try:
+ blocks, not_found = extract_symbols(contents, opts['s'])
+ except SyntaxError:
+ # non python code
+ error("Unable to parse the input as valid Python code")
+ return
+
+ if len(not_found) == 1:
+ warn('The symbol `%s` was not found' % not_found[0])
+ elif len(not_found) > 1:
+ warn('The symbols %s were not found' % get_text_list(not_found,
+ wrap_item_with='`')
+ )
+
+ contents = '\n'.join(blocks)
+
+ if 'r' in opts:
+ ranges = opts['r'].replace(',', ' ')
+ lines = contents.split('\n')
+ slices = extract_code_ranges(ranges)
+ contents = [lines[slice(*slc)] for slc in slices]
contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
-
- l = len(contents)
-
- # 200 000 is ~ 2500 full 80 caracter lines
- # so in average, more than 5000 lines
- if l > 200000 and 'y' not in opts:
- try:
- ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
- " (%d characters). Continue (y/[N]) ?" % l), default='n' )
- except StdinNotImplementedError:
- #asume yes if raw input not implemented
- ans = True
-
- if ans is False :
- print('Operation cancelled.')
- return
-
- contents = "# %load {}\n".format(arg_s) + contents
-
- self.shell.set_next_input(contents, replace=True)
-
- @staticmethod
- def _find_edit_target(shell, args, opts, last_call):
- """Utility method used by magic_edit to find what to edit."""
-
- def make_filename(arg):
- "Make a filename from the given args"
- try:
- filename = get_py_filename(arg)
- except IOError:
- # If it ends with .py but doesn't already exist, assume we want
- # a new file.
- if arg.endswith('.py'):
- filename = arg
- else:
- filename = None
- return filename
-
- # Set a few locals from the options for convenience:
- opts_prev = 'p' in opts
- opts_raw = 'r' in opts
-
- # custom exceptions
- class DataIsObject(Exception): pass
-
- # Default line number value
- lineno = opts.get('n',None)
-
- if opts_prev:
- args = '_%s' % last_call[0]
- if args not in shell.user_ns:
- args = last_call[1]
-
- # by default this is done with temp files, except when the given
- # arg is a filename
- use_temp = True
-
- data = ''
-
- # First, see if the arguments should be a filename.
- filename = make_filename(args)
- if filename:
- use_temp = False
- elif args:
- # Mode where user specifies ranges of lines, like in %macro.
- data = shell.extract_input_lines(args, opts_raw)
- if not data:
- try:
- # Load the parameter given as a variable. If not a string,
- # process it as an object instead (below)
-
- #print '*** args',args,'type',type(args) # dbg
- data = eval(args, shell.user_ns)
- if not isinstance(data, string_types):
- raise DataIsObject
-
- except (NameError,SyntaxError):
- # given argument is not a variable, try as a filename
- filename = make_filename(args)
- if filename is None:
- warn("Argument given (%s) can't be found as a variable "
- "or as a filename." % args)
- return (None, None, None)
- use_temp = False
-
- except DataIsObject:
- # macros have a special edit function
- if isinstance(data, Macro):
- raise MacroToEdit(data)
-
- # For objects, try to edit the file where they are defined
- filename = find_file(data)
- if filename:
- if 'fakemodule' in filename.lower() and \
- inspect.isclass(data):
- # class created by %edit? Try to find source
- # by looking for method definitions instead, the
- # __module__ in those classes is FakeModule.
- attrs = [getattr(data, aname) for aname in dir(data)]
- for attr in attrs:
- if not inspect.ismethod(attr):
- continue
- filename = find_file(attr)
- if filename and \
- 'fakemodule' not in filename.lower():
- # change the attribute to be the edit
- # target instead
- data = attr
- break
-
- m = ipython_input_pat.match(os.path.basename(filename))
- if m:
- raise InteractivelyDefined(int(m.groups()[0]))
-
- datafile = 1
- if filename is None:
- filename = make_filename(args)
- datafile = 1
- if filename is not None:
- # only warn about this if we get a real name
- warn('Could not find file where `%s` is defined.\n'
- 'Opening a file named `%s`' % (args, filename))
- # Now, make sure we can actually read the source (if it was
- # in a temp file it's gone by now).
- if datafile:
- if lineno is None:
- lineno = find_source_lines(data)
- if lineno is None:
- filename = make_filename(args)
- if filename is None:
- warn('The file where `%s` was defined '
- 'cannot be read or found.' % data)
- return (None, None, None)
- use_temp = False
-
- if use_temp:
- filename = shell.mktempfile(data)
- print('IPython will make a temporary file named:',filename)
-
- # use last_call to remember the state of the previous call, but don't
- # let it be clobbered by successive '-p' calls.
- try:
- last_call[0] = shell.displayhook.prompt_count
- if not opts_prev:
- last_call[1] = args
- except:
- pass
-
-
- return filename, lineno, use_temp
-
- def _edit_macro(self,mname,macro):
- """open an editor with the macro data in a file"""
- filename = self.shell.mktempfile(macro.value)
- self.shell.hooks.editor(filename)
-
- # and make a new macro object, to replace the old one
- with open(filename) as mfile:
- mvalue = mfile.read()
- self.shell.user_ns[mname] = Macro(mvalue)
-
- @skip_doctest
- @line_magic
- def edit(self, parameter_s='',last_call=['','']):
- """Bring up an editor and execute the resulting code.
-
- Usage:
- %edit [options] [args]
-
- %edit runs IPython's editor hook. The default version of this hook is
- set to call the editor specified by your $EDITOR environment variable.
- If this isn't found, it will default to vi under Linux/Unix and to
- notepad under Windows. See the end of this docstring for how to change
- the editor hook.
-
- You can also set the value of this editor via the
- ``TerminalInteractiveShell.editor`` option in your configuration file.
- This is useful if you wish to use a different editor from your typical
- default with IPython (and for Windows users who typically don't set
- environment variables).
-
- This command allows you to conveniently edit multi-line code right in
- your IPython session.
-
- If called without arguments, %edit opens up an empty editor with a
- temporary file and will execute the contents of this file when you
- close it (don't forget to save it!).
-
-
- Options:
-
- -n <number>: open the editor at a specified line number. By default,
- the IPython editor hook uses the unix syntax 'editor +N filename', but
- you can configure this by providing your own modified hook if your
- favorite editor supports line-number specifications with a different
- syntax.
-
- -p: this will call the editor with the same data as the previous time
- it was used, regardless of how long ago (in your current session) it
- was.
-
- -r: use 'raw' input. This option only applies to input taken from the
- user's history. By default, the 'processed' history is used, so that
- magics are loaded in their transformed version to valid Python. If
- this option is given, the raw input as typed as the command line is
- used instead. When you exit the editor, it will be executed by
- IPython's own processor.
-
- -x: do not execute the edited code immediately upon exit. This is
- mainly useful if you are editing programs which need to be called with
- command line arguments, which you can then do using %run.
-
-
- Arguments:
-
- If arguments are given, the following possibilities exist:
-
- - If the argument is a filename, IPython will load that into the
- editor. It will execute its contents with execfile() when you exit,
- loading any code in the file into your interactive namespace.
-
- - The arguments are ranges of input history, e.g. "7 ~1/4-6".
- The syntax is the same as in the %history magic.
-
- - If the argument is a string variable, its contents are loaded
- into the editor. You can thus edit any string which contains
- python code (including the result of previous edits).
-
- - If the argument is the name of an object (other than a string),
- IPython will try to locate the file where it was defined and open the
- editor at the point where it is defined. You can use `%edit function`
- to load an editor exactly at the point where 'function' is defined,
- edit it and have the file be executed automatically.
-
- - If the object is a macro (see %macro for details), this opens up your
- specified editor with a temporary file containing the macro's data.
- Upon exit, the macro is reloaded with the contents of the file.
-
- Note: opening at an exact line is only supported under Unix, and some
- editors (like kedit and gedit up to Gnome 2.8) do not understand the
- '+NUMBER' parameter necessary for this feature. Good editors like
- (X)Emacs, vi, jed, pico and joe all do.
-
- After executing your code, %edit will return as output the code you
- typed in the editor (except when it was an existing file). This way
- you can reload the code in further invocations of %edit as a variable,
- via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
- the output.
-
- Note that %edit is also available through the alias %ed.
-
- This is an example of creating a simple function inside the editor and
- then modifying it. First, start up the editor::
-
- In [1]: edit
- Editing... done. Executing edited code...
- Out[1]: 'def foo():\\n print "foo() was defined in an editing
- session"\\n'
-
- We can then call the function foo()::
-
- In [2]: foo()
- foo() was defined in an editing session
-
- Now we edit foo. IPython automatically loads the editor with the
- (temporary) file where foo() was previously defined::
-
- In [3]: edit foo
- Editing... done. Executing edited code...
-
- And if we call foo() again we get the modified version::
-
- In [4]: foo()
- foo() has now been changed!
-
- Here is an example of how to edit a code snippet successive
- times. First we call the editor::
-
- In [5]: edit
- Editing... done. Executing edited code...
- hello
- Out[5]: "print 'hello'\\n"
-
- Now we call it again with the previous output (stored in _)::
-
- In [6]: edit _
- Editing... done. Executing edited code...
- hello world
- Out[6]: "print 'hello world'\\n"
-
- Now we call it with the output #8 (stored in _8, also as Out[8])::
-
- In [7]: edit _8
- Editing... done. Executing edited code...
- hello again
- Out[7]: "print 'hello again'\\n"
-
-
- Changing the default editor hook:
-
- If you wish to write your own editor hook, you can put it in a
- configuration file which you load at startup time. The default hook
- is defined in the IPython.core.hooks module, and you can use that as a
- starting example for further modifications. That file also has
- general instructions on how to set a new hook for use once you've
- defined it."""
- opts,args = self.parse_options(parameter_s,'prxn:')
-
- try:
- filename, lineno, is_temp = self._find_edit_target(self.shell,
- args, opts, last_call)
- except MacroToEdit as e:
- self._edit_macro(args, e.args[0])
- return
- except InteractivelyDefined as e:
- print("Editing In[%i]" % e.index)
- args = str(e.index)
- filename, lineno, is_temp = self._find_edit_target(self.shell,
- args, opts, last_call)
- if filename is None:
- # nothing was found, warnings have already been issued,
- # just give up.
- return
-
- if is_temp:
- self._knowntemps.add(filename)
- elif (filename in self._knowntemps):
- is_temp = True
-
-
- # do actual editing here
- print('Editing...', end=' ')
- sys.stdout.flush()
- try:
- # Quote filenames that may have spaces in them
- if ' ' in filename:
- filename = "'%s'" % filename
- self.shell.hooks.editor(filename,lineno)
- except TryNext:
- warn('Could not open editor')
- return
-
- # XXX TODO: should this be generalized for all string vars?
- # For now, this is special-cased to blocks created by cpaste
- if args.strip() == 'pasted_block':
- with open(filename, 'r') as f:
- self.shell.user_ns['pasted_block'] = f.read()
-
- if 'x' in opts: # -x prevents actual execution
- print()
- else:
- print('done. Executing edited code...')
- with preserve_keys(self.shell.user_ns, '__file__'):
- if not is_temp:
- self.shell.user_ns['__file__'] = filename
- if 'r' in opts: # Untranslated IPython code
- with open(filename, 'r') as f:
- source = f.read()
- self.shell.run_cell(source, store_history=False)
- else:
- self.shell.safe_execfile(filename, self.shell.user_ns,
- self.shell.user_ns)
-
- if is_temp:
- try:
- return open(filename).read()
- except IOError as msg:
- if msg.filename == filename:
- warn('File not found. Did you forget to save?')
- return
- else:
- self.shell.showtraceback()
+
+ l = len(contents)
+
+ # 200 000 is ~ 2500 full 80 caracter lines
+ # so in average, more than 5000 lines
+ if l > 200000 and 'y' not in opts:
+ try:
+ ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
+ " (%d characters). Continue (y/[N]) ?" % l), default='n' )
+ except StdinNotImplementedError:
+ #asume yes if raw input not implemented
+ ans = True
+
+ if ans is False :
+ print('Operation cancelled.')
+ return
+
+ contents = "# %load {}\n".format(arg_s) + contents
+
+ self.shell.set_next_input(contents, replace=True)
+
+ @staticmethod
+ def _find_edit_target(shell, args, opts, last_call):
+ """Utility method used by magic_edit to find what to edit."""
+
+ def make_filename(arg):
+ "Make a filename from the given args"
+ try:
+ filename = get_py_filename(arg)
+ except IOError:
+ # If it ends with .py but doesn't already exist, assume we want
+ # a new file.
+ if arg.endswith('.py'):
+ filename = arg
+ else:
+ filename = None
+ return filename
+
+ # Set a few locals from the options for convenience:
+ opts_prev = 'p' in opts
+ opts_raw = 'r' in opts
+
+ # custom exceptions
+ class DataIsObject(Exception): pass
+
+ # Default line number value
+ lineno = opts.get('n',None)
+
+ if opts_prev:
+ args = '_%s' % last_call[0]
+ if args not in shell.user_ns:
+ args = last_call[1]
+
+ # by default this is done with temp files, except when the given
+ # arg is a filename
+ use_temp = True
+
+ data = ''
+
+ # First, see if the arguments should be a filename.
+ filename = make_filename(args)
+ if filename:
+ use_temp = False
+ elif args:
+ # Mode where user specifies ranges of lines, like in %macro.
+ data = shell.extract_input_lines(args, opts_raw)
+ if not data:
+ try:
+ # Load the parameter given as a variable. If not a string,
+ # process it as an object instead (below)
+
+ #print '*** args',args,'type',type(args) # dbg
+ data = eval(args, shell.user_ns)
+ if not isinstance(data, string_types):
+ raise DataIsObject
+
+ except (NameError,SyntaxError):
+ # given argument is not a variable, try as a filename
+ filename = make_filename(args)
+ if filename is None:
+ warn("Argument given (%s) can't be found as a variable "
+ "or as a filename." % args)
+ return (None, None, None)
+ use_temp = False
+
+ except DataIsObject:
+ # macros have a special edit function
+ if isinstance(data, Macro):
+ raise MacroToEdit(data)
+
+ # For objects, try to edit the file where they are defined
+ filename = find_file(data)
+ if filename:
+ if 'fakemodule' in filename.lower() and \
+ inspect.isclass(data):
+ # class created by %edit? Try to find source
+ # by looking for method definitions instead, the
+ # __module__ in those classes is FakeModule.
+ attrs = [getattr(data, aname) for aname in dir(data)]
+ for attr in attrs:
+ if not inspect.ismethod(attr):
+ continue
+ filename = find_file(attr)
+ if filename and \
+ 'fakemodule' not in filename.lower():
+ # change the attribute to be the edit
+ # target instead
+ data = attr
+ break
+
+ m = ipython_input_pat.match(os.path.basename(filename))
+ if m:
+ raise InteractivelyDefined(int(m.groups()[0]))
+
+ datafile = 1
+ if filename is None:
+ filename = make_filename(args)
+ datafile = 1
+ if filename is not None:
+ # only warn about this if we get a real name
+ warn('Could not find file where `%s` is defined.\n'
+ 'Opening a file named `%s`' % (args, filename))
+ # Now, make sure we can actually read the source (if it was
+ # in a temp file it's gone by now).
+ if datafile:
+ if lineno is None:
+ lineno = find_source_lines(data)
+ if lineno is None:
+ filename = make_filename(args)
+ if filename is None:
+ warn('The file where `%s` was defined '
+ 'cannot be read or found.' % data)
+ return (None, None, None)
+ use_temp = False
+
+ if use_temp:
+ filename = shell.mktempfile(data)
+ print('IPython will make a temporary file named:',filename)
+
+ # use last_call to remember the state of the previous call, but don't
+ # let it be clobbered by successive '-p' calls.
+ try:
+ last_call[0] = shell.displayhook.prompt_count
+ if not opts_prev:
+ last_call[1] = args
+ except:
+ pass
+
+
+ return filename, lineno, use_temp
+
+ def _edit_macro(self,mname,macro):
+ """open an editor with the macro data in a file"""
+ filename = self.shell.mktempfile(macro.value)
+ self.shell.hooks.editor(filename)
+
+ # and make a new macro object, to replace the old one
+ with open(filename) as mfile:
+ mvalue = mfile.read()
+ self.shell.user_ns[mname] = Macro(mvalue)
+
+ @skip_doctest
+ @line_magic
+ def edit(self, parameter_s='',last_call=['','']):
+ """Bring up an editor and execute the resulting code.
+
+ Usage:
+ %edit [options] [args]
+
+ %edit runs IPython's editor hook. The default version of this hook is
+ set to call the editor specified by your $EDITOR environment variable.
+ If this isn't found, it will default to vi under Linux/Unix and to
+ notepad under Windows. See the end of this docstring for how to change
+ the editor hook.
+
+ You can also set the value of this editor via the
+ ``TerminalInteractiveShell.editor`` option in your configuration file.
+ This is useful if you wish to use a different editor from your typical
+ default with IPython (and for Windows users who typically don't set
+ environment variables).
+
+ This command allows you to conveniently edit multi-line code right in
+ your IPython session.
+
+ If called without arguments, %edit opens up an empty editor with a
+ temporary file and will execute the contents of this file when you
+ close it (don't forget to save it!).
+
+
+ Options:
+
+ -n <number>: open the editor at a specified line number. By default,
+ the IPython editor hook uses the unix syntax 'editor +N filename', but
+ you can configure this by providing your own modified hook if your
+ favorite editor supports line-number specifications with a different
+ syntax.
+
+ -p: this will call the editor with the same data as the previous time
+ it was used, regardless of how long ago (in your current session) it
+ was.
+
+ -r: use 'raw' input. This option only applies to input taken from the
+ user's history. By default, the 'processed' history is used, so that
+ magics are loaded in their transformed version to valid Python. If
+ this option is given, the raw input as typed as the command line is
+ used instead. When you exit the editor, it will be executed by
+ IPython's own processor.
+
+ -x: do not execute the edited code immediately upon exit. This is
+ mainly useful if you are editing programs which need to be called with
+ command line arguments, which you can then do using %run.
+
+
+ Arguments:
+
+ If arguments are given, the following possibilities exist:
+
+ - If the argument is a filename, IPython will load that into the
+ editor. It will execute its contents with execfile() when you exit,
+ loading any code in the file into your interactive namespace.
+
+ - The arguments are ranges of input history, e.g. "7 ~1/4-6".
+ The syntax is the same as in the %history magic.
+
+ - If the argument is a string variable, its contents are loaded
+ into the editor. You can thus edit any string which contains
+ python code (including the result of previous edits).
+
+ - If the argument is the name of an object (other than a string),
+ IPython will try to locate the file where it was defined and open the
+ editor at the point where it is defined. You can use `%edit function`
+ to load an editor exactly at the point where 'function' is defined,
+ edit it and have the file be executed automatically.
+
+ - If the object is a macro (see %macro for details), this opens up your
+ specified editor with a temporary file containing the macro's data.
+ Upon exit, the macro is reloaded with the contents of the file.
+
+ Note: opening at an exact line is only supported under Unix, and some
+ editors (like kedit and gedit up to Gnome 2.8) do not understand the
+ '+NUMBER' parameter necessary for this feature. Good editors like
+ (X)Emacs, vi, jed, pico and joe all do.
+
+ After executing your code, %edit will return as output the code you
+ typed in the editor (except when it was an existing file). This way
+ you can reload the code in further invocations of %edit as a variable,
+ via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
+ the output.
+
+ Note that %edit is also available through the alias %ed.
+
+ This is an example of creating a simple function inside the editor and
+ then modifying it. First, start up the editor::
+
+ In [1]: edit
+ Editing... done. Executing edited code...
+ Out[1]: 'def foo():\\n print "foo() was defined in an editing
+ session"\\n'
+
+ We can then call the function foo()::
+
+ In [2]: foo()
+ foo() was defined in an editing session
+
+ Now we edit foo. IPython automatically loads the editor with the
+ (temporary) file where foo() was previously defined::
+
+ In [3]: edit foo
+ Editing... done. Executing edited code...
+
+ And if we call foo() again we get the modified version::
+
+ In [4]: foo()
+ foo() has now been changed!
+
+ Here is an example of how to edit a code snippet successive
+ times. First we call the editor::
+
+ In [5]: edit
+ Editing... done. Executing edited code...
+ hello
+ Out[5]: "print 'hello'\\n"
+
+ Now we call it again with the previous output (stored in _)::
+
+ In [6]: edit _
+ Editing... done. Executing edited code...
+ hello world
+ Out[6]: "print 'hello world'\\n"
+
+ Now we call it with the output #8 (stored in _8, also as Out[8])::
+
+ In [7]: edit _8
+ Editing... done. Executing edited code...
+ hello again
+ Out[7]: "print 'hello again'\\n"
+
+
+ Changing the default editor hook:
+
+ If you wish to write your own editor hook, you can put it in a
+ configuration file which you load at startup time. The default hook
+ is defined in the IPython.core.hooks module, and you can use that as a
+ starting example for further modifications. That file also has
+ general instructions on how to set a new hook for use once you've
+ defined it."""
+ opts,args = self.parse_options(parameter_s,'prxn:')
+
+ try:
+ filename, lineno, is_temp = self._find_edit_target(self.shell,
+ args, opts, last_call)
+ except MacroToEdit as e:
+ self._edit_macro(args, e.args[0])
+ return
+ except InteractivelyDefined as e:
+ print("Editing In[%i]" % e.index)
+ args = str(e.index)
+ filename, lineno, is_temp = self._find_edit_target(self.shell,
+ args, opts, last_call)
+ if filename is None:
+ # nothing was found, warnings have already been issued,
+ # just give up.
+ return
+
+ if is_temp:
+ self._knowntemps.add(filename)
+ elif (filename in self._knowntemps):
+ is_temp = True
+
+
+ # do actual editing here
+ print('Editing...', end=' ')
+ sys.stdout.flush()
+ try:
+ # Quote filenames that may have spaces in them
+ if ' ' in filename:
+ filename = "'%s'" % filename
+ self.shell.hooks.editor(filename,lineno)
+ except TryNext:
+ warn('Could not open editor')
+ return
+
+ # XXX TODO: should this be generalized for all string vars?
+ # For now, this is special-cased to blocks created by cpaste
+ if args.strip() == 'pasted_block':
+ with open(filename, 'r') as f:
+ self.shell.user_ns['pasted_block'] = f.read()
+
+ if 'x' in opts: # -x prevents actual execution
+ print()
+ else:
+ print('done. Executing edited code...')
+ with preserve_keys(self.shell.user_ns, '__file__'):
+ if not is_temp:
+ self.shell.user_ns['__file__'] = filename
+ if 'r' in opts: # Untranslated IPython code
+ with open(filename, 'r') as f:
+ source = f.read()
+ self.shell.run_cell(source, store_history=False)
+ else:
+ self.shell.safe_execfile(filename, self.shell.user_ns,
+ self.shell.user_ns)
+
+ if is_temp:
+ try:
+ return open(filename).read()
+ except IOError as msg:
+ if msg.filename == filename:
+ warn('File not found. Did you forget to save?')
+ return
+ else:
+ self.shell.showtraceback()
diff --git a/contrib/python/ipython/py2/IPython/core/magics/config.py b/contrib/python/ipython/py2/IPython/core/magics/config.py
index f023cf9267..9505697791 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/config.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/config.py
@@ -1,159 +1,159 @@
-"""Implementation of configuration-related magic functions.
-"""
-from __future__ import print_function
+"""Implementation of configuration-related magic functions.
+"""
+from __future__ import print_function
from __future__ import absolute_import
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012 The IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Stdlib
-import re
-
-# Our own packages
-from IPython.core.error import UsageError
-from IPython.core.magic import Magics, magics_class, line_magic
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012 The IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Stdlib
+import re
+
+# Our own packages
+from IPython.core.error import UsageError
+from IPython.core.magic import Magics, magics_class, line_magic
from logging import error
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-
-reg = re.compile('^\w+\.\w+$')
-@magics_class
-class ConfigMagics(Magics):
-
- def __init__(self, shell):
- super(ConfigMagics, self).__init__(shell)
- self.configurables = []
-
- @line_magic
- def config(self, s):
- """configure IPython
-
- %config Class[.trait=value]
-
- This magic exposes most of the IPython config system. Any
- Configurable class should be able to be configured with the simple
- line::
-
- %config Class.trait=value
-
- Where `value` will be resolved in the user's namespace, if it is an
- expression or variable name.
-
- Examples
- --------
-
- To see what classes are available for config, pass no arguments::
-
- In [1]: %config
- Available objects for config:
- TerminalInteractiveShell
- HistoryManager
- PrefilterManager
- AliasManager
- IPCompleter
- DisplayFormatter
-
- To view what is configurable on a given class, just pass the class
- name::
-
- In [2]: %config IPCompleter
- IPCompleter options
- -----------------
- IPCompleter.omit__names=<Enum>
- Current: 2
- Choices: (0, 1, 2)
- Instruct the completer to omit private method names
- Specifically, when completing on ``object.<tab>``.
- When 2 [default]: all names that start with '_' will be excluded.
- When 1: all 'magic' names (``__foo__``) will be excluded.
- When 0: nothing will be excluded.
- IPCompleter.merge_completions=<CBool>
- Current: True
- Whether to merge completion results into a single list
- If False, only the completion results from the first non-empty
- completer will be returned.
- IPCompleter.limit_to__all__=<CBool>
- Current: False
- Instruct the completer to use __all__ for the completion
- Specifically, when completing on ``object.<tab>``.
- When True: only those names in obj.__all__ will be included.
- When False [default]: the __all__ attribute is ignored
- IPCompleter.greedy=<CBool>
- Current: False
- Activate greedy completion
- This will enable completion on elements of lists, results of
- function calls, etc., but can be unsafe because the code is
- actually evaluated on TAB.
-
- but the real use is in setting values::
-
- In [3]: %config IPCompleter.greedy = True
-
- and these values are read from the user_ns if they are variables::
-
- In [4]: feeling_greedy=False
-
- In [5]: %config IPCompleter.greedy = feeling_greedy
-
- """
- from traitlets.config.loader import Config
- # some IPython objects are Configurable, but do not yet have
- # any configurable traits. Exclude them from the effects of
- # this magic, as their presence is just noise:
- configurables = [ c for c in self.shell.configurables
- if c.__class__.class_traits(config=True) ]
- classnames = [ c.__class__.__name__ for c in configurables ]
-
- line = s.strip()
- if not line:
- # print available configurable names
- print("Available objects for config:")
- for name in classnames:
- print(" ", name)
- return
- elif line in classnames:
- # `%config TerminalInteractiveShell` will print trait info for
- # TerminalInteractiveShell
- c = configurables[classnames.index(line)]
- cls = c.__class__
- help = cls.class_get_help(c)
- # strip leading '--' from cl-args:
- help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
- print(help)
- return
- elif reg.match(line):
- cls, attr = line.split('.')
- return getattr(configurables[classnames.index(cls)],attr)
- elif '=' not in line:
- msg = "Invalid config statement: %r, "\
- "should be `Class.trait = value`."
-
- ll = line.lower()
- for classname in classnames:
- if ll == classname.lower():
- msg = msg + '\nDid you mean %s (note the case)?' % classname
- break
-
- raise UsageError( msg % line)
-
- # otherwise, assume we are setting configurables.
- # leave quotes on args when splitting, because we want
- # unquoted args to eval in user_ns
- cfg = Config()
- exec("cfg."+line, locals(), self.shell.user_ns)
-
- for configurable in configurables:
- try:
- configurable.update_config(cfg)
- except Exception as e:
- error(e)
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+
+reg = re.compile('^\w+\.\w+$')
+@magics_class
+class ConfigMagics(Magics):
+
+ def __init__(self, shell):
+ super(ConfigMagics, self).__init__(shell)
+ self.configurables = []
+
+ @line_magic
+ def config(self, s):
+ """configure IPython
+
+ %config Class[.trait=value]
+
+ This magic exposes most of the IPython config system. Any
+ Configurable class should be able to be configured with the simple
+ line::
+
+ %config Class.trait=value
+
+ Where `value` will be resolved in the user's namespace, if it is an
+ expression or variable name.
+
+ Examples
+ --------
+
+ To see what classes are available for config, pass no arguments::
+
+ In [1]: %config
+ Available objects for config:
+ TerminalInteractiveShell
+ HistoryManager
+ PrefilterManager
+ AliasManager
+ IPCompleter
+ DisplayFormatter
+
+ To view what is configurable on a given class, just pass the class
+ name::
+
+ In [2]: %config IPCompleter
+ IPCompleter options
+ -----------------
+ IPCompleter.omit__names=<Enum>
+ Current: 2
+ Choices: (0, 1, 2)
+ Instruct the completer to omit private method names
+ Specifically, when completing on ``object.<tab>``.
+ When 2 [default]: all names that start with '_' will be excluded.
+ When 1: all 'magic' names (``__foo__``) will be excluded.
+ When 0: nothing will be excluded.
+ IPCompleter.merge_completions=<CBool>
+ Current: True
+ Whether to merge completion results into a single list
+ If False, only the completion results from the first non-empty
+ completer will be returned.
+ IPCompleter.limit_to__all__=<CBool>
+ Current: False
+ Instruct the completer to use __all__ for the completion
+ Specifically, when completing on ``object.<tab>``.
+ When True: only those names in obj.__all__ will be included.
+ When False [default]: the __all__ attribute is ignored
+ IPCompleter.greedy=<CBool>
+ Current: False
+ Activate greedy completion
+ This will enable completion on elements of lists, results of
+ function calls, etc., but can be unsafe because the code is
+ actually evaluated on TAB.
+
+ but the real use is in setting values::
+
+ In [3]: %config IPCompleter.greedy = True
+
+ and these values are read from the user_ns if they are variables::
+
+ In [4]: feeling_greedy=False
+
+ In [5]: %config IPCompleter.greedy = feeling_greedy
+
+ """
+ from traitlets.config.loader import Config
+ # some IPython objects are Configurable, but do not yet have
+ # any configurable traits. Exclude them from the effects of
+ # this magic, as their presence is just noise:
+ configurables = [ c for c in self.shell.configurables
+ if c.__class__.class_traits(config=True) ]
+ classnames = [ c.__class__.__name__ for c in configurables ]
+
+ line = s.strip()
+ if not line:
+ # print available configurable names
+ print("Available objects for config:")
+ for name in classnames:
+ print(" ", name)
+ return
+ elif line in classnames:
+ # `%config TerminalInteractiveShell` will print trait info for
+ # TerminalInteractiveShell
+ c = configurables[classnames.index(line)]
+ cls = c.__class__
+ help = cls.class_get_help(c)
+ # strip leading '--' from cl-args:
+ help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
+ print(help)
+ return
+ elif reg.match(line):
+ cls, attr = line.split('.')
+ return getattr(configurables[classnames.index(cls)],attr)
+ elif '=' not in line:
+ msg = "Invalid config statement: %r, "\
+ "should be `Class.trait = value`."
+
+ ll = line.lower()
+ for classname in classnames:
+ if ll == classname.lower():
+ msg = msg + '\nDid you mean %s (note the case)?' % classname
+ break
+
+ raise UsageError( msg % line)
+
+ # otherwise, assume we are setting configurables.
+ # leave quotes on args when splitting, because we want
+ # unquoted args to eval in user_ns
+ cfg = Config()
+ exec("cfg."+line, locals(), self.shell.user_ns)
+
+ for configurable in configurables:
+ try:
+ configurable.update_config(cfg)
+ except Exception as e:
+ error(e)
diff --git a/contrib/python/ipython/py2/IPython/core/magics/display.py b/contrib/python/ipython/py2/IPython/core/magics/display.py
index 156a86b10a..c4a8f44d9a 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/display.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/display.py
@@ -1,36 +1,36 @@
-"""Simple magics for display formats"""
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012 The IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Our own packages
-from IPython.core.display import display, Javascript, Latex, SVG, HTML
-from IPython.core.magic import (
- Magics, magics_class, cell_magic
-)
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-
-
-@magics_class
-class DisplayMagics(Magics):
- """Magics for displaying various output types with literals
+"""Simple magics for display formats"""
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012 The IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Our own packages
+from IPython.core.display import display, Javascript, Latex, SVG, HTML
+from IPython.core.magic import (
+ Magics, magics_class, cell_magic
+)
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+
+
+@magics_class
+class DisplayMagics(Magics):
+ """Magics for displaying various output types with literals
Defines javascript/latex/svg/html cell magics for writing
- blocks in those languages, to be rendered in the frontend.
- """
+ blocks in those languages, to be rendered in the frontend.
+ """
- @cell_magic
+ @cell_magic
def js(self, line, cell):
"""Run the cell block of Javascript code
@@ -39,27 +39,27 @@ class DisplayMagics(Magics):
self.javascript(line, cell)
@cell_magic
- def javascript(self, line, cell):
- """Run the cell block of Javascript code"""
- display(Javascript(cell))
+ def javascript(self, line, cell):
+ """Run the cell block of Javascript code"""
+ display(Javascript(cell))
- @cell_magic
- def latex(self, line, cell):
- """Render the cell as a block of latex
+ @cell_magic
+ def latex(self, line, cell):
+ """Render the cell as a block of latex
- The subset of latex which is support depends on the implementation in
+ The subset of latex which is support depends on the implementation in
the client. In the Jupyter Notebook, this magic only renders the subset
of latex defined by MathJax
- [here](https://docs.mathjax.org/en/v2.5-latest/tex.html)."""
- display(Latex(cell))
-
- @cell_magic
- def svg(self, line, cell):
- """Render the cell as an SVG literal"""
- display(SVG(cell))
-
- @cell_magic
- def html(self, line, cell):
- """Render the cell as a block of HTML"""
- display(HTML(cell))
+ [here](https://docs.mathjax.org/en/v2.5-latest/tex.html)."""
+ display(Latex(cell))
+
+ @cell_magic
+ def svg(self, line, cell):
+ """Render the cell as an SVG literal"""
+ display(SVG(cell))
+
+ @cell_magic
+ def html(self, line, cell):
+ """Render the cell as a block of HTML"""
+ display(HTML(cell))
diff --git a/contrib/python/ipython/py2/IPython/core/magics/execution.py b/contrib/python/ipython/py2/IPython/core/magics/execution.py
index a10c3409bc..3734b0cdae 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/execution.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/execution.py
@@ -1,710 +1,710 @@
-# -*- coding: utf-8 -*-
-"""Implementation of execution-related magic functions."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
+# -*- coding: utf-8 -*-
+"""Implementation of execution-related magic functions."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
from __future__ import absolute_import
-
-import ast
-import bdb
-import gc
-import itertools
-import os
-import sys
-import time
-import timeit
-from pdb import Restart
-
-# cProfile was added in Python2.5
-try:
- import cProfile as profile
- import pstats
-except ImportError:
- # profile isn't bundled by default in Debian for license reasons
- try:
- import profile, pstats
- except ImportError:
- profile = pstats = None
-
+
+import ast
+import bdb
+import gc
+import itertools
+import os
+import sys
+import time
+import timeit
+from pdb import Restart
+
+# cProfile was added in Python2.5
+try:
+ import cProfile as profile
+ import pstats
+except ImportError:
+ # profile isn't bundled by default in Debian for license reasons
+ try:
+ import profile, pstats
+ except ImportError:
+ profile = pstats = None
+
from IPython.core import oinspect
-from IPython.core import magic_arguments
-from IPython.core import page
-from IPython.core.error import UsageError
-from IPython.core.macro import Macro
-from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
- line_cell_magic, on_off, needs_local_scope)
-from IPython.testing.skipdoctest import skip_doctest
-from IPython.utils import py3compat
-from IPython.utils.py3compat import builtin_mod, iteritems, PY3
-from IPython.utils.contexts import preserve_keys
-from IPython.utils.capture import capture_output
-from IPython.utils.ipstruct import Struct
-from IPython.utils.module_paths import find_mod
+from IPython.core import magic_arguments
+from IPython.core import page
+from IPython.core.error import UsageError
+from IPython.core.macro import Macro
+from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
+ line_cell_magic, on_off, needs_local_scope)
+from IPython.testing.skipdoctest import skip_doctest
+from IPython.utils import py3compat
+from IPython.utils.py3compat import builtin_mod, iteritems, PY3
+from IPython.utils.contexts import preserve_keys
+from IPython.utils.capture import capture_output
+from IPython.utils.ipstruct import Struct
+from IPython.utils.module_paths import find_mod
from IPython.utils.path import get_py_filename, shellglob
-from IPython.utils.timing import clock, clock2
+from IPython.utils.timing import clock, clock2
from warnings import warn
from logging import error
-
-if PY3:
- from io import StringIO
-else:
- from StringIO import StringIO
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-
-
-class TimeitResult(object):
- """
- Object returned by the timeit magic with info about the run.
-
+
+if PY3:
+ from io import StringIO
+else:
+ from StringIO import StringIO
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+
+
+class TimeitResult(object):
+ """
+ Object returned by the timeit magic with info about the run.
+
Contains the following attributes :
-
+
loops: (int) number of loops done per measurement
repeat: (int) number of times the measurement has been repeated
best: (float) best execution time / number
all_runs: (list of float) execution time of each run (in s)
- compile_time: (float) time of statement compilation (s)
-
- """
-
- def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
- self.loops = loops
- self.repeat = repeat
- self.best = best
- self.worst = worst
- self.all_runs = all_runs
- self.compile_time = compile_time
- self._precision = precision
-
- def _repr_pretty_(self, p , cycle):
- if self.loops == 1: # No s at "loops" if only one loop
- unic = u"%d loop, best of %d: %s per loop" % (self.loops, self.repeat,
- _format_time(self.best, self._precision))
- else:
- unic = u"%d loops, best of %d: %s per loop" % (self.loops, self.repeat,
- _format_time(self.best, self._precision))
- p.text(u'<TimeitResult : '+unic+u'>')
-
-
-class TimeitTemplateFiller(ast.NodeTransformer):
- """Fill in the AST template for timing execution.
-
- This is quite closely tied to the template definition, which is in
- :meth:`ExecutionMagics.timeit`.
- """
- def __init__(self, ast_setup, ast_stmt):
- self.ast_setup = ast_setup
- self.ast_stmt = ast_stmt
-
- def visit_FunctionDef(self, node):
- "Fill in the setup statement"
- self.generic_visit(node)
- if node.name == "inner":
- node.body[:1] = self.ast_setup.body
-
- return node
-
- def visit_For(self, node):
- "Fill in the statement to be timed"
- if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
- node.body = self.ast_stmt.body
- return node
-
-
-class Timer(timeit.Timer):
- """Timer class that explicitly uses self.inner
-
- which is an undocumented implementation detail of CPython,
- not shared by PyPy.
- """
- # Timer.timeit copied from CPython 3.4.2
- def timeit(self, number=timeit.default_number):
- """Time 'number' executions of the main statement.
-
- To be precise, this executes the setup statement once, and
- then returns the time it takes to execute the main statement
- a number of times, as a float measured in seconds. The
- argument is the number of times through the loop, defaulting
- to one million. The main statement, the setup statement and
- the timer function to be used are passed to the constructor.
- """
- it = itertools.repeat(None, number)
- gcold = gc.isenabled()
- gc.disable()
- try:
- timing = self.inner(it, self.timer)
- finally:
- if gcold:
- gc.enable()
- return timing
-
-
-@magics_class
-class ExecutionMagics(Magics):
- """Magics related to code execution, debugging, profiling, etc.
-
- """
-
- def __init__(self, shell):
- super(ExecutionMagics, self).__init__(shell)
- if profile is None:
- self.prun = self.profile_missing_notice
- # Default execution function used to actually run user code.
- self.default_runner = None
-
- def profile_missing_notice(self, *args, **kwargs):
- error("""\
-The profile module could not be found. It has been removed from the standard
-python packages because of its non-free license. To use profiling, install the
-python-profiler package from non-free.""")
-
- @skip_doctest
- @line_cell_magic
- def prun(self, parameter_s='', cell=None):
-
- """Run a statement through the python code profiler.
-
- Usage, in line mode:
- %prun [options] statement
-
- Usage, in cell mode:
- %%prun [options] [statement]
- code...
- code...
-
- In cell mode, the additional code lines are appended to the (possibly
- empty) statement in the first line. Cell mode allows you to easily
- profile multiline blocks without having to put them in a separate
- function.
-
- The given statement (which doesn't require quote marks) is run via the
- python profiler in a manner similar to the profile.run() function.
- Namespaces are internally managed to work correctly; profile.run
- cannot be used in IPython because it makes certain assumptions about
- namespaces which do not hold under IPython.
-
- Options:
-
- -l <limit>
- you can place restrictions on what or how much of the
- profile gets printed. The limit value can be:
-
- * A string: only information for function names containing this string
- is printed.
-
- * An integer: only these many lines are printed.
-
- * A float (between 0 and 1): this fraction of the report is printed
- (for example, use a limit of 0.4 to see the topmost 40% only).
-
- You can combine several limits with repeated use of the option. For
- example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
- information about class constructors.
-
- -r
- return the pstats.Stats object generated by the profiling. This
- object has all the information about the profile in it, and you can
- later use it for further analysis or in other functions.
-
- -s <key>
- sort profile by given key. You can provide more than one key
- by using the option several times: '-s key1 -s key2 -s key3...'. The
- default sorting key is 'time'.
-
- The following is copied verbatim from the profile documentation
- referenced below:
-
- When more than one key is provided, additional keys are used as
- secondary criteria when the there is equality in all keys selected
- before them.
-
- Abbreviations can be used for any key names, as long as the
- abbreviation is unambiguous. The following are the keys currently
- defined:
-
- ============ =====================
- Valid Arg Meaning
- ============ =====================
- "calls" call count
- "cumulative" cumulative time
- "file" file name
- "module" file name
- "pcalls" primitive call count
- "line" line number
- "name" function name
- "nfl" name/file/line
- "stdname" standard name
- "time" internal time
- ============ =====================
-
- Note that all sorts on statistics are in descending order (placing
- most time consuming items first), where as name, file, and line number
- searches are in ascending order (i.e., alphabetical). The subtle
- distinction between "nfl" and "stdname" is that the standard name is a
- sort of the name as printed, which means that the embedded line
- numbers get compared in an odd way. For example, lines 3, 20, and 40
- would (if the file names were the same) appear in the string order
- "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
- line numbers. In fact, sort_stats("nfl") is the same as
- sort_stats("name", "file", "line").
-
- -T <filename>
- save profile results as shown on screen to a text
- file. The profile is still shown on screen.
-
- -D <filename>
- save (via dump_stats) profile statistics to given
- filename. This data is in a format understood by the pstats module, and
- is generated by a call to the dump_stats() method of profile
- objects. The profile is still shown on screen.
-
- -q
- suppress output to the pager. Best used with -T and/or -D above.
-
- If you want to run complete programs under the profiler's control, use
- ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
- contains profiler specific options as described here.
-
- You can read the complete documentation for the profile module with::
-
- In [1]: import profile; profile.help()
- """
- opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
- list_all=True, posix=False)
- if cell is not None:
- arg_str += '\n' + cell
- arg_str = self.shell.input_splitter.transform_cell(arg_str)
- return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
-
- def _run_with_profiler(self, code, opts, namespace):
- """
- Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
-
- Parameters
- ----------
- code : str
- Code to be executed.
- opts : Struct
- Options parsed by `self.parse_options`.
- namespace : dict
- A dictionary for Python namespace (e.g., `self.shell.user_ns`).
-
- """
-
- # Fill default values for unspecified options:
- opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
-
- prof = profile.Profile()
- try:
- prof = prof.runctx(code, namespace, namespace)
- sys_exit = ''
- except SystemExit:
- sys_exit = """*** SystemExit exception caught in code being profiled."""
-
- stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
-
- lims = opts.l
- if lims:
- lims = [] # rebuild lims with ints/floats/strings
- for lim in opts.l:
- try:
- lims.append(int(lim))
- except ValueError:
- try:
- lims.append(float(lim))
- except ValueError:
- lims.append(lim)
-
- # Trap output.
- stdout_trap = StringIO()
- stats_stream = stats.stream
- try:
- stats.stream = stdout_trap
- stats.print_stats(*lims)
- finally:
- stats.stream = stats_stream
-
- output = stdout_trap.getvalue()
- output = output.rstrip()
-
- if 'q' not in opts:
- page.page(output)
- print(sys_exit, end=' ')
-
- dump_file = opts.D[0]
- text_file = opts.T[0]
- if dump_file:
- prof.dump_stats(dump_file)
- print('\n*** Profile stats marshalled to file',\
- repr(dump_file)+'.',sys_exit)
- if text_file:
- pfile = open(text_file,'w')
- pfile.write(output)
- pfile.close()
- print('\n*** Profile printout saved to text file',\
- repr(text_file)+'.',sys_exit)
-
- if 'r' in opts:
- return stats
- else:
- return None
-
- @line_magic
- def pdb(self, parameter_s=''):
- """Control the automatic calling of the pdb interactive debugger.
-
- Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
- argument it works as a toggle.
-
- When an exception is triggered, IPython can optionally call the
- interactive pdb debugger after the traceback printout. %pdb toggles
- this feature on and off.
-
- The initial state of this feature is set in your configuration
- file (the option is ``InteractiveShell.pdb``).
-
- If you want to just activate the debugger AFTER an exception has fired,
- without having to type '%pdb on' and rerunning your code, you can use
- the %debug magic."""
-
- par = parameter_s.strip().lower()
-
- if par:
- try:
- new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
- except KeyError:
- print ('Incorrect argument. Use on/1, off/0, '
- 'or nothing for a toggle.')
- return
- else:
- # toggle
- new_pdb = not self.shell.call_pdb
-
- # set on the shell
- self.shell.call_pdb = new_pdb
- print('Automatic pdb calling has been turned',on_off(new_pdb))
-
- @skip_doctest
- @magic_arguments.magic_arguments()
- @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
- help="""
- Set break point at LINE in FILE.
- """
- )
- @magic_arguments.argument('statement', nargs='*',
- help="""
- Code to run in debugger.
- You can omit this in cell magic mode.
- """
- )
- @line_cell_magic
- def debug(self, line='', cell=None):
- """Activate the interactive debugger.
-
- This magic command support two ways of activating debugger.
- One is to activate debugger before executing code. This way, you
- can set a break point, to step through the code from the point.
- You can use this mode by giving statements to execute and optionally
- a breakpoint.
-
- The other one is to activate debugger in post-mortem mode. You can
- activate this mode simply running %debug without any argument.
- If an exception has just occurred, this lets you inspect its stack
- frames interactively. Note that this will always work only on the last
- traceback that occurred, so you must call this quickly after an
- exception that you wish to inspect has fired, because if another one
- occurs, it clobbers the previous one.
-
- If you want IPython to automatically do this on every exception, see
- the %pdb magic for more details.
- """
- args = magic_arguments.parse_argstring(self.debug, line)
-
- if not (args.breakpoint or args.statement or cell):
- self._debug_post_mortem()
- else:
- code = "\n".join(args.statement)
- if cell:
- code += "\n" + cell
- self._debug_exec(code, args.breakpoint)
-
- def _debug_post_mortem(self):
- self.shell.debugger(force=True)
-
- def _debug_exec(self, code, breakpoint):
- if breakpoint:
+ compile_time: (float) time of statement compilation (s)
+
+ """
+
+ def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
+ self.loops = loops
+ self.repeat = repeat
+ self.best = best
+ self.worst = worst
+ self.all_runs = all_runs
+ self.compile_time = compile_time
+ self._precision = precision
+
+ def _repr_pretty_(self, p , cycle):
+ if self.loops == 1: # No s at "loops" if only one loop
+ unic = u"%d loop, best of %d: %s per loop" % (self.loops, self.repeat,
+ _format_time(self.best, self._precision))
+ else:
+ unic = u"%d loops, best of %d: %s per loop" % (self.loops, self.repeat,
+ _format_time(self.best, self._precision))
+ p.text(u'<TimeitResult : '+unic+u'>')
+
+
+class TimeitTemplateFiller(ast.NodeTransformer):
+ """Fill in the AST template for timing execution.
+
+ This is quite closely tied to the template definition, which is in
+ :meth:`ExecutionMagics.timeit`.
+ """
+ def __init__(self, ast_setup, ast_stmt):
+ self.ast_setup = ast_setup
+ self.ast_stmt = ast_stmt
+
+ def visit_FunctionDef(self, node):
+ "Fill in the setup statement"
+ self.generic_visit(node)
+ if node.name == "inner":
+ node.body[:1] = self.ast_setup.body
+
+ return node
+
+ def visit_For(self, node):
+ "Fill in the statement to be timed"
+ if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
+ node.body = self.ast_stmt.body
+ return node
+
+
+class Timer(timeit.Timer):
+ """Timer class that explicitly uses self.inner
+
+ which is an undocumented implementation detail of CPython,
+ not shared by PyPy.
+ """
+ # Timer.timeit copied from CPython 3.4.2
+ def timeit(self, number=timeit.default_number):
+ """Time 'number' executions of the main statement.
+
+ To be precise, this executes the setup statement once, and
+ then returns the time it takes to execute the main statement
+ a number of times, as a float measured in seconds. The
+ argument is the number of times through the loop, defaulting
+ to one million. The main statement, the setup statement and
+ the timer function to be used are passed to the constructor.
+ """
+ it = itertools.repeat(None, number)
+ gcold = gc.isenabled()
+ gc.disable()
+ try:
+ timing = self.inner(it, self.timer)
+ finally:
+ if gcold:
+ gc.enable()
+ return timing
+
+
+@magics_class
+class ExecutionMagics(Magics):
+ """Magics related to code execution, debugging, profiling, etc.
+
+ """
+
+ def __init__(self, shell):
+ super(ExecutionMagics, self).__init__(shell)
+ if profile is None:
+ self.prun = self.profile_missing_notice
+ # Default execution function used to actually run user code.
+ self.default_runner = None
+
+ def profile_missing_notice(self, *args, **kwargs):
+ error("""\
+The profile module could not be found. It has been removed from the standard
+python packages because of its non-free license. To use profiling, install the
+python-profiler package from non-free.""")
+
+ @skip_doctest
+ @line_cell_magic
+ def prun(self, parameter_s='', cell=None):
+
+ """Run a statement through the python code profiler.
+
+ Usage, in line mode:
+ %prun [options] statement
+
+ Usage, in cell mode:
+ %%prun [options] [statement]
+ code...
+ code...
+
+ In cell mode, the additional code lines are appended to the (possibly
+ empty) statement in the first line. Cell mode allows you to easily
+ profile multiline blocks without having to put them in a separate
+ function.
+
+ The given statement (which doesn't require quote marks) is run via the
+ python profiler in a manner similar to the profile.run() function.
+ Namespaces are internally managed to work correctly; profile.run
+ cannot be used in IPython because it makes certain assumptions about
+ namespaces which do not hold under IPython.
+
+ Options:
+
+ -l <limit>
+ you can place restrictions on what or how much of the
+ profile gets printed. The limit value can be:
+
+ * A string: only information for function names containing this string
+ is printed.
+
+ * An integer: only these many lines are printed.
+
+ * A float (between 0 and 1): this fraction of the report is printed
+ (for example, use a limit of 0.4 to see the topmost 40% only).
+
+ You can combine several limits with repeated use of the option. For
+ example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
+ information about class constructors.
+
+ -r
+ return the pstats.Stats object generated by the profiling. This
+ object has all the information about the profile in it, and you can
+ later use it for further analysis or in other functions.
+
+ -s <key>
+ sort profile by given key. You can provide more than one key
+ by using the option several times: '-s key1 -s key2 -s key3...'. The
+ default sorting key is 'time'.
+
+ The following is copied verbatim from the profile documentation
+ referenced below:
+
+ When more than one key is provided, additional keys are used as
+ secondary criteria when the there is equality in all keys selected
+ before them.
+
+ Abbreviations can be used for any key names, as long as the
+ abbreviation is unambiguous. The following are the keys currently
+ defined:
+
+ ============ =====================
+ Valid Arg Meaning
+ ============ =====================
+ "calls" call count
+ "cumulative" cumulative time
+ "file" file name
+ "module" file name
+ "pcalls" primitive call count
+ "line" line number
+ "name" function name
+ "nfl" name/file/line
+ "stdname" standard name
+ "time" internal time
+ ============ =====================
+
+ Note that all sorts on statistics are in descending order (placing
+ most time consuming items first), where as name, file, and line number
+ searches are in ascending order (i.e., alphabetical). The subtle
+ distinction between "nfl" and "stdname" is that the standard name is a
+ sort of the name as printed, which means that the embedded line
+ numbers get compared in an odd way. For example, lines 3, 20, and 40
+ would (if the file names were the same) appear in the string order
+ "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
+ line numbers. In fact, sort_stats("nfl") is the same as
+ sort_stats("name", "file", "line").
+
+ -T <filename>
+ save profile results as shown on screen to a text
+ file. The profile is still shown on screen.
+
+ -D <filename>
+ save (via dump_stats) profile statistics to given
+ filename. This data is in a format understood by the pstats module, and
+ is generated by a call to the dump_stats() method of profile
+ objects. The profile is still shown on screen.
+
+ -q
+ suppress output to the pager. Best used with -T and/or -D above.
+
+ If you want to run complete programs under the profiler's control, use
+ ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
+ contains profiler specific options as described here.
+
+ You can read the complete documentation for the profile module with::
+
+ In [1]: import profile; profile.help()
+ """
+ opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
+ list_all=True, posix=False)
+ if cell is not None:
+ arg_str += '\n' + cell
+ arg_str = self.shell.input_splitter.transform_cell(arg_str)
+ return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
+
+ def _run_with_profiler(self, code, opts, namespace):
+ """
+ Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
+
+ Parameters
+ ----------
+ code : str
+ Code to be executed.
+ opts : Struct
+ Options parsed by `self.parse_options`.
+ namespace : dict
+ A dictionary for Python namespace (e.g., `self.shell.user_ns`).
+
+ """
+
+ # Fill default values for unspecified options:
+ opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
+
+ prof = profile.Profile()
+ try:
+ prof = prof.runctx(code, namespace, namespace)
+ sys_exit = ''
+ except SystemExit:
+ sys_exit = """*** SystemExit exception caught in code being profiled."""
+
+ stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
+
+ lims = opts.l
+ if lims:
+ lims = [] # rebuild lims with ints/floats/strings
+ for lim in opts.l:
+ try:
+ lims.append(int(lim))
+ except ValueError:
+ try:
+ lims.append(float(lim))
+ except ValueError:
+ lims.append(lim)
+
+ # Trap output.
+ stdout_trap = StringIO()
+ stats_stream = stats.stream
+ try:
+ stats.stream = stdout_trap
+ stats.print_stats(*lims)
+ finally:
+ stats.stream = stats_stream
+
+ output = stdout_trap.getvalue()
+ output = output.rstrip()
+
+ if 'q' not in opts:
+ page.page(output)
+ print(sys_exit, end=' ')
+
+ dump_file = opts.D[0]
+ text_file = opts.T[0]
+ if dump_file:
+ prof.dump_stats(dump_file)
+ print('\n*** Profile stats marshalled to file',\
+ repr(dump_file)+'.',sys_exit)
+ if text_file:
+ pfile = open(text_file,'w')
+ pfile.write(output)
+ pfile.close()
+ print('\n*** Profile printout saved to text file',\
+ repr(text_file)+'.',sys_exit)
+
+ if 'r' in opts:
+ return stats
+ else:
+ return None
+
+ @line_magic
+ def pdb(self, parameter_s=''):
+ """Control the automatic calling of the pdb interactive debugger.
+
+ Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
+ argument it works as a toggle.
+
+ When an exception is triggered, IPython can optionally call the
+ interactive pdb debugger after the traceback printout. %pdb toggles
+ this feature on and off.
+
+ The initial state of this feature is set in your configuration
+ file (the option is ``InteractiveShell.pdb``).
+
+ If you want to just activate the debugger AFTER an exception has fired,
+ without having to type '%pdb on' and rerunning your code, you can use
+ the %debug magic."""
+
+ par = parameter_s.strip().lower()
+
+ if par:
+ try:
+ new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
+ except KeyError:
+ print ('Incorrect argument. Use on/1, off/0, '
+ 'or nothing for a toggle.')
+ return
+ else:
+ # toggle
+ new_pdb = not self.shell.call_pdb
+
+ # set on the shell
+ self.shell.call_pdb = new_pdb
+ print('Automatic pdb calling has been turned',on_off(new_pdb))
+
+ @skip_doctest
+ @magic_arguments.magic_arguments()
+ @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
+ help="""
+ Set break point at LINE in FILE.
+ """
+ )
+ @magic_arguments.argument('statement', nargs='*',
+ help="""
+ Code to run in debugger.
+ You can omit this in cell magic mode.
+ """
+ )
+ @line_cell_magic
+ def debug(self, line='', cell=None):
+ """Activate the interactive debugger.
+
+ This magic command support two ways of activating debugger.
+ One is to activate debugger before executing code. This way, you
+ can set a break point, to step through the code from the point.
+ You can use this mode by giving statements to execute and optionally
+ a breakpoint.
+
+ The other one is to activate debugger in post-mortem mode. You can
+ activate this mode simply running %debug without any argument.
+ If an exception has just occurred, this lets you inspect its stack
+ frames interactively. Note that this will always work only on the last
+ traceback that occurred, so you must call this quickly after an
+ exception that you wish to inspect has fired, because if another one
+ occurs, it clobbers the previous one.
+
+ If you want IPython to automatically do this on every exception, see
+ the %pdb magic for more details.
+ """
+ args = magic_arguments.parse_argstring(self.debug, line)
+
+ if not (args.breakpoint or args.statement or cell):
+ self._debug_post_mortem()
+ else:
+ code = "\n".join(args.statement)
+ if cell:
+ code += "\n" + cell
+ self._debug_exec(code, args.breakpoint)
+
+ def _debug_post_mortem(self):
+ self.shell.debugger(force=True)
+
+ def _debug_exec(self, code, breakpoint):
+ if breakpoint:
(filename, bp_line) = breakpoint.rsplit(':', 1)
- bp_line = int(bp_line)
- else:
- (filename, bp_line) = (None, None)
- self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
-
- @line_magic
- def tb(self, s):
- """Print the last traceback with the currently active exception mode.
-
- See %xmode for changing exception reporting modes."""
- self.shell.showtraceback()
-
- @skip_doctest
- @line_magic
- def run(self, parameter_s='', runner=None,
- file_finder=get_py_filename):
- """Run the named file inside IPython as a program.
-
- Usage::
-
- %run [-n -i -e -G]
- [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
- ( -m mod | file ) [args]
-
- Parameters after the filename are passed as command-line arguments to
- the program (put in sys.argv). Then, control returns to IPython's
- prompt.
-
- This is similar to running at a system prompt ``python file args``,
- but with the advantage of giving you IPython's tracebacks, and of
- loading all variables into your interactive namespace for further use
- (unless -p is used, see below).
-
- The file is executed in a namespace initially consisting only of
- ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
- sees its environment as if it were being run as a stand-alone program
- (except for sharing global objects such as previously imported
- modules). But after execution, the IPython interactive namespace gets
- updated with all variables defined in the program (except for __name__
- and sys.argv). This allows for very convenient loading of code for
- interactive work, while giving each program a 'clean sheet' to run in.
-
- Arguments are expanded using shell-like glob match. Patterns
- '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
- tilde '~' will be expanded into user's home directory. Unlike
- real shells, quotation does not suppress expansions. Use
- *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
- To completely disable these expansions, you can use -G flag.
-
- Options:
-
- -n
- __name__ is NOT set to '__main__', but to the running file's name
- without extension (as python does under import). This allows running
- scripts and reloading the definitions in them without calling code
- protected by an ``if __name__ == "__main__"`` clause.
-
- -i
- run the file in IPython's namespace instead of an empty one. This
- is useful if you are experimenting with code written in a text editor
- which depends on variables defined interactively.
-
- -e
- ignore sys.exit() calls or SystemExit exceptions in the script
- being run. This is particularly useful if IPython is being used to
- run unittests, which always exit with a sys.exit() call. In such
- cases you are interested in the output of the test results, not in
- seeing a traceback of the unittest module.
-
- -t
- print timing information at the end of the run. IPython will give
- you an estimated CPU time consumption for your script, which under
- Unix uses the resource module to avoid the wraparound problems of
- time.clock(). Under Unix, an estimate of time spent on system tasks
- is also given (for Windows platforms this is reported as 0.0).
-
- If -t is given, an additional ``-N<N>`` option can be given, where <N>
- must be an integer indicating how many times you want the script to
- run. The final timing report will include total and per run results.
-
- For example (testing the script uniq_stable.py)::
-
- In [1]: run -t uniq_stable
-
- IPython CPU timings (estimated):
- User : 0.19597 s.
- System: 0.0 s.
-
- In [2]: run -t -N5 uniq_stable
-
- IPython CPU timings (estimated):
- Total runs performed: 5
- Times : Total Per run
- User : 0.910862 s, 0.1821724 s.
- System: 0.0 s, 0.0 s.
-
- -d
- run your program under the control of pdb, the Python debugger.
- This allows you to execute your program step by step, watch variables,
- etc. Internally, what IPython does is similar to calling::
-
- pdb.run('execfile("YOURFILENAME")')
-
- with a breakpoint set on line 1 of your file. You can change the line
- number for this automatic breakpoint to be <N> by using the -bN option
- (where N must be an integer). For example::
-
- %run -d -b40 myscript
-
- will set the first breakpoint at line 40 in myscript.py. Note that
- the first breakpoint must be set on a line which actually does
- something (not a comment or docstring) for it to stop execution.
-
- Or you can specify a breakpoint in a different file::
-
- %run -d -b myotherfile.py:20 myscript
-
- When the pdb debugger starts, you will see a (Pdb) prompt. You must
- first enter 'c' (without quotes) to start execution up to the first
- breakpoint.
-
- Entering 'help' gives information about the use of the debugger. You
- can easily see pdb's full documentation with "import pdb;pdb.help()"
- at a prompt.
-
- -p
- run program under the control of the Python profiler module (which
- prints a detailed report of execution times, function calls, etc).
-
- You can pass other options after -p which affect the behavior of the
- profiler itself. See the docs for %prun for details.
-
- In this mode, the program's variables do NOT propagate back to the
- IPython interactive namespace (because they remain in the namespace
- where the profiler executes them).
-
- Internally this triggers a call to %prun, see its documentation for
- details on the options available specifically for profiling.
-
- There is one special usage for which the text above doesn't apply:
- if the filename ends with .ipy[nb], the file is run as ipython script,
- just as if the commands were written on IPython prompt.
-
- -m
- specify module name to load instead of script path. Similar to
- the -m option for the python interpreter. Use this option last if you
- want to combine with other %run options. Unlike the python interpreter
- only source modules are allowed no .pyc or .pyo files.
- For example::
-
- %run -m example
-
- will run the example module.
-
- -G
- disable shell-like glob expansion of arguments.
-
- """
-
- # get arguments and set sys.argv for program to be run.
- opts, arg_lst = self.parse_options(parameter_s,
- 'nidtN:b:pD:l:rs:T:em:G',
- mode='list', list_all=1)
- if "m" in opts:
- modulename = opts["m"][0]
- modpath = find_mod(modulename)
- if modpath is None:
- warn('%r is not a valid modulename on sys.path'%modulename)
- return
- arg_lst = [modpath] + arg_lst
- try:
- filename = file_finder(arg_lst[0])
- except IndexError:
- warn('you must provide at least a filename.')
- print('\n%run:\n', oinspect.getdoc(self.run))
- return
- except IOError as e:
- try:
- msg = str(e)
- except UnicodeError:
- msg = e.message
- error(msg)
- return
-
- if filename.lower().endswith(('.ipy', '.ipynb')):
- with preserve_keys(self.shell.user_ns, '__file__'):
- self.shell.user_ns['__file__'] = filename
- self.shell.safe_execfile_ipy(filename)
- return
-
- # Control the response to exit() calls made by the script being run
- exit_ignore = 'e' in opts
-
- # Make sure that the running script gets a proper sys.argv as if it
- # were run from a system shell.
- save_argv = sys.argv # save it for later restoring
-
- if 'G' in opts:
- args = arg_lst[1:]
- else:
- # tilde and glob expansion
- args = shellglob(map(os.path.expanduser, arg_lst[1:]))
-
- sys.argv = [filename] + args # put in the proper filename
- # protect sys.argv from potential unicode strings on Python 2:
- if not py3compat.PY3:
- sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
-
- if 'i' in opts:
- # Run in user's interactive namespace
- prog_ns = self.shell.user_ns
- __name__save = self.shell.user_ns['__name__']
- prog_ns['__name__'] = '__main__'
- main_mod = self.shell.user_module
-
- # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
- # set the __file__ global in the script's namespace
- # TK: Is this necessary in interactive mode?
- prog_ns['__file__'] = filename
- else:
- # Run in a fresh, empty namespace
- if 'n' in opts:
- name = os.path.splitext(os.path.basename(filename))[0]
- else:
- name = '__main__'
-
- # The shell MUST hold a reference to prog_ns so after %run
- # exits, the python deletion mechanism doesn't zero it out
- # (leaving dangling references). See interactiveshell for details
- main_mod = self.shell.new_main_mod(filename, name)
- prog_ns = main_mod.__dict__
-
- # pickle fix. See interactiveshell for an explanation. But we need to
- # make sure that, if we overwrite __main__, we replace it at the end
- main_mod_name = prog_ns['__name__']
-
- if main_mod_name == '__main__':
- restore_main = sys.modules['__main__']
- else:
- restore_main = False
-
- # This needs to be undone at the end to prevent holding references to
- # every single object ever created.
- sys.modules[main_mod_name] = main_mod
-
- if 'p' in opts or 'd' in opts:
- if 'm' in opts:
- code = 'run_module(modulename, prog_ns)'
- code_ns = {
- 'run_module': self.shell.safe_run_module,
- 'prog_ns': prog_ns,
- 'modulename': modulename,
- }
- else:
- if 'd' in opts:
- # allow exceptions to raise in debug mode
- code = 'execfile(filename, prog_ns, raise_exceptions=True)'
- else:
- code = 'execfile(filename, prog_ns)'
- code_ns = {
- 'execfile': self.shell.safe_execfile,
- 'prog_ns': prog_ns,
- 'filename': get_py_filename(filename),
- }
-
- try:
- stats = None
+ bp_line = int(bp_line)
+ else:
+ (filename, bp_line) = (None, None)
+ self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
+
+ @line_magic
+ def tb(self, s):
+ """Print the last traceback with the currently active exception mode.
+
+ See %xmode for changing exception reporting modes."""
+ self.shell.showtraceback()
+
+ @skip_doctest
+ @line_magic
+ def run(self, parameter_s='', runner=None,
+ file_finder=get_py_filename):
+ """Run the named file inside IPython as a program.
+
+ Usage::
+
+ %run [-n -i -e -G]
+ [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
+ ( -m mod | file ) [args]
+
+ Parameters after the filename are passed as command-line arguments to
+ the program (put in sys.argv). Then, control returns to IPython's
+ prompt.
+
+ This is similar to running at a system prompt ``python file args``,
+ but with the advantage of giving you IPython's tracebacks, and of
+ loading all variables into your interactive namespace for further use
+ (unless -p is used, see below).
+
+ The file is executed in a namespace initially consisting only of
+ ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
+ sees its environment as if it were being run as a stand-alone program
+ (except for sharing global objects such as previously imported
+ modules). But after execution, the IPython interactive namespace gets
+ updated with all variables defined in the program (except for __name__
+ and sys.argv). This allows for very convenient loading of code for
+ interactive work, while giving each program a 'clean sheet' to run in.
+
+ Arguments are expanded using shell-like glob match. Patterns
+ '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
+ tilde '~' will be expanded into user's home directory. Unlike
+ real shells, quotation does not suppress expansions. Use
+ *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
+ To completely disable these expansions, you can use -G flag.
+
+ Options:
+
+ -n
+ __name__ is NOT set to '__main__', but to the running file's name
+ without extension (as python does under import). This allows running
+ scripts and reloading the definitions in them without calling code
+ protected by an ``if __name__ == "__main__"`` clause.
+
+ -i
+ run the file in IPython's namespace instead of an empty one. This
+ is useful if you are experimenting with code written in a text editor
+ which depends on variables defined interactively.
+
+ -e
+ ignore sys.exit() calls or SystemExit exceptions in the script
+ being run. This is particularly useful if IPython is being used to
+ run unittests, which always exit with a sys.exit() call. In such
+ cases you are interested in the output of the test results, not in
+ seeing a traceback of the unittest module.
+
+ -t
+ print timing information at the end of the run. IPython will give
+ you an estimated CPU time consumption for your script, which under
+ Unix uses the resource module to avoid the wraparound problems of
+ time.clock(). Under Unix, an estimate of time spent on system tasks
+ is also given (for Windows platforms this is reported as 0.0).
+
+ If -t is given, an additional ``-N<N>`` option can be given, where <N>
+ must be an integer indicating how many times you want the script to
+ run. The final timing report will include total and per run results.
+
+ For example (testing the script uniq_stable.py)::
+
+ In [1]: run -t uniq_stable
+
+ IPython CPU timings (estimated):
+ User : 0.19597 s.
+ System: 0.0 s.
+
+ In [2]: run -t -N5 uniq_stable
+
+ IPython CPU timings (estimated):
+ Total runs performed: 5
+ Times : Total Per run
+ User : 0.910862 s, 0.1821724 s.
+ System: 0.0 s, 0.0 s.
+
+ -d
+ run your program under the control of pdb, the Python debugger.
+ This allows you to execute your program step by step, watch variables,
+ etc. Internally, what IPython does is similar to calling::
+
+ pdb.run('execfile("YOURFILENAME")')
+
+ with a breakpoint set on line 1 of your file. You can change the line
+ number for this automatic breakpoint to be <N> by using the -bN option
+ (where N must be an integer). For example::
+
+ %run -d -b40 myscript
+
+ will set the first breakpoint at line 40 in myscript.py. Note that
+ the first breakpoint must be set on a line which actually does
+ something (not a comment or docstring) for it to stop execution.
+
+ Or you can specify a breakpoint in a different file::
+
+ %run -d -b myotherfile.py:20 myscript
+
+ When the pdb debugger starts, you will see a (Pdb) prompt. You must
+ first enter 'c' (without quotes) to start execution up to the first
+ breakpoint.
+
+ Entering 'help' gives information about the use of the debugger. You
+ can easily see pdb's full documentation with "import pdb;pdb.help()"
+ at a prompt.
+
+ -p
+ run program under the control of the Python profiler module (which
+ prints a detailed report of execution times, function calls, etc).
+
+ You can pass other options after -p which affect the behavior of the
+ profiler itself. See the docs for %prun for details.
+
+ In this mode, the program's variables do NOT propagate back to the
+ IPython interactive namespace (because they remain in the namespace
+ where the profiler executes them).
+
+ Internally this triggers a call to %prun, see its documentation for
+ details on the options available specifically for profiling.
+
+ There is one special usage for which the text above doesn't apply:
+ if the filename ends with .ipy[nb], the file is run as ipython script,
+ just as if the commands were written on IPython prompt.
+
+ -m
+ specify module name to load instead of script path. Similar to
+ the -m option for the python interpreter. Use this option last if you
+ want to combine with other %run options. Unlike the python interpreter
+ only source modules are allowed no .pyc or .pyo files.
+ For example::
+
+ %run -m example
+
+ will run the example module.
+
+ -G
+ disable shell-like glob expansion of arguments.
+
+ """
+
+ # get arguments and set sys.argv for program to be run.
+ opts, arg_lst = self.parse_options(parameter_s,
+ 'nidtN:b:pD:l:rs:T:em:G',
+ mode='list', list_all=1)
+ if "m" in opts:
+ modulename = opts["m"][0]
+ modpath = find_mod(modulename)
+ if modpath is None:
+ warn('%r is not a valid modulename on sys.path'%modulename)
+ return
+ arg_lst = [modpath] + arg_lst
+ try:
+ filename = file_finder(arg_lst[0])
+ except IndexError:
+ warn('you must provide at least a filename.')
+ print('\n%run:\n', oinspect.getdoc(self.run))
+ return
+ except IOError as e:
+ try:
+ msg = str(e)
+ except UnicodeError:
+ msg = e.message
+ error(msg)
+ return
+
+ if filename.lower().endswith(('.ipy', '.ipynb')):
+ with preserve_keys(self.shell.user_ns, '__file__'):
+ self.shell.user_ns['__file__'] = filename
+ self.shell.safe_execfile_ipy(filename)
+ return
+
+ # Control the response to exit() calls made by the script being run
+ exit_ignore = 'e' in opts
+
+ # Make sure that the running script gets a proper sys.argv as if it
+ # were run from a system shell.
+ save_argv = sys.argv # save it for later restoring
+
+ if 'G' in opts:
+ args = arg_lst[1:]
+ else:
+ # tilde and glob expansion
+ args = shellglob(map(os.path.expanduser, arg_lst[1:]))
+
+ sys.argv = [filename] + args # put in the proper filename
+ # protect sys.argv from potential unicode strings on Python 2:
+ if not py3compat.PY3:
+ sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
+
+ if 'i' in opts:
+ # Run in user's interactive namespace
+ prog_ns = self.shell.user_ns
+ __name__save = self.shell.user_ns['__name__']
+ prog_ns['__name__'] = '__main__'
+ main_mod = self.shell.user_module
+
+ # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
+ # set the __file__ global in the script's namespace
+ # TK: Is this necessary in interactive mode?
+ prog_ns['__file__'] = filename
+ else:
+ # Run in a fresh, empty namespace
+ if 'n' in opts:
+ name = os.path.splitext(os.path.basename(filename))[0]
+ else:
+ name = '__main__'
+
+ # The shell MUST hold a reference to prog_ns so after %run
+ # exits, the python deletion mechanism doesn't zero it out
+ # (leaving dangling references). See interactiveshell for details
+ main_mod = self.shell.new_main_mod(filename, name)
+ prog_ns = main_mod.__dict__
+
+ # pickle fix. See interactiveshell for an explanation. But we need to
+ # make sure that, if we overwrite __main__, we replace it at the end
+ main_mod_name = prog_ns['__name__']
+
+ if main_mod_name == '__main__':
+ restore_main = sys.modules['__main__']
+ else:
+ restore_main = False
+
+ # This needs to be undone at the end to prevent holding references to
+ # every single object ever created.
+ sys.modules[main_mod_name] = main_mod
+
+ if 'p' in opts or 'd' in opts:
+ if 'm' in opts:
+ code = 'run_module(modulename, prog_ns)'
+ code_ns = {
+ 'run_module': self.shell.safe_run_module,
+ 'prog_ns': prog_ns,
+ 'modulename': modulename,
+ }
+ else:
+ if 'd' in opts:
+ # allow exceptions to raise in debug mode
+ code = 'execfile(filename, prog_ns, raise_exceptions=True)'
+ else:
+ code = 'execfile(filename, prog_ns)'
+ code_ns = {
+ 'execfile': self.shell.safe_execfile,
+ 'prog_ns': prog_ns,
+ 'filename': get_py_filename(filename),
+ }
+
+ try:
+ stats = None
if 'p' in opts:
stats = self._run_with_profiler(code, opts, code_ns)
else:
@@ -713,20 +713,20 @@ python-profiler package from non-free.""")
opts.get('b', ['1'])[0], filename)
self._run_with_debugger(
code, code_ns, filename, bp_line, bp_file)
- else:
+ else:
if 'm' in opts:
def run():
self.shell.safe_run_module(modulename, prog_ns)
- else:
+ else:
if runner is None:
runner = self.default_runner
if runner is None:
runner = self.shell.safe_execfile
-
+
def run():
runner(filename, prog_ns, prog_ns,
exit_ignore=exit_ignore)
-
+
if 't' in opts:
# timed execution
try:
@@ -740,67 +740,67 @@ python-profiler package from non-free.""")
else:
# regular execution
run()
-
+
if 'i' in opts:
self.shell.user_ns['__name__'] = __name__save
else:
# update IPython interactive namespace
-
+
# Some forms of read errors on the file may mean the
# __name__ key was never set; using pop we don't have to
# worry about a possible KeyError.
prog_ns.pop('__name__', None)
-
+
with preserve_keys(self.shell.user_ns, '__file__'):
self.shell.user_ns.update(prog_ns)
- finally:
- # It's a bit of a mystery why, but __builtins__ can change from
- # being a module to becoming a dict missing some key data after
- # %run. As best I can see, this is NOT something IPython is doing
- # at all, and similar problems have been reported before:
- # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
- # Since this seems to be done by the interpreter itself, the best
- # we can do is to at least restore __builtins__ for the user on
- # exit.
- self.shell.user_ns['__builtins__'] = builtin_mod
-
- # Ensure key global structures are restored
- sys.argv = save_argv
- if restore_main:
- sys.modules['__main__'] = restore_main
- else:
- # Remove from sys.modules the reference to main_mod we'd
- # added. Otherwise it will trap references to objects
- # contained therein.
- del sys.modules[main_mod_name]
-
- return stats
-
- def _run_with_debugger(self, code, code_ns, filename=None,
- bp_line=None, bp_file=None):
- """
- Run `code` in debugger with a break point.
-
- Parameters
- ----------
- code : str
- Code to execute.
- code_ns : dict
- A namespace in which `code` is executed.
- filename : str
- `code` is ran as if it is in `filename`.
- bp_line : int, optional
- Line number of the break point.
- bp_file : str, optional
- Path to the file in which break point is specified.
- `filename` is used if not given.
-
- Raises
- ------
- UsageError
- If the break point given by `bp_line` is not valid.
-
- """
+ finally:
+ # It's a bit of a mystery why, but __builtins__ can change from
+ # being a module to becoming a dict missing some key data after
+ # %run. As best I can see, this is NOT something IPython is doing
+ # at all, and similar problems have been reported before:
+ # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
+ # Since this seems to be done by the interpreter itself, the best
+ # we can do is to at least restore __builtins__ for the user on
+ # exit.
+ self.shell.user_ns['__builtins__'] = builtin_mod
+
+ # Ensure key global structures are restored
+ sys.argv = save_argv
+ if restore_main:
+ sys.modules['__main__'] = restore_main
+ else:
+ # Remove from sys.modules the reference to main_mod we'd
+ # added. Otherwise it will trap references to objects
+ # contained therein.
+ del sys.modules[main_mod_name]
+
+ return stats
+
+ def _run_with_debugger(self, code, code_ns, filename=None,
+ bp_line=None, bp_file=None):
+ """
+ Run `code` in debugger with a break point.
+
+ Parameters
+ ----------
+ code : str
+ Code to execute.
+ code_ns : dict
+ A namespace in which `code` is executed.
+ filename : str
+ `code` is ran as if it is in `filename`.
+ bp_line : int, optional
+ Line number of the break point.
+ bp_file : str, optional
+ Path to the file in which break point is specified.
+ `filename` is used if not given.
+
+ Raises
+ ------
+ UsageError
+ If the break point given by `bp_line` is not valid.
+
+ """
deb = self.shell.InteractiveTB.pdb
if not deb:
self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
@@ -811,208 +811,208 @@ python-profiler package from non-free.""")
if hasattr(deb, 'curframe'):
del deb.curframe
- # reset Breakpoint state, which is moronically kept
- # in a class
- bdb.Breakpoint.next = 1
- bdb.Breakpoint.bplist = {}
- bdb.Breakpoint.bpbynumber = [None]
+ # reset Breakpoint state, which is moronically kept
+ # in a class
+ bdb.Breakpoint.next = 1
+ bdb.Breakpoint.bplist = {}
+ bdb.Breakpoint.bpbynumber = [None]
deb.clear_all_breaks()
- if bp_line is not None:
- # Set an initial breakpoint to stop execution
- maxtries = 10
- bp_file = bp_file or filename
- checkline = deb.checkline(bp_file, bp_line)
- if not checkline:
- for bp in range(bp_line + 1, bp_line + maxtries + 1):
- if deb.checkline(bp_file, bp):
- break
- else:
- msg = ("\nI failed to find a valid line to set "
- "a breakpoint\n"
- "after trying up to line: %s.\n"
- "Please set a valid breakpoint manually "
- "with the -b option." % bp)
- raise UsageError(msg)
- # if we find a good linenumber, set the breakpoint
- deb.do_break('%s:%s' % (bp_file, bp_line))
-
- if filename:
- # Mimic Pdb._runscript(...)
- deb._wait_for_mainpyfile = True
- deb.mainpyfile = deb.canonic(filename)
-
- # Start file run
- print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
- try:
- if filename:
- # save filename so it can be used by methods on the deb object
- deb._exec_filename = filename
- while True:
- try:
- deb.run(code, code_ns)
- except Restart:
- print("Restarting")
- if filename:
- deb._wait_for_mainpyfile = True
- deb.mainpyfile = deb.canonic(filename)
- continue
- else:
- break
-
-
- except:
- etype, value, tb = sys.exc_info()
- # Skip three frames in the traceback: the %run one,
- # one inside bdb.py, and the command-line typed by the
- # user (run by exec in pdb itself).
- self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
-
- @staticmethod
- def _run_with_timing(run, nruns):
- """
- Run function `run` and print timing information.
-
- Parameters
- ----------
- run : callable
- Any callable object which takes no argument.
- nruns : int
- Number of times to execute `run`.
-
- """
- twall0 = time.time()
- if nruns == 1:
- t0 = clock2()
- run()
- t1 = clock2()
- t_usr = t1[0] - t0[0]
- t_sys = t1[1] - t0[1]
- print("\nIPython CPU timings (estimated):")
- print(" User : %10.2f s." % t_usr)
- print(" System : %10.2f s." % t_sys)
- else:
- runs = range(nruns)
- t0 = clock2()
- for nr in runs:
- run()
- t1 = clock2()
- t_usr = t1[0] - t0[0]
- t_sys = t1[1] - t0[1]
- print("\nIPython CPU timings (estimated):")
- print("Total runs performed:", nruns)
- print(" Times : %10s %10s" % ('Total', 'Per run'))
- print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
- print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
- twall1 = time.time()
- print("Wall time: %10.2f s." % (twall1 - twall0))
-
- @skip_doctest
- @line_cell_magic
- def timeit(self, line='', cell=None):
- """Time execution of a Python statement or expression
-
- Usage, in line mode:
- %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
- or in cell mode:
- %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
- code
- code...
-
- Time execution of a Python statement or expression using the timeit
- module. This function can be used both as a line and cell magic:
-
- - In line mode you can time a single-line statement (though multiple
- ones can be chained with using semicolons).
-
- - In cell mode, the statement in the first line is used as setup code
- (executed but not timed) and the body of the cell is timed. The cell
- body has access to any variables created in the setup code.
-
- Options:
- -n<N>: execute the given statement <N> times in a loop. If this value
- is not given, a fitting value is chosen.
-
- -r<R>: repeat the loop iteration <R> times and take the best result.
- Default: 3
-
- -t: use time.time to measure the time, which is the default on Unix.
- This function measures wall time.
-
- -c: use time.clock to measure the time, which is the default on
- Windows and measures wall time. On Unix, resource.getrusage is used
- instead and returns the CPU user time.
-
- -p<P>: use a precision of <P> digits to display the timing result.
- Default: 3
-
- -q: Quiet, do not print result.
-
- -o: return a TimeitResult that can be stored in a variable to inspect
- the result in more details.
-
-
- Examples
- --------
- ::
-
- In [1]: %timeit pass
- 10000000 loops, best of 3: 53.3 ns per loop
-
- In [2]: u = None
-
- In [3]: %timeit u is None
- 10000000 loops, best of 3: 184 ns per loop
-
- In [4]: %timeit -r 4 u == None
- 1000000 loops, best of 4: 242 ns per loop
-
- In [5]: import time
-
- In [6]: %timeit -n1 time.sleep(2)
- 1 loop, best of 3: 2 s per loop
-
-
- The times reported by %timeit will be slightly higher than those
- reported by the timeit.py script when variables are accessed. This is
- due to the fact that %timeit executes the statement in the namespace
- of the shell, compared with timeit.py, which uses a single setup
- statement to import function or create variables. Generally, the bias
- does not matter as long as results from timeit.py are not mixed with
- those from %timeit."""
-
- opts, stmt = self.parse_options(line,'n:r:tcp:qo',
- posix=False, strict=False)
- if stmt == "" and cell is None:
- return
-
- timefunc = timeit.default_timer
- number = int(getattr(opts, "n", 0))
- repeat = int(getattr(opts, "r", timeit.default_repeat))
- precision = int(getattr(opts, "p", 3))
- quiet = 'q' in opts
- return_result = 'o' in opts
- if hasattr(opts, "t"):
- timefunc = time.time
- if hasattr(opts, "c"):
- timefunc = clock
-
- timer = Timer(timer=timefunc)
- # this code has tight coupling to the inner workings of timeit.Timer,
- # but is there a better way to achieve that the code stmt has access
- # to the shell namespace?
- transform = self.shell.input_splitter.transform_cell
-
- if cell is None:
- # called as line magic
- ast_setup = self.shell.compile.ast_parse("pass")
- ast_stmt = self.shell.compile.ast_parse(transform(stmt))
- else:
- ast_setup = self.shell.compile.ast_parse(transform(stmt))
- ast_stmt = self.shell.compile.ast_parse(transform(cell))
-
- ast_setup = self.shell.transform_ast(ast_setup)
- ast_stmt = self.shell.transform_ast(ast_stmt)
-
+ if bp_line is not None:
+ # Set an initial breakpoint to stop execution
+ maxtries = 10
+ bp_file = bp_file or filename
+ checkline = deb.checkline(bp_file, bp_line)
+ if not checkline:
+ for bp in range(bp_line + 1, bp_line + maxtries + 1):
+ if deb.checkline(bp_file, bp):
+ break
+ else:
+ msg = ("\nI failed to find a valid line to set "
+ "a breakpoint\n"
+ "after trying up to line: %s.\n"
+ "Please set a valid breakpoint manually "
+ "with the -b option." % bp)
+ raise UsageError(msg)
+ # if we find a good linenumber, set the breakpoint
+ deb.do_break('%s:%s' % (bp_file, bp_line))
+
+ if filename:
+ # Mimic Pdb._runscript(...)
+ deb._wait_for_mainpyfile = True
+ deb.mainpyfile = deb.canonic(filename)
+
+ # Start file run
+ print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
+ try:
+ if filename:
+ # save filename so it can be used by methods on the deb object
+ deb._exec_filename = filename
+ while True:
+ try:
+ deb.run(code, code_ns)
+ except Restart:
+ print("Restarting")
+ if filename:
+ deb._wait_for_mainpyfile = True
+ deb.mainpyfile = deb.canonic(filename)
+ continue
+ else:
+ break
+
+
+ except:
+ etype, value, tb = sys.exc_info()
+ # Skip three frames in the traceback: the %run one,
+ # one inside bdb.py, and the command-line typed by the
+ # user (run by exec in pdb itself).
+ self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
+
+ @staticmethod
+ def _run_with_timing(run, nruns):
+ """
+ Run function `run` and print timing information.
+
+ Parameters
+ ----------
+ run : callable
+ Any callable object which takes no argument.
+ nruns : int
+ Number of times to execute `run`.
+
+ """
+ twall0 = time.time()
+ if nruns == 1:
+ t0 = clock2()
+ run()
+ t1 = clock2()
+ t_usr = t1[0] - t0[0]
+ t_sys = t1[1] - t0[1]
+ print("\nIPython CPU timings (estimated):")
+ print(" User : %10.2f s." % t_usr)
+ print(" System : %10.2f s." % t_sys)
+ else:
+ runs = range(nruns)
+ t0 = clock2()
+ for nr in runs:
+ run()
+ t1 = clock2()
+ t_usr = t1[0] - t0[0]
+ t_sys = t1[1] - t0[1]
+ print("\nIPython CPU timings (estimated):")
+ print("Total runs performed:", nruns)
+ print(" Times : %10s %10s" % ('Total', 'Per run'))
+ print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
+ print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
+ twall1 = time.time()
+ print("Wall time: %10.2f s." % (twall1 - twall0))
+
+ @skip_doctest
+ @line_cell_magic
+ def timeit(self, line='', cell=None):
+ """Time execution of a Python statement or expression
+
+ Usage, in line mode:
+ %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
+ or in cell mode:
+ %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
+ code
+ code...
+
+ Time execution of a Python statement or expression using the timeit
+ module. This function can be used both as a line and cell magic:
+
+ - In line mode you can time a single-line statement (though multiple
+ ones can be chained with using semicolons).
+
+ - In cell mode, the statement in the first line is used as setup code
+ (executed but not timed) and the body of the cell is timed. The cell
+ body has access to any variables created in the setup code.
+
+ Options:
+ -n<N>: execute the given statement <N> times in a loop. If this value
+ is not given, a fitting value is chosen.
+
+ -r<R>: repeat the loop iteration <R> times and take the best result.
+ Default: 3
+
+ -t: use time.time to measure the time, which is the default on Unix.
+ This function measures wall time.
+
+ -c: use time.clock to measure the time, which is the default on
+ Windows and measures wall time. On Unix, resource.getrusage is used
+ instead and returns the CPU user time.
+
+ -p<P>: use a precision of <P> digits to display the timing result.
+ Default: 3
+
+ -q: Quiet, do not print result.
+
+ -o: return a TimeitResult that can be stored in a variable to inspect
+ the result in more details.
+
+
+ Examples
+ --------
+ ::
+
+ In [1]: %timeit pass
+ 10000000 loops, best of 3: 53.3 ns per loop
+
+ In [2]: u = None
+
+ In [3]: %timeit u is None
+ 10000000 loops, best of 3: 184 ns per loop
+
+ In [4]: %timeit -r 4 u == None
+ 1000000 loops, best of 4: 242 ns per loop
+
+ In [5]: import time
+
+ In [6]: %timeit -n1 time.sleep(2)
+ 1 loop, best of 3: 2 s per loop
+
+
+ The times reported by %timeit will be slightly higher than those
+ reported by the timeit.py script when variables are accessed. This is
+ due to the fact that %timeit executes the statement in the namespace
+ of the shell, compared with timeit.py, which uses a single setup
+ statement to import function or create variables. Generally, the bias
+ does not matter as long as results from timeit.py are not mixed with
+ those from %timeit."""
+
+ opts, stmt = self.parse_options(line,'n:r:tcp:qo',
+ posix=False, strict=False)
+ if stmt == "" and cell is None:
+ return
+
+ timefunc = timeit.default_timer
+ number = int(getattr(opts, "n", 0))
+ repeat = int(getattr(opts, "r", timeit.default_repeat))
+ precision = int(getattr(opts, "p", 3))
+ quiet = 'q' in opts
+ return_result = 'o' in opts
+ if hasattr(opts, "t"):
+ timefunc = time.time
+ if hasattr(opts, "c"):
+ timefunc = clock
+
+ timer = Timer(timer=timefunc)
+ # this code has tight coupling to the inner workings of timeit.Timer,
+ # but is there a better way to achieve that the code stmt has access
+ # to the shell namespace?
+ transform = self.shell.input_splitter.transform_cell
+
+ if cell is None:
+ # called as line magic
+ ast_setup = self.shell.compile.ast_parse("pass")
+ ast_stmt = self.shell.compile.ast_parse(transform(stmt))
+ else:
+ ast_setup = self.shell.compile.ast_parse(transform(stmt))
+ ast_stmt = self.shell.compile.ast_parse(transform(cell))
+
+ ast_setup = self.shell.transform_ast(ast_setup)
+ ast_stmt = self.shell.transform_ast(ast_stmt)
+
# Check that these compile to valid Python code *outside* the timer func
# Invalid code may become valid when put inside the function & loop,
# which messes up error messages.
@@ -1020,359 +1020,359 @@ python-profiler package from non-free.""")
self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec")
self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec")
- # This codestring is taken from timeit.template - we fill it in as an
- # AST, so that we can apply our AST transformations to the user code
- # without affecting the timing code.
- timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
- ' setup\n'
- ' _t0 = _timer()\n'
- ' for _i in _it:\n'
- ' stmt\n'
- ' _t1 = _timer()\n'
- ' return _t1 - _t0\n')
-
- timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
- timeit_ast = ast.fix_missing_locations(timeit_ast)
-
- # Track compilation time so it can be reported if too long
- # Minimum time above which compilation time will be reported
- tc_min = 0.1
-
- t0 = clock()
- code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
- tc = clock()-t0
-
- ns = {}
- exec(code, self.shell.user_ns, ns)
- timer.inner = ns["inner"]
-
- # This is used to check if there is a huge difference between the
- # best and worst timings.
- # Issue: https://github.com/ipython/ipython/issues/6471
- worst_tuning = 0
- if number == 0:
- # determine number so that 0.2 <= total time < 2.0
- number = 1
- for _ in range(1, 10):
- time_number = timer.timeit(number)
- worst_tuning = max(worst_tuning, time_number / number)
- if time_number >= 0.2:
- break
- number *= 10
- all_runs = timer.repeat(repeat, number)
- best = min(all_runs) / number
-
- worst = max(all_runs) / number
- if worst_tuning:
- worst = max(worst, worst_tuning)
-
- if not quiet :
- # Check best timing is greater than zero to avoid a
- # ZeroDivisionError.
- # In cases where the slowest timing is lesser than a micosecond
- # we assume that it does not really matter if the fastest
- # timing is 4 times faster than the slowest timing or not.
- if worst > 4 * best and best > 0 and worst > 1e-6:
- print("The slowest run took %0.2f times longer than the "
- "fastest. This could mean that an intermediate result "
- "is being cached." % (worst / best))
- if number == 1: # No s at "loops" if only one loop
- print(u"%d loop, best of %d: %s per loop" % (number, repeat,
- _format_time(best, precision)))
- else:
- print(u"%d loops, best of %d: %s per loop" % (number, repeat,
- _format_time(best, precision)))
- if tc > tc_min:
- print("Compiler time: %.2f s" % tc)
- if return_result:
- return TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
-
- @skip_doctest
- @needs_local_scope
- @line_cell_magic
- def time(self,line='', cell=None, local_ns=None):
- """Time execution of a Python statement or expression.
-
- The CPU and wall clock times are printed, and the value of the
- expression (if any) is returned. Note that under Win32, system time
- is always reported as 0, since it can not be measured.
-
- This function can be used both as a line and cell magic:
-
- - In line mode you can time a single-line statement (though multiple
- ones can be chained with using semicolons).
-
- - In cell mode, you can time the cell body (a directly
- following statement raises an error).
-
- This function provides very basic timing functionality. Use the timeit
- magic for more control over the measurement.
-
- Examples
- --------
- ::
-
- In [1]: %time 2**128
- CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
- Wall time: 0.00
- Out[1]: 340282366920938463463374607431768211456L
-
- In [2]: n = 1000000
-
- In [3]: %time sum(range(n))
- CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
- Wall time: 1.37
- Out[3]: 499999500000L
-
- In [4]: %time print 'hello world'
- hello world
- CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
- Wall time: 0.00
-
- Note that the time needed by Python to compile the given expression
- will be reported if it is more than 0.1s. In this example, the
- actual exponentiation is done by Python at compilation time, so while
- the expression can take a noticeable amount of time to compute, that
- time is purely due to the compilation:
-
- In [5]: %time 3**9999;
- CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
- Wall time: 0.00 s
-
- In [6]: %time 3**999999;
- CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
- Wall time: 0.00 s
- Compiler : 0.78 s
- """
-
- # fail immediately if the given expression can't be compiled
-
- if line and cell:
- raise UsageError("Can't use statement directly after '%%time'!")
-
- if cell:
- expr = self.shell.input_transformer_manager.transform_cell(cell)
- else:
- expr = self.shell.input_transformer_manager.transform_cell(line)
-
- # Minimum time above which parse time will be reported
- tp_min = 0.1
-
- t0 = clock()
- expr_ast = self.shell.compile.ast_parse(expr)
- tp = clock()-t0
-
- # Apply AST transformations
- expr_ast = self.shell.transform_ast(expr_ast)
-
- # Minimum time above which compilation time will be reported
- tc_min = 0.1
-
- if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
- mode = 'eval'
- source = '<timed eval>'
- expr_ast = ast.Expression(expr_ast.body[0].value)
- else:
- mode = 'exec'
- source = '<timed exec>'
- t0 = clock()
- code = self.shell.compile(expr_ast, source, mode)
- tc = clock()-t0
-
- # skew measurement as little as possible
- glob = self.shell.user_ns
- wtime = time.time
- # time execution
- wall_st = wtime()
- if mode=='eval':
- st = clock2()
- out = eval(code, glob, local_ns)
- end = clock2()
- else:
- st = clock2()
- exec(code, glob, local_ns)
- end = clock2()
- out = None
- wall_end = wtime()
- # Compute actual times and report
- wall_time = wall_end-wall_st
- cpu_user = end[0]-st[0]
- cpu_sys = end[1]-st[1]
- cpu_tot = cpu_user+cpu_sys
- # On windows cpu_sys is always zero, so no new information to the next print
- if sys.platform != 'win32':
- print("CPU times: user %s, sys: %s, total: %s" % \
- (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
- print("Wall time: %s" % _format_time(wall_time))
- if tc > tc_min:
- print("Compiler : %s" % _format_time(tc))
- if tp > tp_min:
- print("Parser : %s" % _format_time(tp))
- return out
-
- @skip_doctest
- @line_magic
- def macro(self, parameter_s=''):
- """Define a macro for future re-execution. It accepts ranges of history,
- filenames or string objects.
-
- Usage:\\
- %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
-
- Options:
-
- -r: use 'raw' input. By default, the 'processed' history is used,
- so that magics are loaded in their transformed version to valid
- Python. If this option is given, the raw input as typed at the
- command line is used instead.
-
- -q: quiet macro definition. By default, a tag line is printed
- to indicate the macro has been created, and then the contents of
- the macro are printed. If this option is given, then no printout
- is produced once the macro is created.
-
- This will define a global variable called `name` which is a string
- made of joining the slices and lines you specify (n1,n2,... numbers
- above) from your input history into a single string. This variable
- acts like an automatic function which re-executes those lines as if
- you had typed them. You just type 'name' at the prompt and the code
- executes.
-
- The syntax for indicating input ranges is described in %history.
-
- Note: as a 'hidden' feature, you can also use traditional python slice
- notation, where N:M means numbers N through M-1.
-
- For example, if your history contains (print using %hist -n )::
-
- 44: x=1
- 45: y=3
- 46: z=x+y
- 47: print x
- 48: a=5
- 49: print 'x',x,'y',y
-
- you can create a macro with lines 44 through 47 (included) and line 49
- called my_macro with::
-
- In [55]: %macro my_macro 44-47 49
-
- Now, typing `my_macro` (without quotes) will re-execute all this code
- in one pass.
-
- You don't need to give the line-numbers in order, and any given line
- number can appear multiple times. You can assemble macros with any
- lines from your input history in any order.
-
- The macro is a simple object which holds its value in an attribute,
- but IPython's display system checks for macros and executes them as
- code instead of printing them when you type their name.
-
- You can view a macro's contents by explicitly printing it with::
-
- print macro_name
-
- """
- opts,args = self.parse_options(parameter_s,'rq',mode='list')
- if not args: # List existing macros
- return sorted(k for k,v in iteritems(self.shell.user_ns) if\
- isinstance(v, Macro))
- if len(args) == 1:
- raise UsageError(
- "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
- name, codefrom = args[0], " ".join(args[1:])
-
- #print 'rng',ranges # dbg
- try:
- lines = self.shell.find_user_code(codefrom, 'r' in opts)
- except (ValueError, TypeError) as e:
- print(e.args[0])
- return
- macro = Macro(lines)
- self.shell.define_macro(name, macro)
- if not ( 'q' in opts) :
- print('Macro `%s` created. To execute, type its name (without quotes).' % name)
- print('=== Macro contents: ===')
- print(macro, end=' ')
-
- @magic_arguments.magic_arguments()
- @magic_arguments.argument('output', type=str, default='', nargs='?',
- help="""The name of the variable in which to store output.
- This is a utils.io.CapturedIO object with stdout/err attributes
- for the text of the captured output.
-
- CapturedOutput also has a show() method for displaying the output,
- and __call__ as well, so you can use that to quickly display the
- output.
-
- If unspecified, captured output is discarded.
- """
- )
- @magic_arguments.argument('--no-stderr', action="store_true",
- help="""Don't capture stderr."""
- )
- @magic_arguments.argument('--no-stdout', action="store_true",
- help="""Don't capture stdout."""
- )
- @magic_arguments.argument('--no-display', action="store_true",
- help="""Don't capture IPython's rich display."""
- )
- @cell_magic
- def capture(self, line, cell):
- """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
- args = magic_arguments.parse_argstring(self.capture, line)
- out = not args.no_stdout
- err = not args.no_stderr
- disp = not args.no_display
- with capture_output(out, err, disp) as io:
- self.shell.run_cell(cell)
- if args.output:
- self.shell.user_ns[args.output] = io
-
-def parse_breakpoint(text, current_file):
- '''Returns (file, line) for file:line and (current_file, line) for line'''
- colon = text.find(':')
- if colon == -1:
- return current_file, int(text)
- else:
- return text[:colon], int(text[colon+1:])
-
-def _format_time(timespan, precision=3):
- """Formats the timespan in a human readable form"""
- import math
-
- if timespan >= 60.0:
- # we have more than a minute, format that in a human readable form
- # Idea from http://snipplr.com/view/5713/
- parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
- time = []
- leftover = timespan
- for suffix, length in parts:
- value = int(leftover / length)
- if value > 0:
- leftover = leftover % length
- time.append(u'%s%s' % (str(value), suffix))
- if leftover < 1:
- break
- return " ".join(time)
-
-
- # Unfortunately the unicode 'micro' symbol can cause problems in
- # certain terminals.
- # See bug: https://bugs.launchpad.net/ipython/+bug/348466
- # Try to prevent crashes by being more secure than it needs to
- # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
- units = [u"s", u"ms",u'us',"ns"] # the save value
- if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
- try:
- u'\xb5'.encode(sys.stdout.encoding)
- units = [u"s", u"ms",u'\xb5s',"ns"]
- except:
- pass
- scaling = [1, 1e3, 1e6, 1e9]
-
- if timespan > 0.0:
- order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
- else:
- order = 3
- return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
+ # This codestring is taken from timeit.template - we fill it in as an
+ # AST, so that we can apply our AST transformations to the user code
+ # without affecting the timing code.
+ timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
+ ' setup\n'
+ ' _t0 = _timer()\n'
+ ' for _i in _it:\n'
+ ' stmt\n'
+ ' _t1 = _timer()\n'
+ ' return _t1 - _t0\n')
+
+ timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
+ timeit_ast = ast.fix_missing_locations(timeit_ast)
+
+ # Track compilation time so it can be reported if too long
+ # Minimum time above which compilation time will be reported
+ tc_min = 0.1
+
+ t0 = clock()
+ code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
+ tc = clock()-t0
+
+ ns = {}
+ exec(code, self.shell.user_ns, ns)
+ timer.inner = ns["inner"]
+
+ # This is used to check if there is a huge difference between the
+ # best and worst timings.
+ # Issue: https://github.com/ipython/ipython/issues/6471
+ worst_tuning = 0
+ if number == 0:
+ # determine number so that 0.2 <= total time < 2.0
+ number = 1
+ for _ in range(1, 10):
+ time_number = timer.timeit(number)
+ worst_tuning = max(worst_tuning, time_number / number)
+ if time_number >= 0.2:
+ break
+ number *= 10
+ all_runs = timer.repeat(repeat, number)
+ best = min(all_runs) / number
+
+ worst = max(all_runs) / number
+ if worst_tuning:
+ worst = max(worst, worst_tuning)
+
+ if not quiet :
+ # Check best timing is greater than zero to avoid a
+ # ZeroDivisionError.
+ # In cases where the slowest timing is lesser than a micosecond
+ # we assume that it does not really matter if the fastest
+ # timing is 4 times faster than the slowest timing or not.
+ if worst > 4 * best and best > 0 and worst > 1e-6:
+ print("The slowest run took %0.2f times longer than the "
+ "fastest. This could mean that an intermediate result "
+ "is being cached." % (worst / best))
+ if number == 1: # No s at "loops" if only one loop
+ print(u"%d loop, best of %d: %s per loop" % (number, repeat,
+ _format_time(best, precision)))
+ else:
+ print(u"%d loops, best of %d: %s per loop" % (number, repeat,
+ _format_time(best, precision)))
+ if tc > tc_min:
+ print("Compiler time: %.2f s" % tc)
+ if return_result:
+ return TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
+
+ @skip_doctest
+ @needs_local_scope
+ @line_cell_magic
+ def time(self,line='', cell=None, local_ns=None):
+ """Time execution of a Python statement or expression.
+
+ The CPU and wall clock times are printed, and the value of the
+ expression (if any) is returned. Note that under Win32, system time
+ is always reported as 0, since it can not be measured.
+
+ This function can be used both as a line and cell magic:
+
+ - In line mode you can time a single-line statement (though multiple
+ ones can be chained with using semicolons).
+
+ - In cell mode, you can time the cell body (a directly
+ following statement raises an error).
+
+ This function provides very basic timing functionality. Use the timeit
+ magic for more control over the measurement.
+
+ Examples
+ --------
+ ::
+
+ In [1]: %time 2**128
+ CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
+ Wall time: 0.00
+ Out[1]: 340282366920938463463374607431768211456L
+
+ In [2]: n = 1000000
+
+ In [3]: %time sum(range(n))
+ CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
+ Wall time: 1.37
+ Out[3]: 499999500000L
+
+ In [4]: %time print 'hello world'
+ hello world
+ CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
+ Wall time: 0.00
+
+ Note that the time needed by Python to compile the given expression
+ will be reported if it is more than 0.1s. In this example, the
+ actual exponentiation is done by Python at compilation time, so while
+ the expression can take a noticeable amount of time to compute, that
+ time is purely due to the compilation:
+
+ In [5]: %time 3**9999;
+ CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
+ Wall time: 0.00 s
+
+ In [6]: %time 3**999999;
+ CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
+ Wall time: 0.00 s
+ Compiler : 0.78 s
+ """
+
+ # fail immediately if the given expression can't be compiled
+
+ if line and cell:
+ raise UsageError("Can't use statement directly after '%%time'!")
+
+ if cell:
+ expr = self.shell.input_transformer_manager.transform_cell(cell)
+ else:
+ expr = self.shell.input_transformer_manager.transform_cell(line)
+
+ # Minimum time above which parse time will be reported
+ tp_min = 0.1
+
+ t0 = clock()
+ expr_ast = self.shell.compile.ast_parse(expr)
+ tp = clock()-t0
+
+ # Apply AST transformations
+ expr_ast = self.shell.transform_ast(expr_ast)
+
+ # Minimum time above which compilation time will be reported
+ tc_min = 0.1
+
+ if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
+ mode = 'eval'
+ source = '<timed eval>'
+ expr_ast = ast.Expression(expr_ast.body[0].value)
+ else:
+ mode = 'exec'
+ source = '<timed exec>'
+ t0 = clock()
+ code = self.shell.compile(expr_ast, source, mode)
+ tc = clock()-t0
+
+ # skew measurement as little as possible
+ glob = self.shell.user_ns
+ wtime = time.time
+ # time execution
+ wall_st = wtime()
+ if mode=='eval':
+ st = clock2()
+ out = eval(code, glob, local_ns)
+ end = clock2()
+ else:
+ st = clock2()
+ exec(code, glob, local_ns)
+ end = clock2()
+ out = None
+ wall_end = wtime()
+ # Compute actual times and report
+ wall_time = wall_end-wall_st
+ cpu_user = end[0]-st[0]
+ cpu_sys = end[1]-st[1]
+ cpu_tot = cpu_user+cpu_sys
+ # On windows cpu_sys is always zero, so no new information to the next print
+ if sys.platform != 'win32':
+ print("CPU times: user %s, sys: %s, total: %s" % \
+ (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
+ print("Wall time: %s" % _format_time(wall_time))
+ if tc > tc_min:
+ print("Compiler : %s" % _format_time(tc))
+ if tp > tp_min:
+ print("Parser : %s" % _format_time(tp))
+ return out
+
+ @skip_doctest
+ @line_magic
+ def macro(self, parameter_s=''):
+ """Define a macro for future re-execution. It accepts ranges of history,
+ filenames or string objects.
+
+ Usage:\\
+ %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
+
+ Options:
+
+ -r: use 'raw' input. By default, the 'processed' history is used,
+ so that magics are loaded in their transformed version to valid
+ Python. If this option is given, the raw input as typed at the
+ command line is used instead.
+
+ -q: quiet macro definition. By default, a tag line is printed
+ to indicate the macro has been created, and then the contents of
+ the macro are printed. If this option is given, then no printout
+ is produced once the macro is created.
+
+ This will define a global variable called `name` which is a string
+ made of joining the slices and lines you specify (n1,n2,... numbers
+ above) from your input history into a single string. This variable
+ acts like an automatic function which re-executes those lines as if
+ you had typed them. You just type 'name' at the prompt and the code
+ executes.
+
+ The syntax for indicating input ranges is described in %history.
+
+ Note: as a 'hidden' feature, you can also use traditional python slice
+ notation, where N:M means numbers N through M-1.
+
+ For example, if your history contains (print using %hist -n )::
+
+ 44: x=1
+ 45: y=3
+ 46: z=x+y
+ 47: print x
+ 48: a=5
+ 49: print 'x',x,'y',y
+
+ you can create a macro with lines 44 through 47 (included) and line 49
+ called my_macro with::
+
+ In [55]: %macro my_macro 44-47 49
+
+ Now, typing `my_macro` (without quotes) will re-execute all this code
+ in one pass.
+
+ You don't need to give the line-numbers in order, and any given line
+ number can appear multiple times. You can assemble macros with any
+ lines from your input history in any order.
+
+ The macro is a simple object which holds its value in an attribute,
+ but IPython's display system checks for macros and executes them as
+ code instead of printing them when you type their name.
+
+ You can view a macro's contents by explicitly printing it with::
+
+ print macro_name
+
+ """
+ opts,args = self.parse_options(parameter_s,'rq',mode='list')
+ if not args: # List existing macros
+ return sorted(k for k,v in iteritems(self.shell.user_ns) if\
+ isinstance(v, Macro))
+ if len(args) == 1:
+ raise UsageError(
+ "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
+ name, codefrom = args[0], " ".join(args[1:])
+
+ #print 'rng',ranges # dbg
+ try:
+ lines = self.shell.find_user_code(codefrom, 'r' in opts)
+ except (ValueError, TypeError) as e:
+ print(e.args[0])
+ return
+ macro = Macro(lines)
+ self.shell.define_macro(name, macro)
+ if not ( 'q' in opts) :
+ print('Macro `%s` created. To execute, type its name (without quotes).' % name)
+ print('=== Macro contents: ===')
+ print(macro, end=' ')
+
+ @magic_arguments.magic_arguments()
+ @magic_arguments.argument('output', type=str, default='', nargs='?',
+ help="""The name of the variable in which to store output.
+ This is a utils.io.CapturedIO object with stdout/err attributes
+ for the text of the captured output.
+
+ CapturedOutput also has a show() method for displaying the output,
+ and __call__ as well, so you can use that to quickly display the
+ output.
+
+ If unspecified, captured output is discarded.
+ """
+ )
+ @magic_arguments.argument('--no-stderr', action="store_true",
+ help="""Don't capture stderr."""
+ )
+ @magic_arguments.argument('--no-stdout', action="store_true",
+ help="""Don't capture stdout."""
+ )
+ @magic_arguments.argument('--no-display', action="store_true",
+ help="""Don't capture IPython's rich display."""
+ )
+ @cell_magic
+ def capture(self, line, cell):
+ """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
+ args = magic_arguments.parse_argstring(self.capture, line)
+ out = not args.no_stdout
+ err = not args.no_stderr
+ disp = not args.no_display
+ with capture_output(out, err, disp) as io:
+ self.shell.run_cell(cell)
+ if args.output:
+ self.shell.user_ns[args.output] = io
+
+def parse_breakpoint(text, current_file):
+ '''Returns (file, line) for file:line and (current_file, line) for line'''
+ colon = text.find(':')
+ if colon == -1:
+ return current_file, int(text)
+ else:
+ return text[:colon], int(text[colon+1:])
+
+def _format_time(timespan, precision=3):
+ """Formats the timespan in a human readable form"""
+ import math
+
+ if timespan >= 60.0:
+ # we have more than a minute, format that in a human readable form
+ # Idea from http://snipplr.com/view/5713/
+ parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
+ time = []
+ leftover = timespan
+ for suffix, length in parts:
+ value = int(leftover / length)
+ if value > 0:
+ leftover = leftover % length
+ time.append(u'%s%s' % (str(value), suffix))
+ if leftover < 1:
+ break
+ return " ".join(time)
+
+
+ # Unfortunately the unicode 'micro' symbol can cause problems in
+ # certain terminals.
+ # See bug: https://bugs.launchpad.net/ipython/+bug/348466
+ # Try to prevent crashes by being more secure than it needs to
+ # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
+ units = [u"s", u"ms",u'us',"ns"] # the save value
+ if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
+ try:
+ u'\xb5'.encode(sys.stdout.encoding)
+ units = [u"s", u"ms",u'\xb5s',"ns"]
+ except:
+ pass
+ scaling = [1, 1e3, 1e6, 1e9]
+
+ if timespan > 0.0:
+ order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
+ else:
+ order = 3
+ return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
diff --git a/contrib/python/ipython/py2/IPython/core/magics/extension.py b/contrib/python/ipython/py2/IPython/core/magics/extension.py
index cf9a9ab9d1..2991d55ca4 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/extension.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/extension.py
@@ -1,67 +1,67 @@
-"""Implementation of magic functions for the extension machinery.
-"""
-from __future__ import print_function
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012 The IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Stdlib
-import os
-
-# Our own packages
-from IPython.core.error import UsageError
-from IPython.core.magic import Magics, magics_class, line_magic
-from warnings import warn
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-
-@magics_class
-class ExtensionMagics(Magics):
- """Magics to manage the IPython extensions system."""
-
- @line_magic
- def load_ext(self, module_str):
- """Load an IPython extension by its module name."""
- if not module_str:
- raise UsageError('Missing module name.')
- res = self.shell.extension_manager.load_extension(module_str)
-
- if res == 'already loaded':
- print("The %s extension is already loaded. To reload it, use:" % module_str)
- print(" %reload_ext", module_str)
- elif res == 'no load function':
- print("The %s module is not an IPython extension." % module_str)
-
- @line_magic
- def unload_ext(self, module_str):
- """Unload an IPython extension by its module name.
-
- Not all extensions can be unloaded, only those which define an
- ``unload_ipython_extension`` function.
- """
- if not module_str:
- raise UsageError('Missing module name.')
-
- res = self.shell.extension_manager.unload_extension(module_str)
-
- if res == 'no unload function':
- print("The %s extension doesn't define how to unload it." % module_str)
- elif res == "not loaded":
- print("The %s extension is not loaded." % module_str)
-
- @line_magic
- def reload_ext(self, module_str):
- """Reload an IPython extension by its module name."""
- if not module_str:
- raise UsageError('Missing module name.')
- self.shell.extension_manager.reload_extension(module_str)
+"""Implementation of magic functions for the extension machinery.
+"""
+from __future__ import print_function
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012 The IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Stdlib
+import os
+
+# Our own packages
+from IPython.core.error import UsageError
+from IPython.core.magic import Magics, magics_class, line_magic
+from warnings import warn
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+
+@magics_class
+class ExtensionMagics(Magics):
+ """Magics to manage the IPython extensions system."""
+
+ @line_magic
+ def load_ext(self, module_str):
+ """Load an IPython extension by its module name."""
+ if not module_str:
+ raise UsageError('Missing module name.')
+ res = self.shell.extension_manager.load_extension(module_str)
+
+ if res == 'already loaded':
+ print("The %s extension is already loaded. To reload it, use:" % module_str)
+ print(" %reload_ext", module_str)
+ elif res == 'no load function':
+ print("The %s module is not an IPython extension." % module_str)
+
+ @line_magic
+ def unload_ext(self, module_str):
+ """Unload an IPython extension by its module name.
+
+ Not all extensions can be unloaded, only those which define an
+ ``unload_ipython_extension`` function.
+ """
+ if not module_str:
+ raise UsageError('Missing module name.')
+
+ res = self.shell.extension_manager.unload_extension(module_str)
+
+ if res == 'no unload function':
+ print("The %s extension doesn't define how to unload it." % module_str)
+ elif res == "not loaded":
+ print("The %s extension is not loaded." % module_str)
+
+ @line_magic
+ def reload_ext(self, module_str):
+ """Reload an IPython extension by its module name."""
+ if not module_str:
+ raise UsageError('Missing module name.')
+ self.shell.extension_manager.reload_extension(module_str)
diff --git a/contrib/python/ipython/py2/IPython/core/magics/history.py b/contrib/python/ipython/py2/IPython/core/magics/history.py
index 342e641d48..5967591394 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/history.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/history.py
@@ -1,320 +1,320 @@
-"""Implementation of magic functions related to History.
-"""
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012, IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-from __future__ import print_function
-
-# Stdlib
-import os
+"""Implementation of magic functions related to History.
+"""
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012, IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+from __future__ import print_function
+
+# Stdlib
+import os
import sys
-from io import open as io_open
-
-# Our own packages
-from IPython.core.error import StdinNotImplementedError
-from IPython.core.magic import Magics, magics_class, line_magic
-from IPython.core.magic_arguments import (argument, magic_arguments,
- parse_argstring)
-from IPython.testing.skipdoctest import skip_doctest
-from IPython.utils import io
-from IPython.utils.py3compat import cast_unicode_py2
-
-#-----------------------------------------------------------------------------
-# Magics class implementation
-#-----------------------------------------------------------------------------
-
-
-_unspecified = object()
-
-
-@magics_class
-class HistoryMagics(Magics):
-
- @magic_arguments()
- @argument(
- '-n', dest='print_nums', action='store_true', default=False,
- help="""
- print line numbers for each input.
- This feature is only available if numbered prompts are in use.
- """)
- @argument(
- '-o', dest='get_output', action='store_true', default=False,
- help="also print outputs for each input.")
- @argument(
- '-p', dest='pyprompts', action='store_true', default=False,
- help="""
- print classic '>>>' python prompts before each input.
- This is useful for making documentation, and in conjunction
- with -o, for producing doctest-ready output.
- """)
- @argument(
- '-t', dest='raw', action='store_false', default=True,
- help="""
- print the 'translated' history, as IPython understands it.
- IPython filters your input and converts it all into valid Python
- source before executing it (things like magics or aliases are turned
- into function calls, for example). With this option, you'll see the
- native history instead of the user-entered version: '%%cd /' will be
- seen as 'get_ipython().magic("%%cd /")' instead of '%%cd /'.
- """)
- @argument(
- '-f', dest='filename',
- help="""
- FILENAME: instead of printing the output to the screen, redirect
- it to the given file. The file is always overwritten, though *when
- it can*, IPython asks for confirmation first. In particular, running
- the command 'history -f FILENAME' from the IPython Notebook
- interface will replace FILENAME even if it already exists *without*
- confirmation.
- """)
- @argument(
- '-g', dest='pattern', nargs='*', default=None,
- help="""
- treat the arg as a glob pattern to search for in (full) history.
- This includes the saved history (almost all commands ever written).
- The pattern may contain '?' to match one unknown character and '*'
- to match any number of unknown characters. Use '%%hist -g' to show
- full saved history (may be very long).
- """)
- @argument(
- '-l', dest='limit', type=int, nargs='?', default=_unspecified,
- help="""
- get the last n lines from all sessions. Specify n as a single
- arg, or the default is the last 10 lines.
- """)
- @argument(
- '-u', dest='unique', action='store_true',
- help="""
- when searching history using `-g`, show only unique history.
- """)
- @argument('range', nargs='*')
- @skip_doctest
- @line_magic
- def history(self, parameter_s = ''):
- """Print input history (_i<n> variables), with most recent last.
-
- By default, input history is printed without line numbers so it can be
- directly pasted into an editor. Use -n to show them.
-
- By default, all input history from the current session is displayed.
- Ranges of history can be indicated using the syntax:
-
- ``4``
- Line 4, current session
- ``4-6``
- Lines 4-6, current session
- ``243/1-5``
- Lines 1-5, session 243
- ``~2/7``
- Line 7, session 2 before current
- ``~8/1-~6/5``
- From the first line of 8 sessions ago, to the fifth line of 6
- sessions ago.
-
- Multiple ranges can be entered, separated by spaces
-
- The same syntax is used by %macro, %save, %edit, %rerun
-
- Examples
- --------
- ::
-
- In [6]: %history -n 4-6
- 4:a = 12
- 5:print a**2
- 6:%history -n 4-6
-
- """
-
- args = parse_argstring(self.history, parameter_s)
-
- # For brevity
- history_manager = self.shell.history_manager
-
- def _format_lineno(session, line):
- """Helper function to format line numbers properly."""
- if session in (0, history_manager.session_number):
- return str(line)
- return "%s/%s" % (session, line)
-
- # Check if output to specific file was requested.
- outfname = args.filename
- if not outfname:
+from io import open as io_open
+
+# Our own packages
+from IPython.core.error import StdinNotImplementedError
+from IPython.core.magic import Magics, magics_class, line_magic
+from IPython.core.magic_arguments import (argument, magic_arguments,
+ parse_argstring)
+from IPython.testing.skipdoctest import skip_doctest
+from IPython.utils import io
+from IPython.utils.py3compat import cast_unicode_py2
+
+#-----------------------------------------------------------------------------
+# Magics class implementation
+#-----------------------------------------------------------------------------
+
+
+_unspecified = object()
+
+
+@magics_class
+class HistoryMagics(Magics):
+
+ @magic_arguments()
+ @argument(
+ '-n', dest='print_nums', action='store_true', default=False,
+ help="""
+ print line numbers for each input.
+ This feature is only available if numbered prompts are in use.
+ """)
+ @argument(
+ '-o', dest='get_output', action='store_true', default=False,
+ help="also print outputs for each input.")
+ @argument(
+ '-p', dest='pyprompts', action='store_true', default=False,
+ help="""
+ print classic '>>>' python prompts before each input.
+ This is useful for making documentation, and in conjunction
+ with -o, for producing doctest-ready output.
+ """)
+ @argument(
+ '-t', dest='raw', action='store_false', default=True,
+ help="""
+ print the 'translated' history, as IPython understands it.
+ IPython filters your input and converts it all into valid Python
+ source before executing it (things like magics or aliases are turned
+ into function calls, for example). With this option, you'll see the
+ native history instead of the user-entered version: '%%cd /' will be
+ seen as 'get_ipython().magic("%%cd /")' instead of '%%cd /'.
+ """)
+ @argument(
+ '-f', dest='filename',
+ help="""
+ FILENAME: instead of printing the output to the screen, redirect
+ it to the given file. The file is always overwritten, though *when
+ it can*, IPython asks for confirmation first. In particular, running
+ the command 'history -f FILENAME' from the IPython Notebook
+ interface will replace FILENAME even if it already exists *without*
+ confirmation.
+ """)
+ @argument(
+ '-g', dest='pattern', nargs='*', default=None,
+ help="""
+ treat the arg as a glob pattern to search for in (full) history.
+ This includes the saved history (almost all commands ever written).
+ The pattern may contain '?' to match one unknown character and '*'
+ to match any number of unknown characters. Use '%%hist -g' to show
+ full saved history (may be very long).
+ """)
+ @argument(
+ '-l', dest='limit', type=int, nargs='?', default=_unspecified,
+ help="""
+ get the last n lines from all sessions. Specify n as a single
+ arg, or the default is the last 10 lines.
+ """)
+ @argument(
+ '-u', dest='unique', action='store_true',
+ help="""
+ when searching history using `-g`, show only unique history.
+ """)
+ @argument('range', nargs='*')
+ @skip_doctest
+ @line_magic
+ def history(self, parameter_s = ''):
+ """Print input history (_i<n> variables), with most recent last.
+
+ By default, input history is printed without line numbers so it can be
+ directly pasted into an editor. Use -n to show them.
+
+ By default, all input history from the current session is displayed.
+ Ranges of history can be indicated using the syntax:
+
+ ``4``
+ Line 4, current session
+ ``4-6``
+ Lines 4-6, current session
+ ``243/1-5``
+ Lines 1-5, session 243
+ ``~2/7``
+ Line 7, session 2 before current
+ ``~8/1-~6/5``
+ From the first line of 8 sessions ago, to the fifth line of 6
+ sessions ago.
+
+ Multiple ranges can be entered, separated by spaces
+
+ The same syntax is used by %macro, %save, %edit, %rerun
+
+ Examples
+ --------
+ ::
+
+ In [6]: %history -n 4-6
+ 4:a = 12
+ 5:print a**2
+ 6:%history -n 4-6
+
+ """
+
+ args = parse_argstring(self.history, parameter_s)
+
+ # For brevity
+ history_manager = self.shell.history_manager
+
+ def _format_lineno(session, line):
+ """Helper function to format line numbers properly."""
+ if session in (0, history_manager.session_number):
+ return str(line)
+ return "%s/%s" % (session, line)
+
+ # Check if output to specific file was requested.
+ outfname = args.filename
+ if not outfname:
outfile = sys.stdout # default
- # We don't want to close stdout at the end!
- close_at_end = False
- else:
- if os.path.exists(outfname):
- try:
- ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
- except StdinNotImplementedError:
- ans = True
- if not ans:
- print('Aborting.')
- return
- print("Overwriting file.")
- outfile = io_open(outfname, 'w', encoding='utf-8')
- close_at_end = True
-
- print_nums = args.print_nums
- get_output = args.get_output
- pyprompts = args.pyprompts
- raw = args.raw
-
- pattern = None
- limit = None if args.limit is _unspecified else args.limit
-
- if args.pattern is not None:
- if args.pattern:
- pattern = "*" + " ".join(args.pattern) + "*"
- else:
- pattern = "*"
- hist = history_manager.search(pattern, raw=raw, output=get_output,
- n=limit, unique=args.unique)
- print_nums = True
- elif args.limit is not _unspecified:
- n = 10 if limit is None else limit
- hist = history_manager.get_tail(n, raw=raw, output=get_output)
- else:
- if args.range: # Get history by ranges
- hist = history_manager.get_range_by_str(" ".join(args.range),
- raw, get_output)
- else: # Just get history for the current session
- hist = history_manager.get_range(raw=raw, output=get_output)
-
- # We could be displaying the entire history, so let's not try to pull
- # it into a list in memory. Anything that needs more space will just
- # misalign.
- width = 4
-
- for session, lineno, inline in hist:
- # Print user history with tabs expanded to 4 spaces. The GUI
- # clients use hard tabs for easier usability in auto-indented code,
- # but we want to produce PEP-8 compliant history for safe pasting
- # into an editor.
- if get_output:
- inline, output = inline
- inline = inline.expandtabs(4).rstrip()
-
- multiline = "\n" in inline
- line_sep = '\n' if multiline else ' '
- if print_nums:
- print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
- line_sep), file=outfile, end=u'')
- if pyprompts:
- print(u">>> ", end=u"", file=outfile)
- if multiline:
- inline = "\n... ".join(inline.splitlines()) + "\n..."
- print(inline, file=outfile)
- if get_output and output:
- print(cast_unicode_py2(output), file=outfile)
-
- if close_at_end:
- outfile.close()
-
- @line_magic
- def recall(self, arg):
- r"""Repeat a command, or get command to input line for editing.
-
- %recall and %rep are equivalent.
-
- - %recall (no arguments):
-
- Place a string version of last computation result (stored in the
- special '_' variable) to the next input prompt. Allows you to create
- elaborate command lines without using copy-paste::
-
- In[1]: l = ["hei", "vaan"]
- In[2]: "".join(l)
- Out[2]: heivaan
- In[3]: %recall
- In[4]: heivaan_ <== cursor blinking
-
- %recall 45
-
- Place history line 45 on the next input prompt. Use %hist to find
- out the number.
-
- %recall 1-4
-
- Combine the specified lines into one cell, and place it on the next
- input prompt. See %history for the slice syntax.
-
- %recall foo+bar
-
- If foo+bar can be evaluated in the user namespace, the result is
- placed at the next input prompt. Otherwise, the history is searched
- for lines which contain that substring, and the most recent one is
- placed at the next input prompt.
- """
- if not arg: # Last output
- self.shell.set_next_input(str(self.shell.user_ns["_"]))
- return
- # Get history range
- histlines = self.shell.history_manager.get_range_by_str(arg)
- cmd = "\n".join(x[2] for x in histlines)
- if cmd:
- self.shell.set_next_input(cmd.rstrip())
- return
-
- try: # Variable in user namespace
- cmd = str(eval(arg, self.shell.user_ns))
- except Exception: # Search for term in history
- histlines = self.shell.history_manager.search("*"+arg+"*")
- for h in reversed([x[2] for x in histlines]):
- if 'recall' in h or 'rep' in h:
- continue
- self.shell.set_next_input(h.rstrip())
- return
- else:
- self.shell.set_next_input(cmd.rstrip())
- print("Couldn't evaluate or find in history:", arg)
-
- @line_magic
- def rerun(self, parameter_s=''):
- """Re-run previous input
-
- By default, you can specify ranges of input history to be repeated
- (as with %history). With no arguments, it will repeat the last line.
-
- Options:
-
- -l <n> : Repeat the last n lines of input, not including the
- current command.
-
- -g foo : Repeat the most recent line which contains foo
- """
- opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
- if "l" in opts: # Last n lines
- n = int(opts['l'])
- hist = self.shell.history_manager.get_tail(n)
- elif "g" in opts: # Search
- p = "*"+opts['g']+"*"
- hist = list(self.shell.history_manager.search(p))
- for l in reversed(hist):
- if "rerun" not in l[2]:
- hist = [l] # The last match which isn't a %rerun
- break
- else:
- hist = [] # No matches except %rerun
- elif args: # Specify history ranges
- hist = self.shell.history_manager.get_range_by_str(args)
- else: # Last line
- hist = self.shell.history_manager.get_tail(1)
- hist = [x[2] for x in hist]
- if not hist:
- print("No lines in history match specification")
- return
- histlines = "\n".join(hist)
- print("=== Executing: ===")
- print(histlines)
- print("=== Output: ===")
- self.shell.run_cell("\n".join(hist), store_history=False)
+ # We don't want to close stdout at the end!
+ close_at_end = False
+ else:
+ if os.path.exists(outfname):
+ try:
+ ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
+ except StdinNotImplementedError:
+ ans = True
+ if not ans:
+ print('Aborting.')
+ return
+ print("Overwriting file.")
+ outfile = io_open(outfname, 'w', encoding='utf-8')
+ close_at_end = True
+
+ print_nums = args.print_nums
+ get_output = args.get_output
+ pyprompts = args.pyprompts
+ raw = args.raw
+
+ pattern = None
+ limit = None if args.limit is _unspecified else args.limit
+
+ if args.pattern is not None:
+ if args.pattern:
+ pattern = "*" + " ".join(args.pattern) + "*"
+ else:
+ pattern = "*"
+ hist = history_manager.search(pattern, raw=raw, output=get_output,
+ n=limit, unique=args.unique)
+ print_nums = True
+ elif args.limit is not _unspecified:
+ n = 10 if limit is None else limit
+ hist = history_manager.get_tail(n, raw=raw, output=get_output)
+ else:
+ if args.range: # Get history by ranges
+ hist = history_manager.get_range_by_str(" ".join(args.range),
+ raw, get_output)
+ else: # Just get history for the current session
+ hist = history_manager.get_range(raw=raw, output=get_output)
+
+ # We could be displaying the entire history, so let's not try to pull
+ # it into a list in memory. Anything that needs more space will just
+ # misalign.
+ width = 4
+
+ for session, lineno, inline in hist:
+ # Print user history with tabs expanded to 4 spaces. The GUI
+ # clients use hard tabs for easier usability in auto-indented code,
+ # but we want to produce PEP-8 compliant history for safe pasting
+ # into an editor.
+ if get_output:
+ inline, output = inline
+ inline = inline.expandtabs(4).rstrip()
+
+ multiline = "\n" in inline
+ line_sep = '\n' if multiline else ' '
+ if print_nums:
+ print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
+ line_sep), file=outfile, end=u'')
+ if pyprompts:
+ print(u">>> ", end=u"", file=outfile)
+ if multiline:
+ inline = "\n... ".join(inline.splitlines()) + "\n..."
+ print(inline, file=outfile)
+ if get_output and output:
+ print(cast_unicode_py2(output), file=outfile)
+
+ if close_at_end:
+ outfile.close()
+
+ @line_magic
+ def recall(self, arg):
+ r"""Repeat a command, or get command to input line for editing.
+
+ %recall and %rep are equivalent.
+
+ - %recall (no arguments):
+
+ Place a string version of last computation result (stored in the
+ special '_' variable) to the next input prompt. Allows you to create
+ elaborate command lines without using copy-paste::
+
+ In[1]: l = ["hei", "vaan"]
+ In[2]: "".join(l)
+ Out[2]: heivaan
+ In[3]: %recall
+ In[4]: heivaan_ <== cursor blinking
+
+ %recall 45
+
+ Place history line 45 on the next input prompt. Use %hist to find
+ out the number.
+
+ %recall 1-4
+
+ Combine the specified lines into one cell, and place it on the next
+ input prompt. See %history for the slice syntax.
+
+ %recall foo+bar
+
+ If foo+bar can be evaluated in the user namespace, the result is
+ placed at the next input prompt. Otherwise, the history is searched
+ for lines which contain that substring, and the most recent one is
+ placed at the next input prompt.
+ """
+ if not arg: # Last output
+ self.shell.set_next_input(str(self.shell.user_ns["_"]))
+ return
+ # Get history range
+ histlines = self.shell.history_manager.get_range_by_str(arg)
+ cmd = "\n".join(x[2] for x in histlines)
+ if cmd:
+ self.shell.set_next_input(cmd.rstrip())
+ return
+
+ try: # Variable in user namespace
+ cmd = str(eval(arg, self.shell.user_ns))
+ except Exception: # Search for term in history
+ histlines = self.shell.history_manager.search("*"+arg+"*")
+ for h in reversed([x[2] for x in histlines]):
+ if 'recall' in h or 'rep' in h:
+ continue
+ self.shell.set_next_input(h.rstrip())
+ return
+ else:
+ self.shell.set_next_input(cmd.rstrip())
+ print("Couldn't evaluate or find in history:", arg)
+
+ @line_magic
+ def rerun(self, parameter_s=''):
+ """Re-run previous input
+
+ By default, you can specify ranges of input history to be repeated
+ (as with %history). With no arguments, it will repeat the last line.
+
+ Options:
+
+ -l <n> : Repeat the last n lines of input, not including the
+ current command.
+
+ -g foo : Repeat the most recent line which contains foo
+ """
+ opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
+ if "l" in opts: # Last n lines
+ n = int(opts['l'])
+ hist = self.shell.history_manager.get_tail(n)
+ elif "g" in opts: # Search
+ p = "*"+opts['g']+"*"
+ hist = list(self.shell.history_manager.search(p))
+ for l in reversed(hist):
+ if "rerun" not in l[2]:
+ hist = [l] # The last match which isn't a %rerun
+ break
+ else:
+ hist = [] # No matches except %rerun
+ elif args: # Specify history ranges
+ hist = self.shell.history_manager.get_range_by_str(args)
+ else: # Last line
+ hist = self.shell.history_manager.get_tail(1)
+ hist = [x[2] for x in hist]
+ if not hist:
+ print("No lines in history match specification")
+ return
+ histlines = "\n".join(hist)
+ print("=== Executing: ===")
+ print(histlines)
+ print("=== Output: ===")
+ self.shell.run_cell("\n".join(hist), store_history=False)
diff --git a/contrib/python/ipython/py2/IPython/core/magics/logging.py b/contrib/python/ipython/py2/IPython/core/magics/logging.py
index 0fafdeff6b..90214ab54a 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/logging.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/logging.py
@@ -1,184 +1,184 @@
-"""Implementation of magic functions for IPython's own logging.
-"""
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012 The IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Stdlib
-import os
-import sys
-
-# Our own packages
-from IPython.core.magic import Magics, magics_class, line_magic
+"""Implementation of magic functions for IPython's own logging.
+"""
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012 The IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Stdlib
+import os
+import sys
+
+# Our own packages
+from IPython.core.magic import Magics, magics_class, line_magic
from warnings import warn
-from IPython.utils.py3compat import str_to_unicode
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-
-@magics_class
-class LoggingMagics(Magics):
- """Magics related to all logging machinery."""
-
- @line_magic
- def logstart(self, parameter_s=''):
- """Start logging anywhere in a session.
-
- %logstart [-o|-r|-t] [log_name [log_mode]]
-
- If no name is given, it defaults to a file named 'ipython_log.py' in your
- current directory, in 'rotate' mode (see below).
-
- '%logstart name' saves to file 'name' in 'backup' mode. It saves your
- history up to that point and then continues logging.
-
- %logstart takes a second optional parameter: logging mode. This can be one
- of (note that the modes are given unquoted):
-
- append
- Keep logging at the end of any existing file.
-
- backup
- Rename any existing file to name~ and start name.
-
- global
- Append to a single logfile in your home directory.
-
- over
- Overwrite any existing log.
-
- rotate
- Create rotating logs: name.1~, name.2~, etc.
-
- Options:
-
- -o
- log also IPython's output. In this mode, all commands which
- generate an Out[NN] prompt are recorded to the logfile, right after
- their corresponding input line. The output lines are always
- prepended with a '#[Out]# ' marker, so that the log remains valid
- Python code.
-
- Since this marker is always the same, filtering only the output from
- a log is very easy, using for example a simple awk call::
-
- awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
-
- -r
- log 'raw' input. Normally, IPython's logs contain the processed
- input, so that user lines are logged in their final form, converted
- into valid Python. For example, %Exit is logged as
- _ip.magic("Exit"). If the -r flag is given, all input is logged
- exactly as typed, with no transformations applied.
-
- -t
- put timestamps before each input line logged (these are put in
- comments).
- """
-
- opts,par = self.parse_options(parameter_s,'ort')
- log_output = 'o' in opts
- log_raw_input = 'r' in opts
- timestamp = 't' in opts
-
- logger = self.shell.logger
-
- # if no args are given, the defaults set in the logger constructor by
- # ipython remain valid
- if par:
- try:
- logfname,logmode = par.split()
- except:
- logfname = par
- logmode = 'backup'
- else:
- logfname = logger.logfname
- logmode = logger.logmode
- # put logfname into rc struct as if it had been called on the command
- # line, so it ends up saved in the log header Save it in case we need
- # to restore it...
- old_logfile = self.shell.logfile
- if logfname:
- logfname = os.path.expanduser(logfname)
- self.shell.logfile = logfname
-
- loghead = u'# IPython log file\n\n'
- try:
- logger.logstart(logfname, loghead, logmode, log_output, timestamp,
- log_raw_input)
- except:
- self.shell.logfile = old_logfile
- warn("Couldn't start log: %s" % sys.exc_info()[1])
- else:
- # log input history up to this point, optionally interleaving
- # output if requested
-
- if timestamp:
- # disable timestamping for the previous history, since we've
- # lost those already (no time machine here).
- logger.timestamp = False
-
- if log_raw_input:
- input_hist = self.shell.history_manager.input_hist_raw
- else:
- input_hist = self.shell.history_manager.input_hist_parsed
-
- if log_output:
- log_write = logger.log_write
- output_hist = self.shell.history_manager.output_hist
- for n in range(1,len(input_hist)-1):
- log_write(input_hist[n].rstrip() + u'\n')
- if n in output_hist:
- log_write(str_to_unicode(repr(output_hist[n])),'output')
- else:
- logger.log_write(u'\n'.join(input_hist[1:]))
- logger.log_write(u'\n')
- if timestamp:
- # re-enable timestamping
- logger.timestamp = True
-
- print ('Activating auto-logging. '
- 'Current session state plus future input saved.')
- logger.logstate()
-
- @line_magic
- def logstop(self, parameter_s=''):
- """Fully stop logging and close log file.
-
- In order to start logging again, a new %logstart call needs to be made,
- possibly (though not necessarily) with a new filename, mode and other
- options."""
- self.shell.logger.logstop()
-
- @line_magic
- def logoff(self, parameter_s=''):
- """Temporarily stop logging.
-
- You must have previously started logging."""
- self.shell.logger.switch_log(0)
-
- @line_magic
- def logon(self, parameter_s=''):
- """Restart logging.
-
- This function is for restarting logging which you've temporarily
- stopped with %logoff. For starting logging for the first time, you
- must use the %logstart function, which allows you to specify an
- optional log filename."""
-
- self.shell.logger.switch_log(1)
-
- @line_magic
- def logstate(self, parameter_s=''):
- """Print the status of the logging system."""
-
- self.shell.logger.logstate()
+from IPython.utils.py3compat import str_to_unicode
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+
+@magics_class
+class LoggingMagics(Magics):
+ """Magics related to all logging machinery."""
+
+ @line_magic
+ def logstart(self, parameter_s=''):
+ """Start logging anywhere in a session.
+
+ %logstart [-o|-r|-t] [log_name [log_mode]]
+
+ If no name is given, it defaults to a file named 'ipython_log.py' in your
+ current directory, in 'rotate' mode (see below).
+
+ '%logstart name' saves to file 'name' in 'backup' mode. It saves your
+ history up to that point and then continues logging.
+
+ %logstart takes a second optional parameter: logging mode. This can be one
+ of (note that the modes are given unquoted):
+
+ append
+ Keep logging at the end of any existing file.
+
+ backup
+ Rename any existing file to name~ and start name.
+
+ global
+ Append to a single logfile in your home directory.
+
+ over
+ Overwrite any existing log.
+
+ rotate
+ Create rotating logs: name.1~, name.2~, etc.
+
+ Options:
+
+ -o
+ log also IPython's output. In this mode, all commands which
+ generate an Out[NN] prompt are recorded to the logfile, right after
+ their corresponding input line. The output lines are always
+ prepended with a '#[Out]# ' marker, so that the log remains valid
+ Python code.
+
+ Since this marker is always the same, filtering only the output from
+ a log is very easy, using for example a simple awk call::
+
+ awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
+
+ -r
+ log 'raw' input. Normally, IPython's logs contain the processed
+ input, so that user lines are logged in their final form, converted
+ into valid Python. For example, %Exit is logged as
+ _ip.magic("Exit"). If the -r flag is given, all input is logged
+ exactly as typed, with no transformations applied.
+
+ -t
+ put timestamps before each input line logged (these are put in
+ comments).
+ """
+
+ opts,par = self.parse_options(parameter_s,'ort')
+ log_output = 'o' in opts
+ log_raw_input = 'r' in opts
+ timestamp = 't' in opts
+
+ logger = self.shell.logger
+
+ # if no args are given, the defaults set in the logger constructor by
+ # ipython remain valid
+ if par:
+ try:
+ logfname,logmode = par.split()
+ except:
+ logfname = par
+ logmode = 'backup'
+ else:
+ logfname = logger.logfname
+ logmode = logger.logmode
+ # put logfname into rc struct as if it had been called on the command
+ # line, so it ends up saved in the log header Save it in case we need
+ # to restore it...
+ old_logfile = self.shell.logfile
+ if logfname:
+ logfname = os.path.expanduser(logfname)
+ self.shell.logfile = logfname
+
+ loghead = u'# IPython log file\n\n'
+ try:
+ logger.logstart(logfname, loghead, logmode, log_output, timestamp,
+ log_raw_input)
+ except:
+ self.shell.logfile = old_logfile
+ warn("Couldn't start log: %s" % sys.exc_info()[1])
+ else:
+ # log input history up to this point, optionally interleaving
+ # output if requested
+
+ if timestamp:
+ # disable timestamping for the previous history, since we've
+ # lost those already (no time machine here).
+ logger.timestamp = False
+
+ if log_raw_input:
+ input_hist = self.shell.history_manager.input_hist_raw
+ else:
+ input_hist = self.shell.history_manager.input_hist_parsed
+
+ if log_output:
+ log_write = logger.log_write
+ output_hist = self.shell.history_manager.output_hist
+ for n in range(1,len(input_hist)-1):
+ log_write(input_hist[n].rstrip() + u'\n')
+ if n in output_hist:
+ log_write(str_to_unicode(repr(output_hist[n])),'output')
+ else:
+ logger.log_write(u'\n'.join(input_hist[1:]))
+ logger.log_write(u'\n')
+ if timestamp:
+ # re-enable timestamping
+ logger.timestamp = True
+
+ print ('Activating auto-logging. '
+ 'Current session state plus future input saved.')
+ logger.logstate()
+
+ @line_magic
+ def logstop(self, parameter_s=''):
+ """Fully stop logging and close log file.
+
+ In order to start logging again, a new %logstart call needs to be made,
+ possibly (though not necessarily) with a new filename, mode and other
+ options."""
+ self.shell.logger.logstop()
+
+ @line_magic
+ def logoff(self, parameter_s=''):
+ """Temporarily stop logging.
+
+ You must have previously started logging."""
+ self.shell.logger.switch_log(0)
+
+ @line_magic
+ def logon(self, parameter_s=''):
+ """Restart logging.
+
+ This function is for restarting logging which you've temporarily
+ stopped with %logoff. For starting logging for the first time, you
+ must use the %logstart function, which allows you to specify an
+ optional log filename."""
+
+ self.shell.logger.switch_log(1)
+
+ @line_magic
+ def logstate(self, parameter_s=''):
+ """Print the status of the logging system."""
+
+ self.shell.logger.logstate()
diff --git a/contrib/python/ipython/py2/IPython/core/magics/namespace.py b/contrib/python/ipython/py2/IPython/core/magics/namespace.py
index fafecb191b..c02b38716b 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/namespace.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/namespace.py
@@ -1,704 +1,704 @@
-"""Implementation of namespace-related magic functions.
-"""
-from __future__ import print_function
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012 The IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Stdlib
-import gc
-import re
-import sys
-
-# Our own packages
-from IPython.core import page
-from IPython.core.error import StdinNotImplementedError, UsageError
-from IPython.core.magic import Magics, magics_class, line_magic
-from IPython.testing.skipdoctest import skip_doctest
-from IPython.utils.encoding import DEFAULT_ENCODING
-from IPython.utils.openpy import read_py_file
-from IPython.utils.path import get_py_filename
-from IPython.utils.py3compat import unicode_type
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-
-@magics_class
-class NamespaceMagics(Magics):
- """Magics to manage various aspects of the user's namespace.
-
- These include listing variables, introspecting into them, etc.
- """
-
- @line_magic
- def pinfo(self, parameter_s='', namespaces=None):
- """Provide detailed information about an object.
-
- '%pinfo object' is just a synonym for object? or ?object."""
-
- #print 'pinfo par: <%s>' % parameter_s # dbg
- # detail_level: 0 -> obj? , 1 -> obj??
- detail_level = 0
- # We need to detect if we got called as 'pinfo pinfo foo', which can
- # happen if the user types 'pinfo foo?' at the cmd line.
- pinfo,qmark1,oname,qmark2 = \
- re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
- if pinfo or qmark1 or qmark2:
- detail_level = 1
- if "*" in oname:
- self.psearch(oname)
- else:
- self.shell._inspect('pinfo', oname, detail_level=detail_level,
- namespaces=namespaces)
-
- @line_magic
- def pinfo2(self, parameter_s='', namespaces=None):
- """Provide extra detailed information about an object.
-
- '%pinfo2 object' is just a synonym for object?? or ??object."""
- self.shell._inspect('pinfo', parameter_s, detail_level=1,
- namespaces=namespaces)
-
- @skip_doctest
- @line_magic
- def pdef(self, parameter_s='', namespaces=None):
- """Print the call signature for any callable object.
-
- If the object is a class, print the constructor information.
-
- Examples
- --------
- ::
-
- In [3]: %pdef urllib.urlopen
- urllib.urlopen(url, data=None, proxies=None)
- """
- self.shell._inspect('pdef',parameter_s, namespaces)
-
- @line_magic
- def pdoc(self, parameter_s='', namespaces=None):
- """Print the docstring for an object.
-
- If the given object is a class, it will print both the class and the
- constructor docstrings."""
- self.shell._inspect('pdoc',parameter_s, namespaces)
-
- @line_magic
- def psource(self, parameter_s='', namespaces=None):
- """Print (or run through pager) the source code for an object."""
- if not parameter_s:
- raise UsageError('Missing object name.')
- self.shell._inspect('psource',parameter_s, namespaces)
-
- @line_magic
- def pfile(self, parameter_s='', namespaces=None):
- """Print (or run through pager) the file where an object is defined.
-
- The file opens at the line where the object definition begins. IPython
- will honor the environment variable PAGER if set, and otherwise will
- do its best to print the file in a convenient form.
-
- If the given argument is not an object currently defined, IPython will
- try to interpret it as a filename (automatically adding a .py extension
- if needed). You can thus use %pfile as a syntax highlighting code
- viewer."""
-
- # first interpret argument as an object name
- out = self.shell._inspect('pfile',parameter_s, namespaces)
- # if not, try the input as a filename
- if out == 'not found':
- try:
- filename = get_py_filename(parameter_s)
- except IOError as msg:
- print(msg)
- return
- page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
-
- @line_magic
- def psearch(self, parameter_s=''):
- """Search for object in namespaces by wildcard.
-
- %psearch [options] PATTERN [OBJECT TYPE]
-
- Note: ? can be used as a synonym for %psearch, at the beginning or at
- the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
- rest of the command line must be unchanged (options come first), so
- for example the following forms are equivalent
-
- %psearch -i a* function
- -i a* function?
- ?-i a* function
-
- Arguments:
-
- PATTERN
-
- where PATTERN is a string containing * as a wildcard similar to its
- use in a shell. The pattern is matched in all namespaces on the
- search path. By default objects starting with a single _ are not
- matched, many IPython generated objects have a single
- underscore. The default is case insensitive matching. Matching is
- also done on the attributes of objects and not only on the objects
- in a module.
-
- [OBJECT TYPE]
-
- Is the name of a python type from the types module. The name is
- given in lowercase without the ending type, ex. StringType is
- written string. By adding a type here only objects matching the
- given type are matched. Using all here makes the pattern match all
- types (this is the default).
-
- Options:
-
- -a: makes the pattern match even objects whose names start with a
- single underscore. These names are normally omitted from the
- search.
-
- -i/-c: make the pattern case insensitive/sensitive. If neither of
- these options are given, the default is read from your configuration
- file, with the option ``InteractiveShell.wildcards_case_sensitive``.
- If this option is not specified in your configuration file, IPython's
- internal default is to do a case sensitive search.
-
- -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
- specify can be searched in any of the following namespaces:
- 'builtin', 'user', 'user_global','internal', 'alias', where
- 'builtin' and 'user' are the search defaults. Note that you should
- not use quotes when specifying namespaces.
-
- 'Builtin' contains the python module builtin, 'user' contains all
- user data, 'alias' only contain the shell aliases and no python
- objects, 'internal' contains objects used by IPython. The
- 'user_global' namespace is only used by embedded IPython instances,
- and it contains module-level globals. You can add namespaces to the
- search with -s or exclude them with -e (these options can be given
- more than once).
-
- Examples
- --------
- ::
-
- %psearch a* -> objects beginning with an a
- %psearch -e builtin a* -> objects NOT in the builtin space starting in a
- %psearch a* function -> all functions beginning with an a
- %psearch re.e* -> objects beginning with an e in module re
- %psearch r*.e* -> objects that start with e in modules starting in r
- %psearch r*.* string -> all strings in modules beginning with r
-
- Case sensitive search::
-
- %psearch -c a* list all object beginning with lower case a
-
- Show objects beginning with a single _::
-
- %psearch -a _* list objects beginning with a single underscore
- """
- try:
- parameter_s.encode('ascii')
- except UnicodeEncodeError:
- print('Python identifiers can only contain ascii characters.')
- return
-
- # default namespaces to be searched
- def_search = ['user_local', 'user_global', 'builtin']
-
- # Process options/args
- opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
- opt = opts.get
- shell = self.shell
- psearch = shell.inspector.psearch
-
- # select case options
- if 'i' in opts:
- ignore_case = True
- elif 'c' in opts:
- ignore_case = False
- else:
- ignore_case = not shell.wildcards_case_sensitive
-
- # Build list of namespaces to search from user options
- def_search.extend(opt('s',[]))
- ns_exclude = ns_exclude=opt('e',[])
- ns_search = [nm for nm in def_search if nm not in ns_exclude]
-
- # Call the actual search
- try:
- psearch(args,shell.ns_table,ns_search,
- show_all=opt('a'),ignore_case=ignore_case)
- except:
- shell.showtraceback()
-
- @skip_doctest
- @line_magic
- def who_ls(self, parameter_s=''):
- """Return a sorted list of all interactive variables.
-
- If arguments are given, only variables of types matching these
- arguments are returned.
-
- Examples
- --------
-
- Define two variables and list them with who_ls::
-
- In [1]: alpha = 123
-
- In [2]: beta = 'test'
-
- In [3]: %who_ls
- Out[3]: ['alpha', 'beta']
-
- In [4]: %who_ls int
- Out[4]: ['alpha']
-
- In [5]: %who_ls str
- Out[5]: ['beta']
- """
-
- user_ns = self.shell.user_ns
- user_ns_hidden = self.shell.user_ns_hidden
- nonmatching = object() # This can never be in user_ns
- out = [ i for i in user_ns
- if not i.startswith('_') \
- and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
-
- typelist = parameter_s.split()
- if typelist:
- typeset = set(typelist)
- out = [i for i in out if type(user_ns[i]).__name__ in typeset]
-
- out.sort()
- return out
-
- @skip_doctest
- @line_magic
- def who(self, parameter_s=''):
- """Print all interactive variables, with some minimal formatting.
-
- If any arguments are given, only variables whose type matches one of
- these are printed. For example::
-
- %who function str
-
- will only list functions and strings, excluding all other types of
- variables. To find the proper type names, simply use type(var) at a
- command line to see how python prints type names. For example:
-
- ::
-
- In [1]: type('hello')\\
- Out[1]: <type 'str'>
-
- indicates that the type name for strings is 'str'.
-
- ``%who`` always excludes executed names loaded through your configuration
- file and things which are internal to IPython.
-
- This is deliberate, as typically you may load many modules and the
- purpose of %who is to show you only what you've manually defined.
-
- Examples
- --------
-
- Define two variables and list them with who::
-
- In [1]: alpha = 123
-
- In [2]: beta = 'test'
-
- In [3]: %who
- alpha beta
-
- In [4]: %who int
- alpha
-
- In [5]: %who str
- beta
- """
-
- varlist = self.who_ls(parameter_s)
- if not varlist:
- if parameter_s:
- print('No variables match your requested type.')
- else:
- print('Interactive namespace is empty.')
- return
-
- # if we have variables, move on...
- count = 0
- for i in varlist:
- print(i+'\t', end=' ')
- count += 1
- if count > 8:
- count = 0
- print()
- print()
-
- @skip_doctest
- @line_magic
- def whos(self, parameter_s=''):
- """Like %who, but gives some extra information about each variable.
-
- The same type filtering of %who can be applied here.
-
- For all variables, the type is printed. Additionally it prints:
-
- - For {},[],(): their length.
-
- - For numpy arrays, a summary with shape, number of
- elements, typecode and size in memory.
-
- - Everything else: a string representation, snipping their middle if
- too long.
-
- Examples
- --------
-
- Define two variables and list them with whos::
-
- In [1]: alpha = 123
-
- In [2]: beta = 'test'
-
- In [3]: %whos
- Variable Type Data/Info
- --------------------------------
- alpha int 123
- beta str test
- """
-
- varnames = self.who_ls(parameter_s)
- if not varnames:
- if parameter_s:
- print('No variables match your requested type.')
- else:
- print('Interactive namespace is empty.')
- return
-
- # if we have variables, move on...
-
- # for these types, show len() instead of data:
- seq_types = ['dict', 'list', 'tuple']
-
- # for numpy arrays, display summary info
- ndarray_type = None
- if 'numpy' in sys.modules:
- try:
- from numpy import ndarray
- except ImportError:
- pass
- else:
- ndarray_type = ndarray.__name__
-
- # Find all variable names and types so we can figure out column sizes
-
- # some types are well known and can be shorter
- abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
- def type_name(v):
- tn = type(v).__name__
- return abbrevs.get(tn,tn)
-
- varlist = [self.shell.user_ns[n] for n in varnames]
-
- typelist = []
- for vv in varlist:
- tt = type_name(vv)
-
- if tt=='instance':
- typelist.append( abbrevs.get(str(vv.__class__),
- str(vv.__class__)))
- else:
- typelist.append(tt)
-
- # column labels and # of spaces as separator
- varlabel = 'Variable'
- typelabel = 'Type'
- datalabel = 'Data/Info'
- colsep = 3
- # variable format strings
- vformat = "{0:<{varwidth}}{1:<{typewidth}}"
- aformat = "%s: %s elems, type `%s`, %s bytes"
- # find the size of the columns to format the output nicely
- varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
- typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
- # table header
- print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
- ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
- # and the table itself
- kb = 1024
- Mb = 1048576 # kb**2
- for vname,var,vtype in zip(varnames,varlist,typelist):
- print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
- if vtype in seq_types:
- print("n="+str(len(var)))
- elif vtype == ndarray_type:
- vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
- if vtype==ndarray_type:
- # numpy
- vsize = var.size
- vbytes = vsize*var.itemsize
- vdtype = var.dtype
-
- if vbytes < 100000:
- print(aformat % (vshape, vsize, vdtype, vbytes))
- else:
- print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
- if vbytes < Mb:
- print('(%s kb)' % (vbytes/kb,))
- else:
- print('(%s Mb)' % (vbytes/Mb,))
- else:
- try:
- vstr = str(var)
- except UnicodeEncodeError:
- vstr = unicode_type(var).encode(DEFAULT_ENCODING,
- 'backslashreplace')
- except:
- vstr = "<object with id %d (str() failed)>" % id(var)
- vstr = vstr.replace('\n', '\\n')
- if len(vstr) < 50:
- print(vstr)
- else:
- print(vstr[:25] + "<...>" + vstr[-25:])
-
- @line_magic
- def reset(self, parameter_s=''):
- """Resets the namespace by removing all names defined by the user, if
- called without arguments, or by removing some types of objects, such
- as everything currently in IPython's In[] and Out[] containers (see
- the parameters for details).
-
- Parameters
- ----------
- -f : force reset without asking for confirmation.
-
- -s : 'Soft' reset: Only clears your namespace, leaving history intact.
- References to objects may be kept. By default (without this option),
- we do a 'hard' reset, giving you a new session and removing all
- references to objects from the current session.
-
- in : reset input history
-
- out : reset output history
-
- dhist : reset directory history
-
- array : reset only variables that are NumPy arrays
-
- See Also
- --------
- reset_selective : invoked as ``%reset_selective``
-
- Examples
- --------
- ::
-
- In [6]: a = 1
-
- In [7]: a
- Out[7]: 1
-
- In [8]: 'a' in _ip.user_ns
- Out[8]: True
-
- In [9]: %reset -f
-
- In [1]: 'a' in _ip.user_ns
- Out[1]: False
-
- In [2]: %reset -f in
- Flushing input history
-
- In [3]: %reset -f dhist in
- Flushing directory history
- Flushing input history
-
- Notes
- -----
- Calling this magic from clients that do not implement standard input,
- such as the ipython notebook interface, will reset the namespace
- without confirmation.
- """
- opts, args = self.parse_options(parameter_s,'sf', mode='list')
- if 'f' in opts:
- ans = True
- else:
- try:
- ans = self.shell.ask_yes_no(
- "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
- default='n')
- except StdinNotImplementedError:
- ans = True
- if not ans:
- print('Nothing done.')
- return
-
- if 's' in opts: # Soft reset
- user_ns = self.shell.user_ns
- for i in self.who_ls():
- del(user_ns[i])
- elif len(args) == 0: # Hard reset
- self.shell.reset(new_session = False)
-
- # reset in/out/dhist/array: previously extensinions/clearcmd.py
- ip = self.shell
- user_ns = self.shell.user_ns # local lookup, heavily used
-
- for target in args:
- target = target.lower() # make matches case insensitive
- if target == 'out':
- print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
- self.shell.displayhook.flush()
-
- elif target == 'in':
- print("Flushing input history")
- pc = self.shell.displayhook.prompt_count + 1
- for n in range(1, pc):
- key = '_i'+repr(n)
- user_ns.pop(key,None)
- user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
- hm = ip.history_manager
- # don't delete these, as %save and %macro depending on the
- # length of these lists to be preserved
- hm.input_hist_parsed[:] = [''] * pc
- hm.input_hist_raw[:] = [''] * pc
- # hm has internal machinery for _i,_ii,_iii, clear it out
- hm._i = hm._ii = hm._iii = hm._i00 = u''
-
- elif target == 'array':
- # Support cleaning up numpy arrays
- try:
- from numpy import ndarray
- # This must be done with items and not iteritems because
- # we're going to modify the dict in-place.
- for x,val in list(user_ns.items()):
- if isinstance(val,ndarray):
- del user_ns[x]
- except ImportError:
- print("reset array only works if Numpy is available.")
-
- elif target == 'dhist':
- print("Flushing directory history")
- del user_ns['_dh'][:]
-
- else:
- print("Don't know how to reset ", end=' ')
- print(target + ", please run `%reset?` for details")
-
- gc.collect()
-
- @line_magic
- def reset_selective(self, parameter_s=''):
- """Resets the namespace by removing names defined by the user.
-
- Input/Output history are left around in case you need them.
-
- %reset_selective [-f] regex
-
- No action is taken if regex is not included
-
- Options
- -f : force reset without asking for confirmation.
-
- See Also
- --------
- reset : invoked as ``%reset``
-
- Examples
- --------
-
- We first fully reset the namespace so your output looks identical to
- this example for pedagogical reasons; in practice you do not need a
- full reset::
-
- In [1]: %reset -f
-
- Now, with a clean namespace we can make a few variables and use
- ``%reset_selective`` to only delete names that match our regexp::
-
- In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
-
- In [3]: who_ls
- Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
-
- In [4]: %reset_selective -f b[2-3]m
-
- In [5]: who_ls
- Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
-
- In [6]: %reset_selective -f d
-
- In [7]: who_ls
- Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
-
- In [8]: %reset_selective -f c
-
- In [9]: who_ls
- Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
-
- In [10]: %reset_selective -f b
-
- In [11]: who_ls
- Out[11]: ['a']
-
- Notes
- -----
- Calling this magic from clients that do not implement standard input,
- such as the ipython notebook interface, will reset the namespace
- without confirmation.
- """
-
- opts, regex = self.parse_options(parameter_s,'f')
-
- if 'f' in opts:
- ans = True
- else:
- try:
- ans = self.shell.ask_yes_no(
- "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
- default='n')
- except StdinNotImplementedError:
- ans = True
- if not ans:
- print('Nothing done.')
- return
- user_ns = self.shell.user_ns
- if not regex:
- print('No regex pattern specified. Nothing done.')
- return
- else:
- try:
- m = re.compile(regex)
- except TypeError:
- raise TypeError('regex must be a string or compiled pattern')
- for i in self.who_ls():
- if m.search(i):
- del(user_ns[i])
-
- @line_magic
- def xdel(self, parameter_s=''):
- """Delete a variable, trying to clear it from anywhere that
- IPython's machinery has references to it. By default, this uses
- the identity of the named object in the user namespace to remove
- references held under other names. The object is also removed
- from the output history.
-
- Options
- -n : Delete the specified name from all namespaces, without
- checking their identity.
- """
- opts, varname = self.parse_options(parameter_s,'n')
- try:
- self.shell.del_var(varname, ('n' in opts))
- except (NameError, ValueError) as e:
- print(type(e).__name__ +": "+ str(e))
+"""Implementation of namespace-related magic functions.
+"""
+from __future__ import print_function
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012 The IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Stdlib
+import gc
+import re
+import sys
+
+# Our own packages
+from IPython.core import page
+from IPython.core.error import StdinNotImplementedError, UsageError
+from IPython.core.magic import Magics, magics_class, line_magic
+from IPython.testing.skipdoctest import skip_doctest
+from IPython.utils.encoding import DEFAULT_ENCODING
+from IPython.utils.openpy import read_py_file
+from IPython.utils.path import get_py_filename
+from IPython.utils.py3compat import unicode_type
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+
+@magics_class
+class NamespaceMagics(Magics):
+ """Magics to manage various aspects of the user's namespace.
+
+ These include listing variables, introspecting into them, etc.
+ """
+
+ @line_magic
+ def pinfo(self, parameter_s='', namespaces=None):
+ """Provide detailed information about an object.
+
+ '%pinfo object' is just a synonym for object? or ?object."""
+
+ #print 'pinfo par: <%s>' % parameter_s # dbg
+ # detail_level: 0 -> obj? , 1 -> obj??
+ detail_level = 0
+ # We need to detect if we got called as 'pinfo pinfo foo', which can
+ # happen if the user types 'pinfo foo?' at the cmd line.
+ pinfo,qmark1,oname,qmark2 = \
+ re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
+ if pinfo or qmark1 or qmark2:
+ detail_level = 1
+ if "*" in oname:
+ self.psearch(oname)
+ else:
+ self.shell._inspect('pinfo', oname, detail_level=detail_level,
+ namespaces=namespaces)
+
+ @line_magic
+ def pinfo2(self, parameter_s='', namespaces=None):
+ """Provide extra detailed information about an object.
+
+ '%pinfo2 object' is just a synonym for object?? or ??object."""
+ self.shell._inspect('pinfo', parameter_s, detail_level=1,
+ namespaces=namespaces)
+
+ @skip_doctest
+ @line_magic
+ def pdef(self, parameter_s='', namespaces=None):
+ """Print the call signature for any callable object.
+
+ If the object is a class, print the constructor information.
+
+ Examples
+ --------
+ ::
+
+ In [3]: %pdef urllib.urlopen
+ urllib.urlopen(url, data=None, proxies=None)
+ """
+ self.shell._inspect('pdef',parameter_s, namespaces)
+
+ @line_magic
+ def pdoc(self, parameter_s='', namespaces=None):
+ """Print the docstring for an object.
+
+ If the given object is a class, it will print both the class and the
+ constructor docstrings."""
+ self.shell._inspect('pdoc',parameter_s, namespaces)
+
+ @line_magic
+ def psource(self, parameter_s='', namespaces=None):
+ """Print (or run through pager) the source code for an object."""
+ if not parameter_s:
+ raise UsageError('Missing object name.')
+ self.shell._inspect('psource',parameter_s, namespaces)
+
+ @line_magic
+ def pfile(self, parameter_s='', namespaces=None):
+ """Print (or run through pager) the file where an object is defined.
+
+ The file opens at the line where the object definition begins. IPython
+ will honor the environment variable PAGER if set, and otherwise will
+ do its best to print the file in a convenient form.
+
+ If the given argument is not an object currently defined, IPython will
+ try to interpret it as a filename (automatically adding a .py extension
+ if needed). You can thus use %pfile as a syntax highlighting code
+ viewer."""
+
+ # first interpret argument as an object name
+ out = self.shell._inspect('pfile',parameter_s, namespaces)
+ # if not, try the input as a filename
+ if out == 'not found':
+ try:
+ filename = get_py_filename(parameter_s)
+ except IOError as msg:
+ print(msg)
+ return
+ page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
+
+ @line_magic
+ def psearch(self, parameter_s=''):
+ """Search for object in namespaces by wildcard.
+
+ %psearch [options] PATTERN [OBJECT TYPE]
+
+ Note: ? can be used as a synonym for %psearch, at the beginning or at
+ the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
+ rest of the command line must be unchanged (options come first), so
+ for example the following forms are equivalent
+
+ %psearch -i a* function
+ -i a* function?
+ ?-i a* function
+
+ Arguments:
+
+ PATTERN
+
+ where PATTERN is a string containing * as a wildcard similar to its
+ use in a shell. The pattern is matched in all namespaces on the
+ search path. By default objects starting with a single _ are not
+ matched, many IPython generated objects have a single
+ underscore. The default is case insensitive matching. Matching is
+ also done on the attributes of objects and not only on the objects
+ in a module.
+
+ [OBJECT TYPE]
+
+ Is the name of a python type from the types module. The name is
+ given in lowercase without the ending type, ex. StringType is
+ written string. By adding a type here only objects matching the
+ given type are matched. Using all here makes the pattern match all
+ types (this is the default).
+
+ Options:
+
+ -a: makes the pattern match even objects whose names start with a
+ single underscore. These names are normally omitted from the
+ search.
+
+ -i/-c: make the pattern case insensitive/sensitive. If neither of
+ these options are given, the default is read from your configuration
+ file, with the option ``InteractiveShell.wildcards_case_sensitive``.
+ If this option is not specified in your configuration file, IPython's
+ internal default is to do a case sensitive search.
+
+ -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
+ specify can be searched in any of the following namespaces:
+ 'builtin', 'user', 'user_global','internal', 'alias', where
+ 'builtin' and 'user' are the search defaults. Note that you should
+ not use quotes when specifying namespaces.
+
+ 'Builtin' contains the python module builtin, 'user' contains all
+ user data, 'alias' only contain the shell aliases and no python
+ objects, 'internal' contains objects used by IPython. The
+ 'user_global' namespace is only used by embedded IPython instances,
+ and it contains module-level globals. You can add namespaces to the
+ search with -s or exclude them with -e (these options can be given
+ more than once).
+
+ Examples
+ --------
+ ::
+
+ %psearch a* -> objects beginning with an a
+ %psearch -e builtin a* -> objects NOT in the builtin space starting in a
+ %psearch a* function -> all functions beginning with an a
+ %psearch re.e* -> objects beginning with an e in module re
+ %psearch r*.e* -> objects that start with e in modules starting in r
+ %psearch r*.* string -> all strings in modules beginning with r
+
+ Case sensitive search::
+
+ %psearch -c a* list all object beginning with lower case a
+
+ Show objects beginning with a single _::
+
+ %psearch -a _* list objects beginning with a single underscore
+ """
+ try:
+ parameter_s.encode('ascii')
+ except UnicodeEncodeError:
+ print('Python identifiers can only contain ascii characters.')
+ return
+
+ # default namespaces to be searched
+ def_search = ['user_local', 'user_global', 'builtin']
+
+ # Process options/args
+ opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
+ opt = opts.get
+ shell = self.shell
+ psearch = shell.inspector.psearch
+
+ # select case options
+ if 'i' in opts:
+ ignore_case = True
+ elif 'c' in opts:
+ ignore_case = False
+ else:
+ ignore_case = not shell.wildcards_case_sensitive
+
+ # Build list of namespaces to search from user options
+ def_search.extend(opt('s',[]))
+ ns_exclude = ns_exclude=opt('e',[])
+ ns_search = [nm for nm in def_search if nm not in ns_exclude]
+
+ # Call the actual search
+ try:
+ psearch(args,shell.ns_table,ns_search,
+ show_all=opt('a'),ignore_case=ignore_case)
+ except:
+ shell.showtraceback()
+
+ @skip_doctest
+ @line_magic
+ def who_ls(self, parameter_s=''):
+ """Return a sorted list of all interactive variables.
+
+ If arguments are given, only variables of types matching these
+ arguments are returned.
+
+ Examples
+ --------
+
+ Define two variables and list them with who_ls::
+
+ In [1]: alpha = 123
+
+ In [2]: beta = 'test'
+
+ In [3]: %who_ls
+ Out[3]: ['alpha', 'beta']
+
+ In [4]: %who_ls int
+ Out[4]: ['alpha']
+
+ In [5]: %who_ls str
+ Out[5]: ['beta']
+ """
+
+ user_ns = self.shell.user_ns
+ user_ns_hidden = self.shell.user_ns_hidden
+ nonmatching = object() # This can never be in user_ns
+ out = [ i for i in user_ns
+ if not i.startswith('_') \
+ and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
+
+ typelist = parameter_s.split()
+ if typelist:
+ typeset = set(typelist)
+ out = [i for i in out if type(user_ns[i]).__name__ in typeset]
+
+ out.sort()
+ return out
+
+ @skip_doctest
+ @line_magic
+ def who(self, parameter_s=''):
+ """Print all interactive variables, with some minimal formatting.
+
+ If any arguments are given, only variables whose type matches one of
+ these are printed. For example::
+
+ %who function str
+
+ will only list functions and strings, excluding all other types of
+ variables. To find the proper type names, simply use type(var) at a
+ command line to see how python prints type names. For example:
+
+ ::
+
+ In [1]: type('hello')\\
+ Out[1]: <type 'str'>
+
+ indicates that the type name for strings is 'str'.
+
+ ``%who`` always excludes executed names loaded through your configuration
+ file and things which are internal to IPython.
+
+ This is deliberate, as typically you may load many modules and the
+ purpose of %who is to show you only what you've manually defined.
+
+ Examples
+ --------
+
+ Define two variables and list them with who::
+
+ In [1]: alpha = 123
+
+ In [2]: beta = 'test'
+
+ In [3]: %who
+ alpha beta
+
+ In [4]: %who int
+ alpha
+
+ In [5]: %who str
+ beta
+ """
+
+ varlist = self.who_ls(parameter_s)
+ if not varlist:
+ if parameter_s:
+ print('No variables match your requested type.')
+ else:
+ print('Interactive namespace is empty.')
+ return
+
+ # if we have variables, move on...
+ count = 0
+ for i in varlist:
+ print(i+'\t', end=' ')
+ count += 1
+ if count > 8:
+ count = 0
+ print()
+ print()
+
+ @skip_doctest
+ @line_magic
+ def whos(self, parameter_s=''):
+ """Like %who, but gives some extra information about each variable.
+
+ The same type filtering of %who can be applied here.
+
+ For all variables, the type is printed. Additionally it prints:
+
+ - For {},[],(): their length.
+
+ - For numpy arrays, a summary with shape, number of
+ elements, typecode and size in memory.
+
+ - Everything else: a string representation, snipping their middle if
+ too long.
+
+ Examples
+ --------
+
+ Define two variables and list them with whos::
+
+ In [1]: alpha = 123
+
+ In [2]: beta = 'test'
+
+ In [3]: %whos
+ Variable Type Data/Info
+ --------------------------------
+ alpha int 123
+ beta str test
+ """
+
+ varnames = self.who_ls(parameter_s)
+ if not varnames:
+ if parameter_s:
+ print('No variables match your requested type.')
+ else:
+ print('Interactive namespace is empty.')
+ return
+
+ # if we have variables, move on...
+
+ # for these types, show len() instead of data:
+ seq_types = ['dict', 'list', 'tuple']
+
+ # for numpy arrays, display summary info
+ ndarray_type = None
+ if 'numpy' in sys.modules:
+ try:
+ from numpy import ndarray
+ except ImportError:
+ pass
+ else:
+ ndarray_type = ndarray.__name__
+
+ # Find all variable names and types so we can figure out column sizes
+
+ # some types are well known and can be shorter
+ abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
+ def type_name(v):
+ tn = type(v).__name__
+ return abbrevs.get(tn,tn)
+
+ varlist = [self.shell.user_ns[n] for n in varnames]
+
+ typelist = []
+ for vv in varlist:
+ tt = type_name(vv)
+
+ if tt=='instance':
+ typelist.append( abbrevs.get(str(vv.__class__),
+ str(vv.__class__)))
+ else:
+ typelist.append(tt)
+
+ # column labels and # of spaces as separator
+ varlabel = 'Variable'
+ typelabel = 'Type'
+ datalabel = 'Data/Info'
+ colsep = 3
+ # variable format strings
+ vformat = "{0:<{varwidth}}{1:<{typewidth}}"
+ aformat = "%s: %s elems, type `%s`, %s bytes"
+ # find the size of the columns to format the output nicely
+ varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
+ typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
+ # table header
+ print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
+ ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
+ # and the table itself
+ kb = 1024
+ Mb = 1048576 # kb**2
+ for vname,var,vtype in zip(varnames,varlist,typelist):
+ print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
+ if vtype in seq_types:
+ print("n="+str(len(var)))
+ elif vtype == ndarray_type:
+ vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
+ if vtype==ndarray_type:
+ # numpy
+ vsize = var.size
+ vbytes = vsize*var.itemsize
+ vdtype = var.dtype
+
+ if vbytes < 100000:
+ print(aformat % (vshape, vsize, vdtype, vbytes))
+ else:
+ print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
+ if vbytes < Mb:
+ print('(%s kb)' % (vbytes/kb,))
+ else:
+ print('(%s Mb)' % (vbytes/Mb,))
+ else:
+ try:
+ vstr = str(var)
+ except UnicodeEncodeError:
+ vstr = unicode_type(var).encode(DEFAULT_ENCODING,
+ 'backslashreplace')
+ except:
+ vstr = "<object with id %d (str() failed)>" % id(var)
+ vstr = vstr.replace('\n', '\\n')
+ if len(vstr) < 50:
+ print(vstr)
+ else:
+ print(vstr[:25] + "<...>" + vstr[-25:])
+
+ @line_magic
+ def reset(self, parameter_s=''):
+ """Resets the namespace by removing all names defined by the user, if
+ called without arguments, or by removing some types of objects, such
+ as everything currently in IPython's In[] and Out[] containers (see
+ the parameters for details).
+
+ Parameters
+ ----------
+ -f : force reset without asking for confirmation.
+
+ -s : 'Soft' reset: Only clears your namespace, leaving history intact.
+ References to objects may be kept. By default (without this option),
+ we do a 'hard' reset, giving you a new session and removing all
+ references to objects from the current session.
+
+ in : reset input history
+
+ out : reset output history
+
+ dhist : reset directory history
+
+ array : reset only variables that are NumPy arrays
+
+ See Also
+ --------
+ reset_selective : invoked as ``%reset_selective``
+
+ Examples
+ --------
+ ::
+
+ In [6]: a = 1
+
+ In [7]: a
+ Out[7]: 1
+
+ In [8]: 'a' in _ip.user_ns
+ Out[8]: True
+
+ In [9]: %reset -f
+
+ In [1]: 'a' in _ip.user_ns
+ Out[1]: False
+
+ In [2]: %reset -f in
+ Flushing input history
+
+ In [3]: %reset -f dhist in
+ Flushing directory history
+ Flushing input history
+
+ Notes
+ -----
+ Calling this magic from clients that do not implement standard input,
+ such as the ipython notebook interface, will reset the namespace
+ without confirmation.
+ """
+ opts, args = self.parse_options(parameter_s,'sf', mode='list')
+ if 'f' in opts:
+ ans = True
+ else:
+ try:
+ ans = self.shell.ask_yes_no(
+ "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
+ default='n')
+ except StdinNotImplementedError:
+ ans = True
+ if not ans:
+ print('Nothing done.')
+ return
+
+ if 's' in opts: # Soft reset
+ user_ns = self.shell.user_ns
+ for i in self.who_ls():
+ del(user_ns[i])
+ elif len(args) == 0: # Hard reset
+ self.shell.reset(new_session = False)
+
+ # reset in/out/dhist/array: previously extensinions/clearcmd.py
+ ip = self.shell
+ user_ns = self.shell.user_ns # local lookup, heavily used
+
+ for target in args:
+ target = target.lower() # make matches case insensitive
+ if target == 'out':
+ print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
+ self.shell.displayhook.flush()
+
+ elif target == 'in':
+ print("Flushing input history")
+ pc = self.shell.displayhook.prompt_count + 1
+ for n in range(1, pc):
+ key = '_i'+repr(n)
+ user_ns.pop(key,None)
+ user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
+ hm = ip.history_manager
+ # don't delete these, as %save and %macro depending on the
+ # length of these lists to be preserved
+ hm.input_hist_parsed[:] = [''] * pc
+ hm.input_hist_raw[:] = [''] * pc
+ # hm has internal machinery for _i,_ii,_iii, clear it out
+ hm._i = hm._ii = hm._iii = hm._i00 = u''
+
+ elif target == 'array':
+ # Support cleaning up numpy arrays
+ try:
+ from numpy import ndarray
+ # This must be done with items and not iteritems because
+ # we're going to modify the dict in-place.
+ for x,val in list(user_ns.items()):
+ if isinstance(val,ndarray):
+ del user_ns[x]
+ except ImportError:
+ print("reset array only works if Numpy is available.")
+
+ elif target == 'dhist':
+ print("Flushing directory history")
+ del user_ns['_dh'][:]
+
+ else:
+ print("Don't know how to reset ", end=' ')
+ print(target + ", please run `%reset?` for details")
+
+ gc.collect()
+
+ @line_magic
+ def reset_selective(self, parameter_s=''):
+ """Resets the namespace by removing names defined by the user.
+
+ Input/Output history are left around in case you need them.
+
+ %reset_selective [-f] regex
+
+ No action is taken if regex is not included
+
+ Options
+ -f : force reset without asking for confirmation.
+
+ See Also
+ --------
+ reset : invoked as ``%reset``
+
+ Examples
+ --------
+
+ We first fully reset the namespace so your output looks identical to
+ this example for pedagogical reasons; in practice you do not need a
+ full reset::
+
+ In [1]: %reset -f
+
+ Now, with a clean namespace we can make a few variables and use
+ ``%reset_selective`` to only delete names that match our regexp::
+
+ In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
+
+ In [3]: who_ls
+ Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
+
+ In [4]: %reset_selective -f b[2-3]m
+
+ In [5]: who_ls
+ Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
+
+ In [6]: %reset_selective -f d
+
+ In [7]: who_ls
+ Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
+
+ In [8]: %reset_selective -f c
+
+ In [9]: who_ls
+ Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
+
+ In [10]: %reset_selective -f b
+
+ In [11]: who_ls
+ Out[11]: ['a']
+
+ Notes
+ -----
+ Calling this magic from clients that do not implement standard input,
+ such as the ipython notebook interface, will reset the namespace
+ without confirmation.
+ """
+
+ opts, regex = self.parse_options(parameter_s,'f')
+
+ if 'f' in opts:
+ ans = True
+ else:
+ try:
+ ans = self.shell.ask_yes_no(
+ "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
+ default='n')
+ except StdinNotImplementedError:
+ ans = True
+ if not ans:
+ print('Nothing done.')
+ return
+ user_ns = self.shell.user_ns
+ if not regex:
+ print('No regex pattern specified. Nothing done.')
+ return
+ else:
+ try:
+ m = re.compile(regex)
+ except TypeError:
+ raise TypeError('regex must be a string or compiled pattern')
+ for i in self.who_ls():
+ if m.search(i):
+ del(user_ns[i])
+
+ @line_magic
+ def xdel(self, parameter_s=''):
+ """Delete a variable, trying to clear it from anywhere that
+ IPython's machinery has references to it. By default, this uses
+ the identity of the named object in the user namespace to remove
+ references held under other names. The object is also removed
+ from the output history.
+
+ Options
+ -n : Delete the specified name from all namespaces, without
+ checking their identity.
+ """
+ opts, varname = self.parse_options(parameter_s,'n')
+ try:
+ self.shell.del_var(varname, ('n' in opts))
+ except (NameError, ValueError) as e:
+ print(type(e).__name__ +": "+ str(e))
diff --git a/contrib/python/ipython/py2/IPython/core/magics/osm.py b/contrib/python/ipython/py2/IPython/core/magics/osm.py
index e4c3bbc7b6..352cf2d451 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/osm.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/osm.py
@@ -1,790 +1,790 @@
-"""Implementation of magic functions for interaction with the OS.
-
-Note: this module is named 'osm' instead of 'os' to avoid a collision with the
-builtin.
-"""
-from __future__ import print_function
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012 The IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Stdlib
-import io
-import os
-import re
-import sys
-from pprint import pformat
-
-# Our own packages
-from IPython.core import magic_arguments
-from IPython.core import oinspect
-from IPython.core import page
-from IPython.core.alias import AliasError, Alias
-from IPython.core.error import UsageError
-from IPython.core.magic import (
- Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
-)
-from IPython.testing.skipdoctest import skip_doctest
-from IPython.utils.openpy import source_to_unicode
-from IPython.utils.process import abbrev_cwd
-from IPython.utils import py3compat
-from IPython.utils.py3compat import unicode_type
-from IPython.utils.terminal import set_term_title
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-@magics_class
-class OSMagics(Magics):
- """Magics to interact with the underlying OS (shell-type functionality).
- """
-
- @skip_doctest
- @line_magic
- def alias(self, parameter_s=''):
- """Define an alias for a system command.
-
- '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
-
- Then, typing 'alias_name params' will execute the system command 'cmd
- params' (from your underlying operating system).
-
- Aliases have lower precedence than magic functions and Python normal
- variables, so if 'foo' is both a Python variable and an alias, the
- alias can not be executed until 'del foo' removes the Python variable.
-
- You can use the %l specifier in an alias definition to represent the
- whole line when the alias is called. For example::
-
- In [2]: alias bracket echo "Input in brackets: <%l>"
- In [3]: bracket hello world
- Input in brackets: <hello world>
-
- You can also define aliases with parameters using %s specifiers (one
- per parameter)::
-
- In [1]: alias parts echo first %s second %s
- In [2]: %parts A B
- first A second B
- In [3]: %parts A
- Incorrect number of arguments: 2 expected.
- parts is an alias to: 'echo first %s second %s'
-
- Note that %l and %s are mutually exclusive. You can only use one or
- the other in your aliases.
-
- Aliases expand Python variables just like system calls using ! or !!
- do: all expressions prefixed with '$' get expanded. For details of
- the semantic rules, see PEP-215:
- http://www.python.org/peps/pep-0215.html. This is the library used by
- IPython for variable expansion. If you want to access a true shell
- variable, an extra $ is necessary to prevent its expansion by
- IPython::
-
- In [6]: alias show echo
- In [7]: PATH='A Python string'
- In [8]: show $PATH
- A Python string
- In [9]: show $$PATH
- /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
-
- You can use the alias facility to acess all of $PATH. See the %rehashx
- function, which automatically creates aliases for the contents of your
- $PATH.
-
- If called with no parameters, %alias prints the current alias table."""
-
- par = parameter_s.strip()
- if not par:
- aliases = sorted(self.shell.alias_manager.aliases)
- # stored = self.shell.db.get('stored_aliases', {} )
- # for k, v in stored:
- # atab.append(k, v[0])
-
- print("Total number of aliases:", len(aliases))
- sys.stdout.flush()
- return aliases
-
- # Now try to define a new one
- try:
- alias,cmd = par.split(None, 1)
- except TypeError:
- print(oinspect.getdoc(self.alias))
- return
-
- try:
- self.shell.alias_manager.define_alias(alias, cmd)
- except AliasError as e:
- print(e)
- # end magic_alias
-
- @line_magic
- def unalias(self, parameter_s=''):
- """Remove an alias"""
-
- aname = parameter_s.strip()
- try:
- self.shell.alias_manager.undefine_alias(aname)
- except ValueError as e:
- print(e)
- return
-
- stored = self.shell.db.get('stored_aliases', {} )
- if aname in stored:
- print("Removing %stored alias",aname)
- del stored[aname]
- self.shell.db['stored_aliases'] = stored
-
- @line_magic
- def rehashx(self, parameter_s=''):
- """Update the alias table with all executable files in $PATH.
-
- rehashx explicitly checks that every entry in $PATH is a file
- with execute access (os.X_OK).
-
- Under Windows, it checks executability as a match against a
- '|'-separated string of extensions, stored in the IPython config
- variable win_exec_ext. This defaults to 'exe|com|bat'.
-
- This function also resets the root module cache of module completer,
- used on slow filesystems.
- """
- from IPython.core.alias import InvalidAliasError
-
- # for the benefit of module completer in ipy_completers.py
- del self.shell.db['rootmodules_cache']
-
- path = [os.path.abspath(os.path.expanduser(p)) for p in
- os.environ.get('PATH','').split(os.pathsep)]
-
- syscmdlist = []
- # Now define isexec in a cross platform manner.
- if os.name == 'posix':
- isexec = lambda fname:os.path.isfile(fname) and \
- os.access(fname,os.X_OK)
- else:
- try:
- winext = os.environ['pathext'].replace(';','|').replace('.','')
- except KeyError:
- winext = 'exe|com|bat|py'
- if 'py' not in winext:
- winext += '|py'
- execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
- isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
- savedir = py3compat.getcwd()
-
- # Now walk the paths looking for executables to alias.
- try:
- # write the whole loop for posix/Windows so we don't have an if in
- # the innermost part
- if os.name == 'posix':
- for pdir in path:
- try:
- os.chdir(pdir)
- dirlist = os.listdir(pdir)
- except OSError:
- continue
- for ff in dirlist:
- if isexec(ff):
- try:
- # Removes dots from the name since ipython
- # will assume names with dots to be python.
- if not self.shell.alias_manager.is_alias(ff):
- self.shell.alias_manager.define_alias(
- ff.replace('.',''), ff)
- except InvalidAliasError:
- pass
- else:
- syscmdlist.append(ff)
- else:
- no_alias = Alias.blacklist
- for pdir in path:
- try:
- os.chdir(pdir)
- dirlist = os.listdir(pdir)
- except OSError:
- continue
- for ff in dirlist:
- base, ext = os.path.splitext(ff)
- if isexec(ff) and base.lower() not in no_alias:
- if ext.lower() == '.exe':
- ff = base
- try:
- # Removes dots from the name since ipython
- # will assume names with dots to be python.
- self.shell.alias_manager.define_alias(
- base.lower().replace('.',''), ff)
- except InvalidAliasError:
- pass
- syscmdlist.append(ff)
- self.shell.db['syscmdlist'] = syscmdlist
- finally:
- os.chdir(savedir)
-
- @skip_doctest
- @line_magic
- def pwd(self, parameter_s=''):
- """Return the current working directory path.
-
- Examples
- --------
- ::
-
- In [9]: pwd
- Out[9]: '/home/tsuser/sprint/ipython'
- """
- return py3compat.getcwd()
-
- @skip_doctest
- @line_magic
- def cd(self, parameter_s=''):
- """Change the current working directory.
-
- This command automatically maintains an internal list of directories
- you visit during your IPython session, in the variable _dh. The
- command %dhist shows this history nicely formatted. You can also
- do 'cd -<tab>' to see directory history conveniently.
-
- Usage:
-
- cd 'dir': changes to directory 'dir'.
-
- cd -: changes to the last visited directory.
-
- cd -<n>: changes to the n-th directory in the directory history.
-
- cd --foo: change to directory that matches 'foo' in history
-
- cd -b <bookmark_name>: jump to a bookmark set by %bookmark
- (note: cd <bookmark_name> is enough if there is no
- directory <bookmark_name>, but a bookmark with the name exists.)
- 'cd -b <tab>' allows you to tab-complete bookmark names.
-
- Options:
-
- -q: quiet. Do not print the working directory after the cd command is
- executed. By default IPython's cd command does print this directory,
- since the default prompts do not display path information.
-
- Note that !cd doesn't work for this purpose because the shell where
- !command runs is immediately discarded after executing 'command'.
-
- Examples
- --------
- ::
-
- In [10]: cd parent/child
- /home/tsuser/parent/child
- """
-
- oldcwd = py3compat.getcwd()
- numcd = re.match(r'(-)(\d+)$',parameter_s)
- # jump in directory history by number
- if numcd:
- nn = int(numcd.group(2))
- try:
- ps = self.shell.user_ns['_dh'][nn]
- except IndexError:
- print('The requested directory does not exist in history.')
- return
- else:
- opts = {}
- elif parameter_s.startswith('--'):
- ps = None
- fallback = None
- pat = parameter_s[2:]
- dh = self.shell.user_ns['_dh']
- # first search only by basename (last component)
- for ent in reversed(dh):
- if pat in os.path.basename(ent) and os.path.isdir(ent):
- ps = ent
- break
-
- if fallback is None and pat in ent and os.path.isdir(ent):
- fallback = ent
-
- # if we have no last part match, pick the first full path match
- if ps is None:
- ps = fallback
-
- if ps is None:
- print("No matching entry in directory history")
- return
- else:
- opts = {}
-
-
- else:
+"""Implementation of magic functions for interaction with the OS.
+
+Note: this module is named 'osm' instead of 'os' to avoid a collision with the
+builtin.
+"""
+from __future__ import print_function
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012 The IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Stdlib
+import io
+import os
+import re
+import sys
+from pprint import pformat
+
+# Our own packages
+from IPython.core import magic_arguments
+from IPython.core import oinspect
+from IPython.core import page
+from IPython.core.alias import AliasError, Alias
+from IPython.core.error import UsageError
+from IPython.core.magic import (
+ Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
+)
+from IPython.testing.skipdoctest import skip_doctest
+from IPython.utils.openpy import source_to_unicode
+from IPython.utils.process import abbrev_cwd
+from IPython.utils import py3compat
+from IPython.utils.py3compat import unicode_type
+from IPython.utils.terminal import set_term_title
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+@magics_class
+class OSMagics(Magics):
+ """Magics to interact with the underlying OS (shell-type functionality).
+ """
+
+ @skip_doctest
+ @line_magic
+ def alias(self, parameter_s=''):
+ """Define an alias for a system command.
+
+ '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
+
+ Then, typing 'alias_name params' will execute the system command 'cmd
+ params' (from your underlying operating system).
+
+ Aliases have lower precedence than magic functions and Python normal
+ variables, so if 'foo' is both a Python variable and an alias, the
+ alias can not be executed until 'del foo' removes the Python variable.
+
+ You can use the %l specifier in an alias definition to represent the
+ whole line when the alias is called. For example::
+
+ In [2]: alias bracket echo "Input in brackets: <%l>"
+ In [3]: bracket hello world
+ Input in brackets: <hello world>
+
+ You can also define aliases with parameters using %s specifiers (one
+ per parameter)::
+
+ In [1]: alias parts echo first %s second %s
+ In [2]: %parts A B
+ first A second B
+ In [3]: %parts A
+ Incorrect number of arguments: 2 expected.
+ parts is an alias to: 'echo first %s second %s'
+
+ Note that %l and %s are mutually exclusive. You can only use one or
+ the other in your aliases.
+
+ Aliases expand Python variables just like system calls using ! or !!
+ do: all expressions prefixed with '$' get expanded. For details of
+ the semantic rules, see PEP-215:
+ http://www.python.org/peps/pep-0215.html. This is the library used by
+ IPython for variable expansion. If you want to access a true shell
+ variable, an extra $ is necessary to prevent its expansion by
+ IPython::
+
+ In [6]: alias show echo
+ In [7]: PATH='A Python string'
+ In [8]: show $PATH
+ A Python string
+ In [9]: show $$PATH
+ /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
+
+ You can use the alias facility to acess all of $PATH. See the %rehashx
+ function, which automatically creates aliases for the contents of your
+ $PATH.
+
+ If called with no parameters, %alias prints the current alias table."""
+
+ par = parameter_s.strip()
+ if not par:
+ aliases = sorted(self.shell.alias_manager.aliases)
+ # stored = self.shell.db.get('stored_aliases', {} )
+ # for k, v in stored:
+ # atab.append(k, v[0])
+
+ print("Total number of aliases:", len(aliases))
+ sys.stdout.flush()
+ return aliases
+
+ # Now try to define a new one
+ try:
+ alias,cmd = par.split(None, 1)
+ except TypeError:
+ print(oinspect.getdoc(self.alias))
+ return
+
+ try:
+ self.shell.alias_manager.define_alias(alias, cmd)
+ except AliasError as e:
+ print(e)
+ # end magic_alias
+
+ @line_magic
+ def unalias(self, parameter_s=''):
+ """Remove an alias"""
+
+ aname = parameter_s.strip()
+ try:
+ self.shell.alias_manager.undefine_alias(aname)
+ except ValueError as e:
+ print(e)
+ return
+
+ stored = self.shell.db.get('stored_aliases', {} )
+ if aname in stored:
+ print("Removing %stored alias",aname)
+ del stored[aname]
+ self.shell.db['stored_aliases'] = stored
+
+ @line_magic
+ def rehashx(self, parameter_s=''):
+ """Update the alias table with all executable files in $PATH.
+
+ rehashx explicitly checks that every entry in $PATH is a file
+ with execute access (os.X_OK).
+
+ Under Windows, it checks executability as a match against a
+ '|'-separated string of extensions, stored in the IPython config
+ variable win_exec_ext. This defaults to 'exe|com|bat'.
+
+ This function also resets the root module cache of module completer,
+ used on slow filesystems.
+ """
+ from IPython.core.alias import InvalidAliasError
+
+ # for the benefit of module completer in ipy_completers.py
+ del self.shell.db['rootmodules_cache']
+
+ path = [os.path.abspath(os.path.expanduser(p)) for p in
+ os.environ.get('PATH','').split(os.pathsep)]
+
+ syscmdlist = []
+ # Now define isexec in a cross platform manner.
+ if os.name == 'posix':
+ isexec = lambda fname:os.path.isfile(fname) and \
+ os.access(fname,os.X_OK)
+ else:
+ try:
+ winext = os.environ['pathext'].replace(';','|').replace('.','')
+ except KeyError:
+ winext = 'exe|com|bat|py'
+ if 'py' not in winext:
+ winext += '|py'
+ execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
+ isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
+ savedir = py3compat.getcwd()
+
+ # Now walk the paths looking for executables to alias.
+ try:
+ # write the whole loop for posix/Windows so we don't have an if in
+ # the innermost part
+ if os.name == 'posix':
+ for pdir in path:
+ try:
+ os.chdir(pdir)
+ dirlist = os.listdir(pdir)
+ except OSError:
+ continue
+ for ff in dirlist:
+ if isexec(ff):
+ try:
+ # Removes dots from the name since ipython
+ # will assume names with dots to be python.
+ if not self.shell.alias_manager.is_alias(ff):
+ self.shell.alias_manager.define_alias(
+ ff.replace('.',''), ff)
+ except InvalidAliasError:
+ pass
+ else:
+ syscmdlist.append(ff)
+ else:
+ no_alias = Alias.blacklist
+ for pdir in path:
+ try:
+ os.chdir(pdir)
+ dirlist = os.listdir(pdir)
+ except OSError:
+ continue
+ for ff in dirlist:
+ base, ext = os.path.splitext(ff)
+ if isexec(ff) and base.lower() not in no_alias:
+ if ext.lower() == '.exe':
+ ff = base
+ try:
+ # Removes dots from the name since ipython
+ # will assume names with dots to be python.
+ self.shell.alias_manager.define_alias(
+ base.lower().replace('.',''), ff)
+ except InvalidAliasError:
+ pass
+ syscmdlist.append(ff)
+ self.shell.db['syscmdlist'] = syscmdlist
+ finally:
+ os.chdir(savedir)
+
+ @skip_doctest
+ @line_magic
+ def pwd(self, parameter_s=''):
+ """Return the current working directory path.
+
+ Examples
+ --------
+ ::
+
+ In [9]: pwd
+ Out[9]: '/home/tsuser/sprint/ipython'
+ """
+ return py3compat.getcwd()
+
+ @skip_doctest
+ @line_magic
+ def cd(self, parameter_s=''):
+ """Change the current working directory.
+
+ This command automatically maintains an internal list of directories
+ you visit during your IPython session, in the variable _dh. The
+ command %dhist shows this history nicely formatted. You can also
+ do 'cd -<tab>' to see directory history conveniently.
+
+ Usage:
+
+ cd 'dir': changes to directory 'dir'.
+
+ cd -: changes to the last visited directory.
+
+ cd -<n>: changes to the n-th directory in the directory history.
+
+ cd --foo: change to directory that matches 'foo' in history
+
+ cd -b <bookmark_name>: jump to a bookmark set by %bookmark
+ (note: cd <bookmark_name> is enough if there is no
+ directory <bookmark_name>, but a bookmark with the name exists.)
+ 'cd -b <tab>' allows you to tab-complete bookmark names.
+
+ Options:
+
+ -q: quiet. Do not print the working directory after the cd command is
+ executed. By default IPython's cd command does print this directory,
+ since the default prompts do not display path information.
+
+ Note that !cd doesn't work for this purpose because the shell where
+ !command runs is immediately discarded after executing 'command'.
+
+ Examples
+ --------
+ ::
+
+ In [10]: cd parent/child
+ /home/tsuser/parent/child
+ """
+
+ oldcwd = py3compat.getcwd()
+ numcd = re.match(r'(-)(\d+)$',parameter_s)
+ # jump in directory history by number
+ if numcd:
+ nn = int(numcd.group(2))
+ try:
+ ps = self.shell.user_ns['_dh'][nn]
+ except IndexError:
+ print('The requested directory does not exist in history.')
+ return
+ else:
+ opts = {}
+ elif parameter_s.startswith('--'):
+ ps = None
+ fallback = None
+ pat = parameter_s[2:]
+ dh = self.shell.user_ns['_dh']
+ # first search only by basename (last component)
+ for ent in reversed(dh):
+ if pat in os.path.basename(ent) and os.path.isdir(ent):
+ ps = ent
+ break
+
+ if fallback is None and pat in ent and os.path.isdir(ent):
+ fallback = ent
+
+ # if we have no last part match, pick the first full path match
+ if ps is None:
+ ps = fallback
+
+ if ps is None:
+ print("No matching entry in directory history")
+ return
+ else:
+ opts = {}
+
+
+ else:
opts, ps = self.parse_options(parameter_s, 'qb', mode='string')
- # jump to previous
- if ps == '-':
- try:
- ps = self.shell.user_ns['_dh'][-2]
- except IndexError:
- raise UsageError('%cd -: No previous directory to change to.')
- # jump to bookmark if needed
- else:
- if not os.path.isdir(ps) or 'b' in opts:
- bkms = self.shell.db.get('bookmarks', {})
-
- if ps in bkms:
- target = bkms[ps]
- print('(bookmark:%s) -> %s' % (ps, target))
- ps = target
- else:
- if 'b' in opts:
- raise UsageError("Bookmark '%s' not found. "
- "Use '%%bookmark -l' to see your bookmarks." % ps)
-
- # at this point ps should point to the target dir
- if ps:
- try:
- os.chdir(os.path.expanduser(ps))
- if hasattr(self.shell, 'term_title') and self.shell.term_title:
- set_term_title('IPython: ' + abbrev_cwd())
- except OSError:
- print(sys.exc_info()[1])
- else:
- cwd = py3compat.getcwd()
- dhist = self.shell.user_ns['_dh']
- if oldcwd != cwd:
- dhist.append(cwd)
- self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
-
- else:
- os.chdir(self.shell.home_dir)
- if hasattr(self.shell, 'term_title') and self.shell.term_title:
- set_term_title('IPython: ' + '~')
- cwd = py3compat.getcwd()
- dhist = self.shell.user_ns['_dh']
-
- if oldcwd != cwd:
- dhist.append(cwd)
- self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
- if not 'q' in opts and self.shell.user_ns['_dh']:
- print(self.shell.user_ns['_dh'][-1])
-
- @line_magic
- def env(self, parameter_s=''):
- """Get, set, or list environment variables.
-
- Usage:\\
-
- %env: lists all environment variables/values
- %env var: get value for var
- %env var val: set value for var
- %env var=val: set value for var
- %env var=$val: set value for var, using python expansion if possible
- """
- if parameter_s.strip():
- split = '=' if '=' in parameter_s else ' '
- bits = parameter_s.split(split)
- if len(bits) == 1:
- key = parameter_s.strip()
- if key in os.environ:
- return os.environ[key]
- else:
- err = "Environment does not have key: {0}".format(key)
- raise UsageError(err)
- if len(bits) > 1:
- return self.set_env(parameter_s)
- return dict(os.environ)
-
- @line_magic
- def set_env(self, parameter_s):
- """Set environment variables. Assumptions are that either "val" is a
- name in the user namespace, or val is something that evaluates to a
- string.
-
- Usage:\\
- %set_env var val: set value for var
- %set_env var=val: set value for var
- %set_env var=$val: set value for var, using python expansion if possible
- """
- split = '=' if '=' in parameter_s else ' '
- bits = parameter_s.split(split, 1)
- if not parameter_s.strip() or len(bits)<2:
- raise UsageError("usage is 'set_env var=val'")
- var = bits[0].strip()
- val = bits[1].strip()
- if re.match(r'.*\s.*', var):
- # an environment variable with whitespace is almost certainly
- # not what the user intended. what's more likely is the wrong
- # split was chosen, ie for "set_env cmd_args A=B", we chose
- # '=' for the split and should have chosen ' '. to get around
- # this, users should just assign directly to os.environ or use
- # standard magic {var} expansion.
- err = "refusing to set env var with whitespace: '{0}'"
- err = err.format(val)
- raise UsageError(err)
- os.environ[py3compat.cast_bytes_py2(var)] = py3compat.cast_bytes_py2(val)
- print('env: {0}={1}'.format(var,val))
-
- @line_magic
- def pushd(self, parameter_s=''):
- """Place the current dir on stack and change directory.
-
- Usage:\\
- %pushd ['dirname']
- """
-
- dir_s = self.shell.dir_stack
+ # jump to previous
+ if ps == '-':
+ try:
+ ps = self.shell.user_ns['_dh'][-2]
+ except IndexError:
+ raise UsageError('%cd -: No previous directory to change to.')
+ # jump to bookmark if needed
+ else:
+ if not os.path.isdir(ps) or 'b' in opts:
+ bkms = self.shell.db.get('bookmarks', {})
+
+ if ps in bkms:
+ target = bkms[ps]
+ print('(bookmark:%s) -> %s' % (ps, target))
+ ps = target
+ else:
+ if 'b' in opts:
+ raise UsageError("Bookmark '%s' not found. "
+ "Use '%%bookmark -l' to see your bookmarks." % ps)
+
+ # at this point ps should point to the target dir
+ if ps:
+ try:
+ os.chdir(os.path.expanduser(ps))
+ if hasattr(self.shell, 'term_title') and self.shell.term_title:
+ set_term_title('IPython: ' + abbrev_cwd())
+ except OSError:
+ print(sys.exc_info()[1])
+ else:
+ cwd = py3compat.getcwd()
+ dhist = self.shell.user_ns['_dh']
+ if oldcwd != cwd:
+ dhist.append(cwd)
+ self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
+
+ else:
+ os.chdir(self.shell.home_dir)
+ if hasattr(self.shell, 'term_title') and self.shell.term_title:
+ set_term_title('IPython: ' + '~')
+ cwd = py3compat.getcwd()
+ dhist = self.shell.user_ns['_dh']
+
+ if oldcwd != cwd:
+ dhist.append(cwd)
+ self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
+ if not 'q' in opts and self.shell.user_ns['_dh']:
+ print(self.shell.user_ns['_dh'][-1])
+
+ @line_magic
+ def env(self, parameter_s=''):
+ """Get, set, or list environment variables.
+
+ Usage:\\
+
+ %env: lists all environment variables/values
+ %env var: get value for var
+ %env var val: set value for var
+ %env var=val: set value for var
+ %env var=$val: set value for var, using python expansion if possible
+ """
+ if parameter_s.strip():
+ split = '=' if '=' in parameter_s else ' '
+ bits = parameter_s.split(split)
+ if len(bits) == 1:
+ key = parameter_s.strip()
+ if key in os.environ:
+ return os.environ[key]
+ else:
+ err = "Environment does not have key: {0}".format(key)
+ raise UsageError(err)
+ if len(bits) > 1:
+ return self.set_env(parameter_s)
+ return dict(os.environ)
+
+ @line_magic
+ def set_env(self, parameter_s):
+ """Set environment variables. Assumptions are that either "val" is a
+ name in the user namespace, or val is something that evaluates to a
+ string.
+
+ Usage:\\
+ %set_env var val: set value for var
+ %set_env var=val: set value for var
+ %set_env var=$val: set value for var, using python expansion if possible
+ """
+ split = '=' if '=' in parameter_s else ' '
+ bits = parameter_s.split(split, 1)
+ if not parameter_s.strip() or len(bits)<2:
+ raise UsageError("usage is 'set_env var=val'")
+ var = bits[0].strip()
+ val = bits[1].strip()
+ if re.match(r'.*\s.*', var):
+ # an environment variable with whitespace is almost certainly
+ # not what the user intended. what's more likely is the wrong
+ # split was chosen, ie for "set_env cmd_args A=B", we chose
+ # '=' for the split and should have chosen ' '. to get around
+ # this, users should just assign directly to os.environ or use
+ # standard magic {var} expansion.
+ err = "refusing to set env var with whitespace: '{0}'"
+ err = err.format(val)
+ raise UsageError(err)
+ os.environ[py3compat.cast_bytes_py2(var)] = py3compat.cast_bytes_py2(val)
+ print('env: {0}={1}'.format(var,val))
+
+ @line_magic
+ def pushd(self, parameter_s=''):
+ """Place the current dir on stack and change directory.
+
+ Usage:\\
+ %pushd ['dirname']
+ """
+
+ dir_s = self.shell.dir_stack
tgt = os.path.expanduser(parameter_s)
- cwd = py3compat.getcwd().replace(self.shell.home_dir,'~')
- if tgt:
- self.cd(parameter_s)
- dir_s.insert(0,cwd)
- return self.shell.magic('dirs')
-
- @line_magic
- def popd(self, parameter_s=''):
- """Change to directory popped off the top of the stack.
- """
- if not self.shell.dir_stack:
- raise UsageError("%popd on empty stack")
- top = self.shell.dir_stack.pop(0)
- self.cd(top)
- print("popd ->",top)
-
- @line_magic
- def dirs(self, parameter_s=''):
- """Return the current directory stack."""
-
- return self.shell.dir_stack
-
- @line_magic
- def dhist(self, parameter_s=''):
- """Print your history of visited directories.
-
- %dhist -> print full history\\
- %dhist n -> print last n entries only\\
- %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\\
-
- This history is automatically maintained by the %cd command, and
- always available as the global list variable _dh. You can use %cd -<n>
- to go to directory number <n>.
-
- Note that most of time, you should view directory history by entering
- cd -<TAB>.
-
- """
-
- dh = self.shell.user_ns['_dh']
- if parameter_s:
- try:
- args = map(int,parameter_s.split())
- except:
- self.arg_err(self.dhist)
- return
- if len(args) == 1:
- ini,fin = max(len(dh)-(args[0]),0),len(dh)
- elif len(args) == 2:
- ini,fin = args
- fin = min(fin, len(dh))
- else:
- self.arg_err(self.dhist)
- return
- else:
- ini,fin = 0,len(dh)
- print('Directory history (kept in _dh)')
- for i in range(ini, fin):
- print("%d: %s" % (i, dh[i]))
-
- @skip_doctest
- @line_magic
- def sc(self, parameter_s=''):
- """Shell capture - run shell command and capture output (DEPRECATED use !).
-
- DEPRECATED. Suboptimal, retained for backwards compatibility.
-
- You should use the form 'var = !command' instead. Example:
-
- "%sc -l myfiles = ls ~" should now be written as
-
- "myfiles = !ls ~"
-
- myfiles.s, myfiles.l and myfiles.n still apply as documented
- below.
-
- --
- %sc [options] varname=command
-
- IPython will run the given command using commands.getoutput(), and
- will then update the user's interactive namespace with a variable
- called varname, containing the value of the call. Your command can
- contain shell wildcards, pipes, etc.
-
- The '=' sign in the syntax is mandatory, and the variable name you
- supply must follow Python's standard conventions for valid names.
-
- (A special format without variable name exists for internal use)
-
- Options:
-
- -l: list output. Split the output on newlines into a list before
- assigning it to the given variable. By default the output is stored
- as a single string.
-
- -v: verbose. Print the contents of the variable.
-
- In most cases you should not need to split as a list, because the
- returned value is a special type of string which can automatically
- provide its contents either as a list (split on newlines) or as a
- space-separated string. These are convenient, respectively, either
- for sequential processing or to be passed to a shell command.
-
- For example::
-
- # Capture into variable a
- In [1]: sc a=ls *py
-
- # a is a string with embedded newlines
- In [2]: a
- Out[2]: 'setup.py\\nwin32_manual_post_install.py'
-
- # which can be seen as a list:
- In [3]: a.l
- Out[3]: ['setup.py', 'win32_manual_post_install.py']
-
- # or as a whitespace-separated string:
- In [4]: a.s
- Out[4]: 'setup.py win32_manual_post_install.py'
-
- # a.s is useful to pass as a single command line:
- In [5]: !wc -l $a.s
- 146 setup.py
- 130 win32_manual_post_install.py
- 276 total
-
- # while the list form is useful to loop over:
- In [6]: for f in a.l:
- ...: !wc -l $f
- ...:
- 146 setup.py
- 130 win32_manual_post_install.py
-
- Similarly, the lists returned by the -l option are also special, in
- the sense that you can equally invoke the .s attribute on them to
- automatically get a whitespace-separated string from their contents::
-
- In [7]: sc -l b=ls *py
-
- In [8]: b
- Out[8]: ['setup.py', 'win32_manual_post_install.py']
-
- In [9]: b.s
- Out[9]: 'setup.py win32_manual_post_install.py'
-
- In summary, both the lists and strings used for output capture have
- the following special attributes::
-
- .l (or .list) : value as list.
- .n (or .nlstr): value as newline-separated string.
- .s (or .spstr): value as space-separated string.
- """
-
- opts,args = self.parse_options(parameter_s, 'lv')
- # Try to get a variable name and command to run
- try:
- # the variable name must be obtained from the parse_options
- # output, which uses shlex.split to strip options out.
- var,_ = args.split('=', 1)
- var = var.strip()
- # But the command has to be extracted from the original input
- # parameter_s, not on what parse_options returns, to avoid the
- # quote stripping which shlex.split performs on it.
- _,cmd = parameter_s.split('=', 1)
- except ValueError:
- var,cmd = '',''
- # If all looks ok, proceed
- split = 'l' in opts
- out = self.shell.getoutput(cmd, split=split)
- if 'v' in opts:
- print('%s ==\n%s' % (var, pformat(out)))
- if var:
- self.shell.user_ns.update({var:out})
- else:
- return out
-
- @line_cell_magic
- def sx(self, line='', cell=None):
- """Shell execute - run shell command and capture output (!! is short-hand).
-
- %sx command
-
- IPython will run the given command using commands.getoutput(), and
- return the result formatted as a list (split on '\\n'). Since the
- output is _returned_, it will be stored in ipython's regular output
- cache Out[N] and in the '_N' automatic variables.
-
- Notes:
-
- 1) If an input line begins with '!!', then %sx is automatically
- invoked. That is, while::
-
- !ls
-
- causes ipython to simply issue system('ls'), typing::
-
- !!ls
-
- is a shorthand equivalent to::
-
- %sx ls
-
- 2) %sx differs from %sc in that %sx automatically splits into a list,
- like '%sc -l'. The reason for this is to make it as easy as possible
- to process line-oriented shell output via further python commands.
- %sc is meant to provide much finer control, but requires more
- typing.
-
- 3) Just like %sc -l, this is a list with special attributes:
- ::
-
- .l (or .list) : value as list.
- .n (or .nlstr): value as newline-separated string.
- .s (or .spstr): value as whitespace-separated string.
-
- This is very useful when trying to use such lists as arguments to
- system commands."""
-
- if cell is None:
- # line magic
- return self.shell.getoutput(line)
- else:
- opts,args = self.parse_options(line, '', 'out=')
- output = self.shell.getoutput(cell)
- out_name = opts.get('out', opts.get('o'))
- if out_name:
- self.shell.user_ns[out_name] = output
- else:
- return output
-
- system = line_cell_magic('system')(sx)
- bang = cell_magic('!')(sx)
-
- @line_magic
- def bookmark(self, parameter_s=''):
- """Manage IPython's bookmark system.
-
- %bookmark <name> - set bookmark to current dir
- %bookmark <name> <dir> - set bookmark to <dir>
- %bookmark -l - list all bookmarks
- %bookmark -d <name> - remove bookmark
- %bookmark -r - remove all bookmarks
-
- You can later on access a bookmarked folder with::
-
- %cd -b <name>
-
- or simply '%cd <name>' if there is no directory called <name> AND
- there is such a bookmark defined.
-
- Your bookmarks persist through IPython sessions, but they are
- associated with each profile."""
-
- opts,args = self.parse_options(parameter_s,'drl',mode='list')
- if len(args) > 2:
- raise UsageError("%bookmark: too many arguments")
-
- bkms = self.shell.db.get('bookmarks',{})
-
- if 'd' in opts:
- try:
- todel = args[0]
- except IndexError:
- raise UsageError(
- "%bookmark -d: must provide a bookmark to delete")
- else:
- try:
- del bkms[todel]
- except KeyError:
- raise UsageError(
- "%%bookmark -d: Can't delete bookmark '%s'" % todel)
-
- elif 'r' in opts:
- bkms = {}
- elif 'l' in opts:
- bks = sorted(bkms)
- if bks:
- size = max(map(len, bks))
- else:
- size = 0
- fmt = '%-'+str(size)+'s -> %s'
- print('Current bookmarks:')
- for bk in bks:
- print(fmt % (bk, bkms[bk]))
- else:
- if not args:
- raise UsageError("%bookmark: You must specify the bookmark name")
- elif len(args)==1:
- bkms[args[0]] = py3compat.getcwd()
- elif len(args)==2:
- bkms[args[0]] = args[1]
- self.shell.db['bookmarks'] = bkms
-
- @line_magic
- def pycat(self, parameter_s=''):
- """Show a syntax-highlighted file through a pager.
-
- This magic is similar to the cat utility, but it will assume the file
- to be Python source and will show it with syntax highlighting.
-
- This magic command can either take a local filename, an url,
- an history range (see %history) or a macro as argument ::
-
- %pycat myscript.py
- %pycat 7-27
- %pycat myMacro
- %pycat http://www.example.com/myscript.py
- """
- if not parameter_s:
- raise UsageError('Missing filename, URL, input history range, '
- 'or macro.')
-
- try :
- cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
- except (ValueError, IOError):
- print("Error: no such file, variable, URL, history range or macro")
- return
-
- page.page(self.shell.pycolorize(source_to_unicode(cont)))
-
- @magic_arguments.magic_arguments()
- @magic_arguments.argument(
- '-a', '--append', action='store_true', default=False,
- help='Append contents of the cell to an existing file. '
- 'The file will be created if it does not exist.'
- )
- @magic_arguments.argument(
- 'filename', type=unicode_type,
- help='file to write'
- )
- @cell_magic
- def writefile(self, line, cell):
- """Write the contents of the cell to a file.
-
- The file will be overwritten unless the -a (--append) flag is specified.
- """
- args = magic_arguments.parse_argstring(self.writefile, line)
+ cwd = py3compat.getcwd().replace(self.shell.home_dir,'~')
+ if tgt:
+ self.cd(parameter_s)
+ dir_s.insert(0,cwd)
+ return self.shell.magic('dirs')
+
+ @line_magic
+ def popd(self, parameter_s=''):
+ """Change to directory popped off the top of the stack.
+ """
+ if not self.shell.dir_stack:
+ raise UsageError("%popd on empty stack")
+ top = self.shell.dir_stack.pop(0)
+ self.cd(top)
+ print("popd ->",top)
+
+ @line_magic
+ def dirs(self, parameter_s=''):
+ """Return the current directory stack."""
+
+ return self.shell.dir_stack
+
+ @line_magic
+ def dhist(self, parameter_s=''):
+ """Print your history of visited directories.
+
+ %dhist -> print full history\\
+ %dhist n -> print last n entries only\\
+ %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\\
+
+ This history is automatically maintained by the %cd command, and
+ always available as the global list variable _dh. You can use %cd -<n>
+ to go to directory number <n>.
+
+ Note that most of time, you should view directory history by entering
+ cd -<TAB>.
+
+ """
+
+ dh = self.shell.user_ns['_dh']
+ if parameter_s:
+ try:
+ args = map(int,parameter_s.split())
+ except:
+ self.arg_err(self.dhist)
+ return
+ if len(args) == 1:
+ ini,fin = max(len(dh)-(args[0]),0),len(dh)
+ elif len(args) == 2:
+ ini,fin = args
+ fin = min(fin, len(dh))
+ else:
+ self.arg_err(self.dhist)
+ return
+ else:
+ ini,fin = 0,len(dh)
+ print('Directory history (kept in _dh)')
+ for i in range(ini, fin):
+ print("%d: %s" % (i, dh[i]))
+
+ @skip_doctest
+ @line_magic
+ def sc(self, parameter_s=''):
+ """Shell capture - run shell command and capture output (DEPRECATED use !).
+
+ DEPRECATED. Suboptimal, retained for backwards compatibility.
+
+ You should use the form 'var = !command' instead. Example:
+
+ "%sc -l myfiles = ls ~" should now be written as
+
+ "myfiles = !ls ~"
+
+ myfiles.s, myfiles.l and myfiles.n still apply as documented
+ below.
+
+ --
+ %sc [options] varname=command
+
+ IPython will run the given command using commands.getoutput(), and
+ will then update the user's interactive namespace with a variable
+ called varname, containing the value of the call. Your command can
+ contain shell wildcards, pipes, etc.
+
+ The '=' sign in the syntax is mandatory, and the variable name you
+ supply must follow Python's standard conventions for valid names.
+
+ (A special format without variable name exists for internal use)
+
+ Options:
+
+ -l: list output. Split the output on newlines into a list before
+ assigning it to the given variable. By default the output is stored
+ as a single string.
+
+ -v: verbose. Print the contents of the variable.
+
+ In most cases you should not need to split as a list, because the
+ returned value is a special type of string which can automatically
+ provide its contents either as a list (split on newlines) or as a
+ space-separated string. These are convenient, respectively, either
+ for sequential processing or to be passed to a shell command.
+
+ For example::
+
+ # Capture into variable a
+ In [1]: sc a=ls *py
+
+ # a is a string with embedded newlines
+ In [2]: a
+ Out[2]: 'setup.py\\nwin32_manual_post_install.py'
+
+ # which can be seen as a list:
+ In [3]: a.l
+ Out[3]: ['setup.py', 'win32_manual_post_install.py']
+
+ # or as a whitespace-separated string:
+ In [4]: a.s
+ Out[4]: 'setup.py win32_manual_post_install.py'
+
+ # a.s is useful to pass as a single command line:
+ In [5]: !wc -l $a.s
+ 146 setup.py
+ 130 win32_manual_post_install.py
+ 276 total
+
+ # while the list form is useful to loop over:
+ In [6]: for f in a.l:
+ ...: !wc -l $f
+ ...:
+ 146 setup.py
+ 130 win32_manual_post_install.py
+
+ Similarly, the lists returned by the -l option are also special, in
+ the sense that you can equally invoke the .s attribute on them to
+ automatically get a whitespace-separated string from their contents::
+
+ In [7]: sc -l b=ls *py
+
+ In [8]: b
+ Out[8]: ['setup.py', 'win32_manual_post_install.py']
+
+ In [9]: b.s
+ Out[9]: 'setup.py win32_manual_post_install.py'
+
+ In summary, both the lists and strings used for output capture have
+ the following special attributes::
+
+ .l (or .list) : value as list.
+ .n (or .nlstr): value as newline-separated string.
+ .s (or .spstr): value as space-separated string.
+ """
+
+ opts,args = self.parse_options(parameter_s, 'lv')
+ # Try to get a variable name and command to run
+ try:
+ # the variable name must be obtained from the parse_options
+ # output, which uses shlex.split to strip options out.
+ var,_ = args.split('=', 1)
+ var = var.strip()
+ # But the command has to be extracted from the original input
+ # parameter_s, not on what parse_options returns, to avoid the
+ # quote stripping which shlex.split performs on it.
+ _,cmd = parameter_s.split('=', 1)
+ except ValueError:
+ var,cmd = '',''
+ # If all looks ok, proceed
+ split = 'l' in opts
+ out = self.shell.getoutput(cmd, split=split)
+ if 'v' in opts:
+ print('%s ==\n%s' % (var, pformat(out)))
+ if var:
+ self.shell.user_ns.update({var:out})
+ else:
+ return out
+
+ @line_cell_magic
+ def sx(self, line='', cell=None):
+ """Shell execute - run shell command and capture output (!! is short-hand).
+
+ %sx command
+
+ IPython will run the given command using commands.getoutput(), and
+ return the result formatted as a list (split on '\\n'). Since the
+ output is _returned_, it will be stored in ipython's regular output
+ cache Out[N] and in the '_N' automatic variables.
+
+ Notes:
+
+ 1) If an input line begins with '!!', then %sx is automatically
+ invoked. That is, while::
+
+ !ls
+
+ causes ipython to simply issue system('ls'), typing::
+
+ !!ls
+
+ is a shorthand equivalent to::
+
+ %sx ls
+
+ 2) %sx differs from %sc in that %sx automatically splits into a list,
+ like '%sc -l'. The reason for this is to make it as easy as possible
+ to process line-oriented shell output via further python commands.
+ %sc is meant to provide much finer control, but requires more
+ typing.
+
+ 3) Just like %sc -l, this is a list with special attributes:
+ ::
+
+ .l (or .list) : value as list.
+ .n (or .nlstr): value as newline-separated string.
+ .s (or .spstr): value as whitespace-separated string.
+
+ This is very useful when trying to use such lists as arguments to
+ system commands."""
+
+ if cell is None:
+ # line magic
+ return self.shell.getoutput(line)
+ else:
+ opts,args = self.parse_options(line, '', 'out=')
+ output = self.shell.getoutput(cell)
+ out_name = opts.get('out', opts.get('o'))
+ if out_name:
+ self.shell.user_ns[out_name] = output
+ else:
+ return output
+
+ system = line_cell_magic('system')(sx)
+ bang = cell_magic('!')(sx)
+
+ @line_magic
+ def bookmark(self, parameter_s=''):
+ """Manage IPython's bookmark system.
+
+ %bookmark <name> - set bookmark to current dir
+ %bookmark <name> <dir> - set bookmark to <dir>
+ %bookmark -l - list all bookmarks
+ %bookmark -d <name> - remove bookmark
+ %bookmark -r - remove all bookmarks
+
+ You can later on access a bookmarked folder with::
+
+ %cd -b <name>
+
+ or simply '%cd <name>' if there is no directory called <name> AND
+ there is such a bookmark defined.
+
+ Your bookmarks persist through IPython sessions, but they are
+ associated with each profile."""
+
+ opts,args = self.parse_options(parameter_s,'drl',mode='list')
+ if len(args) > 2:
+ raise UsageError("%bookmark: too many arguments")
+
+ bkms = self.shell.db.get('bookmarks',{})
+
+ if 'd' in opts:
+ try:
+ todel = args[0]
+ except IndexError:
+ raise UsageError(
+ "%bookmark -d: must provide a bookmark to delete")
+ else:
+ try:
+ del bkms[todel]
+ except KeyError:
+ raise UsageError(
+ "%%bookmark -d: Can't delete bookmark '%s'" % todel)
+
+ elif 'r' in opts:
+ bkms = {}
+ elif 'l' in opts:
+ bks = sorted(bkms)
+ if bks:
+ size = max(map(len, bks))
+ else:
+ size = 0
+ fmt = '%-'+str(size)+'s -> %s'
+ print('Current bookmarks:')
+ for bk in bks:
+ print(fmt % (bk, bkms[bk]))
+ else:
+ if not args:
+ raise UsageError("%bookmark: You must specify the bookmark name")
+ elif len(args)==1:
+ bkms[args[0]] = py3compat.getcwd()
+ elif len(args)==2:
+ bkms[args[0]] = args[1]
+ self.shell.db['bookmarks'] = bkms
+
+ @line_magic
+ def pycat(self, parameter_s=''):
+ """Show a syntax-highlighted file through a pager.
+
+ This magic is similar to the cat utility, but it will assume the file
+ to be Python source and will show it with syntax highlighting.
+
+ This magic command can either take a local filename, an url,
+ an history range (see %history) or a macro as argument ::
+
+ %pycat myscript.py
+ %pycat 7-27
+ %pycat myMacro
+ %pycat http://www.example.com/myscript.py
+ """
+ if not parameter_s:
+ raise UsageError('Missing filename, URL, input history range, '
+ 'or macro.')
+
+ try :
+ cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
+ except (ValueError, IOError):
+ print("Error: no such file, variable, URL, history range or macro")
+ return
+
+ page.page(self.shell.pycolorize(source_to_unicode(cont)))
+
+ @magic_arguments.magic_arguments()
+ @magic_arguments.argument(
+ '-a', '--append', action='store_true', default=False,
+ help='Append contents of the cell to an existing file. '
+ 'The file will be created if it does not exist.'
+ )
+ @magic_arguments.argument(
+ 'filename', type=unicode_type,
+ help='file to write'
+ )
+ @cell_magic
+ def writefile(self, line, cell):
+ """Write the contents of the cell to a file.
+
+ The file will be overwritten unless the -a (--append) flag is specified.
+ """
+ args = magic_arguments.parse_argstring(self.writefile, line)
filename = os.path.expanduser(args.filename)
- if os.path.exists(filename):
- if args.append:
- print("Appending to %s" % filename)
- else:
- print("Overwriting %s" % filename)
- else:
- print("Writing %s" % filename)
-
- mode = 'a' if args.append else 'w'
- with io.open(filename, mode, encoding='utf-8') as f:
- f.write(cell)
+ if os.path.exists(filename):
+ if args.append:
+ print("Appending to %s" % filename)
+ else:
+ print("Overwriting %s" % filename)
+ else:
+ print("Writing %s" % filename)
+
+ mode = 'a' if args.append else 'w'
+ with io.open(filename, mode, encoding='utf-8') as f:
+ f.write(cell)
diff --git a/contrib/python/ipython/py2/IPython/core/magics/pylab.py b/contrib/python/ipython/py2/IPython/core/magics/pylab.py
index deec14cb7c..6c5cd68a59 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/pylab.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/pylab.py
@@ -1,167 +1,167 @@
-"""Implementation of magic functions for matplotlib/pylab support.
-"""
-from __future__ import print_function
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012 The IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Our own packages
-from traitlets.config.application import Application
-from IPython.core import magic_arguments
-from IPython.core.magic import Magics, magics_class, line_magic
-from IPython.testing.skipdoctest import skip_doctest
+"""Implementation of magic functions for matplotlib/pylab support.
+"""
+from __future__ import print_function
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012 The IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Our own packages
+from traitlets.config.application import Application
+from IPython.core import magic_arguments
+from IPython.core.magic import Magics, magics_class, line_magic
+from IPython.testing.skipdoctest import skip_doctest
from warnings import warn
-from IPython.core.pylabtools import backends
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-
-magic_gui_arg = magic_arguments.argument(
- 'gui', nargs='?',
- help="""Name of the matplotlib backend to use %s.
- If given, the corresponding matplotlib backend is used,
- otherwise it will be matplotlib's default
- (which you can set in your matplotlib config file).
- """ % str(tuple(sorted(backends.keys())))
-)
-
-
-@magics_class
-class PylabMagics(Magics):
- """Magics related to matplotlib's pylab support"""
-
- @skip_doctest
- @line_magic
- @magic_arguments.magic_arguments()
- @magic_arguments.argument('-l', '--list', action='store_true',
- help='Show available matplotlib backends')
- @magic_gui_arg
- def matplotlib(self, line=''):
- """Set up matplotlib to work interactively.
-
- This function lets you activate matplotlib interactive support
- at any point during an IPython session. It does not import anything
- into the interactive namespace.
-
- If you are using the inline matplotlib backend in the IPython Notebook
- you can set which figure formats are enabled using the following::
-
- In [1]: from IPython.display import set_matplotlib_formats
-
- In [2]: set_matplotlib_formats('pdf', 'svg')
-
- The default for inline figures sets `bbox_inches` to 'tight'. This can
- cause discrepancies between the displayed image and the identical
- image created using `savefig`. This behavior can be disabled using the
- `%config` magic::
-
- In [3]: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
-
- In addition, see the docstring of
- `IPython.display.set_matplotlib_formats` and
- `IPython.display.set_matplotlib_close` for more information on
- changing additional behaviors of the inline backend.
-
- Examples
- --------
- To enable the inline backend for usage with the IPython Notebook::
-
- In [1]: %matplotlib inline
-
- In this case, where the matplotlib default is TkAgg::
-
- In [2]: %matplotlib
- Using matplotlib backend: TkAgg
-
- But you can explicitly request a different GUI backend::
-
- In [3]: %matplotlib qt
-
- You can list the available backends using the -l/--list option::
-
- In [4]: %matplotlib --list
- Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt', 'nbagg',
- 'gtk', 'tk', 'inline']
- """
- args = magic_arguments.parse_argstring(self.matplotlib, line)
- if args.list:
- backends_list = list(backends.keys())
- print("Available matplotlib backends: %s" % backends_list)
- else:
- gui, backend = self.shell.enable_matplotlib(args.gui)
- self._show_matplotlib_backend(args.gui, backend)
-
- @skip_doctest
- @line_magic
- @magic_arguments.magic_arguments()
- @magic_arguments.argument(
- '--no-import-all', action='store_true', default=None,
- help="""Prevent IPython from performing ``import *`` into the interactive namespace.
-
- You can govern the default behavior of this flag with the
- InteractiveShellApp.pylab_import_all configurable.
- """
- )
- @magic_gui_arg
- def pylab(self, line=''):
- """Load numpy and matplotlib to work interactively.
-
- This function lets you activate pylab (matplotlib, numpy and
- interactive support) at any point during an IPython session.
-
- %pylab makes the following imports::
-
- import numpy
- import matplotlib
- from matplotlib import pylab, mlab, pyplot
- np = numpy
- plt = pyplot
-
- from IPython.display import display
- from IPython.core.pylabtools import figsize, getfigs
-
- from pylab import *
- from numpy import *
-
- If you pass `--no-import-all`, the last two `*` imports will be excluded.
-
- See the %matplotlib magic for more details about activating matplotlib
- without affecting the interactive namespace.
- """
- args = magic_arguments.parse_argstring(self.pylab, line)
- if args.no_import_all is None:
- # get default from Application
- if Application.initialized():
- app = Application.instance()
- try:
- import_all = app.pylab_import_all
- except AttributeError:
- import_all = True
- else:
- # nothing specified, no app - default True
- import_all = True
- else:
- # invert no-import flag
- import_all = not args.no_import_all
-
- gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
- self._show_matplotlib_backend(args.gui, backend)
- print ("Populating the interactive namespace from numpy and matplotlib")
- if clobbered:
- warn("pylab import has clobbered these variables: %s" % clobbered +
- "\n`%matplotlib` prevents importing * from pylab and numpy"
- )
-
- def _show_matplotlib_backend(self, gui, backend):
- """show matplotlib message backend message"""
- if not gui or gui == 'auto':
- print("Using matplotlib backend: %s" % backend)
+from IPython.core.pylabtools import backends
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+
+magic_gui_arg = magic_arguments.argument(
+ 'gui', nargs='?',
+ help="""Name of the matplotlib backend to use %s.
+ If given, the corresponding matplotlib backend is used,
+ otherwise it will be matplotlib's default
+ (which you can set in your matplotlib config file).
+ """ % str(tuple(sorted(backends.keys())))
+)
+
+
+@magics_class
+class PylabMagics(Magics):
+ """Magics related to matplotlib's pylab support"""
+
+ @skip_doctest
+ @line_magic
+ @magic_arguments.magic_arguments()
+ @magic_arguments.argument('-l', '--list', action='store_true',
+ help='Show available matplotlib backends')
+ @magic_gui_arg
+ def matplotlib(self, line=''):
+ """Set up matplotlib to work interactively.
+
+ This function lets you activate matplotlib interactive support
+ at any point during an IPython session. It does not import anything
+ into the interactive namespace.
+
+ If you are using the inline matplotlib backend in the IPython Notebook
+ you can set which figure formats are enabled using the following::
+
+ In [1]: from IPython.display import set_matplotlib_formats
+
+ In [2]: set_matplotlib_formats('pdf', 'svg')
+
+ The default for inline figures sets `bbox_inches` to 'tight'. This can
+ cause discrepancies between the displayed image and the identical
+ image created using `savefig`. This behavior can be disabled using the
+ `%config` magic::
+
+ In [3]: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
+
+ In addition, see the docstring of
+ `IPython.display.set_matplotlib_formats` and
+ `IPython.display.set_matplotlib_close` for more information on
+ changing additional behaviors of the inline backend.
+
+ Examples
+ --------
+ To enable the inline backend for usage with the IPython Notebook::
+
+ In [1]: %matplotlib inline
+
+ In this case, where the matplotlib default is TkAgg::
+
+ In [2]: %matplotlib
+ Using matplotlib backend: TkAgg
+
+ But you can explicitly request a different GUI backend::
+
+ In [3]: %matplotlib qt
+
+ You can list the available backends using the -l/--list option::
+
+ In [4]: %matplotlib --list
+ Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt', 'nbagg',
+ 'gtk', 'tk', 'inline']
+ """
+ args = magic_arguments.parse_argstring(self.matplotlib, line)
+ if args.list:
+ backends_list = list(backends.keys())
+ print("Available matplotlib backends: %s" % backends_list)
+ else:
+ gui, backend = self.shell.enable_matplotlib(args.gui)
+ self._show_matplotlib_backend(args.gui, backend)
+
+ @skip_doctest
+ @line_magic
+ @magic_arguments.magic_arguments()
+ @magic_arguments.argument(
+ '--no-import-all', action='store_true', default=None,
+ help="""Prevent IPython from performing ``import *`` into the interactive namespace.
+
+ You can govern the default behavior of this flag with the
+ InteractiveShellApp.pylab_import_all configurable.
+ """
+ )
+ @magic_gui_arg
+ def pylab(self, line=''):
+ """Load numpy and matplotlib to work interactively.
+
+ This function lets you activate pylab (matplotlib, numpy and
+ interactive support) at any point during an IPython session.
+
+ %pylab makes the following imports::
+
+ import numpy
+ import matplotlib
+ from matplotlib import pylab, mlab, pyplot
+ np = numpy
+ plt = pyplot
+
+ from IPython.display import display
+ from IPython.core.pylabtools import figsize, getfigs
+
+ from pylab import *
+ from numpy import *
+
+ If you pass `--no-import-all`, the last two `*` imports will be excluded.
+
+ See the %matplotlib magic for more details about activating matplotlib
+ without affecting the interactive namespace.
+ """
+ args = magic_arguments.parse_argstring(self.pylab, line)
+ if args.no_import_all is None:
+ # get default from Application
+ if Application.initialized():
+ app = Application.instance()
+ try:
+ import_all = app.pylab_import_all
+ except AttributeError:
+ import_all = True
+ else:
+ # nothing specified, no app - default True
+ import_all = True
+ else:
+ # invert no-import flag
+ import_all = not args.no_import_all
+
+ gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
+ self._show_matplotlib_backend(args.gui, backend)
+ print ("Populating the interactive namespace from numpy and matplotlib")
+ if clobbered:
+ warn("pylab import has clobbered these variables: %s" % clobbered +
+ "\n`%matplotlib` prevents importing * from pylab and numpy"
+ )
+
+ def _show_matplotlib_backend(self, gui, backend):
+ """show matplotlib message backend message"""
+ if not gui or gui == 'auto':
+ print("Using matplotlib backend: %s" % backend)
diff --git a/contrib/python/ipython/py2/IPython/core/magics/script.py b/contrib/python/ipython/py2/IPython/core/magics/script.py
index d381d97234..3fbddc38a8 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/script.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/script.py
@@ -1,280 +1,280 @@
-"""Magic functions for running cells in various scripts."""
-from __future__ import print_function
-
+"""Magic functions for running cells in various scripts."""
+from __future__ import print_function
+
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
-
-import errno
-import os
-import sys
-import signal
-import time
-from subprocess import Popen, PIPE
-import atexit
-
-from IPython.core import magic_arguments
-from IPython.core.magic import (
- Magics, magics_class, line_magic, cell_magic
-)
-from IPython.lib.backgroundjobs import BackgroundJobManager
-from IPython.utils import py3compat
-from IPython.utils.process import arg_split
+
+import errno
+import os
+import sys
+import signal
+import time
+from subprocess import Popen, PIPE
+import atexit
+
+from IPython.core import magic_arguments
+from IPython.core.magic import (
+ Magics, magics_class, line_magic, cell_magic
+)
+from IPython.lib.backgroundjobs import BackgroundJobManager
+from IPython.utils import py3compat
+from IPython.utils.process import arg_split
from traitlets import List, Dict, default
-
-#-----------------------------------------------------------------------------
-# Magic implementation classes
-#-----------------------------------------------------------------------------
-
-def script_args(f):
- """single decorator for adding script args"""
- args = [
- magic_arguments.argument(
- '--out', type=str,
- help="""The variable in which to store stdout from the script.
- If the script is backgrounded, this will be the stdout *pipe*,
- instead of the stderr text itself.
- """
- ),
- magic_arguments.argument(
- '--err', type=str,
- help="""The variable in which to store stderr from the script.
- If the script is backgrounded, this will be the stderr *pipe*,
- instead of the stderr text itself.
- """
- ),
- magic_arguments.argument(
- '--bg', action="store_true",
- help="""Whether to run the script in the background.
- If given, the only way to see the output of the command is
- with --out/err.
- """
- ),
- magic_arguments.argument(
- '--proc', type=str,
- help="""The variable in which to store Popen instance.
- This is used only when --bg option is given.
- """
- ),
- ]
- for arg in args:
- f = arg(f)
- return f
-
-@magics_class
-class ScriptMagics(Magics):
- """Magics for talking to scripts
-
- This defines a base `%%script` cell magic for running a cell
- with a program in a subprocess, and registers a few top-level
- magics that call %%script with common interpreters.
- """
+
+#-----------------------------------------------------------------------------
+# Magic implementation classes
+#-----------------------------------------------------------------------------
+
+def script_args(f):
+ """single decorator for adding script args"""
+ args = [
+ magic_arguments.argument(
+ '--out', type=str,
+ help="""The variable in which to store stdout from the script.
+ If the script is backgrounded, this will be the stdout *pipe*,
+ instead of the stderr text itself.
+ """
+ ),
+ magic_arguments.argument(
+ '--err', type=str,
+ help="""The variable in which to store stderr from the script.
+ If the script is backgrounded, this will be the stderr *pipe*,
+ instead of the stderr text itself.
+ """
+ ),
+ magic_arguments.argument(
+ '--bg', action="store_true",
+ help="""Whether to run the script in the background.
+ If given, the only way to see the output of the command is
+ with --out/err.
+ """
+ ),
+ magic_arguments.argument(
+ '--proc', type=str,
+ help="""The variable in which to store Popen instance.
+ This is used only when --bg option is given.
+ """
+ ),
+ ]
+ for arg in args:
+ f = arg(f)
+ return f
+
+@magics_class
+class ScriptMagics(Magics):
+ """Magics for talking to scripts
+
+ This defines a base `%%script` cell magic for running a cell
+ with a program in a subprocess, and registers a few top-level
+ magics that call %%script with common interpreters.
+ """
script_magics = List(
- help="""Extra script cell magics to define
-
- This generates simple wrappers of `%%script foo` as `%%foo`.
-
- If you want to add script magics that aren't on your path,
- specify them in script_paths
- """,
+ help="""Extra script cell magics to define
+
+ This generates simple wrappers of `%%script foo` as `%%foo`.
+
+ If you want to add script magics that aren't on your path,
+ specify them in script_paths
+ """,
).tag(config=True)
@default('script_magics')
- def _script_magics_default(self):
- """default to a common list of programs"""
-
- defaults = [
- 'sh',
- 'bash',
- 'perl',
- 'ruby',
- 'python',
- 'python2',
- 'python3',
- 'pypy',
- ]
- if os.name == 'nt':
- defaults.extend([
- 'cmd',
- ])
-
- return defaults
-
+ def _script_magics_default(self):
+ """default to a common list of programs"""
+
+ defaults = [
+ 'sh',
+ 'bash',
+ 'perl',
+ 'ruby',
+ 'python',
+ 'python2',
+ 'python3',
+ 'pypy',
+ ]
+ if os.name == 'nt':
+ defaults.extend([
+ 'cmd',
+ ])
+
+ return defaults
+
script_paths = Dict(
- help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
-
- Only necessary for items in script_magics where the default path will not
- find the right interpreter.
- """
+ help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
+
+ Only necessary for items in script_magics where the default path will not
+ find the right interpreter.
+ """
).tag(config=True)
-
- def __init__(self, shell=None):
- super(ScriptMagics, self).__init__(shell=shell)
- self._generate_script_magics()
- self.job_manager = BackgroundJobManager()
- self.bg_processes = []
- atexit.register(self.kill_bg_processes)
-
- def __del__(self):
- self.kill_bg_processes()
-
- def _generate_script_magics(self):
- cell_magics = self.magics['cell']
- for name in self.script_magics:
- cell_magics[name] = self._make_script_magic(name)
-
- def _make_script_magic(self, name):
- """make a named magic, that calls %%script with a particular program"""
- # expand to explicit path if necessary:
- script = self.script_paths.get(name, name)
-
- @magic_arguments.magic_arguments()
- @script_args
- def named_script_magic(line, cell):
- # if line, add it as cl-flags
- if line:
- line = "%s %s" % (script, line)
- else:
- line = script
- return self.shebang(line, cell)
-
- # write a basic docstring:
- named_script_magic.__doc__ = \
- """%%{name} script magic
-
- Run cells with {script} in a subprocess.
-
- This is a shortcut for `%%script {script}`
- """.format(**locals())
-
- return named_script_magic
-
- @magic_arguments.magic_arguments()
- @script_args
- @cell_magic("script")
- def shebang(self, line, cell):
- """Run a cell via a shell command
-
- The `%%script` line is like the #! line of script,
- specifying a program (bash, perl, ruby, etc.) with which to run.
-
- The rest of the cell is run by that program.
-
- Examples
- --------
- ::
-
- In [1]: %%script bash
- ...: for i in 1 2 3; do
- ...: echo $i
- ...: done
- 1
- 2
- 3
- """
- argv = arg_split(line, posix = not sys.platform.startswith('win'))
- args, cmd = self.shebang.parser.parse_known_args(argv)
-
- try:
- p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)
- except OSError as e:
- if e.errno == errno.ENOENT:
- print("Couldn't find program: %r" % cmd[0])
- return
- else:
- raise
-
- if not cell.endswith('\n'):
- cell += '\n'
- cell = cell.encode('utf8', 'replace')
- if args.bg:
- self.bg_processes.append(p)
- self._gc_bg_processes()
- if args.out:
- self.shell.user_ns[args.out] = p.stdout
- if args.err:
- self.shell.user_ns[args.err] = p.stderr
- self.job_manager.new(self._run_script, p, cell, daemon=True)
- if args.proc:
- self.shell.user_ns[args.proc] = p
- return
-
- try:
- out, err = p.communicate(cell)
- except KeyboardInterrupt:
- try:
- p.send_signal(signal.SIGINT)
- time.sleep(0.1)
- if p.poll() is not None:
- print("Process is interrupted.")
- return
- p.terminate()
- time.sleep(0.1)
- if p.poll() is not None:
- print("Process is terminated.")
- return
- p.kill()
- print("Process is killed.")
- except OSError:
- pass
- except Exception as e:
- print("Error while terminating subprocess (pid=%i): %s" \
- % (p.pid, e))
- return
- out = py3compat.bytes_to_str(out)
- err = py3compat.bytes_to_str(err)
- if args.out:
- self.shell.user_ns[args.out] = out
- else:
- sys.stdout.write(out)
- sys.stdout.flush()
- if args.err:
- self.shell.user_ns[args.err] = err
- else:
- sys.stderr.write(err)
- sys.stderr.flush()
-
- def _run_script(self, p, cell):
- """callback for running the script in the background"""
- p.stdin.write(cell)
- p.stdin.close()
- p.wait()
-
- @line_magic("killbgscripts")
- def killbgscripts(self, _nouse_=''):
- """Kill all BG processes started by %%script and its family."""
- self.kill_bg_processes()
- print("All background processes were killed.")
-
- def kill_bg_processes(self):
- """Kill all BG processes which are still running."""
+
+ def __init__(self, shell=None):
+ super(ScriptMagics, self).__init__(shell=shell)
+ self._generate_script_magics()
+ self.job_manager = BackgroundJobManager()
+ self.bg_processes = []
+ atexit.register(self.kill_bg_processes)
+
+ def __del__(self):
+ self.kill_bg_processes()
+
+ def _generate_script_magics(self):
+ cell_magics = self.magics['cell']
+ for name in self.script_magics:
+ cell_magics[name] = self._make_script_magic(name)
+
+ def _make_script_magic(self, name):
+ """make a named magic, that calls %%script with a particular program"""
+ # expand to explicit path if necessary:
+ script = self.script_paths.get(name, name)
+
+ @magic_arguments.magic_arguments()
+ @script_args
+ def named_script_magic(line, cell):
+ # if line, add it as cl-flags
+ if line:
+ line = "%s %s" % (script, line)
+ else:
+ line = script
+ return self.shebang(line, cell)
+
+ # write a basic docstring:
+ named_script_magic.__doc__ = \
+ """%%{name} script magic
+
+ Run cells with {script} in a subprocess.
+
+ This is a shortcut for `%%script {script}`
+ """.format(**locals())
+
+ return named_script_magic
+
+ @magic_arguments.magic_arguments()
+ @script_args
+ @cell_magic("script")
+ def shebang(self, line, cell):
+ """Run a cell via a shell command
+
+ The `%%script` line is like the #! line of script,
+ specifying a program (bash, perl, ruby, etc.) with which to run.
+
+ The rest of the cell is run by that program.
+
+ Examples
+ --------
+ ::
+
+ In [1]: %%script bash
+ ...: for i in 1 2 3; do
+ ...: echo $i
+ ...: done
+ 1
+ 2
+ 3
+ """
+ argv = arg_split(line, posix = not sys.platform.startswith('win'))
+ args, cmd = self.shebang.parser.parse_known_args(argv)
+
+ try:
+ p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)
+ except OSError as e:
+ if e.errno == errno.ENOENT:
+ print("Couldn't find program: %r" % cmd[0])
+ return
+ else:
+ raise
+
+ if not cell.endswith('\n'):
+ cell += '\n'
+ cell = cell.encode('utf8', 'replace')
+ if args.bg:
+ self.bg_processes.append(p)
+ self._gc_bg_processes()
+ if args.out:
+ self.shell.user_ns[args.out] = p.stdout
+ if args.err:
+ self.shell.user_ns[args.err] = p.stderr
+ self.job_manager.new(self._run_script, p, cell, daemon=True)
+ if args.proc:
+ self.shell.user_ns[args.proc] = p
+ return
+
+ try:
+ out, err = p.communicate(cell)
+ except KeyboardInterrupt:
+ try:
+ p.send_signal(signal.SIGINT)
+ time.sleep(0.1)
+ if p.poll() is not None:
+ print("Process is interrupted.")
+ return
+ p.terminate()
+ time.sleep(0.1)
+ if p.poll() is not None:
+ print("Process is terminated.")
+ return
+ p.kill()
+ print("Process is killed.")
+ except OSError:
+ pass
+ except Exception as e:
+ print("Error while terminating subprocess (pid=%i): %s" \
+ % (p.pid, e))
+ return
+ out = py3compat.bytes_to_str(out)
+ err = py3compat.bytes_to_str(err)
+ if args.out:
+ self.shell.user_ns[args.out] = out
+ else:
+ sys.stdout.write(out)
+ sys.stdout.flush()
+ if args.err:
+ self.shell.user_ns[args.err] = err
+ else:
+ sys.stderr.write(err)
+ sys.stderr.flush()
+
+ def _run_script(self, p, cell):
+ """callback for running the script in the background"""
+ p.stdin.write(cell)
+ p.stdin.close()
+ p.wait()
+
+ @line_magic("killbgscripts")
+ def killbgscripts(self, _nouse_=''):
+ """Kill all BG processes started by %%script and its family."""
+ self.kill_bg_processes()
+ print("All background processes were killed.")
+
+ def kill_bg_processes(self):
+ """Kill all BG processes which are still running."""
if not self.bg_processes:
return
- for p in self.bg_processes:
- if p.poll() is None:
- try:
- p.send_signal(signal.SIGINT)
- except:
- pass
- time.sleep(0.1)
+ for p in self.bg_processes:
+ if p.poll() is None:
+ try:
+ p.send_signal(signal.SIGINT)
+ except:
+ pass
+ time.sleep(0.1)
self._gc_bg_processes()
if not self.bg_processes:
return
- for p in self.bg_processes:
- if p.poll() is None:
- try:
- p.terminate()
- except:
- pass
- time.sleep(0.1)
+ for p in self.bg_processes:
+ if p.poll() is None:
+ try:
+ p.terminate()
+ except:
+ pass
+ time.sleep(0.1)
self._gc_bg_processes()
if not self.bg_processes:
return
- for p in self.bg_processes:
- if p.poll() is None:
- try:
- p.kill()
- except:
- pass
- self._gc_bg_processes()
-
- def _gc_bg_processes(self):
- self.bg_processes = [p for p in self.bg_processes if p.poll() is None]
+ for p in self.bg_processes:
+ if p.poll() is None:
+ try:
+ p.kill()
+ except:
+ pass
+ self._gc_bg_processes()
+
+ def _gc_bg_processes(self):
+ self.bg_processes = [p for p in self.bg_processes if p.poll() is None]
diff --git a/contrib/python/ipython/py2/IPython/core/oinspect.py b/contrib/python/ipython/py2/IPython/core/oinspect.py
index 6849412528..55a4efe8c0 100644
--- a/contrib/python/ipython/py2/IPython/core/oinspect.py
+++ b/contrib/python/ipython/py2/IPython/core/oinspect.py
@@ -1,49 +1,49 @@
-# -*- coding: utf-8 -*-
-"""Tools for inspecting Python objects.
-
-Uses syntax highlighting for presenting the various information elements.
-
-Similar in spirit to the inspect module, but all calls take a name argument to
-reference the name under which an object is being read.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
-__all__ = ['Inspector','InspectColors']
-
-# stdlib modules
-import inspect
-import linecache
+# -*- coding: utf-8 -*-
+"""Tools for inspecting Python objects.
+
+Uses syntax highlighting for presenting the various information elements.
+
+Similar in spirit to the inspect module, but all calls take a name argument to
+reference the name under which an object is being read.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
+__all__ = ['Inspector','InspectColors']
+
+# stdlib modules
+import inspect
+import linecache
import warnings
-import os
-from textwrap import dedent
-import types
-import io as stdlib_io
-
-try:
- from itertools import izip_longest
-except ImportError:
- from itertools import zip_longest as izip_longest
-
-# IPython's own
-from IPython.core import page
-from IPython.lib.pretty import pretty
-from IPython.testing.skipdoctest import skip_doctest_py3
-from IPython.utils import PyColorize
-from IPython.utils import openpy
-from IPython.utils import py3compat
-from IPython.utils.dir2 import safe_hasattr
-from IPython.utils.path import compress_user
-from IPython.utils.text import indent
-from IPython.utils.wildcard import list_namespace
-from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
-from IPython.utils.py3compat import cast_unicode, string_types, PY3
-from IPython.utils.signatures import signature
+import os
+from textwrap import dedent
+import types
+import io as stdlib_io
+
+try:
+ from itertools import izip_longest
+except ImportError:
+ from itertools import zip_longest as izip_longest
+
+# IPython's own
+from IPython.core import page
+from IPython.lib.pretty import pretty
+from IPython.testing.skipdoctest import skip_doctest_py3
+from IPython.utils import PyColorize
+from IPython.utils import openpy
+from IPython.utils import py3compat
+from IPython.utils.dir2 import safe_hasattr
+from IPython.utils.path import compress_user
+from IPython.utils.text import indent
+from IPython.utils.wildcard import list_namespace
+from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
+from IPython.utils.py3compat import cast_unicode, string_types, PY3
+from IPython.utils.signatures import signature
from IPython.utils.colorable import Colorable
-
+
from pygments import highlight
try:
# PythonLexer was renamed to Python2Lexer in pygments 2.5
@@ -55,510 +55,510 @@ from pygments.formatters import HtmlFormatter
def pylight(code):
return highlight(code, Python2Lexer(), HtmlFormatter(noclasses=True))
-# builtin docstrings to ignore
-_func_call_docstring = types.FunctionType.__call__.__doc__
-_object_init_docstring = object.__init__.__doc__
-_builtin_type_docstrings = {
- inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
- types.FunctionType, property)
-}
-
-_builtin_func_type = type(all)
-_builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
-#****************************************************************************
-# Builtin color schemes
-
-Colors = TermColors # just a shorthand
-
-InspectColors = PyColorize.ANSICodeColors
-
-#****************************************************************************
-# Auxiliary functions and objects
-
-# See the messaging spec for the definition of all these fields. This list
-# effectively defines the order of display
-info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
- 'length', 'file', 'definition', 'docstring', 'source',
- 'init_definition', 'class_docstring', 'init_docstring',
- 'call_def', 'call_docstring',
- # These won't be printed but will be used to determine how to
- # format the object
- 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name'
- ]
-
-
-def object_info(**kw):
- """Make an object info dict with all fields present."""
- infodict = dict(izip_longest(info_fields, [None]))
- infodict.update(kw)
- return infodict
-
-
-def get_encoding(obj):
- """Get encoding for python source file defining obj
-
- Returns None if obj is not defined in a sourcefile.
- """
- ofile = find_file(obj)
- # run contents of file through pager starting at line where the object
- # is defined, as long as the file isn't binary and is actually on the
- # filesystem.
- if ofile is None:
- return None
- elif ofile.endswith(('.so', '.dll', '.pyd')):
- return None
- elif not os.path.isfile(ofile):
- return None
- else:
- # Print only text files, not extension binaries. Note that
- # getsourcelines returns lineno with 1-offset and page() uses
- # 0-offset, so we must adjust.
- with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
- encoding, lines = openpy.detect_encoding(buffer.readline)
- return encoding
-
-def getdoc(obj):
- """Stable wrapper around inspect.getdoc.
-
- This can't crash because of attribute problems.
-
- It also attempts to call a getdoc() method on the given object. This
- allows objects which provide their docstrings via non-standard mechanisms
+# builtin docstrings to ignore
+_func_call_docstring = types.FunctionType.__call__.__doc__
+_object_init_docstring = object.__init__.__doc__
+_builtin_type_docstrings = {
+ inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
+ types.FunctionType, property)
+}
+
+_builtin_func_type = type(all)
+_builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
+#****************************************************************************
+# Builtin color schemes
+
+Colors = TermColors # just a shorthand
+
+InspectColors = PyColorize.ANSICodeColors
+
+#****************************************************************************
+# Auxiliary functions and objects
+
+# See the messaging spec for the definition of all these fields. This list
+# effectively defines the order of display
+info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
+ 'length', 'file', 'definition', 'docstring', 'source',
+ 'init_definition', 'class_docstring', 'init_docstring',
+ 'call_def', 'call_docstring',
+ # These won't be printed but will be used to determine how to
+ # format the object
+ 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name'
+ ]
+
+
+def object_info(**kw):
+ """Make an object info dict with all fields present."""
+ infodict = dict(izip_longest(info_fields, [None]))
+ infodict.update(kw)
+ return infodict
+
+
+def get_encoding(obj):
+ """Get encoding for python source file defining obj
+
+ Returns None if obj is not defined in a sourcefile.
+ """
+ ofile = find_file(obj)
+ # run contents of file through pager starting at line where the object
+ # is defined, as long as the file isn't binary and is actually on the
+ # filesystem.
+ if ofile is None:
+ return None
+ elif ofile.endswith(('.so', '.dll', '.pyd')):
+ return None
+ elif not os.path.isfile(ofile):
+ return None
+ else:
+ # Print only text files, not extension binaries. Note that
+ # getsourcelines returns lineno with 1-offset and page() uses
+ # 0-offset, so we must adjust.
+ with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
+ encoding, lines = openpy.detect_encoding(buffer.readline)
+ return encoding
+
+def getdoc(obj):
+ """Stable wrapper around inspect.getdoc.
+
+ This can't crash because of attribute problems.
+
+ It also attempts to call a getdoc() method on the given object. This
+ allows objects which provide their docstrings via non-standard mechanisms
(like Pyro proxies) to still be inspected by ipython's ? system.
"""
- # Allow objects to offer customized documentation via a getdoc method:
- try:
- ds = obj.getdoc()
- except Exception:
- pass
- else:
- # if we get extra info, we add it to the normal docstring.
- if isinstance(ds, string_types):
- return inspect.cleandoc(ds)
- try:
- docstr = inspect.getdoc(obj)
- encoding = get_encoding(obj)
- return py3compat.cast_unicode(docstr, encoding=encoding)
- except Exception:
- # Harden against an inspect failure, which can occur with
+ # Allow objects to offer customized documentation via a getdoc method:
+ try:
+ ds = obj.getdoc()
+ except Exception:
+ pass
+ else:
+ # if we get extra info, we add it to the normal docstring.
+ if isinstance(ds, string_types):
+ return inspect.cleandoc(ds)
+ try:
+ docstr = inspect.getdoc(obj)
+ encoding = get_encoding(obj)
+ return py3compat.cast_unicode(docstr, encoding=encoding)
+ except Exception:
+ # Harden against an inspect failure, which can occur with
# extensions modules.
- raise
- return None
-
-
-def getsource(obj, oname=''):
- """Wrapper around inspect.getsource.
-
- This can be modified by other projects to provide customized source
- extraction.
-
- Parameters
- ----------
- obj : object
- an object whose source code we will attempt to extract
- oname : str
- (optional) a name under which the object is known
-
- Returns
- -------
- src : unicode or None
-
- """
-
- if isinstance(obj, property):
- sources = []
- for attrname in ['fget', 'fset', 'fdel']:
- fn = getattr(obj, attrname)
- if fn is not None:
- encoding = get_encoding(fn)
- oname_prefix = ('%s.' % oname) if oname else ''
- sources.append(cast_unicode(
- ''.join(('# ', oname_prefix, attrname)),
- encoding=encoding))
- if inspect.isfunction(fn):
- sources.append(dedent(getsource(fn)))
- else:
- # Default str/repr only prints function name,
- # pretty.pretty prints module name too.
- sources.append(cast_unicode(
- '%s%s = %s\n' % (
- oname_prefix, attrname, pretty(fn)),
- encoding=encoding))
- if sources:
- return '\n'.join(sources)
- else:
- return None
-
- else:
- # Get source for non-property objects.
-
- obj = _get_wrapped(obj)
-
- try:
- src = inspect.getsource(obj)
- except TypeError:
- # The object itself provided no meaningful source, try looking for
- # its class definition instead.
- if hasattr(obj, '__class__'):
- try:
- src = inspect.getsource(obj.__class__)
- except TypeError:
- return None
-
- encoding = get_encoding(obj)
- return cast_unicode(src, encoding=encoding)
-
-
-def is_simple_callable(obj):
- """True if obj is a function ()"""
- return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
- isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
-
-
-def getargspec(obj):
- """Wrapper around :func:`inspect.getfullargspec` on Python 3, and
- :func:inspect.getargspec` on Python 2.
-
- In addition to functions and methods, this can also handle objects with a
- ``__call__`` attribute.
- """
- if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
- obj = obj.__call__
-
- return inspect.getfullargspec(obj) if PY3 else inspect.getargspec(obj)
-
-
-def format_argspec(argspec):
- """Format argspect, convenience wrapper around inspect's.
-
- This takes a dict instead of ordered arguments and calls
- inspect.format_argspec with the arguments in the necessary order.
- """
- return inspect.formatargspec(argspec['args'], argspec['varargs'],
- argspec['varkw'], argspec['defaults'])
-
-
-def call_tip(oinfo, format_call=True):
- """Extract call tip data from an oinfo dict.
-
- Parameters
- ----------
- oinfo : dict
-
- format_call : bool, optional
- If True, the call line is formatted and returned as a string. If not, a
- tuple of (name, argspec) is returned.
-
- Returns
- -------
- call_info : None, str or (str, dict) tuple.
- When format_call is True, the whole call information is formattted as a
- single string. Otherwise, the object's name and its argspec dict are
- returned. If no call information is available, None is returned.
-
- docstring : str or None
- The most relevant docstring for calling purposes is returned, if
- available. The priority is: call docstring for callable instances, then
- constructor docstring for classes, then main object's docstring otherwise
- (regular functions).
- """
- # Get call definition
- argspec = oinfo.get('argspec')
- if argspec is None:
- call_line = None
- else:
- # Callable objects will have 'self' as their first argument, prune
- # it out if it's there for clarity (since users do *not* pass an
- # extra first argument explicitly).
- try:
- has_self = argspec['args'][0] == 'self'
- except (KeyError, IndexError):
- pass
- else:
- if has_self:
- argspec['args'] = argspec['args'][1:]
-
- call_line = oinfo['name']+format_argspec(argspec)
-
- # Now get docstring.
- # The priority is: call docstring, constructor docstring, main one.
- doc = oinfo.get('call_docstring')
- if doc is None:
- doc = oinfo.get('init_docstring')
- if doc is None:
- doc = oinfo.get('docstring','')
-
- return call_line, doc
-
-
-def _get_wrapped(obj):
- """Get the original object if wrapped in one or more @decorators
-
- Some objects automatically construct similar objects on any unrecognised
- attribute access (e.g. unittest.mock.call). To protect against infinite loops,
- this will arbitrarily cut off after 100 levels of obj.__wrapped__
- attribute access. --TK, Jan 2016
- """
- orig_obj = obj
- i = 0
- while safe_hasattr(obj, '__wrapped__'):
- obj = obj.__wrapped__
- i += 1
- if i > 100:
- # __wrapped__ is probably a lie, so return the thing we started with
- return orig_obj
- return obj
-
-def find_file(obj):
- """Find the absolute path to the file where an object was defined.
-
- This is essentially a robust wrapper around `inspect.getabsfile`.
-
- Returns None if no file can be found.
-
- Parameters
- ----------
- obj : any Python object
-
- Returns
- -------
- fname : str
- The absolute path to the file where the object was defined.
- """
- obj = _get_wrapped(obj)
-
- fname = None
- try:
- fname = inspect.getabsfile(obj)
- except TypeError:
- # For an instance, the file that matters is where its class was
- # declared.
- if hasattr(obj, '__class__'):
- try:
- fname = inspect.getabsfile(obj.__class__)
- except TypeError:
- # Can happen for builtins
- pass
- except:
- pass
- return cast_unicode(fname)
-
-
-def find_source_lines(obj):
- """Find the line number in a file where an object was defined.
-
- This is essentially a robust wrapper around `inspect.getsourcelines`.
-
- Returns None if no file can be found.
-
- Parameters
- ----------
- obj : any Python object
-
- Returns
- -------
- lineno : int
- The line number where the object definition starts.
- """
- obj = _get_wrapped(obj)
-
- try:
- try:
- lineno = inspect.getsourcelines(obj)[1]
- except TypeError:
- # For instances, try the class object like getsource() does
- if hasattr(obj, '__class__'):
- lineno = inspect.getsourcelines(obj.__class__)[1]
- else:
- lineno = None
- except:
- return None
-
- return lineno
-
+ raise
+ return None
+
+
+def getsource(obj, oname=''):
+ """Wrapper around inspect.getsource.
+
+ This can be modified by other projects to provide customized source
+ extraction.
+
+ Parameters
+ ----------
+ obj : object
+ an object whose source code we will attempt to extract
+ oname : str
+ (optional) a name under which the object is known
+
+ Returns
+ -------
+ src : unicode or None
+
+ """
+
+ if isinstance(obj, property):
+ sources = []
+ for attrname in ['fget', 'fset', 'fdel']:
+ fn = getattr(obj, attrname)
+ if fn is not None:
+ encoding = get_encoding(fn)
+ oname_prefix = ('%s.' % oname) if oname else ''
+ sources.append(cast_unicode(
+ ''.join(('# ', oname_prefix, attrname)),
+ encoding=encoding))
+ if inspect.isfunction(fn):
+ sources.append(dedent(getsource(fn)))
+ else:
+ # Default str/repr only prints function name,
+ # pretty.pretty prints module name too.
+ sources.append(cast_unicode(
+ '%s%s = %s\n' % (
+ oname_prefix, attrname, pretty(fn)),
+ encoding=encoding))
+ if sources:
+ return '\n'.join(sources)
+ else:
+ return None
+
+ else:
+ # Get source for non-property objects.
+
+ obj = _get_wrapped(obj)
+
+ try:
+ src = inspect.getsource(obj)
+ except TypeError:
+ # The object itself provided no meaningful source, try looking for
+ # its class definition instead.
+ if hasattr(obj, '__class__'):
+ try:
+ src = inspect.getsource(obj.__class__)
+ except TypeError:
+ return None
+
+ encoding = get_encoding(obj)
+ return cast_unicode(src, encoding=encoding)
+
+
+def is_simple_callable(obj):
+ """True if obj is a function ()"""
+ return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
+ isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
+
+
+def getargspec(obj):
+ """Wrapper around :func:`inspect.getfullargspec` on Python 3, and
+ :func:inspect.getargspec` on Python 2.
+
+ In addition to functions and methods, this can also handle objects with a
+ ``__call__`` attribute.
+ """
+ if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
+ obj = obj.__call__
+
+ return inspect.getfullargspec(obj) if PY3 else inspect.getargspec(obj)
+
+
+def format_argspec(argspec):
+ """Format argspect, convenience wrapper around inspect's.
+
+ This takes a dict instead of ordered arguments and calls
+ inspect.format_argspec with the arguments in the necessary order.
+ """
+ return inspect.formatargspec(argspec['args'], argspec['varargs'],
+ argspec['varkw'], argspec['defaults'])
+
+
+def call_tip(oinfo, format_call=True):
+ """Extract call tip data from an oinfo dict.
+
+ Parameters
+ ----------
+ oinfo : dict
+
+ format_call : bool, optional
+ If True, the call line is formatted and returned as a string. If not, a
+ tuple of (name, argspec) is returned.
+
+ Returns
+ -------
+ call_info : None, str or (str, dict) tuple.
+ When format_call is True, the whole call information is formattted as a
+ single string. Otherwise, the object's name and its argspec dict are
+ returned. If no call information is available, None is returned.
+
+ docstring : str or None
+ The most relevant docstring for calling purposes is returned, if
+ available. The priority is: call docstring for callable instances, then
+ constructor docstring for classes, then main object's docstring otherwise
+ (regular functions).
+ """
+ # Get call definition
+ argspec = oinfo.get('argspec')
+ if argspec is None:
+ call_line = None
+ else:
+ # Callable objects will have 'self' as their first argument, prune
+ # it out if it's there for clarity (since users do *not* pass an
+ # extra first argument explicitly).
+ try:
+ has_self = argspec['args'][0] == 'self'
+ except (KeyError, IndexError):
+ pass
+ else:
+ if has_self:
+ argspec['args'] = argspec['args'][1:]
+
+ call_line = oinfo['name']+format_argspec(argspec)
+
+ # Now get docstring.
+ # The priority is: call docstring, constructor docstring, main one.
+ doc = oinfo.get('call_docstring')
+ if doc is None:
+ doc = oinfo.get('init_docstring')
+ if doc is None:
+ doc = oinfo.get('docstring','')
+
+ return call_line, doc
+
+
+def _get_wrapped(obj):
+ """Get the original object if wrapped in one or more @decorators
+
+ Some objects automatically construct similar objects on any unrecognised
+ attribute access (e.g. unittest.mock.call). To protect against infinite loops,
+ this will arbitrarily cut off after 100 levels of obj.__wrapped__
+ attribute access. --TK, Jan 2016
+ """
+ orig_obj = obj
+ i = 0
+ while safe_hasattr(obj, '__wrapped__'):
+ obj = obj.__wrapped__
+ i += 1
+ if i > 100:
+ # __wrapped__ is probably a lie, so return the thing we started with
+ return orig_obj
+ return obj
+
+def find_file(obj):
+ """Find the absolute path to the file where an object was defined.
+
+ This is essentially a robust wrapper around `inspect.getabsfile`.
+
+ Returns None if no file can be found.
+
+ Parameters
+ ----------
+ obj : any Python object
+
+ Returns
+ -------
+ fname : str
+ The absolute path to the file where the object was defined.
+ """
+ obj = _get_wrapped(obj)
+
+ fname = None
+ try:
+ fname = inspect.getabsfile(obj)
+ except TypeError:
+ # For an instance, the file that matters is where its class was
+ # declared.
+ if hasattr(obj, '__class__'):
+ try:
+ fname = inspect.getabsfile(obj.__class__)
+ except TypeError:
+ # Can happen for builtins
+ pass
+ except:
+ pass
+ return cast_unicode(fname)
+
+
+def find_source_lines(obj):
+ """Find the line number in a file where an object was defined.
+
+ This is essentially a robust wrapper around `inspect.getsourcelines`.
+
+ Returns None if no file can be found.
+
+ Parameters
+ ----------
+ obj : any Python object
+
+ Returns
+ -------
+ lineno : int
+ The line number where the object definition starts.
+ """
+ obj = _get_wrapped(obj)
+
+ try:
+ try:
+ lineno = inspect.getsourcelines(obj)[1]
+ except TypeError:
+ # For instances, try the class object like getsource() does
+ if hasattr(obj, '__class__'):
+ lineno = inspect.getsourcelines(obj.__class__)[1]
+ else:
+ lineno = None
+ except:
+ return None
+
+ return lineno
+
class Inspector(Colorable):
-
- def __init__(self, color_table=InspectColors,
- code_color_table=PyColorize.ANSICodeColors,
- scheme='NoColor',
+
+ def __init__(self, color_table=InspectColors,
+ code_color_table=PyColorize.ANSICodeColors,
+ scheme='NoColor',
str_detail_level=0,
parent=None, config=None):
super(Inspector, self).__init__(parent=parent, config=config)
- self.color_table = color_table
+ self.color_table = color_table
self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
- self.format = self.parser.format
- self.str_detail_level = str_detail_level
- self.set_active_scheme(scheme)
-
- def _getdef(self,obj,oname=''):
- """Return the call signature for any callable object.
-
- If any exception is generated, None is returned instead and the
- exception is suppressed."""
- try:
- hdef = oname + str(signature(obj))
- return cast_unicode(hdef)
- except:
- return None
-
- def __head(self,h):
- """Return a header string with proper colors."""
- return '%s%s%s' % (self.color_table.active_colors.header,h,
- self.color_table.active_colors.normal)
-
- def set_active_scheme(self, scheme):
- self.color_table.set_active_scheme(scheme)
- self.parser.color_table.set_active_scheme(scheme)
-
- def noinfo(self, msg, oname):
- """Generic message when no information is found."""
- print('No %s found' % msg, end=' ')
- if oname:
- print('for %s' % oname)
- else:
- print()
-
- def pdef(self, obj, oname=''):
- """Print the call signature for any callable object.
-
- If the object is a class, print the constructor information."""
-
- if not callable(obj):
- print('Object is not callable.')
- return
-
- header = ''
-
- if inspect.isclass(obj):
- header = self.__head('Class constructor information:\n')
- elif (not py3compat.PY3) and type(obj) is types.InstanceType:
- obj = obj.__call__
-
- output = self._getdef(obj,oname)
- if output is None:
- self.noinfo('definition header',oname)
- else:
+ self.format = self.parser.format
+ self.str_detail_level = str_detail_level
+ self.set_active_scheme(scheme)
+
+ def _getdef(self,obj,oname=''):
+ """Return the call signature for any callable object.
+
+ If any exception is generated, None is returned instead and the
+ exception is suppressed."""
+ try:
+ hdef = oname + str(signature(obj))
+ return cast_unicode(hdef)
+ except:
+ return None
+
+ def __head(self,h):
+ """Return a header string with proper colors."""
+ return '%s%s%s' % (self.color_table.active_colors.header,h,
+ self.color_table.active_colors.normal)
+
+ def set_active_scheme(self, scheme):
+ self.color_table.set_active_scheme(scheme)
+ self.parser.color_table.set_active_scheme(scheme)
+
+ def noinfo(self, msg, oname):
+ """Generic message when no information is found."""
+ print('No %s found' % msg, end=' ')
+ if oname:
+ print('for %s' % oname)
+ else:
+ print()
+
+ def pdef(self, obj, oname=''):
+ """Print the call signature for any callable object.
+
+ If the object is a class, print the constructor information."""
+
+ if not callable(obj):
+ print('Object is not callable.')
+ return
+
+ header = ''
+
+ if inspect.isclass(obj):
+ header = self.__head('Class constructor information:\n')
+ elif (not py3compat.PY3) and type(obj) is types.InstanceType:
+ obj = obj.__call__
+
+ output = self._getdef(obj,oname)
+ if output is None:
+ self.noinfo('definition header',oname)
+ else:
print(header,self.format(output), end=' ')
-
- # In Python 3, all classes are new-style, so they all have __init__.
- @skip_doctest_py3
+
+ # In Python 3, all classes are new-style, so they all have __init__.
+ @skip_doctest_py3
def pdoc(self, obj, oname='', formatter=None):
- """Print the docstring for any object.
-
- Optional:
- -formatter: a function to run the docstring through for specially
- formatted docstrings.
-
- Examples
- --------
-
- In [1]: class NoInit:
- ...: pass
-
- In [2]: class NoDoc:
- ...: def __init__(self):
- ...: pass
-
- In [3]: %pdoc NoDoc
- No documentation found for NoDoc
-
- In [4]: %pdoc NoInit
- No documentation found for NoInit
-
- In [5]: obj = NoInit()
-
- In [6]: %pdoc obj
- No documentation found for obj
-
- In [5]: obj2 = NoDoc()
-
- In [6]: %pdoc obj2
- No documentation found for obj2
- """
-
- head = self.__head # For convenience
- lines = []
- ds = getdoc(obj)
- if formatter:
+ """Print the docstring for any object.
+
+ Optional:
+ -formatter: a function to run the docstring through for specially
+ formatted docstrings.
+
+ Examples
+ --------
+
+ In [1]: class NoInit:
+ ...: pass
+
+ In [2]: class NoDoc:
+ ...: def __init__(self):
+ ...: pass
+
+ In [3]: %pdoc NoDoc
+ No documentation found for NoDoc
+
+ In [4]: %pdoc NoInit
+ No documentation found for NoInit
+
+ In [5]: obj = NoInit()
+
+ In [6]: %pdoc obj
+ No documentation found for obj
+
+ In [5]: obj2 = NoDoc()
+
+ In [6]: %pdoc obj2
+ No documentation found for obj2
+ """
+
+ head = self.__head # For convenience
+ lines = []
+ ds = getdoc(obj)
+ if formatter:
ds = formatter(ds).get('plain/text', ds)
- if ds:
- lines.append(head("Class docstring:"))
- lines.append(indent(ds))
- if inspect.isclass(obj) and hasattr(obj, '__init__'):
- init_ds = getdoc(obj.__init__)
- if init_ds is not None:
- lines.append(head("Init docstring:"))
- lines.append(indent(init_ds))
- elif hasattr(obj,'__call__'):
- call_ds = getdoc(obj.__call__)
- if call_ds:
- lines.append(head("Call docstring:"))
- lines.append(indent(call_ds))
-
- if not lines:
- self.noinfo('documentation',oname)
- else:
- page.page('\n'.join(lines))
-
- def psource(self, obj, oname=''):
- """Print the source code for an object."""
-
- # Flush the source cache because inspect can return out-of-date source
- linecache.checkcache()
- try:
- src = getsource(obj, oname=oname)
- except Exception:
- src = None
-
- if src is None:
- self.noinfo('source', oname)
- else:
- page.page(self.format(src))
-
- def pfile(self, obj, oname=''):
- """Show the whole file where an object was defined."""
-
- lineno = find_source_lines(obj)
- if lineno is None:
- self.noinfo('file', oname)
- return
-
- ofile = find_file(obj)
- # run contents of file through pager starting at line where the object
- # is defined, as long as the file isn't binary and is actually on the
- # filesystem.
- if ofile.endswith(('.so', '.dll', '.pyd')):
- print('File %r is binary, not printing.' % ofile)
- elif not os.path.isfile(ofile):
- print('File %r does not exist, not printing.' % ofile)
- else:
- # Print only text files, not extension binaries. Note that
- # getsourcelines returns lineno with 1-offset and page() uses
- # 0-offset, so we must adjust.
- page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
-
- def _format_fields(self, fields, title_width=0):
- """Formats a list of fields for display.
-
- Parameters
- ----------
- fields : list
- A list of 2-tuples: (field_title, field_content)
- title_width : int
- How many characters to pad titles to. Default to longest title.
- """
- out = []
- header = self.__head
- if title_width == 0:
- title_width = max(len(title) + 2 for title, _ in fields)
- for title, content in fields:
- if len(content.splitlines()) > 1:
+ if ds:
+ lines.append(head("Class docstring:"))
+ lines.append(indent(ds))
+ if inspect.isclass(obj) and hasattr(obj, '__init__'):
+ init_ds = getdoc(obj.__init__)
+ if init_ds is not None:
+ lines.append(head("Init docstring:"))
+ lines.append(indent(init_ds))
+ elif hasattr(obj,'__call__'):
+ call_ds = getdoc(obj.__call__)
+ if call_ds:
+ lines.append(head("Call docstring:"))
+ lines.append(indent(call_ds))
+
+ if not lines:
+ self.noinfo('documentation',oname)
+ else:
+ page.page('\n'.join(lines))
+
+ def psource(self, obj, oname=''):
+ """Print the source code for an object."""
+
+ # Flush the source cache because inspect can return out-of-date source
+ linecache.checkcache()
+ try:
+ src = getsource(obj, oname=oname)
+ except Exception:
+ src = None
+
+ if src is None:
+ self.noinfo('source', oname)
+ else:
+ page.page(self.format(src))
+
+ def pfile(self, obj, oname=''):
+ """Show the whole file where an object was defined."""
+
+ lineno = find_source_lines(obj)
+ if lineno is None:
+ self.noinfo('file', oname)
+ return
+
+ ofile = find_file(obj)
+ # run contents of file through pager starting at line where the object
+ # is defined, as long as the file isn't binary and is actually on the
+ # filesystem.
+ if ofile.endswith(('.so', '.dll', '.pyd')):
+ print('File %r is binary, not printing.' % ofile)
+ elif not os.path.isfile(ofile):
+ print('File %r does not exist, not printing.' % ofile)
+ else:
+ # Print only text files, not extension binaries. Note that
+ # getsourcelines returns lineno with 1-offset and page() uses
+ # 0-offset, so we must adjust.
+ page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
+
+ def _format_fields(self, fields, title_width=0):
+ """Formats a list of fields for display.
+
+ Parameters
+ ----------
+ fields : list
+ A list of 2-tuples: (field_title, field_content)
+ title_width : int
+ How many characters to pad titles to. Default to longest title.
+ """
+ out = []
+ header = self.__head
+ if title_width == 0:
+ title_width = max(len(title) + 2 for title, _ in fields)
+ for title, content in fields:
+ if len(content.splitlines()) > 1:
title = header(title + ':') + '\n'
- else:
+ else:
title = header((title + ':').ljust(title_width))
- out.append(cast_unicode(title) + cast_unicode(content))
- return "\n".join(out)
-
+ out.append(cast_unicode(title) + cast_unicode(content))
+ return "\n".join(out)
+
def _mime_format(self, text, formatter=None):
"""Return a mime bundle representation of the input text.
@@ -637,56 +637,56 @@ class Inspector(Colorable):
'text/html': pylight(text)
}
- if info['isalias']:
+ if info['isalias']:
append_field(_mime, 'Repr', 'string_form')
-
- elif info['ismagic']:
+
+ elif info['ismagic']:
if detail_level > 0:
append_field(_mime, 'Source', 'source', code_formatter)
- else:
+ else:
append_field(_mime, 'Docstring', 'docstring', formatter)
append_field(_mime, 'File', 'file')
-
- elif info['isclass'] or is_simple_callable(obj):
- # Functions, methods, classes
+
+ elif info['isclass'] or is_simple_callable(obj):
+ # Functions, methods, classes
append_field(_mime, 'Signature', 'definition', code_formatter)
append_field(_mime, 'Init signature', 'init_definition', code_formatter)
if detail_level > 0 and info['source']:
append_field(_mime, 'Source', 'source', code_formatter)
- else:
+ else:
append_field(_mime, 'Docstring', 'docstring', formatter)
append_field(_mime, 'Init docstring', 'init_docstring', formatter)
-
+
append_field(_mime, 'File', 'file')
append_field(_mime, 'Type', 'type_name')
-
- else:
- # General Python objects
+
+ else:
+ # General Python objects
append_field(_mime, 'Signature', 'definition', code_formatter)
append_field(_mime, 'Call signature', 'call_def', code_formatter)
append_field(_mime, 'Type', 'type_name')
-
- # Base class for old-style instances
- if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']:
+
+ # Base class for old-style instances
+ if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']:
append_field(_mime, 'Base Class', 'base_class')
-
+
append_field(_mime, 'String form', 'string_form')
-
- # Namespace
- if info['namespace'] != 'Interactive':
+
+ # Namespace
+ if info['namespace'] != 'Interactive':
append_field(_mime, 'Namespace', 'namespace')
-
+
append_field(_mime, 'Length', 'length')
append_field(_mime, 'File', 'file')
- # Source or docstring, depending on detail level and whether
- # source found.
+ # Source or docstring, depending on detail level and whether
+ # source found.
if detail_level > 0:
append_field(_mime, 'Source', 'source', code_formatter)
else:
append_field(_mime, 'Docstring', 'docstring', formatter)
-
+
append_field(_mime, 'Class docstring', 'class_docstring', formatter)
append_field(_mime, 'Init docstring', 'init_docstring', formatter)
append_field(_mime, 'Call docstring', 'call_docstring', formatter)
@@ -695,15 +695,15 @@ class Inspector(Colorable):
return self.format_mime(_mime)
def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True):
- """Show detailed information about an object.
-
- Optional arguments:
-
- - oname: name of the variable pointing to the object.
-
+ """Show detailed information about an object.
+
+ Optional arguments:
+
+ - oname: name of the variable pointing to the object.
+
- formatter: callable (optional)
A special formatter for docstrings.
-
+
The formatter is a callable that takes a string as an input
and returns either a formatted string or a mime type bundle
in the form of a dictionnary.
@@ -711,17 +711,17 @@ class Inspector(Colorable):
Although the support of custom formatter returning a string
instead of a mime type bundle is deprecated.
- - info: a structure with some information fields which may have been
- precomputed already.
-
- - detail_level: if set to 1, more information is given.
- """
+ - info: a structure with some information fields which may have been
+ precomputed already.
+
+ - detail_level: if set to 1, more information is given.
+ """
info = self._get_info(obj, oname, formatter, info, detail_level)
if not enable_html_pager:
del info['text/html']
page.page(info)
- def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
+ def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
"""DEPRECATED. Compute a dict with detailed information about an object.
"""
if formatter is not None:
@@ -731,126 +731,126 @@ class Inspector(Colorable):
return self._info(obj, oname=oname, info=info, detail_level=detail_level)
def _info(self, obj, oname='', info=None, detail_level=0):
- """Compute a dict with detailed information about an object.
-
- Optional arguments:
-
- - oname: name of the variable pointing to the object.
-
- - info: a structure with some information fields which may have been
- precomputed already.
-
- - detail_level: if set to 1, more information is given.
- """
-
- obj_type = type(obj)
-
- if info is None:
- ismagic = 0
- isalias = 0
- ospace = ''
- else:
- ismagic = info.ismagic
- isalias = info.isalias
- ospace = info.namespace
-
- # Get docstring, special-casing aliases:
- if isalias:
- if not callable(obj):
- try:
- ds = "Alias to the system command:\n %s" % obj[1]
- except:
- ds = "Alias: " + str(obj)
- else:
- ds = "Alias to " + str(obj)
- if obj.__doc__:
- ds += "\nDocstring:\n" + obj.__doc__
- else:
- ds = getdoc(obj)
- if ds is None:
- ds = '<no docstring>'
-
- # store output in a dict, we initialize it here and fill it as we go
- out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
-
- string_max = 200 # max size of strings to show (snipped if longer)
+ """Compute a dict with detailed information about an object.
+
+ Optional arguments:
+
+ - oname: name of the variable pointing to the object.
+
+ - info: a structure with some information fields which may have been
+ precomputed already.
+
+ - detail_level: if set to 1, more information is given.
+ """
+
+ obj_type = type(obj)
+
+ if info is None:
+ ismagic = 0
+ isalias = 0
+ ospace = ''
+ else:
+ ismagic = info.ismagic
+ isalias = info.isalias
+ ospace = info.namespace
+
+ # Get docstring, special-casing aliases:
+ if isalias:
+ if not callable(obj):
+ try:
+ ds = "Alias to the system command:\n %s" % obj[1]
+ except:
+ ds = "Alias: " + str(obj)
+ else:
+ ds = "Alias to " + str(obj)
+ if obj.__doc__:
+ ds += "\nDocstring:\n" + obj.__doc__
+ else:
+ ds = getdoc(obj)
+ if ds is None:
+ ds = '<no docstring>'
+
+ # store output in a dict, we initialize it here and fill it as we go
+ out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
+
+ string_max = 200 # max size of strings to show (snipped if longer)
shalf = int((string_max - 5) / 2)
-
- if ismagic:
- obj_type_name = 'Magic function'
- elif isalias:
- obj_type_name = 'System alias'
- else:
- obj_type_name = obj_type.__name__
- out['type_name'] = obj_type_name
-
- try:
- bclass = obj.__class__
- out['base_class'] = str(bclass)
- except: pass
-
- # String form, but snip if too long in ? form (full in ??)
- if detail_level >= self.str_detail_level:
- try:
- ostr = str(obj)
- str_head = 'string_form'
- if not detail_level and len(ostr)>string_max:
- ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
- ostr = ("\n" + " " * len(str_head.expandtabs())).\
- join(q.strip() for q in ostr.split("\n"))
- out[str_head] = ostr
- except:
- pass
-
- if ospace:
- out['namespace'] = ospace
-
- # Length (for strings and lists)
- try:
- out['length'] = str(len(obj))
- except: pass
-
- # Filename where object was defined
- binary_file = False
- fname = find_file(obj)
- if fname is None:
- # if anything goes wrong, we don't want to show source, so it's as
- # if the file was binary
- binary_file = True
- else:
- if fname.endswith(('.so', '.dll', '.pyd')):
- binary_file = True
- elif fname.endswith('<string>'):
- fname = 'Dynamically generated function. No source code available.'
- out['file'] = compress_user(fname)
-
- # Original source code for a callable, class or property.
- if detail_level:
- # Flush the source cache because inspect can return out-of-date
- # source
- linecache.checkcache()
- try:
- if isinstance(obj, property) or not binary_file:
- src = getsource(obj, oname)
- if src is not None:
- src = src.rstrip()
- out['source'] = src
-
- except Exception:
- pass
-
- # Add docstring only if no source is to be shown (avoid repetitions).
- if ds and out.get('source', None) is None:
- out['docstring'] = ds
-
- # Constructor docstring for classes
- if inspect.isclass(obj):
- out['isclass'] = True
+
+ if ismagic:
+ obj_type_name = 'Magic function'
+ elif isalias:
+ obj_type_name = 'System alias'
+ else:
+ obj_type_name = obj_type.__name__
+ out['type_name'] = obj_type_name
+
+ try:
+ bclass = obj.__class__
+ out['base_class'] = str(bclass)
+ except: pass
+
+ # String form, but snip if too long in ? form (full in ??)
+ if detail_level >= self.str_detail_level:
+ try:
+ ostr = str(obj)
+ str_head = 'string_form'
+ if not detail_level and len(ostr)>string_max:
+ ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
+ ostr = ("\n" + " " * len(str_head.expandtabs())).\
+ join(q.strip() for q in ostr.split("\n"))
+ out[str_head] = ostr
+ except:
+ pass
+
+ if ospace:
+ out['namespace'] = ospace
+
+ # Length (for strings and lists)
+ try:
+ out['length'] = str(len(obj))
+ except: pass
+
+ # Filename where object was defined
+ binary_file = False
+ fname = find_file(obj)
+ if fname is None:
+ # if anything goes wrong, we don't want to show source, so it's as
+ # if the file was binary
+ binary_file = True
+ else:
+ if fname.endswith(('.so', '.dll', '.pyd')):
+ binary_file = True
+ elif fname.endswith('<string>'):
+ fname = 'Dynamically generated function. No source code available.'
+ out['file'] = compress_user(fname)
+
+ # Original source code for a callable, class or property.
+ if detail_level:
+ # Flush the source cache because inspect can return out-of-date
+ # source
+ linecache.checkcache()
+ try:
+ if isinstance(obj, property) or not binary_file:
+ src = getsource(obj, oname)
+ if src is not None:
+ src = src.rstrip()
+ out['source'] = src
+
+ except Exception:
+ pass
+
+ # Add docstring only if no source is to be shown (avoid repetitions).
+ if ds and out.get('source', None) is None:
+ out['docstring'] = ds
+
+ # Constructor docstring for classes
+ if inspect.isclass(obj):
+ out['isclass'] = True
# get the init signature:
- try:
+ try:
init_def = self._getdef(obj, oname)
- except AttributeError:
+ except AttributeError:
init_def = None
# get the __init__ docstring
@@ -858,7 +858,7 @@ class Inspector(Colorable):
obj_init = obj.__init__
except AttributeError:
init_ds = None
- else:
+ else:
if init_def is None:
# Get signature from init if top-level sig failed.
# Can happen for built-in types (list, etc.).
@@ -867,149 +867,149 @@ class Inspector(Colorable):
except AttributeError:
pass
init_ds = getdoc(obj_init)
- # Skip Python's auto-generated docstrings
- if init_ds == _object_init_docstring:
- init_ds = None
-
+ # Skip Python's auto-generated docstrings
+ if init_ds == _object_init_docstring:
+ init_ds = None
+
if init_def:
out['init_definition'] = init_def
-
+
if init_ds:
out['init_docstring'] = init_ds
- # and class docstring for instances:
- else:
- # reconstruct the function definition and print it:
- defln = self._getdef(obj, oname)
- if defln:
+ # and class docstring for instances:
+ else:
+ # reconstruct the function definition and print it:
+ defln = self._getdef(obj, oname)
+ if defln:
out['definition'] = defln
-
- # First, check whether the instance docstring is identical to the
- # class one, and print it separately if they don't coincide. In
- # most cases they will, but it's nice to print all the info for
- # objects which use instance-customized docstrings.
- if ds:
- try:
- cls = getattr(obj,'__class__')
- except:
- class_ds = None
- else:
- class_ds = getdoc(cls)
- # Skip Python's auto-generated docstrings
- if class_ds in _builtin_type_docstrings:
- class_ds = None
- if class_ds and ds != class_ds:
- out['class_docstring'] = class_ds
-
- # Next, try to show constructor docstrings
- try:
- init_ds = getdoc(obj.__init__)
- # Skip Python's auto-generated docstrings
- if init_ds == _object_init_docstring:
- init_ds = None
- except AttributeError:
- init_ds = None
- if init_ds:
- out['init_docstring'] = init_ds
-
- # Call form docstring for callable instances
- if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
- call_def = self._getdef(obj.__call__, oname)
+
+ # First, check whether the instance docstring is identical to the
+ # class one, and print it separately if they don't coincide. In
+ # most cases they will, but it's nice to print all the info for
+ # objects which use instance-customized docstrings.
+ if ds:
+ try:
+ cls = getattr(obj,'__class__')
+ except:
+ class_ds = None
+ else:
+ class_ds = getdoc(cls)
+ # Skip Python's auto-generated docstrings
+ if class_ds in _builtin_type_docstrings:
+ class_ds = None
+ if class_ds and ds != class_ds:
+ out['class_docstring'] = class_ds
+
+ # Next, try to show constructor docstrings
+ try:
+ init_ds = getdoc(obj.__init__)
+ # Skip Python's auto-generated docstrings
+ if init_ds == _object_init_docstring:
+ init_ds = None
+ except AttributeError:
+ init_ds = None
+ if init_ds:
+ out['init_docstring'] = init_ds
+
+ # Call form docstring for callable instances
+ if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
+ call_def = self._getdef(obj.__call__, oname)
if call_def and (call_def != out.get('definition')):
- # it may never be the case that call def and definition differ,
- # but don't include the same signature twice
+ # it may never be the case that call def and definition differ,
+ # but don't include the same signature twice
out['call_def'] = call_def
- call_ds = getdoc(obj.__call__)
- # Skip Python's auto-generated docstrings
- if call_ds == _func_call_docstring:
- call_ds = None
- if call_ds:
- out['call_docstring'] = call_ds
-
- # Compute the object's argspec as a callable. The key is to decide
- # whether to pull it from the object itself, from its __init__ or
- # from its __call__ method.
-
- if inspect.isclass(obj):
- # Old-style classes need not have an __init__
- callable_obj = getattr(obj, "__init__", None)
- elif callable(obj):
- callable_obj = obj
- else:
- callable_obj = None
-
- if callable_obj is not None:
- try:
- argspec = getargspec(callable_obj)
- except (TypeError, AttributeError):
- # For extensions/builtins we can't retrieve the argspec
- pass
- else:
- # named tuples' _asdict() method returns an OrderedDict, but we
- # we want a normal
- out['argspec'] = argspec_dict = dict(argspec._asdict())
- # We called this varkw before argspec became a named tuple.
- # With getfullargspec it's also called varkw.
- if 'varkw' not in argspec_dict:
- argspec_dict['varkw'] = argspec_dict.pop('keywords')
-
- return object_info(**out)
-
- def psearch(self,pattern,ns_table,ns_search=[],
- ignore_case=False,show_all=False):
- """Search namespaces with wildcards for objects.
-
- Arguments:
-
- - pattern: string containing shell-like wildcards to use in namespace
- searches and optionally a type specification to narrow the search to
- objects of that type.
-
- - ns_table: dict of name->namespaces for search.
-
- Optional arguments:
-
- - ns_search: list of namespace names to include in search.
-
- - ignore_case(False): make the search case-insensitive.
-
- - show_all(False): show all names, including those starting with
- underscores.
- """
- #print 'ps pattern:<%r>' % pattern # dbg
-
- # defaults
- type_pattern = 'all'
- filter = ''
-
- cmds = pattern.split()
- len_cmds = len(cmds)
- if len_cmds == 1:
- # Only filter pattern given
- filter = cmds[0]
- elif len_cmds == 2:
- # Both filter and type specified
- filter,type_pattern = cmds
- else:
- raise ValueError('invalid argument string for psearch: <%s>' %
- pattern)
-
- # filter search namespaces
- for name in ns_search:
- if name not in ns_table:
- raise ValueError('invalid namespace <%s>. Valid names: %s' %
- (name,ns_table.keys()))
-
- #print 'type_pattern:',type_pattern # dbg
- search_result, namespaces_seen = set(), set()
- for ns_name in ns_search:
- ns = ns_table[ns_name]
- # Normally, locals and globals are the same, so we just check one.
- if id(ns) in namespaces_seen:
- continue
- namespaces_seen.add(id(ns))
- tmp_res = list_namespace(ns, type_pattern, filter,
- ignore_case=ignore_case, show_all=show_all)
- search_result.update(tmp_res)
-
- page.page('\n'.join(sorted(search_result)))
+ call_ds = getdoc(obj.__call__)
+ # Skip Python's auto-generated docstrings
+ if call_ds == _func_call_docstring:
+ call_ds = None
+ if call_ds:
+ out['call_docstring'] = call_ds
+
+ # Compute the object's argspec as a callable. The key is to decide
+ # whether to pull it from the object itself, from its __init__ or
+ # from its __call__ method.
+
+ if inspect.isclass(obj):
+ # Old-style classes need not have an __init__
+ callable_obj = getattr(obj, "__init__", None)
+ elif callable(obj):
+ callable_obj = obj
+ else:
+ callable_obj = None
+
+ if callable_obj is not None:
+ try:
+ argspec = getargspec(callable_obj)
+ except (TypeError, AttributeError):
+ # For extensions/builtins we can't retrieve the argspec
+ pass
+ else:
+ # named tuples' _asdict() method returns an OrderedDict, but we
+ # we want a normal
+ out['argspec'] = argspec_dict = dict(argspec._asdict())
+ # We called this varkw before argspec became a named tuple.
+ # With getfullargspec it's also called varkw.
+ if 'varkw' not in argspec_dict:
+ argspec_dict['varkw'] = argspec_dict.pop('keywords')
+
+ return object_info(**out)
+
+ def psearch(self,pattern,ns_table,ns_search=[],
+ ignore_case=False,show_all=False):
+ """Search namespaces with wildcards for objects.
+
+ Arguments:
+
+ - pattern: string containing shell-like wildcards to use in namespace
+ searches and optionally a type specification to narrow the search to
+ objects of that type.
+
+ - ns_table: dict of name->namespaces for search.
+
+ Optional arguments:
+
+ - ns_search: list of namespace names to include in search.
+
+ - ignore_case(False): make the search case-insensitive.
+
+ - show_all(False): show all names, including those starting with
+ underscores.
+ """
+ #print 'ps pattern:<%r>' % pattern # dbg
+
+ # defaults
+ type_pattern = 'all'
+ filter = ''
+
+ cmds = pattern.split()
+ len_cmds = len(cmds)
+ if len_cmds == 1:
+ # Only filter pattern given
+ filter = cmds[0]
+ elif len_cmds == 2:
+ # Both filter and type specified
+ filter,type_pattern = cmds
+ else:
+ raise ValueError('invalid argument string for psearch: <%s>' %
+ pattern)
+
+ # filter search namespaces
+ for name in ns_search:
+ if name not in ns_table:
+ raise ValueError('invalid namespace <%s>. Valid names: %s' %
+ (name,ns_table.keys()))
+
+ #print 'type_pattern:',type_pattern # dbg
+ search_result, namespaces_seen = set(), set()
+ for ns_name in ns_search:
+ ns = ns_table[ns_name]
+ # Normally, locals and globals are the same, so we just check one.
+ if id(ns) in namespaces_seen:
+ continue
+ namespaces_seen.add(id(ns))
+ tmp_res = list_namespace(ns, type_pattern, filter,
+ ignore_case=ignore_case, show_all=show_all)
+ search_result.update(tmp_res)
+
+ page.page('\n'.join(sorted(search_result)))
diff --git a/contrib/python/ipython/py2/IPython/core/page.py b/contrib/python/ipython/py2/IPython/core/page.py
index ba14901e19..6d213c9f29 100644
--- a/contrib/python/ipython/py2/IPython/core/page.py
+++ b/contrib/python/ipython/py2/IPython/core/page.py
@@ -1,386 +1,386 @@
-# encoding: utf-8
-"""
-Paging capabilities for IPython.core
-
-Notes
------
-
-For now this uses IPython hooks, so it can't be in IPython.utils. If we can get
-rid of that dependency, we could move it there.
------
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
-import os
-import re
-import sys
-import tempfile
-
-from io import UnsupportedOperation
-
-from IPython import get_ipython
-from IPython.core.display import display
-from IPython.core.error import TryNext
-from IPython.utils.data import chop
-from IPython.utils.process import system
-from IPython.utils.terminal import get_terminal_size
-from IPython.utils import py3compat
-
-
-def display_page(strng, start=0, screen_lines=25):
- """Just display, no paging. screen_lines is ignored."""
- if isinstance(strng, dict):
- data = strng
- else:
- if start:
- strng = u'\n'.join(strng.splitlines()[start:])
+# encoding: utf-8
+"""
+Paging capabilities for IPython.core
+
+Notes
+-----
+
+For now this uses IPython hooks, so it can't be in IPython.utils. If we can get
+rid of that dependency, we could move it there.
+-----
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
+import os
+import re
+import sys
+import tempfile
+
+from io import UnsupportedOperation
+
+from IPython import get_ipython
+from IPython.core.display import display
+from IPython.core.error import TryNext
+from IPython.utils.data import chop
+from IPython.utils.process import system
+from IPython.utils.terminal import get_terminal_size
+from IPython.utils import py3compat
+
+
+def display_page(strng, start=0, screen_lines=25):
+ """Just display, no paging. screen_lines is ignored."""
+ if isinstance(strng, dict):
+ data = strng
+ else:
+ if start:
+ strng = u'\n'.join(strng.splitlines()[start:])
data = { 'text/plain': strng }
- display(data, raw=True)
-
-
-def as_hook(page_func):
- """Wrap a pager func to strip the `self` arg
-
- so it can be called as a hook.
- """
- return lambda self, *args, **kwargs: page_func(*args, **kwargs)
-
-
-esc_re = re.compile(r"(\x1b[^m]+m)")
-
-def page_dumb(strng, start=0, screen_lines=25):
- """Very dumb 'pager' in Python, for when nothing else works.
-
- Only moves forward, same interface as page(), except for pager_cmd and
+ display(data, raw=True)
+
+
+def as_hook(page_func):
+ """Wrap a pager func to strip the `self` arg
+
+ so it can be called as a hook.
+ """
+ return lambda self, *args, **kwargs: page_func(*args, **kwargs)
+
+
+esc_re = re.compile(r"(\x1b[^m]+m)")
+
+def page_dumb(strng, start=0, screen_lines=25):
+ """Very dumb 'pager' in Python, for when nothing else works.
+
+ Only moves forward, same interface as page(), except for pager_cmd and
mode.
"""
if isinstance(strng, dict):
strng = strng.get('text/plain', '')
- out_ln = strng.splitlines()[start:]
- screens = chop(out_ln,screen_lines-1)
- if len(screens) == 1:
+ out_ln = strng.splitlines()[start:]
+ screens = chop(out_ln,screen_lines-1)
+ if len(screens) == 1:
print(os.linesep.join(screens[0]))
- else:
- last_escape = ""
- for scr in screens[0:-1]:
- hunk = os.linesep.join(scr)
+ else:
+ last_escape = ""
+ for scr in screens[0:-1]:
+ hunk = os.linesep.join(scr)
print(last_escape + hunk)
- if not page_more():
- return
- esc_list = esc_re.findall(hunk)
- if len(esc_list) > 0:
- last_escape = esc_list[-1]
+ if not page_more():
+ return
+ esc_list = esc_re.findall(hunk)
+ if len(esc_list) > 0:
+ last_escape = esc_list[-1]
print(last_escape + os.linesep.join(screens[-1]))
-
-def _detect_screen_size(screen_lines_def):
- """Attempt to work out the number of lines on the screen.
-
- This is called by page(). It can raise an error (e.g. when run in the
- test suite), so it's separated out so it can easily be called in a try block.
- """
- TERM = os.environ.get('TERM',None)
- if not((TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5'):
- # curses causes problems on many terminals other than xterm, and
- # some termios calls lock up on Sun OS5.
- return screen_lines_def
-
- try:
- import termios
- import curses
- except ImportError:
- return screen_lines_def
-
- # There is a bug in curses, where *sometimes* it fails to properly
- # initialize, and then after the endwin() call is made, the
- # terminal is left in an unusable state. Rather than trying to
- # check everytime for this (by requesting and comparing termios
- # flags each time), we just save the initial terminal state and
- # unconditionally reset it every time. It's cheaper than making
- # the checks.
- try:
- term_flags = termios.tcgetattr(sys.stdout)
- except termios.error as err:
- # can fail on Linux 2.6, pager_page will catch the TypeError
- raise TypeError('termios error: {0}'.format(err))
-
- # Curses modifies the stdout buffer size by default, which messes
- # up Python's normal stdout buffering. This would manifest itself
- # to IPython users as delayed printing on stdout after having used
- # the pager.
- #
- # We can prevent this by manually setting the NCURSES_NO_SETBUF
- # environment variable. For more details, see:
- # http://bugs.python.org/issue10144
- NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
- os.environ['NCURSES_NO_SETBUF'] = ''
-
- # Proceed with curses initialization
- try:
- scr = curses.initscr()
- except AttributeError:
- # Curses on Solaris may not be complete, so we can't use it there
- return screen_lines_def
-
- screen_lines_real,screen_cols = scr.getmaxyx()
- curses.endwin()
-
- # Restore environment
- if NCURSES_NO_SETBUF is None:
- del os.environ['NCURSES_NO_SETBUF']
- else:
- os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
-
- # Restore terminal state in case endwin() didn't.
- termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
- # Now we have what we needed: the screen size in rows/columns
- return screen_lines_real
- #print '***Screen size:',screen_lines_real,'lines x',\
- #screen_cols,'columns.' # dbg
-
-def pager_page(strng, start=0, screen_lines=0, pager_cmd=None):
- """Display a string, piping through a pager after a certain length.
-
- strng can be a mime-bundle dict, supplying multiple representations,
- keyed by mime-type.
-
- The screen_lines parameter specifies the number of *usable* lines of your
- terminal screen (total lines minus lines you need to reserve to show other
- information).
-
- If you set screen_lines to a number <=0, page() will try to auto-determine
- your screen size and will only use up to (screen_size+screen_lines) for
- printing, paging after that. That is, if you want auto-detection but need
- to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
- auto-detection without any lines reserved simply use screen_lines = 0.
-
- If a string won't fit in the allowed lines, it is sent through the
- specified pager command. If none given, look for PAGER in the environment,
- and ultimately default to less.
-
- If no system pager works, the string is sent through a 'dumb pager'
- written in python, very simplistic.
- """
-
- # for compatibility with mime-bundle form:
- if isinstance(strng, dict):
- strng = strng['text/plain']
-
- # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
- TERM = os.environ.get('TERM','dumb')
- if TERM in ['dumb','emacs'] and os.name != 'nt':
- print(strng)
- return
- # chop off the topmost part of the string we don't want to see
- str_lines = strng.splitlines()[start:]
- str_toprint = os.linesep.join(str_lines)
- num_newlines = len(str_lines)
- len_str = len(str_toprint)
-
- # Dumb heuristics to guesstimate number of on-screen lines the string
- # takes. Very basic, but good enough for docstrings in reasonable
- # terminals. If someone later feels like refining it, it's not hard.
- numlines = max(num_newlines,int(len_str/80)+1)
-
- screen_lines_def = get_terminal_size()[1]
-
- # auto-determine screen size
- if screen_lines <= 0:
- try:
- screen_lines += _detect_screen_size(screen_lines_def)
- except (TypeError, UnsupportedOperation):
+
+def _detect_screen_size(screen_lines_def):
+ """Attempt to work out the number of lines on the screen.
+
+ This is called by page(). It can raise an error (e.g. when run in the
+ test suite), so it's separated out so it can easily be called in a try block.
+ """
+ TERM = os.environ.get('TERM',None)
+ if not((TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5'):
+ # curses causes problems on many terminals other than xterm, and
+ # some termios calls lock up on Sun OS5.
+ return screen_lines_def
+
+ try:
+ import termios
+ import curses
+ except ImportError:
+ return screen_lines_def
+
+ # There is a bug in curses, where *sometimes* it fails to properly
+ # initialize, and then after the endwin() call is made, the
+ # terminal is left in an unusable state. Rather than trying to
+ # check everytime for this (by requesting and comparing termios
+ # flags each time), we just save the initial terminal state and
+ # unconditionally reset it every time. It's cheaper than making
+ # the checks.
+ try:
+ term_flags = termios.tcgetattr(sys.stdout)
+ except termios.error as err:
+ # can fail on Linux 2.6, pager_page will catch the TypeError
+ raise TypeError('termios error: {0}'.format(err))
+
+ # Curses modifies the stdout buffer size by default, which messes
+ # up Python's normal stdout buffering. This would manifest itself
+ # to IPython users as delayed printing on stdout after having used
+ # the pager.
+ #
+ # We can prevent this by manually setting the NCURSES_NO_SETBUF
+ # environment variable. For more details, see:
+ # http://bugs.python.org/issue10144
+ NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
+ os.environ['NCURSES_NO_SETBUF'] = ''
+
+ # Proceed with curses initialization
+ try:
+ scr = curses.initscr()
+ except AttributeError:
+ # Curses on Solaris may not be complete, so we can't use it there
+ return screen_lines_def
+
+ screen_lines_real,screen_cols = scr.getmaxyx()
+ curses.endwin()
+
+ # Restore environment
+ if NCURSES_NO_SETBUF is None:
+ del os.environ['NCURSES_NO_SETBUF']
+ else:
+ os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
+
+ # Restore terminal state in case endwin() didn't.
+ termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
+ # Now we have what we needed: the screen size in rows/columns
+ return screen_lines_real
+ #print '***Screen size:',screen_lines_real,'lines x',\
+ #screen_cols,'columns.' # dbg
+
+def pager_page(strng, start=0, screen_lines=0, pager_cmd=None):
+ """Display a string, piping through a pager after a certain length.
+
+ strng can be a mime-bundle dict, supplying multiple representations,
+ keyed by mime-type.
+
+ The screen_lines parameter specifies the number of *usable* lines of your
+ terminal screen (total lines minus lines you need to reserve to show other
+ information).
+
+ If you set screen_lines to a number <=0, page() will try to auto-determine
+ your screen size and will only use up to (screen_size+screen_lines) for
+ printing, paging after that. That is, if you want auto-detection but need
+ to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
+ auto-detection without any lines reserved simply use screen_lines = 0.
+
+ If a string won't fit in the allowed lines, it is sent through the
+ specified pager command. If none given, look for PAGER in the environment,
+ and ultimately default to less.
+
+ If no system pager works, the string is sent through a 'dumb pager'
+ written in python, very simplistic.
+ """
+
+ # for compatibility with mime-bundle form:
+ if isinstance(strng, dict):
+ strng = strng['text/plain']
+
+ # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
+ TERM = os.environ.get('TERM','dumb')
+ if TERM in ['dumb','emacs'] and os.name != 'nt':
+ print(strng)
+ return
+ # chop off the topmost part of the string we don't want to see
+ str_lines = strng.splitlines()[start:]
+ str_toprint = os.linesep.join(str_lines)
+ num_newlines = len(str_lines)
+ len_str = len(str_toprint)
+
+ # Dumb heuristics to guesstimate number of on-screen lines the string
+ # takes. Very basic, but good enough for docstrings in reasonable
+ # terminals. If someone later feels like refining it, it's not hard.
+ numlines = max(num_newlines,int(len_str/80)+1)
+
+ screen_lines_def = get_terminal_size()[1]
+
+ # auto-determine screen size
+ if screen_lines <= 0:
+ try:
+ screen_lines += _detect_screen_size(screen_lines_def)
+ except (TypeError, UnsupportedOperation):
print(str_toprint)
- return
-
- #print 'numlines',numlines,'screenlines',screen_lines # dbg
- if numlines <= screen_lines :
- #print '*** normal print' # dbg
+ return
+
+ #print 'numlines',numlines,'screenlines',screen_lines # dbg
+ if numlines <= screen_lines :
+ #print '*** normal print' # dbg
print(str_toprint)
- else:
- # Try to open pager and default to internal one if that fails.
- # All failure modes are tagged as 'retval=1', to match the return
- # value of a failed system command. If any intermediate attempt
- # sets retval to 1, at the end we resort to our own page_dumb() pager.
- pager_cmd = get_pager_cmd(pager_cmd)
- pager_cmd += ' ' + get_pager_start(pager_cmd,start)
- if os.name == 'nt':
- if pager_cmd.startswith('type'):
- # The default WinXP 'type' command is failing on complex strings.
- retval = 1
- else:
- fd, tmpname = tempfile.mkstemp('.txt')
- try:
- os.close(fd)
- with open(tmpname, 'wt') as tmpfile:
- tmpfile.write(strng)
- cmd = "%s < %s" % (pager_cmd, tmpname)
- # tmpfile needs to be closed for windows
- if os.system(cmd):
- retval = 1
- else:
- retval = None
- finally:
- os.remove(tmpname)
- else:
- try:
- retval = None
- # if I use popen4, things hang. No idea why.
- #pager,shell_out = os.popen4(pager_cmd)
- pager = os.popen(pager_cmd, 'w')
- try:
- pager_encoding = pager.encoding or sys.stdout.encoding
- pager.write(py3compat.cast_bytes_py2(
- strng, encoding=pager_encoding))
- finally:
- retval = pager.close()
- except IOError as msg: # broken pipe when user quits
- if msg.args == (32, 'Broken pipe'):
- retval = None
- else:
- retval = 1
- except OSError:
- # Other strange problems, sometimes seen in Win2k/cygwin
- retval = 1
- if retval is not None:
- page_dumb(strng,screen_lines=screen_lines)
-
-
-def page(data, start=0, screen_lines=0, pager_cmd=None):
- """Display content in a pager, piping through a pager after a certain length.
-
- data can be a mime-bundle dict, supplying multiple representations,
- keyed by mime-type, or text.
-
- Pager is dispatched via the `show_in_pager` IPython hook.
- If no hook is registered, `pager_page` will be used.
- """
- # Some routines may auto-compute start offsets incorrectly and pass a
- # negative value. Offset to 0 for robustness.
- start = max(0, start)
-
- # first, try the hook
- ip = get_ipython()
- if ip:
- try:
- ip.hooks.show_in_pager(data, start=start, screen_lines=screen_lines)
- return
- except TryNext:
- pass
-
- # fallback on default pager
- return pager_page(data, start, screen_lines, pager_cmd)
-
-
-def page_file(fname, start=0, pager_cmd=None):
- """Page a file, using an optional pager command and starting line.
- """
-
- pager_cmd = get_pager_cmd(pager_cmd)
- pager_cmd += ' ' + get_pager_start(pager_cmd,start)
-
- try:
- if os.environ['TERM'] in ['emacs','dumb']:
- raise EnvironmentError
- system(pager_cmd + ' ' + fname)
- except:
- try:
- if start > 0:
- start -= 1
- page(open(fname).read(),start)
- except:
- print('Unable to show file',repr(fname))
-
-
-def get_pager_cmd(pager_cmd=None):
- """Return a pager command.
-
- Makes some attempts at finding an OS-correct one.
- """
- if os.name == 'posix':
+ else:
+ # Try to open pager and default to internal one if that fails.
+ # All failure modes are tagged as 'retval=1', to match the return
+ # value of a failed system command. If any intermediate attempt
+ # sets retval to 1, at the end we resort to our own page_dumb() pager.
+ pager_cmd = get_pager_cmd(pager_cmd)
+ pager_cmd += ' ' + get_pager_start(pager_cmd,start)
+ if os.name == 'nt':
+ if pager_cmd.startswith('type'):
+ # The default WinXP 'type' command is failing on complex strings.
+ retval = 1
+ else:
+ fd, tmpname = tempfile.mkstemp('.txt')
+ try:
+ os.close(fd)
+ with open(tmpname, 'wt') as tmpfile:
+ tmpfile.write(strng)
+ cmd = "%s < %s" % (pager_cmd, tmpname)
+ # tmpfile needs to be closed for windows
+ if os.system(cmd):
+ retval = 1
+ else:
+ retval = None
+ finally:
+ os.remove(tmpname)
+ else:
+ try:
+ retval = None
+ # if I use popen4, things hang. No idea why.
+ #pager,shell_out = os.popen4(pager_cmd)
+ pager = os.popen(pager_cmd, 'w')
+ try:
+ pager_encoding = pager.encoding or sys.stdout.encoding
+ pager.write(py3compat.cast_bytes_py2(
+ strng, encoding=pager_encoding))
+ finally:
+ retval = pager.close()
+ except IOError as msg: # broken pipe when user quits
+ if msg.args == (32, 'Broken pipe'):
+ retval = None
+ else:
+ retval = 1
+ except OSError:
+ # Other strange problems, sometimes seen in Win2k/cygwin
+ retval = 1
+ if retval is not None:
+ page_dumb(strng,screen_lines=screen_lines)
+
+
+def page(data, start=0, screen_lines=0, pager_cmd=None):
+ """Display content in a pager, piping through a pager after a certain length.
+
+ data can be a mime-bundle dict, supplying multiple representations,
+ keyed by mime-type, or text.
+
+ Pager is dispatched via the `show_in_pager` IPython hook.
+ If no hook is registered, `pager_page` will be used.
+ """
+ # Some routines may auto-compute start offsets incorrectly and pass a
+ # negative value. Offset to 0 for robustness.
+ start = max(0, start)
+
+ # first, try the hook
+ ip = get_ipython()
+ if ip:
+ try:
+ ip.hooks.show_in_pager(data, start=start, screen_lines=screen_lines)
+ return
+ except TryNext:
+ pass
+
+ # fallback on default pager
+ return pager_page(data, start, screen_lines, pager_cmd)
+
+
+def page_file(fname, start=0, pager_cmd=None):
+ """Page a file, using an optional pager command and starting line.
+ """
+
+ pager_cmd = get_pager_cmd(pager_cmd)
+ pager_cmd += ' ' + get_pager_start(pager_cmd,start)
+
+ try:
+ if os.environ['TERM'] in ['emacs','dumb']:
+ raise EnvironmentError
+ system(pager_cmd + ' ' + fname)
+ except:
+ try:
+ if start > 0:
+ start -= 1
+ page(open(fname).read(),start)
+ except:
+ print('Unable to show file',repr(fname))
+
+
+def get_pager_cmd(pager_cmd=None):
+ """Return a pager command.
+
+ Makes some attempts at finding an OS-correct one.
+ """
+ if os.name == 'posix':
default_pager_cmd = 'less -R' # -R for color control sequences
- elif os.name in ['nt','dos']:
- default_pager_cmd = 'type'
-
- if pager_cmd is None:
- try:
- pager_cmd = os.environ['PAGER']
- except:
- pager_cmd = default_pager_cmd
+ elif os.name in ['nt','dos']:
+ default_pager_cmd = 'type'
+
+ if pager_cmd is None:
+ try:
+ pager_cmd = os.environ['PAGER']
+ except:
+ pager_cmd = default_pager_cmd
if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower():
pager_cmd += ' -R'
- return pager_cmd
-
-
-def get_pager_start(pager, start):
- """Return the string for paging files with an offset.
-
- This is the '+N' argument which less and more (under Unix) accept.
- """
-
- if pager in ['less','more']:
- if start:
- start_string = '+' + str(start)
- else:
- start_string = ''
- else:
- start_string = ''
- return start_string
-
-
-# (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
-if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
- import msvcrt
- def page_more():
- """ Smart pausing between pages
-
- @return: True if need print more lines, False if quit
- """
+ return pager_cmd
+
+
+def get_pager_start(pager, start):
+ """Return the string for paging files with an offset.
+
+ This is the '+N' argument which less and more (under Unix) accept.
+ """
+
+ if pager in ['less','more']:
+ if start:
+ start_string = '+' + str(start)
+ else:
+ start_string = ''
+ else:
+ start_string = ''
+ return start_string
+
+
+# (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
+if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
+ import msvcrt
+ def page_more():
+ """ Smart pausing between pages
+
+ @return: True if need print more lines, False if quit
+ """
sys.stdout.write('---Return to continue, q to quit--- ')
- ans = msvcrt.getwch()
- if ans in ("q", "Q"):
- result = False
- else:
- result = True
+ ans = msvcrt.getwch()
+ if ans in ("q", "Q"):
+ result = False
+ else:
+ result = True
sys.stdout.write("\b"*37 + " "*37 + "\b"*37)
- return result
-else:
- def page_more():
- ans = py3compat.input('---Return to continue, q to quit--- ')
- if ans.lower().startswith('q'):
- return False
- else:
- return True
-
-
-def snip_print(str,width = 75,print_full = 0,header = ''):
- """Print a string snipping the midsection to fit in width.
-
- print_full: mode control:
-
- - 0: only snip long strings
- - 1: send to page() directly.
- - 2: snip long strings and ask for full length viewing with page()
-
- Return 1 if snipping was necessary, 0 otherwise."""
-
- if print_full == 1:
- page(header+str)
- return 0
-
- print(header, end=' ')
- if len(str) < width:
- print(str)
- snip = 0
- else:
- whalf = int((width -5)/2)
- print(str[:whalf] + ' <...> ' + str[-whalf:])
- snip = 1
- if snip and print_full == 2:
- if py3compat.input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
- page(str)
- return snip
+ return result
+else:
+ def page_more():
+ ans = py3compat.input('---Return to continue, q to quit--- ')
+ if ans.lower().startswith('q'):
+ return False
+ else:
+ return True
+
+
+def snip_print(str,width = 75,print_full = 0,header = ''):
+ """Print a string snipping the midsection to fit in width.
+
+ print_full: mode control:
+
+ - 0: only snip long strings
+ - 1: send to page() directly.
+ - 2: snip long strings and ask for full length viewing with page()
+
+ Return 1 if snipping was necessary, 0 otherwise."""
+
+ if print_full == 1:
+ page(header+str)
+ return 0
+
+ print(header, end=' ')
+ if len(str) < width:
+ print(str)
+ snip = 0
+ else:
+ whalf = int((width -5)/2)
+ print(str[:whalf] + ' <...> ' + str[-whalf:])
+ snip = 1
+ if snip and print_full == 2:
+ if py3compat.input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
+ page(str)
+ return snip
diff --git a/contrib/python/ipython/py2/IPython/core/payload.py b/contrib/python/ipython/py2/IPython/core/payload.py
index caa9268fe2..6818be1537 100644
--- a/contrib/python/ipython/py2/IPython/core/payload.py
+++ b/contrib/python/ipython/py2/IPython/core/payload.py
@@ -1,55 +1,55 @@
-# -*- coding: utf-8 -*-
-"""Payload system for IPython.
-
-Authors:
-
-* Fernando Perez
-* Brian Granger
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from traitlets.config.configurable import Configurable
-from traitlets import List
-
-#-----------------------------------------------------------------------------
-# Main payload class
-#-----------------------------------------------------------------------------
-
-class PayloadManager(Configurable):
-
- _payload = List([])
-
- def write_payload(self, data, single=True):
- """Include or update the specified `data` payload in the PayloadManager.
-
- If a previous payload with the same source exists and `single` is True,
- it will be overwritten with the new one.
- """
-
- if not isinstance(data, dict):
- raise TypeError('Each payload write must be a dict, got: %r' % data)
-
- if single and 'source' in data:
- source = data['source']
- for i, pl in enumerate(self._payload):
- if 'source' in pl and pl['source'] == source:
- self._payload[i] = data
- return
-
- self._payload.append(data)
-
- def read_payload(self):
- return self._payload
-
- def clear_payload(self):
- self._payload = []
+# -*- coding: utf-8 -*-
+"""Payload system for IPython.
+
+Authors:
+
+* Fernando Perez
+* Brian Granger
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+from traitlets.config.configurable import Configurable
+from traitlets import List
+
+#-----------------------------------------------------------------------------
+# Main payload class
+#-----------------------------------------------------------------------------
+
+class PayloadManager(Configurable):
+
+ _payload = List([])
+
+ def write_payload(self, data, single=True):
+ """Include or update the specified `data` payload in the PayloadManager.
+
+ If a previous payload with the same source exists and `single` is True,
+ it will be overwritten with the new one.
+ """
+
+ if not isinstance(data, dict):
+ raise TypeError('Each payload write must be a dict, got: %r' % data)
+
+ if single and 'source' in data:
+ source = data['source']
+ for i, pl in enumerate(self._payload):
+ if 'source' in pl and pl['source'] == source:
+ self._payload[i] = data
+ return
+
+ self._payload.append(data)
+
+ def read_payload(self):
+ return self._payload
+
+ def clear_payload(self):
+ self._payload = []
diff --git a/contrib/python/ipython/py2/IPython/core/payloadpage.py b/contrib/python/ipython/py2/IPython/core/payloadpage.py
index 43ac441631..eb613445dd 100644
--- a/contrib/python/ipython/py2/IPython/core/payloadpage.py
+++ b/contrib/python/ipython/py2/IPython/core/payloadpage.py
@@ -1,52 +1,52 @@
-# encoding: utf-8
-"""A payload based version of page."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import warnings
-from IPython.core.getipython import get_ipython
-
-
-def page(strng, start=0, screen_lines=0, pager_cmd=None):
- """Print a string, piping through a pager.
-
- This version ignores the screen_lines and pager_cmd arguments and uses
- IPython's payload system instead.
-
- Parameters
- ----------
- strng : str or mime-dict
- Text to page, or a mime-type keyed dict of already formatted data.
-
- start : int
- Starting line at which to place the display.
- """
-
- # Some routines may auto-compute start offsets incorrectly and pass a
- # negative value. Offset to 0 for robustness.
- start = max(0, start)
- shell = get_ipython()
-
- if isinstance(strng, dict):
- data = strng
- else:
- data = {'text/plain' : strng}
- payload = dict(
- source='page',
- data=data,
- start=start,
- )
- shell.payload_manager.write_payload(payload)
-
-
-def install_payload_page():
- """DEPRECATED, use show_in_pager hook
-
- Install this version of page as IPython.core.page.page.
- """
- warnings.warn("""install_payload_page is deprecated.
- Use `ip.set_hook('show_in_pager, page.as_hook(payloadpage.page))`
- """)
- from IPython.core import page as corepage
- corepage.page = page
+# encoding: utf-8
+"""A payload based version of page."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import warnings
+from IPython.core.getipython import get_ipython
+
+
+def page(strng, start=0, screen_lines=0, pager_cmd=None):
+ """Print a string, piping through a pager.
+
+ This version ignores the screen_lines and pager_cmd arguments and uses
+ IPython's payload system instead.
+
+ Parameters
+ ----------
+ strng : str or mime-dict
+ Text to page, or a mime-type keyed dict of already formatted data.
+
+ start : int
+ Starting line at which to place the display.
+ """
+
+ # Some routines may auto-compute start offsets incorrectly and pass a
+ # negative value. Offset to 0 for robustness.
+ start = max(0, start)
+ shell = get_ipython()
+
+ if isinstance(strng, dict):
+ data = strng
+ else:
+ data = {'text/plain' : strng}
+ payload = dict(
+ source='page',
+ data=data,
+ start=start,
+ )
+ shell.payload_manager.write_payload(payload)
+
+
+def install_payload_page():
+ """DEPRECATED, use show_in_pager hook
+
+ Install this version of page as IPython.core.page.page.
+ """
+ warnings.warn("""install_payload_page is deprecated.
+ Use `ip.set_hook('show_in_pager, page.as_hook(payloadpage.page))`
+ """)
+ from IPython.core import page as corepage
+ corepage.page = page
diff --git a/contrib/python/ipython/py2/IPython/core/prefilter.py b/contrib/python/ipython/py2/IPython/core/prefilter.py
index 953b6d2d43..cbed3fd80a 100644
--- a/contrib/python/ipython/py2/IPython/core/prefilter.py
+++ b/contrib/python/ipython/py2/IPython/core/prefilter.py
@@ -1,700 +1,700 @@
-# encoding: utf-8
-"""
-Prefiltering components.
-
-Prefilters transform user input before it is exec'd by Python. These
-transforms are used to implement additional syntax such as !ls and %magic.
-"""
-
+# encoding: utf-8
+"""
+Prefiltering components.
+
+Prefilters transform user input before it is exec'd by Python. These
+transforms are used to implement additional syntax such as !ls and %magic.
+"""
+
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
-
-from keyword import iskeyword
-import re
-
-from IPython.core.autocall import IPyAutocall
-from traitlets.config.configurable import Configurable
-from IPython.core.inputsplitter import (
- ESC_MAGIC,
- ESC_QUOTE,
- ESC_QUOTE2,
- ESC_PAREN,
-)
-from IPython.core.macro import Macro
-from IPython.core.splitinput import LineInfo
-
-from traitlets import (
+
+from keyword import iskeyword
+import re
+
+from IPython.core.autocall import IPyAutocall
+from traitlets.config.configurable import Configurable
+from IPython.core.inputsplitter import (
+ ESC_MAGIC,
+ ESC_QUOTE,
+ ESC_QUOTE2,
+ ESC_PAREN,
+)
+from IPython.core.macro import Macro
+from IPython.core.splitinput import LineInfo
+
+from traitlets import (
List, Integer, Unicode, Bool, Instance, CRegExp
-)
-
-#-----------------------------------------------------------------------------
-# Global utilities, errors and constants
-#-----------------------------------------------------------------------------
-
-
-class PrefilterError(Exception):
- pass
-
-
-# RegExp to identify potential function names
-re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
-
-# RegExp to exclude strings with this start from autocalling. In
-# particular, all binary operators should be excluded, so that if foo is
-# callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
-# characters '!=()' don't need to be checked for, as the checkPythonChars
-# routine explicitely does so, to catch direct calls and rebindings of
-# existing names.
-
-# Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
-# it affects the rest of the group in square brackets.
-re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
- r'|^is |^not |^in |^and |^or ')
-
-# try to catch also methods for stuff in lists/tuples/dicts: off
-# (experimental). For this to work, the line_split regexp would need
-# to be modified so it wouldn't break things at '['. That line is
-# nasty enough that I shouldn't change it until I can test it _well_.
-#self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
-
-
-# Handler Check Utilities
-def is_shadowed(identifier, ip):
- """Is the given identifier defined in one of the namespaces which shadow
- the alias and magic namespaces? Note that an identifier is different
- than ifun, because it can not contain a '.' character."""
- # This is much safer than calling ofind, which can change state
- return (identifier in ip.user_ns \
- or identifier in ip.user_global_ns \
- or identifier in ip.ns_table['builtin']\
- or iskeyword(identifier))
-
-
-#-----------------------------------------------------------------------------
-# Main Prefilter manager
-#-----------------------------------------------------------------------------
-
-
-class PrefilterManager(Configurable):
- """Main prefilter component.
-
- The IPython prefilter is run on all user input before it is run. The
- prefilter consumes lines of input and produces transformed lines of
- input.
-
- The iplementation consists of two phases:
-
- 1. Transformers
- 2. Checkers and handlers
-
- Over time, we plan on deprecating the checkers and handlers and doing
- everything in the transformers.
-
- The transformers are instances of :class:`PrefilterTransformer` and have
- a single method :meth:`transform` that takes a line and returns a
- transformed line. The transformation can be accomplished using any
- tool, but our current ones use regular expressions for speed.
-
- After all the transformers have been run, the line is fed to the checkers,
- which are instances of :class:`PrefilterChecker`. The line is passed to
- the :meth:`check` method, which either returns `None` or a
- :class:`PrefilterHandler` instance. If `None` is returned, the other
- checkers are tried. If an :class:`PrefilterHandler` instance is returned,
- the line is passed to the :meth:`handle` method of the returned
- handler and no further checkers are tried.
-
- Both transformers and checkers have a `priority` attribute, that determines
- the order in which they are called. Smaller priorities are tried first.
-
- Both transformers and checkers also have `enabled` attribute, which is
- a boolean that determines if the instance is used.
-
- Users or developers can change the priority or enabled attribute of
- transformers or checkers, but they must call the :meth:`sort_checkers`
- or :meth:`sort_transformers` method after changing the priority.
- """
-
+)
+
+#-----------------------------------------------------------------------------
+# Global utilities, errors and constants
+#-----------------------------------------------------------------------------
+
+
+class PrefilterError(Exception):
+ pass
+
+
+# RegExp to identify potential function names
+re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
+
+# RegExp to exclude strings with this start from autocalling. In
+# particular, all binary operators should be excluded, so that if foo is
+# callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
+# characters '!=()' don't need to be checked for, as the checkPythonChars
+# routine explicitely does so, to catch direct calls and rebindings of
+# existing names.
+
+# Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
+# it affects the rest of the group in square brackets.
+re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
+ r'|^is |^not |^in |^and |^or ')
+
+# try to catch also methods for stuff in lists/tuples/dicts: off
+# (experimental). For this to work, the line_split regexp would need
+# to be modified so it wouldn't break things at '['. That line is
+# nasty enough that I shouldn't change it until I can test it _well_.
+#self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
+
+
+# Handler Check Utilities
+def is_shadowed(identifier, ip):
+ """Is the given identifier defined in one of the namespaces which shadow
+ the alias and magic namespaces? Note that an identifier is different
+ than ifun, because it can not contain a '.' character."""
+ # This is much safer than calling ofind, which can change state
+ return (identifier in ip.user_ns \
+ or identifier in ip.user_global_ns \
+ or identifier in ip.ns_table['builtin']\
+ or iskeyword(identifier))
+
+
+#-----------------------------------------------------------------------------
+# Main Prefilter manager
+#-----------------------------------------------------------------------------
+
+
+class PrefilterManager(Configurable):
+ """Main prefilter component.
+
+ The IPython prefilter is run on all user input before it is run. The
+ prefilter consumes lines of input and produces transformed lines of
+ input.
+
+ The iplementation consists of two phases:
+
+ 1. Transformers
+ 2. Checkers and handlers
+
+ Over time, we plan on deprecating the checkers and handlers and doing
+ everything in the transformers.
+
+ The transformers are instances of :class:`PrefilterTransformer` and have
+ a single method :meth:`transform` that takes a line and returns a
+ transformed line. The transformation can be accomplished using any
+ tool, but our current ones use regular expressions for speed.
+
+ After all the transformers have been run, the line is fed to the checkers,
+ which are instances of :class:`PrefilterChecker`. The line is passed to
+ the :meth:`check` method, which either returns `None` or a
+ :class:`PrefilterHandler` instance. If `None` is returned, the other
+ checkers are tried. If an :class:`PrefilterHandler` instance is returned,
+ the line is passed to the :meth:`handle` method of the returned
+ handler and no further checkers are tried.
+
+ Both transformers and checkers have a `priority` attribute, that determines
+ the order in which they are called. Smaller priorities are tried first.
+
+ Both transformers and checkers also have `enabled` attribute, which is
+ a boolean that determines if the instance is used.
+
+ Users or developers can change the priority or enabled attribute of
+ transformers or checkers, but they must call the :meth:`sort_checkers`
+ or :meth:`sort_transformers` method after changing the priority.
+ """
+
multi_line_specials = Bool(True).tag(config=True)
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
-
- def __init__(self, shell=None, **kwargs):
- super(PrefilterManager, self).__init__(shell=shell, **kwargs)
- self.shell = shell
- self.init_transformers()
- self.init_handlers()
- self.init_checkers()
-
- #-------------------------------------------------------------------------
- # API for managing transformers
- #-------------------------------------------------------------------------
-
- def init_transformers(self):
- """Create the default transformers."""
- self._transformers = []
- for transformer_cls in _default_transformers:
- transformer_cls(
- shell=self.shell, prefilter_manager=self, parent=self
- )
-
- def sort_transformers(self):
- """Sort the transformers by priority.
-
- This must be called after the priority of a transformer is changed.
- The :meth:`register_transformer` method calls this automatically.
- """
- self._transformers.sort(key=lambda x: x.priority)
-
- @property
- def transformers(self):
- """Return a list of checkers, sorted by priority."""
- return self._transformers
-
- def register_transformer(self, transformer):
- """Register a transformer instance."""
- if transformer not in self._transformers:
- self._transformers.append(transformer)
- self.sort_transformers()
-
- def unregister_transformer(self, transformer):
- """Unregister a transformer instance."""
- if transformer in self._transformers:
- self._transformers.remove(transformer)
-
- #-------------------------------------------------------------------------
- # API for managing checkers
- #-------------------------------------------------------------------------
-
- def init_checkers(self):
- """Create the default checkers."""
- self._checkers = []
- for checker in _default_checkers:
- checker(
- shell=self.shell, prefilter_manager=self, parent=self
- )
-
- def sort_checkers(self):
- """Sort the checkers by priority.
-
- This must be called after the priority of a checker is changed.
- The :meth:`register_checker` method calls this automatically.
- """
- self._checkers.sort(key=lambda x: x.priority)
-
- @property
- def checkers(self):
- """Return a list of checkers, sorted by priority."""
- return self._checkers
-
- def register_checker(self, checker):
- """Register a checker instance."""
- if checker not in self._checkers:
- self._checkers.append(checker)
- self.sort_checkers()
-
- def unregister_checker(self, checker):
- """Unregister a checker instance."""
- if checker in self._checkers:
- self._checkers.remove(checker)
-
- #-------------------------------------------------------------------------
- # API for managing handlers
- #-------------------------------------------------------------------------
-
- def init_handlers(self):
- """Create the default handlers."""
- self._handlers = {}
- self._esc_handlers = {}
- for handler in _default_handlers:
- handler(
- shell=self.shell, prefilter_manager=self, parent=self
- )
-
- @property
- def handlers(self):
- """Return a dict of all the handlers."""
- return self._handlers
-
- def register_handler(self, name, handler, esc_strings):
- """Register a handler instance by name with esc_strings."""
- self._handlers[name] = handler
- for esc_str in esc_strings:
- self._esc_handlers[esc_str] = handler
-
- def unregister_handler(self, name, handler, esc_strings):
- """Unregister a handler instance by name with esc_strings."""
- try:
- del self._handlers[name]
- except KeyError:
- pass
- for esc_str in esc_strings:
- h = self._esc_handlers.get(esc_str)
- if h is handler:
- del self._esc_handlers[esc_str]
-
- def get_handler_by_name(self, name):
- """Get a handler by its name."""
- return self._handlers.get(name)
-
- def get_handler_by_esc(self, esc_str):
- """Get a handler by its escape string."""
- return self._esc_handlers.get(esc_str)
-
- #-------------------------------------------------------------------------
- # Main prefiltering API
- #-------------------------------------------------------------------------
-
- def prefilter_line_info(self, line_info):
- """Prefilter a line that has been converted to a LineInfo object.
-
- This implements the checker/handler part of the prefilter pipe.
- """
- # print "prefilter_line_info: ", line_info
- handler = self.find_handler(line_info)
- return handler.handle(line_info)
-
- def find_handler(self, line_info):
- """Find a handler for the line_info by trying checkers."""
- for checker in self.checkers:
- if checker.enabled:
- handler = checker.check(line_info)
- if handler:
- return handler
- return self.get_handler_by_name('normal')
-
- def transform_line(self, line, continue_prompt):
- """Calls the enabled transformers in order of increasing priority."""
- for transformer in self.transformers:
- if transformer.enabled:
- line = transformer.transform(line, continue_prompt)
- return line
-
- def prefilter_line(self, line, continue_prompt=False):
- """Prefilter a single input line as text.
-
- This method prefilters a single line of text by calling the
- transformers and then the checkers/handlers.
- """
-
- # print "prefilter_line: ", line, continue_prompt
- # All handlers *must* return a value, even if it's blank ('').
-
- # save the line away in case we crash, so the post-mortem handler can
- # record it
- self.shell._last_input_line = line
-
- if not line:
- # Return immediately on purely empty lines, so that if the user
- # previously typed some whitespace that started a continuation
- # prompt, he can break out of that loop with just an empty line.
- # This is how the default python prompt works.
- return ''
-
- # At this point, we invoke our transformers.
- if not continue_prompt or (continue_prompt and self.multi_line_specials):
- line = self.transform_line(line, continue_prompt)
-
- # Now we compute line_info for the checkers and handlers
- line_info = LineInfo(line, continue_prompt)
-
- # the input history needs to track even empty lines
- stripped = line.strip()
-
- normal_handler = self.get_handler_by_name('normal')
- if not stripped:
- return normal_handler.handle(line_info)
-
- # special handlers are only allowed for single line statements
- if continue_prompt and not self.multi_line_specials:
- return normal_handler.handle(line_info)
-
- prefiltered = self.prefilter_line_info(line_info)
- # print "prefiltered line: %r" % prefiltered
- return prefiltered
-
- def prefilter_lines(self, lines, continue_prompt=False):
- """Prefilter multiple input lines of text.
-
- This is the main entry point for prefiltering multiple lines of
- input. This simply calls :meth:`prefilter_line` for each line of
- input.
-
- This covers cases where there are multiple lines in the user entry,
- which is the case when the user goes back to a multiline history
- entry and presses enter.
- """
- llines = lines.rstrip('\n').split('\n')
- # We can get multiple lines in one shot, where multiline input 'blends'
- # into one line, in cases like recalling from the readline history
- # buffer. We need to make sure that in such cases, we correctly
- # communicate downstream which line is first and which are continuation
- # ones.
- if len(llines) > 1:
- out = '\n'.join([self.prefilter_line(line, lnum>0)
- for lnum, line in enumerate(llines) ])
- else:
- out = self.prefilter_line(llines[0], continue_prompt)
-
- return out
-
-#-----------------------------------------------------------------------------
-# Prefilter transformers
-#-----------------------------------------------------------------------------
-
-
-class PrefilterTransformer(Configurable):
- """Transform a line of user input."""
-
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
+
+ def __init__(self, shell=None, **kwargs):
+ super(PrefilterManager, self).__init__(shell=shell, **kwargs)
+ self.shell = shell
+ self.init_transformers()
+ self.init_handlers()
+ self.init_checkers()
+
+ #-------------------------------------------------------------------------
+ # API for managing transformers
+ #-------------------------------------------------------------------------
+
+ def init_transformers(self):
+ """Create the default transformers."""
+ self._transformers = []
+ for transformer_cls in _default_transformers:
+ transformer_cls(
+ shell=self.shell, prefilter_manager=self, parent=self
+ )
+
+ def sort_transformers(self):
+ """Sort the transformers by priority.
+
+ This must be called after the priority of a transformer is changed.
+ The :meth:`register_transformer` method calls this automatically.
+ """
+ self._transformers.sort(key=lambda x: x.priority)
+
+ @property
+ def transformers(self):
+ """Return a list of checkers, sorted by priority."""
+ return self._transformers
+
+ def register_transformer(self, transformer):
+ """Register a transformer instance."""
+ if transformer not in self._transformers:
+ self._transformers.append(transformer)
+ self.sort_transformers()
+
+ def unregister_transformer(self, transformer):
+ """Unregister a transformer instance."""
+ if transformer in self._transformers:
+ self._transformers.remove(transformer)
+
+ #-------------------------------------------------------------------------
+ # API for managing checkers
+ #-------------------------------------------------------------------------
+
+ def init_checkers(self):
+ """Create the default checkers."""
+ self._checkers = []
+ for checker in _default_checkers:
+ checker(
+ shell=self.shell, prefilter_manager=self, parent=self
+ )
+
+ def sort_checkers(self):
+ """Sort the checkers by priority.
+
+ This must be called after the priority of a checker is changed.
+ The :meth:`register_checker` method calls this automatically.
+ """
+ self._checkers.sort(key=lambda x: x.priority)
+
+ @property
+ def checkers(self):
+ """Return a list of checkers, sorted by priority."""
+ return self._checkers
+
+ def register_checker(self, checker):
+ """Register a checker instance."""
+ if checker not in self._checkers:
+ self._checkers.append(checker)
+ self.sort_checkers()
+
+ def unregister_checker(self, checker):
+ """Unregister a checker instance."""
+ if checker in self._checkers:
+ self._checkers.remove(checker)
+
+ #-------------------------------------------------------------------------
+ # API for managing handlers
+ #-------------------------------------------------------------------------
+
+ def init_handlers(self):
+ """Create the default handlers."""
+ self._handlers = {}
+ self._esc_handlers = {}
+ for handler in _default_handlers:
+ handler(
+ shell=self.shell, prefilter_manager=self, parent=self
+ )
+
+ @property
+ def handlers(self):
+ """Return a dict of all the handlers."""
+ return self._handlers
+
+ def register_handler(self, name, handler, esc_strings):
+ """Register a handler instance by name with esc_strings."""
+ self._handlers[name] = handler
+ for esc_str in esc_strings:
+ self._esc_handlers[esc_str] = handler
+
+ def unregister_handler(self, name, handler, esc_strings):
+ """Unregister a handler instance by name with esc_strings."""
+ try:
+ del self._handlers[name]
+ except KeyError:
+ pass
+ for esc_str in esc_strings:
+ h = self._esc_handlers.get(esc_str)
+ if h is handler:
+ del self._esc_handlers[esc_str]
+
+ def get_handler_by_name(self, name):
+ """Get a handler by its name."""
+ return self._handlers.get(name)
+
+ def get_handler_by_esc(self, esc_str):
+ """Get a handler by its escape string."""
+ return self._esc_handlers.get(esc_str)
+
+ #-------------------------------------------------------------------------
+ # Main prefiltering API
+ #-------------------------------------------------------------------------
+
+ def prefilter_line_info(self, line_info):
+ """Prefilter a line that has been converted to a LineInfo object.
+
+ This implements the checker/handler part of the prefilter pipe.
+ """
+ # print "prefilter_line_info: ", line_info
+ handler = self.find_handler(line_info)
+ return handler.handle(line_info)
+
+ def find_handler(self, line_info):
+ """Find a handler for the line_info by trying checkers."""
+ for checker in self.checkers:
+ if checker.enabled:
+ handler = checker.check(line_info)
+ if handler:
+ return handler
+ return self.get_handler_by_name('normal')
+
+ def transform_line(self, line, continue_prompt):
+ """Calls the enabled transformers in order of increasing priority."""
+ for transformer in self.transformers:
+ if transformer.enabled:
+ line = transformer.transform(line, continue_prompt)
+ return line
+
+ def prefilter_line(self, line, continue_prompt=False):
+ """Prefilter a single input line as text.
+
+ This method prefilters a single line of text by calling the
+ transformers and then the checkers/handlers.
+ """
+
+ # print "prefilter_line: ", line, continue_prompt
+ # All handlers *must* return a value, even if it's blank ('').
+
+ # save the line away in case we crash, so the post-mortem handler can
+ # record it
+ self.shell._last_input_line = line
+
+ if not line:
+ # Return immediately on purely empty lines, so that if the user
+ # previously typed some whitespace that started a continuation
+ # prompt, he can break out of that loop with just an empty line.
+ # This is how the default python prompt works.
+ return ''
+
+ # At this point, we invoke our transformers.
+ if not continue_prompt or (continue_prompt and self.multi_line_specials):
+ line = self.transform_line(line, continue_prompt)
+
+ # Now we compute line_info for the checkers and handlers
+ line_info = LineInfo(line, continue_prompt)
+
+ # the input history needs to track even empty lines
+ stripped = line.strip()
+
+ normal_handler = self.get_handler_by_name('normal')
+ if not stripped:
+ return normal_handler.handle(line_info)
+
+ # special handlers are only allowed for single line statements
+ if continue_prompt and not self.multi_line_specials:
+ return normal_handler.handle(line_info)
+
+ prefiltered = self.prefilter_line_info(line_info)
+ # print "prefiltered line: %r" % prefiltered
+ return prefiltered
+
+ def prefilter_lines(self, lines, continue_prompt=False):
+ """Prefilter multiple input lines of text.
+
+ This is the main entry point for prefiltering multiple lines of
+ input. This simply calls :meth:`prefilter_line` for each line of
+ input.
+
+ This covers cases where there are multiple lines in the user entry,
+ which is the case when the user goes back to a multiline history
+ entry and presses enter.
+ """
+ llines = lines.rstrip('\n').split('\n')
+ # We can get multiple lines in one shot, where multiline input 'blends'
+ # into one line, in cases like recalling from the readline history
+ # buffer. We need to make sure that in such cases, we correctly
+ # communicate downstream which line is first and which are continuation
+ # ones.
+ if len(llines) > 1:
+ out = '\n'.join([self.prefilter_line(line, lnum>0)
+ for lnum, line in enumerate(llines) ])
+ else:
+ out = self.prefilter_line(llines[0], continue_prompt)
+
+ return out
+
+#-----------------------------------------------------------------------------
+# Prefilter transformers
+#-----------------------------------------------------------------------------
+
+
+class PrefilterTransformer(Configurable):
+ """Transform a line of user input."""
+
priority = Integer(100).tag(config=True)
- # Transformers don't currently use shell or prefilter_manager, but as we
- # move away from checkers and handlers, they will need them.
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
- prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
+ # Transformers don't currently use shell or prefilter_manager, but as we
+ # move away from checkers and handlers, they will need them.
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
+ prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
enabled = Bool(True).tag(config=True)
-
- def __init__(self, shell=None, prefilter_manager=None, **kwargs):
- super(PrefilterTransformer, self).__init__(
- shell=shell, prefilter_manager=prefilter_manager, **kwargs
- )
- self.prefilter_manager.register_transformer(self)
-
- def transform(self, line, continue_prompt):
- """Transform a line, returning the new one."""
- return None
-
- def __repr__(self):
- return "<%s(priority=%r, enabled=%r)>" % (
- self.__class__.__name__, self.priority, self.enabled)
-
-
-#-----------------------------------------------------------------------------
-# Prefilter checkers
-#-----------------------------------------------------------------------------
-
-
-class PrefilterChecker(Configurable):
- """Inspect an input line and return a handler for that line."""
-
+
+ def __init__(self, shell=None, prefilter_manager=None, **kwargs):
+ super(PrefilterTransformer, self).__init__(
+ shell=shell, prefilter_manager=prefilter_manager, **kwargs
+ )
+ self.prefilter_manager.register_transformer(self)
+
+ def transform(self, line, continue_prompt):
+ """Transform a line, returning the new one."""
+ return None
+
+ def __repr__(self):
+ return "<%s(priority=%r, enabled=%r)>" % (
+ self.__class__.__name__, self.priority, self.enabled)
+
+
+#-----------------------------------------------------------------------------
+# Prefilter checkers
+#-----------------------------------------------------------------------------
+
+
+class PrefilterChecker(Configurable):
+ """Inspect an input line and return a handler for that line."""
+
priority = Integer(100).tag(config=True)
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
- prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
+ prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
enabled = Bool(True).tag(config=True)
-
- def __init__(self, shell=None, prefilter_manager=None, **kwargs):
- super(PrefilterChecker, self).__init__(
- shell=shell, prefilter_manager=prefilter_manager, **kwargs
- )
- self.prefilter_manager.register_checker(self)
-
- def check(self, line_info):
- """Inspect line_info and return a handler instance or None."""
- return None
-
- def __repr__(self):
- return "<%s(priority=%r, enabled=%r)>" % (
- self.__class__.__name__, self.priority, self.enabled)
-
-
-class EmacsChecker(PrefilterChecker):
-
+
+ def __init__(self, shell=None, prefilter_manager=None, **kwargs):
+ super(PrefilterChecker, self).__init__(
+ shell=shell, prefilter_manager=prefilter_manager, **kwargs
+ )
+ self.prefilter_manager.register_checker(self)
+
+ def check(self, line_info):
+ """Inspect line_info and return a handler instance or None."""
+ return None
+
+ def __repr__(self):
+ return "<%s(priority=%r, enabled=%r)>" % (
+ self.__class__.__name__, self.priority, self.enabled)
+
+
+class EmacsChecker(PrefilterChecker):
+
priority = Integer(100).tag(config=True)
enabled = Bool(False).tag(config=True)
-
- def check(self, line_info):
- "Emacs ipython-mode tags certain input lines."
- if line_info.line.endswith('# PYTHON-MODE'):
- return self.prefilter_manager.get_handler_by_name('emacs')
- else:
- return None
-
-
-class MacroChecker(PrefilterChecker):
-
+
+ def check(self, line_info):
+ "Emacs ipython-mode tags certain input lines."
+ if line_info.line.endswith('# PYTHON-MODE'):
+ return self.prefilter_manager.get_handler_by_name('emacs')
+ else:
+ return None
+
+
+class MacroChecker(PrefilterChecker):
+
priority = Integer(250).tag(config=True)
-
- def check(self, line_info):
- obj = self.shell.user_ns.get(line_info.ifun)
- if isinstance(obj, Macro):
- return self.prefilter_manager.get_handler_by_name('macro')
- else:
- return None
-
-
-class IPyAutocallChecker(PrefilterChecker):
-
+
+ def check(self, line_info):
+ obj = self.shell.user_ns.get(line_info.ifun)
+ if isinstance(obj, Macro):
+ return self.prefilter_manager.get_handler_by_name('macro')
+ else:
+ return None
+
+
+class IPyAutocallChecker(PrefilterChecker):
+
priority = Integer(300).tag(config=True)
-
- def check(self, line_info):
- "Instances of IPyAutocall in user_ns get autocalled immediately"
- obj = self.shell.user_ns.get(line_info.ifun, None)
- if isinstance(obj, IPyAutocall):
- obj.set_ip(self.shell)
- return self.prefilter_manager.get_handler_by_name('auto')
- else:
- return None
-
-
-class AssignmentChecker(PrefilterChecker):
-
+
+ def check(self, line_info):
+ "Instances of IPyAutocall in user_ns get autocalled immediately"
+ obj = self.shell.user_ns.get(line_info.ifun, None)
+ if isinstance(obj, IPyAutocall):
+ obj.set_ip(self.shell)
+ return self.prefilter_manager.get_handler_by_name('auto')
+ else:
+ return None
+
+
+class AssignmentChecker(PrefilterChecker):
+
priority = Integer(600).tag(config=True)
-
- def check(self, line_info):
- """Check to see if user is assigning to a var for the first time, in
- which case we want to avoid any sort of automagic / autocall games.
-
- This allows users to assign to either alias or magic names true python
- variables (the magic/alias systems always take second seat to true
- python code). E.g. ls='hi', or ls,that=1,2"""
- if line_info.the_rest:
- if line_info.the_rest[0] in '=,':
- return self.prefilter_manager.get_handler_by_name('normal')
- else:
- return None
-
-
-class AutoMagicChecker(PrefilterChecker):
-
+
+ def check(self, line_info):
+ """Check to see if user is assigning to a var for the first time, in
+ which case we want to avoid any sort of automagic / autocall games.
+
+ This allows users to assign to either alias or magic names true python
+ variables (the magic/alias systems always take second seat to true
+ python code). E.g. ls='hi', or ls,that=1,2"""
+ if line_info.the_rest:
+ if line_info.the_rest[0] in '=,':
+ return self.prefilter_manager.get_handler_by_name('normal')
+ else:
+ return None
+
+
+class AutoMagicChecker(PrefilterChecker):
+
priority = Integer(700).tag(config=True)
-
- def check(self, line_info):
- """If the ifun is magic, and automagic is on, run it. Note: normal,
- non-auto magic would already have been triggered via '%' in
- check_esc_chars. This just checks for automagic. Also, before
- triggering the magic handler, make sure that there is nothing in the
- user namespace which could shadow it."""
- if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
- return None
-
- # We have a likely magic method. Make sure we should actually call it.
- if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
- return None
-
- head = line_info.ifun.split('.',1)[0]
- if is_shadowed(head, self.shell):
- return None
-
- return self.prefilter_manager.get_handler_by_name('magic')
-
-
-class PythonOpsChecker(PrefilterChecker):
-
+
+ def check(self, line_info):
+ """If the ifun is magic, and automagic is on, run it. Note: normal,
+ non-auto magic would already have been triggered via '%' in
+ check_esc_chars. This just checks for automagic. Also, before
+ triggering the magic handler, make sure that there is nothing in the
+ user namespace which could shadow it."""
+ if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
+ return None
+
+ # We have a likely magic method. Make sure we should actually call it.
+ if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
+ return None
+
+ head = line_info.ifun.split('.',1)[0]
+ if is_shadowed(head, self.shell):
+ return None
+
+ return self.prefilter_manager.get_handler_by_name('magic')
+
+
+class PythonOpsChecker(PrefilterChecker):
+
priority = Integer(900).tag(config=True)
-
- def check(self, line_info):
- """If the 'rest' of the line begins with a function call or pretty much
- any python operator, we should simply execute the line (regardless of
- whether or not there's a possible autocall expansion). This avoids
- spurious (and very confusing) geattr() accesses."""
- if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
- return self.prefilter_manager.get_handler_by_name('normal')
- else:
- return None
-
-
-class AutocallChecker(PrefilterChecker):
-
+
+ def check(self, line_info):
+ """If the 'rest' of the line begins with a function call or pretty much
+ any python operator, we should simply execute the line (regardless of
+ whether or not there's a possible autocall expansion). This avoids
+ spurious (and very confusing) geattr() accesses."""
+ if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
+ return self.prefilter_manager.get_handler_by_name('normal')
+ else:
+ return None
+
+
+class AutocallChecker(PrefilterChecker):
+
priority = Integer(1000).tag(config=True)
-
+
function_name_regexp = CRegExp(re_fun_name,
help="RegExp to identify potential function names."
).tag(config=True)
exclude_regexp = CRegExp(re_exclude_auto,
help="RegExp to exclude strings with this start from autocalling."
).tag(config=True)
-
- def check(self, line_info):
- "Check if the initial word/function is callable and autocall is on."
- if not self.shell.autocall:
- return None
-
- oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
- if not oinfo['found']:
- return None
-
- if callable(oinfo['obj']) \
- and (not self.exclude_regexp.match(line_info.the_rest)) \
- and self.function_name_regexp.match(line_info.ifun):
- return self.prefilter_manager.get_handler_by_name('auto')
- else:
- return None
-
-
-#-----------------------------------------------------------------------------
-# Prefilter handlers
-#-----------------------------------------------------------------------------
-
-
-class PrefilterHandler(Configurable):
-
- handler_name = Unicode('normal')
- esc_strings = List([])
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
- prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
-
- def __init__(self, shell=None, prefilter_manager=None, **kwargs):
- super(PrefilterHandler, self).__init__(
- shell=shell, prefilter_manager=prefilter_manager, **kwargs
- )
- self.prefilter_manager.register_handler(
- self.handler_name,
- self,
- self.esc_strings
- )
-
- def handle(self, line_info):
- # print "normal: ", line_info
- """Handle normal input lines. Use as a template for handlers."""
-
- # With autoindent on, we need some way to exit the input loop, and I
- # don't want to force the user to have to backspace all the way to
- # clear the line. The rule will be in this case, that either two
- # lines of pure whitespace in a row, or a line of pure whitespace but
- # of a size different to the indent level, will exit the input loop.
- line = line_info.line
- continue_prompt = line_info.continue_prompt
-
- if (continue_prompt and
- self.shell.autoindent and
- line.isspace() and
- 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
- line = ''
-
- return line
-
- def __str__(self):
- return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
-
-
-class MacroHandler(PrefilterHandler):
- handler_name = Unicode("macro")
-
- def handle(self, line_info):
- obj = self.shell.user_ns.get(line_info.ifun)
- pre_space = line_info.pre_whitespace
- line_sep = "\n" + pre_space
- return pre_space + line_sep.join(obj.value.splitlines())
-
-
-class MagicHandler(PrefilterHandler):
-
- handler_name = Unicode('magic')
- esc_strings = List([ESC_MAGIC])
-
- def handle(self, line_info):
- """Execute magic functions."""
- ifun = line_info.ifun
- the_rest = line_info.the_rest
- cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace,
- (ifun + " " + the_rest))
- return cmd
-
-
-class AutoHandler(PrefilterHandler):
-
- handler_name = Unicode('auto')
- esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
-
- def handle(self, line_info):
- """Handle lines which can be auto-executed, quoting if requested."""
- line = line_info.line
- ifun = line_info.ifun
- the_rest = line_info.the_rest
- esc = line_info.esc
- continue_prompt = line_info.continue_prompt
- obj = line_info.ofind(self.shell)['obj']
-
- # This should only be active for single-line input!
- if continue_prompt:
- return line
-
- force_auto = isinstance(obj, IPyAutocall)
-
- # User objects sometimes raise exceptions on attribute access other
- # than AttributeError (we've seen it in the past), so it's safest to be
- # ultra-conservative here and catch all.
- try:
- auto_rewrite = obj.rewrite
- except Exception:
- auto_rewrite = True
-
- if esc == ESC_QUOTE:
- # Auto-quote splitting on whitespace
- newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
- elif esc == ESC_QUOTE2:
- # Auto-quote whole string
- newcmd = '%s("%s")' % (ifun,the_rest)
- elif esc == ESC_PAREN:
- newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
- else:
- # Auto-paren.
- if force_auto:
- # Don't rewrite if it is already a call.
- do_rewrite = not the_rest.startswith('(')
- else:
- if not the_rest:
- # We only apply it to argument-less calls if the autocall
- # parameter is set to 2.
- do_rewrite = (self.shell.autocall >= 2)
- elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
- # Don't autocall in this case: item access for an object
- # which is BOTH callable and implements __getitem__.
- do_rewrite = False
- else:
- do_rewrite = True
-
- # Figure out the rewritten command
- if do_rewrite:
- if the_rest.endswith(';'):
- newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
- else:
- newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
- else:
- normal_handler = self.prefilter_manager.get_handler_by_name('normal')
- return normal_handler.handle(line_info)
-
- # Display the rewritten call
- if auto_rewrite:
- self.shell.auto_rewrite_input(newcmd)
-
- return newcmd
-
-
-class EmacsHandler(PrefilterHandler):
-
- handler_name = Unicode('emacs')
- esc_strings = List([])
-
- def handle(self, line_info):
- """Handle input lines marked by python-mode."""
-
- # Currently, nothing is done. Later more functionality can be added
- # here if needed.
-
- # The input cache shouldn't be updated
- return line_info.line
-
-
-#-----------------------------------------------------------------------------
-# Defaults
-#-----------------------------------------------------------------------------
-
-
-_default_transformers = [
-]
-
-_default_checkers = [
- EmacsChecker,
- MacroChecker,
- IPyAutocallChecker,
- AssignmentChecker,
- AutoMagicChecker,
- PythonOpsChecker,
- AutocallChecker
-]
-
-_default_handlers = [
- PrefilterHandler,
- MacroHandler,
- MagicHandler,
- AutoHandler,
- EmacsHandler
-]
+
+ def check(self, line_info):
+ "Check if the initial word/function is callable and autocall is on."
+ if not self.shell.autocall:
+ return None
+
+ oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
+ if not oinfo['found']:
+ return None
+
+ if callable(oinfo['obj']) \
+ and (not self.exclude_regexp.match(line_info.the_rest)) \
+ and self.function_name_regexp.match(line_info.ifun):
+ return self.prefilter_manager.get_handler_by_name('auto')
+ else:
+ return None
+
+
+#-----------------------------------------------------------------------------
+# Prefilter handlers
+#-----------------------------------------------------------------------------
+
+
+class PrefilterHandler(Configurable):
+
+ handler_name = Unicode('normal')
+ esc_strings = List([])
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
+ prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
+
+ def __init__(self, shell=None, prefilter_manager=None, **kwargs):
+ super(PrefilterHandler, self).__init__(
+ shell=shell, prefilter_manager=prefilter_manager, **kwargs
+ )
+ self.prefilter_manager.register_handler(
+ self.handler_name,
+ self,
+ self.esc_strings
+ )
+
+ def handle(self, line_info):
+ # print "normal: ", line_info
+ """Handle normal input lines. Use as a template for handlers."""
+
+ # With autoindent on, we need some way to exit the input loop, and I
+ # don't want to force the user to have to backspace all the way to
+ # clear the line. The rule will be in this case, that either two
+ # lines of pure whitespace in a row, or a line of pure whitespace but
+ # of a size different to the indent level, will exit the input loop.
+ line = line_info.line
+ continue_prompt = line_info.continue_prompt
+
+ if (continue_prompt and
+ self.shell.autoindent and
+ line.isspace() and
+ 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
+ line = ''
+
+ return line
+
+ def __str__(self):
+ return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
+
+
+class MacroHandler(PrefilterHandler):
+ handler_name = Unicode("macro")
+
+ def handle(self, line_info):
+ obj = self.shell.user_ns.get(line_info.ifun)
+ pre_space = line_info.pre_whitespace
+ line_sep = "\n" + pre_space
+ return pre_space + line_sep.join(obj.value.splitlines())
+
+
+class MagicHandler(PrefilterHandler):
+
+ handler_name = Unicode('magic')
+ esc_strings = List([ESC_MAGIC])
+
+ def handle(self, line_info):
+ """Execute magic functions."""
+ ifun = line_info.ifun
+ the_rest = line_info.the_rest
+ cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace,
+ (ifun + " " + the_rest))
+ return cmd
+
+
+class AutoHandler(PrefilterHandler):
+
+ handler_name = Unicode('auto')
+ esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
+
+ def handle(self, line_info):
+ """Handle lines which can be auto-executed, quoting if requested."""
+ line = line_info.line
+ ifun = line_info.ifun
+ the_rest = line_info.the_rest
+ esc = line_info.esc
+ continue_prompt = line_info.continue_prompt
+ obj = line_info.ofind(self.shell)['obj']
+
+ # This should only be active for single-line input!
+ if continue_prompt:
+ return line
+
+ force_auto = isinstance(obj, IPyAutocall)
+
+ # User objects sometimes raise exceptions on attribute access other
+ # than AttributeError (we've seen it in the past), so it's safest to be
+ # ultra-conservative here and catch all.
+ try:
+ auto_rewrite = obj.rewrite
+ except Exception:
+ auto_rewrite = True
+
+ if esc == ESC_QUOTE:
+ # Auto-quote splitting on whitespace
+ newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
+ elif esc == ESC_QUOTE2:
+ # Auto-quote whole string
+ newcmd = '%s("%s")' % (ifun,the_rest)
+ elif esc == ESC_PAREN:
+ newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
+ else:
+ # Auto-paren.
+ if force_auto:
+ # Don't rewrite if it is already a call.
+ do_rewrite = not the_rest.startswith('(')
+ else:
+ if not the_rest:
+ # We only apply it to argument-less calls if the autocall
+ # parameter is set to 2.
+ do_rewrite = (self.shell.autocall >= 2)
+ elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
+ # Don't autocall in this case: item access for an object
+ # which is BOTH callable and implements __getitem__.
+ do_rewrite = False
+ else:
+ do_rewrite = True
+
+ # Figure out the rewritten command
+ if do_rewrite:
+ if the_rest.endswith(';'):
+ newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
+ else:
+ newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
+ else:
+ normal_handler = self.prefilter_manager.get_handler_by_name('normal')
+ return normal_handler.handle(line_info)
+
+ # Display the rewritten call
+ if auto_rewrite:
+ self.shell.auto_rewrite_input(newcmd)
+
+ return newcmd
+
+
+class EmacsHandler(PrefilterHandler):
+
+ handler_name = Unicode('emacs')
+ esc_strings = List([])
+
+ def handle(self, line_info):
+ """Handle input lines marked by python-mode."""
+
+ # Currently, nothing is done. Later more functionality can be added
+ # here if needed.
+
+ # The input cache shouldn't be updated
+ return line_info.line
+
+
+#-----------------------------------------------------------------------------
+# Defaults
+#-----------------------------------------------------------------------------
+
+
+_default_transformers = [
+]
+
+_default_checkers = [
+ EmacsChecker,
+ MacroChecker,
+ IPyAutocallChecker,
+ AssignmentChecker,
+ AutoMagicChecker,
+ PythonOpsChecker,
+ AutocallChecker
+]
+
+_default_handlers = [
+ PrefilterHandler,
+ MacroHandler,
+ MagicHandler,
+ AutoHandler,
+ EmacsHandler
+]
diff --git a/contrib/python/ipython/py2/IPython/core/profile/README_STARTUP b/contrib/python/ipython/py2/IPython/core/profile/README_STARTUP
index 051134cfc3..61d4700042 100644
--- a/contrib/python/ipython/py2/IPython/core/profile/README_STARTUP
+++ b/contrib/python/ipython/py2/IPython/core/profile/README_STARTUP
@@ -1,11 +1,11 @@
-This is the IPython startup directory
-
-.py and .ipy files in this directory will be run *prior* to any code or files specified
-via the exec_lines or exec_files configurables whenever you load this profile.
-
-Files will be run in lexicographical order, so you can control the execution order of files
-with a prefix, e.g.::
-
- 00-first.py
- 50-middle.py
- 99-last.ipy
+This is the IPython startup directory
+
+.py and .ipy files in this directory will be run *prior* to any code or files specified
+via the exec_lines or exec_files configurables whenever you load this profile.
+
+Files will be run in lexicographical order, so you can control the execution order of files
+with a prefix, e.g.::
+
+ 00-first.py
+ 50-middle.py
+ 99-last.ipy
diff --git a/contrib/python/ipython/py2/IPython/core/profileapp.py b/contrib/python/ipython/py2/IPython/core/profileapp.py
index 54e4f3b94c..b8e5fd26ac 100644
--- a/contrib/python/ipython/py2/IPython/core/profileapp.py
+++ b/contrib/python/ipython/py2/IPython/core/profileapp.py
@@ -1,314 +1,314 @@
-# encoding: utf-8
-"""
-An application for managing IPython profiles.
-
-To be invoked as the `ipython profile` subcommand.
-
-Authors:
-
-* Min RK
-
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import os
-
-from traitlets.config.application import Application
-from IPython.core.application import (
- BaseIPythonApplication, base_flags
-)
-from IPython.core.profiledir import ProfileDir
-from IPython.utils.importstring import import_item
-from IPython.paths import get_ipython_dir, get_ipython_package_dir
-from IPython.utils import py3compat
+# encoding: utf-8
+"""
+An application for managing IPython profiles.
+
+To be invoked as the `ipython profile` subcommand.
+
+Authors:
+
+* Min RK
+
+"""
+from __future__ import print_function
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import os
+
+from traitlets.config.application import Application
+from IPython.core.application import (
+ BaseIPythonApplication, base_flags
+)
+from IPython.core.profiledir import ProfileDir
+from IPython.utils.importstring import import_item
+from IPython.paths import get_ipython_dir, get_ipython_package_dir
+from IPython.utils import py3compat
from traitlets import Unicode, Bool, Dict, observe
-
-#-----------------------------------------------------------------------------
-# Constants
-#-----------------------------------------------------------------------------
-
-create_help = """Create an IPython profile by name
-
-Create an ipython profile directory by its name or
-profile directory path. Profile directories contain
-configuration, log and security related files and are named
-using the convention 'profile_<name>'. By default they are
-located in your ipython directory. Once created, you will
-can edit the configuration files in the profile
-directory to configure IPython. Most users will create a
-profile directory by name,
-`ipython profile create myprofile`, which will put the directory
-in `<ipython_dir>/profile_myprofile`.
-"""
-list_help = """List available IPython profiles
-
-List all available profiles, by profile location, that can
-be found in the current working directly or in the ipython
-directory. Profile directories are named using the convention
-'profile_<profile>'.
-"""
-profile_help = """Manage IPython profiles
-
-Profile directories contain
-configuration, log and security related files and are named
-using the convention 'profile_<name>'. By default they are
-located in your ipython directory. You can create profiles
-with `ipython profile create <name>`, or see the profiles you
-already have with `ipython profile list`
-
-To get started configuring IPython, simply do:
-
-$> ipython profile create
-
-and IPython will create the default profile in <ipython_dir>/profile_default,
-where you can edit ipython_config.py to start configuring IPython.
-
-"""
-
-_list_examples = "ipython profile list # list all profiles"
-
-_create_examples = """
-ipython profile create foo # create profile foo w/ default config files
-ipython profile create foo --reset # restage default config files over current
-ipython profile create foo --parallel # also stage parallel config files
-"""
-
-_main_examples = """
-ipython profile create -h # show the help string for the create subcommand
-ipython profile list -h # show the help string for the list subcommand
-
-ipython locate profile foo # print the path to the directory for profile 'foo'
-"""
-
-#-----------------------------------------------------------------------------
-# Profile Application Class (for `ipython profile` subcommand)
-#-----------------------------------------------------------------------------
-
-
-def list_profiles_in(path):
- """list profiles in a given root directory"""
- files = os.listdir(path)
- profiles = []
- for f in files:
- try:
- full_path = os.path.join(path, f)
- except UnicodeError:
- continue
- if os.path.isdir(full_path) and f.startswith('profile_'):
- profiles.append(f.split('_',1)[-1])
- return profiles
-
-
-def list_bundled_profiles():
- """list profiles that are bundled with IPython."""
- path = os.path.join(get_ipython_package_dir(), u'core', u'profile')
- files = os.listdir(path)
- profiles = []
- for profile in files:
- full_path = os.path.join(path, profile)
- if os.path.isdir(full_path) and profile != "__pycache__":
- profiles.append(profile)
- return profiles
-
-
-class ProfileLocate(BaseIPythonApplication):
- description = """print the path to an IPython profile dir"""
-
- def parse_command_line(self, argv=None):
- super(ProfileLocate, self).parse_command_line(argv)
- if self.extra_args:
- self.profile = self.extra_args[0]
-
- def start(self):
- print(self.profile_dir.location)
-
-
-class ProfileList(Application):
- name = u'ipython-profile'
- description = list_help
- examples = _list_examples
-
- aliases = Dict({
- 'ipython-dir' : 'ProfileList.ipython_dir',
- 'log-level' : 'Application.log_level',
- })
- flags = Dict(dict(
- debug = ({'Application' : {'log_level' : 0}},
- "Set Application.log_level to 0, maximizing log output."
- )
- ))
-
+
+#-----------------------------------------------------------------------------
+# Constants
+#-----------------------------------------------------------------------------
+
+create_help = """Create an IPython profile by name
+
+Create an ipython profile directory by its name or
+profile directory path. Profile directories contain
+configuration, log and security related files and are named
+using the convention 'profile_<name>'. By default they are
+located in your ipython directory. Once created, you will
+can edit the configuration files in the profile
+directory to configure IPython. Most users will create a
+profile directory by name,
+`ipython profile create myprofile`, which will put the directory
+in `<ipython_dir>/profile_myprofile`.
+"""
+list_help = """List available IPython profiles
+
+List all available profiles, by profile location, that can
+be found in the current working directly or in the ipython
+directory. Profile directories are named using the convention
+'profile_<profile>'.
+"""
+profile_help = """Manage IPython profiles
+
+Profile directories contain
+configuration, log and security related files and are named
+using the convention 'profile_<name>'. By default they are
+located in your ipython directory. You can create profiles
+with `ipython profile create <name>`, or see the profiles you
+already have with `ipython profile list`
+
+To get started configuring IPython, simply do:
+
+$> ipython profile create
+
+and IPython will create the default profile in <ipython_dir>/profile_default,
+where you can edit ipython_config.py to start configuring IPython.
+
+"""
+
+_list_examples = "ipython profile list # list all profiles"
+
+_create_examples = """
+ipython profile create foo # create profile foo w/ default config files
+ipython profile create foo --reset # restage default config files over current
+ipython profile create foo --parallel # also stage parallel config files
+"""
+
+_main_examples = """
+ipython profile create -h # show the help string for the create subcommand
+ipython profile list -h # show the help string for the list subcommand
+
+ipython locate profile foo # print the path to the directory for profile 'foo'
+"""
+
+#-----------------------------------------------------------------------------
+# Profile Application Class (for `ipython profile` subcommand)
+#-----------------------------------------------------------------------------
+
+
+def list_profiles_in(path):
+ """list profiles in a given root directory"""
+ files = os.listdir(path)
+ profiles = []
+ for f in files:
+ try:
+ full_path = os.path.join(path, f)
+ except UnicodeError:
+ continue
+ if os.path.isdir(full_path) and f.startswith('profile_'):
+ profiles.append(f.split('_',1)[-1])
+ return profiles
+
+
+def list_bundled_profiles():
+ """list profiles that are bundled with IPython."""
+ path = os.path.join(get_ipython_package_dir(), u'core', u'profile')
+ files = os.listdir(path)
+ profiles = []
+ for profile in files:
+ full_path = os.path.join(path, profile)
+ if os.path.isdir(full_path) and profile != "__pycache__":
+ profiles.append(profile)
+ return profiles
+
+
+class ProfileLocate(BaseIPythonApplication):
+ description = """print the path to an IPython profile dir"""
+
+ def parse_command_line(self, argv=None):
+ super(ProfileLocate, self).parse_command_line(argv)
+ if self.extra_args:
+ self.profile = self.extra_args[0]
+
+ def start(self):
+ print(self.profile_dir.location)
+
+
+class ProfileList(Application):
+ name = u'ipython-profile'
+ description = list_help
+ examples = _list_examples
+
+ aliases = Dict({
+ 'ipython-dir' : 'ProfileList.ipython_dir',
+ 'log-level' : 'Application.log_level',
+ })
+ flags = Dict(dict(
+ debug = ({'Application' : {'log_level' : 0}},
+ "Set Application.log_level to 0, maximizing log output."
+ )
+ ))
+
ipython_dir = Unicode(get_ipython_dir(),
- help="""
- The name of the IPython directory. This directory is used for logging
- configuration (through profiles), history storage, etc. The default
- is usually $HOME/.ipython. This options can also be specified through
- the environment variable IPYTHONDIR.
- """
+ help="""
+ The name of the IPython directory. This directory is used for logging
+ configuration (through profiles), history storage, etc. The default
+ is usually $HOME/.ipython. This options can also be specified through
+ the environment variable IPYTHONDIR.
+ """
).tag(config=True)
-
-
- def _print_profiles(self, profiles):
- """print list of profiles, indented."""
- for profile in profiles:
- print(' %s' % profile)
-
- def list_profile_dirs(self):
- profiles = list_bundled_profiles()
- if profiles:
- print()
- print("Available profiles in IPython:")
- self._print_profiles(profiles)
- print()
- print(" The first request for a bundled profile will copy it")
- print(" into your IPython directory (%s)," % self.ipython_dir)
- print(" where you can customize it.")
-
- profiles = list_profiles_in(self.ipython_dir)
- if profiles:
- print()
- print("Available profiles in %s:" % self.ipython_dir)
- self._print_profiles(profiles)
-
- profiles = list_profiles_in(py3compat.getcwd())
- if profiles:
- print()
- print("Available profiles in current directory (%s):" % py3compat.getcwd())
- self._print_profiles(profiles)
-
- print()
- print("To use any of the above profiles, start IPython with:")
- print(" ipython --profile=<name>")
- print()
-
- def start(self):
- self.list_profile_dirs()
-
-
-create_flags = {}
-create_flags.update(base_flags)
-# don't include '--init' flag, which implies running profile create in other apps
-create_flags.pop('init')
-create_flags['reset'] = ({'ProfileCreate': {'overwrite' : True}},
- "reset config files in this profile to the defaults.")
-create_flags['parallel'] = ({'ProfileCreate': {'parallel' : True}},
- "Include the config files for parallel "
- "computing apps (ipengine, ipcontroller, etc.)")
-
-
-class ProfileCreate(BaseIPythonApplication):
- name = u'ipython-profile'
- description = create_help
- examples = _create_examples
+
+
+ def _print_profiles(self, profiles):
+ """print list of profiles, indented."""
+ for profile in profiles:
+ print(' %s' % profile)
+
+ def list_profile_dirs(self):
+ profiles = list_bundled_profiles()
+ if profiles:
+ print()
+ print("Available profiles in IPython:")
+ self._print_profiles(profiles)
+ print()
+ print(" The first request for a bundled profile will copy it")
+ print(" into your IPython directory (%s)," % self.ipython_dir)
+ print(" where you can customize it.")
+
+ profiles = list_profiles_in(self.ipython_dir)
+ if profiles:
+ print()
+ print("Available profiles in %s:" % self.ipython_dir)
+ self._print_profiles(profiles)
+
+ profiles = list_profiles_in(py3compat.getcwd())
+ if profiles:
+ print()
+ print("Available profiles in current directory (%s):" % py3compat.getcwd())
+ self._print_profiles(profiles)
+
+ print()
+ print("To use any of the above profiles, start IPython with:")
+ print(" ipython --profile=<name>")
+ print()
+
+ def start(self):
+ self.list_profile_dirs()
+
+
+create_flags = {}
+create_flags.update(base_flags)
+# don't include '--init' flag, which implies running profile create in other apps
+create_flags.pop('init')
+create_flags['reset'] = ({'ProfileCreate': {'overwrite' : True}},
+ "reset config files in this profile to the defaults.")
+create_flags['parallel'] = ({'ProfileCreate': {'parallel' : True}},
+ "Include the config files for parallel "
+ "computing apps (ipengine, ipcontroller, etc.)")
+
+
+class ProfileCreate(BaseIPythonApplication):
+ name = u'ipython-profile'
+ description = create_help
+ examples = _create_examples
auto_create = Bool(True)
- def _log_format_default(self):
- return "[%(name)s] %(message)s"
-
- def _copy_config_files_default(self):
- return True
-
+ def _log_format_default(self):
+ return "[%(name)s] %(message)s"
+
+ def _copy_config_files_default(self):
+ return True
+
parallel = Bool(False,
help="whether to include parallel computing config files"
).tag(config=True)
@observe('parallel')
def _parallel_changed(self, change):
- parallel_files = [ 'ipcontroller_config.py',
- 'ipengine_config.py',
- 'ipcluster_config.py'
- ]
+ parallel_files = [ 'ipcontroller_config.py',
+ 'ipengine_config.py',
+ 'ipcluster_config.py'
+ ]
if change['new']:
- for cf in parallel_files:
- self.config_files.append(cf)
- else:
- for cf in parallel_files:
- if cf in self.config_files:
- self.config_files.remove(cf)
-
- def parse_command_line(self, argv):
- super(ProfileCreate, self).parse_command_line(argv)
- # accept positional arg as profile name
- if self.extra_args:
- self.profile = self.extra_args[0]
-
- flags = Dict(create_flags)
-
- classes = [ProfileDir]
-
- def _import_app(self, app_path):
- """import an app class"""
- app = None
- name = app_path.rsplit('.', 1)[-1]
- try:
- app = import_item(app_path)
- except ImportError:
- self.log.info("Couldn't import %s, config file will be excluded", name)
- except Exception:
- self.log.warning('Unexpected error importing %s', name, exc_info=True)
- return app
-
- def init_config_files(self):
- super(ProfileCreate, self).init_config_files()
- # use local imports, since these classes may import from here
- from IPython.terminal.ipapp import TerminalIPythonApp
- apps = [TerminalIPythonApp]
- for app_path in (
- 'ipykernel.kernelapp.IPKernelApp',
- ):
- app = self._import_app(app_path)
- if app is not None:
- apps.append(app)
- if self.parallel:
- from ipyparallel.apps.ipcontrollerapp import IPControllerApp
- from ipyparallel.apps.ipengineapp import IPEngineApp
- from ipyparallel.apps.ipclusterapp import IPClusterStart
- apps.extend([
- IPControllerApp,
- IPEngineApp,
- IPClusterStart,
- ])
- for App in apps:
- app = App()
- app.config.update(self.config)
- app.log = self.log
- app.overwrite = self.overwrite
- app.copy_config_files=True
- app.ipython_dir=self.ipython_dir
- app.profile_dir=self.profile_dir
- app.init_config_files()
-
- def stage_default_config_file(self):
- pass
-
-
-class ProfileApp(Application):
- name = u'ipython profile'
- description = profile_help
- examples = _main_examples
-
- subcommands = Dict(dict(
- create = (ProfileCreate, ProfileCreate.description.splitlines()[0]),
- list = (ProfileList, ProfileList.description.splitlines()[0]),
- locate = (ProfileLocate, ProfileLocate.description.splitlines()[0]),
- ))
-
- def start(self):
- if self.subapp is None:
- print("No subcommand specified. Must specify one of: %s"%(self.subcommands.keys()))
- print()
- self.print_description()
- self.print_subcommands()
- self.exit(1)
- else:
- return self.subapp.start()
+ for cf in parallel_files:
+ self.config_files.append(cf)
+ else:
+ for cf in parallel_files:
+ if cf in self.config_files:
+ self.config_files.remove(cf)
+
+ def parse_command_line(self, argv):
+ super(ProfileCreate, self).parse_command_line(argv)
+ # accept positional arg as profile name
+ if self.extra_args:
+ self.profile = self.extra_args[0]
+
+ flags = Dict(create_flags)
+
+ classes = [ProfileDir]
+
+ def _import_app(self, app_path):
+ """import an app class"""
+ app = None
+ name = app_path.rsplit('.', 1)[-1]
+ try:
+ app = import_item(app_path)
+ except ImportError:
+ self.log.info("Couldn't import %s, config file will be excluded", name)
+ except Exception:
+ self.log.warning('Unexpected error importing %s', name, exc_info=True)
+ return app
+
+ def init_config_files(self):
+ super(ProfileCreate, self).init_config_files()
+ # use local imports, since these classes may import from here
+ from IPython.terminal.ipapp import TerminalIPythonApp
+ apps = [TerminalIPythonApp]
+ for app_path in (
+ 'ipykernel.kernelapp.IPKernelApp',
+ ):
+ app = self._import_app(app_path)
+ if app is not None:
+ apps.append(app)
+ if self.parallel:
+ from ipyparallel.apps.ipcontrollerapp import IPControllerApp
+ from ipyparallel.apps.ipengineapp import IPEngineApp
+ from ipyparallel.apps.ipclusterapp import IPClusterStart
+ apps.extend([
+ IPControllerApp,
+ IPEngineApp,
+ IPClusterStart,
+ ])
+ for App in apps:
+ app = App()
+ app.config.update(self.config)
+ app.log = self.log
+ app.overwrite = self.overwrite
+ app.copy_config_files=True
+ app.ipython_dir=self.ipython_dir
+ app.profile_dir=self.profile_dir
+ app.init_config_files()
+
+ def stage_default_config_file(self):
+ pass
+
+
+class ProfileApp(Application):
+ name = u'ipython profile'
+ description = profile_help
+ examples = _main_examples
+
+ subcommands = Dict(dict(
+ create = (ProfileCreate, ProfileCreate.description.splitlines()[0]),
+ list = (ProfileList, ProfileList.description.splitlines()[0]),
+ locate = (ProfileLocate, ProfileLocate.description.splitlines()[0]),
+ ))
+
+ def start(self):
+ if self.subapp is None:
+ print("No subcommand specified. Must specify one of: %s"%(self.subcommands.keys()))
+ print()
+ self.print_description()
+ self.print_subcommands()
+ self.exit(1)
+ else:
+ return self.subapp.start()
diff --git a/contrib/python/ipython/py2/IPython/core/profiledir.py b/contrib/python/ipython/py2/IPython/core/profiledir.py
index 4e54f8c68c..b777f13da0 100644
--- a/contrib/python/ipython/py2/IPython/core/profiledir.py
+++ b/contrib/python/ipython/py2/IPython/core/profiledir.py
@@ -1,222 +1,222 @@
-# encoding: utf-8
-"""An object for managing IPython profile directories."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import os
-import shutil
-import errno
-
-from traitlets.config.configurable import LoggingConfigurable
-from IPython.paths import get_ipython_package_dir
-from IPython.utils.path import expand_path, ensure_dir_exists
-from IPython.utils import py3compat
+# encoding: utf-8
+"""An object for managing IPython profile directories."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import os
+import shutil
+import errno
+
+from traitlets.config.configurable import LoggingConfigurable
+from IPython.paths import get_ipython_package_dir
+from IPython.utils.path import expand_path, ensure_dir_exists
+from IPython.utils import py3compat
from traitlets import Unicode, Bool, observe
-
-#-----------------------------------------------------------------------------
-# Module errors
-#-----------------------------------------------------------------------------
-
-class ProfileDirError(Exception):
- pass
-
-
-#-----------------------------------------------------------------------------
-# Class for managing profile directories
-#-----------------------------------------------------------------------------
-
-class ProfileDir(LoggingConfigurable):
- """An object to manage the profile directory and its resources.
-
- The profile directory is used by all IPython applications, to manage
- configuration, logging and security.
-
- This object knows how to find, create and manage these directories. This
- should be used by any code that wants to handle profiles.
- """
-
- security_dir_name = Unicode('security')
- log_dir_name = Unicode('log')
- startup_dir_name = Unicode('startup')
- pid_dir_name = Unicode('pid')
- static_dir_name = Unicode('static')
- security_dir = Unicode(u'')
- log_dir = Unicode(u'')
- startup_dir = Unicode(u'')
- pid_dir = Unicode(u'')
- static_dir = Unicode(u'')
-
+
+#-----------------------------------------------------------------------------
+# Module errors
+#-----------------------------------------------------------------------------
+
+class ProfileDirError(Exception):
+ pass
+
+
+#-----------------------------------------------------------------------------
+# Class for managing profile directories
+#-----------------------------------------------------------------------------
+
+class ProfileDir(LoggingConfigurable):
+ """An object to manage the profile directory and its resources.
+
+ The profile directory is used by all IPython applications, to manage
+ configuration, logging and security.
+
+ This object knows how to find, create and manage these directories. This
+ should be used by any code that wants to handle profiles.
+ """
+
+ security_dir_name = Unicode('security')
+ log_dir_name = Unicode('log')
+ startup_dir_name = Unicode('startup')
+ pid_dir_name = Unicode('pid')
+ static_dir_name = Unicode('static')
+ security_dir = Unicode(u'')
+ log_dir = Unicode(u'')
+ startup_dir = Unicode(u'')
+ pid_dir = Unicode(u'')
+ static_dir = Unicode(u'')
+
location = Unicode(u'',
- help="""Set the profile location directly. This overrides the logic used by the
- `profile` option.""",
+ help="""Set the profile location directly. This overrides the logic used by the
+ `profile` option.""",
).tag(config=True)
-
- _location_isset = Bool(False) # flag for detecting multiply set location
+
+ _location_isset = Bool(False) # flag for detecting multiply set location
@observe('location')
def _location_changed(self, change):
- if self._location_isset:
- raise RuntimeError("Cannot set profile location more than once.")
- self._location_isset = True
+ if self._location_isset:
+ raise RuntimeError("Cannot set profile location more than once.")
+ self._location_isset = True
new = change['new']
- ensure_dir_exists(new)
-
- # ensure config files exist:
- self.security_dir = os.path.join(new, self.security_dir_name)
- self.log_dir = os.path.join(new, self.log_dir_name)
- self.startup_dir = os.path.join(new, self.startup_dir_name)
- self.pid_dir = os.path.join(new, self.pid_dir_name)
- self.static_dir = os.path.join(new, self.static_dir_name)
- self.check_dirs()
+ ensure_dir_exists(new)
+
+ # ensure config files exist:
+ self.security_dir = os.path.join(new, self.security_dir_name)
+ self.log_dir = os.path.join(new, self.log_dir_name)
+ self.startup_dir = os.path.join(new, self.startup_dir_name)
+ self.pid_dir = os.path.join(new, self.pid_dir_name)
+ self.static_dir = os.path.join(new, self.static_dir_name)
+ self.check_dirs()
- def _mkdir(self, path, mode=None):
- """ensure a directory exists at a given path
-
- This is a version of os.mkdir, with the following differences:
-
- - returns True if it created the directory, False otherwise
- - ignores EEXIST, protecting against race conditions where
- the dir may have been created in between the check and
- the creation
- - sets permissions if requested and the dir already exists
- """
- if os.path.exists(path):
- if mode and os.stat(path).st_mode != mode:
- try:
- os.chmod(path, mode)
- except OSError:
- self.log.warning(
- "Could not set permissions on %s",
- path
- )
- return False
- try:
- if mode:
- os.mkdir(path, mode)
- else:
- os.mkdir(path)
- except OSError as e:
- if e.errno == errno.EEXIST:
- return False
- else:
- raise
-
- return True
+ def _mkdir(self, path, mode=None):
+ """ensure a directory exists at a given path
+
+ This is a version of os.mkdir, with the following differences:
+
+ - returns True if it created the directory, False otherwise
+ - ignores EEXIST, protecting against race conditions where
+ the dir may have been created in between the check and
+ the creation
+ - sets permissions if requested and the dir already exists
+ """
+ if os.path.exists(path):
+ if mode and os.stat(path).st_mode != mode:
+ try:
+ os.chmod(path, mode)
+ except OSError:
+ self.log.warning(
+ "Could not set permissions on %s",
+ path
+ )
+ return False
+ try:
+ if mode:
+ os.mkdir(path, mode)
+ else:
+ os.mkdir(path)
+ except OSError as e:
+ if e.errno == errno.EEXIST:
+ return False
+ else:
+ raise
+
+ return True
@observe('log_dir')
def check_log_dir(self, change=None):
- self._mkdir(self.log_dir)
+ self._mkdir(self.log_dir)
@observe('startup_dir')
def check_startup_dir(self, change=None):
- self._mkdir(self.startup_dir)
-
- readme = os.path.join(self.startup_dir, 'README')
-
+ self._mkdir(self.startup_dir)
+
+ readme = os.path.join(self.startup_dir, 'README')
+
if not os.path.exists(readme):
import pkgutil
with open(readme, 'wb') as f:
f.write(pkgutil.get_data(__name__, 'profile/README_STARTUP'))
-
+
@observe('security_dir')
def check_security_dir(self, change=None):
- self._mkdir(self.security_dir, 0o40700)
-
+ self._mkdir(self.security_dir, 0o40700)
+
@observe('pid_dir')
def check_pid_dir(self, change=None):
- self._mkdir(self.pid_dir, 0o40700)
-
- def check_dirs(self):
- self.check_security_dir()
- self.check_log_dir()
- self.check_pid_dir()
- self.check_startup_dir()
-
- def copy_config_file(self, config_file, path=None, overwrite=False):
- """Copy a default config file into the active profile directory.
-
- Default configuration files are kept in :mod:`IPython.core.profile`.
- This function moves these from that location to the working profile
- directory.
- """
- dst = os.path.join(self.location, config_file)
- if os.path.isfile(dst) and not overwrite:
- return False
- if path is None:
- path = os.path.join(get_ipython_package_dir(), u'core', u'profile', u'default')
- src = os.path.join(path, config_file)
- shutil.copy(src, dst)
- return True
-
- @classmethod
- def create_profile_dir(cls, profile_dir, config=None):
- """Create a new profile directory given a full path.
-
- Parameters
- ----------
- profile_dir : str
- The full path to the profile directory. If it does exist, it will
- be used. If not, it will be created.
- """
- return cls(location=profile_dir, config=config)
-
- @classmethod
- def create_profile_dir_by_name(cls, path, name=u'default', config=None):
- """Create a profile dir by profile name and path.
-
- Parameters
- ----------
- path : unicode
- The path (directory) to put the profile directory in.
- name : unicode
- The name of the profile. The name of the profile directory will
- be "profile_<profile>".
- """
- if not os.path.isdir(path):
- raise ProfileDirError('Directory not found: %s' % path)
- profile_dir = os.path.join(path, u'profile_' + name)
- return cls(location=profile_dir, config=config)
-
- @classmethod
- def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
- """Find an existing profile dir by profile name, return its ProfileDir.
-
- This searches through a sequence of paths for a profile dir. If it
- is not found, a :class:`ProfileDirError` exception will be raised.
-
- The search path algorithm is:
- 1. ``py3compat.getcwd()``
- 2. ``ipython_dir``
-
- Parameters
- ----------
- ipython_dir : unicode or str
- The IPython directory to use.
- name : unicode or str
- The name of the profile. The name of the profile directory
- will be "profile_<profile>".
- """
- dirname = u'profile_' + name
- paths = [py3compat.getcwd(), ipython_dir]
- for p in paths:
- profile_dir = os.path.join(p, dirname)
- if os.path.isdir(profile_dir):
- return cls(location=profile_dir, config=config)
- else:
- raise ProfileDirError('Profile directory not found in paths: %s' % dirname)
-
- @classmethod
- def find_profile_dir(cls, profile_dir, config=None):
- """Find/create a profile dir and return its ProfileDir.
-
- This will create the profile directory if it doesn't exist.
-
- Parameters
- ----------
- profile_dir : unicode or str
- The path of the profile directory.
- """
- profile_dir = expand_path(profile_dir)
- if not os.path.isdir(profile_dir):
- raise ProfileDirError('Profile directory not found: %s' % profile_dir)
- return cls(location=profile_dir, config=config)
+ self._mkdir(self.pid_dir, 0o40700)
+
+ def check_dirs(self):
+ self.check_security_dir()
+ self.check_log_dir()
+ self.check_pid_dir()
+ self.check_startup_dir()
+
+ def copy_config_file(self, config_file, path=None, overwrite=False):
+ """Copy a default config file into the active profile directory.
+
+ Default configuration files are kept in :mod:`IPython.core.profile`.
+ This function moves these from that location to the working profile
+ directory.
+ """
+ dst = os.path.join(self.location, config_file)
+ if os.path.isfile(dst) and not overwrite:
+ return False
+ if path is None:
+ path = os.path.join(get_ipython_package_dir(), u'core', u'profile', u'default')
+ src = os.path.join(path, config_file)
+ shutil.copy(src, dst)
+ return True
+
+ @classmethod
+ def create_profile_dir(cls, profile_dir, config=None):
+ """Create a new profile directory given a full path.
+
+ Parameters
+ ----------
+ profile_dir : str
+ The full path to the profile directory. If it does exist, it will
+ be used. If not, it will be created.
+ """
+ return cls(location=profile_dir, config=config)
+
+ @classmethod
+ def create_profile_dir_by_name(cls, path, name=u'default', config=None):
+ """Create a profile dir by profile name and path.
+
+ Parameters
+ ----------
+ path : unicode
+ The path (directory) to put the profile directory in.
+ name : unicode
+ The name of the profile. The name of the profile directory will
+ be "profile_<profile>".
+ """
+ if not os.path.isdir(path):
+ raise ProfileDirError('Directory not found: %s' % path)
+ profile_dir = os.path.join(path, u'profile_' + name)
+ return cls(location=profile_dir, config=config)
+
+ @classmethod
+ def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
+ """Find an existing profile dir by profile name, return its ProfileDir.
+
+ This searches through a sequence of paths for a profile dir. If it
+ is not found, a :class:`ProfileDirError` exception will be raised.
+
+ The search path algorithm is:
+ 1. ``py3compat.getcwd()``
+ 2. ``ipython_dir``
+
+ Parameters
+ ----------
+ ipython_dir : unicode or str
+ The IPython directory to use.
+ name : unicode or str
+ The name of the profile. The name of the profile directory
+ will be "profile_<profile>".
+ """
+ dirname = u'profile_' + name
+ paths = [py3compat.getcwd(), ipython_dir]
+ for p in paths:
+ profile_dir = os.path.join(p, dirname)
+ if os.path.isdir(profile_dir):
+ return cls(location=profile_dir, config=config)
+ else:
+ raise ProfileDirError('Profile directory not found in paths: %s' % dirname)
+
+ @classmethod
+ def find_profile_dir(cls, profile_dir, config=None):
+ """Find/create a profile dir and return its ProfileDir.
+
+ This will create the profile directory if it doesn't exist.
+
+ Parameters
+ ----------
+ profile_dir : unicode or str
+ The path of the profile directory.
+ """
+ profile_dir = expand_path(profile_dir)
+ if not os.path.isdir(profile_dir):
+ raise ProfileDirError('Profile directory not found: %s' % profile_dir)
+ return cls(location=profile_dir, config=config)
diff --git a/contrib/python/ipython/py2/IPython/core/prompts.py b/contrib/python/ipython/py2/IPython/core/prompts.py
index 126e84fdfd..7802bc5363 100644
--- a/contrib/python/ipython/py2/IPython/core/prompts.py
+++ b/contrib/python/ipython/py2/IPython/core/prompts.py
@@ -1,26 +1,26 @@
-# -*- coding: utf-8 -*-
+# -*- coding: utf-8 -*-
"""Being removed
-"""
-
+"""
+
from IPython.utils import py3compat
-
-class LazyEvaluate(object):
- """This is used for formatting strings with values that need to be updated
- at that time, such as the current time or working directory."""
- def __init__(self, func, *args, **kwargs):
- self.func = func
- self.args = args
- self.kwargs = kwargs
-
- def __call__(self, **kwargs):
- self.kwargs.update(kwargs)
- return self.func(*self.args, **self.kwargs)
-
- def __str__(self):
- return str(self())
-
- def __unicode__(self):
- return py3compat.unicode_type(self())
-
- def __format__(self, format_spec):
- return format(self(), format_spec)
+
+class LazyEvaluate(object):
+ """This is used for formatting strings with values that need to be updated
+ at that time, such as the current time or working directory."""
+ def __init__(self, func, *args, **kwargs):
+ self.func = func
+ self.args = args
+ self.kwargs = kwargs
+
+ def __call__(self, **kwargs):
+ self.kwargs.update(kwargs)
+ return self.func(*self.args, **self.kwargs)
+
+ def __str__(self):
+ return str(self())
+
+ def __unicode__(self):
+ return py3compat.unicode_type(self())
+
+ def __format__(self, format_spec):
+ return format(self(), format_spec)
diff --git a/contrib/python/ipython/py2/IPython/core/pylabtools.py b/contrib/python/ipython/py2/IPython/core/pylabtools.py
index 79072b41a9..a1932d8c48 100644
--- a/contrib/python/ipython/py2/IPython/core/pylabtools.py
+++ b/contrib/python/ipython/py2/IPython/core/pylabtools.py
@@ -1,28 +1,28 @@
-# -*- coding: utf-8 -*-
-"""Pylab (matplotlib) support utilities."""
-from __future__ import print_function
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from io import BytesIO
-
-from IPython.core.display import _pngxy
-from IPython.utils.decorators import flag_calls
-from IPython.utils import py3compat
-
-# If user specifies a GUI, that dictates the backend, otherwise we read the
-# user's mpl default from the mpl rc structure
-backends = {'tk': 'TkAgg',
- 'gtk': 'GTKAgg',
- 'gtk3': 'GTK3Agg',
- 'wx': 'WXAgg',
- 'qt4': 'Qt4Agg',
- 'qt5': 'Qt5Agg',
+# -*- coding: utf-8 -*-
+"""Pylab (matplotlib) support utilities."""
+from __future__ import print_function
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from io import BytesIO
+
+from IPython.core.display import _pngxy
+from IPython.utils.decorators import flag_calls
+from IPython.utils import py3compat
+
+# If user specifies a GUI, that dictates the backend, otherwise we read the
+# user's mpl default from the mpl rc structure
+backends = {'tk': 'TkAgg',
+ 'gtk': 'GTKAgg',
+ 'gtk3': 'GTK3Agg',
+ 'wx': 'WXAgg',
+ 'qt4': 'Qt4Agg',
+ 'qt5': 'Qt5Agg',
'qt': 'Qt5Agg',
- 'osx': 'MacOSX',
- 'nbagg': 'nbAgg',
- 'notebook': 'nbAgg',
+ 'osx': 'MacOSX',
+ 'nbagg': 'nbAgg',
+ 'notebook': 'nbAgg',
'agg': 'agg',
'svg': 'svg',
'pdf': 'pdf',
@@ -31,20 +31,20 @@ backends = {'tk': 'TkAgg',
'ipympl': 'module://ipympl.backend_nbagg',
'widget': 'module://ipympl.backend_nbagg',
}
-
-# We also need a reverse backends2guis mapping that will properly choose which
-# GUI support to activate based on the desired matplotlib backend. For the
-# most part it's just a reverse of the above dict, but we also need to add a
-# few others that map to the same GUI manually:
-backend2gui = dict(zip(backends.values(), backends.keys()))
-# Our tests expect backend2gui to just return 'qt'
-backend2gui['Qt4Agg'] = 'qt'
-# In the reverse mapping, there are a few extra valid matplotlib backends that
-# map to the same GUI support
-backend2gui['GTK'] = backend2gui['GTKCairo'] = 'gtk'
-backend2gui['GTK3Cairo'] = 'gtk3'
-backend2gui['WX'] = 'wx'
-backend2gui['CocoaAgg'] = 'osx'
+
+# We also need a reverse backends2guis mapping that will properly choose which
+# GUI support to activate based on the desired matplotlib backend. For the
+# most part it's just a reverse of the above dict, but we also need to add a
+# few others that map to the same GUI manually:
+backend2gui = dict(zip(backends.values(), backends.keys()))
+# Our tests expect backend2gui to just return 'qt'
+backend2gui['Qt4Agg'] = 'qt'
+# In the reverse mapping, there are a few extra valid matplotlib backends that
+# map to the same GUI support
+backend2gui['GTK'] = backend2gui['GTKCairo'] = 'gtk'
+backend2gui['GTK3Cairo'] = 'gtk3'
+backend2gui['WX'] = 'wx'
+backend2gui['CocoaAgg'] = 'osx'
# And some backends that don't need GUI integration
del backend2gui['nbAgg']
del backend2gui['agg']
@@ -52,138 +52,138 @@ del backend2gui['svg']
del backend2gui['pdf']
del backend2gui['ps']
del backend2gui['module://ipykernel.pylab.backend_inline']
-
-#-----------------------------------------------------------------------------
-# Matplotlib utilities
-#-----------------------------------------------------------------------------
-
-
-def getfigs(*fig_nums):
- """Get a list of matplotlib figures by figure numbers.
-
- If no arguments are given, all available figures are returned. If the
- argument list contains references to invalid figures, a warning is printed
- but the function continues pasting further figures.
-
- Parameters
- ----------
- figs : tuple
- A tuple of ints giving the figure numbers of the figures to return.
- """
- from matplotlib._pylab_helpers import Gcf
- if not fig_nums:
- fig_managers = Gcf.get_all_fig_managers()
- return [fm.canvas.figure for fm in fig_managers]
- else:
- figs = []
- for num in fig_nums:
- f = Gcf.figs.get(num)
- if f is None:
- print('Warning: figure %s not available.' % num)
- else:
- figs.append(f.canvas.figure)
- return figs
-
-
-def figsize(sizex, sizey):
- """Set the default figure size to be [sizex, sizey].
-
- This is just an easy to remember, convenience wrapper that sets::
-
- matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
- """
- import matplotlib
- matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
-
-
-def print_figure(fig, fmt='png', bbox_inches='tight', **kwargs):
- """Print a figure to an image, and return the resulting file data
-
- Returned data will be bytes unless ``fmt='svg'``,
- in which case it will be unicode.
-
- Any keyword args are passed to fig.canvas.print_figure,
- such as ``quality`` or ``bbox_inches``.
- """
- from matplotlib import rcParams
- # When there's an empty figure, we shouldn't return anything, otherwise we
- # get big blank areas in the qt console.
- if not fig.axes and not fig.lines:
- return
-
+
+#-----------------------------------------------------------------------------
+# Matplotlib utilities
+#-----------------------------------------------------------------------------
+
+
+def getfigs(*fig_nums):
+ """Get a list of matplotlib figures by figure numbers.
+
+ If no arguments are given, all available figures are returned. If the
+ argument list contains references to invalid figures, a warning is printed
+ but the function continues pasting further figures.
+
+ Parameters
+ ----------
+ figs : tuple
+ A tuple of ints giving the figure numbers of the figures to return.
+ """
+ from matplotlib._pylab_helpers import Gcf
+ if not fig_nums:
+ fig_managers = Gcf.get_all_fig_managers()
+ return [fm.canvas.figure for fm in fig_managers]
+ else:
+ figs = []
+ for num in fig_nums:
+ f = Gcf.figs.get(num)
+ if f is None:
+ print('Warning: figure %s not available.' % num)
+ else:
+ figs.append(f.canvas.figure)
+ return figs
+
+
+def figsize(sizex, sizey):
+ """Set the default figure size to be [sizex, sizey].
+
+ This is just an easy to remember, convenience wrapper that sets::
+
+ matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
+ """
+ import matplotlib
+ matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
+
+
+def print_figure(fig, fmt='png', bbox_inches='tight', **kwargs):
+ """Print a figure to an image, and return the resulting file data
+
+ Returned data will be bytes unless ``fmt='svg'``,
+ in which case it will be unicode.
+
+ Any keyword args are passed to fig.canvas.print_figure,
+ such as ``quality`` or ``bbox_inches``.
+ """
+ from matplotlib import rcParams
+ # When there's an empty figure, we shouldn't return anything, otherwise we
+ # get big blank areas in the qt console.
+ if not fig.axes and not fig.lines:
+ return
+
dpi = fig.dpi
- if fmt == 'retina':
- dpi = dpi * 2
- fmt = 'png'
-
- # build keyword args
- kw = dict(
- format=fmt,
- facecolor=fig.get_facecolor(),
- edgecolor=fig.get_edgecolor(),
- dpi=dpi,
- bbox_inches=bbox_inches,
- )
- # **kwargs get higher priority
- kw.update(kwargs)
-
- bytes_io = BytesIO()
- fig.canvas.print_figure(bytes_io, **kw)
- data = bytes_io.getvalue()
- if fmt == 'svg':
- data = data.decode('utf-8')
- return data
-
-def retina_figure(fig, **kwargs):
- """format a figure as a pixel-doubled (retina) PNG"""
- pngdata = print_figure(fig, fmt='retina', **kwargs)
- # Make sure that retina_figure acts just like print_figure and returns
- # None when the figure is empty.
- if pngdata is None:
- return
- w, h = _pngxy(pngdata)
- metadata = dict(width=w//2, height=h//2)
- return pngdata, metadata
-
-# We need a little factory function here to create the closure where
-# safe_execfile can live.
-def mpl_runner(safe_execfile):
- """Factory to return a matplotlib-enabled runner for %run.
-
- Parameters
- ----------
- safe_execfile : function
- This must be a function with the same interface as the
- :meth:`safe_execfile` method of IPython.
-
- Returns
- -------
- A function suitable for use as the ``runner`` argument of the %run magic
- function.
- """
-
- def mpl_execfile(fname,*where,**kw):
- """matplotlib-aware wrapper around safe_execfile.
-
- Its interface is identical to that of the :func:`execfile` builtin.
-
- This is ultimately a call to execfile(), but wrapped in safeties to
- properly handle interactive rendering."""
-
- import matplotlib
+ if fmt == 'retina':
+ dpi = dpi * 2
+ fmt = 'png'
+
+ # build keyword args
+ kw = dict(
+ format=fmt,
+ facecolor=fig.get_facecolor(),
+ edgecolor=fig.get_edgecolor(),
+ dpi=dpi,
+ bbox_inches=bbox_inches,
+ )
+ # **kwargs get higher priority
+ kw.update(kwargs)
+
+ bytes_io = BytesIO()
+ fig.canvas.print_figure(bytes_io, **kw)
+ data = bytes_io.getvalue()
+ if fmt == 'svg':
+ data = data.decode('utf-8')
+ return data
+
+def retina_figure(fig, **kwargs):
+ """format a figure as a pixel-doubled (retina) PNG"""
+ pngdata = print_figure(fig, fmt='retina', **kwargs)
+ # Make sure that retina_figure acts just like print_figure and returns
+ # None when the figure is empty.
+ if pngdata is None:
+ return
+ w, h = _pngxy(pngdata)
+ metadata = dict(width=w//2, height=h//2)
+ return pngdata, metadata
+
+# We need a little factory function here to create the closure where
+# safe_execfile can live.
+def mpl_runner(safe_execfile):
+ """Factory to return a matplotlib-enabled runner for %run.
+
+ Parameters
+ ----------
+ safe_execfile : function
+ This must be a function with the same interface as the
+ :meth:`safe_execfile` method of IPython.
+
+ Returns
+ -------
+ A function suitable for use as the ``runner`` argument of the %run magic
+ function.
+ """
+
+ def mpl_execfile(fname,*where,**kw):
+ """matplotlib-aware wrapper around safe_execfile.
+
+ Its interface is identical to that of the :func:`execfile` builtin.
+
+ This is ultimately a call to execfile(), but wrapped in safeties to
+ properly handle interactive rendering."""
+
+ import matplotlib
import matplotlib.pyplot as plt
-
- #print '*** Matplotlib runner ***' # dbg
- # turn off rendering until end of script
- is_interactive = matplotlib.rcParams['interactive']
- matplotlib.interactive(False)
- safe_execfile(fname,*where,**kw)
- matplotlib.interactive(is_interactive)
- # make rendering call now, if the user tried to do it
+
+ #print '*** Matplotlib runner ***' # dbg
+ # turn off rendering until end of script
+ is_interactive = matplotlib.rcParams['interactive']
+ matplotlib.interactive(False)
+ safe_execfile(fname,*where,**kw)
+ matplotlib.interactive(is_interactive)
+ # make rendering call now, if the user tried to do it
if plt.draw_if_interactive.called:
plt.draw()
plt.draw_if_interactive.called = False
-
+
# re-draw everything that is stale
try:
da = plt.draw_all
@@ -192,225 +192,225 @@ def mpl_runner(safe_execfile):
else:
da()
- return mpl_execfile
-
-
-def _reshow_nbagg_figure(fig):
- """reshow an nbagg figure"""
- try:
- reshow = fig.canvas.manager.reshow
- except AttributeError:
- raise NotImplementedError()
- else:
- reshow()
-
-
-def select_figure_formats(shell, formats, **kwargs):
- """Select figure formats for the inline backend.
-
- Parameters
- ==========
- shell : InteractiveShell
- The main IPython instance.
- formats : str or set
- One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
- **kwargs : any
- Extra keyword arguments to be passed to fig.canvas.print_figure.
- """
- import matplotlib
- from matplotlib.figure import Figure
-
- svg_formatter = shell.display_formatter.formatters['image/svg+xml']
- png_formatter = shell.display_formatter.formatters['image/png']
- jpg_formatter = shell.display_formatter.formatters['image/jpeg']
- pdf_formatter = shell.display_formatter.formatters['application/pdf']
-
- if isinstance(formats, py3compat.string_types):
- formats = {formats}
- # cast in case of list / tuple
- formats = set(formats)
-
- [ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ]
+ return mpl_execfile
+
+
+def _reshow_nbagg_figure(fig):
+ """reshow an nbagg figure"""
+ try:
+ reshow = fig.canvas.manager.reshow
+ except AttributeError:
+ raise NotImplementedError()
+ else:
+ reshow()
+
+
+def select_figure_formats(shell, formats, **kwargs):
+ """Select figure formats for the inline backend.
+
+ Parameters
+ ==========
+ shell : InteractiveShell
+ The main IPython instance.
+ formats : str or set
+ One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
+ **kwargs : any
+ Extra keyword arguments to be passed to fig.canvas.print_figure.
+ """
+ import matplotlib
+ from matplotlib.figure import Figure
+
+ svg_formatter = shell.display_formatter.formatters['image/svg+xml']
+ png_formatter = shell.display_formatter.formatters['image/png']
+ jpg_formatter = shell.display_formatter.formatters['image/jpeg']
+ pdf_formatter = shell.display_formatter.formatters['application/pdf']
+
+ if isinstance(formats, py3compat.string_types):
+ formats = {formats}
+ # cast in case of list / tuple
+ formats = set(formats)
+
+ [ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ]
mplbackend = matplotlib.get_backend().lower()
if mplbackend == 'nbagg' or mplbackend == 'module://ipympl.backend_nbagg':
- formatter = shell.display_formatter.ipython_display_formatter
- formatter.for_type(Figure, _reshow_nbagg_figure)
-
- supported = {'png', 'png2x', 'retina', 'jpg', 'jpeg', 'svg', 'pdf'}
- bad = formats.difference(supported)
- if bad:
- bs = "%s" % ','.join([repr(f) for f in bad])
- gs = "%s" % ','.join([repr(f) for f in supported])
- raise ValueError("supported formats are: %s not %s" % (gs, bs))
-
- if 'png' in formats:
- png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
- if 'retina' in formats or 'png2x' in formats:
- png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
- if 'jpg' in formats or 'jpeg' in formats:
- jpg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'jpg', **kwargs))
- if 'svg' in formats:
- svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg', **kwargs))
- if 'pdf' in formats:
- pdf_formatter.for_type(Figure, lambda fig: print_figure(fig, 'pdf', **kwargs))
-
-#-----------------------------------------------------------------------------
-# Code for initializing matplotlib and importing pylab
-#-----------------------------------------------------------------------------
-
-
-def find_gui_and_backend(gui=None, gui_select=None):
- """Given a gui string return the gui and mpl backend.
-
- Parameters
- ----------
- gui : str
- Can be one of ('tk','gtk','wx','qt','qt4','inline').
- gui_select : str
- Can be one of ('tk','gtk','wx','qt','qt4','inline').
- This is any gui already selected by the shell.
-
- Returns
- -------
- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
- 'WXAgg','Qt4Agg','module://ipykernel.pylab.backend_inline').
- """
-
- import matplotlib
-
- if gui and gui != 'auto':
- # select backend based on requested gui
- backend = backends[gui]
- else:
- # We need to read the backend from the original data structure, *not*
- # from mpl.rcParams, since a prior invocation of %matplotlib may have
- # overwritten that.
- # WARNING: this assumes matplotlib 1.1 or newer!!
- backend = matplotlib.rcParamsOrig['backend']
- # In this case, we need to find what the appropriate gui selection call
- # should be for IPython, so we can activate inputhook accordingly
- gui = backend2gui.get(backend, None)
-
- # If we have already had a gui active, we need it and inline are the
- # ones allowed.
- if gui_select and gui != gui_select:
- gui = gui_select
- backend = backends[gui]
-
- return gui, backend
-
-
-def activate_matplotlib(backend):
- """Activate the given backend and set interactive to True."""
-
- import matplotlib
- matplotlib.interactive(True)
-
- # Matplotlib had a bug where even switch_backend could not force
- # the rcParam to update. This needs to be set *before* the module
- # magic of switch_backend().
- matplotlib.rcParams['backend'] = backend
-
- import matplotlib.pyplot
- matplotlib.pyplot.switch_backend(backend)
-
- # This must be imported last in the matplotlib series, after
- # backend/interactivity choices have been made
+ formatter = shell.display_formatter.ipython_display_formatter
+ formatter.for_type(Figure, _reshow_nbagg_figure)
+
+ supported = {'png', 'png2x', 'retina', 'jpg', 'jpeg', 'svg', 'pdf'}
+ bad = formats.difference(supported)
+ if bad:
+ bs = "%s" % ','.join([repr(f) for f in bad])
+ gs = "%s" % ','.join([repr(f) for f in supported])
+ raise ValueError("supported formats are: %s not %s" % (gs, bs))
+
+ if 'png' in formats:
+ png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
+ if 'retina' in formats or 'png2x' in formats:
+ png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
+ if 'jpg' in formats or 'jpeg' in formats:
+ jpg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'jpg', **kwargs))
+ if 'svg' in formats:
+ svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg', **kwargs))
+ if 'pdf' in formats:
+ pdf_formatter.for_type(Figure, lambda fig: print_figure(fig, 'pdf', **kwargs))
+
+#-----------------------------------------------------------------------------
+# Code for initializing matplotlib and importing pylab
+#-----------------------------------------------------------------------------
+
+
+def find_gui_and_backend(gui=None, gui_select=None):
+ """Given a gui string return the gui and mpl backend.
+
+ Parameters
+ ----------
+ gui : str
+ Can be one of ('tk','gtk','wx','qt','qt4','inline').
+ gui_select : str
+ Can be one of ('tk','gtk','wx','qt','qt4','inline').
+ This is any gui already selected by the shell.
+
+ Returns
+ -------
+ A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
+ 'WXAgg','Qt4Agg','module://ipykernel.pylab.backend_inline').
+ """
+
+ import matplotlib
+
+ if gui and gui != 'auto':
+ # select backend based on requested gui
+ backend = backends[gui]
+ else:
+ # We need to read the backend from the original data structure, *not*
+ # from mpl.rcParams, since a prior invocation of %matplotlib may have
+ # overwritten that.
+ # WARNING: this assumes matplotlib 1.1 or newer!!
+ backend = matplotlib.rcParamsOrig['backend']
+ # In this case, we need to find what the appropriate gui selection call
+ # should be for IPython, so we can activate inputhook accordingly
+ gui = backend2gui.get(backend, None)
+
+ # If we have already had a gui active, we need it and inline are the
+ # ones allowed.
+ if gui_select and gui != gui_select:
+ gui = gui_select
+ backend = backends[gui]
+
+ return gui, backend
+
+
+def activate_matplotlib(backend):
+ """Activate the given backend and set interactive to True."""
+
+ import matplotlib
+ matplotlib.interactive(True)
+
+ # Matplotlib had a bug where even switch_backend could not force
+ # the rcParam to update. This needs to be set *before* the module
+ # magic of switch_backend().
+ matplotlib.rcParams['backend'] = backend
+
+ import matplotlib.pyplot
+ matplotlib.pyplot.switch_backend(backend)
+
+ # This must be imported last in the matplotlib series, after
+ # backend/interactivity choices have been made
import matplotlib.pyplot as plt
-
+
plt.show._needmain = False
- # We need to detect at runtime whether show() is called by the user.
- # For this, we wrap it into a decorator which adds a 'called' flag.
+ # We need to detect at runtime whether show() is called by the user.
+ # For this, we wrap it into a decorator which adds a 'called' flag.
plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)
-
-
-def import_pylab(user_ns, import_all=True):
- """Populate the namespace with pylab-related values.
-
- Imports matplotlib, pylab, numpy, and everything from pylab and numpy.
-
- Also imports a few names from IPython (figsize, display, getfigs)
-
- """
-
- # Import numpy as np/pyplot as plt are conventions we're trying to
- # somewhat standardize on. Making them available to users by default
- # will greatly help this.
- s = ("import numpy\n"
- "import matplotlib\n"
- "from matplotlib import pylab, mlab, pyplot\n"
- "np = numpy\n"
- "plt = pyplot\n"
- )
- exec(s, user_ns)
-
- if import_all:
- s = ("from matplotlib.pylab import *\n"
- "from numpy import *\n")
- exec(s, user_ns)
-
- # IPython symbols to add
- user_ns['figsize'] = figsize
- from IPython.core.display import display
- # Add display and getfigs to the user's namespace
- user_ns['display'] = display
- user_ns['getfigs'] = getfigs
-
-
-def configure_inline_support(shell, backend):
- """Configure an IPython shell object for matplotlib use.
-
- Parameters
- ----------
- shell : InteractiveShell instance
-
- backend : matplotlib backend
- """
- # If using our svg payload backend, register the post-execution
- # function that will pick up the results for display. This can only be
- # done with access to the real shell object.
-
- # Note: if we can't load the inline backend, then there's no point
- # continuing (such as in terminal-only shells in environments without
- # zeromq available).
- try:
- from ipykernel.pylab.backend_inline import InlineBackend
- except ImportError:
- return
+
+
+def import_pylab(user_ns, import_all=True):
+ """Populate the namespace with pylab-related values.
+
+ Imports matplotlib, pylab, numpy, and everything from pylab and numpy.
+
+ Also imports a few names from IPython (figsize, display, getfigs)
+
+ """
+
+ # Import numpy as np/pyplot as plt are conventions we're trying to
+ # somewhat standardize on. Making them available to users by default
+ # will greatly help this.
+ s = ("import numpy\n"
+ "import matplotlib\n"
+ "from matplotlib import pylab, mlab, pyplot\n"
+ "np = numpy\n"
+ "plt = pyplot\n"
+ )
+ exec(s, user_ns)
+
+ if import_all:
+ s = ("from matplotlib.pylab import *\n"
+ "from numpy import *\n")
+ exec(s, user_ns)
+
+ # IPython symbols to add
+ user_ns['figsize'] = figsize
+ from IPython.core.display import display
+ # Add display and getfigs to the user's namespace
+ user_ns['display'] = display
+ user_ns['getfigs'] = getfigs
+
+
+def configure_inline_support(shell, backend):
+ """Configure an IPython shell object for matplotlib use.
+
+ Parameters
+ ----------
+ shell : InteractiveShell instance
+
+ backend : matplotlib backend
+ """
+ # If using our svg payload backend, register the post-execution
+ # function that will pick up the results for display. This can only be
+ # done with access to the real shell object.
+
+ # Note: if we can't load the inline backend, then there's no point
+ # continuing (such as in terminal-only shells in environments without
+ # zeromq available).
+ try:
+ from ipykernel.pylab.backend_inline import InlineBackend
+ except ImportError:
+ return
import matplotlib
-
- cfg = InlineBackend.instance(parent=shell)
- cfg.shell = shell
- if cfg not in shell.configurables:
- shell.configurables.append(cfg)
-
- if backend == backends['inline']:
- from ipykernel.pylab.backend_inline import flush_figures
- shell.events.register('post_execute', flush_figures)
-
- # Save rcParams that will be overwrittern
- shell._saved_rcParams = dict()
- for k in cfg.rc:
+
+ cfg = InlineBackend.instance(parent=shell)
+ cfg.shell = shell
+ if cfg not in shell.configurables:
+ shell.configurables.append(cfg)
+
+ if backend == backends['inline']:
+ from ipykernel.pylab.backend_inline import flush_figures
+ shell.events.register('post_execute', flush_figures)
+
+ # Save rcParams that will be overwrittern
+ shell._saved_rcParams = dict()
+ for k in cfg.rc:
shell._saved_rcParams[k] = matplotlib.rcParams[k]
- # load inline_rc
+ # load inline_rc
matplotlib.rcParams.update(cfg.rc)
- new_backend_name = "inline"
- else:
- from ipykernel.pylab.backend_inline import flush_figures
- try:
- shell.events.unregister('post_execute', flush_figures)
- except ValueError:
- pass
- if hasattr(shell, '_saved_rcParams'):
+ new_backend_name = "inline"
+ else:
+ from ipykernel.pylab.backend_inline import flush_figures
+ try:
+ shell.events.unregister('post_execute', flush_figures)
+ except ValueError:
+ pass
+ if hasattr(shell, '_saved_rcParams'):
matplotlib.rcParams.update(shell._saved_rcParams)
- del shell._saved_rcParams
- new_backend_name = "other"
-
- # only enable the formats once -> don't change the enabled formats (which the user may
- # has changed) when getting another "%matplotlib inline" call.
- # See https://github.com/ipython/ipykernel/issues/29
- cur_backend = getattr(configure_inline_support, "current_backend", "unset")
- if new_backend_name != cur_backend:
- # Setup the default figure format
- select_figure_formats(shell, cfg.figure_formats, **cfg.print_figure_kwargs)
- configure_inline_support.current_backend = new_backend_name
+ del shell._saved_rcParams
+ new_backend_name = "other"
+
+ # only enable the formats once -> don't change the enabled formats (which the user may
+ # has changed) when getting another "%matplotlib inline" call.
+ # See https://github.com/ipython/ipykernel/issues/29
+ cur_backend = getattr(configure_inline_support, "current_backend", "unset")
+ if new_backend_name != cur_backend:
+ # Setup the default figure format
+ select_figure_formats(shell, cfg.figure_formats, **cfg.print_figure_kwargs)
+ configure_inline_support.current_backend = new_backend_name
diff --git a/contrib/python/ipython/py2/IPython/core/release.py b/contrib/python/ipython/py2/IPython/core/release.py
index 94d54bb828..94dea1073b 100644
--- a/contrib/python/ipython/py2/IPython/core/release.py
+++ b/contrib/python/ipython/py2/IPython/core/release.py
@@ -1,123 +1,123 @@
-# -*- coding: utf-8 -*-
-"""Release data for the IPython project."""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2008, IPython Development Team.
-# Copyright (c) 2001, Fernando Perez <fernando.perez@colorado.edu>
-# Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
-# Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-# Name of the package for release purposes. This is the name which labels
-# the tarballs and RPMs made by distutils, so it's best to lowercase it.
-name = 'ipython'
-
-# IPython version information. An empty _version_extra corresponds to a full
-# release. 'dev' as a _version_extra string means this is a development
-# version
+# -*- coding: utf-8 -*-
+"""Release data for the IPython project."""
+
+#-----------------------------------------------------------------------------
+# Copyright (c) 2008, IPython Development Team.
+# Copyright (c) 2001, Fernando Perez <fernando.perez@colorado.edu>
+# Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
+# Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+# Name of the package for release purposes. This is the name which labels
+# the tarballs and RPMs made by distutils, so it's best to lowercase it.
+name = 'ipython'
+
+# IPython version information. An empty _version_extra corresponds to a full
+# release. 'dev' as a _version_extra string means this is a development
+# version
_version_major = 5
_version_minor = 9
_version_patch = 0
-_version_extra = '.dev'
+_version_extra = '.dev'
# _version_extra = 'rc1'
-_version_extra = '' # Uncomment this for full releases
-
-# release.codename is deprecated in 2.0, will be removed in 3.0
-codename = ''
-
-# Construct full version string from these.
-_ver = [_version_major, _version_minor, _version_patch]
-
-__version__ = '.'.join(map(str, _ver))
-if _version_extra:
- __version__ = __version__ + _version_extra
-
-version = __version__ # backwards compatibility name
-version_info = (_version_major, _version_minor, _version_patch, _version_extra)
-
-# Change this when incrementing the kernel protocol version
-kernel_protocol_version_info = (5, 0)
-kernel_protocol_version = "%i.%i" % kernel_protocol_version_info
-
-description = "IPython: Productive Interactive Computing"
-
-long_description = \
-"""
-IPython provides a rich toolkit to help you make the most out of using Python
-interactively. Its main components are:
-
-* A powerful interactive Python shell
-* A `Jupyter <http://jupyter.org/>`_ kernel to work with Python code in Jupyter
- notebooks and other interactive frontends.
-
-The enhanced interactive Python shells have the following main features:
-
-* Comprehensive object introspection.
-
-* Input history, persistent across sessions.
-
-* Caching of output results during a session with automatically generated
- references.
-
-* Extensible tab completion, with support by default for completion of python
- variables and keywords, filenames and function keywords.
-
-* Extensible system of 'magic' commands for controlling the environment and
- performing many tasks related either to IPython or the operating system.
-
-* A rich configuration system with easy switching between different setups
- (simpler than changing $PYTHONSTARTUP environment variables every time).
-
-* Session logging and reloading.
-
-* Extensible syntax processing for special purpose situations.
-
-* Access to the system shell with user-extensible alias system.
-
-* Easily embeddable in other Python programs and GUIs.
-
-* Integrated access to the pdb debugger and the Python profiler.
-
-The latest development version is always available from IPython's `GitHub
-site <http://github.com/ipython>`_.
-"""
-
-license = 'BSD'
-
-authors = {'Fernando' : ('Fernando Perez','fperez.net@gmail.com'),
- 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
- 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
- 'Ville' : ('Ville Vainio','vivainio@gmail.com'),
- 'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'),
- 'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com'),
- 'Thomas' : ('Thomas A. Kluyver', 'takowl@gmail.com'),
- 'Jorgen' : ('Jorgen Stenarson', 'jorgen.stenarson@bostream.nu'),
- 'Matthias' : ('Matthias Bussonnier', 'bussonniermatthias@gmail.com'),
- }
-
-author = 'The IPython Development Team'
-
+_version_extra = '' # Uncomment this for full releases
+
+# release.codename is deprecated in 2.0, will be removed in 3.0
+codename = ''
+
+# Construct full version string from these.
+_ver = [_version_major, _version_minor, _version_patch]
+
+__version__ = '.'.join(map(str, _ver))
+if _version_extra:
+ __version__ = __version__ + _version_extra
+
+version = __version__ # backwards compatibility name
+version_info = (_version_major, _version_minor, _version_patch, _version_extra)
+
+# Change this when incrementing the kernel protocol version
+kernel_protocol_version_info = (5, 0)
+kernel_protocol_version = "%i.%i" % kernel_protocol_version_info
+
+description = "IPython: Productive Interactive Computing"
+
+long_description = \
+"""
+IPython provides a rich toolkit to help you make the most out of using Python
+interactively. Its main components are:
+
+* A powerful interactive Python shell
+* A `Jupyter <http://jupyter.org/>`_ kernel to work with Python code in Jupyter
+ notebooks and other interactive frontends.
+
+The enhanced interactive Python shells have the following main features:
+
+* Comprehensive object introspection.
+
+* Input history, persistent across sessions.
+
+* Caching of output results during a session with automatically generated
+ references.
+
+* Extensible tab completion, with support by default for completion of python
+ variables and keywords, filenames and function keywords.
+
+* Extensible system of 'magic' commands for controlling the environment and
+ performing many tasks related either to IPython or the operating system.
+
+* A rich configuration system with easy switching between different setups
+ (simpler than changing $PYTHONSTARTUP environment variables every time).
+
+* Session logging and reloading.
+
+* Extensible syntax processing for special purpose situations.
+
+* Access to the system shell with user-extensible alias system.
+
+* Easily embeddable in other Python programs and GUIs.
+
+* Integrated access to the pdb debugger and the Python profiler.
+
+The latest development version is always available from IPython's `GitHub
+site <http://github.com/ipython>`_.
+"""
+
+license = 'BSD'
+
+authors = {'Fernando' : ('Fernando Perez','fperez.net@gmail.com'),
+ 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
+ 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
+ 'Ville' : ('Ville Vainio','vivainio@gmail.com'),
+ 'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'),
+ 'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com'),
+ 'Thomas' : ('Thomas A. Kluyver', 'takowl@gmail.com'),
+ 'Jorgen' : ('Jorgen Stenarson', 'jorgen.stenarson@bostream.nu'),
+ 'Matthias' : ('Matthias Bussonnier', 'bussonniermatthias@gmail.com'),
+ }
+
+author = 'The IPython Development Team'
+
author_email = 'ipython-dev@python.org'
-
+
url = 'https://ipython.org'
-
-
-platforms = ['Linux','Mac OSX','Windows']
-
-keywords = ['Interactive','Interpreter','Shell', 'Embedding']
-
-classifiers = [
- 'Framework :: IPython',
- 'Intended Audience :: Developers',
- 'Intended Audience :: Science/Research',
- 'License :: OSI Approved :: BSD License',
- 'Programming Language :: Python',
- 'Programming Language :: Python :: 2',
- 'Programming Language :: Python :: 2.7',
- 'Programming Language :: Python :: 3',
- 'Topic :: System :: Shells'
- ]
+
+
+platforms = ['Linux','Mac OSX','Windows']
+
+keywords = ['Interactive','Interpreter','Shell', 'Embedding']
+
+classifiers = [
+ 'Framework :: IPython',
+ 'Intended Audience :: Developers',
+ 'Intended Audience :: Science/Research',
+ 'License :: OSI Approved :: BSD License',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Topic :: System :: Shells'
+ ]
diff --git a/contrib/python/ipython/py2/IPython/core/shadowns.py b/contrib/python/ipython/py2/IPython/core/shadowns.py
index c9868ea569..d2d93b61bd 100644
--- a/contrib/python/ipython/py2/IPython/core/shadowns.py
+++ b/contrib/python/ipython/py2/IPython/core/shadowns.py
@@ -1 +1 @@
-""" Shadow namespace """ \ No newline at end of file
+""" Shadow namespace """ \ No newline at end of file
diff --git a/contrib/python/ipython/py2/IPython/core/shellapp.py b/contrib/python/ipython/py2/IPython/core/shellapp.py
index 18ef594527..213648246e 100644
--- a/contrib/python/ipython/py2/IPython/core/shellapp.py
+++ b/contrib/python/ipython/py2/IPython/core/shellapp.py
@@ -1,415 +1,415 @@
-# encoding: utf-8
-"""
-A mixin for :class:`~IPython.core.application.Application` classes that
-launch InteractiveShell instances, load extensions, etc.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import absolute_import
-from __future__ import print_function
-
-import glob
+# encoding: utf-8
+"""
+A mixin for :class:`~IPython.core.application.Application` classes that
+launch InteractiveShell instances, load extensions, etc.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import absolute_import
+from __future__ import print_function
+
+import glob
from itertools import chain
-import os
-import sys
-
-from traitlets.config.application import boolean_flag
-from traitlets.config.configurable import Configurable
-from traitlets.config.loader import Config
+import os
+import sys
+
+from traitlets.config.application import boolean_flag
+from traitlets.config.configurable import Configurable
+from traitlets.config.loader import Config
from IPython.core.application import SYSTEM_CONFIG_DIRS, ENV_CONFIG_DIRS
-from IPython.core import pylabtools
-from IPython.utils import py3compat
-from IPython.utils.contexts import preserve_keys
-from IPython.utils.path import filefind
-from traitlets import (
+from IPython.core import pylabtools
+from IPython.utils import py3compat
+from IPython.utils.contexts import preserve_keys
+from IPython.utils.path import filefind
+from traitlets import (
Unicode, Instance, List, Bool, CaselessStrEnum, observe,
-)
+)
from IPython.terminal import pt_inputhooks
-
-#-----------------------------------------------------------------------------
-# Aliases and Flags
-#-----------------------------------------------------------------------------
-
+
+#-----------------------------------------------------------------------------
+# Aliases and Flags
+#-----------------------------------------------------------------------------
+
gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases))
-
-backend_keys = sorted(pylabtools.backends.keys())
-backend_keys.insert(0, 'auto')
-
-shell_flags = {}
-
-addflag = lambda *args: shell_flags.update(boolean_flag(*args))
-addflag('autoindent', 'InteractiveShell.autoindent',
- 'Turn on autoindenting.', 'Turn off autoindenting.'
-)
-addflag('automagic', 'InteractiveShell.automagic',
- """Turn on the auto calling of magic commands. Type %%magic at the
- IPython prompt for more information.""",
- 'Turn off the auto calling of magic commands.'
-)
-addflag('pdb', 'InteractiveShell.pdb',
- "Enable auto calling the pdb debugger after every exception.",
- "Disable auto calling the pdb debugger after every exception."
-)
-addflag('pprint', 'PlainTextFormatter.pprint',
- "Enable auto pretty printing of results.",
- "Disable auto pretty printing of results."
-)
-addflag('color-info', 'InteractiveShell.color_info',
- """IPython can display information about objects via a set of functions,
- and optionally can use colors for this, syntax highlighting
- source code and various other elements. This is on by default, but can cause
- problems with some pagers. If you see such problems, you can disable the
- colours.""",
- "Disable using colors for info related things."
-)
-nosep_config = Config()
-nosep_config.InteractiveShell.separate_in = ''
-nosep_config.InteractiveShell.separate_out = ''
-nosep_config.InteractiveShell.separate_out2 = ''
-
-shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
-shell_flags['pylab'] = (
- {'InteractiveShellApp' : {'pylab' : 'auto'}},
- """Pre-load matplotlib and numpy for interactive use with
- the default matplotlib backend."""
-)
-shell_flags['matplotlib'] = (
- {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
- """Configure matplotlib for interactive use with
- the default matplotlib backend."""
-)
-
-# it's possible we don't want short aliases for *all* of these:
-shell_aliases = dict(
- autocall='InteractiveShell.autocall',
- colors='InteractiveShell.colors',
- logfile='InteractiveShell.logfile',
- logappend='InteractiveShell.logappend',
- c='InteractiveShellApp.code_to_run',
- m='InteractiveShellApp.module_to_run',
- ext='InteractiveShellApp.extra_extension',
- gui='InteractiveShellApp.gui',
- pylab='InteractiveShellApp.pylab',
- matplotlib='InteractiveShellApp.matplotlib',
-)
-shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
-
-#-----------------------------------------------------------------------------
-# Main classes and functions
-#-----------------------------------------------------------------------------
-
-class InteractiveShellApp(Configurable):
- """A Mixin for applications that start InteractiveShell instances.
-
- Provides configurables for loading extensions and executing files
- as part of configuring a Shell environment.
-
- The following methods should be called by the :meth:`initialize` method
- of the subclass:
-
- - :meth:`init_path`
- - :meth:`init_shell` (to be implemented by the subclass)
- - :meth:`init_gui_pylab`
- - :meth:`init_extensions`
- - :meth:`init_code`
- """
+
+backend_keys = sorted(pylabtools.backends.keys())
+backend_keys.insert(0, 'auto')
+
+shell_flags = {}
+
+addflag = lambda *args: shell_flags.update(boolean_flag(*args))
+addflag('autoindent', 'InteractiveShell.autoindent',
+ 'Turn on autoindenting.', 'Turn off autoindenting.'
+)
+addflag('automagic', 'InteractiveShell.automagic',
+ """Turn on the auto calling of magic commands. Type %%magic at the
+ IPython prompt for more information.""",
+ 'Turn off the auto calling of magic commands.'
+)
+addflag('pdb', 'InteractiveShell.pdb',
+ "Enable auto calling the pdb debugger after every exception.",
+ "Disable auto calling the pdb debugger after every exception."
+)
+addflag('pprint', 'PlainTextFormatter.pprint',
+ "Enable auto pretty printing of results.",
+ "Disable auto pretty printing of results."
+)
+addflag('color-info', 'InteractiveShell.color_info',
+ """IPython can display information about objects via a set of functions,
+ and optionally can use colors for this, syntax highlighting
+ source code and various other elements. This is on by default, but can cause
+ problems with some pagers. If you see such problems, you can disable the
+ colours.""",
+ "Disable using colors for info related things."
+)
+nosep_config = Config()
+nosep_config.InteractiveShell.separate_in = ''
+nosep_config.InteractiveShell.separate_out = ''
+nosep_config.InteractiveShell.separate_out2 = ''
+
+shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
+shell_flags['pylab'] = (
+ {'InteractiveShellApp' : {'pylab' : 'auto'}},
+ """Pre-load matplotlib and numpy for interactive use with
+ the default matplotlib backend."""
+)
+shell_flags['matplotlib'] = (
+ {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
+ """Configure matplotlib for interactive use with
+ the default matplotlib backend."""
+)
+
+# it's possible we don't want short aliases for *all* of these:
+shell_aliases = dict(
+ autocall='InteractiveShell.autocall',
+ colors='InteractiveShell.colors',
+ logfile='InteractiveShell.logfile',
+ logappend='InteractiveShell.logappend',
+ c='InteractiveShellApp.code_to_run',
+ m='InteractiveShellApp.module_to_run',
+ ext='InteractiveShellApp.extra_extension',
+ gui='InteractiveShellApp.gui',
+ pylab='InteractiveShellApp.pylab',
+ matplotlib='InteractiveShellApp.matplotlib',
+)
+shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
+
+#-----------------------------------------------------------------------------
+# Main classes and functions
+#-----------------------------------------------------------------------------
+
+class InteractiveShellApp(Configurable):
+ """A Mixin for applications that start InteractiveShell instances.
+
+ Provides configurables for loading extensions and executing files
+ as part of configuring a Shell environment.
+
+ The following methods should be called by the :meth:`initialize` method
+ of the subclass:
+
+ - :meth:`init_path`
+ - :meth:`init_shell` (to be implemented by the subclass)
+ - :meth:`init_gui_pylab`
+ - :meth:`init_extensions`
+ - :meth:`init_code`
+ """
extensions = List(Unicode(),
- help="A list of dotted module names of IPython extensions to load."
+ help="A list of dotted module names of IPython extensions to load."
).tag(config=True)
extra_extension = Unicode('',
- help="dotted module name of an IPython extension to load."
+ help="dotted module name of an IPython extension to load."
).tag(config=True)
-
+
reraise_ipython_extension_failures = Bool(False,
- help="Reraise exceptions encountered loading IPython extensions?",
+ help="Reraise exceptions encountered loading IPython extensions?",
).tag(config=True)
-
- # Extensions that are always loaded (not configurable)
+
+ # Extensions that are always loaded (not configurable)
default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
hide_initial_ns = Bool(True,
- help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
- be hidden from tools like %who?"""
+ help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
+ be hidden from tools like %who?"""
).tag(config=True)
-
+
exec_files = List(Unicode(),
- help="""List of files to run at IPython startup."""
+ help="""List of files to run at IPython startup."""
).tag(config=True)
exec_PYTHONSTARTUP = Bool(True,
- help="""Run the file referenced by the PYTHONSTARTUP environment
- variable at IPython startup."""
+ help="""Run the file referenced by the PYTHONSTARTUP environment
+ variable at IPython startup."""
).tag(config=True)
file_to_run = Unicode('',
help="""A file to be run""").tag(config=True)
-
+
exec_lines = List(Unicode(),
- help="""lines of code to run at IPython startup."""
+ help="""lines of code to run at IPython startup."""
).tag(config=True)
code_to_run = Unicode('',
- help="Execute the given command string."
+ help="Execute the given command string."
).tag(config=True)
module_to_run = Unicode('',
- help="Run the module as a script."
+ help="Run the module as a script."
).tag(config=True)
gui = CaselessStrEnum(gui_keys, allow_none=True,
- help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
+ help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
).tag(config=True)
- matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
- help="""Configure matplotlib for interactive use with
- the default matplotlib backend."""
+ matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
+ help="""Configure matplotlib for interactive use with
+ the default matplotlib backend."""
).tag(config=True)
- pylab = CaselessStrEnum(backend_keys, allow_none=True,
- help="""Pre-load matplotlib and numpy for interactive use,
- selecting a particular matplotlib backend and loop integration.
- """
+ pylab = CaselessStrEnum(backend_keys, allow_none=True,
+ help="""Pre-load matplotlib and numpy for interactive use,
+ selecting a particular matplotlib backend and loop integration.
+ """
).tag(config=True)
pylab_import_all = Bool(True,
- help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
- and an ``import *`` is done from numpy and pylab, when using pylab mode.
+ help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
+ and an ``import *`` is done from numpy and pylab, when using pylab mode.
- When False, pylab mode should not import any names into the user namespace.
- """
+ When False, pylab mode should not import any names into the user namespace.
+ """
).tag(config=True)
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
- allow_none=True)
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
+ allow_none=True)
# whether interact-loop should start
interact = Bool(True)
- user_ns = Instance(dict, args=None, allow_none=True)
+ user_ns = Instance(dict, args=None, allow_none=True)
@observe('user_ns')
def _user_ns_changed(self, change):
- if self.shell is not None:
+ if self.shell is not None:
self.shell.user_ns = change['new']
- self.shell.init_user_ns()
-
- def init_path(self):
- """Add current working directory, '', to sys.path"""
- if sys.path[0] != '':
- sys.path.insert(0, '')
-
- def init_shell(self):
- raise NotImplementedError("Override in subclasses")
-
- def init_gui_pylab(self):
- """Enable GUI event loop integration, taking pylab into account."""
- enable = False
- shell = self.shell
- if self.pylab:
- enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
- key = self.pylab
- elif self.matplotlib:
- enable = shell.enable_matplotlib
- key = self.matplotlib
- elif self.gui:
- enable = shell.enable_gui
- key = self.gui
-
- if not enable:
- return
-
- try:
- r = enable(key)
- except ImportError:
- self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
- self.shell.showtraceback()
- return
- except Exception:
- self.log.warning("GUI event loop or pylab initialization failed")
- self.shell.showtraceback()
- return
-
- if isinstance(r, tuple):
- gui, backend = r[:2]
- self.log.info("Enabling GUI event loop integration, "
- "eventloop=%s, matplotlib=%s", gui, backend)
- if key == "auto":
- print("Using matplotlib backend: %s" % backend)
- else:
- gui = r
- self.log.info("Enabling GUI event loop integration, "
- "eventloop=%s", gui)
-
- def init_extensions(self):
- """Load all IPython extensions in IPythonApp.extensions.
-
- This uses the :meth:`ExtensionManager.load_extensions` to load all
- the extensions listed in ``self.extensions``.
- """
- try:
- self.log.debug("Loading IPython extensions...")
- extensions = self.default_extensions + self.extensions
- if self.extra_extension:
- extensions.append(self.extra_extension)
- for ext in extensions:
- try:
- self.log.info("Loading IPython extension: %s" % ext)
- self.shell.extension_manager.load_extension(ext)
- except:
- if self.reraise_ipython_extension_failures:
- raise
- msg = ("Error in loading extension: {ext}\n"
- "Check your config files in {location}".format(
- ext=ext,
- location=self.profile_dir.location
- ))
- self.log.warning(msg, exc_info=True)
- except:
- if self.reraise_ipython_extension_failures:
- raise
- self.log.warning("Unknown error in loading extensions:", exc_info=True)
-
- def init_code(self):
- """run the pre-flight code, specified via exec_lines"""
- self._run_startup_files()
- self._run_exec_lines()
- self._run_exec_files()
-
- # Hide variables defined here from %who etc.
- if self.hide_initial_ns:
- self.shell.user_ns_hidden.update(self.shell.user_ns)
-
- # command-line execution (ipython -i script.py, ipython -m module)
- # should *not* be excluded from %whos
- self._run_cmd_line_code()
- self._run_module()
-
- # flush output, so itwon't be attached to the first cell
- sys.stdout.flush()
- sys.stderr.flush()
-
- def _run_exec_lines(self):
- """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
- if not self.exec_lines:
- return
- try:
- self.log.debug("Running code from IPythonApp.exec_lines...")
- for line in self.exec_lines:
- try:
- self.log.info("Running code in user namespace: %s" %
- line)
- self.shell.run_cell(line, store_history=False)
- except:
- self.log.warning("Error in executing line in user "
- "namespace: %s" % line)
- self.shell.showtraceback()
- except:
- self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
- self.shell.showtraceback()
-
- def _exec_file(self, fname, shell_futures=False):
- try:
- full_filename = filefind(fname, [u'.', self.ipython_dir])
+ self.shell.init_user_ns()
+
+ def init_path(self):
+ """Add current working directory, '', to sys.path"""
+ if sys.path[0] != '':
+ sys.path.insert(0, '')
+
+ def init_shell(self):
+ raise NotImplementedError("Override in subclasses")
+
+ def init_gui_pylab(self):
+ """Enable GUI event loop integration, taking pylab into account."""
+ enable = False
+ shell = self.shell
+ if self.pylab:
+ enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
+ key = self.pylab
+ elif self.matplotlib:
+ enable = shell.enable_matplotlib
+ key = self.matplotlib
+ elif self.gui:
+ enable = shell.enable_gui
+ key = self.gui
+
+ if not enable:
+ return
+
+ try:
+ r = enable(key)
+ except ImportError:
+ self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
+ self.shell.showtraceback()
+ return
+ except Exception:
+ self.log.warning("GUI event loop or pylab initialization failed")
+ self.shell.showtraceback()
+ return
+
+ if isinstance(r, tuple):
+ gui, backend = r[:2]
+ self.log.info("Enabling GUI event loop integration, "
+ "eventloop=%s, matplotlib=%s", gui, backend)
+ if key == "auto":
+ print("Using matplotlib backend: %s" % backend)
+ else:
+ gui = r
+ self.log.info("Enabling GUI event loop integration, "
+ "eventloop=%s", gui)
+
+ def init_extensions(self):
+ """Load all IPython extensions in IPythonApp.extensions.
+
+ This uses the :meth:`ExtensionManager.load_extensions` to load all
+ the extensions listed in ``self.extensions``.
+ """
+ try:
+ self.log.debug("Loading IPython extensions...")
+ extensions = self.default_extensions + self.extensions
+ if self.extra_extension:
+ extensions.append(self.extra_extension)
+ for ext in extensions:
+ try:
+ self.log.info("Loading IPython extension: %s" % ext)
+ self.shell.extension_manager.load_extension(ext)
+ except:
+ if self.reraise_ipython_extension_failures:
+ raise
+ msg = ("Error in loading extension: {ext}\n"
+ "Check your config files in {location}".format(
+ ext=ext,
+ location=self.profile_dir.location
+ ))
+ self.log.warning(msg, exc_info=True)
+ except:
+ if self.reraise_ipython_extension_failures:
+ raise
+ self.log.warning("Unknown error in loading extensions:", exc_info=True)
+
+ def init_code(self):
+ """run the pre-flight code, specified via exec_lines"""
+ self._run_startup_files()
+ self._run_exec_lines()
+ self._run_exec_files()
+
+ # Hide variables defined here from %who etc.
+ if self.hide_initial_ns:
+ self.shell.user_ns_hidden.update(self.shell.user_ns)
+
+ # command-line execution (ipython -i script.py, ipython -m module)
+ # should *not* be excluded from %whos
+ self._run_cmd_line_code()
+ self._run_module()
+
+ # flush output, so itwon't be attached to the first cell
+ sys.stdout.flush()
+ sys.stderr.flush()
+
+ def _run_exec_lines(self):
+ """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
+ if not self.exec_lines:
+ return
+ try:
+ self.log.debug("Running code from IPythonApp.exec_lines...")
+ for line in self.exec_lines:
+ try:
+ self.log.info("Running code in user namespace: %s" %
+ line)
+ self.shell.run_cell(line, store_history=False)
+ except:
+ self.log.warning("Error in executing line in user "
+ "namespace: %s" % line)
+ self.shell.showtraceback()
+ except:
+ self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
+ self.shell.showtraceback()
+
+ def _exec_file(self, fname, shell_futures=False):
+ try:
+ full_filename = filefind(fname, [u'.', self.ipython_dir])
except IOError:
- self.log.warning("File not found: %r"%fname)
- return
- # Make sure that the running script gets a proper sys.argv as if it
- # were run from a system shell.
- save_argv = sys.argv
- sys.argv = [full_filename] + self.extra_args[1:]
- # protect sys.argv from potential unicode strings on Python 2:
- if not py3compat.PY3:
- sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
- try:
- if os.path.isfile(full_filename):
- self.log.info("Running file in user namespace: %s" %
- full_filename)
- # Ensure that __file__ is always defined to match Python
- # behavior.
- with preserve_keys(self.shell.user_ns, '__file__'):
- self.shell.user_ns['__file__'] = fname
- if full_filename.endswith('.ipy'):
- self.shell.safe_execfile_ipy(full_filename,
- shell_futures=shell_futures)
- else:
- # default to python, even without extension
- self.shell.safe_execfile(full_filename,
- self.shell.user_ns,
- shell_futures=shell_futures,
- raise_exceptions=True)
- finally:
- sys.argv = save_argv
-
- def _run_startup_files(self):
- """Run files from profile startup directory"""
+ self.log.warning("File not found: %r"%fname)
+ return
+ # Make sure that the running script gets a proper sys.argv as if it
+ # were run from a system shell.
+ save_argv = sys.argv
+ sys.argv = [full_filename] + self.extra_args[1:]
+ # protect sys.argv from potential unicode strings on Python 2:
+ if not py3compat.PY3:
+ sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
+ try:
+ if os.path.isfile(full_filename):
+ self.log.info("Running file in user namespace: %s" %
+ full_filename)
+ # Ensure that __file__ is always defined to match Python
+ # behavior.
+ with preserve_keys(self.shell.user_ns, '__file__'):
+ self.shell.user_ns['__file__'] = fname
+ if full_filename.endswith('.ipy'):
+ self.shell.safe_execfile_ipy(full_filename,
+ shell_futures=shell_futures)
+ else:
+ # default to python, even without extension
+ self.shell.safe_execfile(full_filename,
+ self.shell.user_ns,
+ shell_futures=shell_futures,
+ raise_exceptions=True)
+ finally:
+ sys.argv = save_argv
+
+ def _run_startup_files(self):
+ """Run files from profile startup directory"""
startup_dirs = [self.profile_dir.startup_dir] + [
os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS)
]
- startup_files = []
-
- if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
- not (self.file_to_run or self.code_to_run or self.module_to_run):
- python_startup = os.environ['PYTHONSTARTUP']
- self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
- try:
- self._exec_file(python_startup)
- except:
- self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
- self.shell.showtraceback()
+ startup_files = []
+
+ if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
+ not (self.file_to_run or self.code_to_run or self.module_to_run):
+ python_startup = os.environ['PYTHONSTARTUP']
+ self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
+ try:
+ self._exec_file(python_startup)
+ except:
+ self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
+ self.shell.showtraceback()
for startup_dir in startup_dirs[::-1]:
startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
- if not startup_files:
- return
-
- self.log.debug("Running startup files from %s...", startup_dir)
- try:
- for fname in sorted(startup_files):
- self._exec_file(fname)
- except:
- self.log.warning("Unknown error in handling startup files:")
- self.shell.showtraceback()
-
- def _run_exec_files(self):
- """Run files from IPythonApp.exec_files"""
- if not self.exec_files:
- return
-
- self.log.debug("Running files in IPythonApp.exec_files...")
- try:
- for fname in self.exec_files:
- self._exec_file(fname)
- except:
- self.log.warning("Unknown error in handling IPythonApp.exec_files:")
- self.shell.showtraceback()
-
- def _run_cmd_line_code(self):
- """Run code or file specified at the command-line"""
- if self.code_to_run:
- line = self.code_to_run
- try:
- self.log.info("Running code given at command line (c=): %s" %
- line)
- self.shell.run_cell(line, store_history=False)
- except:
- self.log.warning("Error in executing line in user namespace: %s" %
- line)
- self.shell.showtraceback()
+ if not startup_files:
+ return
+
+ self.log.debug("Running startup files from %s...", startup_dir)
+ try:
+ for fname in sorted(startup_files):
+ self._exec_file(fname)
+ except:
+ self.log.warning("Unknown error in handling startup files:")
+ self.shell.showtraceback()
+
+ def _run_exec_files(self):
+ """Run files from IPythonApp.exec_files"""
+ if not self.exec_files:
+ return
+
+ self.log.debug("Running files in IPythonApp.exec_files...")
+ try:
+ for fname in self.exec_files:
+ self._exec_file(fname)
+ except:
+ self.log.warning("Unknown error in handling IPythonApp.exec_files:")
+ self.shell.showtraceback()
+
+ def _run_cmd_line_code(self):
+ """Run code or file specified at the command-line"""
+ if self.code_to_run:
+ line = self.code_to_run
+ try:
+ self.log.info("Running code given at command line (c=): %s" %
+ line)
+ self.shell.run_cell(line, store_history=False)
+ except:
+ self.log.warning("Error in executing line in user namespace: %s" %
+ line)
+ self.shell.showtraceback()
if not self.interact:
self.exit(1)
-
- # Like Python itself, ignore the second if the first of these is present
- elif self.file_to_run:
- fname = self.file_to_run
+
+ # Like Python itself, ignore the second if the first of these is present
+ elif self.file_to_run:
+ fname = self.file_to_run
if os.path.isdir(fname):
fname = os.path.join(fname, "__main__.py")
- try:
- self._exec_file(fname, shell_futures=True)
- except:
- self.shell.showtraceback(tb_offset=4)
+ try:
+ self._exec_file(fname, shell_futures=True)
+ except:
+ self.shell.showtraceback(tb_offset=4)
if not self.interact:
self.exit(1)
-
- def _run_module(self):
- """Run module specified at the command-line."""
- if self.module_to_run:
- # Make sure that the module gets a proper sys.argv as if it were
- # run using `python -m`.
- save_argv = sys.argv
- sys.argv = [sys.executable] + self.extra_args
- try:
- self.shell.safe_run_module(self.module_to_run,
- self.shell.user_ns)
- finally:
- sys.argv = save_argv
+
+ def _run_module(self):
+ """Run module specified at the command-line."""
+ if self.module_to_run:
+ # Make sure that the module gets a proper sys.argv as if it were
+ # run using `python -m`.
+ save_argv = sys.argv
+ sys.argv = [sys.executable] + self.extra_args
+ try:
+ self.shell.safe_run_module(self.module_to_run,
+ self.shell.user_ns)
+ finally:
+ sys.argv = save_argv
diff --git a/contrib/python/ipython/py2/IPython/core/splitinput.py b/contrib/python/ipython/py2/IPython/core/splitinput.py
index 2c54687cb1..7b957726fb 100644
--- a/contrib/python/ipython/py2/IPython/core/splitinput.py
+++ b/contrib/python/ipython/py2/IPython/core/splitinput.py
@@ -1,137 +1,137 @@
-# encoding: utf-8
-"""
-Simple utility for splitting user input. This is used by both inputsplitter and
-prefilter.
-
-Authors:
-
-* Brian Granger
-* Fernando Perez
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import re
-import sys
-
-from IPython.utils import py3compat
-from IPython.utils.encoding import get_stream_enc
-
-#-----------------------------------------------------------------------------
-# Main function
-#-----------------------------------------------------------------------------
-
-# RegExp for splitting line contents into pre-char//first word-method//rest.
-# For clarity, each group in on one line.
-
-# WARNING: update the regexp if the escapes in interactiveshell are changed, as
-# they are hardwired in.
-
-# Although it's not solely driven by the regex, note that:
-# ,;/% only trigger if they are the first character on the line
-# ! and !! trigger if they are first char(s) *or* follow an indent
-# ? triggers as first or last char.
-
-line_split = re.compile("""
- ^(\s*) # any leading space
- ([,;/%]|!!?|\?\??)? # escape character or characters
- \s*(%{0,2}[\w\.\*]*) # function/method, possibly with leading %
- # to correctly treat things like '?%magic'
- (.*?$|$) # rest of line
- """, re.VERBOSE)
-
-
-def split_user_input(line, pattern=None):
- """Split user input into initial whitespace, escape character, function part
- and the rest.
- """
- # We need to ensure that the rest of this routine deals only with unicode
- encoding = get_stream_enc(sys.stdin, 'utf-8')
- line = py3compat.cast_unicode(line, encoding)
-
- if pattern is None:
- pattern = line_split
- match = pattern.match(line)
- if not match:
- # print "match failed for line '%s'" % line
- try:
- ifun, the_rest = line.split(None,1)
- except ValueError:
- # print "split failed for line '%s'" % line
- ifun, the_rest = line, u''
- pre = re.match('^(\s*)(.*)',line).groups()[0]
- esc = ""
- else:
- pre, esc, ifun, the_rest = match.groups()
-
- #print 'line:<%s>' % line # dbg
- #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun.strip(),the_rest) # dbg
- return pre, esc or '', ifun.strip(), the_rest.lstrip()
-
-
-class LineInfo(object):
- """A single line of input and associated info.
-
- Includes the following as properties:
-
- line
- The original, raw line
-
- continue_prompt
- Is this line a continuation in a sequence of multiline input?
-
- pre
- Any leading whitespace.
-
- esc
- The escape character(s) in pre or the empty string if there isn't one.
- Note that '!!' and '??' are possible values for esc. Otherwise it will
- always be a single character.
-
- ifun
- The 'function part', which is basically the maximal initial sequence
- of valid python identifiers and the '.' character. This is what is
- checked for alias and magic transformations, used for auto-calling,
- etc. In contrast to Python identifiers, it may start with "%" and contain
- "*".
-
- the_rest
- Everything else on the line.
- """
- def __init__(self, line, continue_prompt=False):
- self.line = line
- self.continue_prompt = continue_prompt
- self.pre, self.esc, self.ifun, self.the_rest = split_user_input(line)
-
- self.pre_char = self.pre.strip()
- if self.pre_char:
- self.pre_whitespace = '' # No whitespace allowd before esc chars
- else:
- self.pre_whitespace = self.pre
-
- def ofind(self, ip):
- """Do a full, attribute-walking lookup of the ifun in the various
- namespaces for the given IPython InteractiveShell instance.
-
- Return a dict with keys: {found, obj, ospace, ismagic}
-
- Note: can cause state changes because of calling getattr, but should
- only be run if autocall is on and if the line hasn't matched any
- other, less dangerous handlers.
-
- Does cache the results of the call, so can be called multiple times
- without worrying about *further* damaging state.
- """
- return ip._ofind(self.ifun)
-
- def __str__(self):
- return "LineInfo [%s|%s|%s|%s]" %(self.pre, self.esc, self.ifun, self.the_rest)
+# encoding: utf-8
+"""
+Simple utility for splitting user input. This is used by both inputsplitter and
+prefilter.
+
+Authors:
+
+* Brian Granger
+* Fernando Perez
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import re
+import sys
+
+from IPython.utils import py3compat
+from IPython.utils.encoding import get_stream_enc
+
+#-----------------------------------------------------------------------------
+# Main function
+#-----------------------------------------------------------------------------
+
+# RegExp for splitting line contents into pre-char//first word-method//rest.
+# For clarity, each group in on one line.
+
+# WARNING: update the regexp if the escapes in interactiveshell are changed, as
+# they are hardwired in.
+
+# Although it's not solely driven by the regex, note that:
+# ,;/% only trigger if they are the first character on the line
+# ! and !! trigger if they are first char(s) *or* follow an indent
+# ? triggers as first or last char.
+
+line_split = re.compile("""
+ ^(\s*) # any leading space
+ ([,;/%]|!!?|\?\??)? # escape character or characters
+ \s*(%{0,2}[\w\.\*]*) # function/method, possibly with leading %
+ # to correctly treat things like '?%magic'
+ (.*?$|$) # rest of line
+ """, re.VERBOSE)
+
+
+def split_user_input(line, pattern=None):
+ """Split user input into initial whitespace, escape character, function part
+ and the rest.
+ """
+ # We need to ensure that the rest of this routine deals only with unicode
+ encoding = get_stream_enc(sys.stdin, 'utf-8')
+ line = py3compat.cast_unicode(line, encoding)
+
+ if pattern is None:
+ pattern = line_split
+ match = pattern.match(line)
+ if not match:
+ # print "match failed for line '%s'" % line
+ try:
+ ifun, the_rest = line.split(None,1)
+ except ValueError:
+ # print "split failed for line '%s'" % line
+ ifun, the_rest = line, u''
+ pre = re.match('^(\s*)(.*)',line).groups()[0]
+ esc = ""
+ else:
+ pre, esc, ifun, the_rest = match.groups()
+
+ #print 'line:<%s>' % line # dbg
+ #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun.strip(),the_rest) # dbg
+ return pre, esc or '', ifun.strip(), the_rest.lstrip()
+
+
+class LineInfo(object):
+ """A single line of input and associated info.
+
+ Includes the following as properties:
+
+ line
+ The original, raw line
+
+ continue_prompt
+ Is this line a continuation in a sequence of multiline input?
+
+ pre
+ Any leading whitespace.
+
+ esc
+ The escape character(s) in pre or the empty string if there isn't one.
+ Note that '!!' and '??' are possible values for esc. Otherwise it will
+ always be a single character.
+
+ ifun
+ The 'function part', which is basically the maximal initial sequence
+ of valid python identifiers and the '.' character. This is what is
+ checked for alias and magic transformations, used for auto-calling,
+ etc. In contrast to Python identifiers, it may start with "%" and contain
+ "*".
+
+ the_rest
+ Everything else on the line.
+ """
+ def __init__(self, line, continue_prompt=False):
+ self.line = line
+ self.continue_prompt = continue_prompt
+ self.pre, self.esc, self.ifun, self.the_rest = split_user_input(line)
+
+ self.pre_char = self.pre.strip()
+ if self.pre_char:
+ self.pre_whitespace = '' # No whitespace allowd before esc chars
+ else:
+ self.pre_whitespace = self.pre
+
+ def ofind(self, ip):
+ """Do a full, attribute-walking lookup of the ifun in the various
+ namespaces for the given IPython InteractiveShell instance.
+
+ Return a dict with keys: {found, obj, ospace, ismagic}
+
+ Note: can cause state changes because of calling getattr, but should
+ only be run if autocall is on and if the line hasn't matched any
+ other, less dangerous handlers.
+
+ Does cache the results of the call, so can be called multiple times
+ without worrying about *further* damaging state.
+ """
+ return ip._ofind(self.ifun)
+
+ def __str__(self):
+ return "LineInfo [%s|%s|%s|%s]" %(self.pre, self.esc, self.ifun, self.the_rest)
diff --git a/contrib/python/ipython/py2/IPython/core/ultratb.py b/contrib/python/ipython/py2/IPython/core/ultratb.py
index 4fc1e9574b..a855145825 100644
--- a/contrib/python/ipython/py2/IPython/core/ultratb.py
+++ b/contrib/python/ipython/py2/IPython/core/ultratb.py
@@ -1,1499 +1,1499 @@
-# -*- coding: utf-8 -*-
-"""
-Verbose and colourful traceback formatting.
-
-**ColorTB**
-
-I've always found it a bit hard to visually parse tracebacks in Python. The
-ColorTB class is a solution to that problem. It colors the different parts of a
-traceback in a manner similar to what you would expect from a syntax-highlighting
-text editor.
-
-Installation instructions for ColorTB::
-
- import sys,ultratb
- sys.excepthook = ultratb.ColorTB()
-
-**VerboseTB**
-
-I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
-of useful info when a traceback occurs. Ping originally had it spit out HTML
-and intended it for CGI programmers, but why should they have all the fun? I
-altered it to spit out colored text to the terminal. It's a bit overwhelming,
-but kind of neat, and maybe useful for long-running programs that you believe
-are bug-free. If a crash *does* occur in that type of program you want details.
-Give it a shot--you'll love it or you'll hate it.
-
-.. note::
-
- The Verbose mode prints the variables currently visible where the exception
- happened (shortening their strings if too long). This can potentially be
- very slow, if you happen to have a huge data structure whose string
- representation is complex to compute. Your computer may appear to freeze for
- a while with cpu usage at 100%. If this occurs, you can cancel the traceback
- with Ctrl-C (maybe hitting it more than once).
-
- If you encounter this kind of situation often, you may want to use the
- Verbose_novars mode instead of the regular Verbose, which avoids formatting
- variables (but otherwise includes the information and context given by
- Verbose).
-
+# -*- coding: utf-8 -*-
+"""
+Verbose and colourful traceback formatting.
+
+**ColorTB**
+
+I've always found it a bit hard to visually parse tracebacks in Python. The
+ColorTB class is a solution to that problem. It colors the different parts of a
+traceback in a manner similar to what you would expect from a syntax-highlighting
+text editor.
+
+Installation instructions for ColorTB::
+
+ import sys,ultratb
+ sys.excepthook = ultratb.ColorTB()
+
+**VerboseTB**
+
+I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
+of useful info when a traceback occurs. Ping originally had it spit out HTML
+and intended it for CGI programmers, but why should they have all the fun? I
+altered it to spit out colored text to the terminal. It's a bit overwhelming,
+but kind of neat, and maybe useful for long-running programs that you believe
+are bug-free. If a crash *does* occur in that type of program you want details.
+Give it a shot--you'll love it or you'll hate it.
+
+.. note::
+
+ The Verbose mode prints the variables currently visible where the exception
+ happened (shortening their strings if too long). This can potentially be
+ very slow, if you happen to have a huge data structure whose string
+ representation is complex to compute. Your computer may appear to freeze for
+ a while with cpu usage at 100%. If this occurs, you can cancel the traceback
+ with Ctrl-C (maybe hitting it more than once).
+
+ If you encounter this kind of situation often, you may want to use the
+ Verbose_novars mode instead of the regular Verbose, which avoids formatting
+ variables (but otherwise includes the information and context given by
+ Verbose).
+
.. note::
-
+
The verbose mode print all variables in the stack, which means it can
potentially leak sensitive information like access keys, or unencryted
password.
-Installation instructions for VerboseTB::
-
- import sys,ultratb
- sys.excepthook = ultratb.VerboseTB()
-
-Note: Much of the code in this module was lifted verbatim from the standard
-library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
-
-Color schemes
--------------
-
-The colors are defined in the class TBTools through the use of the
-ColorSchemeTable class. Currently the following exist:
-
- - NoColor: allows all of this module to be used in any terminal (the color
- escapes are just dummy blank strings).
-
- - Linux: is meant to look good in a terminal like the Linux console (black
- or very dark background).
-
- - LightBG: similar to Linux but swaps dark/light colors to be more readable
- in light background terminals.
-
+Installation instructions for VerboseTB::
+
+ import sys,ultratb
+ sys.excepthook = ultratb.VerboseTB()
+
+Note: Much of the code in this module was lifted verbatim from the standard
+library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
+
+Color schemes
+-------------
+
+The colors are defined in the class TBTools through the use of the
+ColorSchemeTable class. Currently the following exist:
+
+ - NoColor: allows all of this module to be used in any terminal (the color
+ escapes are just dummy blank strings).
+
+ - Linux: is meant to look good in a terminal like the Linux console (black
+ or very dark background).
+
+ - LightBG: similar to Linux but swaps dark/light colors to be more readable
+ in light background terminals.
+
- Neutral: a neutral color scheme that should be readable on both light and
dark background
-You can implement other color schemes easily, the syntax is fairly
-self-explanatory. Please send back new schemes you develop to the author for
-possible inclusion in future releases.
-
-Inheritance diagram:
-
-.. inheritance-diagram:: IPython.core.ultratb
- :parts: 3
-"""
-
-#*****************************************************************************
-# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
-# Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#*****************************************************************************
-
+You can implement other color schemes easily, the syntax is fairly
+self-explanatory. Please send back new schemes you develop to the author for
+possible inclusion in future releases.
+
+Inheritance diagram:
+
+.. inheritance-diagram:: IPython.core.ultratb
+ :parts: 3
+"""
+
+#*****************************************************************************
+# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
+# Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#*****************************************************************************
+
from __future__ import absolute_import
-from __future__ import unicode_literals
-from __future__ import print_function
-
-import dis
-import inspect
-import keyword
-import linecache
-import os
-import pydoc
-import re
-import sys
-import time
-import tokenize
-import traceback
-import types
-
-try: # Python 2
- generate_tokens = tokenize.generate_tokens
-except AttributeError: # Python 3
- generate_tokens = tokenize.tokenize
-
-# For purposes of monkeypatching inspect to fix a bug in it.
-from inspect import getsourcefile, getfile, getmodule, \
- ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
-
-# IPython's own modules
-from IPython import get_ipython
-from IPython.core import debugger
-from IPython.core.display_trap import DisplayTrap
-from IPython.core.excolors import exception_colors
-from IPython.utils import PyColorize
-from IPython.utils import openpy
-from IPython.utils import path as util_path
-from IPython.utils import py3compat
-from IPython.utils import ulinecache
-from IPython.utils.data import uniq_stable
+from __future__ import unicode_literals
+from __future__ import print_function
+
+import dis
+import inspect
+import keyword
+import linecache
+import os
+import pydoc
+import re
+import sys
+import time
+import tokenize
+import traceback
+import types
+
+try: # Python 2
+ generate_tokens = tokenize.generate_tokens
+except AttributeError: # Python 3
+ generate_tokens = tokenize.tokenize
+
+# For purposes of monkeypatching inspect to fix a bug in it.
+from inspect import getsourcefile, getfile, getmodule, \
+ ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
+
+# IPython's own modules
+from IPython import get_ipython
+from IPython.core import debugger
+from IPython.core.display_trap import DisplayTrap
+from IPython.core.excolors import exception_colors
+from IPython.utils import PyColorize
+from IPython.utils import openpy
+from IPython.utils import path as util_path
+from IPython.utils import py3compat
+from IPython.utils import ulinecache
+from IPython.utils.data import uniq_stable
from IPython.utils.terminal import get_terminal_size
from logging import info, error
-
+
import IPython.utils.colorable as colorable
-# Globals
-# amount of space to put line numbers before verbose tracebacks
-INDENT_SIZE = 8
-
-# Default color scheme. This is used, for example, by the traceback
-# formatter. When running in an actual IPython instance, the user's rc.colors
-# value is used, but having a module global makes this functionality available
-# to users of ultratb who are NOT running inside ipython.
-DEFAULT_SCHEME = 'NoColor'
-
-# ---------------------------------------------------------------------------
-# Code begins
-
-# Utility functions
-def inspect_error():
- """Print a message about internal inspect errors.
-
- These are unfortunately quite common."""
-
- error('Internal Python error in the inspect module.\n'
- 'Below is the traceback from this internal error.\n')
-
-
-# This function is a monkeypatch we apply to the Python inspect module. We have
-# now found when it's needed (see discussion on issue gh-1456), and we have a
-# test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
-# the monkeypatch is not applied. TK, Aug 2012.
-def findsource(object):
- """Return the entire source file and starting line number for an object.
-
- The argument may be a module, class, method, function, traceback, frame,
- or code object. The source code is returned as a list of all the lines
- in the file and the line number indexes a line in that list. An IOError
- is raised if the source code cannot be retrieved.
-
- FIXED version with which we monkeypatch the stdlib to work around a bug."""
-
- file = getsourcefile(object) or getfile(object)
- # If the object is a frame, then trying to get the globals dict from its
- # module won't work. Instead, the frame object itself has the globals
- # dictionary.
- globals_dict = None
- if inspect.isframe(object):
- # XXX: can this ever be false?
- globals_dict = object.f_globals
- else:
- module = getmodule(object, file)
- if module:
- globals_dict = module.__dict__
- lines = linecache.getlines(file, globals_dict)
- if not lines:
- raise IOError('could not get source code')
-
- if ismodule(object):
- return lines, 0
-
- if isclass(object):
- name = object.__name__
- pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
- # make some effort to find the best matching class definition:
- # use the one with the least indentation, which is the one
- # that's most probably not inside a function definition.
- candidates = []
- for i in range(len(lines)):
- match = pat.match(lines[i])
- if match:
- # if it's at toplevel, it's already the best one
- if lines[i][0] == 'c':
- return lines, i
- # else add whitespace to candidate list
- candidates.append((match.group(1), i))
- if candidates:
- # this will sort by whitespace, and by line number,
- # less whitespace first
- candidates.sort()
- return lines, candidates[0][1]
- else:
- raise IOError('could not find class definition')
-
- if ismethod(object):
- object = object.__func__
- if isfunction(object):
- object = object.__code__
- if istraceback(object):
- object = object.tb_frame
- if isframe(object):
- object = object.f_code
- if iscode(object):
- if not hasattr(object, 'co_firstlineno'):
- raise IOError('could not find function definition')
- pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
- pmatch = pat.match
- # fperez - fix: sometimes, co_firstlineno can give a number larger than
- # the length of lines, which causes an error. Safeguard against that.
- lnum = min(object.co_firstlineno, len(lines)) - 1
- while lnum > 0:
+# Globals
+# amount of space to put line numbers before verbose tracebacks
+INDENT_SIZE = 8
+
+# Default color scheme. This is used, for example, by the traceback
+# formatter. When running in an actual IPython instance, the user's rc.colors
+# value is used, but having a module global makes this functionality available
+# to users of ultratb who are NOT running inside ipython.
+DEFAULT_SCHEME = 'NoColor'
+
+# ---------------------------------------------------------------------------
+# Code begins
+
+# Utility functions
+def inspect_error():
+ """Print a message about internal inspect errors.
+
+ These are unfortunately quite common."""
+
+ error('Internal Python error in the inspect module.\n'
+ 'Below is the traceback from this internal error.\n')
+
+
+# This function is a monkeypatch we apply to the Python inspect module. We have
+# now found when it's needed (see discussion on issue gh-1456), and we have a
+# test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
+# the monkeypatch is not applied. TK, Aug 2012.
+def findsource(object):
+ """Return the entire source file and starting line number for an object.
+
+ The argument may be a module, class, method, function, traceback, frame,
+ or code object. The source code is returned as a list of all the lines
+ in the file and the line number indexes a line in that list. An IOError
+ is raised if the source code cannot be retrieved.
+
+ FIXED version with which we monkeypatch the stdlib to work around a bug."""
+
+ file = getsourcefile(object) or getfile(object)
+ # If the object is a frame, then trying to get the globals dict from its
+ # module won't work. Instead, the frame object itself has the globals
+ # dictionary.
+ globals_dict = None
+ if inspect.isframe(object):
+ # XXX: can this ever be false?
+ globals_dict = object.f_globals
+ else:
+ module = getmodule(object, file)
+ if module:
+ globals_dict = module.__dict__
+ lines = linecache.getlines(file, globals_dict)
+ if not lines:
+ raise IOError('could not get source code')
+
+ if ismodule(object):
+ return lines, 0
+
+ if isclass(object):
+ name = object.__name__
+ pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
+ # make some effort to find the best matching class definition:
+ # use the one with the least indentation, which is the one
+ # that's most probably not inside a function definition.
+ candidates = []
+ for i in range(len(lines)):
+ match = pat.match(lines[i])
+ if match:
+ # if it's at toplevel, it's already the best one
+ if lines[i][0] == 'c':
+ return lines, i
+ # else add whitespace to candidate list
+ candidates.append((match.group(1), i))
+ if candidates:
+ # this will sort by whitespace, and by line number,
+ # less whitespace first
+ candidates.sort()
+ return lines, candidates[0][1]
+ else:
+ raise IOError('could not find class definition')
+
+ if ismethod(object):
+ object = object.__func__
+ if isfunction(object):
+ object = object.__code__
+ if istraceback(object):
+ object = object.tb_frame
+ if isframe(object):
+ object = object.f_code
+ if iscode(object):
+ if not hasattr(object, 'co_firstlineno'):
+ raise IOError('could not find function definition')
+ pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
+ pmatch = pat.match
+ # fperez - fix: sometimes, co_firstlineno can give a number larger than
+ # the length of lines, which causes an error. Safeguard against that.
+ lnum = min(object.co_firstlineno, len(lines)) - 1
+ while lnum > 0:
if pmatch(lines[lnum]):
break
- lnum -= 1
-
- return lines, lnum
- raise IOError('could not find code object')
-
-
-# This is a patched version of inspect.getargs that applies the (unmerged)
-# patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
-# https://github.com/ipython/ipython/issues/8205 and
-# https://github.com/ipython/ipython/issues/8293
-def getargs(co):
- """Get information about the arguments accepted by a code object.
-
- Three things are returned: (args, varargs, varkw), where 'args' is
- a list of argument names (possibly containing nested lists), and
- 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
- if not iscode(co):
- raise TypeError('{!r} is not a code object'.format(co))
-
- nargs = co.co_argcount
- names = co.co_varnames
- args = list(names[:nargs])
- step = 0
-
- # The following acrobatics are for anonymous (tuple) arguments.
- for i in range(nargs):
- if args[i][:1] in ('', '.'):
- stack, remain, count = [], [], []
- while step < len(co.co_code):
- op = ord(co.co_code[step])
- step = step + 1
- if op >= dis.HAVE_ARGUMENT:
- opname = dis.opname[op]
- value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
- step = step + 2
- if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
- remain.append(value)
- count.append(value)
- elif opname in ('STORE_FAST', 'STORE_DEREF'):
- if op in dis.haslocal:
- stack.append(co.co_varnames[value])
- elif op in dis.hasfree:
- stack.append((co.co_cellvars + co.co_freevars)[value])
- # Special case for sublists of length 1: def foo((bar))
- # doesn't generate the UNPACK_TUPLE bytecode, so if
- # `remain` is empty here, we have such a sublist.
- if not remain:
- stack[0] = [stack[0]]
- break
- else:
- remain[-1] = remain[-1] - 1
- while remain[-1] == 0:
- remain.pop()
- size = count.pop()
- stack[-size:] = [stack[-size:]]
+ lnum -= 1
+
+ return lines, lnum
+ raise IOError('could not find code object')
+
+
+# This is a patched version of inspect.getargs that applies the (unmerged)
+# patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
+# https://github.com/ipython/ipython/issues/8205 and
+# https://github.com/ipython/ipython/issues/8293
+def getargs(co):
+ """Get information about the arguments accepted by a code object.
+
+ Three things are returned: (args, varargs, varkw), where 'args' is
+ a list of argument names (possibly containing nested lists), and
+ 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
+ if not iscode(co):
+ raise TypeError('{!r} is not a code object'.format(co))
+
+ nargs = co.co_argcount
+ names = co.co_varnames
+ args = list(names[:nargs])
+ step = 0
+
+ # The following acrobatics are for anonymous (tuple) arguments.
+ for i in range(nargs):
+ if args[i][:1] in ('', '.'):
+ stack, remain, count = [], [], []
+ while step < len(co.co_code):
+ op = ord(co.co_code[step])
+ step = step + 1
+ if op >= dis.HAVE_ARGUMENT:
+ opname = dis.opname[op]
+ value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
+ step = step + 2
+ if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
+ remain.append(value)
+ count.append(value)
+ elif opname in ('STORE_FAST', 'STORE_DEREF'):
+ if op in dis.haslocal:
+ stack.append(co.co_varnames[value])
+ elif op in dis.hasfree:
+ stack.append((co.co_cellvars + co.co_freevars)[value])
+ # Special case for sublists of length 1: def foo((bar))
+ # doesn't generate the UNPACK_TUPLE bytecode, so if
+ # `remain` is empty here, we have such a sublist.
+ if not remain:
+ stack[0] = [stack[0]]
+ break
+ else:
+ remain[-1] = remain[-1] - 1
+ while remain[-1] == 0:
+ remain.pop()
+ size = count.pop()
+ stack[-size:] = [stack[-size:]]
if not remain:
break
- remain[-1] = remain[-1] - 1
+ remain[-1] = remain[-1] - 1
if not remain:
break
- args[i] = stack[0]
-
- varargs = None
- if co.co_flags & inspect.CO_VARARGS:
- varargs = co.co_varnames[nargs]
- nargs = nargs + 1
- varkw = None
- if co.co_flags & inspect.CO_VARKEYWORDS:
- varkw = co.co_varnames[nargs]
- return inspect.Arguments(args, varargs, varkw)
-
-
-# Monkeypatch inspect to apply our bugfix.
-def with_patch_inspect(f):
- """decorator for monkeypatching inspect.findsource"""
-
- def wrapped(*args, **kwargs):
- save_findsource = inspect.findsource
- save_getargs = inspect.getargs
- inspect.findsource = findsource
- inspect.getargs = getargs
- try:
- return f(*args, **kwargs)
- finally:
- inspect.findsource = save_findsource
- inspect.getargs = save_getargs
-
- return wrapped
-
-
-if py3compat.PY3:
- fixed_getargvalues = inspect.getargvalues
-else:
- # Fixes for https://github.com/ipython/ipython/issues/8293
- # and https://github.com/ipython/ipython/issues/8205.
- # The relevant bug is caused by failure to correctly handle anonymous tuple
- # unpacking, which only exists in Python 2.
- fixed_getargvalues = with_patch_inspect(inspect.getargvalues)
-
-
-def fix_frame_records_filenames(records):
- """Try to fix the filenames in each record from inspect.getinnerframes().
-
- Particularly, modules loaded from within zip files have useless filenames
- attached to their code object, and inspect.getinnerframes() just uses it.
- """
- fixed_records = []
- for frame, filename, line_no, func_name, lines, index in records:
- # Look inside the frame's globals dictionary for __file__,
- # which should be better. However, keep Cython filenames since
- # we prefer the source filenames over the compiled .so file.
- filename = py3compat.cast_unicode_py2(filename, "utf-8")
- if not filename.endswith(('.pyx', '.pxd', '.pxi')):
- better_fn = frame.f_globals.get('__file__', None)
- if isinstance(better_fn, str):
- # Check the type just in case someone did something weird with
- # __file__. It might also be None if the error occurred during
- # import.
- filename = better_fn
- fixed_records.append((frame, filename, line_no, func_name, lines, index))
- return fixed_records
-
-
-@with_patch_inspect
-def _fixed_getinnerframes(etb, context=1, tb_offset=0):
- LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
-
- records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
- # If the error is at the console, don't build any context, since it would
- # otherwise produce 5 blank lines printed out (there is no file at the
- # console)
- rec_check = records[tb_offset:]
- try:
- rname = rec_check[0][1]
- if rname == '<ipython console>' or rname.endswith('<string>'):
- return rec_check
- except IndexError:
- pass
-
- aux = traceback.extract_tb(etb)
- assert len(records) == len(aux)
- for i, (file, lnum, _, _) in zip(range(len(records)), aux):
- maybeStart = lnum - 1 - context // 2
- start = max(maybeStart, 0)
- end = start + context
- lines = ulinecache.getlines(file)[start:end]
- buf = list(records[i])
- buf[LNUM_POS] = lnum
- buf[INDEX_POS] = lnum - 1 - start
- buf[LINES_POS] = lines
- records[i] = tuple(buf)
- return records[tb_offset:]
-
-# Helper function -- largely belongs to VerboseTB, but we need the same
-# functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
-# can be recognized properly by ipython.el's py-traceback-line-re
-# (SyntaxErrors have to be treated specially because they have no traceback)
-
-_parser = PyColorize.Parser()
-
-
-def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None):
- numbers_width = INDENT_SIZE - 1
- res = []
- i = lnum - index
-
- # This lets us get fully syntax-highlighted tracebacks.
- if scheme is None:
- ipinst = get_ipython()
- if ipinst is not None:
- scheme = ipinst.colors
- else:
- scheme = DEFAULT_SCHEME
-
- _line_format = _parser.format2
-
- for line in lines:
- line = py3compat.cast_unicode(line)
-
- new_line, err = _line_format(line, 'str', scheme)
- if not err: line = new_line
-
- if i == lnum:
- # This is the line with the error
- pad = numbers_width - len(str(i))
+ args[i] = stack[0]
+
+ varargs = None
+ if co.co_flags & inspect.CO_VARARGS:
+ varargs = co.co_varnames[nargs]
+ nargs = nargs + 1
+ varkw = None
+ if co.co_flags & inspect.CO_VARKEYWORDS:
+ varkw = co.co_varnames[nargs]
+ return inspect.Arguments(args, varargs, varkw)
+
+
+# Monkeypatch inspect to apply our bugfix.
+def with_patch_inspect(f):
+ """decorator for monkeypatching inspect.findsource"""
+
+ def wrapped(*args, **kwargs):
+ save_findsource = inspect.findsource
+ save_getargs = inspect.getargs
+ inspect.findsource = findsource
+ inspect.getargs = getargs
+ try:
+ return f(*args, **kwargs)
+ finally:
+ inspect.findsource = save_findsource
+ inspect.getargs = save_getargs
+
+ return wrapped
+
+
+if py3compat.PY3:
+ fixed_getargvalues = inspect.getargvalues
+else:
+ # Fixes for https://github.com/ipython/ipython/issues/8293
+ # and https://github.com/ipython/ipython/issues/8205.
+ # The relevant bug is caused by failure to correctly handle anonymous tuple
+ # unpacking, which only exists in Python 2.
+ fixed_getargvalues = with_patch_inspect(inspect.getargvalues)
+
+
+def fix_frame_records_filenames(records):
+ """Try to fix the filenames in each record from inspect.getinnerframes().
+
+ Particularly, modules loaded from within zip files have useless filenames
+ attached to their code object, and inspect.getinnerframes() just uses it.
+ """
+ fixed_records = []
+ for frame, filename, line_no, func_name, lines, index in records:
+ # Look inside the frame's globals dictionary for __file__,
+ # which should be better. However, keep Cython filenames since
+ # we prefer the source filenames over the compiled .so file.
+ filename = py3compat.cast_unicode_py2(filename, "utf-8")
+ if not filename.endswith(('.pyx', '.pxd', '.pxi')):
+ better_fn = frame.f_globals.get('__file__', None)
+ if isinstance(better_fn, str):
+ # Check the type just in case someone did something weird with
+ # __file__. It might also be None if the error occurred during
+ # import.
+ filename = better_fn
+ fixed_records.append((frame, filename, line_no, func_name, lines, index))
+ return fixed_records
+
+
+@with_patch_inspect
+def _fixed_getinnerframes(etb, context=1, tb_offset=0):
+ LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
+
+ records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
+ # If the error is at the console, don't build any context, since it would
+ # otherwise produce 5 blank lines printed out (there is no file at the
+ # console)
+ rec_check = records[tb_offset:]
+ try:
+ rname = rec_check[0][1]
+ if rname == '<ipython console>' or rname.endswith('<string>'):
+ return rec_check
+ except IndexError:
+ pass
+
+ aux = traceback.extract_tb(etb)
+ assert len(records) == len(aux)
+ for i, (file, lnum, _, _) in zip(range(len(records)), aux):
+ maybeStart = lnum - 1 - context // 2
+ start = max(maybeStart, 0)
+ end = start + context
+ lines = ulinecache.getlines(file)[start:end]
+ buf = list(records[i])
+ buf[LNUM_POS] = lnum
+ buf[INDEX_POS] = lnum - 1 - start
+ buf[LINES_POS] = lines
+ records[i] = tuple(buf)
+ return records[tb_offset:]
+
+# Helper function -- largely belongs to VerboseTB, but we need the same
+# functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
+# can be recognized properly by ipython.el's py-traceback-line-re
+# (SyntaxErrors have to be treated specially because they have no traceback)
+
+_parser = PyColorize.Parser()
+
+
+def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None):
+ numbers_width = INDENT_SIZE - 1
+ res = []
+ i = lnum - index
+
+ # This lets us get fully syntax-highlighted tracebacks.
+ if scheme is None:
+ ipinst = get_ipython()
+ if ipinst is not None:
+ scheme = ipinst.colors
+ else:
+ scheme = DEFAULT_SCHEME
+
+ _line_format = _parser.format2
+
+ for line in lines:
+ line = py3compat.cast_unicode(line)
+
+ new_line, err = _line_format(line, 'str', scheme)
+ if not err: line = new_line
+
+ if i == lnum:
+ # This is the line with the error
+ pad = numbers_width - len(str(i))
num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
- line = '%s%s%s %s%s' % (Colors.linenoEm, num,
- Colors.line, line, Colors.Normal)
- else:
- num = '%*s' % (numbers_width, i)
- line = '%s%s%s %s' % (Colors.lineno, num,
- Colors.Normal, line)
-
- res.append(line)
- if lvals and i == lnum:
- res.append(lvals + '\n')
- i = i + 1
- return res
-
-def is_recursion_error(etype, value, records):
- try:
- # RecursionError is new in Python 3.5
- recursion_error_type = RecursionError
- except NameError:
- recursion_error_type = RuntimeError
-
- # The default recursion limit is 1000, but some of that will be taken up
- # by stack frames in IPython itself. >500 frames probably indicates
- # a recursion error.
- return (etype is recursion_error_type) \
+ line = '%s%s%s %s%s' % (Colors.linenoEm, num,
+ Colors.line, line, Colors.Normal)
+ else:
+ num = '%*s' % (numbers_width, i)
+ line = '%s%s%s %s' % (Colors.lineno, num,
+ Colors.Normal, line)
+
+ res.append(line)
+ if lvals and i == lnum:
+ res.append(lvals + '\n')
+ i = i + 1
+ return res
+
+def is_recursion_error(etype, value, records):
+ try:
+ # RecursionError is new in Python 3.5
+ recursion_error_type = RecursionError
+ except NameError:
+ recursion_error_type = RuntimeError
+
+ # The default recursion limit is 1000, but some of that will be taken up
+ # by stack frames in IPython itself. >500 frames probably indicates
+ # a recursion error.
+ return (etype is recursion_error_type) \
and str("recursion") in str(value).lower() \
- and len(records) > 500
-
-def find_recursion(etype, value, records):
- """Identify the repeating stack frames from a RecursionError traceback
-
- 'records' is a list as returned by VerboseTB.get_records()
-
- Returns (last_unique, repeat_length)
- """
- # This involves a bit of guesswork - we want to show enough of the traceback
- # to indicate where the recursion is occurring. We guess that the innermost
- # quarter of the traceback (250 frames by default) is repeats, and find the
- # first frame (from in to out) that looks different.
- if not is_recursion_error(etype, value, records):
- return len(records), 0
-
- # Select filename, lineno, func_name to track frames with
- records = [r[1:4] for r in records]
- inner_frames = records[-(len(records)//4):]
- frames_repeated = set(inner_frames)
-
- last_seen_at = {}
- longest_repeat = 0
- i = len(records)
- for frame in reversed(records):
- i -= 1
- if frame not in frames_repeated:
- last_unique = i
- break
-
- if frame in last_seen_at:
- distance = last_seen_at[frame] - i
- longest_repeat = max(longest_repeat, distance)
-
- last_seen_at[frame] = i
- else:
- last_unique = 0 # The whole traceback was recursion
-
- return last_unique, longest_repeat
-
-#---------------------------------------------------------------------------
-# Module classes
+ and len(records) > 500
+
+def find_recursion(etype, value, records):
+ """Identify the repeating stack frames from a RecursionError traceback
+
+ 'records' is a list as returned by VerboseTB.get_records()
+
+ Returns (last_unique, repeat_length)
+ """
+ # This involves a bit of guesswork - we want to show enough of the traceback
+ # to indicate where the recursion is occurring. We guess that the innermost
+ # quarter of the traceback (250 frames by default) is repeats, and find the
+ # first frame (from in to out) that looks different.
+ if not is_recursion_error(etype, value, records):
+ return len(records), 0
+
+ # Select filename, lineno, func_name to track frames with
+ records = [r[1:4] for r in records]
+ inner_frames = records[-(len(records)//4):]
+ frames_repeated = set(inner_frames)
+
+ last_seen_at = {}
+ longest_repeat = 0
+ i = len(records)
+ for frame in reversed(records):
+ i -= 1
+ if frame not in frames_repeated:
+ last_unique = i
+ break
+
+ if frame in last_seen_at:
+ distance = last_seen_at[frame] - i
+ longest_repeat = max(longest_repeat, distance)
+
+ last_seen_at[frame] = i
+ else:
+ last_unique = 0 # The whole traceback was recursion
+
+ return last_unique, longest_repeat
+
+#---------------------------------------------------------------------------
+# Module classes
class TBTools(colorable.Colorable):
- """Basic tools used by all traceback printer classes."""
-
- # Number of frames to skip when reporting tracebacks
- tb_offset = 0
-
+ """Basic tools used by all traceback printer classes."""
+
+ # Number of frames to skip when reporting tracebacks
+ tb_offset = 0
+
def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
- # Whether to call the interactive pdb debugger after printing
- # tracebacks or not
+ # Whether to call the interactive pdb debugger after printing
+ # tracebacks or not
super(TBTools, self).__init__(parent=parent, config=config)
- self.call_pdb = call_pdb
-
- # Output stream to write to. Note that we store the original value in
- # a private attribute and then make the public ostream a property, so
+ self.call_pdb = call_pdb
+
+ # Output stream to write to. Note that we store the original value in
+ # a private attribute and then make the public ostream a property, so
# that we can delay accessing sys.stdout until runtime. The way
# things are written now, the sys.stdout object is dynamically managed
- # so a reference to it should NEVER be stored statically. This
- # property approach confines this detail to a single location, and all
- # subclasses can simply access self.ostream for writing.
- self._ostream = ostream
-
- # Create color table
- self.color_scheme_table = exception_colors()
-
- self.set_colors(color_scheme)
- self.old_scheme = color_scheme # save initial value for toggles
-
- if call_pdb:
+ # so a reference to it should NEVER be stored statically. This
+ # property approach confines this detail to a single location, and all
+ # subclasses can simply access self.ostream for writing.
+ self._ostream = ostream
+
+ # Create color table
+ self.color_scheme_table = exception_colors()
+
+ self.set_colors(color_scheme)
+ self.old_scheme = color_scheme # save initial value for toggles
+
+ if call_pdb:
self.pdb = debugger.Pdb()
- else:
- self.pdb = None
-
- def _get_ostream(self):
- """Output stream that exceptions are written to.
-
- Valid values are:
-
- - None: the default, which means that IPython will dynamically resolve
+ else:
+ self.pdb = None
+
+ def _get_ostream(self):
+ """Output stream that exceptions are written to.
+
+ Valid values are:
+
+ - None: the default, which means that IPython will dynamically resolve
to sys.stdout. This ensures compatibility with most tools, including
- Windows (where plain stdout doesn't recognize ANSI escapes).
-
- - Any object with 'write' and 'flush' attributes.
- """
+ Windows (where plain stdout doesn't recognize ANSI escapes).
+
+ - Any object with 'write' and 'flush' attributes.
+ """
return sys.stdout if self._ostream is None else self._ostream
-
- def _set_ostream(self, val):
- assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
- self._ostream = val
-
- ostream = property(_get_ostream, _set_ostream)
-
- def set_colors(self, *args, **kw):
- """Shorthand access to the color table scheme selector method."""
-
- # Set own color table
- self.color_scheme_table.set_active_scheme(*args, **kw)
- # for convenience, set Colors to the active scheme
- self.Colors = self.color_scheme_table.active_colors
- # Also set colors of debugger
- if hasattr(self, 'pdb') and self.pdb is not None:
- self.pdb.set_colors(*args, **kw)
-
- def color_toggle(self):
- """Toggle between the currently active color scheme and NoColor."""
-
- if self.color_scheme_table.active_scheme_name == 'NoColor':
- self.color_scheme_table.set_active_scheme(self.old_scheme)
- self.Colors = self.color_scheme_table.active_colors
- else:
- self.old_scheme = self.color_scheme_table.active_scheme_name
- self.color_scheme_table.set_active_scheme('NoColor')
- self.Colors = self.color_scheme_table.active_colors
-
- def stb2text(self, stb):
- """Convert a structured traceback (a list) to a string."""
- return '\n'.join(stb)
-
- def text(self, etype, value, tb, tb_offset=None, context=5):
- """Return formatted traceback.
-
- Subclasses may override this if they add extra arguments.
- """
- tb_list = self.structured_traceback(etype, value, tb,
- tb_offset, context)
- return self.stb2text(tb_list)
-
- def structured_traceback(self, etype, evalue, tb, tb_offset=None,
- context=5, mode=None):
- """Return a list of traceback frames.
-
- Must be implemented by each class.
- """
- raise NotImplementedError()
-
-
-#---------------------------------------------------------------------------
-class ListTB(TBTools):
- """Print traceback information from a traceback list, with optional color.
-
- Calling requires 3 arguments: (etype, evalue, elist)
- as would be obtained by::
-
- etype, evalue, tb = sys.exc_info()
- if tb:
- elist = traceback.extract_tb(tb)
- else:
- elist = None
-
- It can thus be used by programs which need to process the traceback before
- printing (such as console replacements based on the code module from the
- standard library).
-
- Because they are meant to be called without a full traceback (only a
- list), instances of this class can't call the interactive pdb debugger."""
-
+
+ def _set_ostream(self, val):
+ assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
+ self._ostream = val
+
+ ostream = property(_get_ostream, _set_ostream)
+
+ def set_colors(self, *args, **kw):
+ """Shorthand access to the color table scheme selector method."""
+
+ # Set own color table
+ self.color_scheme_table.set_active_scheme(*args, **kw)
+ # for convenience, set Colors to the active scheme
+ self.Colors = self.color_scheme_table.active_colors
+ # Also set colors of debugger
+ if hasattr(self, 'pdb') and self.pdb is not None:
+ self.pdb.set_colors(*args, **kw)
+
+ def color_toggle(self):
+ """Toggle between the currently active color scheme and NoColor."""
+
+ if self.color_scheme_table.active_scheme_name == 'NoColor':
+ self.color_scheme_table.set_active_scheme(self.old_scheme)
+ self.Colors = self.color_scheme_table.active_colors
+ else:
+ self.old_scheme = self.color_scheme_table.active_scheme_name
+ self.color_scheme_table.set_active_scheme('NoColor')
+ self.Colors = self.color_scheme_table.active_colors
+
+ def stb2text(self, stb):
+ """Convert a structured traceback (a list) to a string."""
+ return '\n'.join(stb)
+
+ def text(self, etype, value, tb, tb_offset=None, context=5):
+ """Return formatted traceback.
+
+ Subclasses may override this if they add extra arguments.
+ """
+ tb_list = self.structured_traceback(etype, value, tb,
+ tb_offset, context)
+ return self.stb2text(tb_list)
+
+ def structured_traceback(self, etype, evalue, tb, tb_offset=None,
+ context=5, mode=None):
+ """Return a list of traceback frames.
+
+ Must be implemented by each class.
+ """
+ raise NotImplementedError()
+
+
+#---------------------------------------------------------------------------
+class ListTB(TBTools):
+ """Print traceback information from a traceback list, with optional color.
+
+ Calling requires 3 arguments: (etype, evalue, elist)
+ as would be obtained by::
+
+ etype, evalue, tb = sys.exc_info()
+ if tb:
+ elist = traceback.extract_tb(tb)
+ else:
+ elist = None
+
+ It can thus be used by programs which need to process the traceback before
+ printing (such as console replacements based on the code module from the
+ standard library).
+
+ Because they are meant to be called without a full traceback (only a
+ list), instances of this class can't call the interactive pdb debugger."""
+
def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
- TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
+ TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
ostream=ostream, parent=parent)
-
- def __call__(self, etype, value, elist):
- self.ostream.flush()
- self.ostream.write(self.text(etype, value, elist))
- self.ostream.write('\n')
-
- def structured_traceback(self, etype, value, elist, tb_offset=None,
- context=5):
- """Return a color formatted string with the traceback info.
-
- Parameters
- ----------
- etype : exception type
- Type of the exception raised.
-
- value : object
- Data stored in the exception
-
- elist : list
- List of frames, see class docstring for details.
-
- tb_offset : int, optional
- Number of frames in the traceback to skip. If not given, the
- instance value is used (set in constructor).
-
- context : int, optional
- Number of lines of context information to print.
-
- Returns
- -------
- String with formatted exception.
- """
- tb_offset = self.tb_offset if tb_offset is None else tb_offset
- Colors = self.Colors
- out_list = []
- if elist:
-
- if tb_offset and len(elist) > tb_offset:
- elist = elist[tb_offset:]
-
- out_list.append('Traceback %s(most recent call last)%s:' %
- (Colors.normalEm, Colors.Normal) + '\n')
- out_list.extend(self._format_list(elist))
- # The exception info should be a single entry in the list.
- lines = ''.join(self._format_exception_only(etype, value))
- out_list.append(lines)
-
- # Note: this code originally read:
-
- ## for line in lines[:-1]:
- ## out_list.append(" "+line)
- ## out_list.append(lines[-1])
-
- # This means it was indenting everything but the last line by a little
- # bit. I've disabled this for now, but if we see ugliness somewhere we
- # can restore it.
-
- return out_list
-
- def _format_list(self, extracted_list):
- """Format a list of traceback entry tuples for printing.
-
- Given a list of tuples as returned by extract_tb() or
- extract_stack(), return a list of strings ready for printing.
- Each string in the resulting list corresponds to the item with the
- same index in the argument list. Each string ends in a newline;
- the strings may contain internal newlines as well, for those items
- whose source text line is not None.
-
- Lifted almost verbatim from traceback.py
- """
-
- Colors = self.Colors
- list = []
- for filename, lineno, name, line in extracted_list[:-1]:
- item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
- (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
- Colors.lineno, lineno, Colors.Normal,
- Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
- if line:
- item += ' %s\n' % line.strip()
- list.append(item)
- # Emphasize the last entry
- filename, lineno, name, line = extracted_list[-1]
- item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
- (Colors.normalEm,
- Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
- Colors.linenoEm, lineno, Colors.normalEm,
- Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
- Colors.Normal)
- if line:
- item += '%s %s%s\n' % (Colors.line, line.strip(),
- Colors.Normal)
- list.append(item)
- return list
-
- def _format_exception_only(self, etype, value):
- """Format the exception part of a traceback.
-
- The arguments are the exception type and value such as given by
- sys.exc_info()[:2]. The return value is a list of strings, each ending
- in a newline. Normally, the list contains a single string; however,
- for SyntaxError exceptions, it contains several lines that (when
- printed) display detailed information about where the syntax error
- occurred. The message indicating which exception occurred is the
- always last string in the list.
-
- Also lifted nearly verbatim from traceback.py
- """
- have_filedata = False
- Colors = self.Colors
- list = []
+
+ def __call__(self, etype, value, elist):
+ self.ostream.flush()
+ self.ostream.write(self.text(etype, value, elist))
+ self.ostream.write('\n')
+
+ def structured_traceback(self, etype, value, elist, tb_offset=None,
+ context=5):
+ """Return a color formatted string with the traceback info.
+
+ Parameters
+ ----------
+ etype : exception type
+ Type of the exception raised.
+
+ value : object
+ Data stored in the exception
+
+ elist : list
+ List of frames, see class docstring for details.
+
+ tb_offset : int, optional
+ Number of frames in the traceback to skip. If not given, the
+ instance value is used (set in constructor).
+
+ context : int, optional
+ Number of lines of context information to print.
+
+ Returns
+ -------
+ String with formatted exception.
+ """
+ tb_offset = self.tb_offset if tb_offset is None else tb_offset
+ Colors = self.Colors
+ out_list = []
+ if elist:
+
+ if tb_offset and len(elist) > tb_offset:
+ elist = elist[tb_offset:]
+
+ out_list.append('Traceback %s(most recent call last)%s:' %
+ (Colors.normalEm, Colors.Normal) + '\n')
+ out_list.extend(self._format_list(elist))
+ # The exception info should be a single entry in the list.
+ lines = ''.join(self._format_exception_only(etype, value))
+ out_list.append(lines)
+
+ # Note: this code originally read:
+
+ ## for line in lines[:-1]:
+ ## out_list.append(" "+line)
+ ## out_list.append(lines[-1])
+
+ # This means it was indenting everything but the last line by a little
+ # bit. I've disabled this for now, but if we see ugliness somewhere we
+ # can restore it.
+
+ return out_list
+
+ def _format_list(self, extracted_list):
+ """Format a list of traceback entry tuples for printing.
+
+ Given a list of tuples as returned by extract_tb() or
+ extract_stack(), return a list of strings ready for printing.
+ Each string in the resulting list corresponds to the item with the
+ same index in the argument list. Each string ends in a newline;
+ the strings may contain internal newlines as well, for those items
+ whose source text line is not None.
+
+ Lifted almost verbatim from traceback.py
+ """
+
+ Colors = self.Colors
+ list = []
+ for filename, lineno, name, line in extracted_list[:-1]:
+ item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
+ (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
+ Colors.lineno, lineno, Colors.Normal,
+ Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
+ if line:
+ item += ' %s\n' % line.strip()
+ list.append(item)
+ # Emphasize the last entry
+ filename, lineno, name, line = extracted_list[-1]
+ item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
+ (Colors.normalEm,
+ Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
+ Colors.linenoEm, lineno, Colors.normalEm,
+ Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
+ Colors.Normal)
+ if line:
+ item += '%s %s%s\n' % (Colors.line, line.strip(),
+ Colors.Normal)
+ list.append(item)
+ return list
+
+ def _format_exception_only(self, etype, value):
+ """Format the exception part of a traceback.
+
+ The arguments are the exception type and value such as given by
+ sys.exc_info()[:2]. The return value is a list of strings, each ending
+ in a newline. Normally, the list contains a single string; however,
+ for SyntaxError exceptions, it contains several lines that (when
+ printed) display detailed information about where the syntax error
+ occurred. The message indicating which exception occurred is the
+ always last string in the list.
+
+ Also lifted nearly verbatim from traceback.py
+ """
+ have_filedata = False
+ Colors = self.Colors
+ list = []
stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
- if value is None:
- # Not sure if this can still happen in Python 2.6 and above
+ if value is None:
+ # Not sure if this can still happen in Python 2.6 and above
list.append(stype + '\n')
- else:
- if issubclass(etype, SyntaxError):
- have_filedata = True
- if not value.filename: value.filename = "<string>"
- if value.lineno:
- lineno = value.lineno
- textline = ulinecache.getline(value.filename, value.lineno)
- else:
- lineno = 'unknown'
- textline = ''
- list.append('%s File %s"%s"%s, line %s%s%s\n' % \
- (Colors.normalEm,
- Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
- Colors.linenoEm, lineno, Colors.Normal ))
- if textline == '':
- textline = py3compat.cast_unicode(value.text, "utf-8")
-
- if textline is not None:
- i = 0
- while i < len(textline) and textline[i].isspace():
- i += 1
- list.append('%s %s%s\n' % (Colors.line,
- textline.strip(),
- Colors.Normal))
- if value.offset is not None:
- s = ' '
- for c in textline[i:value.offset - 1]:
- if c.isspace():
- s += c
- else:
- s += ' '
- list.append('%s%s^%s\n' % (Colors.caret, s,
- Colors.Normal))
-
- try:
- s = value.msg
- except Exception:
- s = self._some_str(value)
- if s:
+ else:
+ if issubclass(etype, SyntaxError):
+ have_filedata = True
+ if not value.filename: value.filename = "<string>"
+ if value.lineno:
+ lineno = value.lineno
+ textline = ulinecache.getline(value.filename, value.lineno)
+ else:
+ lineno = 'unknown'
+ textline = ''
+ list.append('%s File %s"%s"%s, line %s%s%s\n' % \
+ (Colors.normalEm,
+ Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
+ Colors.linenoEm, lineno, Colors.Normal ))
+ if textline == '':
+ textline = py3compat.cast_unicode(value.text, "utf-8")
+
+ if textline is not None:
+ i = 0
+ while i < len(textline) and textline[i].isspace():
+ i += 1
+ list.append('%s %s%s\n' % (Colors.line,
+ textline.strip(),
+ Colors.Normal))
+ if value.offset is not None:
+ s = ' '
+ for c in textline[i:value.offset - 1]:
+ if c.isspace():
+ s += c
+ else:
+ s += ' '
+ list.append('%s%s^%s\n' % (Colors.caret, s,
+ Colors.Normal))
+
+ try:
+ s = value.msg
+ except Exception:
+ s = self._some_str(value)
+ if s:
list.append('%s%s:%s %s\n' % (stype, Colors.excName,
- Colors.Normal, s))
- else:
+ Colors.Normal, s))
+ else:
list.append('%s\n' % stype)
-
- # sync with user hooks
- if have_filedata:
- ipinst = get_ipython()
- if ipinst is not None:
- ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
-
- return list
-
- def get_exception_only(self, etype, value):
- """Only print the exception type and message, without a traceback.
-
- Parameters
- ----------
- etype : exception type
- value : exception value
- """
- return ListTB.structured_traceback(self, etype, value, [])
-
- def show_exception_only(self, etype, evalue):
- """Only print the exception type and message, without a traceback.
-
- Parameters
- ----------
- etype : exception type
- value : exception value
- """
- # This method needs to use __call__ from *this* class, not the one from
- # a subclass whose signature or behavior may be different
- ostream = self.ostream
- ostream.flush()
- ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
- ostream.flush()
-
- def _some_str(self, value):
- # Lifted from traceback.py
- try:
+
+ # sync with user hooks
+ if have_filedata:
+ ipinst = get_ipython()
+ if ipinst is not None:
+ ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
+
+ return list
+
+ def get_exception_only(self, etype, value):
+ """Only print the exception type and message, without a traceback.
+
+ Parameters
+ ----------
+ etype : exception type
+ value : exception value
+ """
+ return ListTB.structured_traceback(self, etype, value, [])
+
+ def show_exception_only(self, etype, evalue):
+ """Only print the exception type and message, without a traceback.
+
+ Parameters
+ ----------
+ etype : exception type
+ value : exception value
+ """
+ # This method needs to use __call__ from *this* class, not the one from
+ # a subclass whose signature or behavior may be different
+ ostream = self.ostream
+ ostream.flush()
+ ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
+ ostream.flush()
+
+ def _some_str(self, value):
+ # Lifted from traceback.py
+ try:
return py3compat.cast_unicode(str(value))
- except:
+ except:
return u'<unprintable %s object>' % type(value).__name__
-
-
-#----------------------------------------------------------------------------
-class VerboseTB(TBTools):
- """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
- of HTML. Requires inspect and pydoc. Crazy, man.
-
- Modified version which optionally strips the topmost entries from the
- traceback, to be used with alternate interpreters (because their own code
- would appear in the traceback)."""
-
- def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
- tb_offset=0, long_header=False, include_vars=True,
+
+
+#----------------------------------------------------------------------------
+class VerboseTB(TBTools):
+ """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
+ of HTML. Requires inspect and pydoc. Crazy, man.
+
+ Modified version which optionally strips the topmost entries from the
+ traceback, to be used with alternate interpreters (because their own code
+ would appear in the traceback)."""
+
+ def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
+ tb_offset=0, long_header=False, include_vars=True,
check_cache=None, debugger_cls = None):
- """Specify traceback offset, headers and color scheme.
-
- Define how many frames to drop from the tracebacks. Calling it with
- tb_offset=1 allows use of this handler in interpreters which will have
- their own code at the top of the traceback (VerboseTB will first
- remove that frame before printing the traceback info)."""
- TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
- ostream=ostream)
- self.tb_offset = tb_offset
- self.long_header = long_header
- self.include_vars = include_vars
- # By default we use linecache.checkcache, but the user can provide a
- # different check_cache implementation. This is used by the IPython
- # kernel to provide tracebacks for interactive code that is cached,
- # by a compiler instance that flushes the linecache but preserves its
- # own code cache.
- if check_cache is None:
- check_cache = linecache.checkcache
- self.check_cache = check_cache
-
+ """Specify traceback offset, headers and color scheme.
+
+ Define how many frames to drop from the tracebacks. Calling it with
+ tb_offset=1 allows use of this handler in interpreters which will have
+ their own code at the top of the traceback (VerboseTB will first
+ remove that frame before printing the traceback info)."""
+ TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
+ ostream=ostream)
+ self.tb_offset = tb_offset
+ self.long_header = long_header
+ self.include_vars = include_vars
+ # By default we use linecache.checkcache, but the user can provide a
+ # different check_cache implementation. This is used by the IPython
+ # kernel to provide tracebacks for interactive code that is cached,
+ # by a compiler instance that flushes the linecache but preserves its
+ # own code cache.
+ if check_cache is None:
+ check_cache = linecache.checkcache
+ self.check_cache = check_cache
+
self.debugger_cls = debugger_cls or debugger.Pdb
- def format_records(self, records, last_unique, recursion_repeat):
- """Format the stack frames of the traceback"""
- frames = []
- for r in records[:last_unique+recursion_repeat+1]:
- #print '*** record:',file,lnum,func,lines,index # dbg
- frames.append(self.format_record(*r))
-
- if recursion_repeat:
- frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
- frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
-
- return frames
-
- def format_record(self, frame, file, lnum, func, lines, index):
- """Format a single stack frame"""
- Colors = self.Colors # just a shorthand + quicker name lookup
- ColorsNormal = Colors.Normal # used a lot
- col_scheme = self.color_scheme_table.active_scheme_name
- indent = ' ' * INDENT_SIZE
- em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
- undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
- tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
- tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
- ColorsNormal)
- tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
- (Colors.vName, Colors.valEm, ColorsNormal)
- tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
- tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
- Colors.vName, ColorsNormal)
- tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
-
- tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
- tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
- ColorsNormal)
-
- abspath = os.path.abspath
-
-
- if not file:
- file = '?'
- elif file.startswith(str("<")) and file.endswith(str(">")):
- # Not a real filename, no problem...
- pass
- elif not os.path.isabs(file):
- # Try to make the filename absolute by trying all
- # sys.path entries (which is also what linecache does)
- for dirname in sys.path:
- try:
- fullname = os.path.join(dirname, file)
- if os.path.isfile(fullname):
- file = os.path.abspath(fullname)
- break
- except Exception:
- # Just in case that sys.path contains very
- # strange entries...
- pass
-
- file = py3compat.cast_unicode(file, util_path.fs_encoding)
- link = tpl_link % file
- args, varargs, varkw, locals = fixed_getargvalues(frame)
-
- if func == '?':
- call = ''
- else:
- # Decide whether to include variable details or not
- var_repr = self.include_vars and eqrepr or nullrepr
- try:
- call = tpl_call % (func, inspect.formatargvalues(args,
- varargs, varkw,
- locals, formatvalue=var_repr))
- except KeyError:
- # This happens in situations like errors inside generator
- # expressions, where local variables are listed in the
- # line, but can't be extracted from the frame. I'm not
- # 100% sure this isn't actually a bug in inspect itself,
- # but since there's no info for us to compute with, the
- # best we can do is report the failure and move on. Here
- # we must *not* call any traceback construction again,
- # because that would mess up use of %debug later on. So we
- # simply report the failure and move on. The only
- # limitation will be that this frame won't have locals
- # listed in the call signature. Quite subtle problem...
- # I can't think of a good way to validate this in a unit
- # test, but running a script consisting of:
- # dict( (k,v.strip()) for (k,v) in range(10) )
- # will illustrate the error, if this exception catch is
- # disabled.
- call = tpl_call_fail % func
-
- # Don't attempt to tokenize binary files.
- if file.endswith(('.so', '.pyd', '.dll')):
- return '%s %s\n' % (link, call)
-
- elif file.endswith(('.pyc', '.pyo')):
- # Look up the corresponding source file.
+ def format_records(self, records, last_unique, recursion_repeat):
+ """Format the stack frames of the traceback"""
+ frames = []
+ for r in records[:last_unique+recursion_repeat+1]:
+ #print '*** record:',file,lnum,func,lines,index # dbg
+ frames.append(self.format_record(*r))
+
+ if recursion_repeat:
+ frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
+ frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
+
+ return frames
+
+ def format_record(self, frame, file, lnum, func, lines, index):
+ """Format a single stack frame"""
+ Colors = self.Colors # just a shorthand + quicker name lookup
+ ColorsNormal = Colors.Normal # used a lot
+ col_scheme = self.color_scheme_table.active_scheme_name
+ indent = ' ' * INDENT_SIZE
+ em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
+ undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
+ tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
+ tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
+ ColorsNormal)
+ tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
+ (Colors.vName, Colors.valEm, ColorsNormal)
+ tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
+ tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
+ Colors.vName, ColorsNormal)
+ tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
+
+ tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
+ tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
+ ColorsNormal)
+
+ abspath = os.path.abspath
+
+
+ if not file:
+ file = '?'
+ elif file.startswith(str("<")) and file.endswith(str(">")):
+ # Not a real filename, no problem...
+ pass
+ elif not os.path.isabs(file):
+ # Try to make the filename absolute by trying all
+ # sys.path entries (which is also what linecache does)
+ for dirname in sys.path:
+ try:
+ fullname = os.path.join(dirname, file)
+ if os.path.isfile(fullname):
+ file = os.path.abspath(fullname)
+ break
+ except Exception:
+ # Just in case that sys.path contains very
+ # strange entries...
+ pass
+
+ file = py3compat.cast_unicode(file, util_path.fs_encoding)
+ link = tpl_link % file
+ args, varargs, varkw, locals = fixed_getargvalues(frame)
+
+ if func == '?':
+ call = ''
+ else:
+ # Decide whether to include variable details or not
+ var_repr = self.include_vars and eqrepr or nullrepr
+ try:
+ call = tpl_call % (func, inspect.formatargvalues(args,
+ varargs, varkw,
+ locals, formatvalue=var_repr))
+ except KeyError:
+ # This happens in situations like errors inside generator
+ # expressions, where local variables are listed in the
+ # line, but can't be extracted from the frame. I'm not
+ # 100% sure this isn't actually a bug in inspect itself,
+ # but since there's no info for us to compute with, the
+ # best we can do is report the failure and move on. Here
+ # we must *not* call any traceback construction again,
+ # because that would mess up use of %debug later on. So we
+ # simply report the failure and move on. The only
+ # limitation will be that this frame won't have locals
+ # listed in the call signature. Quite subtle problem...
+ # I can't think of a good way to validate this in a unit
+ # test, but running a script consisting of:
+ # dict( (k,v.strip()) for (k,v) in range(10) )
+ # will illustrate the error, if this exception catch is
+ # disabled.
+ call = tpl_call_fail % func
+
+ # Don't attempt to tokenize binary files.
+ if file.endswith(('.so', '.pyd', '.dll')):
+ return '%s %s\n' % (link, call)
+
+ elif file.endswith(('.pyc', '.pyo')):
+ # Look up the corresponding source file.
try:
file = openpy.source_from_cache(file)
except ValueError:
# Failed to get the source file for some reason
# E.g. https://github.com/ipython/ipython/issues/9486
return '%s %s\n' % (link, call)
-
- def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
- line = getline(file, lnum[0])
- lnum[0] += 1
- return line
-
- # Build the list of names on this line of code where the exception
- # occurred.
- try:
- names = []
- name_cont = False
-
- for token_type, token, start, end, line in generate_tokens(linereader):
- # build composite names
- if token_type == tokenize.NAME and token not in keyword.kwlist:
- if name_cont:
- # Continuation of a dotted name
- try:
- names[-1].append(token)
- except IndexError:
- names.append([token])
- name_cont = False
- else:
- # Regular new names. We append everything, the caller
- # will be responsible for pruning the list later. It's
- # very tricky to try to prune as we go, b/c composite
- # names can fool us. The pruning at the end is easy
- # to do (or the caller can print a list with repeated
- # names if so desired.
- names.append([token])
- elif token == '.':
- name_cont = True
- elif token_type == tokenize.NEWLINE:
- break
-
- except (IndexError, UnicodeDecodeError, SyntaxError):
- # signals exit of tokenizer
- # SyntaxError can occur if the file is not actually Python
- # - see gh-6300
- pass
- except tokenize.TokenError as msg:
- _m = ("An unexpected error occurred while tokenizing input\n"
- "The following traceback may be corrupted or invalid\n"
- "The error message is: %s\n" % msg)
- error(_m)
-
- # Join composite names (e.g. "dict.fromkeys")
- names = ['.'.join(n) for n in names]
- # prune names list of duplicates, but keep the right order
- unique_names = uniq_stable(names)
-
- # Start loop over vars
- lvals = []
- if self.include_vars:
- for name_full in unique_names:
- name_base = name_full.split('.', 1)[0]
- if name_base in frame.f_code.co_varnames:
- if name_base in locals:
- try:
- value = repr(eval(name_full, locals))
- except:
- value = undefined
- else:
- value = undefined
- name = tpl_local_var % name_full
- else:
- if name_base in frame.f_globals:
- try:
- value = repr(eval(name_full, frame.f_globals))
- except:
- value = undefined
- else:
- value = undefined
- name = tpl_global_var % name_full
- lvals.append(tpl_name_val % (name, value))
- if lvals:
- lvals = '%s%s' % (indent, em_normal.join(lvals))
- else:
- lvals = ''
-
- level = '%s %s\n' % (link, call)
-
- if index is None:
- return level
- else:
- return '%s%s' % (level, ''.join(
- _format_traceback_lines(lnum, index, lines, Colors, lvals,
- col_scheme)))
-
- def prepare_chained_exception_message(self, cause):
- direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
- exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
-
- if cause:
- message = [[direct_cause]]
- else:
- message = [[exception_during_handling]]
- return message
-
- def prepare_header(self, etype, long_version=False):
- colors = self.Colors # just a shorthand + quicker name lookup
- colorsnormal = colors.Normal # used a lot
- exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
+
+ def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
+ line = getline(file, lnum[0])
+ lnum[0] += 1
+ return line
+
+ # Build the list of names on this line of code where the exception
+ # occurred.
+ try:
+ names = []
+ name_cont = False
+
+ for token_type, token, start, end, line in generate_tokens(linereader):
+ # build composite names
+ if token_type == tokenize.NAME and token not in keyword.kwlist:
+ if name_cont:
+ # Continuation of a dotted name
+ try:
+ names[-1].append(token)
+ except IndexError:
+ names.append([token])
+ name_cont = False
+ else:
+ # Regular new names. We append everything, the caller
+ # will be responsible for pruning the list later. It's
+ # very tricky to try to prune as we go, b/c composite
+ # names can fool us. The pruning at the end is easy
+ # to do (or the caller can print a list with repeated
+ # names if so desired.
+ names.append([token])
+ elif token == '.':
+ name_cont = True
+ elif token_type == tokenize.NEWLINE:
+ break
+
+ except (IndexError, UnicodeDecodeError, SyntaxError):
+ # signals exit of tokenizer
+ # SyntaxError can occur if the file is not actually Python
+ # - see gh-6300
+ pass
+ except tokenize.TokenError as msg:
+ _m = ("An unexpected error occurred while tokenizing input\n"
+ "The following traceback may be corrupted or invalid\n"
+ "The error message is: %s\n" % msg)
+ error(_m)
+
+ # Join composite names (e.g. "dict.fromkeys")
+ names = ['.'.join(n) for n in names]
+ # prune names list of duplicates, but keep the right order
+ unique_names = uniq_stable(names)
+
+ # Start loop over vars
+ lvals = []
+ if self.include_vars:
+ for name_full in unique_names:
+ name_base = name_full.split('.', 1)[0]
+ if name_base in frame.f_code.co_varnames:
+ if name_base in locals:
+ try:
+ value = repr(eval(name_full, locals))
+ except:
+ value = undefined
+ else:
+ value = undefined
+ name = tpl_local_var % name_full
+ else:
+ if name_base in frame.f_globals:
+ try:
+ value = repr(eval(name_full, frame.f_globals))
+ except:
+ value = undefined
+ else:
+ value = undefined
+ name = tpl_global_var % name_full
+ lvals.append(tpl_name_val % (name, value))
+ if lvals:
+ lvals = '%s%s' % (indent, em_normal.join(lvals))
+ else:
+ lvals = ''
+
+ level = '%s %s\n' % (link, call)
+
+ if index is None:
+ return level
+ else:
+ return '%s%s' % (level, ''.join(
+ _format_traceback_lines(lnum, index, lines, Colors, lvals,
+ col_scheme)))
+
+ def prepare_chained_exception_message(self, cause):
+ direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
+ exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
+
+ if cause:
+ message = [[direct_cause]]
+ else:
+ message = [[exception_during_handling]]
+ return message
+
+ def prepare_header(self, etype, long_version=False):
+ colors = self.Colors # just a shorthand + quicker name lookup
+ colorsnormal = colors.Normal # used a lot
+ exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
width = min(75, get_terminal_size()[0])
- if long_version:
- # Header with the exception type, python version, and date
- pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
- date = time.ctime(time.time())
-
+ if long_version:
+ # Header with the exception type, python version, and date
+ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
+ date = time.ctime(time.time())
+
head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
exc, ' ' * (width - len(str(etype)) - len(pyver)),
pyver, date.rjust(width) )
- head += "\nA problem occurred executing Python code. Here is the sequence of function" \
- "\ncalls leading up to the error, with the most recent (innermost) call last."
- else:
- # Simplified header
- head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
+ head += "\nA problem occurred executing Python code. Here is the sequence of function" \
+ "\ncalls leading up to the error, with the most recent (innermost) call last."
+ else:
+ # Simplified header
+ head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
rjust(width - len(str(etype))) )
-
- return head
-
- def format_exception(self, etype, evalue):
- colors = self.Colors # just a shorthand + quicker name lookup
- colorsnormal = colors.Normal # used a lot
- indent = ' ' * INDENT_SIZE
- # Get (safely) a string form of the exception info
- try:
- etype_str, evalue_str = map(str, (etype, evalue))
- except:
- # User exception is improperly defined.
- etype, evalue = str, sys.exc_info()[:2]
- etype_str, evalue_str = map(str, (etype, evalue))
- # ... and format it
- exception = ['%s%s%s: %s' % (colors.excName, etype_str,
- colorsnormal, py3compat.cast_unicode(evalue_str))]
-
- if (not py3compat.PY3) and type(evalue) is types.InstanceType:
- try:
- names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
- except:
- # Every now and then, an object with funny internals blows up
- # when dir() is called on it. We do the best we can to report
- # the problem and continue
- _m = '%sException reporting error (object with broken dir())%s:'
- exception.append(_m % (colors.excName, colorsnormal))
- etype_str, evalue_str = map(str, sys.exc_info()[:2])
- exception.append('%s%s%s: %s' % (colors.excName, etype_str,
- colorsnormal, py3compat.cast_unicode(evalue_str)))
- names = []
- for name in names:
- value = text_repr(getattr(evalue, name))
- exception.append('\n%s%s = %s' % (indent, name, value))
-
- return exception
-
- def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
- """Formats the header, traceback and exception message for a single exception.
-
- This may be called multiple times by Python 3 exception chaining
- (PEP 3134).
- """
- # some locals
- orig_etype = etype
- try:
- etype = etype.__name__
- except AttributeError:
- pass
-
- tb_offset = self.tb_offset if tb_offset is None else tb_offset
- head = self.prepare_header(etype, self.long_header)
- records = self.get_records(etb, number_of_lines_of_context, tb_offset)
-
- if records is None:
- return ""
-
- last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
-
- frames = self.format_records(records, last_unique, recursion_repeat)
-
- formatted_exception = self.format_exception(etype, evalue)
- if records:
- filepath, lnum = records[-1][1:3]
- filepath = os.path.abspath(filepath)
- ipinst = get_ipython()
- if ipinst is not None:
- ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
-
- return [[head] + frames + [''.join(formatted_exception[0])]]
-
- def get_records(self, etb, number_of_lines_of_context, tb_offset):
- try:
- # Try the default getinnerframes and Alex's: Alex's fixes some
- # problems, but it generates empty tracebacks for console errors
- # (5 blanks lines) where none should be returned.
- return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
+
+ return head
+
+ def format_exception(self, etype, evalue):
+ colors = self.Colors # just a shorthand + quicker name lookup
+ colorsnormal = colors.Normal # used a lot
+ indent = ' ' * INDENT_SIZE
+ # Get (safely) a string form of the exception info
+ try:
+ etype_str, evalue_str = map(str, (etype, evalue))
+ except:
+ # User exception is improperly defined.
+ etype, evalue = str, sys.exc_info()[:2]
+ etype_str, evalue_str = map(str, (etype, evalue))
+ # ... and format it
+ exception = ['%s%s%s: %s' % (colors.excName, etype_str,
+ colorsnormal, py3compat.cast_unicode(evalue_str))]
+
+ if (not py3compat.PY3) and type(evalue) is types.InstanceType:
+ try:
+ names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
+ except:
+ # Every now and then, an object with funny internals blows up
+ # when dir() is called on it. We do the best we can to report
+ # the problem and continue
+ _m = '%sException reporting error (object with broken dir())%s:'
+ exception.append(_m % (colors.excName, colorsnormal))
+ etype_str, evalue_str = map(str, sys.exc_info()[:2])
+ exception.append('%s%s%s: %s' % (colors.excName, etype_str,
+ colorsnormal, py3compat.cast_unicode(evalue_str)))
+ names = []
+ for name in names:
+ value = text_repr(getattr(evalue, name))
+ exception.append('\n%s%s = %s' % (indent, name, value))
+
+ return exception
+
+ def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
+ """Formats the header, traceback and exception message for a single exception.
+
+ This may be called multiple times by Python 3 exception chaining
+ (PEP 3134).
+ """
+ # some locals
+ orig_etype = etype
+ try:
+ etype = etype.__name__
+ except AttributeError:
+ pass
+
+ tb_offset = self.tb_offset if tb_offset is None else tb_offset
+ head = self.prepare_header(etype, self.long_header)
+ records = self.get_records(etb, number_of_lines_of_context, tb_offset)
+
+ if records is None:
+ return ""
+
+ last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
+
+ frames = self.format_records(records, last_unique, recursion_repeat)
+
+ formatted_exception = self.format_exception(etype, evalue)
+ if records:
+ filepath, lnum = records[-1][1:3]
+ filepath = os.path.abspath(filepath)
+ ipinst = get_ipython()
+ if ipinst is not None:
+ ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
+
+ return [[head] + frames + [''.join(formatted_exception[0])]]
+
+ def get_records(self, etb, number_of_lines_of_context, tb_offset):
+ try:
+ # Try the default getinnerframes and Alex's: Alex's fixes some
+ # problems, but it generates empty tracebacks for console errors
+ # (5 blanks lines) where none should be returned.
+ return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
except UnicodeDecodeError:
# This can occur if a file's encoding magic comment is wrong.
# I can't see a way to recover without duplicating a bunch of code
# from the stdlib traceback module. --TK
error('\nUnicodeDecodeError while processing traceback.\n')
return None
- except:
- # FIXME: I've been getting many crash reports from python 2.3
- # users, traceable to inspect.py. If I can find a small test-case
- # to reproduce this, I should either write a better workaround or
- # file a bug report against inspect (if that's the real problem).
- # So far, I haven't been able to find an isolated example to
- # reproduce the problem.
- inspect_error()
- traceback.print_exc(file=self.ostream)
- info('\nUnfortunately, your original traceback can not be constructed.\n')
- return None
-
- def get_parts_of_chained_exception(self, evalue):
- def get_chained_exception(exception_value):
- cause = getattr(exception_value, '__cause__', None)
- if cause:
- return cause
- if getattr(exception_value, '__suppress_context__', False):
- return None
- return getattr(exception_value, '__context__', None)
-
- chained_evalue = get_chained_exception(evalue)
-
- if chained_evalue:
- return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
-
- def structured_traceback(self, etype, evalue, etb, tb_offset=None,
- number_of_lines_of_context=5):
- """Return a nice text document describing the traceback."""
-
- formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
- tb_offset)
-
- colors = self.Colors # just a shorthand + quicker name lookup
- colorsnormal = colors.Normal # used a lot
+ except:
+ # FIXME: I've been getting many crash reports from python 2.3
+ # users, traceable to inspect.py. If I can find a small test-case
+ # to reproduce this, I should either write a better workaround or
+ # file a bug report against inspect (if that's the real problem).
+ # So far, I haven't been able to find an isolated example to
+ # reproduce the problem.
+ inspect_error()
+ traceback.print_exc(file=self.ostream)
+ info('\nUnfortunately, your original traceback can not be constructed.\n')
+ return None
+
+ def get_parts_of_chained_exception(self, evalue):
+ def get_chained_exception(exception_value):
+ cause = getattr(exception_value, '__cause__', None)
+ if cause:
+ return cause
+ if getattr(exception_value, '__suppress_context__', False):
+ return None
+ return getattr(exception_value, '__context__', None)
+
+ chained_evalue = get_chained_exception(evalue)
+
+ if chained_evalue:
+ return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
+
+ def structured_traceback(self, etype, evalue, etb, tb_offset=None,
+ number_of_lines_of_context=5):
+ """Return a nice text document describing the traceback."""
+
+ formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
+ tb_offset)
+
+ colors = self.Colors # just a shorthand + quicker name lookup
+ colorsnormal = colors.Normal # used a lot
head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
- structured_traceback_parts = [head]
- if py3compat.PY3:
- chained_exceptions_tb_offset = 0
- lines_of_context = 3
- formatted_exceptions = formatted_exception
- exception = self.get_parts_of_chained_exception(evalue)
- if exception:
- formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
- etype, evalue, etb = exception
- else:
- evalue = None
- chained_exc_ids = set()
- while evalue:
- formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
- chained_exceptions_tb_offset)
- exception = self.get_parts_of_chained_exception(evalue)
-
- if exception and not id(exception[1]) in chained_exc_ids:
- chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
- formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
- etype, evalue, etb = exception
- else:
- evalue = None
-
- # we want to see exceptions in a reversed order:
- # the first exception should be on top
- for formatted_exception in reversed(formatted_exceptions):
- structured_traceback_parts += formatted_exception
- else:
- structured_traceback_parts += formatted_exception[0]
-
- return structured_traceback_parts
-
- def debugger(self, force=False):
- """Call up the pdb debugger if desired, always clean up the tb
- reference.
-
- Keywords:
-
- - force(False): by default, this routine checks the instance call_pdb
- flag and does not actually invoke the debugger if the flag is false.
- The 'force' option forces the debugger to activate even if the flag
- is false.
-
- If the call_pdb flag is set, the pdb interactive debugger is
- invoked. In all cases, the self.tb reference to the current traceback
- is deleted to prevent lingering references which hamper memory
- management.
-
- Note that each call to pdb() does an 'import readline', so if your app
- requires a special setup for the readline completers, you'll have to
- fix that by hand after invoking the exception handler."""
-
- if force or self.call_pdb:
- if self.pdb is None:
+ structured_traceback_parts = [head]
+ if py3compat.PY3:
+ chained_exceptions_tb_offset = 0
+ lines_of_context = 3
+ formatted_exceptions = formatted_exception
+ exception = self.get_parts_of_chained_exception(evalue)
+ if exception:
+ formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
+ etype, evalue, etb = exception
+ else:
+ evalue = None
+ chained_exc_ids = set()
+ while evalue:
+ formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
+ chained_exceptions_tb_offset)
+ exception = self.get_parts_of_chained_exception(evalue)
+
+ if exception and not id(exception[1]) in chained_exc_ids:
+ chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
+ formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
+ etype, evalue, etb = exception
+ else:
+ evalue = None
+
+ # we want to see exceptions in a reversed order:
+ # the first exception should be on top
+ for formatted_exception in reversed(formatted_exceptions):
+ structured_traceback_parts += formatted_exception
+ else:
+ structured_traceback_parts += formatted_exception[0]
+
+ return structured_traceback_parts
+
+ def debugger(self, force=False):
+ """Call up the pdb debugger if desired, always clean up the tb
+ reference.
+
+ Keywords:
+
+ - force(False): by default, this routine checks the instance call_pdb
+ flag and does not actually invoke the debugger if the flag is false.
+ The 'force' option forces the debugger to activate even if the flag
+ is false.
+
+ If the call_pdb flag is set, the pdb interactive debugger is
+ invoked. In all cases, the self.tb reference to the current traceback
+ is deleted to prevent lingering references which hamper memory
+ management.
+
+ Note that each call to pdb() does an 'import readline', so if your app
+ requires a special setup for the readline completers, you'll have to
+ fix that by hand after invoking the exception handler."""
+
+ if force or self.call_pdb:
+ if self.pdb is None:
self.pdb = self.debugger_cls()
- # the system displayhook may have changed, restore the original
- # for pdb
- display_trap = DisplayTrap(hook=sys.__displayhook__)
- with display_trap:
- self.pdb.reset()
- # Find the right frame so we don't pop up inside ipython itself
- if hasattr(self, 'tb') and self.tb is not None:
- etb = self.tb
- else:
- etb = self.tb = sys.last_traceback
- while self.tb is not None and self.tb.tb_next is not None:
- self.tb = self.tb.tb_next
- if etb and etb.tb_next:
- etb = etb.tb_next
- self.pdb.botframe = etb.tb_frame
- self.pdb.interaction(self.tb.tb_frame, self.tb)
-
- if hasattr(self, 'tb'):
- del self.tb
-
- def handler(self, info=None):
- (etype, evalue, etb) = info or sys.exc_info()
- self.tb = etb
- ostream = self.ostream
- ostream.flush()
- ostream.write(self.text(etype, evalue, etb))
- ostream.write('\n')
- ostream.flush()
-
- # Changed so an instance can just be called as VerboseTB_inst() and print
- # out the right info on its own.
- def __call__(self, etype=None, evalue=None, etb=None):
- """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
- if etb is None:
- self.handler()
- else:
- self.handler((etype, evalue, etb))
- try:
- self.debugger()
- except KeyboardInterrupt:
- print("\nKeyboardInterrupt")
-
-
-#----------------------------------------------------------------------------
-class FormattedTB(VerboseTB, ListTB):
- """Subclass ListTB but allow calling with a traceback.
-
- It can thus be used as a sys.excepthook for Python > 2.1.
-
- Also adds 'Context' and 'Verbose' modes, not available in ListTB.
-
- Allows a tb_offset to be specified. This is useful for situations where
- one needs to remove a number of topmost frames from the traceback (such as
- occurs with python programs that themselves execute other python code,
- like Python shells). """
-
- def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
- ostream=None,
- tb_offset=0, long_header=False, include_vars=False,
+ # the system displayhook may have changed, restore the original
+ # for pdb
+ display_trap = DisplayTrap(hook=sys.__displayhook__)
+ with display_trap:
+ self.pdb.reset()
+ # Find the right frame so we don't pop up inside ipython itself
+ if hasattr(self, 'tb') and self.tb is not None:
+ etb = self.tb
+ else:
+ etb = self.tb = sys.last_traceback
+ while self.tb is not None and self.tb.tb_next is not None:
+ self.tb = self.tb.tb_next
+ if etb and etb.tb_next:
+ etb = etb.tb_next
+ self.pdb.botframe = etb.tb_frame
+ self.pdb.interaction(self.tb.tb_frame, self.tb)
+
+ if hasattr(self, 'tb'):
+ del self.tb
+
+ def handler(self, info=None):
+ (etype, evalue, etb) = info or sys.exc_info()
+ self.tb = etb
+ ostream = self.ostream
+ ostream.flush()
+ ostream.write(self.text(etype, evalue, etb))
+ ostream.write('\n')
+ ostream.flush()
+
+ # Changed so an instance can just be called as VerboseTB_inst() and print
+ # out the right info on its own.
+ def __call__(self, etype=None, evalue=None, etb=None):
+ """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
+ if etb is None:
+ self.handler()
+ else:
+ self.handler((etype, evalue, etb))
+ try:
+ self.debugger()
+ except KeyboardInterrupt:
+ print("\nKeyboardInterrupt")
+
+
+#----------------------------------------------------------------------------
+class FormattedTB(VerboseTB, ListTB):
+ """Subclass ListTB but allow calling with a traceback.
+
+ It can thus be used as a sys.excepthook for Python > 2.1.
+
+ Also adds 'Context' and 'Verbose' modes, not available in ListTB.
+
+ Allows a tb_offset to be specified. This is useful for situations where
+ one needs to remove a number of topmost frames from the traceback (such as
+ occurs with python programs that themselves execute other python code,
+ like Python shells). """
+
+ def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
+ ostream=None,
+ tb_offset=0, long_header=False, include_vars=False,
check_cache=None, debugger_cls=None):
-
- # NEVER change the order of this list. Put new modes at the end:
- self.valid_modes = ['Plain', 'Context', 'Verbose']
- self.verbose_modes = self.valid_modes[1:3]
-
- VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
- ostream=ostream, tb_offset=tb_offset,
- long_header=long_header, include_vars=include_vars,
+
+ # NEVER change the order of this list. Put new modes at the end:
+ self.valid_modes = ['Plain', 'Context', 'Verbose']
+ self.verbose_modes = self.valid_modes[1:3]
+
+ VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
+ ostream=ostream, tb_offset=tb_offset,
+ long_header=long_header, include_vars=include_vars,
check_cache=check_cache, debugger_cls=debugger_cls)
-
- # Different types of tracebacks are joined with different separators to
- # form a single string. They are taken from this dict
- self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
- # set_mode also sets the tb_join_char attribute
- self.set_mode(mode)
-
- def _extract_tb(self, tb):
- if tb:
- return traceback.extract_tb(tb)
- else:
- return None
-
- def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
- tb_offset = self.tb_offset if tb_offset is None else tb_offset
- mode = self.mode
- if mode in self.verbose_modes:
- # Verbose modes need a full traceback
- return VerboseTB.structured_traceback(
- self, etype, value, tb, tb_offset, number_of_lines_of_context
- )
- else:
- # We must check the source cache because otherwise we can print
- # out-of-date source code.
- self.check_cache()
- # Now we can extract and format the exception
- elist = self._extract_tb(tb)
- return ListTB.structured_traceback(
- self, etype, value, elist, tb_offset, number_of_lines_of_context
- )
-
- def stb2text(self, stb):
- """Convert a structured traceback (a list) to a string."""
- return self.tb_join_char.join(stb)
-
-
- def set_mode(self, mode=None):
- """Switch to the desired mode.
-
- If mode is not specified, cycles through the available modes."""
-
- if not mode:
- new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
- len(self.valid_modes)
- self.mode = self.valid_modes[new_idx]
- elif mode not in self.valid_modes:
- raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
- 'Valid modes: ' + str(self.valid_modes))
- else:
- self.mode = mode
- # include variable details only in 'Verbose' mode
- self.include_vars = (self.mode == self.valid_modes[2])
- # Set the join character for generating text tracebacks
- self.tb_join_char = self._join_chars[self.mode]
-
- # some convenient shortcuts
- def plain(self):
- self.set_mode(self.valid_modes[0])
-
- def context(self):
- self.set_mode(self.valid_modes[1])
-
- def verbose(self):
- self.set_mode(self.valid_modes[2])
-
-
-#----------------------------------------------------------------------------
-class AutoFormattedTB(FormattedTB):
- """A traceback printer which can be called on the fly.
-
- It will find out about exceptions by itself.
-
- A brief example::
-
- AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
- try:
- ...
- except:
- AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
- """
-
- def __call__(self, etype=None, evalue=None, etb=None,
- out=None, tb_offset=None):
- """Print out a formatted exception traceback.
-
- Optional arguments:
- - out: an open file-like object to direct output to.
-
- - tb_offset: the number of frames to skip over in the stack, on a
- per-call basis (this overrides temporarily the instance's tb_offset
- given at initialization time. """
-
- if out is None:
- out = self.ostream
- out.flush()
- out.write(self.text(etype, evalue, etb, tb_offset))
- out.write('\n')
- out.flush()
- # FIXME: we should remove the auto pdb behavior from here and leave
- # that to the clients.
- try:
- self.debugger()
- except KeyboardInterrupt:
- print("\nKeyboardInterrupt")
-
- def structured_traceback(self, etype=None, value=None, tb=None,
- tb_offset=None, number_of_lines_of_context=5):
- if etype is None:
- etype, value, tb = sys.exc_info()
- self.tb = tb
- return FormattedTB.structured_traceback(
- self, etype, value, tb, tb_offset, number_of_lines_of_context)
-
-
-#---------------------------------------------------------------------------
-
-# A simple class to preserve Nathan's original functionality.
-class ColorTB(FormattedTB):
- """Shorthand to initialize a FormattedTB in Linux colors mode."""
-
- def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
- FormattedTB.__init__(self, color_scheme=color_scheme,
- call_pdb=call_pdb, **kwargs)
-
-
-class SyntaxTB(ListTB):
- """Extension which holds some state: the last exception value"""
-
- def __init__(self, color_scheme='NoColor'):
- ListTB.__init__(self, color_scheme)
- self.last_syntax_error = None
-
- def __call__(self, etype, value, elist):
- self.last_syntax_error = value
-
- ListTB.__call__(self, etype, value, elist)
-
- def structured_traceback(self, etype, value, elist, tb_offset=None,
- context=5):
- # If the source file has been edited, the line in the syntax error can
- # be wrong (retrieved from an outdated cache). This replaces it with
- # the current value.
- if isinstance(value, SyntaxError) \
- and isinstance(value.filename, py3compat.string_types) \
- and isinstance(value.lineno, int):
- linecache.checkcache(value.filename)
- newtext = ulinecache.getline(value.filename, value.lineno)
- if newtext:
- value.text = newtext
+
+ # Different types of tracebacks are joined with different separators to
+ # form a single string. They are taken from this dict
+ self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
+ # set_mode also sets the tb_join_char attribute
+ self.set_mode(mode)
+
+ def _extract_tb(self, tb):
+ if tb:
+ return traceback.extract_tb(tb)
+ else:
+ return None
+
+ def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
+ tb_offset = self.tb_offset if tb_offset is None else tb_offset
+ mode = self.mode
+ if mode in self.verbose_modes:
+ # Verbose modes need a full traceback
+ return VerboseTB.structured_traceback(
+ self, etype, value, tb, tb_offset, number_of_lines_of_context
+ )
+ else:
+ # We must check the source cache because otherwise we can print
+ # out-of-date source code.
+ self.check_cache()
+ # Now we can extract and format the exception
+ elist = self._extract_tb(tb)
+ return ListTB.structured_traceback(
+ self, etype, value, elist, tb_offset, number_of_lines_of_context
+ )
+
+ def stb2text(self, stb):
+ """Convert a structured traceback (a list) to a string."""
+ return self.tb_join_char.join(stb)
+
+
+ def set_mode(self, mode=None):
+ """Switch to the desired mode.
+
+ If mode is not specified, cycles through the available modes."""
+
+ if not mode:
+ new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
+ len(self.valid_modes)
+ self.mode = self.valid_modes[new_idx]
+ elif mode not in self.valid_modes:
+ raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
+ 'Valid modes: ' + str(self.valid_modes))
+ else:
+ self.mode = mode
+ # include variable details only in 'Verbose' mode
+ self.include_vars = (self.mode == self.valid_modes[2])
+ # Set the join character for generating text tracebacks
+ self.tb_join_char = self._join_chars[self.mode]
+
+ # some convenient shortcuts
+ def plain(self):
+ self.set_mode(self.valid_modes[0])
+
+ def context(self):
+ self.set_mode(self.valid_modes[1])
+
+ def verbose(self):
+ self.set_mode(self.valid_modes[2])
+
+
+#----------------------------------------------------------------------------
+class AutoFormattedTB(FormattedTB):
+ """A traceback printer which can be called on the fly.
+
+ It will find out about exceptions by itself.
+
+ A brief example::
+
+ AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
+ try:
+ ...
+ except:
+ AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
+ """
+
+ def __call__(self, etype=None, evalue=None, etb=None,
+ out=None, tb_offset=None):
+ """Print out a formatted exception traceback.
+
+ Optional arguments:
+ - out: an open file-like object to direct output to.
+
+ - tb_offset: the number of frames to skip over in the stack, on a
+ per-call basis (this overrides temporarily the instance's tb_offset
+ given at initialization time. """
+
+ if out is None:
+ out = self.ostream
+ out.flush()
+ out.write(self.text(etype, evalue, etb, tb_offset))
+ out.write('\n')
+ out.flush()
+ # FIXME: we should remove the auto pdb behavior from here and leave
+ # that to the clients.
+ try:
+ self.debugger()
+ except KeyboardInterrupt:
+ print("\nKeyboardInterrupt")
+
+ def structured_traceback(self, etype=None, value=None, tb=None,
+ tb_offset=None, number_of_lines_of_context=5):
+ if etype is None:
+ etype, value, tb = sys.exc_info()
+ self.tb = tb
+ return FormattedTB.structured_traceback(
+ self, etype, value, tb, tb_offset, number_of_lines_of_context)
+
+
+#---------------------------------------------------------------------------
+
+# A simple class to preserve Nathan's original functionality.
+class ColorTB(FormattedTB):
+ """Shorthand to initialize a FormattedTB in Linux colors mode."""
+
+ def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
+ FormattedTB.__init__(self, color_scheme=color_scheme,
+ call_pdb=call_pdb, **kwargs)
+
+
+class SyntaxTB(ListTB):
+ """Extension which holds some state: the last exception value"""
+
+ def __init__(self, color_scheme='NoColor'):
+ ListTB.__init__(self, color_scheme)
+ self.last_syntax_error = None
+
+ def __call__(self, etype, value, elist):
+ self.last_syntax_error = value
+
+ ListTB.__call__(self, etype, value, elist)
+
+ def structured_traceback(self, etype, value, elist, tb_offset=None,
+ context=5):
+ # If the source file has been edited, the line in the syntax error can
+ # be wrong (retrieved from an outdated cache). This replaces it with
+ # the current value.
+ if isinstance(value, SyntaxError) \
+ and isinstance(value.filename, py3compat.string_types) \
+ and isinstance(value.lineno, int):
+ linecache.checkcache(value.filename)
+ newtext = ulinecache.getline(value.filename, value.lineno)
+ if newtext:
+ value.text = newtext
self.last_syntax_error = value
- return super(SyntaxTB, self).structured_traceback(etype, value, elist,
- tb_offset=tb_offset, context=context)
-
- def clear_err_state(self):
- """Return the current error state and clear it"""
- e = self.last_syntax_error
- self.last_syntax_error = None
- return e
-
- def stb2text(self, stb):
- """Convert a structured traceback (a list) to a string."""
- return ''.join(stb)
-
-
-# some internal-use functions
-def text_repr(value):
- """Hopefully pretty robust repr equivalent."""
- # this is pretty horrible but should always return *something*
- try:
- return pydoc.text.repr(value)
- except KeyboardInterrupt:
- raise
- except:
- try:
- return repr(value)
- except KeyboardInterrupt:
- raise
- except:
- try:
- # all still in an except block so we catch
- # getattr raising
- name = getattr(value, '__name__', None)
- if name:
- # ick, recursion
- return text_repr(name)
- klass = getattr(value, '__class__', None)
- if klass:
- return '%s instance' % text_repr(klass)
- except KeyboardInterrupt:
- raise
- except:
- return 'UNRECOVERABLE REPR FAILURE'
-
-
-def eqrepr(value, repr=text_repr):
- return '=%s' % repr(value)
-
-
-def nullrepr(value, repr=text_repr):
- return ''
+ return super(SyntaxTB, self).structured_traceback(etype, value, elist,
+ tb_offset=tb_offset, context=context)
+
+ def clear_err_state(self):
+ """Return the current error state and clear it"""
+ e = self.last_syntax_error
+ self.last_syntax_error = None
+ return e
+
+ def stb2text(self, stb):
+ """Convert a structured traceback (a list) to a string."""
+ return ''.join(stb)
+
+
+# some internal-use functions
+def text_repr(value):
+ """Hopefully pretty robust repr equivalent."""
+ # this is pretty horrible but should always return *something*
+ try:
+ return pydoc.text.repr(value)
+ except KeyboardInterrupt:
+ raise
+ except:
+ try:
+ return repr(value)
+ except KeyboardInterrupt:
+ raise
+ except:
+ try:
+ # all still in an except block so we catch
+ # getattr raising
+ name = getattr(value, '__name__', None)
+ if name:
+ # ick, recursion
+ return text_repr(name)
+ klass = getattr(value, '__class__', None)
+ if klass:
+ return '%s instance' % text_repr(klass)
+ except KeyboardInterrupt:
+ raise
+ except:
+ return 'UNRECOVERABLE REPR FAILURE'
+
+
+def eqrepr(value, repr=text_repr):
+ return '=%s' % repr(value)
+
+
+def nullrepr(value, repr=text_repr):
+ return ''
diff --git a/contrib/python/ipython/py2/IPython/core/usage.py b/contrib/python/ipython/py2/IPython/core/usage.py
index 8a890c7792..c4d3c16eca 100644
--- a/contrib/python/ipython/py2/IPython/core/usage.py
+++ b/contrib/python/ipython/py2/IPython/core/usage.py
@@ -1,344 +1,344 @@
-# -*- coding: utf-8 -*-
-"""Usage information for the main IPython applications.
-"""
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-# Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-import sys
-from IPython.core import release
-
-cl_usage = """\
-=========
- IPython
-=========
-
-Tools for Interactive Computing in Python
-=========================================
-
- A Python shell with automatic history (input and output), dynamic object
- introspection, easier configuration, command completion, access to the
- system shell and more. IPython can also be embedded in running programs.
-
-
-Usage
-
- ipython [subcommand] [options] [-c cmd | -m mod | file] [--] [arg] ...
-
- If invoked with no options, it executes the file and exits, passing the
- remaining arguments to the script, just as if you had specified the same
- command with python. You may need to specify `--` before args to be passed
- to the script, to prevent IPython from attempting to parse them. If you
- specify the option `-i` before the filename, it will enter an interactive
- IPython session after running the script, rather than exiting. Files ending
- in .py will be treated as normal Python, but files ending in .ipy can
- contain special IPython syntax (magic commands, shell expansions, etc.).
-
- Almost all configuration in IPython is available via the command-line. Do
- `ipython --help-all` to see all available options. For persistent
- configuration, look into your `ipython_config.py` configuration file for
- details.
-
- This file is typically installed in the `IPYTHONDIR` directory, and there
- is a separate configuration directory for each profile. The default profile
- directory will be located in $IPYTHONDIR/profile_default. IPYTHONDIR
- defaults to to `$HOME/.ipython`. For Windows users, $HOME resolves to
- C:\\Users\\YourUserName in most instances.
-
- To initialize a profile with the default configuration file, do::
-
- $> ipython profile create
-
- and start editing `IPYTHONDIR/profile_default/ipython_config.py`
-
- In IPython's documentation, we will refer to this directory as
- `IPYTHONDIR`, you can change its default location by creating an
- environment variable with this name and setting it to the desired path.
-
- For more information, see the manual available in HTML and PDF in your
- installation, or online at http://ipython.org/documentation.html.
-"""
-
-interactive_usage = """
-IPython -- An enhanced Interactive Python
-=========================================
-
+# -*- coding: utf-8 -*-
+"""Usage information for the main IPython applications.
+"""
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+# Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+import sys
+from IPython.core import release
+
+cl_usage = """\
+=========
+ IPython
+=========
+
+Tools for Interactive Computing in Python
+=========================================
+
+ A Python shell with automatic history (input and output), dynamic object
+ introspection, easier configuration, command completion, access to the
+ system shell and more. IPython can also be embedded in running programs.
+
+
+Usage
+
+ ipython [subcommand] [options] [-c cmd | -m mod | file] [--] [arg] ...
+
+ If invoked with no options, it executes the file and exits, passing the
+ remaining arguments to the script, just as if you had specified the same
+ command with python. You may need to specify `--` before args to be passed
+ to the script, to prevent IPython from attempting to parse them. If you
+ specify the option `-i` before the filename, it will enter an interactive
+ IPython session after running the script, rather than exiting. Files ending
+ in .py will be treated as normal Python, but files ending in .ipy can
+ contain special IPython syntax (magic commands, shell expansions, etc.).
+
+ Almost all configuration in IPython is available via the command-line. Do
+ `ipython --help-all` to see all available options. For persistent
+ configuration, look into your `ipython_config.py` configuration file for
+ details.
+
+ This file is typically installed in the `IPYTHONDIR` directory, and there
+ is a separate configuration directory for each profile. The default profile
+ directory will be located in $IPYTHONDIR/profile_default. IPYTHONDIR
+ defaults to to `$HOME/.ipython`. For Windows users, $HOME resolves to
+ C:\\Users\\YourUserName in most instances.
+
+ To initialize a profile with the default configuration file, do::
+
+ $> ipython profile create
+
+ and start editing `IPYTHONDIR/profile_default/ipython_config.py`
+
+ In IPython's documentation, we will refer to this directory as
+ `IPYTHONDIR`, you can change its default location by creating an
+ environment variable with this name and setting it to the desired path.
+
+ For more information, see the manual available in HTML and PDF in your
+ installation, or online at http://ipython.org/documentation.html.
+"""
+
+interactive_usage = """
+IPython -- An enhanced Interactive Python
+=========================================
+
IPython offers a fully compatible replacement for the standard Python
interpreter, with convenient shell features, special commands, command
history mechanism and output results caching.
-
-At your system command line, type 'ipython -h' to see the command line
-options available. This document only describes interactive features.
-
-MAIN FEATURES
--------------
-
+
+At your system command line, type 'ipython -h' to see the command line
+options available. This document only describes interactive features.
+
+MAIN FEATURES
+-------------
+
* Access to the standard Python help with object docstrings and the Python
manuals. Simply type 'help' (no quotes) to invoke it.
-
-* Magic commands: type %magic for information on the magic subsystem.
-
-* System command aliases, via the %alias command or the configuration file(s).
-
-* Dynamic object information:
-
+
+* Magic commands: type %magic for information on the magic subsystem.
+
+* System command aliases, via the %alias command or the configuration file(s).
+
+* Dynamic object information:
+
Typing ?word or word? prints detailed information about an object. Certain
long strings (code, etc.) get snipped in the center for brevity.
-
- Typing ??word or word?? gives access to the full information without
+
+ Typing ??word or word?? gives access to the full information without
snipping long strings. Strings that are longer than the screen are printed
through the less pager.
-
- The ?/?? system gives access to the full source code for any object (if
- available), shows function prototypes and other useful information.
-
- If you just want to see an object's docstring, type '%pdoc object' (without
- quotes, and without % if you have automagic on).
-
+
+ The ?/?? system gives access to the full source code for any object (if
+ available), shows function prototypes and other useful information.
+
+ If you just want to see an object's docstring, type '%pdoc object' (without
+ quotes, and without % if you have automagic on).
+
* Tab completion in the local namespace:
-
- At any time, hitting tab will complete any available python commands or
- variable names, and show you a list of the possible completions if there's
- no unambiguous one. It will also complete filenames in the current directory.
-
+
+ At any time, hitting tab will complete any available python commands or
+ variable names, and show you a list of the possible completions if there's
+ no unambiguous one. It will also complete filenames in the current directory.
+
* Search previous command history in multiple ways:
-
+
- Start typing, and then use arrow keys up/down or (Ctrl-p/Ctrl-n) to search
through the history items that match what you've typed so far.
-
- - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
- your history for lines that match what you've typed so far, completing as
- much as it can.
-
+
+ - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
+ your history for lines that match what you've typed so far, completing as
+ much as it can.
+
- %hist: search history by index.
-
-* Persistent command history across sessions.
-
-* Logging of input with the ability to save and restore a working session.
-
+
+* Persistent command history across sessions.
+
+* Logging of input with the ability to save and restore a working session.
+
* System shell with !. Typing !ls will run 'ls' in the current directory.
-
-* The reload command does a 'deep' reload of a module: changes made to the
- module since you imported will actually be available without having to exit.
-
-* Verbose and colored exception traceback printouts. See the magic xmode and
- xcolor functions for details (just type %magic).
-
-* Input caching system:
-
- IPython offers numbered prompts (In/Out) with input and output caching. All
- input is saved and can be retrieved as variables (besides the usual arrow
- key recall).
-
- The following GLOBAL variables always exist (so don't overwrite them!):
- _i: stores previous input.
- _ii: next previous.
- _iii: next-next previous.
- _ih : a list of all input _ih[n] is the input from line n.
-
- Additionally, global variables named _i<n> are dynamically created (<n>
- being the prompt counter), such that _i<n> == _ih[<n>]
-
- For example, what you typed at prompt 14 is available as _i14 and _ih[14].
-
- You can create macros which contain multiple input lines from this history,
- for later re-execution, with the %macro function.
-
- The history function %hist allows you to see any part of your input history
- by printing a range of the _i variables. Note that inputs which contain
- magic functions (%) appear in the history with a prepended comment. This is
- because they aren't really valid Python code, so you can't exec them.
-
-* Output caching system:
-
- For output that is returned from actions, a system similar to the input
- cache exists but using _ instead of _i. Only actions that produce a result
- (NOT assignments, for example) are cached. If you are familiar with
- Mathematica, IPython's _ variables behave exactly like Mathematica's %
- variables.
-
- The following GLOBAL variables always exist (so don't overwrite them!):
- _ (one underscore): previous output.
- __ (two underscores): next previous.
- ___ (three underscores): next-next previous.
-
- Global variables named _<n> are dynamically created (<n> being the prompt
- counter), such that the result of output <n> is always available as _<n>.
-
- Finally, a global dictionary named _oh exists with entries for all lines
- which generated output.
-
-* Directory history:
-
- Your history of visited directories is kept in the global list _dh, and the
- magic %cd command can be used to go to any entry in that list.
-
-* Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
-
- 1. Auto-parentheses
-
- Callable objects (i.e. functions, methods, etc) can be invoked like
- this (notice the commas between the arguments)::
+
+* The reload command does a 'deep' reload of a module: changes made to the
+ module since you imported will actually be available without having to exit.
+
+* Verbose and colored exception traceback printouts. See the magic xmode and
+ xcolor functions for details (just type %magic).
+
+* Input caching system:
+
+ IPython offers numbered prompts (In/Out) with input and output caching. All
+ input is saved and can be retrieved as variables (besides the usual arrow
+ key recall).
+
+ The following GLOBAL variables always exist (so don't overwrite them!):
+ _i: stores previous input.
+ _ii: next previous.
+ _iii: next-next previous.
+ _ih : a list of all input _ih[n] is the input from line n.
+
+ Additionally, global variables named _i<n> are dynamically created (<n>
+ being the prompt counter), such that _i<n> == _ih[<n>]
+
+ For example, what you typed at prompt 14 is available as _i14 and _ih[14].
+
+ You can create macros which contain multiple input lines from this history,
+ for later re-execution, with the %macro function.
+
+ The history function %hist allows you to see any part of your input history
+ by printing a range of the _i variables. Note that inputs which contain
+ magic functions (%) appear in the history with a prepended comment. This is
+ because they aren't really valid Python code, so you can't exec them.
+
+* Output caching system:
+
+ For output that is returned from actions, a system similar to the input
+ cache exists but using _ instead of _i. Only actions that produce a result
+ (NOT assignments, for example) are cached. If you are familiar with
+ Mathematica, IPython's _ variables behave exactly like Mathematica's %
+ variables.
+
+ The following GLOBAL variables always exist (so don't overwrite them!):
+ _ (one underscore): previous output.
+ __ (two underscores): next previous.
+ ___ (three underscores): next-next previous.
+
+ Global variables named _<n> are dynamically created (<n> being the prompt
+ counter), such that the result of output <n> is always available as _<n>.
+
+ Finally, a global dictionary named _oh exists with entries for all lines
+ which generated output.
+
+* Directory history:
+
+ Your history of visited directories is kept in the global list _dh, and the
+ magic %cd command can be used to go to any entry in that list.
+
+* Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
+
+ 1. Auto-parentheses
- In [1]: callable_ob arg1, arg2, arg3
-
- and the input will be translated to this::
-
- callable_ob(arg1, arg2, arg3)
-
- This feature is off by default (in rare cases it can produce
- undesirable side-effects), but you can activate it at the command-line
- by starting IPython with `--autocall 1`, set it permanently in your
- configuration file, or turn on at runtime with `%autocall 1`.
-
- You can force auto-parentheses by using '/' as the first character
- of a line. For example::
-
- In [1]: /globals # becomes 'globals()'
-
- Note that the '/' MUST be the first character on the line! This
- won't work::
-
- In [2]: print /globals # syntax error
-
- In most cases the automatic algorithm should work, so you should
- rarely need to explicitly invoke /. One notable exception is if you
- are trying to call a function with a list of tuples as arguments (the
- parenthesis will confuse IPython)::
-
- In [1]: zip (1,2,3),(4,5,6) # won't work
-
- but this will work::
-
- In [2]: /zip (1,2,3),(4,5,6)
- ------> zip ((1,2,3),(4,5,6))
- Out[2]= [(1, 4), (2, 5), (3, 6)]
-
- IPython tells you that it has altered your command line by
- displaying the new command line preceded by -->. e.g.::
-
- In [18]: callable list
- -------> callable (list)
-
- 2. Auto-Quoting
-
- You can force auto-quoting of a function's arguments by using ',' as
- the first character of a line. For example::
-
- In [1]: ,my_function /home/me # becomes my_function("/home/me")
-
- If you use ';' instead, the whole argument is quoted as a single
- string (while ',' splits on whitespace)::
-
- In [2]: ,my_function a b c # becomes my_function("a","b","c")
- In [3]: ;my_function a b c # becomes my_function("a b c")
-
- Note that the ',' MUST be the first character on the line! This
- won't work::
-
- In [4]: x = ,my_function /home/me # syntax error
-"""
-
-interactive_usage_min = """\
-An enhanced console for Python.
-Some of its features are:
-- Tab completion in the local namespace.
-- Logging of input, see command-line options.
-- System shell escape via ! , eg !ls.
-- Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
-- Keeps track of locally defined variables via %who, %whos.
-- Show object information with a ? eg ?x or x? (use ?? for more info).
-"""
-
-quick_reference = r"""
-IPython -- An enhanced Interactive Python - Quick Reference Card
-================================================================
-
-obj?, obj?? : Get help, or more help for object (also works as
- ?obj, ??obj).
-?foo.*abc* : List names in 'foo' containing 'abc' in them.
-%magic : Information about IPython's 'magic' % functions.
-
-Magic functions are prefixed by % or %%, and typically take their arguments
-without parentheses, quotes or even commas for convenience. Line magics take a
-single % and cell magics are prefixed with two %%.
-
-Example magic function calls:
-
-%alias d ls -F : 'd' is now an alias for 'ls -F'
-alias d ls -F : Works if 'alias' not a python name
-alist = %alias : Get list of aliases to 'alist'
-cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
-%cd?? : See help AND source for magic %cd
-%timeit x=10 : time the 'x=10' statement with high precision.
-%%timeit x=2**100
-x**100 : time 'x**100' with a setup of 'x=2**100'; setup code is not
- counted. This is an example of a cell magic.
-
-System commands:
-
-!cp a.txt b/ : System command escape, calls os.system()
-cp a.txt b/ : after %rehashx, most system commands work without !
-cp ${f}.txt $bar : Variable expansion in magics and system commands
-files = !ls /usr : Capture sytem command output
-files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
-
-History:
-
-_i, _ii, _iii : Previous, next previous, next next previous input
-_i4, _ih[2:5] : Input history line 4, lines 2-4
-exec _i81 : Execute input history line #81 again
-%rep 81 : Edit input history line #81
-_, __, ___ : previous, next previous, next next previous output
-_dh : Directory history
-_oh : Output history
-%hist : Command history of current session.
-%hist -g foo : Search command history of (almost) all sessions for 'foo'.
-%hist -g : Command history of (almost) all sessions.
-%hist 1/2-8 : Command history containing lines 2-8 of session 1.
-%hist 1/ ~2/ : Command history of session 1 and 2 sessions before current.
-%hist ~8/1-~6/5 : Command history from line 1 of 8 sessions ago to
- line 5 of 6 sessions ago.
-%edit 0/ : Open editor to execute code with history of current session.
-
-Autocall:
-
-f 1,2 : f(1,2) # Off by default, enable with %autocall magic.
-/f 1,2 : f(1,2) (forced autoparen)
-,f 1 2 : f("1","2")
-;f 1 2 : f("1 2")
-
-Remember: TAB completion works in many contexts, not just file names
-or python names.
-
-The following magic functions are currently available:
-
-"""
-
-quick_guide = """\
-? -> Introduction and overview of IPython's features.
-%quickref -> Quick reference.
-help -> Python's own help system.
-object? -> Details about 'object', use 'object??' for extra details.
-"""
-
-default_banner_parts = [
- 'Python %s\n' % (sys.version.split('\n')[0],),
- 'Type "copyright", "credits" or "license" for more information.\n\n',
- 'IPython {version} -- An enhanced Interactive Python.\n'.format(
- version=release.version,
- ),
- quick_guide
-]
-
-default_banner = ''.join(default_banner_parts)
-
+ Callable objects (i.e. functions, methods, etc) can be invoked like
+ this (notice the commas between the arguments)::
+
+ In [1]: callable_ob arg1, arg2, arg3
+
+ and the input will be translated to this::
+
+ callable_ob(arg1, arg2, arg3)
+
+ This feature is off by default (in rare cases it can produce
+ undesirable side-effects), but you can activate it at the command-line
+ by starting IPython with `--autocall 1`, set it permanently in your
+ configuration file, or turn on at runtime with `%autocall 1`.
+
+ You can force auto-parentheses by using '/' as the first character
+ of a line. For example::
+
+ In [1]: /globals # becomes 'globals()'
+
+ Note that the '/' MUST be the first character on the line! This
+ won't work::
+
+ In [2]: print /globals # syntax error
+
+ In most cases the automatic algorithm should work, so you should
+ rarely need to explicitly invoke /. One notable exception is if you
+ are trying to call a function with a list of tuples as arguments (the
+ parenthesis will confuse IPython)::
+
+ In [1]: zip (1,2,3),(4,5,6) # won't work
+
+ but this will work::
+
+ In [2]: /zip (1,2,3),(4,5,6)
+ ------> zip ((1,2,3),(4,5,6))
+ Out[2]= [(1, 4), (2, 5), (3, 6)]
+
+ IPython tells you that it has altered your command line by
+ displaying the new command line preceded by -->. e.g.::
+
+ In [18]: callable list
+ -------> callable (list)
+
+ 2. Auto-Quoting
+
+ You can force auto-quoting of a function's arguments by using ',' as
+ the first character of a line. For example::
+
+ In [1]: ,my_function /home/me # becomes my_function("/home/me")
+
+ If you use ';' instead, the whole argument is quoted as a single
+ string (while ',' splits on whitespace)::
+
+ In [2]: ,my_function a b c # becomes my_function("a","b","c")
+ In [3]: ;my_function a b c # becomes my_function("a b c")
+
+ Note that the ',' MUST be the first character on the line! This
+ won't work::
+
+ In [4]: x = ,my_function /home/me # syntax error
+"""
+
+interactive_usage_min = """\
+An enhanced console for Python.
+Some of its features are:
+- Tab completion in the local namespace.
+- Logging of input, see command-line options.
+- System shell escape via ! , eg !ls.
+- Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
+- Keeps track of locally defined variables via %who, %whos.
+- Show object information with a ? eg ?x or x? (use ?? for more info).
+"""
+
+quick_reference = r"""
+IPython -- An enhanced Interactive Python - Quick Reference Card
+================================================================
+
+obj?, obj?? : Get help, or more help for object (also works as
+ ?obj, ??obj).
+?foo.*abc* : List names in 'foo' containing 'abc' in them.
+%magic : Information about IPython's 'magic' % functions.
+
+Magic functions are prefixed by % or %%, and typically take their arguments
+without parentheses, quotes or even commas for convenience. Line magics take a
+single % and cell magics are prefixed with two %%.
+
+Example magic function calls:
+
+%alias d ls -F : 'd' is now an alias for 'ls -F'
+alias d ls -F : Works if 'alias' not a python name
+alist = %alias : Get list of aliases to 'alist'
+cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
+%cd?? : See help AND source for magic %cd
+%timeit x=10 : time the 'x=10' statement with high precision.
+%%timeit x=2**100
+x**100 : time 'x**100' with a setup of 'x=2**100'; setup code is not
+ counted. This is an example of a cell magic.
+
+System commands:
+
+!cp a.txt b/ : System command escape, calls os.system()
+cp a.txt b/ : after %rehashx, most system commands work without !
+cp ${f}.txt $bar : Variable expansion in magics and system commands
+files = !ls /usr : Capture sytem command output
+files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
+
+History:
+
+_i, _ii, _iii : Previous, next previous, next next previous input
+_i4, _ih[2:5] : Input history line 4, lines 2-4
+exec _i81 : Execute input history line #81 again
+%rep 81 : Edit input history line #81
+_, __, ___ : previous, next previous, next next previous output
+_dh : Directory history
+_oh : Output history
+%hist : Command history of current session.
+%hist -g foo : Search command history of (almost) all sessions for 'foo'.
+%hist -g : Command history of (almost) all sessions.
+%hist 1/2-8 : Command history containing lines 2-8 of session 1.
+%hist 1/ ~2/ : Command history of session 1 and 2 sessions before current.
+%hist ~8/1-~6/5 : Command history from line 1 of 8 sessions ago to
+ line 5 of 6 sessions ago.
+%edit 0/ : Open editor to execute code with history of current session.
+
+Autocall:
+
+f 1,2 : f(1,2) # Off by default, enable with %autocall magic.
+/f 1,2 : f(1,2) (forced autoparen)
+,f 1 2 : f("1","2")
+;f 1 2 : f("1 2")
+
+Remember: TAB completion works in many contexts, not just file names
+or python names.
+
+The following magic functions are currently available:
+
+"""
+
+quick_guide = """\
+? -> Introduction and overview of IPython's features.
+%quickref -> Quick reference.
+help -> Python's own help system.
+object? -> Details about 'object', use 'object??' for extra details.
+"""
+
+default_banner_parts = [
+ 'Python %s\n' % (sys.version.split('\n')[0],),
+ 'Type "copyright", "credits" or "license" for more information.\n\n',
+ 'IPython {version} -- An enhanced Interactive Python.\n'.format(
+ version=release.version,
+ ),
+ quick_guide
+]
+
+default_banner = ''.join(default_banner_parts)
+
# deprecated GUI banner
-
+
default_gui_banner = '\n'.join([
'DEPRECATED: IPython.core.usage.default_gui_banner is deprecated and will be removed',
default_banner,
diff --git a/contrib/python/ipython/py2/IPython/display.py b/contrib/python/ipython/py2/IPython/display.py
index 872b93e92b..7d248ba023 100644
--- a/contrib/python/ipython/py2/IPython/display.py
+++ b/contrib/python/ipython/py2/IPython/display.py
@@ -1,16 +1,16 @@
-"""Public API for display tools in IPython.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2012 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from IPython.core.display import *
-from IPython.lib.display import *
+"""Public API for display tools in IPython.
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2012 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+from IPython.core.display import *
+from IPython.lib.display import *
diff --git a/contrib/python/ipython/py2/IPython/extensions/__init__.py b/contrib/python/ipython/py2/IPython/extensions/__init__.py
index acc4dc7601..db7f79fca6 100644
--- a/contrib/python/ipython/py2/IPython/extensions/__init__.py
+++ b/contrib/python/ipython/py2/IPython/extensions/__init__.py
@@ -1,2 +1,2 @@
-# -*- coding: utf-8 -*-
-"""This directory is meant for IPython extensions."""
+# -*- coding: utf-8 -*-
+"""This directory is meant for IPython extensions."""
diff --git a/contrib/python/ipython/py2/IPython/extensions/autoreload.py b/contrib/python/ipython/py2/IPython/extensions/autoreload.py
index 9406e697d2..d3e420574d 100644
--- a/contrib/python/ipython/py2/IPython/extensions/autoreload.py
+++ b/contrib/python/ipython/py2/IPython/extensions/autoreload.py
@@ -1,536 +1,536 @@
-"""IPython extension to reload modules before executing user code.
-
-``autoreload`` reloads modules automatically before entering the execution of
-code typed at the IPython prompt.
-
-This makes for example the following workflow possible:
-
-.. sourcecode:: ipython
-
- In [1]: %load_ext autoreload
-
- In [2]: %autoreload 2
-
- In [3]: from foo import some_function
-
- In [4]: some_function()
- Out[4]: 42
-
- In [5]: # open foo.py in an editor and change some_function to return 43
-
- In [6]: some_function()
- Out[6]: 43
-
-The module was reloaded without reloading it explicitly, and the object
-imported with ``from foo import ...`` was also updated.
-
-Usage
-=====
-
-The following magic commands are provided:
-
-``%autoreload``
-
- Reload all modules (except those excluded by ``%aimport``)
- automatically now.
-
-``%autoreload 0``
-
- Disable automatic reloading.
-
-``%autoreload 1``
-
- Reload all modules imported with ``%aimport`` every time before
- executing the Python code typed.
-
-``%autoreload 2``
-
- Reload all modules (except those excluded by ``%aimport``) every
- time before executing the Python code typed.
-
-``%aimport``
-
- List modules which are to be automatically imported or not to be imported.
-
-``%aimport foo``
-
- Import module 'foo' and mark it to be autoreloaded for ``%autoreload 1``
-
-``%aimport -foo``
-
- Mark module 'foo' to not be autoreloaded.
-
-Caveats
-=======
-
-Reloading Python modules in a reliable way is in general difficult,
-and unexpected things may occur. ``%autoreload`` tries to work around
-common pitfalls by replacing function code objects and parts of
-classes previously in the module with new versions. This makes the
-following things to work:
-
-- Functions and classes imported via 'from xxx import foo' are upgraded
- to new versions when 'xxx' is reloaded.
-
-- Methods and properties of classes are upgraded on reload, so that
- calling 'c.foo()' on an object 'c' created before the reload causes
- the new code for 'foo' to be executed.
-
-Some of the known remaining caveats are:
-
-- Replacing code objects does not always succeed: changing a @property
- in a class to an ordinary method or a method to a member variable
- can cause problems (but in old objects only).
-
-- Functions that are removed (eg. via monkey-patching) from a module
- before it is reloaded are not upgraded.
-
-- C extension modules cannot be reloaded, and so cannot be autoreloaded.
-"""
-from __future__ import print_function
-
-skip_doctest = True
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2000 Thomas Heller
-# Copyright (C) 2008 Pauli Virtanen <pav@iki.fi>
-# Copyright (C) 2012 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-#
-# This IPython module is written by Pauli Virtanen, based on the autoreload
-# code by Thomas Heller.
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import os
-import sys
-import traceback
-import types
-import weakref
-
-try:
- # Reload is not defined by default in Python3.
- reload
-except NameError:
- from imp import reload
-
-from IPython.utils import openpy
-from IPython.utils.py3compat import PY3
-
-#------------------------------------------------------------------------------
-# Autoreload functionality
-#------------------------------------------------------------------------------
-
-class ModuleReloader(object):
- enabled = False
- """Whether this reloader is enabled"""
-
- check_all = True
- """Autoreload all modules, not just those listed in 'modules'"""
-
- def __init__(self):
- # Modules that failed to reload: {module: mtime-on-failed-reload, ...}
- self.failed = {}
- # Modules specially marked as autoreloadable.
- self.modules = {}
- # Modules specially marked as not autoreloadable.
- self.skip_modules = {}
- # (module-name, name) -> weakref, for replacing old code objects
- self.old_objects = {}
- # Module modification timestamps
- self.modules_mtimes = {}
-
- # Cache module modification times
- self.check(check_all=True, do_reload=False)
-
- def mark_module_skipped(self, module_name):
- """Skip reloading the named module in the future"""
- try:
- del self.modules[module_name]
- except KeyError:
- pass
- self.skip_modules[module_name] = True
-
- def mark_module_reloadable(self, module_name):
- """Reload the named module in the future (if it is imported)"""
- try:
- del self.skip_modules[module_name]
- except KeyError:
- pass
- self.modules[module_name] = True
-
- def aimport_module(self, module_name):
- """Import a module, and mark it reloadable
-
- Returns
- -------
- top_module : module
- The imported module if it is top-level, or the top-level
- top_name : module
- Name of top_module
-
- """
- self.mark_module_reloadable(module_name)
-
- __import__(module_name)
- top_name = module_name.split('.')[0]
- top_module = sys.modules[top_name]
- return top_module, top_name
-
- def filename_and_mtime(self, module):
- if not hasattr(module, '__file__') or module.__file__ is None:
- return None, None
-
+"""IPython extension to reload modules before executing user code.
+
+``autoreload`` reloads modules automatically before entering the execution of
+code typed at the IPython prompt.
+
+This makes for example the following workflow possible:
+
+.. sourcecode:: ipython
+
+ In [1]: %load_ext autoreload
+
+ In [2]: %autoreload 2
+
+ In [3]: from foo import some_function
+
+ In [4]: some_function()
+ Out[4]: 42
+
+ In [5]: # open foo.py in an editor and change some_function to return 43
+
+ In [6]: some_function()
+ Out[6]: 43
+
+The module was reloaded without reloading it explicitly, and the object
+imported with ``from foo import ...`` was also updated.
+
+Usage
+=====
+
+The following magic commands are provided:
+
+``%autoreload``
+
+ Reload all modules (except those excluded by ``%aimport``)
+ automatically now.
+
+``%autoreload 0``
+
+ Disable automatic reloading.
+
+``%autoreload 1``
+
+ Reload all modules imported with ``%aimport`` every time before
+ executing the Python code typed.
+
+``%autoreload 2``
+
+ Reload all modules (except those excluded by ``%aimport``) every
+ time before executing the Python code typed.
+
+``%aimport``
+
+ List modules which are to be automatically imported or not to be imported.
+
+``%aimport foo``
+
+ Import module 'foo' and mark it to be autoreloaded for ``%autoreload 1``
+
+``%aimport -foo``
+
+ Mark module 'foo' to not be autoreloaded.
+
+Caveats
+=======
+
+Reloading Python modules in a reliable way is in general difficult,
+and unexpected things may occur. ``%autoreload`` tries to work around
+common pitfalls by replacing function code objects and parts of
+classes previously in the module with new versions. This makes the
+following things to work:
+
+- Functions and classes imported via 'from xxx import foo' are upgraded
+ to new versions when 'xxx' is reloaded.
+
+- Methods and properties of classes are upgraded on reload, so that
+ calling 'c.foo()' on an object 'c' created before the reload causes
+ the new code for 'foo' to be executed.
+
+Some of the known remaining caveats are:
+
+- Replacing code objects does not always succeed: changing a @property
+ in a class to an ordinary method or a method to a member variable
+ can cause problems (but in old objects only).
+
+- Functions that are removed (eg. via monkey-patching) from a module
+ before it is reloaded are not upgraded.
+
+- C extension modules cannot be reloaded, and so cannot be autoreloaded.
+"""
+from __future__ import print_function
+
+skip_doctest = True
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2000 Thomas Heller
+# Copyright (C) 2008 Pauli Virtanen <pav@iki.fi>
+# Copyright (C) 2012 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+#
+# This IPython module is written by Pauli Virtanen, based on the autoreload
+# code by Thomas Heller.
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import os
+import sys
+import traceback
+import types
+import weakref
+
+try:
+ # Reload is not defined by default in Python3.
+ reload
+except NameError:
+ from imp import reload
+
+from IPython.utils import openpy
+from IPython.utils.py3compat import PY3
+
+#------------------------------------------------------------------------------
+# Autoreload functionality
+#------------------------------------------------------------------------------
+
+class ModuleReloader(object):
+ enabled = False
+ """Whether this reloader is enabled"""
+
+ check_all = True
+ """Autoreload all modules, not just those listed in 'modules'"""
+
+ def __init__(self):
+ # Modules that failed to reload: {module: mtime-on-failed-reload, ...}
+ self.failed = {}
+ # Modules specially marked as autoreloadable.
+ self.modules = {}
+ # Modules specially marked as not autoreloadable.
+ self.skip_modules = {}
+ # (module-name, name) -> weakref, for replacing old code objects
+ self.old_objects = {}
+ # Module modification timestamps
+ self.modules_mtimes = {}
+
+ # Cache module modification times
+ self.check(check_all=True, do_reload=False)
+
+ def mark_module_skipped(self, module_name):
+ """Skip reloading the named module in the future"""
+ try:
+ del self.modules[module_name]
+ except KeyError:
+ pass
+ self.skip_modules[module_name] = True
+
+ def mark_module_reloadable(self, module_name):
+ """Reload the named module in the future (if it is imported)"""
+ try:
+ del self.skip_modules[module_name]
+ except KeyError:
+ pass
+ self.modules[module_name] = True
+
+ def aimport_module(self, module_name):
+ """Import a module, and mark it reloadable
+
+ Returns
+ -------
+ top_module : module
+ The imported module if it is top-level, or the top-level
+ top_name : module
+ Name of top_module
+
+ """
+ self.mark_module_reloadable(module_name)
+
+ __import__(module_name)
+ top_name = module_name.split('.')[0]
+ top_module = sys.modules[top_name]
+ return top_module, top_name
+
+ def filename_and_mtime(self, module):
+ if not hasattr(module, '__file__') or module.__file__ is None:
+ return None, None
+
if getattr(module, '__name__', None) in [None, '__mp_main__', '__main__']:
# we cannot reload(__main__) or reload(__mp_main__)
- return None, None
-
- filename = module.__file__
- path, ext = os.path.splitext(filename)
-
- if ext.lower() == '.py':
- py_filename = filename
- else:
- try:
- py_filename = openpy.source_from_cache(filename)
- except ValueError:
- return None, None
-
- try:
- pymtime = os.stat(py_filename).st_mtime
- except OSError:
- return None, None
-
- return py_filename, pymtime
-
- def check(self, check_all=False, do_reload=True):
- """Check whether some modules need to be reloaded."""
-
- if not self.enabled and not check_all:
- return
-
- if check_all or self.check_all:
- modules = list(sys.modules.keys())
- else:
- modules = list(self.modules.keys())
-
- for modname in modules:
- m = sys.modules.get(modname, None)
-
- if modname in self.skip_modules:
- continue
-
- py_filename, pymtime = self.filename_and_mtime(m)
- if py_filename is None:
- continue
-
- try:
- if pymtime <= self.modules_mtimes[modname]:
- continue
- except KeyError:
- self.modules_mtimes[modname] = pymtime
- continue
- else:
- if self.failed.get(py_filename, None) == pymtime:
- continue
-
- self.modules_mtimes[modname] = pymtime
-
- # If we've reached this point, we should try to reload the module
- if do_reload:
- try:
- superreload(m, reload, self.old_objects)
- if py_filename in self.failed:
- del self.failed[py_filename]
- except:
- print("[autoreload of %s failed: %s]" % (
- modname, traceback.format_exc(1)), file=sys.stderr)
- self.failed[py_filename] = pymtime
-
-#------------------------------------------------------------------------------
-# superreload
-#------------------------------------------------------------------------------
-
-if PY3:
- func_attrs = ['__code__', '__defaults__', '__doc__',
- '__closure__', '__globals__', '__dict__']
-else:
- func_attrs = ['func_code', 'func_defaults', 'func_doc',
- 'func_closure', 'func_globals', 'func_dict']
-
-
-def update_function(old, new):
- """Upgrade the code object of a function"""
- for name in func_attrs:
- try:
- setattr(old, name, getattr(new, name))
- except (AttributeError, TypeError):
- pass
-
-
-def update_class(old, new):
- """Replace stuff in the __dict__ of a class, and upgrade
- method code objects"""
- for key in list(old.__dict__.keys()):
- old_obj = getattr(old, key)
-
- try:
- new_obj = getattr(new, key)
- except AttributeError:
- # obsolete attribute: remove it
- try:
- delattr(old, key)
- except (AttributeError, TypeError):
- pass
- continue
-
- if update_generic(old_obj, new_obj): continue
-
- try:
- setattr(old, key, getattr(new, key))
- except (AttributeError, TypeError):
- pass # skip non-writable attributes
-
-
-def update_property(old, new):
- """Replace get/set/del functions of a property"""
- update_generic(old.fdel, new.fdel)
- update_generic(old.fget, new.fget)
- update_generic(old.fset, new.fset)
-
-
-def isinstance2(a, b, typ):
- return isinstance(a, typ) and isinstance(b, typ)
-
-
-UPDATE_RULES = [
- (lambda a, b: isinstance2(a, b, type),
- update_class),
- (lambda a, b: isinstance2(a, b, types.FunctionType),
- update_function),
- (lambda a, b: isinstance2(a, b, property),
- update_property),
-]
-
-
-if PY3:
- UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.MethodType),
- lambda a, b: update_function(a.__func__, b.__func__)),
- ])
-else:
- UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.ClassType),
- update_class),
- (lambda a, b: isinstance2(a, b, types.MethodType),
- lambda a, b: update_function(a.__func__, b.__func__)),
- ])
-
-
-def update_generic(a, b):
- for type_check, update in UPDATE_RULES:
- if type_check(a, b):
- update(a, b)
- return True
- return False
-
-
-class StrongRef(object):
- def __init__(self, obj):
- self.obj = obj
- def __call__(self):
- return self.obj
-
-
-def superreload(module, reload=reload, old_objects={}):
- """Enhanced version of the builtin reload function.
-
- superreload remembers objects previously in the module, and
-
- - upgrades the class dictionary of every old class in the module
- - upgrades the code object of every old function and method
- - clears the module's namespace before reloading
-
- """
-
- # collect old objects in the module
- for name, obj in list(module.__dict__.items()):
- if not hasattr(obj, '__module__') or obj.__module__ != module.__name__:
- continue
- key = (module.__name__, name)
- try:
- old_objects.setdefault(key, []).append(weakref.ref(obj))
- except TypeError:
- # weakref doesn't work for all types;
- # create strong references for 'important' cases
- if not PY3 and isinstance(obj, types.ClassType):
- old_objects.setdefault(key, []).append(StrongRef(obj))
-
- # reload module
- try:
- # clear namespace first from old cruft
- old_dict = module.__dict__.copy()
- old_name = module.__name__
- module.__dict__.clear()
- module.__dict__['__name__'] = old_name
- module.__dict__['__loader__'] = old_dict['__loader__']
- except (TypeError, AttributeError, KeyError):
- pass
-
- try:
- module = reload(module)
- except:
- # restore module dictionary on failed reload
- module.__dict__.update(old_dict)
- raise
-
- # iterate over all objects and update functions & classes
- for name, new_obj in list(module.__dict__.items()):
- key = (module.__name__, name)
- if key not in old_objects: continue
-
- new_refs = []
- for old_ref in old_objects[key]:
- old_obj = old_ref()
- if old_obj is None: continue
- new_refs.append(old_ref)
- update_generic(old_obj, new_obj)
-
- if new_refs:
- old_objects[key] = new_refs
- else:
- del old_objects[key]
-
- return module
-
-#------------------------------------------------------------------------------
-# IPython connectivity
-#------------------------------------------------------------------------------
-
-from IPython.core.magic import Magics, magics_class, line_magic
-
-@magics_class
-class AutoreloadMagics(Magics):
- def __init__(self, *a, **kw):
- super(AutoreloadMagics, self).__init__(*a, **kw)
- self._reloader = ModuleReloader()
- self._reloader.check_all = False
- self.loaded_modules = set(sys.modules)
-
- @line_magic
- def autoreload(self, parameter_s=''):
- r"""%autoreload => Reload modules automatically
-
- %autoreload
- Reload all modules (except those excluded by %aimport) automatically
- now.
-
- %autoreload 0
- Disable automatic reloading.
-
- %autoreload 1
- Reload all modules imported with %aimport every time before executing
- the Python code typed.
-
- %autoreload 2
- Reload all modules (except those excluded by %aimport) every time
- before executing the Python code typed.
-
- Reloading Python modules in a reliable way is in general
- difficult, and unexpected things may occur. %autoreload tries to
- work around common pitfalls by replacing function code objects and
- parts of classes previously in the module with new versions. This
- makes the following things to work:
-
- - Functions and classes imported via 'from xxx import foo' are upgraded
- to new versions when 'xxx' is reloaded.
-
- - Methods and properties of classes are upgraded on reload, so that
- calling 'c.foo()' on an object 'c' created before the reload causes
- the new code for 'foo' to be executed.
-
- Some of the known remaining caveats are:
-
- - Replacing code objects does not always succeed: changing a @property
- in a class to an ordinary method or a method to a member variable
- can cause problems (but in old objects only).
-
- - Functions that are removed (eg. via monkey-patching) from a module
- before it is reloaded are not upgraded.
-
- - C extension modules cannot be reloaded, and so cannot be
- autoreloaded.
-
- """
- if parameter_s == '':
- self._reloader.check(True)
- elif parameter_s == '0':
- self._reloader.enabled = False
- elif parameter_s == '1':
- self._reloader.check_all = False
- self._reloader.enabled = True
- elif parameter_s == '2':
- self._reloader.check_all = True
- self._reloader.enabled = True
-
- @line_magic
- def aimport(self, parameter_s='', stream=None):
- """%aimport => Import modules for automatic reloading.
-
- %aimport
- List modules to automatically import and not to import.
-
- %aimport foo
- Import module 'foo' and mark it to be autoreloaded for %autoreload 1
-
- %aimport -foo
- Mark module 'foo' to not be autoreloaded for %autoreload 1
- """
- modname = parameter_s
- if not modname:
- to_reload = sorted(self._reloader.modules.keys())
- to_skip = sorted(self._reloader.skip_modules.keys())
- if stream is None:
- stream = sys.stdout
- if self._reloader.check_all:
- stream.write("Modules to reload:\nall-except-skipped\n")
- else:
- stream.write("Modules to reload:\n%s\n" % ' '.join(to_reload))
- stream.write("\nModules to skip:\n%s\n" % ' '.join(to_skip))
- elif modname.startswith('-'):
- modname = modname[1:]
- self._reloader.mark_module_skipped(modname)
- else:
- top_module, top_name = self._reloader.aimport_module(modname)
-
- # Inject module to user namespace
- self.shell.push({top_name: top_module})
-
- def pre_run_cell(self):
- if self._reloader.enabled:
- try:
- self._reloader.check()
- except:
- pass
-
- def post_execute_hook(self):
- """Cache the modification times of any modules imported in this execution
- """
- newly_loaded_modules = set(sys.modules) - self.loaded_modules
- for modname in newly_loaded_modules:
- _, pymtime = self._reloader.filename_and_mtime(sys.modules[modname])
- if pymtime is not None:
- self._reloader.modules_mtimes[modname] = pymtime
-
- self.loaded_modules.update(newly_loaded_modules)
-
-
-def load_ipython_extension(ip):
- """Load the extension in IPython."""
- auto_reload = AutoreloadMagics(ip)
- ip.register_magics(auto_reload)
- ip.events.register('pre_run_cell', auto_reload.pre_run_cell)
- ip.events.register('post_execute', auto_reload.post_execute_hook)
+ return None, None
+
+ filename = module.__file__
+ path, ext = os.path.splitext(filename)
+
+ if ext.lower() == '.py':
+ py_filename = filename
+ else:
+ try:
+ py_filename = openpy.source_from_cache(filename)
+ except ValueError:
+ return None, None
+
+ try:
+ pymtime = os.stat(py_filename).st_mtime
+ except OSError:
+ return None, None
+
+ return py_filename, pymtime
+
+ def check(self, check_all=False, do_reload=True):
+ """Check whether some modules need to be reloaded."""
+
+ if not self.enabled and not check_all:
+ return
+
+ if check_all or self.check_all:
+ modules = list(sys.modules.keys())
+ else:
+ modules = list(self.modules.keys())
+
+ for modname in modules:
+ m = sys.modules.get(modname, None)
+
+ if modname in self.skip_modules:
+ continue
+
+ py_filename, pymtime = self.filename_and_mtime(m)
+ if py_filename is None:
+ continue
+
+ try:
+ if pymtime <= self.modules_mtimes[modname]:
+ continue
+ except KeyError:
+ self.modules_mtimes[modname] = pymtime
+ continue
+ else:
+ if self.failed.get(py_filename, None) == pymtime:
+ continue
+
+ self.modules_mtimes[modname] = pymtime
+
+ # If we've reached this point, we should try to reload the module
+ if do_reload:
+ try:
+ superreload(m, reload, self.old_objects)
+ if py_filename in self.failed:
+ del self.failed[py_filename]
+ except:
+ print("[autoreload of %s failed: %s]" % (
+ modname, traceback.format_exc(1)), file=sys.stderr)
+ self.failed[py_filename] = pymtime
+
+#------------------------------------------------------------------------------
+# superreload
+#------------------------------------------------------------------------------
+
+if PY3:
+ func_attrs = ['__code__', '__defaults__', '__doc__',
+ '__closure__', '__globals__', '__dict__']
+else:
+ func_attrs = ['func_code', 'func_defaults', 'func_doc',
+ 'func_closure', 'func_globals', 'func_dict']
+
+
+def update_function(old, new):
+ """Upgrade the code object of a function"""
+ for name in func_attrs:
+ try:
+ setattr(old, name, getattr(new, name))
+ except (AttributeError, TypeError):
+ pass
+
+
+def update_class(old, new):
+ """Replace stuff in the __dict__ of a class, and upgrade
+ method code objects"""
+ for key in list(old.__dict__.keys()):
+ old_obj = getattr(old, key)
+
+ try:
+ new_obj = getattr(new, key)
+ except AttributeError:
+ # obsolete attribute: remove it
+ try:
+ delattr(old, key)
+ except (AttributeError, TypeError):
+ pass
+ continue
+
+ if update_generic(old_obj, new_obj): continue
+
+ try:
+ setattr(old, key, getattr(new, key))
+ except (AttributeError, TypeError):
+ pass # skip non-writable attributes
+
+
+def update_property(old, new):
+ """Replace get/set/del functions of a property"""
+ update_generic(old.fdel, new.fdel)
+ update_generic(old.fget, new.fget)
+ update_generic(old.fset, new.fset)
+
+
+def isinstance2(a, b, typ):
+ return isinstance(a, typ) and isinstance(b, typ)
+
+
+UPDATE_RULES = [
+ (lambda a, b: isinstance2(a, b, type),
+ update_class),
+ (lambda a, b: isinstance2(a, b, types.FunctionType),
+ update_function),
+ (lambda a, b: isinstance2(a, b, property),
+ update_property),
+]
+
+
+if PY3:
+ UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.MethodType),
+ lambda a, b: update_function(a.__func__, b.__func__)),
+ ])
+else:
+ UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.ClassType),
+ update_class),
+ (lambda a, b: isinstance2(a, b, types.MethodType),
+ lambda a, b: update_function(a.__func__, b.__func__)),
+ ])
+
+
+def update_generic(a, b):
+ for type_check, update in UPDATE_RULES:
+ if type_check(a, b):
+ update(a, b)
+ return True
+ return False
+
+
+class StrongRef(object):
+ def __init__(self, obj):
+ self.obj = obj
+ def __call__(self):
+ return self.obj
+
+
+def superreload(module, reload=reload, old_objects={}):
+ """Enhanced version of the builtin reload function.
+
+ superreload remembers objects previously in the module, and
+
+ - upgrades the class dictionary of every old class in the module
+ - upgrades the code object of every old function and method
+ - clears the module's namespace before reloading
+
+ """
+
+ # collect old objects in the module
+ for name, obj in list(module.__dict__.items()):
+ if not hasattr(obj, '__module__') or obj.__module__ != module.__name__:
+ continue
+ key = (module.__name__, name)
+ try:
+ old_objects.setdefault(key, []).append(weakref.ref(obj))
+ except TypeError:
+ # weakref doesn't work for all types;
+ # create strong references for 'important' cases
+ if not PY3 and isinstance(obj, types.ClassType):
+ old_objects.setdefault(key, []).append(StrongRef(obj))
+
+ # reload module
+ try:
+ # clear namespace first from old cruft
+ old_dict = module.__dict__.copy()
+ old_name = module.__name__
+ module.__dict__.clear()
+ module.__dict__['__name__'] = old_name
+ module.__dict__['__loader__'] = old_dict['__loader__']
+ except (TypeError, AttributeError, KeyError):
+ pass
+
+ try:
+ module = reload(module)
+ except:
+ # restore module dictionary on failed reload
+ module.__dict__.update(old_dict)
+ raise
+
+ # iterate over all objects and update functions & classes
+ for name, new_obj in list(module.__dict__.items()):
+ key = (module.__name__, name)
+ if key not in old_objects: continue
+
+ new_refs = []
+ for old_ref in old_objects[key]:
+ old_obj = old_ref()
+ if old_obj is None: continue
+ new_refs.append(old_ref)
+ update_generic(old_obj, new_obj)
+
+ if new_refs:
+ old_objects[key] = new_refs
+ else:
+ del old_objects[key]
+
+ return module
+
+#------------------------------------------------------------------------------
+# IPython connectivity
+#------------------------------------------------------------------------------
+
+from IPython.core.magic import Magics, magics_class, line_magic
+
+@magics_class
+class AutoreloadMagics(Magics):
+ def __init__(self, *a, **kw):
+ super(AutoreloadMagics, self).__init__(*a, **kw)
+ self._reloader = ModuleReloader()
+ self._reloader.check_all = False
+ self.loaded_modules = set(sys.modules)
+
+ @line_magic
+ def autoreload(self, parameter_s=''):
+ r"""%autoreload => Reload modules automatically
+
+ %autoreload
+ Reload all modules (except those excluded by %aimport) automatically
+ now.
+
+ %autoreload 0
+ Disable automatic reloading.
+
+ %autoreload 1
+ Reload all modules imported with %aimport every time before executing
+ the Python code typed.
+
+ %autoreload 2
+ Reload all modules (except those excluded by %aimport) every time
+ before executing the Python code typed.
+
+ Reloading Python modules in a reliable way is in general
+ difficult, and unexpected things may occur. %autoreload tries to
+ work around common pitfalls by replacing function code objects and
+ parts of classes previously in the module with new versions. This
+ makes the following things to work:
+
+ - Functions and classes imported via 'from xxx import foo' are upgraded
+ to new versions when 'xxx' is reloaded.
+
+ - Methods and properties of classes are upgraded on reload, so that
+ calling 'c.foo()' on an object 'c' created before the reload causes
+ the new code for 'foo' to be executed.
+
+ Some of the known remaining caveats are:
+
+ - Replacing code objects does not always succeed: changing a @property
+ in a class to an ordinary method or a method to a member variable
+ can cause problems (but in old objects only).
+
+ - Functions that are removed (eg. via monkey-patching) from a module
+ before it is reloaded are not upgraded.
+
+ - C extension modules cannot be reloaded, and so cannot be
+ autoreloaded.
+
+ """
+ if parameter_s == '':
+ self._reloader.check(True)
+ elif parameter_s == '0':
+ self._reloader.enabled = False
+ elif parameter_s == '1':
+ self._reloader.check_all = False
+ self._reloader.enabled = True
+ elif parameter_s == '2':
+ self._reloader.check_all = True
+ self._reloader.enabled = True
+
+ @line_magic
+ def aimport(self, parameter_s='', stream=None):
+ """%aimport => Import modules for automatic reloading.
+
+ %aimport
+ List modules to automatically import and not to import.
+
+ %aimport foo
+ Import module 'foo' and mark it to be autoreloaded for %autoreload 1
+
+ %aimport -foo
+ Mark module 'foo' to not be autoreloaded for %autoreload 1
+ """
+ modname = parameter_s
+ if not modname:
+ to_reload = sorted(self._reloader.modules.keys())
+ to_skip = sorted(self._reloader.skip_modules.keys())
+ if stream is None:
+ stream = sys.stdout
+ if self._reloader.check_all:
+ stream.write("Modules to reload:\nall-except-skipped\n")
+ else:
+ stream.write("Modules to reload:\n%s\n" % ' '.join(to_reload))
+ stream.write("\nModules to skip:\n%s\n" % ' '.join(to_skip))
+ elif modname.startswith('-'):
+ modname = modname[1:]
+ self._reloader.mark_module_skipped(modname)
+ else:
+ top_module, top_name = self._reloader.aimport_module(modname)
+
+ # Inject module to user namespace
+ self.shell.push({top_name: top_module})
+
+ def pre_run_cell(self):
+ if self._reloader.enabled:
+ try:
+ self._reloader.check()
+ except:
+ pass
+
+ def post_execute_hook(self):
+ """Cache the modification times of any modules imported in this execution
+ """
+ newly_loaded_modules = set(sys.modules) - self.loaded_modules
+ for modname in newly_loaded_modules:
+ _, pymtime = self._reloader.filename_and_mtime(sys.modules[modname])
+ if pymtime is not None:
+ self._reloader.modules_mtimes[modname] = pymtime
+
+ self.loaded_modules.update(newly_loaded_modules)
+
+
+def load_ipython_extension(ip):
+ """Load the extension in IPython."""
+ auto_reload = AutoreloadMagics(ip)
+ ip.register_magics(auto_reload)
+ ip.events.register('pre_run_cell', auto_reload.pre_run_cell)
+ ip.events.register('post_execute', auto_reload.post_execute_hook)
diff --git a/contrib/python/ipython/py2/IPython/extensions/cythonmagic.py b/contrib/python/ipython/py2/IPython/extensions/cythonmagic.py
index 65c3e39548..3c88e7c2a1 100644
--- a/contrib/python/ipython/py2/IPython/extensions/cythonmagic.py
+++ b/contrib/python/ipython/py2/IPython/extensions/cythonmagic.py
@@ -1,21 +1,21 @@
-# -*- coding: utf-8 -*-
-"""
-**DEPRECATED**
-
-The cython magic has been integrated into Cython itself,
-which is now released in version 0.21.
-
-cf github `Cython` organisation, `Cython` repo, under the
-file `Cython/Build/IpythonMagic.py`
-"""
-#-----------------------------------------------------------------------------
-# Copyright (C) 2010-2011, IPython Development Team.
-#-----------------------------------------------------------------------------
-
-import warnings
-
-## still load the magic in IPython 3.x, remove completely in future versions.
-def load_ipython_extension(ip):
- """Load the extension in IPython."""
-
- warnings.warn("""The Cython magic has been moved to the Cython package""")
+# -*- coding: utf-8 -*-
+"""
+**DEPRECATED**
+
+The cython magic has been integrated into Cython itself,
+which is now released in version 0.21.
+
+cf github `Cython` organisation, `Cython` repo, under the
+file `Cython/Build/IpythonMagic.py`
+"""
+#-----------------------------------------------------------------------------
+# Copyright (C) 2010-2011, IPython Development Team.
+#-----------------------------------------------------------------------------
+
+import warnings
+
+## still load the magic in IPython 3.x, remove completely in future versions.
+def load_ipython_extension(ip):
+ """Load the extension in IPython."""
+
+ warnings.warn("""The Cython magic has been moved to the Cython package""")
diff --git a/contrib/python/ipython/py2/IPython/extensions/rmagic.py b/contrib/python/ipython/py2/IPython/extensions/rmagic.py
index ecc25bc4f8..ec5763972e 100644
--- a/contrib/python/ipython/py2/IPython/extensions/rmagic.py
+++ b/contrib/python/ipython/py2/IPython/extensions/rmagic.py
@@ -1,12 +1,12 @@
-# -*- coding: utf-8 -*-
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2012 The IPython Development Team
-#-----------------------------------------------------------------------------
-
-import warnings
-
-def load_ipython_extension(ip):
- """Load the extension in IPython."""
- warnings.warn("The rmagic extension in IPython has moved to "
- "`rpy2.ipython`, please see `rpy2` documentation.")
+# -*- coding: utf-8 -*-
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2012 The IPython Development Team
+#-----------------------------------------------------------------------------
+
+import warnings
+
+def load_ipython_extension(ip):
+ """Load the extension in IPython."""
+ warnings.warn("The rmagic extension in IPython has moved to "
+ "`rpy2.ipython`, please see `rpy2` documentation.")
diff --git a/contrib/python/ipython/py2/IPython/extensions/storemagic.py b/contrib/python/ipython/py2/IPython/extensions/storemagic.py
index 34371a30f2..2fd1abf993 100644
--- a/contrib/python/ipython/py2/IPython/extensions/storemagic.py
+++ b/contrib/python/ipython/py2/IPython/extensions/storemagic.py
@@ -1,228 +1,228 @@
-# -*- coding: utf-8 -*-
-"""
-%store magic for lightweight persistence.
-
-Stores variables, aliases and macros in IPython's database.
-
-To automatically restore stored variables at startup, add this to your
-:file:`ipython_config.py` file::
-
- c.StoreMagics.autorestore = True
-"""
-from __future__ import print_function
-
+# -*- coding: utf-8 -*-
+"""
+%store magic for lightweight persistence.
+
+Stores variables, aliases and macros in IPython's database.
+
+To automatically restore stored variables at startup, add this to your
+:file:`ipython_config.py` file::
+
+ c.StoreMagics.autorestore = True
+"""
+from __future__ import print_function
+
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
-
-import inspect, os, sys, textwrap
-
-from IPython.core.error import UsageError
-from IPython.core.magic import Magics, magics_class, line_magic
-from traitlets import Bool
-from IPython.utils.py3compat import string_types
-
-
-def restore_aliases(ip):
- staliases = ip.db.get('stored_aliases', {})
- for k,v in staliases.items():
- #print "restore alias",k,v # dbg
- #self.alias_table[k] = v
- ip.alias_manager.define_alias(k,v)
-
-
-def refresh_variables(ip):
- db = ip.db
- for key in db.keys('autorestore/*'):
- # strip autorestore
- justkey = os.path.basename(key)
- try:
- obj = db[key]
- except KeyError:
- print("Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey)
- print("The error was:", sys.exc_info()[0])
- else:
- #print "restored",justkey,"=",obj #dbg
- ip.user_ns[justkey] = obj
-
-
-def restore_dhist(ip):
- ip.user_ns['_dh'] = ip.db.get('dhist',[])
-
-
-def restore_data(ip):
- refresh_variables(ip)
- restore_aliases(ip)
- restore_dhist(ip)
-
-
-@magics_class
-class StoreMagics(Magics):
- """Lightweight persistence for python variables.
-
- Provides the %store magic."""
-
+
+import inspect, os, sys, textwrap
+
+from IPython.core.error import UsageError
+from IPython.core.magic import Magics, magics_class, line_magic
+from traitlets import Bool
+from IPython.utils.py3compat import string_types
+
+
+def restore_aliases(ip):
+ staliases = ip.db.get('stored_aliases', {})
+ for k,v in staliases.items():
+ #print "restore alias",k,v # dbg
+ #self.alias_table[k] = v
+ ip.alias_manager.define_alias(k,v)
+
+
+def refresh_variables(ip):
+ db = ip.db
+ for key in db.keys('autorestore/*'):
+ # strip autorestore
+ justkey = os.path.basename(key)
+ try:
+ obj = db[key]
+ except KeyError:
+ print("Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey)
+ print("The error was:", sys.exc_info()[0])
+ else:
+ #print "restored",justkey,"=",obj #dbg
+ ip.user_ns[justkey] = obj
+
+
+def restore_dhist(ip):
+ ip.user_ns['_dh'] = ip.db.get('dhist',[])
+
+
+def restore_data(ip):
+ refresh_variables(ip)
+ restore_aliases(ip)
+ restore_dhist(ip)
+
+
+@magics_class
+class StoreMagics(Magics):
+ """Lightweight persistence for python variables.
+
+ Provides the %store magic."""
+
autorestore = Bool(False, help=
- """If True, any %store-d variables will be automatically restored
- when IPython starts.
- """
+ """If True, any %store-d variables will be automatically restored
+ when IPython starts.
+ """
).tag(config=True)
-
- def __init__(self, shell):
- super(StoreMagics, self).__init__(shell=shell)
- self.shell.configurables.append(self)
- if self.autorestore:
- restore_data(self.shell)
-
- @line_magic
- def store(self, parameter_s=''):
- """Lightweight persistence for python variables.
-
- Example::
-
- In [1]: l = ['hello',10,'world']
- In [2]: %store l
- In [3]: exit
-
- (IPython session is closed and started again...)
-
- ville@badger:~$ ipython
- In [1]: l
- NameError: name 'l' is not defined
- In [2]: %store -r
- In [3]: l
- Out[3]: ['hello', 10, 'world']
-
- Usage:
-
- * ``%store`` - Show list of all variables and their current
- values
- * ``%store spam`` - Store the *current* value of the variable spam
- to disk
- * ``%store -d spam`` - Remove the variable and its value from storage
- * ``%store -z`` - Remove all variables from storage
- * ``%store -r`` - Refresh all variables from store (overwrite
- current vals)
- * ``%store -r spam bar`` - Refresh specified variables from store
- (delete current val)
- * ``%store foo >a.txt`` - Store value of foo to new file a.txt
- * ``%store foo >>a.txt`` - Append value of foo to file a.txt
-
- It should be noted that if you change the value of a variable, you
- need to %store it again if you want to persist the new value.
-
- Note also that the variables will need to be pickleable; most basic
- python types can be safely %store'd.
-
- Also aliases can be %store'd across sessions.
- """
-
- opts,argsl = self.parse_options(parameter_s,'drz',mode='string')
- args = argsl.split(None,1)
- ip = self.shell
- db = ip.db
- # delete
- if 'd' in opts:
- try:
- todel = args[0]
- except IndexError:
- raise UsageError('You must provide the variable to forget')
- else:
- try:
- del db['autorestore/' + todel]
- except:
- raise UsageError("Can't delete variable '%s'" % todel)
- # reset
- elif 'z' in opts:
- for k in db.keys('autorestore/*'):
- del db[k]
-
- elif 'r' in opts:
- if args:
- for arg in args:
- try:
- obj = db['autorestore/' + arg]
- except KeyError:
- print("no stored variable %s" % arg)
- else:
- ip.user_ns[arg] = obj
- else:
- restore_data(ip)
-
- # run without arguments -> list variables & values
- elif not args:
- vars = db.keys('autorestore/*')
- vars.sort()
- if vars:
- size = max(map(len, vars))
- else:
- size = 0
-
- print('Stored variables and their in-db values:')
- fmt = '%-'+str(size)+'s -> %s'
- get = db.get
- for var in vars:
- justkey = os.path.basename(var)
- # print 30 first characters from every var
- print(fmt % (justkey, repr(get(var, '<unavailable>'))[:50]))
-
- # default action - store the variable
- else:
- # %store foo >file.txt or >>file.txt
- if len(args) > 1 and args[1].startswith('>'):
- fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
- if args[1].startswith('>>'):
- fil = open(fnam, 'a')
- else:
- fil = open(fnam, 'w')
- obj = ip.ev(args[0])
- print("Writing '%s' (%s) to file '%s'." % (args[0],
- obj.__class__.__name__, fnam))
-
-
- if not isinstance (obj, string_types):
- from pprint import pprint
- pprint(obj, fil)
- else:
- fil.write(obj)
- if not obj.endswith('\n'):
- fil.write('\n')
-
- fil.close()
- return
-
- # %store foo
- try:
- obj = ip.user_ns[args[0]]
- except KeyError:
- # it might be an alias
- name = args[0]
- try:
- cmd = ip.alias_manager.retrieve_alias(name)
- except ValueError:
- raise UsageError("Unknown variable '%s'" % name)
-
- staliases = db.get('stored_aliases',{})
- staliases[name] = cmd
- db['stored_aliases'] = staliases
- print("Alias stored: %s (%s)" % (name, cmd))
- return
-
- else:
- modname = getattr(inspect.getmodule(obj), '__name__', '')
- if modname == '__main__':
- print(textwrap.dedent("""\
- Warning:%s is %s
- Proper storage of interactively declared classes (or instances
- of those classes) is not possible! Only instances
- of classes in real modules on file system can be %%store'd.
- """ % (args[0], obj) ))
- return
- #pickled = pickle.dumps(obj)
- db[ 'autorestore/' + args[0] ] = obj
- print("Stored '%s' (%s)" % (args[0], obj.__class__.__name__))
-
-
-def load_ipython_extension(ip):
- """Load the extension in IPython."""
- ip.register_magics(StoreMagics)
-
+
+ def __init__(self, shell):
+ super(StoreMagics, self).__init__(shell=shell)
+ self.shell.configurables.append(self)
+ if self.autorestore:
+ restore_data(self.shell)
+
+ @line_magic
+ def store(self, parameter_s=''):
+ """Lightweight persistence for python variables.
+
+ Example::
+
+ In [1]: l = ['hello',10,'world']
+ In [2]: %store l
+ In [3]: exit
+
+ (IPython session is closed and started again...)
+
+ ville@badger:~$ ipython
+ In [1]: l
+ NameError: name 'l' is not defined
+ In [2]: %store -r
+ In [3]: l
+ Out[3]: ['hello', 10, 'world']
+
+ Usage:
+
+ * ``%store`` - Show list of all variables and their current
+ values
+ * ``%store spam`` - Store the *current* value of the variable spam
+ to disk
+ * ``%store -d spam`` - Remove the variable and its value from storage
+ * ``%store -z`` - Remove all variables from storage
+ * ``%store -r`` - Refresh all variables from store (overwrite
+ current vals)
+ * ``%store -r spam bar`` - Refresh specified variables from store
+ (delete current val)
+ * ``%store foo >a.txt`` - Store value of foo to new file a.txt
+ * ``%store foo >>a.txt`` - Append value of foo to file a.txt
+
+ It should be noted that if you change the value of a variable, you
+ need to %store it again if you want to persist the new value.
+
+ Note also that the variables will need to be pickleable; most basic
+ python types can be safely %store'd.
+
+ Also aliases can be %store'd across sessions.
+ """
+
+ opts,argsl = self.parse_options(parameter_s,'drz',mode='string')
+ args = argsl.split(None,1)
+ ip = self.shell
+ db = ip.db
+ # delete
+ if 'd' in opts:
+ try:
+ todel = args[0]
+ except IndexError:
+ raise UsageError('You must provide the variable to forget')
+ else:
+ try:
+ del db['autorestore/' + todel]
+ except:
+ raise UsageError("Can't delete variable '%s'" % todel)
+ # reset
+ elif 'z' in opts:
+ for k in db.keys('autorestore/*'):
+ del db[k]
+
+ elif 'r' in opts:
+ if args:
+ for arg in args:
+ try:
+ obj = db['autorestore/' + arg]
+ except KeyError:
+ print("no stored variable %s" % arg)
+ else:
+ ip.user_ns[arg] = obj
+ else:
+ restore_data(ip)
+
+ # run without arguments -> list variables & values
+ elif not args:
+ vars = db.keys('autorestore/*')
+ vars.sort()
+ if vars:
+ size = max(map(len, vars))
+ else:
+ size = 0
+
+ print('Stored variables and their in-db values:')
+ fmt = '%-'+str(size)+'s -> %s'
+ get = db.get
+ for var in vars:
+ justkey = os.path.basename(var)
+ # print 30 first characters from every var
+ print(fmt % (justkey, repr(get(var, '<unavailable>'))[:50]))
+
+ # default action - store the variable
+ else:
+ # %store foo >file.txt or >>file.txt
+ if len(args) > 1 and args[1].startswith('>'):
+ fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
+ if args[1].startswith('>>'):
+ fil = open(fnam, 'a')
+ else:
+ fil = open(fnam, 'w')
+ obj = ip.ev(args[0])
+ print("Writing '%s' (%s) to file '%s'." % (args[0],
+ obj.__class__.__name__, fnam))
+
+
+ if not isinstance (obj, string_types):
+ from pprint import pprint
+ pprint(obj, fil)
+ else:
+ fil.write(obj)
+ if not obj.endswith('\n'):
+ fil.write('\n')
+
+ fil.close()
+ return
+
+ # %store foo
+ try:
+ obj = ip.user_ns[args[0]]
+ except KeyError:
+ # it might be an alias
+ name = args[0]
+ try:
+ cmd = ip.alias_manager.retrieve_alias(name)
+ except ValueError:
+ raise UsageError("Unknown variable '%s'" % name)
+
+ staliases = db.get('stored_aliases',{})
+ staliases[name] = cmd
+ db['stored_aliases'] = staliases
+ print("Alias stored: %s (%s)" % (name, cmd))
+ return
+
+ else:
+ modname = getattr(inspect.getmodule(obj), '__name__', '')
+ if modname == '__main__':
+ print(textwrap.dedent("""\
+ Warning:%s is %s
+ Proper storage of interactively declared classes (or instances
+ of those classes) is not possible! Only instances
+ of classes in real modules on file system can be %%store'd.
+ """ % (args[0], obj) ))
+ return
+ #pickled = pickle.dumps(obj)
+ db[ 'autorestore/' + args[0] ] = obj
+ print("Stored '%s' (%s)" % (args[0], obj.__class__.__name__))
+
+
+def load_ipython_extension(ip):
+ """Load the extension in IPython."""
+ ip.register_magics(StoreMagics)
+
diff --git a/contrib/python/ipython/py2/IPython/extensions/sympyprinting.py b/contrib/python/ipython/py2/IPython/extensions/sympyprinting.py
index 1428605ed2..7f9fb2ef98 100644
--- a/contrib/python/ipython/py2/IPython/extensions/sympyprinting.py
+++ b/contrib/python/ipython/py2/IPython/extensions/sympyprinting.py
@@ -1,32 +1,32 @@
-"""
-**DEPRECATED**
-
-A print function that pretty prints sympy Basic objects.
-
-:moduleauthor: Brian Granger
-
-Usage
-=====
-
-Once the extension is loaded, Sympy Basic objects are automatically
-pretty-printed.
-
-As of SymPy 0.7.2, maintenance of this extension has moved to SymPy under
-sympy.interactive.ipythonprinting, any modifications to account for changes to
-SymPy should be submitted to SymPy rather than changed here. This module is
-maintained here for backwards compatablitiy with old SymPy versions.
-
-"""
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008 The IPython Development Team
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import warnings
-
-def load_ipython_extension(ip):
- warnings.warn("The sympyprinting extension has moved to `sympy`, "
- "use `from sympy import init_printing; init_printing()`")
+"""
+**DEPRECATED**
+
+A print function that pretty prints sympy Basic objects.
+
+:moduleauthor: Brian Granger
+
+Usage
+=====
+
+Once the extension is loaded, Sympy Basic objects are automatically
+pretty-printed.
+
+As of SymPy 0.7.2, maintenance of this extension has moved to SymPy under
+sympy.interactive.ipythonprinting, any modifications to account for changes to
+SymPy should be submitted to SymPy rather than changed here. This module is
+maintained here for backwards compatablitiy with old SymPy versions.
+
+"""
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008 The IPython Development Team
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import warnings
+
+def load_ipython_extension(ip):
+ warnings.warn("The sympyprinting extension has moved to `sympy`, "
+ "use `from sympy import init_printing; init_printing()`")
diff --git a/contrib/python/ipython/py2/IPython/external/__init__.py b/contrib/python/ipython/py2/IPython/external/__init__.py
index 5e948bfe1d..3104c19462 100644
--- a/contrib/python/ipython/py2/IPython/external/__init__.py
+++ b/contrib/python/ipython/py2/IPython/external/__init__.py
@@ -1,5 +1,5 @@
-"""
-This package contains all third-party modules bundled with IPython.
-"""
-
-__all__ = ["simplegeneric"]
+"""
+This package contains all third-party modules bundled with IPython.
+"""
+
+__all__ = ["simplegeneric"]
diff --git a/contrib/python/ipython/py2/IPython/external/decorators/__init__.py b/contrib/python/ipython/py2/IPython/external/decorators/__init__.py
index 7aae6b74cd..dd8f52b711 100644
--- a/contrib/python/ipython/py2/IPython/external/decorators/__init__.py
+++ b/contrib/python/ipython/py2/IPython/external/decorators/__init__.py
@@ -1,9 +1,9 @@
-try:
- from numpy.testing.decorators import *
- from numpy.testing.noseclasses import KnownFailure
-except ImportError:
- from ._decorators import *
- try:
- from ._numpy_testing_noseclasses import KnownFailure
- except ImportError:
- pass
+try:
+ from numpy.testing.decorators import *
+ from numpy.testing.noseclasses import KnownFailure
+except ImportError:
+ from ._decorators import *
+ try:
+ from ._numpy_testing_noseclasses import KnownFailure
+ except ImportError:
+ pass
diff --git a/contrib/python/ipython/py2/IPython/external/decorators/_decorators.py b/contrib/python/ipython/py2/IPython/external/decorators/_decorators.py
index b0df539b0b..19de5e5cde 100644
--- a/contrib/python/ipython/py2/IPython/external/decorators/_decorators.py
+++ b/contrib/python/ipython/py2/IPython/external/decorators/_decorators.py
@@ -1,281 +1,281 @@
-"""
-Decorators for labeling and modifying behavior of test objects.
-
-Decorators that merely return a modified version of the original
-function object are straightforward. Decorators that return a new
-function object need to use
-::
-
- nose.tools.make_decorator(original_function)(decorator)
-
-in returning the decorator, in order to preserve meta-data such as
-function name, setup and teardown functions and so on - see
-``nose.tools`` for more information.
-
-"""
-import warnings
-
-# IPython changes: make this work if numpy not available
-# Original code:
-#from numpy.testing.utils import \
-# WarningManager, WarningMessage
-# Our version:
-from ._numpy_testing_utils import WarningManager
-try:
- from ._numpy_testing_noseclasses import KnownFailureTest
-except:
- pass
-
-# End IPython changes
-
-def slow(t):
- """
- Label a test as 'slow'.
-
- The exact definition of a slow test is obviously both subjective and
- hardware-dependent, but in general any individual test that requires more
- than a second or two should be labeled as slow (the whole suite consists of
- thousands of tests, so even a second is significant).
-
- Parameters
- ----------
- t : callable
- The test to label as slow.
-
- Returns
- -------
- t : callable
- The decorated test `t`.
-
- Examples
- --------
- The `numpy.testing` module includes ``import decorators as dec``.
- A test can be decorated as slow like this::
-
- from numpy.testing import *
-
- @dec.slow
- def test_big(self):
- print 'Big, slow test'
-
- """
-
- t.slow = True
- return t
-
-def setastest(tf=True):
- """
- Signals to nose that this function is or is not a test.
-
- Parameters
- ----------
- tf : bool
- If True, specifies that the decorated callable is a test.
- If False, specifies that the decorated callable is not a test.
- Default is True.
-
- Notes
- -----
- This decorator can't use the nose namespace, because it can be
- called from a non-test module. See also ``istest`` and ``nottest`` in
- ``nose.tools``.
-
- Examples
- --------
- `setastest` can be used in the following way::
-
- from numpy.testing.decorators import setastest
-
- @setastest(False)
- def func_with_test_in_name(arg1, arg2):
- pass
-
- """
- def set_test(t):
- t.__test__ = tf
- return t
- return set_test
-
-def skipif(skip_condition, msg=None):
- """
- Make function raise SkipTest exception if a given condition is true.
-
- If the condition is a callable, it is used at runtime to dynamically
- make the decision. This is useful for tests that may require costly
- imports, to delay the cost until the test suite is actually executed.
-
- Parameters
- ----------
- skip_condition : bool or callable
- Flag to determine whether to skip the decorated test.
- msg : str, optional
- Message to give on raising a SkipTest exception. Default is None.
-
- Returns
- -------
- decorator : function
- Decorator which, when applied to a function, causes SkipTest
- to be raised when `skip_condition` is True, and the function
- to be called normally otherwise.
-
- Notes
- -----
- The decorator itself is decorated with the ``nose.tools.make_decorator``
- function in order to transmit function name, and various other metadata.
-
- """
-
- def skip_decorator(f):
- # Local import to avoid a hard nose dependency and only incur the
- # import time overhead at actual test-time.
- import nose
-
- # Allow for both boolean or callable skip conditions.
- if callable(skip_condition):
- skip_val = lambda : skip_condition()
- else:
- skip_val = lambda : skip_condition
-
- def get_msg(func,msg=None):
- """Skip message with information about function being skipped."""
- if msg is None:
- out = 'Test skipped due to test condition'
- else:
- out = '\n'+msg
-
- return "Skipping test: %s%s" % (func.__name__,out)
-
- # We need to define *two* skippers because Python doesn't allow both
- # return with value and yield inside the same function.
- def skipper_func(*args, **kwargs):
- """Skipper for normal test functions."""
- if skip_val():
- raise nose.SkipTest(get_msg(f,msg))
- else:
- return f(*args, **kwargs)
-
- def skipper_gen(*args, **kwargs):
- """Skipper for test generators."""
- if skip_val():
- raise nose.SkipTest(get_msg(f,msg))
- else:
- for x in f(*args, **kwargs):
- yield x
-
- # Choose the right skipper to use when building the actual decorator.
- if nose.util.isgenerator(f):
- skipper = skipper_gen
- else:
- skipper = skipper_func
-
- return nose.tools.make_decorator(f)(skipper)
-
- return skip_decorator
-
-def knownfailureif(fail_condition, msg=None):
- """
- Make function raise KnownFailureTest exception if given condition is true.
-
- If the condition is a callable, it is used at runtime to dynamically
- make the decision. This is useful for tests that may require costly
- imports, to delay the cost until the test suite is actually executed.
-
- Parameters
- ----------
- fail_condition : bool or callable
- Flag to determine whether to mark the decorated test as a known
- failure (if True) or not (if False).
- msg : str, optional
- Message to give on raising a KnownFailureTest exception.
- Default is None.
-
- Returns
- -------
- decorator : function
- Decorator, which, when applied to a function, causes SkipTest
- to be raised when `skip_condition` is True, and the function
- to be called normally otherwise.
-
- Notes
- -----
- The decorator itself is decorated with the ``nose.tools.make_decorator``
- function in order to transmit function name, and various other metadata.
-
- """
- if msg is None:
- msg = 'Test skipped due to known failure'
-
- # Allow for both boolean or callable known failure conditions.
- if callable(fail_condition):
- fail_val = lambda : fail_condition()
- else:
- fail_val = lambda : fail_condition
-
- def knownfail_decorator(f):
- # Local import to avoid a hard nose dependency and only incur the
- # import time overhead at actual test-time.
- import nose
- def knownfailer(*args, **kwargs):
- if fail_val():
- raise KnownFailureTest(msg)
- else:
- return f(*args, **kwargs)
- return nose.tools.make_decorator(f)(knownfailer)
-
- return knownfail_decorator
-
-def deprecated(conditional=True):
- """
- Filter deprecation warnings while running the test suite.
-
- This decorator can be used to filter DeprecationWarning's, to avoid
- printing them during the test suite run, while checking that the test
- actually raises a DeprecationWarning.
-
- Parameters
- ----------
- conditional : bool or callable, optional
- Flag to determine whether to mark test as deprecated or not. If the
- condition is a callable, it is used at runtime to dynamically make the
- decision. Default is True.
-
- Returns
- -------
- decorator : function
- The `deprecated` decorator itself.
-
- Notes
- -----
- .. versionadded:: 1.4.0
-
- """
- def deprecate_decorator(f):
- # Local import to avoid a hard nose dependency and only incur the
- # import time overhead at actual test-time.
- import nose
-
- def _deprecated_imp(*args, **kwargs):
- # Poor man's replacement for the with statement
- ctx = WarningManager(record=True)
- l = ctx.__enter__()
- warnings.simplefilter('always')
- try:
- f(*args, **kwargs)
- if not len(l) > 0:
- raise AssertionError("No warning raised when calling %s"
- % f.__name__)
- if not l[0].category is DeprecationWarning:
- raise AssertionError("First warning for %s is not a " \
- "DeprecationWarning( is %s)" % (f.__name__, l[0]))
- finally:
- ctx.__exit__()
-
- if callable(conditional):
- cond = conditional()
- else:
- cond = conditional
- if cond:
- return nose.tools.make_decorator(f)(_deprecated_imp)
- else:
- return f
- return deprecate_decorator
+"""
+Decorators for labeling and modifying behavior of test objects.
+
+Decorators that merely return a modified version of the original
+function object are straightforward. Decorators that return a new
+function object need to use
+::
+
+ nose.tools.make_decorator(original_function)(decorator)
+
+in returning the decorator, in order to preserve meta-data such as
+function name, setup and teardown functions and so on - see
+``nose.tools`` for more information.
+
+"""
+import warnings
+
+# IPython changes: make this work if numpy not available
+# Original code:
+#from numpy.testing.utils import \
+# WarningManager, WarningMessage
+# Our version:
+from ._numpy_testing_utils import WarningManager
+try:
+ from ._numpy_testing_noseclasses import KnownFailureTest
+except:
+ pass
+
+# End IPython changes
+
+def slow(t):
+ """
+ Label a test as 'slow'.
+
+ The exact definition of a slow test is obviously both subjective and
+ hardware-dependent, but in general any individual test that requires more
+ than a second or two should be labeled as slow (the whole suite consists of
+ thousands of tests, so even a second is significant).
+
+ Parameters
+ ----------
+ t : callable
+ The test to label as slow.
+
+ Returns
+ -------
+ t : callable
+ The decorated test `t`.
+
+ Examples
+ --------
+ The `numpy.testing` module includes ``import decorators as dec``.
+ A test can be decorated as slow like this::
+
+ from numpy.testing import *
+
+ @dec.slow
+ def test_big(self):
+ print 'Big, slow test'
+
+ """
+
+ t.slow = True
+ return t
+
+def setastest(tf=True):
+ """
+ Signals to nose that this function is or is not a test.
+
+ Parameters
+ ----------
+ tf : bool
+ If True, specifies that the decorated callable is a test.
+ If False, specifies that the decorated callable is not a test.
+ Default is True.
+
+ Notes
+ -----
+ This decorator can't use the nose namespace, because it can be
+ called from a non-test module. See also ``istest`` and ``nottest`` in
+ ``nose.tools``.
+
+ Examples
+ --------
+ `setastest` can be used in the following way::
+
+ from numpy.testing.decorators import setastest
+
+ @setastest(False)
+ def func_with_test_in_name(arg1, arg2):
+ pass
+
+ """
+ def set_test(t):
+ t.__test__ = tf
+ return t
+ return set_test
+
+def skipif(skip_condition, msg=None):
+ """
+ Make function raise SkipTest exception if a given condition is true.
+
+ If the condition is a callable, it is used at runtime to dynamically
+ make the decision. This is useful for tests that may require costly
+ imports, to delay the cost until the test suite is actually executed.
+
+ Parameters
+ ----------
+ skip_condition : bool or callable
+ Flag to determine whether to skip the decorated test.
+ msg : str, optional
+ Message to give on raising a SkipTest exception. Default is None.
+
+ Returns
+ -------
+ decorator : function
+ Decorator which, when applied to a function, causes SkipTest
+ to be raised when `skip_condition` is True, and the function
+ to be called normally otherwise.
+
+ Notes
+ -----
+ The decorator itself is decorated with the ``nose.tools.make_decorator``
+ function in order to transmit function name, and various other metadata.
+
+ """
+
+ def skip_decorator(f):
+ # Local import to avoid a hard nose dependency and only incur the
+ # import time overhead at actual test-time.
+ import nose
+
+ # Allow for both boolean or callable skip conditions.
+ if callable(skip_condition):
+ skip_val = lambda : skip_condition()
+ else:
+ skip_val = lambda : skip_condition
+
+ def get_msg(func,msg=None):
+ """Skip message with information about function being skipped."""
+ if msg is None:
+ out = 'Test skipped due to test condition'
+ else:
+ out = '\n'+msg
+
+ return "Skipping test: %s%s" % (func.__name__,out)
+
+ # We need to define *two* skippers because Python doesn't allow both
+ # return with value and yield inside the same function.
+ def skipper_func(*args, **kwargs):
+ """Skipper for normal test functions."""
+ if skip_val():
+ raise nose.SkipTest(get_msg(f,msg))
+ else:
+ return f(*args, **kwargs)
+
+ def skipper_gen(*args, **kwargs):
+ """Skipper for test generators."""
+ if skip_val():
+ raise nose.SkipTest(get_msg(f,msg))
+ else:
+ for x in f(*args, **kwargs):
+ yield x
+
+ # Choose the right skipper to use when building the actual decorator.
+ if nose.util.isgenerator(f):
+ skipper = skipper_gen
+ else:
+ skipper = skipper_func
+
+ return nose.tools.make_decorator(f)(skipper)
+
+ return skip_decorator
+
+def knownfailureif(fail_condition, msg=None):
+ """
+ Make function raise KnownFailureTest exception if given condition is true.
+
+ If the condition is a callable, it is used at runtime to dynamically
+ make the decision. This is useful for tests that may require costly
+ imports, to delay the cost until the test suite is actually executed.
+
+ Parameters
+ ----------
+ fail_condition : bool or callable
+ Flag to determine whether to mark the decorated test as a known
+ failure (if True) or not (if False).
+ msg : str, optional
+ Message to give on raising a KnownFailureTest exception.
+ Default is None.
+
+ Returns
+ -------
+ decorator : function
+ Decorator, which, when applied to a function, causes SkipTest
+ to be raised when `skip_condition` is True, and the function
+ to be called normally otherwise.
+
+ Notes
+ -----
+ The decorator itself is decorated with the ``nose.tools.make_decorator``
+ function in order to transmit function name, and various other metadata.
+
+ """
+ if msg is None:
+ msg = 'Test skipped due to known failure'
+
+ # Allow for both boolean or callable known failure conditions.
+ if callable(fail_condition):
+ fail_val = lambda : fail_condition()
+ else:
+ fail_val = lambda : fail_condition
+
+ def knownfail_decorator(f):
+ # Local import to avoid a hard nose dependency and only incur the
+ # import time overhead at actual test-time.
+ import nose
+ def knownfailer(*args, **kwargs):
+ if fail_val():
+ raise KnownFailureTest(msg)
+ else:
+ return f(*args, **kwargs)
+ return nose.tools.make_decorator(f)(knownfailer)
+
+ return knownfail_decorator
+
+def deprecated(conditional=True):
+ """
+ Filter deprecation warnings while running the test suite.
+
+ This decorator can be used to filter DeprecationWarning's, to avoid
+ printing them during the test suite run, while checking that the test
+ actually raises a DeprecationWarning.
+
+ Parameters
+ ----------
+ conditional : bool or callable, optional
+ Flag to determine whether to mark test as deprecated or not. If the
+ condition is a callable, it is used at runtime to dynamically make the
+ decision. Default is True.
+
+ Returns
+ -------
+ decorator : function
+ The `deprecated` decorator itself.
+
+ Notes
+ -----
+ .. versionadded:: 1.4.0
+
+ """
+ def deprecate_decorator(f):
+ # Local import to avoid a hard nose dependency and only incur the
+ # import time overhead at actual test-time.
+ import nose
+
+ def _deprecated_imp(*args, **kwargs):
+ # Poor man's replacement for the with statement
+ ctx = WarningManager(record=True)
+ l = ctx.__enter__()
+ warnings.simplefilter('always')
+ try:
+ f(*args, **kwargs)
+ if not len(l) > 0:
+ raise AssertionError("No warning raised when calling %s"
+ % f.__name__)
+ if not l[0].category is DeprecationWarning:
+ raise AssertionError("First warning for %s is not a " \
+ "DeprecationWarning( is %s)" % (f.__name__, l[0]))
+ finally:
+ ctx.__exit__()
+
+ if callable(conditional):
+ cond = conditional()
+ else:
+ cond = conditional
+ if cond:
+ return nose.tools.make_decorator(f)(_deprecated_imp)
+ else:
+ return f
+ return deprecate_decorator
diff --git a/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_noseclasses.py b/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_noseclasses.py
index 2b3d2841a7..ca6ccd87bb 100644
--- a/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_noseclasses.py
+++ b/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_noseclasses.py
@@ -1,41 +1,41 @@
-# IPython: modified copy of numpy.testing.noseclasses, so
-# IPython.external._decorators works without numpy being installed.
-
-# These classes implement a "known failure" error class.
-
-import os
-
-from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin
-
-class KnownFailureTest(Exception):
- '''Raise this exception to mark a test as a known failing test.'''
- pass
-
-
-class KnownFailure(ErrorClassPlugin):
- '''Plugin that installs a KNOWNFAIL error class for the
- KnownFailureClass exception. When KnownFailureTest is raised,
- the exception will be logged in the knownfail attribute of the
- result, 'K' or 'KNOWNFAIL' (verbose) will be output, and the
- exception will not be counted as an error or failure.'''
- enabled = True
- knownfail = ErrorClass(KnownFailureTest,
- label='KNOWNFAIL',
- isfailure=False)
-
- def options(self, parser, env=os.environ):
- env_opt = 'NOSE_WITHOUT_KNOWNFAIL'
- parser.add_option('--no-knownfail', action='store_true',
- dest='noKnownFail', default=env.get(env_opt, False),
- help='Disable special handling of KnownFailureTest '
- 'exceptions')
-
- def configure(self, options, conf):
- if not self.can_configure:
- return
- self.conf = conf
- disable = getattr(options, 'noKnownFail', False)
- if disable:
- self.enabled = False
-
-
+# IPython: modified copy of numpy.testing.noseclasses, so
+# IPython.external._decorators works without numpy being installed.
+
+# These classes implement a "known failure" error class.
+
+import os
+
+from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin
+
+class KnownFailureTest(Exception):
+ '''Raise this exception to mark a test as a known failing test.'''
+ pass
+
+
+class KnownFailure(ErrorClassPlugin):
+ '''Plugin that installs a KNOWNFAIL error class for the
+ KnownFailureClass exception. When KnownFailureTest is raised,
+ the exception will be logged in the knownfail attribute of the
+ result, 'K' or 'KNOWNFAIL' (verbose) will be output, and the
+ exception will not be counted as an error or failure.'''
+ enabled = True
+ knownfail = ErrorClass(KnownFailureTest,
+ label='KNOWNFAIL',
+ isfailure=False)
+
+ def options(self, parser, env=os.environ):
+ env_opt = 'NOSE_WITHOUT_KNOWNFAIL'
+ parser.add_option('--no-knownfail', action='store_true',
+ dest='noKnownFail', default=env.get(env_opt, False),
+ help='Disable special handling of KnownFailureTest '
+ 'exceptions')
+
+ def configure(self, options, conf):
+ if not self.can_configure:
+ return
+ self.conf = conf
+ disable = getattr(options, 'noKnownFail', False)
+ if disable:
+ self.enabled = False
+
+
diff --git a/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py b/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py
index d12cba38ac..ad7bd0f981 100644
--- a/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py
+++ b/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py
@@ -1,112 +1,112 @@
-# IPython: modified copy of numpy.testing.utils, so
-# IPython.external._decorators works without numpy being installed.
-"""
-Utility function to facilitate testing.
-"""
-
-import sys
-import warnings
-
-# The following two classes are copied from python 2.6 warnings module (context
-# manager)
-class WarningMessage(object):
-
- """
- Holds the result of a single showwarning() call.
-
- Notes
- -----
- `WarningMessage` is copied from the Python 2.6 warnings module,
- so it can be used in NumPy with older Python versions.
-
- """
-
- _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
- "line")
-
- def __init__(self, message, category, filename, lineno, file=None,
- line=None):
- local_values = locals()
- for attr in self._WARNING_DETAILS:
- setattr(self, attr, local_values[attr])
- if category:
- self._category_name = category.__name__
- else:
- self._category_name = None
-
- def __str__(self):
- return ("{message : %r, category : %r, filename : %r, lineno : %s, "
- "line : %r}" % (self.message, self._category_name,
- self.filename, self.lineno, self.line))
-
-class WarningManager:
- """
- A context manager that copies and restores the warnings filter upon
- exiting the context.
-
- The 'record' argument specifies whether warnings should be captured by a
- custom implementation of ``warnings.showwarning()`` and be appended to a
- list returned by the context manager. Otherwise None is returned by the
- context manager. The objects appended to the list are arguments whose
- attributes mirror the arguments to ``showwarning()``.
-
- The 'module' argument is to specify an alternative module to the module
- named 'warnings' and imported under that name. This argument is only useful
- when testing the warnings module itself.
-
- Notes
- -----
- `WarningManager` is a copy of the ``catch_warnings`` context manager
- from the Python 2.6 warnings module, with slight modifications.
- It is copied so it can be used in NumPy with older Python versions.
-
- """
- def __init__(self, record=False, module=None):
- self._record = record
- if module is None:
- self._module = sys.modules['warnings']
- else:
- self._module = module
- self._entered = False
-
- def __enter__(self):
- if self._entered:
- raise RuntimeError("Cannot enter %r twice" % self)
- self._entered = True
- self._filters = self._module.filters
- self._module.filters = self._filters[:]
- self._showwarning = self._module.showwarning
- if self._record:
- log = []
- def showwarning(*args, **kwargs):
- log.append(WarningMessage(*args, **kwargs))
- self._module.showwarning = showwarning
- return log
- else:
- return None
-
+# IPython: modified copy of numpy.testing.utils, so
+# IPython.external._decorators works without numpy being installed.
+"""
+Utility function to facilitate testing.
+"""
+
+import sys
+import warnings
+
+# The following two classes are copied from python 2.6 warnings module (context
+# manager)
+class WarningMessage(object):
+
+ """
+ Holds the result of a single showwarning() call.
+
+ Notes
+ -----
+ `WarningMessage` is copied from the Python 2.6 warnings module,
+ so it can be used in NumPy with older Python versions.
+
+ """
+
+ _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
+ "line")
+
+ def __init__(self, message, category, filename, lineno, file=None,
+ line=None):
+ local_values = locals()
+ for attr in self._WARNING_DETAILS:
+ setattr(self, attr, local_values[attr])
+ if category:
+ self._category_name = category.__name__
+ else:
+ self._category_name = None
+
+ def __str__(self):
+ return ("{message : %r, category : %r, filename : %r, lineno : %s, "
+ "line : %r}" % (self.message, self._category_name,
+ self.filename, self.lineno, self.line))
+
+class WarningManager:
+ """
+ A context manager that copies and restores the warnings filter upon
+ exiting the context.
+
+ The 'record' argument specifies whether warnings should be captured by a
+ custom implementation of ``warnings.showwarning()`` and be appended to a
+ list returned by the context manager. Otherwise None is returned by the
+ context manager. The objects appended to the list are arguments whose
+ attributes mirror the arguments to ``showwarning()``.
+
+ The 'module' argument is to specify an alternative module to the module
+ named 'warnings' and imported under that name. This argument is only useful
+ when testing the warnings module itself.
+
+ Notes
+ -----
+ `WarningManager` is a copy of the ``catch_warnings`` context manager
+ from the Python 2.6 warnings module, with slight modifications.
+ It is copied so it can be used in NumPy with older Python versions.
+
+ """
+ def __init__(self, record=False, module=None):
+ self._record = record
+ if module is None:
+ self._module = sys.modules['warnings']
+ else:
+ self._module = module
+ self._entered = False
+
+ def __enter__(self):
+ if self._entered:
+ raise RuntimeError("Cannot enter %r twice" % self)
+ self._entered = True
+ self._filters = self._module.filters
+ self._module.filters = self._filters[:]
+ self._showwarning = self._module.showwarning
+ if self._record:
+ log = []
+ def showwarning(*args, **kwargs):
+ log.append(WarningMessage(*args, **kwargs))
+ self._module.showwarning = showwarning
+ return log
+ else:
+ return None
+
def __exit__(self, type_, value, traceback):
- if not self._entered:
- raise RuntimeError("Cannot exit %r without entering first" % self)
- self._module.filters = self._filters
- self._module.showwarning = self._showwarning
-
-def assert_warns(warning_class, func, *args, **kw):
- """Fail unless a warning of class warning_class is thrown by callable when
- invoked with arguments args and keyword arguments kwargs.
-
- If a different type of warning is thrown, it will not be caught, and the
- test case will be deemed to have suffered an error.
- """
-
- # XXX: once we may depend on python >= 2.6, this can be replaced by the
- # warnings module context manager.
+ if not self._entered:
+ raise RuntimeError("Cannot exit %r without entering first" % self)
+ self._module.filters = self._filters
+ self._module.showwarning = self._showwarning
+
+def assert_warns(warning_class, func, *args, **kw):
+ """Fail unless a warning of class warning_class is thrown by callable when
+ invoked with arguments args and keyword arguments kwargs.
+
+ If a different type of warning is thrown, it will not be caught, and the
+ test case will be deemed to have suffered an error.
+ """
+
+ # XXX: once we may depend on python >= 2.6, this can be replaced by the
+ # warnings module context manager.
with WarningManager(record=True) as l:
warnings.simplefilter('always')
- func(*args, **kw)
- if not len(l) > 0:
- raise AssertionError("No warning raised when calling %s"
- % func.__name__)
- if not l[0].category is warning_class:
- raise AssertionError("First warning for %s is not a " \
- "%s( is %s)" % (func.__name__, warning_class, l[0]))
+ func(*args, **kw)
+ if not len(l) > 0:
+ raise AssertionError("No warning raised when calling %s"
+ % func.__name__)
+ if not l[0].category is warning_class:
+ raise AssertionError("First warning for %s is not a " \
+ "%s( is %s)" % (func.__name__, warning_class, l[0]))
diff --git a/contrib/python/ipython/py2/IPython/external/mathjax.py b/contrib/python/ipython/py2/IPython/external/mathjax.py
index c614e46579..1b9b80905b 100644
--- a/contrib/python/ipython/py2/IPython/external/mathjax.py
+++ b/contrib/python/ipython/py2/IPython/external/mathjax.py
@@ -1,13 +1,13 @@
-#!/usr/bin/python
-"""
-`IPython.external.mathjax` is deprecated with IPython 4.0+
-
-mathjax is now install by default with the notebook package
-
-"""
-
-import sys
-
-if __name__ == '__main__' :
- sys.exit("IPython.external.mathjax is deprecated, Mathjax is now installed by default with the notebook package")
-
+#!/usr/bin/python
+"""
+`IPython.external.mathjax` is deprecated with IPython 4.0+
+
+mathjax is now install by default with the notebook package
+
+"""
+
+import sys
+
+if __name__ == '__main__' :
+ sys.exit("IPython.external.mathjax is deprecated, Mathjax is now installed by default with the notebook package")
+
diff --git a/contrib/python/ipython/py2/IPython/external/qt_for_kernel.py b/contrib/python/ipython/py2/IPython/external/qt_for_kernel.py
index fe1dc15dae..1a94e7e0a2 100644
--- a/contrib/python/ipython/py2/IPython/external/qt_for_kernel.py
+++ b/contrib/python/ipython/py2/IPython/external/qt_for_kernel.py
@@ -1,95 +1,95 @@
-""" Import Qt in a manner suitable for an IPython kernel.
-
-This is the import used for the `gui=qt` or `matplotlib=qt` initialization.
-
-Import Priority:
-
-if Qt has been imported anywhere else:
- use that
-
-if matplotlib has been imported and doesn't support v2 (<= 1.0.1):
- use PyQt4 @v1
-
-Next, ask QT_API env variable
-
-if QT_API not set:
- ask matplotlib what it's using. If Qt4Agg or Qt5Agg, then use the
- version matplotlib is configured with
-
- else: (matplotlib said nothing)
- # this is the default path - nobody told us anything
- try in this order:
- PyQt default version, PySide, PyQt5
-else:
- use what QT_API says
-
-"""
-# NOTE: This is no longer an external, third-party module, and should be
-# considered part of IPython. For compatibility however, it is being kept in
-# IPython/external.
-
-import os
-import sys
-
-from IPython.utils.version import check_version
-from IPython.external.qt_loaders import (load_qt, loaded_api, QT_API_PYSIDE,
+""" Import Qt in a manner suitable for an IPython kernel.
+
+This is the import used for the `gui=qt` or `matplotlib=qt` initialization.
+
+Import Priority:
+
+if Qt has been imported anywhere else:
+ use that
+
+if matplotlib has been imported and doesn't support v2 (<= 1.0.1):
+ use PyQt4 @v1
+
+Next, ask QT_API env variable
+
+if QT_API not set:
+ ask matplotlib what it's using. If Qt4Agg or Qt5Agg, then use the
+ version matplotlib is configured with
+
+ else: (matplotlib said nothing)
+ # this is the default path - nobody told us anything
+ try in this order:
+ PyQt default version, PySide, PyQt5
+else:
+ use what QT_API says
+
+"""
+# NOTE: This is no longer an external, third-party module, and should be
+# considered part of IPython. For compatibility however, it is being kept in
+# IPython/external.
+
+import os
+import sys
+
+from IPython.utils.version import check_version
+from IPython.external.qt_loaders import (load_qt, loaded_api, QT_API_PYSIDE,
QT_API_PYSIDE2, QT_API_PYQT, QT_API_PYQT5,
- QT_API_PYQTv1, QT_API_PYQT_DEFAULT)
-
+ QT_API_PYQTv1, QT_API_PYQT_DEFAULT)
+
_qt_apis = (QT_API_PYSIDE, QT_API_PYSIDE2, QT_API_PYQT, QT_API_PYQT5, QT_API_PYQTv1,
- QT_API_PYQT_DEFAULT)
-
-#Constraints placed on an imported matplotlib
-def matplotlib_options(mpl):
- if mpl is None:
- return
- backend = mpl.rcParams.get('backend', None)
- if backend == 'Qt4Agg':
- mpqt = mpl.rcParams.get('backend.qt4', None)
- if mpqt is None:
- return None
- if mpqt.lower() == 'pyside':
- return [QT_API_PYSIDE]
- elif mpqt.lower() == 'pyqt4':
- return [QT_API_PYQT_DEFAULT]
- elif mpqt.lower() == 'pyqt4v2':
- return [QT_API_PYQT]
- raise ImportError("unhandled value for backend.qt4 from matplotlib: %r" %
- mpqt)
- elif backend == 'Qt5Agg':
- mpqt = mpl.rcParams.get('backend.qt5', None)
- if mpqt is None:
- return None
- if mpqt.lower() == 'pyqt5':
- return [QT_API_PYQT5]
- raise ImportError("unhandled value for backend.qt5 from matplotlib: %r" %
- mpqt)
-
-def get_options():
- """Return a list of acceptable QT APIs, in decreasing order of
- preference
- """
- #already imported Qt somewhere. Use that
- loaded = loaded_api()
- if loaded is not None:
- return [loaded]
-
- mpl = sys.modules.get('matplotlib', None)
-
- if mpl is not None and not check_version(mpl.__version__, '1.0.2'):
- #1.0.1 only supports PyQt4 v1
- return [QT_API_PYQT_DEFAULT]
-
- qt_api = os.environ.get('QT_API', None)
- if qt_api is None:
- #no ETS variable. Ask mpl, then use default fallback path
+ QT_API_PYQT_DEFAULT)
+
+#Constraints placed on an imported matplotlib
+def matplotlib_options(mpl):
+ if mpl is None:
+ return
+ backend = mpl.rcParams.get('backend', None)
+ if backend == 'Qt4Agg':
+ mpqt = mpl.rcParams.get('backend.qt4', None)
+ if mpqt is None:
+ return None
+ if mpqt.lower() == 'pyside':
+ return [QT_API_PYSIDE]
+ elif mpqt.lower() == 'pyqt4':
+ return [QT_API_PYQT_DEFAULT]
+ elif mpqt.lower() == 'pyqt4v2':
+ return [QT_API_PYQT]
+ raise ImportError("unhandled value for backend.qt4 from matplotlib: %r" %
+ mpqt)
+ elif backend == 'Qt5Agg':
+ mpqt = mpl.rcParams.get('backend.qt5', None)
+ if mpqt is None:
+ return None
+ if mpqt.lower() == 'pyqt5':
+ return [QT_API_PYQT5]
+ raise ImportError("unhandled value for backend.qt5 from matplotlib: %r" %
+ mpqt)
+
+def get_options():
+ """Return a list of acceptable QT APIs, in decreasing order of
+ preference
+ """
+ #already imported Qt somewhere. Use that
+ loaded = loaded_api()
+ if loaded is not None:
+ return [loaded]
+
+ mpl = sys.modules.get('matplotlib', None)
+
+ if mpl is not None and not check_version(mpl.__version__, '1.0.2'):
+ #1.0.1 only supports PyQt4 v1
+ return [QT_API_PYQT_DEFAULT]
+
+ qt_api = os.environ.get('QT_API', None)
+ if qt_api is None:
+ #no ETS variable. Ask mpl, then use default fallback path
return matplotlib_options(mpl) or [QT_API_PYQT_DEFAULT, QT_API_PYSIDE,
QT_API_PYQT5, QT_API_PYSIDE2]
- elif qt_api not in _qt_apis:
- raise RuntimeError("Invalid Qt API %r, valid values are: %r" %
- (qt_api, ', '.join(_qt_apis)))
- else:
- return [qt_api]
-
-api_opts = get_options()
-QtCore, QtGui, QtSvg, QT_API = load_qt(api_opts)
+ elif qt_api not in _qt_apis:
+ raise RuntimeError("Invalid Qt API %r, valid values are: %r" %
+ (qt_api, ', '.join(_qt_apis)))
+ else:
+ return [qt_api]
+
+api_opts = get_options()
+QtCore, QtGui, QtSvg, QT_API = load_qt(api_opts)
diff --git a/contrib/python/ipython/py2/IPython/external/qt_loaders.py b/contrib/python/ipython/py2/IPython/external/qt_loaders.py
index e9912106e9..3b894fb2ab 100644
--- a/contrib/python/ipython/py2/IPython/external/qt_loaders.py
+++ b/contrib/python/ipython/py2/IPython/external/qt_loaders.py
@@ -1,27 +1,27 @@
-"""
-This module contains factory functions that attempt
-to return Qt submodules from the various python Qt bindings.
-
-It also protects against double-importing Qt with different
-bindings, which is unstable and likely to crash
-
-This is used primarily by qt and qt_for_kernel, and shouldn't
-be accessed directly from the outside
-"""
-import sys
-import types
-from functools import partial
-
-from IPython.utils.version import check_version
-
-# Available APIs.
-QT_API_PYQT = 'pyqt' # Force version 2
-QT_API_PYQT5 = 'pyqt5'
-QT_API_PYQTv1 = 'pyqtv1' # Force version 2
-QT_API_PYQT_DEFAULT = 'pyqtdefault' # use system default for version 1 vs. 2
-QT_API_PYSIDE = 'pyside'
+"""
+This module contains factory functions that attempt
+to return Qt submodules from the various python Qt bindings.
+
+It also protects against double-importing Qt with different
+bindings, which is unstable and likely to crash
+
+This is used primarily by qt and qt_for_kernel, and shouldn't
+be accessed directly from the outside
+"""
+import sys
+import types
+from functools import partial
+
+from IPython.utils.version import check_version
+
+# Available APIs.
+QT_API_PYQT = 'pyqt' # Force version 2
+QT_API_PYQT5 = 'pyqt5'
+QT_API_PYQTv1 = 'pyqtv1' # Force version 2
+QT_API_PYQT_DEFAULT = 'pyqtdefault' # use system default for version 1 vs. 2
+QT_API_PYSIDE = 'pyside'
QT_API_PYSIDE2 = 'pyside2'
-
+
api_to_module = {QT_API_PYSIDE2: 'PySide2',
QT_API_PYSIDE: 'PySide',
QT_API_PYQT: 'PyQt4',
@@ -29,124 +29,124 @@ api_to_module = {QT_API_PYSIDE2: 'PySide2',
QT_API_PYQT5: 'PyQt5',
QT_API_PYQT_DEFAULT: 'PyQt4',
}
-
-
-class ImportDenier(object):
- """Import Hook that will guard against bad Qt imports
- once IPython commits to a specific binding
- """
-
- def __init__(self):
- self.__forbidden = set()
-
- def forbid(self, module_name):
- sys.modules.pop(module_name, None)
- self.__forbidden.add(module_name)
-
- def find_module(self, fullname, path=None):
- if path:
- return
- if fullname in self.__forbidden:
- return self
-
- def load_module(self, fullname):
- raise ImportError("""
- Importing %s disabled by IPython, which has
- already imported an Incompatible QT Binding: %s
- """ % (fullname, loaded_api()))
-
-ID = ImportDenier()
+
+
+class ImportDenier(object):
+ """Import Hook that will guard against bad Qt imports
+ once IPython commits to a specific binding
+ """
+
+ def __init__(self):
+ self.__forbidden = set()
+
+ def forbid(self, module_name):
+ sys.modules.pop(module_name, None)
+ self.__forbidden.add(module_name)
+
+ def find_module(self, fullname, path=None):
+ if path:
+ return
+ if fullname in self.__forbidden:
+ return self
+
+ def load_module(self, fullname):
+ raise ImportError("""
+ Importing %s disabled by IPython, which has
+ already imported an Incompatible QT Binding: %s
+ """ % (fullname, loaded_api()))
+
+ID = ImportDenier()
sys.meta_path.insert(0, ID)
-
-
-def commit_api(api):
- """Commit to a particular API, and trigger ImportErrors on subsequent
- dangerous imports"""
-
+
+
+def commit_api(api):
+ """Commit to a particular API, and trigger ImportErrors on subsequent
+ dangerous imports"""
+
if api == QT_API_PYSIDE2:
ID.forbid('PySide')
ID.forbid('PyQt4')
ID.forbid('PyQt5')
- if api == QT_API_PYSIDE:
+ if api == QT_API_PYSIDE:
ID.forbid('PySide2')
- ID.forbid('PyQt4')
- ID.forbid('PyQt5')
- elif api == QT_API_PYQT5:
+ ID.forbid('PyQt4')
+ ID.forbid('PyQt5')
+ elif api == QT_API_PYQT5:
ID.forbid('PySide2')
- ID.forbid('PySide')
- ID.forbid('PyQt4')
- else: # There are three other possibilities, all representing PyQt4
- ID.forbid('PyQt5')
+ ID.forbid('PySide')
+ ID.forbid('PyQt4')
+ else: # There are three other possibilities, all representing PyQt4
+ ID.forbid('PyQt5')
ID.forbid('PySide2')
- ID.forbid('PySide')
-
-
-def loaded_api():
- """Return which API is loaded, if any
-
- If this returns anything besides None,
- importing any other Qt binding is unsafe.
-
- Returns
- -------
+ ID.forbid('PySide')
+
+
+def loaded_api():
+ """Return which API is loaded, if any
+
+ If this returns anything besides None,
+ importing any other Qt binding is unsafe.
+
+ Returns
+ -------
None, 'pyside2', 'pyside', 'pyqt', 'pyqt5', or 'pyqtv1'
- """
- if 'PyQt4.QtCore' in sys.modules:
- if qtapi_version() == 2:
- return QT_API_PYQT
- else:
- return QT_API_PYQTv1
- elif 'PySide.QtCore' in sys.modules:
- return QT_API_PYSIDE
+ """
+ if 'PyQt4.QtCore' in sys.modules:
+ if qtapi_version() == 2:
+ return QT_API_PYQT
+ else:
+ return QT_API_PYQTv1
+ elif 'PySide.QtCore' in sys.modules:
+ return QT_API_PYSIDE
elif 'PySide2.QtCore' in sys.modules:
return QT_API_PYSIDE2
- elif 'PyQt5.QtCore' in sys.modules:
- return QT_API_PYQT5
- return None
-
-
-def has_binding(api):
+ elif 'PyQt5.QtCore' in sys.modules:
+ return QT_API_PYQT5
+ return None
+
+
+def has_binding(api):
"""Safely check for PyQt4/5, PySide or PySide2, without importing submodules
-
+
Supports Python <= 3.3
- Parameters
- ----------
+ Parameters
+ ----------
api : str [ 'pyqtv1' | 'pyqt' | 'pyqt5' | 'pyside' | 'pyside2' | 'pyqtdefault']
- Which module to check for
-
- Returns
- -------
- True if the relevant module appears to be importable
- """
- # we can't import an incomplete pyside and pyqt4
- # this will cause a crash in sip (#1431)
- # check for complete presence before importing
+ Which module to check for
+
+ Returns
+ -------
+ True if the relevant module appears to be importable
+ """
+ # we can't import an incomplete pyside and pyqt4
+ # this will cause a crash in sip (#1431)
+ # check for complete presence before importing
module_name = api_to_module[api]
-
- import imp
- try:
- #importing top level PyQt4/PySide module is ok...
- mod = __import__(module_name)
- #...importing submodules is not
- imp.find_module('QtCore', mod.__path__)
- imp.find_module('QtGui', mod.__path__)
- imp.find_module('QtSvg', mod.__path__)
+
+ import imp
+ try:
+ #importing top level PyQt4/PySide module is ok...
+ mod = __import__(module_name)
+ #...importing submodules is not
+ imp.find_module('QtCore', mod.__path__)
+ imp.find_module('QtGui', mod.__path__)
+ imp.find_module('QtSvg', mod.__path__)
if api in (QT_API_PYQT5, QT_API_PYSIDE2):
- # QT5 requires QtWidgets too
- imp.find_module('QtWidgets', mod.__path__)
-
- #we can also safely check PySide version
- if api == QT_API_PYSIDE:
- return check_version(mod.__version__, '1.0.3')
- else:
- return True
- except ImportError:
- return False
-
+ # QT5 requires QtWidgets too
+ imp.find_module('QtWidgets', mod.__path__)
+
+ #we can also safely check PySide version
+ if api == QT_API_PYSIDE:
+ return check_version(mod.__version__, '1.0.3')
+ else:
+ return True
+ except ImportError:
+ return False
+
def has_binding_new(api):
"""Safely check for PyQt4/5, PySide or PySide2, without importing submodules
-
+
Supports Python >= 3.4
Parameters
@@ -187,108 +187,108 @@ def has_binding_new(api):
if sys.version_info >= (3, 4):
has_binding = has_binding_new
-def qtapi_version():
- """Return which QString API has been set, if any
-
- Returns
- -------
- The QString API version (1 or 2), or None if not set
- """
- try:
- import sip
- except ImportError:
- return
- try:
- return sip.getapi('QString')
- except ValueError:
- return
-
-
-def can_import(api):
- """Safely query whether an API is importable, without importing it"""
- if not has_binding(api):
- return False
-
- current = loaded_api()
- if api == QT_API_PYQT_DEFAULT:
- return current in [QT_API_PYQT, QT_API_PYQTv1, None]
- else:
- return current in [api, None]
-
-
-def import_pyqt4(version=2):
- """
- Import PyQt4
-
- Parameters
- ----------
- version : 1, 2, or None
- Which QString/QVariant API to use. Set to None to use the system
- default
-
- ImportErrors rasied within this function are non-recoverable
- """
- # The new-style string API (version=2) automatically
- # converts QStrings to Unicode Python strings. Also, automatically unpacks
- # QVariants to their underlying objects.
- import sip
-
- if version is not None:
- sip.setapi('QString', version)
- sip.setapi('QVariant', version)
-
- from PyQt4 import QtGui, QtCore, QtSvg
-
- if not check_version(QtCore.PYQT_VERSION_STR, '4.7'):
- raise ImportError("IPython requires PyQt4 >= 4.7, found %s" %
- QtCore.PYQT_VERSION_STR)
-
- # Alias PyQt-specific functions for PySide compatibility.
- QtCore.Signal = QtCore.pyqtSignal
- QtCore.Slot = QtCore.pyqtSlot
-
- # query for the API version (in case version == None)
- version = sip.getapi('QString')
- api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT
- return QtCore, QtGui, QtSvg, api
-
-
-def import_pyqt5():
- """
- Import PyQt5
-
- ImportErrors rasied within this function are non-recoverable
- """
- import sip
-
- from PyQt5 import QtCore, QtSvg, QtWidgets, QtGui
-
- # Alias PyQt-specific functions for PySide compatibility.
- QtCore.Signal = QtCore.pyqtSignal
- QtCore.Slot = QtCore.pyqtSlot
-
- # Join QtGui and QtWidgets for Qt4 compatibility.
- QtGuiCompat = types.ModuleType('QtGuiCompat')
- QtGuiCompat.__dict__.update(QtGui.__dict__)
- QtGuiCompat.__dict__.update(QtWidgets.__dict__)
-
- api = QT_API_PYQT5
- return QtCore, QtGuiCompat, QtSvg, api
-
-
-def import_pyside():
- """
- Import PySide
-
- ImportErrors raised within this function are non-recoverable
- """
- from PySide import QtGui, QtCore, QtSvg
- return QtCore, QtGui, QtSvg, QT_API_PYSIDE
-
+def qtapi_version():
+ """Return which QString API has been set, if any
+
+ Returns
+ -------
+ The QString API version (1 or 2), or None if not set
+ """
+ try:
+ import sip
+ except ImportError:
+ return
+ try:
+ return sip.getapi('QString')
+ except ValueError:
+ return
+
+
+def can_import(api):
+ """Safely query whether an API is importable, without importing it"""
+ if not has_binding(api):
+ return False
+
+ current = loaded_api()
+ if api == QT_API_PYQT_DEFAULT:
+ return current in [QT_API_PYQT, QT_API_PYQTv1, None]
+ else:
+ return current in [api, None]
+
+
+def import_pyqt4(version=2):
+ """
+ Import PyQt4
+
+ Parameters
+ ----------
+ version : 1, 2, or None
+ Which QString/QVariant API to use. Set to None to use the system
+ default
+
+ ImportErrors rasied within this function are non-recoverable
+ """
+ # The new-style string API (version=2) automatically
+ # converts QStrings to Unicode Python strings. Also, automatically unpacks
+ # QVariants to their underlying objects.
+ import sip
+
+ if version is not None:
+ sip.setapi('QString', version)
+ sip.setapi('QVariant', version)
+
+ from PyQt4 import QtGui, QtCore, QtSvg
+
+ if not check_version(QtCore.PYQT_VERSION_STR, '4.7'):
+ raise ImportError("IPython requires PyQt4 >= 4.7, found %s" %
+ QtCore.PYQT_VERSION_STR)
+
+ # Alias PyQt-specific functions for PySide compatibility.
+ QtCore.Signal = QtCore.pyqtSignal
+ QtCore.Slot = QtCore.pyqtSlot
+
+ # query for the API version (in case version == None)
+ version = sip.getapi('QString')
+ api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT
+ return QtCore, QtGui, QtSvg, api
+
+
+def import_pyqt5():
+ """
+ Import PyQt5
+
+ ImportErrors rasied within this function are non-recoverable
+ """
+ import sip
+
+ from PyQt5 import QtCore, QtSvg, QtWidgets, QtGui
+
+ # Alias PyQt-specific functions for PySide compatibility.
+ QtCore.Signal = QtCore.pyqtSignal
+ QtCore.Slot = QtCore.pyqtSlot
+
+ # Join QtGui and QtWidgets for Qt4 compatibility.
+ QtGuiCompat = types.ModuleType('QtGuiCompat')
+ QtGuiCompat.__dict__.update(QtGui.__dict__)
+ QtGuiCompat.__dict__.update(QtWidgets.__dict__)
+
+ api = QT_API_PYQT5
+ return QtCore, QtGuiCompat, QtSvg, api
+
+
+def import_pyside():
+ """
+ Import PySide
+
+ ImportErrors raised within this function are non-recoverable
+ """
+ from PySide import QtGui, QtCore, QtSvg
+ return QtCore, QtGui, QtSvg, QT_API_PYSIDE
+
def import_pyside2():
"""
Import PySide2
-
+
ImportErrors raised within this function are non-recoverable
"""
from PySide2 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport
@@ -302,71 +302,71 @@ def import_pyside2():
return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE2
-def load_qt(api_options):
- """
- Attempt to import Qt, given a preference list
- of permissible bindings
-
- It is safe to call this function multiple times.
-
- Parameters
- ----------
- api_options: List of strings
+def load_qt(api_options):
+ """
+ Attempt to import Qt, given a preference list
+ of permissible bindings
+
+ It is safe to call this function multiple times.
+
+ Parameters
+ ----------
+ api_options: List of strings
The order of APIs to try. Valid items are 'pyside', 'pyside2',
- 'pyqt', 'pyqt5', 'pyqtv1' and 'pyqtdefault'
-
- Returns
- -------
-
- A tuple of QtCore, QtGui, QtSvg, QT_API
- The first three are the Qt modules. The last is the
- string indicating which module was loaded.
-
- Raises
- ------
- ImportError, if it isn't possible to import any requested
- bindings (either becaues they aren't installed, or because
- an incompatible library has already been installed)
- """
+ 'pyqt', 'pyqt5', 'pyqtv1' and 'pyqtdefault'
+
+ Returns
+ -------
+
+ A tuple of QtCore, QtGui, QtSvg, QT_API
+ The first three are the Qt modules. The last is the
+ string indicating which module was loaded.
+
+ Raises
+ ------
+ ImportError, if it isn't possible to import any requested
+ bindings (either becaues they aren't installed, or because
+ an incompatible library has already been installed)
+ """
loaders = {
QT_API_PYSIDE2: import_pyside2,
QT_API_PYSIDE: import_pyside,
- QT_API_PYQT: import_pyqt4,
- QT_API_PYQT5: import_pyqt5,
- QT_API_PYQTv1: partial(import_pyqt4, version=1),
- QT_API_PYQT_DEFAULT: partial(import_pyqt4, version=None)
+ QT_API_PYQT: import_pyqt4,
+ QT_API_PYQT5: import_pyqt5,
+ QT_API_PYQTv1: partial(import_pyqt4, version=1),
+ QT_API_PYQT_DEFAULT: partial(import_pyqt4, version=None)
}
-
- for api in api_options:
-
- if api not in loaders:
- raise RuntimeError(
- "Invalid Qt API %r, valid values are: %s" %
- (api, ", ".join(["%r" % k for k in loaders.keys()])))
-
- if not can_import(api):
- continue
-
- #cannot safely recover from an ImportError during this
- result = loaders[api]()
- api = result[-1] # changed if api = QT_API_PYQT_DEFAULT
- commit_api(api)
- return result
- else:
- raise ImportError("""
- Could not load requested Qt binding. Please ensure that
+
+ for api in api_options:
+
+ if api not in loaders:
+ raise RuntimeError(
+ "Invalid Qt API %r, valid values are: %s" %
+ (api, ", ".join(["%r" % k for k in loaders.keys()])))
+
+ if not can_import(api):
+ continue
+
+ #cannot safely recover from an ImportError during this
+ result = loaders[api]()
+ api = result[-1] # changed if api = QT_API_PYQT_DEFAULT
+ commit_api(api)
+ return result
+ else:
+ raise ImportError("""
+ Could not load requested Qt binding. Please ensure that
PyQt4 >= 4.7, PyQt5, PySide >= 1.0.3 or PySide2 is available,
- and only one is imported per session.
-
- Currently-imported Qt library: %r
- PyQt4 available (requires QtCore, QtGui, QtSvg): %s
- PyQt5 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s
- PySide >= 1.0.3 installed: %s
+ and only one is imported per session.
+
+ Currently-imported Qt library: %r
+ PyQt4 available (requires QtCore, QtGui, QtSvg): %s
+ PyQt5 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s
+ PySide >= 1.0.3 installed: %s
PySide2 installed: %s
- Tried to load: %r
- """ % (loaded_api(),
- has_binding(QT_API_PYQT),
- has_binding(QT_API_PYQT5),
- has_binding(QT_API_PYSIDE),
+ Tried to load: %r
+ """ % (loaded_api(),
+ has_binding(QT_API_PYQT),
+ has_binding(QT_API_PYQT5),
+ has_binding(QT_API_PYSIDE),
has_binding(QT_API_PYSIDE2),
- api_options))
+ api_options))
diff --git a/contrib/python/ipython/py2/IPython/frontend.py b/contrib/python/ipython/py2/IPython/frontend.py
index d60957b19b..9cc3eaff2f 100644
--- a/contrib/python/ipython/py2/IPython/frontend.py
+++ b/contrib/python/ipython/py2/IPython/frontend.py
@@ -1,29 +1,29 @@
-"""
-Shim to maintain backwards compatibility with old frontend imports.
-
-We have moved all contents of the old `frontend` subpackage into top-level
-subpackages (`html`, `qt` and `terminal`), and flattened the notebook into
-just `IPython.html`, formerly `IPython.frontend.html.notebook`.
-
-This will let code that was making `from IPython.frontend...` calls continue
-working, though a warning will be printed.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import sys
-from warnings import warn
-
-from IPython.utils.shimmodule import ShimModule, ShimWarning
-
+"""
+Shim to maintain backwards compatibility with old frontend imports.
+
+We have moved all contents of the old `frontend` subpackage into top-level
+subpackages (`html`, `qt` and `terminal`), and flattened the notebook into
+just `IPython.html`, formerly `IPython.frontend.html.notebook`.
+
+This will let code that was making `from IPython.frontend...` calls continue
+working, though a warning will be printed.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import sys
+from warnings import warn
+
+from IPython.utils.shimmodule import ShimModule, ShimWarning
+
warn("The top-level `frontend` package has been deprecated since IPython 1.0. "
- "All its subpackages have been moved to the top `IPython` level.", ShimWarning)
-
-# Unconditionally insert the shim into sys.modules so that further import calls
-# trigger the custom attribute access above
-
-sys.modules['IPython.frontend.html.notebook'] = ShimModule(
- src='IPython.frontend.html.notebook', mirror='IPython.html')
-sys.modules['IPython.frontend'] = ShimModule(
- src='IPython.frontend', mirror='IPython')
+ "All its subpackages have been moved to the top `IPython` level.", ShimWarning)
+
+# Unconditionally insert the shim into sys.modules so that further import calls
+# trigger the custom attribute access above
+
+sys.modules['IPython.frontend.html.notebook'] = ShimModule(
+ src='IPython.frontend.html.notebook', mirror='IPython.html')
+sys.modules['IPython.frontend'] = ShimModule(
+ src='IPython.frontend', mirror='IPython')
diff --git a/contrib/python/ipython/py2/IPython/html.py b/contrib/python/ipython/py2/IPython/html.py
index 3e5595d8e6..050be5c599 100644
--- a/contrib/python/ipython/py2/IPython/html.py
+++ b/contrib/python/ipython/py2/IPython/html.py
@@ -1,28 +1,28 @@
-"""
-Shim to maintain backwards compatibility with old IPython.html imports.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import sys
-from warnings import warn
-
-from IPython.utils.shimmodule import ShimModule, ShimWarning
-
+"""
+Shim to maintain backwards compatibility with old IPython.html imports.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import sys
+from warnings import warn
+
+from IPython.utils.shimmodule import ShimModule, ShimWarning
+
warn("The `IPython.html` package has been deprecated since IPython 4.0. "
- "You should import from `notebook` instead. "
- "`IPython.html.widgets` has moved to `ipywidgets`.", ShimWarning)
-
-_widgets = sys.modules['IPython.html.widgets'] = ShimModule(
- src='IPython.html.widgets', mirror='ipywidgets')
-
-_html = ShimModule(
- src='IPython.html', mirror='notebook')
-
-# hook up widgets
-_html.widgets = _widgets
-sys.modules['IPython.html'] = _html
-
-if __name__ == '__main__':
- from notebook import notebookapp as app
- app.launch_new_instance()
+ "You should import from `notebook` instead. "
+ "`IPython.html.widgets` has moved to `ipywidgets`.", ShimWarning)
+
+_widgets = sys.modules['IPython.html.widgets'] = ShimModule(
+ src='IPython.html.widgets', mirror='ipywidgets')
+
+_html = ShimModule(
+ src='IPython.html', mirror='notebook')
+
+# hook up widgets
+_html.widgets = _widgets
+sys.modules['IPython.html'] = _html
+
+if __name__ == '__main__':
+ from notebook import notebookapp as app
+ app.launch_new_instance()
diff --git a/contrib/python/ipython/py2/IPython/kernel/__init__.py b/contrib/python/ipython/py2/IPython/kernel/__init__.py
index 036548fffa..70a05ed4aa 100644
--- a/contrib/python/ipython/py2/IPython/kernel/__init__.py
+++ b/contrib/python/ipython/py2/IPython/kernel/__init__.py
@@ -1,35 +1,35 @@
-"""
-Shim to maintain backwards compatibility with old IPython.kernel imports.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import sys
-from warnings import warn
-
-from IPython.utils.shimmodule import ShimModule, ShimWarning
-
+"""
+Shim to maintain backwards compatibility with old IPython.kernel imports.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import sys
+from warnings import warn
+
+from IPython.utils.shimmodule import ShimModule, ShimWarning
+
warn("The `IPython.kernel` package has been deprecated since IPython 4.0."
- "You should import from ipykernel or jupyter_client instead.", ShimWarning)
-
-
-# zmq subdir is gone
-sys.modules['IPython.kernel.zmq.session'] = ShimModule(
- src='IPython.kernel.zmq.session', mirror='jupyter_client.session')
-sys.modules['IPython.kernel.zmq'] = ShimModule(
- src='IPython.kernel.zmq', mirror='ipykernel')
-
-for pkg in ('comm', 'inprocess'):
- src = 'IPython.kernel.%s' % pkg
- sys.modules[src] = ShimModule(src=src, mirror='ipykernel.%s' % pkg)
-
-for pkg in ('ioloop', 'blocking'):
- src = 'IPython.kernel.%s' % pkg
- sys.modules[src] = ShimModule(src=src, mirror='jupyter_client.%s' % pkg)
-
-# required for `from IPython.kernel import PKG`
-from ipykernel import comm, inprocess
-from jupyter_client import ioloop, blocking
-# public API
-from ipykernel.connect import *
-from jupyter_client import *
+ "You should import from ipykernel or jupyter_client instead.", ShimWarning)
+
+
+# zmq subdir is gone
+sys.modules['IPython.kernel.zmq.session'] = ShimModule(
+ src='IPython.kernel.zmq.session', mirror='jupyter_client.session')
+sys.modules['IPython.kernel.zmq'] = ShimModule(
+ src='IPython.kernel.zmq', mirror='ipykernel')
+
+for pkg in ('comm', 'inprocess'):
+ src = 'IPython.kernel.%s' % pkg
+ sys.modules[src] = ShimModule(src=src, mirror='ipykernel.%s' % pkg)
+
+for pkg in ('ioloop', 'blocking'):
+ src = 'IPython.kernel.%s' % pkg
+ sys.modules[src] = ShimModule(src=src, mirror='jupyter_client.%s' % pkg)
+
+# required for `from IPython.kernel import PKG`
+from ipykernel import comm, inprocess
+from jupyter_client import ioloop, blocking
+# public API
+from ipykernel.connect import *
+from jupyter_client import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/__main__.py b/contrib/python/ipython/py2/IPython/kernel/__main__.py
index adafe73d02..d1f0cf5334 100644
--- a/contrib/python/ipython/py2/IPython/kernel/__main__.py
+++ b/contrib/python/ipython/py2/IPython/kernel/__main__.py
@@ -1,3 +1,3 @@
-if __name__ == '__main__':
- from ipykernel import kernelapp as app
- app.launch_new_instance()
+if __name__ == '__main__':
+ from ipykernel import kernelapp as app
+ app.launch_new_instance()
diff --git a/contrib/python/ipython/py2/IPython/kernel/adapter.py b/contrib/python/ipython/py2/IPython/kernel/adapter.py
index 8a52dbbc2b..3b8c046b2d 100644
--- a/contrib/python/ipython/py2/IPython/kernel/adapter.py
+++ b/contrib/python/ipython/py2/IPython/kernel/adapter.py
@@ -1 +1 @@
-from jupyter_client.adapter import *
+from jupyter_client.adapter import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/channels.py b/contrib/python/ipython/py2/IPython/kernel/channels.py
index f204db9ca3..8c7fe2a063 100644
--- a/contrib/python/ipython/py2/IPython/kernel/channels.py
+++ b/contrib/python/ipython/py2/IPython/kernel/channels.py
@@ -1 +1 @@
-from jupyter_client.channels import *
+from jupyter_client.channels import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/channelsabc.py b/contrib/python/ipython/py2/IPython/kernel/channelsabc.py
index c0a44511b1..88944012d4 100644
--- a/contrib/python/ipython/py2/IPython/kernel/channelsabc.py
+++ b/contrib/python/ipython/py2/IPython/kernel/channelsabc.py
@@ -1 +1 @@
-from jupyter_client.channelsabc import *
+from jupyter_client.channelsabc import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/client.py b/contrib/python/ipython/py2/IPython/kernel/client.py
index d9768e5bc4..a98690b74c 100644
--- a/contrib/python/ipython/py2/IPython/kernel/client.py
+++ b/contrib/python/ipython/py2/IPython/kernel/client.py
@@ -1 +1 @@
-from jupyter_client.client import *
+from jupyter_client.client import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/clientabc.py b/contrib/python/ipython/py2/IPython/kernel/clientabc.py
index e82cb19e2a..e0cf06c942 100644
--- a/contrib/python/ipython/py2/IPython/kernel/clientabc.py
+++ b/contrib/python/ipython/py2/IPython/kernel/clientabc.py
@@ -1 +1 @@
-from jupyter_client.clientabc import *
+from jupyter_client.clientabc import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/connect.py b/contrib/python/ipython/py2/IPython/kernel/connect.py
index be992cc709..5b6d40a5d3 100644
--- a/contrib/python/ipython/py2/IPython/kernel/connect.py
+++ b/contrib/python/ipython/py2/IPython/kernel/connect.py
@@ -1,2 +1,2 @@
-from ipykernel.connect import *
-from jupyter_client.connect import *
+from ipykernel.connect import *
+from jupyter_client.connect import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/kernelspec.py b/contrib/python/ipython/py2/IPython/kernel/kernelspec.py
index 8a64337920..123419b2f5 100644
--- a/contrib/python/ipython/py2/IPython/kernel/kernelspec.py
+++ b/contrib/python/ipython/py2/IPython/kernel/kernelspec.py
@@ -1 +1 @@
-from jupyter_client.kernelspec import *
+from jupyter_client.kernelspec import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/kernelspecapp.py b/contrib/python/ipython/py2/IPython/kernel/kernelspecapp.py
index 16f9f9eba9..28cd33abd3 100644
--- a/contrib/python/ipython/py2/IPython/kernel/kernelspecapp.py
+++ b/contrib/python/ipython/py2/IPython/kernel/kernelspecapp.py
@@ -1 +1 @@
-from jupyter_client.kernelspecapp import *
+from jupyter_client.kernelspecapp import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/launcher.py b/contrib/python/ipython/py2/IPython/kernel/launcher.py
index 0500ab198b..1953bc4809 100644
--- a/contrib/python/ipython/py2/IPython/kernel/launcher.py
+++ b/contrib/python/ipython/py2/IPython/kernel/launcher.py
@@ -1 +1 @@
-from jupyter_client.launcher import *
+from jupyter_client.launcher import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/manager.py b/contrib/python/ipython/py2/IPython/kernel/manager.py
index 9d9d84806f..c88097cff6 100644
--- a/contrib/python/ipython/py2/IPython/kernel/manager.py
+++ b/contrib/python/ipython/py2/IPython/kernel/manager.py
@@ -1 +1 @@
-from jupyter_client.manager import *
+from jupyter_client.manager import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/managerabc.py b/contrib/python/ipython/py2/IPython/kernel/managerabc.py
index f748bdf2ce..6b40827ff8 100644
--- a/contrib/python/ipython/py2/IPython/kernel/managerabc.py
+++ b/contrib/python/ipython/py2/IPython/kernel/managerabc.py
@@ -1 +1 @@
-from jupyter_client.managerabc import *
+from jupyter_client.managerabc import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/multikernelmanager.py b/contrib/python/ipython/py2/IPython/kernel/multikernelmanager.py
index 71fd8dbb34..ce576e27ea 100644
--- a/contrib/python/ipython/py2/IPython/kernel/multikernelmanager.py
+++ b/contrib/python/ipython/py2/IPython/kernel/multikernelmanager.py
@@ -1 +1 @@
-from jupyter_client.multikernelmanager import *
+from jupyter_client.multikernelmanager import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/restarter.py b/contrib/python/ipython/py2/IPython/kernel/restarter.py
index 2b1de99c8e..dc24117c3a 100644
--- a/contrib/python/ipython/py2/IPython/kernel/restarter.py
+++ b/contrib/python/ipython/py2/IPython/kernel/restarter.py
@@ -1 +1 @@
-from jupyter_client.restarter import *
+from jupyter_client.restarter import *
diff --git a/contrib/python/ipython/py2/IPython/kernel/threaded.py b/contrib/python/ipython/py2/IPython/kernel/threaded.py
index 97997eeb70..4a1072f7fe 100644
--- a/contrib/python/ipython/py2/IPython/kernel/threaded.py
+++ b/contrib/python/ipython/py2/IPython/kernel/threaded.py
@@ -1 +1 @@
-from jupyter_client.threaded import *
+from jupyter_client.threaded import *
diff --git a/contrib/python/ipython/py2/IPython/lib/__init__.py b/contrib/python/ipython/py2/IPython/lib/__init__.py
index 21e34d84ca..8eb89012df 100644
--- a/contrib/python/ipython/py2/IPython/lib/__init__.py
+++ b/contrib/python/ipython/py2/IPython/lib/__init__.py
@@ -1,21 +1,21 @@
-# encoding: utf-8
-"""
-Extra capabilities for IPython
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from IPython.lib.security import passwd
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
+# encoding: utf-8
+"""
+Extra capabilities for IPython
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+from IPython.lib.security import passwd
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
diff --git a/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py b/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py
index 1acfe7df1e..b724126bbb 100644
--- a/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py
+++ b/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py
@@ -1,491 +1,491 @@
-# -*- coding: utf-8 -*-
-"""Manage background (threaded) jobs conveniently from an interactive shell.
-
-This module provides a BackgroundJobManager class. This is the main class
-meant for public usage, it implements an object which can create and manage
-new background jobs.
-
-It also provides the actual job classes managed by these BackgroundJobManager
-objects, see their docstrings below.
-
-
-This system was inspired by discussions with B. Granger and the
-BackgroundCommand class described in the book Python Scripting for
-Computational Science, by H. P. Langtangen:
-
-http://folk.uio.no/hpl/scripting
-
-(although ultimately no code from this text was used, as IPython's system is a
-separate implementation).
-
-An example notebook is provided in our documentation illustrating interactive
-use of the system.
-"""
-from __future__ import print_function
-
-#*****************************************************************************
-# Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#*****************************************************************************
-
-# Code begins
-import sys
-import threading
-
-from IPython import get_ipython
-from IPython.core.ultratb import AutoFormattedTB
+# -*- coding: utf-8 -*-
+"""Manage background (threaded) jobs conveniently from an interactive shell.
+
+This module provides a BackgroundJobManager class. This is the main class
+meant for public usage, it implements an object which can create and manage
+new background jobs.
+
+It also provides the actual job classes managed by these BackgroundJobManager
+objects, see their docstrings below.
+
+
+This system was inspired by discussions with B. Granger and the
+BackgroundCommand class described in the book Python Scripting for
+Computational Science, by H. P. Langtangen:
+
+http://folk.uio.no/hpl/scripting
+
+(although ultimately no code from this text was used, as IPython's system is a
+separate implementation).
+
+An example notebook is provided in our documentation illustrating interactive
+use of the system.
+"""
+from __future__ import print_function
+
+#*****************************************************************************
+# Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#*****************************************************************************
+
+# Code begins
+import sys
+import threading
+
+from IPython import get_ipython
+from IPython.core.ultratb import AutoFormattedTB
from logging import error
-from IPython.utils.py3compat import string_types
-
-
-class BackgroundJobManager(object):
- """Class to manage a pool of backgrounded threaded jobs.
-
- Below, we assume that 'jobs' is a BackgroundJobManager instance.
-
- Usage summary (see the method docstrings for details):
-
- jobs.new(...) -> start a new job
-
- jobs() or jobs.status() -> print status summary of all jobs
-
- jobs[N] -> returns job number N.
-
- foo = jobs[N].result -> assign to variable foo the result of job N
-
- jobs[N].traceback() -> print the traceback of dead job N
-
- jobs.remove(N) -> remove (finished) job N
-
- jobs.flush() -> remove all finished jobs
-
- As a convenience feature, BackgroundJobManager instances provide the
- utility result and traceback methods which retrieve the corresponding
- information from the jobs list:
-
- jobs.result(N) <--> jobs[N].result
- jobs.traceback(N) <--> jobs[N].traceback()
-
- While this appears minor, it allows you to use tab completion
- interactively on the job manager instance.
- """
-
- def __init__(self):
- # Lists for job management, accessed via a property to ensure they're
- # up to date.x
- self._running = []
- self._completed = []
- self._dead = []
- # A dict of all jobs, so users can easily access any of them
- self.all = {}
- # For reporting
- self._comp_report = []
- self._dead_report = []
- # Store status codes locally for fast lookups
- self._s_created = BackgroundJobBase.stat_created_c
- self._s_running = BackgroundJobBase.stat_running_c
- self._s_completed = BackgroundJobBase.stat_completed_c
- self._s_dead = BackgroundJobBase.stat_dead_c
-
- @property
- def running(self):
- self._update_status()
- return self._running
-
- @property
- def dead(self):
- self._update_status()
- return self._dead
-
- @property
- def completed(self):
- self._update_status()
- return self._completed
-
- def new(self, func_or_exp, *args, **kwargs):
- """Add a new background job and start it in a separate thread.
-
- There are two types of jobs which can be created:
-
- 1. Jobs based on expressions which can be passed to an eval() call.
- The expression must be given as a string. For example:
-
- job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])
-
- The given expression is passed to eval(), along with the optional
- global/local dicts provided. If no dicts are given, they are
- extracted automatically from the caller's frame.
-
- A Python statement is NOT a valid eval() expression. Basically, you
- can only use as an eval() argument something which can go on the right
- of an '=' sign and be assigned to a variable.
-
- For example,"print 'hello'" is not valid, but '2+3' is.
-
- 2. Jobs given a function object, optionally passing additional
- positional arguments:
-
- job_manager.new(myfunc, x, y)
-
- The function is called with the given arguments.
-
- If you need to pass keyword arguments to your function, you must
- supply them as a dict named kw:
-
- job_manager.new(myfunc, x, y, kw=dict(z=1))
-
- The reason for this assymmetry is that the new() method needs to
- maintain access to its own keywords, and this prevents name collisions
- between arguments to new() and arguments to your own functions.
-
- In both cases, the result is stored in the job.result field of the
- background job object.
-
- You can set `daemon` attribute of the thread by giving the keyword
- argument `daemon`.
-
- Notes and caveats:
-
- 1. All threads running share the same standard output. Thus, if your
- background jobs generate output, it will come out on top of whatever
- you are currently writing. For this reason, background jobs are best
- used with silent functions which simply return their output.
-
- 2. Threads also all work within the same global namespace, and this
- system does not lock interactive variables. So if you send job to the
- background which operates on a mutable object for a long time, and
- start modifying that same mutable object interactively (or in another
- backgrounded job), all sorts of bizarre behaviour will occur.
-
- 3. If a background job is spending a lot of time inside a C extension
- module which does not release the Python Global Interpreter Lock
- (GIL), this will block the IPython prompt. This is simply because the
- Python interpreter can only switch between threads at Python
- bytecodes. While the execution is inside C code, the interpreter must
- simply wait unless the extension module releases the GIL.
-
- 4. There is no way, due to limitations in the Python threads library,
- to kill a thread once it has started."""
-
- if callable(func_or_exp):
- kw = kwargs.get('kw',{})
- job = BackgroundJobFunc(func_or_exp,*args,**kw)
- elif isinstance(func_or_exp, string_types):
- if not args:
- frame = sys._getframe(1)
- glob, loc = frame.f_globals, frame.f_locals
- elif len(args)==1:
- glob = loc = args[0]
- elif len(args)==2:
- glob,loc = args
- else:
- raise ValueError(
- 'Expression jobs take at most 2 args (globals,locals)')
- job = BackgroundJobExpr(func_or_exp, glob, loc)
- else:
- raise TypeError('invalid args for new job')
-
- if kwargs.get('daemon', False):
- job.daemon = True
- job.num = len(self.all)+1 if self.all else 0
- self.running.append(job)
- self.all[job.num] = job
- print('Starting job # %s in a separate thread.' % job.num)
- job.start()
- return job
-
- def __getitem__(self, job_key):
- num = job_key if isinstance(job_key, int) else job_key.num
- return self.all[num]
-
- def __call__(self):
- """An alias to self.status(),
-
- This allows you to simply call a job manager instance much like the
- Unix `jobs` shell command."""
-
- return self.status()
-
- def _update_status(self):
- """Update the status of the job lists.
-
- This method moves finished jobs to one of two lists:
- - self.completed: jobs which completed successfully
- - self.dead: jobs which finished but died.
-
- It also copies those jobs to corresponding _report lists. These lists
- are used to report jobs completed/dead since the last update, and are
- then cleared by the reporting function after each call."""
-
- # Status codes
- srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead
- # State lists, use the actual lists b/c the public names are properties
- # that call this very function on access
- running, completed, dead = self._running, self._completed, self._dead
-
- # Now, update all state lists
- for num, job in enumerate(running):
- stat = job.stat_code
- if stat == srun:
- continue
- elif stat == scomp:
- completed.append(job)
- self._comp_report.append(job)
- running[num] = False
- elif stat == sdead:
- dead.append(job)
- self._dead_report.append(job)
- running[num] = False
- # Remove dead/completed jobs from running list
- running[:] = filter(None, running)
-
- def _group_report(self,group,name):
- """Report summary for a given job group.
-
- Return True if the group had any elements."""
-
- if group:
- print('%s jobs:' % name)
- for job in group:
- print('%s : %s' % (job.num,job))
- print()
- return True
-
- def _group_flush(self,group,name):
- """Flush a given job group
-
- Return True if the group had any elements."""
-
- njobs = len(group)
- if njobs:
- plural = {1:''}.setdefault(njobs,'s')
- print('Flushing %s %s job%s.' % (njobs,name,plural))
- group[:] = []
- return True
-
- def _status_new(self):
- """Print the status of newly finished jobs.
-
- Return True if any new jobs are reported.
-
- This call resets its own state every time, so it only reports jobs
- which have finished since the last time it was called."""
-
- self._update_status()
- new_comp = self._group_report(self._comp_report, 'Completed')
- new_dead = self._group_report(self._dead_report,
- 'Dead, call jobs.traceback() for details')
- self._comp_report[:] = []
- self._dead_report[:] = []
- return new_comp or new_dead
-
- def status(self,verbose=0):
- """Print a status of all jobs currently being managed."""
-
- self._update_status()
- self._group_report(self.running,'Running')
- self._group_report(self.completed,'Completed')
- self._group_report(self.dead,'Dead')
- # Also flush the report queues
- self._comp_report[:] = []
- self._dead_report[:] = []
-
- def remove(self,num):
- """Remove a finished (completed or dead) job."""
-
- try:
- job = self.all[num]
- except KeyError:
- error('Job #%s not found' % num)
- else:
- stat_code = job.stat_code
- if stat_code == self._s_running:
- error('Job #%s is still running, it can not be removed.' % num)
- return
- elif stat_code == self._s_completed:
- self.completed.remove(job)
- elif stat_code == self._s_dead:
- self.dead.remove(job)
-
- def flush(self):
- """Flush all finished jobs (completed and dead) from lists.
-
- Running jobs are never flushed.
-
- It first calls _status_new(), to update info. If any jobs have
- completed since the last _status_new() call, the flush operation
- aborts."""
-
- # Remove the finished jobs from the master dict
- alljobs = self.all
- for job in self.completed+self.dead:
- del(alljobs[job.num])
-
- # Now flush these lists completely
- fl_comp = self._group_flush(self.completed, 'Completed')
- fl_dead = self._group_flush(self.dead, 'Dead')
- if not (fl_comp or fl_dead):
- print('No jobs to flush.')
-
- def result(self,num):
- """result(N) -> return the result of job N."""
- try:
- return self.all[num].result
- except KeyError:
- error('Job #%s not found' % num)
-
- def _traceback(self, job):
- num = job if isinstance(job, int) else job.num
- try:
- self.all[num].traceback()
- except KeyError:
- error('Job #%s not found' % num)
-
- def traceback(self, job=None):
- if job is None:
- self._update_status()
- for deadjob in self.dead:
- print("Traceback for: %r" % deadjob)
- self._traceback(deadjob)
- print()
- else:
- self._traceback(job)
-
-
-class BackgroundJobBase(threading.Thread):
- """Base class to build BackgroundJob classes.
-
- The derived classes must implement:
-
- - Their own __init__, since the one here raises NotImplementedError. The
- derived constructor must call self._init() at the end, to provide common
- initialization.
-
- - A strform attribute used in calls to __str__.
-
- - A call() method, which will make the actual execution call and must
- return a value to be held in the 'result' field of the job object.
- """
-
- # Class constants for status, in string and as numerical codes (when
- # updating jobs lists, we don't want to do string comparisons). This will
- # be done at every user prompt, so it has to be as fast as possible
- stat_created = 'Created'; stat_created_c = 0
- stat_running = 'Running'; stat_running_c = 1
- stat_completed = 'Completed'; stat_completed_c = 2
- stat_dead = 'Dead (Exception), call jobs.traceback() for details'
- stat_dead_c = -1
-
- def __init__(self):
- """Must be implemented in subclasses.
-
- Subclasses must call :meth:`_init` for standard initialisation.
- """
- raise NotImplementedError("This class can not be instantiated directly.")
-
- def _init(self):
- """Common initialization for all BackgroundJob objects"""
-
- for attr in ['call','strform']:
- assert hasattr(self,attr), "Missing attribute <%s>" % attr
-
- # The num tag can be set by an external job manager
- self.num = None
-
- self.status = BackgroundJobBase.stat_created
- self.stat_code = BackgroundJobBase.stat_created_c
- self.finished = False
- self.result = '<BackgroundJob has not completed>'
-
- # reuse the ipython traceback handler if we can get to it, otherwise
- # make a new one
- try:
- make_tb = get_ipython().InteractiveTB.text
- except:
- make_tb = AutoFormattedTB(mode = 'Context',
- color_scheme='NoColor',
- tb_offset = 1).text
- # Note that the actual API for text() requires the three args to be
- # passed in, so we wrap it in a simple lambda.
- self._make_tb = lambda : make_tb(None, None, None)
-
- # Hold a formatted traceback if one is generated.
- self._tb = None
-
- threading.Thread.__init__(self)
-
- def __str__(self):
- return self.strform
-
- def __repr__(self):
- return '<BackgroundJob #%d: %s>' % (self.num, self.strform)
-
- def traceback(self):
- print(self._tb)
-
- def run(self):
- try:
- self.status = BackgroundJobBase.stat_running
- self.stat_code = BackgroundJobBase.stat_running_c
- self.result = self.call()
- except:
- self.status = BackgroundJobBase.stat_dead
- self.stat_code = BackgroundJobBase.stat_dead_c
- self.finished = None
- self.result = ('<BackgroundJob died, call jobs.traceback() for details>')
- self._tb = self._make_tb()
- else:
- self.status = BackgroundJobBase.stat_completed
- self.stat_code = BackgroundJobBase.stat_completed_c
- self.finished = True
-
-
-class BackgroundJobExpr(BackgroundJobBase):
- """Evaluate an expression as a background job (uses a separate thread)."""
-
- def __init__(self, expression, glob=None, loc=None):
- """Create a new job from a string which can be fed to eval().
-
- global/locals dicts can be provided, which will be passed to the eval
- call."""
-
- # fail immediately if the given expression can't be compiled
- self.code = compile(expression,'<BackgroundJob compilation>','eval')
-
- glob = {} if glob is None else glob
- loc = {} if loc is None else loc
- self.expression = self.strform = expression
- self.glob = glob
- self.loc = loc
- self._init()
-
- def call(self):
- return eval(self.code,self.glob,self.loc)
-
-
-class BackgroundJobFunc(BackgroundJobBase):
- """Run a function call as a background job (uses a separate thread)."""
-
- def __init__(self, func, *args, **kwargs):
- """Create a new job from a callable object.
-
- Any positional arguments and keyword args given to this constructor
- after the initial callable are passed directly to it."""
-
- if not callable(func):
- raise TypeError(
- 'first argument to BackgroundJobFunc must be callable')
-
- self.func = func
- self.args = args
- self.kwargs = kwargs
- # The string form will only include the function passed, because
- # generating string representations of the arguments is a potentially
- # _very_ expensive operation (e.g. with large arrays).
- self.strform = str(func)
- self._init()
-
- def call(self):
- return self.func(*self.args, **self.kwargs)
+from IPython.utils.py3compat import string_types
+
+
+class BackgroundJobManager(object):
+ """Class to manage a pool of backgrounded threaded jobs.
+
+ Below, we assume that 'jobs' is a BackgroundJobManager instance.
+
+ Usage summary (see the method docstrings for details):
+
+ jobs.new(...) -> start a new job
+
+ jobs() or jobs.status() -> print status summary of all jobs
+
+ jobs[N] -> returns job number N.
+
+ foo = jobs[N].result -> assign to variable foo the result of job N
+
+ jobs[N].traceback() -> print the traceback of dead job N
+
+ jobs.remove(N) -> remove (finished) job N
+
+ jobs.flush() -> remove all finished jobs
+
+ As a convenience feature, BackgroundJobManager instances provide the
+ utility result and traceback methods which retrieve the corresponding
+ information from the jobs list:
+
+ jobs.result(N) <--> jobs[N].result
+ jobs.traceback(N) <--> jobs[N].traceback()
+
+ While this appears minor, it allows you to use tab completion
+ interactively on the job manager instance.
+ """
+
+ def __init__(self):
+ # Lists for job management, accessed via a property to ensure they're
+ # up to date.x
+ self._running = []
+ self._completed = []
+ self._dead = []
+ # A dict of all jobs, so users can easily access any of them
+ self.all = {}
+ # For reporting
+ self._comp_report = []
+ self._dead_report = []
+ # Store status codes locally for fast lookups
+ self._s_created = BackgroundJobBase.stat_created_c
+ self._s_running = BackgroundJobBase.stat_running_c
+ self._s_completed = BackgroundJobBase.stat_completed_c
+ self._s_dead = BackgroundJobBase.stat_dead_c
+
+ @property
+ def running(self):
+ self._update_status()
+ return self._running
+
+ @property
+ def dead(self):
+ self._update_status()
+ return self._dead
+
+ @property
+ def completed(self):
+ self._update_status()
+ return self._completed
+
+ def new(self, func_or_exp, *args, **kwargs):
+ """Add a new background job and start it in a separate thread.
+
+ There are two types of jobs which can be created:
+
+ 1. Jobs based on expressions which can be passed to an eval() call.
+ The expression must be given as a string. For example:
+
+ job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])
+
+ The given expression is passed to eval(), along with the optional
+ global/local dicts provided. If no dicts are given, they are
+ extracted automatically from the caller's frame.
+
+ A Python statement is NOT a valid eval() expression. Basically, you
+ can only use as an eval() argument something which can go on the right
+ of an '=' sign and be assigned to a variable.
+
+ For example,"print 'hello'" is not valid, but '2+3' is.
+
+ 2. Jobs given a function object, optionally passing additional
+ positional arguments:
+
+ job_manager.new(myfunc, x, y)
+
+ The function is called with the given arguments.
+
+ If you need to pass keyword arguments to your function, you must
+ supply them as a dict named kw:
+
+ job_manager.new(myfunc, x, y, kw=dict(z=1))
+
+ The reason for this assymmetry is that the new() method needs to
+ maintain access to its own keywords, and this prevents name collisions
+ between arguments to new() and arguments to your own functions.
+
+ In both cases, the result is stored in the job.result field of the
+ background job object.
+
+ You can set `daemon` attribute of the thread by giving the keyword
+ argument `daemon`.
+
+ Notes and caveats:
+
+ 1. All threads running share the same standard output. Thus, if your
+ background jobs generate output, it will come out on top of whatever
+ you are currently writing. For this reason, background jobs are best
+ used with silent functions which simply return their output.
+
+ 2. Threads also all work within the same global namespace, and this
+ system does not lock interactive variables. So if you send job to the
+ background which operates on a mutable object for a long time, and
+ start modifying that same mutable object interactively (or in another
+ backgrounded job), all sorts of bizarre behaviour will occur.
+
+ 3. If a background job is spending a lot of time inside a C extension
+ module which does not release the Python Global Interpreter Lock
+ (GIL), this will block the IPython prompt. This is simply because the
+ Python interpreter can only switch between threads at Python
+ bytecodes. While the execution is inside C code, the interpreter must
+ simply wait unless the extension module releases the GIL.
+
+ 4. There is no way, due to limitations in the Python threads library,
+ to kill a thread once it has started."""
+
+ if callable(func_or_exp):
+ kw = kwargs.get('kw',{})
+ job = BackgroundJobFunc(func_or_exp,*args,**kw)
+ elif isinstance(func_or_exp, string_types):
+ if not args:
+ frame = sys._getframe(1)
+ glob, loc = frame.f_globals, frame.f_locals
+ elif len(args)==1:
+ glob = loc = args[0]
+ elif len(args)==2:
+ glob,loc = args
+ else:
+ raise ValueError(
+ 'Expression jobs take at most 2 args (globals,locals)')
+ job = BackgroundJobExpr(func_or_exp, glob, loc)
+ else:
+ raise TypeError('invalid args for new job')
+
+ if kwargs.get('daemon', False):
+ job.daemon = True
+ job.num = len(self.all)+1 if self.all else 0
+ self.running.append(job)
+ self.all[job.num] = job
+ print('Starting job # %s in a separate thread.' % job.num)
+ job.start()
+ return job
+
+ def __getitem__(self, job_key):
+ num = job_key if isinstance(job_key, int) else job_key.num
+ return self.all[num]
+
+ def __call__(self):
+ """An alias to self.status(),
+
+ This allows you to simply call a job manager instance much like the
+ Unix `jobs` shell command."""
+
+ return self.status()
+
+ def _update_status(self):
+ """Update the status of the job lists.
+
+ This method moves finished jobs to one of two lists:
+ - self.completed: jobs which completed successfully
+ - self.dead: jobs which finished but died.
+
+ It also copies those jobs to corresponding _report lists. These lists
+ are used to report jobs completed/dead since the last update, and are
+ then cleared by the reporting function after each call."""
+
+ # Status codes
+ srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead
+ # State lists, use the actual lists b/c the public names are properties
+ # that call this very function on access
+ running, completed, dead = self._running, self._completed, self._dead
+
+ # Now, update all state lists
+ for num, job in enumerate(running):
+ stat = job.stat_code
+ if stat == srun:
+ continue
+ elif stat == scomp:
+ completed.append(job)
+ self._comp_report.append(job)
+ running[num] = False
+ elif stat == sdead:
+ dead.append(job)
+ self._dead_report.append(job)
+ running[num] = False
+ # Remove dead/completed jobs from running list
+ running[:] = filter(None, running)
+
+ def _group_report(self,group,name):
+ """Report summary for a given job group.
+
+ Return True if the group had any elements."""
+
+ if group:
+ print('%s jobs:' % name)
+ for job in group:
+ print('%s : %s' % (job.num,job))
+ print()
+ return True
+
+ def _group_flush(self,group,name):
+ """Flush a given job group
+
+ Return True if the group had any elements."""
+
+ njobs = len(group)
+ if njobs:
+ plural = {1:''}.setdefault(njobs,'s')
+ print('Flushing %s %s job%s.' % (njobs,name,plural))
+ group[:] = []
+ return True
+
+ def _status_new(self):
+ """Print the status of newly finished jobs.
+
+ Return True if any new jobs are reported.
+
+ This call resets its own state every time, so it only reports jobs
+ which have finished since the last time it was called."""
+
+ self._update_status()
+ new_comp = self._group_report(self._comp_report, 'Completed')
+ new_dead = self._group_report(self._dead_report,
+ 'Dead, call jobs.traceback() for details')
+ self._comp_report[:] = []
+ self._dead_report[:] = []
+ return new_comp or new_dead
+
+ def status(self,verbose=0):
+ """Print a status of all jobs currently being managed."""
+
+ self._update_status()
+ self._group_report(self.running,'Running')
+ self._group_report(self.completed,'Completed')
+ self._group_report(self.dead,'Dead')
+ # Also flush the report queues
+ self._comp_report[:] = []
+ self._dead_report[:] = []
+
+ def remove(self,num):
+ """Remove a finished (completed or dead) job."""
+
+ try:
+ job = self.all[num]
+ except KeyError:
+ error('Job #%s not found' % num)
+ else:
+ stat_code = job.stat_code
+ if stat_code == self._s_running:
+ error('Job #%s is still running, it can not be removed.' % num)
+ return
+ elif stat_code == self._s_completed:
+ self.completed.remove(job)
+ elif stat_code == self._s_dead:
+ self.dead.remove(job)
+
+ def flush(self):
+ """Flush all finished jobs (completed and dead) from lists.
+
+ Running jobs are never flushed.
+
+ It first calls _status_new(), to update info. If any jobs have
+ completed since the last _status_new() call, the flush operation
+ aborts."""
+
+ # Remove the finished jobs from the master dict
+ alljobs = self.all
+ for job in self.completed+self.dead:
+ del(alljobs[job.num])
+
+ # Now flush these lists completely
+ fl_comp = self._group_flush(self.completed, 'Completed')
+ fl_dead = self._group_flush(self.dead, 'Dead')
+ if not (fl_comp or fl_dead):
+ print('No jobs to flush.')
+
+ def result(self,num):
+ """result(N) -> return the result of job N."""
+ try:
+ return self.all[num].result
+ except KeyError:
+ error('Job #%s not found' % num)
+
+ def _traceback(self, job):
+ num = job if isinstance(job, int) else job.num
+ try:
+ self.all[num].traceback()
+ except KeyError:
+ error('Job #%s not found' % num)
+
+ def traceback(self, job=None):
+ if job is None:
+ self._update_status()
+ for deadjob in self.dead:
+ print("Traceback for: %r" % deadjob)
+ self._traceback(deadjob)
+ print()
+ else:
+ self._traceback(job)
+
+
+class BackgroundJobBase(threading.Thread):
+ """Base class to build BackgroundJob classes.
+
+ The derived classes must implement:
+
+ - Their own __init__, since the one here raises NotImplementedError. The
+ derived constructor must call self._init() at the end, to provide common
+ initialization.
+
+ - A strform attribute used in calls to __str__.
+
+ - A call() method, which will make the actual execution call and must
+ return a value to be held in the 'result' field of the job object.
+ """
+
+ # Class constants for status, in string and as numerical codes (when
+ # updating jobs lists, we don't want to do string comparisons). This will
+ # be done at every user prompt, so it has to be as fast as possible
+ stat_created = 'Created'; stat_created_c = 0
+ stat_running = 'Running'; stat_running_c = 1
+ stat_completed = 'Completed'; stat_completed_c = 2
+ stat_dead = 'Dead (Exception), call jobs.traceback() for details'
+ stat_dead_c = -1
+
+ def __init__(self):
+ """Must be implemented in subclasses.
+
+ Subclasses must call :meth:`_init` for standard initialisation.
+ """
+ raise NotImplementedError("This class can not be instantiated directly.")
+
+ def _init(self):
+ """Common initialization for all BackgroundJob objects"""
+
+ for attr in ['call','strform']:
+ assert hasattr(self,attr), "Missing attribute <%s>" % attr
+
+ # The num tag can be set by an external job manager
+ self.num = None
+
+ self.status = BackgroundJobBase.stat_created
+ self.stat_code = BackgroundJobBase.stat_created_c
+ self.finished = False
+ self.result = '<BackgroundJob has not completed>'
+
+ # reuse the ipython traceback handler if we can get to it, otherwise
+ # make a new one
+ try:
+ make_tb = get_ipython().InteractiveTB.text
+ except:
+ make_tb = AutoFormattedTB(mode = 'Context',
+ color_scheme='NoColor',
+ tb_offset = 1).text
+ # Note that the actual API for text() requires the three args to be
+ # passed in, so we wrap it in a simple lambda.
+ self._make_tb = lambda : make_tb(None, None, None)
+
+ # Hold a formatted traceback if one is generated.
+ self._tb = None
+
+ threading.Thread.__init__(self)
+
+ def __str__(self):
+ return self.strform
+
+ def __repr__(self):
+ return '<BackgroundJob #%d: %s>' % (self.num, self.strform)
+
+ def traceback(self):
+ print(self._tb)
+
+ def run(self):
+ try:
+ self.status = BackgroundJobBase.stat_running
+ self.stat_code = BackgroundJobBase.stat_running_c
+ self.result = self.call()
+ except:
+ self.status = BackgroundJobBase.stat_dead
+ self.stat_code = BackgroundJobBase.stat_dead_c
+ self.finished = None
+ self.result = ('<BackgroundJob died, call jobs.traceback() for details>')
+ self._tb = self._make_tb()
+ else:
+ self.status = BackgroundJobBase.stat_completed
+ self.stat_code = BackgroundJobBase.stat_completed_c
+ self.finished = True
+
+
+class BackgroundJobExpr(BackgroundJobBase):
+ """Evaluate an expression as a background job (uses a separate thread)."""
+
+ def __init__(self, expression, glob=None, loc=None):
+ """Create a new job from a string which can be fed to eval().
+
+ global/locals dicts can be provided, which will be passed to the eval
+ call."""
+
+ # fail immediately if the given expression can't be compiled
+ self.code = compile(expression,'<BackgroundJob compilation>','eval')
+
+ glob = {} if glob is None else glob
+ loc = {} if loc is None else loc
+ self.expression = self.strform = expression
+ self.glob = glob
+ self.loc = loc
+ self._init()
+
+ def call(self):
+ return eval(self.code,self.glob,self.loc)
+
+
+class BackgroundJobFunc(BackgroundJobBase):
+ """Run a function call as a background job (uses a separate thread)."""
+
+ def __init__(self, func, *args, **kwargs):
+ """Create a new job from a callable object.
+
+ Any positional arguments and keyword args given to this constructor
+ after the initial callable are passed directly to it."""
+
+ if not callable(func):
+ raise TypeError(
+ 'first argument to BackgroundJobFunc must be callable')
+
+ self.func = func
+ self.args = args
+ self.kwargs = kwargs
+ # The string form will only include the function passed, because
+ # generating string representations of the arguments is a potentially
+ # _very_ expensive operation (e.g. with large arrays).
+ self.strform = str(func)
+ self._init()
+
+ def call(self):
+ return self.func(*self.args, **self.kwargs)
diff --git a/contrib/python/ipython/py2/IPython/lib/clipboard.py b/contrib/python/ipython/py2/IPython/lib/clipboard.py
index 713313da33..ac9b685c7d 100644
--- a/contrib/python/ipython/py2/IPython/lib/clipboard.py
+++ b/contrib/python/ipython/py2/IPython/lib/clipboard.py
@@ -1,72 +1,72 @@
-""" Utilities for accessing the platform's clipboard.
-"""
-
-import subprocess
-
-from IPython.core.error import TryNext
-import IPython.utils.py3compat as py3compat
-
-class ClipboardEmpty(ValueError):
- pass
-
-def win32_clipboard_get():
- """ Get the current clipboard's text on Windows.
-
- Requires Mark Hammond's pywin32 extensions.
- """
- try:
- import win32clipboard
- except ImportError:
- raise TryNext("Getting text from the clipboard requires the pywin32 "
- "extensions: http://sourceforge.net/projects/pywin32/")
- win32clipboard.OpenClipboard()
- try:
- text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
- except (TypeError, win32clipboard.error):
- try:
- text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
- text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
- except (TypeError, win32clipboard.error):
- raise ClipboardEmpty
- finally:
- win32clipboard.CloseClipboard()
- return text
-
-def osx_clipboard_get():
- """ Get the clipboard's text on OS X.
- """
- p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],
- stdout=subprocess.PIPE)
- text, stderr = p.communicate()
- # Text comes in with old Mac \r line endings. Change them to \n.
- text = text.replace(b'\r', b'\n')
- text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
- return text
-
-def tkinter_clipboard_get():
- """ Get the clipboard's text using Tkinter.
-
- This is the default on systems that are not Windows or OS X. It may
- interfere with other UI toolkits and should be replaced with an
- implementation that uses that toolkit.
- """
- try:
- from tkinter import Tk, TclError # Py 3
- except ImportError:
- try:
- from Tkinter import Tk, TclError # Py 2
- except ImportError:
- raise TryNext("Getting text from the clipboard on this platform "
- "requires Tkinter.")
- root = Tk()
- root.withdraw()
- try:
- text = root.clipboard_get()
- except TclError:
- raise ClipboardEmpty
- finally:
- root.destroy()
- text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
- return text
-
-
+""" Utilities for accessing the platform's clipboard.
+"""
+
+import subprocess
+
+from IPython.core.error import TryNext
+import IPython.utils.py3compat as py3compat
+
+class ClipboardEmpty(ValueError):
+ pass
+
+def win32_clipboard_get():
+ """ Get the current clipboard's text on Windows.
+
+ Requires Mark Hammond's pywin32 extensions.
+ """
+ try:
+ import win32clipboard
+ except ImportError:
+ raise TryNext("Getting text from the clipboard requires the pywin32 "
+ "extensions: http://sourceforge.net/projects/pywin32/")
+ win32clipboard.OpenClipboard()
+ try:
+ text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
+ except (TypeError, win32clipboard.error):
+ try:
+ text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
+ text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
+ except (TypeError, win32clipboard.error):
+ raise ClipboardEmpty
+ finally:
+ win32clipboard.CloseClipboard()
+ return text
+
+def osx_clipboard_get():
+ """ Get the clipboard's text on OS X.
+ """
+ p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],
+ stdout=subprocess.PIPE)
+ text, stderr = p.communicate()
+ # Text comes in with old Mac \r line endings. Change them to \n.
+ text = text.replace(b'\r', b'\n')
+ text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
+ return text
+
+def tkinter_clipboard_get():
+ """ Get the clipboard's text using Tkinter.
+
+ This is the default on systems that are not Windows or OS X. It may
+ interfere with other UI toolkits and should be replaced with an
+ implementation that uses that toolkit.
+ """
+ try:
+ from tkinter import Tk, TclError # Py 3
+ except ImportError:
+ try:
+ from Tkinter import Tk, TclError # Py 2
+ except ImportError:
+ raise TryNext("Getting text from the clipboard on this platform "
+ "requires Tkinter.")
+ root = Tk()
+ root.withdraw()
+ try:
+ text = root.clipboard_get()
+ except TclError:
+ raise ClipboardEmpty
+ finally:
+ root.destroy()
+ text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
+ return text
+
+
diff --git a/contrib/python/ipython/py2/IPython/lib/deepreload.py b/contrib/python/ipython/py2/IPython/lib/deepreload.py
index 72f2b5752f..76b493c0bb 100644
--- a/contrib/python/ipython/py2/IPython/lib/deepreload.py
+++ b/contrib/python/ipython/py2/IPython/lib/deepreload.py
@@ -1,362 +1,362 @@
-# -*- coding: utf-8 -*-
-"""
-Provides a reload() function that acts recursively.
-
-Python's normal :func:`python:reload` function only reloads the module that it's
-passed. The :func:`reload` function in this module also reloads everything
-imported from that module, which is useful when you're changing files deep
-inside a package.
-
-To use this as your default reload function, type this for Python 2::
-
- import __builtin__
- from IPython.lib import deepreload
- __builtin__.reload = deepreload.reload
-
-Or this for Python 3::
-
- import builtins
- from IPython.lib import deepreload
- builtins.reload = deepreload.reload
-
-A reference to the original :func:`python:reload` is stored in this module as
-:data:`original_reload`, so you can restore it later.
-
-This code is almost entirely based on knee.py, which is a Python
-re-implementation of hierarchical module import.
-"""
-from __future__ import print_function
-#*****************************************************************************
-# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#*****************************************************************************
-
-from contextlib import contextmanager
-import imp
-import sys
-
-from types import ModuleType
-from warnings import warn
-
-from IPython.utils.py3compat import builtin_mod, builtin_mod_name
-
-original_import = builtin_mod.__import__
-
-@contextmanager
-def replace_import_hook(new_import):
- saved_import = builtin_mod.__import__
- builtin_mod.__import__ = new_import
- try:
- yield
- finally:
- builtin_mod.__import__ = saved_import
-
-def get_parent(globals, level):
- """
- parent, name = get_parent(globals, level)
-
- Return the package that an import is being performed in. If globals comes
- from the module foo.bar.bat (not itself a package), this returns the
- sys.modules entry for foo.bar. If globals is from a package's __init__.py,
- the package's entry in sys.modules is returned.
-
- If globals doesn't come from a package or a module in a package, or a
- corresponding entry is not found in sys.modules, None is returned.
- """
- orig_level = level
-
- if not level or not isinstance(globals, dict):
- return None, ''
-
- pkgname = globals.get('__package__', None)
-
- if pkgname is not None:
- # __package__ is set, so use it
- if not hasattr(pkgname, 'rindex'):
- raise ValueError('__package__ set to non-string')
- if len(pkgname) == 0:
- if level > 0:
- raise ValueError('Attempted relative import in non-package')
- return None, ''
- name = pkgname
- else:
- # __package__ not set, so figure it out and set it
- if '__name__' not in globals:
- return None, ''
- modname = globals['__name__']
-
- if '__path__' in globals:
- # __path__ is set, so modname is already the package name
- globals['__package__'] = name = modname
- else:
- # Normal module, so work out the package name if any
- lastdot = modname.rfind('.')
- if lastdot < 0 < level:
- raise ValueError("Attempted relative import in non-package")
- if lastdot < 0:
- globals['__package__'] = None
- return None, ''
- globals['__package__'] = name = modname[:lastdot]
-
- dot = len(name)
- for x in range(level, 1, -1):
- try:
- dot = name.rindex('.', 0, dot)
- except ValueError:
- raise ValueError("attempted relative import beyond top-level "
- "package")
- name = name[:dot]
-
- try:
- parent = sys.modules[name]
- except:
- if orig_level < 1:
- warn("Parent module '%.200s' not found while handling absolute "
- "import" % name)
- parent = None
- else:
- raise SystemError("Parent module '%.200s' not loaded, cannot "
- "perform relative import" % name)
-
- # We expect, but can't guarantee, if parent != None, that:
- # - parent.__name__ == name
- # - parent.__dict__ is globals
- # If this is violated... Who cares?
- return parent, name
-
-def load_next(mod, altmod, name, buf):
- """
- mod, name, buf = load_next(mod, altmod, name, buf)
-
- altmod is either None or same as mod
- """
-
- if len(name) == 0:
- # completely empty module name should only happen in
- # 'from . import' (or '__import__("")')
- return mod, None, buf
-
- dot = name.find('.')
- if dot == 0:
- raise ValueError('Empty module name')
-
- if dot < 0:
- subname = name
- next = None
- else:
- subname = name[:dot]
- next = name[dot+1:]
-
- if buf != '':
- buf += '.'
- buf += subname
-
- result = import_submodule(mod, subname, buf)
- if result is None and mod != altmod:
- result = import_submodule(altmod, subname, subname)
- if result is not None:
- buf = subname
-
- if result is None:
- raise ImportError("No module named %.200s" % name)
-
- return result, next, buf
-
-# Need to keep track of what we've already reloaded to prevent cyclic evil
-found_now = {}
-
-def import_submodule(mod, subname, fullname):
- """m = import_submodule(mod, subname, fullname)"""
- # Require:
- # if mod == None: subname == fullname
- # else: mod.__name__ + "." + subname == fullname
-
- global found_now
- if fullname in found_now and fullname in sys.modules:
- m = sys.modules[fullname]
- else:
- print('Reloading', fullname)
- found_now[fullname] = 1
- oldm = sys.modules.get(fullname, None)
-
- if mod is None:
- path = None
- elif hasattr(mod, '__path__'):
- path = mod.__path__
- else:
- return None
-
- try:
- # This appears to be necessary on Python 3, because imp.find_module()
- # tries to import standard libraries (like io) itself, and we don't
- # want them to be processed by our deep_import_hook.
- with replace_import_hook(original_import):
- fp, filename, stuff = imp.find_module(subname, path)
- except ImportError:
- return None
-
- try:
- m = imp.load_module(fullname, fp, filename, stuff)
- except:
- # load_module probably removed name from modules because of
- # the error. Put back the original module object.
- if oldm:
- sys.modules[fullname] = oldm
- raise
- finally:
- if fp: fp.close()
-
- add_submodule(mod, m, fullname, subname)
-
- return m
-
-def add_submodule(mod, submod, fullname, subname):
- """mod.{subname} = submod"""
- if mod is None:
- return #Nothing to do here.
-
- if submod is None:
- submod = sys.modules[fullname]
-
- setattr(mod, subname, submod)
-
- return
-
-def ensure_fromlist(mod, fromlist, buf, recursive):
- """Handle 'from module import a, b, c' imports."""
- if not hasattr(mod, '__path__'):
- return
- for item in fromlist:
- if not hasattr(item, 'rindex'):
- raise TypeError("Item in ``from list'' not a string")
- if item == '*':
- if recursive:
- continue # avoid endless recursion
- try:
- all = mod.__all__
- except AttributeError:
- pass
- else:
- ret = ensure_fromlist(mod, all, buf, 1)
- if not ret:
- return 0
- elif not hasattr(mod, item):
- import_submodule(mod, item, buf + '.' + item)
-
-def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):
- """Replacement for __import__()"""
- parent, buf = get_parent(globals, level)
-
- head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)
-
- tail = head
- while name:
- tail, name, buf = load_next(tail, tail, name, buf)
-
- # If tail is None, both get_parent and load_next found
- # an empty module name: someone called __import__("") or
- # doctored faulty bytecode
- if tail is None:
- raise ValueError('Empty module name')
-
- if not fromlist:
- return head
-
- ensure_fromlist(tail, fromlist, buf, 0)
- return tail
-
-modules_reloading = {}
-
-def deep_reload_hook(m):
- """Replacement for reload()."""
- if not isinstance(m, ModuleType):
- raise TypeError("reload() argument must be module")
-
- name = m.__name__
-
- if name not in sys.modules:
- raise ImportError("reload(): module %.200s not in sys.modules" % name)
-
- global modules_reloading
- try:
- return modules_reloading[name]
- except:
- modules_reloading[name] = m
-
- dot = name.rfind('.')
- if dot < 0:
- subname = name
- path = None
- else:
- try:
- parent = sys.modules[name[:dot]]
- except KeyError:
- modules_reloading.clear()
- raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
- subname = name[dot+1:]
- path = getattr(parent, "__path__", None)
-
- try:
- # This appears to be necessary on Python 3, because imp.find_module()
- # tries to import standard libraries (like io) itself, and we don't
- # want them to be processed by our deep_import_hook.
- with replace_import_hook(original_import):
- fp, filename, stuff = imp.find_module(subname, path)
- finally:
- modules_reloading.clear()
-
- try:
- newm = imp.load_module(name, fp, filename, stuff)
- except:
- # load_module probably removed name from modules because of
- # the error. Put back the original module object.
- sys.modules[name] = m
- raise
- finally:
- if fp: fp.close()
-
- modules_reloading.clear()
- return newm
-
-# Save the original hooks
-try:
- original_reload = builtin_mod.reload
-except AttributeError:
- original_reload = imp.reload # Python 3
-
-# Replacement for reload()
+# -*- coding: utf-8 -*-
+"""
+Provides a reload() function that acts recursively.
+
+Python's normal :func:`python:reload` function only reloads the module that it's
+passed. The :func:`reload` function in this module also reloads everything
+imported from that module, which is useful when you're changing files deep
+inside a package.
+
+To use this as your default reload function, type this for Python 2::
+
+ import __builtin__
+ from IPython.lib import deepreload
+ __builtin__.reload = deepreload.reload
+
+Or this for Python 3::
+
+ import builtins
+ from IPython.lib import deepreload
+ builtins.reload = deepreload.reload
+
+A reference to the original :func:`python:reload` is stored in this module as
+:data:`original_reload`, so you can restore it later.
+
+This code is almost entirely based on knee.py, which is a Python
+re-implementation of hierarchical module import.
+"""
+from __future__ import print_function
+#*****************************************************************************
+# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#*****************************************************************************
+
+from contextlib import contextmanager
+import imp
+import sys
+
+from types import ModuleType
+from warnings import warn
+
+from IPython.utils.py3compat import builtin_mod, builtin_mod_name
+
+original_import = builtin_mod.__import__
+
+@contextmanager
+def replace_import_hook(new_import):
+ saved_import = builtin_mod.__import__
+ builtin_mod.__import__ = new_import
+ try:
+ yield
+ finally:
+ builtin_mod.__import__ = saved_import
+
+def get_parent(globals, level):
+ """
+ parent, name = get_parent(globals, level)
+
+ Return the package that an import is being performed in. If globals comes
+ from the module foo.bar.bat (not itself a package), this returns the
+ sys.modules entry for foo.bar. If globals is from a package's __init__.py,
+ the package's entry in sys.modules is returned.
+
+ If globals doesn't come from a package or a module in a package, or a
+ corresponding entry is not found in sys.modules, None is returned.
+ """
+ orig_level = level
+
+ if not level or not isinstance(globals, dict):
+ return None, ''
+
+ pkgname = globals.get('__package__', None)
+
+ if pkgname is not None:
+ # __package__ is set, so use it
+ if not hasattr(pkgname, 'rindex'):
+ raise ValueError('__package__ set to non-string')
+ if len(pkgname) == 0:
+ if level > 0:
+ raise ValueError('Attempted relative import in non-package')
+ return None, ''
+ name = pkgname
+ else:
+ # __package__ not set, so figure it out and set it
+ if '__name__' not in globals:
+ return None, ''
+ modname = globals['__name__']
+
+ if '__path__' in globals:
+ # __path__ is set, so modname is already the package name
+ globals['__package__'] = name = modname
+ else:
+ # Normal module, so work out the package name if any
+ lastdot = modname.rfind('.')
+ if lastdot < 0 < level:
+ raise ValueError("Attempted relative import in non-package")
+ if lastdot < 0:
+ globals['__package__'] = None
+ return None, ''
+ globals['__package__'] = name = modname[:lastdot]
+
+ dot = len(name)
+ for x in range(level, 1, -1):
+ try:
+ dot = name.rindex('.', 0, dot)
+ except ValueError:
+ raise ValueError("attempted relative import beyond top-level "
+ "package")
+ name = name[:dot]
+
+ try:
+ parent = sys.modules[name]
+ except:
+ if orig_level < 1:
+ warn("Parent module '%.200s' not found while handling absolute "
+ "import" % name)
+ parent = None
+ else:
+ raise SystemError("Parent module '%.200s' not loaded, cannot "
+ "perform relative import" % name)
+
+ # We expect, but can't guarantee, if parent != None, that:
+ # - parent.__name__ == name
+ # - parent.__dict__ is globals
+ # If this is violated... Who cares?
+ return parent, name
+
+def load_next(mod, altmod, name, buf):
+ """
+ mod, name, buf = load_next(mod, altmod, name, buf)
+
+ altmod is either None or same as mod
+ """
+
+ if len(name) == 0:
+ # completely empty module name should only happen in
+ # 'from . import' (or '__import__("")')
+ return mod, None, buf
+
+ dot = name.find('.')
+ if dot == 0:
+ raise ValueError('Empty module name')
+
+ if dot < 0:
+ subname = name
+ next = None
+ else:
+ subname = name[:dot]
+ next = name[dot+1:]
+
+ if buf != '':
+ buf += '.'
+ buf += subname
+
+ result = import_submodule(mod, subname, buf)
+ if result is None and mod != altmod:
+ result = import_submodule(altmod, subname, subname)
+ if result is not None:
+ buf = subname
+
+ if result is None:
+ raise ImportError("No module named %.200s" % name)
+
+ return result, next, buf
+
+# Need to keep track of what we've already reloaded to prevent cyclic evil
+found_now = {}
+
+def import_submodule(mod, subname, fullname):
+ """m = import_submodule(mod, subname, fullname)"""
+ # Require:
+ # if mod == None: subname == fullname
+ # else: mod.__name__ + "." + subname == fullname
+
+ global found_now
+ if fullname in found_now and fullname in sys.modules:
+ m = sys.modules[fullname]
+ else:
+ print('Reloading', fullname)
+ found_now[fullname] = 1
+ oldm = sys.modules.get(fullname, None)
+
+ if mod is None:
+ path = None
+ elif hasattr(mod, '__path__'):
+ path = mod.__path__
+ else:
+ return None
+
+ try:
+ # This appears to be necessary on Python 3, because imp.find_module()
+ # tries to import standard libraries (like io) itself, and we don't
+ # want them to be processed by our deep_import_hook.
+ with replace_import_hook(original_import):
+ fp, filename, stuff = imp.find_module(subname, path)
+ except ImportError:
+ return None
+
+ try:
+ m = imp.load_module(fullname, fp, filename, stuff)
+ except:
+ # load_module probably removed name from modules because of
+ # the error. Put back the original module object.
+ if oldm:
+ sys.modules[fullname] = oldm
+ raise
+ finally:
+ if fp: fp.close()
+
+ add_submodule(mod, m, fullname, subname)
+
+ return m
+
+def add_submodule(mod, submod, fullname, subname):
+ """mod.{subname} = submod"""
+ if mod is None:
+ return #Nothing to do here.
+
+ if submod is None:
+ submod = sys.modules[fullname]
+
+ setattr(mod, subname, submod)
+
+ return
+
+def ensure_fromlist(mod, fromlist, buf, recursive):
+ """Handle 'from module import a, b, c' imports."""
+ if not hasattr(mod, '__path__'):
+ return
+ for item in fromlist:
+ if not hasattr(item, 'rindex'):
+ raise TypeError("Item in ``from list'' not a string")
+ if item == '*':
+ if recursive:
+ continue # avoid endless recursion
+ try:
+ all = mod.__all__
+ except AttributeError:
+ pass
+ else:
+ ret = ensure_fromlist(mod, all, buf, 1)
+ if not ret:
+ return 0
+ elif not hasattr(mod, item):
+ import_submodule(mod, item, buf + '.' + item)
+
+def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):
+ """Replacement for __import__()"""
+ parent, buf = get_parent(globals, level)
+
+ head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)
+
+ tail = head
+ while name:
+ tail, name, buf = load_next(tail, tail, name, buf)
+
+ # If tail is None, both get_parent and load_next found
+ # an empty module name: someone called __import__("") or
+ # doctored faulty bytecode
+ if tail is None:
+ raise ValueError('Empty module name')
+
+ if not fromlist:
+ return head
+
+ ensure_fromlist(tail, fromlist, buf, 0)
+ return tail
+
+modules_reloading = {}
+
+def deep_reload_hook(m):
+ """Replacement for reload()."""
+ if not isinstance(m, ModuleType):
+ raise TypeError("reload() argument must be module")
+
+ name = m.__name__
+
+ if name not in sys.modules:
+ raise ImportError("reload(): module %.200s not in sys.modules" % name)
+
+ global modules_reloading
+ try:
+ return modules_reloading[name]
+ except:
+ modules_reloading[name] = m
+
+ dot = name.rfind('.')
+ if dot < 0:
+ subname = name
+ path = None
+ else:
+ try:
+ parent = sys.modules[name[:dot]]
+ except KeyError:
+ modules_reloading.clear()
+ raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
+ subname = name[dot+1:]
+ path = getattr(parent, "__path__", None)
+
+ try:
+ # This appears to be necessary on Python 3, because imp.find_module()
+ # tries to import standard libraries (like io) itself, and we don't
+ # want them to be processed by our deep_import_hook.
+ with replace_import_hook(original_import):
+ fp, filename, stuff = imp.find_module(subname, path)
+ finally:
+ modules_reloading.clear()
+
+ try:
+ newm = imp.load_module(name, fp, filename, stuff)
+ except:
+ # load_module probably removed name from modules because of
+ # the error. Put back the original module object.
+ sys.modules[name] = m
+ raise
+ finally:
+ if fp: fp.close()
+
+ modules_reloading.clear()
+ return newm
+
+# Save the original hooks
+try:
+ original_reload = builtin_mod.reload
+except AttributeError:
+ original_reload = imp.reload # Python 3
+
+# Replacement for reload()
def reload(module, exclude=('sys', 'os.path', builtin_mod_name, '__main__',
'numpy', 'numpy._globals')):
- """Recursively reload all modules used in the given module. Optionally
- takes a list of modules to exclude from reloading. The default exclude
- list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
- display, exception, and io hooks.
- """
- global found_now
- for i in exclude:
- found_now[i] = 1
- try:
- with replace_import_hook(deep_import_hook):
- return deep_reload_hook(module)
- finally:
- found_now = {}
-
-
-def _dreload(module, **kwargs):
- """
- **deprecated**
-
- import reload explicitly from `IPython.lib.deepreload` to use it
-
- """
+ """Recursively reload all modules used in the given module. Optionally
+ takes a list of modules to exclude from reloading. The default exclude
+ list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
+ display, exception, and io hooks.
+ """
+ global found_now
+ for i in exclude:
+ found_now[i] = 1
+ try:
+ with replace_import_hook(deep_import_hook):
+ return deep_reload_hook(module)
+ finally:
+ found_now = {}
+
+
+def _dreload(module, **kwargs):
+ """
+ **deprecated**
+
+ import reload explicitly from `IPython.lib.deepreload` to use it
+
+ """
# this was marked as deprecated and for 5.0 removal, but
# IPython.core_builtin_trap have a Deprecation warning for 6.0, so cannot
# remove that now.
- warn("""
+ warn("""
injecting `dreload` in interactive namespace is deprecated since IPython 4.0.
-Please import `reload` explicitly from `IPython.lib.deepreload`.
-""", DeprecationWarning, stacklevel=2)
- reload(module, **kwargs)
-
+Please import `reload` explicitly from `IPython.lib.deepreload`.
+""", DeprecationWarning, stacklevel=2)
+ reload(module, **kwargs)
+
diff --git a/contrib/python/ipython/py2/IPython/lib/demo.py b/contrib/python/ipython/py2/IPython/lib/demo.py
index d630db99f9..b0f3503ed7 100644
--- a/contrib/python/ipython/py2/IPython/lib/demo.py
+++ b/contrib/python/ipython/py2/IPython/lib/demo.py
@@ -1,583 +1,583 @@
-"""Module for interactive demos using IPython.
-
-This module implements a few classes for running Python scripts interactively
-in IPython for demonstrations. With very simple markup (a few tags in
-comments), you can control points where the script stops executing and returns
-control to IPython.
-
-
-Provided classes
-----------------
-
-The classes are (see their docstrings for further details):
-
- - Demo: pure python demos
-
- - IPythonDemo: demos with input to be processed by IPython as if it had been
- typed interactively (so magics work, as well as any other special syntax you
- may have added via input prefilters).
-
- - LineDemo: single-line version of the Demo class. These demos are executed
- one line at a time, and require no markup.
-
- - IPythonLineDemo: IPython version of the LineDemo class (the demo is
- executed a line at a time, but processed via IPython).
-
- - ClearMixin: mixin to make Demo classes with less visual clutter. It
- declares an empty marquee and a pre_cmd that clears the screen before each
- block (see Subclassing below).
-
- - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
- classes.
-
-Inheritance diagram:
-
-.. inheritance-diagram:: IPython.lib.demo
- :parts: 3
-
-Subclassing
------------
-
-The classes here all include a few methods meant to make customization by
-subclassing more convenient. Their docstrings below have some more details:
-
- - marquee(): generates a marquee to provide visible on-screen markers at each
- block start and end.
-
- - pre_cmd(): run right before the execution of each block.
-
- - post_cmd(): run right after the execution of each block. If the block
- raises an exception, this is NOT called.
-
-
-Operation
----------
-
-The file is run in its own empty namespace (though you can pass it a string of
-arguments as if in a command line environment, and it will see those as
-sys.argv). But at each stop, the global IPython namespace is updated with the
-current internal demo namespace, so you can work interactively with the data
-accumulated so far.
-
-By default, each block of code is printed (with syntax highlighting) before
-executing it and you have to confirm execution. This is intended to show the
-code to an audience first so you can discuss it, and only proceed with
-execution once you agree. There are a few tags which allow you to modify this
-behavior.
-
-The supported tags are:
-
-# <demo> stop
-
- Defines block boundaries, the points where IPython stops execution of the
- file and returns to the interactive prompt.
-
- You can optionally mark the stop tag with extra dashes before and after the
- word 'stop', to help visually distinguish the blocks in a text editor:
-
- # <demo> --- stop ---
-
-
-# <demo> silent
-
- Make a block execute silently (and hence automatically). Typically used in
- cases where you have some boilerplate or initialization code which you need
- executed but do not want to be seen in the demo.
-
-# <demo> auto
-
- Make a block execute automatically, but still being printed. Useful for
- simple code which does not warrant discussion, since it avoids the extra
- manual confirmation.
-
-# <demo> auto_all
-
- This tag can _only_ be in the first block, and if given it overrides the
- individual auto tags to make the whole demo fully automatic (no block asks
- for confirmation). It can also be given at creation time (or the attribute
- set later) to override what's in the file.
-
-While _any_ python file can be run as a Demo instance, if there are no stop
-tags the whole file will run in a single block (no different that calling
-first %pycat and then %run). The minimal markup to make this useful is to
-place a set of stop tags; the other tags are only there to let you fine-tune
-the execution.
-
-This is probably best explained with the simple example file below. You can
-copy this into a file named ex_demo.py, and try running it via::
-
+"""Module for interactive demos using IPython.
+
+This module implements a few classes for running Python scripts interactively
+in IPython for demonstrations. With very simple markup (a few tags in
+comments), you can control points where the script stops executing and returns
+control to IPython.
+
+
+Provided classes
+----------------
+
+The classes are (see their docstrings for further details):
+
+ - Demo: pure python demos
+
+ - IPythonDemo: demos with input to be processed by IPython as if it had been
+ typed interactively (so magics work, as well as any other special syntax you
+ may have added via input prefilters).
+
+ - LineDemo: single-line version of the Demo class. These demos are executed
+ one line at a time, and require no markup.
+
+ - IPythonLineDemo: IPython version of the LineDemo class (the demo is
+ executed a line at a time, but processed via IPython).
+
+ - ClearMixin: mixin to make Demo classes with less visual clutter. It
+ declares an empty marquee and a pre_cmd that clears the screen before each
+ block (see Subclassing below).
+
+ - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
+ classes.
+
+Inheritance diagram:
+
+.. inheritance-diagram:: IPython.lib.demo
+ :parts: 3
+
+Subclassing
+-----------
+
+The classes here all include a few methods meant to make customization by
+subclassing more convenient. Their docstrings below have some more details:
+
+ - marquee(): generates a marquee to provide visible on-screen markers at each
+ block start and end.
+
+ - pre_cmd(): run right before the execution of each block.
+
+ - post_cmd(): run right after the execution of each block. If the block
+ raises an exception, this is NOT called.
+
+
+Operation
+---------
+
+The file is run in its own empty namespace (though you can pass it a string of
+arguments as if in a command line environment, and it will see those as
+sys.argv). But at each stop, the global IPython namespace is updated with the
+current internal demo namespace, so you can work interactively with the data
+accumulated so far.
+
+By default, each block of code is printed (with syntax highlighting) before
+executing it and you have to confirm execution. This is intended to show the
+code to an audience first so you can discuss it, and only proceed with
+execution once you agree. There are a few tags which allow you to modify this
+behavior.
+
+The supported tags are:
+
+# <demo> stop
+
+ Defines block boundaries, the points where IPython stops execution of the
+ file and returns to the interactive prompt.
+
+ You can optionally mark the stop tag with extra dashes before and after the
+ word 'stop', to help visually distinguish the blocks in a text editor:
+
+ # <demo> --- stop ---
+
+
+# <demo> silent
+
+ Make a block execute silently (and hence automatically). Typically used in
+ cases where you have some boilerplate or initialization code which you need
+ executed but do not want to be seen in the demo.
+
+# <demo> auto
+
+ Make a block execute automatically, but still being printed. Useful for
+ simple code which does not warrant discussion, since it avoids the extra
+ manual confirmation.
+
+# <demo> auto_all
+
+ This tag can _only_ be in the first block, and if given it overrides the
+ individual auto tags to make the whole demo fully automatic (no block asks
+ for confirmation). It can also be given at creation time (or the attribute
+ set later) to override what's in the file.
+
+While _any_ python file can be run as a Demo instance, if there are no stop
+tags the whole file will run in a single block (no different that calling
+first %pycat and then %run). The minimal markup to make this useful is to
+place a set of stop tags; the other tags are only there to let you fine-tune
+the execution.
+
+This is probably best explained with the simple example file below. You can
+copy this into a file named ex_demo.py, and try running it via::
+
from IPython.lib.demo import Demo
- d = Demo('ex_demo.py')
- d()
-
-Each time you call the demo object, it runs the next block. The demo object
-has a few useful methods for navigation, like again(), edit(), jump(), seek()
-and back(). It can be reset for a new run via reset() or reloaded from disk
-(in case you've edited the source) via reload(). See their docstrings below.
-
-Note: To make this simpler to explore, a file called "demo-exercizer.py" has
-been added to the "docs/examples/core" directory. Just cd to this directory in
-an IPython session, and type::
-
- %run demo-exercizer.py
-
-and then follow the directions.
-
-Example
--------
-
-The following is a very simple example of a valid demo file.
-
-::
-
- #################### EXAMPLE DEMO <ex_demo.py> ###############################
- '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
-
- print 'Hello, welcome to an interactive IPython demo.'
-
- # The mark below defines a block boundary, which is a point where IPython will
- # stop execution and return to the interactive prompt. The dashes are actually
- # optional and used only as a visual aid to clearly separate blocks while
- # editing the demo code.
- # <demo> stop
-
- x = 1
- y = 2
-
- # <demo> stop
-
- # the mark below makes this block as silent
- # <demo> silent
-
- print 'This is a silent block, which gets executed but not printed.'
-
- # <demo> stop
- # <demo> auto
- print 'This is an automatic block.'
- print 'It is executed without asking for confirmation, but printed.'
- z = x+y
-
- print 'z=',x
-
- # <demo> stop
- # This is just another normal block.
- print 'z is now:', z
-
- print 'bye!'
- ################### END EXAMPLE DEMO <ex_demo.py> ############################
-"""
-
-from __future__ import unicode_literals
-
-#*****************************************************************************
-# Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#
-#*****************************************************************************
-from __future__ import print_function
-
-import os
-import re
-import shlex
-import sys
-
-from IPython.utils import io
-from IPython.utils.text import marquee
-from IPython.utils import openpy
-from IPython.utils import py3compat
-__all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
-
-class DemoError(Exception): pass
-
-def re_mark(mark):
- return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
-
-class Demo(object):
-
- re_stop = re_mark('-*\s?stop\s?-*')
- re_silent = re_mark('silent')
- re_auto = re_mark('auto')
- re_auto_all = re_mark('auto_all')
-
- def __init__(self,src,title='',arg_str='',auto_all=None):
- """Make a new demo object. To run the demo, simply call the object.
-
- See the module docstring for full details and an example (you can use
- IPython.Demo? in IPython to see it).
-
- Inputs:
-
- - src is either a file, or file-like object, or a
- string that can be resolved to a filename.
-
- Optional inputs:
-
- - title: a string to use as the demo name. Of most use when the demo
- you are making comes from an object that has no filename, or if you
- want an alternate denotation distinct from the filename.
-
- - arg_str(''): a string of arguments, internally converted to a list
- just like sys.argv, so the demo script can see a similar
- environment.
-
- - auto_all(None): global flag to run all blocks automatically without
- confirmation. This attribute overrides the block-level tags and
- applies to the whole demo. It is an attribute of the object, and
- can be changed at runtime simply by reassigning it to a boolean
- value.
- """
- if hasattr(src, "read"):
- # It seems to be a file or a file-like object
- self.fname = "from a file-like object"
- if title == '':
- self.title = "from a file-like object"
- else:
- self.title = title
- else:
- # Assume it's a string or something that can be converted to one
- self.fname = src
- if title == '':
- (filepath, filename) = os.path.split(src)
- self.title = filename
- else:
- self.title = title
- self.sys_argv = [src] + shlex.split(arg_str)
- self.auto_all = auto_all
- self.src = src
-
- # get a few things from ipython. While it's a bit ugly design-wise,
- # it ensures that things like color scheme and the like are always in
- # sync with the ipython mode being used. This class is only meant to
- # be used inside ipython anyways, so it's OK.
- ip = get_ipython() # this is in builtins whenever IPython is running
- self.ip_ns = ip.user_ns
- self.ip_colorize = ip.pycolorize
- self.ip_showtb = ip.showtraceback
- self.ip_run_cell = ip.run_cell
- self.shell = ip
-
- # load user data and initialize data structures
- self.reload()
-
- def fload(self):
- """Load file object."""
- # read data and parse into blocks
- if hasattr(self, 'fobj') and self.fobj is not None:
- self.fobj.close()
- if hasattr(self.src, "read"):
- # It seems to be a file or a file-like object
- self.fobj = self.src
- else:
- # Assume it's a string or something that can be converted to one
- self.fobj = openpy.open(self.fname)
-
- def reload(self):
- """Reload source from disk and initialize state."""
- self.fload()
-
- self.src = "".join(openpy.strip_encoding_cookie(self.fobj))
- src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
- self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
- self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
-
- # if auto_all is not given (def. None), we read it from the file
- if self.auto_all is None:
- self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
- else:
- self.auto_all = bool(self.auto_all)
-
- # Clean the sources from all markup so it doesn't get displayed when
- # running the demo
- src_blocks = []
- auto_strip = lambda s: self.re_auto.sub('',s)
- for i,b in enumerate(src_b):
- if self._auto[i]:
- src_blocks.append(auto_strip(b))
- else:
- src_blocks.append(b)
- # remove the auto_all marker
- src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
-
- self.nblocks = len(src_blocks)
- self.src_blocks = src_blocks
-
- # also build syntax-highlighted source
- self.src_blocks_colored = list(map(self.ip_colorize,self.src_blocks))
-
- # ensure clean namespace and seek offset
- self.reset()
-
- def reset(self):
- """Reset the namespace and seek pointer to restart the demo"""
- self.user_ns = {}
- self.finished = False
- self.block_index = 0
-
- def _validate_index(self,index):
- if index<0 or index>=self.nblocks:
- raise ValueError('invalid block index %s' % index)
-
- def _get_index(self,index):
- """Get the current block index, validating and checking status.
-
- Returns None if the demo is finished"""
-
- if index is None:
- if self.finished:
+ d = Demo('ex_demo.py')
+ d()
+
+Each time you call the demo object, it runs the next block. The demo object
+has a few useful methods for navigation, like again(), edit(), jump(), seek()
+and back(). It can be reset for a new run via reset() or reloaded from disk
+(in case you've edited the source) via reload(). See their docstrings below.
+
+Note: To make this simpler to explore, a file called "demo-exercizer.py" has
+been added to the "docs/examples/core" directory. Just cd to this directory in
+an IPython session, and type::
+
+ %run demo-exercizer.py
+
+and then follow the directions.
+
+Example
+-------
+
+The following is a very simple example of a valid demo file.
+
+::
+
+ #################### EXAMPLE DEMO <ex_demo.py> ###############################
+ '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
+
+ print 'Hello, welcome to an interactive IPython demo.'
+
+ # The mark below defines a block boundary, which is a point where IPython will
+ # stop execution and return to the interactive prompt. The dashes are actually
+ # optional and used only as a visual aid to clearly separate blocks while
+ # editing the demo code.
+ # <demo> stop
+
+ x = 1
+ y = 2
+
+ # <demo> stop
+
+ # the mark below makes this block as silent
+ # <demo> silent
+
+ print 'This is a silent block, which gets executed but not printed.'
+
+ # <demo> stop
+ # <demo> auto
+ print 'This is an automatic block.'
+ print 'It is executed without asking for confirmation, but printed.'
+ z = x+y
+
+ print 'z=',x
+
+ # <demo> stop
+ # This is just another normal block.
+ print 'z is now:', z
+
+ print 'bye!'
+ ################### END EXAMPLE DEMO <ex_demo.py> ############################
+"""
+
+from __future__ import unicode_literals
+
+#*****************************************************************************
+# Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#
+#*****************************************************************************
+from __future__ import print_function
+
+import os
+import re
+import shlex
+import sys
+
+from IPython.utils import io
+from IPython.utils.text import marquee
+from IPython.utils import openpy
+from IPython.utils import py3compat
+__all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
+
+class DemoError(Exception): pass
+
+def re_mark(mark):
+ return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
+
+class Demo(object):
+
+ re_stop = re_mark('-*\s?stop\s?-*')
+ re_silent = re_mark('silent')
+ re_auto = re_mark('auto')
+ re_auto_all = re_mark('auto_all')
+
+ def __init__(self,src,title='',arg_str='',auto_all=None):
+ """Make a new demo object. To run the demo, simply call the object.
+
+ See the module docstring for full details and an example (you can use
+ IPython.Demo? in IPython to see it).
+
+ Inputs:
+
+ - src is either a file, or file-like object, or a
+ string that can be resolved to a filename.
+
+ Optional inputs:
+
+ - title: a string to use as the demo name. Of most use when the demo
+ you are making comes from an object that has no filename, or if you
+ want an alternate denotation distinct from the filename.
+
+ - arg_str(''): a string of arguments, internally converted to a list
+ just like sys.argv, so the demo script can see a similar
+ environment.
+
+ - auto_all(None): global flag to run all blocks automatically without
+ confirmation. This attribute overrides the block-level tags and
+ applies to the whole demo. It is an attribute of the object, and
+ can be changed at runtime simply by reassigning it to a boolean
+ value.
+ """
+ if hasattr(src, "read"):
+ # It seems to be a file or a file-like object
+ self.fname = "from a file-like object"
+ if title == '':
+ self.title = "from a file-like object"
+ else:
+ self.title = title
+ else:
+ # Assume it's a string or something that can be converted to one
+ self.fname = src
+ if title == '':
+ (filepath, filename) = os.path.split(src)
+ self.title = filename
+ else:
+ self.title = title
+ self.sys_argv = [src] + shlex.split(arg_str)
+ self.auto_all = auto_all
+ self.src = src
+
+ # get a few things from ipython. While it's a bit ugly design-wise,
+ # it ensures that things like color scheme and the like are always in
+ # sync with the ipython mode being used. This class is only meant to
+ # be used inside ipython anyways, so it's OK.
+ ip = get_ipython() # this is in builtins whenever IPython is running
+ self.ip_ns = ip.user_ns
+ self.ip_colorize = ip.pycolorize
+ self.ip_showtb = ip.showtraceback
+ self.ip_run_cell = ip.run_cell
+ self.shell = ip
+
+ # load user data and initialize data structures
+ self.reload()
+
+ def fload(self):
+ """Load file object."""
+ # read data and parse into blocks
+ if hasattr(self, 'fobj') and self.fobj is not None:
+ self.fobj.close()
+ if hasattr(self.src, "read"):
+ # It seems to be a file or a file-like object
+ self.fobj = self.src
+ else:
+ # Assume it's a string or something that can be converted to one
+ self.fobj = openpy.open(self.fname)
+
+ def reload(self):
+ """Reload source from disk and initialize state."""
+ self.fload()
+
+ self.src = "".join(openpy.strip_encoding_cookie(self.fobj))
+ src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
+ self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
+ self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
+
+ # if auto_all is not given (def. None), we read it from the file
+ if self.auto_all is None:
+ self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
+ else:
+ self.auto_all = bool(self.auto_all)
+
+ # Clean the sources from all markup so it doesn't get displayed when
+ # running the demo
+ src_blocks = []
+ auto_strip = lambda s: self.re_auto.sub('',s)
+ for i,b in enumerate(src_b):
+ if self._auto[i]:
+ src_blocks.append(auto_strip(b))
+ else:
+ src_blocks.append(b)
+ # remove the auto_all marker
+ src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
+
+ self.nblocks = len(src_blocks)
+ self.src_blocks = src_blocks
+
+ # also build syntax-highlighted source
+ self.src_blocks_colored = list(map(self.ip_colorize,self.src_blocks))
+
+ # ensure clean namespace and seek offset
+ self.reset()
+
+ def reset(self):
+ """Reset the namespace and seek pointer to restart the demo"""
+ self.user_ns = {}
+ self.finished = False
+ self.block_index = 0
+
+ def _validate_index(self,index):
+ if index<0 or index>=self.nblocks:
+ raise ValueError('invalid block index %s' % index)
+
+ def _get_index(self,index):
+ """Get the current block index, validating and checking status.
+
+ Returns None if the demo is finished"""
+
+ if index is None:
+ if self.finished:
print('Demo finished. Use <demo_name>.reset() if you want to rerun it.')
- return None
- index = self.block_index
- else:
- self._validate_index(index)
- return index
-
- def seek(self,index):
- """Move the current seek pointer to the given block.
-
- You can use negative indices to seek from the end, with identical
- semantics to those of Python lists."""
- if index<0:
- index = self.nblocks + index
- self._validate_index(index)
- self.block_index = index
- self.finished = False
-
- def back(self,num=1):
- """Move the seek pointer back num blocks (default is 1)."""
- self.seek(self.block_index-num)
-
- def jump(self,num=1):
- """Jump a given number of blocks relative to the current one.
-
- The offset can be positive or negative, defaults to 1."""
- self.seek(self.block_index+num)
-
- def again(self):
- """Move the seek pointer back one block and re-execute."""
- self.back(1)
- self()
-
- def edit(self,index=None):
- """Edit a block.
-
- If no number is given, use the last block executed.
-
- This edits the in-memory copy of the demo, it does NOT modify the
- original source file. If you want to do that, simply open the file in
- an editor and use reload() when you make changes to the file. This
- method is meant to let you change a block during a demonstration for
- explanatory purposes, without damaging your original script."""
-
- index = self._get_index(index)
- if index is None:
- return
- # decrease the index by one (unless we're at the very beginning), so
- # that the default demo.edit() call opens up the sblock we've last run
- if index>0:
- index -= 1
-
- filename = self.shell.mktempfile(self.src_blocks[index])
- self.shell.hooks.editor(filename,1)
- with open(filename, 'r') as f:
- new_block = f.read()
- # update the source and colored block
- self.src_blocks[index] = new_block
- self.src_blocks_colored[index] = self.ip_colorize(new_block)
- self.block_index = index
- # call to run with the newly edited index
- self()
-
- def show(self,index=None):
- """Show a single block on screen"""
-
- index = self._get_index(index)
- if index is None:
- return
-
- print(self.marquee('<%s> block # %s (%s remaining)' %
+ return None
+ index = self.block_index
+ else:
+ self._validate_index(index)
+ return index
+
+ def seek(self,index):
+ """Move the current seek pointer to the given block.
+
+ You can use negative indices to seek from the end, with identical
+ semantics to those of Python lists."""
+ if index<0:
+ index = self.nblocks + index
+ self._validate_index(index)
+ self.block_index = index
+ self.finished = False
+
+ def back(self,num=1):
+ """Move the seek pointer back num blocks (default is 1)."""
+ self.seek(self.block_index-num)
+
+ def jump(self,num=1):
+ """Jump a given number of blocks relative to the current one.
+
+ The offset can be positive or negative, defaults to 1."""
+ self.seek(self.block_index+num)
+
+ def again(self):
+ """Move the seek pointer back one block and re-execute."""
+ self.back(1)
+ self()
+
+ def edit(self,index=None):
+ """Edit a block.
+
+ If no number is given, use the last block executed.
+
+ This edits the in-memory copy of the demo, it does NOT modify the
+ original source file. If you want to do that, simply open the file in
+ an editor and use reload() when you make changes to the file. This
+ method is meant to let you change a block during a demonstration for
+ explanatory purposes, without damaging your original script."""
+
+ index = self._get_index(index)
+ if index is None:
+ return
+ # decrease the index by one (unless we're at the very beginning), so
+ # that the default demo.edit() call opens up the sblock we've last run
+ if index>0:
+ index -= 1
+
+ filename = self.shell.mktempfile(self.src_blocks[index])
+ self.shell.hooks.editor(filename,1)
+ with open(filename, 'r') as f:
+ new_block = f.read()
+ # update the source and colored block
+ self.src_blocks[index] = new_block
+ self.src_blocks_colored[index] = self.ip_colorize(new_block)
+ self.block_index = index
+ # call to run with the newly edited index
+ self()
+
+ def show(self,index=None):
+ """Show a single block on screen"""
+
+ index = self._get_index(index)
+ if index is None:
+ return
+
+ print(self.marquee('<%s> block # %s (%s remaining)' %
(self.title,index,self.nblocks-index-1)))
print(self.src_blocks_colored[index])
- sys.stdout.flush()
-
- def show_all(self):
- """Show entire demo on screen, block by block"""
-
- fname = self.title
- title = self.title
- nblocks = self.nblocks
- silent = self._silent
- marquee = self.marquee
- for index,block in enumerate(self.src_blocks_colored):
- if silent[index]:
- print(marquee('<%s> SILENT block # %s (%s remaining)' %
+ sys.stdout.flush()
+
+ def show_all(self):
+ """Show entire demo on screen, block by block"""
+
+ fname = self.title
+ title = self.title
+ nblocks = self.nblocks
+ silent = self._silent
+ marquee = self.marquee
+ for index,block in enumerate(self.src_blocks_colored):
+ if silent[index]:
+ print(marquee('<%s> SILENT block # %s (%s remaining)' %
(title,index,nblocks-index-1)))
- else:
- print(marquee('<%s> block # %s (%s remaining)' %
+ else:
+ print(marquee('<%s> block # %s (%s remaining)' %
(title,index,nblocks-index-1)))
print(block, end=' ')
- sys.stdout.flush()
-
- def run_cell(self,source):
- """Execute a string with one or more lines of code"""
-
- exec(source, self.user_ns)
-
- def __call__(self,index=None):
- """run a block of the demo.
-
- If index is given, it should be an integer >=1 and <= nblocks. This
- means that the calling convention is one off from typical Python
- lists. The reason for the inconsistency is that the demo always
- prints 'Block n/N, and N is the total, so it would be very odd to use
- zero-indexing here."""
-
- index = self._get_index(index)
- if index is None:
- return
- try:
- marquee = self.marquee
- next_block = self.src_blocks[index]
- self.block_index += 1
- if self._silent[index]:
- print(marquee('Executing silent block # %s (%s remaining)' %
+ sys.stdout.flush()
+
+ def run_cell(self,source):
+ """Execute a string with one or more lines of code"""
+
+ exec(source, self.user_ns)
+
+ def __call__(self,index=None):
+ """run a block of the demo.
+
+ If index is given, it should be an integer >=1 and <= nblocks. This
+ means that the calling convention is one off from typical Python
+ lists. The reason for the inconsistency is that the demo always
+ prints 'Block n/N, and N is the total, so it would be very odd to use
+ zero-indexing here."""
+
+ index = self._get_index(index)
+ if index is None:
+ return
+ try:
+ marquee = self.marquee
+ next_block = self.src_blocks[index]
+ self.block_index += 1
+ if self._silent[index]:
+ print(marquee('Executing silent block # %s (%s remaining)' %
(index,self.nblocks-index-1)))
- else:
- self.pre_cmd()
- self.show(index)
- if self.auto_all or self._auto[index]:
+ else:
+ self.pre_cmd()
+ self.show(index)
+ if self.auto_all or self._auto[index]:
print(marquee('output:'))
- else:
+ else:
print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ')
- ans = py3compat.input().strip()
- if ans:
+ ans = py3compat.input().strip()
+ if ans:
print(marquee('Block NOT executed'))
- return
- try:
- save_argv = sys.argv
- sys.argv = self.sys_argv
- self.run_cell(next_block)
- self.post_cmd()
- finally:
- sys.argv = save_argv
-
- except:
- self.ip_showtb(filename=self.fname)
- else:
- self.ip_ns.update(self.user_ns)
-
- if self.block_index == self.nblocks:
- mq1 = self.marquee('END OF DEMO')
- if mq1:
+ return
+ try:
+ save_argv = sys.argv
+ sys.argv = self.sys_argv
+ self.run_cell(next_block)
+ self.post_cmd()
+ finally:
+ sys.argv = save_argv
+
+ except:
+ self.ip_showtb(filename=self.fname)
+ else:
+ self.ip_ns.update(self.user_ns)
+
+ if self.block_index == self.nblocks:
+ mq1 = self.marquee('END OF DEMO')
+ if mq1:
# avoid spurious print if empty marquees are used
print()
print(mq1)
print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'))
- self.finished = True
-
- # These methods are meant to be overridden by subclasses who may wish to
- # customize the behavior of of their demos.
- def marquee(self,txt='',width=78,mark='*'):
- """Return the input string centered in a 'marquee'."""
- return marquee(txt,width,mark)
-
- def pre_cmd(self):
- """Method called before executing each block."""
- pass
-
- def post_cmd(self):
- """Method called after executing each block."""
- pass
-
-
-class IPythonDemo(Demo):
- """Class for interactive demos with IPython's input processing applied.
-
- This subclasses Demo, but instead of executing each block by the Python
- interpreter (via exec), it actually calls IPython on it, so that any input
- filters which may be in place are applied to the input block.
-
- If you have an interactive environment which exposes special input
- processing, you can use this class instead to write demo scripts which
- operate exactly as if you had typed them interactively. The default Demo
- class requires the input to be valid, pure Python code.
- """
-
- def run_cell(self,source):
- """Execute a string with one or more lines of code"""
-
- self.shell.run_cell(source)
-
-class LineDemo(Demo):
- """Demo where each line is executed as a separate block.
-
- The input script should be valid Python code.
-
- This class doesn't require any markup at all, and it's meant for simple
- scripts (with no nesting or any kind of indentation) which consist of
- multiple lines of input to be executed, one at a time, as if they had been
- typed in the interactive prompt.
-
- Note: the input can not have *any* indentation, which means that only
- single-lines of input are accepted, not even function definitions are
- valid."""
-
- def reload(self):
- """Reload source from disk and initialize state."""
- # read data and parse into blocks
- self.fload()
- lines = self.fobj.readlines()
- src_b = [l for l in lines if l.strip()]
- nblocks = len(src_b)
- self.src = ''.join(lines)
- self._silent = [False]*nblocks
- self._auto = [True]*nblocks
- self.auto_all = True
- self.nblocks = nblocks
- self.src_blocks = src_b
-
- # also build syntax-highlighted source
- self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
-
- # ensure clean namespace and seek offset
- self.reset()
-
-
-class IPythonLineDemo(IPythonDemo,LineDemo):
- """Variant of the LineDemo class whose input is processed by IPython."""
- pass
-
-
-class ClearMixin(object):
- """Use this mixin to make Demo classes with less visual clutter.
-
- Demos using this mixin will clear the screen before every block and use
- blank marquees.
-
- Note that in order for the methods defined here to actually override those
- of the classes it's mixed with, it must go /first/ in the inheritance
- tree. For example:
-
- class ClearIPDemo(ClearMixin,IPythonDemo): pass
-
- will provide an IPythonDemo class with the mixin's features.
- """
-
- def marquee(self,txt='',width=78,mark='*'):
- """Blank marquee that returns '' no matter what the input."""
- return ''
-
- def pre_cmd(self):
- """Method called before executing each block.
-
- This one simply clears the screen."""
- from IPython.utils.terminal import term_clear
- term_clear()
-
-class ClearDemo(ClearMixin,Demo):
- pass
-
-
-class ClearIPDemo(ClearMixin,IPythonDemo):
- pass
+ self.finished = True
+
+ # These methods are meant to be overridden by subclasses who may wish to
+ # customize the behavior of of their demos.
+ def marquee(self,txt='',width=78,mark='*'):
+ """Return the input string centered in a 'marquee'."""
+ return marquee(txt,width,mark)
+
+ def pre_cmd(self):
+ """Method called before executing each block."""
+ pass
+
+ def post_cmd(self):
+ """Method called after executing each block."""
+ pass
+
+
+class IPythonDemo(Demo):
+ """Class for interactive demos with IPython's input processing applied.
+
+ This subclasses Demo, but instead of executing each block by the Python
+ interpreter (via exec), it actually calls IPython on it, so that any input
+ filters which may be in place are applied to the input block.
+
+ If you have an interactive environment which exposes special input
+ processing, you can use this class instead to write demo scripts which
+ operate exactly as if you had typed them interactively. The default Demo
+ class requires the input to be valid, pure Python code.
+ """
+
+ def run_cell(self,source):
+ """Execute a string with one or more lines of code"""
+
+ self.shell.run_cell(source)
+
+class LineDemo(Demo):
+ """Demo where each line is executed as a separate block.
+
+ The input script should be valid Python code.
+
+ This class doesn't require any markup at all, and it's meant for simple
+ scripts (with no nesting or any kind of indentation) which consist of
+ multiple lines of input to be executed, one at a time, as if they had been
+ typed in the interactive prompt.
+
+ Note: the input can not have *any* indentation, which means that only
+ single-lines of input are accepted, not even function definitions are
+ valid."""
+
+ def reload(self):
+ """Reload source from disk and initialize state."""
+ # read data and parse into blocks
+ self.fload()
+ lines = self.fobj.readlines()
+ src_b = [l for l in lines if l.strip()]
+ nblocks = len(src_b)
+ self.src = ''.join(lines)
+ self._silent = [False]*nblocks
+ self._auto = [True]*nblocks
+ self.auto_all = True
+ self.nblocks = nblocks
+ self.src_blocks = src_b
+
+ # also build syntax-highlighted source
+ self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
+
+ # ensure clean namespace and seek offset
+ self.reset()
+
+
+class IPythonLineDemo(IPythonDemo,LineDemo):
+ """Variant of the LineDemo class whose input is processed by IPython."""
+ pass
+
+
+class ClearMixin(object):
+ """Use this mixin to make Demo classes with less visual clutter.
+
+ Demos using this mixin will clear the screen before every block and use
+ blank marquees.
+
+ Note that in order for the methods defined here to actually override those
+ of the classes it's mixed with, it must go /first/ in the inheritance
+ tree. For example:
+
+ class ClearIPDemo(ClearMixin,IPythonDemo): pass
+
+ will provide an IPythonDemo class with the mixin's features.
+ """
+
+ def marquee(self,txt='',width=78,mark='*'):
+ """Blank marquee that returns '' no matter what the input."""
+ return ''
+
+ def pre_cmd(self):
+ """Method called before executing each block.
+
+ This one simply clears the screen."""
+ from IPython.utils.terminal import term_clear
+ term_clear()
+
+class ClearDemo(ClearMixin,Demo):
+ pass
+
+
+class ClearIPDemo(ClearMixin,IPythonDemo):
+ pass
diff --git a/contrib/python/ipython/py2/IPython/lib/display.py b/contrib/python/ipython/py2/IPython/lib/display.py
index bf55015ff4..9221e2e062 100644
--- a/contrib/python/ipython/py2/IPython/lib/display.py
+++ b/contrib/python/ipython/py2/IPython/lib/display.py
@@ -1,558 +1,558 @@
-"""Various display related classes.
-
-Authors : MinRK, gregcaporaso, dannystaple
-"""
-from os.path import exists, isfile, splitext, abspath, join, isdir
-from os import walk, sep
-
-from IPython.core.display import DisplayObject
-
-__all__ = ['Audio', 'IFrame', 'YouTubeVideo', 'VimeoVideo', 'ScribdDocument',
- 'FileLink', 'FileLinks']
-
-
-class Audio(DisplayObject):
- """Create an audio object.
-
- When this object is returned by an input cell or passed to the
- display function, it will result in Audio controls being displayed
- in the frontend (only works in the notebook).
-
- Parameters
- ----------
- data : numpy array, list, unicode, str or bytes
- Can be one of
-
- * Numpy 1d array containing the desired waveform (mono)
- * Numpy 2d array containing waveforms for each channel.
- Shape=(NCHAN, NSAMPLES). For the standard channel order, see
- http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
- * List of float or integer representing the waveform (mono)
- * String containing the filename
- * Bytestring containing raw PCM data or
- * URL pointing to a file on the web.
-
- If the array option is used the waveform will be normalized.
-
- If a filename or url is used the format support will be browser
- dependent.
- url : unicode
- A URL to download the data from.
- filename : unicode
- Path to a local file to load the data from.
- embed : boolean
+"""Various display related classes.
+
+Authors : MinRK, gregcaporaso, dannystaple
+"""
+from os.path import exists, isfile, splitext, abspath, join, isdir
+from os import walk, sep
+
+from IPython.core.display import DisplayObject
+
+__all__ = ['Audio', 'IFrame', 'YouTubeVideo', 'VimeoVideo', 'ScribdDocument',
+ 'FileLink', 'FileLinks']
+
+
+class Audio(DisplayObject):
+ """Create an audio object.
+
+ When this object is returned by an input cell or passed to the
+ display function, it will result in Audio controls being displayed
+ in the frontend (only works in the notebook).
+
+ Parameters
+ ----------
+ data : numpy array, list, unicode, str or bytes
+ Can be one of
+
+ * Numpy 1d array containing the desired waveform (mono)
+ * Numpy 2d array containing waveforms for each channel.
+ Shape=(NCHAN, NSAMPLES). For the standard channel order, see
+ http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
+ * List of float or integer representing the waveform (mono)
+ * String containing the filename
+ * Bytestring containing raw PCM data or
+ * URL pointing to a file on the web.
+
+ If the array option is used the waveform will be normalized.
+
+ If a filename or url is used the format support will be browser
+ dependent.
+ url : unicode
+ A URL to download the data from.
+ filename : unicode
+ Path to a local file to load the data from.
+ embed : boolean
Should the audio data be embedded using a data URI (True) or should
- the original source be referenced. Set this to True if you want the
- audio to playable later with no internet connection in the notebook.
-
- Default is `True`, unless the keyword argument `url` is set, then
- default value is `False`.
- rate : integer
- The sampling rate of the raw data.
- Only required when data parameter is being used as an array
- autoplay : bool
- Set to True if the audio should immediately start playing.
- Default is `False`.
-
- Examples
- --------
- ::
-
- # Generate a sound
- import numpy as np
- framerate = 44100
- t = np.linspace(0,5,framerate*5)
- data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t))
- Audio(data,rate=framerate)
-
- # Can also do stereo or more channels
- dataleft = np.sin(2*np.pi*220*t)
- dataright = np.sin(2*np.pi*224*t)
- Audio([dataleft, dataright],rate=framerate)
-
- Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # From URL
- Audio(url="http://www.w3schools.com/html/horse.ogg")
-
- Audio('/path/to/sound.wav') # From file
- Audio(filename='/path/to/sound.ogg')
-
- Audio(b'RAW_WAV_DATA..) # From bytes
- Audio(data=b'RAW_WAV_DATA..)
-
- """
- _read_flags = 'rb'
-
- def __init__(self, data=None, filename=None, url=None, embed=None, rate=None, autoplay=False):
- if filename is None and url is None and data is None:
- raise ValueError("No image data found. Expecting filename, url, or data.")
- if embed is False and url is None:
- raise ValueError("No url found. Expecting url when embed=False")
-
- if url is not None and embed is not True:
- self.embed = False
- else:
- self.embed = True
- self.autoplay = autoplay
- super(Audio, self).__init__(data=data, url=url, filename=filename)
-
- if self.data is not None and not isinstance(self.data, bytes):
- self.data = self._make_wav(data,rate)
-
- def reload(self):
- """Reload the raw data from file or URL."""
- import mimetypes
- if self.embed:
- super(Audio, self).reload()
-
- if self.filename is not None:
- self.mimetype = mimetypes.guess_type(self.filename)[0]
- elif self.url is not None:
- self.mimetype = mimetypes.guess_type(self.url)[0]
- else:
- self.mimetype = "audio/wav"
-
- def _make_wav(self, data, rate):
- """ Transform a numpy array to a PCM bytestring """
- import struct
- from io import BytesIO
- import wave
-
- try:
- import numpy as np
-
- data = np.array(data, dtype=float)
- if len(data.shape) == 1:
- nchan = 1
- elif len(data.shape) == 2:
- # In wave files,channels are interleaved. E.g.,
- # "L1R1L2R2..." for stereo. See
- # http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
- # for channel ordering
- nchan = data.shape[0]
- data = data.T.ravel()
- else:
- raise ValueError('Array audio input must be a 1D or 2D array')
- scaled = np.int16(data/np.max(np.abs(data))*32767).tolist()
- except ImportError:
- # check that it is a "1D" list
- idata = iter(data) # fails if not an iterable
- try:
- iter(idata.next())
- raise TypeError('Only lists of mono audio are '
- 'supported if numpy is not installed')
- except TypeError:
- # this means it's not a nested list, which is what we want
- pass
- maxabsvalue = float(max([abs(x) for x in data]))
- scaled = [int(x/maxabsvalue*32767) for x in data]
- nchan = 1
-
- fp = BytesIO()
- waveobj = wave.open(fp,mode='wb')
- waveobj.setnchannels(nchan)
- waveobj.setframerate(rate)
- waveobj.setsampwidth(2)
- waveobj.setcomptype('NONE','NONE')
- waveobj.writeframes(b''.join([struct.pack('<h',x) for x in scaled]))
- val = fp.getvalue()
- waveobj.close()
-
- return val
-
- def _data_and_metadata(self):
- """shortcut for returning metadata with url information, if defined"""
- md = {}
- if self.url:
- md['url'] = self.url
- if md:
- return self.data, md
- else:
- return self.data
-
- def _repr_html_(self):
- src = """
- <audio controls="controls" {autoplay}>
- <source src="{src}" type="{type}" />
- Your browser does not support the audio element.
- </audio>
- """
- return src.format(src=self.src_attr(),type=self.mimetype, autoplay=self.autoplay_attr())
-
- def src_attr(self):
- import base64
- if self.embed and (self.data is not None):
- data = base64=base64.b64encode(self.data).decode('ascii')
- return """data:{type};base64,{base64}""".format(type=self.mimetype,
- base64=data)
- elif self.url is not None:
- return self.url
- else:
- return ""
-
- def autoplay_attr(self):
- if(self.autoplay):
- return 'autoplay="autoplay"'
- else:
- return ''
-
-class IFrame(object):
- """
- Generic class to embed an iframe in an IPython notebook
- """
-
- iframe = """
- <iframe
- width="{width}"
- height="{height}"
- src="{src}{params}"
- frameborder="0"
- allowfullscreen
- ></iframe>
- """
-
- def __init__(self, src, width, height, **kwargs):
- self.src = src
- self.width = width
- self.height = height
- self.params = kwargs
-
- def _repr_html_(self):
- """return the embed iframe"""
- if self.params:
- try:
- from urllib.parse import urlencode # Py 3
- except ImportError:
- from urllib import urlencode
- params = "?" + urlencode(self.params)
- else:
- params = ""
- return self.iframe.format(src=self.src,
- width=self.width,
- height=self.height,
- params=params)
-
-class YouTubeVideo(IFrame):
- """Class for embedding a YouTube Video in an IPython session, based on its video id.
-
- e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would
- do::
-
- vid = YouTubeVideo("foo")
- display(vid)
-
- To start from 30 seconds::
-
- vid = YouTubeVideo("abc", start=30)
- display(vid)
-
- To calculate seconds from time as hours, minutes, seconds use
- :class:`datetime.timedelta`::
-
- start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
-
- Other parameters can be provided as documented at
+ the original source be referenced. Set this to True if you want the
+ audio to playable later with no internet connection in the notebook.
+
+ Default is `True`, unless the keyword argument `url` is set, then
+ default value is `False`.
+ rate : integer
+ The sampling rate of the raw data.
+ Only required when data parameter is being used as an array
+ autoplay : bool
+ Set to True if the audio should immediately start playing.
+ Default is `False`.
+
+ Examples
+ --------
+ ::
+
+ # Generate a sound
+ import numpy as np
+ framerate = 44100
+ t = np.linspace(0,5,framerate*5)
+ data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t))
+ Audio(data,rate=framerate)
+
+ # Can also do stereo or more channels
+ dataleft = np.sin(2*np.pi*220*t)
+ dataright = np.sin(2*np.pi*224*t)
+ Audio([dataleft, dataright],rate=framerate)
+
+ Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # From URL
+ Audio(url="http://www.w3schools.com/html/horse.ogg")
+
+ Audio('/path/to/sound.wav') # From file
+ Audio(filename='/path/to/sound.ogg')
+
+ Audio(b'RAW_WAV_DATA..) # From bytes
+ Audio(data=b'RAW_WAV_DATA..)
+
+ """
+ _read_flags = 'rb'
+
+ def __init__(self, data=None, filename=None, url=None, embed=None, rate=None, autoplay=False):
+ if filename is None and url is None and data is None:
+ raise ValueError("No image data found. Expecting filename, url, or data.")
+ if embed is False and url is None:
+ raise ValueError("No url found. Expecting url when embed=False")
+
+ if url is not None and embed is not True:
+ self.embed = False
+ else:
+ self.embed = True
+ self.autoplay = autoplay
+ super(Audio, self).__init__(data=data, url=url, filename=filename)
+
+ if self.data is not None and not isinstance(self.data, bytes):
+ self.data = self._make_wav(data,rate)
+
+ def reload(self):
+ """Reload the raw data from file or URL."""
+ import mimetypes
+ if self.embed:
+ super(Audio, self).reload()
+
+ if self.filename is not None:
+ self.mimetype = mimetypes.guess_type(self.filename)[0]
+ elif self.url is not None:
+ self.mimetype = mimetypes.guess_type(self.url)[0]
+ else:
+ self.mimetype = "audio/wav"
+
+ def _make_wav(self, data, rate):
+ """ Transform a numpy array to a PCM bytestring """
+ import struct
+ from io import BytesIO
+ import wave
+
+ try:
+ import numpy as np
+
+ data = np.array(data, dtype=float)
+ if len(data.shape) == 1:
+ nchan = 1
+ elif len(data.shape) == 2:
+ # In wave files,channels are interleaved. E.g.,
+ # "L1R1L2R2..." for stereo. See
+ # http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
+ # for channel ordering
+ nchan = data.shape[0]
+ data = data.T.ravel()
+ else:
+ raise ValueError('Array audio input must be a 1D or 2D array')
+ scaled = np.int16(data/np.max(np.abs(data))*32767).tolist()
+ except ImportError:
+ # check that it is a "1D" list
+ idata = iter(data) # fails if not an iterable
+ try:
+ iter(idata.next())
+ raise TypeError('Only lists of mono audio are '
+ 'supported if numpy is not installed')
+ except TypeError:
+ # this means it's not a nested list, which is what we want
+ pass
+ maxabsvalue = float(max([abs(x) for x in data]))
+ scaled = [int(x/maxabsvalue*32767) for x in data]
+ nchan = 1
+
+ fp = BytesIO()
+ waveobj = wave.open(fp,mode='wb')
+ waveobj.setnchannels(nchan)
+ waveobj.setframerate(rate)
+ waveobj.setsampwidth(2)
+ waveobj.setcomptype('NONE','NONE')
+ waveobj.writeframes(b''.join([struct.pack('<h',x) for x in scaled]))
+ val = fp.getvalue()
+ waveobj.close()
+
+ return val
+
+ def _data_and_metadata(self):
+ """shortcut for returning metadata with url information, if defined"""
+ md = {}
+ if self.url:
+ md['url'] = self.url
+ if md:
+ return self.data, md
+ else:
+ return self.data
+
+ def _repr_html_(self):
+ src = """
+ <audio controls="controls" {autoplay}>
+ <source src="{src}" type="{type}" />
+ Your browser does not support the audio element.
+ </audio>
+ """
+ return src.format(src=self.src_attr(),type=self.mimetype, autoplay=self.autoplay_attr())
+
+ def src_attr(self):
+ import base64
+ if self.embed and (self.data is not None):
+ data = base64=base64.b64encode(self.data).decode('ascii')
+ return """data:{type};base64,{base64}""".format(type=self.mimetype,
+ base64=data)
+ elif self.url is not None:
+ return self.url
+ else:
+ return ""
+
+ def autoplay_attr(self):
+ if(self.autoplay):
+ return 'autoplay="autoplay"'
+ else:
+ return ''
+
+class IFrame(object):
+ """
+ Generic class to embed an iframe in an IPython notebook
+ """
+
+ iframe = """
+ <iframe
+ width="{width}"
+ height="{height}"
+ src="{src}{params}"
+ frameborder="0"
+ allowfullscreen
+ ></iframe>
+ """
+
+ def __init__(self, src, width, height, **kwargs):
+ self.src = src
+ self.width = width
+ self.height = height
+ self.params = kwargs
+
+ def _repr_html_(self):
+ """return the embed iframe"""
+ if self.params:
+ try:
+ from urllib.parse import urlencode # Py 3
+ except ImportError:
+ from urllib import urlencode
+ params = "?" + urlencode(self.params)
+ else:
+ params = ""
+ return self.iframe.format(src=self.src,
+ width=self.width,
+ height=self.height,
+ params=params)
+
+class YouTubeVideo(IFrame):
+ """Class for embedding a YouTube Video in an IPython session, based on its video id.
+
+ e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would
+ do::
+
+ vid = YouTubeVideo("foo")
+ display(vid)
+
+ To start from 30 seconds::
+
+ vid = YouTubeVideo("abc", start=30)
+ display(vid)
+
+ To calculate seconds from time as hours, minutes, seconds use
+ :class:`datetime.timedelta`::
+
+ start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
+
+ Other parameters can be provided as documented at
https://developers.google.com/youtube/player_parameters#Parameters
-
- When converting the notebook using nbconvert, a jpeg representation of the video
- will be inserted in the document.
- """
-
- def __init__(self, id, width=400, height=300, **kwargs):
- self.id=id
- src = "https://www.youtube.com/embed/{0}".format(id)
- super(YouTubeVideo, self).__init__(src, width, height, **kwargs)
-
- def _repr_jpeg_(self):
- try:
- from urllib.request import urlopen # Py3
- except ImportError:
- from urllib2 import urlopen
- try:
- return urlopen("https://img.youtube.com/vi/{id}/hqdefault.jpg".format(id=self.id)).read()
- except IOError:
- return None
-
-class VimeoVideo(IFrame):
- """
- Class for embedding a Vimeo video in an IPython session, based on its video id.
- """
-
- def __init__(self, id, width=400, height=300, **kwargs):
- src="https://player.vimeo.com/video/{0}".format(id)
- super(VimeoVideo, self).__init__(src, width, height, **kwargs)
-
-class ScribdDocument(IFrame):
- """
- Class for embedding a Scribd document in an IPython session
-
- Use the start_page params to specify a starting point in the document
- Use the view_mode params to specify display type one off scroll | slideshow | book
-
- e.g to Display Wes' foundational paper about PANDAS in book mode from page 3
-
- ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book")
- """
-
- def __init__(self, id, width=400, height=300, **kwargs):
- src="https://www.scribd.com/embeds/{0}/content".format(id)
- super(ScribdDocument, self).__init__(src, width, height, **kwargs)
-
-class FileLink(object):
- """Class for embedding a local file link in an IPython session, based on path
-
- e.g. to embed a link that was generated in the IPython notebook as my/data.txt
-
- you would do::
-
- local_file = FileLink("my/data.txt")
- display(local_file)
-
- or in the HTML notebook, just::
-
- FileLink("my/data.txt")
- """
-
- html_link_str = "<a href='%s' target='_blank'>%s</a>"
-
- def __init__(self,
- path,
- url_prefix='',
- result_html_prefix='',
- result_html_suffix='<br>'):
- """
- Parameters
- ----------
- path : str
- path to the file or directory that should be formatted
+
+ When converting the notebook using nbconvert, a jpeg representation of the video
+ will be inserted in the document.
+ """
+
+ def __init__(self, id, width=400, height=300, **kwargs):
+ self.id=id
+ src = "https://www.youtube.com/embed/{0}".format(id)
+ super(YouTubeVideo, self).__init__(src, width, height, **kwargs)
+
+ def _repr_jpeg_(self):
+ try:
+ from urllib.request import urlopen # Py3
+ except ImportError:
+ from urllib2 import urlopen
+ try:
+ return urlopen("https://img.youtube.com/vi/{id}/hqdefault.jpg".format(id=self.id)).read()
+ except IOError:
+ return None
+
+class VimeoVideo(IFrame):
+ """
+ Class for embedding a Vimeo video in an IPython session, based on its video id.
+ """
+
+ def __init__(self, id, width=400, height=300, **kwargs):
+ src="https://player.vimeo.com/video/{0}".format(id)
+ super(VimeoVideo, self).__init__(src, width, height, **kwargs)
+
+class ScribdDocument(IFrame):
+ """
+ Class for embedding a Scribd document in an IPython session
+
+ Use the start_page params to specify a starting point in the document
+ Use the view_mode params to specify display type one off scroll | slideshow | book
+
+ e.g to Display Wes' foundational paper about PANDAS in book mode from page 3
+
+ ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book")
+ """
+
+ def __init__(self, id, width=400, height=300, **kwargs):
+ src="https://www.scribd.com/embeds/{0}/content".format(id)
+ super(ScribdDocument, self).__init__(src, width, height, **kwargs)
+
+class FileLink(object):
+ """Class for embedding a local file link in an IPython session, based on path
+
+ e.g. to embed a link that was generated in the IPython notebook as my/data.txt
+
+ you would do::
+
+ local_file = FileLink("my/data.txt")
+ display(local_file)
+
+ or in the HTML notebook, just::
+
+ FileLink("my/data.txt")
+ """
+
+ html_link_str = "<a href='%s' target='_blank'>%s</a>"
+
+ def __init__(self,
+ path,
+ url_prefix='',
+ result_html_prefix='',
+ result_html_suffix='<br>'):
+ """
+ Parameters
+ ----------
+ path : str
+ path to the file or directory that should be formatted
url_prefix : str
- prefix to be prepended to all files to form a working link [default:
+ prefix to be prepended to all files to form a working link [default:
'']
- result_html_prefix : str
+ result_html_prefix : str
text to append to beginning to link [default: '']
- result_html_suffix : str
- text to append at the end of link [default: '<br>']
- """
- if isdir(path):
- raise ValueError("Cannot display a directory using FileLink. "
- "Use FileLinks to display '%s'." % path)
- self.path = path
- self.url_prefix = url_prefix
- self.result_html_prefix = result_html_prefix
- self.result_html_suffix = result_html_suffix
-
- def _format_path(self):
- fp = ''.join([self.url_prefix,self.path])
- return ''.join([self.result_html_prefix,
- self.html_link_str % (fp, self.path),
- self.result_html_suffix])
-
- def _repr_html_(self):
- """return html link to file
- """
- if not exists(self.path):
- return ("Path (<tt>%s</tt>) doesn't exist. "
- "It may still be in the process of "
- "being generated, or you may have the "
- "incorrect path." % self.path)
-
- return self._format_path()
-
- def __repr__(self):
- """return absolute path to file
- """
- return abspath(self.path)
-
-class FileLinks(FileLink):
- """Class for embedding local file links in an IPython session, based on path
-
- e.g. to embed links to files that were generated in the IPython notebook
- under ``my/data``, you would do::
-
- local_files = FileLinks("my/data")
- display(local_files)
-
- or in the HTML notebook, just::
-
- FileLinks("my/data")
- """
- def __init__(self,
- path,
- url_prefix='',
- included_suffixes=None,
- result_html_prefix='',
- result_html_suffix='<br>',
- notebook_display_formatter=None,
- terminal_display_formatter=None,
- recursive=True):
- """
- See :class:`FileLink` for the ``path``, ``url_prefix``,
- ``result_html_prefix`` and ``result_html_suffix`` parameters.
-
- included_suffixes : list
- Filename suffixes to include when formatting output [default: include
- all files]
-
- notebook_display_formatter : function
- Used to format links for display in the notebook. See discussion of
- formatter functions below.
-
- terminal_display_formatter : function
- Used to format links for display in the terminal. See discussion of
- formatter functions below.
-
- Formatter functions must be of the form::
-
- f(dirname, fnames, included_suffixes)
-
- dirname : str
- The name of a directory
- fnames : list
- The files in that directory
- included_suffixes : list
- The file suffixes that should be included in the output (passing None
- meansto include all suffixes in the output in the built-in formatters)
- recursive : boolean
- Whether to recurse into subdirectories. Default is True.
-
- The function should return a list of lines that will be printed in the
- notebook (if passing notebook_display_formatter) or the terminal (if
- passing terminal_display_formatter). This function is iterated over for
- each directory in self.path. Default formatters are in place, can be
- passed here to support alternative formatting.
-
- """
- if isfile(path):
- raise ValueError("Cannot display a file using FileLinks. "
- "Use FileLink to display '%s'." % path)
- self.included_suffixes = included_suffixes
- # remove trailing slashs for more consistent output formatting
- path = path.rstrip('/')
-
- self.path = path
- self.url_prefix = url_prefix
- self.result_html_prefix = result_html_prefix
- self.result_html_suffix = result_html_suffix
-
- self.notebook_display_formatter = \
- notebook_display_formatter or self._get_notebook_display_formatter()
- self.terminal_display_formatter = \
- terminal_display_formatter or self._get_terminal_display_formatter()
-
- self.recursive = recursive
-
- def _get_display_formatter(self,
- dirname_output_format,
- fname_output_format,
- fp_format,
- fp_cleaner=None):
- """ generate built-in formatter function
-
- this is used to define both the notebook and terminal built-in
- formatters as they only differ by some wrapper text for each entry
-
- dirname_output_format: string to use for formatting directory
- names, dirname will be substituted for a single "%s" which
- must appear in this string
- fname_output_format: string to use for formatting file names,
- if a single "%s" appears in the string, fname will be substituted
- if two "%s" appear in the string, the path to fname will be
- substituted for the first and fname will be substituted for the
- second
- fp_format: string to use for formatting filepaths, must contain
- exactly two "%s" and the dirname will be subsituted for the first
- and fname will be substituted for the second
- """
- def f(dirname, fnames, included_suffixes=None):
- result = []
- # begin by figuring out which filenames, if any,
- # are going to be displayed
- display_fnames = []
- for fname in fnames:
- if (isfile(join(dirname,fname)) and
- (included_suffixes is None or
- splitext(fname)[1] in included_suffixes)):
- display_fnames.append(fname)
-
- if len(display_fnames) == 0:
- # if there are no filenames to display, don't print anything
- # (not even the directory name)
- pass
- else:
- # otherwise print the formatted directory name followed by
- # the formatted filenames
- dirname_output_line = dirname_output_format % dirname
- result.append(dirname_output_line)
- for fname in display_fnames:
- fp = fp_format % (dirname,fname)
- if fp_cleaner is not None:
- fp = fp_cleaner(fp)
- try:
- # output can include both a filepath and a filename...
- fname_output_line = fname_output_format % (fp, fname)
- except TypeError:
- # ... or just a single filepath
- fname_output_line = fname_output_format % fname
- result.append(fname_output_line)
- return result
- return f
-
- def _get_notebook_display_formatter(self,
- spacer="&nbsp;&nbsp;"):
- """ generate function to use for notebook formatting
- """
- dirname_output_format = \
- self.result_html_prefix + "%s/" + self.result_html_suffix
- fname_output_format = \
- self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
- fp_format = self.url_prefix + '%s/%s'
- if sep == "\\":
- # Working on a platform where the path separator is "\", so
- # must convert these to "/" for generating a URI
- def fp_cleaner(fp):
- # Replace all occurences of backslash ("\") with a forward
- # slash ("/") - this is necessary on windows when a path is
- # provided as input, but we must link to a URI
- return fp.replace('\\','/')
- else:
- fp_cleaner = None
-
- return self._get_display_formatter(dirname_output_format,
- fname_output_format,
- fp_format,
- fp_cleaner)
-
- def _get_terminal_display_formatter(self,
- spacer=" "):
- """ generate function to use for terminal formatting
- """
- dirname_output_format = "%s/"
- fname_output_format = spacer + "%s"
- fp_format = '%s/%s'
-
- return self._get_display_formatter(dirname_output_format,
- fname_output_format,
- fp_format)
-
- def _format_path(self):
- result_lines = []
- if self.recursive:
- walked_dir = list(walk(self.path))
- else:
- walked_dir = [next(walk(self.path))]
- walked_dir.sort()
- for dirname, subdirs, fnames in walked_dir:
- result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
- return '\n'.join(result_lines)
-
- def __repr__(self):
- """return newline-separated absolute paths
- """
- result_lines = []
- if self.recursive:
- walked_dir = list(walk(self.path))
- else:
- walked_dir = [next(walk(self.path))]
- walked_dir.sort()
- for dirname, subdirs, fnames in walked_dir:
- result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
- return '\n'.join(result_lines)
+ result_html_suffix : str
+ text to append at the end of link [default: '<br>']
+ """
+ if isdir(path):
+ raise ValueError("Cannot display a directory using FileLink. "
+ "Use FileLinks to display '%s'." % path)
+ self.path = path
+ self.url_prefix = url_prefix
+ self.result_html_prefix = result_html_prefix
+ self.result_html_suffix = result_html_suffix
+
+ def _format_path(self):
+ fp = ''.join([self.url_prefix,self.path])
+ return ''.join([self.result_html_prefix,
+ self.html_link_str % (fp, self.path),
+ self.result_html_suffix])
+
+ def _repr_html_(self):
+ """return html link to file
+ """
+ if not exists(self.path):
+ return ("Path (<tt>%s</tt>) doesn't exist. "
+ "It may still be in the process of "
+ "being generated, or you may have the "
+ "incorrect path." % self.path)
+
+ return self._format_path()
+
+ def __repr__(self):
+ """return absolute path to file
+ """
+ return abspath(self.path)
+
+class FileLinks(FileLink):
+ """Class for embedding local file links in an IPython session, based on path
+
+ e.g. to embed links to files that were generated in the IPython notebook
+ under ``my/data``, you would do::
+
+ local_files = FileLinks("my/data")
+ display(local_files)
+
+ or in the HTML notebook, just::
+
+ FileLinks("my/data")
+ """
+ def __init__(self,
+ path,
+ url_prefix='',
+ included_suffixes=None,
+ result_html_prefix='',
+ result_html_suffix='<br>',
+ notebook_display_formatter=None,
+ terminal_display_formatter=None,
+ recursive=True):
+ """
+ See :class:`FileLink` for the ``path``, ``url_prefix``,
+ ``result_html_prefix`` and ``result_html_suffix`` parameters.
+
+ included_suffixes : list
+ Filename suffixes to include when formatting output [default: include
+ all files]
+
+ notebook_display_formatter : function
+ Used to format links for display in the notebook. See discussion of
+ formatter functions below.
+
+ terminal_display_formatter : function
+ Used to format links for display in the terminal. See discussion of
+ formatter functions below.
+
+ Formatter functions must be of the form::
+
+ f(dirname, fnames, included_suffixes)
+
+ dirname : str
+ The name of a directory
+ fnames : list
+ The files in that directory
+ included_suffixes : list
+ The file suffixes that should be included in the output (passing None
+ meansto include all suffixes in the output in the built-in formatters)
+ recursive : boolean
+ Whether to recurse into subdirectories. Default is True.
+
+ The function should return a list of lines that will be printed in the
+ notebook (if passing notebook_display_formatter) or the terminal (if
+ passing terminal_display_formatter). This function is iterated over for
+ each directory in self.path. Default formatters are in place, can be
+ passed here to support alternative formatting.
+
+ """
+ if isfile(path):
+ raise ValueError("Cannot display a file using FileLinks. "
+ "Use FileLink to display '%s'." % path)
+ self.included_suffixes = included_suffixes
+ # remove trailing slashs for more consistent output formatting
+ path = path.rstrip('/')
+
+ self.path = path
+ self.url_prefix = url_prefix
+ self.result_html_prefix = result_html_prefix
+ self.result_html_suffix = result_html_suffix
+
+ self.notebook_display_formatter = \
+ notebook_display_formatter or self._get_notebook_display_formatter()
+ self.terminal_display_formatter = \
+ terminal_display_formatter or self._get_terminal_display_formatter()
+
+ self.recursive = recursive
+
+ def _get_display_formatter(self,
+ dirname_output_format,
+ fname_output_format,
+ fp_format,
+ fp_cleaner=None):
+ """ generate built-in formatter function
+
+ this is used to define both the notebook and terminal built-in
+ formatters as they only differ by some wrapper text for each entry
+
+ dirname_output_format: string to use for formatting directory
+ names, dirname will be substituted for a single "%s" which
+ must appear in this string
+ fname_output_format: string to use for formatting file names,
+ if a single "%s" appears in the string, fname will be substituted
+ if two "%s" appear in the string, the path to fname will be
+ substituted for the first and fname will be substituted for the
+ second
+ fp_format: string to use for formatting filepaths, must contain
+ exactly two "%s" and the dirname will be subsituted for the first
+ and fname will be substituted for the second
+ """
+ def f(dirname, fnames, included_suffixes=None):
+ result = []
+ # begin by figuring out which filenames, if any,
+ # are going to be displayed
+ display_fnames = []
+ for fname in fnames:
+ if (isfile(join(dirname,fname)) and
+ (included_suffixes is None or
+ splitext(fname)[1] in included_suffixes)):
+ display_fnames.append(fname)
+
+ if len(display_fnames) == 0:
+ # if there are no filenames to display, don't print anything
+ # (not even the directory name)
+ pass
+ else:
+ # otherwise print the formatted directory name followed by
+ # the formatted filenames
+ dirname_output_line = dirname_output_format % dirname
+ result.append(dirname_output_line)
+ for fname in display_fnames:
+ fp = fp_format % (dirname,fname)
+ if fp_cleaner is not None:
+ fp = fp_cleaner(fp)
+ try:
+ # output can include both a filepath and a filename...
+ fname_output_line = fname_output_format % (fp, fname)
+ except TypeError:
+ # ... or just a single filepath
+ fname_output_line = fname_output_format % fname
+ result.append(fname_output_line)
+ return result
+ return f
+
+ def _get_notebook_display_formatter(self,
+ spacer="&nbsp;&nbsp;"):
+ """ generate function to use for notebook formatting
+ """
+ dirname_output_format = \
+ self.result_html_prefix + "%s/" + self.result_html_suffix
+ fname_output_format = \
+ self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
+ fp_format = self.url_prefix + '%s/%s'
+ if sep == "\\":
+ # Working on a platform where the path separator is "\", so
+ # must convert these to "/" for generating a URI
+ def fp_cleaner(fp):
+ # Replace all occurences of backslash ("\") with a forward
+ # slash ("/") - this is necessary on windows when a path is
+ # provided as input, but we must link to a URI
+ return fp.replace('\\','/')
+ else:
+ fp_cleaner = None
+
+ return self._get_display_formatter(dirname_output_format,
+ fname_output_format,
+ fp_format,
+ fp_cleaner)
+
+ def _get_terminal_display_formatter(self,
+ spacer=" "):
+ """ generate function to use for terminal formatting
+ """
+ dirname_output_format = "%s/"
+ fname_output_format = spacer + "%s"
+ fp_format = '%s/%s'
+
+ return self._get_display_formatter(dirname_output_format,
+ fname_output_format,
+ fp_format)
+
+ def _format_path(self):
+ result_lines = []
+ if self.recursive:
+ walked_dir = list(walk(self.path))
+ else:
+ walked_dir = [next(walk(self.path))]
+ walked_dir.sort()
+ for dirname, subdirs, fnames in walked_dir:
+ result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
+ return '\n'.join(result_lines)
+
+ def __repr__(self):
+ """return newline-separated absolute paths
+ """
+ result_lines = []
+ if self.recursive:
+ walked_dir = list(walk(self.path))
+ else:
+ walked_dir = [next(walk(self.path))]
+ walked_dir.sort()
+ for dirname, subdirs, fnames in walked_dir:
+ result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
+ return '\n'.join(result_lines)
diff --git a/contrib/python/ipython/py2/IPython/lib/editorhooks.py b/contrib/python/ipython/py2/IPython/lib/editorhooks.py
index 31964fbe72..392557b509 100644
--- a/contrib/python/ipython/py2/IPython/lib/editorhooks.py
+++ b/contrib/python/ipython/py2/IPython/lib/editorhooks.py
@@ -1,129 +1,129 @@
-""" 'editor' hooks for common editors that work well with ipython
-
-They should honor the line number argument, at least.
-
-Contributions are *very* welcome.
-"""
-from __future__ import print_function
-
-import os
-import pipes
-import shlex
-import subprocess
-import sys
-
-from IPython import get_ipython
-from IPython.core.error import TryNext
-from IPython.utils import py3compat
-
-
-def install_editor(template, wait=False):
- """Installs the editor that is called by IPython for the %edit magic.
-
- This overrides the default editor, which is generally set by your EDITOR
- environment variable or is notepad (windows) or vi (linux). By supplying a
- template string `run_template`, you can control how the editor is invoked
- by IPython -- (e.g. the format in which it accepts command line options)
-
- Parameters
- ----------
- template : basestring
- run_template acts as a template for how your editor is invoked by
- the shell. It should contain '{filename}', which will be replaced on
- invokation with the file name, and '{line}', $line by line number
- (or 0) to invoke the file with.
- wait : bool
- If `wait` is true, wait until the user presses enter before returning,
- to facilitate non-blocking editors that exit immediately after
- the call.
- """
-
- # not all editors support $line, so we'll leave out this check
- # for substitution in ['$file', '$line']:
- # if not substitution in run_template:
- # raise ValueError(('run_template should contain %s'
- # ' for string substitution. You supplied "%s"' % (substitution,
- # run_template)))
-
- def call_editor(self, filename, line=0):
- if line is None:
- line = 0
- cmd = template.format(filename=pipes.quote(filename), line=line)
- print(">", cmd)
- # pipes.quote doesn't work right on Windows, but it does after splitting
- if sys.platform.startswith('win'):
- cmd = shlex.split(cmd)
- proc = subprocess.Popen(cmd, shell=True)
+""" 'editor' hooks for common editors that work well with ipython
+
+They should honor the line number argument, at least.
+
+Contributions are *very* welcome.
+"""
+from __future__ import print_function
+
+import os
+import pipes
+import shlex
+import subprocess
+import sys
+
+from IPython import get_ipython
+from IPython.core.error import TryNext
+from IPython.utils import py3compat
+
+
+def install_editor(template, wait=False):
+ """Installs the editor that is called by IPython for the %edit magic.
+
+ This overrides the default editor, which is generally set by your EDITOR
+ environment variable or is notepad (windows) or vi (linux). By supplying a
+ template string `run_template`, you can control how the editor is invoked
+ by IPython -- (e.g. the format in which it accepts command line options)
+
+ Parameters
+ ----------
+ template : basestring
+ run_template acts as a template for how your editor is invoked by
+ the shell. It should contain '{filename}', which will be replaced on
+ invokation with the file name, and '{line}', $line by line number
+ (or 0) to invoke the file with.
+ wait : bool
+ If `wait` is true, wait until the user presses enter before returning,
+ to facilitate non-blocking editors that exit immediately after
+ the call.
+ """
+
+ # not all editors support $line, so we'll leave out this check
+ # for substitution in ['$file', '$line']:
+ # if not substitution in run_template:
+ # raise ValueError(('run_template should contain %s'
+ # ' for string substitution. You supplied "%s"' % (substitution,
+ # run_template)))
+
+ def call_editor(self, filename, line=0):
+ if line is None:
+ line = 0
+ cmd = template.format(filename=pipes.quote(filename), line=line)
+ print(">", cmd)
+ # pipes.quote doesn't work right on Windows, but it does after splitting
+ if sys.platform.startswith('win'):
+ cmd = shlex.split(cmd)
+ proc = subprocess.Popen(cmd, shell=True)
if proc.wait() != 0:
- raise TryNext()
- if wait:
- py3compat.input("Press Enter when done editing:")
-
- get_ipython().set_hook('editor', call_editor)
- get_ipython().editor = template
-
-
-# in these, exe is always the path/name of the executable. Useful
-# if you don't have the editor directory in your path
-def komodo(exe=u'komodo'):
- """ Activestate Komodo [Edit] """
- install_editor(exe + u' -l {line} {filename}', wait=True)
-
-
-def scite(exe=u"scite"):
- """ SciTE or Sc1 """
- install_editor(exe + u' {filename} -goto:{line}')
-
-
-def notepadplusplus(exe=u'notepad++'):
- """ Notepad++ http://notepad-plus.sourceforge.net """
- install_editor(exe + u' -n{line} {filename}')
-
-
-def jed(exe=u'jed'):
- """ JED, the lightweight emacsish editor """
- install_editor(exe + u' +{line} {filename}')
-
-
-def idle(exe=u'idle'):
- """ Idle, the editor bundled with python
-
- Parameters
- ----------
- exe : str, None
- If none, should be pretty smart about finding the executable.
- """
- if exe is None:
- import idlelib
- p = os.path.dirname(idlelib.__filename__)
- # i'm not sure if this actually works. Is this idle.py script
- # guarenteed to be executable?
- exe = os.path.join(p, 'idle.py')
- install_editor(exe + u' {filename}')
-
-
-def mate(exe=u'mate'):
- """ TextMate, the missing editor"""
- # wait=True is not required since we're using the -w flag to mate
- install_editor(exe + u' -w -l {line} {filename}')
-
-
-# ##########################################
-# these are untested, report any problems
-# ##########################################
-
-
-def emacs(exe=u'emacs'):
- install_editor(exe + u' +{line} {filename}')
-
-
-def gnuclient(exe=u'gnuclient'):
- install_editor(exe + u' -nw +{line} {filename}')
-
-
-def crimson_editor(exe=u'cedt.exe'):
- install_editor(exe + u' /L:{line} {filename}')
-
-
-def kate(exe=u'kate'):
- install_editor(exe + u' -u -l {line} {filename}')
+ raise TryNext()
+ if wait:
+ py3compat.input("Press Enter when done editing:")
+
+ get_ipython().set_hook('editor', call_editor)
+ get_ipython().editor = template
+
+
+# in these, exe is always the path/name of the executable. Useful
+# if you don't have the editor directory in your path
+def komodo(exe=u'komodo'):
+ """ Activestate Komodo [Edit] """
+ install_editor(exe + u' -l {line} {filename}', wait=True)
+
+
+def scite(exe=u"scite"):
+ """ SciTE or Sc1 """
+ install_editor(exe + u' {filename} -goto:{line}')
+
+
+def notepadplusplus(exe=u'notepad++'):
+ """ Notepad++ http://notepad-plus.sourceforge.net """
+ install_editor(exe + u' -n{line} {filename}')
+
+
+def jed(exe=u'jed'):
+ """ JED, the lightweight emacsish editor """
+ install_editor(exe + u' +{line} {filename}')
+
+
+def idle(exe=u'idle'):
+ """ Idle, the editor bundled with python
+
+ Parameters
+ ----------
+ exe : str, None
+ If none, should be pretty smart about finding the executable.
+ """
+ if exe is None:
+ import idlelib
+ p = os.path.dirname(idlelib.__filename__)
+ # i'm not sure if this actually works. Is this idle.py script
+ # guarenteed to be executable?
+ exe = os.path.join(p, 'idle.py')
+ install_editor(exe + u' {filename}')
+
+
+def mate(exe=u'mate'):
+ """ TextMate, the missing editor"""
+ # wait=True is not required since we're using the -w flag to mate
+ install_editor(exe + u' -w -l {line} {filename}')
+
+
+# ##########################################
+# these are untested, report any problems
+# ##########################################
+
+
+def emacs(exe=u'emacs'):
+ install_editor(exe + u' +{line} {filename}')
+
+
+def gnuclient(exe=u'gnuclient'):
+ install_editor(exe + u' -nw +{line} {filename}')
+
+
+def crimson_editor(exe=u'cedt.exe'):
+ install_editor(exe + u' /L:{line} {filename}')
+
+
+def kate(exe=u'kate'):
+ install_editor(exe + u' -u -l {line} {filename}')
diff --git a/contrib/python/ipython/py2/IPython/lib/guisupport.py b/contrib/python/ipython/py2/IPython/lib/guisupport.py
index 57020b30b1..5e13d4343c 100644
--- a/contrib/python/ipython/py2/IPython/lib/guisupport.py
+++ b/contrib/python/ipython/py2/IPython/lib/guisupport.py
@@ -1,83 +1,83 @@
-# coding: utf-8
-"""
-Support for creating GUI apps and starting event loops.
-
-IPython's GUI integration allows interative plotting and GUI usage in IPython
-session. IPython has two different types of GUI integration:
-
-1. The terminal based IPython supports GUI event loops through Python's
- PyOS_InputHook. PyOS_InputHook is a hook that Python calls periodically
- whenever raw_input is waiting for a user to type code. We implement GUI
- support in the terminal by setting PyOS_InputHook to a function that
- iterates the event loop for a short while. It is important to note that
- in this situation, the real GUI event loop is NOT run in the normal
- manner, so you can't use the normal means to detect that it is running.
-2. In the two process IPython kernel/frontend, the GUI event loop is run in
- the kernel. In this case, the event loop is run in the normal manner by
- calling the function or method of the GUI toolkit that starts the event
- loop.
-
-In addition to starting the GUI event loops in one of these two ways, IPython
-will *always* create an appropriate GUI application object when GUi
-integration is enabled.
-
-If you want your GUI apps to run in IPython you need to do two things:
-
-1. Test to see if there is already an existing main application object. If
- there is, you should use it. If there is not an existing application object
- you should create one.
-2. Test to see if the GUI event loop is running. If it is, you should not
- start it. If the event loop is not running you may start it.
-
-This module contains functions for each toolkit that perform these things
-in a consistent manner. Because of how PyOS_InputHook runs the event loop
-you cannot detect if the event loop is running using the traditional calls
-(such as ``wx.GetApp.IsMainLoopRunning()`` in wxPython). If PyOS_InputHook is
-set These methods will return a false negative. That is, they will say the
-event loop is not running, when is actually is. To work around this limitation
-we proposed the following informal protocol:
-
-* Whenever someone starts the event loop, they *must* set the ``_in_event_loop``
- attribute of the main application object to ``True``. This should be done
- regardless of how the event loop is actually run.
-* Whenever someone stops the event loop, they *must* set the ``_in_event_loop``
- attribute of the main application object to ``False``.
-* If you want to see if the event loop is running, you *must* use ``hasattr``
- to see if ``_in_event_loop`` attribute has been set. If it is set, you
- *must* use its value. If it has not been set, you can query the toolkit
- in the normal manner.
-* If you want GUI support and no one else has created an application or
- started the event loop you *must* do this. We don't want projects to
- attempt to defer these things to someone else if they themselves need it.
-
-The functions below implement this logic for each GUI toolkit. If you need
-to create custom application subclasses, you will likely have to modify this
-code for your own purposes. This code can be copied into your own project
-so you don't have to depend on IPython.
-
-"""
-
+# coding: utf-8
+"""
+Support for creating GUI apps and starting event loops.
+
+IPython's GUI integration allows interative plotting and GUI usage in IPython
+session. IPython has two different types of GUI integration:
+
+1. The terminal based IPython supports GUI event loops through Python's
+ PyOS_InputHook. PyOS_InputHook is a hook that Python calls periodically
+ whenever raw_input is waiting for a user to type code. We implement GUI
+ support in the terminal by setting PyOS_InputHook to a function that
+ iterates the event loop for a short while. It is important to note that
+ in this situation, the real GUI event loop is NOT run in the normal
+ manner, so you can't use the normal means to detect that it is running.
+2. In the two process IPython kernel/frontend, the GUI event loop is run in
+ the kernel. In this case, the event loop is run in the normal manner by
+ calling the function or method of the GUI toolkit that starts the event
+ loop.
+
+In addition to starting the GUI event loops in one of these two ways, IPython
+will *always* create an appropriate GUI application object when GUi
+integration is enabled.
+
+If you want your GUI apps to run in IPython you need to do two things:
+
+1. Test to see if there is already an existing main application object. If
+ there is, you should use it. If there is not an existing application object
+ you should create one.
+2. Test to see if the GUI event loop is running. If it is, you should not
+ start it. If the event loop is not running you may start it.
+
+This module contains functions for each toolkit that perform these things
+in a consistent manner. Because of how PyOS_InputHook runs the event loop
+you cannot detect if the event loop is running using the traditional calls
+(such as ``wx.GetApp.IsMainLoopRunning()`` in wxPython). If PyOS_InputHook is
+set These methods will return a false negative. That is, they will say the
+event loop is not running, when is actually is. To work around this limitation
+we proposed the following informal protocol:
+
+* Whenever someone starts the event loop, they *must* set the ``_in_event_loop``
+ attribute of the main application object to ``True``. This should be done
+ regardless of how the event loop is actually run.
+* Whenever someone stops the event loop, they *must* set the ``_in_event_loop``
+ attribute of the main application object to ``False``.
+* If you want to see if the event loop is running, you *must* use ``hasattr``
+ to see if ``_in_event_loop`` attribute has been set. If it is set, you
+ *must* use its value. If it has not been set, you can query the toolkit
+ in the normal manner.
+* If you want GUI support and no one else has created an application or
+ started the event loop you *must* do this. We don't want projects to
+ attempt to defer these things to someone else if they themselves need it.
+
+The functions below implement this logic for each GUI toolkit. If you need
+to create custom application subclasses, you will likely have to modify this
+code for your own purposes. This code can be copied into your own project
+so you don't have to depend on IPython.
+
+"""
+
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
-
+
from IPython.core.getipython import get_ipython
-
-#-----------------------------------------------------------------------------
-# wx
-#-----------------------------------------------------------------------------
-
-def get_app_wx(*args, **kwargs):
- """Create a new wx app or return an exiting one."""
- import wx
- app = wx.GetApp()
- if app is None:
- if 'redirect' not in kwargs:
- kwargs['redirect'] = False
- app = wx.PySimpleApp(*args, **kwargs)
- return app
-
-def is_event_loop_running_wx(app=None):
- """Is the wx event loop running."""
+
+#-----------------------------------------------------------------------------
+# wx
+#-----------------------------------------------------------------------------
+
+def get_app_wx(*args, **kwargs):
+ """Create a new wx app or return an exiting one."""
+ import wx
+ app = wx.GetApp()
+ if app is None:
+ if 'redirect' not in kwargs:
+ kwargs['redirect'] = False
+ app = wx.PySimpleApp(*args, **kwargs)
+ return app
+
+def is_event_loop_running_wx(app=None):
+ """Is the wx event loop running."""
# New way: check attribute on shell instance
ip = get_ipython()
if ip is not None:
@@ -87,69 +87,69 @@ def is_event_loop_running_wx(app=None):
# to check if the event loop is running, unlike Qt.
# Old way: check Wx application
- if app is None:
- app = get_app_wx()
- if hasattr(app, '_in_event_loop'):
- return app._in_event_loop
- else:
- return app.IsMainLoopRunning()
-
-def start_event_loop_wx(app=None):
- """Start the wx event loop in a consistent manner."""
- if app is None:
- app = get_app_wx()
- if not is_event_loop_running_wx(app):
- app._in_event_loop = True
- app.MainLoop()
- app._in_event_loop = False
- else:
- app._in_event_loop = True
-
-#-----------------------------------------------------------------------------
-# qt4
-#-----------------------------------------------------------------------------
-
-def get_app_qt4(*args, **kwargs):
- """Create a new qt4 app or return an existing one."""
- from IPython.external.qt_for_kernel import QtGui
- app = QtGui.QApplication.instance()
- if app is None:
- if not args:
- args = ([''],)
- app = QtGui.QApplication(*args, **kwargs)
- return app
-
-def is_event_loop_running_qt4(app=None):
- """Is the qt4 event loop running."""
+ if app is None:
+ app = get_app_wx()
+ if hasattr(app, '_in_event_loop'):
+ return app._in_event_loop
+ else:
+ return app.IsMainLoopRunning()
+
+def start_event_loop_wx(app=None):
+ """Start the wx event loop in a consistent manner."""
+ if app is None:
+ app = get_app_wx()
+ if not is_event_loop_running_wx(app):
+ app._in_event_loop = True
+ app.MainLoop()
+ app._in_event_loop = False
+ else:
+ app._in_event_loop = True
+
+#-----------------------------------------------------------------------------
+# qt4
+#-----------------------------------------------------------------------------
+
+def get_app_qt4(*args, **kwargs):
+ """Create a new qt4 app or return an existing one."""
+ from IPython.external.qt_for_kernel import QtGui
+ app = QtGui.QApplication.instance()
+ if app is None:
+ if not args:
+ args = ([''],)
+ app = QtGui.QApplication(*args, **kwargs)
+ return app
+
+def is_event_loop_running_qt4(app=None):
+ """Is the qt4 event loop running."""
# New way: check attribute on shell instance
ip = get_ipython()
if ip is not None:
return ip.active_eventloop and ip.active_eventloop.startswith('qt')
# Old way: check attribute on QApplication singleton
- if app is None:
- app = get_app_qt4([''])
- if hasattr(app, '_in_event_loop'):
- return app._in_event_loop
- else:
- # Does qt4 provide a other way to detect this?
- return False
-
-def start_event_loop_qt4(app=None):
- """Start the qt4 event loop in a consistent manner."""
- if app is None:
- app = get_app_qt4([''])
- if not is_event_loop_running_qt4(app):
- app._in_event_loop = True
- app.exec_()
- app._in_event_loop = False
- else:
- app._in_event_loop = True
-
-#-----------------------------------------------------------------------------
-# Tk
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# gtk
-#-----------------------------------------------------------------------------
+ if app is None:
+ app = get_app_qt4([''])
+ if hasattr(app, '_in_event_loop'):
+ return app._in_event_loop
+ else:
+ # Does qt4 provide a other way to detect this?
+ return False
+
+def start_event_loop_qt4(app=None):
+ """Start the qt4 event loop in a consistent manner."""
+ if app is None:
+ app = get_app_qt4([''])
+ if not is_event_loop_running_qt4(app):
+ app._in_event_loop = True
+ app.exec_()
+ app._in_event_loop = False
+ else:
+ app._in_event_loop = True
+
+#-----------------------------------------------------------------------------
+# Tk
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# gtk
+#-----------------------------------------------------------------------------
diff --git a/contrib/python/ipython/py2/IPython/lib/inputhook.py b/contrib/python/ipython/py2/IPython/lib/inputhook.py
index 38ccda8831..e6e8f2dbbc 100644
--- a/contrib/python/ipython/py2/IPython/lib/inputhook.py
+++ b/contrib/python/ipython/py2/IPython/lib/inputhook.py
@@ -1,666 +1,666 @@
-# coding: utf-8
-"""
+# coding: utf-8
+"""
Deprecated since IPython 5.0
-Inputhook management for GUI event loop integration.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-try:
- import ctypes
-except ImportError:
- ctypes = None
-except SystemError: # IronPython issue, 2/8/2014
- ctypes = None
-import os
-import platform
-import sys
-from distutils.version import LooseVersion as V
-
+Inputhook management for GUI event loop integration.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+try:
+ import ctypes
+except ImportError:
+ ctypes = None
+except SystemError: # IronPython issue, 2/8/2014
+ ctypes = None
+import os
+import platform
+import sys
+from distutils.version import LooseVersion as V
+
from warnings import warn
-
+
warn("`IPython.lib.inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
-#-----------------------------------------------------------------------------
-# Constants
-#-----------------------------------------------------------------------------
-
-# Constants for identifying the GUI toolkits.
-GUI_WX = 'wx'
-GUI_QT = 'qt'
-GUI_QT4 = 'qt4'
-GUI_GTK = 'gtk'
-GUI_TK = 'tk'
-GUI_OSX = 'osx'
-GUI_GLUT = 'glut'
-GUI_PYGLET = 'pyglet'
-GUI_GTK3 = 'gtk3'
-GUI_NONE = 'none' # i.e. disable
-
-#-----------------------------------------------------------------------------
-# Utilities
-#-----------------------------------------------------------------------------
-
-def _stdin_ready_posix():
- """Return True if there's something to read on stdin (posix version)."""
- infds, outfds, erfds = select.select([sys.stdin],[],[],0)
- return bool(infds)
-
-def _stdin_ready_nt():
- """Return True if there's something to read on stdin (nt version)."""
- return msvcrt.kbhit()
-
-def _stdin_ready_other():
- """Return True, assuming there's something to read on stdin."""
- return True
-
-def _use_appnope():
- """Should we use appnope for dealing with OS X app nap?
-
- Checks if we are on OS X 10.9 or greater.
- """
- return sys.platform == 'darwin' and V(platform.mac_ver()[0]) >= V('10.9')
-
-def _ignore_CTRL_C_posix():
- """Ignore CTRL+C (SIGINT)."""
- signal.signal(signal.SIGINT, signal.SIG_IGN)
-
-def _allow_CTRL_C_posix():
- """Take CTRL+C into account (SIGINT)."""
- signal.signal(signal.SIGINT, signal.default_int_handler)
-
-def _ignore_CTRL_C_other():
- """Ignore CTRL+C (not implemented)."""
- pass
-
-def _allow_CTRL_C_other():
- """Take CTRL+C into account (not implemented)."""
- pass
-
-if os.name == 'posix':
- import select
- import signal
- stdin_ready = _stdin_ready_posix
- ignore_CTRL_C = _ignore_CTRL_C_posix
- allow_CTRL_C = _allow_CTRL_C_posix
-elif os.name == 'nt':
- import msvcrt
- stdin_ready = _stdin_ready_nt
- ignore_CTRL_C = _ignore_CTRL_C_other
- allow_CTRL_C = _allow_CTRL_C_other
-else:
- stdin_ready = _stdin_ready_other
- ignore_CTRL_C = _ignore_CTRL_C_other
- allow_CTRL_C = _allow_CTRL_C_other
-
-
-#-----------------------------------------------------------------------------
-# Main InputHookManager class
-#-----------------------------------------------------------------------------
-
-
-class InputHookManager(object):
+#-----------------------------------------------------------------------------
+# Constants
+#-----------------------------------------------------------------------------
+
+# Constants for identifying the GUI toolkits.
+GUI_WX = 'wx'
+GUI_QT = 'qt'
+GUI_QT4 = 'qt4'
+GUI_GTK = 'gtk'
+GUI_TK = 'tk'
+GUI_OSX = 'osx'
+GUI_GLUT = 'glut'
+GUI_PYGLET = 'pyglet'
+GUI_GTK3 = 'gtk3'
+GUI_NONE = 'none' # i.e. disable
+
+#-----------------------------------------------------------------------------
+# Utilities
+#-----------------------------------------------------------------------------
+
+def _stdin_ready_posix():
+ """Return True if there's something to read on stdin (posix version)."""
+ infds, outfds, erfds = select.select([sys.stdin],[],[],0)
+ return bool(infds)
+
+def _stdin_ready_nt():
+ """Return True if there's something to read on stdin (nt version)."""
+ return msvcrt.kbhit()
+
+def _stdin_ready_other():
+ """Return True, assuming there's something to read on stdin."""
+ return True
+
+def _use_appnope():
+ """Should we use appnope for dealing with OS X app nap?
+
+ Checks if we are on OS X 10.9 or greater.
+ """
+ return sys.platform == 'darwin' and V(platform.mac_ver()[0]) >= V('10.9')
+
+def _ignore_CTRL_C_posix():
+ """Ignore CTRL+C (SIGINT)."""
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
+
+def _allow_CTRL_C_posix():
+ """Take CTRL+C into account (SIGINT)."""
+ signal.signal(signal.SIGINT, signal.default_int_handler)
+
+def _ignore_CTRL_C_other():
+ """Ignore CTRL+C (not implemented)."""
+ pass
+
+def _allow_CTRL_C_other():
+ """Take CTRL+C into account (not implemented)."""
+ pass
+
+if os.name == 'posix':
+ import select
+ import signal
+ stdin_ready = _stdin_ready_posix
+ ignore_CTRL_C = _ignore_CTRL_C_posix
+ allow_CTRL_C = _allow_CTRL_C_posix
+elif os.name == 'nt':
+ import msvcrt
+ stdin_ready = _stdin_ready_nt
+ ignore_CTRL_C = _ignore_CTRL_C_other
+ allow_CTRL_C = _allow_CTRL_C_other
+else:
+ stdin_ready = _stdin_ready_other
+ ignore_CTRL_C = _ignore_CTRL_C_other
+ allow_CTRL_C = _allow_CTRL_C_other
+
+
+#-----------------------------------------------------------------------------
+# Main InputHookManager class
+#-----------------------------------------------------------------------------
+
+
+class InputHookManager(object):
"""DEPRECATED since IPython 5.0
-
+
Manage PyOS_InputHook for different GUI toolkits.
- This class installs various hooks under ``PyOSInputHook`` to handle
- GUI event loop integration.
- """
-
- def __init__(self):
- if ctypes is None:
- warn("IPython GUI event loop requires ctypes, %gui will not be available")
- else:
- self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
- self.guihooks = {}
- self.aliases = {}
- self.apps = {}
- self._reset()
-
- def _reset(self):
- self._callback_pyfunctype = None
- self._callback = None
- self._installed = False
- self._current_gui = None
-
- def get_pyos_inputhook(self):
+ This class installs various hooks under ``PyOSInputHook`` to handle
+ GUI event loop integration.
+ """
+
+ def __init__(self):
+ if ctypes is None:
+ warn("IPython GUI event loop requires ctypes, %gui will not be available")
+ else:
+ self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
+ self.guihooks = {}
+ self.aliases = {}
+ self.apps = {}
+ self._reset()
+
+ def _reset(self):
+ self._callback_pyfunctype = None
+ self._callback = None
+ self._installed = False
+ self._current_gui = None
+
+ def get_pyos_inputhook(self):
"""DEPRECATED since IPython 5.0
Return the current PyOS_InputHook as a ctypes.c_void_p."""
warn("`get_pyos_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
-
- def get_pyos_inputhook_as_func(self):
+ return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
+
+ def get_pyos_inputhook_as_func(self):
"""DEPRECATED since IPython 5.0
Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
warn("`get_pyos_inputhook_as_func` is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
-
- def set_inputhook(self, callback):
+ return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
+
+ def set_inputhook(self, callback):
"""DEPRECATED since IPython 5.0
Set PyOS_InputHook to callback and return the previous one."""
- # On platforms with 'readline' support, it's all too likely to
- # have a KeyboardInterrupt signal delivered *even before* an
- # initial ``try:`` clause in the callback can be executed, so
- # we need to disable CTRL+C in this situation.
- ignore_CTRL_C()
- self._callback = callback
- self._callback_pyfunctype = self.PYFUNC(callback)
- pyos_inputhook_ptr = self.get_pyos_inputhook()
- original = self.get_pyos_inputhook_as_func()
- pyos_inputhook_ptr.value = \
- ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
- self._installed = True
- return original
-
- def clear_inputhook(self, app=None):
+ # On platforms with 'readline' support, it's all too likely to
+ # have a KeyboardInterrupt signal delivered *even before* an
+ # initial ``try:`` clause in the callback can be executed, so
+ # we need to disable CTRL+C in this situation.
+ ignore_CTRL_C()
+ self._callback = callback
+ self._callback_pyfunctype = self.PYFUNC(callback)
+ pyos_inputhook_ptr = self.get_pyos_inputhook()
+ original = self.get_pyos_inputhook_as_func()
+ pyos_inputhook_ptr.value = \
+ ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
+ self._installed = True
+ return original
+
+ def clear_inputhook(self, app=None):
"""DEPRECATED since IPython 5.0
-
+
Set PyOS_InputHook to NULL and return the previous one.
- Parameters
- ----------
- app : optional, ignored
- This parameter is allowed only so that clear_inputhook() can be
- called with a similar interface as all the ``enable_*`` methods. But
- the actual value of the parameter is ignored. This uniform interface
- makes it easier to have user-level entry points in the main IPython
- app like :meth:`enable_gui`."""
+ Parameters
+ ----------
+ app : optional, ignored
+ This parameter is allowed only so that clear_inputhook() can be
+ called with a similar interface as all the ``enable_*`` methods. But
+ the actual value of the parameter is ignored. This uniform interface
+ makes it easier to have user-level entry points in the main IPython
+ app like :meth:`enable_gui`."""
warn("`clear_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- pyos_inputhook_ptr = self.get_pyos_inputhook()
- original = self.get_pyos_inputhook_as_func()
- pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
- allow_CTRL_C()
- self._reset()
- return original
-
- def clear_app_refs(self, gui=None):
+ pyos_inputhook_ptr = self.get_pyos_inputhook()
+ original = self.get_pyos_inputhook_as_func()
+ pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
+ allow_CTRL_C()
+ self._reset()
+ return original
+
+ def clear_app_refs(self, gui=None):
"""DEPRECATED since IPython 5.0
-
+
Clear IPython's internal reference to an application instance.
- Whenever we create an app for a user on qt4 or wx, we hold a
- reference to the app. This is needed because in some cases bad things
- can happen if a user doesn't hold a reference themselves. This
- method is provided to clear the references we are holding.
-
- Parameters
- ----------
- gui : None or str
- If None, clear all app references. If ('wx', 'qt4') clear
- the app for that toolkit. References are not held for gtk or tk
- as those toolkits don't have the notion of an app.
- """
+ Whenever we create an app for a user on qt4 or wx, we hold a
+ reference to the app. This is needed because in some cases bad things
+ can happen if a user doesn't hold a reference themselves. This
+ method is provided to clear the references we are holding.
+
+ Parameters
+ ----------
+ gui : None or str
+ If None, clear all app references. If ('wx', 'qt4') clear
+ the app for that toolkit. References are not held for gtk or tk
+ as those toolkits don't have the notion of an app.
+ """
warn("`clear_app_refs` is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- if gui is None:
- self.apps = {}
- elif gui in self.apps:
- del self.apps[gui]
-
- def register(self, toolkitname, *aliases):
+ if gui is None:
+ self.apps = {}
+ elif gui in self.apps:
+ del self.apps[gui]
+
+ def register(self, toolkitname, *aliases):
"""DEPRECATED since IPython 5.0
Register a class to provide the event loop for a given GUI.
-
- This is intended to be used as a class decorator. It should be passed
- the names with which to register this GUI integration. The classes
- themselves should subclass :class:`InputHookBase`.
-
- ::
-
- @inputhook_manager.register('qt')
- class QtInputHook(InputHookBase):
- def enable(self, app=None):
- ...
- """
+
+ This is intended to be used as a class decorator. It should be passed
+ the names with which to register this GUI integration. The classes
+ themselves should subclass :class:`InputHookBase`.
+
+ ::
+
+ @inputhook_manager.register('qt')
+ class QtInputHook(InputHookBase):
+ def enable(self, app=None):
+ ...
+ """
warn("`register` is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- def decorator(cls):
- if ctypes is not None:
- inst = cls(self)
- self.guihooks[toolkitname] = inst
- for a in aliases:
- self.aliases[a] = toolkitname
- return cls
- return decorator
-
- def current_gui(self):
+ def decorator(cls):
+ if ctypes is not None:
+ inst = cls(self)
+ self.guihooks[toolkitname] = inst
+ for a in aliases:
+ self.aliases[a] = toolkitname
+ return cls
+ return decorator
+
+ def current_gui(self):
"""DEPRECATED since IPython 5.0
Return a string indicating the currently active GUI or None."""
warn("`current_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- return self._current_gui
-
- def enable_gui(self, gui=None, app=None):
+ return self._current_gui
+
+ def enable_gui(self, gui=None, app=None):
"""DEPRECATED since IPython 5.0
-
+
Switch amongst GUI input hooks by name.
- This is a higher level method than :meth:`set_inputhook` - it uses the
- GUI name to look up a registered object which enables the input hook
- for that GUI.
-
- Parameters
- ----------
- gui : optional, string or None
- If None (or 'none'), clears input hook, otherwise it must be one
- of the recognized GUI names (see ``GUI_*`` constants in module).
-
- app : optional, existing application object.
- For toolkits that have the concept of a global app, you can supply an
- existing one. If not given, the toolkit will be probed for one, and if
- none is found, a new one will be created. Note that GTK does not have
- this concept, and passing an app if ``gui=="GTK"`` will raise an error.
-
- Returns
- -------
- The output of the underlying gui switch routine, typically the actual
- PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
- one.
- """
+ This is a higher level method than :meth:`set_inputhook` - it uses the
+ GUI name to look up a registered object which enables the input hook
+ for that GUI.
+
+ Parameters
+ ----------
+ gui : optional, string or None
+ If None (or 'none'), clears input hook, otherwise it must be one
+ of the recognized GUI names (see ``GUI_*`` constants in module).
+
+ app : optional, existing application object.
+ For toolkits that have the concept of a global app, you can supply an
+ existing one. If not given, the toolkit will be probed for one, and if
+ none is found, a new one will be created. Note that GTK does not have
+ this concept, and passing an app if ``gui=="GTK"`` will raise an error.
+
+ Returns
+ -------
+ The output of the underlying gui switch routine, typically the actual
+ PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
+ one.
+ """
warn("`enable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- if gui in (None, GUI_NONE):
- return self.disable_gui()
-
- if gui in self.aliases:
- return self.enable_gui(self.aliases[gui], app)
-
- try:
- gui_hook = self.guihooks[gui]
- except KeyError:
- e = "Invalid GUI request {!r}, valid ones are: {}"
- raise ValueError(e.format(gui, ', '.join(self.guihooks)))
- self._current_gui = gui
-
- app = gui_hook.enable(app)
- if app is not None:
- app._in_event_loop = True
+ if gui in (None, GUI_NONE):
+ return self.disable_gui()
+
+ if gui in self.aliases:
+ return self.enable_gui(self.aliases[gui], app)
+
+ try:
+ gui_hook = self.guihooks[gui]
+ except KeyError:
+ e = "Invalid GUI request {!r}, valid ones are: {}"
+ raise ValueError(e.format(gui, ', '.join(self.guihooks)))
+ self._current_gui = gui
+
+ app = gui_hook.enable(app)
+ if app is not None:
+ app._in_event_loop = True
self.apps[gui] = app
- return app
-
- def disable_gui(self):
+ return app
+
+ def disable_gui(self):
"""DEPRECATED since IPython 5.0
Disable GUI event loop integration.
-
- If an application was registered, this sets its ``_in_event_loop``
- attribute to False. It then calls :meth:`clear_inputhook`.
- """
+
+ If an application was registered, this sets its ``_in_event_loop``
+ attribute to False. It then calls :meth:`clear_inputhook`.
+ """
warn("`disable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- gui = self._current_gui
- if gui in self.apps:
- self.apps[gui]._in_event_loop = False
- return self.clear_inputhook()
-
-class InputHookBase(object):
+ gui = self._current_gui
+ if gui in self.apps:
+ self.apps[gui]._in_event_loop = False
+ return self.clear_inputhook()
+
+class InputHookBase(object):
"""DEPRECATED since IPython 5.0
Base class for input hooks for specific toolkits.
-
- Subclasses should define an :meth:`enable` method with one argument, ``app``,
- which will either be an instance of the toolkit's application class, or None.
- They may also define a :meth:`disable` method with no arguments.
- """
- def __init__(self, manager):
- self.manager = manager
-
- def disable(self):
- pass
-
-inputhook_manager = InputHookManager()
-
-@inputhook_manager.register('osx')
-class NullInputHook(InputHookBase):
+
+ Subclasses should define an :meth:`enable` method with one argument, ``app``,
+ which will either be an instance of the toolkit's application class, or None.
+ They may also define a :meth:`disable` method with no arguments.
+ """
+ def __init__(self, manager):
+ self.manager = manager
+
+ def disable(self):
+ pass
+
+inputhook_manager = InputHookManager()
+
+@inputhook_manager.register('osx')
+class NullInputHook(InputHookBase):
"""DEPRECATED since IPython 5.0
A null inputhook that doesn't need to do anything"""
- def enable(self, app=None):
+ def enable(self, app=None):
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
-
-@inputhook_manager.register('wx')
-class WxInputHook(InputHookBase):
- def enable(self, app=None):
+
+@inputhook_manager.register('wx')
+class WxInputHook(InputHookBase):
+ def enable(self, app=None):
"""DEPRECATED since IPython 5.0
-
+
Enable event loop integration with wxPython.
- Parameters
- ----------
- app : WX Application, optional.
- Running application to use. If not given, we probe WX for an
- existing application object, and create a new one if none is found.
-
- Notes
- -----
- This methods sets the ``PyOS_InputHook`` for wxPython, which allows
- the wxPython to integrate with terminal based applications like
- IPython.
-
- If ``app`` is not given we probe for an existing one, and return it if
- found. If no existing app is found, we create an :class:`wx.App` as
- follows::
-
- import wx
- app = wx.App(redirect=False, clearSigInt=False)
- """
+ Parameters
+ ----------
+ app : WX Application, optional.
+ Running application to use. If not given, we probe WX for an
+ existing application object, and create a new one if none is found.
+
+ Notes
+ -----
+ This methods sets the ``PyOS_InputHook`` for wxPython, which allows
+ the wxPython to integrate with terminal based applications like
+ IPython.
+
+ If ``app`` is not given we probe for an existing one, and return it if
+ found. If no existing app is found, we create an :class:`wx.App` as
+ follows::
+
+ import wx
+ app = wx.App(redirect=False, clearSigInt=False)
+ """
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- import wx
-
- wx_version = V(wx.__version__).version
-
- if wx_version < [2, 8]:
- raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
-
- from IPython.lib.inputhookwx import inputhook_wx
- self.manager.set_inputhook(inputhook_wx)
- if _use_appnope():
- from appnope import nope
- nope()
-
- import wx
- if app is None:
- app = wx.GetApp()
- if app is None:
- app = wx.App(redirect=False, clearSigInt=False)
-
- return app
-
- def disable(self):
+ import wx
+
+ wx_version = V(wx.__version__).version
+
+ if wx_version < [2, 8]:
+ raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
+
+ from IPython.lib.inputhookwx import inputhook_wx
+ self.manager.set_inputhook(inputhook_wx)
+ if _use_appnope():
+ from appnope import nope
+ nope()
+
+ import wx
+ if app is None:
+ app = wx.GetApp()
+ if app is None:
+ app = wx.App(redirect=False, clearSigInt=False)
+
+ return app
+
+ def disable(self):
"""DEPRECATED since IPython 5.0
-
+
Disable event loop integration with wxPython.
- This restores appnapp on OS X
- """
+ This restores appnapp on OS X
+ """
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- if _use_appnope():
- from appnope import nap
- nap()
-
-@inputhook_manager.register('qt', 'qt4')
-class Qt4InputHook(InputHookBase):
- def enable(self, app=None):
+ if _use_appnope():
+ from appnope import nap
+ nap()
+
+@inputhook_manager.register('qt', 'qt4')
+class Qt4InputHook(InputHookBase):
+ def enable(self, app=None):
"""DEPRECATED since IPython 5.0
Enable event loop integration with PyQt4.
-
- Parameters
- ----------
- app : Qt Application, optional.
- Running application to use. If not given, we probe Qt for an
- existing application object, and create a new one if none is found.
-
- Notes
- -----
- This methods sets the PyOS_InputHook for PyQt4, which allows
- the PyQt4 to integrate with terminal based applications like
- IPython.
-
- If ``app`` is not given we probe for an existing one, and return it if
- found. If no existing app is found, we create an :class:`QApplication`
- as follows::
-
- from PyQt4 import QtCore
- app = QtGui.QApplication(sys.argv)
- """
+
+ Parameters
+ ----------
+ app : Qt Application, optional.
+ Running application to use. If not given, we probe Qt for an
+ existing application object, and create a new one if none is found.
+
+ Notes
+ -----
+ This methods sets the PyOS_InputHook for PyQt4, which allows
+ the PyQt4 to integrate with terminal based applications like
+ IPython.
+
+ If ``app`` is not given we probe for an existing one, and return it if
+ found. If no existing app is found, we create an :class:`QApplication`
+ as follows::
+
+ from PyQt4 import QtCore
+ app = QtGui.QApplication(sys.argv)
+ """
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- from IPython.lib.inputhookqt4 import create_inputhook_qt4
- app, inputhook_qt4 = create_inputhook_qt4(self.manager, app)
- self.manager.set_inputhook(inputhook_qt4)
- if _use_appnope():
- from appnope import nope
- nope()
-
- return app
-
- def disable_qt4(self):
+ from IPython.lib.inputhookqt4 import create_inputhook_qt4
+ app, inputhook_qt4 = create_inputhook_qt4(self.manager, app)
+ self.manager.set_inputhook(inputhook_qt4)
+ if _use_appnope():
+ from appnope import nope
+ nope()
+
+ return app
+
+ def disable_qt4(self):
"""DEPRECATED since IPython 5.0
-
+
Disable event loop integration with PyQt4.
- This restores appnapp on OS X
- """
+ This restores appnapp on OS X
+ """
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- if _use_appnope():
- from appnope import nap
- nap()
-
-
-@inputhook_manager.register('qt5')
-class Qt5InputHook(Qt4InputHook):
- def enable(self, app=None):
+ if _use_appnope():
+ from appnope import nap
+ nap()
+
+
+@inputhook_manager.register('qt5')
+class Qt5InputHook(Qt4InputHook):
+ def enable(self, app=None):
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- os.environ['QT_API'] = 'pyqt5'
- return Qt4InputHook.enable(self, app)
-
-
-@inputhook_manager.register('gtk')
-class GtkInputHook(InputHookBase):
- def enable(self, app=None):
+ os.environ['QT_API'] = 'pyqt5'
+ return Qt4InputHook.enable(self, app)
+
+
+@inputhook_manager.register('gtk')
+class GtkInputHook(InputHookBase):
+ def enable(self, app=None):
"""DEPRECATED since IPython 5.0
-
+
Enable event loop integration with PyGTK.
- Parameters
- ----------
- app : ignored
- Ignored, it's only a placeholder to keep the call signature of all
- gui activation methods consistent, which simplifies the logic of
- supporting magics.
-
- Notes
- -----
- This methods sets the PyOS_InputHook for PyGTK, which allows
- the PyGTK to integrate with terminal based applications like
- IPython.
- """
+ Parameters
+ ----------
+ app : ignored
+ Ignored, it's only a placeholder to keep the call signature of all
+ gui activation methods consistent, which simplifies the logic of
+ supporting magics.
+
+ Notes
+ -----
+ This methods sets the PyOS_InputHook for PyGTK, which allows
+ the PyGTK to integrate with terminal based applications like
+ IPython.
+ """
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- import gtk
- try:
- gtk.set_interactive(True)
- except AttributeError:
- # For older versions of gtk, use our own ctypes version
- from IPython.lib.inputhookgtk import inputhook_gtk
- self.manager.set_inputhook(inputhook_gtk)
-
-
-@inputhook_manager.register('tk')
-class TkInputHook(InputHookBase):
- def enable(self, app=None):
+ import gtk
+ try:
+ gtk.set_interactive(True)
+ except AttributeError:
+ # For older versions of gtk, use our own ctypes version
+ from IPython.lib.inputhookgtk import inputhook_gtk
+ self.manager.set_inputhook(inputhook_gtk)
+
+
+@inputhook_manager.register('tk')
+class TkInputHook(InputHookBase):
+ def enable(self, app=None):
"""DEPRECATED since IPython 5.0
-
+
Enable event loop integration with Tk.
- Parameters
- ----------
- app : toplevel :class:`Tkinter.Tk` widget, optional.
- Running toplevel widget to use. If not given, we probe Tk for an
- existing one, and create a new one if none is found.
-
- Notes
- -----
- If you have already created a :class:`Tkinter.Tk` object, the only
- thing done by this method is to register with the
- :class:`InputHookManager`, since creating that object automatically
- sets ``PyOS_InputHook``.
- """
+ Parameters
+ ----------
+ app : toplevel :class:`Tkinter.Tk` widget, optional.
+ Running toplevel widget to use. If not given, we probe Tk for an
+ existing one, and create a new one if none is found.
+
+ Notes
+ -----
+ If you have already created a :class:`Tkinter.Tk` object, the only
+ thing done by this method is to register with the
+ :class:`InputHookManager`, since creating that object automatically
+ sets ``PyOS_InputHook``.
+ """
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- if app is None:
- try:
- from tkinter import Tk # Py 3
- except ImportError:
- from Tkinter import Tk # Py 2
- app = Tk()
- app.withdraw()
- self.manager.apps[GUI_TK] = app
- return app
-
-
-@inputhook_manager.register('glut')
-class GlutInputHook(InputHookBase):
- def enable(self, app=None):
+ if app is None:
+ try:
+ from tkinter import Tk # Py 3
+ except ImportError:
+ from Tkinter import Tk # Py 2
+ app = Tk()
+ app.withdraw()
+ self.manager.apps[GUI_TK] = app
+ return app
+
+
+@inputhook_manager.register('glut')
+class GlutInputHook(InputHookBase):
+ def enable(self, app=None):
"""DEPRECATED since IPython 5.0
-
+
Enable event loop integration with GLUT.
- Parameters
- ----------
-
- app : ignored
- Ignored, it's only a placeholder to keep the call signature of all
- gui activation methods consistent, which simplifies the logic of
- supporting magics.
-
- Notes
- -----
-
- This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
- integrate with terminal based applications like IPython. Due to GLUT
- limitations, it is currently not possible to start the event loop
- without first creating a window. You should thus not create another
- window but use instead the created one. See 'gui-glut.py' in the
- docs/examples/lib directory.
-
- The default screen mode is set to:
- glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
- """
+ Parameters
+ ----------
+
+ app : ignored
+ Ignored, it's only a placeholder to keep the call signature of all
+ gui activation methods consistent, which simplifies the logic of
+ supporting magics.
+
+ Notes
+ -----
+
+ This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
+ integrate with terminal based applications like IPython. Due to GLUT
+ limitations, it is currently not possible to start the event loop
+ without first creating a window. You should thus not create another
+ window but use instead the created one. See 'gui-glut.py' in the
+ docs/examples/lib directory.
+
+ The default screen mode is set to:
+ glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
+ """
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
-
- import OpenGL.GLUT as glut
- from IPython.lib.inputhookglut import glut_display_mode, \
- glut_close, glut_display, \
- glut_idle, inputhook_glut
-
- if GUI_GLUT not in self.manager.apps:
- glut.glutInit( sys.argv )
- glut.glutInitDisplayMode( glut_display_mode )
- # This is specific to freeglut
- if bool(glut.glutSetOption):
- glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
- glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
- glut.glutCreateWindow( sys.argv[0] )
- glut.glutReshapeWindow( 1, 1 )
- glut.glutHideWindow( )
- glut.glutWMCloseFunc( glut_close )
- glut.glutDisplayFunc( glut_display )
- glut.glutIdleFunc( glut_idle )
- else:
- glut.glutWMCloseFunc( glut_close )
- glut.glutDisplayFunc( glut_display )
- glut.glutIdleFunc( glut_idle)
- self.manager.set_inputhook( inputhook_glut )
-
-
- def disable(self):
+
+ import OpenGL.GLUT as glut
+ from IPython.lib.inputhookglut import glut_display_mode, \
+ glut_close, glut_display, \
+ glut_idle, inputhook_glut
+
+ if GUI_GLUT not in self.manager.apps:
+ glut.glutInit( sys.argv )
+ glut.glutInitDisplayMode( glut_display_mode )
+ # This is specific to freeglut
+ if bool(glut.glutSetOption):
+ glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
+ glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
+ glut.glutCreateWindow( sys.argv[0] )
+ glut.glutReshapeWindow( 1, 1 )
+ glut.glutHideWindow( )
+ glut.glutWMCloseFunc( glut_close )
+ glut.glutDisplayFunc( glut_display )
+ glut.glutIdleFunc( glut_idle )
+ else:
+ glut.glutWMCloseFunc( glut_close )
+ glut.glutDisplayFunc( glut_display )
+ glut.glutIdleFunc( glut_idle)
+ self.manager.set_inputhook( inputhook_glut )
+
+
+ def disable(self):
"""DEPRECATED since IPython 5.0
Disable event loop integration with glut.
-
- This sets PyOS_InputHook to NULL and set the display function to a
- dummy one and set the timer to a dummy timer that will be triggered
- very far in the future.
- """
+
+ This sets PyOS_InputHook to NULL and set the display function to a
+ dummy one and set the timer to a dummy timer that will be triggered
+ very far in the future.
+ """
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- import OpenGL.GLUT as glut
- from glut_support import glutMainLoopEvent
-
- glut.glutHideWindow() # This is an event to be processed below
- glutMainLoopEvent()
- super(GlutInputHook, self).disable()
-
-@inputhook_manager.register('pyglet')
-class PygletInputHook(InputHookBase):
- def enable(self, app=None):
+ import OpenGL.GLUT as glut
+ from glut_support import glutMainLoopEvent
+
+ glut.glutHideWindow() # This is an event to be processed below
+ glutMainLoopEvent()
+ super(GlutInputHook, self).disable()
+
+@inputhook_manager.register('pyglet')
+class PygletInputHook(InputHookBase):
+ def enable(self, app=None):
"""DEPRECATED since IPython 5.0
-
+
Enable event loop integration with pyglet.
- Parameters
- ----------
- app : ignored
- Ignored, it's only a placeholder to keep the call signature of all
- gui activation methods consistent, which simplifies the logic of
- supporting magics.
-
- Notes
- -----
- This methods sets the ``PyOS_InputHook`` for pyglet, which allows
- pyglet to integrate with terminal based applications like
- IPython.
-
- """
+ Parameters
+ ----------
+ app : ignored
+ Ignored, it's only a placeholder to keep the call signature of all
+ gui activation methods consistent, which simplifies the logic of
+ supporting magics.
+
+ Notes
+ -----
+ This methods sets the ``PyOS_InputHook`` for pyglet, which allows
+ pyglet to integrate with terminal based applications like
+ IPython.
+
+ """
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- from IPython.lib.inputhookpyglet import inputhook_pyglet
- self.manager.set_inputhook(inputhook_pyglet)
- return app
-
-
-@inputhook_manager.register('gtk3')
-class Gtk3InputHook(InputHookBase):
- def enable(self, app=None):
+ from IPython.lib.inputhookpyglet import inputhook_pyglet
+ self.manager.set_inputhook(inputhook_pyglet)
+ return app
+
+
+@inputhook_manager.register('gtk3')
+class Gtk3InputHook(InputHookBase):
+ def enable(self, app=None):
"""DEPRECATED since IPython 5.0
-
+
Enable event loop integration with Gtk3 (gir bindings).
- Parameters
- ----------
- app : ignored
- Ignored, it's only a placeholder to keep the call signature of all
- gui activation methods consistent, which simplifies the logic of
- supporting magics.
-
- Notes
- -----
- This methods sets the PyOS_InputHook for Gtk3, which allows
- the Gtk3 to integrate with terminal based applications like
- IPython.
- """
+ Parameters
+ ----------
+ app : ignored
+ Ignored, it's only a placeholder to keep the call signature of all
+ gui activation methods consistent, which simplifies the logic of
+ supporting magics.
+
+ Notes
+ -----
+ This methods sets the PyOS_InputHook for Gtk3, which allows
+ the Gtk3 to integrate with terminal based applications like
+ IPython.
+ """
warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
DeprecationWarning, stacklevel=2)
- from IPython.lib.inputhookgtk3 import inputhook_gtk3
- self.manager.set_inputhook(inputhook_gtk3)
-
-
-clear_inputhook = inputhook_manager.clear_inputhook
-set_inputhook = inputhook_manager.set_inputhook
-current_gui = inputhook_manager.current_gui
-clear_app_refs = inputhook_manager.clear_app_refs
-enable_gui = inputhook_manager.enable_gui
-disable_gui = inputhook_manager.disable_gui
-register = inputhook_manager.register
-guis = inputhook_manager.guihooks
-
-
-def _deprecated_disable():
+ from IPython.lib.inputhookgtk3 import inputhook_gtk3
+ self.manager.set_inputhook(inputhook_gtk3)
+
+
+clear_inputhook = inputhook_manager.clear_inputhook
+set_inputhook = inputhook_manager.set_inputhook
+current_gui = inputhook_manager.current_gui
+clear_app_refs = inputhook_manager.clear_app_refs
+enable_gui = inputhook_manager.enable_gui
+disable_gui = inputhook_manager.disable_gui
+register = inputhook_manager.register
+guis = inputhook_manager.guihooks
+
+
+def _deprecated_disable():
warn("This function is deprecated since IPython 4.0 use disable_gui() instead",
DeprecationWarning, stacklevel=2)
- inputhook_manager.disable_gui()
+ inputhook_manager.disable_gui()
-disable_wx = disable_qt4 = disable_gtk = disable_gtk3 = disable_glut = \
- disable_pyglet = disable_osx = _deprecated_disable
+disable_wx = disable_qt4 = disable_gtk = disable_gtk3 = disable_glut = \
+ disable_pyglet = disable_osx = _deprecated_disable
diff --git a/contrib/python/ipython/py2/IPython/lib/inputhookglut.py b/contrib/python/ipython/py2/IPython/lib/inputhookglut.py
index 5dd908f814..14bafe1632 100644
--- a/contrib/python/ipython/py2/IPython/lib/inputhookglut.py
+++ b/contrib/python/ipython/py2/IPython/lib/inputhookglut.py
@@ -1,173 +1,173 @@
-# coding: utf-8
-"""
-GLUT Inputhook support functions
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-# GLUT is quite an old library and it is difficult to ensure proper
-# integration within IPython since original GLUT does not allow to handle
-# events one by one. Instead, it requires for the mainloop to be entered
-# and never returned (there is not even a function to exit he
-# mainloop). Fortunately, there are alternatives such as freeglut
-# (available for linux and windows) and the OSX implementation gives
-# access to a glutCheckLoop() function that blocks itself until a new
-# event is received. This means we have to setup the idle callback to
-# ensure we got at least one event that will unblock the function.
-#
-# Furthermore, it is not possible to install these handlers without a window
-# being first created. We choose to make this window invisible. This means that
-# display mode options are set at this level and user won't be able to change
-# them later without modifying the code. This should probably be made available
-# via IPython options system.
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-import os
-import sys
-import time
-import signal
-import OpenGL.GLUT as glut
-import OpenGL.platform as platform
-from timeit import default_timer as clock
-
-#-----------------------------------------------------------------------------
-# Constants
-#-----------------------------------------------------------------------------
-
-# Frame per second : 60
-# Should probably be an IPython option
-glut_fps = 60
-
-
-# Display mode : double buffeed + rgba + depth
-# Should probably be an IPython option
-glut_display_mode = (glut.GLUT_DOUBLE |
- glut.GLUT_RGBA |
- glut.GLUT_DEPTH)
-
-glutMainLoopEvent = None
-if sys.platform == 'darwin':
- try:
- glutCheckLoop = platform.createBaseFunction(
- 'glutCheckLoop', dll=platform.GLUT, resultType=None,
- argTypes=[],
- doc='glutCheckLoop( ) -> None',
- argNames=(),
- )
- except AttributeError:
- raise RuntimeError(
- '''Your glut implementation does not allow interactive sessions'''
- '''Consider installing freeglut.''')
- glutMainLoopEvent = glutCheckLoop
-elif glut.HAVE_FREEGLUT:
- glutMainLoopEvent = glut.glutMainLoopEvent
-else:
- raise RuntimeError(
- '''Your glut implementation does not allow interactive sessions. '''
- '''Consider installing freeglut.''')
-
-
-#-----------------------------------------------------------------------------
-# Platform-dependent imports and functions
-#-----------------------------------------------------------------------------
-
-if os.name == 'posix':
- import select
-
- def stdin_ready():
- infds, outfds, erfds = select.select([sys.stdin],[],[],0)
- if infds:
- return True
- else:
- return False
-
-elif sys.platform == 'win32':
- import msvcrt
-
- def stdin_ready():
- return msvcrt.kbhit()
-
-#-----------------------------------------------------------------------------
-# Callback functions
-#-----------------------------------------------------------------------------
-
-def glut_display():
- # Dummy display function
- pass
-
-def glut_idle():
- # Dummy idle function
- pass
-
-def glut_close():
- # Close function only hides the current window
- glut.glutHideWindow()
- glutMainLoopEvent()
-
-def glut_int_handler(signum, frame):
- # Catch sigint and print the defautl message
- signal.signal(signal.SIGINT, signal.default_int_handler)
- print('\nKeyboardInterrupt')
- # Need to reprint the prompt at this stage
-
-
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-def inputhook_glut():
- """Run the pyglet event loop by processing pending events only.
-
- This keeps processing pending events until stdin is ready. After
- processing all pending events, a call to time.sleep is inserted. This is
- needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
- though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
-
- signal.signal(signal.SIGINT, glut_int_handler)
-
- try:
- t = clock()
-
- # Make sure the default window is set after a window has been closed
- if glut.glutGetWindow() == 0:
- glut.glutSetWindow( 1 )
- glutMainLoopEvent()
- return 0
-
- while not stdin_ready():
- glutMainLoopEvent()
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- except KeyboardInterrupt:
- pass
- return 0
+# coding: utf-8
+"""
+GLUT Inputhook support functions
+"""
+from __future__ import print_function
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+# GLUT is quite an old library and it is difficult to ensure proper
+# integration within IPython since original GLUT does not allow to handle
+# events one by one. Instead, it requires for the mainloop to be entered
+# and never returned (there is not even a function to exit he
+# mainloop). Fortunately, there are alternatives such as freeglut
+# (available for linux and windows) and the OSX implementation gives
+# access to a glutCheckLoop() function that blocks itself until a new
+# event is received. This means we have to setup the idle callback to
+# ensure we got at least one event that will unblock the function.
+#
+# Furthermore, it is not possible to install these handlers without a window
+# being first created. We choose to make this window invisible. This means that
+# display mode options are set at this level and user won't be able to change
+# them later without modifying the code. This should probably be made available
+# via IPython options system.
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+import os
+import sys
+import time
+import signal
+import OpenGL.GLUT as glut
+import OpenGL.platform as platform
+from timeit import default_timer as clock
+
+#-----------------------------------------------------------------------------
+# Constants
+#-----------------------------------------------------------------------------
+
+# Frame per second : 60
+# Should probably be an IPython option
+glut_fps = 60
+
+
+# Display mode : double buffeed + rgba + depth
+# Should probably be an IPython option
+glut_display_mode = (glut.GLUT_DOUBLE |
+ glut.GLUT_RGBA |
+ glut.GLUT_DEPTH)
+
+glutMainLoopEvent = None
+if sys.platform == 'darwin':
+ try:
+ glutCheckLoop = platform.createBaseFunction(
+ 'glutCheckLoop', dll=platform.GLUT, resultType=None,
+ argTypes=[],
+ doc='glutCheckLoop( ) -> None',
+ argNames=(),
+ )
+ except AttributeError:
+ raise RuntimeError(
+ '''Your glut implementation does not allow interactive sessions'''
+ '''Consider installing freeglut.''')
+ glutMainLoopEvent = glutCheckLoop
+elif glut.HAVE_FREEGLUT:
+ glutMainLoopEvent = glut.glutMainLoopEvent
+else:
+ raise RuntimeError(
+ '''Your glut implementation does not allow interactive sessions. '''
+ '''Consider installing freeglut.''')
+
+
+#-----------------------------------------------------------------------------
+# Platform-dependent imports and functions
+#-----------------------------------------------------------------------------
+
+if os.name == 'posix':
+ import select
+
+ def stdin_ready():
+ infds, outfds, erfds = select.select([sys.stdin],[],[],0)
+ if infds:
+ return True
+ else:
+ return False
+
+elif sys.platform == 'win32':
+ import msvcrt
+
+ def stdin_ready():
+ return msvcrt.kbhit()
+
+#-----------------------------------------------------------------------------
+# Callback functions
+#-----------------------------------------------------------------------------
+
+def glut_display():
+ # Dummy display function
+ pass
+
+def glut_idle():
+ # Dummy idle function
+ pass
+
+def glut_close():
+ # Close function only hides the current window
+ glut.glutHideWindow()
+ glutMainLoopEvent()
+
+def glut_int_handler(signum, frame):
+ # Catch sigint and print the defautl message
+ signal.signal(signal.SIGINT, signal.default_int_handler)
+ print('\nKeyboardInterrupt')
+ # Need to reprint the prompt at this stage
+
+
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+def inputhook_glut():
+ """Run the pyglet event loop by processing pending events only.
+
+ This keeps processing pending events until stdin is ready. After
+ processing all pending events, a call to time.sleep is inserted. This is
+ needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
+ though for best performance.
+ """
+ # We need to protect against a user pressing Control-C when IPython is
+ # idle and this is running. We trap KeyboardInterrupt and pass.
+
+ signal.signal(signal.SIGINT, glut_int_handler)
+
+ try:
+ t = clock()
+
+ # Make sure the default window is set after a window has been closed
+ if glut.glutGetWindow() == 0:
+ glut.glutSetWindow( 1 )
+ glutMainLoopEvent()
+ return 0
+
+ while not stdin_ready():
+ glutMainLoopEvent()
+ # We need to sleep at this point to keep the idle CPU load
+ # low. However, if sleep to long, GUI response is poor. As
+ # a compromise, we watch how often GUI events are being processed
+ # and switch between a short and long sleep time. Here are some
+ # stats useful in helping to tune this.
+ # time CPU load
+ # 0.001 13%
+ # 0.005 3%
+ # 0.01 1.5%
+ # 0.05 0.5%
+ used_time = clock() - t
+ if used_time > 10.0:
+ # print 'Sleep for 1 s' # dbg
+ time.sleep(1.0)
+ elif used_time > 0.1:
+ # Few GUI events coming in, so we can sleep longer
+ # print 'Sleep for 0.05 s' # dbg
+ time.sleep(0.05)
+ else:
+ # Many GUI events coming in, so sleep only very little
+ time.sleep(0.001)
+ except KeyboardInterrupt:
+ pass
+ return 0
diff --git a/contrib/python/ipython/py2/IPython/lib/inputhookgtk.py b/contrib/python/ipython/py2/IPython/lib/inputhookgtk.py
index 52dfac5f52..2b4b656f91 100644
--- a/contrib/python/ipython/py2/IPython/lib/inputhookgtk.py
+++ b/contrib/python/ipython/py2/IPython/lib/inputhookgtk.py
@@ -1,35 +1,35 @@
-# encoding: utf-8
-"""
-Enable pygtk to be used interacive by setting PyOS_InputHook.
-
-Authors: Brian Granger
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import sys
-import gtk, gobject
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-
-def _main_quit(*args, **kwargs):
- gtk.main_quit()
- return False
-
-def inputhook_gtk():
- gobject.io_add_watch(sys.stdin, gobject.IO_IN, _main_quit)
- gtk.main()
- return 0
-
+# encoding: utf-8
+"""
+Enable pygtk to be used interacive by setting PyOS_InputHook.
+
+Authors: Brian Granger
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import sys
+import gtk, gobject
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+
+def _main_quit(*args, **kwargs):
+ gtk.main_quit()
+ return False
+
+def inputhook_gtk():
+ gobject.io_add_watch(sys.stdin, gobject.IO_IN, _main_quit)
+ gtk.main()
+ return 0
+
diff --git a/contrib/python/ipython/py2/IPython/lib/inputhookgtk3.py b/contrib/python/ipython/py2/IPython/lib/inputhookgtk3.py
index 6998805145..531f5cae14 100644
--- a/contrib/python/ipython/py2/IPython/lib/inputhookgtk3.py
+++ b/contrib/python/ipython/py2/IPython/lib/inputhookgtk3.py
@@ -1,34 +1,34 @@
-# encoding: utf-8
-"""
-Enable Gtk3 to be used interacive by IPython.
-
-Authors: Thomi Richards
-"""
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import sys
-from gi.repository import Gtk, GLib
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-def _main_quit(*args, **kwargs):
- Gtk.main_quit()
- return False
-
-
-def inputhook_gtk3():
- GLib.io_add_watch(sys.stdin, GLib.IO_IN, _main_quit)
- Gtk.main()
- return 0
+# encoding: utf-8
+"""
+Enable Gtk3 to be used interacive by IPython.
+
+Authors: Thomi Richards
+"""
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012, the IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import sys
+from gi.repository import Gtk, GLib
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+def _main_quit(*args, **kwargs):
+ Gtk.main_quit()
+ return False
+
+
+def inputhook_gtk3():
+ GLib.io_add_watch(sys.stdin, GLib.IO_IN, _main_quit)
+ Gtk.main()
+ return 0
diff --git a/contrib/python/ipython/py2/IPython/lib/inputhookpyglet.py b/contrib/python/ipython/py2/IPython/lib/inputhookpyglet.py
index 3cd209946e..b82fcf5ea7 100644
--- a/contrib/python/ipython/py2/IPython/lib/inputhookpyglet.py
+++ b/contrib/python/ipython/py2/IPython/lib/inputhookpyglet.py
@@ -1,111 +1,111 @@
-# encoding: utf-8
-"""
-Enable pyglet to be used interacive by setting PyOS_InputHook.
-
-Authors
--------
-
-* Nicolas P. Rougier
-* Fernando Perez
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import os
-import sys
-import time
-from timeit import default_timer as clock
-import pyglet
-
-#-----------------------------------------------------------------------------
-# Platform-dependent imports and functions
-#-----------------------------------------------------------------------------
-
-if os.name == 'posix':
- import select
-
- def stdin_ready():
- infds, outfds, erfds = select.select([sys.stdin],[],[],0)
- if infds:
- return True
- else:
- return False
-
-elif sys.platform == 'win32':
- import msvcrt
-
- def stdin_ready():
- return msvcrt.kbhit()
-
-
-# On linux only, window.flip() has a bug that causes an AttributeError on
-# window close. For details, see:
-# http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e
-
-if sys.platform.startswith('linux'):
- def flip(window):
- try:
- window.flip()
- except AttributeError:
- pass
-else:
- def flip(window):
- window.flip()
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-def inputhook_pyglet():
- """Run the pyglet event loop by processing pending events only.
-
- This keeps processing pending events until stdin is ready. After
- processing all pending events, a call to time.sleep is inserted. This is
- needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
- though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
- try:
- t = clock()
- while not stdin_ready():
- pyglet.clock.tick()
- for window in pyglet.app.windows:
- window.switch_to()
- window.dispatch_events()
- window.dispatch_event('on_draw')
- flip(window)
-
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- except KeyboardInterrupt:
- pass
- return 0
+# encoding: utf-8
+"""
+Enable pyglet to be used interacive by setting PyOS_InputHook.
+
+Authors
+-------
+
+* Nicolas P. Rougier
+* Fernando Perez
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import os
+import sys
+import time
+from timeit import default_timer as clock
+import pyglet
+
+#-----------------------------------------------------------------------------
+# Platform-dependent imports and functions
+#-----------------------------------------------------------------------------
+
+if os.name == 'posix':
+ import select
+
+ def stdin_ready():
+ infds, outfds, erfds = select.select([sys.stdin],[],[],0)
+ if infds:
+ return True
+ else:
+ return False
+
+elif sys.platform == 'win32':
+ import msvcrt
+
+ def stdin_ready():
+ return msvcrt.kbhit()
+
+
+# On linux only, window.flip() has a bug that causes an AttributeError on
+# window close. For details, see:
+# http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e
+
+if sys.platform.startswith('linux'):
+ def flip(window):
+ try:
+ window.flip()
+ except AttributeError:
+ pass
+else:
+ def flip(window):
+ window.flip()
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+def inputhook_pyglet():
+ """Run the pyglet event loop by processing pending events only.
+
+ This keeps processing pending events until stdin is ready. After
+ processing all pending events, a call to time.sleep is inserted. This is
+ needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
+ though for best performance.
+ """
+ # We need to protect against a user pressing Control-C when IPython is
+ # idle and this is running. We trap KeyboardInterrupt and pass.
+ try:
+ t = clock()
+ while not stdin_ready():
+ pyglet.clock.tick()
+ for window in pyglet.app.windows:
+ window.switch_to()
+ window.dispatch_events()
+ window.dispatch_event('on_draw')
+ flip(window)
+
+ # We need to sleep at this point to keep the idle CPU load
+ # low. However, if sleep to long, GUI response is poor. As
+ # a compromise, we watch how often GUI events are being processed
+ # and switch between a short and long sleep time. Here are some
+ # stats useful in helping to tune this.
+ # time CPU load
+ # 0.001 13%
+ # 0.005 3%
+ # 0.01 1.5%
+ # 0.05 0.5%
+ used_time = clock() - t
+ if used_time > 10.0:
+ # print 'Sleep for 1 s' # dbg
+ time.sleep(1.0)
+ elif used_time > 0.1:
+ # Few GUI events coming in, so we can sleep longer
+ # print 'Sleep for 0.05 s' # dbg
+ time.sleep(0.05)
+ else:
+ # Many GUI events coming in, so sleep only very little
+ time.sleep(0.001)
+ except KeyboardInterrupt:
+ pass
+ return 0
diff --git a/contrib/python/ipython/py2/IPython/lib/inputhookqt4.py b/contrib/python/ipython/py2/IPython/lib/inputhookqt4.py
index a0d0f9e348..8a83902fc0 100644
--- a/contrib/python/ipython/py2/IPython/lib/inputhookqt4.py
+++ b/contrib/python/ipython/py2/IPython/lib/inputhookqt4.py
@@ -1,180 +1,180 @@
-# -*- coding: utf-8 -*-
-"""
-Qt4's inputhook support function
-
-Author: Christian Boos
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import os
-import signal
-import threading
-
-from IPython.core.interactiveshell import InteractiveShell
-from IPython.external.qt_for_kernel import QtCore, QtGui
-from IPython.lib.inputhook import allow_CTRL_C, ignore_CTRL_C, stdin_ready
-
-#-----------------------------------------------------------------------------
-# Module Globals
-#-----------------------------------------------------------------------------
-
-got_kbdint = False
-sigint_timer = None
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-def create_inputhook_qt4(mgr, app=None):
- """Create an input hook for running the Qt4 application event loop.
-
- Parameters
- ----------
- mgr : an InputHookManager
-
- app : Qt Application, optional.
- Running application to use. If not given, we probe Qt for an
- existing application object, and create a new one if none is found.
-
- Returns
- -------
- A pair consisting of a Qt Application (either the one given or the
- one found or created) and a inputhook.
-
- Notes
- -----
- We use a custom input hook instead of PyQt4's default one, as it
- interacts better with the readline packages (issue #481).
-
- The inputhook function works in tandem with a 'pre_prompt_hook'
- which automatically restores the hook as an inputhook in case the
- latter has been temporarily disabled after having intercepted a
- KeyboardInterrupt.
- """
-
- if app is None:
- app = QtCore.QCoreApplication.instance()
- if app is None:
- app = QtGui.QApplication([" "])
-
- # Re-use previously created inputhook if any
- ip = InteractiveShell.instance()
- if hasattr(ip, '_inputhook_qt4'):
- return app, ip._inputhook_qt4
-
- # Otherwise create the inputhook_qt4/preprompthook_qt4 pair of
- # hooks (they both share the got_kbdint flag)
-
- def inputhook_qt4():
- """PyOS_InputHook python hook for Qt4.
-
- Process pending Qt events and if there's no pending keyboard
- input, spend a short slice of time (50ms) running the Qt event
- loop.
-
- As a Python ctypes callback can't raise an exception, we catch
- the KeyboardInterrupt and temporarily deactivate the hook,
- which will let a *second* CTRL+C be processed normally and go
- back to a clean prompt line.
- """
- try:
- allow_CTRL_C()
- app = QtCore.QCoreApplication.instance()
- if not app: # shouldn't happen, but safer if it happens anyway...
- return 0
- app.processEvents(QtCore.QEventLoop.AllEvents, 300)
- if not stdin_ready():
- # Generally a program would run QCoreApplication::exec()
- # from main() to enter and process the Qt event loop until
- # quit() or exit() is called and the program terminates.
- #
- # For our input hook integration, we need to repeatedly
- # enter and process the Qt event loop for only a short
- # amount of time (say 50ms) to ensure that Python stays
- # responsive to other user inputs.
- #
- # A naive approach would be to repeatedly call
- # QCoreApplication::exec(), using a timer to quit after a
- # short amount of time. Unfortunately, QCoreApplication
- # emits an aboutToQuit signal before stopping, which has
- # the undesirable effect of closing all modal windows.
- #
- # To work around this problem, we instead create a
- # QEventLoop and call QEventLoop::exec(). Other than
- # setting some state variables which do not seem to be
- # used anywhere, the only thing QCoreApplication adds is
- # the aboutToQuit signal which is precisely what we are
- # trying to avoid.
- timer = QtCore.QTimer()
- event_loop = QtCore.QEventLoop()
- timer.timeout.connect(event_loop.quit)
- while not stdin_ready():
- timer.start(50)
- event_loop.exec_()
- timer.stop()
- except KeyboardInterrupt:
- global got_kbdint, sigint_timer
-
- ignore_CTRL_C()
- got_kbdint = True
- mgr.clear_inputhook()
-
- # This generates a second SIGINT so the user doesn't have to
- # press CTRL+C twice to get a clean prompt.
- #
- # Since we can't catch the resulting KeyboardInterrupt here
- # (because this is a ctypes callback), we use a timer to
- # generate the SIGINT after we leave this callback.
- #
- # Unfortunately this doesn't work on Windows (SIGINT kills
- # Python and CTRL_C_EVENT doesn't work).
- if(os.name == 'posix'):
- pid = os.getpid()
- if(not sigint_timer):
- sigint_timer = threading.Timer(.01, os.kill,
- args=[pid, signal.SIGINT] )
- sigint_timer.start()
- else:
- print("\nKeyboardInterrupt - Ctrl-C again for new prompt")
-
-
- except: # NO exceptions are allowed to escape from a ctypes callback
- ignore_CTRL_C()
- from traceback import print_exc
- print_exc()
- print("Got exception from inputhook_qt4, unregistering.")
- mgr.clear_inputhook()
- finally:
- allow_CTRL_C()
- return 0
-
- def preprompthook_qt4(ishell):
- """'pre_prompt_hook' used to restore the Qt4 input hook
-
- (in case the latter was temporarily deactivated after a
- CTRL+C)
- """
- global got_kbdint, sigint_timer
-
- if(sigint_timer):
- sigint_timer.cancel()
- sigint_timer = None
-
- if got_kbdint:
- mgr.set_inputhook(inputhook_qt4)
- got_kbdint = False
-
- ip._inputhook_qt4 = inputhook_qt4
- ip.set_hook('pre_prompt_hook', preprompthook_qt4)
-
- return app, inputhook_qt4
+# -*- coding: utf-8 -*-
+"""
+Qt4's inputhook support function
+
+Author: Christian Boos
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import os
+import signal
+import threading
+
+from IPython.core.interactiveshell import InteractiveShell
+from IPython.external.qt_for_kernel import QtCore, QtGui
+from IPython.lib.inputhook import allow_CTRL_C, ignore_CTRL_C, stdin_ready
+
+#-----------------------------------------------------------------------------
+# Module Globals
+#-----------------------------------------------------------------------------
+
+got_kbdint = False
+sigint_timer = None
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+def create_inputhook_qt4(mgr, app=None):
+ """Create an input hook for running the Qt4 application event loop.
+
+ Parameters
+ ----------
+ mgr : an InputHookManager
+
+ app : Qt Application, optional.
+ Running application to use. If not given, we probe Qt for an
+ existing application object, and create a new one if none is found.
+
+ Returns
+ -------
+ A pair consisting of a Qt Application (either the one given or the
+ one found or created) and a inputhook.
+
+ Notes
+ -----
+ We use a custom input hook instead of PyQt4's default one, as it
+ interacts better with the readline packages (issue #481).
+
+ The inputhook function works in tandem with a 'pre_prompt_hook'
+ which automatically restores the hook as an inputhook in case the
+ latter has been temporarily disabled after having intercepted a
+ KeyboardInterrupt.
+ """
+
+ if app is None:
+ app = QtCore.QCoreApplication.instance()
+ if app is None:
+ app = QtGui.QApplication([" "])
+
+ # Re-use previously created inputhook if any
+ ip = InteractiveShell.instance()
+ if hasattr(ip, '_inputhook_qt4'):
+ return app, ip._inputhook_qt4
+
+ # Otherwise create the inputhook_qt4/preprompthook_qt4 pair of
+ # hooks (they both share the got_kbdint flag)
+
+ def inputhook_qt4():
+ """PyOS_InputHook python hook for Qt4.
+
+ Process pending Qt events and if there's no pending keyboard
+ input, spend a short slice of time (50ms) running the Qt event
+ loop.
+
+ As a Python ctypes callback can't raise an exception, we catch
+ the KeyboardInterrupt and temporarily deactivate the hook,
+ which will let a *second* CTRL+C be processed normally and go
+ back to a clean prompt line.
+ """
+ try:
+ allow_CTRL_C()
+ app = QtCore.QCoreApplication.instance()
+ if not app: # shouldn't happen, but safer if it happens anyway...
+ return 0
+ app.processEvents(QtCore.QEventLoop.AllEvents, 300)
+ if not stdin_ready():
+ # Generally a program would run QCoreApplication::exec()
+ # from main() to enter and process the Qt event loop until
+ # quit() or exit() is called and the program terminates.
+ #
+ # For our input hook integration, we need to repeatedly
+ # enter and process the Qt event loop for only a short
+ # amount of time (say 50ms) to ensure that Python stays
+ # responsive to other user inputs.
+ #
+ # A naive approach would be to repeatedly call
+ # QCoreApplication::exec(), using a timer to quit after a
+ # short amount of time. Unfortunately, QCoreApplication
+ # emits an aboutToQuit signal before stopping, which has
+ # the undesirable effect of closing all modal windows.
+ #
+ # To work around this problem, we instead create a
+ # QEventLoop and call QEventLoop::exec(). Other than
+ # setting some state variables which do not seem to be
+ # used anywhere, the only thing QCoreApplication adds is
+ # the aboutToQuit signal which is precisely what we are
+ # trying to avoid.
+ timer = QtCore.QTimer()
+ event_loop = QtCore.QEventLoop()
+ timer.timeout.connect(event_loop.quit)
+ while not stdin_ready():
+ timer.start(50)
+ event_loop.exec_()
+ timer.stop()
+ except KeyboardInterrupt:
+ global got_kbdint, sigint_timer
+
+ ignore_CTRL_C()
+ got_kbdint = True
+ mgr.clear_inputhook()
+
+ # This generates a second SIGINT so the user doesn't have to
+ # press CTRL+C twice to get a clean prompt.
+ #
+ # Since we can't catch the resulting KeyboardInterrupt here
+ # (because this is a ctypes callback), we use a timer to
+ # generate the SIGINT after we leave this callback.
+ #
+ # Unfortunately this doesn't work on Windows (SIGINT kills
+ # Python and CTRL_C_EVENT doesn't work).
+ if(os.name == 'posix'):
+ pid = os.getpid()
+ if(not sigint_timer):
+ sigint_timer = threading.Timer(.01, os.kill,
+ args=[pid, signal.SIGINT] )
+ sigint_timer.start()
+ else:
+ print("\nKeyboardInterrupt - Ctrl-C again for new prompt")
+
+
+ except: # NO exceptions are allowed to escape from a ctypes callback
+ ignore_CTRL_C()
+ from traceback import print_exc
+ print_exc()
+ print("Got exception from inputhook_qt4, unregistering.")
+ mgr.clear_inputhook()
+ finally:
+ allow_CTRL_C()
+ return 0
+
+ def preprompthook_qt4(ishell):
+ """'pre_prompt_hook' used to restore the Qt4 input hook
+
+ (in case the latter was temporarily deactivated after a
+ CTRL+C)
+ """
+ global got_kbdint, sigint_timer
+
+ if(sigint_timer):
+ sigint_timer.cancel()
+ sigint_timer = None
+
+ if got_kbdint:
+ mgr.set_inputhook(inputhook_qt4)
+ got_kbdint = False
+
+ ip._inputhook_qt4 = inputhook_qt4
+ ip.set_hook('pre_prompt_hook', preprompthook_qt4)
+
+ return app, inputhook_qt4
diff --git a/contrib/python/ipython/py2/IPython/lib/inputhookwx.py b/contrib/python/ipython/py2/IPython/lib/inputhookwx.py
index e054c6d915..3aac526131 100644
--- a/contrib/python/ipython/py2/IPython/lib/inputhookwx.py
+++ b/contrib/python/ipython/py2/IPython/lib/inputhookwx.py
@@ -1,167 +1,167 @@
-# encoding: utf-8
-
-"""
-Enable wxPython to be used interacive by setting PyOS_InputHook.
-
-Authors: Robin Dunn, Brian Granger, Ondrej Certik
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import sys
-import signal
-import time
-from timeit import default_timer as clock
-import wx
-
-from IPython.lib.inputhook import stdin_ready
-
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-def inputhook_wx1():
- """Run the wx event loop by processing pending events only.
-
- This approach seems to work, but its performance is not great as it
- relies on having PyOS_InputHook called regularly.
- """
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
-
- # Make a temporary event loop and process system events until
- # there are no more waiting, then allow idle events (which
- # will also deal with pending or posted wx events.)
- evtloop = wx.EventLoop()
- ea = wx.EventLoopActivator(evtloop)
- while evtloop.Pending():
- evtloop.Dispatch()
- app.ProcessIdle()
- del ea
- except KeyboardInterrupt:
- pass
- return 0
-
-class EventLoopTimer(wx.Timer):
-
- def __init__(self, func):
- self.func = func
- wx.Timer.__init__(self)
-
- def Notify(self):
- self.func()
-
-class EventLoopRunner(object):
-
- def Run(self, time):
- self.evtloop = wx.EventLoop()
- self.timer = EventLoopTimer(self.check_stdin)
- self.timer.Start(time)
- self.evtloop.Run()
-
- def check_stdin(self):
- if stdin_ready():
- self.timer.Stop()
- self.evtloop.Exit()
-
-def inputhook_wx2():
- """Run the wx event loop, polling for stdin.
-
- This version runs the wx eventloop for an undetermined amount of time,
- during which it periodically checks to see if anything is ready on
- stdin. If anything is ready on stdin, the event loop exits.
-
- The argument to elr.Run controls how often the event loop looks at stdin.
- This determines the responsiveness at the keyboard. A setting of 1000
- enables a user to type at most 1 char per second. I have found that a
- setting of 10 gives good keyboard response. We can shorten it further,
- but eventually performance would suffer from calling select/kbhit too
- often.
- """
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
- elr = EventLoopRunner()
- # As this time is made shorter, keyboard response improves, but idle
- # CPU load goes up. 10 ms seems like a good compromise.
- elr.Run(time=10) # CHANGE time here to control polling interval
- except KeyboardInterrupt:
- pass
- return 0
-
-def inputhook_wx3():
- """Run the wx event loop by processing pending events only.
-
- This is like inputhook_wx1, but it keeps processing pending events
- until stdin is ready. After processing all pending events, a call to
- time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
- This sleep time should be tuned though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
-
- # The import of wx on Linux sets the handler for signal.SIGINT
- # to 0. This is a bug in wx or gtk. We fix by just setting it
- # back to the Python default.
- if not callable(signal.getsignal(signal.SIGINT)):
- signal.signal(signal.SIGINT, signal.default_int_handler)
-
- evtloop = wx.EventLoop()
- ea = wx.EventLoopActivator(evtloop)
- t = clock()
- while not stdin_ready():
- while evtloop.Pending():
- t = clock()
- evtloop.Dispatch()
- app.ProcessIdle()
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- del ea
- except KeyboardInterrupt:
- pass
- return 0
-
-if sys.platform == 'darwin':
- # On OSX, evtloop.Pending() always returns True, regardless of there being
- # any events pending. As such we can't use implementations 1 or 3 of the
- # inputhook as those depend on a pending/dispatch loop.
- inputhook_wx = inputhook_wx2
-else:
- # This is our default implementation
- inputhook_wx = inputhook_wx3
+# encoding: utf-8
+
+"""
+Enable wxPython to be used interacive by setting PyOS_InputHook.
+
+Authors: Robin Dunn, Brian Granger, Ondrej Certik
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import sys
+import signal
+import time
+from timeit import default_timer as clock
+import wx
+
+from IPython.lib.inputhook import stdin_ready
+
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+def inputhook_wx1():
+ """Run the wx event loop by processing pending events only.
+
+ This approach seems to work, but its performance is not great as it
+ relies on having PyOS_InputHook called regularly.
+ """
+ try:
+ app = wx.GetApp()
+ if app is not None:
+ assert wx.Thread_IsMain()
+
+ # Make a temporary event loop and process system events until
+ # there are no more waiting, then allow idle events (which
+ # will also deal with pending or posted wx events.)
+ evtloop = wx.EventLoop()
+ ea = wx.EventLoopActivator(evtloop)
+ while evtloop.Pending():
+ evtloop.Dispatch()
+ app.ProcessIdle()
+ del ea
+ except KeyboardInterrupt:
+ pass
+ return 0
+
+class EventLoopTimer(wx.Timer):
+
+ def __init__(self, func):
+ self.func = func
+ wx.Timer.__init__(self)
+
+ def Notify(self):
+ self.func()
+
+class EventLoopRunner(object):
+
+ def Run(self, time):
+ self.evtloop = wx.EventLoop()
+ self.timer = EventLoopTimer(self.check_stdin)
+ self.timer.Start(time)
+ self.evtloop.Run()
+
+ def check_stdin(self):
+ if stdin_ready():
+ self.timer.Stop()
+ self.evtloop.Exit()
+
+def inputhook_wx2():
+ """Run the wx event loop, polling for stdin.
+
+ This version runs the wx eventloop for an undetermined amount of time,
+ during which it periodically checks to see if anything is ready on
+ stdin. If anything is ready on stdin, the event loop exits.
+
+ The argument to elr.Run controls how often the event loop looks at stdin.
+ This determines the responsiveness at the keyboard. A setting of 1000
+ enables a user to type at most 1 char per second. I have found that a
+ setting of 10 gives good keyboard response. We can shorten it further,
+ but eventually performance would suffer from calling select/kbhit too
+ often.
+ """
+ try:
+ app = wx.GetApp()
+ if app is not None:
+ assert wx.Thread_IsMain()
+ elr = EventLoopRunner()
+ # As this time is made shorter, keyboard response improves, but idle
+ # CPU load goes up. 10 ms seems like a good compromise.
+ elr.Run(time=10) # CHANGE time here to control polling interval
+ except KeyboardInterrupt:
+ pass
+ return 0
+
+def inputhook_wx3():
+ """Run the wx event loop by processing pending events only.
+
+ This is like inputhook_wx1, but it keeps processing pending events
+ until stdin is ready. After processing all pending events, a call to
+ time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
+ This sleep time should be tuned though for best performance.
+ """
+ # We need to protect against a user pressing Control-C when IPython is
+ # idle and this is running. We trap KeyboardInterrupt and pass.
+ try:
+ app = wx.GetApp()
+ if app is not None:
+ assert wx.Thread_IsMain()
+
+ # The import of wx on Linux sets the handler for signal.SIGINT
+ # to 0. This is a bug in wx or gtk. We fix by just setting it
+ # back to the Python default.
+ if not callable(signal.getsignal(signal.SIGINT)):
+ signal.signal(signal.SIGINT, signal.default_int_handler)
+
+ evtloop = wx.EventLoop()
+ ea = wx.EventLoopActivator(evtloop)
+ t = clock()
+ while not stdin_ready():
+ while evtloop.Pending():
+ t = clock()
+ evtloop.Dispatch()
+ app.ProcessIdle()
+ # We need to sleep at this point to keep the idle CPU load
+ # low. However, if sleep to long, GUI response is poor. As
+ # a compromise, we watch how often GUI events are being processed
+ # and switch between a short and long sleep time. Here are some
+ # stats useful in helping to tune this.
+ # time CPU load
+ # 0.001 13%
+ # 0.005 3%
+ # 0.01 1.5%
+ # 0.05 0.5%
+ used_time = clock() - t
+ if used_time > 10.0:
+ # print 'Sleep for 1 s' # dbg
+ time.sleep(1.0)
+ elif used_time > 0.1:
+ # Few GUI events coming in, so we can sleep longer
+ # print 'Sleep for 0.05 s' # dbg
+ time.sleep(0.05)
+ else:
+ # Many GUI events coming in, so sleep only very little
+ time.sleep(0.001)
+ del ea
+ except KeyboardInterrupt:
+ pass
+ return 0
+
+if sys.platform == 'darwin':
+ # On OSX, evtloop.Pending() always returns True, regardless of there being
+ # any events pending. As such we can't use implementations 1 or 3 of the
+ # inputhook as those depend on a pending/dispatch loop.
+ inputhook_wx = inputhook_wx2
+else:
+ # This is our default implementation
+ inputhook_wx = inputhook_wx3
diff --git a/contrib/python/ipython/py2/IPython/lib/kernel.py b/contrib/python/ipython/py2/IPython/lib/kernel.py
index 7de2ea4b12..af9827667f 100644
--- a/contrib/python/ipython/py2/IPython/lib/kernel.py
+++ b/contrib/python/ipython/py2/IPython/lib/kernel.py
@@ -1,13 +1,13 @@
-"""[DEPRECATED] Utilities for connecting to kernels
-
-Moved to IPython.kernel.connect
-"""
-
-import warnings
-warnings.warn("IPython.lib.kernel moved to IPython.kernel.connect in IPython 1.0,"
- " and will be removed in IPython 6.0.",
- DeprecationWarning
-)
-
-from ipykernel.connect import *
-
+"""[DEPRECATED] Utilities for connecting to kernels
+
+Moved to IPython.kernel.connect
+"""
+
+import warnings
+warnings.warn("IPython.lib.kernel moved to IPython.kernel.connect in IPython 1.0,"
+ " and will be removed in IPython 6.0.",
+ DeprecationWarning
+)
+
+from ipykernel.connect import *
+
diff --git a/contrib/python/ipython/py2/IPython/lib/latextools.py b/contrib/python/ipython/py2/IPython/lib/latextools.py
index 4df8e562ed..c3230dd489 100644
--- a/contrib/python/ipython/py2/IPython/lib/latextools.py
+++ b/contrib/python/ipython/py2/IPython/lib/latextools.py
@@ -1,111 +1,111 @@
-# -*- coding: utf-8 -*-
-"""Tools for handling LaTeX."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from io import BytesIO, open
-import os
-import tempfile
-import shutil
-import subprocess
-
-from IPython.utils.process import find_cmd, FindCmdError
-from traitlets.config import get_config
-from traitlets.config.configurable import SingletonConfigurable
-from traitlets import List, Bool, Unicode
-from IPython.utils.py3compat import cast_unicode, cast_unicode_py2 as u, PY3
-
-try: # Py3
- from base64 import encodebytes
-except ImportError: # Py2
- from base64 import encodestring as encodebytes
-
-
-class LaTeXTool(SingletonConfigurable):
- """An object to store configuration of the LaTeX tool."""
- def _config_default(self):
- return get_config()
-
- backends = List(
- Unicode(), ["matplotlib", "dvipng"],
- help="Preferred backend to draw LaTeX math equations. "
- "Backends in the list are checked one by one and the first "
- "usable one is used. Note that `matplotlib` backend "
- "is usable only for inline style equations. To draw "
- "display style equations, `dvipng` backend must be specified. ",
- # It is a List instead of Enum, to make configuration more
- # flexible. For example, to use matplotlib mainly but dvipng
- # for display style, the default ["matplotlib", "dvipng"] can
- # be used. To NOT use dvipng so that other repr such as
- # unicode pretty printing is used, you can use ["matplotlib"].
+# -*- coding: utf-8 -*-
+"""Tools for handling LaTeX."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from io import BytesIO, open
+import os
+import tempfile
+import shutil
+import subprocess
+
+from IPython.utils.process import find_cmd, FindCmdError
+from traitlets.config import get_config
+from traitlets.config.configurable import SingletonConfigurable
+from traitlets import List, Bool, Unicode
+from IPython.utils.py3compat import cast_unicode, cast_unicode_py2 as u, PY3
+
+try: # Py3
+ from base64 import encodebytes
+except ImportError: # Py2
+ from base64 import encodestring as encodebytes
+
+
+class LaTeXTool(SingletonConfigurable):
+ """An object to store configuration of the LaTeX tool."""
+ def _config_default(self):
+ return get_config()
+
+ backends = List(
+ Unicode(), ["matplotlib", "dvipng"],
+ help="Preferred backend to draw LaTeX math equations. "
+ "Backends in the list are checked one by one and the first "
+ "usable one is used. Note that `matplotlib` backend "
+ "is usable only for inline style equations. To draw "
+ "display style equations, `dvipng` backend must be specified. ",
+ # It is a List instead of Enum, to make configuration more
+ # flexible. For example, to use matplotlib mainly but dvipng
+ # for display style, the default ["matplotlib", "dvipng"] can
+ # be used. To NOT use dvipng so that other repr such as
+ # unicode pretty printing is used, you can use ["matplotlib"].
).tag(config=True)
-
- use_breqn = Bool(
- True,
- help="Use breqn.sty to automatically break long equations. "
- "This configuration takes effect only for dvipng backend.",
+
+ use_breqn = Bool(
+ True,
+ help="Use breqn.sty to automatically break long equations. "
+ "This configuration takes effect only for dvipng backend.",
).tag(config=True)
-
- packages = List(
- ['amsmath', 'amsthm', 'amssymb', 'bm'],
- help="A list of packages to use for dvipng backend. "
- "'breqn' will be automatically appended when use_breqn=True.",
+
+ packages = List(
+ ['amsmath', 'amsthm', 'amssymb', 'bm'],
+ help="A list of packages to use for dvipng backend. "
+ "'breqn' will be automatically appended when use_breqn=True.",
).tag(config=True)
-
- preamble = Unicode(
- help="Additional preamble to use when generating LaTeX source "
- "for dvipng backend.",
+
+ preamble = Unicode(
+ help="Additional preamble to use when generating LaTeX source "
+ "for dvipng backend.",
).tag(config=True)
-
-
-def latex_to_png(s, encode=False, backend=None, wrap=False):
- """Render a LaTeX string to PNG.
-
- Parameters
- ----------
+
+
+def latex_to_png(s, encode=False, backend=None, wrap=False):
+ """Render a LaTeX string to PNG.
+
+ Parameters
+ ----------
s : str
- The raw string containing valid inline LaTeX.
- encode : bool, optional
- Should the PNG data base64 encoded to make it JSON'able.
- backend : {matplotlib, dvipng}
- Backend for producing PNG data.
- wrap : bool
- If true, Automatically wrap `s` as a LaTeX equation.
-
- None is returned when the backend cannot be used.
-
- """
- s = cast_unicode(s)
- allowed_backends = LaTeXTool.instance().backends
- if backend is None:
- backend = allowed_backends[0]
- if backend not in allowed_backends:
- return None
- if backend == 'matplotlib':
- f = latex_to_png_mpl
- elif backend == 'dvipng':
- f = latex_to_png_dvipng
- else:
- raise ValueError('No such backend {0}'.format(backend))
- bin_data = f(s, wrap)
- if encode and bin_data:
- bin_data = encodebytes(bin_data)
- return bin_data
-
-
-def latex_to_png_mpl(s, wrap):
- try:
- from matplotlib import mathtext
+ The raw string containing valid inline LaTeX.
+ encode : bool, optional
+ Should the PNG data base64 encoded to make it JSON'able.
+ backend : {matplotlib, dvipng}
+ Backend for producing PNG data.
+ wrap : bool
+ If true, Automatically wrap `s` as a LaTeX equation.
+
+ None is returned when the backend cannot be used.
+
+ """
+ s = cast_unicode(s)
+ allowed_backends = LaTeXTool.instance().backends
+ if backend is None:
+ backend = allowed_backends[0]
+ if backend not in allowed_backends:
+ return None
+ if backend == 'matplotlib':
+ f = latex_to_png_mpl
+ elif backend == 'dvipng':
+ f = latex_to_png_dvipng
+ else:
+ raise ValueError('No such backend {0}'.format(backend))
+ bin_data = f(s, wrap)
+ if encode and bin_data:
+ bin_data = encodebytes(bin_data)
+ return bin_data
+
+
+def latex_to_png_mpl(s, wrap):
+ try:
+ from matplotlib import mathtext
from pyparsing import ParseFatalException
- except ImportError:
- return None
-
- # mpl mathtext doesn't support display math, force inline
- s = s.replace('$$', '$')
- if wrap:
- s = u'${0}$'.format(s)
-
+ except ImportError:
+ return None
+
+ # mpl mathtext doesn't support display math, force inline
+ s = s.replace('$$', '$')
+ if wrap:
+ s = u'${0}$'.format(s)
+
try:
mt = mathtext.MathTextParser('bitmap')
f = BytesIO()
@@ -113,93 +113,93 @@ def latex_to_png_mpl(s, wrap):
return f.getvalue()
except (ValueError, RuntimeError, ParseFatalException):
return None
-
-
-def latex_to_png_dvipng(s, wrap):
- try:
- find_cmd('latex')
- find_cmd('dvipng')
- except FindCmdError:
- return None
- try:
- workdir = tempfile.mkdtemp()
- tmpfile = os.path.join(workdir, "tmp.tex")
- dvifile = os.path.join(workdir, "tmp.dvi")
- outfile = os.path.join(workdir, "tmp.png")
-
- with open(tmpfile, "w", encoding='utf8') as f:
- f.writelines(genelatex(s, wrap))
-
- with open(os.devnull, 'wb') as devnull:
- subprocess.check_call(
- ["latex", "-halt-on-error", "-interaction", "batchmode", tmpfile],
- cwd=workdir, stdout=devnull, stderr=devnull)
-
- subprocess.check_call(
- ["dvipng", "-T", "tight", "-x", "1500", "-z", "9",
- "-bg", "transparent", "-o", outfile, dvifile], cwd=workdir,
- stdout=devnull, stderr=devnull)
-
- with open(outfile, "rb") as f:
- return f.read()
+
+
+def latex_to_png_dvipng(s, wrap):
+ try:
+ find_cmd('latex')
+ find_cmd('dvipng')
+ except FindCmdError:
+ return None
+ try:
+ workdir = tempfile.mkdtemp()
+ tmpfile = os.path.join(workdir, "tmp.tex")
+ dvifile = os.path.join(workdir, "tmp.dvi")
+ outfile = os.path.join(workdir, "tmp.png")
+
+ with open(tmpfile, "w", encoding='utf8') as f:
+ f.writelines(genelatex(s, wrap))
+
+ with open(os.devnull, 'wb') as devnull:
+ subprocess.check_call(
+ ["latex", "-halt-on-error", "-interaction", "batchmode", tmpfile],
+ cwd=workdir, stdout=devnull, stderr=devnull)
+
+ subprocess.check_call(
+ ["dvipng", "-T", "tight", "-x", "1500", "-z", "9",
+ "-bg", "transparent", "-o", outfile, dvifile], cwd=workdir,
+ stdout=devnull, stderr=devnull)
+
+ with open(outfile, "rb") as f:
+ return f.read()
except subprocess.CalledProcessError:
return None
- finally:
- shutil.rmtree(workdir)
-
-
-def kpsewhich(filename):
- """Invoke kpsewhich command with an argument `filename`."""
- try:
- find_cmd("kpsewhich")
- proc = subprocess.Popen(
- ["kpsewhich", filename],
- stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- (stdout, stderr) = proc.communicate()
- return stdout.strip().decode('utf8', 'replace')
- except FindCmdError:
- pass
-
-
-def genelatex(body, wrap):
- """Generate LaTeX document for dvipng backend."""
- lt = LaTeXTool.instance()
- breqn = wrap and lt.use_breqn and kpsewhich("breqn.sty")
- yield u(r'\documentclass{article}')
- packages = lt.packages
- if breqn:
- packages = packages + ['breqn']
- for pack in packages:
- yield u(r'\usepackage{{{0}}}'.format(pack))
- yield u(r'\pagestyle{empty}')
- if lt.preamble:
- yield lt.preamble
- yield u(r'\begin{document}')
- if breqn:
- yield u(r'\begin{dmath*}')
- yield body
- yield u(r'\end{dmath*}')
- elif wrap:
- yield u'$${0}$$'.format(body)
- else:
- yield body
- yield u'\end{document}'
-
-
-_data_uri_template_png = u"""<img src="data:image/png;base64,%s" alt=%s />"""
-
-def latex_to_html(s, alt='image'):
- """Render LaTeX to HTML with embedded PNG data using data URIs.
-
- Parameters
- ----------
- s : str
- The raw string containing valid inline LateX.
- alt : str
- The alt text to use for the HTML.
- """
- base64_data = latex_to_png(s, encode=True).decode('ascii')
- if base64_data:
- return _data_uri_template_png % (base64_data, alt)
-
-
+ finally:
+ shutil.rmtree(workdir)
+
+
+def kpsewhich(filename):
+ """Invoke kpsewhich command with an argument `filename`."""
+ try:
+ find_cmd("kpsewhich")
+ proc = subprocess.Popen(
+ ["kpsewhich", filename],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ (stdout, stderr) = proc.communicate()
+ return stdout.strip().decode('utf8', 'replace')
+ except FindCmdError:
+ pass
+
+
+def genelatex(body, wrap):
+ """Generate LaTeX document for dvipng backend."""
+ lt = LaTeXTool.instance()
+ breqn = wrap and lt.use_breqn and kpsewhich("breqn.sty")
+ yield u(r'\documentclass{article}')
+ packages = lt.packages
+ if breqn:
+ packages = packages + ['breqn']
+ for pack in packages:
+ yield u(r'\usepackage{{{0}}}'.format(pack))
+ yield u(r'\pagestyle{empty}')
+ if lt.preamble:
+ yield lt.preamble
+ yield u(r'\begin{document}')
+ if breqn:
+ yield u(r'\begin{dmath*}')
+ yield body
+ yield u(r'\end{dmath*}')
+ elif wrap:
+ yield u'$${0}$$'.format(body)
+ else:
+ yield body
+ yield u'\end{document}'
+
+
+_data_uri_template_png = u"""<img src="data:image/png;base64,%s" alt=%s />"""
+
+def latex_to_html(s, alt='image'):
+ """Render LaTeX to HTML with embedded PNG data using data URIs.
+
+ Parameters
+ ----------
+ s : str
+ The raw string containing valid inline LateX.
+ alt : str
+ The alt text to use for the HTML.
+ """
+ base64_data = latex_to_png(s, encode=True).decode('ascii')
+ if base64_data:
+ return _data_uri_template_png % (base64_data, alt)
+
+
diff --git a/contrib/python/ipython/py2/IPython/lib/lexers.py b/contrib/python/ipython/py2/IPython/lib/lexers.py
index ec43856115..9160ae1245 100644
--- a/contrib/python/ipython/py2/IPython/lib/lexers.py
+++ b/contrib/python/ipython/py2/IPython/lib/lexers.py
@@ -1,517 +1,517 @@
-# -*- coding: utf-8 -*-
-"""
-Defines a variety of Pygments lexers for highlighting IPython code.
-
-This includes:
-
- IPythonLexer, IPython3Lexer
- Lexers for pure IPython (python + magic/shell commands)
-
- IPythonPartialTracebackLexer, IPythonTracebackLexer
- Supports 2.x and 3.x via keyword `python3`. The partial traceback
- lexer reads everything but the Python code appearing in a traceback.
- The full lexer combines the partial lexer with an IPython lexer.
-
- IPythonConsoleLexer
- A lexer for IPython console sessions, with support for tracebacks.
-
- IPyLexer
- A friendly lexer which examines the first line of text and from it,
- decides whether to use an IPython lexer or an IPython console lexer.
- This is probably the only lexer that needs to be explicitly added
- to Pygments.
-
-"""
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-# Standard library
-import re
-
-# Third party
+# -*- coding: utf-8 -*-
+"""
+Defines a variety of Pygments lexers for highlighting IPython code.
+
+This includes:
+
+ IPythonLexer, IPython3Lexer
+ Lexers for pure IPython (python + magic/shell commands)
+
+ IPythonPartialTracebackLexer, IPythonTracebackLexer
+ Supports 2.x and 3.x via keyword `python3`. The partial traceback
+ lexer reads everything but the Python code appearing in a traceback.
+ The full lexer combines the partial lexer with an IPython lexer.
+
+ IPythonConsoleLexer
+ A lexer for IPython console sessions, with support for tracebacks.
+
+ IPyLexer
+ A friendly lexer which examines the first line of text and from it,
+ decides whether to use an IPython lexer or an IPython console lexer.
+ This is probably the only lexer that needs to be explicitly added
+ to Pygments.
+
+"""
+#-----------------------------------------------------------------------------
+# Copyright (c) 2013, the IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+# Standard library
+import re
+
+# Third party
from pygments.lexers import BashLexer, Python3Lexer
try:
# PythonLexer was renamed to Python2Lexer in pygments 2.5
from pygments.lexers import Python2Lexer
except ImportError:
from pygments.lexers import PythonLexer as Python2Lexer
-from pygments.lexer import (
- Lexer, DelegatingLexer, RegexLexer, do_insertions, bygroups, using,
-)
-from pygments.token import (
+from pygments.lexer import (
+ Lexer, DelegatingLexer, RegexLexer, do_insertions, bygroups, using,
+)
+from pygments.token import (
Generic, Keyword, Literal, Name, Operator, Other, Text, Error,
-)
-from pygments.util import get_bool_opt
-
-# Local
-
-line_re = re.compile('.*?\n')
-
-__all__ = ['build_ipy_lexer', 'IPython3Lexer', 'IPythonLexer',
- 'IPythonPartialTracebackLexer', 'IPythonTracebackLexer',
- 'IPythonConsoleLexer', 'IPyLexer']
-
-ipython_tokens = [
- (r"(?s)(\s*)(%%)(\w+)(.*)", bygroups(Text, Operator, Keyword, Text)),
- (r'(?s)(^\s*)(%%!)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(BashLexer))),
- (r"(%%?)(\w+)(\?\??)$", bygroups(Operator, Keyword, Operator)),
- (r"\b(\?\??)(\s*)$", bygroups(Operator, Text)),
- (r'(%)(sx|sc|system)(.*)(\n)', bygroups(Operator, Keyword,
- using(BashLexer), Text)),
- (r'(%)(\w+)(.*\n)', bygroups(Operator, Keyword, Text)),
- (r'^(!!)(.+)(\n)', bygroups(Operator, using(BashLexer), Text)),
- (r'(!)(?!=)(.+)(\n)', bygroups(Operator, using(BashLexer), Text)),
- (r'^(\s*)(\?\??)(\s*%{0,2}[\w\.\*]*)', bygroups(Text, Operator, Text)),
- (r'(\s*%{0,2}[\w\.\*]*)(\?\??)(\s*)$', bygroups(Text, Operator, Text)),
-]
-
-def build_ipy_lexer(python3):
- """Builds IPython lexers depending on the value of `python3`.
-
- The lexer inherits from an appropriate Python lexer and then adds
- information about IPython specific keywords (i.e. magic commands,
- shell commands, etc.)
-
- Parameters
- ----------
- python3 : bool
- If `True`, then build an IPython lexer from a Python 3 lexer.
-
- """
- # It would be nice to have a single IPython lexer class which takes
- # a boolean `python3`. But since there are two Python lexer classes,
- # we will also have two IPython lexer classes.
- if python3:
- PyLexer = Python3Lexer
- name = 'IPython3'
- aliases = ['ipython3']
- doc = """IPython3 Lexer"""
- else:
+)
+from pygments.util import get_bool_opt
+
+# Local
+
+line_re = re.compile('.*?\n')
+
+__all__ = ['build_ipy_lexer', 'IPython3Lexer', 'IPythonLexer',
+ 'IPythonPartialTracebackLexer', 'IPythonTracebackLexer',
+ 'IPythonConsoleLexer', 'IPyLexer']
+
+ipython_tokens = [
+ (r"(?s)(\s*)(%%)(\w+)(.*)", bygroups(Text, Operator, Keyword, Text)),
+ (r'(?s)(^\s*)(%%!)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(BashLexer))),
+ (r"(%%?)(\w+)(\?\??)$", bygroups(Operator, Keyword, Operator)),
+ (r"\b(\?\??)(\s*)$", bygroups(Operator, Text)),
+ (r'(%)(sx|sc|system)(.*)(\n)', bygroups(Operator, Keyword,
+ using(BashLexer), Text)),
+ (r'(%)(\w+)(.*\n)', bygroups(Operator, Keyword, Text)),
+ (r'^(!!)(.+)(\n)', bygroups(Operator, using(BashLexer), Text)),
+ (r'(!)(?!=)(.+)(\n)', bygroups(Operator, using(BashLexer), Text)),
+ (r'^(\s*)(\?\??)(\s*%{0,2}[\w\.\*]*)', bygroups(Text, Operator, Text)),
+ (r'(\s*%{0,2}[\w\.\*]*)(\?\??)(\s*)$', bygroups(Text, Operator, Text)),
+]
+
+def build_ipy_lexer(python3):
+ """Builds IPython lexers depending on the value of `python3`.
+
+ The lexer inherits from an appropriate Python lexer and then adds
+ information about IPython specific keywords (i.e. magic commands,
+ shell commands, etc.)
+
+ Parameters
+ ----------
+ python3 : bool
+ If `True`, then build an IPython lexer from a Python 3 lexer.
+
+ """
+ # It would be nice to have a single IPython lexer class which takes
+ # a boolean `python3`. But since there are two Python lexer classes,
+ # we will also have two IPython lexer classes.
+ if python3:
+ PyLexer = Python3Lexer
+ name = 'IPython3'
+ aliases = ['ipython3']
+ doc = """IPython3 Lexer"""
+ else:
PyLexer = Python2Lexer
- name = 'IPython'
- aliases = ['ipython2', 'ipython']
- doc = """IPython Lexer"""
-
- tokens = PyLexer.tokens.copy()
- tokens['root'] = ipython_tokens + tokens['root']
-
- attrs = {'name': name, 'aliases': aliases, 'filenames': [],
- '__doc__': doc, 'tokens': tokens}
-
- return type(name, (PyLexer,), attrs)
-
-
-IPython3Lexer = build_ipy_lexer(python3=True)
-IPythonLexer = build_ipy_lexer(python3=False)
-
-
-class IPythonPartialTracebackLexer(RegexLexer):
- """
- Partial lexer for IPython tracebacks.
-
- Handles all the non-python output. This works for both Python 2.x and 3.x.
-
- """
- name = 'IPython Partial Traceback'
-
- tokens = {
- 'root': [
- # Tracebacks for syntax errors have a different style.
- # For both types of tracebacks, we mark the first line with
- # Generic.Traceback. For syntax errors, we mark the filename
- # as we mark the filenames for non-syntax tracebacks.
- #
- # These two regexps define how IPythonConsoleLexer finds a
- # traceback.
- #
- ## Non-syntax traceback
- (r'^(\^C)?(-+\n)', bygroups(Error, Generic.Traceback)),
- ## Syntax traceback
- (r'^( File)(.*)(, line )(\d+\n)',
- bygroups(Generic.Traceback, Name.Namespace,
- Generic.Traceback, Literal.Number.Integer)),
-
- # (Exception Identifier)(Whitespace)(Traceback Message)
- (r'(?u)(^[^\d\W]\w*)(\s*)(Traceback.*?\n)',
- bygroups(Name.Exception, Generic.Whitespace, Text)),
- # (Module/Filename)(Text)(Callee)(Function Signature)
- # Better options for callee and function signature?
- (r'(.*)( in )(.*)(\(.*\)\n)',
- bygroups(Name.Namespace, Text, Name.Entity, Name.Tag)),
- # Regular line: (Whitespace)(Line Number)(Python Code)
- (r'(\s*?)(\d+)(.*?\n)',
- bygroups(Generic.Whitespace, Literal.Number.Integer, Other)),
- # Emphasized line: (Arrow)(Line Number)(Python Code)
- # Using Exception token so arrow color matches the Exception.
- (r'(-*>?\s?)(\d+)(.*?\n)',
- bygroups(Name.Exception, Literal.Number.Integer, Other)),
- # (Exception Identifier)(Message)
- (r'(?u)(^[^\d\W]\w*)(:.*?\n)',
- bygroups(Name.Exception, Text)),
- # Tag everything else as Other, will be handled later.
- (r'.*\n', Other),
- ],
- }
-
-
-class IPythonTracebackLexer(DelegatingLexer):
- """
- IPython traceback lexer.
-
- For doctests, the tracebacks can be snipped as much as desired with the
- exception to the lines that designate a traceback. For non-syntax error
- tracebacks, this is the line of hyphens. For syntax error tracebacks,
- this is the line which lists the File and line number.
-
- """
- # The lexer inherits from DelegatingLexer. The "root" lexer is an
- # appropriate IPython lexer, which depends on the value of the boolean
- # `python3`. First, we parse with the partial IPython traceback lexer.
- # Then, any code marked with the "Other" token is delegated to the root
- # lexer.
- #
- name = 'IPython Traceback'
- aliases = ['ipythontb']
-
- def __init__(self, **options):
- self.python3 = get_bool_opt(options, 'python3', False)
- if self.python3:
- self.aliases = ['ipython3tb']
- else:
- self.aliases = ['ipython2tb', 'ipythontb']
-
- if self.python3:
- IPyLexer = IPython3Lexer
- else:
- IPyLexer = IPythonLexer
-
- DelegatingLexer.__init__(self, IPyLexer,
- IPythonPartialTracebackLexer, **options)
-
-class IPythonConsoleLexer(Lexer):
- """
- An IPython console lexer for IPython code-blocks and doctests, such as:
-
- .. code-block:: rst
-
- .. code-block:: ipythonconsole
-
- In [1]: a = 'foo'
-
- In [2]: a
- Out[2]: 'foo'
-
- In [3]: print a
- foo
-
- In [4]: 1 / 0
-
-
- Support is also provided for IPython exceptions:
-
- .. code-block:: rst
-
- .. code-block:: ipythonconsole
-
- In [1]: raise Exception
-
- ---------------------------------------------------------------------------
- Exception Traceback (most recent call last)
- <ipython-input-1-fca2ab0ca76b> in <module>()
- ----> 1 raise Exception
-
- Exception:
-
- """
- name = 'IPython console session'
- aliases = ['ipythonconsole']
- mimetypes = ['text/x-ipython-console']
-
- # The regexps used to determine what is input and what is output.
- # The default prompts for IPython are:
- #
+ name = 'IPython'
+ aliases = ['ipython2', 'ipython']
+ doc = """IPython Lexer"""
+
+ tokens = PyLexer.tokens.copy()
+ tokens['root'] = ipython_tokens + tokens['root']
+
+ attrs = {'name': name, 'aliases': aliases, 'filenames': [],
+ '__doc__': doc, 'tokens': tokens}
+
+ return type(name, (PyLexer,), attrs)
+
+
+IPython3Lexer = build_ipy_lexer(python3=True)
+IPythonLexer = build_ipy_lexer(python3=False)
+
+
+class IPythonPartialTracebackLexer(RegexLexer):
+ """
+ Partial lexer for IPython tracebacks.
+
+ Handles all the non-python output. This works for both Python 2.x and 3.x.
+
+ """
+ name = 'IPython Partial Traceback'
+
+ tokens = {
+ 'root': [
+ # Tracebacks for syntax errors have a different style.
+ # For both types of tracebacks, we mark the first line with
+ # Generic.Traceback. For syntax errors, we mark the filename
+ # as we mark the filenames for non-syntax tracebacks.
+ #
+ # These two regexps define how IPythonConsoleLexer finds a
+ # traceback.
+ #
+ ## Non-syntax traceback
+ (r'^(\^C)?(-+\n)', bygroups(Error, Generic.Traceback)),
+ ## Syntax traceback
+ (r'^( File)(.*)(, line )(\d+\n)',
+ bygroups(Generic.Traceback, Name.Namespace,
+ Generic.Traceback, Literal.Number.Integer)),
+
+ # (Exception Identifier)(Whitespace)(Traceback Message)
+ (r'(?u)(^[^\d\W]\w*)(\s*)(Traceback.*?\n)',
+ bygroups(Name.Exception, Generic.Whitespace, Text)),
+ # (Module/Filename)(Text)(Callee)(Function Signature)
+ # Better options for callee and function signature?
+ (r'(.*)( in )(.*)(\(.*\)\n)',
+ bygroups(Name.Namespace, Text, Name.Entity, Name.Tag)),
+ # Regular line: (Whitespace)(Line Number)(Python Code)
+ (r'(\s*?)(\d+)(.*?\n)',
+ bygroups(Generic.Whitespace, Literal.Number.Integer, Other)),
+ # Emphasized line: (Arrow)(Line Number)(Python Code)
+ # Using Exception token so arrow color matches the Exception.
+ (r'(-*>?\s?)(\d+)(.*?\n)',
+ bygroups(Name.Exception, Literal.Number.Integer, Other)),
+ # (Exception Identifier)(Message)
+ (r'(?u)(^[^\d\W]\w*)(:.*?\n)',
+ bygroups(Name.Exception, Text)),
+ # Tag everything else as Other, will be handled later.
+ (r'.*\n', Other),
+ ],
+ }
+
+
+class IPythonTracebackLexer(DelegatingLexer):
+ """
+ IPython traceback lexer.
+
+ For doctests, the tracebacks can be snipped as much as desired with the
+ exception to the lines that designate a traceback. For non-syntax error
+ tracebacks, this is the line of hyphens. For syntax error tracebacks,
+ this is the line which lists the File and line number.
+
+ """
+ # The lexer inherits from DelegatingLexer. The "root" lexer is an
+ # appropriate IPython lexer, which depends on the value of the boolean
+ # `python3`. First, we parse with the partial IPython traceback lexer.
+ # Then, any code marked with the "Other" token is delegated to the root
+ # lexer.
+ #
+ name = 'IPython Traceback'
+ aliases = ['ipythontb']
+
+ def __init__(self, **options):
+ self.python3 = get_bool_opt(options, 'python3', False)
+ if self.python3:
+ self.aliases = ['ipython3tb']
+ else:
+ self.aliases = ['ipython2tb', 'ipythontb']
+
+ if self.python3:
+ IPyLexer = IPython3Lexer
+ else:
+ IPyLexer = IPythonLexer
+
+ DelegatingLexer.__init__(self, IPyLexer,
+ IPythonPartialTracebackLexer, **options)
+
+class IPythonConsoleLexer(Lexer):
+ """
+ An IPython console lexer for IPython code-blocks and doctests, such as:
+
+ .. code-block:: rst
+
+ .. code-block:: ipythonconsole
+
+ In [1]: a = 'foo'
+
+ In [2]: a
+ Out[2]: 'foo'
+
+ In [3]: print a
+ foo
+
+ In [4]: 1 / 0
+
+
+ Support is also provided for IPython exceptions:
+
+ .. code-block:: rst
+
+ .. code-block:: ipythonconsole
+
+ In [1]: raise Exception
+
+ ---------------------------------------------------------------------------
+ Exception Traceback (most recent call last)
+ <ipython-input-1-fca2ab0ca76b> in <module>()
+ ----> 1 raise Exception
+
+ Exception:
+
+ """
+ name = 'IPython console session'
+ aliases = ['ipythonconsole']
+ mimetypes = ['text/x-ipython-console']
+
+ # The regexps used to determine what is input and what is output.
+ # The default prompts for IPython are:
+ #
# in = 'In [#]: '
# continuation = ' .D.: '
# template = 'Out[#]: '
- #
+ #
# Where '#' is the 'prompt number' or 'execution count' and 'D'
# D is a number of dots matching the width of the execution count
#
- in1_regex = r'In \[[0-9]+\]: '
- in2_regex = r' \.\.+\.: '
- out_regex = r'Out\[[0-9]+\]: '
-
- #: The regex to determine when a traceback starts.
- ipytb_start = re.compile(r'^(\^C)?(-+\n)|^( File)(.*)(, line )(\d+\n)')
-
- def __init__(self, **options):
- """Initialize the IPython console lexer.
-
- Parameters
- ----------
- python3 : bool
- If `True`, then the console inputs are parsed using a Python 3
- lexer. Otherwise, they are parsed using a Python 2 lexer.
- in1_regex : RegexObject
- The compiled regular expression used to detect the start
- of inputs. Although the IPython configuration setting may have a
- trailing whitespace, do not include it in the regex. If `None`,
- then the default input prompt is assumed.
- in2_regex : RegexObject
- The compiled regular expression used to detect the continuation
- of inputs. Although the IPython configuration setting may have a
- trailing whitespace, do not include it in the regex. If `None`,
- then the default input prompt is assumed.
- out_regex : RegexObject
- The compiled regular expression used to detect outputs. If `None`,
- then the default output prompt is assumed.
-
- """
- self.python3 = get_bool_opt(options, 'python3', False)
- if self.python3:
- self.aliases = ['ipython3console']
- else:
- self.aliases = ['ipython2console', 'ipythonconsole']
-
- in1_regex = options.get('in1_regex', self.in1_regex)
- in2_regex = options.get('in2_regex', self.in2_regex)
- out_regex = options.get('out_regex', self.out_regex)
-
- # So that we can work with input and output prompts which have been
- # rstrip'd (possibly by editors) we also need rstrip'd variants. If
- # we do not do this, then such prompts will be tagged as 'output'.
- # The reason can't just use the rstrip'd variants instead is because
- # we want any whitespace associated with the prompt to be inserted
- # with the token. This allows formatted code to be modified so as hide
- # the appearance of prompts, with the whitespace included. One example
- # use of this is in copybutton.js from the standard lib Python docs.
- in1_regex_rstrip = in1_regex.rstrip() + '\n'
- in2_regex_rstrip = in2_regex.rstrip() + '\n'
- out_regex_rstrip = out_regex.rstrip() + '\n'
-
- # Compile and save them all.
- attrs = ['in1_regex', 'in2_regex', 'out_regex',
- 'in1_regex_rstrip', 'in2_regex_rstrip', 'out_regex_rstrip']
- for attr in attrs:
- self.__setattr__(attr, re.compile(locals()[attr]))
-
- Lexer.__init__(self, **options)
-
- if self.python3:
- pylexer = IPython3Lexer
- tblexer = IPythonTracebackLexer
- else:
- pylexer = IPythonLexer
- tblexer = IPythonTracebackLexer
-
- self.pylexer = pylexer(**options)
- self.tblexer = tblexer(**options)
-
- self.reset()
-
- def reset(self):
- self.mode = 'output'
- self.index = 0
- self.buffer = u''
- self.insertions = []
-
- def buffered_tokens(self):
- """
- Generator of unprocessed tokens after doing insertions and before
- changing to a new state.
-
- """
- if self.mode == 'output':
- tokens = [(0, Generic.Output, self.buffer)]
- elif self.mode == 'input':
- tokens = self.pylexer.get_tokens_unprocessed(self.buffer)
- else: # traceback
- tokens = self.tblexer.get_tokens_unprocessed(self.buffer)
-
- for i, t, v in do_insertions(self.insertions, tokens):
- # All token indexes are relative to the buffer.
- yield self.index + i, t, v
-
- # Clear it all
- self.index += len(self.buffer)
- self.buffer = u''
- self.insertions = []
-
- def get_mci(self, line):
- """
- Parses the line and returns a 3-tuple: (mode, code, insertion).
-
- `mode` is the next mode (or state) of the lexer, and is always equal
- to 'input', 'output', or 'tb'.
-
- `code` is a portion of the line that should be added to the buffer
- corresponding to the next mode and eventually lexed by another lexer.
- For example, `code` could be Python code if `mode` were 'input'.
-
- `insertion` is a 3-tuple (index, token, text) representing an
- unprocessed "token" that will be inserted into the stream of tokens
- that are created from the buffer once we change modes. This is usually
- the input or output prompt.
-
- In general, the next mode depends on current mode and on the contents
- of `line`.
-
- """
- # To reduce the number of regex match checks, we have multiple
- # 'if' blocks instead of 'if-elif' blocks.
-
- # Check for possible end of input
- in2_match = self.in2_regex.match(line)
- in2_match_rstrip = self.in2_regex_rstrip.match(line)
- if (in2_match and in2_match.group().rstrip() == line.rstrip()) or \
- in2_match_rstrip:
- end_input = True
- else:
- end_input = False
- if end_input and self.mode != 'tb':
- # Only look for an end of input when not in tb mode.
- # An ellipsis could appear within the traceback.
- mode = 'output'
- code = u''
- insertion = (0, Generic.Prompt, line)
- return mode, code, insertion
-
- # Check for output prompt
- out_match = self.out_regex.match(line)
- out_match_rstrip = self.out_regex_rstrip.match(line)
- if out_match or out_match_rstrip:
- mode = 'output'
- if out_match:
- idx = out_match.end()
- else:
- idx = out_match_rstrip.end()
- code = line[idx:]
- # Use the 'heading' token for output. We cannot use Generic.Error
- # since it would conflict with exceptions.
- insertion = (0, Generic.Heading, line[:idx])
- return mode, code, insertion
-
-
- # Check for input or continuation prompt (non stripped version)
- in1_match = self.in1_regex.match(line)
- if in1_match or (in2_match and self.mode != 'tb'):
- # New input or when not in tb, continued input.
- # We do not check for continued input when in tb since it is
- # allowable to replace a long stack with an ellipsis.
- mode = 'input'
- if in1_match:
- idx = in1_match.end()
- else: # in2_match
- idx = in2_match.end()
- code = line[idx:]
- insertion = (0, Generic.Prompt, line[:idx])
- return mode, code, insertion
-
- # Check for input or continuation prompt (stripped version)
- in1_match_rstrip = self.in1_regex_rstrip.match(line)
- if in1_match_rstrip or (in2_match_rstrip and self.mode != 'tb'):
- # New input or when not in tb, continued input.
- # We do not check for continued input when in tb since it is
- # allowable to replace a long stack with an ellipsis.
- mode = 'input'
- if in1_match_rstrip:
- idx = in1_match_rstrip.end()
- else: # in2_match
- idx = in2_match_rstrip.end()
- code = line[idx:]
- insertion = (0, Generic.Prompt, line[:idx])
- return mode, code, insertion
-
- # Check for traceback
- if self.ipytb_start.match(line):
- mode = 'tb'
- code = line
- insertion = None
- return mode, code, insertion
-
- # All other stuff...
- if self.mode in ('input', 'output'):
- # We assume all other text is output. Multiline input that
- # does not use the continuation marker cannot be detected.
- # For example, the 3 in the following is clearly output:
- #
- # In [1]: print 3
- # 3
- #
- # But the following second line is part of the input:
- #
- # In [2]: while True:
- # print True
- #
- # In both cases, the 2nd line will be 'output'.
- #
- mode = 'output'
- else:
- mode = 'tb'
-
- code = line
- insertion = None
-
- return mode, code, insertion
-
- def get_tokens_unprocessed(self, text):
- self.reset()
- for match in line_re.finditer(text):
- line = match.group()
- mode, code, insertion = self.get_mci(line)
-
- if mode != self.mode:
- # Yield buffered tokens before transitioning to new mode.
- for token in self.buffered_tokens():
- yield token
- self.mode = mode
-
- if insertion:
- self.insertions.append((len(self.buffer), [insertion]))
- self.buffer += code
-
+ in1_regex = r'In \[[0-9]+\]: '
+ in2_regex = r' \.\.+\.: '
+ out_regex = r'Out\[[0-9]+\]: '
+
+ #: The regex to determine when a traceback starts.
+ ipytb_start = re.compile(r'^(\^C)?(-+\n)|^( File)(.*)(, line )(\d+\n)')
+
+ def __init__(self, **options):
+ """Initialize the IPython console lexer.
+
+ Parameters
+ ----------
+ python3 : bool
+ If `True`, then the console inputs are parsed using a Python 3
+ lexer. Otherwise, they are parsed using a Python 2 lexer.
+ in1_regex : RegexObject
+ The compiled regular expression used to detect the start
+ of inputs. Although the IPython configuration setting may have a
+ trailing whitespace, do not include it in the regex. If `None`,
+ then the default input prompt is assumed.
+ in2_regex : RegexObject
+ The compiled regular expression used to detect the continuation
+ of inputs. Although the IPython configuration setting may have a
+ trailing whitespace, do not include it in the regex. If `None`,
+ then the default input prompt is assumed.
+ out_regex : RegexObject
+ The compiled regular expression used to detect outputs. If `None`,
+ then the default output prompt is assumed.
+
+ """
+ self.python3 = get_bool_opt(options, 'python3', False)
+ if self.python3:
+ self.aliases = ['ipython3console']
+ else:
+ self.aliases = ['ipython2console', 'ipythonconsole']
+
+ in1_regex = options.get('in1_regex', self.in1_regex)
+ in2_regex = options.get('in2_regex', self.in2_regex)
+ out_regex = options.get('out_regex', self.out_regex)
+
+ # So that we can work with input and output prompts which have been
+ # rstrip'd (possibly by editors) we also need rstrip'd variants. If
+ # we do not do this, then such prompts will be tagged as 'output'.
+ # The reason can't just use the rstrip'd variants instead is because
+ # we want any whitespace associated with the prompt to be inserted
+ # with the token. This allows formatted code to be modified so as hide
+ # the appearance of prompts, with the whitespace included. One example
+ # use of this is in copybutton.js from the standard lib Python docs.
+ in1_regex_rstrip = in1_regex.rstrip() + '\n'
+ in2_regex_rstrip = in2_regex.rstrip() + '\n'
+ out_regex_rstrip = out_regex.rstrip() + '\n'
+
+ # Compile and save them all.
+ attrs = ['in1_regex', 'in2_regex', 'out_regex',
+ 'in1_regex_rstrip', 'in2_regex_rstrip', 'out_regex_rstrip']
+ for attr in attrs:
+ self.__setattr__(attr, re.compile(locals()[attr]))
+
+ Lexer.__init__(self, **options)
+
+ if self.python3:
+ pylexer = IPython3Lexer
+ tblexer = IPythonTracebackLexer
+ else:
+ pylexer = IPythonLexer
+ tblexer = IPythonTracebackLexer
+
+ self.pylexer = pylexer(**options)
+ self.tblexer = tblexer(**options)
+
+ self.reset()
+
+ def reset(self):
+ self.mode = 'output'
+ self.index = 0
+ self.buffer = u''
+ self.insertions = []
+
+ def buffered_tokens(self):
+ """
+ Generator of unprocessed tokens after doing insertions and before
+ changing to a new state.
+
+ """
+ if self.mode == 'output':
+ tokens = [(0, Generic.Output, self.buffer)]
+ elif self.mode == 'input':
+ tokens = self.pylexer.get_tokens_unprocessed(self.buffer)
+ else: # traceback
+ tokens = self.tblexer.get_tokens_unprocessed(self.buffer)
+
+ for i, t, v in do_insertions(self.insertions, tokens):
+ # All token indexes are relative to the buffer.
+ yield self.index + i, t, v
+
+ # Clear it all
+ self.index += len(self.buffer)
+ self.buffer = u''
+ self.insertions = []
+
+ def get_mci(self, line):
+ """
+ Parses the line and returns a 3-tuple: (mode, code, insertion).
+
+ `mode` is the next mode (or state) of the lexer, and is always equal
+ to 'input', 'output', or 'tb'.
+
+ `code` is a portion of the line that should be added to the buffer
+ corresponding to the next mode and eventually lexed by another lexer.
+ For example, `code` could be Python code if `mode` were 'input'.
+
+ `insertion` is a 3-tuple (index, token, text) representing an
+ unprocessed "token" that will be inserted into the stream of tokens
+ that are created from the buffer once we change modes. This is usually
+ the input or output prompt.
+
+ In general, the next mode depends on current mode and on the contents
+ of `line`.
+
+ """
+ # To reduce the number of regex match checks, we have multiple
+ # 'if' blocks instead of 'if-elif' blocks.
+
+ # Check for possible end of input
+ in2_match = self.in2_regex.match(line)
+ in2_match_rstrip = self.in2_regex_rstrip.match(line)
+ if (in2_match and in2_match.group().rstrip() == line.rstrip()) or \
+ in2_match_rstrip:
+ end_input = True
+ else:
+ end_input = False
+ if end_input and self.mode != 'tb':
+ # Only look for an end of input when not in tb mode.
+ # An ellipsis could appear within the traceback.
+ mode = 'output'
+ code = u''
+ insertion = (0, Generic.Prompt, line)
+ return mode, code, insertion
+
+ # Check for output prompt
+ out_match = self.out_regex.match(line)
+ out_match_rstrip = self.out_regex_rstrip.match(line)
+ if out_match or out_match_rstrip:
+ mode = 'output'
+ if out_match:
+ idx = out_match.end()
+ else:
+ idx = out_match_rstrip.end()
+ code = line[idx:]
+ # Use the 'heading' token for output. We cannot use Generic.Error
+ # since it would conflict with exceptions.
+ insertion = (0, Generic.Heading, line[:idx])
+ return mode, code, insertion
+
+
+ # Check for input or continuation prompt (non stripped version)
+ in1_match = self.in1_regex.match(line)
+ if in1_match or (in2_match and self.mode != 'tb'):
+ # New input or when not in tb, continued input.
+ # We do not check for continued input when in tb since it is
+ # allowable to replace a long stack with an ellipsis.
+ mode = 'input'
+ if in1_match:
+ idx = in1_match.end()
+ else: # in2_match
+ idx = in2_match.end()
+ code = line[idx:]
+ insertion = (0, Generic.Prompt, line[:idx])
+ return mode, code, insertion
+
+ # Check for input or continuation prompt (stripped version)
+ in1_match_rstrip = self.in1_regex_rstrip.match(line)
+ if in1_match_rstrip or (in2_match_rstrip and self.mode != 'tb'):
+ # New input or when not in tb, continued input.
+ # We do not check for continued input when in tb since it is
+ # allowable to replace a long stack with an ellipsis.
+ mode = 'input'
+ if in1_match_rstrip:
+ idx = in1_match_rstrip.end()
+ else: # in2_match
+ idx = in2_match_rstrip.end()
+ code = line[idx:]
+ insertion = (0, Generic.Prompt, line[:idx])
+ return mode, code, insertion
+
+ # Check for traceback
+ if self.ipytb_start.match(line):
+ mode = 'tb'
+ code = line
+ insertion = None
+ return mode, code, insertion
+
+ # All other stuff...
+ if self.mode in ('input', 'output'):
+ # We assume all other text is output. Multiline input that
+ # does not use the continuation marker cannot be detected.
+ # For example, the 3 in the following is clearly output:
+ #
+ # In [1]: print 3
+ # 3
+ #
+ # But the following second line is part of the input:
+ #
+ # In [2]: while True:
+ # print True
+ #
+ # In both cases, the 2nd line will be 'output'.
+ #
+ mode = 'output'
+ else:
+ mode = 'tb'
+
+ code = line
+ insertion = None
+
+ return mode, code, insertion
+
+ def get_tokens_unprocessed(self, text):
+ self.reset()
+ for match in line_re.finditer(text):
+ line = match.group()
+ mode, code, insertion = self.get_mci(line)
+
+ if mode != self.mode:
+ # Yield buffered tokens before transitioning to new mode.
+ for token in self.buffered_tokens():
+ yield token
+ self.mode = mode
+
+ if insertion:
+ self.insertions.append((len(self.buffer), [insertion]))
+ self.buffer += code
+
for token in self.buffered_tokens():
yield token
-class IPyLexer(Lexer):
- """
- Primary lexer for all IPython-like code.
-
- This is a simple helper lexer. If the first line of the text begins with
- "In \[[0-9]+\]:", then the entire text is parsed with an IPython console
- lexer. If not, then the entire text is parsed with an IPython lexer.
-
- The goal is to reduce the number of lexers that are registered
- with Pygments.
-
- """
- name = 'IPy session'
- aliases = ['ipy']
-
- def __init__(self, **options):
- self.python3 = get_bool_opt(options, 'python3', False)
- if self.python3:
- self.aliases = ['ipy3']
- else:
- self.aliases = ['ipy2', 'ipy']
-
- Lexer.__init__(self, **options)
-
- self.IPythonLexer = IPythonLexer(**options)
- self.IPythonConsoleLexer = IPythonConsoleLexer(**options)
-
- def get_tokens_unprocessed(self, text):
- # Search for the input prompt anywhere...this allows code blocks to
- # begin with comments as well.
- if re.match(r'.*(In \[[0-9]+\]:)', text.strip(), re.DOTALL):
- lex = self.IPythonConsoleLexer
- else:
- lex = self.IPythonLexer
- for token in lex.get_tokens_unprocessed(text):
- yield token
-
+class IPyLexer(Lexer):
+ """
+ Primary lexer for all IPython-like code.
+
+ This is a simple helper lexer. If the first line of the text begins with
+ "In \[[0-9]+\]:", then the entire text is parsed with an IPython console
+ lexer. If not, then the entire text is parsed with an IPython lexer.
+
+ The goal is to reduce the number of lexers that are registered
+ with Pygments.
+
+ """
+ name = 'IPy session'
+ aliases = ['ipy']
+
+ def __init__(self, **options):
+ self.python3 = get_bool_opt(options, 'python3', False)
+ if self.python3:
+ self.aliases = ['ipy3']
+ else:
+ self.aliases = ['ipy2', 'ipy']
+
+ Lexer.__init__(self, **options)
+
+ self.IPythonLexer = IPythonLexer(**options)
+ self.IPythonConsoleLexer = IPythonConsoleLexer(**options)
+
+ def get_tokens_unprocessed(self, text):
+ # Search for the input prompt anywhere...this allows code blocks to
+ # begin with comments as well.
+ if re.match(r'.*(In \[[0-9]+\]:)', text.strip(), re.DOTALL):
+ lex = self.IPythonConsoleLexer
+ else:
+ lex = self.IPythonLexer
+ for token in lex.get_tokens_unprocessed(text):
+ yield token
+
diff --git a/contrib/python/ipython/py2/IPython/lib/pretty.py b/contrib/python/ipython/py2/IPython/lib/pretty.py
index 385365fc3c..28eee523c5 100644
--- a/contrib/python/ipython/py2/IPython/lib/pretty.py
+++ b/contrib/python/ipython/py2/IPython/lib/pretty.py
@@ -1,127 +1,127 @@
-# -*- coding: utf-8 -*-
-"""
-Python advanced pretty printer. This pretty printer is intended to
-replace the old `pprint` python module which does not allow developers
-to provide their own pretty print callbacks.
-
-This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
-
-
-Example Usage
--------------
-
-To directly print the representation of an object use `pprint`::
-
- from pretty import pprint
- pprint(complex_object)
-
-To get a string of the output use `pretty`::
-
- from pretty import pretty
- string = pretty(complex_object)
-
-
-Extending
----------
-
-The pretty library allows developers to add pretty printing rules for their
-own objects. This process is straightforward. All you have to do is to
-add a `_repr_pretty_` method to your object and call the methods on the
-pretty printer passed::
-
- class MyObject(object):
-
- def _repr_pretty_(self, p, cycle):
- ...
-
-Here is an example implementation of a `_repr_pretty_` method for a list
-subclass::
-
- class MyList(list):
-
- def _repr_pretty_(self, p, cycle):
- if cycle:
- p.text('MyList(...)')
- else:
- with p.group(8, 'MyList([', '])'):
- for idx, item in enumerate(self):
- if idx:
- p.text(',')
- p.breakable()
- p.pretty(item)
-
-The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
-react to that or the result is an infinite loop. `p.text()` just adds
-non breaking text to the output, `p.breakable()` either adds a whitespace
-or breaks here. If you pass it an argument it's used instead of the
-default space. `p.pretty` prettyprints another object using the pretty print
-method.
-
-The first parameter to the `group` function specifies the extra indentation
-of the next line. In this example the next item will either be on the same
-line (if the items are short enough) or aligned with the right edge of the
-opening bracket of `MyList`.
-
-If you just want to indent something you can use the group function
-without open / close parameters. You can also use this code::
-
- with p.indent(2):
- ...
-
-Inheritance diagram:
-
-.. inheritance-diagram:: IPython.lib.pretty
- :parts: 3
-
-:copyright: 2007 by Armin Ronacher.
- Portions (c) 2009 by Robert Kern.
-:license: BSD License.
-"""
-from __future__ import print_function
-from contextlib import contextmanager
-import sys
-import types
-import re
-import datetime
-from collections import deque
-
+# -*- coding: utf-8 -*-
+"""
+Python advanced pretty printer. This pretty printer is intended to
+replace the old `pprint` python module which does not allow developers
+to provide their own pretty print callbacks.
+
+This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
+
+
+Example Usage
+-------------
+
+To directly print the representation of an object use `pprint`::
+
+ from pretty import pprint
+ pprint(complex_object)
+
+To get a string of the output use `pretty`::
+
+ from pretty import pretty
+ string = pretty(complex_object)
+
+
+Extending
+---------
+
+The pretty library allows developers to add pretty printing rules for their
+own objects. This process is straightforward. All you have to do is to
+add a `_repr_pretty_` method to your object and call the methods on the
+pretty printer passed::
+
+ class MyObject(object):
+
+ def _repr_pretty_(self, p, cycle):
+ ...
+
+Here is an example implementation of a `_repr_pretty_` method for a list
+subclass::
+
+ class MyList(list):
+
+ def _repr_pretty_(self, p, cycle):
+ if cycle:
+ p.text('MyList(...)')
+ else:
+ with p.group(8, 'MyList([', '])'):
+ for idx, item in enumerate(self):
+ if idx:
+ p.text(',')
+ p.breakable()
+ p.pretty(item)
+
+The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
+react to that or the result is an infinite loop. `p.text()` just adds
+non breaking text to the output, `p.breakable()` either adds a whitespace
+or breaks here. If you pass it an argument it's used instead of the
+default space. `p.pretty` prettyprints another object using the pretty print
+method.
+
+The first parameter to the `group` function specifies the extra indentation
+of the next line. In this example the next item will either be on the same
+line (if the items are short enough) or aligned with the right edge of the
+opening bracket of `MyList`.
+
+If you just want to indent something you can use the group function
+without open / close parameters. You can also use this code::
+
+ with p.indent(2):
+ ...
+
+Inheritance diagram:
+
+.. inheritance-diagram:: IPython.lib.pretty
+ :parts: 3
+
+:copyright: 2007 by Armin Ronacher.
+ Portions (c) 2009 by Robert Kern.
+:license: BSD License.
+"""
+from __future__ import print_function
+from contextlib import contextmanager
+import sys
+import types
+import re
+import datetime
+from collections import deque
+
from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types
-from IPython.utils.encoding import get_stream_enc
-
-from io import StringIO
-
-
-__all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
- 'for_type', 'for_type_by_name']
-
-
-MAX_SEQ_LENGTH = 1000
+from IPython.utils.encoding import get_stream_enc
+
+from io import StringIO
+
+
+__all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
+ 'for_type', 'for_type_by_name']
+
+
+MAX_SEQ_LENGTH = 1000
# The language spec says that dicts preserve order from 3.7, but CPython
# does so from 3.6, so it seems likely that people will expect that.
DICT_IS_ORDERED = sys.version_info >= (3, 6)
-_re_pattern_type = type(re.compile(''))
-
-def _safe_getattr(obj, attr, default=None):
- """Safe version of getattr.
-
- Same as getattr, but will return ``default`` on any Exception,
- rather than raising.
- """
- try:
- return getattr(obj, attr, default)
- except Exception:
- return default
-
-if PY3:
- CUnicodeIO = StringIO
-else:
- class CUnicodeIO(StringIO):
- """StringIO that casts str to unicode on Python 2"""
- def write(self, text):
- return super(CUnicodeIO, self).write(
- cast_unicode(text, encoding=get_stream_enc(sys.stdout)))
-
-
+_re_pattern_type = type(re.compile(''))
+
+def _safe_getattr(obj, attr, default=None):
+ """Safe version of getattr.
+
+ Same as getattr, but will return ``default`` on any Exception,
+ rather than raising.
+ """
+ try:
+ return getattr(obj, attr, default)
+ except Exception:
+ return default
+
+if PY3:
+ CUnicodeIO = StringIO
+else:
+ class CUnicodeIO(StringIO):
+ """StringIO that casts str to unicode on Python 2"""
+ def write(self, text):
+ return super(CUnicodeIO, self).write(
+ cast_unicode(text, encoding=get_stream_enc(sys.stdout)))
+
+
def _sorted_for_pprint(items):
"""
Sort the given items for pretty printing. Since some predictable
@@ -137,734 +137,734 @@ def _sorted_for_pprint(items):
except Exception:
return items
-def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
- """
- Pretty print the object's representation.
- """
- stream = CUnicodeIO()
- printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
- printer.pretty(obj)
- printer.flush()
- return stream.getvalue()
-
-
-def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
- """
- Like `pretty` but print to stdout.
- """
- printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
- printer.pretty(obj)
- printer.flush()
- sys.stdout.write(newline)
- sys.stdout.flush()
-
-class _PrettyPrinterBase(object):
-
- @contextmanager
- def indent(self, indent):
- """with statement support for indenting/dedenting."""
- self.indentation += indent
- try:
- yield
- finally:
- self.indentation -= indent
-
- @contextmanager
- def group(self, indent=0, open='', close=''):
- """like begin_group / end_group but for the with statement."""
- self.begin_group(indent, open)
- try:
- yield
- finally:
- self.end_group(indent, close)
-
-class PrettyPrinter(_PrettyPrinterBase):
- """
- Baseclass for the `RepresentationPrinter` prettyprinter that is used to
- generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
- this printer knows nothing about the default pprinters or the `_repr_pretty_`
- callback method.
- """
-
- def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
- self.output = output
- self.max_width = max_width
- self.newline = newline
- self.max_seq_length = max_seq_length
- self.output_width = 0
- self.buffer_width = 0
- self.buffer = deque()
-
- root_group = Group(0)
- self.group_stack = [root_group]
- self.group_queue = GroupQueue(root_group)
- self.indentation = 0
-
- def _break_outer_groups(self):
- while self.max_width < self.output_width + self.buffer_width:
- group = self.group_queue.deq()
- if not group:
- return
- while group.breakables:
- x = self.buffer.popleft()
- self.output_width = x.output(self.output, self.output_width)
- self.buffer_width -= x.width
- while self.buffer and isinstance(self.buffer[0], Text):
- x = self.buffer.popleft()
- self.output_width = x.output(self.output, self.output_width)
- self.buffer_width -= x.width
-
- def text(self, obj):
- """Add literal text to the output."""
- width = len(obj)
- if self.buffer:
- text = self.buffer[-1]
- if not isinstance(text, Text):
- text = Text()
- self.buffer.append(text)
- text.add(obj, width)
- self.buffer_width += width
- self._break_outer_groups()
- else:
- self.output.write(obj)
- self.output_width += width
-
- def breakable(self, sep=' '):
- """
- Add a breakable separator to the output. This does not mean that it
- will automatically break here. If no breaking on this position takes
- place the `sep` is inserted which default to one space.
- """
- width = len(sep)
- group = self.group_stack[-1]
- if group.want_break:
- self.flush()
- self.output.write(self.newline)
- self.output.write(' ' * self.indentation)
- self.output_width = self.indentation
- self.buffer_width = 0
- else:
- self.buffer.append(Breakable(sep, width, self))
- self.buffer_width += width
- self._break_outer_groups()
-
- def break_(self):
- """
- Explicitly insert a newline into the output, maintaining correct indentation.
- """
- self.flush()
- self.output.write(self.newline)
- self.output.write(' ' * self.indentation)
- self.output_width = self.indentation
- self.buffer_width = 0
-
-
- def begin_group(self, indent=0, open=''):
- """
- Begin a group. If you want support for python < 2.5 which doesn't has
- the with statement this is the preferred way:
-
- p.begin_group(1, '{')
- ...
- p.end_group(1, '}')
-
- The python 2.5 expression would be this:
-
- with p.group(1, '{', '}'):
- ...
-
- The first parameter specifies the indentation for the next line (usually
- the width of the opening text), the second the opening text. All
- parameters are optional.
- """
- if open:
- self.text(open)
- group = Group(self.group_stack[-1].depth + 1)
- self.group_stack.append(group)
- self.group_queue.enq(group)
- self.indentation += indent
-
- def _enumerate(self, seq):
- """like enumerate, but with an upper limit on the number of items"""
- for idx, x in enumerate(seq):
- if self.max_seq_length and idx >= self.max_seq_length:
- self.text(',')
- self.breakable()
- self.text('...')
- return
- yield idx, x
-
- def end_group(self, dedent=0, close=''):
- """End a group. See `begin_group` for more details."""
- self.indentation -= dedent
- group = self.group_stack.pop()
- if not group.breakables:
- self.group_queue.remove(group)
- if close:
- self.text(close)
-
- def flush(self):
- """Flush data that is left in the buffer."""
- for data in self.buffer:
- self.output_width += data.output(self.output, self.output_width)
- self.buffer.clear()
- self.buffer_width = 0
-
-
-def _get_mro(obj_class):
- """ Get a reasonable method resolution order of a class and its superclasses
- for both old-style and new-style classes.
- """
- if not hasattr(obj_class, '__mro__'):
- # Old-style class. Mix in object to make a fake new-style class.
- try:
- obj_class = type(obj_class.__name__, (obj_class, object), {})
- except TypeError:
- # Old-style extension type that does not descend from object.
- # FIXME: try to construct a more thorough MRO.
- mro = [obj_class]
- else:
- mro = obj_class.__mro__[1:-1]
- else:
- mro = obj_class.__mro__
- return mro
-
-
-class RepresentationPrinter(PrettyPrinter):
- """
- Special pretty printer that has a `pretty` method that calls the pretty
- printer for a python object.
-
- This class stores processing data on `self` so you must *never* use
- this class in a threaded environment. Always lock it or reinstanciate
- it.
-
- Instances also have a verbose flag callbacks can access to control their
- output. For example the default instance repr prints all attributes and
- methods that are not prefixed by an underscore if the printer is in
- verbose mode.
- """
-
- def __init__(self, output, verbose=False, max_width=79, newline='\n',
- singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
- max_seq_length=MAX_SEQ_LENGTH):
-
- PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
- self.verbose = verbose
- self.stack = []
- if singleton_pprinters is None:
- singleton_pprinters = _singleton_pprinters.copy()
- self.singleton_pprinters = singleton_pprinters
- if type_pprinters is None:
- type_pprinters = _type_pprinters.copy()
- self.type_pprinters = type_pprinters
- if deferred_pprinters is None:
- deferred_pprinters = _deferred_type_pprinters.copy()
- self.deferred_pprinters = deferred_pprinters
-
- def pretty(self, obj):
- """Pretty print the given object."""
- obj_id = id(obj)
- cycle = obj_id in self.stack
- self.stack.append(obj_id)
- self.begin_group()
- try:
- obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
- # First try to find registered singleton printers for the type.
- try:
- printer = self.singleton_pprinters[obj_id]
- except (TypeError, KeyError):
- pass
- else:
- return printer(obj, self, cycle)
- # Next walk the mro and check for either:
- # 1) a registered printer
- # 2) a _repr_pretty_ method
- for cls in _get_mro(obj_class):
- if cls in self.type_pprinters:
- # printer registered in self.type_pprinters
- return self.type_pprinters[cls](obj, self, cycle)
- else:
- # deferred printer
- printer = self._in_deferred_types(cls)
- if printer is not None:
- return printer(obj, self, cycle)
- else:
- # Finally look for special method names.
- # Some objects automatically create any requested
- # attribute. Try to ignore most of them by checking for
- # callability.
- if '_repr_pretty_' in cls.__dict__:
- meth = cls._repr_pretty_
- if callable(meth):
- return meth(obj, self, cycle)
+def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
+ """
+ Pretty print the object's representation.
+ """
+ stream = CUnicodeIO()
+ printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
+ printer.pretty(obj)
+ printer.flush()
+ return stream.getvalue()
+
+
+def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
+ """
+ Like `pretty` but print to stdout.
+ """
+ printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
+ printer.pretty(obj)
+ printer.flush()
+ sys.stdout.write(newline)
+ sys.stdout.flush()
+
+class _PrettyPrinterBase(object):
+
+ @contextmanager
+ def indent(self, indent):
+ """with statement support for indenting/dedenting."""
+ self.indentation += indent
+ try:
+ yield
+ finally:
+ self.indentation -= indent
+
+ @contextmanager
+ def group(self, indent=0, open='', close=''):
+ """like begin_group / end_group but for the with statement."""
+ self.begin_group(indent, open)
+ try:
+ yield
+ finally:
+ self.end_group(indent, close)
+
+class PrettyPrinter(_PrettyPrinterBase):
+ """
+ Baseclass for the `RepresentationPrinter` prettyprinter that is used to
+ generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
+ this printer knows nothing about the default pprinters or the `_repr_pretty_`
+ callback method.
+ """
+
+ def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
+ self.output = output
+ self.max_width = max_width
+ self.newline = newline
+ self.max_seq_length = max_seq_length
+ self.output_width = 0
+ self.buffer_width = 0
+ self.buffer = deque()
+
+ root_group = Group(0)
+ self.group_stack = [root_group]
+ self.group_queue = GroupQueue(root_group)
+ self.indentation = 0
+
+ def _break_outer_groups(self):
+ while self.max_width < self.output_width + self.buffer_width:
+ group = self.group_queue.deq()
+ if not group:
+ return
+ while group.breakables:
+ x = self.buffer.popleft()
+ self.output_width = x.output(self.output, self.output_width)
+ self.buffer_width -= x.width
+ while self.buffer and isinstance(self.buffer[0], Text):
+ x = self.buffer.popleft()
+ self.output_width = x.output(self.output, self.output_width)
+ self.buffer_width -= x.width
+
+ def text(self, obj):
+ """Add literal text to the output."""
+ width = len(obj)
+ if self.buffer:
+ text = self.buffer[-1]
+ if not isinstance(text, Text):
+ text = Text()
+ self.buffer.append(text)
+ text.add(obj, width)
+ self.buffer_width += width
+ self._break_outer_groups()
+ else:
+ self.output.write(obj)
+ self.output_width += width
+
+ def breakable(self, sep=' '):
+ """
+ Add a breakable separator to the output. This does not mean that it
+ will automatically break here. If no breaking on this position takes
+ place the `sep` is inserted which default to one space.
+ """
+ width = len(sep)
+ group = self.group_stack[-1]
+ if group.want_break:
+ self.flush()
+ self.output.write(self.newline)
+ self.output.write(' ' * self.indentation)
+ self.output_width = self.indentation
+ self.buffer_width = 0
+ else:
+ self.buffer.append(Breakable(sep, width, self))
+ self.buffer_width += width
+ self._break_outer_groups()
+
+ def break_(self):
+ """
+ Explicitly insert a newline into the output, maintaining correct indentation.
+ """
+ self.flush()
+ self.output.write(self.newline)
+ self.output.write(' ' * self.indentation)
+ self.output_width = self.indentation
+ self.buffer_width = 0
+
+
+ def begin_group(self, indent=0, open=''):
+ """
+ Begin a group. If you want support for python < 2.5 which doesn't has
+ the with statement this is the preferred way:
+
+ p.begin_group(1, '{')
+ ...
+ p.end_group(1, '}')
+
+ The python 2.5 expression would be this:
+
+ with p.group(1, '{', '}'):
+ ...
+
+ The first parameter specifies the indentation for the next line (usually
+ the width of the opening text), the second the opening text. All
+ parameters are optional.
+ """
+ if open:
+ self.text(open)
+ group = Group(self.group_stack[-1].depth + 1)
+ self.group_stack.append(group)
+ self.group_queue.enq(group)
+ self.indentation += indent
+
+ def _enumerate(self, seq):
+ """like enumerate, but with an upper limit on the number of items"""
+ for idx, x in enumerate(seq):
+ if self.max_seq_length and idx >= self.max_seq_length:
+ self.text(',')
+ self.breakable()
+ self.text('...')
+ return
+ yield idx, x
+
+ def end_group(self, dedent=0, close=''):
+ """End a group. See `begin_group` for more details."""
+ self.indentation -= dedent
+ group = self.group_stack.pop()
+ if not group.breakables:
+ self.group_queue.remove(group)
+ if close:
+ self.text(close)
+
+ def flush(self):
+ """Flush data that is left in the buffer."""
+ for data in self.buffer:
+ self.output_width += data.output(self.output, self.output_width)
+ self.buffer.clear()
+ self.buffer_width = 0
+
+
+def _get_mro(obj_class):
+ """ Get a reasonable method resolution order of a class and its superclasses
+ for both old-style and new-style classes.
+ """
+ if not hasattr(obj_class, '__mro__'):
+ # Old-style class. Mix in object to make a fake new-style class.
+ try:
+ obj_class = type(obj_class.__name__, (obj_class, object), {})
+ except TypeError:
+ # Old-style extension type that does not descend from object.
+ # FIXME: try to construct a more thorough MRO.
+ mro = [obj_class]
+ else:
+ mro = obj_class.__mro__[1:-1]
+ else:
+ mro = obj_class.__mro__
+ return mro
+
+
+class RepresentationPrinter(PrettyPrinter):
+ """
+ Special pretty printer that has a `pretty` method that calls the pretty
+ printer for a python object.
+
+ This class stores processing data on `self` so you must *never* use
+ this class in a threaded environment. Always lock it or reinstanciate
+ it.
+
+ Instances also have a verbose flag callbacks can access to control their
+ output. For example the default instance repr prints all attributes and
+ methods that are not prefixed by an underscore if the printer is in
+ verbose mode.
+ """
+
+ def __init__(self, output, verbose=False, max_width=79, newline='\n',
+ singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
+ max_seq_length=MAX_SEQ_LENGTH):
+
+ PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
+ self.verbose = verbose
+ self.stack = []
+ if singleton_pprinters is None:
+ singleton_pprinters = _singleton_pprinters.copy()
+ self.singleton_pprinters = singleton_pprinters
+ if type_pprinters is None:
+ type_pprinters = _type_pprinters.copy()
+ self.type_pprinters = type_pprinters
+ if deferred_pprinters is None:
+ deferred_pprinters = _deferred_type_pprinters.copy()
+ self.deferred_pprinters = deferred_pprinters
+
+ def pretty(self, obj):
+ """Pretty print the given object."""
+ obj_id = id(obj)
+ cycle = obj_id in self.stack
+ self.stack.append(obj_id)
+ self.begin_group()
+ try:
+ obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
+ # First try to find registered singleton printers for the type.
+ try:
+ printer = self.singleton_pprinters[obj_id]
+ except (TypeError, KeyError):
+ pass
+ else:
+ return printer(obj, self, cycle)
+ # Next walk the mro and check for either:
+ # 1) a registered printer
+ # 2) a _repr_pretty_ method
+ for cls in _get_mro(obj_class):
+ if cls in self.type_pprinters:
+ # printer registered in self.type_pprinters
+ return self.type_pprinters[cls](obj, self, cycle)
+ else:
+ # deferred printer
+ printer = self._in_deferred_types(cls)
+ if printer is not None:
+ return printer(obj, self, cycle)
+ else:
+ # Finally look for special method names.
+ # Some objects automatically create any requested
+ # attribute. Try to ignore most of them by checking for
+ # callability.
+ if '_repr_pretty_' in cls.__dict__:
+ meth = cls._repr_pretty_
+ if callable(meth):
+ return meth(obj, self, cycle)
if cls is not object \
and callable(cls.__dict__.get('__repr__')):
return _repr_pprint(obj, self, cycle)
- return _default_pprint(obj, self, cycle)
- finally:
- self.end_group()
- self.stack.pop()
-
- def _in_deferred_types(self, cls):
- """
- Check if the given class is specified in the deferred type registry.
-
- Returns the printer from the registry if it exists, and None if the
- class is not in the registry. Successful matches will be moved to the
- regular type registry for future use.
- """
- mod = _safe_getattr(cls, '__module__', None)
- name = _safe_getattr(cls, '__name__', None)
- key = (mod, name)
- printer = None
- if key in self.deferred_pprinters:
- # Move the printer over to the regular registry.
- printer = self.deferred_pprinters.pop(key)
- self.type_pprinters[cls] = printer
- return printer
-
-
-class Printable(object):
-
- def output(self, stream, output_width):
- return output_width
-
-
-class Text(Printable):
-
- def __init__(self):
- self.objs = []
- self.width = 0
-
- def output(self, stream, output_width):
- for obj in self.objs:
- stream.write(obj)
- return output_width + self.width
-
- def add(self, obj, width):
- self.objs.append(obj)
- self.width += width
-
-
-class Breakable(Printable):
-
- def __init__(self, seq, width, pretty):
- self.obj = seq
- self.width = width
- self.pretty = pretty
- self.indentation = pretty.indentation
- self.group = pretty.group_stack[-1]
- self.group.breakables.append(self)
-
- def output(self, stream, output_width):
- self.group.breakables.popleft()
- if self.group.want_break:
- stream.write(self.pretty.newline)
- stream.write(' ' * self.indentation)
- return self.indentation
- if not self.group.breakables:
- self.pretty.group_queue.remove(self.group)
- stream.write(self.obj)
- return output_width + self.width
-
-
-class Group(Printable):
-
- def __init__(self, depth):
- self.depth = depth
- self.breakables = deque()
- self.want_break = False
-
-
-class GroupQueue(object):
-
- def __init__(self, *groups):
- self.queue = []
- for group in groups:
- self.enq(group)
-
- def enq(self, group):
- depth = group.depth
- while depth > len(self.queue) - 1:
- self.queue.append([])
- self.queue[depth].append(group)
-
- def deq(self):
- for stack in self.queue:
- for idx, group in enumerate(reversed(stack)):
- if group.breakables:
- del stack[idx]
- group.want_break = True
- return group
- for group in stack:
- group.want_break = True
- del stack[:]
-
- def remove(self, group):
- try:
- self.queue[group.depth].remove(group)
- except ValueError:
- pass
-
-try:
- _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
-except AttributeError: # Python 3
- _baseclass_reprs = (object.__repr__,)
-
-
-def _default_pprint(obj, p, cycle):
- """
- The default print function. Used if an object does not provide one and
- it's none of the builtin objects.
- """
- klass = _safe_getattr(obj, '__class__', None) or type(obj)
- if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
- # A user-provided repr. Find newlines and replace them with p.break_()
- _repr_pprint(obj, p, cycle)
- return
- p.begin_group(1, '<')
- p.pretty(klass)
- p.text(' at 0x%x' % id(obj))
- if cycle:
- p.text(' ...')
- elif p.verbose:
- first = True
- for key in dir(obj):
- if not key.startswith('_'):
- try:
- value = getattr(obj, key)
- except AttributeError:
- continue
- if isinstance(value, types.MethodType):
- continue
- if not first:
- p.text(',')
- p.breakable()
- p.text(key)
- p.text('=')
- step = len(key) + 1
- p.indentation += step
- p.pretty(value)
- p.indentation -= step
- first = False
- p.end_group(1, '>')
-
-
+ return _default_pprint(obj, self, cycle)
+ finally:
+ self.end_group()
+ self.stack.pop()
+
+ def _in_deferred_types(self, cls):
+ """
+ Check if the given class is specified in the deferred type registry.
+
+ Returns the printer from the registry if it exists, and None if the
+ class is not in the registry. Successful matches will be moved to the
+ regular type registry for future use.
+ """
+ mod = _safe_getattr(cls, '__module__', None)
+ name = _safe_getattr(cls, '__name__', None)
+ key = (mod, name)
+ printer = None
+ if key in self.deferred_pprinters:
+ # Move the printer over to the regular registry.
+ printer = self.deferred_pprinters.pop(key)
+ self.type_pprinters[cls] = printer
+ return printer
+
+
+class Printable(object):
+
+ def output(self, stream, output_width):
+ return output_width
+
+
+class Text(Printable):
+
+ def __init__(self):
+ self.objs = []
+ self.width = 0
+
+ def output(self, stream, output_width):
+ for obj in self.objs:
+ stream.write(obj)
+ return output_width + self.width
+
+ def add(self, obj, width):
+ self.objs.append(obj)
+ self.width += width
+
+
+class Breakable(Printable):
+
+ def __init__(self, seq, width, pretty):
+ self.obj = seq
+ self.width = width
+ self.pretty = pretty
+ self.indentation = pretty.indentation
+ self.group = pretty.group_stack[-1]
+ self.group.breakables.append(self)
+
+ def output(self, stream, output_width):
+ self.group.breakables.popleft()
+ if self.group.want_break:
+ stream.write(self.pretty.newline)
+ stream.write(' ' * self.indentation)
+ return self.indentation
+ if not self.group.breakables:
+ self.pretty.group_queue.remove(self.group)
+ stream.write(self.obj)
+ return output_width + self.width
+
+
+class Group(Printable):
+
+ def __init__(self, depth):
+ self.depth = depth
+ self.breakables = deque()
+ self.want_break = False
+
+
+class GroupQueue(object):
+
+ def __init__(self, *groups):
+ self.queue = []
+ for group in groups:
+ self.enq(group)
+
+ def enq(self, group):
+ depth = group.depth
+ while depth > len(self.queue) - 1:
+ self.queue.append([])
+ self.queue[depth].append(group)
+
+ def deq(self):
+ for stack in self.queue:
+ for idx, group in enumerate(reversed(stack)):
+ if group.breakables:
+ del stack[idx]
+ group.want_break = True
+ return group
+ for group in stack:
+ group.want_break = True
+ del stack[:]
+
+ def remove(self, group):
+ try:
+ self.queue[group.depth].remove(group)
+ except ValueError:
+ pass
+
+try:
+ _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
+except AttributeError: # Python 3
+ _baseclass_reprs = (object.__repr__,)
+
+
+def _default_pprint(obj, p, cycle):
+ """
+ The default print function. Used if an object does not provide one and
+ it's none of the builtin objects.
+ """
+ klass = _safe_getattr(obj, '__class__', None) or type(obj)
+ if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
+ # A user-provided repr. Find newlines and replace them with p.break_()
+ _repr_pprint(obj, p, cycle)
+ return
+ p.begin_group(1, '<')
+ p.pretty(klass)
+ p.text(' at 0x%x' % id(obj))
+ if cycle:
+ p.text(' ...')
+ elif p.verbose:
+ first = True
+ for key in dir(obj):
+ if not key.startswith('_'):
+ try:
+ value = getattr(obj, key)
+ except AttributeError:
+ continue
+ if isinstance(value, types.MethodType):
+ continue
+ if not first:
+ p.text(',')
+ p.breakable()
+ p.text(key)
+ p.text('=')
+ step = len(key) + 1
+ p.indentation += step
+ p.pretty(value)
+ p.indentation -= step
+ first = False
+ p.end_group(1, '>')
+
+
def _seq_pprinter_factory(start, end):
- """
- Factory that returns a pprint function useful for sequences. Used by
- the default pprint for tuples, dicts, and lists.
- """
- def inner(obj, p, cycle):
- if cycle:
- return p.text(start + '...' + end)
- step = len(start)
- p.begin_group(step, start)
- for idx, x in p._enumerate(obj):
- if idx:
- p.text(',')
- p.breakable()
- p.pretty(x)
- if len(obj) == 1 and type(obj) is tuple:
- # Special case for 1-item tuples.
- p.text(',')
- p.end_group(step, end)
- return inner
-
-
+ """
+ Factory that returns a pprint function useful for sequences. Used by
+ the default pprint for tuples, dicts, and lists.
+ """
+ def inner(obj, p, cycle):
+ if cycle:
+ return p.text(start + '...' + end)
+ step = len(start)
+ p.begin_group(step, start)
+ for idx, x in p._enumerate(obj):
+ if idx:
+ p.text(',')
+ p.breakable()
+ p.pretty(x)
+ if len(obj) == 1 and type(obj) is tuple:
+ # Special case for 1-item tuples.
+ p.text(',')
+ p.end_group(step, end)
+ return inner
+
+
def _set_pprinter_factory(start, end):
- """
- Factory that returns a pprint function useful for sets and frozensets.
- """
- def inner(obj, p, cycle):
- if cycle:
- return p.text(start + '...' + end)
- if len(obj) == 0:
- # Special case.
+ """
+ Factory that returns a pprint function useful for sets and frozensets.
+ """
+ def inner(obj, p, cycle):
+ if cycle:
+ return p.text(start + '...' + end)
+ if len(obj) == 0:
+ # Special case.
p.text(type(obj).__name__ + '()')
- else:
- step = len(start)
- p.begin_group(step, start)
- # Like dictionary keys, we will try to sort the items if there aren't too many
- if not (p.max_seq_length and len(obj) >= p.max_seq_length):
+ else:
+ step = len(start)
+ p.begin_group(step, start)
+ # Like dictionary keys, we will try to sort the items if there aren't too many
+ if not (p.max_seq_length and len(obj) >= p.max_seq_length):
items = _sorted_for_pprint(obj)
else:
items = obj
- for idx, x in p._enumerate(items):
- if idx:
- p.text(',')
- p.breakable()
- p.pretty(x)
- p.end_group(step, end)
- return inner
-
-
+ for idx, x in p._enumerate(items):
+ if idx:
+ p.text(',')
+ p.breakable()
+ p.pretty(x)
+ p.end_group(step, end)
+ return inner
+
+
def _dict_pprinter_factory(start, end):
- """
- Factory that returns a pprint function used by the default pprint of
- dicts and dict proxies.
- """
- def inner(obj, p, cycle):
- if cycle:
- return p.text('{...}')
+ """
+ Factory that returns a pprint function used by the default pprint of
+ dicts and dict proxies.
+ """
+ def inner(obj, p, cycle):
+ if cycle:
+ return p.text('{...}')
step = len(start)
p.begin_group(step, start)
- keys = obj.keys()
- # if dict isn't large enough to be truncated, sort keys before displaying
+ keys = obj.keys()
+ # if dict isn't large enough to be truncated, sort keys before displaying
# From Python 3.7, dicts preserve order by definition, so we don't sort.
if not DICT_IS_ORDERED \
and not (p.max_seq_length and len(obj) >= p.max_seq_length):
keys = _sorted_for_pprint(keys)
- for idx, key in p._enumerate(keys):
- if idx:
- p.text(',')
- p.breakable()
- p.pretty(key)
- p.text(': ')
- p.pretty(obj[key])
+ for idx, key in p._enumerate(keys):
+ if idx:
+ p.text(',')
+ p.breakable()
+ p.pretty(key)
+ p.text(': ')
+ p.pretty(obj[key])
p.end_group(step, end)
- return inner
-
-
-def _super_pprint(obj, p, cycle):
- """The pprint for the super type."""
- p.begin_group(8, '<super: ')
- p.pretty(obj.__thisclass__)
- p.text(',')
- p.breakable()
+ return inner
+
+
+def _super_pprint(obj, p, cycle):
+ """The pprint for the super type."""
+ p.begin_group(8, '<super: ')
+ p.pretty(obj.__thisclass__)
+ p.text(',')
+ p.breakable()
if PYPY: # In PyPy, super() objects don't have __self__ attributes
dself = obj.__repr__.__self__
p.pretty(None if dself is obj else dself)
else:
p.pretty(obj.__self__)
- p.end_group(8, '>')
-
-
-def _re_pattern_pprint(obj, p, cycle):
- """The pprint function for regular expression patterns."""
- p.text('re.compile(')
- pattern = repr(obj.pattern)
- if pattern[:1] in 'uU':
- pattern = pattern[1:]
- prefix = 'ur'
- else:
- prefix = 'r'
- pattern = prefix + pattern.replace('\\\\', '\\')
- p.text(pattern)
- if obj.flags:
- p.text(',')
- p.breakable()
- done_one = False
- for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
- 'UNICODE', 'VERBOSE', 'DEBUG'):
- if obj.flags & getattr(re, flag):
- if done_one:
- p.text('|')
- p.text('re.' + flag)
- done_one = True
- p.text(')')
-
-
-def _type_pprint(obj, p, cycle):
- """The pprint for classes and types."""
- # Heap allocated types might not have the module attribute,
- # and others may set it to None.
-
+ p.end_group(8, '>')
+
+
+def _re_pattern_pprint(obj, p, cycle):
+ """The pprint function for regular expression patterns."""
+ p.text('re.compile(')
+ pattern = repr(obj.pattern)
+ if pattern[:1] in 'uU':
+ pattern = pattern[1:]
+ prefix = 'ur'
+ else:
+ prefix = 'r'
+ pattern = prefix + pattern.replace('\\\\', '\\')
+ p.text(pattern)
+ if obj.flags:
+ p.text(',')
+ p.breakable()
+ done_one = False
+ for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
+ 'UNICODE', 'VERBOSE', 'DEBUG'):
+ if obj.flags & getattr(re, flag):
+ if done_one:
+ p.text('|')
+ p.text('re.' + flag)
+ done_one = True
+ p.text(')')
+
+
+def _type_pprint(obj, p, cycle):
+ """The pprint for classes and types."""
+ # Heap allocated types might not have the module attribute,
+ # and others may set it to None.
+
# Checks for a __repr__ override in the metaclass. Can't compare the
# type(obj).__repr__ directly because in PyPy the representation function
# inherited from type isn't the same type.__repr__
if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
- _repr_pprint(obj, p, cycle)
- return
-
- mod = _safe_getattr(obj, '__module__', None)
- try:
- name = obj.__qualname__
- if not isinstance(name, string_types):
- # This can happen if the type implements __qualname__ as a property
- # or other descriptor in Python 2.
- raise Exception("Try __name__")
- except Exception:
- name = obj.__name__
- if not isinstance(name, string_types):
- name = '<unknown type>'
-
- if mod in (None, '__builtin__', 'builtins', 'exceptions'):
- p.text(name)
- else:
- p.text(mod + '.' + name)
-
-
-def _repr_pprint(obj, p, cycle):
- """A pprint that just redirects to the normal repr function."""
- # Find newlines and replace them with p.break_()
- output = repr(obj)
- for idx,output_line in enumerate(output.splitlines()):
- if idx:
- p.break_()
- p.text(output_line)
-
-
-def _function_pprint(obj, p, cycle):
- """Base pprint for all functions and builtin functions."""
- name = _safe_getattr(obj, '__qualname__', obj.__name__)
- mod = obj.__module__
- if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
- name = mod + '.' + name
- p.text('<function %s>' % name)
-
-
-def _exception_pprint(obj, p, cycle):
- """Base pprint for all exceptions."""
- name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
- if obj.__class__.__module__ not in ('exceptions', 'builtins'):
- name = '%s.%s' % (obj.__class__.__module__, name)
- step = len(name) + 1
- p.begin_group(step, name + '(')
- for idx, arg in enumerate(getattr(obj, 'args', ())):
- if idx:
- p.text(',')
- p.breakable()
- p.pretty(arg)
- p.end_group(step, ')')
-
-
-#: the exception base
-try:
- _exception_base = BaseException
-except NameError:
- _exception_base = Exception
-
-
-#: printers for builtin types
-_type_pprinters = {
- int: _repr_pprint,
- float: _repr_pprint,
- str: _repr_pprint,
+ _repr_pprint(obj, p, cycle)
+ return
+
+ mod = _safe_getattr(obj, '__module__', None)
+ try:
+ name = obj.__qualname__
+ if not isinstance(name, string_types):
+ # This can happen if the type implements __qualname__ as a property
+ # or other descriptor in Python 2.
+ raise Exception("Try __name__")
+ except Exception:
+ name = obj.__name__
+ if not isinstance(name, string_types):
+ name = '<unknown type>'
+
+ if mod in (None, '__builtin__', 'builtins', 'exceptions'):
+ p.text(name)
+ else:
+ p.text(mod + '.' + name)
+
+
+def _repr_pprint(obj, p, cycle):
+ """A pprint that just redirects to the normal repr function."""
+ # Find newlines and replace them with p.break_()
+ output = repr(obj)
+ for idx,output_line in enumerate(output.splitlines()):
+ if idx:
+ p.break_()
+ p.text(output_line)
+
+
+def _function_pprint(obj, p, cycle):
+ """Base pprint for all functions and builtin functions."""
+ name = _safe_getattr(obj, '__qualname__', obj.__name__)
+ mod = obj.__module__
+ if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
+ name = mod + '.' + name
+ p.text('<function %s>' % name)
+
+
+def _exception_pprint(obj, p, cycle):
+ """Base pprint for all exceptions."""
+ name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
+ if obj.__class__.__module__ not in ('exceptions', 'builtins'):
+ name = '%s.%s' % (obj.__class__.__module__, name)
+ step = len(name) + 1
+ p.begin_group(step, name + '(')
+ for idx, arg in enumerate(getattr(obj, 'args', ())):
+ if idx:
+ p.text(',')
+ p.breakable()
+ p.pretty(arg)
+ p.end_group(step, ')')
+
+
+#: the exception base
+try:
+ _exception_base = BaseException
+except NameError:
+ _exception_base = Exception
+
+
+#: printers for builtin types
+_type_pprinters = {
+ int: _repr_pprint,
+ float: _repr_pprint,
+ str: _repr_pprint,
tuple: _seq_pprinter_factory('(', ')'),
list: _seq_pprinter_factory('[', ']'),
dict: _dict_pprinter_factory('{', '}'),
-
+
set: _set_pprinter_factory('{', '}'),
frozenset: _set_pprinter_factory('frozenset({', '})'),
- super: _super_pprint,
- _re_pattern_type: _re_pattern_pprint,
- type: _type_pprint,
- types.FunctionType: _function_pprint,
- types.BuiltinFunctionType: _function_pprint,
- types.MethodType: _repr_pprint,
-
- datetime.datetime: _repr_pprint,
- datetime.timedelta: _repr_pprint,
- _exception_base: _exception_pprint
-}
-
-try:
+ super: _super_pprint,
+ _re_pattern_type: _re_pattern_pprint,
+ type: _type_pprint,
+ types.FunctionType: _function_pprint,
+ types.BuiltinFunctionType: _function_pprint,
+ types.MethodType: _repr_pprint,
+
+ datetime.datetime: _repr_pprint,
+ datetime.timedelta: _repr_pprint,
+ _exception_base: _exception_pprint
+}
+
+try:
# In PyPy, types.DictProxyType is dict, setting the dictproxy printer
# using dict.setdefault avoids overwritting the dict printer
_type_pprinters.setdefault(types.DictProxyType,
_dict_pprinter_factory('dict_proxy({', '})'))
- _type_pprinters[types.ClassType] = _type_pprint
- _type_pprinters[types.SliceType] = _repr_pprint
-except AttributeError: # Python 3
+ _type_pprinters[types.ClassType] = _type_pprint
+ _type_pprinters[types.SliceType] = _repr_pprint
+except AttributeError: # Python 3
_type_pprinters[types.MappingProxyType] = \
_dict_pprinter_factory('mappingproxy({', '})')
- _type_pprinters[slice] = _repr_pprint
-
-try:
- _type_pprinters[xrange] = _repr_pprint
- _type_pprinters[long] = _repr_pprint
- _type_pprinters[unicode] = _repr_pprint
-except NameError:
- _type_pprinters[range] = _repr_pprint
- _type_pprinters[bytes] = _repr_pprint
-
-#: printers for types specified by name
-_deferred_type_pprinters = {
-}
-
-def for_type(typ, func):
- """
- Add a pretty printer for a given type.
- """
- oldfunc = _type_pprinters.get(typ, None)
- if func is not None:
- # To support easy restoration of old pprinters, we need to ignore Nones.
- _type_pprinters[typ] = func
- return oldfunc
-
-def for_type_by_name(type_module, type_name, func):
- """
- Add a pretty printer for a type specified by the module and name of a type
- rather than the type object itself.
- """
- key = (type_module, type_name)
- oldfunc = _deferred_type_pprinters.get(key, None)
- if func is not None:
- # To support easy restoration of old pprinters, we need to ignore Nones.
- _deferred_type_pprinters[key] = func
- return oldfunc
-
-
-#: printers for the default singletons
-_singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
- NotImplemented]), _repr_pprint)
-
-
-def _defaultdict_pprint(obj, p, cycle):
- name = obj.__class__.__name__
- with p.group(len(name) + 1, name + '(', ')'):
- if cycle:
- p.text('...')
- else:
- p.pretty(obj.default_factory)
- p.text(',')
- p.breakable()
- p.pretty(dict(obj))
-
-def _ordereddict_pprint(obj, p, cycle):
- name = obj.__class__.__name__
- with p.group(len(name) + 1, name + '(', ')'):
- if cycle:
- p.text('...')
- elif len(obj):
- p.pretty(list(obj.items()))
-
-def _deque_pprint(obj, p, cycle):
- name = obj.__class__.__name__
- with p.group(len(name) + 1, name + '(', ')'):
- if cycle:
- p.text('...')
- else:
- p.pretty(list(obj))
-
-
-def _counter_pprint(obj, p, cycle):
- name = obj.__class__.__name__
- with p.group(len(name) + 1, name + '(', ')'):
- if cycle:
- p.text('...')
- elif len(obj):
- p.pretty(dict(obj))
-
-for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
-for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
-for_type_by_name('collections', 'deque', _deque_pprint)
-for_type_by_name('collections', 'Counter', _counter_pprint)
-
-if __name__ == '__main__':
- from random import randrange
- class Foo(object):
- def __init__(self):
- self.foo = 1
- self.bar = re.compile(r'\s+')
- self.blub = dict.fromkeys(range(30), randrange(1, 40))
- self.hehe = 23424.234234
- self.list = ["blub", "blah", self]
-
- def get_foo(self):
- print("foo")
-
- pprint(Foo(), verbose=True)
+ _type_pprinters[slice] = _repr_pprint
+
+try:
+ _type_pprinters[xrange] = _repr_pprint
+ _type_pprinters[long] = _repr_pprint
+ _type_pprinters[unicode] = _repr_pprint
+except NameError:
+ _type_pprinters[range] = _repr_pprint
+ _type_pprinters[bytes] = _repr_pprint
+
+#: printers for types specified by name
+_deferred_type_pprinters = {
+}
+
+def for_type(typ, func):
+ """
+ Add a pretty printer for a given type.
+ """
+ oldfunc = _type_pprinters.get(typ, None)
+ if func is not None:
+ # To support easy restoration of old pprinters, we need to ignore Nones.
+ _type_pprinters[typ] = func
+ return oldfunc
+
+def for_type_by_name(type_module, type_name, func):
+ """
+ Add a pretty printer for a type specified by the module and name of a type
+ rather than the type object itself.
+ """
+ key = (type_module, type_name)
+ oldfunc = _deferred_type_pprinters.get(key, None)
+ if func is not None:
+ # To support easy restoration of old pprinters, we need to ignore Nones.
+ _deferred_type_pprinters[key] = func
+ return oldfunc
+
+
+#: printers for the default singletons
+_singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
+ NotImplemented]), _repr_pprint)
+
+
+def _defaultdict_pprint(obj, p, cycle):
+ name = obj.__class__.__name__
+ with p.group(len(name) + 1, name + '(', ')'):
+ if cycle:
+ p.text('...')
+ else:
+ p.pretty(obj.default_factory)
+ p.text(',')
+ p.breakable()
+ p.pretty(dict(obj))
+
+def _ordereddict_pprint(obj, p, cycle):
+ name = obj.__class__.__name__
+ with p.group(len(name) + 1, name + '(', ')'):
+ if cycle:
+ p.text('...')
+ elif len(obj):
+ p.pretty(list(obj.items()))
+
+def _deque_pprint(obj, p, cycle):
+ name = obj.__class__.__name__
+ with p.group(len(name) + 1, name + '(', ')'):
+ if cycle:
+ p.text('...')
+ else:
+ p.pretty(list(obj))
+
+
+def _counter_pprint(obj, p, cycle):
+ name = obj.__class__.__name__
+ with p.group(len(name) + 1, name + '(', ')'):
+ if cycle:
+ p.text('...')
+ elif len(obj):
+ p.pretty(dict(obj))
+
+for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
+for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
+for_type_by_name('collections', 'deque', _deque_pprint)
+for_type_by_name('collections', 'Counter', _counter_pprint)
+
+if __name__ == '__main__':
+ from random import randrange
+ class Foo(object):
+ def __init__(self):
+ self.foo = 1
+ self.bar = re.compile(r'\s+')
+ self.blub = dict.fromkeys(range(30), randrange(1, 40))
+ self.hehe = 23424.234234
+ self.list = ["blub", "blah", self]
+
+ def get_foo(self):
+ print("foo")
+
+ pprint(Foo(), verbose=True)
diff --git a/contrib/python/ipython/py2/IPython/lib/security.py b/contrib/python/ipython/py2/IPython/lib/security.py
index a20fcc132e..8429c2a4be 100644
--- a/contrib/python/ipython/py2/IPython/lib/security.py
+++ b/contrib/python/ipython/py2/IPython/lib/security.py
@@ -1,114 +1,114 @@
-"""
-Password generation for the IPython notebook.
-"""
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-# Stdlib
-import getpass
-import hashlib
-import random
-
-# Our own
-from IPython.core.error import UsageError
-from IPython.utils.py3compat import cast_bytes, str_to_bytes
-
-#-----------------------------------------------------------------------------
-# Globals
-#-----------------------------------------------------------------------------
-
-# Length of the salt in nr of hex chars, which implies salt_len * 4
-# bits of randomness.
-salt_len = 12
-
-#-----------------------------------------------------------------------------
-# Functions
-#-----------------------------------------------------------------------------
-
-def passwd(passphrase=None, algorithm='sha1'):
- """Generate hashed password and salt for use in notebook configuration.
-
- In the notebook configuration, set `c.NotebookApp.password` to
- the generated string.
-
- Parameters
- ----------
- passphrase : str
- Password to hash. If unspecified, the user is asked to input
- and verify a password.
- algorithm : str
- Hashing algorithm to use (e.g, 'sha1' or any argument supported
- by :func:`hashlib.new`).
-
- Returns
- -------
- hashed_passphrase : str
- Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'.
-
- Examples
- --------
- >>> passwd('mypassword')
- 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12'
-
- """
- if passphrase is None:
- for i in range(3):
- p0 = getpass.getpass('Enter password: ')
- p1 = getpass.getpass('Verify password: ')
- if p0 == p1:
- passphrase = p0
- break
- else:
- print('Passwords do not match.')
- else:
- raise UsageError('No matching passwords found. Giving up.')
-
- h = hashlib.new(algorithm)
- salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len)
- h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii'))
-
- return ':'.join((algorithm, salt, h.hexdigest()))
-
-
-def passwd_check(hashed_passphrase, passphrase):
- """Verify that a given passphrase matches its hashed version.
-
- Parameters
- ----------
- hashed_passphrase : str
- Hashed password, in the format returned by `passwd`.
- passphrase : str
- Passphrase to validate.
-
- Returns
- -------
- valid : bool
- True if the passphrase matches the hash.
-
- Examples
- --------
- >>> from IPython.lib.security import passwd_check
- >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a',
- ... 'mypassword')
- True
-
- >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a',
- ... 'anotherpassword')
- False
- """
- try:
- algorithm, salt, pw_digest = hashed_passphrase.split(':', 2)
- except (ValueError, TypeError):
- return False
-
- try:
- h = hashlib.new(algorithm)
- except ValueError:
- return False
-
- if len(pw_digest) == 0:
- return False
-
- h.update(cast_bytes(passphrase, 'utf-8') + cast_bytes(salt, 'ascii'))
-
- return h.hexdigest() == pw_digest
+"""
+Password generation for the IPython notebook.
+"""
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+# Stdlib
+import getpass
+import hashlib
+import random
+
+# Our own
+from IPython.core.error import UsageError
+from IPython.utils.py3compat import cast_bytes, str_to_bytes
+
+#-----------------------------------------------------------------------------
+# Globals
+#-----------------------------------------------------------------------------
+
+# Length of the salt in nr of hex chars, which implies salt_len * 4
+# bits of randomness.
+salt_len = 12
+
+#-----------------------------------------------------------------------------
+# Functions
+#-----------------------------------------------------------------------------
+
+def passwd(passphrase=None, algorithm='sha1'):
+ """Generate hashed password and salt for use in notebook configuration.
+
+ In the notebook configuration, set `c.NotebookApp.password` to
+ the generated string.
+
+ Parameters
+ ----------
+ passphrase : str
+ Password to hash. If unspecified, the user is asked to input
+ and verify a password.
+ algorithm : str
+ Hashing algorithm to use (e.g, 'sha1' or any argument supported
+ by :func:`hashlib.new`).
+
+ Returns
+ -------
+ hashed_passphrase : str
+ Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'.
+
+ Examples
+ --------
+ >>> passwd('mypassword')
+ 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12'
+
+ """
+ if passphrase is None:
+ for i in range(3):
+ p0 = getpass.getpass('Enter password: ')
+ p1 = getpass.getpass('Verify password: ')
+ if p0 == p1:
+ passphrase = p0
+ break
+ else:
+ print('Passwords do not match.')
+ else:
+ raise UsageError('No matching passwords found. Giving up.')
+
+ h = hashlib.new(algorithm)
+ salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len)
+ h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii'))
+
+ return ':'.join((algorithm, salt, h.hexdigest()))
+
+
+def passwd_check(hashed_passphrase, passphrase):
+ """Verify that a given passphrase matches its hashed version.
+
+ Parameters
+ ----------
+ hashed_passphrase : str
+ Hashed password, in the format returned by `passwd`.
+ passphrase : str
+ Passphrase to validate.
+
+ Returns
+ -------
+ valid : bool
+ True if the passphrase matches the hash.
+
+ Examples
+ --------
+ >>> from IPython.lib.security import passwd_check
+ >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a',
+ ... 'mypassword')
+ True
+
+ >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a',
+ ... 'anotherpassword')
+ False
+ """
+ try:
+ algorithm, salt, pw_digest = hashed_passphrase.split(':', 2)
+ except (ValueError, TypeError):
+ return False
+
+ try:
+ h = hashlib.new(algorithm)
+ except ValueError:
+ return False
+
+ if len(pw_digest) == 0:
+ return False
+
+ h.update(cast_bytes(passphrase, 'utf-8') + cast_bytes(salt, 'ascii'))
+
+ return h.hexdigest() == pw_digest
diff --git a/contrib/python/ipython/py2/IPython/nbconvert.py b/contrib/python/ipython/py2/IPython/nbconvert.py
index 3d0a6c5076..2de4ee50bc 100644
--- a/contrib/python/ipython/py2/IPython/nbconvert.py
+++ b/contrib/python/ipython/py2/IPython/nbconvert.py
@@ -1,19 +1,19 @@
-"""
-Shim to maintain backwards compatibility with old IPython.nbconvert imports.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import sys
-from warnings import warn
-
-from IPython.utils.shimmodule import ShimModule, ShimWarning
-
+"""
+Shim to maintain backwards compatibility with old IPython.nbconvert imports.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import sys
+from warnings import warn
+
+from IPython.utils.shimmodule import ShimModule, ShimWarning
+
warn("The `IPython.nbconvert` package has been deprecated since IPython 4.0. "
- "You should import from nbconvert instead.", ShimWarning)
-
-# Unconditionally insert the shim into sys.modules so that further import calls
-# trigger the custom attribute access above
-
-sys.modules['IPython.nbconvert'] = ShimModule(
- src='IPython.nbconvert', mirror='nbconvert')
+ "You should import from nbconvert instead.", ShimWarning)
+
+# Unconditionally insert the shim into sys.modules so that further import calls
+# trigger the custom attribute access above
+
+sys.modules['IPython.nbconvert'] = ShimModule(
+ src='IPython.nbconvert', mirror='nbconvert')
diff --git a/contrib/python/ipython/py2/IPython/nbformat.py b/contrib/python/ipython/py2/IPython/nbformat.py
index 2626d50e0c..310277de00 100644
--- a/contrib/python/ipython/py2/IPython/nbformat.py
+++ b/contrib/python/ipython/py2/IPython/nbformat.py
@@ -1,19 +1,19 @@
-"""
-Shim to maintain backwards compatibility with old IPython.nbformat imports.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import sys
-from warnings import warn
-
-from IPython.utils.shimmodule import ShimModule, ShimWarning
-
+"""
+Shim to maintain backwards compatibility with old IPython.nbformat imports.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import sys
+from warnings import warn
+
+from IPython.utils.shimmodule import ShimModule, ShimWarning
+
warn("The `IPython.nbformat` package has been deprecated since IPython 4.0. "
- "You should import from nbformat instead.", ShimWarning)
-
-# Unconditionally insert the shim into sys.modules so that further import calls
-# trigger the custom attribute access above
-
-sys.modules['IPython.nbformat'] = ShimModule(
- src='IPython.nbformat', mirror='nbformat')
+ "You should import from nbformat instead.", ShimWarning)
+
+# Unconditionally insert the shim into sys.modules so that further import calls
+# trigger the custom attribute access above
+
+sys.modules['IPython.nbformat'] = ShimModule(
+ src='IPython.nbformat', mirror='nbformat')
diff --git a/contrib/python/ipython/py2/IPython/parallel.py b/contrib/python/ipython/py2/IPython/parallel.py
index ea25050476..0f10012783 100644
--- a/contrib/python/ipython/py2/IPython/parallel.py
+++ b/contrib/python/ipython/py2/IPython/parallel.py
@@ -1,20 +1,20 @@
-"""
-Shim to maintain backwards compatibility with old IPython.parallel imports.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import sys
-from warnings import warn
-
-from IPython.utils.shimmodule import ShimModule, ShimWarning
-
+"""
+Shim to maintain backwards compatibility with old IPython.parallel imports.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import sys
+from warnings import warn
+
+from IPython.utils.shimmodule import ShimModule, ShimWarning
+
warn("The `IPython.parallel` package has been deprecated since IPython 4.0. "
- "You should import from ipyparallel instead.", ShimWarning)
-
-# Unconditionally insert the shim into sys.modules so that further import calls
-# trigger the custom attribute access above
-
-sys.modules['IPython.parallel'] = ShimModule(
- src='IPython.parallel', mirror='ipyparallel')
-
+ "You should import from ipyparallel instead.", ShimWarning)
+
+# Unconditionally insert the shim into sys.modules so that further import calls
+# trigger the custom attribute access above
+
+sys.modules['IPython.parallel'] = ShimModule(
+ src='IPython.parallel', mirror='ipyparallel')
+
diff --git a/contrib/python/ipython/py2/IPython/paths.py b/contrib/python/ipython/py2/IPython/paths.py
index d14f26c1fb..59787722a5 100644
--- a/contrib/python/ipython/py2/IPython/paths.py
+++ b/contrib/python/ipython/py2/IPython/paths.py
@@ -1,120 +1,120 @@
-"""Find files and directories which IPython uses.
-"""
-import os.path
-import shutil
-import tempfile
-from warnings import warn
-
-import IPython
-from IPython.utils.importstring import import_item
-from IPython.utils.path import (
- get_home_dir, get_xdg_dir, get_xdg_cache_dir, compress_user, _writable_dir,
- ensure_dir_exists, fs_encoding, filefind
-)
-from IPython.utils import py3compat
-
-def get_ipython_dir():
- """Get the IPython directory for this platform and user.
-
- This uses the logic in `get_home_dir` to find the home directory
- and then adds .ipython to the end of the path.
- """
-
- env = os.environ
- pjoin = os.path.join
-
-
- ipdir_def = '.ipython'
-
- home_dir = get_home_dir()
- xdg_dir = get_xdg_dir()
-
- # import pdb; pdb.set_trace() # dbg
- if 'IPYTHON_DIR' in env:
- warn('The environment variable IPYTHON_DIR is deprecated. '
- 'Please use IPYTHONDIR instead.')
- ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None))
- if ipdir is None:
- # not set explicitly, use ~/.ipython
- ipdir = pjoin(home_dir, ipdir_def)
- if xdg_dir:
- # Several IPython versions (up to 1.x) defaulted to .config/ipython
- # on Linux. We have decided to go back to using .ipython everywhere
- xdg_ipdir = pjoin(xdg_dir, 'ipython')
-
- if _writable_dir(xdg_ipdir):
- cu = compress_user
- if os.path.exists(ipdir):
- warn(('Ignoring {0} in favour of {1}. Remove {0} to '
- 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
- elif os.path.islink(xdg_ipdir):
- warn(('{0} is deprecated. Move link to {1} to '
- 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
- else:
- warn('Moving {0} to {1}'.format(cu(xdg_ipdir), cu(ipdir)))
- shutil.move(xdg_ipdir, ipdir)
-
- ipdir = os.path.normpath(os.path.expanduser(ipdir))
-
- if os.path.exists(ipdir) and not _writable_dir(ipdir):
- # ipdir exists, but is not writable
- warn("IPython dir '{0}' is not a writable location,"
- " using a temp directory.".format(ipdir))
- ipdir = tempfile.mkdtemp()
- elif not os.path.exists(ipdir):
- parent = os.path.dirname(ipdir)
- if not _writable_dir(parent):
- # ipdir does not exist and parent isn't writable
- warn("IPython parent '{0}' is not a writable location,"
- " using a temp directory.".format(parent))
- ipdir = tempfile.mkdtemp()
-
- return py3compat.cast_unicode(ipdir, fs_encoding)
-
-
-def get_ipython_cache_dir():
- """Get the cache directory it is created if it does not exist."""
- xdgdir = get_xdg_cache_dir()
- if xdgdir is None:
- return get_ipython_dir()
- ipdir = os.path.join(xdgdir, "ipython")
- if not os.path.exists(ipdir) and _writable_dir(xdgdir):
- ensure_dir_exists(ipdir)
- elif not _writable_dir(xdgdir):
- return get_ipython_dir()
-
- return py3compat.cast_unicode(ipdir, fs_encoding)
-
-
-def get_ipython_package_dir():
- """Get the base directory where IPython itself is installed."""
- ipdir = os.path.dirname(IPython.__file__)
- return py3compat.cast_unicode(ipdir, fs_encoding)
-
-
-def get_ipython_module_path(module_str):
- """Find the path to an IPython module in this version of IPython.
-
- This will always find the version of the module that is in this importable
- IPython package. This will always return the path to the ``.py``
- version of the module.
- """
- if module_str == 'IPython':
- return os.path.join(get_ipython_package_dir(), '__init__.py')
- mod = import_item(module_str)
- the_path = mod.__file__.replace('.pyc', '.py')
- the_path = the_path.replace('.pyo', '.py')
- return py3compat.cast_unicode(the_path, fs_encoding)
-
-def locate_profile(profile='default'):
- """Find the path to the folder associated with a given profile.
-
- I.e. find $IPYTHONDIR/profile_whatever.
- """
- from IPython.core.profiledir import ProfileDir, ProfileDirError
- try:
- pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
- except ProfileDirError:
- # IOError makes more sense when people are expecting a path
- raise IOError("Couldn't find profile %r" % profile)
- return pd.location
+"""Find files and directories which IPython uses.
+"""
+import os.path
+import shutil
+import tempfile
+from warnings import warn
+
+import IPython
+from IPython.utils.importstring import import_item
+from IPython.utils.path import (
+ get_home_dir, get_xdg_dir, get_xdg_cache_dir, compress_user, _writable_dir,
+ ensure_dir_exists, fs_encoding, filefind
+)
+from IPython.utils import py3compat
+
+def get_ipython_dir():
+ """Get the IPython directory for this platform and user.
+
+ This uses the logic in `get_home_dir` to find the home directory
+ and then adds .ipython to the end of the path.
+ """
+
+ env = os.environ
+ pjoin = os.path.join
+
+
+ ipdir_def = '.ipython'
+
+ home_dir = get_home_dir()
+ xdg_dir = get_xdg_dir()
+
+ # import pdb; pdb.set_trace() # dbg
+ if 'IPYTHON_DIR' in env:
+ warn('The environment variable IPYTHON_DIR is deprecated. '
+ 'Please use IPYTHONDIR instead.')
+ ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None))
+ if ipdir is None:
+ # not set explicitly, use ~/.ipython
+ ipdir = pjoin(home_dir, ipdir_def)
+ if xdg_dir:
+ # Several IPython versions (up to 1.x) defaulted to .config/ipython
+ # on Linux. We have decided to go back to using .ipython everywhere
+ xdg_ipdir = pjoin(xdg_dir, 'ipython')
+
+ if _writable_dir(xdg_ipdir):
+ cu = compress_user
+ if os.path.exists(ipdir):
+ warn(('Ignoring {0} in favour of {1}. Remove {0} to '
+ 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
+ elif os.path.islink(xdg_ipdir):
+ warn(('{0} is deprecated. Move link to {1} to '
+ 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
+ else:
+ warn('Moving {0} to {1}'.format(cu(xdg_ipdir), cu(ipdir)))
+ shutil.move(xdg_ipdir, ipdir)
+
+ ipdir = os.path.normpath(os.path.expanduser(ipdir))
+
+ if os.path.exists(ipdir) and not _writable_dir(ipdir):
+ # ipdir exists, but is not writable
+ warn("IPython dir '{0}' is not a writable location,"
+ " using a temp directory.".format(ipdir))
+ ipdir = tempfile.mkdtemp()
+ elif not os.path.exists(ipdir):
+ parent = os.path.dirname(ipdir)
+ if not _writable_dir(parent):
+ # ipdir does not exist and parent isn't writable
+ warn("IPython parent '{0}' is not a writable location,"
+ " using a temp directory.".format(parent))
+ ipdir = tempfile.mkdtemp()
+
+ return py3compat.cast_unicode(ipdir, fs_encoding)
+
+
+def get_ipython_cache_dir():
+ """Get the cache directory it is created if it does not exist."""
+ xdgdir = get_xdg_cache_dir()
+ if xdgdir is None:
+ return get_ipython_dir()
+ ipdir = os.path.join(xdgdir, "ipython")
+ if not os.path.exists(ipdir) and _writable_dir(xdgdir):
+ ensure_dir_exists(ipdir)
+ elif not _writable_dir(xdgdir):
+ return get_ipython_dir()
+
+ return py3compat.cast_unicode(ipdir, fs_encoding)
+
+
+def get_ipython_package_dir():
+ """Get the base directory where IPython itself is installed."""
+ ipdir = os.path.dirname(IPython.__file__)
+ return py3compat.cast_unicode(ipdir, fs_encoding)
+
+
+def get_ipython_module_path(module_str):
+ """Find the path to an IPython module in this version of IPython.
+
+ This will always find the version of the module that is in this importable
+ IPython package. This will always return the path to the ``.py``
+ version of the module.
+ """
+ if module_str == 'IPython':
+ return os.path.join(get_ipython_package_dir(), '__init__.py')
+ mod = import_item(module_str)
+ the_path = mod.__file__.replace('.pyc', '.py')
+ the_path = the_path.replace('.pyo', '.py')
+ return py3compat.cast_unicode(the_path, fs_encoding)
+
+def locate_profile(profile='default'):
+ """Find the path to the folder associated with a given profile.
+
+ I.e. find $IPYTHONDIR/profile_whatever.
+ """
+ from IPython.core.profiledir import ProfileDir, ProfileDirError
+ try:
+ pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
+ except ProfileDirError:
+ # IOError makes more sense when people are expecting a path
+ raise IOError("Couldn't find profile %r" % profile)
+ return pd.location
diff --git a/contrib/python/ipython/py2/IPython/qt.py b/contrib/python/ipython/py2/IPython/qt.py
index 9b032e271e..7557a3f329 100644
--- a/contrib/python/ipython/py2/IPython/qt.py
+++ b/contrib/python/ipython/py2/IPython/qt.py
@@ -1,24 +1,24 @@
-"""
-Shim to maintain backwards compatibility with old IPython.qt imports.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import sys
-from warnings import warn
-
-from IPython.utils.shimmodule import ShimModule, ShimWarning
-
+"""
+Shim to maintain backwards compatibility with old IPython.qt imports.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import sys
+from warnings import warn
+
+from IPython.utils.shimmodule import ShimModule, ShimWarning
+
warn("The `IPython.qt` package has been deprecated since IPython 4.0. "
- "You should import from qtconsole instead.", ShimWarning)
-
-# Unconditionally insert the shim into sys.modules so that further import calls
-# trigger the custom attribute access above
-
-_console = sys.modules['IPython.qt.console'] = ShimModule(
- src='IPython.qt.console', mirror='qtconsole')
-
-_qt = ShimModule(src='IPython.qt', mirror='qtconsole')
-
-_qt.console = _console
-sys.modules['IPython.qt'] = _qt
+ "You should import from qtconsole instead.", ShimWarning)
+
+# Unconditionally insert the shim into sys.modules so that further import calls
+# trigger the custom attribute access above
+
+_console = sys.modules['IPython.qt.console'] = ShimModule(
+ src='IPython.qt.console', mirror='qtconsole')
+
+_qt = ShimModule(src='IPython.qt', mirror='qtconsole')
+
+_qt.console = _console
+sys.modules['IPython.qt'] = _qt
diff --git a/contrib/python/ipython/py2/IPython/sphinxext/custom_doctests.py b/contrib/python/ipython/py2/IPython/sphinxext/custom_doctests.py
index 65d7051f4e..7678fd6801 100644
--- a/contrib/python/ipython/py2/IPython/sphinxext/custom_doctests.py
+++ b/contrib/python/ipython/py2/IPython/sphinxext/custom_doctests.py
@@ -1,155 +1,155 @@
-"""
-Handlers for IPythonDirective's @doctest pseudo-decorator.
-
-The Sphinx extension that provides support for embedded IPython code provides
-a pseudo-decorator @doctest, which treats the input/output block as a
-doctest, raising a RuntimeError during doc generation if the actual output
-(after running the input) does not match the expected output.
-
-An example usage is:
-
-.. code-block:: rst
-
- .. ipython::
-
- In [1]: x = 1
-
- @doctest
- In [2]: x + 2
- Out[3]: 3
-
-One can also provide arguments to the decorator. The first argument should be
-the name of a custom handler. The specification of any other arguments is
-determined by the handler. For example,
-
-.. code-block:: rst
-
- .. ipython::
-
- @doctest float
- In [154]: 0.1 + 0.2
- Out[154]: 0.3
-
-allows the actual output ``0.30000000000000004`` to match the expected output
-due to a comparison with `np.allclose`.
-
-This module contains handlers for the @doctest pseudo-decorator. Handlers
-should have the following function signature::
-
- handler(sphinx_shell, args, input_lines, found, submitted)
-
-where `sphinx_shell` is the embedded Sphinx shell, `args` contains the list
-of arguments that follow: '@doctest handler_name', `input_lines` contains
-a list of the lines relevant to the current doctest, `found` is a string
-containing the output from the IPython shell, and `submitted` is a string
-containing the expected output from the IPython shell.
-
-Handlers must be registered in the `doctests` dict at the end of this module.
-
-"""
-
-def str_to_array(s):
- """
- Simplistic converter of strings from repr to float NumPy arrays.
-
- If the repr representation has ellipsis in it, then this will fail.
-
- Parameters
- ----------
- s : str
- The repr version of a NumPy array.
-
- Examples
- --------
- >>> s = "array([ 0.3, inf, nan])"
- >>> a = str_to_array(s)
-
- """
- import numpy as np
-
- # Need to make sure eval() knows about inf and nan.
- # This also assumes default printoptions for NumPy.
- from numpy import inf, nan
-
- if s.startswith(u'array'):
- # Remove array( and )
- s = s[6:-1]
-
- if s.startswith(u'['):
- a = np.array(eval(s), dtype=float)
- else:
- # Assume its a regular float. Force 1D so we can index into it.
- a = np.atleast_1d(float(s))
- return a
-
-def float_doctest(sphinx_shell, args, input_lines, found, submitted):
- """
- Doctest which allow the submitted output to vary slightly from the input.
-
- Here is how it might appear in an rst file:
-
- .. code-block:: rst
-
- .. ipython::
-
- @doctest float
- In [1]: 0.1 + 0.2
- Out[1]: 0.3
-
- """
- import numpy as np
-
- if len(args) == 2:
- rtol = 1e-05
- atol = 1e-08
- else:
- # Both must be specified if any are specified.
- try:
- rtol = float(args[2])
- atol = float(args[3])
- except IndexError:
- e = ("Both `rtol` and `atol` must be specified "
- "if either are specified: {0}".format(args))
- raise IndexError(e)
-
- try:
- submitted = str_to_array(submitted)
- found = str_to_array(found)
- except:
- # For example, if the array is huge and there are ellipsis in it.
- error = True
- else:
- found_isnan = np.isnan(found)
- submitted_isnan = np.isnan(submitted)
- error = not np.allclose(found_isnan, submitted_isnan)
- error |= not np.allclose(found[~found_isnan],
- submitted[~submitted_isnan],
- rtol=rtol, atol=atol)
-
- TAB = ' ' * 4
- directive = sphinx_shell.directive
- if directive is None:
- source = 'Unavailable'
- content = 'Unavailable'
- else:
- source = directive.state.document.current_source
- # Add tabs and make into a single string.
- content = '\n'.join([TAB + line for line in directive.content])
-
- if error:
-
- e = ('doctest float comparison failure\n\n'
- 'Document source: {0}\n\n'
- 'Raw content: \n{1}\n\n'
- 'On input line(s):\n{TAB}{2}\n\n'
- 'we found output:\n{TAB}{3}\n\n'
- 'instead of the expected:\n{TAB}{4}\n\n')
- e = e.format(source, content, '\n'.join(input_lines), repr(found),
- repr(submitted), TAB=TAB)
- raise RuntimeError(e)
-
-# dict of allowable doctest handlers. The key represents the first argument
-# that must be given to @doctest in order to activate the handler.
-doctests = {
- 'float': float_doctest,
-}
+"""
+Handlers for IPythonDirective's @doctest pseudo-decorator.
+
+The Sphinx extension that provides support for embedded IPython code provides
+a pseudo-decorator @doctest, which treats the input/output block as a
+doctest, raising a RuntimeError during doc generation if the actual output
+(after running the input) does not match the expected output.
+
+An example usage is:
+
+.. code-block:: rst
+
+ .. ipython::
+
+ In [1]: x = 1
+
+ @doctest
+ In [2]: x + 2
+ Out[3]: 3
+
+One can also provide arguments to the decorator. The first argument should be
+the name of a custom handler. The specification of any other arguments is
+determined by the handler. For example,
+
+.. code-block:: rst
+
+ .. ipython::
+
+ @doctest float
+ In [154]: 0.1 + 0.2
+ Out[154]: 0.3
+
+allows the actual output ``0.30000000000000004`` to match the expected output
+due to a comparison with `np.allclose`.
+
+This module contains handlers for the @doctest pseudo-decorator. Handlers
+should have the following function signature::
+
+ handler(sphinx_shell, args, input_lines, found, submitted)
+
+where `sphinx_shell` is the embedded Sphinx shell, `args` contains the list
+of arguments that follow: '@doctest handler_name', `input_lines` contains
+a list of the lines relevant to the current doctest, `found` is a string
+containing the output from the IPython shell, and `submitted` is a string
+containing the expected output from the IPython shell.
+
+Handlers must be registered in the `doctests` dict at the end of this module.
+
+"""
+
+def str_to_array(s):
+ """
+ Simplistic converter of strings from repr to float NumPy arrays.
+
+ If the repr representation has ellipsis in it, then this will fail.
+
+ Parameters
+ ----------
+ s : str
+ The repr version of a NumPy array.
+
+ Examples
+ --------
+ >>> s = "array([ 0.3, inf, nan])"
+ >>> a = str_to_array(s)
+
+ """
+ import numpy as np
+
+ # Need to make sure eval() knows about inf and nan.
+ # This also assumes default printoptions for NumPy.
+ from numpy import inf, nan
+
+ if s.startswith(u'array'):
+ # Remove array( and )
+ s = s[6:-1]
+
+ if s.startswith(u'['):
+ a = np.array(eval(s), dtype=float)
+ else:
+ # Assume its a regular float. Force 1D so we can index into it.
+ a = np.atleast_1d(float(s))
+ return a
+
+def float_doctest(sphinx_shell, args, input_lines, found, submitted):
+ """
+ Doctest which allow the submitted output to vary slightly from the input.
+
+ Here is how it might appear in an rst file:
+
+ .. code-block:: rst
+
+ .. ipython::
+
+ @doctest float
+ In [1]: 0.1 + 0.2
+ Out[1]: 0.3
+
+ """
+ import numpy as np
+
+ if len(args) == 2:
+ rtol = 1e-05
+ atol = 1e-08
+ else:
+ # Both must be specified if any are specified.
+ try:
+ rtol = float(args[2])
+ atol = float(args[3])
+ except IndexError:
+ e = ("Both `rtol` and `atol` must be specified "
+ "if either are specified: {0}".format(args))
+ raise IndexError(e)
+
+ try:
+ submitted = str_to_array(submitted)
+ found = str_to_array(found)
+ except:
+ # For example, if the array is huge and there are ellipsis in it.
+ error = True
+ else:
+ found_isnan = np.isnan(found)
+ submitted_isnan = np.isnan(submitted)
+ error = not np.allclose(found_isnan, submitted_isnan)
+ error |= not np.allclose(found[~found_isnan],
+ submitted[~submitted_isnan],
+ rtol=rtol, atol=atol)
+
+ TAB = ' ' * 4
+ directive = sphinx_shell.directive
+ if directive is None:
+ source = 'Unavailable'
+ content = 'Unavailable'
+ else:
+ source = directive.state.document.current_source
+ # Add tabs and make into a single string.
+ content = '\n'.join([TAB + line for line in directive.content])
+
+ if error:
+
+ e = ('doctest float comparison failure\n\n'
+ 'Document source: {0}\n\n'
+ 'Raw content: \n{1}\n\n'
+ 'On input line(s):\n{TAB}{2}\n\n'
+ 'we found output:\n{TAB}{3}\n\n'
+ 'instead of the expected:\n{TAB}{4}\n\n')
+ e = e.format(source, content, '\n'.join(input_lines), repr(found),
+ repr(submitted), TAB=TAB)
+ raise RuntimeError(e)
+
+# dict of allowable doctest handlers. The key represents the first argument
+# that must be given to @doctest in order to activate the handler.
+doctests = {
+ 'float': float_doctest,
+}
diff --git a/contrib/python/ipython/py2/IPython/sphinxext/ipython_console_highlighting.py b/contrib/python/ipython/py2/IPython/sphinxext/ipython_console_highlighting.py
index bc64087797..b93a151fb3 100644
--- a/contrib/python/ipython/py2/IPython/sphinxext/ipython_console_highlighting.py
+++ b/contrib/python/ipython/py2/IPython/sphinxext/ipython_console_highlighting.py
@@ -1,28 +1,28 @@
-"""
-reST directive for syntax-highlighting ipython interactive sessions.
-
-"""
-
-from sphinx import highlighting
-from IPython.lib.lexers import IPyLexer
-
-def setup(app):
- """Setup as a sphinx extension."""
-
- # This is only a lexer, so adding it below to pygments appears sufficient.
- # But if somebody knows what the right API usage should be to do that via
- # sphinx, by all means fix it here. At least having this setup.py
- # suppresses the sphinx warning we'd get without it.
- metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
- return metadata
-
-# Register the extension as a valid pygments lexer.
-# Alternatively, we could register the lexer with pygments instead. This would
-# require using setuptools entrypoints: http://pygments.org/docs/plugins
-
-ipy2 = IPyLexer(python3=False)
-ipy3 = IPyLexer(python3=True)
-
-highlighting.lexers['ipython'] = ipy2
-highlighting.lexers['ipython2'] = ipy2
-highlighting.lexers['ipython3'] = ipy3
+"""
+reST directive for syntax-highlighting ipython interactive sessions.
+
+"""
+
+from sphinx import highlighting
+from IPython.lib.lexers import IPyLexer
+
+def setup(app):
+ """Setup as a sphinx extension."""
+
+ # This is only a lexer, so adding it below to pygments appears sufficient.
+ # But if somebody knows what the right API usage should be to do that via
+ # sphinx, by all means fix it here. At least having this setup.py
+ # suppresses the sphinx warning we'd get without it.
+ metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
+ return metadata
+
+# Register the extension as a valid pygments lexer.
+# Alternatively, we could register the lexer with pygments instead. This would
+# require using setuptools entrypoints: http://pygments.org/docs/plugins
+
+ipy2 = IPyLexer(python3=False)
+ipy3 = IPyLexer(python3=True)
+
+highlighting.lexers['ipython'] = ipy2
+highlighting.lexers['ipython2'] = ipy2
+highlighting.lexers['ipython3'] = ipy3
diff --git a/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py b/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py
index a9e9b65108..8df9ace1f3 100644
--- a/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py
+++ b/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py
@@ -1,1178 +1,1178 @@
-# -*- coding: utf-8 -*-
-"""
-Sphinx directive to support embedded IPython code.
-
-This directive allows pasting of entire interactive IPython sessions, prompts
-and all, and their code will actually get re-executed at doc build time, with
-all prompts renumbered sequentially. It also allows you to input code as a pure
-python input by giving the argument python to the directive. The output looks
-like an interactive ipython section.
-
-To enable this directive, simply list it in your Sphinx ``conf.py`` file
-(making sure the directory where you placed it is visible to sphinx, as is
-needed for all Sphinx directives). For example, to enable syntax highlighting
-and the IPython directive::
-
- extensions = ['IPython.sphinxext.ipython_console_highlighting',
- 'IPython.sphinxext.ipython_directive']
-
-The IPython directive outputs code-blocks with the language 'ipython'. So
-if you do not have the syntax highlighting extension enabled as well, then
-all rendered code-blocks will be uncolored. By default this directive assumes
-that your prompts are unchanged IPython ones, but this can be customized.
-The configurable options that can be placed in conf.py are:
-
-ipython_savefig_dir:
- The directory in which to save the figures. This is relative to the
- Sphinx source directory. The default is `html_static_path`.
-ipython_rgxin:
- The compiled regular expression to denote the start of IPython input
- lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You
- shouldn't need to change this.
-ipython_rgxout:
- The compiled regular expression to denote the start of IPython output
- lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You
- shouldn't need to change this.
-ipython_promptin:
- The string to represent the IPython input prompt in the generated ReST.
- The default is 'In [%d]:'. This expects that the line numbers are used
- in the prompt.
-ipython_promptout:
- The string to represent the IPython prompt in the generated ReST. The
- default is 'Out [%d]:'. This expects that the line numbers are used
- in the prompt.
-ipython_mplbackend:
- The string which specifies if the embedded Sphinx shell should import
- Matplotlib and set the backend. The value specifies a backend that is
- passed to `matplotlib.use()` before any lines in `ipython_execlines` are
- executed. If not specified in conf.py, then the default value of 'agg' is
- used. To use the IPython directive without matplotlib as a dependency, set
- the value to `None`. It may end up that matplotlib is still imported
- if the user specifies so in `ipython_execlines` or makes use of the
- @savefig pseudo decorator.
-ipython_execlines:
- A list of strings to be exec'd in the embedded Sphinx shell. Typical
- usage is to make certain packages always available. Set this to an empty
- list if you wish to have no imports always available. If specified in
- conf.py as `None`, then it has the effect of making no imports available.
- If omitted from conf.py altogether, then the default value of
- ['import numpy as np', 'import matplotlib.pyplot as plt'] is used.
-ipython_holdcount
- When the @suppress pseudo-decorator is used, the execution count can be
- incremented or not. The default behavior is to hold the execution count,
- corresponding to a value of `True`. Set this to `False` to increment
- the execution count after each suppressed command.
-
-As an example, to use the IPython directive when `matplotlib` is not available,
-one sets the backend to `None`::
-
- ipython_mplbackend = None
-
-An example usage of the directive is:
-
-.. code-block:: rst
-
- .. ipython::
-
- In [1]: x = 1
-
- In [2]: y = x**2
-
- In [3]: print(y)
-
-See http://matplotlib.org/sampledoc/ipython_directive.html for additional
-documentation.
-
-Pseudo-Decorators
-=================
-
-Note: Only one decorator is supported per input. If more than one decorator
-is specified, then only the last one is used.
-
-In addition to the Pseudo-Decorators/options described at the above link,
-several enhancements have been made. The directive will emit a message to the
-console at build-time if code-execution resulted in an exception or warning.
-You can suppress these on a per-block basis by specifying the :okexcept:
-or :okwarning: options:
-
-.. code-block:: rst
-
- .. ipython::
- :okexcept:
- :okwarning:
-
- In [1]: 1/0
- In [2]: # raise warning.
-
+# -*- coding: utf-8 -*-
+"""
+Sphinx directive to support embedded IPython code.
+
+This directive allows pasting of entire interactive IPython sessions, prompts
+and all, and their code will actually get re-executed at doc build time, with
+all prompts renumbered sequentially. It also allows you to input code as a pure
+python input by giving the argument python to the directive. The output looks
+like an interactive ipython section.
+
+To enable this directive, simply list it in your Sphinx ``conf.py`` file
+(making sure the directory where you placed it is visible to sphinx, as is
+needed for all Sphinx directives). For example, to enable syntax highlighting
+and the IPython directive::
+
+ extensions = ['IPython.sphinxext.ipython_console_highlighting',
+ 'IPython.sphinxext.ipython_directive']
+
+The IPython directive outputs code-blocks with the language 'ipython'. So
+if you do not have the syntax highlighting extension enabled as well, then
+all rendered code-blocks will be uncolored. By default this directive assumes
+that your prompts are unchanged IPython ones, but this can be customized.
+The configurable options that can be placed in conf.py are:
+
+ipython_savefig_dir:
+ The directory in which to save the figures. This is relative to the
+ Sphinx source directory. The default is `html_static_path`.
+ipython_rgxin:
+ The compiled regular expression to denote the start of IPython input
+ lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You
+ shouldn't need to change this.
+ipython_rgxout:
+ The compiled regular expression to denote the start of IPython output
+ lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You
+ shouldn't need to change this.
+ipython_promptin:
+ The string to represent the IPython input prompt in the generated ReST.
+ The default is 'In [%d]:'. This expects that the line numbers are used
+ in the prompt.
+ipython_promptout:
+ The string to represent the IPython prompt in the generated ReST. The
+ default is 'Out [%d]:'. This expects that the line numbers are used
+ in the prompt.
+ipython_mplbackend:
+ The string which specifies if the embedded Sphinx shell should import
+ Matplotlib and set the backend. The value specifies a backend that is
+ passed to `matplotlib.use()` before any lines in `ipython_execlines` are
+ executed. If not specified in conf.py, then the default value of 'agg' is
+ used. To use the IPython directive without matplotlib as a dependency, set
+ the value to `None`. It may end up that matplotlib is still imported
+ if the user specifies so in `ipython_execlines` or makes use of the
+ @savefig pseudo decorator.
+ipython_execlines:
+ A list of strings to be exec'd in the embedded Sphinx shell. Typical
+ usage is to make certain packages always available. Set this to an empty
+ list if you wish to have no imports always available. If specified in
+ conf.py as `None`, then it has the effect of making no imports available.
+ If omitted from conf.py altogether, then the default value of
+ ['import numpy as np', 'import matplotlib.pyplot as plt'] is used.
+ipython_holdcount
+ When the @suppress pseudo-decorator is used, the execution count can be
+ incremented or not. The default behavior is to hold the execution count,
+ corresponding to a value of `True`. Set this to `False` to increment
+ the execution count after each suppressed command.
+
+As an example, to use the IPython directive when `matplotlib` is not available,
+one sets the backend to `None`::
+
+ ipython_mplbackend = None
+
+An example usage of the directive is:
+
+.. code-block:: rst
+
+ .. ipython::
+
+ In [1]: x = 1
+
+ In [2]: y = x**2
+
+ In [3]: print(y)
+
+See http://matplotlib.org/sampledoc/ipython_directive.html for additional
+documentation.
+
+Pseudo-Decorators
+=================
+
+Note: Only one decorator is supported per input. If more than one decorator
+is specified, then only the last one is used.
+
+In addition to the Pseudo-Decorators/options described at the above link,
+several enhancements have been made. The directive will emit a message to the
+console at build-time if code-execution resulted in an exception or warning.
+You can suppress these on a per-block basis by specifying the :okexcept:
+or :okwarning: options:
+
+.. code-block:: rst
+
+ .. ipython::
+ :okexcept:
+ :okwarning:
+
+ In [1]: 1/0
+ In [2]: # raise warning.
+
To Do
-----
-
-- Turn the ad-hoc test() function into a real test suite.
-- Break up ipython-specific functionality from matplotlib stuff into better
- separated code.
-
-Authors
--------
-
-- John D Hunter: orignal author.
-- Fernando Perez: refactoring, documentation, cleanups, port to 0.11.
-- VáclavŠmilauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
-- Skipper Seabold, refactoring, cleanups, pure python addition
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Stdlib
-import atexit
+
+- Turn the ad-hoc test() function into a real test suite.
+- Break up ipython-specific functionality from matplotlib stuff into better
+ separated code.
+
+Authors
+-------
+
+- John D Hunter: orignal author.
+- Fernando Perez: refactoring, documentation, cleanups, port to 0.11.
+- VáclavŠmilauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
+- Skipper Seabold, refactoring, cleanups, pure python addition
+"""
+from __future__ import print_function
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Stdlib
+import atexit
import errno
-import os
-import re
-import sys
-import tempfile
-import ast
-import warnings
-import shutil
-
-
-# Third-party
-from docutils.parsers.rst import directives
+import os
+import re
+import sys
+import tempfile
+import ast
+import warnings
+import shutil
+
+
+# Third-party
+from docutils.parsers.rst import directives
from docutils.parsers.rst import Directive
-
-# Our own
-from traitlets.config import Config
-from IPython import InteractiveShell
-from IPython.core.profiledir import ProfileDir
-from IPython.utils import io
-from IPython.utils.py3compat import PY3
-
-if PY3:
- from io import StringIO
-else:
- from StringIO import StringIO
-
-#-----------------------------------------------------------------------------
-# Globals
-#-----------------------------------------------------------------------------
-# for tokenizing blocks
-COMMENT, INPUT, OUTPUT = range(3)
-
-#-----------------------------------------------------------------------------
-# Functions and class declarations
-#-----------------------------------------------------------------------------
-
-def block_parser(part, rgxin, rgxout, fmtin, fmtout):
- """
- part is a string of ipython text, comprised of at most one
- input, one output, comments, and blank lines. The block parser
- parses the text into a list of::
-
- blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]
-
- where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and
- data is, depending on the type of token::
-
- COMMENT : the comment string
-
- INPUT: the (DECORATOR, INPUT_LINE, REST) where
- DECORATOR: the input decorator (or None)
- INPUT_LINE: the input as string (possibly multi-line)
- REST : any stdout generated by the input line (not OUTPUT)
-
- OUTPUT: the output string, possibly multi-line
-
- """
- block = []
- lines = part.split('\n')
- N = len(lines)
- i = 0
- decorator = None
- while 1:
-
- if i==N:
- # nothing left to parse -- the last line
- break
-
- line = lines[i]
- i += 1
- line_stripped = line.strip()
- if line_stripped.startswith('#'):
- block.append((COMMENT, line))
- continue
-
- if line_stripped.startswith('@'):
- # Here is where we assume there is, at most, one decorator.
- # Might need to rethink this.
- decorator = line_stripped
- continue
-
- # does this look like an input line?
- matchin = rgxin.match(line)
- if matchin:
- lineno, inputline = int(matchin.group(1)), matchin.group(2)
-
- # the ....: continuation string
- continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
- Nc = len(continuation)
- # input lines can continue on for more than one line, if
- # we have a '\' line continuation char or a function call
- # echo line 'print'. The input line can only be
- # terminated by the end of the block or an output line, so
- # we parse out the rest of the input line if it is
- # multiline as well as any echo text
-
- rest = []
- while i<N:
-
- # look ahead; if the next line is blank, or a comment, or
- # an output line, we're done
-
- nextline = lines[i]
- matchout = rgxout.match(nextline)
- #print "nextline=%s, continuation=%s, starts=%s"%(nextline, continuation, nextline.startswith(continuation))
- if matchout or nextline.startswith('#'):
- break
- elif nextline.startswith(continuation):
- # The default ipython_rgx* treat the space following the colon as optional.
- # However, If the space is there we must consume it or code
- # employing the cython_magic extension will fail to execute.
- #
- # This works with the default ipython_rgx* patterns,
- # If you modify them, YMMV.
- nextline = nextline[Nc:]
- if nextline and nextline[0] == ' ':
- nextline = nextline[1:]
-
- inputline += '\n' + nextline
- else:
- rest.append(nextline)
- i+= 1
-
- block.append((INPUT, (decorator, inputline, '\n'.join(rest))))
- continue
-
- # if it looks like an output line grab all the text to the end
- # of the block
- matchout = rgxout.match(line)
- if matchout:
- lineno, output = int(matchout.group(1)), matchout.group(2)
- if i<N-1:
- output = '\n'.join([output] + lines[i:])
-
- block.append((OUTPUT, output))
- break
-
- return block
-
-
-class EmbeddedSphinxShell(object):
- """An embedded IPython instance to run inside Sphinx"""
-
- def __init__(self, exec_lines=None):
-
- self.cout = StringIO()
-
- if exec_lines is None:
- exec_lines = []
-
- # Create config object for IPython
- config = Config()
- config.HistoryManager.hist_file = ':memory:'
- config.InteractiveShell.autocall = False
- config.InteractiveShell.autoindent = False
- config.InteractiveShell.colors = 'NoColor'
-
- # create a profile so instance history isn't saved
- tmp_profile_dir = tempfile.mkdtemp(prefix='profile_')
- profname = 'auto_profile_sphinx_build'
- pdir = os.path.join(tmp_profile_dir,profname)
- profile = ProfileDir.create_profile_dir(pdir)
-
- # Create and initialize global ipython, but don't start its mainloop.
- # This will persist across different EmbededSphinxShell instances.
- IP = InteractiveShell.instance(config=config, profile_dir=profile)
- atexit.register(self.cleanup)
-
- # Store a few parts of IPython we'll need.
- self.IP = IP
- self.user_ns = self.IP.user_ns
- self.user_global_ns = self.IP.user_global_ns
-
- self.input = ''
- self.output = ''
- self.tmp_profile_dir = tmp_profile_dir
-
- self.is_verbatim = False
- self.is_doctest = False
- self.is_suppress = False
-
- # Optionally, provide more detailed information to shell.
- # this is assigned by the SetUp method of IPythonDirective
- # to point at itself.
- #
- # So, you can access handy things at self.directive.state
- self.directive = None
-
- # on the first call to the savefig decorator, we'll import
- # pyplot as plt so we can make a call to the plt.gcf().savefig
- self._pyplot_imported = False
-
- # Prepopulate the namespace.
- for line in exec_lines:
- self.process_input_line(line, store_history=False)
-
- def cleanup(self):
- shutil.rmtree(self.tmp_profile_dir, ignore_errors=True)
-
- def clear_cout(self):
- self.cout.seek(0)
- self.cout.truncate(0)
-
- def process_input_line(self, line, store_history=True):
- """process the input, capturing stdout"""
-
- stdout = sys.stdout
- splitter = self.IP.input_splitter
- try:
- sys.stdout = self.cout
- splitter.push(line)
- more = splitter.push_accepts_more()
- if not more:
- source_raw = splitter.raw_reset()
- self.IP.run_cell(source_raw, store_history=store_history)
- finally:
- sys.stdout = stdout
-
- def process_image(self, decorator):
- """
- # build out an image directive like
- # .. image:: somefile.png
- # :width 4in
- #
- # from an input like
- # savefig somefile.png width=4in
- """
- savefig_dir = self.savefig_dir
- source_dir = self.source_dir
- saveargs = decorator.split(' ')
- filename = saveargs[1]
+
+# Our own
+from traitlets.config import Config
+from IPython import InteractiveShell
+from IPython.core.profiledir import ProfileDir
+from IPython.utils import io
+from IPython.utils.py3compat import PY3
+
+if PY3:
+ from io import StringIO
+else:
+ from StringIO import StringIO
+
+#-----------------------------------------------------------------------------
+# Globals
+#-----------------------------------------------------------------------------
+# for tokenizing blocks
+COMMENT, INPUT, OUTPUT = range(3)
+
+#-----------------------------------------------------------------------------
+# Functions and class declarations
+#-----------------------------------------------------------------------------
+
+def block_parser(part, rgxin, rgxout, fmtin, fmtout):
+ """
+ part is a string of ipython text, comprised of at most one
+ input, one output, comments, and blank lines. The block parser
+ parses the text into a list of::
+
+ blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]
+
+ where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and
+ data is, depending on the type of token::
+
+ COMMENT : the comment string
+
+ INPUT: the (DECORATOR, INPUT_LINE, REST) where
+ DECORATOR: the input decorator (or None)
+ INPUT_LINE: the input as string (possibly multi-line)
+ REST : any stdout generated by the input line (not OUTPUT)
+
+ OUTPUT: the output string, possibly multi-line
+
+ """
+ block = []
+ lines = part.split('\n')
+ N = len(lines)
+ i = 0
+ decorator = None
+ while 1:
+
+ if i==N:
+ # nothing left to parse -- the last line
+ break
+
+ line = lines[i]
+ i += 1
+ line_stripped = line.strip()
+ if line_stripped.startswith('#'):
+ block.append((COMMENT, line))
+ continue
+
+ if line_stripped.startswith('@'):
+ # Here is where we assume there is, at most, one decorator.
+ # Might need to rethink this.
+ decorator = line_stripped
+ continue
+
+ # does this look like an input line?
+ matchin = rgxin.match(line)
+ if matchin:
+ lineno, inputline = int(matchin.group(1)), matchin.group(2)
+
+ # the ....: continuation string
+ continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
+ Nc = len(continuation)
+ # input lines can continue on for more than one line, if
+ # we have a '\' line continuation char or a function call
+ # echo line 'print'. The input line can only be
+ # terminated by the end of the block or an output line, so
+ # we parse out the rest of the input line if it is
+ # multiline as well as any echo text
+
+ rest = []
+ while i<N:
+
+ # look ahead; if the next line is blank, or a comment, or
+ # an output line, we're done
+
+ nextline = lines[i]
+ matchout = rgxout.match(nextline)
+ #print "nextline=%s, continuation=%s, starts=%s"%(nextline, continuation, nextline.startswith(continuation))
+ if matchout or nextline.startswith('#'):
+ break
+ elif nextline.startswith(continuation):
+ # The default ipython_rgx* treat the space following the colon as optional.
+ # However, If the space is there we must consume it or code
+ # employing the cython_magic extension will fail to execute.
+ #
+ # This works with the default ipython_rgx* patterns,
+ # If you modify them, YMMV.
+ nextline = nextline[Nc:]
+ if nextline and nextline[0] == ' ':
+ nextline = nextline[1:]
+
+ inputline += '\n' + nextline
+ else:
+ rest.append(nextline)
+ i+= 1
+
+ block.append((INPUT, (decorator, inputline, '\n'.join(rest))))
+ continue
+
+ # if it looks like an output line grab all the text to the end
+ # of the block
+ matchout = rgxout.match(line)
+ if matchout:
+ lineno, output = int(matchout.group(1)), matchout.group(2)
+ if i<N-1:
+ output = '\n'.join([output] + lines[i:])
+
+ block.append((OUTPUT, output))
+ break
+
+ return block
+
+
+class EmbeddedSphinxShell(object):
+ """An embedded IPython instance to run inside Sphinx"""
+
+ def __init__(self, exec_lines=None):
+
+ self.cout = StringIO()
+
+ if exec_lines is None:
+ exec_lines = []
+
+ # Create config object for IPython
+ config = Config()
+ config.HistoryManager.hist_file = ':memory:'
+ config.InteractiveShell.autocall = False
+ config.InteractiveShell.autoindent = False
+ config.InteractiveShell.colors = 'NoColor'
+
+ # create a profile so instance history isn't saved
+ tmp_profile_dir = tempfile.mkdtemp(prefix='profile_')
+ profname = 'auto_profile_sphinx_build'
+ pdir = os.path.join(tmp_profile_dir,profname)
+ profile = ProfileDir.create_profile_dir(pdir)
+
+ # Create and initialize global ipython, but don't start its mainloop.
+ # This will persist across different EmbededSphinxShell instances.
+ IP = InteractiveShell.instance(config=config, profile_dir=profile)
+ atexit.register(self.cleanup)
+
+ # Store a few parts of IPython we'll need.
+ self.IP = IP
+ self.user_ns = self.IP.user_ns
+ self.user_global_ns = self.IP.user_global_ns
+
+ self.input = ''
+ self.output = ''
+ self.tmp_profile_dir = tmp_profile_dir
+
+ self.is_verbatim = False
+ self.is_doctest = False
+ self.is_suppress = False
+
+ # Optionally, provide more detailed information to shell.
+ # this is assigned by the SetUp method of IPythonDirective
+ # to point at itself.
+ #
+ # So, you can access handy things at self.directive.state
+ self.directive = None
+
+ # on the first call to the savefig decorator, we'll import
+ # pyplot as plt so we can make a call to the plt.gcf().savefig
+ self._pyplot_imported = False
+
+ # Prepopulate the namespace.
+ for line in exec_lines:
+ self.process_input_line(line, store_history=False)
+
+ def cleanup(self):
+ shutil.rmtree(self.tmp_profile_dir, ignore_errors=True)
+
+ def clear_cout(self):
+ self.cout.seek(0)
+ self.cout.truncate(0)
+
+ def process_input_line(self, line, store_history=True):
+ """process the input, capturing stdout"""
+
+ stdout = sys.stdout
+ splitter = self.IP.input_splitter
+ try:
+ sys.stdout = self.cout
+ splitter.push(line)
+ more = splitter.push_accepts_more()
+ if not more:
+ source_raw = splitter.raw_reset()
+ self.IP.run_cell(source_raw, store_history=store_history)
+ finally:
+ sys.stdout = stdout
+
+ def process_image(self, decorator):
+ """
+ # build out an image directive like
+ # .. image:: somefile.png
+ # :width 4in
+ #
+ # from an input like
+ # savefig somefile.png width=4in
+ """
+ savefig_dir = self.savefig_dir
+ source_dir = self.source_dir
+ saveargs = decorator.split(' ')
+ filename = saveargs[1]
# insert relative path to image file in source (as absolute path for Sphinx)
outfile = '/' + os.path.relpath(os.path.join(savefig_dir,filename),
source_dir)
-
- imagerows = ['.. image:: %s'%outfile]
-
- for kwarg in saveargs[2:]:
- arg, val = kwarg.split('=')
- arg = arg.strip()
- val = val.strip()
- imagerows.append(' :%s: %s'%(arg, val))
-
- image_file = os.path.basename(outfile) # only return file name
- image_directive = '\n'.join(imagerows)
- return image_file, image_directive
-
- # Callbacks for each type of token
- def process_input(self, data, input_prompt, lineno):
- """
- Process data block for INPUT token.
-
- """
- decorator, input, rest = data
- image_file = None
- image_directive = None
-
- is_verbatim = decorator=='@verbatim' or self.is_verbatim
- is_doctest = (decorator is not None and \
- decorator.startswith('@doctest')) or self.is_doctest
- is_suppress = decorator=='@suppress' or self.is_suppress
- is_okexcept = decorator=='@okexcept' or self.is_okexcept
- is_okwarning = decorator=='@okwarning' or self.is_okwarning
- is_savefig = decorator is not None and \
- decorator.startswith('@savefig')
-
- input_lines = input.split('\n')
- if len(input_lines) > 1:
- if input_lines[-1] != "":
- input_lines.append('') # make sure there's a blank line
- # so splitter buffer gets reset
-
- continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
-
- if is_savefig:
- image_file, image_directive = self.process_image(decorator)
-
- ret = []
- is_semicolon = False
-
- # Hold the execution count, if requested to do so.
- if is_suppress and self.hold_count:
- store_history = False
- else:
- store_history = True
-
- # Note: catch_warnings is not thread safe
- with warnings.catch_warnings(record=True) as ws:
- for i, line in enumerate(input_lines):
- if line.endswith(';'):
- is_semicolon = True
-
- if i == 0:
- # process the first input line
- if is_verbatim:
- self.process_input_line('')
- self.IP.execution_count += 1 # increment it anyway
- else:
- # only submit the line in non-verbatim mode
- self.process_input_line(line, store_history=store_history)
- formatted_line = '%s %s'%(input_prompt, line)
- else:
- # process a continuation line
- if not is_verbatim:
- self.process_input_line(line, store_history=store_history)
-
- formatted_line = '%s %s'%(continuation, line)
-
- if not is_suppress:
- ret.append(formatted_line)
-
- if not is_suppress and len(rest.strip()) and is_verbatim:
- # The "rest" is the standard output of the input. This needs to be
- # added when in verbatim mode. If there is no "rest", then we don't
- # add it, as the new line will be added by the processed output.
- ret.append(rest)
-
- # Fetch the processed output. (This is not the submitted output.)
- self.cout.seek(0)
- processed_output = self.cout.read()
- if not is_suppress and not is_semicolon:
- #
- # In IPythonDirective.run, the elements of `ret` are eventually
- # combined such that '' entries correspond to newlines. So if
- # `processed_output` is equal to '', then the adding it to `ret`
- # ensures that there is a blank line between consecutive inputs
- # that have no outputs, as in:
- #
- # In [1]: x = 4
- #
- # In [2]: x = 5
- #
- # When there is processed output, it has a '\n' at the tail end. So
- # adding the output to `ret` will provide the necessary spacing
- # between consecutive input/output blocks, as in:
- #
- # In [1]: x
- # Out[1]: 5
- #
- # In [2]: x
- # Out[2]: 5
- #
- # When there is stdout from the input, it also has a '\n' at the
- # tail end, and so this ensures proper spacing as well. E.g.:
- #
- # In [1]: print x
- # 5
- #
- # In [2]: x = 5
- #
- # When in verbatim mode, `processed_output` is empty (because
- # nothing was passed to IP. Sometimes the submitted code block has
- # an Out[] portion and sometimes it does not. When it does not, we
- # need to ensure proper spacing, so we have to add '' to `ret`.
- # However, if there is an Out[] in the submitted code, then we do
- # not want to add a newline as `process_output` has stuff to add.
- # The difficulty is that `process_input` doesn't know if
- # `process_output` will be called---so it doesn't know if there is
- # Out[] in the code block. The requires that we include a hack in
- # `process_block`. See the comments there.
- #
- ret.append(processed_output)
- elif is_semicolon:
- # Make sure there is a newline after the semicolon.
- ret.append('')
-
- # context information
- filename = "Unknown"
- lineno = 0
- if self.directive.state:
- filename = self.directive.state.document.current_source
- lineno = self.directive.state.document.current_line
-
- # output any exceptions raised during execution to stdout
- # unless :okexcept: has been specified.
- if not is_okexcept and "Traceback" in processed_output:
- s = "\nException in %s at block ending on line %s\n" % (filename, lineno)
- s += "Specify :okexcept: as an option in the ipython:: block to suppress this message\n"
- sys.stdout.write('\n\n>>>' + ('-' * 73))
- sys.stdout.write(s)
- sys.stdout.write(processed_output)
- sys.stdout.write('<<<' + ('-' * 73) + '\n\n')
-
- # output any warning raised during execution to stdout
- # unless :okwarning: has been specified.
- if not is_okwarning:
- for w in ws:
- s = "\nWarning in %s at block ending on line %s\n" % (filename, lineno)
- s += "Specify :okwarning: as an option in the ipython:: block to suppress this message\n"
- sys.stdout.write('\n\n>>>' + ('-' * 73))
- sys.stdout.write(s)
- sys.stdout.write(('-' * 76) + '\n')
- s=warnings.formatwarning(w.message, w.category,
- w.filename, w.lineno, w.line)
- sys.stdout.write(s)
- sys.stdout.write('<<<' + ('-' * 73) + '\n')
-
- self.cout.truncate(0)
-
- return (ret, input_lines, processed_output,
- is_doctest, decorator, image_file, image_directive)
-
-
- def process_output(self, data, output_prompt, input_lines, output,
- is_doctest, decorator, image_file):
- """
- Process data block for OUTPUT token.
-
- """
- # Recall: `data` is the submitted output, and `output` is the processed
- # output from `input_lines`.
-
- TAB = ' ' * 4
-
- if is_doctest and output is not None:
-
- found = output # This is the processed output
- found = found.strip()
- submitted = data.strip()
-
- if self.directive is None:
- source = 'Unavailable'
- content = 'Unavailable'
- else:
- source = self.directive.state.document.current_source
- content = self.directive.content
- # Add tabs and join into a single string.
- content = '\n'.join([TAB + line for line in content])
-
- # Make sure the output contains the output prompt.
- ind = found.find(output_prompt)
- if ind < 0:
- e = ('output does not contain output prompt\n\n'
- 'Document source: {0}\n\n'
- 'Raw content: \n{1}\n\n'
- 'Input line(s):\n{TAB}{2}\n\n'
- 'Output line(s):\n{TAB}{3}\n\n')
- e = e.format(source, content, '\n'.join(input_lines),
- repr(found), TAB=TAB)
- raise RuntimeError(e)
- found = found[len(output_prompt):].strip()
-
- # Handle the actual doctest comparison.
- if decorator.strip() == '@doctest':
- # Standard doctest
- if found != submitted:
- e = ('doctest failure\n\n'
- 'Document source: {0}\n\n'
- 'Raw content: \n{1}\n\n'
- 'On input line(s):\n{TAB}{2}\n\n'
- 'we found output:\n{TAB}{3}\n\n'
- 'instead of the expected:\n{TAB}{4}\n\n')
- e = e.format(source, content, '\n'.join(input_lines),
- repr(found), repr(submitted), TAB=TAB)
- raise RuntimeError(e)
- else:
- self.custom_doctest(decorator, input_lines, found, submitted)
-
- # When in verbatim mode, this holds additional submitted output
- # to be written in the final Sphinx output.
- # https://github.com/ipython/ipython/issues/5776
- out_data = []
-
- is_verbatim = decorator=='@verbatim' or self.is_verbatim
- if is_verbatim and data.strip():
- # Note that `ret` in `process_block` has '' as its last element if
- # the code block was in verbatim mode. So if there is no submitted
- # output, then we will have proper spacing only if we do not add
- # an additional '' to `out_data`. This is why we condition on
- # `and data.strip()`.
-
- # The submitted output has no output prompt. If we want the
- # prompt and the code to appear, we need to join them now
- # instead of adding them separately---as this would create an
- # undesired newline. How we do this ultimately depends on the
- # format of the output regex. I'll do what works for the default
- # prompt for now, and we might have to adjust if it doesn't work
- # in other cases. Finally, the submitted output does not have
- # a trailing newline, so we must add it manually.
- out_data.append("{0} {1}\n".format(output_prompt, data))
-
- return out_data
-
- def process_comment(self, data):
- """Process data fPblock for COMMENT token."""
- if not self.is_suppress:
- return [data]
-
- def save_image(self, image_file):
- """
- Saves the image file to disk.
- """
- self.ensure_pyplot()
- command = 'plt.gcf().savefig("%s")'%image_file
- #print 'SAVEFIG', command # dbg
- self.process_input_line('bookmark ipy_thisdir', store_history=False)
- self.process_input_line('cd -b ipy_savedir', store_history=False)
- self.process_input_line(command, store_history=False)
- self.process_input_line('cd -b ipy_thisdir', store_history=False)
- self.process_input_line('bookmark -d ipy_thisdir', store_history=False)
- self.clear_cout()
-
- def process_block(self, block):
- """
- process block from the block_parser and return a list of processed lines
- """
- ret = []
- output = None
- input_lines = None
- lineno = self.IP.execution_count
-
- input_prompt = self.promptin % lineno
- output_prompt = self.promptout % lineno
- image_file = None
- image_directive = None
-
- found_input = False
- for token, data in block:
- if token == COMMENT:
- out_data = self.process_comment(data)
- elif token == INPUT:
- found_input = True
- (out_data, input_lines, output, is_doctest,
- decorator, image_file, image_directive) = \
- self.process_input(data, input_prompt, lineno)
- elif token == OUTPUT:
- if not found_input:
-
- TAB = ' ' * 4
- linenumber = 0
- source = 'Unavailable'
- content = 'Unavailable'
- if self.directive:
- linenumber = self.directive.state.document.current_line
- source = self.directive.state.document.current_source
- content = self.directive.content
- # Add tabs and join into a single string.
- content = '\n'.join([TAB + line for line in content])
-
- e = ('\n\nInvalid block: Block contains an output prompt '
- 'without an input prompt.\n\n'
- 'Document source: {0}\n\n'
- 'Content begins at line {1}: \n\n{2}\n\n'
- 'Problematic block within content: \n\n{TAB}{3}\n\n')
- e = e.format(source, linenumber, content, block, TAB=TAB)
-
- # Write, rather than include in exception, since Sphinx
- # will truncate tracebacks.
- sys.stdout.write(e)
- raise RuntimeError('An invalid block was detected.')
-
- out_data = \
- self.process_output(data, output_prompt, input_lines,
- output, is_doctest, decorator,
- image_file)
- if out_data:
- # Then there was user submitted output in verbatim mode.
- # We need to remove the last element of `ret` that was
- # added in `process_input`, as it is '' and would introduce
- # an undesirable newline.
- assert(ret[-1] == '')
- del ret[-1]
-
- if out_data:
- ret.extend(out_data)
-
- # save the image files
- if image_file is not None:
- self.save_image(image_file)
-
- return ret, image_directive
-
- def ensure_pyplot(self):
- """
- Ensures that pyplot has been imported into the embedded IPython shell.
-
- Also, makes sure to set the backend appropriately if not set already.
-
- """
- # We are here if the @figure pseudo decorator was used. Thus, it's
- # possible that we could be here even if python_mplbackend were set to
- # `None`. That's also strange and perhaps worthy of raising an
- # exception, but for now, we just set the backend to 'agg'.
-
- if not self._pyplot_imported:
- if 'matplotlib.backends' not in sys.modules:
- # Then ipython_matplotlib was set to None but there was a
- # call to the @figure decorator (and ipython_execlines did
- # not set a backend).
- #raise Exception("No backend was set, but @figure was used!")
- import matplotlib
- matplotlib.use('agg')
-
- # Always import pyplot into embedded shell.
- self.process_input_line('import matplotlib.pyplot as plt',
- store_history=False)
- self._pyplot_imported = True
-
- def process_pure_python(self, content):
- """
- content is a list of strings. it is unedited directive content
-
- This runs it line by line in the InteractiveShell, prepends
- prompts as needed capturing stderr and stdout, then returns
- the content as a list as if it were ipython code
- """
- output = []
- savefig = False # keep up with this to clear figure
- multiline = False # to handle line continuation
- multiline_start = None
- fmtin = self.promptin
-
- ct = 0
-
- for lineno, line in enumerate(content):
-
- line_stripped = line.strip()
- if not len(line):
- output.append(line)
- continue
-
- # handle decorators
- if line_stripped.startswith('@'):
- output.extend([line])
- if 'savefig' in line:
- savefig = True # and need to clear figure
- continue
-
- # handle comments
- if line_stripped.startswith('#'):
- output.extend([line])
- continue
-
- # deal with lines checking for multiline
- continuation = u' %s:'% ''.join(['.']*(len(str(ct))+2))
- if not multiline:
- modified = u"%s %s" % (fmtin % ct, line_stripped)
- output.append(modified)
- ct += 1
- try:
- ast.parse(line_stripped)
- output.append(u'')
- except Exception: # on a multiline
- multiline = True
- multiline_start = lineno
- else: # still on a multiline
- modified = u'%s %s' % (continuation, line)
- output.append(modified)
-
- # if the next line is indented, it should be part of multiline
- if len(content) > lineno + 1:
- nextline = content[lineno + 1]
- if len(nextline) - len(nextline.lstrip()) > 3:
- continue
- try:
- mod = ast.parse(
- '\n'.join(content[multiline_start:lineno+1]))
- if isinstance(mod.body[0], ast.FunctionDef):
- # check to see if we have the whole function
- for element in mod.body[0].body:
- if isinstance(element, ast.Return):
- multiline = False
- else:
- output.append(u'')
- multiline = False
- except Exception:
- pass
-
- if savefig: # clear figure if plotted
- self.ensure_pyplot()
- self.process_input_line('plt.clf()', store_history=False)
- self.clear_cout()
- savefig = False
-
- return output
-
- def custom_doctest(self, decorator, input_lines, found, submitted):
- """
- Perform a specialized doctest.
-
- """
- from .custom_doctests import doctests
-
- args = decorator.split()
- doctest_type = args[1]
- if doctest_type in doctests:
- doctests[doctest_type](self, args, input_lines, found, submitted)
- else:
- e = "Invalid option to @doctest: {0}".format(doctest_type)
- raise Exception(e)
-
-
-class IPythonDirective(Directive):
-
- has_content = True
- required_arguments = 0
- optional_arguments = 4 # python, suppress, verbatim, doctest
- final_argumuent_whitespace = True
- option_spec = { 'python': directives.unchanged,
- 'suppress' : directives.flag,
- 'verbatim' : directives.flag,
- 'doctest' : directives.flag,
- 'okexcept': directives.flag,
- 'okwarning': directives.flag
- }
-
- shell = None
-
- seen_docs = set()
-
- def get_config_options(self):
- # contains sphinx configuration variables
- config = self.state.document.settings.env.config
-
- # get config variables to set figure output directory
- savefig_dir = config.ipython_savefig_dir
+
+ imagerows = ['.. image:: %s'%outfile]
+
+ for kwarg in saveargs[2:]:
+ arg, val = kwarg.split('=')
+ arg = arg.strip()
+ val = val.strip()
+ imagerows.append(' :%s: %s'%(arg, val))
+
+ image_file = os.path.basename(outfile) # only return file name
+ image_directive = '\n'.join(imagerows)
+ return image_file, image_directive
+
+ # Callbacks for each type of token
+ def process_input(self, data, input_prompt, lineno):
+ """
+ Process data block for INPUT token.
+
+ """
+ decorator, input, rest = data
+ image_file = None
+ image_directive = None
+
+ is_verbatim = decorator=='@verbatim' or self.is_verbatim
+ is_doctest = (decorator is not None and \
+ decorator.startswith('@doctest')) or self.is_doctest
+ is_suppress = decorator=='@suppress' or self.is_suppress
+ is_okexcept = decorator=='@okexcept' or self.is_okexcept
+ is_okwarning = decorator=='@okwarning' or self.is_okwarning
+ is_savefig = decorator is not None and \
+ decorator.startswith('@savefig')
+
+ input_lines = input.split('\n')
+ if len(input_lines) > 1:
+ if input_lines[-1] != "":
+ input_lines.append('') # make sure there's a blank line
+ # so splitter buffer gets reset
+
+ continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
+
+ if is_savefig:
+ image_file, image_directive = self.process_image(decorator)
+
+ ret = []
+ is_semicolon = False
+
+ # Hold the execution count, if requested to do so.
+ if is_suppress and self.hold_count:
+ store_history = False
+ else:
+ store_history = True
+
+ # Note: catch_warnings is not thread safe
+ with warnings.catch_warnings(record=True) as ws:
+ for i, line in enumerate(input_lines):
+ if line.endswith(';'):
+ is_semicolon = True
+
+ if i == 0:
+ # process the first input line
+ if is_verbatim:
+ self.process_input_line('')
+ self.IP.execution_count += 1 # increment it anyway
+ else:
+ # only submit the line in non-verbatim mode
+ self.process_input_line(line, store_history=store_history)
+ formatted_line = '%s %s'%(input_prompt, line)
+ else:
+ # process a continuation line
+ if not is_verbatim:
+ self.process_input_line(line, store_history=store_history)
+
+ formatted_line = '%s %s'%(continuation, line)
+
+ if not is_suppress:
+ ret.append(formatted_line)
+
+ if not is_suppress and len(rest.strip()) and is_verbatim:
+ # The "rest" is the standard output of the input. This needs to be
+ # added when in verbatim mode. If there is no "rest", then we don't
+ # add it, as the new line will be added by the processed output.
+ ret.append(rest)
+
+ # Fetch the processed output. (This is not the submitted output.)
+ self.cout.seek(0)
+ processed_output = self.cout.read()
+ if not is_suppress and not is_semicolon:
+ #
+ # In IPythonDirective.run, the elements of `ret` are eventually
+ # combined such that '' entries correspond to newlines. So if
+ # `processed_output` is equal to '', then the adding it to `ret`
+ # ensures that there is a blank line between consecutive inputs
+ # that have no outputs, as in:
+ #
+ # In [1]: x = 4
+ #
+ # In [2]: x = 5
+ #
+ # When there is processed output, it has a '\n' at the tail end. So
+ # adding the output to `ret` will provide the necessary spacing
+ # between consecutive input/output blocks, as in:
+ #
+ # In [1]: x
+ # Out[1]: 5
+ #
+ # In [2]: x
+ # Out[2]: 5
+ #
+ # When there is stdout from the input, it also has a '\n' at the
+ # tail end, and so this ensures proper spacing as well. E.g.:
+ #
+ # In [1]: print x
+ # 5
+ #
+ # In [2]: x = 5
+ #
+ # When in verbatim mode, `processed_output` is empty (because
+ # nothing was passed to IP. Sometimes the submitted code block has
+ # an Out[] portion and sometimes it does not. When it does not, we
+ # need to ensure proper spacing, so we have to add '' to `ret`.
+ # However, if there is an Out[] in the submitted code, then we do
+ # not want to add a newline as `process_output` has stuff to add.
+ # The difficulty is that `process_input` doesn't know if
+ # `process_output` will be called---so it doesn't know if there is
+ # Out[] in the code block. The requires that we include a hack in
+ # `process_block`. See the comments there.
+ #
+ ret.append(processed_output)
+ elif is_semicolon:
+ # Make sure there is a newline after the semicolon.
+ ret.append('')
+
+ # context information
+ filename = "Unknown"
+ lineno = 0
+ if self.directive.state:
+ filename = self.directive.state.document.current_source
+ lineno = self.directive.state.document.current_line
+
+ # output any exceptions raised during execution to stdout
+ # unless :okexcept: has been specified.
+ if not is_okexcept and "Traceback" in processed_output:
+ s = "\nException in %s at block ending on line %s\n" % (filename, lineno)
+ s += "Specify :okexcept: as an option in the ipython:: block to suppress this message\n"
+ sys.stdout.write('\n\n>>>' + ('-' * 73))
+ sys.stdout.write(s)
+ sys.stdout.write(processed_output)
+ sys.stdout.write('<<<' + ('-' * 73) + '\n\n')
+
+ # output any warning raised during execution to stdout
+ # unless :okwarning: has been specified.
+ if not is_okwarning:
+ for w in ws:
+ s = "\nWarning in %s at block ending on line %s\n" % (filename, lineno)
+ s += "Specify :okwarning: as an option in the ipython:: block to suppress this message\n"
+ sys.stdout.write('\n\n>>>' + ('-' * 73))
+ sys.stdout.write(s)
+ sys.stdout.write(('-' * 76) + '\n')
+ s=warnings.formatwarning(w.message, w.category,
+ w.filename, w.lineno, w.line)
+ sys.stdout.write(s)
+ sys.stdout.write('<<<' + ('-' * 73) + '\n')
+
+ self.cout.truncate(0)
+
+ return (ret, input_lines, processed_output,
+ is_doctest, decorator, image_file, image_directive)
+
+
+ def process_output(self, data, output_prompt, input_lines, output,
+ is_doctest, decorator, image_file):
+ """
+ Process data block for OUTPUT token.
+
+ """
+ # Recall: `data` is the submitted output, and `output` is the processed
+ # output from `input_lines`.
+
+ TAB = ' ' * 4
+
+ if is_doctest and output is not None:
+
+ found = output # This is the processed output
+ found = found.strip()
+ submitted = data.strip()
+
+ if self.directive is None:
+ source = 'Unavailable'
+ content = 'Unavailable'
+ else:
+ source = self.directive.state.document.current_source
+ content = self.directive.content
+ # Add tabs and join into a single string.
+ content = '\n'.join([TAB + line for line in content])
+
+ # Make sure the output contains the output prompt.
+ ind = found.find(output_prompt)
+ if ind < 0:
+ e = ('output does not contain output prompt\n\n'
+ 'Document source: {0}\n\n'
+ 'Raw content: \n{1}\n\n'
+ 'Input line(s):\n{TAB}{2}\n\n'
+ 'Output line(s):\n{TAB}{3}\n\n')
+ e = e.format(source, content, '\n'.join(input_lines),
+ repr(found), TAB=TAB)
+ raise RuntimeError(e)
+ found = found[len(output_prompt):].strip()
+
+ # Handle the actual doctest comparison.
+ if decorator.strip() == '@doctest':
+ # Standard doctest
+ if found != submitted:
+ e = ('doctest failure\n\n'
+ 'Document source: {0}\n\n'
+ 'Raw content: \n{1}\n\n'
+ 'On input line(s):\n{TAB}{2}\n\n'
+ 'we found output:\n{TAB}{3}\n\n'
+ 'instead of the expected:\n{TAB}{4}\n\n')
+ e = e.format(source, content, '\n'.join(input_lines),
+ repr(found), repr(submitted), TAB=TAB)
+ raise RuntimeError(e)
+ else:
+ self.custom_doctest(decorator, input_lines, found, submitted)
+
+ # When in verbatim mode, this holds additional submitted output
+ # to be written in the final Sphinx output.
+ # https://github.com/ipython/ipython/issues/5776
+ out_data = []
+
+ is_verbatim = decorator=='@verbatim' or self.is_verbatim
+ if is_verbatim and data.strip():
+ # Note that `ret` in `process_block` has '' as its last element if
+ # the code block was in verbatim mode. So if there is no submitted
+ # output, then we will have proper spacing only if we do not add
+ # an additional '' to `out_data`. This is why we condition on
+ # `and data.strip()`.
+
+ # The submitted output has no output prompt. If we want the
+ # prompt and the code to appear, we need to join them now
+ # instead of adding them separately---as this would create an
+ # undesired newline. How we do this ultimately depends on the
+ # format of the output regex. I'll do what works for the default
+ # prompt for now, and we might have to adjust if it doesn't work
+ # in other cases. Finally, the submitted output does not have
+ # a trailing newline, so we must add it manually.
+ out_data.append("{0} {1}\n".format(output_prompt, data))
+
+ return out_data
+
+ def process_comment(self, data):
+ """Process data fPblock for COMMENT token."""
+ if not self.is_suppress:
+ return [data]
+
+ def save_image(self, image_file):
+ """
+ Saves the image file to disk.
+ """
+ self.ensure_pyplot()
+ command = 'plt.gcf().savefig("%s")'%image_file
+ #print 'SAVEFIG', command # dbg
+ self.process_input_line('bookmark ipy_thisdir', store_history=False)
+ self.process_input_line('cd -b ipy_savedir', store_history=False)
+ self.process_input_line(command, store_history=False)
+ self.process_input_line('cd -b ipy_thisdir', store_history=False)
+ self.process_input_line('bookmark -d ipy_thisdir', store_history=False)
+ self.clear_cout()
+
+ def process_block(self, block):
+ """
+ process block from the block_parser and return a list of processed lines
+ """
+ ret = []
+ output = None
+ input_lines = None
+ lineno = self.IP.execution_count
+
+ input_prompt = self.promptin % lineno
+ output_prompt = self.promptout % lineno
+ image_file = None
+ image_directive = None
+
+ found_input = False
+ for token, data in block:
+ if token == COMMENT:
+ out_data = self.process_comment(data)
+ elif token == INPUT:
+ found_input = True
+ (out_data, input_lines, output, is_doctest,
+ decorator, image_file, image_directive) = \
+ self.process_input(data, input_prompt, lineno)
+ elif token == OUTPUT:
+ if not found_input:
+
+ TAB = ' ' * 4
+ linenumber = 0
+ source = 'Unavailable'
+ content = 'Unavailable'
+ if self.directive:
+ linenumber = self.directive.state.document.current_line
+ source = self.directive.state.document.current_source
+ content = self.directive.content
+ # Add tabs and join into a single string.
+ content = '\n'.join([TAB + line for line in content])
+
+ e = ('\n\nInvalid block: Block contains an output prompt '
+ 'without an input prompt.\n\n'
+ 'Document source: {0}\n\n'
+ 'Content begins at line {1}: \n\n{2}\n\n'
+ 'Problematic block within content: \n\n{TAB}{3}\n\n')
+ e = e.format(source, linenumber, content, block, TAB=TAB)
+
+ # Write, rather than include in exception, since Sphinx
+ # will truncate tracebacks.
+ sys.stdout.write(e)
+ raise RuntimeError('An invalid block was detected.')
+
+ out_data = \
+ self.process_output(data, output_prompt, input_lines,
+ output, is_doctest, decorator,
+ image_file)
+ if out_data:
+ # Then there was user submitted output in verbatim mode.
+ # We need to remove the last element of `ret` that was
+ # added in `process_input`, as it is '' and would introduce
+ # an undesirable newline.
+ assert(ret[-1] == '')
+ del ret[-1]
+
+ if out_data:
+ ret.extend(out_data)
+
+ # save the image files
+ if image_file is not None:
+ self.save_image(image_file)
+
+ return ret, image_directive
+
+ def ensure_pyplot(self):
+ """
+ Ensures that pyplot has been imported into the embedded IPython shell.
+
+ Also, makes sure to set the backend appropriately if not set already.
+
+ """
+ # We are here if the @figure pseudo decorator was used. Thus, it's
+ # possible that we could be here even if python_mplbackend were set to
+ # `None`. That's also strange and perhaps worthy of raising an
+ # exception, but for now, we just set the backend to 'agg'.
+
+ if not self._pyplot_imported:
+ if 'matplotlib.backends' not in sys.modules:
+ # Then ipython_matplotlib was set to None but there was a
+ # call to the @figure decorator (and ipython_execlines did
+ # not set a backend).
+ #raise Exception("No backend was set, but @figure was used!")
+ import matplotlib
+ matplotlib.use('agg')
+
+ # Always import pyplot into embedded shell.
+ self.process_input_line('import matplotlib.pyplot as plt',
+ store_history=False)
+ self._pyplot_imported = True
+
+ def process_pure_python(self, content):
+ """
+ content is a list of strings. it is unedited directive content
+
+ This runs it line by line in the InteractiveShell, prepends
+ prompts as needed capturing stderr and stdout, then returns
+ the content as a list as if it were ipython code
+ """
+ output = []
+ savefig = False # keep up with this to clear figure
+ multiline = False # to handle line continuation
+ multiline_start = None
+ fmtin = self.promptin
+
+ ct = 0
+
+ for lineno, line in enumerate(content):
+
+ line_stripped = line.strip()
+ if not len(line):
+ output.append(line)
+ continue
+
+ # handle decorators
+ if line_stripped.startswith('@'):
+ output.extend([line])
+ if 'savefig' in line:
+ savefig = True # and need to clear figure
+ continue
+
+ # handle comments
+ if line_stripped.startswith('#'):
+ output.extend([line])
+ continue
+
+ # deal with lines checking for multiline
+ continuation = u' %s:'% ''.join(['.']*(len(str(ct))+2))
+ if not multiline:
+ modified = u"%s %s" % (fmtin % ct, line_stripped)
+ output.append(modified)
+ ct += 1
+ try:
+ ast.parse(line_stripped)
+ output.append(u'')
+ except Exception: # on a multiline
+ multiline = True
+ multiline_start = lineno
+ else: # still on a multiline
+ modified = u'%s %s' % (continuation, line)
+ output.append(modified)
+
+ # if the next line is indented, it should be part of multiline
+ if len(content) > lineno + 1:
+ nextline = content[lineno + 1]
+ if len(nextline) - len(nextline.lstrip()) > 3:
+ continue
+ try:
+ mod = ast.parse(
+ '\n'.join(content[multiline_start:lineno+1]))
+ if isinstance(mod.body[0], ast.FunctionDef):
+ # check to see if we have the whole function
+ for element in mod.body[0].body:
+ if isinstance(element, ast.Return):
+ multiline = False
+ else:
+ output.append(u'')
+ multiline = False
+ except Exception:
+ pass
+
+ if savefig: # clear figure if plotted
+ self.ensure_pyplot()
+ self.process_input_line('plt.clf()', store_history=False)
+ self.clear_cout()
+ savefig = False
+
+ return output
+
+ def custom_doctest(self, decorator, input_lines, found, submitted):
+ """
+ Perform a specialized doctest.
+
+ """
+ from .custom_doctests import doctests
+
+ args = decorator.split()
+ doctest_type = args[1]
+ if doctest_type in doctests:
+ doctests[doctest_type](self, args, input_lines, found, submitted)
+ else:
+ e = "Invalid option to @doctest: {0}".format(doctest_type)
+ raise Exception(e)
+
+
+class IPythonDirective(Directive):
+
+ has_content = True
+ required_arguments = 0
+ optional_arguments = 4 # python, suppress, verbatim, doctest
+ final_argumuent_whitespace = True
+ option_spec = { 'python': directives.unchanged,
+ 'suppress' : directives.flag,
+ 'verbatim' : directives.flag,
+ 'doctest' : directives.flag,
+ 'okexcept': directives.flag,
+ 'okwarning': directives.flag
+ }
+
+ shell = None
+
+ seen_docs = set()
+
+ def get_config_options(self):
+ # contains sphinx configuration variables
+ config = self.state.document.settings.env.config
+
+ # get config variables to set figure output directory
+ savefig_dir = config.ipython_savefig_dir
source_dir = self.state.document.settings.env.srcdir
savefig_dir = os.path.join(source_dir, savefig_dir)
-
- # get regex and prompt stuff
- rgxin = config.ipython_rgxin
- rgxout = config.ipython_rgxout
- promptin = config.ipython_promptin
- promptout = config.ipython_promptout
- mplbackend = config.ipython_mplbackend
- exec_lines = config.ipython_execlines
- hold_count = config.ipython_holdcount
-
- return (savefig_dir, source_dir, rgxin, rgxout,
- promptin, promptout, mplbackend, exec_lines, hold_count)
-
- def setup(self):
- # Get configuration values.
- (savefig_dir, source_dir, rgxin, rgxout, promptin, promptout,
- mplbackend, exec_lines, hold_count) = self.get_config_options()
-
+
+ # get regex and prompt stuff
+ rgxin = config.ipython_rgxin
+ rgxout = config.ipython_rgxout
+ promptin = config.ipython_promptin
+ promptout = config.ipython_promptout
+ mplbackend = config.ipython_mplbackend
+ exec_lines = config.ipython_execlines
+ hold_count = config.ipython_holdcount
+
+ return (savefig_dir, source_dir, rgxin, rgxout,
+ promptin, promptout, mplbackend, exec_lines, hold_count)
+
+ def setup(self):
+ # Get configuration values.
+ (savefig_dir, source_dir, rgxin, rgxout, promptin, promptout,
+ mplbackend, exec_lines, hold_count) = self.get_config_options()
+
try:
os.makedirs(savefig_dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise
- if self.shell is None:
- # We will be here many times. However, when the
- # EmbeddedSphinxShell is created, its interactive shell member
- # is the same for each instance.
-
+ if self.shell is None:
+ # We will be here many times. However, when the
+ # EmbeddedSphinxShell is created, its interactive shell member
+ # is the same for each instance.
+
if mplbackend and 'matplotlib.backends' not in sys.modules:
- import matplotlib
- matplotlib.use(mplbackend)
-
- # Must be called after (potentially) importing matplotlib and
- # setting its backend since exec_lines might import pylab.
- self.shell = EmbeddedSphinxShell(exec_lines)
-
- # Store IPython directive to enable better error messages
- self.shell.directive = self
-
- # reset the execution count if we haven't processed this doc
- #NOTE: this may be borked if there are multiple seen_doc tmp files
- #check time stamp?
- if not self.state.document.current_source in self.seen_docs:
- self.shell.IP.history_manager.reset()
- self.shell.IP.execution_count = 1
- self.seen_docs.add(self.state.document.current_source)
-
- # and attach to shell so we don't have to pass them around
- self.shell.rgxin = rgxin
- self.shell.rgxout = rgxout
- self.shell.promptin = promptin
- self.shell.promptout = promptout
- self.shell.savefig_dir = savefig_dir
- self.shell.source_dir = source_dir
- self.shell.hold_count = hold_count
-
- # setup bookmark for saving figures directory
- self.shell.process_input_line('bookmark ipy_savedir %s'%savefig_dir,
- store_history=False)
- self.shell.clear_cout()
-
- return rgxin, rgxout, promptin, promptout
-
- def teardown(self):
- # delete last bookmark
- self.shell.process_input_line('bookmark -d ipy_savedir',
- store_history=False)
- self.shell.clear_cout()
-
- def run(self):
- debug = False
-
- #TODO, any reason block_parser can't be a method of embeddable shell
- # then we wouldn't have to carry these around
- rgxin, rgxout, promptin, promptout = self.setup()
-
- options = self.options
- self.shell.is_suppress = 'suppress' in options
- self.shell.is_doctest = 'doctest' in options
- self.shell.is_verbatim = 'verbatim' in options
- self.shell.is_okexcept = 'okexcept' in options
- self.shell.is_okwarning = 'okwarning' in options
-
- # handle pure python code
- if 'python' in self.arguments:
- content = self.content
- self.content = self.shell.process_pure_python(content)
-
- # parts consists of all text within the ipython-block.
- # Each part is an input/output block.
- parts = '\n'.join(self.content).split('\n\n')
-
- lines = ['.. code-block:: ipython', '']
- figures = []
-
- for part in parts:
- block = block_parser(part, rgxin, rgxout, promptin, promptout)
- if len(block):
- rows, figure = self.shell.process_block(block)
- for row in rows:
- lines.extend([' {0}'.format(line)
- for line in row.split('\n')])
-
- if figure is not None:
- figures.append(figure)
-
- for figure in figures:
- lines.append('')
- lines.extend(figure.split('\n'))
- lines.append('')
-
- if len(lines) > 2:
- if debug:
- print('\n'.join(lines))
- else:
- # This has to do with input, not output. But if we comment
- # these lines out, then no IPython code will appear in the
- # final output.
- self.state_machine.insert_input(
- lines, self.state_machine.input_lines.source(0))
-
- # cleanup
- self.teardown()
-
- return []
-
-# Enable as a proper Sphinx directive
-def setup(app):
- setup.app = app
-
- app.add_directive('ipython', IPythonDirective)
+ import matplotlib
+ matplotlib.use(mplbackend)
+
+ # Must be called after (potentially) importing matplotlib and
+ # setting its backend since exec_lines might import pylab.
+ self.shell = EmbeddedSphinxShell(exec_lines)
+
+ # Store IPython directive to enable better error messages
+ self.shell.directive = self
+
+ # reset the execution count if we haven't processed this doc
+ #NOTE: this may be borked if there are multiple seen_doc tmp files
+ #check time stamp?
+ if not self.state.document.current_source in self.seen_docs:
+ self.shell.IP.history_manager.reset()
+ self.shell.IP.execution_count = 1
+ self.seen_docs.add(self.state.document.current_source)
+
+ # and attach to shell so we don't have to pass them around
+ self.shell.rgxin = rgxin
+ self.shell.rgxout = rgxout
+ self.shell.promptin = promptin
+ self.shell.promptout = promptout
+ self.shell.savefig_dir = savefig_dir
+ self.shell.source_dir = source_dir
+ self.shell.hold_count = hold_count
+
+ # setup bookmark for saving figures directory
+ self.shell.process_input_line('bookmark ipy_savedir %s'%savefig_dir,
+ store_history=False)
+ self.shell.clear_cout()
+
+ return rgxin, rgxout, promptin, promptout
+
+ def teardown(self):
+ # delete last bookmark
+ self.shell.process_input_line('bookmark -d ipy_savedir',
+ store_history=False)
+ self.shell.clear_cout()
+
+ def run(self):
+ debug = False
+
+ #TODO, any reason block_parser can't be a method of embeddable shell
+ # then we wouldn't have to carry these around
+ rgxin, rgxout, promptin, promptout = self.setup()
+
+ options = self.options
+ self.shell.is_suppress = 'suppress' in options
+ self.shell.is_doctest = 'doctest' in options
+ self.shell.is_verbatim = 'verbatim' in options
+ self.shell.is_okexcept = 'okexcept' in options
+ self.shell.is_okwarning = 'okwarning' in options
+
+ # handle pure python code
+ if 'python' in self.arguments:
+ content = self.content
+ self.content = self.shell.process_pure_python(content)
+
+ # parts consists of all text within the ipython-block.
+ # Each part is an input/output block.
+ parts = '\n'.join(self.content).split('\n\n')
+
+ lines = ['.. code-block:: ipython', '']
+ figures = []
+
+ for part in parts:
+ block = block_parser(part, rgxin, rgxout, promptin, promptout)
+ if len(block):
+ rows, figure = self.shell.process_block(block)
+ for row in rows:
+ lines.extend([' {0}'.format(line)
+ for line in row.split('\n')])
+
+ if figure is not None:
+ figures.append(figure)
+
+ for figure in figures:
+ lines.append('')
+ lines.extend(figure.split('\n'))
+ lines.append('')
+
+ if len(lines) > 2:
+ if debug:
+ print('\n'.join(lines))
+ else:
+ # This has to do with input, not output. But if we comment
+ # these lines out, then no IPython code will appear in the
+ # final output.
+ self.state_machine.insert_input(
+ lines, self.state_machine.input_lines.source(0))
+
+ # cleanup
+ self.teardown()
+
+ return []
+
+# Enable as a proper Sphinx directive
+def setup(app):
+ setup.app = app
+
+ app.add_directive('ipython', IPythonDirective)
app.add_config_value('ipython_savefig_dir', 'savefig', 'env')
- app.add_config_value('ipython_rgxin',
- re.compile('In \[(\d+)\]:\s?(.*)\s*'), 'env')
- app.add_config_value('ipython_rgxout',
- re.compile('Out\[(\d+)\]:\s?(.*)\s*'), 'env')
- app.add_config_value('ipython_promptin', 'In [%d]:', 'env')
- app.add_config_value('ipython_promptout', 'Out[%d]:', 'env')
-
- # We could just let matplotlib pick whatever is specified as the default
- # backend in the matplotlibrc file, but this would cause issues if the
- # backend didn't work in headless environments. For this reason, 'agg'
- # is a good default backend choice.
- app.add_config_value('ipython_mplbackend', 'agg', 'env')
-
- # If the user sets this config value to `None`, then EmbeddedSphinxShell's
- # __init__ method will treat it as [].
- execlines = ['import numpy as np', 'import matplotlib.pyplot as plt']
- app.add_config_value('ipython_execlines', execlines, 'env')
-
- app.add_config_value('ipython_holdcount', True, 'env')
-
- metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
- return metadata
-
-# Simple smoke test, needs to be converted to a proper automatic test.
-def test():
-
- examples = [
- r"""
-In [9]: pwd
-Out[9]: '/home/jdhunter/py4science/book'
-
-In [10]: cd bookdata/
-/home/jdhunter/py4science/book/bookdata
-
-In [2]: from pylab import *
-
-In [2]: ion()
-
-In [3]: im = imread('stinkbug.png')
-
-@savefig mystinkbug.png width=4in
-In [4]: imshow(im)
-Out[4]: <matplotlib.image.AxesImage object at 0x39ea850>
-
-""",
- r"""
-
-In [1]: x = 'hello world'
-
-# string methods can be
-# used to alter the string
-@doctest
-In [2]: x.upper()
-Out[2]: 'HELLO WORLD'
-
-@verbatim
-In [3]: x.st<TAB>
-x.startswith x.strip
-""",
- r"""
-
-In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
- .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
-
-In [131]: print url.split('&')
-['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv']
-
-In [60]: import urllib
-
-""",
- r"""\
-
-In [133]: import numpy.random
-
-@suppress
-In [134]: numpy.random.seed(2358)
-
-@doctest
-In [135]: numpy.random.rand(10,2)
-Out[135]:
-array([[ 0.64524308, 0.59943846],
- [ 0.47102322, 0.8715456 ],
- [ 0.29370834, 0.74776844],
- [ 0.99539577, 0.1313423 ],
- [ 0.16250302, 0.21103583],
- [ 0.81626524, 0.1312433 ],
- [ 0.67338089, 0.72302393],
- [ 0.7566368 , 0.07033696],
- [ 0.22591016, 0.77731835],
- [ 0.0072729 , 0.34273127]])
-
-""",
-
- r"""
-In [106]: print x
-jdh
-
-In [109]: for i in range(10):
- .....: print i
- .....:
- .....:
-0
-1
-2
-3
-4
-5
-6
-7
-8
-9
-""",
-
- r"""
-
-In [144]: from pylab import *
-
-In [145]: ion()
-
-# use a semicolon to suppress the output
-@savefig test_hist.png width=4in
-In [151]: hist(np.random.randn(10000), 100);
-
-
-@savefig test_plot.png width=4in
-In [151]: plot(np.random.randn(10000), 'o');
- """,
-
- r"""
-# use a semicolon to suppress the output
-In [151]: plt.clf()
-
-@savefig plot_simple.png width=4in
-In [151]: plot([1,2,3])
-
-@savefig hist_simple.png width=4in
-In [151]: hist(np.random.randn(10000), 100);
-
-""",
- r"""
-# update the current fig
-In [151]: ylabel('number')
-
-In [152]: title('normal distribution')
-
-
-@savefig hist_with_text.png
-In [153]: grid(True)
-
-@doctest float
-In [154]: 0.1 + 0.2
-Out[154]: 0.3
-
-@doctest float
-In [155]: np.arange(16).reshape(4,4)
-Out[155]:
-array([[ 0, 1, 2, 3],
- [ 4, 5, 6, 7],
- [ 8, 9, 10, 11],
- [12, 13, 14, 15]])
-
-In [1]: x = np.arange(16, dtype=float).reshape(4,4)
-
-In [2]: x[0,0] = np.inf
-
-In [3]: x[0,1] = np.nan
-
-@doctest float
-In [4]: x
-Out[4]:
-array([[ inf, nan, 2., 3.],
- [ 4., 5., 6., 7.],
- [ 8., 9., 10., 11.],
- [ 12., 13., 14., 15.]])
-
-
- """,
- ]
- # skip local-file depending first example:
- examples = examples[1:]
-
- #ipython_directive.DEBUG = True # dbg
- #options = dict(suppress=True) # dbg
- options = dict()
- for example in examples:
- content = example.split('\n')
- IPythonDirective('debug', arguments=None, options=options,
- content=content, lineno=0,
- content_offset=None, block_text=None,
- state=None, state_machine=None,
- )
-
-# Run test suite as a script
-if __name__=='__main__':
- if not os.path.isdir('_static'):
- os.mkdir('_static')
- test()
- print('All OK? Check figures in _static/')
+ app.add_config_value('ipython_rgxin',
+ re.compile('In \[(\d+)\]:\s?(.*)\s*'), 'env')
+ app.add_config_value('ipython_rgxout',
+ re.compile('Out\[(\d+)\]:\s?(.*)\s*'), 'env')
+ app.add_config_value('ipython_promptin', 'In [%d]:', 'env')
+ app.add_config_value('ipython_promptout', 'Out[%d]:', 'env')
+
+ # We could just let matplotlib pick whatever is specified as the default
+ # backend in the matplotlibrc file, but this would cause issues if the
+ # backend didn't work in headless environments. For this reason, 'agg'
+ # is a good default backend choice.
+ app.add_config_value('ipython_mplbackend', 'agg', 'env')
+
+ # If the user sets this config value to `None`, then EmbeddedSphinxShell's
+ # __init__ method will treat it as [].
+ execlines = ['import numpy as np', 'import matplotlib.pyplot as plt']
+ app.add_config_value('ipython_execlines', execlines, 'env')
+
+ app.add_config_value('ipython_holdcount', True, 'env')
+
+ metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
+ return metadata
+
+# Simple smoke test, needs to be converted to a proper automatic test.
+def test():
+
+ examples = [
+ r"""
+In [9]: pwd
+Out[9]: '/home/jdhunter/py4science/book'
+
+In [10]: cd bookdata/
+/home/jdhunter/py4science/book/bookdata
+
+In [2]: from pylab import *
+
+In [2]: ion()
+
+In [3]: im = imread('stinkbug.png')
+
+@savefig mystinkbug.png width=4in
+In [4]: imshow(im)
+Out[4]: <matplotlib.image.AxesImage object at 0x39ea850>
+
+""",
+ r"""
+
+In [1]: x = 'hello world'
+
+# string methods can be
+# used to alter the string
+@doctest
+In [2]: x.upper()
+Out[2]: 'HELLO WORLD'
+
+@verbatim
+In [3]: x.st<TAB>
+x.startswith x.strip
+""",
+ r"""
+
+In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
+ .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
+
+In [131]: print url.split('&')
+['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv']
+
+In [60]: import urllib
+
+""",
+ r"""\
+
+In [133]: import numpy.random
+
+@suppress
+In [134]: numpy.random.seed(2358)
+
+@doctest
+In [135]: numpy.random.rand(10,2)
+Out[135]:
+array([[ 0.64524308, 0.59943846],
+ [ 0.47102322, 0.8715456 ],
+ [ 0.29370834, 0.74776844],
+ [ 0.99539577, 0.1313423 ],
+ [ 0.16250302, 0.21103583],
+ [ 0.81626524, 0.1312433 ],
+ [ 0.67338089, 0.72302393],
+ [ 0.7566368 , 0.07033696],
+ [ 0.22591016, 0.77731835],
+ [ 0.0072729 , 0.34273127]])
+
+""",
+
+ r"""
+In [106]: print x
+jdh
+
+In [109]: for i in range(10):
+ .....: print i
+ .....:
+ .....:
+0
+1
+2
+3
+4
+5
+6
+7
+8
+9
+""",
+
+ r"""
+
+In [144]: from pylab import *
+
+In [145]: ion()
+
+# use a semicolon to suppress the output
+@savefig test_hist.png width=4in
+In [151]: hist(np.random.randn(10000), 100);
+
+
+@savefig test_plot.png width=4in
+In [151]: plot(np.random.randn(10000), 'o');
+ """,
+
+ r"""
+# use a semicolon to suppress the output
+In [151]: plt.clf()
+
+@savefig plot_simple.png width=4in
+In [151]: plot([1,2,3])
+
+@savefig hist_simple.png width=4in
+In [151]: hist(np.random.randn(10000), 100);
+
+""",
+ r"""
+# update the current fig
+In [151]: ylabel('number')
+
+In [152]: title('normal distribution')
+
+
+@savefig hist_with_text.png
+In [153]: grid(True)
+
+@doctest float
+In [154]: 0.1 + 0.2
+Out[154]: 0.3
+
+@doctest float
+In [155]: np.arange(16).reshape(4,4)
+Out[155]:
+array([[ 0, 1, 2, 3],
+ [ 4, 5, 6, 7],
+ [ 8, 9, 10, 11],
+ [12, 13, 14, 15]])
+
+In [1]: x = np.arange(16, dtype=float).reshape(4,4)
+
+In [2]: x[0,0] = np.inf
+
+In [3]: x[0,1] = np.nan
+
+@doctest float
+In [4]: x
+Out[4]:
+array([[ inf, nan, 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.],
+ [ 12., 13., 14., 15.]])
+
+
+ """,
+ ]
+ # skip local-file depending first example:
+ examples = examples[1:]
+
+ #ipython_directive.DEBUG = True # dbg
+ #options = dict(suppress=True) # dbg
+ options = dict()
+ for example in examples:
+ content = example.split('\n')
+ IPythonDirective('debug', arguments=None, options=options,
+ content=content, lineno=0,
+ content_offset=None, block_text=None,
+ state=None, state_machine=None,
+ )
+
+# Run test suite as a script
+if __name__=='__main__':
+ if not os.path.isdir('_static'):
+ os.mkdir('_static')
+ test()
+ print('All OK? Check figures in _static/')
diff --git a/contrib/python/ipython/py2/IPython/terminal/console.py b/contrib/python/ipython/py2/IPython/terminal/console.py
index 981ee46b17..65571a7572 100644
--- a/contrib/python/ipython/py2/IPython/terminal/console.py
+++ b/contrib/python/ipython/py2/IPython/terminal/console.py
@@ -1,19 +1,19 @@
-"""
-Shim to maintain backwards compatibility with old IPython.terminal.console imports.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import sys
-from warnings import warn
-
-from IPython.utils.shimmodule import ShimModule, ShimWarning
-
+"""
+Shim to maintain backwards compatibility with old IPython.terminal.console imports.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import sys
+from warnings import warn
+
+from IPython.utils.shimmodule import ShimModule, ShimWarning
+
warn("The `IPython.terminal.console` package has been deprecated since IPython 4.0. "
- "You should import from jupyter_console instead.", ShimWarning)
-
-# Unconditionally insert the shim into sys.modules so that further import calls
-# trigger the custom attribute access above
-
-sys.modules['IPython.terminal.console'] = ShimModule(
- src='IPython.terminal.console', mirror='jupyter_console')
+ "You should import from jupyter_console instead.", ShimWarning)
+
+# Unconditionally insert the shim into sys.modules so that further import calls
+# trigger the custom attribute access above
+
+sys.modules['IPython.terminal.console'] = ShimModule(
+ src='IPython.terminal.console', mirror='jupyter_console')
diff --git a/contrib/python/ipython/py2/IPython/terminal/embed.py b/contrib/python/ipython/py2/IPython/terminal/embed.py
index 8ff15313dd..5ad70431e4 100644
--- a/contrib/python/ipython/py2/IPython/terminal/embed.py
+++ b/contrib/python/ipython/py2/IPython/terminal/embed.py
@@ -1,33 +1,33 @@
-# encoding: utf-8
-"""
-An embedded IPython shell.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import with_statement
-from __future__ import print_function
-
-import sys
-import warnings
-
-from IPython.core import ultratb, compilerop
+# encoding: utf-8
+"""
+An embedded IPython shell.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import with_statement
+from __future__ import print_function
+
+import sys
+import warnings
+
+from IPython.core import ultratb, compilerop
from IPython.core import magic_arguments
-from IPython.core.magic import Magics, magics_class, line_magic
+from IPython.core.magic import Magics, magics_class, line_magic
from IPython.core.interactiveshell import DummyMod, InteractiveShell
-from IPython.terminal.interactiveshell import TerminalInteractiveShell
-from IPython.terminal.ipapp import load_default_config
-
-from traitlets import Bool, CBool, Unicode
-from IPython.utils.io import ask_yes_no
-
-class KillEmbeded(Exception):pass
-
-# This is an additional magic that is exposed in embedded shells.
-@magics_class
-class EmbeddedMagics(Magics):
-
- @line_magic
+from IPython.terminal.interactiveshell import TerminalInteractiveShell
+from IPython.terminal.ipapp import load_default_config
+
+from traitlets import Bool, CBool, Unicode
+from IPython.utils.io import ask_yes_no
+
+class KillEmbeded(Exception):pass
+
+# This is an additional magic that is exposed in embedded shells.
+@magics_class
+class EmbeddedMagics(Magics):
+
+ @line_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument('-i', '--instance', action='store_true',
help='Kill instance instead of call location')
@@ -35,10 +35,10 @@ class EmbeddedMagics(Magics):
help='Also exit the current session')
@magic_arguments.argument('-y', '--yes', action='store_true',
help='Do not ask confirmation')
- def kill_embedded(self, parameter_s=''):
+ def kill_embedded(self, parameter_s=''):
"""%kill_embedded : deactivate for good the current embedded IPython
-
- This function (after asking for confirmation) sets an internal flag so
+
+ This function (after asking for confirmation) sets an internal flag so
that an embedded IPython will never activate again for the given call
location. This is useful to permanently disable a shell that is being
called inside a loop: once you've figured out what you needed from it,
@@ -60,8 +60,8 @@ class EmbeddedMagics(Magics):
This was the default behavior before IPython 5.2
- """
-
+ """
+
args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s)
print(args)
if args.instance:
@@ -85,38 +85,38 @@ class EmbeddedMagics(Magics):
self.shell.embedded_active = False
print("This embedded IPython call location will not reactivate anymore "
"once you exit.")
-
+
if args.exit:
# Ask-exit does not really ask, it just set internals flags to exit
# on next loop.
self.shell.ask_exit()
-
-
- @line_magic
- def exit_raise(self, parameter_s=''):
- """%exit_raise Make the current embedded kernel exit and raise and exception.
-
- This function sets an internal flag so that an embedded IPython will
- raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is
- useful to permanently exit a loop that create IPython embed instance.
- """
-
- self.shell.should_raise = True
- self.shell.ask_exit()
-
-
-
-class InteractiveShellEmbed(TerminalInteractiveShell):
-
- dummy_mode = Bool(False)
- exit_msg = Unicode('')
- embedded = CBool(True)
- should_raise = CBool(False)
- # Like the base class display_banner is not configurable, but here it
- # is True by default.
- display_banner = CBool(True)
- exit_msg = Unicode()
-
+
+
+ @line_magic
+ def exit_raise(self, parameter_s=''):
+ """%exit_raise Make the current embedded kernel exit and raise and exception.
+
+ This function sets an internal flag so that an embedded IPython will
+ raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is
+ useful to permanently exit a loop that create IPython embed instance.
+ """
+
+ self.shell.should_raise = True
+ self.shell.ask_exit()
+
+
+
+class InteractiveShellEmbed(TerminalInteractiveShell):
+
+ dummy_mode = Bool(False)
+ exit_msg = Unicode('')
+ embedded = CBool(True)
+ should_raise = CBool(False)
+ # Like the base class display_banner is not configurable, but here it
+ # is True by default.
+ display_banner = CBool(True)
+ exit_msg = Unicode()
+
# When embedding, by default we don't change the terminal title
term_title = Bool(False,
help="Automatically set the terminal title"
@@ -144,140 +144,140 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
InteractiveShellEmbed._inactive_locations.add(
self._call_location_id)
- def __init__(self, **kw):
- if kw.get('user_global_ns', None) is not None:
+ def __init__(self, **kw):
+ if kw.get('user_global_ns', None) is not None:
raise DeprecationWarning(
"Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.")
-
+
clid = kw.pop('_init_location_id', None)
if not clid:
frame = sys._getframe(1)
clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
self._init_location_id = clid
- super(InteractiveShellEmbed,self).__init__(**kw)
-
- # don't use the ipython crash handler so that user exceptions aren't
- # trapped
- sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
- mode=self.xmode,
- call_pdb=self.pdb)
-
- def init_sys_modules(self):
+ super(InteractiveShellEmbed,self).__init__(**kw)
+
+ # don't use the ipython crash handler so that user exceptions aren't
+ # trapped
+ sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
+ mode=self.xmode,
+ call_pdb=self.pdb)
+
+ def init_sys_modules(self):
"""
Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing.
"""
- pass
-
- def init_magics(self):
- super(InteractiveShellEmbed, self).init_magics()
- self.register_magics(EmbeddedMagics)
-
- def __call__(self, header='', local_ns=None, module=None, dummy=None,
+ pass
+
+ def init_magics(self):
+ super(InteractiveShellEmbed, self).init_magics()
+ self.register_magics(EmbeddedMagics)
+
+ def __call__(self, header='', local_ns=None, module=None, dummy=None,
stack_depth=1, global_ns=None, compile_flags=None, **kw):
- """Activate the interactive interpreter.
-
- __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
- the interpreter shell with the given local and global namespaces, and
- optionally print a header string at startup.
-
- The shell can be globally activated/deactivated using the
- dummy_mode attribute. This allows you to turn off a shell used
- for debugging globally.
-
- However, *each* time you call the shell you can override the current
- state of dummy_mode with the optional keyword parameter 'dummy'. For
- example, if you set dummy mode on with IPShell.dummy_mode = True, you
- can still have a specific call work by making it as IPShell(dummy=False).
- """
-
+ """Activate the interactive interpreter.
+
+ __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
+ the interpreter shell with the given local and global namespaces, and
+ optionally print a header string at startup.
+
+ The shell can be globally activated/deactivated using the
+ dummy_mode attribute. This allows you to turn off a shell used
+ for debugging globally.
+
+ However, *each* time you call the shell you can override the current
+ state of dummy_mode with the optional keyword parameter 'dummy'. For
+ example, if you set dummy mode on with IPShell.dummy_mode = True, you
+ can still have a specific call work by making it as IPShell(dummy=False).
+ """
+
# we are called, set the underlying interactiveshell not to exit.
self.keep_running = True
- # If the user has turned it off, go away
+ # If the user has turned it off, go away
clid = kw.pop('_call_location_id', None)
if not clid:
frame = sys._getframe(1)
clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
self._call_location_id = clid
- if not self.embedded_active:
- return
-
- # Normal exits from interactive mode set this flag, so the shell can't
- # re-enter (it checks this variable at the start of interactive mode).
- self.exit_now = False
-
- # Allow the dummy parameter to override the global __dummy_mode
- if dummy or (dummy != 0 and self.dummy_mode):
- return
-
- # self.banner is auto computed
- if header:
- self.old_banner2 = self.banner2
- self.banner2 = self.banner2 + '\n' + header + '\n'
- else:
- self.old_banner2 = ''
-
+ if not self.embedded_active:
+ return
+
+ # Normal exits from interactive mode set this flag, so the shell can't
+ # re-enter (it checks this variable at the start of interactive mode).
+ self.exit_now = False
+
+ # Allow the dummy parameter to override the global __dummy_mode
+ if dummy or (dummy != 0 and self.dummy_mode):
+ return
+
+ # self.banner is auto computed
+ if header:
+ self.old_banner2 = self.banner2
+ self.banner2 = self.banner2 + '\n' + header + '\n'
+ else:
+ self.old_banner2 = ''
+
if self.display_banner:
self.show_banner()
- # Call the embedding code with a stack depth of 1 so it can skip over
- # our call and get the original caller's namespaces.
- self.mainloop(local_ns, module, stack_depth=stack_depth,
- global_ns=global_ns, compile_flags=compile_flags)
-
- self.banner2 = self.old_banner2
-
- if self.exit_msg is not None:
- print(self.exit_msg)
-
- if self.should_raise:
- raise KillEmbeded('Embedded IPython raising error, as user requested.')
-
-
- def mainloop(self, local_ns=None, module=None, stack_depth=0,
- display_banner=None, global_ns=None, compile_flags=None):
- """Embeds IPython into a running python program.
-
- Parameters
- ----------
-
- local_ns, module
- Working local namespace (a dict) and module (a module or similar
- object). If given as None, they are automatically taken from the scope
- where the shell was called, so that program variables become visible.
-
- stack_depth : int
- How many levels in the stack to go to looking for namespaces (when
- local_ns or module is None). This allows an intermediate caller to
- make sure that this function gets the namespace from the intended
- level in the stack. By default (0) it will get its locals and globals
- from the immediate caller.
-
- compile_flags
- A bit field identifying the __future__ features
- that are enabled, as passed to the builtin :func:`compile` function.
- If given as None, they are automatically taken from the scope where
- the shell was called.
-
- """
-
- if (global_ns is not None) and (module is None):
+ # Call the embedding code with a stack depth of 1 so it can skip over
+ # our call and get the original caller's namespaces.
+ self.mainloop(local_ns, module, stack_depth=stack_depth,
+ global_ns=global_ns, compile_flags=compile_flags)
+
+ self.banner2 = self.old_banner2
+
+ if self.exit_msg is not None:
+ print(self.exit_msg)
+
+ if self.should_raise:
+ raise KillEmbeded('Embedded IPython raising error, as user requested.')
+
+
+ def mainloop(self, local_ns=None, module=None, stack_depth=0,
+ display_banner=None, global_ns=None, compile_flags=None):
+ """Embeds IPython into a running python program.
+
+ Parameters
+ ----------
+
+ local_ns, module
+ Working local namespace (a dict) and module (a module or similar
+ object). If given as None, they are automatically taken from the scope
+ where the shell was called, so that program variables become visible.
+
+ stack_depth : int
+ How many levels in the stack to go to looking for namespaces (when
+ local_ns or module is None). This allows an intermediate caller to
+ make sure that this function gets the namespace from the intended
+ level in the stack. By default (0) it will get its locals and globals
+ from the immediate caller.
+
+ compile_flags
+ A bit field identifying the __future__ features
+ that are enabled, as passed to the builtin :func:`compile` function.
+ If given as None, they are automatically taken from the scope where
+ the shell was called.
+
+ """
+
+ if (global_ns is not None) and (module is None):
raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.")
-
+
if (display_banner is not None):
warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning)
- # Get locals and globals from caller
- if ((local_ns is None or module is None or compile_flags is None)
- and self.default_user_namespaces):
- call_frame = sys._getframe(stack_depth).f_back
-
- if local_ns is None:
- local_ns = call_frame.f_locals
- if module is None:
- global_ns = call_frame.f_globals
+ # Get locals and globals from caller
+ if ((local_ns is None or module is None or compile_flags is None)
+ and self.default_user_namespaces):
+ call_frame = sys._getframe(stack_depth).f_back
+
+ if local_ns is None:
+ local_ns = call_frame.f_locals
+ if module is None:
+ global_ns = call_frame.f_globals
try:
module = sys.modules[global_ns['__name__']]
except KeyError:
@@ -286,110 +286,110 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
)
module = DummyMod()
module.__dict__ = global_ns
- if compile_flags is None:
- compile_flags = (call_frame.f_code.co_flags &
- compilerop.PyCF_MASK)
-
- # Save original namespace and module so we can restore them after
- # embedding; otherwise the shell doesn't shut down correctly.
- orig_user_module = self.user_module
- orig_user_ns = self.user_ns
- orig_compile_flags = self.compile.flags
-
- # Update namespaces and fire up interpreter
-
- # The global one is easy, we can just throw it in
- if module is not None:
- self.user_module = module
-
- # But the user/local one is tricky: ipython needs it to store internal
- # data, but we also need the locals. We'll throw our hidden variables
- # like _ih and get_ipython() into the local namespace, but delete them
- # later.
- if local_ns is not None:
- reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
- self.user_ns = reentrant_local_ns
- self.init_user_ns()
-
- # Compiler flags
- if compile_flags is not None:
- self.compile.flags = compile_flags
-
- # make sure the tab-completer has the correct frame information, so it
- # actually completes using the frame's locals/globals
- self.set_completer_frame()
-
- with self.builtin_trap, self.display_trap:
+ if compile_flags is None:
+ compile_flags = (call_frame.f_code.co_flags &
+ compilerop.PyCF_MASK)
+
+ # Save original namespace and module so we can restore them after
+ # embedding; otherwise the shell doesn't shut down correctly.
+ orig_user_module = self.user_module
+ orig_user_ns = self.user_ns
+ orig_compile_flags = self.compile.flags
+
+ # Update namespaces and fire up interpreter
+
+ # The global one is easy, we can just throw it in
+ if module is not None:
+ self.user_module = module
+
+ # But the user/local one is tricky: ipython needs it to store internal
+ # data, but we also need the locals. We'll throw our hidden variables
+ # like _ih and get_ipython() into the local namespace, but delete them
+ # later.
+ if local_ns is not None:
+ reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
+ self.user_ns = reentrant_local_ns
+ self.init_user_ns()
+
+ # Compiler flags
+ if compile_flags is not None:
+ self.compile.flags = compile_flags
+
+ # make sure the tab-completer has the correct frame information, so it
+ # actually completes using the frame's locals/globals
+ self.set_completer_frame()
+
+ with self.builtin_trap, self.display_trap:
self.interact()
-
- # now, purge out the local namespace of IPython's hidden variables.
- if local_ns is not None:
- local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
-
-
- # Restore original namespace so shell can shut down when we exit.
- self.user_module = orig_user_module
- self.user_ns = orig_user_ns
- self.compile.flags = orig_compile_flags
-
-
-def embed(**kwargs):
- """Call this to embed IPython at the current point in your program.
-
- The first invocation of this will create an :class:`InteractiveShellEmbed`
- instance and then call it. Consecutive calls just call the already
- created instance.
-
- If you don't want the kernel to initialize the namespace
- from the scope of the surrounding function,
- and/or you want to load full IPython configuration,
- you probably want `IPython.start_ipython()` instead.
-
- Here is a simple example::
-
- from IPython import embed
- a = 10
- b = 20
- embed(header='First time')
- c = 30
- d = 40
- embed()
-
- Full customization can be done by passing a :class:`Config` in as the
- config argument.
- """
- config = kwargs.get('config')
- header = kwargs.pop('header', u'')
- compile_flags = kwargs.pop('compile_flags', None)
- if config is None:
- config = load_default_config()
- config.InteractiveShellEmbed = config.TerminalInteractiveShell
- kwargs['config'] = config
- #save ps1/ps2 if defined
- ps1 = None
- ps2 = None
- try:
- ps1 = sys.ps1
- ps2 = sys.ps2
- except AttributeError:
- pass
- #save previous instance
- saved_shell_instance = InteractiveShell._instance
- if saved_shell_instance is not None:
- cls = type(saved_shell_instance)
- cls.clear_instance()
+
+ # now, purge out the local namespace of IPython's hidden variables.
+ if local_ns is not None:
+ local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
+
+
+ # Restore original namespace so shell can shut down when we exit.
+ self.user_module = orig_user_module
+ self.user_ns = orig_user_ns
+ self.compile.flags = orig_compile_flags
+
+
+def embed(**kwargs):
+ """Call this to embed IPython at the current point in your program.
+
+ The first invocation of this will create an :class:`InteractiveShellEmbed`
+ instance and then call it. Consecutive calls just call the already
+ created instance.
+
+ If you don't want the kernel to initialize the namespace
+ from the scope of the surrounding function,
+ and/or you want to load full IPython configuration,
+ you probably want `IPython.start_ipython()` instead.
+
+ Here is a simple example::
+
+ from IPython import embed
+ a = 10
+ b = 20
+ embed(header='First time')
+ c = 30
+ d = 40
+ embed()
+
+ Full customization can be done by passing a :class:`Config` in as the
+ config argument.
+ """
+ config = kwargs.get('config')
+ header = kwargs.pop('header', u'')
+ compile_flags = kwargs.pop('compile_flags', None)
+ if config is None:
+ config = load_default_config()
+ config.InteractiveShellEmbed = config.TerminalInteractiveShell
+ kwargs['config'] = config
+ #save ps1/ps2 if defined
+ ps1 = None
+ ps2 = None
+ try:
+ ps1 = sys.ps1
+ ps2 = sys.ps2
+ except AttributeError:
+ pass
+ #save previous instance
+ saved_shell_instance = InteractiveShell._instance
+ if saved_shell_instance is not None:
+ cls = type(saved_shell_instance)
+ cls.clear_instance()
frame = sys._getframe(1)
shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % (
frame.f_code.co_filename, frame.f_lineno), **kwargs)
shell(header=header, stack_depth=2, compile_flags=compile_flags,
_call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno))
- InteractiveShellEmbed.clear_instance()
- #restore previous instance
- if saved_shell_instance is not None:
- cls = type(saved_shell_instance)
- cls.clear_instance()
- for subclass in cls._walk_mro():
- subclass._instance = saved_shell_instance
- if ps1 is not None:
- sys.ps1 = ps1
- sys.ps2 = ps2
+ InteractiveShellEmbed.clear_instance()
+ #restore previous instance
+ if saved_shell_instance is not None:
+ cls = type(saved_shell_instance)
+ cls.clear_instance()
+ for subclass in cls._walk_mro():
+ subclass._instance = saved_shell_instance
+ if ps1 is not None:
+ sys.ps1 = ps1
+ sys.ps2 = ps2
diff --git a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py
index e80f8c1503..f67cc6b502 100644
--- a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py
+++ b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py
@@ -1,18 +1,18 @@
"""IPython terminal interface using prompt_toolkit"""
-from __future__ import print_function
-
-import os
-import sys
+from __future__ import print_function
+
+import os
+import sys
import warnings
from warnings import warn
-
-from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
+
+from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
from IPython.utils import io
from IPython.utils.py3compat import PY3, cast_unicode_py2, input, string_types
-from IPython.utils.terminal import toggle_set_term_title, set_term_title
-from IPython.utils.process import abbrev_cwd
+from IPython.utils.terminal import toggle_set_term_title, set_term_title
+from IPython.utils.process import abbrev_cwd
from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union
-
+
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
@@ -22,7 +22,7 @@ from prompt_toolkit.interface import CommandLineInterface
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
-
+
from pygments.styles import get_style_by_name
from pygments.style import Style
from pygments.token import Token
@@ -59,23 +59,23 @@ _style_overrides_linux = {
-def get_default_editor():
- try:
- ed = os.environ['EDITOR']
+def get_default_editor():
+ try:
+ ed = os.environ['EDITOR']
if not PY3:
- ed = ed.decode()
- return ed
- except KeyError:
- pass
- except UnicodeError:
- warn("$EDITOR environment variable is not pure ASCII. Using platform "
- "default editor.")
-
- if os.name == 'posix':
- return 'vi' # the only one guaranteed to be there!
- else:
- return 'notepad' # same in Windows!
-
+ ed = ed.decode()
+ return ed
+ except KeyError:
+ pass
+ except UnicodeError:
+ warn("$EDITOR environment variable is not pure ASCII. Using platform "
+ "default editor.")
+
+ if os.name == 'posix':
+ return 'vi' # the only one guaranteed to be there!
+ else:
+ return 'notepad' # same in Windows!
+
# conservatively check for tty
# overridden streams can result in things like:
# - sys.stdin = None
@@ -87,116 +87,116 @@ for _name in ('stdin', 'stdout', 'stderr'):
break
else:
_is_tty = True
-
-
+
+
_use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
-
+
class TerminalInteractiveShell(InteractiveShell):
space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
'to reserve for the completion menu'
).tag(config=True)
-
+
def _space_for_menu_changed(self, old, new):
self._update_layout()
-
+
pt_cli = None
debugger_history = None
_pt_app = None
-
+
simple_prompt = Bool(_use_simple_prompt,
help="""Use `raw_input` for the REPL, without completion and prompt colors.
-
+
Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
IPython own testing machinery, and emacs inferior-shell integration through elpy.
-
+
This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
environment variable is set, or the current terminal is not a tty.
-
+
"""
).tag(config=True)
-
+
@property
def debugger_cls(self):
return Pdb if self.simple_prompt else TerminalPdb
-
+
confirm_exit = Bool(True,
help="""
Set to confirm when you try to exit IPython with an EOF (Control-D
in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
you can force a direct exit without any confirmation.""",
).tag(config=True)
-
+
editing_mode = Unicode('emacs',
help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
).tag(config=True)
-
+
mouse_support = Bool(False,
help="Enable mouse support in the prompt"
).tag(config=True)
-
+
# We don't load the list of styles for the help string, because loading
# Pygments plugins takes time and can cause unexpected errors.
highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
help="""The name or class of a Pygments style to use for syntax
highlighting. To see available styles, run `pygmentize -L styles`."""
).tag(config=True)
-
+
@observe('highlighting_style')
@observe('colors')
def _highlighting_style_changed(self, change):
self.refresh_style()
-
+
def refresh_style(self):
self._style = self._make_style_from_name_or_cls(self.highlighting_style)
-
-
+
+
highlighting_style_overrides = Dict(
help="Override highlighting format for specific tokens"
).tag(config=True)
-
+
true_color = Bool(False,
help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
"If your terminal supports true color, the following command "
"should print 'TRUECOLOR' in orange: "
"printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
).tag(config=True)
-
+
editor = Unicode(get_default_editor(),
help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
).tag(config=True)
-
+
prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
-
+
prompts = Instance(Prompts)
-
+
@default('prompts')
def _prompts_default(self):
return self.prompts_class(self)
-
+
@observe('prompts')
def _(self, change):
self._update_layout()
-
+
@default('displayhook_class')
def _displayhook_class_default(self):
return RichPromptDisplayHook
-
+
term_title = Bool(True,
help="Automatically set the terminal title"
).tag(config=True)
-
+
display_completions = Enum(('column', 'multicolumn','readlinelike'),
help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
"'readlinelike'. These options are for `prompt_toolkit`, see "
"`prompt_toolkit` documentation for more information."
),
default_value='multicolumn').tag(config=True)
-
+
highlight_matching_brackets = Bool(True,
help="Highlight matching brackets.",
).tag(config=True)
-
+
extra_open_editor_shortcuts = Bool(False,
help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
"This is in addition to the F2 binding, which is always enabled."
@@ -210,14 +210,14 @@ class TerminalInteractiveShell(InteractiveShell):
set_term_title('IPython: ' + abbrev_cwd())
else:
toggle_set_term_title(False)
-
+
def init_display_formatter(self):
super(TerminalInteractiveShell, self).init_display_formatter()
# terminal only supports plain text
self.display_formatter.active_types = ['text/plain']
# disable `_ipython_display_`
self.display_formatter.ipython_display_formatter.enabled = False
-
+
def init_prompt_toolkit_cli(self):
if self.simple_prompt:
# Fall back to plain non-interactive output for tests.
@@ -233,13 +233,13 @@ class TerminalInteractiveShell(InteractiveShell):
return isp.source_reset()
self.prompt_for_code = prompt
return
-
+
# Set up keyboard shortcuts
kbmanager = KeyBindingManager.for_prompt(
enable_open_in_editor=self.extra_open_editor_shortcuts,
)
register_ipython_shortcuts(kbmanager.registry, self)
-
+
# Pre-populate history from IPython's history database
history = InMemoryHistory()
last_cell = u""
@@ -250,12 +250,12 @@ class TerminalInteractiveShell(InteractiveShell):
if cell and (cell != last_cell):
history.append(cell)
last_cell = cell
-
+
self._style = self._make_style_from_name_or_cls(self.highlighting_style)
self.style = DynamicStyle(lambda: self._style)
-
+
editing_mode = getattr(EditingMode, self.editing_mode.upper())
-
+
def patch_stdout(**kwargs):
return self.pt_cli.patch_stdout_context(**kwargs)
@@ -274,13 +274,13 @@ class TerminalInteractiveShell(InteractiveShell):
self.pt_cli = CommandLineInterface(
self._pt_app, eventloop=self._eventloop,
output=create_output(true_color=self.true_color))
-
+
def _make_style_from_name_or_cls(self, name_or_cls):
"""
Small wrapper that make an IPython compatible style from a style name
-
+
We need that to add style for prompt ... etc.
- """
+ """
style_overrides = {}
if name_or_cls == 'legacy':
legacy = self.colors.lower()
@@ -336,9 +336,9 @@ class TerminalInteractiveShell(InteractiveShell):
style_overrides.update(self.highlighting_style_overrides)
style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
style_dict=style_overrides)
-
+
return style
-
+
def _layout_options(self):
"""
Return the current layout option for the current Terminal InteractiveShell
@@ -350,7 +350,7 @@ class TerminalInteractiveShell(InteractiveShell):
'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
'multiline':True,
'display_completions_in_columns': (self.display_completions == 'multicolumn'),
-
+
# Highlight matching brackets, but only when this setting is
# enabled, and only when the DEFAULT_BUFFER has the focus.
'extra_input_processors': [ConditionalProcessor(
@@ -358,20 +358,20 @@ class TerminalInteractiveShell(InteractiveShell):
filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
Condition(lambda cli: self.highlight_matching_brackets))],
}
-
+
def _update_layout(self):
- """
+ """
Ask for a re computation of the application layout, if for example ,
some configuration options have changed.
"""
if self._pt_app:
self._pt_app.layout = create_prompt_layout(**self._layout_options())
-
+
def prompt_for_code(self):
document = self.pt_cli.run(
pre_run=self.pre_prompt, reset_current_buffer=True)
return document.text
-
+
def enable_win_unicode_console(self):
if sys.version_info >= (3, 6):
# Since PEP 528, Python uses the unicode APIs for the Windows
@@ -379,36 +379,36 @@ class TerminalInteractiveShell(InteractiveShell):
return
import win_unicode_console
-
+
if PY3:
win_unicode_console.enable()
- else:
+ else:
# https://github.com/ipython/ipython/issues/9768
from win_unicode_console.streams import (TextStreamWrapper,
stdout_text_transcoded, stderr_text_transcoded)
-
+
class LenientStrStreamWrapper(TextStreamWrapper):
def write(self, s):
if isinstance(s, bytes):
s = s.decode(self.encoding, 'replace')
-
+
self.base.write(s)
-
+
stdout_text_str = LenientStrStreamWrapper(stdout_text_transcoded)
stderr_text_str = LenientStrStreamWrapper(stderr_text_transcoded)
-
+
win_unicode_console.enable(stdout=stdout_text_str,
stderr=stderr_text_str)
-
+
def init_io(self):
if sys.platform not in {'win32', 'cli'}:
return
-
+
self.enable_win_unicode_console()
-
+
import colorama
colorama.init()
-
+
# For some reason we make these wrappers around stdout/stderr.
# For now, we need to reset them so all output gets coloured.
# https://github.com/ipython/ipython/issues/8669
@@ -418,37 +418,37 @@ class TerminalInteractiveShell(InteractiveShell):
warnings.simplefilter('ignore', DeprecationWarning)
io.stdout = io.IOStream(sys.stdout)
io.stderr = io.IOStream(sys.stderr)
-
+
def init_magics(self):
super(TerminalInteractiveShell, self).init_magics()
self.register_magics(TerminalMagics)
-
- def init_alias(self):
- # The parent class defines aliases that can be safely used with any
- # frontend.
- super(TerminalInteractiveShell, self).init_alias()
-
- # Now define aliases that only make sense on the terminal, because they
- # need direct access to the console in a way that we can't emulate in
- # GUI or web frontend
- if os.name == 'posix':
+
+ def init_alias(self):
+ # The parent class defines aliases that can be safely used with any
+ # frontend.
+ super(TerminalInteractiveShell, self).init_alias()
+
+ # Now define aliases that only make sense on the terminal, because they
+ # need direct access to the console in a way that we can't emulate in
+ # GUI or web frontend
+ if os.name == 'posix':
for cmd in ['clear', 'more', 'less', 'man']:
self.alias_manager.soft_define_alias(cmd, cmd)
-
-
+
+
def __init__(self, *args, **kwargs):
super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
self.init_prompt_toolkit_cli()
self.init_term_title()
self.keep_running = True
-
+
self.debugger_history = InMemoryHistory()
-
+
def ask_exit(self):
self.keep_running = False
-
+
rl_next_input = None
-
+
def pre_prompt(self):
if self.rl_next_input:
# We can't set the buffer here, because it will be reset just after
@@ -464,34 +464,34 @@ class TerminalInteractiveShell(InteractiveShell):
# directly here.
set_doc()
self.rl_next_input = None
-
+
def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
-
+
if display_banner is not DISPLAY_BANNER_DEPRECATED:
warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
-
+
self.keep_running = True
while self.keep_running:
print(self.separate_in, end='')
-
- try:
+
+ try:
code = self.prompt_for_code()
except EOFError:
if (not self.confirm_exit) \
or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
self.ask_exit()
-
- else:
+
+ else:
if code:
self.run_cell(code, store_history=True)
-
+
def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
# An extra layer of protection in case someone mashing Ctrl-C breaks
# out of our internal code.
if display_banner is not DISPLAY_BANNER_DEPRECATED:
warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
while True:
- try:
+ try:
self.interact()
break
except KeyboardInterrupt as e:
@@ -503,12 +503,12 @@ class TerminalInteractiveShell(InteractiveShell):
# https://github.com/ipython/ipython/pull/9867
if hasattr(self, '_eventloop'):
self._eventloop.stop()
-
+
_inputhook = None
def inputhook(self, context):
if self._inputhook is not None:
self._inputhook(context)
-
+
active_eventloop = None
def enable_gui(self, gui=None):
if gui:
@@ -516,24 +516,24 @@ class TerminalInteractiveShell(InteractiveShell):
get_inputhook_name_and_func(gui)
else:
self.active_eventloop = self._inputhook = None
-
+
# Run !system commands directly, not through pipes, so terminal programs
# work correctly.
system = InteractiveShell.system_raw
-
+
def auto_rewrite_input(self, cmd):
"""Overridden from the parent class to use fancy rewriting prompt"""
if not self.show_rewritten_input:
return
-
+
tokens = self.prompts.rewrite_prompt_tokens()
if self.pt_cli:
self.pt_cli.print_tokens(tokens)
print(cmd)
- else:
+ else:
prompt = ''.join(s for t, s in tokens)
print(prompt, cmd, sep='')
-
+
_prompts_before = None
def switch_doctest_mode(self, mode):
"""Switch prompts to classic for %doctest_mode"""
@@ -544,9 +544,9 @@ class TerminalInteractiveShell(InteractiveShell):
self.prompts = self._prompts_before
self._prompts_before = None
self._update_layout()
-
-
+
+
InteractiveShellABC.register(TerminalInteractiveShell)
-
+
if __name__ == '__main__':
TerminalInteractiveShell.instance().interact()
diff --git a/contrib/python/ipython/py2/IPython/terminal/ipapp.py b/contrib/python/ipython/py2/IPython/terminal/ipapp.py
index f8136ef0b6..6b25aaa3e3 100755
--- a/contrib/python/ipython/py2/IPython/terminal/ipapp.py
+++ b/contrib/python/ipython/py2/IPython/terminal/ipapp.py
@@ -1,190 +1,190 @@
-#!/usr/bin/env python
-# encoding: utf-8
-"""
-The :class:`~IPython.core.application.Application` object for the command
-line :command:`ipython` program.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import absolute_import
-from __future__ import print_function
-
-import logging
-import os
-import sys
+#!/usr/bin/env python
+# encoding: utf-8
+"""
+The :class:`~IPython.core.application.Application` object for the command
+line :command:`ipython` program.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import absolute_import
+from __future__ import print_function
+
+import logging
+import os
+import sys
import warnings
-
-from traitlets.config.loader import Config
-from traitlets.config.application import boolean_flag, catch_config_error, Application
-from IPython.core import release
-from IPython.core import usage
-from IPython.core.completer import IPCompleter
-from IPython.core.crashhandler import CrashHandler
-from IPython.core.formatters import PlainTextFormatter
-from IPython.core.history import HistoryManager
-from IPython.core.application import (
- ProfileDir, BaseIPythonApplication, base_flags, base_aliases
-)
-from IPython.core.magics import ScriptMagics
-from IPython.core.shellapp import (
- InteractiveShellApp, shell_flags, shell_aliases
-)
-from IPython.extensions.storemagic import StoreMagics
+
+from traitlets.config.loader import Config
+from traitlets.config.application import boolean_flag, catch_config_error, Application
+from IPython.core import release
+from IPython.core import usage
+from IPython.core.completer import IPCompleter
+from IPython.core.crashhandler import CrashHandler
+from IPython.core.formatters import PlainTextFormatter
+from IPython.core.history import HistoryManager
+from IPython.core.application import (
+ ProfileDir, BaseIPythonApplication, base_flags, base_aliases
+)
+from IPython.core.magics import ScriptMagics
+from IPython.core.shellapp import (
+ InteractiveShellApp, shell_flags, shell_aliases
+)
+from IPython.extensions.storemagic import StoreMagics
from .interactiveshell import TerminalInteractiveShell
-from IPython.paths import get_ipython_dir
-from traitlets import (
+from IPython.paths import get_ipython_dir
+from traitlets import (
Bool, List, Dict, default, observe, Type
-)
-
-#-----------------------------------------------------------------------------
-# Globals, utilities and helpers
-#-----------------------------------------------------------------------------
-
-_examples = """
-ipython --matplotlib # enable matplotlib integration
-ipython --matplotlib=qt # enable matplotlib integration with qt4 backend
-
-ipython --log-level=DEBUG # set logging to DEBUG
-ipython --profile=foo # start with profile foo
-
-ipython profile create foo # create profile foo w/ default config files
-ipython help profile # show the help for the profile subcmd
-
-ipython locate # print the path to the IPython directory
-ipython locate profile foo # print the path to the directory for profile `foo`
-"""
-
-#-----------------------------------------------------------------------------
-# Crash handler for this application
-#-----------------------------------------------------------------------------
-
-class IPAppCrashHandler(CrashHandler):
- """sys.excepthook for IPython itself, leaves a detailed report on disk."""
-
- def __init__(self, app):
- contact_name = release.author
- contact_email = release.author_email
- bug_tracker = 'https://github.com/ipython/ipython/issues'
- super(IPAppCrashHandler,self).__init__(
- app, contact_name, contact_email, bug_tracker
- )
-
- def make_report(self,traceback):
- """Return a string containing a crash report."""
-
- sec_sep = self.section_sep
- # Start with parent report
- report = [super(IPAppCrashHandler, self).make_report(traceback)]
- # Add interactive-specific info we may have
- rpt_add = report.append
- try:
- rpt_add(sec_sep+"History of session input:")
- for line in self.app.shell.user_ns['_ih']:
- rpt_add(line)
- rpt_add('\n*** Last line of input (may not be in above history):\n')
- rpt_add(self.app.shell._last_input_line+'\n')
- except:
- pass
-
- return ''.join(report)
-
-#-----------------------------------------------------------------------------
-# Aliases and Flags
-#-----------------------------------------------------------------------------
-flags = dict(base_flags)
-flags.update(shell_flags)
-frontend_flags = {}
-addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
-addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
- 'Turn on auto editing of files with syntax errors.',
- 'Turn off auto editing of files with syntax errors.'
-)
+)
+
+#-----------------------------------------------------------------------------
+# Globals, utilities and helpers
+#-----------------------------------------------------------------------------
+
+_examples = """
+ipython --matplotlib # enable matplotlib integration
+ipython --matplotlib=qt # enable matplotlib integration with qt4 backend
+
+ipython --log-level=DEBUG # set logging to DEBUG
+ipython --profile=foo # start with profile foo
+
+ipython profile create foo # create profile foo w/ default config files
+ipython help profile # show the help for the profile subcmd
+
+ipython locate # print the path to the IPython directory
+ipython locate profile foo # print the path to the directory for profile `foo`
+"""
+
+#-----------------------------------------------------------------------------
+# Crash handler for this application
+#-----------------------------------------------------------------------------
+
+class IPAppCrashHandler(CrashHandler):
+ """sys.excepthook for IPython itself, leaves a detailed report on disk."""
+
+ def __init__(self, app):
+ contact_name = release.author
+ contact_email = release.author_email
+ bug_tracker = 'https://github.com/ipython/ipython/issues'
+ super(IPAppCrashHandler,self).__init__(
+ app, contact_name, contact_email, bug_tracker
+ )
+
+ def make_report(self,traceback):
+ """Return a string containing a crash report."""
+
+ sec_sep = self.section_sep
+ # Start with parent report
+ report = [super(IPAppCrashHandler, self).make_report(traceback)]
+ # Add interactive-specific info we may have
+ rpt_add = report.append
+ try:
+ rpt_add(sec_sep+"History of session input:")
+ for line in self.app.shell.user_ns['_ih']:
+ rpt_add(line)
+ rpt_add('\n*** Last line of input (may not be in above history):\n')
+ rpt_add(self.app.shell._last_input_line+'\n')
+ except:
+ pass
+
+ return ''.join(report)
+
+#-----------------------------------------------------------------------------
+# Aliases and Flags
+#-----------------------------------------------------------------------------
+flags = dict(base_flags)
+flags.update(shell_flags)
+frontend_flags = {}
+addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
+addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
+ 'Turn on auto editing of files with syntax errors.',
+ 'Turn off auto editing of files with syntax errors.'
+)
addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt',
"Force simple minimal prompt using `raw_input`",
"Use a rich interactive prompt with prompt_toolkit",
)
-addflag('banner', 'TerminalIPythonApp.display_banner',
- "Display a banner upon starting IPython.",
- "Don't display a banner upon starting IPython."
-)
-addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
- """Set to confirm when you try to exit IPython with an EOF (Control-D
- in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
- you can force a direct exit without any confirmation.""",
- "Don't prompt the user when exiting."
-)
-addflag('term-title', 'TerminalInteractiveShell.term_title',
- "Enable auto setting the terminal title.",
- "Disable auto setting the terminal title."
-)
-classic_config = Config()
-classic_config.InteractiveShell.cache_size = 0
-classic_config.PlainTextFormatter.pprint = False
+addflag('banner', 'TerminalIPythonApp.display_banner',
+ "Display a banner upon starting IPython.",
+ "Don't display a banner upon starting IPython."
+)
+addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
+ """Set to confirm when you try to exit IPython with an EOF (Control-D
+ in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
+ you can force a direct exit without any confirmation.""",
+ "Don't prompt the user when exiting."
+)
+addflag('term-title', 'TerminalInteractiveShell.term_title',
+ "Enable auto setting the terminal title.",
+ "Disable auto setting the terminal title."
+)
+classic_config = Config()
+classic_config.InteractiveShell.cache_size = 0
+classic_config.PlainTextFormatter.pprint = False
classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts'
-classic_config.InteractiveShell.separate_in = ''
-classic_config.InteractiveShell.separate_out = ''
-classic_config.InteractiveShell.separate_out2 = ''
-classic_config.InteractiveShell.colors = 'NoColor'
-classic_config.InteractiveShell.xmode = 'Plain'
-
-frontend_flags['classic']=(
- classic_config,
- "Gives IPython a similar feel to the classic Python prompt."
-)
-# # log doesn't make so much sense this way anymore
-# paa('--log','-l',
-# action='store_true', dest='InteractiveShell.logstart',
-# help="Start logging to the default log file (./ipython_log.py).")
-#
-# # quick is harder to implement
-frontend_flags['quick']=(
- {'TerminalIPythonApp' : {'quick' : True}},
- "Enable quick startup with no config files."
-)
-
-frontend_flags['i'] = (
- {'TerminalIPythonApp' : {'force_interact' : True}},
- """If running code from the command line, become interactive afterwards.
- It is often useful to follow this with `--` to treat remaining flags as
- script arguments.
- """
-)
-flags.update(frontend_flags)
-
-aliases = dict(base_aliases)
-aliases.update(shell_aliases)
-
-#-----------------------------------------------------------------------------
-# Main classes and functions
-#-----------------------------------------------------------------------------
-
-
-class LocateIPythonApp(BaseIPythonApplication):
- description = """print the path to the IPython dir"""
- subcommands = Dict(dict(
- profile=('IPython.core.profileapp.ProfileLocate',
- "print the path to an IPython profile directory",
- ),
- ))
- def start(self):
- if self.subapp is not None:
- return self.subapp.start()
- else:
- print(self.ipython_dir)
-
-
-class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
- name = u'ipython'
- description = usage.cl_usage
- crash_handler_class = IPAppCrashHandler
- examples = _examples
-
- flags = Dict(flags)
- aliases = Dict(aliases)
- classes = List()
+classic_config.InteractiveShell.separate_in = ''
+classic_config.InteractiveShell.separate_out = ''
+classic_config.InteractiveShell.separate_out2 = ''
+classic_config.InteractiveShell.colors = 'NoColor'
+classic_config.InteractiveShell.xmode = 'Plain'
+
+frontend_flags['classic']=(
+ classic_config,
+ "Gives IPython a similar feel to the classic Python prompt."
+)
+# # log doesn't make so much sense this way anymore
+# paa('--log','-l',
+# action='store_true', dest='InteractiveShell.logstart',
+# help="Start logging to the default log file (./ipython_log.py).")
+#
+# # quick is harder to implement
+frontend_flags['quick']=(
+ {'TerminalIPythonApp' : {'quick' : True}},
+ "Enable quick startup with no config files."
+)
+
+frontend_flags['i'] = (
+ {'TerminalIPythonApp' : {'force_interact' : True}},
+ """If running code from the command line, become interactive afterwards.
+ It is often useful to follow this with `--` to treat remaining flags as
+ script arguments.
+ """
+)
+flags.update(frontend_flags)
+
+aliases = dict(base_aliases)
+aliases.update(shell_aliases)
+
+#-----------------------------------------------------------------------------
+# Main classes and functions
+#-----------------------------------------------------------------------------
+
+
+class LocateIPythonApp(BaseIPythonApplication):
+ description = """print the path to the IPython dir"""
+ subcommands = Dict(dict(
+ profile=('IPython.core.profileapp.ProfileLocate',
+ "print the path to an IPython profile directory",
+ ),
+ ))
+ def start(self):
+ if self.subapp is not None:
+ return self.subapp.start()
+ else:
+ print(self.ipython_dir)
+
+
+class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
+ name = u'ipython'
+ description = usage.cl_usage
+ crash_handler_class = IPAppCrashHandler
+ examples = _examples
+
+ flags = Dict(flags)
+ aliases = Dict(aliases)
+ classes = List()
interactive_shell_class = Type(
klass=object, # use default_value otherwise which only allow subclasses.
@@ -193,185 +193,185 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
).tag(config=True)
@default('classes')
- def _classes_default(self):
- """This has to be in a method, for TerminalIPythonApp to be available."""
- return [
- InteractiveShellApp, # ShellApp comes before TerminalApp, because
- self.__class__, # it will also affect subclasses (e.g. QtConsole)
- TerminalInteractiveShell,
- HistoryManager,
- ProfileDir,
- PlainTextFormatter,
- IPCompleter,
- ScriptMagics,
- StoreMagics,
- ]
-
- deprecated_subcommands = dict(
- qtconsole=('qtconsole.qtconsoleapp.JupyterQtConsoleApp',
- """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter Qt Console."""
- ),
- notebook=('notebook.notebookapp.NotebookApp',
- """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter HTML Notebook Server."""
- ),
- console=('jupyter_console.app.ZMQTerminalIPythonApp',
- """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter terminal-based Console."""
- ),
- nbconvert=('nbconvert.nbconvertapp.NbConvertApp',
- "DEPRECATED, Will be removed in IPython 6.0 : Convert notebooks to/from other formats."
- ),
- trust=('nbformat.sign.TrustNotebookApp',
- "DEPRECATED, Will be removed in IPython 6.0 : Sign notebooks to trust their potentially unsafe contents at load."
- ),
- kernelspec=('jupyter_client.kernelspecapp.KernelSpecApp',
- "DEPRECATED, Will be removed in IPython 6.0 : Manage Jupyter kernel specifications."
- ),
- )
- subcommands = dict(
- profile = ("IPython.core.profileapp.ProfileApp",
- "Create and manage IPython profiles."
- ),
- kernel = ("ipykernel.kernelapp.IPKernelApp",
- "Start a kernel without an attached frontend."
- ),
- locate=('IPython.terminal.ipapp.LocateIPythonApp',
- LocateIPythonApp.description
- ),
- history=('IPython.core.historyapp.HistoryApp',
- "Manage the IPython history database."
- ),
- )
- deprecated_subcommands['install-nbextension'] = (
- "notebook.nbextensions.InstallNBExtensionApp",
- "DEPRECATED, Will be removed in IPython 6.0 : Install Jupyter notebook extension files"
- )
- subcommands.update(deprecated_subcommands)
-
- # *do* autocreate requested profile, but don't create the config file.
- auto_create=Bool(True)
- # configurables
+ def _classes_default(self):
+ """This has to be in a method, for TerminalIPythonApp to be available."""
+ return [
+ InteractiveShellApp, # ShellApp comes before TerminalApp, because
+ self.__class__, # it will also affect subclasses (e.g. QtConsole)
+ TerminalInteractiveShell,
+ HistoryManager,
+ ProfileDir,
+ PlainTextFormatter,
+ IPCompleter,
+ ScriptMagics,
+ StoreMagics,
+ ]
+
+ deprecated_subcommands = dict(
+ qtconsole=('qtconsole.qtconsoleapp.JupyterQtConsoleApp',
+ """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter Qt Console."""
+ ),
+ notebook=('notebook.notebookapp.NotebookApp',
+ """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter HTML Notebook Server."""
+ ),
+ console=('jupyter_console.app.ZMQTerminalIPythonApp',
+ """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter terminal-based Console."""
+ ),
+ nbconvert=('nbconvert.nbconvertapp.NbConvertApp',
+ "DEPRECATED, Will be removed in IPython 6.0 : Convert notebooks to/from other formats."
+ ),
+ trust=('nbformat.sign.TrustNotebookApp',
+ "DEPRECATED, Will be removed in IPython 6.0 : Sign notebooks to trust their potentially unsafe contents at load."
+ ),
+ kernelspec=('jupyter_client.kernelspecapp.KernelSpecApp',
+ "DEPRECATED, Will be removed in IPython 6.0 : Manage Jupyter kernel specifications."
+ ),
+ )
+ subcommands = dict(
+ profile = ("IPython.core.profileapp.ProfileApp",
+ "Create and manage IPython profiles."
+ ),
+ kernel = ("ipykernel.kernelapp.IPKernelApp",
+ "Start a kernel without an attached frontend."
+ ),
+ locate=('IPython.terminal.ipapp.LocateIPythonApp',
+ LocateIPythonApp.description
+ ),
+ history=('IPython.core.historyapp.HistoryApp',
+ "Manage the IPython history database."
+ ),
+ )
+ deprecated_subcommands['install-nbextension'] = (
+ "notebook.nbextensions.InstallNBExtensionApp",
+ "DEPRECATED, Will be removed in IPython 6.0 : Install Jupyter notebook extension files"
+ )
+ subcommands.update(deprecated_subcommands)
+
+ # *do* autocreate requested profile, but don't create the config file.
+ auto_create=Bool(True)
+ # configurables
quick = Bool(False,
- help="""Start IPython quickly by skipping the loading of config files."""
+ help="""Start IPython quickly by skipping the loading of config files."""
).tag(config=True)
@observe('quick')
def _quick_changed(self, change):
if change['new']:
- self.load_config_file = lambda *a, **kw: None
-
+ self.load_config_file = lambda *a, **kw: None
+
display_banner = Bool(True,
- help="Whether to display a banner upon starting IPython."
+ help="Whether to display a banner upon starting IPython."
).tag(config=True)
-
- # if there is code of files to run from the cmd line, don't interact
- # unless the --i flag (App.force_interact) is true.
+
+ # if there is code of files to run from the cmd line, don't interact
+ # unless the --i flag (App.force_interact) is true.
force_interact = Bool(False,
- help="""If a command or file is given via the command-line,
- e.g. 'ipython foo.py', start an interactive shell after executing the
- file or command."""
+ help="""If a command or file is given via the command-line,
+ e.g. 'ipython foo.py', start an interactive shell after executing the
+ file or command."""
).tag(config=True)
@observe('force_interact')
def _force_interact_changed(self, change):
if change['new']:
- self.interact = True
-
+ self.interact = True
+
@observe('file_to_run', 'code_to_run', 'module_to_run')
def _file_to_run_changed(self, change):
new = change['new']
- if new:
- self.something_to_run = True
- if new and not self.force_interact:
- self.interact = False
-
- # internal, not-configurable
- something_to_run=Bool(False)
-
- def parse_command_line(self, argv=None):
- """override to allow old '-pylab' flag with deprecation warning"""
-
- argv = sys.argv[1:] if argv is None else argv
-
- if '-pylab' in argv:
- # deprecated `-pylab` given,
- # warn and transform into current syntax
- argv = argv[:] # copy, don't clobber
- idx = argv.index('-pylab')
+ if new:
+ self.something_to_run = True
+ if new and not self.force_interact:
+ self.interact = False
+
+ # internal, not-configurable
+ something_to_run=Bool(False)
+
+ def parse_command_line(self, argv=None):
+ """override to allow old '-pylab' flag with deprecation warning"""
+
+ argv = sys.argv[1:] if argv is None else argv
+
+ if '-pylab' in argv:
+ # deprecated `-pylab` given,
+ # warn and transform into current syntax
+ argv = argv[:] # copy, don't clobber
+ idx = argv.index('-pylab')
warnings.warn("`-pylab` flag has been deprecated.\n"
- " Use `--matplotlib <backend>` and import pylab manually.")
- argv[idx] = '--pylab'
-
- return super(TerminalIPythonApp, self).parse_command_line(argv)
-
- @catch_config_error
- def initialize(self, argv=None):
- """Do actions after construct, but before starting the app."""
- super(TerminalIPythonApp, self).initialize(argv)
- if self.subapp is not None:
- # don't bother initializing further, starting subapp
- return
- # print self.extra_args
- if self.extra_args and not self.something_to_run:
- self.file_to_run = self.extra_args[0]
- self.init_path()
- # create the shell
- self.init_shell()
- # and draw the banner
- self.init_banner()
- # Now a variety of things that happen after the banner is printed.
- self.init_gui_pylab()
- self.init_extensions()
- self.init_code()
-
- def init_shell(self):
- """initialize the InteractiveShell instance"""
- # Create an InteractiveShell instance.
- # shell.display_banner should always be False for the terminal
- # based app, because we call shell.show_banner() by hand below
- # so the banner shows *before* all extension loading stuff.
+ " Use `--matplotlib <backend>` and import pylab manually.")
+ argv[idx] = '--pylab'
+
+ return super(TerminalIPythonApp, self).parse_command_line(argv)
+
+ @catch_config_error
+ def initialize(self, argv=None):
+ """Do actions after construct, but before starting the app."""
+ super(TerminalIPythonApp, self).initialize(argv)
+ if self.subapp is not None:
+ # don't bother initializing further, starting subapp
+ return
+ # print self.extra_args
+ if self.extra_args and not self.something_to_run:
+ self.file_to_run = self.extra_args[0]
+ self.init_path()
+ # create the shell
+ self.init_shell()
+ # and draw the banner
+ self.init_banner()
+ # Now a variety of things that happen after the banner is printed.
+ self.init_gui_pylab()
+ self.init_extensions()
+ self.init_code()
+
+ def init_shell(self):
+ """initialize the InteractiveShell instance"""
+ # Create an InteractiveShell instance.
+ # shell.display_banner should always be False for the terminal
+ # based app, because we call shell.show_banner() by hand below
+ # so the banner shows *before* all extension loading stuff.
self.shell = self.interactive_shell_class.instance(parent=self,
profile_dir=self.profile_dir,
- ipython_dir=self.ipython_dir, user_ns=self.user_ns)
- self.shell.configurables.append(self)
-
- def init_banner(self):
- """optionally display the banner"""
- if self.display_banner and self.interact:
- self.shell.show_banner()
- # Make sure there is a space below the banner.
- if self.log_level <= logging.INFO: print()
-
- def _pylab_changed(self, name, old, new):
- """Replace --pylab='inline' with --pylab='auto'"""
- if new == 'inline':
+ ipython_dir=self.ipython_dir, user_ns=self.user_ns)
+ self.shell.configurables.append(self)
+
+ def init_banner(self):
+ """optionally display the banner"""
+ if self.display_banner and self.interact:
+ self.shell.show_banner()
+ # Make sure there is a space below the banner.
+ if self.log_level <= logging.INFO: print()
+
+ def _pylab_changed(self, name, old, new):
+ """Replace --pylab='inline' with --pylab='auto'"""
+ if new == 'inline':
warnings.warn("'inline' not available as pylab backend, "
- "using 'auto' instead.")
- self.pylab = 'auto'
-
- def start(self):
- if self.subapp is not None:
- return self.subapp.start()
- # perform any prexec steps:
- if self.interact:
- self.log.debug("Starting IPython's mainloop...")
- self.shell.mainloop()
- else:
- self.log.debug("IPython not interactive...")
-
-def load_default_config(ipython_dir=None):
- """Load the default config file from the default ipython_dir.
-
- This is useful for embedded shells.
- """
- if ipython_dir is None:
- ipython_dir = get_ipython_dir()
-
- profile_dir = os.path.join(ipython_dir, 'profile_default')
+ "using 'auto' instead.")
+ self.pylab = 'auto'
+
+ def start(self):
+ if self.subapp is not None:
+ return self.subapp.start()
+ # perform any prexec steps:
+ if self.interact:
+ self.log.debug("Starting IPython's mainloop...")
+ self.shell.mainloop()
+ else:
+ self.log.debug("IPython not interactive...")
+
+def load_default_config(ipython_dir=None):
+ """Load the default config file from the default ipython_dir.
+
+ This is useful for embedded shells.
+ """
+ if ipython_dir is None:
+ ipython_dir = get_ipython_dir()
+
+ profile_dir = os.path.join(ipython_dir, 'profile_default')
app = TerminalIPythonApp()
app.config_file_paths.append(profile_dir)
app.load_config_file()
return app.config
-
-launch_new_instance = TerminalIPythonApp.launch_instance
-
-
-if __name__ == '__main__':
- launch_new_instance()
+
+launch_new_instance = TerminalIPythonApp.launch_instance
+
+
+if __name__ == '__main__':
+ launch_new_instance()
diff --git a/contrib/python/ipython/py2/IPython/testing/__init__.py b/contrib/python/ipython/py2/IPython/testing/__init__.py
index 6011b39f77..165f503169 100644
--- a/contrib/python/ipython/py2/IPython/testing/__init__.py
+++ b/contrib/python/ipython/py2/IPython/testing/__init__.py
@@ -1,38 +1,38 @@
-"""Testing support (tools to test IPython itself).
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2009-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Functions
-#-----------------------------------------------------------------------------
-
-# User-level entry point for testing
-def test(**kwargs):
- """Run the entire IPython test suite.
-
- Any of the options for run_iptestall() may be passed as keyword arguments.
-
- For example::
-
- IPython.test(testgroups=['lib', 'config', 'utils'], fast=2)
-
- will run those three sections of the test suite, using two processes.
- """
-
- # Do the import internally, so that this function doesn't increase total
- # import time
- from .iptestcontroller import run_iptestall, default_options
- options = default_options()
- for name, val in kwargs.items():
- setattr(options, name, val)
- run_iptestall(options)
-
-# So nose doesn't try to run this as a test itself and we end up with an
-# infinite test loop
-test.__test__ = False
+"""Testing support (tools to test IPython itself).
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2009-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Functions
+#-----------------------------------------------------------------------------
+
+# User-level entry point for testing
+def test(**kwargs):
+ """Run the entire IPython test suite.
+
+ Any of the options for run_iptestall() may be passed as keyword arguments.
+
+ For example::
+
+ IPython.test(testgroups=['lib', 'config', 'utils'], fast=2)
+
+ will run those three sections of the test suite, using two processes.
+ """
+
+ # Do the import internally, so that this function doesn't increase total
+ # import time
+ from .iptestcontroller import run_iptestall, default_options
+ options = default_options()
+ for name, val in kwargs.items():
+ setattr(options, name, val)
+ run_iptestall(options)
+
+# So nose doesn't try to run this as a test itself and we end up with an
+# infinite test loop
+test.__test__ = False
diff --git a/contrib/python/ipython/py2/IPython/testing/__main__.py b/contrib/python/ipython/py2/IPython/testing/__main__.py
index 179ec6f699..4b0bb8ba9c 100644
--- a/contrib/python/ipython/py2/IPython/testing/__main__.py
+++ b/contrib/python/ipython/py2/IPython/testing/__main__.py
@@ -1,3 +1,3 @@
-if __name__ == '__main__':
- from IPython.testing import iptestcontroller
- iptestcontroller.main()
+if __name__ == '__main__':
+ from IPython.testing import iptestcontroller
+ iptestcontroller.main()
diff --git a/contrib/python/ipython/py2/IPython/testing/decorators.py b/contrib/python/ipython/py2/IPython/testing/decorators.py
index 2fe72f6cae..c9807ce70e 100644
--- a/contrib/python/ipython/py2/IPython/testing/decorators.py
+++ b/contrib/python/ipython/py2/IPython/testing/decorators.py
@@ -1,384 +1,384 @@
-# -*- coding: utf-8 -*-
-"""Decorators for labeling test objects.
-
-Decorators that merely return a modified version of the original function
-object are straightforward. Decorators that return a new function object need
-to use nose.tools.make_decorator(original_function)(decorator) in returning the
-decorator, in order to preserve metadata such as function name, setup and
-teardown functions and so on - see nose.tools for more information.
-
-This module provides a set of useful decorators meant to be ready to use in
-your own tests. See the bottom of the file for the ready-made ones, and if you
-find yourself writing a new one that may be of generic use, add it here.
-
-Included decorators:
-
-
-Lightweight testing that remains unittest-compatible.
-
-- An @as_unittest decorator can be used to tag any normal parameter-less
- function as a unittest TestCase. Then, both nose and normal unittest will
- recognize it as such. This will make it easier to migrate away from Nose if
- we ever need/want to while maintaining very lightweight tests.
-
-NOTE: This file contains IPython-specific decorators. Using the machinery in
-IPython.external.decorators, we import either numpy.testing.decorators if numpy is
-available, OR use equivalent code in IPython.external._decorators, which
-we've copied verbatim from numpy.
-
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import sys
-import os
-import tempfile
-import unittest
-import warnings
-
-from decorator import decorator
-
-# Expose the unittest-driven decorators
-from .ipunittest import ipdoctest, ipdocstring
-
-# Grab the numpy-specific decorators which we keep in a file that we
-# occasionally update from upstream: decorators.py is a copy of
-# numpy.testing.decorators, we expose all of it here.
-from IPython.external.decorators import *
-
-# For onlyif_cmd_exists decorator
+# -*- coding: utf-8 -*-
+"""Decorators for labeling test objects.
+
+Decorators that merely return a modified version of the original function
+object are straightforward. Decorators that return a new function object need
+to use nose.tools.make_decorator(original_function)(decorator) in returning the
+decorator, in order to preserve metadata such as function name, setup and
+teardown functions and so on - see nose.tools for more information.
+
+This module provides a set of useful decorators meant to be ready to use in
+your own tests. See the bottom of the file for the ready-made ones, and if you
+find yourself writing a new one that may be of generic use, add it here.
+
+Included decorators:
+
+
+Lightweight testing that remains unittest-compatible.
+
+- An @as_unittest decorator can be used to tag any normal parameter-less
+ function as a unittest TestCase. Then, both nose and normal unittest will
+ recognize it as such. This will make it easier to migrate away from Nose if
+ we ever need/want to while maintaining very lightweight tests.
+
+NOTE: This file contains IPython-specific decorators. Using the machinery in
+IPython.external.decorators, we import either numpy.testing.decorators if numpy is
+available, OR use equivalent code in IPython.external._decorators, which
+we've copied verbatim from numpy.
+
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import sys
+import os
+import tempfile
+import unittest
+import warnings
+
+from decorator import decorator
+
+# Expose the unittest-driven decorators
+from .ipunittest import ipdoctest, ipdocstring
+
+# Grab the numpy-specific decorators which we keep in a file that we
+# occasionally update from upstream: decorators.py is a copy of
+# numpy.testing.decorators, we expose all of it here.
+from IPython.external.decorators import *
+
+# For onlyif_cmd_exists decorator
from IPython.utils.py3compat import string_types, which, PY2, PY3, PYPY
-
-#-----------------------------------------------------------------------------
-# Classes and functions
-#-----------------------------------------------------------------------------
-
-# Simple example of the basic idea
-def as_unittest(func):
- """Decorator to make a simple function into a normal test via unittest."""
- class Tester(unittest.TestCase):
- def test(self):
- func()
-
- Tester.__name__ = func.__name__
-
- return Tester
-
-# Utility functions
-
+
+#-----------------------------------------------------------------------------
+# Classes and functions
+#-----------------------------------------------------------------------------
+
+# Simple example of the basic idea
+def as_unittest(func):
+ """Decorator to make a simple function into a normal test via unittest."""
+ class Tester(unittest.TestCase):
+ def test(self):
+ func()
+
+ Tester.__name__ = func.__name__
+
+ return Tester
+
+# Utility functions
+
def apply_wrapper(wrapper, func):
- """Apply a wrapper to a function for decoration.
-
- This mixes Michele Simionato's decorator tool with nose's make_decorator,
- to apply a wrapper in a decorator so that all nose attributes, as well as
- function signature and other properties, survive the decoration cleanly.
- This will ensure that wrapped functions can still be well introspected via
- IPython, for example.
- """
+ """Apply a wrapper to a function for decoration.
+
+ This mixes Michele Simionato's decorator tool with nose's make_decorator,
+ to apply a wrapper in a decorator so that all nose attributes, as well as
+ function signature and other properties, survive the decoration cleanly.
+ This will ensure that wrapped functions can still be well introspected via
+ IPython, for example.
+ """
warnings.warn("The function `apply_wrapper` is deprecated since IPython 4.0",
DeprecationWarning, stacklevel=2)
- import nose.tools
-
- return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
-
-
+ import nose.tools
+
+ return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
+
+
def make_label_dec(label, ds=None):
- """Factory function to create a decorator that applies one or more labels.
-
- Parameters
- ----------
- label : string or sequence
- One or more labels that will be applied by the decorator to the functions
- it decorates. Labels are attributes of the decorated function with their
- value set to True.
-
- ds : string
- An optional docstring for the resulting decorator. If not given, a
- default docstring is auto-generated.
-
- Returns
- -------
- A decorator.
-
- Examples
- --------
-
- A simple labeling decorator:
-
- >>> slow = make_label_dec('slow')
- >>> slow.__doc__
- "Labels a test as 'slow'."
-
- And one that uses multiple labels and a custom docstring:
-
- >>> rare = make_label_dec(['slow','hard'],
- ... "Mix labels 'slow' and 'hard' for rare tests.")
- >>> rare.__doc__
- "Mix labels 'slow' and 'hard' for rare tests."
-
- Now, let's test using this one:
- >>> @rare
- ... def f(): pass
- ...
- >>>
- >>> f.slow
- True
- >>> f.hard
- True
- """
-
+ """Factory function to create a decorator that applies one or more labels.
+
+ Parameters
+ ----------
+ label : string or sequence
+ One or more labels that will be applied by the decorator to the functions
+ it decorates. Labels are attributes of the decorated function with their
+ value set to True.
+
+ ds : string
+ An optional docstring for the resulting decorator. If not given, a
+ default docstring is auto-generated.
+
+ Returns
+ -------
+ A decorator.
+
+ Examples
+ --------
+
+ A simple labeling decorator:
+
+ >>> slow = make_label_dec('slow')
+ >>> slow.__doc__
+ "Labels a test as 'slow'."
+
+ And one that uses multiple labels and a custom docstring:
+
+ >>> rare = make_label_dec(['slow','hard'],
+ ... "Mix labels 'slow' and 'hard' for rare tests.")
+ >>> rare.__doc__
+ "Mix labels 'slow' and 'hard' for rare tests."
+
+ Now, let's test using this one:
+ >>> @rare
+ ... def f(): pass
+ ...
+ >>>
+ >>> f.slow
+ True
+ >>> f.hard
+ True
+ """
+
warnings.warn("The function `make_label_dec` is deprecated since IPython 4.0",
DeprecationWarning, stacklevel=2)
- if isinstance(label, string_types):
- labels = [label]
- else:
- labels = label
-
- # Validate that the given label(s) are OK for use in setattr() by doing a
- # dry run on a dummy function.
- tmp = lambda : None
- for label in labels:
- setattr(tmp,label,True)
-
- # This is the actual decorator we'll return
- def decor(f):
- for label in labels:
- setattr(f,label,True)
- return f
-
- # Apply the user's docstring, or autogenerate a basic one
- if ds is None:
- ds = "Labels a test as %r." % label
- decor.__doc__ = ds
-
- return decor
-
-
-# Inspired by numpy's skipif, but uses the full apply_wrapper utility to
-# preserve function metadata better and allows the skip condition to be a
-# callable.
-def skipif(skip_condition, msg=None):
- ''' Make function raise SkipTest exception if skip_condition is true
-
- Parameters
- ----------
-
- skip_condition : bool or callable
- Flag to determine whether to skip test. If the condition is a
- callable, it is used at runtime to dynamically make the decision. This
- is useful for tests that may require costly imports, to delay the cost
- until the test suite is actually executed.
- msg : string
- Message to give on raising a SkipTest exception.
-
- Returns
- -------
- decorator : function
- Decorator, which, when applied to a function, causes SkipTest
- to be raised when the skip_condition was True, and the function
- to be called normally otherwise.
-
- Notes
- -----
- You will see from the code that we had to further decorate the
- decorator with the nose.tools.make_decorator function in order to
- transmit function name, and various other metadata.
- '''
-
- def skip_decorator(f):
- # Local import to avoid a hard nose dependency and only incur the
- # import time overhead at actual test-time.
- import nose
-
- # Allow for both boolean or callable skip conditions.
- if callable(skip_condition):
- skip_val = skip_condition
- else:
- skip_val = lambda : skip_condition
-
- def get_msg(func,msg=None):
- """Skip message with information about function being skipped."""
- if msg is None: out = 'Test skipped due to test condition.'
- else: out = msg
- return "Skipping test: %s. %s" % (func.__name__,out)
-
- # We need to define *two* skippers because Python doesn't allow both
- # return with value and yield inside the same function.
- def skipper_func(*args, **kwargs):
- """Skipper for normal test functions."""
- if skip_val():
- raise nose.SkipTest(get_msg(f,msg))
- else:
- return f(*args, **kwargs)
-
- def skipper_gen(*args, **kwargs):
- """Skipper for test generators."""
- if skip_val():
- raise nose.SkipTest(get_msg(f,msg))
- else:
- for x in f(*args, **kwargs):
- yield x
-
- # Choose the right skipper to use when building the actual generator.
- if nose.util.isgenerator(f):
- skipper = skipper_gen
- else:
- skipper = skipper_func
-
- return nose.tools.make_decorator(f)(skipper)
-
- return skip_decorator
-
-# A version with the condition set to true, common case just to attach a message
-# to a skip decorator
-def skip(msg=None):
- """Decorator factory - mark a test function for skipping from test suite.
-
- Parameters
- ----------
- msg : string
- Optional message to be added.
-
- Returns
- -------
- decorator : function
- Decorator, which, when applied to a function, causes SkipTest
- to be raised, with the optional message added.
- """
-
- return skipif(True,msg)
-
-
-def onlyif(condition, msg):
- """The reverse from skipif, see skipif for details."""
-
- if callable(condition):
- skip_condition = lambda : not condition()
- else:
- skip_condition = lambda : not condition
-
- return skipif(skip_condition, msg)
-
-#-----------------------------------------------------------------------------
-# Utility functions for decorators
-def module_not_available(module):
- """Can module be imported? Returns true if module does NOT import.
-
- This is used to make a decorator to skip tests that require module to be
- available, but delay the 'import numpy' to test execution time.
- """
- try:
- mod = __import__(module)
- mod_not_avail = False
- except ImportError:
- mod_not_avail = True
-
- return mod_not_avail
-
-
-def decorated_dummy(dec, name):
- """Return a dummy function decorated with dec, with the given name.
-
- Examples
- --------
- import IPython.testing.decorators as dec
- setup = dec.decorated_dummy(dec.skip_if_no_x11, __name__)
- """
+ if isinstance(label, string_types):
+ labels = [label]
+ else:
+ labels = label
+
+ # Validate that the given label(s) are OK for use in setattr() by doing a
+ # dry run on a dummy function.
+ tmp = lambda : None
+ for label in labels:
+ setattr(tmp,label,True)
+
+ # This is the actual decorator we'll return
+ def decor(f):
+ for label in labels:
+ setattr(f,label,True)
+ return f
+
+ # Apply the user's docstring, or autogenerate a basic one
+ if ds is None:
+ ds = "Labels a test as %r." % label
+ decor.__doc__ = ds
+
+ return decor
+
+
+# Inspired by numpy's skipif, but uses the full apply_wrapper utility to
+# preserve function metadata better and allows the skip condition to be a
+# callable.
+def skipif(skip_condition, msg=None):
+ ''' Make function raise SkipTest exception if skip_condition is true
+
+ Parameters
+ ----------
+
+ skip_condition : bool or callable
+ Flag to determine whether to skip test. If the condition is a
+ callable, it is used at runtime to dynamically make the decision. This
+ is useful for tests that may require costly imports, to delay the cost
+ until the test suite is actually executed.
+ msg : string
+ Message to give on raising a SkipTest exception.
+
+ Returns
+ -------
+ decorator : function
+ Decorator, which, when applied to a function, causes SkipTest
+ to be raised when the skip_condition was True, and the function
+ to be called normally otherwise.
+
+ Notes
+ -----
+ You will see from the code that we had to further decorate the
+ decorator with the nose.tools.make_decorator function in order to
+ transmit function name, and various other metadata.
+ '''
+
+ def skip_decorator(f):
+ # Local import to avoid a hard nose dependency and only incur the
+ # import time overhead at actual test-time.
+ import nose
+
+ # Allow for both boolean or callable skip conditions.
+ if callable(skip_condition):
+ skip_val = skip_condition
+ else:
+ skip_val = lambda : skip_condition
+
+ def get_msg(func,msg=None):
+ """Skip message with information about function being skipped."""
+ if msg is None: out = 'Test skipped due to test condition.'
+ else: out = msg
+ return "Skipping test: %s. %s" % (func.__name__,out)
+
+ # We need to define *two* skippers because Python doesn't allow both
+ # return with value and yield inside the same function.
+ def skipper_func(*args, **kwargs):
+ """Skipper for normal test functions."""
+ if skip_val():
+ raise nose.SkipTest(get_msg(f,msg))
+ else:
+ return f(*args, **kwargs)
+
+ def skipper_gen(*args, **kwargs):
+ """Skipper for test generators."""
+ if skip_val():
+ raise nose.SkipTest(get_msg(f,msg))
+ else:
+ for x in f(*args, **kwargs):
+ yield x
+
+ # Choose the right skipper to use when building the actual generator.
+ if nose.util.isgenerator(f):
+ skipper = skipper_gen
+ else:
+ skipper = skipper_func
+
+ return nose.tools.make_decorator(f)(skipper)
+
+ return skip_decorator
+
+# A version with the condition set to true, common case just to attach a message
+# to a skip decorator
+def skip(msg=None):
+ """Decorator factory - mark a test function for skipping from test suite.
+
+ Parameters
+ ----------
+ msg : string
+ Optional message to be added.
+
+ Returns
+ -------
+ decorator : function
+ Decorator, which, when applied to a function, causes SkipTest
+ to be raised, with the optional message added.
+ """
+
+ return skipif(True,msg)
+
+
+def onlyif(condition, msg):
+ """The reverse from skipif, see skipif for details."""
+
+ if callable(condition):
+ skip_condition = lambda : not condition()
+ else:
+ skip_condition = lambda : not condition
+
+ return skipif(skip_condition, msg)
+
+#-----------------------------------------------------------------------------
+# Utility functions for decorators
+def module_not_available(module):
+ """Can module be imported? Returns true if module does NOT import.
+
+ This is used to make a decorator to skip tests that require module to be
+ available, but delay the 'import numpy' to test execution time.
+ """
+ try:
+ mod = __import__(module)
+ mod_not_avail = False
+ except ImportError:
+ mod_not_avail = True
+
+ return mod_not_avail
+
+
+def decorated_dummy(dec, name):
+ """Return a dummy function decorated with dec, with the given name.
+
+ Examples
+ --------
+ import IPython.testing.decorators as dec
+ setup = dec.decorated_dummy(dec.skip_if_no_x11, __name__)
+ """
warnings.warn("The function `decorated_dummy` is deprecated since IPython 4.0",
DeprecationWarning, stacklevel=2)
- dummy = lambda: None
- dummy.__name__ = name
- return dec(dummy)
-
-#-----------------------------------------------------------------------------
-# Decorators for public use
-
-# Decorators to skip certain tests on specific platforms.
-skip_win32 = skipif(sys.platform == 'win32',
- "This test does not run under Windows")
-skip_linux = skipif(sys.platform.startswith('linux'),
- "This test does not run under Linux")
-skip_osx = skipif(sys.platform == 'darwin',"This test does not run under OS X")
-
-
-# Decorators to skip tests if not on specific platforms.
-skip_if_not_win32 = skipif(sys.platform != 'win32',
- "This test only runs under Windows")
-skip_if_not_linux = skipif(not sys.platform.startswith('linux'),
- "This test only runs under Linux")
-skip_if_not_osx = skipif(sys.platform != 'darwin',
- "This test only runs under OSX")
-
-
-_x11_skip_cond = (sys.platform not in ('darwin', 'win32') and
- os.environ.get('DISPLAY', '') == '')
-_x11_skip_msg = "Skipped under *nix when X11/XOrg not available"
-
-skip_if_no_x11 = skipif(_x11_skip_cond, _x11_skip_msg)
-
-# not a decorator itself, returns a dummy function to be used as setup
-def skip_file_no_x11(name):
+ dummy = lambda: None
+ dummy.__name__ = name
+ return dec(dummy)
+
+#-----------------------------------------------------------------------------
+# Decorators for public use
+
+# Decorators to skip certain tests on specific platforms.
+skip_win32 = skipif(sys.platform == 'win32',
+ "This test does not run under Windows")
+skip_linux = skipif(sys.platform.startswith('linux'),
+ "This test does not run under Linux")
+skip_osx = skipif(sys.platform == 'darwin',"This test does not run under OS X")
+
+
+# Decorators to skip tests if not on specific platforms.
+skip_if_not_win32 = skipif(sys.platform != 'win32',
+ "This test only runs under Windows")
+skip_if_not_linux = skipif(not sys.platform.startswith('linux'),
+ "This test only runs under Linux")
+skip_if_not_osx = skipif(sys.platform != 'darwin',
+ "This test only runs under OSX")
+
+
+_x11_skip_cond = (sys.platform not in ('darwin', 'win32') and
+ os.environ.get('DISPLAY', '') == '')
+_x11_skip_msg = "Skipped under *nix when X11/XOrg not available"
+
+skip_if_no_x11 = skipif(_x11_skip_cond, _x11_skip_msg)
+
+# not a decorator itself, returns a dummy function to be used as setup
+def skip_file_no_x11(name):
warnings.warn("The function `skip_file_no_x11` is deprecated since IPython 4.0",
DeprecationWarning, stacklevel=2)
- return decorated_dummy(skip_if_no_x11, name) if _x11_skip_cond else None
-
-# Other skip decorators
-
-# generic skip without module
-skip_without = lambda mod: skipif(module_not_available(mod), "This test requires %s" % mod)
-
-skipif_not_numpy = skip_without('numpy')
-
-skipif_not_matplotlib = skip_without('matplotlib')
-
-skipif_not_sympy = skip_without('sympy')
-
-skip_known_failure = knownfailureif(True,'This test is known to fail')
-
-known_failure_py3 = knownfailureif(sys.version_info[0] >= 3,
- 'This test is known to fail on Python 3.')
-
+ return decorated_dummy(skip_if_no_x11, name) if _x11_skip_cond else None
+
+# Other skip decorators
+
+# generic skip without module
+skip_without = lambda mod: skipif(module_not_available(mod), "This test requires %s" % mod)
+
+skipif_not_numpy = skip_without('numpy')
+
+skipif_not_matplotlib = skip_without('matplotlib')
+
+skipif_not_sympy = skip_without('sympy')
+
+skip_known_failure = knownfailureif(True,'This test is known to fail')
+
+known_failure_py3 = knownfailureif(sys.version_info[0] >= 3,
+ 'This test is known to fail on Python 3.')
+
cpython2_only = skipif(PY3 or PYPY, "This test only runs on CPython 2.")
-py2_only = skipif(PY3, "This test only runs on Python 2.")
-py3_only = skipif(PY2, "This test only runs on Python 3.")
-
-# A null 'decorator', useful to make more readable code that needs to pick
-# between different decorators based on OS or other conditions
-null_deco = lambda f: f
-
-# Some tests only run where we can use unicode paths. Note that we can't just
-# check os.path.supports_unicode_filenames, which is always False on Linux.
-try:
- f = tempfile.NamedTemporaryFile(prefix=u"tmp€")
-except UnicodeEncodeError:
- unicode_paths = False
-else:
- unicode_paths = True
- f.close()
-
-onlyif_unicode_paths = onlyif(unicode_paths, ("This test is only applicable "
- "where we can use unicode in filenames."))
-
-
-def onlyif_cmds_exist(*commands):
- """
- Decorator to skip test when at least one of `commands` is not found.
- """
- for cmd in commands:
- if not which(cmd):
- return skip("This test runs only if command '{0}' "
- "is installed".format(cmd))
- return null_deco
-
-def onlyif_any_cmd_exists(*commands):
- """
- Decorator to skip test unless at least one of `commands` is found.
- """
+py2_only = skipif(PY3, "This test only runs on Python 2.")
+py3_only = skipif(PY2, "This test only runs on Python 3.")
+
+# A null 'decorator', useful to make more readable code that needs to pick
+# between different decorators based on OS or other conditions
+null_deco = lambda f: f
+
+# Some tests only run where we can use unicode paths. Note that we can't just
+# check os.path.supports_unicode_filenames, which is always False on Linux.
+try:
+ f = tempfile.NamedTemporaryFile(prefix=u"tmp€")
+except UnicodeEncodeError:
+ unicode_paths = False
+else:
+ unicode_paths = True
+ f.close()
+
+onlyif_unicode_paths = onlyif(unicode_paths, ("This test is only applicable "
+ "where we can use unicode in filenames."))
+
+
+def onlyif_cmds_exist(*commands):
+ """
+ Decorator to skip test when at least one of `commands` is not found.
+ """
+ for cmd in commands:
+ if not which(cmd):
+ return skip("This test runs only if command '{0}' "
+ "is installed".format(cmd))
+ return null_deco
+
+def onlyif_any_cmd_exists(*commands):
+ """
+ Decorator to skip test unless at least one of `commands` is found.
+ """
warnings.warn("The function `onlyif_any_cmd_exists` is deprecated since IPython 4.0",
DeprecationWarning, stacklevel=2)
- for cmd in commands:
- if which(cmd):
- return null_deco
- return skip("This test runs only if one of the commands {0} "
- "is installed".format(commands))
+ for cmd in commands:
+ if which(cmd):
+ return null_deco
+ return skip("This test runs only if one of the commands {0} "
+ "is installed".format(commands))
diff --git a/contrib/python/ipython/py2/IPython/testing/globalipapp.py b/contrib/python/ipython/py2/IPython/testing/globalipapp.py
index a40702cc67..3983393112 100644
--- a/contrib/python/ipython/py2/IPython/testing/globalipapp.py
+++ b/contrib/python/ipython/py2/IPython/testing/globalipapp.py
@@ -1,138 +1,138 @@
-"""Global IPython app to support test running.
-
-We must start our own ipython object and heavily muck with it so that all the
-modifications IPython makes to system behavior don't send the doctest machinery
-into a fit. This code should be considered a gross hack, but it gets the job
-done.
-"""
-from __future__ import absolute_import
-from __future__ import print_function
-
+"""Global IPython app to support test running.
+
+We must start our own ipython object and heavily muck with it so that all the
+modifications IPython makes to system behavior don't send the doctest machinery
+into a fit. This code should be considered a gross hack, but it gets the job
+done.
+"""
+from __future__ import absolute_import
+from __future__ import print_function
+
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
-
-import sys
+
+import sys
import warnings
-
-from . import tools
-
-from IPython.core import page
-from IPython.utils import io
-from IPython.utils import py3compat
-from IPython.utils.py3compat import builtin_mod
-from IPython.terminal.interactiveshell import TerminalInteractiveShell
-
-
-class StreamProxy(io.IOStream):
- """Proxy for sys.stdout/err. This will request the stream *at call time*
- allowing for nose's Capture plugin's redirection of sys.stdout/err.
-
- Parameters
- ----------
- name : str
- The name of the stream. This will be requested anew at every call
- """
-
- def __init__(self, name):
+
+from . import tools
+
+from IPython.core import page
+from IPython.utils import io
+from IPython.utils import py3compat
+from IPython.utils.py3compat import builtin_mod
+from IPython.terminal.interactiveshell import TerminalInteractiveShell
+
+
+class StreamProxy(io.IOStream):
+ """Proxy for sys.stdout/err. This will request the stream *at call time*
+ allowing for nose's Capture plugin's redirection of sys.stdout/err.
+
+ Parameters
+ ----------
+ name : str
+ The name of the stream. This will be requested anew at every call
+ """
+
+ def __init__(self, name):
warnings.warn("StreamProxy is deprecated and unused as of IPython 5", DeprecationWarning,
stacklevel=2,
)
- self.name=name
-
- @property
- def stream(self):
- return getattr(sys, self.name)
-
- def flush(self):
- self.stream.flush()
-
-
-def get_ipython():
- # This will get replaced by the real thing once we start IPython below
- return start_ipython()
-
-
-# A couple of methods to override those in the running IPython to interact
-# better with doctest (doctest captures on raw stdout, so we need to direct
-# various types of output there otherwise it will miss them).
-
-def xsys(self, cmd):
- """Replace the default system call with a capturing one for doctest.
- """
- # We use getoutput, but we need to strip it because pexpect captures
- # the trailing newline differently from commands.getoutput
- print(self.getoutput(cmd, split=False, depth=1).rstrip(), end='', file=sys.stdout)
- sys.stdout.flush()
-
-
-def _showtraceback(self, etype, evalue, stb):
- """Print the traceback purely on stdout for doctest to capture it.
- """
- print(self.InteractiveTB.stb2text(stb), file=sys.stdout)
-
-
-def start_ipython():
- """Start a global IPython shell, which we need for IPython-specific syntax.
- """
- global get_ipython
-
- # This function should only ever run once!
- if hasattr(start_ipython, 'already_called'):
- return
- start_ipython.already_called = True
-
- # Store certain global objects that IPython modifies
- _displayhook = sys.displayhook
- _excepthook = sys.excepthook
- _main = sys.modules.get('__main__')
-
- # Create custom argv and namespaces for our IPython to be test-friendly
- config = tools.default_config()
+ self.name=name
+
+ @property
+ def stream(self):
+ return getattr(sys, self.name)
+
+ def flush(self):
+ self.stream.flush()
+
+
+def get_ipython():
+ # This will get replaced by the real thing once we start IPython below
+ return start_ipython()
+
+
+# A couple of methods to override those in the running IPython to interact
+# better with doctest (doctest captures on raw stdout, so we need to direct
+# various types of output there otherwise it will miss them).
+
+def xsys(self, cmd):
+ """Replace the default system call with a capturing one for doctest.
+ """
+ # We use getoutput, but we need to strip it because pexpect captures
+ # the trailing newline differently from commands.getoutput
+ print(self.getoutput(cmd, split=False, depth=1).rstrip(), end='', file=sys.stdout)
+ sys.stdout.flush()
+
+
+def _showtraceback(self, etype, evalue, stb):
+ """Print the traceback purely on stdout for doctest to capture it.
+ """
+ print(self.InteractiveTB.stb2text(stb), file=sys.stdout)
+
+
+def start_ipython():
+ """Start a global IPython shell, which we need for IPython-specific syntax.
+ """
+ global get_ipython
+
+ # This function should only ever run once!
+ if hasattr(start_ipython, 'already_called'):
+ return
+ start_ipython.already_called = True
+
+ # Store certain global objects that IPython modifies
+ _displayhook = sys.displayhook
+ _excepthook = sys.excepthook
+ _main = sys.modules.get('__main__')
+
+ # Create custom argv and namespaces for our IPython to be test-friendly
+ config = tools.default_config()
config.TerminalInteractiveShell.simple_prompt = True
-
- # Create and initialize our test-friendly IPython instance.
- shell = TerminalInteractiveShell.instance(config=config,
- )
-
- # A few more tweaks needed for playing nicely with doctests...
-
- # remove history file
- shell.tempfiles.append(config.HistoryManager.hist_file)
-
- # These traps are normally only active for interactive use, set them
- # permanently since we'll be mocking interactive sessions.
- shell.builtin_trap.activate()
-
- # Modify the IPython system call with one that uses getoutput, so that we
- # can capture subcommands and print them to Python's stdout, otherwise the
- # doctest machinery would miss them.
- shell.system = py3compat.MethodType(xsys, shell)
-
- shell._showtraceback = py3compat.MethodType(_showtraceback, shell)
-
- # IPython is ready, now clean up some global state...
-
- # Deactivate the various python system hooks added by ipython for
- # interactive convenience so we don't confuse the doctest system
- sys.modules['__main__'] = _main
- sys.displayhook = _displayhook
- sys.excepthook = _excepthook
-
- # So that ipython magics and aliases can be doctested (they work by making
- # a call into a global _ip object). Also make the top-level get_ipython
- # now return this without recursively calling here again.
- _ip = shell
- get_ipython = _ip.get_ipython
- builtin_mod._ip = _ip
- builtin_mod.get_ipython = get_ipython
-
- # Override paging, so we don't require user interaction during the tests.
- def nopage(strng, start=0, screen_lines=0, pager_cmd=None):
+
+ # Create and initialize our test-friendly IPython instance.
+ shell = TerminalInteractiveShell.instance(config=config,
+ )
+
+ # A few more tweaks needed for playing nicely with doctests...
+
+ # remove history file
+ shell.tempfiles.append(config.HistoryManager.hist_file)
+
+ # These traps are normally only active for interactive use, set them
+ # permanently since we'll be mocking interactive sessions.
+ shell.builtin_trap.activate()
+
+ # Modify the IPython system call with one that uses getoutput, so that we
+ # can capture subcommands and print them to Python's stdout, otherwise the
+ # doctest machinery would miss them.
+ shell.system = py3compat.MethodType(xsys, shell)
+
+ shell._showtraceback = py3compat.MethodType(_showtraceback, shell)
+
+ # IPython is ready, now clean up some global state...
+
+ # Deactivate the various python system hooks added by ipython for
+ # interactive convenience so we don't confuse the doctest system
+ sys.modules['__main__'] = _main
+ sys.displayhook = _displayhook
+ sys.excepthook = _excepthook
+
+ # So that ipython magics and aliases can be doctested (they work by making
+ # a call into a global _ip object). Also make the top-level get_ipython
+ # now return this without recursively calling here again.
+ _ip = shell
+ get_ipython = _ip.get_ipython
+ builtin_mod._ip = _ip
+ builtin_mod.get_ipython = get_ipython
+
+ # Override paging, so we don't require user interaction during the tests.
+ def nopage(strng, start=0, screen_lines=0, pager_cmd=None):
if isinstance(strng, dict):
strng = strng.get('text/plain', '')
- print(strng)
-
- page.orig_page = page.pager_page
- page.pager_page = nopage
-
- return _ip
+ print(strng)
+
+ page.orig_page = page.pager_page
+ page.pager_page = nopage
+
+ return _ip
diff --git a/contrib/python/ipython/py2/IPython/testing/iptest.py b/contrib/python/ipython/py2/IPython/testing/iptest.py
index 9a5a3d6f58..4018264125 100644
--- a/contrib/python/ipython/py2/IPython/testing/iptest.py
+++ b/contrib/python/ipython/py2/IPython/testing/iptest.py
@@ -1,55 +1,55 @@
-# -*- coding: utf-8 -*-
-"""IPython Test Suite Runner.
-
-This module provides a main entry point to a user script to test IPython
-itself from the command line. There are two ways of running this script:
-
-1. With the syntax `iptest all`. This runs our entire test suite by
- calling this script (with different arguments) recursively. This
- causes modules and package to be tested in different processes, using nose
- or trial where appropriate.
-2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
- the script simply calls nose, but with special command line flags and
- plugins loaded.
-
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
-import glob
-from io import BytesIO
-import os
-import os.path as path
-import sys
-from threading import Thread, Lock, Event
-import warnings
-
-import nose.plugins.builtin
-from nose.plugins.xunit import Xunit
-from nose import SkipTest
-from nose.core import TestProgram
-from nose.plugins import Plugin
-from nose.util import safe_str
-
-from IPython import version_info
-from IPython.utils.py3compat import bytes_to_str
-from IPython.utils.importstring import import_item
-from IPython.testing.plugin.ipdoctest import IPythonDoctest
-from IPython.external.decorators import KnownFailure, knownfailureif
-
-pjoin = path.join
-
-
-# Enable printing all warnings raise by IPython's modules
+# -*- coding: utf-8 -*-
+"""IPython Test Suite Runner.
+
+This module provides a main entry point to a user script to test IPython
+itself from the command line. There are two ways of running this script:
+
+1. With the syntax `iptest all`. This runs our entire test suite by
+ calling this script (with different arguments) recursively. This
+ causes modules and package to be tested in different processes, using nose
+ or trial where appropriate.
+2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
+ the script simply calls nose, but with special command line flags and
+ plugins loaded.
+
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
+import glob
+from io import BytesIO
+import os
+import os.path as path
+import sys
+from threading import Thread, Lock, Event
+import warnings
+
+import nose.plugins.builtin
+from nose.plugins.xunit import Xunit
+from nose import SkipTest
+from nose.core import TestProgram
+from nose.plugins import Plugin
+from nose.util import safe_str
+
+from IPython import version_info
+from IPython.utils.py3compat import bytes_to_str
+from IPython.utils.importstring import import_item
+from IPython.testing.plugin.ipdoctest import IPythonDoctest
+from IPython.external.decorators import KnownFailure, knownfailureif
+
+pjoin = path.join
+
+
+# Enable printing all warnings raise by IPython's modules
warnings.filterwarnings('ignore', message='.*Matplotlib is building the font cache.*', category=UserWarning, module='.*')
if sys.version_info > (3,0):
warnings.filterwarnings('error', message='.*', category=ResourceWarning, module='.*')
warnings.filterwarnings('error', message=".*{'config': True}.*", category=DeprecationWarning, module='IPy.*')
-warnings.filterwarnings('default', message='.*', category=Warning, module='IPy.*')
-
+warnings.filterwarnings('default', message='.*', category=Warning, module='IPy.*')
+
warnings.filterwarnings('error', message='.*apply_wrapper.*', category=DeprecationWarning, module='.*')
warnings.filterwarnings('error', message='.*make_label_dec', category=DeprecationWarning, module='.*')
warnings.filterwarnings('error', message='.*decorated_dummy.*', category=DeprecationWarning, module='.*')
@@ -60,384 +60,384 @@ warnings.filterwarnings('error', message='.*disable_gui.*', category=Deprecation
warnings.filterwarnings('error', message='.*ExceptionColors global is deprecated.*', category=DeprecationWarning, module='.*')
-if version_info < (6,):
- # nose.tools renames all things from `camelCase` to `snake_case` which raise an
- # warning with the runner they also import from standard import library. (as of Dec 2015)
- # Ignore, let's revisit that in a couple of years for IPython 6.
- warnings.filterwarnings('ignore', message='.*Please use assertEqual instead', category=Warning, module='IPython.*')
-
-
-# ------------------------------------------------------------------------------
-# Monkeypatch Xunit to count known failures as skipped.
-# ------------------------------------------------------------------------------
-def monkeypatch_xunit():
- try:
- knownfailureif(True)(lambda: None)()
- except Exception as e:
- KnownFailureTest = type(e)
-
- def addError(self, test, err, capt=None):
- if issubclass(err[0], KnownFailureTest):
- err = (SkipTest,) + err[1:]
- return self.orig_addError(test, err, capt)
-
- Xunit.orig_addError = Xunit.addError
- Xunit.addError = addError
-
-#-----------------------------------------------------------------------------
-# Check which dependencies are installed and greater than minimum version.
-#-----------------------------------------------------------------------------
-def extract_version(mod):
- return mod.__version__
-
-def test_for(item, min_version=None, callback=extract_version):
- """Test to see if item is importable, and optionally check against a minimum
- version.
-
- If min_version is given, the default behavior is to check against the
- `__version__` attribute of the item, but specifying `callback` allows you to
- extract the value you are interested in. e.g::
-
- In [1]: import sys
-
- In [2]: from IPython.testing.iptest import test_for
-
- In [3]: test_for('sys', (2,6), callback=lambda sys: sys.version_info)
- Out[3]: True
-
- """
- try:
- check = import_item(item)
- except (ImportError, RuntimeError):
- # GTK reports Runtime error if it can't be initialized even if it's
- # importable.
- return False
- else:
- if min_version:
- if callback:
- # extra processing step to get version to compare
- check = callback(check)
-
- return check >= min_version
- else:
- return True
-
-# Global dict where we can store information on what we have and what we don't
-# have available at test run time
-have = {'matplotlib': test_for('matplotlib'),
- 'pygments': test_for('pygments'),
- 'sqlite3': test_for('sqlite3')}
-
-#-----------------------------------------------------------------------------
-# Test suite definitions
-#-----------------------------------------------------------------------------
-
-test_group_names = ['core',
- 'extensions', 'lib', 'terminal', 'testing', 'utils',
- ]
-
-class TestSection(object):
- def __init__(self, name, includes):
- self.name = name
- self.includes = includes
- self.excludes = []
- self.dependencies = []
- self.enabled = True
-
- def exclude(self, module):
- if not module.startswith('IPython'):
- module = self.includes[0] + "." + module
- self.excludes.append(module.replace('.', os.sep))
-
- def requires(self, *packages):
- self.dependencies.extend(packages)
-
- @property
- def will_run(self):
- return self.enabled and all(have[p] for p in self.dependencies)
-
-# Name -> (include, exclude, dependencies_met)
-test_sections = {n:TestSection(n, ['IPython.%s' % n]) for n in test_group_names}
-
-
-# Exclusions and dependencies
-# ---------------------------
-
-# core:
-sec = test_sections['core']
-if not have['sqlite3']:
- sec.exclude('tests.test_history')
- sec.exclude('history')
-if not have['matplotlib']:
- sec.exclude('pylabtools'),
- sec.exclude('tests.test_pylabtools')
-
-# lib:
-sec = test_sections['lib']
-sec.exclude('kernel')
-if not have['pygments']:
- sec.exclude('tests.test_lexers')
-# We do this unconditionally, so that the test suite doesn't import
-# gtk, changing the default encoding and masking some unicode bugs.
-sec.exclude('inputhookgtk')
-# We also do this unconditionally, because wx can interfere with Unix signals.
-# There are currently no tests for it anyway.
-sec.exclude('inputhookwx')
-# Testing inputhook will need a lot of thought, to figure out
-# how to have tests that don't lock up with the gui event
-# loops in the picture
-sec.exclude('inputhook')
-
-# testing:
-sec = test_sections['testing']
-# These have to be skipped on win32 because they use echo, rm, cd, etc.
-# See ticket https://github.com/ipython/ipython/issues/87
-if sys.platform == 'win32':
- sec.exclude('plugin.test_exampleip')
- sec.exclude('plugin.dtexample')
-
-# don't run jupyter_console tests found via shim
-test_sections['terminal'].exclude('console')
-
-# extensions:
-sec = test_sections['extensions']
-# This is deprecated in favour of rpy2
-sec.exclude('rmagic')
-# autoreload does some strange stuff, so move it to its own test section
-sec.exclude('autoreload')
-sec.exclude('tests.test_autoreload')
-test_sections['autoreload'] = TestSection('autoreload',
- ['IPython.extensions.autoreload', 'IPython.extensions.tests.test_autoreload'])
-test_group_names.append('autoreload')
-
-
-#-----------------------------------------------------------------------------
-# Functions and classes
-#-----------------------------------------------------------------------------
-
-def check_exclusions_exist():
- from IPython.paths import get_ipython_package_dir
+if version_info < (6,):
+ # nose.tools renames all things from `camelCase` to `snake_case` which raise an
+ # warning with the runner they also import from standard import library. (as of Dec 2015)
+ # Ignore, let's revisit that in a couple of years for IPython 6.
+ warnings.filterwarnings('ignore', message='.*Please use assertEqual instead', category=Warning, module='IPython.*')
+
+
+# ------------------------------------------------------------------------------
+# Monkeypatch Xunit to count known failures as skipped.
+# ------------------------------------------------------------------------------
+def monkeypatch_xunit():
+ try:
+ knownfailureif(True)(lambda: None)()
+ except Exception as e:
+ KnownFailureTest = type(e)
+
+ def addError(self, test, err, capt=None):
+ if issubclass(err[0], KnownFailureTest):
+ err = (SkipTest,) + err[1:]
+ return self.orig_addError(test, err, capt)
+
+ Xunit.orig_addError = Xunit.addError
+ Xunit.addError = addError
+
+#-----------------------------------------------------------------------------
+# Check which dependencies are installed and greater than minimum version.
+#-----------------------------------------------------------------------------
+def extract_version(mod):
+ return mod.__version__
+
+def test_for(item, min_version=None, callback=extract_version):
+ """Test to see if item is importable, and optionally check against a minimum
+ version.
+
+ If min_version is given, the default behavior is to check against the
+ `__version__` attribute of the item, but specifying `callback` allows you to
+ extract the value you are interested in. e.g::
+
+ In [1]: import sys
+
+ In [2]: from IPython.testing.iptest import test_for
+
+ In [3]: test_for('sys', (2,6), callback=lambda sys: sys.version_info)
+ Out[3]: True
+
+ """
+ try:
+ check = import_item(item)
+ except (ImportError, RuntimeError):
+ # GTK reports Runtime error if it can't be initialized even if it's
+ # importable.
+ return False
+ else:
+ if min_version:
+ if callback:
+ # extra processing step to get version to compare
+ check = callback(check)
+
+ return check >= min_version
+ else:
+ return True
+
+# Global dict where we can store information on what we have and what we don't
+# have available at test run time
+have = {'matplotlib': test_for('matplotlib'),
+ 'pygments': test_for('pygments'),
+ 'sqlite3': test_for('sqlite3')}
+
+#-----------------------------------------------------------------------------
+# Test suite definitions
+#-----------------------------------------------------------------------------
+
+test_group_names = ['core',
+ 'extensions', 'lib', 'terminal', 'testing', 'utils',
+ ]
+
+class TestSection(object):
+ def __init__(self, name, includes):
+ self.name = name
+ self.includes = includes
+ self.excludes = []
+ self.dependencies = []
+ self.enabled = True
+
+ def exclude(self, module):
+ if not module.startswith('IPython'):
+ module = self.includes[0] + "." + module
+ self.excludes.append(module.replace('.', os.sep))
+
+ def requires(self, *packages):
+ self.dependencies.extend(packages)
+
+ @property
+ def will_run(self):
+ return self.enabled and all(have[p] for p in self.dependencies)
+
+# Name -> (include, exclude, dependencies_met)
+test_sections = {n:TestSection(n, ['IPython.%s' % n]) for n in test_group_names}
+
+
+# Exclusions and dependencies
+# ---------------------------
+
+# core:
+sec = test_sections['core']
+if not have['sqlite3']:
+ sec.exclude('tests.test_history')
+ sec.exclude('history')
+if not have['matplotlib']:
+ sec.exclude('pylabtools'),
+ sec.exclude('tests.test_pylabtools')
+
+# lib:
+sec = test_sections['lib']
+sec.exclude('kernel')
+if not have['pygments']:
+ sec.exclude('tests.test_lexers')
+# We do this unconditionally, so that the test suite doesn't import
+# gtk, changing the default encoding and masking some unicode bugs.
+sec.exclude('inputhookgtk')
+# We also do this unconditionally, because wx can interfere with Unix signals.
+# There are currently no tests for it anyway.
+sec.exclude('inputhookwx')
+# Testing inputhook will need a lot of thought, to figure out
+# how to have tests that don't lock up with the gui event
+# loops in the picture
+sec.exclude('inputhook')
+
+# testing:
+sec = test_sections['testing']
+# These have to be skipped on win32 because they use echo, rm, cd, etc.
+# See ticket https://github.com/ipython/ipython/issues/87
+if sys.platform == 'win32':
+ sec.exclude('plugin.test_exampleip')
+ sec.exclude('plugin.dtexample')
+
+# don't run jupyter_console tests found via shim
+test_sections['terminal'].exclude('console')
+
+# extensions:
+sec = test_sections['extensions']
+# This is deprecated in favour of rpy2
+sec.exclude('rmagic')
+# autoreload does some strange stuff, so move it to its own test section
+sec.exclude('autoreload')
+sec.exclude('tests.test_autoreload')
+test_sections['autoreload'] = TestSection('autoreload',
+ ['IPython.extensions.autoreload', 'IPython.extensions.tests.test_autoreload'])
+test_group_names.append('autoreload')
+
+
+#-----------------------------------------------------------------------------
+# Functions and classes
+#-----------------------------------------------------------------------------
+
+def check_exclusions_exist():
+ from IPython.paths import get_ipython_package_dir
from warnings import warn
- parent = os.path.dirname(get_ipython_package_dir())
- for sec in test_sections:
- for pattern in sec.exclusions:
- fullpath = pjoin(parent, pattern)
- if not os.path.exists(fullpath) and not glob.glob(fullpath + '.*'):
- warn("Excluding nonexistent file: %r" % pattern)
-
-
-class ExclusionPlugin(Plugin):
- """A nose plugin to effect our exclusions of files and directories.
- """
- name = 'exclusions'
- score = 3000 # Should come before any other plugins
-
- def __init__(self, exclude_patterns=None):
- """
- Parameters
- ----------
-
- exclude_patterns : sequence of strings, optional
- Filenames containing these patterns (as raw strings, not as regular
- expressions) are excluded from the tests.
- """
- self.exclude_patterns = exclude_patterns or []
- super(ExclusionPlugin, self).__init__()
-
- def options(self, parser, env=os.environ):
- Plugin.options(self, parser, env)
-
- def configure(self, options, config):
- Plugin.configure(self, options, config)
- # Override nose trying to disable plugin.
- self.enabled = True
-
- def wantFile(self, filename):
- """Return whether the given filename should be scanned for tests.
- """
- if any(pat in filename for pat in self.exclude_patterns):
- return False
- return None
-
- def wantDirectory(self, directory):
- """Return whether the given directory should be scanned for tests.
- """
- if any(pat in directory for pat in self.exclude_patterns):
- return False
- return None
-
-
-class StreamCapturer(Thread):
- daemon = True # Don't hang if main thread crashes
- started = False
- def __init__(self, echo=False):
- super(StreamCapturer, self).__init__()
- self.echo = echo
- self.streams = []
- self.buffer = BytesIO()
- self.readfd, self.writefd = os.pipe()
- self.buffer_lock = Lock()
- self.stop = Event()
-
- def run(self):
- self.started = True
-
- while not self.stop.is_set():
- chunk = os.read(self.readfd, 1024)
-
- with self.buffer_lock:
- self.buffer.write(chunk)
- if self.echo:
- sys.stdout.write(bytes_to_str(chunk))
-
- os.close(self.readfd)
- os.close(self.writefd)
-
- def reset_buffer(self):
- with self.buffer_lock:
- self.buffer.truncate(0)
- self.buffer.seek(0)
-
- def get_buffer(self):
- with self.buffer_lock:
- return self.buffer.getvalue()
-
- def ensure_started(self):
- if not self.started:
- self.start()
-
- def halt(self):
- """Safely stop the thread."""
- if not self.started:
- return
-
- self.stop.set()
- os.write(self.writefd, b'\0') # Ensure we're not locked in a read()
- self.join()
-
-class SubprocessStreamCapturePlugin(Plugin):
- name='subprocstreams'
- def __init__(self):
- Plugin.__init__(self)
- self.stream_capturer = StreamCapturer()
- self.destination = os.environ.get('IPTEST_SUBPROC_STREAMS', 'capture')
- # This is ugly, but distant parts of the test machinery need to be able
- # to redirect streams, so we make the object globally accessible.
- nose.iptest_stdstreams_fileno = self.get_write_fileno
-
- def get_write_fileno(self):
- if self.destination == 'capture':
- self.stream_capturer.ensure_started()
- return self.stream_capturer.writefd
- elif self.destination == 'discard':
- return os.open(os.devnull, os.O_WRONLY)
- else:
- return sys.__stdout__.fileno()
-
- def configure(self, options, config):
- Plugin.configure(self, options, config)
- # Override nose trying to disable plugin.
- if self.destination == 'capture':
- self.enabled = True
-
- def startTest(self, test):
- # Reset log capture
- self.stream_capturer.reset_buffer()
-
- def formatFailure(self, test, err):
- # Show output
- ec, ev, tb = err
- captured = self.stream_capturer.get_buffer().decode('utf-8', 'replace')
- if captured.strip():
- ev = safe_str(ev)
- out = [ev, '>> begin captured subprocess output <<',
- captured,
- '>> end captured subprocess output <<']
- return ec, '\n'.join(out), tb
-
- return err
-
- formatError = formatFailure
-
- def finalize(self, result):
- self.stream_capturer.halt()
-
-
-def run_iptest():
- """Run the IPython test suite using nose.
-
- This function is called when this script is **not** called with the form
- `iptest all`. It simply calls nose with appropriate command line flags
- and accepts all of the standard nose arguments.
- """
- # Apply our monkeypatch to Xunit
- if '--with-xunit' in sys.argv and not hasattr(Xunit, 'orig_addError'):
- monkeypatch_xunit()
-
- arg1 = sys.argv[1]
- if arg1 in test_sections:
- section = test_sections[arg1]
- sys.argv[1:2] = section.includes
- elif arg1.startswith('IPython.') and arg1[8:] in test_sections:
- section = test_sections[arg1[8:]]
- sys.argv[1:2] = section.includes
- else:
- section = TestSection(arg1, includes=[arg1])
-
-
- argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
- # We add --exe because of setuptools' imbecility (it
- # blindly does chmod +x on ALL files). Nose does the
- # right thing and it tries to avoid executables,
- # setuptools unfortunately forces our hand here. This
- # has been discussed on the distutils list and the
- # setuptools devs refuse to fix this problem!
- '--exe',
- ]
- if '-a' not in argv and '-A' not in argv:
- argv = argv + ['-a', '!crash']
-
- if nose.__version__ >= '0.11':
- # I don't fully understand why we need this one, but depending on what
- # directory the test suite is run from, if we don't give it, 0 tests
- # get run. Specifically, if the test suite is run from the source dir
- # with an argument (like 'iptest.py IPython.core', 0 tests are run,
- # even if the same call done in this directory works fine). It appears
- # that if the requested package is in the current dir, nose bails early
- # by default. Since it's otherwise harmless, leave it in by default
- # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
- argv.append('--traverse-namespace')
-
- plugins = [ ExclusionPlugin(section.excludes), KnownFailure(),
- SubprocessStreamCapturePlugin() ]
-
- # we still have some vestigial doctests in core
- if (section.name.startswith(('core', 'IPython.core'))):
- plugins.append(IPythonDoctest())
- argv.extend([
- '--with-ipdoctest',
- '--ipdoctest-tests',
- '--ipdoctest-extension=txt',
- ])
-
-
- # Use working directory set by parent process (see iptestcontroller)
- if 'IPTEST_WORKING_DIR' in os.environ:
- os.chdir(os.environ['IPTEST_WORKING_DIR'])
-
- # We need a global ipython running in this process, but the special
- # in-process group spawns its own IPython kernels, so for *that* group we
- # must avoid also opening the global one (otherwise there's a conflict of
- # singletons). Ultimately the solution to this problem is to refactor our
- # assumptions about what needs to be a singleton and what doesn't (app
- # objects should, individual shells shouldn't). But for now, this
- # workaround allows the test suite for the inprocess module to complete.
- if 'kernel.inprocess' not in section.name:
- from IPython.testing import globalipapp
- globalipapp.start_ipython()
-
- # Now nose can run
- TestProgram(argv=argv, addplugins=plugins)
-
-if __name__ == '__main__':
- run_iptest()
+ parent = os.path.dirname(get_ipython_package_dir())
+ for sec in test_sections:
+ for pattern in sec.exclusions:
+ fullpath = pjoin(parent, pattern)
+ if not os.path.exists(fullpath) and not glob.glob(fullpath + '.*'):
+ warn("Excluding nonexistent file: %r" % pattern)
+
+
+class ExclusionPlugin(Plugin):
+ """A nose plugin to effect our exclusions of files and directories.
+ """
+ name = 'exclusions'
+ score = 3000 # Should come before any other plugins
+
+ def __init__(self, exclude_patterns=None):
+ """
+ Parameters
+ ----------
+
+ exclude_patterns : sequence of strings, optional
+ Filenames containing these patterns (as raw strings, not as regular
+ expressions) are excluded from the tests.
+ """
+ self.exclude_patterns = exclude_patterns or []
+ super(ExclusionPlugin, self).__init__()
+
+ def options(self, parser, env=os.environ):
+ Plugin.options(self, parser, env)
+
+ def configure(self, options, config):
+ Plugin.configure(self, options, config)
+ # Override nose trying to disable plugin.
+ self.enabled = True
+
+ def wantFile(self, filename):
+ """Return whether the given filename should be scanned for tests.
+ """
+ if any(pat in filename for pat in self.exclude_patterns):
+ return False
+ return None
+
+ def wantDirectory(self, directory):
+ """Return whether the given directory should be scanned for tests.
+ """
+ if any(pat in directory for pat in self.exclude_patterns):
+ return False
+ return None
+
+
+class StreamCapturer(Thread):
+ daemon = True # Don't hang if main thread crashes
+ started = False
+ def __init__(self, echo=False):
+ super(StreamCapturer, self).__init__()
+ self.echo = echo
+ self.streams = []
+ self.buffer = BytesIO()
+ self.readfd, self.writefd = os.pipe()
+ self.buffer_lock = Lock()
+ self.stop = Event()
+
+ def run(self):
+ self.started = True
+
+ while not self.stop.is_set():
+ chunk = os.read(self.readfd, 1024)
+
+ with self.buffer_lock:
+ self.buffer.write(chunk)
+ if self.echo:
+ sys.stdout.write(bytes_to_str(chunk))
+
+ os.close(self.readfd)
+ os.close(self.writefd)
+
+ def reset_buffer(self):
+ with self.buffer_lock:
+ self.buffer.truncate(0)
+ self.buffer.seek(0)
+
+ def get_buffer(self):
+ with self.buffer_lock:
+ return self.buffer.getvalue()
+
+ def ensure_started(self):
+ if not self.started:
+ self.start()
+
+ def halt(self):
+ """Safely stop the thread."""
+ if not self.started:
+ return
+
+ self.stop.set()
+ os.write(self.writefd, b'\0') # Ensure we're not locked in a read()
+ self.join()
+
+class SubprocessStreamCapturePlugin(Plugin):
+ name='subprocstreams'
+ def __init__(self):
+ Plugin.__init__(self)
+ self.stream_capturer = StreamCapturer()
+ self.destination = os.environ.get('IPTEST_SUBPROC_STREAMS', 'capture')
+ # This is ugly, but distant parts of the test machinery need to be able
+ # to redirect streams, so we make the object globally accessible.
+ nose.iptest_stdstreams_fileno = self.get_write_fileno
+
+ def get_write_fileno(self):
+ if self.destination == 'capture':
+ self.stream_capturer.ensure_started()
+ return self.stream_capturer.writefd
+ elif self.destination == 'discard':
+ return os.open(os.devnull, os.O_WRONLY)
+ else:
+ return sys.__stdout__.fileno()
+
+ def configure(self, options, config):
+ Plugin.configure(self, options, config)
+ # Override nose trying to disable plugin.
+ if self.destination == 'capture':
+ self.enabled = True
+
+ def startTest(self, test):
+ # Reset log capture
+ self.stream_capturer.reset_buffer()
+
+ def formatFailure(self, test, err):
+ # Show output
+ ec, ev, tb = err
+ captured = self.stream_capturer.get_buffer().decode('utf-8', 'replace')
+ if captured.strip():
+ ev = safe_str(ev)
+ out = [ev, '>> begin captured subprocess output <<',
+ captured,
+ '>> end captured subprocess output <<']
+ return ec, '\n'.join(out), tb
+
+ return err
+
+ formatError = formatFailure
+
+ def finalize(self, result):
+ self.stream_capturer.halt()
+
+
+def run_iptest():
+ """Run the IPython test suite using nose.
+
+ This function is called when this script is **not** called with the form
+ `iptest all`. It simply calls nose with appropriate command line flags
+ and accepts all of the standard nose arguments.
+ """
+ # Apply our monkeypatch to Xunit
+ if '--with-xunit' in sys.argv and not hasattr(Xunit, 'orig_addError'):
+ monkeypatch_xunit()
+
+ arg1 = sys.argv[1]
+ if arg1 in test_sections:
+ section = test_sections[arg1]
+ sys.argv[1:2] = section.includes
+ elif arg1.startswith('IPython.') and arg1[8:] in test_sections:
+ section = test_sections[arg1[8:]]
+ sys.argv[1:2] = section.includes
+ else:
+ section = TestSection(arg1, includes=[arg1])
+
+
+ argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
+ # We add --exe because of setuptools' imbecility (it
+ # blindly does chmod +x on ALL files). Nose does the
+ # right thing and it tries to avoid executables,
+ # setuptools unfortunately forces our hand here. This
+ # has been discussed on the distutils list and the
+ # setuptools devs refuse to fix this problem!
+ '--exe',
+ ]
+ if '-a' not in argv and '-A' not in argv:
+ argv = argv + ['-a', '!crash']
+
+ if nose.__version__ >= '0.11':
+ # I don't fully understand why we need this one, but depending on what
+ # directory the test suite is run from, if we don't give it, 0 tests
+ # get run. Specifically, if the test suite is run from the source dir
+ # with an argument (like 'iptest.py IPython.core', 0 tests are run,
+ # even if the same call done in this directory works fine). It appears
+ # that if the requested package is in the current dir, nose bails early
+ # by default. Since it's otherwise harmless, leave it in by default
+ # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
+ argv.append('--traverse-namespace')
+
+ plugins = [ ExclusionPlugin(section.excludes), KnownFailure(),
+ SubprocessStreamCapturePlugin() ]
+
+ # we still have some vestigial doctests in core
+ if (section.name.startswith(('core', 'IPython.core'))):
+ plugins.append(IPythonDoctest())
+ argv.extend([
+ '--with-ipdoctest',
+ '--ipdoctest-tests',
+ '--ipdoctest-extension=txt',
+ ])
+
+
+ # Use working directory set by parent process (see iptestcontroller)
+ if 'IPTEST_WORKING_DIR' in os.environ:
+ os.chdir(os.environ['IPTEST_WORKING_DIR'])
+
+ # We need a global ipython running in this process, but the special
+ # in-process group spawns its own IPython kernels, so for *that* group we
+ # must avoid also opening the global one (otherwise there's a conflict of
+ # singletons). Ultimately the solution to this problem is to refactor our
+ # assumptions about what needs to be a singleton and what doesn't (app
+ # objects should, individual shells shouldn't). But for now, this
+ # workaround allows the test suite for the inprocess module to complete.
+ if 'kernel.inprocess' not in section.name:
+ from IPython.testing import globalipapp
+ globalipapp.start_ipython()
+
+ # Now nose can run
+ TestProgram(argv=argv, addplugins=plugins)
+
+if __name__ == '__main__':
+ run_iptest()
diff --git a/contrib/python/ipython/py2/IPython/testing/iptestcontroller.py b/contrib/python/ipython/py2/IPython/testing/iptestcontroller.py
index 6d8834f193..95aa06e4a4 100644
--- a/contrib/python/ipython/py2/IPython/testing/iptestcontroller.py
+++ b/contrib/python/ipython/py2/IPython/testing/iptestcontroller.py
@@ -1,532 +1,532 @@
-# -*- coding: utf-8 -*-
-"""IPython Test Process Controller
-
-This module runs one or more subprocesses which will actually run the IPython
-test suite.
-
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
-import argparse
-import json
-import multiprocessing.pool
-import os
-import stat
-import re
-import requests
-import shutil
-import signal
-import sys
-import subprocess
-import time
-
-from .iptest import (
- have, test_group_names as py_test_group_names, test_sections, StreamCapturer,
- test_for,
-)
-from IPython.utils.path import compress_user
-from IPython.utils.py3compat import bytes_to_str
-from IPython.utils.sysinfo import get_sys_info
-from IPython.utils.tempdir import TemporaryDirectory
-from IPython.utils.text import strip_ansi
-
-try:
- # Python >= 3.3
- from subprocess import TimeoutExpired
- def popen_wait(p, timeout):
- return p.wait(timeout)
-except ImportError:
- class TimeoutExpired(Exception):
- pass
- def popen_wait(p, timeout):
- """backport of Popen.wait from Python 3"""
- for i in range(int(10 * timeout)):
- if p.poll() is not None:
- return
- time.sleep(0.1)
- if p.poll() is None:
- raise TimeoutExpired
-
-NOTEBOOK_SHUTDOWN_TIMEOUT = 10
-
-class TestController(object):
- """Run tests in a subprocess
- """
- #: str, IPython test suite to be executed.
- section = None
- #: list, command line arguments to be executed
- cmd = None
- #: dict, extra environment variables to set for the subprocess
- env = None
- #: list, TemporaryDirectory instances to clear up when the process finishes
- dirs = None
- #: subprocess.Popen instance
- process = None
- #: str, process stdout+stderr
- stdout = None
-
- def __init__(self):
- self.cmd = []
- self.env = {}
- self.dirs = []
-
- def setup(self):
- """Create temporary directories etc.
-
- This is only called when we know the test group will be run. Things
- created here may be cleaned up by self.cleanup().
- """
- pass
-
- def launch(self, buffer_output=False, capture_output=False):
- # print('*** ENV:', self.env) # dbg
- # print('*** CMD:', self.cmd) # dbg
- env = os.environ.copy()
- env.update(self.env)
- if buffer_output:
- capture_output = True
- self.stdout_capturer = c = StreamCapturer(echo=not buffer_output)
- c.start()
- stdout = c.writefd if capture_output else None
- stderr = subprocess.STDOUT if capture_output else None
- self.process = subprocess.Popen(self.cmd, stdout=stdout,
- stderr=stderr, env=env)
-
- def wait(self):
- self.process.wait()
- self.stdout_capturer.halt()
- self.stdout = self.stdout_capturer.get_buffer()
- return self.process.returncode
-
- def print_extra_info(self):
- """Print extra information about this test run.
-
- If we're running in parallel and showing the concise view, this is only
- called if the test group fails. Otherwise, it's called before the test
- group is started.
-
- The base implementation does nothing, but it can be overridden by
- subclasses.
- """
- return
-
- def cleanup_process(self):
- """Cleanup on exit by killing any leftover processes."""
- subp = self.process
- if subp is None or (subp.poll() is not None):
- return # Process doesn't exist, or is already dead.
-
- try:
- print('Cleaning up stale PID: %d' % subp.pid)
- subp.kill()
- except: # (OSError, WindowsError) ?
- # This is just a best effort, if we fail or the process was
- # really gone, ignore it.
- pass
- else:
- for i in range(10):
- if subp.poll() is None:
- time.sleep(0.1)
- else:
- break
-
- if subp.poll() is None:
- # The process did not die...
- print('... failed. Manual cleanup may be required.')
-
- def cleanup(self):
- "Kill process if it's still alive, and clean up temporary directories"
- self.cleanup_process()
- for td in self.dirs:
- td.cleanup()
-
- __del__ = cleanup
-
-
-class PyTestController(TestController):
- """Run Python tests using IPython.testing.iptest"""
- #: str, Python command to execute in subprocess
- pycmd = None
-
- def __init__(self, section, options):
- """Create new test runner."""
- TestController.__init__(self)
- self.section = section
- # pycmd is put into cmd[2] in PyTestController.launch()
- self.cmd = [sys.executable, '-c', None, section]
- self.pycmd = "from IPython.testing.iptest import run_iptest; run_iptest()"
- self.options = options
-
- def setup(self):
- ipydir = TemporaryDirectory()
- self.dirs.append(ipydir)
- self.env['IPYTHONDIR'] = ipydir.name
- self.workingdir = workingdir = TemporaryDirectory()
- self.dirs.append(workingdir)
- self.env['IPTEST_WORKING_DIR'] = workingdir.name
- # This means we won't get odd effects from our own matplotlib config
- self.env['MPLCONFIGDIR'] = workingdir.name
- # For security reasons (http://bugs.python.org/issue16202), use
- # a temporary directory to which other users have no access.
- self.env['TMPDIR'] = workingdir.name
-
- # Add a non-accessible directory to PATH (see gh-7053)
- noaccess = os.path.join(self.workingdir.name, "_no_access_")
- self.noaccess = noaccess
- os.mkdir(noaccess, 0)
-
- PATH = os.environ.get('PATH', '')
- if PATH:
- PATH = noaccess + os.pathsep + PATH
- else:
- PATH = noaccess
- self.env['PATH'] = PATH
-
- # From options:
- if self.options.xunit:
- self.add_xunit()
- if self.options.coverage:
- self.add_coverage()
- self.env['IPTEST_SUBPROC_STREAMS'] = self.options.subproc_streams
- self.cmd.extend(self.options.extra_args)
-
- def cleanup(self):
- """
- Make the non-accessible directory created in setup() accessible
- again, otherwise deleting the workingdir will fail.
- """
- os.chmod(self.noaccess, stat.S_IRWXU)
- TestController.cleanup(self)
-
- @property
- def will_run(self):
- try:
- return test_sections[self.section].will_run
- except KeyError:
- return True
-
- def add_xunit(self):
- xunit_file = os.path.abspath(self.section + '.xunit.xml')
- self.cmd.extend(['--with-xunit', '--xunit-file', xunit_file])
-
- def add_coverage(self):
- try:
- sources = test_sections[self.section].includes
- except KeyError:
- sources = ['IPython']
-
- coverage_rc = ("[run]\n"
- "data_file = {data_file}\n"
- "source =\n"
- " {source}\n"
- ).format(data_file=os.path.abspath('.coverage.'+self.section),
- source="\n ".join(sources))
- config_file = os.path.join(self.workingdir.name, '.coveragerc')
- with open(config_file, 'w') as f:
- f.write(coverage_rc)
-
- self.env['COVERAGE_PROCESS_START'] = config_file
- self.pycmd = "import coverage; coverage.process_startup(); " + self.pycmd
-
- def launch(self, buffer_output=False):
- self.cmd[2] = self.pycmd
- super(PyTestController, self).launch(buffer_output=buffer_output)
-
-
-def prepare_controllers(options):
- """Returns two lists of TestController instances, those to run, and those
- not to run."""
- testgroups = options.testgroups
- if not testgroups:
- testgroups = py_test_group_names
-
- controllers = [PyTestController(name, options) for name in testgroups]
-
- to_run = [c for c in controllers if c.will_run]
- not_run = [c for c in controllers if not c.will_run]
- return to_run, not_run
-
-def do_run(controller, buffer_output=True):
- """Setup and run a test controller.
-
- If buffer_output is True, no output is displayed, to avoid it appearing
- interleaved. In this case, the caller is responsible for displaying test
- output on failure.
-
- Returns
- -------
- controller : TestController
- The same controller as passed in, as a convenience for using map() type
- APIs.
- exitcode : int
- The exit code of the test subprocess. Non-zero indicates failure.
- """
- try:
- try:
- controller.setup()
- if not buffer_output:
- controller.print_extra_info()
- controller.launch(buffer_output=buffer_output)
- except Exception:
- import traceback
- traceback.print_exc()
- return controller, 1 # signal failure
-
- exitcode = controller.wait()
- return controller, exitcode
-
- except KeyboardInterrupt:
- return controller, -signal.SIGINT
- finally:
- controller.cleanup()
-
-def report():
- """Return a string with a summary report of test-related variables."""
- inf = get_sys_info()
- out = []
- def _add(name, value):
- out.append((name, value))
-
- _add('IPython version', inf['ipython_version'])
- _add('IPython commit', "{} ({})".format(inf['commit_hash'], inf['commit_source']))
- _add('IPython package', compress_user(inf['ipython_path']))
- _add('Python version', inf['sys_version'].replace('\n',''))
- _add('sys.executable', compress_user(inf['sys_executable']))
- _add('Platform', inf['platform'])
-
- width = max(len(n) for (n,v) in out)
- out = ["{:<{width}}: {}\n".format(n, v, width=width) for (n,v) in out]
-
- avail = []
- not_avail = []
-
- for k, is_avail in have.items():
- if is_avail:
- avail.append(k)
- else:
- not_avail.append(k)
-
- if avail:
- out.append('\nTools and libraries available at test time:\n')
- avail.sort()
- out.append(' ' + ' '.join(avail)+'\n')
-
- if not_avail:
- out.append('\nTools and libraries NOT available at test time:\n')
- not_avail.sort()
- out.append(' ' + ' '.join(not_avail)+'\n')
-
- return ''.join(out)
-
-def run_iptestall(options):
- """Run the entire IPython test suite by calling nose and trial.
-
- This function constructs :class:`IPTester` instances for all IPython
- modules and package and then runs each of them. This causes the modules
- and packages of IPython to be tested each in their own subprocess using
- nose.
-
- Parameters
- ----------
-
- All parameters are passed as attributes of the options object.
-
- testgroups : list of str
- Run only these sections of the test suite. If empty, run all the available
- sections.
-
- fast : int or None
- Run the test suite in parallel, using n simultaneous processes. If None
- is passed, one process is used per CPU core. Default 1 (i.e. sequential)
-
- inc_slow : bool
- Include slow tests. By default, these tests aren't run.
-
- url : unicode
- Address:port to use when running the JS tests.
-
- xunit : bool
- Produce Xunit XML output. This is written to multiple foo.xunit.xml files.
-
- coverage : bool or str
- Measure code coverage from tests. True will store the raw coverage data,
- or pass 'html' or 'xml' to get reports.
-
- extra_args : list
- Extra arguments to pass to the test subprocesses, e.g. '-v'
- """
- to_run, not_run = prepare_controllers(options)
-
- def justify(ltext, rtext, width=70, fill='-'):
- ltext += ' '
- rtext = (' ' + rtext).rjust(width - len(ltext), fill)
- return ltext + rtext
-
- # Run all test runners, tracking execution time
- failed = []
- t_start = time.time()
-
- print()
- if options.fast == 1:
- # This actually means sequential, i.e. with 1 job
- for controller in to_run:
- print('Test group:', controller.section)
- sys.stdout.flush() # Show in correct order when output is piped
- controller, res = do_run(controller, buffer_output=False)
- if res:
- failed.append(controller)
- if res == -signal.SIGINT:
- print("Interrupted")
- break
- print()
-
- else:
- # Run tests concurrently
- try:
- pool = multiprocessing.pool.ThreadPool(options.fast)
- for (controller, res) in pool.imap_unordered(do_run, to_run):
- res_string = 'OK' if res == 0 else 'FAILED'
- print(justify('Test group: ' + controller.section, res_string))
- if res:
- controller.print_extra_info()
- print(bytes_to_str(controller.stdout))
- failed.append(controller)
- if res == -signal.SIGINT:
- print("Interrupted")
- break
- except KeyboardInterrupt:
- return
-
- for controller in not_run:
- print(justify('Test group: ' + controller.section, 'NOT RUN'))
-
- t_end = time.time()
- t_tests = t_end - t_start
- nrunners = len(to_run)
- nfail = len(failed)
- # summarize results
- print('_'*70)
- print('Test suite completed for system with the following information:')
- print(report())
- took = "Took %.3fs." % t_tests
- print('Status: ', end='')
- if not failed:
- print('OK (%d test groups).' % nrunners, took)
- else:
- # If anything went wrong, point out what command to rerun manually to
- # see the actual errors and individual summary
- failed_sections = [c.section for c in failed]
- print('ERROR - {} out of {} test groups failed ({}).'.format(nfail,
- nrunners, ', '.join(failed_sections)), took)
- print()
- print('You may wish to rerun these, with:')
- print(' iptest', *failed_sections)
- print()
-
- if options.coverage:
- from coverage import coverage, CoverageException
- cov = coverage(data_file='.coverage')
- cov.combine()
- cov.save()
-
- # Coverage HTML report
- if options.coverage == 'html':
- html_dir = 'ipy_htmlcov'
- shutil.rmtree(html_dir, ignore_errors=True)
- print("Writing HTML coverage report to %s/ ... " % html_dir, end="")
- sys.stdout.flush()
-
- # Custom HTML reporter to clean up module names.
- from coverage.html import HtmlReporter
- class CustomHtmlReporter(HtmlReporter):
- def find_code_units(self, morfs):
- super(CustomHtmlReporter, self).find_code_units(morfs)
- for cu in self.code_units:
- nameparts = cu.name.split(os.sep)
- if 'IPython' not in nameparts:
- continue
- ix = nameparts.index('IPython')
- cu.name = '.'.join(nameparts[ix:])
-
- # Reimplement the html_report method with our custom reporter
- cov.get_data()
- cov.config.from_args(omit='*{0}tests{0}*'.format(os.sep), html_dir=html_dir,
- html_title='IPython test coverage',
- )
- reporter = CustomHtmlReporter(cov, cov.config)
- reporter.report(None)
- print('done.')
-
- # Coverage XML report
- elif options.coverage == 'xml':
- try:
- cov.xml_report(outfile='ipy_coverage.xml')
- except CoverageException as e:
- print('Generating coverage report failed. Are you running javascript tests only?')
- import traceback
- traceback.print_exc()
-
- if failed:
- # Ensure that our exit code indicates failure
- sys.exit(1)
-
-argparser = argparse.ArgumentParser(description='Run IPython test suite')
-argparser.add_argument('testgroups', nargs='*',
- help='Run specified groups of tests. If omitted, run '
- 'all tests.')
-argparser.add_argument('--all', action='store_true',
- help='Include slow tests not run by default.')
-argparser.add_argument('--url', help="URL to use for the JS tests.")
-argparser.add_argument('-j', '--fast', nargs='?', const=None, default=1, type=int,
- help='Run test sections in parallel. This starts as many '
- 'processes as you have cores, or you can specify a number.')
-argparser.add_argument('--xunit', action='store_true',
- help='Produce Xunit XML results')
-argparser.add_argument('--coverage', nargs='?', const=True, default=False,
- help="Measure test coverage. Specify 'html' or "
- "'xml' to get reports.")
-argparser.add_argument('--subproc-streams', default='capture',
- help="What to do with stdout/stderr from subprocesses. "
- "'capture' (default), 'show' and 'discard' are the options.")
-
-def default_options():
- """Get an argparse Namespace object with the default arguments, to pass to
- :func:`run_iptestall`.
- """
- options = argparser.parse_args([])
- options.extra_args = []
- return options
-
-def main():
- # iptest doesn't work correctly if the working directory is the
- # root of the IPython source tree. Tell the user to avoid
- # frustration.
- if os.path.exists(os.path.join(os.getcwd(),
- 'IPython', 'testing', '__main__.py')):
- print("Don't run iptest from the IPython source directory",
- file=sys.stderr)
- sys.exit(1)
- # Arguments after -- should be passed through to nose. Argparse treats
- # everything after -- as regular positional arguments, so we separate them
- # first.
- try:
- ix = sys.argv.index('--')
- except ValueError:
- to_parse = sys.argv[1:]
- extra_args = []
- else:
- to_parse = sys.argv[1:ix]
- extra_args = sys.argv[ix+1:]
-
- options = argparser.parse_args(to_parse)
- options.extra_args = extra_args
-
- run_iptestall(options)
-
-
-if __name__ == '__main__':
- main()
+# -*- coding: utf-8 -*-
+"""IPython Test Process Controller
+
+This module runs one or more subprocesses which will actually run the IPython
+test suite.
+
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
+import argparse
+import json
+import multiprocessing.pool
+import os
+import stat
+import re
+import requests
+import shutil
+import signal
+import sys
+import subprocess
+import time
+
+from .iptest import (
+ have, test_group_names as py_test_group_names, test_sections, StreamCapturer,
+ test_for,
+)
+from IPython.utils.path import compress_user
+from IPython.utils.py3compat import bytes_to_str
+from IPython.utils.sysinfo import get_sys_info
+from IPython.utils.tempdir import TemporaryDirectory
+from IPython.utils.text import strip_ansi
+
+try:
+ # Python >= 3.3
+ from subprocess import TimeoutExpired
+ def popen_wait(p, timeout):
+ return p.wait(timeout)
+except ImportError:
+ class TimeoutExpired(Exception):
+ pass
+ def popen_wait(p, timeout):
+ """backport of Popen.wait from Python 3"""
+ for i in range(int(10 * timeout)):
+ if p.poll() is not None:
+ return
+ time.sleep(0.1)
+ if p.poll() is None:
+ raise TimeoutExpired
+
+NOTEBOOK_SHUTDOWN_TIMEOUT = 10
+
+class TestController(object):
+ """Run tests in a subprocess
+ """
+ #: str, IPython test suite to be executed.
+ section = None
+ #: list, command line arguments to be executed
+ cmd = None
+ #: dict, extra environment variables to set for the subprocess
+ env = None
+ #: list, TemporaryDirectory instances to clear up when the process finishes
+ dirs = None
+ #: subprocess.Popen instance
+ process = None
+ #: str, process stdout+stderr
+ stdout = None
+
+ def __init__(self):
+ self.cmd = []
+ self.env = {}
+ self.dirs = []
+
+ def setup(self):
+ """Create temporary directories etc.
+
+ This is only called when we know the test group will be run. Things
+ created here may be cleaned up by self.cleanup().
+ """
+ pass
+
+ def launch(self, buffer_output=False, capture_output=False):
+ # print('*** ENV:', self.env) # dbg
+ # print('*** CMD:', self.cmd) # dbg
+ env = os.environ.copy()
+ env.update(self.env)
+ if buffer_output:
+ capture_output = True
+ self.stdout_capturer = c = StreamCapturer(echo=not buffer_output)
+ c.start()
+ stdout = c.writefd if capture_output else None
+ stderr = subprocess.STDOUT if capture_output else None
+ self.process = subprocess.Popen(self.cmd, stdout=stdout,
+ stderr=stderr, env=env)
+
+ def wait(self):
+ self.process.wait()
+ self.stdout_capturer.halt()
+ self.stdout = self.stdout_capturer.get_buffer()
+ return self.process.returncode
+
+ def print_extra_info(self):
+ """Print extra information about this test run.
+
+ If we're running in parallel and showing the concise view, this is only
+ called if the test group fails. Otherwise, it's called before the test
+ group is started.
+
+ The base implementation does nothing, but it can be overridden by
+ subclasses.
+ """
+ return
+
+ def cleanup_process(self):
+ """Cleanup on exit by killing any leftover processes."""
+ subp = self.process
+ if subp is None or (subp.poll() is not None):
+ return # Process doesn't exist, or is already dead.
+
+ try:
+ print('Cleaning up stale PID: %d' % subp.pid)
+ subp.kill()
+ except: # (OSError, WindowsError) ?
+ # This is just a best effort, if we fail or the process was
+ # really gone, ignore it.
+ pass
+ else:
+ for i in range(10):
+ if subp.poll() is None:
+ time.sleep(0.1)
+ else:
+ break
+
+ if subp.poll() is None:
+ # The process did not die...
+ print('... failed. Manual cleanup may be required.')
+
+ def cleanup(self):
+ "Kill process if it's still alive, and clean up temporary directories"
+ self.cleanup_process()
+ for td in self.dirs:
+ td.cleanup()
+
+ __del__ = cleanup
+
+
+class PyTestController(TestController):
+ """Run Python tests using IPython.testing.iptest"""
+ #: str, Python command to execute in subprocess
+ pycmd = None
+
+ def __init__(self, section, options):
+ """Create new test runner."""
+ TestController.__init__(self)
+ self.section = section
+ # pycmd is put into cmd[2] in PyTestController.launch()
+ self.cmd = [sys.executable, '-c', None, section]
+ self.pycmd = "from IPython.testing.iptest import run_iptest; run_iptest()"
+ self.options = options
+
+ def setup(self):
+ ipydir = TemporaryDirectory()
+ self.dirs.append(ipydir)
+ self.env['IPYTHONDIR'] = ipydir.name
+ self.workingdir = workingdir = TemporaryDirectory()
+ self.dirs.append(workingdir)
+ self.env['IPTEST_WORKING_DIR'] = workingdir.name
+ # This means we won't get odd effects from our own matplotlib config
+ self.env['MPLCONFIGDIR'] = workingdir.name
+ # For security reasons (http://bugs.python.org/issue16202), use
+ # a temporary directory to which other users have no access.
+ self.env['TMPDIR'] = workingdir.name
+
+ # Add a non-accessible directory to PATH (see gh-7053)
+ noaccess = os.path.join(self.workingdir.name, "_no_access_")
+ self.noaccess = noaccess
+ os.mkdir(noaccess, 0)
+
+ PATH = os.environ.get('PATH', '')
+ if PATH:
+ PATH = noaccess + os.pathsep + PATH
+ else:
+ PATH = noaccess
+ self.env['PATH'] = PATH
+
+ # From options:
+ if self.options.xunit:
+ self.add_xunit()
+ if self.options.coverage:
+ self.add_coverage()
+ self.env['IPTEST_SUBPROC_STREAMS'] = self.options.subproc_streams
+ self.cmd.extend(self.options.extra_args)
+
+ def cleanup(self):
+ """
+ Make the non-accessible directory created in setup() accessible
+ again, otherwise deleting the workingdir will fail.
+ """
+ os.chmod(self.noaccess, stat.S_IRWXU)
+ TestController.cleanup(self)
+
+ @property
+ def will_run(self):
+ try:
+ return test_sections[self.section].will_run
+ except KeyError:
+ return True
+
+ def add_xunit(self):
+ xunit_file = os.path.abspath(self.section + '.xunit.xml')
+ self.cmd.extend(['--with-xunit', '--xunit-file', xunit_file])
+
+ def add_coverage(self):
+ try:
+ sources = test_sections[self.section].includes
+ except KeyError:
+ sources = ['IPython']
+
+ coverage_rc = ("[run]\n"
+ "data_file = {data_file}\n"
+ "source =\n"
+ " {source}\n"
+ ).format(data_file=os.path.abspath('.coverage.'+self.section),
+ source="\n ".join(sources))
+ config_file = os.path.join(self.workingdir.name, '.coveragerc')
+ with open(config_file, 'w') as f:
+ f.write(coverage_rc)
+
+ self.env['COVERAGE_PROCESS_START'] = config_file
+ self.pycmd = "import coverage; coverage.process_startup(); " + self.pycmd
+
+ def launch(self, buffer_output=False):
+ self.cmd[2] = self.pycmd
+ super(PyTestController, self).launch(buffer_output=buffer_output)
+
+
+def prepare_controllers(options):
+ """Returns two lists of TestController instances, those to run, and those
+ not to run."""
+ testgroups = options.testgroups
+ if not testgroups:
+ testgroups = py_test_group_names
+
+ controllers = [PyTestController(name, options) for name in testgroups]
+
+ to_run = [c for c in controllers if c.will_run]
+ not_run = [c for c in controllers if not c.will_run]
+ return to_run, not_run
+
+def do_run(controller, buffer_output=True):
+ """Setup and run a test controller.
+
+ If buffer_output is True, no output is displayed, to avoid it appearing
+ interleaved. In this case, the caller is responsible for displaying test
+ output on failure.
+
+ Returns
+ -------
+ controller : TestController
+ The same controller as passed in, as a convenience for using map() type
+ APIs.
+ exitcode : int
+ The exit code of the test subprocess. Non-zero indicates failure.
+ """
+ try:
+ try:
+ controller.setup()
+ if not buffer_output:
+ controller.print_extra_info()
+ controller.launch(buffer_output=buffer_output)
+ except Exception:
+ import traceback
+ traceback.print_exc()
+ return controller, 1 # signal failure
+
+ exitcode = controller.wait()
+ return controller, exitcode
+
+ except KeyboardInterrupt:
+ return controller, -signal.SIGINT
+ finally:
+ controller.cleanup()
+
+def report():
+ """Return a string with a summary report of test-related variables."""
+ inf = get_sys_info()
+ out = []
+ def _add(name, value):
+ out.append((name, value))
+
+ _add('IPython version', inf['ipython_version'])
+ _add('IPython commit', "{} ({})".format(inf['commit_hash'], inf['commit_source']))
+ _add('IPython package', compress_user(inf['ipython_path']))
+ _add('Python version', inf['sys_version'].replace('\n',''))
+ _add('sys.executable', compress_user(inf['sys_executable']))
+ _add('Platform', inf['platform'])
+
+ width = max(len(n) for (n,v) in out)
+ out = ["{:<{width}}: {}\n".format(n, v, width=width) for (n,v) in out]
+
+ avail = []
+ not_avail = []
+
+ for k, is_avail in have.items():
+ if is_avail:
+ avail.append(k)
+ else:
+ not_avail.append(k)
+
+ if avail:
+ out.append('\nTools and libraries available at test time:\n')
+ avail.sort()
+ out.append(' ' + ' '.join(avail)+'\n')
+
+ if not_avail:
+ out.append('\nTools and libraries NOT available at test time:\n')
+ not_avail.sort()
+ out.append(' ' + ' '.join(not_avail)+'\n')
+
+ return ''.join(out)
+
+def run_iptestall(options):
+ """Run the entire IPython test suite by calling nose and trial.
+
+ This function constructs :class:`IPTester` instances for all IPython
+ modules and package and then runs each of them. This causes the modules
+ and packages of IPython to be tested each in their own subprocess using
+ nose.
+
+ Parameters
+ ----------
+
+ All parameters are passed as attributes of the options object.
+
+ testgroups : list of str
+ Run only these sections of the test suite. If empty, run all the available
+ sections.
+
+ fast : int or None
+ Run the test suite in parallel, using n simultaneous processes. If None
+ is passed, one process is used per CPU core. Default 1 (i.e. sequential)
+
+ inc_slow : bool
+ Include slow tests. By default, these tests aren't run.
+
+ url : unicode
+ Address:port to use when running the JS tests.
+
+ xunit : bool
+ Produce Xunit XML output. This is written to multiple foo.xunit.xml files.
+
+ coverage : bool or str
+ Measure code coverage from tests. True will store the raw coverage data,
+ or pass 'html' or 'xml' to get reports.
+
+ extra_args : list
+ Extra arguments to pass to the test subprocesses, e.g. '-v'
+ """
+ to_run, not_run = prepare_controllers(options)
+
+ def justify(ltext, rtext, width=70, fill='-'):
+ ltext += ' '
+ rtext = (' ' + rtext).rjust(width - len(ltext), fill)
+ return ltext + rtext
+
+ # Run all test runners, tracking execution time
+ failed = []
+ t_start = time.time()
+
+ print()
+ if options.fast == 1:
+ # This actually means sequential, i.e. with 1 job
+ for controller in to_run:
+ print('Test group:', controller.section)
+ sys.stdout.flush() # Show in correct order when output is piped
+ controller, res = do_run(controller, buffer_output=False)
+ if res:
+ failed.append(controller)
+ if res == -signal.SIGINT:
+ print("Interrupted")
+ break
+ print()
+
+ else:
+ # Run tests concurrently
+ try:
+ pool = multiprocessing.pool.ThreadPool(options.fast)
+ for (controller, res) in pool.imap_unordered(do_run, to_run):
+ res_string = 'OK' if res == 0 else 'FAILED'
+ print(justify('Test group: ' + controller.section, res_string))
+ if res:
+ controller.print_extra_info()
+ print(bytes_to_str(controller.stdout))
+ failed.append(controller)
+ if res == -signal.SIGINT:
+ print("Interrupted")
+ break
+ except KeyboardInterrupt:
+ return
+
+ for controller in not_run:
+ print(justify('Test group: ' + controller.section, 'NOT RUN'))
+
+ t_end = time.time()
+ t_tests = t_end - t_start
+ nrunners = len(to_run)
+ nfail = len(failed)
+ # summarize results
+ print('_'*70)
+ print('Test suite completed for system with the following information:')
+ print(report())
+ took = "Took %.3fs." % t_tests
+ print('Status: ', end='')
+ if not failed:
+ print('OK (%d test groups).' % nrunners, took)
+ else:
+ # If anything went wrong, point out what command to rerun manually to
+ # see the actual errors and individual summary
+ failed_sections = [c.section for c in failed]
+ print('ERROR - {} out of {} test groups failed ({}).'.format(nfail,
+ nrunners, ', '.join(failed_sections)), took)
+ print()
+ print('You may wish to rerun these, with:')
+ print(' iptest', *failed_sections)
+ print()
+
+ if options.coverage:
+ from coverage import coverage, CoverageException
+ cov = coverage(data_file='.coverage')
+ cov.combine()
+ cov.save()
+
+ # Coverage HTML report
+ if options.coverage == 'html':
+ html_dir = 'ipy_htmlcov'
+ shutil.rmtree(html_dir, ignore_errors=True)
+ print("Writing HTML coverage report to %s/ ... " % html_dir, end="")
+ sys.stdout.flush()
+
+ # Custom HTML reporter to clean up module names.
+ from coverage.html import HtmlReporter
+ class CustomHtmlReporter(HtmlReporter):
+ def find_code_units(self, morfs):
+ super(CustomHtmlReporter, self).find_code_units(morfs)
+ for cu in self.code_units:
+ nameparts = cu.name.split(os.sep)
+ if 'IPython' not in nameparts:
+ continue
+ ix = nameparts.index('IPython')
+ cu.name = '.'.join(nameparts[ix:])
+
+ # Reimplement the html_report method with our custom reporter
+ cov.get_data()
+ cov.config.from_args(omit='*{0}tests{0}*'.format(os.sep), html_dir=html_dir,
+ html_title='IPython test coverage',
+ )
+ reporter = CustomHtmlReporter(cov, cov.config)
+ reporter.report(None)
+ print('done.')
+
+ # Coverage XML report
+ elif options.coverage == 'xml':
+ try:
+ cov.xml_report(outfile='ipy_coverage.xml')
+ except CoverageException as e:
+ print('Generating coverage report failed. Are you running javascript tests only?')
+ import traceback
+ traceback.print_exc()
+
+ if failed:
+ # Ensure that our exit code indicates failure
+ sys.exit(1)
+
+argparser = argparse.ArgumentParser(description='Run IPython test suite')
+argparser.add_argument('testgroups', nargs='*',
+ help='Run specified groups of tests. If omitted, run '
+ 'all tests.')
+argparser.add_argument('--all', action='store_true',
+ help='Include slow tests not run by default.')
+argparser.add_argument('--url', help="URL to use for the JS tests.")
+argparser.add_argument('-j', '--fast', nargs='?', const=None, default=1, type=int,
+ help='Run test sections in parallel. This starts as many '
+ 'processes as you have cores, or you can specify a number.')
+argparser.add_argument('--xunit', action='store_true',
+ help='Produce Xunit XML results')
+argparser.add_argument('--coverage', nargs='?', const=True, default=False,
+ help="Measure test coverage. Specify 'html' or "
+ "'xml' to get reports.")
+argparser.add_argument('--subproc-streams', default='capture',
+ help="What to do with stdout/stderr from subprocesses. "
+ "'capture' (default), 'show' and 'discard' are the options.")
+
+def default_options():
+ """Get an argparse Namespace object with the default arguments, to pass to
+ :func:`run_iptestall`.
+ """
+ options = argparser.parse_args([])
+ options.extra_args = []
+ return options
+
+def main():
+ # iptest doesn't work correctly if the working directory is the
+ # root of the IPython source tree. Tell the user to avoid
+ # frustration.
+ if os.path.exists(os.path.join(os.getcwd(),
+ 'IPython', 'testing', '__main__.py')):
+ print("Don't run iptest from the IPython source directory",
+ file=sys.stderr)
+ sys.exit(1)
+ # Arguments after -- should be passed through to nose. Argparse treats
+ # everything after -- as regular positional arguments, so we separate them
+ # first.
+ try:
+ ix = sys.argv.index('--')
+ except ValueError:
+ to_parse = sys.argv[1:]
+ extra_args = []
+ else:
+ to_parse = sys.argv[1:ix]
+ extra_args = sys.argv[ix+1:]
+
+ options = argparser.parse_args(to_parse)
+ options.extra_args = extra_args
+
+ run_iptestall(options)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/contrib/python/ipython/py2/IPython/testing/ipunittest.py b/contrib/python/ipython/py2/IPython/testing/ipunittest.py
index 04ea8320fb..da059816e2 100644
--- a/contrib/python/ipython/py2/IPython/testing/ipunittest.py
+++ b/contrib/python/ipython/py2/IPython/testing/ipunittest.py
@@ -1,178 +1,178 @@
-"""Experimental code for cleaner support of IPython syntax with unittest.
-
-In IPython up until 0.10, we've used very hacked up nose machinery for running
-tests with IPython special syntax, and this has proved to be extremely slow.
-This module provides decorators to try a different approach, stemming from a
-conversation Brian and I (FP) had about this problem Sept/09.
-
-The goal is to be able to easily write simple functions that can be seen by
-unittest as tests, and ultimately for these to support doctests with full
-IPython syntax. Nose already offers this based on naming conventions and our
-hackish plugins, but we are seeking to move away from nose dependencies if
-possible.
-
-This module follows a different approach, based on decorators.
-
-- A decorator called @ipdoctest can mark any function as having a docstring
- that should be viewed as a doctest, but after syntax conversion.
-
-Authors
--------
-
-- Fernando Perez <Fernando.Perez@berkeley.edu>
-"""
-
-from __future__ import absolute_import
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2009-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Stdlib
-import re
-import unittest
-from doctest import DocTestFinder, DocTestRunner, TestResults
-
-#-----------------------------------------------------------------------------
-# Classes and functions
-#-----------------------------------------------------------------------------
-
-def count_failures(runner):
- """Count number of failures in a doctest runner.
-
- Code modeled after the summarize() method in doctest.
- """
- return [TestResults(f, t) for f, t in runner._name2ft.values() if f > 0 ]
-
-
-class IPython2PythonConverter(object):
- """Convert IPython 'syntax' to valid Python.
-
- Eventually this code may grow to be the full IPython syntax conversion
- implementation, but for now it only does prompt convertion."""
-
- def __init__(self):
- self.rps1 = re.compile(r'In\ \[\d+\]: ')
- self.rps2 = re.compile(r'\ \ \ \.\.\.+: ')
- self.rout = re.compile(r'Out\[\d+\]: \s*?\n?')
- self.pyps1 = '>>> '
- self.pyps2 = '... '
- self.rpyps1 = re.compile ('(\s*%s)(.*)$' % self.pyps1)
- self.rpyps2 = re.compile ('(\s*%s)(.*)$' % self.pyps2)
-
- def __call__(self, ds):
- """Convert IPython prompts to python ones in a string."""
- from . import globalipapp
-
- pyps1 = '>>> '
- pyps2 = '... '
- pyout = ''
-
- dnew = ds
- dnew = self.rps1.sub(pyps1, dnew)
- dnew = self.rps2.sub(pyps2, dnew)
- dnew = self.rout.sub(pyout, dnew)
- ip = globalipapp.get_ipython()
-
- # Convert input IPython source into valid Python.
- out = []
- newline = out.append
- for line in dnew.splitlines():
-
- mps1 = self.rpyps1.match(line)
- if mps1 is not None:
- prompt, text = mps1.groups()
- newline(prompt+ip.prefilter(text, False))
- continue
-
- mps2 = self.rpyps2.match(line)
- if mps2 is not None:
- prompt, text = mps2.groups()
- newline(prompt+ip.prefilter(text, True))
- continue
-
- newline(line)
- newline('') # ensure a closing newline, needed by doctest
- #print "PYSRC:", '\n'.join(out) # dbg
- return '\n'.join(out)
-
- #return dnew
-
-
-class Doc2UnitTester(object):
- """Class whose instances act as a decorator for docstring testing.
-
- In practice we're only likely to need one instance ever, made below (though
- no attempt is made at turning it into a singleton, there is no need for
- that).
- """
- def __init__(self, verbose=False):
- """New decorator.
-
- Parameters
- ----------
-
- verbose : boolean, optional (False)
- Passed to the doctest finder and runner to control verbosity.
- """
- self.verbose = verbose
- # We can reuse the same finder for all instances
- self.finder = DocTestFinder(verbose=verbose, recurse=False)
-
- def __call__(self, func):
- """Use as a decorator: doctest a function's docstring as a unittest.
-
- This version runs normal doctests, but the idea is to make it later run
- ipython syntax instead."""
-
- # Capture the enclosing instance with a different name, so the new
- # class below can see it without confusion regarding its own 'self'
- # that will point to the test instance at runtime
- d2u = self
-
- # Rewrite the function's docstring to have python syntax
- if func.__doc__ is not None:
- func.__doc__ = ip2py(func.__doc__)
-
- # Now, create a tester object that is a real unittest instance, so
- # normal unittest machinery (or Nose, or Trial) can find it.
- class Tester(unittest.TestCase):
- def test(self):
- # Make a new runner per function to be tested
- runner = DocTestRunner(verbose=d2u.verbose)
+"""Experimental code for cleaner support of IPython syntax with unittest.
+
+In IPython up until 0.10, we've used very hacked up nose machinery for running
+tests with IPython special syntax, and this has proved to be extremely slow.
+This module provides decorators to try a different approach, stemming from a
+conversation Brian and I (FP) had about this problem Sept/09.
+
+The goal is to be able to easily write simple functions that can be seen by
+unittest as tests, and ultimately for these to support doctests with full
+IPython syntax. Nose already offers this based on naming conventions and our
+hackish plugins, but we are seeking to move away from nose dependencies if
+possible.
+
+This module follows a different approach, based on decorators.
+
+- A decorator called @ipdoctest can mark any function as having a docstring
+ that should be viewed as a doctest, but after syntax conversion.
+
+Authors
+-------
+
+- Fernando Perez <Fernando.Perez@berkeley.edu>
+"""
+
+from __future__ import absolute_import
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2009-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Stdlib
+import re
+import unittest
+from doctest import DocTestFinder, DocTestRunner, TestResults
+
+#-----------------------------------------------------------------------------
+# Classes and functions
+#-----------------------------------------------------------------------------
+
+def count_failures(runner):
+ """Count number of failures in a doctest runner.
+
+ Code modeled after the summarize() method in doctest.
+ """
+ return [TestResults(f, t) for f, t in runner._name2ft.values() if f > 0 ]
+
+
+class IPython2PythonConverter(object):
+ """Convert IPython 'syntax' to valid Python.
+
+ Eventually this code may grow to be the full IPython syntax conversion
+ implementation, but for now it only does prompt convertion."""
+
+ def __init__(self):
+ self.rps1 = re.compile(r'In\ \[\d+\]: ')
+ self.rps2 = re.compile(r'\ \ \ \.\.\.+: ')
+ self.rout = re.compile(r'Out\[\d+\]: \s*?\n?')
+ self.pyps1 = '>>> '
+ self.pyps2 = '... '
+ self.rpyps1 = re.compile ('(\s*%s)(.*)$' % self.pyps1)
+ self.rpyps2 = re.compile ('(\s*%s)(.*)$' % self.pyps2)
+
+ def __call__(self, ds):
+ """Convert IPython prompts to python ones in a string."""
+ from . import globalipapp
+
+ pyps1 = '>>> '
+ pyps2 = '... '
+ pyout = ''
+
+ dnew = ds
+ dnew = self.rps1.sub(pyps1, dnew)
+ dnew = self.rps2.sub(pyps2, dnew)
+ dnew = self.rout.sub(pyout, dnew)
+ ip = globalipapp.get_ipython()
+
+ # Convert input IPython source into valid Python.
+ out = []
+ newline = out.append
+ for line in dnew.splitlines():
+
+ mps1 = self.rpyps1.match(line)
+ if mps1 is not None:
+ prompt, text = mps1.groups()
+ newline(prompt+ip.prefilter(text, False))
+ continue
+
+ mps2 = self.rpyps2.match(line)
+ if mps2 is not None:
+ prompt, text = mps2.groups()
+ newline(prompt+ip.prefilter(text, True))
+ continue
+
+ newline(line)
+ newline('') # ensure a closing newline, needed by doctest
+ #print "PYSRC:", '\n'.join(out) # dbg
+ return '\n'.join(out)
+
+ #return dnew
+
+
+class Doc2UnitTester(object):
+ """Class whose instances act as a decorator for docstring testing.
+
+ In practice we're only likely to need one instance ever, made below (though
+ no attempt is made at turning it into a singleton, there is no need for
+ that).
+ """
+ def __init__(self, verbose=False):
+ """New decorator.
+
+ Parameters
+ ----------
+
+ verbose : boolean, optional (False)
+ Passed to the doctest finder and runner to control verbosity.
+ """
+ self.verbose = verbose
+ # We can reuse the same finder for all instances
+ self.finder = DocTestFinder(verbose=verbose, recurse=False)
+
+ def __call__(self, func):
+ """Use as a decorator: doctest a function's docstring as a unittest.
+
+ This version runs normal doctests, but the idea is to make it later run
+ ipython syntax instead."""
+
+ # Capture the enclosing instance with a different name, so the new
+ # class below can see it without confusion regarding its own 'self'
+ # that will point to the test instance at runtime
+ d2u = self
+
+ # Rewrite the function's docstring to have python syntax
+ if func.__doc__ is not None:
+ func.__doc__ = ip2py(func.__doc__)
+
+ # Now, create a tester object that is a real unittest instance, so
+ # normal unittest machinery (or Nose, or Trial) can find it.
+ class Tester(unittest.TestCase):
+ def test(self):
+ # Make a new runner per function to be tested
+ runner = DocTestRunner(verbose=d2u.verbose)
for the_test in d2u.finder.find(func, func.__name__):
runner.run(the_test)
- failed = count_failures(runner)
- if failed:
- # Since we only looked at a single function's docstring,
- # failed should contain at most one item. More than that
- # is a case we can't handle and should error out on
- if len(failed) > 1:
- err = "Invalid number of test results:" % failed
- raise ValueError(err)
- # Report a normal failure.
- self.fail('failed doctests: %s' % str(failed[0]))
-
- # Rename it so test reports have the original signature.
- Tester.__name__ = func.__name__
- return Tester
-
-
-def ipdocstring(func):
- """Change the function docstring via ip2py.
- """
- if func.__doc__ is not None:
- func.__doc__ = ip2py(func.__doc__)
- return func
-
-
-# Make an instance of the classes for public use
-ipdoctest = Doc2UnitTester()
-ip2py = IPython2PythonConverter()
+ failed = count_failures(runner)
+ if failed:
+ # Since we only looked at a single function's docstring,
+ # failed should contain at most one item. More than that
+ # is a case we can't handle and should error out on
+ if len(failed) > 1:
+ err = "Invalid number of test results:" % failed
+ raise ValueError(err)
+ # Report a normal failure.
+ self.fail('failed doctests: %s' % str(failed[0]))
+
+ # Rename it so test reports have the original signature.
+ Tester.__name__ = func.__name__
+ return Tester
+
+
+def ipdocstring(func):
+ """Change the function docstring via ip2py.
+ """
+ if func.__doc__ is not None:
+ func.__doc__ = ip2py(func.__doc__)
+ return func
+
+
+# Make an instance of the classes for public use
+ipdoctest = Doc2UnitTester()
+ip2py = IPython2PythonConverter()
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/Makefile b/contrib/python/ipython/py2/IPython/testing/plugin/Makefile
index d57d198f15..6f999a38fd 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/Makefile
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/Makefile
@@ -1,74 +1,74 @@
-# Set this prefix to where you want to install the plugin
-PREFIX=/usr/local
-
-NOSE0=nosetests -vs --with-doctest --doctest-tests --detailed-errors
-NOSE=nosetests -vvs --with-ipdoctest --doctest-tests --doctest-extension=txt \
---detailed-errors
-
-SRC=ipdoctest.py setup.py ../decorators.py
-
-# Default target for clean 'make'
-default: interactiveshell
-
-# The actual plugin installation
-plugin: IPython_doctest_plugin.egg-info
-
-# Simple targets that test one thing
-simple: plugin simple.py
- $(NOSE) simple.py
-
-dtest: plugin dtexample.py
- $(NOSE) dtexample.py
-
-rtest: plugin test_refs.py
- $(NOSE) test_refs.py
-
-test: plugin dtexample.py
- $(NOSE) dtexample.py test*.py test*.txt
-
-deb: plugin dtexample.py
- $(NOSE) test_combo.txt
-
-# IPython tests
-deco:
- $(NOSE0) IPython.testing.decorators
-
-magic: plugin
- $(NOSE) IPython.core.magic
-
-excolors: plugin
- $(NOSE) IPython.core.excolors
-
-interactiveshell: plugin
- $(NOSE) IPython.core.interactiveshell
-
-strd: plugin
- $(NOSE) IPython.core.strdispatch
-
-engine: plugin
- $(NOSE) IPython.kernel
-
-tf: plugin
- $(NOSE) IPython.config.traitlets
-
-# All of ipython itself
-ipython: plugin
- $(NOSE) IPython
-
-
-# Combined targets
-sr: rtest strd
-
-base: dtest rtest test strd deco
-
-quick: base interactiveshell ipipe
-
-all: base ipython
-
-# Main plugin and cleanup
-IPython_doctest_plugin.egg-info: $(SRC)
- python setup.py install --prefix=$(PREFIX)
- touch $@
-
-clean:
- rm -rf IPython_doctest_plugin.egg-info *~ *pyc build/ dist/
+# Set this prefix to where you want to install the plugin
+PREFIX=/usr/local
+
+NOSE0=nosetests -vs --with-doctest --doctest-tests --detailed-errors
+NOSE=nosetests -vvs --with-ipdoctest --doctest-tests --doctest-extension=txt \
+--detailed-errors
+
+SRC=ipdoctest.py setup.py ../decorators.py
+
+# Default target for clean 'make'
+default: interactiveshell
+
+# The actual plugin installation
+plugin: IPython_doctest_plugin.egg-info
+
+# Simple targets that test one thing
+simple: plugin simple.py
+ $(NOSE) simple.py
+
+dtest: plugin dtexample.py
+ $(NOSE) dtexample.py
+
+rtest: plugin test_refs.py
+ $(NOSE) test_refs.py
+
+test: plugin dtexample.py
+ $(NOSE) dtexample.py test*.py test*.txt
+
+deb: plugin dtexample.py
+ $(NOSE) test_combo.txt
+
+# IPython tests
+deco:
+ $(NOSE0) IPython.testing.decorators
+
+magic: plugin
+ $(NOSE) IPython.core.magic
+
+excolors: plugin
+ $(NOSE) IPython.core.excolors
+
+interactiveshell: plugin
+ $(NOSE) IPython.core.interactiveshell
+
+strd: plugin
+ $(NOSE) IPython.core.strdispatch
+
+engine: plugin
+ $(NOSE) IPython.kernel
+
+tf: plugin
+ $(NOSE) IPython.config.traitlets
+
+# All of ipython itself
+ipython: plugin
+ $(NOSE) IPython
+
+
+# Combined targets
+sr: rtest strd
+
+base: dtest rtest test strd deco
+
+quick: base interactiveshell ipipe
+
+all: base ipython
+
+# Main plugin and cleanup
+IPython_doctest_plugin.egg-info: $(SRC)
+ python setup.py install --prefix=$(PREFIX)
+ touch $@
+
+clean:
+ rm -rf IPython_doctest_plugin.egg-info *~ *pyc build/ dist/
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/README.txt b/contrib/python/ipython/py2/IPython/testing/plugin/README.txt
index e08380d9de..6b34f9e5e1 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/README.txt
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/README.txt
@@ -1,39 +1,39 @@
-=======================================================
- Nose plugin with IPython and extension module support
-=======================================================
-
-This directory provides the key functionality for test support that IPython
-needs as a nose plugin, which can be installed for use in projects other than
-IPython.
-
-The presence of a Makefile here is mostly for development and debugging
-purposes as it only provides a few shorthand commands. You can manually
-install the plugin by using standard Python procedures (``setup.py install``
-with appropriate arguments).
-
-To install the plugin using the Makefile, edit its first line to reflect where
-you'd like the installation. If you want it system-wide, you may want to edit
-the install line in the plugin target to use sudo and no prefix::
-
- sudo python setup.py install
-
-instead of the code using `--prefix` that's in there.
-
-Once you've set the prefix, simply build/install the plugin with::
-
- make
-
-and run the tests with::
-
- make test
-
-You should see output similar to::
-
- maqroll[plugin]> make test
- nosetests -s --with-ipdoctest --doctest-tests dtexample.py
- ..
- ----------------------------------------------------------------------
- Ran 2 tests in 0.016s
-
- OK
-
+=======================================================
+ Nose plugin with IPython and extension module support
+=======================================================
+
+This directory provides the key functionality for test support that IPython
+needs as a nose plugin, which can be installed for use in projects other than
+IPython.
+
+The presence of a Makefile here is mostly for development and debugging
+purposes as it only provides a few shorthand commands. You can manually
+install the plugin by using standard Python procedures (``setup.py install``
+with appropriate arguments).
+
+To install the plugin using the Makefile, edit its first line to reflect where
+you'd like the installation. If you want it system-wide, you may want to edit
+the install line in the plugin target to use sudo and no prefix::
+
+ sudo python setup.py install
+
+instead of the code using `--prefix` that's in there.
+
+Once you've set the prefix, simply build/install the plugin with::
+
+ make
+
+and run the tests with::
+
+ make test
+
+You should see output similar to::
+
+ maqroll[plugin]> make test
+ nosetests -s --with-ipdoctest --doctest-tests dtexample.py
+ ..
+ ----------------------------------------------------------------------
+ Ran 2 tests in 0.016s
+
+ OK
+
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/dtexample.py b/contrib/python/ipython/py2/IPython/testing/plugin/dtexample.py
index 081bf35571..5e02629bf7 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/dtexample.py
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/dtexample.py
@@ -1,158 +1,158 @@
-"""Simple example using doctests.
-
-This file just contains doctests both using plain python and IPython prompts.
-All tests should be loaded by nose.
-"""
-from __future__ import print_function
-
-def pyfunc():
- """Some pure python tests...
-
- >>> pyfunc()
- 'pyfunc'
-
- >>> import os
-
- >>> 2+3
- 5
-
- >>> for i in range(3):
- ... print(i, end=' ')
- ... print(i+1, end=' ')
- ...
- 0 1 1 2 2 3
- """
- return 'pyfunc'
-
-def ipfunc():
- """Some ipython tests...
-
- In [1]: import os
-
- In [3]: 2+3
- Out[3]: 5
-
- In [26]: for i in range(3):
- ....: print(i, end=' ')
- ....: print(i+1, end=' ')
- ....:
- 0 1 1 2 2 3
-
-
- Examples that access the operating system work:
-
- In [1]: !echo hello
- hello
-
- In [2]: !echo hello > /tmp/foo_iptest
-
- In [3]: !cat /tmp/foo_iptest
- hello
-
- In [4]: rm -f /tmp/foo_iptest
-
- It's OK to use '_' for the last result, but do NOT try to use IPython's
- numbered history of _NN outputs, since those won't exist under the
- doctest environment:
-
- In [7]: 'hi'
- Out[7]: 'hi'
-
- In [8]: print(repr(_))
- 'hi'
-
- In [7]: 3+4
- Out[7]: 7
-
- In [8]: _+3
- Out[8]: 10
-
- In [9]: ipfunc()
- Out[9]: 'ipfunc'
- """
- return 'ipfunc'
-
-
-def ranfunc():
- """A function with some random output.
-
- Normal examples are verified as usual:
- >>> 1+3
- 4
-
- But if you put '# random' in the output, it is ignored:
- >>> 1+3
- junk goes here... # random
-
- >>> 1+2
- again, anything goes #random
- if multiline, the random mark is only needed once.
-
- >>> 1+2
- You can also put the random marker at the end:
- # random
-
- >>> 1+2
- # random
- .. or at the beginning.
-
- More correct input is properly verified:
- >>> ranfunc()
- 'ranfunc'
- """
- return 'ranfunc'
-
-
-def random_all():
- """A function where we ignore the output of ALL examples.
-
- Examples:
-
- # all-random
-
- This mark tells the testing machinery that all subsequent examples should
- be treated as random (ignoring their output). They are still executed,
- so if a they raise an error, it will be detected as such, but their
- output is completely ignored.
-
- >>> 1+3
- junk goes here...
-
- >>> 1+3
- klasdfj;
-
- >>> 1+2
- again, anything goes
- blah...
- """
- pass
-
-def iprand():
- """Some ipython tests with random output.
-
- In [7]: 3+4
- Out[7]: 7
-
- In [8]: print('hello')
- world # random
-
- In [9]: iprand()
- Out[9]: 'iprand'
- """
- return 'iprand'
-
-def iprand_all():
- """Some ipython tests with fully random output.
-
- # all-random
-
- In [7]: 1
- Out[7]: 99
-
- In [8]: print('hello')
- world
-
- In [9]: iprand_all()
- Out[9]: 'junk'
- """
- return 'iprand_all'
+"""Simple example using doctests.
+
+This file just contains doctests both using plain python and IPython prompts.
+All tests should be loaded by nose.
+"""
+from __future__ import print_function
+
+def pyfunc():
+ """Some pure python tests...
+
+ >>> pyfunc()
+ 'pyfunc'
+
+ >>> import os
+
+ >>> 2+3
+ 5
+
+ >>> for i in range(3):
+ ... print(i, end=' ')
+ ... print(i+1, end=' ')
+ ...
+ 0 1 1 2 2 3
+ """
+ return 'pyfunc'
+
+def ipfunc():
+ """Some ipython tests...
+
+ In [1]: import os
+
+ In [3]: 2+3
+ Out[3]: 5
+
+ In [26]: for i in range(3):
+ ....: print(i, end=' ')
+ ....: print(i+1, end=' ')
+ ....:
+ 0 1 1 2 2 3
+
+
+ Examples that access the operating system work:
+
+ In [1]: !echo hello
+ hello
+
+ In [2]: !echo hello > /tmp/foo_iptest
+
+ In [3]: !cat /tmp/foo_iptest
+ hello
+
+ In [4]: rm -f /tmp/foo_iptest
+
+ It's OK to use '_' for the last result, but do NOT try to use IPython's
+ numbered history of _NN outputs, since those won't exist under the
+ doctest environment:
+
+ In [7]: 'hi'
+ Out[7]: 'hi'
+
+ In [8]: print(repr(_))
+ 'hi'
+
+ In [7]: 3+4
+ Out[7]: 7
+
+ In [8]: _+3
+ Out[8]: 10
+
+ In [9]: ipfunc()
+ Out[9]: 'ipfunc'
+ """
+ return 'ipfunc'
+
+
+def ranfunc():
+ """A function with some random output.
+
+ Normal examples are verified as usual:
+ >>> 1+3
+ 4
+
+ But if you put '# random' in the output, it is ignored:
+ >>> 1+3
+ junk goes here... # random
+
+ >>> 1+2
+ again, anything goes #random
+ if multiline, the random mark is only needed once.
+
+ >>> 1+2
+ You can also put the random marker at the end:
+ # random
+
+ >>> 1+2
+ # random
+ .. or at the beginning.
+
+ More correct input is properly verified:
+ >>> ranfunc()
+ 'ranfunc'
+ """
+ return 'ranfunc'
+
+
+def random_all():
+ """A function where we ignore the output of ALL examples.
+
+ Examples:
+
+ # all-random
+
+ This mark tells the testing machinery that all subsequent examples should
+ be treated as random (ignoring their output). They are still executed,
+ so if a they raise an error, it will be detected as such, but their
+ output is completely ignored.
+
+ >>> 1+3
+ junk goes here...
+
+ >>> 1+3
+ klasdfj;
+
+ >>> 1+2
+ again, anything goes
+ blah...
+ """
+ pass
+
+def iprand():
+ """Some ipython tests with random output.
+
+ In [7]: 3+4
+ Out[7]: 7
+
+ In [8]: print('hello')
+ world # random
+
+ In [9]: iprand()
+ Out[9]: 'iprand'
+ """
+ return 'iprand'
+
+def iprand_all():
+ """Some ipython tests with fully random output.
+
+ # all-random
+
+ In [7]: 1
+ Out[7]: 99
+
+ In [8]: print('hello')
+ world
+
+ In [9]: iprand_all()
+ Out[9]: 'junk'
+ """
+ return 'iprand_all'
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py b/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py
index 64e7e536f8..bc750e0efd 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py
@@ -1,769 +1,769 @@
-"""Nose Plugin that supports IPython doctests.
-
-Limitations:
-
-- When generating examples for use as doctests, make sure that you have
- pretty-printing OFF. This can be done either by setting the
- ``PlainTextFormatter.pprint`` option in your configuration file to False, or
- by interactively disabling it with %Pprint. This is required so that IPython
- output matches that of normal Python, which is used by doctest for internal
- execution.
-
-- Do not rely on specific prompt numbers for results (such as using
- '_34==True', for example). For IPython tests run via an external process the
- prompt numbers may be different, and IPython tests run as normal python code
- won't even have these special _NN variables set at all.
-"""
-
-#-----------------------------------------------------------------------------
-# Module imports
-
-# From the standard library
-import doctest
-import inspect
-import logging
-import os
-import re
-import sys
-
+"""Nose Plugin that supports IPython doctests.
+
+Limitations:
+
+- When generating examples for use as doctests, make sure that you have
+ pretty-printing OFF. This can be done either by setting the
+ ``PlainTextFormatter.pprint`` option in your configuration file to False, or
+ by interactively disabling it with %Pprint. This is required so that IPython
+ output matches that of normal Python, which is used by doctest for internal
+ execution.
+
+- Do not rely on specific prompt numbers for results (such as using
+ '_34==True', for example). For IPython tests run via an external process the
+ prompt numbers may be different, and IPython tests run as normal python code
+ won't even have these special _NN variables set at all.
+"""
+
+#-----------------------------------------------------------------------------
+# Module imports
+
+# From the standard library
+import doctest
+import inspect
+import logging
+import os
+import re
+import sys
+
from testpath import modified_env
-from inspect import getmodule
-
-# We are overriding the default doctest runner, so we need to import a few
-# things from doctest directly
-from doctest import (REPORTING_FLAGS, REPORT_ONLY_FIRST_FAILURE,
- _unittest_reportflags, DocTestRunner,
- _extract_future_flags, pdb, _OutputRedirectingPdb,
- _exception_traceback,
- linecache)
-
-# Third-party modules
-
-from nose.plugins import doctests, Plugin
+from inspect import getmodule
+
+# We are overriding the default doctest runner, so we need to import a few
+# things from doctest directly
+from doctest import (REPORTING_FLAGS, REPORT_ONLY_FIRST_FAILURE,
+ _unittest_reportflags, DocTestRunner,
+ _extract_future_flags, pdb, _OutputRedirectingPdb,
+ _exception_traceback,
+ linecache)
+
+# Third-party modules
+
+from nose.plugins import doctests, Plugin
from nose.util import anyp, tolist
-
-# Our own imports
-from IPython.utils.py3compat import builtin_mod, PY3, getcwd
-
-if PY3:
- from io import StringIO
-else:
- from StringIO import StringIO
-
-#-----------------------------------------------------------------------------
-# Module globals and other constants
-#-----------------------------------------------------------------------------
-
-log = logging.getLogger(__name__)
-
-
-#-----------------------------------------------------------------------------
-# Classes and functions
-#-----------------------------------------------------------------------------
-
-def is_extension_module(filename):
- """Return whether the given filename is an extension module.
-
- This simply checks that the extension is either .so or .pyd.
- """
- return os.path.splitext(filename)[1].lower() in ('.so','.pyd')
-
-
-class DocTestSkip(object):
- """Object wrapper for doctests to be skipped."""
-
- ds_skip = """Doctest to skip.
- >>> 1 #doctest: +SKIP
- """
-
- def __init__(self,obj):
- self.obj = obj
-
- def __getattribute__(self,key):
- if key == '__doc__':
- return DocTestSkip.ds_skip
- else:
- return getattr(object.__getattribute__(self,'obj'),key)
-
-# Modified version of the one in the stdlib, that fixes a python bug (doctests
-# not found in extension modules, http://bugs.python.org/issue3158)
-class DocTestFinder(doctest.DocTestFinder):
-
- def _from_module(self, module, object):
- """
- Return true if the given object is defined in the given
- module.
- """
- if module is None:
- return True
- elif inspect.isfunction(object):
- return module.__dict__ is object.__globals__
- elif inspect.isbuiltin(object):
- return module.__name__ == object.__module__
- elif inspect.isclass(object):
- return module.__name__ == object.__module__
- elif inspect.ismethod(object):
- # This one may be a bug in cython that fails to correctly set the
- # __module__ attribute of methods, but since the same error is easy
- # to make by extension code writers, having this safety in place
- # isn't such a bad idea
- return module.__name__ == object.__self__.__class__.__module__
- elif inspect.getmodule(object) is not None:
- return module is inspect.getmodule(object)
- elif hasattr(object, '__module__'):
- return module.__name__ == object.__module__
- elif isinstance(object, property):
- return True # [XX] no way not be sure.
- elif inspect.ismethoddescriptor(object):
- # Unbound PyQt signals reach this point in Python 3.4b3, and we want
- # to avoid throwing an error. See also http://bugs.python.org/issue3158
- return False
- else:
- raise ValueError("object must be a class or function, got %r" % object)
-
- def _find(self, tests, obj, name, module, source_lines, globs, seen):
- """
- Find tests for the given object and any contained objects, and
- add them to `tests`.
- """
- print('_find for:', obj, name, module) # dbg
- if hasattr(obj,"skip_doctest"):
- #print 'SKIPPING DOCTEST FOR:',obj # dbg
- obj = DocTestSkip(obj)
-
- doctest.DocTestFinder._find(self,tests, obj, name, module,
- source_lines, globs, seen)
-
- # Below we re-run pieces of the above method with manual modifications,
- # because the original code is buggy and fails to correctly identify
- # doctests in extension modules.
-
- # Local shorthands
+
+# Our own imports
+from IPython.utils.py3compat import builtin_mod, PY3, getcwd
+
+if PY3:
+ from io import StringIO
+else:
+ from StringIO import StringIO
+
+#-----------------------------------------------------------------------------
+# Module globals and other constants
+#-----------------------------------------------------------------------------
+
+log = logging.getLogger(__name__)
+
+
+#-----------------------------------------------------------------------------
+# Classes and functions
+#-----------------------------------------------------------------------------
+
+def is_extension_module(filename):
+ """Return whether the given filename is an extension module.
+
+ This simply checks that the extension is either .so or .pyd.
+ """
+ return os.path.splitext(filename)[1].lower() in ('.so','.pyd')
+
+
+class DocTestSkip(object):
+ """Object wrapper for doctests to be skipped."""
+
+ ds_skip = """Doctest to skip.
+ >>> 1 #doctest: +SKIP
+ """
+
+ def __init__(self,obj):
+ self.obj = obj
+
+ def __getattribute__(self,key):
+ if key == '__doc__':
+ return DocTestSkip.ds_skip
+ else:
+ return getattr(object.__getattribute__(self,'obj'),key)
+
+# Modified version of the one in the stdlib, that fixes a python bug (doctests
+# not found in extension modules, http://bugs.python.org/issue3158)
+class DocTestFinder(doctest.DocTestFinder):
+
+ def _from_module(self, module, object):
+ """
+ Return true if the given object is defined in the given
+ module.
+ """
+ if module is None:
+ return True
+ elif inspect.isfunction(object):
+ return module.__dict__ is object.__globals__
+ elif inspect.isbuiltin(object):
+ return module.__name__ == object.__module__
+ elif inspect.isclass(object):
+ return module.__name__ == object.__module__
+ elif inspect.ismethod(object):
+ # This one may be a bug in cython that fails to correctly set the
+ # __module__ attribute of methods, but since the same error is easy
+ # to make by extension code writers, having this safety in place
+ # isn't such a bad idea
+ return module.__name__ == object.__self__.__class__.__module__
+ elif inspect.getmodule(object) is not None:
+ return module is inspect.getmodule(object)
+ elif hasattr(object, '__module__'):
+ return module.__name__ == object.__module__
+ elif isinstance(object, property):
+ return True # [XX] no way not be sure.
+ elif inspect.ismethoddescriptor(object):
+ # Unbound PyQt signals reach this point in Python 3.4b3, and we want
+ # to avoid throwing an error. See also http://bugs.python.org/issue3158
+ return False
+ else:
+ raise ValueError("object must be a class or function, got %r" % object)
+
+ def _find(self, tests, obj, name, module, source_lines, globs, seen):
+ """
+ Find tests for the given object and any contained objects, and
+ add them to `tests`.
+ """
+ print('_find for:', obj, name, module) # dbg
+ if hasattr(obj,"skip_doctest"):
+ #print 'SKIPPING DOCTEST FOR:',obj # dbg
+ obj = DocTestSkip(obj)
+
+ doctest.DocTestFinder._find(self,tests, obj, name, module,
+ source_lines, globs, seen)
+
+ # Below we re-run pieces of the above method with manual modifications,
+ # because the original code is buggy and fails to correctly identify
+ # doctests in extension modules.
+
+ # Local shorthands
from inspect import isroutine, isclass
-
- # Look for tests in a module's contained objects.
- if inspect.ismodule(obj) and self._recurse:
- for valname, val in obj.__dict__.items():
- valname1 = '%s.%s' % (name, valname)
- if ( (isroutine(val) or isclass(val))
- and self._from_module(module, val) ):
-
- self._find(tests, val, valname1, module, source_lines,
- globs, seen)
-
- # Look for tests in a class's contained objects.
- if inspect.isclass(obj) and self._recurse:
- #print 'RECURSE into class:',obj # dbg
- for valname, val in obj.__dict__.items():
- # Special handling for staticmethod/classmethod.
- if isinstance(val, staticmethod):
- val = getattr(obj, valname)
- if isinstance(val, classmethod):
- val = getattr(obj, valname).__func__
-
- # Recurse to methods, properties, and nested classes.
- if ((inspect.isfunction(val) or inspect.isclass(val) or
- inspect.ismethod(val) or
- isinstance(val, property)) and
- self._from_module(module, val)):
- valname = '%s.%s' % (name, valname)
- self._find(tests, val, valname, module, source_lines,
- globs, seen)
-
-
-class IPDoctestOutputChecker(doctest.OutputChecker):
- """Second-chance checker with support for random tests.
-
- If the default comparison doesn't pass, this checker looks in the expected
- output string for flags that tell us to ignore the output.
- """
-
- random_re = re.compile(r'#\s*random\s+')
-
- def check_output(self, want, got, optionflags):
- """Check output, accepting special markers embedded in the output.
-
- If the output didn't pass the default validation but the special string
- '#random' is included, we accept it."""
-
- # Let the original tester verify first, in case people have valid tests
- # that happen to have a comment saying '#random' embedded in.
- ret = doctest.OutputChecker.check_output(self, want, got,
- optionflags)
- if not ret and self.random_re.search(want):
- #print >> sys.stderr, 'RANDOM OK:',want # dbg
- return True
-
- return ret
-
-
-class DocTestCase(doctests.DocTestCase):
- """Proxy for DocTestCase: provides an address() method that
- returns the correct address for the doctest case. Otherwise
- acts as a proxy to the test case. To provide hints for address(),
- an obj may also be passed -- this will be used as the test object
- for purposes of determining the test address, if it is provided.
- """
-
- # Note: this method was taken from numpy's nosetester module.
-
- # Subclass nose.plugins.doctests.DocTestCase to work around a bug in
- # its constructor that blocks non-default arguments from being passed
- # down into doctest.DocTestCase
-
- def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
- checker=None, obj=None, result_var='_'):
- self._result_var = result_var
- doctests.DocTestCase.__init__(self, test,
- optionflags=optionflags,
- setUp=setUp, tearDown=tearDown,
- checker=checker)
- # Now we must actually copy the original constructor from the stdlib
- # doctest class, because we can't call it directly and a bug in nose
- # means it never gets passed the right arguments.
-
- self._dt_optionflags = optionflags
- self._dt_checker = checker
- self._dt_test = test
- self._dt_test_globs_ori = test.globs
- self._dt_setUp = setUp
- self._dt_tearDown = tearDown
-
- # XXX - store this runner once in the object!
- runner = IPDocTestRunner(optionflags=optionflags,
- checker=checker, verbose=False)
- self._dt_runner = runner
-
-
- # Each doctest should remember the directory it was loaded from, so
- # things like %run work without too many contortions
- self._ori_dir = os.path.dirname(test.filename)
-
- # Modified runTest from the default stdlib
- def runTest(self):
- test = self._dt_test
- runner = self._dt_runner
-
- old = sys.stdout
- new = StringIO()
- optionflags = self._dt_optionflags
-
- if not (optionflags & REPORTING_FLAGS):
- # The option flags don't include any reporting flags,
- # so add the default reporting flags
- optionflags |= _unittest_reportflags
-
- try:
- # Save our current directory and switch out to the one where the
- # test was originally created, in case another doctest did a
- # directory change. We'll restore this in the finally clause.
- curdir = getcwd()
- #print 'runTest in dir:', self._ori_dir # dbg
- os.chdir(self._ori_dir)
-
- runner.DIVIDER = "-"*70
- failures, tries = runner.run(test,out=new.write,
- clear_globs=False)
- finally:
- sys.stdout = old
- os.chdir(curdir)
-
- if failures:
- raise self.failureException(self.format_failure(new.getvalue()))
-
- def setUp(self):
- """Modified test setup that syncs with ipython namespace"""
- #print "setUp test", self._dt_test.examples # dbg
- if isinstance(self._dt_test.examples[0], IPExample):
- # for IPython examples *only*, we swap the globals with the ipython
- # namespace, after updating it with the globals (which doctest
- # fills with the necessary info from the module being tested).
- self.user_ns_orig = {}
- self.user_ns_orig.update(_ip.user_ns)
- _ip.user_ns.update(self._dt_test.globs)
- # We must remove the _ key in the namespace, so that Python's
- # doctest code sets it naturally
- _ip.user_ns.pop('_', None)
- _ip.user_ns['__builtins__'] = builtin_mod
- self._dt_test.globs = _ip.user_ns
-
- super(DocTestCase, self).setUp()
-
- def tearDown(self):
-
- # Undo the test.globs reassignment we made, so that the parent class
- # teardown doesn't destroy the ipython namespace
- if isinstance(self._dt_test.examples[0], IPExample):
- self._dt_test.globs = self._dt_test_globs_ori
- _ip.user_ns.clear()
- _ip.user_ns.update(self.user_ns_orig)
-
- # XXX - fperez: I am not sure if this is truly a bug in nose 0.11, but
- # it does look like one to me: its tearDown method tries to run
- #
- # delattr(builtin_mod, self._result_var)
- #
- # without checking that the attribute really is there; it implicitly
- # assumes it should have been set via displayhook. But if the
- # displayhook was never called, this doesn't necessarily happen. I
- # haven't been able to find a little self-contained example outside of
- # ipython that would show the problem so I can report it to the nose
- # team, but it does happen a lot in our code.
- #
- # So here, we just protect as narrowly as possible by trapping an
- # attribute error whose message would be the name of self._result_var,
- # and letting any other error propagate.
- try:
- super(DocTestCase, self).tearDown()
- except AttributeError as exc:
- if exc.args[0] != self._result_var:
- raise
-
-
-# A simple subclassing of the original with a different class name, so we can
-# distinguish and treat differently IPython examples from pure python ones.
-class IPExample(doctest.Example): pass
-
-
-class IPExternalExample(doctest.Example):
- """Doctest examples to be run in an external process."""
-
- def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
- options=None):
- # Parent constructor
- doctest.Example.__init__(self,source,want,exc_msg,lineno,indent,options)
-
- # An EXTRA newline is needed to prevent pexpect hangs
- self.source += '\n'
-
-
-class IPDocTestParser(doctest.DocTestParser):
- """
- A class used to parse strings containing doctest examples.
-
- Note: This is a version modified to properly recognize IPython input and
- convert any IPython examples into valid Python ones.
- """
- # This regular expression is used to find doctest examples in a
- # string. It defines three groups: `source` is the source code
- # (including leading indentation and prompts); `indent` is the
- # indentation of the first (PS1) line of the source code; and
- # `want` is the expected output (including leading indentation).
-
- # Classic Python prompts or default IPython ones
- _PS1_PY = r'>>>'
- _PS2_PY = r'\.\.\.'
-
- _PS1_IP = r'In\ \[\d+\]:'
- _PS2_IP = r'\ \ \ \.\.\.+:'
-
- _RE_TPL = r'''
- # Source consists of a PS1 line followed by zero or more PS2 lines.
- (?P<source>
- (?:^(?P<indent> [ ]*) (?P<ps1> %s) .*) # PS1 line
- (?:\n [ ]* (?P<ps2> %s) .*)*) # PS2 lines
- \n? # a newline
- # Want consists of any non-blank lines that do not start with PS1.
- (?P<want> (?:(?![ ]*$) # Not a blank line
- (?![ ]*%s) # Not a line starting with PS1
- (?![ ]*%s) # Not a line starting with PS2
- .*$\n? # But any other line
- )*)
- '''
-
- _EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY),
- re.MULTILINE | re.VERBOSE)
-
- _EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP),
- re.MULTILINE | re.VERBOSE)
-
- # Mark a test as being fully random. In this case, we simply append the
- # random marker ('#random') to each individual example's output. This way
- # we don't need to modify any other code.
- _RANDOM_TEST = re.compile(r'#\s*all-random\s+')
-
- # Mark tests to be executed in an external process - currently unsupported.
- _EXTERNAL_IP = re.compile(r'#\s*ipdoctest:\s*EXTERNAL')
-
- def ip2py(self,source):
- """Convert input IPython source into valid Python."""
- block = _ip.input_transformer_manager.transform_cell(source)
- if len(block.splitlines()) == 1:
- return _ip.prefilter(block)
- else:
- return block
-
- def parse(self, string, name='<string>'):
- """
- Divide the given string into examples and intervening text,
- and return them as a list of alternating Examples and strings.
- Line numbers for the Examples are 0-based. The optional
- argument `name` is a name identifying this string, and is only
- used for error messages.
- """
-
- #print 'Parse string:\n',string # dbg
-
- string = string.expandtabs()
- # If all lines begin with the same indentation, then strip it.
- min_indent = self._min_indent(string)
- if min_indent > 0:
- string = '\n'.join([l[min_indent:] for l in string.split('\n')])
-
- output = []
- charno, lineno = 0, 0
-
- # We make 'all random' tests by adding the '# random' mark to every
- # block of output in the test.
- if self._RANDOM_TEST.search(string):
- random_marker = '\n# random'
- else:
- random_marker = ''
-
- # Whether to convert the input from ipython to python syntax
- ip2py = False
- # Find all doctest examples in the string. First, try them as Python
- # examples, then as IPython ones
- terms = list(self._EXAMPLE_RE_PY.finditer(string))
- if terms:
- # Normal Python example
- #print '-'*70 # dbg
- #print 'PyExample, Source:\n',string # dbg
- #print '-'*70 # dbg
- Example = doctest.Example
- else:
- # It's an ipython example. Note that IPExamples are run
- # in-process, so their syntax must be turned into valid python.
- # IPExternalExamples are run out-of-process (via pexpect) so they
- # don't need any filtering (a real ipython will be executing them).
- terms = list(self._EXAMPLE_RE_IP.finditer(string))
- if self._EXTERNAL_IP.search(string):
- #print '-'*70 # dbg
- #print 'IPExternalExample, Source:\n',string # dbg
- #print '-'*70 # dbg
- Example = IPExternalExample
- else:
- #print '-'*70 # dbg
- #print 'IPExample, Source:\n',string # dbg
- #print '-'*70 # dbg
- Example = IPExample
- ip2py = True
-
- for m in terms:
- # Add the pre-example text to `output`.
- output.append(string[charno:m.start()])
- # Update lineno (lines before this example)
- lineno += string.count('\n', charno, m.start())
- # Extract info from the regexp match.
- (source, options, want, exc_msg) = \
- self._parse_example(m, name, lineno,ip2py)
-
- # Append the random-output marker (it defaults to empty in most
- # cases, it's only non-empty for 'all-random' tests):
- want += random_marker
-
- if Example is IPExternalExample:
- options[doctest.NORMALIZE_WHITESPACE] = True
- want += '\n'
-
- # Create an Example, and add it to the list.
- if not self._IS_BLANK_OR_COMMENT(source):
- output.append(Example(source, want, exc_msg,
- lineno=lineno,
- indent=min_indent+len(m.group('indent')),
- options=options))
- # Update lineno (lines inside this example)
- lineno += string.count('\n', m.start(), m.end())
- # Update charno.
- charno = m.end()
- # Add any remaining post-example text to `output`.
- output.append(string[charno:])
- return output
-
- def _parse_example(self, m, name, lineno,ip2py=False):
- """
- Given a regular expression match from `_EXAMPLE_RE` (`m`),
- return a pair `(source, want)`, where `source` is the matched
- example's source code (with prompts and indentation stripped);
- and `want` is the example's expected output (with indentation
- stripped).
-
- `name` is the string's name, and `lineno` is the line number
- where the example starts; both are used for error messages.
-
- Optional:
- `ip2py`: if true, filter the input via IPython to convert the syntax
- into valid python.
- """
-
- # Get the example's indentation level.
- indent = len(m.group('indent'))
-
- # Divide source into lines; check that they're properly
- # indented; and then strip their indentation & prompts.
- source_lines = m.group('source').split('\n')
-
- # We're using variable-length input prompts
- ps1 = m.group('ps1')
- ps2 = m.group('ps2')
- ps1_len = len(ps1)
-
- self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len)
- if ps2:
- self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno)
-
- source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines])
-
- if ip2py:
- # Convert source input from IPython into valid Python syntax
- source = self.ip2py(source)
-
- # Divide want into lines; check that it's properly indented; and
- # then strip the indentation. Spaces before the last newline should
- # be preserved, so plain rstrip() isn't good enough.
- want = m.group('want')
- want_lines = want.split('\n')
- if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
- del want_lines[-1] # forget final newline & spaces after it
- self._check_prefix(want_lines, ' '*indent, name,
- lineno + len(source_lines))
-
- # Remove ipython output prompt that might be present in the first line
- want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0])
-
- want = '\n'.join([wl[indent:] for wl in want_lines])
-
- # If `want` contains a traceback message, then extract it.
- m = self._EXCEPTION_RE.match(want)
- if m:
- exc_msg = m.group('msg')
- else:
- exc_msg = None
-
- # Extract options from the source.
- options = self._find_options(source, name, lineno)
-
- return source, options, want, exc_msg
-
- def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len):
- """
- Given the lines of a source string (including prompts and
- leading indentation), check to make sure that every prompt is
- followed by a space character. If any line is not followed by
- a space character, then raise ValueError.
-
- Note: IPython-modified version which takes the input prompt length as a
- parameter, so that prompts of variable length can be dealt with.
- """
- space_idx = indent+ps1_len
- min_len = space_idx+1
- for i, line in enumerate(lines):
- if len(line) >= min_len and line[space_idx] != ' ':
- raise ValueError('line %r of the docstring for %s '
- 'lacks blank after %s: %r' %
- (lineno+i+1, name,
- line[indent:space_idx], line))
-
-
-SKIP = doctest.register_optionflag('SKIP')
-
-
-class IPDocTestRunner(doctest.DocTestRunner,object):
- """Test runner that synchronizes the IPython namespace with test globals.
- """
-
- def run(self, test, compileflags=None, out=None, clear_globs=True):
-
- # Hack: ipython needs access to the execution context of the example,
- # so that it can propagate user variables loaded by %run into
- # test.globs. We put them here into our modified %run as a function
- # attribute. Our new %run will then only make the namespace update
- # when called (rather than unconconditionally updating test.globs here
- # for all examples, most of which won't be calling %run anyway).
- #_ip._ipdoctest_test_globs = test.globs
- #_ip._ipdoctest_test_filename = test.filename
-
- test.globs.update(_ip.user_ns)
-
+
+ # Look for tests in a module's contained objects.
+ if inspect.ismodule(obj) and self._recurse:
+ for valname, val in obj.__dict__.items():
+ valname1 = '%s.%s' % (name, valname)
+ if ( (isroutine(val) or isclass(val))
+ and self._from_module(module, val) ):
+
+ self._find(tests, val, valname1, module, source_lines,
+ globs, seen)
+
+ # Look for tests in a class's contained objects.
+ if inspect.isclass(obj) and self._recurse:
+ #print 'RECURSE into class:',obj # dbg
+ for valname, val in obj.__dict__.items():
+ # Special handling for staticmethod/classmethod.
+ if isinstance(val, staticmethod):
+ val = getattr(obj, valname)
+ if isinstance(val, classmethod):
+ val = getattr(obj, valname).__func__
+
+ # Recurse to methods, properties, and nested classes.
+ if ((inspect.isfunction(val) or inspect.isclass(val) or
+ inspect.ismethod(val) or
+ isinstance(val, property)) and
+ self._from_module(module, val)):
+ valname = '%s.%s' % (name, valname)
+ self._find(tests, val, valname, module, source_lines,
+ globs, seen)
+
+
+class IPDoctestOutputChecker(doctest.OutputChecker):
+ """Second-chance checker with support for random tests.
+
+ If the default comparison doesn't pass, this checker looks in the expected
+ output string for flags that tell us to ignore the output.
+ """
+
+ random_re = re.compile(r'#\s*random\s+')
+
+ def check_output(self, want, got, optionflags):
+ """Check output, accepting special markers embedded in the output.
+
+ If the output didn't pass the default validation but the special string
+ '#random' is included, we accept it."""
+
+ # Let the original tester verify first, in case people have valid tests
+ # that happen to have a comment saying '#random' embedded in.
+ ret = doctest.OutputChecker.check_output(self, want, got,
+ optionflags)
+ if not ret and self.random_re.search(want):
+ #print >> sys.stderr, 'RANDOM OK:',want # dbg
+ return True
+
+ return ret
+
+
+class DocTestCase(doctests.DocTestCase):
+ """Proxy for DocTestCase: provides an address() method that
+ returns the correct address for the doctest case. Otherwise
+ acts as a proxy to the test case. To provide hints for address(),
+ an obj may also be passed -- this will be used as the test object
+ for purposes of determining the test address, if it is provided.
+ """
+
+ # Note: this method was taken from numpy's nosetester module.
+
+ # Subclass nose.plugins.doctests.DocTestCase to work around a bug in
+ # its constructor that blocks non-default arguments from being passed
+ # down into doctest.DocTestCase
+
+ def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
+ checker=None, obj=None, result_var='_'):
+ self._result_var = result_var
+ doctests.DocTestCase.__init__(self, test,
+ optionflags=optionflags,
+ setUp=setUp, tearDown=tearDown,
+ checker=checker)
+ # Now we must actually copy the original constructor from the stdlib
+ # doctest class, because we can't call it directly and a bug in nose
+ # means it never gets passed the right arguments.
+
+ self._dt_optionflags = optionflags
+ self._dt_checker = checker
+ self._dt_test = test
+ self._dt_test_globs_ori = test.globs
+ self._dt_setUp = setUp
+ self._dt_tearDown = tearDown
+
+ # XXX - store this runner once in the object!
+ runner = IPDocTestRunner(optionflags=optionflags,
+ checker=checker, verbose=False)
+ self._dt_runner = runner
+
+
+ # Each doctest should remember the directory it was loaded from, so
+ # things like %run work without too many contortions
+ self._ori_dir = os.path.dirname(test.filename)
+
+ # Modified runTest from the default stdlib
+ def runTest(self):
+ test = self._dt_test
+ runner = self._dt_runner
+
+ old = sys.stdout
+ new = StringIO()
+ optionflags = self._dt_optionflags
+
+ if not (optionflags & REPORTING_FLAGS):
+ # The option flags don't include any reporting flags,
+ # so add the default reporting flags
+ optionflags |= _unittest_reportflags
+
+ try:
+ # Save our current directory and switch out to the one where the
+ # test was originally created, in case another doctest did a
+ # directory change. We'll restore this in the finally clause.
+ curdir = getcwd()
+ #print 'runTest in dir:', self._ori_dir # dbg
+ os.chdir(self._ori_dir)
+
+ runner.DIVIDER = "-"*70
+ failures, tries = runner.run(test,out=new.write,
+ clear_globs=False)
+ finally:
+ sys.stdout = old
+ os.chdir(curdir)
+
+ if failures:
+ raise self.failureException(self.format_failure(new.getvalue()))
+
+ def setUp(self):
+ """Modified test setup that syncs with ipython namespace"""
+ #print "setUp test", self._dt_test.examples # dbg
+ if isinstance(self._dt_test.examples[0], IPExample):
+ # for IPython examples *only*, we swap the globals with the ipython
+ # namespace, after updating it with the globals (which doctest
+ # fills with the necessary info from the module being tested).
+ self.user_ns_orig = {}
+ self.user_ns_orig.update(_ip.user_ns)
+ _ip.user_ns.update(self._dt_test.globs)
+ # We must remove the _ key in the namespace, so that Python's
+ # doctest code sets it naturally
+ _ip.user_ns.pop('_', None)
+ _ip.user_ns['__builtins__'] = builtin_mod
+ self._dt_test.globs = _ip.user_ns
+
+ super(DocTestCase, self).setUp()
+
+ def tearDown(self):
+
+ # Undo the test.globs reassignment we made, so that the parent class
+ # teardown doesn't destroy the ipython namespace
+ if isinstance(self._dt_test.examples[0], IPExample):
+ self._dt_test.globs = self._dt_test_globs_ori
+ _ip.user_ns.clear()
+ _ip.user_ns.update(self.user_ns_orig)
+
+ # XXX - fperez: I am not sure if this is truly a bug in nose 0.11, but
+ # it does look like one to me: its tearDown method tries to run
+ #
+ # delattr(builtin_mod, self._result_var)
+ #
+ # without checking that the attribute really is there; it implicitly
+ # assumes it should have been set via displayhook. But if the
+ # displayhook was never called, this doesn't necessarily happen. I
+ # haven't been able to find a little self-contained example outside of
+ # ipython that would show the problem so I can report it to the nose
+ # team, but it does happen a lot in our code.
+ #
+ # So here, we just protect as narrowly as possible by trapping an
+ # attribute error whose message would be the name of self._result_var,
+ # and letting any other error propagate.
+ try:
+ super(DocTestCase, self).tearDown()
+ except AttributeError as exc:
+ if exc.args[0] != self._result_var:
+ raise
+
+
+# A simple subclassing of the original with a different class name, so we can
+# distinguish and treat differently IPython examples from pure python ones.
+class IPExample(doctest.Example): pass
+
+
+class IPExternalExample(doctest.Example):
+ """Doctest examples to be run in an external process."""
+
+ def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
+ options=None):
+ # Parent constructor
+ doctest.Example.__init__(self,source,want,exc_msg,lineno,indent,options)
+
+ # An EXTRA newline is needed to prevent pexpect hangs
+ self.source += '\n'
+
+
+class IPDocTestParser(doctest.DocTestParser):
+ """
+ A class used to parse strings containing doctest examples.
+
+ Note: This is a version modified to properly recognize IPython input and
+ convert any IPython examples into valid Python ones.
+ """
+ # This regular expression is used to find doctest examples in a
+ # string. It defines three groups: `source` is the source code
+ # (including leading indentation and prompts); `indent` is the
+ # indentation of the first (PS1) line of the source code; and
+ # `want` is the expected output (including leading indentation).
+
+ # Classic Python prompts or default IPython ones
+ _PS1_PY = r'>>>'
+ _PS2_PY = r'\.\.\.'
+
+ _PS1_IP = r'In\ \[\d+\]:'
+ _PS2_IP = r'\ \ \ \.\.\.+:'
+
+ _RE_TPL = r'''
+ # Source consists of a PS1 line followed by zero or more PS2 lines.
+ (?P<source>
+ (?:^(?P<indent> [ ]*) (?P<ps1> %s) .*) # PS1 line
+ (?:\n [ ]* (?P<ps2> %s) .*)*) # PS2 lines
+ \n? # a newline
+ # Want consists of any non-blank lines that do not start with PS1.
+ (?P<want> (?:(?![ ]*$) # Not a blank line
+ (?![ ]*%s) # Not a line starting with PS1
+ (?![ ]*%s) # Not a line starting with PS2
+ .*$\n? # But any other line
+ )*)
+ '''
+
+ _EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY),
+ re.MULTILINE | re.VERBOSE)
+
+ _EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP),
+ re.MULTILINE | re.VERBOSE)
+
+ # Mark a test as being fully random. In this case, we simply append the
+ # random marker ('#random') to each individual example's output. This way
+ # we don't need to modify any other code.
+ _RANDOM_TEST = re.compile(r'#\s*all-random\s+')
+
+ # Mark tests to be executed in an external process - currently unsupported.
+ _EXTERNAL_IP = re.compile(r'#\s*ipdoctest:\s*EXTERNAL')
+
+ def ip2py(self,source):
+ """Convert input IPython source into valid Python."""
+ block = _ip.input_transformer_manager.transform_cell(source)
+ if len(block.splitlines()) == 1:
+ return _ip.prefilter(block)
+ else:
+ return block
+
+ def parse(self, string, name='<string>'):
+ """
+ Divide the given string into examples and intervening text,
+ and return them as a list of alternating Examples and strings.
+ Line numbers for the Examples are 0-based. The optional
+ argument `name` is a name identifying this string, and is only
+ used for error messages.
+ """
+
+ #print 'Parse string:\n',string # dbg
+
+ string = string.expandtabs()
+ # If all lines begin with the same indentation, then strip it.
+ min_indent = self._min_indent(string)
+ if min_indent > 0:
+ string = '\n'.join([l[min_indent:] for l in string.split('\n')])
+
+ output = []
+ charno, lineno = 0, 0
+
+ # We make 'all random' tests by adding the '# random' mark to every
+ # block of output in the test.
+ if self._RANDOM_TEST.search(string):
+ random_marker = '\n# random'
+ else:
+ random_marker = ''
+
+ # Whether to convert the input from ipython to python syntax
+ ip2py = False
+ # Find all doctest examples in the string. First, try them as Python
+ # examples, then as IPython ones
+ terms = list(self._EXAMPLE_RE_PY.finditer(string))
+ if terms:
+ # Normal Python example
+ #print '-'*70 # dbg
+ #print 'PyExample, Source:\n',string # dbg
+ #print '-'*70 # dbg
+ Example = doctest.Example
+ else:
+ # It's an ipython example. Note that IPExamples are run
+ # in-process, so their syntax must be turned into valid python.
+ # IPExternalExamples are run out-of-process (via pexpect) so they
+ # don't need any filtering (a real ipython will be executing them).
+ terms = list(self._EXAMPLE_RE_IP.finditer(string))
+ if self._EXTERNAL_IP.search(string):
+ #print '-'*70 # dbg
+ #print 'IPExternalExample, Source:\n',string # dbg
+ #print '-'*70 # dbg
+ Example = IPExternalExample
+ else:
+ #print '-'*70 # dbg
+ #print 'IPExample, Source:\n',string # dbg
+ #print '-'*70 # dbg
+ Example = IPExample
+ ip2py = True
+
+ for m in terms:
+ # Add the pre-example text to `output`.
+ output.append(string[charno:m.start()])
+ # Update lineno (lines before this example)
+ lineno += string.count('\n', charno, m.start())
+ # Extract info from the regexp match.
+ (source, options, want, exc_msg) = \
+ self._parse_example(m, name, lineno,ip2py)
+
+ # Append the random-output marker (it defaults to empty in most
+ # cases, it's only non-empty for 'all-random' tests):
+ want += random_marker
+
+ if Example is IPExternalExample:
+ options[doctest.NORMALIZE_WHITESPACE] = True
+ want += '\n'
+
+ # Create an Example, and add it to the list.
+ if not self._IS_BLANK_OR_COMMENT(source):
+ output.append(Example(source, want, exc_msg,
+ lineno=lineno,
+ indent=min_indent+len(m.group('indent')),
+ options=options))
+ # Update lineno (lines inside this example)
+ lineno += string.count('\n', m.start(), m.end())
+ # Update charno.
+ charno = m.end()
+ # Add any remaining post-example text to `output`.
+ output.append(string[charno:])
+ return output
+
+ def _parse_example(self, m, name, lineno,ip2py=False):
+ """
+ Given a regular expression match from `_EXAMPLE_RE` (`m`),
+ return a pair `(source, want)`, where `source` is the matched
+ example's source code (with prompts and indentation stripped);
+ and `want` is the example's expected output (with indentation
+ stripped).
+
+ `name` is the string's name, and `lineno` is the line number
+ where the example starts; both are used for error messages.
+
+ Optional:
+ `ip2py`: if true, filter the input via IPython to convert the syntax
+ into valid python.
+ """
+
+ # Get the example's indentation level.
+ indent = len(m.group('indent'))
+
+ # Divide source into lines; check that they're properly
+ # indented; and then strip their indentation & prompts.
+ source_lines = m.group('source').split('\n')
+
+ # We're using variable-length input prompts
+ ps1 = m.group('ps1')
+ ps2 = m.group('ps2')
+ ps1_len = len(ps1)
+
+ self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len)
+ if ps2:
+ self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno)
+
+ source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines])
+
+ if ip2py:
+ # Convert source input from IPython into valid Python syntax
+ source = self.ip2py(source)
+
+ # Divide want into lines; check that it's properly indented; and
+ # then strip the indentation. Spaces before the last newline should
+ # be preserved, so plain rstrip() isn't good enough.
+ want = m.group('want')
+ want_lines = want.split('\n')
+ if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
+ del want_lines[-1] # forget final newline & spaces after it
+ self._check_prefix(want_lines, ' '*indent, name,
+ lineno + len(source_lines))
+
+ # Remove ipython output prompt that might be present in the first line
+ want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0])
+
+ want = '\n'.join([wl[indent:] for wl in want_lines])
+
+ # If `want` contains a traceback message, then extract it.
+ m = self._EXCEPTION_RE.match(want)
+ if m:
+ exc_msg = m.group('msg')
+ else:
+ exc_msg = None
+
+ # Extract options from the source.
+ options = self._find_options(source, name, lineno)
+
+ return source, options, want, exc_msg
+
+ def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len):
+ """
+ Given the lines of a source string (including prompts and
+ leading indentation), check to make sure that every prompt is
+ followed by a space character. If any line is not followed by
+ a space character, then raise ValueError.
+
+ Note: IPython-modified version which takes the input prompt length as a
+ parameter, so that prompts of variable length can be dealt with.
+ """
+ space_idx = indent+ps1_len
+ min_len = space_idx+1
+ for i, line in enumerate(lines):
+ if len(line) >= min_len and line[space_idx] != ' ':
+ raise ValueError('line %r of the docstring for %s '
+ 'lacks blank after %s: %r' %
+ (lineno+i+1, name,
+ line[indent:space_idx], line))
+
+
+SKIP = doctest.register_optionflag('SKIP')
+
+
+class IPDocTestRunner(doctest.DocTestRunner,object):
+ """Test runner that synchronizes the IPython namespace with test globals.
+ """
+
+ def run(self, test, compileflags=None, out=None, clear_globs=True):
+
+ # Hack: ipython needs access to the execution context of the example,
+ # so that it can propagate user variables loaded by %run into
+ # test.globs. We put them here into our modified %run as a function
+ # attribute. Our new %run will then only make the namespace update
+ # when called (rather than unconconditionally updating test.globs here
+ # for all examples, most of which won't be calling %run anyway).
+ #_ip._ipdoctest_test_globs = test.globs
+ #_ip._ipdoctest_test_filename = test.filename
+
+ test.globs.update(_ip.user_ns)
+
# Override terminal size to standardise traceback format
with modified_env({'COLUMNS': '80', 'LINES': '24'}):
return super(IPDocTestRunner,self).run(test,
compileflags,out,clear_globs)
-
-
-class DocFileCase(doctest.DocFileCase):
- """Overrides to provide filename
- """
- def address(self):
- return (self._dt_test.filename, None, None)
-
-
-class ExtensionDoctest(doctests.Doctest):
- """Nose Plugin that supports doctests in extension modules.
- """
- name = 'extdoctest' # call nosetests with --with-extdoctest
- enabled = True
-
- def options(self, parser, env=os.environ):
- Plugin.options(self, parser, env)
- parser.add_option('--doctest-tests', action='store_true',
- dest='doctest_tests',
- default=env.get('NOSE_DOCTEST_TESTS',True),
- help="Also look for doctests in test modules. "
- "Note that classes, methods and functions should "
- "have either doctests or non-doctest tests, "
- "not both. [NOSE_DOCTEST_TESTS]")
- parser.add_option('--doctest-extension', action="append",
- dest="doctestExtension",
- help="Also look for doctests in files with "
- "this extension [NOSE_DOCTEST_EXTENSION]")
- # Set the default as a list, if given in env; otherwise
- # an additional value set on the command line will cause
- # an error.
- env_setting = env.get('NOSE_DOCTEST_EXTENSION')
- if env_setting is not None:
- parser.set_defaults(doctestExtension=tolist(env_setting))
-
-
- def configure(self, options, config):
- Plugin.configure(self, options, config)
- # Pull standard doctest plugin out of config; we will do doctesting
- config.plugins.plugins = [p for p in config.plugins.plugins
- if p.name != 'doctest']
- self.doctest_tests = options.doctest_tests
- self.extension = tolist(options.doctestExtension)
-
- self.parser = doctest.DocTestParser()
- self.finder = DocTestFinder()
- self.checker = IPDoctestOutputChecker()
- self.globs = None
- self.extraglobs = None
-
-
- def loadTestsFromExtensionModule(self,filename):
- bpath,mod = os.path.split(filename)
- modname = os.path.splitext(mod)[0]
- try:
- sys.path.append(bpath)
- module = __import__(modname)
- tests = list(self.loadTestsFromModule(module))
- finally:
- sys.path.pop()
- return tests
-
- # NOTE: the method below is almost a copy of the original one in nose, with
- # a few modifications to control output checking.
-
- def loadTestsFromModule(self, module):
- #print '*** ipdoctest - lTM',module # dbg
-
- if not self.matches(module.__name__):
- log.debug("Doctest doesn't want module %s", module)
- return
-
- tests = self.finder.find(module,globs=self.globs,
- extraglobs=self.extraglobs)
- if not tests:
- return
-
- # always use whitespace and ellipsis options
- optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
-
- tests.sort()
- module_file = module.__file__
- if module_file[-4:] in ('.pyc', '.pyo'):
- module_file = module_file[:-1]
- for test in tests:
- if not test.examples:
- continue
- if not test.filename:
- test.filename = module_file
-
- yield DocTestCase(test,
- optionflags=optionflags,
- checker=self.checker)
-
-
- def loadTestsFromFile(self, filename):
- #print "ipdoctest - from file", filename # dbg
- if is_extension_module(filename):
- for t in self.loadTestsFromExtensionModule(filename):
- yield t
- else:
- if self.extension and anyp(filename.endswith, self.extension):
- name = os.path.basename(filename)
- dh = open(filename)
- try:
- doc = dh.read()
- finally:
- dh.close()
- test = self.parser.get_doctest(
- doc, globs={'__file__': filename}, name=name,
- filename=filename, lineno=0)
- if test.examples:
- #print 'FileCase:',test.examples # dbg
- yield DocFileCase(test)
- else:
- yield False # no tests to load
-
-
-class IPythonDoctest(ExtensionDoctest):
- """Nose Plugin that supports doctests in extension modules.
- """
- name = 'ipdoctest' # call nosetests with --with-ipdoctest
- enabled = True
-
- def makeTest(self, obj, parent):
- """Look for doctests in the given object, which will be a
- function, method or class.
- """
- #print 'Plugin analyzing:', obj, parent # dbg
- # always use whitespace and ellipsis options
- optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
-
- doctests = self.finder.find(obj, module=getmodule(parent))
- if doctests:
- for test in doctests:
- if len(test.examples) == 0:
- continue
-
- yield DocTestCase(test, obj=obj,
- optionflags=optionflags,
- checker=self.checker)
-
- def options(self, parser, env=os.environ):
- #print "Options for nose plugin:", self.name # dbg
- Plugin.options(self, parser, env)
- parser.add_option('--ipdoctest-tests', action='store_true',
- dest='ipdoctest_tests',
- default=env.get('NOSE_IPDOCTEST_TESTS',True),
- help="Also look for doctests in test modules. "
- "Note that classes, methods and functions should "
- "have either doctests or non-doctest tests, "
- "not both. [NOSE_IPDOCTEST_TESTS]")
- parser.add_option('--ipdoctest-extension', action="append",
- dest="ipdoctest_extension",
- help="Also look for doctests in files with "
- "this extension [NOSE_IPDOCTEST_EXTENSION]")
- # Set the default as a list, if given in env; otherwise
- # an additional value set on the command line will cause
- # an error.
- env_setting = env.get('NOSE_IPDOCTEST_EXTENSION')
- if env_setting is not None:
- parser.set_defaults(ipdoctest_extension=tolist(env_setting))
-
- def configure(self, options, config):
- #print "Configuring nose plugin:", self.name # dbg
- Plugin.configure(self, options, config)
- # Pull standard doctest plugin out of config; we will do doctesting
- config.plugins.plugins = [p for p in config.plugins.plugins
- if p.name != 'doctest']
- self.doctest_tests = options.ipdoctest_tests
- self.extension = tolist(options.ipdoctest_extension)
-
- self.parser = IPDocTestParser()
- self.finder = DocTestFinder(parser=self.parser)
- self.checker = IPDoctestOutputChecker()
- self.globs = None
- self.extraglobs = None
+
+
+class DocFileCase(doctest.DocFileCase):
+ """Overrides to provide filename
+ """
+ def address(self):
+ return (self._dt_test.filename, None, None)
+
+
+class ExtensionDoctest(doctests.Doctest):
+ """Nose Plugin that supports doctests in extension modules.
+ """
+ name = 'extdoctest' # call nosetests with --with-extdoctest
+ enabled = True
+
+ def options(self, parser, env=os.environ):
+ Plugin.options(self, parser, env)
+ parser.add_option('--doctest-tests', action='store_true',
+ dest='doctest_tests',
+ default=env.get('NOSE_DOCTEST_TESTS',True),
+ help="Also look for doctests in test modules. "
+ "Note that classes, methods and functions should "
+ "have either doctests or non-doctest tests, "
+ "not both. [NOSE_DOCTEST_TESTS]")
+ parser.add_option('--doctest-extension', action="append",
+ dest="doctestExtension",
+ help="Also look for doctests in files with "
+ "this extension [NOSE_DOCTEST_EXTENSION]")
+ # Set the default as a list, if given in env; otherwise
+ # an additional value set on the command line will cause
+ # an error.
+ env_setting = env.get('NOSE_DOCTEST_EXTENSION')
+ if env_setting is not None:
+ parser.set_defaults(doctestExtension=tolist(env_setting))
+
+
+ def configure(self, options, config):
+ Plugin.configure(self, options, config)
+ # Pull standard doctest plugin out of config; we will do doctesting
+ config.plugins.plugins = [p for p in config.plugins.plugins
+ if p.name != 'doctest']
+ self.doctest_tests = options.doctest_tests
+ self.extension = tolist(options.doctestExtension)
+
+ self.parser = doctest.DocTestParser()
+ self.finder = DocTestFinder()
+ self.checker = IPDoctestOutputChecker()
+ self.globs = None
+ self.extraglobs = None
+
+
+ def loadTestsFromExtensionModule(self,filename):
+ bpath,mod = os.path.split(filename)
+ modname = os.path.splitext(mod)[0]
+ try:
+ sys.path.append(bpath)
+ module = __import__(modname)
+ tests = list(self.loadTestsFromModule(module))
+ finally:
+ sys.path.pop()
+ return tests
+
+ # NOTE: the method below is almost a copy of the original one in nose, with
+ # a few modifications to control output checking.
+
+ def loadTestsFromModule(self, module):
+ #print '*** ipdoctest - lTM',module # dbg
+
+ if not self.matches(module.__name__):
+ log.debug("Doctest doesn't want module %s", module)
+ return
+
+ tests = self.finder.find(module,globs=self.globs,
+ extraglobs=self.extraglobs)
+ if not tests:
+ return
+
+ # always use whitespace and ellipsis options
+ optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
+
+ tests.sort()
+ module_file = module.__file__
+ if module_file[-4:] in ('.pyc', '.pyo'):
+ module_file = module_file[:-1]
+ for test in tests:
+ if not test.examples:
+ continue
+ if not test.filename:
+ test.filename = module_file
+
+ yield DocTestCase(test,
+ optionflags=optionflags,
+ checker=self.checker)
+
+
+ def loadTestsFromFile(self, filename):
+ #print "ipdoctest - from file", filename # dbg
+ if is_extension_module(filename):
+ for t in self.loadTestsFromExtensionModule(filename):
+ yield t
+ else:
+ if self.extension and anyp(filename.endswith, self.extension):
+ name = os.path.basename(filename)
+ dh = open(filename)
+ try:
+ doc = dh.read()
+ finally:
+ dh.close()
+ test = self.parser.get_doctest(
+ doc, globs={'__file__': filename}, name=name,
+ filename=filename, lineno=0)
+ if test.examples:
+ #print 'FileCase:',test.examples # dbg
+ yield DocFileCase(test)
+ else:
+ yield False # no tests to load
+
+
+class IPythonDoctest(ExtensionDoctest):
+ """Nose Plugin that supports doctests in extension modules.
+ """
+ name = 'ipdoctest' # call nosetests with --with-ipdoctest
+ enabled = True
+
+ def makeTest(self, obj, parent):
+ """Look for doctests in the given object, which will be a
+ function, method or class.
+ """
+ #print 'Plugin analyzing:', obj, parent # dbg
+ # always use whitespace and ellipsis options
+ optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
+
+ doctests = self.finder.find(obj, module=getmodule(parent))
+ if doctests:
+ for test in doctests:
+ if len(test.examples) == 0:
+ continue
+
+ yield DocTestCase(test, obj=obj,
+ optionflags=optionflags,
+ checker=self.checker)
+
+ def options(self, parser, env=os.environ):
+ #print "Options for nose plugin:", self.name # dbg
+ Plugin.options(self, parser, env)
+ parser.add_option('--ipdoctest-tests', action='store_true',
+ dest='ipdoctest_tests',
+ default=env.get('NOSE_IPDOCTEST_TESTS',True),
+ help="Also look for doctests in test modules. "
+ "Note that classes, methods and functions should "
+ "have either doctests or non-doctest tests, "
+ "not both. [NOSE_IPDOCTEST_TESTS]")
+ parser.add_option('--ipdoctest-extension', action="append",
+ dest="ipdoctest_extension",
+ help="Also look for doctests in files with "
+ "this extension [NOSE_IPDOCTEST_EXTENSION]")
+ # Set the default as a list, if given in env; otherwise
+ # an additional value set on the command line will cause
+ # an error.
+ env_setting = env.get('NOSE_IPDOCTEST_EXTENSION')
+ if env_setting is not None:
+ parser.set_defaults(ipdoctest_extension=tolist(env_setting))
+
+ def configure(self, options, config):
+ #print "Configuring nose plugin:", self.name # dbg
+ Plugin.configure(self, options, config)
+ # Pull standard doctest plugin out of config; we will do doctesting
+ config.plugins.plugins = [p for p in config.plugins.plugins
+ if p.name != 'doctest']
+ self.doctest_tests = options.ipdoctest_tests
+ self.extension = tolist(options.ipdoctest_extension)
+
+ self.parser = IPDocTestParser()
+ self.finder = DocTestFinder(parser=self.parser)
+ self.checker = IPDoctestOutputChecker()
+ self.globs = None
+ self.extraglobs = None
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/iptest.py b/contrib/python/ipython/py2/IPython/testing/plugin/iptest.py
index 25b4634f2f..a75cab993f 100755
--- a/contrib/python/ipython/py2/IPython/testing/plugin/iptest.py
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/iptest.py
@@ -1,19 +1,19 @@
-#!/usr/bin/env python
-"""Nose-based test runner.
-"""
-from __future__ import print_function
-
-from nose.core import main
-from nose.plugins.builtin import plugins
-from nose.plugins.doctests import Doctest
-
-from . import ipdoctest
-from .ipdoctest import IPDocTestRunner
-
-if __name__ == '__main__':
- print('WARNING: this code is incomplete!')
- print()
-
- pp = [x() for x in plugins] # activate all builtin plugins first
- main(testRunner=IPDocTestRunner(),
- plugins=pp+[ipdoctest.IPythonDoctest(),Doctest()])
+#!/usr/bin/env python
+"""Nose-based test runner.
+"""
+from __future__ import print_function
+
+from nose.core import main
+from nose.plugins.builtin import plugins
+from nose.plugins.doctests import Doctest
+
+from . import ipdoctest
+from .ipdoctest import IPDocTestRunner
+
+if __name__ == '__main__':
+ print('WARNING: this code is incomplete!')
+ print()
+
+ pp = [x() for x in plugins] # activate all builtin plugins first
+ main(testRunner=IPDocTestRunner(),
+ plugins=pp+[ipdoctest.IPythonDoctest(),Doctest()])
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/setup.py b/contrib/python/ipython/py2/IPython/testing/plugin/setup.py
index 785704337b..a3281d30c8 100755
--- a/contrib/python/ipython/py2/IPython/testing/plugin/setup.py
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/setup.py
@@ -1,18 +1,18 @@
-#!/usr/bin/env python
-"""A Nose plugin to support IPython doctests.
-"""
-
-from setuptools import setup
-
-setup(name='IPython doctest plugin',
- version='0.1',
- author='The IPython Team',
- description = 'Nose plugin to load IPython-extended doctests',
- license = 'LGPL',
- py_modules = ['ipdoctest'],
- entry_points = {
- 'nose.plugins.0.10': ['ipdoctest = ipdoctest:IPythonDoctest',
- 'extdoctest = ipdoctest:ExtensionDoctest',
- ],
- },
- )
+#!/usr/bin/env python
+"""A Nose plugin to support IPython doctests.
+"""
+
+from setuptools import setup
+
+setup(name='IPython doctest plugin',
+ version='0.1',
+ author='The IPython Team',
+ description = 'Nose plugin to load IPython-extended doctests',
+ license = 'LGPL',
+ py_modules = ['ipdoctest'],
+ entry_points = {
+ 'nose.plugins.0.10': ['ipdoctest = ipdoctest:IPythonDoctest',
+ 'extdoctest = ipdoctest:ExtensionDoctest',
+ ],
+ },
+ )
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/show_refs.py b/contrib/python/ipython/py2/IPython/testing/plugin/show_refs.py
index 4c517da949..ef7dd157ae 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/show_refs.py
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/show_refs.py
@@ -1,20 +1,20 @@
-"""Simple script to show reference holding behavior.
-
-This is used by a companion test case.
-"""
-from __future__ import print_function
-
-import gc
-
-class C(object):
- def __del__(self):
- pass
- #print 'deleting object...' # dbg
-
-if __name__ == '__main__':
- c = C()
-
- c_refs = gc.get_referrers(c)
- ref_ids = list(map(id,c_refs))
-
- print('c referrers:',list(map(type,c_refs)))
+"""Simple script to show reference holding behavior.
+
+This is used by a companion test case.
+"""
+from __future__ import print_function
+
+import gc
+
+class C(object):
+ def __del__(self):
+ pass
+ #print 'deleting object...' # dbg
+
+if __name__ == '__main__':
+ c = C()
+
+ c_refs = gc.get_referrers(c)
+ ref_ids = list(map(id,c_refs))
+
+ print('c referrers:',list(map(type,c_refs)))
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/simple.py b/contrib/python/ipython/py2/IPython/testing/plugin/simple.py
index bcc43f55e8..a7d33d9a16 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/simple.py
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/simple.py
@@ -1,34 +1,34 @@
-"""Simple example using doctests.
-
-This file just contains doctests both using plain python and IPython prompts.
-All tests should be loaded by nose.
-"""
-from __future__ import print_function
-
-def pyfunc():
- """Some pure python tests...
-
- >>> pyfunc()
- 'pyfunc'
-
- >>> import os
-
- >>> 2+3
- 5
-
- >>> for i in range(3):
- ... print(i, end=' ')
- ... print(i+1, end=' ')
- ...
- 0 1 1 2 2 3
- """
- return 'pyfunc'
-
-
-def ipyfunc2():
- """Some pure python tests...
-
- >>> 1+1
- 2
- """
- return 'pyfunc2'
+"""Simple example using doctests.
+
+This file just contains doctests both using plain python and IPython prompts.
+All tests should be loaded by nose.
+"""
+from __future__ import print_function
+
+def pyfunc():
+ """Some pure python tests...
+
+ >>> pyfunc()
+ 'pyfunc'
+
+ >>> import os
+
+ >>> 2+3
+ 5
+
+ >>> for i in range(3):
+ ... print(i, end=' ')
+ ... print(i+1, end=' ')
+ ...
+ 0 1 1 2 2 3
+ """
+ return 'pyfunc'
+
+
+def ipyfunc2():
+ """Some pure python tests...
+
+ >>> 1+1
+ 2
+ """
+ return 'pyfunc2'
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/simplevars.py b/contrib/python/ipython/py2/IPython/testing/plugin/simplevars.py
index ee4039a59a..5134c6e928 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/simplevars.py
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/simplevars.py
@@ -1,3 +1,3 @@
-from __future__ import print_function
-x = 1
-print('x is:',x)
+from __future__ import print_function
+x = 1
+print('x is:',x)
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/test_combo.txt b/contrib/python/ipython/py2/IPython/testing/plugin/test_combo.txt
index 0de694fe7e..6c8759f3e7 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/test_combo.txt
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/test_combo.txt
@@ -1,36 +1,36 @@
-=======================
- Combo testing example
-=======================
-
-This is a simple example that mixes ipython doctests::
-
- In [1]: import code
-
- In [2]: 2**12
- Out[2]: 4096
-
-with command-line example information that does *not* get executed::
-
- $ mpirun -n 4 ipengine --controller-port=10000 --controller-ip=host0
-
-and with literal examples of Python source code::
-
- controller = dict(host='myhost',
- engine_port=None, # default is 10105
- control_port=None,
- )
-
- # keys are hostnames, values are the number of engine on that host
- engines = dict(node1=2,
- node2=2,
- node3=2,
- node3=2,
- )
-
- # Force failure to detect that this test is being run.
- 1/0
-
-These source code examples are executed but no output is compared at all. An
-error or failure is reported only if an exception is raised.
-
-NOTE: the execution of pure python blocks is not yet working!
+=======================
+ Combo testing example
+=======================
+
+This is a simple example that mixes ipython doctests::
+
+ In [1]: import code
+
+ In [2]: 2**12
+ Out[2]: 4096
+
+with command-line example information that does *not* get executed::
+
+ $ mpirun -n 4 ipengine --controller-port=10000 --controller-ip=host0
+
+and with literal examples of Python source code::
+
+ controller = dict(host='myhost',
+ engine_port=None, # default is 10105
+ control_port=None,
+ )
+
+ # keys are hostnames, values are the number of engine on that host
+ engines = dict(node1=2,
+ node2=2,
+ node3=2,
+ node3=2,
+ )
+
+ # Force failure to detect that this test is being run.
+ 1/0
+
+These source code examples are executed but no output is compared at all. An
+error or failure is reported only if an exception is raised.
+
+NOTE: the execution of pure python blocks is not yet working!
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/test_example.txt b/contrib/python/ipython/py2/IPython/testing/plugin/test_example.txt
index f6258b0615..f8b681eb4f 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/test_example.txt
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/test_example.txt
@@ -1,24 +1,24 @@
-=====================================
- Tests in example form - pure python
-=====================================
-
-This file contains doctest examples embedded as code blocks, using normal
-Python prompts. See the accompanying file for similar examples using IPython
-prompts (you can't mix both types within one file). The following will be run
-as a test::
-
- >>> 1+1
- 2
- >>> print ("hello")
- hello
-
-More than one example works::
-
- >>> s="Hello World"
-
- >>> s.upper()
- 'HELLO WORLD'
-
-but you should note that the *entire* test file is considered to be a single
-test. Individual code blocks that fail are printed separately as ``example
-failures``, but the whole file is still counted and reported as one test.
+=====================================
+ Tests in example form - pure python
+=====================================
+
+This file contains doctest examples embedded as code blocks, using normal
+Python prompts. See the accompanying file for similar examples using IPython
+prompts (you can't mix both types within one file). The following will be run
+as a test::
+
+ >>> 1+1
+ 2
+ >>> print ("hello")
+ hello
+
+More than one example works::
+
+ >>> s="Hello World"
+
+ >>> s.upper()
+ 'HELLO WORLD'
+
+but you should note that the *entire* test file is considered to be a single
+test. Individual code blocks that fail are printed separately as ``example
+failures``, but the whole file is still counted and reported as one test.
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/test_exampleip.txt b/contrib/python/ipython/py2/IPython/testing/plugin/test_exampleip.txt
index cbc00cc976..8afcbfdf7d 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/test_exampleip.txt
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/test_exampleip.txt
@@ -1,30 +1,30 @@
-=================================
- Tests in example form - IPython
-=================================
-
-You can write text files with examples that use IPython prompts (as long as you
-use the nose ipython doctest plugin), but you can not mix and match prompt
-styles in a single file. That is, you either use all ``>>>`` prompts or all
-IPython-style prompts. Your test suite *can* have both types, you just need to
-put each type of example in a separate. Using IPython prompts, you can paste
-directly from your session::
-
- In [5]: s="Hello World"
-
- In [6]: s.upper()
- Out[6]: 'HELLO WORLD'
-
-Another example::
-
- In [8]: 1+3
- Out[8]: 4
-
-Just like in IPython docstrings, you can use all IPython syntax and features::
-
- In [9]: !echo "hello"
- hello
-
- In [10]: a='hi'
-
- In [11]: !echo $a
- hi
+=================================
+ Tests in example form - IPython
+=================================
+
+You can write text files with examples that use IPython prompts (as long as you
+use the nose ipython doctest plugin), but you can not mix and match prompt
+styles in a single file. That is, you either use all ``>>>`` prompts or all
+IPython-style prompts. Your test suite *can* have both types, you just need to
+put each type of example in a separate. Using IPython prompts, you can paste
+directly from your session::
+
+ In [5]: s="Hello World"
+
+ In [6]: s.upper()
+ Out[6]: 'HELLO WORLD'
+
+Another example::
+
+ In [8]: 1+3
+ Out[8]: 4
+
+Just like in IPython docstrings, you can use all IPython syntax and features::
+
+ In [9]: !echo "hello"
+ hello
+
+ In [10]: a='hi'
+
+ In [11]: !echo $a
+ hi
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/test_ipdoctest.py b/contrib/python/ipython/py2/IPython/testing/plugin/test_ipdoctest.py
index 05dc387d9b..a7add7da79 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/test_ipdoctest.py
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/test_ipdoctest.py
@@ -1,80 +1,80 @@
-"""Tests for the ipdoctest machinery itself.
-
-Note: in a file named test_X, functions whose only test is their docstring (as
-a doctest) and which have no test functionality of their own, should be called
-'doctest_foo' instead of 'test_foo', otherwise they get double-counted (the
-empty function call is counted as a test, which just inflates tests numbers
-artificially).
-"""
-from IPython.utils.py3compat import doctest_refactor_print
-
-@doctest_refactor_print
-def doctest_simple():
- """ipdoctest must handle simple inputs
-
- In [1]: 1
- Out[1]: 1
-
- In [2]: print 1
- 1
- """
-
-@doctest_refactor_print
-def doctest_multiline1():
- """The ipdoctest machinery must handle multiline examples gracefully.
-
- In [2]: for i in range(4):
- ...: print i
- ...:
- 0
- 1
- 2
- 3
- """
-
-@doctest_refactor_print
-def doctest_multiline2():
- """Multiline examples that define functions and print output.
-
- In [7]: def f(x):
- ...: return x+1
- ...:
-
- In [8]: f(1)
- Out[8]: 2
-
- In [9]: def g(x):
- ...: print 'x is:',x
- ...:
-
- In [10]: g(1)
- x is: 1
-
- In [11]: g('hello')
- x is: hello
- """
-
-
-def doctest_multiline3():
- """Multiline examples with blank lines.
-
- In [12]: def h(x):
- ....: if x>1:
- ....: return x**2
- ....: # To leave a blank line in the input, you must mark it
- ....: # with a comment character:
- ....: #
- ....: # otherwise the doctest parser gets confused.
- ....: else:
- ....: return -1
- ....:
-
- In [13]: h(5)
- Out[13]: 25
-
- In [14]: h(1)
- Out[14]: -1
-
- In [15]: h(0)
- Out[15]: -1
- """
+"""Tests for the ipdoctest machinery itself.
+
+Note: in a file named test_X, functions whose only test is their docstring (as
+a doctest) and which have no test functionality of their own, should be called
+'doctest_foo' instead of 'test_foo', otherwise they get double-counted (the
+empty function call is counted as a test, which just inflates tests numbers
+artificially).
+"""
+from IPython.utils.py3compat import doctest_refactor_print
+
+@doctest_refactor_print
+def doctest_simple():
+ """ipdoctest must handle simple inputs
+
+ In [1]: 1
+ Out[1]: 1
+
+ In [2]: print 1
+ 1
+ """
+
+@doctest_refactor_print
+def doctest_multiline1():
+ """The ipdoctest machinery must handle multiline examples gracefully.
+
+ In [2]: for i in range(4):
+ ...: print i
+ ...:
+ 0
+ 1
+ 2
+ 3
+ """
+
+@doctest_refactor_print
+def doctest_multiline2():
+ """Multiline examples that define functions and print output.
+
+ In [7]: def f(x):
+ ...: return x+1
+ ...:
+
+ In [8]: f(1)
+ Out[8]: 2
+
+ In [9]: def g(x):
+ ...: print 'x is:',x
+ ...:
+
+ In [10]: g(1)
+ x is: 1
+
+ In [11]: g('hello')
+ x is: hello
+ """
+
+
+def doctest_multiline3():
+ """Multiline examples with blank lines.
+
+ In [12]: def h(x):
+ ....: if x>1:
+ ....: return x**2
+ ....: # To leave a blank line in the input, you must mark it
+ ....: # with a comment character:
+ ....: #
+ ....: # otherwise the doctest parser gets confused.
+ ....: else:
+ ....: return -1
+ ....:
+
+ In [13]: h(5)
+ Out[13]: 25
+
+ In [14]: h(1)
+ Out[14]: -1
+
+ In [15]: h(0)
+ Out[15]: -1
+ """
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/test_refs.py b/contrib/python/ipython/py2/IPython/testing/plugin/test_refs.py
index 8a2a78b75d..50d0857134 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/test_refs.py
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/test_refs.py
@@ -1,46 +1,46 @@
-"""Some simple tests for the plugin while running scripts.
-"""
-# Module imports
-# Std lib
-import inspect
-
-# Our own
-
-#-----------------------------------------------------------------------------
-# Testing functions
-
-def test_trivial():
- """A trivial passing test."""
- pass
-
-def doctest_run():
- """Test running a trivial script.
-
- In [13]: run simplevars.py
- x is: 1
- """
-
-def doctest_runvars():
- """Test that variables defined in scripts get loaded correcly via %run.
-
- In [13]: run simplevars.py
- x is: 1
-
- In [14]: x
- Out[14]: 1
- """
-
-def doctest_ivars():
- """Test that variables defined interactively are picked up.
- In [5]: zz=1
-
- In [6]: zz
- Out[6]: 1
- """
-
-def doctest_refs():
- """DocTest reference holding issues when running scripts.
-
- In [32]: run show_refs.py
- c referrers: [<... 'dict'>]
- """
+"""Some simple tests for the plugin while running scripts.
+"""
+# Module imports
+# Std lib
+import inspect
+
+# Our own
+
+#-----------------------------------------------------------------------------
+# Testing functions
+
+def test_trivial():
+ """A trivial passing test."""
+ pass
+
+def doctest_run():
+ """Test running a trivial script.
+
+ In [13]: run simplevars.py
+ x is: 1
+ """
+
+def doctest_runvars():
+ """Test that variables defined in scripts get loaded correcly via %run.
+
+ In [13]: run simplevars.py
+ x is: 1
+
+ In [14]: x
+ Out[14]: 1
+ """
+
+def doctest_ivars():
+ """Test that variables defined interactively are picked up.
+ In [5]: zz=1
+
+ In [6]: zz
+ Out[6]: 1
+ """
+
+def doctest_refs():
+ """DocTest reference holding issues when running scripts.
+
+ In [32]: run show_refs.py
+ c referrers: [<... 'dict'>]
+ """
diff --git a/contrib/python/ipython/py2/IPython/testing/skipdoctest.py b/contrib/python/ipython/py2/IPython/testing/skipdoctest.py
index 8357f609b0..564ca54027 100644
--- a/contrib/python/ipython/py2/IPython/testing/skipdoctest.py
+++ b/contrib/python/ipython/py2/IPython/testing/skipdoctest.py
@@ -1,41 +1,41 @@
-"""Decorators marks that a doctest should be skipped, for both python 2 and 3.
-
-The IPython.testing.decorators module triggers various extra imports, including
-numpy and sympy if they're present. Since this decorator is used in core parts
-of IPython, it's in a separate module so that running IPython doesn't trigger
-those imports."""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2009-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import sys
-
-#-----------------------------------------------------------------------------
-# Decorators
-#-----------------------------------------------------------------------------
-
-def skip_doctest(f):
- """Decorator - mark a function or method for skipping its doctest.
-
- This decorator allows you to mark a function whose docstring you wish to
- omit from testing, while preserving the docstring for introspection, help,
- etc."""
- f.skip_doctest = True
- return f
-
-
-def skip_doctest_py3(f):
- """Decorator - skip the doctest under Python 3."""
- f.skip_doctest = (sys.version_info[0] >= 3)
- return f
+"""Decorators marks that a doctest should be skipped, for both python 2 and 3.
+
+The IPython.testing.decorators module triggers various extra imports, including
+numpy and sympy if they're present. Since this decorator is used in core parts
+of IPython, it's in a separate module so that running IPython doesn't trigger
+those imports."""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2009-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import sys
+
+#-----------------------------------------------------------------------------
+# Decorators
+#-----------------------------------------------------------------------------
+
+def skip_doctest(f):
+ """Decorator - mark a function or method for skipping its doctest.
+
+ This decorator allows you to mark a function whose docstring you wish to
+ omit from testing, while preserving the docstring for introspection, help,
+ etc."""
+ f.skip_doctest = True
+ return f
+
+
+def skip_doctest_py3(f):
+ """Decorator - skip the doctest under Python 3."""
+ f.skip_doctest = (sys.version_info[0] >= 3)
+ return f
def skip_doctest_py2(f):
"""Decorator - skip the doctest under Python 3."""
diff --git a/contrib/python/ipython/py2/IPython/testing/tools.py b/contrib/python/ipython/py2/IPython/testing/tools.py
index 98f796fe3c..23bf6a68cb 100644
--- a/contrib/python/ipython/py2/IPython/testing/tools.py
+++ b/contrib/python/ipython/py2/IPython/testing/tools.py
@@ -1,296 +1,296 @@
-"""Generic testing tools.
-
-Authors
--------
-- Fernando Perez <Fernando.Perez@berkeley.edu>
-"""
-
-from __future__ import absolute_import
-
+"""Generic testing tools.
+
+Authors
+-------
+- Fernando Perez <Fernando.Perez@berkeley.edu>
+"""
+
+from __future__ import absolute_import
+
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
-
-import os
-import re
-import sys
-import tempfile
-
-from contextlib import contextmanager
-from io import StringIO
-from subprocess import Popen, PIPE
+
+import os
+import re
+import sys
+import tempfile
+
+from contextlib import contextmanager
+from io import StringIO
+from subprocess import Popen, PIPE
try:
from unittest.mock import patch
except ImportError:
# Python 2 compatibility
from mock import patch
-
-try:
- # These tools are used by parts of the runtime, so we make the nose
- # dependency optional at this point. Nose is a hard dependency to run the
- # test suite, but NOT to use ipython itself.
- import nose.tools as nt
- has_nose = True
-except ImportError:
- has_nose = False
-
-from traitlets.config.loader import Config
-from IPython.utils.process import get_output_error_code
-from IPython.utils.text import list_strings
-from IPython.utils.io import temp_pyfile, Tee
-from IPython.utils import py3compat
-from IPython.utils.encoding import DEFAULT_ENCODING
-
-from . import decorators as dec
-from . import skipdoctest
-
-
-# The docstring for full_path doctests differently on win32 (different path
-# separator) so just skip the doctest there. The example remains informative.
-doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco
-
-@doctest_deco
-def full_path(startPath,files):
- """Make full paths for all the listed files, based on startPath.
-
- Only the base part of startPath is kept, since this routine is typically
- used with a script's ``__file__`` variable as startPath. The base of startPath
- is then prepended to all the listed files, forming the output list.
-
- Parameters
- ----------
- startPath : string
- Initial path to use as the base for the results. This path is split
- using os.path.split() and only its first component is kept.
-
- files : string or list
- One or more files.
-
- Examples
- --------
-
- >>> full_path('/foo/bar.py',['a.txt','b.txt'])
- ['/foo/a.txt', '/foo/b.txt']
-
- >>> full_path('/foo',['a.txt','b.txt'])
- ['/a.txt', '/b.txt']
-
- If a single file is given, the output is still a list::
-
- >>> full_path('/foo','a.txt')
- ['/a.txt']
- """
-
- files = list_strings(files)
- base = os.path.split(startPath)[0]
- return [ os.path.join(base,f) for f in files ]
-
-
-def parse_test_output(txt):
- """Parse the output of a test run and return errors, failures.
-
- Parameters
- ----------
- txt : str
- Text output of a test run, assumed to contain a line of one of the
- following forms::
-
- 'FAILED (errors=1)'
- 'FAILED (failures=1)'
- 'FAILED (errors=1, failures=1)'
-
- Returns
- -------
- nerr, nfail
- number of errors and failures.
- """
-
- err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE)
- if err_m:
- nerr = int(err_m.group(1))
- nfail = 0
- return nerr, nfail
-
- fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE)
- if fail_m:
- nerr = 0
- nfail = int(fail_m.group(1))
- return nerr, nfail
-
- both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt,
- re.MULTILINE)
- if both_m:
- nerr = int(both_m.group(1))
- nfail = int(both_m.group(2))
- return nerr, nfail
-
- # If the input didn't match any of these forms, assume no error/failures
- return 0, 0
-
-
-# So nose doesn't think this is a test
-parse_test_output.__test__ = False
-
-
-def default_argv():
- """Return a valid default argv for creating testing instances of ipython"""
-
- return ['--quick', # so no config file is loaded
- # Other defaults to minimize side effects on stdout
- '--colors=NoColor', '--no-term-title','--no-banner',
- '--autocall=0']
-
-
-def default_config():
- """Return a config object with good defaults for testing."""
- config = Config()
- config.TerminalInteractiveShell.colors = 'NoColor'
- config.TerminalTerminalInteractiveShell.term_title = False,
- config.TerminalInteractiveShell.autocall = 0
- f = tempfile.NamedTemporaryFile(suffix=u'test_hist.sqlite', delete=False)
- config.HistoryManager.hist_file = f.name
- f.close()
- config.HistoryManager.db_cache_size = 10000
- return config
-
-
-def get_ipython_cmd(as_string=False):
- """
- Return appropriate IPython command line name. By default, this will return
- a list that can be used with subprocess.Popen, for example, but passing
- `as_string=True` allows for returning the IPython command as a string.
-
- Parameters
- ----------
- as_string: bool
- Flag to allow to return the command as a string.
- """
- ipython_cmd = [sys.executable, "-m", "IPython"]
-
- if as_string:
- ipython_cmd = " ".join(ipython_cmd)
-
- return ipython_cmd
-
-def ipexec(fname, options=None, commands=()):
- """Utility to call 'ipython filename'.
-
- Starts IPython with a minimal and safe configuration to make startup as fast
- as possible.
-
- Note that this starts IPython in a subprocess!
-
- Parameters
- ----------
- fname : str
- Name of file to be executed (should have .py or .ipy extension).
-
- options : optional, list
- Extra command-line flags to be passed to IPython.
-
- commands : optional, list
- Commands to send in on stdin
-
- Returns
- -------
- (stdout, stderr) of ipython subprocess.
- """
- if options is None: options = []
-
+
+try:
+ # These tools are used by parts of the runtime, so we make the nose
+ # dependency optional at this point. Nose is a hard dependency to run the
+ # test suite, but NOT to use ipython itself.
+ import nose.tools as nt
+ has_nose = True
+except ImportError:
+ has_nose = False
+
+from traitlets.config.loader import Config
+from IPython.utils.process import get_output_error_code
+from IPython.utils.text import list_strings
+from IPython.utils.io import temp_pyfile, Tee
+from IPython.utils import py3compat
+from IPython.utils.encoding import DEFAULT_ENCODING
+
+from . import decorators as dec
+from . import skipdoctest
+
+
+# The docstring for full_path doctests differently on win32 (different path
+# separator) so just skip the doctest there. The example remains informative.
+doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco
+
+@doctest_deco
+def full_path(startPath,files):
+ """Make full paths for all the listed files, based on startPath.
+
+ Only the base part of startPath is kept, since this routine is typically
+ used with a script's ``__file__`` variable as startPath. The base of startPath
+ is then prepended to all the listed files, forming the output list.
+
+ Parameters
+ ----------
+ startPath : string
+ Initial path to use as the base for the results. This path is split
+ using os.path.split() and only its first component is kept.
+
+ files : string or list
+ One or more files.
+
+ Examples
+ --------
+
+ >>> full_path('/foo/bar.py',['a.txt','b.txt'])
+ ['/foo/a.txt', '/foo/b.txt']
+
+ >>> full_path('/foo',['a.txt','b.txt'])
+ ['/a.txt', '/b.txt']
+
+ If a single file is given, the output is still a list::
+
+ >>> full_path('/foo','a.txt')
+ ['/a.txt']
+ """
+
+ files = list_strings(files)
+ base = os.path.split(startPath)[0]
+ return [ os.path.join(base,f) for f in files ]
+
+
+def parse_test_output(txt):
+ """Parse the output of a test run and return errors, failures.
+
+ Parameters
+ ----------
+ txt : str
+ Text output of a test run, assumed to contain a line of one of the
+ following forms::
+
+ 'FAILED (errors=1)'
+ 'FAILED (failures=1)'
+ 'FAILED (errors=1, failures=1)'
+
+ Returns
+ -------
+ nerr, nfail
+ number of errors and failures.
+ """
+
+ err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE)
+ if err_m:
+ nerr = int(err_m.group(1))
+ nfail = 0
+ return nerr, nfail
+
+ fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE)
+ if fail_m:
+ nerr = 0
+ nfail = int(fail_m.group(1))
+ return nerr, nfail
+
+ both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt,
+ re.MULTILINE)
+ if both_m:
+ nerr = int(both_m.group(1))
+ nfail = int(both_m.group(2))
+ return nerr, nfail
+
+ # If the input didn't match any of these forms, assume no error/failures
+ return 0, 0
+
+
+# So nose doesn't think this is a test
+parse_test_output.__test__ = False
+
+
+def default_argv():
+ """Return a valid default argv for creating testing instances of ipython"""
+
+ return ['--quick', # so no config file is loaded
+ # Other defaults to minimize side effects on stdout
+ '--colors=NoColor', '--no-term-title','--no-banner',
+ '--autocall=0']
+
+
+def default_config():
+ """Return a config object with good defaults for testing."""
+ config = Config()
+ config.TerminalInteractiveShell.colors = 'NoColor'
+ config.TerminalTerminalInteractiveShell.term_title = False,
+ config.TerminalInteractiveShell.autocall = 0
+ f = tempfile.NamedTemporaryFile(suffix=u'test_hist.sqlite', delete=False)
+ config.HistoryManager.hist_file = f.name
+ f.close()
+ config.HistoryManager.db_cache_size = 10000
+ return config
+
+
+def get_ipython_cmd(as_string=False):
+ """
+ Return appropriate IPython command line name. By default, this will return
+ a list that can be used with subprocess.Popen, for example, but passing
+ `as_string=True` allows for returning the IPython command as a string.
+
+ Parameters
+ ----------
+ as_string: bool
+ Flag to allow to return the command as a string.
+ """
+ ipython_cmd = [sys.executable, "-m", "IPython"]
+
+ if as_string:
+ ipython_cmd = " ".join(ipython_cmd)
+
+ return ipython_cmd
+
+def ipexec(fname, options=None, commands=()):
+ """Utility to call 'ipython filename'.
+
+ Starts IPython with a minimal and safe configuration to make startup as fast
+ as possible.
+
+ Note that this starts IPython in a subprocess!
+
+ Parameters
+ ----------
+ fname : str
+ Name of file to be executed (should have .py or .ipy extension).
+
+ options : optional, list
+ Extra command-line flags to be passed to IPython.
+
+ commands : optional, list
+ Commands to send in on stdin
+
+ Returns
+ -------
+ (stdout, stderr) of ipython subprocess.
+ """
+ if options is None: options = []
+
cmdargs = default_argv() + options
-
- test_dir = os.path.dirname(__file__)
-
- ipython_cmd = get_ipython_cmd()
- # Absolute path for filename
- full_fname = os.path.join(test_dir, fname)
- full_cmd = ipython_cmd + cmdargs + [full_fname]
- env = os.environ.copy()
- # FIXME: ignore all warnings in ipexec while we have shims
- # should we keep suppressing warnings here, even after removing shims?
- env['PYTHONWARNINGS'] = 'ignore'
- # env.pop('PYTHONWARNINGS', None) # Avoid extraneous warnings appearing on stderr
- for k, v in env.items():
- # Debug a bizarre failure we've seen on Windows:
- # TypeError: environment can only contain strings
- if not isinstance(v, str):
- print(k, v)
- p = Popen(full_cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env)
- out, err = p.communicate(input=py3compat.str_to_bytes('\n'.join(commands)) or None)
- out, err = py3compat.bytes_to_str(out), py3compat.bytes_to_str(err)
- # `import readline` causes 'ESC[?1034h' to be output sometimes,
- # so strip that out before doing comparisons
- if out:
- out = re.sub(r'\x1b\[[^h]+h', '', out)
- return out, err
-
-
-def ipexec_validate(fname, expected_out, expected_err='',
- options=None, commands=()):
- """Utility to call 'ipython filename' and validate output/error.
-
- This function raises an AssertionError if the validation fails.
-
- Note that this starts IPython in a subprocess!
-
- Parameters
- ----------
- fname : str
- Name of the file to be executed (should have .py or .ipy extension).
-
- expected_out : str
- Expected stdout of the process.
-
- expected_err : optional, str
- Expected stderr of the process.
-
- options : optional, list
- Extra command-line flags to be passed to IPython.
-
- Returns
- -------
- None
- """
-
- import nose.tools as nt
-
- out, err = ipexec(fname, options, commands)
- #print 'OUT', out # dbg
- #print 'ERR', err # dbg
- # If there are any errors, we must check those befor stdout, as they may be
- # more informative than simply having an empty stdout.
- if err:
- if expected_err:
- nt.assert_equal("\n".join(err.strip().splitlines()), "\n".join(expected_err.strip().splitlines()))
- else:
- raise ValueError('Running file %r produced error: %r' %
- (fname, err))
- # If no errors or output on stderr was expected, match stdout
- nt.assert_equal("\n".join(out.strip().splitlines()), "\n".join(expected_out.strip().splitlines()))
-
-
-class TempFileMixin(object):
- """Utility class to create temporary Python/IPython files.
-
- Meant as a mixin class for test cases."""
-
- def mktmp(self, src, ext='.py'):
- """Make a valid python temp file."""
- fname, f = temp_pyfile(src, ext)
- self.tmpfile = f
- self.fname = fname
-
- def tearDown(self):
- if hasattr(self, 'tmpfile'):
- # If the tmpfile wasn't made because of skipped tests, like in
- # win32, there's nothing to cleanup.
- self.tmpfile.close()
- try:
- os.unlink(self.fname)
- except:
- # On Windows, even though we close the file, we still can't
- # delete it. I have no clue why
- pass
-
+
+ test_dir = os.path.dirname(__file__)
+
+ ipython_cmd = get_ipython_cmd()
+ # Absolute path for filename
+ full_fname = os.path.join(test_dir, fname)
+ full_cmd = ipython_cmd + cmdargs + [full_fname]
+ env = os.environ.copy()
+ # FIXME: ignore all warnings in ipexec while we have shims
+ # should we keep suppressing warnings here, even after removing shims?
+ env['PYTHONWARNINGS'] = 'ignore'
+ # env.pop('PYTHONWARNINGS', None) # Avoid extraneous warnings appearing on stderr
+ for k, v in env.items():
+ # Debug a bizarre failure we've seen on Windows:
+ # TypeError: environment can only contain strings
+ if not isinstance(v, str):
+ print(k, v)
+ p = Popen(full_cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env)
+ out, err = p.communicate(input=py3compat.str_to_bytes('\n'.join(commands)) or None)
+ out, err = py3compat.bytes_to_str(out), py3compat.bytes_to_str(err)
+ # `import readline` causes 'ESC[?1034h' to be output sometimes,
+ # so strip that out before doing comparisons
+ if out:
+ out = re.sub(r'\x1b\[[^h]+h', '', out)
+ return out, err
+
+
+def ipexec_validate(fname, expected_out, expected_err='',
+ options=None, commands=()):
+ """Utility to call 'ipython filename' and validate output/error.
+
+ This function raises an AssertionError if the validation fails.
+
+ Note that this starts IPython in a subprocess!
+
+ Parameters
+ ----------
+ fname : str
+ Name of the file to be executed (should have .py or .ipy extension).
+
+ expected_out : str
+ Expected stdout of the process.
+
+ expected_err : optional, str
+ Expected stderr of the process.
+
+ options : optional, list
+ Extra command-line flags to be passed to IPython.
+
+ Returns
+ -------
+ None
+ """
+
+ import nose.tools as nt
+
+ out, err = ipexec(fname, options, commands)
+ #print 'OUT', out # dbg
+ #print 'ERR', err # dbg
+ # If there are any errors, we must check those befor stdout, as they may be
+ # more informative than simply having an empty stdout.
+ if err:
+ if expected_err:
+ nt.assert_equal("\n".join(err.strip().splitlines()), "\n".join(expected_err.strip().splitlines()))
+ else:
+ raise ValueError('Running file %r produced error: %r' %
+ (fname, err))
+ # If no errors or output on stderr was expected, match stdout
+ nt.assert_equal("\n".join(out.strip().splitlines()), "\n".join(expected_out.strip().splitlines()))
+
+
+class TempFileMixin(object):
+ """Utility class to create temporary Python/IPython files.
+
+ Meant as a mixin class for test cases."""
+
+ def mktmp(self, src, ext='.py'):
+ """Make a valid python temp file."""
+ fname, f = temp_pyfile(src, ext)
+ self.tmpfile = f
+ self.fname = fname
+
+ def tearDown(self):
+ if hasattr(self, 'tmpfile'):
+ # If the tmpfile wasn't made because of skipped tests, like in
+ # win32, there's nothing to cleanup.
+ self.tmpfile.close()
+ try:
+ os.unlink(self.fname)
+ except:
+ # On Windows, even though we close the file, we still can't
+ # delete it. I have no clue why
+ pass
+
def __enter__(self):
return self
@@ -298,149 +298,149 @@ class TempFileMixin(object):
self.tearDown()
-pair_fail_msg = ("Testing {0}\n\n"
- "In:\n"
- " {1!r}\n"
- "Expected:\n"
- " {2!r}\n"
- "Got:\n"
- " {3!r}\n")
-def check_pairs(func, pairs):
- """Utility function for the common case of checking a function with a
- sequence of input/output pairs.
-
- Parameters
- ----------
- func : callable
- The function to be tested. Should accept a single argument.
- pairs : iterable
- A list of (input, expected_output) tuples.
-
- Returns
- -------
- None. Raises an AssertionError if any output does not match the expected
- value.
- """
- name = getattr(func, "func_name", getattr(func, "__name__", "<unknown>"))
- for inp, expected in pairs:
- out = func(inp)
- assert out == expected, pair_fail_msg.format(name, inp, expected, out)
-
-
-if py3compat.PY3:
- MyStringIO = StringIO
-else:
- # In Python 2, stdout/stderr can have either bytes or unicode written to them,
- # so we need a class that can handle both.
- class MyStringIO(StringIO):
- def write(self, s):
- s = py3compat.cast_unicode(s, encoding=DEFAULT_ENCODING)
- super(MyStringIO, self).write(s)
-
-_re_type = type(re.compile(r''))
-
-notprinted_msg = """Did not find {0!r} in printed output (on {1}):
--------
-{2!s}
--------
-"""
-
-class AssertPrints(object):
- """Context manager for testing that code prints certain text.
-
- Examples
- --------
- >>> with AssertPrints("abc", suppress=False):
- ... print("abcd")
- ... print("def")
- ...
- abcd
- def
- """
- def __init__(self, s, channel='stdout', suppress=True):
- self.s = s
- if isinstance(self.s, (py3compat.string_types, _re_type)):
- self.s = [self.s]
- self.channel = channel
- self.suppress = suppress
-
- def __enter__(self):
- self.orig_stream = getattr(sys, self.channel)
- self.buffer = MyStringIO()
- self.tee = Tee(self.buffer, channel=self.channel)
- setattr(sys, self.channel, self.buffer if self.suppress else self.tee)
-
- def __exit__(self, etype, value, traceback):
- try:
- if value is not None:
- # If an error was raised, don't check anything else
- return False
- self.tee.flush()
- setattr(sys, self.channel, self.orig_stream)
- printed = self.buffer.getvalue()
- for s in self.s:
- if isinstance(s, _re_type):
- assert s.search(printed), notprinted_msg.format(s.pattern, self.channel, printed)
- else:
- assert s in printed, notprinted_msg.format(s, self.channel, printed)
- return False
- finally:
- self.tee.close()
-
-printed_msg = """Found {0!r} in printed output (on {1}):
--------
-{2!s}
--------
-"""
-
-class AssertNotPrints(AssertPrints):
- """Context manager for checking that certain output *isn't* produced.
-
- Counterpart of AssertPrints"""
- def __exit__(self, etype, value, traceback):
- try:
- if value is not None:
- # If an error was raised, don't check anything else
- self.tee.close()
- return False
- self.tee.flush()
- setattr(sys, self.channel, self.orig_stream)
- printed = self.buffer.getvalue()
- for s in self.s:
- if isinstance(s, _re_type):
- assert not s.search(printed),printed_msg.format(
- s.pattern, self.channel, printed)
- else:
- assert s not in printed, printed_msg.format(
- s, self.channel, printed)
- return False
- finally:
- self.tee.close()
-
-@contextmanager
-def mute_warn():
- from IPython.utils import warn
- save_warn = warn.warn
- warn.warn = lambda *a, **kw: None
- try:
- yield
- finally:
- warn.warn = save_warn
-
-@contextmanager
-def make_tempfile(name):
- """ Create an empty, named, temporary file for the duration of the context.
- """
- f = open(name, 'w')
- f.close()
- try:
- yield
- finally:
- os.unlink(name)
-
+pair_fail_msg = ("Testing {0}\n\n"
+ "In:\n"
+ " {1!r}\n"
+ "Expected:\n"
+ " {2!r}\n"
+ "Got:\n"
+ " {3!r}\n")
+def check_pairs(func, pairs):
+ """Utility function for the common case of checking a function with a
+ sequence of input/output pairs.
+
+ Parameters
+ ----------
+ func : callable
+ The function to be tested. Should accept a single argument.
+ pairs : iterable
+ A list of (input, expected_output) tuples.
+
+ Returns
+ -------
+ None. Raises an AssertionError if any output does not match the expected
+ value.
+ """
+ name = getattr(func, "func_name", getattr(func, "__name__", "<unknown>"))
+ for inp, expected in pairs:
+ out = func(inp)
+ assert out == expected, pair_fail_msg.format(name, inp, expected, out)
+
+
+if py3compat.PY3:
+ MyStringIO = StringIO
+else:
+ # In Python 2, stdout/stderr can have either bytes or unicode written to them,
+ # so we need a class that can handle both.
+ class MyStringIO(StringIO):
+ def write(self, s):
+ s = py3compat.cast_unicode(s, encoding=DEFAULT_ENCODING)
+ super(MyStringIO, self).write(s)
+
+_re_type = type(re.compile(r''))
+
+notprinted_msg = """Did not find {0!r} in printed output (on {1}):
+-------
+{2!s}
+-------
+"""
+
+class AssertPrints(object):
+ """Context manager for testing that code prints certain text.
+
+ Examples
+ --------
+ >>> with AssertPrints("abc", suppress=False):
+ ... print("abcd")
+ ... print("def")
+ ...
+ abcd
+ def
+ """
+ def __init__(self, s, channel='stdout', suppress=True):
+ self.s = s
+ if isinstance(self.s, (py3compat.string_types, _re_type)):
+ self.s = [self.s]
+ self.channel = channel
+ self.suppress = suppress
+
+ def __enter__(self):
+ self.orig_stream = getattr(sys, self.channel)
+ self.buffer = MyStringIO()
+ self.tee = Tee(self.buffer, channel=self.channel)
+ setattr(sys, self.channel, self.buffer if self.suppress else self.tee)
+
+ def __exit__(self, etype, value, traceback):
+ try:
+ if value is not None:
+ # If an error was raised, don't check anything else
+ return False
+ self.tee.flush()
+ setattr(sys, self.channel, self.orig_stream)
+ printed = self.buffer.getvalue()
+ for s in self.s:
+ if isinstance(s, _re_type):
+ assert s.search(printed), notprinted_msg.format(s.pattern, self.channel, printed)
+ else:
+ assert s in printed, notprinted_msg.format(s, self.channel, printed)
+ return False
+ finally:
+ self.tee.close()
+
+printed_msg = """Found {0!r} in printed output (on {1}):
+-------
+{2!s}
+-------
+"""
+
+class AssertNotPrints(AssertPrints):
+ """Context manager for checking that certain output *isn't* produced.
+
+ Counterpart of AssertPrints"""
+ def __exit__(self, etype, value, traceback):
+ try:
+ if value is not None:
+ # If an error was raised, don't check anything else
+ self.tee.close()
+ return False
+ self.tee.flush()
+ setattr(sys, self.channel, self.orig_stream)
+ printed = self.buffer.getvalue()
+ for s in self.s:
+ if isinstance(s, _re_type):
+ assert not s.search(printed),printed_msg.format(
+ s.pattern, self.channel, printed)
+ else:
+ assert s not in printed, printed_msg.format(
+ s, self.channel, printed)
+ return False
+ finally:
+ self.tee.close()
+
+@contextmanager
+def mute_warn():
+ from IPython.utils import warn
+ save_warn = warn.warn
+ warn.warn = lambda *a, **kw: None
+ try:
+ yield
+ finally:
+ warn.warn = save_warn
+
+@contextmanager
+def make_tempfile(name):
+ """ Create an empty, named, temporary file for the duration of the context.
+ """
+ f = open(name, 'w')
+ f.close()
+ try:
+ yield
+ finally:
+ os.unlink(name)
+
def fake_input(inputs):
"""Temporarily replace the input() function to return the given values
-
+
Use as a context manager:
with fake_input(['result1', 'result2']):
@@ -460,24 +460,24 @@ def fake_input(inputs):
'input' if py3compat.PY3 else 'raw_input')
return patch(input_name, mock_input)
-def help_output_test(subcommand=''):
- """test that `ipython [subcommand] -h` works"""
- cmd = get_ipython_cmd() + [subcommand, '-h']
- out, err, rc = get_output_error_code(cmd)
- nt.assert_equal(rc, 0, err)
- nt.assert_not_in("Traceback", err)
- nt.assert_in("Options", out)
- nt.assert_in("--help-all", out)
- return out, err
-
-
-def help_all_output_test(subcommand=''):
- """test that `ipython [subcommand] --help-all` works"""
- cmd = get_ipython_cmd() + [subcommand, '--help-all']
- out, err, rc = get_output_error_code(cmd)
- nt.assert_equal(rc, 0, err)
- nt.assert_not_in("Traceback", err)
- nt.assert_in("Options", out)
+def help_output_test(subcommand=''):
+ """test that `ipython [subcommand] -h` works"""
+ cmd = get_ipython_cmd() + [subcommand, '-h']
+ out, err, rc = get_output_error_code(cmd)
+ nt.assert_equal(rc, 0, err)
+ nt.assert_not_in("Traceback", err)
+ nt.assert_in("Options", out)
+ nt.assert_in("--help-all", out)
+ return out, err
+
+
+def help_all_output_test(subcommand=''):
+ """test that `ipython [subcommand] --help-all` works"""
+ cmd = get_ipython_cmd() + [subcommand, '--help-all']
+ out, err, rc = get_output_error_code(cmd)
+ nt.assert_equal(rc, 0, err)
+ nt.assert_not_in("Traceback", err)
+ nt.assert_in("Options", out)
nt.assert_in("Class", out)
- return out, err
-
+ return out, err
+
diff --git a/contrib/python/ipython/py2/IPython/utils/PyColorize.py b/contrib/python/ipython/py2/IPython/utils/PyColorize.py
index 13c03c3398..124eb2d4e3 100644
--- a/contrib/python/ipython/py2/IPython/utils/PyColorize.py
+++ b/contrib/python/ipython/py2/IPython/utils/PyColorize.py
@@ -1,127 +1,127 @@
-# -*- coding: utf-8 -*-
-"""
-Class and program to colorize python source code for ANSI terminals.
-
-Based on an HTML code highlighter by Jurgen Hermann found at:
-http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298
-
-Modifications by Fernando Perez (fperez@colorado.edu).
-
-Information on the original HTML highlighter follows:
-
-MoinMoin - Python Source Parser
-
-Title: Colorize Python source using the built-in tokenizer
-
-Submitter: Jurgen Hermann
-Last Updated:2001/04/06
-
-Version no:1.2
-
-Description:
-
-This code is part of MoinMoin (http://moin.sourceforge.net/) and converts
-Python source code to HTML markup, rendering comments, keywords,
-operators, numeric and string literals in different colors.
-
-It shows how to use the built-in keyword, token and tokenize modules to
-scan Python source code and re-emit it with no changes to its original
-formatting (which is the hard part).
-"""
-from __future__ import print_function
-from __future__ import absolute_import
-from __future__ import unicode_literals
-
-__all__ = ['ANSICodeColors','Parser']
-
-_scheme_default = 'Linux'
-
-
-# Imports
-import keyword
-import os
-import sys
-import token
-import tokenize
-
-try:
- generate_tokens = tokenize.generate_tokens
-except AttributeError:
- # Python 3. Note that we use the undocumented _tokenize because it expects
- # strings, not bytes. See also Python issue #9969.
- generate_tokens = tokenize._tokenize
-
-from IPython.utils.coloransi import TermColors, InputTermColors ,ColorScheme, ColorSchemeTable
-from IPython.utils.py3compat import PY3
-
+# -*- coding: utf-8 -*-
+"""
+Class and program to colorize python source code for ANSI terminals.
+
+Based on an HTML code highlighter by Jurgen Hermann found at:
+http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298
+
+Modifications by Fernando Perez (fperez@colorado.edu).
+
+Information on the original HTML highlighter follows:
+
+MoinMoin - Python Source Parser
+
+Title: Colorize Python source using the built-in tokenizer
+
+Submitter: Jurgen Hermann
+Last Updated:2001/04/06
+
+Version no:1.2
+
+Description:
+
+This code is part of MoinMoin (http://moin.sourceforge.net/) and converts
+Python source code to HTML markup, rendering comments, keywords,
+operators, numeric and string literals in different colors.
+
+It shows how to use the built-in keyword, token and tokenize modules to
+scan Python source code and re-emit it with no changes to its original
+formatting (which is the hard part).
+"""
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
+__all__ = ['ANSICodeColors','Parser']
+
+_scheme_default = 'Linux'
+
+
+# Imports
+import keyword
+import os
+import sys
+import token
+import tokenize
+
+try:
+ generate_tokens = tokenize.generate_tokens
+except AttributeError:
+ # Python 3. Note that we use the undocumented _tokenize because it expects
+ # strings, not bytes. See also Python issue #9969.
+ generate_tokens = tokenize._tokenize
+
+from IPython.utils.coloransi import TermColors, InputTermColors ,ColorScheme, ColorSchemeTable
+from IPython.utils.py3compat import PY3
+
from .colorable import Colorable
-if PY3:
- from io import StringIO
-else:
- from StringIO import StringIO
-
-#############################################################################
-### Python Source Parser (does Hilighting)
-#############################################################################
-
-_KEYWORD = token.NT_OFFSET + 1
-_TEXT = token.NT_OFFSET + 2
-
-#****************************************************************************
-# Builtin color schemes
-
-Colors = TermColors # just a shorthand
-
-# Build a few color schemes
-NoColor = ColorScheme(
- 'NoColor',{
- 'header' : Colors.NoColor,
- token.NUMBER : Colors.NoColor,
- token.OP : Colors.NoColor,
- token.STRING : Colors.NoColor,
- tokenize.COMMENT : Colors.NoColor,
- token.NAME : Colors.NoColor,
- token.ERRORTOKEN : Colors.NoColor,
-
- _KEYWORD : Colors.NoColor,
- _TEXT : Colors.NoColor,
-
- 'in_prompt' : InputTermColors.NoColor, # Input prompt
- 'in_number' : InputTermColors.NoColor, # Input prompt number
- 'in_prompt2' : InputTermColors.NoColor, # Continuation prompt
- 'in_normal' : InputTermColors.NoColor, # color off (usu. Colors.Normal)
-
- 'out_prompt' : Colors.NoColor, # Output prompt
- 'out_number' : Colors.NoColor, # Output prompt number
-
- 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
- } )
-
-LinuxColors = ColorScheme(
- 'Linux',{
- 'header' : Colors.LightRed,
- token.NUMBER : Colors.LightCyan,
- token.OP : Colors.Yellow,
- token.STRING : Colors.LightBlue,
- tokenize.COMMENT : Colors.LightRed,
- token.NAME : Colors.Normal,
- token.ERRORTOKEN : Colors.Red,
-
- _KEYWORD : Colors.LightGreen,
- _TEXT : Colors.Yellow,
-
- 'in_prompt' : InputTermColors.Green,
- 'in_number' : InputTermColors.LightGreen,
- 'in_prompt2' : InputTermColors.Green,
- 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
-
- 'out_prompt' : Colors.Red,
- 'out_number' : Colors.LightRed,
-
- 'normal' : Colors.Normal # color off (usu. Colors.Normal)
- } )
-
+if PY3:
+ from io import StringIO
+else:
+ from StringIO import StringIO
+
+#############################################################################
+### Python Source Parser (does Hilighting)
+#############################################################################
+
+_KEYWORD = token.NT_OFFSET + 1
+_TEXT = token.NT_OFFSET + 2
+
+#****************************************************************************
+# Builtin color schemes
+
+Colors = TermColors # just a shorthand
+
+# Build a few color schemes
+NoColor = ColorScheme(
+ 'NoColor',{
+ 'header' : Colors.NoColor,
+ token.NUMBER : Colors.NoColor,
+ token.OP : Colors.NoColor,
+ token.STRING : Colors.NoColor,
+ tokenize.COMMENT : Colors.NoColor,
+ token.NAME : Colors.NoColor,
+ token.ERRORTOKEN : Colors.NoColor,
+
+ _KEYWORD : Colors.NoColor,
+ _TEXT : Colors.NoColor,
+
+ 'in_prompt' : InputTermColors.NoColor, # Input prompt
+ 'in_number' : InputTermColors.NoColor, # Input prompt number
+ 'in_prompt2' : InputTermColors.NoColor, # Continuation prompt
+ 'in_normal' : InputTermColors.NoColor, # color off (usu. Colors.Normal)
+
+ 'out_prompt' : Colors.NoColor, # Output prompt
+ 'out_number' : Colors.NoColor, # Output prompt number
+
+ 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
+ } )
+
+LinuxColors = ColorScheme(
+ 'Linux',{
+ 'header' : Colors.LightRed,
+ token.NUMBER : Colors.LightCyan,
+ token.OP : Colors.Yellow,
+ token.STRING : Colors.LightBlue,
+ tokenize.COMMENT : Colors.LightRed,
+ token.NAME : Colors.Normal,
+ token.ERRORTOKEN : Colors.Red,
+
+ _KEYWORD : Colors.LightGreen,
+ _TEXT : Colors.Yellow,
+
+ 'in_prompt' : InputTermColors.Green,
+ 'in_number' : InputTermColors.LightGreen,
+ 'in_prompt2' : InputTermColors.Green,
+ 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
+
+ 'out_prompt' : Colors.Red,
+ 'out_number' : Colors.LightRed,
+
+ 'normal' : Colors.Normal # color off (usu. Colors.Normal)
+ } )
+
NeutralColors = ColorScheme(
'Neutral',{
'header' : Colors.Red,
@@ -156,227 +156,227 @@ NeutralColors = ColorScheme(
if os.name == 'nt':
NeutralColors = LinuxColors.copy(name='Neutral')
-LightBGColors = ColorScheme(
- 'LightBG',{
- 'header' : Colors.Red,
- token.NUMBER : Colors.Cyan,
- token.OP : Colors.Blue,
- token.STRING : Colors.Blue,
- tokenize.COMMENT : Colors.Red,
- token.NAME : Colors.Normal,
- token.ERRORTOKEN : Colors.Red,
-
-
- _KEYWORD : Colors.Green,
- _TEXT : Colors.Blue,
-
- 'in_prompt' : InputTermColors.Blue,
- 'in_number' : InputTermColors.LightBlue,
- 'in_prompt2' : InputTermColors.Blue,
- 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
-
- 'out_prompt' : Colors.Red,
- 'out_number' : Colors.LightRed,
-
- 'normal' : Colors.Normal # color off (usu. Colors.Normal)
- } )
-
-# Build table of color schemes (needed by the parser)
+LightBGColors = ColorScheme(
+ 'LightBG',{
+ 'header' : Colors.Red,
+ token.NUMBER : Colors.Cyan,
+ token.OP : Colors.Blue,
+ token.STRING : Colors.Blue,
+ tokenize.COMMENT : Colors.Red,
+ token.NAME : Colors.Normal,
+ token.ERRORTOKEN : Colors.Red,
+
+
+ _KEYWORD : Colors.Green,
+ _TEXT : Colors.Blue,
+
+ 'in_prompt' : InputTermColors.Blue,
+ 'in_number' : InputTermColors.LightBlue,
+ 'in_prompt2' : InputTermColors.Blue,
+ 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
+
+ 'out_prompt' : Colors.Red,
+ 'out_number' : Colors.LightRed,
+
+ 'normal' : Colors.Normal # color off (usu. Colors.Normal)
+ } )
+
+# Build table of color schemes (needed by the parser)
ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors],
- _scheme_default)
-
+ _scheme_default)
+
class Parser(Colorable):
- """ Format colored Python source.
- """
-
+ """ Format colored Python source.
+ """
+
def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
- """ Create a parser with a specified color table and output channel.
-
- Call format() to process code.
- """
+ """ Create a parser with a specified color table and output channel.
+
+ Call format() to process code.
+ """
super(Parser, self).__init__(parent=parent)
- self.color_table = color_table and color_table or ANSICodeColors
- self.out = out
-
- def format(self, raw, out = None, scheme = ''):
- return self.format2(raw, out, scheme)[0]
-
- def format2(self, raw, out = None, scheme = ''):
- """ Parse and send the colored source.
-
- If out and scheme are not specified, the defaults (given to
- constructor) are used.
-
- out should be a file-type object. Optionally, out can be given as the
- string 'str' and the parser will automatically return the output in a
- string."""
-
- string_output = 0
- if out == 'str' or self.out == 'str' or \
- isinstance(self.out,StringIO):
- # XXX - I don't really like this state handling logic, but at this
- # point I don't want to make major changes, so adding the
- # isinstance() check is the simplest I can do to ensure correct
- # behavior.
- out_old = self.out
- self.out = StringIO()
- string_output = 1
- elif out is not None:
- self.out = out
-
- # Fast return of the unmodified input for NoColor scheme
- if scheme == 'NoColor':
- error = False
- self.out.write(raw)
- if string_output:
- return raw,error
- else:
- return None,error
-
- # local shorthands
- colors = self.color_table[scheme].colors
- self.colors = colors # put in object so __call__ sees it
-
- # Remove trailing whitespace and normalize tabs
- self.raw = raw.expandtabs().rstrip()
-
- # store line offsets in self.lines
- self.lines = [0, 0]
- pos = 0
- raw_find = self.raw.find
- lines_append = self.lines.append
- while 1:
- pos = raw_find('\n', pos) + 1
- if not pos: break
- lines_append(pos)
- lines_append(len(self.raw))
-
- # parse the source and write it
- self.pos = 0
- text = StringIO(self.raw)
-
- error = False
- try:
- for atoken in generate_tokens(text.readline):
- self(*atoken)
- except tokenize.TokenError as ex:
- msg = ex.args[0]
- line = ex.args[1][0]
- self.out.write("%s\n\n*** ERROR: %s%s%s\n" %
- (colors[token.ERRORTOKEN],
- msg, self.raw[self.lines[line]:],
- colors.normal)
- )
- error = True
- self.out.write(colors.normal+'\n')
- if string_output:
- output = self.out.getvalue()
- self.out = out_old
- return (output, error)
- return (None, error)
-
- def __call__(self, toktype, toktext, start_pos, end_pos, line):
- """ Token handler, with syntax highlighting."""
- (srow,scol) = start_pos
- (erow,ecol) = end_pos
- colors = self.colors
- owrite = self.out.write
-
- # line separator, so this works across platforms
- linesep = os.linesep
-
- # calculate new positions
- oldpos = self.pos
- newpos = self.lines[srow] + scol
- self.pos = newpos + len(toktext)
-
- # send the original whitespace, if needed
- if newpos > oldpos:
- owrite(self.raw[oldpos:newpos])
-
- # skip indenting tokens
- if toktype in [token.INDENT, token.DEDENT]:
- self.pos = newpos
- return
-
- # map token type to a color group
- if token.LPAR <= toktype <= token.OP:
- toktype = token.OP
- elif toktype == token.NAME and keyword.iskeyword(toktext):
- toktype = _KEYWORD
- color = colors.get(toktype, colors[_TEXT])
-
- #print '<%s>' % toktext, # dbg
-
- # Triple quoted strings must be handled carefully so that backtracking
- # in pagers works correctly. We need color terminators on _each_ line.
- if linesep in toktext:
- toktext = toktext.replace(linesep, '%s%s%s' %
- (colors.normal,linesep,color))
-
- # send text
- owrite('%s%s%s' % (color,toktext,colors.normal))
-
-def main(argv=None):
- """Run as a command-line script: colorize a python file or stdin using ANSI
- color escapes and print to stdout.
-
- Inputs:
-
- - argv(None): a list of strings like sys.argv[1:] giving the command-line
- arguments. If None, use sys.argv[1:].
- """
-
- usage_msg = """%prog [options] [filename]
-
-Colorize a python file or stdin using ANSI color escapes and print to stdout.
-If no filename is given, or if filename is -, read standard input."""
-
- import optparse
- parser = optparse.OptionParser(usage=usage_msg)
- newopt = parser.add_option
- newopt('-s','--scheme',metavar='NAME',dest='scheme_name',action='store',
- choices=['Linux','LightBG','NoColor'],default=_scheme_default,
- help="give the color scheme to use. Currently only 'Linux'\
- (default) and 'LightBG' and 'NoColor' are implemented (give without\
- quotes)")
-
- opts,args = parser.parse_args(argv)
-
- if len(args) > 1:
- parser.error("you must give at most one filename.")
-
- if len(args) == 0:
- fname = '-' # no filename given; setup to read from stdin
- else:
- fname = args[0]
-
- if fname == '-':
- stream = sys.stdin
- else:
- try:
- stream = open(fname)
- except IOError as msg:
- print(msg, file=sys.stderr)
- sys.exit(1)
-
- parser = Parser()
-
- # we need nested try blocks because pre-2.5 python doesn't support unified
- # try-except-finally
- try:
- try:
- # write colorized version to stdout
- parser.format(stream.read(),scheme=opts.scheme_name)
- except IOError as msg:
- # if user reads through a pager and quits, don't print traceback
- if msg.args != (32,'Broken pipe'):
- raise
- finally:
- if stream is not sys.stdin:
- stream.close() # in case a non-handled exception happened above
-
-if __name__ == "__main__":
- main()
+ self.color_table = color_table and color_table or ANSICodeColors
+ self.out = out
+
+ def format(self, raw, out = None, scheme = ''):
+ return self.format2(raw, out, scheme)[0]
+
+ def format2(self, raw, out = None, scheme = ''):
+ """ Parse and send the colored source.
+
+ If out and scheme are not specified, the defaults (given to
+ constructor) are used.
+
+ out should be a file-type object. Optionally, out can be given as the
+ string 'str' and the parser will automatically return the output in a
+ string."""
+
+ string_output = 0
+ if out == 'str' or self.out == 'str' or \
+ isinstance(self.out,StringIO):
+ # XXX - I don't really like this state handling logic, but at this
+ # point I don't want to make major changes, so adding the
+ # isinstance() check is the simplest I can do to ensure correct
+ # behavior.
+ out_old = self.out
+ self.out = StringIO()
+ string_output = 1
+ elif out is not None:
+ self.out = out
+
+ # Fast return of the unmodified input for NoColor scheme
+ if scheme == 'NoColor':
+ error = False
+ self.out.write(raw)
+ if string_output:
+ return raw,error
+ else:
+ return None,error
+
+ # local shorthands
+ colors = self.color_table[scheme].colors
+ self.colors = colors # put in object so __call__ sees it
+
+ # Remove trailing whitespace and normalize tabs
+ self.raw = raw.expandtabs().rstrip()
+
+ # store line offsets in self.lines
+ self.lines = [0, 0]
+ pos = 0
+ raw_find = self.raw.find
+ lines_append = self.lines.append
+ while 1:
+ pos = raw_find('\n', pos) + 1
+ if not pos: break
+ lines_append(pos)
+ lines_append(len(self.raw))
+
+ # parse the source and write it
+ self.pos = 0
+ text = StringIO(self.raw)
+
+ error = False
+ try:
+ for atoken in generate_tokens(text.readline):
+ self(*atoken)
+ except tokenize.TokenError as ex:
+ msg = ex.args[0]
+ line = ex.args[1][0]
+ self.out.write("%s\n\n*** ERROR: %s%s%s\n" %
+ (colors[token.ERRORTOKEN],
+ msg, self.raw[self.lines[line]:],
+ colors.normal)
+ )
+ error = True
+ self.out.write(colors.normal+'\n')
+ if string_output:
+ output = self.out.getvalue()
+ self.out = out_old
+ return (output, error)
+ return (None, error)
+
+ def __call__(self, toktype, toktext, start_pos, end_pos, line):
+ """ Token handler, with syntax highlighting."""
+ (srow,scol) = start_pos
+ (erow,ecol) = end_pos
+ colors = self.colors
+ owrite = self.out.write
+
+ # line separator, so this works across platforms
+ linesep = os.linesep
+
+ # calculate new positions
+ oldpos = self.pos
+ newpos = self.lines[srow] + scol
+ self.pos = newpos + len(toktext)
+
+ # send the original whitespace, if needed
+ if newpos > oldpos:
+ owrite(self.raw[oldpos:newpos])
+
+ # skip indenting tokens
+ if toktype in [token.INDENT, token.DEDENT]:
+ self.pos = newpos
+ return
+
+ # map token type to a color group
+ if token.LPAR <= toktype <= token.OP:
+ toktype = token.OP
+ elif toktype == token.NAME and keyword.iskeyword(toktext):
+ toktype = _KEYWORD
+ color = colors.get(toktype, colors[_TEXT])
+
+ #print '<%s>' % toktext, # dbg
+
+ # Triple quoted strings must be handled carefully so that backtracking
+ # in pagers works correctly. We need color terminators on _each_ line.
+ if linesep in toktext:
+ toktext = toktext.replace(linesep, '%s%s%s' %
+ (colors.normal,linesep,color))
+
+ # send text
+ owrite('%s%s%s' % (color,toktext,colors.normal))
+
+def main(argv=None):
+ """Run as a command-line script: colorize a python file or stdin using ANSI
+ color escapes and print to stdout.
+
+ Inputs:
+
+ - argv(None): a list of strings like sys.argv[1:] giving the command-line
+ arguments. If None, use sys.argv[1:].
+ """
+
+ usage_msg = """%prog [options] [filename]
+
+Colorize a python file or stdin using ANSI color escapes and print to stdout.
+If no filename is given, or if filename is -, read standard input."""
+
+ import optparse
+ parser = optparse.OptionParser(usage=usage_msg)
+ newopt = parser.add_option
+ newopt('-s','--scheme',metavar='NAME',dest='scheme_name',action='store',
+ choices=['Linux','LightBG','NoColor'],default=_scheme_default,
+ help="give the color scheme to use. Currently only 'Linux'\
+ (default) and 'LightBG' and 'NoColor' are implemented (give without\
+ quotes)")
+
+ opts,args = parser.parse_args(argv)
+
+ if len(args) > 1:
+ parser.error("you must give at most one filename.")
+
+ if len(args) == 0:
+ fname = '-' # no filename given; setup to read from stdin
+ else:
+ fname = args[0]
+
+ if fname == '-':
+ stream = sys.stdin
+ else:
+ try:
+ stream = open(fname)
+ except IOError as msg:
+ print(msg, file=sys.stderr)
+ sys.exit(1)
+
+ parser = Parser()
+
+ # we need nested try blocks because pre-2.5 python doesn't support unified
+ # try-except-finally
+ try:
+ try:
+ # write colorized version to stdout
+ parser.format(stream.read(),scheme=opts.scheme_name)
+ except IOError as msg:
+ # if user reads through a pager and quits, don't print traceback
+ if msg.args != (32,'Broken pipe'):
+ raise
+ finally:
+ if stream is not sys.stdin:
+ stream.close() # in case a non-handled exception happened above
+
+if __name__ == "__main__":
+ main()
diff --git a/contrib/python/ipython/py2/IPython/utils/_process_cli.py b/contrib/python/ipython/py2/IPython/utils/_process_cli.py
index a65decf3b6..a7b7b90b68 100644
--- a/contrib/python/ipython/py2/IPython/utils/_process_cli.py
+++ b/contrib/python/ipython/py2/IPython/utils/_process_cli.py
@@ -1,78 +1,78 @@
-"""cli-specific implementation of process utilities.
-
-cli - Common Language Infrastructure for IronPython. Code
- can run on any operating system. Check os.name for os-
- specific settings.
-
-This file is only meant to be imported by process.py, not by end-users.
-
-This file is largely untested. To become a full drop-in process
-interface for IronPython will probably require you to help fill
-in the details.
-"""
-
-# Import cli libraries:
-import clr
-import System
-
-# Import Python libraries:
-import os
-
-# Import IPython libraries:
-from IPython.utils import py3compat
-from ._process_common import arg_split
-
-def _find_cmd(cmd):
- """Find the full path to a command using which."""
- paths = System.Environment.GetEnvironmentVariable("PATH").Split(os.pathsep)
- for path in paths:
- filename = os.path.join(path, cmd)
- if System.IO.File.Exists(filename):
- return py3compat.bytes_to_str(filename)
- raise OSError("command %r not found" % cmd)
-
-def system(cmd):
- """
- system(cmd) should work in a cli environment on Mac OSX, Linux,
- and Windows
- """
- psi = System.Diagnostics.ProcessStartInfo(cmd)
- psi.RedirectStandardOutput = True
- psi.RedirectStandardError = True
- psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
- psi.UseShellExecute = False
- # Start up process:
- reg = System.Diagnostics.Process.Start(psi)
-
-def getoutput(cmd):
- """
- getoutput(cmd) should work in a cli environment on Mac OSX, Linux,
- and Windows
- """
- psi = System.Diagnostics.ProcessStartInfo(cmd)
- psi.RedirectStandardOutput = True
- psi.RedirectStandardError = True
- psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
- psi.UseShellExecute = False
- # Start up process:
- reg = System.Diagnostics.Process.Start(psi)
- myOutput = reg.StandardOutput
- output = myOutput.ReadToEnd()
- myError = reg.StandardError
- error = myError.ReadToEnd()
- return output
-
-def check_pid(pid):
- """
- Check if a process with the given PID (pid) exists
- """
- try:
- System.Diagnostics.Process.GetProcessById(pid)
- # process with given pid is running
- return True
- except System.InvalidOperationException:
- # process wasn't started by this object (but is running)
- return True
- except System.ArgumentException:
- # process with given pid isn't running
- return False
+"""cli-specific implementation of process utilities.
+
+cli - Common Language Infrastructure for IronPython. Code
+ can run on any operating system. Check os.name for os-
+ specific settings.
+
+This file is only meant to be imported by process.py, not by end-users.
+
+This file is largely untested. To become a full drop-in process
+interface for IronPython will probably require you to help fill
+in the details.
+"""
+
+# Import cli libraries:
+import clr
+import System
+
+# Import Python libraries:
+import os
+
+# Import IPython libraries:
+from IPython.utils import py3compat
+from ._process_common import arg_split
+
+def _find_cmd(cmd):
+ """Find the full path to a command using which."""
+ paths = System.Environment.GetEnvironmentVariable("PATH").Split(os.pathsep)
+ for path in paths:
+ filename = os.path.join(path, cmd)
+ if System.IO.File.Exists(filename):
+ return py3compat.bytes_to_str(filename)
+ raise OSError("command %r not found" % cmd)
+
+def system(cmd):
+ """
+ system(cmd) should work in a cli environment on Mac OSX, Linux,
+ and Windows
+ """
+ psi = System.Diagnostics.ProcessStartInfo(cmd)
+ psi.RedirectStandardOutput = True
+ psi.RedirectStandardError = True
+ psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
+ psi.UseShellExecute = False
+ # Start up process:
+ reg = System.Diagnostics.Process.Start(psi)
+
+def getoutput(cmd):
+ """
+ getoutput(cmd) should work in a cli environment on Mac OSX, Linux,
+ and Windows
+ """
+ psi = System.Diagnostics.ProcessStartInfo(cmd)
+ psi.RedirectStandardOutput = True
+ psi.RedirectStandardError = True
+ psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
+ psi.UseShellExecute = False
+ # Start up process:
+ reg = System.Diagnostics.Process.Start(psi)
+ myOutput = reg.StandardOutput
+ output = myOutput.ReadToEnd()
+ myError = reg.StandardError
+ error = myError.ReadToEnd()
+ return output
+
+def check_pid(pid):
+ """
+ Check if a process with the given PID (pid) exists
+ """
+ try:
+ System.Diagnostics.Process.GetProcessById(pid)
+ # process with given pid is running
+ return True
+ except System.InvalidOperationException:
+ # process wasn't started by this object (but is running)
+ return True
+ except System.ArgumentException:
+ # process with given pid isn't running
+ return False
diff --git a/contrib/python/ipython/py2/IPython/utils/_process_common.py b/contrib/python/ipython/py2/IPython/utils/_process_common.py
index 6851e41869..9ede30d3f8 100644
--- a/contrib/python/ipython/py2/IPython/utils/_process_common.py
+++ b/contrib/python/ipython/py2/IPython/utils/_process_common.py
@@ -1,75 +1,75 @@
-"""Common utilities for the various process_* implementations.
-
-This file is only meant to be imported by the platform-specific implementations
-of subprocess utilities, and it contains tools that are common to all of them.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2010-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-import subprocess
-import shlex
-import sys
+"""Common utilities for the various process_* implementations.
+
+This file is only meant to be imported by the platform-specific implementations
+of subprocess utilities, and it contains tools that are common to all of them.
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2010-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+import subprocess
+import shlex
+import sys
import os
-
-from IPython.utils import py3compat
-
-#-----------------------------------------------------------------------------
-# Function definitions
-#-----------------------------------------------------------------------------
-
-def read_no_interrupt(p):
- """Read from a pipe ignoring EINTR errors.
-
- This is necessary because when reading from pipes with GUI event loops
- running in the background, often interrupts are raised that stop the
- command from completing."""
- import errno
-
- try:
- return p.read()
- except IOError as err:
- if err.errno != errno.EINTR:
- raise
-
-
-def process_handler(cmd, callback, stderr=subprocess.PIPE):
- """Open a command in a shell subprocess and execute a callback.
-
- This function provides common scaffolding for creating subprocess.Popen()
- calls. It creates a Popen object and then calls the callback with it.
-
- Parameters
- ----------
- cmd : str or list
- A command to be executed by the system, using :class:`subprocess.Popen`.
- If a string is passed, it will be run in the system shell. If a list is
- passed, it will be used directly as arguments.
-
- callback : callable
- A one-argument function that will be called with the Popen object.
-
- stderr : file descriptor number, optional
- By default this is set to ``subprocess.PIPE``, but you can also pass the
- value ``subprocess.STDOUT`` to force the subprocess' stderr to go into
- the same file descriptor as its stdout. This is useful to read stdout
- and stderr combined in the order they are generated.
-
- Returns
- -------
- The return value of the provided callback is returned.
- """
- sys.stdout.flush()
- sys.stderr.flush()
- # On win32, close_fds can't be true when using pipes for stdin/out/err
- close_fds = sys.platform != 'win32'
+
+from IPython.utils import py3compat
+
+#-----------------------------------------------------------------------------
+# Function definitions
+#-----------------------------------------------------------------------------
+
+def read_no_interrupt(p):
+ """Read from a pipe ignoring EINTR errors.
+
+ This is necessary because when reading from pipes with GUI event loops
+ running in the background, often interrupts are raised that stop the
+ command from completing."""
+ import errno
+
+ try:
+ return p.read()
+ except IOError as err:
+ if err.errno != errno.EINTR:
+ raise
+
+
+def process_handler(cmd, callback, stderr=subprocess.PIPE):
+ """Open a command in a shell subprocess and execute a callback.
+
+ This function provides common scaffolding for creating subprocess.Popen()
+ calls. It creates a Popen object and then calls the callback with it.
+
+ Parameters
+ ----------
+ cmd : str or list
+ A command to be executed by the system, using :class:`subprocess.Popen`.
+ If a string is passed, it will be run in the system shell. If a list is
+ passed, it will be used directly as arguments.
+
+ callback : callable
+ A one-argument function that will be called with the Popen object.
+
+ stderr : file descriptor number, optional
+ By default this is set to ``subprocess.PIPE``, but you can also pass the
+ value ``subprocess.STDOUT`` to force the subprocess' stderr to go into
+ the same file descriptor as its stdout. This is useful to read stdout
+ and stderr combined in the order they are generated.
+
+ Returns
+ -------
+ The return value of the provided callback is returned.
+ """
+ sys.stdout.flush()
+ sys.stderr.flush()
+ # On win32, close_fds can't be true when using pipes for stdin/out/err
+ close_fds = sys.platform != 'win32'
# Determine if cmd should be run with system shell.
shell = isinstance(cmd, py3compat.string_types)
# On POSIX systems run shell commands with user-preferred shell.
@@ -78,146 +78,146 @@ def process_handler(cmd, callback, stderr=subprocess.PIPE):
executable = os.environ['SHELL']
p = subprocess.Popen(cmd, shell=shell,
executable=executable,
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=stderr,
- close_fds=close_fds)
-
- try:
- out = callback(p)
- except KeyboardInterrupt:
- print('^C')
- sys.stdout.flush()
- sys.stderr.flush()
- out = None
- finally:
- # Make really sure that we don't leave processes behind, in case the
- # call above raises an exception
- # We start by assuming the subprocess finished (to avoid NameErrors
- # later depending on the path taken)
- if p.returncode is None:
- try:
- p.terminate()
- p.poll()
- except OSError:
- pass
- # One last try on our way out
- if p.returncode is None:
- try:
- p.kill()
- except OSError:
- pass
-
- return out
-
-
-def getoutput(cmd):
- """Run a command and return its stdout/stderr as a string.
-
- Parameters
- ----------
- cmd : str or list
- A command to be executed in the system shell.
-
- Returns
- -------
- output : str
- A string containing the combination of stdout and stderr from the
- subprocess, in whatever order the subprocess originally wrote to its
- file descriptors (so the order of the information in this string is the
- correct order as would be seen if running the command in a terminal).
- """
- out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT)
- if out is None:
- return ''
- return py3compat.bytes_to_str(out)
-
-
-def getoutputerror(cmd):
- """Return (standard output, standard error) of executing cmd in a shell.
-
- Accepts the same arguments as os.system().
-
- Parameters
- ----------
- cmd : str or list
- A command to be executed in the system shell.
-
- Returns
- -------
- stdout : str
- stderr : str
- """
- return get_output_error_code(cmd)[:2]
-
-def get_output_error_code(cmd):
- """Return (standard output, standard error, return code) of executing cmd
- in a shell.
-
- Accepts the same arguments as os.system().
-
- Parameters
- ----------
- cmd : str or list
- A command to be executed in the system shell.
-
- Returns
- -------
- stdout : str
- stderr : str
- returncode: int
- """
-
- out_err, p = process_handler(cmd, lambda p: (p.communicate(), p))
- if out_err is None:
- return '', '', p.returncode
- out, err = out_err
- return py3compat.bytes_to_str(out), py3compat.bytes_to_str(err), p.returncode
-
-def arg_split(s, posix=False, strict=True):
- """Split a command line's arguments in a shell-like manner.
-
- This is a modified version of the standard library's shlex.split()
- function, but with a default of posix=False for splitting, so that quotes
- in inputs are respected.
-
- if strict=False, then any errors shlex.split would raise will result in the
- unparsed remainder being the last element of the list, rather than raising.
- This is because we sometimes use arg_split to parse things other than
- command-line args.
- """
-
- # Unfortunately, python's shlex module is buggy with unicode input:
- # http://bugs.python.org/issue1170
- # At least encoding the input when it's unicode seems to help, but there
- # may be more problems lurking. Apparently this is fixed in python3.
- is_unicode = False
- if (not py3compat.PY3) and isinstance(s, unicode):
- is_unicode = True
- s = s.encode('utf-8')
- lex = shlex.shlex(s, posix=posix)
- lex.whitespace_split = True
- # Extract tokens, ensuring that things like leaving open quotes
- # does not cause this to raise. This is important, because we
- # sometimes pass Python source through this (e.g. %timeit f(" ")),
- # and it shouldn't raise an exception.
- # It may be a bad idea to parse things that are not command-line args
- # through this function, but we do, so let's be safe about it.
- lex.commenters='' #fix for GH-1269
- tokens = []
- while True:
- try:
- tokens.append(next(lex))
- except StopIteration:
- break
- except ValueError:
- if strict:
- raise
- # couldn't parse, get remaining blob as last token
- tokens.append(lex.token)
- break
-
- if is_unicode:
- # Convert the tokens back to unicode.
- tokens = [x.decode('utf-8') for x in tokens]
- return tokens
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=stderr,
+ close_fds=close_fds)
+
+ try:
+ out = callback(p)
+ except KeyboardInterrupt:
+ print('^C')
+ sys.stdout.flush()
+ sys.stderr.flush()
+ out = None
+ finally:
+ # Make really sure that we don't leave processes behind, in case the
+ # call above raises an exception
+ # We start by assuming the subprocess finished (to avoid NameErrors
+ # later depending on the path taken)
+ if p.returncode is None:
+ try:
+ p.terminate()
+ p.poll()
+ except OSError:
+ pass
+ # One last try on our way out
+ if p.returncode is None:
+ try:
+ p.kill()
+ except OSError:
+ pass
+
+ return out
+
+
+def getoutput(cmd):
+ """Run a command and return its stdout/stderr as a string.
+
+ Parameters
+ ----------
+ cmd : str or list
+ A command to be executed in the system shell.
+
+ Returns
+ -------
+ output : str
+ A string containing the combination of stdout and stderr from the
+ subprocess, in whatever order the subprocess originally wrote to its
+ file descriptors (so the order of the information in this string is the
+ correct order as would be seen if running the command in a terminal).
+ """
+ out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT)
+ if out is None:
+ return ''
+ return py3compat.bytes_to_str(out)
+
+
+def getoutputerror(cmd):
+ """Return (standard output, standard error) of executing cmd in a shell.
+
+ Accepts the same arguments as os.system().
+
+ Parameters
+ ----------
+ cmd : str or list
+ A command to be executed in the system shell.
+
+ Returns
+ -------
+ stdout : str
+ stderr : str
+ """
+ return get_output_error_code(cmd)[:2]
+
+def get_output_error_code(cmd):
+ """Return (standard output, standard error, return code) of executing cmd
+ in a shell.
+
+ Accepts the same arguments as os.system().
+
+ Parameters
+ ----------
+ cmd : str or list
+ A command to be executed in the system shell.
+
+ Returns
+ -------
+ stdout : str
+ stderr : str
+ returncode: int
+ """
+
+ out_err, p = process_handler(cmd, lambda p: (p.communicate(), p))
+ if out_err is None:
+ return '', '', p.returncode
+ out, err = out_err
+ return py3compat.bytes_to_str(out), py3compat.bytes_to_str(err), p.returncode
+
+def arg_split(s, posix=False, strict=True):
+ """Split a command line's arguments in a shell-like manner.
+
+ This is a modified version of the standard library's shlex.split()
+ function, but with a default of posix=False for splitting, so that quotes
+ in inputs are respected.
+
+ if strict=False, then any errors shlex.split would raise will result in the
+ unparsed remainder being the last element of the list, rather than raising.
+ This is because we sometimes use arg_split to parse things other than
+ command-line args.
+ """
+
+ # Unfortunately, python's shlex module is buggy with unicode input:
+ # http://bugs.python.org/issue1170
+ # At least encoding the input when it's unicode seems to help, but there
+ # may be more problems lurking. Apparently this is fixed in python3.
+ is_unicode = False
+ if (not py3compat.PY3) and isinstance(s, unicode):
+ is_unicode = True
+ s = s.encode('utf-8')
+ lex = shlex.shlex(s, posix=posix)
+ lex.whitespace_split = True
+ # Extract tokens, ensuring that things like leaving open quotes
+ # does not cause this to raise. This is important, because we
+ # sometimes pass Python source through this (e.g. %timeit f(" ")),
+ # and it shouldn't raise an exception.
+ # It may be a bad idea to parse things that are not command-line args
+ # through this function, but we do, so let's be safe about it.
+ lex.commenters='' #fix for GH-1269
+ tokens = []
+ while True:
+ try:
+ tokens.append(next(lex))
+ except StopIteration:
+ break
+ except ValueError:
+ if strict:
+ raise
+ # couldn't parse, get remaining blob as last token
+ tokens.append(lex.token)
+ break
+
+ if is_unicode:
+ # Convert the tokens back to unicode.
+ tokens = [x.decode('utf-8') for x in tokens]
+ return tokens
diff --git a/contrib/python/ipython/py2/IPython/utils/_process_posix.py b/contrib/python/ipython/py2/IPython/utils/_process_posix.py
index 059e80c991..ac3a9a0507 100644
--- a/contrib/python/ipython/py2/IPython/utils/_process_posix.py
+++ b/contrib/python/ipython/py2/IPython/utils/_process_posix.py
@@ -1,225 +1,225 @@
-"""Posix-specific implementation of process utilities.
-
-This file is only meant to be imported by process.py, not by end-users.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2010-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-from __future__ import print_function
-
-# Stdlib
-import errno
-import os
-import subprocess as sp
-import sys
-
-import pexpect
-
-# Our own
-from ._process_common import getoutput, arg_split
-from IPython.utils import py3compat
-from IPython.utils.encoding import DEFAULT_ENCODING
-
-#-----------------------------------------------------------------------------
-# Function definitions
-#-----------------------------------------------------------------------------
-
-def _find_cmd(cmd):
- """Find the full path to a command using which."""
-
- path = sp.Popen(['/usr/bin/env', 'which', cmd],
- stdout=sp.PIPE, stderr=sp.PIPE).communicate()[0]
- return py3compat.bytes_to_str(path)
-
-
-class ProcessHandler(object):
- """Execute subprocesses under the control of pexpect.
- """
- # Timeout in seconds to wait on each reading of the subprocess' output.
- # This should not be set too low to avoid cpu overusage from our side,
- # since we read in a loop whose period is controlled by this timeout.
- read_timeout = 0.05
-
- # Timeout to give a process if we receive SIGINT, between sending the
- # SIGINT to the process and forcefully terminating it.
- terminate_timeout = 0.2
-
- # File object where stdout and stderr of the subprocess will be written
- logfile = None
-
- # Shell to call for subprocesses to execute
- _sh = None
-
- @property
- def sh(self):
- if self._sh is None:
- self._sh = pexpect.which('sh')
- if self._sh is None:
- raise OSError('"sh" shell not found')
-
- return self._sh
-
- def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None):
- """Arguments are used for pexpect calls."""
- self.read_timeout = (ProcessHandler.read_timeout if read_timeout is
- None else read_timeout)
- self.terminate_timeout = (ProcessHandler.terminate_timeout if
- terminate_timeout is None else
- terminate_timeout)
- self.logfile = sys.stdout if logfile is None else logfile
-
- def getoutput(self, cmd):
- """Run a command and return its stdout/stderr as a string.
-
- Parameters
- ----------
- cmd : str
- A command to be executed in the system shell.
-
- Returns
- -------
- output : str
- A string containing the combination of stdout and stderr from the
- subprocess, in whatever order the subprocess originally wrote to its
- file descriptors (so the order of the information in this string is the
- correct order as would be seen if running the command in a terminal).
- """
- try:
- return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n')
- except KeyboardInterrupt:
- print('^C', file=sys.stderr, end='')
-
- def getoutput_pexpect(self, cmd):
- """Run a command and return its stdout/stderr as a string.
-
- Parameters
- ----------
- cmd : str
- A command to be executed in the system shell.
-
- Returns
- -------
- output : str
- A string containing the combination of stdout and stderr from the
- subprocess, in whatever order the subprocess originally wrote to its
- file descriptors (so the order of the information in this string is the
- correct order as would be seen if running the command in a terminal).
- """
- try:
- return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n')
- except KeyboardInterrupt:
- print('^C', file=sys.stderr, end='')
-
- def system(self, cmd):
- """Execute a command in a subshell.
-
- Parameters
- ----------
- cmd : str
- A command to be executed in the system shell.
-
- Returns
- -------
- int : child's exitstatus
- """
- # Get likely encoding for the output.
- enc = DEFAULT_ENCODING
-
- # Patterns to match on the output, for pexpect. We read input and
- # allow either a short timeout or EOF
- patterns = [pexpect.TIMEOUT, pexpect.EOF]
- # the index of the EOF pattern in the list.
- # even though we know it's 1, this call means we don't have to worry if
- # we change the above list, and forget to change this value:
- EOF_index = patterns.index(pexpect.EOF)
- # The size of the output stored so far in the process output buffer.
- # Since pexpect only appends to this buffer, each time we print we
- # record how far we've printed, so that next time we only print *new*
- # content from the buffer.
- out_size = 0
- try:
- # Since we're not really searching the buffer for text patterns, we
- # can set pexpect's search window to be tiny and it won't matter.
- # We only search for the 'patterns' timeout or EOF, which aren't in
- # the text itself.
- #child = pexpect.spawn(pcmd, searchwindowsize=1)
- if hasattr(pexpect, 'spawnb'):
- child = pexpect.spawnb(self.sh, args=['-c', cmd]) # Pexpect-U
- else:
- child = pexpect.spawn(self.sh, args=['-c', cmd]) # Vanilla Pexpect
- flush = sys.stdout.flush
- while True:
- # res is the index of the pattern that caused the match, so we
- # know whether we've finished (if we matched EOF) or not
- res_idx = child.expect_list(patterns, self.read_timeout)
- print(child.before[out_size:].decode(enc, 'replace'), end='')
- flush()
- if res_idx==EOF_index:
- break
- # Update the pointer to what we've already printed
- out_size = len(child.before)
- except KeyboardInterrupt:
- # We need to send ^C to the process. The ascii code for '^C' is 3
- # (the character is known as ETX for 'End of Text', see
- # curses.ascii.ETX).
- child.sendline(chr(3))
- # Read and print any more output the program might produce on its
- # way out.
- try:
- out_size = len(child.before)
- child.expect_list(patterns, self.terminate_timeout)
- print(child.before[out_size:].decode(enc, 'replace'), end='')
- sys.stdout.flush()
- except KeyboardInterrupt:
- # Impatient users tend to type it multiple times
- pass
- finally:
- # Ensure the subprocess really is terminated
- child.terminate(force=True)
- # add isalive check, to ensure exitstatus is set:
- child.isalive()
-
- # We follow the subprocess pattern, returning either the exit status
- # as a positive number, or the terminating signal as a negative
- # number.
- # on Linux, sh returns 128+n for signals terminating child processes on Linux
- # on BSD (OS X), the signal code is set instead
- if child.exitstatus is None:
- # on WIFSIGNALED, pexpect sets signalstatus, leaving exitstatus=None
- if child.signalstatus is None:
- # this condition may never occur,
- # but let's be certain we always return an integer.
- return 0
- return -child.signalstatus
- if child.exitstatus > 128:
- return -(child.exitstatus - 128)
- return child.exitstatus
-
-
-# Make system() with a functional interface for outside use. Note that we use
-# getoutput() from the _common utils, which is built on top of popen(). Using
-# pexpect to get subprocess output produces difficult to parse output, since
-# programs think they are talking to a tty and produce highly formatted output
-# (ls is a good example) that makes them hard.
-system = ProcessHandler().system
-
-def check_pid(pid):
- try:
- os.kill(pid, 0)
- except OSError as err:
- if err.errno == errno.ESRCH:
- return False
- elif err.errno == errno.EPERM:
- # Don't have permission to signal the process - probably means it exists
- return True
- raise
- else:
- return True
+"""Posix-specific implementation of process utilities.
+
+This file is only meant to be imported by process.py, not by end-users.
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2010-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+from __future__ import print_function
+
+# Stdlib
+import errno
+import os
+import subprocess as sp
+import sys
+
+import pexpect
+
+# Our own
+from ._process_common import getoutput, arg_split
+from IPython.utils import py3compat
+from IPython.utils.encoding import DEFAULT_ENCODING
+
+#-----------------------------------------------------------------------------
+# Function definitions
+#-----------------------------------------------------------------------------
+
+def _find_cmd(cmd):
+ """Find the full path to a command using which."""
+
+ path = sp.Popen(['/usr/bin/env', 'which', cmd],
+ stdout=sp.PIPE, stderr=sp.PIPE).communicate()[0]
+ return py3compat.bytes_to_str(path)
+
+
+class ProcessHandler(object):
+ """Execute subprocesses under the control of pexpect.
+ """
+ # Timeout in seconds to wait on each reading of the subprocess' output.
+ # This should not be set too low to avoid cpu overusage from our side,
+ # since we read in a loop whose period is controlled by this timeout.
+ read_timeout = 0.05
+
+ # Timeout to give a process if we receive SIGINT, between sending the
+ # SIGINT to the process and forcefully terminating it.
+ terminate_timeout = 0.2
+
+ # File object where stdout and stderr of the subprocess will be written
+ logfile = None
+
+ # Shell to call for subprocesses to execute
+ _sh = None
+
+ @property
+ def sh(self):
+ if self._sh is None:
+ self._sh = pexpect.which('sh')
+ if self._sh is None:
+ raise OSError('"sh" shell not found')
+
+ return self._sh
+
+ def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None):
+ """Arguments are used for pexpect calls."""
+ self.read_timeout = (ProcessHandler.read_timeout if read_timeout is
+ None else read_timeout)
+ self.terminate_timeout = (ProcessHandler.terminate_timeout if
+ terminate_timeout is None else
+ terminate_timeout)
+ self.logfile = sys.stdout if logfile is None else logfile
+
+ def getoutput(self, cmd):
+ """Run a command and return its stdout/stderr as a string.
+
+ Parameters
+ ----------
+ cmd : str
+ A command to be executed in the system shell.
+
+ Returns
+ -------
+ output : str
+ A string containing the combination of stdout and stderr from the
+ subprocess, in whatever order the subprocess originally wrote to its
+ file descriptors (so the order of the information in this string is the
+ correct order as would be seen if running the command in a terminal).
+ """
+ try:
+ return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n')
+ except KeyboardInterrupt:
+ print('^C', file=sys.stderr, end='')
+
+ def getoutput_pexpect(self, cmd):
+ """Run a command and return its stdout/stderr as a string.
+
+ Parameters
+ ----------
+ cmd : str
+ A command to be executed in the system shell.
+
+ Returns
+ -------
+ output : str
+ A string containing the combination of stdout and stderr from the
+ subprocess, in whatever order the subprocess originally wrote to its
+ file descriptors (so the order of the information in this string is the
+ correct order as would be seen if running the command in a terminal).
+ """
+ try:
+ return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n')
+ except KeyboardInterrupt:
+ print('^C', file=sys.stderr, end='')
+
+ def system(self, cmd):
+ """Execute a command in a subshell.
+
+ Parameters
+ ----------
+ cmd : str
+ A command to be executed in the system shell.
+
+ Returns
+ -------
+ int : child's exitstatus
+ """
+ # Get likely encoding for the output.
+ enc = DEFAULT_ENCODING
+
+ # Patterns to match on the output, for pexpect. We read input and
+ # allow either a short timeout or EOF
+ patterns = [pexpect.TIMEOUT, pexpect.EOF]
+ # the index of the EOF pattern in the list.
+ # even though we know it's 1, this call means we don't have to worry if
+ # we change the above list, and forget to change this value:
+ EOF_index = patterns.index(pexpect.EOF)
+ # The size of the output stored so far in the process output buffer.
+ # Since pexpect only appends to this buffer, each time we print we
+ # record how far we've printed, so that next time we only print *new*
+ # content from the buffer.
+ out_size = 0
+ try:
+ # Since we're not really searching the buffer for text patterns, we
+ # can set pexpect's search window to be tiny and it won't matter.
+ # We only search for the 'patterns' timeout or EOF, which aren't in
+ # the text itself.
+ #child = pexpect.spawn(pcmd, searchwindowsize=1)
+ if hasattr(pexpect, 'spawnb'):
+ child = pexpect.spawnb(self.sh, args=['-c', cmd]) # Pexpect-U
+ else:
+ child = pexpect.spawn(self.sh, args=['-c', cmd]) # Vanilla Pexpect
+ flush = sys.stdout.flush
+ while True:
+ # res is the index of the pattern that caused the match, so we
+ # know whether we've finished (if we matched EOF) or not
+ res_idx = child.expect_list(patterns, self.read_timeout)
+ print(child.before[out_size:].decode(enc, 'replace'), end='')
+ flush()
+ if res_idx==EOF_index:
+ break
+ # Update the pointer to what we've already printed
+ out_size = len(child.before)
+ except KeyboardInterrupt:
+ # We need to send ^C to the process. The ascii code for '^C' is 3
+ # (the character is known as ETX for 'End of Text', see
+ # curses.ascii.ETX).
+ child.sendline(chr(3))
+ # Read and print any more output the program might produce on its
+ # way out.
+ try:
+ out_size = len(child.before)
+ child.expect_list(patterns, self.terminate_timeout)
+ print(child.before[out_size:].decode(enc, 'replace'), end='')
+ sys.stdout.flush()
+ except KeyboardInterrupt:
+ # Impatient users tend to type it multiple times
+ pass
+ finally:
+ # Ensure the subprocess really is terminated
+ child.terminate(force=True)
+ # add isalive check, to ensure exitstatus is set:
+ child.isalive()
+
+ # We follow the subprocess pattern, returning either the exit status
+ # as a positive number, or the terminating signal as a negative
+ # number.
+ # on Linux, sh returns 128+n for signals terminating child processes on Linux
+ # on BSD (OS X), the signal code is set instead
+ if child.exitstatus is None:
+ # on WIFSIGNALED, pexpect sets signalstatus, leaving exitstatus=None
+ if child.signalstatus is None:
+ # this condition may never occur,
+ # but let's be certain we always return an integer.
+ return 0
+ return -child.signalstatus
+ if child.exitstatus > 128:
+ return -(child.exitstatus - 128)
+ return child.exitstatus
+
+
+# Make system() with a functional interface for outside use. Note that we use
+# getoutput() from the _common utils, which is built on top of popen(). Using
+# pexpect to get subprocess output produces difficult to parse output, since
+# programs think they are talking to a tty and produce highly formatted output
+# (ls is a good example) that makes them hard.
+system = ProcessHandler().system
+
+def check_pid(pid):
+ try:
+ os.kill(pid, 0)
+ except OSError as err:
+ if err.errno == errno.ESRCH:
+ return False
+ elif err.errno == errno.EPERM:
+ # Don't have permission to signal the process - probably means it exists
+ return True
+ raise
+ else:
+ return True
diff --git a/contrib/python/ipython/py2/IPython/utils/_process_win32.py b/contrib/python/ipython/py2/IPython/utils/_process_win32.py
index 6d7d0f4197..3ac59b2c29 100644
--- a/contrib/python/ipython/py2/IPython/utils/_process_win32.py
+++ b/contrib/python/ipython/py2/IPython/utils/_process_win32.py
@@ -1,192 +1,192 @@
-"""Windows-specific implementation of process utilities.
-
-This file is only meant to be imported by process.py, not by end-users.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2010-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-from __future__ import print_function
-
-# stdlib
-import os
-import sys
-import ctypes
-
-from ctypes import c_int, POINTER
-from ctypes.wintypes import LPCWSTR, HLOCAL
-from subprocess import STDOUT
-
-# our own imports
-from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split
-from . import py3compat
-from .encoding import DEFAULT_ENCODING
-
-#-----------------------------------------------------------------------------
-# Function definitions
-#-----------------------------------------------------------------------------
-
-class AvoidUNCPath(object):
- """A context manager to protect command execution from UNC paths.
-
- In the Win32 API, commands can't be invoked with the cwd being a UNC path.
- This context manager temporarily changes directory to the 'C:' drive on
- entering, and restores the original working directory on exit.
-
- The context manager returns the starting working directory *if* it made a
- change and None otherwise, so that users can apply the necessary adjustment
- to their system calls in the event of a change.
-
- Examples
- --------
- ::
- cmd = 'dir'
- with AvoidUNCPath() as path:
- if path is not None:
- cmd = '"pushd %s &&"%s' % (path, cmd)
- os.system(cmd)
- """
- def __enter__(self):
- self.path = py3compat.getcwd()
- self.is_unc_path = self.path.startswith(r"\\")
- if self.is_unc_path:
- # change to c drive (as cmd.exe cannot handle UNC addresses)
- os.chdir("C:")
- return self.path
- else:
- # We return None to signal that there was no change in the working
- # directory
- return None
-
- def __exit__(self, exc_type, exc_value, traceback):
- if self.is_unc_path:
- os.chdir(self.path)
-
-
-def _find_cmd(cmd):
- """Find the full path to a .bat or .exe using the win32api module."""
- try:
- from win32api import SearchPath
- except ImportError:
- raise ImportError('you need to have pywin32 installed for this to work')
- else:
- PATH = os.environ['PATH']
- extensions = ['.exe', '.com', '.bat', '.py']
- path = None
- for ext in extensions:
- try:
- path = SearchPath(PATH, cmd, ext)[0]
- except:
- pass
- if path is None:
- raise OSError("command %r not found" % cmd)
- else:
- return path
-
-
-def _system_body(p):
- """Callback for _system."""
- enc = DEFAULT_ENCODING
- for line in read_no_interrupt(p.stdout).splitlines():
- line = line.decode(enc, 'replace')
- print(line, file=sys.stdout)
- for line in read_no_interrupt(p.stderr).splitlines():
- line = line.decode(enc, 'replace')
- print(line, file=sys.stderr)
-
- # Wait to finish for returncode
- return p.wait()
-
-
-def system(cmd):
- """Win32 version of os.system() that works with network shares.
-
- Note that this implementation returns None, as meant for use in IPython.
-
- Parameters
- ----------
- cmd : str or list
- A command to be executed in the system shell.
-
- Returns
- -------
- None : we explicitly do NOT return the subprocess status code, as this
- utility is meant to be used extensively in IPython, where any return value
- would trigger :func:`sys.displayhook` calls.
- """
- # The controller provides interactivity with both
- # stdin and stdout
- #import _process_win32_controller
- #_process_win32_controller.system(cmd)
-
- with AvoidUNCPath() as path:
- if path is not None:
- cmd = '"pushd %s &&"%s' % (path, cmd)
- return process_handler(cmd, _system_body)
-
-def getoutput(cmd):
- """Return standard output of executing cmd in a shell.
-
- Accepts the same arguments as os.system().
-
- Parameters
- ----------
- cmd : str or list
- A command to be executed in the system shell.
-
- Returns
- -------
- stdout : str
- """
-
- with AvoidUNCPath() as path:
- if path is not None:
- cmd = '"pushd %s &&"%s' % (path, cmd)
- out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT)
-
- if out is None:
- out = b''
- return py3compat.bytes_to_str(out)
-
-try:
- CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
- CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)]
- CommandLineToArgvW.restype = POINTER(LPCWSTR)
- LocalFree = ctypes.windll.kernel32.LocalFree
- LocalFree.res_type = HLOCAL
- LocalFree.arg_types = [HLOCAL]
-
- def arg_split(commandline, posix=False, strict=True):
- """Split a command line's arguments in a shell-like manner.
-
- This is a special version for windows that use a ctypes call to CommandLineToArgvW
- to do the argv splitting. The posix paramter is ignored.
-
- If strict=False, process_common.arg_split(...strict=False) is used instead.
- """
- #CommandLineToArgvW returns path to executable if called with empty string.
- if commandline.strip() == "":
- return []
- if not strict:
- # not really a cl-arg, fallback on _process_common
- return py_arg_split(commandline, posix=posix, strict=strict)
- argvn = c_int()
- result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn))
- result_array_type = LPCWSTR * argvn.value
- result = [arg for arg in result_array_type.from_address(ctypes.addressof(result_pointer.contents))]
- retval = LocalFree(result_pointer)
- return result
-except AttributeError:
- arg_split = py_arg_split
-
-def check_pid(pid):
- # OpenProcess returns 0 if no such process (of ours) exists
- # positive int otherwise
- return bool(ctypes.windll.kernel32.OpenProcess(1,0,pid))
+"""Windows-specific implementation of process utilities.
+
+This file is only meant to be imported by process.py, not by end-users.
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2010-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+from __future__ import print_function
+
+# stdlib
+import os
+import sys
+import ctypes
+
+from ctypes import c_int, POINTER
+from ctypes.wintypes import LPCWSTR, HLOCAL
+from subprocess import STDOUT
+
+# our own imports
+from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split
+from . import py3compat
+from .encoding import DEFAULT_ENCODING
+
+#-----------------------------------------------------------------------------
+# Function definitions
+#-----------------------------------------------------------------------------
+
+class AvoidUNCPath(object):
+ """A context manager to protect command execution from UNC paths.
+
+ In the Win32 API, commands can't be invoked with the cwd being a UNC path.
+ This context manager temporarily changes directory to the 'C:' drive on
+ entering, and restores the original working directory on exit.
+
+ The context manager returns the starting working directory *if* it made a
+ change and None otherwise, so that users can apply the necessary adjustment
+ to their system calls in the event of a change.
+
+ Examples
+ --------
+ ::
+ cmd = 'dir'
+ with AvoidUNCPath() as path:
+ if path is not None:
+ cmd = '"pushd %s &&"%s' % (path, cmd)
+ os.system(cmd)
+ """
+ def __enter__(self):
+ self.path = py3compat.getcwd()
+ self.is_unc_path = self.path.startswith(r"\\")
+ if self.is_unc_path:
+ # change to c drive (as cmd.exe cannot handle UNC addresses)
+ os.chdir("C:")
+ return self.path
+ else:
+ # We return None to signal that there was no change in the working
+ # directory
+ return None
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ if self.is_unc_path:
+ os.chdir(self.path)
+
+
+def _find_cmd(cmd):
+ """Find the full path to a .bat or .exe using the win32api module."""
+ try:
+ from win32api import SearchPath
+ except ImportError:
+ raise ImportError('you need to have pywin32 installed for this to work')
+ else:
+ PATH = os.environ['PATH']
+ extensions = ['.exe', '.com', '.bat', '.py']
+ path = None
+ for ext in extensions:
+ try:
+ path = SearchPath(PATH, cmd, ext)[0]
+ except:
+ pass
+ if path is None:
+ raise OSError("command %r not found" % cmd)
+ else:
+ return path
+
+
+def _system_body(p):
+ """Callback for _system."""
+ enc = DEFAULT_ENCODING
+ for line in read_no_interrupt(p.stdout).splitlines():
+ line = line.decode(enc, 'replace')
+ print(line, file=sys.stdout)
+ for line in read_no_interrupt(p.stderr).splitlines():
+ line = line.decode(enc, 'replace')
+ print(line, file=sys.stderr)
+
+ # Wait to finish for returncode
+ return p.wait()
+
+
+def system(cmd):
+ """Win32 version of os.system() that works with network shares.
+
+ Note that this implementation returns None, as meant for use in IPython.
+
+ Parameters
+ ----------
+ cmd : str or list
+ A command to be executed in the system shell.
+
+ Returns
+ -------
+ None : we explicitly do NOT return the subprocess status code, as this
+ utility is meant to be used extensively in IPython, where any return value
+ would trigger :func:`sys.displayhook` calls.
+ """
+ # The controller provides interactivity with both
+ # stdin and stdout
+ #import _process_win32_controller
+ #_process_win32_controller.system(cmd)
+
+ with AvoidUNCPath() as path:
+ if path is not None:
+ cmd = '"pushd %s &&"%s' % (path, cmd)
+ return process_handler(cmd, _system_body)
+
+def getoutput(cmd):
+ """Return standard output of executing cmd in a shell.
+
+ Accepts the same arguments as os.system().
+
+ Parameters
+ ----------
+ cmd : str or list
+ A command to be executed in the system shell.
+
+ Returns
+ -------
+ stdout : str
+ """
+
+ with AvoidUNCPath() as path:
+ if path is not None:
+ cmd = '"pushd %s &&"%s' % (path, cmd)
+ out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT)
+
+ if out is None:
+ out = b''
+ return py3compat.bytes_to_str(out)
+
+try:
+ CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
+ CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)]
+ CommandLineToArgvW.restype = POINTER(LPCWSTR)
+ LocalFree = ctypes.windll.kernel32.LocalFree
+ LocalFree.res_type = HLOCAL
+ LocalFree.arg_types = [HLOCAL]
+
+ def arg_split(commandline, posix=False, strict=True):
+ """Split a command line's arguments in a shell-like manner.
+
+ This is a special version for windows that use a ctypes call to CommandLineToArgvW
+ to do the argv splitting. The posix paramter is ignored.
+
+ If strict=False, process_common.arg_split(...strict=False) is used instead.
+ """
+ #CommandLineToArgvW returns path to executable if called with empty string.
+ if commandline.strip() == "":
+ return []
+ if not strict:
+ # not really a cl-arg, fallback on _process_common
+ return py_arg_split(commandline, posix=posix, strict=strict)
+ argvn = c_int()
+ result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn))
+ result_array_type = LPCWSTR * argvn.value
+ result = [arg for arg in result_array_type.from_address(ctypes.addressof(result_pointer.contents))]
+ retval = LocalFree(result_pointer)
+ return result
+except AttributeError:
+ arg_split = py_arg_split
+
+def check_pid(pid):
+ # OpenProcess returns 0 if no such process (of ours) exists
+ # positive int otherwise
+ return bool(ctypes.windll.kernel32.OpenProcess(1,0,pid))
diff --git a/contrib/python/ipython/py2/IPython/utils/_process_win32_controller.py b/contrib/python/ipython/py2/IPython/utils/_process_win32_controller.py
index 607e411916..555eec23b3 100644
--- a/contrib/python/ipython/py2/IPython/utils/_process_win32_controller.py
+++ b/contrib/python/ipython/py2/IPython/utils/_process_win32_controller.py
@@ -1,577 +1,577 @@
-"""Windows-specific implementation of process utilities with direct WinAPI.
-
-This file is meant to be used by process.py
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2010-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-from __future__ import print_function
-
-# stdlib
-import os, sys, threading
-import ctypes, msvcrt
-
-# local imports
-from . import py3compat
-
-# Win32 API types needed for the API calls
-from ctypes import POINTER
-from ctypes.wintypes import HANDLE, HLOCAL, LPVOID, WORD, DWORD, BOOL, \
- ULONG, LPCWSTR
-LPDWORD = POINTER(DWORD)
-LPHANDLE = POINTER(HANDLE)
-ULONG_PTR = POINTER(ULONG)
-class SECURITY_ATTRIBUTES(ctypes.Structure):
- _fields_ = [("nLength", DWORD),
- ("lpSecurityDescriptor", LPVOID),
- ("bInheritHandle", BOOL)]
-LPSECURITY_ATTRIBUTES = POINTER(SECURITY_ATTRIBUTES)
-class STARTUPINFO(ctypes.Structure):
- _fields_ = [("cb", DWORD),
- ("lpReserved", LPCWSTR),
- ("lpDesktop", LPCWSTR),
- ("lpTitle", LPCWSTR),
- ("dwX", DWORD),
- ("dwY", DWORD),
- ("dwXSize", DWORD),
- ("dwYSize", DWORD),
- ("dwXCountChars", DWORD),
- ("dwYCountChars", DWORD),
- ("dwFillAttribute", DWORD),
- ("dwFlags", DWORD),
- ("wShowWindow", WORD),
- ("cbReserved2", WORD),
- ("lpReserved2", LPVOID),
- ("hStdInput", HANDLE),
- ("hStdOutput", HANDLE),
- ("hStdError", HANDLE)]
-LPSTARTUPINFO = POINTER(STARTUPINFO)
-class PROCESS_INFORMATION(ctypes.Structure):
- _fields_ = [("hProcess", HANDLE),
- ("hThread", HANDLE),
- ("dwProcessId", DWORD),
- ("dwThreadId", DWORD)]
-LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION)
-
-# Win32 API constants needed
-ERROR_HANDLE_EOF = 38
-ERROR_BROKEN_PIPE = 109
-ERROR_NO_DATA = 232
-HANDLE_FLAG_INHERIT = 0x0001
-STARTF_USESTDHANDLES = 0x0100
-CREATE_SUSPENDED = 0x0004
-CREATE_NEW_CONSOLE = 0x0010
-CREATE_NO_WINDOW = 0x08000000
-STILL_ACTIVE = 259
-WAIT_TIMEOUT = 0x0102
-WAIT_FAILED = 0xFFFFFFFF
-INFINITE = 0xFFFFFFFF
-DUPLICATE_SAME_ACCESS = 0x00000002
-ENABLE_ECHO_INPUT = 0x0004
-ENABLE_LINE_INPUT = 0x0002
-ENABLE_PROCESSED_INPUT = 0x0001
-
-# Win32 API functions needed
-GetLastError = ctypes.windll.kernel32.GetLastError
-GetLastError.argtypes = []
-GetLastError.restype = DWORD
-
-CreateFile = ctypes.windll.kernel32.CreateFileW
-CreateFile.argtypes = [LPCWSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE]
-CreateFile.restype = HANDLE
-
-CreatePipe = ctypes.windll.kernel32.CreatePipe
-CreatePipe.argtypes = [POINTER(HANDLE), POINTER(HANDLE),
- LPSECURITY_ATTRIBUTES, DWORD]
-CreatePipe.restype = BOOL
-
-CreateProcess = ctypes.windll.kernel32.CreateProcessW
-CreateProcess.argtypes = [LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES,
- LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPCWSTR, LPSTARTUPINFO,
- LPPROCESS_INFORMATION]
-CreateProcess.restype = BOOL
-
-GetExitCodeProcess = ctypes.windll.kernel32.GetExitCodeProcess
-GetExitCodeProcess.argtypes = [HANDLE, LPDWORD]
-GetExitCodeProcess.restype = BOOL
-
-GetCurrentProcess = ctypes.windll.kernel32.GetCurrentProcess
-GetCurrentProcess.argtypes = []
-GetCurrentProcess.restype = HANDLE
-
-ResumeThread = ctypes.windll.kernel32.ResumeThread
-ResumeThread.argtypes = [HANDLE]
-ResumeThread.restype = DWORD
-
-ReadFile = ctypes.windll.kernel32.ReadFile
-ReadFile.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD, LPVOID]
-ReadFile.restype = BOOL
-
-WriteFile = ctypes.windll.kernel32.WriteFile
-WriteFile.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD, LPVOID]
-WriteFile.restype = BOOL
-
-GetConsoleMode = ctypes.windll.kernel32.GetConsoleMode
-GetConsoleMode.argtypes = [HANDLE, LPDWORD]
-GetConsoleMode.restype = BOOL
-
-SetConsoleMode = ctypes.windll.kernel32.SetConsoleMode
-SetConsoleMode.argtypes = [HANDLE, DWORD]
-SetConsoleMode.restype = BOOL
-
-FlushConsoleInputBuffer = ctypes.windll.kernel32.FlushConsoleInputBuffer
-FlushConsoleInputBuffer.argtypes = [HANDLE]
-FlushConsoleInputBuffer.restype = BOOL
-
-WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject
-WaitForSingleObject.argtypes = [HANDLE, DWORD]
-WaitForSingleObject.restype = DWORD
-
-DuplicateHandle = ctypes.windll.kernel32.DuplicateHandle
-DuplicateHandle.argtypes = [HANDLE, HANDLE, HANDLE, LPHANDLE,
- DWORD, BOOL, DWORD]
-DuplicateHandle.restype = BOOL
-
-SetHandleInformation = ctypes.windll.kernel32.SetHandleInformation
-SetHandleInformation.argtypes = [HANDLE, DWORD, DWORD]
-SetHandleInformation.restype = BOOL
-
-CloseHandle = ctypes.windll.kernel32.CloseHandle
-CloseHandle.argtypes = [HANDLE]
-CloseHandle.restype = BOOL
-
-CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
-CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(ctypes.c_int)]
-CommandLineToArgvW.restype = POINTER(LPCWSTR)
-
-LocalFree = ctypes.windll.kernel32.LocalFree
-LocalFree.argtypes = [HLOCAL]
-LocalFree.restype = HLOCAL
-
-class AvoidUNCPath(object):
- """A context manager to protect command execution from UNC paths.
-
- In the Win32 API, commands can't be invoked with the cwd being a UNC path.
- This context manager temporarily changes directory to the 'C:' drive on
- entering, and restores the original working directory on exit.
-
- The context manager returns the starting working directory *if* it made a
- change and None otherwise, so that users can apply the necessary adjustment
- to their system calls in the event of a change.
-
- Examples
- --------
- ::
- cmd = 'dir'
- with AvoidUNCPath() as path:
- if path is not None:
- cmd = '"pushd %s &&"%s' % (path, cmd)
- os.system(cmd)
- """
- def __enter__(self):
- self.path = py3compat.getcwd()
- self.is_unc_path = self.path.startswith(r"\\")
- if self.is_unc_path:
- # change to c drive (as cmd.exe cannot handle UNC addresses)
- os.chdir("C:")
- return self.path
- else:
- # We return None to signal that there was no change in the working
- # directory
- return None
-
- def __exit__(self, exc_type, exc_value, traceback):
- if self.is_unc_path:
- os.chdir(self.path)
-
-
-class Win32ShellCommandController(object):
- """Runs a shell command in a 'with' context.
-
- This implementation is Win32-specific.
-
- Example:
- # Runs the command interactively with default console stdin/stdout
- with ShellCommandController('python -i') as scc:
- scc.run()
-
- # Runs the command using the provided functions for stdin/stdout
- def my_stdout_func(s):
- # print or save the string 's'
- write_to_stdout(s)
- def my_stdin_func():
- # If input is available, return it as a string.
- if input_available():
- return get_input()
- # If no input available, return None after a short delay to
- # keep from blocking.
- else:
- time.sleep(0.01)
- return None
-
- with ShellCommandController('python -i') as scc:
- scc.run(my_stdout_func, my_stdin_func)
- """
-
- def __init__(self, cmd, mergeout = True):
- """Initializes the shell command controller.
-
- The cmd is the program to execute, and mergeout is
- whether to blend stdout and stderr into one output
- in stdout. Merging them together in this fashion more
- reliably keeps stdout and stderr in the correct order
- especially for interactive shell usage.
- """
- self.cmd = cmd
- self.mergeout = mergeout
-
- def __enter__(self):
- cmd = self.cmd
- mergeout = self.mergeout
-
- self.hstdout, self.hstdin, self.hstderr = None, None, None
- self.piProcInfo = None
- try:
- p_hstdout, c_hstdout, p_hstderr, \
- c_hstderr, p_hstdin, c_hstdin = [None]*6
-
- # SECURITY_ATTRIBUTES with inherit handle set to True
- saAttr = SECURITY_ATTRIBUTES()
- saAttr.nLength = ctypes.sizeof(saAttr)
- saAttr.bInheritHandle = True
- saAttr.lpSecurityDescriptor = None
-
- def create_pipe(uninherit):
- """Creates a Windows pipe, which consists of two handles.
-
- The 'uninherit' parameter controls which handle is not
- inherited by the child process.
- """
- handles = HANDLE(), HANDLE()
- if not CreatePipe(ctypes.byref(handles[0]),
- ctypes.byref(handles[1]), ctypes.byref(saAttr), 0):
- raise ctypes.WinError()
- if not SetHandleInformation(handles[uninherit],
- HANDLE_FLAG_INHERIT, 0):
- raise ctypes.WinError()
- return handles[0].value, handles[1].value
-
- p_hstdout, c_hstdout = create_pipe(uninherit=0)
- # 'mergeout' signals that stdout and stderr should be merged.
- # We do that by using one pipe for both of them.
- if mergeout:
- c_hstderr = HANDLE()
- if not DuplicateHandle(GetCurrentProcess(), c_hstdout,
- GetCurrentProcess(), ctypes.byref(c_hstderr),
- 0, True, DUPLICATE_SAME_ACCESS):
- raise ctypes.WinError()
- else:
- p_hstderr, c_hstderr = create_pipe(uninherit=0)
- c_hstdin, p_hstdin = create_pipe(uninherit=1)
-
- # Create the process object
- piProcInfo = PROCESS_INFORMATION()
- siStartInfo = STARTUPINFO()
- siStartInfo.cb = ctypes.sizeof(siStartInfo)
- siStartInfo.hStdInput = c_hstdin
- siStartInfo.hStdOutput = c_hstdout
- siStartInfo.hStdError = c_hstderr
- siStartInfo.dwFlags = STARTF_USESTDHANDLES
- dwCreationFlags = CREATE_SUSPENDED | CREATE_NO_WINDOW # | CREATE_NEW_CONSOLE
-
- if not CreateProcess(None,
- u"cmd.exe /c " + cmd,
- None, None, True, dwCreationFlags,
- None, None, ctypes.byref(siStartInfo),
- ctypes.byref(piProcInfo)):
- raise ctypes.WinError()
-
- # Close this process's versions of the child handles
- CloseHandle(c_hstdin)
- c_hstdin = None
- CloseHandle(c_hstdout)
- c_hstdout = None
- if c_hstderr is not None:
- CloseHandle(c_hstderr)
- c_hstderr = None
-
- # Transfer ownership of the parent handles to the object
- self.hstdin = p_hstdin
- p_hstdin = None
- self.hstdout = p_hstdout
- p_hstdout = None
- if not mergeout:
- self.hstderr = p_hstderr
- p_hstderr = None
- self.piProcInfo = piProcInfo
-
- finally:
- if p_hstdin:
- CloseHandle(p_hstdin)
- if c_hstdin:
- CloseHandle(c_hstdin)
- if p_hstdout:
- CloseHandle(p_hstdout)
- if c_hstdout:
- CloseHandle(c_hstdout)
- if p_hstderr:
- CloseHandle(p_hstderr)
- if c_hstderr:
- CloseHandle(c_hstderr)
-
- return self
-
- def _stdin_thread(self, handle, hprocess, func, stdout_func):
- exitCode = DWORD()
- bytesWritten = DWORD(0)
- while True:
- #print("stdin thread loop start")
- # Get the input string (may be bytes or unicode)
- data = func()
-
- # None signals to poll whether the process has exited
- if data is None:
- #print("checking for process completion")
- if not GetExitCodeProcess(hprocess, ctypes.byref(exitCode)):
- raise ctypes.WinError()
- if exitCode.value != STILL_ACTIVE:
- return
- # TESTING: Does zero-sized writefile help?
- if not WriteFile(handle, "", 0,
- ctypes.byref(bytesWritten), None):
- raise ctypes.WinError()
- continue
- #print("\nGot str %s\n" % repr(data), file=sys.stderr)
-
- # Encode the string to the console encoding
- if isinstance(data, unicode): #FIXME: Python3
- data = data.encode('utf_8')
-
- # What we have now must be a string of bytes
- if not isinstance(data, str): #FIXME: Python3
- raise RuntimeError("internal stdin function string error")
-
- # An empty string signals EOF
- if len(data) == 0:
- return
-
- # In a windows console, sometimes the input is echoed,
- # but sometimes not. How do we determine when to do this?
- stdout_func(data)
- # WriteFile may not accept all the data at once.
- # Loop until everything is processed
- while len(data) != 0:
- #print("Calling writefile")
- if not WriteFile(handle, data, len(data),
- ctypes.byref(bytesWritten), None):
- # This occurs at exit
- if GetLastError() == ERROR_NO_DATA:
- return
- raise ctypes.WinError()
- #print("Called writefile")
- data = data[bytesWritten.value:]
-
- def _stdout_thread(self, handle, func):
- # Allocate the output buffer
- data = ctypes.create_string_buffer(4096)
- while True:
- bytesRead = DWORD(0)
- if not ReadFile(handle, data, 4096,
- ctypes.byref(bytesRead), None):
- le = GetLastError()
- if le == ERROR_BROKEN_PIPE:
- return
- else:
- raise ctypes.WinError()
- # FIXME: Python3
- s = data.value[0:bytesRead.value]
- #print("\nv: %s" % repr(s), file=sys.stderr)
- func(s.decode('utf_8', 'replace'))
-
- def run(self, stdout_func = None, stdin_func = None, stderr_func = None):
- """Runs the process, using the provided functions for I/O.
-
- The function stdin_func should return strings whenever a
- character or characters become available.
- The functions stdout_func and stderr_func are called whenever
- something is printed to stdout or stderr, respectively.
- These functions are called from different threads (but not
- concurrently, because of the GIL).
- """
- if stdout_func is None and stdin_func is None and stderr_func is None:
- return self._run_stdio()
-
- if stderr_func is not None and self.mergeout:
- raise RuntimeError("Shell command was initiated with "
- "merged stdin/stdout, but a separate stderr_func "
- "was provided to the run() method")
-
- # Create a thread for each input/output handle
- stdin_thread = None
- threads = []
- if stdin_func:
- stdin_thread = threading.Thread(target=self._stdin_thread,
- args=(self.hstdin, self.piProcInfo.hProcess,
- stdin_func, stdout_func))
- threads.append(threading.Thread(target=self._stdout_thread,
- args=(self.hstdout, stdout_func)))
- if not self.mergeout:
- if stderr_func is None:
- stderr_func = stdout_func
- threads.append(threading.Thread(target=self._stdout_thread,
- args=(self.hstderr, stderr_func)))
- # Start the I/O threads and the process
- if ResumeThread(self.piProcInfo.hThread) == 0xFFFFFFFF:
- raise ctypes.WinError()
- if stdin_thread is not None:
- stdin_thread.start()
- for thread in threads:
- thread.start()
- # Wait for the process to complete
- if WaitForSingleObject(self.piProcInfo.hProcess, INFINITE) == \
- WAIT_FAILED:
- raise ctypes.WinError()
- # Wait for the I/O threads to complete
- for thread in threads:
- thread.join()
-
- # Wait for the stdin thread to complete
- if stdin_thread is not None:
- stdin_thread.join()
-
- def _stdin_raw_nonblock(self):
- """Use the raw Win32 handle of sys.stdin to do non-blocking reads"""
- # WARNING: This is experimental, and produces inconsistent results.
- # It's possible for the handle not to be appropriate for use
- # with WaitForSingleObject, among other things.
- handle = msvcrt.get_osfhandle(sys.stdin.fileno())
- result = WaitForSingleObject(handle, 100)
- if result == WAIT_FAILED:
- raise ctypes.WinError()
- elif result == WAIT_TIMEOUT:
- print(".", end='')
- return None
- else:
- data = ctypes.create_string_buffer(256)
- bytesRead = DWORD(0)
- print('?', end='')
-
- if not ReadFile(handle, data, 256,
- ctypes.byref(bytesRead), None):
- raise ctypes.WinError()
- # This ensures the non-blocking works with an actual console
- # Not checking the error, so the processing will still work with
- # other handle types
- FlushConsoleInputBuffer(handle)
-
- data = data.value
- data = data.replace('\r\n', '\n')
- data = data.replace('\r', '\n')
- print(repr(data) + " ", end='')
- return data
-
- def _stdin_raw_block(self):
- """Use a blocking stdin read"""
- # The big problem with the blocking read is that it doesn't
- # exit when it's supposed to in all contexts. An extra
- # key-press may be required to trigger the exit.
- try:
- data = sys.stdin.read(1)
- data = data.replace('\r', '\n')
- return data
- except WindowsError as we:
- if we.winerror == ERROR_NO_DATA:
- # This error occurs when the pipe is closed
- return None
- else:
- # Otherwise let the error propagate
- raise we
-
- def _stdout_raw(self, s):
- """Writes the string to stdout"""
- print(s, end='', file=sys.stdout)
- sys.stdout.flush()
-
- def _stderr_raw(self, s):
- """Writes the string to stdout"""
- print(s, end='', file=sys.stderr)
- sys.stderr.flush()
-
- def _run_stdio(self):
- """Runs the process using the system standard I/O.
-
- IMPORTANT: stdin needs to be asynchronous, so the Python
- sys.stdin object is not used. Instead,
- msvcrt.kbhit/getwch are used asynchronously.
- """
- # Disable Line and Echo mode
- #lpMode = DWORD()
- #handle = msvcrt.get_osfhandle(sys.stdin.fileno())
- #if GetConsoleMode(handle, ctypes.byref(lpMode)):
- # set_console_mode = True
- # if not SetConsoleMode(handle, lpMode.value &
- # ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)):
- # raise ctypes.WinError()
-
- if self.mergeout:
- return self.run(stdout_func = self._stdout_raw,
- stdin_func = self._stdin_raw_block)
- else:
- return self.run(stdout_func = self._stdout_raw,
- stdin_func = self._stdin_raw_block,
- stderr_func = self._stderr_raw)
-
- # Restore the previous console mode
- #if set_console_mode:
- # if not SetConsoleMode(handle, lpMode.value):
- # raise ctypes.WinError()
-
- def __exit__(self, exc_type, exc_value, traceback):
- if self.hstdin:
- CloseHandle(self.hstdin)
- self.hstdin = None
- if self.hstdout:
- CloseHandle(self.hstdout)
- self.hstdout = None
- if self.hstderr:
- CloseHandle(self.hstderr)
- self.hstderr = None
- if self.piProcInfo is not None:
- CloseHandle(self.piProcInfo.hProcess)
- CloseHandle(self.piProcInfo.hThread)
- self.piProcInfo = None
-
-
-def system(cmd):
- """Win32 version of os.system() that works with network shares.
-
- Note that this implementation returns None, as meant for use in IPython.
-
- Parameters
- ----------
- cmd : str
- A command to be executed in the system shell.
-
- Returns
- -------
- None : we explicitly do NOT return the subprocess status code, as this
- utility is meant to be used extensively in IPython, where any return value
- would trigger :func:`sys.displayhook` calls.
- """
- with AvoidUNCPath() as path:
- if path is not None:
- cmd = '"pushd %s &&"%s' % (path, cmd)
- with Win32ShellCommandController(cmd) as scc:
- scc.run()
-
-
-if __name__ == "__main__":
- print("Test starting!")
- #system("cmd")
- system("python -i")
- print("Test finished!")
+"""Windows-specific implementation of process utilities with direct WinAPI.
+
+This file is meant to be used by process.py
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2010-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+from __future__ import print_function
+
+# stdlib
+import os, sys, threading
+import ctypes, msvcrt
+
+# local imports
+from . import py3compat
+
+# Win32 API types needed for the API calls
+from ctypes import POINTER
+from ctypes.wintypes import HANDLE, HLOCAL, LPVOID, WORD, DWORD, BOOL, \
+ ULONG, LPCWSTR
+LPDWORD = POINTER(DWORD)
+LPHANDLE = POINTER(HANDLE)
+ULONG_PTR = POINTER(ULONG)
+class SECURITY_ATTRIBUTES(ctypes.Structure):
+ _fields_ = [("nLength", DWORD),
+ ("lpSecurityDescriptor", LPVOID),
+ ("bInheritHandle", BOOL)]
+LPSECURITY_ATTRIBUTES = POINTER(SECURITY_ATTRIBUTES)
+class STARTUPINFO(ctypes.Structure):
+ _fields_ = [("cb", DWORD),
+ ("lpReserved", LPCWSTR),
+ ("lpDesktop", LPCWSTR),
+ ("lpTitle", LPCWSTR),
+ ("dwX", DWORD),
+ ("dwY", DWORD),
+ ("dwXSize", DWORD),
+ ("dwYSize", DWORD),
+ ("dwXCountChars", DWORD),
+ ("dwYCountChars", DWORD),
+ ("dwFillAttribute", DWORD),
+ ("dwFlags", DWORD),
+ ("wShowWindow", WORD),
+ ("cbReserved2", WORD),
+ ("lpReserved2", LPVOID),
+ ("hStdInput", HANDLE),
+ ("hStdOutput", HANDLE),
+ ("hStdError", HANDLE)]
+LPSTARTUPINFO = POINTER(STARTUPINFO)
+class PROCESS_INFORMATION(ctypes.Structure):
+ _fields_ = [("hProcess", HANDLE),
+ ("hThread", HANDLE),
+ ("dwProcessId", DWORD),
+ ("dwThreadId", DWORD)]
+LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION)
+
+# Win32 API constants needed
+ERROR_HANDLE_EOF = 38
+ERROR_BROKEN_PIPE = 109
+ERROR_NO_DATA = 232
+HANDLE_FLAG_INHERIT = 0x0001
+STARTF_USESTDHANDLES = 0x0100
+CREATE_SUSPENDED = 0x0004
+CREATE_NEW_CONSOLE = 0x0010
+CREATE_NO_WINDOW = 0x08000000
+STILL_ACTIVE = 259
+WAIT_TIMEOUT = 0x0102
+WAIT_FAILED = 0xFFFFFFFF
+INFINITE = 0xFFFFFFFF
+DUPLICATE_SAME_ACCESS = 0x00000002
+ENABLE_ECHO_INPUT = 0x0004
+ENABLE_LINE_INPUT = 0x0002
+ENABLE_PROCESSED_INPUT = 0x0001
+
+# Win32 API functions needed
+GetLastError = ctypes.windll.kernel32.GetLastError
+GetLastError.argtypes = []
+GetLastError.restype = DWORD
+
+CreateFile = ctypes.windll.kernel32.CreateFileW
+CreateFile.argtypes = [LPCWSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE]
+CreateFile.restype = HANDLE
+
+CreatePipe = ctypes.windll.kernel32.CreatePipe
+CreatePipe.argtypes = [POINTER(HANDLE), POINTER(HANDLE),
+ LPSECURITY_ATTRIBUTES, DWORD]
+CreatePipe.restype = BOOL
+
+CreateProcess = ctypes.windll.kernel32.CreateProcessW
+CreateProcess.argtypes = [LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES,
+ LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPCWSTR, LPSTARTUPINFO,
+ LPPROCESS_INFORMATION]
+CreateProcess.restype = BOOL
+
+GetExitCodeProcess = ctypes.windll.kernel32.GetExitCodeProcess
+GetExitCodeProcess.argtypes = [HANDLE, LPDWORD]
+GetExitCodeProcess.restype = BOOL
+
+GetCurrentProcess = ctypes.windll.kernel32.GetCurrentProcess
+GetCurrentProcess.argtypes = []
+GetCurrentProcess.restype = HANDLE
+
+ResumeThread = ctypes.windll.kernel32.ResumeThread
+ResumeThread.argtypes = [HANDLE]
+ResumeThread.restype = DWORD
+
+ReadFile = ctypes.windll.kernel32.ReadFile
+ReadFile.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD, LPVOID]
+ReadFile.restype = BOOL
+
+WriteFile = ctypes.windll.kernel32.WriteFile
+WriteFile.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD, LPVOID]
+WriteFile.restype = BOOL
+
+GetConsoleMode = ctypes.windll.kernel32.GetConsoleMode
+GetConsoleMode.argtypes = [HANDLE, LPDWORD]
+GetConsoleMode.restype = BOOL
+
+SetConsoleMode = ctypes.windll.kernel32.SetConsoleMode
+SetConsoleMode.argtypes = [HANDLE, DWORD]
+SetConsoleMode.restype = BOOL
+
+FlushConsoleInputBuffer = ctypes.windll.kernel32.FlushConsoleInputBuffer
+FlushConsoleInputBuffer.argtypes = [HANDLE]
+FlushConsoleInputBuffer.restype = BOOL
+
+WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject
+WaitForSingleObject.argtypes = [HANDLE, DWORD]
+WaitForSingleObject.restype = DWORD
+
+DuplicateHandle = ctypes.windll.kernel32.DuplicateHandle
+DuplicateHandle.argtypes = [HANDLE, HANDLE, HANDLE, LPHANDLE,
+ DWORD, BOOL, DWORD]
+DuplicateHandle.restype = BOOL
+
+SetHandleInformation = ctypes.windll.kernel32.SetHandleInformation
+SetHandleInformation.argtypes = [HANDLE, DWORD, DWORD]
+SetHandleInformation.restype = BOOL
+
+CloseHandle = ctypes.windll.kernel32.CloseHandle
+CloseHandle.argtypes = [HANDLE]
+CloseHandle.restype = BOOL
+
+CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
+CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(ctypes.c_int)]
+CommandLineToArgvW.restype = POINTER(LPCWSTR)
+
+LocalFree = ctypes.windll.kernel32.LocalFree
+LocalFree.argtypes = [HLOCAL]
+LocalFree.restype = HLOCAL
+
+class AvoidUNCPath(object):
+ """A context manager to protect command execution from UNC paths.
+
+ In the Win32 API, commands can't be invoked with the cwd being a UNC path.
+ This context manager temporarily changes directory to the 'C:' drive on
+ entering, and restores the original working directory on exit.
+
+ The context manager returns the starting working directory *if* it made a
+ change and None otherwise, so that users can apply the necessary adjustment
+ to their system calls in the event of a change.
+
+ Examples
+ --------
+ ::
+ cmd = 'dir'
+ with AvoidUNCPath() as path:
+ if path is not None:
+ cmd = '"pushd %s &&"%s' % (path, cmd)
+ os.system(cmd)
+ """
+ def __enter__(self):
+ self.path = py3compat.getcwd()
+ self.is_unc_path = self.path.startswith(r"\\")
+ if self.is_unc_path:
+ # change to c drive (as cmd.exe cannot handle UNC addresses)
+ os.chdir("C:")
+ return self.path
+ else:
+ # We return None to signal that there was no change in the working
+ # directory
+ return None
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ if self.is_unc_path:
+ os.chdir(self.path)
+
+
+class Win32ShellCommandController(object):
+ """Runs a shell command in a 'with' context.
+
+ This implementation is Win32-specific.
+
+ Example:
+ # Runs the command interactively with default console stdin/stdout
+ with ShellCommandController('python -i') as scc:
+ scc.run()
+
+ # Runs the command using the provided functions for stdin/stdout
+ def my_stdout_func(s):
+ # print or save the string 's'
+ write_to_stdout(s)
+ def my_stdin_func():
+ # If input is available, return it as a string.
+ if input_available():
+ return get_input()
+ # If no input available, return None after a short delay to
+ # keep from blocking.
+ else:
+ time.sleep(0.01)
+ return None
+
+ with ShellCommandController('python -i') as scc:
+ scc.run(my_stdout_func, my_stdin_func)
+ """
+
+ def __init__(self, cmd, mergeout = True):
+ """Initializes the shell command controller.
+
+ The cmd is the program to execute, and mergeout is
+ whether to blend stdout and stderr into one output
+ in stdout. Merging them together in this fashion more
+ reliably keeps stdout and stderr in the correct order
+ especially for interactive shell usage.
+ """
+ self.cmd = cmd
+ self.mergeout = mergeout
+
+ def __enter__(self):
+ cmd = self.cmd
+ mergeout = self.mergeout
+
+ self.hstdout, self.hstdin, self.hstderr = None, None, None
+ self.piProcInfo = None
+ try:
+ p_hstdout, c_hstdout, p_hstderr, \
+ c_hstderr, p_hstdin, c_hstdin = [None]*6
+
+ # SECURITY_ATTRIBUTES with inherit handle set to True
+ saAttr = SECURITY_ATTRIBUTES()
+ saAttr.nLength = ctypes.sizeof(saAttr)
+ saAttr.bInheritHandle = True
+ saAttr.lpSecurityDescriptor = None
+
+ def create_pipe(uninherit):
+ """Creates a Windows pipe, which consists of two handles.
+
+ The 'uninherit' parameter controls which handle is not
+ inherited by the child process.
+ """
+ handles = HANDLE(), HANDLE()
+ if not CreatePipe(ctypes.byref(handles[0]),
+ ctypes.byref(handles[1]), ctypes.byref(saAttr), 0):
+ raise ctypes.WinError()
+ if not SetHandleInformation(handles[uninherit],
+ HANDLE_FLAG_INHERIT, 0):
+ raise ctypes.WinError()
+ return handles[0].value, handles[1].value
+
+ p_hstdout, c_hstdout = create_pipe(uninherit=0)
+ # 'mergeout' signals that stdout and stderr should be merged.
+ # We do that by using one pipe for both of them.
+ if mergeout:
+ c_hstderr = HANDLE()
+ if not DuplicateHandle(GetCurrentProcess(), c_hstdout,
+ GetCurrentProcess(), ctypes.byref(c_hstderr),
+ 0, True, DUPLICATE_SAME_ACCESS):
+ raise ctypes.WinError()
+ else:
+ p_hstderr, c_hstderr = create_pipe(uninherit=0)
+ c_hstdin, p_hstdin = create_pipe(uninherit=1)
+
+ # Create the process object
+ piProcInfo = PROCESS_INFORMATION()
+ siStartInfo = STARTUPINFO()
+ siStartInfo.cb = ctypes.sizeof(siStartInfo)
+ siStartInfo.hStdInput = c_hstdin
+ siStartInfo.hStdOutput = c_hstdout
+ siStartInfo.hStdError = c_hstderr
+ siStartInfo.dwFlags = STARTF_USESTDHANDLES
+ dwCreationFlags = CREATE_SUSPENDED | CREATE_NO_WINDOW # | CREATE_NEW_CONSOLE
+
+ if not CreateProcess(None,
+ u"cmd.exe /c " + cmd,
+ None, None, True, dwCreationFlags,
+ None, None, ctypes.byref(siStartInfo),
+ ctypes.byref(piProcInfo)):
+ raise ctypes.WinError()
+
+ # Close this process's versions of the child handles
+ CloseHandle(c_hstdin)
+ c_hstdin = None
+ CloseHandle(c_hstdout)
+ c_hstdout = None
+ if c_hstderr is not None:
+ CloseHandle(c_hstderr)
+ c_hstderr = None
+
+ # Transfer ownership of the parent handles to the object
+ self.hstdin = p_hstdin
+ p_hstdin = None
+ self.hstdout = p_hstdout
+ p_hstdout = None
+ if not mergeout:
+ self.hstderr = p_hstderr
+ p_hstderr = None
+ self.piProcInfo = piProcInfo
+
+ finally:
+ if p_hstdin:
+ CloseHandle(p_hstdin)
+ if c_hstdin:
+ CloseHandle(c_hstdin)
+ if p_hstdout:
+ CloseHandle(p_hstdout)
+ if c_hstdout:
+ CloseHandle(c_hstdout)
+ if p_hstderr:
+ CloseHandle(p_hstderr)
+ if c_hstderr:
+ CloseHandle(c_hstderr)
+
+ return self
+
+ def _stdin_thread(self, handle, hprocess, func, stdout_func):
+ exitCode = DWORD()
+ bytesWritten = DWORD(0)
+ while True:
+ #print("stdin thread loop start")
+ # Get the input string (may be bytes or unicode)
+ data = func()
+
+ # None signals to poll whether the process has exited
+ if data is None:
+ #print("checking for process completion")
+ if not GetExitCodeProcess(hprocess, ctypes.byref(exitCode)):
+ raise ctypes.WinError()
+ if exitCode.value != STILL_ACTIVE:
+ return
+ # TESTING: Does zero-sized writefile help?
+ if not WriteFile(handle, "", 0,
+ ctypes.byref(bytesWritten), None):
+ raise ctypes.WinError()
+ continue
+ #print("\nGot str %s\n" % repr(data), file=sys.stderr)
+
+ # Encode the string to the console encoding
+ if isinstance(data, unicode): #FIXME: Python3
+ data = data.encode('utf_8')
+
+ # What we have now must be a string of bytes
+ if not isinstance(data, str): #FIXME: Python3
+ raise RuntimeError("internal stdin function string error")
+
+ # An empty string signals EOF
+ if len(data) == 0:
+ return
+
+ # In a windows console, sometimes the input is echoed,
+ # but sometimes not. How do we determine when to do this?
+ stdout_func(data)
+ # WriteFile may not accept all the data at once.
+ # Loop until everything is processed
+ while len(data) != 0:
+ #print("Calling writefile")
+ if not WriteFile(handle, data, len(data),
+ ctypes.byref(bytesWritten), None):
+ # This occurs at exit
+ if GetLastError() == ERROR_NO_DATA:
+ return
+ raise ctypes.WinError()
+ #print("Called writefile")
+ data = data[bytesWritten.value:]
+
+ def _stdout_thread(self, handle, func):
+ # Allocate the output buffer
+ data = ctypes.create_string_buffer(4096)
+ while True:
+ bytesRead = DWORD(0)
+ if not ReadFile(handle, data, 4096,
+ ctypes.byref(bytesRead), None):
+ le = GetLastError()
+ if le == ERROR_BROKEN_PIPE:
+ return
+ else:
+ raise ctypes.WinError()
+ # FIXME: Python3
+ s = data.value[0:bytesRead.value]
+ #print("\nv: %s" % repr(s), file=sys.stderr)
+ func(s.decode('utf_8', 'replace'))
+
+ def run(self, stdout_func = None, stdin_func = None, stderr_func = None):
+ """Runs the process, using the provided functions for I/O.
+
+ The function stdin_func should return strings whenever a
+ character or characters become available.
+ The functions stdout_func and stderr_func are called whenever
+ something is printed to stdout or stderr, respectively.
+ These functions are called from different threads (but not
+ concurrently, because of the GIL).
+ """
+ if stdout_func is None and stdin_func is None and stderr_func is None:
+ return self._run_stdio()
+
+ if stderr_func is not None and self.mergeout:
+ raise RuntimeError("Shell command was initiated with "
+ "merged stdin/stdout, but a separate stderr_func "
+ "was provided to the run() method")
+
+ # Create a thread for each input/output handle
+ stdin_thread = None
+ threads = []
+ if stdin_func:
+ stdin_thread = threading.Thread(target=self._stdin_thread,
+ args=(self.hstdin, self.piProcInfo.hProcess,
+ stdin_func, stdout_func))
+ threads.append(threading.Thread(target=self._stdout_thread,
+ args=(self.hstdout, stdout_func)))
+ if not self.mergeout:
+ if stderr_func is None:
+ stderr_func = stdout_func
+ threads.append(threading.Thread(target=self._stdout_thread,
+ args=(self.hstderr, stderr_func)))
+ # Start the I/O threads and the process
+ if ResumeThread(self.piProcInfo.hThread) == 0xFFFFFFFF:
+ raise ctypes.WinError()
+ if stdin_thread is not None:
+ stdin_thread.start()
+ for thread in threads:
+ thread.start()
+ # Wait for the process to complete
+ if WaitForSingleObject(self.piProcInfo.hProcess, INFINITE) == \
+ WAIT_FAILED:
+ raise ctypes.WinError()
+ # Wait for the I/O threads to complete
+ for thread in threads:
+ thread.join()
+
+ # Wait for the stdin thread to complete
+ if stdin_thread is not None:
+ stdin_thread.join()
+
+ def _stdin_raw_nonblock(self):
+ """Use the raw Win32 handle of sys.stdin to do non-blocking reads"""
+ # WARNING: This is experimental, and produces inconsistent results.
+ # It's possible for the handle not to be appropriate for use
+ # with WaitForSingleObject, among other things.
+ handle = msvcrt.get_osfhandle(sys.stdin.fileno())
+ result = WaitForSingleObject(handle, 100)
+ if result == WAIT_FAILED:
+ raise ctypes.WinError()
+ elif result == WAIT_TIMEOUT:
+ print(".", end='')
+ return None
+ else:
+ data = ctypes.create_string_buffer(256)
+ bytesRead = DWORD(0)
+ print('?', end='')
+
+ if not ReadFile(handle, data, 256,
+ ctypes.byref(bytesRead), None):
+ raise ctypes.WinError()
+ # This ensures the non-blocking works with an actual console
+ # Not checking the error, so the processing will still work with
+ # other handle types
+ FlushConsoleInputBuffer(handle)
+
+ data = data.value
+ data = data.replace('\r\n', '\n')
+ data = data.replace('\r', '\n')
+ print(repr(data) + " ", end='')
+ return data
+
+ def _stdin_raw_block(self):
+ """Use a blocking stdin read"""
+ # The big problem with the blocking read is that it doesn't
+ # exit when it's supposed to in all contexts. An extra
+ # key-press may be required to trigger the exit.
+ try:
+ data = sys.stdin.read(1)
+ data = data.replace('\r', '\n')
+ return data
+ except WindowsError as we:
+ if we.winerror == ERROR_NO_DATA:
+ # This error occurs when the pipe is closed
+ return None
+ else:
+ # Otherwise let the error propagate
+ raise we
+
+ def _stdout_raw(self, s):
+ """Writes the string to stdout"""
+ print(s, end='', file=sys.stdout)
+ sys.stdout.flush()
+
+ def _stderr_raw(self, s):
+ """Writes the string to stdout"""
+ print(s, end='', file=sys.stderr)
+ sys.stderr.flush()
+
+ def _run_stdio(self):
+ """Runs the process using the system standard I/O.
+
+ IMPORTANT: stdin needs to be asynchronous, so the Python
+ sys.stdin object is not used. Instead,
+ msvcrt.kbhit/getwch are used asynchronously.
+ """
+ # Disable Line and Echo mode
+ #lpMode = DWORD()
+ #handle = msvcrt.get_osfhandle(sys.stdin.fileno())
+ #if GetConsoleMode(handle, ctypes.byref(lpMode)):
+ # set_console_mode = True
+ # if not SetConsoleMode(handle, lpMode.value &
+ # ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)):
+ # raise ctypes.WinError()
+
+ if self.mergeout:
+ return self.run(stdout_func = self._stdout_raw,
+ stdin_func = self._stdin_raw_block)
+ else:
+ return self.run(stdout_func = self._stdout_raw,
+ stdin_func = self._stdin_raw_block,
+ stderr_func = self._stderr_raw)
+
+ # Restore the previous console mode
+ #if set_console_mode:
+ # if not SetConsoleMode(handle, lpMode.value):
+ # raise ctypes.WinError()
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ if self.hstdin:
+ CloseHandle(self.hstdin)
+ self.hstdin = None
+ if self.hstdout:
+ CloseHandle(self.hstdout)
+ self.hstdout = None
+ if self.hstderr:
+ CloseHandle(self.hstderr)
+ self.hstderr = None
+ if self.piProcInfo is not None:
+ CloseHandle(self.piProcInfo.hProcess)
+ CloseHandle(self.piProcInfo.hThread)
+ self.piProcInfo = None
+
+
+def system(cmd):
+ """Win32 version of os.system() that works with network shares.
+
+ Note that this implementation returns None, as meant for use in IPython.
+
+ Parameters
+ ----------
+ cmd : str
+ A command to be executed in the system shell.
+
+ Returns
+ -------
+ None : we explicitly do NOT return the subprocess status code, as this
+ utility is meant to be used extensively in IPython, where any return value
+ would trigger :func:`sys.displayhook` calls.
+ """
+ with AvoidUNCPath() as path:
+ if path is not None:
+ cmd = '"pushd %s &&"%s' % (path, cmd)
+ with Win32ShellCommandController(cmd) as scc:
+ scc.run()
+
+
+if __name__ == "__main__":
+ print("Test starting!")
+ #system("cmd")
+ system("python -i")
+ print("Test finished!")
diff --git a/contrib/python/ipython/py2/IPython/utils/_signatures.py b/contrib/python/ipython/py2/IPython/utils/_signatures.py
index 9f403618ce..20f52b98ed 100644
--- a/contrib/python/ipython/py2/IPython/utils/_signatures.py
+++ b/contrib/python/ipython/py2/IPython/utils/_signatures.py
@@ -1,818 +1,818 @@
-"""Function signature objects for callables.
-
-Back port of Python 3.3's function signature tools from the inspect module,
-modified to be compatible with Python 2.7 and 3.2+.
-"""
-
-#-----------------------------------------------------------------------------
-# Python 3.3 stdlib inspect.py is public domain
-#
-# Backports Copyright (C) 2013 Aaron Iles
-# Used under Apache License Version 2.0
+"""Function signature objects for callables.
+
+Back port of Python 3.3's function signature tools from the inspect module,
+modified to be compatible with Python 2.7 and 3.2+.
+"""
+
+#-----------------------------------------------------------------------------
+# Python 3.3 stdlib inspect.py is public domain
#
-# Further Changes are Copyright (C) 2013 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-from __future__ import absolute_import, division, print_function
-import itertools
-import functools
-import re
-import types
+# Backports Copyright (C) 2013 Aaron Iles
+# Used under Apache License Version 2.0
+#
+# Further Changes are Copyright (C) 2013 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+from __future__ import absolute_import, division, print_function
+import itertools
+import functools
+import re
+import types
import inspect
-
-
-# patch for single-file
-# we don't support 2.6, so we can just import OrderedDict
-from collections import OrderedDict
-
-__version__ = '0.3'
-# end patch
-
-__all__ = ['BoundArguments', 'Parameter', 'Signature', 'signature']
-
-
-_WrapperDescriptor = type(type.__call__)
-_MethodWrapper = type(all.__call__)
-
-_NonUserDefinedCallables = (_WrapperDescriptor,
- _MethodWrapper,
- types.BuiltinFunctionType)
-
-
-def formatannotation(annotation, base_module=None):
- if isinstance(annotation, type):
- if annotation.__module__ in ('builtins', '__builtin__', base_module):
- return annotation.__name__
- return annotation.__module__+'.'+annotation.__name__
- return repr(annotation)
-
-
-def _get_user_defined_method(cls, method_name, *nested):
- try:
- if cls is type:
- return
- meth = getattr(cls, method_name)
- for name in nested:
- meth = getattr(meth, name, meth)
- except AttributeError:
- return
- else:
- if not isinstance(meth, _NonUserDefinedCallables):
- # Once '__signature__' will be added to 'C'-level
- # callables, this check won't be necessary
- return meth
-
-
-def signature(obj):
- '''Get a signature object for the passed callable.'''
-
- if not callable(obj):
- raise TypeError('{0!r} is not a callable object'.format(obj))
-
+
+
+# patch for single-file
+# we don't support 2.6, so we can just import OrderedDict
+from collections import OrderedDict
+
+__version__ = '0.3'
+# end patch
+
+__all__ = ['BoundArguments', 'Parameter', 'Signature', 'signature']
+
+
+_WrapperDescriptor = type(type.__call__)
+_MethodWrapper = type(all.__call__)
+
+_NonUserDefinedCallables = (_WrapperDescriptor,
+ _MethodWrapper,
+ types.BuiltinFunctionType)
+
+
+def formatannotation(annotation, base_module=None):
+ if isinstance(annotation, type):
+ if annotation.__module__ in ('builtins', '__builtin__', base_module):
+ return annotation.__name__
+ return annotation.__module__+'.'+annotation.__name__
+ return repr(annotation)
+
+
+def _get_user_defined_method(cls, method_name, *nested):
+ try:
+ if cls is type:
+ return
+ meth = getattr(cls, method_name)
+ for name in nested:
+ meth = getattr(meth, name, meth)
+ except AttributeError:
+ return
+ else:
+ if not isinstance(meth, _NonUserDefinedCallables):
+ # Once '__signature__' will be added to 'C'-level
+ # callables, this check won't be necessary
+ return meth
+
+
+def signature(obj):
+ '''Get a signature object for the passed callable.'''
+
+ if not callable(obj):
+ raise TypeError('{0!r} is not a callable object'.format(obj))
+
if inspect.ismethod(obj):
- if obj.__self__ is None:
- # Unbound method - treat it as a function (no distinction in Py 3)
- obj = obj.__func__
- else:
- # Bound method: trim off the first parameter (typically self or cls)
- sig = signature(obj.__func__)
- return sig.replace(parameters=tuple(sig.parameters.values())[1:])
-
- try:
- sig = obj.__signature__
- except AttributeError:
- pass
- else:
- if sig is not None:
- return sig
-
- try:
- # Was this function wrapped by a decorator?
- wrapped = obj.__wrapped__
- except AttributeError:
- pass
- else:
- return signature(wrapped)
-
+ if obj.__self__ is None:
+ # Unbound method - treat it as a function (no distinction in Py 3)
+ obj = obj.__func__
+ else:
+ # Bound method: trim off the first parameter (typically self or cls)
+ sig = signature(obj.__func__)
+ return sig.replace(parameters=tuple(sig.parameters.values())[1:])
+
+ try:
+ sig = obj.__signature__
+ except AttributeError:
+ pass
+ else:
+ if sig is not None:
+ return sig
+
+ try:
+ # Was this function wrapped by a decorator?
+ wrapped = obj.__wrapped__
+ except AttributeError:
+ pass
+ else:
+ return signature(wrapped)
+
if inspect.isfunction(obj):
- return Signature.from_function(obj)
-
- if isinstance(obj, functools.partial):
- sig = signature(obj.func)
-
- new_params = OrderedDict(sig.parameters.items())
-
- partial_args = obj.args or ()
- partial_keywords = obj.keywords or {}
- try:
- ba = sig.bind_partial(*partial_args, **partial_keywords)
- except TypeError as ex:
- msg = 'partial object {0!r} has incorrect arguments'.format(obj)
- raise ValueError(msg)
-
- for arg_name, arg_value in ba.arguments.items():
- param = new_params[arg_name]
- if arg_name in partial_keywords:
- # We set a new default value, because the following code
- # is correct:
- #
- # >>> def foo(a): print(a)
- # >>> print(partial(partial(foo, a=10), a=20)())
- # 20
- # >>> print(partial(partial(foo, a=10), a=20)(a=30))
- # 30
- #
- # So, with 'partial' objects, passing a keyword argument is
- # like setting a new default value for the corresponding
- # parameter
- #
- # We also mark this parameter with '_partial_kwarg'
- # flag. Later, in '_bind', the 'default' value of this
- # parameter will be added to 'kwargs', to simulate
- # the 'functools.partial' real call.
- new_params[arg_name] = param.replace(default=arg_value,
- _partial_kwarg=True)
-
- elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
- not param._partial_kwarg):
- new_params.pop(arg_name)
-
- return sig.replace(parameters=new_params.values())
-
- sig = None
- if isinstance(obj, type):
- # obj is a class or a metaclass
-
- # First, let's see if it has an overloaded __call__ defined
- # in its metaclass
- call = _get_user_defined_method(type(obj), '__call__')
- if call is not None:
- sig = signature(call)
- else:
- # Now we check if the 'obj' class has a '__new__' method
- new = _get_user_defined_method(obj, '__new__')
- if new is not None:
- sig = signature(new)
- else:
- # Finally, we should have at least __init__ implemented
- init = _get_user_defined_method(obj, '__init__')
- if init is not None:
- sig = signature(init)
- elif not isinstance(obj, _NonUserDefinedCallables):
- # An object with __call__
- # We also check that the 'obj' is not an instance of
- # _WrapperDescriptor or _MethodWrapper to avoid
- # infinite recursion (and even potential segfault)
- call = _get_user_defined_method(type(obj), '__call__', 'im_func')
- if call is not None:
- sig = signature(call)
-
- if sig is not None:
- return sig
-
- if isinstance(obj, types.BuiltinFunctionType):
- # Raise a nicer error message for builtins
- msg = 'no signature found for builtin function {0!r}'.format(obj)
- raise ValueError(msg)
-
- raise ValueError('callable {0!r} is not supported by signature'.format(obj))
-
-
-class _void(object):
- '''A private marker - used in Parameter & Signature'''
-
-
-class _empty(object):
- pass
-
-
-class _ParameterKind(int):
- def __new__(self, *args, **kwargs):
- obj = int.__new__(self, *args)
- obj._name = kwargs['name']
- return obj
-
- def __str__(self):
- return self._name
-
- def __repr__(self):
- return '<_ParameterKind: {0!r}>'.format(self._name)
-
-
-_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
-_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
-_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
-_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
-_VAR_KEYWORD = _ParameterKind(4, name='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 not set.
- * annotation
- The annotation for the parameter if specified. If the
- parameter has no annotation, this attribute is not set.
- * 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', '_partial_kwarg')
-
- 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,
- _partial_kwarg=False):
-
- 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 = '{0} parameters cannot have default values'.format(kind)
- raise ValueError(msg)
- self._default = default
- self._annotation = annotation
-
- if name is None:
- if kind != _POSITIONAL_ONLY:
- raise ValueError("None is not a valid name for a "
- "non-positional-only parameter")
- self._name = name
- else:
- name = str(name)
- if kind != _POSITIONAL_ONLY and not re.match(r'[a-z_]\w*$', name, re.I):
- msg = '{0!r} is not a valid parameter name'.format(name)
- raise ValueError(msg)
- self._name = name
-
- self._partial_kwarg = _partial_kwarg
-
- @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, _partial_kwarg=_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
-
- if _partial_kwarg is _void:
- _partial_kwarg = self._partial_kwarg
-
- return type(self)(name, kind, default=default, annotation=annotation,
- _partial_kwarg=_partial_kwarg)
-
- def __str__(self):
- kind = self.kind
-
- formatted = self._name
- if kind == _POSITIONAL_ONLY:
- if formatted is None:
- formatted = ''
- formatted = '<{0}>'.format(formatted)
-
- # Add annotation and default value
- if self._annotation is not _empty:
- formatted = '{0}:{1}'.format(formatted,
- formatannotation(self._annotation))
-
- if self._default is not _empty:
- formatted = '{0}={1}'.format(formatted, repr(self._default))
-
- if kind == _VAR_POSITIONAL:
- formatted = '*' + formatted
- elif kind == _VAR_KEYWORD:
- formatted = '**' + formatted
-
- return formatted
-
- def __repr__(self):
- return '<{0} at {1:#x} {2!r}>'.format(self.__class__.__name__,
- id(self), self.name)
-
- def __hash__(self):
- msg = "unhashable type: '{0}'".format(self.__class__.__name__)
- raise TypeError(msg)
-
- def __eq__(self, other):
- return (issubclass(other.__class__, Parameter) and
- self._name == other._name and
- self._kind == other._kind and
- self._default == other._default and
- self._annotation == other._annotation)
-
- def __ne__(self, other):
- return not self.__eq__(other)
-
-
-class BoundArguments(object):
- '''Result of :meth:`Signature.bind` call. Holds the mapping of arguments
- to the function's parameters.
-
- Has the following public attributes:
-
- arguments : :class:`collections.OrderedDict`
- An ordered mutable mapping of parameters' names to arguments' values.
- Does not contain arguments' default values.
- signature : :class:`Signature`
- The Signature object that created this instance.
- args : tuple
- Tuple of positional arguments values.
- kwargs : dict
- Dict of keyword arguments values.
- '''
-
- 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) or
- param._partial_kwarg):
- # Keyword arguments mapped by 'functools.partial'
- # (Parameter._partial_kwarg is True) are mapped
- # in 'BoundArguments.kwargs', along with 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) or
- param._partial_kwarg):
- 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 __hash__(self):
- msg = "unhashable type: '{0}'".format(self.__class__.__name__)
- raise TypeError(msg)
-
- def __eq__(self, other):
- return (issubclass(other.__class__, BoundArguments) and
- self.signature == other.signature and
- self.arguments == other.arguments)
-
- def __ne__(self, other):
- return not self.__eq__(other)
-
-
-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:
-
- parameters : :class:`collections.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
- The annotation for the return type of the function if specified.
- If the function has no annotation for its return type, this
- attribute is not set.
- '''
-
- __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
-
- for idx, param in enumerate(parameters):
- kind = param.kind
- if kind < top_kind:
- msg = 'wrong parameter order: {0} before {1}'
- msg = msg.format(top_kind, param.kind)
- raise ValueError(msg)
- else:
- top_kind = kind
-
- name = param.name
- if name is None:
- name = str(idx)
- param = param.replace(name=name)
-
- if name in params:
- msg = 'duplicate parameter name: {0!r}'.format(name)
- raise ValueError(msg)
- params[name] = param
- else:
- params = OrderedDict(((param.name, param)
- for param in parameters))
-
- self._parameters = params
- self._return_annotation = return_annotation
-
- @classmethod
- def from_function(cls, func):
- '''Constructs Signature for the given python function'''
-
+ return Signature.from_function(obj)
+
+ if isinstance(obj, functools.partial):
+ sig = signature(obj.func)
+
+ new_params = OrderedDict(sig.parameters.items())
+
+ partial_args = obj.args or ()
+ partial_keywords = obj.keywords or {}
+ try:
+ ba = sig.bind_partial(*partial_args, **partial_keywords)
+ except TypeError as ex:
+ msg = 'partial object {0!r} has incorrect arguments'.format(obj)
+ raise ValueError(msg)
+
+ for arg_name, arg_value in ba.arguments.items():
+ param = new_params[arg_name]
+ if arg_name in partial_keywords:
+ # We set a new default value, because the following code
+ # is correct:
+ #
+ # >>> def foo(a): print(a)
+ # >>> print(partial(partial(foo, a=10), a=20)())
+ # 20
+ # >>> print(partial(partial(foo, a=10), a=20)(a=30))
+ # 30
+ #
+ # So, with 'partial' objects, passing a keyword argument is
+ # like setting a new default value for the corresponding
+ # parameter
+ #
+ # We also mark this parameter with '_partial_kwarg'
+ # flag. Later, in '_bind', the 'default' value of this
+ # parameter will be added to 'kwargs', to simulate
+ # the 'functools.partial' real call.
+ new_params[arg_name] = param.replace(default=arg_value,
+ _partial_kwarg=True)
+
+ elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
+ not param._partial_kwarg):
+ new_params.pop(arg_name)
+
+ return sig.replace(parameters=new_params.values())
+
+ sig = None
+ if isinstance(obj, type):
+ # obj is a class or a metaclass
+
+ # First, let's see if it has an overloaded __call__ defined
+ # in its metaclass
+ call = _get_user_defined_method(type(obj), '__call__')
+ if call is not None:
+ sig = signature(call)
+ else:
+ # Now we check if the 'obj' class has a '__new__' method
+ new = _get_user_defined_method(obj, '__new__')
+ if new is not None:
+ sig = signature(new)
+ else:
+ # Finally, we should have at least __init__ implemented
+ init = _get_user_defined_method(obj, '__init__')
+ if init is not None:
+ sig = signature(init)
+ elif not isinstance(obj, _NonUserDefinedCallables):
+ # An object with __call__
+ # We also check that the 'obj' is not an instance of
+ # _WrapperDescriptor or _MethodWrapper to avoid
+ # infinite recursion (and even potential segfault)
+ call = _get_user_defined_method(type(obj), '__call__', 'im_func')
+ if call is not None:
+ sig = signature(call)
+
+ if sig is not None:
+ return sig
+
+ if isinstance(obj, types.BuiltinFunctionType):
+ # Raise a nicer error message for builtins
+ msg = 'no signature found for builtin function {0!r}'.format(obj)
+ raise ValueError(msg)
+
+ raise ValueError('callable {0!r} is not supported by signature'.format(obj))
+
+
+class _void(object):
+ '''A private marker - used in Parameter & Signature'''
+
+
+class _empty(object):
+ pass
+
+
+class _ParameterKind(int):
+ def __new__(self, *args, **kwargs):
+ obj = int.__new__(self, *args)
+ obj._name = kwargs['name']
+ return obj
+
+ def __str__(self):
+ return self._name
+
+ def __repr__(self):
+ return '<_ParameterKind: {0!r}>'.format(self._name)
+
+
+_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
+_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
+_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
+_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
+_VAR_KEYWORD = _ParameterKind(4, name='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 not set.
+ * annotation
+ The annotation for the parameter if specified. If the
+ parameter has no annotation, this attribute is not set.
+ * 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', '_partial_kwarg')
+
+ 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,
+ _partial_kwarg=False):
+
+ 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 = '{0} parameters cannot have default values'.format(kind)
+ raise ValueError(msg)
+ self._default = default
+ self._annotation = annotation
+
+ if name is None:
+ if kind != _POSITIONAL_ONLY:
+ raise ValueError("None is not a valid name for a "
+ "non-positional-only parameter")
+ self._name = name
+ else:
+ name = str(name)
+ if kind != _POSITIONAL_ONLY and not re.match(r'[a-z_]\w*$', name, re.I):
+ msg = '{0!r} is not a valid parameter name'.format(name)
+ raise ValueError(msg)
+ self._name = name
+
+ self._partial_kwarg = _partial_kwarg
+
+ @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, _partial_kwarg=_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
+
+ if _partial_kwarg is _void:
+ _partial_kwarg = self._partial_kwarg
+
+ return type(self)(name, kind, default=default, annotation=annotation,
+ _partial_kwarg=_partial_kwarg)
+
+ def __str__(self):
+ kind = self.kind
+
+ formatted = self._name
+ if kind == _POSITIONAL_ONLY:
+ if formatted is None:
+ formatted = ''
+ formatted = '<{0}>'.format(formatted)
+
+ # Add annotation and default value
+ if self._annotation is not _empty:
+ formatted = '{0}:{1}'.format(formatted,
+ formatannotation(self._annotation))
+
+ if self._default is not _empty:
+ formatted = '{0}={1}'.format(formatted, repr(self._default))
+
+ if kind == _VAR_POSITIONAL:
+ formatted = '*' + formatted
+ elif kind == _VAR_KEYWORD:
+ formatted = '**' + formatted
+
+ return formatted
+
+ def __repr__(self):
+ return '<{0} at {1:#x} {2!r}>'.format(self.__class__.__name__,
+ id(self), self.name)
+
+ def __hash__(self):
+ msg = "unhashable type: '{0}'".format(self.__class__.__name__)
+ raise TypeError(msg)
+
+ def __eq__(self, other):
+ return (issubclass(other.__class__, Parameter) and
+ self._name == other._name and
+ self._kind == other._kind and
+ self._default == other._default and
+ self._annotation == other._annotation)
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+
+class BoundArguments(object):
+ '''Result of :meth:`Signature.bind` call. Holds the mapping of arguments
+ to the function's parameters.
+
+ Has the following public attributes:
+
+ arguments : :class:`collections.OrderedDict`
+ An ordered mutable mapping of parameters' names to arguments' values.
+ Does not contain arguments' default values.
+ signature : :class:`Signature`
+ The Signature object that created this instance.
+ args : tuple
+ Tuple of positional arguments values.
+ kwargs : dict
+ Dict of keyword arguments values.
+ '''
+
+ 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) or
+ param._partial_kwarg):
+ # Keyword arguments mapped by 'functools.partial'
+ # (Parameter._partial_kwarg is True) are mapped
+ # in 'BoundArguments.kwargs', along with 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) or
+ param._partial_kwarg):
+ 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 __hash__(self):
+ msg = "unhashable type: '{0}'".format(self.__class__.__name__)
+ raise TypeError(msg)
+
+ def __eq__(self, other):
+ return (issubclass(other.__class__, BoundArguments) and
+ self.signature == other.signature and
+ self.arguments == other.arguments)
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+
+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:
+
+ parameters : :class:`collections.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
+ The annotation for the return type of the function if specified.
+ If the function has no annotation for its return type, this
+ attribute is not set.
+ '''
+
+ __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
+
+ for idx, param in enumerate(parameters):
+ kind = param.kind
+ if kind < top_kind:
+ msg = 'wrong parameter order: {0} before {1}'
+ msg = msg.format(top_kind, param.kind)
+ raise ValueError(msg)
+ else:
+ top_kind = kind
+
+ name = param.name
+ if name is None:
+ name = str(idx)
+ param = param.replace(name=name)
+
+ if name in params:
+ msg = 'duplicate parameter name: {0!r}'.format(name)
+ raise ValueError(msg)
+ params[name] = param
+ else:
+ params = OrderedDict(((param.name, param)
+ for param in parameters))
+
+ self._parameters = params
+ self._return_annotation = return_annotation
+
+ @classmethod
+ def from_function(cls, func):
+ '''Constructs Signature for the given python function'''
+
if not inspect.isfunction(func):
- raise TypeError('{0!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 = getattr(func_code, 'co_kwonlyargcount', 0)
- keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
- annotations = getattr(func, '__annotations__', {})
- defaults = func.__defaults__
- kwdefaults = getattr(func, '__kwdefaults__', None)
-
- 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 & 0x04:
- 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 & 0x08:
- index = pos_count + keyword_only_count
- if func_code.co_flags & 0x04:
- index += 1
-
- name = arg_names[index]
- annotation = annotations.get(name, _empty)
- parameters.append(Parameter(name, annotation=annotation,
- kind=_VAR_KEYWORD))
-
- return cls(parameters,
- return_annotation=annotations.get('return', _empty),
- __validate_parameters__=False)
-
- @property
- def parameters(self):
- try:
- return types.MappingProxyType(self._parameters)
- except AttributeError:
- return OrderedDict(self._parameters.items())
-
- @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__(self):
- msg = "unhashable type: '{0}'".format(self.__class__.__name__)
- raise TypeError(msg)
-
- def __eq__(self, other):
- if (not issubclass(type(other), Signature) or
- self.return_annotation != other.return_annotation or
- len(self.parameters) != len(other.parameters)):
- return False
-
- other_positions = dict((param, idx)
- for idx, param in enumerate(other.parameters.keys()))
-
- for idx, (param_name, param) in enumerate(self.parameters.items()):
- if param.kind == _KEYWORD_ONLY:
- try:
- other_param = other.parameters[param_name]
- except KeyError:
- return False
- else:
- if param != other_param:
- return False
- else:
- try:
- other_idx = other_positions[param_name]
- except KeyError:
- return False
- else:
- if (idx != other_idx or
- param != other.parameters[param_name]):
- return False
-
- return True
-
- def __ne__(self, other):
- return not self.__eq__(other)
-
- 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)
-
- if partial:
- # Support for binding arguments to 'functools.partial' objects.
- # See 'functools.partial' case in 'signature()' implementation
- # for details.
- for param_name, param in self.parameters.items():
- if (param._partial_kwarg and param_name not in kwargs):
- # Simulating 'functools.partial' behavior
- kwargs[param_name] = param.default
-
- 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)
- 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:
- if partial:
- parameters_ex = (param,)
- break
- else:
- msg = '{arg!r} parameter lacking default value'
- msg = msg.format(arg=param.name)
- raise TypeError(msg)
- else:
- # We have a positional argument to process
- try:
- param = next(parameters)
- except StopIteration:
- raise TypeError('too many positional arguments')
- 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')
-
- 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))
-
- 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 == _POSITIONAL_ONLY:
- # This should never happen in case of a properly built
- # Signature object (but let's have this check here
- # to ensure correct behaviour just in case)
- raise TypeError('{arg!r} parameter is positional only, '
- 'but was passed as a keyword'. \
- format(arg=param.name))
-
- if param.kind == _VAR_KEYWORD:
- # Memorize that we have a '**kwargs'-like parameter
- kwargs_param = param
- 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('{arg!r} parameter lacking default value'. \
- format(arg=param_name))
-
- else:
- 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('too many keyword arguments')
-
- return self._bound_arguments_cls(self, arguments)
-
- def bind(self, *args, **kwargs):
- '''Get a :class:`BoundArguments` object, that maps the passed `args`
- and `kwargs` to the function's signature. Raises :exc:`TypeError`
- if the passed arguments can not be bound.
- '''
- return self._bind(args, kwargs)
-
- def bind_partial(self, *args, **kwargs):
- '''Get a :class:`BoundArguments` object, that partially maps the
- passed `args` and `kwargs` to the function's signature.
- Raises :exc:`TypeError` if the passed arguments can not be bound.
- '''
- return self._bind(args, kwargs, partial=True)
-
- def __str__(self):
- result = []
- render_kw_only_separator = True
- for idx, param in enumerate(self.parameters.values()):
- formatted = str(param)
-
- kind = param.kind
- 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)
-
- rendered = '({0})'.format(', '.join(result))
-
- if self.return_annotation is not _empty:
- anno = formatannotation(self.return_annotation)
- rendered += ' -> {0}'.format(anno)
-
- return rendered
-
+ raise TypeError('{0!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 = getattr(func_code, 'co_kwonlyargcount', 0)
+ keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
+ annotations = getattr(func, '__annotations__', {})
+ defaults = func.__defaults__
+ kwdefaults = getattr(func, '__kwdefaults__', None)
+
+ 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 & 0x04:
+ 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 & 0x08:
+ index = pos_count + keyword_only_count
+ if func_code.co_flags & 0x04:
+ index += 1
+
+ name = arg_names[index]
+ annotation = annotations.get(name, _empty)
+ parameters.append(Parameter(name, annotation=annotation,
+ kind=_VAR_KEYWORD))
+
+ return cls(parameters,
+ return_annotation=annotations.get('return', _empty),
+ __validate_parameters__=False)
+
+ @property
+ def parameters(self):
+ try:
+ return types.MappingProxyType(self._parameters)
+ except AttributeError:
+ return OrderedDict(self._parameters.items())
+
+ @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__(self):
+ msg = "unhashable type: '{0}'".format(self.__class__.__name__)
+ raise TypeError(msg)
+
+ def __eq__(self, other):
+ if (not issubclass(type(other), Signature) or
+ self.return_annotation != other.return_annotation or
+ len(self.parameters) != len(other.parameters)):
+ return False
+
+ other_positions = dict((param, idx)
+ for idx, param in enumerate(other.parameters.keys()))
+
+ for idx, (param_name, param) in enumerate(self.parameters.items()):
+ if param.kind == _KEYWORD_ONLY:
+ try:
+ other_param = other.parameters[param_name]
+ except KeyError:
+ return False
+ else:
+ if param != other_param:
+ return False
+ else:
+ try:
+ other_idx = other_positions[param_name]
+ except KeyError:
+ return False
+ else:
+ if (idx != other_idx or
+ param != other.parameters[param_name]):
+ return False
+
+ return True
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ 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)
+
+ if partial:
+ # Support for binding arguments to 'functools.partial' objects.
+ # See 'functools.partial' case in 'signature()' implementation
+ # for details.
+ for param_name, param in self.parameters.items():
+ if (param._partial_kwarg and param_name not in kwargs):
+ # Simulating 'functools.partial' behavior
+ kwargs[param_name] = param.default
+
+ 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)
+ 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:
+ if partial:
+ parameters_ex = (param,)
+ break
+ else:
+ msg = '{arg!r} parameter lacking default value'
+ msg = msg.format(arg=param.name)
+ raise TypeError(msg)
+ else:
+ # We have a positional argument to process
+ try:
+ param = next(parameters)
+ except StopIteration:
+ raise TypeError('too many positional arguments')
+ 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')
+
+ 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))
+
+ 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 == _POSITIONAL_ONLY:
+ # This should never happen in case of a properly built
+ # Signature object (but let's have this check here
+ # to ensure correct behaviour just in case)
+ raise TypeError('{arg!r} parameter is positional only, '
+ 'but was passed as a keyword'. \
+ format(arg=param.name))
+
+ if param.kind == _VAR_KEYWORD:
+ # Memorize that we have a '**kwargs'-like parameter
+ kwargs_param = param
+ 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('{arg!r} parameter lacking default value'. \
+ format(arg=param_name))
+
+ else:
+ 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('too many keyword arguments')
+
+ return self._bound_arguments_cls(self, arguments)
+
+ def bind(self, *args, **kwargs):
+ '''Get a :class:`BoundArguments` object, that maps the passed `args`
+ and `kwargs` to the function's signature. Raises :exc:`TypeError`
+ if the passed arguments can not be bound.
+ '''
+ return self._bind(args, kwargs)
+
+ def bind_partial(self, *args, **kwargs):
+ '''Get a :class:`BoundArguments` object, that partially maps the
+ passed `args` and `kwargs` to the function's signature.
+ Raises :exc:`TypeError` if the passed arguments can not be bound.
+ '''
+ return self._bind(args, kwargs, partial=True)
+
+ def __str__(self):
+ result = []
+ render_kw_only_separator = True
+ for idx, param in enumerate(self.parameters.values()):
+ formatted = str(param)
+
+ kind = param.kind
+ 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)
+
+ rendered = '({0})'.format(', '.join(result))
+
+ if self.return_annotation is not _empty:
+ anno = formatannotation(self.return_annotation)
+ rendered += ' -> {0}'.format(anno)
+
+ return rendered
+
diff --git a/contrib/python/ipython/py2/IPython/utils/_sysinfo.py b/contrib/python/ipython/py2/IPython/utils/_sysinfo.py
index f3422bbb3c..21dd2fcceb 100644
--- a/contrib/python/ipython/py2/IPython/utils/_sysinfo.py
+++ b/contrib/python/ipython/py2/IPython/utils/_sysinfo.py
@@ -1,2 +1,2 @@
-# GENERATED BY setup.py
+# GENERATED BY setup.py
commit = u"2348ebbe4"
diff --git a/contrib/python/ipython/py2/IPython/utils/_tokenize_py2.py b/contrib/python/ipython/py2/IPython/utils/_tokenize_py2.py
index ffd7cc5e71..195df96ee5 100644
--- a/contrib/python/ipython/py2/IPython/utils/_tokenize_py2.py
+++ b/contrib/python/ipython/py2/IPython/utils/_tokenize_py2.py
@@ -1,439 +1,439 @@
-"""Patched version of standard library tokenize, to deal with various bugs.
-
-Patches
-
-- Relevant parts of Gareth Rees' patch for Python issue #12691 (untokenizing),
- manually applied.
-- Newlines in comments and blank lines should be either NL or NEWLINE, depending
- on whether they are in a multi-line statement. Filed as Python issue #17061.
-
--------------------------------------------------------------------------------
-Tokenization help for Python programs.
-
-generate_tokens(readline) is a generator that breaks a stream of
-text into Python tokens. It accepts a readline-like method which is called
-repeatedly to get the next line of input (or "" for EOF). It generates
-5-tuples with these members:
-
- the token type (see token.py)
- the token (a string)
- the starting (row, column) indices of the token (a 2-tuple of ints)
- the ending (row, column) indices of the token (a 2-tuple of ints)
- the original line (string)
-
-It is designed to match the working of the Python tokenizer exactly, except
-that it produces COMMENT tokens for comments and gives type OP for all
-operators
-
-Older entry points
- tokenize_loop(readline, tokeneater)
- tokenize(readline, tokeneater=printtoken)
-are the same, except instead of generating tokens, tokeneater is a callback
-function to which the 5 fields described above are passed as 5 arguments,
-each time a new token is found."""
-from __future__ import print_function
-
-__author__ = 'Ka-Ping Yee <ping@lfw.org>'
-__credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
- 'Skip Montanaro, Raymond Hettinger')
-
-import string, re
-from token import *
-
-import token
-__all__ = [x for x in dir(token) if not x.startswith("_")]
-__all__ += ["COMMENT", "tokenize", "generate_tokens", "NL", "untokenize"]
-del x
-del token
-
-__all__ += ["TokenError"]
-
-COMMENT = N_TOKENS
-tok_name[COMMENT] = 'COMMENT'
-NL = N_TOKENS + 1
-tok_name[NL] = 'NL'
-N_TOKENS += 2
-
-def group(*choices): return '(' + '|'.join(choices) + ')'
-def any(*choices): return group(*choices) + '*'
-def maybe(*choices): return group(*choices) + '?'
-
-Whitespace = r'[ \f\t]*'
-Comment = r'#[^\r\n]*'
-Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
-Name = r'[a-zA-Z_]\w*'
-
-Hexnumber = r'0[xX][\da-fA-F]+[lL]?'
-Octnumber = r'(0[oO][0-7]+)|(0[0-7]*)[lL]?'
-Binnumber = r'0[bB][01]+[lL]?'
-Decnumber = r'[1-9]\d*[lL]?'
-Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
-Exponent = r'[eE][-+]?\d+'
-Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent)
-Expfloat = r'\d+' + Exponent
-Floatnumber = group(Pointfloat, Expfloat)
-Imagnumber = group(r'\d+[jJ]', Floatnumber + r'[jJ]')
-Number = group(Imagnumber, Floatnumber, Intnumber)
-
-# Tail end of ' string.
-Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
-# Tail end of " string.
-Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
-# Tail end of ''' string.
-Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
-# Tail end of """ string.
-Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
-Triple = group("[uUbB]?[rR]?'''", '[uUbB]?[rR]?"""')
-# Single-line ' or " string.
-String = group(r"[uUbB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
- r'[uUbB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
-
-# Because of leftmost-then-longest match semantics, be sure to put the
-# longest operators first (e.g., if = came before ==, == would get
-# recognized as two instances of =).
-Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=",
- r"//=?",
- r"[+\-*/%&|^=<>]=?",
- r"~")
-
-Bracket = '[][(){}]'
-Special = group(r'\r?\n', r'[:;.,`@]')
-Funny = group(Operator, Bracket, Special)
-
-PlainToken = group(Number, Funny, String, Name)
-Token = Ignore + PlainToken
-
-# First (or only) line of ' or " string.
-ContStr = group(r"[uUbB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
- group("'", r'\\\r?\n'),
- r'[uUbB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
- group('"', r'\\\r?\n'))
-PseudoExtras = group(r'\\\r?\n', Comment, Triple)
-PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
-
-tokenprog, pseudoprog, single3prog, double3prog = map(
- re.compile, (Token, PseudoToken, Single3, Double3))
-endprogs = {"'": re.compile(Single), '"': re.compile(Double),
- "'''": single3prog, '"""': double3prog,
- "r'''": single3prog, 'r"""': double3prog,
- "u'''": single3prog, 'u"""': double3prog,
- "ur'''": single3prog, 'ur"""': double3prog,
- "R'''": single3prog, 'R"""': double3prog,
- "U'''": single3prog, 'U"""': double3prog,
- "uR'''": single3prog, 'uR"""': double3prog,
- "Ur'''": single3prog, 'Ur"""': double3prog,
- "UR'''": single3prog, 'UR"""': double3prog,
- "b'''": single3prog, 'b"""': double3prog,
- "br'''": single3prog, 'br"""': double3prog,
- "B'''": single3prog, 'B"""': double3prog,
- "bR'''": single3prog, 'bR"""': double3prog,
- "Br'''": single3prog, 'Br"""': double3prog,
- "BR'''": single3prog, 'BR"""': double3prog,
- 'r': None, 'R': None, 'u': None, 'U': None,
- 'b': None, 'B': None}
-
-triple_quoted = {}
-for t in ("'''", '"""',
- "r'''", 'r"""', "R'''", 'R"""',
- "u'''", 'u"""', "U'''", 'U"""',
- "ur'''", 'ur"""', "Ur'''", 'Ur"""',
- "uR'''", 'uR"""', "UR'''", 'UR"""',
- "b'''", 'b"""', "B'''", 'B"""',
- "br'''", 'br"""', "Br'''", 'Br"""',
- "bR'''", 'bR"""', "BR'''", 'BR"""'):
- triple_quoted[t] = t
-single_quoted = {}
-for t in ("'", '"',
- "r'", 'r"', "R'", 'R"',
- "u'", 'u"', "U'", 'U"',
- "ur'", 'ur"', "Ur'", 'Ur"',
- "uR'", 'uR"', "UR'", 'UR"',
- "b'", 'b"', "B'", 'B"',
- "br'", 'br"', "Br'", 'Br"',
- "bR'", 'bR"', "BR'", 'BR"' ):
- single_quoted[t] = t
-
-tabsize = 8
-
-class TokenError(Exception): pass
-
-class StopTokenizing(Exception): pass
-
-def printtoken(type, token, srow_scol, erow_ecol, line): # for testing
- srow, scol = srow_scol
- erow, ecol = erow_ecol
- print("%d,%d-%d,%d:\t%s\t%s" % \
- (srow, scol, erow, ecol, tok_name[type], repr(token)))
-
-def tokenize(readline, tokeneater=printtoken):
- """
- The tokenize() function accepts two parameters: one representing the
- input stream, and one providing an output mechanism for tokenize().
-
- The first parameter, readline, must be a callable object which provides
- the same interface as the readline() method of built-in file objects.
- Each call to the function should return one line of input as a string.
-
- The second parameter, tokeneater, must also be a callable object. It is
- called once for each token, with five arguments, corresponding to the
- tuples generated by generate_tokens().
- """
- try:
- tokenize_loop(readline, tokeneater)
- except StopTokenizing:
- pass
-
-# backwards compatible interface
-def tokenize_loop(readline, tokeneater):
- for token_info in generate_tokens(readline):
- tokeneater(*token_info)
-
-class Untokenizer:
-
- def __init__(self):
- self.tokens = []
- self.prev_row = 1
- self.prev_col = 0
-
- def add_whitespace(self, start):
- row, col = start
- assert row >= self.prev_row
- col_offset = col - self.prev_col
- if col_offset > 0:
- self.tokens.append(" " * col_offset)
- elif row > self.prev_row and tok_type not in (NEWLINE, NL, ENDMARKER):
- # Line was backslash-continued
- self.tokens.append(" ")
-
- def untokenize(self, tokens):
- iterable = iter(tokens)
- for t in iterable:
- if len(t) == 2:
- self.compat(t, iterable)
- break
- tok_type, token, start, end = t[:4]
- self.add_whitespace(start)
- self.tokens.append(token)
- self.prev_row, self.prev_col = end
- if tok_type in (NEWLINE, NL):
- self.prev_row += 1
- self.prev_col = 0
- return "".join(self.tokens)
-
- def compat(self, token, iterable):
- # This import is here to avoid problems when the itertools
- # module is not built yet and tokenize is imported.
- from itertools import chain
- startline = False
- prevstring = False
- indents = []
- toks_append = self.tokens.append
- for tok in chain([token], iterable):
- toknum, tokval = tok[:2]
-
- if toknum in (NAME, NUMBER):
- tokval += ' '
-
- # Insert a space between two consecutive strings
- if toknum == STRING:
- if prevstring:
- tokval = ' ' + tokval
- prevstring = True
- else:
- prevstring = False
-
- if toknum == INDENT:
- indents.append(tokval)
- continue
- elif toknum == DEDENT:
- indents.pop()
- continue
- elif toknum in (NEWLINE, NL):
- startline = True
- elif startline and indents:
- toks_append(indents[-1])
- startline = False
- toks_append(tokval)
-
-def untokenize(iterable):
- """Transform tokens back into Python source code.
-
- Each element returned by the iterable must be a token sequence
- with at least two elements, a token number and token value. If
- only two tokens are passed, the resulting output is poor.
-
- Round-trip invariant for full input:
- Untokenized source will match input source exactly
-
- Round-trip invariant for limited intput:
- # Output text will tokenize the back to the input
- t1 = [tok[:2] for tok in generate_tokens(f.readline)]
- newcode = untokenize(t1)
- readline = iter(newcode.splitlines(1)).next
- t2 = [tok[:2] for tok in generate_tokens(readline)]
- assert t1 == t2
- """
- ut = Untokenizer()
- return ut.untokenize(iterable)
-
-def generate_tokens(readline):
- """
- The generate_tokens() generator requires one argment, readline, which
- must be a callable object which provides the same interface as the
- readline() method of built-in file objects. Each call to the function
- should return one line of input as a string. Alternately, readline
- can be a callable function terminating with StopIteration:
- readline = open(myfile).next # Example of alternate readline
-
- The generator produces 5-tuples with these members: the token type; the
- token string; a 2-tuple (srow, scol) of ints specifying the row and
- column where the token begins in the source; a 2-tuple (erow, ecol) of
- ints specifying the row and column where the token ends in the source;
- and the line on which the token was found. The line passed is the
- logical line; continuation lines are included.
- """
- lnum = parenlev = continued = 0
- namechars, numchars = string.ascii_letters + '_', '0123456789'
- contstr, needcont = '', 0
- contline = None
- indents = [0]
-
- while 1: # loop over lines in stream
- try:
- line = readline()
- except StopIteration:
- line = ''
- lnum += 1
- pos, max = 0, len(line)
-
- if contstr: # continued string
- if not line:
- raise TokenError("EOF in multi-line string", strstart)
- endmatch = endprog.match(line)
- if endmatch:
- pos = end = endmatch.end(0)
- yield (STRING, contstr + line[:end],
- strstart, (lnum, end), contline + line)
- contstr, needcont = '', 0
- contline = None
- elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
- yield (ERRORTOKEN, contstr + line,
- strstart, (lnum, len(line)), contline)
- contstr = ''
- contline = None
- continue
- else:
- contstr = contstr + line
- contline = contline + line
- continue
-
- elif parenlev == 0 and not continued: # new statement
- if not line: break
- column = 0
- while pos < max: # measure leading whitespace
- if line[pos] == ' ':
- column += 1
- elif line[pos] == '\t':
- column = (column//tabsize + 1)*tabsize
- elif line[pos] == '\f':
- column = 0
- else:
- break
- pos += 1
- if pos == max:
- break
-
- if line[pos] in '#\r\n': # skip comments or blank lines
- if line[pos] == '#':
- comment_token = line[pos:].rstrip('\r\n')
- nl_pos = pos + len(comment_token)
- yield (COMMENT, comment_token,
- (lnum, pos), (lnum, pos + len(comment_token)), line)
- yield (NEWLINE, line[nl_pos:],
- (lnum, nl_pos), (lnum, len(line)), line)
- else:
- yield (NEWLINE, line[pos:],
- (lnum, pos), (lnum, len(line)), line)
- continue
-
- if column > indents[-1]: # count indents or dedents
- indents.append(column)
- yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
- while column < indents[-1]:
- if column not in indents:
- raise IndentationError(
- "unindent does not match any outer indentation level",
- ("<tokenize>", lnum, pos, line))
- indents = indents[:-1]
- yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
-
- else: # continued statement
- if not line:
- raise TokenError("EOF in multi-line statement", (lnum, 0))
- continued = 0
-
- while pos < max:
- pseudomatch = pseudoprog.match(line, pos)
- if pseudomatch: # scan for tokens
- start, end = pseudomatch.span(1)
- spos, epos, pos = (lnum, start), (lnum, end), end
- token, initial = line[start:end], line[start]
-
- if initial in numchars or \
- (initial == '.' and token != '.'): # ordinary number
- yield (NUMBER, token, spos, epos, line)
- elif initial in '\r\n':
- yield (NL if parenlev > 0 else NEWLINE,
- token, spos, epos, line)
- elif initial == '#':
- assert not token.endswith("\n")
- yield (COMMENT, token, spos, epos, line)
- elif token in triple_quoted:
- endprog = endprogs[token]
- endmatch = endprog.match(line, pos)
- if endmatch: # all on one line
- pos = endmatch.end(0)
- token = line[start:pos]
- yield (STRING, token, spos, (lnum, pos), line)
- else:
- strstart = (lnum, start) # multiple lines
- contstr = line[start:]
- contline = line
- break
- elif initial in single_quoted or \
- token[:2] in single_quoted or \
- token[:3] in single_quoted:
- if token[-1] == '\n': # continued string
- strstart = (lnum, start)
- endprog = (endprogs[initial] or endprogs[token[1]] or
- endprogs[token[2]])
- contstr, needcont = line[start:], 1
- contline = line
- break
- else: # ordinary string
- yield (STRING, token, spos, epos, line)
- elif initial in namechars: # ordinary name
- yield (NAME, token, spos, epos, line)
- elif initial == '\\': # continued stmt
- continued = 1
- else:
- if initial in '([{':
- parenlev += 1
- elif initial in ')]}':
- parenlev -= 1
- yield (OP, token, spos, epos, line)
- else:
- yield (ERRORTOKEN, line[pos],
- (lnum, pos), (lnum, pos+1), line)
- pos += 1
-
- for indent in indents[1:]: # pop remaining indent levels
- yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
- yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
-
-if __name__ == '__main__': # testing
- import sys
- if len(sys.argv) > 1:
- tokenize(open(sys.argv[1]).readline)
- else:
- tokenize(sys.stdin.readline)
+"""Patched version of standard library tokenize, to deal with various bugs.
+
+Patches
+
+- Relevant parts of Gareth Rees' patch for Python issue #12691 (untokenizing),
+ manually applied.
+- Newlines in comments and blank lines should be either NL or NEWLINE, depending
+ on whether they are in a multi-line statement. Filed as Python issue #17061.
+
+-------------------------------------------------------------------------------
+Tokenization help for Python programs.
+
+generate_tokens(readline) is a generator that breaks a stream of
+text into Python tokens. It accepts a readline-like method which is called
+repeatedly to get the next line of input (or "" for EOF). It generates
+5-tuples with these members:
+
+ the token type (see token.py)
+ the token (a string)
+ the starting (row, column) indices of the token (a 2-tuple of ints)
+ the ending (row, column) indices of the token (a 2-tuple of ints)
+ the original line (string)
+
+It is designed to match the working of the Python tokenizer exactly, except
+that it produces COMMENT tokens for comments and gives type OP for all
+operators
+
+Older entry points
+ tokenize_loop(readline, tokeneater)
+ tokenize(readline, tokeneater=printtoken)
+are the same, except instead of generating tokens, tokeneater is a callback
+function to which the 5 fields described above are passed as 5 arguments,
+each time a new token is found."""
+from __future__ import print_function
+
+__author__ = 'Ka-Ping Yee <ping@lfw.org>'
+__credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
+ 'Skip Montanaro, Raymond Hettinger')
+
+import string, re
+from token import *
+
+import token
+__all__ = [x for x in dir(token) if not x.startswith("_")]
+__all__ += ["COMMENT", "tokenize", "generate_tokens", "NL", "untokenize"]
+del x
+del token
+
+__all__ += ["TokenError"]
+
+COMMENT = N_TOKENS
+tok_name[COMMENT] = 'COMMENT'
+NL = N_TOKENS + 1
+tok_name[NL] = 'NL'
+N_TOKENS += 2
+
+def group(*choices): return '(' + '|'.join(choices) + ')'
+def any(*choices): return group(*choices) + '*'
+def maybe(*choices): return group(*choices) + '?'
+
+Whitespace = r'[ \f\t]*'
+Comment = r'#[^\r\n]*'
+Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
+Name = r'[a-zA-Z_]\w*'
+
+Hexnumber = r'0[xX][\da-fA-F]+[lL]?'
+Octnumber = r'(0[oO][0-7]+)|(0[0-7]*)[lL]?'
+Binnumber = r'0[bB][01]+[lL]?'
+Decnumber = r'[1-9]\d*[lL]?'
+Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
+Exponent = r'[eE][-+]?\d+'
+Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent)
+Expfloat = r'\d+' + Exponent
+Floatnumber = group(Pointfloat, Expfloat)
+Imagnumber = group(r'\d+[jJ]', Floatnumber + r'[jJ]')
+Number = group(Imagnumber, Floatnumber, Intnumber)
+
+# Tail end of ' string.
+Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
+# Tail end of " string.
+Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
+# Tail end of ''' string.
+Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
+# Tail end of """ string.
+Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
+Triple = group("[uUbB]?[rR]?'''", '[uUbB]?[rR]?"""')
+# Single-line ' or " string.
+String = group(r"[uUbB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
+ r'[uUbB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
+
+# Because of leftmost-then-longest match semantics, be sure to put the
+# longest operators first (e.g., if = came before ==, == would get
+# recognized as two instances of =).
+Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=",
+ r"//=?",
+ r"[+\-*/%&|^=<>]=?",
+ r"~")
+
+Bracket = '[][(){}]'
+Special = group(r'\r?\n', r'[:;.,`@]')
+Funny = group(Operator, Bracket, Special)
+
+PlainToken = group(Number, Funny, String, Name)
+Token = Ignore + PlainToken
+
+# First (or only) line of ' or " string.
+ContStr = group(r"[uUbB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
+ group("'", r'\\\r?\n'),
+ r'[uUbB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
+ group('"', r'\\\r?\n'))
+PseudoExtras = group(r'\\\r?\n', Comment, Triple)
+PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
+
+tokenprog, pseudoprog, single3prog, double3prog = map(
+ re.compile, (Token, PseudoToken, Single3, Double3))
+endprogs = {"'": re.compile(Single), '"': re.compile(Double),
+ "'''": single3prog, '"""': double3prog,
+ "r'''": single3prog, 'r"""': double3prog,
+ "u'''": single3prog, 'u"""': double3prog,
+ "ur'''": single3prog, 'ur"""': double3prog,
+ "R'''": single3prog, 'R"""': double3prog,
+ "U'''": single3prog, 'U"""': double3prog,
+ "uR'''": single3prog, 'uR"""': double3prog,
+ "Ur'''": single3prog, 'Ur"""': double3prog,
+ "UR'''": single3prog, 'UR"""': double3prog,
+ "b'''": single3prog, 'b"""': double3prog,
+ "br'''": single3prog, 'br"""': double3prog,
+ "B'''": single3prog, 'B"""': double3prog,
+ "bR'''": single3prog, 'bR"""': double3prog,
+ "Br'''": single3prog, 'Br"""': double3prog,
+ "BR'''": single3prog, 'BR"""': double3prog,
+ 'r': None, 'R': None, 'u': None, 'U': None,
+ 'b': None, 'B': None}
+
+triple_quoted = {}
+for t in ("'''", '"""',
+ "r'''", 'r"""', "R'''", 'R"""',
+ "u'''", 'u"""', "U'''", 'U"""',
+ "ur'''", 'ur"""', "Ur'''", 'Ur"""',
+ "uR'''", 'uR"""', "UR'''", 'UR"""',
+ "b'''", 'b"""', "B'''", 'B"""',
+ "br'''", 'br"""', "Br'''", 'Br"""',
+ "bR'''", 'bR"""', "BR'''", 'BR"""'):
+ triple_quoted[t] = t
+single_quoted = {}
+for t in ("'", '"',
+ "r'", 'r"', "R'", 'R"',
+ "u'", 'u"', "U'", 'U"',
+ "ur'", 'ur"', "Ur'", 'Ur"',
+ "uR'", 'uR"', "UR'", 'UR"',
+ "b'", 'b"', "B'", 'B"',
+ "br'", 'br"', "Br'", 'Br"',
+ "bR'", 'bR"', "BR'", 'BR"' ):
+ single_quoted[t] = t
+
+tabsize = 8
+
+class TokenError(Exception): pass
+
+class StopTokenizing(Exception): pass
+
+def printtoken(type, token, srow_scol, erow_ecol, line): # for testing
+ srow, scol = srow_scol
+ erow, ecol = erow_ecol
+ print("%d,%d-%d,%d:\t%s\t%s" % \
+ (srow, scol, erow, ecol, tok_name[type], repr(token)))
+
+def tokenize(readline, tokeneater=printtoken):
+ """
+ The tokenize() function accepts two parameters: one representing the
+ input stream, and one providing an output mechanism for tokenize().
+
+ The first parameter, readline, must be a callable object which provides
+ the same interface as the readline() method of built-in file objects.
+ Each call to the function should return one line of input as a string.
+
+ The second parameter, tokeneater, must also be a callable object. It is
+ called once for each token, with five arguments, corresponding to the
+ tuples generated by generate_tokens().
+ """
+ try:
+ tokenize_loop(readline, tokeneater)
+ except StopTokenizing:
+ pass
+
+# backwards compatible interface
+def tokenize_loop(readline, tokeneater):
+ for token_info in generate_tokens(readline):
+ tokeneater(*token_info)
+
+class Untokenizer:
+
+ def __init__(self):
+ self.tokens = []
+ self.prev_row = 1
+ self.prev_col = 0
+
+ def add_whitespace(self, start):
+ row, col = start
+ assert row >= self.prev_row
+ col_offset = col - self.prev_col
+ if col_offset > 0:
+ self.tokens.append(" " * col_offset)
+ elif row > self.prev_row and tok_type not in (NEWLINE, NL, ENDMARKER):
+ # Line was backslash-continued
+ self.tokens.append(" ")
+
+ def untokenize(self, tokens):
+ iterable = iter(tokens)
+ for t in iterable:
+ if len(t) == 2:
+ self.compat(t, iterable)
+ break
+ tok_type, token, start, end = t[:4]
+ self.add_whitespace(start)
+ self.tokens.append(token)
+ self.prev_row, self.prev_col = end
+ if tok_type in (NEWLINE, NL):
+ self.prev_row += 1
+ self.prev_col = 0
+ return "".join(self.tokens)
+
+ def compat(self, token, iterable):
+ # This import is here to avoid problems when the itertools
+ # module is not built yet and tokenize is imported.
+ from itertools import chain
+ startline = False
+ prevstring = False
+ indents = []
+ toks_append = self.tokens.append
+ for tok in chain([token], iterable):
+ toknum, tokval = tok[:2]
+
+ if toknum in (NAME, NUMBER):
+ tokval += ' '
+
+ # Insert a space between two consecutive strings
+ if toknum == STRING:
+ if prevstring:
+ tokval = ' ' + tokval
+ prevstring = True
+ else:
+ prevstring = False
+
+ if toknum == INDENT:
+ indents.append(tokval)
+ continue
+ elif toknum == DEDENT:
+ indents.pop()
+ continue
+ elif toknum in (NEWLINE, NL):
+ startline = True
+ elif startline and indents:
+ toks_append(indents[-1])
+ startline = False
+ toks_append(tokval)
+
+def untokenize(iterable):
+ """Transform tokens back into Python source code.
+
+ Each element returned by the iterable must be a token sequence
+ with at least two elements, a token number and token value. If
+ only two tokens are passed, the resulting output is poor.
+
+ Round-trip invariant for full input:
+ Untokenized source will match input source exactly
+
+ Round-trip invariant for limited intput:
+ # Output text will tokenize the back to the input
+ t1 = [tok[:2] for tok in generate_tokens(f.readline)]
+ newcode = untokenize(t1)
+ readline = iter(newcode.splitlines(1)).next
+ t2 = [tok[:2] for tok in generate_tokens(readline)]
+ assert t1 == t2
+ """
+ ut = Untokenizer()
+ return ut.untokenize(iterable)
+
+def generate_tokens(readline):
+ """
+ The generate_tokens() generator requires one argment, readline, which
+ must be a callable object which provides the same interface as the
+ readline() method of built-in file objects. Each call to the function
+ should return one line of input as a string. Alternately, readline
+ can be a callable function terminating with StopIteration:
+ readline = open(myfile).next # Example of alternate readline
+
+ The generator produces 5-tuples with these members: the token type; the
+ token string; a 2-tuple (srow, scol) of ints specifying the row and
+ column where the token begins in the source; a 2-tuple (erow, ecol) of
+ ints specifying the row and column where the token ends in the source;
+ and the line on which the token was found. The line passed is the
+ logical line; continuation lines are included.
+ """
+ lnum = parenlev = continued = 0
+ namechars, numchars = string.ascii_letters + '_', '0123456789'
+ contstr, needcont = '', 0
+ contline = None
+ indents = [0]
+
+ while 1: # loop over lines in stream
+ try:
+ line = readline()
+ except StopIteration:
+ line = ''
+ lnum += 1
+ pos, max = 0, len(line)
+
+ if contstr: # continued string
+ if not line:
+ raise TokenError("EOF in multi-line string", strstart)
+ endmatch = endprog.match(line)
+ if endmatch:
+ pos = end = endmatch.end(0)
+ yield (STRING, contstr + line[:end],
+ strstart, (lnum, end), contline + line)
+ contstr, needcont = '', 0
+ contline = None
+ elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
+ yield (ERRORTOKEN, contstr + line,
+ strstart, (lnum, len(line)), contline)
+ contstr = ''
+ contline = None
+ continue
+ else:
+ contstr = contstr + line
+ contline = contline + line
+ continue
+
+ elif parenlev == 0 and not continued: # new statement
+ if not line: break
+ column = 0
+ while pos < max: # measure leading whitespace
+ if line[pos] == ' ':
+ column += 1
+ elif line[pos] == '\t':
+ column = (column//tabsize + 1)*tabsize
+ elif line[pos] == '\f':
+ column = 0
+ else:
+ break
+ pos += 1
+ if pos == max:
+ break
+
+ if line[pos] in '#\r\n': # skip comments or blank lines
+ if line[pos] == '#':
+ comment_token = line[pos:].rstrip('\r\n')
+ nl_pos = pos + len(comment_token)
+ yield (COMMENT, comment_token,
+ (lnum, pos), (lnum, pos + len(comment_token)), line)
+ yield (NEWLINE, line[nl_pos:],
+ (lnum, nl_pos), (lnum, len(line)), line)
+ else:
+ yield (NEWLINE, line[pos:],
+ (lnum, pos), (lnum, len(line)), line)
+ continue
+
+ if column > indents[-1]: # count indents or dedents
+ indents.append(column)
+ yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
+ while column < indents[-1]:
+ if column not in indents:
+ raise IndentationError(
+ "unindent does not match any outer indentation level",
+ ("<tokenize>", lnum, pos, line))
+ indents = indents[:-1]
+ yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
+
+ else: # continued statement
+ if not line:
+ raise TokenError("EOF in multi-line statement", (lnum, 0))
+ continued = 0
+
+ while pos < max:
+ pseudomatch = pseudoprog.match(line, pos)
+ if pseudomatch: # scan for tokens
+ start, end = pseudomatch.span(1)
+ spos, epos, pos = (lnum, start), (lnum, end), end
+ token, initial = line[start:end], line[start]
+
+ if initial in numchars or \
+ (initial == '.' and token != '.'): # ordinary number
+ yield (NUMBER, token, spos, epos, line)
+ elif initial in '\r\n':
+ yield (NL if parenlev > 0 else NEWLINE,
+ token, spos, epos, line)
+ elif initial == '#':
+ assert not token.endswith("\n")
+ yield (COMMENT, token, spos, epos, line)
+ elif token in triple_quoted:
+ endprog = endprogs[token]
+ endmatch = endprog.match(line, pos)
+ if endmatch: # all on one line
+ pos = endmatch.end(0)
+ token = line[start:pos]
+ yield (STRING, token, spos, (lnum, pos), line)
+ else:
+ strstart = (lnum, start) # multiple lines
+ contstr = line[start:]
+ contline = line
+ break
+ elif initial in single_quoted or \
+ token[:2] in single_quoted or \
+ token[:3] in single_quoted:
+ if token[-1] == '\n': # continued string
+ strstart = (lnum, start)
+ endprog = (endprogs[initial] or endprogs[token[1]] or
+ endprogs[token[2]])
+ contstr, needcont = line[start:], 1
+ contline = line
+ break
+ else: # ordinary string
+ yield (STRING, token, spos, epos, line)
+ elif initial in namechars: # ordinary name
+ yield (NAME, token, spos, epos, line)
+ elif initial == '\\': # continued stmt
+ continued = 1
+ else:
+ if initial in '([{':
+ parenlev += 1
+ elif initial in ')]}':
+ parenlev -= 1
+ yield (OP, token, spos, epos, line)
+ else:
+ yield (ERRORTOKEN, line[pos],
+ (lnum, pos), (lnum, pos+1), line)
+ pos += 1
+
+ for indent in indents[1:]: # pop remaining indent levels
+ yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
+ yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
+
+if __name__ == '__main__': # testing
+ import sys
+ if len(sys.argv) > 1:
+ tokenize(open(sys.argv[1]).readline)
+ else:
+ tokenize(sys.stdin.readline)
diff --git a/contrib/python/ipython/py2/IPython/utils/_tokenize_py3.py b/contrib/python/ipython/py2/IPython/utils/_tokenize_py3.py
index ca85023c32..ee1fd9e639 100644
--- a/contrib/python/ipython/py2/IPython/utils/_tokenize_py3.py
+++ b/contrib/python/ipython/py2/IPython/utils/_tokenize_py3.py
@@ -1,595 +1,595 @@
-"""Patched version of standard library tokenize, to deal with various bugs.
-
-Based on Python 3.2 code.
-
-Patches:
-
-- Gareth Rees' patch for Python issue #12691 (untokenizing)
- - Except we don't encode the output of untokenize
- - Python 2 compatible syntax, so that it can be byte-compiled at installation
-- Newlines in comments and blank lines should be either NL or NEWLINE, depending
- on whether they are in a multi-line statement. Filed as Python issue #17061.
-- Export generate_tokens & TokenError
-- u and rb literals are allowed under Python 3.3 and above.
-
-------------------------------------------------------------------------------
-Tokenization help for Python programs.
-
-tokenize(readline) is a generator that breaks a stream of bytes into
-Python tokens. It decodes the bytes according to PEP-0263 for
-determining source file encoding.
-
-It accepts a readline-like method which is called repeatedly to get the
-next line of input (or b"" for EOF). It generates 5-tuples with these
-members:
-
- the token type (see token.py)
- the token (a string)
- the starting (row, column) indices of the token (a 2-tuple of ints)
- the ending (row, column) indices of the token (a 2-tuple of ints)
- the original line (string)
-
-It is designed to match the working of the Python tokenizer exactly, except
-that it produces COMMENT tokens for comments and gives type OP for all
-operators. Additionally, all token lists start with an ENCODING token
-which tells you which encoding was used to decode the bytes stream.
-"""
-from __future__ import absolute_import
-
-__author__ = 'Ka-Ping Yee <ping@lfw.org>'
-__credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
- 'Skip Montanaro, Raymond Hettinger, Trent Nelson, '
- 'Michael Foord')
-import builtins
-import re
-import sys
-from token import *
-from codecs import lookup, BOM_UTF8
-import collections
-from io import TextIOWrapper
-cookie_re = re.compile("coding[:=]\s*([-\w.]+)")
-
-import token
-__all__ = token.__all__ + ["COMMENT", "tokenize", "detect_encoding",
- "NL", "untokenize", "ENCODING", "TokenInfo"]
-del token
-
-__all__ += ["generate_tokens", "TokenError"]
-
-COMMENT = N_TOKENS
-tok_name[COMMENT] = 'COMMENT'
-NL = N_TOKENS + 1
-tok_name[NL] = 'NL'
-ENCODING = N_TOKENS + 2
-tok_name[ENCODING] = 'ENCODING'
-N_TOKENS += 3
-
-class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
- def __repr__(self):
- annotated_type = '%d (%s)' % (self.type, tok_name[self.type])
- return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' %
- self._replace(type=annotated_type))
-
-def group(*choices): return '(' + '|'.join(choices) + ')'
-def any(*choices): return group(*choices) + '*'
-def maybe(*choices): return group(*choices) + '?'
-
-# Note: we use unicode matching for names ("\w") but ascii matching for
-# number literals.
-Whitespace = r'[ \f\t]*'
-Comment = r'#[^\r\n]*'
-Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
-Name = r'\w+'
-
-Hexnumber = r'0[xX][0-9a-fA-F]+'
-Binnumber = r'0[bB][01]+'
-Octnumber = r'0[oO][0-7]+'
-Decnumber = r'(?:0+|[1-9][0-9]*)'
-Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
-Exponent = r'[eE][-+]?[0-9]+'
-Pointfloat = group(r'[0-9]+\.[0-9]*', r'\.[0-9]+') + maybe(Exponent)
-Expfloat = r'[0-9]+' + Exponent
-Floatnumber = group(Pointfloat, Expfloat)
-Imagnumber = group(r'[0-9]+[jJ]', Floatnumber + r'[jJ]')
-Number = group(Imagnumber, Floatnumber, Intnumber)
-
-if sys.version_info.minor >= 3:
- StringPrefix = r'(?:[bB][rR]?|[rR][bB]?|[uU])?'
-else:
- StringPrefix = r'(?:[bB]?[rR]?)?'
-
-# Tail end of ' string.
-Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
-# Tail end of " string.
-Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
-# Tail end of ''' string.
-Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
-# Tail end of """ string.
-Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
-Triple = group(StringPrefix + "'''", StringPrefix + '"""')
-# Single-line ' or " string.
-String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
- StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
-
-# Because of leftmost-then-longest match semantics, be sure to put the
-# longest operators first (e.g., if = came before ==, == would get
-# recognized as two instances of =).
-Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=",
- r"//=?", r"->",
- r"[+\-*/%&|^=<>]=?",
- r"~")
-
-Bracket = '[][(){}]'
-Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]')
-Funny = group(Operator, Bracket, Special)
-
-PlainToken = group(Number, Funny, String, Name)
-Token = Ignore + PlainToken
-
-# First (or only) line of ' or " string.
-ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
- group("'", r'\\\r?\n'),
- StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
- group('"', r'\\\r?\n'))
-PseudoExtras = group(r'\\\r?\n', Comment, Triple)
-PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
-
-def _compile(expr):
- return re.compile(expr, re.UNICODE)
-
-tokenprog, pseudoprog, single3prog, double3prog = map(
- _compile, (Token, PseudoToken, Single3, Double3))
-endprogs = {"'": _compile(Single), '"': _compile(Double),
- "'''": single3prog, '"""': double3prog,
- "r'''": single3prog, 'r"""': double3prog,
- "b'''": single3prog, 'b"""': double3prog,
- "R'''": single3prog, 'R"""': double3prog,
- "B'''": single3prog, 'B"""': double3prog,
- "br'''": single3prog, 'br"""': double3prog,
- "bR'''": single3prog, 'bR"""': double3prog,
- "Br'''": single3prog, 'Br"""': double3prog,
- "BR'''": single3prog, 'BR"""': double3prog,
- 'r': None, 'R': None, 'b': None, 'B': None}
-
-triple_quoted = {}
-for t in ("'''", '"""',
- "r'''", 'r"""', "R'''", 'R"""',
- "b'''", 'b"""', "B'''", 'B"""',
- "br'''", 'br"""', "Br'''", 'Br"""',
- "bR'''", 'bR"""', "BR'''", 'BR"""'):
- triple_quoted[t] = t
-single_quoted = {}
-for t in ("'", '"',
- "r'", 'r"', "R'", 'R"',
- "b'", 'b"', "B'", 'B"',
- "br'", 'br"', "Br'", 'Br"',
- "bR'", 'bR"', "BR'", 'BR"' ):
- single_quoted[t] = t
-
-if sys.version_info.minor >= 3:
- # Python 3.3
- for _prefix in ['rb', 'rB', 'Rb', 'RB', 'u', 'U']:
- _t2 = _prefix+'"""'
- endprogs[_t2] = double3prog
- triple_quoted[_t2] = _t2
- _t1 = _prefix + "'''"
- endprogs[_t1] = single3prog
- triple_quoted[_t1] = _t1
- single_quoted[_prefix+'"'] = _prefix+'"'
- single_quoted[_prefix+"'"] = _prefix+"'"
- del _prefix, _t2, _t1
- endprogs['u'] = None
- endprogs['U'] = None
-
-del _compile
-
-tabsize = 8
-
-class TokenError(Exception): pass
-
-class StopTokenizing(Exception): pass
-
-
-class Untokenizer:
-
- def __init__(self):
- self.tokens = []
- self.prev_row = 1
- self.prev_col = 0
- self.encoding = 'utf-8'
-
- def add_whitespace(self, tok_type, start):
- row, col = start
- assert row >= self.prev_row
- col_offset = col - self.prev_col
- if col_offset > 0:
- self.tokens.append(" " * col_offset)
- elif row > self.prev_row and tok_type not in (NEWLINE, NL, ENDMARKER):
- # Line was backslash-continued.
- self.tokens.append(" ")
-
- def untokenize(self, tokens):
- iterable = iter(tokens)
- for t in iterable:
- if len(t) == 2:
- self.compat(t, iterable)
- break
- tok_type, token, start, end = t[:4]
- if tok_type == ENCODING:
- self.encoding = token
- continue
- self.add_whitespace(tok_type, start)
- self.tokens.append(token)
- self.prev_row, self.prev_col = end
- if tok_type in (NEWLINE, NL):
- self.prev_row += 1
- self.prev_col = 0
- return "".join(self.tokens)
-
- def compat(self, token, iterable):
- # This import is here to avoid problems when the itertools
- # module is not built yet and tokenize is imported.
- from itertools import chain
- startline = False
- prevstring = False
- indents = []
- toks_append = self.tokens.append
-
- for tok in chain([token], iterable):
- toknum, tokval = tok[:2]
- if toknum == ENCODING:
- self.encoding = tokval
- continue
-
- if toknum in (NAME, NUMBER):
- tokval += ' '
-
- # Insert a space between two consecutive strings
- if toknum == STRING:
- if prevstring:
- tokval = ' ' + tokval
- prevstring = True
- else:
- prevstring = False
-
- if toknum == INDENT:
- indents.append(tokval)
- continue
- elif toknum == DEDENT:
- indents.pop()
- continue
- elif toknum in (NEWLINE, NL):
- startline = True
- elif startline and indents:
- toks_append(indents[-1])
- startline = False
- toks_append(tokval)
-
-
-def untokenize(tokens):
- """
- Convert ``tokens`` (an iterable) back into Python source code. Return
- a bytes object, encoded using the encoding specified by the last
- ENCODING token in ``tokens``, or UTF-8 if no ENCODING token is found.
-
- The result is guaranteed to tokenize back to match the input so that
- the conversion is lossless and round-trips are assured. The
- guarantee applies only to the token type and token string as the
- spacing between tokens (column positions) may change.
-
- :func:`untokenize` has two modes. If the input tokens are sequences
- of length 2 (``type``, ``string``) then spaces are added as necessary to
- preserve the round-trip property.
-
- If the input tokens are sequences of length 4 or more (``type``,
- ``string``, ``start``, ``end``), as returned by :func:`tokenize`, then
- spaces are added so that each token appears in the result at the
- position indicated by ``start`` and ``end``, if possible.
- """
- return Untokenizer().untokenize(tokens)
-
-
-def _get_normal_name(orig_enc):
- """Imitates get_normal_name in tokenizer.c."""
- # Only care about the first 12 characters.
- enc = orig_enc[:12].lower().replace("_", "-")
- if enc == "utf-8" or enc.startswith("utf-8-"):
- return "utf-8"
- if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
- enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
- return "iso-8859-1"
- return orig_enc
-
-def detect_encoding(readline):
- """
- The detect_encoding() function is used to detect the encoding that should
- be used to decode a Python source file. It requires one argment, readline,
- in the same way as the tokenize() generator.
-
- It will call readline a maximum of twice, and return the encoding used
- (as a string) and a list of any lines (left as bytes) it has read in.
-
- It detects the encoding from the presence of a utf-8 bom or an encoding
- cookie as specified in pep-0263. If both a bom and a cookie are present,
- but disagree, a SyntaxError will be raised. If the encoding cookie is an
- invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
- 'utf-8-sig' is returned.
-
- If no encoding is specified, then the default of 'utf-8' will be returned.
- """
- bom_found = False
- encoding = None
- default = 'utf-8'
- def read_or_stop():
- try:
- return readline()
- except StopIteration:
- return b''
-
- def find_cookie(line):
- try:
- # Decode as UTF-8. Either the line is an encoding declaration,
- # in which case it should be pure ASCII, or it must be UTF-8
- # per default encoding.
- line_string = line.decode('utf-8')
- except UnicodeDecodeError:
- raise SyntaxError("invalid or missing encoding declaration")
-
- matches = cookie_re.findall(line_string)
- if not matches:
- return None
- encoding = _get_normal_name(matches[0])
- try:
- codec = lookup(encoding)
- except LookupError:
- # This behaviour mimics the Python interpreter
- raise SyntaxError("unknown encoding: " + encoding)
-
- if bom_found:
- if encoding != 'utf-8':
- # This behaviour mimics the Python interpreter
- raise SyntaxError('encoding problem: utf-8')
- encoding += '-sig'
- return encoding
-
- first = read_or_stop()
- if first.startswith(BOM_UTF8):
- bom_found = True
- first = first[3:]
- default = 'utf-8-sig'
- if not first:
- return default, []
-
- encoding = find_cookie(first)
- if encoding:
- return encoding, [first]
-
- second = read_or_stop()
- if not second:
- return default, [first]
-
- encoding = find_cookie(second)
- if encoding:
- return encoding, [first, second]
-
- return default, [first, second]
-
-
-def open(filename):
- """Open a file in read only mode using the encoding detected by
- detect_encoding().
- """
- buffer = builtins.open(filename, 'rb')
- encoding, lines = detect_encoding(buffer.readline)
- buffer.seek(0)
- text = TextIOWrapper(buffer, encoding, line_buffering=True)
- text.mode = 'r'
- return text
-
-
-def tokenize(readline):
- """
- The tokenize() generator requires one argment, readline, which
- must be a callable object which provides the same interface as the
- readline() method of built-in file objects. Each call to the function
- should return one line of input as bytes. Alternately, readline
- can be a callable function terminating with StopIteration:
- readline = open(myfile, 'rb').__next__ # Example of alternate readline
-
- The generator produces 5-tuples with these members: the token type; the
- token string; a 2-tuple (srow, scol) of ints specifying the row and
- column where the token begins in the source; a 2-tuple (erow, ecol) of
- ints specifying the row and column where the token ends in the source;
- and the line on which the token was found. The line passed is the
- logical line; continuation lines are included.
-
- The first token sequence will always be an ENCODING token
- which tells you which encoding was used to decode the bytes stream.
- """
- # This import is here to avoid problems when the itertools module is not
- # built yet and tokenize is imported.
- from itertools import chain, repeat
- encoding, consumed = detect_encoding(readline)
- rl_gen = iter(readline, b"")
- empty = repeat(b"")
- return _tokenize(chain(consumed, rl_gen, empty).__next__, encoding)
-
-
-def _tokenize(readline, encoding):
- lnum = parenlev = continued = 0
- numchars = '0123456789'
- contstr, needcont = '', 0
- contline = None
- indents = [0]
-
- if encoding is not None:
- if encoding == "utf-8-sig":
- # BOM will already have been stripped.
- encoding = "utf-8"
- yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
- while True: # loop over lines in stream
- try:
- line = readline()
- except StopIteration:
- line = b''
-
- if encoding is not None:
- line = line.decode(encoding)
- lnum += 1
- pos, max = 0, len(line)
-
- if contstr: # continued string
- if not line:
- raise TokenError("EOF in multi-line string", strstart)
- endmatch = endprog.match(line)
- if endmatch:
- pos = end = endmatch.end(0)
- yield TokenInfo(STRING, contstr + line[:end],
- strstart, (lnum, end), contline + line)
- contstr, needcont = '', 0
- contline = None
- elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
- yield TokenInfo(ERRORTOKEN, contstr + line,
- strstart, (lnum, len(line)), contline)
- contstr = ''
- contline = None
- continue
- else:
- contstr = contstr + line
- contline = contline + line
- continue
-
- elif parenlev == 0 and not continued: # new statement
- if not line: break
- column = 0
- while pos < max: # measure leading whitespace
- if line[pos] == ' ':
- column += 1
- elif line[pos] == '\t':
- column = (column//tabsize + 1)*tabsize
- elif line[pos] == '\f':
- column = 0
- else:
- break
- pos += 1
- if pos == max:
- break
-
- if line[pos] in '#\r\n': # skip comments or blank lines
- if line[pos] == '#':
- comment_token = line[pos:].rstrip('\r\n')
- nl_pos = pos + len(comment_token)
- yield TokenInfo(COMMENT, comment_token,
- (lnum, pos), (lnum, pos + len(comment_token)), line)
- yield TokenInfo(NEWLINE, line[nl_pos:],
- (lnum, nl_pos), (lnum, len(line)), line)
- else:
- yield TokenInfo(NEWLINE, line[pos:],
- (lnum, pos), (lnum, len(line)), line)
- continue
-
- if column > indents[-1]: # count indents or dedents
- indents.append(column)
- yield TokenInfo(INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
- while column < indents[-1]:
- if column not in indents:
- raise IndentationError(
- "unindent does not match any outer indentation level",
- ("<tokenize>", lnum, pos, line))
- indents = indents[:-1]
- yield TokenInfo(DEDENT, '', (lnum, pos), (lnum, pos), line)
-
- else: # continued statement
- if not line:
- raise TokenError("EOF in multi-line statement", (lnum, 0))
- continued = 0
-
- while pos < max:
- pseudomatch = pseudoprog.match(line, pos)
- if pseudomatch: # scan for tokens
- start, end = pseudomatch.span(1)
- spos, epos, pos = (lnum, start), (lnum, end), end
- token, initial = line[start:end], line[start]
-
- if (initial in numchars or # ordinary number
- (initial == '.' and token != '.' and token != '...')):
- yield TokenInfo(NUMBER, token, spos, epos, line)
- elif initial in '\r\n':
- yield TokenInfo(NL if parenlev > 0 else NEWLINE,
- token, spos, epos, line)
- elif initial == '#':
- assert not token.endswith("\n")
- yield TokenInfo(COMMENT, token, spos, epos, line)
- elif token in triple_quoted:
- endprog = endprogs[token]
- endmatch = endprog.match(line, pos)
- if endmatch: # all on one line
- pos = endmatch.end(0)
- token = line[start:pos]
- yield TokenInfo(STRING, token, spos, (lnum, pos), line)
- else:
- strstart = (lnum, start) # multiple lines
- contstr = line[start:]
- contline = line
- break
- elif initial in single_quoted or \
- token[:2] in single_quoted or \
- token[:3] in single_quoted:
- if token[-1] == '\n': # continued string
- strstart = (lnum, start)
- endprog = (endprogs[initial] or endprogs[token[1]] or
- endprogs[token[2]])
- contstr, needcont = line[start:], 1
- contline = line
- break
- else: # ordinary string
- yield TokenInfo(STRING, token, spos, epos, line)
- elif initial.isidentifier(): # ordinary name
- yield TokenInfo(NAME, token, spos, epos, line)
- elif initial == '\\': # continued stmt
- continued = 1
- else:
- if initial in '([{':
- parenlev += 1
- elif initial in ')]}':
- parenlev -= 1
- yield TokenInfo(OP, token, spos, epos, line)
- else:
- yield TokenInfo(ERRORTOKEN, line[pos],
- (lnum, pos), (lnum, pos+1), line)
- pos += 1
-
- for indent in indents[1:]: # pop remaining indent levels
- yield TokenInfo(DEDENT, '', (lnum, 0), (lnum, 0), '')
- yield TokenInfo(ENDMARKER, '', (lnum, 0), (lnum, 0), '')
-
-
-# An undocumented, backwards compatible, API for all the places in the standard
-# library that expect to be able to use tokenize with strings
-def generate_tokens(readline):
- return _tokenize(readline, None)
-
-if __name__ == "__main__":
- # Quick sanity check
- s = b'''def parseline(self, line):
- """Parse the line into a command name and a string containing
- the arguments. Returns a tuple containing (command, args, line).
- 'command' and 'args' may be None if the line couldn't be parsed.
- """
- line = line.strip()
- if not line:
- return None, None, line
- elif line[0] == '?':
- line = 'help ' + line[1:]
- elif line[0] == '!':
- if hasattr(self, 'do_shell'):
- line = 'shell ' + line[1:]
- else:
- return None, None, line
- i, n = 0, len(line)
- while i < n and line[i] in self.identchars: i = i+1
- cmd, arg = line[:i], line[i:].strip()
- return cmd, arg, line
- '''
- for tok in tokenize(iter(s.splitlines()).__next__):
- print(tok)
+"""Patched version of standard library tokenize, to deal with various bugs.
+
+Based on Python 3.2 code.
+
+Patches:
+
+- Gareth Rees' patch for Python issue #12691 (untokenizing)
+ - Except we don't encode the output of untokenize
+ - Python 2 compatible syntax, so that it can be byte-compiled at installation
+- Newlines in comments and blank lines should be either NL or NEWLINE, depending
+ on whether they are in a multi-line statement. Filed as Python issue #17061.
+- Export generate_tokens & TokenError
+- u and rb literals are allowed under Python 3.3 and above.
+
+------------------------------------------------------------------------------
+Tokenization help for Python programs.
+
+tokenize(readline) is a generator that breaks a stream of bytes into
+Python tokens. It decodes the bytes according to PEP-0263 for
+determining source file encoding.
+
+It accepts a readline-like method which is called repeatedly to get the
+next line of input (or b"" for EOF). It generates 5-tuples with these
+members:
+
+ the token type (see token.py)
+ the token (a string)
+ the starting (row, column) indices of the token (a 2-tuple of ints)
+ the ending (row, column) indices of the token (a 2-tuple of ints)
+ the original line (string)
+
+It is designed to match the working of the Python tokenizer exactly, except
+that it produces COMMENT tokens for comments and gives type OP for all
+operators. Additionally, all token lists start with an ENCODING token
+which tells you which encoding was used to decode the bytes stream.
+"""
+from __future__ import absolute_import
+
+__author__ = 'Ka-Ping Yee <ping@lfw.org>'
+__credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
+ 'Skip Montanaro, Raymond Hettinger, Trent Nelson, '
+ 'Michael Foord')
+import builtins
+import re
+import sys
+from token import *
+from codecs import lookup, BOM_UTF8
+import collections
+from io import TextIOWrapper
+cookie_re = re.compile("coding[:=]\s*([-\w.]+)")
+
+import token
+__all__ = token.__all__ + ["COMMENT", "tokenize", "detect_encoding",
+ "NL", "untokenize", "ENCODING", "TokenInfo"]
+del token
+
+__all__ += ["generate_tokens", "TokenError"]
+
+COMMENT = N_TOKENS
+tok_name[COMMENT] = 'COMMENT'
+NL = N_TOKENS + 1
+tok_name[NL] = 'NL'
+ENCODING = N_TOKENS + 2
+tok_name[ENCODING] = 'ENCODING'
+N_TOKENS += 3
+
+class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
+ def __repr__(self):
+ annotated_type = '%d (%s)' % (self.type, tok_name[self.type])
+ return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' %
+ self._replace(type=annotated_type))
+
+def group(*choices): return '(' + '|'.join(choices) + ')'
+def any(*choices): return group(*choices) + '*'
+def maybe(*choices): return group(*choices) + '?'
+
+# Note: we use unicode matching for names ("\w") but ascii matching for
+# number literals.
+Whitespace = r'[ \f\t]*'
+Comment = r'#[^\r\n]*'
+Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
+Name = r'\w+'
+
+Hexnumber = r'0[xX][0-9a-fA-F]+'
+Binnumber = r'0[bB][01]+'
+Octnumber = r'0[oO][0-7]+'
+Decnumber = r'(?:0+|[1-9][0-9]*)'
+Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
+Exponent = r'[eE][-+]?[0-9]+'
+Pointfloat = group(r'[0-9]+\.[0-9]*', r'\.[0-9]+') + maybe(Exponent)
+Expfloat = r'[0-9]+' + Exponent
+Floatnumber = group(Pointfloat, Expfloat)
+Imagnumber = group(r'[0-9]+[jJ]', Floatnumber + r'[jJ]')
+Number = group(Imagnumber, Floatnumber, Intnumber)
+
+if sys.version_info.minor >= 3:
+ StringPrefix = r'(?:[bB][rR]?|[rR][bB]?|[uU])?'
+else:
+ StringPrefix = r'(?:[bB]?[rR]?)?'
+
+# Tail end of ' string.
+Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
+# Tail end of " string.
+Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
+# Tail end of ''' string.
+Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
+# Tail end of """ string.
+Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
+Triple = group(StringPrefix + "'''", StringPrefix + '"""')
+# Single-line ' or " string.
+String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
+ StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
+
+# Because of leftmost-then-longest match semantics, be sure to put the
+# longest operators first (e.g., if = came before ==, == would get
+# recognized as two instances of =).
+Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=",
+ r"//=?", r"->",
+ r"[+\-*/%&|^=<>]=?",
+ r"~")
+
+Bracket = '[][(){}]'
+Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]')
+Funny = group(Operator, Bracket, Special)
+
+PlainToken = group(Number, Funny, String, Name)
+Token = Ignore + PlainToken
+
+# First (or only) line of ' or " string.
+ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
+ group("'", r'\\\r?\n'),
+ StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
+ group('"', r'\\\r?\n'))
+PseudoExtras = group(r'\\\r?\n', Comment, Triple)
+PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
+
+def _compile(expr):
+ return re.compile(expr, re.UNICODE)
+
+tokenprog, pseudoprog, single3prog, double3prog = map(
+ _compile, (Token, PseudoToken, Single3, Double3))
+endprogs = {"'": _compile(Single), '"': _compile(Double),
+ "'''": single3prog, '"""': double3prog,
+ "r'''": single3prog, 'r"""': double3prog,
+ "b'''": single3prog, 'b"""': double3prog,
+ "R'''": single3prog, 'R"""': double3prog,
+ "B'''": single3prog, 'B"""': double3prog,
+ "br'''": single3prog, 'br"""': double3prog,
+ "bR'''": single3prog, 'bR"""': double3prog,
+ "Br'''": single3prog, 'Br"""': double3prog,
+ "BR'''": single3prog, 'BR"""': double3prog,
+ 'r': None, 'R': None, 'b': None, 'B': None}
+
+triple_quoted = {}
+for t in ("'''", '"""',
+ "r'''", 'r"""', "R'''", 'R"""',
+ "b'''", 'b"""', "B'''", 'B"""',
+ "br'''", 'br"""', "Br'''", 'Br"""',
+ "bR'''", 'bR"""', "BR'''", 'BR"""'):
+ triple_quoted[t] = t
+single_quoted = {}
+for t in ("'", '"',
+ "r'", 'r"', "R'", 'R"',
+ "b'", 'b"', "B'", 'B"',
+ "br'", 'br"', "Br'", 'Br"',
+ "bR'", 'bR"', "BR'", 'BR"' ):
+ single_quoted[t] = t
+
+if sys.version_info.minor >= 3:
+ # Python 3.3
+ for _prefix in ['rb', 'rB', 'Rb', 'RB', 'u', 'U']:
+ _t2 = _prefix+'"""'
+ endprogs[_t2] = double3prog
+ triple_quoted[_t2] = _t2
+ _t1 = _prefix + "'''"
+ endprogs[_t1] = single3prog
+ triple_quoted[_t1] = _t1
+ single_quoted[_prefix+'"'] = _prefix+'"'
+ single_quoted[_prefix+"'"] = _prefix+"'"
+ del _prefix, _t2, _t1
+ endprogs['u'] = None
+ endprogs['U'] = None
+
+del _compile
+
+tabsize = 8
+
+class TokenError(Exception): pass
+
+class StopTokenizing(Exception): pass
+
+
+class Untokenizer:
+
+ def __init__(self):
+ self.tokens = []
+ self.prev_row = 1
+ self.prev_col = 0
+ self.encoding = 'utf-8'
+
+ def add_whitespace(self, tok_type, start):
+ row, col = start
+ assert row >= self.prev_row
+ col_offset = col - self.prev_col
+ if col_offset > 0:
+ self.tokens.append(" " * col_offset)
+ elif row > self.prev_row and tok_type not in (NEWLINE, NL, ENDMARKER):
+ # Line was backslash-continued.
+ self.tokens.append(" ")
+
+ def untokenize(self, tokens):
+ iterable = iter(tokens)
+ for t in iterable:
+ if len(t) == 2:
+ self.compat(t, iterable)
+ break
+ tok_type, token, start, end = t[:4]
+ if tok_type == ENCODING:
+ self.encoding = token
+ continue
+ self.add_whitespace(tok_type, start)
+ self.tokens.append(token)
+ self.prev_row, self.prev_col = end
+ if tok_type in (NEWLINE, NL):
+ self.prev_row += 1
+ self.prev_col = 0
+ return "".join(self.tokens)
+
+ def compat(self, token, iterable):
+ # This import is here to avoid problems when the itertools
+ # module is not built yet and tokenize is imported.
+ from itertools import chain
+ startline = False
+ prevstring = False
+ indents = []
+ toks_append = self.tokens.append
+
+ for tok in chain([token], iterable):
+ toknum, tokval = tok[:2]
+ if toknum == ENCODING:
+ self.encoding = tokval
+ continue
+
+ if toknum in (NAME, NUMBER):
+ tokval += ' '
+
+ # Insert a space between two consecutive strings
+ if toknum == STRING:
+ if prevstring:
+ tokval = ' ' + tokval
+ prevstring = True
+ else:
+ prevstring = False
+
+ if toknum == INDENT:
+ indents.append(tokval)
+ continue
+ elif toknum == DEDENT:
+ indents.pop()
+ continue
+ elif toknum in (NEWLINE, NL):
+ startline = True
+ elif startline and indents:
+ toks_append(indents[-1])
+ startline = False
+ toks_append(tokval)
+
+
+def untokenize(tokens):
+ """
+ Convert ``tokens`` (an iterable) back into Python source code. Return
+ a bytes object, encoded using the encoding specified by the last
+ ENCODING token in ``tokens``, or UTF-8 if no ENCODING token is found.
+
+ The result is guaranteed to tokenize back to match the input so that
+ the conversion is lossless and round-trips are assured. The
+ guarantee applies only to the token type and token string as the
+ spacing between tokens (column positions) may change.
+
+ :func:`untokenize` has two modes. If the input tokens are sequences
+ of length 2 (``type``, ``string``) then spaces are added as necessary to
+ preserve the round-trip property.
+
+ If the input tokens are sequences of length 4 or more (``type``,
+ ``string``, ``start``, ``end``), as returned by :func:`tokenize`, then
+ spaces are added so that each token appears in the result at the
+ position indicated by ``start`` and ``end``, if possible.
+ """
+ return Untokenizer().untokenize(tokens)
+
+
+def _get_normal_name(orig_enc):
+ """Imitates get_normal_name in tokenizer.c."""
+ # Only care about the first 12 characters.
+ enc = orig_enc[:12].lower().replace("_", "-")
+ if enc == "utf-8" or enc.startswith("utf-8-"):
+ return "utf-8"
+ if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
+ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
+ return "iso-8859-1"
+ return orig_enc
+
+def detect_encoding(readline):
+ """
+ The detect_encoding() function is used to detect the encoding that should
+ be used to decode a Python source file. It requires one argment, readline,
+ in the same way as the tokenize() generator.
+
+ It will call readline a maximum of twice, and return the encoding used
+ (as a string) and a list of any lines (left as bytes) it has read in.
+
+ It detects the encoding from the presence of a utf-8 bom or an encoding
+ cookie as specified in pep-0263. If both a bom and a cookie are present,
+ but disagree, a SyntaxError will be raised. If the encoding cookie is an
+ invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
+ 'utf-8-sig' is returned.
+
+ If no encoding is specified, then the default of 'utf-8' will be returned.
+ """
+ bom_found = False
+ encoding = None
+ default = 'utf-8'
+ def read_or_stop():
+ try:
+ return readline()
+ except StopIteration:
+ return b''
+
+ def find_cookie(line):
+ try:
+ # Decode as UTF-8. Either the line is an encoding declaration,
+ # in which case it should be pure ASCII, or it must be UTF-8
+ # per default encoding.
+ line_string = line.decode('utf-8')
+ except UnicodeDecodeError:
+ raise SyntaxError("invalid or missing encoding declaration")
+
+ matches = cookie_re.findall(line_string)
+ if not matches:
+ return None
+ encoding = _get_normal_name(matches[0])
+ try:
+ codec = lookup(encoding)
+ except LookupError:
+ # This behaviour mimics the Python interpreter
+ raise SyntaxError("unknown encoding: " + encoding)
+
+ if bom_found:
+ if encoding != 'utf-8':
+ # This behaviour mimics the Python interpreter
+ raise SyntaxError('encoding problem: utf-8')
+ encoding += '-sig'
+ return encoding
+
+ first = read_or_stop()
+ if first.startswith(BOM_UTF8):
+ bom_found = True
+ first = first[3:]
+ default = 'utf-8-sig'
+ if not first:
+ return default, []
+
+ encoding = find_cookie(first)
+ if encoding:
+ return encoding, [first]
+
+ second = read_or_stop()
+ if not second:
+ return default, [first]
+
+ encoding = find_cookie(second)
+ if encoding:
+ return encoding, [first, second]
+
+ return default, [first, second]
+
+
+def open(filename):
+ """Open a file in read only mode using the encoding detected by
+ detect_encoding().
+ """
+ buffer = builtins.open(filename, 'rb')
+ encoding, lines = detect_encoding(buffer.readline)
+ buffer.seek(0)
+ text = TextIOWrapper(buffer, encoding, line_buffering=True)
+ text.mode = 'r'
+ return text
+
+
+def tokenize(readline):
+ """
+ The tokenize() generator requires one argment, readline, which
+ must be a callable object which provides the same interface as the
+ readline() method of built-in file objects. Each call to the function
+ should return one line of input as bytes. Alternately, readline
+ can be a callable function terminating with StopIteration:
+ readline = open(myfile, 'rb').__next__ # Example of alternate readline
+
+ The generator produces 5-tuples with these members: the token type; the
+ token string; a 2-tuple (srow, scol) of ints specifying the row and
+ column where the token begins in the source; a 2-tuple (erow, ecol) of
+ ints specifying the row and column where the token ends in the source;
+ and the line on which the token was found. The line passed is the
+ logical line; continuation lines are included.
+
+ The first token sequence will always be an ENCODING token
+ which tells you which encoding was used to decode the bytes stream.
+ """
+ # This import is here to avoid problems when the itertools module is not
+ # built yet and tokenize is imported.
+ from itertools import chain, repeat
+ encoding, consumed = detect_encoding(readline)
+ rl_gen = iter(readline, b"")
+ empty = repeat(b"")
+ return _tokenize(chain(consumed, rl_gen, empty).__next__, encoding)
+
+
+def _tokenize(readline, encoding):
+ lnum = parenlev = continued = 0
+ numchars = '0123456789'
+ contstr, needcont = '', 0
+ contline = None
+ indents = [0]
+
+ if encoding is not None:
+ if encoding == "utf-8-sig":
+ # BOM will already have been stripped.
+ encoding = "utf-8"
+ yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
+ while True: # loop over lines in stream
+ try:
+ line = readline()
+ except StopIteration:
+ line = b''
+
+ if encoding is not None:
+ line = line.decode(encoding)
+ lnum += 1
+ pos, max = 0, len(line)
+
+ if contstr: # continued string
+ if not line:
+ raise TokenError("EOF in multi-line string", strstart)
+ endmatch = endprog.match(line)
+ if endmatch:
+ pos = end = endmatch.end(0)
+ yield TokenInfo(STRING, contstr + line[:end],
+ strstart, (lnum, end), contline + line)
+ contstr, needcont = '', 0
+ contline = None
+ elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
+ yield TokenInfo(ERRORTOKEN, contstr + line,
+ strstart, (lnum, len(line)), contline)
+ contstr = ''
+ contline = None
+ continue
+ else:
+ contstr = contstr + line
+ contline = contline + line
+ continue
+
+ elif parenlev == 0 and not continued: # new statement
+ if not line: break
+ column = 0
+ while pos < max: # measure leading whitespace
+ if line[pos] == ' ':
+ column += 1
+ elif line[pos] == '\t':
+ column = (column//tabsize + 1)*tabsize
+ elif line[pos] == '\f':
+ column = 0
+ else:
+ break
+ pos += 1
+ if pos == max:
+ break
+
+ if line[pos] in '#\r\n': # skip comments or blank lines
+ if line[pos] == '#':
+ comment_token = line[pos:].rstrip('\r\n')
+ nl_pos = pos + len(comment_token)
+ yield TokenInfo(COMMENT, comment_token,
+ (lnum, pos), (lnum, pos + len(comment_token)), line)
+ yield TokenInfo(NEWLINE, line[nl_pos:],
+ (lnum, nl_pos), (lnum, len(line)), line)
+ else:
+ yield TokenInfo(NEWLINE, line[pos:],
+ (lnum, pos), (lnum, len(line)), line)
+ continue
+
+ if column > indents[-1]: # count indents or dedents
+ indents.append(column)
+ yield TokenInfo(INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
+ while column < indents[-1]:
+ if column not in indents:
+ raise IndentationError(
+ "unindent does not match any outer indentation level",
+ ("<tokenize>", lnum, pos, line))
+ indents = indents[:-1]
+ yield TokenInfo(DEDENT, '', (lnum, pos), (lnum, pos), line)
+
+ else: # continued statement
+ if not line:
+ raise TokenError("EOF in multi-line statement", (lnum, 0))
+ continued = 0
+
+ while pos < max:
+ pseudomatch = pseudoprog.match(line, pos)
+ if pseudomatch: # scan for tokens
+ start, end = pseudomatch.span(1)
+ spos, epos, pos = (lnum, start), (lnum, end), end
+ token, initial = line[start:end], line[start]
+
+ if (initial in numchars or # ordinary number
+ (initial == '.' and token != '.' and token != '...')):
+ yield TokenInfo(NUMBER, token, spos, epos, line)
+ elif initial in '\r\n':
+ yield TokenInfo(NL if parenlev > 0 else NEWLINE,
+ token, spos, epos, line)
+ elif initial == '#':
+ assert not token.endswith("\n")
+ yield TokenInfo(COMMENT, token, spos, epos, line)
+ elif token in triple_quoted:
+ endprog = endprogs[token]
+ endmatch = endprog.match(line, pos)
+ if endmatch: # all on one line
+ pos = endmatch.end(0)
+ token = line[start:pos]
+ yield TokenInfo(STRING, token, spos, (lnum, pos), line)
+ else:
+ strstart = (lnum, start) # multiple lines
+ contstr = line[start:]
+ contline = line
+ break
+ elif initial in single_quoted or \
+ token[:2] in single_quoted or \
+ token[:3] in single_quoted:
+ if token[-1] == '\n': # continued string
+ strstart = (lnum, start)
+ endprog = (endprogs[initial] or endprogs[token[1]] or
+ endprogs[token[2]])
+ contstr, needcont = line[start:], 1
+ contline = line
+ break
+ else: # ordinary string
+ yield TokenInfo(STRING, token, spos, epos, line)
+ elif initial.isidentifier(): # ordinary name
+ yield TokenInfo(NAME, token, spos, epos, line)
+ elif initial == '\\': # continued stmt
+ continued = 1
+ else:
+ if initial in '([{':
+ parenlev += 1
+ elif initial in ')]}':
+ parenlev -= 1
+ yield TokenInfo(OP, token, spos, epos, line)
+ else:
+ yield TokenInfo(ERRORTOKEN, line[pos],
+ (lnum, pos), (lnum, pos+1), line)
+ pos += 1
+
+ for indent in indents[1:]: # pop remaining indent levels
+ yield TokenInfo(DEDENT, '', (lnum, 0), (lnum, 0), '')
+ yield TokenInfo(ENDMARKER, '', (lnum, 0), (lnum, 0), '')
+
+
+# An undocumented, backwards compatible, API for all the places in the standard
+# library that expect to be able to use tokenize with strings
+def generate_tokens(readline):
+ return _tokenize(readline, None)
+
+if __name__ == "__main__":
+ # Quick sanity check
+ s = b'''def parseline(self, line):
+ """Parse the line into a command name and a string containing
+ the arguments. Returns a tuple containing (command, args, line).
+ 'command' and 'args' may be None if the line couldn't be parsed.
+ """
+ line = line.strip()
+ if not line:
+ return None, None, line
+ elif line[0] == '?':
+ line = 'help ' + line[1:]
+ elif line[0] == '!':
+ if hasattr(self, 'do_shell'):
+ line = 'shell ' + line[1:]
+ else:
+ return None, None, line
+ i, n = 0, len(line)
+ while i < n and line[i] in self.identchars: i = i+1
+ cmd, arg = line[:i], line[i:].strip()
+ return cmd, arg, line
+ '''
+ for tok in tokenize(iter(s.splitlines()).__next__):
+ print(tok)
diff --git a/contrib/python/ipython/py2/IPython/utils/capture.py b/contrib/python/ipython/py2/IPython/utils/capture.py
index bb241b0fad..d8f919568c 100644
--- a/contrib/python/ipython/py2/IPython/utils/capture.py
+++ b/contrib/python/ipython/py2/IPython/utils/capture.py
@@ -1,176 +1,176 @@
-# encoding: utf-8
-"""IO capturing utilities."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function, absolute_import
-
-import sys
-
-from IPython.utils.py3compat import PY3
-
-if PY3:
- from io import StringIO
-else:
- from StringIO import StringIO
-
-#-----------------------------------------------------------------------------
-# Classes and functions
-#-----------------------------------------------------------------------------
-
-
-class RichOutput(object):
+# encoding: utf-8
+"""IO capturing utilities."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function, absolute_import
+
+import sys
+
+from IPython.utils.py3compat import PY3
+
+if PY3:
+ from io import StringIO
+else:
+ from StringIO import StringIO
+
+#-----------------------------------------------------------------------------
+# Classes and functions
+#-----------------------------------------------------------------------------
+
+
+class RichOutput(object):
def __init__(self, data=None, metadata=None, transient=None, update=False):
- self.data = data or {}
- self.metadata = metadata or {}
+ self.data = data or {}
+ self.metadata = metadata or {}
self.transient = transient or {}
self.update = update
- def display(self):
- from IPython.display import publish_display_data
+ def display(self):
+ from IPython.display import publish_display_data
publish_display_data(data=self.data, metadata=self.metadata,
transient=self.transient, update=self.update)
- def _repr_mime_(self, mime):
- if mime not in self.data:
- return
- data = self.data[mime]
- if mime in self.metadata:
- return data, self.metadata[mime]
- else:
- return data
-
- def _repr_html_(self):
- return self._repr_mime_("text/html")
-
- def _repr_latex_(self):
- return self._repr_mime_("text/latex")
-
- def _repr_json_(self):
- return self._repr_mime_("application/json")
-
- def _repr_javascript_(self):
- return self._repr_mime_("application/javascript")
-
- def _repr_png_(self):
- return self._repr_mime_("image/png")
-
- def _repr_jpeg_(self):
- return self._repr_mime_("image/jpeg")
-
- def _repr_svg_(self):
- return self._repr_mime_("image/svg+xml")
-
-
-class CapturedIO(object):
- """Simple object for containing captured stdout/err and rich display StringIO objects
-
- Each instance `c` has three attributes:
-
- - ``c.stdout`` : standard output as a string
- - ``c.stderr`` : standard error as a string
- - ``c.outputs``: a list of rich display outputs
-
- Additionally, there's a ``c.show()`` method which will print all of the
- above in the same order, and can be invoked simply via ``c()``.
- """
-
- def __init__(self, stdout, stderr, outputs=None):
- self._stdout = stdout
- self._stderr = stderr
- if outputs is None:
- outputs = []
- self._outputs = outputs
-
- def __str__(self):
- return self.stdout
-
- @property
- def stdout(self):
- "Captured standard output"
- if not self._stdout:
- return ''
- return self._stdout.getvalue()
-
- @property
- def stderr(self):
- "Captured standard error"
- if not self._stderr:
- return ''
- return self._stderr.getvalue()
-
- @property
- def outputs(self):
- """A list of the captured rich display outputs, if any.
-
- If you have a CapturedIO object ``c``, these can be displayed in IPython
- using::
-
- from IPython.display import display
- for o in c.outputs:
- display(o)
- """
+ def _repr_mime_(self, mime):
+ if mime not in self.data:
+ return
+ data = self.data[mime]
+ if mime in self.metadata:
+ return data, self.metadata[mime]
+ else:
+ return data
+
+ def _repr_html_(self):
+ return self._repr_mime_("text/html")
+
+ def _repr_latex_(self):
+ return self._repr_mime_("text/latex")
+
+ def _repr_json_(self):
+ return self._repr_mime_("application/json")
+
+ def _repr_javascript_(self):
+ return self._repr_mime_("application/javascript")
+
+ def _repr_png_(self):
+ return self._repr_mime_("image/png")
+
+ def _repr_jpeg_(self):
+ return self._repr_mime_("image/jpeg")
+
+ def _repr_svg_(self):
+ return self._repr_mime_("image/svg+xml")
+
+
+class CapturedIO(object):
+ """Simple object for containing captured stdout/err and rich display StringIO objects
+
+ Each instance `c` has three attributes:
+
+ - ``c.stdout`` : standard output as a string
+ - ``c.stderr`` : standard error as a string
+ - ``c.outputs``: a list of rich display outputs
+
+ Additionally, there's a ``c.show()`` method which will print all of the
+ above in the same order, and can be invoked simply via ``c()``.
+ """
+
+ def __init__(self, stdout, stderr, outputs=None):
+ self._stdout = stdout
+ self._stderr = stderr
+ if outputs is None:
+ outputs = []
+ self._outputs = outputs
+
+ def __str__(self):
+ return self.stdout
+
+ @property
+ def stdout(self):
+ "Captured standard output"
+ if not self._stdout:
+ return ''
+ return self._stdout.getvalue()
+
+ @property
+ def stderr(self):
+ "Captured standard error"
+ if not self._stderr:
+ return ''
+ return self._stderr.getvalue()
+
+ @property
+ def outputs(self):
+ """A list of the captured rich display outputs, if any.
+
+ If you have a CapturedIO object ``c``, these can be displayed in IPython
+ using::
+
+ from IPython.display import display
+ for o in c.outputs:
+ display(o)
+ """
return [ RichOutput(**kargs) for kargs in self._outputs ]
- def show(self):
- """write my output to sys.stdout/err as appropriate"""
- sys.stdout.write(self.stdout)
- sys.stderr.write(self.stderr)
- sys.stdout.flush()
- sys.stderr.flush()
+ def show(self):
+ """write my output to sys.stdout/err as appropriate"""
+ sys.stdout.write(self.stdout)
+ sys.stderr.write(self.stderr)
+ sys.stdout.flush()
+ sys.stderr.flush()
for kargs in self._outputs:
RichOutput(**kargs).display()
- __call__ = show
-
-
-class capture_output(object):
- """context manager for capturing stdout/err"""
- stdout = True
- stderr = True
- display = True
-
- def __init__(self, stdout=True, stderr=True, display=True):
- self.stdout = stdout
- self.stderr = stderr
- self.display = display
- self.shell = None
-
- def __enter__(self):
- from IPython.core.getipython import get_ipython
- from IPython.core.displaypub import CapturingDisplayPublisher
+ __call__ = show
+
+
+class capture_output(object):
+ """context manager for capturing stdout/err"""
+ stdout = True
+ stderr = True
+ display = True
+
+ def __init__(self, stdout=True, stderr=True, display=True):
+ self.stdout = stdout
+ self.stderr = stderr
+ self.display = display
+ self.shell = None
+
+ def __enter__(self):
+ from IPython.core.getipython import get_ipython
+ from IPython.core.displaypub import CapturingDisplayPublisher
from IPython.core.displayhook import CapturingDisplayHook
- self.sys_stdout = sys.stdout
- self.sys_stderr = sys.stderr
-
- if self.display:
- self.shell = get_ipython()
- if self.shell is None:
- self.save_display_pub = None
- self.display = False
-
- stdout = stderr = outputs = None
- if self.stdout:
- stdout = sys.stdout = StringIO()
- if self.stderr:
- stderr = sys.stderr = StringIO()
- if self.display:
- self.save_display_pub = self.shell.display_pub
- self.shell.display_pub = CapturingDisplayPublisher()
- outputs = self.shell.display_pub.outputs
+ self.sys_stdout = sys.stdout
+ self.sys_stderr = sys.stderr
+
+ if self.display:
+ self.shell = get_ipython()
+ if self.shell is None:
+ self.save_display_pub = None
+ self.display = False
+
+ stdout = stderr = outputs = None
+ if self.stdout:
+ stdout = sys.stdout = StringIO()
+ if self.stderr:
+ stderr = sys.stderr = StringIO()
+ if self.display:
+ self.save_display_pub = self.shell.display_pub
+ self.shell.display_pub = CapturingDisplayPublisher()
+ outputs = self.shell.display_pub.outputs
self.save_display_hook = sys.displayhook
sys.displayhook = CapturingDisplayHook(shell=self.shell,
outputs=outputs)
- return CapturedIO(stdout, stderr, outputs)
+ return CapturedIO(stdout, stderr, outputs)
- def __exit__(self, exc_type, exc_value, traceback):
- sys.stdout = self.sys_stdout
- sys.stderr = self.sys_stderr
- if self.display and self.shell:
- self.shell.display_pub = self.save_display_pub
+ def __exit__(self, exc_type, exc_value, traceback):
+ sys.stdout = self.sys_stdout
+ sys.stderr = self.sys_stderr
+ if self.display and self.shell:
+ self.shell.display_pub = self.save_display_pub
sys.displayhook = self.save_display_hook
-
-
+
+
diff --git a/contrib/python/ipython/py2/IPython/utils/coloransi.py b/contrib/python/ipython/py2/IPython/utils/coloransi.py
index 597c69fe11..bc8e8377f7 100644
--- a/contrib/python/ipython/py2/IPython/utils/coloransi.py
+++ b/contrib/python/ipython/py2/IPython/utils/coloransi.py
@@ -1,187 +1,187 @@
-# -*- coding: utf-8 -*-
-"""Tools for coloring text in ANSI terminals.
-"""
-
-#*****************************************************************************
-# Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#*****************************************************************************
-
-__all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
-
-import os
-
-from IPython.utils.ipstruct import Struct
-
-color_templates = (
- # Dark colors
- ("Black" , "0;30"),
- ("Red" , "0;31"),
- ("Green" , "0;32"),
- ("Brown" , "0;33"),
- ("Blue" , "0;34"),
- ("Purple" , "0;35"),
- ("Cyan" , "0;36"),
- ("LightGray" , "0;37"),
- # Light colors
- ("DarkGray" , "1;30"),
- ("LightRed" , "1;31"),
- ("LightGreen" , "1;32"),
- ("Yellow" , "1;33"),
- ("LightBlue" , "1;34"),
- ("LightPurple" , "1;35"),
- ("LightCyan" , "1;36"),
- ("White" , "1;37"),
- # Blinking colors. Probably should not be used in anything serious.
- ("BlinkBlack" , "5;30"),
- ("BlinkRed" , "5;31"),
- ("BlinkGreen" , "5;32"),
- ("BlinkYellow" , "5;33"),
- ("BlinkBlue" , "5;34"),
- ("BlinkPurple" , "5;35"),
- ("BlinkCyan" , "5;36"),
- ("BlinkLightGray", "5;37"),
- )
-
-def make_color_table(in_class):
- """Build a set of color attributes in a class.
-
- Helper function for building the :class:`TermColors` and
- :class`InputTermColors`.
- """
- for name,value in color_templates:
- setattr(in_class,name,in_class._base % value)
-
-class TermColors:
- """Color escape sequences.
-
- This class defines the escape sequences for all the standard (ANSI?)
- colors in terminals. Also defines a NoColor escape which is just the null
- string, suitable for defining 'dummy' color schemes in terminals which get
- confused by color escapes.
-
- This class should be used as a mixin for building color schemes."""
-
- NoColor = '' # for color schemes in color-less terminals.
- Normal = '\033[0m' # Reset normal coloring
- _base = '\033[%sm' # Template for all other colors
-
-# Build the actual color table as a set of class attributes:
-make_color_table(TermColors)
-
-class InputTermColors:
- """Color escape sequences for input prompts.
-
- This class is similar to TermColors, but the escapes are wrapped in \001
- and \002 so that readline can properly know the length of each line and
- can wrap lines accordingly. Use this class for any colored text which
- needs to be used in input prompts, such as in calls to raw_input().
-
- This class defines the escape sequences for all the standard (ANSI?)
- colors in terminals. Also defines a NoColor escape which is just the null
- string, suitable for defining 'dummy' color schemes in terminals which get
- confused by color escapes.
-
- This class should be used as a mixin for building color schemes."""
-
- NoColor = '' # for color schemes in color-less terminals.
-
- if os.name == 'nt' and os.environ.get('TERM','dumb') == 'emacs':
- # (X)emacs on W32 gets confused with \001 and \002 so we remove them
- Normal = '\033[0m' # Reset normal coloring
- _base = '\033[%sm' # Template for all other colors
- else:
- Normal = '\001\033[0m\002' # Reset normal coloring
- _base = '\001\033[%sm\002' # Template for all other colors
-
-# Build the actual color table as a set of class attributes:
-make_color_table(InputTermColors)
-
-class NoColors:
- """This defines all the same names as the colour classes, but maps them to
- empty strings, so it can easily be substituted to turn off colours."""
- NoColor = ''
- Normal = ''
-
-for name, value in color_templates:
- setattr(NoColors, name, '')
-
-class ColorScheme:
- """Generic color scheme class. Just a name and a Struct."""
- def __init__(self,__scheme_name_,colordict=None,**colormap):
- self.name = __scheme_name_
- if colordict is None:
- self.colors = Struct(**colormap)
- else:
- self.colors = Struct(colordict)
-
- def copy(self,name=None):
- """Return a full copy of the object, optionally renaming it."""
- if name is None:
- name = self.name
- return ColorScheme(name, self.colors.dict())
-
-class ColorSchemeTable(dict):
- """General class to handle tables of color schemes.
-
- It's basically a dict of color schemes with a couple of shorthand
- attributes and some convenient methods.
-
- active_scheme_name -> obvious
- active_colors -> actual color table of the active scheme"""
-
- def __init__(self, scheme_list=None, default_scheme=''):
- """Create a table of color schemes.
-
- The table can be created empty and manually filled or it can be
- created with a list of valid color schemes AND the specification for
- the default active scheme.
- """
-
- # create object attributes to be set later
- self.active_scheme_name = ''
- self.active_colors = None
-
- if scheme_list:
- if default_scheme == '':
- raise ValueError('you must specify the default color scheme')
- for scheme in scheme_list:
- self.add_scheme(scheme)
- self.set_active_scheme(default_scheme)
-
- def copy(self):
- """Return full copy of object"""
- return ColorSchemeTable(self.values(),self.active_scheme_name)
-
- def add_scheme(self,new_scheme):
- """Add a new color scheme to the table."""
- if not isinstance(new_scheme,ColorScheme):
- raise ValueError('ColorSchemeTable only accepts ColorScheme instances')
- self[new_scheme.name] = new_scheme
-
- def set_active_scheme(self,scheme,case_sensitive=0):
- """Set the currently active scheme.
-
- Names are by default compared in a case-insensitive way, but this can
- be changed by setting the parameter case_sensitive to true."""
-
- scheme_names = list(self.keys())
- if case_sensitive:
- valid_schemes = scheme_names
- scheme_test = scheme
- else:
- valid_schemes = [s.lower() for s in scheme_names]
- scheme_test = scheme.lower()
- try:
- scheme_idx = valid_schemes.index(scheme_test)
- except ValueError:
- raise ValueError('Unrecognized color scheme: ' + scheme + \
- '\nValid schemes: '+str(scheme_names).replace("'', ",''))
- else:
- active = scheme_names[scheme_idx]
- self.active_scheme_name = active
- self.active_colors = self[active].colors
- # Now allow using '' as an index for the current active scheme
- self[''] = self[active]
+# -*- coding: utf-8 -*-
+"""Tools for coloring text in ANSI terminals.
+"""
+
+#*****************************************************************************
+# Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#*****************************************************************************
+
+__all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
+
+import os
+
+from IPython.utils.ipstruct import Struct
+
+color_templates = (
+ # Dark colors
+ ("Black" , "0;30"),
+ ("Red" , "0;31"),
+ ("Green" , "0;32"),
+ ("Brown" , "0;33"),
+ ("Blue" , "0;34"),
+ ("Purple" , "0;35"),
+ ("Cyan" , "0;36"),
+ ("LightGray" , "0;37"),
+ # Light colors
+ ("DarkGray" , "1;30"),
+ ("LightRed" , "1;31"),
+ ("LightGreen" , "1;32"),
+ ("Yellow" , "1;33"),
+ ("LightBlue" , "1;34"),
+ ("LightPurple" , "1;35"),
+ ("LightCyan" , "1;36"),
+ ("White" , "1;37"),
+ # Blinking colors. Probably should not be used in anything serious.
+ ("BlinkBlack" , "5;30"),
+ ("BlinkRed" , "5;31"),
+ ("BlinkGreen" , "5;32"),
+ ("BlinkYellow" , "5;33"),
+ ("BlinkBlue" , "5;34"),
+ ("BlinkPurple" , "5;35"),
+ ("BlinkCyan" , "5;36"),
+ ("BlinkLightGray", "5;37"),
+ )
+
+def make_color_table(in_class):
+ """Build a set of color attributes in a class.
+
+ Helper function for building the :class:`TermColors` and
+ :class`InputTermColors`.
+ """
+ for name,value in color_templates:
+ setattr(in_class,name,in_class._base % value)
+
+class TermColors:
+ """Color escape sequences.
+
+ This class defines the escape sequences for all the standard (ANSI?)
+ colors in terminals. Also defines a NoColor escape which is just the null
+ string, suitable for defining 'dummy' color schemes in terminals which get
+ confused by color escapes.
+
+ This class should be used as a mixin for building color schemes."""
+
+ NoColor = '' # for color schemes in color-less terminals.
+ Normal = '\033[0m' # Reset normal coloring
+ _base = '\033[%sm' # Template for all other colors
+
+# Build the actual color table as a set of class attributes:
+make_color_table(TermColors)
+
+class InputTermColors:
+ """Color escape sequences for input prompts.
+
+ This class is similar to TermColors, but the escapes are wrapped in \001
+ and \002 so that readline can properly know the length of each line and
+ can wrap lines accordingly. Use this class for any colored text which
+ needs to be used in input prompts, such as in calls to raw_input().
+
+ This class defines the escape sequences for all the standard (ANSI?)
+ colors in terminals. Also defines a NoColor escape which is just the null
+ string, suitable for defining 'dummy' color schemes in terminals which get
+ confused by color escapes.
+
+ This class should be used as a mixin for building color schemes."""
+
+ NoColor = '' # for color schemes in color-less terminals.
+
+ if os.name == 'nt' and os.environ.get('TERM','dumb') == 'emacs':
+ # (X)emacs on W32 gets confused with \001 and \002 so we remove them
+ Normal = '\033[0m' # Reset normal coloring
+ _base = '\033[%sm' # Template for all other colors
+ else:
+ Normal = '\001\033[0m\002' # Reset normal coloring
+ _base = '\001\033[%sm\002' # Template for all other colors
+
+# Build the actual color table as a set of class attributes:
+make_color_table(InputTermColors)
+
+class NoColors:
+ """This defines all the same names as the colour classes, but maps them to
+ empty strings, so it can easily be substituted to turn off colours."""
+ NoColor = ''
+ Normal = ''
+
+for name, value in color_templates:
+ setattr(NoColors, name, '')
+
+class ColorScheme:
+ """Generic color scheme class. Just a name and a Struct."""
+ def __init__(self,__scheme_name_,colordict=None,**colormap):
+ self.name = __scheme_name_
+ if colordict is None:
+ self.colors = Struct(**colormap)
+ else:
+ self.colors = Struct(colordict)
+
+ def copy(self,name=None):
+ """Return a full copy of the object, optionally renaming it."""
+ if name is None:
+ name = self.name
+ return ColorScheme(name, self.colors.dict())
+
+class ColorSchemeTable(dict):
+ """General class to handle tables of color schemes.
+
+ It's basically a dict of color schemes with a couple of shorthand
+ attributes and some convenient methods.
+
+ active_scheme_name -> obvious
+ active_colors -> actual color table of the active scheme"""
+
+ def __init__(self, scheme_list=None, default_scheme=''):
+ """Create a table of color schemes.
+
+ The table can be created empty and manually filled or it can be
+ created with a list of valid color schemes AND the specification for
+ the default active scheme.
+ """
+
+ # create object attributes to be set later
+ self.active_scheme_name = ''
+ self.active_colors = None
+
+ if scheme_list:
+ if default_scheme == '':
+ raise ValueError('you must specify the default color scheme')
+ for scheme in scheme_list:
+ self.add_scheme(scheme)
+ self.set_active_scheme(default_scheme)
+
+ def copy(self):
+ """Return full copy of object"""
+ return ColorSchemeTable(self.values(),self.active_scheme_name)
+
+ def add_scheme(self,new_scheme):
+ """Add a new color scheme to the table."""
+ if not isinstance(new_scheme,ColorScheme):
+ raise ValueError('ColorSchemeTable only accepts ColorScheme instances')
+ self[new_scheme.name] = new_scheme
+
+ def set_active_scheme(self,scheme,case_sensitive=0):
+ """Set the currently active scheme.
+
+ Names are by default compared in a case-insensitive way, but this can
+ be changed by setting the parameter case_sensitive to true."""
+
+ scheme_names = list(self.keys())
+ if case_sensitive:
+ valid_schemes = scheme_names
+ scheme_test = scheme
+ else:
+ valid_schemes = [s.lower() for s in scheme_names]
+ scheme_test = scheme.lower()
+ try:
+ scheme_idx = valid_schemes.index(scheme_test)
+ except ValueError:
+ raise ValueError('Unrecognized color scheme: ' + scheme + \
+ '\nValid schemes: '+str(scheme_names).replace("'', ",''))
+ else:
+ active = scheme_names[scheme_idx]
+ self.active_scheme_name = active
+ self.active_colors = self[active].colors
+ # Now allow using '' as an index for the current active scheme
+ self[''] = self[active]
diff --git a/contrib/python/ipython/py2/IPython/utils/contexts.py b/contrib/python/ipython/py2/IPython/utils/contexts.py
index 358dfe8b29..4d379b0eda 100644
--- a/contrib/python/ipython/py2/IPython/utils/contexts.py
+++ b/contrib/python/ipython/py2/IPython/utils/contexts.py
@@ -1,66 +1,66 @@
-# encoding: utf-8
-"""Miscellaneous context managers.
-"""
-
+# encoding: utf-8
+"""Miscellaneous context managers.
+"""
+
import warnings
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-class preserve_keys(object):
- """Preserve a set of keys in a dictionary.
-
- Upon entering the context manager the current values of the keys
- will be saved. Upon exiting, the dictionary will be updated to
- restore the original value of the preserved keys. Preserved keys
- which did not exist when entering the context manager will be
- deleted.
-
- Examples
- --------
-
- >>> d = {'a': 1, 'b': 2, 'c': 3}
- >>> with preserve_keys(d, 'b', 'c', 'd'):
- ... del d['a']
- ... del d['b'] # will be reset to 2
- ... d['c'] = None # will be reset to 3
- ... d['d'] = 4 # will be deleted
- ... d['e'] = 5
- ... print(sorted(d.items()))
- ...
- [('c', None), ('d', 4), ('e', 5)]
- >>> print(sorted(d.items()))
- [('b', 2), ('c', 3), ('e', 5)]
- """
-
- def __init__(self, dictionary, *keys):
- self.dictionary = dictionary
- self.keys = keys
-
- def __enter__(self):
- # Actions to perform upon exiting.
- to_delete = []
- to_update = {}
-
- d = self.dictionary
- for k in self.keys:
- if k in d:
- to_update[k] = d[k]
- else:
- to_delete.append(k)
-
- self.to_delete = to_delete
- self.to_update = to_update
-
- def __exit__(self, *exc_info):
- d = self.dictionary
-
- for k in self.to_delete:
- d.pop(k, None)
- d.update(self.to_update)
-
-
-class NoOpContext(object):
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+class preserve_keys(object):
+ """Preserve a set of keys in a dictionary.
+
+ Upon entering the context manager the current values of the keys
+ will be saved. Upon exiting, the dictionary will be updated to
+ restore the original value of the preserved keys. Preserved keys
+ which did not exist when entering the context manager will be
+ deleted.
+
+ Examples
+ --------
+
+ >>> d = {'a': 1, 'b': 2, 'c': 3}
+ >>> with preserve_keys(d, 'b', 'c', 'd'):
+ ... del d['a']
+ ... del d['b'] # will be reset to 2
+ ... d['c'] = None # will be reset to 3
+ ... d['d'] = 4 # will be deleted
+ ... d['e'] = 5
+ ... print(sorted(d.items()))
+ ...
+ [('c', None), ('d', 4), ('e', 5)]
+ >>> print(sorted(d.items()))
+ [('b', 2), ('c', 3), ('e', 5)]
+ """
+
+ def __init__(self, dictionary, *keys):
+ self.dictionary = dictionary
+ self.keys = keys
+
+ def __enter__(self):
+ # Actions to perform upon exiting.
+ to_delete = []
+ to_update = {}
+
+ d = self.dictionary
+ for k in self.keys:
+ if k in d:
+ to_update[k] = d[k]
+ else:
+ to_delete.append(k)
+
+ self.to_delete = to_delete
+ self.to_update = to_update
+
+ def __exit__(self, *exc_info):
+ d = self.dictionary
+
+ for k in self.to_delete:
+ d.pop(k, None)
+ d.update(self.to_update)
+
+
+class NoOpContext(object):
"""
Deprecated
@@ -70,5 +70,5 @@ class NoOpContext(object):
warnings.warn("""NoOpContext is deprecated since IPython 5.0 """,
DeprecationWarning, stacklevel=2)
- def __enter__(self): pass
- def __exit__(self, type, value, traceback): pass
+ def __enter__(self): pass
+ def __exit__(self, type, value, traceback): pass
diff --git a/contrib/python/ipython/py2/IPython/utils/daemonize.py b/contrib/python/ipython/py2/IPython/utils/daemonize.py
index f093cf67cb..a1bfaa193b 100644
--- a/contrib/python/ipython/py2/IPython/utils/daemonize.py
+++ b/contrib/python/ipython/py2/IPython/utils/daemonize.py
@@ -1,4 +1,4 @@
-from warnings import warn
-
-warn("IPython.utils.daemonize has moved to ipyparallel.apps.daemonize")
-from ipyparallel.apps.daemonize import daemonize
+from warnings import warn
+
+warn("IPython.utils.daemonize has moved to ipyparallel.apps.daemonize")
+from ipyparallel.apps.daemonize import daemonize
diff --git a/contrib/python/ipython/py2/IPython/utils/data.py b/contrib/python/ipython/py2/IPython/utils/data.py
index 36a8aabd95..308a692559 100644
--- a/contrib/python/ipython/py2/IPython/utils/data.py
+++ b/contrib/python/ipython/py2/IPython/utils/data.py
@@ -1,37 +1,37 @@
-# encoding: utf-8
-"""Utilities for working with data structures like lists, dicts and tuples.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-from .py3compat import xrange
-
-def uniq_stable(elems):
- """uniq_stable(elems) -> list
-
- Return from an iterable, a list of all the unique elements in the input,
- but maintaining the order in which they first appear.
-
- Note: All elements in the input must be hashable for this routine
- to work, as it internally uses a set for efficiency reasons.
- """
- seen = set()
- return [x for x in elems if x not in seen and not seen.add(x)]
-
-
-def flatten(seq):
- """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
-
- return [x for subseq in seq for x in subseq]
-
-
-def chop(seq, size):
- """Chop a sequence into chunks of the given size."""
- return [seq[i:i+size] for i in xrange(0,len(seq),size)]
-
-
+# encoding: utf-8
+"""Utilities for working with data structures like lists, dicts and tuples.
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+from .py3compat import xrange
+
+def uniq_stable(elems):
+ """uniq_stable(elems) -> list
+
+ Return from an iterable, a list of all the unique elements in the input,
+ but maintaining the order in which they first appear.
+
+ Note: All elements in the input must be hashable for this routine
+ to work, as it internally uses a set for efficiency reasons.
+ """
+ seen = set()
+ return [x for x in elems if x not in seen and not seen.add(x)]
+
+
+def flatten(seq):
+ """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
+
+ return [x for subseq in seq for x in subseq]
+
+
+def chop(seq, size):
+ """Chop a sequence into chunks of the given size."""
+ return [seq[i:i+size] for i in xrange(0,len(seq),size)]
+
+
diff --git a/contrib/python/ipython/py2/IPython/utils/decorators.py b/contrib/python/ipython/py2/IPython/utils/decorators.py
index 79be8ca1e6..c26485553c 100644
--- a/contrib/python/ipython/py2/IPython/utils/decorators.py
+++ b/contrib/python/ipython/py2/IPython/utils/decorators.py
@@ -1,58 +1,58 @@
-# encoding: utf-8
-"""Decorators that don't go anywhere else.
-
-This module contains misc. decorators that don't really go with another module
-in :mod:`IPython.utils`. Beore putting something here please see if it should
-go into another topical module in :mod:`IPython.utils`.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-def flag_calls(func):
- """Wrap a function to detect and flag when it gets called.
-
- This is a decorator which takes a function and wraps it in a function with
- a 'called' attribute. wrapper.called is initialized to False.
-
- The wrapper.called attribute is set to False right before each call to the
- wrapped function, so if the call fails it remains False. After the call
- completes, wrapper.called is set to True and the output is returned.
-
- Testing for truth in wrapper.called allows you to determine if a call to
- func() was attempted and succeeded."""
-
- # don't wrap twice
- if hasattr(func, 'called'):
- return func
-
- def wrapper(*args,**kw):
- wrapper.called = False
- out = func(*args,**kw)
- wrapper.called = True
- return out
-
- wrapper.called = False
- wrapper.__doc__ = func.__doc__
- return wrapper
-
-def undoc(func):
- """Mark a function or class as undocumented.
-
- This is found by inspecting the AST, so for now it must be used directly
- as @undoc, not as e.g. @decorators.undoc
- """
- return func
-
+# encoding: utf-8
+"""Decorators that don't go anywhere else.
+
+This module contains misc. decorators that don't really go with another module
+in :mod:`IPython.utils`. Beore putting something here please see if it should
+go into another topical module in :mod:`IPython.utils`.
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+def flag_calls(func):
+ """Wrap a function to detect and flag when it gets called.
+
+ This is a decorator which takes a function and wraps it in a function with
+ a 'called' attribute. wrapper.called is initialized to False.
+
+ The wrapper.called attribute is set to False right before each call to the
+ wrapped function, so if the call fails it remains False. After the call
+ completes, wrapper.called is set to True and the output is returned.
+
+ Testing for truth in wrapper.called allows you to determine if a call to
+ func() was attempted and succeeded."""
+
+ # don't wrap twice
+ if hasattr(func, 'called'):
+ return func
+
+ def wrapper(*args,**kw):
+ wrapper.called = False
+ out = func(*args,**kw)
+ wrapper.called = True
+ return out
+
+ wrapper.called = False
+ wrapper.__doc__ = func.__doc__
+ return wrapper
+
+def undoc(func):
+ """Mark a function or class as undocumented.
+
+ This is found by inspecting the AST, so for now it must be used directly
+ as @undoc, not as e.g. @decorators.undoc
+ """
+ return func
+
diff --git a/contrib/python/ipython/py2/IPython/utils/dir2.py b/contrib/python/ipython/py2/IPython/utils/dir2.py
index fb0cd719ef..f6f164f9b1 100644
--- a/contrib/python/ipython/py2/IPython/utils/dir2.py
+++ b/contrib/python/ipython/py2/IPython/utils/dir2.py
@@ -1,51 +1,51 @@
-# encoding: utf-8
-"""A fancy version of Python's builtin :func:`dir` function.
-"""
-
+# encoding: utf-8
+"""A fancy version of Python's builtin :func:`dir` function.
+"""
+
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
-
+
import inspect
-from .py3compat import string_types
-
-
-def safe_hasattr(obj, attr):
- """In recent versions of Python, hasattr() only catches AttributeError.
- This catches all errors.
- """
- try:
- getattr(obj, attr)
- return True
- except:
- return False
-
-
-def dir2(obj):
- """dir2(obj) -> list of strings
-
- Extended version of the Python builtin dir(), which does a few extra
- checks.
-
- This version is guaranteed to return only a list of true strings, whereas
- dir() returns anything that objects inject into themselves, even if they
- are later not really valid for attribute access (many extension libraries
- have such bugs).
- """
-
- # Start building the attribute list via dir(), and then complete it
- # with a few extra special-purpose calls.
-
- try:
- words = set(dir(obj))
- except Exception:
- # TypeError: dir(obj) does not return a list
- words = set()
-
- # filter out non-string attributes which may be stuffed by dir() calls
- # and poor coding in third-party modules
-
- words = [w for w in words if isinstance(w, string_types)]
- return sorted(words)
+from .py3compat import string_types
+
+
+def safe_hasattr(obj, attr):
+ """In recent versions of Python, hasattr() only catches AttributeError.
+ This catches all errors.
+ """
+ try:
+ getattr(obj, attr)
+ return True
+ except:
+ return False
+
+
+def dir2(obj):
+ """dir2(obj) -> list of strings
+
+ Extended version of the Python builtin dir(), which does a few extra
+ checks.
+
+ This version is guaranteed to return only a list of true strings, whereas
+ dir() returns anything that objects inject into themselves, even if they
+ are later not really valid for attribute access (many extension libraries
+ have such bugs).
+ """
+
+ # Start building the attribute list via dir(), and then complete it
+ # with a few extra special-purpose calls.
+
+ try:
+ words = set(dir(obj))
+ except Exception:
+ # TypeError: dir(obj) does not return a list
+ words = set()
+
+ # filter out non-string attributes which may be stuffed by dir() calls
+ # and poor coding in third-party modules
+
+ words = [w for w in words if isinstance(w, string_types)]
+ return sorted(words)
def get_real_method(obj, name):
diff --git a/contrib/python/ipython/py2/IPython/utils/encoding.py b/contrib/python/ipython/py2/IPython/utils/encoding.py
index ba8ca09534..387a24700c 100644
--- a/contrib/python/ipython/py2/IPython/utils/encoding.py
+++ b/contrib/python/ipython/py2/IPython/utils/encoding.py
@@ -1,71 +1,71 @@
-# coding: utf-8
-"""
-Utilities for dealing with text encodings
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2012 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-import sys
-import locale
-import warnings
-
-# to deal with the possibility of sys.std* not being a stream at all
-def get_stream_enc(stream, default=None):
- """Return the given stream's encoding or a default.
-
- There are cases where ``sys.std*`` might not actually be a stream, so
- check for the encoding attribute prior to returning it, and return
- a default if it doesn't exist or evaluates as False. ``default``
- is None if not provided.
- """
- if not hasattr(stream, 'encoding') or not stream.encoding:
- return default
- else:
- return stream.encoding
-
-# Less conservative replacement for sys.getdefaultencoding, that will try
-# to match the environment.
-# Defined here as central function, so if we find better choices, we
-# won't need to make changes all over IPython.
-def getdefaultencoding(prefer_stream=True):
- """Return IPython's guess for the default encoding for bytes as text.
-
- If prefer_stream is True (default), asks for stdin.encoding first,
- to match the calling Terminal, but that is often None for subprocesses.
-
- Then fall back on locale.getpreferredencoding(),
- which should be a sensible platform default (that respects LANG environment),
- and finally to sys.getdefaultencoding() which is the most conservative option,
- and usually ASCII on Python 2 or UTF8 on Python 3.
- """
- enc = None
- if prefer_stream:
- enc = get_stream_enc(sys.stdin)
- if not enc or enc=='ascii':
- try:
- # There are reports of getpreferredencoding raising errors
- # in some cases, which may well be fixed, but let's be conservative here.
- enc = locale.getpreferredencoding()
- except Exception:
- pass
- enc = enc or sys.getdefaultencoding()
- # On windows `cp0` can be returned to indicate that there is no code page.
- # Since cp0 is an invalid encoding return instead cp1252 which is the
- # Western European default.
- if enc == 'cp0':
- warnings.warn(
- "Invalid code page cp0 detected - using cp1252 instead."
- "If cp1252 is incorrect please ensure a valid code page "
- "is defined for the process.", RuntimeWarning)
- return 'cp1252'
- return enc
-
-DEFAULT_ENCODING = getdefaultencoding()
+# coding: utf-8
+"""
+Utilities for dealing with text encodings
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2012 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+import sys
+import locale
+import warnings
+
+# to deal with the possibility of sys.std* not being a stream at all
+def get_stream_enc(stream, default=None):
+ """Return the given stream's encoding or a default.
+
+ There are cases where ``sys.std*`` might not actually be a stream, so
+ check for the encoding attribute prior to returning it, and return
+ a default if it doesn't exist or evaluates as False. ``default``
+ is None if not provided.
+ """
+ if not hasattr(stream, 'encoding') or not stream.encoding:
+ return default
+ else:
+ return stream.encoding
+
+# Less conservative replacement for sys.getdefaultencoding, that will try
+# to match the environment.
+# Defined here as central function, so if we find better choices, we
+# won't need to make changes all over IPython.
+def getdefaultencoding(prefer_stream=True):
+ """Return IPython's guess for the default encoding for bytes as text.
+
+ If prefer_stream is True (default), asks for stdin.encoding first,
+ to match the calling Terminal, but that is often None for subprocesses.
+
+ Then fall back on locale.getpreferredencoding(),
+ which should be a sensible platform default (that respects LANG environment),
+ and finally to sys.getdefaultencoding() which is the most conservative option,
+ and usually ASCII on Python 2 or UTF8 on Python 3.
+ """
+ enc = None
+ if prefer_stream:
+ enc = get_stream_enc(sys.stdin)
+ if not enc or enc=='ascii':
+ try:
+ # There are reports of getpreferredencoding raising errors
+ # in some cases, which may well be fixed, but let's be conservative here.
+ enc = locale.getpreferredencoding()
+ except Exception:
+ pass
+ enc = enc or sys.getdefaultencoding()
+ # On windows `cp0` can be returned to indicate that there is no code page.
+ # Since cp0 is an invalid encoding return instead cp1252 which is the
+ # Western European default.
+ if enc == 'cp0':
+ warnings.warn(
+ "Invalid code page cp0 detected - using cp1252 instead."
+ "If cp1252 is incorrect please ensure a valid code page "
+ "is defined for the process.", RuntimeWarning)
+ return 'cp1252'
+ return enc
+
+DEFAULT_ENCODING = getdefaultencoding()
diff --git a/contrib/python/ipython/py2/IPython/utils/eventful.py b/contrib/python/ipython/py2/IPython/utils/eventful.py
index e954a45e0a..fc0f7aee4f 100644
--- a/contrib/python/ipython/py2/IPython/utils/eventful.py
+++ b/contrib/python/ipython/py2/IPython/utils/eventful.py
@@ -1,7 +1,7 @@
-from __future__ import absolute_import
-
-from warnings import warn
-
-warn("IPython.utils.eventful has moved to traitlets.eventful")
-
-from traitlets.eventful import *
+from __future__ import absolute_import
+
+from warnings import warn
+
+warn("IPython.utils.eventful has moved to traitlets.eventful")
+
+from traitlets.eventful import *
diff --git a/contrib/python/ipython/py2/IPython/utils/frame.py b/contrib/python/ipython/py2/IPython/utils/frame.py
index ebf9e47bf9..76ccc71c44 100644
--- a/contrib/python/ipython/py2/IPython/utils/frame.py
+++ b/contrib/python/ipython/py2/IPython/utils/frame.py
@@ -1,98 +1,98 @@
-# encoding: utf-8
-"""
-Utilities for working with stack frames.
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import sys
-from IPython.utils import py3compat
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-@py3compat.doctest_refactor_print
-def extract_vars(*names,**kw):
- """Extract a set of variables by name from another frame.
-
- Parameters
- ----------
- *names : str
- One or more variable names which will be extracted from the caller's
- frame.
-
- depth : integer, optional
- How many frames in the stack to walk when looking for your variables.
- The default is 0, which will use the frame where the call was made.
-
-
- Examples
- --------
- ::
-
- In [2]: def func(x):
- ...: y = 1
- ...: print(sorted(extract_vars('x','y').items()))
- ...:
-
- In [3]: func('hello')
- [('x', 'hello'), ('y', 1)]
- """
-
- depth = kw.get('depth',0)
-
- callerNS = sys._getframe(depth+1).f_locals
- return dict((k,callerNS[k]) for k in names)
-
-
-def extract_vars_above(*names):
- """Extract a set of variables by name from another frame.
-
- Similar to extractVars(), but with a specified depth of 1, so that names
- are exctracted exactly from above the caller.
-
- This is simply a convenience function so that the very common case (for us)
- of skipping exactly 1 frame doesn't have to construct a special dict for
- keyword passing."""
-
- callerNS = sys._getframe(2).f_locals
- return dict((k,callerNS[k]) for k in names)
-
-
-def debugx(expr,pre_msg=''):
- """Print the value of an expression from the caller's frame.
-
- Takes an expression, evaluates it in the caller's frame and prints both
- the given expression and the resulting value (as well as a debug mark
- indicating the name of the calling function. The input must be of a form
- suitable for eval().
-
- An optional message can be passed, which will be prepended to the printed
- expr->value pair."""
-
- cf = sys._getframe(1)
- print('[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
- eval(expr,cf.f_globals,cf.f_locals)))
-
-
-# deactivate it by uncommenting the following line, which makes it a no-op
-#def debugx(expr,pre_msg=''): pass
-
-def extract_module_locals(depth=0):
- """Returns (module, locals) of the function `depth` frames away from the caller"""
- f = sys._getframe(depth + 1)
- global_ns = f.f_globals
- module = sys.modules[global_ns['__name__']]
- return (module, f.f_locals)
-
+# encoding: utf-8
+"""
+Utilities for working with stack frames.
+"""
+from __future__ import print_function
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import sys
+from IPython.utils import py3compat
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+@py3compat.doctest_refactor_print
+def extract_vars(*names,**kw):
+ """Extract a set of variables by name from another frame.
+
+ Parameters
+ ----------
+ *names : str
+ One or more variable names which will be extracted from the caller's
+ frame.
+
+ depth : integer, optional
+ How many frames in the stack to walk when looking for your variables.
+ The default is 0, which will use the frame where the call was made.
+
+
+ Examples
+ --------
+ ::
+
+ In [2]: def func(x):
+ ...: y = 1
+ ...: print(sorted(extract_vars('x','y').items()))
+ ...:
+
+ In [3]: func('hello')
+ [('x', 'hello'), ('y', 1)]
+ """
+
+ depth = kw.get('depth',0)
+
+ callerNS = sys._getframe(depth+1).f_locals
+ return dict((k,callerNS[k]) for k in names)
+
+
+def extract_vars_above(*names):
+ """Extract a set of variables by name from another frame.
+
+ Similar to extractVars(), but with a specified depth of 1, so that names
+ are exctracted exactly from above the caller.
+
+ This is simply a convenience function so that the very common case (for us)
+ of skipping exactly 1 frame doesn't have to construct a special dict for
+ keyword passing."""
+
+ callerNS = sys._getframe(2).f_locals
+ return dict((k,callerNS[k]) for k in names)
+
+
+def debugx(expr,pre_msg=''):
+ """Print the value of an expression from the caller's frame.
+
+ Takes an expression, evaluates it in the caller's frame and prints both
+ the given expression and the resulting value (as well as a debug mark
+ indicating the name of the calling function. The input must be of a form
+ suitable for eval().
+
+ An optional message can be passed, which will be prepended to the printed
+ expr->value pair."""
+
+ cf = sys._getframe(1)
+ print('[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
+ eval(expr,cf.f_globals,cf.f_locals)))
+
+
+# deactivate it by uncommenting the following line, which makes it a no-op
+#def debugx(expr,pre_msg=''): pass
+
+def extract_module_locals(depth=0):
+ """Returns (module, locals) of the function `depth` frames away from the caller"""
+ f = sys._getframe(depth + 1)
+ global_ns = f.f_globals
+ module = sys.modules[global_ns['__name__']]
+ return (module, f.f_locals)
+
diff --git a/contrib/python/ipython/py2/IPython/utils/generics.py b/contrib/python/ipython/py2/IPython/utils/generics.py
index ff856a7e55..5ffdc86ebd 100644
--- a/contrib/python/ipython/py2/IPython/utils/generics.py
+++ b/contrib/python/ipython/py2/IPython/utils/generics.py
@@ -1,34 +1,34 @@
-# encoding: utf-8
-"""Generic functions for extending IPython.
-
-See http://pypi.python.org/pypi/simplegeneric.
-"""
-
-from IPython.core.error import TryNext
-from simplegeneric import generic
-
-
-@generic
-def inspect_object(obj):
- """Called when you do obj?"""
- raise TryNext
-
-
-@generic
-def complete_object(obj, prev_completions):
- """Custom completer dispatching for python objects.
-
- Parameters
- ----------
- obj : object
- The object to complete.
- prev_completions : list
- List of attributes discovered so far.
-
- This should return the list of attributes in obj. If you only wish to
- add to the attributes already discovered normally, return
- own_attrs + prev_completions.
- """
- raise TryNext
-
-
+# encoding: utf-8
+"""Generic functions for extending IPython.
+
+See http://pypi.python.org/pypi/simplegeneric.
+"""
+
+from IPython.core.error import TryNext
+from simplegeneric import generic
+
+
+@generic
+def inspect_object(obj):
+ """Called when you do obj?"""
+ raise TryNext
+
+
+@generic
+def complete_object(obj, prev_completions):
+ """Custom completer dispatching for python objects.
+
+ Parameters
+ ----------
+ obj : object
+ The object to complete.
+ prev_completions : list
+ List of attributes discovered so far.
+
+ This should return the list of attributes in obj. If you only wish to
+ add to the attributes already discovered normally, return
+ own_attrs + prev_completions.
+ """
+ raise TryNext
+
+
diff --git a/contrib/python/ipython/py2/IPython/utils/importstring.py b/contrib/python/ipython/py2/IPython/utils/importstring.py
index 2c7a2a167e..c8e1840eb3 100644
--- a/contrib/python/ipython/py2/IPython/utils/importstring.py
+++ b/contrib/python/ipython/py2/IPython/utils/importstring.py
@@ -1,39 +1,39 @@
-# encoding: utf-8
-"""
-A simple utility to import something by its string name.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-
-def import_item(name):
- """Import and return ``bar`` given the string ``foo.bar``.
-
- Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
- executing the code ``from foo import bar``.
-
- Parameters
- ----------
- name : string
- The fully qualified name of the module/package being imported.
-
- Returns
- -------
- mod : module object
- The module that was imported.
- """
-
- parts = name.rsplit('.', 1)
- if len(parts) == 2:
- # called with 'foo.bar....'
- package, obj = parts
- module = __import__(package, fromlist=[obj])
- try:
- pak = getattr(module, obj)
- except AttributeError:
- raise ImportError('No module named %s' % obj)
- return pak
- else:
- # called with un-dotted string
- return __import__(parts[0])
+# encoding: utf-8
+"""
+A simple utility to import something by its string name.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+
+def import_item(name):
+ """Import and return ``bar`` given the string ``foo.bar``.
+
+ Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
+ executing the code ``from foo import bar``.
+
+ Parameters
+ ----------
+ name : string
+ The fully qualified name of the module/package being imported.
+
+ Returns
+ -------
+ mod : module object
+ The module that was imported.
+ """
+
+ parts = name.rsplit('.', 1)
+ if len(parts) == 2:
+ # called with 'foo.bar....'
+ package, obj = parts
+ module = __import__(package, fromlist=[obj])
+ try:
+ pak = getattr(module, obj)
+ except AttributeError:
+ raise ImportError('No module named %s' % obj)
+ return pak
+ else:
+ # called with un-dotted string
+ return __import__(parts[0])
diff --git a/contrib/python/ipython/py2/IPython/utils/io.py b/contrib/python/ipython/py2/IPython/utils/io.py
index c316c73bcd..036d6e3926 100644
--- a/contrib/python/ipython/py2/IPython/utils/io.py
+++ b/contrib/python/ipython/py2/IPython/utils/io.py
@@ -1,95 +1,95 @@
-# encoding: utf-8
-"""
-IO related utilities.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-from __future__ import absolute_import
-
-
-import atexit
-import os
-import sys
-import tempfile
+# encoding: utf-8
+"""
+IO related utilities.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+from __future__ import absolute_import
+
+
+import atexit
+import os
+import sys
+import tempfile
import warnings
-from warnings import warn
+from warnings import warn
from IPython.utils.decorators import undoc
-from .capture import CapturedIO, capture_output
-from .py3compat import string_types, input, PY3
-
+from .capture import CapturedIO, capture_output
+from .py3compat import string_types, input, PY3
+
@undoc
-class IOStream:
-
+class IOStream:
+
def __init__(self, stream, fallback=None):
warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
DeprecationWarning, stacklevel=2)
- if not hasattr(stream,'write') or not hasattr(stream,'flush'):
- if fallback is not None:
- stream = fallback
- else:
- raise ValueError("fallback required, but not specified")
- self.stream = stream
- self._swrite = stream.write
-
- # clone all methods not overridden:
- def clone(meth):
- return not hasattr(self, meth) and not meth.startswith('_')
- for meth in filter(clone, dir(stream)):
+ if not hasattr(stream,'write') or not hasattr(stream,'flush'):
+ if fallback is not None:
+ stream = fallback
+ else:
+ raise ValueError("fallback required, but not specified")
+ self.stream = stream
+ self._swrite = stream.write
+
+ # clone all methods not overridden:
+ def clone(meth):
+ return not hasattr(self, meth) and not meth.startswith('_')
+ for meth in filter(clone, dir(stream)):
try:
val = getattr(stream, meth)
except AttributeError:
pass
else:
setattr(self, meth, val)
-
- def __repr__(self):
- cls = self.__class__
- tpl = '{mod}.{cls}({args})'
- return tpl.format(mod=cls.__module__, cls=cls.__name__, args=self.stream)
-
- def write(self,data):
+
+ def __repr__(self):
+ cls = self.__class__
+ tpl = '{mod}.{cls}({args})'
+ return tpl.format(mod=cls.__module__, cls=cls.__name__, args=self.stream)
+
+ def write(self,data):
warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
DeprecationWarning, stacklevel=2)
- try:
- self._swrite(data)
- except:
- try:
- # print handles some unicode issues which may trip a plain
- # write() call. Emulate write() by using an empty end
- # argument.
- print(data, end='', file=self.stream)
- except:
- # if we get here, something is seriously broken.
- print('ERROR - failed to write data to stream:', self.stream,
- file=sys.stderr)
-
- def writelines(self, lines):
+ try:
+ self._swrite(data)
+ except:
+ try:
+ # print handles some unicode issues which may trip a plain
+ # write() call. Emulate write() by using an empty end
+ # argument.
+ print(data, end='', file=self.stream)
+ except:
+ # if we get here, something is seriously broken.
+ print('ERROR - failed to write data to stream:', self.stream,
+ file=sys.stderr)
+
+ def writelines(self, lines):
warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
DeprecationWarning, stacklevel=2)
- if isinstance(lines, string_types):
- lines = [lines]
- for line in lines:
- self.write(line)
-
- # This class used to have a writeln method, but regular files and streams
- # in Python don't have this method. We need to keep this completely
- # compatible so we removed it.
-
- @property
- def closed(self):
- return self.stream.closed
-
- def close(self):
- pass
-
-# setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
+ if isinstance(lines, string_types):
+ lines = [lines]
+ for line in lines:
+ self.write(line)
+
+ # This class used to have a writeln method, but regular files and streams
+ # in Python don't have this method. We need to keep this completely
+ # compatible so we removed it.
+
+ @property
+ def closed(self):
+ return self.stream.closed
+
+ def close(self):
+ pass
+
+# setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
devnull = open(os.devnull, 'w')
-atexit.register(devnull.close)
-
+atexit.register(devnull.close)
+
# io.std* are deprecated, but don't show our own deprecation warnings
# during initialization of the deprecated API.
with warnings.catch_warnings():
@@ -98,149 +98,149 @@ with warnings.catch_warnings():
stdout = IOStream(sys.stdout, fallback=devnull)
stderr = IOStream(sys.stderr, fallback=devnull)
-class Tee(object):
- """A class to duplicate an output stream to stdout/err.
-
- This works in a manner very similar to the Unix 'tee' command.
-
- When the object is closed or deleted, it closes the original file given to
- it for duplication.
- """
- # Inspired by:
- # http://mail.python.org/pipermail/python-list/2007-May/442737.html
-
- def __init__(self, file_or_name, mode="w", channel='stdout'):
- """Construct a new Tee object.
-
- Parameters
- ----------
- file_or_name : filename or open filehandle (writable)
- File that will be duplicated
-
- mode : optional, valid mode for open().
- If a filename was give, open with this mode.
-
- channel : str, one of ['stdout', 'stderr']
- """
- if channel not in ['stdout', 'stderr']:
- raise ValueError('Invalid channel spec %s' % channel)
-
- if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):
- self.file = file_or_name
- else:
- self.file = open(file_or_name, mode)
- self.channel = channel
- self.ostream = getattr(sys, channel)
- setattr(sys, channel, self)
- self._closed = False
-
- def close(self):
- """Close the file and restore the channel."""
- self.flush()
- setattr(sys, self.channel, self.ostream)
- self.file.close()
- self._closed = True
-
- def write(self, data):
- """Write data to both channels."""
- self.file.write(data)
- self.ostream.write(data)
- self.ostream.flush()
-
- def flush(self):
- """Flush both channels."""
- self.file.flush()
- self.ostream.flush()
-
- def __del__(self):
- if not self._closed:
- self.close()
-
-
-def ask_yes_no(prompt, default=None, interrupt=None):
- """Asks a question and returns a boolean (y/n) answer.
-
- If default is given (one of 'y','n'), it is used if the user input is
- empty. If interrupt is given (one of 'y','n'), it is used if the user
- presses Ctrl-C. Otherwise the question is repeated until an answer is
- given.
-
- An EOF is treated as the default answer. If there is no default, an
- exception is raised to prevent infinite loops.
-
- Valid answers are: y/yes/n/no (match is not case sensitive)."""
-
- answers = {'y':True,'n':False,'yes':True,'no':False}
- ans = None
- while ans not in answers.keys():
- try:
- ans = input(prompt+' ').lower()
- if not ans: # response was an empty string
- ans = default
- except KeyboardInterrupt:
- if interrupt:
- ans = interrupt
- except EOFError:
- if default in answers.keys():
- ans = default
- print()
- else:
- raise
-
- return answers[ans]
-
-
-def temp_pyfile(src, ext='.py'):
- """Make a temporary python file, return filename and filehandle.
-
- Parameters
- ----------
- src : string or list of strings (no need for ending newlines if list)
- Source code to be written to the file.
-
- ext : optional, string
- Extension for the generated file.
-
- Returns
- -------
- (filename, open filehandle)
- It is the caller's responsibility to close the open file and unlink it.
- """
- fname = tempfile.mkstemp(ext)[1]
- f = open(fname,'w')
- f.write(src)
- f.flush()
- return fname, f
-
-def atomic_writing(*args, **kwargs):
- """DEPRECATED: moved to notebook.services.contents.fileio"""
- warn("IPython.utils.io.atomic_writing has moved to notebook.services.contents.fileio")
- from notebook.services.contents.fileio import atomic_writing
- return atomic_writing(*args, **kwargs)
-
-def raw_print(*args, **kw):
- """Raw print to sys.__stdout__, otherwise identical interface to print()."""
-
- print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
- file=sys.__stdout__)
- sys.__stdout__.flush()
-
-
-def raw_print_err(*args, **kw):
- """Raw print to sys.__stderr__, otherwise identical interface to print()."""
-
- print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
- file=sys.__stderr__)
- sys.__stderr__.flush()
-
-
-# Short aliases for quick debugging, do NOT use these in production code.
-rprint = raw_print
-rprinte = raw_print_err
-
-
-def unicode_std_stream(stream='stdout'):
- """DEPRECATED, moved to nbconvert.utils.io"""
- warn("IPython.utils.io.unicode_std_stream has moved to nbconvert.utils.io")
- from nbconvert.utils.io import unicode_std_stream
- return unicode_std_stream(stream)
+class Tee(object):
+ """A class to duplicate an output stream to stdout/err.
+
+ This works in a manner very similar to the Unix 'tee' command.
+
+ When the object is closed or deleted, it closes the original file given to
+ it for duplication.
+ """
+ # Inspired by:
+ # http://mail.python.org/pipermail/python-list/2007-May/442737.html
+
+ def __init__(self, file_or_name, mode="w", channel='stdout'):
+ """Construct a new Tee object.
+
+ Parameters
+ ----------
+ file_or_name : filename or open filehandle (writable)
+ File that will be duplicated
+
+ mode : optional, valid mode for open().
+ If a filename was give, open with this mode.
+
+ channel : str, one of ['stdout', 'stderr']
+ """
+ if channel not in ['stdout', 'stderr']:
+ raise ValueError('Invalid channel spec %s' % channel)
+
+ if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):
+ self.file = file_or_name
+ else:
+ self.file = open(file_or_name, mode)
+ self.channel = channel
+ self.ostream = getattr(sys, channel)
+ setattr(sys, channel, self)
+ self._closed = False
+
+ def close(self):
+ """Close the file and restore the channel."""
+ self.flush()
+ setattr(sys, self.channel, self.ostream)
+ self.file.close()
+ self._closed = True
+
+ def write(self, data):
+ """Write data to both channels."""
+ self.file.write(data)
+ self.ostream.write(data)
+ self.ostream.flush()
+
+ def flush(self):
+ """Flush both channels."""
+ self.file.flush()
+ self.ostream.flush()
+
+ def __del__(self):
+ if not self._closed:
+ self.close()
+
+
+def ask_yes_no(prompt, default=None, interrupt=None):
+ """Asks a question and returns a boolean (y/n) answer.
+
+ If default is given (one of 'y','n'), it is used if the user input is
+ empty. If interrupt is given (one of 'y','n'), it is used if the user
+ presses Ctrl-C. Otherwise the question is repeated until an answer is
+ given.
+
+ An EOF is treated as the default answer. If there is no default, an
+ exception is raised to prevent infinite loops.
+
+ Valid answers are: y/yes/n/no (match is not case sensitive)."""
+
+ answers = {'y':True,'n':False,'yes':True,'no':False}
+ ans = None
+ while ans not in answers.keys():
+ try:
+ ans = input(prompt+' ').lower()
+ if not ans: # response was an empty string
+ ans = default
+ except KeyboardInterrupt:
+ if interrupt:
+ ans = interrupt
+ except EOFError:
+ if default in answers.keys():
+ ans = default
+ print()
+ else:
+ raise
+
+ return answers[ans]
+
+
+def temp_pyfile(src, ext='.py'):
+ """Make a temporary python file, return filename and filehandle.
+
+ Parameters
+ ----------
+ src : string or list of strings (no need for ending newlines if list)
+ Source code to be written to the file.
+
+ ext : optional, string
+ Extension for the generated file.
+
+ Returns
+ -------
+ (filename, open filehandle)
+ It is the caller's responsibility to close the open file and unlink it.
+ """
+ fname = tempfile.mkstemp(ext)[1]
+ f = open(fname,'w')
+ f.write(src)
+ f.flush()
+ return fname, f
+
+def atomic_writing(*args, **kwargs):
+ """DEPRECATED: moved to notebook.services.contents.fileio"""
+ warn("IPython.utils.io.atomic_writing has moved to notebook.services.contents.fileio")
+ from notebook.services.contents.fileio import atomic_writing
+ return atomic_writing(*args, **kwargs)
+
+def raw_print(*args, **kw):
+ """Raw print to sys.__stdout__, otherwise identical interface to print()."""
+
+ print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
+ file=sys.__stdout__)
+ sys.__stdout__.flush()
+
+
+def raw_print_err(*args, **kw):
+ """Raw print to sys.__stderr__, otherwise identical interface to print()."""
+
+ print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
+ file=sys.__stderr__)
+ sys.__stderr__.flush()
+
+
+# Short aliases for quick debugging, do NOT use these in production code.
+rprint = raw_print
+rprinte = raw_print_err
+
+
+def unicode_std_stream(stream='stdout'):
+ """DEPRECATED, moved to nbconvert.utils.io"""
+ warn("IPython.utils.io.unicode_std_stream has moved to nbconvert.utils.io")
+ from nbconvert.utils.io import unicode_std_stream
+ return unicode_std_stream(stream)
diff --git a/contrib/python/ipython/py2/IPython/utils/ipstruct.py b/contrib/python/ipython/py2/IPython/utils/ipstruct.py
index e17760b4f9..e2b3e8fa4c 100644
--- a/contrib/python/ipython/py2/IPython/utils/ipstruct.py
+++ b/contrib/python/ipython/py2/IPython/utils/ipstruct.py
@@ -1,391 +1,391 @@
-# encoding: utf-8
-"""A dict subclass that supports attribute style access.
-
-Authors:
-
-* Fernando Perez (original)
-* Brian Granger (refactoring to a dict subclass)
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-__all__ = ['Struct']
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-
-class Struct(dict):
- """A dict subclass with attribute style access.
-
- This dict subclass has a a few extra features:
-
- * Attribute style access.
- * Protection of class members (like keys, items) when using attribute
- style access.
- * The ability to restrict assignment to only existing keys.
- * Intelligent merging.
- * Overloaded operators.
- """
- _allownew = True
- def __init__(self, *args, **kw):
- """Initialize with a dictionary, another Struct, or data.
-
- Parameters
- ----------
- args : dict, Struct
- Initialize with one dict or Struct
- kw : dict
- Initialize with key, value pairs.
-
- Examples
- --------
-
- >>> s = Struct(a=10,b=30)
- >>> s.a
- 10
- >>> s.b
- 30
- >>> s2 = Struct(s,c=30)
- >>> sorted(s2.keys())
- ['a', 'b', 'c']
- """
- object.__setattr__(self, '_allownew', True)
- dict.__init__(self, *args, **kw)
-
- def __setitem__(self, key, value):
- """Set an item with check for allownew.
-
- Examples
- --------
-
- >>> s = Struct()
- >>> s['a'] = 10
- >>> s.allow_new_attr(False)
- >>> s['a'] = 10
- >>> s['a']
- 10
- >>> try:
- ... s['b'] = 20
- ... except KeyError:
- ... print('this is not allowed')
- ...
- this is not allowed
- """
- if not self._allownew and key not in self:
- raise KeyError(
- "can't create new attribute %s when allow_new_attr(False)" % key)
- dict.__setitem__(self, key, value)
-
- def __setattr__(self, key, value):
- """Set an attr with protection of class members.
-
- This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to
- :exc:`AttributeError`.
-
- Examples
- --------
-
- >>> s = Struct()
- >>> s.a = 10
- >>> s.a
- 10
- >>> try:
- ... s.get = 10
- ... except AttributeError:
- ... print("you can't set a class member")
- ...
- you can't set a class member
- """
- # If key is an str it might be a class member or instance var
- if isinstance(key, str):
- # I can't simply call hasattr here because it calls getattr, which
- # calls self.__getattr__, which returns True for keys in
- # self._data. But I only want keys in the class and in
- # self.__dict__
- if key in self.__dict__ or hasattr(Struct, key):
- raise AttributeError(
- 'attr %s is a protected member of class Struct.' % key
- )
- try:
- self.__setitem__(key, value)
- except KeyError as e:
- raise AttributeError(e)
-
- def __getattr__(self, key):
- """Get an attr by calling :meth:`dict.__getitem__`.
-
- Like :meth:`__setattr__`, this method converts :exc:`KeyError` to
- :exc:`AttributeError`.
-
- Examples
- --------
-
- >>> s = Struct(a=10)
- >>> s.a
- 10
- >>> type(s.get)
- <... 'builtin_function_or_method'>
- >>> try:
- ... s.b
- ... except AttributeError:
- ... print("I don't have that key")
- ...
- I don't have that key
- """
- try:
- result = self[key]
- except KeyError:
- raise AttributeError(key)
- else:
- return result
-
- def __iadd__(self, other):
- """s += s2 is a shorthand for s.merge(s2).
-
- Examples
- --------
-
- >>> s = Struct(a=10,b=30)
- >>> s2 = Struct(a=20,c=40)
- >>> s += s2
- >>> sorted(s.keys())
- ['a', 'b', 'c']
- """
- self.merge(other)
- return self
-
- def __add__(self,other):
- """s + s2 -> New Struct made from s.merge(s2).
-
- Examples
- --------
-
- >>> s1 = Struct(a=10,b=30)
- >>> s2 = Struct(a=20,c=40)
- >>> s = s1 + s2
- >>> sorted(s.keys())
- ['a', 'b', 'c']
- """
- sout = self.copy()
- sout.merge(other)
- return sout
-
- def __sub__(self,other):
- """s1 - s2 -> remove keys in s2 from s1.
-
- Examples
- --------
-
- >>> s1 = Struct(a=10,b=30)
- >>> s2 = Struct(a=40)
- >>> s = s1 - s2
- >>> s
- {'b': 30}
- """
- sout = self.copy()
- sout -= other
- return sout
-
- def __isub__(self,other):
- """Inplace remove keys from self that are in other.
-
- Examples
- --------
-
- >>> s1 = Struct(a=10,b=30)
- >>> s2 = Struct(a=40)
- >>> s1 -= s2
- >>> s1
- {'b': 30}
- """
- for k in other.keys():
- if k in self:
- del self[k]
- return self
-
- def __dict_invert(self, data):
- """Helper function for merge.
-
- Takes a dictionary whose values are lists and returns a dict with
- the elements of each list as keys and the original keys as values.
- """
- outdict = {}
- for k,lst in data.items():
- if isinstance(lst, str):
- lst = lst.split()
- for entry in lst:
- outdict[entry] = k
- return outdict
-
- def dict(self):
- return self
-
- def copy(self):
- """Return a copy as a Struct.
-
- Examples
- --------
-
- >>> s = Struct(a=10,b=30)
- >>> s2 = s.copy()
- >>> type(s2) is Struct
- True
- """
- return Struct(dict.copy(self))
-
- def hasattr(self, key):
- """hasattr function available as a method.
-
- Implemented like has_key.
-
- Examples
- --------
-
- >>> s = Struct(a=10)
- >>> s.hasattr('a')
- True
- >>> s.hasattr('b')
- False
- >>> s.hasattr('get')
- False
- """
- return key in self
-
- def allow_new_attr(self, allow = True):
- """Set whether new attributes can be created in this Struct.
-
- This can be used to catch typos by verifying that the attribute user
- tries to change already exists in this Struct.
- """
- object.__setattr__(self, '_allownew', allow)
-
- def merge(self, __loc_data__=None, __conflict_solve=None, **kw):
- """Merge two Structs with customizable conflict resolution.
-
- This is similar to :meth:`update`, but much more flexible. First, a
- dict is made from data+key=value pairs. When merging this dict with
- the Struct S, the optional dictionary 'conflict' is used to decide
- what to do.
-
- If conflict is not given, the default behavior is to preserve any keys
- with their current value (the opposite of the :meth:`update` method's
- behavior).
-
- Parameters
- ----------
- __loc_data : dict, Struct
- The data to merge into self
- __conflict_solve : dict
- The conflict policy dict. The keys are binary functions used to
- resolve the conflict and the values are lists of strings naming
- the keys the conflict resolution function applies to. Instead of
- a list of strings a space separated string can be used, like
- 'a b c'.
- kw : dict
- Additional key, value pairs to merge in
-
- Notes
- -----
-
- The `__conflict_solve` dict is a dictionary of binary functions which will be used to
- solve key conflicts. Here is an example::
-
- __conflict_solve = dict(
- func1=['a','b','c'],
- func2=['d','e']
- )
-
- In this case, the function :func:`func1` will be used to resolve
- keys 'a', 'b' and 'c' and the function :func:`func2` will be used for
- keys 'd' and 'e'. This could also be written as::
-
- __conflict_solve = dict(func1='a b c',func2='d e')
-
- These functions will be called for each key they apply to with the
- form::
-
- func1(self['a'], other['a'])
-
- The return value is used as the final merged value.
-
- As a convenience, merge() provides five (the most commonly needed)
- pre-defined policies: preserve, update, add, add_flip and add_s. The
- easiest explanation is their implementation::
-
- preserve = lambda old,new: old
- update = lambda old,new: new
- add = lambda old,new: old + new
- add_flip = lambda old,new: new + old # note change of order!
- add_s = lambda old,new: old + ' ' + new # only for str!
-
- You can use those four words (as strings) as keys instead
- of defining them as functions, and the merge method will substitute
- the appropriate functions for you.
-
- For more complicated conflict resolution policies, you still need to
- construct your own functions.
-
- Examples
- --------
-
- This show the default policy:
-
- >>> s = Struct(a=10,b=30)
- >>> s2 = Struct(a=20,c=40)
- >>> s.merge(s2)
- >>> sorted(s.items())
- [('a', 10), ('b', 30), ('c', 40)]
-
- Now, show how to specify a conflict dict:
-
- >>> s = Struct(a=10,b=30)
- >>> s2 = Struct(a=20,b=40)
- >>> conflict = {'update':'a','add':'b'}
- >>> s.merge(s2,conflict)
- >>> sorted(s.items())
- [('a', 20), ('b', 70)]
- """
-
- data_dict = dict(__loc_data__,**kw)
-
- # policies for conflict resolution: two argument functions which return
- # the value that will go in the new struct
- preserve = lambda old,new: old
- update = lambda old,new: new
- add = lambda old,new: old + new
- add_flip = lambda old,new: new + old # note change of order!
- add_s = lambda old,new: old + ' ' + new
-
- # default policy is to keep current keys when there's a conflict
- conflict_solve = dict.fromkeys(self, preserve)
-
- # the conflict_solve dictionary is given by the user 'inverted': we
- # need a name-function mapping, it comes as a function -> names
- # dict. Make a local copy (b/c we'll make changes), replace user
- # strings for the three builtin policies and invert it.
- if __conflict_solve:
- inv_conflict_solve_user = __conflict_solve.copy()
- for name, func in [('preserve',preserve), ('update',update),
- ('add',add), ('add_flip',add_flip),
- ('add_s',add_s)]:
- if name in inv_conflict_solve_user.keys():
- inv_conflict_solve_user[func] = inv_conflict_solve_user[name]
- del inv_conflict_solve_user[name]
- conflict_solve.update(self.__dict_invert(inv_conflict_solve_user))
- for key in data_dict:
- if key not in self:
- self[key] = data_dict[key]
- else:
- self[key] = conflict_solve[key](self[key],data_dict[key])
-
+# encoding: utf-8
+"""A dict subclass that supports attribute style access.
+
+Authors:
+
+* Fernando Perez (original)
+* Brian Granger (refactoring to a dict subclass)
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+__all__ = ['Struct']
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+
+class Struct(dict):
+ """A dict subclass with attribute style access.
+
+ This dict subclass has a a few extra features:
+
+ * Attribute style access.
+ * Protection of class members (like keys, items) when using attribute
+ style access.
+ * The ability to restrict assignment to only existing keys.
+ * Intelligent merging.
+ * Overloaded operators.
+ """
+ _allownew = True
+ def __init__(self, *args, **kw):
+ """Initialize with a dictionary, another Struct, or data.
+
+ Parameters
+ ----------
+ args : dict, Struct
+ Initialize with one dict or Struct
+ kw : dict
+ Initialize with key, value pairs.
+
+ Examples
+ --------
+
+ >>> s = Struct(a=10,b=30)
+ >>> s.a
+ 10
+ >>> s.b
+ 30
+ >>> s2 = Struct(s,c=30)
+ >>> sorted(s2.keys())
+ ['a', 'b', 'c']
+ """
+ object.__setattr__(self, '_allownew', True)
+ dict.__init__(self, *args, **kw)
+
+ def __setitem__(self, key, value):
+ """Set an item with check for allownew.
+
+ Examples
+ --------
+
+ >>> s = Struct()
+ >>> s['a'] = 10
+ >>> s.allow_new_attr(False)
+ >>> s['a'] = 10
+ >>> s['a']
+ 10
+ >>> try:
+ ... s['b'] = 20
+ ... except KeyError:
+ ... print('this is not allowed')
+ ...
+ this is not allowed
+ """
+ if not self._allownew and key not in self:
+ raise KeyError(
+ "can't create new attribute %s when allow_new_attr(False)" % key)
+ dict.__setitem__(self, key, value)
+
+ def __setattr__(self, key, value):
+ """Set an attr with protection of class members.
+
+ This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to
+ :exc:`AttributeError`.
+
+ Examples
+ --------
+
+ >>> s = Struct()
+ >>> s.a = 10
+ >>> s.a
+ 10
+ >>> try:
+ ... s.get = 10
+ ... except AttributeError:
+ ... print("you can't set a class member")
+ ...
+ you can't set a class member
+ """
+ # If key is an str it might be a class member or instance var
+ if isinstance(key, str):
+ # I can't simply call hasattr here because it calls getattr, which
+ # calls self.__getattr__, which returns True for keys in
+ # self._data. But I only want keys in the class and in
+ # self.__dict__
+ if key in self.__dict__ or hasattr(Struct, key):
+ raise AttributeError(
+ 'attr %s is a protected member of class Struct.' % key
+ )
+ try:
+ self.__setitem__(key, value)
+ except KeyError as e:
+ raise AttributeError(e)
+
+ def __getattr__(self, key):
+ """Get an attr by calling :meth:`dict.__getitem__`.
+
+ Like :meth:`__setattr__`, this method converts :exc:`KeyError` to
+ :exc:`AttributeError`.
+
+ Examples
+ --------
+
+ >>> s = Struct(a=10)
+ >>> s.a
+ 10
+ >>> type(s.get)
+ <... 'builtin_function_or_method'>
+ >>> try:
+ ... s.b
+ ... except AttributeError:
+ ... print("I don't have that key")
+ ...
+ I don't have that key
+ """
+ try:
+ result = self[key]
+ except KeyError:
+ raise AttributeError(key)
+ else:
+ return result
+
+ def __iadd__(self, other):
+ """s += s2 is a shorthand for s.merge(s2).
+
+ Examples
+ --------
+
+ >>> s = Struct(a=10,b=30)
+ >>> s2 = Struct(a=20,c=40)
+ >>> s += s2
+ >>> sorted(s.keys())
+ ['a', 'b', 'c']
+ """
+ self.merge(other)
+ return self
+
+ def __add__(self,other):
+ """s + s2 -> New Struct made from s.merge(s2).
+
+ Examples
+ --------
+
+ >>> s1 = Struct(a=10,b=30)
+ >>> s2 = Struct(a=20,c=40)
+ >>> s = s1 + s2
+ >>> sorted(s.keys())
+ ['a', 'b', 'c']
+ """
+ sout = self.copy()
+ sout.merge(other)
+ return sout
+
+ def __sub__(self,other):
+ """s1 - s2 -> remove keys in s2 from s1.
+
+ Examples
+ --------
+
+ >>> s1 = Struct(a=10,b=30)
+ >>> s2 = Struct(a=40)
+ >>> s = s1 - s2
+ >>> s
+ {'b': 30}
+ """
+ sout = self.copy()
+ sout -= other
+ return sout
+
+ def __isub__(self,other):
+ """Inplace remove keys from self that are in other.
+
+ Examples
+ --------
+
+ >>> s1 = Struct(a=10,b=30)
+ >>> s2 = Struct(a=40)
+ >>> s1 -= s2
+ >>> s1
+ {'b': 30}
+ """
+ for k in other.keys():
+ if k in self:
+ del self[k]
+ return self
+
+ def __dict_invert(self, data):
+ """Helper function for merge.
+
+ Takes a dictionary whose values are lists and returns a dict with
+ the elements of each list as keys and the original keys as values.
+ """
+ outdict = {}
+ for k,lst in data.items():
+ if isinstance(lst, str):
+ lst = lst.split()
+ for entry in lst:
+ outdict[entry] = k
+ return outdict
+
+ def dict(self):
+ return self
+
+ def copy(self):
+ """Return a copy as a Struct.
+
+ Examples
+ --------
+
+ >>> s = Struct(a=10,b=30)
+ >>> s2 = s.copy()
+ >>> type(s2) is Struct
+ True
+ """
+ return Struct(dict.copy(self))
+
+ def hasattr(self, key):
+ """hasattr function available as a method.
+
+ Implemented like has_key.
+
+ Examples
+ --------
+
+ >>> s = Struct(a=10)
+ >>> s.hasattr('a')
+ True
+ >>> s.hasattr('b')
+ False
+ >>> s.hasattr('get')
+ False
+ """
+ return key in self
+
+ def allow_new_attr(self, allow = True):
+ """Set whether new attributes can be created in this Struct.
+
+ This can be used to catch typos by verifying that the attribute user
+ tries to change already exists in this Struct.
+ """
+ object.__setattr__(self, '_allownew', allow)
+
+ def merge(self, __loc_data__=None, __conflict_solve=None, **kw):
+ """Merge two Structs with customizable conflict resolution.
+
+ This is similar to :meth:`update`, but much more flexible. First, a
+ dict is made from data+key=value pairs. When merging this dict with
+ the Struct S, the optional dictionary 'conflict' is used to decide
+ what to do.
+
+ If conflict is not given, the default behavior is to preserve any keys
+ with their current value (the opposite of the :meth:`update` method's
+ behavior).
+
+ Parameters
+ ----------
+ __loc_data : dict, Struct
+ The data to merge into self
+ __conflict_solve : dict
+ The conflict policy dict. The keys are binary functions used to
+ resolve the conflict and the values are lists of strings naming
+ the keys the conflict resolution function applies to. Instead of
+ a list of strings a space separated string can be used, like
+ 'a b c'.
+ kw : dict
+ Additional key, value pairs to merge in
+
+ Notes
+ -----
+
+ The `__conflict_solve` dict is a dictionary of binary functions which will be used to
+ solve key conflicts. Here is an example::
+
+ __conflict_solve = dict(
+ func1=['a','b','c'],
+ func2=['d','e']
+ )
+
+ In this case, the function :func:`func1` will be used to resolve
+ keys 'a', 'b' and 'c' and the function :func:`func2` will be used for
+ keys 'd' and 'e'. This could also be written as::
+
+ __conflict_solve = dict(func1='a b c',func2='d e')
+
+ These functions will be called for each key they apply to with the
+ form::
+
+ func1(self['a'], other['a'])
+
+ The return value is used as the final merged value.
+
+ As a convenience, merge() provides five (the most commonly needed)
+ pre-defined policies: preserve, update, add, add_flip and add_s. The
+ easiest explanation is their implementation::
+
+ preserve = lambda old,new: old
+ update = lambda old,new: new
+ add = lambda old,new: old + new
+ add_flip = lambda old,new: new + old # note change of order!
+ add_s = lambda old,new: old + ' ' + new # only for str!
+
+ You can use those four words (as strings) as keys instead
+ of defining them as functions, and the merge method will substitute
+ the appropriate functions for you.
+
+ For more complicated conflict resolution policies, you still need to
+ construct your own functions.
+
+ Examples
+ --------
+
+ This show the default policy:
+
+ >>> s = Struct(a=10,b=30)
+ >>> s2 = Struct(a=20,c=40)
+ >>> s.merge(s2)
+ >>> sorted(s.items())
+ [('a', 10), ('b', 30), ('c', 40)]
+
+ Now, show how to specify a conflict dict:
+
+ >>> s = Struct(a=10,b=30)
+ >>> s2 = Struct(a=20,b=40)
+ >>> conflict = {'update':'a','add':'b'}
+ >>> s.merge(s2,conflict)
+ >>> sorted(s.items())
+ [('a', 20), ('b', 70)]
+ """
+
+ data_dict = dict(__loc_data__,**kw)
+
+ # policies for conflict resolution: two argument functions which return
+ # the value that will go in the new struct
+ preserve = lambda old,new: old
+ update = lambda old,new: new
+ add = lambda old,new: old + new
+ add_flip = lambda old,new: new + old # note change of order!
+ add_s = lambda old,new: old + ' ' + new
+
+ # default policy is to keep current keys when there's a conflict
+ conflict_solve = dict.fromkeys(self, preserve)
+
+ # the conflict_solve dictionary is given by the user 'inverted': we
+ # need a name-function mapping, it comes as a function -> names
+ # dict. Make a local copy (b/c we'll make changes), replace user
+ # strings for the three builtin policies and invert it.
+ if __conflict_solve:
+ inv_conflict_solve_user = __conflict_solve.copy()
+ for name, func in [('preserve',preserve), ('update',update),
+ ('add',add), ('add_flip',add_flip),
+ ('add_s',add_s)]:
+ if name in inv_conflict_solve_user.keys():
+ inv_conflict_solve_user[func] = inv_conflict_solve_user[name]
+ del inv_conflict_solve_user[name]
+ conflict_solve.update(self.__dict_invert(inv_conflict_solve_user))
+ for key in data_dict:
+ if key not in self:
+ self[key] = data_dict[key]
+ else:
+ self[key] = conflict_solve[key](self[key],data_dict[key])
+
diff --git a/contrib/python/ipython/py2/IPython/utils/jsonutil.py b/contrib/python/ipython/py2/IPython/utils/jsonutil.py
index 4bb400ca1e..c3ee93859e 100644
--- a/contrib/python/ipython/py2/IPython/utils/jsonutil.py
+++ b/contrib/python/ipython/py2/IPython/utils/jsonutil.py
@@ -1,5 +1,5 @@
-from warnings import warn
-
-warn("IPython.utils.jsonutil has moved to jupyter_client.jsonutil")
-
-from jupyter_client.jsonutil import *
+from warnings import warn
+
+warn("IPython.utils.jsonutil has moved to jupyter_client.jsonutil")
+
+from jupyter_client.jsonutil import *
diff --git a/contrib/python/ipython/py2/IPython/utils/localinterfaces.py b/contrib/python/ipython/py2/IPython/utils/localinterfaces.py
index f90564def5..89b8fdeb54 100644
--- a/contrib/python/ipython/py2/IPython/utils/localinterfaces.py
+++ b/contrib/python/ipython/py2/IPython/utils/localinterfaces.py
@@ -1,5 +1,5 @@
-from warnings import warn
-
-warn("IPython.utils.localinterfaces has moved to jupyter_client.localinterfaces")
-
-from jupyter_client.localinterfaces import *
+from warnings import warn
+
+warn("IPython.utils.localinterfaces has moved to jupyter_client.localinterfaces")
+
+from jupyter_client.localinterfaces import *
diff --git a/contrib/python/ipython/py2/IPython/utils/log.py b/contrib/python/ipython/py2/IPython/utils/log.py
index 422bb9b343..3eb9bdadd8 100644
--- a/contrib/python/ipython/py2/IPython/utils/log.py
+++ b/contrib/python/ipython/py2/IPython/utils/log.py
@@ -1,7 +1,7 @@
-from __future__ import absolute_import
-
-from warnings import warn
-
-warn("IPython.utils.log has moved to traitlets.log")
-
-from traitlets.log import *
+from __future__ import absolute_import
+
+from warnings import warn
+
+warn("IPython.utils.log has moved to traitlets.log")
+
+from traitlets.log import *
diff --git a/contrib/python/ipython/py2/IPython/utils/module_paths.py b/contrib/python/ipython/py2/IPython/utils/module_paths.py
index fc2c7f07c0..45a711c0b4 100644
--- a/contrib/python/ipython/py2/IPython/utils/module_paths.py
+++ b/contrib/python/ipython/py2/IPython/utils/module_paths.py
@@ -1,125 +1,125 @@
-"""Utility functions for finding modules
-
-Utility functions for finding modules on sys.path.
-
-`find_mod` finds named module on sys.path.
-
-`get_init` helper function that finds __init__ file in a directory.
-
-`find_module` variant of imp.find_module in std_lib that only returns
-path to module and not an open file object as well.
-
-
-
-"""
-#-----------------------------------------------------------------------------
-# Copyright (c) 2011, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-from __future__ import print_function
-
-# Stdlib imports
-import imp
-import os
-
-# Third-party imports
-
-# Our own imports
-
-
-#-----------------------------------------------------------------------------
-# Globals and constants
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Local utilities
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Classes and functions
-#-----------------------------------------------------------------------------
-def find_module(name, path=None):
- """imp.find_module variant that only return path of module.
-
- The `imp.find_module` returns a filehandle that we are not interested in.
- Also we ignore any bytecode files that `imp.find_module` finds.
-
- Parameters
- ----------
- name : str
- name of module to locate
- path : list of str
- list of paths to search for `name`. If path=None then search sys.path
-
- Returns
- -------
- filename : str
- Return full path of module or None if module is missing or does not have
- .py or .pyw extension
- """
- if name is None:
- return None
- try:
- file, filename, _ = imp.find_module(name, path)
- except ImportError:
- return None
- if file is None:
- return filename
- else:
- file.close()
- if os.path.splitext(filename)[1] in [".py", ".pyc"]:
- return filename
- else:
- return None
-
-def get_init(dirname):
- """Get __init__ file path for module directory
-
- Parameters
- ----------
- dirname : str
- Find the __init__ file in directory `dirname`
-
- Returns
- -------
- init_path : str
- Path to __init__ file
- """
- fbase = os.path.join(dirname, "__init__")
- for ext in [".py", ".pyw"]:
- fname = fbase + ext
- if os.path.isfile(fname):
- return fname
-
-
-def find_mod(module_name):
- """Find module `module_name` on sys.path
-
- Return the path to module `module_name`. If `module_name` refers to
- a module directory then return path to __init__ file. Return full
- path of module or None if module is missing or does not have .py or .pyw
- extension. We are not interested in running bytecode.
-
- Parameters
- ----------
- module_name : str
-
- Returns
- -------
- modulepath : str
- Path to module `module_name`.
- """
- parts = module_name.split(".")
- basepath = find_module(parts[0])
- for submodname in parts[1:]:
- basepath = find_module(submodname, [basepath])
- if basepath and os.path.isdir(basepath):
- basepath = get_init(basepath)
- return basepath
+"""Utility functions for finding modules
+
+Utility functions for finding modules on sys.path.
+
+`find_mod` finds named module on sys.path.
+
+`get_init` helper function that finds __init__ file in a directory.
+
+`find_module` variant of imp.find_module in std_lib that only returns
+path to module and not an open file object as well.
+
+
+
+"""
+#-----------------------------------------------------------------------------
+# Copyright (c) 2011, the IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+from __future__ import print_function
+
+# Stdlib imports
+import imp
+import os
+
+# Third-party imports
+
+# Our own imports
+
+
+#-----------------------------------------------------------------------------
+# Globals and constants
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Local utilities
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Classes and functions
+#-----------------------------------------------------------------------------
+def find_module(name, path=None):
+ """imp.find_module variant that only return path of module.
+
+ The `imp.find_module` returns a filehandle that we are not interested in.
+ Also we ignore any bytecode files that `imp.find_module` finds.
+
+ Parameters
+ ----------
+ name : str
+ name of module to locate
+ path : list of str
+ list of paths to search for `name`. If path=None then search sys.path
+
+ Returns
+ -------
+ filename : str
+ Return full path of module or None if module is missing or does not have
+ .py or .pyw extension
+ """
+ if name is None:
+ return None
+ try:
+ file, filename, _ = imp.find_module(name, path)
+ except ImportError:
+ return None
+ if file is None:
+ return filename
+ else:
+ file.close()
+ if os.path.splitext(filename)[1] in [".py", ".pyc"]:
+ return filename
+ else:
+ return None
+
+def get_init(dirname):
+ """Get __init__ file path for module directory
+
+ Parameters
+ ----------
+ dirname : str
+ Find the __init__ file in directory `dirname`
+
+ Returns
+ -------
+ init_path : str
+ Path to __init__ file
+ """
+ fbase = os.path.join(dirname, "__init__")
+ for ext in [".py", ".pyw"]:
+ fname = fbase + ext
+ if os.path.isfile(fname):
+ return fname
+
+
+def find_mod(module_name):
+ """Find module `module_name` on sys.path
+
+ Return the path to module `module_name`. If `module_name` refers to
+ a module directory then return path to __init__ file. Return full
+ path of module or None if module is missing or does not have .py or .pyw
+ extension. We are not interested in running bytecode.
+
+ Parameters
+ ----------
+ module_name : str
+
+ Returns
+ -------
+ modulepath : str
+ Path to module `module_name`.
+ """
+ parts = module_name.split(".")
+ basepath = find_module(parts[0])
+ for submodname in parts[1:]:
+ basepath = find_module(submodname, [basepath])
+ if basepath and os.path.isdir(basepath):
+ basepath = get_init(basepath)
+ return basepath
diff --git a/contrib/python/ipython/py2/IPython/utils/openpy.py b/contrib/python/ipython/py2/IPython/utils/openpy.py
index f55f254bc1..0a7cc0f00e 100644
--- a/contrib/python/ipython/py2/IPython/utils/openpy.py
+++ b/contrib/python/ipython/py2/IPython/utils/openpy.py
@@ -1,249 +1,249 @@
-"""
-Tools to open .py files as Unicode, using the encoding specified within the file,
-as per PEP 263.
-
-Much of the code is taken from the tokenize module in Python 3.2.
-"""
-from __future__ import absolute_import
-
-import io
-from io import TextIOWrapper, BytesIO
-import os.path
-import re
-
-from .py3compat import unicode_type
-
-cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)", re.UNICODE)
-cookie_comment_re = re.compile(r"^\s*#.*coding[:=]\s*([-\w.]+)", re.UNICODE)
-
-try:
- # Available in Python 3
- from tokenize import detect_encoding
-except ImportError:
- from codecs import lookup, BOM_UTF8
-
- # Copied from Python 3.2 tokenize
- def _get_normal_name(orig_enc):
- """Imitates get_normal_name in tokenizer.c."""
- # Only care about the first 12 characters.
- enc = orig_enc[:12].lower().replace("_", "-")
- if enc == "utf-8" or enc.startswith("utf-8-"):
- return "utf-8"
- if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
- enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
- return "iso-8859-1"
- return orig_enc
-
- # Copied from Python 3.2 tokenize
- def detect_encoding(readline):
- """
- The detect_encoding() function is used to detect the encoding that should
- be used to decode a Python source file. It requires one argment, readline,
- in the same way as the tokenize() generator.
-
- It will call readline a maximum of twice, and return the encoding used
- (as a string) and a list of any lines (left as bytes) it has read in.
-
- It detects the encoding from the presence of a utf-8 bom or an encoding
- cookie as specified in pep-0263. If both a bom and a cookie are present,
- but disagree, a SyntaxError will be raised. If the encoding cookie is an
- invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
- 'utf-8-sig' is returned.
-
- If no encoding is specified, then the default of 'utf-8' will be returned.
- """
- bom_found = False
- encoding = None
- default = 'utf-8'
- def read_or_stop():
- try:
- return readline()
- except StopIteration:
- return b''
-
- def find_cookie(line):
- try:
- line_string = line.decode('ascii')
- except UnicodeDecodeError:
- return None
-
- matches = cookie_re.findall(line_string)
- if not matches:
- return None
- encoding = _get_normal_name(matches[0])
- try:
- codec = lookup(encoding)
- except LookupError:
- # This behaviour mimics the Python interpreter
- raise SyntaxError("unknown encoding: " + encoding)
-
- if bom_found:
- if codec.name != 'utf-8':
- # This behaviour mimics the Python interpreter
- raise SyntaxError('encoding problem: utf-8')
- encoding += '-sig'
- return encoding
-
- first = read_or_stop()
- if first.startswith(BOM_UTF8):
- bom_found = True
- first = first[3:]
- default = 'utf-8-sig'
- if not first:
- return default, []
-
- encoding = find_cookie(first)
- if encoding:
- return encoding, [first]
-
- second = read_or_stop()
- if not second:
- return default, [first]
-
- encoding = find_cookie(second)
- if encoding:
- return encoding, [first, second]
-
- return default, [first, second]
-
-try:
- # Available in Python 3.2 and above.
- from tokenize import open
-except ImportError:
- # Copied from Python 3.2 tokenize
- def open(filename):
- """Open a file in read only mode using the encoding detected by
- detect_encoding().
- """
- buffer = io.open(filename, 'rb') # Tweaked to use io.open for Python 2
- encoding, lines = detect_encoding(buffer.readline)
- buffer.seek(0)
- text = TextIOWrapper(buffer, encoding, line_buffering=True)
- text.mode = 'r'
- return text
-
-def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True):
- """Converts a bytes string with python source code to unicode.
-
- Unicode strings are passed through unchanged. Byte strings are checked
- for the python source file encoding cookie to determine encoding.
- txt can be either a bytes buffer or a string containing the source
- code.
- """
- if isinstance(txt, unicode_type):
- return txt
- if isinstance(txt, bytes):
- buffer = BytesIO(txt)
- else:
- buffer = txt
+"""
+Tools to open .py files as Unicode, using the encoding specified within the file,
+as per PEP 263.
+
+Much of the code is taken from the tokenize module in Python 3.2.
+"""
+from __future__ import absolute_import
+
+import io
+from io import TextIOWrapper, BytesIO
+import os.path
+import re
+
+from .py3compat import unicode_type
+
+cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)", re.UNICODE)
+cookie_comment_re = re.compile(r"^\s*#.*coding[:=]\s*([-\w.]+)", re.UNICODE)
+
+try:
+ # Available in Python 3
+ from tokenize import detect_encoding
+except ImportError:
+ from codecs import lookup, BOM_UTF8
+
+ # Copied from Python 3.2 tokenize
+ def _get_normal_name(orig_enc):
+ """Imitates get_normal_name in tokenizer.c."""
+ # Only care about the first 12 characters.
+ enc = orig_enc[:12].lower().replace("_", "-")
+ if enc == "utf-8" or enc.startswith("utf-8-"):
+ return "utf-8"
+ if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
+ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
+ return "iso-8859-1"
+ return orig_enc
+
+ # Copied from Python 3.2 tokenize
+ def detect_encoding(readline):
+ """
+ The detect_encoding() function is used to detect the encoding that should
+ be used to decode a Python source file. It requires one argment, readline,
+ in the same way as the tokenize() generator.
+
+ It will call readline a maximum of twice, and return the encoding used
+ (as a string) and a list of any lines (left as bytes) it has read in.
+
+ It detects the encoding from the presence of a utf-8 bom or an encoding
+ cookie as specified in pep-0263. If both a bom and a cookie are present,
+ but disagree, a SyntaxError will be raised. If the encoding cookie is an
+ invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
+ 'utf-8-sig' is returned.
+
+ If no encoding is specified, then the default of 'utf-8' will be returned.
+ """
+ bom_found = False
+ encoding = None
+ default = 'utf-8'
+ def read_or_stop():
+ try:
+ return readline()
+ except StopIteration:
+ return b''
+
+ def find_cookie(line):
+ try:
+ line_string = line.decode('ascii')
+ except UnicodeDecodeError:
+ return None
+
+ matches = cookie_re.findall(line_string)
+ if not matches:
+ return None
+ encoding = _get_normal_name(matches[0])
+ try:
+ codec = lookup(encoding)
+ except LookupError:
+ # This behaviour mimics the Python interpreter
+ raise SyntaxError("unknown encoding: " + encoding)
+
+ if bom_found:
+ if codec.name != 'utf-8':
+ # This behaviour mimics the Python interpreter
+ raise SyntaxError('encoding problem: utf-8')
+ encoding += '-sig'
+ return encoding
+
+ first = read_or_stop()
+ if first.startswith(BOM_UTF8):
+ bom_found = True
+ first = first[3:]
+ default = 'utf-8-sig'
+ if not first:
+ return default, []
+
+ encoding = find_cookie(first)
+ if encoding:
+ return encoding, [first]
+
+ second = read_or_stop()
+ if not second:
+ return default, [first]
+
+ encoding = find_cookie(second)
+ if encoding:
+ return encoding, [first, second]
+
+ return default, [first, second]
+
+try:
+ # Available in Python 3.2 and above.
+ from tokenize import open
+except ImportError:
+ # Copied from Python 3.2 tokenize
+ def open(filename):
+ """Open a file in read only mode using the encoding detected by
+ detect_encoding().
+ """
+ buffer = io.open(filename, 'rb') # Tweaked to use io.open for Python 2
+ encoding, lines = detect_encoding(buffer.readline)
+ buffer.seek(0)
+ text = TextIOWrapper(buffer, encoding, line_buffering=True)
+ text.mode = 'r'
+ return text
+
+def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True):
+ """Converts a bytes string with python source code to unicode.
+
+ Unicode strings are passed through unchanged. Byte strings are checked
+ for the python source file encoding cookie to determine encoding.
+ txt can be either a bytes buffer or a string containing the source
+ code.
+ """
+ if isinstance(txt, unicode_type):
+ return txt
+ if isinstance(txt, bytes):
+ buffer = BytesIO(txt)
+ else:
+ buffer = txt
+ try:
+ encoding, _ = detect_encoding(buffer.readline)
+ except SyntaxError:
+ encoding = "ascii"
+ buffer.seek(0)
+ text = TextIOWrapper(buffer, encoding, errors=errors, line_buffering=True)
+ text.mode = 'r'
+ if skip_encoding_cookie:
+ return u"".join(strip_encoding_cookie(text))
+ else:
+ return text.read()
+
+def strip_encoding_cookie(filelike):
+ """Generator to pull lines from a text-mode file, skipping the encoding
+ cookie if it is found in the first two lines.
+ """
+ it = iter(filelike)
+ try:
+ first = next(it)
+ if not cookie_comment_re.match(first):
+ yield first
+ second = next(it)
+ if not cookie_comment_re.match(second):
+ yield second
+ except StopIteration:
+ return
+
+ for line in it:
+ yield line
+
+def read_py_file(filename, skip_encoding_cookie=True):
+ """Read a Python file, using the encoding declared inside the file.
+
+ Parameters
+ ----------
+ filename : str
+ The path to the file to read.
+ skip_encoding_cookie : bool
+ If True (the default), and the encoding declaration is found in the first
+ two lines, that line will be excluded from the output - compiling a
+ unicode string with an encoding declaration is a SyntaxError in Python 2.
+
+ Returns
+ -------
+ A unicode string containing the contents of the file.
+ """
+ with open(filename) as f: # the open function defined in this module.
+ if skip_encoding_cookie:
+ return "".join(strip_encoding_cookie(f))
+ else:
+ return f.read()
+
+def read_py_url(url, errors='replace', skip_encoding_cookie=True):
+ """Read a Python file from a URL, using the encoding declared inside the file.
+
+ Parameters
+ ----------
+ url : str
+ The URL from which to fetch the file.
+ errors : str
+ How to handle decoding errors in the file. Options are the same as for
+ bytes.decode(), but here 'replace' is the default.
+ skip_encoding_cookie : bool
+ If True (the default), and the encoding declaration is found in the first
+ two lines, that line will be excluded from the output - compiling a
+ unicode string with an encoding declaration is a SyntaxError in Python 2.
+
+ Returns
+ -------
+ A unicode string containing the contents of the file.
+ """
+ # Deferred import for faster start
+ try:
+ from urllib.request import urlopen # Py 3
+ except ImportError:
+ from urllib import urlopen
+ response = urlopen(url)
+ buffer = io.BytesIO(response.read())
+ return source_to_unicode(buffer, errors, skip_encoding_cookie)
+
+def _list_readline(x):
+ """Given a list, returns a readline() function that returns the next element
+ with each call.
+ """
+ x = iter(x)
+ def readline():
+ return next(x)
+ return readline
+
+# Code for going between .py files and cached .pyc files ----------------------
+
+try: # Python 3.2, see PEP 3147
try:
- encoding, _ = detect_encoding(buffer.readline)
- except SyntaxError:
- encoding = "ascii"
- buffer.seek(0)
- text = TextIOWrapper(buffer, encoding, errors=errors, line_buffering=True)
- text.mode = 'r'
- if skip_encoding_cookie:
- return u"".join(strip_encoding_cookie(text))
- else:
- return text.read()
-
-def strip_encoding_cookie(filelike):
- """Generator to pull lines from a text-mode file, skipping the encoding
- cookie if it is found in the first two lines.
- """
- it = iter(filelike)
- try:
- first = next(it)
- if not cookie_comment_re.match(first):
- yield first
- second = next(it)
- if not cookie_comment_re.match(second):
- yield second
- except StopIteration:
- return
-
- for line in it:
- yield line
-
-def read_py_file(filename, skip_encoding_cookie=True):
- """Read a Python file, using the encoding declared inside the file.
-
- Parameters
- ----------
- filename : str
- The path to the file to read.
- skip_encoding_cookie : bool
- If True (the default), and the encoding declaration is found in the first
- two lines, that line will be excluded from the output - compiling a
- unicode string with an encoding declaration is a SyntaxError in Python 2.
-
- Returns
- -------
- A unicode string containing the contents of the file.
- """
- with open(filename) as f: # the open function defined in this module.
- if skip_encoding_cookie:
- return "".join(strip_encoding_cookie(f))
- else:
- return f.read()
-
-def read_py_url(url, errors='replace', skip_encoding_cookie=True):
- """Read a Python file from a URL, using the encoding declared inside the file.
-
- Parameters
- ----------
- url : str
- The URL from which to fetch the file.
- errors : str
- How to handle decoding errors in the file. Options are the same as for
- bytes.decode(), but here 'replace' is the default.
- skip_encoding_cookie : bool
- If True (the default), and the encoding declaration is found in the first
- two lines, that line will be excluded from the output - compiling a
- unicode string with an encoding declaration is a SyntaxError in Python 2.
-
- Returns
- -------
- A unicode string containing the contents of the file.
- """
- # Deferred import for faster start
- try:
- from urllib.request import urlopen # Py 3
- except ImportError:
- from urllib import urlopen
- response = urlopen(url)
- buffer = io.BytesIO(response.read())
- return source_to_unicode(buffer, errors, skip_encoding_cookie)
-
-def _list_readline(x):
- """Given a list, returns a readline() function that returns the next element
- with each call.
- """
- x = iter(x)
- def readline():
- return next(x)
- return readline
-
-# Code for going between .py files and cached .pyc files ----------------------
-
-try: # Python 3.2, see PEP 3147
- try:
- from importlib.util import source_from_cache, cache_from_source
- except ImportError :
- ## deprecated since 3.4
- from imp import source_from_cache, cache_from_source
-except ImportError:
- # Python <= 3.1: .pyc files go next to .py
- def source_from_cache(path):
- basename, ext = os.path.splitext(path)
- if ext not in ('.pyc', '.pyo'):
- raise ValueError('Not a cached Python file extension', ext)
- # Should we look for .pyw files?
- return basename + '.py'
-
- def cache_from_source(path, debug_override=None):
- if debug_override is None:
- debug_override = __debug__
- basename, ext = os.path.splitext(path)
- return basename + '.pyc' if debug_override else '.pyo'
+ from importlib.util import source_from_cache, cache_from_source
+ except ImportError :
+ ## deprecated since 3.4
+ from imp import source_from_cache, cache_from_source
+except ImportError:
+ # Python <= 3.1: .pyc files go next to .py
+ def source_from_cache(path):
+ basename, ext = os.path.splitext(path)
+ if ext not in ('.pyc', '.pyo'):
+ raise ValueError('Not a cached Python file extension', ext)
+ # Should we look for .pyw files?
+ return basename + '.py'
+
+ def cache_from_source(path, debug_override=None):
+ if debug_override is None:
+ debug_override = __debug__
+ basename, ext = os.path.splitext(path)
+ return basename + '.pyc' if debug_override else '.pyo'
diff --git a/contrib/python/ipython/py2/IPython/utils/path.py b/contrib/python/ipython/py2/IPython/utils/path.py
index 800e0e13ee..fa850812c7 100644
--- a/contrib/python/ipython/py2/IPython/utils/path.py
+++ b/contrib/python/ipython/py2/IPython/utils/path.py
@@ -1,447 +1,447 @@
-# encoding: utf-8
-"""
-Utilities for path handling.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import os
-import sys
-import errno
-import shutil
-import random
-import glob
-from warnings import warn
-from hashlib import md5
-
-from IPython.utils.process import system
-from IPython.utils import py3compat
-from IPython.utils.decorators import undoc
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-fs_encoding = sys.getfilesystemencoding()
-
-def _writable_dir(path):
- """Whether `path` is a directory, to which the user has write access."""
- return os.path.isdir(path) and os.access(path, os.W_OK)
-
-if sys.platform == 'win32':
- def _get_long_path_name(path):
- """Get a long path name (expand ~) on Windows using ctypes.
-
- Examples
- --------
-
- >>> get_long_path_name('c:\\docume~1')
- u'c:\\\\Documents and Settings'
-
- """
- try:
- import ctypes
- except ImportError:
- raise ImportError('you need to have ctypes installed for this to work')
- _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
- _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
- ctypes.c_uint ]
-
- buf = ctypes.create_unicode_buffer(260)
- rv = _GetLongPathName(path, buf, 260)
- if rv == 0 or rv > 260:
- return path
- else:
- return buf.value
-else:
- def _get_long_path_name(path):
- """Dummy no-op."""
- return path
-
-
-
-def get_long_path_name(path):
- """Expand a path into its long form.
-
- On Windows this expands any ~ in the paths. On other platforms, it is
- a null operation.
- """
- return _get_long_path_name(path)
-
-
-def unquote_filename(name, win32=(sys.platform=='win32')):
- """ On Windows, remove leading and trailing quotes from filenames.
+# encoding: utf-8
+"""
+Utilities for path handling.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import os
+import sys
+import errno
+import shutil
+import random
+import glob
+from warnings import warn
+from hashlib import md5
+
+from IPython.utils.process import system
+from IPython.utils import py3compat
+from IPython.utils.decorators import undoc
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+fs_encoding = sys.getfilesystemencoding()
+
+def _writable_dir(path):
+ """Whether `path` is a directory, to which the user has write access."""
+ return os.path.isdir(path) and os.access(path, os.W_OK)
+
+if sys.platform == 'win32':
+ def _get_long_path_name(path):
+ """Get a long path name (expand ~) on Windows using ctypes.
+
+ Examples
+ --------
+
+ >>> get_long_path_name('c:\\docume~1')
+ u'c:\\\\Documents and Settings'
+
+ """
+ try:
+ import ctypes
+ except ImportError:
+ raise ImportError('you need to have ctypes installed for this to work')
+ _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
+ _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
+ ctypes.c_uint ]
+
+ buf = ctypes.create_unicode_buffer(260)
+ rv = _GetLongPathName(path, buf, 260)
+ if rv == 0 or rv > 260:
+ return path
+ else:
+ return buf.value
+else:
+ def _get_long_path_name(path):
+ """Dummy no-op."""
+ return path
+
+
+
+def get_long_path_name(path):
+ """Expand a path into its long form.
+
+ On Windows this expands any ~ in the paths. On other platforms, it is
+ a null operation.
+ """
+ return _get_long_path_name(path)
+
+
+def unquote_filename(name, win32=(sys.platform=='win32')):
+ """ On Windows, remove leading and trailing quotes from filenames.
This function has been deprecated and should not be used any more:
unquoting is now taken care of by :func:`IPython.utils.process.arg_split`.
- """
+ """
warn("'unquote_filename' is deprecated since IPython 5.0 and should not "
"be used anymore", DeprecationWarning, stacklevel=2)
- if win32:
- if name.startswith(("'", '"')) and name.endswith(("'", '"')):
- name = name[1:-1]
- return name
-
-
-def compress_user(path):
- """Reverse of :func:`os.path.expanduser`
+ if win32:
+ if name.startswith(("'", '"')) and name.endswith(("'", '"')):
+ name = name[1:-1]
+ return name
+
+
+def compress_user(path):
+ """Reverse of :func:`os.path.expanduser`
"""
- path = py3compat.unicode_to_str(path, sys.getfilesystemencoding())
- home = os.path.expanduser('~')
- if path.startswith(home):
- path = "~" + path[len(home):]
- return path
-
-def get_py_filename(name, force_win32=None):
- """Return a valid python filename in the current directory.
-
- If the given name is not a file, it adds '.py' and searches again.
- Raises IOError with an informative message if the file isn't found.
- """
-
- name = os.path.expanduser(name)
+ path = py3compat.unicode_to_str(path, sys.getfilesystemencoding())
+ home = os.path.expanduser('~')
+ if path.startswith(home):
+ path = "~" + path[len(home):]
+ return path
+
+def get_py_filename(name, force_win32=None):
+ """Return a valid python filename in the current directory.
+
+ If the given name is not a file, it adds '.py' and searches again.
+ Raises IOError with an informative message if the file isn't found.
+ """
+
+ name = os.path.expanduser(name)
if force_win32 is not None:
warn("The 'force_win32' argument to 'get_py_filename' is deprecated "
"since IPython 5.0 and should not be used anymore",
DeprecationWarning, stacklevel=2)
- if not os.path.isfile(name) and not name.endswith('.py'):
- name += '.py'
- if os.path.isfile(name):
- return name
- else:
- raise IOError('File `%r` not found.' % name)
-
-
-def filefind(filename, path_dirs=None):
- """Find a file by looking through a sequence of paths.
-
- This iterates through a sequence of paths looking for a file and returns
- the full, absolute path of the first occurence of the file. If no set of
- path dirs is given, the filename is tested as is, after running through
- :func:`expandvars` and :func:`expanduser`. Thus a simple call::
-
- filefind('myfile.txt')
-
- will find the file in the current working dir, but::
-
- filefind('~/myfile.txt')
-
- Will find the file in the users home directory. This function does not
- automatically try any paths, such as the cwd or the user's home directory.
-
- Parameters
- ----------
- filename : str
- The filename to look for.
- path_dirs : str, None or sequence of str
- The sequence of paths to look for the file in. If None, the filename
- need to be absolute or be in the cwd. If a string, the string is
- put into a sequence and the searched. If a sequence, walk through
- each element and join with ``filename``, calling :func:`expandvars`
- and :func:`expanduser` before testing for existence.
-
- Returns
- -------
- Raises :exc:`IOError` or returns absolute path to file.
- """
-
- # If paths are quoted, abspath gets confused, strip them...
- filename = filename.strip('"').strip("'")
- # If the input is an absolute path, just check it exists
- if os.path.isabs(filename) and os.path.isfile(filename):
- return filename
-
- if path_dirs is None:
- path_dirs = ("",)
- elif isinstance(path_dirs, py3compat.string_types):
- path_dirs = (path_dirs,)
-
- for path in path_dirs:
- if path == '.': path = py3compat.getcwd()
- testname = expand_path(os.path.join(path, filename))
- if os.path.isfile(testname):
- return os.path.abspath(testname)
-
- raise IOError("File %r does not exist in any of the search paths: %r" %
- (filename, path_dirs) )
-
-
-class HomeDirError(Exception):
- pass
-
-
-def get_home_dir(require_writable=False):
- """Return the 'home' directory, as a unicode string.
-
- Uses os.path.expanduser('~'), and checks for writability.
-
- See stdlib docs for how this is determined.
- $HOME is first priority on *ALL* platforms.
-
- Parameters
- ----------
-
- require_writable : bool [default: False]
- if True:
- guarantees the return value is a writable directory, otherwise
- raises HomeDirError
- if False:
- The path is resolved, but it is not guaranteed to exist or be writable.
- """
-
- homedir = os.path.expanduser('~')
- # Next line will make things work even when /home/ is a symlink to
- # /usr/home as it is on FreeBSD, for example
- homedir = os.path.realpath(homedir)
-
- if not _writable_dir(homedir) and os.name == 'nt':
- # expanduser failed, use the registry to get the 'My Documents' folder.
- try:
- try:
- import winreg as wreg # Py 3
- except ImportError:
- import _winreg as wreg # Py 2
- key = wreg.OpenKey(
- wreg.HKEY_CURRENT_USER,
- "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
- )
- homedir = wreg.QueryValueEx(key,'Personal')[0]
- key.Close()
- except:
- pass
-
- if (not require_writable) or _writable_dir(homedir):
- return py3compat.cast_unicode(homedir, fs_encoding)
- else:
- raise HomeDirError('%s is not a writable dir, '
- 'set $HOME environment variable to override' % homedir)
-
-def get_xdg_dir():
- """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
-
- This is only for non-OS X posix (Linux,Unix,etc.) systems.
- """
-
- env = os.environ
-
- if os.name == 'posix' and sys.platform != 'darwin':
- # Linux, Unix, AIX, etc.
- # use ~/.config if empty OR not set
- xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
- if xdg and _writable_dir(xdg):
- return py3compat.cast_unicode(xdg, fs_encoding)
-
- return None
-
-
-def get_xdg_cache_dir():
- """Return the XDG_CACHE_HOME, if it is defined and exists, else None.
-
- This is only for non-OS X posix (Linux,Unix,etc.) systems.
- """
-
- env = os.environ
-
- if os.name == 'posix' and sys.platform != 'darwin':
- # Linux, Unix, AIX, etc.
- # use ~/.cache if empty OR not set
- xdg = env.get("XDG_CACHE_HOME", None) or os.path.join(get_home_dir(), '.cache')
- if xdg and _writable_dir(xdg):
- return py3compat.cast_unicode(xdg, fs_encoding)
-
- return None
-
-
-@undoc
-def get_ipython_dir():
+ if not os.path.isfile(name) and not name.endswith('.py'):
+ name += '.py'
+ if os.path.isfile(name):
+ return name
+ else:
+ raise IOError('File `%r` not found.' % name)
+
+
+def filefind(filename, path_dirs=None):
+ """Find a file by looking through a sequence of paths.
+
+ This iterates through a sequence of paths looking for a file and returns
+ the full, absolute path of the first occurence of the file. If no set of
+ path dirs is given, the filename is tested as is, after running through
+ :func:`expandvars` and :func:`expanduser`. Thus a simple call::
+
+ filefind('myfile.txt')
+
+ will find the file in the current working dir, but::
+
+ filefind('~/myfile.txt')
+
+ Will find the file in the users home directory. This function does not
+ automatically try any paths, such as the cwd or the user's home directory.
+
+ Parameters
+ ----------
+ filename : str
+ The filename to look for.
+ path_dirs : str, None or sequence of str
+ The sequence of paths to look for the file in. If None, the filename
+ need to be absolute or be in the cwd. If a string, the string is
+ put into a sequence and the searched. If a sequence, walk through
+ each element and join with ``filename``, calling :func:`expandvars`
+ and :func:`expanduser` before testing for existence.
+
+ Returns
+ -------
+ Raises :exc:`IOError` or returns absolute path to file.
+ """
+
+ # If paths are quoted, abspath gets confused, strip them...
+ filename = filename.strip('"').strip("'")
+ # If the input is an absolute path, just check it exists
+ if os.path.isabs(filename) and os.path.isfile(filename):
+ return filename
+
+ if path_dirs is None:
+ path_dirs = ("",)
+ elif isinstance(path_dirs, py3compat.string_types):
+ path_dirs = (path_dirs,)
+
+ for path in path_dirs:
+ if path == '.': path = py3compat.getcwd()
+ testname = expand_path(os.path.join(path, filename))
+ if os.path.isfile(testname):
+ return os.path.abspath(testname)
+
+ raise IOError("File %r does not exist in any of the search paths: %r" %
+ (filename, path_dirs) )
+
+
+class HomeDirError(Exception):
+ pass
+
+
+def get_home_dir(require_writable=False):
+ """Return the 'home' directory, as a unicode string.
+
+ Uses os.path.expanduser('~'), and checks for writability.
+
+ See stdlib docs for how this is determined.
+ $HOME is first priority on *ALL* platforms.
+
+ Parameters
+ ----------
+
+ require_writable : bool [default: False]
+ if True:
+ guarantees the return value is a writable directory, otherwise
+ raises HomeDirError
+ if False:
+ The path is resolved, but it is not guaranteed to exist or be writable.
+ """
+
+ homedir = os.path.expanduser('~')
+ # Next line will make things work even when /home/ is a symlink to
+ # /usr/home as it is on FreeBSD, for example
+ homedir = os.path.realpath(homedir)
+
+ if not _writable_dir(homedir) and os.name == 'nt':
+ # expanduser failed, use the registry to get the 'My Documents' folder.
+ try:
+ try:
+ import winreg as wreg # Py 3
+ except ImportError:
+ import _winreg as wreg # Py 2
+ key = wreg.OpenKey(
+ wreg.HKEY_CURRENT_USER,
+ "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
+ )
+ homedir = wreg.QueryValueEx(key,'Personal')[0]
+ key.Close()
+ except:
+ pass
+
+ if (not require_writable) or _writable_dir(homedir):
+ return py3compat.cast_unicode(homedir, fs_encoding)
+ else:
+ raise HomeDirError('%s is not a writable dir, '
+ 'set $HOME environment variable to override' % homedir)
+
+def get_xdg_dir():
+ """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
+
+ This is only for non-OS X posix (Linux,Unix,etc.) systems.
+ """
+
+ env = os.environ
+
+ if os.name == 'posix' and sys.platform != 'darwin':
+ # Linux, Unix, AIX, etc.
+ # use ~/.config if empty OR not set
+ xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
+ if xdg and _writable_dir(xdg):
+ return py3compat.cast_unicode(xdg, fs_encoding)
+
+ return None
+
+
+def get_xdg_cache_dir():
+ """Return the XDG_CACHE_HOME, if it is defined and exists, else None.
+
+ This is only for non-OS X posix (Linux,Unix,etc.) systems.
+ """
+
+ env = os.environ
+
+ if os.name == 'posix' and sys.platform != 'darwin':
+ # Linux, Unix, AIX, etc.
+ # use ~/.cache if empty OR not set
+ xdg = env.get("XDG_CACHE_HOME", None) or os.path.join(get_home_dir(), '.cache')
+ if xdg and _writable_dir(xdg):
+ return py3compat.cast_unicode(xdg, fs_encoding)
+
+ return None
+
+
+@undoc
+def get_ipython_dir():
warn("get_ipython_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2)
- from IPython.paths import get_ipython_dir
- return get_ipython_dir()
-
-@undoc
-def get_ipython_cache_dir():
+ from IPython.paths import get_ipython_dir
+ return get_ipython_dir()
+
+@undoc
+def get_ipython_cache_dir():
warn("get_ipython_cache_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2)
- from IPython.paths import get_ipython_cache_dir
- return get_ipython_cache_dir()
-
-@undoc
-def get_ipython_package_dir():
+ from IPython.paths import get_ipython_cache_dir
+ return get_ipython_cache_dir()
+
+@undoc
+def get_ipython_package_dir():
warn("get_ipython_package_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2)
- from IPython.paths import get_ipython_package_dir
- return get_ipython_package_dir()
-
-@undoc
-def get_ipython_module_path(module_str):
+ from IPython.paths import get_ipython_package_dir
+ return get_ipython_package_dir()
+
+@undoc
+def get_ipython_module_path(module_str):
warn("get_ipython_module_path has moved to the IPython.paths module since IPython 4.0.", stacklevel=2)
- from IPython.paths import get_ipython_module_path
- return get_ipython_module_path(module_str)
-
-@undoc
-def locate_profile(profile='default'):
+ from IPython.paths import get_ipython_module_path
+ return get_ipython_module_path(module_str)
+
+@undoc
+def locate_profile(profile='default'):
warn("locate_profile has moved to the IPython.paths module since IPython 4.0.", stacklevel=2)
- from IPython.paths import locate_profile
- return locate_profile(profile=profile)
-
-def expand_path(s):
- """Expand $VARS and ~names in a string, like a shell
-
- :Examples:
-
- In [2]: os.environ['FOO']='test'
-
- In [3]: expand_path('variable FOO is $FOO')
- Out[3]: 'variable FOO is test'
- """
- # This is a pretty subtle hack. When expand user is given a UNC path
- # on Windows (\\server\share$\%username%), os.path.expandvars, removes
- # the $ to get (\\server\share\%username%). I think it considered $
- # alone an empty var. But, we need the $ to remains there (it indicates
- # a hidden share).
- if os.name=='nt':
- s = s.replace('$\\', 'IPYTHON_TEMP')
- s = os.path.expandvars(os.path.expanduser(s))
- if os.name=='nt':
- s = s.replace('IPYTHON_TEMP', '$\\')
- return s
-
-
-def unescape_glob(string):
- """Unescape glob pattern in `string`."""
- def unescape(s):
- for pattern in '*[]!?':
- s = s.replace(r'\{0}'.format(pattern), pattern)
- return s
- return '\\'.join(map(unescape, string.split('\\\\')))
-
-
-def shellglob(args):
- """
- Do glob expansion for each element in `args` and return a flattened list.
-
- Unmatched glob pattern will remain as-is in the returned list.
-
- """
- expanded = []
- # Do not unescape backslash in Windows as it is interpreted as
- # path separator:
- unescape = unescape_glob if sys.platform != 'win32' else lambda x: x
- for a in args:
- expanded.extend(glob.glob(a) or [unescape(a)])
- return expanded
-
-
-def target_outdated(target,deps):
- """Determine whether a target is out of date.
-
- target_outdated(target,deps) -> 1/0
-
- deps: list of filenames which MUST exist.
- target: single filename which may or may not exist.
-
- If target doesn't exist or is older than any file listed in deps, return
- true, otherwise return false.
- """
- try:
- target_time = os.path.getmtime(target)
- except os.error:
- return 1
- for dep in deps:
- dep_time = os.path.getmtime(dep)
- if dep_time > target_time:
- #print "For target",target,"Dep failed:",dep # dbg
- #print "times (dep,tar):",dep_time,target_time # dbg
- return 1
- return 0
-
-
-def target_update(target,deps,cmd):
- """Update a target with a given command given a list of dependencies.
-
- target_update(target,deps,cmd) -> runs cmd if target is outdated.
-
- This is just a wrapper around target_outdated() which calls the given
- command if target is outdated."""
-
- if target_outdated(target,deps):
- system(cmd)
-
-@undoc
-def filehash(path):
- """Make an MD5 hash of a file, ignoring any differences in line
- ending characters."""
+ from IPython.paths import locate_profile
+ return locate_profile(profile=profile)
+
+def expand_path(s):
+ """Expand $VARS and ~names in a string, like a shell
+
+ :Examples:
+
+ In [2]: os.environ['FOO']='test'
+
+ In [3]: expand_path('variable FOO is $FOO')
+ Out[3]: 'variable FOO is test'
+ """
+ # This is a pretty subtle hack. When expand user is given a UNC path
+ # on Windows (\\server\share$\%username%), os.path.expandvars, removes
+ # the $ to get (\\server\share\%username%). I think it considered $
+ # alone an empty var. But, we need the $ to remains there (it indicates
+ # a hidden share).
+ if os.name=='nt':
+ s = s.replace('$\\', 'IPYTHON_TEMP')
+ s = os.path.expandvars(os.path.expanduser(s))
+ if os.name=='nt':
+ s = s.replace('IPYTHON_TEMP', '$\\')
+ return s
+
+
+def unescape_glob(string):
+ """Unescape glob pattern in `string`."""
+ def unescape(s):
+ for pattern in '*[]!?':
+ s = s.replace(r'\{0}'.format(pattern), pattern)
+ return s
+ return '\\'.join(map(unescape, string.split('\\\\')))
+
+
+def shellglob(args):
+ """
+ Do glob expansion for each element in `args` and return a flattened list.
+
+ Unmatched glob pattern will remain as-is in the returned list.
+
+ """
+ expanded = []
+ # Do not unescape backslash in Windows as it is interpreted as
+ # path separator:
+ unescape = unescape_glob if sys.platform != 'win32' else lambda x: x
+ for a in args:
+ expanded.extend(glob.glob(a) or [unescape(a)])
+ return expanded
+
+
+def target_outdated(target,deps):
+ """Determine whether a target is out of date.
+
+ target_outdated(target,deps) -> 1/0
+
+ deps: list of filenames which MUST exist.
+ target: single filename which may or may not exist.
+
+ If target doesn't exist or is older than any file listed in deps, return
+ true, otherwise return false.
+ """
+ try:
+ target_time = os.path.getmtime(target)
+ except os.error:
+ return 1
+ for dep in deps:
+ dep_time = os.path.getmtime(dep)
+ if dep_time > target_time:
+ #print "For target",target,"Dep failed:",dep # dbg
+ #print "times (dep,tar):",dep_time,target_time # dbg
+ return 1
+ return 0
+
+
+def target_update(target,deps,cmd):
+ """Update a target with a given command given a list of dependencies.
+
+ target_update(target,deps,cmd) -> runs cmd if target is outdated.
+
+ This is just a wrapper around target_outdated() which calls the given
+ command if target is outdated."""
+
+ if target_outdated(target,deps):
+ system(cmd)
+
+@undoc
+def filehash(path):
+ """Make an MD5 hash of a file, ignoring any differences in line
+ ending characters."""
warn("filehash() is deprecated since IPython 4.0", DeprecationWarning, stacklevel=2)
- with open(path, "rU") as f:
- return md5(py3compat.str_to_bytes(f.read())).hexdigest()
-
-ENOLINK = 1998
-
-def link(src, dst):
- """Hard links ``src`` to ``dst``, returning 0 or errno.
-
- Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
- supported by the operating system.
- """
-
- if not hasattr(os, "link"):
- return ENOLINK
- link_errno = 0
- try:
- os.link(src, dst)
- except OSError as e:
- link_errno = e.errno
- return link_errno
-
-
-def link_or_copy(src, dst):
- """Attempts to hardlink ``src`` to ``dst``, copying if the link fails.
-
- Attempts to maintain the semantics of ``shutil.copy``.
-
- Because ``os.link`` does not overwrite files, a unique temporary file
- will be used if the target already exists, then that file will be moved
- into place.
- """
-
- if os.path.isdir(dst):
- dst = os.path.join(dst, os.path.basename(src))
-
- link_errno = link(src, dst)
- if link_errno == errno.EEXIST:
- if os.stat(src).st_ino == os.stat(dst).st_ino:
- # dst is already a hard link to the correct file, so we don't need
- # to do anything else. If we try to link and rename the file
- # anyway, we get duplicate files - see http://bugs.python.org/issue21876
- return
-
- new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), )
- try:
- link_or_copy(src, new_dst)
- except:
- try:
- os.remove(new_dst)
- except OSError:
- pass
- raise
- os.rename(new_dst, dst)
- elif link_errno != 0:
- # Either link isn't supported, or the filesystem doesn't support
- # linking, or 'src' and 'dst' are on different filesystems.
- shutil.copy(src, dst)
-
-def ensure_dir_exists(path, mode=0o755):
- """ensure that a directory exists
-
- If it doesn't exist, try to create it and protect against a race condition
- if another process is doing the same.
-
- The default permissions are 755, which differ from os.makedirs default of 777.
- """
- if not os.path.exists(path):
- try:
- os.makedirs(path, mode=mode)
- except OSError as e:
- if e.errno != errno.EEXIST:
- raise
- elif not os.path.isdir(path):
- raise IOError("%r exists but is not a directory" % path)
+ with open(path, "rU") as f:
+ return md5(py3compat.str_to_bytes(f.read())).hexdigest()
+
+ENOLINK = 1998
+
+def link(src, dst):
+ """Hard links ``src`` to ``dst``, returning 0 or errno.
+
+ Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
+ supported by the operating system.
+ """
+
+ if not hasattr(os, "link"):
+ return ENOLINK
+ link_errno = 0
+ try:
+ os.link(src, dst)
+ except OSError as e:
+ link_errno = e.errno
+ return link_errno
+
+
+def link_or_copy(src, dst):
+ """Attempts to hardlink ``src`` to ``dst``, copying if the link fails.
+
+ Attempts to maintain the semantics of ``shutil.copy``.
+
+ Because ``os.link`` does not overwrite files, a unique temporary file
+ will be used if the target already exists, then that file will be moved
+ into place.
+ """
+
+ if os.path.isdir(dst):
+ dst = os.path.join(dst, os.path.basename(src))
+
+ link_errno = link(src, dst)
+ if link_errno == errno.EEXIST:
+ if os.stat(src).st_ino == os.stat(dst).st_ino:
+ # dst is already a hard link to the correct file, so we don't need
+ # to do anything else. If we try to link and rename the file
+ # anyway, we get duplicate files - see http://bugs.python.org/issue21876
+ return
+
+ new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), )
+ try:
+ link_or_copy(src, new_dst)
+ except:
+ try:
+ os.remove(new_dst)
+ except OSError:
+ pass
+ raise
+ os.rename(new_dst, dst)
+ elif link_errno != 0:
+ # Either link isn't supported, or the filesystem doesn't support
+ # linking, or 'src' and 'dst' are on different filesystems.
+ shutil.copy(src, dst)
+
+def ensure_dir_exists(path, mode=0o755):
+ """ensure that a directory exists
+
+ If it doesn't exist, try to create it and protect against a race condition
+ if another process is doing the same.
+
+ The default permissions are 755, which differ from os.makedirs default of 777.
+ """
+ if not os.path.exists(path):
+ try:
+ os.makedirs(path, mode=mode)
+ except OSError as e:
+ if e.errno != errno.EEXIST:
+ raise
+ elif not os.path.isdir(path):
+ raise IOError("%r exists but is not a directory" % path)
diff --git a/contrib/python/ipython/py2/IPython/utils/pickleutil.py b/contrib/python/ipython/py2/IPython/utils/pickleutil.py
index 9111ad73c0..665ff09f2d 100644
--- a/contrib/python/ipython/py2/IPython/utils/pickleutil.py
+++ b/contrib/python/ipython/py2/IPython/utils/pickleutil.py
@@ -1,5 +1,5 @@
-from warnings import warn
-
-warn("IPython.utils.pickleutil has moved to ipykernel.pickleutil")
-
-from ipykernel.pickleutil import *
+from warnings import warn
+
+warn("IPython.utils.pickleutil has moved to ipykernel.pickleutil")
+
+from ipykernel.pickleutil import *
diff --git a/contrib/python/ipython/py2/IPython/utils/process.py b/contrib/python/ipython/py2/IPython/utils/process.py
index ca85a03b5c..a274f43f3a 100644
--- a/contrib/python/ipython/py2/IPython/utils/process.py
+++ b/contrib/python/ipython/py2/IPython/utils/process.py
@@ -1,106 +1,106 @@
-# encoding: utf-8
-"""
-Utilities for working with external processes.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
-import os
-import sys
-
-if sys.platform == 'win32':
- from ._process_win32 import system, getoutput, arg_split, check_pid
-elif sys.platform == 'cli':
- from ._process_cli import system, getoutput, arg_split, check_pid
-else:
- from ._process_posix import system, getoutput, arg_split, check_pid
-
-from ._process_common import getoutputerror, get_output_error_code, process_handler
-from . import py3compat
-
-
-class FindCmdError(Exception):
- pass
-
-
-def find_cmd(cmd):
- """Find absolute path to executable cmd in a cross platform manner.
-
- This function tries to determine the full path to a command line program
- using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
- time it will use the version that is first on the users `PATH`.
-
- Warning, don't use this to find IPython command line programs as there
- is a risk you will find the wrong one. Instead find those using the
- following code and looking for the application itself::
-
- from IPython.utils.path import get_ipython_module_path
- from IPython.utils.process import pycmd2argv
- argv = pycmd2argv(get_ipython_module_path('IPython.terminal.ipapp'))
-
- Parameters
- ----------
- cmd : str
- The command line program to look for.
- """
- path = py3compat.which(cmd)
- if path is None:
- raise FindCmdError('command could not be found: %s' % cmd)
- return path
-
-
-def is_cmd_found(cmd):
- """Check whether executable `cmd` exists or not and return a bool."""
- try:
- find_cmd(cmd)
- return True
- except FindCmdError:
- return False
-
-
-def pycmd2argv(cmd):
- r"""Take the path of a python command and return a list (argv-style).
-
- This only works on Python based command line programs and will find the
- location of the ``python`` executable using ``sys.executable`` to make
- sure the right version is used.
-
- For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe,
- .com or .bat, and [, cmd] otherwise.
-
- Parameters
- ----------
- cmd : string
- The path of the command.
-
- Returns
- -------
- argv-style list.
- """
- ext = os.path.splitext(cmd)[1]
- if ext in ['.exe', '.com', '.bat']:
- return [cmd]
- else:
- return [sys.executable, cmd]
-
-
-def abbrev_cwd():
- """ Return abbreviated version of cwd, e.g. d:mydir """
- cwd = py3compat.getcwd().replace('\\','/')
- drivepart = ''
- tail = cwd
- if sys.platform == 'win32':
- if len(cwd) < 4:
- return cwd
- drivepart,tail = os.path.splitdrive(cwd)
-
-
- parts = tail.split('/')
- if len(parts) > 2:
- tail = '/'.join(parts[-2:])
-
- return (drivepart + (
- cwd == '/' and '/' or tail))
+# encoding: utf-8
+"""
+Utilities for working with external processes.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
+import os
+import sys
+
+if sys.platform == 'win32':
+ from ._process_win32 import system, getoutput, arg_split, check_pid
+elif sys.platform == 'cli':
+ from ._process_cli import system, getoutput, arg_split, check_pid
+else:
+ from ._process_posix import system, getoutput, arg_split, check_pid
+
+from ._process_common import getoutputerror, get_output_error_code, process_handler
+from . import py3compat
+
+
+class FindCmdError(Exception):
+ pass
+
+
+def find_cmd(cmd):
+ """Find absolute path to executable cmd in a cross platform manner.
+
+ This function tries to determine the full path to a command line program
+ using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
+ time it will use the version that is first on the users `PATH`.
+
+ Warning, don't use this to find IPython command line programs as there
+ is a risk you will find the wrong one. Instead find those using the
+ following code and looking for the application itself::
+
+ from IPython.utils.path import get_ipython_module_path
+ from IPython.utils.process import pycmd2argv
+ argv = pycmd2argv(get_ipython_module_path('IPython.terminal.ipapp'))
+
+ Parameters
+ ----------
+ cmd : str
+ The command line program to look for.
+ """
+ path = py3compat.which(cmd)
+ if path is None:
+ raise FindCmdError('command could not be found: %s' % cmd)
+ return path
+
+
+def is_cmd_found(cmd):
+ """Check whether executable `cmd` exists or not and return a bool."""
+ try:
+ find_cmd(cmd)
+ return True
+ except FindCmdError:
+ return False
+
+
+def pycmd2argv(cmd):
+ r"""Take the path of a python command and return a list (argv-style).
+
+ This only works on Python based command line programs and will find the
+ location of the ``python`` executable using ``sys.executable`` to make
+ sure the right version is used.
+
+ For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe,
+ .com or .bat, and [, cmd] otherwise.
+
+ Parameters
+ ----------
+ cmd : string
+ The path of the command.
+
+ Returns
+ -------
+ argv-style list.
+ """
+ ext = os.path.splitext(cmd)[1]
+ if ext in ['.exe', '.com', '.bat']:
+ return [cmd]
+ else:
+ return [sys.executable, cmd]
+
+
+def abbrev_cwd():
+ """ Return abbreviated version of cwd, e.g. d:mydir """
+ cwd = py3compat.getcwd().replace('\\','/')
+ drivepart = ''
+ tail = cwd
+ if sys.platform == 'win32':
+ if len(cwd) < 4:
+ return cwd
+ drivepart,tail = os.path.splitdrive(cwd)
+
+
+ parts = tail.split('/')
+ if len(parts) > 2:
+ tail = '/'.join(parts[-2:])
+
+ return (drivepart + (
+ cwd == '/' and '/' or tail))
diff --git a/contrib/python/ipython/py2/IPython/utils/py3compat.py b/contrib/python/ipython/py2/IPython/utils/py3compat.py
index adaac362a7..88602e5342 100644
--- a/contrib/python/ipython/py2/IPython/utils/py3compat.py
+++ b/contrib/python/ipython/py2/IPython/utils/py3compat.py
@@ -1,336 +1,336 @@
-# coding: utf-8
-"""Compatibility tricks for Python 3. Mainly to do with unicode."""
-import functools
-import os
-import sys
-import re
-import shutil
-import types
+# coding: utf-8
+"""Compatibility tricks for Python 3. Mainly to do with unicode."""
+import functools
+import os
+import sys
+import re
+import shutil
+import types
import platform
-
-from .encoding import DEFAULT_ENCODING
-
-def no_code(x, encoding=None):
- return x
-
-def decode(s, encoding=None):
- encoding = encoding or DEFAULT_ENCODING
- return s.decode(encoding, "replace")
-
-def encode(u, encoding=None):
- encoding = encoding or DEFAULT_ENCODING
- return u.encode(encoding, "replace")
-
-
-def cast_unicode(s, encoding=None):
- if isinstance(s, bytes):
- return decode(s, encoding)
- return s
-
-def cast_bytes(s, encoding=None):
- if not isinstance(s, bytes):
- return encode(s, encoding)
- return s
-
-def buffer_to_bytes(buf):
- """Cast a buffer object to bytes"""
- if not isinstance(buf, bytes):
- buf = bytes(buf)
- return buf
-
-def _modify_str_or_docstring(str_change_func):
- @functools.wraps(str_change_func)
- def wrapper(func_or_str):
- if isinstance(func_or_str, string_types):
- func = None
- doc = func_or_str
- else:
- func = func_or_str
- doc = func.__doc__
-
- # PYTHONOPTIMIZE=2 strips docstrings, so they can disappear unexpectedly
- if doc is not None:
- doc = str_change_func(doc)
-
- if func:
- func.__doc__ = doc
- return func
- return doc
- return wrapper
-
-def safe_unicode(e):
- """unicode(e) with various fallbacks. Used for exceptions, which may not be
- safe to call unicode() on.
- """
- try:
- return unicode_type(e)
- except UnicodeError:
- pass
-
- try:
- return str_to_unicode(str(e))
- except UnicodeError:
- pass
-
- try:
- return str_to_unicode(repr(e))
- except UnicodeError:
- pass
-
- return u'Unrecoverably corrupt evalue'
-
-# shutil.which from Python 3.4
-def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None):
- """Given a command, mode, and a PATH string, return the path which
- conforms to the given mode on the PATH, or None if there is no such
- file.
-
- `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
- of os.environ.get("PATH"), or can be overridden with a custom search
- path.
-
- This is a backport of shutil.which from Python 3.4
- """
- # Check that a given file can be accessed with the correct mode.
- # Additionally check that `file` is not a directory, as on Windows
- # directories pass the os.access check.
- def _access_check(fn, mode):
- return (os.path.exists(fn) and os.access(fn, mode)
- and not os.path.isdir(fn))
-
- # If we're given a path with a directory part, look it up directly rather
- # than referring to PATH directories. This includes checking relative to the
- # current directory, e.g. ./script
- if os.path.dirname(cmd):
- if _access_check(cmd, mode):
- return cmd
- return None
-
- if path is None:
- path = os.environ.get("PATH", os.defpath)
- if not path:
- return None
- path = path.split(os.pathsep)
-
- if sys.platform == "win32":
- # The current directory takes precedence on Windows.
- if not os.curdir in path:
- path.insert(0, os.curdir)
-
- # PATHEXT is necessary to check on Windows.
- pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
- # See if the given file matches any of the expected path extensions.
- # This will allow us to short circuit when given "python.exe".
- # If it does match, only test that one, otherwise we have to try
- # others.
- if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
- files = [cmd]
- else:
- files = [cmd + ext for ext in pathext]
- else:
- # On other platforms you don't have things like PATHEXT to tell you
- # what file suffixes are executable, so just pass on cmd as-is.
- files = [cmd]
-
- seen = set()
- for dir in path:
- normdir = os.path.normcase(dir)
- if not normdir in seen:
- seen.add(normdir)
- for thefile in files:
- name = os.path.join(dir, thefile)
- if _access_check(name, mode):
- return name
- return None
-
-if sys.version_info[0] >= 3:
- PY3 = True
-
- # keep reference to builtin_mod because the kernel overrides that value
- # to forward requests to a frontend.
- def input(prompt=''):
- return builtin_mod.input(prompt)
-
- builtin_mod_name = "builtins"
- import builtins as builtin_mod
-
- str_to_unicode = no_code
- unicode_to_str = no_code
- str_to_bytes = encode
- bytes_to_str = decode
- cast_bytes_py2 = no_code
- cast_unicode_py2 = no_code
- buffer_to_bytes_py2 = no_code
-
- string_types = (str,)
- unicode_type = str
-
- which = shutil.which
-
- def isidentifier(s, dotted=False):
- if dotted:
- return all(isidentifier(a) for a in s.split("."))
- return s.isidentifier()
-
- xrange = range
- def iteritems(d): return iter(d.items())
- def itervalues(d): return iter(d.values())
- getcwd = os.getcwd
-
- MethodType = types.MethodType
-
- def execfile(fname, glob, loc=None, compiler=None):
- loc = loc if (loc is not None) else glob
- with open(fname, 'rb') as f:
- compiler = compiler or compile
- exec(compiler(f.read(), fname, 'exec'), glob, loc)
-
- # Refactor print statements in doctests.
- _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
- def _print_statement_sub(match):
- expr = match.groups('expr')
- return "print(%s)" % expr
-
- @_modify_str_or_docstring
- def doctest_refactor_print(doc):
- """Refactor 'print x' statements in a doctest to print(x) style. 2to3
- unfortunately doesn't pick up on our doctests.
-
- Can accept a string or a function, so it can be used as a decorator."""
- return _print_statement_re.sub(_print_statement_sub, doc)
-
- # Abstract u'abc' syntax:
- @_modify_str_or_docstring
- def u_format(s):
- """"{u}'abc'" --> "'abc'" (Python 3)
-
- Accepts a string or a function, so it can be used as a decorator."""
- return s.format(u='')
-
- def get_closure(f):
- """Get a function's closure attribute"""
- return f.__closure__
-
-else:
- PY3 = False
-
- # keep reference to builtin_mod because the kernel overrides that value
- # to forward requests to a frontend.
- def input(prompt=''):
- return builtin_mod.raw_input(prompt)
-
- builtin_mod_name = "__builtin__"
- import __builtin__ as builtin_mod
-
- str_to_unicode = decode
- unicode_to_str = encode
- str_to_bytes = no_code
- bytes_to_str = no_code
- cast_bytes_py2 = cast_bytes
- cast_unicode_py2 = cast_unicode
- buffer_to_bytes_py2 = buffer_to_bytes
-
- string_types = (str, unicode)
- unicode_type = unicode
-
- import re
- _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
- def isidentifier(s, dotted=False):
- if dotted:
- return all(isidentifier(a) for a in s.split("."))
- return bool(_name_re.match(s))
-
- xrange = xrange
- def iteritems(d): return d.iteritems()
- def itervalues(d): return d.itervalues()
- getcwd = os.getcwdu
-
- def MethodType(func, instance):
- return types.MethodType(func, instance, type(instance))
-
- def doctest_refactor_print(func_or_str):
- return func_or_str
-
- def get_closure(f):
- """Get a function's closure attribute"""
- return f.func_closure
-
- which = _shutil_which
-
- # Abstract u'abc' syntax:
- @_modify_str_or_docstring
- def u_format(s):
- """"{u}'abc'" --> "u'abc'" (Python 2)
-
- Accepts a string or a function, so it can be used as a decorator."""
- return s.format(u='u')
-
- if sys.platform == 'win32':
- def execfile(fname, glob=None, loc=None, compiler=None):
- loc = loc if (loc is not None) else glob
- scripttext = builtin_mod.open(fname).read()+ '\n'
- # compile converts unicode filename to str assuming
- # ascii. Let's do the conversion before calling compile
- if isinstance(fname, unicode):
- filename = unicode_to_str(fname)
- else:
- filename = fname
- compiler = compiler or compile
- exec(compiler(scripttext, filename, 'exec'), glob, loc)
-
- else:
- def execfile(fname, glob=None, loc=None, compiler=None):
- if isinstance(fname, unicode):
- filename = fname.encode(sys.getfilesystemencoding())
- else:
- filename = fname
- where = [ns for ns in [glob, loc] if ns is not None]
- if compiler is None:
- builtin_mod.execfile(filename, *where)
- else:
- scripttext = builtin_mod.open(fname).read().rstrip() + '\n'
- exec(compiler(scripttext, filename, 'exec'), glob, loc)
-
-
-PY2 = not PY3
+
+from .encoding import DEFAULT_ENCODING
+
+def no_code(x, encoding=None):
+ return x
+
+def decode(s, encoding=None):
+ encoding = encoding or DEFAULT_ENCODING
+ return s.decode(encoding, "replace")
+
+def encode(u, encoding=None):
+ encoding = encoding or DEFAULT_ENCODING
+ return u.encode(encoding, "replace")
+
+
+def cast_unicode(s, encoding=None):
+ if isinstance(s, bytes):
+ return decode(s, encoding)
+ return s
+
+def cast_bytes(s, encoding=None):
+ if not isinstance(s, bytes):
+ return encode(s, encoding)
+ return s
+
+def buffer_to_bytes(buf):
+ """Cast a buffer object to bytes"""
+ if not isinstance(buf, bytes):
+ buf = bytes(buf)
+ return buf
+
+def _modify_str_or_docstring(str_change_func):
+ @functools.wraps(str_change_func)
+ def wrapper(func_or_str):
+ if isinstance(func_or_str, string_types):
+ func = None
+ doc = func_or_str
+ else:
+ func = func_or_str
+ doc = func.__doc__
+
+ # PYTHONOPTIMIZE=2 strips docstrings, so they can disappear unexpectedly
+ if doc is not None:
+ doc = str_change_func(doc)
+
+ if func:
+ func.__doc__ = doc
+ return func
+ return doc
+ return wrapper
+
+def safe_unicode(e):
+ """unicode(e) with various fallbacks. Used for exceptions, which may not be
+ safe to call unicode() on.
+ """
+ try:
+ return unicode_type(e)
+ except UnicodeError:
+ pass
+
+ try:
+ return str_to_unicode(str(e))
+ except UnicodeError:
+ pass
+
+ try:
+ return str_to_unicode(repr(e))
+ except UnicodeError:
+ pass
+
+ return u'Unrecoverably corrupt evalue'
+
+# shutil.which from Python 3.4
+def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None):
+ """Given a command, mode, and a PATH string, return the path which
+ conforms to the given mode on the PATH, or None if there is no such
+ file.
+
+ `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
+ of os.environ.get("PATH"), or can be overridden with a custom search
+ path.
+
+ This is a backport of shutil.which from Python 3.4
+ """
+ # Check that a given file can be accessed with the correct mode.
+ # Additionally check that `file` is not a directory, as on Windows
+ # directories pass the os.access check.
+ def _access_check(fn, mode):
+ return (os.path.exists(fn) and os.access(fn, mode)
+ and not os.path.isdir(fn))
+
+ # If we're given a path with a directory part, look it up directly rather
+ # than referring to PATH directories. This includes checking relative to the
+ # current directory, e.g. ./script
+ if os.path.dirname(cmd):
+ if _access_check(cmd, mode):
+ return cmd
+ return None
+
+ if path is None:
+ path = os.environ.get("PATH", os.defpath)
+ if not path:
+ return None
+ path = path.split(os.pathsep)
+
+ if sys.platform == "win32":
+ # The current directory takes precedence on Windows.
+ if not os.curdir in path:
+ path.insert(0, os.curdir)
+
+ # PATHEXT is necessary to check on Windows.
+ pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
+ # See if the given file matches any of the expected path extensions.
+ # This will allow us to short circuit when given "python.exe".
+ # If it does match, only test that one, otherwise we have to try
+ # others.
+ if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
+ files = [cmd]
+ else:
+ files = [cmd + ext for ext in pathext]
+ else:
+ # On other platforms you don't have things like PATHEXT to tell you
+ # what file suffixes are executable, so just pass on cmd as-is.
+ files = [cmd]
+
+ seen = set()
+ for dir in path:
+ normdir = os.path.normcase(dir)
+ if not normdir in seen:
+ seen.add(normdir)
+ for thefile in files:
+ name = os.path.join(dir, thefile)
+ if _access_check(name, mode):
+ return name
+ return None
+
+if sys.version_info[0] >= 3:
+ PY3 = True
+
+ # keep reference to builtin_mod because the kernel overrides that value
+ # to forward requests to a frontend.
+ def input(prompt=''):
+ return builtin_mod.input(prompt)
+
+ builtin_mod_name = "builtins"
+ import builtins as builtin_mod
+
+ str_to_unicode = no_code
+ unicode_to_str = no_code
+ str_to_bytes = encode
+ bytes_to_str = decode
+ cast_bytes_py2 = no_code
+ cast_unicode_py2 = no_code
+ buffer_to_bytes_py2 = no_code
+
+ string_types = (str,)
+ unicode_type = str
+
+ which = shutil.which
+
+ def isidentifier(s, dotted=False):
+ if dotted:
+ return all(isidentifier(a) for a in s.split("."))
+ return s.isidentifier()
+
+ xrange = range
+ def iteritems(d): return iter(d.items())
+ def itervalues(d): return iter(d.values())
+ getcwd = os.getcwd
+
+ MethodType = types.MethodType
+
+ def execfile(fname, glob, loc=None, compiler=None):
+ loc = loc if (loc is not None) else glob
+ with open(fname, 'rb') as f:
+ compiler = compiler or compile
+ exec(compiler(f.read(), fname, 'exec'), glob, loc)
+
+ # Refactor print statements in doctests.
+ _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
+ def _print_statement_sub(match):
+ expr = match.groups('expr')
+ return "print(%s)" % expr
+
+ @_modify_str_or_docstring
+ def doctest_refactor_print(doc):
+ """Refactor 'print x' statements in a doctest to print(x) style. 2to3
+ unfortunately doesn't pick up on our doctests.
+
+ Can accept a string or a function, so it can be used as a decorator."""
+ return _print_statement_re.sub(_print_statement_sub, doc)
+
+ # Abstract u'abc' syntax:
+ @_modify_str_or_docstring
+ def u_format(s):
+ """"{u}'abc'" --> "'abc'" (Python 3)
+
+ Accepts a string or a function, so it can be used as a decorator."""
+ return s.format(u='')
+
+ def get_closure(f):
+ """Get a function's closure attribute"""
+ return f.__closure__
+
+else:
+ PY3 = False
+
+ # keep reference to builtin_mod because the kernel overrides that value
+ # to forward requests to a frontend.
+ def input(prompt=''):
+ return builtin_mod.raw_input(prompt)
+
+ builtin_mod_name = "__builtin__"
+ import __builtin__ as builtin_mod
+
+ str_to_unicode = decode
+ unicode_to_str = encode
+ str_to_bytes = no_code
+ bytes_to_str = no_code
+ cast_bytes_py2 = cast_bytes
+ cast_unicode_py2 = cast_unicode
+ buffer_to_bytes_py2 = buffer_to_bytes
+
+ string_types = (str, unicode)
+ unicode_type = unicode
+
+ import re
+ _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
+ def isidentifier(s, dotted=False):
+ if dotted:
+ return all(isidentifier(a) for a in s.split("."))
+ return bool(_name_re.match(s))
+
+ xrange = xrange
+ def iteritems(d): return d.iteritems()
+ def itervalues(d): return d.itervalues()
+ getcwd = os.getcwdu
+
+ def MethodType(func, instance):
+ return types.MethodType(func, instance, type(instance))
+
+ def doctest_refactor_print(func_or_str):
+ return func_or_str
+
+ def get_closure(f):
+ """Get a function's closure attribute"""
+ return f.func_closure
+
+ which = _shutil_which
+
+ # Abstract u'abc' syntax:
+ @_modify_str_or_docstring
+ def u_format(s):
+ """"{u}'abc'" --> "u'abc'" (Python 2)
+
+ Accepts a string or a function, so it can be used as a decorator."""
+ return s.format(u='u')
+
+ if sys.platform == 'win32':
+ def execfile(fname, glob=None, loc=None, compiler=None):
+ loc = loc if (loc is not None) else glob
+ scripttext = builtin_mod.open(fname).read()+ '\n'
+ # compile converts unicode filename to str assuming
+ # ascii. Let's do the conversion before calling compile
+ if isinstance(fname, unicode):
+ filename = unicode_to_str(fname)
+ else:
+ filename = fname
+ compiler = compiler or compile
+ exec(compiler(scripttext, filename, 'exec'), glob, loc)
+
+ else:
+ def execfile(fname, glob=None, loc=None, compiler=None):
+ if isinstance(fname, unicode):
+ filename = fname.encode(sys.getfilesystemencoding())
+ else:
+ filename = fname
+ where = [ns for ns in [glob, loc] if ns is not None]
+ if compiler is None:
+ builtin_mod.execfile(filename, *where)
+ else:
+ scripttext = builtin_mod.open(fname).read().rstrip() + '\n'
+ exec(compiler(scripttext, filename, 'exec'), glob, loc)
+
+
+PY2 = not PY3
PYPY = platform.python_implementation() == "PyPy"
-
-
-def annotate(**kwargs):
- """Python 3 compatible function annotation for Python 2."""
- if not kwargs:
- raise ValueError('annotations must be provided as keyword arguments')
- def dec(f):
- if hasattr(f, '__annotations__'):
- for k, v in kwargs.items():
- f.__annotations__[k] = v
- else:
- f.__annotations__ = kwargs
- return f
- return dec
-
-
-# Parts below taken from six:
-# Copyright (c) 2010-2013 Benjamin Peterson
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in all
-# copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-# SOFTWARE.
-
-def with_metaclass(meta, *bases):
- """Create a base class with a metaclass."""
- return meta("_NewBase", bases, {})
+
+
+def annotate(**kwargs):
+ """Python 3 compatible function annotation for Python 2."""
+ if not kwargs:
+ raise ValueError('annotations must be provided as keyword arguments')
+ def dec(f):
+ if hasattr(f, '__annotations__'):
+ for k, v in kwargs.items():
+ f.__annotations__[k] = v
+ else:
+ f.__annotations__ = kwargs
+ return f
+ return dec
+
+
+# Parts below taken from six:
+# Copyright (c) 2010-2013 Benjamin Peterson
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+def with_metaclass(meta, *bases):
+ """Create a base class with a metaclass."""
+ return meta("_NewBase", bases, {})
diff --git a/contrib/python/ipython/py2/IPython/utils/rlineimpl.py b/contrib/python/ipython/py2/IPython/utils/rlineimpl.py
index f8c4e84334..e1cf03942c 100644
--- a/contrib/python/ipython/py2/IPython/utils/rlineimpl.py
+++ b/contrib/python/ipython/py2/IPython/utils/rlineimpl.py
@@ -1,74 +1,74 @@
-# -*- coding: utf-8 -*-
-""" Imports and provides the 'correct' version of readline for the platform.
-
-Readline is used throughout IPython as::
-
- import IPython.utils.rlineimpl as readline
-
-In addition to normal readline stuff, this module provides have_readline
-boolean and _outputfile variable used in IPython.utils.
-"""
-
-import sys
-import warnings
-
-_rlmod_names = ['gnureadline', 'readline']
-
-have_readline = False
-for _rlmod_name in _rlmod_names:
- try:
- # import readline as _rl
- _rl = __import__(_rlmod_name)
- # from readline import *
- globals().update({k:v for k,v in _rl.__dict__.items() if not k.startswith('_')})
- except ImportError:
- pass
- else:
- have_readline = True
- break
-
-if have_readline and (sys.platform == 'win32' or sys.platform == 'cli'):
- try:
- _outputfile=_rl.GetOutputFile()
- except AttributeError:
- warnings.warn("Failed GetOutputFile")
- have_readline = False
-
-# Test to see if libedit is being used instead of GNU readline.
-# Thanks to Boyd Waters for the original patch.
-uses_libedit = False
-
-if have_readline:
- # Official Python docs state that 'libedit' is in the docstring for libedit readline:
- uses_libedit = _rl.__doc__ and 'libedit' in _rl.__doc__
- # Note that many non-System Pythons also do not use proper readline,
- # but do not report libedit at all, nor are they linked dynamically against libedit.
- # known culprits of this include: EPD, Fink
- # There is not much we can do to detect this, until we find a specific failure
- # case, rather than relying on the readline module to self-identify as broken.
-
-if uses_libedit and sys.platform == 'darwin':
- _rl.parse_and_bind("bind ^I rl_complete")
- warnings.warn('\n'.join(['', "*"*78,
- "libedit detected - readline will not be well behaved, including but not limited to:",
- " * crashes on tab completion",
- " * incorrect history navigation",
- " * corrupting long-lines",
- " * failure to wrap or indent lines properly",
- "It is highly recommended that you install gnureadline, which is installable with:",
- " pip install gnureadline",
- "*"*78]),
- RuntimeWarning)
-
-# the clear_history() function was only introduced in Python 2.4 and is
-# actually optional in the readline API, so we must explicitly check for its
-# existence. Some known platforms actually don't have it. This thread:
-# http://mail.python.org/pipermail/python-dev/2003-August/037845.html
-# has the original discussion.
-
-if have_readline:
- try:
- _rl.clear_history
- except AttributeError:
- def clear_history(): pass
- _rl.clear_history = clear_history
+# -*- coding: utf-8 -*-
+""" Imports and provides the 'correct' version of readline for the platform.
+
+Readline is used throughout IPython as::
+
+ import IPython.utils.rlineimpl as readline
+
+In addition to normal readline stuff, this module provides have_readline
+boolean and _outputfile variable used in IPython.utils.
+"""
+
+import sys
+import warnings
+
+_rlmod_names = ['gnureadline', 'readline']
+
+have_readline = False
+for _rlmod_name in _rlmod_names:
+ try:
+ # import readline as _rl
+ _rl = __import__(_rlmod_name)
+ # from readline import *
+ globals().update({k:v for k,v in _rl.__dict__.items() if not k.startswith('_')})
+ except ImportError:
+ pass
+ else:
+ have_readline = True
+ break
+
+if have_readline and (sys.platform == 'win32' or sys.platform == 'cli'):
+ try:
+ _outputfile=_rl.GetOutputFile()
+ except AttributeError:
+ warnings.warn("Failed GetOutputFile")
+ have_readline = False
+
+# Test to see if libedit is being used instead of GNU readline.
+# Thanks to Boyd Waters for the original patch.
+uses_libedit = False
+
+if have_readline:
+ # Official Python docs state that 'libedit' is in the docstring for libedit readline:
+ uses_libedit = _rl.__doc__ and 'libedit' in _rl.__doc__
+ # Note that many non-System Pythons also do not use proper readline,
+ # but do not report libedit at all, nor are they linked dynamically against libedit.
+ # known culprits of this include: EPD, Fink
+ # There is not much we can do to detect this, until we find a specific failure
+ # case, rather than relying on the readline module to self-identify as broken.
+
+if uses_libedit and sys.platform == 'darwin':
+ _rl.parse_and_bind("bind ^I rl_complete")
+ warnings.warn('\n'.join(['', "*"*78,
+ "libedit detected - readline will not be well behaved, including but not limited to:",
+ " * crashes on tab completion",
+ " * incorrect history navigation",
+ " * corrupting long-lines",
+ " * failure to wrap or indent lines properly",
+ "It is highly recommended that you install gnureadline, which is installable with:",
+ " pip install gnureadline",
+ "*"*78]),
+ RuntimeWarning)
+
+# the clear_history() function was only introduced in Python 2.4 and is
+# actually optional in the readline API, so we must explicitly check for its
+# existence. Some known platforms actually don't have it. This thread:
+# http://mail.python.org/pipermail/python-dev/2003-August/037845.html
+# has the original discussion.
+
+if have_readline:
+ try:
+ _rl.clear_history
+ except AttributeError:
+ def clear_history(): pass
+ _rl.clear_history = clear_history
diff --git a/contrib/python/ipython/py2/IPython/utils/sentinel.py b/contrib/python/ipython/py2/IPython/utils/sentinel.py
index 7af2558c1a..dc57a2591c 100644
--- a/contrib/python/ipython/py2/IPython/utils/sentinel.py
+++ b/contrib/python/ipython/py2/IPython/utils/sentinel.py
@@ -1,17 +1,17 @@
-"""Sentinel class for constants with useful reprs"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-class Sentinel(object):
-
- def __init__(self, name, module, docstring=None):
- self.name = name
- self.module = module
- if docstring:
- self.__doc__ = docstring
-
-
- def __repr__(self):
- return str(self.module)+'.'+self.name
-
+"""Sentinel class for constants with useful reprs"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+class Sentinel(object):
+
+ def __init__(self, name, module, docstring=None):
+ self.name = name
+ self.module = module
+ if docstring:
+ self.__doc__ = docstring
+
+
+ def __repr__(self):
+ return str(self.module)+'.'+self.name
+
diff --git a/contrib/python/ipython/py2/IPython/utils/shimmodule.py b/contrib/python/ipython/py2/IPython/utils/shimmodule.py
index c2cf6c6de7..8b74f5011a 100644
--- a/contrib/python/ipython/py2/IPython/utils/shimmodule.py
+++ b/contrib/python/ipython/py2/IPython/utils/shimmodule.py
@@ -1,92 +1,92 @@
-"""A shim module for deprecated imports
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import sys
-import types
-
-from .importstring import import_item
-
-class ShimWarning(Warning):
- """A warning to show when a module has moved, and a shim is in its place."""
-
-class ShimImporter(object):
- """Import hook for a shim.
-
- This ensures that submodule imports return the real target module,
- not a clone that will confuse `is` and `isinstance` checks.
- """
- def __init__(self, src, mirror):
- self.src = src
- self.mirror = mirror
-
- def _mirror_name(self, fullname):
- """get the name of the mirrored module"""
-
- return self.mirror + fullname[len(self.src):]
-
- def find_module(self, fullname, path=None):
- """Return self if we should be used to import the module."""
- if fullname.startswith(self.src + '.'):
- mirror_name = self._mirror_name(fullname)
- try:
- mod = import_item(mirror_name)
- except ImportError:
- return
- else:
- if not isinstance(mod, types.ModuleType):
- # not a module
- return None
- return self
-
- def load_module(self, fullname):
- """Import the mirrored module, and insert it into sys.modules"""
- mirror_name = self._mirror_name(fullname)
- mod = import_item(mirror_name)
- sys.modules[fullname] = mod
- return mod
-
-
-class ShimModule(types.ModuleType):
-
- def __init__(self, *args, **kwargs):
- self._mirror = kwargs.pop("mirror")
- src = kwargs.pop("src", None)
- if src:
- kwargs['name'] = src.rsplit('.', 1)[-1]
- super(ShimModule, self).__init__(*args, **kwargs)
- # add import hook for descendent modules
- if src:
- sys.meta_path.append(
- ShimImporter(src=src, mirror=self._mirror)
- )
-
- @property
- def __path__(self):
- return []
-
- @property
- def __spec__(self):
- """Don't produce __spec__ until requested"""
- return __import__(self._mirror).__spec__
-
- def __dir__(self):
- return dir(__import__(self._mirror))
-
- @property
- def __all__(self):
- """Ensure __all__ is always defined"""
- mod = __import__(self._mirror)
- try:
- return mod.__all__
- except AttributeError:
- return [name for name in dir(mod) if not name.startswith('_')]
-
- def __getattr__(self, key):
- # Use the equivalent of import_item(name), see below
- name = "%s.%s" % (self._mirror, key)
- try:
- return import_item(name)
- except ImportError:
- raise AttributeError(key)
+"""A shim module for deprecated imports
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import sys
+import types
+
+from .importstring import import_item
+
+class ShimWarning(Warning):
+ """A warning to show when a module has moved, and a shim is in its place."""
+
+class ShimImporter(object):
+ """Import hook for a shim.
+
+ This ensures that submodule imports return the real target module,
+ not a clone that will confuse `is` and `isinstance` checks.
+ """
+ def __init__(self, src, mirror):
+ self.src = src
+ self.mirror = mirror
+
+ def _mirror_name(self, fullname):
+ """get the name of the mirrored module"""
+
+ return self.mirror + fullname[len(self.src):]
+
+ def find_module(self, fullname, path=None):
+ """Return self if we should be used to import the module."""
+ if fullname.startswith(self.src + '.'):
+ mirror_name = self._mirror_name(fullname)
+ try:
+ mod = import_item(mirror_name)
+ except ImportError:
+ return
+ else:
+ if not isinstance(mod, types.ModuleType):
+ # not a module
+ return None
+ return self
+
+ def load_module(self, fullname):
+ """Import the mirrored module, and insert it into sys.modules"""
+ mirror_name = self._mirror_name(fullname)
+ mod = import_item(mirror_name)
+ sys.modules[fullname] = mod
+ return mod
+
+
+class ShimModule(types.ModuleType):
+
+ def __init__(self, *args, **kwargs):
+ self._mirror = kwargs.pop("mirror")
+ src = kwargs.pop("src", None)
+ if src:
+ kwargs['name'] = src.rsplit('.', 1)[-1]
+ super(ShimModule, self).__init__(*args, **kwargs)
+ # add import hook for descendent modules
+ if src:
+ sys.meta_path.append(
+ ShimImporter(src=src, mirror=self._mirror)
+ )
+
+ @property
+ def __path__(self):
+ return []
+
+ @property
+ def __spec__(self):
+ """Don't produce __spec__ until requested"""
+ return __import__(self._mirror).__spec__
+
+ def __dir__(self):
+ return dir(__import__(self._mirror))
+
+ @property
+ def __all__(self):
+ """Ensure __all__ is always defined"""
+ mod = __import__(self._mirror)
+ try:
+ return mod.__all__
+ except AttributeError:
+ return [name for name in dir(mod) if not name.startswith('_')]
+
+ def __getattr__(self, key):
+ # Use the equivalent of import_item(name), see below
+ name = "%s.%s" % (self._mirror, key)
+ try:
+ return import_item(name)
+ except ImportError:
+ raise AttributeError(key)
diff --git a/contrib/python/ipython/py2/IPython/utils/signatures.py b/contrib/python/ipython/py2/IPython/utils/signatures.py
index 4d0eb74a7e..dedc51cfda 100644
--- a/contrib/python/ipython/py2/IPython/utils/signatures.py
+++ b/contrib/python/ipython/py2/IPython/utils/signatures.py
@@ -1,11 +1,11 @@
-"""Function signature objects for callables.
-
-Use the standard library version if available, as it is more up to date.
-Fallback on backport otherwise.
-"""
-
-
-try:
- from inspect import BoundArguments, Parameter, Signature, signature
-except ImportError:
- from ._signatures import BoundArguments, Parameter, Signature, signature
+"""Function signature objects for callables.
+
+Use the standard library version if available, as it is more up to date.
+Fallback on backport otherwise.
+"""
+
+
+try:
+ from inspect import BoundArguments, Parameter, Signature, signature
+except ImportError:
+ from ._signatures import BoundArguments, Parameter, Signature, signature
diff --git a/contrib/python/ipython/py2/IPython/utils/strdispatch.py b/contrib/python/ipython/py2/IPython/utils/strdispatch.py
index a6183404e7..d6bf510535 100644
--- a/contrib/python/ipython/py2/IPython/utils/strdispatch.py
+++ b/contrib/python/ipython/py2/IPython/utils/strdispatch.py
@@ -1,68 +1,68 @@
-"""String dispatch class to match regexps and dispatch commands.
-"""
-
-# Stdlib imports
-import re
-
-# Our own modules
-from IPython.core.hooks import CommandChainDispatcher
-
-# Code begins
-class StrDispatch(object):
- """Dispatch (lookup) a set of strings / regexps for match.
-
- Example:
-
- >>> dis = StrDispatch()
- >>> dis.add_s('hei',34, priority = 4)
- >>> dis.add_s('hei',123, priority = 2)
- >>> dis.add_re('h.i', 686)
- >>> print(list(dis.flat_matches('hei')))
- [123, 34, 686]
- """
-
- def __init__(self):
- self.strs = {}
- self.regexs = {}
-
- def add_s(self, s, obj, priority= 0 ):
- """ Adds a target 'string' for dispatching """
-
- chain = self.strs.get(s, CommandChainDispatcher())
- chain.add(obj,priority)
- self.strs[s] = chain
-
- def add_re(self, regex, obj, priority= 0 ):
- """ Adds a target regexp for dispatching """
-
- chain = self.regexs.get(regex, CommandChainDispatcher())
- chain.add(obj,priority)
- self.regexs[regex] = chain
-
- def dispatch(self, key):
- """ Get a seq of Commandchain objects that match key """
- if key in self.strs:
- yield self.strs[key]
-
- for r, obj in self.regexs.items():
- if re.match(r, key):
- yield obj
- else:
- #print "nomatch",key # dbg
- pass
-
- def __repr__(self):
- return "<Strdispatch %s, %s>" % (self.strs, self.regexs)
-
- def s_matches(self, key):
- if key not in self.strs:
- return
- for el in self.strs[key]:
- yield el[1]
-
- def flat_matches(self, key):
- """ Yield all 'value' targets, without priority """
- for val in self.dispatch(key):
- for el in val:
- yield el[1] # only value, no priority
- return
+"""String dispatch class to match regexps and dispatch commands.
+"""
+
+# Stdlib imports
+import re
+
+# Our own modules
+from IPython.core.hooks import CommandChainDispatcher
+
+# Code begins
+class StrDispatch(object):
+ """Dispatch (lookup) a set of strings / regexps for match.
+
+ Example:
+
+ >>> dis = StrDispatch()
+ >>> dis.add_s('hei',34, priority = 4)
+ >>> dis.add_s('hei',123, priority = 2)
+ >>> dis.add_re('h.i', 686)
+ >>> print(list(dis.flat_matches('hei')))
+ [123, 34, 686]
+ """
+
+ def __init__(self):
+ self.strs = {}
+ self.regexs = {}
+
+ def add_s(self, s, obj, priority= 0 ):
+ """ Adds a target 'string' for dispatching """
+
+ chain = self.strs.get(s, CommandChainDispatcher())
+ chain.add(obj,priority)
+ self.strs[s] = chain
+
+ def add_re(self, regex, obj, priority= 0 ):
+ """ Adds a target regexp for dispatching """
+
+ chain = self.regexs.get(regex, CommandChainDispatcher())
+ chain.add(obj,priority)
+ self.regexs[regex] = chain
+
+ def dispatch(self, key):
+ """ Get a seq of Commandchain objects that match key """
+ if key in self.strs:
+ yield self.strs[key]
+
+ for r, obj in self.regexs.items():
+ if re.match(r, key):
+ yield obj
+ else:
+ #print "nomatch",key # dbg
+ pass
+
+ def __repr__(self):
+ return "<Strdispatch %s, %s>" % (self.strs, self.regexs)
+
+ def s_matches(self, key):
+ if key not in self.strs:
+ return
+ for el in self.strs[key]:
+ yield el[1]
+
+ def flat_matches(self, key):
+ """ Yield all 'value' targets, without priority """
+ for val in self.dispatch(key):
+ for el in val:
+ yield el[1] # only value, no priority
+ return
diff --git a/contrib/python/ipython/py2/IPython/utils/sysinfo.py b/contrib/python/ipython/py2/IPython/utils/sysinfo.py
index 51ca68d9cf..db7f2914d4 100644
--- a/contrib/python/ipython/py2/IPython/utils/sysinfo.py
+++ b/contrib/python/ipython/py2/IPython/utils/sysinfo.py
@@ -1,167 +1,167 @@
-# encoding: utf-8
-"""
-Utilities for getting information about IPython and the system it's running in.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import os
-import platform
-import pprint
-import sys
-import subprocess
-
-from IPython.core import release
-from IPython.utils import py3compat, _sysinfo, encoding
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-def pkg_commit_hash(pkg_path):
- """Get short form of commit hash given directory `pkg_path`
-
- We get the commit hash from (in order of preference):
-
- * IPython.utils._sysinfo.commit
- * git output, if we are in a git repository
-
- If these fail, we return a not-found placeholder tuple
-
- Parameters
- ----------
- pkg_path : str
- directory containing package
- only used for getting commit from active repo
-
- Returns
- -------
- hash_from : str
- Where we got the hash from - description
- hash_str : str
- short form of hash
- """
- # Try and get commit from written commit text file
- if _sysinfo.commit:
- return "installation", _sysinfo.commit
-
- # maybe we are in a repository
- proc = subprocess.Popen('git rev-parse --short HEAD',
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- cwd=pkg_path, shell=True)
- repo_commit, _ = proc.communicate()
- if repo_commit:
- return 'repository', repo_commit.strip().decode('ascii')
- return '(none found)', u'<not found>'
-
-
-def pkg_info(pkg_path):
- """Return dict describing the context of this package
-
- Parameters
- ----------
- pkg_path : str
- path containing __init__.py for package
-
- Returns
- -------
- context : dict
- with named parameters of interest
- """
- src, hsh = pkg_commit_hash(pkg_path)
- return dict(
- ipython_version=release.version,
- ipython_path=pkg_path,
- commit_source=src,
- commit_hash=hsh,
- sys_version=sys.version,
- sys_executable=sys.executable,
- sys_platform=sys.platform,
- platform=platform.platform(),
- os_name=os.name,
- default_encoding=encoding.DEFAULT_ENCODING,
- )
-
-def get_sys_info():
- """Return useful information about IPython and the system, as a dict."""
- p = os.path
- path = p.realpath(p.dirname(p.abspath(p.join(__file__, '..'))))
- return pkg_info(path)
-
-@py3compat.doctest_refactor_print
-def sys_info():
- """Return useful information about IPython and the system, as a string.
-
- Examples
- --------
- ::
-
- In [2]: print sys_info()
- {'commit_hash': '144fdae', # random
- 'commit_source': 'repository',
- 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython',
- 'ipython_version': '0.11.dev',
- 'os_name': 'posix',
- 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick',
- 'sys_executable': '/usr/bin/python',
- 'sys_platform': 'linux2',
- 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'}
- """
- return pprint.pformat(get_sys_info())
-
-def _num_cpus_unix():
- """Return the number of active CPUs on a Unix system."""
- return os.sysconf("SC_NPROCESSORS_ONLN")
-
-
-def _num_cpus_darwin():
- """Return the number of active CPUs on a Darwin system."""
- p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)
- return p.stdout.read()
-
-
-def _num_cpus_windows():
- """Return the number of active CPUs on a Windows system."""
- return os.environ.get("NUMBER_OF_PROCESSORS")
-
-
-def num_cpus():
- """Return the effective number of CPUs in the system as an integer.
-
- This cross-platform function makes an attempt at finding the total number of
- available CPUs in the system, as returned by various underlying system and
- python calls.
-
- If it can't find a sensible answer, it returns 1 (though an error *may* make
- it return a large positive number that's actually incorrect).
- """
-
- # Many thanks to the Parallel Python project (http://www.parallelpython.com)
- # for the names of the keys we needed to look up for this function. This
- # code was inspired by their equivalent function.
-
- ncpufuncs = {'Linux':_num_cpus_unix,
- 'Darwin':_num_cpus_darwin,
- 'Windows':_num_cpus_windows
- }
-
- ncpufunc = ncpufuncs.get(platform.system(),
- # default to unix version (Solaris, AIX, etc)
- _num_cpus_unix)
-
- try:
- ncpus = max(1,int(ncpufunc()))
- except:
- ncpus = 1
- return ncpus
-
+# encoding: utf-8
+"""
+Utilities for getting information about IPython and the system it's running in.
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import os
+import platform
+import pprint
+import sys
+import subprocess
+
+from IPython.core import release
+from IPython.utils import py3compat, _sysinfo, encoding
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+def pkg_commit_hash(pkg_path):
+ """Get short form of commit hash given directory `pkg_path`
+
+ We get the commit hash from (in order of preference):
+
+ * IPython.utils._sysinfo.commit
+ * git output, if we are in a git repository
+
+ If these fail, we return a not-found placeholder tuple
+
+ Parameters
+ ----------
+ pkg_path : str
+ directory containing package
+ only used for getting commit from active repo
+
+ Returns
+ -------
+ hash_from : str
+ Where we got the hash from - description
+ hash_str : str
+ short form of hash
+ """
+ # Try and get commit from written commit text file
+ if _sysinfo.commit:
+ return "installation", _sysinfo.commit
+
+ # maybe we are in a repository
+ proc = subprocess.Popen('git rev-parse --short HEAD',
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ cwd=pkg_path, shell=True)
+ repo_commit, _ = proc.communicate()
+ if repo_commit:
+ return 'repository', repo_commit.strip().decode('ascii')
+ return '(none found)', u'<not found>'
+
+
+def pkg_info(pkg_path):
+ """Return dict describing the context of this package
+
+ Parameters
+ ----------
+ pkg_path : str
+ path containing __init__.py for package
+
+ Returns
+ -------
+ context : dict
+ with named parameters of interest
+ """
+ src, hsh = pkg_commit_hash(pkg_path)
+ return dict(
+ ipython_version=release.version,
+ ipython_path=pkg_path,
+ commit_source=src,
+ commit_hash=hsh,
+ sys_version=sys.version,
+ sys_executable=sys.executable,
+ sys_platform=sys.platform,
+ platform=platform.platform(),
+ os_name=os.name,
+ default_encoding=encoding.DEFAULT_ENCODING,
+ )
+
+def get_sys_info():
+ """Return useful information about IPython and the system, as a dict."""
+ p = os.path
+ path = p.realpath(p.dirname(p.abspath(p.join(__file__, '..'))))
+ return pkg_info(path)
+
+@py3compat.doctest_refactor_print
+def sys_info():
+ """Return useful information about IPython and the system, as a string.
+
+ Examples
+ --------
+ ::
+
+ In [2]: print sys_info()
+ {'commit_hash': '144fdae', # random
+ 'commit_source': 'repository',
+ 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython',
+ 'ipython_version': '0.11.dev',
+ 'os_name': 'posix',
+ 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick',
+ 'sys_executable': '/usr/bin/python',
+ 'sys_platform': 'linux2',
+ 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'}
+ """
+ return pprint.pformat(get_sys_info())
+
+def _num_cpus_unix():
+ """Return the number of active CPUs on a Unix system."""
+ return os.sysconf("SC_NPROCESSORS_ONLN")
+
+
+def _num_cpus_darwin():
+ """Return the number of active CPUs on a Darwin system."""
+ p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)
+ return p.stdout.read()
+
+
+def _num_cpus_windows():
+ """Return the number of active CPUs on a Windows system."""
+ return os.environ.get("NUMBER_OF_PROCESSORS")
+
+
+def num_cpus():
+ """Return the effective number of CPUs in the system as an integer.
+
+ This cross-platform function makes an attempt at finding the total number of
+ available CPUs in the system, as returned by various underlying system and
+ python calls.
+
+ If it can't find a sensible answer, it returns 1 (though an error *may* make
+ it return a large positive number that's actually incorrect).
+ """
+
+ # Many thanks to the Parallel Python project (http://www.parallelpython.com)
+ # for the names of the keys we needed to look up for this function. This
+ # code was inspired by their equivalent function.
+
+ ncpufuncs = {'Linux':_num_cpus_unix,
+ 'Darwin':_num_cpus_darwin,
+ 'Windows':_num_cpus_windows
+ }
+
+ ncpufunc = ncpufuncs.get(platform.system(),
+ # default to unix version (Solaris, AIX, etc)
+ _num_cpus_unix)
+
+ try:
+ ncpus = max(1,int(ncpufunc()))
+ except:
+ ncpus = 1
+ return ncpus
+
diff --git a/contrib/python/ipython/py2/IPython/utils/syspathcontext.py b/contrib/python/ipython/py2/IPython/utils/syspathcontext.py
index fdcfbbee35..89612038ff 100644
--- a/contrib/python/ipython/py2/IPython/utils/syspathcontext.py
+++ b/contrib/python/ipython/py2/IPython/utils/syspathcontext.py
@@ -1,71 +1,71 @@
-# encoding: utf-8
-"""
-Context managers for adding things to sys.path temporarily.
-
-Authors:
-
-* Brian Granger
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import sys
-
-from IPython.utils.py3compat import cast_bytes_py2
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-class appended_to_syspath(object):
- """A context for appending a directory to sys.path for a second."""
-
- def __init__(self, dir):
- self.dir = cast_bytes_py2(dir, sys.getdefaultencoding())
-
- def __enter__(self):
- if self.dir not in sys.path:
- sys.path.append(self.dir)
- self.added = True
- else:
- self.added = False
-
- def __exit__(self, type, value, traceback):
- if self.added:
- try:
- sys.path.remove(self.dir)
- except ValueError:
- pass
- # Returning False causes any exceptions to be re-raised.
- return False
-
-class prepended_to_syspath(object):
- """A context for prepending a directory to sys.path for a second."""
-
- def __init__(self, dir):
- self.dir = cast_bytes_py2(dir, sys.getdefaultencoding())
-
- def __enter__(self):
- if self.dir not in sys.path:
- sys.path.insert(0,self.dir)
- self.added = True
- else:
- self.added = False
-
- def __exit__(self, type, value, traceback):
- if self.added:
- try:
- sys.path.remove(self.dir)
- except ValueError:
- pass
- # Returning False causes any exceptions to be re-raised.
- return False
+# encoding: utf-8
+"""
+Context managers for adding things to sys.path temporarily.
+
+Authors:
+
+* Brian Granger
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import sys
+
+from IPython.utils.py3compat import cast_bytes_py2
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+class appended_to_syspath(object):
+ """A context for appending a directory to sys.path for a second."""
+
+ def __init__(self, dir):
+ self.dir = cast_bytes_py2(dir, sys.getdefaultencoding())
+
+ def __enter__(self):
+ if self.dir not in sys.path:
+ sys.path.append(self.dir)
+ self.added = True
+ else:
+ self.added = False
+
+ def __exit__(self, type, value, traceback):
+ if self.added:
+ try:
+ sys.path.remove(self.dir)
+ except ValueError:
+ pass
+ # Returning False causes any exceptions to be re-raised.
+ return False
+
+class prepended_to_syspath(object):
+ """A context for prepending a directory to sys.path for a second."""
+
+ def __init__(self, dir):
+ self.dir = cast_bytes_py2(dir, sys.getdefaultencoding())
+
+ def __enter__(self):
+ if self.dir not in sys.path:
+ sys.path.insert(0,self.dir)
+ self.added = True
+ else:
+ self.added = False
+
+ def __exit__(self, type, value, traceback):
+ if self.added:
+ try:
+ sys.path.remove(self.dir)
+ except ValueError:
+ pass
+ # Returning False causes any exceptions to be re-raised.
+ return False
diff --git a/contrib/python/ipython/py2/IPython/utils/tempdir.py b/contrib/python/ipython/py2/IPython/utils/tempdir.py
index 909205e192..951abd65c9 100644
--- a/contrib/python/ipython/py2/IPython/utils/tempdir.py
+++ b/contrib/python/ipython/py2/IPython/utils/tempdir.py
@@ -1,145 +1,145 @@
-"""TemporaryDirectory class, copied from Python 3.2.
-
-This is copied from the stdlib and will be standard in Python 3.2 and onwards.
-"""
-from __future__ import print_function
-
-import os as _os
-import warnings as _warnings
-import sys as _sys
-
-# This code should only be used in Python versions < 3.2, since after that we
-# can rely on the stdlib itself.
-try:
- from tempfile import TemporaryDirectory
-
-except ImportError:
- from tempfile import mkdtemp, template
-
- class TemporaryDirectory(object):
- """Create and return a temporary directory. This has the same
- behavior as mkdtemp but can be used as a context manager. For
- example:
-
- with TemporaryDirectory() as tmpdir:
- ...
-
- Upon exiting the context, the directory and everthing contained
- in it are removed.
- """
-
- def __init__(self, suffix="", prefix=template, dir=None):
- self.name = mkdtemp(suffix, prefix, dir)
- self._closed = False
-
- def __enter__(self):
- return self.name
-
- def cleanup(self, _warn=False):
- if self.name and not self._closed:
- try:
- self._rmtree(self.name)
- except (TypeError, AttributeError) as ex:
- # Issue #10188: Emit a warning on stderr
- # if the directory could not be cleaned
- # up due to missing globals
- if "None" not in str(ex):
- raise
- print("ERROR: {!r} while cleaning up {!r}".format(ex, self,),
- file=_sys.stderr)
- return
- self._closed = True
- if _warn:
- self._warn("Implicitly cleaning up {!r}".format(self),
- Warning)
-
- def __exit__(self, exc, value, tb):
- self.cleanup()
-
- def __del__(self):
- # Issue a ResourceWarning if implicit cleanup needed
- self.cleanup(_warn=True)
-
-
- # XXX (ncoghlan): The following code attempts to make
- # this class tolerant of the module nulling out process
- # that happens during CPython interpreter shutdown
- # Alas, it doesn't actually manage it. See issue #10188
- _listdir = staticmethod(_os.listdir)
- _path_join = staticmethod(_os.path.join)
- _isdir = staticmethod(_os.path.isdir)
- _remove = staticmethod(_os.remove)
- _rmdir = staticmethod(_os.rmdir)
- _os_error = _os.error
- _warn = _warnings.warn
-
- def _rmtree(self, path):
- # Essentially a stripped down version of shutil.rmtree. We can't
- # use globals because they may be None'ed out at shutdown.
- for name in self._listdir(path):
- fullname = self._path_join(path, name)
- try:
- isdir = self._isdir(fullname)
- except self._os_error:
- isdir = False
- if isdir:
- self._rmtree(fullname)
- else:
- try:
- self._remove(fullname)
- except self._os_error:
- pass
- try:
- self._rmdir(path)
- except self._os_error:
- pass
-
-
-class NamedFileInTemporaryDirectory(object):
-
- def __init__(self, filename, mode='w+b', bufsize=-1, **kwds):
- """
- Open a file named `filename` in a temporary directory.
-
- This context manager is preferred over `NamedTemporaryFile` in
- stdlib `tempfile` when one needs to reopen the file.
-
- Arguments `mode` and `bufsize` are passed to `open`.
- Rest of the arguments are passed to `TemporaryDirectory`.
-
- """
- self._tmpdir = TemporaryDirectory(**kwds)
- path = _os.path.join(self._tmpdir.name, filename)
- self.file = open(path, mode, bufsize)
-
- def cleanup(self):
- self.file.close()
- self._tmpdir.cleanup()
-
- __del__ = cleanup
-
- def __enter__(self):
- return self.file
-
- def __exit__(self, type, value, traceback):
- self.cleanup()
-
-
-class TemporaryWorkingDirectory(TemporaryDirectory):
- """
- Creates a temporary directory and sets the cwd to that directory.
- Automatically reverts to previous cwd upon cleanup.
- Usage example:
-
- with TemporaryWorkingDirectory() as tmpdir:
- ...
- """
- def __enter__(self):
- self.old_wd = _os.getcwd()
- _os.chdir(self.name)
- return super(TemporaryWorkingDirectory, self).__enter__()
-
- def __exit__(self, exc, value, tb):
- _os.chdir(self.old_wd)
- return super(TemporaryWorkingDirectory, self).__exit__(exc, value, tb)
-
+"""TemporaryDirectory class, copied from Python 3.2.
+
+This is copied from the stdlib and will be standard in Python 3.2 and onwards.
+"""
+from __future__ import print_function
+
+import os as _os
+import warnings as _warnings
+import sys as _sys
+
+# This code should only be used in Python versions < 3.2, since after that we
+# can rely on the stdlib itself.
+try:
+ from tempfile import TemporaryDirectory
+
+except ImportError:
+ from tempfile import mkdtemp, template
+
+ class TemporaryDirectory(object):
+ """Create and return a temporary directory. This has the same
+ behavior as mkdtemp but can be used as a context manager. For
+ example:
+
+ with TemporaryDirectory() as tmpdir:
+ ...
+
+ Upon exiting the context, the directory and everthing contained
+ in it are removed.
+ """
+
+ def __init__(self, suffix="", prefix=template, dir=None):
+ self.name = mkdtemp(suffix, prefix, dir)
+ self._closed = False
+
+ def __enter__(self):
+ return self.name
+
+ def cleanup(self, _warn=False):
+ if self.name and not self._closed:
+ try:
+ self._rmtree(self.name)
+ except (TypeError, AttributeError) as ex:
+ # Issue #10188: Emit a warning on stderr
+ # if the directory could not be cleaned
+ # up due to missing globals
+ if "None" not in str(ex):
+ raise
+ print("ERROR: {!r} while cleaning up {!r}".format(ex, self,),
+ file=_sys.stderr)
+ return
+ self._closed = True
+ if _warn:
+ self._warn("Implicitly cleaning up {!r}".format(self),
+ Warning)
+
+ def __exit__(self, exc, value, tb):
+ self.cleanup()
+
+ def __del__(self):
+ # Issue a ResourceWarning if implicit cleanup needed
+ self.cleanup(_warn=True)
+
+
+ # XXX (ncoghlan): The following code attempts to make
+ # this class tolerant of the module nulling out process
+ # that happens during CPython interpreter shutdown
+ # Alas, it doesn't actually manage it. See issue #10188
+ _listdir = staticmethod(_os.listdir)
+ _path_join = staticmethod(_os.path.join)
+ _isdir = staticmethod(_os.path.isdir)
+ _remove = staticmethod(_os.remove)
+ _rmdir = staticmethod(_os.rmdir)
+ _os_error = _os.error
+ _warn = _warnings.warn
+
+ def _rmtree(self, path):
+ # Essentially a stripped down version of shutil.rmtree. We can't
+ # use globals because they may be None'ed out at shutdown.
+ for name in self._listdir(path):
+ fullname = self._path_join(path, name)
+ try:
+ isdir = self._isdir(fullname)
+ except self._os_error:
+ isdir = False
+ if isdir:
+ self._rmtree(fullname)
+ else:
+ try:
+ self._remove(fullname)
+ except self._os_error:
+ pass
+ try:
+ self._rmdir(path)
+ except self._os_error:
+ pass
+
+
+class NamedFileInTemporaryDirectory(object):
+
+ def __init__(self, filename, mode='w+b', bufsize=-1, **kwds):
+ """
+ Open a file named `filename` in a temporary directory.
+
+ This context manager is preferred over `NamedTemporaryFile` in
+ stdlib `tempfile` when one needs to reopen the file.
+
+ Arguments `mode` and `bufsize` are passed to `open`.
+ Rest of the arguments are passed to `TemporaryDirectory`.
+
+ """
+ self._tmpdir = TemporaryDirectory(**kwds)
+ path = _os.path.join(self._tmpdir.name, filename)
+ self.file = open(path, mode, bufsize)
+
+ def cleanup(self):
+ self.file.close()
+ self._tmpdir.cleanup()
+
+ __del__ = cleanup
+
+ def __enter__(self):
+ return self.file
+
+ def __exit__(self, type, value, traceback):
+ self.cleanup()
+
+
+class TemporaryWorkingDirectory(TemporaryDirectory):
+ """
+ Creates a temporary directory and sets the cwd to that directory.
+ Automatically reverts to previous cwd upon cleanup.
+ Usage example:
+
+ with TemporaryWorkingDirectory() as tmpdir:
+ ...
+ """
+ def __enter__(self):
+ self.old_wd = _os.getcwd()
+ _os.chdir(self.name)
+ return super(TemporaryWorkingDirectory, self).__enter__()
+
+ def __exit__(self, exc, value, tb):
+ _os.chdir(self.old_wd)
+ return super(TemporaryWorkingDirectory, self).__exit__(exc, value, tb)
+
diff --git a/contrib/python/ipython/py2/IPython/utils/terminal.py b/contrib/python/ipython/py2/IPython/utils/terminal.py
index 833debce41..e92c410c79 100644
--- a/contrib/python/ipython/py2/IPython/utils/terminal.py
+++ b/contrib/python/ipython/py2/IPython/utils/terminal.py
@@ -1,22 +1,22 @@
-# encoding: utf-8
-"""
-Utilities for working with terminals.
-
-Authors:
-
-* Brian E. Granger
-* Fernando Perez
-* Alexander Belchenko (e-mail: bialix AT ukr.net)
-"""
-
+# encoding: utf-8
+"""
+Utilities for working with terminals.
+
+Authors:
+
+* Brian E. Granger
+* Fernando Perez
+* Alexander Belchenko (e-mail: bialix AT ukr.net)
+"""
+
from __future__ import absolute_import
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
-
-import os
-import sys
-import warnings
+
+import os
+import sys
+import warnings
try:
from shutil import get_terminal_size as _get_terminal_size
except ImportError:
@@ -25,101 +25,101 @@ except ImportError:
from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size
except ImportError:
from ._get_terminal_size import get_terminal_size as _get_terminal_size
-
-from . import py3compat
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-# This variable is part of the expected API of the module:
-ignore_termtitle = True
-
-
-
-if os.name == 'posix':
- def _term_clear():
- os.system('clear')
-elif sys.platform == 'win32':
- def _term_clear():
- os.system('cls')
-else:
- def _term_clear():
- pass
-
-
-
-def toggle_set_term_title(val):
- """Control whether set_term_title is active or not.
-
- set_term_title() allows writing to the console titlebar. In embedded
- widgets this can cause problems, so this call can be used to toggle it on
- or off as needed.
-
- The default state of the module is for the function to be disabled.
-
- Parameters
- ----------
- val : bool
- If True, set_term_title() actually writes to the terminal (using the
- appropriate platform-specific module). If False, it is a no-op.
- """
- global ignore_termtitle
- ignore_termtitle = not(val)
-
-
-def _set_term_title(*args,**kw):
- """Dummy no-op."""
- pass
-
-
-def _set_term_title_xterm(title):
- """ Change virtual terminal title in xterm-workalikes """
- sys.stdout.write('\033]0;%s\007' % title)
-
-if os.name == 'posix':
- TERM = os.environ.get('TERM','')
- if TERM.startswith('xterm'):
- _set_term_title = _set_term_title_xterm
-elif sys.platform == 'win32':
- try:
- import ctypes
-
- SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW
- SetConsoleTitleW.argtypes = [ctypes.c_wchar_p]
-
- def _set_term_title(title):
- """Set terminal title using ctypes to access the Win32 APIs."""
- SetConsoleTitleW(title)
- except ImportError:
- def _set_term_title(title):
- """Set terminal title using the 'title' command."""
- global ignore_termtitle
-
- try:
- # Cannot be on network share when issuing system commands
- curr = py3compat.getcwd()
- os.chdir("C:")
- ret = os.system("title " + title)
- finally:
- os.chdir(curr)
- if ret:
- # non-zero return code signals error, don't try again
- ignore_termtitle = True
-
-
-def set_term_title(title):
- """Set terminal title using the necessary platform-dependent calls."""
- if ignore_termtitle:
- return
- _set_term_title(title)
-
-
-def freeze_term_title():
- warnings.warn("This function is deprecated, use toggle_set_term_title()")
- global ignore_termtitle
- ignore_termtitle = True
-
-
+
+from . import py3compat
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+# This variable is part of the expected API of the module:
+ignore_termtitle = True
+
+
+
+if os.name == 'posix':
+ def _term_clear():
+ os.system('clear')
+elif sys.platform == 'win32':
+ def _term_clear():
+ os.system('cls')
+else:
+ def _term_clear():
+ pass
+
+
+
+def toggle_set_term_title(val):
+ """Control whether set_term_title is active or not.
+
+ set_term_title() allows writing to the console titlebar. In embedded
+ widgets this can cause problems, so this call can be used to toggle it on
+ or off as needed.
+
+ The default state of the module is for the function to be disabled.
+
+ Parameters
+ ----------
+ val : bool
+ If True, set_term_title() actually writes to the terminal (using the
+ appropriate platform-specific module). If False, it is a no-op.
+ """
+ global ignore_termtitle
+ ignore_termtitle = not(val)
+
+
+def _set_term_title(*args,**kw):
+ """Dummy no-op."""
+ pass
+
+
+def _set_term_title_xterm(title):
+ """ Change virtual terminal title in xterm-workalikes """
+ sys.stdout.write('\033]0;%s\007' % title)
+
+if os.name == 'posix':
+ TERM = os.environ.get('TERM','')
+ if TERM.startswith('xterm'):
+ _set_term_title = _set_term_title_xterm
+elif sys.platform == 'win32':
+ try:
+ import ctypes
+
+ SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW
+ SetConsoleTitleW.argtypes = [ctypes.c_wchar_p]
+
+ def _set_term_title(title):
+ """Set terminal title using ctypes to access the Win32 APIs."""
+ SetConsoleTitleW(title)
+ except ImportError:
+ def _set_term_title(title):
+ """Set terminal title using the 'title' command."""
+ global ignore_termtitle
+
+ try:
+ # Cannot be on network share when issuing system commands
+ curr = py3compat.getcwd()
+ os.chdir("C:")
+ ret = os.system("title " + title)
+ finally:
+ os.chdir(curr)
+ if ret:
+ # non-zero return code signals error, don't try again
+ ignore_termtitle = True
+
+
+def set_term_title(title):
+ """Set terminal title using the necessary platform-dependent calls."""
+ if ignore_termtitle:
+ return
+ _set_term_title(title)
+
+
+def freeze_term_title():
+ warnings.warn("This function is deprecated, use toggle_set_term_title()")
+ global ignore_termtitle
+ ignore_termtitle = True
+
+
def get_terminal_size(defaultx=80, defaulty=25):
return _get_terminal_size((defaultx, defaulty))
diff --git a/contrib/python/ipython/py2/IPython/utils/text.py b/contrib/python/ipython/py2/IPython/utils/text.py
index 50ff04e1fc..5ed1a845e3 100644
--- a/contrib/python/ipython/py2/IPython/utils/text.py
+++ b/contrib/python/ipython/py2/IPython/utils/text.py
@@ -1,783 +1,783 @@
-# encoding: utf-8
-"""
-Utilities for working with strings and text.
-
-Inheritance diagram:
-
-.. inheritance-diagram:: IPython.utils.text
- :parts: 3
-"""
-from __future__ import absolute_import
-
-import os
-import re
-import sys
-import textwrap
-from string import Formatter
+# encoding: utf-8
+"""
+Utilities for working with strings and text.
+
+Inheritance diagram:
+
+.. inheritance-diagram:: IPython.utils.text
+ :parts: 3
+"""
+from __future__ import absolute_import
+
+import os
+import re
+import sys
+import textwrap
+from string import Formatter
try:
from pathlib import Path
except ImportError:
# Python 2 backport
from pathlib2 import Path
-
-from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest
-from IPython.utils import py3compat
-
-# datetime.strftime date format for ipython
-if sys.platform == 'win32':
- date_format = "%B %d, %Y"
-else:
- date_format = "%B %-d, %Y"
-
-class LSString(str):
- """String derivative with a special access attributes.
-
- These are normal strings, but with the special attributes:
-
- .l (or .list) : value as list (split on newlines).
- .n (or .nlstr): original value (the string itself).
- .s (or .spstr): value as whitespace-separated string.
- .p (or .paths): list of path objects (requires path.py package)
-
- Any values which require transformations are computed only once and
- cached.
-
- Such strings are very useful to efficiently interact with the shell, which
- typically only understands whitespace-separated options for commands."""
-
- def get_list(self):
- try:
- return self.__list
- except AttributeError:
- self.__list = self.split('\n')
- return self.__list
-
- l = list = property(get_list)
-
- def get_spstr(self):
- try:
- return self.__spstr
- except AttributeError:
- self.__spstr = self.replace('\n',' ')
- return self.__spstr
-
- s = spstr = property(get_spstr)
-
- def get_nlstr(self):
- return self
-
- n = nlstr = property(get_nlstr)
-
- def get_paths(self):
- try:
- return self.__paths
- except AttributeError:
+
+from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest
+from IPython.utils import py3compat
+
+# datetime.strftime date format for ipython
+if sys.platform == 'win32':
+ date_format = "%B %d, %Y"
+else:
+ date_format = "%B %-d, %Y"
+
+class LSString(str):
+ """String derivative with a special access attributes.
+
+ These are normal strings, but with the special attributes:
+
+ .l (or .list) : value as list (split on newlines).
+ .n (or .nlstr): original value (the string itself).
+ .s (or .spstr): value as whitespace-separated string.
+ .p (or .paths): list of path objects (requires path.py package)
+
+ Any values which require transformations are computed only once and
+ cached.
+
+ Such strings are very useful to efficiently interact with the shell, which
+ typically only understands whitespace-separated options for commands."""
+
+ def get_list(self):
+ try:
+ return self.__list
+ except AttributeError:
+ self.__list = self.split('\n')
+ return self.__list
+
+ l = list = property(get_list)
+
+ def get_spstr(self):
+ try:
+ return self.__spstr
+ except AttributeError:
+ self.__spstr = self.replace('\n',' ')
+ return self.__spstr
+
+ s = spstr = property(get_spstr)
+
+ def get_nlstr(self):
+ return self
+
+ n = nlstr = property(get_nlstr)
+
+ def get_paths(self):
+ try:
+ return self.__paths
+ except AttributeError:
self.__paths = [Path(p) for p in self.split('\n') if os.path.exists(p)]
- return self.__paths
-
- p = paths = property(get_paths)
-
-# FIXME: We need to reimplement type specific displayhook and then add this
-# back as a custom printer. This should also be moved outside utils into the
-# core.
-
-# def print_lsstring(arg):
-# """ Prettier (non-repr-like) and more informative printer for LSString """
-# print "LSString (.p, .n, .l, .s available). Value:"
-# print arg
-#
-#
-# print_lsstring = result_display.when_type(LSString)(print_lsstring)
-
-
-class SList(list):
- """List derivative with a special access attributes.
-
- These are normal lists, but with the special attributes:
-
- * .l (or .list) : value as list (the list itself).
- * .n (or .nlstr): value as a string, joined on newlines.
- * .s (or .spstr): value as a string, joined on spaces.
- * .p (or .paths): list of path objects (requires path.py package)
-
- Any values which require transformations are computed only once and
- cached."""
-
- def get_list(self):
- return self
-
- l = list = property(get_list)
-
- def get_spstr(self):
- try:
- return self.__spstr
- except AttributeError:
- self.__spstr = ' '.join(self)
- return self.__spstr
-
- s = spstr = property(get_spstr)
-
- def get_nlstr(self):
- try:
- return self.__nlstr
- except AttributeError:
- self.__nlstr = '\n'.join(self)
- return self.__nlstr
-
- n = nlstr = property(get_nlstr)
-
- def get_paths(self):
- try:
- return self.__paths
- except AttributeError:
+ return self.__paths
+
+ p = paths = property(get_paths)
+
+# FIXME: We need to reimplement type specific displayhook and then add this
+# back as a custom printer. This should also be moved outside utils into the
+# core.
+
+# def print_lsstring(arg):
+# """ Prettier (non-repr-like) and more informative printer for LSString """
+# print "LSString (.p, .n, .l, .s available). Value:"
+# print arg
+#
+#
+# print_lsstring = result_display.when_type(LSString)(print_lsstring)
+
+
+class SList(list):
+ """List derivative with a special access attributes.
+
+ These are normal lists, but with the special attributes:
+
+ * .l (or .list) : value as list (the list itself).
+ * .n (or .nlstr): value as a string, joined on newlines.
+ * .s (or .spstr): value as a string, joined on spaces.
+ * .p (or .paths): list of path objects (requires path.py package)
+
+ Any values which require transformations are computed only once and
+ cached."""
+
+ def get_list(self):
+ return self
+
+ l = list = property(get_list)
+
+ def get_spstr(self):
+ try:
+ return self.__spstr
+ except AttributeError:
+ self.__spstr = ' '.join(self)
+ return self.__spstr
+
+ s = spstr = property(get_spstr)
+
+ def get_nlstr(self):
+ try:
+ return self.__nlstr
+ except AttributeError:
+ self.__nlstr = '\n'.join(self)
+ return self.__nlstr
+
+ n = nlstr = property(get_nlstr)
+
+ def get_paths(self):
+ try:
+ return self.__paths
+ except AttributeError:
self.__paths = [Path(p) for p in self if os.path.exists(p)]
- return self.__paths
-
- p = paths = property(get_paths)
-
- def grep(self, pattern, prune = False, field = None):
- """ Return all strings matching 'pattern' (a regex or callable)
-
- This is case-insensitive. If prune is true, return all items
- NOT matching the pattern.
-
- If field is specified, the match must occur in the specified
- whitespace-separated field.
-
- Examples::
-
- a.grep( lambda x: x.startswith('C') )
- a.grep('Cha.*log', prune=1)
- a.grep('chm', field=-1)
- """
-
- def match_target(s):
- if field is None:
- return s
- parts = s.split()
- try:
- tgt = parts[field]
- return tgt
- except IndexError:
- return ""
-
- if isinstance(pattern, py3compat.string_types):
- pred = lambda x : re.search(pattern, x, re.IGNORECASE)
- else:
- pred = pattern
- if not prune:
- return SList([el for el in self if pred(match_target(el))])
- else:
- return SList([el for el in self if not pred(match_target(el))])
-
- def fields(self, *fields):
- """ Collect whitespace-separated fields from string list
-
- Allows quick awk-like usage of string lists.
-
- Example data (in var a, created by 'a = !ls -l')::
-
- -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
- drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
-
- * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']``
- * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']``
- (note the joining by space).
- * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']``
-
- IndexErrors are ignored.
-
- Without args, fields() just split()'s the strings.
- """
- if len(fields) == 0:
- return [el.split() for el in self]
-
- res = SList()
- for el in [f.split() for f in self]:
- lineparts = []
-
- for fd in fields:
- try:
- lineparts.append(el[fd])
- except IndexError:
- pass
- if lineparts:
- res.append(" ".join(lineparts))
-
- return res
-
- def sort(self,field= None, nums = False):
- """ sort by specified fields (see fields())
-
- Example::
-
- a.sort(1, nums = True)
-
- Sorts a by second field, in numerical order (so that 21 > 3)
-
- """
-
- #decorate, sort, undecorate
- if field is not None:
- dsu = [[SList([line]).fields(field), line] for line in self]
- else:
- dsu = [[line, line] for line in self]
- if nums:
- for i in range(len(dsu)):
- numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
- try:
- n = int(numstr)
- except ValueError:
- n = 0
- dsu[i][0] = n
-
-
- dsu.sort()
- return SList([t[1] for t in dsu])
-
-
-# FIXME: We need to reimplement type specific displayhook and then add this
-# back as a custom printer. This should also be moved outside utils into the
-# core.
-
-# def print_slist(arg):
-# """ Prettier (non-repr-like) and more informative printer for SList """
-# print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
-# if hasattr(arg, 'hideonce') and arg.hideonce:
-# arg.hideonce = False
-# return
-#
-# nlprint(arg) # This was a nested list printer, now removed.
-#
-# print_slist = result_display.when_type(SList)(print_slist)
-
-
-def indent(instr,nspaces=4, ntabs=0, flatten=False):
- """Indent a string a given number of spaces or tabstops.
-
- indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
-
- Parameters
- ----------
-
- instr : basestring
- The string to be indented.
- nspaces : int (default: 4)
- The number of spaces to be indented.
- ntabs : int (default: 0)
- The number of tabs to be indented.
- flatten : bool (default: False)
- Whether to scrub existing indentation. If True, all lines will be
- aligned to the same indentation. If False, existing indentation will
- be strictly increased.
-
- Returns
- -------
-
- str|unicode : string indented by ntabs and nspaces.
-
- """
- if instr is None:
- return
- ind = '\t'*ntabs+' '*nspaces
- if flatten:
- pat = re.compile(r'^\s*', re.MULTILINE)
- else:
- pat = re.compile(r'^', re.MULTILINE)
- outstr = re.sub(pat, ind, instr)
- if outstr.endswith(os.linesep+ind):
- return outstr[:-len(ind)]
- else:
- return outstr
-
-
-def list_strings(arg):
- """Always return a list of strings, given a string or list of strings
- as input.
-
- Examples
- --------
- ::
-
- In [7]: list_strings('A single string')
- Out[7]: ['A single string']
-
- In [8]: list_strings(['A single string in a list'])
- Out[8]: ['A single string in a list']
-
- In [9]: list_strings(['A','list','of','strings'])
- Out[9]: ['A', 'list', 'of', 'strings']
- """
-
- if isinstance(arg, py3compat.string_types): return [arg]
- else: return arg
-
-
-def marquee(txt='',width=78,mark='*'):
- """Return the input string centered in a 'marquee'.
-
- Examples
- --------
- ::
-
- In [16]: marquee('A test',40)
- Out[16]: '**************** A test ****************'
-
- In [17]: marquee('A test',40,'-')
- Out[17]: '---------------- A test ----------------'
-
- In [18]: marquee('A test',40,' ')
- Out[18]: ' A test '
-
- """
- if not txt:
- return (mark*width)[:width]
- nmark = (width-len(txt)-2)//len(mark)//2
- if nmark < 0: nmark =0
- marks = mark*nmark
- return '%s %s %s' % (marks,txt,marks)
-
-
-ini_spaces_re = re.compile(r'^(\s+)')
-
-def num_ini_spaces(strng):
- """Return the number of initial spaces in a string"""
-
- ini_spaces = ini_spaces_re.match(strng)
- if ini_spaces:
- return ini_spaces.end()
- else:
- return 0
-
-
-def format_screen(strng):
- """Format a string for screen printing.
-
- This removes some latex-type format codes."""
- # Paragraph continue
- par_re = re.compile(r'\\$',re.MULTILINE)
- strng = par_re.sub('',strng)
- return strng
-
-
-def dedent(text):
- """Equivalent of textwrap.dedent that ignores unindented first line.
-
- This means it will still dedent strings like:
- '''foo
- is a bar
- '''
-
- For use in wrap_paragraphs.
- """
-
- if text.startswith('\n'):
- # text starts with blank line, don't ignore the first line
- return textwrap.dedent(text)
-
- # split first line
- splits = text.split('\n',1)
- if len(splits) == 1:
- # only one line
- return textwrap.dedent(text)
-
- first, rest = splits
- # dedent everything but the first line
- rest = textwrap.dedent(rest)
- return '\n'.join([first, rest])
-
-
-def wrap_paragraphs(text, ncols=80):
- """Wrap multiple paragraphs to fit a specified width.
-
- This is equivalent to textwrap.wrap, but with support for multiple
- paragraphs, as separated by empty lines.
-
- Returns
- -------
-
- list of complete paragraphs, wrapped to fill `ncols` columns.
- """
- paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
- text = dedent(text).strip()
- paragraphs = paragraph_re.split(text)[::2] # every other entry is space
- out_ps = []
- indent_re = re.compile(r'\n\s+', re.MULTILINE)
- for p in paragraphs:
- # presume indentation that survives dedent is meaningful formatting,
- # so don't fill unless text is flush.
- if indent_re.search(p) is None:
- # wrap paragraph
- p = textwrap.fill(p, ncols)
- out_ps.append(p)
- return out_ps
-
-
-def long_substr(data):
- """Return the longest common substring in a list of strings.
-
- Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python
- """
- substr = ''
- if len(data) > 1 and len(data[0]) > 0:
- for i in range(len(data[0])):
- for j in range(len(data[0])-i+1):
- if j > len(substr) and all(data[0][i:i+j] in x for x in data):
- substr = data[0][i:i+j]
- elif len(data) == 1:
- substr = data[0]
- return substr
-
-
-def strip_email_quotes(text):
- """Strip leading email quotation characters ('>').
-
- Removes any combination of leading '>' interspersed with whitespace that
- appears *identically* in all lines of the input text.
-
- Parameters
- ----------
- text : str
-
- Examples
- --------
-
- Simple uses::
-
- In [2]: strip_email_quotes('> > text')
- Out[2]: 'text'
-
- In [3]: strip_email_quotes('> > text\\n> > more')
- Out[3]: 'text\\nmore'
-
- Note how only the common prefix that appears in all lines is stripped::
-
- In [4]: strip_email_quotes('> > text\\n> > more\\n> more...')
- Out[4]: '> text\\n> more\\nmore...'
-
- So if any line has no quote marks ('>') , then none are stripped from any
- of them ::
-
- In [5]: strip_email_quotes('> > text\\n> > more\\nlast different')
- Out[5]: '> > text\\n> > more\\nlast different'
- """
- lines = text.splitlines()
- matches = set()
- for line in lines:
- prefix = re.match(r'^(\s*>[ >]*)', line)
- if prefix:
- matches.add(prefix.group(1))
- else:
- break
- else:
- prefix = long_substr(list(matches))
- if prefix:
- strip = len(prefix)
- text = '\n'.join([ ln[strip:] for ln in lines])
- return text
-
-def strip_ansi(source):
- """
- Remove ansi escape codes from text.
-
- Parameters
- ----------
- source : str
- Source to remove the ansi from
- """
- return re.sub(r'\033\[(\d|;)+?m', '', source)
-
-
-class EvalFormatter(Formatter):
- """A String Formatter that allows evaluation of simple expressions.
-
- Note that this version interprets a : as specifying a format string (as per
- standard string formatting), so if slicing is required, you must explicitly
- create a slice.
-
- This is to be used in templating cases, such as the parallel batch
- script templates, where simple arithmetic on arguments is useful.
-
- Examples
- --------
- ::
-
- In [1]: f = EvalFormatter()
- In [2]: f.format('{n//4}', n=8)
- Out[2]: '2'
-
- In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello")
- Out[3]: 'll'
- """
- def get_field(self, name, args, kwargs):
- v = eval(name, kwargs)
- return v, name
-
-#XXX: As of Python 3.4, the format string parsing no longer splits on a colon
-# inside [], so EvalFormatter can handle slicing. Once we only support 3.4 and
-# above, it should be possible to remove FullEvalFormatter.
-
-@skip_doctest_py3
-class FullEvalFormatter(Formatter):
- """A String Formatter that allows evaluation of simple expressions.
-
- Any time a format key is not found in the kwargs,
- it will be tried as an expression in the kwargs namespace.
-
- Note that this version allows slicing using [1:2], so you cannot specify
- a format string. Use :class:`EvalFormatter` to permit format strings.
-
- Examples
- --------
- ::
-
- In [1]: f = FullEvalFormatter()
- In [2]: f.format('{n//4}', n=8)
- Out[2]: u'2'
-
- In [3]: f.format('{list(range(5))[2:4]}')
- Out[3]: u'[2, 3]'
-
- In [4]: f.format('{3*2}')
- Out[4]: u'6'
- """
- # copied from Formatter._vformat with minor changes to allow eval
- # and replace the format_spec code with slicing
- def vformat(self, format_string, args, kwargs):
- result = []
- for literal_text, field_name, format_spec, conversion in \
- self.parse(format_string):
-
- # output the literal text
- if literal_text:
- result.append(literal_text)
-
- # if there's a field, output it
- if field_name is not None:
- # this is some markup, find the object and do
- # the formatting
-
- if format_spec:
- # override format spec, to allow slicing:
- field_name = ':'.join([field_name, format_spec])
-
- # eval the contents of the field for the object
- # to be formatted
- obj = eval(field_name, kwargs)
-
- # do any conversion on the resulting object
- obj = self.convert_field(obj, conversion)
-
- # format the object and append to the result
- result.append(self.format_field(obj, ''))
-
- return u''.join(py3compat.cast_unicode(s) for s in result)
-
-
-@skip_doctest_py3
-class DollarFormatter(FullEvalFormatter):
- """Formatter allowing Itpl style $foo replacement, for names and attribute
- access only. Standard {foo} replacement also works, and allows full
- evaluation of its arguments.
-
- Examples
- --------
- ::
-
- In [1]: f = DollarFormatter()
- In [2]: f.format('{n//4}', n=8)
- Out[2]: u'2'
-
- In [3]: f.format('23 * 76 is $result', result=23*76)
- Out[3]: u'23 * 76 is 1748'
-
- In [4]: f.format('$a or {b}', a=1, b=2)
- Out[4]: u'1 or 2'
- """
- _dollar_pattern = re.compile("(.*?)\$(\$?[\w\.]+)")
- def parse(self, fmt_string):
- for literal_txt, field_name, format_spec, conversion \
- in Formatter.parse(self, fmt_string):
-
- # Find $foo patterns in the literal text.
- continue_from = 0
- txt = ""
- for m in self._dollar_pattern.finditer(literal_txt):
- new_txt, new_field = m.group(1,2)
- # $$foo --> $foo
- if new_field.startswith("$"):
- txt += new_txt + new_field
- else:
- yield (txt + new_txt, new_field, "", None)
- txt = ""
- continue_from = m.end()
-
- # Re-yield the {foo} style pattern
- yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion)
-
-#-----------------------------------------------------------------------------
-# Utils to columnize a list of string
-#-----------------------------------------------------------------------------
-
-def _col_chunks(l, max_rows, row_first=False):
- """Yield successive max_rows-sized column chunks from l."""
- if row_first:
- ncols = (len(l) // max_rows) + (len(l) % max_rows > 0)
- for i in py3compat.xrange(ncols):
- yield [l[j] for j in py3compat.xrange(i, len(l), ncols)]
- else:
- for i in py3compat.xrange(0, len(l), max_rows):
- yield l[i:(i + max_rows)]
-
-
-def _find_optimal(rlist, row_first=False, separator_size=2, displaywidth=80):
- """Calculate optimal info to columnize a list of string"""
- for max_rows in range(1, len(rlist) + 1):
- col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first)))
- sumlength = sum(col_widths)
- ncols = len(col_widths)
- if sumlength + separator_size * (ncols - 1) <= displaywidth:
- break
- return {'num_columns': ncols,
- 'optimal_separator_width': (displaywidth - sumlength) / (ncols - 1) if (ncols - 1) else 0,
- 'max_rows': max_rows,
- 'column_widths': col_widths
- }
-
-
-def _get_or_default(mylist, i, default=None):
- """return list item number, or default if don't exist"""
- if i >= len(mylist):
- return default
- else :
- return mylist[i]
-
-
-def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) :
- """Returns a nested list, and info to columnize items
-
- Parameters
- ----------
-
- items
- list of strings to columize
- row_first : (default False)
- Whether to compute columns for a row-first matrix instead of
- column-first (default).
- empty : (default None)
- default value to fill list if needed
- separator_size : int (default=2)
- How much caracters will be used as a separation between each columns.
- displaywidth : int (default=80)
- The width of the area onto wich the columns should enter
-
- Returns
- -------
-
- strings_matrix
-
- nested list of string, the outer most list contains as many list as
- rows, the innermost lists have each as many element as colums. If the
- total number of elements in `items` does not equal the product of
- rows*columns, the last element of some lists are filled with `None`.
-
- dict_info
- some info to make columnize easier:
-
- num_columns
- number of columns
- max_rows
- maximum number of rows (final number may be less)
- column_widths
- list of with of each columns
- optimal_separator_width
- best separator width between columns
-
- Examples
- --------
- ::
-
- In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l']
- ...: compute_item_matrix(l, displaywidth=12)
- Out[1]:
- ([['aaa', 'f', 'k'],
- ['b', 'g', 'l'],
- ['cc', 'h', None],
- ['d', 'i', None],
- ['eeeee', 'j', None]],
- {'num_columns': 3,
- 'column_widths': [5, 1, 1],
- 'optimal_separator_width': 2,
- 'max_rows': 5})
- """
- info = _find_optimal(list(map(len, items)), row_first, *args, **kwargs)
- nrow, ncol = info['max_rows'], info['num_columns']
- if row_first:
- return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info)
- else:
- return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info)
-
-
-def columnize(items, row_first=False, separator=' ', displaywidth=80, spread=False):
- """ Transform a list of strings into a single string with columns.
-
- Parameters
- ----------
- items : sequence of strings
- The strings to process.
-
- row_first : (default False)
- Whether to compute columns for a row-first matrix instead of
- column-first (default).
-
- separator : str, optional [default is two spaces]
- The string that separates columns.
-
- displaywidth : int, optional [default is 80]
- Width of the display in number of characters.
-
- Returns
- -------
- The formatted string.
- """
- if not items:
- return '\n'
- matrix, info = compute_item_matrix(items, row_first=row_first, separator_size=len(separator), displaywidth=displaywidth)
- if spread:
- separator = separator.ljust(int(info['optimal_separator_width']))
- fmatrix = [filter(None, x) for x in matrix]
- sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['column_widths'])])
- return '\n'.join(map(sjoin, fmatrix))+'\n'
-
-
-def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""):
- """
- Return a string with a natural enumeration of items
-
- >>> get_text_list(['a', 'b', 'c', 'd'])
- 'a, b, c and d'
- >>> get_text_list(['a', 'b', 'c'], ' or ')
- 'a, b or c'
- >>> get_text_list(['a', 'b', 'c'], ', ')
- 'a, b, c'
- >>> get_text_list(['a', 'b'], ' or ')
- 'a or b'
- >>> get_text_list(['a'])
- 'a'
- >>> get_text_list([])
- ''
- >>> get_text_list(['a', 'b'], wrap_item_with="`")
- '`a` and `b`'
- >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ")
- 'a + b + c = d'
- """
- if len(list_) == 0:
- return ''
- if wrap_item_with:
- list_ = ['%s%s%s' % (wrap_item_with, item, wrap_item_with) for
- item in list_]
- if len(list_) == 1:
- return list_[0]
- return '%s%s%s' % (
- sep.join(i for i in list_[:-1]),
- last_sep, list_[-1])
+ return self.__paths
+
+ p = paths = property(get_paths)
+
+ def grep(self, pattern, prune = False, field = None):
+ """ Return all strings matching 'pattern' (a regex or callable)
+
+ This is case-insensitive. If prune is true, return all items
+ NOT matching the pattern.
+
+ If field is specified, the match must occur in the specified
+ whitespace-separated field.
+
+ Examples::
+
+ a.grep( lambda x: x.startswith('C') )
+ a.grep('Cha.*log', prune=1)
+ a.grep('chm', field=-1)
+ """
+
+ def match_target(s):
+ if field is None:
+ return s
+ parts = s.split()
+ try:
+ tgt = parts[field]
+ return tgt
+ except IndexError:
+ return ""
+
+ if isinstance(pattern, py3compat.string_types):
+ pred = lambda x : re.search(pattern, x, re.IGNORECASE)
+ else:
+ pred = pattern
+ if not prune:
+ return SList([el for el in self if pred(match_target(el))])
+ else:
+ return SList([el for el in self if not pred(match_target(el))])
+
+ def fields(self, *fields):
+ """ Collect whitespace-separated fields from string list
+
+ Allows quick awk-like usage of string lists.
+
+ Example data (in var a, created by 'a = !ls -l')::
+
+ -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
+ drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
+
+ * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']``
+ * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']``
+ (note the joining by space).
+ * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']``
+
+ IndexErrors are ignored.
+
+ Without args, fields() just split()'s the strings.
+ """
+ if len(fields) == 0:
+ return [el.split() for el in self]
+
+ res = SList()
+ for el in [f.split() for f in self]:
+ lineparts = []
+
+ for fd in fields:
+ try:
+ lineparts.append(el[fd])
+ except IndexError:
+ pass
+ if lineparts:
+ res.append(" ".join(lineparts))
+
+ return res
+
+ def sort(self,field= None, nums = False):
+ """ sort by specified fields (see fields())
+
+ Example::
+
+ a.sort(1, nums = True)
+
+ Sorts a by second field, in numerical order (so that 21 > 3)
+
+ """
+
+ #decorate, sort, undecorate
+ if field is not None:
+ dsu = [[SList([line]).fields(field), line] for line in self]
+ else:
+ dsu = [[line, line] for line in self]
+ if nums:
+ for i in range(len(dsu)):
+ numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
+ try:
+ n = int(numstr)
+ except ValueError:
+ n = 0
+ dsu[i][0] = n
+
+
+ dsu.sort()
+ return SList([t[1] for t in dsu])
+
+
+# FIXME: We need to reimplement type specific displayhook and then add this
+# back as a custom printer. This should also be moved outside utils into the
+# core.
+
+# def print_slist(arg):
+# """ Prettier (non-repr-like) and more informative printer for SList """
+# print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
+# if hasattr(arg, 'hideonce') and arg.hideonce:
+# arg.hideonce = False
+# return
+#
+# nlprint(arg) # This was a nested list printer, now removed.
+#
+# print_slist = result_display.when_type(SList)(print_slist)
+
+
+def indent(instr,nspaces=4, ntabs=0, flatten=False):
+ """Indent a string a given number of spaces or tabstops.
+
+ indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
+
+ Parameters
+ ----------
+
+ instr : basestring
+ The string to be indented.
+ nspaces : int (default: 4)
+ The number of spaces to be indented.
+ ntabs : int (default: 0)
+ The number of tabs to be indented.
+ flatten : bool (default: False)
+ Whether to scrub existing indentation. If True, all lines will be
+ aligned to the same indentation. If False, existing indentation will
+ be strictly increased.
+
+ Returns
+ -------
+
+ str|unicode : string indented by ntabs and nspaces.
+
+ """
+ if instr is None:
+ return
+ ind = '\t'*ntabs+' '*nspaces
+ if flatten:
+ pat = re.compile(r'^\s*', re.MULTILINE)
+ else:
+ pat = re.compile(r'^', re.MULTILINE)
+ outstr = re.sub(pat, ind, instr)
+ if outstr.endswith(os.linesep+ind):
+ return outstr[:-len(ind)]
+ else:
+ return outstr
+
+
+def list_strings(arg):
+ """Always return a list of strings, given a string or list of strings
+ as input.
+
+ Examples
+ --------
+ ::
+
+ In [7]: list_strings('A single string')
+ Out[7]: ['A single string']
+
+ In [8]: list_strings(['A single string in a list'])
+ Out[8]: ['A single string in a list']
+
+ In [9]: list_strings(['A','list','of','strings'])
+ Out[9]: ['A', 'list', 'of', 'strings']
+ """
+
+ if isinstance(arg, py3compat.string_types): return [arg]
+ else: return arg
+
+
+def marquee(txt='',width=78,mark='*'):
+ """Return the input string centered in a 'marquee'.
+
+ Examples
+ --------
+ ::
+
+ In [16]: marquee('A test',40)
+ Out[16]: '**************** A test ****************'
+
+ In [17]: marquee('A test',40,'-')
+ Out[17]: '---------------- A test ----------------'
+
+ In [18]: marquee('A test',40,' ')
+ Out[18]: ' A test '
+
+ """
+ if not txt:
+ return (mark*width)[:width]
+ nmark = (width-len(txt)-2)//len(mark)//2
+ if nmark < 0: nmark =0
+ marks = mark*nmark
+ return '%s %s %s' % (marks,txt,marks)
+
+
+ini_spaces_re = re.compile(r'^(\s+)')
+
+def num_ini_spaces(strng):
+ """Return the number of initial spaces in a string"""
+
+ ini_spaces = ini_spaces_re.match(strng)
+ if ini_spaces:
+ return ini_spaces.end()
+ else:
+ return 0
+
+
+def format_screen(strng):
+ """Format a string for screen printing.
+
+ This removes some latex-type format codes."""
+ # Paragraph continue
+ par_re = re.compile(r'\\$',re.MULTILINE)
+ strng = par_re.sub('',strng)
+ return strng
+
+
+def dedent(text):
+ """Equivalent of textwrap.dedent that ignores unindented first line.
+
+ This means it will still dedent strings like:
+ '''foo
+ is a bar
+ '''
+
+ For use in wrap_paragraphs.
+ """
+
+ if text.startswith('\n'):
+ # text starts with blank line, don't ignore the first line
+ return textwrap.dedent(text)
+
+ # split first line
+ splits = text.split('\n',1)
+ if len(splits) == 1:
+ # only one line
+ return textwrap.dedent(text)
+
+ first, rest = splits
+ # dedent everything but the first line
+ rest = textwrap.dedent(rest)
+ return '\n'.join([first, rest])
+
+
+def wrap_paragraphs(text, ncols=80):
+ """Wrap multiple paragraphs to fit a specified width.
+
+ This is equivalent to textwrap.wrap, but with support for multiple
+ paragraphs, as separated by empty lines.
+
+ Returns
+ -------
+
+ list of complete paragraphs, wrapped to fill `ncols` columns.
+ """
+ paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
+ text = dedent(text).strip()
+ paragraphs = paragraph_re.split(text)[::2] # every other entry is space
+ out_ps = []
+ indent_re = re.compile(r'\n\s+', re.MULTILINE)
+ for p in paragraphs:
+ # presume indentation that survives dedent is meaningful formatting,
+ # so don't fill unless text is flush.
+ if indent_re.search(p) is None:
+ # wrap paragraph
+ p = textwrap.fill(p, ncols)
+ out_ps.append(p)
+ return out_ps
+
+
+def long_substr(data):
+ """Return the longest common substring in a list of strings.
+
+ Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python
+ """
+ substr = ''
+ if len(data) > 1 and len(data[0]) > 0:
+ for i in range(len(data[0])):
+ for j in range(len(data[0])-i+1):
+ if j > len(substr) and all(data[0][i:i+j] in x for x in data):
+ substr = data[0][i:i+j]
+ elif len(data) == 1:
+ substr = data[0]
+ return substr
+
+
+def strip_email_quotes(text):
+ """Strip leading email quotation characters ('>').
+
+ Removes any combination of leading '>' interspersed with whitespace that
+ appears *identically* in all lines of the input text.
+
+ Parameters
+ ----------
+ text : str
+
+ Examples
+ --------
+
+ Simple uses::
+
+ In [2]: strip_email_quotes('> > text')
+ Out[2]: 'text'
+
+ In [3]: strip_email_quotes('> > text\\n> > more')
+ Out[3]: 'text\\nmore'
+
+ Note how only the common prefix that appears in all lines is stripped::
+
+ In [4]: strip_email_quotes('> > text\\n> > more\\n> more...')
+ Out[4]: '> text\\n> more\\nmore...'
+
+ So if any line has no quote marks ('>') , then none are stripped from any
+ of them ::
+
+ In [5]: strip_email_quotes('> > text\\n> > more\\nlast different')
+ Out[5]: '> > text\\n> > more\\nlast different'
+ """
+ lines = text.splitlines()
+ matches = set()
+ for line in lines:
+ prefix = re.match(r'^(\s*>[ >]*)', line)
+ if prefix:
+ matches.add(prefix.group(1))
+ else:
+ break
+ else:
+ prefix = long_substr(list(matches))
+ if prefix:
+ strip = len(prefix)
+ text = '\n'.join([ ln[strip:] for ln in lines])
+ return text
+
+def strip_ansi(source):
+ """
+ Remove ansi escape codes from text.
+
+ Parameters
+ ----------
+ source : str
+ Source to remove the ansi from
+ """
+ return re.sub(r'\033\[(\d|;)+?m', '', source)
+
+
+class EvalFormatter(Formatter):
+ """A String Formatter that allows evaluation of simple expressions.
+
+ Note that this version interprets a : as specifying a format string (as per
+ standard string formatting), so if slicing is required, you must explicitly
+ create a slice.
+
+ This is to be used in templating cases, such as the parallel batch
+ script templates, where simple arithmetic on arguments is useful.
+
+ Examples
+ --------
+ ::
+
+ In [1]: f = EvalFormatter()
+ In [2]: f.format('{n//4}', n=8)
+ Out[2]: '2'
+
+ In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello")
+ Out[3]: 'll'
+ """
+ def get_field(self, name, args, kwargs):
+ v = eval(name, kwargs)
+ return v, name
+
+#XXX: As of Python 3.4, the format string parsing no longer splits on a colon
+# inside [], so EvalFormatter can handle slicing. Once we only support 3.4 and
+# above, it should be possible to remove FullEvalFormatter.
+
+@skip_doctest_py3
+class FullEvalFormatter(Formatter):
+ """A String Formatter that allows evaluation of simple expressions.
+
+ Any time a format key is not found in the kwargs,
+ it will be tried as an expression in the kwargs namespace.
+
+ Note that this version allows slicing using [1:2], so you cannot specify
+ a format string. Use :class:`EvalFormatter` to permit format strings.
+
+ Examples
+ --------
+ ::
+
+ In [1]: f = FullEvalFormatter()
+ In [2]: f.format('{n//4}', n=8)
+ Out[2]: u'2'
+
+ In [3]: f.format('{list(range(5))[2:4]}')
+ Out[3]: u'[2, 3]'
+
+ In [4]: f.format('{3*2}')
+ Out[4]: u'6'
+ """
+ # copied from Formatter._vformat with minor changes to allow eval
+ # and replace the format_spec code with slicing
+ def vformat(self, format_string, args, kwargs):
+ result = []
+ for literal_text, field_name, format_spec, conversion in \
+ self.parse(format_string):
+
+ # output the literal text
+ if literal_text:
+ result.append(literal_text)
+
+ # if there's a field, output it
+ if field_name is not None:
+ # this is some markup, find the object and do
+ # the formatting
+
+ if format_spec:
+ # override format spec, to allow slicing:
+ field_name = ':'.join([field_name, format_spec])
+
+ # eval the contents of the field for the object
+ # to be formatted
+ obj = eval(field_name, kwargs)
+
+ # do any conversion on the resulting object
+ obj = self.convert_field(obj, conversion)
+
+ # format the object and append to the result
+ result.append(self.format_field(obj, ''))
+
+ return u''.join(py3compat.cast_unicode(s) for s in result)
+
+
+@skip_doctest_py3
+class DollarFormatter(FullEvalFormatter):
+ """Formatter allowing Itpl style $foo replacement, for names and attribute
+ access only. Standard {foo} replacement also works, and allows full
+ evaluation of its arguments.
+
+ Examples
+ --------
+ ::
+
+ In [1]: f = DollarFormatter()
+ In [2]: f.format('{n//4}', n=8)
+ Out[2]: u'2'
+
+ In [3]: f.format('23 * 76 is $result', result=23*76)
+ Out[3]: u'23 * 76 is 1748'
+
+ In [4]: f.format('$a or {b}', a=1, b=2)
+ Out[4]: u'1 or 2'
+ """
+ _dollar_pattern = re.compile("(.*?)\$(\$?[\w\.]+)")
+ def parse(self, fmt_string):
+ for literal_txt, field_name, format_spec, conversion \
+ in Formatter.parse(self, fmt_string):
+
+ # Find $foo patterns in the literal text.
+ continue_from = 0
+ txt = ""
+ for m in self._dollar_pattern.finditer(literal_txt):
+ new_txt, new_field = m.group(1,2)
+ # $$foo --> $foo
+ if new_field.startswith("$"):
+ txt += new_txt + new_field
+ else:
+ yield (txt + new_txt, new_field, "", None)
+ txt = ""
+ continue_from = m.end()
+
+ # Re-yield the {foo} style pattern
+ yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion)
+
+#-----------------------------------------------------------------------------
+# Utils to columnize a list of string
+#-----------------------------------------------------------------------------
+
+def _col_chunks(l, max_rows, row_first=False):
+ """Yield successive max_rows-sized column chunks from l."""
+ if row_first:
+ ncols = (len(l) // max_rows) + (len(l) % max_rows > 0)
+ for i in py3compat.xrange(ncols):
+ yield [l[j] for j in py3compat.xrange(i, len(l), ncols)]
+ else:
+ for i in py3compat.xrange(0, len(l), max_rows):
+ yield l[i:(i + max_rows)]
+
+
+def _find_optimal(rlist, row_first=False, separator_size=2, displaywidth=80):
+ """Calculate optimal info to columnize a list of string"""
+ for max_rows in range(1, len(rlist) + 1):
+ col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first)))
+ sumlength = sum(col_widths)
+ ncols = len(col_widths)
+ if sumlength + separator_size * (ncols - 1) <= displaywidth:
+ break
+ return {'num_columns': ncols,
+ 'optimal_separator_width': (displaywidth - sumlength) / (ncols - 1) if (ncols - 1) else 0,
+ 'max_rows': max_rows,
+ 'column_widths': col_widths
+ }
+
+
+def _get_or_default(mylist, i, default=None):
+ """return list item number, or default if don't exist"""
+ if i >= len(mylist):
+ return default
+ else :
+ return mylist[i]
+
+
+def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) :
+ """Returns a nested list, and info to columnize items
+
+ Parameters
+ ----------
+
+ items
+ list of strings to columize
+ row_first : (default False)
+ Whether to compute columns for a row-first matrix instead of
+ column-first (default).
+ empty : (default None)
+ default value to fill list if needed
+ separator_size : int (default=2)
+ How much caracters will be used as a separation between each columns.
+ displaywidth : int (default=80)
+ The width of the area onto wich the columns should enter
+
+ Returns
+ -------
+
+ strings_matrix
+
+ nested list of string, the outer most list contains as many list as
+ rows, the innermost lists have each as many element as colums. If the
+ total number of elements in `items` does not equal the product of
+ rows*columns, the last element of some lists are filled with `None`.
+
+ dict_info
+ some info to make columnize easier:
+
+ num_columns
+ number of columns
+ max_rows
+ maximum number of rows (final number may be less)
+ column_widths
+ list of with of each columns
+ optimal_separator_width
+ best separator width between columns
+
+ Examples
+ --------
+ ::
+
+ In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l']
+ ...: compute_item_matrix(l, displaywidth=12)
+ Out[1]:
+ ([['aaa', 'f', 'k'],
+ ['b', 'g', 'l'],
+ ['cc', 'h', None],
+ ['d', 'i', None],
+ ['eeeee', 'j', None]],
+ {'num_columns': 3,
+ 'column_widths': [5, 1, 1],
+ 'optimal_separator_width': 2,
+ 'max_rows': 5})
+ """
+ info = _find_optimal(list(map(len, items)), row_first, *args, **kwargs)
+ nrow, ncol = info['max_rows'], info['num_columns']
+ if row_first:
+ return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info)
+ else:
+ return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info)
+
+
+def columnize(items, row_first=False, separator=' ', displaywidth=80, spread=False):
+ """ Transform a list of strings into a single string with columns.
+
+ Parameters
+ ----------
+ items : sequence of strings
+ The strings to process.
+
+ row_first : (default False)
+ Whether to compute columns for a row-first matrix instead of
+ column-first (default).
+
+ separator : str, optional [default is two spaces]
+ The string that separates columns.
+
+ displaywidth : int, optional [default is 80]
+ Width of the display in number of characters.
+
+ Returns
+ -------
+ The formatted string.
+ """
+ if not items:
+ return '\n'
+ matrix, info = compute_item_matrix(items, row_first=row_first, separator_size=len(separator), displaywidth=displaywidth)
+ if spread:
+ separator = separator.ljust(int(info['optimal_separator_width']))
+ fmatrix = [filter(None, x) for x in matrix]
+ sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['column_widths'])])
+ return '\n'.join(map(sjoin, fmatrix))+'\n'
+
+
+def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""):
+ """
+ Return a string with a natural enumeration of items
+
+ >>> get_text_list(['a', 'b', 'c', 'd'])
+ 'a, b, c and d'
+ >>> get_text_list(['a', 'b', 'c'], ' or ')
+ 'a, b or c'
+ >>> get_text_list(['a', 'b', 'c'], ', ')
+ 'a, b, c'
+ >>> get_text_list(['a', 'b'], ' or ')
+ 'a or b'
+ >>> get_text_list(['a'])
+ 'a'
+ >>> get_text_list([])
+ ''
+ >>> get_text_list(['a', 'b'], wrap_item_with="`")
+ '`a` and `b`'
+ >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ")
+ 'a + b + c = d'
+ """
+ if len(list_) == 0:
+ return ''
+ if wrap_item_with:
+ list_ = ['%s%s%s' % (wrap_item_with, item, wrap_item_with) for
+ item in list_]
+ if len(list_) == 1:
+ return list_[0]
+ return '%s%s%s' % (
+ sep.join(i for i in list_[:-1]),
+ last_sep, list_[-1])
diff --git a/contrib/python/ipython/py2/IPython/utils/timing.py b/contrib/python/ipython/py2/IPython/utils/timing.py
index ff88bf664d..99b7bbc59a 100644
--- a/contrib/python/ipython/py2/IPython/utils/timing.py
+++ b/contrib/python/ipython/py2/IPython/utils/timing.py
@@ -1,118 +1,118 @@
-# encoding: utf-8
-"""
-Utilities for timing code execution.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import time
-
-from .py3compat import xrange
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-# If possible (Unix), use the resource module instead of time.clock()
-try:
- import resource
- def clocku():
- """clocku() -> floating point number
-
- Return the *USER* CPU time in seconds since the start of the process.
- This is done via a call to resource.getrusage, so it avoids the
- wraparound problems in time.clock()."""
-
- return resource.getrusage(resource.RUSAGE_SELF)[0]
-
- def clocks():
- """clocks() -> floating point number
-
- Return the *SYSTEM* CPU time in seconds since the start of the process.
- This is done via a call to resource.getrusage, so it avoids the
- wraparound problems in time.clock()."""
-
- return resource.getrusage(resource.RUSAGE_SELF)[1]
-
- def clock():
- """clock() -> floating point number
-
- Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
- the process. This is done via a call to resource.getrusage, so it
- avoids the wraparound problems in time.clock()."""
-
- u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
- return u+s
-
- def clock2():
- """clock2() -> (t_user,t_system)
-
- Similar to clock(), but return a tuple of user/system times."""
- return resource.getrusage(resource.RUSAGE_SELF)[:2]
-except ImportError:
- # There is no distinction of user/system time under windows, so we just use
- # time.clock() for everything...
- clocku = clocks = clock = time.clock
- def clock2():
- """Under windows, system CPU time can't be measured.
-
- This just returns clock() and zero."""
- return time.clock(),0.0
-
-
-def timings_out(reps,func,*args,**kw):
- """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
-
- Execute a function reps times, return a tuple with the elapsed total
- CPU time in seconds, the time per call and the function's output.
-
- Under Unix, the return value is the sum of user+system time consumed by
- the process, computed via the resource module. This prevents problems
- related to the wraparound effect which the time.clock() function has.
-
- Under Windows the return value is in wall clock seconds. See the
- documentation for the time module for more details."""
-
- reps = int(reps)
- assert reps >=1, 'reps must be >= 1'
- if reps==1:
- start = clock()
- out = func(*args,**kw)
- tot_time = clock()-start
- else:
- rng = xrange(reps-1) # the last time is executed separately to store output
- start = clock()
- for dummy in rng: func(*args,**kw)
- out = func(*args,**kw) # one last time
- tot_time = clock()-start
- av_time = tot_time / reps
- return tot_time,av_time,out
-
-
-def timings(reps,func,*args,**kw):
- """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
-
- Execute a function reps times, return a tuple with the elapsed total CPU
- time in seconds and the time per call. These are just the first two values
- in timings_out()."""
-
- return timings_out(reps,func,*args,**kw)[0:2]
-
-
-def timing(func,*args,**kw):
- """timing(func,*args,**kw) -> t_total
-
- Execute a function once, return the elapsed total CPU time in
- seconds. This is just the first value in timings_out()."""
-
- return timings_out(1,func,*args,**kw)[0]
-
+# encoding: utf-8
+"""
+Utilities for timing code execution.
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2008-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import time
+
+from .py3compat import xrange
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+# If possible (Unix), use the resource module instead of time.clock()
+try:
+ import resource
+ def clocku():
+ """clocku() -> floating point number
+
+ Return the *USER* CPU time in seconds since the start of the process.
+ This is done via a call to resource.getrusage, so it avoids the
+ wraparound problems in time.clock()."""
+
+ return resource.getrusage(resource.RUSAGE_SELF)[0]
+
+ def clocks():
+ """clocks() -> floating point number
+
+ Return the *SYSTEM* CPU time in seconds since the start of the process.
+ This is done via a call to resource.getrusage, so it avoids the
+ wraparound problems in time.clock()."""
+
+ return resource.getrusage(resource.RUSAGE_SELF)[1]
+
+ def clock():
+ """clock() -> floating point number
+
+ Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
+ the process. This is done via a call to resource.getrusage, so it
+ avoids the wraparound problems in time.clock()."""
+
+ u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
+ return u+s
+
+ def clock2():
+ """clock2() -> (t_user,t_system)
+
+ Similar to clock(), but return a tuple of user/system times."""
+ return resource.getrusage(resource.RUSAGE_SELF)[:2]
+except ImportError:
+ # There is no distinction of user/system time under windows, so we just use
+ # time.clock() for everything...
+ clocku = clocks = clock = time.clock
+ def clock2():
+ """Under windows, system CPU time can't be measured.
+
+ This just returns clock() and zero."""
+ return time.clock(),0.0
+
+
+def timings_out(reps,func,*args,**kw):
+ """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
+
+ Execute a function reps times, return a tuple with the elapsed total
+ CPU time in seconds, the time per call and the function's output.
+
+ Under Unix, the return value is the sum of user+system time consumed by
+ the process, computed via the resource module. This prevents problems
+ related to the wraparound effect which the time.clock() function has.
+
+ Under Windows the return value is in wall clock seconds. See the
+ documentation for the time module for more details."""
+
+ reps = int(reps)
+ assert reps >=1, 'reps must be >= 1'
+ if reps==1:
+ start = clock()
+ out = func(*args,**kw)
+ tot_time = clock()-start
+ else:
+ rng = xrange(reps-1) # the last time is executed separately to store output
+ start = clock()
+ for dummy in rng: func(*args,**kw)
+ out = func(*args,**kw) # one last time
+ tot_time = clock()-start
+ av_time = tot_time / reps
+ return tot_time,av_time,out
+
+
+def timings(reps,func,*args,**kw):
+ """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
+
+ Execute a function reps times, return a tuple with the elapsed total CPU
+ time in seconds and the time per call. These are just the first two values
+ in timings_out()."""
+
+ return timings_out(reps,func,*args,**kw)[0:2]
+
+
+def timing(func,*args,**kw):
+ """timing(func,*args,**kw) -> t_total
+
+ Execute a function once, return the elapsed total CPU time in
+ seconds. This is just the first value in timings_out()."""
+
+ return timings_out(1,func,*args,**kw)[0]
+
diff --git a/contrib/python/ipython/py2/IPython/utils/tokenize2.py b/contrib/python/ipython/py2/IPython/utils/tokenize2.py
index 7e60a8a629..cbb5292e5a 100644
--- a/contrib/python/ipython/py2/IPython/utils/tokenize2.py
+++ b/contrib/python/ipython/py2/IPython/utils/tokenize2.py
@@ -1,9 +1,9 @@
-"""Load our patched versions of tokenize.
-"""
-
-import sys
-
-if sys.version_info[0] >= 3:
- from ._tokenize_py3 import *
-else:
- from ._tokenize_py2 import *
+"""Load our patched versions of tokenize.
+"""
+
+import sys
+
+if sys.version_info[0] >= 3:
+ from ._tokenize_py3 import *
+else:
+ from ._tokenize_py2 import *
diff --git a/contrib/python/ipython/py2/IPython/utils/tokenutil.py b/contrib/python/ipython/py2/IPython/utils/tokenutil.py
index 940da98d3d..f52d3b7658 100644
--- a/contrib/python/ipython/py2/IPython/utils/tokenutil.py
+++ b/contrib/python/ipython/py2/IPython/utils/tokenutil.py
@@ -1,128 +1,128 @@
-"""Token-related utilities"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import absolute_import, print_function
-
-from collections import namedtuple
-from io import StringIO
-from keyword import iskeyword
-
-from . import tokenize2
-from .py3compat import cast_unicode_py2
-
-Token = namedtuple('Token', ['token', 'text', 'start', 'end', 'line'])
-
-def generate_tokens(readline):
- """wrap generate_tokens to catch EOF errors"""
- try:
- for token in tokenize2.generate_tokens(readline):
- yield token
- except tokenize2.TokenError:
- # catch EOF error
- return
-
-def line_at_cursor(cell, cursor_pos=0):
- """Return the line in a cell at a given cursor position
-
- Used for calling line-based APIs that don't support multi-line input, yet.
-
- Parameters
- ----------
-
+"""Token-related utilities"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import absolute_import, print_function
+
+from collections import namedtuple
+from io import StringIO
+from keyword import iskeyword
+
+from . import tokenize2
+from .py3compat import cast_unicode_py2
+
+Token = namedtuple('Token', ['token', 'text', 'start', 'end', 'line'])
+
+def generate_tokens(readline):
+ """wrap generate_tokens to catch EOF errors"""
+ try:
+ for token in tokenize2.generate_tokens(readline):
+ yield token
+ except tokenize2.TokenError:
+ # catch EOF error
+ return
+
+def line_at_cursor(cell, cursor_pos=0):
+ """Return the line in a cell at a given cursor position
+
+ Used for calling line-based APIs that don't support multi-line input, yet.
+
+ Parameters
+ ----------
+
cell: str
- multiline block of text
- cursor_pos: integer
- the cursor position
-
- Returns
- -------
-
- (line, offset): (text, integer)
- The line with the current cursor, and the character offset of the start of the line.
- """
- offset = 0
- lines = cell.splitlines(True)
- for line in lines:
- next_offset = offset + len(line)
- if next_offset >= cursor_pos:
- break
- offset = next_offset
- else:
- line = ""
- return (line, offset)
-
-def token_at_cursor(cell, cursor_pos=0):
- """Get the token at a given cursor
-
- Used for introspection.
-
- Function calls are prioritized, so the token for the callable will be returned
- if the cursor is anywhere inside the call.
-
- Parameters
- ----------
-
- cell : unicode
- A block of Python code
- cursor_pos : int
- The location of the cursor in the block where the token should be found
- """
- cell = cast_unicode_py2(cell)
- names = []
- tokens = []
- call_names = []
-
- offsets = {1: 0} # lines start at 1
- for tup in generate_tokens(StringIO(cell).readline):
-
- tok = Token(*tup)
-
- # token, text, start, end, line = tup
- start_line, start_col = tok.start
- end_line, end_col = tok.end
- if end_line + 1 not in offsets:
- # keep track of offsets for each line
- lines = tok.line.splitlines(True)
- for lineno, line in zip(range(start_line + 1, end_line + 2), lines):
- if lineno not in offsets:
- offsets[lineno] = offsets[lineno-1] + len(line)
-
- offset = offsets[start_line]
- # allow '|foo' to find 'foo' at the beginning of a line
- boundary = cursor_pos + 1 if start_col == 0 else cursor_pos
- if offset + start_col >= boundary:
- # current token starts after the cursor,
- # don't consume it
- break
-
- if tok.token == tokenize2.NAME and not iskeyword(tok.text):
- if names and tokens and tokens[-1].token == tokenize2.OP and tokens[-1].text == '.':
- names[-1] = "%s.%s" % (names[-1], tok.text)
- else:
- names.append(tok.text)
- elif tok.token == tokenize2.OP:
- if tok.text == '=' and names:
- # don't inspect the lhs of an assignment
- names.pop(-1)
- if tok.text == '(' and names:
- # if we are inside a function call, inspect the function
- call_names.append(names[-1])
- elif tok.text == ')' and call_names:
- call_names.pop(-1)
-
- tokens.append(tok)
-
- if offsets[end_line] + end_col > cursor_pos:
- # we found the cursor, stop reading
- break
-
- if call_names:
- return call_names[-1]
- elif names:
- return names[-1]
- else:
- return ''
-
-
+ multiline block of text
+ cursor_pos: integer
+ the cursor position
+
+ Returns
+ -------
+
+ (line, offset): (text, integer)
+ The line with the current cursor, and the character offset of the start of the line.
+ """
+ offset = 0
+ lines = cell.splitlines(True)
+ for line in lines:
+ next_offset = offset + len(line)
+ if next_offset >= cursor_pos:
+ break
+ offset = next_offset
+ else:
+ line = ""
+ return (line, offset)
+
+def token_at_cursor(cell, cursor_pos=0):
+ """Get the token at a given cursor
+
+ Used for introspection.
+
+ Function calls are prioritized, so the token for the callable will be returned
+ if the cursor is anywhere inside the call.
+
+ Parameters
+ ----------
+
+ cell : unicode
+ A block of Python code
+ cursor_pos : int
+ The location of the cursor in the block where the token should be found
+ """
+ cell = cast_unicode_py2(cell)
+ names = []
+ tokens = []
+ call_names = []
+
+ offsets = {1: 0} # lines start at 1
+ for tup in generate_tokens(StringIO(cell).readline):
+
+ tok = Token(*tup)
+
+ # token, text, start, end, line = tup
+ start_line, start_col = tok.start
+ end_line, end_col = tok.end
+ if end_line + 1 not in offsets:
+ # keep track of offsets for each line
+ lines = tok.line.splitlines(True)
+ for lineno, line in zip(range(start_line + 1, end_line + 2), lines):
+ if lineno not in offsets:
+ offsets[lineno] = offsets[lineno-1] + len(line)
+
+ offset = offsets[start_line]
+ # allow '|foo' to find 'foo' at the beginning of a line
+ boundary = cursor_pos + 1 if start_col == 0 else cursor_pos
+ if offset + start_col >= boundary:
+ # current token starts after the cursor,
+ # don't consume it
+ break
+
+ if tok.token == tokenize2.NAME and not iskeyword(tok.text):
+ if names and tokens and tokens[-1].token == tokenize2.OP and tokens[-1].text == '.':
+ names[-1] = "%s.%s" % (names[-1], tok.text)
+ else:
+ names.append(tok.text)
+ elif tok.token == tokenize2.OP:
+ if tok.text == '=' and names:
+ # don't inspect the lhs of an assignment
+ names.pop(-1)
+ if tok.text == '(' and names:
+ # if we are inside a function call, inspect the function
+ call_names.append(names[-1])
+ elif tok.text == ')' and call_names:
+ call_names.pop(-1)
+
+ tokens.append(tok)
+
+ if offsets[end_line] + end_col > cursor_pos:
+ # we found the cursor, stop reading
+ break
+
+ if call_names:
+ return call_names[-1]
+ elif names:
+ return names[-1]
+ else:
+ return ''
+
+
diff --git a/contrib/python/ipython/py2/IPython/utils/traitlets.py b/contrib/python/ipython/py2/IPython/utils/traitlets.py
index 0ff664fb5c..b4ff7a2689 100644
--- a/contrib/python/ipython/py2/IPython/utils/traitlets.py
+++ b/contrib/python/ipython/py2/IPython/utils/traitlets.py
@@ -1,7 +1,7 @@
-from __future__ import absolute_import
-
-from warnings import warn
-
-warn("IPython.utils.traitlets has moved to a top-level traitlets package.")
-
-from traitlets import *
+from __future__ import absolute_import
+
+from warnings import warn
+
+warn("IPython.utils.traitlets has moved to a top-level traitlets package.")
+
+from traitlets import *
diff --git a/contrib/python/ipython/py2/IPython/utils/tz.py b/contrib/python/ipython/py2/IPython/utils/tz.py
index 14172b2f4a..b315d532d1 100644
--- a/contrib/python/ipython/py2/IPython/utils/tz.py
+++ b/contrib/python/ipython/py2/IPython/utils/tz.py
@@ -1,46 +1,46 @@
-# encoding: utf-8
-"""
-Timezone utilities
-
-Just UTC-awareness right now
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2013 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from datetime import tzinfo, timedelta, datetime
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-# constant for zero offset
-ZERO = timedelta(0)
-
-class tzUTC(tzinfo):
- """tzinfo object for UTC (zero offset)"""
-
- def utcoffset(self, d):
- return ZERO
-
- def dst(self, d):
- return ZERO
-
-UTC = tzUTC()
-
-def utc_aware(unaware):
- """decorator for adding UTC tzinfo to datetime's utcfoo methods"""
- def utc_method(*args, **kwargs):
- dt = unaware(*args, **kwargs)
- return dt.replace(tzinfo=UTC)
- return utc_method
-
-utcfromtimestamp = utc_aware(datetime.utcfromtimestamp)
-utcnow = utc_aware(datetime.utcnow)
+# encoding: utf-8
+"""
+Timezone utilities
+
+Just UTC-awareness right now
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2013 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+from datetime import tzinfo, timedelta, datetime
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+# constant for zero offset
+ZERO = timedelta(0)
+
+class tzUTC(tzinfo):
+ """tzinfo object for UTC (zero offset)"""
+
+ def utcoffset(self, d):
+ return ZERO
+
+ def dst(self, d):
+ return ZERO
+
+UTC = tzUTC()
+
+def utc_aware(unaware):
+ """decorator for adding UTC tzinfo to datetime's utcfoo methods"""
+ def utc_method(*args, **kwargs):
+ dt = unaware(*args, **kwargs)
+ return dt.replace(tzinfo=UTC)
+ return utc_method
+
+utcfromtimestamp = utc_aware(datetime.utcfromtimestamp)
+utcnow = utc_aware(datetime.utcnow)
diff --git a/contrib/python/ipython/py2/IPython/utils/ulinecache.py b/contrib/python/ipython/py2/IPython/utils/ulinecache.py
index 886454c267..f53b0dde69 100644
--- a/contrib/python/ipython/py2/IPython/utils/ulinecache.py
+++ b/contrib/python/ipython/py2/IPython/utils/ulinecache.py
@@ -1,45 +1,45 @@
-"""Wrapper around linecache which decodes files to unicode according to PEP 263.
-
-This is only needed for Python 2 - linecache in Python 3 does the same thing
-itself.
-"""
-import functools
-import linecache
-import sys
-
-from IPython.utils import py3compat
-from IPython.utils import openpy
-
-if py3compat.PY3:
- getline = linecache.getline
-
- # getlines has to be looked up at runtime, because doctests monkeypatch it.
- @functools.wraps(linecache.getlines)
- def getlines(filename, module_globals=None):
- return linecache.getlines(filename, module_globals=module_globals)
-
-else:
- def getlines(filename, module_globals=None):
- """Get the lines (as unicode) for a file from the cache.
- Update the cache if it doesn't contain an entry for this file already."""
- filename = py3compat.cast_bytes(filename, sys.getfilesystemencoding())
- lines = linecache.getlines(filename, module_globals=module_globals)
-
- # The bits we cache ourselves can be unicode.
- if (not lines) or isinstance(lines[0], py3compat.unicode_type):
- return lines
-
- readline = openpy._list_readline(lines)
- try:
- encoding, _ = openpy.detect_encoding(readline)
- except SyntaxError:
- encoding = 'ascii'
- return [l.decode(encoding, 'replace') for l in lines]
-
- # This is a straight copy of linecache.getline
- def getline(filename, lineno, module_globals=None):
- lines = getlines(filename, module_globals)
- if 1 <= lineno <= len(lines):
- return lines[lineno-1]
- else:
- return ''
+"""Wrapper around linecache which decodes files to unicode according to PEP 263.
+
+This is only needed for Python 2 - linecache in Python 3 does the same thing
+itself.
+"""
+import functools
+import linecache
+import sys
+
+from IPython.utils import py3compat
+from IPython.utils import openpy
+
+if py3compat.PY3:
+ getline = linecache.getline
+
+ # getlines has to be looked up at runtime, because doctests monkeypatch it.
+ @functools.wraps(linecache.getlines)
+ def getlines(filename, module_globals=None):
+ return linecache.getlines(filename, module_globals=module_globals)
+
+else:
+ def getlines(filename, module_globals=None):
+ """Get the lines (as unicode) for a file from the cache.
+ Update the cache if it doesn't contain an entry for this file already."""
+ filename = py3compat.cast_bytes(filename, sys.getfilesystemencoding())
+ lines = linecache.getlines(filename, module_globals=module_globals)
+
+ # The bits we cache ourselves can be unicode.
+ if (not lines) or isinstance(lines[0], py3compat.unicode_type):
+ return lines
+
+ readline = openpy._list_readline(lines)
+ try:
+ encoding, _ = openpy.detect_encoding(readline)
+ except SyntaxError:
+ encoding = 'ascii'
+ return [l.decode(encoding, 'replace') for l in lines]
+
+ # This is a straight copy of linecache.getline
+ def getline(filename, lineno, module_globals=None):
+ lines = getlines(filename, module_globals)
+ if 1 <= lineno <= len(lines):
+ return lines[lineno-1]
+ else:
+ return ''
diff --git a/contrib/python/ipython/py2/IPython/utils/version.py b/contrib/python/ipython/py2/IPython/utils/version.py
index 3d1018f7bd..1de0047e6b 100644
--- a/contrib/python/ipython/py2/IPython/utils/version.py
+++ b/contrib/python/ipython/py2/IPython/utils/version.py
@@ -1,36 +1,36 @@
-# encoding: utf-8
-"""
-Utilities for version comparison
-
-It is a bit ridiculous that we need these.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2013 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from distutils.version import LooseVersion
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-def check_version(v, check):
- """check version string v >= check
-
- If dev/prerelease tags result in TypeError for string-number comparison,
- it is assumed that the dependency is satisfied.
- Users on dev branches are responsible for keeping their own packages up to date.
- """
- try:
- return LooseVersion(v) >= LooseVersion(check)
- except TypeError:
- return True
-
+# encoding: utf-8
+"""
+Utilities for version comparison
+
+It is a bit ridiculous that we need these.
+"""
+
+#-----------------------------------------------------------------------------
+# Copyright (C) 2013 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+from distutils.version import LooseVersion
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+def check_version(v, check):
+ """check version string v >= check
+
+ If dev/prerelease tags result in TypeError for string-number comparison,
+ it is assumed that the dependency is satisfied.
+ Users on dev branches are responsible for keeping their own packages up to date.
+ """
+ try:
+ return LooseVersion(v) >= LooseVersion(check)
+ except TypeError:
+ return True
+
diff --git a/contrib/python/ipython/py2/IPython/utils/warn.py b/contrib/python/ipython/py2/IPython/utils/warn.py
index 831e4265ac..dd4852227b 100644
--- a/contrib/python/ipython/py2/IPython/utils/warn.py
+++ b/contrib/python/ipython/py2/IPython/utils/warn.py
@@ -1,65 +1,65 @@
-# encoding: utf-8
-"""
-Utilities for warnings. Shoudn't we just use the built in warnings module.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
-import sys
+# encoding: utf-8
+"""
+Utilities for warnings. Shoudn't we just use the built in warnings module.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
+import sys
import warnings
-
+
warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
-
-def warn(msg,level=2,exit_val=1):
+
+def warn(msg,level=2,exit_val=1):
"""Deprecated
-
+
Standard warning printer. Gives formatting consistency.
-
+
Output is sent to sys.stderr.
- Options:
-
- -level(2): allows finer control:
- 0 -> Do nothing, dummy function.
- 1 -> Print message.
- 2 -> Print 'WARNING:' + message. (Default level).
- 3 -> Print 'ERROR:' + message.
- 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
-
- -exit_val (1): exit value returned by sys.exit() for a level 4
- warning. Ignored for all other levels."""
+ Options:
+
+ -level(2): allows finer control:
+ 0 -> Do nothing, dummy function.
+ 1 -> Print message.
+ 2 -> Print 'WARNING:' + message. (Default level).
+ 3 -> Print 'ERROR:' + message.
+ 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
+
+ -exit_val (1): exit value returned by sys.exit() for a level 4
+ warning. Ignored for all other levels."""
warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
- if level>0:
- header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
+ if level>0:
+ header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
print(header[level], msg, sep='', file=sys.stderr)
- if level == 4:
+ if level == 4:
print('Exiting.\n', file=sys.stderr)
- sys.exit(exit_val)
-
-
-def info(msg):
+ sys.exit(exit_val)
+
+
+def info(msg):
"""Deprecated
Equivalent to warn(msg,level=1)."""
-
- warn(msg,level=1)
-
-
-def error(msg):
+
+ warn(msg,level=1)
+
+
+def error(msg):
"""Deprecated
Equivalent to warn(msg,level=3)."""
-
- warn(msg,level=3)
-
-
-def fatal(msg,exit_val=1):
+
+ warn(msg,level=3)
+
+
+def fatal(msg,exit_val=1):
"""Deprecated
Equivalent to warn(msg,exit_val=exit_val,level=4)."""
-
- warn(msg,exit_val=exit_val,level=4)
+
+ warn(msg,exit_val=exit_val,level=4)
diff --git a/contrib/python/ipython/py2/IPython/utils/wildcard.py b/contrib/python/ipython/py2/IPython/utils/wildcard.py
index f8e895752c..d22491bd96 100644
--- a/contrib/python/ipython/py2/IPython/utils/wildcard.py
+++ b/contrib/python/ipython/py2/IPython/utils/wildcard.py
@@ -1,112 +1,112 @@
-# -*- coding: utf-8 -*-
-"""Support for wildcard pattern matching in object inspection.
-
-Authors
--------
-- Jörgen Stenarson <jorgen.stenarson@bostream.nu>
-- Thomas Kluyver
-"""
-
-#*****************************************************************************
-# Copyright (C) 2005 Jörgen Stenarson <jorgen.stenarson@bostream.nu>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#*****************************************************************************
-
-import re
-import types
-
-from IPython.utils.dir2 import dir2
-from .py3compat import iteritems
-
-def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
- """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
- objects from the types package, and vice versa."""
- typenamelist = [tname for tname in dir(types) if tname.endswith("Type")]
- typestr2type, type2typestr = {}, {}
-
- for tname in typenamelist:
- name = tname[:-4].lower() # Cut 'Type' off the end of the name
- obj = getattr(types, tname)
- typestr2type[name] = obj
- if name not in dont_include_in_type2typestr:
- type2typestr[obj] = name
- return typestr2type, type2typestr
-
-typestr2type, type2typestr = create_typestr2type_dicts()
-
-def is_type(obj, typestr_or_type):
- """is_type(obj, typestr_or_type) verifies if obj is of a certain type. It
- can take strings or actual python types for the second argument, i.e.
- 'tuple'<->TupleType. 'all' matches all types.
-
- TODO: Should be extended for choosing more than one type."""
- if typestr_or_type == "all":
- return True
- if type(typestr_or_type) == type:
- test_type = typestr_or_type
- else:
- test_type = typestr2type.get(typestr_or_type, False)
- if test_type:
- return isinstance(obj, test_type)
- return False
-
-def show_hidden(str, show_all=False):
- """Return true for strings starting with single _ if show_all is true."""
- return show_all or str.startswith("__") or not str.startswith("_")
-
-def dict_dir(obj):
- """Produce a dictionary of an object's attributes. Builds on dir2 by
- checking that a getattr() call actually succeeds."""
- ns = {}
- for key in dir2(obj):
- # This seemingly unnecessary try/except is actually needed
- # because there is code out there with metaclasses that
- # create 'write only' attributes, where a getattr() call
- # will fail even if the attribute appears listed in the
- # object's dictionary. Properties can actually do the same
- # thing. In particular, Traits use this pattern
- try:
- ns[key] = getattr(obj, key)
- except AttributeError:
- pass
- return ns
-
-def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True,
- show_all=True):
- """Filter a namespace dictionary by name pattern and item type."""
- pattern = name_pattern.replace("*",".*").replace("?",".")
- if ignore_case:
- reg = re.compile(pattern+"$", re.I)
- else:
- reg = re.compile(pattern+"$")
-
- # Check each one matches regex; shouldn't be hidden; of correct type.
- return dict((key,obj) for key, obj in iteritems(ns) if reg.match(key) \
- and show_hidden(key, show_all) \
- and is_type(obj, type_pattern) )
-
-def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False):
- """Return dictionary of all objects in a namespace dictionary that match
- type_pattern and filter."""
- pattern_list=filter.split(".")
- if len(pattern_list) == 1:
- return filter_ns(namespace, name_pattern=pattern_list[0],
- type_pattern=type_pattern,
- ignore_case=ignore_case, show_all=show_all)
- else:
- # This is where we can change if all objects should be searched or
- # only modules. Just change the type_pattern to module to search only
- # modules
- filtered = filter_ns(namespace, name_pattern=pattern_list[0],
- type_pattern="all",
- ignore_case=ignore_case, show_all=show_all)
- results = {}
- for name, obj in iteritems(filtered):
- ns = list_namespace(dict_dir(obj), type_pattern,
- ".".join(pattern_list[1:]),
- ignore_case=ignore_case, show_all=show_all)
- for inner_name, inner_obj in iteritems(ns):
- results["%s.%s"%(name,inner_name)] = inner_obj
- return results
+# -*- coding: utf-8 -*-
+"""Support for wildcard pattern matching in object inspection.
+
+Authors
+-------
+- Jörgen Stenarson <jorgen.stenarson@bostream.nu>
+- Thomas Kluyver
+"""
+
+#*****************************************************************************
+# Copyright (C) 2005 Jörgen Stenarson <jorgen.stenarson@bostream.nu>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#*****************************************************************************
+
+import re
+import types
+
+from IPython.utils.dir2 import dir2
+from .py3compat import iteritems
+
+def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
+ """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
+ objects from the types package, and vice versa."""
+ typenamelist = [tname for tname in dir(types) if tname.endswith("Type")]
+ typestr2type, type2typestr = {}, {}
+
+ for tname in typenamelist:
+ name = tname[:-4].lower() # Cut 'Type' off the end of the name
+ obj = getattr(types, tname)
+ typestr2type[name] = obj
+ if name not in dont_include_in_type2typestr:
+ type2typestr[obj] = name
+ return typestr2type, type2typestr
+
+typestr2type, type2typestr = create_typestr2type_dicts()
+
+def is_type(obj, typestr_or_type):
+ """is_type(obj, typestr_or_type) verifies if obj is of a certain type. It
+ can take strings or actual python types for the second argument, i.e.
+ 'tuple'<->TupleType. 'all' matches all types.
+
+ TODO: Should be extended for choosing more than one type."""
+ if typestr_or_type == "all":
+ return True
+ if type(typestr_or_type) == type:
+ test_type = typestr_or_type
+ else:
+ test_type = typestr2type.get(typestr_or_type, False)
+ if test_type:
+ return isinstance(obj, test_type)
+ return False
+
+def show_hidden(str, show_all=False):
+ """Return true for strings starting with single _ if show_all is true."""
+ return show_all or str.startswith("__") or not str.startswith("_")
+
+def dict_dir(obj):
+ """Produce a dictionary of an object's attributes. Builds on dir2 by
+ checking that a getattr() call actually succeeds."""
+ ns = {}
+ for key in dir2(obj):
+ # This seemingly unnecessary try/except is actually needed
+ # because there is code out there with metaclasses that
+ # create 'write only' attributes, where a getattr() call
+ # will fail even if the attribute appears listed in the
+ # object's dictionary. Properties can actually do the same
+ # thing. In particular, Traits use this pattern
+ try:
+ ns[key] = getattr(obj, key)
+ except AttributeError:
+ pass
+ return ns
+
+def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True,
+ show_all=True):
+ """Filter a namespace dictionary by name pattern and item type."""
+ pattern = name_pattern.replace("*",".*").replace("?",".")
+ if ignore_case:
+ reg = re.compile(pattern+"$", re.I)
+ else:
+ reg = re.compile(pattern+"$")
+
+ # Check each one matches regex; shouldn't be hidden; of correct type.
+ return dict((key,obj) for key, obj in iteritems(ns) if reg.match(key) \
+ and show_hidden(key, show_all) \
+ and is_type(obj, type_pattern) )
+
+def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False):
+ """Return dictionary of all objects in a namespace dictionary that match
+ type_pattern and filter."""
+ pattern_list=filter.split(".")
+ if len(pattern_list) == 1:
+ return filter_ns(namespace, name_pattern=pattern_list[0],
+ type_pattern=type_pattern,
+ ignore_case=ignore_case, show_all=show_all)
+ else:
+ # This is where we can change if all objects should be searched or
+ # only modules. Just change the type_pattern to module to search only
+ # modules
+ filtered = filter_ns(namespace, name_pattern=pattern_list[0],
+ type_pattern="all",
+ ignore_case=ignore_case, show_all=show_all)
+ results = {}
+ for name, obj in iteritems(filtered):
+ ns = list_namespace(dict_dir(obj), type_pattern,
+ ".".join(pattern_list[1:]),
+ ignore_case=ignore_case, show_all=show_all)
+ for inner_name, inner_obj in iteritems(ns):
+ results["%s.%s"%(name,inner_name)] = inner_obj
+ return results
diff --git a/contrib/python/ipython/py2/bin/ya.make b/contrib/python/ipython/py2/bin/ya.make
index c9d596dbae..0ff960df6f 100644
--- a/contrib/python/ipython/py2/bin/ya.make
+++ b/contrib/python/ipython/py2/bin/ya.make
@@ -1,11 +1,11 @@
PROGRAM(ipython)
-
+
OWNER(g:python-contrib borman nslus)
-
+
PEERDIR(
contrib/python/ipython
-)
-
+)
+
PY_MAIN(IPython:start_ipython)
-END()
+END()
diff --git a/contrib/python/ipython/ya.make b/contrib/python/ipython/ya.make
index d5058e7943..b1dd8c5e23 100644
--- a/contrib/python/ipython/ya.make
+++ b/contrib/python/ipython/ya.make
@@ -1,5 +1,5 @@
PY23_LIBRARY()
-
+
LICENSE(Service-Py23-Proxy)
OWNER(g:python-contrib)
@@ -12,7 +12,7 @@ ENDIF()
NO_LINT()
-END()
+END()
RECURSE(
py2
diff --git a/contrib/python/jedi/LICENSE.txt b/contrib/python/jedi/LICENSE.txt
index 06be7c0b0b..94f954567b 100644
--- a/contrib/python/jedi/LICENSE.txt
+++ b/contrib/python/jedi/LICENSE.txt
@@ -1,24 +1,24 @@
All contributions towards Jedi are MIT licensed.
-------------------------------------------------------------------------------
-The MIT License (MIT)
-
-Copyright (c) <2013> <David Halter and others, see AUTHORS.txt>
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
+The MIT License (MIT)
+
+Copyright (c) <2013> <David Halter and others, see AUTHORS.txt>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/contrib/python/jedi/jedi/__init__.py b/contrib/python/jedi/jedi/__init__.py
index 6f423b4ed8..d23739bee3 100644
--- a/contrib/python/jedi/jedi/__init__.py
+++ b/contrib/python/jedi/jedi/__init__.py
@@ -1,46 +1,46 @@
-"""
-Jedi is a static analysis tool for Python that can be used in IDEs/editors. Its
-historic focus is autocompletion, but does static analysis for now as well.
-Jedi is fast and is very well tested. It understands Python on a deeper level
-than all other static analysis frameworks for Python.
-
-Jedi has support for two different goto functions. It's possible to search for
-related names and to list all names in a Python file and infer them. Jedi
-understands docstrings and you can use Jedi autocompletion in your REPL as
-well.
-
-Jedi uses a very simple API to connect with IDE's. There's a reference
-implementation as a `VIM-Plugin <https://github.com/davidhalter/jedi-vim>`_,
-which uses Jedi's autocompletion. We encourage you to use Jedi in your IDEs.
-It's really easy.
-
-To give you a simple example how you can use the Jedi library, here is an
-example for the autocompletion feature:
-
->>> import jedi
->>> source = '''
-... import datetime
-... datetime.da'''
->>> script = jedi.Script(source, 3, len('datetime.da'), 'example.py')
->>> script
+"""
+Jedi is a static analysis tool for Python that can be used in IDEs/editors. Its
+historic focus is autocompletion, but does static analysis for now as well.
+Jedi is fast and is very well tested. It understands Python on a deeper level
+than all other static analysis frameworks for Python.
+
+Jedi has support for two different goto functions. It's possible to search for
+related names and to list all names in a Python file and infer them. Jedi
+understands docstrings and you can use Jedi autocompletion in your REPL as
+well.
+
+Jedi uses a very simple API to connect with IDE's. There's a reference
+implementation as a `VIM-Plugin <https://github.com/davidhalter/jedi-vim>`_,
+which uses Jedi's autocompletion. We encourage you to use Jedi in your IDEs.
+It's really easy.
+
+To give you a simple example how you can use the Jedi library, here is an
+example for the autocompletion feature:
+
+>>> import jedi
+>>> source = '''
+... import datetime
+... datetime.da'''
+>>> script = jedi.Script(source, 3, len('datetime.da'), 'example.py')
+>>> script
<Script: 'example.py' ...>
->>> completions = script.completions()
->>> completions #doctest: +ELLIPSIS
-[<Completion: date>, <Completion: datetime>, ...]
->>> print(completions[0].complete)
-te
->>> print(completions[0].name)
-date
-
-As you see Jedi is pretty simple and allows you to concentrate on writing a
-good text editor, while still having very good IDE features for Python.
-"""
-
+>>> completions = script.completions()
+>>> completions #doctest: +ELLIPSIS
+[<Completion: date>, <Completion: datetime>, ...]
+>>> print(completions[0].complete)
+te
+>>> print(completions[0].name)
+date
+
+As you see Jedi is pretty simple and allows you to concentrate on writing a
+good text editor, while still having very good IDE features for Python.
+"""
+
__version__ = '0.13.3'
-
+
from jedi.api import Script, Interpreter, set_debug_function, \
preload_module, names
-from jedi import settings
+from jedi import settings
from jedi.api.environment import find_virtualenvs, find_system_environments, \
get_default_environment, InvalidPythonEnvironment, create_environment, \
get_system_environment
diff --git a/contrib/python/jedi/jedi/__main__.py b/contrib/python/jedi/jedi/__main__.py
index 8498f90762..f2ee047769 100644
--- a/contrib/python/jedi/jedi/__main__.py
+++ b/contrib/python/jedi/jedi/__main__.py
@@ -1,43 +1,43 @@
import sys
-from os.path import join, dirname, abspath, isdir
-
-
+from os.path import join, dirname, abspath, isdir
+
+
def _start_linter():
- """
- This is a pre-alpha API. You're not supposed to use it at all, except for
- testing. It will very likely change.
- """
- import jedi
-
- if '--debug' in sys.argv:
- jedi.set_debug_function()
-
- for path in sys.argv[2:]:
- if path.startswith('--'):
- continue
- if isdir(path):
- import fnmatch
- import os
-
- paths = []
- for root, dirnames, filenames in os.walk(path):
- for filename in fnmatch.filter(filenames, '*.py'):
- paths.append(os.path.join(root, filename))
- else:
- paths = [path]
-
- try:
- for path in paths:
- for error in jedi.Script(path=path)._analysis():
- print(error)
- except Exception:
- if '--pdb' in sys.argv:
+ """
+ This is a pre-alpha API. You're not supposed to use it at all, except for
+ testing. It will very likely change.
+ """
+ import jedi
+
+ if '--debug' in sys.argv:
+ jedi.set_debug_function()
+
+ for path in sys.argv[2:]:
+ if path.startswith('--'):
+ continue
+ if isdir(path):
+ import fnmatch
+ import os
+
+ paths = []
+ for root, dirnames, filenames in os.walk(path):
+ for filename in fnmatch.filter(filenames, '*.py'):
+ paths.append(os.path.join(root, filename))
+ else:
+ paths = [path]
+
+ try:
+ for path in paths:
+ for error in jedi.Script(path=path)._analysis():
+ print(error)
+ except Exception:
+ if '--pdb' in sys.argv:
import traceback
traceback.print_exc()
- import pdb
- pdb.post_mortem()
- else:
- raise
+ import pdb
+ pdb.post_mortem()
+ else:
+ raise
if len(sys.argv) == 2 and sys.argv[1] == 'repl':
diff --git a/contrib/python/jedi/jedi/_compatibility.py b/contrib/python/jedi/jedi/_compatibility.py
index a14b126ec6..f8f93c1063 100644
--- a/contrib/python/jedi/jedi/_compatibility.py
+++ b/contrib/python/jedi/jedi/_compatibility.py
@@ -1,30 +1,30 @@
-"""
+"""
To ensure compatibility from Python ``2.7`` - ``3.x``, a module has been
-created. Clearly there is huge need to use conforming syntax.
-"""
+created. Clearly there is huge need to use conforming syntax.
+"""
import errno
-import sys
-import os
-import re
+import sys
+import os
+import re
import pkgutil
import warnings
import inspect
import subprocess
-try:
- import importlib
-except ImportError:
- pass
-
-is_py3 = sys.version_info[0] >= 3
+try:
+ import importlib
+except ImportError:
+ pass
+
+is_py3 = sys.version_info[0] >= 3
is_py35 = is_py3 and sys.version_info[1] >= 5
py_version = int(str(sys.version_info[0]) + str(sys.version_info[1]))
-
-
+
+
class DummyFile(object):
def __init__(self, loader, string):
self.loader = loader
self.string = string
-
+
def read(self):
return self.loader.get_source(self.string)
@@ -64,8 +64,8 @@ def find_module_py34(string, path=None, full_name=None, is_global_search=True):
def find_module_py33(string, path=None, loader=None, full_name=None, is_global_search=True):
loader = loader or importlib.machinery.PathFinder.find_module(string, path)
- if loader is None and path is None: # Fallback to find builtins
- try:
+ if loader is None and path is None: # Fallback to find builtins
+ try:
with warnings.catch_warnings(record=True):
# Mute "DeprecationWarning: Use importlib.util.find_spec()
# instead." While we should replace that in the future, it's
@@ -73,17 +73,17 @@ def find_module_py33(string, path=None, loader=None, full_name=None, is_global_s
# it was added in Python 3.4 and find_loader hasn't been
# removed in 3.6.
loader = importlib.find_loader(string)
- except ValueError as e:
- # See #491. Importlib might raise a ValueError, to avoid this, we
- # just raise an ImportError to fix the issue.
+ except ValueError as e:
+ # See #491. Importlib might raise a ValueError, to avoid this, we
+ # just raise an ImportError to fix the issue.
raise ImportError("Originally " + repr(e))
-
- if loader is None:
+
+ if loader is None:
raise ImportError("Couldn't find a loader for {}".format(string))
-
- try:
- is_package = loader.is_package(string)
- if is_package:
+
+ try:
+ is_package = loader.is_package(string)
+ if is_package:
if hasattr(loader, 'path'):
module_path = os.path.dirname(loader.path)
else:
@@ -93,27 +93,27 @@ def find_module_py33(string, path=None, loader=None, full_name=None, is_global_s
module_file = DummyFile(loader, string)
else:
module_file = None
- else:
- module_path = loader.get_filename(string)
+ else:
+ module_path = loader.get_filename(string)
module_file = DummyFile(loader, string)
- except AttributeError:
- # ExtensionLoader has not attribute get_filename, instead it has a
- # path attribute that we can use to retrieve the module path
- try:
- module_path = loader.path
+ except AttributeError:
+ # ExtensionLoader has not attribute get_filename, instead it has a
+ # path attribute that we can use to retrieve the module path
+ try:
+ module_path = loader.path
module_file = DummyFile(loader, string)
- except AttributeError:
- module_path = string
- module_file = None
- finally:
- is_package = False
-
+ except AttributeError:
+ module_path = string
+ module_file = None
+ finally:
+ is_package = False
+
if hasattr(loader, 'archive'):
module_path = loader.archive
- return module_file, module_path, is_package
-
-
+ return module_file, module_path, is_package
+
+
def find_module_pre_py34(string, path=None, full_name=None, is_global_search=True):
# This import is here, because in other places it will raise a
# DeprecationWarning.
@@ -124,7 +124,7 @@ def find_module_pre_py34(string, path=None, full_name=None, is_global_search=Tru
return module_file, module_path, module_type is imp.PKG_DIRECTORY
except ImportError:
pass
-
+
if path is None:
path = sys.path
for item in path:
@@ -147,20 +147,20 @@ def find_module_pre_py34(string, path=None, full_name=None, is_global_search=Tru
except ImportError:
pass
raise ImportError("No module named {}".format(string))
-
+
find_module = find_module_py34 if is_py3 else find_module_pre_py34
-find_module.__doc__ = """
-Provides information about a module.
-
-This function isolates the differences in importing libraries introduced with
-python 3.3 on; it gets a module name and optionally a path. It will return a
-tuple containin an open file for the module (if not builtin), the filename
-or the name of the module if it is a builtin one and a boolean indicating
-if the module is contained in a package.
-"""
-
-
+find_module.__doc__ = """
+Provides information about a module.
+
+This function isolates the differences in importing libraries introduced with
+python 3.3 on; it gets a module name and optionally a path. It will return a
+tuple containin an open file for the module (if not builtin), the filename
+or the name of the module if it is a builtin one and a boolean indicating
+if the module is contained in a package.
+"""
+
+
def _iter_modules(paths, prefix=''):
# Copy of pkgutil.iter_modules adapted to work with namespaces
@@ -236,69 +236,69 @@ else:
return [suffix for suffix, _, _ in imp.get_suffixes()]
-# unicode function
-try:
- unicode = unicode
-except NameError:
- unicode = str
-
-
-# re-raise function
-if is_py3:
- def reraise(exception, traceback):
- raise exception.with_traceback(traceback)
-else:
- eval(compile("""
-def reraise(exception, traceback):
- raise exception, None, traceback
-""", 'blub', 'exec'))
-
-reraise.__doc__ = """
-Re-raise `exception` with a `traceback` object.
-
-Usage::
-
- reraise(Exception, sys.exc_info()[2])
-
-"""
-
-
-class Python3Method(object):
- def __init__(self, func):
- self.func = func
-
- def __get__(self, obj, objtype):
- if obj is None:
- return lambda *args, **kwargs: self.func(*args, **kwargs)
- else:
- return lambda *args, **kwargs: self.func(obj, *args, **kwargs)
-
-
-def use_metaclass(meta, *bases):
- """ Create a class with a metaclass. """
- if not bases:
- bases = (object,)
+# unicode function
+try:
+ unicode = unicode
+except NameError:
+ unicode = str
+
+
+# re-raise function
+if is_py3:
+ def reraise(exception, traceback):
+ raise exception.with_traceback(traceback)
+else:
+ eval(compile("""
+def reraise(exception, traceback):
+ raise exception, None, traceback
+""", 'blub', 'exec'))
+
+reraise.__doc__ = """
+Re-raise `exception` with a `traceback` object.
+
+Usage::
+
+ reraise(Exception, sys.exc_info()[2])
+
+"""
+
+
+class Python3Method(object):
+ def __init__(self, func):
+ self.func = func
+
+ def __get__(self, obj, objtype):
+ if obj is None:
+ return lambda *args, **kwargs: self.func(*args, **kwargs)
+ else:
+ return lambda *args, **kwargs: self.func(obj, *args, **kwargs)
+
+
+def use_metaclass(meta, *bases):
+ """ Create a class with a metaclass. """
+ if not bases:
+ bases = (object,)
return meta("Py2CompatibilityMetaClass", bases, {})
-
-
-try:
- encoding = sys.stdout.encoding
- if encoding is None:
- encoding = 'utf-8'
-except AttributeError:
- encoding = 'ascii'
-
-
+
+
+try:
+ encoding = sys.stdout.encoding
+ if encoding is None:
+ encoding = 'utf-8'
+except AttributeError:
+ encoding = 'ascii'
+
+
def u(string, errors='strict'):
- """Cast to unicode DAMMIT!
- Written because Python2 repr always implicitly casts to a string, so we
- have to cast back to a unicode (and we now that we always deal with valid
- unicode, because we check that in the beginning).
- """
+ """Cast to unicode DAMMIT!
+ Written because Python2 repr always implicitly casts to a string, so we
+ have to cast back to a unicode (and we now that we always deal with valid
+ unicode, because we check that in the beginning).
+ """
if isinstance(string, bytes):
return unicode(string, encoding='UTF-8', errors=errors)
- return string
-
+ return string
+
def cast_path(obj):
"""
@@ -320,29 +320,29 @@ def force_unicode(obj):
return cast_path(obj)
-try:
- import builtins # module name in python 3
-except ImportError:
+try:
+ import builtins # module name in python 3
+except ImportError:
import __builtin__ as builtins # noqa: F401
-
-
+
+
import ast # noqa: F401
-
-
-def literal_eval(string):
- return ast.literal_eval(string)
-
-
-try:
- from itertools import zip_longest
-except ImportError:
+
+
+def literal_eval(string):
+ return ast.literal_eval(string)
+
+
+try:
+ from itertools import zip_longest
+except ImportError:
from itertools import izip_longest as zip_longest # Python 2 # noqa: F401
-
+
try:
FileNotFoundError = FileNotFoundError
except NameError:
FileNotFoundError = IOError
-
+
try:
NotADirectoryError = NotADirectoryError
except NameError:
@@ -354,18 +354,18 @@ except NameError:
PermissionError = IOError
-def no_unicode_pprint(dct):
- """
- Python 2/3 dict __repr__ may be different, because of unicode differens
- (with or without a `u` prefix). Normally in doctests we could use `pprint`
- to sort dicts and check for equality, but here we have to write a separate
- function to do that.
- """
- import pprint
- s = pprint.pformat(dct)
- print(re.sub("u'", "'", s))
-
-
+def no_unicode_pprint(dct):
+ """
+ Python 2/3 dict __repr__ may be different, because of unicode differens
+ (with or without a `u` prefix). Normally in doctests we could use `pprint`
+ to sort dicts and check for equality, but here we have to write a separate
+ function to do that.
+ """
+ import pprint
+ s = pprint.pformat(dct)
+ print(re.sub("u'", "'", s))
+
+
def print_to_stderr(*args):
if is_py3:
eval("print(*args, file=sys.stderr)")
@@ -374,22 +374,22 @@ def print_to_stderr(*args):
sys.stderr.flush()
-def utf8_repr(func):
- """
- ``__repr__`` methods in Python 2 don't allow unicode objects to be
- returned. Therefore cast them to utf-8 bytes in this decorator.
- """
- def wrapper(self):
- result = func(self)
- if isinstance(result, unicode):
- return result.encode('utf-8')
- else:
- return result
-
- if is_py3:
- return func
- else:
- return wrapper
+def utf8_repr(func):
+ """
+ ``__repr__`` methods in Python 2 don't allow unicode objects to be
+ returned. Therefore cast them to utf-8 bytes in this decorator.
+ """
+ def wrapper(self):
+ result = func(self)
+ if isinstance(result, unicode):
+ return result.encode('utf-8')
+ else:
+ return result
+
+ if is_py3:
+ return func
+ else:
+ return wrapper
if is_py3:
diff --git a/contrib/python/jedi/jedi/api/__init__.py b/contrib/python/jedi/jedi/api/__init__.py
index 69d34ab64f..9e568cf8f8 100644
--- a/contrib/python/jedi/jedi/api/__init__.py
+++ b/contrib/python/jedi/jedi/api/__init__.py
@@ -1,34 +1,34 @@
-"""
-The API basically only provides one class. You can create a :class:`Script` and
-use its methods.
-
-Additionally you can add a debug function with :func:`set_debug_function`.
+"""
+The API basically only provides one class. You can create a :class:`Script` and
+use its methods.
+
+Additionally you can add a debug function with :func:`set_debug_function`.
Alternatively, if you don't need a custom function and are happy with printing
debug messages to stdout, simply call :func:`set_debug_function` without
arguments.
-
-.. warning:: Please, note that Jedi is **not thread safe**.
-"""
-import os
+
+.. warning:: Please, note that Jedi is **not thread safe**.
+"""
+import os
import sys
-import warnings
-
+import warnings
+
import parso
from parso.python import tree
from jedi._compatibility import force_unicode, is_py3
from jedi.parser_utils import get_executable_nodes
-from jedi import debug
-from jedi import settings
-from jedi import cache
-from jedi.api import classes
-from jedi.api import interpreter
-from jedi.api import helpers
+from jedi import debug
+from jedi import settings
+from jedi import cache
+from jedi.api import classes
+from jedi.api import interpreter
+from jedi.api import helpers
from jedi.api.completion import Completion
from jedi.api.environment import InterpreterEnvironment
from jedi.api.project import get_default_project
-from jedi.evaluate import Evaluator
-from jedi.evaluate import imports
+from jedi.evaluate import Evaluator
+from jedi.evaluate import imports
from jedi.evaluate import usages
from jedi.evaluate.arguments import try_iter_content
from jedi.evaluate.helpers import get_module_names, evaluate_call_of_leaf
@@ -37,20 +37,20 @@ from jedi.evaluate.filters import TreeNameDefinition, ParamName
from jedi.evaluate.syntax_tree import tree_name_to_contexts
from jedi.evaluate.context import ModuleContext
from jedi.evaluate.context.iterable import unpack_tuple_to_dict
-
-# Jedi uses lots and lots of recursion. By setting this a little bit higher, we
-# can remove some "maximum recursion depth" errors.
+
+# Jedi uses lots and lots of recursion. By setting this a little bit higher, we
+# can remove some "maximum recursion depth" errors.
sys.setrecursionlimit(3000)
-
-
-class Script(object):
- """
- A Script is the base for completions, goto or whatever you want to do with
- |jedi|.
-
- You can either use the ``source`` parameter or ``path`` to read a file.
- Usually you're going to want to use both of them (in an editor).
-
+
+
+class Script(object):
+ """
+ A Script is the base for completions, goto or whatever you want to do with
+ |jedi|.
+
+ You can either use the ``source`` parameter or ``path`` to read a file.
+ Usually you're going to want to use both of them (in an editor).
+
The script might be analyzed in a different ``sys.path`` than |jedi|:
- if `sys_path` parameter is not ``None``, it will be used as ``sys.path``
@@ -63,34 +63,34 @@ class Script(object):
- otherwise ``sys.path`` will match that of |jedi|.
- :param source: The source code of the current file, separated by newlines.
- :type source: str
- :param line: The line to perform actions on (starting with 1).
- :type line: int
+ :param source: The source code of the current file, separated by newlines.
+ :type source: str
+ :param line: The line to perform actions on (starting with 1).
+ :type line: int
:param column: The column of the cursor (starting with 0).
:type column: int
- :param path: The path of the file in the file system, or ``''`` if
- it hasn't been saved yet.
- :type path: str or None
- :param encoding: The encoding of ``source``, if it is not a
- ``unicode`` object (default ``'utf-8'``).
- :type encoding: str
+ :param path: The path of the file in the file system, or ``''`` if
+ it hasn't been saved yet.
+ :type path: str or None
+ :param encoding: The encoding of ``source``, if it is not a
+ ``unicode`` object (default ``'utf-8'``).
+ :type encoding: str
:param sys_path: ``sys.path`` to use during analysis of the script
:type sys_path: list
:param environment: TODO
:type sys_path: Environment
- """
- def __init__(self, source=None, line=None, column=None, path=None,
+ """
+ def __init__(self, source=None, line=None, column=None, path=None,
encoding='utf-8', sys_path=None, environment=None):
- self._orig_path = path
+ self._orig_path = path
# An empty path (also empty string) should always result in no path.
self.path = os.path.abspath(path) if path else None
-
- if source is None:
+
+ if source is None:
# TODO add a better warning than the traceback!
with open(path, 'rb') as f:
- source = f.read()
-
+ source = f.read()
+
# Load the Python grammar of the current interpreter.
self._grammar = parso.load_grammar()
@@ -122,8 +122,8 @@ class Script(object):
self._code = source
line = max(len(self._code_lines), 1) if line is None else line
if not (0 < line <= len(self._code_lines)):
- raise ValueError('`line` parameter is not in a valid range.')
-
+ raise ValueError('`line` parameter is not in a valid range.')
+
line_string = self._code_lines[line - 1]
line_len = len(line_string)
if line_string.endswith('\r\n'):
@@ -131,53 +131,53 @@ class Script(object):
if line_string.endswith('\n'):
line_len -= 1
- column = line_len if column is None else column
- if not (0 <= column <= line_len):
+ column = line_len if column is None else column
+ if not (0 <= column <= line_len):
raise ValueError('`column` parameter (%d) is not in a valid range '
'(0-%d) for line %d (%r).' % (
column, line_len, line, line_string))
- self._pos = line, column
+ self._pos = line, column
self._path = path
-
- cache.clear_time_caches()
- debug.reset_time()
-
+
+ cache.clear_time_caches()
+ debug.reset_time()
+
def _get_module(self):
name = '__main__'
if self.path is not None:
import_names = dotted_path_in_sys_path(self._evaluator.get_sys_path(), self.path)
if import_names is not None:
name = '.'.join(import_names)
-
+
module = ModuleContext(
self._evaluator, self._module_node, self.path,
code_lines=self._code_lines
)
imports.add_module_to_cache(self._evaluator, name, module)
return module
-
- def __repr__(self):
+
+ def __repr__(self):
return '<%s: %s %r>' % (
self.__class__.__name__,
repr(self._orig_path),
self._evaluator.environment,
)
-
- def completions(self):
- """
- Return :class:`classes.Completion` objects. Those objects contain
- information about the completions, more than just names.
-
- :return: Completion objects, sorted by name and __ comes last.
- :rtype: list of :class:`classes.Completion`
- """
- debug.speed('completions start')
+
+ def completions(self):
+ """
+ Return :class:`classes.Completion` objects. Those objects contain
+ information about the completions, more than just names.
+
+ :return: Completion objects, sorted by name and __ comes last.
+ :rtype: list of :class:`classes.Completion`
+ """
+ debug.speed('completions start')
completion = Completion(
self._evaluator, self._get_module(), self._code_lines,
self._pos, self.call_signatures
)
completions = completion.completions()
-
+
def iter_import_completions():
for c in completions:
tree_name = c._name.tree_name
@@ -187,57 +187,57 @@ class Script(object):
if definition is not None \
and definition.type in ('import_name', 'import_from'):
yield c
-
+
if len(list(iter_import_completions())) > 10:
# For now disable completions if there's a lot of imports that
# might potentially be resolved. This is the case for tensorflow
# and has been fixed for it. This is obviously temporary until we
# have a better solution.
self._evaluator.infer_enabled = False
-
- debug.speed('completions end')
+
+ debug.speed('completions end')
return completions
-
- def goto_definitions(self):
- """
- Return the definitions of a the path under the cursor. goto function!
- This follows complicated paths and returns the end, not the first
- definition. The big difference between :meth:`goto_assignments` and
- :meth:`goto_definitions` is that :meth:`goto_assignments` doesn't
- follow imports and statements. Multiple objects may be returned,
- because Python itself is a dynamic language, which means depending on
- an option you can have two different versions of a function.
-
- :rtype: list of :class:`classes.Definition`
- """
+
+ def goto_definitions(self):
+ """
+ Return the definitions of a the path under the cursor. goto function!
+ This follows complicated paths and returns the end, not the first
+ definition. The big difference between :meth:`goto_assignments` and
+ :meth:`goto_definitions` is that :meth:`goto_assignments` doesn't
+ follow imports and statements. Multiple objects may be returned,
+ because Python itself is a dynamic language, which means depending on
+ an option you can have two different versions of a function.
+
+ :rtype: list of :class:`classes.Definition`
+ """
leaf = self._module_node.get_name_of_position(self._pos)
if leaf is None:
leaf = self._module_node.get_leaf_for_position(self._pos)
if leaf is None:
return []
-
+
context = self._evaluator.create_context(self._get_module(), leaf)
definitions = helpers.evaluate_goto_definition(self._evaluator, context, leaf)
-
- names = [s.name for s in definitions]
- defs = [classes.Definition(self._evaluator, name) for name in names]
+
+ names = [s.name for s in definitions]
+ defs = [classes.Definition(self._evaluator, name) for name in names]
# The additional set here allows the definitions to become unique in an
# API sense. In the internals we want to separate more things than in
# the API.
- return helpers.sorted_definitions(set(defs))
-
+ return helpers.sorted_definitions(set(defs))
+
def goto_assignments(self, follow_imports=False, follow_builtin_imports=False):
- """
+ """
Return the first definition found, while optionally following imports.
Multiple objects may be returned, because Python itself is a
- dynamic language, which means depending on an option you can have two
- different versions of a function.
-
+ dynamic language, which means depending on an option you can have two
+ different versions of a function.
+
:param follow_imports: The goto call will follow imports.
:param follow_builtin_imports: If follow_imports is True will decide if
it follow builtin imports.
- :rtype: list of :class:`classes.Definition`
- """
+ :rtype: list of :class:`classes.Definition`
+ """
def filter_follow_imports(names, check):
for name in names:
if check(name):
@@ -247,7 +247,7 @@ class Script(object):
for new_name in new_names:
if new_name.start_pos is None:
found_builtin = True
-
+
if found_builtin and not isinstance(name, imports.SubModuleName):
yield name
else:
@@ -255,81 +255,81 @@ class Script(object):
yield new_name
else:
yield name
-
+
tree_name = self._module_node.get_name_of_position(self._pos)
if tree_name is None:
- return []
+ return []
context = self._evaluator.create_context(self._get_module(), tree_name)
names = list(self._evaluator.goto(context, tree_name))
-
+
if follow_imports:
def check(name):
return name.is_import()
- else:
+ else:
def check(name):
return isinstance(name, imports.SubModuleName)
-
+
names = filter_follow_imports(names, check)
-
+
defs = [classes.Definition(self._evaluator, d) for d in set(names)]
return helpers.sorted_definitions(defs)
-
+
def usages(self, additional_module_paths=(), **kwargs):
- """
- Return :class:`classes.Definition` objects, which contain all
- names that point to the definition of the name under the cursor. This
- is very useful for refactoring (renaming), or to show all usages of a
- variable.
-
- .. todo:: Implement additional_module_paths
-
+ """
+ Return :class:`classes.Definition` objects, which contain all
+ names that point to the definition of the name under the cursor. This
+ is very useful for refactoring (renaming), or to show all usages of a
+ variable.
+
+ .. todo:: Implement additional_module_paths
+
:param additional_module_paths: Deprecated, never ever worked.
:param include_builtins: Default True, checks if a usage is a builtin
(e.g. ``sys``) and in that case does not return it.
- :rtype: list of :class:`classes.Definition`
- """
+ :rtype: list of :class:`classes.Definition`
+ """
if additional_module_paths:
warnings.warn(
"Deprecated since version 0.12.0. This never even worked, just ignore it.",
DeprecationWarning,
stacklevel=2
)
-
+
def _usages(include_builtins=True):
tree_name = self._module_node.get_name_of_position(self._pos)
if tree_name is None:
# Must be syntax
- return []
-
+ return []
+
names = usages.usages(self._get_module(), tree_name)
-
+
definitions = [classes.Definition(self._evaluator, n) for n in names]
if not include_builtins:
definitions = [d for d in definitions if not d.in_builtin_module()]
return helpers.sorted_definitions(definitions)
return _usages(**kwargs)
-
- def call_signatures(self):
- """
- Return the function object of the call you're currently in.
-
- E.g. if the cursor is here::
-
- abs(# <-- cursor is here
-
- This would return the ``abs`` function. On the other hand::
-
- abs()# <-- cursor is here
-
+
+ def call_signatures(self):
+ """
+ Return the function object of the call you're currently in.
+
+ E.g. if the cursor is here::
+
+ abs(# <-- cursor is here
+
+ This would return the ``abs`` function. On the other hand::
+
+ abs()# <-- cursor is here
+
This would return an empty list..
-
- :rtype: list of :class:`classes.CallSignature`
- """
+
+ :rtype: list of :class:`classes.CallSignature`
+ """
call_signature_details = \
helpers.get_call_signature_details(self._module_node, self._pos)
if call_signature_details is None:
- return []
-
+ return []
+
context = self._evaluator.create_context(
self._get_module(),
call_signature_details.bracket_leaf
@@ -341,15 +341,15 @@ class Script(object):
self._code_lines,
self._pos
)
- debug.speed('func_call followed')
-
+ debug.speed('func_call followed')
+
return [classes.CallSignature(self._evaluator, d.name,
call_signature_details.bracket_leaf.start_pos,
call_signature_details.call_index,
call_signature_details.keyword_name_str)
for d in definitions if hasattr(d, 'py__call__')]
-
- def _analysis(self):
+
+ def _analysis(self):
self._evaluator.is_analysis = True
self._evaluator.analysis_modules = [self._module_node]
module = self._get_module()
@@ -370,65 +370,65 @@ class Script(object):
for testlist in node.children[:-1:2]:
# Iterate tuples.
unpack_tuple_to_dict(context, types, testlist)
- else:
+ else:
if node.type == 'name':
defs = self._evaluator.goto_definitions(context, node)
else:
defs = evaluate_call_of_leaf(context, node)
try_iter_content(defs)
self._evaluator.reset_recursion_limitations()
-
+
ana = [a for a in self._evaluator.analysis if self.path == a.path]
return sorted(set(ana), key=lambda x: x.line)
finally:
self._evaluator.is_analysis = False
-
-
-class Interpreter(Script):
- """
- Jedi API for Python REPLs.
-
- In addition to completion of simple attribute access, Jedi
- supports code completion based on static code analysis.
- Jedi can complete attributes of object which is not initialized
- yet.
-
- >>> from os.path import join
- >>> namespace = locals()
+
+
+class Interpreter(Script):
+ """
+ Jedi API for Python REPLs.
+
+ In addition to completion of simple attribute access, Jedi
+ supports code completion based on static code analysis.
+ Jedi can complete attributes of object which is not initialized
+ yet.
+
+ >>> from os.path import join
+ >>> namespace = locals()
>>> script = Interpreter('join("").up', [namespace])
- >>> print(script.completions()[0].name)
- upper
- """
-
- def __init__(self, source, namespaces, **kwds):
- """
- Parse `source` and mixin interpreted Python objects from `namespaces`.
-
- :type source: str
- :arg source: Code to parse.
- :type namespaces: list of dict
- :arg namespaces: a list of namespace dictionaries such as the one
- returned by :func:`locals`.
-
- Other optional arguments are same as the ones for :class:`Script`.
- If `line` and `column` are None, they are assumed be at the end of
- `source`.
- """
+ >>> print(script.completions()[0].name)
+ upper
+ """
+
+ def __init__(self, source, namespaces, **kwds):
+ """
+ Parse `source` and mixin interpreted Python objects from `namespaces`.
+
+ :type source: str
+ :arg source: Code to parse.
+ :type namespaces: list of dict
+ :arg namespaces: a list of namespace dictionaries such as the one
+ returned by :func:`locals`.
+
+ Other optional arguments are same as the ones for :class:`Script`.
+ If `line` and `column` are None, they are assumed be at the end of
+ `source`.
+ """
try:
namespaces = [dict(n) for n in namespaces]
except Exception:
raise TypeError("namespaces must be a non-empty list of dicts.")
-
+
environment = kwds.get('environment', None)
if environment is None:
environment = InterpreterEnvironment()
- else:
+ else:
if not isinstance(environment, InterpreterEnvironment):
raise TypeError("The environment needs to be an InterpreterEnvironment subclass.")
-
+
super(Interpreter, self).__init__(source, environment=environment, **kwds)
self.namespaces = namespaces
-
+
def _get_module(self):
return interpreter.MixedModuleContext(
self._evaluator,
@@ -437,28 +437,28 @@ class Interpreter(Script):
path=self.path,
code_lines=self._code_lines,
)
-
-
-def names(source=None, path=None, encoding='utf-8', all_scopes=False,
+
+
+def names(source=None, path=None, encoding='utf-8', all_scopes=False,
definitions=True, references=False, environment=None):
- """
- Returns a list of `Definition` objects, containing name parts.
- This means you can call ``Definition.goto_assignments()`` and get the
- reference of a name.
- The parameters are the same as in :py:class:`Script`, except or the
- following ones:
-
- :param all_scopes: If True lists the names of all scopes instead of only
- the module namespace.
- :param definitions: If True lists the names that have been defined by a
- class, function or a statement (``a = b`` returns ``a``).
- :param references: If True lists all the names that are not listed by
- ``definitions=True``. E.g. ``a = b`` returns ``b``.
- """
- def def_ref_filter(_def):
+ """
+ Returns a list of `Definition` objects, containing name parts.
+ This means you can call ``Definition.goto_assignments()`` and get the
+ reference of a name.
+ The parameters are the same as in :py:class:`Script`, except or the
+ following ones:
+
+ :param all_scopes: If True lists the names of all scopes instead of only
+ the module namespace.
+ :param definitions: If True lists the names that have been defined by a
+ class, function or a statement (``a = b`` returns ``a``).
+ :param references: If True lists all the names that are not listed by
+ ``definitions=True``. E.g. ``a = b`` returns ``b``.
+ """
+ def def_ref_filter(_def):
is_def = _def._name.tree_name.is_definition()
- return definitions and is_def or references and not is_def
-
+ return definitions and is_def or references and not is_def
+
def create_name(name):
if name.parent.type == 'param':
cls = ParamName
@@ -470,7 +470,7 @@ def names(source=None, path=None, encoding='utf-8', all_scopes=False,
name
)
- # Set line/column to a random position, because they don't matter.
+ # Set line/column to a random position, because they don't matter.
script = Script(source, line=1, column=0, path=path, encoding=encoding, environment=environment)
module_context = script._get_module()
defs = [
@@ -479,31 +479,31 @@ def names(source=None, path=None, encoding='utf-8', all_scopes=False,
create_name(name)
) for name in get_module_names(script._module_node, all_scopes)
]
- return sorted(filter(def_ref_filter, defs), key=lambda x: (x.line, x.column))
-
-
-def preload_module(*modules):
- """
- Preloading modules tells Jedi to load a module now, instead of lazy parsing
- of modules. Usful for IDEs, to control which modules to load on startup.
-
- :param modules: different module names, list of string.
- """
- for m in modules:
- s = "import %s as x; x." % m
- Script(s, 1, len(s), None).completions()
-
-
-def set_debug_function(func_cb=debug.print_to_stdout, warnings=True,
- notices=True, speed=True):
- """
- Define a callback debug function to get all the debug messages.
-
+ return sorted(filter(def_ref_filter, defs), key=lambda x: (x.line, x.column))
+
+
+def preload_module(*modules):
+ """
+ Preloading modules tells Jedi to load a module now, instead of lazy parsing
+ of modules. Usful for IDEs, to control which modules to load on startup.
+
+ :param modules: different module names, list of string.
+ """
+ for m in modules:
+ s = "import %s as x; x." % m
+ Script(s, 1, len(s), None).completions()
+
+
+def set_debug_function(func_cb=debug.print_to_stdout, warnings=True,
+ notices=True, speed=True):
+ """
+ Define a callback debug function to get all the debug messages.
+
If you don't specify any arguments, debug messages will be printed to stdout.
- :param func_cb: The callback function for debug messages, with n params.
- """
- debug.debug_function = func_cb
- debug.enable_warning = warnings
- debug.enable_notice = notices
- debug.enable_speed = speed
+ :param func_cb: The callback function for debug messages, with n params.
+ """
+ debug.debug_function = func_cb
+ debug.enable_warning = warnings
+ debug.enable_notice = notices
+ debug.enable_speed = speed
diff --git a/contrib/python/jedi/jedi/api/classes.py b/contrib/python/jedi/jedi/api/classes.py
index bba278adc8..9602e04a8b 100644
--- a/contrib/python/jedi/jedi/api/classes.py
+++ b/contrib/python/jedi/jedi/api/classes.py
@@ -1,138 +1,138 @@
-"""
-The :mod:`jedi.api.classes` module contains the return classes of the API.
-These classes are the much bigger part of the whole API, because they contain
-the interesting information about completion and goto operations.
-"""
-import re
-
+"""
+The :mod:`jedi.api.classes` module contains the return classes of the API.
+These classes are the much bigger part of the whole API, because they contain
+the interesting information about completion and goto operations.
+"""
+import re
+
from parso.python.tree import search_ancestor
-from jedi import settings
+from jedi import settings
from jedi.evaluate.utils import ignored, unite
from jedi.cache import memoize_method
-from jedi.evaluate import imports
-from jedi.evaluate import compiled
+from jedi.evaluate import imports
+from jedi.evaluate import compiled
from jedi.evaluate.imports import ImportName
from jedi.evaluate.context import instance
from jedi.evaluate.context import ClassContext, FunctionExecutionContext
from jedi.api.keywords import KeywordName
-
-
+
+
def _sort_names_by_start_pos(names):
return sorted(names, key=lambda s: s.start_pos or (0, 0))
def defined_names(evaluator, context):
- """
- List sub-definitions (e.g., methods in class).
-
- :type scope: Scope
- :rtype: list of Definition
- """
+ """
+ List sub-definitions (e.g., methods in class).
+
+ :type scope: Scope
+ :rtype: list of Definition
+ """
filter = next(context.get_filters(search_global=True))
names = [name for name in filter.values()]
return [Definition(evaluator, n) for n in _sort_names_by_start_pos(names)]
-
-
-class BaseDefinition(object):
- _mapping = {
- 'posixpath': 'os.path',
- 'riscospath': 'os.path',
- 'ntpath': 'os.path',
- 'os2emxpath': 'os.path',
- 'macpath': 'os.path',
- 'genericpath': 'os.path',
- 'posix': 'os',
- '_io': 'io',
- '_functools': 'functools',
- '_sqlite3': 'sqlite3',
- '__builtin__': '',
- 'builtins': '',
- }
-
- _tuple_mapping = dict((tuple(k.split('.')), v) for (k, v) in {
- 'argparse._ActionsContainer': 'argparse.ArgumentParser',
- }.items())
-
- def __init__(self, evaluator, name):
- self._evaluator = evaluator
- self._name = name
- """
+
+
+class BaseDefinition(object):
+ _mapping = {
+ 'posixpath': 'os.path',
+ 'riscospath': 'os.path',
+ 'ntpath': 'os.path',
+ 'os2emxpath': 'os.path',
+ 'macpath': 'os.path',
+ 'genericpath': 'os.path',
+ 'posix': 'os',
+ '_io': 'io',
+ '_functools': 'functools',
+ '_sqlite3': 'sqlite3',
+ '__builtin__': '',
+ 'builtins': '',
+ }
+
+ _tuple_mapping = dict((tuple(k.split('.')), v) for (k, v) in {
+ 'argparse._ActionsContainer': 'argparse.ArgumentParser',
+ }.items())
+
+ def __init__(self, evaluator, name):
+ self._evaluator = evaluator
+ self._name = name
+ """
An instance of :class:`parso.reprsentation.Name` subclass.
- """
+ """
self.is_keyword = isinstance(self._name, KeywordName)
-
- # generate a path to the definition
+
+ # generate a path to the definition
self._module = name.get_root_context()
- if self.in_builtin_module():
- self.module_path = None
- else:
+ if self.in_builtin_module():
+ self.module_path = None
+ else:
self.module_path = self._module.py__file__()
- """Shows the file path of a module. e.g. ``/usr/lib/python2.7/os.py``"""
-
- @property
- def name(self):
- """
- Name of variable/function/class/module.
-
- For example, for ``x = None`` it returns ``'x'``.
-
- :rtype: str or None
- """
+ """Shows the file path of a module. e.g. ``/usr/lib/python2.7/os.py``"""
+
+ @property
+ def name(self):
+ """
+ Name of variable/function/class/module.
+
+ For example, for ``x = None`` it returns ``'x'``.
+
+ :rtype: str or None
+ """
return self._name.string_name
-
- @property
- def type(self):
- """
- The type of the definition.
-
- Here is an example of the value of this attribute. Let's consider
- the following source. As what is in ``variable`` is unambiguous
- to Jedi, :meth:`jedi.Script.goto_definitions` should return a list of
- definition for ``sys``, ``f``, ``C`` and ``x``.
-
- >>> from jedi import Script
- >>> source = '''
- ... import keyword
- ...
- ... class C:
- ... pass
- ...
- ... class D:
- ... pass
- ...
- ... x = D()
- ...
- ... def f():
- ... pass
- ...
- ... for variable in [keyword, f, C, x]:
- ... variable'''
-
- >>> script = Script(source)
- >>> defs = script.goto_definitions()
-
- Before showing what is in ``defs``, let's sort it by :attr:`line`
- so that it is easy to relate the result to the source code.
-
- >>> defs = sorted(defs, key=lambda d: d.line)
- >>> defs # doctest: +NORMALIZE_WHITESPACE
- [<Definition module keyword>, <Definition class C>,
+
+ @property
+ def type(self):
+ """
+ The type of the definition.
+
+ Here is an example of the value of this attribute. Let's consider
+ the following source. As what is in ``variable`` is unambiguous
+ to Jedi, :meth:`jedi.Script.goto_definitions` should return a list of
+ definition for ``sys``, ``f``, ``C`` and ``x``.
+
+ >>> from jedi import Script
+ >>> source = '''
+ ... import keyword
+ ...
+ ... class C:
+ ... pass
+ ...
+ ... class D:
+ ... pass
+ ...
+ ... x = D()
+ ...
+ ... def f():
+ ... pass
+ ...
+ ... for variable in [keyword, f, C, x]:
+ ... variable'''
+
+ >>> script = Script(source)
+ >>> defs = script.goto_definitions()
+
+ Before showing what is in ``defs``, let's sort it by :attr:`line`
+ so that it is easy to relate the result to the source code.
+
+ >>> defs = sorted(defs, key=lambda d: d.line)
+ >>> defs # doctest: +NORMALIZE_WHITESPACE
+ [<Definition module keyword>, <Definition class C>,
<Definition instance D>, <Definition def f>]
-
- Finally, here is what you can get from :attr:`type`:
-
+
+ Finally, here is what you can get from :attr:`type`:
+
>>> defs = [str(d.type) for d in defs] # It's unicode and in Py2 has u before it.
>>> defs[0]
- 'module'
+ 'module'
>>> defs[1]
- 'class'
+ 'class'
>>> defs[2]
- 'instance'
+ 'instance'
>>> defs[3]
- 'function'
-
- """
+ 'function'
+
+ """
tree_name = self._name.tree_name
resolve = False
if tree_name is not None:
@@ -141,14 +141,14 @@ class BaseDefinition(object):
if definition is not None and definition.type == 'import_from' and \
tree_name.is_definition():
resolve = True
-
+
if isinstance(self._name, imports.SubModuleName) or resolve:
for context in self._name.infer():
return context.api_type
return self._name.api_type
-
- def _path(self):
- """The path to a module/class/function definition."""
+
+ def _path(self):
+ """The path to a module/class/function definition."""
def to_reverse():
name = self._name
if name.api_type == 'module':
@@ -169,7 +169,7 @@ class BaseDefinition(object):
# ImportError. So simply return the name.
yield name.string_name
return
- else:
+ else:
yield name.string_name
parent_context = name.parent_context
@@ -181,139 +181,139 @@ class BaseDefinition(object):
yield parent_context.name.string_name
except AttributeError:
pass
- else:
+ else:
for name in reversed(method().split('.')):
yield name
parent_context = parent_context.parent_context
return reversed(list(to_reverse()))
-
- @property
- def module_name(self):
- """
- The module name.
-
- >>> from jedi import Script
- >>> source = 'import json'
- >>> script = Script(source, path='example.py')
- >>> d = script.goto_definitions()[0]
- >>> print(d.module_name) # doctest: +ELLIPSIS
- json
- """
+
+ @property
+ def module_name(self):
+ """
+ The module name.
+
+ >>> from jedi import Script
+ >>> source = 'import json'
+ >>> script = Script(source, path='example.py')
+ >>> d = script.goto_definitions()[0]
+ >>> print(d.module_name) # doctest: +ELLIPSIS
+ json
+ """
return self._module.name.string_name
-
- def in_builtin_module(self):
- """Whether this is a builtin module."""
- return isinstance(self._module, compiled.CompiledObject)
-
- @property
- def line(self):
- """The line where the definition occurs (starting with 1)."""
+
+ def in_builtin_module(self):
+ """Whether this is a builtin module."""
+ return isinstance(self._module, compiled.CompiledObject)
+
+ @property
+ def line(self):
+ """The line where the definition occurs (starting with 1)."""
start_pos = self._name.start_pos
if start_pos is None:
- return None
+ return None
return start_pos[0]
-
- @property
- def column(self):
- """The column where the definition occurs (starting with 0)."""
+
+ @property
+ def column(self):
+ """The column where the definition occurs (starting with 0)."""
start_pos = self._name.start_pos
if start_pos is None:
- return None
+ return None
return start_pos[1]
-
+
def docstring(self, raw=False, fast=True):
- r"""
- Return a document string for this completion object.
-
- Example:
-
- >>> from jedi import Script
- >>> source = '''\
- ... def f(a, b=1):
- ... "Document for function f."
- ... '''
- >>> script = Script(source, 1, len('def f'), 'example.py')
- >>> doc = script.goto_definitions()[0].docstring()
- >>> print(doc)
- f(a, b=1)
- <BLANKLINE>
- Document for function f.
-
- Notice that useful extra information is added to the actual
- docstring. For function, it is call signature. If you need
- actual docstring, use ``raw=True`` instead.
-
- >>> print(script.goto_definitions()[0].docstring(raw=True))
- Document for function f.
-
+ r"""
+ Return a document string for this completion object.
+
+ Example:
+
+ >>> from jedi import Script
+ >>> source = '''\
+ ... def f(a, b=1):
+ ... "Document for function f."
+ ... '''
+ >>> script = Script(source, 1, len('def f'), 'example.py')
+ >>> doc = script.goto_definitions()[0].docstring()
+ >>> print(doc)
+ f(a, b=1)
+ <BLANKLINE>
+ Document for function f.
+
+ Notice that useful extra information is added to the actual
+ docstring. For function, it is call signature. If you need
+ actual docstring, use ``raw=True`` instead.
+
+ >>> print(script.goto_definitions()[0].docstring(raw=True))
+ Document for function f.
+
:param fast: Don't follow imports that are only one level deep like
``import foo``, but follow ``from foo import bar``. This makes
sense for speed reasons. Completing `import a` is slow if you use
the ``foo.docstring(fast=False)`` on every object, because it
parses all libraries starting with ``a``.
- """
+ """
return _Help(self._name).docstring(fast=fast, raw=raw)
-
- @property
- def description(self):
- """A textual description of the object."""
+
+ @property
+ def description(self):
+ """A textual description of the object."""
return self._name.string_name
-
- @property
- def full_name(self):
- """
- Dot-separated path of this object.
-
- It is in the form of ``<module>[.<submodule>[...]][.<object>]``.
- It is useful when you want to look up Python manual of the
- object at hand.
-
- Example:
-
- >>> from jedi import Script
- >>> source = '''
- ... import os
- ... os.path.join'''
- >>> script = Script(source, 3, len('os.path.join'), 'example.py')
- >>> print(script.goto_definitions()[0].full_name)
- os.path.join
-
+
+ @property
+ def full_name(self):
+ """
+ Dot-separated path of this object.
+
+ It is in the form of ``<module>[.<submodule>[...]][.<object>]``.
+ It is useful when you want to look up Python manual of the
+ object at hand.
+
+ Example:
+
+ >>> from jedi import Script
+ >>> source = '''
+ ... import os
+ ... os.path.join'''
+ >>> script = Script(source, 3, len('os.path.join'), 'example.py')
+ >>> print(script.goto_definitions()[0].full_name)
+ os.path.join
+
Notice that it returns ``'os.path.join'`` instead of (for example)
``'posixpath.join'``. This is not correct, since the modules name would
be ``<module 'posixpath' ...>```. However most users find the latter
more practical.
- """
+ """
path = list(self._path())
- # TODO add further checks, the mapping should only occur on stdlib.
- if not path:
- return None # for keywords the path is empty
-
+ # TODO add further checks, the mapping should only occur on stdlib.
+ if not path:
+ return None # for keywords the path is empty
+
with ignored(KeyError):
- path[0] = self._mapping[path[0]]
- for key, repl in self._tuple_mapping.items():
- if tuple(path[:len(key)]) == key:
- path = [repl] + path[len(key):]
-
- return '.'.join(path if path[0] else path[1:])
-
- def goto_assignments(self):
+ path[0] = self._mapping[path[0]]
+ for key, repl in self._tuple_mapping.items():
+ if tuple(path[:len(key)]) == key:
+ path = [repl] + path[len(key):]
+
+ return '.'.join(path if path[0] else path[1:])
+
+ def goto_assignments(self):
if self._name.tree_name is None:
return self
-
+
names = self._evaluator.goto(self._name.parent_context, self._name.tree_name)
return [Definition(self._evaluator, n) for n in names]
-
+
def _goto_definitions(self):
# TODO make this function public.
return [Definition(self._evaluator, d.name) for d in self._name.infer()]
- @property
+ @property
@memoize_method
- def params(self):
- """
- Raises an ``AttributeError``if the definition is not callable.
- Otherwise returns a list of `Definition` that represents the params.
- """
+ def params(self):
+ """
+ Raises an ``AttributeError``if the definition is not callable.
+ Otherwise returns a list of `Definition` that represents the params.
+ """
def get_param_names(context):
param_names = []
if context.api_type == 'function':
@@ -341,28 +341,28 @@ class BaseDefinition(object):
return param_names
followed = list(self._name.infer())
- if not followed or not hasattr(followed[0], 'py__call__'):
+ if not followed or not hasattr(followed[0], 'py__call__'):
raise AttributeError('There are no params defined on this.')
context = followed[0] # only check the first one.
-
+
return [Definition(self._evaluator, n) for n in get_param_names(context)]
-
- def parent(self):
+
+ def parent(self):
context = self._name.parent_context
if context is None:
return None
-
+
if isinstance(context, FunctionExecutionContext):
context = context.function_context
return Definition(self._evaluator, context.name)
- def __repr__(self):
- return "<%s %s>" % (type(self).__name__, self.description)
-
+ def __repr__(self):
+ return "<%s %s>" % (type(self).__name__, self.description)
+
def get_line_code(self, before=0, after=0):
"""
Returns the line of code where this object was defined.
-
+
:param before: Add n lines before the current line to the output.
:param after: Add n lines after the current line to the output.
@@ -379,47 +379,47 @@ class BaseDefinition(object):
return ''.join(lines[start_index:index + after + 1])
-class Completion(BaseDefinition):
- """
- `Completion` objects are returned from :meth:`api.Script.completions`. They
- provide additional information about a completion.
- """
+class Completion(BaseDefinition):
+ """
+ `Completion` objects are returned from :meth:`api.Script.completions`. They
+ provide additional information about a completion.
+ """
def __init__(self, evaluator, name, stack, like_name_length):
- super(Completion, self).__init__(evaluator, name)
-
- self._like_name_length = like_name_length
+ super(Completion, self).__init__(evaluator, name)
+
+ self._like_name_length = like_name_length
self._stack = stack
-
- # Completion objects with the same Completion name (which means
- # duplicate items in the completion)
- self._same_name_completions = []
-
- def _complete(self, like_name):
- append = ''
- if settings.add_bracket_after_function \
- and self.type == 'Function':
- append = '('
-
+
+ # Completion objects with the same Completion name (which means
+ # duplicate items in the completion)
+ self._same_name_completions = []
+
+ def _complete(self, like_name):
+ append = ''
+ if settings.add_bracket_after_function \
+ and self.type == 'Function':
+ append = '('
+
if self._name.api_type == 'param' and self._stack is not None:
nonterminals = [stack_node.nonterminal for stack_node in self._stack]
if 'trailer' in nonterminals and 'argument' not in nonterminals:
# TODO this doesn't work for nested calls.
append += '='
-
+
name = self._name.string_name
- if like_name:
- name = name[self._like_name_length:]
+ if like_name:
+ name = name[self._like_name_length:]
return name + append
-
- @property
- def complete(self):
- """
- Return the rest of the word, e.g. completing ``isinstance``::
-
- isinstan# <-- Cursor is here
-
- would return the string 'ce'. It also adds additional stuff, depending
- on your `settings.py`.
+
+ @property
+ def complete(self):
+ """
+ Return the rest of the word, e.g. completing ``isinstance``::
+
+ isinstan# <-- Cursor is here
+
+ would return the string 'ce'. It also adds additional stuff, depending
+ on your `settings.py`.
Assuming the following function definition::
@@ -430,24 +430,24 @@ class Completion(BaseDefinition):
would be `am=`
- """
- return self._complete(True)
-
- @property
- def name_with_symbols(self):
- """
+ """
+ return self._complete(True)
+
+ @property
+ def name_with_symbols(self):
+ """
Similar to :attr:`name`, but like :attr:`name` returns also the
symbols, for example assuming the following function definition::
-
+
def foo(param=0):
pass
-
+
completing ``foo(`` would give a ``Completion`` which
``name_with_symbols`` would be "param=".
- """
- return self._complete(False)
-
+ """
+ return self._complete(False)
+
def docstring(self, raw=False, fast=True):
if self._like_name_length >= 3:
# In this case we can just resolve the like name, because we
@@ -455,65 +455,65 @@ class Completion(BaseDefinition):
fast = False
return super(Completion, self).docstring(raw=raw, fast=fast)
- @property
- def description(self):
- """Provide a description of the completion object."""
+ @property
+ def description(self):
+ """Provide a description of the completion object."""
# TODO improve the class structure.
return Definition.description.__get__(self)
-
- def __repr__(self):
+
+ def __repr__(self):
return '<%s: %s>' % (type(self).__name__, self._name.string_name)
-
+
@memoize_method
- def follow_definition(self):
- """
- Return the original definitions. I strongly recommend not using it for
- your completions, because it might slow down |jedi|. If you want to
- read only a few objects (<=20), it might be useful, especially to get
- the original docstrings. The basic problem of this function is that it
- follows all results. This means with 1000 completions (e.g. numpy),
- it's just PITA-slow.
- """
+ def follow_definition(self):
+ """
+ Return the original definitions. I strongly recommend not using it for
+ your completions, because it might slow down |jedi|. If you want to
+ read only a few objects (<=20), it might be useful, especially to get
+ the original docstrings. The basic problem of this function is that it
+ follows all results. This means with 1000 completions (e.g. numpy),
+ it's just PITA-slow.
+ """
defs = self._name.infer()
- return [Definition(self._evaluator, d.name) for d in defs]
-
-
+ return [Definition(self._evaluator, d.name) for d in defs]
+
+
class Definition(BaseDefinition):
- """
- *Definition* objects are returned from :meth:`api.Script.goto_assignments`
- or :meth:`api.Script.goto_definitions`.
- """
- def __init__(self, evaluator, definition):
- super(Definition, self).__init__(evaluator, definition)
-
- @property
- def description(self):
- """
- A description of the :class:`.Definition` object, which is heavily used
- in testing. e.g. for ``isinstance`` it returns ``def isinstance``.
-
- Example:
-
- >>> from jedi import Script
- >>> source = '''
- ... def f():
- ... pass
- ...
- ... class C:
- ... pass
- ...
- ... variable = f if random.choice([0,1]) else C'''
- >>> script = Script(source, column=3) # line is maximum by default
- >>> defs = script.goto_definitions()
- >>> defs = sorted(defs, key=lambda d: d.line)
- >>> defs
- [<Definition def f>, <Definition class C>]
- >>> str(defs[0].description) # strip literals in python2
- 'def f'
- >>> str(defs[1].description)
- 'class C'
-
- """
+ """
+ *Definition* objects are returned from :meth:`api.Script.goto_assignments`
+ or :meth:`api.Script.goto_definitions`.
+ """
+ def __init__(self, evaluator, definition):
+ super(Definition, self).__init__(evaluator, definition)
+
+ @property
+ def description(self):
+ """
+ A description of the :class:`.Definition` object, which is heavily used
+ in testing. e.g. for ``isinstance`` it returns ``def isinstance``.
+
+ Example:
+
+ >>> from jedi import Script
+ >>> source = '''
+ ... def f():
+ ... pass
+ ...
+ ... class C:
+ ... pass
+ ...
+ ... variable = f if random.choice([0,1]) else C'''
+ >>> script = Script(source, column=3) # line is maximum by default
+ >>> defs = script.goto_definitions()
+ >>> defs = sorted(defs, key=lambda d: d.line)
+ >>> defs
+ [<Definition def f>, <Definition class C>]
+ >>> str(defs[0].description) # strip literals in python2
+ 'def f'
+ >>> str(defs[1].description)
+ 'class C'
+
+ """
typ = self.type
tree_name = self._name.tree_name
if typ in ('function', 'class', 'module', 'instance') or tree_name is None:
@@ -527,152 +527,152 @@ class Definition(BaseDefinition):
include_comma=False
)
return typ + ' ' + code
-
+
definition = tree_name.get_definition() or tree_name
# Remove the prefix, because that's not what we want for get_code
# here.
txt = definition.get_code(include_prefix=False)
- # Delete comments:
+ # Delete comments:
txt = re.sub(r'#[^\n]+\n', ' ', txt)
- # Delete multi spaces/newlines
+ # Delete multi spaces/newlines
txt = re.sub(r'\s+', ' ', txt).strip()
return txt
-
- @property
- def desc_with_module(self):
- """
- In addition to the definition, also return the module.
-
- .. warning:: Don't use this function yet, its behaviour may change. If
- you really need it, talk to me.
-
- .. todo:: Add full path. This function is should return a
- `module.class.function` path.
- """
+
+ @property
+ def desc_with_module(self):
+ """
+ In addition to the definition, also return the module.
+
+ .. warning:: Don't use this function yet, its behaviour may change. If
+ you really need it, talk to me.
+
+ .. todo:: Add full path. This function is should return a
+ `module.class.function` path.
+ """
position = '' if self.in_builtin_module else '@%s' % self.line
- return "%s:%s%s" % (self.module_name, self.description, position)
-
+ return "%s:%s%s" % (self.module_name, self.description, position)
+
@memoize_method
- def defined_names(self):
- """
- List sub-definitions (e.g., methods in class).
-
- :rtype: list of Definition
- """
+ def defined_names(self):
+ """
+ List sub-definitions (e.g., methods in class).
+
+ :rtype: list of Definition
+ """
defs = self._name.infer()
return sorted(
unite(defined_names(self._evaluator, d) for d in defs),
key=lambda s: s._name.start_pos or (0, 0)
)
-
- def is_definition(self):
- """
- Returns True, if defined as a name in a statement, function or class.
- Returns False, if it's a reference to such a definition.
- """
+
+ def is_definition(self):
+ """
+ Returns True, if defined as a name in a statement, function or class.
+ Returns False, if it's a reference to such a definition.
+ """
if self._name.tree_name is None:
return True
else:
return self._name.tree_name.is_definition()
-
- def __eq__(self, other):
- return self._name.start_pos == other._name.start_pos \
- and self.module_path == other.module_path \
- and self.name == other.name \
- and self._evaluator == other._evaluator
-
- def __ne__(self, other):
- return not self.__eq__(other)
-
- def __hash__(self):
- return hash((self._name.start_pos, self.module_path, self.name, self._evaluator))
-
-
-class CallSignature(Definition):
- """
- `CallSignature` objects is the return value of `Script.function_definition`.
- It knows what functions you are currently in. e.g. `isinstance(` would
- return the `isinstance` function. without `(` it would return nothing.
- """
+
+ def __eq__(self, other):
+ return self._name.start_pos == other._name.start_pos \
+ and self.module_path == other.module_path \
+ and self.name == other.name \
+ and self._evaluator == other._evaluator
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def __hash__(self):
+ return hash((self._name.start_pos, self.module_path, self.name, self._evaluator))
+
+
+class CallSignature(Definition):
+ """
+ `CallSignature` objects is the return value of `Script.function_definition`.
+ It knows what functions you are currently in. e.g. `isinstance(` would
+ return the `isinstance` function. without `(` it would return nothing.
+ """
def __init__(self, evaluator, executable_name, bracket_start_pos, index, key_name_str):
- super(CallSignature, self).__init__(evaluator, executable_name)
- self._index = index
+ super(CallSignature, self).__init__(evaluator, executable_name)
+ self._index = index
self._key_name_str = key_name_str
self._bracket_start_pos = bracket_start_pos
-
- @property
- def index(self):
- """
- The Param index of the current call.
- Returns None if the index cannot be found in the curent call.
- """
+
+ @property
+ def index(self):
+ """
+ The Param index of the current call.
+ Returns None if the index cannot be found in the curent call.
+ """
if self._key_name_str is not None:
- for i, param in enumerate(self.params):
+ for i, param in enumerate(self.params):
if self._key_name_str == param.name:
- return i
+ return i
if self.params:
param_name = self.params[-1]._name
if param_name.tree_name is not None:
if param_name.tree_name.get_definition().star_count == 2:
return i
return None
-
- if self._index >= len(self.params):
- for i, param in enumerate(self.params):
+
+ if self._index >= len(self.params):
+ for i, param in enumerate(self.params):
tree_name = param._name.tree_name
if tree_name is not None:
# *args case
if tree_name.get_definition().star_count == 1:
return i
- return None
- return self._index
-
- @property
- def bracket_start(self):
- """
- The indent of the bracket that is responsible for the last function
- call.
- """
+ return None
+ return self._index
+
+ @property
+ def bracket_start(self):
+ """
+ The indent of the bracket that is responsible for the last function
+ call.
+ """
return self._bracket_start_pos
-
- @property
+
+ @property
def _params_str(self):
return ', '.join([p.description[6:]
for p in self.params])
-
- def __repr__(self):
+
+ def __repr__(self):
return '<%s: %s index=%r params=[%s]>' % (
type(self).__name__,
self._name.string_name,
self._index,
self._params_str,
)
-
-
-class _Help(object):
- """
- Temporary implementation, will be used as `Script.help() or something in
- the future.
- """
- def __init__(self, definition):
- self._name = definition
-
+
+
+class _Help(object):
+ """
+ Temporary implementation, will be used as `Script.help() or something in
+ the future.
+ """
+ def __init__(self, definition):
+ self._name = definition
+
@memoize_method
def _get_contexts(self, fast):
if isinstance(self._name, ImportName) and fast:
return {}
-
+
if self._name.api_type == 'statement':
return {}
return self._name.infer()
def docstring(self, fast=True, raw=True):
- """
+ """
The docstring ``__doc__`` for any object.
-
- See :attr:`doc` for example.
- """
+
+ See :attr:`doc` for example.
+ """
# TODO: Use all of the followed objects as output. Possibly divinding
# them by a few dashes.
for context in self._get_contexts(fast=fast):
diff --git a/contrib/python/jedi/jedi/api/helpers.py b/contrib/python/jedi/jedi/api/helpers.py
index 1cf24b6a32..7cf4bc6fc4 100644
--- a/contrib/python/jedi/jedi/api/helpers.py
+++ b/contrib/python/jedi/jedi/api/helpers.py
@@ -1,28 +1,28 @@
-"""
-Helpers for the API
-"""
-import re
+"""
+Helpers for the API
+"""
+import re
from collections import namedtuple
from textwrap import dedent
-
+
from parso.python.parser import Parser
from parso.python import tree
-
+
from jedi._compatibility import u
from jedi.evaluate.syntax_tree import eval_atom
from jedi.evaluate.helpers import evaluate_call_of_leaf
from jedi.evaluate.compiled import get_string_context_set
from jedi.cache import call_signature_time_cache
-
-
+
+
CompletionParts = namedtuple('CompletionParts', ['path', 'has_dot', 'name'])
-
-def sorted_definitions(defs):
- # Note: `or ''` below is required because `module_path` could be
- return sorted(defs, key=lambda x: (x.module_path or '', x.line or 0, x.column or 0))
-
-
+
+def sorted_definitions(defs):
+ # Note: `or ''` below is required because `module_path` could be
+ return sorted(defs, key=lambda x: (x.module_path or '', x.line or 0, x.column or 0))
+
+
def get_on_completion_name(module_node, lines, position):
leaf = module_node.get_leaf_for_position(position)
if leaf is None or leaf.type in ('string', 'error_leaf'):
@@ -95,12 +95,12 @@ def _get_code_for_stack(code_lines, module_node, position):
def get_stack_at_position(grammar, code_lines, module_node, pos):
- """
+ """
Returns the possible node names (e.g. import_from, xor_test or yield_stmt).
- """
+ """
class EndMarkerReached(Exception):
pass
-
+
def tokenize_without_endmarker(code):
# TODO This is for now not an official parso API that exists purely
# for Jedi.
@@ -116,7 +116,7 @@ def get_stack_at_position(grammar, code_lines, module_node, pos):
raise EndMarkerReached()
else:
yield token
-
+
# The code might be indedented, just remove it.
code = dedent(_get_code_for_stack(code_lines, module_node, pos))
# We use a word to tell Jedi when we have reached the start of the
@@ -124,7 +124,7 @@ def get_stack_at_position(grammar, code_lines, module_node, pos):
# Use Z as a prefix because it's not part of a number suffix.
safeword = 'ZZZ_USER_WANTS_TO_COMPLETE_HERE_WITH_JEDI'
code = code + ' ' + safeword
-
+
p = Parser(grammar._pgen_grammar, error_recovery=True)
try:
p.parse(tokens=tokenize_without_endmarker(code))
@@ -134,14 +134,14 @@ def get_stack_at_position(grammar, code_lines, module_node, pos):
"This really shouldn't happen. There's a bug in Jedi:\n%s"
% list(tokenize_without_endmarker(code))
)
-
-
+
+
def evaluate_goto_definition(evaluator, context, leaf):
if leaf.type == 'name':
# In case of a name we can just use goto_definition which does all the
# magic itself.
return evaluator.goto_definitions(context, leaf)
-
+
parent = leaf.parent
if parent.type == 'atom':
return context.eval_node(leaf.parent)
@@ -152,7 +152,7 @@ def evaluate_goto_definition(evaluator, context, leaf):
elif leaf.type in ('fstring_string', 'fstring_start', 'fstring_end'):
return get_string_context_set(evaluator)
return []
-
+
CallSignatureDetails = namedtuple(
'CallSignatureDetails',
diff --git a/contrib/python/jedi/jedi/api/interpreter.py b/contrib/python/jedi/jedi/api/interpreter.py
index 3395142964..c9b7bd69bb 100644
--- a/contrib/python/jedi/jedi/api/interpreter.py
+++ b/contrib/python/jedi/jedi/api/interpreter.py
@@ -1,32 +1,32 @@
-"""
-TODO Some parts of this module are still not well documented.
-"""
-
+"""
+TODO Some parts of this module are still not well documented.
+"""
+
from jedi.evaluate.context import ModuleContext
-from jedi.evaluate import compiled
+from jedi.evaluate import compiled
from jedi.evaluate.compiled import mixed
from jedi.evaluate.compiled.access import create_access_path
from jedi.evaluate.base_context import Context
-
-
+
+
def _create(evaluator, obj):
return compiled.create_from_access_path(
evaluator, create_access_path(evaluator, obj)
)
-
-
+
+
class NamespaceObject(object):
def __init__(self, dct):
self.__dict__ = dct
-
-
+
+
class MixedModuleContext(Context):
type = 'mixed_module'
-
+
def __init__(self, evaluator, tree_module, namespaces, path, code_lines):
self.evaluator = evaluator
self._namespaces = namespaces
-
+
self._namespace_objects = [NamespaceObject(n) for n in namespaces]
self._module_context = ModuleContext(
evaluator, tree_module,
@@ -34,14 +34,14 @@ class MixedModuleContext(Context):
code_lines=code_lines
)
self.tree_node = tree_module
-
+
def get_node(self):
return self.tree_node
-
+
def get_filters(self, *args, **kwargs):
for filter in self._module_context.get_filters(*args, **kwargs):
yield filter
-
+
for namespace_obj in self._namespace_objects:
compiled_object = _create(self.evaluator, namespace_obj)
mixed_object = mixed.MixedObject(
@@ -52,7 +52,7 @@ class MixedModuleContext(Context):
)
for filter in mixed_object.get_filters(*args, **kwargs):
yield filter
-
+
@property
def code_lines(self):
return self._module_context.code_lines
diff --git a/contrib/python/jedi/jedi/api/keywords.py b/contrib/python/jedi/jedi/api/keywords.py
index 81e3d1c21c..2991a0f81a 100644
--- a/contrib/python/jedi/jedi/api/keywords.py
+++ b/contrib/python/jedi/jedi/api/keywords.py
@@ -1,11 +1,11 @@
-import pydoc
-
+import pydoc
+
from jedi.evaluate.utils import ignored
from jedi.evaluate.filters import AbstractNameDefinition
-
-try:
- from pydoc_data import topics as pydoc_topics
-except ImportError:
+
+try:
+ from pydoc_data import topics as pydoc_topics
+except ImportError:
# Python 2
try:
import pydoc_topics
@@ -13,72 +13,72 @@ except ImportError:
# This is for Python 3 embeddable version, which dont have
# pydoc_data module in its file python3x.zip.
pydoc_topics = None
-
-
+
+
def get_operator(evaluator, string, pos):
return Keyword(evaluator, string, pos)
-
-
+
+
class KeywordName(AbstractNameDefinition):
api_type = u'keyword'
-
+
def __init__(self, evaluator, name):
self.evaluator = evaluator
self.string_name = name
self.parent_context = evaluator.builtins_module
-
+
def infer(self):
return [Keyword(self.evaluator, self.string_name, (0, 0))]
-
-
+
+
class Keyword(object):
api_type = u'keyword'
-
+
def __init__(self, evaluator, name, pos):
self.name = KeywordName(evaluator, name)
- self.start_pos = pos
+ self.start_pos = pos
self.parent = evaluator.builtins_module
-
- @property
- def names(self):
- """ For a `parsing.Name` like comparision """
- return [self.name]
-
+
+ @property
+ def names(self):
+ """ For a `parsing.Name` like comparision """
+ return [self.name]
+
def py__doc__(self, include_call_signature=False):
return imitate_pydoc(self.name.string_name)
-
- def __repr__(self):
- return '<%s: %s>' % (type(self).__name__, self.name)
-
-
-def imitate_pydoc(string):
- """
- It's not possible to get the pydoc's without starting the annoying pager
- stuff.
- """
+
+ def __repr__(self):
+ return '<%s: %s>' % (type(self).__name__, self.name)
+
+
+def imitate_pydoc(string):
+ """
+ It's not possible to get the pydoc's without starting the annoying pager
+ stuff.
+ """
if pydoc_topics is None:
return ''
- # str needed because of possible unicode stuff in py2k (pydoc doesn't work
- # with unicode strings)
- string = str(string)
- h = pydoc.help
+ # str needed because of possible unicode stuff in py2k (pydoc doesn't work
+ # with unicode strings)
+ string = str(string)
+ h = pydoc.help
with ignored(KeyError):
- # try to access symbols
- string = h.symbols[string]
- string, _, related = string.partition(' ')
-
- get_target = lambda s: h.topics.get(s, h.keywords.get(s))
- while isinstance(string, str):
- string = get_target(string)
-
- try:
- # is a tuple now
- label, related = string
- except TypeError:
- return ''
-
- try:
+ # try to access symbols
+ string = h.symbols[string]
+ string, _, related = string.partition(' ')
+
+ get_target = lambda s: h.topics.get(s, h.keywords.get(s))
+ while isinstance(string, str):
+ string = get_target(string)
+
+ try:
+ # is a tuple now
+ label, related = string
+ except TypeError:
+ return ''
+
+ try:
return pydoc_topics.topics[label].strip() if pydoc_topics else ''
- except KeyError:
- return ''
+ except KeyError:
+ return ''
diff --git a/contrib/python/jedi/jedi/api/replstartup.py b/contrib/python/jedi/jedi/api/replstartup.py
index 98734bf703..3ac8470877 100644
--- a/contrib/python/jedi/jedi/api/replstartup.py
+++ b/contrib/python/jedi/jedi/api/replstartup.py
@@ -1,29 +1,29 @@
-"""
-To use Jedi completion in Python interpreter, add the following in your shell
+"""
+To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``). This works only on Linux/Mac, because readline is
not available on Windows. If you still want Jedi autocompletion in your REPL,
just use IPython instead::
-
- export PYTHONSTARTUP="$(python -m jedi repl)"
-
-Then you will be able to use Jedi completer in your Python interpreter::
-
- $ python
- Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
- [GCC 4.6.1] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> import os
+
+ export PYTHONSTARTUP="$(python -m jedi repl)"
+
+Then you will be able to use Jedi completer in your Python interpreter::
+
+ $ python
+ Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
+ [GCC 4.6.1] on linux2
+ Type "help", "copyright", "credits" or "license" for more information.
+ >>> import os
>>> os.path.join('a', 'b').split().in<TAB> # doctest: +SKIP
..dex ..sert
-
-"""
-import jedi.utils
-from jedi import __version__ as __jedi_version__
-
-print('REPL completion using Jedi %s' % __jedi_version__)
-jedi.utils.setup_readline()
-
-del jedi
-
-# Note: try not to do many things here, as it will contaminate global
-# namespace of the interpreter.
+
+"""
+import jedi.utils
+from jedi import __version__ as __jedi_version__
+
+print('REPL completion using Jedi %s' % __jedi_version__)
+jedi.utils.setup_readline()
+
+del jedi
+
+# Note: try not to do many things here, as it will contaminate global
+# namespace of the interpreter.
diff --git a/contrib/python/jedi/jedi/cache.py b/contrib/python/jedi/jedi/cache.py
index b20ea1e779..93e2bd7fcf 100644
--- a/contrib/python/jedi/jedi/cache.py
+++ b/contrib/python/jedi/jedi/cache.py
@@ -1,37 +1,37 @@
-"""
-This caching is very important for speed and memory optimizations. There's
-nothing really spectacular, just some decorators. The following cache types are
-available:
-
-- ``time_cache`` can be used to cache something for just a limited time span,
- which can be useful if there's user interaction and the user cannot react
- faster than a certain time.
-
-This module is one of the reasons why |jedi| is not thread-safe. As you can see
-there are global variables, which are holding the cache information. Some of
-these variables are being cleaned after every API usage.
-"""
-import time
+"""
+This caching is very important for speed and memory optimizations. There's
+nothing really spectacular, just some decorators. The following cache types are
+available:
+
+- ``time_cache`` can be used to cache something for just a limited time span,
+ which can be useful if there's user interaction and the user cannot react
+ faster than a certain time.
+
+This module is one of the reasons why |jedi| is not thread-safe. As you can see
+there are global variables, which are holding the cache information. Some of
+these variables are being cleaned after every API usage.
+"""
+import time
from functools import wraps
-
-from jedi import settings
+
+from jedi import settings
from parso.cache import parser_cache
-
-_time_caches = {}
-
-
+
+_time_caches = {}
+
+
def underscore_memoization(func):
"""
Decorator for methods::
-
+
class A(object):
def x(self):
if self._x:
self._x = 10
return self._x
-
+
Becomes::
-
+
class A(object):
@underscore_memoization
def x(self):
@@ -52,65 +52,65 @@ def underscore_memoization(func):
return wrapper
-def clear_time_caches(delete_all=False):
- """ Jedi caches many things, that should be completed after each completion
- finishes.
-
- :param delete_all: Deletes also the cache that is normally not deleted,
- like parser cache, which is important for faster parsing.
- """
- global _time_caches
-
- if delete_all:
- for cache in _time_caches.values():
- cache.clear()
- parser_cache.clear()
- else:
- # normally just kill the expired entries, not all
- for tc in _time_caches.values():
- # check time_cache for expired entries
- for key, (t, value) in list(tc.items()):
- if t < time.time():
- # delete expired entries
- del tc[key]
-
-
+def clear_time_caches(delete_all=False):
+ """ Jedi caches many things, that should be completed after each completion
+ finishes.
+
+ :param delete_all: Deletes also the cache that is normally not deleted,
+ like parser cache, which is important for faster parsing.
+ """
+ global _time_caches
+
+ if delete_all:
+ for cache in _time_caches.values():
+ cache.clear()
+ parser_cache.clear()
+ else:
+ # normally just kill the expired entries, not all
+ for tc in _time_caches.values():
+ # check time_cache for expired entries
+ for key, (t, value) in list(tc.items()):
+ if t < time.time():
+ # delete expired entries
+ del tc[key]
+
+
def call_signature_time_cache(time_add_setting):
- """
- This decorator works as follows: Call it with a setting and after that
- use the function with a callable that returns the key.
- But: This function is only called if the key is not available. After a
- certain amount of time (`time_add_setting`) the cache is invalid.
+ """
+ This decorator works as follows: Call it with a setting and after that
+ use the function with a callable that returns the key.
+ But: This function is only called if the key is not available. After a
+ certain amount of time (`time_add_setting`) the cache is invalid.
If the given key is None, the function will not be cached.
- """
- def _temp(key_func):
- dct = {}
- _time_caches[time_add_setting] = dct
-
- def wrapper(*args, **kwargs):
- generator = key_func(*args, **kwargs)
- key = next(generator)
- try:
- expiry, value = dct[key]
- if expiry > time.time():
- return value
- except KeyError:
- pass
-
- value = next(generator)
- time_add = getattr(settings, time_add_setting)
- if key is not None:
- dct[key] = time.time() + time_add, value
- return value
- return wrapper
- return _temp
-
-
+ """
+ def _temp(key_func):
+ dct = {}
+ _time_caches[time_add_setting] = dct
+
+ def wrapper(*args, **kwargs):
+ generator = key_func(*args, **kwargs)
+ key = next(generator)
+ try:
+ expiry, value = dct[key]
+ if expiry > time.time():
+ return value
+ except KeyError:
+ pass
+
+ value = next(generator)
+ time_add = getattr(settings, time_add_setting)
+ if key is not None:
+ dct[key] = time.time() + time_add, value
+ return value
+ return wrapper
+ return _temp
+
+
def time_cache(seconds):
def decorator(func):
cache = {}
-
+
@wraps(func)
def wrapper(*args, **kwargs):
key = (args, frozenset(kwargs.items()))
@@ -123,24 +123,24 @@ def time_cache(seconds):
result = func(*args, **kwargs)
cache[key] = time.time(), result
return result
-
+
wrapper.clear_cache = lambda: cache.clear()
return wrapper
-
+
return decorator
-
-
-def memoize_method(method):
- """A normal memoize function."""
+
+
+def memoize_method(method):
+ """A normal memoize function."""
@wraps(method)
- def wrapper(self, *args, **kwargs):
+ def wrapper(self, *args, **kwargs):
cache_dict = self.__dict__.setdefault('_memoize_method_dct', {})
dct = cache_dict.setdefault(method, {})
- key = (args, frozenset(kwargs.items()))
- try:
- return dct[key]
- except KeyError:
- result = method(self, *args, **kwargs)
- dct[key] = result
- return result
- return wrapper
+ key = (args, frozenset(kwargs.items()))
+ try:
+ return dct[key]
+ except KeyError:
+ result = method(self, *args, **kwargs)
+ dct[key] = result
+ return result
+ return wrapper
diff --git a/contrib/python/jedi/jedi/debug.py b/contrib/python/jedi/jedi/debug.py
index 69205d921d..49fda4bcac 100644
--- a/contrib/python/jedi/jedi/debug.py
+++ b/contrib/python/jedi/jedi/debug.py
@@ -1,7 +1,7 @@
-from jedi._compatibility import encoding, is_py3, u
-import os
-import time
-
+from jedi._compatibility import encoding, is_py3, u
+import os
+import time
+
_inited = False
@@ -14,14 +14,14 @@ def _lazy_colorama_init():
"""
-try:
- if os.name == 'nt':
+try:
+ if os.name == 'nt':
# Does not work on Windows, as pyreadline and colorama interfere
- raise ImportError
- else:
- # Use colorama for nicer console output.
- from colorama import Fore, init
- from colorama import initialise
+ raise ImportError
+ else:
+ # Use colorama for nicer console output.
+ from colorama import Fore, init
+ from colorama import initialise
def _lazy_colorama_init(): # noqa: F811
"""
@@ -44,76 +44,76 @@ try:
pass
_inited = True
-except ImportError:
- class Fore(object):
- RED = ''
- GREEN = ''
- YELLOW = ''
+except ImportError:
+ class Fore(object):
+ RED = ''
+ GREEN = ''
+ YELLOW = ''
MAGENTA = ''
- RESET = ''
-
-NOTICE = object()
-WARNING = object()
-SPEED = object()
-
-enable_speed = False
-enable_warning = False
-enable_notice = False
-
-# callback, interface: level, str
-debug_function = None
+ RESET = ''
+
+NOTICE = object()
+WARNING = object()
+SPEED = object()
+
+enable_speed = False
+enable_warning = False
+enable_notice = False
+
+# callback, interface: level, str
+debug_function = None
_debug_indent = 0
-_start_time = time.time()
-
-
-def reset_time():
- global _start_time, _debug_indent
- _start_time = time.time()
+_start_time = time.time()
+
+
+def reset_time():
+ global _start_time, _debug_indent
+ _start_time = time.time()
_debug_indent = 0
-
-
-def increase_indent(func):
- """Decorator for makin """
- def wrapper(*args, **kwargs):
- global _debug_indent
- _debug_indent += 1
- try:
+
+
+def increase_indent(func):
+ """Decorator for makin """
+ def wrapper(*args, **kwargs):
+ global _debug_indent
+ _debug_indent += 1
+ try:
return func(*args, **kwargs)
- finally:
- _debug_indent -= 1
- return wrapper
-
-
+ finally:
+ _debug_indent -= 1
+ return wrapper
+
+
def dbg(message, *args, **kwargs):
- """ Looks at the stack, to see if a debug message should be printed. """
+ """ Looks at the stack, to see if a debug message should be printed. """
# Python 2 compatibility, because it doesn't understand default args
color = kwargs.pop('color', 'GREEN')
assert color
- if debug_function and enable_notice:
+ if debug_function and enable_notice:
i = ' ' * _debug_indent
_lazy_colorama_init()
debug_function(color, i + 'dbg: ' + message % tuple(u(repr(a)) for a in args))
-
-
+
+
def warning(message, *args, **kwargs):
format = kwargs.pop('format', True)
assert not kwargs
- if debug_function and enable_warning:
- i = ' ' * _debug_indent
+ if debug_function and enable_warning:
+ i = ' ' * _debug_indent
if format:
message = message % tuple(u(repr(a)) for a in args)
debug_function('RED', i + 'warning: ' + message)
-
-
-def speed(name):
- if debug_function and enable_speed:
- now = time.time()
- i = ' ' * _debug_indent
+
+
+def speed(name):
+ if debug_function and enable_speed:
+ now = time.time()
+ i = ' ' * _debug_indent
debug_function('YELLOW', i + 'speed: ' + '%s %s' % (name, now - _start_time))
-
-
+
+
def print_to_stdout(color, str_out):
"""
The default debug function that prints to standard out.
@@ -122,9 +122,9 @@ def print_to_stdout(color, str_out):
"""
col = getattr(Fore, color)
_lazy_colorama_init()
- if not is_py3:
- str_out = str_out.encode(encoding, 'replace')
- print(col + str_out + Fore.RESET)
-
-
-# debug_function = print_to_stdout
+ if not is_py3:
+ str_out = str_out.encode(encoding, 'replace')
+ print(col + str_out + Fore.RESET)
+
+
+# debug_function = print_to_stdout
diff --git a/contrib/python/jedi/jedi/evaluate/__init__.py b/contrib/python/jedi/jedi/evaluate/__init__.py
index 00104c870e..48339439ee 100644
--- a/contrib/python/jedi/jedi/evaluate/__init__.py
+++ b/contrib/python/jedi/jedi/evaluate/__init__.py
@@ -1,80 +1,80 @@
-"""
-Evaluation of Python code in |jedi| is based on three assumptions:
-
-* The code uses as least side effects as possible. Jedi understands certain
- list/tuple/set modifications, but there's no guarantee that Jedi detects
- everything (list.append in different modules for example).
-* No magic is being used:
-
- - metaclasses
- - ``setattr()`` / ``__import__()``
- - writing to ``globals()``, ``locals()``, ``object.__dict__``
-* The programmer is not a total dick, e.g. like `this
- <https://github.com/davidhalter/jedi/issues/24>`_ :-)
-
+"""
+Evaluation of Python code in |jedi| is based on three assumptions:
+
+* The code uses as least side effects as possible. Jedi understands certain
+ list/tuple/set modifications, but there's no guarantee that Jedi detects
+ everything (list.append in different modules for example).
+* No magic is being used:
+
+ - metaclasses
+ - ``setattr()`` / ``__import__()``
+ - writing to ``globals()``, ``locals()``, ``object.__dict__``
+* The programmer is not a total dick, e.g. like `this
+ <https://github.com/davidhalter/jedi/issues/24>`_ :-)
+
The actual algorithm is based on a principle called lazy evaluation. That
said, the typical entry point for static analysis is calling
``eval_expr_stmt``. There's separate logic for autocompletion in the API, the
evaluator is all about evaluating an expression.
-
+
TODO this paragraph is not what jedi does anymore, it's similar, but not the
same.
Now you need to understand what follows after ``eval_expr_stmt``. Let's
-make an example::
-
- import datetime
- datetime.date.toda# <-- cursor here
-
-First of all, this module doesn't care about completion. It really just cares
+make an example::
+
+ import datetime
+ datetime.date.toda# <-- cursor here
+
+First of all, this module doesn't care about completion. It really just cares
about ``datetime.date``. At the end of the procedure ``eval_expr_stmt`` will
-return the ``date`` class.
-
-To *visualize* this (simplified):
-
+return the ``date`` class.
+
+To *visualize* this (simplified):
+
- ``Evaluator.eval_expr_stmt`` doesn't do much, because there's no assignment.
- ``Context.eval_node`` cares for resolving the dotted path
-- ``Evaluator.find_types`` searches for global definitions of datetime, which
- it finds in the definition of an import, by scanning the syntax tree.
-- Using the import logic, the datetime module is found.
+- ``Evaluator.find_types`` searches for global definitions of datetime, which
+ it finds in the definition of an import, by scanning the syntax tree.
+- Using the import logic, the datetime module is found.
- Now ``find_types`` is called again by ``eval_node`` to find ``date``
- inside the datetime module.
-
-Now what would happen if we wanted ``datetime.date.foo.bar``? Two more
-calls to ``find_types``. However the second call would be ignored, because the
-first one would return nothing (there's no foo attribute in ``date``).
-
-What if the import would contain another ``ExprStmt`` like this::
-
- from foo import bar
- Date = bar.baz
-
+ inside the datetime module.
+
+Now what would happen if we wanted ``datetime.date.foo.bar``? Two more
+calls to ``find_types``. However the second call would be ignored, because the
+first one would return nothing (there's no foo attribute in ``date``).
+
+What if the import would contain another ``ExprStmt`` like this::
+
+ from foo import bar
+ Date = bar.baz
+
Well... You get it. Just another ``eval_expr_stmt`` recursion. It's really
-easy. Python can obviously get way more complicated then this. To understand
-tuple assignments, list comprehensions and everything else, a lot more code had
-to be written.
-
-Jedi has been tested very well, so you can just start modifying code. It's best
-to write your own test first for your "new" feature. Don't be scared of
-breaking stuff. As long as the tests pass, you're most likely to be fine.
-
-I need to mention now that lazy evaluation is really good because it
-only *evaluates* what needs to be *evaluated*. All the statements and modules
-that are not used are just being ignored.
-"""
-
+easy. Python can obviously get way more complicated then this. To understand
+tuple assignments, list comprehensions and everything else, a lot more code had
+to be written.
+
+Jedi has been tested very well, so you can just start modifying code. It's best
+to write your own test first for your "new" feature. Don't be scared of
+breaking stuff. As long as the tests pass, you're most likely to be fine.
+
+I need to mention now that lazy evaluation is really good because it
+only *evaluates* what needs to be *evaluated*. All the statements and modules
+that are not used are just being ignored.
+"""
+
from parso.python import tree
import parso
from parso import python_bytes_to_unicode
-
-from jedi import debug
+
+from jedi import debug
from jedi import parser_utils
from jedi.evaluate.utils import unite
-from jedi.evaluate import imports
-from jedi.evaluate import recursion
+from jedi.evaluate import imports
+from jedi.evaluate import recursion
from jedi.evaluate.cache import evaluator_function_cache
-from jedi.evaluate import compiled
-from jedi.evaluate import helpers
+from jedi.evaluate import compiled
+from jedi.evaluate import helpers
from jedi.evaluate.filters import TreeNameDefinition, ParamName
from jedi.evaluate.base_context import ContextualizedName, ContextualizedNode, \
ContextSet, NO_CONTEXTS, iterate_contexts
@@ -83,9 +83,9 @@ from jedi.evaluate.context import ClassContext, FunctionContext, \
from jedi.evaluate.context.iterable import CompForContext
from jedi.evaluate.syntax_tree import eval_trailer, eval_expr_stmt, \
eval_node, check_tuple_assignments
-
-
-class Evaluator(object):
+
+
+class Evaluator(object):
def __init__(self, project, environment=None, script_path=None):
if environment is None:
environment = project.get_environment()
@@ -95,12 +95,12 @@ class Evaluator(object):
self.grammar = environment.get_grammar()
self.latest_grammar = parso.load_grammar(version='3.6')
- self.memoize_cache = {} # for memoize decorators
+ self.memoize_cache = {} # for memoize decorators
self.module_cache = imports.ModuleCache() # does the job of `sys.modules`.
self.compiled_cache = {} # see `evaluate.compiled.create()`
self.inferred_element_counts = {}
self.mixed_cache = {} # see `evaluate.compiled.mixed._create()`
- self.analysis = []
+ self.analysis = []
self.dynamic_params_depth = 0
self.is_analysis = False
self.project = project
@@ -108,30 +108,30 @@ class Evaluator(object):
# This setting is only temporary to limit the work we have to do with
# tensorflow and others.
self.infer_enabled = True
-
+
self.reset_recursion_limitations()
self.allow_different_encoding = True
-
+
@property
@evaluator_function_cache()
def builtins_module(self):
return compiled.get_special_object(self, u'BUILTINS')
-
+
def reset_recursion_limitations(self):
self.recursion_detector = recursion.RecursionDetector()
self.execution_recursion_detector = recursion.ExecutionRecursionDetector(self)
-
+
def get_sys_path(self):
"""Convenience function"""
return self.project._get_sys_path(self, environment=self.environment)
-
+
def eval_element(self, context, element):
if not self.infer_enabled:
return NO_CONTEXTS
-
+
if isinstance(context, CompForContext):
return eval_node(context, element)
-
+
if_stmt = element
while if_stmt is not None:
if_stmt = if_stmt.parent
@@ -172,7 +172,7 @@ class Evaluator(object):
# long.
name_dicts = [{}]
break
-
+
original_name_dicts = list(name_dicts)
name_dicts = []
for definition in definitions:
@@ -180,7 +180,7 @@ class Evaluator(object):
for i, name_dict in enumerate(new_name_dicts):
new_name_dicts[i] = name_dict.copy()
new_name_dicts[i][if_name.value] = ContextSet(definition)
-
+
name_dicts += new_name_dicts
else:
for name_dict in name_dicts:
@@ -191,18 +191,18 @@ class Evaluator(object):
with helpers.predefine_names(context, if_stmt, name_dict):
result |= eval_node(context, element)
return result
- else:
+ else:
return self._eval_element_if_evaluated(context, element)
- else:
+ else:
if predefined_if_name_dict:
return eval_node(context, element)
- else:
+ else:
return self._eval_element_if_evaluated(context, element)
-
+
def _eval_element_if_evaluated(self, context, element):
- """
+ """
TODO This function is temporary: Merge with eval_element.
- """
+ """
parent = element
while parent is not None:
parent = parent.parent
@@ -210,11 +210,11 @@ class Evaluator(object):
if predefined_if_name_dict is not None:
return eval_node(context, element)
return self._eval_element_cached(context, element)
-
+
@evaluator_function_cache(default=NO_CONTEXTS)
def _eval_element_cached(self, context, element):
return eval_node(context, element)
-
+
def goto_definitions(self, context, name):
def_ = name.get_definition(import_name_always=True)
if def_ is not None:
@@ -223,7 +223,7 @@ class Evaluator(object):
return [ClassContext(self, context, name.parent)]
elif type_ == 'funcdef':
return [FunctionContext.from_context(context, name.parent)]
-
+
if type_ == 'expr_stmt':
is_simple_name = name.parent.type not in ('power', 'trailer')
if is_simple_name:
@@ -236,9 +236,9 @@ class Evaluator(object):
return check_tuple_assignments(self, c_node, for_types)
if type_ in ('import_from', 'import_name'):
return imports.infer_import(context, name)
-
+
return helpers.evaluate_call_of_leaf(context, name)
-
+
def goto(self, context, name):
definition = name.get_definition(import_name_always=True)
if definition is not None:
@@ -256,59 +256,59 @@ class Evaluator(object):
elif type_ in ('import_from', 'import_name'):
module_names = imports.infer_import(context, name, is_goto=True)
return module_names
-
- par = name.parent
+
+ par = name.parent
node_type = par.type
if node_type == 'argument' and par.children[1] == '=' and par.children[0] == name:
- # Named param goto.
- trailer = par.parent
- if trailer.type == 'arglist':
- trailer = trailer.parent
- if trailer.type != 'classdef':
- if trailer.type == 'decorator':
+ # Named param goto.
+ trailer = par.parent
+ if trailer.type == 'arglist':
+ trailer = trailer.parent
+ if trailer.type != 'classdef':
+ if trailer.type == 'decorator':
context_set = context.eval_node(trailer.children[1])
- else:
- i = trailer.parent.children.index(trailer)
- to_evaluate = trailer.parent.children[:i]
+ else:
+ i = trailer.parent.children.index(trailer)
+ to_evaluate = trailer.parent.children[:i]
if to_evaluate[0] == 'await':
to_evaluate.pop(0)
context_set = context.eval_node(to_evaluate[0])
- for trailer in to_evaluate[1:]:
+ for trailer in to_evaluate[1:]:
context_set = eval_trailer(context, context_set, trailer)
- param_names = []
+ param_names = []
for context in context_set:
- try:
+ try:
get_param_names = context.get_param_names
- except AttributeError:
- pass
- else:
+ except AttributeError:
+ pass
+ else:
for param_name in get_param_names():
if param_name.string_name == name.value:
param_names.append(param_name)
- return param_names
+ return param_names
elif node_type == 'dotted_name': # Is a decorator.
- index = par.children.index(name)
- if index > 0:
- new_dotted = helpers.deep_ast_copy(par)
- new_dotted.children[index - 1:] = []
+ index = par.children.index(name)
+ if index > 0:
+ new_dotted = helpers.deep_ast_copy(par)
+ new_dotted.children[index - 1:] = []
values = context.eval_node(new_dotted)
return unite(
value.py__getattribute__(name, name_context=context, is_goto=True)
for value in values
)
-
+
if node_type == 'trailer' and par.children[0] == '.':
values = helpers.evaluate_call_of_leaf(context, name, cut_own_trailer=True)
return unite(
value.py__getattribute__(name, name_context=context, is_goto=True)
for value in values
)
- else:
+ else:
stmt = tree.search_ancestor(
name, 'expr_stmt', 'lambdef'
) or name
if stmt.type == 'lambdef':
- stmt = name
+ stmt = name
return context.py__getattribute__(
name,
position=stmt.start_pos,
diff --git a/contrib/python/jedi/jedi/evaluate/analysis.py b/contrib/python/jedi/jedi/evaluate/analysis.py
index f942a268f2..ded4e9f208 100644
--- a/contrib/python/jedi/jedi/evaluate/analysis.py
+++ b/contrib/python/jedi/jedi/evaluate/analysis.py
@@ -1,18 +1,18 @@
-"""
-Module for statical analysis.
-"""
+"""
+Module for statical analysis.
+"""
from parso.python import tree
from jedi._compatibility import force_unicode
-from jedi import debug
-from jedi.evaluate.compiled import CompiledObject
+from jedi import debug
+from jedi.evaluate.compiled import CompiledObject
from jedi.evaluate.helpers import is_string
-
-
-CODES = {
- 'attribute-error': (1, AttributeError, 'Potential AttributeError.'),
- 'name-error': (2, NameError, 'Potential NameError.'),
- 'import-error': (3, ImportError, 'Potential ImportError.'),
+
+
+CODES = {
+ 'attribute-error': (1, AttributeError, 'Potential AttributeError.'),
+ 'name-error': (2, NameError, 'Potential NameError.'),
+ 'import-error': (3, ImportError, 'Potential ImportError.'),
'type-error-too-many-arguments': (4, TypeError, None),
'type-error-too-few-arguments': (5, TypeError, None),
'type-error-keyword-argument': (6, TypeError, None),
@@ -25,96 +25,96 @@ CODES = {
'type-error-not-subscriptable': (13, TypeError, None),
'value-error-too-many-values': (14, ValueError, None),
'value-error-too-few-values': (15, ValueError, None),
-}
-
-
-class Error(object):
- def __init__(self, name, module_path, start_pos, message=None):
- self.path = module_path
- self._start_pos = start_pos
- self.name = name
- if message is None:
- message = CODES[self.name][2]
- self.message = message
-
- @property
- def line(self):
- return self._start_pos[0]
-
- @property
- def column(self):
- return self._start_pos[1]
-
- @property
- def code(self):
- # The class name start
- first = self.__class__.__name__[0]
- return first + str(CODES[self.name][0])
-
- def __unicode__(self):
- return '%s:%s:%s: %s %s' % (self.path, self.line, self.column,
- self.code, self.message)
-
- def __str__(self):
- return self.__unicode__()
-
- def __eq__(self, other):
+}
+
+
+class Error(object):
+ def __init__(self, name, module_path, start_pos, message=None):
+ self.path = module_path
+ self._start_pos = start_pos
+ self.name = name
+ if message is None:
+ message = CODES[self.name][2]
+ self.message = message
+
+ @property
+ def line(self):
+ return self._start_pos[0]
+
+ @property
+ def column(self):
+ return self._start_pos[1]
+
+ @property
+ def code(self):
+ # The class name start
+ first = self.__class__.__name__[0]
+ return first + str(CODES[self.name][0])
+
+ def __unicode__(self):
+ return '%s:%s:%s: %s %s' % (self.path, self.line, self.column,
+ self.code, self.message)
+
+ def __str__(self):
+ return self.__unicode__()
+
+ def __eq__(self, other):
return (self.path == other.path and self.name == other.name and
self._start_pos == other._start_pos)
-
- def __ne__(self, other):
- return not self.__eq__(other)
-
- def __hash__(self):
- return hash((self.path, self._start_pos, self.name))
-
- def __repr__(self):
- return '<%s %s: %s@%s,%s>' % (self.__class__.__name__,
- self.name, self.path,
- self._start_pos[0], self._start_pos[1])
-
-
-class Warning(Error):
- pass
-
-
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def __hash__(self):
+ return hash((self.path, self._start_pos, self.name))
+
+ def __repr__(self):
+ return '<%s %s: %s@%s,%s>' % (self.__class__.__name__,
+ self.name, self.path,
+ self._start_pos[0], self._start_pos[1])
+
+
+class Warning(Error):
+ pass
+
+
def add(node_context, error_name, node, message=None, typ=Error, payload=None):
exception = CODES[error_name][1]
if _check_for_exception_catch(node_context, node, exception, payload):
- return
-
+ return
+
# TODO this path is probably not right
module_context = node_context.get_root_context()
module_path = module_context.py__file__()
instance = typ(error_name, module_path, node.start_pos, message)
debug.warning(str(instance), format=False)
node_context.evaluator.analysis.append(instance)
-
-
-def _check_for_setattr(instance):
- """
- Check if there's any setattr method inside an instance. If so, return True.
- """
+
+
+def _check_for_setattr(instance):
+ """
+ Check if there's any setattr method inside an instance. If so, return True.
+ """
from jedi.evaluate.context import ModuleContext
module = instance.get_root_context()
if not isinstance(module, ModuleContext):
return False
node = module.tree_node
- try:
+ try:
stmts = node.get_used_names()['setattr']
- except KeyError:
- return False
-
+ except KeyError:
+ return False
+
return any(node.start_pos < stmt.start_pos < node.end_pos
- for stmt in stmts)
-
-
+ for stmt in stmts)
+
+
def add_attribute_error(name_context, lookup_context, name):
message = ('AttributeError: %s has no attribute %s.' % (lookup_context, name))
from jedi.evaluate.context.instance import AbstractInstanceContext, CompiledInstanceName
- # Check for __getattr__/__getattribute__ existance and issue a warning
- # instead of an error, if that happens.
+ # Check for __getattr__/__getattribute__ existance and issue a warning
+ # instead of an error, if that happens.
typ = Error
if isinstance(lookup_context, AbstractInstanceContext):
slot_names = lookup_context.get_function_slot_names(u'__getattr__') + \
@@ -125,94 +125,94 @@ def add_attribute_error(name_context, lookup_context, name):
n.parent_context.obj == object:
typ = Warning
break
-
+
if _check_for_setattr(lookup_context):
typ = Warning
-
+
payload = lookup_context, name
add(name_context, 'attribute-error', name, message, typ, payload)
-
+
def _check_for_exception_catch(node_context, jedi_name, exception, payload=None):
- """
- Checks if a jedi object (e.g. `Statement`) sits inside a try/catch and
- doesn't count as an error (if equal to `exception`).
- Also checks `hasattr` for AttributeErrors and uses the `payload` to compare
- it.
- Returns True if the exception was catched.
- """
- def check_match(cls, exception):
- try:
+ """
+ Checks if a jedi object (e.g. `Statement`) sits inside a try/catch and
+ doesn't count as an error (if equal to `exception`).
+ Also checks `hasattr` for AttributeErrors and uses the `payload` to compare
+ it.
+ Returns True if the exception was catched.
+ """
+ def check_match(cls, exception):
+ try:
return isinstance(cls, CompiledObject) and cls.is_super_class(exception)
- except TypeError:
- return False
-
- def check_try_for_except(obj, exception):
- # Only nodes in try
- iterator = iter(obj.children)
- for branch_type in iterator:
- colon = next(iterator)
- suite = next(iterator)
- if branch_type == 'try' \
+ except TypeError:
+ return False
+
+ def check_try_for_except(obj, exception):
+ # Only nodes in try
+ iterator = iter(obj.children)
+ for branch_type in iterator:
+ colon = next(iterator)
+ suite = next(iterator)
+ if branch_type == 'try' \
and not (branch_type.start_pos < jedi_name.start_pos <= suite.end_pos):
- return False
-
+ return False
+
for node in obj.get_except_clause_tests():
- if node is None:
- return True # An exception block that catches everything.
- else:
+ if node is None:
+ return True # An exception block that catches everything.
+ else:
except_classes = node_context.eval_node(node)
- for cls in except_classes:
+ for cls in except_classes:
from jedi.evaluate.context import iterable
if isinstance(cls, iterable.Sequence) and \
cls.array_type == 'tuple':
- # multiple exceptions
+ # multiple exceptions
for lazy_context in cls.py__iter__():
for typ in lazy_context.infer():
if check_match(typ, exception):
return True
- else:
- if check_match(cls, exception):
- return True
-
- def check_hasattr(node, suite):
- try:
+ else:
+ if check_match(cls, exception):
+ return True
+
+ def check_hasattr(node, suite):
+ try:
assert suite.start_pos <= jedi_name.start_pos < suite.end_pos
assert node.type in ('power', 'atom_expr')
- base = node.children[0]
- assert base.type == 'name' and base.value == 'hasattr'
- trailer = node.children[1]
- assert trailer.type == 'trailer'
- arglist = trailer.children[1]
- assert arglist.type == 'arglist'
+ base = node.children[0]
+ assert base.type == 'name' and base.value == 'hasattr'
+ trailer = node.children[1]
+ assert trailer.type == 'trailer'
+ arglist = trailer.children[1]
+ assert arglist.type == 'arglist'
from jedi.evaluate.arguments import TreeArguments
args = list(TreeArguments(node_context.evaluator, node_context, arglist).unpack())
- # Arguments should be very simple
- assert len(args) == 2
-
- # Check name
+ # Arguments should be very simple
+ assert len(args) == 2
+
+ # Check name
key, lazy_context = args[1]
names = list(lazy_context.infer())
assert len(names) == 1 and is_string(names[0])
assert force_unicode(names[0].get_safe_value()) == payload[1].value
-
- # Check objects
+
+ # Check objects
key, lazy_context = args[0]
objects = lazy_context.infer()
- return payload[0] in objects
- except AssertionError:
- return False
-
+ return payload[0] in objects
+ except AssertionError:
+ return False
+
obj = jedi_name
while obj is not None and not isinstance(obj, (tree.Function, tree.Class)):
if isinstance(obj, tree.Flow):
- # try/except catch check
+ # try/except catch check
if obj.type == 'try_stmt' and check_try_for_except(obj, exception):
- return True
- # hasattr check
+ return True
+ # hasattr check
if exception == AttributeError and obj.type in ('if_stmt', 'while_stmt'):
- if check_hasattr(obj.children[1], obj.children[3]):
- return True
- obj = obj.parent
-
- return False
+ if check_hasattr(obj.children[1], obj.children[3]):
+ return True
+ obj = obj.parent
+
+ return False
diff --git a/contrib/python/jedi/jedi/evaluate/cache.py b/contrib/python/jedi/jedi/evaluate/cache.py
index d61a053b42..c619e698a3 100644
--- a/contrib/python/jedi/jedi/evaluate/cache.py
+++ b/contrib/python/jedi/jedi/evaluate/cache.py
@@ -1,50 +1,50 @@
-"""
+"""
- the popular ``_memoize_default`` works like a typical memoize and returns the
- default otherwise.
+ default otherwise.
- ``CachedMetaClass`` uses ``_memoize_default`` to do the same with classes.
-"""
-
+"""
+
_NO_DEFAULT = object()
-
-
+
+
def _memoize_default(default=_NO_DEFAULT, evaluator_is_first_arg=False, second_arg_is_evaluator=False):
- """ This is a typical memoization decorator, BUT there is one difference:
- To prevent recursion it sets defaults.
-
- Preventing recursion is in this case the much bigger use than speed. I
- don't think, that there is a big speed difference, but there are many cases
- where recursion could happen (think about a = b; b = a).
- """
- def func(function):
- def wrapper(obj, *args, **kwargs):
+ """ This is a typical memoization decorator, BUT there is one difference:
+ To prevent recursion it sets defaults.
+
+ Preventing recursion is in this case the much bigger use than speed. I
+ don't think, that there is a big speed difference, but there are many cases
+ where recursion could happen (think about a = b; b = a).
+ """
+ def func(function):
+ def wrapper(obj, *args, **kwargs):
# TODO These checks are kind of ugly and slow.
- if evaluator_is_first_arg:
- cache = obj.memoize_cache
+ if evaluator_is_first_arg:
+ cache = obj.memoize_cache
elif second_arg_is_evaluator:
cache = args[0].memoize_cache # needed for meta classes
- else:
+ else:
cache = obj.evaluator.memoize_cache
-
- try:
- memo = cache[function]
- except KeyError:
- memo = {}
- cache[function] = memo
-
- key = (obj, args, frozenset(kwargs.items()))
- if key in memo:
- return memo[key]
- else:
+
+ try:
+ memo = cache[function]
+ except KeyError:
+ memo = {}
+ cache[function] = memo
+
+ key = (obj, args, frozenset(kwargs.items()))
+ if key in memo:
+ return memo[key]
+ else:
if default is not _NO_DEFAULT:
- memo[key] = default
- rv = function(obj, *args, **kwargs)
- memo[key] = rv
- return rv
- return wrapper
-
- return func
-
-
+ memo[key] = default
+ rv = function(obj, *args, **kwargs)
+ memo[key] = rv
+ return rv
+ return wrapper
+
+ return func
+
+
def evaluator_function_cache(default=_NO_DEFAULT):
def decorator(func):
return _memoize_default(default=default, evaluator_is_first_arg=True)(func)
@@ -66,12 +66,12 @@ def evaluator_as_method_param_cache():
return decorator
-class CachedMetaClass(type):
- """
- This is basically almost the same than the decorator above, it just caches
- class initializations. Either you do it this way or with decorators, but
- with decorators you lose class access (isinstance, etc).
- """
+class CachedMetaClass(type):
+ """
+ This is basically almost the same than the decorator above, it just caches
+ class initializations. Either you do it this way or with decorators, but
+ with decorators you lose class access (isinstance, etc).
+ """
@evaluator_as_method_param_cache()
- def __call__(self, *args, **kwargs):
- return super(CachedMetaClass, self).__call__(*args, **kwargs)
+ def __call__(self, *args, **kwargs):
+ return super(CachedMetaClass, self).__call__(*args, **kwargs)
diff --git a/contrib/python/jedi/jedi/evaluate/compiled/__init__.py b/contrib/python/jedi/jedi/evaluate/compiled/__init__.py
index 386eef81ea..757aec5234 100644
--- a/contrib/python/jedi/jedi/evaluate/compiled/__init__.py
+++ b/contrib/python/jedi/jedi/evaluate/compiled/__init__.py
@@ -2,41 +2,41 @@ from jedi._compatibility import unicode
from jedi.evaluate.compiled.context import CompiledObject, CompiledName, \
CompiledObjectFilter, CompiledContextName, create_from_access_path, \
create_from_name
-
-
+
+
def builtin_from_name(evaluator, string):
builtins = evaluator.builtins_module
return create_from_name(evaluator, builtins, string)
-
-
+
+
def create_simple_object(evaluator, obj):
- """
+ """
Only allows creations of objects that are easily picklable across Python
versions.
- """
+ """
assert isinstance(obj, (int, float, str, bytes, unicode, slice, complex))
return create_from_access_path(
evaluator,
evaluator.compiled_subprocess.create_simple_object(obj)
)
-
-
+
+
def get_special_object(evaluator, identifier):
return create_from_access_path(
evaluator,
evaluator.compiled_subprocess.get_special_object(identifier)
)
-
-
+
+
def get_string_context_set(evaluator):
return builtin_from_name(evaluator, u'str').execute_evaluated()
-
-
+
+
def load_module(evaluator, dotted_name, **kwargs):
# Temporary, some tensorflow builtins cannot be loaded, so it's tried again
# and again and it's really slow.
if dotted_name.startswith('tensorflow.'):
- return None
+ return None
access_path = evaluator.compiled_subprocess.load_module(dotted_name=dotted_name, **kwargs)
if access_path is None:
return None
diff --git a/contrib/python/jedi/jedi/evaluate/compiled/fake.py b/contrib/python/jedi/jedi/evaluate/compiled/fake.py
index 98f126d144..a38ff34938 100644
--- a/contrib/python/jedi/jedi/evaluate/compiled/fake.py
+++ b/contrib/python/jedi/jedi/evaluate/compiled/fake.py
@@ -1,19 +1,19 @@
-"""
-Loads functions that are mixed in to the standard library. E.g. builtins are
-written in C (binaries), but my autocompletion only understands Python code. By
-mixing in Python code, the autocompletion should work much better for builtins.
-"""
+"""
+Loads functions that are mixed in to the standard library. E.g. builtins are
+written in C (binaries), but my autocompletion only understands Python code. By
+mixing in Python code, the autocompletion should work much better for builtins.
+"""
import sys
-import os
+import os
from itertools import chain
-
+
import __res
-
+
from jedi._compatibility import unicode
-
+
fake_modules = {}
-
-
+
+
def _get_path_dict():
path = os.path.dirname(__file__)
base_path = os.path.join(path, 'fake')
@@ -24,37 +24,37 @@ def _get_path_dict():
if file_name.startswith(base_path) and file_name.endswith('.pym'):
dct[file_name[len(base_path) + 1:-4]] = file_name
return dct
-
-
+
+
_path_dict = _get_path_dict()
-
-
+
+
class FakeDoesNotExist(Exception):
pass
-
+
def _load_faked_module(evaluator, module_name):
- try:
+ try:
return fake_modules[module_name]
except KeyError:
- pass
-
+ pass
+
check_module_name = module_name
if module_name == '__builtin__' and evaluator.environment.version_info.major == 2:
check_module_name = 'builtins'
- try:
+ try:
path = _path_dict[check_module_name]
except KeyError:
fake_modules[module_name] = None
return
-
+
if sys.version_info[0] == 3:
path = bytes(path, 'ascii')
source = __res.resfs_read(path)
-
+
fake_modules[module_name] = m = evaluator.latest_grammar.parse(unicode(source))
-
+
if check_module_name != module_name:
# There are two implementations of `open` for either python 2/3.
# -> Rename the python2 version (`look at fake/builtins.pym`).
@@ -63,14 +63,14 @@ def _load_faked_module(evaluator, module_name):
open_func = _search_scope(m, 'open_python2')
open_func.children[1].value = 'open'
return m
-
-
+
+
def _search_scope(scope, obj_name):
for s in chain(scope.iter_classdefs(), scope.iter_funcdefs()):
if s.name.value == obj_name:
return s
-
-
+
+
def get_faked_with_parent_context(parent_context, name):
if parent_context.tree_node is not None:
# Try to search in already clearly defined stuff.
@@ -78,7 +78,7 @@ def get_faked_with_parent_context(parent_context, name):
if found is not None:
return found
raise FakeDoesNotExist
-
+
def get_faked_module(evaluator, string_name):
module = _load_faked_module(evaluator, string_name)
diff --git a/contrib/python/jedi/jedi/evaluate/compiled/fake/_functools.pym b/contrib/python/jedi/jedi/evaluate/compiled/fake/_functools.pym
index e56a1f4fa4..909ef03fc3 100644
--- a/contrib/python/jedi/jedi/evaluate/compiled/fake/_functools.pym
+++ b/contrib/python/jedi/jedi/evaluate/compiled/fake/_functools.pym
@@ -1,9 +1,9 @@
-class partial():
- def __init__(self, func, *args, **keywords):
- self.__func = func
- self.__args = args
- self.__keywords = keywords
-
- def __call__(self, *args, **kwargs):
- # TODO should be **dict(self.__keywords, **kwargs)
- return self.__func(*(self.__args + args), **self.__keywords)
+class partial():
+ def __init__(self, func, *args, **keywords):
+ self.__func = func
+ self.__args = args
+ self.__keywords = keywords
+
+ def __call__(self, *args, **kwargs):
+ # TODO should be **dict(self.__keywords, **kwargs)
+ return self.__func(*(self.__args + args), **self.__keywords)
diff --git a/contrib/python/jedi/jedi/evaluate/compiled/fake/_sqlite3.pym b/contrib/python/jedi/jedi/evaluate/compiled/fake/_sqlite3.pym
index 0df417a0bf..2151e652b4 100644
--- a/contrib/python/jedi/jedi/evaluate/compiled/fake/_sqlite3.pym
+++ b/contrib/python/jedi/jedi/evaluate/compiled/fake/_sqlite3.pym
@@ -1,26 +1,26 @@
-def connect(database, timeout=None, isolation_level=None, detect_types=None, factory=None):
- return Connection()
-
-
-class Connection():
- def cursor(self):
- return Cursor()
-
-
-class Cursor():
- def cursor(self):
- return Cursor()
-
- def fetchone(self):
- return Row()
-
- def fetchmany(self, size=cursor.arraysize):
- return [self.fetchone()]
-
- def fetchall(self):
- return [self.fetchone()]
-
-
-class Row():
- def keys(self):
- return ['']
+def connect(database, timeout=None, isolation_level=None, detect_types=None, factory=None):
+ return Connection()
+
+
+class Connection():
+ def cursor(self):
+ return Cursor()
+
+
+class Cursor():
+ def cursor(self):
+ return Cursor()
+
+ def fetchone(self):
+ return Row()
+
+ def fetchmany(self, size=cursor.arraysize):
+ return [self.fetchone()]
+
+ def fetchall(self):
+ return [self.fetchone()]
+
+
+class Row():
+ def keys(self):
+ return ['']
diff --git a/contrib/python/jedi/jedi/evaluate/compiled/fake/_sre.pym b/contrib/python/jedi/jedi/evaluate/compiled/fake/_sre.pym
index 4d271c0cb5..217be56339 100644
--- a/contrib/python/jedi/jedi/evaluate/compiled/fake/_sre.pym
+++ b/contrib/python/jedi/jedi/evaluate/compiled/fake/_sre.pym
@@ -1,99 +1,99 @@
-def compile():
- class SRE_Match():
- endpos = int()
- lastgroup = int()
- lastindex = int()
- pos = int()
- string = str()
- regs = ((int(), int()),)
-
- def __init__(self, pattern):
- self.re = pattern
-
- def start(self):
- return int()
-
- def end(self):
- return int()
-
- def span(self):
- return int(), int()
-
- def expand(self):
- return str()
-
- def group(self, nr):
- return str()
-
- def groupdict(self):
- return {str(): str()}
-
- def groups(self):
- return (str(),)
-
- class SRE_Pattern():
- flags = int()
- groupindex = {}
- groups = int()
- pattern = str()
-
- def findall(self, string, pos=None, endpos=None):
- """
- findall(string[, pos[, endpos]]) --> list.
- Return a list of all non-overlapping matches of pattern in string.
- """
- return [str()]
-
- def finditer(self, string, pos=None, endpos=None):
- """
- finditer(string[, pos[, endpos]]) --> iterator.
- Return an iterator over all non-overlapping matches for the
- RE pattern in string. For each match, the iterator returns a
- match object.
- """
- yield SRE_Match(self)
-
- def match(self, string, pos=None, endpos=None):
- """
- match(string[, pos[, endpos]]) --> match object or None.
- Matches zero or more characters at the beginning of the string
- pattern
- """
- return SRE_Match(self)
-
- def scanner(self, string, pos=None, endpos=None):
- pass
-
- def search(self, string, pos=None, endpos=None):
- """
- search(string[, pos[, endpos]]) --> match object or None.
- Scan through string looking for a match, and return a corresponding
- MatchObject instance. Return None if no position in the string matches.
- """
- return SRE_Match(self)
-
- def split(self, string, maxsplit=0]):
- """
- split(string[, maxsplit = 0]) --> list.
- Split string by the occurrences of pattern.
- """
- return [str()]
-
- def sub(self, repl, string, count=0):
- """
- sub(repl, string[, count = 0]) --> newstring
- Return the string obtained by replacing the leftmost non-overlapping
- occurrences of pattern in string by the replacement repl.
- """
- return str()
-
- def subn(self, repl, string, count=0):
- """
- subn(repl, string[, count = 0]) --> (newstring, number of subs)
- Return the tuple (new_string, number_of_subs_made) found by replacing
- the leftmost non-overlapping occurrences of pattern with the
- replacement repl.
- """
- return (str(), int())
-
- return SRE_Pattern()
+def compile():
+ class SRE_Match():
+ endpos = int()
+ lastgroup = int()
+ lastindex = int()
+ pos = int()
+ string = str()
+ regs = ((int(), int()),)
+
+ def __init__(self, pattern):
+ self.re = pattern
+
+ def start(self):
+ return int()
+
+ def end(self):
+ return int()
+
+ def span(self):
+ return int(), int()
+
+ def expand(self):
+ return str()
+
+ def group(self, nr):
+ return str()
+
+ def groupdict(self):
+ return {str(): str()}
+
+ def groups(self):
+ return (str(),)
+
+ class SRE_Pattern():
+ flags = int()
+ groupindex = {}
+ groups = int()
+ pattern = str()
+
+ def findall(self, string, pos=None, endpos=None):
+ """
+ findall(string[, pos[, endpos]]) --> list.
+ Return a list of all non-overlapping matches of pattern in string.
+ """
+ return [str()]
+
+ def finditer(self, string, pos=None, endpos=None):
+ """
+ finditer(string[, pos[, endpos]]) --> iterator.
+ Return an iterator over all non-overlapping matches for the
+ RE pattern in string. For each match, the iterator returns a
+ match object.
+ """
+ yield SRE_Match(self)
+
+ def match(self, string, pos=None, endpos=None):
+ """
+ match(string[, pos[, endpos]]) --> match object or None.
+ Matches zero or more characters at the beginning of the string
+ pattern
+ """
+ return SRE_Match(self)
+
+ def scanner(self, string, pos=None, endpos=None):
+ pass
+
+ def search(self, string, pos=None, endpos=None):
+ """
+ search(string[, pos[, endpos]]) --> match object or None.
+ Scan through string looking for a match, and return a corresponding
+ MatchObject instance. Return None if no position in the string matches.
+ """
+ return SRE_Match(self)
+
+ def split(self, string, maxsplit=0]):
+ """
+ split(string[, maxsplit = 0]) --> list.
+ Split string by the occurrences of pattern.
+ """
+ return [str()]
+
+ def sub(self, repl, string, count=0):
+ """
+ sub(repl, string[, count = 0]) --> newstring
+ Return the string obtained by replacing the leftmost non-overlapping
+ occurrences of pattern in string by the replacement repl.
+ """
+ return str()
+
+ def subn(self, repl, string, count=0):
+ """
+ subn(repl, string[, count = 0]) --> (newstring, number of subs)
+ Return the tuple (new_string, number_of_subs_made) found by replacing
+ the leftmost non-overlapping occurrences of pattern with the
+ replacement repl.
+ """
+ return (str(), int())
+
+ return SRE_Pattern()
diff --git a/contrib/python/jedi/jedi/evaluate/compiled/fake/_weakref.pym b/contrib/python/jedi/jedi/evaluate/compiled/fake/_weakref.pym
index 26148b7df4..298d0b0dba 100644
--- a/contrib/python/jedi/jedi/evaluate/compiled/fake/_weakref.pym
+++ b/contrib/python/jedi/jedi/evaluate/compiled/fake/_weakref.pym
@@ -1,9 +1,9 @@
-def proxy(object, callback=None):
- return object
-
+def proxy(object, callback=None):
+ return object
+
class ref():
- def __init__(self, object, callback=None):
- self.__object = object
+ def __init__(self, object, callback=None):
+ self.__object = object
- def __call__(self):
- return self.__object
+ def __call__(self):
+ return self.__object
diff --git a/contrib/python/jedi/jedi/evaluate/compiled/fake/builtins.pym b/contrib/python/jedi/jedi/evaluate/compiled/fake/builtins.pym
index 4f737d4e8a..46ec619fb4 100644
--- a/contrib/python/jedi/jedi/evaluate/compiled/fake/builtins.pym
+++ b/contrib/python/jedi/jedi/evaluate/compiled/fake/builtins.pym
@@ -1,225 +1,225 @@
-"""
-Pure Python implementation of some builtins.
-This code is not going to be executed anywhere.
-These implementations are not always correct, but should work as good as
-possible for the auto completion.
-"""
-
-
-def next(iterator, default=None):
- if random.choice([0, 1]):
- if hasattr("next"):
- return iterator.next()
- else:
- return iterator.__next__()
- else:
- if default is not None:
- return default
-
-
-def iter(collection, sentinel=None):
- if sentinel:
- yield collection()
- else:
- for c in collection:
- yield c
-
-
-def range(start, stop=None, step=1):
- return [0]
-
-
-class file():
- def __iter__(self):
- yield ''
-
- def next(self):
- return ''
-
+"""
+Pure Python implementation of some builtins.
+This code is not going to be executed anywhere.
+These implementations are not always correct, but should work as good as
+possible for the auto completion.
+"""
+
+
+def next(iterator, default=None):
+ if random.choice([0, 1]):
+ if hasattr("next"):
+ return iterator.next()
+ else:
+ return iterator.__next__()
+ else:
+ if default is not None:
+ return default
+
+
+def iter(collection, sentinel=None):
+ if sentinel:
+ yield collection()
+ else:
+ for c in collection:
+ yield c
+
+
+def range(start, stop=None, step=1):
+ return [0]
+
+
+class file():
+ def __iter__(self):
+ yield ''
+
+ def next(self):
+ return ''
+
def readlines(self):
return ['']
-
+
def __enter__(self):
return self
-class xrange():
- # Attention: this function doesn't exist in Py3k (there it is range).
- def __iter__(self):
- yield 1
-
- def count(self):
- return 1
-
- def index(self):
- return 1
-
-
-def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True):
- import io
- return io.TextIOWrapper(file, mode, buffering, encoding, errors, newline, closefd)
-
-
-def open_python2(name, mode=None, buffering=None):
- return file(name, mode, buffering)
-
-
-#--------------------------------------------------------
-# descriptors
-#--------------------------------------------------------
-class property():
- def __init__(self, fget, fset=None, fdel=None, doc=None):
- self.fget = fget
- self.fset = fset
- self.fdel = fdel
- self.__doc__ = doc
-
- def __get__(self, obj, cls):
- return self.fget(obj)
-
- def __set__(self, obj, value):
- self.fset(obj, value)
-
- def __delete__(self, obj):
- self.fdel(obj)
-
- def setter(self, func):
- self.fset = func
- return self
-
- def getter(self, func):
- self.fget = func
- return self
-
- def deleter(self, func):
- self.fdel = func
- return self
-
-
-class staticmethod():
- def __init__(self, func):
- self.__func = func
-
- def __get__(self, obj, cls):
- return self.__func
-
-
-class classmethod():
- def __init__(self, func):
- self.__func = func
-
- def __get__(self, obj, cls):
- def _method(*args, **kwargs):
- return self.__func(cls, *args, **kwargs)
- return _method
-
-
-#--------------------------------------------------------
-# array stuff
-#--------------------------------------------------------
-class list():
- def __init__(self, iterable=[]):
- self.__iterable = []
- for i in iterable:
- self.__iterable += [i]
-
- def __iter__(self):
- for i in self.__iterable:
- yield i
-
- def __getitem__(self, y):
- return self.__iterable[y]
-
- def pop(self):
+class xrange():
+ # Attention: this function doesn't exist in Py3k (there it is range).
+ def __iter__(self):
+ yield 1
+
+ def count(self):
+ return 1
+
+ def index(self):
+ return 1
+
+
+def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True):
+ import io
+ return io.TextIOWrapper(file, mode, buffering, encoding, errors, newline, closefd)
+
+
+def open_python2(name, mode=None, buffering=None):
+ return file(name, mode, buffering)
+
+
+#--------------------------------------------------------
+# descriptors
+#--------------------------------------------------------
+class property():
+ def __init__(self, fget, fset=None, fdel=None, doc=None):
+ self.fget = fget
+ self.fset = fset
+ self.fdel = fdel
+ self.__doc__ = doc
+
+ def __get__(self, obj, cls):
+ return self.fget(obj)
+
+ def __set__(self, obj, value):
+ self.fset(obj, value)
+
+ def __delete__(self, obj):
+ self.fdel(obj)
+
+ def setter(self, func):
+ self.fset = func
+ return self
+
+ def getter(self, func):
+ self.fget = func
+ return self
+
+ def deleter(self, func):
+ self.fdel = func
+ return self
+
+
+class staticmethod():
+ def __init__(self, func):
+ self.__func = func
+
+ def __get__(self, obj, cls):
+ return self.__func
+
+
+class classmethod():
+ def __init__(self, func):
+ self.__func = func
+
+ def __get__(self, obj, cls):
+ def _method(*args, **kwargs):
+ return self.__func(cls, *args, **kwargs)
+ return _method
+
+
+#--------------------------------------------------------
+# array stuff
+#--------------------------------------------------------
+class list():
+ def __init__(self, iterable=[]):
+ self.__iterable = []
+ for i in iterable:
+ self.__iterable += [i]
+
+ def __iter__(self):
+ for i in self.__iterable:
+ yield i
+
+ def __getitem__(self, y):
+ return self.__iterable[y]
+
+ def pop(self):
return self.__iterable[int()]
-
-
-class tuple():
- def __init__(self, iterable=[]):
- self.__iterable = []
- for i in iterable:
- self.__iterable += [i]
-
- def __iter__(self):
- for i in self.__iterable:
- yield i
-
- def __getitem__(self, y):
- return self.__iterable[y]
-
- def index(self):
- return 1
-
- def count(self):
- return 1
-
-
-class set():
- def __init__(self, iterable=[]):
- self.__iterable = iterable
-
- def __iter__(self):
- for i in self.__iterable:
- yield i
-
- def pop(self):
- return list(self.__iterable)[-1]
-
- def copy(self):
- return self
-
- def difference(self, other):
- return self - other
-
- def intersection(self, other):
- return self & other
-
- def symmetric_difference(self, other):
- return self ^ other
-
- def union(self, other):
- return self | other
-
-
-class frozenset():
- def __init__(self, iterable=[]):
- self.__iterable = iterable
-
- def __iter__(self):
- for i in self.__iterable:
- yield i
-
- def copy(self):
- return self
-
-
-class dict():
- def __init__(self, **elements):
- self.__elements = elements
-
- def clear(self):
- # has a strange docstr
- pass
-
+
+
+class tuple():
+ def __init__(self, iterable=[]):
+ self.__iterable = []
+ for i in iterable:
+ self.__iterable += [i]
+
+ def __iter__(self):
+ for i in self.__iterable:
+ yield i
+
+ def __getitem__(self, y):
+ return self.__iterable[y]
+
+ def index(self):
+ return 1
+
+ def count(self):
+ return 1
+
+
+class set():
+ def __init__(self, iterable=[]):
+ self.__iterable = iterable
+
+ def __iter__(self):
+ for i in self.__iterable:
+ yield i
+
+ def pop(self):
+ return list(self.__iterable)[-1]
+
+ def copy(self):
+ return self
+
+ def difference(self, other):
+ return self - other
+
+ def intersection(self, other):
+ return self & other
+
+ def symmetric_difference(self, other):
+ return self ^ other
+
+ def union(self, other):
+ return self | other
+
+
+class frozenset():
+ def __init__(self, iterable=[]):
+ self.__iterable = iterable
+
+ def __iter__(self):
+ for i in self.__iterable:
+ yield i
+
+ def copy(self):
+ return self
+
+
+class dict():
+ def __init__(self, **elements):
+ self.__elements = elements
+
+ def clear(self):
+ # has a strange docstr
+ pass
+
def __getitem__(self, obj):
return self.__elements[obj]
- def get(self, k, d=None):
- # TODO implement
- try:
+ def get(self, k, d=None):
+ # TODO implement
+ try:
return self.__elements[k]
- pass
- except KeyError:
- return d
-
+ pass
+ except KeyError:
+ return d
+
def values(self):
return self.__elements.values()
- def setdefault(self, k, d):
- # TODO maybe also return the content
- return d
-
-
+ def setdefault(self, k, d):
+ # TODO maybe also return the content
+ return d
+
+
class enumerate():
def __init__(self, sequence, start=0):
self.__sequence = sequence
@@ -235,43 +235,43 @@ class enumerate():
return next(self.__iter__())
-class reversed():
- def __init__(self, sequence):
- self.__sequence = sequence
-
- def __iter__(self):
- for i in self.__sequence:
- yield i
-
- def __next__(self):
- return next(self.__iter__())
-
- def next(self):
- return next(self.__iter__())
-
-
-def sorted(iterable, cmp=None, key=None, reverse=False):
- return iterable
-
-
-#--------------------------------------------------------
-# basic types
-#--------------------------------------------------------
-class int():
- def __init__(self, x, base=None):
- pass
-
-
-class str():
- def __init__(self, obj):
- pass
-
+class reversed():
+ def __init__(self, sequence):
+ self.__sequence = sequence
+
+ def __iter__(self):
+ for i in self.__sequence:
+ yield i
+
+ def __next__(self):
+ return next(self.__iter__())
+
+ def next(self):
+ return next(self.__iter__())
+
+
+def sorted(iterable, cmp=None, key=None, reverse=False):
+ return iterable
+
+
+#--------------------------------------------------------
+# basic types
+#--------------------------------------------------------
+class int():
+ def __init__(self, x, base=None):
+ pass
+
+
+class str():
+ def __init__(self, obj):
+ pass
+
def strip(self):
return str()
-
+
def split(self):
return [str()]
-class type():
- def mro():
- return [object]
+class type():
+ def mro():
+ return [object]
diff --git a/contrib/python/jedi/jedi/evaluate/compiled/fake/datetime.pym b/contrib/python/jedi/jedi/evaluate/compiled/fake/datetime.pym
index d981e60051..823ac5b7fd 100644
--- a/contrib/python/jedi/jedi/evaluate/compiled/fake/datetime.pym
+++ b/contrib/python/jedi/jedi/evaluate/compiled/fake/datetime.pym
@@ -1,4 +1,4 @@
-class datetime():
- @staticmethod
- def now():
- return datetime()
+class datetime():
+ @staticmethod
+ def now():
+ return datetime()
diff --git a/contrib/python/jedi/jedi/evaluate/compiled/fake/io.pym b/contrib/python/jedi/jedi/evaluate/compiled/fake/io.pym
index e97310e742..c1f4fc0116 100644
--- a/contrib/python/jedi/jedi/evaluate/compiled/fake/io.pym
+++ b/contrib/python/jedi/jedi/evaluate/compiled/fake/io.pym
@@ -1,9 +1,9 @@
-class TextIOWrapper():
- def __next__(self):
- return str()
-
- def __iter__(self):
- yield str()
+class TextIOWrapper():
+ def __next__(self):
+ return str()
+
+ def __iter__(self):
+ yield str()
def readlines(self):
return ['']
diff --git a/contrib/python/jedi/jedi/evaluate/compiled/fake/posix.pym b/contrib/python/jedi/jedi/evaluate/compiled/fake/posix.pym
index 2c8f6a56e3..4417f7cb04 100644
--- a/contrib/python/jedi/jedi/evaluate/compiled/fake/posix.pym
+++ b/contrib/python/jedi/jedi/evaluate/compiled/fake/posix.pym
@@ -1,5 +1,5 @@
-def getcwd():
- return ''
-
-def getcwdu():
- return ''
+def getcwd():
+ return ''
+
+def getcwdu():
+ return ''
diff --git a/contrib/python/jedi/jedi/evaluate/docstrings.py b/contrib/python/jedi/jedi/evaluate/docstrings.py
index 1983a7635b..aaef8ea853 100644
--- a/contrib/python/jedi/jedi/evaluate/docstrings.py
+++ b/contrib/python/jedi/jedi/evaluate/docstrings.py
@@ -1,49 +1,49 @@
-"""
-Docstrings are another source of information for functions and classes.
-:mod:`jedi.evaluate.dynamic` tries to find all executions of functions, while
+"""
+Docstrings are another source of information for functions and classes.
+:mod:`jedi.evaluate.dynamic` tries to find all executions of functions, while
the docstring parsing is much easier. There are three different types of
-docstrings that |jedi| understands:
-
-- `Sphinx <http://sphinx-doc.org/markup/desc.html#info-field-lists>`_
-- `Epydoc <http://epydoc.sourceforge.net/manual-fields.html>`_
+docstrings that |jedi| understands:
+
+- `Sphinx <http://sphinx-doc.org/markup/desc.html#info-field-lists>`_
+- `Epydoc <http://epydoc.sourceforge.net/manual-fields.html>`_
- `Numpydoc <https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt>`_
-
-For example, the sphinx annotation ``:type foo: str`` clearly states that the
-type of ``foo`` is ``str``.
-
-As an addition to parameter searching, this module also provides return
-annotations.
-"""
-
-import re
-from textwrap import dedent
-
+
+For example, the sphinx annotation ``:type foo: str`` clearly states that the
+type of ``foo`` is ``str``.
+
+As an addition to parameter searching, this module also provides return
+annotations.
+"""
+
+import re
+from textwrap import dedent
+
from parso import parse, ParserSyntaxError
-
+
from jedi._compatibility import u
from jedi.evaluate.utils import indent_block
from jedi.evaluate.cache import evaluator_method_cache
from jedi.evaluate.base_context import iterator_to_context_set, ContextSet, \
NO_CONTEXTS
from jedi.evaluate.lazy_context import LazyKnownContexts
-
-DOCSTRING_PARAM_PATTERNS = [
- r'\s*:type\s+%s:\s*([^\n]+)', # Sphinx
+
+DOCSTRING_PARAM_PATTERNS = [
+ r'\s*:type\s+%s:\s*([^\n]+)', # Sphinx
r'\s*:param\s+(\w+)\s+%s:[^\n]*', # Sphinx param with type
- r'\s*@type\s+%s:\s*([^\n]+)', # Epydoc
-]
-
-DOCSTRING_RETURN_PATTERNS = [
- re.compile(r'\s*:rtype:\s*([^\n]+)', re.M), # Sphinx
- re.compile(r'\s*@rtype:\s*([^\n]+)', re.M), # Epydoc
-]
-
-REST_ROLE_PATTERN = re.compile(r':[^`]+:`([^`]+)`')
-
-
+ r'\s*@type\s+%s:\s*([^\n]+)', # Epydoc
+]
+
+DOCSTRING_RETURN_PATTERNS = [
+ re.compile(r'\s*:rtype:\s*([^\n]+)', re.M), # Sphinx
+ re.compile(r'\s*@rtype:\s*([^\n]+)', re.M), # Epydoc
+]
+
+REST_ROLE_PATTERN = re.compile(r':[^`]+:`([^`]+)`')
+
+
_numpy_doc_string_cache = None
-
+
def _get_numpy_doc_string_cls():
global _numpy_doc_string_cache
@@ -65,7 +65,7 @@ def _search_param_in_numpydocstr(docstr, param_str):
# prepared and return gracefully.
params = _get_numpy_doc_string_cls()(docstr)._parsed_data['Parameters']
except (KeyError, AttributeError, ImportError):
- return []
+ return []
for p_name, p_type, p_descr in params:
if p_name == param_str:
m = re.match(r'([^,]+(,[^,]+)*?)(,[ ]*optional)?$', p_type)
@@ -73,8 +73,8 @@ def _search_param_in_numpydocstr(docstr, param_str):
p_type = m.group(1)
return list(_expand_typestr(p_type))
return []
-
-
+
+
def _search_return_in_numpydocstr(docstr):
"""
Search `docstr` (in numpydoc format) for type(-s) of function returns.
@@ -131,59 +131,59 @@ def _expand_typestr(type_str):
yield type_str
-def _search_param_in_docstr(docstr, param_str):
- """
- Search `docstr` for type(-s) of `param_str`.
-
- >>> _search_param_in_docstr(':type param: int', 'param')
- ['int']
- >>> _search_param_in_docstr('@type param: int', 'param')
- ['int']
- >>> _search_param_in_docstr(
- ... ':type param: :class:`threading.Thread`', 'param')
- ['threading.Thread']
- >>> bool(_search_param_in_docstr('no document', 'param'))
- False
- >>> _search_param_in_docstr(':param int param: some description', 'param')
- ['int']
-
- """
- # look at #40 to see definitions of those params
- patterns = [re.compile(p % re.escape(param_str))
- for p in DOCSTRING_PARAM_PATTERNS]
- for pattern in patterns:
- match = pattern.search(docstr)
- if match:
- return [_strip_rst_role(match.group(1))]
-
+def _search_param_in_docstr(docstr, param_str):
+ """
+ Search `docstr` for type(-s) of `param_str`.
+
+ >>> _search_param_in_docstr(':type param: int', 'param')
+ ['int']
+ >>> _search_param_in_docstr('@type param: int', 'param')
+ ['int']
+ >>> _search_param_in_docstr(
+ ... ':type param: :class:`threading.Thread`', 'param')
+ ['threading.Thread']
+ >>> bool(_search_param_in_docstr('no document', 'param'))
+ False
+ >>> _search_param_in_docstr(':param int param: some description', 'param')
+ ['int']
+
+ """
+ # look at #40 to see definitions of those params
+ patterns = [re.compile(p % re.escape(param_str))
+ for p in DOCSTRING_PARAM_PATTERNS]
+ for pattern in patterns:
+ match = pattern.search(docstr)
+ if match:
+ return [_strip_rst_role(match.group(1))]
+
return _search_param_in_numpydocstr(docstr, param_str)
-
-
-def _strip_rst_role(type_str):
- """
- Strip off the part looks like a ReST role in `type_str`.
-
- >>> _strip_rst_role(':class:`ClassName`') # strip off :class:
- 'ClassName'
- >>> _strip_rst_role(':py:obj:`module.Object`') # works with domain
- 'module.Object'
- >>> _strip_rst_role('ClassName') # do nothing when not ReST role
- 'ClassName'
-
- See also:
- http://sphinx-doc.org/domains.html#cross-referencing-python-objects
-
- """
- match = REST_ROLE_PATTERN.match(type_str)
- if match:
- return match.group(1)
- else:
- return type_str
-
-
+
+
+def _strip_rst_role(type_str):
+ """
+ Strip off the part looks like a ReST role in `type_str`.
+
+ >>> _strip_rst_role(':class:`ClassName`') # strip off :class:
+ 'ClassName'
+ >>> _strip_rst_role(':py:obj:`module.Object`') # works with domain
+ 'module.Object'
+ >>> _strip_rst_role('ClassName') # do nothing when not ReST role
+ 'ClassName'
+
+ See also:
+ http://sphinx-doc.org/domains.html#cross-referencing-python-objects
+
+ """
+ match = REST_ROLE_PATTERN.match(type_str)
+ if match:
+ return match.group(1)
+ else:
+ return type_str
+
+
def _evaluate_for_statement_string(module_context, string):
code = dedent(u("""
- def pseudo_docstring_stuff():
+ def pseudo_docstring_stuff():
'''
Create a pseudo function for docstring statements.
Need this docstring so that if the below part is not valid Python this
@@ -191,30 +191,30 @@ def _evaluate_for_statement_string(module_context, string):
'''
{}
"""))
- if string is None:
- return []
-
+ if string is None:
+ return []
+
for element in re.findall(r'((?:\w+\.)*\w+)\.', string):
- # Try to import module part in dotted name.
- # (e.g., 'threading' in 'threading.Thread').
- string = 'import %s\n' % element + string
-
- # Take the default grammar here, if we load the Python 2.7 grammar here, it
- # will be impossible to use `...` (Ellipsis) as a token. Docstring types
- # don't need to conform with the current grammar.
+ # Try to import module part in dotted name.
+ # (e.g., 'threading' in 'threading.Thread').
+ string = 'import %s\n' % element + string
+
+ # Take the default grammar here, if we load the Python 2.7 grammar here, it
+ # will be impossible to use `...` (Ellipsis) as a token. Docstring types
+ # don't need to conform with the current grammar.
grammar = module_context.evaluator.latest_grammar
- try:
+ try:
module = grammar.parse(code.format(indent_block(string)), error_recovery=False)
except ParserSyntaxError:
return []
try:
funcdef = next(module.iter_funcdefs())
# First pick suite, then simple_stmt and then the node,
- # which is also not the last item, because there's a newline.
+ # which is also not the last item, because there's a newline.
stmt = funcdef.children[-1].children[-1].children[-2]
- except (AttributeError, IndexError):
- return []
-
+ except (AttributeError, IndexError):
+ return []
+
if stmt.type not in ('name', 'atom', 'atom_expr'):
return []
@@ -225,34 +225,34 @@ def _evaluate_for_statement_string(module_context, string):
funcdef
)
func_execution_context = function_context.get_function_execution()
- # Use the module of the param.
- # TODO this module is not the module of the param in case of a function
- # call. In that case it's the module of the function call.
- # stuffed with content from a function call.
+ # Use the module of the param.
+ # TODO this module is not the module of the param in case of a function
+ # call. In that case it's the module of the function call.
+ # stuffed with content from a function call.
return list(_execute_types_in_stmt(func_execution_context, stmt))
-
-
+
+
def _execute_types_in_stmt(module_context, stmt):
- """
- Executing all types or general elements that we find in a statement. This
- doesn't include tuple, list and dict literals, because the stuff they
- contain is executed. (Used as type information).
- """
+ """
+ Executing all types or general elements that we find in a statement. This
+ doesn't include tuple, list and dict literals, because the stuff they
+ contain is executed. (Used as type information).
+ """
definitions = module_context.eval_node(stmt)
return ContextSet.from_sets(
_execute_array_values(module_context.evaluator, d)
for d in definitions
)
-
-
-def _execute_array_values(evaluator, array):
- """
- Tuples indicate that there's not just one return value, but the listed
- ones. `(str, int)` means that it returns a tuple with both types.
- """
+
+
+def _execute_array_values(evaluator, array):
+ """
+ Tuples indicate that there's not just one return value, but the listed
+ ones. `(str, int)` means that it returns a tuple with both types.
+ """
from jedi.evaluate.context.iterable import SequenceLiteralContext, FakeSequence
if isinstance(array, SequenceLiteralContext):
- values = []
+ values = []
for lazy_context in array.py__iter__():
objects = ContextSet.from_sets(
_execute_array_values(evaluator, typ)
@@ -260,15 +260,15 @@ def _execute_array_values(evaluator, array):
)
values.append(LazyKnownContexts(objects))
return {FakeSequence(evaluator, array.array_type, values)}
- else:
+ else:
return array.execute_evaluated()
-
-
+
+
@evaluator_method_cache()
def infer_param(execution_context, param):
from jedi.evaluate.context.instance import InstanceArguments
from jedi.evaluate.context import FunctionExecutionContext
-
+
def eval_docstring(docstring):
return ContextSet.from_iterable(
p
@@ -279,29 +279,29 @@ def infer_param(execution_context, param):
func = param.get_parent_function()
if func.type == 'lambdef':
return NO_CONTEXTS
-
+
types = eval_docstring(execution_context.py__doc__())
if isinstance(execution_context, FunctionExecutionContext) \
and isinstance(execution_context.var_args, InstanceArguments) \
and execution_context.function_context.py__name__() == '__init__':
class_context = execution_context.var_args.instance.class_context
types |= eval_docstring(class_context.py__doc__())
-
+
return types
@evaluator_method_cache()
@iterator_to_context_set
def infer_return_types(function_context):
- def search_return_in_docstr(code):
- for p in DOCSTRING_RETURN_PATTERNS:
- match = p.search(code)
- if match:
+ def search_return_in_docstr(code):
+ for p in DOCSTRING_RETURN_PATTERNS:
+ match = p.search(code)
+ if match:
yield _strip_rst_role(match.group(1))
# Check for numpy style return hint
for type_ in _search_return_in_numpydocstr(code):
yield type_
-
+
for type_str in search_return_in_docstr(function_context.py__doc__()):
for type_eval in _evaluate_for_statement_string(function_context.get_root_context(), type_str):
yield type_eval
diff --git a/contrib/python/jedi/jedi/evaluate/dynamic.py b/contrib/python/jedi/jedi/evaluate/dynamic.py
index dcf7796d3b..7f7b0d87bd 100644
--- a/contrib/python/jedi/jedi/evaluate/dynamic.py
+++ b/contrib/python/jedi/jedi/evaluate/dynamic.py
@@ -1,27 +1,27 @@
-"""
-One of the really important features of |jedi| is to have an option to
-understand code like this::
-
- def foo(bar):
- bar. # completion here
- foo(1)
-
-There's no doubt wheter bar is an ``int`` or not, but if there's also a call
-like ``foo('str')``, what would happen? Well, we'll just show both. Because
-that's what a human would expect.
-
-It works as follows:
-
-- |Jedi| sees a param
-- search for function calls named ``foo``
+"""
+One of the really important features of |jedi| is to have an option to
+understand code like this::
+
+ def foo(bar):
+ bar. # completion here
+ foo(1)
+
+There's no doubt wheter bar is an ``int`` or not, but if there's also a call
+like ``foo('str')``, what would happen? Well, we'll just show both. Because
+that's what a human would expect.
+
+It works as follows:
+
+- |Jedi| sees a param
+- search for function calls named ``foo``
- execute these calls and check the input.
-"""
-
+"""
+
from parso.python import tree
-from jedi import settings
-from jedi import debug
+from jedi import settings
+from jedi import debug
from jedi.evaluate.cache import evaluator_function_cache
-from jedi.evaluate import imports
+from jedi.evaluate import imports
from jedi.evaluate.arguments import TreeArguments
from jedi.evaluate.param import create_default_params
from jedi.evaluate.helpers import is_stdlib_path
@@ -30,20 +30,20 @@ from jedi.parser_utils import get_parent_scope
from jedi.evaluate.context import ModuleContext, instance
from jedi.evaluate.base_context import ContextSet, NO_CONTEXTS
from jedi.evaluate import recursion
-
-
+
+
MAX_PARAM_SEARCHES = 20
class DynamicExecutedParams(object):
- """
+ """
Simulates being a parameter while actually just being multiple params.
- """
-
+ """
+
def __init__(self, evaluator, executed_params):
self.evaluator = evaluator
self._executed_params = executed_params
-
+
def infer(self):
with recursion.execution_allowed(self.evaluator, self) as allowed:
# We need to catch recursions that may occur, because an
@@ -52,25 +52,25 @@ class DynamicExecutedParams(object):
if allowed:
return ContextSet.from_sets(p.infer() for p in self._executed_params)
return NO_CONTEXTS
-
-@debug.increase_indent
+
+@debug.increase_indent
def search_params(evaluator, execution_context, funcdef):
- """
- A dynamic search for param values. If you try to complete a type:
-
- >>> def func(foo):
- ... foo
- >>> func(1)
- >>> func("")
-
- It is not known what the type ``foo`` without analysing the whole code. You
- have to look for all calls to ``func`` to find out what ``foo`` possibly
- is.
- """
- if not settings.dynamic_params:
+ """
+ A dynamic search for param values. If you try to complete a type:
+
+ >>> def func(foo):
+ ... foo
+ >>> func(1)
+ >>> func("")
+
+ It is not known what the type ``foo`` without analysing the whole code. You
+ have to look for all calls to ``func`` to find out what ``foo`` possibly
+ is.
+ """
+ if not settings.dynamic_params:
return create_default_params(execution_context, funcdef)
-
+
evaluator.dynamic_params_depth += 1
try:
path = execution_context.get_root_context().py__file__()
@@ -80,7 +80,7 @@ def search_params(evaluator, execution_context, funcdef):
# This makes everything slower. Just disable it and run the tests,
# you will see the slowdown, especially in 3.6.
return create_default_params(execution_context, funcdef)
-
+
if funcdef.type == 'lambdef':
string_name = _get_lambda_name(funcdef)
if string_name is None:
@@ -88,7 +88,7 @@ def search_params(evaluator, execution_context, funcdef):
else:
string_name = funcdef.name.value
debug.dbg('Dynamic param search in %s.', string_name, color='MAGENTA')
-
+
try:
module_context = execution_context.get_root_context()
function_executions = _search_function_executions(
@@ -116,16 +116,16 @@ def search_params(evaluator, execution_context, funcdef):
@evaluator_function_cache(default=None)
@to_list
def _search_function_executions(evaluator, module_context, funcdef, string_name):
- """
- Returns a list of param names.
- """
+ """
+ Returns a list of param names.
+ """
compare_node = funcdef
if string_name == '__init__':
cls = get_parent_scope(funcdef)
if isinstance(cls, tree.Class):
string_name = cls.name.value
compare_node = cls
-
+
found_executions = False
i = 0
for for_mod_context in imports.get_modules_containing_name(
@@ -134,25 +134,25 @@ def _search_function_executions(evaluator, module_context, funcdef, string_name)
return
for name, trailer in _get_possible_nodes(for_mod_context, string_name):
i += 1
-
+
# This is a simple way to stop Jedi's dynamic param recursion
# from going wild: The deeper Jedi's in the recursion, the less
# code should be evaluated.
if i * evaluator.dynamic_params_depth > MAX_PARAM_SEARCHES:
return
-
+
random_context = evaluator.create_context(for_mod_context, name)
for function_execution in _check_name_for_execution(
evaluator, random_context, compare_node, name, trailer):
found_executions = True
yield function_execution
-
+
# If there are results after processing a module, we're probably
# good to process. This is a speed optimization.
if found_executions:
return
-
-
+
+
def _get_lambda_name(node):
stmt = node.parent
if stmt.type == 'expr_stmt':
@@ -161,16 +161,16 @@ def _get_lambda_name(node):
first = stmt.children[0]
if first.type == 'name':
return first.value
-
+
return None
-
+
def _get_possible_nodes(module_context, func_string_name):
- try:
+ try:
names = module_context.tree_node.get_used_names()[func_string_name]
except KeyError:
return
-
+
for name in names:
bracket = name.get_next_leaf()
trailer = bracket.parent
diff --git a/contrib/python/jedi/jedi/evaluate/finder.py b/contrib/python/jedi/jedi/evaluate/finder.py
index 1633e3ae65..5e7043f796 100644
--- a/contrib/python/jedi/jedi/evaluate/finder.py
+++ b/contrib/python/jedi/jedi/evaluate/finder.py
@@ -1,41 +1,41 @@
-"""
-Searching for names with given scope and name. This is very central in Jedi and
-Python. The name resolution is quite complicated with descripter,
-``__getattribute__``, ``__getattr__``, ``global``, etc.
-
+"""
+Searching for names with given scope and name. This is very central in Jedi and
+Python. The name resolution is quite complicated with descripter,
+``__getattribute__``, ``__getattr__``, ``global``, etc.
+
If you want to understand name resolution, please read the first few chapters
in http://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/.
-Flow checks
-+++++++++++
-
-Flow checks are not really mature. There's only a check for ``isinstance``. It
-would check whether a flow has the form of ``if isinstance(a, type_or_tuple)``.
-Unfortunately every other thing is being ignored (e.g. a == '' would be easy to
-check for -> a is a string). There's big potential in these checks.
-"""
-
+Flow checks
++++++++++++
+
+Flow checks are not really mature. There's only a check for ``isinstance``. It
+would check whether a flow has the form of ``if isinstance(a, type_or_tuple)``.
+Unfortunately every other thing is being ignored (e.g. a == '' would be easy to
+check for -> a is a string). There's big potential in these checks.
+"""
+
from parso.python import tree
from parso.tree import search_ancestor
-from jedi import debug
-from jedi import settings
+from jedi import debug
+from jedi import settings
from jedi.evaluate.context import AbstractInstanceContext
-from jedi.evaluate import compiled
-from jedi.evaluate import analysis
-from jedi.evaluate import flow_analysis
+from jedi.evaluate import compiled
+from jedi.evaluate import analysis
+from jedi.evaluate import flow_analysis
from jedi.evaluate.arguments import TreeArguments
-from jedi.evaluate import helpers
+from jedi.evaluate import helpers
from jedi.evaluate.context import iterable
from jedi.evaluate.filters import get_global_filters, TreeNameDefinition
from jedi.evaluate.base_context import ContextSet
from jedi.parser_utils import is_scope, get_parent_scope
-
-
-class NameFinder(object):
+
+
+class NameFinder(object):
def __init__(self, evaluator, context, name_context, name_or_str,
position=None, analysis_errors=True):
- self._evaluator = evaluator
- # Make sure that it's not just a syntax tree node.
+ self._evaluator = evaluator
+ # Make sure that it's not just a syntax tree node.
self._context = context
self._name_context = name_context
self._name = name_or_str
@@ -46,8 +46,8 @@ class NameFinder(object):
self._position = position
self._found_predefined_types = None
self._analysis_errors = analysis_errors
-
- @debug.increase_indent
+
+ @debug.increase_indent
def find(self, filters, attribute_lookup):
"""
:params bool attribute_lookup: Tell to logic if we're accessing the
@@ -63,7 +63,7 @@ class NameFinder(object):
if check is flow_analysis.UNREACHABLE:
return ContextSet()
return self._found_predefined_types
-
+
types = self._names_to_types(names, attribute_lookup)
if not names and self._analysis_errors and not types \
@@ -74,12 +74,12 @@ class NameFinder(object):
analysis.add_attribute_error(
self._name_context, self._context, self._name)
else:
- message = ("NameError: name '%s' is not defined."
+ message = ("NameError: name '%s' is not defined."
% self._string_name)
analysis.add(self._name_context, 'name-error', self._name, message)
-
- return types
-
+
+ return types
+
def _get_origin_scope(self):
if isinstance(self._name, tree.Name):
scope = self._name
@@ -89,14 +89,14 @@ class NameFinder(object):
break
scope = scope.parent
return scope
- else:
+ else:
return None
-
+
def get_filters(self, search_global=False):
origin_scope = self._get_origin_scope()
if search_global:
position = self._position
-
+
# For functions and classes the defaults don't belong to the
# function and get evaluated in the context before the function. So
# make sure to exclude the function/class name.
@@ -113,17 +113,17 @@ class NameFinder(object):
if position < colon.start_pos:
if lambdef is None or position < lambdef.children[-2].start_pos:
position = ancestor.start_pos
-
+
return get_global_filters(self._evaluator, self._context, position, origin_scope)
else:
return self._context.get_filters(search_global, self._position, origin_scope=origin_scope)
-
+
def filter_name(self, filters):
- """
- Searches names that are defined in a scope (the different
+ """
+ Searches names that are defined in a scope (the different
``filters``), until a name fits.
- """
- names = []
+ """
+ names = []
if self._context.predefined_names and isinstance(self._name, tree.Name):
node = self._name
while node is not None and not is_scope(node):
@@ -140,7 +140,7 @@ class NameFinder(object):
for filter in filters:
names = filter.get(self._string_name)
- if names:
+ if names:
if len(names) == 1:
n, = names
if isinstance(n, TreeNameDefinition):
@@ -152,17 +152,17 @@ class NameFinder(object):
if n.tree_name == self._name:
if self._name.get_definition().type == 'import_from':
continue
- break
-
+ break
+
debug.dbg('finder.filter_name %s in (%s): %s@%s',
self._string_name, self._context, names, self._position)
return list(names)
-
- def _check_getattr(self, inst):
- """Checks for both __getattr__ and __getattribute__ methods"""
- # str is important, because it shouldn't be `Name`!
+
+ def _check_getattr(self, inst):
+ """Checks for both __getattr__ and __getattribute__ methods"""
+ # str is important, because it shouldn't be `Name`!
name = compiled.create_simple_object(self._evaluator, self._string_name)
-
+
# This is a little bit special. `__getattribute__` is in Python
# executed before `__getattr__`. But: I know no use case, where
# this could be practical and where Jedi would return wrong types.
@@ -173,15 +173,15 @@ class NameFinder(object):
names = (inst.get_function_slot_names(u'__getattr__') or
inst.get_function_slot_names(u'__getattribute__'))
return inst.execute_function_slots(names, name)
-
+
def _names_to_types(self, names, attribute_lookup):
contexts = ContextSet.from_sets(name.infer() for name in names)
-
+
debug.dbg('finder._names_to_types: %s -> %s', names, contexts)
if not names and isinstance(self._context, AbstractInstanceContext):
- # handling __getattr__ / __getattribute__
+ # handling __getattr__ / __getattribute__
return self._check_getattr(self._context)
-
+
# Add isinstance and other if/assert knowledge.
if not contexts and isinstance(self._name, tree.Name) and \
not isinstance(self._name_context, AbstractInstanceContext):
@@ -198,25 +198,25 @@ class NameFinder(object):
if flow_scope == base_node:
break
return contexts
-
-
+
+
def _check_flow_information(context, flow, search_name, pos):
- """ Try to find out the type of a variable just with the information that
- is given by the flows: e.g. It is also responsible for assert checks.::
-
- if isinstance(k, str):
- k. # <- completion here
-
- ensures that `k` is a string.
- """
- if not settings.dynamic_flow_information:
- return None
-
+ """ Try to find out the type of a variable just with the information that
+ is given by the flows: e.g. It is also responsible for assert checks.::
+
+ if isinstance(k, str):
+ k. # <- completion here
+
+ ensures that `k` is a string.
+ """
+ if not settings.dynamic_flow_information:
+ return None
+
result = None
if is_scope(flow):
- # Check for asserts.
+ # Check for asserts.
module_node = flow.get_root_node()
- try:
+ try:
names = module_node.get_used_names()[search_name.value]
except KeyError:
return None
@@ -224,49 +224,49 @@ def _check_flow_information(context, flow, search_name, pos):
n for n in names
if flow.start_pos <= n.start_pos < (pos or flow.end_pos)
])
-
- for name in names:
+
+ for name in names:
ass = search_ancestor(name, 'assert_stmt')
if ass is not None:
result = _check_isinstance_type(context, ass.assertion, search_name)
if result is not None:
return result
-
+
if flow.type in ('if_stmt', 'while_stmt'):
potential_ifs = [c for c in flow.children[1::4] if c != ':']
for if_test in reversed(potential_ifs):
if search_name.start_pos > if_test.end_pos:
return _check_isinstance_type(context, if_test, search_name)
- return result
-
-
+ return result
+
+
def _check_isinstance_type(context, element, search_name):
- try:
+ try:
assert element.type in ('power', 'atom_expr')
- # this might be removed if we analyze and, etc
- assert len(element.children) == 2
- first, trailer = element.children
+ # this might be removed if we analyze and, etc
+ assert len(element.children) == 2
+ first, trailer = element.children
assert first.type == 'name' and first.value == 'isinstance'
- assert trailer.type == 'trailer' and trailer.children[0] == '('
- assert len(trailer.children) == 3
-
- # arglist stuff
- arglist = trailer.children[1]
+ assert trailer.type == 'trailer' and trailer.children[0] == '('
+ assert len(trailer.children) == 3
+
+ # arglist stuff
+ arglist = trailer.children[1]
args = TreeArguments(context.evaluator, context, arglist, trailer)
param_list = list(args.unpack())
- # Disallow keyword arguments
+ # Disallow keyword arguments
assert len(param_list) == 2
(key1, lazy_context_object), (key2, lazy_context_cls) = param_list
assert key1 is None and key2 is None
call = helpers.call_of_leaf(search_name)
is_instance_call = helpers.call_of_leaf(lazy_context_object.data)
- # Do a simple get_code comparison. They should just have the same code,
- # and everything will be all right.
+ # Do a simple get_code comparison. They should just have the same code,
+ # and everything will be all right.
normalize = context.evaluator.grammar._normalize
assert normalize(is_instance_call) == normalize(call)
- except AssertionError:
+ except AssertionError:
return None
-
+
context_set = ContextSet()
for cls_or_tup in lazy_context_cls.infer():
if isinstance(cls_or_tup, iterable.Sequence) and cls_or_tup.array_type == 'tuple':
diff --git a/contrib/python/jedi/jedi/evaluate/flow_analysis.py b/contrib/python/jedi/jedi/evaluate/flow_analysis.py
index 2f75cf2f87..474071f14c 100644
--- a/contrib/python/jedi/jedi/evaluate/flow_analysis.py
+++ b/contrib/python/jedi/jedi/evaluate/flow_analysis.py
@@ -1,52 +1,52 @@
from jedi.parser_utils import get_flow_branch_keyword, is_scope, get_parent_scope
from jedi.evaluate.recursion import execution_allowed
-
-
-class Status(object):
- lookup_table = {}
-
- def __init__(self, value, name):
- self._value = value
- self._name = name
- Status.lookup_table[value] = self
-
- def invert(self):
- if self is REACHABLE:
- return UNREACHABLE
- elif self is UNREACHABLE:
- return REACHABLE
- else:
- return UNSURE
-
- def __and__(self, other):
- if UNSURE in (self, other):
- return UNSURE
- else:
- return REACHABLE if self._value and other._value else UNREACHABLE
-
- def __repr__(self):
- return '<%s: %s>' % (type(self).__name__, self._name)
-
-
-REACHABLE = Status(True, 'reachable')
-UNREACHABLE = Status(False, 'unreachable')
-UNSURE = Status(None, 'unsure')
-
-
+
+
+class Status(object):
+ lookup_table = {}
+
+ def __init__(self, value, name):
+ self._value = value
+ self._name = name
+ Status.lookup_table[value] = self
+
+ def invert(self):
+ if self is REACHABLE:
+ return UNREACHABLE
+ elif self is UNREACHABLE:
+ return REACHABLE
+ else:
+ return UNSURE
+
+ def __and__(self, other):
+ if UNSURE in (self, other):
+ return UNSURE
+ else:
+ return REACHABLE if self._value and other._value else UNREACHABLE
+
+ def __repr__(self):
+ return '<%s: %s>' % (type(self).__name__, self._name)
+
+
+REACHABLE = Status(True, 'reachable')
+UNREACHABLE = Status(False, 'unreachable')
+UNSURE = Status(None, 'unsure')
+
+
def _get_flow_scopes(node):
while True:
node = get_parent_scope(node, include_flows=True)
if node is None or is_scope(node):
return
yield node
-
-
+
+
def reachability_check(context, context_scope, node, origin_scope=None):
first_flow_scope = get_parent_scope(node, include_flows=True)
if origin_scope is not None:
origin_flow_scopes = list(_get_flow_scopes(origin_scope))
node_flow_scopes = list(_get_flow_scopes(node))
-
+
branch_matches = True
for flow_scope in origin_flow_scopes:
if flow_scope in node_flow_scopes:
@@ -79,32 +79,32 @@ def reachability_check(context, context_scope, node, origin_scope=None):
def _break_check(context, context_scope, flow_scope, node):
- reachable = REACHABLE
+ reachable = REACHABLE
if flow_scope.type == 'if_stmt':
if flow_scope.is_node_after_else(node):
for check_node in flow_scope.get_test_nodes():
reachable = _check_if(context, check_node)
- if reachable in (REACHABLE, UNSURE):
- break
- reachable = reachable.invert()
- else:
+ if reachable in (REACHABLE, UNSURE):
+ break
+ reachable = reachable.invert()
+ else:
flow_node = flow_scope.get_corresponding_test_node(node)
if flow_node is not None:
reachable = _check_if(context, flow_node)
elif flow_scope.type in ('try_stmt', 'while_stmt'):
- return UNSURE
-
- # Only reachable branches need to be examined further.
- if reachable in (UNREACHABLE, UNSURE):
- return reachable
-
+ return UNSURE
+
+ # Only reachable branches need to be examined further.
+ if reachable in (UNREACHABLE, UNSURE):
+ return reachable
+
if context_scope != flow_scope and context_scope != flow_scope.parent:
flow_scope = get_parent_scope(flow_scope, include_flows=True)
return reachable & _break_check(context, context_scope, flow_scope, node)
else:
return reachable
-
-
+
+
def _check_if(context, node):
with execution_allowed(context.evaluator, node) as allowed:
if not allowed:
diff --git a/contrib/python/jedi/jedi/evaluate/helpers.py b/contrib/python/jedi/jedi/evaluate/helpers.py
index 989e3676bd..c94a1fbe55 100644
--- a/contrib/python/jedi/jedi/evaluate/helpers.py
+++ b/contrib/python/jedi/jedi/evaluate/helpers.py
@@ -1,27 +1,27 @@
-import copy
+import copy
import sys
import re
import os
-from itertools import chain
+from itertools import chain
from contextlib import contextmanager
-
+
from parso.python import tree
-
+
from jedi._compatibility import unicode
from jedi.parser_utils import get_parent_scope
-
-
+
+
def is_stdlib_path(path):
# Python standard library paths look like this:
# /usr/lib/python3.5/...
# TODO The implementation below is probably incorrect and not complete.
if 'dist-packages' in path or 'site-packages' in path:
return False
-
+
base_path = os.path.join(sys.prefix, 'lib', 'python')
return bool(re.match(re.escape(base_path) + r'\d.\d', path))
-
-
+
+
def deep_ast_copy(obj):
"""
Much, much faster than copy.deepcopy, but just for parser tree nodes.
@@ -35,25 +35,25 @@ def deep_ast_copy(obj):
if isinstance(child, tree.Leaf):
new_child = copy.copy(child)
new_child.parent = new_obj
- else:
+ else:
new_child = deep_ast_copy(child)
new_child.parent = new_obj
new_children.append(new_child)
new_obj.children = new_children
-
- return new_obj
-
-
+
+ return new_obj
+
+
def evaluate_call_of_leaf(context, leaf, cut_own_trailer=False):
- """
- Creates a "call" node that consist of all ``trailer`` and ``power``
- objects. E.g. if you call it with ``append``::
-
- list([]).append(3) or None
-
- You would get a node with the content ``list([]).append`` back.
-
- This generates a copy of the original ast node.
+ """
+ Creates a "call" node that consist of all ``trailer`` and ``power``
+ objects. E.g. if you call it with ``append``::
+
+ list([]).append(3) or None
+
+ You would get a node with the content ``list([]).append`` back.
+
+ This generates a copy of the original ast node.
If you're using the leaf, e.g. the bracket `)` it will return ``list([])``.
@@ -62,12 +62,12 @@ def evaluate_call_of_leaf(context, leaf, cut_own_trailer=False):
- infer the type of ``foo`` to offer completions after foo
- infer the type of ``bar`` to be able to jump to the definition of foo
The option ``cut_own_trailer`` must be set to true for the second purpose.
- """
+ """
trailer = leaf.parent
if trailer.type == 'fstring':
from jedi.evaluate import compiled
return compiled.get_string_context_set(context.evaluator)
-
+
# The leaf may not be the last or first child, because there exist three
# different trailers: `( x )`, `[ x ]` and `.x`. In the first two examples
# we should not match anything more than x.
@@ -75,14 +75,14 @@ def evaluate_call_of_leaf(context, leaf, cut_own_trailer=False):
if trailer.type == 'atom':
return context.eval_node(trailer)
return context.eval_node(leaf)
-
+
power = trailer.parent
index = power.children.index(trailer)
if cut_own_trailer:
cut = index
else:
cut = index + 1
-
+
if power.type == 'error_node':
start = index
while True:
@@ -94,7 +94,7 @@ def evaluate_call_of_leaf(context, leaf, cut_own_trailer=False):
else:
base = power.children[0]
trailers = power.children[1:cut]
-
+
if base == 'await':
base = trailers[0]
trailers = trailers[1:]
@@ -161,11 +161,11 @@ def get_names_of_node(node):
return list(chain.from_iterable(get_names_of_node(c) for c in children))
-def get_module_names(module, all_scopes):
- """
- Returns a dictionary with name parts as keys and their call paths as
- values.
- """
+def get_module_names(module, all_scopes):
+ """
+ Returns a dictionary with name parts as keys and their call paths as
+ values.
+ """
names = chain.from_iterable(module.get_used_names().values())
if not all_scopes:
# We have to filter all the names that don't have the module as a
@@ -194,42 +194,42 @@ def is_compiled(context):
def is_string(context):
if context.evaluator.environment.version_info.major == 2:
str_classes = (unicode, bytes)
- else:
+ else:
str_classes = (unicode,)
return is_compiled(context) and isinstance(context.get_safe_value(default=None), str_classes)
-
-
+
+
def is_literal(context):
return is_number(context) or is_string(context)
-
-
+
+
def _get_safe_value_or_none(context, accept):
if is_compiled(context):
value = context.get_safe_value(default=None)
if isinstance(value, accept):
return value
-
-
+
+
def get_int_or_none(context):
return _get_safe_value_or_none(context, int)
-
-
+
+
def is_number(context):
return _get_safe_value_or_none(context, (int, float)) is not None
-
-
+
+
class EvaluatorTypeError(Exception):
pass
-
-
+
+
class EvaluatorIndexError(Exception):
pass
-
-
+
+
class EvaluatorKeyError(Exception):
pass
-
-
+
+
@contextmanager
def reraise_as_evaluator(*exception_classes):
try:
diff --git a/contrib/python/jedi/jedi/evaluate/imports.py b/contrib/python/jedi/jedi/evaluate/imports.py
index 690d93cd1e..3b1df31a44 100644
--- a/contrib/python/jedi/jedi/evaluate/imports.py
+++ b/contrib/python/jedi/jedi/evaluate/imports.py
@@ -1,57 +1,57 @@
-"""
-:mod:`jedi.evaluate.imports` is here to resolve import statements and return
-the modules/classes/functions/whatever, which they stand for. However there's
-not any actual importing done. This module is about finding modules in the
-filesystem. This can be quite tricky sometimes, because Python imports are not
-always that simple.
-
-This module uses imp for python up to 3.2 and importlib for python 3.3 on; the
-correct implementation is delegated to _compatibility.
-
-This module also supports import autocompletion, which means to complete
+"""
+:mod:`jedi.evaluate.imports` is here to resolve import statements and return
+the modules/classes/functions/whatever, which they stand for. However there's
+not any actual importing done. This module is about finding modules in the
+filesystem. This can be quite tricky sometimes, because Python imports are not
+always that simple.
+
+This module uses imp for python up to 3.2 and importlib for python 3.3 on; the
+correct implementation is delegated to _compatibility.
+
+This module also supports import autocompletion, which means to complete
statements like ``from datetim`` (cursor at the end would return ``datetime``).
-"""
-import os
-
+"""
+import os
+
from parso.python import tree
from parso.tree import search_ancestor
from parso import python_bytes_to_unicode
from jedi._compatibility import (FileNotFoundError, ImplicitNSInfo,
force_unicode, unicode)
-from jedi import debug
+from jedi import debug
from jedi import settings
from jedi.parser_utils import get_cached_code_lines
-from jedi.evaluate import sys_path
-from jedi.evaluate import helpers
-from jedi.evaluate import compiled
-from jedi.evaluate import analysis
+from jedi.evaluate import sys_path
+from jedi.evaluate import helpers
+from jedi.evaluate import compiled
+from jedi.evaluate import analysis
from jedi.evaluate.utils import unite
from jedi.evaluate.cache import evaluator_method_cache
from jedi.evaluate.filters import AbstractNameDefinition
from jedi.evaluate.base_context import ContextSet, NO_CONTEXTS
-
-
+
+
class ModuleCache(object):
def __init__(self):
self._path_cache = {}
self._name_cache = {}
-
+
def add(self, module, name):
path = module.py__file__()
self._path_cache[path] = module
self._name_cache[name] = module
-
+
def iterate_modules_with_names(self):
return self._name_cache.items()
-
+
def get(self, name):
return self._name_cache[name]
-
+
def get_from_path(self, path):
return self._path_cache[path]
-
-
+
+
# This memoization is needed, because otherwise we will infinitely loop on
# certain imports.
@evaluator_method_cache(default=NO_CONTEXTS)
@@ -72,18 +72,18 @@ def infer_import(context, tree_name, is_goto=False):
# if from_names exists in the modules.
from_import_name = import_path[-1]
import_path = from_names
-
+
importer = Importer(evaluator, tuple(import_path),
module_context, import_node.level)
-
+
types = importer.follow()
-
+
#if import_node.is_nested() and not self.nested_resolve:
# scopes = [NestedImportModule(module, import_node)]
-
+
if not types:
return NO_CONTEXTS
-
+
if from_import_name is not None:
types = unite(
t.py__getattribute__(
@@ -96,7 +96,7 @@ def infer_import(context, tree_name, is_goto=False):
)
if not is_goto:
types = ContextSet.from_set(types)
-
+
if not types:
path = import_path + [from_import_name]
importer = Importer(evaluator, tuple(path),
@@ -109,62 +109,62 @@ def infer_import(context, tree_name, is_goto=False):
# goto only accepts `Name`
if is_goto:
types = set(s.name for s in types)
-
+
debug.dbg('after import: %s', types)
return types
-
-
-class NestedImportModule(tree.Module):
- """
- TODO while there's no use case for nested import module right now, we might
- be able to use them for static analysis checks later on.
- """
- def __init__(self, module, nested_import):
- self._module = module
- self._nested_import = nested_import
-
- def _get_nested_import_name(self):
- """
- Generates an Import statement, that can be used to fake nested imports.
- """
- i = self._nested_import
- # This is not an existing Import statement. Therefore, set position to
- # 0 (0 is not a valid line number).
- zero = (0, 0)
- names = [unicode(name) for name in i.namespace_names[1:]]
- name = helpers.FakeName(names, self._nested_import)
- new = tree.Import(i._sub_module, zero, zero, name)
- new.parent = self._module
- debug.dbg('Generated a nested import: %s', new)
- return helpers.FakeName(str(i.namespace_names[1]), new)
-
- def __getattr__(self, name):
- return getattr(self._module, name)
-
- def __repr__(self):
- return "<%s: %s of %s>" % (self.__class__.__name__, self._module,
- self._nested_import)
-
-
+
+
+class NestedImportModule(tree.Module):
+ """
+ TODO while there's no use case for nested import module right now, we might
+ be able to use them for static analysis checks later on.
+ """
+ def __init__(self, module, nested_import):
+ self._module = module
+ self._nested_import = nested_import
+
+ def _get_nested_import_name(self):
+ """
+ Generates an Import statement, that can be used to fake nested imports.
+ """
+ i = self._nested_import
+ # This is not an existing Import statement. Therefore, set position to
+ # 0 (0 is not a valid line number).
+ zero = (0, 0)
+ names = [unicode(name) for name in i.namespace_names[1:]]
+ name = helpers.FakeName(names, self._nested_import)
+ new = tree.Import(i._sub_module, zero, zero, name)
+ new.parent = self._module
+ debug.dbg('Generated a nested import: %s', new)
+ return helpers.FakeName(str(i.namespace_names[1]), new)
+
+ def __getattr__(self, name):
+ return getattr(self._module, name)
+
+ def __repr__(self):
+ return "<%s: %s of %s>" % (self.__class__.__name__, self._module,
+ self._nested_import)
+
+
def _add_error(context, name, message=None):
# Should be a name, not a string!
if message is None:
name_str = str(name.value) if isinstance(name, tree.Name) else name
message = 'No module named ' + name_str
- if hasattr(name, 'parent'):
+ if hasattr(name, 'parent'):
analysis.add(context, 'import-error', name, message)
else:
debug.warning('ImportError without origin: ' + message)
-
-
+
+
class ImportName(AbstractNameDefinition):
start_pos = (1, 0)
_level = 0
-
+
def __init__(self, parent_context, string_name):
self.parent_context = parent_context
self.string_name = string_name
-
+
def infer(self):
return Importer(
self.parent_context.evaluator,
@@ -189,35 +189,35 @@ class SubModuleName(ImportName):
_level = 1
-class Importer(object):
+class Importer(object):
def __init__(self, evaluator, import_path, module_context, level=0):
- """
- An implementation similar to ``__import__``. Use `follow`
- to actually follow the imports.
-
- *level* specifies whether to use absolute or relative imports. 0 (the
- default) means only perform absolute imports. Positive values for level
- indicate the number of parent directories to search relative to the
- directory of the module calling ``__import__()`` (see PEP 328 for the
- details).
-
- :param import_path: List of namespaces (strings or Names).
- """
- debug.speed('import %s' % (import_path,))
- self._evaluator = evaluator
- self.level = level
+ """
+ An implementation similar to ``__import__``. Use `follow`
+ to actually follow the imports.
+
+ *level* specifies whether to use absolute or relative imports. 0 (the
+ default) means only perform absolute imports. Positive values for level
+ indicate the number of parent directories to search relative to the
+ directory of the module calling ``__import__()`` (see PEP 328 for the
+ details).
+
+ :param import_path: List of namespaces (strings or Names).
+ """
+ debug.speed('import %s' % (import_path,))
+ self._evaluator = evaluator
+ self.level = level
self.module_context = module_context
- try:
+ try:
self.file_path = module_context.py__file__()
- except AttributeError:
- # Can be None for certain compiled modules like 'builtins'.
- self.file_path = None
-
- if level:
+ except AttributeError:
+ # Can be None for certain compiled modules like 'builtins'.
+ self.file_path = None
+
+ if level:
base = module_context.py__package__().split('.')
if base == [''] or base == ['__main__']:
- base = []
- if level > len(base):
+ base = []
+ if level > len(base):
path = module_context.py__file__()
if path is not None:
import_path = list(import_path)
@@ -246,64 +246,64 @@ class Importer(object):
# are in the file system. Therefore we cannot know what to do.
# In this case we just let the path there and ignore that it's
# a relative path. Not sure if that's a good idea.
- else:
- # Here we basically rewrite the level to 0.
+ else:
+ # Here we basically rewrite the level to 0.
base = tuple(base)
if level > 1:
base = base[:-level + 1]
import_path = base + tuple(import_path)
- self.import_path = import_path
-
- @property
- def str_import_path(self):
- """Returns the import path as pure strings instead of `Name`."""
+ self.import_path = import_path
+
+ @property
+ def str_import_path(self):
+ """Returns the import path as pure strings instead of `Name`."""
return tuple(
name.value if isinstance(name, tree.Name) else name
for name in self.import_path
)
-
- def sys_path_with_modifications(self):
-
+
+ def sys_path_with_modifications(self):
+
sys_path_mod = (
self._evaluator.get_sys_path()
+ sys_path.check_sys_path_modifications(self.module_context)
)
-
+
if self.import_path and self.file_path is not None \
and self._evaluator.environment.version_info.major == 2:
# Python2 uses an old strange way of importing relative imports.
sys_path_mod.append(force_unicode(os.path.dirname(self.file_path)))
-
+
return sys_path_mod
- def follow(self):
+ def follow(self):
if not self.import_path or not self._evaluator.infer_enabled:
return NO_CONTEXTS
- return self._do_import(self.import_path, self.sys_path_with_modifications())
-
- def _do_import(self, import_path, sys_path):
- """
- This method is very similar to importlib's `_gcd_import`.
- """
+ return self._do_import(self.import_path, self.sys_path_with_modifications())
+
+ def _do_import(self, import_path, sys_path):
+ """
+ This method is very similar to importlib's `_gcd_import`.
+ """
import_parts = [
force_unicode(i.value if isinstance(i, tree.Name) else i)
for i in import_path
]
-
- # Handle "magic" Flask extension imports:
- # ``flask.ext.foo`` is really ``flask_foo`` or ``flaskext.foo``.
- if len(import_path) > 2 and import_parts[:2] == ['flask', 'ext']:
- # New style.
- ipath = ('flask_' + str(import_parts[2]),) + import_path[3:]
- modules = self._do_import(ipath, sys_path)
- if modules:
- return modules
- else:
- # Old style
- return self._do_import(('flaskext',) + import_path[2:], sys_path)
-
+
+ # Handle "magic" Flask extension imports:
+ # ``flask.ext.foo`` is really ``flask_foo`` or ``flaskext.foo``.
+ if len(import_path) > 2 and import_parts[:2] == ['flask', 'ext']:
+ # New style.
+ ipath = ('flask_' + str(import_parts[2]),) + import_path[3:]
+ modules = self._do_import(ipath, sys_path)
+ if modules:
+ return modules
+ else:
+ # Old style
+ return self._do_import(('flaskext',) + import_path[2:], sys_path)
+
if import_parts[0] in settings.auto_import_modules:
module = _load_module(
self._evaluator,
@@ -312,42 +312,42 @@ class Importer(object):
)
return ContextSet(module)
- module_name = '.'.join(import_parts)
- try:
+ module_name = '.'.join(import_parts)
+ try:
return ContextSet(self._evaluator.module_cache.get(module_name))
- except KeyError:
- pass
-
- if len(import_path) > 1:
- # This is a recursive way of importing that works great with
- # the module cache.
- bases = self._do_import(import_path[:-1], sys_path)
- if not bases:
+ except KeyError:
+ pass
+
+ if len(import_path) > 1:
+ # This is a recursive way of importing that works great with
+ # the module cache.
+ bases = self._do_import(import_path[:-1], sys_path)
+ if not bases:
return NO_CONTEXTS
- # We can take the first element, because only the os special
- # case yields multiple modules, which is not important for
- # further imports.
+ # We can take the first element, because only the os special
+ # case yields multiple modules, which is not important for
+ # further imports.
parent_module = list(bases)[0]
-
- # This is a huge exception, we follow a nested import
- # ``os.path``, because it's a very important one in Python
- # that is being achieved by messing with ``sys.modules`` in
- # ``os``.
+
+ # This is a huge exception, we follow a nested import
+ # ``os.path``, because it's a very important one in Python
+ # that is being achieved by messing with ``sys.modules`` in
+ # ``os``.
if import_parts == ['os', 'path']:
return parent_module.py__getattribute__('path')
-
- try:
+
+ try:
method = parent_module.py__path__
- except AttributeError:
- # The module is not a package.
+ except AttributeError:
+ # The module is not a package.
_add_error(self.module_context, import_path[-1])
return NO_CONTEXTS
- else:
+ else:
paths = method()
- debug.dbg('search_module %s in paths %s', module_name, paths)
- for path in paths:
- # At the moment we are only using one path. So this is
- # not important to be correct.
+ debug.dbg('search_module %s in paths %s', module_name, paths)
+ for path in paths:
+ # At the moment we are only using one path. So this is
+ # not important to be correct.
if not isinstance(path, list):
path = [path]
code, module_path, is_pkg = self._evaluator.compiled_subprocess.get_module_info(
@@ -357,11 +357,11 @@ class Importer(object):
is_global_search=False,
)
if module_path is not None:
- break
+ break
else:
_add_error(self.module_context, import_path[-1])
return NO_CONTEXTS
- else:
+ else:
debug.dbg('global search_module %s in %s', import_parts[-1], self.file_path)
# Override the sys.path. It works only good that way.
# Injecting the path directly into `find_module` did not work.
@@ -372,111 +372,111 @@ class Importer(object):
is_global_search=True,
)
if module_path is None:
- # The module is not a package.
+ # The module is not a package.
_add_error(self.module_context, import_path[-1])
return NO_CONTEXTS
-
+
module = _load_module(
self._evaluator, module_path, code, sys_path,
import_names=import_parts,
safe_module_name=True,
)
-
+
if module is None:
# The file might raise an ImportError e.g. and therefore not be
# importable.
return NO_CONTEXTS
-
+
return ContextSet(module)
-
+
def _generate_name(self, name, in_module=None):
# Create a pseudo import to be able to follow them.
if in_module is None:
return ImportName(self.module_context, name)
return SubModuleName(in_module, name)
-
+
def _get_module_names(self, search_path=None, in_module=None):
- """
- Get the names of all modules in the search_path. This means file names
- and not names defined in the files.
- """
+ """
+ Get the names of all modules in the search_path. This means file names
+ and not names defined in the files.
+ """
sub = self._evaluator.compiled_subprocess
-
- names = []
- # add builtin module names
+
+ names = []
+ # add builtin module names
if search_path is None and in_module is None:
names += [self._generate_name(name) for name in sub.get_builtin_module_names()]
-
- if search_path is None:
- search_path = self.sys_path_with_modifications()
+
+ if search_path is None:
+ search_path = self.sys_path_with_modifications()
for name in sub.list_module_names(search_path):
names.append(self._generate_name(name, in_module=in_module))
- return names
-
- def completion_names(self, evaluator, only_modules=False):
- """
- :param only_modules: Indicates wheter it's possible to import a
- definition that is not defined in a module.
- """
+ return names
+
+ def completion_names(self, evaluator, only_modules=False):
+ """
+ :param only_modules: Indicates wheter it's possible to import a
+ definition that is not defined in a module.
+ """
from jedi.evaluate.context import ModuleContext
from jedi.evaluate.context.namespace import ImplicitNamespaceContext
- names = []
- if self.import_path:
- # flask
- if self.str_import_path == ('flask', 'ext'):
- # List Flask extensions like ``flask_foo``
- for mod in self._get_module_names():
+ names = []
+ if self.import_path:
+ # flask
+ if self.str_import_path == ('flask', 'ext'):
+ # List Flask extensions like ``flask_foo``
+ for mod in self._get_module_names():
modname = mod.string_name
- if modname.startswith('flask_'):
- extname = modname[len('flask_'):]
- names.append(self._generate_name(extname))
- # Now the old style: ``flaskext.foo``
- for dir in self.sys_path_with_modifications():
- flaskext = os.path.join(dir, 'flaskext')
- if os.path.isdir(flaskext):
- names += self._get_module_names([flaskext])
-
+ if modname.startswith('flask_'):
+ extname = modname[len('flask_'):]
+ names.append(self._generate_name(extname))
+ # Now the old style: ``flaskext.foo``
+ for dir in self.sys_path_with_modifications():
+ flaskext = os.path.join(dir, 'flaskext')
+ if os.path.isdir(flaskext):
+ names += self._get_module_names([flaskext])
+
for context in self.follow():
- # Non-modules are not completable.
+ # Non-modules are not completable.
if context.api_type != 'module': # not a module
- continue
- # namespace packages
+ continue
+ # namespace packages
if isinstance(context, ModuleContext) and context.py__file__().endswith('__init__.py'):
paths = context.py__path__()
names += self._get_module_names(paths, in_module=context)
-
+
# implicit namespace packages
elif isinstance(context, ImplicitNamespaceContext):
paths = context.paths
names += self._get_module_names(paths, in_module=context)
- if only_modules:
- # In the case of an import like `from x.` we don't need to
- # add all the variables.
- if ('os',) == self.str_import_path and not self.level:
- # os.path is a hardcoded exception, because it's a
- # ``sys.modules`` modification.
+ if only_modules:
+ # In the case of an import like `from x.` we don't need to
+ # add all the variables.
+ if ('os',) == self.str_import_path and not self.level:
+ # os.path is a hardcoded exception, because it's a
+ # ``sys.modules`` modification.
names.append(self._generate_name('path', context))
-
- continue
-
+
+ continue
+
for filter in context.get_filters(search_global=False):
names += filter.values()
- else:
- # Empty import path=completion after import
- if not self.level:
- names += self._get_module_names()
-
- if self.file_path is not None:
- path = os.path.abspath(self.file_path)
- for i in range(self.level - 1):
- path = os.path.dirname(path)
- names += self._get_module_names([path])
-
- return names
-
-
+ else:
+ # Empty import path=completion after import
+ if not self.level:
+ names += self._get_module_names()
+
+ if self.file_path is not None:
+ path = os.path.abspath(self.file_path)
+ for i in range(self.level - 1):
+ path = os.path.dirname(path)
+ names += self._get_module_names([path])
+
+ return names
+
+
def _load_module(evaluator, path=None, code=None, sys_path=None,
import_names=None, safe_module_name=False):
if import_names is None:
@@ -515,30 +515,30 @@ def _load_module(evaluator, path=None, code=None, sys_path=None,
path=path,
code_lines=get_cached_code_lines(evaluator.grammar, path),
)
- else:
+ else:
assert dotted_name is not None
module = compiled.load_module(evaluator, dotted_name=dotted_name, sys_path=sys_path)
-
+
if module is not None and dotted_name is not None:
add_module_to_cache(evaluator, dotted_name, module, safe=safe_module_name)
- return module
-
-
+ return module
+
+
def add_module_to_cache(evaluator, module_name, module, safe=False):
if not safe and '.' not in module_name:
- # We cannot add paths with dots, because that would collide with
- # the sepatator dots for nested packages. Therefore we return
- # `__main__` in ModuleWrapper.py__name__(), which is similar to
- # Python behavior.
+ # We cannot add paths with dots, because that would collide with
+ # the sepatator dots for nested packages. Therefore we return
+ # `__main__` in ModuleWrapper.py__name__(), which is similar to
+ # Python behavior.
return
evaluator.module_cache.add(module, module_name)
-
-
+
+
def get_modules_containing_name(evaluator, modules, name):
- """
- Search a name in the directories of modules.
- """
+ """
+ Search a name in the directories of modules.
+ """
def check_directories(paths):
for p in paths:
if p is not None:
@@ -549,8 +549,8 @@ def get_modules_containing_name(evaluator, modules, name):
path = os.path.join(d, file_name)
if file_name.endswith('.py'):
yield path
-
- def check_fs(path):
+
+ def check_fs(path):
try:
f = open(path, 'rb')
except FileNotFoundError:
@@ -565,9 +565,9 @@ def get_modules_containing_name(evaluator, modules, name):
sys_path=e_sys_path,
import_names=import_names,
)
- return module
-
- # skip non python modules
+ return module
+
+ # skip non python modules
used_mod_paths = set()
for m in modules:
try:
@@ -576,11 +576,11 @@ def get_modules_containing_name(evaluator, modules, name):
pass
else:
used_mod_paths.add(path)
- yield m
-
+ yield m
+
if not settings.dynamic_params_for_other_modules:
return
-
+
additional = set(os.path.abspath(p) for p in settings.additional_dynamic_modules)
# Check the directories of used modules.
paths = (additional | set(check_directories(used_mod_paths))) \
diff --git a/contrib/python/jedi/jedi/evaluate/param.py b/contrib/python/jedi/jedi/evaluate/param.py
index c6bd8376f5..84f281e532 100644
--- a/contrib/python/jedi/jedi/evaluate/param.py
+++ b/contrib/python/jedi/jedi/evaluate/param.py
@@ -1,74 +1,74 @@
-from collections import defaultdict
-
+from collections import defaultdict
+
from jedi.evaluate.utils import PushBackIterator
-from jedi.evaluate import analysis
+from jedi.evaluate import analysis
from jedi.evaluate.lazy_context import LazyKnownContext, \
LazyTreeContext, LazyUnknownContext
from jedi.evaluate import docstrings
from jedi.evaluate import pep0484
from jedi.evaluate.context import iterable
-
-
+
+
def _add_argument_issue(parent_context, error_name, lazy_context, message):
if isinstance(lazy_context, LazyTreeContext):
node = lazy_context.data
if node.parent.type == 'argument':
node = node.parent
analysis.add(parent_context, error_name, node, message)
-
-
+
+
class ExecutedParam(object):
- """Fake a param and give it values."""
+ """Fake a param and give it values."""
def __init__(self, execution_context, param_node, lazy_context):
self._execution_context = execution_context
self._param_node = param_node
self._lazy_context = lazy_context
self.string_name = param_node.name.value
-
+
def infer(self):
pep0484_hints = pep0484.infer_param(self._execution_context, self._param_node)
doc_params = docstrings.infer_param(self._execution_context, self._param_node)
if pep0484_hints or doc_params:
return pep0484_hints | doc_params
-
+
return self._lazy_context.infer()
-
- @property
+
+ @property
def var_args(self):
return self._execution_context.var_args
-
+
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self.string_name)
-
-
+
+
def get_executed_params(execution_context, var_args):
result_params = []
param_dict = {}
funcdef = execution_context.tree_node
parent_context = execution_context.parent_context
-
+
for param in funcdef.get_params():
param_dict[param.name.value] = param
unpacked_va = list(var_args.unpack(funcdef))
var_arg_iterator = PushBackIterator(iter(unpacked_va))
-
- non_matching_keys = defaultdict(lambda: [])
- keys_used = {}
- keys_only = False
- had_multiple_value_error = False
+
+ non_matching_keys = defaultdict(lambda: [])
+ keys_used = {}
+ keys_only = False
+ had_multiple_value_error = False
for param in funcdef.get_params():
- # The value and key can both be null. There, the defaults apply.
- # args / kwargs will just be empty arrays / dicts, respectively.
- # Wrong value count is just ignored. If you try to test cases that are
- # not allowed in Python, Jedi will maybe not show any completions.
+ # The value and key can both be null. There, the defaults apply.
+ # args / kwargs will just be empty arrays / dicts, respectively.
+ # Wrong value count is just ignored. If you try to test cases that are
+ # not allowed in Python, Jedi will maybe not show any completions.
key, argument = next(var_arg_iterator, (None, None))
- while key is not None:
- keys_only = True
- try:
+ while key is not None:
+ keys_only = True
+ try:
key_param = param_dict[key]
- except KeyError:
+ except KeyError:
non_matching_keys[key] = argument
- else:
+ else:
if key in keys_used:
had_multiple_value_error = True
m = ("TypeError: %s() got multiple values for keyword argument '%s'."
@@ -79,15 +79,15 @@ def get_executed_params(execution_context, var_args):
else:
keys_used[key] = ExecutedParam(execution_context, key_param, argument)
key, argument = next(var_arg_iterator, (None, None))
-
+
try:
result_params.append(keys_used[param.name.value])
continue
except KeyError:
pass
-
+
if param.star_count == 1:
- # *args param
+ # *args param
lazy_context_list = []
if argument is not None:
lazy_context_list.append(argument)
@@ -100,12 +100,12 @@ def get_executed_params(execution_context, var_args):
seq = iterable.FakeSequence(execution_context.evaluator, u'tuple', lazy_context_list)
result_arg = LazyKnownContext(seq)
elif param.star_count == 2:
- # **kwargs param
+ # **kwargs param
dct = iterable.FakeDict(execution_context.evaluator, dict(non_matching_keys))
result_arg = LazyKnownContext(dct)
- non_matching_keys = {}
- else:
- # normal param
+ non_matching_keys = {}
+ else:
+ # normal param
if argument is None:
# No value: Return an empty container
if param.default is None:
@@ -117,30 +117,30 @@ def get_executed_params(execution_context, var_args):
node, message=m)
else:
result_arg = LazyTreeContext(parent_context, param.default)
- else:
+ else:
result_arg = argument
-
+
result_params.append(ExecutedParam(execution_context, param, result_arg))
if not isinstance(result_arg, LazyUnknownContext):
keys_used[param.name.value] = result_params[-1]
-
- if keys_only:
- # All arguments should be handed over to the next function. It's not
- # about the values inside, it's about the names. Jedi needs to now that
- # there's nothing to find for certain names.
- for k in set(param_dict) - set(keys_used):
- param = param_dict[k]
-
+
+ if keys_only:
+ # All arguments should be handed over to the next function. It's not
+ # about the values inside, it's about the names. Jedi needs to now that
+ # there's nothing to find for certain names.
+ for k in set(param_dict) - set(keys_used):
+ param = param_dict[k]
+
if not (non_matching_keys or had_multiple_value_error or
param.star_count or param.default):
- # add a warning only if there's not another one.
+ # add a warning only if there's not another one.
for node in var_args.get_calling_nodes():
m = _error_argument_count(funcdef, len(unpacked_va))
analysis.add(parent_context, 'type-error-too-few-arguments',
node, message=m)
-
+
for key, lazy_context in non_matching_keys.items():
- m = "TypeError: %s() got an unexpected keyword argument '%s'." \
+ m = "TypeError: %s() got an unexpected keyword argument '%s'." \
% (funcdef.name, key)
_add_argument_issue(
parent_context,
@@ -148,31 +148,31 @@ def get_executed_params(execution_context, var_args):
lazy_context,
message=m
)
-
+
remaining_arguments = list(var_arg_iterator)
if remaining_arguments:
m = _error_argument_count(funcdef, len(unpacked_va))
- # Just report an error for the first param that is not needed (like
- # cPython).
+ # Just report an error for the first param that is not needed (like
+ # cPython).
first_key, lazy_context = remaining_arguments[0]
if var_args.get_calling_nodes():
# There might not be a valid calling node so check for that first.
_add_argument_issue(parent_context, 'type-error-too-many-arguments', lazy_context, message=m)
return result_params
-
-
+
+
def _error_argument_count(funcdef, actual_count):
params = funcdef.get_params()
default_arguments = sum(1 for p in params if p.default or p.star_count)
if default_arguments == 0:
before = 'exactly '
- else:
+ else:
before = 'from %s to ' % (len(params) - default_arguments)
return ('TypeError: %s() takes %s%s arguments (%s given).'
% (funcdef.name, before, len(params), actual_count))
-
-
+
+
def _create_default_param(execution_context, param):
if param.star_count == 1:
result_arg = LazyKnownContext(
@@ -184,11 +184,11 @@ def _create_default_param(execution_context, param):
)
elif param.default is None:
result_arg = LazyUnknownContext()
- else:
+ else:
result_arg = LazyTreeContext(execution_context.parent_context, param.default)
return ExecutedParam(execution_context, param, result_arg)
-
-
+
+
def create_default_params(execution_context, funcdef):
return [_create_default_param(execution_context, p)
for p in funcdef.get_params()]
diff --git a/contrib/python/jedi/jedi/evaluate/recursion.py b/contrib/python/jedi/jedi/evaluate/recursion.py
index 0223c47291..1f4f6384e9 100644
--- a/contrib/python/jedi/jedi/evaluate/recursion.py
+++ b/contrib/python/jedi/jedi/evaluate/recursion.py
@@ -1,37 +1,37 @@
-"""
-Recursions are the recipe of |jedi| to conquer Python code. However, someone
-must stop recursions going mad. Some settings are here to make |jedi| stop at
-the right time. You can read more about them :ref:`here <settings-recursion>`.
-
-Next to :mod:`jedi.evaluate.cache` this module also makes |jedi| not
-thread-safe. Why? ``execution_recursion_decorator`` uses class variables to
-count the function calls.
-
+"""
+Recursions are the recipe of |jedi| to conquer Python code. However, someone
+must stop recursions going mad. Some settings are here to make |jedi| stop at
+the right time. You can read more about them :ref:`here <settings-recursion>`.
+
+Next to :mod:`jedi.evaluate.cache` this module also makes |jedi| not
+thread-safe. Why? ``execution_recursion_decorator`` uses class variables to
+count the function calls.
+
.. _settings-recursion:
-
+
Settings
~~~~~~~~~~
-
+
Recursion settings are important if you don't want extremly
recursive python code to go absolutely crazy.
-
+
The default values are based on experiments while completing the |jedi| library
itself (inception!). But I don't think there's any other Python library that
uses recursion in a similarly extreme way. Completion should also be fast and
therefore the quality might not always be maximal.
-
+
.. autodata:: recursion_limit
.. autodata:: total_function_execution_limit
.. autodata:: per_function_execution_limit
.. autodata:: per_function_recursion_limit
"""
-
+
from contextlib import contextmanager
-
+
from jedi import debug
from jedi.evaluate.base_context import NO_CONTEXTS
-
-
+
+
recursion_limit = 15
"""
Like ``sys.getrecursionlimit()``, just for |jedi|.
@@ -48,13 +48,13 @@ per_function_recursion_limit = 2
"""
A function may not be executed more than this number of times recursively.
"""
-
-
+
+
class RecursionDetector(object):
def __init__(self):
self.pushed_nodes = []
-
-
+
+
@contextmanager
def execution_allowed(evaluator, node):
"""
@@ -62,7 +62,7 @@ def execution_allowed(evaluator, node):
at the same place, in the same module may not be executed two times.
"""
pushed_nodes = evaluator.recursion_detector.pushed_nodes
-
+
if node in pushed_nodes:
debug.warning('catched stmt recursion: %s @%s', node,
getattr(node, 'start_pos', None))
@@ -73,8 +73,8 @@ def execution_allowed(evaluator, node):
yield True
finally:
pushed_nodes.pop()
-
-
+
+
def execution_recursion_decorator(default=NO_CONTEXTS):
def decorator(func):
def wrapper(self, **kwargs):
@@ -90,43 +90,43 @@ def execution_recursion_decorator(default=NO_CONTEXTS):
return result
return wrapper
return decorator
-
-
-class ExecutionRecursionDetector(object):
- """
- Catches recursions of executions.
- """
+
+
+class ExecutionRecursionDetector(object):
+ """
+ Catches recursions of executions.
+ """
def __init__(self, evaluator):
self._evaluator = evaluator
-
+
self._recursion_level = 0
self._parent_execution_funcs = []
self._funcdef_execution_counts = {}
self._execution_count = 0
-
+
def pop_execution(self):
self._parent_execution_funcs.pop()
self._recursion_level -= 1
-
+
def push_execution(self, execution):
funcdef = execution.tree_node
-
+
# These two will be undone in pop_execution.
self._recursion_level += 1
self._parent_execution_funcs.append(funcdef)
-
+
module = execution.get_root_context()
if module == self._evaluator.builtins_module:
# We have control over builtins so we know they are not recursing
# like crazy. Therefore we just let them execute always, because
# they usually just help a lot with getting good results.
- return False
-
+ return False
+
if self._recursion_level > recursion_limit:
- return True
+ return True
if self._execution_count >= total_function_execution_limit:
- return True
+ return True
self._execution_count += 1
if self._funcdef_execution_counts.setdefault(funcdef, 0) >= per_function_execution_limit:
@@ -135,4 +135,4 @@ class ExecutionRecursionDetector(object):
if self._parent_execution_funcs.count(funcdef) > per_function_recursion_limit:
return True
- return False
+ return False
diff --git a/contrib/python/jedi/jedi/evaluate/stdlib.py b/contrib/python/jedi/jedi/evaluate/stdlib.py
index 5303318235..52c223838b 100644
--- a/contrib/python/jedi/jedi/evaluate/stdlib.py
+++ b/contrib/python/jedi/jedi/evaluate/stdlib.py
@@ -1,21 +1,21 @@
-"""
-Implementations of standard library functions, because it's not possible to
-understand them with Jedi.
-
-To add a new implementation, create a function and add it to the
-``_implemented`` dict at the bottom of this module.
-
+"""
+Implementations of standard library functions, because it's not possible to
+understand them with Jedi.
+
+To add a new implementation, create a function and add it to the
+``_implemented`` dict at the bottom of this module.
+
Note that this module exists only to implement very specific functionality in
the standard library. The usual way to understand the standard library is the
compiled module that returns the types for C-builtins.
-"""
+"""
import parso
-
+
from jedi._compatibility import force_unicode
from jedi import debug
from jedi.evaluate.arguments import ValuesArguments, repack_with_argument_clinic
from jedi.evaluate import analysis
-from jedi.evaluate import compiled
+from jedi.evaluate import compiled
from jedi.evaluate.context.instance import \
AbstractInstanceContext, CompiledInstance, BoundMethod, InstanceArguments
from jedi.evaluate.base_context import ContextualizedNode, \
@@ -24,7 +24,7 @@ from jedi.evaluate.context import ClassContext, ModuleContext, FunctionExecution
from jedi.evaluate.context import iterable
from jedi.evaluate.lazy_context import LazyTreeContext
from jedi.evaluate.syntax_tree import is_string
-
+
# Now this is all part of fake tuples in Jedi. However super doesn't work on
# __init__ and __new__ doesn't work at all. So adding this to nametuples is
# just the easiest way.
@@ -32,7 +32,7 @@ _NAMEDTUPLE_INIT = """
def __init__(_cls, {arg_list}):
'A helper function for namedtuple.'
self.__iterable = ({arg_list})
-
+
def __iter__(self):
for i in self.__iterable:
yield i
@@ -43,51 +43,51 @@ _NAMEDTUPLE_INIT = """
"""
-class NotInStdLib(LookupError):
- pass
-
-
+class NotInStdLib(LookupError):
+ pass
+
+
def execute(evaluator, obj, arguments):
if isinstance(obj, BoundMethod):
raise NotInStdLib()
- try:
+ try:
obj_name = obj.name.string_name
- except AttributeError:
- pass
- else:
+ except AttributeError:
+ pass
+ else:
if obj.parent_context == evaluator.builtins_module:
- module_name = 'builtins'
+ module_name = 'builtins'
elif isinstance(obj.parent_context, ModuleContext):
module_name = obj.parent_context.name.string_name
- else:
- module_name = ''
-
- # for now we just support builtin functions.
- try:
+ else:
+ module_name = ''
+
+ # for now we just support builtin functions.
+ try:
func = _implemented[module_name][obj_name]
- except KeyError:
- pass
+ except KeyError:
+ pass
else:
return func(evaluator, obj, arguments=arguments)
- raise NotInStdLib()
-
-
+ raise NotInStdLib()
+
+
def _follow_param(evaluator, arguments, index):
- try:
+ try:
key, lazy_context = list(arguments.unpack())[index]
- except IndexError:
+ except IndexError:
return NO_CONTEXTS
- else:
+ else:
return lazy_context.infer()
-
-
+
+
def argument_clinic(string, want_obj=False, want_context=False, want_arguments=False):
- """
- Works like Argument Clinic (PEP 436), to validate function params.
- """
-
- def f(func):
+ """
+ Works like Argument Clinic (PEP 436), to validate function params.
+ """
+
+ def f(func):
@repack_with_argument_clinic(string, keep_arguments_param=True)
def wrapper(evaluator, obj, *args, **kwargs):
arguments = kwargs.pop('arguments')
@@ -103,11 +103,11 @@ def argument_clinic(string, want_obj=False, want_context=False, want_arguments=F
result = func(evaluator, *args, **kwargs)
debug.dbg('builtin end: %s', result, color='MAGENTA')
return result
-
- return wrapper
- return f
-
-
+
+ return wrapper
+ return f
+
+
@argument_clinic('iterator[, default], /')
def builtins_next(evaluator, iterators, defaults):
"""
@@ -132,45 +132,45 @@ def builtins_next(evaluator, iterators, defaults):
return defaults
-@argument_clinic('object, name[, default], /')
-def builtins_getattr(evaluator, objects, names, defaults=None):
- # follow the first param
- for obj in objects:
- for name in names:
+@argument_clinic('object, name[, default], /')
+def builtins_getattr(evaluator, objects, names, defaults=None):
+ # follow the first param
+ for obj in objects:
+ for name in names:
if is_string(name):
return obj.py__getattribute__(force_unicode(name.get_safe_value()))
- else:
- debug.warning('getattr called without str')
- continue
+ else:
+ debug.warning('getattr called without str')
+ continue
return NO_CONTEXTS
-
-
-@argument_clinic('object[, bases, dict], /')
-def builtins_type(evaluator, objects, bases, dicts):
- if bases or dicts:
+
+
+@argument_clinic('object[, bases, dict], /')
+def builtins_type(evaluator, objects, bases, dicts):
+ if bases or dicts:
# It's a type creation... maybe someday...
return NO_CONTEXTS
- else:
+ else:
return objects.py__class__()
-
-
+
+
class SuperInstance(AbstractInstanceContext):
- """To be used like the object ``super`` returns."""
- def __init__(self, evaluator, cls):
- su = cls.py_mro()[1]
- super().__init__(evaluator, su and su[0] or self)
-
-
+ """To be used like the object ``super`` returns."""
+ def __init__(self, evaluator, cls):
+ su = cls.py_mro()[1]
+ super().__init__(evaluator, su and su[0] or self)
+
+
@argument_clinic('[type[, obj]], /', want_context=True)
def builtins_super(evaluator, types, objects, context):
- # TODO make this able to detect multiple inheritance super
+ # TODO make this able to detect multiple inheritance super
if isinstance(context, FunctionExecutionContext):
if isinstance(context.var_args, InstanceArguments):
su = context.var_args.instance.py__class__().py__bases__()
return su[0].infer().execute_evaluated()
-
+
return NO_CONTEXTS
-
+
@argument_clinic('sequence, /', want_obj=True, want_arguments=True)
def builtins_reversed(evaluator, sequences, obj, arguments):
@@ -185,42 +185,42 @@ def builtins_reversed(evaluator, sequences, obj, arguments):
ordered = list(sequences.iterate(cn))
rev = list(reversed(ordered))
- # Repack iterator values and then run it the normal way. This is
- # necessary, because `reversed` is a function and autocompletion
- # would fail in certain cases like `reversed(x).__iter__` if we
- # just returned the result directly.
+ # Repack iterator values and then run it the normal way. This is
+ # necessary, because `reversed` is a function and autocompletion
+ # would fail in certain cases like `reversed(x).__iter__` if we
+ # just returned the result directly.
seq = iterable.FakeSequence(evaluator, u'list', rev)
arguments = ValuesArguments([ContextSet(seq)])
return ContextSet(CompiledInstance(evaluator, evaluator.builtins_module, obj, arguments))
-
-
+
+
@argument_clinic('obj, type, /', want_arguments=True)
def builtins_isinstance(evaluator, objects, types, arguments):
bool_results = set()
- for o in objects:
+ for o in objects:
cls = o.py__class__()
- try:
+ try:
mro_func = cls.py__mro__
- except AttributeError:
- # This is temporary. Everything should have a class attribute in
- # Python?! Maybe we'll leave it here, because some numpy objects or
- # whatever might not.
+ except AttributeError:
+ # This is temporary. Everything should have a class attribute in
+ # Python?! Maybe we'll leave it here, because some numpy objects or
+ # whatever might not.
bool_results = set([True, False])
break
-
+
mro = mro_func()
-
- for cls_or_tup in types:
- if cls_or_tup.is_class():
- bool_results.add(cls_or_tup in mro)
+
+ for cls_or_tup in types:
+ if cls_or_tup.is_class():
+ bool_results.add(cls_or_tup in mro)
elif cls_or_tup.name.string_name == 'tuple' \
and cls_or_tup.get_root_context() == evaluator.builtins_module:
- # Check for tuples.
+ # Check for tuples.
classes = ContextSet.from_sets(
lazy_context.infer()
for lazy_context in cls_or_tup.iterate()
)
- bool_results.add(any(cls in mro for cls in classes))
+ bool_results.add(any(cls in mro for cls in classes))
else:
_, lazy_context = list(arguments.unpack())[1]
if isinstance(lazy_context, LazyTreeContext):
@@ -229,34 +229,34 @@ def builtins_isinstance(evaluator, objects, types, arguments):
'class, type, or tuple of classes and types, ' \
'not %s.' % cls_or_tup
analysis.add(lazy_context._context, 'type-error-isinstance', node, message)
-
+
return ContextSet.from_iterable(
compiled.builtin_from_name(evaluator, force_unicode(str(b)))
for b in bool_results
)
-
-
+
+
def collections_namedtuple(evaluator, obj, arguments):
- """
- Implementation of the namedtuple function.
-
- This has to be done by processing the namedtuple class template and
- evaluating the result.
-
- """
+ """
+ Implementation of the namedtuple function.
+
+ This has to be done by processing the namedtuple class template and
+ evaluating the result.
+
+ """
collections_context = obj.parent_context
_class_template_set = collections_context.py__getattribute__(u'_class_template')
if not _class_template_set:
# Namedtuples are not supported on Python 2.6, early 2.7, because the
# _class_template variable is not defined, there.
return NO_CONTEXTS
-
- # Process arguments
+
+ # Process arguments
# TODO here we only use one of the types, we should use all.
# TODO this is buggy, doesn't need to be a string
name = list(_follow_param(evaluator, arguments, 0))[0].get_safe_value()
_fields = list(_follow_param(evaluator, arguments, 1))[0]
- if isinstance(_fields, compiled.CompiledObject):
+ if isinstance(_fields, compiled.CompiledObject):
fields = _fields.get_safe_value().replace(',', ' ').split()
elif isinstance(_fields, iterable.Sequence):
fields = [
@@ -264,9 +264,9 @@ def collections_namedtuple(evaluator, obj, arguments):
for lazy_context in _fields.py__iter__()
for v in lazy_context.infer() if is_string(v)
]
- else:
+ else:
return NO_CONTEXTS
-
+
def get_var(name):
x, = collections_context.py__getattribute__(name)
return x.get_safe_value()
@@ -275,15 +275,15 @@ def collections_namedtuple(evaluator, obj, arguments):
base += _NAMEDTUPLE_INIT
# Build source code
code = base.format(
- typename=name,
+ typename=name,
field_names=tuple(fields),
- num_fields=len(fields),
+ num_fields=len(fields),
arg_list=repr(tuple(fields)).replace("u'", "").replace("'", "")[1:-1],
repr_fmt=', '.join(get_var(u'_repr_template').format(name=name) for name in fields),
field_defs='\n'.join(get_var(u'_field_template').format(index=index, name=name)
- for index, name in enumerate(fields))
- )
-
+ for index, name in enumerate(fields))
+ )
+
# Parse source code
module = evaluator.grammar.parse(code)
generated_class = next(module.iter_classdefs())
@@ -292,30 +292,30 @@ def collections_namedtuple(evaluator, obj, arguments):
code_lines=parso.split_lines(code, keepends=True),
)
return ContextSet(ClassContext(evaluator, parent_context, generated_class))
-
-
-@argument_clinic('first, /')
-def _return_first_param(evaluator, firsts):
- return firsts
-
-
-_implemented = {
- 'builtins': {
- 'getattr': builtins_getattr,
- 'type': builtins_type,
- 'super': builtins_super,
- 'reversed': builtins_reversed,
- 'isinstance': builtins_isinstance,
- },
- 'copy': {
- 'copy': _return_first_param,
- 'deepcopy': _return_first_param,
- },
- 'json': {
+
+
+@argument_clinic('first, /')
+def _return_first_param(evaluator, firsts):
+ return firsts
+
+
+_implemented = {
+ 'builtins': {
+ 'getattr': builtins_getattr,
+ 'type': builtins_type,
+ 'super': builtins_super,
+ 'reversed': builtins_reversed,
+ 'isinstance': builtins_isinstance,
+ },
+ 'copy': {
+ 'copy': _return_first_param,
+ 'deepcopy': _return_first_param,
+ },
+ 'json': {
'load': lambda evaluator, obj, arguments: NO_CONTEXTS,
'loads': lambda evaluator, obj, arguments: NO_CONTEXTS,
- },
- 'collections': {
- 'namedtuple': collections_namedtuple,
- },
-}
+ },
+ 'collections': {
+ 'namedtuple': collections_namedtuple,
+ },
+}
diff --git a/contrib/python/jedi/jedi/evaluate/sys_path.py b/contrib/python/jedi/jedi/evaluate/sys_path.py
index a43d2ba177..8fb1843f05 100644
--- a/contrib/python/jedi/jedi/evaluate/sys_path.py
+++ b/contrib/python/jedi/jedi/evaluate/sys_path.py
@@ -1,5 +1,5 @@
-import os
-
+import os
+
from jedi._compatibility import unicode, force_unicode, all_suffixes
from jedi.evaluate.cache import evaluator_method_cache
from jedi.evaluate.base_context import ContextualizedNode
@@ -7,58 +7,58 @@ from jedi.evaluate.helpers import is_string
from jedi.common.utils import traverse_parents
from jedi.parser_utils import get_cached_code_lines
from jedi import settings
-from jedi import debug
-
-
+from jedi import debug
+
+
def _abs_path(module_context, path):
if os.path.isabs(path):
return path
-
+
module_path = module_context.py__file__()
if module_path is None:
# In this case we have no idea where we actually are in the file
# system.
return None
-
+
base_dir = os.path.dirname(module_path)
path = force_unicode(path)
return os.path.abspath(os.path.join(base_dir, path))
-
-
+
+
def _paths_from_assignment(module_context, expr_stmt):
- """
- Extracts the assigned strings from an assignment that looks as follows::
-
+ """
+ Extracts the assigned strings from an assignment that looks as follows::
+
sys.path[0:0] = ['module/path', 'another/module/path']
-
- This function is in general pretty tolerant (and therefore 'buggy').
- However, it's not a big issue usually to add more paths to Jedi's sys_path,
- because it will only affect Jedi in very random situations and by adding
- more paths than necessary, it usually benefits the general user.
- """
- for assignee, operator in zip(expr_stmt.children[::2], expr_stmt.children[1::2]):
- try:
- assert operator in ['=', '+=']
+
+ This function is in general pretty tolerant (and therefore 'buggy').
+ However, it's not a big issue usually to add more paths to Jedi's sys_path,
+ because it will only affect Jedi in very random situations and by adding
+ more paths than necessary, it usually benefits the general user.
+ """
+ for assignee, operator in zip(expr_stmt.children[::2], expr_stmt.children[1::2]):
+ try:
+ assert operator in ['=', '+=']
assert assignee.type in ('power', 'atom_expr') and \
len(assignee.children) > 1
- c = assignee.children
- assert c[0].type == 'name' and c[0].value == 'sys'
- trailer = c[1]
- assert trailer.children[0] == '.' and trailer.children[1].value == 'path'
- # TODO Essentially we're not checking details on sys.path
- # manipulation. Both assigment of the sys.path and changing/adding
+ c = assignee.children
+ assert c[0].type == 'name' and c[0].value == 'sys'
+ trailer = c[1]
+ assert trailer.children[0] == '.' and trailer.children[1].value == 'path'
+ # TODO Essentially we're not checking details on sys.path
+ # manipulation. Both assigment of the sys.path and changing/adding
# parts of the sys.path are the same: They get added to the end of
# the current sys.path.
- """
- execution = c[2]
- assert execution.children[0] == '['
- subscript = execution.children[1]
- assert subscript.type == 'subscript'
- assert ':' in subscript.children
- """
- except AssertionError:
- continue
-
+ """
+ execution = c[2]
+ assert execution.children[0] == '['
+ subscript = execution.children[1]
+ assert subscript.type == 'subscript'
+ assert ':' in subscript.children
+ """
+ except AssertionError:
+ continue
+
cn = ContextualizedNode(module_context.create_context(expr_stmt), expr_stmt)
for lazy_context in cn.infer().iterate(cn):
for context in lazy_context.infer():
@@ -66,59 +66,59 @@ def _paths_from_assignment(module_context, expr_stmt):
abs_path = _abs_path(module_context, context.get_safe_value())
if abs_path is not None:
yield abs_path
-
-
+
+
def _paths_from_list_modifications(module_context, trailer1, trailer2):
- """ extract the path from either "sys.path.append" or "sys.path.insert" """
- # Guarantee that both are trailers, the first one a name and the second one
- # a function execution with at least one param.
+ """ extract the path from either "sys.path.append" or "sys.path.insert" """
+ # Guarantee that both are trailers, the first one a name and the second one
+ # a function execution with at least one param.
if not (trailer1.type == 'trailer' and trailer1.children[0] == '.'
and trailer2.type == 'trailer' and trailer2.children[0] == '('
- and len(trailer2.children) == 3):
+ and len(trailer2.children) == 3):
return
-
- name = trailer1.children[1].value
- if name not in ['insert', 'append']:
+
+ name = trailer1.children[1].value
+ if name not in ['insert', 'append']:
return
- arg = trailer2.children[1]
- if name == 'insert' and len(arg.children) in (3, 4): # Possible trailing comma.
- arg = arg.children[2]
-
+ arg = trailer2.children[1]
+ if name == 'insert' and len(arg.children) in (3, 4): # Possible trailing comma.
+ arg = arg.children[2]
+
for context in module_context.create_context(arg).eval_node(arg):
if is_string(context):
abs_path = _abs_path(module_context, context.get_safe_value())
if abs_path is not None:
yield abs_path
-
+
@evaluator_method_cache(default=[])
def check_sys_path_modifications(module_context):
"""
Detect sys.path modifications within module.
"""
- def get_sys_path_powers(names):
- for name in names:
- power = name.parent.parent
+ def get_sys_path_powers(names):
+ for name in names:
+ power = name.parent.parent
if power.type in ('power', 'atom_expr'):
- c = power.children
+ c = power.children
if c[0].type == 'name' and c[0].value == 'sys' \
and c[1].type == 'trailer':
- n = c[1].children[1]
+ n = c[1].children[1]
if n.type == 'name' and n.value == 'path':
- yield name, power
-
+ yield name, power
+
if module_context.tree_node is None:
return []
added = []
- try:
+ try:
possible_names = module_context.tree_node.get_used_names()['path']
- except KeyError:
- pass
- else:
- for name, power in get_sys_path_powers(possible_names):
+ except KeyError:
+ pass
+ else:
+ for name, power in get_sys_path_powers(possible_names):
expr_stmt = power.parent
- if len(power.children) >= 4:
+ if len(power.children) >= 4:
added.extend(
_paths_from_list_modifications(
module_context, *power.children[2:4]
@@ -127,18 +127,18 @@ def check_sys_path_modifications(module_context):
elif expr_stmt is not None and expr_stmt.type == 'expr_stmt':
added.extend(_paths_from_assignment(module_context, expr_stmt))
return added
-
-
+
+
def discover_buildout_paths(evaluator, script_path):
- buildout_script_paths = set()
-
+ buildout_script_paths = set()
+
for buildout_script_path in _get_buildout_script_paths(script_path):
for path in _get_paths_from_buildout_script(evaluator, buildout_script_path):
- buildout_script_paths.add(path)
-
+ buildout_script_paths.add(path)
+
return buildout_script_paths
-
-
+
+
def _get_paths_from_buildout_script(evaluator, buildout_script_path):
try:
module_node = evaluator.parse(
@@ -148,52 +148,52 @@ def _get_paths_from_buildout_script(evaluator, buildout_script_path):
)
except IOError:
debug.warning('Error trying to read buildout_script: %s', buildout_script_path)
- return
-
+ return
+
from jedi.evaluate.context import ModuleContext
module = ModuleContext(
evaluator, module_node, buildout_script_path,
code_lines=get_cached_code_lines(evaluator.grammar, buildout_script_path),
)
for path in check_sys_path_modifications(module):
- yield path
-
-
-def _get_parent_dir_with_file(path, filename):
- for parent in traverse_parents(path):
- if os.path.isfile(os.path.join(parent, filename)):
- return parent
- return None
-
-
+ yield path
+
+
+def _get_parent_dir_with_file(path, filename):
+ for parent in traverse_parents(path):
+ if os.path.isfile(os.path.join(parent, filename)):
+ return parent
+ return None
+
+
def _get_buildout_script_paths(search_path):
- """
- if there is a 'buildout.cfg' file in one of the parent directories of the
- given module it will return a list of all files in the buildout bin
- directory that look like python files.
-
+ """
+ if there is a 'buildout.cfg' file in one of the parent directories of the
+ given module it will return a list of all files in the buildout bin
+ directory that look like python files.
+
:param search_path: absolute path to the module.
:type search_path: str
- """
+ """
project_root = _get_parent_dir_with_file(search_path, 'buildout.cfg')
- if not project_root:
+ if not project_root:
return
- bin_path = os.path.join(project_root, 'bin')
- if not os.path.exists(bin_path):
+ bin_path = os.path.join(project_root, 'bin')
+ if not os.path.exists(bin_path):
return
- for filename in os.listdir(bin_path):
- try:
- filepath = os.path.join(bin_path, filename)
- with open(filepath, 'r') as f:
- firstline = f.readline()
- if firstline.startswith('#!') and 'python' in firstline:
+ for filename in os.listdir(bin_path):
+ try:
+ filepath = os.path.join(bin_path, filename)
+ with open(filepath, 'r') as f:
+ firstline = f.readline()
+ if firstline.startswith('#!') and 'python' in firstline:
yield filepath
except (UnicodeDecodeError, IOError) as e:
# Probably a binary file; permission error or race cond. because
# file got deleted. Ignore it.
- debug.warning(unicode(e))
- continue
+ debug.warning(unicode(e))
+ continue
def dotted_path_in_sys_path(sys_path, module_path):
diff --git a/contrib/python/jedi/jedi/refactoring.py b/contrib/python/jedi/jedi/refactoring.py
index d887a16d08..6c1d74d1bd 100644
--- a/contrib/python/jedi/jedi/refactoring.py
+++ b/contrib/python/jedi/jedi/refactoring.py
@@ -1,172 +1,172 @@
-"""
+"""
THIS is not in active development, please check
https://github.com/davidhalter/jedi/issues/667 first before editing.
-Introduce some basic refactoring functions to |jedi|. This module is still in a
-very early development stage and needs much testing and improvement.
-
-.. warning:: I won't do too much here, but if anyone wants to step in, please
- do. Refactoring is none of my priorities
-
+Introduce some basic refactoring functions to |jedi|. This module is still in a
+very early development stage and needs much testing and improvement.
+
+.. warning:: I won't do too much here, but if anyone wants to step in, please
+ do. Refactoring is none of my priorities
+
It uses the |jedi| `API <api.html>`_ and supports currently the
-following functions (sometimes bug-prone):
-
-- rename
-- extract variable
-- inline variable
-"""
-import difflib
-
+following functions (sometimes bug-prone):
+
+- rename
+- extract variable
+- inline variable
+"""
+import difflib
+
from parso import python_bytes_to_unicode, split_lines
-from jedi.evaluate import helpers
-
-
-class Refactoring(object):
- def __init__(self, change_dct):
- """
- :param change_dct: dict(old_path=(new_path, old_lines, new_lines))
- """
- self.change_dct = change_dct
-
- def old_files(self):
- dct = {}
- for old_path, (new_path, old_l, new_l) in self.change_dct.items():
+from jedi.evaluate import helpers
+
+
+class Refactoring(object):
+ def __init__(self, change_dct):
+ """
+ :param change_dct: dict(old_path=(new_path, old_lines, new_lines))
+ """
+ self.change_dct = change_dct
+
+ def old_files(self):
+ dct = {}
+ for old_path, (new_path, old_l, new_l) in self.change_dct.items():
dct[old_path] = '\n'.join(old_l)
- return dct
-
- def new_files(self):
- dct = {}
- for old_path, (new_path, old_l, new_l) in self.change_dct.items():
- dct[new_path] = '\n'.join(new_l)
- return dct
-
- def diff(self):
- texts = []
- for old_path, (new_path, old_l, new_l) in self.change_dct.items():
- if old_path:
- udiff = difflib.unified_diff(old_l, new_l)
- else:
- udiff = difflib.unified_diff(old_l, new_l, old_path, new_path)
- texts.append('\n'.join(udiff))
- return '\n'.join(texts)
-
-
-def rename(script, new_name):
- """ The `args` / `kwargs` params are the same as in `api.Script`.
+ return dct
+
+ def new_files(self):
+ dct = {}
+ for old_path, (new_path, old_l, new_l) in self.change_dct.items():
+ dct[new_path] = '\n'.join(new_l)
+ return dct
+
+ def diff(self):
+ texts = []
+ for old_path, (new_path, old_l, new_l) in self.change_dct.items():
+ if old_path:
+ udiff = difflib.unified_diff(old_l, new_l)
+ else:
+ udiff = difflib.unified_diff(old_l, new_l, old_path, new_path)
+ texts.append('\n'.join(udiff))
+ return '\n'.join(texts)
+
+
+def rename(script, new_name):
+ """ The `args` / `kwargs` params are the same as in `api.Script`.
:param new_name: The new name of the script.
:param script: The source Script object.
- :return: list of changed lines/changed files
- """
- return Refactoring(_rename(script.usages(), new_name))
-
-
-def _rename(names, replace_str):
- """ For both rename and inline. """
- order = sorted(names, key=lambda x: (x.module_path, x.line, x.column),
- reverse=True)
-
- def process(path, old_lines, new_lines):
- if new_lines is not None: # goto next file, save last
- dct[path] = path, old_lines, new_lines
-
- dct = {}
- current_path = object()
- new_lines = old_lines = None
- for name in order:
- if name.in_builtin_module():
- continue
- if current_path != name.module_path:
- current_path = name.module_path
-
- process(current_path, old_lines, new_lines)
- if current_path is not None:
- # None means take the source that is a normal param.
- with open(current_path) as f:
- source = f.read()
-
+ :return: list of changed lines/changed files
+ """
+ return Refactoring(_rename(script.usages(), new_name))
+
+
+def _rename(names, replace_str):
+ """ For both rename and inline. """
+ order = sorted(names, key=lambda x: (x.module_path, x.line, x.column),
+ reverse=True)
+
+ def process(path, old_lines, new_lines):
+ if new_lines is not None: # goto next file, save last
+ dct[path] = path, old_lines, new_lines
+
+ dct = {}
+ current_path = object()
+ new_lines = old_lines = None
+ for name in order:
+ if name.in_builtin_module():
+ continue
+ if current_path != name.module_path:
+ current_path = name.module_path
+
+ process(current_path, old_lines, new_lines)
+ if current_path is not None:
+ # None means take the source that is a normal param.
+ with open(current_path) as f:
+ source = f.read()
+
new_lines = split_lines(python_bytes_to_unicode(source))
- old_lines = new_lines[:]
-
- nr, indent = name.line, name.column
- line = new_lines[nr - 1]
- new_lines[nr - 1] = line[:indent] + replace_str + \
- line[indent + len(name.name):]
- process(current_path, old_lines, new_lines)
- return dct
-
-
-def extract(script, new_name):
- """ The `args` / `kwargs` params are the same as in `api.Script`.
- :param operation: The refactoring operation to execute.
- :type operation: str
- :type source: str
- :return: list of changed lines/changed files
- """
+ old_lines = new_lines[:]
+
+ nr, indent = name.line, name.column
+ line = new_lines[nr - 1]
+ new_lines[nr - 1] = line[:indent] + replace_str + \
+ line[indent + len(name.name):]
+ process(current_path, old_lines, new_lines)
+ return dct
+
+
+def extract(script, new_name):
+ """ The `args` / `kwargs` params are the same as in `api.Script`.
+ :param operation: The refactoring operation to execute.
+ :type operation: str
+ :type source: str
+ :return: list of changed lines/changed files
+ """
new_lines = split_lines(python_bytes_to_unicode(script.source))
- old_lines = new_lines[:]
-
- user_stmt = script._parser.user_stmt()
-
+ old_lines = new_lines[:]
+
+ user_stmt = script._parser.user_stmt()
+
# TODO care for multi-line extracts
- dct = {}
- if user_stmt:
- pos = script._pos
- line_index = pos[0] - 1
+ dct = {}
+ if user_stmt:
+ pos = script._pos
+ line_index = pos[0] - 1
# Be careful here. 'array_for_pos' does not exist in 'helpers'.
- arr, index = helpers.array_for_pos(user_stmt, pos)
- if arr is not None:
- start_pos = arr[index].start_pos
- end_pos = arr[index].end_pos
-
- # take full line if the start line is different from end line
- e = end_pos[1] if end_pos[0] == start_pos[0] else None
- start_line = new_lines[start_pos[0] - 1]
- text = start_line[start_pos[1]:e]
- for l in range(start_pos[0], end_pos[0] - 1):
+ arr, index = helpers.array_for_pos(user_stmt, pos)
+ if arr is not None:
+ start_pos = arr[index].start_pos
+ end_pos = arr[index].end_pos
+
+ # take full line if the start line is different from end line
+ e = end_pos[1] if end_pos[0] == start_pos[0] else None
+ start_line = new_lines[start_pos[0] - 1]
+ text = start_line[start_pos[1]:e]
+ for l in range(start_pos[0], end_pos[0] - 1):
text += '\n' + str(l)
- if e is None:
- end_line = new_lines[end_pos[0] - 1]
- text += '\n' + end_line[:end_pos[1]]
-
- # remove code from new lines
- t = text.lstrip()
- del_start = start_pos[1] + len(text) - len(t)
-
- text = t.rstrip()
- del_end = len(t) - len(text)
- if e is None:
- new_lines[end_pos[0] - 1] = end_line[end_pos[1] - del_end:]
- e = len(start_line)
- else:
- e = e - del_end
- start_line = start_line[:del_start] + new_name + start_line[e:]
- new_lines[start_pos[0] - 1] = start_line
- new_lines[start_pos[0]:end_pos[0] - 1] = []
-
+ if e is None:
+ end_line = new_lines[end_pos[0] - 1]
+ text += '\n' + end_line[:end_pos[1]]
+
+ # remove code from new lines
+ t = text.lstrip()
+ del_start = start_pos[1] + len(text) - len(t)
+
+ text = t.rstrip()
+ del_end = len(t) - len(text)
+ if e is None:
+ new_lines[end_pos[0] - 1] = end_line[end_pos[1] - del_end:]
+ e = len(start_line)
+ else:
+ e = e - del_end
+ start_line = start_line[:del_start] + new_name + start_line[e:]
+ new_lines[start_pos[0] - 1] = start_line
+ new_lines[start_pos[0]:end_pos[0] - 1] = []
+
# add parentheses in multi-line case
- open_brackets = ['(', '[', '{']
- close_brackets = [')', ']', '}']
- if '\n' in text and not (text[0] in open_brackets and text[-1] ==
- close_brackets[open_brackets.index(text[0])]):
- text = '(%s)' % text
-
- # add new line before statement
- indent = user_stmt.start_pos[1]
- new = "%s%s = %s" % (' ' * indent, new_name, text)
- new_lines.insert(line_index, new)
- dct[script.path] = script.path, old_lines, new_lines
- return Refactoring(dct)
-
-
-def inline(script):
- """
- :type script: api.Script
- """
+ open_brackets = ['(', '[', '{']
+ close_brackets = [')', ']', '}']
+ if '\n' in text and not (text[0] in open_brackets and text[-1] ==
+ close_brackets[open_brackets.index(text[0])]):
+ text = '(%s)' % text
+
+ # add new line before statement
+ indent = user_stmt.start_pos[1]
+ new = "%s%s = %s" % (' ' * indent, new_name, text)
+ new_lines.insert(line_index, new)
+ dct[script.path] = script.path, old_lines, new_lines
+ return Refactoring(dct)
+
+
+def inline(script):
+ """
+ :type script: api.Script
+ """
new_lines = split_lines(python_bytes_to_unicode(script.source))
-
- dct = {}
-
- definitions = script.goto_assignments()
+
+ dct = {}
+
+ definitions = script.goto_assignments()
assert len(definitions) == 1
stmt = definitions[0]._definition
usages = script.usages()
@@ -178,7 +178,7 @@ def inline(script):
# don't allow multi-line refactorings for now.
assert stmt.start_pos[0] == stmt.end_pos[0]
index = stmt.start_pos[0] - 1
-
+
line = new_lines[index]
replace_str = line[expression_list[0].start_pos[1]:stmt.end_pos[1] + 1]
replace_str = replace_str.strip()
@@ -187,11 +187,11 @@ def inline(script):
arr = expression_list[0]
if replace_str[0] not in ['(', '[', '{'] and len(arr) > 1:
replace_str = '(%s)' % replace_str
-
+
# if it's the only assignment, remove the statement
if len(stmt.get_defined_names()) == 1:
line = line[:stmt.start_pos[1]] + line[stmt.end_pos[1]:]
-
+
dct = _rename(inlines, replace_str)
# remove the empty line
new_lines = dct[script.path][2]
@@ -199,5 +199,5 @@ def inline(script):
new_lines[index] = line
else:
new_lines.pop(index)
-
- return Refactoring(dct)
+
+ return Refactoring(dct)
diff --git a/contrib/python/jedi/jedi/settings.py b/contrib/python/jedi/jedi/settings.py
index 2ee60aaeb3..436fadfc0e 100644
--- a/contrib/python/jedi/jedi/settings.py
+++ b/contrib/python/jedi/jedi/settings.py
@@ -1,164 +1,164 @@
-"""
-This module contains variables with global |jedi| settings. To change the
-behavior of |jedi|, change the variables defined in :mod:`jedi.settings`.
-
-Plugins should expose an interface so that the user can adjust the
-configuration.
-
-
-Example usage::
-
- from jedi import settings
- settings.case_insensitive_completion = True
-
-
-Completion output
-~~~~~~~~~~~~~~~~~
-
-.. autodata:: case_insensitive_completion
-.. autodata:: add_bracket_after_function
-.. autodata:: no_completion_duplicates
-
-
-Filesystem cache
-~~~~~~~~~~~~~~~~
-
-.. autodata:: cache_directory
-.. autodata:: use_filesystem_cache
-
-
-Parser
-~~~~~~
-
-.. autodata:: fast_parser
-
-
-Dynamic stuff
-~~~~~~~~~~~~~
-
-.. autodata:: dynamic_array_additions
-.. autodata:: dynamic_params
-.. autodata:: dynamic_params_for_other_modules
-.. autodata:: additional_dynamic_modules
-.. autodata:: auto_import_modules
-
-
-Caching
-~~~~~~~
-
-.. autodata:: call_signatures_validity
-
-
-"""
-import os
-import platform
-
-# ----------------
-# completion output settings
-# ----------------
-
-case_insensitive_completion = True
-"""
-The completion is by default case insensitive.
-"""
-
-add_bracket_after_function = False
-"""
-Adds an opening bracket after a function, because that's normal behaviour.
-Removed it again, because in VIM that is not very practical.
-"""
-
-no_completion_duplicates = True
-"""
-If set, completions with the same name don't appear in the output anymore,
-but are in the `same_name_completions` attribute.
-"""
-
-# ----------------
-# Filesystem cache
-# ----------------
-
-use_filesystem_cache = True
-"""
-Use filesystem cache to save once parsed files with pickle.
-"""
-
-if platform.system().lower() == 'windows':
- _cache_directory = os.path.join(os.getenv('APPDATA') or '~', 'Jedi',
- 'Jedi')
-elif platform.system().lower() == 'darwin':
- _cache_directory = os.path.join('~', 'Library', 'Caches', 'Jedi')
-else:
- _cache_directory = os.path.join(os.getenv('XDG_CACHE_HOME') or '~/.cache',
- 'jedi')
-cache_directory = os.path.expanduser(_cache_directory)
-"""
+"""
+This module contains variables with global |jedi| settings. To change the
+behavior of |jedi|, change the variables defined in :mod:`jedi.settings`.
+
+Plugins should expose an interface so that the user can adjust the
+configuration.
+
+
+Example usage::
+
+ from jedi import settings
+ settings.case_insensitive_completion = True
+
+
+Completion output
+~~~~~~~~~~~~~~~~~
+
+.. autodata:: case_insensitive_completion
+.. autodata:: add_bracket_after_function
+.. autodata:: no_completion_duplicates
+
+
+Filesystem cache
+~~~~~~~~~~~~~~~~
+
+.. autodata:: cache_directory
+.. autodata:: use_filesystem_cache
+
+
+Parser
+~~~~~~
+
+.. autodata:: fast_parser
+
+
+Dynamic stuff
+~~~~~~~~~~~~~
+
+.. autodata:: dynamic_array_additions
+.. autodata:: dynamic_params
+.. autodata:: dynamic_params_for_other_modules
+.. autodata:: additional_dynamic_modules
+.. autodata:: auto_import_modules
+
+
+Caching
+~~~~~~~
+
+.. autodata:: call_signatures_validity
+
+
+"""
+import os
+import platform
+
+# ----------------
+# completion output settings
+# ----------------
+
+case_insensitive_completion = True
+"""
+The completion is by default case insensitive.
+"""
+
+add_bracket_after_function = False
+"""
+Adds an opening bracket after a function, because that's normal behaviour.
+Removed it again, because in VIM that is not very practical.
+"""
+
+no_completion_duplicates = True
+"""
+If set, completions with the same name don't appear in the output anymore,
+but are in the `same_name_completions` attribute.
+"""
+
+# ----------------
+# Filesystem cache
+# ----------------
+
+use_filesystem_cache = True
+"""
+Use filesystem cache to save once parsed files with pickle.
+"""
+
+if platform.system().lower() == 'windows':
+ _cache_directory = os.path.join(os.getenv('APPDATA') or '~', 'Jedi',
+ 'Jedi')
+elif platform.system().lower() == 'darwin':
+ _cache_directory = os.path.join('~', 'Library', 'Caches', 'Jedi')
+else:
+ _cache_directory = os.path.join(os.getenv('XDG_CACHE_HOME') or '~/.cache',
+ 'jedi')
+cache_directory = os.path.expanduser(_cache_directory)
+"""
The path where the cache is stored.
-
-On Linux, this defaults to ``~/.cache/jedi/``, on OS X to
-``~/Library/Caches/Jedi/`` and on Windows to ``%APPDATA%\\Jedi\\Jedi\\``.
-On Linux, if environment variable ``$XDG_CACHE_HOME`` is set,
-``$XDG_CACHE_HOME/jedi`` is used instead of the default one.
-"""
-
-# ----------------
-# parser
-# ----------------
-
-fast_parser = True
-"""
-Use the fast parser. This means that reparsing is only being done if
-something has been changed e.g. to a function. If this happens, only the
-function is being reparsed.
-"""
-
-# ----------------
-# dynamic stuff
-# ----------------
-
-dynamic_array_additions = True
-"""
-check for `append`, etc. on arrays: [], {}, () as well as list/set calls.
-"""
-
-dynamic_params = True
-"""
-A dynamic param completion, finds the callees of the function, which define
-the params of a function.
-"""
-
-dynamic_params_for_other_modules = True
-"""
-Do the same for other modules.
-"""
-
-additional_dynamic_modules = []
-"""
-Additional modules in which |jedi| checks if statements are to be found. This
-is practical for IDEs, that want to administrate their modules themselves.
-"""
-
-dynamic_flow_information = True
-"""
-Check for `isinstance` and other information to infer a type.
-"""
-
-auto_import_modules = [
+
+On Linux, this defaults to ``~/.cache/jedi/``, on OS X to
+``~/Library/Caches/Jedi/`` and on Windows to ``%APPDATA%\\Jedi\\Jedi\\``.
+On Linux, if environment variable ``$XDG_CACHE_HOME`` is set,
+``$XDG_CACHE_HOME/jedi`` is used instead of the default one.
+"""
+
+# ----------------
+# parser
+# ----------------
+
+fast_parser = True
+"""
+Use the fast parser. This means that reparsing is only being done if
+something has been changed e.g. to a function. If this happens, only the
+function is being reparsed.
+"""
+
+# ----------------
+# dynamic stuff
+# ----------------
+
+dynamic_array_additions = True
+"""
+check for `append`, etc. on arrays: [], {}, () as well as list/set calls.
+"""
+
+dynamic_params = True
+"""
+A dynamic param completion, finds the callees of the function, which define
+the params of a function.
+"""
+
+dynamic_params_for_other_modules = True
+"""
+Do the same for other modules.
+"""
+
+additional_dynamic_modules = []
+"""
+Additional modules in which |jedi| checks if statements are to be found. This
+is practical for IDEs, that want to administrate their modules themselves.
+"""
+
+dynamic_flow_information = True
+"""
+Check for `isinstance` and other information to infer a type.
+"""
+
+auto_import_modules = [
'hashlib', # hashlib is mostly using setattr, which jedi doesn't understand
'gi', # This third-party repository (GTK stuff) doesn't really work with jedi
-]
-"""
-Modules that are not analyzed but imported, although they contain Python code.
-This improves autocompletion for libraries that use ``setattr`` or
-``globals()`` modifications a lot.
-"""
-
-# ----------------
-# caching validity (time)
-# ----------------
-
-call_signatures_validity = 3.0
-"""
-Finding function calls might be slow (0.1-0.5s). This is not acceptible for
-normal writing. Therefore cache it for a short time.
-"""
+]
+"""
+Modules that are not analyzed but imported, although they contain Python code.
+This improves autocompletion for libraries that use ``setattr`` or
+``globals()`` modifications a lot.
+"""
+
+# ----------------
+# caching validity (time)
+# ----------------
+
+call_signatures_validity = 3.0
+"""
+Finding function calls might be slow (0.1-0.5s). This is not acceptible for
+normal writing. Therefore cache it for a short time.
+"""
diff --git a/contrib/python/jedi/jedi/utils.py b/contrib/python/jedi/jedi/utils.py
index 0a75afe984..04e87c301c 100644
--- a/contrib/python/jedi/jedi/utils.py
+++ b/contrib/python/jedi/jedi/utils.py
@@ -1,66 +1,66 @@
-"""
-Utilities for end-users.
-"""
-
-from __future__ import absolute_import
-import __main__
-from collections import namedtuple
+"""
+Utilities for end-users.
+"""
+
+from __future__ import absolute_import
+import __main__
+from collections import namedtuple
import logging
import traceback
-import re
-import os
-import sys
-
+import re
+import os
+import sys
+
from parso import split_lines
-from jedi import Interpreter
+from jedi import Interpreter
from jedi.api.helpers import get_on_completion_name
-
-
+
+
READLINE_DEBUG = False
-def setup_readline(namespace_module=__main__):
- """
- Install Jedi completer to :mod:`readline`.
-
- This function setups :mod:`readline` to use Jedi in Python interactive
- shell. If you want to use a custom ``PYTHONSTARTUP`` file (typically
- ``$HOME/.pythonrc.py``), you can add this piece of code::
-
- try:
- from jedi.utils import setup_readline
- setup_readline()
- except ImportError:
- # Fallback to the stdlib readline completer if it is installed.
- # Taken from http://docs.python.org/2/library/rlcompleter.html
- print("Jedi is not installed, falling back to readline")
- try:
- import readline
- import rlcompleter
- readline.parse_and_bind("tab: complete")
- except ImportError:
- print("Readline is not installed either. No tab completion is enabled.")
-
- This will fallback to the readline completer if Jedi is not installed.
- The readline completer will only complete names in the global namespace,
- so for example::
-
- ran<TAB>
-
- will complete to ``range``
-
- with both Jedi and readline, but::
-
- range(10).cou<TAB>
-
- will show complete to ``range(10).count`` only with Jedi.
-
- You'll also need to add ``export PYTHONSTARTUP=$HOME/.pythonrc.py`` to
- your shell profile (usually ``.bash_profile`` or ``.profile`` if you use
- bash).
-
- """
+def setup_readline(namespace_module=__main__):
+ """
+ Install Jedi completer to :mod:`readline`.
+
+ This function setups :mod:`readline` to use Jedi in Python interactive
+ shell. If you want to use a custom ``PYTHONSTARTUP`` file (typically
+ ``$HOME/.pythonrc.py``), you can add this piece of code::
+
+ try:
+ from jedi.utils import setup_readline
+ setup_readline()
+ except ImportError:
+ # Fallback to the stdlib readline completer if it is installed.
+ # Taken from http://docs.python.org/2/library/rlcompleter.html
+ print("Jedi is not installed, falling back to readline")
+ try:
+ import readline
+ import rlcompleter
+ readline.parse_and_bind("tab: complete")
+ except ImportError:
+ print("Readline is not installed either. No tab completion is enabled.")
+
+ This will fallback to the readline completer if Jedi is not installed.
+ The readline completer will only complete names in the global namespace,
+ so for example::
+
+ ran<TAB>
+
+ will complete to ``range``
+
+ with both Jedi and readline, but::
+
+ range(10).cou<TAB>
+
+ will show complete to ``range(10).count`` only with Jedi.
+
+ You'll also need to add ``export PYTHONSTARTUP=$HOME/.pythonrc.py`` to
+ your shell profile (usually ``.bash_profile`` or ``.profile`` if you use
+ bash).
+
+ """
if READLINE_DEBUG:
logging.basicConfig(
filename='/tmp/jedi.log',
@@ -68,24 +68,24 @@ def setup_readline(namespace_module=__main__):
level=logging.DEBUG
)
- class JediRL(object):
- def complete(self, text, state):
- """
- This complete stuff is pretty weird, a generator would make
- a lot more sense, but probably due to backwards compatibility
- this is still the way how it works.
-
- The only important part is stuff in the ``state == 0`` flow,
- everything else has been copied from the ``rlcompleter`` std.
- library module.
- """
- if state == 0:
- sys.path.insert(0, os.getcwd())
- # Calling python doesn't have a path, so add to sys.path.
- try:
+ class JediRL(object):
+ def complete(self, text, state):
+ """
+ This complete stuff is pretty weird, a generator would make
+ a lot more sense, but probably due to backwards compatibility
+ this is still the way how it works.
+
+ The only important part is stuff in the ``state == 0`` flow,
+ everything else has been copied from the ``rlcompleter`` std.
+ library module.
+ """
+ if state == 0:
+ sys.path.insert(0, os.getcwd())
+ # Calling python doesn't have a path, so add to sys.path.
+ try:
logging.debug("Start REPL completion: " + repr(text))
- interpreter = Interpreter(text, [namespace_module.__dict__])
-
+ interpreter = Interpreter(text, [namespace_module.__dict__])
+
lines = split_lines(text)
position = (len(lines), len(lines[-1]))
name = get_on_completion_name(
@@ -94,49 +94,49 @@ def setup_readline(namespace_module=__main__):
position
)
before = text[:len(text) - len(name)]
- completions = interpreter.completions()
+ completions = interpreter.completions()
logging.debug("REPL completions: %s", completions)
except:
logging.error("REPL Completion error:\n" + traceback.format_exc())
raise
- finally:
- sys.path.pop(0)
-
- self.matches = [before + c.name_with_symbols for c in completions]
- try:
- return self.matches[state]
- except IndexError:
- return None
-
- try:
+ finally:
+ sys.path.pop(0)
+
+ self.matches = [before + c.name_with_symbols for c in completions]
+ try:
+ return self.matches[state]
+ except IndexError:
+ return None
+
+ try:
# Need to import this one as well to make sure it's executed before
# this code. This didn't use to be an issue until 3.3. Starting with
# 3.4 this is different, it always overwrites the completer if it's not
# already imported here.
import rlcompleter # noqa: F401
- import readline
- except ImportError:
+ import readline
+ except ImportError:
print("Jedi: Module readline not available.")
- else:
- readline.set_completer(JediRL().complete)
- readline.parse_and_bind("tab: complete")
- # jedi itself does the case matching
- readline.parse_and_bind("set completion-ignore-case on")
- # because it's easier to hit the tab just once
- readline.parse_and_bind("set show-all-if-unmodified")
- readline.parse_and_bind("set show-all-if-ambiguous on")
- # don't repeat all the things written in the readline all the time
- readline.parse_and_bind("set completion-prefix-display-length 2")
- # No delimiters, Jedi handles that.
- readline.set_completer_delims('')
-
-
-def version_info():
- """
- Returns a namedtuple of Jedi's version, similar to Python's
- ``sys.version_info``.
- """
- Version = namedtuple('Version', 'major, minor, micro')
- from jedi import __version__
+ else:
+ readline.set_completer(JediRL().complete)
+ readline.parse_and_bind("tab: complete")
+ # jedi itself does the case matching
+ readline.parse_and_bind("set completion-ignore-case on")
+ # because it's easier to hit the tab just once
+ readline.parse_and_bind("set show-all-if-unmodified")
+ readline.parse_and_bind("set show-all-if-ambiguous on")
+ # don't repeat all the things written in the readline all the time
+ readline.parse_and_bind("set completion-prefix-display-length 2")
+ # No delimiters, Jedi handles that.
+ readline.set_completer_delims('')
+
+
+def version_info():
+ """
+ Returns a namedtuple of Jedi's version, similar to Python's
+ ``sys.version_info``.
+ """
+ Version = namedtuple('Version', 'major, minor, micro')
+ from jedi import __version__
tupl = re.findall(r'[a-z]+|\d+', __version__)
- return Version(*[x if i == 3 else int(x) for i, x in enumerate(tupl)])
+ return Version(*[x if i == 3 else int(x) for i, x in enumerate(tupl)])
diff --git a/contrib/python/jedi/ya.make b/contrib/python/jedi/ya.make
index dfc0c7ecb8..eff2fef2a7 100644
--- a/contrib/python/jedi/ya.make
+++ b/contrib/python/jedi/ya.make
@@ -1,45 +1,45 @@
PY23_LIBRARY(jedi)
-
+
LICENSE(MIT)
OWNER(g:python-contrib borman)
-
+
VERSION(0.13.3)
-PEERDIR(
+PEERDIR(
contrib/python/parso
contrib/python/setuptools
-)
-
-PY_SRCS(
- TOP_LEVEL
- jedi/__init__.py
+)
+
+PY_SRCS(
+ TOP_LEVEL
+ jedi/__init__.py
jedi/__main__.py
- jedi/_compatibility.py
- jedi/api/__init__.py
- jedi/api/classes.py
+ jedi/_compatibility.py
+ jedi/api/__init__.py
+ jedi/api/classes.py
jedi/api/completion.py
jedi/api/environment.py
jedi/api/exceptions.py
- jedi/api/helpers.py
- jedi/api/interpreter.py
- jedi/api/keywords.py
+ jedi/api/helpers.py
+ jedi/api/interpreter.py
+ jedi/api/keywords.py
jedi/api/project.py
- jedi/api/replstartup.py
- jedi/cache.py
+ jedi/api/replstartup.py
+ jedi/cache.py
jedi/common/__init__.py
jedi/common/context.py
jedi/common/utils.py
- jedi/debug.py
- jedi/evaluate/__init__.py
- jedi/evaluate/analysis.py
+ jedi/debug.py
+ jedi/evaluate/__init__.py
+ jedi/evaluate/analysis.py
jedi/evaluate/arguments.py
jedi/evaluate/base_context.py
- jedi/evaluate/cache.py
- jedi/evaluate/compiled/__init__.py
+ jedi/evaluate/cache.py
+ jedi/evaluate/compiled/__init__.py
jedi/evaluate/compiled/access.py
jedi/evaluate/compiled/context.py
- jedi/evaluate/compiled/fake.py
+ jedi/evaluate/compiled/fake.py
jedi/evaluate/compiled/getattr_static.py
jedi/evaluate/compiled/mixed.py
jedi/evaluate/compiled/subprocess/__init__.py
@@ -53,30 +53,30 @@ PY_SRCS(
jedi/evaluate/context/klass.py
jedi/evaluate/context/module.py
jedi/evaluate/context/namespace.py
- jedi/evaluate/docstrings.py
- jedi/evaluate/dynamic.py
+ jedi/evaluate/docstrings.py
+ jedi/evaluate/dynamic.py
jedi/evaluate/filters.py
- jedi/evaluate/finder.py
- jedi/evaluate/flow_analysis.py
- jedi/evaluate/helpers.py
- jedi/evaluate/imports.py
+ jedi/evaluate/finder.py
+ jedi/evaluate/flow_analysis.py
+ jedi/evaluate/helpers.py
+ jedi/evaluate/imports.py
jedi/evaluate/jedi_typing.py
jedi/evaluate/lazy_context.py
- jedi/evaluate/param.py
+ jedi/evaluate/param.py
jedi/evaluate/parser_cache.py
jedi/evaluate/pep0484.py
- jedi/evaluate/recursion.py
- jedi/evaluate/stdlib.py
+ jedi/evaluate/recursion.py
+ jedi/evaluate/stdlib.py
jedi/evaluate/syntax_tree.py
- jedi/evaluate/sys_path.py
+ jedi/evaluate/sys_path.py
jedi/evaluate/usages.py
jedi/evaluate/utils.py
jedi/parser_utils.py
- jedi/refactoring.py
- jedi/settings.py
- jedi/utils.py
-)
-
+ jedi/refactoring.py
+ jedi/settings.py
+ jedi/utils.py
+)
+
RESOURCE_FILES(
PREFIX contrib/python/jedi/
.dist-info/METADATA
@@ -94,4 +94,4 @@ RESOURCE_FILES(
NO_LINT()
-END()
+END()
diff --git a/contrib/python/pexpect/LICENSE b/contrib/python/pexpect/LICENSE
index 11f4b1686f..754db5afcb 100644
--- a/contrib/python/pexpect/LICENSE
+++ b/contrib/python/pexpect/LICENSE
@@ -1,20 +1,20 @@
ISC LICENSE
-
- This license is approved by the OSI and FSF as GPL-compatible.
- http://opensource.org/licenses/isc-license.txt
-
- Copyright (c) 2013-2014, Pexpect development team
- Copyright (c) 2012, Noah Spurrier <noah@noah.org>
-
+
+ This license is approved by the OSI and FSF as GPL-compatible.
+ http://opensource.org/licenses/isc-license.txt
+
+ Copyright (c) 2013-2014, Pexpect development team
+ Copyright (c) 2012, Noah Spurrier <noah@noah.org>
+
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
diff --git a/contrib/python/pexpect/pexpect/ANSI.py b/contrib/python/pexpect/pexpect/ANSI.py
index 50bd7732f7..1cd2e90e7a 100644
--- a/contrib/python/pexpect/pexpect/ANSI.py
+++ b/contrib/python/pexpect/pexpect/ANSI.py
@@ -1,351 +1,351 @@
-'''This implements an ANSI (VT100) terminal emulator as a subclass of screen.
-
-PEXPECT LICENSE
-
- This license is approved by the OSI and FSF as GPL-compatible.
- http://opensource.org/licenses/isc-license.txt
-
- Copyright (c) 2012, Noah Spurrier <noah@noah.org>
- PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
- PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
- COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-'''
-
-# references:
-# http://en.wikipedia.org/wiki/ANSI_escape_code
-# http://www.retards.org/terminals/vt102.html
-# http://vt100.net/docs/vt102-ug/contents.html
-# http://vt100.net/docs/vt220-rm/
-# http://www.termsys.demon.co.uk/vtansi.htm
-
-from . import screen
-from . import FSM
-import string
-
-#
-# The 'Do.*' functions are helper functions for the ANSI class.
-#
-def DoEmit (fsm):
-
- screen = fsm.memory[0]
- screen.write_ch(fsm.input_symbol)
-
-def DoStartNumber (fsm):
-
- fsm.memory.append (fsm.input_symbol)
-
-def DoBuildNumber (fsm):
-
- ns = fsm.memory.pop()
- ns = ns + fsm.input_symbol
- fsm.memory.append (ns)
-
-def DoBackOne (fsm):
-
- screen = fsm.memory[0]
- screen.cursor_back ()
-
-def DoBack (fsm):
-
- count = int(fsm.memory.pop())
- screen = fsm.memory[0]
- screen.cursor_back (count)
-
-def DoDownOne (fsm):
-
- screen = fsm.memory[0]
- screen.cursor_down ()
-
-def DoDown (fsm):
-
- count = int(fsm.memory.pop())
- screen = fsm.memory[0]
- screen.cursor_down (count)
-
-def DoForwardOne (fsm):
-
- screen = fsm.memory[0]
- screen.cursor_forward ()
-
-def DoForward (fsm):
-
- count = int(fsm.memory.pop())
- screen = fsm.memory[0]
- screen.cursor_forward (count)
-
-def DoUpReverse (fsm):
-
- screen = fsm.memory[0]
- screen.cursor_up_reverse()
-
-def DoUpOne (fsm):
-
- screen = fsm.memory[0]
- screen.cursor_up ()
-
-def DoUp (fsm):
-
- count = int(fsm.memory.pop())
- screen = fsm.memory[0]
- screen.cursor_up (count)
-
-def DoHome (fsm):
-
- c = int(fsm.memory.pop())
- r = int(fsm.memory.pop())
- screen = fsm.memory[0]
- screen.cursor_home (r,c)
-
-def DoHomeOrigin (fsm):
-
- c = 1
- r = 1
- screen = fsm.memory[0]
- screen.cursor_home (r,c)
-
-def DoEraseDown (fsm):
-
- screen = fsm.memory[0]
- screen.erase_down()
-
-def DoErase (fsm):
-
- arg = int(fsm.memory.pop())
- screen = fsm.memory[0]
- if arg == 0:
- screen.erase_down()
- elif arg == 1:
- screen.erase_up()
- elif arg == 2:
- screen.erase_screen()
-
-def DoEraseEndOfLine (fsm):
-
- screen = fsm.memory[0]
- screen.erase_end_of_line()
-
-def DoEraseLine (fsm):
-
- arg = int(fsm.memory.pop())
- screen = fsm.memory[0]
- if arg == 0:
- screen.erase_end_of_line()
- elif arg == 1:
- screen.erase_start_of_line()
- elif arg == 2:
- screen.erase_line()
-
-def DoEnableScroll (fsm):
-
- screen = fsm.memory[0]
- screen.scroll_screen()
-
-def DoCursorSave (fsm):
-
- screen = fsm.memory[0]
- screen.cursor_save_attrs()
-
-def DoCursorRestore (fsm):
-
- screen = fsm.memory[0]
- screen.cursor_restore_attrs()
-
-def DoScrollRegion (fsm):
-
- screen = fsm.memory[0]
- r2 = int(fsm.memory.pop())
- r1 = int(fsm.memory.pop())
- screen.scroll_screen_rows (r1,r2)
-
-def DoMode (fsm):
-
- screen = fsm.memory[0]
- mode = fsm.memory.pop() # Should be 4
- # screen.setReplaceMode ()
-
-def DoLog (fsm):
-
- screen = fsm.memory[0]
- fsm.memory = [screen]
- fout = open ('log', 'a')
- fout.write (fsm.input_symbol + ',' + fsm.current_state + '\n')
- fout.close()
-
-class term (screen.screen):
-
- '''This class is an abstract, generic terminal.
- This does nothing. This is a placeholder that
- provides a common base class for other terminals
- such as an ANSI terminal. '''
-
- def __init__ (self, r=24, c=80, *args, **kwargs):
-
- screen.screen.__init__(self, r,c,*args,**kwargs)
-
-class ANSI (term):
- '''This class implements an ANSI (VT100) terminal.
- It is a stream filter that recognizes ANSI terminal
- escape sequences and maintains the state of a screen object. '''
-
- def __init__ (self, r=24,c=80,*args,**kwargs):
-
- term.__init__(self,r,c,*args,**kwargs)
-
- #self.screen = screen (24,80)
- self.state = FSM.FSM ('INIT',[self])
- self.state.set_default_transition (DoLog, 'INIT')
- self.state.add_transition_any ('INIT', DoEmit, 'INIT')
- self.state.add_transition ('\x1b', 'INIT', None, 'ESC')
- self.state.add_transition_any ('ESC', DoLog, 'INIT')
- self.state.add_transition ('(', 'ESC', None, 'G0SCS')
- self.state.add_transition (')', 'ESC', None, 'G1SCS')
- self.state.add_transition_list ('AB012', 'G0SCS', None, 'INIT')
- self.state.add_transition_list ('AB012', 'G1SCS', None, 'INIT')
- self.state.add_transition ('7', 'ESC', DoCursorSave, 'INIT')
- self.state.add_transition ('8', 'ESC', DoCursorRestore, 'INIT')
- self.state.add_transition ('M', 'ESC', DoUpReverse, 'INIT')
- self.state.add_transition ('>', 'ESC', DoUpReverse, 'INIT')
- self.state.add_transition ('<', 'ESC', DoUpReverse, 'INIT')
- self.state.add_transition ('=', 'ESC', None, 'INIT') # Selects application keypad.
- self.state.add_transition ('#', 'ESC', None, 'GRAPHICS_POUND')
- self.state.add_transition_any ('GRAPHICS_POUND', None, 'INIT')
- self.state.add_transition ('[', 'ESC', None, 'ELB')
- # ELB means Escape Left Bracket. That is ^[[
- self.state.add_transition ('H', 'ELB', DoHomeOrigin, 'INIT')
- self.state.add_transition ('D', 'ELB', DoBackOne, 'INIT')
- self.state.add_transition ('B', 'ELB', DoDownOne, 'INIT')
- self.state.add_transition ('C', 'ELB', DoForwardOne, 'INIT')
- self.state.add_transition ('A', 'ELB', DoUpOne, 'INIT')
- self.state.add_transition ('J', 'ELB', DoEraseDown, 'INIT')
- self.state.add_transition ('K', 'ELB', DoEraseEndOfLine, 'INIT')
- self.state.add_transition ('r', 'ELB', DoEnableScroll, 'INIT')
- self.state.add_transition ('m', 'ELB', self.do_sgr, 'INIT')
- self.state.add_transition ('?', 'ELB', None, 'MODECRAP')
- self.state.add_transition_list (string.digits, 'ELB', DoStartNumber, 'NUMBER_1')
- self.state.add_transition_list (string.digits, 'NUMBER_1', DoBuildNumber, 'NUMBER_1')
- self.state.add_transition ('D', 'NUMBER_1', DoBack, 'INIT')
- self.state.add_transition ('B', 'NUMBER_1', DoDown, 'INIT')
- self.state.add_transition ('C', 'NUMBER_1', DoForward, 'INIT')
- self.state.add_transition ('A', 'NUMBER_1', DoUp, 'INIT')
- self.state.add_transition ('J', 'NUMBER_1', DoErase, 'INIT')
- self.state.add_transition ('K', 'NUMBER_1', DoEraseLine, 'INIT')
- self.state.add_transition ('l', 'NUMBER_1', DoMode, 'INIT')
- ### It gets worse... the 'm' code can have infinite number of
- ### number;number;number before it. I've never seen more than two,
- ### but the specs say it's allowed. crap!
- self.state.add_transition ('m', 'NUMBER_1', self.do_sgr, 'INIT')
- ### LED control. Same implementation problem as 'm' code.
- self.state.add_transition ('q', 'NUMBER_1', self.do_decsca, 'INIT')
-
- # \E[?47h switch to alternate screen
- # \E[?47l restores to normal screen from alternate screen.
- self.state.add_transition_list (string.digits, 'MODECRAP', DoStartNumber, 'MODECRAP_NUM')
- self.state.add_transition_list (string.digits, 'MODECRAP_NUM', DoBuildNumber, 'MODECRAP_NUM')
- self.state.add_transition ('l', 'MODECRAP_NUM', self.do_modecrap, 'INIT')
- self.state.add_transition ('h', 'MODECRAP_NUM', self.do_modecrap, 'INIT')
-
-#RM Reset Mode Esc [ Ps l none
- self.state.add_transition (';', 'NUMBER_1', None, 'SEMICOLON')
- self.state.add_transition_any ('SEMICOLON', DoLog, 'INIT')
- self.state.add_transition_list (string.digits, 'SEMICOLON', DoStartNumber, 'NUMBER_2')
- self.state.add_transition_list (string.digits, 'NUMBER_2', DoBuildNumber, 'NUMBER_2')
- self.state.add_transition_any ('NUMBER_2', DoLog, 'INIT')
- self.state.add_transition ('H', 'NUMBER_2', DoHome, 'INIT')
- self.state.add_transition ('f', 'NUMBER_2', DoHome, 'INIT')
- self.state.add_transition ('r', 'NUMBER_2', DoScrollRegion, 'INIT')
- ### It gets worse... the 'm' code can have infinite number of
- ### number;number;number before it. I've never seen more than two,
- ### but the specs say it's allowed. crap!
- self.state.add_transition ('m', 'NUMBER_2', self.do_sgr, 'INIT')
- ### LED control. Same problem as 'm' code.
- self.state.add_transition ('q', 'NUMBER_2', self.do_decsca, 'INIT')
- self.state.add_transition (';', 'NUMBER_2', None, 'SEMICOLON_X')
-
- # Create a state for 'q' and 'm' which allows an infinite number of ignored numbers
- self.state.add_transition_any ('SEMICOLON_X', DoLog, 'INIT')
- self.state.add_transition_list (string.digits, 'SEMICOLON_X', DoStartNumber, 'NUMBER_X')
- self.state.add_transition_list (string.digits, 'NUMBER_X', DoBuildNumber, 'NUMBER_X')
- self.state.add_transition_any ('NUMBER_X', DoLog, 'INIT')
- self.state.add_transition ('m', 'NUMBER_X', self.do_sgr, 'INIT')
- self.state.add_transition ('q', 'NUMBER_X', self.do_decsca, 'INIT')
- self.state.add_transition (';', 'NUMBER_X', None, 'SEMICOLON_X')
-
- def process (self, c):
- """Process a single character. Called by :meth:`write`."""
- if isinstance(c, bytes):
- c = self._decode(c)
- self.state.process(c)
-
- def process_list (self, l):
-
- self.write(l)
-
- def write (self, s):
- """Process text, writing it to the virtual screen while handling
- ANSI escape codes.
- """
- if isinstance(s, bytes):
- s = self._decode(s)
- for c in s:
- self.process(c)
-
- def flush (self):
- pass
-
- def write_ch (self, ch):
- '''This puts a character at the current cursor position. The cursor
- position is moved forward with wrap-around, but no scrolling is done if
- the cursor hits the lower-right corner of the screen. '''
-
- if isinstance(ch, bytes):
- ch = self._decode(ch)
-
- #\r and \n both produce a call to cr() and lf(), respectively.
- ch = ch[0]
-
- if ch == u'\r':
- self.cr()
- return
- if ch == u'\n':
- self.crlf()
- return
- if ch == chr(screen.BS):
- self.cursor_back()
- return
- self.put_abs(self.cur_r, self.cur_c, ch)
- old_r = self.cur_r
- old_c = self.cur_c
- self.cursor_forward()
- if old_c == self.cur_c:
- self.cursor_down()
- if old_r != self.cur_r:
- self.cursor_home (self.cur_r, 1)
- else:
- self.scroll_up ()
- self.cursor_home (self.cur_r, 1)
- self.erase_line()
-
- def do_sgr (self, fsm):
- '''Select Graphic Rendition, e.g. color. '''
- screen = fsm.memory[0]
- fsm.memory = [screen]
-
- def do_decsca (self, fsm):
- '''Select character protection attribute. '''
- screen = fsm.memory[0]
- fsm.memory = [screen]
-
- def do_modecrap (self, fsm):
- '''Handler for \x1b[?<number>h and \x1b[?<number>l. If anyone
- wanted to actually use these, they'd need to add more states to the
- FSM rather than just improve or override this method. '''
- screen = fsm.memory[0]
- fsm.memory = [screen]
+'''This implements an ANSI (VT100) terminal emulator as a subclass of screen.
+
+PEXPECT LICENSE
+
+ This license is approved by the OSI and FSF as GPL-compatible.
+ http://opensource.org/licenses/isc-license.txt
+
+ Copyright (c) 2012, Noah Spurrier <noah@noah.org>
+ PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
+ PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
+ COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+'''
+
+# references:
+# http://en.wikipedia.org/wiki/ANSI_escape_code
+# http://www.retards.org/terminals/vt102.html
+# http://vt100.net/docs/vt102-ug/contents.html
+# http://vt100.net/docs/vt220-rm/
+# http://www.termsys.demon.co.uk/vtansi.htm
+
+from . import screen
+from . import FSM
+import string
+
+#
+# The 'Do.*' functions are helper functions for the ANSI class.
+#
+def DoEmit (fsm):
+
+ screen = fsm.memory[0]
+ screen.write_ch(fsm.input_symbol)
+
+def DoStartNumber (fsm):
+
+ fsm.memory.append (fsm.input_symbol)
+
+def DoBuildNumber (fsm):
+
+ ns = fsm.memory.pop()
+ ns = ns + fsm.input_symbol
+ fsm.memory.append (ns)
+
+def DoBackOne (fsm):
+
+ screen = fsm.memory[0]
+ screen.cursor_back ()
+
+def DoBack (fsm):
+
+ count = int(fsm.memory.pop())
+ screen = fsm.memory[0]
+ screen.cursor_back (count)
+
+def DoDownOne (fsm):
+
+ screen = fsm.memory[0]
+ screen.cursor_down ()
+
+def DoDown (fsm):
+
+ count = int(fsm.memory.pop())
+ screen = fsm.memory[0]
+ screen.cursor_down (count)
+
+def DoForwardOne (fsm):
+
+ screen = fsm.memory[0]
+ screen.cursor_forward ()
+
+def DoForward (fsm):
+
+ count = int(fsm.memory.pop())
+ screen = fsm.memory[0]
+ screen.cursor_forward (count)
+
+def DoUpReverse (fsm):
+
+ screen = fsm.memory[0]
+ screen.cursor_up_reverse()
+
+def DoUpOne (fsm):
+
+ screen = fsm.memory[0]
+ screen.cursor_up ()
+
+def DoUp (fsm):
+
+ count = int(fsm.memory.pop())
+ screen = fsm.memory[0]
+ screen.cursor_up (count)
+
+def DoHome (fsm):
+
+ c = int(fsm.memory.pop())
+ r = int(fsm.memory.pop())
+ screen = fsm.memory[0]
+ screen.cursor_home (r,c)
+
+def DoHomeOrigin (fsm):
+
+ c = 1
+ r = 1
+ screen = fsm.memory[0]
+ screen.cursor_home (r,c)
+
+def DoEraseDown (fsm):
+
+ screen = fsm.memory[0]
+ screen.erase_down()
+
+def DoErase (fsm):
+
+ arg = int(fsm.memory.pop())
+ screen = fsm.memory[0]
+ if arg == 0:
+ screen.erase_down()
+ elif arg == 1:
+ screen.erase_up()
+ elif arg == 2:
+ screen.erase_screen()
+
+def DoEraseEndOfLine (fsm):
+
+ screen = fsm.memory[0]
+ screen.erase_end_of_line()
+
+def DoEraseLine (fsm):
+
+ arg = int(fsm.memory.pop())
+ screen = fsm.memory[0]
+ if arg == 0:
+ screen.erase_end_of_line()
+ elif arg == 1:
+ screen.erase_start_of_line()
+ elif arg == 2:
+ screen.erase_line()
+
+def DoEnableScroll (fsm):
+
+ screen = fsm.memory[0]
+ screen.scroll_screen()
+
+def DoCursorSave (fsm):
+
+ screen = fsm.memory[0]
+ screen.cursor_save_attrs()
+
+def DoCursorRestore (fsm):
+
+ screen = fsm.memory[0]
+ screen.cursor_restore_attrs()
+
+def DoScrollRegion (fsm):
+
+ screen = fsm.memory[0]
+ r2 = int(fsm.memory.pop())
+ r1 = int(fsm.memory.pop())
+ screen.scroll_screen_rows (r1,r2)
+
+def DoMode (fsm):
+
+ screen = fsm.memory[0]
+ mode = fsm.memory.pop() # Should be 4
+ # screen.setReplaceMode ()
+
+def DoLog (fsm):
+
+ screen = fsm.memory[0]
+ fsm.memory = [screen]
+ fout = open ('log', 'a')
+ fout.write (fsm.input_symbol + ',' + fsm.current_state + '\n')
+ fout.close()
+
+class term (screen.screen):
+
+ '''This class is an abstract, generic terminal.
+ This does nothing. This is a placeholder that
+ provides a common base class for other terminals
+ such as an ANSI terminal. '''
+
+ def __init__ (self, r=24, c=80, *args, **kwargs):
+
+ screen.screen.__init__(self, r,c,*args,**kwargs)
+
+class ANSI (term):
+ '''This class implements an ANSI (VT100) terminal.
+ It is a stream filter that recognizes ANSI terminal
+ escape sequences and maintains the state of a screen object. '''
+
+ def __init__ (self, r=24,c=80,*args,**kwargs):
+
+ term.__init__(self,r,c,*args,**kwargs)
+
+ #self.screen = screen (24,80)
+ self.state = FSM.FSM ('INIT',[self])
+ self.state.set_default_transition (DoLog, 'INIT')
+ self.state.add_transition_any ('INIT', DoEmit, 'INIT')
+ self.state.add_transition ('\x1b', 'INIT', None, 'ESC')
+ self.state.add_transition_any ('ESC', DoLog, 'INIT')
+ self.state.add_transition ('(', 'ESC', None, 'G0SCS')
+ self.state.add_transition (')', 'ESC', None, 'G1SCS')
+ self.state.add_transition_list ('AB012', 'G0SCS', None, 'INIT')
+ self.state.add_transition_list ('AB012', 'G1SCS', None, 'INIT')
+ self.state.add_transition ('7', 'ESC', DoCursorSave, 'INIT')
+ self.state.add_transition ('8', 'ESC', DoCursorRestore, 'INIT')
+ self.state.add_transition ('M', 'ESC', DoUpReverse, 'INIT')
+ self.state.add_transition ('>', 'ESC', DoUpReverse, 'INIT')
+ self.state.add_transition ('<', 'ESC', DoUpReverse, 'INIT')
+ self.state.add_transition ('=', 'ESC', None, 'INIT') # Selects application keypad.
+ self.state.add_transition ('#', 'ESC', None, 'GRAPHICS_POUND')
+ self.state.add_transition_any ('GRAPHICS_POUND', None, 'INIT')
+ self.state.add_transition ('[', 'ESC', None, 'ELB')
+ # ELB means Escape Left Bracket. That is ^[[
+ self.state.add_transition ('H', 'ELB', DoHomeOrigin, 'INIT')
+ self.state.add_transition ('D', 'ELB', DoBackOne, 'INIT')
+ self.state.add_transition ('B', 'ELB', DoDownOne, 'INIT')
+ self.state.add_transition ('C', 'ELB', DoForwardOne, 'INIT')
+ self.state.add_transition ('A', 'ELB', DoUpOne, 'INIT')
+ self.state.add_transition ('J', 'ELB', DoEraseDown, 'INIT')
+ self.state.add_transition ('K', 'ELB', DoEraseEndOfLine, 'INIT')
+ self.state.add_transition ('r', 'ELB', DoEnableScroll, 'INIT')
+ self.state.add_transition ('m', 'ELB', self.do_sgr, 'INIT')
+ self.state.add_transition ('?', 'ELB', None, 'MODECRAP')
+ self.state.add_transition_list (string.digits, 'ELB', DoStartNumber, 'NUMBER_1')
+ self.state.add_transition_list (string.digits, 'NUMBER_1', DoBuildNumber, 'NUMBER_1')
+ self.state.add_transition ('D', 'NUMBER_1', DoBack, 'INIT')
+ self.state.add_transition ('B', 'NUMBER_1', DoDown, 'INIT')
+ self.state.add_transition ('C', 'NUMBER_1', DoForward, 'INIT')
+ self.state.add_transition ('A', 'NUMBER_1', DoUp, 'INIT')
+ self.state.add_transition ('J', 'NUMBER_1', DoErase, 'INIT')
+ self.state.add_transition ('K', 'NUMBER_1', DoEraseLine, 'INIT')
+ self.state.add_transition ('l', 'NUMBER_1', DoMode, 'INIT')
+ ### It gets worse... the 'm' code can have infinite number of
+ ### number;number;number before it. I've never seen more than two,
+ ### but the specs say it's allowed. crap!
+ self.state.add_transition ('m', 'NUMBER_1', self.do_sgr, 'INIT')
+ ### LED control. Same implementation problem as 'm' code.
+ self.state.add_transition ('q', 'NUMBER_1', self.do_decsca, 'INIT')
+
+ # \E[?47h switch to alternate screen
+ # \E[?47l restores to normal screen from alternate screen.
+ self.state.add_transition_list (string.digits, 'MODECRAP', DoStartNumber, 'MODECRAP_NUM')
+ self.state.add_transition_list (string.digits, 'MODECRAP_NUM', DoBuildNumber, 'MODECRAP_NUM')
+ self.state.add_transition ('l', 'MODECRAP_NUM', self.do_modecrap, 'INIT')
+ self.state.add_transition ('h', 'MODECRAP_NUM', self.do_modecrap, 'INIT')
+
+#RM Reset Mode Esc [ Ps l none
+ self.state.add_transition (';', 'NUMBER_1', None, 'SEMICOLON')
+ self.state.add_transition_any ('SEMICOLON', DoLog, 'INIT')
+ self.state.add_transition_list (string.digits, 'SEMICOLON', DoStartNumber, 'NUMBER_2')
+ self.state.add_transition_list (string.digits, 'NUMBER_2', DoBuildNumber, 'NUMBER_2')
+ self.state.add_transition_any ('NUMBER_2', DoLog, 'INIT')
+ self.state.add_transition ('H', 'NUMBER_2', DoHome, 'INIT')
+ self.state.add_transition ('f', 'NUMBER_2', DoHome, 'INIT')
+ self.state.add_transition ('r', 'NUMBER_2', DoScrollRegion, 'INIT')
+ ### It gets worse... the 'm' code can have infinite number of
+ ### number;number;number before it. I've never seen more than two,
+ ### but the specs say it's allowed. crap!
+ self.state.add_transition ('m', 'NUMBER_2', self.do_sgr, 'INIT')
+ ### LED control. Same problem as 'm' code.
+ self.state.add_transition ('q', 'NUMBER_2', self.do_decsca, 'INIT')
+ self.state.add_transition (';', 'NUMBER_2', None, 'SEMICOLON_X')
+
+ # Create a state for 'q' and 'm' which allows an infinite number of ignored numbers
+ self.state.add_transition_any ('SEMICOLON_X', DoLog, 'INIT')
+ self.state.add_transition_list (string.digits, 'SEMICOLON_X', DoStartNumber, 'NUMBER_X')
+ self.state.add_transition_list (string.digits, 'NUMBER_X', DoBuildNumber, 'NUMBER_X')
+ self.state.add_transition_any ('NUMBER_X', DoLog, 'INIT')
+ self.state.add_transition ('m', 'NUMBER_X', self.do_sgr, 'INIT')
+ self.state.add_transition ('q', 'NUMBER_X', self.do_decsca, 'INIT')
+ self.state.add_transition (';', 'NUMBER_X', None, 'SEMICOLON_X')
+
+ def process (self, c):
+ """Process a single character. Called by :meth:`write`."""
+ if isinstance(c, bytes):
+ c = self._decode(c)
+ self.state.process(c)
+
+ def process_list (self, l):
+
+ self.write(l)
+
+ def write (self, s):
+ """Process text, writing it to the virtual screen while handling
+ ANSI escape codes.
+ """
+ if isinstance(s, bytes):
+ s = self._decode(s)
+ for c in s:
+ self.process(c)
+
+ def flush (self):
+ pass
+
+ def write_ch (self, ch):
+ '''This puts a character at the current cursor position. The cursor
+ position is moved forward with wrap-around, but no scrolling is done if
+ the cursor hits the lower-right corner of the screen. '''
+
+ if isinstance(ch, bytes):
+ ch = self._decode(ch)
+
+ #\r and \n both produce a call to cr() and lf(), respectively.
+ ch = ch[0]
+
+ if ch == u'\r':
+ self.cr()
+ return
+ if ch == u'\n':
+ self.crlf()
+ return
+ if ch == chr(screen.BS):
+ self.cursor_back()
+ return
+ self.put_abs(self.cur_r, self.cur_c, ch)
+ old_r = self.cur_r
+ old_c = self.cur_c
+ self.cursor_forward()
+ if old_c == self.cur_c:
+ self.cursor_down()
+ if old_r != self.cur_r:
+ self.cursor_home (self.cur_r, 1)
+ else:
+ self.scroll_up ()
+ self.cursor_home (self.cur_r, 1)
+ self.erase_line()
+
+ def do_sgr (self, fsm):
+ '''Select Graphic Rendition, e.g. color. '''
+ screen = fsm.memory[0]
+ fsm.memory = [screen]
+
+ def do_decsca (self, fsm):
+ '''Select character protection attribute. '''
+ screen = fsm.memory[0]
+ fsm.memory = [screen]
+
+ def do_modecrap (self, fsm):
+ '''Handler for \x1b[?<number>h and \x1b[?<number>l. If anyone
+ wanted to actually use these, they'd need to add more states to the
+ FSM rather than just improve or override this method. '''
+ screen = fsm.memory[0]
+ fsm.memory = [screen]
diff --git a/contrib/python/pexpect/pexpect/FSM.py b/contrib/python/pexpect/pexpect/FSM.py
index 45fcc1baa9..46b392ea08 100644
--- a/contrib/python/pexpect/pexpect/FSM.py
+++ b/contrib/python/pexpect/pexpect/FSM.py
@@ -1,334 +1,334 @@
-#!/usr/bin/env python
-
-'''This module implements a Finite State Machine (FSM). In addition to state
-this FSM also maintains a user defined "memory". So this FSM can be used as a
-Push-down Automata (PDA) since a PDA is a FSM + memory.
-
-The following describes how the FSM works, but you will probably also need to
-see the example function to understand how the FSM is used in practice.
-
-You define an FSM by building tables of transitions. For a given input symbol
-the process() method uses these tables to decide what action to call and what
-the next state will be. The FSM has a table of transitions that associate:
-
- (input_symbol, current_state) --> (action, next_state)
-
-Where "action" is a function you define. The symbols and states can be any
-objects. You use the add_transition() and add_transition_list() methods to add
-to the transition table. The FSM also has a table of transitions that
-associate:
-
- (current_state) --> (action, next_state)
-
-You use the add_transition_any() method to add to this transition table. The
-FSM also has one default transition that is not associated with any specific
-input_symbol or state. You use the set_default_transition() method to set the
-default transition.
-
-When an action function is called it is passed a reference to the FSM. The
-action function may then access attributes of the FSM such as input_symbol,
-current_state, or "memory". The "memory" attribute can be any object that you
-want to pass along to the action functions. It is not used by the FSM itself.
-For parsing you would typically pass a list to be used as a stack.
-
-The processing sequence is as follows. The process() method is given an
-input_symbol to process. The FSM will search the table of transitions that
-associate:
-
- (input_symbol, current_state) --> (action, next_state)
-
-If the pair (input_symbol, current_state) is found then process() will call the
-associated action function and then set the current state to the next_state.
-
-If the FSM cannot find a match for (input_symbol, current_state) it will then
-search the table of transitions that associate:
-
- (current_state) --> (action, next_state)
-
-If the current_state is found then the process() method will call the
-associated action function and then set the current state to the next_state.
-Notice that this table lacks an input_symbol. It lets you define transitions
-for a current_state and ANY input_symbol. Hence, it is called the "any" table.
-Remember, it is always checked after first searching the table for a specific
-(input_symbol, current_state).
-
-For the case where the FSM did not match either of the previous two cases the
-FSM will try to use the default transition. If the default transition is
-defined then the process() method will call the associated action function and
-then set the current state to the next_state. This lets you define a default
-transition as a catch-all case. You can think of it as an exception handler.
-There can be only one default transition.
-
-Finally, if none of the previous cases are defined for an input_symbol and
-current_state then the FSM will raise an exception. This may be desirable, but
-you can always prevent this just by defining a default transition.
-
-Noah Spurrier 20020822
-
-PEXPECT LICENSE
-
- This license is approved by the OSI and FSF as GPL-compatible.
- http://opensource.org/licenses/isc-license.txt
-
- Copyright (c) 2012, Noah Spurrier <noah@noah.org>
- PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
- PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
- COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-'''
-
-class ExceptionFSM(Exception):
-
- '''This is the FSM Exception class.'''
-
- def __init__(self, value):
- self.value = value
-
- def __str__(self):
- return 'ExceptionFSM: ' + str(self.value)
-
-class FSM:
-
- '''This is a Finite State Machine (FSM).
- '''
-
- def __init__(self, initial_state, memory=None):
-
- '''This creates the FSM. You set the initial state here. The "memory"
- attribute is any object that you want to pass along to the action
- functions. It is not used by the FSM. For parsing you would typically
- pass a list to be used as a stack. '''
-
- # Map (input_symbol, current_state) --> (action, next_state).
- self.state_transitions = {}
- # Map (current_state) --> (action, next_state).
- self.state_transitions_any = {}
- self.default_transition = None
-
- self.input_symbol = None
- self.initial_state = initial_state
- self.current_state = self.initial_state
- self.next_state = None
- self.action = None
- self.memory = memory
-
- def reset (self):
-
- '''This sets the current_state to the initial_state and sets
- input_symbol to None. The initial state was set by the constructor
- __init__(). '''
-
- self.current_state = self.initial_state
- self.input_symbol = None
-
- def add_transition (self, input_symbol, state, action=None, next_state=None):
-
- '''This adds a transition that associates:
-
- (input_symbol, current_state) --> (action, next_state)
-
- The action may be set to None in which case the process() method will
- ignore the action and only set the next_state. The next_state may be
- set to None in which case the current state will be unchanged.
-
- You can also set transitions for a list of symbols by using
- add_transition_list(). '''
-
- if next_state is None:
- next_state = state
- self.state_transitions[(input_symbol, state)] = (action, next_state)
-
- def add_transition_list (self, list_input_symbols, state, action=None, next_state=None):
-
- '''This adds the same transition for a list of input symbols.
- You can pass a list or a string. Note that it is handy to use
- string.digits, string.whitespace, string.letters, etc. to add
- transitions that match character classes.
-
- The action may be set to None in which case the process() method will
- ignore the action and only set the next_state. The next_state may be
- set to None in which case the current state will be unchanged. '''
-
- if next_state is None:
- next_state = state
- for input_symbol in list_input_symbols:
- self.add_transition (input_symbol, state, action, next_state)
-
- def add_transition_any (self, state, action=None, next_state=None):
-
- '''This adds a transition that associates:
-
- (current_state) --> (action, next_state)
-
- That is, any input symbol will match the current state.
- The process() method checks the "any" state associations after it first
- checks for an exact match of (input_symbol, current_state).
-
- The action may be set to None in which case the process() method will
- ignore the action and only set the next_state. The next_state may be
- set to None in which case the current state will be unchanged. '''
-
- if next_state is None:
- next_state = state
- self.state_transitions_any [state] = (action, next_state)
-
- def set_default_transition (self, action, next_state):
-
- '''This sets the default transition. This defines an action and
- next_state if the FSM cannot find the input symbol and the current
- state in the transition list and if the FSM cannot find the
- current_state in the transition_any list. This is useful as a final
- fall-through state for catching errors and undefined states.
-
- The default transition can be removed by setting the attribute
- default_transition to None. '''
-
- self.default_transition = (action, next_state)
-
- def get_transition (self, input_symbol, state):
-
- '''This returns (action, next state) given an input_symbol and state.
- This does not modify the FSM state, so calling this method has no side
- effects. Normally you do not call this method directly. It is called by
- process().
-
- The sequence of steps to check for a defined transition goes from the
- most specific to the least specific.
-
- 1. Check state_transitions[] that match exactly the tuple,
- (input_symbol, state)
-
- 2. Check state_transitions_any[] that match (state)
- In other words, match a specific state and ANY input_symbol.
-
- 3. Check if the default_transition is defined.
- This catches any input_symbol and any state.
- This is a handler for errors, undefined states, or defaults.
-
- 4. No transition was defined. If we get here then raise an exception.
- '''
-
- if (input_symbol, state) in self.state_transitions:
- return self.state_transitions[(input_symbol, state)]
- elif state in self.state_transitions_any:
- return self.state_transitions_any[state]
- elif self.default_transition is not None:
- return self.default_transition
- else:
- raise ExceptionFSM ('Transition is undefined: (%s, %s).' %
- (str(input_symbol), str(state)) )
-
- def process (self, input_symbol):
-
- '''This is the main method that you call to process input. This may
- cause the FSM to change state and call an action. This method calls
- get_transition() to find the action and next_state associated with the
- input_symbol and current_state. If the action is None then the action
- is not called and only the current state is changed. This method
- processes one complete input symbol. You can process a list of symbols
- (or a string) by calling process_list(). '''
-
- self.input_symbol = input_symbol
- (self.action, self.next_state) = self.get_transition (self.input_symbol, self.current_state)
- if self.action is not None:
- self.action (self)
- self.current_state = self.next_state
- self.next_state = None
-
- def process_list (self, input_symbols):
-
- '''This takes a list and sends each element to process(). The list may
- be a string or any iterable object. '''
-
- for s in input_symbols:
- self.process (s)
-
-##############################################################################
-# The following is an example that demonstrates the use of the FSM class to
-# process an RPN expression. Run this module from the command line. You will
-# get a prompt > for input. Enter an RPN Expression. Numbers may be integers.
-# Operators are * / + - Use the = sign to evaluate and print the expression.
-# For example:
-#
-# 167 3 2 2 * * * 1 - =
-#
-# will print:
-#
-# 2003
-##############################################################################
-
-import sys
-import string
-
-PY3 = (sys.version_info[0] >= 3)
-
-#
-# These define the actions.
-# Note that "memory" is a list being used as a stack.
-#
-
-def BeginBuildNumber (fsm):
- fsm.memory.append (fsm.input_symbol)
-
-def BuildNumber (fsm):
- s = fsm.memory.pop ()
- s = s + fsm.input_symbol
- fsm.memory.append (s)
-
-def EndBuildNumber (fsm):
- s = fsm.memory.pop ()
- fsm.memory.append (int(s))
-
-def DoOperator (fsm):
- ar = fsm.memory.pop()
- al = fsm.memory.pop()
- if fsm.input_symbol == '+':
- fsm.memory.append (al + ar)
- elif fsm.input_symbol == '-':
- fsm.memory.append (al - ar)
- elif fsm.input_symbol == '*':
- fsm.memory.append (al * ar)
- elif fsm.input_symbol == '/':
- fsm.memory.append (al / ar)
-
-def DoEqual (fsm):
- print(str(fsm.memory.pop()))
-
-def Error (fsm):
- print('That does not compute.')
- print(str(fsm.input_symbol))
-
-def main():
-
- '''This is where the example starts and the FSM state transitions are
- defined. Note that states are strings (such as 'INIT'). This is not
- necessary, but it makes the example easier to read. '''
-
- f = FSM ('INIT', [])
- f.set_default_transition (Error, 'INIT')
- f.add_transition_any ('INIT', None, 'INIT')
- f.add_transition ('=', 'INIT', DoEqual, 'INIT')
- f.add_transition_list (string.digits, 'INIT', BeginBuildNumber, 'BUILDING_NUMBER')
- f.add_transition_list (string.digits, 'BUILDING_NUMBER', BuildNumber, 'BUILDING_NUMBER')
- f.add_transition_list (string.whitespace, 'BUILDING_NUMBER', EndBuildNumber, 'INIT')
- f.add_transition_list ('+-*/', 'INIT', DoOperator, 'INIT')
-
- print()
- print('Enter an RPN Expression.')
- print('Numbers may be integers. Operators are * / + -')
- print('Use the = sign to evaluate and print the expression.')
- print('For example: ')
- print(' 167 3 2 2 * * * 1 - =')
- inputstr = (input if PY3 else raw_input)('> ') # analysis:ignore
- f.process_list(inputstr)
-
-
-if __name__ == '__main__':
- main()
+#!/usr/bin/env python
+
+'''This module implements a Finite State Machine (FSM). In addition to state
+this FSM also maintains a user defined "memory". So this FSM can be used as a
+Push-down Automata (PDA) since a PDA is a FSM + memory.
+
+The following describes how the FSM works, but you will probably also need to
+see the example function to understand how the FSM is used in practice.
+
+You define an FSM by building tables of transitions. For a given input symbol
+the process() method uses these tables to decide what action to call and what
+the next state will be. The FSM has a table of transitions that associate:
+
+ (input_symbol, current_state) --> (action, next_state)
+
+Where "action" is a function you define. The symbols and states can be any
+objects. You use the add_transition() and add_transition_list() methods to add
+to the transition table. The FSM also has a table of transitions that
+associate:
+
+ (current_state) --> (action, next_state)
+
+You use the add_transition_any() method to add to this transition table. The
+FSM also has one default transition that is not associated with any specific
+input_symbol or state. You use the set_default_transition() method to set the
+default transition.
+
+When an action function is called it is passed a reference to the FSM. The
+action function may then access attributes of the FSM such as input_symbol,
+current_state, or "memory". The "memory" attribute can be any object that you
+want to pass along to the action functions. It is not used by the FSM itself.
+For parsing you would typically pass a list to be used as a stack.
+
+The processing sequence is as follows. The process() method is given an
+input_symbol to process. The FSM will search the table of transitions that
+associate:
+
+ (input_symbol, current_state) --> (action, next_state)
+
+If the pair (input_symbol, current_state) is found then process() will call the
+associated action function and then set the current state to the next_state.
+
+If the FSM cannot find a match for (input_symbol, current_state) it will then
+search the table of transitions that associate:
+
+ (current_state) --> (action, next_state)
+
+If the current_state is found then the process() method will call the
+associated action function and then set the current state to the next_state.
+Notice that this table lacks an input_symbol. It lets you define transitions
+for a current_state and ANY input_symbol. Hence, it is called the "any" table.
+Remember, it is always checked after first searching the table for a specific
+(input_symbol, current_state).
+
+For the case where the FSM did not match either of the previous two cases the
+FSM will try to use the default transition. If the default transition is
+defined then the process() method will call the associated action function and
+then set the current state to the next_state. This lets you define a default
+transition as a catch-all case. You can think of it as an exception handler.
+There can be only one default transition.
+
+Finally, if none of the previous cases are defined for an input_symbol and
+current_state then the FSM will raise an exception. This may be desirable, but
+you can always prevent this just by defining a default transition.
+
+Noah Spurrier 20020822
+
+PEXPECT LICENSE
+
+ This license is approved by the OSI and FSF as GPL-compatible.
+ http://opensource.org/licenses/isc-license.txt
+
+ Copyright (c) 2012, Noah Spurrier <noah@noah.org>
+ PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
+ PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
+ COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+'''
+
+class ExceptionFSM(Exception):
+
+ '''This is the FSM Exception class.'''
+
+ def __init__(self, value):
+ self.value = value
+
+ def __str__(self):
+ return 'ExceptionFSM: ' + str(self.value)
+
+class FSM:
+
+ '''This is a Finite State Machine (FSM).
+ '''
+
+ def __init__(self, initial_state, memory=None):
+
+ '''This creates the FSM. You set the initial state here. The "memory"
+ attribute is any object that you want to pass along to the action
+ functions. It is not used by the FSM. For parsing you would typically
+ pass a list to be used as a stack. '''
+
+ # Map (input_symbol, current_state) --> (action, next_state).
+ self.state_transitions = {}
+ # Map (current_state) --> (action, next_state).
+ self.state_transitions_any = {}
+ self.default_transition = None
+
+ self.input_symbol = None
+ self.initial_state = initial_state
+ self.current_state = self.initial_state
+ self.next_state = None
+ self.action = None
+ self.memory = memory
+
+ def reset (self):
+
+ '''This sets the current_state to the initial_state and sets
+ input_symbol to None. The initial state was set by the constructor
+ __init__(). '''
+
+ self.current_state = self.initial_state
+ self.input_symbol = None
+
+ def add_transition (self, input_symbol, state, action=None, next_state=None):
+
+ '''This adds a transition that associates:
+
+ (input_symbol, current_state) --> (action, next_state)
+
+ The action may be set to None in which case the process() method will
+ ignore the action and only set the next_state. The next_state may be
+ set to None in which case the current state will be unchanged.
+
+ You can also set transitions for a list of symbols by using
+ add_transition_list(). '''
+
+ if next_state is None:
+ next_state = state
+ self.state_transitions[(input_symbol, state)] = (action, next_state)
+
+ def add_transition_list (self, list_input_symbols, state, action=None, next_state=None):
+
+ '''This adds the same transition for a list of input symbols.
+ You can pass a list or a string. Note that it is handy to use
+ string.digits, string.whitespace, string.letters, etc. to add
+ transitions that match character classes.
+
+ The action may be set to None in which case the process() method will
+ ignore the action and only set the next_state. The next_state may be
+ set to None in which case the current state will be unchanged. '''
+
+ if next_state is None:
+ next_state = state
+ for input_symbol in list_input_symbols:
+ self.add_transition (input_symbol, state, action, next_state)
+
+ def add_transition_any (self, state, action=None, next_state=None):
+
+ '''This adds a transition that associates:
+
+ (current_state) --> (action, next_state)
+
+ That is, any input symbol will match the current state.
+ The process() method checks the "any" state associations after it first
+ checks for an exact match of (input_symbol, current_state).
+
+ The action may be set to None in which case the process() method will
+ ignore the action and only set the next_state. The next_state may be
+ set to None in which case the current state will be unchanged. '''
+
+ if next_state is None:
+ next_state = state
+ self.state_transitions_any [state] = (action, next_state)
+
+ def set_default_transition (self, action, next_state):
+
+ '''This sets the default transition. This defines an action and
+ next_state if the FSM cannot find the input symbol and the current
+ state in the transition list and if the FSM cannot find the
+ current_state in the transition_any list. This is useful as a final
+ fall-through state for catching errors and undefined states.
+
+ The default transition can be removed by setting the attribute
+ default_transition to None. '''
+
+ self.default_transition = (action, next_state)
+
+ def get_transition (self, input_symbol, state):
+
+ '''This returns (action, next state) given an input_symbol and state.
+ This does not modify the FSM state, so calling this method has no side
+ effects. Normally you do not call this method directly. It is called by
+ process().
+
+ The sequence of steps to check for a defined transition goes from the
+ most specific to the least specific.
+
+ 1. Check state_transitions[] that match exactly the tuple,
+ (input_symbol, state)
+
+ 2. Check state_transitions_any[] that match (state)
+ In other words, match a specific state and ANY input_symbol.
+
+ 3. Check if the default_transition is defined.
+ This catches any input_symbol and any state.
+ This is a handler for errors, undefined states, or defaults.
+
+ 4. No transition was defined. If we get here then raise an exception.
+ '''
+
+ if (input_symbol, state) in self.state_transitions:
+ return self.state_transitions[(input_symbol, state)]
+ elif state in self.state_transitions_any:
+ return self.state_transitions_any[state]
+ elif self.default_transition is not None:
+ return self.default_transition
+ else:
+ raise ExceptionFSM ('Transition is undefined: (%s, %s).' %
+ (str(input_symbol), str(state)) )
+
+ def process (self, input_symbol):
+
+ '''This is the main method that you call to process input. This may
+ cause the FSM to change state and call an action. This method calls
+ get_transition() to find the action and next_state associated with the
+ input_symbol and current_state. If the action is None then the action
+ is not called and only the current state is changed. This method
+ processes one complete input symbol. You can process a list of symbols
+ (or a string) by calling process_list(). '''
+
+ self.input_symbol = input_symbol
+ (self.action, self.next_state) = self.get_transition (self.input_symbol, self.current_state)
+ if self.action is not None:
+ self.action (self)
+ self.current_state = self.next_state
+ self.next_state = None
+
+ def process_list (self, input_symbols):
+
+ '''This takes a list and sends each element to process(). The list may
+ be a string or any iterable object. '''
+
+ for s in input_symbols:
+ self.process (s)
+
+##############################################################################
+# The following is an example that demonstrates the use of the FSM class to
+# process an RPN expression. Run this module from the command line. You will
+# get a prompt > for input. Enter an RPN Expression. Numbers may be integers.
+# Operators are * / + - Use the = sign to evaluate and print the expression.
+# For example:
+#
+# 167 3 2 2 * * * 1 - =
+#
+# will print:
+#
+# 2003
+##############################################################################
+
+import sys
+import string
+
+PY3 = (sys.version_info[0] >= 3)
+
+#
+# These define the actions.
+# Note that "memory" is a list being used as a stack.
+#
+
+def BeginBuildNumber (fsm):
+ fsm.memory.append (fsm.input_symbol)
+
+def BuildNumber (fsm):
+ s = fsm.memory.pop ()
+ s = s + fsm.input_symbol
+ fsm.memory.append (s)
+
+def EndBuildNumber (fsm):
+ s = fsm.memory.pop ()
+ fsm.memory.append (int(s))
+
+def DoOperator (fsm):
+ ar = fsm.memory.pop()
+ al = fsm.memory.pop()
+ if fsm.input_symbol == '+':
+ fsm.memory.append (al + ar)
+ elif fsm.input_symbol == '-':
+ fsm.memory.append (al - ar)
+ elif fsm.input_symbol == '*':
+ fsm.memory.append (al * ar)
+ elif fsm.input_symbol == '/':
+ fsm.memory.append (al / ar)
+
+def DoEqual (fsm):
+ print(str(fsm.memory.pop()))
+
+def Error (fsm):
+ print('That does not compute.')
+ print(str(fsm.input_symbol))
+
+def main():
+
+ '''This is where the example starts and the FSM state transitions are
+ defined. Note that states are strings (such as 'INIT'). This is not
+ necessary, but it makes the example easier to read. '''
+
+ f = FSM ('INIT', [])
+ f.set_default_transition (Error, 'INIT')
+ f.add_transition_any ('INIT', None, 'INIT')
+ f.add_transition ('=', 'INIT', DoEqual, 'INIT')
+ f.add_transition_list (string.digits, 'INIT', BeginBuildNumber, 'BUILDING_NUMBER')
+ f.add_transition_list (string.digits, 'BUILDING_NUMBER', BuildNumber, 'BUILDING_NUMBER')
+ f.add_transition_list (string.whitespace, 'BUILDING_NUMBER', EndBuildNumber, 'INIT')
+ f.add_transition_list ('+-*/', 'INIT', DoOperator, 'INIT')
+
+ print()
+ print('Enter an RPN Expression.')
+ print('Numbers may be integers. Operators are * / + -')
+ print('Use the = sign to evaluate and print the expression.')
+ print('For example: ')
+ print(' 167 3 2 2 * * * 1 - =')
+ inputstr = (input if PY3 else raw_input)('> ') # analysis:ignore
+ f.process_list(inputstr)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/contrib/python/pexpect/pexpect/__init__.py b/contrib/python/pexpect/pexpect/__init__.py
index 0e5f215e7c..7e30453787 100644
--- a/contrib/python/pexpect/pexpect/__init__.py
+++ b/contrib/python/pexpect/pexpect/__init__.py
@@ -1,85 +1,85 @@
-'''Pexpect is a Python module for spawning child applications and controlling
-them automatically. Pexpect can be used for automating interactive applications
-such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
-scripts for duplicating software package installations on different servers. It
-can be used for automated software testing. Pexpect is in the spirit of Don
-Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
-require TCL and Expect or require C extensions to be compiled. Pexpect does not
-use C, Expect, or TCL extensions. It should work on any platform that supports
-the standard Python pty module. The Pexpect interface focuses on ease of use so
-that simple tasks are easy.
-
-There are two main interfaces to the Pexpect system; these are the function,
-run() and the class, spawn. The spawn class is more powerful. The run()
-function is simpler than spawn, and is good for quickly calling program. When
-you call the run() function it executes a given program and then returns the
-output. This is a handy replacement for os.system().
-
-For example::
-
- pexpect.run('ls -la')
-
-The spawn class is the more powerful interface to the Pexpect system. You can
-use this to spawn a child program then interact with it by sending input and
-expecting responses (waiting for patterns in the child's output).
-
-For example::
-
- child = pexpect.spawn('scp foo user@example.com:.')
- child.expect('Password:')
- child.sendline(mypassword)
-
-This works even for commands that ask for passwords or other input outside of
-the normal stdio streams. For example, ssh reads input directly from the TTY
-device which bypasses stdin.
-
-Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
-Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
-vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
-Jacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey,
-Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume
-Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John
-Spiegel, Jan Grant, and Shane Kerr. Let me know if I forgot anyone.
-
-Pexpect is free, open source, and all that good stuff.
-http://pexpect.sourceforge.net/
-
-PEXPECT LICENSE
-
- This license is approved by the OSI and FSF as GPL-compatible.
- http://opensource.org/licenses/isc-license.txt
-
- Copyright (c) 2012, Noah Spurrier <noah@noah.org>
- PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
- PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
- COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-'''
-
-import sys
-PY3 = (sys.version_info[0] >= 3)
-
-from .exceptions import ExceptionPexpect, EOF, TIMEOUT
-from .utils import split_command_line, which, is_executable_file
-from .expect import Expecter, searcher_re, searcher_string
-
-if sys.platform != 'win32':
- # On Unix, these are available at the top level for backwards compatibility
- from .pty_spawn import spawn, spawnu
- from .run import run, runu
-
+'''Pexpect is a Python module for spawning child applications and controlling
+them automatically. Pexpect can be used for automating interactive applications
+such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
+scripts for duplicating software package installations on different servers. It
+can be used for automated software testing. Pexpect is in the spirit of Don
+Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
+require TCL and Expect or require C extensions to be compiled. Pexpect does not
+use C, Expect, or TCL extensions. It should work on any platform that supports
+the standard Python pty module. The Pexpect interface focuses on ease of use so
+that simple tasks are easy.
+
+There are two main interfaces to the Pexpect system; these are the function,
+run() and the class, spawn. The spawn class is more powerful. The run()
+function is simpler than spawn, and is good for quickly calling program. When
+you call the run() function it executes a given program and then returns the
+output. This is a handy replacement for os.system().
+
+For example::
+
+ pexpect.run('ls -la')
+
+The spawn class is the more powerful interface to the Pexpect system. You can
+use this to spawn a child program then interact with it by sending input and
+expecting responses (waiting for patterns in the child's output).
+
+For example::
+
+ child = pexpect.spawn('scp foo user@example.com:.')
+ child.expect('Password:')
+ child.sendline(mypassword)
+
+This works even for commands that ask for passwords or other input outside of
+the normal stdio streams. For example, ssh reads input directly from the TTY
+device which bypasses stdin.
+
+Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
+Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
+vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
+Jacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey,
+Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume
+Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John
+Spiegel, Jan Grant, and Shane Kerr. Let me know if I forgot anyone.
+
+Pexpect is free, open source, and all that good stuff.
+http://pexpect.sourceforge.net/
+
+PEXPECT LICENSE
+
+ This license is approved by the OSI and FSF as GPL-compatible.
+ http://opensource.org/licenses/isc-license.txt
+
+ Copyright (c) 2012, Noah Spurrier <noah@noah.org>
+ PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
+ PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
+ COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+'''
+
+import sys
+PY3 = (sys.version_info[0] >= 3)
+
+from .exceptions import ExceptionPexpect, EOF, TIMEOUT
+from .utils import split_command_line, which, is_executable_file
+from .expect import Expecter, searcher_re, searcher_string
+
+if sys.platform != 'win32':
+ # On Unix, these are available at the top level for backwards compatibility
+ from .pty_spawn import spawn, spawnu
+ from .run import run, runu
+
__version__ = '4.8.0'
-__revision__ = ''
-__all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnu', 'run', 'runu',
- 'which', 'split_command_line', '__version__', '__revision__']
-
-
-
-# vim: set shiftround expandtab tabstop=4 shiftwidth=4 ft=python autoindent :
+__revision__ = ''
+__all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnu', 'run', 'runu',
+ 'which', 'split_command_line', '__version__', '__revision__']
+
+
+
+# vim: set shiftround expandtab tabstop=4 shiftwidth=4 ft=python autoindent :
diff --git a/contrib/python/pexpect/pexpect/_async.py b/contrib/python/pexpect/pexpect/_async.py
index 4260ad6107..dfbfeef5fb 100644
--- a/contrib/python/pexpect/pexpect/_async.py
+++ b/contrib/python/pexpect/pexpect/_async.py
@@ -1,16 +1,16 @@
-import asyncio
-import errno
+import asyncio
+import errno
import signal
-
-from pexpect import EOF
-
-@asyncio.coroutine
-def expect_async(expecter, timeout=None):
- # First process data that was previously read - if it maches, we don't need
- # async stuff.
+
+from pexpect import EOF
+
+@asyncio.coroutine
+def expect_async(expecter, timeout=None):
+ # First process data that was previously read - if it maches, we don't need
+ # async stuff.
idx = expecter.existing_data()
- if idx is not None:
- return idx
+ if idx is not None:
+ return idx
if not expecter.spawn.async_pw_transport:
pw = PatternWaiter()
pw.set_expecter(expecter)
@@ -21,12 +21,12 @@ def expect_async(expecter, timeout=None):
pw, transport = expecter.spawn.async_pw_transport
pw.set_expecter(expecter)
transport.resume_reading()
- try:
- return (yield from asyncio.wait_for(pw.fut, timeout))
- except asyncio.TimeoutError as e:
- transport.pause_reading()
- return expecter.timeout(e)
-
+ try:
+ return (yield from asyncio.wait_for(pw.fut, timeout))
+ except asyncio.TimeoutError as e:
+ transport.pause_reading()
+ return expecter.timeout(e)
+
@asyncio.coroutine
def repl_run_command_async(repl, cmdlines, timeout=-1):
res = []
@@ -45,59 +45,59 @@ def repl_run_command_async(repl, cmdlines, timeout=-1):
raise ValueError("Continuation prompt found - input was incomplete:")
return u''.join(res + [repl.child.before])
-class PatternWaiter(asyncio.Protocol):
+class PatternWaiter(asyncio.Protocol):
transport = None
def set_expecter(self, expecter):
- self.expecter = expecter
- self.fut = asyncio.Future()
+ self.expecter = expecter
+ self.fut = asyncio.Future()
- def found(self, result):
- if not self.fut.done():
- self.fut.set_result(result)
+ def found(self, result):
+ if not self.fut.done():
+ self.fut.set_result(result)
self.transport.pause_reading()
- def error(self, exc):
- if not self.fut.done():
- self.fut.set_exception(exc)
+ def error(self, exc):
+ if not self.fut.done():
+ self.fut.set_exception(exc)
self.transport.pause_reading()
def connection_made(self, transport):
self.transport = transport
- def data_received(self, data):
- spawn = self.expecter.spawn
- s = spawn._decoder.decode(data)
- spawn._log(s, 'read')
-
- if self.fut.done():
+ def data_received(self, data):
+ spawn = self.expecter.spawn
+ s = spawn._decoder.decode(data)
+ spawn._log(s, 'read')
+
+ if self.fut.done():
spawn._before.write(s)
spawn._buffer.write(s)
- return
-
- try:
+ return
+
+ try:
index = self.expecter.new_data(s)
- if index is not None:
- # Found a match
- self.found(index)
- except Exception as e:
- self.expecter.errored()
- self.error(e)
+ if index is not None:
+ # Found a match
+ self.found(index)
+ except Exception as e:
+ self.expecter.errored()
+ self.error(e)
- def eof_received(self):
- # N.B. If this gets called, async will close the pipe (the spawn object)
- # for us
- try:
- self.expecter.spawn.flag_eof = True
- index = self.expecter.eof()
- except EOF as e:
- self.error(e)
- else:
- self.found(index)
+ def eof_received(self):
+ # N.B. If this gets called, async will close the pipe (the spawn object)
+ # for us
+ try:
+ self.expecter.spawn.flag_eof = True
+ index = self.expecter.eof()
+ except EOF as e:
+ self.error(e)
+ else:
+ self.found(index)
- def connection_lost(self, exc):
- if isinstance(exc, OSError) and exc.errno == errno.EIO:
- # We may get here without eof_received being called, e.g on Linux
- self.eof_received()
- elif exc is not None:
- self.error(exc)
+ def connection_lost(self, exc):
+ if isinstance(exc, OSError) and exc.errno == errno.EIO:
+ # We may get here without eof_received being called, e.g on Linux
+ self.eof_received()
+ elif exc is not None:
+ self.error(exc)
diff --git a/contrib/python/pexpect/pexpect/exceptions.py b/contrib/python/pexpect/pexpect/exceptions.py
index f1c10df2e1..cb360f0261 100644
--- a/contrib/python/pexpect/pexpect/exceptions.py
+++ b/contrib/python/pexpect/pexpect/exceptions.py
@@ -1,35 +1,35 @@
-"""Exception classes used by Pexpect"""
-
-import traceback
-import sys
-
-class ExceptionPexpect(Exception):
- '''Base class for all exceptions raised by this module.
- '''
-
- def __init__(self, value):
- super(ExceptionPexpect, self).__init__(value)
- self.value = value
-
- def __str__(self):
- return str(self.value)
-
- def get_trace(self):
- '''This returns an abbreviated stack trace with lines that only concern
- the caller. In other words, the stack trace inside the Pexpect module
- is not included. '''
-
- tblist = traceback.extract_tb(sys.exc_info()[2])
- tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])
- and ('pexpect/expect' not in item[0])]
- tblist = traceback.format_list(tblist)
- return ''.join(tblist)
-
-
-class EOF(ExceptionPexpect):
- '''Raised when EOF is read from a child.
- This usually means the child has exited.'''
-
-
-class TIMEOUT(ExceptionPexpect):
- '''Raised when a read time exceeds the timeout. '''
+"""Exception classes used by Pexpect"""
+
+import traceback
+import sys
+
+class ExceptionPexpect(Exception):
+ '''Base class for all exceptions raised by this module.
+ '''
+
+ def __init__(self, value):
+ super(ExceptionPexpect, self).__init__(value)
+ self.value = value
+
+ def __str__(self):
+ return str(self.value)
+
+ def get_trace(self):
+ '''This returns an abbreviated stack trace with lines that only concern
+ the caller. In other words, the stack trace inside the Pexpect module
+ is not included. '''
+
+ tblist = traceback.extract_tb(sys.exc_info()[2])
+ tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])
+ and ('pexpect/expect' not in item[0])]
+ tblist = traceback.format_list(tblist)
+ return ''.join(tblist)
+
+
+class EOF(ExceptionPexpect):
+ '''Raised when EOF is read from a child.
+ This usually means the child has exited.'''
+
+
+class TIMEOUT(ExceptionPexpect):
+ '''Raised when a read time exceeds the timeout. '''
diff --git a/contrib/python/pexpect/pexpect/expect.py b/contrib/python/pexpect/pexpect/expect.py
index 00ad4f0748..d3409db9d7 100644
--- a/contrib/python/pexpect/pexpect/expect.py
+++ b/contrib/python/pexpect/pexpect/expect.py
@@ -1,27 +1,27 @@
-import time
-
-from .exceptions import EOF, TIMEOUT
-
-class Expecter(object):
- def __init__(self, spawn, searcher, searchwindowsize=-1):
- self.spawn = spawn
- self.searcher = searcher
+import time
+
+from .exceptions import EOF, TIMEOUT
+
+class Expecter(object):
+ def __init__(self, spawn, searcher, searchwindowsize=-1):
+ self.spawn = spawn
+ self.searcher = searcher
# A value of -1 means to use the figure from spawn, which should
# be None or a positive number.
- if searchwindowsize == -1:
- searchwindowsize = spawn.searchwindowsize
- self.searchwindowsize = searchwindowsize
+ if searchwindowsize == -1:
+ searchwindowsize = spawn.searchwindowsize
+ self.searchwindowsize = searchwindowsize
self.lookback = None
if hasattr(searcher, 'longest_string'):
self.lookback = searcher.longest_string
def do_search(self, window, freshlen):
- spawn = self.spawn
- searcher = self.searcher
+ spawn = self.spawn
+ searcher = self.searcher
if freshlen > len(window):
freshlen = len(window)
index = searcher.search(window, freshlen, self.searchwindowsize)
- if index >= 0:
+ if index >= 0:
spawn._buffer = spawn.buffer_type()
spawn._buffer.write(window[searcher.end:])
spawn.before = spawn._before.getvalue()[
@@ -29,10 +29,10 @@ class Expecter(object):
spawn._before = spawn.buffer_type()
spawn._before.write(window[searcher.end:])
spawn.after = window[searcher.start:searcher.end]
- spawn.match = searcher.match
- spawn.match_index = index
- # Found a match
- return index
+ spawn.match = searcher.match
+ spawn.match_index = index
+ # Found a match
+ return index
elif self.searchwindowsize or self.lookback:
maintain = self.searchwindowsize or self.lookback
if spawn._buffer.tell() > maintain:
@@ -97,275 +97,275 @@ class Expecter(object):
window = spawn._buffer.read()
return self.do_search(window, freshlen)
- def eof(self, err=None):
- spawn = self.spawn
-
+ def eof(self, err=None):
+ spawn = self.spawn
+
spawn.before = spawn._before.getvalue()
spawn._buffer = spawn.buffer_type()
spawn._before = spawn.buffer_type()
- spawn.after = EOF
- index = self.searcher.eof_index
- if index >= 0:
- spawn.match = EOF
- spawn.match_index = index
- return index
- else:
- spawn.match = None
- spawn.match_index = None
- msg = str(spawn)
+ spawn.after = EOF
+ index = self.searcher.eof_index
+ if index >= 0:
+ spawn.match = EOF
+ spawn.match_index = index
+ return index
+ else:
+ spawn.match = None
+ spawn.match_index = None
+ msg = str(spawn)
msg += '\nsearcher: %s' % self.searcher
- if err is not None:
- msg = str(err) + '\n' + msg
+ if err is not None:
+ msg = str(err) + '\n' + msg
exc = EOF(msg)
exc.__cause__ = None # in Python 3.x we can use "raise exc from None"
raise exc
- def timeout(self, err=None):
- spawn = self.spawn
-
+ def timeout(self, err=None):
+ spawn = self.spawn
+
spawn.before = spawn._before.getvalue()
- spawn.after = TIMEOUT
- index = self.searcher.timeout_index
- if index >= 0:
- spawn.match = TIMEOUT
- spawn.match_index = index
- return index
- else:
- spawn.match = None
- spawn.match_index = None
- msg = str(spawn)
+ spawn.after = TIMEOUT
+ index = self.searcher.timeout_index
+ if index >= 0:
+ spawn.match = TIMEOUT
+ spawn.match_index = index
+ return index
+ else:
+ spawn.match = None
+ spawn.match_index = None
+ msg = str(spawn)
msg += '\nsearcher: %s' % self.searcher
- if err is not None:
- msg = str(err) + '\n' + msg
-
+ if err is not None:
+ msg = str(err) + '\n' + msg
+
exc = TIMEOUT(msg)
exc.__cause__ = None # in Python 3.x we can use "raise exc from None"
raise exc
- def errored(self):
- spawn = self.spawn
+ def errored(self):
+ spawn = self.spawn
spawn.before = spawn._before.getvalue()
- spawn.after = None
- spawn.match = None
- spawn.match_index = None
-
- def expect_loop(self, timeout=-1):
- """Blocking expect"""
- spawn = self.spawn
-
- if timeout is not None:
- end_time = time.time() + timeout
-
- try:
+ spawn.after = None
+ spawn.match = None
+ spawn.match_index = None
+
+ def expect_loop(self, timeout=-1):
+ """Blocking expect"""
+ spawn = self.spawn
+
+ if timeout is not None:
+ end_time = time.time() + timeout
+
+ try:
idx = self.existing_data()
if idx is not None:
return idx
- while True:
- # No match at this point
- if (timeout is not None) and (timeout < 0):
- return self.timeout()
- # Still have time left, so read more data
- incoming = spawn.read_nonblocking(spawn.maxread, timeout)
+ while True:
+ # No match at this point
+ if (timeout is not None) and (timeout < 0):
+ return self.timeout()
+ # Still have time left, so read more data
+ incoming = spawn.read_nonblocking(spawn.maxread, timeout)
if self.spawn.delayafterread is not None:
time.sleep(self.spawn.delayafterread)
idx = self.new_data(incoming)
# Keep reading until exception or return.
if idx is not None:
return idx
- if timeout is not None:
- timeout = end_time - time.time()
- except EOF as e:
- return self.eof(e)
- except TIMEOUT as e:
- return self.timeout(e)
- except:
- self.errored()
- raise
-
-
-class searcher_string(object):
- '''This is a plain string search helper for the spawn.expect_any() method.
- This helper class is for speed. For more powerful regex patterns
- see the helper class, searcher_re.
-
- Attributes:
-
- eof_index - index of EOF, or -1
- timeout_index - index of TIMEOUT, or -1
-
- After a successful match by the search() method the following attributes
- are available:
-
- start - index into the buffer, first byte of match
- end - index into the buffer, first byte after match
- match - the matching string itself
-
- '''
-
- def __init__(self, strings):
- '''This creates an instance of searcher_string. This argument 'strings'
- may be a list; a sequence of strings; or the EOF or TIMEOUT types. '''
-
- self.eof_index = -1
- self.timeout_index = -1
- self._strings = []
+ if timeout is not None:
+ timeout = end_time - time.time()
+ except EOF as e:
+ return self.eof(e)
+ except TIMEOUT as e:
+ return self.timeout(e)
+ except:
+ self.errored()
+ raise
+
+
+class searcher_string(object):
+ '''This is a plain string search helper for the spawn.expect_any() method.
+ This helper class is for speed. For more powerful regex patterns
+ see the helper class, searcher_re.
+
+ Attributes:
+
+ eof_index - index of EOF, or -1
+ timeout_index - index of TIMEOUT, or -1
+
+ After a successful match by the search() method the following attributes
+ are available:
+
+ start - index into the buffer, first byte of match
+ end - index into the buffer, first byte after match
+ match - the matching string itself
+
+ '''
+
+ def __init__(self, strings):
+ '''This creates an instance of searcher_string. This argument 'strings'
+ may be a list; a sequence of strings; or the EOF or TIMEOUT types. '''
+
+ self.eof_index = -1
+ self.timeout_index = -1
+ self._strings = []
self.longest_string = 0
- for n, s in enumerate(strings):
- if s is EOF:
- self.eof_index = n
- continue
- if s is TIMEOUT:
- self.timeout_index = n
- continue
- self._strings.append((n, s))
+ for n, s in enumerate(strings):
+ if s is EOF:
+ self.eof_index = n
+ continue
+ if s is TIMEOUT:
+ self.timeout_index = n
+ continue
+ self._strings.append((n, s))
if len(s) > self.longest_string:
self.longest_string = len(s)
-
- def __str__(self):
- '''This returns a human-readable string that represents the state of
- the object.'''
-
+
+ def __str__(self):
+ '''This returns a human-readable string that represents the state of
+ the object.'''
+
ss = [(ns[0], ' %d: %r' % ns) for ns in self._strings]
- ss.append((-1, 'searcher_string:'))
- if self.eof_index >= 0:
- ss.append((self.eof_index, ' %d: EOF' % self.eof_index))
- if self.timeout_index >= 0:
- ss.append((self.timeout_index,
- ' %d: TIMEOUT' % self.timeout_index))
- ss.sort()
- ss = list(zip(*ss))[1]
- return '\n'.join(ss)
-
- def search(self, buffer, freshlen, searchwindowsize=None):
+ ss.append((-1, 'searcher_string:'))
+ if self.eof_index >= 0:
+ ss.append((self.eof_index, ' %d: EOF' % self.eof_index))
+ if self.timeout_index >= 0:
+ ss.append((self.timeout_index,
+ ' %d: TIMEOUT' % self.timeout_index))
+ ss.sort()
+ ss = list(zip(*ss))[1]
+ return '\n'.join(ss)
+
+ def search(self, buffer, freshlen, searchwindowsize=None):
'''This searches 'buffer' for the first occurrence of one of the search
- strings. 'freshlen' must indicate the number of bytes at the end of
- 'buffer' which have not been searched before. It helps to avoid
- searching the same, possibly big, buffer over and over again.
-
- See class spawn for the 'searchwindowsize' argument.
-
- If there is a match this returns the index of that string, and sets
- 'start', 'end' and 'match'. Otherwise, this returns -1. '''
-
- first_match = None
-
- # 'freshlen' helps a lot here. Further optimizations could
- # possibly include:
- #
- # using something like the Boyer-Moore Fast String Searching
- # Algorithm; pre-compiling the search through a list of
- # strings into something that can scan the input once to
- # search for all N strings; realize that if we search for
- # ['bar', 'baz'] and the input is '...foo' we need not bother
- # rescanning until we've read three more bytes.
- #
- # Sadly, I don't know enough about this interesting topic. /grahn
-
- for index, s in self._strings:
- if searchwindowsize is None:
- # the match, if any, can only be in the fresh data,
- # or at the very end of the old data
- offset = -(freshlen + len(s))
- else:
- # better obey searchwindowsize
- offset = -searchwindowsize
- n = buffer.find(s, offset)
- if n >= 0 and (first_match is None or n < first_match):
- first_match = n
- best_index, best_match = index, s
- if first_match is None:
- return -1
- self.match = best_match
- self.start = first_match
- self.end = self.start + len(self.match)
- return best_index
-
-
-class searcher_re(object):
- '''This is regular expression string search helper for the
- spawn.expect_any() method. This helper class is for powerful
- pattern matching. For speed, see the helper class, searcher_string.
-
- Attributes:
-
- eof_index - index of EOF, or -1
- timeout_index - index of TIMEOUT, or -1
-
- After a successful match by the search() method the following attributes
- are available:
-
- start - index into the buffer, first byte of match
- end - index into the buffer, first byte after match
+ strings. 'freshlen' must indicate the number of bytes at the end of
+ 'buffer' which have not been searched before. It helps to avoid
+ searching the same, possibly big, buffer over and over again.
+
+ See class spawn for the 'searchwindowsize' argument.
+
+ If there is a match this returns the index of that string, and sets
+ 'start', 'end' and 'match'. Otherwise, this returns -1. '''
+
+ first_match = None
+
+ # 'freshlen' helps a lot here. Further optimizations could
+ # possibly include:
+ #
+ # using something like the Boyer-Moore Fast String Searching
+ # Algorithm; pre-compiling the search through a list of
+ # strings into something that can scan the input once to
+ # search for all N strings; realize that if we search for
+ # ['bar', 'baz'] and the input is '...foo' we need not bother
+ # rescanning until we've read three more bytes.
+ #
+ # Sadly, I don't know enough about this interesting topic. /grahn
+
+ for index, s in self._strings:
+ if searchwindowsize is None:
+ # the match, if any, can only be in the fresh data,
+ # or at the very end of the old data
+ offset = -(freshlen + len(s))
+ else:
+ # better obey searchwindowsize
+ offset = -searchwindowsize
+ n = buffer.find(s, offset)
+ if n >= 0 and (first_match is None or n < first_match):
+ first_match = n
+ best_index, best_match = index, s
+ if first_match is None:
+ return -1
+ self.match = best_match
+ self.start = first_match
+ self.end = self.start + len(self.match)
+ return best_index
+
+
+class searcher_re(object):
+ '''This is regular expression string search helper for the
+ spawn.expect_any() method. This helper class is for powerful
+ pattern matching. For speed, see the helper class, searcher_string.
+
+ Attributes:
+
+ eof_index - index of EOF, or -1
+ timeout_index - index of TIMEOUT, or -1
+
+ After a successful match by the search() method the following attributes
+ are available:
+
+ start - index into the buffer, first byte of match
+ end - index into the buffer, first byte after match
match - the re.match object returned by a successful re.search
-
- '''
-
- def __init__(self, patterns):
- '''This creates an instance that searches for 'patterns' Where
- 'patterns' may be a list or other sequence of compiled regular
- expressions, or the EOF or TIMEOUT types.'''
-
- self.eof_index = -1
- self.timeout_index = -1
- self._searches = []
+
+ '''
+
+ def __init__(self, patterns):
+ '''This creates an instance that searches for 'patterns' Where
+ 'patterns' may be a list or other sequence of compiled regular
+ expressions, or the EOF or TIMEOUT types.'''
+
+ self.eof_index = -1
+ self.timeout_index = -1
+ self._searches = []
for n, s in enumerate(patterns):
- if s is EOF:
- self.eof_index = n
- continue
- if s is TIMEOUT:
- self.timeout_index = n
- continue
- self._searches.append((n, s))
-
- def __str__(self):
- '''This returns a human-readable string that represents the state of
- the object.'''
-
- #ss = [(n, ' %d: re.compile("%s")' %
- # (n, repr(s.pattern))) for n, s in self._searches]
- ss = list()
- for n, s in self._searches:
+ if s is EOF:
+ self.eof_index = n
+ continue
+ if s is TIMEOUT:
+ self.timeout_index = n
+ continue
+ self._searches.append((n, s))
+
+ def __str__(self):
+ '''This returns a human-readable string that represents the state of
+ the object.'''
+
+ #ss = [(n, ' %d: re.compile("%s")' %
+ # (n, repr(s.pattern))) for n, s in self._searches]
+ ss = list()
+ for n, s in self._searches:
ss.append((n, ' %d: re.compile(%r)' % (n, s.pattern)))
- ss.append((-1, 'searcher_re:'))
- if self.eof_index >= 0:
- ss.append((self.eof_index, ' %d: EOF' % self.eof_index))
- if self.timeout_index >= 0:
- ss.append((self.timeout_index, ' %d: TIMEOUT' %
- self.timeout_index))
- ss.sort()
- ss = list(zip(*ss))[1]
- return '\n'.join(ss)
-
- def search(self, buffer, freshlen, searchwindowsize=None):
+ ss.append((-1, 'searcher_re:'))
+ if self.eof_index >= 0:
+ ss.append((self.eof_index, ' %d: EOF' % self.eof_index))
+ if self.timeout_index >= 0:
+ ss.append((self.timeout_index, ' %d: TIMEOUT' %
+ self.timeout_index))
+ ss.sort()
+ ss = list(zip(*ss))[1]
+ return '\n'.join(ss)
+
+ def search(self, buffer, freshlen, searchwindowsize=None):
'''This searches 'buffer' for the first occurrence of one of the regular
- expressions. 'freshlen' must indicate the number of bytes at the end of
- 'buffer' which have not been searched before.
-
- See class spawn for the 'searchwindowsize' argument.
-
- If there is a match this returns the index of that string, and sets
- 'start', 'end' and 'match'. Otherwise, returns -1.'''
-
- first_match = None
- # 'freshlen' doesn't help here -- we cannot predict the
- # length of a match, and the re module provides no help.
- if searchwindowsize is None:
- searchstart = 0
- else:
- searchstart = max(0, len(buffer) - searchwindowsize)
- for index, s in self._searches:
- match = s.search(buffer, searchstart)
- if match is None:
- continue
- n = match.start()
- if first_match is None or n < first_match:
- first_match = n
- the_match = match
- best_index = index
- if first_match is None:
- return -1
- self.start = first_match
- self.match = the_match
- self.end = self.match.end()
+ expressions. 'freshlen' must indicate the number of bytes at the end of
+ 'buffer' which have not been searched before.
+
+ See class spawn for the 'searchwindowsize' argument.
+
+ If there is a match this returns the index of that string, and sets
+ 'start', 'end' and 'match'. Otherwise, returns -1.'''
+
+ first_match = None
+ # 'freshlen' doesn't help here -- we cannot predict the
+ # length of a match, and the re module provides no help.
+ if searchwindowsize is None:
+ searchstart = 0
+ else:
+ searchstart = max(0, len(buffer) - searchwindowsize)
+ for index, s in self._searches:
+ match = s.search(buffer, searchstart)
+ if match is None:
+ continue
+ n = match.start()
+ if first_match is None or n < first_match:
+ first_match = n
+ the_match = match
+ best_index = index
+ if first_match is None:
+ return -1
+ self.start = first_match
+ self.match = the_match
+ self.end = self.match.end()
return best_index
diff --git a/contrib/python/pexpect/pexpect/fdpexpect.py b/contrib/python/pexpect/pexpect/fdpexpect.py
index a3096537f6..cddd50e100 100644
--- a/contrib/python/pexpect/pexpect/fdpexpect.py
+++ b/contrib/python/pexpect/pexpect/fdpexpect.py
@@ -1,119 +1,119 @@
-'''This is like pexpect, but it will work with any file descriptor that you
+'''This is like pexpect, but it will work with any file descriptor that you
pass it. You are responsible for opening and close the file descriptor.
-This allows you to use Pexpect with sockets and named pipes (FIFOs).
-
-PEXPECT LICENSE
-
- This license is approved by the OSI and FSF as GPL-compatible.
- http://opensource.org/licenses/isc-license.txt
-
- Copyright (c) 2012, Noah Spurrier <noah@noah.org>
- PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
- PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
- COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-'''
-
-from .spawnbase import SpawnBase
+This allows you to use Pexpect with sockets and named pipes (FIFOs).
+
+PEXPECT LICENSE
+
+ This license is approved by the OSI and FSF as GPL-compatible.
+ http://opensource.org/licenses/isc-license.txt
+
+ Copyright (c) 2012, Noah Spurrier <noah@noah.org>
+ PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
+ PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
+ COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+'''
+
+from .spawnbase import SpawnBase
from .exceptions import ExceptionPexpect, TIMEOUT
from .utils import select_ignore_interrupts, poll_ignore_interrupts
-import os
-
-__all__ = ['fdspawn']
-
-class fdspawn(SpawnBase):
- '''This is like pexpect.spawn but allows you to supply your own open file
- descriptor. For example, you could use it to read through a file looking
- for patterns, or to control a modem or serial device. '''
-
- def __init__ (self, fd, args=None, timeout=30, maxread=2000, searchwindowsize=None,
+import os
+
+__all__ = ['fdspawn']
+
+class fdspawn(SpawnBase):
+ '''This is like pexpect.spawn but allows you to supply your own open file
+ descriptor. For example, you could use it to read through a file looking
+ for patterns, or to control a modem or serial device. '''
+
+ def __init__ (self, fd, args=None, timeout=30, maxread=2000, searchwindowsize=None,
logfile=None, encoding=None, codec_errors='strict', use_poll=False):
- '''This takes a file descriptor (an int) or an object that support the
- fileno() method (returning an int). All Python file-like objects
- support fileno(). '''
-
- if type(fd) != type(0) and hasattr(fd, 'fileno'):
- fd = fd.fileno()
-
- if type(fd) != type(0):
- raise ExceptionPexpect('The fd argument is not an int. If this is a command string then maybe you want to use pexpect.spawn.')
-
- try: # make sure fd is a valid file descriptor
- os.fstat(fd)
- except OSError:
- raise ExceptionPexpect('The fd argument is not a valid file descriptor.')
-
- self.args = None
- self.command = None
- SpawnBase.__init__(self, timeout, maxread, searchwindowsize, logfile,
- encoding=encoding, codec_errors=codec_errors)
- self.child_fd = fd
- self.own_fd = False
- self.closed = False
- self.name = '<file descriptor %d>' % fd
+ '''This takes a file descriptor (an int) or an object that support the
+ fileno() method (returning an int). All Python file-like objects
+ support fileno(). '''
+
+ if type(fd) != type(0) and hasattr(fd, 'fileno'):
+ fd = fd.fileno()
+
+ if type(fd) != type(0):
+ raise ExceptionPexpect('The fd argument is not an int. If this is a command string then maybe you want to use pexpect.spawn.')
+
+ try: # make sure fd is a valid file descriptor
+ os.fstat(fd)
+ except OSError:
+ raise ExceptionPexpect('The fd argument is not a valid file descriptor.')
+
+ self.args = None
+ self.command = None
+ SpawnBase.__init__(self, timeout, maxread, searchwindowsize, logfile,
+ encoding=encoding, codec_errors=codec_errors)
+ self.child_fd = fd
+ self.own_fd = False
+ self.closed = False
+ self.name = '<file descriptor %d>' % fd
self.use_poll = use_poll
-
- def close (self):
- """Close the file descriptor.
-
- Calling this method a second time does nothing, but if the file
- descriptor was closed elsewhere, :class:`OSError` will be raised.
- """
- if self.child_fd == -1:
- return
-
- self.flush()
- os.close(self.child_fd)
- self.child_fd = -1
- self.closed = True
-
- def isalive (self):
- '''This checks if the file descriptor is still valid. If :func:`os.fstat`
- does not raise an exception then we assume it is alive. '''
-
- if self.child_fd == -1:
- return False
- try:
- os.fstat(self.child_fd)
- return True
- except:
- return False
-
- def terminate (self, force=False): # pragma: no cover
- '''Deprecated and invalid. Just raises an exception.'''
- raise ExceptionPexpect('This method is not valid for file descriptors.')
-
- # These four methods are left around for backwards compatibility, but not
- # documented as part of fdpexpect. You're encouraged to use os.write
- # directly.
- def send(self, s):
- "Write to fd, return number of bytes written"
- s = self._coerce_send_string(s)
- self._log(s, 'send')
-
- b = self._encoder.encode(s, final=False)
- return os.write(self.child_fd, b)
-
- def sendline(self, s):
- "Write to fd with trailing newline, return number of bytes written"
- s = self._coerce_send_string(s)
- return self.send(s + self.linesep)
-
- def write(self, s):
- "Write to fd, return None"
- self.send(s)
-
- def writelines(self, sequence):
- "Call self.write() for each item in sequence"
- for s in sequence:
- self.write(s)
+
+ def close (self):
+ """Close the file descriptor.
+
+ Calling this method a second time does nothing, but if the file
+ descriptor was closed elsewhere, :class:`OSError` will be raised.
+ """
+ if self.child_fd == -1:
+ return
+
+ self.flush()
+ os.close(self.child_fd)
+ self.child_fd = -1
+ self.closed = True
+
+ def isalive (self):
+ '''This checks if the file descriptor is still valid. If :func:`os.fstat`
+ does not raise an exception then we assume it is alive. '''
+
+ if self.child_fd == -1:
+ return False
+ try:
+ os.fstat(self.child_fd)
+ return True
+ except:
+ return False
+
+ def terminate (self, force=False): # pragma: no cover
+ '''Deprecated and invalid. Just raises an exception.'''
+ raise ExceptionPexpect('This method is not valid for file descriptors.')
+
+ # These four methods are left around for backwards compatibility, but not
+ # documented as part of fdpexpect. You're encouraged to use os.write
+ # directly.
+ def send(self, s):
+ "Write to fd, return number of bytes written"
+ s = self._coerce_send_string(s)
+ self._log(s, 'send')
+
+ b = self._encoder.encode(s, final=False)
+ return os.write(self.child_fd, b)
+
+ def sendline(self, s):
+ "Write to fd with trailing newline, return number of bytes written"
+ s = self._coerce_send_string(s)
+ return self.send(s + self.linesep)
+
+ def write(self, s):
+ "Write to fd, return None"
+ self.send(s)
+
+ def writelines(self, sequence):
+ "Call self.write() for each item in sequence"
+ for s in sequence:
+ self.write(s)
def read_nonblocking(self, size=1, timeout=-1):
"""
diff --git a/contrib/python/pexpect/pexpect/popen_spawn.py b/contrib/python/pexpect/pexpect/popen_spawn.py
index 59cd85738a..4bb58cfe76 100644
--- a/contrib/python/pexpect/pexpect/popen_spawn.py
+++ b/contrib/python/pexpect/pexpect/popen_spawn.py
@@ -1,30 +1,30 @@
-"""Provides an interface like pexpect.spawn interface using subprocess.Popen
-"""
-import os
-import threading
-import subprocess
-import sys
-import time
-import signal
-import shlex
-
-try:
- from queue import Queue, Empty # Python 3
-except ImportError:
- from Queue import Queue, Empty # Python 2
-
-from .spawnbase import SpawnBase, PY3
-from .exceptions import EOF
+"""Provides an interface like pexpect.spawn interface using subprocess.Popen
+"""
+import os
+import threading
+import subprocess
+import sys
+import time
+import signal
+import shlex
+
+try:
+ from queue import Queue, Empty # Python 3
+except ImportError:
+ from Queue import Queue, Empty # Python 2
+
+from .spawnbase import SpawnBase, PY3
+from .exceptions import EOF
from .utils import string_types
-
-class PopenSpawn(SpawnBase):
- def __init__(self, cmd, timeout=30, maxread=2000, searchwindowsize=None,
+
+class PopenSpawn(SpawnBase):
+ def __init__(self, cmd, timeout=30, maxread=2000, searchwindowsize=None,
logfile=None, cwd=None, env=None, encoding=None,
codec_errors='strict', preexec_fn=None):
- super(PopenSpawn, self).__init__(timeout=timeout, maxread=maxread,
- searchwindowsize=searchwindowsize, logfile=logfile,
- encoding=encoding, codec_errors=codec_errors)
-
+ super(PopenSpawn, self).__init__(timeout=timeout, maxread=maxread,
+ searchwindowsize=searchwindowsize, logfile=logfile,
+ encoding=encoding, codec_errors=codec_errors)
+
# Note that `SpawnBase` initializes `self.crlf` to `\r\n`
# because the default behaviour for a PTY is to convert
# incoming LF to `\r\n` (see the `onlcr` flag and
@@ -37,152 +37,152 @@ class PopenSpawn(SpawnBase):
else:
self.crlf = self.string_type (os.linesep)
- kwargs = dict(bufsize=0, stdin=subprocess.PIPE,
- stderr=subprocess.STDOUT, stdout=subprocess.PIPE,
+ kwargs = dict(bufsize=0, stdin=subprocess.PIPE,
+ stderr=subprocess.STDOUT, stdout=subprocess.PIPE,
cwd=cwd, preexec_fn=preexec_fn, env=env)
-
- if sys.platform == 'win32':
- startupinfo = subprocess.STARTUPINFO()
- startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
- kwargs['startupinfo'] = startupinfo
- kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP
-
+
+ if sys.platform == 'win32':
+ startupinfo = subprocess.STARTUPINFO()
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
+ kwargs['startupinfo'] = startupinfo
+ kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP
+
if isinstance(cmd, string_types) and sys.platform != 'win32':
cmd = shlex.split(cmd, posix=os.name == 'posix')
-
- self.proc = subprocess.Popen(cmd, **kwargs)
+
+ self.proc = subprocess.Popen(cmd, **kwargs)
self.pid = self.proc.pid
- self.closed = False
- self._buf = self.string_type()
-
- self._read_queue = Queue()
- self._read_thread = threading.Thread(target=self._read_incoming)
- self._read_thread.setDaemon(True)
- self._read_thread.start()
-
- _read_reached_eof = False
-
- def read_nonblocking(self, size, timeout):
- buf = self._buf
- if self._read_reached_eof:
- # We have already finished reading. Use up any buffered data,
- # then raise EOF
- if buf:
- self._buf = buf[size:]
- return buf[:size]
- else:
- self.flag_eof = True
- raise EOF('End Of File (EOF).')
-
- if timeout == -1:
- timeout = self.timeout
- elif timeout is None:
- timeout = 1e6
-
- t0 = time.time()
- while (time.time() - t0) < timeout and size and len(buf) < size:
- try:
- incoming = self._read_queue.get_nowait()
- except Empty:
- break
- else:
- if incoming is None:
- self._read_reached_eof = True
- break
-
- buf += self._decoder.decode(incoming, final=False)
-
- r, self._buf = buf[:size], buf[size:]
-
- self._log(r, 'read')
- return r
-
- def _read_incoming(self):
- """Run in a thread to move output from a pipe to a queue."""
- fileno = self.proc.stdout.fileno()
- while 1:
- buf = b''
- try:
- buf = os.read(fileno, 1024)
- except OSError as e:
- self._log(e, 'read')
-
- if not buf:
- # This indicates we have reached EOF
- self._read_queue.put(None)
- return
-
- self._read_queue.put(buf)
-
- def write(self, s):
- '''This is similar to send() except that there is no return value.
- '''
- self.send(s)
-
- def writelines(self, sequence):
- '''This calls write() for each element in the sequence.
-
- The sequence can be any iterable object producing strings, typically a
- list of strings. This does not add line separators. There is no return
- value.
- '''
- for s in sequence:
- self.send(s)
-
- def send(self, s):
- '''Send data to the subprocess' stdin.
-
- Returns the number of bytes written.
- '''
- s = self._coerce_send_string(s)
- self._log(s, 'send')
-
- b = self._encoder.encode(s, final=False)
- if PY3:
- return self.proc.stdin.write(b)
- else:
- # On Python 2, .write() returns None, so we return the length of
- # bytes written ourselves. This assumes they all got written.
- self.proc.stdin.write(b)
- return len(b)
-
- def sendline(self, s=''):
- '''Wraps send(), sending string ``s`` to child process, with os.linesep
- automatically appended. Returns number of bytes written. '''
-
- n = self.send(s)
- return n + self.send(self.linesep)
-
- def wait(self):
- '''Wait for the subprocess to finish.
-
- Returns the exit code.
- '''
- status = self.proc.wait()
- if status >= 0:
- self.exitstatus = status
- self.signalstatus = None
- else:
- self.exitstatus = None
- self.signalstatus = -status
- self.terminated = True
- return status
-
- def kill(self, sig):
- '''Sends a Unix signal to the subprocess.
-
- Use constants from the :mod:`signal` module to specify which signal.
- '''
- if sys.platform == 'win32':
- if sig in [signal.SIGINT, signal.CTRL_C_EVENT]:
- sig = signal.CTRL_C_EVENT
- elif sig in [signal.SIGBREAK, signal.CTRL_BREAK_EVENT]:
- sig = signal.CTRL_BREAK_EVENT
- else:
- sig = signal.SIGTERM
-
- os.kill(self.proc.pid, sig)
-
- def sendeof(self):
- '''Closes the stdin pipe from the writing end.'''
- self.proc.stdin.close()
+ self.closed = False
+ self._buf = self.string_type()
+
+ self._read_queue = Queue()
+ self._read_thread = threading.Thread(target=self._read_incoming)
+ self._read_thread.setDaemon(True)
+ self._read_thread.start()
+
+ _read_reached_eof = False
+
+ def read_nonblocking(self, size, timeout):
+ buf = self._buf
+ if self._read_reached_eof:
+ # We have already finished reading. Use up any buffered data,
+ # then raise EOF
+ if buf:
+ self._buf = buf[size:]
+ return buf[:size]
+ else:
+ self.flag_eof = True
+ raise EOF('End Of File (EOF).')
+
+ if timeout == -1:
+ timeout = self.timeout
+ elif timeout is None:
+ timeout = 1e6
+
+ t0 = time.time()
+ while (time.time() - t0) < timeout and size and len(buf) < size:
+ try:
+ incoming = self._read_queue.get_nowait()
+ except Empty:
+ break
+ else:
+ if incoming is None:
+ self._read_reached_eof = True
+ break
+
+ buf += self._decoder.decode(incoming, final=False)
+
+ r, self._buf = buf[:size], buf[size:]
+
+ self._log(r, 'read')
+ return r
+
+ def _read_incoming(self):
+ """Run in a thread to move output from a pipe to a queue."""
+ fileno = self.proc.stdout.fileno()
+ while 1:
+ buf = b''
+ try:
+ buf = os.read(fileno, 1024)
+ except OSError as e:
+ self._log(e, 'read')
+
+ if not buf:
+ # This indicates we have reached EOF
+ self._read_queue.put(None)
+ return
+
+ self._read_queue.put(buf)
+
+ def write(self, s):
+ '''This is similar to send() except that there is no return value.
+ '''
+ self.send(s)
+
+ def writelines(self, sequence):
+ '''This calls write() for each element in the sequence.
+
+ The sequence can be any iterable object producing strings, typically a
+ list of strings. This does not add line separators. There is no return
+ value.
+ '''
+ for s in sequence:
+ self.send(s)
+
+ def send(self, s):
+ '''Send data to the subprocess' stdin.
+
+ Returns the number of bytes written.
+ '''
+ s = self._coerce_send_string(s)
+ self._log(s, 'send')
+
+ b = self._encoder.encode(s, final=False)
+ if PY3:
+ return self.proc.stdin.write(b)
+ else:
+ # On Python 2, .write() returns None, so we return the length of
+ # bytes written ourselves. This assumes they all got written.
+ self.proc.stdin.write(b)
+ return len(b)
+
+ def sendline(self, s=''):
+ '''Wraps send(), sending string ``s`` to child process, with os.linesep
+ automatically appended. Returns number of bytes written. '''
+
+ n = self.send(s)
+ return n + self.send(self.linesep)
+
+ def wait(self):
+ '''Wait for the subprocess to finish.
+
+ Returns the exit code.
+ '''
+ status = self.proc.wait()
+ if status >= 0:
+ self.exitstatus = status
+ self.signalstatus = None
+ else:
+ self.exitstatus = None
+ self.signalstatus = -status
+ self.terminated = True
+ return status
+
+ def kill(self, sig):
+ '''Sends a Unix signal to the subprocess.
+
+ Use constants from the :mod:`signal` module to specify which signal.
+ '''
+ if sys.platform == 'win32':
+ if sig in [signal.SIGINT, signal.CTRL_C_EVENT]:
+ sig = signal.CTRL_C_EVENT
+ elif sig in [signal.SIGBREAK, signal.CTRL_BREAK_EVENT]:
+ sig = signal.CTRL_BREAK_EVENT
+ else:
+ sig = signal.SIGTERM
+
+ os.kill(self.proc.pid, sig)
+
+ def sendeof(self):
+ '''Closes the stdin pipe from the writing end.'''
+ self.proc.stdin.close()
diff --git a/contrib/python/pexpect/pexpect/pty_spawn.py b/contrib/python/pexpect/pexpect/pty_spawn.py
index 3c055cdda3..8e28ca7cd7 100644
--- a/contrib/python/pexpect/pexpect/pty_spawn.py
+++ b/contrib/python/pexpect/pexpect/pty_spawn.py
@@ -1,447 +1,447 @@
-import os
-import sys
-import time
-import pty
-import tty
-import errno
-import signal
-from contextlib import contextmanager
-
-import ptyprocess
-from ptyprocess.ptyprocess import use_native_pty_fork
-
-from .exceptions import ExceptionPexpect, EOF, TIMEOUT
-from .spawnbase import SpawnBase
+import os
+import sys
+import time
+import pty
+import tty
+import errno
+import signal
+from contextlib import contextmanager
+
+import ptyprocess
+from ptyprocess.ptyprocess import use_native_pty_fork
+
+from .exceptions import ExceptionPexpect, EOF, TIMEOUT
+from .spawnbase import SpawnBase
from .utils import (
which, split_command_line, select_ignore_interrupts, poll_ignore_interrupts
)
-
-@contextmanager
-def _wrap_ptyprocess_err():
- """Turn ptyprocess errors into our own ExceptionPexpect errors"""
- try:
- yield
- except ptyprocess.PtyProcessError as e:
- raise ExceptionPexpect(*e.args)
-
-PY3 = (sys.version_info[0] >= 3)
-
-class spawn(SpawnBase):
- '''This is the main class interface for Pexpect. Use this class to start
- and control child applications. '''
-
- # This is purely informational now - changing it has no effect
- use_native_pty_fork = use_native_pty_fork
-
- def __init__(self, command, args=[], timeout=30, maxread=2000,
- searchwindowsize=None, logfile=None, cwd=None, env=None,
- ignore_sighup=False, echo=True, preexec_fn=None,
+
+@contextmanager
+def _wrap_ptyprocess_err():
+ """Turn ptyprocess errors into our own ExceptionPexpect errors"""
+ try:
+ yield
+ except ptyprocess.PtyProcessError as e:
+ raise ExceptionPexpect(*e.args)
+
+PY3 = (sys.version_info[0] >= 3)
+
+class spawn(SpawnBase):
+ '''This is the main class interface for Pexpect. Use this class to start
+ and control child applications. '''
+
+ # This is purely informational now - changing it has no effect
+ use_native_pty_fork = use_native_pty_fork
+
+ def __init__(self, command, args=[], timeout=30, maxread=2000,
+ searchwindowsize=None, logfile=None, cwd=None, env=None,
+ ignore_sighup=False, echo=True, preexec_fn=None,
encoding=None, codec_errors='strict', dimensions=None,
use_poll=False):
- '''This is the constructor. The command parameter may be a string that
- includes a command and any arguments to the command. For example::
-
- child = pexpect.spawn('/usr/bin/ftp')
- child = pexpect.spawn('/usr/bin/ssh user@example.com')
- child = pexpect.spawn('ls -latr /tmp')
-
- You may also construct it with a list of arguments like so::
-
- child = pexpect.spawn('/usr/bin/ftp', [])
- child = pexpect.spawn('/usr/bin/ssh', ['user@example.com'])
- child = pexpect.spawn('ls', ['-latr', '/tmp'])
-
- After this the child application will be created and will be ready to
- talk to. For normal use, see expect() and send() and sendline().
-
- Remember that Pexpect does NOT interpret shell meta characters such as
- redirect, pipe, or wild cards (``>``, ``|``, or ``*``). This is a
- common mistake. If you want to run a command and pipe it through
- another command then you must also start a shell. For example::
-
- child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
- child.expect(pexpect.EOF)
-
- The second form of spawn (where you pass a list of arguments) is useful
- in situations where you wish to spawn a command and pass it its own
- argument list. This can make syntax more clear. For example, the
- following is equivalent to the previous example::
-
- shell_cmd = 'ls -l | grep LOG > logs.txt'
- child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
- child.expect(pexpect.EOF)
-
- The maxread attribute sets the read buffer size. This is maximum number
- of bytes that Pexpect will try to read from a TTY at one time. Setting
- the maxread size to 1 will turn off buffering. Setting the maxread
- value higher may help performance in cases where large amounts of
- output are read back from the child. This feature is useful in
- conjunction with searchwindowsize.
-
- When the keyword argument *searchwindowsize* is None (default), the
- full buffer is searched at each iteration of receiving incoming data.
- The default number of bytes scanned at each iteration is very large
- and may be reduced to collaterally reduce search cost. After
- :meth:`~.expect` returns, the full buffer attribute remains up to
- size *maxread* irrespective of *searchwindowsize* value.
-
- When the keyword argument ``timeout`` is specified as a number,
- (default: *30*), then :class:`TIMEOUT` will be raised after the value
- specified has elapsed, in seconds, for any of the :meth:`~.expect`
- family of method calls. When None, TIMEOUT will not be raised, and
- :meth:`~.expect` may block indefinitely until match.
-
-
- The logfile member turns on or off logging. All input and output will
- be copied to the given file object. Set logfile to None to stop
- logging. This is the default. Set logfile to sys.stdout to echo
- everything to standard output. The logfile is flushed after each write.
-
- Example log input and output to a file::
-
- child = pexpect.spawn('some_command')
- fout = open('mylog.txt','wb')
- child.logfile = fout
-
- Example log to stdout::
-
- # In Python 2:
- child = pexpect.spawn('some_command')
- child.logfile = sys.stdout
-
+ '''This is the constructor. The command parameter may be a string that
+ includes a command and any arguments to the command. For example::
+
+ child = pexpect.spawn('/usr/bin/ftp')
+ child = pexpect.spawn('/usr/bin/ssh user@example.com')
+ child = pexpect.spawn('ls -latr /tmp')
+
+ You may also construct it with a list of arguments like so::
+
+ child = pexpect.spawn('/usr/bin/ftp', [])
+ child = pexpect.spawn('/usr/bin/ssh', ['user@example.com'])
+ child = pexpect.spawn('ls', ['-latr', '/tmp'])
+
+ After this the child application will be created and will be ready to
+ talk to. For normal use, see expect() and send() and sendline().
+
+ Remember that Pexpect does NOT interpret shell meta characters such as
+ redirect, pipe, or wild cards (``>``, ``|``, or ``*``). This is a
+ common mistake. If you want to run a command and pipe it through
+ another command then you must also start a shell. For example::
+
+ child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
+ child.expect(pexpect.EOF)
+
+ The second form of spawn (where you pass a list of arguments) is useful
+ in situations where you wish to spawn a command and pass it its own
+ argument list. This can make syntax more clear. For example, the
+ following is equivalent to the previous example::
+
+ shell_cmd = 'ls -l | grep LOG > logs.txt'
+ child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
+ child.expect(pexpect.EOF)
+
+ The maxread attribute sets the read buffer size. This is maximum number
+ of bytes that Pexpect will try to read from a TTY at one time. Setting
+ the maxread size to 1 will turn off buffering. Setting the maxread
+ value higher may help performance in cases where large amounts of
+ output are read back from the child. This feature is useful in
+ conjunction with searchwindowsize.
+
+ When the keyword argument *searchwindowsize* is None (default), the
+ full buffer is searched at each iteration of receiving incoming data.
+ The default number of bytes scanned at each iteration is very large
+ and may be reduced to collaterally reduce search cost. After
+ :meth:`~.expect` returns, the full buffer attribute remains up to
+ size *maxread* irrespective of *searchwindowsize* value.
+
+ When the keyword argument ``timeout`` is specified as a number,
+ (default: *30*), then :class:`TIMEOUT` will be raised after the value
+ specified has elapsed, in seconds, for any of the :meth:`~.expect`
+ family of method calls. When None, TIMEOUT will not be raised, and
+ :meth:`~.expect` may block indefinitely until match.
+
+
+ The logfile member turns on or off logging. All input and output will
+ be copied to the given file object. Set logfile to None to stop
+ logging. This is the default. Set logfile to sys.stdout to echo
+ everything to standard output. The logfile is flushed after each write.
+
+ Example log input and output to a file::
+
+ child = pexpect.spawn('some_command')
+ fout = open('mylog.txt','wb')
+ child.logfile = fout
+
+ Example log to stdout::
+
+ # In Python 2:
+ child = pexpect.spawn('some_command')
+ child.logfile = sys.stdout
+
# In Python 3, we'll use the ``encoding`` argument to decode data
# from the subprocess and handle it as unicode:
child = pexpect.spawn('some_command', encoding='utf-8')
- child.logfile = sys.stdout
-
- The logfile_read and logfile_send members can be used to separately log
- the input from the child and output sent to the child. Sometimes you
- don't want to see everything you write to the child. You only want to
- log what the child sends back. For example::
-
- child = pexpect.spawn('some_command')
- child.logfile_read = sys.stdout
-
- You will need to pass an encoding to spawn in the above code if you are
- using Python 3.
-
- To separately log output sent to the child use logfile_send::
-
- child.logfile_send = fout
-
- If ``ignore_sighup`` is True, the child process will ignore SIGHUP
- signals. The default is False from Pexpect 4.0, meaning that SIGHUP
- will be handled normally by the child.
-
- The delaybeforesend helps overcome a weird behavior that many users
- were experiencing. The typical problem was that a user would expect() a
- "Password:" prompt and then immediately call sendline() to send the
- password. The user would then see that their password was echoed back
- to them. Passwords don't normally echo. The problem is caused by the
- fact that most applications print out the "Password" prompt and then
- turn off stdin echo, but if you send your password before the
- application turned off echo, then you get your password echoed.
- Normally this wouldn't be a problem when interacting with a human at a
- real keyboard. If you introduce a slight delay just before writing then
- this seems to clear up the problem. This was such a common problem for
- many users that I decided that the default pexpect behavior should be
- to sleep just before writing to the child application. 1/20th of a
- second (50 ms) seems to be enough to clear up the problem. You can set
+ child.logfile = sys.stdout
+
+ The logfile_read and logfile_send members can be used to separately log
+ the input from the child and output sent to the child. Sometimes you
+ don't want to see everything you write to the child. You only want to
+ log what the child sends back. For example::
+
+ child = pexpect.spawn('some_command')
+ child.logfile_read = sys.stdout
+
+ You will need to pass an encoding to spawn in the above code if you are
+ using Python 3.
+
+ To separately log output sent to the child use logfile_send::
+
+ child.logfile_send = fout
+
+ If ``ignore_sighup`` is True, the child process will ignore SIGHUP
+ signals. The default is False from Pexpect 4.0, meaning that SIGHUP
+ will be handled normally by the child.
+
+ The delaybeforesend helps overcome a weird behavior that many users
+ were experiencing. The typical problem was that a user would expect() a
+ "Password:" prompt and then immediately call sendline() to send the
+ password. The user would then see that their password was echoed back
+ to them. Passwords don't normally echo. The problem is caused by the
+ fact that most applications print out the "Password" prompt and then
+ turn off stdin echo, but if you send your password before the
+ application turned off echo, then you get your password echoed.
+ Normally this wouldn't be a problem when interacting with a human at a
+ real keyboard. If you introduce a slight delay just before writing then
+ this seems to clear up the problem. This was such a common problem for
+ many users that I decided that the default pexpect behavior should be
+ to sleep just before writing to the child application. 1/20th of a
+ second (50 ms) seems to be enough to clear up the problem. You can set
delaybeforesend to None to return to the old behavior.
-
- Note that spawn is clever about finding commands on your path.
- It uses the same logic that "which" uses to find executables.
-
- If you wish to get the exit status of the child you must call the
- close() method. The exit or signal status of the child will be stored
- in self.exitstatus or self.signalstatus. If the child exited normally
- then exitstatus will store the exit return code and signalstatus will
- be None. If the child was terminated abnormally with a signal then
+
+ Note that spawn is clever about finding commands on your path.
+ It uses the same logic that "which" uses to find executables.
+
+ If you wish to get the exit status of the child you must call the
+ close() method. The exit or signal status of the child will be stored
+ in self.exitstatus or self.signalstatus. If the child exited normally
+ then exitstatus will store the exit return code and signalstatus will
+ be None. If the child was terminated abnormally with a signal then
signalstatus will store the signal value and exitstatus will be None::
child = pexpect.spawn('some_command')
child.close()
print(child.exitstatus, child.signalstatus)
- If you need more detail you can also read the self.status member which
- stores the status returned by os.waitpid. You can interpret this using
- os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.
-
- The echo attribute may be set to False to disable echoing of input.
- As a pseudo-terminal, all input echoed by the "keyboard" (send()
- or sendline()) will be repeated to output. For many cases, it is
- not desirable to have echo enabled, and it may be later disabled
- using setecho(False) followed by waitnoecho(). However, for some
- platforms such as Solaris, this is not possible, and should be
- disabled immediately on spawn.
-
- If preexec_fn is given, it will be called in the child process before
- launching the given command. This is useful to e.g. reset inherited
- signal handlers.
-
- The dimensions attribute specifies the size of the pseudo-terminal as
- seen by the subprocess, and is specified as a two-entry tuple (rows,
- columns). If this is unspecified, the defaults in ptyprocess will apply.
+ If you need more detail you can also read the self.status member which
+ stores the status returned by os.waitpid. You can interpret this using
+ os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.
+
+ The echo attribute may be set to False to disable echoing of input.
+ As a pseudo-terminal, all input echoed by the "keyboard" (send()
+ or sendline()) will be repeated to output. For many cases, it is
+ not desirable to have echo enabled, and it may be later disabled
+ using setecho(False) followed by waitnoecho(). However, for some
+ platforms such as Solaris, this is not possible, and should be
+ disabled immediately on spawn.
+
+ If preexec_fn is given, it will be called in the child process before
+ launching the given command. This is useful to e.g. reset inherited
+ signal handlers.
+
+ The dimensions attribute specifies the size of the pseudo-terminal as
+ seen by the subprocess, and is specified as a two-entry tuple (rows,
+ columns). If this is unspecified, the defaults in ptyprocess will apply.
The use_poll attribute enables using select.poll() over select.select()
for socket handling. This is handy if your system could have > 1024 fds
- '''
- super(spawn, self).__init__(timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize,
- logfile=logfile, encoding=encoding, codec_errors=codec_errors)
- self.STDIN_FILENO = pty.STDIN_FILENO
- self.STDOUT_FILENO = pty.STDOUT_FILENO
- self.STDERR_FILENO = pty.STDERR_FILENO
+ '''
+ super(spawn, self).__init__(timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize,
+ logfile=logfile, encoding=encoding, codec_errors=codec_errors)
+ self.STDIN_FILENO = pty.STDIN_FILENO
+ self.STDOUT_FILENO = pty.STDOUT_FILENO
+ self.STDERR_FILENO = pty.STDERR_FILENO
self.str_last_chars = 100
- self.cwd = cwd
- self.env = env
- self.echo = echo
- self.ignore_sighup = ignore_sighup
- self.__irix_hack = sys.platform.lower().startswith('irix')
- if command is None:
- self.command = None
- self.args = None
- self.name = '<pexpect factory incomplete>'
- else:
- self._spawn(command, args, preexec_fn, dimensions)
+ self.cwd = cwd
+ self.env = env
+ self.echo = echo
+ self.ignore_sighup = ignore_sighup
+ self.__irix_hack = sys.platform.lower().startswith('irix')
+ if command is None:
+ self.command = None
+ self.args = None
+ self.name = '<pexpect factory incomplete>'
+ else:
+ self._spawn(command, args, preexec_fn, dimensions)
self.use_poll = use_poll
-
- def __str__(self):
- '''This returns a human-readable string that represents the state of
- the object. '''
-
- s = []
- s.append(repr(self))
- s.append('command: ' + str(self.command))
- s.append('args: %r' % (self.args,))
+
+ def __str__(self):
+ '''This returns a human-readable string that represents the state of
+ the object. '''
+
+ s = []
+ s.append(repr(self))
+ s.append('command: ' + str(self.command))
+ s.append('args: %r' % (self.args,))
s.append('buffer (last %s chars): %r' % (self.str_last_chars,self.buffer[-self.str_last_chars:]))
s.append('before (last %s chars): %r' % (self.str_last_chars,self.before[-self.str_last_chars:] if self.before else ''))
- s.append('after: %r' % (self.after,))
- s.append('match: %r' % (self.match,))
- s.append('match_index: ' + str(self.match_index))
- s.append('exitstatus: ' + str(self.exitstatus))
+ s.append('after: %r' % (self.after,))
+ s.append('match: %r' % (self.match,))
+ s.append('match_index: ' + str(self.match_index))
+ s.append('exitstatus: ' + str(self.exitstatus))
if hasattr(self, 'ptyproc'):
s.append('flag_eof: ' + str(self.flag_eof))
- s.append('pid: ' + str(self.pid))
- s.append('child_fd: ' + str(self.child_fd))
- s.append('closed: ' + str(self.closed))
- s.append('timeout: ' + str(self.timeout))
- s.append('delimiter: ' + str(self.delimiter))
- s.append('logfile: ' + str(self.logfile))
- s.append('logfile_read: ' + str(self.logfile_read))
- s.append('logfile_send: ' + str(self.logfile_send))
- s.append('maxread: ' + str(self.maxread))
- s.append('ignorecase: ' + str(self.ignorecase))
- s.append('searchwindowsize: ' + str(self.searchwindowsize))
- s.append('delaybeforesend: ' + str(self.delaybeforesend))
- s.append('delayafterclose: ' + str(self.delayafterclose))
- s.append('delayafterterminate: ' + str(self.delayafterterminate))
- return '\n'.join(s)
-
- def _spawn(self, command, args=[], preexec_fn=None, dimensions=None):
- '''This starts the given command in a child process. This does all the
- fork/exec type of stuff for a pty. This is called by __init__. If args
- is empty then command will be parsed (split on spaces) and args will be
- set to parsed arguments. '''
-
- # The pid and child_fd of this object get set by this method.
- # Note that it is difficult for this method to fail.
- # You cannot detect if the child process cannot start.
- # So the only way you can tell if the child process started
- # or not is to try to read from the file descriptor. If you get
- # EOF immediately then it means that the child is already dead.
- # That may not necessarily be bad because you may have spawned a child
- # that performs some task; creates no stdout output; and then dies.
-
- # If command is an int type then it may represent a file descriptor.
- if isinstance(command, type(0)):
- raise ExceptionPexpect('Command is an int type. ' +
- 'If this is a file descriptor then maybe you want to ' +
- 'use fdpexpect.fdspawn which takes an existing ' +
- 'file descriptor instead of a command string.')
-
- if not isinstance(args, type([])):
- raise TypeError('The argument, args, must be a list.')
-
- if args == []:
- self.args = split_command_line(command)
- self.command = self.args[0]
- else:
- # Make a shallow copy of the args list.
- self.args = args[:]
- self.args.insert(0, command)
- self.command = command
-
+ s.append('pid: ' + str(self.pid))
+ s.append('child_fd: ' + str(self.child_fd))
+ s.append('closed: ' + str(self.closed))
+ s.append('timeout: ' + str(self.timeout))
+ s.append('delimiter: ' + str(self.delimiter))
+ s.append('logfile: ' + str(self.logfile))
+ s.append('logfile_read: ' + str(self.logfile_read))
+ s.append('logfile_send: ' + str(self.logfile_send))
+ s.append('maxread: ' + str(self.maxread))
+ s.append('ignorecase: ' + str(self.ignorecase))
+ s.append('searchwindowsize: ' + str(self.searchwindowsize))
+ s.append('delaybeforesend: ' + str(self.delaybeforesend))
+ s.append('delayafterclose: ' + str(self.delayafterclose))
+ s.append('delayafterterminate: ' + str(self.delayafterterminate))
+ return '\n'.join(s)
+
+ def _spawn(self, command, args=[], preexec_fn=None, dimensions=None):
+ '''This starts the given command in a child process. This does all the
+ fork/exec type of stuff for a pty. This is called by __init__. If args
+ is empty then command will be parsed (split on spaces) and args will be
+ set to parsed arguments. '''
+
+ # The pid and child_fd of this object get set by this method.
+ # Note that it is difficult for this method to fail.
+ # You cannot detect if the child process cannot start.
+ # So the only way you can tell if the child process started
+ # or not is to try to read from the file descriptor. If you get
+ # EOF immediately then it means that the child is already dead.
+ # That may not necessarily be bad because you may have spawned a child
+ # that performs some task; creates no stdout output; and then dies.
+
+ # If command is an int type then it may represent a file descriptor.
+ if isinstance(command, type(0)):
+ raise ExceptionPexpect('Command is an int type. ' +
+ 'If this is a file descriptor then maybe you want to ' +
+ 'use fdpexpect.fdspawn which takes an existing ' +
+ 'file descriptor instead of a command string.')
+
+ if not isinstance(args, type([])):
+ raise TypeError('The argument, args, must be a list.')
+
+ if args == []:
+ self.args = split_command_line(command)
+ self.command = self.args[0]
+ else:
+ # Make a shallow copy of the args list.
+ self.args = args[:]
+ self.args.insert(0, command)
+ self.command = command
+
command_with_path = which(self.command, env=self.env)
- if command_with_path is None:
- raise ExceptionPexpect('The command was not found or was not ' +
- 'executable: %s.' % self.command)
- self.command = command_with_path
- self.args[0] = self.command
-
- self.name = '<' + ' '.join(self.args) + '>'
-
- assert self.pid is None, 'The pid member must be None.'
- assert self.command is not None, 'The command member must not be None.'
-
- kwargs = {'echo': self.echo, 'preexec_fn': preexec_fn}
- if self.ignore_sighup:
- def preexec_wrapper():
- "Set SIGHUP to be ignored, then call the real preexec_fn"
- signal.signal(signal.SIGHUP, signal.SIG_IGN)
- if preexec_fn is not None:
- preexec_fn()
- kwargs['preexec_fn'] = preexec_wrapper
-
- if dimensions is not None:
- kwargs['dimensions'] = dimensions
-
+ if command_with_path is None:
+ raise ExceptionPexpect('The command was not found or was not ' +
+ 'executable: %s.' % self.command)
+ self.command = command_with_path
+ self.args[0] = self.command
+
+ self.name = '<' + ' '.join(self.args) + '>'
+
+ assert self.pid is None, 'The pid member must be None.'
+ assert self.command is not None, 'The command member must not be None.'
+
+ kwargs = {'echo': self.echo, 'preexec_fn': preexec_fn}
+ if self.ignore_sighup:
+ def preexec_wrapper():
+ "Set SIGHUP to be ignored, then call the real preexec_fn"
+ signal.signal(signal.SIGHUP, signal.SIG_IGN)
+ if preexec_fn is not None:
+ preexec_fn()
+ kwargs['preexec_fn'] = preexec_wrapper
+
+ if dimensions is not None:
+ kwargs['dimensions'] = dimensions
+
if self.encoding is not None:
# Encode command line using the specified encoding
self.args = [a if isinstance(a, bytes) else a.encode(self.encoding)
for a in self.args]
-
+
self.ptyproc = self._spawnpty(self.args, env=self.env,
cwd=self.cwd, **kwargs)
- self.pid = self.ptyproc.pid
- self.child_fd = self.ptyproc.fd
-
-
- self.terminated = False
- self.closed = False
-
+ self.pid = self.ptyproc.pid
+ self.child_fd = self.ptyproc.fd
+
+
+ self.terminated = False
+ self.closed = False
+
def _spawnpty(self, args, **kwargs):
'''Spawn a pty and return an instance of PtyProcess.'''
return ptyprocess.PtyProcess.spawn(args, **kwargs)
- def close(self, force=True):
- '''This closes the connection with the child application. Note that
- calling close() more than once is valid. This emulates standard Python
- behavior with files. Set force to True if you want to make sure that
- the child is terminated (SIGKILL is sent if the child ignores SIGHUP
- and SIGINT). '''
-
- self.flush()
+ def close(self, force=True):
+ '''This closes the connection with the child application. Note that
+ calling close() more than once is valid. This emulates standard Python
+ behavior with files. Set force to True if you want to make sure that
+ the child is terminated (SIGKILL is sent if the child ignores SIGHUP
+ and SIGINT). '''
+
+ self.flush()
with _wrap_ptyprocess_err():
# PtyProcessError may be raised if it is not possible to terminate
# the child.
self.ptyproc.close(force=force)
- self.isalive() # Update exit status from ptyproc
- self.child_fd = -1
+ self.isalive() # Update exit status from ptyproc
+ self.child_fd = -1
self.closed = True
-
- def isatty(self):
- '''This returns True if the file descriptor is open and connected to a
- tty(-like) device, else False.
-
- On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
- the child pty may not appear as a terminal device. This means
- methods such as setecho(), setwinsize(), getwinsize() may raise an
- IOError. '''
-
- return os.isatty(self.child_fd)
-
- def waitnoecho(self, timeout=-1):
- '''This waits until the terminal ECHO flag is set False. This returns
- True if the echo mode is off. This returns False if the ECHO flag was
- not set False before the timeout. This can be used to detect when the
- child is waiting for a password. Usually a child application will turn
- off echo mode when it is waiting for the user to enter a password. For
- example, instead of expecting the "password:" prompt you can wait for
- the child to set ECHO off::
-
- p = pexpect.spawn('ssh user@example.com')
- p.waitnoecho()
- p.sendline(mypassword)
-
- If timeout==-1 then this method will use the value in self.timeout.
- If timeout==None then this method to block until ECHO flag is False.
- '''
-
- if timeout == -1:
- timeout = self.timeout
- if timeout is not None:
- end_time = time.time() + timeout
- while True:
- if not self.getecho():
- return True
- if timeout < 0 and timeout is not None:
- return False
- if timeout is not None:
- timeout = end_time - time.time()
- time.sleep(0.1)
-
- def getecho(self):
- '''This returns the terminal echo mode. This returns True if echo is
- on or False if echo is off. Child applications that are expecting you
- to enter a password often set ECHO False. See waitnoecho().
-
- Not supported on platforms where ``isatty()`` returns False. '''
- return self.ptyproc.getecho()
-
- def setecho(self, state):
- '''This sets the terminal echo mode on or off. Note that anything the
- child sent before the echo will be lost, so you should be sure that
- your input buffer is empty before you call setecho(). For example, the
- following will work as expected::
-
- p = pexpect.spawn('cat') # Echo is on by default.
- p.sendline('1234') # We expect see this twice from the child...
- p.expect(['1234']) # ... once from the tty echo...
- p.expect(['1234']) # ... and again from cat itself.
- p.setecho(False) # Turn off tty echo
- p.sendline('abcd') # We will set this only once (echoed by cat).
- p.sendline('wxyz') # We will set this only once (echoed by cat)
- p.expect(['abcd'])
- p.expect(['wxyz'])
-
- The following WILL NOT WORK because the lines sent before the setecho
- will be lost::
-
- p = pexpect.spawn('cat')
- p.sendline('1234')
- p.setecho(False) # Turn off tty echo
- p.sendline('abcd') # We will set this only once (echoed by cat).
- p.sendline('wxyz') # We will set this only once (echoed by cat)
- p.expect(['1234'])
- p.expect(['1234'])
- p.expect(['abcd'])
- p.expect(['wxyz'])
-
-
- Not supported on platforms where ``isatty()`` returns False.
- '''
- return self.ptyproc.setecho(state)
-
- def read_nonblocking(self, size=1, timeout=-1):
- '''This reads at most size characters from the child application. It
- includes a timeout. If the read does not complete within the timeout
- period then a TIMEOUT exception is raised. If the end of file is read
- then an EOF exception will be raised. If a logfile is specified, a
- copy is written to that log.
-
- If timeout is None then the read may block indefinitely.
- If timeout is -1 then the self.timeout value is used. If timeout is 0
- then the child is polled and if there is no data immediately ready
- then this will raise a TIMEOUT exception.
-
- The timeout refers only to the amount of time to read at least one
- character. This is not affected by the 'size' parameter, so if you call
- read_nonblocking(size=100, timeout=30) and only one character is
- available right away then one character will be returned immediately.
- It will not wait for 30 seconds for another 99 characters to come in.
-
+
+ def isatty(self):
+ '''This returns True if the file descriptor is open and connected to a
+ tty(-like) device, else False.
+
+ On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
+ the child pty may not appear as a terminal device. This means
+ methods such as setecho(), setwinsize(), getwinsize() may raise an
+ IOError. '''
+
+ return os.isatty(self.child_fd)
+
+ def waitnoecho(self, timeout=-1):
+ '''This waits until the terminal ECHO flag is set False. This returns
+ True if the echo mode is off. This returns False if the ECHO flag was
+ not set False before the timeout. This can be used to detect when the
+ child is waiting for a password. Usually a child application will turn
+ off echo mode when it is waiting for the user to enter a password. For
+ example, instead of expecting the "password:" prompt you can wait for
+ the child to set ECHO off::
+
+ p = pexpect.spawn('ssh user@example.com')
+ p.waitnoecho()
+ p.sendline(mypassword)
+
+ If timeout==-1 then this method will use the value in self.timeout.
+ If timeout==None then this method to block until ECHO flag is False.
+ '''
+
+ if timeout == -1:
+ timeout = self.timeout
+ if timeout is not None:
+ end_time = time.time() + timeout
+ while True:
+ if not self.getecho():
+ return True
+ if timeout < 0 and timeout is not None:
+ return False
+ if timeout is not None:
+ timeout = end_time - time.time()
+ time.sleep(0.1)
+
+ def getecho(self):
+ '''This returns the terminal echo mode. This returns True if echo is
+ on or False if echo is off. Child applications that are expecting you
+ to enter a password often set ECHO False. See waitnoecho().
+
+ Not supported on platforms where ``isatty()`` returns False. '''
+ return self.ptyproc.getecho()
+
+ def setecho(self, state):
+ '''This sets the terminal echo mode on or off. Note that anything the
+ child sent before the echo will be lost, so you should be sure that
+ your input buffer is empty before you call setecho(). For example, the
+ following will work as expected::
+
+ p = pexpect.spawn('cat') # Echo is on by default.
+ p.sendline('1234') # We expect see this twice from the child...
+ p.expect(['1234']) # ... once from the tty echo...
+ p.expect(['1234']) # ... and again from cat itself.
+ p.setecho(False) # Turn off tty echo
+ p.sendline('abcd') # We will set this only once (echoed by cat).
+ p.sendline('wxyz') # We will set this only once (echoed by cat)
+ p.expect(['abcd'])
+ p.expect(['wxyz'])
+
+ The following WILL NOT WORK because the lines sent before the setecho
+ will be lost::
+
+ p = pexpect.spawn('cat')
+ p.sendline('1234')
+ p.setecho(False) # Turn off tty echo
+ p.sendline('abcd') # We will set this only once (echoed by cat).
+ p.sendline('wxyz') # We will set this only once (echoed by cat)
+ p.expect(['1234'])
+ p.expect(['1234'])
+ p.expect(['abcd'])
+ p.expect(['wxyz'])
+
+
+ Not supported on platforms where ``isatty()`` returns False.
+ '''
+ return self.ptyproc.setecho(state)
+
+ def read_nonblocking(self, size=1, timeout=-1):
+ '''This reads at most size characters from the child application. It
+ includes a timeout. If the read does not complete within the timeout
+ period then a TIMEOUT exception is raised. If the end of file is read
+ then an EOF exception will be raised. If a logfile is specified, a
+ copy is written to that log.
+
+ If timeout is None then the read may block indefinitely.
+ If timeout is -1 then the self.timeout value is used. If timeout is 0
+ then the child is polled and if there is no data immediately ready
+ then this will raise a TIMEOUT exception.
+
+ The timeout refers only to the amount of time to read at least one
+ character. This is not affected by the 'size' parameter, so if you call
+ read_nonblocking(size=100, timeout=30) and only one character is
+ available right away then one character will be returned immediately.
+ It will not wait for 30 seconds for another 99 characters to come in.
+
On the other hand, if there are bytes available to read immediately,
all those bytes will be read (up to the buffer size). So, if the
buffer size is 1 megabyte and there is 1 megabyte of data available
to read, the buffer will be filled, regardless of timeout.
-
+
This is a wrapper around os.read(). It uses select.select() or
select.poll() to implement the timeout. '''
- if self.closed:
- raise ValueError('I/O operation on closed file.')
-
+ if self.closed:
+ raise ValueError('I/O operation on closed file.')
+
if self.use_poll:
def select(timeout):
return poll_ignore_interrupts([self.child_fd], timeout)
@@ -472,10 +472,10 @@ class spawn(SpawnBase):
return incoming
return incoming
- if timeout == -1:
- timeout = self.timeout
-
- if not self.isalive():
+ if timeout == -1:
+ timeout = self.timeout
+
+ if not self.isalive():
# The process is dead, but there may or may not be data
# available to read. Note that some systems such as Solaris
# do not give an EOF when the child dies. In fact, you can
@@ -486,20 +486,20 @@ class spawn(SpawnBase):
return super(spawn, self).read_nonblocking(size)
self.flag_eof = True
raise EOF('End Of File (EOF). Braindead platform.')
- elif self.__irix_hack:
- # Irix takes a long time before it realizes a child was terminated.
+ elif self.__irix_hack:
+ # Irix takes a long time before it realizes a child was terminated.
# Make sure that the timeout is at least 2 seconds.
- # FIXME So does this mean Irix systems are forced to always have
- # FIXME a 2 second delay when calling read_nonblocking? That sucks.
+ # FIXME So does this mean Irix systems are forced to always have
+ # FIXME a 2 second delay when calling read_nonblocking? That sucks.
if timeout is not None and timeout < 2:
timeout = 2
-
+
# Because of the select(0) check above, we know that no data
# is available right now. But if a non-zero timeout is given
# (possibly timeout=None), we call select() with a timeout.
if (timeout != 0) and select(timeout):
- return super(spawn, self).read_nonblocking(size)
-
+ return super(spawn, self).read_nonblocking(size)
+
if not self.isalive():
# Some platforms, such as Irix, will claim that their
# processes are alive; timeout on the select; and
@@ -508,353 +508,353 @@ class spawn(SpawnBase):
raise EOF('End of File (EOF). Very slow platform.')
else:
raise TIMEOUT('Timeout exceeded.')
-
- def write(self, s):
- '''This is similar to send() except that there is no return value.
- '''
-
- self.send(s)
-
- def writelines(self, sequence):
- '''This calls write() for each element in the sequence. The sequence
- can be any iterable object producing strings, typically a list of
- strings. This does not add line separators. There is no return value.
- '''
-
- for s in sequence:
- self.write(s)
-
- def send(self, s):
- '''Sends string ``s`` to the child process, returning the number of
- bytes written. If a logfile is specified, a copy is written to that
- log.
-
- The default terminal input mode is canonical processing unless set
- otherwise by the child process. This allows backspace and other line
- processing to be performed prior to transmitting to the receiving
- program. As this is buffered, there is a limited size of such buffer.
-
- On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
- other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
- on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
-
- This value may be discovered using fpathconf(3)::
-
+
+ def write(self, s):
+ '''This is similar to send() except that there is no return value.
+ '''
+
+ self.send(s)
+
+ def writelines(self, sequence):
+ '''This calls write() for each element in the sequence. The sequence
+ can be any iterable object producing strings, typically a list of
+ strings. This does not add line separators. There is no return value.
+ '''
+
+ for s in sequence:
+ self.write(s)
+
+ def send(self, s):
+ '''Sends string ``s`` to the child process, returning the number of
+ bytes written. If a logfile is specified, a copy is written to that
+ log.
+
+ The default terminal input mode is canonical processing unless set
+ otherwise by the child process. This allows backspace and other line
+ processing to be performed prior to transmitting to the receiving
+ program. As this is buffered, there is a limited size of such buffer.
+
+ On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
+ other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
+ on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
+
+ This value may be discovered using fpathconf(3)::
+
>>> from os import fpathconf
>>> print(fpathconf(0, 'PC_MAX_CANON'))
256
-
- On such a system, only 256 bytes may be received per line. Any
- subsequent bytes received will be discarded. BEL (``'\a'``) is then
- sent to output if IMAXBEL (termios.h) is set by the tty driver.
- This is usually enabled by default. Linux does not honor this as
- an option -- it behaves as though it is always set on.
-
- Canonical input processing may be disabled altogether by executing
- a shell, then stty(1), before executing the final program::
-
+
+ On such a system, only 256 bytes may be received per line. Any
+ subsequent bytes received will be discarded. BEL (``'\a'``) is then
+ sent to output if IMAXBEL (termios.h) is set by the tty driver.
+ This is usually enabled by default. Linux does not honor this as
+ an option -- it behaves as though it is always set on.
+
+ Canonical input processing may be disabled altogether by executing
+ a shell, then stty(1), before executing the final program::
+
>>> bash = pexpect.spawn('/bin/bash', echo=False)
>>> bash.sendline('stty -icanon')
>>> bash.sendline('base64')
>>> bash.sendline('x' * 5000)
- '''
-
+ '''
+
if self.delaybeforesend is not None:
time.sleep(self.delaybeforesend)
-
- s = self._coerce_send_string(s)
- self._log(s, 'send')
-
- b = self._encoder.encode(s, final=False)
- return os.write(self.child_fd, b)
-
- def sendline(self, s=''):
- '''Wraps send(), sending string ``s`` to child process, with
- ``os.linesep`` automatically appended. Returns number of bytes
- written. Only a limited number of bytes may be sent for each
- line in the default terminal mode, see docstring of :meth:`send`.
- '''
+
+ s = self._coerce_send_string(s)
+ self._log(s, 'send')
+
+ b = self._encoder.encode(s, final=False)
+ return os.write(self.child_fd, b)
+
+ def sendline(self, s=''):
+ '''Wraps send(), sending string ``s`` to child process, with
+ ``os.linesep`` automatically appended. Returns number of bytes
+ written. Only a limited number of bytes may be sent for each
+ line in the default terminal mode, see docstring of :meth:`send`.
+ '''
s = self._coerce_send_string(s)
return self.send(s + self.linesep)
-
- def _log_control(self, s):
- """Write control characters to the appropriate log files"""
- if self.encoding is not None:
- s = s.decode(self.encoding, 'replace')
- self._log(s, 'send')
-
- def sendcontrol(self, char):
- '''Helper method that wraps send() with mnemonic access for sending control
- character to the child (such as Ctrl-C or Ctrl-D). For example, to send
- Ctrl-G (ASCII 7, bell, '\a')::
-
- child.sendcontrol('g')
-
- See also, sendintr() and sendeof().
- '''
- n, byte = self.ptyproc.sendcontrol(char)
- self._log_control(byte)
- return n
-
- def sendeof(self):
- '''This sends an EOF to the child. This sends a character which causes
- the pending parent output buffer to be sent to the waiting child
- program without waiting for end-of-line. If it is the first character
- of the line, the read() in the user program returns 0, which signifies
- end-of-file. This means to work as expected a sendeof() has to be
- called at the beginning of a line. This method does not send a newline.
- It is the responsibility of the caller to ensure the eof is sent at the
- beginning of a line. '''
-
- n, byte = self.ptyproc.sendeof()
- self._log_control(byte)
-
- def sendintr(self):
- '''This sends a SIGINT to the child. It does not require
- the SIGINT to be the first character on a line. '''
-
- n, byte = self.ptyproc.sendintr()
- self._log_control(byte)
-
- @property
- def flag_eof(self):
- return self.ptyproc.flag_eof
-
- @flag_eof.setter
- def flag_eof(self, value):
- self.ptyproc.flag_eof = value
-
- def eof(self):
- '''This returns True if the EOF exception was ever raised.
- '''
- return self.flag_eof
-
- def terminate(self, force=False):
- '''This forces a child process to terminate. It starts nicely with
- SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
- returns True if the child was terminated. This returns False if the
- child could not be terminated. '''
-
- if not self.isalive():
- return True
- try:
- self.kill(signal.SIGHUP)
- time.sleep(self.delayafterterminate)
- if not self.isalive():
- return True
- self.kill(signal.SIGCONT)
- time.sleep(self.delayafterterminate)
- if not self.isalive():
- return True
- self.kill(signal.SIGINT)
- time.sleep(self.delayafterterminate)
- if not self.isalive():
- return True
- if force:
- self.kill(signal.SIGKILL)
- time.sleep(self.delayafterterminate)
- if not self.isalive():
- return True
- else:
- return False
- return False
- except OSError:
- # I think there are kernel timing issues that sometimes cause
- # this to happen. I think isalive() reports True, but the
- # process is dead to the kernel.
- # Make one last attempt to see if the kernel is up to date.
- time.sleep(self.delayafterterminate)
- if not self.isalive():
- return True
- else:
- return False
-
- def wait(self):
- '''This waits until the child exits. This is a blocking call. This will
- not read any data from the child, so this will block forever if the
- child has unread output and has terminated. In other words, the child
- may have printed output then called exit(), but, the child is
- technically still alive until its output is read by the parent.
-
- This method is non-blocking if :meth:`wait` has already been called
- previously or :meth:`isalive` method returns False. It simply returns
- the previously determined exit status.
- '''
-
- ptyproc = self.ptyproc
- with _wrap_ptyprocess_err():
- # exception may occur if "Is some other process attempting
- # "job control with our child pid?"
- exitstatus = ptyproc.wait()
- self.status = ptyproc.status
- self.exitstatus = ptyproc.exitstatus
- self.signalstatus = ptyproc.signalstatus
- self.terminated = True
-
- return exitstatus
-
- def isalive(self):
- '''This tests if the child process is running or not. This is
- non-blocking. If the child was terminated then this will read the
- exitstatus or signalstatus of the child. This returns True if the child
- process appears to be running or False if not. It can take literally
- SECONDS for Solaris to return the right status. '''
-
- ptyproc = self.ptyproc
- with _wrap_ptyprocess_err():
- alive = ptyproc.isalive()
-
- if not alive:
- self.status = ptyproc.status
- self.exitstatus = ptyproc.exitstatus
- self.signalstatus = ptyproc.signalstatus
- self.terminated = True
-
- return alive
-
- def kill(self, sig):
-
- '''This sends the given signal to the child application. In keeping
- with UNIX tradition it has a misleading name. It does not necessarily
- kill the child unless you send the right signal. '''
-
- # Same as os.kill, but the pid is given for you.
- if self.isalive():
- os.kill(self.pid, sig)
-
- def getwinsize(self):
- '''This returns the terminal window size of the child tty. The return
- value is a tuple of (rows, cols). '''
- return self.ptyproc.getwinsize()
-
- def setwinsize(self, rows, cols):
- '''This sets the terminal window size of the child tty. This will cause
- a SIGWINCH signal to be sent to the child. This does not change the
- physical window size. It changes the size reported to TTY-aware
- applications like vi or curses -- applications that respond to the
- SIGWINCH signal. '''
- return self.ptyproc.setwinsize(rows, cols)
-
-
- def interact(self, escape_character=chr(29),
- input_filter=None, output_filter=None):
-
- '''This gives control of the child process to the interactive user (the
- human at the keyboard). Keystrokes are sent to the child process, and
- the stdout and stderr output of the child process is printed. This
- simply echos the child stdout and child stderr to the real stdout and
- it echos the real stdin to the child stdin. When the user types the
- escape_character this method will return None. The escape_character
- will not be transmitted. The default for escape_character is
- entered as ``Ctrl - ]``, the very same as BSD telnet. To prevent
- escaping, escape_character may be set to None.
-
- If a logfile is specified, then the data sent and received from the
- child process in interact mode is duplicated to the given log.
-
- You may pass in optional input and output filter functions. These
+
+ def _log_control(self, s):
+ """Write control characters to the appropriate log files"""
+ if self.encoding is not None:
+ s = s.decode(self.encoding, 'replace')
+ self._log(s, 'send')
+
+ def sendcontrol(self, char):
+ '''Helper method that wraps send() with mnemonic access for sending control
+ character to the child (such as Ctrl-C or Ctrl-D). For example, to send
+ Ctrl-G (ASCII 7, bell, '\a')::
+
+ child.sendcontrol('g')
+
+ See also, sendintr() and sendeof().
+ '''
+ n, byte = self.ptyproc.sendcontrol(char)
+ self._log_control(byte)
+ return n
+
+ def sendeof(self):
+ '''This sends an EOF to the child. This sends a character which causes
+ the pending parent output buffer to be sent to the waiting child
+ program without waiting for end-of-line. If it is the first character
+ of the line, the read() in the user program returns 0, which signifies
+ end-of-file. This means to work as expected a sendeof() has to be
+ called at the beginning of a line. This method does not send a newline.
+ It is the responsibility of the caller to ensure the eof is sent at the
+ beginning of a line. '''
+
+ n, byte = self.ptyproc.sendeof()
+ self._log_control(byte)
+
+ def sendintr(self):
+ '''This sends a SIGINT to the child. It does not require
+ the SIGINT to be the first character on a line. '''
+
+ n, byte = self.ptyproc.sendintr()
+ self._log_control(byte)
+
+ @property
+ def flag_eof(self):
+ return self.ptyproc.flag_eof
+
+ @flag_eof.setter
+ def flag_eof(self, value):
+ self.ptyproc.flag_eof = value
+
+ def eof(self):
+ '''This returns True if the EOF exception was ever raised.
+ '''
+ return self.flag_eof
+
+ def terminate(self, force=False):
+ '''This forces a child process to terminate. It starts nicely with
+ SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
+ returns True if the child was terminated. This returns False if the
+ child could not be terminated. '''
+
+ if not self.isalive():
+ return True
+ try:
+ self.kill(signal.SIGHUP)
+ time.sleep(self.delayafterterminate)
+ if not self.isalive():
+ return True
+ self.kill(signal.SIGCONT)
+ time.sleep(self.delayafterterminate)
+ if not self.isalive():
+ return True
+ self.kill(signal.SIGINT)
+ time.sleep(self.delayafterterminate)
+ if not self.isalive():
+ return True
+ if force:
+ self.kill(signal.SIGKILL)
+ time.sleep(self.delayafterterminate)
+ if not self.isalive():
+ return True
+ else:
+ return False
+ return False
+ except OSError:
+ # I think there are kernel timing issues that sometimes cause
+ # this to happen. I think isalive() reports True, but the
+ # process is dead to the kernel.
+ # Make one last attempt to see if the kernel is up to date.
+ time.sleep(self.delayafterterminate)
+ if not self.isalive():
+ return True
+ else:
+ return False
+
+ def wait(self):
+ '''This waits until the child exits. This is a blocking call. This will
+ not read any data from the child, so this will block forever if the
+ child has unread output and has terminated. In other words, the child
+ may have printed output then called exit(), but, the child is
+ technically still alive until its output is read by the parent.
+
+ This method is non-blocking if :meth:`wait` has already been called
+ previously or :meth:`isalive` method returns False. It simply returns
+ the previously determined exit status.
+ '''
+
+ ptyproc = self.ptyproc
+ with _wrap_ptyprocess_err():
+ # exception may occur if "Is some other process attempting
+ # "job control with our child pid?"
+ exitstatus = ptyproc.wait()
+ self.status = ptyproc.status
+ self.exitstatus = ptyproc.exitstatus
+ self.signalstatus = ptyproc.signalstatus
+ self.terminated = True
+
+ return exitstatus
+
+ def isalive(self):
+ '''This tests if the child process is running or not. This is
+ non-blocking. If the child was terminated then this will read the
+ exitstatus or signalstatus of the child. This returns True if the child
+ process appears to be running or False if not. It can take literally
+ SECONDS for Solaris to return the right status. '''
+
+ ptyproc = self.ptyproc
+ with _wrap_ptyprocess_err():
+ alive = ptyproc.isalive()
+
+ if not alive:
+ self.status = ptyproc.status
+ self.exitstatus = ptyproc.exitstatus
+ self.signalstatus = ptyproc.signalstatus
+ self.terminated = True
+
+ return alive
+
+ def kill(self, sig):
+
+ '''This sends the given signal to the child application. In keeping
+ with UNIX tradition it has a misleading name. It does not necessarily
+ kill the child unless you send the right signal. '''
+
+ # Same as os.kill, but the pid is given for you.
+ if self.isalive():
+ os.kill(self.pid, sig)
+
+ def getwinsize(self):
+ '''This returns the terminal window size of the child tty. The return
+ value is a tuple of (rows, cols). '''
+ return self.ptyproc.getwinsize()
+
+ def setwinsize(self, rows, cols):
+ '''This sets the terminal window size of the child tty. This will cause
+ a SIGWINCH signal to be sent to the child. This does not change the
+ physical window size. It changes the size reported to TTY-aware
+ applications like vi or curses -- applications that respond to the
+ SIGWINCH signal. '''
+ return self.ptyproc.setwinsize(rows, cols)
+
+
+ def interact(self, escape_character=chr(29),
+ input_filter=None, output_filter=None):
+
+ '''This gives control of the child process to the interactive user (the
+ human at the keyboard). Keystrokes are sent to the child process, and
+ the stdout and stderr output of the child process is printed. This
+ simply echos the child stdout and child stderr to the real stdout and
+ it echos the real stdin to the child stdin. When the user types the
+ escape_character this method will return None. The escape_character
+ will not be transmitted. The default for escape_character is
+ entered as ``Ctrl - ]``, the very same as BSD telnet. To prevent
+ escaping, escape_character may be set to None.
+
+ If a logfile is specified, then the data sent and received from the
+ child process in interact mode is duplicated to the given log.
+
+ You may pass in optional input and output filter functions. These
functions should take bytes array and return bytes array too. Even
with ``encoding='utf-8'`` support, meth:`interact` will always pass
input_filter and output_filter bytes. You may need to wrap your
function to decode and encode back to UTF-8.
-
+
The output_filter will be passed all the output from the child process.
The input_filter will be passed all the keyboard input from the user.
The input_filter is run BEFORE the check for the escape_character.
- Note that if you change the window size of the parent the SIGWINCH
- signal will not be passed through to the child. If you want the child
- window size to change when the parent's window size changes then do
- something like the following example::
-
- import pexpect, struct, fcntl, termios, signal, sys
- def sigwinch_passthrough (sig, data):
- s = struct.pack("HHHH", 0, 0, 0, 0)
- a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
- termios.TIOCGWINSZ , s))
+ Note that if you change the window size of the parent the SIGWINCH
+ signal will not be passed through to the child. If you want the child
+ window size to change when the parent's window size changes then do
+ something like the following example::
+
+ import pexpect, struct, fcntl, termios, signal, sys
+ def sigwinch_passthrough (sig, data):
+ s = struct.pack("HHHH", 0, 0, 0, 0)
+ a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
+ termios.TIOCGWINSZ , s))
if not p.closed:
p.setwinsize(a[0],a[1])
# Note this 'p' is global and used in sigwinch_passthrough.
- p = pexpect.spawn('/bin/bash')
- signal.signal(signal.SIGWINCH, sigwinch_passthrough)
- p.interact()
- '''
-
- # Flush the buffer.
- self.write_to_stdout(self.buffer)
- self.stdout.flush()
+ p = pexpect.spawn('/bin/bash')
+ signal.signal(signal.SIGWINCH, sigwinch_passthrough)
+ p.interact()
+ '''
+
+ # Flush the buffer.
+ self.write_to_stdout(self.buffer)
+ self.stdout.flush()
self._buffer = self.buffer_type()
- mode = tty.tcgetattr(self.STDIN_FILENO)
- tty.setraw(self.STDIN_FILENO)
- if escape_character is not None and PY3:
- escape_character = escape_character.encode('latin-1')
- try:
- self.__interact_copy(escape_character, input_filter, output_filter)
- finally:
- tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
-
- def __interact_writen(self, fd, data):
- '''This is used by the interact() method.
- '''
-
- while data != b'' and self.isalive():
- n = os.write(fd, data)
- data = data[n:]
-
- def __interact_read(self, fd):
- '''This is used by the interact() method.
- '''
-
- return os.read(fd, 1000)
-
+ mode = tty.tcgetattr(self.STDIN_FILENO)
+ tty.setraw(self.STDIN_FILENO)
+ if escape_character is not None and PY3:
+ escape_character = escape_character.encode('latin-1')
+ try:
+ self.__interact_copy(escape_character, input_filter, output_filter)
+ finally:
+ tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
+
+ def __interact_writen(self, fd, data):
+ '''This is used by the interact() method.
+ '''
+
+ while data != b'' and self.isalive():
+ n = os.write(fd, data)
+ data = data[n:]
+
+ def __interact_read(self, fd):
+ '''This is used by the interact() method.
+ '''
+
+ return os.read(fd, 1000)
+
def __interact_copy(
self, escape_character=None, input_filter=None, output_filter=None
):
-
- '''This is used by the interact() method.
- '''
-
- while self.isalive():
+
+ '''This is used by the interact() method.
+ '''
+
+ while self.isalive():
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd, self.STDIN_FILENO])
else:
r, w, e = select_ignore_interrupts(
[self.child_fd, self.STDIN_FILENO], [], []
)
- if self.child_fd in r:
- try:
- data = self.__interact_read(self.child_fd)
- except OSError as err:
- if err.args[0] == errno.EIO:
- # Linux-style EOF
- break
- raise
- if data == b'':
- # BSD-style EOF
- break
- if output_filter:
- data = output_filter(data)
- self._log(data, 'read')
- os.write(self.STDOUT_FILENO, data)
- if self.STDIN_FILENO in r:
- data = self.__interact_read(self.STDIN_FILENO)
- if input_filter:
- data = input_filter(data)
- i = -1
- if escape_character is not None:
- i = data.rfind(escape_character)
- if i != -1:
- data = data[:i]
- if data:
- self._log(data, 'send')
- self.__interact_writen(self.child_fd, data)
- break
- self._log(data, 'send')
- self.__interact_writen(self.child_fd, data)
-
-
-def spawnu(*args, **kwargs):
- """Deprecated: pass encoding to spawn() instead."""
- kwargs.setdefault('encoding', 'utf-8')
- return spawn(*args, **kwargs)
+ if self.child_fd in r:
+ try:
+ data = self.__interact_read(self.child_fd)
+ except OSError as err:
+ if err.args[0] == errno.EIO:
+ # Linux-style EOF
+ break
+ raise
+ if data == b'':
+ # BSD-style EOF
+ break
+ if output_filter:
+ data = output_filter(data)
+ self._log(data, 'read')
+ os.write(self.STDOUT_FILENO, data)
+ if self.STDIN_FILENO in r:
+ data = self.__interact_read(self.STDIN_FILENO)
+ if input_filter:
+ data = input_filter(data)
+ i = -1
+ if escape_character is not None:
+ i = data.rfind(escape_character)
+ if i != -1:
+ data = data[:i]
+ if data:
+ self._log(data, 'send')
+ self.__interact_writen(self.child_fd, data)
+ break
+ self._log(data, 'send')
+ self.__interact_writen(self.child_fd, data)
+
+
+def spawnu(*args, **kwargs):
+ """Deprecated: pass encoding to spawn() instead."""
+ kwargs.setdefault('encoding', 'utf-8')
+ return spawn(*args, **kwargs)
diff --git a/contrib/python/pexpect/pexpect/pxssh.py b/contrib/python/pexpect/pexpect/pxssh.py
index 00e10aad07..3d53bd9746 100644
--- a/contrib/python/pexpect/pexpect/pxssh.py
+++ b/contrib/python/pexpect/pexpect/pxssh.py
@@ -1,38 +1,38 @@
-'''This class extends pexpect.spawn to specialize setting up SSH connections.
-This adds methods for login, logout, and expecting the shell prompt.
-
-PEXPECT LICENSE
-
- This license is approved by the OSI and FSF as GPL-compatible.
- http://opensource.org/licenses/isc-license.txt
-
- Copyright (c) 2012, Noah Spurrier <noah@noah.org>
- PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
- PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
- COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-'''
-
-from pexpect import ExceptionPexpect, TIMEOUT, EOF, spawn
-import time
-import os
+'''This class extends pexpect.spawn to specialize setting up SSH connections.
+This adds methods for login, logout, and expecting the shell prompt.
+
+PEXPECT LICENSE
+
+ This license is approved by the OSI and FSF as GPL-compatible.
+ http://opensource.org/licenses/isc-license.txt
+
+ Copyright (c) 2012, Noah Spurrier <noah@noah.org>
+ PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
+ PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
+ COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+'''
+
+from pexpect import ExceptionPexpect, TIMEOUT, EOF, spawn
+import time
+import os
import sys
import re
-
-__all__ = ['ExceptionPxssh', 'pxssh']
-
-# Exception classes used by this module.
-class ExceptionPxssh(ExceptionPexpect):
- '''Raised for pxssh exceptions.
- '''
-
+
+__all__ = ['ExceptionPxssh', 'pxssh']
+
+# Exception classes used by this module.
+class ExceptionPxssh(ExceptionPexpect):
+ '''Raised for pxssh exceptions.
+ '''
+
if sys.version_info > (3, 0):
from shlex import quote
else:
@@ -49,240 +49,240 @@ else:
# the string $'b is then quoted as '$'"'"'b'
return "'" + s.replace("'", "'\"'\"'") + "'"
-class pxssh (spawn):
- '''This class extends pexpect.spawn to specialize setting up SSH
- connections. This adds methods for login, logout, and expecting the shell
- prompt. It does various tricky things to handle many situations in the SSH
- login process. For example, if the session is your first login, then pxssh
- automatically accepts the remote certificate; or if you have public key
- authentication setup then pxssh won't wait for the password prompt.
-
- pxssh uses the shell prompt to synchronize output from the remote host. In
- order to make this more robust it sets the shell prompt to something more
- unique than just $ or #. This should work on most Borne/Bash or Csh style
- shells.
-
- Example that runs a few commands on a remote server and prints the result::
-
+class pxssh (spawn):
+ '''This class extends pexpect.spawn to specialize setting up SSH
+ connections. This adds methods for login, logout, and expecting the shell
+ prompt. It does various tricky things to handle many situations in the SSH
+ login process. For example, if the session is your first login, then pxssh
+ automatically accepts the remote certificate; or if you have public key
+ authentication setup then pxssh won't wait for the password prompt.
+
+ pxssh uses the shell prompt to synchronize output from the remote host. In
+ order to make this more robust it sets the shell prompt to something more
+ unique than just $ or #. This should work on most Borne/Bash or Csh style
+ shells.
+
+ Example that runs a few commands on a remote server and prints the result::
+
from pexpect import pxssh
- import getpass
- try:
- s = pxssh.pxssh()
- hostname = raw_input('hostname: ')
- username = raw_input('username: ')
- password = getpass.getpass('password: ')
- s.login(hostname, username, password)
- s.sendline('uptime') # run a command
- s.prompt() # match the prompt
- print(s.before) # print everything before the prompt.
- s.sendline('ls -l')
- s.prompt()
- print(s.before)
- s.sendline('df')
- s.prompt()
- print(s.before)
- s.logout()
- except pxssh.ExceptionPxssh as e:
- print("pxssh failed on login.")
- print(e)
-
- Example showing how to specify SSH options::
-
+ import getpass
+ try:
+ s = pxssh.pxssh()
+ hostname = raw_input('hostname: ')
+ username = raw_input('username: ')
+ password = getpass.getpass('password: ')
+ s.login(hostname, username, password)
+ s.sendline('uptime') # run a command
+ s.prompt() # match the prompt
+ print(s.before) # print everything before the prompt.
+ s.sendline('ls -l')
+ s.prompt()
+ print(s.before)
+ s.sendline('df')
+ s.prompt()
+ print(s.before)
+ s.logout()
+ except pxssh.ExceptionPxssh as e:
+ print("pxssh failed on login.")
+ print(e)
+
+ Example showing how to specify SSH options::
+
from pexpect import pxssh
- s = pxssh.pxssh(options={
- "StrictHostKeyChecking": "no",
- "UserKnownHostsFile": "/dev/null"})
- ...
-
- Note that if you have ssh-agent running while doing development with pxssh
- then this can lead to a lot of confusion. Many X display managers (xdm,
- gdm, kdm, etc.) will automatically start a GUI agent. You may see a GUI
- dialog box popup asking for a password during development. You should turn
- off any key agents during testing. The 'force_password' attribute will turn
- off public key authentication. This will only work if the remote SSH server
- is configured to allow password logins. Example of using 'force_password'
- attribute::
-
- s = pxssh.pxssh()
- s.force_password = True
- hostname = raw_input('hostname: ')
- username = raw_input('username: ')
- password = getpass.getpass('password: ')
- s.login (hostname, username, password)
+ s = pxssh.pxssh(options={
+ "StrictHostKeyChecking": "no",
+ "UserKnownHostsFile": "/dev/null"})
+ ...
+
+ Note that if you have ssh-agent running while doing development with pxssh
+ then this can lead to a lot of confusion. Many X display managers (xdm,
+ gdm, kdm, etc.) will automatically start a GUI agent. You may see a GUI
+ dialog box popup asking for a password during development. You should turn
+ off any key agents during testing. The 'force_password' attribute will turn
+ off public key authentication. This will only work if the remote SSH server
+ is configured to allow password logins. Example of using 'force_password'
+ attribute::
+
+ s = pxssh.pxssh()
+ s.force_password = True
+ hostname = raw_input('hostname: ')
+ username = raw_input('username: ')
+ password = getpass.getpass('password: ')
+ s.login (hostname, username, password)
`debug_command_string` is only for the test suite to confirm that the string
generated for SSH is correct, using this will not allow you to do
anything other than get a string back from `pxssh.pxssh.login()`.
- '''
-
- def __init__ (self, timeout=30, maxread=2000, searchwindowsize=None,
- logfile=None, cwd=None, env=None, ignore_sighup=True, echo=True,
+ '''
+
+ def __init__ (self, timeout=30, maxread=2000, searchwindowsize=None,
+ logfile=None, cwd=None, env=None, ignore_sighup=True, echo=True,
options={}, encoding=None, codec_errors='strict',
debug_command_string=False, use_poll=False):
-
- spawn.__init__(self, None, timeout=timeout, maxread=maxread,
- searchwindowsize=searchwindowsize, logfile=logfile,
- cwd=cwd, env=env, ignore_sighup=ignore_sighup, echo=echo,
+
+ spawn.__init__(self, None, timeout=timeout, maxread=maxread,
+ searchwindowsize=searchwindowsize, logfile=logfile,
+ cwd=cwd, env=env, ignore_sighup=ignore_sighup, echo=echo,
encoding=encoding, codec_errors=codec_errors, use_poll=use_poll)
-
- self.name = '<pxssh>'
-
- #SUBTLE HACK ALERT! Note that the command that SETS the prompt uses a
- #slightly different string than the regular expression to match it. This
- #is because when you set the prompt the command will echo back, but we
- #don't want to match the echoed command. So if we make the set command
- #slightly different than the regex we eliminate the problem. To make the
- #set command different we add a backslash in front of $. The $ doesn't
- #need to be escaped, but it doesn't hurt and serves to make the set
- #prompt command different than the regex.
-
- # used to match the command-line prompt
+
+ self.name = '<pxssh>'
+
+ #SUBTLE HACK ALERT! Note that the command that SETS the prompt uses a
+ #slightly different string than the regular expression to match it. This
+ #is because when you set the prompt the command will echo back, but we
+ #don't want to match the echoed command. So if we make the set command
+ #slightly different than the regex we eliminate the problem. To make the
+ #set command different we add a backslash in front of $. The $ doesn't
+ #need to be escaped, but it doesn't hurt and serves to make the set
+ #prompt command different than the regex.
+
+ # used to match the command-line prompt
self.UNIQUE_PROMPT = r"\[PEXPECT\][\$\#] "
- self.PROMPT = self.UNIQUE_PROMPT
-
- # used to set shell command-line prompt to UNIQUE_PROMPT.
+ self.PROMPT = self.UNIQUE_PROMPT
+
+ # used to set shell command-line prompt to UNIQUE_PROMPT.
self.PROMPT_SET_SH = r"PS1='[PEXPECT]\$ '"
self.PROMPT_SET_CSH = r"set prompt='[PEXPECT]\$ '"
- self.SSH_OPTS = ("-o'RSAAuthentication=no'"
- + " -o 'PubkeyAuthentication=no'")
-# Disabling host key checking, makes you vulnerable to MITM attacks.
-# + " -o 'StrictHostKeyChecking=no'"
-# + " -o 'UserKnownHostsFile /dev/null' ")
- # Disabling X11 forwarding gets rid of the annoying SSH_ASKPASS from
- # displaying a GUI password dialog. I have not figured out how to
- # disable only SSH_ASKPASS without also disabling X11 forwarding.
- # Unsetting SSH_ASKPASS on the remote side doesn't disable it! Annoying!
- #self.SSH_OPTS = "-x -o'RSAAuthentication=no' -o 'PubkeyAuthentication=no'"
- self.force_password = False
+ self.SSH_OPTS = ("-o'RSAAuthentication=no'"
+ + " -o 'PubkeyAuthentication=no'")
+# Disabling host key checking, makes you vulnerable to MITM attacks.
+# + " -o 'StrictHostKeyChecking=no'"
+# + " -o 'UserKnownHostsFile /dev/null' ")
+ # Disabling X11 forwarding gets rid of the annoying SSH_ASKPASS from
+ # displaying a GUI password dialog. I have not figured out how to
+ # disable only SSH_ASKPASS without also disabling X11 forwarding.
+ # Unsetting SSH_ASKPASS on the remote side doesn't disable it! Annoying!
+ #self.SSH_OPTS = "-x -o'RSAAuthentication=no' -o 'PubkeyAuthentication=no'"
+ self.force_password = False
self.debug_command_string = debug_command_string
-
- # User defined SSH options, eg,
- # ssh.otions = dict(StrictHostKeyChecking="no",UserKnownHostsFile="/dev/null")
- self.options = options
-
- def levenshtein_distance(self, a, b):
- '''This calculates the Levenshtein distance between a and b.
- '''
-
- n, m = len(a), len(b)
- if n > m:
- a,b = b,a
- n,m = m,n
- current = range(n+1)
- for i in range(1,m+1):
- previous, current = current, [i]+[0]*n
- for j in range(1,n+1):
- add, delete = previous[j]+1, current[j-1]+1
- change = previous[j-1]
- if a[j-1] != b[i-1]:
- change = change + 1
- current[j] = min(add, delete, change)
- return current[n]
-
- def try_read_prompt(self, timeout_multiplier):
- '''This facilitates using communication timeouts to perform
- synchronization as quickly as possible, while supporting high latency
- connections with a tunable worst case performance. Fast connections
- should be read almost immediately. Worst case performance for this
- method is timeout_multiplier * 3 seconds.
- '''
-
- # maximum time allowed to read the first response
- first_char_timeout = timeout_multiplier * 0.5
-
- # maximum time allowed between subsequent characters
- inter_char_timeout = timeout_multiplier * 0.1
-
- # maximum time for reading the entire prompt
- total_timeout = timeout_multiplier * 3.0
-
- prompt = self.string_type()
- begin = time.time()
- expired = 0.0
- timeout = first_char_timeout
-
- while expired < total_timeout:
- try:
- prompt += self.read_nonblocking(size=1, timeout=timeout)
- expired = time.time() - begin # updated total time expired
- timeout = inter_char_timeout
- except TIMEOUT:
- break
-
- return prompt
-
- def sync_original_prompt (self, sync_multiplier=1.0):
- '''This attempts to find the prompt. Basically, press enter and record
- the response; press enter again and record the response; if the two
- responses are similar then assume we are at the original prompt.
- This can be a slow function. Worst case with the default sync_multiplier
- can take 12 seconds. Low latency connections are more likely to fail
- with a low sync_multiplier. Best case sync time gets worse with a
- high sync multiplier (500 ms with default). '''
-
- # All of these timing pace values are magic.
- # I came up with these based on what seemed reliable for
- # connecting to a heavily loaded machine I have.
- self.sendline()
- time.sleep(0.1)
-
- try:
- # Clear the buffer before getting the prompt.
- self.try_read_prompt(sync_multiplier)
- except TIMEOUT:
- pass
-
- self.sendline()
- x = self.try_read_prompt(sync_multiplier)
-
- self.sendline()
- a = self.try_read_prompt(sync_multiplier)
-
- self.sendline()
- b = self.try_read_prompt(sync_multiplier)
-
- ld = self.levenshtein_distance(a,b)
- len_a = len(a)
- if len_a == 0:
- return False
- if float(ld)/len_a < 0.4:
- return True
- return False
-
- ### TODO: This is getting messy and I'm pretty sure this isn't perfect.
- ### TODO: I need to draw a flow chart for this.
+
+ # User defined SSH options, eg,
+ # ssh.otions = dict(StrictHostKeyChecking="no",UserKnownHostsFile="/dev/null")
+ self.options = options
+
+ def levenshtein_distance(self, a, b):
+ '''This calculates the Levenshtein distance between a and b.
+ '''
+
+ n, m = len(a), len(b)
+ if n > m:
+ a,b = b,a
+ n,m = m,n
+ current = range(n+1)
+ for i in range(1,m+1):
+ previous, current = current, [i]+[0]*n
+ for j in range(1,n+1):
+ add, delete = previous[j]+1, current[j-1]+1
+ change = previous[j-1]
+ if a[j-1] != b[i-1]:
+ change = change + 1
+ current[j] = min(add, delete, change)
+ return current[n]
+
+ def try_read_prompt(self, timeout_multiplier):
+ '''This facilitates using communication timeouts to perform
+ synchronization as quickly as possible, while supporting high latency
+ connections with a tunable worst case performance. Fast connections
+ should be read almost immediately. Worst case performance for this
+ method is timeout_multiplier * 3 seconds.
+ '''
+
+ # maximum time allowed to read the first response
+ first_char_timeout = timeout_multiplier * 0.5
+
+ # maximum time allowed between subsequent characters
+ inter_char_timeout = timeout_multiplier * 0.1
+
+ # maximum time for reading the entire prompt
+ total_timeout = timeout_multiplier * 3.0
+
+ prompt = self.string_type()
+ begin = time.time()
+ expired = 0.0
+ timeout = first_char_timeout
+
+ while expired < total_timeout:
+ try:
+ prompt += self.read_nonblocking(size=1, timeout=timeout)
+ expired = time.time() - begin # updated total time expired
+ timeout = inter_char_timeout
+ except TIMEOUT:
+ break
+
+ return prompt
+
+ def sync_original_prompt (self, sync_multiplier=1.0):
+ '''This attempts to find the prompt. Basically, press enter and record
+ the response; press enter again and record the response; if the two
+ responses are similar then assume we are at the original prompt.
+ This can be a slow function. Worst case with the default sync_multiplier
+ can take 12 seconds. Low latency connections are more likely to fail
+ with a low sync_multiplier. Best case sync time gets worse with a
+ high sync multiplier (500 ms with default). '''
+
+ # All of these timing pace values are magic.
+ # I came up with these based on what seemed reliable for
+ # connecting to a heavily loaded machine I have.
+ self.sendline()
+ time.sleep(0.1)
+
+ try:
+ # Clear the buffer before getting the prompt.
+ self.try_read_prompt(sync_multiplier)
+ except TIMEOUT:
+ pass
+
+ self.sendline()
+ x = self.try_read_prompt(sync_multiplier)
+
+ self.sendline()
+ a = self.try_read_prompt(sync_multiplier)
+
+ self.sendline()
+ b = self.try_read_prompt(sync_multiplier)
+
+ ld = self.levenshtein_distance(a,b)
+ len_a = len(a)
+ if len_a == 0:
+ return False
+ if float(ld)/len_a < 0.4:
+ return True
+ return False
+
+ ### TODO: This is getting messy and I'm pretty sure this isn't perfect.
+ ### TODO: I need to draw a flow chart for this.
### TODO: Unit tests for SSH tunnels, remote SSH command exec, disabling original prompt sync
def login (self, server, username=None, password='', terminal_type='ansi',
- original_prompt=r"[#$]", login_timeout=10, port=None,
- auto_prompt_reset=True, ssh_key=None, quiet=True,
+ original_prompt=r"[#$]", login_timeout=10, port=None,
+ auto_prompt_reset=True, ssh_key=None, quiet=True,
sync_multiplier=1, check_local_ip=True,
password_regex=r'(?i)(?:password:)|(?:passphrase for key)',
ssh_tunnels={}, spawn_local_ssh=True,
sync_original_prompt=True, ssh_config=None, cmd='ssh'):
- '''This logs the user into the given server.
-
+ '''This logs the user into the given server.
+
It uses 'original_prompt' to try to find the prompt right after login.
When it finds the prompt it immediately tries to reset the prompt to
something more easily matched. The default 'original_prompt' is very
optimistic and is easily fooled. It's more reliable to try to match the original
- prompt as exactly as possible to prevent false matches by server
- strings such as the "Message Of The Day". On many systems you can
- disable the MOTD on the remote server by creating a zero-length file
- called :file:`~/.hushlogin` on the remote server. If a prompt cannot be found
- then this will not necessarily cause the login to fail. In the case of
- a timeout when looking for the prompt we assume that the original
- prompt was so weird that we could not match it, so we use a few tricks
- to guess when we have reached the prompt. Then we hope for the best and
- blindly try to reset the prompt to something more unique. If that fails
- then login() raises an :class:`ExceptionPxssh` exception.
-
- In some situations it is not possible or desirable to reset the
- original prompt. In this case, pass ``auto_prompt_reset=False`` to
- inhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxssh
- uses a unique prompt in the :meth:`prompt` method. If the original prompt is
- not reset then this will disable the :meth:`prompt` method unless you
- manually set the :attr:`PROMPT` attribute.
+ prompt as exactly as possible to prevent false matches by server
+ strings such as the "Message Of The Day". On many systems you can
+ disable the MOTD on the remote server by creating a zero-length file
+ called :file:`~/.hushlogin` on the remote server. If a prompt cannot be found
+ then this will not necessarily cause the login to fail. In the case of
+ a timeout when looking for the prompt we assume that the original
+ prompt was so weird that we could not match it, so we use a few tricks
+ to guess when we have reached the prompt. Then we hope for the best and
+ blindly try to reset the prompt to something more unique. If that fails
+ then login() raises an :class:`ExceptionPxssh` exception.
+
+ In some situations it is not possible or desirable to reset the
+ original prompt. In this case, pass ``auto_prompt_reset=False`` to
+ inhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxssh
+ uses a unique prompt in the :meth:`prompt` method. If the original prompt is
+ not reset then this will disable the :meth:`prompt` method unless you
+ manually set the :attr:`PROMPT` attribute.
Set ``password_regex`` if there is a MOTD message with `password` in it.
Changing this is like playing in traffic, don't (p)expect it to match straight
@@ -306,27 +306,27 @@ class pxssh (spawn):
Alter the ``cmd`` to change the ssh client used, or to prepend it with network
namespaces. For example ```cmd="ip netns exec vlan2 ssh"``` to execute the ssh in
network namespace named ```vlan```.
- '''
+ '''
session_regex_array = ["(?i)are you sure you want to continue connecting", original_prompt, password_regex, "(?i)permission denied", "(?i)terminal type", TIMEOUT]
session_init_regex_array = []
session_init_regex_array.extend(session_regex_array)
session_init_regex_array.extend(["(?i)connection closed by remote host", EOF])
-
- ssh_options = ''.join([" -o '%s=%s'" % (o, v) for (o, v) in self.options.items()])
- if quiet:
- ssh_options = ssh_options + ' -q'
- if not check_local_ip:
- ssh_options = ssh_options + " -o'NoHostAuthenticationForLocalhost=yes'"
- if self.force_password:
- ssh_options = ssh_options + ' ' + self.SSH_OPTS
+
+ ssh_options = ''.join([" -o '%s=%s'" % (o, v) for (o, v) in self.options.items()])
+ if quiet:
+ ssh_options = ssh_options + ' -q'
+ if not check_local_ip:
+ ssh_options = ssh_options + " -o'NoHostAuthenticationForLocalhost=yes'"
+ if self.force_password:
+ ssh_options = ssh_options + ' ' + self.SSH_OPTS
if ssh_config is not None:
if spawn_local_ssh and not os.path.isfile(ssh_config):
raise ExceptionPxssh('SSH config does not exist or is not a file.')
ssh_options = ssh_options + ' -F ' + ssh_config
- if port is not None:
- ssh_options = ssh_options + ' -p %s'%(str(port))
- if ssh_key is not None:
+ if port is not None:
+ ssh_options = ssh_options + ' -p %s'%(str(port))
+ if ssh_key is not None:
# Allow forwarding our SSH key to the current session
if ssh_key==True:
ssh_options = ssh_options + ' -A'
@@ -395,143 +395,143 @@ class pxssh (spawn):
cmd += " %s %s" % (ssh_options, server)
if self.debug_command_string:
return(cmd)
-
+
# Are we asking for a local ssh command or to spawn one in another session?
if spawn_local_ssh:
spawn._spawn(self, cmd)
else:
self.sendline(cmd)
- # This does not distinguish between a remote server 'password' prompt
- # and a local ssh 'passphrase' prompt (for unlocking a private key).
+ # This does not distinguish between a remote server 'password' prompt
+ # and a local ssh 'passphrase' prompt (for unlocking a private key).
i = self.expect(session_init_regex_array, timeout=login_timeout)
-
- # First phase
- if i==0:
- # New certificate -- always accept it.
- # This is what you get if SSH does not have the remote host's
- # public key stored in the 'known_hosts' cache.
- self.sendline("yes")
+
+ # First phase
+ if i==0:
+ # New certificate -- always accept it.
+ # This is what you get if SSH does not have the remote host's
+ # public key stored in the 'known_hosts' cache.
+ self.sendline("yes")
i = self.expect(session_regex_array)
- if i==2: # password or passphrase
- self.sendline(password)
+ if i==2: # password or passphrase
+ self.sendline(password)
i = self.expect(session_regex_array)
- if i==4:
- self.sendline(terminal_type)
+ if i==4:
+ self.sendline(terminal_type)
i = self.expect(session_regex_array)
if i==7:
self.close()
raise ExceptionPxssh('Could not establish connection to host')
-
- # Second phase
- if i==0:
- # This is weird. This should not happen twice in a row.
- self.close()
- raise ExceptionPxssh('Weird error. Got "are you sure" prompt twice.')
- elif i==1: # can occur if you have a public key pair set to authenticate.
- ### TODO: May NOT be OK if expect() got tricked and matched a false prompt.
- pass
- elif i==2: # password prompt again
- # For incorrect passwords, some ssh servers will
- # ask for the password again, others return 'denied' right away.
- # If we get the password prompt again then this means
- # we didn't get the password right the first time.
- self.close()
- raise ExceptionPxssh('password refused')
- elif i==3: # permission denied -- password was bad.
- self.close()
- raise ExceptionPxssh('permission denied')
- elif i==4: # terminal type again? WTF?
- self.close()
- raise ExceptionPxssh('Weird error. Got "terminal type" prompt twice.')
- elif i==5: # Timeout
- #This is tricky... I presume that we are at the command-line prompt.
- #It may be that the shell prompt was so weird that we couldn't match
- #it. Or it may be that we couldn't log in for some other reason. I
- #can't be sure, but it's safe to guess that we did login because if
- #I presume wrong and we are not logged in then this should be caught
- #later when I try to set the shell prompt.
- pass
- elif i==6: # Connection closed by remote host
- self.close()
- raise ExceptionPxssh('connection closed')
- else: # Unexpected
- self.close()
- raise ExceptionPxssh('unexpected login response')
+
+ # Second phase
+ if i==0:
+ # This is weird. This should not happen twice in a row.
+ self.close()
+ raise ExceptionPxssh('Weird error. Got "are you sure" prompt twice.')
+ elif i==1: # can occur if you have a public key pair set to authenticate.
+ ### TODO: May NOT be OK if expect() got tricked and matched a false prompt.
+ pass
+ elif i==2: # password prompt again
+ # For incorrect passwords, some ssh servers will
+ # ask for the password again, others return 'denied' right away.
+ # If we get the password prompt again then this means
+ # we didn't get the password right the first time.
+ self.close()
+ raise ExceptionPxssh('password refused')
+ elif i==3: # permission denied -- password was bad.
+ self.close()
+ raise ExceptionPxssh('permission denied')
+ elif i==4: # terminal type again? WTF?
+ self.close()
+ raise ExceptionPxssh('Weird error. Got "terminal type" prompt twice.')
+ elif i==5: # Timeout
+ #This is tricky... I presume that we are at the command-line prompt.
+ #It may be that the shell prompt was so weird that we couldn't match
+ #it. Or it may be that we couldn't log in for some other reason. I
+ #can't be sure, but it's safe to guess that we did login because if
+ #I presume wrong and we are not logged in then this should be caught
+ #later when I try to set the shell prompt.
+ pass
+ elif i==6: # Connection closed by remote host
+ self.close()
+ raise ExceptionPxssh('connection closed')
+ else: # Unexpected
+ self.close()
+ raise ExceptionPxssh('unexpected login response')
if sync_original_prompt:
if not self.sync_original_prompt(sync_multiplier):
self.close()
raise ExceptionPxssh('could not synchronize with original prompt')
- # We appear to be in.
- # set shell prompt to something unique.
- if auto_prompt_reset:
- if not self.set_unique_prompt():
- self.close()
- raise ExceptionPxssh('could not set shell prompt '
- '(received: %r, expected: %r).' % (
- self.before, self.PROMPT,))
- return True
-
- def logout (self):
- '''Sends exit to the remote shell.
-
- If there are stopped jobs then this automatically sends exit twice.
- '''
- self.sendline("exit")
- index = self.expect([EOF, "(?i)there are stopped jobs"])
- if index==1:
- self.sendline("exit")
- self.expect(EOF)
- self.close()
-
- def prompt(self, timeout=-1):
- '''Match the next shell prompt.
-
- This is little more than a short-cut to the :meth:`~pexpect.spawn.expect`
- method. Note that if you called :meth:`login` with
- ``auto_prompt_reset=False``, then before calling :meth:`prompt` you must
- set the :attr:`PROMPT` attribute to a regex that it will use for
- matching the prompt.
-
- Calling :meth:`prompt` will erase the contents of the :attr:`before`
- attribute even if no prompt is ever matched. If timeout is not given or
- it is set to -1 then self.timeout is used.
-
- :return: True if the shell prompt was matched, False if the timeout was
- reached.
- '''
-
- if timeout == -1:
- timeout = self.timeout
- i = self.expect([self.PROMPT, TIMEOUT], timeout=timeout)
- if i==1:
- return False
- return True
-
- def set_unique_prompt(self):
- '''This sets the remote prompt to something more unique than ``#`` or ``$``.
- This makes it easier for the :meth:`prompt` method to match the shell prompt
- unambiguously. This method is called automatically by the :meth:`login`
- method, but you may want to call it manually if you somehow reset the
- shell prompt. For example, if you 'su' to a different user then you
- will need to manually reset the prompt. This sends shell commands to
- the remote host to set the prompt, so this assumes the remote host is
- ready to receive commands.
-
- Alternatively, you may use your own prompt pattern. In this case you
- should call :meth:`login` with ``auto_prompt_reset=False``; then set the
- :attr:`PROMPT` attribute to a regular expression. After that, the
- :meth:`prompt` method will try to match your prompt pattern.
- '''
-
- self.sendline("unset PROMPT_COMMAND")
- self.sendline(self.PROMPT_SET_SH) # sh-style
- i = self.expect ([TIMEOUT, self.PROMPT], timeout=10)
- if i == 0: # csh-style
- self.sendline(self.PROMPT_SET_CSH)
- i = self.expect([TIMEOUT, self.PROMPT], timeout=10)
- if i == 0:
- return False
- return True
-
-# vi:ts=4:sw=4:expandtab:ft=python:
+ # We appear to be in.
+ # set shell prompt to something unique.
+ if auto_prompt_reset:
+ if not self.set_unique_prompt():
+ self.close()
+ raise ExceptionPxssh('could not set shell prompt '
+ '(received: %r, expected: %r).' % (
+ self.before, self.PROMPT,))
+ return True
+
+ def logout (self):
+ '''Sends exit to the remote shell.
+
+ If there are stopped jobs then this automatically sends exit twice.
+ '''
+ self.sendline("exit")
+ index = self.expect([EOF, "(?i)there are stopped jobs"])
+ if index==1:
+ self.sendline("exit")
+ self.expect(EOF)
+ self.close()
+
+ def prompt(self, timeout=-1):
+ '''Match the next shell prompt.
+
+ This is little more than a short-cut to the :meth:`~pexpect.spawn.expect`
+ method. Note that if you called :meth:`login` with
+ ``auto_prompt_reset=False``, then before calling :meth:`prompt` you must
+ set the :attr:`PROMPT` attribute to a regex that it will use for
+ matching the prompt.
+
+ Calling :meth:`prompt` will erase the contents of the :attr:`before`
+ attribute even if no prompt is ever matched. If timeout is not given or
+ it is set to -1 then self.timeout is used.
+
+ :return: True if the shell prompt was matched, False if the timeout was
+ reached.
+ '''
+
+ if timeout == -1:
+ timeout = self.timeout
+ i = self.expect([self.PROMPT, TIMEOUT], timeout=timeout)
+ if i==1:
+ return False
+ return True
+
+ def set_unique_prompt(self):
+ '''This sets the remote prompt to something more unique than ``#`` or ``$``.
+ This makes it easier for the :meth:`prompt` method to match the shell prompt
+ unambiguously. This method is called automatically by the :meth:`login`
+ method, but you may want to call it manually if you somehow reset the
+ shell prompt. For example, if you 'su' to a different user then you
+ will need to manually reset the prompt. This sends shell commands to
+ the remote host to set the prompt, so this assumes the remote host is
+ ready to receive commands.
+
+ Alternatively, you may use your own prompt pattern. In this case you
+ should call :meth:`login` with ``auto_prompt_reset=False``; then set the
+ :attr:`PROMPT` attribute to a regular expression. After that, the
+ :meth:`prompt` method will try to match your prompt pattern.
+ '''
+
+ self.sendline("unset PROMPT_COMMAND")
+ self.sendline(self.PROMPT_SET_SH) # sh-style
+ i = self.expect ([TIMEOUT, self.PROMPT], timeout=10)
+ if i == 0: # csh-style
+ self.sendline(self.PROMPT_SET_CSH)
+ i = self.expect([TIMEOUT, self.PROMPT], timeout=10)
+ if i == 0:
+ return False
+ return True
+
+# vi:ts=4:sw=4:expandtab:ft=python:
diff --git a/contrib/python/pexpect/pexpect/replwrap.py b/contrib/python/pexpect/pexpect/replwrap.py
index 79562de4c1..c930f1e4fe 100644
--- a/contrib/python/pexpect/pexpect/replwrap.py
+++ b/contrib/python/pexpect/pexpect/replwrap.py
@@ -1,122 +1,122 @@
-"""Generic wrapper for read-eval-print-loops, a.k.a. interactive shells
-"""
-import os.path
-import signal
-import sys
-
-import pexpect
-
-PY3 = (sys.version_info[0] >= 3)
-
-if PY3:
- basestring = str
-
-PEXPECT_PROMPT = u'[PEXPECT_PROMPT>'
-PEXPECT_CONTINUATION_PROMPT = u'[PEXPECT_PROMPT+'
-
-class REPLWrapper(object):
- """Wrapper for a REPL.
-
- :param cmd_or_spawn: This can either be an instance of :class:`pexpect.spawn`
- in which a REPL has already been started, or a str command to start a new
- REPL process.
- :param str orig_prompt: The prompt to expect at first.
- :param str prompt_change: A command to change the prompt to something more
- unique. If this is ``None``, the prompt will not be changed. This will
- be formatted with the new and continuation prompts as positional
- parameters, so you can use ``{}`` style formatting to insert them into
- the command.
- :param str new_prompt: The more unique prompt to expect after the change.
- :param str extra_init_cmd: Commands to do extra initialisation, such as
- disabling pagers.
- """
- def __init__(self, cmd_or_spawn, orig_prompt, prompt_change,
- new_prompt=PEXPECT_PROMPT,
- continuation_prompt=PEXPECT_CONTINUATION_PROMPT,
- extra_init_cmd=None):
- if isinstance(cmd_or_spawn, basestring):
- self.child = pexpect.spawn(cmd_or_spawn, echo=False, encoding='utf-8')
- else:
- self.child = cmd_or_spawn
- if self.child.echo:
- # Existing spawn instance has echo enabled, disable it
- # to prevent our input from being repeated to output.
- self.child.setecho(False)
- self.child.waitnoecho()
-
- if prompt_change is None:
- self.prompt = orig_prompt
- else:
- self.set_prompt(orig_prompt,
- prompt_change.format(new_prompt, continuation_prompt))
- self.prompt = new_prompt
- self.continuation_prompt = continuation_prompt
-
- self._expect_prompt()
-
- if extra_init_cmd is not None:
- self.run_command(extra_init_cmd)
-
- def set_prompt(self, orig_prompt, prompt_change):
- self.child.expect(orig_prompt)
- self.child.sendline(prompt_change)
-
+"""Generic wrapper for read-eval-print-loops, a.k.a. interactive shells
+"""
+import os.path
+import signal
+import sys
+
+import pexpect
+
+PY3 = (sys.version_info[0] >= 3)
+
+if PY3:
+ basestring = str
+
+PEXPECT_PROMPT = u'[PEXPECT_PROMPT>'
+PEXPECT_CONTINUATION_PROMPT = u'[PEXPECT_PROMPT+'
+
+class REPLWrapper(object):
+ """Wrapper for a REPL.
+
+ :param cmd_or_spawn: This can either be an instance of :class:`pexpect.spawn`
+ in which a REPL has already been started, or a str command to start a new
+ REPL process.
+ :param str orig_prompt: The prompt to expect at first.
+ :param str prompt_change: A command to change the prompt to something more
+ unique. If this is ``None``, the prompt will not be changed. This will
+ be formatted with the new and continuation prompts as positional
+ parameters, so you can use ``{}`` style formatting to insert them into
+ the command.
+ :param str new_prompt: The more unique prompt to expect after the change.
+ :param str extra_init_cmd: Commands to do extra initialisation, such as
+ disabling pagers.
+ """
+ def __init__(self, cmd_or_spawn, orig_prompt, prompt_change,
+ new_prompt=PEXPECT_PROMPT,
+ continuation_prompt=PEXPECT_CONTINUATION_PROMPT,
+ extra_init_cmd=None):
+ if isinstance(cmd_or_spawn, basestring):
+ self.child = pexpect.spawn(cmd_or_spawn, echo=False, encoding='utf-8')
+ else:
+ self.child = cmd_or_spawn
+ if self.child.echo:
+ # Existing spawn instance has echo enabled, disable it
+ # to prevent our input from being repeated to output.
+ self.child.setecho(False)
+ self.child.waitnoecho()
+
+ if prompt_change is None:
+ self.prompt = orig_prompt
+ else:
+ self.set_prompt(orig_prompt,
+ prompt_change.format(new_prompt, continuation_prompt))
+ self.prompt = new_prompt
+ self.continuation_prompt = continuation_prompt
+
+ self._expect_prompt()
+
+ if extra_init_cmd is not None:
+ self.run_command(extra_init_cmd)
+
+ def set_prompt(self, orig_prompt, prompt_change):
+ self.child.expect(orig_prompt)
+ self.child.sendline(prompt_change)
+
def _expect_prompt(self, timeout=-1, async_=False):
- return self.child.expect_exact([self.prompt, self.continuation_prompt],
+ return self.child.expect_exact([self.prompt, self.continuation_prompt],
timeout=timeout, async_=async_)
-
+
def run_command(self, command, timeout=-1, async_=False):
- """Send a command to the REPL, wait for and return output.
-
- :param str command: The command to send. Trailing newlines are not needed.
- This should be a complete block of input that will trigger execution;
- if a continuation prompt is found after sending input, :exc:`ValueError`
- will be raised.
- :param int timeout: How long to wait for the next prompt. -1 means the
- default from the :class:`pexpect.spawn` object (default 30 seconds).
- None means to wait indefinitely.
+ """Send a command to the REPL, wait for and return output.
+
+ :param str command: The command to send. Trailing newlines are not needed.
+ This should be a complete block of input that will trigger execution;
+ if a continuation prompt is found after sending input, :exc:`ValueError`
+ will be raised.
+ :param int timeout: How long to wait for the next prompt. -1 means the
+ default from the :class:`pexpect.spawn` object (default 30 seconds).
+ None means to wait indefinitely.
:param bool async_: On Python 3.4, or Python 3.3 with asyncio
installed, passing ``async_=True`` will make this return an
:mod:`asyncio` Future, which you can yield from to get the same
result that this method would normally give directly.
- """
- # Split up multiline commands and feed them in bit-by-bit
- cmdlines = command.splitlines()
- # splitlines ignores trailing newlines - add it back in manually
- if command.endswith('\n'):
- cmdlines.append('')
- if not cmdlines:
- raise ValueError("No command was given")
-
+ """
+ # Split up multiline commands and feed them in bit-by-bit
+ cmdlines = command.splitlines()
+ # splitlines ignores trailing newlines - add it back in manually
+ if command.endswith('\n'):
+ cmdlines.append('')
+ if not cmdlines:
+ raise ValueError("No command was given")
+
if async_:
from ._async import repl_run_command_async
return repl_run_command_async(self, cmdlines, timeout)
- res = []
- self.child.sendline(cmdlines[0])
- for line in cmdlines[1:]:
- self._expect_prompt(timeout=timeout)
- res.append(self.child.before)
- self.child.sendline(line)
-
- # Command was fully submitted, now wait for the next prompt
- if self._expect_prompt(timeout=timeout) == 1:
- # We got the continuation prompt - command was incomplete
- self.child.kill(signal.SIGINT)
- self._expect_prompt(timeout=1)
- raise ValueError("Continuation prompt found - input was incomplete:\n"
- + command)
- return u''.join(res + [self.child.before])
-
-def python(command="python"):
- """Start a Python shell and return a :class:`REPLWrapper` object."""
- return REPLWrapper(command, u">>> ", u"import sys; sys.ps1={0!r}; sys.ps2={1!r}")
-
-def bash(command="bash"):
- """Start a bash shell and return a :class:`REPLWrapper` object."""
- bashrc = os.path.join(os.path.dirname(__file__), 'bashrc.sh')
- child = pexpect.spawn(command, ['--rcfile', bashrc], echo=False,
- encoding='utf-8')
+ res = []
+ self.child.sendline(cmdlines[0])
+ for line in cmdlines[1:]:
+ self._expect_prompt(timeout=timeout)
+ res.append(self.child.before)
+ self.child.sendline(line)
+
+ # Command was fully submitted, now wait for the next prompt
+ if self._expect_prompt(timeout=timeout) == 1:
+ # We got the continuation prompt - command was incomplete
+ self.child.kill(signal.SIGINT)
+ self._expect_prompt(timeout=1)
+ raise ValueError("Continuation prompt found - input was incomplete:\n"
+ + command)
+ return u''.join(res + [self.child.before])
+
+def python(command="python"):
+ """Start a Python shell and return a :class:`REPLWrapper` object."""
+ return REPLWrapper(command, u">>> ", u"import sys; sys.ps1={0!r}; sys.ps2={1!r}")
+
+def bash(command="bash"):
+ """Start a bash shell and return a :class:`REPLWrapper` object."""
+ bashrc = os.path.join(os.path.dirname(__file__), 'bashrc.sh')
+ child = pexpect.spawn(command, ['--rcfile', bashrc], echo=False,
+ encoding='utf-8')
# If the user runs 'env', the value of PS1 will be in the output. To avoid
# replwrap seeing that as the next prompt, we'll embed the marker characters
@@ -127,4 +127,4 @@ def bash(command="bash"):
prompt_change = u"PS1='{0}' PS2='{1}' PROMPT_COMMAND=''".format(ps1, ps2)
return REPLWrapper(child, u'\\$', prompt_change,
- extra_init_cmd="export PAGER=cat")
+ extra_init_cmd="export PAGER=cat")
diff --git a/contrib/python/pexpect/pexpect/run.py b/contrib/python/pexpect/pexpect/run.py
index ccfd6050d6..ff288a1246 100644
--- a/contrib/python/pexpect/pexpect/run.py
+++ b/contrib/python/pexpect/pexpect/run.py
@@ -1,157 +1,157 @@
-import sys
-import types
-
-from .exceptions import EOF, TIMEOUT
-from .pty_spawn import spawn
-
-def run(command, timeout=30, withexitstatus=False, events=None,
- extra_args=None, logfile=None, cwd=None, env=None, **kwargs):
-
- '''
- This function runs the given command; waits for it to finish; then
- returns all output as a string. STDERR is included in output. If the full
- path to the command is not given then the path is searched.
-
- Note that lines are terminated by CR/LF (\\r\\n) combination even on
- UNIX-like systems because this is the standard for pseudottys. If you set
- 'withexitstatus' to true, then run will return a tuple of (command_output,
- exitstatus). If 'withexitstatus' is false then this returns just
- command_output.
-
- The run() function can often be used instead of creating a spawn instance.
- For example, the following code uses spawn::
-
- from pexpect import *
- child = spawn('scp foo user@example.com:.')
- child.expect('(?i)password')
- child.sendline(mypassword)
-
- The previous code can be replace with the following::
-
- from pexpect import *
- run('scp foo user@example.com:.', events={'(?i)password': mypassword})
-
- **Examples**
-
- Start the apache daemon on the local machine::
-
- from pexpect import *
- run("/usr/local/apache/bin/apachectl start")
-
- Check in a file using SVN::
-
- from pexpect import *
- run("svn ci -m 'automatic commit' my_file.py")
-
- Run a command and capture exit status::
-
- from pexpect import *
- (command_output, exitstatus) = run('ls -l /bin', withexitstatus=1)
-
- The following will run SSH and execute 'ls -l' on the remote machine. The
- password 'secret' will be sent if the '(?i)password' pattern is ever seen::
-
- run("ssh username@machine.example.com 'ls -l'",
- events={'(?i)password':'secret\\n'})
-
- This will start mencoder to rip a video from DVD. This will also display
- progress ticks every 5 seconds as it runs. For example::
-
- from pexpect import *
- def print_ticks(d):
- print d['event_count'],
- run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
- events={TIMEOUT:print_ticks}, timeout=5)
-
- The 'events' argument should be either a dictionary or a tuple list that
- contains patterns and responses. Whenever one of the patterns is seen
- in the command output, run() will send the associated response string.
- So, run() in the above example can be also written as:
-
- run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
- events=[(TIMEOUT,print_ticks)], timeout=5)
-
- Use a tuple list for events if the command output requires a delicate
- control over what pattern should be matched, since the tuple list is passed
- to pexpect() as its pattern list, with the order of patterns preserved.
-
- Note that you should put newlines in your string if Enter is necessary.
-
- Like the example above, the responses may also contain a callback, either
- a function or method. It should accept a dictionary value as an argument.
- The dictionary contains all the locals from the run() function, so you can
- access the child spawn object or any other variable defined in run()
- (event_count, child, and extra_args are the most useful). A callback may
- return True to stop the current run process. Otherwise run() continues
- until the next event. A callback may also return a string which will be
- sent to the child. 'extra_args' is not used by directly run(). It provides
- a way to pass data to a callback function through run() through the locals
- dictionary passed to a callback.
-
- Like :class:`spawn`, passing *encoding* will make it work with unicode
- instead of bytes. You can pass *codec_errors* to control how errors in
- encoding and decoding are handled.
- '''
- if timeout == -1:
- child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env,
- **kwargs)
- else:
- child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile,
- cwd=cwd, env=env, **kwargs)
- if isinstance(events, list):
- patterns= [x for x,y in events]
- responses = [y for x,y in events]
- elif isinstance(events, dict):
- patterns = list(events.keys())
- responses = list(events.values())
- else:
- # This assumes EOF or TIMEOUT will eventually cause run to terminate.
- patterns = None
- responses = None
- child_result_list = []
- event_count = 0
- while True:
- try:
- index = child.expect(patterns)
- if isinstance(child.after, child.allowed_string_types):
- child_result_list.append(child.before + child.after)
- else:
- # child.after may have been a TIMEOUT or EOF,
- # which we don't want appended to the list.
- child_result_list.append(child.before)
- if isinstance(responses[index], child.allowed_string_types):
- child.send(responses[index])
- elif (isinstance(responses[index], types.FunctionType) or
- isinstance(responses[index], types.MethodType)):
- callback_result = responses[index](locals())
- sys.stdout.flush()
- if isinstance(callback_result, child.allowed_string_types):
- child.send(callback_result)
- elif callback_result:
- break
- else:
- raise TypeError("parameter `event' at index {index} must be "
- "a string, method, or function: {value!r}"
- .format(index=index, value=responses[index]))
- event_count = event_count + 1
- except TIMEOUT:
- child_result_list.append(child.before)
- break
- except EOF:
- child_result_list.append(child.before)
- break
- child_result = child.string_type().join(child_result_list)
- if withexitstatus:
- child.close()
- return (child_result, child.exitstatus)
- else:
- return child_result
-
-def runu(command, timeout=30, withexitstatus=False, events=None,
- extra_args=None, logfile=None, cwd=None, env=None, **kwargs):
- """Deprecated: pass encoding to run() instead.
- """
- kwargs.setdefault('encoding', 'utf-8')
- return run(command, timeout=timeout, withexitstatus=withexitstatus,
- events=events, extra_args=extra_args, logfile=logfile, cwd=cwd,
- env=env, **kwargs)
+import sys
+import types
+
+from .exceptions import EOF, TIMEOUT
+from .pty_spawn import spawn
+
+def run(command, timeout=30, withexitstatus=False, events=None,
+ extra_args=None, logfile=None, cwd=None, env=None, **kwargs):
+
+ '''
+ This function runs the given command; waits for it to finish; then
+ returns all output as a string. STDERR is included in output. If the full
+ path to the command is not given then the path is searched.
+
+ Note that lines are terminated by CR/LF (\\r\\n) combination even on
+ UNIX-like systems because this is the standard for pseudottys. If you set
+ 'withexitstatus' to true, then run will return a tuple of (command_output,
+ exitstatus). If 'withexitstatus' is false then this returns just
+ command_output.
+
+ The run() function can often be used instead of creating a spawn instance.
+ For example, the following code uses spawn::
+
+ from pexpect import *
+ child = spawn('scp foo user@example.com:.')
+ child.expect('(?i)password')
+ child.sendline(mypassword)
+
+ The previous code can be replace with the following::
+
+ from pexpect import *
+ run('scp foo user@example.com:.', events={'(?i)password': mypassword})
+
+ **Examples**
+
+ Start the apache daemon on the local machine::
+
+ from pexpect import *
+ run("/usr/local/apache/bin/apachectl start")
+
+ Check in a file using SVN::
+
+ from pexpect import *
+ run("svn ci -m 'automatic commit' my_file.py")
+
+ Run a command and capture exit status::
+
+ from pexpect import *
+ (command_output, exitstatus) = run('ls -l /bin', withexitstatus=1)
+
+ The following will run SSH and execute 'ls -l' on the remote machine. The
+ password 'secret' will be sent if the '(?i)password' pattern is ever seen::
+
+ run("ssh username@machine.example.com 'ls -l'",
+ events={'(?i)password':'secret\\n'})
+
+ This will start mencoder to rip a video from DVD. This will also display
+ progress ticks every 5 seconds as it runs. For example::
+
+ from pexpect import *
+ def print_ticks(d):
+ print d['event_count'],
+ run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
+ events={TIMEOUT:print_ticks}, timeout=5)
+
+ The 'events' argument should be either a dictionary or a tuple list that
+ contains patterns and responses. Whenever one of the patterns is seen
+ in the command output, run() will send the associated response string.
+ So, run() in the above example can be also written as:
+
+ run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
+ events=[(TIMEOUT,print_ticks)], timeout=5)
+
+ Use a tuple list for events if the command output requires a delicate
+ control over what pattern should be matched, since the tuple list is passed
+ to pexpect() as its pattern list, with the order of patterns preserved.
+
+ Note that you should put newlines in your string if Enter is necessary.
+
+ Like the example above, the responses may also contain a callback, either
+ a function or method. It should accept a dictionary value as an argument.
+ The dictionary contains all the locals from the run() function, so you can
+ access the child spawn object or any other variable defined in run()
+ (event_count, child, and extra_args are the most useful). A callback may
+ return True to stop the current run process. Otherwise run() continues
+ until the next event. A callback may also return a string which will be
+ sent to the child. 'extra_args' is not used by directly run(). It provides
+ a way to pass data to a callback function through run() through the locals
+ dictionary passed to a callback.
+
+ Like :class:`spawn`, passing *encoding* will make it work with unicode
+ instead of bytes. You can pass *codec_errors* to control how errors in
+ encoding and decoding are handled.
+ '''
+ if timeout == -1:
+ child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env,
+ **kwargs)
+ else:
+ child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile,
+ cwd=cwd, env=env, **kwargs)
+ if isinstance(events, list):
+ patterns= [x for x,y in events]
+ responses = [y for x,y in events]
+ elif isinstance(events, dict):
+ patterns = list(events.keys())
+ responses = list(events.values())
+ else:
+ # This assumes EOF or TIMEOUT will eventually cause run to terminate.
+ patterns = None
+ responses = None
+ child_result_list = []
+ event_count = 0
+ while True:
+ try:
+ index = child.expect(patterns)
+ if isinstance(child.after, child.allowed_string_types):
+ child_result_list.append(child.before + child.after)
+ else:
+ # child.after may have been a TIMEOUT or EOF,
+ # which we don't want appended to the list.
+ child_result_list.append(child.before)
+ if isinstance(responses[index], child.allowed_string_types):
+ child.send(responses[index])
+ elif (isinstance(responses[index], types.FunctionType) or
+ isinstance(responses[index], types.MethodType)):
+ callback_result = responses[index](locals())
+ sys.stdout.flush()
+ if isinstance(callback_result, child.allowed_string_types):
+ child.send(callback_result)
+ elif callback_result:
+ break
+ else:
+ raise TypeError("parameter `event' at index {index} must be "
+ "a string, method, or function: {value!r}"
+ .format(index=index, value=responses[index]))
+ event_count = event_count + 1
+ except TIMEOUT:
+ child_result_list.append(child.before)
+ break
+ except EOF:
+ child_result_list.append(child.before)
+ break
+ child_result = child.string_type().join(child_result_list)
+ if withexitstatus:
+ child.close()
+ return (child_result, child.exitstatus)
+ else:
+ return child_result
+
+def runu(command, timeout=30, withexitstatus=False, events=None,
+ extra_args=None, logfile=None, cwd=None, env=None, **kwargs):
+ """Deprecated: pass encoding to run() instead.
+ """
+ kwargs.setdefault('encoding', 'utf-8')
+ return run(command, timeout=timeout, withexitstatus=withexitstatus,
+ events=events, extra_args=extra_args, logfile=logfile, cwd=cwd,
+ env=env, **kwargs)
diff --git a/contrib/python/pexpect/pexpect/screen.py b/contrib/python/pexpect/pexpect/screen.py
index 21055841af..79f95c4e54 100644
--- a/contrib/python/pexpect/pexpect/screen.py
+++ b/contrib/python/pexpect/pexpect/screen.py
@@ -1,431 +1,431 @@
-'''This implements a virtual screen. This is used to support ANSI terminal
-emulation. The screen representation and state is implemented in this class.
-Most of the methods are inspired by ANSI screen control codes. The
-:class:`~pexpect.ANSI.ANSI` class extends this class to add parsing of ANSI
-escape codes.
-
-PEXPECT LICENSE
-
- This license is approved by the OSI and FSF as GPL-compatible.
- http://opensource.org/licenses/isc-license.txt
-
- Copyright (c) 2012, Noah Spurrier <noah@noah.org>
- PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
- PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
- COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-'''
-
-import codecs
-import copy
-import sys
-
-import warnings
-
-warnings.warn(("pexpect.screen and pexpect.ANSI are deprecated. "
- "We recommend using pyte to emulate a terminal screen: "
- "https://pypi.python.org/pypi/pyte"),
- stacklevel=2)
-
-NUL = 0 # Fill character; ignored on input.
-ENQ = 5 # Transmit answerback message.
-BEL = 7 # Ring the bell.
-BS = 8 # Move cursor left.
-HT = 9 # Move cursor to next tab stop.
-LF = 10 # Line feed.
-VT = 11 # Same as LF.
-FF = 12 # Same as LF.
-CR = 13 # Move cursor to left margin or newline.
-SO = 14 # Invoke G1 character set.
-SI = 15 # Invoke G0 character set.
-XON = 17 # Resume transmission.
-XOFF = 19 # Halt transmission.
-CAN = 24 # Cancel escape sequence.
-SUB = 26 # Same as CAN.
-ESC = 27 # Introduce a control sequence.
-DEL = 127 # Fill character; ignored on input.
-SPACE = u' ' # Space or blank character.
-
-PY3 = (sys.version_info[0] >= 3)
-if PY3:
- unicode = str
-
-def constrain (n, min, max):
-
- '''This returns a number, n constrained to the min and max bounds. '''
-
- if n < min:
- return min
- if n > max:
- return max
- return n
-
-class screen:
- '''This object maintains the state of a virtual text screen as a
+'''This implements a virtual screen. This is used to support ANSI terminal
+emulation. The screen representation and state is implemented in this class.
+Most of the methods are inspired by ANSI screen control codes. The
+:class:`~pexpect.ANSI.ANSI` class extends this class to add parsing of ANSI
+escape codes.
+
+PEXPECT LICENSE
+
+ This license is approved by the OSI and FSF as GPL-compatible.
+ http://opensource.org/licenses/isc-license.txt
+
+ Copyright (c) 2012, Noah Spurrier <noah@noah.org>
+ PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
+ PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
+ COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+'''
+
+import codecs
+import copy
+import sys
+
+import warnings
+
+warnings.warn(("pexpect.screen and pexpect.ANSI are deprecated. "
+ "We recommend using pyte to emulate a terminal screen: "
+ "https://pypi.python.org/pypi/pyte"),
+ stacklevel=2)
+
+NUL = 0 # Fill character; ignored on input.
+ENQ = 5 # Transmit answerback message.
+BEL = 7 # Ring the bell.
+BS = 8 # Move cursor left.
+HT = 9 # Move cursor to next tab stop.
+LF = 10 # Line feed.
+VT = 11 # Same as LF.
+FF = 12 # Same as LF.
+CR = 13 # Move cursor to left margin or newline.
+SO = 14 # Invoke G1 character set.
+SI = 15 # Invoke G0 character set.
+XON = 17 # Resume transmission.
+XOFF = 19 # Halt transmission.
+CAN = 24 # Cancel escape sequence.
+SUB = 26 # Same as CAN.
+ESC = 27 # Introduce a control sequence.
+DEL = 127 # Fill character; ignored on input.
+SPACE = u' ' # Space or blank character.
+
+PY3 = (sys.version_info[0] >= 3)
+if PY3:
+ unicode = str
+
+def constrain (n, min, max):
+
+ '''This returns a number, n constrained to the min and max bounds. '''
+
+ if n < min:
+ return min
+ if n > max:
+ return max
+ return n
+
+class screen:
+ '''This object maintains the state of a virtual text screen as a
rectangular array. This maintains a virtual cursor position and handles
- scrolling as characters are added. This supports most of the methods needed
- by an ANSI text screen. Row and column indexes are 1-based (not zero-based,
- like arrays).
-
- Characters are represented internally using unicode. Methods that accept
- input characters, when passed 'bytes' (which in Python 2 is equivalent to
- 'str'), convert them from the encoding specified in the 'encoding'
- parameter to the constructor. Methods that return screen contents return
- unicode strings, with the exception of __str__() under Python 2. Passing
- ``encoding=None`` limits the API to only accept unicode input, so passing
- bytes in will raise :exc:`TypeError`.
- '''
- def __init__(self, r=24, c=80, encoding='latin-1', encoding_errors='replace'):
- '''This initializes a blank screen of the given dimensions.'''
-
- self.rows = r
- self.cols = c
- self.encoding = encoding
- self.encoding_errors = encoding_errors
- if encoding is not None:
+ scrolling as characters are added. This supports most of the methods needed
+ by an ANSI text screen. Row and column indexes are 1-based (not zero-based,
+ like arrays).
+
+ Characters are represented internally using unicode. Methods that accept
+ input characters, when passed 'bytes' (which in Python 2 is equivalent to
+ 'str'), convert them from the encoding specified in the 'encoding'
+ parameter to the constructor. Methods that return screen contents return
+ unicode strings, with the exception of __str__() under Python 2. Passing
+ ``encoding=None`` limits the API to only accept unicode input, so passing
+ bytes in will raise :exc:`TypeError`.
+ '''
+ def __init__(self, r=24, c=80, encoding='latin-1', encoding_errors='replace'):
+ '''This initializes a blank screen of the given dimensions.'''
+
+ self.rows = r
+ self.cols = c
+ self.encoding = encoding
+ self.encoding_errors = encoding_errors
+ if encoding is not None:
self.decoder = codecs.getincrementaldecoder(encoding)(encoding_errors)
- else:
- self.decoder = None
- self.cur_r = 1
- self.cur_c = 1
- self.cur_saved_r = 1
- self.cur_saved_c = 1
- self.scroll_row_start = 1
- self.scroll_row_end = self.rows
- self.w = [ [SPACE] * self.cols for _ in range(self.rows)]
-
- def _decode(self, s):
- '''This converts from the external coding system (as passed to
- the constructor) to the internal one (unicode). '''
- if self.decoder is not None:
- return self.decoder.decode(s)
- else:
- raise TypeError("This screen was constructed with encoding=None, "
- "so it does not handle bytes.")
-
- def _unicode(self):
- '''This returns a printable representation of the screen as a unicode
- string (which, under Python 3.x, is the same as 'str'). The end of each
- screen line is terminated by a newline.'''
-
- return u'\n'.join ([ u''.join(c) for c in self.w ])
-
- if PY3:
- __str__ = _unicode
- else:
- __unicode__ = _unicode
-
- def __str__(self):
- '''This returns a printable representation of the screen. The end of
- each screen line is terminated by a newline. '''
- encoding = self.encoding or 'ascii'
- return self._unicode().encode(encoding, 'replace')
-
- def dump (self):
- '''This returns a copy of the screen as a unicode string. This is similar to
- __str__/__unicode__ except that lines are not terminated with line
- feeds.'''
-
- return u''.join ([ u''.join(c) for c in self.w ])
-
- def pretty (self):
- '''This returns a copy of the screen as a unicode string with an ASCII
- text box around the screen border. This is similar to
- __str__/__unicode__ except that it adds a box.'''
-
- top_bot = u'+' + u'-'*self.cols + u'+\n'
- return top_bot + u'\n'.join([u'|'+line+u'|' for line in unicode(self).split(u'\n')]) + u'\n' + top_bot
-
- def fill (self, ch=SPACE):
-
- if isinstance(ch, bytes):
- ch = self._decode(ch)
-
- self.fill_region (1,1,self.rows,self.cols, ch)
-
- def fill_region (self, rs,cs, re,ce, ch=SPACE):
-
- if isinstance(ch, bytes):
- ch = self._decode(ch)
-
- rs = constrain (rs, 1, self.rows)
- re = constrain (re, 1, self.rows)
- cs = constrain (cs, 1, self.cols)
- ce = constrain (ce, 1, self.cols)
- if rs > re:
- rs, re = re, rs
- if cs > ce:
- cs, ce = ce, cs
- for r in range (rs, re+1):
- for c in range (cs, ce + 1):
- self.put_abs (r,c,ch)
-
- def cr (self):
- '''This moves the cursor to the beginning (col 1) of the current row.
- '''
-
- self.cursor_home (self.cur_r, 1)
-
- def lf (self):
- '''This moves the cursor down with scrolling.
- '''
-
- old_r = self.cur_r
- self.cursor_down()
- if old_r == self.cur_r:
- self.scroll_up ()
- self.erase_line()
-
- def crlf (self):
- '''This advances the cursor with CRLF properties.
- The cursor will line wrap and the screen may scroll.
- '''
-
- self.cr ()
- self.lf ()
-
- def newline (self):
- '''This is an alias for crlf().
- '''
-
- self.crlf()
-
- def put_abs (self, r, c, ch):
- '''Screen array starts at 1 index.'''
-
- r = constrain (r, 1, self.rows)
- c = constrain (c, 1, self.cols)
- if isinstance(ch, bytes):
- ch = self._decode(ch)[0]
- else:
- ch = ch[0]
- self.w[r-1][c-1] = ch
-
- def put (self, ch):
- '''This puts a characters at the current cursor position.
- '''
-
- if isinstance(ch, bytes):
- ch = self._decode(ch)
-
- self.put_abs (self.cur_r, self.cur_c, ch)
-
- def insert_abs (self, r, c, ch):
- '''This inserts a character at (r,c). Everything under
- and to the right is shifted right one character.
- The last character of the line is lost.
- '''
-
- if isinstance(ch, bytes):
- ch = self._decode(ch)
-
- r = constrain (r, 1, self.rows)
- c = constrain (c, 1, self.cols)
- for ci in range (self.cols, c, -1):
- self.put_abs (r,ci, self.get_abs(r,ci-1))
- self.put_abs (r,c,ch)
-
- def insert (self, ch):
-
- if isinstance(ch, bytes):
- ch = self._decode(ch)
-
- self.insert_abs (self.cur_r, self.cur_c, ch)
-
- def get_abs (self, r, c):
-
- r = constrain (r, 1, self.rows)
- c = constrain (c, 1, self.cols)
- return self.w[r-1][c-1]
-
- def get (self):
-
- self.get_abs (self.cur_r, self.cur_c)
-
- def get_region (self, rs,cs, re,ce):
- '''This returns a list of lines representing the region.
- '''
-
- rs = constrain (rs, 1, self.rows)
- re = constrain (re, 1, self.rows)
- cs = constrain (cs, 1, self.cols)
- ce = constrain (ce, 1, self.cols)
- if rs > re:
- rs, re = re, rs
- if cs > ce:
- cs, ce = ce, cs
- sc = []
- for r in range (rs, re+1):
- line = u''
- for c in range (cs, ce + 1):
- ch = self.get_abs (r,c)
- line = line + ch
- sc.append (line)
- return sc
-
- def cursor_constrain (self):
- '''This keeps the cursor within the screen area.
- '''
-
- self.cur_r = constrain (self.cur_r, 1, self.rows)
- self.cur_c = constrain (self.cur_c, 1, self.cols)
-
- def cursor_home (self, r=1, c=1): # <ESC>[{ROW};{COLUMN}H
-
- self.cur_r = r
- self.cur_c = c
- self.cursor_constrain ()
-
- def cursor_back (self,count=1): # <ESC>[{COUNT}D (not confused with down)
-
- self.cur_c = self.cur_c - count
- self.cursor_constrain ()
-
- def cursor_down (self,count=1): # <ESC>[{COUNT}B (not confused with back)
-
- self.cur_r = self.cur_r + count
- self.cursor_constrain ()
-
- def cursor_forward (self,count=1): # <ESC>[{COUNT}C
-
- self.cur_c = self.cur_c + count
- self.cursor_constrain ()
-
- def cursor_up (self,count=1): # <ESC>[{COUNT}A
-
- self.cur_r = self.cur_r - count
- self.cursor_constrain ()
-
- def cursor_up_reverse (self): # <ESC> M (called RI -- Reverse Index)
-
- old_r = self.cur_r
- self.cursor_up()
- if old_r == self.cur_r:
- self.scroll_up()
-
- def cursor_force_position (self, r, c): # <ESC>[{ROW};{COLUMN}f
- '''Identical to Cursor Home.'''
-
- self.cursor_home (r, c)
-
- def cursor_save (self): # <ESC>[s
- '''Save current cursor position.'''
-
- self.cursor_save_attrs()
-
- def cursor_unsave (self): # <ESC>[u
- '''Restores cursor position after a Save Cursor.'''
-
- self.cursor_restore_attrs()
-
- def cursor_save_attrs (self): # <ESC>7
- '''Save current cursor position.'''
-
- self.cur_saved_r = self.cur_r
- self.cur_saved_c = self.cur_c
-
- def cursor_restore_attrs (self): # <ESC>8
- '''Restores cursor position after a Save Cursor.'''
-
- self.cursor_home (self.cur_saved_r, self.cur_saved_c)
-
- def scroll_constrain (self):
- '''This keeps the scroll region within the screen region.'''
-
- if self.scroll_row_start <= 0:
- self.scroll_row_start = 1
- if self.scroll_row_end > self.rows:
- self.scroll_row_end = self.rows
-
- def scroll_screen (self): # <ESC>[r
- '''Enable scrolling for entire display.'''
-
- self.scroll_row_start = 1
- self.scroll_row_end = self.rows
-
- def scroll_screen_rows (self, rs, re): # <ESC>[{start};{end}r
- '''Enable scrolling from row {start} to row {end}.'''
-
- self.scroll_row_start = rs
- self.scroll_row_end = re
- self.scroll_constrain()
-
- def scroll_down (self): # <ESC>D
- '''Scroll display down one line.'''
-
- # Screen is indexed from 1, but arrays are indexed from 0.
- s = self.scroll_row_start - 1
- e = self.scroll_row_end - 1
- self.w[s+1:e+1] = copy.deepcopy(self.w[s:e])
-
- def scroll_up (self): # <ESC>M
- '''Scroll display up one line.'''
-
- # Screen is indexed from 1, but arrays are indexed from 0.
- s = self.scroll_row_start - 1
- e = self.scroll_row_end - 1
- self.w[s:e] = copy.deepcopy(self.w[s+1:e+1])
-
- def erase_end_of_line (self): # <ESC>[0K -or- <ESC>[K
- '''Erases from the current cursor position to the end of the current
- line.'''
-
- self.fill_region (self.cur_r, self.cur_c, self.cur_r, self.cols)
-
- def erase_start_of_line (self): # <ESC>[1K
- '''Erases from the current cursor position to the start of the current
- line.'''
-
- self.fill_region (self.cur_r, 1, self.cur_r, self.cur_c)
-
- def erase_line (self): # <ESC>[2K
- '''Erases the entire current line.'''
-
- self.fill_region (self.cur_r, 1, self.cur_r, self.cols)
-
- def erase_down (self): # <ESC>[0J -or- <ESC>[J
- '''Erases the screen from the current line down to the bottom of the
- screen.'''
-
- self.erase_end_of_line ()
- self.fill_region (self.cur_r + 1, 1, self.rows, self.cols)
-
- def erase_up (self): # <ESC>[1J
- '''Erases the screen from the current line up to the top of the
- screen.'''
-
- self.erase_start_of_line ()
- self.fill_region (self.cur_r-1, 1, 1, self.cols)
-
- def erase_screen (self): # <ESC>[2J
- '''Erases the screen with the background color.'''
-
- self.fill ()
-
- def set_tab (self): # <ESC>H
- '''Sets a tab at the current position.'''
-
- pass
-
- def clear_tab (self): # <ESC>[g
- '''Clears tab at the current position.'''
-
- pass
-
- def clear_all_tabs (self): # <ESC>[3g
- '''Clears all tabs.'''
-
- pass
-
-# Insert line Esc [ Pn L
-# Delete line Esc [ Pn M
-# Delete character Esc [ Pn P
-# Scrolling region Esc [ Pn(top);Pn(bot) r
-
+ else:
+ self.decoder = None
+ self.cur_r = 1
+ self.cur_c = 1
+ self.cur_saved_r = 1
+ self.cur_saved_c = 1
+ self.scroll_row_start = 1
+ self.scroll_row_end = self.rows
+ self.w = [ [SPACE] * self.cols for _ in range(self.rows)]
+
+ def _decode(self, s):
+ '''This converts from the external coding system (as passed to
+ the constructor) to the internal one (unicode). '''
+ if self.decoder is not None:
+ return self.decoder.decode(s)
+ else:
+ raise TypeError("This screen was constructed with encoding=None, "
+ "so it does not handle bytes.")
+
+ def _unicode(self):
+ '''This returns a printable representation of the screen as a unicode
+ string (which, under Python 3.x, is the same as 'str'). The end of each
+ screen line is terminated by a newline.'''
+
+ return u'\n'.join ([ u''.join(c) for c in self.w ])
+
+ if PY3:
+ __str__ = _unicode
+ else:
+ __unicode__ = _unicode
+
+ def __str__(self):
+ '''This returns a printable representation of the screen. The end of
+ each screen line is terminated by a newline. '''
+ encoding = self.encoding or 'ascii'
+ return self._unicode().encode(encoding, 'replace')
+
+ def dump (self):
+ '''This returns a copy of the screen as a unicode string. This is similar to
+ __str__/__unicode__ except that lines are not terminated with line
+ feeds.'''
+
+ return u''.join ([ u''.join(c) for c in self.w ])
+
+ def pretty (self):
+ '''This returns a copy of the screen as a unicode string with an ASCII
+ text box around the screen border. This is similar to
+ __str__/__unicode__ except that it adds a box.'''
+
+ top_bot = u'+' + u'-'*self.cols + u'+\n'
+ return top_bot + u'\n'.join([u'|'+line+u'|' for line in unicode(self).split(u'\n')]) + u'\n' + top_bot
+
+ def fill (self, ch=SPACE):
+
+ if isinstance(ch, bytes):
+ ch = self._decode(ch)
+
+ self.fill_region (1,1,self.rows,self.cols, ch)
+
+ def fill_region (self, rs,cs, re,ce, ch=SPACE):
+
+ if isinstance(ch, bytes):
+ ch = self._decode(ch)
+
+ rs = constrain (rs, 1, self.rows)
+ re = constrain (re, 1, self.rows)
+ cs = constrain (cs, 1, self.cols)
+ ce = constrain (ce, 1, self.cols)
+ if rs > re:
+ rs, re = re, rs
+ if cs > ce:
+ cs, ce = ce, cs
+ for r in range (rs, re+1):
+ for c in range (cs, ce + 1):
+ self.put_abs (r,c,ch)
+
+ def cr (self):
+ '''This moves the cursor to the beginning (col 1) of the current row.
+ '''
+
+ self.cursor_home (self.cur_r, 1)
+
+ def lf (self):
+ '''This moves the cursor down with scrolling.
+ '''
+
+ old_r = self.cur_r
+ self.cursor_down()
+ if old_r == self.cur_r:
+ self.scroll_up ()
+ self.erase_line()
+
+ def crlf (self):
+ '''This advances the cursor with CRLF properties.
+ The cursor will line wrap and the screen may scroll.
+ '''
+
+ self.cr ()
+ self.lf ()
+
+ def newline (self):
+ '''This is an alias for crlf().
+ '''
+
+ self.crlf()
+
+ def put_abs (self, r, c, ch):
+ '''Screen array starts at 1 index.'''
+
+ r = constrain (r, 1, self.rows)
+ c = constrain (c, 1, self.cols)
+ if isinstance(ch, bytes):
+ ch = self._decode(ch)[0]
+ else:
+ ch = ch[0]
+ self.w[r-1][c-1] = ch
+
+ def put (self, ch):
+ '''This puts a characters at the current cursor position.
+ '''
+
+ if isinstance(ch, bytes):
+ ch = self._decode(ch)
+
+ self.put_abs (self.cur_r, self.cur_c, ch)
+
+ def insert_abs (self, r, c, ch):
+ '''This inserts a character at (r,c). Everything under
+ and to the right is shifted right one character.
+ The last character of the line is lost.
+ '''
+
+ if isinstance(ch, bytes):
+ ch = self._decode(ch)
+
+ r = constrain (r, 1, self.rows)
+ c = constrain (c, 1, self.cols)
+ for ci in range (self.cols, c, -1):
+ self.put_abs (r,ci, self.get_abs(r,ci-1))
+ self.put_abs (r,c,ch)
+
+ def insert (self, ch):
+
+ if isinstance(ch, bytes):
+ ch = self._decode(ch)
+
+ self.insert_abs (self.cur_r, self.cur_c, ch)
+
+ def get_abs (self, r, c):
+
+ r = constrain (r, 1, self.rows)
+ c = constrain (c, 1, self.cols)
+ return self.w[r-1][c-1]
+
+ def get (self):
+
+ self.get_abs (self.cur_r, self.cur_c)
+
+ def get_region (self, rs,cs, re,ce):
+ '''This returns a list of lines representing the region.
+ '''
+
+ rs = constrain (rs, 1, self.rows)
+ re = constrain (re, 1, self.rows)
+ cs = constrain (cs, 1, self.cols)
+ ce = constrain (ce, 1, self.cols)
+ if rs > re:
+ rs, re = re, rs
+ if cs > ce:
+ cs, ce = ce, cs
+ sc = []
+ for r in range (rs, re+1):
+ line = u''
+ for c in range (cs, ce + 1):
+ ch = self.get_abs (r,c)
+ line = line + ch
+ sc.append (line)
+ return sc
+
+ def cursor_constrain (self):
+ '''This keeps the cursor within the screen area.
+ '''
+
+ self.cur_r = constrain (self.cur_r, 1, self.rows)
+ self.cur_c = constrain (self.cur_c, 1, self.cols)
+
+ def cursor_home (self, r=1, c=1): # <ESC>[{ROW};{COLUMN}H
+
+ self.cur_r = r
+ self.cur_c = c
+ self.cursor_constrain ()
+
+ def cursor_back (self,count=1): # <ESC>[{COUNT}D (not confused with down)
+
+ self.cur_c = self.cur_c - count
+ self.cursor_constrain ()
+
+ def cursor_down (self,count=1): # <ESC>[{COUNT}B (not confused with back)
+
+ self.cur_r = self.cur_r + count
+ self.cursor_constrain ()
+
+ def cursor_forward (self,count=1): # <ESC>[{COUNT}C
+
+ self.cur_c = self.cur_c + count
+ self.cursor_constrain ()
+
+ def cursor_up (self,count=1): # <ESC>[{COUNT}A
+
+ self.cur_r = self.cur_r - count
+ self.cursor_constrain ()
+
+ def cursor_up_reverse (self): # <ESC> M (called RI -- Reverse Index)
+
+ old_r = self.cur_r
+ self.cursor_up()
+ if old_r == self.cur_r:
+ self.scroll_up()
+
+ def cursor_force_position (self, r, c): # <ESC>[{ROW};{COLUMN}f
+ '''Identical to Cursor Home.'''
+
+ self.cursor_home (r, c)
+
+ def cursor_save (self): # <ESC>[s
+ '''Save current cursor position.'''
+
+ self.cursor_save_attrs()
+
+ def cursor_unsave (self): # <ESC>[u
+ '''Restores cursor position after a Save Cursor.'''
+
+ self.cursor_restore_attrs()
+
+ def cursor_save_attrs (self): # <ESC>7
+ '''Save current cursor position.'''
+
+ self.cur_saved_r = self.cur_r
+ self.cur_saved_c = self.cur_c
+
+ def cursor_restore_attrs (self): # <ESC>8
+ '''Restores cursor position after a Save Cursor.'''
+
+ self.cursor_home (self.cur_saved_r, self.cur_saved_c)
+
+ def scroll_constrain (self):
+ '''This keeps the scroll region within the screen region.'''
+
+ if self.scroll_row_start <= 0:
+ self.scroll_row_start = 1
+ if self.scroll_row_end > self.rows:
+ self.scroll_row_end = self.rows
+
+ def scroll_screen (self): # <ESC>[r
+ '''Enable scrolling for entire display.'''
+
+ self.scroll_row_start = 1
+ self.scroll_row_end = self.rows
+
+ def scroll_screen_rows (self, rs, re): # <ESC>[{start};{end}r
+ '''Enable scrolling from row {start} to row {end}.'''
+
+ self.scroll_row_start = rs
+ self.scroll_row_end = re
+ self.scroll_constrain()
+
+ def scroll_down (self): # <ESC>D
+ '''Scroll display down one line.'''
+
+ # Screen is indexed from 1, but arrays are indexed from 0.
+ s = self.scroll_row_start - 1
+ e = self.scroll_row_end - 1
+ self.w[s+1:e+1] = copy.deepcopy(self.w[s:e])
+
+ def scroll_up (self): # <ESC>M
+ '''Scroll display up one line.'''
+
+ # Screen is indexed from 1, but arrays are indexed from 0.
+ s = self.scroll_row_start - 1
+ e = self.scroll_row_end - 1
+ self.w[s:e] = copy.deepcopy(self.w[s+1:e+1])
+
+ def erase_end_of_line (self): # <ESC>[0K -or- <ESC>[K
+ '''Erases from the current cursor position to the end of the current
+ line.'''
+
+ self.fill_region (self.cur_r, self.cur_c, self.cur_r, self.cols)
+
+ def erase_start_of_line (self): # <ESC>[1K
+ '''Erases from the current cursor position to the start of the current
+ line.'''
+
+ self.fill_region (self.cur_r, 1, self.cur_r, self.cur_c)
+
+ def erase_line (self): # <ESC>[2K
+ '''Erases the entire current line.'''
+
+ self.fill_region (self.cur_r, 1, self.cur_r, self.cols)
+
+ def erase_down (self): # <ESC>[0J -or- <ESC>[J
+ '''Erases the screen from the current line down to the bottom of the
+ screen.'''
+
+ self.erase_end_of_line ()
+ self.fill_region (self.cur_r + 1, 1, self.rows, self.cols)
+
+ def erase_up (self): # <ESC>[1J
+ '''Erases the screen from the current line up to the top of the
+ screen.'''
+
+ self.erase_start_of_line ()
+ self.fill_region (self.cur_r-1, 1, 1, self.cols)
+
+ def erase_screen (self): # <ESC>[2J
+ '''Erases the screen with the background color.'''
+
+ self.fill ()
+
+ def set_tab (self): # <ESC>H
+ '''Sets a tab at the current position.'''
+
+ pass
+
+ def clear_tab (self): # <ESC>[g
+ '''Clears tab at the current position.'''
+
+ pass
+
+ def clear_all_tabs (self): # <ESC>[3g
+ '''Clears all tabs.'''
+
+ pass
+
+# Insert line Esc [ Pn L
+# Delete line Esc [ Pn M
+# Delete character Esc [ Pn P
+# Scrolling region Esc [ Pn(top);Pn(bot) r
+
diff --git a/contrib/python/pexpect/pexpect/spawnbase.py b/contrib/python/pexpect/pexpect/spawnbase.py
index b33eadd069..59e905764c 100644
--- a/contrib/python/pexpect/pexpect/spawnbase.py
+++ b/contrib/python/pexpect/pexpect/spawnbase.py
@@ -1,121 +1,121 @@
from io import StringIO, BytesIO
-import codecs
-import os
-import sys
-import re
-import errno
-from .exceptions import ExceptionPexpect, EOF, TIMEOUT
-from .expect import Expecter, searcher_string, searcher_re
-
-PY3 = (sys.version_info[0] >= 3)
-text_type = str if PY3 else unicode
-
-class _NullCoder(object):
- """Pass bytes through unchanged."""
- @staticmethod
- def encode(b, final=False):
- return b
-
- @staticmethod
- def decode(b, final=False):
- return b
-
-class SpawnBase(object):
- """A base class providing the backwards-compatible spawn API for Pexpect.
-
- This should not be instantiated directly: use :class:`pexpect.spawn` or
- :class:`pexpect.fdpexpect.fdspawn`.
- """
- encoding = None
- pid = None
- flag_eof = False
-
- def __init__(self, timeout=30, maxread=2000, searchwindowsize=None,
- logfile=None, encoding=None, codec_errors='strict'):
- self.stdin = sys.stdin
- self.stdout = sys.stdout
- self.stderr = sys.stderr
-
- self.searcher = None
- self.ignorecase = False
- self.before = None
- self.after = None
- self.match = None
- self.match_index = None
- self.terminated = True
- self.exitstatus = None
- self.signalstatus = None
- # status returned by os.waitpid
- self.status = None
- # the child file descriptor is initially closed
- self.child_fd = -1
- self.timeout = timeout
- self.delimiter = EOF
- self.logfile = logfile
- # input from child (read_nonblocking)
- self.logfile_read = None
- # output to send (send, sendline)
- self.logfile_send = None
- # max bytes to read at one time into buffer
- self.maxread = maxread
- # Data before searchwindowsize point is preserved, but not searched.
- self.searchwindowsize = searchwindowsize
- # Delay used before sending data to child. Time in seconds.
+import codecs
+import os
+import sys
+import re
+import errno
+from .exceptions import ExceptionPexpect, EOF, TIMEOUT
+from .expect import Expecter, searcher_string, searcher_re
+
+PY3 = (sys.version_info[0] >= 3)
+text_type = str if PY3 else unicode
+
+class _NullCoder(object):
+ """Pass bytes through unchanged."""
+ @staticmethod
+ def encode(b, final=False):
+ return b
+
+ @staticmethod
+ def decode(b, final=False):
+ return b
+
+class SpawnBase(object):
+ """A base class providing the backwards-compatible spawn API for Pexpect.
+
+ This should not be instantiated directly: use :class:`pexpect.spawn` or
+ :class:`pexpect.fdpexpect.fdspawn`.
+ """
+ encoding = None
+ pid = None
+ flag_eof = False
+
+ def __init__(self, timeout=30, maxread=2000, searchwindowsize=None,
+ logfile=None, encoding=None, codec_errors='strict'):
+ self.stdin = sys.stdin
+ self.stdout = sys.stdout
+ self.stderr = sys.stderr
+
+ self.searcher = None
+ self.ignorecase = False
+ self.before = None
+ self.after = None
+ self.match = None
+ self.match_index = None
+ self.terminated = True
+ self.exitstatus = None
+ self.signalstatus = None
+ # status returned by os.waitpid
+ self.status = None
+ # the child file descriptor is initially closed
+ self.child_fd = -1
+ self.timeout = timeout
+ self.delimiter = EOF
+ self.logfile = logfile
+ # input from child (read_nonblocking)
+ self.logfile_read = None
+ # output to send (send, sendline)
+ self.logfile_send = None
+ # max bytes to read at one time into buffer
+ self.maxread = maxread
+ # Data before searchwindowsize point is preserved, but not searched.
+ self.searchwindowsize = searchwindowsize
+ # Delay used before sending data to child. Time in seconds.
# Set this to None to skip the time.sleep() call completely.
- self.delaybeforesend = 0.05
- # Used by close() to give kernel time to update process status.
- # Time in seconds.
- self.delayafterclose = 0.1
- # Used by terminate() to give kernel time to update process status.
- # Time in seconds.
- self.delayafterterminate = 0.1
+ self.delaybeforesend = 0.05
+ # Used by close() to give kernel time to update process status.
+ # Time in seconds.
+ self.delayafterclose = 0.1
+ # Used by terminate() to give kernel time to update process status.
+ # Time in seconds.
+ self.delayafterterminate = 0.1
# Delay in seconds to sleep after each call to read_nonblocking().
# Set this to None to skip the time.sleep() call completely: that
# would restore the behavior from pexpect-2.0 (for performance
# reasons or because you don't want to release Python's global
# interpreter lock).
self.delayafterread = 0.0001
- self.softspace = False
- self.name = '<' + repr(self) + '>'
- self.closed = True
-
- # Unicode interface
- self.encoding = encoding
- self.codec_errors = codec_errors
- if encoding is None:
- # bytes mode (accepts some unicode for backwards compatibility)
- self._encoder = self._decoder = _NullCoder()
- self.string_type = bytes
+ self.softspace = False
+ self.name = '<' + repr(self) + '>'
+ self.closed = True
+
+ # Unicode interface
+ self.encoding = encoding
+ self.codec_errors = codec_errors
+ if encoding is None:
+ # bytes mode (accepts some unicode for backwards compatibility)
+ self._encoder = self._decoder = _NullCoder()
+ self.string_type = bytes
self.buffer_type = BytesIO
- self.crlf = b'\r\n'
- if PY3:
- self.allowed_string_types = (bytes, str)
- self.linesep = os.linesep.encode('ascii')
- def write_to_stdout(b):
- try:
- return sys.stdout.buffer.write(b)
- except AttributeError:
- # If stdout has been replaced, it may not have .buffer
- return sys.stdout.write(b.decode('ascii', 'replace'))
- self.write_to_stdout = write_to_stdout
- else:
- self.allowed_string_types = (basestring,) # analysis:ignore
- self.linesep = os.linesep
- self.write_to_stdout = sys.stdout.write
- else:
- # unicode mode
- self._encoder = codecs.getincrementalencoder(encoding)(codec_errors)
- self._decoder = codecs.getincrementaldecoder(encoding)(codec_errors)
- self.string_type = text_type
+ self.crlf = b'\r\n'
+ if PY3:
+ self.allowed_string_types = (bytes, str)
+ self.linesep = os.linesep.encode('ascii')
+ def write_to_stdout(b):
+ try:
+ return sys.stdout.buffer.write(b)
+ except AttributeError:
+ # If stdout has been replaced, it may not have .buffer
+ return sys.stdout.write(b.decode('ascii', 'replace'))
+ self.write_to_stdout = write_to_stdout
+ else:
+ self.allowed_string_types = (basestring,) # analysis:ignore
+ self.linesep = os.linesep
+ self.write_to_stdout = sys.stdout.write
+ else:
+ # unicode mode
+ self._encoder = codecs.getincrementalencoder(encoding)(codec_errors)
+ self._decoder = codecs.getincrementaldecoder(encoding)(codec_errors)
+ self.string_type = text_type
self.buffer_type = StringIO
- self.crlf = u'\r\n'
- self.allowed_string_types = (text_type, )
- if PY3:
- self.linesep = os.linesep
- else:
- self.linesep = os.linesep.decode('ascii')
- # This can handle unicode in both Python 2 and 3
- self.write_to_stdout = sys.stdout.write
+ self.crlf = u'\r\n'
+ self.allowed_string_types = (text_type, )
+ if PY3:
+ self.linesep = os.linesep
+ else:
+ self.linesep = os.linesep.decode('ascii')
+ # This can handle unicode in both Python 2 and 3
+ self.write_to_stdout = sys.stdout.write
# storage for async transport
self.async_pw_transport = None
# This is the read buffer. See maxread.
@@ -123,29 +123,29 @@ class SpawnBase(object):
# The buffer may be trimmed for efficiency reasons. This is the
# untrimmed buffer, used to create the before attribute.
self._before = self.buffer_type()
-
- def _log(self, s, direction):
- if self.logfile is not None:
- self.logfile.write(s)
- self.logfile.flush()
- second_log = self.logfile_send if (direction=='send') else self.logfile_read
- if second_log is not None:
- second_log.write(s)
- second_log.flush()
-
- # For backwards compatibility, in bytes mode (when encoding is None)
- # unicode is accepted for send and expect. Unicode mode is strictly unicode
- # only.
- def _coerce_expect_string(self, s):
- if self.encoding is None and not isinstance(s, bytes):
- return s.encode('ascii')
- return s
-
- def _coerce_send_string(self, s):
- if self.encoding is None and not isinstance(s, bytes):
- return s.encode('utf-8')
- return s
-
+
+ def _log(self, s, direction):
+ if self.logfile is not None:
+ self.logfile.write(s)
+ self.logfile.flush()
+ second_log = self.logfile_send if (direction=='send') else self.logfile_read
+ if second_log is not None:
+ second_log.write(s)
+ second_log.flush()
+
+ # For backwards compatibility, in bytes mode (when encoding is None)
+ # unicode is accepted for send and expect. Unicode mode is strictly unicode
+ # only.
+ def _coerce_expect_string(self, s):
+ if self.encoding is None and not isinstance(s, bytes):
+ return s.encode('ascii')
+ return s
+
+ def _coerce_send_string(self, s):
+ if self.encoding is None and not isinstance(s, bytes):
+ return s.encode('utf-8')
+ return s
+
def _get_buffer(self):
return self._buffer.getvalue()
@@ -157,369 +157,369 @@ class SpawnBase(object):
# to be a string/bytes object)
buffer = property(_get_buffer, _set_buffer)
- def read_nonblocking(self, size=1, timeout=None):
- """This reads data from the file descriptor.
-
- This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.
-
- The timeout parameter is ignored.
- """
-
- try:
- s = os.read(self.child_fd, size)
- except OSError as err:
- if err.args[0] == errno.EIO:
- # Linux-style EOF
- self.flag_eof = True
- raise EOF('End Of File (EOF). Exception style platform.')
- raise
- if s == b'':
- # BSD-style EOF
- self.flag_eof = True
- raise EOF('End Of File (EOF). Empty string style platform.')
-
- s = self._decoder.decode(s, final=False)
- self._log(s, 'read')
- return s
-
- def _pattern_type_err(self, pattern):
- raise TypeError('got {badtype} ({badobj!r}) as pattern, must be one'
- ' of: {goodtypes}, pexpect.EOF, pexpect.TIMEOUT'\
- .format(badtype=type(pattern),
- badobj=pattern,
- goodtypes=', '.join([str(ast)\
- for ast in self.allowed_string_types])
- )
- )
-
- def compile_pattern_list(self, patterns):
- '''This compiles a pattern-string or a list of pattern-strings.
- Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
- those. Patterns may also be None which results in an empty list (you
- might do this if waiting for an EOF or TIMEOUT condition without
- expecting any pattern).
-
- This is used by expect() when calling expect_list(). Thus expect() is
- nothing more than::
-
- cpl = self.compile_pattern_list(pl)
- return self.expect_list(cpl, timeout)
-
- If you are using expect() within a loop it may be more
- efficient to compile the patterns first and then call expect_list().
- This avoid calls in a loop to compile_pattern_list()::
-
- cpl = self.compile_pattern_list(my_pattern)
- while some_condition:
- ...
- i = self.expect_list(cpl, timeout)
- ...
- '''
-
- if patterns is None:
- return []
- if not isinstance(patterns, list):
- patterns = [patterns]
-
- # Allow dot to match \n
- compile_flags = re.DOTALL
- if self.ignorecase:
- compile_flags = compile_flags | re.IGNORECASE
- compiled_pattern_list = []
- for idx, p in enumerate(patterns):
- if isinstance(p, self.allowed_string_types):
- p = self._coerce_expect_string(p)
- compiled_pattern_list.append(re.compile(p, compile_flags))
- elif p is EOF:
- compiled_pattern_list.append(EOF)
- elif p is TIMEOUT:
- compiled_pattern_list.append(TIMEOUT)
- elif isinstance(p, type(re.compile(''))):
- compiled_pattern_list.append(p)
- else:
- self._pattern_type_err(p)
- return compiled_pattern_list
-
+ def read_nonblocking(self, size=1, timeout=None):
+ """This reads data from the file descriptor.
+
+ This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.
+
+ The timeout parameter is ignored.
+ """
+
+ try:
+ s = os.read(self.child_fd, size)
+ except OSError as err:
+ if err.args[0] == errno.EIO:
+ # Linux-style EOF
+ self.flag_eof = True
+ raise EOF('End Of File (EOF). Exception style platform.')
+ raise
+ if s == b'':
+ # BSD-style EOF
+ self.flag_eof = True
+ raise EOF('End Of File (EOF). Empty string style platform.')
+
+ s = self._decoder.decode(s, final=False)
+ self._log(s, 'read')
+ return s
+
+ def _pattern_type_err(self, pattern):
+ raise TypeError('got {badtype} ({badobj!r}) as pattern, must be one'
+ ' of: {goodtypes}, pexpect.EOF, pexpect.TIMEOUT'\
+ .format(badtype=type(pattern),
+ badobj=pattern,
+ goodtypes=', '.join([str(ast)\
+ for ast in self.allowed_string_types])
+ )
+ )
+
+ def compile_pattern_list(self, patterns):
+ '''This compiles a pattern-string or a list of pattern-strings.
+ Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
+ those. Patterns may also be None which results in an empty list (you
+ might do this if waiting for an EOF or TIMEOUT condition without
+ expecting any pattern).
+
+ This is used by expect() when calling expect_list(). Thus expect() is
+ nothing more than::
+
+ cpl = self.compile_pattern_list(pl)
+ return self.expect_list(cpl, timeout)
+
+ If you are using expect() within a loop it may be more
+ efficient to compile the patterns first and then call expect_list().
+ This avoid calls in a loop to compile_pattern_list()::
+
+ cpl = self.compile_pattern_list(my_pattern)
+ while some_condition:
+ ...
+ i = self.expect_list(cpl, timeout)
+ ...
+ '''
+
+ if patterns is None:
+ return []
+ if not isinstance(patterns, list):
+ patterns = [patterns]
+
+ # Allow dot to match \n
+ compile_flags = re.DOTALL
+ if self.ignorecase:
+ compile_flags = compile_flags | re.IGNORECASE
+ compiled_pattern_list = []
+ for idx, p in enumerate(patterns):
+ if isinstance(p, self.allowed_string_types):
+ p = self._coerce_expect_string(p)
+ compiled_pattern_list.append(re.compile(p, compile_flags))
+ elif p is EOF:
+ compiled_pattern_list.append(EOF)
+ elif p is TIMEOUT:
+ compiled_pattern_list.append(TIMEOUT)
+ elif isinstance(p, type(re.compile(''))):
+ compiled_pattern_list.append(p)
+ else:
+ self._pattern_type_err(p)
+ return compiled_pattern_list
+
def expect(self, pattern, timeout=-1, searchwindowsize=-1, async_=False, **kw):
- '''This seeks through the stream until a pattern is matched. The
- pattern is overloaded and may take several types. The pattern can be a
- StringType, EOF, a compiled re, or a list of any of those types.
- Strings will be compiled to re types. This returns the index into the
- pattern list. If the pattern was not a list this returns index 0 on a
- successful match. This may raise exceptions for EOF or TIMEOUT. To
- avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
- list. That will cause expect to match an EOF or TIMEOUT condition
- instead of raising an exception.
-
- If you pass a list of patterns and more than one matches, the first
- match in the stream is chosen. If more than one pattern matches at that
- point, the leftmost in the pattern list is chosen. For example::
-
- # the input is 'foobar'
- index = p.expect(['bar', 'foo', 'foobar'])
- # returns 1('foo') even though 'foobar' is a "better" match
-
- Please note, however, that buffering can affect this behavior, since
- input arrives in unpredictable chunks. For example::
-
- # the input is 'foobar'
- index = p.expect(['foobar', 'foo'])
- # returns 0('foobar') if all input is available at once,
+ '''This seeks through the stream until a pattern is matched. The
+ pattern is overloaded and may take several types. The pattern can be a
+ StringType, EOF, a compiled re, or a list of any of those types.
+ Strings will be compiled to re types. This returns the index into the
+ pattern list. If the pattern was not a list this returns index 0 on a
+ successful match. This may raise exceptions for EOF or TIMEOUT. To
+ avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
+ list. That will cause expect to match an EOF or TIMEOUT condition
+ instead of raising an exception.
+
+ If you pass a list of patterns and more than one matches, the first
+ match in the stream is chosen. If more than one pattern matches at that
+ point, the leftmost in the pattern list is chosen. For example::
+
+ # the input is 'foobar'
+ index = p.expect(['bar', 'foo', 'foobar'])
+ # returns 1('foo') even though 'foobar' is a "better" match
+
+ Please note, however, that buffering can affect this behavior, since
+ input arrives in unpredictable chunks. For example::
+
+ # the input is 'foobar'
+ index = p.expect(['foobar', 'foo'])
+ # returns 0('foobar') if all input is available at once,
# but returns 1('foo') if parts of the final 'bar' arrive late
-
- When a match is found for the given pattern, the class instance
- attribute *match* becomes an re.MatchObject result. Should an EOF
- or TIMEOUT pattern match, then the match attribute will be an instance
- of that exception class. The pairing before and after class
- instance attributes are views of the data preceding and following
- the matching pattern. On general exception, class attribute
- *before* is all data received up to the exception, while *match* and
- *after* attributes are value None.
-
- When the keyword argument timeout is -1 (default), then TIMEOUT will
- raise after the default value specified by the class timeout
- attribute. When None, TIMEOUT will not be raised and may block
- indefinitely until match.
-
- When the keyword argument searchwindowsize is -1 (default), then the
- value specified by the class maxread attribute is used.
-
- A list entry may be EOF or TIMEOUT instead of a string. This will
- catch these exceptions and return the index of the list entry instead
- of raising the exception. The attribute 'after' will be set to the
- exception type. The attribute 'match' will be None. This allows you to
- write code like this::
-
- index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
- if index == 0:
- do_something()
- elif index == 1:
- do_something_else()
- elif index == 2:
- do_some_other_thing()
- elif index == 3:
- do_something_completely_different()
-
- instead of code like this::
-
- try:
- index = p.expect(['good', 'bad'])
- if index == 0:
- do_something()
- elif index == 1:
- do_something_else()
- except EOF:
- do_some_other_thing()
- except TIMEOUT:
- do_something_completely_different()
-
- These two forms are equivalent. It all depends on what you want. You
- can also just expect the EOF if you are waiting for all output of a
- child to finish. For example::
-
- p = pexpect.spawn('/bin/ls')
- p.expect(pexpect.EOF)
- print p.before
-
- If you are trying to optimize for speed then see expect_list().
-
- On Python 3.4, or Python 3.3 with asyncio installed, passing
+
+ When a match is found for the given pattern, the class instance
+ attribute *match* becomes an re.MatchObject result. Should an EOF
+ or TIMEOUT pattern match, then the match attribute will be an instance
+ of that exception class. The pairing before and after class
+ instance attributes are views of the data preceding and following
+ the matching pattern. On general exception, class attribute
+ *before* is all data received up to the exception, while *match* and
+ *after* attributes are value None.
+
+ When the keyword argument timeout is -1 (default), then TIMEOUT will
+ raise after the default value specified by the class timeout
+ attribute. When None, TIMEOUT will not be raised and may block
+ indefinitely until match.
+
+ When the keyword argument searchwindowsize is -1 (default), then the
+ value specified by the class maxread attribute is used.
+
+ A list entry may be EOF or TIMEOUT instead of a string. This will
+ catch these exceptions and return the index of the list entry instead
+ of raising the exception. The attribute 'after' will be set to the
+ exception type. The attribute 'match' will be None. This allows you to
+ write code like this::
+
+ index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
+ if index == 0:
+ do_something()
+ elif index == 1:
+ do_something_else()
+ elif index == 2:
+ do_some_other_thing()
+ elif index == 3:
+ do_something_completely_different()
+
+ instead of code like this::
+
+ try:
+ index = p.expect(['good', 'bad'])
+ if index == 0:
+ do_something()
+ elif index == 1:
+ do_something_else()
+ except EOF:
+ do_some_other_thing()
+ except TIMEOUT:
+ do_something_completely_different()
+
+ These two forms are equivalent. It all depends on what you want. You
+ can also just expect the EOF if you are waiting for all output of a
+ child to finish. For example::
+
+ p = pexpect.spawn('/bin/ls')
+ p.expect(pexpect.EOF)
+ print p.before
+
+ If you are trying to optimize for speed then see expect_list().
+
+ On Python 3.4, or Python 3.3 with asyncio installed, passing
``async_=True`` will make this return an :mod:`asyncio` coroutine,
- which you can yield from to get the same result that this method would
- normally give directly. So, inside a coroutine, you can replace this code::
-
- index = p.expect(patterns)
-
- With this non-blocking form::
-
+ which you can yield from to get the same result that this method would
+ normally give directly. So, inside a coroutine, you can replace this code::
+
+ index = p.expect(patterns)
+
+ With this non-blocking form::
+
index = yield from p.expect(patterns, async_=True)
- '''
+ '''
if 'async' in kw:
async_ = kw.pop('async')
if kw:
raise TypeError("Unknown keyword arguments: {}".format(kw))
-
- compiled_pattern_list = self.compile_pattern_list(pattern)
- return self.expect_list(compiled_pattern_list,
+
+ compiled_pattern_list = self.compile_pattern_list(pattern)
+ return self.expect_list(compiled_pattern_list,
timeout, searchwindowsize, async_)
-
- def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1,
+
+ def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1,
async_=False, **kw):
- '''This takes a list of compiled regular expressions and returns the
- index into the pattern_list that matched the child output. The list may
- also contain EOF or TIMEOUT(which are not compiled regular
- expressions). This method is similar to the expect() method except that
- expect_list() does not recompile the pattern list on every call. This
- may help if you are trying to optimize for speed, otherwise just use
- the expect() method. This is called by expect().
-
-
+ '''This takes a list of compiled regular expressions and returns the
+ index into the pattern_list that matched the child output. The list may
+ also contain EOF or TIMEOUT(which are not compiled regular
+ expressions). This method is similar to the expect() method except that
+ expect_list() does not recompile the pattern list on every call. This
+ may help if you are trying to optimize for speed, otherwise just use
+ the expect() method. This is called by expect().
+
+
Like :meth:`expect`, passing ``async_=True`` will make this return an
- asyncio coroutine.
- '''
- if timeout == -1:
- timeout = self.timeout
+ asyncio coroutine.
+ '''
+ if timeout == -1:
+ timeout = self.timeout
if 'async' in kw:
async_ = kw.pop('async')
if kw:
raise TypeError("Unknown keyword arguments: {}".format(kw))
-
- exp = Expecter(self, searcher_re(pattern_list), searchwindowsize)
+
+ exp = Expecter(self, searcher_re(pattern_list), searchwindowsize)
if async_:
from ._async import expect_async
- return expect_async(exp, timeout)
- else:
- return exp.expect_loop(timeout)
-
- def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1,
+ return expect_async(exp, timeout)
+ else:
+ return exp.expect_loop(timeout)
+
+ def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1,
async_=False, **kw):
-
- '''This is similar to expect(), but uses plain string matching instead
- of compiled regular expressions in 'pattern_list'. The 'pattern_list'
- may be a string; a list or other sequence of strings; or TIMEOUT and
- EOF.
-
- This call might be faster than expect() for two reasons: string
- searching is faster than RE matching and it is possible to limit the
- search to just the end of the input buffer.
-
- This method is also useful when you don't want to have to worry about
- escaping regular expression characters that you want to match.
-
+
+ '''This is similar to expect(), but uses plain string matching instead
+ of compiled regular expressions in 'pattern_list'. The 'pattern_list'
+ may be a string; a list or other sequence of strings; or TIMEOUT and
+ EOF.
+
+ This call might be faster than expect() for two reasons: string
+ searching is faster than RE matching and it is possible to limit the
+ search to just the end of the input buffer.
+
+ This method is also useful when you don't want to have to worry about
+ escaping regular expression characters that you want to match.
+
Like :meth:`expect`, passing ``async_=True`` will make this return an
- asyncio coroutine.
- '''
- if timeout == -1:
- timeout = self.timeout
+ asyncio coroutine.
+ '''
+ if timeout == -1:
+ timeout = self.timeout
if 'async' in kw:
async_ = kw.pop('async')
if kw:
raise TypeError("Unknown keyword arguments: {}".format(kw))
-
- if (isinstance(pattern_list, self.allowed_string_types) or
- pattern_list in (TIMEOUT, EOF)):
- pattern_list = [pattern_list]
-
- def prepare_pattern(pattern):
- if pattern in (TIMEOUT, EOF):
- return pattern
- if isinstance(pattern, self.allowed_string_types):
- return self._coerce_expect_string(pattern)
- self._pattern_type_err(pattern)
-
- try:
- pattern_list = iter(pattern_list)
- except TypeError:
- self._pattern_type_err(pattern_list)
- pattern_list = [prepare_pattern(p) for p in pattern_list]
-
- exp = Expecter(self, searcher_string(pattern_list), searchwindowsize)
+
+ if (isinstance(pattern_list, self.allowed_string_types) or
+ pattern_list in (TIMEOUT, EOF)):
+ pattern_list = [pattern_list]
+
+ def prepare_pattern(pattern):
+ if pattern in (TIMEOUT, EOF):
+ return pattern
+ if isinstance(pattern, self.allowed_string_types):
+ return self._coerce_expect_string(pattern)
+ self._pattern_type_err(pattern)
+
+ try:
+ pattern_list = iter(pattern_list)
+ except TypeError:
+ self._pattern_type_err(pattern_list)
+ pattern_list = [prepare_pattern(p) for p in pattern_list]
+
+ exp = Expecter(self, searcher_string(pattern_list), searchwindowsize)
if async_:
from ._async import expect_async
- return expect_async(exp, timeout)
- else:
- return exp.expect_loop(timeout)
-
- def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1):
- '''This is the common loop used inside expect. The 'searcher' should be
- an instance of searcher_re or searcher_string, which describes how and
- what to search for in the input.
-
- See expect() for other arguments, return value and exceptions. '''
-
- exp = Expecter(self, searcher, searchwindowsize)
- return exp.expect_loop(timeout)
-
- def read(self, size=-1):
- '''This reads at most "size" bytes from the file (less if the read hits
- EOF before obtaining size bytes). If the size argument is negative or
- omitted, read all data until EOF is reached. The bytes are returned as
- a string object. An empty string is returned when EOF is encountered
- immediately. '''
-
- if size == 0:
- return self.string_type()
- if size < 0:
- # delimiter default is EOF
- self.expect(self.delimiter)
- return self.before
-
- # I could have done this more directly by not using expect(), but
- # I deliberately decided to couple read() to expect() so that
+ return expect_async(exp, timeout)
+ else:
+ return exp.expect_loop(timeout)
+
+ def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1):
+ '''This is the common loop used inside expect. The 'searcher' should be
+ an instance of searcher_re or searcher_string, which describes how and
+ what to search for in the input.
+
+ See expect() for other arguments, return value and exceptions. '''
+
+ exp = Expecter(self, searcher, searchwindowsize)
+ return exp.expect_loop(timeout)
+
+ def read(self, size=-1):
+ '''This reads at most "size" bytes from the file (less if the read hits
+ EOF before obtaining size bytes). If the size argument is negative or
+ omitted, read all data until EOF is reached. The bytes are returned as
+ a string object. An empty string is returned when EOF is encountered
+ immediately. '''
+
+ if size == 0:
+ return self.string_type()
+ if size < 0:
+ # delimiter default is EOF
+ self.expect(self.delimiter)
+ return self.before
+
+ # I could have done this more directly by not using expect(), but
+ # I deliberately decided to couple read() to expect() so that
# I would catch any bugs early and ensure consistent behavior.
- # It's a little less efficient, but there is less for me to
- # worry about if I have to later modify read() or expect().
- # Note, it's OK if size==-1 in the regex. That just means it
- # will never match anything in which case we stop only on EOF.
- cre = re.compile(self._coerce_expect_string('.{%d}' % size), re.DOTALL)
- # delimiter default is EOF
- index = self.expect([cre, self.delimiter])
- if index == 0:
- ### FIXME self.before should be ''. Should I assert this?
- return self.after
- return self.before
-
- def readline(self, size=-1):
- '''This reads and returns one entire line. The newline at the end of
- line is returned as part of the string, unless the file ends without a
- newline. An empty string is returned if EOF is encountered immediately.
- This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
- this is what the pseudotty device returns. So contrary to what you may
- expect you will receive newlines as \\r\\n.
-
- If the size argument is 0 then an empty string is returned. In all
- other cases the size argument is ignored, which is not standard
- behavior for a file-like object. '''
-
- if size == 0:
- return self.string_type()
- # delimiter default is EOF
- index = self.expect([self.crlf, self.delimiter])
- if index == 0:
- return self.before + self.crlf
- else:
- return self.before
-
- def __iter__(self):
- '''This is to support iterators over a file-like object.
- '''
- return iter(self.readline, self.string_type())
-
- def readlines(self, sizehint=-1):
- '''This reads until EOF using readline() and returns a list containing
- the lines thus read. The optional 'sizehint' argument is ignored.
- Remember, because this reads until EOF that means the child
- process should have closed its stdout. If you run this method on
- a child that is still running with its stdout open then this
- method will block until it timesout.'''
-
- lines = []
- while True:
- line = self.readline()
- if not line:
- break
- lines.append(line)
- return lines
-
- def fileno(self):
- '''Expose file descriptor for a file-like interface
- '''
- return self.child_fd
-
- def flush(self):
- '''This does nothing. It is here to support the interface for a
- File-like object. '''
- pass
-
- def isatty(self):
- """Overridden in subclass using tty"""
- return False
-
- # For 'with spawn(...) as child:'
- def __enter__(self):
- return self
-
- def __exit__(self, etype, evalue, tb):
- # We rely on subclasses to implement close(). If they don't, it's not
- # clear what a context manager should do.
- self.close()
+ # It's a little less efficient, but there is less for me to
+ # worry about if I have to later modify read() or expect().
+ # Note, it's OK if size==-1 in the regex. That just means it
+ # will never match anything in which case we stop only on EOF.
+ cre = re.compile(self._coerce_expect_string('.{%d}' % size), re.DOTALL)
+ # delimiter default is EOF
+ index = self.expect([cre, self.delimiter])
+ if index == 0:
+ ### FIXME self.before should be ''. Should I assert this?
+ return self.after
+ return self.before
+
+ def readline(self, size=-1):
+ '''This reads and returns one entire line. The newline at the end of
+ line is returned as part of the string, unless the file ends without a
+ newline. An empty string is returned if EOF is encountered immediately.
+ This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
+ this is what the pseudotty device returns. So contrary to what you may
+ expect you will receive newlines as \\r\\n.
+
+ If the size argument is 0 then an empty string is returned. In all
+ other cases the size argument is ignored, which is not standard
+ behavior for a file-like object. '''
+
+ if size == 0:
+ return self.string_type()
+ # delimiter default is EOF
+ index = self.expect([self.crlf, self.delimiter])
+ if index == 0:
+ return self.before + self.crlf
+ else:
+ return self.before
+
+ def __iter__(self):
+ '''This is to support iterators over a file-like object.
+ '''
+ return iter(self.readline, self.string_type())
+
+ def readlines(self, sizehint=-1):
+ '''This reads until EOF using readline() and returns a list containing
+ the lines thus read. The optional 'sizehint' argument is ignored.
+ Remember, because this reads until EOF that means the child
+ process should have closed its stdout. If you run this method on
+ a child that is still running with its stdout open then this
+ method will block until it timesout.'''
+
+ lines = []
+ while True:
+ line = self.readline()
+ if not line:
+ break
+ lines.append(line)
+ return lines
+
+ def fileno(self):
+ '''Expose file descriptor for a file-like interface
+ '''
+ return self.child_fd
+
+ def flush(self):
+ '''This does nothing. It is here to support the interface for a
+ File-like object. '''
+ pass
+
+ def isatty(self):
+ """Overridden in subclass using tty"""
+ return False
+
+ # For 'with spawn(...) as child:'
+ def __enter__(self):
+ return self
+
+ def __exit__(self, etype, evalue, tb):
+ # We rely on subclasses to implement close(). If they don't, it's not
+ # clear what a context manager should do.
+ self.close()
diff --git a/contrib/python/pexpect/pexpect/utils.py b/contrib/python/pexpect/pexpect/utils.py
index 13a7849a0e..f774519609 100644
--- a/contrib/python/pexpect/pexpect/utils.py
+++ b/contrib/python/pexpect/pexpect/utils.py
@@ -1,130 +1,130 @@
-import os
-import sys
-import stat
+import os
+import sys
+import stat
import select
import time
import errno
-
+
try:
InterruptedError
except NameError:
# Alias Python2 exception to Python3
InterruptedError = select.error
-
+
if sys.version_info[0] >= 3:
string_types = (str,)
else:
string_types = (unicode, str)
-def is_executable_file(path):
- """Checks that path is an executable regular file, or a symlink towards one.
-
- This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``.
- """
- # follow symlinks,
- fpath = os.path.realpath(path)
-
- if not os.path.isfile(fpath):
- # non-files (directories, fifo, etc.)
- return False
-
- mode = os.stat(fpath).st_mode
-
- if (sys.platform.startswith('sunos')
- and os.getuid() == 0):
- # When root on Solaris, os.X_OK is True for *all* files, irregardless
- # of their executability -- instead, any permission bit of any user,
- # group, or other is fine enough.
- #
- # (This may be true for other "Unix98" OS's such as HP-UX and AIX)
- return bool(mode & (stat.S_IXUSR |
- stat.S_IXGRP |
- stat.S_IXOTH))
-
- return os.access(fpath, os.X_OK)
-
-
+def is_executable_file(path):
+ """Checks that path is an executable regular file, or a symlink towards one.
+
+ This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``.
+ """
+ # follow symlinks,
+ fpath = os.path.realpath(path)
+
+ if not os.path.isfile(fpath):
+ # non-files (directories, fifo, etc.)
+ return False
+
+ mode = os.stat(fpath).st_mode
+
+ if (sys.platform.startswith('sunos')
+ and os.getuid() == 0):
+ # When root on Solaris, os.X_OK is True for *all* files, irregardless
+ # of their executability -- instead, any permission bit of any user,
+ # group, or other is fine enough.
+ #
+ # (This may be true for other "Unix98" OS's such as HP-UX and AIX)
+ return bool(mode & (stat.S_IXUSR |
+ stat.S_IXGRP |
+ stat.S_IXOTH))
+
+ return os.access(fpath, os.X_OK)
+
+
def which(filename, env=None):
- '''This takes a given filename; tries to find it in the environment path;
- then checks if it is executable. This returns the full path to the filename
- if found and executable. Otherwise this returns None.'''
-
- # Special case where filename contains an explicit path.
- if os.path.dirname(filename) != '' and is_executable_file(filename):
- return filename
+ '''This takes a given filename; tries to find it in the environment path;
+ then checks if it is executable. This returns the full path to the filename
+ if found and executable. Otherwise this returns None.'''
+
+ # Special case where filename contains an explicit path.
+ if os.path.dirname(filename) != '' and is_executable_file(filename):
+ return filename
if env is None:
env = os.environ
p = env.get('PATH')
if not p:
- p = os.defpath
- pathlist = p.split(os.pathsep)
- for path in pathlist:
- ff = os.path.join(path, filename)
- if is_executable_file(ff):
- return ff
- return None
-
-
-def split_command_line(command_line):
-
- '''This splits a command line into a list of arguments. It splits arguments
- on spaces, but handles embedded quotes, doublequotes, and escaped
- characters. It's impossible to do this with a regular expression, so I
- wrote a little state machine to parse the command line. '''
-
- arg_list = []
- arg = ''
-
- # Constants to name the states we can be in.
- state_basic = 0
- state_esc = 1
- state_singlequote = 2
- state_doublequote = 3
- # The state when consuming whitespace between commands.
- state_whitespace = 4
- state = state_basic
-
- for c in command_line:
- if state == state_basic or state == state_whitespace:
- if c == '\\':
- # Escape the next character
- state = state_esc
- elif c == r"'":
- # Handle single quote
- state = state_singlequote
- elif c == r'"':
- # Handle double quote
- state = state_doublequote
- elif c.isspace():
- # Add arg to arg_list if we aren't in the middle of whitespace.
- if state == state_whitespace:
- # Do nothing.
- None
- else:
- arg_list.append(arg)
- arg = ''
- state = state_whitespace
- else:
- arg = arg + c
- state = state_basic
- elif state == state_esc:
- arg = arg + c
- state = state_basic
- elif state == state_singlequote:
- if c == r"'":
- state = state_basic
- else:
- arg = arg + c
- elif state == state_doublequote:
- if c == r'"':
- state = state_basic
- else:
- arg = arg + c
-
- if arg != '':
- arg_list.append(arg)
- return arg_list
+ p = os.defpath
+ pathlist = p.split(os.pathsep)
+ for path in pathlist:
+ ff = os.path.join(path, filename)
+ if is_executable_file(ff):
+ return ff
+ return None
+
+
+def split_command_line(command_line):
+
+ '''This splits a command line into a list of arguments. It splits arguments
+ on spaces, but handles embedded quotes, doublequotes, and escaped
+ characters. It's impossible to do this with a regular expression, so I
+ wrote a little state machine to parse the command line. '''
+
+ arg_list = []
+ arg = ''
+
+ # Constants to name the states we can be in.
+ state_basic = 0
+ state_esc = 1
+ state_singlequote = 2
+ state_doublequote = 3
+ # The state when consuming whitespace between commands.
+ state_whitespace = 4
+ state = state_basic
+
+ for c in command_line:
+ if state == state_basic or state == state_whitespace:
+ if c == '\\':
+ # Escape the next character
+ state = state_esc
+ elif c == r"'":
+ # Handle single quote
+ state = state_singlequote
+ elif c == r'"':
+ # Handle double quote
+ state = state_doublequote
+ elif c.isspace():
+ # Add arg to arg_list if we aren't in the middle of whitespace.
+ if state == state_whitespace:
+ # Do nothing.
+ None
+ else:
+ arg_list.append(arg)
+ arg = ''
+ state = state_whitespace
+ else:
+ arg = arg + c
+ state = state_basic
+ elif state == state_esc:
+ arg = arg + c
+ state = state_basic
+ elif state == state_singlequote:
+ if c == r"'":
+ state = state_basic
+ else:
+ arg = arg + c
+ elif state == state_doublequote:
+ if c == r'"':
+ state = state_basic
+ else:
+ arg = arg + c
+
+ if arg != '':
+ arg_list.append(arg)
+ return arg_list
def select_ignore_interrupts(iwtd, owtd, ewtd, timeout=None):
diff --git a/contrib/python/pexpect/ya.make b/contrib/python/pexpect/ya.make
index 2fdba71fba..a5bb92fcac 100644
--- a/contrib/python/pexpect/ya.make
+++ b/contrib/python/pexpect/ya.make
@@ -1,35 +1,35 @@
PY23_LIBRARY()
-
+
LICENSE(ISC)
OWNER(g:python-contrib borman)
VERSION(4.8.0)
-PEERDIR(
+PEERDIR(
contrib/python/ptyprocess
-)
-
+)
+
NO_LINT()
-PY_SRCS(
- TOP_LEVEL
- pexpect/ANSI.py
- pexpect/FSM.py
- pexpect/__init__.py
- pexpect/exceptions.py
- pexpect/expect.py
- pexpect/fdpexpect.py
- pexpect/popen_spawn.py
- pexpect/pty_spawn.py
- pexpect/pxssh.py
- pexpect/replwrap.py
- pexpect/run.py
- pexpect/screen.py
- pexpect/spawnbase.py
- pexpect/utils.py
-)
-
+PY_SRCS(
+ TOP_LEVEL
+ pexpect/ANSI.py
+ pexpect/FSM.py
+ pexpect/__init__.py
+ pexpect/exceptions.py
+ pexpect/expect.py
+ pexpect/fdpexpect.py
+ pexpect/popen_spawn.py
+ pexpect/pty_spawn.py
+ pexpect/pxssh.py
+ pexpect/replwrap.py
+ pexpect/run.py
+ pexpect/screen.py
+ pexpect/spawnbase.py
+ pexpect/utils.py
+)
+
IF (PYTHON3)
PY_SRCS(
TOP_LEVEL
@@ -43,4 +43,4 @@ RESOURCE_FILES(
.dist-info/top_level.txt
)
-END()
+END()
diff --git a/contrib/python/pickleshare/pickleshare.py b/contrib/python/pickleshare/pickleshare.py
index c5145f3c95..086f84f6ea 100644
--- a/contrib/python/pickleshare/pickleshare.py
+++ b/contrib/python/pickleshare/pickleshare.py
@@ -1,75 +1,75 @@
-#!/usr/bin/env python
-
-""" PickleShare - a small 'shelve' like datastore with concurrency support
-
-Like shelve, a PickleShareDB object acts like a normal dictionary. Unlike
-shelve, many processes can access the database simultaneously. Changing a
-value in database is immediately visible to other processes accessing the
-same database.
-
-Concurrency is possible because the values are stored in separate files. Hence
-the "database" is a directory where *all* files are governed by PickleShare.
-
-Example usage::
-
- from pickleshare import *
- db = PickleShareDB('~/testpickleshare')
- db.clear()
- print "Should be empty:",db.items()
- db['hello'] = 15
- db['aku ankka'] = [1,2,313]
- db['paths/are/ok/key'] = [1,(5,46)]
- print db.keys()
- del db['aku ankka']
-
-This module is certainly not ZODB, but can be used for low-load
-(non-mission-critical) situations where tiny code size trumps the
-advanced features of a "real" object database.
-
+#!/usr/bin/env python
+
+""" PickleShare - a small 'shelve' like datastore with concurrency support
+
+Like shelve, a PickleShareDB object acts like a normal dictionary. Unlike
+shelve, many processes can access the database simultaneously. Changing a
+value in database is immediately visible to other processes accessing the
+same database.
+
+Concurrency is possible because the values are stored in separate files. Hence
+the "database" is a directory where *all* files are governed by PickleShare.
+
+Example usage::
+
+ from pickleshare import *
+ db = PickleShareDB('~/testpickleshare')
+ db.clear()
+ print "Should be empty:",db.items()
+ db['hello'] = 15
+ db['aku ankka'] = [1,2,313]
+ db['paths/are/ok/key'] = [1,(5,46)]
+ print db.keys()
+ del db['aku ankka']
+
+This module is certainly not ZODB, but can be used for low-load
+(non-mission-critical) situations where tiny code size trumps the
+advanced features of a "real" object database.
+
Installation guide: pip install pickleshare
-
-Author: Ville Vainio <vivainio@gmail.com>
-License: MIT open source license.
-
-"""
-
-from __future__ import print_function
-
-
+
+Author: Ville Vainio <vivainio@gmail.com>
+License: MIT open source license.
+
+"""
+
+from __future__ import print_function
+
+
__version__ = "0.7.5"
-
+
try:
from pathlib import Path
except ImportError:
# Python 2 backport
from pathlib2 import Path
-import os,stat,time
-try:
+import os,stat,time
+try:
import collections.abc as collections_abc
except ImportError:
import collections as collections_abc
try:
- import cPickle as pickle
-except ImportError:
- import pickle
-import errno
+ import cPickle as pickle
+except ImportError:
+ import pickle
+import errno
import sys
-
+
if sys.version_info[0] >= 3:
string_types = (str,)
else:
string_types = (str, unicode)
-def gethashfile(key):
- return ("%02x" % abs(hash(key) % 256))[-2:]
-
-_sentinel = object()
-
+def gethashfile(key):
+ return ("%02x" % abs(hash(key) % 256))[-2:]
+
+_sentinel = object()
+
class PickleShareDB(collections_abc.MutableMapping):
- """ The main 'connection' object for PickleShare database """
- def __init__(self,root):
- """ Return a db object that will manage the specied directory"""
+ """ The main 'connection' object for PickleShare database """
+ def __init__(self,root):
+ """ Return a db object that will manage the specied directory"""
if not isinstance(root, string_types):
root = str(root)
root = os.path.abspath(os.path.expanduser(root))
@@ -82,271 +82,271 @@ class PickleShareDB(collections_abc.MutableMapping):
except OSError as e:
if e.errno != errno.EEXIST:
raise
- # cache has { 'key' : (obj, orig_mod_time) }
- self.cache = {}
-
-
- def __getitem__(self,key):
- """ db['key'] reading """
- fil = self.root / key
- try:
- mtime = (fil.stat()[stat.ST_MTIME])
- except OSError:
- raise KeyError(key)
-
- if fil in self.cache and mtime == self.cache[fil][1]:
- return self.cache[fil][0]
- try:
- # The cached item has expired, need to read
- with fil.open("rb") as f:
- obj = pickle.loads(f.read())
- except:
- raise KeyError(key)
-
- self.cache[fil] = (obj,mtime)
- return obj
-
- def __setitem__(self,key,value):
- """ db['key'] = 5 """
- fil = self.root / key
- parent = fil.parent
+ # cache has { 'key' : (obj, orig_mod_time) }
+ self.cache = {}
+
+
+ def __getitem__(self,key):
+ """ db['key'] reading """
+ fil = self.root / key
+ try:
+ mtime = (fil.stat()[stat.ST_MTIME])
+ except OSError:
+ raise KeyError(key)
+
+ if fil in self.cache and mtime == self.cache[fil][1]:
+ return self.cache[fil][0]
+ try:
+ # The cached item has expired, need to read
+ with fil.open("rb") as f:
+ obj = pickle.loads(f.read())
+ except:
+ raise KeyError(key)
+
+ self.cache[fil] = (obj,mtime)
+ return obj
+
+ def __setitem__(self,key,value):
+ """ db['key'] = 5 """
+ fil = self.root / key
+ parent = fil.parent
if parent and not parent.is_dir():
parent.mkdir(parents=True)
- # We specify protocol 2, so that we can mostly go between Python 2
- # and Python 3. We can upgrade to protocol 3 when Python 2 is obsolete.
- with fil.open('wb') as f:
- pickle.dump(value, f, protocol=2)
- try:
+ # We specify protocol 2, so that we can mostly go between Python 2
+ # and Python 3. We can upgrade to protocol 3 when Python 2 is obsolete.
+ with fil.open('wb') as f:
+ pickle.dump(value, f, protocol=2)
+ try:
self.cache[fil] = (value, fil.stat().st_mtime)
- except OSError as e:
- if e.errno != errno.ENOENT:
- raise
-
- def hset(self, hashroot, key, value):
- """ hashed set """
- hroot = self.root / hashroot
+ except OSError as e:
+ if e.errno != errno.ENOENT:
+ raise
+
+ def hset(self, hashroot, key, value):
+ """ hashed set """
+ hroot = self.root / hashroot
if not hroot.is_dir():
hroot.mkdir()
- hfile = hroot / gethashfile(key)
- d = self.get(hfile, {})
- d.update( {key : value})
- self[hfile] = d
-
-
-
- def hget(self, hashroot, key, default = _sentinel, fast_only = True):
- """ hashed get """
- hroot = self.root / hashroot
- hfile = hroot / gethashfile(key)
-
- d = self.get(hfile, _sentinel )
- #print "got dict",d,"from",hfile
- if d is _sentinel:
- if fast_only:
- if default is _sentinel:
- raise KeyError(key)
-
- return default
-
- # slow mode ok, works even after hcompress()
- d = self.hdict(hashroot)
-
- return d.get(key, default)
-
- def hdict(self, hashroot):
- """ Get all data contained in hashed category 'hashroot' as dict """
- hfiles = self.keys(hashroot + "/*")
- hfiles.sort()
- last = len(hfiles) and hfiles[-1] or ''
- if last.endswith('xx'):
- # print "using xx"
- hfiles = [last] + hfiles[:-1]
-
- all = {}
-
- for f in hfiles:
- # print "using",f
- try:
- all.update(self[f])
- except KeyError:
- print("Corrupt",f,"deleted - hset is not threadsafe!")
- del self[f]
-
- self.uncache(f)
-
- return all
-
- def hcompress(self, hashroot):
- """ Compress category 'hashroot', so hset is fast again
-
- hget will fail if fast_only is True for compressed items (that were
- hset before hcompress).
-
- """
- hfiles = self.keys(hashroot + "/*")
- all = {}
- for f in hfiles:
- # print "using",f
- all.update(self[f])
- self.uncache(f)
-
- self[hashroot + '/xx'] = all
- for f in hfiles:
- p = self.root / f
+ hfile = hroot / gethashfile(key)
+ d = self.get(hfile, {})
+ d.update( {key : value})
+ self[hfile] = d
+
+
+
+ def hget(self, hashroot, key, default = _sentinel, fast_only = True):
+ """ hashed get """
+ hroot = self.root / hashroot
+ hfile = hroot / gethashfile(key)
+
+ d = self.get(hfile, _sentinel )
+ #print "got dict",d,"from",hfile
+ if d is _sentinel:
+ if fast_only:
+ if default is _sentinel:
+ raise KeyError(key)
+
+ return default
+
+ # slow mode ok, works even after hcompress()
+ d = self.hdict(hashroot)
+
+ return d.get(key, default)
+
+ def hdict(self, hashroot):
+ """ Get all data contained in hashed category 'hashroot' as dict """
+ hfiles = self.keys(hashroot + "/*")
+ hfiles.sort()
+ last = len(hfiles) and hfiles[-1] or ''
+ if last.endswith('xx'):
+ # print "using xx"
+ hfiles = [last] + hfiles[:-1]
+
+ all = {}
+
+ for f in hfiles:
+ # print "using",f
+ try:
+ all.update(self[f])
+ except KeyError:
+ print("Corrupt",f,"deleted - hset is not threadsafe!")
+ del self[f]
+
+ self.uncache(f)
+
+ return all
+
+ def hcompress(self, hashroot):
+ """ Compress category 'hashroot', so hset is fast again
+
+ hget will fail if fast_only is True for compressed items (that were
+ hset before hcompress).
+
+ """
+ hfiles = self.keys(hashroot + "/*")
+ all = {}
+ for f in hfiles:
+ # print "using",f
+ all.update(self[f])
+ self.uncache(f)
+
+ self[hashroot + '/xx'] = all
+ for f in hfiles:
+ p = self.root / f
if p.name == 'xx':
- continue
+ continue
p.unlink()
-
-
-
- def __delitem__(self,key):
- """ del db["key"] """
- fil = self.root / key
- self.cache.pop(fil,None)
- try:
+
+
+
+ def __delitem__(self,key):
+ """ del db["key"] """
+ fil = self.root / key
+ self.cache.pop(fil,None)
+ try:
fil.unlink()
- except OSError:
- # notfound and permission denied are ok - we
- # lost, the other process wins the conflict
- pass
-
- def _normalized(self, p):
- """ Make a key suitable for user's eyes """
+ except OSError:
+ # notfound and permission denied are ok - we
+ # lost, the other process wins the conflict
+ pass
+
+ def _normalized(self, p):
+ """ Make a key suitable for user's eyes """
return str(p.relative_to(self.root)).replace('\\','/')
-
- def keys(self, globpat = None):
- """ All keys in DB, or all keys matching a glob"""
-
- if globpat is None:
+
+ def keys(self, globpat = None):
+ """ All keys in DB, or all keys matching a glob"""
+
+ if globpat is None:
files = self.root.rglob('*')
- else:
+ else:
files = self.root.glob(globpat)
return [self._normalized(p) for p in files if p.is_file()]
-
- def __iter__(self):
- return iter(self.keys())
-
- def __len__(self):
- return len(self.keys())
-
- def uncache(self,*items):
- """ Removes all, or specified items from cache
-
- Use this after reading a large amount of large objects
- to free up memory, when you won't be needing the objects
- for a while.
-
- """
- if not items:
- self.cache = {}
- for it in items:
- self.cache.pop(it,None)
-
- def waitget(self,key, maxwaittime = 60 ):
- """ Wait (poll) for a key to get a value
-
- Will wait for `maxwaittime` seconds before raising a KeyError.
- The call exits normally if the `key` field in db gets a value
- within the timeout period.
-
- Use this for synchronizing different processes or for ensuring
- that an unfortunately timed "db['key'] = newvalue" operation
- in another process (which causes all 'get' operation to cause a
- KeyError for the duration of pickling) won't screw up your program
- logic.
- """
-
- wtimes = [0.2] * 3 + [0.5] * 2 + [1]
- tries = 0
- waited = 0
- while 1:
- try:
- val = self[key]
- return val
- except KeyError:
- pass
-
- if waited > maxwaittime:
- raise KeyError(key)
-
- time.sleep(wtimes[tries])
- waited+=wtimes[tries]
- if tries < len(wtimes) -1:
- tries+=1
-
- def getlink(self,folder):
- """ Get a convenient link for accessing items """
- return PickleShareLink(self, folder)
-
- def __repr__(self):
- return "PickleShareDB('%s')" % self.root
-
-
-
-class PickleShareLink:
- """ A shortdand for accessing nested PickleShare data conveniently.
-
- Created through PickleShareDB.getlink(), example::
-
- lnk = db.getlink('myobjects/test')
- lnk.foo = 2
- lnk.bar = lnk.foo + 5
-
- """
- def __init__(self, db, keydir ):
- self.__dict__.update(locals())
-
- def __getattr__(self,key):
- return self.__dict__['db'][self.__dict__['keydir']+'/' + key]
- def __setattr__(self,key,val):
- self.db[self.keydir+'/' + key] = val
- def __repr__(self):
- db = self.__dict__['db']
- keys = db.keys( self.__dict__['keydir'] +"/*")
- return "<PickleShareLink '%s': %s>" % (
- self.__dict__['keydir'],
- ";".join([Path(k).basename() for k in keys]))
-
-def main():
- import textwrap
- usage = textwrap.dedent("""\
- pickleshare - manage PickleShare databases
-
- Usage:
-
- pickleshare dump /path/to/db > dump.txt
- pickleshare load /path/to/db < dump.txt
- pickleshare test /path/to/db
- """)
- DB = PickleShareDB
- import sys
- if len(sys.argv) < 2:
- print(usage)
- return
-
- cmd = sys.argv[1]
- args = sys.argv[2:]
- if cmd == 'dump':
- if not args: args= ['.']
- db = DB(args[0])
- import pprint
- pprint.pprint(db.items())
- elif cmd == 'load':
- cont = sys.stdin.read()
- db = DB(args[0])
- data = eval(cont)
- db.clear()
- for k,v in db.items():
- db[k] = v
- elif cmd == 'testwait':
- db = DB(args[0])
- db.clear()
- print(db.waitget('250'))
- elif cmd == 'test':
- test()
- stress()
-
-if __name__== "__main__":
- main()
-
-
+
+ def __iter__(self):
+ return iter(self.keys())
+
+ def __len__(self):
+ return len(self.keys())
+
+ def uncache(self,*items):
+ """ Removes all, or specified items from cache
+
+ Use this after reading a large amount of large objects
+ to free up memory, when you won't be needing the objects
+ for a while.
+
+ """
+ if not items:
+ self.cache = {}
+ for it in items:
+ self.cache.pop(it,None)
+
+ def waitget(self,key, maxwaittime = 60 ):
+ """ Wait (poll) for a key to get a value
+
+ Will wait for `maxwaittime` seconds before raising a KeyError.
+ The call exits normally if the `key` field in db gets a value
+ within the timeout period.
+
+ Use this for synchronizing different processes or for ensuring
+ that an unfortunately timed "db['key'] = newvalue" operation
+ in another process (which causes all 'get' operation to cause a
+ KeyError for the duration of pickling) won't screw up your program
+ logic.
+ """
+
+ wtimes = [0.2] * 3 + [0.5] * 2 + [1]
+ tries = 0
+ waited = 0
+ while 1:
+ try:
+ val = self[key]
+ return val
+ except KeyError:
+ pass
+
+ if waited > maxwaittime:
+ raise KeyError(key)
+
+ time.sleep(wtimes[tries])
+ waited+=wtimes[tries]
+ if tries < len(wtimes) -1:
+ tries+=1
+
+ def getlink(self,folder):
+ """ Get a convenient link for accessing items """
+ return PickleShareLink(self, folder)
+
+ def __repr__(self):
+ return "PickleShareDB('%s')" % self.root
+
+
+
+class PickleShareLink:
+ """ A shortdand for accessing nested PickleShare data conveniently.
+
+ Created through PickleShareDB.getlink(), example::
+
+ lnk = db.getlink('myobjects/test')
+ lnk.foo = 2
+ lnk.bar = lnk.foo + 5
+
+ """
+ def __init__(self, db, keydir ):
+ self.__dict__.update(locals())
+
+ def __getattr__(self,key):
+ return self.__dict__['db'][self.__dict__['keydir']+'/' + key]
+ def __setattr__(self,key,val):
+ self.db[self.keydir+'/' + key] = val
+ def __repr__(self):
+ db = self.__dict__['db']
+ keys = db.keys( self.__dict__['keydir'] +"/*")
+ return "<PickleShareLink '%s': %s>" % (
+ self.__dict__['keydir'],
+ ";".join([Path(k).basename() for k in keys]))
+
+def main():
+ import textwrap
+ usage = textwrap.dedent("""\
+ pickleshare - manage PickleShare databases
+
+ Usage:
+
+ pickleshare dump /path/to/db > dump.txt
+ pickleshare load /path/to/db < dump.txt
+ pickleshare test /path/to/db
+ """)
+ DB = PickleShareDB
+ import sys
+ if len(sys.argv) < 2:
+ print(usage)
+ return
+
+ cmd = sys.argv[1]
+ args = sys.argv[2:]
+ if cmd == 'dump':
+ if not args: args= ['.']
+ db = DB(args[0])
+ import pprint
+ pprint.pprint(db.items())
+ elif cmd == 'load':
+ cont = sys.stdin.read()
+ db = DB(args[0])
+ data = eval(cont)
+ db.clear()
+ for k,v in db.items():
+ db[k] = v
+ elif cmd == 'testwait':
+ db = DB(args[0])
+ db.clear()
+ print(db.waitget('250'))
+ elif cmd == 'test':
+ test()
+ stress()
+
+if __name__== "__main__":
+ main()
+
+
diff --git a/contrib/python/pickleshare/ya.make b/contrib/python/pickleshare/ya.make
index 73437edb09..e24c2cdad7 100644
--- a/contrib/python/pickleshare/ya.make
+++ b/contrib/python/pickleshare/ya.make
@@ -1,5 +1,5 @@
# Generated by devtools/yamaker (pypi).
-
+
PY23_LIBRARY()
OWNER(borman g:python-contrib)
@@ -7,7 +7,7 @@ OWNER(borman g:python-contrib)
VERSION(0.7.5)
LICENSE(MIT)
-
+
IF (PYTHON2)
PEERDIR(
contrib/python/pathlib2
@@ -16,15 +16,15 @@ ENDIF()
NO_LINT()
-PY_SRCS(
- TOP_LEVEL
- pickleshare.py
-)
-
+PY_SRCS(
+ TOP_LEVEL
+ pickleshare.py
+)
+
RESOURCE_FILES(
PREFIX contrib/python/pickleshare/
.dist-info/METADATA
.dist-info/top_level.txt
)
-END()
+END()
diff --git a/contrib/python/prompt-toolkit/py2/ya.make b/contrib/python/prompt-toolkit/py2/ya.make
index 10a9424492..db22aa0a70 100644
--- a/contrib/python/prompt-toolkit/py2/ya.make
+++ b/contrib/python/prompt-toolkit/py2/ya.make
@@ -6,11 +6,11 @@ VERSION(1.0.18)
LICENSE(BSD-3-Clause)
-PEERDIR(
+PEERDIR(
contrib/python/six
contrib/python/wcwidth
-)
-
+)
+
NO_LINT()
NO_CHECK_IMPORTS(
diff --git a/contrib/python/prompt-toolkit/ya.make b/contrib/python/prompt-toolkit/ya.make
index bf12940159..f1f936eb3f 100644
--- a/contrib/python/prompt-toolkit/ya.make
+++ b/contrib/python/prompt-toolkit/ya.make
@@ -9,7 +9,7 @@ IF (PYTHON2)
ELSE()
PEERDIR(contrib/python/prompt-toolkit/py3)
ENDIF()
-
+
NO_LINT()
END()
diff --git a/contrib/python/ptyprocess/ptyprocess/__init__.py b/contrib/python/ptyprocess/ptyprocess/__init__.py
index 4dd4f630c5..3a6268e8a6 100644
--- a/contrib/python/ptyprocess/ptyprocess/__init__.py
+++ b/contrib/python/ptyprocess/ptyprocess/__init__.py
@@ -1,4 +1,4 @@
"""Run a subprocess in a pseudo terminal"""
-from .ptyprocess import PtyProcess, PtyProcessUnicode, PtyProcessError
-
+from .ptyprocess import PtyProcess, PtyProcessUnicode, PtyProcessError
+
__version__ = '0.7.0'
diff --git a/contrib/python/ptyprocess/ptyprocess/_fork_pty.py b/contrib/python/ptyprocess/ptyprocess/_fork_pty.py
index 151e097c40..a8d05fe5a3 100644
--- a/contrib/python/ptyprocess/ptyprocess/_fork_pty.py
+++ b/contrib/python/ptyprocess/ptyprocess/_fork_pty.py
@@ -1,78 +1,78 @@
-"""Substitute for the forkpty system call, to support Solaris.
-"""
-import os
-import errno
-
-from pty import (STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO, CHILD)
+"""Substitute for the forkpty system call, to support Solaris.
+"""
+import os
+import errno
+
+from pty import (STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO, CHILD)
from .util import PtyProcessError
-
-def fork_pty():
- '''This implements a substitute for the forkpty system call. This
- should be more portable than the pty.fork() function. Specifically,
- this should work on Solaris.
-
- Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
- resolve the issue with Python's pty.fork() not supporting Solaris,
- particularly ssh. Based on patch to posixmodule.c authored by Noah
- Spurrier::
-
- http://mail.python.org/pipermail/python-dev/2003-May/035281.html
-
- '''
-
- parent_fd, child_fd = os.openpty()
- if parent_fd < 0 or child_fd < 0:
- raise OSError("os.openpty() failed")
-
- pid = os.fork()
- if pid == CHILD:
- # Child.
- os.close(parent_fd)
- pty_make_controlling_tty(child_fd)
-
- os.dup2(child_fd, STDIN_FILENO)
- os.dup2(child_fd, STDOUT_FILENO)
- os.dup2(child_fd, STDERR_FILENO)
-
- else:
- # Parent.
- os.close(child_fd)
-
- return pid, parent_fd
-
-def pty_make_controlling_tty(tty_fd):
- '''This makes the pseudo-terminal the controlling tty. This should be
- more portable than the pty.fork() function. Specifically, this should
- work on Solaris. '''
-
- child_name = os.ttyname(tty_fd)
-
- # Disconnect from controlling tty, if any. Raises OSError of ENXIO
- # if there was no controlling tty to begin with, such as when
- # executed by a cron(1) job.
- try:
- fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
- os.close(fd)
- except OSError as err:
- if err.errno != errno.ENXIO:
- raise
-
- os.setsid()
-
- # Verify we are disconnected from controlling tty by attempting to open
- # it again. We expect that OSError of ENXIO should always be raised.
- try:
- fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
- os.close(fd)
+
+def fork_pty():
+ '''This implements a substitute for the forkpty system call. This
+ should be more portable than the pty.fork() function. Specifically,
+ this should work on Solaris.
+
+ Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
+ resolve the issue with Python's pty.fork() not supporting Solaris,
+ particularly ssh. Based on patch to posixmodule.c authored by Noah
+ Spurrier::
+
+ http://mail.python.org/pipermail/python-dev/2003-May/035281.html
+
+ '''
+
+ parent_fd, child_fd = os.openpty()
+ if parent_fd < 0 or child_fd < 0:
+ raise OSError("os.openpty() failed")
+
+ pid = os.fork()
+ if pid == CHILD:
+ # Child.
+ os.close(parent_fd)
+ pty_make_controlling_tty(child_fd)
+
+ os.dup2(child_fd, STDIN_FILENO)
+ os.dup2(child_fd, STDOUT_FILENO)
+ os.dup2(child_fd, STDERR_FILENO)
+
+ else:
+ # Parent.
+ os.close(child_fd)
+
+ return pid, parent_fd
+
+def pty_make_controlling_tty(tty_fd):
+ '''This makes the pseudo-terminal the controlling tty. This should be
+ more portable than the pty.fork() function. Specifically, this should
+ work on Solaris. '''
+
+ child_name = os.ttyname(tty_fd)
+
+ # Disconnect from controlling tty, if any. Raises OSError of ENXIO
+ # if there was no controlling tty to begin with, such as when
+ # executed by a cron(1) job.
+ try:
+ fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
+ os.close(fd)
+ except OSError as err:
+ if err.errno != errno.ENXIO:
+ raise
+
+ os.setsid()
+
+ # Verify we are disconnected from controlling tty by attempting to open
+ # it again. We expect that OSError of ENXIO should always be raised.
+ try:
+ fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
+ os.close(fd)
raise PtyProcessError("OSError of errno.ENXIO should be raised.")
- except OSError as err:
- if err.errno != errno.ENXIO:
- raise
-
- # Verify we can open child pty.
- fd = os.open(child_name, os.O_RDWR)
- os.close(fd)
-
- # Verify we now have a controlling tty.
- fd = os.open("/dev/tty", os.O_WRONLY)
+ except OSError as err:
+ if err.errno != errno.ENXIO:
+ raise
+
+ # Verify we can open child pty.
+ fd = os.open(child_name, os.O_RDWR)
+ os.close(fd)
+
+ # Verify we now have a controlling tty.
+ fd = os.open("/dev/tty", os.O_WRONLY)
os.close(fd)
diff --git a/contrib/python/ptyprocess/ptyprocess/ptyprocess.py b/contrib/python/ptyprocess/ptyprocess/ptyprocess.py
index ede9ec8e3b..78d19fdf8f 100644
--- a/contrib/python/ptyprocess/ptyprocess/ptyprocess.py
+++ b/contrib/python/ptyprocess/ptyprocess/ptyprocess.py
@@ -1,65 +1,65 @@
-import codecs
-import errno
-import fcntl
-import io
-import os
-import pty
-import resource
-import signal
-import struct
-import sys
-import termios
-import time
-
-try:
- import builtins # Python 3
-except ImportError:
- import __builtin__ as builtins # Python 2
-
-# Constants
-from pty import (STDIN_FILENO, CHILD)
-
+import codecs
+import errno
+import fcntl
+import io
+import os
+import pty
+import resource
+import signal
+import struct
+import sys
+import termios
+import time
+
+try:
+ import builtins # Python 3
+except ImportError:
+ import __builtin__ as builtins # Python 2
+
+# Constants
+from pty import (STDIN_FILENO, CHILD)
+
from .util import which, PtyProcessError
-
-_platform = sys.platform.lower()
-
-# Solaris uses internal __fork_pty(). All others use pty.fork().
-_is_solaris = (
- _platform.startswith('solaris') or
- _platform.startswith('sunos'))
-
-if _is_solaris:
- use_native_pty_fork = False
- from . import _fork_pty
-else:
- use_native_pty_fork = True
-
-PY3 = sys.version_info[0] >= 3
-
-if PY3:
- def _byte(i):
- return bytes([i])
-else:
- def _byte(i):
- return chr(i)
-
- class FileNotFoundError(OSError): pass
- class TimeoutError(OSError): pass
-
-_EOF, _INTR = None, None
-
-def _make_eof_intr():
- """Set constants _EOF and _INTR.
-
- This avoids doing potentially costly operations on module load.
- """
- global _EOF, _INTR
- if (_EOF is not None) and (_INTR is not None):
+
+_platform = sys.platform.lower()
+
+# Solaris uses internal __fork_pty(). All others use pty.fork().
+_is_solaris = (
+ _platform.startswith('solaris') or
+ _platform.startswith('sunos'))
+
+if _is_solaris:
+ use_native_pty_fork = False
+ from . import _fork_pty
+else:
+ use_native_pty_fork = True
+
+PY3 = sys.version_info[0] >= 3
+
+if PY3:
+ def _byte(i):
+ return bytes([i])
+else:
+ def _byte(i):
+ return chr(i)
+
+ class FileNotFoundError(OSError): pass
+ class TimeoutError(OSError): pass
+
+_EOF, _INTR = None, None
+
+def _make_eof_intr():
+ """Set constants _EOF and _INTR.
+
+ This avoids doing potentially costly operations on module load.
+ """
+ global _EOF, _INTR
+ if (_EOF is not None) and (_INTR is not None):
return
-
- # inherit EOF and INTR definitions from controlling process.
- try:
- from termios import VEOF, VINTR
+
+ # inherit EOF and INTR definitions from controlling process.
+ try:
+ from termios import VEOF, VINTR
fd = None
for name in 'stdin', 'stdout':
stream = getattr(sys, '__%s__' % name, None)
@@ -72,193 +72,193 @@ def _make_eof_intr():
if fd is None:
# no fd, raise ValueError to fallback on CEOF, CINTR
raise ValueError("No stream has a fileno")
- intr = ord(termios.tcgetattr(fd)[6][VINTR])
- eof = ord(termios.tcgetattr(fd)[6][VEOF])
- except (ImportError, OSError, IOError, ValueError, termios.error):
- # unless the controlling process is also not a terminal,
- # such as cron(1), or when stdin and stdout are both closed.
- # Fall-back to using CEOF and CINTR. There
- try:
- from termios import CEOF, CINTR
- (intr, eof) = (CINTR, CEOF)
- except ImportError:
- # ^C, ^D
- (intr, eof) = (3, 4)
-
- _INTR = _byte(intr)
- _EOF = _byte(eof)
-
-# setecho and setwinsize are pulled out here because on some platforms, we need
-# to do this from the child before we exec()
-
-def _setecho(fd, state):
+ intr = ord(termios.tcgetattr(fd)[6][VINTR])
+ eof = ord(termios.tcgetattr(fd)[6][VEOF])
+ except (ImportError, OSError, IOError, ValueError, termios.error):
+ # unless the controlling process is also not a terminal,
+ # such as cron(1), or when stdin and stdout are both closed.
+ # Fall-back to using CEOF and CINTR. There
+ try:
+ from termios import CEOF, CINTR
+ (intr, eof) = (CINTR, CEOF)
+ except ImportError:
+ # ^C, ^D
+ (intr, eof) = (3, 4)
+
+ _INTR = _byte(intr)
+ _EOF = _byte(eof)
+
+# setecho and setwinsize are pulled out here because on some platforms, we need
+# to do this from the child before we exec()
+
+def _setecho(fd, state):
errmsg = 'setecho() may not be called on this platform (it may still be possible to enable/disable echo when spawning the child process)'
-
- try:
- attr = termios.tcgetattr(fd)
- except termios.error as err:
- if err.args[0] == errno.EINVAL:
- raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
- raise
-
- if state:
- attr[3] = attr[3] | termios.ECHO
- else:
- attr[3] = attr[3] & ~termios.ECHO
-
- try:
- # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent and
- # blocked on some platforms. TCSADRAIN would probably be ideal.
- termios.tcsetattr(fd, termios.TCSANOW, attr)
- except IOError as err:
- if err.args[0] == errno.EINVAL:
- raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
- raise
-
-def _setwinsize(fd, rows, cols):
- # Some very old platforms have a bug that causes the value for
- # termios.TIOCSWINSZ to be truncated. There was a hack here to work
- # around this, but it caused problems with newer platforms so has been
- # removed. For details see https://github.com/pexpect/pexpect/issues/39
- TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
- # Note, assume ws_xpixel and ws_ypixel are zero.
- s = struct.pack('HHHH', rows, cols, 0, 0)
- fcntl.ioctl(fd, TIOCSWINSZ, s)
-
-class PtyProcess(object):
- '''This class represents a process running in a pseudoterminal.
-
- The main constructor is the :meth:`spawn` classmethod.
- '''
- string_type = bytes
- if PY3:
- linesep = os.linesep.encode('ascii')
- crlf = '\r\n'.encode('ascii')
-
- @staticmethod
- def write_to_stdout(b):
- try:
- return sys.stdout.buffer.write(b)
- except AttributeError:
- # If stdout has been replaced, it may not have .buffer
- return sys.stdout.write(b.decode('ascii', 'replace'))
- else:
- linesep = os.linesep
- crlf = '\r\n'
- write_to_stdout = sys.stdout.write
-
- encoding = None
-
- argv = None
- env = None
- launch_dir = None
-
- def __init__(self, pid, fd):
- _make_eof_intr() # Ensure _EOF and _INTR are calculated
- self.pid = pid
- self.fd = fd
+
+ try:
+ attr = termios.tcgetattr(fd)
+ except termios.error as err:
+ if err.args[0] == errno.EINVAL:
+ raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
+ raise
+
+ if state:
+ attr[3] = attr[3] | termios.ECHO
+ else:
+ attr[3] = attr[3] & ~termios.ECHO
+
+ try:
+ # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent and
+ # blocked on some platforms. TCSADRAIN would probably be ideal.
+ termios.tcsetattr(fd, termios.TCSANOW, attr)
+ except IOError as err:
+ if err.args[0] == errno.EINVAL:
+ raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
+ raise
+
+def _setwinsize(fd, rows, cols):
+ # Some very old platforms have a bug that causes the value for
+ # termios.TIOCSWINSZ to be truncated. There was a hack here to work
+ # around this, but it caused problems with newer platforms so has been
+ # removed. For details see https://github.com/pexpect/pexpect/issues/39
+ TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
+ # Note, assume ws_xpixel and ws_ypixel are zero.
+ s = struct.pack('HHHH', rows, cols, 0, 0)
+ fcntl.ioctl(fd, TIOCSWINSZ, s)
+
+class PtyProcess(object):
+ '''This class represents a process running in a pseudoterminal.
+
+ The main constructor is the :meth:`spawn` classmethod.
+ '''
+ string_type = bytes
+ if PY3:
+ linesep = os.linesep.encode('ascii')
+ crlf = '\r\n'.encode('ascii')
+
+ @staticmethod
+ def write_to_stdout(b):
+ try:
+ return sys.stdout.buffer.write(b)
+ except AttributeError:
+ # If stdout has been replaced, it may not have .buffer
+ return sys.stdout.write(b.decode('ascii', 'replace'))
+ else:
+ linesep = os.linesep
+ crlf = '\r\n'
+ write_to_stdout = sys.stdout.write
+
+ encoding = None
+
+ argv = None
+ env = None
+ launch_dir = None
+
+ def __init__(self, pid, fd):
+ _make_eof_intr() # Ensure _EOF and _INTR are calculated
+ self.pid = pid
+ self.fd = fd
readf = io.open(fd, 'rb', buffering=0)
writef = io.open(fd, 'wb', buffering=0, closefd=False)
self.fileobj = io.BufferedRWPair(readf, writef)
-
- self.terminated = False
- self.closed = False
- self.exitstatus = None
- self.signalstatus = None
- # status returned by os.waitpid
- self.status = None
- self.flag_eof = False
- # Used by close() to give kernel time to update process status.
- # Time in seconds.
- self.delayafterclose = 0.1
- # Used by terminate() to give kernel time to update process status.
- # Time in seconds.
- self.delayafterterminate = 0.1
-
- @classmethod
- def spawn(
- cls, argv, cwd=None, env=None, echo=True, preexec_fn=None,
+
+ self.terminated = False
+ self.closed = False
+ self.exitstatus = None
+ self.signalstatus = None
+ # status returned by os.waitpid
+ self.status = None
+ self.flag_eof = False
+ # Used by close() to give kernel time to update process status.
+ # Time in seconds.
+ self.delayafterclose = 0.1
+ # Used by terminate() to give kernel time to update process status.
+ # Time in seconds.
+ self.delayafterterminate = 0.1
+
+ @classmethod
+ def spawn(
+ cls, argv, cwd=None, env=None, echo=True, preexec_fn=None,
dimensions=(24, 80), pass_fds=()):
- '''Start the given command in a child process in a pseudo terminal.
-
- This does all the fork/exec type of stuff for a pty, and returns an
- instance of PtyProcess.
-
- If preexec_fn is supplied, it will be called with no arguments in the
- child process before exec-ing the specified command.
- It may, for instance, set signal handlers to SIG_DFL or SIG_IGN.
-
- Dimensions of the psuedoterminal used for the subprocess can be
- specified as a tuple (rows, cols), or the default (24, 80) will be used.
+ '''Start the given command in a child process in a pseudo terminal.
+
+ This does all the fork/exec type of stuff for a pty, and returns an
+ instance of PtyProcess.
+
+ If preexec_fn is supplied, it will be called with no arguments in the
+ child process before exec-ing the specified command.
+ It may, for instance, set signal handlers to SIG_DFL or SIG_IGN.
+
+ Dimensions of the psuedoterminal used for the subprocess can be
+ specified as a tuple (rows, cols), or the default (24, 80) will be used.
By default, all file descriptors except 0, 1 and 2 are closed. This
behavior can be overridden with pass_fds, a list of file descriptors to
keep open between the parent and the child.
- '''
- # Note that it is difficult for this method to fail.
- # You cannot detect if the child process cannot start.
- # So the only way you can tell if the child process started
- # or not is to try to read from the file descriptor. If you get
- # EOF immediately then it means that the child is already dead.
- # That may not necessarily be bad because you may have spawned a child
- # that performs some task; creates no stdout output; and then dies.
-
- if not isinstance(argv, (list, tuple)):
- raise TypeError("Expected a list or tuple for argv, got %r" % argv)
-
- # Shallow copy of argv so we can modify it
- argv = argv[:]
- command = argv[0]
-
- command_with_path = which(command)
- if command_with_path is None:
- raise FileNotFoundError('The command was not found or was not ' +
- 'executable: %s.' % command)
- command = command_with_path
- argv[0] = command
-
- # [issue #119] To prevent the case where exec fails and the user is
- # stuck interacting with a python child process instead of whatever
- # was expected, we implement the solution from
- # http://stackoverflow.com/a/3703179 to pass the exception to the
- # parent process
-
- # [issue #119] 1. Before forking, open a pipe in the parent process.
- exec_err_pipe_read, exec_err_pipe_write = os.pipe()
-
- if use_native_pty_fork:
- pid, fd = pty.fork()
- else:
- # Use internal fork_pty, for Solaris
- pid, fd = _fork_pty.fork_pty()
-
- # Some platforms must call setwinsize() and setecho() from the
- # child process, and others from the master process. We do both,
- # allowing IOError for either.
-
- if pid == CHILD:
- # set window size
- try:
- _setwinsize(STDIN_FILENO, *dimensions)
- except IOError as err:
- if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
- raise
-
- # disable echo if spawn argument echo was unset
- if not echo:
- try:
- _setecho(STDIN_FILENO, False)
- except (IOError, termios.error) as err:
- if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
- raise
-
- # [issue #119] 3. The child closes the reading end and sets the
- # close-on-exec flag for the writing end.
- os.close(exec_err_pipe_read)
- fcntl.fcntl(exec_err_pipe_write, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
-
- # Do not allow child to inherit open file descriptors from parent,
- # with the exception of the exec_err_pipe_write of the pipe
+ '''
+ # Note that it is difficult for this method to fail.
+ # You cannot detect if the child process cannot start.
+ # So the only way you can tell if the child process started
+ # or not is to try to read from the file descriptor. If you get
+ # EOF immediately then it means that the child is already dead.
+ # That may not necessarily be bad because you may have spawned a child
+ # that performs some task; creates no stdout output; and then dies.
+
+ if not isinstance(argv, (list, tuple)):
+ raise TypeError("Expected a list or tuple for argv, got %r" % argv)
+
+ # Shallow copy of argv so we can modify it
+ argv = argv[:]
+ command = argv[0]
+
+ command_with_path = which(command)
+ if command_with_path is None:
+ raise FileNotFoundError('The command was not found or was not ' +
+ 'executable: %s.' % command)
+ command = command_with_path
+ argv[0] = command
+
+ # [issue #119] To prevent the case where exec fails and the user is
+ # stuck interacting with a python child process instead of whatever
+ # was expected, we implement the solution from
+ # http://stackoverflow.com/a/3703179 to pass the exception to the
+ # parent process
+
+ # [issue #119] 1. Before forking, open a pipe in the parent process.
+ exec_err_pipe_read, exec_err_pipe_write = os.pipe()
+
+ if use_native_pty_fork:
+ pid, fd = pty.fork()
+ else:
+ # Use internal fork_pty, for Solaris
+ pid, fd = _fork_pty.fork_pty()
+
+ # Some platforms must call setwinsize() and setecho() from the
+ # child process, and others from the master process. We do both,
+ # allowing IOError for either.
+
+ if pid == CHILD:
+ # set window size
+ try:
+ _setwinsize(STDIN_FILENO, *dimensions)
+ except IOError as err:
+ if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
+ raise
+
+ # disable echo if spawn argument echo was unset
+ if not echo:
+ try:
+ _setecho(STDIN_FILENO, False)
+ except (IOError, termios.error) as err:
+ if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
+ raise
+
+ # [issue #119] 3. The child closes the reading end and sets the
+ # close-on-exec flag for the writing end.
+ os.close(exec_err_pipe_read)
+ fcntl.fcntl(exec_err_pipe_write, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
+
+ # Do not allow child to inherit open file descriptors from parent,
+ # with the exception of the exec_err_pipe_write of the pipe
# and pass_fds.
# Impose ceiling on max_fd: AIX bugfix for users with unlimited
# nofiles where resource.RLIMIT_NOFILE is 2^63-1 and os.closerange()
@@ -267,293 +267,293 @@ class PtyProcess(object):
spass_fds = sorted(set(pass_fds) | {exec_err_pipe_write})
for pair in zip([2] + spass_fds, spass_fds + [max_fd]):
os.closerange(pair[0]+1, pair[1])
-
- if cwd is not None:
- os.chdir(cwd)
-
- if preexec_fn is not None:
- try:
- preexec_fn()
- except Exception as e:
- ename = type(e).__name__
- tosend = '{}:0:{}'.format(ename, str(e))
- if PY3:
- tosend = tosend.encode('utf-8')
-
- os.write(exec_err_pipe_write, tosend)
- os.close(exec_err_pipe_write)
- os._exit(1)
-
- try:
- if env is None:
- os.execv(command, argv)
- else:
- os.execvpe(command, argv, env)
- except OSError as err:
- # [issue #119] 5. If exec fails, the child writes the error
- # code back to the parent using the pipe, then exits.
- tosend = 'OSError:{}:{}'.format(err.errno, str(err))
- if PY3:
- tosend = tosend.encode('utf-8')
- os.write(exec_err_pipe_write, tosend)
- os.close(exec_err_pipe_write)
- os._exit(os.EX_OSERR)
-
- # Parent
- inst = cls(pid, fd)
-
- # Set some informational attributes
- inst.argv = argv
- if env is not None:
- inst.env = env
- if cwd is not None:
- inst.launch_dir = cwd
-
- # [issue #119] 2. After forking, the parent closes the writing end
- # of the pipe and reads from the reading end.
- os.close(exec_err_pipe_write)
- exec_err_data = os.read(exec_err_pipe_read, 4096)
- os.close(exec_err_pipe_read)
-
- # [issue #119] 6. The parent reads eof (a zero-length read) if the
- # child successfully performed exec, since close-on-exec made
- # successful exec close the writing end of the pipe. Or, if exec
- # failed, the parent reads the error code and can proceed
- # accordingly. Either way, the parent blocks until the child calls
- # exec.
- if len(exec_err_data) != 0:
- try:
- errclass, errno_s, errmsg = exec_err_data.split(b':', 2)
- exctype = getattr(builtins, errclass.decode('ascii'), Exception)
-
- exception = exctype(errmsg.decode('utf-8', 'replace'))
- if exctype is OSError:
- exception.errno = int(errno_s)
- except:
- raise Exception('Subprocess failed, got bad error data: %r'
- % exec_err_data)
- else:
- raise exception
-
- try:
- inst.setwinsize(*dimensions)
- except IOError as err:
- if err.args[0] not in (errno.EINVAL, errno.ENOTTY, errno.ENXIO):
- raise
-
- return inst
-
- def __repr__(self):
- clsname = type(self).__name__
- if self.argv is not None:
- args = [repr(self.argv)]
- if self.env is not None:
- args.append("env=%r" % self.env)
- if self.launch_dir is not None:
- args.append("cwd=%r" % self.launch_dir)
-
- return "{}.spawn({})".format(clsname, ", ".join(args))
-
- else:
- return "{}(pid={}, fd={})".format(clsname, self.pid, self.fd)
-
- @staticmethod
- def _coerce_send_string(s):
- if not isinstance(s, bytes):
- return s.encode('utf-8')
- return s
-
- @staticmethod
- def _coerce_read_string(s):
- return s
-
- def __del__(self):
- '''This makes sure that no system resources are left open. Python only
- garbage collects Python objects. OS file descriptors are not Python
- objects, so they must be handled explicitly. If the child file
- descriptor was opened outside of this class (passed to the constructor)
- then this does not close it. '''
-
- if not self.closed:
- # It is possible for __del__ methods to execute during the
- # teardown of the Python VM itself. Thus self.close() may
- # trigger an exception because os.close may be None.
- try:
- self.close()
+
+ if cwd is not None:
+ os.chdir(cwd)
+
+ if preexec_fn is not None:
+ try:
+ preexec_fn()
+ except Exception as e:
+ ename = type(e).__name__
+ tosend = '{}:0:{}'.format(ename, str(e))
+ if PY3:
+ tosend = tosend.encode('utf-8')
+
+ os.write(exec_err_pipe_write, tosend)
+ os.close(exec_err_pipe_write)
+ os._exit(1)
+
+ try:
+ if env is None:
+ os.execv(command, argv)
+ else:
+ os.execvpe(command, argv, env)
+ except OSError as err:
+ # [issue #119] 5. If exec fails, the child writes the error
+ # code back to the parent using the pipe, then exits.
+ tosend = 'OSError:{}:{}'.format(err.errno, str(err))
+ if PY3:
+ tosend = tosend.encode('utf-8')
+ os.write(exec_err_pipe_write, tosend)
+ os.close(exec_err_pipe_write)
+ os._exit(os.EX_OSERR)
+
+ # Parent
+ inst = cls(pid, fd)
+
+ # Set some informational attributes
+ inst.argv = argv
+ if env is not None:
+ inst.env = env
+ if cwd is not None:
+ inst.launch_dir = cwd
+
+ # [issue #119] 2. After forking, the parent closes the writing end
+ # of the pipe and reads from the reading end.
+ os.close(exec_err_pipe_write)
+ exec_err_data = os.read(exec_err_pipe_read, 4096)
+ os.close(exec_err_pipe_read)
+
+ # [issue #119] 6. The parent reads eof (a zero-length read) if the
+ # child successfully performed exec, since close-on-exec made
+ # successful exec close the writing end of the pipe. Or, if exec
+ # failed, the parent reads the error code and can proceed
+ # accordingly. Either way, the parent blocks until the child calls
+ # exec.
+ if len(exec_err_data) != 0:
+ try:
+ errclass, errno_s, errmsg = exec_err_data.split(b':', 2)
+ exctype = getattr(builtins, errclass.decode('ascii'), Exception)
+
+ exception = exctype(errmsg.decode('utf-8', 'replace'))
+ if exctype is OSError:
+ exception.errno = int(errno_s)
+ except:
+ raise Exception('Subprocess failed, got bad error data: %r'
+ % exec_err_data)
+ else:
+ raise exception
+
+ try:
+ inst.setwinsize(*dimensions)
+ except IOError as err:
+ if err.args[0] not in (errno.EINVAL, errno.ENOTTY, errno.ENXIO):
+ raise
+
+ return inst
+
+ def __repr__(self):
+ clsname = type(self).__name__
+ if self.argv is not None:
+ args = [repr(self.argv)]
+ if self.env is not None:
+ args.append("env=%r" % self.env)
+ if self.launch_dir is not None:
+ args.append("cwd=%r" % self.launch_dir)
+
+ return "{}.spawn({})".format(clsname, ", ".join(args))
+
+ else:
+ return "{}(pid={}, fd={})".format(clsname, self.pid, self.fd)
+
+ @staticmethod
+ def _coerce_send_string(s):
+ if not isinstance(s, bytes):
+ return s.encode('utf-8')
+ return s
+
+ @staticmethod
+ def _coerce_read_string(s):
+ return s
+
+ def __del__(self):
+ '''This makes sure that no system resources are left open. Python only
+ garbage collects Python objects. OS file descriptors are not Python
+ objects, so they must be handled explicitly. If the child file
+ descriptor was opened outside of this class (passed to the constructor)
+ then this does not close it. '''
+
+ if not self.closed:
+ # It is possible for __del__ methods to execute during the
+ # teardown of the Python VM itself. Thus self.close() may
+ # trigger an exception because os.close may be None.
+ try:
+ self.close()
# which exception, shouldn't we catch explicitly .. ?
- except:
- pass
-
-
- def fileno(self):
- '''This returns the file descriptor of the pty for the child.
- '''
- return self.fd
-
- def close(self, force=True):
- '''This closes the connection with the child application. Note that
- calling close() more than once is valid. This emulates standard Python
- behavior with files. Set force to True if you want to make sure that
- the child is terminated (SIGKILL is sent if the child ignores SIGHUP
- and SIGINT). '''
- if not self.closed:
- self.flush()
- self.fileobj.close() # Closes the file descriptor
- # Give kernel time to update process status.
- time.sleep(self.delayafterclose)
- if self.isalive():
- if not self.terminate(force):
- raise PtyProcessError('Could not terminate the child.')
- self.fd = -1
- self.closed = True
- #self.pid = None
-
- def flush(self):
- '''This does nothing. It is here to support the interface for a
- File-like object. '''
-
- pass
-
- def isatty(self):
- '''This returns True if the file descriptor is open and connected to a
- tty(-like) device, else False.
-
- On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
- the child pty may not appear as a terminal device. This means
- methods such as setecho(), setwinsize(), getwinsize() may raise an
- IOError. '''
-
- return os.isatty(self.fd)
-
- def waitnoecho(self, timeout=None):
- '''This waits until the terminal ECHO flag is set False. This returns
- True if the echo mode is off. This returns False if the ECHO flag was
- not set False before the timeout. This can be used to detect when the
- child is waiting for a password. Usually a child application will turn
- off echo mode when it is waiting for the user to enter a password. For
- example, instead of expecting the "password:" prompt you can wait for
- the child to set ECHO off::
-
- p = pexpect.spawn('ssh user@example.com')
- p.waitnoecho()
- p.sendline(mypassword)
-
- If timeout==None then this method to block until ECHO flag is False.
- '''
-
- if timeout is not None:
- end_time = time.time() + timeout
- while True:
- if not self.getecho():
- return True
- if timeout < 0 and timeout is not None:
- return False
- if timeout is not None:
- timeout = end_time - time.time()
- time.sleep(0.1)
-
- def getecho(self):
- '''This returns the terminal echo mode. This returns True if echo is
- on or False if echo is off. Child applications that are expecting you
- to enter a password often set ECHO False. See waitnoecho().
-
- Not supported on platforms where ``isatty()`` returns False. '''
-
- try:
- attr = termios.tcgetattr(self.fd)
- except termios.error as err:
- errmsg = 'getecho() may not be called on this platform'
- if err.args[0] == errno.EINVAL:
- raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
- raise
-
- self.echo = bool(attr[3] & termios.ECHO)
- return self.echo
-
- def setecho(self, state):
- '''This sets the terminal echo mode on or off. Note that anything the
- child sent before the echo will be lost, so you should be sure that
- your input buffer is empty before you call setecho(). For example, the
- following will work as expected::
-
- p = pexpect.spawn('cat') # Echo is on by default.
- p.sendline('1234') # We expect see this twice from the child...
- p.expect(['1234']) # ... once from the tty echo...
- p.expect(['1234']) # ... and again from cat itself.
- p.setecho(False) # Turn off tty echo
- p.sendline('abcd') # We will set this only once (echoed by cat).
- p.sendline('wxyz') # We will set this only once (echoed by cat)
- p.expect(['abcd'])
- p.expect(['wxyz'])
-
- The following WILL NOT WORK because the lines sent before the setecho
- will be lost::
-
- p = pexpect.spawn('cat')
- p.sendline('1234')
- p.setecho(False) # Turn off tty echo
- p.sendline('abcd') # We will set this only once (echoed by cat).
- p.sendline('wxyz') # We will set this only once (echoed by cat)
- p.expect(['1234'])
- p.expect(['1234'])
- p.expect(['abcd'])
- p.expect(['wxyz'])
-
-
- Not supported on platforms where ``isatty()`` returns False.
- '''
- _setecho(self.fd, state)
-
- self.echo = state
-
- def read(self, size=1024):
- """Read and return at most ``size`` bytes from the pty.
-
- Can block if there is nothing to read. Raises :exc:`EOFError` if the
- terminal was closed.
-
- Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal
- with the vagaries of EOF on platforms that do strange things, like IRIX
- or older Solaris systems. It handles the errno=EIO pattern used on
- Linux, and the empty-string return used on BSD platforms and (seemingly)
- on recent Solaris.
- """
- try:
+ except:
+ pass
+
+
+ def fileno(self):
+ '''This returns the file descriptor of the pty for the child.
+ '''
+ return self.fd
+
+ def close(self, force=True):
+ '''This closes the connection with the child application. Note that
+ calling close() more than once is valid. This emulates standard Python
+ behavior with files. Set force to True if you want to make sure that
+ the child is terminated (SIGKILL is sent if the child ignores SIGHUP
+ and SIGINT). '''
+ if not self.closed:
+ self.flush()
+ self.fileobj.close() # Closes the file descriptor
+ # Give kernel time to update process status.
+ time.sleep(self.delayafterclose)
+ if self.isalive():
+ if not self.terminate(force):
+ raise PtyProcessError('Could not terminate the child.')
+ self.fd = -1
+ self.closed = True
+ #self.pid = None
+
+ def flush(self):
+ '''This does nothing. It is here to support the interface for a
+ File-like object. '''
+
+ pass
+
+ def isatty(self):
+ '''This returns True if the file descriptor is open and connected to a
+ tty(-like) device, else False.
+
+ On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
+ the child pty may not appear as a terminal device. This means
+ methods such as setecho(), setwinsize(), getwinsize() may raise an
+ IOError. '''
+
+ return os.isatty(self.fd)
+
+ def waitnoecho(self, timeout=None):
+ '''This waits until the terminal ECHO flag is set False. This returns
+ True if the echo mode is off. This returns False if the ECHO flag was
+ not set False before the timeout. This can be used to detect when the
+ child is waiting for a password. Usually a child application will turn
+ off echo mode when it is waiting for the user to enter a password. For
+ example, instead of expecting the "password:" prompt you can wait for
+ the child to set ECHO off::
+
+ p = pexpect.spawn('ssh user@example.com')
+ p.waitnoecho()
+ p.sendline(mypassword)
+
+ If timeout==None then this method to block until ECHO flag is False.
+ '''
+
+ if timeout is not None:
+ end_time = time.time() + timeout
+ while True:
+ if not self.getecho():
+ return True
+ if timeout < 0 and timeout is not None:
+ return False
+ if timeout is not None:
+ timeout = end_time - time.time()
+ time.sleep(0.1)
+
+ def getecho(self):
+ '''This returns the terminal echo mode. This returns True if echo is
+ on or False if echo is off. Child applications that are expecting you
+ to enter a password often set ECHO False. See waitnoecho().
+
+ Not supported on platforms where ``isatty()`` returns False. '''
+
+ try:
+ attr = termios.tcgetattr(self.fd)
+ except termios.error as err:
+ errmsg = 'getecho() may not be called on this platform'
+ if err.args[0] == errno.EINVAL:
+ raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
+ raise
+
+ self.echo = bool(attr[3] & termios.ECHO)
+ return self.echo
+
+ def setecho(self, state):
+ '''This sets the terminal echo mode on or off. Note that anything the
+ child sent before the echo will be lost, so you should be sure that
+ your input buffer is empty before you call setecho(). For example, the
+ following will work as expected::
+
+ p = pexpect.spawn('cat') # Echo is on by default.
+ p.sendline('1234') # We expect see this twice from the child...
+ p.expect(['1234']) # ... once from the tty echo...
+ p.expect(['1234']) # ... and again from cat itself.
+ p.setecho(False) # Turn off tty echo
+ p.sendline('abcd') # We will set this only once (echoed by cat).
+ p.sendline('wxyz') # We will set this only once (echoed by cat)
+ p.expect(['abcd'])
+ p.expect(['wxyz'])
+
+ The following WILL NOT WORK because the lines sent before the setecho
+ will be lost::
+
+ p = pexpect.spawn('cat')
+ p.sendline('1234')
+ p.setecho(False) # Turn off tty echo
+ p.sendline('abcd') # We will set this only once (echoed by cat).
+ p.sendline('wxyz') # We will set this only once (echoed by cat)
+ p.expect(['1234'])
+ p.expect(['1234'])
+ p.expect(['abcd'])
+ p.expect(['wxyz'])
+
+
+ Not supported on platforms where ``isatty()`` returns False.
+ '''
+ _setecho(self.fd, state)
+
+ self.echo = state
+
+ def read(self, size=1024):
+ """Read and return at most ``size`` bytes from the pty.
+
+ Can block if there is nothing to read. Raises :exc:`EOFError` if the
+ terminal was closed.
+
+ Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal
+ with the vagaries of EOF on platforms that do strange things, like IRIX
+ or older Solaris systems. It handles the errno=EIO pattern used on
+ Linux, and the empty-string return used on BSD platforms and (seemingly)
+ on recent Solaris.
+ """
+ try:
s = self.fileobj.read1(size)
- except (OSError, IOError) as err:
- if err.args[0] == errno.EIO:
- # Linux-style EOF
- self.flag_eof = True
- raise EOFError('End Of File (EOF). Exception style platform.')
- raise
- if s == b'':
- # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
- self.flag_eof = True
- raise EOFError('End Of File (EOF). Empty string style platform.')
-
- return s
-
- def readline(self):
- """Read one line from the pseudoterminal, and return it as unicode.
-
- Can block if there is nothing to read. Raises :exc:`EOFError` if the
- terminal was closed.
- """
- try:
- s = self.fileobj.readline()
- except (OSError, IOError) as err:
- if err.args[0] == errno.EIO:
- # Linux-style EOF
- self.flag_eof = True
- raise EOFError('End Of File (EOF). Exception style platform.')
- raise
- if s == b'':
- # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
- self.flag_eof = True
- raise EOFError('End Of File (EOF). Empty string style platform.')
-
- return s
-
+ except (OSError, IOError) as err:
+ if err.args[0] == errno.EIO:
+ # Linux-style EOF
+ self.flag_eof = True
+ raise EOFError('End Of File (EOF). Exception style platform.')
+ raise
+ if s == b'':
+ # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
+ self.flag_eof = True
+ raise EOFError('End Of File (EOF). Empty string style platform.')
+
+ return s
+
+ def readline(self):
+ """Read one line from the pseudoterminal, and return it as unicode.
+
+ Can block if there is nothing to read. Raises :exc:`EOFError` if the
+ terminal was closed.
+ """
+ try:
+ s = self.fileobj.readline()
+ except (OSError, IOError) as err:
+ if err.args[0] == errno.EIO:
+ # Linux-style EOF
+ self.flag_eof = True
+ raise EOFError('End Of File (EOF). Exception style platform.')
+ raise
+ if s == b'':
+ # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
+ self.flag_eof = True
+ raise EOFError('End Of File (EOF). Empty string style platform.')
+
+ return s
+
def _writeb(self, b, flush=True):
n = self.fileobj.write(b)
if flush:
@@ -561,282 +561,282 @@ class PtyProcess(object):
return n
def write(self, s, flush=True):
- """Write bytes to the pseudoterminal.
-
- Returns the number of bytes written.
- """
+ """Write bytes to the pseudoterminal.
+
+ Returns the number of bytes written.
+ """
return self._writeb(s, flush=flush)
-
- def sendcontrol(self, char):
- '''Helper method that wraps send() with mnemonic access for sending control
- character to the child (such as Ctrl-C or Ctrl-D). For example, to send
- Ctrl-G (ASCII 7, bell, '\a')::
-
- child.sendcontrol('g')
-
- See also, sendintr() and sendeof().
- '''
- char = char.lower()
- a = ord(char)
- if 97 <= a <= 122:
- a = a - ord('a') + 1
- byte = _byte(a)
+
+ def sendcontrol(self, char):
+ '''Helper method that wraps send() with mnemonic access for sending control
+ character to the child (such as Ctrl-C or Ctrl-D). For example, to send
+ Ctrl-G (ASCII 7, bell, '\a')::
+
+ child.sendcontrol('g')
+
+ See also, sendintr() and sendeof().
+ '''
+ char = char.lower()
+ a = ord(char)
+ if 97 <= a <= 122:
+ a = a - ord('a') + 1
+ byte = _byte(a)
return self._writeb(byte), byte
- d = {'@': 0, '`': 0,
- '[': 27, '{': 27,
- '\\': 28, '|': 28,
- ']': 29, '}': 29,
- '^': 30, '~': 30,
- '_': 31,
- '?': 127}
- if char not in d:
- return 0, b''
-
- byte = _byte(d[char])
+ d = {'@': 0, '`': 0,
+ '[': 27, '{': 27,
+ '\\': 28, '|': 28,
+ ']': 29, '}': 29,
+ '^': 30, '~': 30,
+ '_': 31,
+ '?': 127}
+ if char not in d:
+ return 0, b''
+
+ byte = _byte(d[char])
return self._writeb(byte), byte
-
- def sendeof(self):
- '''This sends an EOF to the child. This sends a character which causes
- the pending parent output buffer to be sent to the waiting child
- program without waiting for end-of-line. If it is the first character
- of the line, the read() in the user program returns 0, which signifies
- end-of-file. This means to work as expected a sendeof() has to be
- called at the beginning of a line. This method does not send a newline.
- It is the responsibility of the caller to ensure the eof is sent at the
- beginning of a line. '''
-
+
+ def sendeof(self):
+ '''This sends an EOF to the child. This sends a character which causes
+ the pending parent output buffer to be sent to the waiting child
+ program without waiting for end-of-line. If it is the first character
+ of the line, the read() in the user program returns 0, which signifies
+ end-of-file. This means to work as expected a sendeof() has to be
+ called at the beginning of a line. This method does not send a newline.
+ It is the responsibility of the caller to ensure the eof is sent at the
+ beginning of a line. '''
+
return self._writeb(_EOF), _EOF
-
- def sendintr(self):
- '''This sends a SIGINT to the child. It does not require
- the SIGINT to be the first character on a line. '''
-
+
+ def sendintr(self):
+ '''This sends a SIGINT to the child. It does not require
+ the SIGINT to be the first character on a line. '''
+
return self._writeb(_INTR), _INTR
-
- def eof(self):
- '''This returns True if the EOF exception was ever raised.
- '''
-
- return self.flag_eof
-
- def terminate(self, force=False):
- '''This forces a child process to terminate. It starts nicely with
- SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
- returns True if the child was terminated. This returns False if the
- child could not be terminated. '''
-
- if not self.isalive():
- return True
- try:
- self.kill(signal.SIGHUP)
- time.sleep(self.delayafterterminate)
- if not self.isalive():
- return True
- self.kill(signal.SIGCONT)
- time.sleep(self.delayafterterminate)
- if not self.isalive():
- return True
- self.kill(signal.SIGINT)
- time.sleep(self.delayafterterminate)
- if not self.isalive():
- return True
- if force:
- self.kill(signal.SIGKILL)
- time.sleep(self.delayafterterminate)
- if not self.isalive():
- return True
- else:
- return False
- return False
- except OSError:
- # I think there are kernel timing issues that sometimes cause
- # this to happen. I think isalive() reports True, but the
- # process is dead to the kernel.
- # Make one last attempt to see if the kernel is up to date.
- time.sleep(self.delayafterterminate)
- if not self.isalive():
- return True
- else:
- return False
-
- def wait(self):
- '''This waits until the child exits. This is a blocking call. This will
- not read any data from the child, so this will block forever if the
- child has unread output and has terminated. In other words, the child
- may have printed output then called exit(), but, the child is
- technically still alive until its output is read by the parent. '''
-
- if self.isalive():
- pid, status = os.waitpid(self.pid, 0)
- else:
- return self.exitstatus
- self.exitstatus = os.WEXITSTATUS(status)
- if os.WIFEXITED(status):
- self.status = status
- self.exitstatus = os.WEXITSTATUS(status)
- self.signalstatus = None
- self.terminated = True
- elif os.WIFSIGNALED(status):
- self.status = status
- self.exitstatus = None
- self.signalstatus = os.WTERMSIG(status)
- self.terminated = True
- elif os.WIFSTOPPED(status): # pragma: no cover
- # You can't call wait() on a child process in the stopped state.
- raise PtyProcessError('Called wait() on a stopped child ' +
- 'process. This is not supported. Is some other ' +
- 'process attempting job control with our child pid?')
- return self.exitstatus
-
- def isalive(self):
- '''This tests if the child process is running or not. This is
- non-blocking. If the child was terminated then this will read the
- exitstatus or signalstatus of the child. This returns True if the child
- process appears to be running or False if not. It can take literally
- SECONDS for Solaris to return the right status. '''
-
- if self.terminated:
- return False
-
- if self.flag_eof:
- # This is for Linux, which requires the blocking form
- # of waitpid to get the status of a defunct process.
- # This is super-lame. The flag_eof would have been set
- # in read_nonblocking(), so this should be safe.
- waitpid_options = 0
- else:
- waitpid_options = os.WNOHANG
-
- try:
- pid, status = os.waitpid(self.pid, waitpid_options)
- except OSError as e:
- # No child processes
- if e.errno == errno.ECHILD:
- raise PtyProcessError('isalive() encountered condition ' +
- 'where "terminated" is 0, but there was no child ' +
- 'process. Did someone else call waitpid() ' +
- 'on our process?')
- else:
- raise
-
- # I have to do this twice for Solaris.
- # I can't even believe that I figured this out...
- # If waitpid() returns 0 it means that no child process
- # wishes to report, and the value of status is undefined.
- if pid == 0:
- try:
- ### os.WNOHANG) # Solaris!
- pid, status = os.waitpid(self.pid, waitpid_options)
- except OSError as e: # pragma: no cover
- # This should never happen...
- if e.errno == errno.ECHILD:
- raise PtyProcessError('isalive() encountered condition ' +
- 'that should never happen. There was no child ' +
- 'process. Did someone else call waitpid() ' +
- 'on our process?')
- else:
- raise
-
- # If pid is still 0 after two calls to waitpid() then the process
- # really is alive. This seems to work on all platforms, except for
- # Irix which seems to require a blocking call on waitpid or select,
- # so I let read_nonblocking take care of this situation
- # (unfortunately, this requires waiting through the timeout).
- if pid == 0:
- return True
-
- if pid == 0:
- return True
-
- if os.WIFEXITED(status):
- self.status = status
- self.exitstatus = os.WEXITSTATUS(status)
- self.signalstatus = None
- self.terminated = True
- elif os.WIFSIGNALED(status):
- self.status = status
- self.exitstatus = None
- self.signalstatus = os.WTERMSIG(status)
- self.terminated = True
- elif os.WIFSTOPPED(status):
- raise PtyProcessError('isalive() encountered condition ' +
- 'where child process is stopped. This is not ' +
- 'supported. Is some other process attempting ' +
- 'job control with our child pid?')
- return False
-
- def kill(self, sig):
- """Send the given signal to the child application.
-
- In keeping with UNIX tradition it has a misleading name. It does not
- necessarily kill the child unless you send the right signal. See the
- :mod:`signal` module for constants representing signal numbers.
- """
-
- # Same as os.kill, but the pid is given for you.
- if self.isalive():
- os.kill(self.pid, sig)
-
- def getwinsize(self):
- """Return the window size of the pseudoterminal as a tuple (rows, cols).
- """
- TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
- s = struct.pack('HHHH', 0, 0, 0, 0)
- x = fcntl.ioctl(self.fd, TIOCGWINSZ, s)
- return struct.unpack('HHHH', x)[0:2]
-
- def setwinsize(self, rows, cols):
- """Set the terminal window size of the child tty.
-
- This will cause a SIGWINCH signal to be sent to the child. This does not
- change the physical window size. It changes the size reported to
- TTY-aware applications like vi or curses -- applications that respond to
- the SIGWINCH signal.
- """
- return _setwinsize(self.fd, rows, cols)
-
-
-class PtyProcessUnicode(PtyProcess):
- """Unicode wrapper around a process running in a pseudoterminal.
-
- This class exposes a similar interface to :class:`PtyProcess`, but its read
- methods return unicode, and its :meth:`write` accepts unicode.
- """
- if PY3:
- string_type = str
- else:
- string_type = unicode # analysis:ignore
-
- def __init__(self, pid, fd, encoding='utf-8', codec_errors='strict'):
- super(PtyProcessUnicode, self).__init__(pid, fd)
- self.encoding = encoding
- self.codec_errors = codec_errors
- self.decoder = codecs.getincrementaldecoder(encoding)(errors=codec_errors)
-
- def read(self, size=1024):
- """Read at most ``size`` bytes from the pty, return them as unicode.
-
- Can block if there is nothing to read. Raises :exc:`EOFError` if the
- terminal was closed.
-
- The size argument still refers to bytes, not unicode code points.
- """
- b = super(PtyProcessUnicode, self).read(size)
- return self.decoder.decode(b, final=False)
-
- def readline(self):
- """Read one line from the pseudoterminal, and return it as unicode.
-
- Can block if there is nothing to read. Raises :exc:`EOFError` if the
- terminal was closed.
- """
- b = super(PtyProcessUnicode, self).readline()
- return self.decoder.decode(b, final=False)
-
- def write(self, s):
- """Write the unicode string ``s`` to the pseudoterminal.
-
- Returns the number of bytes written.
- """
- b = s.encode(self.encoding)
- return super(PtyProcessUnicode, self).write(b)
+
+ def eof(self):
+ '''This returns True if the EOF exception was ever raised.
+ '''
+
+ return self.flag_eof
+
+ def terminate(self, force=False):
+ '''This forces a child process to terminate. It starts nicely with
+ SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
+ returns True if the child was terminated. This returns False if the
+ child could not be terminated. '''
+
+ if not self.isalive():
+ return True
+ try:
+ self.kill(signal.SIGHUP)
+ time.sleep(self.delayafterterminate)
+ if not self.isalive():
+ return True
+ self.kill(signal.SIGCONT)
+ time.sleep(self.delayafterterminate)
+ if not self.isalive():
+ return True
+ self.kill(signal.SIGINT)
+ time.sleep(self.delayafterterminate)
+ if not self.isalive():
+ return True
+ if force:
+ self.kill(signal.SIGKILL)
+ time.sleep(self.delayafterterminate)
+ if not self.isalive():
+ return True
+ else:
+ return False
+ return False
+ except OSError:
+ # I think there are kernel timing issues that sometimes cause
+ # this to happen. I think isalive() reports True, but the
+ # process is dead to the kernel.
+ # Make one last attempt to see if the kernel is up to date.
+ time.sleep(self.delayafterterminate)
+ if not self.isalive():
+ return True
+ else:
+ return False
+
+ def wait(self):
+ '''This waits until the child exits. This is a blocking call. This will
+ not read any data from the child, so this will block forever if the
+ child has unread output and has terminated. In other words, the child
+ may have printed output then called exit(), but, the child is
+ technically still alive until its output is read by the parent. '''
+
+ if self.isalive():
+ pid, status = os.waitpid(self.pid, 0)
+ else:
+ return self.exitstatus
+ self.exitstatus = os.WEXITSTATUS(status)
+ if os.WIFEXITED(status):
+ self.status = status
+ self.exitstatus = os.WEXITSTATUS(status)
+ self.signalstatus = None
+ self.terminated = True
+ elif os.WIFSIGNALED(status):
+ self.status = status
+ self.exitstatus = None
+ self.signalstatus = os.WTERMSIG(status)
+ self.terminated = True
+ elif os.WIFSTOPPED(status): # pragma: no cover
+ # You can't call wait() on a child process in the stopped state.
+ raise PtyProcessError('Called wait() on a stopped child ' +
+ 'process. This is not supported. Is some other ' +
+ 'process attempting job control with our child pid?')
+ return self.exitstatus
+
+ def isalive(self):
+ '''This tests if the child process is running or not. This is
+ non-blocking. If the child was terminated then this will read the
+ exitstatus or signalstatus of the child. This returns True if the child
+ process appears to be running or False if not. It can take literally
+ SECONDS for Solaris to return the right status. '''
+
+ if self.terminated:
+ return False
+
+ if self.flag_eof:
+ # This is for Linux, which requires the blocking form
+ # of waitpid to get the status of a defunct process.
+ # This is super-lame. The flag_eof would have been set
+ # in read_nonblocking(), so this should be safe.
+ waitpid_options = 0
+ else:
+ waitpid_options = os.WNOHANG
+
+ try:
+ pid, status = os.waitpid(self.pid, waitpid_options)
+ except OSError as e:
+ # No child processes
+ if e.errno == errno.ECHILD:
+ raise PtyProcessError('isalive() encountered condition ' +
+ 'where "terminated" is 0, but there was no child ' +
+ 'process. Did someone else call waitpid() ' +
+ 'on our process?')
+ else:
+ raise
+
+ # I have to do this twice for Solaris.
+ # I can't even believe that I figured this out...
+ # If waitpid() returns 0 it means that no child process
+ # wishes to report, and the value of status is undefined.
+ if pid == 0:
+ try:
+ ### os.WNOHANG) # Solaris!
+ pid, status = os.waitpid(self.pid, waitpid_options)
+ except OSError as e: # pragma: no cover
+ # This should never happen...
+ if e.errno == errno.ECHILD:
+ raise PtyProcessError('isalive() encountered condition ' +
+ 'that should never happen. There was no child ' +
+ 'process. Did someone else call waitpid() ' +
+ 'on our process?')
+ else:
+ raise
+
+ # If pid is still 0 after two calls to waitpid() then the process
+ # really is alive. This seems to work on all platforms, except for
+ # Irix which seems to require a blocking call on waitpid or select,
+ # so I let read_nonblocking take care of this situation
+ # (unfortunately, this requires waiting through the timeout).
+ if pid == 0:
+ return True
+
+ if pid == 0:
+ return True
+
+ if os.WIFEXITED(status):
+ self.status = status
+ self.exitstatus = os.WEXITSTATUS(status)
+ self.signalstatus = None
+ self.terminated = True
+ elif os.WIFSIGNALED(status):
+ self.status = status
+ self.exitstatus = None
+ self.signalstatus = os.WTERMSIG(status)
+ self.terminated = True
+ elif os.WIFSTOPPED(status):
+ raise PtyProcessError('isalive() encountered condition ' +
+ 'where child process is stopped. This is not ' +
+ 'supported. Is some other process attempting ' +
+ 'job control with our child pid?')
+ return False
+
+ def kill(self, sig):
+ """Send the given signal to the child application.
+
+ In keeping with UNIX tradition it has a misleading name. It does not
+ necessarily kill the child unless you send the right signal. See the
+ :mod:`signal` module for constants representing signal numbers.
+ """
+
+ # Same as os.kill, but the pid is given for you.
+ if self.isalive():
+ os.kill(self.pid, sig)
+
+ def getwinsize(self):
+ """Return the window size of the pseudoterminal as a tuple (rows, cols).
+ """
+ TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
+ s = struct.pack('HHHH', 0, 0, 0, 0)
+ x = fcntl.ioctl(self.fd, TIOCGWINSZ, s)
+ return struct.unpack('HHHH', x)[0:2]
+
+ def setwinsize(self, rows, cols):
+ """Set the terminal window size of the child tty.
+
+ This will cause a SIGWINCH signal to be sent to the child. This does not
+ change the physical window size. It changes the size reported to
+ TTY-aware applications like vi or curses -- applications that respond to
+ the SIGWINCH signal.
+ """
+ return _setwinsize(self.fd, rows, cols)
+
+
+class PtyProcessUnicode(PtyProcess):
+ """Unicode wrapper around a process running in a pseudoterminal.
+
+ This class exposes a similar interface to :class:`PtyProcess`, but its read
+ methods return unicode, and its :meth:`write` accepts unicode.
+ """
+ if PY3:
+ string_type = str
+ else:
+ string_type = unicode # analysis:ignore
+
+ def __init__(self, pid, fd, encoding='utf-8', codec_errors='strict'):
+ super(PtyProcessUnicode, self).__init__(pid, fd)
+ self.encoding = encoding
+ self.codec_errors = codec_errors
+ self.decoder = codecs.getincrementaldecoder(encoding)(errors=codec_errors)
+
+ def read(self, size=1024):
+ """Read at most ``size`` bytes from the pty, return them as unicode.
+
+ Can block if there is nothing to read. Raises :exc:`EOFError` if the
+ terminal was closed.
+
+ The size argument still refers to bytes, not unicode code points.
+ """
+ b = super(PtyProcessUnicode, self).read(size)
+ return self.decoder.decode(b, final=False)
+
+ def readline(self):
+ """Read one line from the pseudoterminal, and return it as unicode.
+
+ Can block if there is nothing to read. Raises :exc:`EOFError` if the
+ terminal was closed.
+ """
+ b = super(PtyProcessUnicode, self).readline()
+ return self.decoder.decode(b, final=False)
+
+ def write(self, s):
+ """Write the unicode string ``s`` to the pseudoterminal.
+
+ Returns the number of bytes written.
+ """
+ b = s.encode(self.encoding)
+ return super(PtyProcessUnicode, self).write(b)
diff --git a/contrib/python/ptyprocess/ptyprocess/util.py b/contrib/python/ptyprocess/ptyprocess/util.py
index 9bd6c4c34c..aadbd62c80 100644
--- a/contrib/python/ptyprocess/ptyprocess/util.py
+++ b/contrib/python/ptyprocess/ptyprocess/util.py
@@ -1,69 +1,69 @@
-try:
- from shutil import which # Python >= 3.3
-except ImportError:
- import os, sys
-
- # This is copied from Python 3.4.1
- def which(cmd, mode=os.F_OK | os.X_OK, path=None):
- """Given a command, mode, and a PATH string, return the path which
- conforms to the given mode on the PATH, or None if there is no such
- file.
-
- `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
- of os.environ.get("PATH"), or can be overridden with a custom search
- path.
-
- """
- # Check that a given file can be accessed with the correct mode.
- # Additionally check that `file` is not a directory, as on Windows
- # directories pass the os.access check.
- def _access_check(fn, mode):
- return (os.path.exists(fn) and os.access(fn, mode)
- and not os.path.isdir(fn))
-
- # If we're given a path with a directory part, look it up directly rather
- # than referring to PATH directories. This includes checking relative to the
- # current directory, e.g. ./script
- if os.path.dirname(cmd):
- if _access_check(cmd, mode):
- return cmd
- return None
-
- if path is None:
- path = os.environ.get("PATH", os.defpath)
- if not path:
- return None
- path = path.split(os.pathsep)
-
- if sys.platform == "win32":
- # The current directory takes precedence on Windows.
- if not os.curdir in path:
- path.insert(0, os.curdir)
-
- # PATHEXT is necessary to check on Windows.
- pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
- # See if the given file matches any of the expected path extensions.
- # This will allow us to short circuit when given "python.exe".
- # If it does match, only test that one, otherwise we have to try
- # others.
- if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
- files = [cmd]
- else:
- files = [cmd + ext for ext in pathext]
- else:
- # On other platforms you don't have things like PATHEXT to tell you
- # what file suffixes are executable, so just pass on cmd as-is.
- files = [cmd]
-
- seen = set()
- for dir in path:
- normdir = os.path.normcase(dir)
- if not normdir in seen:
- seen.add(normdir)
- for thefile in files:
- name = os.path.join(dir, thefile)
- if _access_check(name, mode):
- return name
+try:
+ from shutil import which # Python >= 3.3
+except ImportError:
+ import os, sys
+
+ # This is copied from Python 3.4.1
+ def which(cmd, mode=os.F_OK | os.X_OK, path=None):
+ """Given a command, mode, and a PATH string, return the path which
+ conforms to the given mode on the PATH, or None if there is no such
+ file.
+
+ `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
+ of os.environ.get("PATH"), or can be overridden with a custom search
+ path.
+
+ """
+ # Check that a given file can be accessed with the correct mode.
+ # Additionally check that `file` is not a directory, as on Windows
+ # directories pass the os.access check.
+ def _access_check(fn, mode):
+ return (os.path.exists(fn) and os.access(fn, mode)
+ and not os.path.isdir(fn))
+
+ # If we're given a path with a directory part, look it up directly rather
+ # than referring to PATH directories. This includes checking relative to the
+ # current directory, e.g. ./script
+ if os.path.dirname(cmd):
+ if _access_check(cmd, mode):
+ return cmd
+ return None
+
+ if path is None:
+ path = os.environ.get("PATH", os.defpath)
+ if not path:
+ return None
+ path = path.split(os.pathsep)
+
+ if sys.platform == "win32":
+ # The current directory takes precedence on Windows.
+ if not os.curdir in path:
+ path.insert(0, os.curdir)
+
+ # PATHEXT is necessary to check on Windows.
+ pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
+ # See if the given file matches any of the expected path extensions.
+ # This will allow us to short circuit when given "python.exe".
+ # If it does match, only test that one, otherwise we have to try
+ # others.
+ if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
+ files = [cmd]
+ else:
+ files = [cmd + ext for ext in pathext]
+ else:
+ # On other platforms you don't have things like PATHEXT to tell you
+ # what file suffixes are executable, so just pass on cmd as-is.
+ files = [cmd]
+
+ seen = set()
+ for dir in path:
+ normdir = os.path.normcase(dir)
+ if not normdir in seen:
+ seen.add(normdir)
+ for thefile in files:
+ name = os.path.join(dir, thefile)
+ if _access_check(name, mode):
+ return name
return None
diff --git a/contrib/python/ptyprocess/ya.make b/contrib/python/ptyprocess/ya.make
index b80a63187e..5e780214f2 100644
--- a/contrib/python/ptyprocess/ya.make
+++ b/contrib/python/ptyprocess/ya.make
@@ -1,7 +1,7 @@
# Generated by devtools/yamaker (pypi).
PY23_LIBRARY()
-
+
OWNER(borman g:python-contrib)
VERSION(0.7.0)
@@ -10,18 +10,18 @@ LICENSE(ISC)
NO_LINT()
-PY_SRCS(
- TOP_LEVEL
- ptyprocess/__init__.py
- ptyprocess/_fork_pty.py
- ptyprocess/ptyprocess.py
- ptyprocess/util.py
-)
-
+PY_SRCS(
+ TOP_LEVEL
+ ptyprocess/__init__.py
+ ptyprocess/_fork_pty.py
+ ptyprocess/ptyprocess.py
+ ptyprocess/util.py
+)
+
RESOURCE_FILES(
PREFIX contrib/python/ptyprocess/
.dist-info/METADATA
.dist-info/top_level.txt
)
-END()
+END()
diff --git a/contrib/python/py/ya.make b/contrib/python/py/ya.make
index 6a1d18e5fe..cc86cb7fa9 100644
--- a/contrib/python/py/ya.make
+++ b/contrib/python/py/ya.make
@@ -1,13 +1,13 @@
# Generated by devtools/yamaker (pypi).
PY23_LIBRARY()
-
+
OWNER(g:python-contrib)
VERSION(1.11.0)
LICENSE(MIT)
-
+
NO_LINT()
NO_CHECK_IMPORTS(
@@ -15,53 +15,53 @@ NO_CHECK_IMPORTS(
py._code._assertionold
)
-PY_SRCS(
- TOP_LEVEL
+PY_SRCS(
+ TOP_LEVEL
py/__init__.py
py/__init__.pyi
py/__metainfo.py
- py/_builtin.py
+ py/_builtin.py
py/_code/__init__.py
- py/_code/_assertionnew.py
- py/_code/_assertionold.py
+ py/_code/_assertionnew.py
+ py/_code/_assertionold.py
py/_code/_py2traceback.py
- py/_code/assertion.py
- py/_code/code.py
- py/_code/source.py
- py/_error.py
+ py/_code/assertion.py
+ py/_code/code.py
+ py/_code/source.py
+ py/_error.py
py/_io/__init__.py
py/_io/capture.py
- py/_io/saferepr.py
- py/_io/terminalwriter.py
- py/_log/__init__.py
- py/_log/log.py
- py/_log/warning.py
+ py/_io/saferepr.py
+ py/_io/terminalwriter.py
+ py/_log/__init__.py
+ py/_log/log.py
+ py/_log/warning.py
py/_path/__init__.py
- py/_path/cacheutil.py
- py/_path/common.py
- py/_path/local.py
- py/_path/svnurl.py
- py/_path/svnwc.py
+ py/_path/cacheutil.py
+ py/_path/common.py
+ py/_path/local.py
+ py/_path/svnurl.py
+ py/_path/svnwc.py
py/_process/__init__.py
- py/_process/cmdexec.py
- py/_process/forkedfunc.py
- py/_process/killproc.py
- py/_std.py
+ py/_process/cmdexec.py
+ py/_process/forkedfunc.py
+ py/_process/killproc.py
+ py/_std.py
py/_vendored_packages/__init__.py
py/_vendored_packages/apipkg/__init__.py
py/_vendored_packages/apipkg/version.py
py/_vendored_packages/iniconfig/__init__.py
py/_vendored_packages/iniconfig/__init__.pyi
py/_version.py
- py/_xmlgen.py
+ py/_xmlgen.py
py/error.pyi
py/iniconfig.pyi
py/io.pyi
py/path.pyi
py/test.py
py/xml.pyi
-)
-
+)
+
RESOURCE_FILES(
PREFIX contrib/python/py/
.dist-info/METADATA
@@ -70,4 +70,4 @@ RESOURCE_FILES(
py/py.typed
)
-END()
+END()
diff --git a/contrib/python/pyparsing/py2/ya.make b/contrib/python/pyparsing/py2/ya.make
index f625e1661d..e4812f97b5 100644
--- a/contrib/python/pyparsing/py2/ya.make
+++ b/contrib/python/pyparsing/py2/ya.make
@@ -1,7 +1,7 @@
# Generated by devtools/yamaker (pypi).
PY23_LIBRARY()
-
+
PROVIDES(pyparsing)
OWNER(borman orivej g:python-contrib)
@@ -12,15 +12,15 @@ LICENSE(MIT)
NO_LINT()
-PY_SRCS(
- TOP_LEVEL
- pyparsing.py
-)
-
+PY_SRCS(
+ TOP_LEVEL
+ pyparsing.py
+)
+
RESOURCE_FILES(
PREFIX contrib/python/pyparsing/py2/
.dist-info/METADATA
.dist-info/top_level.txt
)
-END()
+END()
diff --git a/contrib/python/pyparsing/py3/ya.make b/contrib/python/pyparsing/py3/ya.make
index 3a8c9d017b..333141d6c4 100644
--- a/contrib/python/pyparsing/py3/ya.make
+++ b/contrib/python/pyparsing/py3/ya.make
@@ -1,7 +1,7 @@
# Generated by devtools/yamaker (pypi).
PY3_LIBRARY()
-
+
PROVIDES(pyparsing)
OWNER(borman orivej g:python-contrib)
@@ -16,8 +16,8 @@ NO_CHECK_IMPORTS(
pyparsing.diagram.*
)
-PY_SRCS(
- TOP_LEVEL
+PY_SRCS(
+ TOP_LEVEL
pyparsing/__init__.py
pyparsing/actions.py
pyparsing/common.py
@@ -29,8 +29,8 @@ PY_SRCS(
pyparsing/testing.py
pyparsing/unicode.py
pyparsing/util.py
-)
-
+)
+
RESOURCE_FILES(
PREFIX contrib/python/pyparsing/py3/
.dist-info/METADATA
@@ -38,4 +38,4 @@ RESOURCE_FILES(
pyparsing/diagram/template.jinja2
)
-END()
+END()
diff --git a/contrib/python/pyparsing/ya.make b/contrib/python/pyparsing/ya.make
index db8aa4fbf6..66da70626d 100644
--- a/contrib/python/pyparsing/ya.make
+++ b/contrib/python/pyparsing/ya.make
@@ -1,5 +1,5 @@
PY23_LIBRARY()
-
+
LICENSE(Service-Py23-Proxy)
OWNER(g:python-contrib)
@@ -13,7 +13,7 @@ ENDIF()
NO_LINT()
END()
-
+
RECURSE(
py2
py3
diff --git a/contrib/python/setuptools/py2/pkg_resources/__init__.py b/contrib/python/setuptools/py2/pkg_resources/__init__.py
index 7f5c87e858..649a2ce651 100644
--- a/contrib/python/setuptools/py2/pkg_resources/__init__.py
+++ b/contrib/python/setuptools/py2/pkg_resources/__init__.py
@@ -1,81 +1,81 @@
# coding: utf-8
-"""
-Package resource API
---------------------
-
-A resource is a logical file contained within a package, or a logical
-subdirectory thereof. The package resource API expects resource names
-to have their path parts separated with ``/``, *not* whatever the local
-path separator is. Do not use os.path operations to manipulate resource
-names being passed into the API.
-
-The package resource API is designed to work with normal filesystem packages,
-.egg files, and unpacked .egg files. It can also work in a limited way with
-.zip files and with custom PEP 302 loaders that support the ``get_data()``
-method.
-"""
-
-from __future__ import absolute_import
-
-import sys
-import os
-import io
-import time
-import re
-import types
-import zipfile
-import zipimport
-import warnings
-import stat
-import functools
-import pkgutil
-import operator
-import platform
-import collections
-import plistlib
-import email.parser
+"""
+Package resource API
+--------------------
+
+A resource is a logical file contained within a package, or a logical
+subdirectory thereof. The package resource API expects resource names
+to have their path parts separated with ``/``, *not* whatever the local
+path separator is. Do not use os.path operations to manipulate resource
+names being passed into the API.
+
+The package resource API is designed to work with normal filesystem packages,
+.egg files, and unpacked .egg files. It can also work in a limited way with
+.zip files and with custom PEP 302 loaders that support the ``get_data()``
+method.
+"""
+
+from __future__ import absolute_import
+
+import sys
+import os
+import io
+import time
+import re
+import types
+import zipfile
+import zipimport
+import warnings
+import stat
+import functools
+import pkgutil
+import operator
+import platform
+import collections
+import plistlib
+import email.parser
import errno
-import tempfile
-import textwrap
+import tempfile
+import textwrap
import itertools
import inspect
import ntpath
import posixpath
-from pkgutil import get_importer
-
-try:
- import _imp
-except ImportError:
- # Python 3.2 compatibility
- import imp as _imp
-
+from pkgutil import get_importer
+
+try:
+ import _imp
+except ImportError:
+ # Python 3.2 compatibility
+ import imp as _imp
+
try:
FileExistsError
except NameError:
FileExistsError = OSError
-
+
from pkg_resources.extern import six
from pkg_resources.extern.six.moves import urllib, map, filter
-# capture these to bypass sandboxing
-from os import utime
-try:
- from os import mkdir, rename, unlink
- WRITE_SUPPORT = True
-except ImportError:
- # no write support, probably under GAE
- WRITE_SUPPORT = False
-
-from os import open as os_open
-from os.path import isdir, split
-
-try:
- import importlib.machinery as importlib_machinery
- # access attribute to force import under delayed import mechanisms.
- importlib_machinery.__name__
-except ImportError:
- importlib_machinery = None
-
+# capture these to bypass sandboxing
+from os import utime
+try:
+ from os import mkdir, rename, unlink
+ WRITE_SUPPORT = True
+except ImportError:
+ # no write support, probably under GAE
+ WRITE_SUPPORT = False
+
+from os import open as os_open
+from os.path import isdir, split
+
+try:
+ import importlib.machinery as importlib_machinery
+ # access attribute to force import under delayed import mechanisms.
+ importlib_machinery.__name__
+except ImportError:
+ importlib_machinery = None
+
from . import py31compat
from pkg_resources.extern import appdirs
from pkg_resources.extern import packaging
@@ -83,8 +83,8 @@ __import__('pkg_resources.extern.packaging.version')
__import__('pkg_resources.extern.packaging.specifiers')
__import__('pkg_resources.extern.packaging.requirements')
__import__('pkg_resources.extern.packaging.markers')
-
-
+
+
__metaclass__ = type
@@ -96,10 +96,10 @@ if six.PY2:
PermissionError = None
NotADirectoryError = None
-# declare some globals that will be defined later to
-# satisfy the linters.
-require = None
-working_set = None
+# declare some globals that will be defined later to
+# satisfy the linters.
+require = None
+working_set = None
add_activation_listener = None
resources_stream = None
cleanup_resources = None
@@ -115,827 +115,827 @@ resource_exists = None
_distribution_finders = None
_namespace_handlers = None
_namespace_packages = None
-
-
-class PEP440Warning(RuntimeWarning):
- """
- Used when there is an issue with a version or specifier not complying with
- PEP 440.
- """
-
-
-def parse_version(v):
- try:
+
+
+class PEP440Warning(RuntimeWarning):
+ """
+ Used when there is an issue with a version or specifier not complying with
+ PEP 440.
+ """
+
+
+def parse_version(v):
+ try:
return packaging.version.Version(v)
- except packaging.version.InvalidVersion:
+ except packaging.version.InvalidVersion:
return packaging.version.LegacyVersion(v)
-
-
-_state_vars = {}
-
-
-def _declare_state(vartype, **kw):
- globals().update(kw)
- _state_vars.update(dict.fromkeys(kw, vartype))
-
-
-def __getstate__():
- state = {}
- g = globals()
- for k, v in _state_vars.items():
+
+
+_state_vars = {}
+
+
+def _declare_state(vartype, **kw):
+ globals().update(kw)
+ _state_vars.update(dict.fromkeys(kw, vartype))
+
+
+def __getstate__():
+ state = {}
+ g = globals()
+ for k, v in _state_vars.items():
state[k] = g['_sget_' + v](g[k])
- return state
-
+ return state
+
-def __setstate__(state):
- g = globals()
- for k, v in state.items():
+def __setstate__(state):
+ g = globals()
+ for k, v in state.items():
g['_sset_' + _state_vars[k]](k, g[k], v)
- return state
-
-
-def _sget_dict(val):
- return val.copy()
-
-
-def _sset_dict(key, ob, state):
- ob.clear()
- ob.update(state)
-
-
-def _sget_object(val):
- return val.__getstate__()
-
-
-def _sset_object(key, ob, state):
- ob.__setstate__(state)
-
-
-_sget_none = _sset_none = lambda *args: None
-
-
-def get_supported_platform():
- """Return this platform's maximum compatible version.
-
- distutils.util.get_platform() normally reports the minimum version
- of Mac OS X that would be required to *use* extensions produced by
- distutils. But what we want when checking compatibility is to know the
- version of Mac OS X that we are *running*. To allow usage of packages that
- explicitly require a newer version of Mac OS X, we must also know the
- current version of the OS.
-
- If this condition occurs for any other platform with a version in its
- platform strings, this function should be extended accordingly.
- """
- plat = get_build_platform()
- m = macosVersionString.match(plat)
- if m is not None and sys.platform == "darwin":
- try:
- plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))
- except ValueError:
- # not Mac OS X
- pass
- return plat
-
-
-__all__ = [
- # Basic resource access and distribution/entry point discovery
+ return state
+
+
+def _sget_dict(val):
+ return val.copy()
+
+
+def _sset_dict(key, ob, state):
+ ob.clear()
+ ob.update(state)
+
+
+def _sget_object(val):
+ return val.__getstate__()
+
+
+def _sset_object(key, ob, state):
+ ob.__setstate__(state)
+
+
+_sget_none = _sset_none = lambda *args: None
+
+
+def get_supported_platform():
+ """Return this platform's maximum compatible version.
+
+ distutils.util.get_platform() normally reports the minimum version
+ of Mac OS X that would be required to *use* extensions produced by
+ distutils. But what we want when checking compatibility is to know the
+ version of Mac OS X that we are *running*. To allow usage of packages that
+ explicitly require a newer version of Mac OS X, we must also know the
+ current version of the OS.
+
+ If this condition occurs for any other platform with a version in its
+ platform strings, this function should be extended accordingly.
+ """
+ plat = get_build_platform()
+ m = macosVersionString.match(plat)
+ if m is not None and sys.platform == "darwin":
+ try:
+ plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))
+ except ValueError:
+ # not Mac OS X
+ pass
+ return plat
+
+
+__all__ = [
+ # Basic resource access and distribution/entry point discovery
'require', 'run_script', 'get_provider', 'get_distribution',
- 'load_entry_point', 'get_entry_map', 'get_entry_info',
- 'iter_entry_points',
- 'resource_string', 'resource_stream', 'resource_filename',
- 'resource_listdir', 'resource_exists', 'resource_isdir',
-
- # Environmental control
- 'declare_namespace', 'working_set', 'add_activation_listener',
- 'find_distributions', 'set_extraction_path', 'cleanup_resources',
- 'get_default_cache',
-
- # Primary implementation classes
- 'Environment', 'WorkingSet', 'ResourceManager',
- 'Distribution', 'Requirement', 'EntryPoint',
-
- # Exceptions
- 'ResolutionError', 'VersionConflict', 'DistributionNotFound',
- 'UnknownExtra', 'ExtractionError',
-
- # Warnings
- 'PEP440Warning',
-
- # Parsing functions and string utilities
- 'parse_requirements', 'parse_version', 'safe_name', 'safe_version',
- 'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',
- 'safe_extra', 'to_filename', 'invalid_marker', 'evaluate_marker',
-
- # filesystem utilities
- 'ensure_directory', 'normalize_path',
-
- # Distribution "precedence" constants
- 'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',
-
- # "Provider" interfaces, implementations, and registration/lookup APIs
- 'IMetadataProvider', 'IResourceProvider', 'FileMetadata',
- 'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',
- 'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',
- 'register_finder', 'register_namespace_handler', 'register_loader_type',
- 'fixup_namespace_packages', 'get_importer',
-
+ 'load_entry_point', 'get_entry_map', 'get_entry_info',
+ 'iter_entry_points',
+ 'resource_string', 'resource_stream', 'resource_filename',
+ 'resource_listdir', 'resource_exists', 'resource_isdir',
+
+ # Environmental control
+ 'declare_namespace', 'working_set', 'add_activation_listener',
+ 'find_distributions', 'set_extraction_path', 'cleanup_resources',
+ 'get_default_cache',
+
+ # Primary implementation classes
+ 'Environment', 'WorkingSet', 'ResourceManager',
+ 'Distribution', 'Requirement', 'EntryPoint',
+
+ # Exceptions
+ 'ResolutionError', 'VersionConflict', 'DistributionNotFound',
+ 'UnknownExtra', 'ExtractionError',
+
+ # Warnings
+ 'PEP440Warning',
+
+ # Parsing functions and string utilities
+ 'parse_requirements', 'parse_version', 'safe_name', 'safe_version',
+ 'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',
+ 'safe_extra', 'to_filename', 'invalid_marker', 'evaluate_marker',
+
+ # filesystem utilities
+ 'ensure_directory', 'normalize_path',
+
+ # Distribution "precedence" constants
+ 'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',
+
+ # "Provider" interfaces, implementations, and registration/lookup APIs
+ 'IMetadataProvider', 'IResourceProvider', 'FileMetadata',
+ 'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',
+ 'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',
+ 'register_finder', 'register_namespace_handler', 'register_loader_type',
+ 'fixup_namespace_packages', 'get_importer',
+
# Warnings
'PkgResourcesDeprecationWarning',
- # Deprecated/backward compatibility only
- 'run_main', 'AvailableDistributions',
-]
-
+ # Deprecated/backward compatibility only
+ 'run_main', 'AvailableDistributions',
+]
+
-class ResolutionError(Exception):
- """Abstract base for dependency resolution errors"""
+class ResolutionError(Exception):
+ """Abstract base for dependency resolution errors"""
- def __repr__(self):
+ def __repr__(self):
return self.__class__.__name__ + repr(self.args)
-
-
-class VersionConflict(ResolutionError):
- """
- An already-installed version conflicts with the requested version.
-
- Should be initialized with the installed Distribution and the requested
- Requirement.
- """
-
- _template = "{self.dist} is installed but {self.req} is required"
-
- @property
- def dist(self):
- return self.args[0]
-
- @property
- def req(self):
- return self.args[1]
-
- def report(self):
- return self._template.format(**locals())
-
- def with_context(self, required_by):
- """
- If required_by is non-empty, return a version of self that is a
- ContextualVersionConflict.
- """
- if not required_by:
- return self
- args = self.args + (required_by,)
- return ContextualVersionConflict(*args)
-
-
-class ContextualVersionConflict(VersionConflict):
- """
- A VersionConflict that accepts a third parameter, the set of the
- requirements that required the installed Distribution.
- """
-
- _template = VersionConflict._template + ' by {self.required_by}'
-
- @property
- def required_by(self):
- return self.args[2]
-
-
-class DistributionNotFound(ResolutionError):
- """A requested distribution was not found"""
-
- _template = ("The '{self.req}' distribution was not found "
- "and is required by {self.requirers_str}")
-
- @property
- def req(self):
- return self.args[0]
-
- @property
- def requirers(self):
- return self.args[1]
-
- @property
- def requirers_str(self):
- if not self.requirers:
- return 'the application'
- return ', '.join(self.requirers)
-
- def report(self):
- return self._template.format(**locals())
-
- def __str__(self):
- return self.report()
-
-
-class UnknownExtra(ResolutionError):
- """Distribution doesn't have an "extra feature" of the given name"""
-
-
-_provider_factories = {}
-
+
+
+class VersionConflict(ResolutionError):
+ """
+ An already-installed version conflicts with the requested version.
+
+ Should be initialized with the installed Distribution and the requested
+ Requirement.
+ """
+
+ _template = "{self.dist} is installed but {self.req} is required"
+
+ @property
+ def dist(self):
+ return self.args[0]
+
+ @property
+ def req(self):
+ return self.args[1]
+
+ def report(self):
+ return self._template.format(**locals())
+
+ def with_context(self, required_by):
+ """
+ If required_by is non-empty, return a version of self that is a
+ ContextualVersionConflict.
+ """
+ if not required_by:
+ return self
+ args = self.args + (required_by,)
+ return ContextualVersionConflict(*args)
+
+
+class ContextualVersionConflict(VersionConflict):
+ """
+ A VersionConflict that accepts a third parameter, the set of the
+ requirements that required the installed Distribution.
+ """
+
+ _template = VersionConflict._template + ' by {self.required_by}'
+
+ @property
+ def required_by(self):
+ return self.args[2]
+
+
+class DistributionNotFound(ResolutionError):
+ """A requested distribution was not found"""
+
+ _template = ("The '{self.req}' distribution was not found "
+ "and is required by {self.requirers_str}")
+
+ @property
+ def req(self):
+ return self.args[0]
+
+ @property
+ def requirers(self):
+ return self.args[1]
+
+ @property
+ def requirers_str(self):
+ if not self.requirers:
+ return 'the application'
+ return ', '.join(self.requirers)
+
+ def report(self):
+ return self._template.format(**locals())
+
+ def __str__(self):
+ return self.report()
+
+
+class UnknownExtra(ResolutionError):
+ """Distribution doesn't have an "extra feature" of the given name"""
+
+
+_provider_factories = {}
+
PY_MAJOR = '{}.{}'.format(*sys.version_info)
-EGG_DIST = 3
-BINARY_DIST = 2
-SOURCE_DIST = 1
-CHECKOUT_DIST = 0
-DEVELOP_DIST = -1
-
-
-def register_loader_type(loader_type, provider_factory):
- """Register `provider_factory` to make providers for `loader_type`
-
- `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
- and `provider_factory` is a function that, passed a *module* object,
- returns an ``IResourceProvider`` for that module.
- """
- _provider_factories[loader_type] = provider_factory
-
-
-def get_provider(moduleOrReq):
- """Return an IResourceProvider for the named module or requirement"""
- if isinstance(moduleOrReq, Requirement):
- return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
- try:
- module = sys.modules[moduleOrReq]
- except KeyError:
- __import__(moduleOrReq)
- module = sys.modules[moduleOrReq]
- loader = getattr(module, '__loader__', None)
- return _find_adapter(_provider_factories, loader)(module)
-
-
-def _macosx_vers(_cache=[]):
- if not _cache:
- version = platform.mac_ver()[0]
- # fallback for MacPorts
- if version == '':
- plist = '/System/Library/CoreServices/SystemVersion.plist'
- if os.path.exists(plist):
- if hasattr(plistlib, 'readPlist'):
- plist_content = plistlib.readPlist(plist)
- if 'ProductVersion' in plist_content:
- version = plist_content['ProductVersion']
-
- _cache.append(version.split('.'))
- return _cache[0]
-
-
-def _macosx_arch(machine):
- return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
-
-
-def get_build_platform():
- """Return this platform's string for platform-specific distributions
-
- XXX Currently this is the same as ``distutils.util.get_platform()``, but it
- needs some hacks for Linux and Mac OS X.
- """
+EGG_DIST = 3
+BINARY_DIST = 2
+SOURCE_DIST = 1
+CHECKOUT_DIST = 0
+DEVELOP_DIST = -1
+
+
+def register_loader_type(loader_type, provider_factory):
+ """Register `provider_factory` to make providers for `loader_type`
+
+ `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
+ and `provider_factory` is a function that, passed a *module* object,
+ returns an ``IResourceProvider`` for that module.
+ """
+ _provider_factories[loader_type] = provider_factory
+
+
+def get_provider(moduleOrReq):
+ """Return an IResourceProvider for the named module or requirement"""
+ if isinstance(moduleOrReq, Requirement):
+ return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
+ try:
+ module = sys.modules[moduleOrReq]
+ except KeyError:
+ __import__(moduleOrReq)
+ module = sys.modules[moduleOrReq]
+ loader = getattr(module, '__loader__', None)
+ return _find_adapter(_provider_factories, loader)(module)
+
+
+def _macosx_vers(_cache=[]):
+ if not _cache:
+ version = platform.mac_ver()[0]
+ # fallback for MacPorts
+ if version == '':
+ plist = '/System/Library/CoreServices/SystemVersion.plist'
+ if os.path.exists(plist):
+ if hasattr(plistlib, 'readPlist'):
+ plist_content = plistlib.readPlist(plist)
+ if 'ProductVersion' in plist_content:
+ version = plist_content['ProductVersion']
+
+ _cache.append(version.split('.'))
+ return _cache[0]
+
+
+def _macosx_arch(machine):
+ return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
+
+
+def get_build_platform():
+ """Return this platform's string for platform-specific distributions
+
+ XXX Currently this is the same as ``distutils.util.get_platform()``, but it
+ needs some hacks for Linux and Mac OS X.
+ """
from sysconfig import get_platform
-
- plat = get_platform()
- if sys.platform == "darwin" and not plat.startswith('macosx-'):
- try:
- version = _macosx_vers()
- machine = os.uname()[4].replace(" ", "_")
+
+ plat = get_platform()
+ if sys.platform == "darwin" and not plat.startswith('macosx-'):
+ try:
+ version = _macosx_vers()
+ machine = os.uname()[4].replace(" ", "_")
return "macosx-%d.%d-%s" % (
int(version[0]), int(version[1]),
_macosx_arch(machine),
)
- except ValueError:
- # if someone is running a non-Mac darwin system, this will fall
- # through to the default implementation
- pass
- return plat
-
-
-macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
-darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
-# XXX backward compat
-get_platform = get_build_platform
-
-
-def compatible_platforms(provided, required):
- """Can code for the `provided` platform run on the `required` platform?
-
- Returns true if either platform is ``None``, or the platforms are equal.
-
- XXX Needs compatibility checks for Linux and other unixy OSes.
- """
+ except ValueError:
+ # if someone is running a non-Mac darwin system, this will fall
+ # through to the default implementation
+ pass
+ return plat
+
+
+macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
+darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
+# XXX backward compat
+get_platform = get_build_platform
+
+
+def compatible_platforms(provided, required):
+ """Can code for the `provided` platform run on the `required` platform?
+
+ Returns true if either platform is ``None``, or the platforms are equal.
+
+ XXX Needs compatibility checks for Linux and other unixy OSes.
+ """
if provided is None or required is None or provided == required:
- # easy case
- return True
-
- # Mac OS X special cases
- reqMac = macosVersionString.match(required)
- if reqMac:
- provMac = macosVersionString.match(provided)
-
- # is this a Mac package?
- if not provMac:
- # this is backwards compatibility for packages built before
- # setuptools 0.6. All packages built after this point will
- # use the new macosx designation.
- provDarwin = darwinVersionString.match(provided)
- if provDarwin:
- dversion = int(provDarwin.group(1))
- macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
- if dversion == 7 and macosversion >= "10.3" or \
- dversion == 8 and macosversion >= "10.4":
- return True
- # egg isn't macosx or legacy darwin
- return False
-
- # are they the same major version and machine type?
- if provMac.group(1) != reqMac.group(1) or \
- provMac.group(3) != reqMac.group(3):
- return False
-
- # is the required OS major update >= the provided one?
- if int(provMac.group(2)) > int(reqMac.group(2)):
- return False
-
- return True
-
- # XXX Linux and other platforms' special cases should go here
- return False
-
-
-def run_script(dist_spec, script_name):
- """Locate distribution `dist_spec` and run its `script_name` script"""
- ns = sys._getframe(1).f_globals
- name = ns['__name__']
- ns.clear()
- ns['__name__'] = name
- require(dist_spec)[0].run_script(script_name, ns)
-
-
-# backward compatibility
-run_main = run_script
-
-
-def get_distribution(dist):
- """Return a current distribution object for a Requirement or string"""
- if isinstance(dist, six.string_types):
- dist = Requirement.parse(dist)
- if isinstance(dist, Requirement):
- dist = get_provider(dist)
- if not isinstance(dist, Distribution):
- raise TypeError("Expected string, Requirement, or Distribution", dist)
- return dist
-
-
-def load_entry_point(dist, group, name):
- """Return `name` entry point of `group` for `dist` or raise ImportError"""
- return get_distribution(dist).load_entry_point(group, name)
-
-
-def get_entry_map(dist, group=None):
- """Return the entry point map for `group`, or the full entry map"""
- return get_distribution(dist).get_entry_map(group)
-
-
-def get_entry_info(dist, group, name):
- """Return the EntryPoint object for `group`+`name`, or ``None``"""
- return get_distribution(dist).get_entry_info(group, name)
-
-
-class IMetadataProvider:
- def has_metadata(name):
- """Does the package's distribution contain the named metadata?"""
-
- def get_metadata(name):
- """The named metadata resource as a string"""
-
- def get_metadata_lines(name):
- """Yield named metadata resource as list of non-blank non-comment lines
-
- Leading and trailing whitespace is stripped from each line, and lines
- with ``#`` as the first non-blank character are omitted."""
-
- def metadata_isdir(name):
- """Is the named metadata a directory? (like ``os.path.isdir()``)"""
-
- def metadata_listdir(name):
- """List of metadata names in the directory (like ``os.listdir()``)"""
-
- def run_script(script_name, namespace):
- """Execute the named script in the supplied namespace dictionary"""
-
-
-class IResourceProvider(IMetadataProvider):
- """An object that provides access to package resources"""
-
- def get_resource_filename(manager, resource_name):
- """Return a true filesystem path for `resource_name`
-
- `manager` must be an ``IResourceManager``"""
-
- def get_resource_stream(manager, resource_name):
- """Return a readable file-like object for `resource_name`
-
- `manager` must be an ``IResourceManager``"""
-
- def get_resource_string(manager, resource_name):
- """Return a string containing the contents of `resource_name`
-
- `manager` must be an ``IResourceManager``"""
-
- def has_resource(resource_name):
- """Does the package contain the named resource?"""
-
- def resource_isdir(resource_name):
- """Is the named resource a directory? (like ``os.path.isdir()``)"""
-
- def resource_listdir(resource_name):
- """List of resource names in the directory (like ``os.listdir()``)"""
-
-
+ # easy case
+ return True
+
+ # Mac OS X special cases
+ reqMac = macosVersionString.match(required)
+ if reqMac:
+ provMac = macosVersionString.match(provided)
+
+ # is this a Mac package?
+ if not provMac:
+ # this is backwards compatibility for packages built before
+ # setuptools 0.6. All packages built after this point will
+ # use the new macosx designation.
+ provDarwin = darwinVersionString.match(provided)
+ if provDarwin:
+ dversion = int(provDarwin.group(1))
+ macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
+ if dversion == 7 and macosversion >= "10.3" or \
+ dversion == 8 and macosversion >= "10.4":
+ return True
+ # egg isn't macosx or legacy darwin
+ return False
+
+ # are they the same major version and machine type?
+ if provMac.group(1) != reqMac.group(1) or \
+ provMac.group(3) != reqMac.group(3):
+ return False
+
+ # is the required OS major update >= the provided one?
+ if int(provMac.group(2)) > int(reqMac.group(2)):
+ return False
+
+ return True
+
+ # XXX Linux and other platforms' special cases should go here
+ return False
+
+
+def run_script(dist_spec, script_name):
+ """Locate distribution `dist_spec` and run its `script_name` script"""
+ ns = sys._getframe(1).f_globals
+ name = ns['__name__']
+ ns.clear()
+ ns['__name__'] = name
+ require(dist_spec)[0].run_script(script_name, ns)
+
+
+# backward compatibility
+run_main = run_script
+
+
+def get_distribution(dist):
+ """Return a current distribution object for a Requirement or string"""
+ if isinstance(dist, six.string_types):
+ dist = Requirement.parse(dist)
+ if isinstance(dist, Requirement):
+ dist = get_provider(dist)
+ if not isinstance(dist, Distribution):
+ raise TypeError("Expected string, Requirement, or Distribution", dist)
+ return dist
+
+
+def load_entry_point(dist, group, name):
+ """Return `name` entry point of `group` for `dist` or raise ImportError"""
+ return get_distribution(dist).load_entry_point(group, name)
+
+
+def get_entry_map(dist, group=None):
+ """Return the entry point map for `group`, or the full entry map"""
+ return get_distribution(dist).get_entry_map(group)
+
+
+def get_entry_info(dist, group, name):
+ """Return the EntryPoint object for `group`+`name`, or ``None``"""
+ return get_distribution(dist).get_entry_info(group, name)
+
+
+class IMetadataProvider:
+ def has_metadata(name):
+ """Does the package's distribution contain the named metadata?"""
+
+ def get_metadata(name):
+ """The named metadata resource as a string"""
+
+ def get_metadata_lines(name):
+ """Yield named metadata resource as list of non-blank non-comment lines
+
+ Leading and trailing whitespace is stripped from each line, and lines
+ with ``#`` as the first non-blank character are omitted."""
+
+ def metadata_isdir(name):
+ """Is the named metadata a directory? (like ``os.path.isdir()``)"""
+
+ def metadata_listdir(name):
+ """List of metadata names in the directory (like ``os.listdir()``)"""
+
+ def run_script(script_name, namespace):
+ """Execute the named script in the supplied namespace dictionary"""
+
+
+class IResourceProvider(IMetadataProvider):
+ """An object that provides access to package resources"""
+
+ def get_resource_filename(manager, resource_name):
+ """Return a true filesystem path for `resource_name`
+
+ `manager` must be an ``IResourceManager``"""
+
+ def get_resource_stream(manager, resource_name):
+ """Return a readable file-like object for `resource_name`
+
+ `manager` must be an ``IResourceManager``"""
+
+ def get_resource_string(manager, resource_name):
+ """Return a string containing the contents of `resource_name`
+
+ `manager` must be an ``IResourceManager``"""
+
+ def has_resource(resource_name):
+ """Does the package contain the named resource?"""
+
+ def resource_isdir(resource_name):
+ """Is the named resource a directory? (like ``os.path.isdir()``)"""
+
+ def resource_listdir(resource_name):
+ """List of resource names in the directory (like ``os.listdir()``)"""
+
+
class WorkingSet:
- """A collection of active distributions on sys.path (or a similar list)"""
-
- def __init__(self, entries=None):
- """Create working set from list of path entries (default=sys.path)"""
- self.entries = []
- self.entry_keys = {}
- self.by_key = {}
- self.callbacks = []
-
- if entries is None:
- entries = sys.path
-
- for entry in entries:
- self.add_entry(entry)
-
- @classmethod
- def _build_master(cls):
- """
- Prepare the master working set.
- """
- ws = cls()
- try:
- from __main__ import __requires__
- except ImportError:
- # The main program does not list any requirements
- return ws
-
- # ensure the requirements are met
- try:
- ws.require(__requires__)
- except VersionConflict:
- return cls._build_from_requirements(__requires__)
-
- return ws
-
- @classmethod
- def _build_from_requirements(cls, req_spec):
- """
- Build a working set from a requirement spec. Rewrites sys.path.
- """
- # try it without defaults already on sys.path
- # by starting with an empty path
- ws = cls([])
- reqs = parse_requirements(req_spec)
- dists = ws.resolve(reqs, Environment())
- for dist in dists:
- ws.add(dist)
-
- # add any missing entries from sys.path
- for entry in sys.path:
- if entry not in ws.entries:
- ws.add_entry(entry)
-
- # then copy back to sys.path
- sys.path[:] = ws.entries
- return ws
-
- def add_entry(self, entry):
- """Add a path item to ``.entries``, finding any distributions on it
-
- ``find_distributions(entry, True)`` is used to find distributions
- corresponding to the path entry, and they are added. `entry` is
- always appended to ``.entries``, even if it is already present.
- (This is because ``sys.path`` can contain the same value more than
- once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
- equal ``sys.path``.)
- """
- self.entry_keys.setdefault(entry, [])
- self.entries.append(entry)
- for dist in find_distributions(entry, True):
- self.add(dist, entry, False)
-
- def __contains__(self, dist):
- """True if `dist` is the active distribution for its project"""
- return self.by_key.get(dist.key) == dist
-
- def find(self, req):
- """Find a distribution matching requirement `req`
-
- If there is an active distribution for the requested project, this
- returns it as long as it meets the version requirement specified by
- `req`. But, if there is an active distribution for the project and it
- does *not* meet the `req` requirement, ``VersionConflict`` is raised.
- If there is no active distribution for the requested project, ``None``
- is returned.
- """
- dist = self.by_key.get(req.key)
- if dist is not None and dist not in req:
- # XXX add more info
- raise VersionConflict(dist, req)
- return dist
-
- def iter_entry_points(self, group, name=None):
- """Yield entry point objects from `group` matching `name`
-
- If `name` is None, yields all entry points in `group` from all
- distributions in the working set, otherwise only ones matching
- both `group` and `name` are yielded (in distribution order).
- """
+ """A collection of active distributions on sys.path (or a similar list)"""
+
+ def __init__(self, entries=None):
+ """Create working set from list of path entries (default=sys.path)"""
+ self.entries = []
+ self.entry_keys = {}
+ self.by_key = {}
+ self.callbacks = []
+
+ if entries is None:
+ entries = sys.path
+
+ for entry in entries:
+ self.add_entry(entry)
+
+ @classmethod
+ def _build_master(cls):
+ """
+ Prepare the master working set.
+ """
+ ws = cls()
+ try:
+ from __main__ import __requires__
+ except ImportError:
+ # The main program does not list any requirements
+ return ws
+
+ # ensure the requirements are met
+ try:
+ ws.require(__requires__)
+ except VersionConflict:
+ return cls._build_from_requirements(__requires__)
+
+ return ws
+
+ @classmethod
+ def _build_from_requirements(cls, req_spec):
+ """
+ Build a working set from a requirement spec. Rewrites sys.path.
+ """
+ # try it without defaults already on sys.path
+ # by starting with an empty path
+ ws = cls([])
+ reqs = parse_requirements(req_spec)
+ dists = ws.resolve(reqs, Environment())
+ for dist in dists:
+ ws.add(dist)
+
+ # add any missing entries from sys.path
+ for entry in sys.path:
+ if entry not in ws.entries:
+ ws.add_entry(entry)
+
+ # then copy back to sys.path
+ sys.path[:] = ws.entries
+ return ws
+
+ def add_entry(self, entry):
+ """Add a path item to ``.entries``, finding any distributions on it
+
+ ``find_distributions(entry, True)`` is used to find distributions
+ corresponding to the path entry, and they are added. `entry` is
+ always appended to ``.entries``, even if it is already present.
+ (This is because ``sys.path`` can contain the same value more than
+ once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
+ equal ``sys.path``.)
+ """
+ self.entry_keys.setdefault(entry, [])
+ self.entries.append(entry)
+ for dist in find_distributions(entry, True):
+ self.add(dist, entry, False)
+
+ def __contains__(self, dist):
+ """True if `dist` is the active distribution for its project"""
+ return self.by_key.get(dist.key) == dist
+
+ def find(self, req):
+ """Find a distribution matching requirement `req`
+
+ If there is an active distribution for the requested project, this
+ returns it as long as it meets the version requirement specified by
+ `req`. But, if there is an active distribution for the project and it
+ does *not* meet the `req` requirement, ``VersionConflict`` is raised.
+ If there is no active distribution for the requested project, ``None``
+ is returned.
+ """
+ dist = self.by_key.get(req.key)
+ if dist is not None and dist not in req:
+ # XXX add more info
+ raise VersionConflict(dist, req)
+ return dist
+
+ def iter_entry_points(self, group, name=None):
+ """Yield entry point objects from `group` matching `name`
+
+ If `name` is None, yields all entry points in `group` from all
+ distributions in the working set, otherwise only ones matching
+ both `group` and `name` are yielded (in distribution order).
+ """
return (
entry
for dist in self
for entry in dist.get_entry_map(group).values()
if name is None or name == entry.name
)
-
- def run_script(self, requires, script_name):
- """Locate distribution for `requires` and run `script_name` script"""
- ns = sys._getframe(1).f_globals
- name = ns['__name__']
- ns.clear()
- ns['__name__'] = name
- self.require(requires)[0].run_script(script_name, ns)
-
- def __iter__(self):
- """Yield distributions for non-duplicate projects in the working set
-
- The yield order is the order in which the items' path entries were
- added to the working set.
- """
- seen = {}
- for item in self.entries:
- if item not in self.entry_keys:
- # workaround a cache issue
- continue
-
- for key in self.entry_keys[item]:
- if key not in seen:
+
+ def run_script(self, requires, script_name):
+ """Locate distribution for `requires` and run `script_name` script"""
+ ns = sys._getframe(1).f_globals
+ name = ns['__name__']
+ ns.clear()
+ ns['__name__'] = name
+ self.require(requires)[0].run_script(script_name, ns)
+
+ def __iter__(self):
+ """Yield distributions for non-duplicate projects in the working set
+
+ The yield order is the order in which the items' path entries were
+ added to the working set.
+ """
+ seen = {}
+ for item in self.entries:
+ if item not in self.entry_keys:
+ # workaround a cache issue
+ continue
+
+ for key in self.entry_keys[item]:
+ if key not in seen:
seen[key] = 1
- yield self.by_key[key]
-
- def add(self, dist, entry=None, insert=True, replace=False):
- """Add `dist` to working set, associated with `entry`
-
- If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
- On exit from this routine, `entry` is added to the end of the working
- set's ``.entries`` (if it wasn't already present).
-
- `dist` is only added to the working set if it's for a project that
- doesn't already have a distribution in the set, unless `replace=True`.
- If it's added, any callbacks registered with the ``subscribe()`` method
- will be called.
- """
- if insert:
- dist.insert_on(self.entries, entry, replace=replace)
-
- if entry is None:
- entry = dist.location
+ yield self.by_key[key]
+
+ def add(self, dist, entry=None, insert=True, replace=False):
+ """Add `dist` to working set, associated with `entry`
+
+ If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
+ On exit from this routine, `entry` is added to the end of the working
+ set's ``.entries`` (if it wasn't already present).
+
+ `dist` is only added to the working set if it's for a project that
+ doesn't already have a distribution in the set, unless `replace=True`.
+ If it's added, any callbacks registered with the ``subscribe()`` method
+ will be called.
+ """
+ if insert:
+ dist.insert_on(self.entries, entry, replace=replace)
+
+ if entry is None:
+ entry = dist.location
keys = self.entry_keys.setdefault(entry, [])
keys2 = self.entry_keys.setdefault(dist.location, [])
- if not replace and dist.key in self.by_key:
- # ignore hidden distros
- return
-
- self.by_key[dist.key] = dist
- if dist.key not in keys:
- keys.append(dist.key)
- if dist.key not in keys2:
- keys2.append(dist.key)
- self._added_new(dist)
-
- def resolve(self, requirements, env=None, installer=None,
+ if not replace and dist.key in self.by_key:
+ # ignore hidden distros
+ return
+
+ self.by_key[dist.key] = dist
+ if dist.key not in keys:
+ keys.append(dist.key)
+ if dist.key not in keys2:
+ keys2.append(dist.key)
+ self._added_new(dist)
+
+ def resolve(self, requirements, env=None, installer=None,
replace_conflicting=False, extras=None):
- """List all distributions needed to (recursively) meet `requirements`
-
- `requirements` must be a sequence of ``Requirement`` objects. `env`,
- if supplied, should be an ``Environment`` instance. If
- not supplied, it defaults to all distributions available within any
- entry or distribution in the working set. `installer`, if supplied,
- will be invoked with each requirement that cannot be met by an
- already-installed distribution; it should return a ``Distribution`` or
- ``None``.
-
+ """List all distributions needed to (recursively) meet `requirements`
+
+ `requirements` must be a sequence of ``Requirement`` objects. `env`,
+ if supplied, should be an ``Environment`` instance. If
+ not supplied, it defaults to all distributions available within any
+ entry or distribution in the working set. `installer`, if supplied,
+ will be invoked with each requirement that cannot be met by an
+ already-installed distribution; it should return a ``Distribution`` or
+ ``None``.
+
Unless `replace_conflicting=True`, raises a VersionConflict exception
if
- any requirements are found on the path that have the correct name but
- the wrong version. Otherwise, if an `installer` is supplied it will be
- invoked to obtain the correct version of the requirement and activate
- it.
+ any requirements are found on the path that have the correct name but
+ the wrong version. Otherwise, if an `installer` is supplied it will be
+ invoked to obtain the correct version of the requirement and activate
+ it.
`extras` is a list of the extras to be used with these requirements.
This is important because extra requirements may look like `my_req;
extra = "my_extra"`, which would otherwise be interpreted as a purely
optional requirement. Instead, we want to be able to assert that these
requirements are truly required.
- """
-
- # set up the stack
- requirements = list(requirements)[::-1]
- # set of processed requirements
- processed = {}
- # key -> dist
- best = {}
- to_activate = []
-
+ """
+
+ # set up the stack
+ requirements = list(requirements)[::-1]
+ # set of processed requirements
+ processed = {}
+ # key -> dist
+ best = {}
+ to_activate = []
+
req_extras = _ReqExtras()
- # Mapping of requirement to set of distributions that required it;
- # useful for reporting info about conflicts.
- required_by = collections.defaultdict(set)
-
- while requirements:
- # process dependencies breadth-first
- req = requirements.pop(0)
- if req in processed:
- # Ignore cyclic or redundant dependencies
- continue
+ # Mapping of requirement to set of distributions that required it;
+ # useful for reporting info about conflicts.
+ required_by = collections.defaultdict(set)
+
+ while requirements:
+ # process dependencies breadth-first
+ req = requirements.pop(0)
+ if req in processed:
+ # Ignore cyclic or redundant dependencies
+ continue
if not req_extras.markers_pass(req, extras):
continue
- dist = best.get(req.key)
- if dist is None:
- # Find the best distribution and add it to the map
- dist = self.by_key.get(req.key)
- if dist is None or (dist not in req and replace_conflicting):
- ws = self
- if env is None:
- if dist is None:
- env = Environment(self.entries)
- else:
- # Use an empty environment and workingset to avoid
- # any further conflicts with the conflicting
- # distribution
- env = Environment([])
- ws = WorkingSet([])
+ dist = best.get(req.key)
+ if dist is None:
+ # Find the best distribution and add it to the map
+ dist = self.by_key.get(req.key)
+ if dist is None or (dist not in req and replace_conflicting):
+ ws = self
+ if env is None:
+ if dist is None:
+ env = Environment(self.entries)
+ else:
+ # Use an empty environment and workingset to avoid
+ # any further conflicts with the conflicting
+ # distribution
+ env = Environment([])
+ ws = WorkingSet([])
dist = best[req.key] = env.best_match(
req, ws, installer,
replace_conflicting=replace_conflicting
)
- if dist is None:
- requirers = required_by.get(req, None)
- raise DistributionNotFound(req, requirers)
- to_activate.append(dist)
- if dist not in req:
- # Oops, the "best" so far conflicts with a dependency
- dependent_req = required_by[req]
- raise VersionConflict(dist, req).with_context(dependent_req)
-
- # push the new requirements onto the stack
- new_requirements = dist.requires(req.extras)[::-1]
- requirements.extend(new_requirements)
-
- # Register the new requirements needed by req
- for new_requirement in new_requirements:
- required_by[new_requirement].add(req.project_name)
+ if dist is None:
+ requirers = required_by.get(req, None)
+ raise DistributionNotFound(req, requirers)
+ to_activate.append(dist)
+ if dist not in req:
+ # Oops, the "best" so far conflicts with a dependency
+ dependent_req = required_by[req]
+ raise VersionConflict(dist, req).with_context(dependent_req)
+
+ # push the new requirements onto the stack
+ new_requirements = dist.requires(req.extras)[::-1]
+ requirements.extend(new_requirements)
+
+ # Register the new requirements needed by req
+ for new_requirement in new_requirements:
+ required_by[new_requirement].add(req.project_name)
req_extras[new_requirement] = req.extras
-
- processed[req] = True
-
- # return list of distros to activate
- return to_activate
-
+
+ processed[req] = True
+
+ # return list of distros to activate
+ return to_activate
+
def find_plugins(
self, plugin_env, full_env=None, installer=None, fallback=True):
- """Find all activatable distributions in `plugin_env`
-
- Example usage::
-
- distributions, errors = working_set.find_plugins(
- Environment(plugin_dirlist)
- )
- # add plugins+libs to sys.path
- map(working_set.add, distributions)
- # display errors
- print('Could not load', errors)
-
- The `plugin_env` should be an ``Environment`` instance that contains
- only distributions that are in the project's "plugin directory" or
- directories. The `full_env`, if supplied, should be an ``Environment``
- contains all currently-available distributions. If `full_env` is not
- supplied, one is created automatically from the ``WorkingSet`` this
- method is called on, which will typically mean that every directory on
- ``sys.path`` will be scanned for distributions.
-
- `installer` is a standard installer callback as used by the
- ``resolve()`` method. The `fallback` flag indicates whether we should
- attempt to resolve older versions of a plugin if the newest version
- cannot be resolved.
-
- This method returns a 2-tuple: (`distributions`, `error_info`), where
- `distributions` is a list of the distributions found in `plugin_env`
- that were loadable, along with any other distributions that are needed
- to resolve their dependencies. `error_info` is a dictionary mapping
- unloadable plugin distributions to an exception instance describing the
- error that occurred. Usually this will be a ``DistributionNotFound`` or
- ``VersionConflict`` instance.
- """
-
- plugin_projects = list(plugin_env)
- # scan project names in alphabetic order
- plugin_projects.sort()
-
- error_info = {}
- distributions = {}
-
- if full_env is None:
- env = Environment(self.entries)
- env += plugin_env
- else:
- env = full_env + plugin_env
-
- shadow_set = self.__class__([])
- # put all our entries in shadow_set
- list(map(shadow_set.add, self))
-
- for project_name in plugin_projects:
-
- for dist in plugin_env[project_name]:
-
- req = [dist.as_requirement()]
-
- try:
- resolvees = shadow_set.resolve(req, env, installer)
-
- except ResolutionError as v:
- # save error info
- error_info[dist] = v
- if fallback:
- # try the next older version of project
- continue
- else:
- # give up on this project, keep going
- break
-
- else:
- list(map(shadow_set.add, resolvees))
- distributions.update(dict.fromkeys(resolvees))
-
- # success, no need to try any more versions of this project
- break
-
- distributions = list(distributions)
- distributions.sort()
-
- return distributions, error_info
-
- def require(self, *requirements):
- """Ensure that distributions matching `requirements` are activated
-
- `requirements` must be a string or a (possibly-nested) sequence
- thereof, specifying the distributions and versions required. The
- return value is a sequence of the distributions that needed to be
- activated to fulfill the requirements; all relevant distributions are
- included, even if they were already activated in this working set.
- """
- needed = self.resolve(parse_requirements(requirements))
-
- for dist in needed:
- self.add(dist)
-
- return needed
-
+ """Find all activatable distributions in `plugin_env`
+
+ Example usage::
+
+ distributions, errors = working_set.find_plugins(
+ Environment(plugin_dirlist)
+ )
+ # add plugins+libs to sys.path
+ map(working_set.add, distributions)
+ # display errors
+ print('Could not load', errors)
+
+ The `plugin_env` should be an ``Environment`` instance that contains
+ only distributions that are in the project's "plugin directory" or
+ directories. The `full_env`, if supplied, should be an ``Environment``
+ contains all currently-available distributions. If `full_env` is not
+ supplied, one is created automatically from the ``WorkingSet`` this
+ method is called on, which will typically mean that every directory on
+ ``sys.path`` will be scanned for distributions.
+
+ `installer` is a standard installer callback as used by the
+ ``resolve()`` method. The `fallback` flag indicates whether we should
+ attempt to resolve older versions of a plugin if the newest version
+ cannot be resolved.
+
+ This method returns a 2-tuple: (`distributions`, `error_info`), where
+ `distributions` is a list of the distributions found in `plugin_env`
+ that were loadable, along with any other distributions that are needed
+ to resolve their dependencies. `error_info` is a dictionary mapping
+ unloadable plugin distributions to an exception instance describing the
+ error that occurred. Usually this will be a ``DistributionNotFound`` or
+ ``VersionConflict`` instance.
+ """
+
+ plugin_projects = list(plugin_env)
+ # scan project names in alphabetic order
+ plugin_projects.sort()
+
+ error_info = {}
+ distributions = {}
+
+ if full_env is None:
+ env = Environment(self.entries)
+ env += plugin_env
+ else:
+ env = full_env + plugin_env
+
+ shadow_set = self.__class__([])
+ # put all our entries in shadow_set
+ list(map(shadow_set.add, self))
+
+ for project_name in plugin_projects:
+
+ for dist in plugin_env[project_name]:
+
+ req = [dist.as_requirement()]
+
+ try:
+ resolvees = shadow_set.resolve(req, env, installer)
+
+ except ResolutionError as v:
+ # save error info
+ error_info[dist] = v
+ if fallback:
+ # try the next older version of project
+ continue
+ else:
+ # give up on this project, keep going
+ break
+
+ else:
+ list(map(shadow_set.add, resolvees))
+ distributions.update(dict.fromkeys(resolvees))
+
+ # success, no need to try any more versions of this project
+ break
+
+ distributions = list(distributions)
+ distributions.sort()
+
+ return distributions, error_info
+
+ def require(self, *requirements):
+ """Ensure that distributions matching `requirements` are activated
+
+ `requirements` must be a string or a (possibly-nested) sequence
+ thereof, specifying the distributions and versions required. The
+ return value is a sequence of the distributions that needed to be
+ activated to fulfill the requirements; all relevant distributions are
+ included, even if they were already activated in this working set.
+ """
+ needed = self.resolve(parse_requirements(requirements))
+
+ for dist in needed:
+ self.add(dist)
+
+ return needed
+
def subscribe(self, callback, existing=True):
"""Invoke `callback` for all distributions
If `existing=True` (default),
call on all existing ones, as well.
"""
- if callback in self.callbacks:
- return
- self.callbacks.append(callback)
+ if callback in self.callbacks:
+ return
+ self.callbacks.append(callback)
if not existing:
return
- for dist in self:
- callback(dist)
-
- def _added_new(self, dist):
- for callback in self.callbacks:
- callback(dist)
-
- def __getstate__(self):
- return (
- self.entries[:], self.entry_keys.copy(), self.by_key.copy(),
- self.callbacks[:]
- )
-
- def __setstate__(self, e_k_b_c):
- entries, keys, by_key, callbacks = e_k_b_c
- self.entries = entries[:]
- self.entry_keys = keys.copy()
- self.by_key = by_key.copy()
- self.callbacks = callbacks[:]
-
-
+ for dist in self:
+ callback(dist)
+
+ def _added_new(self, dist):
+ for callback in self.callbacks:
+ callback(dist)
+
+ def __getstate__(self):
+ return (
+ self.entries[:], self.entry_keys.copy(), self.by_key.copy(),
+ self.callbacks[:]
+ )
+
+ def __setstate__(self, e_k_b_c):
+ entries, keys, by_key, callbacks = e_k_b_c
+ self.entries = entries[:]
+ self.entry_keys = keys.copy()
+ self.by_key = by_key.copy()
+ self.callbacks = callbacks[:]
+
+
class _ReqExtras(dict):
"""
Map each requirement to the extras that demanded it.
@@ -957,353 +957,353 @@ class _ReqExtras(dict):
class Environment:
- """Searchable snapshot of distributions on a search path"""
-
+ """Searchable snapshot of distributions on a search path"""
+
def __init__(
self, search_path=None, platform=get_supported_platform(),
- python=PY_MAJOR):
- """Snapshot distributions available on a search path
-
- Any distributions found on `search_path` are added to the environment.
- `search_path` should be a sequence of ``sys.path`` items. If not
- supplied, ``sys.path`` is used.
-
- `platform` is an optional string specifying the name of the platform
- that platform-specific distributions must be compatible with. If
- unspecified, it defaults to the current platform. `python` is an
+ python=PY_MAJOR):
+ """Snapshot distributions available on a search path
+
+ Any distributions found on `search_path` are added to the environment.
+ `search_path` should be a sequence of ``sys.path`` items. If not
+ supplied, ``sys.path`` is used.
+
+ `platform` is an optional string specifying the name of the platform
+ that platform-specific distributions must be compatible with. If
+ unspecified, it defaults to the current platform. `python` is an
optional string naming the desired version of Python (e.g. ``'3.6'``);
- it defaults to the current version.
-
- You may explicitly set `platform` (and/or `python`) to ``None`` if you
- wish to map *all* distributions, not just those compatible with the
- running platform or Python version.
- """
- self._distmap = {}
- self.platform = platform
- self.python = python
- self.scan(search_path)
-
- def can_add(self, dist):
- """Is distribution `dist` acceptable for this environment?
-
- The distribution must match the platform and python version
- requirements specified when this environment was created, or False
- is returned.
- """
+ it defaults to the current version.
+
+ You may explicitly set `platform` (and/or `python`) to ``None`` if you
+ wish to map *all* distributions, not just those compatible with the
+ running platform or Python version.
+ """
+ self._distmap = {}
+ self.platform = platform
+ self.python = python
+ self.scan(search_path)
+
+ def can_add(self, dist):
+ """Is distribution `dist` acceptable for this environment?
+
+ The distribution must match the platform and python version
+ requirements specified when this environment was created, or False
+ is returned.
+ """
py_compat = (
self.python is None
or dist.py_version is None
or dist.py_version == self.python
)
return py_compat and compatible_platforms(dist.platform, self.platform)
-
- def remove(self, dist):
- """Remove `dist` from the environment"""
- self._distmap[dist.key].remove(dist)
-
- def scan(self, search_path=None):
- """Scan `search_path` for distributions usable in this environment
-
- Any distributions found are added to the environment.
- `search_path` should be a sequence of ``sys.path`` items. If not
- supplied, ``sys.path`` is used. Only distributions conforming to
- the platform/python version defined at initialization are added.
- """
- if search_path is None:
- search_path = sys.path
-
- for item in search_path:
- for dist in find_distributions(item):
- self.add(dist)
-
- def __getitem__(self, project_name):
- """Return a newest-to-oldest list of distributions for `project_name`
-
- Uses case-insensitive `project_name` comparison, assuming all the
- project's distributions use their project's name converted to all
- lowercase as their key.
-
- """
- distribution_key = project_name.lower()
- return self._distmap.get(distribution_key, [])
-
- def add(self, dist):
- """Add `dist` if we ``can_add()`` it and it has not already been added
- """
- if self.can_add(dist) and dist.has_version():
- dists = self._distmap.setdefault(dist.key, [])
- if dist not in dists:
- dists.append(dist)
- dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
-
+
+ def remove(self, dist):
+ """Remove `dist` from the environment"""
+ self._distmap[dist.key].remove(dist)
+
+ def scan(self, search_path=None):
+ """Scan `search_path` for distributions usable in this environment
+
+ Any distributions found are added to the environment.
+ `search_path` should be a sequence of ``sys.path`` items. If not
+ supplied, ``sys.path`` is used. Only distributions conforming to
+ the platform/python version defined at initialization are added.
+ """
+ if search_path is None:
+ search_path = sys.path
+
+ for item in search_path:
+ for dist in find_distributions(item):
+ self.add(dist)
+
+ def __getitem__(self, project_name):
+ """Return a newest-to-oldest list of distributions for `project_name`
+
+ Uses case-insensitive `project_name` comparison, assuming all the
+ project's distributions use their project's name converted to all
+ lowercase as their key.
+
+ """
+ distribution_key = project_name.lower()
+ return self._distmap.get(distribution_key, [])
+
+ def add(self, dist):
+ """Add `dist` if we ``can_add()`` it and it has not already been added
+ """
+ if self.can_add(dist) and dist.has_version():
+ dists = self._distmap.setdefault(dist.key, [])
+ if dist not in dists:
+ dists.append(dist)
+ dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
+
def best_match(
self, req, working_set, installer=None, replace_conflicting=False):
- """Find distribution best matching `req` and usable on `working_set`
-
- This calls the ``find(req)`` method of the `working_set` to see if a
- suitable distribution is already active. (This may raise
- ``VersionConflict`` if an unsuitable version of the project is already
- active in the specified `working_set`.) If a suitable distribution
- isn't active, this method returns the newest distribution in the
- environment that meets the ``Requirement`` in `req`. If no suitable
- distribution is found, and `installer` is supplied, then the result of
- calling the environment's ``obtain(req, installer)`` method will be
- returned.
- """
+ """Find distribution best matching `req` and usable on `working_set`
+
+ This calls the ``find(req)`` method of the `working_set` to see if a
+ suitable distribution is already active. (This may raise
+ ``VersionConflict`` if an unsuitable version of the project is already
+ active in the specified `working_set`.) If a suitable distribution
+ isn't active, this method returns the newest distribution in the
+ environment that meets the ``Requirement`` in `req`. If no suitable
+ distribution is found, and `installer` is supplied, then the result of
+ calling the environment's ``obtain(req, installer)`` method will be
+ returned.
+ """
try:
dist = working_set.find(req)
except VersionConflict:
if not replace_conflicting:
raise
dist = None
- if dist is not None:
- return dist
- for dist in self[req.key]:
- if dist in req:
- return dist
- # try to download/install
- return self.obtain(req, installer)
-
- def obtain(self, requirement, installer=None):
- """Obtain a distribution matching `requirement` (e.g. via download)
-
- Obtain a distro that matches requirement (e.g. via download). In the
- base ``Environment`` class, this routine just returns
- ``installer(requirement)``, unless `installer` is None, in which case
- None is returned instead. This method is a hook that allows subclasses
- to attempt other ways of obtaining a distribution before falling back
- to the `installer` argument."""
- if installer is not None:
- return installer(requirement)
-
- def __iter__(self):
- """Yield the unique project names of the available distributions"""
- for key in self._distmap.keys():
- if self[key]:
- yield key
-
- def __iadd__(self, other):
- """In-place addition of a distribution or environment"""
- if isinstance(other, Distribution):
- self.add(other)
- elif isinstance(other, Environment):
- for project in other:
- for dist in other[project]:
- self.add(dist)
- else:
- raise TypeError("Can't add %r to environment" % (other,))
- return self
-
- def __add__(self, other):
- """Add an environment or distribution to an environment"""
- new = self.__class__([], platform=None, python=None)
- for env in self, other:
- new += env
- return new
-
-
-# XXX backward compatibility
-AvailableDistributions = Environment
-
-
-class ExtractionError(RuntimeError):
- """An error occurred extracting a resource
-
- The following attributes are available from instances of this exception:
-
- manager
- The resource manager that raised this exception
-
- cache_path
- The base directory for resource extraction
-
- original_error
- The exception instance that caused extraction to fail
- """
-
-
-class ResourceManager:
- """Manage resource extraction and packages"""
- extraction_path = None
-
- def __init__(self):
- self.cached_files = {}
-
- def resource_exists(self, package_or_requirement, resource_name):
- """Does the named resource exist?"""
- return get_provider(package_or_requirement).has_resource(resource_name)
-
- def resource_isdir(self, package_or_requirement, resource_name):
- """Is the named resource an existing directory?"""
- return get_provider(package_or_requirement).resource_isdir(
- resource_name
- )
-
- def resource_filename(self, package_or_requirement, resource_name):
- """Return a true filesystem path for specified resource"""
- return get_provider(package_or_requirement).get_resource_filename(
- self, resource_name
- )
-
- def resource_stream(self, package_or_requirement, resource_name):
- """Return a readable file-like object for specified resource"""
- return get_provider(package_or_requirement).get_resource_stream(
- self, resource_name
- )
-
- def resource_string(self, package_or_requirement, resource_name):
- """Return specified resource as a string"""
- return get_provider(package_or_requirement).get_resource_string(
- self, resource_name
- )
-
- def resource_listdir(self, package_or_requirement, resource_name):
- """List the contents of the named resource directory"""
- return get_provider(package_or_requirement).resource_listdir(
- resource_name
- )
-
- def extraction_error(self):
- """Give an error message for problems extracting file(s)"""
-
- old_exc = sys.exc_info()[1]
- cache_path = self.extraction_path or get_default_cache()
-
- tmpl = textwrap.dedent("""
- Can't extract file(s) to egg cache
-
+ if dist is not None:
+ return dist
+ for dist in self[req.key]:
+ if dist in req:
+ return dist
+ # try to download/install
+ return self.obtain(req, installer)
+
+ def obtain(self, requirement, installer=None):
+ """Obtain a distribution matching `requirement` (e.g. via download)
+
+ Obtain a distro that matches requirement (e.g. via download). In the
+ base ``Environment`` class, this routine just returns
+ ``installer(requirement)``, unless `installer` is None, in which case
+ None is returned instead. This method is a hook that allows subclasses
+ to attempt other ways of obtaining a distribution before falling back
+ to the `installer` argument."""
+ if installer is not None:
+ return installer(requirement)
+
+ def __iter__(self):
+ """Yield the unique project names of the available distributions"""
+ for key in self._distmap.keys():
+ if self[key]:
+ yield key
+
+ def __iadd__(self, other):
+ """In-place addition of a distribution or environment"""
+ if isinstance(other, Distribution):
+ self.add(other)
+ elif isinstance(other, Environment):
+ for project in other:
+ for dist in other[project]:
+ self.add(dist)
+ else:
+ raise TypeError("Can't add %r to environment" % (other,))
+ return self
+
+ def __add__(self, other):
+ """Add an environment or distribution to an environment"""
+ new = self.__class__([], platform=None, python=None)
+ for env in self, other:
+ new += env
+ return new
+
+
+# XXX backward compatibility
+AvailableDistributions = Environment
+
+
+class ExtractionError(RuntimeError):
+ """An error occurred extracting a resource
+
+ The following attributes are available from instances of this exception:
+
+ manager
+ The resource manager that raised this exception
+
+ cache_path
+ The base directory for resource extraction
+
+ original_error
+ The exception instance that caused extraction to fail
+ """
+
+
+class ResourceManager:
+ """Manage resource extraction and packages"""
+ extraction_path = None
+
+ def __init__(self):
+ self.cached_files = {}
+
+ def resource_exists(self, package_or_requirement, resource_name):
+ """Does the named resource exist?"""
+ return get_provider(package_or_requirement).has_resource(resource_name)
+
+ def resource_isdir(self, package_or_requirement, resource_name):
+ """Is the named resource an existing directory?"""
+ return get_provider(package_or_requirement).resource_isdir(
+ resource_name
+ )
+
+ def resource_filename(self, package_or_requirement, resource_name):
+ """Return a true filesystem path for specified resource"""
+ return get_provider(package_or_requirement).get_resource_filename(
+ self, resource_name
+ )
+
+ def resource_stream(self, package_or_requirement, resource_name):
+ """Return a readable file-like object for specified resource"""
+ return get_provider(package_or_requirement).get_resource_stream(
+ self, resource_name
+ )
+
+ def resource_string(self, package_or_requirement, resource_name):
+ """Return specified resource as a string"""
+ return get_provider(package_or_requirement).get_resource_string(
+ self, resource_name
+ )
+
+ def resource_listdir(self, package_or_requirement, resource_name):
+ """List the contents of the named resource directory"""
+ return get_provider(package_or_requirement).resource_listdir(
+ resource_name
+ )
+
+ def extraction_error(self):
+ """Give an error message for problems extracting file(s)"""
+
+ old_exc = sys.exc_info()[1]
+ cache_path = self.extraction_path or get_default_cache()
+
+ tmpl = textwrap.dedent("""
+ Can't extract file(s) to egg cache
+
The following error occurred while trying to extract file(s)
to the Python egg cache:
-
- {old_exc}
-
- The Python egg cache directory is currently set to:
-
- {cache_path}
-
+
+ {old_exc}
+
+ The Python egg cache directory is currently set to:
+
+ {cache_path}
+
Perhaps your account does not have write access to this directory?
You can change the cache directory by setting the PYTHON_EGG_CACHE
environment variable to point to an accessible directory.
- """).lstrip()
- err = ExtractionError(tmpl.format(**locals()))
- err.manager = self
- err.cache_path = cache_path
- err.original_error = old_exc
- raise err
-
- def get_cache_path(self, archive_name, names=()):
- """Return absolute location in cache for `archive_name` and `names`
-
- The parent directory of the resulting path will be created if it does
- not already exist. `archive_name` should be the base filename of the
- enclosing egg (which may not be the name of the enclosing zipfile!),
- including its ".egg" extension. `names`, if provided, should be a
- sequence of path name parts "under" the egg's extraction location.
-
- This method should only be called by resource providers that need to
- obtain an extraction location, and only for names they intend to
- extract, as it tracks the generated names for possible cleanup later.
- """
- extract_path = self.extraction_path or get_default_cache()
+ """).lstrip()
+ err = ExtractionError(tmpl.format(**locals()))
+ err.manager = self
+ err.cache_path = cache_path
+ err.original_error = old_exc
+ raise err
+
+ def get_cache_path(self, archive_name, names=()):
+ """Return absolute location in cache for `archive_name` and `names`
+
+ The parent directory of the resulting path will be created if it does
+ not already exist. `archive_name` should be the base filename of the
+ enclosing egg (which may not be the name of the enclosing zipfile!),
+ including its ".egg" extension. `names`, if provided, should be a
+ sequence of path name parts "under" the egg's extraction location.
+
+ This method should only be called by resource providers that need to
+ obtain an extraction location, and only for names they intend to
+ extract, as it tracks the generated names for possible cleanup later.
+ """
+ extract_path = self.extraction_path or get_default_cache()
target_path = os.path.join(extract_path, archive_name + '-tmp', *names)
- try:
- _bypass_ensure_directory(target_path)
+ try:
+ _bypass_ensure_directory(target_path)
except Exception:
- self.extraction_error()
-
- self._warn_unsafe_extraction_path(extract_path)
-
- self.cached_files[target_path] = 1
- return target_path
-
- @staticmethod
- def _warn_unsafe_extraction_path(path):
- """
- If the default extraction path is overridden and set to an insecure
- location, such as /tmp, it opens up an opportunity for an attacker to
- replace an extracted file with an unauthorized payload. Warn the user
- if a known insecure location is used.
-
- See Distribute #375 for more details.
- """
- if os.name == 'nt' and not path.startswith(os.environ['windir']):
- # On Windows, permissions are generally restrictive by default
- # and temp directories are not writable by other users, so
- # bypass the warning.
- return
- mode = os.stat(path).st_mode
- if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
+ self.extraction_error()
+
+ self._warn_unsafe_extraction_path(extract_path)
+
+ self.cached_files[target_path] = 1
+ return target_path
+
+ @staticmethod
+ def _warn_unsafe_extraction_path(path):
+ """
+ If the default extraction path is overridden and set to an insecure
+ location, such as /tmp, it opens up an opportunity for an attacker to
+ replace an extracted file with an unauthorized payload. Warn the user
+ if a known insecure location is used.
+
+ See Distribute #375 for more details.
+ """
+ if os.name == 'nt' and not path.startswith(os.environ['windir']):
+ # On Windows, permissions are generally restrictive by default
+ # and temp directories are not writable by other users, so
+ # bypass the warning.
+ return
+ mode = os.stat(path).st_mode
+ if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
msg = (
"%s is writable by group/others and vulnerable to attack "
- "when "
- "used with get_resource_filename. Consider a more secure "
- "location (set with .set_extraction_path or the "
+ "when "
+ "used with get_resource_filename. Consider a more secure "
+ "location (set with .set_extraction_path or the "
"PYTHON_EGG_CACHE environment variable)." % path
)
- warnings.warn(msg, UserWarning)
-
- def postprocess(self, tempname, filename):
- """Perform any platform-specific postprocessing of `tempname`
-
- This is where Mac header rewrites should be done; other platforms don't
- have anything special they should do.
-
- Resource providers should call this method ONLY after successfully
- extracting a compressed resource. They must NOT call it on resources
- that are already in the filesystem.
-
- `tempname` is the current (temporary) name of the file, and `filename`
- is the name it will be renamed to by the caller after this routine
- returns.
- """
-
- if os.name == 'posix':
- # Make the resource executable
- mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
- os.chmod(tempname, mode)
-
- def set_extraction_path(self, path):
- """Set the base path where resources will be extracted to, if needed.
-
- If you do not call this routine before any extractions take place, the
- path defaults to the return value of ``get_default_cache()``. (Which
- is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
- platform-specific fallbacks. See that routine's documentation for more
- details.)
-
- Resources are extracted to subdirectories of this path based upon
- information given by the ``IResourceProvider``. You may set this to a
- temporary directory, but then you must call ``cleanup_resources()`` to
- delete the extracted files when done. There is no guarantee that
- ``cleanup_resources()`` will be able to remove all extracted files.
-
- (Note: you may not change the extraction path for a given resource
- manager once resources have been extracted, unless you first call
- ``cleanup_resources()``.)
- """
- if self.cached_files:
- raise ValueError(
- "Can't change extraction path, files already extracted"
- )
-
- self.extraction_path = path
-
- def cleanup_resources(self, force=False):
- """
- Delete all extracted resource files and directories, returning a list
- of the file and directory names that could not be successfully removed.
- This function does not have any concurrency protection, so it should
- generally only be called when the extraction path is a temporary
- directory exclusive to a single process. This method is not
- automatically called; you must call it explicitly or register it as an
- ``atexit`` function if you wish to ensure cleanup of a temporary
- directory used for extractions.
- """
- # XXX
-
-
-def get_default_cache():
- """
+ warnings.warn(msg, UserWarning)
+
+ def postprocess(self, tempname, filename):
+ """Perform any platform-specific postprocessing of `tempname`
+
+ This is where Mac header rewrites should be done; other platforms don't
+ have anything special they should do.
+
+ Resource providers should call this method ONLY after successfully
+ extracting a compressed resource. They must NOT call it on resources
+ that are already in the filesystem.
+
+ `tempname` is the current (temporary) name of the file, and `filename`
+ is the name it will be renamed to by the caller after this routine
+ returns.
+ """
+
+ if os.name == 'posix':
+ # Make the resource executable
+ mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
+ os.chmod(tempname, mode)
+
+ def set_extraction_path(self, path):
+ """Set the base path where resources will be extracted to, if needed.
+
+ If you do not call this routine before any extractions take place, the
+ path defaults to the return value of ``get_default_cache()``. (Which
+ is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
+ platform-specific fallbacks. See that routine's documentation for more
+ details.)
+
+ Resources are extracted to subdirectories of this path based upon
+ information given by the ``IResourceProvider``. You may set this to a
+ temporary directory, but then you must call ``cleanup_resources()`` to
+ delete the extracted files when done. There is no guarantee that
+ ``cleanup_resources()`` will be able to remove all extracted files.
+
+ (Note: you may not change the extraction path for a given resource
+ manager once resources have been extracted, unless you first call
+ ``cleanup_resources()``.)
+ """
+ if self.cached_files:
+ raise ValueError(
+ "Can't change extraction path, files already extracted"
+ )
+
+ self.extraction_path = path
+
+ def cleanup_resources(self, force=False):
+ """
+ Delete all extracted resource files and directories, returning a list
+ of the file and directory names that could not be successfully removed.
+ This function does not have any concurrency protection, so it should
+ generally only be called when the extraction path is a temporary
+ directory exclusive to a single process. This method is not
+ automatically called; you must call it explicitly or register it as an
+ ``atexit`` function if you wish to ensure cleanup of a temporary
+ directory used for extractions.
+ """
+ # XXX
+
+
+def get_default_cache():
+ """
Return the ``PYTHON_EGG_CACHE`` environment variable
or a platform-relevant user cache dir for an app
named "Python-Eggs".
@@ -1312,45 +1312,45 @@ def get_default_cache():
os.environ.get('PYTHON_EGG_CACHE')
or appdirs.user_cache_dir(appname='Python-Eggs')
)
-
-
-def safe_name(name):
- """Convert an arbitrary string to a standard distribution name
-
- Any runs of non-alphanumeric/. characters are replaced with a single '-'.
- """
- return re.sub('[^A-Za-z0-9.]+', '-', name)
-
-
-def safe_version(version):
- """
- Convert an arbitrary string to a standard version string
- """
- try:
- # normalize the version
- return str(packaging.version.Version(version))
- except packaging.version.InvalidVersion:
+
+
+def safe_name(name):
+ """Convert an arbitrary string to a standard distribution name
+
+ Any runs of non-alphanumeric/. characters are replaced with a single '-'.
+ """
+ return re.sub('[^A-Za-z0-9.]+', '-', name)
+
+
+def safe_version(version):
+ """
+ Convert an arbitrary string to a standard version string
+ """
+ try:
+ # normalize the version
+ return str(packaging.version.Version(version))
+ except packaging.version.InvalidVersion:
version = version.replace(' ', '.')
- return re.sub('[^A-Za-z0-9.]+', '-', version)
-
-
-def safe_extra(extra):
- """Convert an arbitrary string to a standard 'extra' name
-
- Any runs of non-alphanumeric characters are replaced with a single '_',
- and the result is always lowercased.
- """
+ return re.sub('[^A-Za-z0-9.]+', '-', version)
+
+
+def safe_extra(extra):
+ """Convert an arbitrary string to a standard 'extra' name
+
+ Any runs of non-alphanumeric characters are replaced with a single '_',
+ and the result is always lowercased.
+ """
return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()
-
-
-def to_filename(name):
- """Convert a project or version name to its filename-escaped form
-
- Any '-' characters are currently replaced with '_'.
- """
+
+
+def to_filename(name):
+ """Convert a project or version name to its filename-escaped form
+
+ Any '-' characters are currently replaced with '_'.
+ """
return name.replace('-', '_')
-
-
+
+
def invalid_marker(text):
"""
Validate text as a PEP 508 environment marker; return an exception
@@ -1363,14 +1363,14 @@ def invalid_marker(text):
e.lineno = None
return e
return False
-
-
+
+
def evaluate_marker(text, extra=None):
"""
Evaluate a PEP 508 environment marker.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
-
+
This implementation uses the 'pyparsing' module.
"""
try:
@@ -1378,38 +1378,38 @@ def evaluate_marker(text, extra=None):
return marker.evaluate()
except packaging.markers.InvalidMarker as e:
raise SyntaxError(e)
-
-
-class NullProvider:
- """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
-
- egg_name = None
- egg_info = None
- loader = None
-
- def __init__(self, module):
- self.loader = getattr(module, '__loader__', None)
- self.module_path = os.path.dirname(getattr(module, '__file__', ''))
-
- def get_resource_filename(self, manager, resource_name):
- return self._fn(self.module_path, resource_name)
-
- def get_resource_stream(self, manager, resource_name):
- return io.BytesIO(self.get_resource_string(manager, resource_name))
-
- def get_resource_string(self, manager, resource_name):
- return self._get(self._fn(self.module_path, resource_name))
-
- def has_resource(self, resource_name):
- return self._has(self._fn(self.module_path, resource_name))
-
+
+
+class NullProvider:
+ """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
+
+ egg_name = None
+ egg_info = None
+ loader = None
+
+ def __init__(self, module):
+ self.loader = getattr(module, '__loader__', None)
+ self.module_path = os.path.dirname(getattr(module, '__file__', ''))
+
+ def get_resource_filename(self, manager, resource_name):
+ return self._fn(self.module_path, resource_name)
+
+ def get_resource_stream(self, manager, resource_name):
+ return io.BytesIO(self.get_resource_string(manager, resource_name))
+
+ def get_resource_string(self, manager, resource_name):
+ return self._get(self._fn(self.module_path, resource_name))
+
+ def has_resource(self, resource_name):
+ return self._has(self._fn(self.module_path, resource_name))
+
def _get_metadata_path(self, name):
return self._fn(self.egg_info, name)
- def has_metadata(self, name):
+ def has_metadata(self, name):
if not self.egg_info:
return self.egg_info
-
+
path = self._get_metadata_path(name)
return self._has(path)
@@ -1427,68 +1427,68 @@ class NullProvider:
# troubleshooting, and without changing the exception type.
exc.reason += ' in {} file at path: {}'.format(name, path)
raise
-
- def get_metadata_lines(self, name):
- return yield_lines(self.get_metadata(name))
-
- def resource_isdir(self, resource_name):
- return self._isdir(self._fn(self.module_path, resource_name))
-
- def metadata_isdir(self, name):
- return self.egg_info and self._isdir(self._fn(self.egg_info, name))
-
- def resource_listdir(self, resource_name):
- return self._listdir(self._fn(self.module_path, resource_name))
-
- def metadata_listdir(self, name):
- if self.egg_info:
- return self._listdir(self._fn(self.egg_info, name))
- return []
-
- def run_script(self, script_name, namespace):
+
+ def get_metadata_lines(self, name):
+ return yield_lines(self.get_metadata(name))
+
+ def resource_isdir(self, resource_name):
+ return self._isdir(self._fn(self.module_path, resource_name))
+
+ def metadata_isdir(self, name):
+ return self.egg_info and self._isdir(self._fn(self.egg_info, name))
+
+ def resource_listdir(self, resource_name):
+ return self._listdir(self._fn(self.module_path, resource_name))
+
+ def metadata_listdir(self, name):
+ if self.egg_info:
+ return self._listdir(self._fn(self.egg_info, name))
+ return []
+
+ def run_script(self, script_name, namespace):
script = 'scripts/' + script_name
- if not self.has_metadata(script):
+ if not self.has_metadata(script):
raise ResolutionError(
"Script {script!r} not found in metadata at {self.egg_info!r}"
.format(**locals()),
)
- script_text = self.get_metadata(script).replace('\r\n', '\n')
- script_text = script_text.replace('\r', '\n')
- script_filename = self._fn(self.egg_info, script)
- namespace['__file__'] = script_filename
- if os.path.exists(script_filename):
- source = open(script_filename).read()
- code = compile(source, script_filename, 'exec')
- exec(code, namespace, namespace)
- else:
- from linecache import cache
- cache[script_filename] = (
- len(script_text), 0, script_text.split('\n'), script_filename
- )
+ script_text = self.get_metadata(script).replace('\r\n', '\n')
+ script_text = script_text.replace('\r', '\n')
+ script_filename = self._fn(self.egg_info, script)
+ namespace['__file__'] = script_filename
+ if os.path.exists(script_filename):
+ source = open(script_filename).read()
+ code = compile(source, script_filename, 'exec')
+ exec(code, namespace, namespace)
+ else:
+ from linecache import cache
+ cache[script_filename] = (
+ len(script_text), 0, script_text.split('\n'), script_filename
+ )
script_code = compile(script_text, script_filename, 'exec')
- exec(script_code, namespace, namespace)
-
- def _has(self, path):
- raise NotImplementedError(
- "Can't perform this operation for unregistered loader type"
- )
-
- def _isdir(self, path):
- raise NotImplementedError(
- "Can't perform this operation for unregistered loader type"
- )
-
- def _listdir(self, path):
- raise NotImplementedError(
- "Can't perform this operation for unregistered loader type"
- )
-
- def _fn(self, base, resource_name):
+ exec(script_code, namespace, namespace)
+
+ def _has(self, path):
+ raise NotImplementedError(
+ "Can't perform this operation for unregistered loader type"
+ )
+
+ def _isdir(self, path):
+ raise NotImplementedError(
+ "Can't perform this operation for unregistered loader type"
+ )
+
+ def _listdir(self, path):
+ raise NotImplementedError(
+ "Can't perform this operation for unregistered loader type"
+ )
+
+ def _fn(self, base, resource_name):
self._validate_resource_path(resource_name)
- if resource_name:
- return os.path.join(base, *resource_name.split('/'))
- return base
-
+ if resource_name:
+ return os.path.join(base, *resource_name.split('/'))
+ return base
+
@staticmethod
def _validate_resource_path(path):
"""
@@ -1564,74 +1564,74 @@ is not allowed.
stacklevel=4,
)
- def _get(self, path):
- if hasattr(self.loader, 'get_data'):
- return self.loader.get_data(path)
- raise NotImplementedError(
- "Can't perform this operation for loaders without 'get_data()'"
- )
-
-
-register_loader_type(object, NullProvider)
-
-
-class EggProvider(NullProvider):
- """Provider based on a virtual filesystem"""
-
- def __init__(self, module):
- NullProvider.__init__(self, module)
- self._setup_prefix()
-
- def _setup_prefix(self):
- # we assume here that our metadata may be nested inside a "basket"
- # of multiple eggs; that's why we use module_path instead of .archive
- path = self.module_path
- old = None
+ def _get(self, path):
+ if hasattr(self.loader, 'get_data'):
+ return self.loader.get_data(path)
+ raise NotImplementedError(
+ "Can't perform this operation for loaders without 'get_data()'"
+ )
+
+
+register_loader_type(object, NullProvider)
+
+
+class EggProvider(NullProvider):
+ """Provider based on a virtual filesystem"""
+
+ def __init__(self, module):
+ NullProvider.__init__(self, module)
+ self._setup_prefix()
+
+ def _setup_prefix(self):
+ # we assume here that our metadata may be nested inside a "basket"
+ # of multiple eggs; that's why we use module_path instead of .archive
+ path = self.module_path
+ old = None
while path != old:
if _is_egg_path(path):
- self.egg_name = os.path.basename(path)
- self.egg_info = os.path.join(path, 'EGG-INFO')
- self.egg_root = path
- break
- old = path
- path, base = os.path.split(path)
-
-
-class DefaultProvider(EggProvider):
- """Provides access to package resources in the filesystem"""
-
- def _has(self, path):
- return os.path.exists(path)
-
- def _isdir(self, path):
- return os.path.isdir(path)
-
- def _listdir(self, path):
- return os.listdir(path)
-
- def get_resource_stream(self, manager, resource_name):
- return open(self._fn(self.module_path, resource_name), 'rb')
-
- def _get(self, path):
- with open(path, 'rb') as stream:
- return stream.read()
-
- @classmethod
- def _register(cls):
+ self.egg_name = os.path.basename(path)
+ self.egg_info = os.path.join(path, 'EGG-INFO')
+ self.egg_root = path
+ break
+ old = path
+ path, base = os.path.split(path)
+
+
+class DefaultProvider(EggProvider):
+ """Provides access to package resources in the filesystem"""
+
+ def _has(self, path):
+ return os.path.exists(path)
+
+ def _isdir(self, path):
+ return os.path.isdir(path)
+
+ def _listdir(self, path):
+ return os.listdir(path)
+
+ def get_resource_stream(self, manager, resource_name):
+ return open(self._fn(self.module_path, resource_name), 'rb')
+
+ def _get(self, path):
+ with open(path, 'rb') as stream:
+ return stream.read()
+
+ @classmethod
+ def _register(cls):
loader_names = 'SourceFileLoader', 'SourcelessFileLoader',
for name in loader_names:
loader_cls = getattr(importlib_machinery, name, type(None))
register_loader_type(loader_cls, cls)
-
-
-DefaultProvider._register()
-
-
-class EmptyProvider(NullProvider):
- """Provider that returns nothing for all requests"""
-
- module_path = None
-
+
+
+DefaultProvider._register()
+
+
+class EmptyProvider(NullProvider):
+ """Provider that returns nothing for all requests"""
+
+ module_path = None
+
_isdir = _has = lambda self, path: False
def _get(self, path):
@@ -1640,260 +1640,260 @@ class EmptyProvider(NullProvider):
def _listdir(self, path):
return []
- def __init__(self):
- pass
-
-
-empty_provider = EmptyProvider()
-
-
-class ZipManifests(dict):
- """
- zip manifest builder
- """
-
- @classmethod
- def build(cls, path):
- """
- Build a dictionary similar to the zipimport directory
- caches, except instead of tuples, store ZipInfo objects.
-
- Use a platform-specific path separator (os.sep) for the path keys
- for compatibility with pypy on Windows.
- """
+ def __init__(self):
+ pass
+
+
+empty_provider = EmptyProvider()
+
+
+class ZipManifests(dict):
+ """
+ zip manifest builder
+ """
+
+ @classmethod
+ def build(cls, path):
+ """
+ Build a dictionary similar to the zipimport directory
+ caches, except instead of tuples, store ZipInfo objects.
+
+ Use a platform-specific path separator (os.sep) for the path keys
+ for compatibility with pypy on Windows.
+ """
with zipfile.ZipFile(path) as zfile:
- items = (
- (
- name.replace('/', os.sep),
- zfile.getinfo(name),
- )
- for name in zfile.namelist()
- )
- return dict(items)
-
- load = build
-
-
-class MemoizedZipManifests(ZipManifests):
- """
- Memoized zipfile manifests.
- """
- manifest_mod = collections.namedtuple('manifest_mod', 'manifest mtime')
-
- def load(self, path):
- """
- Load a manifest at path or return a suitable manifest already loaded.
- """
- path = os.path.normpath(path)
- mtime = os.stat(path).st_mtime
-
- if path not in self or self[path].mtime != mtime:
- manifest = self.build(path)
- self[path] = self.manifest_mod(manifest, mtime)
-
- return self[path].manifest
-
-
-class ZipProvider(EggProvider):
- """Resource support for zips and eggs"""
-
- eagers = None
- _zip_manifests = MemoizedZipManifests()
-
- def __init__(self, module):
- EggProvider.__init__(self, module)
+ items = (
+ (
+ name.replace('/', os.sep),
+ zfile.getinfo(name),
+ )
+ for name in zfile.namelist()
+ )
+ return dict(items)
+
+ load = build
+
+
+class MemoizedZipManifests(ZipManifests):
+ """
+ Memoized zipfile manifests.
+ """
+ manifest_mod = collections.namedtuple('manifest_mod', 'manifest mtime')
+
+ def load(self, path):
+ """
+ Load a manifest at path or return a suitable manifest already loaded.
+ """
+ path = os.path.normpath(path)
+ mtime = os.stat(path).st_mtime
+
+ if path not in self or self[path].mtime != mtime:
+ manifest = self.build(path)
+ self[path] = self.manifest_mod(manifest, mtime)
+
+ return self[path].manifest
+
+
+class ZipProvider(EggProvider):
+ """Resource support for zips and eggs"""
+
+ eagers = None
+ _zip_manifests = MemoizedZipManifests()
+
+ def __init__(self, module):
+ EggProvider.__init__(self, module)
self.zip_pre = self.loader.archive + os.sep
-
- def _zipinfo_name(self, fspath):
- # Convert a virtual filename (full path to file) into a zipfile subpath
- # usable with the zipimport directory cache for our target archive
+
+ def _zipinfo_name(self, fspath):
+ # Convert a virtual filename (full path to file) into a zipfile subpath
+ # usable with the zipimport directory cache for our target archive
fspath = fspath.rstrip(os.sep)
if fspath == self.loader.archive:
return ''
- if fspath.startswith(self.zip_pre):
- return fspath[len(self.zip_pre):]
- raise AssertionError(
- "%s is not a subpath of %s" % (fspath, self.zip_pre)
- )
-
- def _parts(self, zip_path):
- # Convert a zipfile subpath into an egg-relative path part list.
- # pseudo-fs path
+ if fspath.startswith(self.zip_pre):
+ return fspath[len(self.zip_pre):]
+ raise AssertionError(
+ "%s is not a subpath of %s" % (fspath, self.zip_pre)
+ )
+
+ def _parts(self, zip_path):
+ # Convert a zipfile subpath into an egg-relative path part list.
+ # pseudo-fs path
fspath = self.zip_pre + zip_path
if fspath.startswith(self.egg_root + os.sep):
return fspath[len(self.egg_root) + 1:].split(os.sep)
- raise AssertionError(
- "%s is not a subpath of %s" % (fspath, self.egg_root)
- )
-
- @property
- def zipinfo(self):
- return self._zip_manifests.load(self.loader.archive)
-
- def get_resource_filename(self, manager, resource_name):
- if not self.egg_name:
- raise NotImplementedError(
- "resource_filename() only supported for .egg, not .zip"
- )
- # no need to lock for extraction, since we use temp names
- zip_path = self._resource_to_zip(resource_name)
- eagers = self._get_eager_resources()
- if '/'.join(self._parts(zip_path)) in eagers:
- for name in eagers:
- self._extract_resource(manager, self._eager_to_zip(name))
- return self._extract_resource(manager, zip_path)
-
- @staticmethod
- def _get_date_and_size(zip_stat):
- size = zip_stat.file_size
- # ymdhms+wday, yday, dst
- date_time = zip_stat.date_time + (0, 0, -1)
- # 1980 offset already done
- timestamp = time.mktime(date_time)
- return timestamp, size
-
- def _extract_resource(self, manager, zip_path):
-
- if zip_path in self._index():
- for name in self._index()[zip_path]:
- last = self._extract_resource(
- manager, os.path.join(zip_path, name)
- )
- # return the extracted directory name
- return os.path.dirname(last)
-
- timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
-
- if not WRITE_SUPPORT:
- raise IOError('"os.rename" and "os.unlink" are not supported '
- 'on this platform')
- try:
-
- real_path = manager.get_cache_path(
- self.egg_name, self._parts(zip_path)
- )
-
- if self._is_current(real_path, zip_path):
- return real_path
-
+ raise AssertionError(
+ "%s is not a subpath of %s" % (fspath, self.egg_root)
+ )
+
+ @property
+ def zipinfo(self):
+ return self._zip_manifests.load(self.loader.archive)
+
+ def get_resource_filename(self, manager, resource_name):
+ if not self.egg_name:
+ raise NotImplementedError(
+ "resource_filename() only supported for .egg, not .zip"
+ )
+ # no need to lock for extraction, since we use temp names
+ zip_path = self._resource_to_zip(resource_name)
+ eagers = self._get_eager_resources()
+ if '/'.join(self._parts(zip_path)) in eagers:
+ for name in eagers:
+ self._extract_resource(manager, self._eager_to_zip(name))
+ return self._extract_resource(manager, zip_path)
+
+ @staticmethod
+ def _get_date_and_size(zip_stat):
+ size = zip_stat.file_size
+ # ymdhms+wday, yday, dst
+ date_time = zip_stat.date_time + (0, 0, -1)
+ # 1980 offset already done
+ timestamp = time.mktime(date_time)
+ return timestamp, size
+
+ def _extract_resource(self, manager, zip_path):
+
+ if zip_path in self._index():
+ for name in self._index()[zip_path]:
+ last = self._extract_resource(
+ manager, os.path.join(zip_path, name)
+ )
+ # return the extracted directory name
+ return os.path.dirname(last)
+
+ timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
+
+ if not WRITE_SUPPORT:
+ raise IOError('"os.rename" and "os.unlink" are not supported '
+ 'on this platform')
+ try:
+
+ real_path = manager.get_cache_path(
+ self.egg_name, self._parts(zip_path)
+ )
+
+ if self._is_current(real_path, zip_path):
+ return real_path
+
outf, tmpnam = _mkstemp(
".$extract",
dir=os.path.dirname(real_path),
)
- os.write(outf, self.loader.get_data(zip_path))
- os.close(outf)
- utime(tmpnam, (timestamp, timestamp))
- manager.postprocess(tmpnam, real_path)
-
- try:
- rename(tmpnam, real_path)
-
- except os.error:
- if os.path.isfile(real_path):
- if self._is_current(real_path, zip_path):
- # the file became current since it was checked above,
- # so proceed.
- return real_path
- # Windows, del old file and retry
+ os.write(outf, self.loader.get_data(zip_path))
+ os.close(outf)
+ utime(tmpnam, (timestamp, timestamp))
+ manager.postprocess(tmpnam, real_path)
+
+ try:
+ rename(tmpnam, real_path)
+
+ except os.error:
+ if os.path.isfile(real_path):
+ if self._is_current(real_path, zip_path):
+ # the file became current since it was checked above,
+ # so proceed.
+ return real_path
+ # Windows, del old file and retry
elif os.name == 'nt':
- unlink(real_path)
- rename(tmpnam, real_path)
- return real_path
- raise
-
- except os.error:
- # report a user-friendly error
- manager.extraction_error()
-
- return real_path
-
- def _is_current(self, file_path, zip_path):
- """
- Return True if the file_path is current for this zip_path
- """
- timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
- if not os.path.isfile(file_path):
- return False
- stat = os.stat(file_path)
+ unlink(real_path)
+ rename(tmpnam, real_path)
+ return real_path
+ raise
+
+ except os.error:
+ # report a user-friendly error
+ manager.extraction_error()
+
+ return real_path
+
+ def _is_current(self, file_path, zip_path):
+ """
+ Return True if the file_path is current for this zip_path
+ """
+ timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
+ if not os.path.isfile(file_path):
+ return False
+ stat = os.stat(file_path)
if stat.st_size != size or stat.st_mtime != timestamp:
- return False
- # check that the contents match
- zip_contents = self.loader.get_data(zip_path)
- with open(file_path, 'rb') as f:
- file_contents = f.read()
- return zip_contents == file_contents
-
- def _get_eager_resources(self):
- if self.eagers is None:
- eagers = []
- for name in ('native_libs.txt', 'eager_resources.txt'):
- if self.has_metadata(name):
- eagers.extend(self.get_metadata_lines(name))
- self.eagers = eagers
- return self.eagers
-
- def _index(self):
- try:
- return self._dirindex
- except AttributeError:
- ind = {}
- for path in self.zipinfo:
- parts = path.split(os.sep)
- while parts:
- parent = os.sep.join(parts[:-1])
- if parent in ind:
- ind[parent].append(parts[-1])
- break
- else:
- ind[parent] = [parts.pop()]
- self._dirindex = ind
- return ind
-
- def _has(self, fspath):
- zip_path = self._zipinfo_name(fspath)
- return zip_path in self.zipinfo or zip_path in self._index()
-
- def _isdir(self, fspath):
- return self._zipinfo_name(fspath) in self._index()
-
- def _listdir(self, fspath):
- return list(self._index().get(self._zipinfo_name(fspath), ()))
-
- def _eager_to_zip(self, resource_name):
- return self._zipinfo_name(self._fn(self.egg_root, resource_name))
-
- def _resource_to_zip(self, resource_name):
- return self._zipinfo_name(self._fn(self.module_path, resource_name))
-
-
-register_loader_type(zipimport.zipimporter, ZipProvider)
-
-
-class FileMetadata(EmptyProvider):
- """Metadata handler for standalone PKG-INFO files
-
- Usage::
-
- metadata = FileMetadata("/path/to/PKG-INFO")
-
- This provider rejects all data and metadata requests except for PKG-INFO,
- which is treated as existing, and will be the contents of the file at
- the provided location.
- """
-
- def __init__(self, path):
- self.path = path
-
+ return False
+ # check that the contents match
+ zip_contents = self.loader.get_data(zip_path)
+ with open(file_path, 'rb') as f:
+ file_contents = f.read()
+ return zip_contents == file_contents
+
+ def _get_eager_resources(self):
+ if self.eagers is None:
+ eagers = []
+ for name in ('native_libs.txt', 'eager_resources.txt'):
+ if self.has_metadata(name):
+ eagers.extend(self.get_metadata_lines(name))
+ self.eagers = eagers
+ return self.eagers
+
+ def _index(self):
+ try:
+ return self._dirindex
+ except AttributeError:
+ ind = {}
+ for path in self.zipinfo:
+ parts = path.split(os.sep)
+ while parts:
+ parent = os.sep.join(parts[:-1])
+ if parent in ind:
+ ind[parent].append(parts[-1])
+ break
+ else:
+ ind[parent] = [parts.pop()]
+ self._dirindex = ind
+ return ind
+
+ def _has(self, fspath):
+ zip_path = self._zipinfo_name(fspath)
+ return zip_path in self.zipinfo or zip_path in self._index()
+
+ def _isdir(self, fspath):
+ return self._zipinfo_name(fspath) in self._index()
+
+ def _listdir(self, fspath):
+ return list(self._index().get(self._zipinfo_name(fspath), ()))
+
+ def _eager_to_zip(self, resource_name):
+ return self._zipinfo_name(self._fn(self.egg_root, resource_name))
+
+ def _resource_to_zip(self, resource_name):
+ return self._zipinfo_name(self._fn(self.module_path, resource_name))
+
+
+register_loader_type(zipimport.zipimporter, ZipProvider)
+
+
+class FileMetadata(EmptyProvider):
+ """Metadata handler for standalone PKG-INFO files
+
+ Usage::
+
+ metadata = FileMetadata("/path/to/PKG-INFO")
+
+ This provider rejects all data and metadata requests except for PKG-INFO,
+ which is treated as existing, and will be the contents of the file at
+ the provided location.
+ """
+
+ def __init__(self, path):
+ self.path = path
+
def _get_metadata_path(self, name):
return self.path
- def has_metadata(self, name):
+ def has_metadata(self, name):
return name == 'PKG-INFO' and os.path.isfile(self.path)
-
- def get_metadata(self, name):
+
+ def get_metadata(self, name):
if name != 'PKG-INFO':
raise KeyError("No metadata except PKG-INFO is available")
-
+
with io.open(self.path, encoding='utf-8', errors="replace") as f:
metadata = f.read()
self._warn_on_replacement(metadata)
@@ -1907,106 +1907,106 @@ class FileMetadata(EmptyProvider):
msg = tmpl.format(**locals())
warnings.warn(msg)
- def get_metadata_lines(self, name):
- return yield_lines(self.get_metadata(name))
-
-
-class PathMetadata(DefaultProvider):
- """Metadata provider for egg directories
-
- Usage::
-
- # Development eggs:
-
- egg_info = "/path/to/PackageName.egg-info"
- base_dir = os.path.dirname(egg_info)
- metadata = PathMetadata(base_dir, egg_info)
- dist_name = os.path.splitext(os.path.basename(egg_info))[0]
- dist = Distribution(basedir, project_name=dist_name, metadata=metadata)
-
- # Unpacked egg directories:
-
- egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
- metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
- dist = Distribution.from_filename(egg_path, metadata=metadata)
- """
-
- def __init__(self, path, egg_info):
- self.module_path = path
- self.egg_info = egg_info
-
-
-class EggMetadata(ZipProvider):
- """Metadata provider for .egg files"""
-
- def __init__(self, importer):
- """Create a metadata provider from a zipimporter"""
-
+ def get_metadata_lines(self, name):
+ return yield_lines(self.get_metadata(name))
+
+
+class PathMetadata(DefaultProvider):
+ """Metadata provider for egg directories
+
+ Usage::
+
+ # Development eggs:
+
+ egg_info = "/path/to/PackageName.egg-info"
+ base_dir = os.path.dirname(egg_info)
+ metadata = PathMetadata(base_dir, egg_info)
+ dist_name = os.path.splitext(os.path.basename(egg_info))[0]
+ dist = Distribution(basedir, project_name=dist_name, metadata=metadata)
+
+ # Unpacked egg directories:
+
+ egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
+ metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
+ dist = Distribution.from_filename(egg_path, metadata=metadata)
+ """
+
+ def __init__(self, path, egg_info):
+ self.module_path = path
+ self.egg_info = egg_info
+
+
+class EggMetadata(ZipProvider):
+ """Metadata provider for .egg files"""
+
+ def __init__(self, importer):
+ """Create a metadata provider from a zipimporter"""
+
self.zip_pre = importer.archive + os.sep
- self.loader = importer
- if importer.prefix:
- self.module_path = os.path.join(importer.archive, importer.prefix)
- else:
- self.module_path = importer.archive
- self._setup_prefix()
-
-
+ self.loader = importer
+ if importer.prefix:
+ self.module_path = os.path.join(importer.archive, importer.prefix)
+ else:
+ self.module_path = importer.archive
+ self._setup_prefix()
+
+
_declare_state('dict', _distribution_finders={})
-def register_finder(importer_type, distribution_finder):
- """Register `distribution_finder` to find distributions in sys.path items
-
- `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
- handler), and `distribution_finder` is a callable that, passed a path
- item and the importer instance, yields ``Distribution`` instances found on
- that path item. See ``pkg_resources.find_on_path`` for an example."""
- _distribution_finders[importer_type] = distribution_finder
-
-
-def find_distributions(path_item, only=False):
- """Yield distributions accessible via `path_item`"""
- importer = get_importer(path_item)
- finder = _find_adapter(_distribution_finders, importer)
- return finder(importer, path_item, only)
-
-
-def find_eggs_in_zip(importer, path_item, only=False):
- """
- Find eggs in zip files; possibly multiple nested eggs.
- """
- if importer.archive.endswith('.whl'):
- # wheels are not supported with this finder
- # they don't have PKG-INFO metadata, and won't ever contain eggs
- return
- metadata = EggMetadata(importer)
- if metadata.has_metadata('PKG-INFO'):
- yield Distribution.from_filename(path_item, metadata=metadata)
- if only:
- # don't yield nested distros
- return
+def register_finder(importer_type, distribution_finder):
+ """Register `distribution_finder` to find distributions in sys.path items
+
+ `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
+ handler), and `distribution_finder` is a callable that, passed a path
+ item and the importer instance, yields ``Distribution`` instances found on
+ that path item. See ``pkg_resources.find_on_path`` for an example."""
+ _distribution_finders[importer_type] = distribution_finder
+
+
+def find_distributions(path_item, only=False):
+ """Yield distributions accessible via `path_item`"""
+ importer = get_importer(path_item)
+ finder = _find_adapter(_distribution_finders, importer)
+ return finder(importer, path_item, only)
+
+
+def find_eggs_in_zip(importer, path_item, only=False):
+ """
+ Find eggs in zip files; possibly multiple nested eggs.
+ """
+ if importer.archive.endswith('.whl'):
+ # wheels are not supported with this finder
+ # they don't have PKG-INFO metadata, and won't ever contain eggs
+ return
+ metadata = EggMetadata(importer)
+ if metadata.has_metadata('PKG-INFO'):
+ yield Distribution.from_filename(path_item, metadata=metadata)
+ if only:
+ # don't yield nested distros
+ return
for subitem in metadata.resource_listdir(''):
if _is_egg_path(subitem):
- subpath = os.path.join(path_item, subitem)
+ subpath = os.path.join(path_item, subitem)
dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
for dist in dists:
- yield dist
+ yield dist
elif subitem.lower().endswith('.dist-info'):
subpath = os.path.join(path_item, subitem)
submeta = EggMetadata(zipimport.zipimporter(subpath))
submeta.egg_info = subpath
yield Distribution.from_location(path_item, subitem, submeta)
-
-register_finder(zipimport.zipimporter, find_eggs_in_zip)
-
-def find_nothing(importer, path_item, only=False):
- return ()
+register_finder(zipimport.zipimporter, find_eggs_in_zip)
+
+def find_nothing(importer, path_item, only=False):
+ return ()
+
+
+register_finder(object, find_nothing)
-register_finder(object, find_nothing)
-
def _by_version_descending(names):
"""
@@ -2034,15 +2034,15 @@ def _by_version_descending(names):
return sorted(names, key=_by_version, reverse=True)
-def find_on_path(importer, path_item, only=False):
- """Yield distributions accessible on a sys.path directory"""
- path_item = _normalize_cached(path_item)
-
+def find_on_path(importer, path_item, only=False):
+ """Yield distributions accessible on a sys.path directory"""
+ path_item = _normalize_cached(path_item)
+
if _is_unpacked_egg(path_item):
yield Distribution.from_filename(
path_item, metadata=PathMetadata(
path_item, os.path.join(path_item, 'EGG-INFO')
- )
+ )
)
return
@@ -2161,73 +2161,73 @@ def resolve_egg_link(path):
return next(dist_groups, ())
-register_finder(pkgutil.ImpImporter, find_on_path)
-
-if hasattr(importlib_machinery, 'FileFinder'):
- register_finder(importlib_machinery.FileFinder, find_on_path)
-
-_declare_state('dict', _namespace_handlers={})
-_declare_state('dict', _namespace_packages={})
-
-
-def register_namespace_handler(importer_type, namespace_handler):
- """Register `namespace_handler` to declare namespace packages
-
- `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
- handler), and `namespace_handler` is a callable like this::
-
- def namespace_handler(importer, path_entry, moduleName, module):
- # return a path_entry to use for child packages
-
- Namespace handlers are only called if the importer object has already
- agreed that it can handle the relevant path item, and they should only
- return a subpath if the module __path__ does not already contain an
- equivalent subpath. For an example namespace handler, see
- ``pkg_resources.file_ns_handler``.
- """
- _namespace_handlers[importer_type] = namespace_handler
-
-
-def _handle_ns(packageName, path_item):
- """Ensure that named package includes a subpath of path_item (if needed)"""
-
- importer = get_importer(path_item)
- if importer is None:
- return None
+register_finder(pkgutil.ImpImporter, find_on_path)
+
+if hasattr(importlib_machinery, 'FileFinder'):
+ register_finder(importlib_machinery.FileFinder, find_on_path)
+
+_declare_state('dict', _namespace_handlers={})
+_declare_state('dict', _namespace_packages={})
+
+
+def register_namespace_handler(importer_type, namespace_handler):
+ """Register `namespace_handler` to declare namespace packages
+
+ `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
+ handler), and `namespace_handler` is a callable like this::
+
+ def namespace_handler(importer, path_entry, moduleName, module):
+ # return a path_entry to use for child packages
+
+ Namespace handlers are only called if the importer object has already
+ agreed that it can handle the relevant path item, and they should only
+ return a subpath if the module __path__ does not already contain an
+ equivalent subpath. For an example namespace handler, see
+ ``pkg_resources.file_ns_handler``.
+ """
+ _namespace_handlers[importer_type] = namespace_handler
+
+
+def _handle_ns(packageName, path_item):
+ """Ensure that named package includes a subpath of path_item (if needed)"""
+
+ importer = get_importer(path_item)
+ if importer is None:
+ return None
# capture warnings due to #1111
with warnings.catch_warnings():
warnings.simplefilter("ignore")
loader = importer.find_module(packageName)
- if loader is None:
- return None
- module = sys.modules.get(packageName)
- if module is None:
- module = sys.modules[packageName] = types.ModuleType(packageName)
- module.__path__ = []
- _set_parent_ns(packageName)
+ if loader is None:
+ return None
+ module = sys.modules.get(packageName)
+ if module is None:
+ module = sys.modules[packageName] = types.ModuleType(packageName)
+ module.__path__ = []
+ _set_parent_ns(packageName)
elif not hasattr(module, '__path__'):
- raise TypeError("Not a package:", packageName)
- handler = _find_adapter(_namespace_handlers, importer)
- subpath = handler(importer, path_item, packageName, module)
- if subpath is not None:
- path = module.__path__
- path.append(subpath)
- loader.load_module(packageName)
- _rebuild_mod_path(path, packageName, module)
- return subpath
-
-
-def _rebuild_mod_path(orig_path, package_name, module):
- """
- Rebuild module.__path__ ensuring that all entries are ordered
- corresponding to their sys.path order
- """
- sys_path = [_normalize_cached(p) for p in sys.path]
+ raise TypeError("Not a package:", packageName)
+ handler = _find_adapter(_namespace_handlers, importer)
+ subpath = handler(importer, path_item, packageName, module)
+ if subpath is not None:
+ path = module.__path__
+ path.append(subpath)
+ loader.load_module(packageName)
+ _rebuild_mod_path(path, packageName, module)
+ return subpath
+
+
+def _rebuild_mod_path(orig_path, package_name, module):
+ """
+ Rebuild module.__path__ ensuring that all entries are ordered
+ corresponding to their sys.path order
+ """
+ sys_path = [_normalize_cached(p) for p in sys.path]
def safe_sys_path_index(entry):
- """
+ """
Workaround for #520 and #513.
"""
try:
@@ -2237,13 +2237,13 @@ def _rebuild_mod_path(orig_path, package_name, module):
def position_in_sys_path(path):
"""
- Return the ordinal of the path based on its position in sys.path
- """
+ Return the ordinal of the path based on its position in sys.path
+ """
path_parts = path.split(os.sep)
module_parts = package_name.count('.') + 1
parts = path_parts[:-module_parts]
return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))
-
+
new_path = sorted(orig_path, key=position_in_sys_path)
new_path = [_normalize_cached(p) for p in new_path]
@@ -2251,85 +2251,85 @@ def _rebuild_mod_path(orig_path, package_name, module):
module.__path__[:] = new_path
else:
module.__path__ = new_path
-
-
-def declare_namespace(packageName):
- """Declare that package 'packageName' is a namespace package"""
-
- _imp.acquire_lock()
- try:
- if packageName in _namespace_packages:
- return
-
+
+
+def declare_namespace(packageName):
+ """Declare that package 'packageName' is a namespace package"""
+
+ _imp.acquire_lock()
+ try:
+ if packageName in _namespace_packages:
+ return
+
path = sys.path
parent, _, _ = packageName.rpartition('.')
if parent:
- declare_namespace(parent)
- if parent not in _namespace_packages:
- __import__(parent)
- try:
- path = sys.modules[parent].__path__
- except AttributeError:
- raise TypeError("Not a package:", parent)
-
- # Track what packages are namespaces, so when new path items are added,
- # they can be updated
+ declare_namespace(parent)
+ if parent not in _namespace_packages:
+ __import__(parent)
+ try:
+ path = sys.modules[parent].__path__
+ except AttributeError:
+ raise TypeError("Not a package:", parent)
+
+ # Track what packages are namespaces, so when new path items are added,
+ # they can be updated
_namespace_packages.setdefault(parent or None, []).append(packageName)
_namespace_packages.setdefault(packageName, [])
-
- for path_item in path:
- # Ensure all the parent's path items are reflected in the child,
- # if they apply
- _handle_ns(packageName, path_item)
-
- finally:
- _imp.release_lock()
-
-
-def fixup_namespace_packages(path_item, parent=None):
- """Ensure that previously-declared namespace packages include path_item"""
- _imp.acquire_lock()
- try:
+
+ for path_item in path:
+ # Ensure all the parent's path items are reflected in the child,
+ # if they apply
+ _handle_ns(packageName, path_item)
+
+ finally:
+ _imp.release_lock()
+
+
+def fixup_namespace_packages(path_item, parent=None):
+ """Ensure that previously-declared namespace packages include path_item"""
+ _imp.acquire_lock()
+ try:
for package in _namespace_packages.get(parent, ()):
- subpath = _handle_ns(package, path_item)
- if subpath:
- fixup_namespace_packages(subpath, package)
- finally:
- _imp.release_lock()
-
-
-def file_ns_handler(importer, path_item, packageName, module):
- """Compute an ns-package subpath for a filesystem or zipfile importer"""
-
- subpath = os.path.join(path_item, packageName.split('.')[-1])
- normalized = _normalize_cached(subpath)
- for item in module.__path__:
+ subpath = _handle_ns(package, path_item)
+ if subpath:
+ fixup_namespace_packages(subpath, package)
+ finally:
+ _imp.release_lock()
+
+
+def file_ns_handler(importer, path_item, packageName, module):
+ """Compute an ns-package subpath for a filesystem or zipfile importer"""
+
+ subpath = os.path.join(path_item, packageName.split('.')[-1])
+ normalized = _normalize_cached(subpath)
+ for item in module.__path__:
if _normalize_cached(item) == normalized:
- break
- else:
- # Only return the path if it's not already there
- return subpath
-
-
-register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)
-register_namespace_handler(zipimport.zipimporter, file_ns_handler)
-
-if hasattr(importlib_machinery, 'FileFinder'):
- register_namespace_handler(importlib_machinery.FileFinder, file_ns_handler)
-
-
-def null_ns_handler(importer, path_item, packageName, module):
- return None
-
-
-register_namespace_handler(object, null_ns_handler)
-
-
-def normalize_path(filename):
- """Normalize a file/dir name for comparison purposes"""
+ break
+ else:
+ # Only return the path if it's not already there
+ return subpath
+
+
+register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)
+register_namespace_handler(zipimport.zipimporter, file_ns_handler)
+
+if hasattr(importlib_machinery, 'FileFinder'):
+ register_namespace_handler(importlib_machinery.FileFinder, file_ns_handler)
+
+
+def null_ns_handler(importer, path_item, packageName, module):
+ return None
+
+
+register_namespace_handler(object, null_ns_handler)
+
+
+def normalize_path(filename):
+ """Normalize a file/dir name for comparison purposes"""
return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))
-
+
def _cygwin_patch(filename): # pragma: nocover
"""
@@ -2342,13 +2342,13 @@ def _cygwin_patch(filename): # pragma: nocover
return os.path.abspath(filename) if sys.platform == 'cygwin' else filename
-def _normalize_cached(filename, _cache={}):
- try:
- return _cache[filename]
- except KeyError:
- _cache[filename] = result = normalize_path(filename)
- return result
-
+def _normalize_cached(filename, _cache={}):
+ try:
+ return _cache[filename]
+ except KeyError:
+ _cache[filename] = result = normalize_path(filename)
+ return result
+
def _is_egg_path(path):
"""
@@ -2357,351 +2357,351 @@ def _is_egg_path(path):
return path.lower().endswith('.egg')
-def _is_unpacked_egg(path):
- """
- Determine if given path appears to be an unpacked egg.
- """
- return (
+def _is_unpacked_egg(path):
+ """
+ Determine if given path appears to be an unpacked egg.
+ """
+ return (
_is_egg_path(path) and
os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO'))
- )
-
-
-def _set_parent_ns(packageName):
- parts = packageName.split('.')
- name = parts.pop()
- if parts:
- parent = '.'.join(parts)
- setattr(sys.modules[parent], name, sys.modules[packageName])
-
-
-def yield_lines(strs):
- """Yield non-empty/non-comment lines of a string or sequence"""
- if isinstance(strs, six.string_types):
- for s in strs.splitlines():
- s = s.strip()
- # skip blank lines/comments
- if s and not s.startswith('#'):
- yield s
- else:
- for ss in strs:
- for s in yield_lines(ss):
- yield s
-
-
-MODULE = re.compile(r"\w+(\.\w+)*$").match
-EGG_NAME = re.compile(
- r"""
- (?P<name>[^-]+) (
- -(?P<ver>[^-]+) (
- -py(?P<pyver>[^-]+) (
- -(?P<plat>.+)
- )?
- )?
- )?
- """,
- re.VERBOSE | re.IGNORECASE,
-).match
-
-
+ )
+
+
+def _set_parent_ns(packageName):
+ parts = packageName.split('.')
+ name = parts.pop()
+ if parts:
+ parent = '.'.join(parts)
+ setattr(sys.modules[parent], name, sys.modules[packageName])
+
+
+def yield_lines(strs):
+ """Yield non-empty/non-comment lines of a string or sequence"""
+ if isinstance(strs, six.string_types):
+ for s in strs.splitlines():
+ s = s.strip()
+ # skip blank lines/comments
+ if s and not s.startswith('#'):
+ yield s
+ else:
+ for ss in strs:
+ for s in yield_lines(ss):
+ yield s
+
+
+MODULE = re.compile(r"\w+(\.\w+)*$").match
+EGG_NAME = re.compile(
+ r"""
+ (?P<name>[^-]+) (
+ -(?P<ver>[^-]+) (
+ -py(?P<pyver>[^-]+) (
+ -(?P<plat>.+)
+ )?
+ )?
+ )?
+ """,
+ re.VERBOSE | re.IGNORECASE,
+).match
+
+
class EntryPoint:
- """Object representing an advertised importable object"""
-
- def __init__(self, name, module_name, attrs=(), extras=(), dist=None):
- if not MODULE(module_name):
- raise ValueError("Invalid module name", module_name)
- self.name = name
- self.module_name = module_name
- self.attrs = tuple(attrs)
+ """Object representing an advertised importable object"""
+
+ def __init__(self, name, module_name, attrs=(), extras=(), dist=None):
+ if not MODULE(module_name):
+ raise ValueError("Invalid module name", module_name)
+ self.name = name
+ self.module_name = module_name
+ self.attrs = tuple(attrs)
self.extras = tuple(extras)
- self.dist = dist
-
- def __str__(self):
- s = "%s = %s" % (self.name, self.module_name)
- if self.attrs:
- s += ':' + '.'.join(self.attrs)
- if self.extras:
- s += ' [%s]' % ','.join(self.extras)
- return s
-
- def __repr__(self):
- return "EntryPoint.parse(%r)" % str(self)
-
- def load(self, require=True, *args, **kwargs):
- """
- Require packages for this EntryPoint, then resolve it.
- """
- if not require or args or kwargs:
- warnings.warn(
- "Parameters to load are deprecated. Call .resolve and "
- ".require separately.",
+ self.dist = dist
+
+ def __str__(self):
+ s = "%s = %s" % (self.name, self.module_name)
+ if self.attrs:
+ s += ':' + '.'.join(self.attrs)
+ if self.extras:
+ s += ' [%s]' % ','.join(self.extras)
+ return s
+
+ def __repr__(self):
+ return "EntryPoint.parse(%r)" % str(self)
+
+ def load(self, require=True, *args, **kwargs):
+ """
+ Require packages for this EntryPoint, then resolve it.
+ """
+ if not require or args or kwargs:
+ warnings.warn(
+ "Parameters to load are deprecated. Call .resolve and "
+ ".require separately.",
PkgResourcesDeprecationWarning,
- stacklevel=2,
- )
- if require:
- self.require(*args, **kwargs)
- return self.resolve()
-
- def resolve(self):
- """
- Resolve the entry point from its module and attrs.
- """
- module = __import__(self.module_name, fromlist=['__name__'], level=0)
- try:
- return functools.reduce(getattr, self.attrs, module)
- except AttributeError as exc:
- raise ImportError(str(exc))
-
- def require(self, env=None, installer=None):
- if self.extras and not self.dist:
- raise UnknownExtra("Can't require() without a distribution", self)
+ stacklevel=2,
+ )
+ if require:
+ self.require(*args, **kwargs)
+ return self.resolve()
+
+ def resolve(self):
+ """
+ Resolve the entry point from its module and attrs.
+ """
+ module = __import__(self.module_name, fromlist=['__name__'], level=0)
+ try:
+ return functools.reduce(getattr, self.attrs, module)
+ except AttributeError as exc:
+ raise ImportError(str(exc))
+
+ def require(self, env=None, installer=None):
+ if self.extras and not self.dist:
+ raise UnknownExtra("Can't require() without a distribution", self)
# Get the requirements for this entry point with all its extras and
# then resolve them. We have to pass `extras` along when resolving so
# that the working set knows what extras we want. Otherwise, for
# dist-info distributions, the working set will assume that the
# requirements for that extra are purely optional and skip over them.
- reqs = self.dist.requires(self.extras)
+ reqs = self.dist.requires(self.extras)
items = working_set.resolve(reqs, env, installer, extras=self.extras)
- list(map(working_set.add, items))
-
- pattern = re.compile(
- r'\s*'
- r'(?P<name>.+?)\s*'
- r'=\s*'
- r'(?P<module>[\w.]+)\s*'
- r'(:\s*(?P<attr>[\w.]+))?\s*'
- r'(?P<extras>\[.*\])?\s*$'
- )
-
- @classmethod
- def parse(cls, src, dist=None):
- """Parse a single entry point from string `src`
-
- Entry point syntax follows the form::
-
- name = some.module:some.attr [extra1, extra2]
-
- The entry name and module name are required, but the ``:attrs`` and
- ``[extras]`` parts are optional
- """
- m = cls.pattern.match(src)
- if not m:
- msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
- raise ValueError(msg, src)
- res = m.groupdict()
- extras = cls._parse_extras(res['extras'])
- attrs = res['attr'].split('.') if res['attr'] else ()
- return cls(res['name'], res['module'], attrs, extras, dist)
-
- @classmethod
- def _parse_extras(cls, extras_spec):
- if not extras_spec:
- return ()
- req = Requirement.parse('x' + extras_spec)
- if req.specs:
- raise ValueError()
- return req.extras
-
- @classmethod
- def parse_group(cls, group, lines, dist=None):
- """Parse an entry point group"""
- if not MODULE(group):
- raise ValueError("Invalid group name", group)
- this = {}
- for line in yield_lines(lines):
- ep = cls.parse(line, dist)
- if ep.name in this:
- raise ValueError("Duplicate entry point", group, ep.name)
+ list(map(working_set.add, items))
+
+ pattern = re.compile(
+ r'\s*'
+ r'(?P<name>.+?)\s*'
+ r'=\s*'
+ r'(?P<module>[\w.]+)\s*'
+ r'(:\s*(?P<attr>[\w.]+))?\s*'
+ r'(?P<extras>\[.*\])?\s*$'
+ )
+
+ @classmethod
+ def parse(cls, src, dist=None):
+ """Parse a single entry point from string `src`
+
+ Entry point syntax follows the form::
+
+ name = some.module:some.attr [extra1, extra2]
+
+ The entry name and module name are required, but the ``:attrs`` and
+ ``[extras]`` parts are optional
+ """
+ m = cls.pattern.match(src)
+ if not m:
+ msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
+ raise ValueError(msg, src)
+ res = m.groupdict()
+ extras = cls._parse_extras(res['extras'])
+ attrs = res['attr'].split('.') if res['attr'] else ()
+ return cls(res['name'], res['module'], attrs, extras, dist)
+
+ @classmethod
+ def _parse_extras(cls, extras_spec):
+ if not extras_spec:
+ return ()
+ req = Requirement.parse('x' + extras_spec)
+ if req.specs:
+ raise ValueError()
+ return req.extras
+
+ @classmethod
+ def parse_group(cls, group, lines, dist=None):
+ """Parse an entry point group"""
+ if not MODULE(group):
+ raise ValueError("Invalid group name", group)
+ this = {}
+ for line in yield_lines(lines):
+ ep = cls.parse(line, dist)
+ if ep.name in this:
+ raise ValueError("Duplicate entry point", group, ep.name)
this[ep.name] = ep
- return this
-
- @classmethod
- def parse_map(cls, data, dist=None):
- """Parse a map of entry point groups"""
- if isinstance(data, dict):
- data = data.items()
- else:
- data = split_sections(data)
- maps = {}
- for group, lines in data:
- if group is None:
- if not lines:
- continue
- raise ValueError("Entry points must be listed in groups")
- group = group.strip()
- if group in maps:
- raise ValueError("Duplicate group name", group)
- maps[group] = cls.parse_group(group, lines, dist)
- return maps
-
-
-def _remove_md5_fragment(location):
- if not location:
- return ''
- parsed = urllib.parse.urlparse(location)
- if parsed[-1].startswith('md5='):
- return urllib.parse.urlunparse(parsed[:-1] + ('',))
- return location
-
-
-def _version_from_file(lines):
- """
- Given an iterable of lines from a Metadata file, return
- the value of the Version field, if present, or None otherwise.
- """
+ return this
+
+ @classmethod
+ def parse_map(cls, data, dist=None):
+ """Parse a map of entry point groups"""
+ if isinstance(data, dict):
+ data = data.items()
+ else:
+ data = split_sections(data)
+ maps = {}
+ for group, lines in data:
+ if group is None:
+ if not lines:
+ continue
+ raise ValueError("Entry points must be listed in groups")
+ group = group.strip()
+ if group in maps:
+ raise ValueError("Duplicate group name", group)
+ maps[group] = cls.parse_group(group, lines, dist)
+ return maps
+
+
+def _remove_md5_fragment(location):
+ if not location:
+ return ''
+ parsed = urllib.parse.urlparse(location)
+ if parsed[-1].startswith('md5='):
+ return urllib.parse.urlunparse(parsed[:-1] + ('',))
+ return location
+
+
+def _version_from_file(lines):
+ """
+ Given an iterable of lines from a Metadata file, return
+ the value of the Version field, if present, or None otherwise.
+ """
def is_version_line(line):
return line.lower().startswith('version:')
- version_lines = filter(is_version_line, lines)
- line = next(iter(version_lines), '')
- _, _, value = line.partition(':')
- return safe_version(value.strip()) or None
-
-
+ version_lines = filter(is_version_line, lines)
+ line = next(iter(version_lines), '')
+ _, _, value = line.partition(':')
+ return safe_version(value.strip()) or None
+
+
class Distribution:
- """Wrap an actual or potential sys.path entry w/metadata"""
- PKG_INFO = 'PKG-INFO'
-
+ """Wrap an actual or potential sys.path entry w/metadata"""
+ PKG_INFO = 'PKG-INFO'
+
def __init__(
self, location=None, metadata=None, project_name=None,
- version=None, py_version=PY_MAJOR, platform=None,
- precedence=EGG_DIST):
- self.project_name = safe_name(project_name or 'Unknown')
- if version is not None:
- self._version = safe_version(version)
- self.py_version = py_version
- self.platform = platform
- self.location = location
- self.precedence = precedence
- self._provider = metadata or empty_provider
-
- @classmethod
- def from_location(cls, location, basename, metadata=None, **kw):
+ version=None, py_version=PY_MAJOR, platform=None,
+ precedence=EGG_DIST):
+ self.project_name = safe_name(project_name or 'Unknown')
+ if version is not None:
+ self._version = safe_version(version)
+ self.py_version = py_version
+ self.platform = platform
+ self.location = location
+ self.precedence = precedence
+ self._provider = metadata or empty_provider
+
+ @classmethod
+ def from_location(cls, location, basename, metadata=None, **kw):
project_name, version, py_version, platform = [None] * 4
- basename, ext = os.path.splitext(basename)
- if ext.lower() in _distributionImpl:
- cls = _distributionImpl[ext.lower()]
-
- match = EGG_NAME(basename)
- if match:
- project_name, version, py_version, platform = match.group(
- 'name', 'ver', 'pyver', 'plat'
- )
- return cls(
- location, metadata, project_name=project_name, version=version,
- py_version=py_version, platform=platform, **kw
- )._reload_version()
-
- def _reload_version(self):
- return self
-
- @property
- def hashcmp(self):
- return (
- self.parsed_version,
- self.precedence,
- self.key,
- _remove_md5_fragment(self.location),
- self.py_version or '',
- self.platform or '',
- )
-
- def __hash__(self):
- return hash(self.hashcmp)
-
- def __lt__(self, other):
- return self.hashcmp < other.hashcmp
-
- def __le__(self, other):
- return self.hashcmp <= other.hashcmp
-
- def __gt__(self, other):
- return self.hashcmp > other.hashcmp
-
- def __ge__(self, other):
- return self.hashcmp >= other.hashcmp
-
- def __eq__(self, other):
- if not isinstance(other, self.__class__):
- # It's not a Distribution, so they are not equal
- return False
- return self.hashcmp == other.hashcmp
-
- def __ne__(self, other):
- return not self == other
-
- # These properties have to be lazy so that we don't have to load any
- # metadata until/unless it's actually needed. (i.e., some distributions
- # may not know their name or version without loading PKG-INFO)
-
- @property
- def key(self):
- try:
- return self._key
- except AttributeError:
- self._key = key = self.project_name.lower()
- return key
-
- @property
- def parsed_version(self):
- if not hasattr(self, "_parsed_version"):
- self._parsed_version = parse_version(self.version)
-
- return self._parsed_version
-
- def _warn_legacy_version(self):
- LV = packaging.version.LegacyVersion
- is_legacy = isinstance(self._parsed_version, LV)
- if not is_legacy:
- return
-
- # While an empty version is technically a legacy version and
- # is not a valid PEP 440 version, it's also unlikely to
- # actually come from someone and instead it is more likely that
- # it comes from setuptools attempting to parse a filename and
- # including it in the list. So for that we'll gate this warning
- # on if the version is anything at all or not.
- if not self.version:
- return
-
- tmpl = textwrap.dedent("""
- '{project_name} ({version})' is being parsed as a legacy,
- non PEP 440,
- version. You may find odd behavior and sort order.
- In particular it will be sorted as less than 0.0. It
- is recommended to migrate to PEP 440 compatible
- versions.
- """).strip().replace('\n', ' ')
-
- warnings.warn(tmpl.format(**vars(self)), PEP440Warning)
-
- @property
- def version(self):
- try:
- return self._version
- except AttributeError:
+ basename, ext = os.path.splitext(basename)
+ if ext.lower() in _distributionImpl:
+ cls = _distributionImpl[ext.lower()]
+
+ match = EGG_NAME(basename)
+ if match:
+ project_name, version, py_version, platform = match.group(
+ 'name', 'ver', 'pyver', 'plat'
+ )
+ return cls(
+ location, metadata, project_name=project_name, version=version,
+ py_version=py_version, platform=platform, **kw
+ )._reload_version()
+
+ def _reload_version(self):
+ return self
+
+ @property
+ def hashcmp(self):
+ return (
+ self.parsed_version,
+ self.precedence,
+ self.key,
+ _remove_md5_fragment(self.location),
+ self.py_version or '',
+ self.platform or '',
+ )
+
+ def __hash__(self):
+ return hash(self.hashcmp)
+
+ def __lt__(self, other):
+ return self.hashcmp < other.hashcmp
+
+ def __le__(self, other):
+ return self.hashcmp <= other.hashcmp
+
+ def __gt__(self, other):
+ return self.hashcmp > other.hashcmp
+
+ def __ge__(self, other):
+ return self.hashcmp >= other.hashcmp
+
+ def __eq__(self, other):
+ if not isinstance(other, self.__class__):
+ # It's not a Distribution, so they are not equal
+ return False
+ return self.hashcmp == other.hashcmp
+
+ def __ne__(self, other):
+ return not self == other
+
+ # These properties have to be lazy so that we don't have to load any
+ # metadata until/unless it's actually needed. (i.e., some distributions
+ # may not know their name or version without loading PKG-INFO)
+
+ @property
+ def key(self):
+ try:
+ return self._key
+ except AttributeError:
+ self._key = key = self.project_name.lower()
+ return key
+
+ @property
+ def parsed_version(self):
+ if not hasattr(self, "_parsed_version"):
+ self._parsed_version = parse_version(self.version)
+
+ return self._parsed_version
+
+ def _warn_legacy_version(self):
+ LV = packaging.version.LegacyVersion
+ is_legacy = isinstance(self._parsed_version, LV)
+ if not is_legacy:
+ return
+
+ # While an empty version is technically a legacy version and
+ # is not a valid PEP 440 version, it's also unlikely to
+ # actually come from someone and instead it is more likely that
+ # it comes from setuptools attempting to parse a filename and
+ # including it in the list. So for that we'll gate this warning
+ # on if the version is anything at all or not.
+ if not self.version:
+ return
+
+ tmpl = textwrap.dedent("""
+ '{project_name} ({version})' is being parsed as a legacy,
+ non PEP 440,
+ version. You may find odd behavior and sort order.
+ In particular it will be sorted as less than 0.0. It
+ is recommended to migrate to PEP 440 compatible
+ versions.
+ """).strip().replace('\n', ' ')
+
+ warnings.warn(tmpl.format(**vars(self)), PEP440Warning)
+
+ @property
+ def version(self):
+ try:
+ return self._version
+ except AttributeError:
version = self._get_version()
- if version is None:
+ if version is None:
path = self._get_metadata_path_for_display(self.PKG_INFO)
msg = (
"Missing 'Version:' header and/or {} file at path: {}"
).format(self.PKG_INFO, path)
raise ValueError(msg, self)
- return version
-
- @property
- def _dep_map(self):
+ return version
+
+ @property
+ def _dep_map(self):
"""
A map of extra to its list of (direct) requirements
for this distribution, including the null extra.
"""
- try:
- return self.__dep_map
- except AttributeError:
+ try:
+ return self.__dep_map
+ except AttributeError:
self.__dep_map = self._filter_extras(self._build_dep_map())
return self.__dep_map
-
+
@staticmethod
def _filter_extras(dm):
"""
@@ -2731,20 +2731,20 @@ class Distribution:
dm.setdefault(extra, []).extend(parse_requirements(reqs))
return dm
- def requires(self, extras=()):
- """List of Requirements needed for this distro if `extras` are used"""
- dm = self._dep_map
- deps = []
- deps.extend(dm.get(None, ()))
- for ext in extras:
- try:
- deps.extend(dm[safe_extra(ext)])
- except KeyError:
- raise UnknownExtra(
- "%s has no such extra feature %r" % (self, ext)
- )
- return deps
-
+ def requires(self, extras=()):
+ """List of Requirements needed for this distro if `extras` are used"""
+ dm = self._dep_map
+ deps = []
+ deps.extend(dm.get(None, ()))
+ for ext in extras:
+ try:
+ deps.extend(dm[safe_extra(ext)])
+ except KeyError:
+ raise UnknownExtra(
+ "%s has no such extra feature %r" % (self, ext)
+ )
+ return deps
+
def _get_metadata_path_for_display(self, name):
"""
Return the path to the given metadata file, if available.
@@ -2762,11 +2762,11 @@ class Distribution:
return path
- def _get_metadata(self, name):
- if self.has_metadata(name):
- for line in self.get_metadata_lines(name):
- yield line
-
+ def _get_metadata(self, name):
+ if self.has_metadata(name):
+ for line in self.get_metadata_lines(name):
+ yield line
+
def _get_version(self):
lines = self._get_metadata(self.PKG_INFO)
version = _version_from_file(lines)
@@ -2774,47 +2774,47 @@ class Distribution:
return version
def activate(self, path=None, replace=False):
- """Ensure distribution is importable on `path` (default=sys.path)"""
- if path is None:
- path = sys.path
+ """Ensure distribution is importable on `path` (default=sys.path)"""
+ if path is None:
+ path = sys.path
self.insert_on(path, replace=replace)
- if path is sys.path:
- fixup_namespace_packages(self.location)
- for pkg in self._get_metadata('namespace_packages.txt'):
- if pkg in sys.modules:
- declare_namespace(pkg)
-
- def egg_name(self):
- """Return what this distribution's standard .egg filename should be"""
- filename = "%s-%s-py%s" % (
- to_filename(self.project_name), to_filename(self.version),
- self.py_version or PY_MAJOR
- )
-
- if self.platform:
- filename += '-' + self.platform
- return filename
-
- def __repr__(self):
- if self.location:
- return "%s (%s)" % (self, self.location)
- else:
- return str(self)
-
- def __str__(self):
- try:
- version = getattr(self, 'version', None)
- except ValueError:
- version = None
- version = version or "[unknown version]"
- return "%s %s" % (self.project_name, version)
-
- def __getattr__(self, attr):
- """Delegate all unrecognized public attributes to .metadata provider"""
- if attr.startswith('_'):
- raise AttributeError(attr)
- return getattr(self._provider, attr)
-
+ if path is sys.path:
+ fixup_namespace_packages(self.location)
+ for pkg in self._get_metadata('namespace_packages.txt'):
+ if pkg in sys.modules:
+ declare_namespace(pkg)
+
+ def egg_name(self):
+ """Return what this distribution's standard .egg filename should be"""
+ filename = "%s-%s-py%s" % (
+ to_filename(self.project_name), to_filename(self.version),
+ self.py_version or PY_MAJOR
+ )
+
+ if self.platform:
+ filename += '-' + self.platform
+ return filename
+
+ def __repr__(self):
+ if self.location:
+ return "%s (%s)" % (self, self.location)
+ else:
+ return str(self)
+
+ def __str__(self):
+ try:
+ version = getattr(self, 'version', None)
+ except ValueError:
+ version = None
+ version = version or "[unknown version]"
+ return "%s %s" % (self.project_name, version)
+
+ def __getattr__(self, attr):
+ """Delegate all unrecognized public attributes to .metadata provider"""
+ if attr.startswith('_'):
+ raise AttributeError(attr)
+ return getattr(self._provider, attr)
+
def __dir__(self):
return list(
set(super(Distribution, self).__dir__())
@@ -2828,48 +2828,48 @@ class Distribution:
# python 2.7 not supported
del __dir__
- @classmethod
- def from_filename(cls, filename, metadata=None, **kw):
- return cls.from_location(
- _normalize_cached(filename), os.path.basename(filename), metadata,
- **kw
- )
-
- def as_requirement(self):
- """Return a ``Requirement`` that matches this distribution exactly"""
- if isinstance(self.parsed_version, packaging.version.Version):
- spec = "%s==%s" % (self.project_name, self.parsed_version)
- else:
- spec = "%s===%s" % (self.project_name, self.parsed_version)
-
- return Requirement.parse(spec)
-
- def load_entry_point(self, group, name):
- """Return the `name` entry point of `group` or raise ImportError"""
- ep = self.get_entry_info(group, name)
- if ep is None:
- raise ImportError("Entry point %r not found" % ((group, name),))
- return ep.load()
-
- def get_entry_map(self, group=None):
- """Return the entry point map for `group`, or the full entry map"""
- try:
- ep_map = self._ep_map
- except AttributeError:
- ep_map = self._ep_map = EntryPoint.parse_map(
- self._get_metadata('entry_points.txt'), self
- )
- if group is not None:
+ @classmethod
+ def from_filename(cls, filename, metadata=None, **kw):
+ return cls.from_location(
+ _normalize_cached(filename), os.path.basename(filename), metadata,
+ **kw
+ )
+
+ def as_requirement(self):
+ """Return a ``Requirement`` that matches this distribution exactly"""
+ if isinstance(self.parsed_version, packaging.version.Version):
+ spec = "%s==%s" % (self.project_name, self.parsed_version)
+ else:
+ spec = "%s===%s" % (self.project_name, self.parsed_version)
+
+ return Requirement.parse(spec)
+
+ def load_entry_point(self, group, name):
+ """Return the `name` entry point of `group` or raise ImportError"""
+ ep = self.get_entry_info(group, name)
+ if ep is None:
+ raise ImportError("Entry point %r not found" % ((group, name),))
+ return ep.load()
+
+ def get_entry_map(self, group=None):
+ """Return the entry point map for `group`, or the full entry map"""
+ try:
+ ep_map = self._ep_map
+ except AttributeError:
+ ep_map = self._ep_map = EntryPoint.parse_map(
+ self._get_metadata('entry_points.txt'), self
+ )
+ if group is not None:
return ep_map.get(group, {})
- return ep_map
-
- def get_entry_info(self, group, name):
- """Return the EntryPoint object for `group`+`name`, or ``None``"""
- return self.get_entry_map(group).get(name)
-
- def insert_on(self, path, loc=None, replace=False):
+ return ep_map
+
+ def get_entry_info(self, group, name):
+ """Return the EntryPoint object for `group`+`name`, or ``None``"""
+ return self.get_entry_map(group).get(name)
+
+ def insert_on(self, path, loc=None, replace=False):
"""Ensure self.location is on path
-
+
If replace=False (default):
- If location is already in path anywhere, do nothing.
- Else:
@@ -2887,200 +2887,200 @@ class Distribution:
- Else: add it to the front of path.
"""
- loc = loc or self.location
- if not loc:
- return
-
- nloc = _normalize_cached(loc)
- bdir = os.path.dirname(nloc)
+ loc = loc or self.location
+ if not loc:
+ return
+
+ nloc = _normalize_cached(loc)
+ bdir = os.path.dirname(nloc)
npath = [(p and _normalize_cached(p) or p) for p in path]
-
- for p, item in enumerate(npath):
- if item == nloc:
+
+ for p, item in enumerate(npath):
+ if item == nloc:
if replace:
break
else:
# don't modify path (even removing duplicates) if
# found and not replace
return
- elif item == bdir and self.precedence == EGG_DIST:
- # if it's an .egg, give it precedence over its directory
+ elif item == bdir and self.precedence == EGG_DIST:
+ # if it's an .egg, give it precedence over its directory
# UNLESS it's already been added to sys.path and replace=False
if (not replace) and nloc in npath[p:]:
return
- if path is sys.path:
- self.check_version_conflict()
- path.insert(p, loc)
- npath.insert(p, nloc)
- break
- else:
- if path is sys.path:
- self.check_version_conflict()
- if replace:
- path.insert(0, loc)
- else:
- path.append(loc)
- return
-
- # p is the spot where we found or inserted loc; now remove duplicates
- while True:
- try:
+ if path is sys.path:
+ self.check_version_conflict()
+ path.insert(p, loc)
+ npath.insert(p, nloc)
+ break
+ else:
+ if path is sys.path:
+ self.check_version_conflict()
+ if replace:
+ path.insert(0, loc)
+ else:
+ path.append(loc)
+ return
+
+ # p is the spot where we found or inserted loc; now remove duplicates
+ while True:
+ try:
np = npath.index(nloc, p + 1)
- except ValueError:
- break
- else:
- del npath[np], path[np]
- # ha!
- p = np
-
- return
-
- def check_version_conflict(self):
- if self.key == 'setuptools':
- # ignore the inevitable setuptools self-conflicts :(
- return
-
- nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
- loc = normalize_path(self.location)
- for modname in self._get_metadata('top_level.txt'):
- if (modname not in sys.modules or modname in nsp
- or modname in _namespace_packages):
- continue
- if modname in ('pkg_resources', 'setuptools', 'site'):
- continue
- fn = getattr(sys.modules[modname], '__file__', None)
- if fn and (normalize_path(fn).startswith(loc) or
- fn.startswith(self.location)):
- continue
- issue_warning(
- "Module %s was already imported from %s, but %s is being added"
- " to sys.path" % (modname, fn, self.location),
- )
-
- def has_version(self):
- try:
- self.version
- except ValueError:
- issue_warning("Unbuilt egg for " + repr(self))
- return False
- return True
-
+ except ValueError:
+ break
+ else:
+ del npath[np], path[np]
+ # ha!
+ p = np
+
+ return
+
+ def check_version_conflict(self):
+ if self.key == 'setuptools':
+ # ignore the inevitable setuptools self-conflicts :(
+ return
+
+ nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
+ loc = normalize_path(self.location)
+ for modname in self._get_metadata('top_level.txt'):
+ if (modname not in sys.modules or modname in nsp
+ or modname in _namespace_packages):
+ continue
+ if modname in ('pkg_resources', 'setuptools', 'site'):
+ continue
+ fn = getattr(sys.modules[modname], '__file__', None)
+ if fn and (normalize_path(fn).startswith(loc) or
+ fn.startswith(self.location)):
+ continue
+ issue_warning(
+ "Module %s was already imported from %s, but %s is being added"
+ " to sys.path" % (modname, fn, self.location),
+ )
+
+ def has_version(self):
+ try:
+ self.version
+ except ValueError:
+ issue_warning("Unbuilt egg for " + repr(self))
+ return False
+ return True
+
def clone(self, **kw):
- """Copy this distribution, substituting in any changed keyword args"""
- names = 'project_name version py_version platform location precedence'
- for attr in names.split():
- kw.setdefault(attr, getattr(self, attr, None))
- kw.setdefault('metadata', self._provider)
- return self.__class__(**kw)
-
- @property
- def extras(self):
- return [dep for dep in self._dep_map if dep]
-
-
-class EggInfoDistribution(Distribution):
- def _reload_version(self):
- """
- Packages installed by distutils (e.g. numpy or scipy),
- which uses an old safe_version, and so
- their version numbers can get mangled when
- converted to filenames (e.g., 1.11.0.dev0+2329eae to
- 1.11.0.dev0_2329eae). These distributions will not be
- parsed properly
- downstream by Distribution and safe_version, so
- take an extra step and try to get the version number from
- the metadata file itself instead of the filename.
- """
+ """Copy this distribution, substituting in any changed keyword args"""
+ names = 'project_name version py_version platform location precedence'
+ for attr in names.split():
+ kw.setdefault(attr, getattr(self, attr, None))
+ kw.setdefault('metadata', self._provider)
+ return self.__class__(**kw)
+
+ @property
+ def extras(self):
+ return [dep for dep in self._dep_map if dep]
+
+
+class EggInfoDistribution(Distribution):
+ def _reload_version(self):
+ """
+ Packages installed by distutils (e.g. numpy or scipy),
+ which uses an old safe_version, and so
+ their version numbers can get mangled when
+ converted to filenames (e.g., 1.11.0.dev0+2329eae to
+ 1.11.0.dev0_2329eae). These distributions will not be
+ parsed properly
+ downstream by Distribution and safe_version, so
+ take an extra step and try to get the version number from
+ the metadata file itself instead of the filename.
+ """
md_version = self._get_version()
- if md_version:
- self._version = md_version
- return self
-
-
-class DistInfoDistribution(Distribution):
+ if md_version:
+ self._version = md_version
+ return self
+
+
+class DistInfoDistribution(Distribution):
"""
Wrap an actual or potential sys.path entry
w/metadata, .dist-info style.
"""
- PKG_INFO = 'METADATA'
- EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
-
- @property
- def _parsed_pkg_info(self):
- """Parse and cache metadata"""
- try:
- return self._pkg_info
- except AttributeError:
- metadata = self.get_metadata(self.PKG_INFO)
- self._pkg_info = email.parser.Parser().parsestr(metadata)
- return self._pkg_info
-
- @property
- def _dep_map(self):
- try:
- return self.__dep_map
- except AttributeError:
- self.__dep_map = self._compute_dependencies()
- return self.__dep_map
-
- def _compute_dependencies(self):
- """Recompute this distribution's dependencies."""
- dm = self.__dep_map = {None: []}
-
- reqs = []
- # Including any condition expressions
- for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
+ PKG_INFO = 'METADATA'
+ EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
+
+ @property
+ def _parsed_pkg_info(self):
+ """Parse and cache metadata"""
+ try:
+ return self._pkg_info
+ except AttributeError:
+ metadata = self.get_metadata(self.PKG_INFO)
+ self._pkg_info = email.parser.Parser().parsestr(metadata)
+ return self._pkg_info
+
+ @property
+ def _dep_map(self):
+ try:
+ return self.__dep_map
+ except AttributeError:
+ self.__dep_map = self._compute_dependencies()
+ return self.__dep_map
+
+ def _compute_dependencies(self):
+ """Recompute this distribution's dependencies."""
+ dm = self.__dep_map = {None: []}
+
+ reqs = []
+ # Including any condition expressions
+ for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
reqs.extend(parse_requirements(req))
-
- def reqs_for_extra(extra):
- for req in reqs:
+
+ def reqs_for_extra(extra):
+ for req in reqs:
if not req.marker or req.marker.evaluate({'extra': extra}):
- yield req
-
- common = frozenset(reqs_for_extra(None))
- dm[None].extend(common)
-
- for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
+ yield req
+
+ common = frozenset(reqs_for_extra(None))
+ dm[None].extend(common)
+
+ for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
s_extra = safe_extra(extra.strip())
dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common)
-
- return dm
-
-
-_distributionImpl = {
- '.egg': Distribution,
- '.egg-info': EggInfoDistribution,
- '.dist-info': DistInfoDistribution,
+
+ return dm
+
+
+_distributionImpl = {
+ '.egg': Distribution,
+ '.egg-info': EggInfoDistribution,
+ '.dist-info': DistInfoDistribution,
}
-
-
+
+
def issue_warning(*args, **kw):
- level = 1
- g = globals()
- try:
- # find the first stack frame that is *not* code in
- # the pkg_resources module, to use for the warning
- while sys._getframe(level).f_globals is g:
- level += 1
- except ValueError:
- pass
- warnings.warn(stacklevel=level + 1, *args, **kw)
-
-
-class RequirementParseError(ValueError):
- def __str__(self):
- return ' '.join(self.args)
-
-
-def parse_requirements(strs):
- """Yield ``Requirement`` objects for each specification in `strs`
-
- `strs` must be a string, or a (possibly-nested) iterable thereof.
- """
- # create a steppable iterator, so we can handle \-continuations
- lines = iter(yield_lines(strs))
-
- for line in lines:
+ level = 1
+ g = globals()
+ try:
+ # find the first stack frame that is *not* code in
+ # the pkg_resources module, to use for the warning
+ while sys._getframe(level).f_globals is g:
+ level += 1
+ except ValueError:
+ pass
+ warnings.warn(stacklevel=level + 1, *args, **kw)
+
+
+class RequirementParseError(ValueError):
+ def __str__(self):
+ return ' '.join(self.args)
+
+
+def parse_requirements(strs):
+ """Yield ``Requirement`` objects for each specification in `strs`
+
+ `strs` must be a string, or a (possibly-nested) iterable thereof.
+ """
+ # create a steppable iterator, so we can handle \-continuations
+ lines = iter(yield_lines(strs))
+
+ for line in lines:
# Drop comments -- a hash without a space may be in a URL.
if ' #' in line:
line = line[:line.find(' #')]
@@ -3092,63 +3092,63 @@ def parse_requirements(strs):
except StopIteration:
return
yield Requirement(line)
-
-
+
+
class Requirement(packaging.requirements.Requirement):
def __init__(self, requirement_string):
- """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
+ """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
try:
super(Requirement, self).__init__(requirement_string)
except packaging.requirements.InvalidRequirement as e:
raise RequirementParseError(str(e))
self.unsafe_name = self.name
project_name = safe_name(self.name)
- self.project_name, self.key = project_name, project_name.lower()
+ self.project_name, self.key = project_name, project_name.lower()
self.specs = [
(spec.operator, spec.version) for spec in self.specifier]
self.extras = tuple(map(safe_extra, self.extras))
- self.hashCmp = (
- self.key,
+ self.hashCmp = (
+ self.key,
self.url,
- self.specifier,
- frozenset(self.extras),
+ self.specifier,
+ frozenset(self.extras),
str(self.marker) if self.marker else None,
- )
- self.__hash = hash(self.hashCmp)
-
- def __eq__(self, other):
- return (
- isinstance(other, Requirement) and
- self.hashCmp == other.hashCmp
- )
-
- def __ne__(self, other):
- return not self == other
-
- def __contains__(self, item):
- if isinstance(item, Distribution):
- if item.key != self.key:
- return False
-
- item = item.version
-
- # Allow prereleases always in order to match the previous behavior of
- # this method. In the future this should be smarter and follow PEP 440
- # more accurately.
- return self.specifier.contains(item, prereleases=True)
-
- def __hash__(self):
- return self.__hash
-
+ )
+ self.__hash = hash(self.hashCmp)
+
+ def __eq__(self, other):
+ return (
+ isinstance(other, Requirement) and
+ self.hashCmp == other.hashCmp
+ )
+
+ def __ne__(self, other):
+ return not self == other
+
+ def __contains__(self, item):
+ if isinstance(item, Distribution):
+ if item.key != self.key:
+ return False
+
+ item = item.version
+
+ # Allow prereleases always in order to match the previous behavior of
+ # this method. In the future this should be smarter and follow PEP 440
+ # more accurately.
+ return self.specifier.contains(item, prereleases=True)
+
+ def __hash__(self):
+ return self.__hash
+
def __repr__(self):
return "Requirement.parse(%r)" % str(self)
-
- @staticmethod
- def parse(s):
- req, = parse_requirements(s)
- return req
-
-
+
+ @staticmethod
+ def parse(s):
+ req, = parse_requirements(s)
+ return req
+
+
def _always_object(classes):
"""
Ensure object appears in the mro even
@@ -3159,70 +3159,70 @@ def _always_object(classes):
return classes
-def _find_adapter(registry, ob):
- """Return an adapter factory for `ob` from `registry`"""
+def _find_adapter(registry, ob):
+ """Return an adapter factory for `ob` from `registry`"""
types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
for t in types:
- if t in registry:
- return registry[t]
-
-
-def ensure_directory(path):
- """Ensure that the parent directory of `path` exists"""
- dirname = os.path.dirname(path)
+ if t in registry:
+ return registry[t]
+
+
+def ensure_directory(path):
+ """Ensure that the parent directory of `path` exists"""
+ dirname = os.path.dirname(path)
py31compat.makedirs(dirname, exist_ok=True)
-
-
-def _bypass_ensure_directory(path):
- """Sandbox-bypassing version of ensure_directory()"""
- if not WRITE_SUPPORT:
- raise IOError('"os.mkdir" not supported on this platform.')
- dirname, filename = split(path)
- if dirname and filename and not isdir(dirname):
- _bypass_ensure_directory(dirname)
+
+
+def _bypass_ensure_directory(path):
+ """Sandbox-bypassing version of ensure_directory()"""
+ if not WRITE_SUPPORT:
+ raise IOError('"os.mkdir" not supported on this platform.')
+ dirname, filename = split(path)
+ if dirname and filename and not isdir(dirname):
+ _bypass_ensure_directory(dirname)
try:
mkdir(dirname, 0o755)
except FileExistsError:
pass
-
-
-def split_sections(s):
- """Split a string or iterable thereof into (section, content) pairs
-
- Each ``section`` is a stripped version of the section header ("[section]")
- and each ``content`` is a list of stripped lines excluding blank lines and
- comment-only lines. If there are any such lines before the first section
- header, they're returned in a first ``section`` of ``None``.
- """
- section = None
- content = []
- for line in yield_lines(s):
- if line.startswith("["):
- if line.endswith("]"):
- if section or content:
- yield section, content
- section = line[1:-1].strip()
- content = []
- else:
- raise ValueError("Invalid section heading", line)
- else:
- content.append(line)
-
- # wrap up last segment
- yield section, content
-
+
+
+def split_sections(s):
+ """Split a string or iterable thereof into (section, content) pairs
+
+ Each ``section`` is a stripped version of the section header ("[section]")
+ and each ``content`` is a list of stripped lines excluding blank lines and
+ comment-only lines. If there are any such lines before the first section
+ header, they're returned in a first ``section`` of ``None``.
+ """
+ section = None
+ content = []
+ for line in yield_lines(s):
+ if line.startswith("["):
+ if line.endswith("]"):
+ if section or content:
+ yield section, content
+ section = line[1:-1].strip()
+ content = []
+ else:
+ raise ValueError("Invalid section heading", line)
+ else:
+ content.append(line)
+
+ # wrap up last segment
+ yield section, content
+
def _mkstemp(*args, **kw):
- old_open = os.open
- try:
- # temporarily bypass sandboxing
- os.open = os_open
+ old_open = os.open
+ try:
+ # temporarily bypass sandboxing
+ os.open = os_open
return tempfile.mkstemp(*args, **kw)
- finally:
- # and then put it back
- os.open = old_open
-
-
+ finally:
+ # and then put it back
+ os.open = old_open
+
+
# Yandex resource support
from __res import Y_PYTHON_SOURCE_ROOT, ResourceImporter, executable
from library.python import resource
@@ -3311,53 +3311,53 @@ register_finder(ResourceImporter, find_in_res)
register_loader_type(ResourceImporter, ResProvider.from_module)
-# Silence the PEP440Warning by default, so that end users don't get hit by it
-# randomly just because they use pkg_resources. We want to append the rule
-# because we want earlier uses of filterwarnings to take precedence over this
-# one.
-warnings.filterwarnings("ignore", category=PEP440Warning, append=True)
-
-
-# from jaraco.functools 1.3
-def _call_aside(f, *args, **kwargs):
- f(*args, **kwargs)
- return f
-
-
-@_call_aside
-def _initialize(g=globals()):
- "Set up global resource manager (deliberately not state-saved)"
- manager = ResourceManager()
- g['_manager'] = manager
+# Silence the PEP440Warning by default, so that end users don't get hit by it
+# randomly just because they use pkg_resources. We want to append the rule
+# because we want earlier uses of filterwarnings to take precedence over this
+# one.
+warnings.filterwarnings("ignore", category=PEP440Warning, append=True)
+
+
+# from jaraco.functools 1.3
+def _call_aside(f, *args, **kwargs):
+ f(*args, **kwargs)
+ return f
+
+
+@_call_aside
+def _initialize(g=globals()):
+ "Set up global resource manager (deliberately not state-saved)"
+ manager = ResourceManager()
+ g['_manager'] = manager
g.update(
(name, getattr(manager, name))
for name in dir(manager)
if not name.startswith('_')
)
-
-
-@_call_aside
-def _initialize_master_working_set():
- """
- Prepare the master working set and make the ``require()``
- API available.
-
- This function has explicit effects on the global state
- of pkg_resources. It is intended to be invoked once at
- the initialization of this module.
-
- Invocation by other packages is unsupported and done
- at their own risk.
- """
- working_set = WorkingSet._build_master()
- _declare_state('object', working_set=working_set)
-
- require = working_set.require
- iter_entry_points = working_set.iter_entry_points
- add_activation_listener = working_set.subscribe
- run_script = working_set.run_script
- # backward compatibility
- run_main = run_script
+
+
+@_call_aside
+def _initialize_master_working_set():
+ """
+ Prepare the master working set and make the ``require()``
+ API available.
+
+ This function has explicit effects on the global state
+ of pkg_resources. It is intended to be invoked once at
+ the initialization of this module.
+
+ Invocation by other packages is unsupported and done
+ at their own risk.
+ """
+ working_set = WorkingSet._build_master()
+ _declare_state('object', working_set=working_set)
+
+ require = working_set.require
+ iter_entry_points = working_set.iter_entry_points
+ add_activation_listener = working_set.subscribe
+ run_script = working_set.run_script
+ # backward compatibility
+ run_main = run_script
# Activate all distributions already on sys.path with replace=False and
# ensure that all distributions added to the working set in the future
# (e.g. by calling ``require()``) will get activated as well,
@@ -3371,9 +3371,9 @@ def _initialize_master_working_set():
existing=False,
)
working_set.entries = []
- # match order
- list(map(working_set.add_entry, sys.path))
- globals().update(locals())
+ # match order
+ list(map(working_set.add_entry, sys.path))
+ globals().update(locals())
class PkgResourcesDeprecationWarning(Warning):
"""
diff --git a/contrib/python/setuptools/py2/setuptools/__init__.py b/contrib/python/setuptools/py2/setuptools/__init__.py
index baa1ea0883..9d8ae1ed5f 100644
--- a/contrib/python/setuptools/py2/setuptools/__init__.py
+++ b/contrib/python/setuptools/py2/setuptools/__init__.py
@@ -1,93 +1,93 @@
-"""Extensions to the 'distutils' for large or complex distributions"""
-
-import os
+"""Extensions to the 'distutils' for large or complex distributions"""
+
+import os
import sys
-import functools
-import distutils.core
-import distutils.filelist
+import functools
+import distutils.core
+import distutils.filelist
import re
from distutils.errors import DistutilsOptionError
-from distutils.util import convert_path
-from fnmatch import fnmatchcase
-
+from distutils.util import convert_path
+from fnmatch import fnmatchcase
+
from ._deprecation_warning import SetuptoolsDeprecationWarning
-
+
from setuptools.extern.six import PY3, string_types
from setuptools.extern.six.moves import filter, map
-import setuptools.version
-from setuptools.extension import Extension
+import setuptools.version
+from setuptools.extension import Extension
from setuptools.dist import Distribution, Feature
-from setuptools.depends import Require
+from setuptools.depends import Require
from . import monkey
-
+
__metaclass__ = type
-__all__ = [
- 'setup', 'Distribution', 'Feature', 'Command', 'Extension', 'Require',
+__all__ = [
+ 'setup', 'Distribution', 'Feature', 'Command', 'Extension', 'Require',
'SetuptoolsDeprecationWarning',
'find_packages'
-]
-
+]
+
if PY3:
__all__.append('find_namespace_packages')
-__version__ = setuptools.version.__version__
-
-bootstrap_install_from = None
-
-# If we run 2to3 on .py files, should we also convert docstrings?
-# Default: yes; assume that we can detect doctests reliably
-run_2to3_on_doctests = True
-# Standard package names for fixer packages
-lib2to3_fixer_packages = ['lib2to3.fixes']
-
-
+__version__ = setuptools.version.__version__
+
+bootstrap_install_from = None
+
+# If we run 2to3 on .py files, should we also convert docstrings?
+# Default: yes; assume that we can detect doctests reliably
+run_2to3_on_doctests = True
+# Standard package names for fixer packages
+lib2to3_fixer_packages = ['lib2to3.fixes']
+
+
class PackageFinder:
"""
Generate a list of all Python packages found within a directory
"""
- @classmethod
- def find(cls, where='.', exclude=(), include=('*',)):
- """Return a list all Python packages found within directory 'where'
-
+ @classmethod
+ def find(cls, where='.', exclude=(), include=('*',)):
+ """Return a list all Python packages found within directory 'where'
+
'where' is the root directory which will be searched for packages. It
should be supplied as a "cross-platform" (i.e. URL-style) path; it will
be converted to the appropriate local path syntax.
- 'exclude' is a sequence of package names to exclude; '*' can be used
- as a wildcard in the names, such that 'foo.*' will exclude all
- subpackages of 'foo' (but not 'foo' itself).
-
- 'include' is a sequence of package names to include. If it's
- specified, only the named packages will be included. If it's not
- specified, all found packages will be included. 'include' can contain
- shell style wildcard patterns just like 'exclude'.
- """
-
+ 'exclude' is a sequence of package names to exclude; '*' can be used
+ as a wildcard in the names, such that 'foo.*' will exclude all
+ subpackages of 'foo' (but not 'foo' itself).
+
+ 'include' is a sequence of package names to include. If it's
+ specified, only the named packages will be included. If it's not
+ specified, all found packages will be included. 'include' can contain
+ shell style wildcard patterns just like 'exclude'.
+ """
+
return list(cls._find_packages_iter(
convert_path(where),
cls._build_filter('ez_setup', '*__pycache__', *exclude),
cls._build_filter(*include)))
-
+
@classmethod
def _find_packages_iter(cls, where, exclude, include):
- """
+ """
All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter.
- """
+ """
for root, dirs, files in os.walk(where, followlinks=True):
# Copy dirs to iterate over it, then empty dirs.
all_dirs = dirs[:]
dirs[:] = []
-
+
for dir in all_dirs:
full_path = os.path.join(root, dir)
rel_path = os.path.relpath(full_path, where)
package = rel_path.replace(os.path.sep, '.')
-
+
# Skip directory trees that are not valid packages
if ('.' in dir or not cls._looks_like_package(full_path)):
continue
@@ -100,31 +100,31 @@ class PackageFinder:
# down there, even if the parent was excluded.
dirs.append(dir)
- @staticmethod
- def _looks_like_package(path):
+ @staticmethod
+ def _looks_like_package(path):
"""Does a directory look like a package?"""
- return os.path.isfile(os.path.join(path, '__init__.py'))
-
- @staticmethod
- def _build_filter(*patterns):
- """
- Given a list of patterns, return a callable that will be true only if
+ return os.path.isfile(os.path.join(path, '__init__.py'))
+
+ @staticmethod
+ def _build_filter(*patterns):
+ """
+ Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
- """
- return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
-
-
-class PEP420PackageFinder(PackageFinder):
- @staticmethod
- def _looks_like_package(path):
- return True
-
-
-find_packages = PackageFinder.find
-
+ """
+ return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
+
+
+class PEP420PackageFinder(PackageFinder):
+ @staticmethod
+ def _looks_like_package(path):
+ return True
+
+
+find_packages = PackageFinder.find
+
if PY3:
find_namespace_packages = PEP420PackageFinder.find
-
+
def _install_setup_requires(attrs):
# Note: do not use `setuptools.Distribution` directly, as
@@ -165,21 +165,21 @@ setup.__doc__ = distutils.core.setup.__doc__
_Command = monkey.get_unpatched(distutils.core.Command)
-
-
-class Command(_Command):
- __doc__ = _Command.__doc__
-
- command_consumes_arguments = False
-
- def __init__(self, dist, **kw):
- """
- Construct the command for dist, updating
- vars(self) with any keyword parameters.
- """
- _Command.__init__(self, dist)
- vars(self).update(kw)
-
+
+
+class Command(_Command):
+ __doc__ = _Command.__doc__
+
+ command_consumes_arguments = False
+
+ def __init__(self, dist, **kw):
+ """
+ Construct the command for dist, updating
+ vars(self) with any keyword parameters.
+ """
+ _Command.__init__(self, dist)
+ vars(self).update(kw)
+
def _ensure_stringlike(self, option, what, default=None):
val = getattr(self, option)
if val is None:
@@ -211,35 +211,35 @@ class Command(_Command):
"'%s' must be a list of strings (got %r)"
% (option, val))
- def reinitialize_command(self, command, reinit_subcommands=0, **kw):
- cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
- vars(cmd).update(kw)
- return cmd
-
-
-def _find_all_simple(path):
- """
- Find all files under 'path'
- """
- results = (
- os.path.join(base, file)
- for base, dirs, files in os.walk(path, followlinks=True)
- for file in files
- )
- return filter(os.path.isfile, results)
-
-
-def findall(dir=os.curdir):
- """
- Find all files under 'dir' and return the list of full filenames.
- Unless dir is '.', return full filenames with dir prepended.
- """
- files = _find_all_simple(dir)
- if dir == os.curdir:
- make_rel = functools.partial(os.path.relpath, start=dir)
- files = map(make_rel, files)
- return list(files)
-
-
+ def reinitialize_command(self, command, reinit_subcommands=0, **kw):
+ cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
+ vars(cmd).update(kw)
+ return cmd
+
+
+def _find_all_simple(path):
+ """
+ Find all files under 'path'
+ """
+ results = (
+ os.path.join(base, file)
+ for base, dirs, files in os.walk(path, followlinks=True)
+ for file in files
+ )
+ return filter(os.path.isfile, results)
+
+
+def findall(dir=os.curdir):
+ """
+ Find all files under 'dir' and return the list of full filenames.
+ Unless dir is '.', return full filenames with dir prepended.
+ """
+ files = _find_all_simple(dir)
+ if dir == os.curdir:
+ make_rel = functools.partial(os.path.relpath, start=dir)
+ files = map(make_rel, files)
+ return list(files)
+
+
# Apply monkey patches
monkey.patch_all()
diff --git a/contrib/python/setuptools/py2/setuptools/archive_util.py b/contrib/python/setuptools/py2/setuptools/archive_util.py
index 82bb09a37b..81436044d9 100644
--- a/contrib/python/setuptools/py2/setuptools/archive_util.py
+++ b/contrib/python/setuptools/py2/setuptools/archive_util.py
@@ -1,13 +1,13 @@
-"""Utilities for extracting common archive formats"""
-
-import zipfile
-import tarfile
-import os
-import shutil
-import posixpath
-import contextlib
-from distutils.errors import DistutilsError
-
+"""Utilities for extracting common archive formats"""
+
+import zipfile
+import tarfile
+import os
+import shutil
+import posixpath
+import contextlib
+from distutils.errors import DistutilsError
+
from pkg_resources import ensure_directory
__all__ = [
@@ -16,158 +16,158 @@ __all__ = [
]
-class UnrecognizedFormat(DistutilsError):
- """Couldn't recognize the archive type"""
-
+class UnrecognizedFormat(DistutilsError):
+ """Couldn't recognize the archive type"""
+
def default_filter(src, dst):
- """The default progress/filter callback; returns True for all files"""
- return dst
-
-
-def unpack_archive(filename, extract_dir, progress_filter=default_filter,
- drivers=None):
- """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
-
- `progress_filter` is a function taking two arguments: a source path
- internal to the archive ('/'-separated), and a filesystem path where it
- will be extracted. The callback must return the desired extract path
- (which may be the same as the one passed in), or else ``None`` to skip
- that file or directory. The callback can thus be used to report on the
- progress of the extraction, as well as to filter the items extracted or
- alter their extraction paths.
-
- `drivers`, if supplied, must be a non-empty sequence of functions with the
- same signature as this function (minus the `drivers` argument), that raise
- ``UnrecognizedFormat`` if they do not support extracting the designated
- archive type. The `drivers` are tried in sequence until one is found that
- does not raise an error, or until all are exhausted (in which case
- ``UnrecognizedFormat`` is raised). If you do not supply a sequence of
- drivers, the module's ``extraction_drivers`` constant will be used, which
- means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that
- order.
- """
- for driver in drivers or extraction_drivers:
- try:
- driver(filename, extract_dir, progress_filter)
- except UnrecognizedFormat:
- continue
- else:
- return
- else:
- raise UnrecognizedFormat(
- "Not a recognized archive type: %s" % filename
- )
-
-
-def unpack_directory(filename, extract_dir, progress_filter=default_filter):
- """"Unpack" a directory, using the same interface as for archives
-
- Raises ``UnrecognizedFormat`` if `filename` is not a directory
- """
- if not os.path.isdir(filename):
- raise UnrecognizedFormat("%s is not a directory" % filename)
-
- paths = {
- filename: ('', extract_dir),
- }
- for base, dirs, files in os.walk(filename):
- src, dst = paths[base]
- for d in dirs:
- paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d)
- for f in files:
- target = os.path.join(dst, f)
- target = progress_filter(src + f, target)
- if not target:
- # skip non-files
- continue
- ensure_directory(target)
- f = os.path.join(base, f)
- shutil.copyfile(f, target)
- shutil.copystat(f, target)
-
-
-def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
- """Unpack zip `filename` to `extract_dir`
-
- Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
- by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation
- of the `progress_filter` argument.
- """
-
- if not zipfile.is_zipfile(filename):
- raise UnrecognizedFormat("%s is not a zip file" % (filename,))
-
+ """The default progress/filter callback; returns True for all files"""
+ return dst
+
+
+def unpack_archive(filename, extract_dir, progress_filter=default_filter,
+ drivers=None):
+ """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
+
+ `progress_filter` is a function taking two arguments: a source path
+ internal to the archive ('/'-separated), and a filesystem path where it
+ will be extracted. The callback must return the desired extract path
+ (which may be the same as the one passed in), or else ``None`` to skip
+ that file or directory. The callback can thus be used to report on the
+ progress of the extraction, as well as to filter the items extracted or
+ alter their extraction paths.
+
+ `drivers`, if supplied, must be a non-empty sequence of functions with the
+ same signature as this function (minus the `drivers` argument), that raise
+ ``UnrecognizedFormat`` if they do not support extracting the designated
+ archive type. The `drivers` are tried in sequence until one is found that
+ does not raise an error, or until all are exhausted (in which case
+ ``UnrecognizedFormat`` is raised). If you do not supply a sequence of
+ drivers, the module's ``extraction_drivers`` constant will be used, which
+ means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that
+ order.
+ """
+ for driver in drivers or extraction_drivers:
+ try:
+ driver(filename, extract_dir, progress_filter)
+ except UnrecognizedFormat:
+ continue
+ else:
+ return
+ else:
+ raise UnrecognizedFormat(
+ "Not a recognized archive type: %s" % filename
+ )
+
+
+def unpack_directory(filename, extract_dir, progress_filter=default_filter):
+ """"Unpack" a directory, using the same interface as for archives
+
+ Raises ``UnrecognizedFormat`` if `filename` is not a directory
+ """
+ if not os.path.isdir(filename):
+ raise UnrecognizedFormat("%s is not a directory" % filename)
+
+ paths = {
+ filename: ('', extract_dir),
+ }
+ for base, dirs, files in os.walk(filename):
+ src, dst = paths[base]
+ for d in dirs:
+ paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d)
+ for f in files:
+ target = os.path.join(dst, f)
+ target = progress_filter(src + f, target)
+ if not target:
+ # skip non-files
+ continue
+ ensure_directory(target)
+ f = os.path.join(base, f)
+ shutil.copyfile(f, target)
+ shutil.copystat(f, target)
+
+
+def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
+ """Unpack zip `filename` to `extract_dir`
+
+ Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
+ by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation
+ of the `progress_filter` argument.
+ """
+
+ if not zipfile.is_zipfile(filename):
+ raise UnrecognizedFormat("%s is not a zip file" % (filename,))
+
with zipfile.ZipFile(filename) as z:
- for info in z.infolist():
- name = info.filename
-
- # don't extract absolute paths or ones with .. in them
- if name.startswith('/') or '..' in name.split('/'):
- continue
-
- target = os.path.join(extract_dir, *name.split('/'))
- target = progress_filter(name, target)
- if not target:
- continue
- if name.endswith('/'):
- # directory
- ensure_directory(target)
- else:
- # file
- ensure_directory(target)
- data = z.read(info.filename)
- with open(target, 'wb') as f:
- f.write(data)
- unix_attributes = info.external_attr >> 16
- if unix_attributes:
- os.chmod(target, unix_attributes)
-
-
-def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
- """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
-
- Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
- by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
- of the `progress_filter` argument.
- """
- try:
- tarobj = tarfile.open(filename)
- except tarfile.TarError:
- raise UnrecognizedFormat(
- "%s is not a compressed or uncompressed tar file" % (filename,)
- )
- with contextlib.closing(tarobj):
- # don't do any chowning!
- tarobj.chown = lambda *args: None
- for member in tarobj:
- name = member.name
- # don't extract absolute paths or ones with .. in them
- if not name.startswith('/') and '..' not in name.split('/'):
- prelim_dst = os.path.join(extract_dir, *name.split('/'))
-
- # resolve any links and to extract the link targets as normal
- # files
- while member is not None and (member.islnk() or member.issym()):
- linkpath = member.linkname
- if member.issym():
- base = posixpath.dirname(member.name)
- linkpath = posixpath.join(base, linkpath)
- linkpath = posixpath.normpath(linkpath)
- member = tarobj._getmember(linkpath)
-
- if member is not None and (member.isfile() or member.isdir()):
- final_dst = progress_filter(name, prelim_dst)
- if final_dst:
- if final_dst.endswith(os.sep):
- final_dst = final_dst[:-1]
- try:
- # XXX Ugh
- tarobj._extract_member(member, final_dst)
- except tarfile.ExtractError:
- # chown/chmod/mkfifo/mknode/makedev failed
- pass
- return True
-
-
-extraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile
+ for info in z.infolist():
+ name = info.filename
+
+ # don't extract absolute paths or ones with .. in them
+ if name.startswith('/') or '..' in name.split('/'):
+ continue
+
+ target = os.path.join(extract_dir, *name.split('/'))
+ target = progress_filter(name, target)
+ if not target:
+ continue
+ if name.endswith('/'):
+ # directory
+ ensure_directory(target)
+ else:
+ # file
+ ensure_directory(target)
+ data = z.read(info.filename)
+ with open(target, 'wb') as f:
+ f.write(data)
+ unix_attributes = info.external_attr >> 16
+ if unix_attributes:
+ os.chmod(target, unix_attributes)
+
+
+def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
+ """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
+
+ Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
+ by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
+ of the `progress_filter` argument.
+ """
+ try:
+ tarobj = tarfile.open(filename)
+ except tarfile.TarError:
+ raise UnrecognizedFormat(
+ "%s is not a compressed or uncompressed tar file" % (filename,)
+ )
+ with contextlib.closing(tarobj):
+ # don't do any chowning!
+ tarobj.chown = lambda *args: None
+ for member in tarobj:
+ name = member.name
+ # don't extract absolute paths or ones with .. in them
+ if not name.startswith('/') and '..' not in name.split('/'):
+ prelim_dst = os.path.join(extract_dir, *name.split('/'))
+
+ # resolve any links and to extract the link targets as normal
+ # files
+ while member is not None and (member.islnk() or member.issym()):
+ linkpath = member.linkname
+ if member.issym():
+ base = posixpath.dirname(member.name)
+ linkpath = posixpath.join(base, linkpath)
+ linkpath = posixpath.normpath(linkpath)
+ member = tarobj._getmember(linkpath)
+
+ if member is not None and (member.isfile() or member.isdir()):
+ final_dst = progress_filter(name, prelim_dst)
+ if final_dst:
+ if final_dst.endswith(os.sep):
+ final_dst = final_dst[:-1]
+ try:
+ # XXX Ugh
+ tarobj._extract_member(member, final_dst)
+ except tarfile.ExtractError:
+ # chown/chmod/mkfifo/mknode/makedev failed
+ pass
+ return True
+
+
+extraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile
diff --git a/contrib/python/setuptools/py2/setuptools/command/__init__.py b/contrib/python/setuptools/py2/setuptools/command/__init__.py
index f335601c84..743f5588fa 100644
--- a/contrib/python/setuptools/py2/setuptools/command/__init__.py
+++ b/contrib/python/setuptools/py2/setuptools/command/__init__.py
@@ -1,17 +1,17 @@
-__all__ = [
- 'alias', 'bdist_egg', 'bdist_rpm', 'build_ext', 'build_py', 'develop',
- 'easy_install', 'egg_info', 'install', 'install_lib', 'rotate', 'saveopts',
- 'sdist', 'setopt', 'test', 'install_egg_info', 'install_scripts',
+__all__ = [
+ 'alias', 'bdist_egg', 'bdist_rpm', 'build_ext', 'build_py', 'develop',
+ 'easy_install', 'egg_info', 'install', 'install_lib', 'rotate', 'saveopts',
+ 'sdist', 'setopt', 'test', 'install_egg_info', 'install_scripts',
'bdist_wininst', 'upload_docs', 'build_clib', 'dist_info',
-]
-
-from distutils.command.bdist import bdist
-import sys
-
-from setuptools.command import install_scripts
-
-if 'egg' not in bdist.format_commands:
- bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
- bdist.format_commands.append('egg')
-
-del bdist, sys
+]
+
+from distutils.command.bdist import bdist
+import sys
+
+from setuptools.command import install_scripts
+
+if 'egg' not in bdist.format_commands:
+ bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
+ bdist.format_commands.append('egg')
+
+del bdist, sys
diff --git a/contrib/python/setuptools/py2/setuptools/command/alias.py b/contrib/python/setuptools/py2/setuptools/command/alias.py
index c057825904..4532b1cc0d 100644
--- a/contrib/python/setuptools/py2/setuptools/command/alias.py
+++ b/contrib/python/setuptools/py2/setuptools/command/alias.py
@@ -1,80 +1,80 @@
-from distutils.errors import DistutilsOptionError
-
+from distutils.errors import DistutilsOptionError
+
from setuptools.extern.six.moves import map
-
-from setuptools.command.setopt import edit_config, option_base, config_file
-
-
-def shquote(arg):
- """Quote an argument for later parsing by shlex.split()"""
- for c in '"', "'", "\\", "#":
- if c in arg:
- return repr(arg)
- if arg.split() != [arg]:
- return repr(arg)
- return arg
-
-
-class alias(option_base):
- """Define a shortcut that invokes one or more commands"""
-
- description = "define a shortcut to invoke one or more commands"
- command_consumes_arguments = True
-
- user_options = [
- ('remove', 'r', 'remove (unset) the alias'),
- ] + option_base.user_options
-
- boolean_options = option_base.boolean_options + ['remove']
-
- def initialize_options(self):
- option_base.initialize_options(self)
- self.args = None
- self.remove = None
-
- def finalize_options(self):
- option_base.finalize_options(self)
- if self.remove and len(self.args) != 1:
- raise DistutilsOptionError(
- "Must specify exactly one argument (the alias name) when "
- "using --remove"
- )
-
- def run(self):
- aliases = self.distribution.get_option_dict('aliases')
-
- if not self.args:
- print("Command Aliases")
- print("---------------")
- for alias in aliases:
- print("setup.py alias", format_alias(alias, aliases))
- return
-
- elif len(self.args) == 1:
- alias, = self.args
- if self.remove:
- command = None
- elif alias in aliases:
- print("setup.py alias", format_alias(alias, aliases))
- return
- else:
- print("No alias definition found for %r" % alias)
- return
- else:
- alias = self.args[0]
- command = ' '.join(map(shquote, self.args[1:]))
-
- edit_config(self.filename, {'aliases': {alias: command}}, self.dry_run)
-
-
-def format_alias(name, aliases):
- source, command = aliases[name]
- if source == config_file('global'):
- source = '--global-config '
- elif source == config_file('user'):
- source = '--user-config '
- elif source == config_file('local'):
- source = ''
- else:
- source = '--filename=%r' % source
- return source + name + ' ' + command
+
+from setuptools.command.setopt import edit_config, option_base, config_file
+
+
+def shquote(arg):
+ """Quote an argument for later parsing by shlex.split()"""
+ for c in '"', "'", "\\", "#":
+ if c in arg:
+ return repr(arg)
+ if arg.split() != [arg]:
+ return repr(arg)
+ return arg
+
+
+class alias(option_base):
+ """Define a shortcut that invokes one or more commands"""
+
+ description = "define a shortcut to invoke one or more commands"
+ command_consumes_arguments = True
+
+ user_options = [
+ ('remove', 'r', 'remove (unset) the alias'),
+ ] + option_base.user_options
+
+ boolean_options = option_base.boolean_options + ['remove']
+
+ def initialize_options(self):
+ option_base.initialize_options(self)
+ self.args = None
+ self.remove = None
+
+ def finalize_options(self):
+ option_base.finalize_options(self)
+ if self.remove and len(self.args) != 1:
+ raise DistutilsOptionError(
+ "Must specify exactly one argument (the alias name) when "
+ "using --remove"
+ )
+
+ def run(self):
+ aliases = self.distribution.get_option_dict('aliases')
+
+ if not self.args:
+ print("Command Aliases")
+ print("---------------")
+ for alias in aliases:
+ print("setup.py alias", format_alias(alias, aliases))
+ return
+
+ elif len(self.args) == 1:
+ alias, = self.args
+ if self.remove:
+ command = None
+ elif alias in aliases:
+ print("setup.py alias", format_alias(alias, aliases))
+ return
+ else:
+ print("No alias definition found for %r" % alias)
+ return
+ else:
+ alias = self.args[0]
+ command = ' '.join(map(shquote, self.args[1:]))
+
+ edit_config(self.filename, {'aliases': {alias: command}}, self.dry_run)
+
+
+def format_alias(name, aliases):
+ source, command = aliases[name]
+ if source == config_file('global'):
+ source = '--global-config '
+ elif source == config_file('user'):
+ source = '--user-config '
+ elif source == config_file('local'):
+ source = ''
+ else:
+ source = '--filename=%r' % source
+ return source + name + ' ' + command
diff --git a/contrib/python/setuptools/py2/setuptools/command/bdist_egg.py b/contrib/python/setuptools/py2/setuptools/command/bdist_egg.py
index 798c044589..98470f1715 100644
--- a/contrib/python/setuptools/py2/setuptools/command/bdist_egg.py
+++ b/contrib/python/setuptools/py2/setuptools/command/bdist_egg.py
@@ -1,45 +1,45 @@
-"""setuptools.command.bdist_egg
-
-Build .egg distributions"""
-
-from distutils.errors import DistutilsSetupError
-from distutils.dir_util import remove_tree, mkpath
-from distutils import log
-from types import CodeType
-import sys
-import os
+"""setuptools.command.bdist_egg
+
+Build .egg distributions"""
+
+from distutils.errors import DistutilsSetupError
+from distutils.dir_util import remove_tree, mkpath
+from distutils import log
+from types import CodeType
+import sys
+import os
import re
import textwrap
-import marshal
-
+import marshal
+
from setuptools.extern import six
-
-from pkg_resources import get_build_platform, Distribution, ensure_directory
-from pkg_resources import EntryPoint
-from setuptools.extension import Library
-from setuptools import Command
-
-try:
- # Python 2.7 or >=3.2
- from sysconfig import get_path, get_python_version
-
- def _get_purelib():
- return get_path("purelib")
-except ImportError:
- from distutils.sysconfig import get_python_lib, get_python_version
-
- def _get_purelib():
- return get_python_lib(False)
-
-
-def strip_module(filename):
- if '.' in filename:
- filename = os.path.splitext(filename)[0]
- if filename.endswith('module'):
- filename = filename[:-6]
- return filename
-
-
+
+from pkg_resources import get_build_platform, Distribution, ensure_directory
+from pkg_resources import EntryPoint
+from setuptools.extension import Library
+from setuptools import Command
+
+try:
+ # Python 2.7 or >=3.2
+ from sysconfig import get_path, get_python_version
+
+ def _get_purelib():
+ return get_path("purelib")
+except ImportError:
+ from distutils.sysconfig import get_python_lib, get_python_version
+
+ def _get_purelib():
+ return get_python_lib(False)
+
+
+def strip_module(filename):
+ if '.' in filename:
+ filename = os.path.splitext(filename)[0]
+ if filename.endswith('module'):
+ filename = filename[:-6]
+ return filename
+
+
def sorted_walk(dir):
"""Do os.walk in a reproducible way,
independent of indeterministic filesystem readdir order
@@ -50,205 +50,205 @@ def sorted_walk(dir):
yield base, dirs, files
-def write_stub(resource, pyfile):
- _stub_template = textwrap.dedent("""
- def __bootstrap__():
- global __bootstrap__, __loader__, __file__
- import sys, pkg_resources, imp
- __file__ = pkg_resources.resource_filename(__name__, %r)
- __loader__ = None; del __bootstrap__, __loader__
- imp.load_dynamic(__name__,__file__)
- __bootstrap__()
- """).lstrip()
- with open(pyfile, 'w') as f:
- f.write(_stub_template % resource)
-
-
-class bdist_egg(Command):
- description = "create an \"egg\" distribution"
-
- user_options = [
- ('bdist-dir=', 'b',
- "temporary directory for creating the distribution"),
- ('plat-name=', 'p', "platform name to embed in generated filenames "
- "(default: %s)" % get_build_platform()),
- ('exclude-source-files', None,
- "remove all .py files from the generated egg"),
- ('keep-temp', 'k',
- "keep the pseudo-installation tree around after " +
- "creating the distribution archive"),
- ('dist-dir=', 'd',
- "directory to put final built distributions in"),
- ('skip-build', None,
- "skip rebuilding everything (for testing/debugging)"),
- ]
-
- boolean_options = [
- 'keep-temp', 'skip-build', 'exclude-source-files'
- ]
-
- def initialize_options(self):
- self.bdist_dir = None
- self.plat_name = None
- self.keep_temp = 0
- self.dist_dir = None
- self.skip_build = 0
- self.egg_output = None
- self.exclude_source_files = None
-
- def finalize_options(self):
- ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
- self.egg_info = ei_cmd.egg_info
-
- if self.bdist_dir is None:
- bdist_base = self.get_finalized_command('bdist').bdist_base
- self.bdist_dir = os.path.join(bdist_base, 'egg')
-
- if self.plat_name is None:
- self.plat_name = get_build_platform()
-
- self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
-
- if self.egg_output is None:
-
- # Compute filename of the output egg
- basename = Distribution(
- None, None, ei_cmd.egg_name, ei_cmd.egg_version,
- get_python_version(),
- self.distribution.has_ext_modules() and self.plat_name
- ).egg_name()
-
- self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
-
- def do_install_data(self):
- # Hack for packages that install data to install's --install-lib
- self.get_finalized_command('install').install_lib = self.bdist_dir
-
- site_packages = os.path.normcase(os.path.realpath(_get_purelib()))
- old, self.distribution.data_files = self.distribution.data_files, []
-
- for item in old:
- if isinstance(item, tuple) and len(item) == 2:
- if os.path.isabs(item[0]):
- realpath = os.path.realpath(item[0])
- normalized = os.path.normcase(realpath)
- if normalized == site_packages or normalized.startswith(
- site_packages + os.sep
- ):
- item = realpath[len(site_packages) + 1:], item[1]
- # XXX else: raise ???
- self.distribution.data_files.append(item)
-
- try:
+def write_stub(resource, pyfile):
+ _stub_template = textwrap.dedent("""
+ def __bootstrap__():
+ global __bootstrap__, __loader__, __file__
+ import sys, pkg_resources, imp
+ __file__ = pkg_resources.resource_filename(__name__, %r)
+ __loader__ = None; del __bootstrap__, __loader__
+ imp.load_dynamic(__name__,__file__)
+ __bootstrap__()
+ """).lstrip()
+ with open(pyfile, 'w') as f:
+ f.write(_stub_template % resource)
+
+
+class bdist_egg(Command):
+ description = "create an \"egg\" distribution"
+
+ user_options = [
+ ('bdist-dir=', 'b',
+ "temporary directory for creating the distribution"),
+ ('plat-name=', 'p', "platform name to embed in generated filenames "
+ "(default: %s)" % get_build_platform()),
+ ('exclude-source-files', None,
+ "remove all .py files from the generated egg"),
+ ('keep-temp', 'k',
+ "keep the pseudo-installation tree around after " +
+ "creating the distribution archive"),
+ ('dist-dir=', 'd',
+ "directory to put final built distributions in"),
+ ('skip-build', None,
+ "skip rebuilding everything (for testing/debugging)"),
+ ]
+
+ boolean_options = [
+ 'keep-temp', 'skip-build', 'exclude-source-files'
+ ]
+
+ def initialize_options(self):
+ self.bdist_dir = None
+ self.plat_name = None
+ self.keep_temp = 0
+ self.dist_dir = None
+ self.skip_build = 0
+ self.egg_output = None
+ self.exclude_source_files = None
+
+ def finalize_options(self):
+ ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
+ self.egg_info = ei_cmd.egg_info
+
+ if self.bdist_dir is None:
+ bdist_base = self.get_finalized_command('bdist').bdist_base
+ self.bdist_dir = os.path.join(bdist_base, 'egg')
+
+ if self.plat_name is None:
+ self.plat_name = get_build_platform()
+
+ self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
+
+ if self.egg_output is None:
+
+ # Compute filename of the output egg
+ basename = Distribution(
+ None, None, ei_cmd.egg_name, ei_cmd.egg_version,
+ get_python_version(),
+ self.distribution.has_ext_modules() and self.plat_name
+ ).egg_name()
+
+ self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
+
+ def do_install_data(self):
+ # Hack for packages that install data to install's --install-lib
+ self.get_finalized_command('install').install_lib = self.bdist_dir
+
+ site_packages = os.path.normcase(os.path.realpath(_get_purelib()))
+ old, self.distribution.data_files = self.distribution.data_files, []
+
+ for item in old:
+ if isinstance(item, tuple) and len(item) == 2:
+ if os.path.isabs(item[0]):
+ realpath = os.path.realpath(item[0])
+ normalized = os.path.normcase(realpath)
+ if normalized == site_packages or normalized.startswith(
+ site_packages + os.sep
+ ):
+ item = realpath[len(site_packages) + 1:], item[1]
+ # XXX else: raise ???
+ self.distribution.data_files.append(item)
+
+ try:
log.info("installing package data to %s", self.bdist_dir)
- self.call_command('install_data', force=0, root=None)
- finally:
- self.distribution.data_files = old
-
- def get_outputs(self):
- return [self.egg_output]
-
- def call_command(self, cmdname, **kw):
- """Invoke reinitialized command `cmdname` with keyword args"""
- for dirname in INSTALL_DIRECTORY_ATTRS:
- kw.setdefault(dirname, self.bdist_dir)
- kw.setdefault('skip_build', self.skip_build)
- kw.setdefault('dry_run', self.dry_run)
- cmd = self.reinitialize_command(cmdname, **kw)
- self.run_command(cmdname)
- return cmd
-
- def run(self):
- # Generate metadata first
- self.run_command("egg_info")
- # We run install_lib before install_data, because some data hacks
- # pull their data path from the install_lib command.
+ self.call_command('install_data', force=0, root=None)
+ finally:
+ self.distribution.data_files = old
+
+ def get_outputs(self):
+ return [self.egg_output]
+
+ def call_command(self, cmdname, **kw):
+ """Invoke reinitialized command `cmdname` with keyword args"""
+ for dirname in INSTALL_DIRECTORY_ATTRS:
+ kw.setdefault(dirname, self.bdist_dir)
+ kw.setdefault('skip_build', self.skip_build)
+ kw.setdefault('dry_run', self.dry_run)
+ cmd = self.reinitialize_command(cmdname, **kw)
+ self.run_command(cmdname)
+ return cmd
+
+ def run(self):
+ # Generate metadata first
+ self.run_command("egg_info")
+ # We run install_lib before install_data, because some data hacks
+ # pull their data path from the install_lib command.
log.info("installing library code to %s", self.bdist_dir)
- instcmd = self.get_finalized_command('install')
- old_root = instcmd.root
- instcmd.root = None
- if self.distribution.has_c_libraries() and not self.skip_build:
- self.run_command('build_clib')
- cmd = self.call_command('install_lib', warn_dir=0)
- instcmd.root = old_root
-
- all_outputs, ext_outputs = self.get_ext_outputs()
- self.stubs = []
- to_compile = []
- for (p, ext_name) in enumerate(ext_outputs):
- filename, ext = os.path.splitext(ext_name)
- pyfile = os.path.join(self.bdist_dir, strip_module(filename) +
- '.py')
- self.stubs.append(pyfile)
+ instcmd = self.get_finalized_command('install')
+ old_root = instcmd.root
+ instcmd.root = None
+ if self.distribution.has_c_libraries() and not self.skip_build:
+ self.run_command('build_clib')
+ cmd = self.call_command('install_lib', warn_dir=0)
+ instcmd.root = old_root
+
+ all_outputs, ext_outputs = self.get_ext_outputs()
+ self.stubs = []
+ to_compile = []
+ for (p, ext_name) in enumerate(ext_outputs):
+ filename, ext = os.path.splitext(ext_name)
+ pyfile = os.path.join(self.bdist_dir, strip_module(filename) +
+ '.py')
+ self.stubs.append(pyfile)
log.info("creating stub loader for %s", ext_name)
- if not self.dry_run:
- write_stub(os.path.basename(ext_name), pyfile)
- to_compile.append(pyfile)
- ext_outputs[p] = ext_name.replace(os.sep, '/')
-
- if to_compile:
- cmd.byte_compile(to_compile)
- if self.distribution.data_files:
- self.do_install_data()
-
- # Make the EGG-INFO directory
- archive_root = self.bdist_dir
- egg_info = os.path.join(archive_root, 'EGG-INFO')
- self.mkpath(egg_info)
- if self.distribution.scripts:
- script_dir = os.path.join(egg_info, 'scripts')
+ if not self.dry_run:
+ write_stub(os.path.basename(ext_name), pyfile)
+ to_compile.append(pyfile)
+ ext_outputs[p] = ext_name.replace(os.sep, '/')
+
+ if to_compile:
+ cmd.byte_compile(to_compile)
+ if self.distribution.data_files:
+ self.do_install_data()
+
+ # Make the EGG-INFO directory
+ archive_root = self.bdist_dir
+ egg_info = os.path.join(archive_root, 'EGG-INFO')
+ self.mkpath(egg_info)
+ if self.distribution.scripts:
+ script_dir = os.path.join(egg_info, 'scripts')
log.info("installing scripts to %s", script_dir)
- self.call_command('install_scripts', install_dir=script_dir,
- no_ep=1)
-
- self.copy_metadata_to(egg_info)
- native_libs = os.path.join(egg_info, "native_libs.txt")
- if all_outputs:
+ self.call_command('install_scripts', install_dir=script_dir,
+ no_ep=1)
+
+ self.copy_metadata_to(egg_info)
+ native_libs = os.path.join(egg_info, "native_libs.txt")
+ if all_outputs:
log.info("writing %s", native_libs)
- if not self.dry_run:
- ensure_directory(native_libs)
- libs_file = open(native_libs, 'wt')
- libs_file.write('\n'.join(all_outputs))
- libs_file.write('\n')
- libs_file.close()
- elif os.path.isfile(native_libs):
+ if not self.dry_run:
+ ensure_directory(native_libs)
+ libs_file = open(native_libs, 'wt')
+ libs_file.write('\n'.join(all_outputs))
+ libs_file.write('\n')
+ libs_file.close()
+ elif os.path.isfile(native_libs):
log.info("removing %s", native_libs)
- if not self.dry_run:
- os.unlink(native_libs)
-
- write_safety_flag(
- os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()
- )
-
- if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):
- log.warn(
- "WARNING: 'depends.txt' will not be used by setuptools 0.6!\n"
- "Use the install_requires/extras_require setup() args instead."
- )
-
- if self.exclude_source_files:
- self.zap_pyfiles()
-
- # Make the archive
- make_zipfile(self.egg_output, archive_root, verbose=self.verbose,
- dry_run=self.dry_run, mode=self.gen_header())
- if not self.keep_temp:
- remove_tree(self.bdist_dir, dry_run=self.dry_run)
-
- # Add to 'Distribution.dist_files' so that the "upload" command works
- getattr(self.distribution, 'dist_files', []).append(
- ('bdist_egg', get_python_version(), self.egg_output))
-
- def zap_pyfiles(self):
- log.info("Removing .py files from temporary directory")
- for base, dirs, files in walk_egg(self.bdist_dir):
- for name in files:
+ if not self.dry_run:
+ os.unlink(native_libs)
+
+ write_safety_flag(
+ os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()
+ )
+
+ if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):
+ log.warn(
+ "WARNING: 'depends.txt' will not be used by setuptools 0.6!\n"
+ "Use the install_requires/extras_require setup() args instead."
+ )
+
+ if self.exclude_source_files:
+ self.zap_pyfiles()
+
+ # Make the archive
+ make_zipfile(self.egg_output, archive_root, verbose=self.verbose,
+ dry_run=self.dry_run, mode=self.gen_header())
+ if not self.keep_temp:
+ remove_tree(self.bdist_dir, dry_run=self.dry_run)
+
+ # Add to 'Distribution.dist_files' so that the "upload" command works
+ getattr(self.distribution, 'dist_files', []).append(
+ ('bdist_egg', get_python_version(), self.egg_output))
+
+ def zap_pyfiles(self):
+ log.info("Removing .py files from temporary directory")
+ for base, dirs, files in walk_egg(self.bdist_dir):
+ for name in files:
path = os.path.join(base, name)
- if name.endswith('.py'):
- log.debug("Deleting %s", path)
- os.unlink(path)
-
+ if name.endswith('.py'):
+ log.debug("Deleting %s", path)
+ os.unlink(path)
+
if base.endswith('__pycache__'):
path_old = path
@@ -265,238 +265,238 @@ class bdist_egg(Command):
pass
os.rename(path_old, path_new)
- def zip_safe(self):
- safe = getattr(self.distribution, 'zip_safe', None)
- if safe is not None:
- return safe
- log.warn("zip_safe flag not set; analyzing archive contents...")
- return analyze_egg(self.bdist_dir, self.stubs)
-
- def gen_header(self):
- epm = EntryPoint.parse_map(self.distribution.entry_points or '')
- ep = epm.get('setuptools.installation', {}).get('eggsecutable')
- if ep is None:
- return 'w' # not an eggsecutable, do it the usual way.
-
- if not ep.attrs or ep.extras:
- raise DistutilsSetupError(
- "eggsecutable entry point (%r) cannot have 'extras' "
- "or refer to a module" % (ep,)
- )
-
+ def zip_safe(self):
+ safe = getattr(self.distribution, 'zip_safe', None)
+ if safe is not None:
+ return safe
+ log.warn("zip_safe flag not set; analyzing archive contents...")
+ return analyze_egg(self.bdist_dir, self.stubs)
+
+ def gen_header(self):
+ epm = EntryPoint.parse_map(self.distribution.entry_points or '')
+ ep = epm.get('setuptools.installation', {}).get('eggsecutable')
+ if ep is None:
+ return 'w' # not an eggsecutable, do it the usual way.
+
+ if not ep.attrs or ep.extras:
+ raise DistutilsSetupError(
+ "eggsecutable entry point (%r) cannot have 'extras' "
+ "or refer to a module" % (ep,)
+ )
+
pyver = '{}.{}'.format(*sys.version_info)
- pkg = ep.module_name
- full = '.'.join(ep.attrs)
- base = ep.attrs[0]
- basename = os.path.basename(self.egg_output)
-
- header = (
- "#!/bin/sh\n"
- 'if [ `basename $0` = "%(basename)s" ]\n'
- 'then exec python%(pyver)s -c "'
- "import sys, os; sys.path.insert(0, os.path.abspath('$0')); "
- "from %(pkg)s import %(base)s; sys.exit(%(full)s())"
- '" "$@"\n'
- 'else\n'
- ' echo $0 is not the correct name for this egg file.\n'
- ' echo Please rename it back to %(basename)s and try again.\n'
- ' exec false\n'
- 'fi\n'
- ) % locals()
-
- if not self.dry_run:
- mkpath(os.path.dirname(self.egg_output), dry_run=self.dry_run)
- f = open(self.egg_output, 'w')
- f.write(header)
- f.close()
- return 'a'
-
- def copy_metadata_to(self, target_dir):
- "Copy metadata (egg info) to the target_dir"
- # normalize the path (so that a forward-slash in egg_info will
- # match using startswith below)
- norm_egg_info = os.path.normpath(self.egg_info)
- prefix = os.path.join(norm_egg_info, '')
- for path in self.ei_cmd.filelist.files:
- if path.startswith(prefix):
- target = os.path.join(target_dir, path[len(prefix):])
- ensure_directory(target)
- self.copy_file(path, target)
-
- def get_ext_outputs(self):
- """Get a list of relative paths to C extensions in the output distro"""
-
- all_outputs = []
- ext_outputs = []
-
- paths = {self.bdist_dir: ''}
+ pkg = ep.module_name
+ full = '.'.join(ep.attrs)
+ base = ep.attrs[0]
+ basename = os.path.basename(self.egg_output)
+
+ header = (
+ "#!/bin/sh\n"
+ 'if [ `basename $0` = "%(basename)s" ]\n'
+ 'then exec python%(pyver)s -c "'
+ "import sys, os; sys.path.insert(0, os.path.abspath('$0')); "
+ "from %(pkg)s import %(base)s; sys.exit(%(full)s())"
+ '" "$@"\n'
+ 'else\n'
+ ' echo $0 is not the correct name for this egg file.\n'
+ ' echo Please rename it back to %(basename)s and try again.\n'
+ ' exec false\n'
+ 'fi\n'
+ ) % locals()
+
+ if not self.dry_run:
+ mkpath(os.path.dirname(self.egg_output), dry_run=self.dry_run)
+ f = open(self.egg_output, 'w')
+ f.write(header)
+ f.close()
+ return 'a'
+
+ def copy_metadata_to(self, target_dir):
+ "Copy metadata (egg info) to the target_dir"
+ # normalize the path (so that a forward-slash in egg_info will
+ # match using startswith below)
+ norm_egg_info = os.path.normpath(self.egg_info)
+ prefix = os.path.join(norm_egg_info, '')
+ for path in self.ei_cmd.filelist.files:
+ if path.startswith(prefix):
+ target = os.path.join(target_dir, path[len(prefix):])
+ ensure_directory(target)
+ self.copy_file(path, target)
+
+ def get_ext_outputs(self):
+ """Get a list of relative paths to C extensions in the output distro"""
+
+ all_outputs = []
+ ext_outputs = []
+
+ paths = {self.bdist_dir: ''}
for base, dirs, files in sorted_walk(self.bdist_dir):
- for filename in files:
- if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS:
- all_outputs.append(paths[base] + filename)
- for filename in dirs:
- paths[os.path.join(base, filename)] = (paths[base] +
- filename + '/')
-
- if self.distribution.has_ext_modules():
- build_cmd = self.get_finalized_command('build_ext')
- for ext in build_cmd.extensions:
- if isinstance(ext, Library):
- continue
- fullname = build_cmd.get_ext_fullname(ext.name)
- filename = build_cmd.get_ext_filename(fullname)
- if not os.path.basename(filename).startswith('dl-'):
- if os.path.exists(os.path.join(self.bdist_dir, filename)):
- ext_outputs.append(filename)
-
- return all_outputs, ext_outputs
-
-
-NATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())
-
-
-def walk_egg(egg_dir):
- """Walk an unpacked egg's contents, skipping the metadata directory"""
+ for filename in files:
+ if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS:
+ all_outputs.append(paths[base] + filename)
+ for filename in dirs:
+ paths[os.path.join(base, filename)] = (paths[base] +
+ filename + '/')
+
+ if self.distribution.has_ext_modules():
+ build_cmd = self.get_finalized_command('build_ext')
+ for ext in build_cmd.extensions:
+ if isinstance(ext, Library):
+ continue
+ fullname = build_cmd.get_ext_fullname(ext.name)
+ filename = build_cmd.get_ext_filename(fullname)
+ if not os.path.basename(filename).startswith('dl-'):
+ if os.path.exists(os.path.join(self.bdist_dir, filename)):
+ ext_outputs.append(filename)
+
+ return all_outputs, ext_outputs
+
+
+NATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())
+
+
+def walk_egg(egg_dir):
+ """Walk an unpacked egg's contents, skipping the metadata directory"""
walker = sorted_walk(egg_dir)
- base, dirs, files = next(walker)
- if 'EGG-INFO' in dirs:
- dirs.remove('EGG-INFO')
- yield base, dirs, files
- for bdf in walker:
- yield bdf
-
-
-def analyze_egg(egg_dir, stubs):
- # check for existing flag in EGG-INFO
- for flag, fn in safety_flags.items():
- if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
- return flag
- if not can_scan():
- return False
- safe = True
- for base, dirs, files in walk_egg(egg_dir):
- for name in files:
- if name.endswith('.py') or name.endswith('.pyw'):
- continue
- elif name.endswith('.pyc') or name.endswith('.pyo'):
- # always scan, even if we already know we're not safe
- safe = scan_module(egg_dir, base, name, stubs) and safe
- return safe
-
-
-def write_safety_flag(egg_dir, safe):
- # Write or remove zip safety flag file(s)
- for flag, fn in safety_flags.items():
- fn = os.path.join(egg_dir, fn)
- if os.path.exists(fn):
- if safe is None or bool(safe) != flag:
- os.unlink(fn)
- elif safe is not None and bool(safe) == flag:
- f = open(fn, 'wt')
- f.write('\n')
- f.close()
-
-
-safety_flags = {
- True: 'zip-safe',
- False: 'not-zip-safe',
-}
-
-
-def scan_module(egg_dir, base, name, stubs):
- """Check whether module possibly uses unsafe-for-zipfile stuff"""
-
- filename = os.path.join(base, name)
- if filename[:-1] in stubs:
- return True # Extension module
- pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
- module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
+ base, dirs, files = next(walker)
+ if 'EGG-INFO' in dirs:
+ dirs.remove('EGG-INFO')
+ yield base, dirs, files
+ for bdf in walker:
+ yield bdf
+
+
+def analyze_egg(egg_dir, stubs):
+ # check for existing flag in EGG-INFO
+ for flag, fn in safety_flags.items():
+ if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
+ return flag
+ if not can_scan():
+ return False
+ safe = True
+ for base, dirs, files in walk_egg(egg_dir):
+ for name in files:
+ if name.endswith('.py') or name.endswith('.pyw'):
+ continue
+ elif name.endswith('.pyc') or name.endswith('.pyo'):
+ # always scan, even if we already know we're not safe
+ safe = scan_module(egg_dir, base, name, stubs) and safe
+ return safe
+
+
+def write_safety_flag(egg_dir, safe):
+ # Write or remove zip safety flag file(s)
+ for flag, fn in safety_flags.items():
+ fn = os.path.join(egg_dir, fn)
+ if os.path.exists(fn):
+ if safe is None or bool(safe) != flag:
+ os.unlink(fn)
+ elif safe is not None and bool(safe) == flag:
+ f = open(fn, 'wt')
+ f.write('\n')
+ f.close()
+
+
+safety_flags = {
+ True: 'zip-safe',
+ False: 'not-zip-safe',
+}
+
+
+def scan_module(egg_dir, base, name, stubs):
+ """Check whether module possibly uses unsafe-for-zipfile stuff"""
+
+ filename = os.path.join(base, name)
+ if filename[:-1] in stubs:
+ return True # Extension module
+ pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
+ module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
if six.PY2:
- skip = 8 # skip magic & date
+ skip = 8 # skip magic & date
elif sys.version_info < (3, 7):
skip = 12 # skip magic & date & file size
- else:
+ else:
skip = 16 # skip magic & reserved? & date & file size
- f = open(filename, 'rb')
- f.read(skip)
- code = marshal.load(f)
- f.close()
- safe = True
- symbols = dict.fromkeys(iter_symbols(code))
- for bad in ['__file__', '__path__']:
- if bad in symbols:
- log.warn("%s: module references %s", module, bad)
- safe = False
- if 'inspect' in symbols:
- for bad in [
- 'getsource', 'getabsfile', 'getsourcefile', 'getfile'
- 'getsourcelines', 'findsource', 'getcomments', 'getframeinfo',
- 'getinnerframes', 'getouterframes', 'stack', 'trace'
- ]:
- if bad in symbols:
- log.warn("%s: module MAY be using inspect.%s", module, bad)
- safe = False
- return safe
-
-
-def iter_symbols(code):
- """Yield names and strings used by `code` and its nested code objects"""
- for name in code.co_names:
- yield name
- for const in code.co_consts:
- if isinstance(const, six.string_types):
- yield const
- elif isinstance(const, CodeType):
- for name in iter_symbols(const):
- yield name
-
-
-def can_scan():
- if not sys.platform.startswith('java') and sys.platform != 'cli':
- # CPython, PyPy, etc.
- return True
- log.warn("Unable to analyze compiled code on this platform.")
- log.warn("Please ask the author to include a 'zip_safe'"
- " setting (either True or False) in the package's setup.py")
-
-
-# Attribute names of options for commands that might need to be convinced to
-# install to the egg build directory
-
-INSTALL_DIRECTORY_ATTRS = [
- 'install_lib', 'install_dir', 'install_data', 'install_base'
-]
-
-
-def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
- mode='w'):
- """Create a zip file from all the files under 'base_dir'. The output
- zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
- Python module (if available) or the InfoZIP "zip" utility (if installed
- and found on the default search path). If neither tool is available,
- raises DistutilsExecError. Returns the name of the output zip file.
- """
- import zipfile
-
- mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
- log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
-
- def visit(z, dirname, names):
- for name in names:
- path = os.path.normpath(os.path.join(dirname, name))
- if os.path.isfile(path):
- p = path[len(base_dir) + 1:]
- if not dry_run:
- z.write(path, p)
+ f = open(filename, 'rb')
+ f.read(skip)
+ code = marshal.load(f)
+ f.close()
+ safe = True
+ symbols = dict.fromkeys(iter_symbols(code))
+ for bad in ['__file__', '__path__']:
+ if bad in symbols:
+ log.warn("%s: module references %s", module, bad)
+ safe = False
+ if 'inspect' in symbols:
+ for bad in [
+ 'getsource', 'getabsfile', 'getsourcefile', 'getfile'
+ 'getsourcelines', 'findsource', 'getcomments', 'getframeinfo',
+ 'getinnerframes', 'getouterframes', 'stack', 'trace'
+ ]:
+ if bad in symbols:
+ log.warn("%s: module MAY be using inspect.%s", module, bad)
+ safe = False
+ return safe
+
+
+def iter_symbols(code):
+ """Yield names and strings used by `code` and its nested code objects"""
+ for name in code.co_names:
+ yield name
+ for const in code.co_consts:
+ if isinstance(const, six.string_types):
+ yield const
+ elif isinstance(const, CodeType):
+ for name in iter_symbols(const):
+ yield name
+
+
+def can_scan():
+ if not sys.platform.startswith('java') and sys.platform != 'cli':
+ # CPython, PyPy, etc.
+ return True
+ log.warn("Unable to analyze compiled code on this platform.")
+ log.warn("Please ask the author to include a 'zip_safe'"
+ " setting (either True or False) in the package's setup.py")
+
+
+# Attribute names of options for commands that might need to be convinced to
+# install to the egg build directory
+
+INSTALL_DIRECTORY_ATTRS = [
+ 'install_lib', 'install_dir', 'install_data', 'install_base'
+]
+
+
+def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
+ mode='w'):
+ """Create a zip file from all the files under 'base_dir'. The output
+ zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
+ Python module (if available) or the InfoZIP "zip" utility (if installed
+ and found on the default search path). If neither tool is available,
+ raises DistutilsExecError. Returns the name of the output zip file.
+ """
+ import zipfile
+
+ mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
+ log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
+
+ def visit(z, dirname, names):
+ for name in names:
+ path = os.path.normpath(os.path.join(dirname, name))
+ if os.path.isfile(path):
+ p = path[len(base_dir) + 1:]
+ if not dry_run:
+ z.write(path, p)
log.debug("adding '%s'", p)
-
- compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED
- if not dry_run:
- z = zipfile.ZipFile(zip_filename, mode, compression=compression)
+
+ compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED
+ if not dry_run:
+ z = zipfile.ZipFile(zip_filename, mode, compression=compression)
for dirname, dirs, files in sorted_walk(base_dir):
- visit(z, dirname, files)
- z.close()
- else:
+ visit(z, dirname, files)
+ z.close()
+ else:
for dirname, dirs, files in sorted_walk(base_dir):
- visit(None, dirname, files)
- return zip_filename
+ visit(None, dirname, files)
+ return zip_filename
diff --git a/contrib/python/setuptools/py2/setuptools/command/bdist_rpm.py b/contrib/python/setuptools/py2/setuptools/command/bdist_rpm.py
index 5f1a15e2d9..70730927ec 100644
--- a/contrib/python/setuptools/py2/setuptools/command/bdist_rpm.py
+++ b/contrib/python/setuptools/py2/setuptools/command/bdist_rpm.py
@@ -1,43 +1,43 @@
-import distutils.command.bdist_rpm as orig
-
-
-class bdist_rpm(orig.bdist_rpm):
- """
- Override the default bdist_rpm behavior to do the following:
-
- 1. Run egg_info to ensure the name and version are properly calculated.
- 2. Always run 'install' using --single-version-externally-managed to
- disable eggs in RPM distributions.
- 3. Replace dash with underscore in the version numbers for better RPM
- compatibility.
- """
-
- def run(self):
- # ensure distro name is up-to-date
- self.run_command('egg_info')
-
- orig.bdist_rpm.run(self)
-
- def _make_spec_file(self):
- version = self.distribution.get_version()
- rpmversion = version.replace('-', '_')
- spec = orig.bdist_rpm._make_spec_file(self)
- line23 = '%define version ' + version
- line24 = '%define version ' + rpmversion
- spec = [
- line.replace(
- "Source0: %{name}-%{version}.tar",
- "Source0: %{name}-%{unmangled_version}.tar"
- ).replace(
- "setup.py install ",
- "setup.py install --single-version-externally-managed "
- ).replace(
- "%setup",
- "%setup -n %{name}-%{unmangled_version}"
- ).replace(line23, line24)
- for line in spec
- ]
- insert_loc = spec.index(line24) + 1
- unmangled_version = "%define unmangled_version " + version
- spec.insert(insert_loc, unmangled_version)
- return spec
+import distutils.command.bdist_rpm as orig
+
+
+class bdist_rpm(orig.bdist_rpm):
+ """
+ Override the default bdist_rpm behavior to do the following:
+
+ 1. Run egg_info to ensure the name and version are properly calculated.
+ 2. Always run 'install' using --single-version-externally-managed to
+ disable eggs in RPM distributions.
+ 3. Replace dash with underscore in the version numbers for better RPM
+ compatibility.
+ """
+
+ def run(self):
+ # ensure distro name is up-to-date
+ self.run_command('egg_info')
+
+ orig.bdist_rpm.run(self)
+
+ def _make_spec_file(self):
+ version = self.distribution.get_version()
+ rpmversion = version.replace('-', '_')
+ spec = orig.bdist_rpm._make_spec_file(self)
+ line23 = '%define version ' + version
+ line24 = '%define version ' + rpmversion
+ spec = [
+ line.replace(
+ "Source0: %{name}-%{version}.tar",
+ "Source0: %{name}-%{unmangled_version}.tar"
+ ).replace(
+ "setup.py install ",
+ "setup.py install --single-version-externally-managed "
+ ).replace(
+ "%setup",
+ "%setup -n %{name}-%{unmangled_version}"
+ ).replace(line23, line24)
+ for line in spec
+ ]
+ insert_loc = spec.index(line24) + 1
+ unmangled_version = "%define unmangled_version " + version
+ spec.insert(insert_loc, unmangled_version)
+ return spec
diff --git a/contrib/python/setuptools/py2/setuptools/command/bdist_wininst.py b/contrib/python/setuptools/py2/setuptools/command/bdist_wininst.py
index 9ca62d60c3..073de97b46 100644
--- a/contrib/python/setuptools/py2/setuptools/command/bdist_wininst.py
+++ b/contrib/python/setuptools/py2/setuptools/command/bdist_wininst.py
@@ -1,21 +1,21 @@
-import distutils.command.bdist_wininst as orig
-
-
-class bdist_wininst(orig.bdist_wininst):
- def reinitialize_command(self, command, reinit_subcommands=0):
- """
- Supplement reinitialize_command to work around
- http://bugs.python.org/issue20819
- """
- cmd = self.distribution.reinitialize_command(
- command, reinit_subcommands)
- if command in ('install', 'install_lib'):
- cmd.install_lib = None
- return cmd
-
- def run(self):
- self._is_running = True
- try:
- orig.bdist_wininst.run(self)
- finally:
- self._is_running = False
+import distutils.command.bdist_wininst as orig
+
+
+class bdist_wininst(orig.bdist_wininst):
+ def reinitialize_command(self, command, reinit_subcommands=0):
+ """
+ Supplement reinitialize_command to work around
+ http://bugs.python.org/issue20819
+ """
+ cmd = self.distribution.reinitialize_command(
+ command, reinit_subcommands)
+ if command in ('install', 'install_lib'):
+ cmd.install_lib = None
+ return cmd
+
+ def run(self):
+ self._is_running = True
+ try:
+ orig.bdist_wininst.run(self)
+ finally:
+ self._is_running = False
diff --git a/contrib/python/setuptools/py2/setuptools/command/build_ext.py b/contrib/python/setuptools/py2/setuptools/command/build_ext.py
index 235ad9d305..1b51e040b4 100644
--- a/contrib/python/setuptools/py2/setuptools/command/build_ext.py
+++ b/contrib/python/setuptools/py2/setuptools/command/build_ext.py
@@ -1,16 +1,16 @@
import os
import sys
import itertools
-from distutils.command.build_ext import build_ext as _du_build_ext
-from distutils.file_util import copy_file
-from distutils.ccompiler import new_compiler
+from distutils.command.build_ext import build_ext as _du_build_ext
+from distutils.file_util import copy_file
+from distutils.ccompiler import new_compiler
from distutils.sysconfig import customize_compiler, get_config_var
-from distutils.errors import DistutilsError
-from distutils import log
-
-from setuptools.extension import Library
+from distutils.errors import DistutilsError
+from distutils import log
+
+from setuptools.extension import Library
from setuptools.extern import six
-
+
if six.PY2:
import imp
@@ -18,20 +18,20 @@ if six.PY2:
else:
from importlib.machinery import EXTENSION_SUFFIXES
-try:
- # Attempt to use Cython for building extensions, if available
- from Cython.Distutils.build_ext import build_ext as _build_ext
+try:
+ # Attempt to use Cython for building extensions, if available
+ from Cython.Distutils.build_ext import build_ext as _build_ext
# Additionally, assert that the compiler module will load
# also. Ref #1229.
__import__('Cython.Compiler.Main')
-except ImportError:
- _build_ext = _du_build_ext
-
+except ImportError:
+ _build_ext = _du_build_ext
+
# make sure _config_vars is initialized
get_config_var("LDSHARED")
from distutils.sysconfig import _config_vars as _CONFIG_VARS
-
-
+
+
def _customize_compiler_for_shlib(compiler):
if sys.platform == "darwin":
# building .dylib requires additional compiler flags on OSX; here we
@@ -52,21 +52,21 @@ def _customize_compiler_for_shlib(compiler):
customize_compiler(compiler)
-have_rtld = False
-use_stubs = False
-libtype = 'shared'
-
-if sys.platform == "darwin":
- use_stubs = True
-elif os.name != 'nt':
- try:
- import dl
- use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')
- except ImportError:
- pass
-
-if_dl = lambda s: s if have_rtld else ''
-
+have_rtld = False
+use_stubs = False
+libtype = 'shared'
+
+if sys.platform == "darwin":
+ use_stubs = True
+elif os.name != 'nt':
+ try:
+ import dl
+ use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')
+ except ImportError:
+ pass
+
+if_dl = lambda s: s if have_rtld else ''
+
def get_abi3_suffix():
"""Return the file extension for an abi3-compliant Extension()"""
@@ -77,41 +77,41 @@ def get_abi3_suffix():
return suffix
-class build_ext(_build_ext):
- def run(self):
- """Build extensions in build directory, then copy if --inplace"""
- old_inplace, self.inplace = self.inplace, 0
- _build_ext.run(self)
- self.inplace = old_inplace
- if old_inplace:
- self.copy_extensions_to_source()
-
- def copy_extensions_to_source(self):
- build_py = self.get_finalized_command('build_py')
- for ext in self.extensions:
- fullname = self.get_ext_fullname(ext.name)
- filename = self.get_ext_filename(fullname)
- modpath = fullname.split('.')
- package = '.'.join(modpath[:-1])
- package_dir = build_py.get_package_dir(package)
- dest_filename = os.path.join(package_dir,
- os.path.basename(filename))
- src_filename = os.path.join(self.build_lib, filename)
-
- # Always copy, even if source is older than destination, to ensure
- # that the right extensions for the current Python/platform are
- # used.
- copy_file(
- src_filename, dest_filename, verbose=self.verbose,
- dry_run=self.dry_run
- )
- if ext._needs_stub:
- self.write_stub(package_dir or os.curdir, ext, True)
-
- def get_ext_filename(self, fullname):
- filename = _build_ext.get_ext_filename(self, fullname)
- if fullname in self.ext_map:
- ext = self.ext_map[fullname]
+class build_ext(_build_ext):
+ def run(self):
+ """Build extensions in build directory, then copy if --inplace"""
+ old_inplace, self.inplace = self.inplace, 0
+ _build_ext.run(self)
+ self.inplace = old_inplace
+ if old_inplace:
+ self.copy_extensions_to_source()
+
+ def copy_extensions_to_source(self):
+ build_py = self.get_finalized_command('build_py')
+ for ext in self.extensions:
+ fullname = self.get_ext_fullname(ext.name)
+ filename = self.get_ext_filename(fullname)
+ modpath = fullname.split('.')
+ package = '.'.join(modpath[:-1])
+ package_dir = build_py.get_package_dir(package)
+ dest_filename = os.path.join(package_dir,
+ os.path.basename(filename))
+ src_filename = os.path.join(self.build_lib, filename)
+
+ # Always copy, even if source is older than destination, to ensure
+ # that the right extensions for the current Python/platform are
+ # used.
+ copy_file(
+ src_filename, dest_filename, verbose=self.verbose,
+ dry_run=self.dry_run
+ )
+ if ext._needs_stub:
+ self.write_stub(package_dir or os.curdir, ext, True)
+
+ def get_ext_filename(self, fullname):
+ filename = _build_ext.get_ext_filename(self, fullname)
+ if fullname in self.ext_map:
+ ext = self.ext_map[fullname]
use_abi3 = (
not six.PY2
and getattr(ext, 'py_limited_api')
@@ -121,207 +121,207 @@ class build_ext(_build_ext):
so_ext = get_config_var('EXT_SUFFIX')
filename = filename[:-len(so_ext)]
filename = filename + get_abi3_suffix()
- if isinstance(ext, Library):
- fn, ext = os.path.splitext(filename)
- return self.shlib_compiler.library_filename(fn, libtype)
- elif use_stubs and ext._links_to_dynamic:
- d, fn = os.path.split(filename)
- return os.path.join(d, 'dl-' + fn)
- return filename
-
- def initialize_options(self):
- _build_ext.initialize_options(self)
- self.shlib_compiler = None
- self.shlibs = []
- self.ext_map = {}
-
- def finalize_options(self):
- _build_ext.finalize_options(self)
- self.extensions = self.extensions or []
- self.check_extensions_list(self.extensions)
- self.shlibs = [ext for ext in self.extensions
- if isinstance(ext, Library)]
- if self.shlibs:
- self.setup_shlib_compiler()
- for ext in self.extensions:
- ext._full_name = self.get_ext_fullname(ext.name)
- for ext in self.extensions:
- fullname = ext._full_name
- self.ext_map[fullname] = ext
-
- # distutils 3.1 will also ask for module names
- # XXX what to do with conflicts?
- self.ext_map[fullname.split('.')[-1]] = ext
-
- ltd = self.shlibs and self.links_to_dynamic(ext) or False
- ns = ltd and use_stubs and not isinstance(ext, Library)
- ext._links_to_dynamic = ltd
- ext._needs_stub = ns
- filename = ext._file_name = self.get_ext_filename(fullname)
- libdir = os.path.dirname(os.path.join(self.build_lib, filename))
- if ltd and libdir not in ext.library_dirs:
- ext.library_dirs.append(libdir)
- if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs:
- ext.runtime_library_dirs.append(os.curdir)
-
- def setup_shlib_compiler(self):
- compiler = self.shlib_compiler = new_compiler(
- compiler=self.compiler, dry_run=self.dry_run, force=self.force
- )
+ if isinstance(ext, Library):
+ fn, ext = os.path.splitext(filename)
+ return self.shlib_compiler.library_filename(fn, libtype)
+ elif use_stubs and ext._links_to_dynamic:
+ d, fn = os.path.split(filename)
+ return os.path.join(d, 'dl-' + fn)
+ return filename
+
+ def initialize_options(self):
+ _build_ext.initialize_options(self)
+ self.shlib_compiler = None
+ self.shlibs = []
+ self.ext_map = {}
+
+ def finalize_options(self):
+ _build_ext.finalize_options(self)
+ self.extensions = self.extensions or []
+ self.check_extensions_list(self.extensions)
+ self.shlibs = [ext for ext in self.extensions
+ if isinstance(ext, Library)]
+ if self.shlibs:
+ self.setup_shlib_compiler()
+ for ext in self.extensions:
+ ext._full_name = self.get_ext_fullname(ext.name)
+ for ext in self.extensions:
+ fullname = ext._full_name
+ self.ext_map[fullname] = ext
+
+ # distutils 3.1 will also ask for module names
+ # XXX what to do with conflicts?
+ self.ext_map[fullname.split('.')[-1]] = ext
+
+ ltd = self.shlibs and self.links_to_dynamic(ext) or False
+ ns = ltd and use_stubs and not isinstance(ext, Library)
+ ext._links_to_dynamic = ltd
+ ext._needs_stub = ns
+ filename = ext._file_name = self.get_ext_filename(fullname)
+ libdir = os.path.dirname(os.path.join(self.build_lib, filename))
+ if ltd and libdir not in ext.library_dirs:
+ ext.library_dirs.append(libdir)
+ if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs:
+ ext.runtime_library_dirs.append(os.curdir)
+
+ def setup_shlib_compiler(self):
+ compiler = self.shlib_compiler = new_compiler(
+ compiler=self.compiler, dry_run=self.dry_run, force=self.force
+ )
_customize_compiler_for_shlib(compiler)
-
- if self.include_dirs is not None:
- compiler.set_include_dirs(self.include_dirs)
- if self.define is not None:
- # 'define' option is a list of (name,value) tuples
- for (name, value) in self.define:
- compiler.define_macro(name, value)
- if self.undef is not None:
- for macro in self.undef:
- compiler.undefine_macro(macro)
- if self.libraries is not None:
- compiler.set_libraries(self.libraries)
- if self.library_dirs is not None:
- compiler.set_library_dirs(self.library_dirs)
- if self.rpath is not None:
- compiler.set_runtime_library_dirs(self.rpath)
- if self.link_objects is not None:
- compiler.set_link_objects(self.link_objects)
-
- # hack so distutils' build_extension() builds a library instead
- compiler.link_shared_object = link_shared_object.__get__(compiler)
-
- def get_export_symbols(self, ext):
- if isinstance(ext, Library):
- return ext.export_symbols
- return _build_ext.get_export_symbols(self, ext)
-
- def build_extension(self, ext):
- ext._convert_pyx_sources_to_lang()
- _compiler = self.compiler
- try:
- if isinstance(ext, Library):
- self.compiler = self.shlib_compiler
- _build_ext.build_extension(self, ext)
- if ext._needs_stub:
- cmd = self.get_finalized_command('build_py').build_lib
- self.write_stub(cmd, ext)
- finally:
- self.compiler = _compiler
-
- def links_to_dynamic(self, ext):
- """Return true if 'ext' links to a dynamic lib in the same package"""
- # XXX this should check to ensure the lib is actually being built
- # XXX as dynamic, and not just using a locally-found version or a
- # XXX static-compiled version
- libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
- pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])
- return any(pkg + libname in libnames for libname in ext.libraries)
-
- def get_outputs(self):
- return _build_ext.get_outputs(self) + self.__get_stubs_outputs()
-
- def __get_stubs_outputs(self):
- # assemble the base name for each extension that needs a stub
- ns_ext_bases = (
- os.path.join(self.build_lib, *ext._full_name.split('.'))
- for ext in self.extensions
- if ext._needs_stub
- )
- # pair each base with the extension
- pairs = itertools.product(ns_ext_bases, self.__get_output_extensions())
- return list(base + fnext for base, fnext in pairs)
-
- def __get_output_extensions(self):
- yield '.py'
- yield '.pyc'
- if self.get_finalized_command('build_py').optimize:
- yield '.pyo'
-
- def write_stub(self, output_dir, ext, compile=False):
- log.info("writing stub loader for %s to %s", ext._full_name,
- output_dir)
- stub_file = (os.path.join(output_dir, *ext._full_name.split('.')) +
- '.py')
- if compile and os.path.exists(stub_file):
- raise DistutilsError(stub_file + " already exists! Please delete.")
- if not self.dry_run:
- f = open(stub_file, 'w')
- f.write(
- '\n'.join([
- "def __bootstrap__():",
- " global __bootstrap__, __file__, __loader__",
- " import sys, os, pkg_resources, imp" + if_dl(", dl"),
- " __file__ = pkg_resources.resource_filename"
- "(__name__,%r)"
- % os.path.basename(ext._file_name),
- " del __bootstrap__",
- " if '__loader__' in globals():",
- " del __loader__",
- if_dl(" old_flags = sys.getdlopenflags()"),
- " old_dir = os.getcwd()",
- " try:",
- " os.chdir(os.path.dirname(__file__))",
- if_dl(" sys.setdlopenflags(dl.RTLD_NOW)"),
- " imp.load_dynamic(__name__,__file__)",
- " finally:",
- if_dl(" sys.setdlopenflags(old_flags)"),
- " os.chdir(old_dir)",
- "__bootstrap__()",
- "" # terminal \n
- ])
- )
- f.close()
- if compile:
- from distutils.util import byte_compile
-
- byte_compile([stub_file], optimize=0,
- force=True, dry_run=self.dry_run)
- optimize = self.get_finalized_command('install_lib').optimize
- if optimize > 0:
- byte_compile([stub_file], optimize=optimize,
- force=True, dry_run=self.dry_run)
- if os.path.exists(stub_file) and not self.dry_run:
- os.unlink(stub_file)
-
-
-if use_stubs or os.name == 'nt':
- # Build shared libraries
- #
- def link_shared_object(
- self, objects, output_libname, output_dir=None, libraries=None,
- library_dirs=None, runtime_library_dirs=None, export_symbols=None,
- debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
- target_lang=None):
- self.link(
- self.SHARED_LIBRARY, objects, output_libname,
- output_dir, libraries, library_dirs, runtime_library_dirs,
- export_symbols, debug, extra_preargs, extra_postargs,
- build_temp, target_lang
- )
-else:
- # Build static libraries everywhere else
- libtype = 'static'
-
- def link_shared_object(
- self, objects, output_libname, output_dir=None, libraries=None,
- library_dirs=None, runtime_library_dirs=None, export_symbols=None,
- debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
- target_lang=None):
- # XXX we need to either disallow these attrs on Library instances,
- # or warn/abort here if set, or something...
- # libraries=None, library_dirs=None, runtime_library_dirs=None,
- # export_symbols=None, extra_preargs=None, extra_postargs=None,
- # build_temp=None
-
- assert output_dir is None # distutils build_ext doesn't pass this
- output_dir, filename = os.path.split(output_libname)
- basename, ext = os.path.splitext(filename)
- if self.library_filename("x").startswith('lib'):
- # strip 'lib' prefix; this is kludgy if some platform uses
- # a different prefix
- basename = basename[3:]
-
- self.create_static_lib(
- objects, basename, output_dir, debug, target_lang
- )
+
+ if self.include_dirs is not None:
+ compiler.set_include_dirs(self.include_dirs)
+ if self.define is not None:
+ # 'define' option is a list of (name,value) tuples
+ for (name, value) in self.define:
+ compiler.define_macro(name, value)
+ if self.undef is not None:
+ for macro in self.undef:
+ compiler.undefine_macro(macro)
+ if self.libraries is not None:
+ compiler.set_libraries(self.libraries)
+ if self.library_dirs is not None:
+ compiler.set_library_dirs(self.library_dirs)
+ if self.rpath is not None:
+ compiler.set_runtime_library_dirs(self.rpath)
+ if self.link_objects is not None:
+ compiler.set_link_objects(self.link_objects)
+
+ # hack so distutils' build_extension() builds a library instead
+ compiler.link_shared_object = link_shared_object.__get__(compiler)
+
+ def get_export_symbols(self, ext):
+ if isinstance(ext, Library):
+ return ext.export_symbols
+ return _build_ext.get_export_symbols(self, ext)
+
+ def build_extension(self, ext):
+ ext._convert_pyx_sources_to_lang()
+ _compiler = self.compiler
+ try:
+ if isinstance(ext, Library):
+ self.compiler = self.shlib_compiler
+ _build_ext.build_extension(self, ext)
+ if ext._needs_stub:
+ cmd = self.get_finalized_command('build_py').build_lib
+ self.write_stub(cmd, ext)
+ finally:
+ self.compiler = _compiler
+
+ def links_to_dynamic(self, ext):
+ """Return true if 'ext' links to a dynamic lib in the same package"""
+ # XXX this should check to ensure the lib is actually being built
+ # XXX as dynamic, and not just using a locally-found version or a
+ # XXX static-compiled version
+ libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
+ pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])
+ return any(pkg + libname in libnames for libname in ext.libraries)
+
+ def get_outputs(self):
+ return _build_ext.get_outputs(self) + self.__get_stubs_outputs()
+
+ def __get_stubs_outputs(self):
+ # assemble the base name for each extension that needs a stub
+ ns_ext_bases = (
+ os.path.join(self.build_lib, *ext._full_name.split('.'))
+ for ext in self.extensions
+ if ext._needs_stub
+ )
+ # pair each base with the extension
+ pairs = itertools.product(ns_ext_bases, self.__get_output_extensions())
+ return list(base + fnext for base, fnext in pairs)
+
+ def __get_output_extensions(self):
+ yield '.py'
+ yield '.pyc'
+ if self.get_finalized_command('build_py').optimize:
+ yield '.pyo'
+
+ def write_stub(self, output_dir, ext, compile=False):
+ log.info("writing stub loader for %s to %s", ext._full_name,
+ output_dir)
+ stub_file = (os.path.join(output_dir, *ext._full_name.split('.')) +
+ '.py')
+ if compile and os.path.exists(stub_file):
+ raise DistutilsError(stub_file + " already exists! Please delete.")
+ if not self.dry_run:
+ f = open(stub_file, 'w')
+ f.write(
+ '\n'.join([
+ "def __bootstrap__():",
+ " global __bootstrap__, __file__, __loader__",
+ " import sys, os, pkg_resources, imp" + if_dl(", dl"),
+ " __file__ = pkg_resources.resource_filename"
+ "(__name__,%r)"
+ % os.path.basename(ext._file_name),
+ " del __bootstrap__",
+ " if '__loader__' in globals():",
+ " del __loader__",
+ if_dl(" old_flags = sys.getdlopenflags()"),
+ " old_dir = os.getcwd()",
+ " try:",
+ " os.chdir(os.path.dirname(__file__))",
+ if_dl(" sys.setdlopenflags(dl.RTLD_NOW)"),
+ " imp.load_dynamic(__name__,__file__)",
+ " finally:",
+ if_dl(" sys.setdlopenflags(old_flags)"),
+ " os.chdir(old_dir)",
+ "__bootstrap__()",
+ "" # terminal \n
+ ])
+ )
+ f.close()
+ if compile:
+ from distutils.util import byte_compile
+
+ byte_compile([stub_file], optimize=0,
+ force=True, dry_run=self.dry_run)
+ optimize = self.get_finalized_command('install_lib').optimize
+ if optimize > 0:
+ byte_compile([stub_file], optimize=optimize,
+ force=True, dry_run=self.dry_run)
+ if os.path.exists(stub_file) and not self.dry_run:
+ os.unlink(stub_file)
+
+
+if use_stubs or os.name == 'nt':
+ # Build shared libraries
+ #
+ def link_shared_object(
+ self, objects, output_libname, output_dir=None, libraries=None,
+ library_dirs=None, runtime_library_dirs=None, export_symbols=None,
+ debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
+ target_lang=None):
+ self.link(
+ self.SHARED_LIBRARY, objects, output_libname,
+ output_dir, libraries, library_dirs, runtime_library_dirs,
+ export_symbols, debug, extra_preargs, extra_postargs,
+ build_temp, target_lang
+ )
+else:
+ # Build static libraries everywhere else
+ libtype = 'static'
+
+ def link_shared_object(
+ self, objects, output_libname, output_dir=None, libraries=None,
+ library_dirs=None, runtime_library_dirs=None, export_symbols=None,
+ debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
+ target_lang=None):
+ # XXX we need to either disallow these attrs on Library instances,
+ # or warn/abort here if set, or something...
+ # libraries=None, library_dirs=None, runtime_library_dirs=None,
+ # export_symbols=None, extra_preargs=None, extra_postargs=None,
+ # build_temp=None
+
+ assert output_dir is None # distutils build_ext doesn't pass this
+ output_dir, filename = os.path.split(output_libname)
+ basename, ext = os.path.splitext(filename)
+ if self.library_filename("x").startswith('lib'):
+ # strip 'lib' prefix; this is kludgy if some platform uses
+ # a different prefix
+ basename = basename[3:]
+
+ self.create_static_lib(
+ objects, basename, output_dir, debug, target_lang
+ )
diff --git a/contrib/python/setuptools/py2/setuptools/command/build_py.py b/contrib/python/setuptools/py2/setuptools/command/build_py.py
index 733e283005..b0314fd413 100644
--- a/contrib/python/setuptools/py2/setuptools/command/build_py.py
+++ b/contrib/python/setuptools/py2/setuptools/command/build_py.py
@@ -1,103 +1,103 @@
-from glob import glob
-from distutils.util import convert_path
-import distutils.command.build_py as orig
-import os
-import fnmatch
-import textwrap
-import io
-import distutils.errors
-import itertools
-
+from glob import glob
+from distutils.util import convert_path
+import distutils.command.build_py as orig
+import os
+import fnmatch
+import textwrap
+import io
+import distutils.errors
+import itertools
+
from setuptools.extern import six
from setuptools.extern.six.moves import map, filter, filterfalse
-
-try:
- from setuptools.lib2to3_ex import Mixin2to3
-except ImportError:
-
- class Mixin2to3:
- def run_2to3(self, files, doctests=True):
- "do nothing"
-
-
-class build_py(orig.build_py, Mixin2to3):
- """Enhanced 'build_py' command that includes data files with packages
-
- The data files are specified via a 'package_data' argument to 'setup()'.
- See 'setuptools.dist.Distribution' for more details.
-
- Also, this version of the 'build_py' command allows you to specify both
- 'py_modules' and 'packages' in the same setup operation.
- """
-
- def finalize_options(self):
- orig.build_py.finalize_options(self)
- self.package_data = self.distribution.package_data
- self.exclude_package_data = (self.distribution.exclude_package_data or
- {})
- if 'data_files' in self.__dict__:
- del self.__dict__['data_files']
- self.__updated_files = []
- self.__doctests_2to3 = []
-
- def run(self):
- """Build modules, packages, and copy data files to build directory"""
- if not self.py_modules and not self.packages:
- return
-
- if self.py_modules:
- self.build_modules()
-
- if self.packages:
- self.build_packages()
- self.build_package_data()
-
- self.run_2to3(self.__updated_files, False)
- self.run_2to3(self.__updated_files, True)
- self.run_2to3(self.__doctests_2to3, True)
-
- # Only compile actual .py files, using our base class' idea of what our
- # output files are.
- self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=0))
-
- def __getattr__(self, attr):
- "lazily compute data files"
- if attr == 'data_files':
- self.data_files = self._get_data_files()
- return self.data_files
- return orig.build_py.__getattr__(self, attr)
-
- def build_module(self, module, module_file, package):
+
+try:
+ from setuptools.lib2to3_ex import Mixin2to3
+except ImportError:
+
+ class Mixin2to3:
+ def run_2to3(self, files, doctests=True):
+ "do nothing"
+
+
+class build_py(orig.build_py, Mixin2to3):
+ """Enhanced 'build_py' command that includes data files with packages
+
+ The data files are specified via a 'package_data' argument to 'setup()'.
+ See 'setuptools.dist.Distribution' for more details.
+
+ Also, this version of the 'build_py' command allows you to specify both
+ 'py_modules' and 'packages' in the same setup operation.
+ """
+
+ def finalize_options(self):
+ orig.build_py.finalize_options(self)
+ self.package_data = self.distribution.package_data
+ self.exclude_package_data = (self.distribution.exclude_package_data or
+ {})
+ if 'data_files' in self.__dict__:
+ del self.__dict__['data_files']
+ self.__updated_files = []
+ self.__doctests_2to3 = []
+
+ def run(self):
+ """Build modules, packages, and copy data files to build directory"""
+ if not self.py_modules and not self.packages:
+ return
+
+ if self.py_modules:
+ self.build_modules()
+
+ if self.packages:
+ self.build_packages()
+ self.build_package_data()
+
+ self.run_2to3(self.__updated_files, False)
+ self.run_2to3(self.__updated_files, True)
+ self.run_2to3(self.__doctests_2to3, True)
+
+ # Only compile actual .py files, using our base class' idea of what our
+ # output files are.
+ self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=0))
+
+ def __getattr__(self, attr):
+ "lazily compute data files"
+ if attr == 'data_files':
+ self.data_files = self._get_data_files()
+ return self.data_files
+ return orig.build_py.__getattr__(self, attr)
+
+ def build_module(self, module, module_file, package):
if six.PY2 and isinstance(package, six.string_types):
# avoid errors on Python 2 when unicode is passed (#190)
package = package.split('.')
- outfile, copied = orig.build_py.build_module(self, module, module_file,
- package)
- if copied:
- self.__updated_files.append(outfile)
- return outfile, copied
-
- def _get_data_files(self):
- """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
- self.analyze_manifest()
- return list(map(self._get_pkg_data_files, self.packages or ()))
-
- def _get_pkg_data_files(self, package):
- # Locate package source directory
- src_dir = self.get_package_dir(package)
-
- # Compute package build directory
- build_dir = os.path.join(*([self.build_lib] + package.split('.')))
-
- # Strip directory from globbed filenames
- filenames = [
- os.path.relpath(file, src_dir)
- for file in self.find_data_files(package, src_dir)
- ]
- return package, src_dir, build_dir, filenames
-
- def find_data_files(self, package, src_dir):
- """Return filenames for package's data files in 'src_dir'"""
+ outfile, copied = orig.build_py.build_module(self, module, module_file,
+ package)
+ if copied:
+ self.__updated_files.append(outfile)
+ return outfile, copied
+
+ def _get_data_files(self):
+ """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
+ self.analyze_manifest()
+ return list(map(self._get_pkg_data_files, self.packages or ()))
+
+ def _get_pkg_data_files(self, package):
+ # Locate package source directory
+ src_dir = self.get_package_dir(package)
+
+ # Compute package build directory
+ build_dir = os.path.join(*([self.build_lib] + package.split('.')))
+
+ # Strip directory from globbed filenames
+ filenames = [
+ os.path.relpath(file, src_dir)
+ for file in self.find_data_files(package, src_dir)
+ ]
+ return package, src_dir, build_dir, filenames
+
+ def find_data_files(self, package, src_dir):
+ """Return filenames for package's data files in 'src_dir'"""
patterns = self._get_platform_patterns(
self.package_data,
package,
@@ -111,111 +111,111 @@ class build_py(orig.build_py, Mixin2to3):
self.manifest_files.get(package, []),
glob_files,
)
- return self.exclude_data_files(package, src_dir, files)
-
- def build_package_data(self):
- """Copy data files into build directory"""
- for package, src_dir, build_dir, filenames in self.data_files:
- for filename in filenames:
- target = os.path.join(build_dir, filename)
- self.mkpath(os.path.dirname(target))
- srcfile = os.path.join(src_dir, filename)
- outf, copied = self.copy_file(srcfile, target)
- srcfile = os.path.abspath(srcfile)
- if (copied and
- srcfile in self.distribution.convert_2to3_doctests):
- self.__doctests_2to3.append(outf)
-
- def analyze_manifest(self):
- self.manifest_files = mf = {}
- if not self.distribution.include_package_data:
- return
- src_dirs = {}
- for package in self.packages or ():
- # Locate package source directory
- src_dirs[assert_relative(self.get_package_dir(package))] = package
-
- self.run_command('egg_info')
- ei_cmd = self.get_finalized_command('egg_info')
- for path in ei_cmd.filelist.files:
- d, f = os.path.split(assert_relative(path))
- prev = None
- oldf = f
- while d and d != prev and d not in src_dirs:
- prev = d
- d, df = os.path.split(d)
- f = os.path.join(df, f)
- if d in src_dirs:
- if path.endswith('.py') and f == oldf:
- continue # it's a module, not data
- mf.setdefault(src_dirs[d], []).append(path)
-
- def get_data_files(self):
- pass # Lazily compute data files in _get_data_files() function.
-
- def check_package(self, package, package_dir):
- """Check namespace packages' __init__ for declare_namespace"""
- try:
- return self.packages_checked[package]
- except KeyError:
- pass
-
- init_py = orig.build_py.check_package(self, package, package_dir)
- self.packages_checked[package] = init_py
-
- if not init_py or not self.distribution.namespace_packages:
- return init_py
-
- for pkg in self.distribution.namespace_packages:
- if pkg == package or pkg.startswith(package + '.'):
- break
- else:
- return init_py
-
- with io.open(init_py, 'rb') as f:
- contents = f.read()
- if b'declare_namespace' not in contents:
- raise distutils.errors.DistutilsError(
- "Namespace package problem: %s is a namespace package, but "
- "its\n__init__.py does not call declare_namespace()! Please "
- 'fix it.\n(See the setuptools manual under '
- '"Namespace Packages" for details.)\n"' % (package,)
- )
- return init_py
-
- def initialize_options(self):
- self.packages_checked = {}
- orig.build_py.initialize_options(self)
-
- def get_package_dir(self, package):
- res = orig.build_py.get_package_dir(self, package)
- if self.distribution.src_root is not None:
- return os.path.join(self.distribution.src_root, res)
- return res
-
- def exclude_data_files(self, package, src_dir, files):
- """Filter filenames for package's data files in 'src_dir'"""
+ return self.exclude_data_files(package, src_dir, files)
+
+ def build_package_data(self):
+ """Copy data files into build directory"""
+ for package, src_dir, build_dir, filenames in self.data_files:
+ for filename in filenames:
+ target = os.path.join(build_dir, filename)
+ self.mkpath(os.path.dirname(target))
+ srcfile = os.path.join(src_dir, filename)
+ outf, copied = self.copy_file(srcfile, target)
+ srcfile = os.path.abspath(srcfile)
+ if (copied and
+ srcfile in self.distribution.convert_2to3_doctests):
+ self.__doctests_2to3.append(outf)
+
+ def analyze_manifest(self):
+ self.manifest_files = mf = {}
+ if not self.distribution.include_package_data:
+ return
+ src_dirs = {}
+ for package in self.packages or ():
+ # Locate package source directory
+ src_dirs[assert_relative(self.get_package_dir(package))] = package
+
+ self.run_command('egg_info')
+ ei_cmd = self.get_finalized_command('egg_info')
+ for path in ei_cmd.filelist.files:
+ d, f = os.path.split(assert_relative(path))
+ prev = None
+ oldf = f
+ while d and d != prev and d not in src_dirs:
+ prev = d
+ d, df = os.path.split(d)
+ f = os.path.join(df, f)
+ if d in src_dirs:
+ if path.endswith('.py') and f == oldf:
+ continue # it's a module, not data
+ mf.setdefault(src_dirs[d], []).append(path)
+
+ def get_data_files(self):
+ pass # Lazily compute data files in _get_data_files() function.
+
+ def check_package(self, package, package_dir):
+ """Check namespace packages' __init__ for declare_namespace"""
+ try:
+ return self.packages_checked[package]
+ except KeyError:
+ pass
+
+ init_py = orig.build_py.check_package(self, package, package_dir)
+ self.packages_checked[package] = init_py
+
+ if not init_py or not self.distribution.namespace_packages:
+ return init_py
+
+ for pkg in self.distribution.namespace_packages:
+ if pkg == package or pkg.startswith(package + '.'):
+ break
+ else:
+ return init_py
+
+ with io.open(init_py, 'rb') as f:
+ contents = f.read()
+ if b'declare_namespace' not in contents:
+ raise distutils.errors.DistutilsError(
+ "Namespace package problem: %s is a namespace package, but "
+ "its\n__init__.py does not call declare_namespace()! Please "
+ 'fix it.\n(See the setuptools manual under '
+ '"Namespace Packages" for details.)\n"' % (package,)
+ )
+ return init_py
+
+ def initialize_options(self):
+ self.packages_checked = {}
+ orig.build_py.initialize_options(self)
+
+ def get_package_dir(self, package):
+ res = orig.build_py.get_package_dir(self, package)
+ if self.distribution.src_root is not None:
+ return os.path.join(self.distribution.src_root, res)
+ return res
+
+ def exclude_data_files(self, package, src_dir, files):
+ """Filter filenames for package's data files in 'src_dir'"""
files = list(files)
patterns = self._get_platform_patterns(
self.exclude_package_data,
package,
src_dir,
- )
+ )
match_groups = (
fnmatch.filter(files, pattern)
for pattern in patterns
- )
+ )
# flatten the groups of matches into an iterable of matches
matches = itertools.chain.from_iterable(match_groups)
bad = set(matches)
keepers = (
- fn
- for fn in files
- if fn not in bad
+ fn
+ for fn in files
+ if fn not in bad
)
# ditch dupes
return list(_unique_everseen(keepers))
-
+
@staticmethod
def _get_platform_patterns(spec, package, src_dir):
"""
@@ -233,7 +233,7 @@ class build_py(orig.build_py, Mixin2to3):
os.path.join(src_dir, convert_path(pattern))
for pattern in raw_patterns
)
-
+
# from Python docs
def _unique_everseen(iterable, key=None):
@@ -254,17 +254,17 @@ def _unique_everseen(iterable, key=None):
yield element
-def assert_relative(path):
- if not os.path.isabs(path):
- return path
- from distutils.errors import DistutilsSetupError
-
- msg = textwrap.dedent("""
- Error: setup script specifies an absolute path:
-
- %s
-
- setup() arguments must *always* be /-separated paths relative to the
- setup.py directory, *never* absolute paths.
- """).lstrip() % path
- raise DistutilsSetupError(msg)
+def assert_relative(path):
+ if not os.path.isabs(path):
+ return path
+ from distutils.errors import DistutilsSetupError
+
+ msg = textwrap.dedent("""
+ Error: setup script specifies an absolute path:
+
+ %s
+
+ setup() arguments must *always* be /-separated paths relative to the
+ setup.py directory, *never* absolute paths.
+ """).lstrip() % path
+ raise DistutilsSetupError(msg)
diff --git a/contrib/python/setuptools/py2/setuptools/command/develop.py b/contrib/python/setuptools/py2/setuptools/command/develop.py
index 6cb7d37a16..b561924609 100644
--- a/contrib/python/setuptools/py2/setuptools/command/develop.py
+++ b/contrib/python/setuptools/py2/setuptools/command/develop.py
@@ -1,86 +1,86 @@
-from distutils.util import convert_path
-from distutils import log
-from distutils.errors import DistutilsError, DistutilsOptionError
-import os
-import glob
-import io
-
+from distutils.util import convert_path
+from distutils import log
+from distutils.errors import DistutilsError, DistutilsOptionError
+import os
+import glob
+import io
+
from setuptools.extern import six
-
+
import pkg_resources
-from setuptools.command.easy_install import easy_install
+from setuptools.command.easy_install import easy_install
from setuptools import namespaces
-import setuptools
-
+import setuptools
+
__metaclass__ = type
-
+
class develop(namespaces.DevelopInstaller, easy_install):
- """Set up package for development"""
-
- description = "install package in 'development mode'"
-
- user_options = easy_install.user_options + [
- ("uninstall", "u", "Uninstall this source package"),
- ("egg-path=", None, "Set the path to be used in the .egg-link file"),
- ]
-
- boolean_options = easy_install.boolean_options + ['uninstall']
-
- command_consumes_arguments = False # override base
-
- def run(self):
- if self.uninstall:
- self.multi_version = True
- self.uninstall_link()
+ """Set up package for development"""
+
+ description = "install package in 'development mode'"
+
+ user_options = easy_install.user_options + [
+ ("uninstall", "u", "Uninstall this source package"),
+ ("egg-path=", None, "Set the path to be used in the .egg-link file"),
+ ]
+
+ boolean_options = easy_install.boolean_options + ['uninstall']
+
+ command_consumes_arguments = False # override base
+
+ def run(self):
+ if self.uninstall:
+ self.multi_version = True
+ self.uninstall_link()
self.uninstall_namespaces()
- else:
- self.install_for_development()
- self.warn_deprecated_options()
-
- def initialize_options(self):
- self.uninstall = None
- self.egg_path = None
- easy_install.initialize_options(self)
- self.setup_path = None
- self.always_copy_from = '.' # always copy eggs installed in curdir
-
- def finalize_options(self):
- ei = self.get_finalized_command("egg_info")
- if ei.broken_egg_info:
- template = "Please rename %r to %r before using 'develop'"
- args = ei.egg_info, ei.broken_egg_info
- raise DistutilsError(template % args)
- self.args = [ei.egg_name]
-
- easy_install.finalize_options(self)
- self.expand_basedirs()
- self.expand_dirs()
- # pick up setup-dir .egg files only: no .egg-info
- self.package_index.scan(glob.glob('*.egg'))
-
- egg_link_fn = ei.egg_name + '.egg-link'
- self.egg_link = os.path.join(self.install_dir, egg_link_fn)
- self.egg_base = ei.egg_base
- if self.egg_path is None:
- self.egg_path = os.path.abspath(ei.egg_base)
-
+ else:
+ self.install_for_development()
+ self.warn_deprecated_options()
+
+ def initialize_options(self):
+ self.uninstall = None
+ self.egg_path = None
+ easy_install.initialize_options(self)
+ self.setup_path = None
+ self.always_copy_from = '.' # always copy eggs installed in curdir
+
+ def finalize_options(self):
+ ei = self.get_finalized_command("egg_info")
+ if ei.broken_egg_info:
+ template = "Please rename %r to %r before using 'develop'"
+ args = ei.egg_info, ei.broken_egg_info
+ raise DistutilsError(template % args)
+ self.args = [ei.egg_name]
+
+ easy_install.finalize_options(self)
+ self.expand_basedirs()
+ self.expand_dirs()
+ # pick up setup-dir .egg files only: no .egg-info
+ self.package_index.scan(glob.glob('*.egg'))
+
+ egg_link_fn = ei.egg_name + '.egg-link'
+ self.egg_link = os.path.join(self.install_dir, egg_link_fn)
+ self.egg_base = ei.egg_base
+ if self.egg_path is None:
+ self.egg_path = os.path.abspath(ei.egg_base)
+
target = pkg_resources.normalize_path(self.egg_base)
egg_path = pkg_resources.normalize_path(
os.path.join(self.install_dir, self.egg_path))
- if egg_path != target:
- raise DistutilsOptionError(
- "--egg-path must be a relative path from the install"
- " directory to " + target
- )
-
- # Make a distribution for the package's source
+ if egg_path != target:
+ raise DistutilsOptionError(
+ "--egg-path must be a relative path from the install"
+ " directory to " + target
+ )
+
+ # Make a distribution for the package's source
self.dist = pkg_resources.Distribution(
- target,
+ target,
pkg_resources.PathMetadata(target, os.path.abspath(ei.egg_info)),
- project_name=ei.egg_name
- )
-
+ project_name=ei.egg_name
+ )
+
self.setup_path = self._resolve_setup_path(
self.egg_base,
self.install_dir,
@@ -101,121 +101,121 @@ class develop(namespaces.DevelopInstaller, easy_install):
os.path.join(install_dir, egg_path, path_to_setup)
)
if resolved != pkg_resources.normalize_path(os.curdir):
- raise DistutilsOptionError(
- "Can't get a consistent path to setup script from"
+ raise DistutilsOptionError(
+ "Can't get a consistent path to setup script from"
" installation directory", resolved,
pkg_resources.normalize_path(os.curdir))
return path_to_setup
-
- def install_for_development(self):
+
+ def install_for_development(self):
if not six.PY2 and getattr(self.distribution, 'use_2to3', False):
- # If we run 2to3 we can not do this inplace:
-
- # Ensure metadata is up-to-date
- self.reinitialize_command('build_py', inplace=0)
- self.run_command('build_py')
- bpy_cmd = self.get_finalized_command("build_py")
+ # If we run 2to3 we can not do this inplace:
+
+ # Ensure metadata is up-to-date
+ self.reinitialize_command('build_py', inplace=0)
+ self.run_command('build_py')
+ bpy_cmd = self.get_finalized_command("build_py")
build_path = pkg_resources.normalize_path(bpy_cmd.build_lib)
-
- # Build extensions
- self.reinitialize_command('egg_info', egg_base=build_path)
- self.run_command('egg_info')
-
- self.reinitialize_command('build_ext', inplace=0)
- self.run_command('build_ext')
-
- # Fixup egg-link and easy-install.pth
- ei_cmd = self.get_finalized_command("egg_info")
- self.egg_path = build_path
- self.dist.location = build_path
- # XXX
+
+ # Build extensions
+ self.reinitialize_command('egg_info', egg_base=build_path)
+ self.run_command('egg_info')
+
+ self.reinitialize_command('build_ext', inplace=0)
+ self.run_command('build_ext')
+
+ # Fixup egg-link and easy-install.pth
+ ei_cmd = self.get_finalized_command("egg_info")
+ self.egg_path = build_path
+ self.dist.location = build_path
+ # XXX
self.dist._provider = pkg_resources.PathMetadata(
build_path, ei_cmd.egg_info)
- else:
- # Without 2to3 inplace works fine:
- self.run_command('egg_info')
-
- # Build extensions in-place
- self.reinitialize_command('build_ext', inplace=1)
- self.run_command('build_ext')
-
- self.install_site_py() # ensure that target dir is site-safe
- if setuptools.bootstrap_install_from:
- self.easy_install(setuptools.bootstrap_install_from)
- setuptools.bootstrap_install_from = None
-
+ else:
+ # Without 2to3 inplace works fine:
+ self.run_command('egg_info')
+
+ # Build extensions in-place
+ self.reinitialize_command('build_ext', inplace=1)
+ self.run_command('build_ext')
+
+ self.install_site_py() # ensure that target dir is site-safe
+ if setuptools.bootstrap_install_from:
+ self.easy_install(setuptools.bootstrap_install_from)
+ setuptools.bootstrap_install_from = None
+
self.install_namespaces()
- # create an .egg-link in the installation dir, pointing to our egg
- log.info("Creating %s (link to %s)", self.egg_link, self.egg_base)
- if not self.dry_run:
- with open(self.egg_link, "w") as f:
- f.write(self.egg_path + "\n" + self.setup_path)
- # postprocess the installed distro, fixing up .pth, installing scripts,
- # and handling requirements
- self.process_distribution(None, self.dist, not self.no_deps)
-
- def uninstall_link(self):
- if os.path.exists(self.egg_link):
- log.info("Removing %s (link to %s)", self.egg_link, self.egg_base)
- egg_link_file = open(self.egg_link)
- contents = [line.rstrip() for line in egg_link_file]
- egg_link_file.close()
- if contents not in ([self.egg_path],
- [self.egg_path, self.setup_path]):
- log.warn("Link points to %s: uninstall aborted", contents)
- return
- if not self.dry_run:
- os.unlink(self.egg_link)
- if not self.dry_run:
- self.update_pth(self.dist) # remove any .pth link to us
- if self.distribution.scripts:
- # XXX should also check for entry point scripts!
- log.warn("Note: you must uninstall or replace scripts manually!")
-
- def install_egg_scripts(self, dist):
- if dist is not self.dist:
- # Installing a dependency, so fall back to normal behavior
- return easy_install.install_egg_scripts(self, dist)
-
- # create wrapper scripts in the script dir, pointing to dist.scripts
-
- # new-style...
- self.install_wrapper_scripts(dist)
-
- # ...and old-style
- for script_name in self.distribution.scripts or []:
- script_path = os.path.abspath(convert_path(script_name))
- script_name = os.path.basename(script_path)
- with io.open(script_path) as strm:
- script_text = strm.read()
- self.install_script(dist, script_name, script_text, script_path)
-
- def install_wrapper_scripts(self, dist):
- dist = VersionlessRequirement(dist)
- return easy_install.install_wrapper_scripts(self, dist)
-
-
+ # create an .egg-link in the installation dir, pointing to our egg
+ log.info("Creating %s (link to %s)", self.egg_link, self.egg_base)
+ if not self.dry_run:
+ with open(self.egg_link, "w") as f:
+ f.write(self.egg_path + "\n" + self.setup_path)
+ # postprocess the installed distro, fixing up .pth, installing scripts,
+ # and handling requirements
+ self.process_distribution(None, self.dist, not self.no_deps)
+
+ def uninstall_link(self):
+ if os.path.exists(self.egg_link):
+ log.info("Removing %s (link to %s)", self.egg_link, self.egg_base)
+ egg_link_file = open(self.egg_link)
+ contents = [line.rstrip() for line in egg_link_file]
+ egg_link_file.close()
+ if contents not in ([self.egg_path],
+ [self.egg_path, self.setup_path]):
+ log.warn("Link points to %s: uninstall aborted", contents)
+ return
+ if not self.dry_run:
+ os.unlink(self.egg_link)
+ if not self.dry_run:
+ self.update_pth(self.dist) # remove any .pth link to us
+ if self.distribution.scripts:
+ # XXX should also check for entry point scripts!
+ log.warn("Note: you must uninstall or replace scripts manually!")
+
+ def install_egg_scripts(self, dist):
+ if dist is not self.dist:
+ # Installing a dependency, so fall back to normal behavior
+ return easy_install.install_egg_scripts(self, dist)
+
+ # create wrapper scripts in the script dir, pointing to dist.scripts
+
+ # new-style...
+ self.install_wrapper_scripts(dist)
+
+ # ...and old-style
+ for script_name in self.distribution.scripts or []:
+ script_path = os.path.abspath(convert_path(script_name))
+ script_name = os.path.basename(script_path)
+ with io.open(script_path) as strm:
+ script_text = strm.read()
+ self.install_script(dist, script_name, script_text, script_path)
+
+ def install_wrapper_scripts(self, dist):
+ dist = VersionlessRequirement(dist)
+ return easy_install.install_wrapper_scripts(self, dist)
+
+
class VersionlessRequirement:
- """
- Adapt a pkg_resources.Distribution to simply return the project
- name as the 'requirement' so that scripts will work across
- multiple versions.
-
+ """
+ Adapt a pkg_resources.Distribution to simply return the project
+ name as the 'requirement' so that scripts will work across
+ multiple versions.
+
>>> from pkg_resources import Distribution
- >>> dist = Distribution(project_name='foo', version='1.0')
- >>> str(dist.as_requirement())
- 'foo==1.0'
- >>> adapted_dist = VersionlessRequirement(dist)
- >>> str(adapted_dist.as_requirement())
- 'foo'
- """
-
- def __init__(self, dist):
- self.__dist = dist
-
- def __getattr__(self, name):
- return getattr(self.__dist, name)
-
- def as_requirement(self):
- return self.project_name
+ >>> dist = Distribution(project_name='foo', version='1.0')
+ >>> str(dist.as_requirement())
+ 'foo==1.0'
+ >>> adapted_dist = VersionlessRequirement(dist)
+ >>> str(adapted_dist.as_requirement())
+ 'foo'
+ """
+
+ def __init__(self, dist):
+ self.__dist = dist
+
+ def __getattr__(self, name):
+ return getattr(self.__dist, name)
+
+ def as_requirement(self):
+ return self.project_name
diff --git a/contrib/python/setuptools/py2/setuptools/command/easy_install.py b/contrib/python/setuptools/py2/setuptools/command/easy_install.py
index 037a85a5f4..426301d6f3 100644
--- a/contrib/python/setuptools/py2/setuptools/command/easy_install.py
+++ b/contrib/python/setuptools/py2/setuptools/command/easy_install.py
@@ -1,46 +1,46 @@
-#!/usr/bin/env python
-"""
-Easy Install
-------------
-
-A tool for doing automatic download/extract/build of distutils-based Python
-packages. For detailed documentation, see the accompanying EasyInstall.txt
-file, or visit the `EasyInstall home page`__.
-
+#!/usr/bin/env python
+"""
+Easy Install
+------------
+
+A tool for doing automatic download/extract/build of distutils-based Python
+packages. For detailed documentation, see the accompanying EasyInstall.txt
+file, or visit the `EasyInstall home page`__.
+
__ https://setuptools.readthedocs.io/en/latest/easy_install.html
-
-"""
-
-from glob import glob
-from distutils.util import get_platform
-from distutils.util import convert_path, subst_vars
+
+"""
+
+from glob import glob
+from distutils.util import get_platform
+from distutils.util import convert_path, subst_vars
from distutils.errors import (
DistutilsArgError, DistutilsOptionError,
DistutilsError, DistutilsPlatformError,
)
-from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
-from distutils import log, dir_util
-from distutils.command.build_scripts import first_line_re
-from distutils.spawn import find_executable
-import sys
-import os
-import zipimport
-import shutil
-import tempfile
-import zipfile
-import re
-import stat
-import random
-import textwrap
-import warnings
-import site
-import struct
-import contextlib
-import subprocess
-import shlex
-import io
-
-
+from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
+from distutils import log, dir_util
+from distutils.command.build_scripts import first_line_re
+from distutils.spawn import find_executable
+import sys
+import os
+import zipimport
+import shutil
+import tempfile
+import zipfile
+import re
+import stat
+import random
+import textwrap
+import warnings
+import site
+import struct
+import contextlib
+import subprocess
+import shlex
+import io
+
+
from sysconfig import get_config_vars, get_path
from setuptools import SetuptoolsDeprecationWarning
@@ -48,358 +48,358 @@ from setuptools import SetuptoolsDeprecationWarning
from setuptools.extern import six
from setuptools.extern.six.moves import configparser, map
-from setuptools import Command
-from setuptools.sandbox import run_setup
+from setuptools import Command
+from setuptools.sandbox import run_setup
from setuptools.py27compat import rmtree_safe
-from setuptools.command import setopt
-from setuptools.archive_util import unpack_archive
+from setuptools.command import setopt
+from setuptools.archive_util import unpack_archive
from setuptools.package_index import (
PackageIndex, parse_requirement_arg, URL_SCHEME,
)
-from setuptools.command import bdist_egg, egg_info
+from setuptools.command import bdist_egg, egg_info
from setuptools.wheel import Wheel
-from pkg_resources import (
- yield_lines, normalize_path, resource_string, ensure_directory,
- get_distribution, find_distributions, Environment, Requirement,
- Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound,
- VersionConflict, DEVELOP_DIST,
-)
+from pkg_resources import (
+ yield_lines, normalize_path, resource_string, ensure_directory,
+ get_distribution, find_distributions, Environment, Requirement,
+ Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound,
+ VersionConflict, DEVELOP_DIST,
+)
import pkg_resources.py31compat
-
+
__metaclass__ = type
-# Turn on PEP440Warnings
-warnings.filterwarnings("default", category=pkg_resources.PEP440Warning)
-
-__all__ = [
- 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg',
- 'main', 'get_exe_prefixes',
-]
-
-
-def is_64bit():
- return struct.calcsize("P") == 8
-
-
-def samefile(p1, p2):
+# Turn on PEP440Warnings
+warnings.filterwarnings("default", category=pkg_resources.PEP440Warning)
+
+__all__ = [
+ 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg',
+ 'main', 'get_exe_prefixes',
+]
+
+
+def is_64bit():
+ return struct.calcsize("P") == 8
+
+
+def samefile(p1, p2):
"""
Determine if two paths reference the same file.
Augments os.path.samefile to work on Windows and
suppresses errors if the path doesn't exist.
"""
- both_exist = os.path.exists(p1) and os.path.exists(p2)
- use_samefile = hasattr(os.path, 'samefile') and both_exist
- if use_samefile:
- return os.path.samefile(p1, p2)
- norm_p1 = os.path.normpath(os.path.normcase(p1))
- norm_p2 = os.path.normpath(os.path.normcase(p2))
- return norm_p1 == norm_p2
-
-
-if six.PY2:
+ both_exist = os.path.exists(p1) and os.path.exists(p2)
+ use_samefile = hasattr(os.path, 'samefile') and both_exist
+ if use_samefile:
+ return os.path.samefile(p1, p2)
+ norm_p1 = os.path.normpath(os.path.normcase(p1))
+ norm_p2 = os.path.normpath(os.path.normcase(p2))
+ return norm_p1 == norm_p2
+
+
+if six.PY2:
def _to_bytes(s):
- return s
-
- def isascii(s):
- try:
- six.text_type(s, 'ascii')
- return True
- except UnicodeError:
- return False
-else:
+ return s
+
+ def isascii(s):
+ try:
+ six.text_type(s, 'ascii')
+ return True
+ except UnicodeError:
+ return False
+else:
def _to_bytes(s):
return s.encode('utf8')
-
- def isascii(s):
- try:
- s.encode('ascii')
- return True
- except UnicodeError:
- return False
-
-
+
+ def isascii(s):
+ try:
+ s.encode('ascii')
+ return True
+ except UnicodeError:
+ return False
+
+
_one_liner = lambda text: textwrap.dedent(text).strip().replace('\n', '; ')
-class easy_install(Command):
- """Manage a download/build/install process"""
- description = "Find/get/install Python packages"
- command_consumes_arguments = True
-
- user_options = [
- ('prefix=', None, "installation prefix"),
- ("zip-ok", "z", "install package as a zipfile"),
- ("multi-version", "m", "make apps have to require() a version"),
- ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"),
- ("install-dir=", "d", "install package to DIR"),
- ("script-dir=", "s", "install scripts to DIR"),
- ("exclude-scripts", "x", "Don't install scripts"),
- ("always-copy", "a", "Copy all needed packages to install dir"),
- ("index-url=", "i", "base URL of Python Package Index"),
- ("find-links=", "f", "additional URL(s) to search for packages"),
- ("build-directory=", "b",
- "download/extract/build in DIR; keep the results"),
- ('optimize=', 'O',
- "also compile with optimization: -O1 for \"python -O\", "
- "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
- ('record=', None,
- "filename in which to record list of installed files"),
- ('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
- ('site-dirs=', 'S', "list of directories where .pth files work"),
- ('editable', 'e', "Install specified packages in editable form"),
- ('no-deps', 'N', "don't install dependencies"),
- ('allow-hosts=', 'H', "pattern(s) that hostnames must match"),
- ('local-snapshots-ok', 'l',
- "allow building eggs from local checkouts"),
- ('version', None, "print version information and exit"),
- ('no-find-links', None,
- "Don't load find-links defined in packages being installed")
- ]
- boolean_options = [
- 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy',
- 'editable',
- 'no-deps', 'local-snapshots-ok', 'version'
- ]
-
- if site.ENABLE_USER_SITE:
- help_msg = "install in user site-package '%s'" % site.USER_SITE
- user_options.append(('user', None, help_msg))
- boolean_options.append('user')
-
- negative_opt = {'always-unzip': 'zip-ok'}
- create_index = PackageIndex
-
- def initialize_options(self):
- # the --user option seems to be an opt-in one,
- # so the default should be False.
- self.user = 0
- self.zip_ok = self.local_snapshots_ok = None
- self.install_dir = self.script_dir = self.exclude_scripts = None
- self.index_url = None
- self.find_links = None
- self.build_directory = None
- self.args = None
- self.optimize = self.record = None
- self.upgrade = self.always_copy = self.multi_version = None
- self.editable = self.no_deps = self.allow_hosts = None
- self.root = self.prefix = self.no_report = None
- self.version = None
- self.install_purelib = None # for pure module distributions
- self.install_platlib = None # non-pure (dists w/ extensions)
- self.install_headers = None # for C/C++ headers
- self.install_lib = None # set to either purelib or platlib
- self.install_scripts = None
- self.install_data = None
- self.install_base = None
- self.install_platbase = None
- if site.ENABLE_USER_SITE:
- self.install_userbase = site.USER_BASE
- self.install_usersite = site.USER_SITE
- else:
- self.install_userbase = None
- self.install_usersite = None
- self.no_find_links = None
-
- # Options not specifiable via command line
- self.package_index = None
- self.pth_file = self.always_copy_from = None
- self.site_dirs = None
- self.installed_projects = {}
- self.sitepy_installed = False
- # Always read easy_install options, even if we are subclassed, or have
- # an independent instance created. This ensures that defaults will
- # always come from the standard configuration file(s)' "easy_install"
- # section, even if this is a "develop" or "install" command, or some
- # other embedding.
- self._dry_run = None
- self.verbose = self.distribution.verbose
- self.distribution._set_command_options(
- self, self.distribution.get_option_dict('easy_install')
- )
-
- def delete_blockers(self, blockers):
- extant_blockers = (
- filename for filename in blockers
- if os.path.exists(filename) or os.path.islink(filename)
- )
- list(map(self._delete_path, extant_blockers))
-
- def _delete_path(self, path):
- log.info("Deleting %s", path)
- if self.dry_run:
- return
-
- is_tree = os.path.isdir(path) and not os.path.islink(path)
- remover = rmtree if is_tree else os.unlink
- remover(path)
-
- @staticmethod
- def _render_version():
- """
- Render the Setuptools version and installation details, then exit.
- """
+class easy_install(Command):
+ """Manage a download/build/install process"""
+ description = "Find/get/install Python packages"
+ command_consumes_arguments = True
+
+ user_options = [
+ ('prefix=', None, "installation prefix"),
+ ("zip-ok", "z", "install package as a zipfile"),
+ ("multi-version", "m", "make apps have to require() a version"),
+ ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"),
+ ("install-dir=", "d", "install package to DIR"),
+ ("script-dir=", "s", "install scripts to DIR"),
+ ("exclude-scripts", "x", "Don't install scripts"),
+ ("always-copy", "a", "Copy all needed packages to install dir"),
+ ("index-url=", "i", "base URL of Python Package Index"),
+ ("find-links=", "f", "additional URL(s) to search for packages"),
+ ("build-directory=", "b",
+ "download/extract/build in DIR; keep the results"),
+ ('optimize=', 'O',
+ "also compile with optimization: -O1 for \"python -O\", "
+ "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
+ ('record=', None,
+ "filename in which to record list of installed files"),
+ ('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
+ ('site-dirs=', 'S', "list of directories where .pth files work"),
+ ('editable', 'e', "Install specified packages in editable form"),
+ ('no-deps', 'N', "don't install dependencies"),
+ ('allow-hosts=', 'H', "pattern(s) that hostnames must match"),
+ ('local-snapshots-ok', 'l',
+ "allow building eggs from local checkouts"),
+ ('version', None, "print version information and exit"),
+ ('no-find-links', None,
+ "Don't load find-links defined in packages being installed")
+ ]
+ boolean_options = [
+ 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy',
+ 'editable',
+ 'no-deps', 'local-snapshots-ok', 'version'
+ ]
+
+ if site.ENABLE_USER_SITE:
+ help_msg = "install in user site-package '%s'" % site.USER_SITE
+ user_options.append(('user', None, help_msg))
+ boolean_options.append('user')
+
+ negative_opt = {'always-unzip': 'zip-ok'}
+ create_index = PackageIndex
+
+ def initialize_options(self):
+ # the --user option seems to be an opt-in one,
+ # so the default should be False.
+ self.user = 0
+ self.zip_ok = self.local_snapshots_ok = None
+ self.install_dir = self.script_dir = self.exclude_scripts = None
+ self.index_url = None
+ self.find_links = None
+ self.build_directory = None
+ self.args = None
+ self.optimize = self.record = None
+ self.upgrade = self.always_copy = self.multi_version = None
+ self.editable = self.no_deps = self.allow_hosts = None
+ self.root = self.prefix = self.no_report = None
+ self.version = None
+ self.install_purelib = None # for pure module distributions
+ self.install_platlib = None # non-pure (dists w/ extensions)
+ self.install_headers = None # for C/C++ headers
+ self.install_lib = None # set to either purelib or platlib
+ self.install_scripts = None
+ self.install_data = None
+ self.install_base = None
+ self.install_platbase = None
+ if site.ENABLE_USER_SITE:
+ self.install_userbase = site.USER_BASE
+ self.install_usersite = site.USER_SITE
+ else:
+ self.install_userbase = None
+ self.install_usersite = None
+ self.no_find_links = None
+
+ # Options not specifiable via command line
+ self.package_index = None
+ self.pth_file = self.always_copy_from = None
+ self.site_dirs = None
+ self.installed_projects = {}
+ self.sitepy_installed = False
+ # Always read easy_install options, even if we are subclassed, or have
+ # an independent instance created. This ensures that defaults will
+ # always come from the standard configuration file(s)' "easy_install"
+ # section, even if this is a "develop" or "install" command, or some
+ # other embedding.
+ self._dry_run = None
+ self.verbose = self.distribution.verbose
+ self.distribution._set_command_options(
+ self, self.distribution.get_option_dict('easy_install')
+ )
+
+ def delete_blockers(self, blockers):
+ extant_blockers = (
+ filename for filename in blockers
+ if os.path.exists(filename) or os.path.islink(filename)
+ )
+ list(map(self._delete_path, extant_blockers))
+
+ def _delete_path(self, path):
+ log.info("Deleting %s", path)
+ if self.dry_run:
+ return
+
+ is_tree = os.path.isdir(path) and not os.path.islink(path)
+ remover = rmtree if is_tree else os.unlink
+ remover(path)
+
+ @staticmethod
+ def _render_version():
+ """
+ Render the Setuptools version and installation details, then exit.
+ """
ver = '{}.{}'.format(*sys.version_info)
- dist = get_distribution('setuptools')
- tmpl = 'setuptools {dist.version} from {dist.location} (Python {ver})'
- print(tmpl.format(**locals()))
- raise SystemExit()
-
- def finalize_options(self):
- self.version and self._render_version()
-
- py_version = sys.version.split()[0]
- prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix')
-
- self.config_vars = {
- 'dist_name': self.distribution.get_name(),
- 'dist_version': self.distribution.get_version(),
- 'dist_fullname': self.distribution.get_fullname(),
- 'py_version': py_version,
- 'py_version_short': py_version[0:3],
- 'py_version_nodot': py_version[0] + py_version[2],
- 'sys_prefix': prefix,
- 'prefix': prefix,
- 'sys_exec_prefix': exec_prefix,
- 'exec_prefix': exec_prefix,
- # Only python 3.2+ has abiflags
- 'abiflags': getattr(sys, 'abiflags', ''),
- }
-
- if site.ENABLE_USER_SITE:
- self.config_vars['userbase'] = self.install_userbase
- self.config_vars['usersite'] = self.install_usersite
-
- self._fix_install_dir_for_user_site()
-
- self.expand_basedirs()
- self.expand_dirs()
-
+ dist = get_distribution('setuptools')
+ tmpl = 'setuptools {dist.version} from {dist.location} (Python {ver})'
+ print(tmpl.format(**locals()))
+ raise SystemExit()
+
+ def finalize_options(self):
+ self.version and self._render_version()
+
+ py_version = sys.version.split()[0]
+ prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix')
+
+ self.config_vars = {
+ 'dist_name': self.distribution.get_name(),
+ 'dist_version': self.distribution.get_version(),
+ 'dist_fullname': self.distribution.get_fullname(),
+ 'py_version': py_version,
+ 'py_version_short': py_version[0:3],
+ 'py_version_nodot': py_version[0] + py_version[2],
+ 'sys_prefix': prefix,
+ 'prefix': prefix,
+ 'sys_exec_prefix': exec_prefix,
+ 'exec_prefix': exec_prefix,
+ # Only python 3.2+ has abiflags
+ 'abiflags': getattr(sys, 'abiflags', ''),
+ }
+
+ if site.ENABLE_USER_SITE:
+ self.config_vars['userbase'] = self.install_userbase
+ self.config_vars['usersite'] = self.install_usersite
+
+ self._fix_install_dir_for_user_site()
+
+ self.expand_basedirs()
+ self.expand_dirs()
+
self._expand(
'install_dir', 'script_dir', 'build_directory',
'site_dirs',
)
- # If a non-default installation directory was specified, default the
- # script directory to match it.
- if self.script_dir is None:
- self.script_dir = self.install_dir
-
- if self.no_find_links is None:
- self.no_find_links = False
-
- # Let install_dir get set by install_lib command, which in turn
- # gets its info from the install command, and takes into account
- # --prefix and --home and all that other crud.
- self.set_undefined_options(
- 'install_lib', ('install_dir', 'install_dir')
- )
- # Likewise, set default script_dir from 'install_scripts.install_dir'
- self.set_undefined_options(
- 'install_scripts', ('install_dir', 'script_dir')
- )
-
- if self.user and self.install_purelib:
- self.install_dir = self.install_purelib
- self.script_dir = self.install_scripts
- # default --record from the install command
- self.set_undefined_options('install', ('record', 'record'))
- # Should this be moved to the if statement below? It's not used
- # elsewhere
- normpath = map(normalize_path, sys.path)
- self.all_site_dirs = get_site_dirs()
- if self.site_dirs is not None:
- site_dirs = [
- os.path.expanduser(s.strip()) for s in
- self.site_dirs.split(',')
- ]
- for d in site_dirs:
- if not os.path.isdir(d):
- log.warn("%s (in --site-dirs) does not exist", d)
- elif normalize_path(d) not in normpath:
- raise DistutilsOptionError(
- d + " (in --site-dirs) is not on sys.path"
- )
- else:
- self.all_site_dirs.append(normalize_path(d))
- if not self.editable:
- self.check_site_dir()
+ # If a non-default installation directory was specified, default the
+ # script directory to match it.
+ if self.script_dir is None:
+ self.script_dir = self.install_dir
+
+ if self.no_find_links is None:
+ self.no_find_links = False
+
+ # Let install_dir get set by install_lib command, which in turn
+ # gets its info from the install command, and takes into account
+ # --prefix and --home and all that other crud.
+ self.set_undefined_options(
+ 'install_lib', ('install_dir', 'install_dir')
+ )
+ # Likewise, set default script_dir from 'install_scripts.install_dir'
+ self.set_undefined_options(
+ 'install_scripts', ('install_dir', 'script_dir')
+ )
+
+ if self.user and self.install_purelib:
+ self.install_dir = self.install_purelib
+ self.script_dir = self.install_scripts
+ # default --record from the install command
+ self.set_undefined_options('install', ('record', 'record'))
+ # Should this be moved to the if statement below? It's not used
+ # elsewhere
+ normpath = map(normalize_path, sys.path)
+ self.all_site_dirs = get_site_dirs()
+ if self.site_dirs is not None:
+ site_dirs = [
+ os.path.expanduser(s.strip()) for s in
+ self.site_dirs.split(',')
+ ]
+ for d in site_dirs:
+ if not os.path.isdir(d):
+ log.warn("%s (in --site-dirs) does not exist", d)
+ elif normalize_path(d) not in normpath:
+ raise DistutilsOptionError(
+ d + " (in --site-dirs) is not on sys.path"
+ )
+ else:
+ self.all_site_dirs.append(normalize_path(d))
+ if not self.editable:
+ self.check_site_dir()
self.index_url = self.index_url or "https://pypi.org/simple/"
- self.shadow_path = self.all_site_dirs[:]
- for path_item in self.install_dir, normalize_path(self.script_dir):
- if path_item not in self.shadow_path:
- self.shadow_path.insert(0, path_item)
-
- if self.allow_hosts is not None:
- hosts = [s.strip() for s in self.allow_hosts.split(',')]
- else:
- hosts = ['*']
- if self.package_index is None:
- self.package_index = self.create_index(
- self.index_url, search_path=self.shadow_path, hosts=hosts,
- )
- self.local_index = Environment(self.shadow_path + sys.path)
-
- if self.find_links is not None:
- if isinstance(self.find_links, six.string_types):
- self.find_links = self.find_links.split()
- else:
- self.find_links = []
- if self.local_snapshots_ok:
- self.package_index.scan_egg_links(self.shadow_path + sys.path)
- if not self.no_find_links:
- self.package_index.add_find_links(self.find_links)
- self.set_undefined_options('install_lib', ('optimize', 'optimize'))
- if not isinstance(self.optimize, int):
- try:
- self.optimize = int(self.optimize)
- if not (0 <= self.optimize <= 2):
- raise ValueError
- except ValueError:
- raise DistutilsOptionError("--optimize must be 0, 1, or 2")
-
- if self.editable and not self.build_directory:
- raise DistutilsArgError(
- "Must specify a build directory (-b) when using --editable"
- )
- if not self.args:
- raise DistutilsArgError(
- "No urls, filenames, or requirements specified (see --help)")
-
- self.outputs = []
-
- def _fix_install_dir_for_user_site(self):
- """
- Fix the install_dir if "--user" was used.
- """
- if not self.user or not site.ENABLE_USER_SITE:
- return
-
- self.create_home_path()
- if self.install_userbase is None:
- msg = "User base directory is not specified"
- raise DistutilsPlatformError(msg)
- self.install_base = self.install_platbase = self.install_userbase
- scheme_name = os.name.replace('posix', 'unix') + '_user'
- self.select_scheme(scheme_name)
-
- def _expand_attrs(self, attrs):
- for attr in attrs:
- val = getattr(self, attr)
- if val is not None:
- if os.name == 'posix' or os.name == 'nt':
- val = os.path.expanduser(val)
- val = subst_vars(val, self.config_vars)
- setattr(self, attr, val)
-
- def expand_basedirs(self):
- """Calls `os.path.expanduser` on install_base, install_platbase and
- root."""
- self._expand_attrs(['install_base', 'install_platbase', 'root'])
-
- def expand_dirs(self):
- """Calls `os.path.expanduser` on install dirs."""
+ self.shadow_path = self.all_site_dirs[:]
+ for path_item in self.install_dir, normalize_path(self.script_dir):
+ if path_item not in self.shadow_path:
+ self.shadow_path.insert(0, path_item)
+
+ if self.allow_hosts is not None:
+ hosts = [s.strip() for s in self.allow_hosts.split(',')]
+ else:
+ hosts = ['*']
+ if self.package_index is None:
+ self.package_index = self.create_index(
+ self.index_url, search_path=self.shadow_path, hosts=hosts,
+ )
+ self.local_index = Environment(self.shadow_path + sys.path)
+
+ if self.find_links is not None:
+ if isinstance(self.find_links, six.string_types):
+ self.find_links = self.find_links.split()
+ else:
+ self.find_links = []
+ if self.local_snapshots_ok:
+ self.package_index.scan_egg_links(self.shadow_path + sys.path)
+ if not self.no_find_links:
+ self.package_index.add_find_links(self.find_links)
+ self.set_undefined_options('install_lib', ('optimize', 'optimize'))
+ if not isinstance(self.optimize, int):
+ try:
+ self.optimize = int(self.optimize)
+ if not (0 <= self.optimize <= 2):
+ raise ValueError
+ except ValueError:
+ raise DistutilsOptionError("--optimize must be 0, 1, or 2")
+
+ if self.editable and not self.build_directory:
+ raise DistutilsArgError(
+ "Must specify a build directory (-b) when using --editable"
+ )
+ if not self.args:
+ raise DistutilsArgError(
+ "No urls, filenames, or requirements specified (see --help)")
+
+ self.outputs = []
+
+ def _fix_install_dir_for_user_site(self):
+ """
+ Fix the install_dir if "--user" was used.
+ """
+ if not self.user or not site.ENABLE_USER_SITE:
+ return
+
+ self.create_home_path()
+ if self.install_userbase is None:
+ msg = "User base directory is not specified"
+ raise DistutilsPlatformError(msg)
+ self.install_base = self.install_platbase = self.install_userbase
+ scheme_name = os.name.replace('posix', 'unix') + '_user'
+ self.select_scheme(scheme_name)
+
+ def _expand_attrs(self, attrs):
+ for attr in attrs:
+ val = getattr(self, attr)
+ if val is not None:
+ if os.name == 'posix' or os.name == 'nt':
+ val = os.path.expanduser(val)
+ val = subst_vars(val, self.config_vars)
+ setattr(self, attr, val)
+
+ def expand_basedirs(self):
+ """Calls `os.path.expanduser` on install_base, install_platbase and
+ root."""
+ self._expand_attrs(['install_base', 'install_platbase', 'root'])
+
+ def expand_dirs(self):
+ """Calls `os.path.expanduser` on install dirs."""
dirs = [
'install_purelib',
'install_platlib',
@@ -409,7 +409,7 @@ class easy_install(Command):
'install_data',
]
self._expand_attrs(dirs)
-
+
def run(self, show_deprecation=True):
if show_deprecation:
self.announce(
@@ -417,228 +417,228 @@ class easy_install(Command):
"and will be removed in a future version."
, log.WARN,
)
- if self.verbose != self.distribution.verbose:
- log.set_verbosity(self.verbose)
- try:
- for spec in self.args:
- self.easy_install(spec, not self.no_deps)
- if self.record:
- outputs = self.outputs
- if self.root: # strip any package prefix
- root_len = len(self.root)
- for counter in range(len(outputs)):
- outputs[counter] = outputs[counter][root_len:]
- from distutils import file_util
-
- self.execute(
- file_util.write_file, (self.record, outputs),
- "writing list of installed files to '%s'" %
- self.record
- )
- self.warn_deprecated_options()
- finally:
- log.set_verbosity(self.distribution.verbose)
-
- def pseudo_tempname(self):
- """Return a pseudo-tempname base in the install directory.
- This code is intentionally naive; if a malicious party can write to
- the target directory you're already in deep doodoo.
- """
- try:
- pid = os.getpid()
+ if self.verbose != self.distribution.verbose:
+ log.set_verbosity(self.verbose)
+ try:
+ for spec in self.args:
+ self.easy_install(spec, not self.no_deps)
+ if self.record:
+ outputs = self.outputs
+ if self.root: # strip any package prefix
+ root_len = len(self.root)
+ for counter in range(len(outputs)):
+ outputs[counter] = outputs[counter][root_len:]
+ from distutils import file_util
+
+ self.execute(
+ file_util.write_file, (self.record, outputs),
+ "writing list of installed files to '%s'" %
+ self.record
+ )
+ self.warn_deprecated_options()
+ finally:
+ log.set_verbosity(self.distribution.verbose)
+
+ def pseudo_tempname(self):
+ """Return a pseudo-tempname base in the install directory.
+ This code is intentionally naive; if a malicious party can write to
+ the target directory you're already in deep doodoo.
+ """
+ try:
+ pid = os.getpid()
except Exception:
- pid = random.randint(0, sys.maxsize)
- return os.path.join(self.install_dir, "test-easy-install-%s" % pid)
-
- def warn_deprecated_options(self):
- pass
-
- def check_site_dir(self):
- """Verify that self.install_dir is .pth-capable dir, if needed"""
-
- instdir = normalize_path(self.install_dir)
- pth_file = os.path.join(instdir, 'easy-install.pth')
-
- # Is it a configured, PYTHONPATH, implicit, or explicit site dir?
- is_site_dir = instdir in self.all_site_dirs
-
- if not is_site_dir and not self.multi_version:
- # No? Then directly test whether it does .pth file processing
- is_site_dir = self.check_pth_processing()
- else:
- # make sure we can write to target dir
- testfile = self.pseudo_tempname() + '.write-test'
- test_exists = os.path.exists(testfile)
- try:
- if test_exists:
- os.unlink(testfile)
- open(testfile, 'w').close()
- os.unlink(testfile)
- except (OSError, IOError):
- self.cant_write_to_target()
-
- if not is_site_dir and not self.multi_version:
- # Can't install non-multi to non-site dir
- raise DistutilsError(self.no_default_version_msg())
-
- if is_site_dir:
- if self.pth_file is None:
- self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
- else:
- self.pth_file = None
-
+ pid = random.randint(0, sys.maxsize)
+ return os.path.join(self.install_dir, "test-easy-install-%s" % pid)
+
+ def warn_deprecated_options(self):
+ pass
+
+ def check_site_dir(self):
+ """Verify that self.install_dir is .pth-capable dir, if needed"""
+
+ instdir = normalize_path(self.install_dir)
+ pth_file = os.path.join(instdir, 'easy-install.pth')
+
+ # Is it a configured, PYTHONPATH, implicit, or explicit site dir?
+ is_site_dir = instdir in self.all_site_dirs
+
+ if not is_site_dir and not self.multi_version:
+ # No? Then directly test whether it does .pth file processing
+ is_site_dir = self.check_pth_processing()
+ else:
+ # make sure we can write to target dir
+ testfile = self.pseudo_tempname() + '.write-test'
+ test_exists = os.path.exists(testfile)
+ try:
+ if test_exists:
+ os.unlink(testfile)
+ open(testfile, 'w').close()
+ os.unlink(testfile)
+ except (OSError, IOError):
+ self.cant_write_to_target()
+
+ if not is_site_dir and not self.multi_version:
+ # Can't install non-multi to non-site dir
+ raise DistutilsError(self.no_default_version_msg())
+
+ if is_site_dir:
+ if self.pth_file is None:
+ self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
+ else:
+ self.pth_file = None
+
if instdir not in map(normalize_path, _pythonpath()):
- # only PYTHONPATH dirs need a site.py, so pretend it's there
- self.sitepy_installed = True
- elif self.multi_version and not os.path.exists(pth_file):
- self.sitepy_installed = True # don't need site.py in this case
- self.pth_file = None # and don't create a .pth file
- self.install_dir = instdir
-
- __cant_write_msg = textwrap.dedent("""
- can't create or remove files in install directory
-
- The following error occurred while trying to add or remove files in the
- installation directory:
-
- %s
-
- The installation directory you specified (via --install-dir, --prefix, or
- the distutils default setting) was:
-
- %s
- """).lstrip()
-
- __not_exists_id = textwrap.dedent("""
- This directory does not currently exist. Please create it and try again, or
- choose a different installation directory (using the -d or --install-dir
- option).
- """).lstrip()
-
- __access_msg = textwrap.dedent("""
- Perhaps your account does not have write access to this directory? If the
- installation directory is a system-owned directory, you may need to sign in
- as the administrator or "root" account. If you do not have administrative
- access to this machine, you may wish to choose a different installation
- directory, preferably one that is listed in your PYTHONPATH environment
- variable.
-
- For information on other options, you may wish to consult the
- documentation at:
-
+ # only PYTHONPATH dirs need a site.py, so pretend it's there
+ self.sitepy_installed = True
+ elif self.multi_version and not os.path.exists(pth_file):
+ self.sitepy_installed = True # don't need site.py in this case
+ self.pth_file = None # and don't create a .pth file
+ self.install_dir = instdir
+
+ __cant_write_msg = textwrap.dedent("""
+ can't create or remove files in install directory
+
+ The following error occurred while trying to add or remove files in the
+ installation directory:
+
+ %s
+
+ The installation directory you specified (via --install-dir, --prefix, or
+ the distutils default setting) was:
+
+ %s
+ """).lstrip()
+
+ __not_exists_id = textwrap.dedent("""
+ This directory does not currently exist. Please create it and try again, or
+ choose a different installation directory (using the -d or --install-dir
+ option).
+ """).lstrip()
+
+ __access_msg = textwrap.dedent("""
+ Perhaps your account does not have write access to this directory? If the
+ installation directory is a system-owned directory, you may need to sign in
+ as the administrator or "root" account. If you do not have administrative
+ access to this machine, you may wish to choose a different installation
+ directory, preferably one that is listed in your PYTHONPATH environment
+ variable.
+
+ For information on other options, you may wish to consult the
+ documentation at:
+
https://setuptools.readthedocs.io/en/latest/easy_install.html
-
- Please make the appropriate changes for your system and try again.
- """).lstrip()
-
- def cant_write_to_target(self):
- msg = self.__cant_write_msg % (sys.exc_info()[1], self.install_dir,)
-
- if not os.path.exists(self.install_dir):
- msg += '\n' + self.__not_exists_id
- else:
- msg += '\n' + self.__access_msg
- raise DistutilsError(msg)
-
- def check_pth_processing(self):
- """Empirically verify whether .pth files are supported in inst. dir"""
- instdir = self.install_dir
- log.info("Checking .pth file support in %s", instdir)
- pth_file = self.pseudo_tempname() + ".pth"
- ok_file = pth_file + '.ok'
- ok_exists = os.path.exists(ok_file)
+
+ Please make the appropriate changes for your system and try again.
+ """).lstrip()
+
+ def cant_write_to_target(self):
+ msg = self.__cant_write_msg % (sys.exc_info()[1], self.install_dir,)
+
+ if not os.path.exists(self.install_dir):
+ msg += '\n' + self.__not_exists_id
+ else:
+ msg += '\n' + self.__access_msg
+ raise DistutilsError(msg)
+
+ def check_pth_processing(self):
+ """Empirically verify whether .pth files are supported in inst. dir"""
+ instdir = self.install_dir
+ log.info("Checking .pth file support in %s", instdir)
+ pth_file = self.pseudo_tempname() + ".pth"
+ ok_file = pth_file + '.ok'
+ ok_exists = os.path.exists(ok_file)
tmpl = _one_liner("""
import os
f = open({ok_file!r}, 'w')
f.write('OK')
f.close()
""") + '\n'
- try:
- if ok_exists:
- os.unlink(ok_file)
- dirname = os.path.dirname(ok_file)
+ try:
+ if ok_exists:
+ os.unlink(ok_file)
+ dirname = os.path.dirname(ok_file)
pkg_resources.py31compat.makedirs(dirname, exist_ok=True)
- f = open(pth_file, 'w')
- except (OSError, IOError):
- self.cant_write_to_target()
- else:
- try:
+ f = open(pth_file, 'w')
+ except (OSError, IOError):
+ self.cant_write_to_target()
+ else:
+ try:
f.write(tmpl.format(**locals()))
- f.close()
- f = None
- executable = sys.executable
- if os.name == 'nt':
- dirname, basename = os.path.split(executable)
- alt = os.path.join(dirname, 'pythonw.exe')
+ f.close()
+ f = None
+ executable = sys.executable
+ if os.name == 'nt':
+ dirname, basename = os.path.split(executable)
+ alt = os.path.join(dirname, 'pythonw.exe')
use_alt = (
basename.lower() == 'python.exe' and
os.path.exists(alt)
)
if use_alt:
- # use pythonw.exe to avoid opening a console window
- executable = alt
-
- from distutils.spawn import spawn
-
- spawn([executable, '-E', '-c', 'pass'], 0)
-
- if os.path.exists(ok_file):
- log.info(
- "TEST PASSED: %s appears to support .pth files",
- instdir
- )
- return True
- finally:
- if f:
- f.close()
- if os.path.exists(ok_file):
- os.unlink(ok_file)
- if os.path.exists(pth_file):
- os.unlink(pth_file)
- if not self.multi_version:
- log.warn("TEST FAILED: %s does NOT support .pth files", instdir)
- return False
-
- def install_egg_scripts(self, dist):
- """Write all the scripts for `dist`, unless scripts are excluded"""
- if not self.exclude_scripts and dist.metadata_isdir('scripts'):
- for script_name in dist.metadata_listdir('scripts'):
- if dist.metadata_isdir('scripts/' + script_name):
- # The "script" is a directory, likely a Python 3
- # __pycache__ directory, so skip it.
- continue
- self.install_script(
- dist, script_name,
- dist.get_metadata('scripts/' + script_name)
- )
- self.install_wrapper_scripts(dist)
-
- def add_output(self, path):
- if os.path.isdir(path):
- for base, dirs, files in os.walk(path):
- for filename in files:
- self.outputs.append(os.path.join(base, filename))
- else:
- self.outputs.append(path)
-
- def not_editable(self, spec):
- if self.editable:
- raise DistutilsArgError(
- "Invalid argument %r: you can't use filenames or URLs "
- "with --editable (except via the --find-links option)."
- % (spec,)
- )
-
- def check_editable(self, spec):
- if not self.editable:
- return
-
- if os.path.exists(os.path.join(self.build_directory, spec.key)):
- raise DistutilsArgError(
- "%r already exists in %s; can't do a checkout there" %
- (spec.key, self.build_directory)
- )
-
+ # use pythonw.exe to avoid opening a console window
+ executable = alt
+
+ from distutils.spawn import spawn
+
+ spawn([executable, '-E', '-c', 'pass'], 0)
+
+ if os.path.exists(ok_file):
+ log.info(
+ "TEST PASSED: %s appears to support .pth files",
+ instdir
+ )
+ return True
+ finally:
+ if f:
+ f.close()
+ if os.path.exists(ok_file):
+ os.unlink(ok_file)
+ if os.path.exists(pth_file):
+ os.unlink(pth_file)
+ if not self.multi_version:
+ log.warn("TEST FAILED: %s does NOT support .pth files", instdir)
+ return False
+
+ def install_egg_scripts(self, dist):
+ """Write all the scripts for `dist`, unless scripts are excluded"""
+ if not self.exclude_scripts and dist.metadata_isdir('scripts'):
+ for script_name in dist.metadata_listdir('scripts'):
+ if dist.metadata_isdir('scripts/' + script_name):
+ # The "script" is a directory, likely a Python 3
+ # __pycache__ directory, so skip it.
+ continue
+ self.install_script(
+ dist, script_name,
+ dist.get_metadata('scripts/' + script_name)
+ )
+ self.install_wrapper_scripts(dist)
+
+ def add_output(self, path):
+ if os.path.isdir(path):
+ for base, dirs, files in os.walk(path):
+ for filename in files:
+ self.outputs.append(os.path.join(base, filename))
+ else:
+ self.outputs.append(path)
+
+ def not_editable(self, spec):
+ if self.editable:
+ raise DistutilsArgError(
+ "Invalid argument %r: you can't use filenames or URLs "
+ "with --editable (except via the --find-links option)."
+ % (spec,)
+ )
+
+ def check_editable(self, spec):
+ if not self.editable:
+ return
+
+ if os.path.exists(os.path.join(self.build_directory, spec.key)):
+ raise DistutilsArgError(
+ "%r already exists in %s; can't do a checkout there" %
+ (spec.key, self.build_directory)
+ )
+
@contextlib.contextmanager
def _tmpdir(self):
tmpdir = tempfile.mkdtemp(prefix=u"easy_install-")
@@ -648,296 +648,296 @@ class easy_install(Command):
finally:
os.path.exists(tmpdir) and rmtree(rmtree_safe(tmpdir))
- def easy_install(self, spec, deps=False):
- if not self.editable:
- self.install_site_py()
-
+ def easy_install(self, spec, deps=False):
+ if not self.editable:
+ self.install_site_py()
+
with self._tmpdir() as tmpdir:
- if not isinstance(spec, Requirement):
- if URL_SCHEME(spec):
- # It's a url, download it to tmpdir and process
- self.not_editable(spec)
+ if not isinstance(spec, Requirement):
+ if URL_SCHEME(spec):
+ # It's a url, download it to tmpdir and process
+ self.not_editable(spec)
dl = self.package_index.download(spec, tmpdir)
return self.install_item(None, dl, tmpdir, deps, True)
-
- elif os.path.exists(spec):
- # Existing file or directory, just process it directly
- self.not_editable(spec)
- return self.install_item(None, spec, tmpdir, deps, True)
- else:
- spec = parse_requirement_arg(spec)
-
- self.check_editable(spec)
- dist = self.package_index.fetch_distribution(
- spec, tmpdir, self.upgrade, self.editable,
- not self.always_copy, self.local_index
- )
- if dist is None:
- msg = "Could not find suitable distribution for %r" % spec
- if self.always_copy:
- msg += " (--always-copy skips system and development eggs)"
- raise DistutilsError(msg)
- elif dist.precedence == DEVELOP_DIST:
- # .egg-info dists don't need installing, just process deps
- self.process_distribution(spec, dist, deps, "Using")
- return dist
- else:
- return self.install_item(spec, dist.location, tmpdir, deps)
-
- def install_item(self, spec, download, tmpdir, deps, install_needed=False):
-
- # Installation is also needed if file in tmpdir or is not an egg
- install_needed = install_needed or self.always_copy
- install_needed = install_needed or os.path.dirname(download) == tmpdir
- install_needed = install_needed or not download.endswith('.egg')
- install_needed = install_needed or (
- self.always_copy_from is not None and
- os.path.dirname(normalize_path(download)) ==
- normalize_path(self.always_copy_from)
- )
-
- if spec and not install_needed:
- # at this point, we know it's a local .egg, we just don't know if
- # it's already installed.
- for dist in self.local_index[spec.project_name]:
- if dist.location == download:
- break
- else:
- install_needed = True # it's not in the local index
-
- log.info("Processing %s", os.path.basename(download))
-
- if install_needed:
- dists = self.install_eggs(spec, download, tmpdir)
- for dist in dists:
- self.process_distribution(spec, dist, deps)
- else:
- dists = [self.egg_distribution(download)]
- self.process_distribution(spec, dists[0], deps, "Using")
-
- if spec is not None:
- for dist in dists:
- if dist in spec:
- return dist
-
- def select_scheme(self, name):
- """Sets the install directories by applying the install schemes."""
- # it's the caller's problem if they supply a bad name!
- scheme = INSTALL_SCHEMES[name]
- for key in SCHEME_KEYS:
- attrname = 'install_' + key
- if getattr(self, attrname) is None:
- setattr(self, attrname, scheme[key])
-
- def process_distribution(self, requirement, dist, deps=True, *info):
- self.update_pth(dist)
- self.package_index.add(dist)
- if dist in self.local_index[dist.key]:
- self.local_index.remove(dist)
- self.local_index.add(dist)
- self.install_egg_scripts(dist)
- self.installed_projects[dist.key] = dist
- log.info(self.installation_report(requirement, dist, *info))
- if (dist.has_metadata('dependency_links.txt') and
- not self.no_find_links):
- self.package_index.add_find_links(
- dist.get_metadata_lines('dependency_links.txt')
- )
- if not deps and not self.always_copy:
- return
- elif requirement is not None and dist.key != requirement.key:
- log.warn("Skipping dependencies for %s", dist)
- return # XXX this is not the distribution we were looking for
- elif requirement is None or dist not in requirement:
- # if we wound up with a different version, resolve what we've got
- distreq = dist.as_requirement()
+
+ elif os.path.exists(spec):
+ # Existing file or directory, just process it directly
+ self.not_editable(spec)
+ return self.install_item(None, spec, tmpdir, deps, True)
+ else:
+ spec = parse_requirement_arg(spec)
+
+ self.check_editable(spec)
+ dist = self.package_index.fetch_distribution(
+ spec, tmpdir, self.upgrade, self.editable,
+ not self.always_copy, self.local_index
+ )
+ if dist is None:
+ msg = "Could not find suitable distribution for %r" % spec
+ if self.always_copy:
+ msg += " (--always-copy skips system and development eggs)"
+ raise DistutilsError(msg)
+ elif dist.precedence == DEVELOP_DIST:
+ # .egg-info dists don't need installing, just process deps
+ self.process_distribution(spec, dist, deps, "Using")
+ return dist
+ else:
+ return self.install_item(spec, dist.location, tmpdir, deps)
+
+ def install_item(self, spec, download, tmpdir, deps, install_needed=False):
+
+ # Installation is also needed if file in tmpdir or is not an egg
+ install_needed = install_needed or self.always_copy
+ install_needed = install_needed or os.path.dirname(download) == tmpdir
+ install_needed = install_needed or not download.endswith('.egg')
+ install_needed = install_needed or (
+ self.always_copy_from is not None and
+ os.path.dirname(normalize_path(download)) ==
+ normalize_path(self.always_copy_from)
+ )
+
+ if spec and not install_needed:
+ # at this point, we know it's a local .egg, we just don't know if
+ # it's already installed.
+ for dist in self.local_index[spec.project_name]:
+ if dist.location == download:
+ break
+ else:
+ install_needed = True # it's not in the local index
+
+ log.info("Processing %s", os.path.basename(download))
+
+ if install_needed:
+ dists = self.install_eggs(spec, download, tmpdir)
+ for dist in dists:
+ self.process_distribution(spec, dist, deps)
+ else:
+ dists = [self.egg_distribution(download)]
+ self.process_distribution(spec, dists[0], deps, "Using")
+
+ if spec is not None:
+ for dist in dists:
+ if dist in spec:
+ return dist
+
+ def select_scheme(self, name):
+ """Sets the install directories by applying the install schemes."""
+ # it's the caller's problem if they supply a bad name!
+ scheme = INSTALL_SCHEMES[name]
+ for key in SCHEME_KEYS:
+ attrname = 'install_' + key
+ if getattr(self, attrname) is None:
+ setattr(self, attrname, scheme[key])
+
+ def process_distribution(self, requirement, dist, deps=True, *info):
+ self.update_pth(dist)
+ self.package_index.add(dist)
+ if dist in self.local_index[dist.key]:
+ self.local_index.remove(dist)
+ self.local_index.add(dist)
+ self.install_egg_scripts(dist)
+ self.installed_projects[dist.key] = dist
+ log.info(self.installation_report(requirement, dist, *info))
+ if (dist.has_metadata('dependency_links.txt') and
+ not self.no_find_links):
+ self.package_index.add_find_links(
+ dist.get_metadata_lines('dependency_links.txt')
+ )
+ if not deps and not self.always_copy:
+ return
+ elif requirement is not None and dist.key != requirement.key:
+ log.warn("Skipping dependencies for %s", dist)
+ return # XXX this is not the distribution we were looking for
+ elif requirement is None or dist not in requirement:
+ # if we wound up with a different version, resolve what we've got
+ distreq = dist.as_requirement()
requirement = Requirement(str(distreq))
- log.info("Processing dependencies for %s", requirement)
- try:
- distros = WorkingSet([]).resolve(
- [requirement], self.local_index, self.easy_install
- )
- except DistributionNotFound as e:
- raise DistutilsError(str(e))
- except VersionConflict as e:
- raise DistutilsError(e.report())
- if self.always_copy or self.always_copy_from:
- # Force all the relevant distros to be copied or activated
- for dist in distros:
- if dist.key not in self.installed_projects:
- self.easy_install(dist.as_requirement())
- log.info("Finished processing dependencies for %s", requirement)
-
- def should_unzip(self, dist):
- if self.zip_ok is not None:
- return not self.zip_ok
- if dist.has_metadata('not-zip-safe'):
- return True
- if not dist.has_metadata('zip-safe'):
- return True
- return False
-
- def maybe_move(self, spec, dist_filename, setup_base):
- dst = os.path.join(self.build_directory, spec.key)
- if os.path.exists(dst):
+ log.info("Processing dependencies for %s", requirement)
+ try:
+ distros = WorkingSet([]).resolve(
+ [requirement], self.local_index, self.easy_install
+ )
+ except DistributionNotFound as e:
+ raise DistutilsError(str(e))
+ except VersionConflict as e:
+ raise DistutilsError(e.report())
+ if self.always_copy or self.always_copy_from:
+ # Force all the relevant distros to be copied or activated
+ for dist in distros:
+ if dist.key not in self.installed_projects:
+ self.easy_install(dist.as_requirement())
+ log.info("Finished processing dependencies for %s", requirement)
+
+ def should_unzip(self, dist):
+ if self.zip_ok is not None:
+ return not self.zip_ok
+ if dist.has_metadata('not-zip-safe'):
+ return True
+ if not dist.has_metadata('zip-safe'):
+ return True
+ return False
+
+ def maybe_move(self, spec, dist_filename, setup_base):
+ dst = os.path.join(self.build_directory, spec.key)
+ if os.path.exists(dst):
msg = (
"%r already exists in %s; build directory %s will not be kept"
)
- log.warn(msg, spec.key, self.build_directory, setup_base)
- return setup_base
- if os.path.isdir(dist_filename):
- setup_base = dist_filename
- else:
- if os.path.dirname(dist_filename) == setup_base:
- os.unlink(dist_filename) # get it out of the tmp dir
- contents = os.listdir(setup_base)
- if len(contents) == 1:
- dist_filename = os.path.join(setup_base, contents[0])
- if os.path.isdir(dist_filename):
- # if the only thing there is a directory, move it instead
- setup_base = dist_filename
- ensure_directory(dst)
- shutil.move(setup_base, dst)
- return dst
-
- def install_wrapper_scripts(self, dist):
- if self.exclude_scripts:
- return
- for args in ScriptWriter.best().get_args(dist):
- self.write_script(*args)
-
- def install_script(self, dist, script_name, script_text, dev_path=None):
- """Generate a legacy script wrapper and install it"""
- spec = str(dist.as_requirement())
- is_script = is_python_script(script_text, script_name)
-
- if is_script:
- body = self._load_template(dev_path) % locals()
- script_text = ScriptWriter.get_header(script_text) + body
+ log.warn(msg, spec.key, self.build_directory, setup_base)
+ return setup_base
+ if os.path.isdir(dist_filename):
+ setup_base = dist_filename
+ else:
+ if os.path.dirname(dist_filename) == setup_base:
+ os.unlink(dist_filename) # get it out of the tmp dir
+ contents = os.listdir(setup_base)
+ if len(contents) == 1:
+ dist_filename = os.path.join(setup_base, contents[0])
+ if os.path.isdir(dist_filename):
+ # if the only thing there is a directory, move it instead
+ setup_base = dist_filename
+ ensure_directory(dst)
+ shutil.move(setup_base, dst)
+ return dst
+
+ def install_wrapper_scripts(self, dist):
+ if self.exclude_scripts:
+ return
+ for args in ScriptWriter.best().get_args(dist):
+ self.write_script(*args)
+
+ def install_script(self, dist, script_name, script_text, dev_path=None):
+ """Generate a legacy script wrapper and install it"""
+ spec = str(dist.as_requirement())
+ is_script = is_python_script(script_text, script_name)
+
+ if is_script:
+ body = self._load_template(dev_path) % locals()
+ script_text = ScriptWriter.get_header(script_text) + body
self.write_script(script_name, _to_bytes(script_text), 'b')
-
- @staticmethod
- def _load_template(dev_path):
- """
- There are a couple of template scripts in the package. This
- function loads one of them and prepares it for use.
- """
+
+ @staticmethod
+ def _load_template(dev_path):
+ """
+ There are a couple of template scripts in the package. This
+ function loads one of them and prepares it for use.
+ """
# See https://github.com/pypa/setuptools/issues/134 for info
- # on script file naming and downstream issues with SVR4
- name = 'script.tmpl'
- if dev_path:
- name = name.replace('.tmpl', ' (dev).tmpl')
-
- raw_bytes = resource_string('setuptools', name)
- return raw_bytes.decode('utf-8')
-
- def write_script(self, script_name, contents, mode="t", blockers=()):
- """Write an executable file to the scripts directory"""
- self.delete_blockers( # clean up old .py/.pyw w/o a script
- [os.path.join(self.script_dir, x) for x in blockers]
- )
- log.info("Installing %s script to %s", script_name, self.script_dir)
- target = os.path.join(self.script_dir, script_name)
- self.add_output(target)
-
+ # on script file naming and downstream issues with SVR4
+ name = 'script.tmpl'
+ if dev_path:
+ name = name.replace('.tmpl', ' (dev).tmpl')
+
+ raw_bytes = resource_string('setuptools', name)
+ return raw_bytes.decode('utf-8')
+
+ def write_script(self, script_name, contents, mode="t", blockers=()):
+ """Write an executable file to the scripts directory"""
+ self.delete_blockers( # clean up old .py/.pyw w/o a script
+ [os.path.join(self.script_dir, x) for x in blockers]
+ )
+ log.info("Installing %s script to %s", script_name, self.script_dir)
+ target = os.path.join(self.script_dir, script_name)
+ self.add_output(target)
+
if self.dry_run:
return
- mask = current_umask()
+ mask = current_umask()
ensure_directory(target)
if os.path.exists(target):
os.unlink(target)
with open(target, "w" + mode) as f:
f.write(contents)
chmod(target, 0o777 - mask)
-
- def install_eggs(self, spec, dist_filename, tmpdir):
- # .egg dirs or files are already built, so just return them
- if dist_filename.lower().endswith('.egg'):
- return [self.install_egg(dist_filename, tmpdir)]
- elif dist_filename.lower().endswith('.exe'):
- return [self.install_exe(dist_filename, tmpdir)]
+
+ def install_eggs(self, spec, dist_filename, tmpdir):
+ # .egg dirs or files are already built, so just return them
+ if dist_filename.lower().endswith('.egg'):
+ return [self.install_egg(dist_filename, tmpdir)]
+ elif dist_filename.lower().endswith('.exe'):
+ return [self.install_exe(dist_filename, tmpdir)]
elif dist_filename.lower().endswith('.whl'):
return [self.install_wheel(dist_filename, tmpdir)]
-
- # Anything else, try to extract and build
- setup_base = tmpdir
- if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
- unpack_archive(dist_filename, tmpdir, self.unpack_progress)
- elif os.path.isdir(dist_filename):
- setup_base = os.path.abspath(dist_filename)
-
- if (setup_base.startswith(tmpdir) # something we downloaded
- and self.build_directory and spec is not None):
- setup_base = self.maybe_move(spec, dist_filename, setup_base)
-
- # Find the setup.py file
- setup_script = os.path.join(setup_base, 'setup.py')
-
- if not os.path.exists(setup_script):
- setups = glob(os.path.join(setup_base, '*', 'setup.py'))
- if not setups:
- raise DistutilsError(
- "Couldn't find a setup script in %s" %
- os.path.abspath(dist_filename)
- )
- if len(setups) > 1:
- raise DistutilsError(
- "Multiple setup scripts in %s" %
- os.path.abspath(dist_filename)
- )
- setup_script = setups[0]
-
- # Now run it, and return the result
- if self.editable:
- log.info(self.report_editable(spec, setup_script))
- return []
- else:
- return self.build_and_install(setup_script, setup_base)
-
- def egg_distribution(self, egg_path):
- if os.path.isdir(egg_path):
- metadata = PathMetadata(egg_path, os.path.join(egg_path,
- 'EGG-INFO'))
- else:
- metadata = EggMetadata(zipimport.zipimporter(egg_path))
- return Distribution.from_filename(egg_path, metadata=metadata)
-
- def install_egg(self, egg_path, tmpdir):
+
+ # Anything else, try to extract and build
+ setup_base = tmpdir
+ if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
+ unpack_archive(dist_filename, tmpdir, self.unpack_progress)
+ elif os.path.isdir(dist_filename):
+ setup_base = os.path.abspath(dist_filename)
+
+ if (setup_base.startswith(tmpdir) # something we downloaded
+ and self.build_directory and spec is not None):
+ setup_base = self.maybe_move(spec, dist_filename, setup_base)
+
+ # Find the setup.py file
+ setup_script = os.path.join(setup_base, 'setup.py')
+
+ if not os.path.exists(setup_script):
+ setups = glob(os.path.join(setup_base, '*', 'setup.py'))
+ if not setups:
+ raise DistutilsError(
+ "Couldn't find a setup script in %s" %
+ os.path.abspath(dist_filename)
+ )
+ if len(setups) > 1:
+ raise DistutilsError(
+ "Multiple setup scripts in %s" %
+ os.path.abspath(dist_filename)
+ )
+ setup_script = setups[0]
+
+ # Now run it, and return the result
+ if self.editable:
+ log.info(self.report_editable(spec, setup_script))
+ return []
+ else:
+ return self.build_and_install(setup_script, setup_base)
+
+ def egg_distribution(self, egg_path):
+ if os.path.isdir(egg_path):
+ metadata = PathMetadata(egg_path, os.path.join(egg_path,
+ 'EGG-INFO'))
+ else:
+ metadata = EggMetadata(zipimport.zipimporter(egg_path))
+ return Distribution.from_filename(egg_path, metadata=metadata)
+
+ def install_egg(self, egg_path, tmpdir):
destination = os.path.join(
self.install_dir,
os.path.basename(egg_path),
)
- destination = os.path.abspath(destination)
- if not self.dry_run:
- ensure_directory(destination)
-
- dist = self.egg_distribution(egg_path)
- if not samefile(egg_path, destination):
- if os.path.isdir(destination) and not os.path.islink(destination):
- dir_util.remove_tree(destination, dry_run=self.dry_run)
- elif os.path.exists(destination):
+ destination = os.path.abspath(destination)
+ if not self.dry_run:
+ ensure_directory(destination)
+
+ dist = self.egg_distribution(egg_path)
+ if not samefile(egg_path, destination):
+ if os.path.isdir(destination) and not os.path.islink(destination):
+ dir_util.remove_tree(destination, dry_run=self.dry_run)
+ elif os.path.exists(destination):
self.execute(
os.unlink,
(destination,),
"Removing " + destination,
)
- try:
- new_dist_is_zipped = False
- if os.path.isdir(egg_path):
- if egg_path.startswith(tmpdir):
- f, m = shutil.move, "Moving"
- else:
- f, m = shutil.copytree, "Copying"
- elif self.should_unzip(dist):
- self.mkpath(destination)
- f, m = self.unpack_and_compile, "Extracting"
- else:
- new_dist_is_zipped = True
- if egg_path.startswith(tmpdir):
- f, m = shutil.move, "Moving"
- else:
- f, m = shutil.copy2, "Copying"
+ try:
+ new_dist_is_zipped = False
+ if os.path.isdir(egg_path):
+ if egg_path.startswith(tmpdir):
+ f, m = shutil.move, "Moving"
+ else:
+ f, m = shutil.copytree, "Copying"
+ elif self.should_unzip(dist):
+ self.mkpath(destination)
+ f, m = self.unpack_and_compile, "Extracting"
+ else:
+ new_dist_is_zipped = True
+ if egg_path.startswith(tmpdir):
+ f, m = shutil.move, "Moving"
+ else:
+ f, m = shutil.copy2, "Copying"
self.execute(
f,
(egg_path, destination),
@@ -951,110 +951,110 @@ class easy_install(Command):
fix_zipimporter_caches=new_dist_is_zipped,
)
except Exception:
- update_dist_caches(destination, fix_zipimporter_caches=False)
- raise
-
- self.add_output(destination)
- return self.egg_distribution(destination)
-
- def install_exe(self, dist_filename, tmpdir):
- # See if it's valid, get data
- cfg = extract_wininst_cfg(dist_filename)
- if cfg is None:
- raise DistutilsError(
- "%s is not a valid distutils Windows .exe" % dist_filename
- )
- # Create a dummy distribution object until we build the real distro
- dist = Distribution(
- None,
- project_name=cfg.get('metadata', 'name'),
- version=cfg.get('metadata', 'version'), platform=get_platform(),
- )
-
- # Convert the .exe to an unpacked egg
+ update_dist_caches(destination, fix_zipimporter_caches=False)
+ raise
+
+ self.add_output(destination)
+ return self.egg_distribution(destination)
+
+ def install_exe(self, dist_filename, tmpdir):
+ # See if it's valid, get data
+ cfg = extract_wininst_cfg(dist_filename)
+ if cfg is None:
+ raise DistutilsError(
+ "%s is not a valid distutils Windows .exe" % dist_filename
+ )
+ # Create a dummy distribution object until we build the real distro
+ dist = Distribution(
+ None,
+ project_name=cfg.get('metadata', 'name'),
+ version=cfg.get('metadata', 'version'), platform=get_platform(),
+ )
+
+ # Convert the .exe to an unpacked egg
egg_path = os.path.join(tmpdir, dist.egg_name() + '.egg')
dist.location = egg_path
- egg_tmp = egg_path + '.tmp'
- _egg_info = os.path.join(egg_tmp, 'EGG-INFO')
- pkg_inf = os.path.join(_egg_info, 'PKG-INFO')
- ensure_directory(pkg_inf) # make sure EGG-INFO dir exists
- dist._provider = PathMetadata(egg_tmp, _egg_info) # XXX
- self.exe_to_egg(dist_filename, egg_tmp)
-
- # Write EGG-INFO/PKG-INFO
- if not os.path.exists(pkg_inf):
- f = open(pkg_inf, 'w')
- f.write('Metadata-Version: 1.0\n')
- for k, v in cfg.items('metadata'):
- if k != 'target_version':
- f.write('%s: %s\n' % (k.replace('_', '-').title(), v))
- f.close()
- script_dir = os.path.join(_egg_info, 'scripts')
- # delete entry-point scripts to avoid duping
+ egg_tmp = egg_path + '.tmp'
+ _egg_info = os.path.join(egg_tmp, 'EGG-INFO')
+ pkg_inf = os.path.join(_egg_info, 'PKG-INFO')
+ ensure_directory(pkg_inf) # make sure EGG-INFO dir exists
+ dist._provider = PathMetadata(egg_tmp, _egg_info) # XXX
+ self.exe_to_egg(dist_filename, egg_tmp)
+
+ # Write EGG-INFO/PKG-INFO
+ if not os.path.exists(pkg_inf):
+ f = open(pkg_inf, 'w')
+ f.write('Metadata-Version: 1.0\n')
+ for k, v in cfg.items('metadata'):
+ if k != 'target_version':
+ f.write('%s: %s\n' % (k.replace('_', '-').title(), v))
+ f.close()
+ script_dir = os.path.join(_egg_info, 'scripts')
+ # delete entry-point scripts to avoid duping
self.delete_blockers([
os.path.join(script_dir, args[0])
for args in ScriptWriter.get_args(dist)
])
- # Build .egg file from tmpdir
- bdist_egg.make_zipfile(
+ # Build .egg file from tmpdir
+ bdist_egg.make_zipfile(
egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run,
- )
- # install the .egg
- return self.install_egg(egg_path, tmpdir)
-
- def exe_to_egg(self, dist_filename, egg_tmp):
- """Extract a bdist_wininst to the directories an egg would use"""
- # Check for .pth file and set up prefix translations
- prefixes = get_exe_prefixes(dist_filename)
- to_compile = []
- native_libs = []
- top_level = {}
-
- def process(src, dst):
- s = src.lower()
- for old, new in prefixes:
- if s.startswith(old):
- src = new + src[len(old):]
- parts = src.split('/')
- dst = os.path.join(egg_tmp, *parts)
- dl = dst.lower()
- if dl.endswith('.pyd') or dl.endswith('.dll'):
- parts[-1] = bdist_egg.strip_module(parts[-1])
- top_level[os.path.splitext(parts[0])[0]] = 1
- native_libs.append(src)
- elif dl.endswith('.py') and old != 'SCRIPTS/':
- top_level[os.path.splitext(parts[0])[0]] = 1
- to_compile.append(dst)
- return dst
- if not src.endswith('.pth'):
- log.warn("WARNING: can't process %s", src)
- return None
-
- # extract, tracking .pyd/.dll->native_libs and .py -> to_compile
- unpack_archive(dist_filename, egg_tmp, process)
- stubs = []
- for res in native_libs:
- if res.lower().endswith('.pyd'): # create stubs for .pyd's
- parts = res.split('/')
- resource = parts[-1]
- parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py'
- pyfile = os.path.join(egg_tmp, *parts)
- to_compile.append(pyfile)
- stubs.append(pyfile)
- bdist_egg.write_stub(resource, pyfile)
- self.byte_compile(to_compile) # compile .py's
- bdist_egg.write_safety_flag(
- os.path.join(egg_tmp, 'EGG-INFO'),
- bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag
-
- for name in 'top_level', 'native_libs':
- if locals()[name]:
- txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt')
- if not os.path.exists(txt):
- f = open(txt, 'w')
- f.write('\n'.join(locals()[name]) + '\n')
- f.close()
-
+ )
+ # install the .egg
+ return self.install_egg(egg_path, tmpdir)
+
+ def exe_to_egg(self, dist_filename, egg_tmp):
+ """Extract a bdist_wininst to the directories an egg would use"""
+ # Check for .pth file and set up prefix translations
+ prefixes = get_exe_prefixes(dist_filename)
+ to_compile = []
+ native_libs = []
+ top_level = {}
+
+ def process(src, dst):
+ s = src.lower()
+ for old, new in prefixes:
+ if s.startswith(old):
+ src = new + src[len(old):]
+ parts = src.split('/')
+ dst = os.path.join(egg_tmp, *parts)
+ dl = dst.lower()
+ if dl.endswith('.pyd') or dl.endswith('.dll'):
+ parts[-1] = bdist_egg.strip_module(parts[-1])
+ top_level[os.path.splitext(parts[0])[0]] = 1
+ native_libs.append(src)
+ elif dl.endswith('.py') and old != 'SCRIPTS/':
+ top_level[os.path.splitext(parts[0])[0]] = 1
+ to_compile.append(dst)
+ return dst
+ if not src.endswith('.pth'):
+ log.warn("WARNING: can't process %s", src)
+ return None
+
+ # extract, tracking .pyd/.dll->native_libs and .py -> to_compile
+ unpack_archive(dist_filename, egg_tmp, process)
+ stubs = []
+ for res in native_libs:
+ if res.lower().endswith('.pyd'): # create stubs for .pyd's
+ parts = res.split('/')
+ resource = parts[-1]
+ parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py'
+ pyfile = os.path.join(egg_tmp, *parts)
+ to_compile.append(pyfile)
+ stubs.append(pyfile)
+ bdist_egg.write_stub(resource, pyfile)
+ self.byte_compile(to_compile) # compile .py's
+ bdist_egg.write_safety_flag(
+ os.path.join(egg_tmp, 'EGG-INFO'),
+ bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag
+
+ for name in 'top_level', 'native_libs':
+ if locals()[name]:
+ txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt')
+ if not os.path.exists(txt):
+ f = open(txt, 'w')
+ f.write('\n'.join(locals()[name]) + '\n')
+ f.close()
+
def install_wheel(self, wheel_path, tmpdir):
wheel = Wheel(wheel_path)
assert wheel.is_compatible()
@@ -1084,318 +1084,318 @@ class easy_install(Command):
self.add_output(destination)
return self.egg_distribution(destination)
- __mv_warning = textwrap.dedent("""
- Because this distribution was installed --multi-version, before you can
- import modules from this package in an application, you will need to
- 'import pkg_resources' and then use a 'require()' call similar to one of
- these examples, in order to select the desired version:
-
- pkg_resources.require("%(name)s") # latest installed version
- pkg_resources.require("%(name)s==%(version)s") # this exact version
- pkg_resources.require("%(name)s>=%(version)s") # this version or higher
- """).lstrip()
-
- __id_warning = textwrap.dedent("""
- Note also that the installation directory must be on sys.path at runtime for
- this to work. (e.g. by being the application's script directory, by being on
- PYTHONPATH, or by being added to sys.path by your code.)
- """)
-
- def installation_report(self, req, dist, what="Installed"):
- """Helpful installation message for display to package users"""
- msg = "\n%(what)s %(eggloc)s%(extras)s"
- if self.multi_version and not self.no_report:
- msg += '\n' + self.__mv_warning
- if self.install_dir not in map(normalize_path, sys.path):
- msg += '\n' + self.__id_warning
-
- eggloc = dist.location
- name = dist.project_name
- version = dist.version
- extras = '' # TODO: self.report_extras(req, dist)
- return msg % locals()
-
- __editable_msg = textwrap.dedent("""
- Extracted editable version of %(spec)s to %(dirname)s
-
- If it uses setuptools in its setup script, you can activate it in
- "development" mode by going to that directory and running::
-
- %(python)s setup.py develop
-
- See the setuptools documentation for the "develop" command for more info.
- """).lstrip()
-
- def report_editable(self, spec, setup_script):
- dirname = os.path.dirname(setup_script)
- python = sys.executable
- return '\n' + self.__editable_msg % locals()
-
- def run_setup(self, setup_script, setup_base, args):
- sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
- sys.modules.setdefault('distutils.command.egg_info', egg_info)
-
- args = list(args)
- if self.verbose > 2:
- v = 'v' * (self.verbose - 1)
- args.insert(0, '-' + v)
- elif self.verbose < 2:
- args.insert(0, '-q')
- if self.dry_run:
- args.insert(0, '-n')
- log.info(
- "Running %s %s", setup_script[len(setup_base) + 1:], ' '.join(args)
- )
- try:
- run_setup(setup_script, args)
- except SystemExit as v:
- raise DistutilsError("Setup script exited with %s" % (v.args[0],))
-
- def build_and_install(self, setup_script, setup_base):
- args = ['bdist_egg', '--dist-dir']
-
- dist_dir = tempfile.mkdtemp(
- prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
- )
- try:
- self._set_fetcher_options(os.path.dirname(setup_script))
- args.append(dist_dir)
-
- self.run_setup(setup_script, setup_base, args)
- all_eggs = Environment([dist_dir])
- eggs = []
- for key in all_eggs:
- for dist in all_eggs[key]:
- eggs.append(self.install_egg(dist.location, setup_base))
- if not eggs and not self.dry_run:
- log.warn("No eggs found in %s (setup script problem?)",
- dist_dir)
- return eggs
- finally:
- rmtree(dist_dir)
- log.set_verbosity(self.verbose) # restore our log verbosity
-
- def _set_fetcher_options(self, base):
- """
- When easy_install is about to run bdist_egg on a source dist, that
- source dist might have 'setup_requires' directives, requiring
- additional fetching. Ensure the fetcher options given to easy_install
- are available to that command as well.
- """
- # find the fetch options from easy_install and write them out
- # to the setup.cfg file.
- ei_opts = self.distribution.get_option_dict('easy_install').copy()
- fetch_directives = (
+ __mv_warning = textwrap.dedent("""
+ Because this distribution was installed --multi-version, before you can
+ import modules from this package in an application, you will need to
+ 'import pkg_resources' and then use a 'require()' call similar to one of
+ these examples, in order to select the desired version:
+
+ pkg_resources.require("%(name)s") # latest installed version
+ pkg_resources.require("%(name)s==%(version)s") # this exact version
+ pkg_resources.require("%(name)s>=%(version)s") # this version or higher
+ """).lstrip()
+
+ __id_warning = textwrap.dedent("""
+ Note also that the installation directory must be on sys.path at runtime for
+ this to work. (e.g. by being the application's script directory, by being on
+ PYTHONPATH, or by being added to sys.path by your code.)
+ """)
+
+ def installation_report(self, req, dist, what="Installed"):
+ """Helpful installation message for display to package users"""
+ msg = "\n%(what)s %(eggloc)s%(extras)s"
+ if self.multi_version and not self.no_report:
+ msg += '\n' + self.__mv_warning
+ if self.install_dir not in map(normalize_path, sys.path):
+ msg += '\n' + self.__id_warning
+
+ eggloc = dist.location
+ name = dist.project_name
+ version = dist.version
+ extras = '' # TODO: self.report_extras(req, dist)
+ return msg % locals()
+
+ __editable_msg = textwrap.dedent("""
+ Extracted editable version of %(spec)s to %(dirname)s
+
+ If it uses setuptools in its setup script, you can activate it in
+ "development" mode by going to that directory and running::
+
+ %(python)s setup.py develop
+
+ See the setuptools documentation for the "develop" command for more info.
+ """).lstrip()
+
+ def report_editable(self, spec, setup_script):
+ dirname = os.path.dirname(setup_script)
+ python = sys.executable
+ return '\n' + self.__editable_msg % locals()
+
+ def run_setup(self, setup_script, setup_base, args):
+ sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
+ sys.modules.setdefault('distutils.command.egg_info', egg_info)
+
+ args = list(args)
+ if self.verbose > 2:
+ v = 'v' * (self.verbose - 1)
+ args.insert(0, '-' + v)
+ elif self.verbose < 2:
+ args.insert(0, '-q')
+ if self.dry_run:
+ args.insert(0, '-n')
+ log.info(
+ "Running %s %s", setup_script[len(setup_base) + 1:], ' '.join(args)
+ )
+ try:
+ run_setup(setup_script, args)
+ except SystemExit as v:
+ raise DistutilsError("Setup script exited with %s" % (v.args[0],))
+
+ def build_and_install(self, setup_script, setup_base):
+ args = ['bdist_egg', '--dist-dir']
+
+ dist_dir = tempfile.mkdtemp(
+ prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
+ )
+ try:
+ self._set_fetcher_options(os.path.dirname(setup_script))
+ args.append(dist_dir)
+
+ self.run_setup(setup_script, setup_base, args)
+ all_eggs = Environment([dist_dir])
+ eggs = []
+ for key in all_eggs:
+ for dist in all_eggs[key]:
+ eggs.append(self.install_egg(dist.location, setup_base))
+ if not eggs and not self.dry_run:
+ log.warn("No eggs found in %s (setup script problem?)",
+ dist_dir)
+ return eggs
+ finally:
+ rmtree(dist_dir)
+ log.set_verbosity(self.verbose) # restore our log verbosity
+
+ def _set_fetcher_options(self, base):
+ """
+ When easy_install is about to run bdist_egg on a source dist, that
+ source dist might have 'setup_requires' directives, requiring
+ additional fetching. Ensure the fetcher options given to easy_install
+ are available to that command as well.
+ """
+ # find the fetch options from easy_install and write them out
+ # to the setup.cfg file.
+ ei_opts = self.distribution.get_option_dict('easy_install').copy()
+ fetch_directives = (
'find_links', 'site_dirs', 'index_url', 'optimize', 'allow_hosts',
- )
- fetch_options = {}
- for key, val in ei_opts.items():
- if key not in fetch_directives:
- continue
- fetch_options[key.replace('_', '-')] = val[1]
- # create a settings dictionary suitable for `edit_config`
- settings = dict(easy_install=fetch_options)
- cfg_filename = os.path.join(base, 'setup.cfg')
- setopt.edit_config(cfg_filename, settings)
-
- def update_pth(self, dist):
- if self.pth_file is None:
- return
-
- for d in self.pth_file[dist.key]: # drop old entries
- if self.multi_version or d.location != dist.location:
- log.info("Removing %s from easy-install.pth file", d)
- self.pth_file.remove(d)
- if d.location in self.shadow_path:
- self.shadow_path.remove(d.location)
-
- if not self.multi_version:
- if dist.location in self.pth_file.paths:
- log.info(
- "%s is already the active version in easy-install.pth",
+ )
+ fetch_options = {}
+ for key, val in ei_opts.items():
+ if key not in fetch_directives:
+ continue
+ fetch_options[key.replace('_', '-')] = val[1]
+ # create a settings dictionary suitable for `edit_config`
+ settings = dict(easy_install=fetch_options)
+ cfg_filename = os.path.join(base, 'setup.cfg')
+ setopt.edit_config(cfg_filename, settings)
+
+ def update_pth(self, dist):
+ if self.pth_file is None:
+ return
+
+ for d in self.pth_file[dist.key]: # drop old entries
+ if self.multi_version or d.location != dist.location:
+ log.info("Removing %s from easy-install.pth file", d)
+ self.pth_file.remove(d)
+ if d.location in self.shadow_path:
+ self.shadow_path.remove(d.location)
+
+ if not self.multi_version:
+ if dist.location in self.pth_file.paths:
+ log.info(
+ "%s is already the active version in easy-install.pth",
dist,
- )
- else:
- log.info("Adding %s to easy-install.pth file", dist)
- self.pth_file.add(dist) # add new entry
- if dist.location not in self.shadow_path:
- self.shadow_path.append(dist.location)
-
- if not self.dry_run:
-
- self.pth_file.save()
-
- if dist.key == 'setuptools':
- # Ensure that setuptools itself never becomes unavailable!
- # XXX should this check for latest version?
- filename = os.path.join(self.install_dir, 'setuptools.pth')
- if os.path.islink(filename):
- os.unlink(filename)
- f = open(filename, 'wt')
- f.write(self.pth_file.make_relative(dist.location) + '\n')
- f.close()
-
- def unpack_progress(self, src, dst):
- # Progress filter for unpacking
- log.debug("Unpacking %s to %s", src, dst)
- return dst # only unpack-and-compile skips files for dry run
-
- def unpack_and_compile(self, egg_path, destination):
- to_compile = []
- to_chmod = []
-
- def pf(src, dst):
- if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
- to_compile.append(dst)
- elif dst.endswith('.dll') or dst.endswith('.so'):
- to_chmod.append(dst)
- self.unpack_progress(src, dst)
- return not self.dry_run and dst or None
-
- unpack_archive(egg_path, destination, pf)
- self.byte_compile(to_compile)
- if not self.dry_run:
- for f in to_chmod:
- mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755
- chmod(f, mode)
-
- def byte_compile(self, to_compile):
- if sys.dont_write_bytecode:
- return
-
- from distutils.util import byte_compile
-
- try:
- # try to make the byte compile messages quieter
- log.set_verbosity(self.verbose - 1)
-
- byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run)
- if self.optimize:
- byte_compile(
- to_compile, optimize=self.optimize, force=1,
+ )
+ else:
+ log.info("Adding %s to easy-install.pth file", dist)
+ self.pth_file.add(dist) # add new entry
+ if dist.location not in self.shadow_path:
+ self.shadow_path.append(dist.location)
+
+ if not self.dry_run:
+
+ self.pth_file.save()
+
+ if dist.key == 'setuptools':
+ # Ensure that setuptools itself never becomes unavailable!
+ # XXX should this check for latest version?
+ filename = os.path.join(self.install_dir, 'setuptools.pth')
+ if os.path.islink(filename):
+ os.unlink(filename)
+ f = open(filename, 'wt')
+ f.write(self.pth_file.make_relative(dist.location) + '\n')
+ f.close()
+
+ def unpack_progress(self, src, dst):
+ # Progress filter for unpacking
+ log.debug("Unpacking %s to %s", src, dst)
+ return dst # only unpack-and-compile skips files for dry run
+
+ def unpack_and_compile(self, egg_path, destination):
+ to_compile = []
+ to_chmod = []
+
+ def pf(src, dst):
+ if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
+ to_compile.append(dst)
+ elif dst.endswith('.dll') or dst.endswith('.so'):
+ to_chmod.append(dst)
+ self.unpack_progress(src, dst)
+ return not self.dry_run and dst or None
+
+ unpack_archive(egg_path, destination, pf)
+ self.byte_compile(to_compile)
+ if not self.dry_run:
+ for f in to_chmod:
+ mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755
+ chmod(f, mode)
+
+ def byte_compile(self, to_compile):
+ if sys.dont_write_bytecode:
+ return
+
+ from distutils.util import byte_compile
+
+ try:
+ # try to make the byte compile messages quieter
+ log.set_verbosity(self.verbose - 1)
+
+ byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run)
+ if self.optimize:
+ byte_compile(
+ to_compile, optimize=self.optimize, force=1,
dry_run=self.dry_run,
- )
- finally:
- log.set_verbosity(self.verbose) # restore original verbosity
-
- __no_default_msg = textwrap.dedent("""
- bad install directory or PYTHONPATH
-
- You are attempting to install a package to a directory that is not
- on PYTHONPATH and which Python does not read ".pth" files from. The
- installation directory you specified (via --install-dir, --prefix, or
- the distutils default setting) was:
-
- %s
-
- and your PYTHONPATH environment variable currently contains:
-
- %r
-
- Here are some of your options for correcting the problem:
-
- * You can choose a different installation directory, i.e., one that is
- on PYTHONPATH or supports .pth files
-
- * You can add the installation directory to the PYTHONPATH environment
- variable. (It must then also be on PYTHONPATH whenever you run
- Python and want to use the package(s) you are installing.)
-
- * You can set up the installation directory to support ".pth" files by
- using one of the approaches described here:
-
+ )
+ finally:
+ log.set_verbosity(self.verbose) # restore original verbosity
+
+ __no_default_msg = textwrap.dedent("""
+ bad install directory or PYTHONPATH
+
+ You are attempting to install a package to a directory that is not
+ on PYTHONPATH and which Python does not read ".pth" files from. The
+ installation directory you specified (via --install-dir, --prefix, or
+ the distutils default setting) was:
+
+ %s
+
+ and your PYTHONPATH environment variable currently contains:
+
+ %r
+
+ Here are some of your options for correcting the problem:
+
+ * You can choose a different installation directory, i.e., one that is
+ on PYTHONPATH or supports .pth files
+
+ * You can add the installation directory to the PYTHONPATH environment
+ variable. (It must then also be on PYTHONPATH whenever you run
+ Python and want to use the package(s) you are installing.)
+
+ * You can set up the installation directory to support ".pth" files by
+ using one of the approaches described here:
+
https://setuptools.readthedocs.io/en/latest/easy_install.html#custom-installation-locations
-
-
- Please make the appropriate changes for your system and try again.""").lstrip()
-
- def no_default_version_msg(self):
- template = self.__no_default_msg
- return template % (self.install_dir, os.environ.get('PYTHONPATH', ''))
-
- def install_site_py(self):
- """Make sure there's a site.py in the target dir, if needed"""
-
- if self.sitepy_installed:
- return # already did it, or don't need to
-
- sitepy = os.path.join(self.install_dir, "site.py")
- source = resource_string("setuptools", "site-patch.py")
+
+
+ Please make the appropriate changes for your system and try again.""").lstrip()
+
+ def no_default_version_msg(self):
+ template = self.__no_default_msg
+ return template % (self.install_dir, os.environ.get('PYTHONPATH', ''))
+
+ def install_site_py(self):
+ """Make sure there's a site.py in the target dir, if needed"""
+
+ if self.sitepy_installed:
+ return # already did it, or don't need to
+
+ sitepy = os.path.join(self.install_dir, "site.py")
+ source = resource_string("setuptools", "site-patch.py")
source = source.decode('utf-8')
- current = ""
-
- if os.path.exists(sitepy):
- log.debug("Checking existing site.py in %s", self.install_dir)
+ current = ""
+
+ if os.path.exists(sitepy):
+ log.debug("Checking existing site.py in %s", self.install_dir)
with io.open(sitepy) as strm:
current = strm.read()
-
- if not current.startswith('def __boot():'):
- raise DistutilsError(
- "%s is not a setuptools-generated site.py; please"
- " remove it." % sitepy
- )
-
- if current != source:
- log.info("Creating %s", sitepy)
- if not self.dry_run:
- ensure_directory(sitepy)
+
+ if not current.startswith('def __boot():'):
+ raise DistutilsError(
+ "%s is not a setuptools-generated site.py; please"
+ " remove it." % sitepy
+ )
+
+ if current != source:
+ log.info("Creating %s", sitepy)
+ if not self.dry_run:
+ ensure_directory(sitepy)
with io.open(sitepy, 'w', encoding='utf-8') as strm:
strm.write(source)
- self.byte_compile([sitepy])
-
- self.sitepy_installed = True
-
- def create_home_path(self):
- """Create directories under ~."""
- if not self.user:
- return
- home = convert_path(os.path.expanduser("~"))
- for name, path in six.iteritems(self.config_vars):
- if path.startswith(home) and not os.path.isdir(path):
- self.debug_print("os.makedirs('%s', 0o700)" % path)
- os.makedirs(path, 0o700)
-
- INSTALL_SCHEMES = dict(
- posix=dict(
- install_dir='$base/lib/python$py_version_short/site-packages',
- script_dir='$base/bin',
- ),
- )
-
- DEFAULT_SCHEME = dict(
- install_dir='$base/Lib/site-packages',
- script_dir='$base/Scripts',
- )
-
- def _expand(self, *attrs):
- config_vars = self.get_finalized_command('install').config_vars
-
- if self.prefix:
- # Set default install_dir/scripts from --prefix
- config_vars = config_vars.copy()
- config_vars['base'] = self.prefix
- scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME)
- for attr, val in scheme.items():
- if getattr(self, attr, None) is None:
- setattr(self, attr, val)
-
- from distutils.util import subst_vars
-
- for attr in attrs:
- val = getattr(self, attr)
- if val is not None:
- val = subst_vars(val, config_vars)
- if os.name == 'posix':
- val = os.path.expanduser(val)
- setattr(self, attr, val)
-
-
+ self.byte_compile([sitepy])
+
+ self.sitepy_installed = True
+
+ def create_home_path(self):
+ """Create directories under ~."""
+ if not self.user:
+ return
+ home = convert_path(os.path.expanduser("~"))
+ for name, path in six.iteritems(self.config_vars):
+ if path.startswith(home) and not os.path.isdir(path):
+ self.debug_print("os.makedirs('%s', 0o700)" % path)
+ os.makedirs(path, 0o700)
+
+ INSTALL_SCHEMES = dict(
+ posix=dict(
+ install_dir='$base/lib/python$py_version_short/site-packages',
+ script_dir='$base/bin',
+ ),
+ )
+
+ DEFAULT_SCHEME = dict(
+ install_dir='$base/Lib/site-packages',
+ script_dir='$base/Scripts',
+ )
+
+ def _expand(self, *attrs):
+ config_vars = self.get_finalized_command('install').config_vars
+
+ if self.prefix:
+ # Set default install_dir/scripts from --prefix
+ config_vars = config_vars.copy()
+ config_vars['base'] = self.prefix
+ scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME)
+ for attr, val in scheme.items():
+ if getattr(self, attr, None) is None:
+ setattr(self, attr, val)
+
+ from distutils.util import subst_vars
+
+ for attr in attrs:
+ val = getattr(self, attr)
+ if val is not None:
+ val = subst_vars(val, config_vars)
+ if os.name == 'posix':
+ val = os.path.expanduser(val)
+ setattr(self, attr, val)
+
+
def _pythonpath():
items = os.environ.get('PYTHONPATH', '').split(os.pathsep)
return filter(None, items)
-def get_site_dirs():
+def get_site_dirs():
"""
Return a list of 'site' dirs
"""
@@ -1405,14 +1405,14 @@ def get_site_dirs():
# start with PYTHONPATH
sitedirs.extend(_pythonpath())
- prefixes = [sys.prefix]
- if sys.exec_prefix != sys.prefix:
- prefixes.append(sys.exec_prefix)
- for prefix in prefixes:
- if prefix:
- if sys.platform in ('os2emx', 'riscos'):
- sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
- elif os.sep == '/':
+ prefixes = [sys.prefix]
+ if sys.exec_prefix != sys.prefix:
+ prefixes.append(sys.exec_prefix)
+ for prefix in prefixes:
+ if prefix:
+ if sys.platform in ('os2emx', 'riscos'):
+ sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
+ elif os.sep == '/':
sitedirs.extend([
os.path.join(
prefix,
@@ -1422,18 +1422,18 @@ def get_site_dirs():
),
os.path.join(prefix, "lib", "site-python"),
])
- else:
+ else:
sitedirs.extend([
prefix,
os.path.join(prefix, "lib", "site-packages"),
])
- if sys.platform == 'darwin':
- # for framework builds *only* we add the standard Apple
- # locations. Currently only per-user, but /Library and
- # /Network/Library could be added too
- if 'Python.framework' in prefix:
- home = os.environ.get('HOME')
- if home:
+ if sys.platform == 'darwin':
+ # for framework builds *only* we add the standard Apple
+ # locations. Currently only per-user, but /Library and
+ # /Network/Library could be added too
+ if 'Python.framework' in prefix:
+ home = os.environ.get('HOME')
+ if home:
home_sp = os.path.join(
home,
'Library',
@@ -1442,602 +1442,602 @@ def get_site_dirs():
'site-packages',
)
sitedirs.append(home_sp)
- lib_paths = get_path('purelib'), get_path('platlib')
- for site_lib in lib_paths:
- if site_lib not in sitedirs:
- sitedirs.append(site_lib)
-
- if site.ENABLE_USER_SITE:
- sitedirs.append(site.USER_SITE)
-
+ lib_paths = get_path('purelib'), get_path('platlib')
+ for site_lib in lib_paths:
+ if site_lib not in sitedirs:
+ sitedirs.append(site_lib)
+
+ if site.ENABLE_USER_SITE:
+ sitedirs.append(site.USER_SITE)
+
try:
sitedirs.extend(site.getsitepackages())
except AttributeError:
pass
- sitedirs = list(map(normalize_path, sitedirs))
-
- return sitedirs
-
-
-def expand_paths(inputs):
- """Yield sys.path directories that might contain "old-style" packages"""
-
- seen = {}
-
- for dirname in inputs:
- dirname = normalize_path(dirname)
- if dirname in seen:
- continue
-
- seen[dirname] = 1
- if not os.path.isdir(dirname):
- continue
-
- files = os.listdir(dirname)
- yield dirname, files
-
- for name in files:
- if not name.endswith('.pth'):
- # We only care about the .pth files
- continue
- if name in ('easy-install.pth', 'setuptools.pth'):
- # Ignore .pth files that we control
- continue
-
- # Read the .pth file
- f = open(os.path.join(dirname, name))
- lines = list(yield_lines(f))
- f.close()
-
- # Yield existing non-dupe, non-import directory lines from it
- for line in lines:
- if not line.startswith("import"):
- line = normalize_path(line.rstrip())
- if line not in seen:
- seen[line] = 1
- if not os.path.isdir(line):
- continue
- yield line, os.listdir(line)
-
-
-def extract_wininst_cfg(dist_filename):
- """Extract configuration data from a bdist_wininst .exe
-
- Returns a configparser.RawConfigParser, or None
- """
- f = open(dist_filename, 'rb')
- try:
- endrec = zipfile._EndRecData(f)
- if endrec is None:
- return None
-
- prepended = (endrec[9] - endrec[5]) - endrec[6]
- if prepended < 12: # no wininst data here
- return None
- f.seek(prepended - 12)
-
- tag, cfglen, bmlen = struct.unpack("<iii", f.read(12))
- if tag not in (0x1234567A, 0x1234567B):
- return None # not a valid tag
-
- f.seek(prepended - (12 + cfglen))
+ sitedirs = list(map(normalize_path, sitedirs))
+
+ return sitedirs
+
+
+def expand_paths(inputs):
+ """Yield sys.path directories that might contain "old-style" packages"""
+
+ seen = {}
+
+ for dirname in inputs:
+ dirname = normalize_path(dirname)
+ if dirname in seen:
+ continue
+
+ seen[dirname] = 1
+ if not os.path.isdir(dirname):
+ continue
+
+ files = os.listdir(dirname)
+ yield dirname, files
+
+ for name in files:
+ if not name.endswith('.pth'):
+ # We only care about the .pth files
+ continue
+ if name in ('easy-install.pth', 'setuptools.pth'):
+ # Ignore .pth files that we control
+ continue
+
+ # Read the .pth file
+ f = open(os.path.join(dirname, name))
+ lines = list(yield_lines(f))
+ f.close()
+
+ # Yield existing non-dupe, non-import directory lines from it
+ for line in lines:
+ if not line.startswith("import"):
+ line = normalize_path(line.rstrip())
+ if line not in seen:
+ seen[line] = 1
+ if not os.path.isdir(line):
+ continue
+ yield line, os.listdir(line)
+
+
+def extract_wininst_cfg(dist_filename):
+ """Extract configuration data from a bdist_wininst .exe
+
+ Returns a configparser.RawConfigParser, or None
+ """
+ f = open(dist_filename, 'rb')
+ try:
+ endrec = zipfile._EndRecData(f)
+ if endrec is None:
+ return None
+
+ prepended = (endrec[9] - endrec[5]) - endrec[6]
+ if prepended < 12: # no wininst data here
+ return None
+ f.seek(prepended - 12)
+
+ tag, cfglen, bmlen = struct.unpack("<iii", f.read(12))
+ if tag not in (0x1234567A, 0x1234567B):
+ return None # not a valid tag
+
+ f.seek(prepended - (12 + cfglen))
init = {'version': '', 'target_version': ''}
cfg = configparser.RawConfigParser(init)
- try:
- part = f.read(cfglen)
- # Read up to the first null byte.
- config = part.split(b'\0', 1)[0]
- # Now the config is in bytes, but for RawConfigParser, it should
- # be text, so decode it.
- config = config.decode(sys.getfilesystemencoding())
- cfg.readfp(six.StringIO(config))
- except configparser.Error:
- return None
- if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
- return None
- return cfg
-
- finally:
- f.close()
-
-
-def get_exe_prefixes(exe_filename):
- """Get exe->egg path translations for a given .exe file"""
-
- prefixes = [
+ try:
+ part = f.read(cfglen)
+ # Read up to the first null byte.
+ config = part.split(b'\0', 1)[0]
+ # Now the config is in bytes, but for RawConfigParser, it should
+ # be text, so decode it.
+ config = config.decode(sys.getfilesystemencoding())
+ cfg.readfp(six.StringIO(config))
+ except configparser.Error:
+ return None
+ if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
+ return None
+ return cfg
+
+ finally:
+ f.close()
+
+
+def get_exe_prefixes(exe_filename):
+ """Get exe->egg path translations for a given .exe file"""
+
+ prefixes = [
('PURELIB/', ''),
('PLATLIB/pywin32_system32', ''),
- ('PLATLIB/', ''),
- ('SCRIPTS/', 'EGG-INFO/scripts/'),
- ('DATA/lib/site-packages', ''),
- ]
- z = zipfile.ZipFile(exe_filename)
- try:
- for info in z.infolist():
- name = info.filename
- parts = name.split('/')
- if len(parts) == 3 and parts[2] == 'PKG-INFO':
- if parts[1].endswith('.egg-info'):
- prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/'))
- break
- if len(parts) != 2 or not name.endswith('.pth'):
- continue
- if name.endswith('-nspkg.pth'):
- continue
- if parts[0].upper() in ('PURELIB', 'PLATLIB'):
- contents = z.read(name)
+ ('PLATLIB/', ''),
+ ('SCRIPTS/', 'EGG-INFO/scripts/'),
+ ('DATA/lib/site-packages', ''),
+ ]
+ z = zipfile.ZipFile(exe_filename)
+ try:
+ for info in z.infolist():
+ name = info.filename
+ parts = name.split('/')
+ if len(parts) == 3 and parts[2] == 'PKG-INFO':
+ if parts[1].endswith('.egg-info'):
+ prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/'))
+ break
+ if len(parts) != 2 or not name.endswith('.pth'):
+ continue
+ if name.endswith('-nspkg.pth'):
+ continue
+ if parts[0].upper() in ('PURELIB', 'PLATLIB'):
+ contents = z.read(name)
if not six.PY2:
- contents = contents.decode()
- for pth in yield_lines(contents):
- pth = pth.strip().replace('\\', '/')
- if not pth.startswith('import'):
- prefixes.append((('%s/%s/' % (parts[0], pth)), ''))
- finally:
- z.close()
- prefixes = [(x.lower(), y) for x, y in prefixes]
- prefixes.sort()
- prefixes.reverse()
- return prefixes
-
-
-class PthDistributions(Environment):
- """A .pth file with Distribution paths in it"""
-
- dirty = False
-
- def __init__(self, filename, sitedirs=()):
- self.filename = filename
- self.sitedirs = list(map(normalize_path, sitedirs))
- self.basedir = normalize_path(os.path.dirname(self.filename))
- self._load()
- Environment.__init__(self, [], None, None)
- for path in yield_lines(self.paths):
- list(map(self.add, find_distributions(path, True)))
-
- def _load(self):
- self.paths = []
- saw_import = False
- seen = dict.fromkeys(self.sitedirs)
- if os.path.isfile(self.filename):
- f = open(self.filename, 'rt')
- for line in f:
- if line.startswith('import'):
- saw_import = True
- continue
- path = line.rstrip()
- self.paths.append(path)
- if not path.strip() or path.strip().startswith('#'):
- continue
- # skip non-existent paths, in case somebody deleted a package
- # manually, and duplicate paths as well
- path = self.paths[-1] = normalize_path(
- os.path.join(self.basedir, path)
- )
- if not os.path.exists(path) or path in seen:
- self.paths.pop() # skip it
- self.dirty = True # we cleaned up, so we're dirty now :)
- continue
- seen[path] = 1
- f.close()
-
- if self.paths and not saw_import:
- self.dirty = True # ensure anything we touch has import wrappers
- while self.paths and not self.paths[-1].strip():
- self.paths.pop()
-
- def save(self):
- """Write changed .pth file back to disk"""
- if not self.dirty:
- return
-
- rel_paths = list(map(self.make_relative, self.paths))
- if rel_paths:
- log.debug("Saving %s", self.filename)
- lines = self._wrap_lines(rel_paths)
- data = '\n'.join(lines) + '\n'
-
- if os.path.islink(self.filename):
- os.unlink(self.filename)
- with open(self.filename, 'wt') as f:
- f.write(data)
-
- elif os.path.exists(self.filename):
- log.debug("Deleting empty %s", self.filename)
- os.unlink(self.filename)
-
- self.dirty = False
-
- @staticmethod
- def _wrap_lines(lines):
- return lines
-
- def add(self, dist):
- """Add `dist` to the distribution map"""
- new_path = (
- dist.location not in self.paths and (
- dist.location not in self.sitedirs or
- # account for '.' being in PYTHONPATH
- dist.location == os.getcwd()
- )
- )
- if new_path:
- self.paths.append(dist.location)
- self.dirty = True
- Environment.add(self, dist)
-
- def remove(self, dist):
- """Remove `dist` from the distribution map"""
- while dist.location in self.paths:
- self.paths.remove(dist.location)
- self.dirty = True
- Environment.remove(self, dist)
-
- def make_relative(self, path):
- npath, last = os.path.split(normalize_path(path))
- baselen = len(self.basedir)
- parts = [last]
- sep = os.altsep == '/' and '/' or os.sep
- while len(npath) >= baselen:
- if npath == self.basedir:
- parts.append(os.curdir)
- parts.reverse()
- return sep.join(parts)
- npath, last = os.path.split(npath)
- parts.append(last)
- else:
- return path
-
-
-class RewritePthDistributions(PthDistributions):
- @classmethod
- def _wrap_lines(cls, lines):
- yield cls.prelude
- for line in lines:
- yield line
- yield cls.postlude
-
+ contents = contents.decode()
+ for pth in yield_lines(contents):
+ pth = pth.strip().replace('\\', '/')
+ if not pth.startswith('import'):
+ prefixes.append((('%s/%s/' % (parts[0], pth)), ''))
+ finally:
+ z.close()
+ prefixes = [(x.lower(), y) for x, y in prefixes]
+ prefixes.sort()
+ prefixes.reverse()
+ return prefixes
+
+
+class PthDistributions(Environment):
+ """A .pth file with Distribution paths in it"""
+
+ dirty = False
+
+ def __init__(self, filename, sitedirs=()):
+ self.filename = filename
+ self.sitedirs = list(map(normalize_path, sitedirs))
+ self.basedir = normalize_path(os.path.dirname(self.filename))
+ self._load()
+ Environment.__init__(self, [], None, None)
+ for path in yield_lines(self.paths):
+ list(map(self.add, find_distributions(path, True)))
+
+ def _load(self):
+ self.paths = []
+ saw_import = False
+ seen = dict.fromkeys(self.sitedirs)
+ if os.path.isfile(self.filename):
+ f = open(self.filename, 'rt')
+ for line in f:
+ if line.startswith('import'):
+ saw_import = True
+ continue
+ path = line.rstrip()
+ self.paths.append(path)
+ if not path.strip() or path.strip().startswith('#'):
+ continue
+ # skip non-existent paths, in case somebody deleted a package
+ # manually, and duplicate paths as well
+ path = self.paths[-1] = normalize_path(
+ os.path.join(self.basedir, path)
+ )
+ if not os.path.exists(path) or path in seen:
+ self.paths.pop() # skip it
+ self.dirty = True # we cleaned up, so we're dirty now :)
+ continue
+ seen[path] = 1
+ f.close()
+
+ if self.paths and not saw_import:
+ self.dirty = True # ensure anything we touch has import wrappers
+ while self.paths and not self.paths[-1].strip():
+ self.paths.pop()
+
+ def save(self):
+ """Write changed .pth file back to disk"""
+ if not self.dirty:
+ return
+
+ rel_paths = list(map(self.make_relative, self.paths))
+ if rel_paths:
+ log.debug("Saving %s", self.filename)
+ lines = self._wrap_lines(rel_paths)
+ data = '\n'.join(lines) + '\n'
+
+ if os.path.islink(self.filename):
+ os.unlink(self.filename)
+ with open(self.filename, 'wt') as f:
+ f.write(data)
+
+ elif os.path.exists(self.filename):
+ log.debug("Deleting empty %s", self.filename)
+ os.unlink(self.filename)
+
+ self.dirty = False
+
+ @staticmethod
+ def _wrap_lines(lines):
+ return lines
+
+ def add(self, dist):
+ """Add `dist` to the distribution map"""
+ new_path = (
+ dist.location not in self.paths and (
+ dist.location not in self.sitedirs or
+ # account for '.' being in PYTHONPATH
+ dist.location == os.getcwd()
+ )
+ )
+ if new_path:
+ self.paths.append(dist.location)
+ self.dirty = True
+ Environment.add(self, dist)
+
+ def remove(self, dist):
+ """Remove `dist` from the distribution map"""
+ while dist.location in self.paths:
+ self.paths.remove(dist.location)
+ self.dirty = True
+ Environment.remove(self, dist)
+
+ def make_relative(self, path):
+ npath, last = os.path.split(normalize_path(path))
+ baselen = len(self.basedir)
+ parts = [last]
+ sep = os.altsep == '/' and '/' or os.sep
+ while len(npath) >= baselen:
+ if npath == self.basedir:
+ parts.append(os.curdir)
+ parts.reverse()
+ return sep.join(parts)
+ npath, last = os.path.split(npath)
+ parts.append(last)
+ else:
+ return path
+
+
+class RewritePthDistributions(PthDistributions):
+ @classmethod
+ def _wrap_lines(cls, lines):
+ yield cls.prelude
+ for line in lines:
+ yield line
+ yield cls.postlude
+
prelude = _one_liner("""
- import sys
- sys.__plen = len(sys.path)
- """)
+ import sys
+ sys.__plen = len(sys.path)
+ """)
postlude = _one_liner("""
- import sys
- new = sys.path[sys.__plen:]
- del sys.path[sys.__plen:]
- p = getattr(sys, '__egginsert', 0)
- sys.path[p:p] = new
- sys.__egginsert = p + len(new)
- """)
-
-
+ import sys
+ new = sys.path[sys.__plen:]
+ del sys.path[sys.__plen:]
+ p = getattr(sys, '__egginsert', 0)
+ sys.path[p:p] = new
+ sys.__egginsert = p + len(new)
+ """)
+
+
if os.environ.get('SETUPTOOLS_SYS_PATH_TECHNIQUE', 'raw') == 'rewrite':
- PthDistributions = RewritePthDistributions
-
-
-def _first_line_re():
- """
- Return a regular expression based on first_line_re suitable for matching
- strings.
- """
- if isinstance(first_line_re.pattern, str):
- return first_line_re
-
- # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
- return re.compile(first_line_re.pattern.decode())
-
-
-def auto_chmod(func, arg, exc):
+ PthDistributions = RewritePthDistributions
+
+
+def _first_line_re():
+ """
+ Return a regular expression based on first_line_re suitable for matching
+ strings.
+ """
+ if isinstance(first_line_re.pattern, str):
+ return first_line_re
+
+ # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
+ return re.compile(first_line_re.pattern.decode())
+
+
+def auto_chmod(func, arg, exc):
if func in [os.unlink, os.remove] and os.name == 'nt':
- chmod(arg, stat.S_IWRITE)
- return func(arg)
- et, ev, _ = sys.exc_info()
- six.reraise(et, (ev[0], ev[1] + (" %s %s" % (func, arg))))
-
-
-def update_dist_caches(dist_path, fix_zipimporter_caches):
- """
- Fix any globally cached `dist_path` related data
-
- `dist_path` should be a path of a newly installed egg distribution (zipped
- or unzipped).
-
- sys.path_importer_cache contains finder objects that have been cached when
- importing data from the original distribution. Any such finders need to be
- cleared since the replacement distribution might be packaged differently,
- e.g. a zipped egg distribution might get replaced with an unzipped egg
- folder or vice versa. Having the old finders cached may then cause Python
- to attempt loading modules from the replacement distribution using an
- incorrect loader.
-
- zipimport.zipimporter objects are Python loaders charged with importing
- data packaged inside zip archives. If stale loaders referencing the
- original distribution, are left behind, they can fail to load modules from
- the replacement distribution. E.g. if an old zipimport.zipimporter instance
- is used to load data from a new zipped egg archive, it may cause the
- operation to attempt to locate the requested data in the wrong location -
- one indicated by the original distribution's zip archive directory
- information. Such an operation may then fail outright, e.g. report having
- read a 'bad local file header', or even worse, it may fail silently &
- return invalid data.
-
- zipimport._zip_directory_cache contains cached zip archive directory
- information for all existing zipimport.zipimporter instances and all such
- instances connected to the same archive share the same cached directory
- information.
-
- If asked, and the underlying Python implementation allows it, we can fix
- all existing zipimport.zipimporter instances instead of having to track
- them down and remove them one by one, by updating their shared cached zip
- archive directory information. This, of course, assumes that the
- replacement distribution is packaged as a zipped egg.
-
- If not asked to fix existing zipimport.zipimporter instances, we still do
- our best to clear any remaining zipimport.zipimporter related cached data
- that might somehow later get used when attempting to load data from the new
- distribution and thus cause such load operations to fail. Note that when
- tracking down such remaining stale data, we can not catch every conceivable
- usage from here, and we clear only those that we know of and have found to
- cause problems if left alive. Any remaining caches should be updated by
- whomever is in charge of maintaining them, i.e. they should be ready to
- handle us replacing their zip archives with new distributions at runtime.
-
- """
- # There are several other known sources of stale zipimport.zipimporter
- # instances that we do not clear here, but might if ever given a reason to
- # do so:
- # * Global setuptools pkg_resources.working_set (a.k.a. 'master working
- # set') may contain distributions which may in turn contain their
- # zipimport.zipimporter loaders.
- # * Several zipimport.zipimporter loaders held by local variables further
- # up the function call stack when running the setuptools installation.
- # * Already loaded modules may have their __loader__ attribute set to the
- # exact loader instance used when importing them. Python 3.4 docs state
- # that this information is intended mostly for introspection and so is
- # not expected to cause us problems.
- normalized_path = normalize_path(dist_path)
- _uncache(normalized_path, sys.path_importer_cache)
- if fix_zipimporter_caches:
- _replace_zip_directory_cache_data(normalized_path)
- else:
- # Here, even though we do not want to fix existing and now stale
- # zipimporter cache information, we still want to remove it. Related to
- # Python's zip archive directory information cache, we clear each of
- # its stale entries in two phases:
- # 1. Clear the entry so attempting to access zip archive information
- # via any existing stale zipimport.zipimporter instances fails.
- # 2. Remove the entry from the cache so any newly constructed
- # zipimport.zipimporter instances do not end up using old stale
- # zip archive directory information.
- # This whole stale data removal step does not seem strictly necessary,
- # but has been left in because it was done before we started replacing
- # the zip archive directory information cache content if possible, and
- # there are no relevant unit tests that we can depend on to tell us if
- # this is really needed.
- _remove_and_clear_zip_directory_cache_data(normalized_path)
-
-
-def _collect_zipimporter_cache_entries(normalized_path, cache):
- """
- Return zipimporter cache entry keys related to a given normalized path.
-
- Alternative path spellings (e.g. those using different character case or
- those using alternative path separators) related to the same path are
- included. Any sub-path entries are included as well, i.e. those
- corresponding to zip archives embedded in other zip archives.
-
- """
- result = []
- prefix_len = len(normalized_path)
- for p in cache:
- np = normalize_path(p)
- if (np.startswith(normalized_path) and
- np[prefix_len:prefix_len + 1] in (os.sep, '')):
- result.append(p)
- return result
-
-
-def _update_zipimporter_cache(normalized_path, cache, updater=None):
- """
- Update zipimporter cache data for a given normalized path.
-
- Any sub-path entries are processed as well, i.e. those corresponding to zip
- archives embedded in other zip archives.
-
- Given updater is a callable taking a cache entry key and the original entry
- (after already removing the entry from the cache), and expected to update
- the entry and possibly return a new one to be inserted in its place.
- Returning None indicates that the entry should not be replaced with a new
- one. If no updater is given, the cache entries are simply removed without
- any additional processing, the same as if the updater simply returned None.
-
- """
- for p in _collect_zipimporter_cache_entries(normalized_path, cache):
- # N.B. pypy's custom zipimport._zip_directory_cache implementation does
- # not support the complete dict interface:
- # * Does not support item assignment, thus not allowing this function
- # to be used only for removing existing cache entries.
- # * Does not support the dict.pop() method, forcing us to use the
- # get/del patterns instead. For more detailed information see the
- # following links:
+ chmod(arg, stat.S_IWRITE)
+ return func(arg)
+ et, ev, _ = sys.exc_info()
+ six.reraise(et, (ev[0], ev[1] + (" %s %s" % (func, arg))))
+
+
+def update_dist_caches(dist_path, fix_zipimporter_caches):
+ """
+ Fix any globally cached `dist_path` related data
+
+ `dist_path` should be a path of a newly installed egg distribution (zipped
+ or unzipped).
+
+ sys.path_importer_cache contains finder objects that have been cached when
+ importing data from the original distribution. Any such finders need to be
+ cleared since the replacement distribution might be packaged differently,
+ e.g. a zipped egg distribution might get replaced with an unzipped egg
+ folder or vice versa. Having the old finders cached may then cause Python
+ to attempt loading modules from the replacement distribution using an
+ incorrect loader.
+
+ zipimport.zipimporter objects are Python loaders charged with importing
+ data packaged inside zip archives. If stale loaders referencing the
+ original distribution, are left behind, they can fail to load modules from
+ the replacement distribution. E.g. if an old zipimport.zipimporter instance
+ is used to load data from a new zipped egg archive, it may cause the
+ operation to attempt to locate the requested data in the wrong location -
+ one indicated by the original distribution's zip archive directory
+ information. Such an operation may then fail outright, e.g. report having
+ read a 'bad local file header', or even worse, it may fail silently &
+ return invalid data.
+
+ zipimport._zip_directory_cache contains cached zip archive directory
+ information for all existing zipimport.zipimporter instances and all such
+ instances connected to the same archive share the same cached directory
+ information.
+
+ If asked, and the underlying Python implementation allows it, we can fix
+ all existing zipimport.zipimporter instances instead of having to track
+ them down and remove them one by one, by updating their shared cached zip
+ archive directory information. This, of course, assumes that the
+ replacement distribution is packaged as a zipped egg.
+
+ If not asked to fix existing zipimport.zipimporter instances, we still do
+ our best to clear any remaining zipimport.zipimporter related cached data
+ that might somehow later get used when attempting to load data from the new
+ distribution and thus cause such load operations to fail. Note that when
+ tracking down such remaining stale data, we can not catch every conceivable
+ usage from here, and we clear only those that we know of and have found to
+ cause problems if left alive. Any remaining caches should be updated by
+ whomever is in charge of maintaining them, i.e. they should be ready to
+ handle us replacing their zip archives with new distributions at runtime.
+
+ """
+ # There are several other known sources of stale zipimport.zipimporter
+ # instances that we do not clear here, but might if ever given a reason to
+ # do so:
+ # * Global setuptools pkg_resources.working_set (a.k.a. 'master working
+ # set') may contain distributions which may in turn contain their
+ # zipimport.zipimporter loaders.
+ # * Several zipimport.zipimporter loaders held by local variables further
+ # up the function call stack when running the setuptools installation.
+ # * Already loaded modules may have their __loader__ attribute set to the
+ # exact loader instance used when importing them. Python 3.4 docs state
+ # that this information is intended mostly for introspection and so is
+ # not expected to cause us problems.
+ normalized_path = normalize_path(dist_path)
+ _uncache(normalized_path, sys.path_importer_cache)
+ if fix_zipimporter_caches:
+ _replace_zip_directory_cache_data(normalized_path)
+ else:
+ # Here, even though we do not want to fix existing and now stale
+ # zipimporter cache information, we still want to remove it. Related to
+ # Python's zip archive directory information cache, we clear each of
+ # its stale entries in two phases:
+ # 1. Clear the entry so attempting to access zip archive information
+ # via any existing stale zipimport.zipimporter instances fails.
+ # 2. Remove the entry from the cache so any newly constructed
+ # zipimport.zipimporter instances do not end up using old stale
+ # zip archive directory information.
+ # This whole stale data removal step does not seem strictly necessary,
+ # but has been left in because it was done before we started replacing
+ # the zip archive directory information cache content if possible, and
+ # there are no relevant unit tests that we can depend on to tell us if
+ # this is really needed.
+ _remove_and_clear_zip_directory_cache_data(normalized_path)
+
+
+def _collect_zipimporter_cache_entries(normalized_path, cache):
+ """
+ Return zipimporter cache entry keys related to a given normalized path.
+
+ Alternative path spellings (e.g. those using different character case or
+ those using alternative path separators) related to the same path are
+ included. Any sub-path entries are included as well, i.e. those
+ corresponding to zip archives embedded in other zip archives.
+
+ """
+ result = []
+ prefix_len = len(normalized_path)
+ for p in cache:
+ np = normalize_path(p)
+ if (np.startswith(normalized_path) and
+ np[prefix_len:prefix_len + 1] in (os.sep, '')):
+ result.append(p)
+ return result
+
+
+def _update_zipimporter_cache(normalized_path, cache, updater=None):
+ """
+ Update zipimporter cache data for a given normalized path.
+
+ Any sub-path entries are processed as well, i.e. those corresponding to zip
+ archives embedded in other zip archives.
+
+ Given updater is a callable taking a cache entry key and the original entry
+ (after already removing the entry from the cache), and expected to update
+ the entry and possibly return a new one to be inserted in its place.
+ Returning None indicates that the entry should not be replaced with a new
+ one. If no updater is given, the cache entries are simply removed without
+ any additional processing, the same as if the updater simply returned None.
+
+ """
+ for p in _collect_zipimporter_cache_entries(normalized_path, cache):
+ # N.B. pypy's custom zipimport._zip_directory_cache implementation does
+ # not support the complete dict interface:
+ # * Does not support item assignment, thus not allowing this function
+ # to be used only for removing existing cache entries.
+ # * Does not support the dict.pop() method, forcing us to use the
+ # get/del patterns instead. For more detailed information see the
+ # following links:
# https://github.com/pypa/setuptools/issues/202#issuecomment-202913420
# http://bit.ly/2h9itJX
- old_entry = cache[p]
- del cache[p]
- new_entry = updater and updater(p, old_entry)
- if new_entry is not None:
- cache[p] = new_entry
-
-
-def _uncache(normalized_path, cache):
- _update_zipimporter_cache(normalized_path, cache)
-
-
-def _remove_and_clear_zip_directory_cache_data(normalized_path):
- def clear_and_remove_cached_zip_archive_directory_data(path, old_entry):
- old_entry.clear()
-
- _update_zipimporter_cache(
- normalized_path, zipimport._zip_directory_cache,
- updater=clear_and_remove_cached_zip_archive_directory_data)
-
-
-# PyPy Python implementation does not allow directly writing to the
-# zipimport._zip_directory_cache and so prevents us from attempting to correct
-# its content. The best we can do there is clear the problematic cache content
-# and have PyPy repopulate it as needed. The downside is that if there are any
-# stale zipimport.zipimporter instances laying around, attempting to use them
-# will fail due to not having its zip archive directory information available
-# instead of being automatically corrected to use the new correct zip archive
-# directory information.
-if '__pypy__' in sys.builtin_module_names:
- _replace_zip_directory_cache_data = \
- _remove_and_clear_zip_directory_cache_data
-else:
-
- def _replace_zip_directory_cache_data(normalized_path):
- def replace_cached_zip_archive_directory_data(path, old_entry):
- # N.B. In theory, we could load the zip directory information just
- # once for all updated path spellings, and then copy it locally and
- # update its contained path strings to contain the correct
- # spelling, but that seems like a way too invasive move (this cache
- # structure is not officially documented anywhere and could in
- # theory change with new Python releases) for no significant
- # benefit.
- old_entry.clear()
- zipimport.zipimporter(path)
- old_entry.update(zipimport._zip_directory_cache[path])
- return old_entry
-
- _update_zipimporter_cache(
- normalized_path, zipimport._zip_directory_cache,
- updater=replace_cached_zip_archive_directory_data)
-
-
-def is_python(text, filename='<string>'):
- "Is this string a valid Python script?"
- try:
- compile(text, filename, 'exec')
- except (SyntaxError, TypeError):
- return False
- else:
- return True
-
-
-def is_sh(executable):
- """Determine if the specified executable is a .sh (contains a #! line)"""
- try:
- with io.open(executable, encoding='latin-1') as fp:
- magic = fp.read(2)
- except (OSError, IOError):
- return executable
- return magic == '#!'
-
-
-def nt_quote_arg(arg):
- """Quote a command line argument according to Windows parsing rules"""
- return subprocess.list2cmdline([arg])
-
-
-def is_python_script(script_text, filename):
- """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
- """
- if filename.endswith('.py') or filename.endswith('.pyw'):
- return True # extension says it's Python
- if is_python(script_text, filename):
- return True # it's syntactically valid Python
- if script_text.startswith('#!'):
- # It begins with a '#!' line, so check if 'python' is in it somewhere
- return 'python' in script_text.splitlines()[0].lower()
-
- return False # Not any Python I can recognize
-
-
-try:
- from os import chmod as _chmod
-except ImportError:
- # Jython compatibility
- def _chmod(*args):
- pass
-
-
-def chmod(path, mode):
- log.debug("changing mode of %s to %o", path, mode)
- try:
- _chmod(path, mode)
- except os.error as e:
- log.debug("chmod failed: %s", e)
-
-
-class CommandSpec(list):
- """
- A command spec for a #! header, specified as a list of arguments akin to
- those passed to Popen.
- """
-
- options = []
- split_args = dict()
-
- @classmethod
- def best(cls):
- """
- Choose the best CommandSpec class based on environmental conditions.
- """
- return cls
-
- @classmethod
- def _sys_executable(cls):
- _default = os.path.normpath(sys.executable)
- return os.environ.get('__PYVENV_LAUNCHER__', _default)
-
- @classmethod
- def from_param(cls, param):
- """
- Construct a CommandSpec from a parameter to build_scripts, which may
- be None.
- """
- if isinstance(param, cls):
- return param
- if isinstance(param, list):
- return cls(param)
- if param is None:
- return cls.from_environment()
- # otherwise, assume it's a string.
- return cls.from_string(param)
-
- @classmethod
- def from_environment(cls):
- return cls([cls._sys_executable()])
-
- @classmethod
- def from_string(cls, string):
- """
- Construct a command spec from a simple string representing a command
- line parseable by shlex.split.
- """
- items = shlex.split(string, **cls.split_args)
- return cls(items)
-
- def install_options(self, script_text):
- self.options = shlex.split(self._extract_options(script_text))
- cmdline = subprocess.list2cmdline(self)
- if not isascii(cmdline):
- self.options[:0] = ['-x']
-
- @staticmethod
- def _extract_options(orig_script):
- """
- Extract any options from the first line of the script.
- """
- first = (orig_script + '\n').splitlines()[0]
- match = _first_line_re().match(first)
- options = match.group(1) or '' if match else ''
- return options.strip()
-
- def as_header(self):
- return self._render(self + list(self.options))
-
- @staticmethod
+ old_entry = cache[p]
+ del cache[p]
+ new_entry = updater and updater(p, old_entry)
+ if new_entry is not None:
+ cache[p] = new_entry
+
+
+def _uncache(normalized_path, cache):
+ _update_zipimporter_cache(normalized_path, cache)
+
+
+def _remove_and_clear_zip_directory_cache_data(normalized_path):
+ def clear_and_remove_cached_zip_archive_directory_data(path, old_entry):
+ old_entry.clear()
+
+ _update_zipimporter_cache(
+ normalized_path, zipimport._zip_directory_cache,
+ updater=clear_and_remove_cached_zip_archive_directory_data)
+
+
+# PyPy Python implementation does not allow directly writing to the
+# zipimport._zip_directory_cache and so prevents us from attempting to correct
+# its content. The best we can do there is clear the problematic cache content
+# and have PyPy repopulate it as needed. The downside is that if there are any
+# stale zipimport.zipimporter instances laying around, attempting to use them
+# will fail due to not having its zip archive directory information available
+# instead of being automatically corrected to use the new correct zip archive
+# directory information.
+if '__pypy__' in sys.builtin_module_names:
+ _replace_zip_directory_cache_data = \
+ _remove_and_clear_zip_directory_cache_data
+else:
+
+ def _replace_zip_directory_cache_data(normalized_path):
+ def replace_cached_zip_archive_directory_data(path, old_entry):
+ # N.B. In theory, we could load the zip directory information just
+ # once for all updated path spellings, and then copy it locally and
+ # update its contained path strings to contain the correct
+ # spelling, but that seems like a way too invasive move (this cache
+ # structure is not officially documented anywhere and could in
+ # theory change with new Python releases) for no significant
+ # benefit.
+ old_entry.clear()
+ zipimport.zipimporter(path)
+ old_entry.update(zipimport._zip_directory_cache[path])
+ return old_entry
+
+ _update_zipimporter_cache(
+ normalized_path, zipimport._zip_directory_cache,
+ updater=replace_cached_zip_archive_directory_data)
+
+
+def is_python(text, filename='<string>'):
+ "Is this string a valid Python script?"
+ try:
+ compile(text, filename, 'exec')
+ except (SyntaxError, TypeError):
+ return False
+ else:
+ return True
+
+
+def is_sh(executable):
+ """Determine if the specified executable is a .sh (contains a #! line)"""
+ try:
+ with io.open(executable, encoding='latin-1') as fp:
+ magic = fp.read(2)
+ except (OSError, IOError):
+ return executable
+ return magic == '#!'
+
+
+def nt_quote_arg(arg):
+ """Quote a command line argument according to Windows parsing rules"""
+ return subprocess.list2cmdline([arg])
+
+
+def is_python_script(script_text, filename):
+ """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
+ """
+ if filename.endswith('.py') or filename.endswith('.pyw'):
+ return True # extension says it's Python
+ if is_python(script_text, filename):
+ return True # it's syntactically valid Python
+ if script_text.startswith('#!'):
+ # It begins with a '#!' line, so check if 'python' is in it somewhere
+ return 'python' in script_text.splitlines()[0].lower()
+
+ return False # Not any Python I can recognize
+
+
+try:
+ from os import chmod as _chmod
+except ImportError:
+ # Jython compatibility
+ def _chmod(*args):
+ pass
+
+
+def chmod(path, mode):
+ log.debug("changing mode of %s to %o", path, mode)
+ try:
+ _chmod(path, mode)
+ except os.error as e:
+ log.debug("chmod failed: %s", e)
+
+
+class CommandSpec(list):
+ """
+ A command spec for a #! header, specified as a list of arguments akin to
+ those passed to Popen.
+ """
+
+ options = []
+ split_args = dict()
+
+ @classmethod
+ def best(cls):
+ """
+ Choose the best CommandSpec class based on environmental conditions.
+ """
+ return cls
+
+ @classmethod
+ def _sys_executable(cls):
+ _default = os.path.normpath(sys.executable)
+ return os.environ.get('__PYVENV_LAUNCHER__', _default)
+
+ @classmethod
+ def from_param(cls, param):
+ """
+ Construct a CommandSpec from a parameter to build_scripts, which may
+ be None.
+ """
+ if isinstance(param, cls):
+ return param
+ if isinstance(param, list):
+ return cls(param)
+ if param is None:
+ return cls.from_environment()
+ # otherwise, assume it's a string.
+ return cls.from_string(param)
+
+ @classmethod
+ def from_environment(cls):
+ return cls([cls._sys_executable()])
+
+ @classmethod
+ def from_string(cls, string):
+ """
+ Construct a command spec from a simple string representing a command
+ line parseable by shlex.split.
+ """
+ items = shlex.split(string, **cls.split_args)
+ return cls(items)
+
+ def install_options(self, script_text):
+ self.options = shlex.split(self._extract_options(script_text))
+ cmdline = subprocess.list2cmdline(self)
+ if not isascii(cmdline):
+ self.options[:0] = ['-x']
+
+ @staticmethod
+ def _extract_options(orig_script):
+ """
+ Extract any options from the first line of the script.
+ """
+ first = (orig_script + '\n').splitlines()[0]
+ match = _first_line_re().match(first)
+ options = match.group(1) or '' if match else ''
+ return options.strip()
+
+ def as_header(self):
+ return self._render(self + list(self.options))
+
+ @staticmethod
def _strip_quotes(item):
_QUOTES = '"\''
for q in _QUOTES:
@@ -2046,301 +2046,301 @@ class CommandSpec(list):
return item
@staticmethod
- def _render(items):
+ def _render(items):
cmdline = subprocess.list2cmdline(
CommandSpec._strip_quotes(item.strip()) for item in items)
- return '#!' + cmdline + '\n'
-
-
-# For pbr compat; will be removed in a future version.
-sys_executable = CommandSpec._sys_executable()
-
-
-class WindowsCommandSpec(CommandSpec):
- split_args = dict(posix=False)
-
-
+ return '#!' + cmdline + '\n'
+
+
+# For pbr compat; will be removed in a future version.
+sys_executable = CommandSpec._sys_executable()
+
+
+class WindowsCommandSpec(CommandSpec):
+ split_args = dict(posix=False)
+
+
class ScriptWriter:
- """
- Encapsulates behavior around writing entry point scripts for console and
- gui apps.
- """
-
+ """
+ Encapsulates behavior around writing entry point scripts for console and
+ gui apps.
+ """
+
template = textwrap.dedent(r"""
- # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r
- __requires__ = %(spec)r
+ # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r
+ __requires__ = %(spec)r
import re
- import sys
- from pkg_resources import load_entry_point
-
- if __name__ == '__main__':
+ import sys
+ from pkg_resources import load_entry_point
+
+ if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
- sys.exit(
- load_entry_point(%(spec)r, %(group)r, %(name)r)()
- )
- """).lstrip()
-
- command_spec_class = CommandSpec
-
- @classmethod
- def get_script_args(cls, dist, executable=None, wininst=False):
- # for backward compatibility
+ sys.exit(
+ load_entry_point(%(spec)r, %(group)r, %(name)r)()
+ )
+ """).lstrip()
+
+ command_spec_class = CommandSpec
+
+ @classmethod
+ def get_script_args(cls, dist, executable=None, wininst=False):
+ # for backward compatibility
warnings.warn("Use get_args", EasyInstallDeprecationWarning)
- writer = (WindowsScriptWriter if wininst else ScriptWriter).best()
- header = cls.get_script_header("", executable, wininst)
- return writer.get_args(dist, header)
-
- @classmethod
- def get_script_header(cls, script_text, executable=None, wininst=False):
- # for backward compatibility
+ writer = (WindowsScriptWriter if wininst else ScriptWriter).best()
+ header = cls.get_script_header("", executable, wininst)
+ return writer.get_args(dist, header)
+
+ @classmethod
+ def get_script_header(cls, script_text, executable=None, wininst=False):
+ # for backward compatibility
warnings.warn("Use get_header", EasyInstallDeprecationWarning, stacklevel=2)
- if wininst:
- executable = "python.exe"
+ if wininst:
+ executable = "python.exe"
return cls.get_header(script_text, executable)
-
- @classmethod
- def get_args(cls, dist, header=None):
- """
- Yield write_script() argument tuples for a distribution's
- console_scripts and gui_scripts entry points.
- """
- if header is None:
- header = cls.get_header()
- spec = str(dist.as_requirement())
- for type_ in 'console', 'gui':
- group = type_ + '_scripts'
- for name, ep in dist.get_entry_map(group).items():
- cls._ensure_safe_name(name)
- script_text = cls.template % locals()
- args = cls._get_script_args(type_, name, header, script_text)
- for res in args:
- yield res
-
- @staticmethod
- def _ensure_safe_name(name):
- """
- Prevent paths in *_scripts entry point names.
- """
- has_path_sep = re.search(r'[\\/]', name)
- if has_path_sep:
- raise ValueError("Path separators not allowed in script names")
-
- @classmethod
- def get_writer(cls, force_windows):
- # for backward compatibility
+
+ @classmethod
+ def get_args(cls, dist, header=None):
+ """
+ Yield write_script() argument tuples for a distribution's
+ console_scripts and gui_scripts entry points.
+ """
+ if header is None:
+ header = cls.get_header()
+ spec = str(dist.as_requirement())
+ for type_ in 'console', 'gui':
+ group = type_ + '_scripts'
+ for name, ep in dist.get_entry_map(group).items():
+ cls._ensure_safe_name(name)
+ script_text = cls.template % locals()
+ args = cls._get_script_args(type_, name, header, script_text)
+ for res in args:
+ yield res
+
+ @staticmethod
+ def _ensure_safe_name(name):
+ """
+ Prevent paths in *_scripts entry point names.
+ """
+ has_path_sep = re.search(r'[\\/]', name)
+ if has_path_sep:
+ raise ValueError("Path separators not allowed in script names")
+
+ @classmethod
+ def get_writer(cls, force_windows):
+ # for backward compatibility
warnings.warn("Use best", EasyInstallDeprecationWarning)
- return WindowsScriptWriter.best() if force_windows else cls.best()
-
- @classmethod
- def best(cls):
- """
- Select the best ScriptWriter for this environment.
- """
- if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):
- return WindowsScriptWriter.best()
- else:
- return cls
-
- @classmethod
- def _get_script_args(cls, type_, name, header, script_text):
- # Simply write the stub with no extension.
- yield (name, header + script_text)
-
- @classmethod
- def get_header(cls, script_text="", executable=None):
- """Create a #! line, getting options (if any) from script_text"""
- cmd = cls.command_spec_class.best().from_param(executable)
- cmd.install_options(script_text)
- return cmd.as_header()
-
-
-class WindowsScriptWriter(ScriptWriter):
- command_spec_class = WindowsCommandSpec
-
- @classmethod
- def get_writer(cls):
- # for backward compatibility
+ return WindowsScriptWriter.best() if force_windows else cls.best()
+
+ @classmethod
+ def best(cls):
+ """
+ Select the best ScriptWriter for this environment.
+ """
+ if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):
+ return WindowsScriptWriter.best()
+ else:
+ return cls
+
+ @classmethod
+ def _get_script_args(cls, type_, name, header, script_text):
+ # Simply write the stub with no extension.
+ yield (name, header + script_text)
+
+ @classmethod
+ def get_header(cls, script_text="", executable=None):
+ """Create a #! line, getting options (if any) from script_text"""
+ cmd = cls.command_spec_class.best().from_param(executable)
+ cmd.install_options(script_text)
+ return cmd.as_header()
+
+
+class WindowsScriptWriter(ScriptWriter):
+ command_spec_class = WindowsCommandSpec
+
+ @classmethod
+ def get_writer(cls):
+ # for backward compatibility
warnings.warn("Use best", EasyInstallDeprecationWarning)
- return cls.best()
-
- @classmethod
- def best(cls):
- """
- Select the best ScriptWriter suitable for Windows
- """
- writer_lookup = dict(
- executable=WindowsExecutableLauncherWriter,
- natural=cls,
- )
- # for compatibility, use the executable launcher by default
- launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable')
- return writer_lookup[launcher]
-
- @classmethod
- def _get_script_args(cls, type_, name, header, script_text):
- "For Windows, add a .py extension"
- ext = dict(console='.pya', gui='.pyw')[type_]
- if ext not in os.environ['PATHEXT'].lower().split(';'):
+ return cls.best()
+
+ @classmethod
+ def best(cls):
+ """
+ Select the best ScriptWriter suitable for Windows
+ """
+ writer_lookup = dict(
+ executable=WindowsExecutableLauncherWriter,
+ natural=cls,
+ )
+ # for compatibility, use the executable launcher by default
+ launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable')
+ return writer_lookup[launcher]
+
+ @classmethod
+ def _get_script_args(cls, type_, name, header, script_text):
+ "For Windows, add a .py extension"
+ ext = dict(console='.pya', gui='.pyw')[type_]
+ if ext not in os.environ['PATHEXT'].lower().split(';'):
msg = (
"{ext} not listed in PATHEXT; scripts will not be "
"recognized as executables."
).format(**locals())
warnings.warn(msg, UserWarning)
- old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
- old.remove(ext)
- header = cls._adjust_header(type_, header)
- blockers = [name + x for x in old]
- yield name + ext, header + script_text, 't', blockers
-
- @classmethod
- def _adjust_header(cls, type_, orig_header):
- """
- Make sure 'pythonw' is used for gui and and 'python' is used for
- console (regardless of what sys.executable is).
- """
- pattern = 'pythonw.exe'
- repl = 'python.exe'
- if type_ == 'gui':
- pattern, repl = repl, pattern
- pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE)
- new_header = pattern_ob.sub(string=orig_header, repl=repl)
- return new_header if cls._use_header(new_header) else orig_header
-
- @staticmethod
- def _use_header(new_header):
- """
- Should _adjust_header use the replaced header?
-
- On non-windows systems, always use. On
- Windows systems, only use the replaced header if it resolves
- to an executable on the system.
- """
- clean_header = new_header[2:-1].strip('"')
- return sys.platform != 'win32' or find_executable(clean_header)
-
-
-class WindowsExecutableLauncherWriter(WindowsScriptWriter):
- @classmethod
- def _get_script_args(cls, type_, name, header, script_text):
- """
- For Windows, add a .py extension and an .exe launcher
- """
- if type_ == 'gui':
- launcher_type = 'gui'
- ext = '-script.pyw'
- old = ['.pyw']
- else:
- launcher_type = 'cli'
- ext = '-script.py'
- old = ['.py', '.pyc', '.pyo']
- hdr = cls._adjust_header(type_, header)
- blockers = [name + x for x in old]
- yield (name + ext, hdr + script_text, 't', blockers)
- yield (
- name + '.exe', get_win_launcher(launcher_type),
- 'b' # write in binary mode
- )
- if not is_64bit():
- # install a manifest for the launcher to prevent Windows
- # from detecting it as an installer (which it will for
- # launchers like easy_install.exe). Consider only
- # adding a manifest for launchers detected as installers.
- # See Distribute #143 for details.
- m_name = name + '.exe.manifest'
- yield (m_name, load_launcher_manifest(name), 't')
-
-
-# for backward-compatibility
-get_script_args = ScriptWriter.get_script_args
-get_script_header = ScriptWriter.get_script_header
-
-
-def get_win_launcher(type):
- """
- Load the Windows launcher (executable) suitable for launching a script.
-
- `type` should be either 'cli' or 'gui'
-
- Returns the executable as a byte string.
- """
- launcher_fn = '%s.exe' % type
- if is_64bit():
- launcher_fn = launcher_fn.replace(".", "-64.")
- else:
- launcher_fn = launcher_fn.replace(".", "-32.")
- return resource_string('setuptools', launcher_fn)
-
-
-def load_launcher_manifest(name):
- manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')
- if six.PY2:
- return manifest % vars()
- else:
- return manifest.decode('utf-8') % vars()
-
-
-def rmtree(path, ignore_errors=False, onerror=auto_chmod):
+ old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
+ old.remove(ext)
+ header = cls._adjust_header(type_, header)
+ blockers = [name + x for x in old]
+ yield name + ext, header + script_text, 't', blockers
+
+ @classmethod
+ def _adjust_header(cls, type_, orig_header):
+ """
+ Make sure 'pythonw' is used for gui and and 'python' is used for
+ console (regardless of what sys.executable is).
+ """
+ pattern = 'pythonw.exe'
+ repl = 'python.exe'
+ if type_ == 'gui':
+ pattern, repl = repl, pattern
+ pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE)
+ new_header = pattern_ob.sub(string=orig_header, repl=repl)
+ return new_header if cls._use_header(new_header) else orig_header
+
+ @staticmethod
+ def _use_header(new_header):
+ """
+ Should _adjust_header use the replaced header?
+
+ On non-windows systems, always use. On
+ Windows systems, only use the replaced header if it resolves
+ to an executable on the system.
+ """
+ clean_header = new_header[2:-1].strip('"')
+ return sys.platform != 'win32' or find_executable(clean_header)
+
+
+class WindowsExecutableLauncherWriter(WindowsScriptWriter):
+ @classmethod
+ def _get_script_args(cls, type_, name, header, script_text):
+ """
+ For Windows, add a .py extension and an .exe launcher
+ """
+ if type_ == 'gui':
+ launcher_type = 'gui'
+ ext = '-script.pyw'
+ old = ['.pyw']
+ else:
+ launcher_type = 'cli'
+ ext = '-script.py'
+ old = ['.py', '.pyc', '.pyo']
+ hdr = cls._adjust_header(type_, header)
+ blockers = [name + x for x in old]
+ yield (name + ext, hdr + script_text, 't', blockers)
+ yield (
+ name + '.exe', get_win_launcher(launcher_type),
+ 'b' # write in binary mode
+ )
+ if not is_64bit():
+ # install a manifest for the launcher to prevent Windows
+ # from detecting it as an installer (which it will for
+ # launchers like easy_install.exe). Consider only
+ # adding a manifest for launchers detected as installers.
+ # See Distribute #143 for details.
+ m_name = name + '.exe.manifest'
+ yield (m_name, load_launcher_manifest(name), 't')
+
+
+# for backward-compatibility
+get_script_args = ScriptWriter.get_script_args
+get_script_header = ScriptWriter.get_script_header
+
+
+def get_win_launcher(type):
+ """
+ Load the Windows launcher (executable) suitable for launching a script.
+
+ `type` should be either 'cli' or 'gui'
+
+ Returns the executable as a byte string.
+ """
+ launcher_fn = '%s.exe' % type
+ if is_64bit():
+ launcher_fn = launcher_fn.replace(".", "-64.")
+ else:
+ launcher_fn = launcher_fn.replace(".", "-32.")
+ return resource_string('setuptools', launcher_fn)
+
+
+def load_launcher_manifest(name):
+ manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')
+ if six.PY2:
+ return manifest % vars()
+ else:
+ return manifest.decode('utf-8') % vars()
+
+
+def rmtree(path, ignore_errors=False, onerror=auto_chmod):
return shutil.rmtree(path, ignore_errors, onerror)
-
-
-def current_umask():
- tmp = os.umask(0o022)
- os.umask(tmp)
- return tmp
-
-
-def bootstrap():
- # This function is called when setuptools*.egg is run using /bin/sh
- import setuptools
-
- argv0 = os.path.dirname(setuptools.__path__[0])
- sys.argv[0] = argv0
- sys.argv.append(argv0)
- main()
-
-
-def main(argv=None, **kw):
- from setuptools import setup
- from setuptools.dist import Distribution
-
- class DistributionWithoutHelpCommands(Distribution):
- common_usage = ""
-
- def _show_help(self, *args, **kw):
- with _patch_usage():
- Distribution._show_help(self, *args, **kw)
-
- if argv is None:
- argv = sys.argv[1:]
-
- with _patch_usage():
- setup(
- script_args=['-q', 'easy_install', '-v'] + argv,
- script_name=sys.argv[0] or 'easy_install',
+
+
+def current_umask():
+ tmp = os.umask(0o022)
+ os.umask(tmp)
+ return tmp
+
+
+def bootstrap():
+ # This function is called when setuptools*.egg is run using /bin/sh
+ import setuptools
+
+ argv0 = os.path.dirname(setuptools.__path__[0])
+ sys.argv[0] = argv0
+ sys.argv.append(argv0)
+ main()
+
+
+def main(argv=None, **kw):
+ from setuptools import setup
+ from setuptools.dist import Distribution
+
+ class DistributionWithoutHelpCommands(Distribution):
+ common_usage = ""
+
+ def _show_help(self, *args, **kw):
+ with _patch_usage():
+ Distribution._show_help(self, *args, **kw)
+
+ if argv is None:
+ argv = sys.argv[1:]
+
+ with _patch_usage():
+ setup(
+ script_args=['-q', 'easy_install', '-v'] + argv,
+ script_name=sys.argv[0] or 'easy_install',
distclass=DistributionWithoutHelpCommands,
**kw
- )
-
-
-@contextlib.contextmanager
-def _patch_usage():
- import distutils.core
- USAGE = textwrap.dedent("""
- usage: %(script)s [options] requirement_or_url ...
- or: %(script)s --help
- """).lstrip()
-
- def gen_usage(script_name):
- return USAGE % dict(
- script=os.path.basename(script_name),
- )
-
- saved = distutils.core.gen_usage
- distutils.core.gen_usage = gen_usage
- try:
- yield
- finally:
- distutils.core.gen_usage = saved
+ )
+
+
+@contextlib.contextmanager
+def _patch_usage():
+ import distutils.core
+ USAGE = textwrap.dedent("""
+ usage: %(script)s [options] requirement_or_url ...
+ or: %(script)s --help
+ """).lstrip()
+
+ def gen_usage(script_name):
+ return USAGE % dict(
+ script=os.path.basename(script_name),
+ )
+
+ saved = distutils.core.gen_usage
+ distutils.core.gen_usage = gen_usage
+ try:
+ yield
+ finally:
+ distutils.core.gen_usage = saved
class EasyInstallDeprecationWarning(SetuptoolsDeprecationWarning):
"""Class for warning about deprecations in EasyInstall in SetupTools. Not ignored by default, unlike DeprecationWarning."""
diff --git a/contrib/python/setuptools/py2/setuptools/command/egg_info.py b/contrib/python/setuptools/py2/setuptools/command/egg_info.py
index 9760018aed..a5c5a2fc19 100644
--- a/contrib/python/setuptools/py2/setuptools/command/egg_info.py
+++ b/contrib/python/setuptools/py2/setuptools/command/egg_info.py
@@ -1,38 +1,38 @@
-"""setuptools.command.egg_info
-
-Create a distribution's .egg-info directory and contents"""
-
-from distutils.filelist import FileList as _FileList
+"""setuptools.command.egg_info
+
+Create a distribution's .egg-info directory and contents"""
+
+from distutils.filelist import FileList as _FileList
from distutils.errors import DistutilsInternalError
-from distutils.util import convert_path
-from distutils import log
-import distutils.errors
-import distutils.filelist
-import os
-import re
-import sys
-import io
-import warnings
-import time
+from distutils.util import convert_path
+from distutils import log
+import distutils.errors
+import distutils.filelist
+import os
+import re
+import sys
+import io
+import warnings
+import time
import collections
-
+
from setuptools.extern import six
from setuptools.extern.six.moves import map
-
-from setuptools import Command
-from setuptools.command.sdist import sdist
-from setuptools.command.sdist import walk_revctrl
-from setuptools.command.setopt import edit_config
-from setuptools.command import bdist_egg
-from pkg_resources import (
- parse_requirements, safe_name, parse_version,
- safe_version, yield_lines, EntryPoint, iter_entry_points, to_filename)
-import setuptools.unicode_utils as unicode_utils
+
+from setuptools import Command
+from setuptools.command.sdist import sdist
+from setuptools.command.sdist import walk_revctrl
+from setuptools.command.setopt import edit_config
+from setuptools.command import bdist_egg
+from pkg_resources import (
+ parse_requirements, safe_name, parse_version,
+ safe_version, yield_lines, EntryPoint, iter_entry_points, to_filename)
+import setuptools.unicode_utils as unicode_utils
from setuptools.glob import glob
-
+
from setuptools.extern import packaging
from setuptools import SetuptoolsDeprecationWarning
-
+
def translate_pattern(glob):
"""
Translate a file path glob like '*.txt' in to a regular expression.
@@ -41,7 +41,7 @@ def translate_pattern(glob):
directories.
"""
pat = ''
-
+
# This will split on '/' within [character classes]. This is deliberate.
chunks = glob.split(os.path.sep)
@@ -143,28 +143,28 @@ class InfoCommon:
class egg_info(InfoCommon, Command):
- description = "create a distribution's .egg-info directory"
-
- user_options = [
- ('egg-base=', 'e', "directory containing .egg-info directories"
- " (default: top of the source tree)"),
- ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
- ('tag-build=', 'b', "Specify explicit tag to add to version number"),
- ('no-date', 'D', "Don't include date stamp [default]"),
- ]
-
+ description = "create a distribution's .egg-info directory"
+
+ user_options = [
+ ('egg-base=', 'e', "directory containing .egg-info directories"
+ " (default: top of the source tree)"),
+ ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
+ ('tag-build=', 'b', "Specify explicit tag to add to version number"),
+ ('no-date', 'D', "Don't include date stamp [default]"),
+ ]
+
boolean_options = ['tag-date']
negative_opt = {
'no-date': 'tag-date',
}
-
- def initialize_options(self):
+
+ def initialize_options(self):
self.egg_base = None
- self.egg_name = None
+ self.egg_name = None
self.egg_info = None
- self.egg_version = None
- self.broken_egg_info = False
-
+ self.egg_version = None
+ self.broken_egg_info = False
+
####################################
# allow the 'tag_svn_revision' to be detected and
# set, supporting sdists built on older Setuptools.
@@ -177,7 +177,7 @@ class egg_info(InfoCommon, Command):
pass
####################################
- def save_version_info(self, filename):
+ def save_version_info(self, filename):
"""
Materialize the value of date into the
build tag. Install build keys in a deterministic order
@@ -189,139 +189,139 @@ class egg_info(InfoCommon, Command):
egg_info['tag_build'] = self.tags()
egg_info['tag_date'] = 0
edit_config(filename, dict(egg_info=egg_info))
-
- def finalize_options(self):
+
+ def finalize_options(self):
# Note: we need to capture the current value returned
# by `self.tagged_version()`, so we can later update
# `self.distribution.metadata.version` without
# repercussions.
self.egg_name = self.name
- self.egg_version = self.tagged_version()
- parsed_version = parse_version(self.egg_version)
-
- try:
- is_version = isinstance(parsed_version, packaging.version.Version)
- spec = (
- "%s==%s" if is_version else "%s===%s"
- )
- list(
- parse_requirements(spec % (self.egg_name, self.egg_version))
- )
- except ValueError:
- raise distutils.errors.DistutilsOptionError(
- "Invalid distribution name or version syntax: %s-%s" %
- (self.egg_name, self.egg_version)
- )
-
- if self.egg_base is None:
- dirs = self.distribution.package_dir
- self.egg_base = (dirs or {}).get('', os.curdir)
-
- self.ensure_dirname('egg_base')
- self.egg_info = to_filename(self.egg_name) + '.egg-info'
- if self.egg_base != os.curdir:
- self.egg_info = os.path.join(self.egg_base, self.egg_info)
- if '-' in self.egg_name:
- self.check_broken_egg_info()
-
- # Set package version for the benefit of dumber commands
- # (e.g. sdist, bdist_wininst, etc.)
- #
- self.distribution.metadata.version = self.egg_version
-
- # If we bootstrapped around the lack of a PKG-INFO, as might be the
- # case in a fresh checkout, make sure that any special tags get added
- # to the version info
- #
- pd = self.distribution._patched_dist
- if pd is not None and pd.key == self.egg_name.lower():
- pd._version = self.egg_version
- pd._parsed_version = parse_version(self.egg_version)
- self.distribution._patched_dist = None
-
- def write_or_delete_file(self, what, filename, data, force=False):
- """Write `data` to `filename` or delete if empty
-
- If `data` is non-empty, this routine is the same as ``write_file()``.
- If `data` is empty but not ``None``, this is the same as calling
- ``delete_file(filename)`. If `data` is ``None``, then this is a no-op
- unless `filename` exists, in which case a warning is issued about the
- orphaned file (if `force` is false), or deleted (if `force` is true).
- """
- if data:
- self.write_file(what, filename, data)
- elif os.path.exists(filename):
- if data is None and not force:
- log.warn(
- "%s not set in setup(), but %s exists", what, filename
- )
- return
- else:
- self.delete_file(filename)
-
- def write_file(self, what, filename, data):
- """Write `data` to `filename` (if not a dry run) after announcing it
-
- `what` is used in a log message to identify what is being written
- to the file.
- """
- log.info("writing %s to %s", what, filename)
+ self.egg_version = self.tagged_version()
+ parsed_version = parse_version(self.egg_version)
+
+ try:
+ is_version = isinstance(parsed_version, packaging.version.Version)
+ spec = (
+ "%s==%s" if is_version else "%s===%s"
+ )
+ list(
+ parse_requirements(spec % (self.egg_name, self.egg_version))
+ )
+ except ValueError:
+ raise distutils.errors.DistutilsOptionError(
+ "Invalid distribution name or version syntax: %s-%s" %
+ (self.egg_name, self.egg_version)
+ )
+
+ if self.egg_base is None:
+ dirs = self.distribution.package_dir
+ self.egg_base = (dirs or {}).get('', os.curdir)
+
+ self.ensure_dirname('egg_base')
+ self.egg_info = to_filename(self.egg_name) + '.egg-info'
+ if self.egg_base != os.curdir:
+ self.egg_info = os.path.join(self.egg_base, self.egg_info)
+ if '-' in self.egg_name:
+ self.check_broken_egg_info()
+
+ # Set package version for the benefit of dumber commands
+ # (e.g. sdist, bdist_wininst, etc.)
+ #
+ self.distribution.metadata.version = self.egg_version
+
+ # If we bootstrapped around the lack of a PKG-INFO, as might be the
+ # case in a fresh checkout, make sure that any special tags get added
+ # to the version info
+ #
+ pd = self.distribution._patched_dist
+ if pd is not None and pd.key == self.egg_name.lower():
+ pd._version = self.egg_version
+ pd._parsed_version = parse_version(self.egg_version)
+ self.distribution._patched_dist = None
+
+ def write_or_delete_file(self, what, filename, data, force=False):
+ """Write `data` to `filename` or delete if empty
+
+ If `data` is non-empty, this routine is the same as ``write_file()``.
+ If `data` is empty but not ``None``, this is the same as calling
+ ``delete_file(filename)`. If `data` is ``None``, then this is a no-op
+ unless `filename` exists, in which case a warning is issued about the
+ orphaned file (if `force` is false), or deleted (if `force` is true).
+ """
+ if data:
+ self.write_file(what, filename, data)
+ elif os.path.exists(filename):
+ if data is None and not force:
+ log.warn(
+ "%s not set in setup(), but %s exists", what, filename
+ )
+ return
+ else:
+ self.delete_file(filename)
+
+ def write_file(self, what, filename, data):
+ """Write `data` to `filename` (if not a dry run) after announcing it
+
+ `what` is used in a log message to identify what is being written
+ to the file.
+ """
+ log.info("writing %s to %s", what, filename)
if not six.PY2:
- data = data.encode("utf-8")
- if not self.dry_run:
- f = open(filename, 'wb')
- f.write(data)
- f.close()
-
- def delete_file(self, filename):
- """Delete `filename` (if not a dry run) after announcing it"""
- log.info("deleting %s", filename)
- if not self.dry_run:
- os.unlink(filename)
-
- def run(self):
- self.mkpath(self.egg_info)
+ data = data.encode("utf-8")
+ if not self.dry_run:
+ f = open(filename, 'wb')
+ f.write(data)
+ f.close()
+
+ def delete_file(self, filename):
+ """Delete `filename` (if not a dry run) after announcing it"""
+ log.info("deleting %s", filename)
+ if not self.dry_run:
+ os.unlink(filename)
+
+ def run(self):
+ self.mkpath(self.egg_info)
os.utime(self.egg_info, None)
- installer = self.distribution.fetch_build_egg
- for ep in iter_entry_points('egg_info.writers'):
- ep.require(installer=installer)
- writer = ep.resolve()
- writer(self, ep.name, os.path.join(self.egg_info, ep.name))
-
- # Get rid of native_libs.txt if it was put there by older bdist_egg
- nl = os.path.join(self.egg_info, "native_libs.txt")
- if os.path.exists(nl):
- self.delete_file(nl)
-
- self.find_sources()
-
- def find_sources(self):
- """Generate SOURCES.txt manifest file"""
- manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
- mm = manifest_maker(self.distribution)
- mm.manifest = manifest_filename
- mm.run()
- self.filelist = mm.filelist
-
- def check_broken_egg_info(self):
- bei = self.egg_name + '.egg-info'
- if self.egg_base != os.curdir:
- bei = os.path.join(self.egg_base, bei)
- if os.path.exists(bei):
- log.warn(
- "-" * 78 + '\n'
- "Note: Your current .egg-info directory has a '-' in its name;"
- '\nthis will not work correctly with "setup.py develop".\n\n'
- 'Please rename %s to %s to correct this problem.\n' + '-' * 78,
- bei, self.egg_info
- )
- self.broken_egg_info = self.egg_info
- self.egg_info = bei # make it work for now
-
-
-class FileList(_FileList):
+ installer = self.distribution.fetch_build_egg
+ for ep in iter_entry_points('egg_info.writers'):
+ ep.require(installer=installer)
+ writer = ep.resolve()
+ writer(self, ep.name, os.path.join(self.egg_info, ep.name))
+
+ # Get rid of native_libs.txt if it was put there by older bdist_egg
+ nl = os.path.join(self.egg_info, "native_libs.txt")
+ if os.path.exists(nl):
+ self.delete_file(nl)
+
+ self.find_sources()
+
+ def find_sources(self):
+ """Generate SOURCES.txt manifest file"""
+ manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
+ mm = manifest_maker(self.distribution)
+ mm.manifest = manifest_filename
+ mm.run()
+ self.filelist = mm.filelist
+
+ def check_broken_egg_info(self):
+ bei = self.egg_name + '.egg-info'
+ if self.egg_base != os.curdir:
+ bei = os.path.join(self.egg_base, bei)
+ if os.path.exists(bei):
+ log.warn(
+ "-" * 78 + '\n'
+ "Note: Your current .egg-info directory has a '-' in its name;"
+ '\nthis will not work correctly with "setup.py develop".\n\n'
+ 'Please rename %s to %s to correct this problem.\n' + '-' * 78,
+ bei, self.egg_info
+ )
+ self.broken_egg_info = self.egg_info
+ self.egg_info = bei # make it work for now
+
+
+class FileList(_FileList):
# Implementations of the various MANIFEST.in commands
-
+
def process_template_line(self, line):
# Parse the line: split it up, make sure the right number of words
# is there, and return the relevant words. 'action' is always
@@ -470,95 +470,95 @@ class FileList(_FileList):
match = translate_pattern(os.path.join('**', pattern))
return self._remove_files(match.match)
- def append(self, item):
- if item.endswith('\r'): # Fix older sdists built on Windows
- item = item[:-1]
- path = convert_path(item)
-
- if self._safe_path(path):
- self.files.append(path)
-
- def extend(self, paths):
- self.files.extend(filter(self._safe_path, paths))
-
- def _repair(self):
- """
- Replace self.files with only safe paths
-
- Because some owners of FileList manipulate the underlying
- ``files`` attribute directly, this method must be called to
- repair those paths.
- """
- self.files = list(filter(self._safe_path, self.files))
-
- def _safe_path(self, path):
- enc_warn = "'%s' not %s encodable -- skipping"
-
- # To avoid accidental trans-codings errors, first to unicode
- u_path = unicode_utils.filesys_decode(path)
- if u_path is None:
- log.warn("'%s' in unexpected encoding -- skipping" % path)
- return False
-
- # Must ensure utf-8 encodability
- utf8_path = unicode_utils.try_encode(u_path, "utf-8")
- if utf8_path is None:
- log.warn(enc_warn, path, 'utf-8')
- return False
-
- try:
- # accept is either way checks out
- if os.path.exists(u_path) or os.path.exists(utf8_path):
- return True
- # this will catch any encode errors decoding u_path
- except UnicodeEncodeError:
- log.warn(enc_warn, path, sys.getfilesystemencoding())
-
-
-class manifest_maker(sdist):
- template = "MANIFEST.in"
-
- def initialize_options(self):
- self.use_defaults = 1
- self.prune = 1
- self.manifest_only = 1
- self.force_manifest = 1
-
- def finalize_options(self):
- pass
-
- def run(self):
- self.filelist = FileList()
- if not os.path.exists(self.manifest):
- self.write_manifest() # it must exist so it'll get in the list
- self.add_defaults()
- if os.path.exists(self.template):
- self.read_template()
- self.prune_file_list()
- self.filelist.sort()
- self.filelist.remove_duplicates()
- self.write_manifest()
-
- def _manifest_normalize(self, path):
- path = unicode_utils.filesys_decode(path)
- return path.replace(os.sep, '/')
-
- def write_manifest(self):
- """
- Write the file list in 'self.filelist' to the manifest file
- named by 'self.manifest'.
- """
- self.filelist._repair()
-
- # Now _repairs should encodability, but not unicode
- files = [self._manifest_normalize(f) for f in self.filelist.files]
- msg = "writing manifest file '%s'" % self.manifest
- self.execute(write_file, (self.manifest, files), msg)
-
+ def append(self, item):
+ if item.endswith('\r'): # Fix older sdists built on Windows
+ item = item[:-1]
+ path = convert_path(item)
+
+ if self._safe_path(path):
+ self.files.append(path)
+
+ def extend(self, paths):
+ self.files.extend(filter(self._safe_path, paths))
+
+ def _repair(self):
+ """
+ Replace self.files with only safe paths
+
+ Because some owners of FileList manipulate the underlying
+ ``files`` attribute directly, this method must be called to
+ repair those paths.
+ """
+ self.files = list(filter(self._safe_path, self.files))
+
+ def _safe_path(self, path):
+ enc_warn = "'%s' not %s encodable -- skipping"
+
+ # To avoid accidental trans-codings errors, first to unicode
+ u_path = unicode_utils.filesys_decode(path)
+ if u_path is None:
+ log.warn("'%s' in unexpected encoding -- skipping" % path)
+ return False
+
+ # Must ensure utf-8 encodability
+ utf8_path = unicode_utils.try_encode(u_path, "utf-8")
+ if utf8_path is None:
+ log.warn(enc_warn, path, 'utf-8')
+ return False
+
+ try:
+ # accept is either way checks out
+ if os.path.exists(u_path) or os.path.exists(utf8_path):
+ return True
+ # this will catch any encode errors decoding u_path
+ except UnicodeEncodeError:
+ log.warn(enc_warn, path, sys.getfilesystemencoding())
+
+
+class manifest_maker(sdist):
+ template = "MANIFEST.in"
+
+ def initialize_options(self):
+ self.use_defaults = 1
+ self.prune = 1
+ self.manifest_only = 1
+ self.force_manifest = 1
+
+ def finalize_options(self):
+ pass
+
+ def run(self):
+ self.filelist = FileList()
+ if not os.path.exists(self.manifest):
+ self.write_manifest() # it must exist so it'll get in the list
+ self.add_defaults()
+ if os.path.exists(self.template):
+ self.read_template()
+ self.prune_file_list()
+ self.filelist.sort()
+ self.filelist.remove_duplicates()
+ self.write_manifest()
+
+ def _manifest_normalize(self, path):
+ path = unicode_utils.filesys_decode(path)
+ return path.replace(os.sep, '/')
+
+ def write_manifest(self):
+ """
+ Write the file list in 'self.filelist' to the manifest file
+ named by 'self.manifest'.
+ """
+ self.filelist._repair()
+
+ # Now _repairs should encodability, but not unicode
+ files = [self._manifest_normalize(f) for f in self.filelist.files]
+ msg = "writing manifest file '%s'" % self.manifest
+ self.execute(write_file, (self.manifest, files), msg)
+
def warn(self, msg):
if not self._should_suppress_warning(msg):
- sdist.warn(self, msg)
-
+ sdist.warn(self, msg)
+
@staticmethod
def _should_suppress_warning(msg):
"""
@@ -566,151 +566,151 @@ class manifest_maker(sdist):
"""
return re.match(r"standard file .*not found", msg)
- def add_defaults(self):
- sdist.add_defaults(self)
+ def add_defaults(self):
+ sdist.add_defaults(self)
self.check_license()
- self.filelist.append(self.template)
- self.filelist.append(self.manifest)
- rcfiles = list(walk_revctrl())
- if rcfiles:
- self.filelist.extend(rcfiles)
- elif os.path.exists(self.manifest):
- self.read_manifest()
+ self.filelist.append(self.template)
+ self.filelist.append(self.manifest)
+ rcfiles = list(walk_revctrl())
+ if rcfiles:
+ self.filelist.extend(rcfiles)
+ elif os.path.exists(self.manifest):
+ self.read_manifest()
if os.path.exists("setup.py"):
# setup.py should be included by default, even if it's not
# the script called to create the sdist
self.filelist.append("setup.py")
- ei_cmd = self.get_finalized_command('egg_info')
+ ei_cmd = self.get_finalized_command('egg_info')
self.filelist.graft(ei_cmd.egg_info)
-
- def prune_file_list(self):
- build = self.get_finalized_command('build')
- base_dir = self.distribution.get_fullname()
+
+ def prune_file_list(self):
+ build = self.get_finalized_command('build')
+ base_dir = self.distribution.get_fullname()
self.filelist.prune(build.build_base)
self.filelist.prune(base_dir)
- sep = re.escape(os.sep)
- self.filelist.exclude_pattern(r'(^|' + sep + r')(RCS|CVS|\.svn)' + sep,
- is_regex=1)
-
-
-def write_file(filename, contents):
- """Create a file with the specified name and write 'contents' (a
- sequence of strings without line terminators) to it.
- """
- contents = "\n".join(contents)
-
- # assuming the contents has been vetted for utf-8 encoding
- contents = contents.encode("utf-8")
-
- with open(filename, "wb") as f: # always write POSIX-style manifest
- f.write(contents)
-
-
-def write_pkg_info(cmd, basename, filename):
- log.info("writing %s", filename)
- if not cmd.dry_run:
- metadata = cmd.distribution.metadata
- metadata.version, oldver = cmd.egg_version, metadata.version
- metadata.name, oldname = cmd.egg_name, metadata.name
-
- try:
- # write unescaped data to PKG-INFO, so older pkg_resources
- # can still parse it
- metadata.write_pkg_info(cmd.egg_info)
- finally:
- metadata.name, metadata.version = oldname, oldver
-
- safe = getattr(cmd.distribution, 'zip_safe', None)
-
- bdist_egg.write_safety_flag(cmd.egg_info, safe)
-
-
-def warn_depends_obsolete(cmd, basename, filename):
- if os.path.exists(filename):
- log.warn(
- "WARNING: 'depends.txt' is not used by setuptools 0.6!\n"
- "Use the install_requires/extras_require setup() args instead."
- )
-
-
-def _write_requirements(stream, reqs):
- lines = yield_lines(reqs or ())
- append_cr = lambda line: line + '\n'
- lines = map(append_cr, lines)
- stream.writelines(lines)
-
-
-def write_requirements(cmd, basename, filename):
- dist = cmd.distribution
- data = six.StringIO()
- _write_requirements(data, dist.install_requires)
- extras_require = dist.extras_require or {}
- for extra in sorted(extras_require):
- data.write('\n[{extra}]\n'.format(**vars()))
- _write_requirements(data, extras_require[extra])
- cmd.write_or_delete_file("requirements", filename, data.getvalue())
-
-
-def write_setup_requirements(cmd, basename, filename):
+ sep = re.escape(os.sep)
+ self.filelist.exclude_pattern(r'(^|' + sep + r')(RCS|CVS|\.svn)' + sep,
+ is_regex=1)
+
+
+def write_file(filename, contents):
+ """Create a file with the specified name and write 'contents' (a
+ sequence of strings without line terminators) to it.
+ """
+ contents = "\n".join(contents)
+
+ # assuming the contents has been vetted for utf-8 encoding
+ contents = contents.encode("utf-8")
+
+ with open(filename, "wb") as f: # always write POSIX-style manifest
+ f.write(contents)
+
+
+def write_pkg_info(cmd, basename, filename):
+ log.info("writing %s", filename)
+ if not cmd.dry_run:
+ metadata = cmd.distribution.metadata
+ metadata.version, oldver = cmd.egg_version, metadata.version
+ metadata.name, oldname = cmd.egg_name, metadata.name
+
+ try:
+ # write unescaped data to PKG-INFO, so older pkg_resources
+ # can still parse it
+ metadata.write_pkg_info(cmd.egg_info)
+ finally:
+ metadata.name, metadata.version = oldname, oldver
+
+ safe = getattr(cmd.distribution, 'zip_safe', None)
+
+ bdist_egg.write_safety_flag(cmd.egg_info, safe)
+
+
+def warn_depends_obsolete(cmd, basename, filename):
+ if os.path.exists(filename):
+ log.warn(
+ "WARNING: 'depends.txt' is not used by setuptools 0.6!\n"
+ "Use the install_requires/extras_require setup() args instead."
+ )
+
+
+def _write_requirements(stream, reqs):
+ lines = yield_lines(reqs or ())
+ append_cr = lambda line: line + '\n'
+ lines = map(append_cr, lines)
+ stream.writelines(lines)
+
+
+def write_requirements(cmd, basename, filename):
+ dist = cmd.distribution
+ data = six.StringIO()
+ _write_requirements(data, dist.install_requires)
+ extras_require = dist.extras_require or {}
+ for extra in sorted(extras_require):
+ data.write('\n[{extra}]\n'.format(**vars()))
+ _write_requirements(data, extras_require[extra])
+ cmd.write_or_delete_file("requirements", filename, data.getvalue())
+
+
+def write_setup_requirements(cmd, basename, filename):
data = io.StringIO()
- _write_requirements(data, cmd.distribution.setup_requires)
- cmd.write_or_delete_file("setup-requirements", filename, data.getvalue())
-
-
-def write_toplevel_names(cmd, basename, filename):
- pkgs = dict.fromkeys(
- [
- k.split('.', 1)[0]
- for k in cmd.distribution.iter_distribution_names()
- ]
- )
- cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n')
-
-
-def overwrite_arg(cmd, basename, filename):
- write_arg(cmd, basename, filename, True)
-
-
-def write_arg(cmd, basename, filename, force=False):
- argname = os.path.splitext(basename)[0]
- value = getattr(cmd.distribution, argname, None)
- if value is not None:
- value = '\n'.join(value) + '\n'
- cmd.write_or_delete_file(argname, filename, value, force)
-
-
-def write_entries(cmd, basename, filename):
- ep = cmd.distribution.entry_points
-
- if isinstance(ep, six.string_types) or ep is None:
- data = ep
- elif ep is not None:
- data = []
- for section, contents in sorted(ep.items()):
- if not isinstance(contents, six.string_types):
- contents = EntryPoint.parse_group(section, contents)
- contents = '\n'.join(sorted(map(str, contents.values())))
- data.append('[%s]\n%s\n\n' % (section, contents))
- data = ''.join(data)
-
- cmd.write_or_delete_file('entry points', filename, data, True)
-
-
-def get_pkg_info_revision():
- """
- Get a -r### off of PKG-INFO Version in case this is an sdist of
- a subversion revision.
- """
+ _write_requirements(data, cmd.distribution.setup_requires)
+ cmd.write_or_delete_file("setup-requirements", filename, data.getvalue())
+
+
+def write_toplevel_names(cmd, basename, filename):
+ pkgs = dict.fromkeys(
+ [
+ k.split('.', 1)[0]
+ for k in cmd.distribution.iter_distribution_names()
+ ]
+ )
+ cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n')
+
+
+def overwrite_arg(cmd, basename, filename):
+ write_arg(cmd, basename, filename, True)
+
+
+def write_arg(cmd, basename, filename, force=False):
+ argname = os.path.splitext(basename)[0]
+ value = getattr(cmd.distribution, argname, None)
+ if value is not None:
+ value = '\n'.join(value) + '\n'
+ cmd.write_or_delete_file(argname, filename, value, force)
+
+
+def write_entries(cmd, basename, filename):
+ ep = cmd.distribution.entry_points
+
+ if isinstance(ep, six.string_types) or ep is None:
+ data = ep
+ elif ep is not None:
+ data = []
+ for section, contents in sorted(ep.items()):
+ if not isinstance(contents, six.string_types):
+ contents = EntryPoint.parse_group(section, contents)
+ contents = '\n'.join(sorted(map(str, contents.values())))
+ data.append('[%s]\n%s\n\n' % (section, contents))
+ data = ''.join(data)
+
+ cmd.write_or_delete_file('entry points', filename, data, True)
+
+
+def get_pkg_info_revision():
+ """
+ Get a -r### off of PKG-INFO Version in case this is an sdist of
+ a subversion revision.
+ """
warnings.warn("get_pkg_info_revision is deprecated.", EggInfoDeprecationWarning)
- if os.path.exists('PKG-INFO'):
- with io.open('PKG-INFO') as f:
- for line in f:
- match = re.match(r"Version:.*-r(\d+)\s*$", line)
- if match:
- return int(match.group(1))
- return 0
+ if os.path.exists('PKG-INFO'):
+ with io.open('PKG-INFO') as f:
+ for line in f:
+ match = re.match(r"Version:.*-r(\d+)\s*$", line)
+ if match:
+ return int(match.group(1))
+ return 0
class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning):
diff --git a/contrib/python/setuptools/py2/setuptools/command/install.py b/contrib/python/setuptools/py2/setuptools/command/install.py
index 236862a647..72b9a3e424 100644
--- a/contrib/python/setuptools/py2/setuptools/command/install.py
+++ b/contrib/python/setuptools/py2/setuptools/command/install.py
@@ -1,125 +1,125 @@
-from distutils.errors import DistutilsArgError
-import inspect
-import glob
-import warnings
-import platform
-import distutils.command.install as orig
-
-import setuptools
-
-# Prior to numpy 1.9, NumPy relies on the '_install' name, so provide it for
+from distutils.errors import DistutilsArgError
+import inspect
+import glob
+import warnings
+import platform
+import distutils.command.install as orig
+
+import setuptools
+
+# Prior to numpy 1.9, NumPy relies on the '_install' name, so provide it for
# now. See https://github.com/pypa/setuptools/issues/199/
-_install = orig.install
-
-
-class install(orig.install):
- """Use easy_install to install the package, w/dependencies"""
-
- user_options = orig.install.user_options + [
- ('old-and-unmanageable', None, "Try not to use this!"),
- ('single-version-externally-managed', None,
- "used by system package builders to create 'flat' eggs"),
- ]
- boolean_options = orig.install.boolean_options + [
- 'old-and-unmanageable', 'single-version-externally-managed',
- ]
- new_commands = [
- ('install_egg_info', lambda self: True),
- ('install_scripts', lambda self: True),
- ]
- _nc = dict(new_commands)
-
- def initialize_options(self):
- orig.install.initialize_options(self)
- self.old_and_unmanageable = None
- self.single_version_externally_managed = None
-
- def finalize_options(self):
- orig.install.finalize_options(self)
- if self.root:
- self.single_version_externally_managed = True
- elif self.single_version_externally_managed:
- if not self.root and not self.record:
- raise DistutilsArgError(
- "You must specify --record or --root when building system"
- " packages"
- )
-
- def handle_extra_path(self):
- if self.root or self.single_version_externally_managed:
- # explicit backward-compatibility mode, allow extra_path to work
- return orig.install.handle_extra_path(self)
-
- # Ignore extra_path when installing an egg (or being run by another
- # command without --root or --single-version-externally-managed
- self.path_file = None
- self.extra_dirs = ''
-
- def run(self):
- # Explicit request for old-style install? Just do it
- if self.old_and_unmanageable or self.single_version_externally_managed:
- return orig.install.run(self)
-
- if not self._called_from_setup(inspect.currentframe()):
- # Run in backward-compatibility mode to support bdist_* commands.
- orig.install.run(self)
- else:
- self.do_egg_install()
-
- @staticmethod
- def _called_from_setup(run_frame):
- """
- Attempt to detect whether run() was called from setup() or by another
- command. If called by setup(), the parent caller will be the
- 'run_command' method in 'distutils.dist', and *its* caller will be
- the 'run_commands' method. If called any other way, the
- immediate caller *might* be 'run_command', but it won't have been
- called by 'run_commands'. Return True in that case or if a call stack
- is unavailable. Return False otherwise.
- """
- if run_frame is None:
- msg = "Call stack not available. bdist_* commands may fail."
- warnings.warn(msg)
- if platform.python_implementation() == 'IronPython':
- msg = "For best results, pass -X:Frames to enable call stack."
- warnings.warn(msg)
- return True
- res = inspect.getouterframes(run_frame)[2]
- caller, = res[:1]
- info = inspect.getframeinfo(caller)
- caller_module = caller.f_globals.get('__name__', '')
- return (
- caller_module == 'distutils.dist'
- and info.function == 'run_commands'
- )
-
- def do_egg_install(self):
-
- easy_install = self.distribution.get_command_class('easy_install')
-
- cmd = easy_install(
- self.distribution, args="x", root=self.root, record=self.record,
- )
- cmd.ensure_finalized() # finalize before bdist_egg munges install cmd
- cmd.always_copy_from = '.' # make sure local-dir eggs get installed
-
- # pick up setup-dir .egg files only: no .egg-info
- cmd.package_index.scan(glob.glob('*.egg'))
-
- self.run_command('bdist_egg')
- args = [self.distribution.get_command_obj('bdist_egg').egg_output]
-
- if setuptools.bootstrap_install_from:
- # Bootstrap self-installation of setuptools
- args.insert(0, setuptools.bootstrap_install_from)
-
- cmd.args = args
+_install = orig.install
+
+
+class install(orig.install):
+ """Use easy_install to install the package, w/dependencies"""
+
+ user_options = orig.install.user_options + [
+ ('old-and-unmanageable', None, "Try not to use this!"),
+ ('single-version-externally-managed', None,
+ "used by system package builders to create 'flat' eggs"),
+ ]
+ boolean_options = orig.install.boolean_options + [
+ 'old-and-unmanageable', 'single-version-externally-managed',
+ ]
+ new_commands = [
+ ('install_egg_info', lambda self: True),
+ ('install_scripts', lambda self: True),
+ ]
+ _nc = dict(new_commands)
+
+ def initialize_options(self):
+ orig.install.initialize_options(self)
+ self.old_and_unmanageable = None
+ self.single_version_externally_managed = None
+
+ def finalize_options(self):
+ orig.install.finalize_options(self)
+ if self.root:
+ self.single_version_externally_managed = True
+ elif self.single_version_externally_managed:
+ if not self.root and not self.record:
+ raise DistutilsArgError(
+ "You must specify --record or --root when building system"
+ " packages"
+ )
+
+ def handle_extra_path(self):
+ if self.root or self.single_version_externally_managed:
+ # explicit backward-compatibility mode, allow extra_path to work
+ return orig.install.handle_extra_path(self)
+
+ # Ignore extra_path when installing an egg (or being run by another
+ # command without --root or --single-version-externally-managed
+ self.path_file = None
+ self.extra_dirs = ''
+
+ def run(self):
+ # Explicit request for old-style install? Just do it
+ if self.old_and_unmanageable or self.single_version_externally_managed:
+ return orig.install.run(self)
+
+ if not self._called_from_setup(inspect.currentframe()):
+ # Run in backward-compatibility mode to support bdist_* commands.
+ orig.install.run(self)
+ else:
+ self.do_egg_install()
+
+ @staticmethod
+ def _called_from_setup(run_frame):
+ """
+ Attempt to detect whether run() was called from setup() or by another
+ command. If called by setup(), the parent caller will be the
+ 'run_command' method in 'distutils.dist', and *its* caller will be
+ the 'run_commands' method. If called any other way, the
+ immediate caller *might* be 'run_command', but it won't have been
+ called by 'run_commands'. Return True in that case or if a call stack
+ is unavailable. Return False otherwise.
+ """
+ if run_frame is None:
+ msg = "Call stack not available. bdist_* commands may fail."
+ warnings.warn(msg)
+ if platform.python_implementation() == 'IronPython':
+ msg = "For best results, pass -X:Frames to enable call stack."
+ warnings.warn(msg)
+ return True
+ res = inspect.getouterframes(run_frame)[2]
+ caller, = res[:1]
+ info = inspect.getframeinfo(caller)
+ caller_module = caller.f_globals.get('__name__', '')
+ return (
+ caller_module == 'distutils.dist'
+ and info.function == 'run_commands'
+ )
+
+ def do_egg_install(self):
+
+ easy_install = self.distribution.get_command_class('easy_install')
+
+ cmd = easy_install(
+ self.distribution, args="x", root=self.root, record=self.record,
+ )
+ cmd.ensure_finalized() # finalize before bdist_egg munges install cmd
+ cmd.always_copy_from = '.' # make sure local-dir eggs get installed
+
+ # pick up setup-dir .egg files only: no .egg-info
+ cmd.package_index.scan(glob.glob('*.egg'))
+
+ self.run_command('bdist_egg')
+ args = [self.distribution.get_command_obj('bdist_egg').egg_output]
+
+ if setuptools.bootstrap_install_from:
+ # Bootstrap self-installation of setuptools
+ args.insert(0, setuptools.bootstrap_install_from)
+
+ cmd.args = args
cmd.run(show_deprecation=False)
- setuptools.bootstrap_install_from = None
-
-
-# XXX Python 3.1 doesn't see _nc if this is inside the class
-install.sub_commands = (
- [cmd for cmd in orig.install.sub_commands if cmd[0] not in install._nc] +
- install.new_commands
-)
+ setuptools.bootstrap_install_from = None
+
+
+# XXX Python 3.1 doesn't see _nc if this is inside the class
+install.sub_commands = (
+ [cmd for cmd in orig.install.sub_commands if cmd[0] not in install._nc] +
+ install.new_commands
+)
diff --git a/contrib/python/setuptools/py2/setuptools/command/install_egg_info.py b/contrib/python/setuptools/py2/setuptools/command/install_egg_info.py
index 10bdb832a9..edc4718b68 100644
--- a/contrib/python/setuptools/py2/setuptools/command/install_egg_info.py
+++ b/contrib/python/setuptools/py2/setuptools/command/install_egg_info.py
@@ -1,62 +1,62 @@
-from distutils import log, dir_util
-import os
-
-from setuptools import Command
+from distutils import log, dir_util
+import os
+
+from setuptools import Command
from setuptools import namespaces
-from setuptools.archive_util import unpack_archive
-import pkg_resources
-
-
+from setuptools.archive_util import unpack_archive
+import pkg_resources
+
+
class install_egg_info(namespaces.Installer, Command):
- """Install an .egg-info directory for the package"""
-
- description = "Install an .egg-info directory for the package"
-
- user_options = [
- ('install-dir=', 'd', "directory to install to"),
- ]
-
- def initialize_options(self):
- self.install_dir = None
-
- def finalize_options(self):
- self.set_undefined_options('install_lib',
- ('install_dir', 'install_dir'))
- ei_cmd = self.get_finalized_command("egg_info")
- basename = pkg_resources.Distribution(
- None, None, ei_cmd.egg_name, ei_cmd.egg_version
- ).egg_name() + '.egg-info'
- self.source = ei_cmd.egg_info
- self.target = os.path.join(self.install_dir, basename)
+ """Install an .egg-info directory for the package"""
+
+ description = "Install an .egg-info directory for the package"
+
+ user_options = [
+ ('install-dir=', 'd', "directory to install to"),
+ ]
+
+ def initialize_options(self):
+ self.install_dir = None
+
+ def finalize_options(self):
+ self.set_undefined_options('install_lib',
+ ('install_dir', 'install_dir'))
+ ei_cmd = self.get_finalized_command("egg_info")
+ basename = pkg_resources.Distribution(
+ None, None, ei_cmd.egg_name, ei_cmd.egg_version
+ ).egg_name() + '.egg-info'
+ self.source = ei_cmd.egg_info
+ self.target = os.path.join(self.install_dir, basename)
self.outputs = []
-
- def run(self):
- self.run_command('egg_info')
- if os.path.isdir(self.target) and not os.path.islink(self.target):
- dir_util.remove_tree(self.target, dry_run=self.dry_run)
- elif os.path.exists(self.target):
- self.execute(os.unlink, (self.target,), "Removing " + self.target)
- if not self.dry_run:
- pkg_resources.ensure_directory(self.target)
- self.execute(
- self.copytree, (), "Copying %s to %s" % (self.source, self.target)
- )
- self.install_namespaces()
-
- def get_outputs(self):
- return self.outputs
-
- def copytree(self):
- # Copy the .egg-info tree to site-packages
- def skimmer(src, dst):
- # filter out source-control directories; note that 'src' is always
- # a '/'-separated path, regardless of platform. 'dst' is a
- # platform-specific path.
- for skip in '.svn/', 'CVS/':
- if src.startswith(skip) or '/' + skip in src:
- return None
- self.outputs.append(dst)
- log.debug("Copying %s to %s", src, dst)
- return dst
-
- unpack_archive(self.source, self.target, skimmer)
+
+ def run(self):
+ self.run_command('egg_info')
+ if os.path.isdir(self.target) and not os.path.islink(self.target):
+ dir_util.remove_tree(self.target, dry_run=self.dry_run)
+ elif os.path.exists(self.target):
+ self.execute(os.unlink, (self.target,), "Removing " + self.target)
+ if not self.dry_run:
+ pkg_resources.ensure_directory(self.target)
+ self.execute(
+ self.copytree, (), "Copying %s to %s" % (self.source, self.target)
+ )
+ self.install_namespaces()
+
+ def get_outputs(self):
+ return self.outputs
+
+ def copytree(self):
+ # Copy the .egg-info tree to site-packages
+ def skimmer(src, dst):
+ # filter out source-control directories; note that 'src' is always
+ # a '/'-separated path, regardless of platform. 'dst' is a
+ # platform-specific path.
+ for skip in '.svn/', 'CVS/':
+ if src.startswith(skip) or '/' + skip in src:
+ return None
+ self.outputs.append(dst)
+ log.debug("Copying %s to %s", src, dst)
+ return dst
+
+ unpack_archive(self.source, self.target, skimmer)
diff --git a/contrib/python/setuptools/py2/setuptools/command/install_lib.py b/contrib/python/setuptools/py2/setuptools/command/install_lib.py
index 96f37ab050..07d6593309 100644
--- a/contrib/python/setuptools/py2/setuptools/command/install_lib.py
+++ b/contrib/python/setuptools/py2/setuptools/command/install_lib.py
@@ -1,121 +1,121 @@
-import os
+import os
import sys
-from itertools import product, starmap
-import distutils.command.install_lib as orig
-
-
-class install_lib(orig.install_lib):
- """Don't add compiled flags to filenames of non-Python files"""
-
- def run(self):
- self.build()
- outfiles = self.install()
- if outfiles is not None:
- # always compile, in case we have any extension stubs to deal with
- self.byte_compile(outfiles)
-
- def get_exclusions(self):
- """
- Return a collections.Sized collections.Container of paths to be
- excluded for single_version_externally_managed installations.
- """
- all_packages = (
- pkg
- for ns_pkg in self._get_SVEM_NSPs()
- for pkg in self._all_packages(ns_pkg)
- )
-
- excl_specs = product(all_packages, self._gen_exclusion_paths())
- return set(starmap(self._exclude_pkg_path, excl_specs))
-
- def _exclude_pkg_path(self, pkg, exclusion_path):
- """
- Given a package name and exclusion path within that package,
- compute the full exclusion path.
- """
- parts = pkg.split('.') + [exclusion_path]
- return os.path.join(self.install_dir, *parts)
-
- @staticmethod
- def _all_packages(pkg_name):
- """
- >>> list(install_lib._all_packages('foo.bar.baz'))
- ['foo.bar.baz', 'foo.bar', 'foo']
- """
- while pkg_name:
- yield pkg_name
- pkg_name, sep, child = pkg_name.rpartition('.')
-
- def _get_SVEM_NSPs(self):
- """
- Get namespace packages (list) but only for
- single_version_externally_managed installations and empty otherwise.
- """
- # TODO: is it necessary to short-circuit here? i.e. what's the cost
- # if get_finalized_command is called even when namespace_packages is
- # False?
- if not self.distribution.namespace_packages:
- return []
-
- install_cmd = self.get_finalized_command('install')
- svem = install_cmd.single_version_externally_managed
-
- return self.distribution.namespace_packages if svem else []
-
- @staticmethod
- def _gen_exclusion_paths():
- """
- Generate file paths to be excluded for namespace packages (bytecode
- cache files).
- """
- # always exclude the package module itself
- yield '__init__.py'
-
- yield '__init__.pyc'
- yield '__init__.pyo'
-
+from itertools import product, starmap
+import distutils.command.install_lib as orig
+
+
+class install_lib(orig.install_lib):
+ """Don't add compiled flags to filenames of non-Python files"""
+
+ def run(self):
+ self.build()
+ outfiles = self.install()
+ if outfiles is not None:
+ # always compile, in case we have any extension stubs to deal with
+ self.byte_compile(outfiles)
+
+ def get_exclusions(self):
+ """
+ Return a collections.Sized collections.Container of paths to be
+ excluded for single_version_externally_managed installations.
+ """
+ all_packages = (
+ pkg
+ for ns_pkg in self._get_SVEM_NSPs()
+ for pkg in self._all_packages(ns_pkg)
+ )
+
+ excl_specs = product(all_packages, self._gen_exclusion_paths())
+ return set(starmap(self._exclude_pkg_path, excl_specs))
+
+ def _exclude_pkg_path(self, pkg, exclusion_path):
+ """
+ Given a package name and exclusion path within that package,
+ compute the full exclusion path.
+ """
+ parts = pkg.split('.') + [exclusion_path]
+ return os.path.join(self.install_dir, *parts)
+
+ @staticmethod
+ def _all_packages(pkg_name):
+ """
+ >>> list(install_lib._all_packages('foo.bar.baz'))
+ ['foo.bar.baz', 'foo.bar', 'foo']
+ """
+ while pkg_name:
+ yield pkg_name
+ pkg_name, sep, child = pkg_name.rpartition('.')
+
+ def _get_SVEM_NSPs(self):
+ """
+ Get namespace packages (list) but only for
+ single_version_externally_managed installations and empty otherwise.
+ """
+ # TODO: is it necessary to short-circuit here? i.e. what's the cost
+ # if get_finalized_command is called even when namespace_packages is
+ # False?
+ if not self.distribution.namespace_packages:
+ return []
+
+ install_cmd = self.get_finalized_command('install')
+ svem = install_cmd.single_version_externally_managed
+
+ return self.distribution.namespace_packages if svem else []
+
+ @staticmethod
+ def _gen_exclusion_paths():
+ """
+ Generate file paths to be excluded for namespace packages (bytecode
+ cache files).
+ """
+ # always exclude the package module itself
+ yield '__init__.py'
+
+ yield '__init__.pyc'
+ yield '__init__.pyo'
+
if not hasattr(sys, 'implementation'):
- return
-
+ return
+
base = os.path.join('__pycache__', '__init__.' + sys.implementation.cache_tag)
- yield base + '.pyc'
- yield base + '.pyo'
- yield base + '.opt-1.pyc'
- yield base + '.opt-2.pyc'
-
- def copy_tree(
- self, infile, outfile,
- preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1
- ):
- assert preserve_mode and preserve_times and not preserve_symlinks
- exclude = self.get_exclusions()
-
- if not exclude:
- return orig.install_lib.copy_tree(self, infile, outfile)
-
- # Exclude namespace package __init__.py* files from the output
-
- from setuptools.archive_util import unpack_directory
- from distutils import log
-
- outfiles = []
-
- def pf(src, dst):
- if dst in exclude:
- log.warn("Skipping installation of %s (namespace package)",
- dst)
- return False
-
- log.info("copying %s -> %s", src, os.path.dirname(dst))
- outfiles.append(dst)
- return dst
-
- unpack_directory(infile, outfile, pf)
- return outfiles
-
- def get_outputs(self):
- outputs = orig.install_lib.get_outputs(self)
- exclude = self.get_exclusions()
- if exclude:
- return [f for f in outputs if f not in exclude]
- return outputs
+ yield base + '.pyc'
+ yield base + '.pyo'
+ yield base + '.opt-1.pyc'
+ yield base + '.opt-2.pyc'
+
+ def copy_tree(
+ self, infile, outfile,
+ preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1
+ ):
+ assert preserve_mode and preserve_times and not preserve_symlinks
+ exclude = self.get_exclusions()
+
+ if not exclude:
+ return orig.install_lib.copy_tree(self, infile, outfile)
+
+ # Exclude namespace package __init__.py* files from the output
+
+ from setuptools.archive_util import unpack_directory
+ from distutils import log
+
+ outfiles = []
+
+ def pf(src, dst):
+ if dst in exclude:
+ log.warn("Skipping installation of %s (namespace package)",
+ dst)
+ return False
+
+ log.info("copying %s -> %s", src, os.path.dirname(dst))
+ outfiles.append(dst)
+ return dst
+
+ unpack_directory(infile, outfile, pf)
+ return outfiles
+
+ def get_outputs(self):
+ outputs = orig.install_lib.get_outputs(self)
+ exclude = self.get_exclusions()
+ if exclude:
+ return [f for f in outputs if f not in exclude]
+ return outputs
diff --git a/contrib/python/setuptools/py2/setuptools/command/install_scripts.py b/contrib/python/setuptools/py2/setuptools/command/install_scripts.py
index 4902f2c621..16234273a2 100644
--- a/contrib/python/setuptools/py2/setuptools/command/install_scripts.py
+++ b/contrib/python/setuptools/py2/setuptools/command/install_scripts.py
@@ -1,65 +1,65 @@
-from distutils import log
-import distutils.command.install_scripts as orig
-import os
+from distutils import log
+import distutils.command.install_scripts as orig
+import os
import sys
-
-from pkg_resources import Distribution, PathMetadata, ensure_directory
-
-
-class install_scripts(orig.install_scripts):
- """Do normal script install, plus any egg_info wrapper scripts"""
-
- def initialize_options(self):
- orig.install_scripts.initialize_options(self)
- self.no_ep = False
-
- def run(self):
- import setuptools.command.easy_install as ei
-
- self.run_command("egg_info")
- if self.distribution.scripts:
- orig.install_scripts.run(self) # run first to set up self.outfiles
- else:
- self.outfiles = []
- if self.no_ep:
- # don't install entry point scripts into .egg file!
- return
-
- ei_cmd = self.get_finalized_command("egg_info")
- dist = Distribution(
- ei_cmd.egg_base, PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),
- ei_cmd.egg_name, ei_cmd.egg_version,
- )
- bs_cmd = self.get_finalized_command('build_scripts')
- exec_param = getattr(bs_cmd, 'executable', None)
- bw_cmd = self.get_finalized_command("bdist_wininst")
- is_wininst = getattr(bw_cmd, '_is_running', False)
- writer = ei.ScriptWriter
- if is_wininst:
- exec_param = "python.exe"
- writer = ei.WindowsScriptWriter
+
+from pkg_resources import Distribution, PathMetadata, ensure_directory
+
+
+class install_scripts(orig.install_scripts):
+ """Do normal script install, plus any egg_info wrapper scripts"""
+
+ def initialize_options(self):
+ orig.install_scripts.initialize_options(self)
+ self.no_ep = False
+
+ def run(self):
+ import setuptools.command.easy_install as ei
+
+ self.run_command("egg_info")
+ if self.distribution.scripts:
+ orig.install_scripts.run(self) # run first to set up self.outfiles
+ else:
+ self.outfiles = []
+ if self.no_ep:
+ # don't install entry point scripts into .egg file!
+ return
+
+ ei_cmd = self.get_finalized_command("egg_info")
+ dist = Distribution(
+ ei_cmd.egg_base, PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),
+ ei_cmd.egg_name, ei_cmd.egg_version,
+ )
+ bs_cmd = self.get_finalized_command('build_scripts')
+ exec_param = getattr(bs_cmd, 'executable', None)
+ bw_cmd = self.get_finalized_command("bdist_wininst")
+ is_wininst = getattr(bw_cmd, '_is_running', False)
+ writer = ei.ScriptWriter
+ if is_wininst:
+ exec_param = "python.exe"
+ writer = ei.WindowsScriptWriter
if exec_param == sys.executable:
# In case the path to the Python executable contains a space, wrap
# it so it's not split up.
exec_param = [exec_param]
- # resolve the writer to the environment
- writer = writer.best()
- cmd = writer.command_spec_class.best().from_param(exec_param)
- for args in writer.get_args(dist, cmd.as_header()):
- self.write_script(*args)
-
- def write_script(self, script_name, contents, mode="t", *ignored):
- """Write an executable file to the scripts directory"""
- from setuptools.command.easy_install import chmod, current_umask
-
- log.info("Installing %s script to %s", script_name, self.install_dir)
- target = os.path.join(self.install_dir, script_name)
- self.outfiles.append(target)
-
- mask = current_umask()
- if not self.dry_run:
- ensure_directory(target)
- f = open(target, "w" + mode)
- f.write(contents)
- f.close()
- chmod(target, 0o777 - mask)
+ # resolve the writer to the environment
+ writer = writer.best()
+ cmd = writer.command_spec_class.best().from_param(exec_param)
+ for args in writer.get_args(dist, cmd.as_header()):
+ self.write_script(*args)
+
+ def write_script(self, script_name, contents, mode="t", *ignored):
+ """Write an executable file to the scripts directory"""
+ from setuptools.command.easy_install import chmod, current_umask
+
+ log.info("Installing %s script to %s", script_name, self.install_dir)
+ target = os.path.join(self.install_dir, script_name)
+ self.outfiles.append(target)
+
+ mask = current_umask()
+ if not self.dry_run:
+ ensure_directory(target)
+ f = open(target, "w" + mode)
+ f.write(contents)
+ f.close()
+ chmod(target, 0o777 - mask)
diff --git a/contrib/python/setuptools/py2/setuptools/command/register.py b/contrib/python/setuptools/py2/setuptools/command/register.py
index dbe5e619f7..b8266b9a60 100644
--- a/contrib/python/setuptools/py2/setuptools/command/register.py
+++ b/contrib/python/setuptools/py2/setuptools/command/register.py
@@ -1,13 +1,13 @@
from distutils import log
-import distutils.command.register as orig
-
+import distutils.command.register as orig
+
from setuptools.errors import RemovedCommandError
-
-class register(orig.register):
+
+class register(orig.register):
"""Formerly used to register packages on PyPI."""
-
- def run(self):
+
+ def run(self):
msg = (
"The register command has been removed, use twine to upload "
+ "instead (https://pypi.org/p/twine)"
diff --git a/contrib/python/setuptools/py2/setuptools/command/rotate.py b/contrib/python/setuptools/py2/setuptools/command/rotate.py
index 3e873a97df..b89353f529 100644
--- a/contrib/python/setuptools/py2/setuptools/command/rotate.py
+++ b/contrib/python/setuptools/py2/setuptools/command/rotate.py
@@ -1,65 +1,65 @@
-from distutils.util import convert_path
-from distutils import log
-from distutils.errors import DistutilsOptionError
-import os
+from distutils.util import convert_path
+from distutils import log
+from distutils.errors import DistutilsOptionError
+import os
import shutil
-
+
from setuptools.extern import six
-
-from setuptools import Command
-
-
-class rotate(Command):
- """Delete older distributions"""
-
- description = "delete older distributions, keeping N newest files"
- user_options = [
- ('match=', 'm', "patterns to match (required)"),
- ('dist-dir=', 'd', "directory where the distributions are"),
- ('keep=', 'k', "number of matching distributions to keep"),
- ]
-
- boolean_options = []
-
- def initialize_options(self):
- self.match = None
- self.dist_dir = None
- self.keep = None
-
- def finalize_options(self):
- if self.match is None:
- raise DistutilsOptionError(
- "Must specify one or more (comma-separated) match patterns "
- "(e.g. '.zip' or '.egg')"
- )
- if self.keep is None:
- raise DistutilsOptionError("Must specify number of files to keep")
- try:
- self.keep = int(self.keep)
- except ValueError:
- raise DistutilsOptionError("--keep must be an integer")
- if isinstance(self.match, six.string_types):
- self.match = [
- convert_path(p.strip()) for p in self.match.split(',')
- ]
- self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
-
- def run(self):
- self.run_command("egg_info")
- from glob import glob
-
- for pattern in self.match:
- pattern = self.distribution.get_name() + '*' + pattern
- files = glob(os.path.join(self.dist_dir, pattern))
- files = [(os.path.getmtime(f), f) for f in files]
- files.sort()
- files.reverse()
-
- log.info("%d file(s) matching %s", len(files), pattern)
- files = files[self.keep:]
- for (t, f) in files:
- log.info("Deleting %s", f)
- if not self.dry_run:
+
+from setuptools import Command
+
+
+class rotate(Command):
+ """Delete older distributions"""
+
+ description = "delete older distributions, keeping N newest files"
+ user_options = [
+ ('match=', 'm', "patterns to match (required)"),
+ ('dist-dir=', 'd', "directory where the distributions are"),
+ ('keep=', 'k', "number of matching distributions to keep"),
+ ]
+
+ boolean_options = []
+
+ def initialize_options(self):
+ self.match = None
+ self.dist_dir = None
+ self.keep = None
+
+ def finalize_options(self):
+ if self.match is None:
+ raise DistutilsOptionError(
+ "Must specify one or more (comma-separated) match patterns "
+ "(e.g. '.zip' or '.egg')"
+ )
+ if self.keep is None:
+ raise DistutilsOptionError("Must specify number of files to keep")
+ try:
+ self.keep = int(self.keep)
+ except ValueError:
+ raise DistutilsOptionError("--keep must be an integer")
+ if isinstance(self.match, six.string_types):
+ self.match = [
+ convert_path(p.strip()) for p in self.match.split(',')
+ ]
+ self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
+
+ def run(self):
+ self.run_command("egg_info")
+ from glob import glob
+
+ for pattern in self.match:
+ pattern = self.distribution.get_name() + '*' + pattern
+ files = glob(os.path.join(self.dist_dir, pattern))
+ files = [(os.path.getmtime(f), f) for f in files]
+ files.sort()
+ files.reverse()
+
+ log.info("%d file(s) matching %s", len(files), pattern)
+ files = files[self.keep:]
+ for (t, f) in files:
+ log.info("Deleting %s", f)
+ if not self.dry_run:
if os.path.isdir(f):
shutil.rmtree(f)
else:
diff --git a/contrib/python/setuptools/py2/setuptools/command/saveopts.py b/contrib/python/setuptools/py2/setuptools/command/saveopts.py
index 3ce03df53c..611cec5528 100644
--- a/contrib/python/setuptools/py2/setuptools/command/saveopts.py
+++ b/contrib/python/setuptools/py2/setuptools/command/saveopts.py
@@ -1,22 +1,22 @@
-from setuptools.command.setopt import edit_config, option_base
-
-
-class saveopts(option_base):
- """Save command-line options to a file"""
-
- description = "save supplied options to setup.cfg or other config file"
-
- def run(self):
- dist = self.distribution
- settings = {}
-
- for cmd in dist.command_options:
-
- if cmd == 'saveopts':
- continue # don't save our own options!
-
- for opt, (src, val) in dist.get_option_dict(cmd).items():
- if src == "command line":
- settings.setdefault(cmd, {})[opt] = val
-
- edit_config(self.filename, settings, self.dry_run)
+from setuptools.command.setopt import edit_config, option_base
+
+
+class saveopts(option_base):
+ """Save command-line options to a file"""
+
+ description = "save supplied options to setup.cfg or other config file"
+
+ def run(self):
+ dist = self.distribution
+ settings = {}
+
+ for cmd in dist.command_options:
+
+ if cmd == 'saveopts':
+ continue # don't save our own options!
+
+ for opt, (src, val) in dist.get_option_dict(cmd).items():
+ if src == "command line":
+ settings.setdefault(cmd, {})[opt] = val
+
+ edit_config(self.filename, settings, self.dry_run)
diff --git a/contrib/python/setuptools/py2/setuptools/command/sdist.py b/contrib/python/setuptools/py2/setuptools/command/sdist.py
index 6afdfa4e0b..8c3438eaa6 100644
--- a/contrib/python/setuptools/py2/setuptools/command/sdist.py
+++ b/contrib/python/setuptools/py2/setuptools/command/sdist.py
@@ -1,64 +1,64 @@
-from distutils import log
-import distutils.command.sdist as orig
-import os
-import sys
-import io
+from distutils import log
+import distutils.command.sdist as orig
+import os
+import sys
+import io
import contextlib
-
+
from setuptools.extern import six, ordered_set
-
+
from .py36compat import sdist_add_defaults
-
-import pkg_resources
-
-_default_revctrl = list
-
-
-def walk_revctrl(dirname=''):
- """Find all files under revision control"""
- for ep in pkg_resources.iter_entry_points('setuptools.file_finders'):
- for item in ep.load()(dirname):
- yield item
-
-
+
+import pkg_resources
+
+_default_revctrl = list
+
+
+def walk_revctrl(dirname=''):
+ """Find all files under revision control"""
+ for ep in pkg_resources.iter_entry_points('setuptools.file_finders'):
+ for item in ep.load()(dirname):
+ yield item
+
+
class sdist(sdist_add_defaults, orig.sdist):
- """Smart sdist that finds anything supported by revision control"""
-
- user_options = [
- ('formats=', None,
- "formats for source distribution (comma-separated list)"),
- ('keep-temp', 'k',
- "keep the distribution tree around after creating " +
- "archive file(s)"),
- ('dist-dir=', 'd',
- "directory to put the source distribution archive(s) in "
- "[default: dist]"),
- ]
-
- negative_opt = {}
-
+ """Smart sdist that finds anything supported by revision control"""
+
+ user_options = [
+ ('formats=', None,
+ "formats for source distribution (comma-separated list)"),
+ ('keep-temp', 'k',
+ "keep the distribution tree around after creating " +
+ "archive file(s)"),
+ ('dist-dir=', 'd',
+ "directory to put the source distribution archive(s) in "
+ "[default: dist]"),
+ ]
+
+ negative_opt = {}
+
README_EXTENSIONS = ['', '.rst', '.txt', '.md']
READMES = tuple('README{0}'.format(ext) for ext in README_EXTENSIONS)
- def run(self):
- self.run_command('egg_info')
- ei_cmd = self.get_finalized_command('egg_info')
- self.filelist = ei_cmd.filelist
- self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt'))
- self.check_readme()
-
- # Run sub commands
- for cmd_name in self.get_sub_commands():
- self.run_command(cmd_name)
-
- self.make_distribution()
-
- dist_files = getattr(self.distribution, 'dist_files', [])
- for file in self.archive_files:
- data = ('sdist', '', file)
- if data not in dist_files:
- dist_files.append(data)
-
+ def run(self):
+ self.run_command('egg_info')
+ ei_cmd = self.get_finalized_command('egg_info')
+ self.filelist = ei_cmd.filelist
+ self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt'))
+ self.check_readme()
+
+ # Run sub commands
+ for cmd_name in self.get_sub_commands():
+ self.run_command(cmd_name)
+
+ self.make_distribution()
+
+ dist_files = getattr(self.distribution, 'dist_files', [])
+ for file in self.archive_files:
+ data = ('sdist', '', file)
+ if data not in dist_files:
+ dist_files.append(data)
+
def initialize_options(self):
orig.sdist.initialize_options(self)
@@ -98,29 +98,29 @@ class sdist(sdist_add_defaults, orig.sdist):
if orig_val is not NoValue:
setattr(os, 'link', orig_val)
- def __read_template_hack(self):
- # This grody hack closes the template file (MANIFEST.in) if an
- # exception occurs during read_template.
- # Doing so prevents an error when easy_install attempts to delete the
- # file.
- try:
- orig.sdist.read_template(self)
+ def __read_template_hack(self):
+ # This grody hack closes the template file (MANIFEST.in) if an
+ # exception occurs during read_template.
+ # Doing so prevents an error when easy_install attempts to delete the
+ # file.
+ try:
+ orig.sdist.read_template(self)
except Exception:
- _, _, tb = sys.exc_info()
- tb.tb_next.tb_frame.f_locals['template'].close()
- raise
-
- # Beginning with Python 2.7.2, 3.1.4, and 3.2.1, this leaky file handle
- # has been fixed, so only override the method if we're using an earlier
- # Python.
- has_leaky_handle = (
- sys.version_info < (2, 7, 2)
- or (3, 0) <= sys.version_info < (3, 1, 4)
- or (3, 2) <= sys.version_info < (3, 2, 1)
- )
- if has_leaky_handle:
- read_template = __read_template_hack
-
+ _, _, tb = sys.exc_info()
+ tb.tb_next.tb_frame.f_locals['template'].close()
+ raise
+
+ # Beginning with Python 2.7.2, 3.1.4, and 3.2.1, this leaky file handle
+ # has been fixed, so only override the method if we're using an earlier
+ # Python.
+ has_leaky_handle = (
+ sys.version_info < (2, 7, 2)
+ or (3, 0) <= sys.version_info < (3, 1, 4)
+ or (3, 2) <= sys.version_info < (3, 2, 1)
+ )
+ if has_leaky_handle:
+ read_template = __read_template_hack
+
def _add_defaults_optional(self):
if six.PY2:
sdist_add_defaults._add_defaults_optional(self)
@@ -131,11 +131,11 @@ class sdist(sdist_add_defaults, orig.sdist):
def _add_defaults_python(self):
"""getting python files"""
- if self.distribution.has_pure_modules():
- build_py = self.get_finalized_command('build_py')
- self.filelist.extend(build_py.get_source_files())
+ if self.distribution.has_pure_modules():
+ build_py = self.get_finalized_command('build_py')
+ self.filelist.extend(build_py.get_source_files())
self._add_data_files(self._safe_data_files(build_py))
-
+
def _safe_data_files(self, build_py):
"""
Extracting data_files from build_py is known to cause
@@ -164,61 +164,61 @@ class sdist(sdist_add_defaults, orig.sdist):
super()._add_defaults_data_files()
except TypeError:
log.warn("data_files contains unexpected objects")
-
- def check_readme(self):
+
+ def check_readme(self):
for f in self.READMES:
- if os.path.exists(f):
- return
- else:
- self.warn(
- "standard file not found: should have one of " +
+ if os.path.exists(f):
+ return
+ else:
+ self.warn(
+ "standard file not found: should have one of " +
', '.join(self.READMES)
- )
-
- def make_release_tree(self, base_dir, files):
- orig.sdist.make_release_tree(self, base_dir, files)
-
- # Save any egg_info command line options used to create this sdist
- dest = os.path.join(base_dir, 'setup.cfg')
- if hasattr(os, 'link') and os.path.exists(dest):
- # unlink and re-copy, since it might be hard-linked, and
- # we don't want to change the source version
- os.unlink(dest)
- self.copy_file('setup.cfg', dest)
-
- self.get_finalized_command('egg_info').save_version_info(dest)
-
- def _manifest_is_not_generated(self):
- # check for special comment used in 2.7.1 and higher
- if not os.path.isfile(self.manifest):
- return False
-
- with io.open(self.manifest, 'rb') as fp:
- first_line = fp.readline()
- return (first_line !=
- '# file GENERATED by distutils, do NOT edit\n'.encode())
-
- def read_manifest(self):
- """Read the manifest file (named by 'self.manifest') and use it to
- fill in 'self.filelist', the list of files to include in the source
- distribution.
- """
- log.info("reading manifest file '%s'", self.manifest)
+ )
+
+ def make_release_tree(self, base_dir, files):
+ orig.sdist.make_release_tree(self, base_dir, files)
+
+ # Save any egg_info command line options used to create this sdist
+ dest = os.path.join(base_dir, 'setup.cfg')
+ if hasattr(os, 'link') and os.path.exists(dest):
+ # unlink and re-copy, since it might be hard-linked, and
+ # we don't want to change the source version
+ os.unlink(dest)
+ self.copy_file('setup.cfg', dest)
+
+ self.get_finalized_command('egg_info').save_version_info(dest)
+
+ def _manifest_is_not_generated(self):
+ # check for special comment used in 2.7.1 and higher
+ if not os.path.isfile(self.manifest):
+ return False
+
+ with io.open(self.manifest, 'rb') as fp:
+ first_line = fp.readline()
+ return (first_line !=
+ '# file GENERATED by distutils, do NOT edit\n'.encode())
+
+ def read_manifest(self):
+ """Read the manifest file (named by 'self.manifest') and use it to
+ fill in 'self.filelist', the list of files to include in the source
+ distribution.
+ """
+ log.info("reading manifest file '%s'", self.manifest)
manifest = open(self.manifest, 'rb')
- for line in manifest:
- # The manifest must contain UTF-8. See #303.
+ for line in manifest:
+ # The manifest must contain UTF-8. See #303.
if not six.PY2:
- try:
- line = line.decode('UTF-8')
- except UnicodeDecodeError:
- log.warn("%r not UTF-8 decodable -- skipping" % line)
- continue
- # ignore comments and blank lines
- line = line.strip()
- if line.startswith('#') or not line:
- continue
- self.filelist.append(line)
- manifest.close()
+ try:
+ line = line.decode('UTF-8')
+ except UnicodeDecodeError:
+ log.warn("%r not UTF-8 decodable -- skipping" % line)
+ continue
+ # ignore comments and blank lines
+ line = line.strip()
+ if line.startswith('#') or not line:
+ continue
+ self.filelist.append(line)
+ manifest.close()
def check_license(self):
"""Checks if license_file' or 'license_files' is configured and adds any
diff --git a/contrib/python/setuptools/py2/setuptools/command/setopt.py b/contrib/python/setuptools/py2/setuptools/command/setopt.py
index 9677a92797..7e57cc0262 100644
--- a/contrib/python/setuptools/py2/setuptools/command/setopt.py
+++ b/contrib/python/setuptools/py2/setuptools/command/setopt.py
@@ -1,149 +1,149 @@
-from distutils.util import convert_path
-from distutils import log
-from distutils.errors import DistutilsOptionError
-import distutils
-import os
-
+from distutils.util import convert_path
+from distutils import log
+from distutils.errors import DistutilsOptionError
+import distutils
+import os
+
from setuptools.extern.six.moves import configparser
-
-from setuptools import Command
-
-__all__ = ['config_file', 'edit_config', 'option_base', 'setopt']
-
-
-def config_file(kind="local"):
- """Get the filename of the distutils, local, global, or per-user config
-
- `kind` must be one of "local", "global", or "user"
- """
- if kind == 'local':
- return 'setup.cfg'
- if kind == 'global':
- return os.path.join(
- os.path.dirname(distutils.__file__), 'distutils.cfg'
- )
- if kind == 'user':
- dot = os.name == 'posix' and '.' or ''
- return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot))
- raise ValueError(
- "config_file() type must be 'local', 'global', or 'user'", kind
- )
-
-
-def edit_config(filename, settings, dry_run=False):
- """Edit a configuration file to include `settings`
-
- `settings` is a dictionary of dictionaries or ``None`` values, keyed by
- command/section name. A ``None`` value means to delete the entire section,
- while a dictionary lists settings to be changed or deleted in that section.
- A setting of ``None`` means to delete that setting.
- """
- log.debug("Reading configuration from %s", filename)
- opts = configparser.RawConfigParser()
- opts.read([filename])
- for section, options in settings.items():
- if options is None:
- log.info("Deleting section [%s] from %s", section, filename)
- opts.remove_section(section)
- else:
- if not opts.has_section(section):
- log.debug("Adding new section [%s] to %s", section, filename)
- opts.add_section(section)
- for option, value in options.items():
- if value is None:
- log.debug(
- "Deleting %s.%s from %s",
- section, option, filename
- )
- opts.remove_option(section, option)
- if not opts.options(section):
- log.info("Deleting empty [%s] section from %s",
- section, filename)
- opts.remove_section(section)
- else:
- log.debug(
- "Setting %s.%s to %r in %s",
- section, option, value, filename
- )
- opts.set(section, option, value)
-
- log.info("Writing %s", filename)
- if not dry_run:
- with open(filename, 'w') as f:
- opts.write(f)
-
-
-class option_base(Command):
- """Abstract base class for commands that mess with config files"""
-
- user_options = [
- ('global-config', 'g',
- "save options to the site-wide distutils.cfg file"),
- ('user-config', 'u',
- "save options to the current user's pydistutils.cfg file"),
- ('filename=', 'f',
- "configuration file to use (default=setup.cfg)"),
- ]
-
- boolean_options = [
- 'global-config', 'user-config',
- ]
-
- def initialize_options(self):
- self.global_config = None
- self.user_config = None
- self.filename = None
-
- def finalize_options(self):
- filenames = []
- if self.global_config:
- filenames.append(config_file('global'))
- if self.user_config:
- filenames.append(config_file('user'))
- if self.filename is not None:
- filenames.append(self.filename)
- if not filenames:
- filenames.append(config_file('local'))
- if len(filenames) > 1:
- raise DistutilsOptionError(
- "Must specify only one configuration file option",
- filenames
- )
- self.filename, = filenames
-
-
-class setopt(option_base):
- """Save command-line options to a file"""
-
- description = "set an option in setup.cfg or another config file"
-
- user_options = [
- ('command=', 'c', 'command to set an option for'),
- ('option=', 'o', 'option to set'),
- ('set-value=', 's', 'value of the option'),
- ('remove', 'r', 'remove (unset) the value'),
- ] + option_base.user_options
-
- boolean_options = option_base.boolean_options + ['remove']
-
- def initialize_options(self):
- option_base.initialize_options(self)
- self.command = None
- self.option = None
- self.set_value = None
- self.remove = None
-
- def finalize_options(self):
- option_base.finalize_options(self)
- if self.command is None or self.option is None:
- raise DistutilsOptionError("Must specify --command *and* --option")
- if self.set_value is None and not self.remove:
- raise DistutilsOptionError("Must specify --set-value or --remove")
-
- def run(self):
- edit_config(
- self.filename, {
- self.command: {self.option.replace('-', '_'): self.set_value}
- },
- self.dry_run
- )
+
+from setuptools import Command
+
+__all__ = ['config_file', 'edit_config', 'option_base', 'setopt']
+
+
+def config_file(kind="local"):
+ """Get the filename of the distutils, local, global, or per-user config
+
+ `kind` must be one of "local", "global", or "user"
+ """
+ if kind == 'local':
+ return 'setup.cfg'
+ if kind == 'global':
+ return os.path.join(
+ os.path.dirname(distutils.__file__), 'distutils.cfg'
+ )
+ if kind == 'user':
+ dot = os.name == 'posix' and '.' or ''
+ return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot))
+ raise ValueError(
+ "config_file() type must be 'local', 'global', or 'user'", kind
+ )
+
+
+def edit_config(filename, settings, dry_run=False):
+ """Edit a configuration file to include `settings`
+
+ `settings` is a dictionary of dictionaries or ``None`` values, keyed by
+ command/section name. A ``None`` value means to delete the entire section,
+ while a dictionary lists settings to be changed or deleted in that section.
+ A setting of ``None`` means to delete that setting.
+ """
+ log.debug("Reading configuration from %s", filename)
+ opts = configparser.RawConfigParser()
+ opts.read([filename])
+ for section, options in settings.items():
+ if options is None:
+ log.info("Deleting section [%s] from %s", section, filename)
+ opts.remove_section(section)
+ else:
+ if not opts.has_section(section):
+ log.debug("Adding new section [%s] to %s", section, filename)
+ opts.add_section(section)
+ for option, value in options.items():
+ if value is None:
+ log.debug(
+ "Deleting %s.%s from %s",
+ section, option, filename
+ )
+ opts.remove_option(section, option)
+ if not opts.options(section):
+ log.info("Deleting empty [%s] section from %s",
+ section, filename)
+ opts.remove_section(section)
+ else:
+ log.debug(
+ "Setting %s.%s to %r in %s",
+ section, option, value, filename
+ )
+ opts.set(section, option, value)
+
+ log.info("Writing %s", filename)
+ if not dry_run:
+ with open(filename, 'w') as f:
+ opts.write(f)
+
+
+class option_base(Command):
+ """Abstract base class for commands that mess with config files"""
+
+ user_options = [
+ ('global-config', 'g',
+ "save options to the site-wide distutils.cfg file"),
+ ('user-config', 'u',
+ "save options to the current user's pydistutils.cfg file"),
+ ('filename=', 'f',
+ "configuration file to use (default=setup.cfg)"),
+ ]
+
+ boolean_options = [
+ 'global-config', 'user-config',
+ ]
+
+ def initialize_options(self):
+ self.global_config = None
+ self.user_config = None
+ self.filename = None
+
+ def finalize_options(self):
+ filenames = []
+ if self.global_config:
+ filenames.append(config_file('global'))
+ if self.user_config:
+ filenames.append(config_file('user'))
+ if self.filename is not None:
+ filenames.append(self.filename)
+ if not filenames:
+ filenames.append(config_file('local'))
+ if len(filenames) > 1:
+ raise DistutilsOptionError(
+ "Must specify only one configuration file option",
+ filenames
+ )
+ self.filename, = filenames
+
+
+class setopt(option_base):
+ """Save command-line options to a file"""
+
+ description = "set an option in setup.cfg or another config file"
+
+ user_options = [
+ ('command=', 'c', 'command to set an option for'),
+ ('option=', 'o', 'option to set'),
+ ('set-value=', 's', 'value of the option'),
+ ('remove', 'r', 'remove (unset) the value'),
+ ] + option_base.user_options
+
+ boolean_options = option_base.boolean_options + ['remove']
+
+ def initialize_options(self):
+ option_base.initialize_options(self)
+ self.command = None
+ self.option = None
+ self.set_value = None
+ self.remove = None
+
+ def finalize_options(self):
+ option_base.finalize_options(self)
+ if self.command is None or self.option is None:
+ raise DistutilsOptionError("Must specify --command *and* --option")
+ if self.set_value is None and not self.remove:
+ raise DistutilsOptionError("Must specify --set-value or --remove")
+
+ def run(self):
+ edit_config(
+ self.filename, {
+ self.command: {self.option.replace('-', '_'): self.set_value}
+ },
+ self.dry_run
+ )
diff --git a/contrib/python/setuptools/py2/setuptools/command/test.py b/contrib/python/setuptools/py2/setuptools/command/test.py
index dfccc90a8d..f6470e9c34 100644
--- a/contrib/python/setuptools/py2/setuptools/command/test.py
+++ b/contrib/python/setuptools/py2/setuptools/command/test.py
@@ -6,121 +6,121 @@ import itertools
import unittest
from distutils.errors import DistutilsError, DistutilsOptionError
from distutils import log
-from unittest import TestLoader
-
+from unittest import TestLoader
+
from setuptools.extern import six
from setuptools.extern.six.moves import map, filter
-
-from pkg_resources import (resource_listdir, resource_exists, normalize_path,
+
+from pkg_resources import (resource_listdir, resource_exists, normalize_path,
working_set, _namespace_packages, evaluate_marker,
- add_activation_listener, require, EntryPoint)
-from setuptools import Command
+ add_activation_listener, require, EntryPoint)
+from setuptools import Command
from .build_py import _unique_everseen
-
+
__metaclass__ = type
-
-class ScanningLoader(TestLoader):
+
+class ScanningLoader(TestLoader):
def __init__(self):
TestLoader.__init__(self)
self._visited = set()
- def loadTestsFromModule(self, module, pattern=None):
- """Return a suite of all tests cases contained in the given module
-
- If the module is a package, load tests from all the modules in it.
- If the module has an ``additional_tests`` function, call it and add
- the return value to the tests.
- """
+ def loadTestsFromModule(self, module, pattern=None):
+ """Return a suite of all tests cases contained in the given module
+
+ If the module is a package, load tests from all the modules in it.
+ If the module has an ``additional_tests`` function, call it and add
+ the return value to the tests.
+ """
if module in self._visited:
return None
self._visited.add(module)
- tests = []
- tests.append(TestLoader.loadTestsFromModule(self, module))
-
- if hasattr(module, "additional_tests"):
- tests.append(module.additional_tests())
-
- if hasattr(module, '__path__'):
- for file in resource_listdir(module.__name__, ''):
- if file.endswith('.py') and file != '__init__.py':
- submodule = module.__name__ + '.' + file[:-3]
- else:
- if resource_exists(module.__name__, file + '/__init__.py'):
- submodule = module.__name__ + '.' + file
- else:
- continue
- tests.append(self.loadTestsFromName(submodule))
-
- if len(tests) != 1:
- return self.suiteClass(tests)
- else:
- return tests[0] # don't create a nested suite for only one return
-
-
-# adapted from jaraco.classes.properties:NonDataProperty
+ tests = []
+ tests.append(TestLoader.loadTestsFromModule(self, module))
+
+ if hasattr(module, "additional_tests"):
+ tests.append(module.additional_tests())
+
+ if hasattr(module, '__path__'):
+ for file in resource_listdir(module.__name__, ''):
+ if file.endswith('.py') and file != '__init__.py':
+ submodule = module.__name__ + '.' + file[:-3]
+ else:
+ if resource_exists(module.__name__, file + '/__init__.py'):
+ submodule = module.__name__ + '.' + file
+ else:
+ continue
+ tests.append(self.loadTestsFromName(submodule))
+
+ if len(tests) != 1:
+ return self.suiteClass(tests)
+ else:
+ return tests[0] # don't create a nested suite for only one return
+
+
+# adapted from jaraco.classes.properties:NonDataProperty
class NonDataProperty:
- def __init__(self, fget):
- self.fget = fget
-
- def __get__(self, obj, objtype=None):
- if obj is None:
- return self
- return self.fget(obj)
-
-
-class test(Command):
- """Command to run unit tests after in-place build"""
-
+ def __init__(self, fget):
+ self.fget = fget
+
+ def __get__(self, obj, objtype=None):
+ if obj is None:
+ return self
+ return self.fget(obj)
+
+
+class test(Command):
+ """Command to run unit tests after in-place build"""
+
description = "run unit tests after in-place build (deprecated)"
-
- user_options = [
- ('test-module=', 'm', "Run 'test_suite' in specified module"),
- ('test-suite=', 's',
+
+ user_options = [
+ ('test-module=', 'm', "Run 'test_suite' in specified module"),
+ ('test-suite=', 's',
"Run single test, case or suite (e.g. 'module.test_suite')"),
- ('test-runner=', 'r', "Test runner to use"),
- ]
-
- def initialize_options(self):
- self.test_suite = None
- self.test_module = None
- self.test_loader = None
- self.test_runner = None
-
- def finalize_options(self):
-
- if self.test_suite and self.test_module:
- msg = "You may specify a module or a suite, but not both"
- raise DistutilsOptionError(msg)
-
- if self.test_suite is None:
- if self.test_module is None:
- self.test_suite = self.distribution.test_suite
- else:
- self.test_suite = self.test_module + ".test_suite"
-
- if self.test_loader is None:
- self.test_loader = getattr(self.distribution, 'test_loader', None)
- if self.test_loader is None:
- self.test_loader = "setuptools.command.test:ScanningLoader"
- if self.test_runner is None:
- self.test_runner = getattr(self.distribution, 'test_runner', None)
-
- @NonDataProperty
- def test_args(self):
- return list(self._test_args())
-
- def _test_args(self):
+ ('test-runner=', 'r', "Test runner to use"),
+ ]
+
+ def initialize_options(self):
+ self.test_suite = None
+ self.test_module = None
+ self.test_loader = None
+ self.test_runner = None
+
+ def finalize_options(self):
+
+ if self.test_suite and self.test_module:
+ msg = "You may specify a module or a suite, but not both"
+ raise DistutilsOptionError(msg)
+
+ if self.test_suite is None:
+ if self.test_module is None:
+ self.test_suite = self.distribution.test_suite
+ else:
+ self.test_suite = self.test_module + ".test_suite"
+
+ if self.test_loader is None:
+ self.test_loader = getattr(self.distribution, 'test_loader', None)
+ if self.test_loader is None:
+ self.test_loader = "setuptools.command.test:ScanningLoader"
+ if self.test_runner is None:
+ self.test_runner = getattr(self.distribution, 'test_runner', None)
+
+ @NonDataProperty
+ def test_args(self):
+ return list(self._test_args())
+
+ def _test_args(self):
if not self.test_suite and sys.version_info >= (2, 7):
yield 'discover'
- if self.verbose:
- yield '--verbose'
- if self.test_suite:
- yield self.test_suite
-
- def with_project_on_sys_path(self, func):
+ if self.verbose:
+ yield '--verbose'
+ if self.test_suite:
+ yield self.test_suite
+
+ def with_project_on_sys_path(self, func):
"""
Backward compatibility for project_on_sys_path context.
"""
@@ -130,49 +130,49 @@ class test(Command):
@contextlib.contextmanager
def project_on_sys_path(self, include_dists=[]):
with_2to3 = not six.PY2 and getattr(self.distribution, 'use_2to3', False)
-
- if with_2to3:
- # If we run 2to3 we can not do this inplace:
-
- # Ensure metadata is up-to-date
- self.reinitialize_command('build_py', inplace=0)
- self.run_command('build_py')
- bpy_cmd = self.get_finalized_command("build_py")
- build_path = normalize_path(bpy_cmd.build_lib)
-
- # Build extensions
- self.reinitialize_command('egg_info', egg_base=build_path)
- self.run_command('egg_info')
-
- self.reinitialize_command('build_ext', inplace=0)
- self.run_command('build_ext')
- else:
- # Without 2to3 inplace works fine:
- self.run_command('egg_info')
-
- # Build extensions in-place
- self.reinitialize_command('build_ext', inplace=1)
- self.run_command('build_ext')
-
- ei_cmd = self.get_finalized_command("egg_info")
-
- old_path = sys.path[:]
- old_modules = sys.modules.copy()
-
- try:
+
+ if with_2to3:
+ # If we run 2to3 we can not do this inplace:
+
+ # Ensure metadata is up-to-date
+ self.reinitialize_command('build_py', inplace=0)
+ self.run_command('build_py')
+ bpy_cmd = self.get_finalized_command("build_py")
+ build_path = normalize_path(bpy_cmd.build_lib)
+
+ # Build extensions
+ self.reinitialize_command('egg_info', egg_base=build_path)
+ self.run_command('egg_info')
+
+ self.reinitialize_command('build_ext', inplace=0)
+ self.run_command('build_ext')
+ else:
+ # Without 2to3 inplace works fine:
+ self.run_command('egg_info')
+
+ # Build extensions in-place
+ self.reinitialize_command('build_ext', inplace=1)
+ self.run_command('build_ext')
+
+ ei_cmd = self.get_finalized_command("egg_info")
+
+ old_path = sys.path[:]
+ old_modules = sys.modules.copy()
+
+ try:
project_path = normalize_path(ei_cmd.egg_base)
sys.path.insert(0, project_path)
- working_set.__init__()
- add_activation_listener(lambda dist: dist.activate())
- require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version))
+ working_set.__init__()
+ add_activation_listener(lambda dist: dist.activate())
+ require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version))
with self.paths_on_pythonpath([project_path]):
yield
- finally:
- sys.path[:] = old_path
- sys.modules.clear()
- sys.modules.update(old_modules)
- working_set.__init__()
-
+ finally:
+ sys.path[:] = old_path
+ sys.modules.clear()
+ sys.modules.update(old_modules)
+ working_set.__init__()
+
@staticmethod
@contextlib.contextmanager
def paths_on_pythonpath(paths):
@@ -213,7 +213,7 @@ class test(Command):
)
return itertools.chain(ir_d, tr_d, er_d)
- def run(self):
+ def run(self):
self.announce(
"WARNING: Testing via this command is deprecated and will be "
"removed in a future version. Users looking for a generic test "
@@ -223,12 +223,12 @@ class test(Command):
)
installed_dists = self.install_dists(self.distribution)
-
- cmd = ' '.join(self._argv)
- if self.dry_run:
- self.announce('skipping "%s" (dry run)' % cmd)
+
+ cmd = ' '.join(self._argv)
+ if self.dry_run:
+ self.announce('skipping "%s" (dry run)' % cmd)
return
-
+
self.announce('running "%s"' % cmd)
paths = map(operator.attrgetter('location'), installed_dists)
@@ -236,44 +236,44 @@ class test(Command):
with self.project_on_sys_path():
self.run_tests()
- def run_tests(self):
- # Purge modules under test from sys.modules. The test loader will
- # re-import them from the build location. Required when 2to3 is used
- # with namespace packages.
+ def run_tests(self):
+ # Purge modules under test from sys.modules. The test loader will
+ # re-import them from the build location. Required when 2to3 is used
+ # with namespace packages.
if not six.PY2 and getattr(self.distribution, 'use_2to3', False):
- module = self.test_suite.split('.')[0]
- if module in _namespace_packages:
- del_modules = []
- if module in sys.modules:
- del_modules.append(module)
- module += '.'
- for name in sys.modules:
- if name.startswith(module):
- del_modules.append(name)
- list(map(sys.modules.__delitem__, del_modules))
-
+ module = self.test_suite.split('.')[0]
+ if module in _namespace_packages:
+ del_modules = []
+ if module in sys.modules:
+ del_modules.append(module)
+ module += '.'
+ for name in sys.modules:
+ if name.startswith(module):
+ del_modules.append(name)
+ list(map(sys.modules.__delitem__, del_modules))
+
test = unittest.main(
- None, None, self._argv,
- testLoader=self._resolve_as_ep(self.test_loader),
- testRunner=self._resolve_as_ep(self.test_runner),
+ None, None, self._argv,
+ testLoader=self._resolve_as_ep(self.test_loader),
+ testRunner=self._resolve_as_ep(self.test_runner),
exit=False,
- )
+ )
if not test.result.wasSuccessful():
msg = 'Test failed: %s' % test.result
self.announce(msg, log.ERROR)
raise DistutilsError(msg)
-
- @property
- def _argv(self):
- return ['unittest'] + self.test_args
-
- @staticmethod
- def _resolve_as_ep(val):
- """
- Load the indicated attribute value, called, as a as if it were
- specified as an entry point.
- """
- if val is None:
- return
- parsed = EntryPoint.parse("x=" + val)
- return parsed.resolve()()
+
+ @property
+ def _argv(self):
+ return ['unittest'] + self.test_args
+
+ @staticmethod
+ def _resolve_as_ep(val):
+ """
+ Load the indicated attribute value, called, as a as if it were
+ specified as an entry point.
+ """
+ if val is None:
+ return
+ parsed = EntryPoint.parse("x=" + val)
+ return parsed.resolve()()
diff --git a/contrib/python/setuptools/py2/setuptools/command/upload_docs.py b/contrib/python/setuptools/py2/setuptools/command/upload_docs.py
index ca84dfc322..130a0cb6c9 100644
--- a/contrib/python/setuptools/py2/setuptools/command/upload_docs.py
+++ b/contrib/python/setuptools/py2/setuptools/command/upload_docs.py
@@ -1,107 +1,107 @@
-# -*- coding: utf-8 -*-
-"""upload_docs
-
-Implements a Distutils 'upload_docs' subcommand (upload documentation to
-PyPI's pythonhosted.org).
-"""
-
-from base64 import standard_b64encode
-from distutils import log
-from distutils.errors import DistutilsOptionError
-import os
-import socket
-import zipfile
-import tempfile
-import shutil
+# -*- coding: utf-8 -*-
+"""upload_docs
+
+Implements a Distutils 'upload_docs' subcommand (upload documentation to
+PyPI's pythonhosted.org).
+"""
+
+from base64 import standard_b64encode
+from distutils import log
+from distutils.errors import DistutilsOptionError
+import os
+import socket
+import zipfile
+import tempfile
+import shutil
import itertools
import functools
-
+
from setuptools.extern import six
from setuptools.extern.six.moves import http_client, urllib
-
-from pkg_resources import iter_entry_points
+
+from pkg_resources import iter_entry_points
from .upload import upload
-
-
+
+
def _encode(s):
errors = 'strict' if six.PY2 else 'surrogateescape'
return s.encode('utf-8', errors)
-
-
+
+
class upload_docs(upload):
# override the default repository as upload_docs isn't
# supported by Warehouse (and won't be).
DEFAULT_REPOSITORY = 'https://pypi.python.org/pypi/'
-
- description = 'Upload documentation to PyPI'
-
- user_options = [
- ('repository=', 'r',
- "url of repository [default: %s]" % upload.DEFAULT_REPOSITORY),
- ('show-response', None,
- 'display full response text from server'),
- ('upload-dir=', None, 'directory to upload'),
- ]
- boolean_options = upload.boolean_options
-
- def has_sphinx(self):
- if self.upload_dir is None:
- for ep in iter_entry_points('distutils.commands', 'build_sphinx'):
- return True
-
- sub_commands = [('build_sphinx', has_sphinx)]
-
- def initialize_options(self):
- upload.initialize_options(self)
- self.upload_dir = None
- self.target_dir = None
-
- def finalize_options(self):
- upload.finalize_options(self)
- if self.upload_dir is None:
- if self.has_sphinx():
- build_sphinx = self.get_finalized_command('build_sphinx')
- self.target_dir = build_sphinx.builder_target_dir
- else:
- build = self.get_finalized_command('build')
- self.target_dir = os.path.join(build.build_base, 'docs')
- else:
- self.ensure_dirname('upload_dir')
- self.target_dir = self.upload_dir
+
+ description = 'Upload documentation to PyPI'
+
+ user_options = [
+ ('repository=', 'r',
+ "url of repository [default: %s]" % upload.DEFAULT_REPOSITORY),
+ ('show-response', None,
+ 'display full response text from server'),
+ ('upload-dir=', None, 'directory to upload'),
+ ]
+ boolean_options = upload.boolean_options
+
+ def has_sphinx(self):
+ if self.upload_dir is None:
+ for ep in iter_entry_points('distutils.commands', 'build_sphinx'):
+ return True
+
+ sub_commands = [('build_sphinx', has_sphinx)]
+
+ def initialize_options(self):
+ upload.initialize_options(self)
+ self.upload_dir = None
+ self.target_dir = None
+
+ def finalize_options(self):
+ upload.finalize_options(self)
+ if self.upload_dir is None:
+ if self.has_sphinx():
+ build_sphinx = self.get_finalized_command('build_sphinx')
+ self.target_dir = build_sphinx.builder_target_dir
+ else:
+ build = self.get_finalized_command('build')
+ self.target_dir = os.path.join(build.build_base, 'docs')
+ else:
+ self.ensure_dirname('upload_dir')
+ self.target_dir = self.upload_dir
if 'pypi.python.org' in self.repository:
log.warn("Upload_docs command is deprecated. Use RTD instead.")
- self.announce('Using upload directory %s' % self.target_dir)
-
- def create_zipfile(self, filename):
- zip_file = zipfile.ZipFile(filename, "w")
- try:
- self.mkpath(self.target_dir) # just in case
- for root, dirs, files in os.walk(self.target_dir):
- if root == self.target_dir and not files:
+ self.announce('Using upload directory %s' % self.target_dir)
+
+ def create_zipfile(self, filename):
+ zip_file = zipfile.ZipFile(filename, "w")
+ try:
+ self.mkpath(self.target_dir) # just in case
+ for root, dirs, files in os.walk(self.target_dir):
+ if root == self.target_dir and not files:
tmpl = "no files found in upload directory '%s'"
raise DistutilsOptionError(tmpl % self.target_dir)
- for name in files:
- full = os.path.join(root, name)
- relative = root[len(self.target_dir):].lstrip(os.path.sep)
- dest = os.path.join(relative, name)
- zip_file.write(full, dest)
- finally:
- zip_file.close()
-
- def run(self):
- # Run sub commands
- for cmd_name in self.get_sub_commands():
- self.run_command(cmd_name)
-
- tmp_dir = tempfile.mkdtemp()
- name = self.distribution.metadata.get_name()
- zip_file = os.path.join(tmp_dir, "%s.zip" % name)
- try:
- self.create_zipfile(zip_file)
- self.upload_file(zip_file)
- finally:
- shutil.rmtree(tmp_dir)
-
+ for name in files:
+ full = os.path.join(root, name)
+ relative = root[len(self.target_dir):].lstrip(os.path.sep)
+ dest = os.path.join(relative, name)
+ zip_file.write(full, dest)
+ finally:
+ zip_file.close()
+
+ def run(self):
+ # Run sub commands
+ for cmd_name in self.get_sub_commands():
+ self.run_command(cmd_name)
+
+ tmp_dir = tempfile.mkdtemp()
+ name = self.distribution.metadata.get_name()
+ zip_file = os.path.join(tmp_dir, "%s.zip" % name)
+ try:
+ self.create_zipfile(zip_file)
+ self.upload_file(zip_file)
+ finally:
+ shutil.rmtree(tmp_dir)
+
@staticmethod
def _build_part(item, sep_boundary):
key, values = item
@@ -141,66 +141,66 @@ class upload_docs(upload):
content_type = 'multipart/form-data; boundary=%s' % boundary.decode('ascii')
return b''.join(body_items), content_type
- def upload_file(self, filename):
+ def upload_file(self, filename):
with open(filename, 'rb') as f:
content = f.read()
- meta = self.distribution.metadata
- data = {
- ':action': 'doc_upload',
- 'name': meta.get_name(),
- 'content': (os.path.basename(filename), content),
- }
- # set up the authentication
+ meta = self.distribution.metadata
+ data = {
+ ':action': 'doc_upload',
+ 'name': meta.get_name(),
+ 'content': (os.path.basename(filename), content),
+ }
+ # set up the authentication
credentials = _encode(self.username + ':' + self.password)
- credentials = standard_b64encode(credentials)
+ credentials = standard_b64encode(credentials)
if not six.PY2:
- credentials = credentials.decode('ascii')
- auth = "Basic " + credentials
-
+ credentials = credentials.decode('ascii')
+ auth = "Basic " + credentials
+
body, ct = self._build_multipart(data)
-
+
msg = "Submitting documentation to %s" % (self.repository)
self.announce(msg, log.INFO)
-
- # build the Request
- # We can't use urllib2 since we need to send the Basic
- # auth right with the first request
- schema, netloc, url, params, query, fragments = \
- urllib.parse.urlparse(self.repository)
- assert not params and not query and not fragments
- if schema == 'http':
- conn = http_client.HTTPConnection(netloc)
- elif schema == 'https':
- conn = http_client.HTTPSConnection(netloc)
- else:
- raise AssertionError("unsupported schema " + schema)
-
- data = ''
- try:
- conn.connect()
- conn.putrequest("POST", url)
+
+ # build the Request
+ # We can't use urllib2 since we need to send the Basic
+ # auth right with the first request
+ schema, netloc, url, params, query, fragments = \
+ urllib.parse.urlparse(self.repository)
+ assert not params and not query and not fragments
+ if schema == 'http':
+ conn = http_client.HTTPConnection(netloc)
+ elif schema == 'https':
+ conn = http_client.HTTPSConnection(netloc)
+ else:
+ raise AssertionError("unsupported schema " + schema)
+
+ data = ''
+ try:
+ conn.connect()
+ conn.putrequest("POST", url)
content_type = ct
- conn.putheader('Content-type', content_type)
- conn.putheader('Content-length', str(len(body)))
- conn.putheader('Authorization', auth)
- conn.endheaders()
- conn.send(body)
- except socket.error as e:
- self.announce(str(e), log.ERROR)
- return
-
- r = conn.getresponse()
- if r.status == 200:
+ conn.putheader('Content-type', content_type)
+ conn.putheader('Content-length', str(len(body)))
+ conn.putheader('Authorization', auth)
+ conn.endheaders()
+ conn.send(body)
+ except socket.error as e:
+ self.announce(str(e), log.ERROR)
+ return
+
+ r = conn.getresponse()
+ if r.status == 200:
msg = 'Server response (%s): %s' % (r.status, r.reason)
self.announce(msg, log.INFO)
- elif r.status == 301:
- location = r.getheader('Location')
- if location is None:
- location = 'https://pythonhosted.org/%s/' % meta.get_name()
+ elif r.status == 301:
+ location = r.getheader('Location')
+ if location is None:
+ location = 'https://pythonhosted.org/%s/' % meta.get_name()
msg = 'Upload successful. Visit %s' % location
self.announce(msg, log.INFO)
- else:
+ else:
msg = 'Upload failed (%s): %s' % (r.status, r.reason)
self.announce(msg, log.ERROR)
- if self.show_response:
- print('-' * 75, r.read(), '-' * 75)
+ if self.show_response:
+ print('-' * 75, r.read(), '-' * 75)
diff --git a/contrib/python/setuptools/py2/setuptools/depends.py b/contrib/python/setuptools/py2/setuptools/depends.py
index bc2b767ff1..a37675cbd9 100644
--- a/contrib/python/setuptools/py2/setuptools/depends.py
+++ b/contrib/python/setuptools/py2/setuptools/depends.py
@@ -1,87 +1,87 @@
-import sys
-import marshal
+import sys
+import marshal
import contextlib
from distutils.version import StrictVersion
-
+
from .py33compat import Bytecode
-
+
from .py27compat import find_module, PY_COMPILED, PY_FROZEN, PY_SOURCE
from . import py27compat
-__all__ = [
- 'Require', 'find_module', 'get_module_constant', 'extract_constant'
-]
-
+__all__ = [
+ 'Require', 'find_module', 'get_module_constant', 'extract_constant'
+]
+
+
+class Require:
+ """A prerequisite to building or installing a distribution"""
-class Require:
- """A prerequisite to building or installing a distribution"""
-
def __init__(
self, name, requested_version, module, homepage='',
- attribute=None, format=None):
-
- if format is None and requested_version is not None:
- format = StrictVersion
-
- if format is not None:
- requested_version = format(requested_version)
- if attribute is None:
- attribute = '__version__'
-
- self.__dict__.update(locals())
- del self.self
-
- def full_name(self):
- """Return full package/distribution name, w/version"""
- if self.requested_version is not None:
+ attribute=None, format=None):
+
+ if format is None and requested_version is not None:
+ format = StrictVersion
+
+ if format is not None:
+ requested_version = format(requested_version)
+ if attribute is None:
+ attribute = '__version__'
+
+ self.__dict__.update(locals())
+ del self.self
+
+ def full_name(self):
+ """Return full package/distribution name, w/version"""
+ if self.requested_version is not None:
return '%s-%s' % (self.name, self.requested_version)
- return self.name
-
- def version_ok(self, version):
- """Is 'version' sufficiently up-to-date?"""
- return self.attribute is None or self.format is None or \
- str(version) != "unknown" and version >= self.requested_version
-
- def get_version(self, paths=None, default="unknown"):
- """Get version number of installed module, 'None', or 'default'
-
- Search 'paths' for module. If not found, return 'None'. If found,
- return the extracted version attribute, or 'default' if no version
- attribute was specified, or the value cannot be determined without
- importing the module. The version is formatted according to the
- requirement's version format (if any), unless it is 'None' or the
- supplied 'default'.
- """
-
- if self.attribute is None:
- try:
+ return self.name
+
+ def version_ok(self, version):
+ """Is 'version' sufficiently up-to-date?"""
+ return self.attribute is None or self.format is None or \
+ str(version) != "unknown" and version >= self.requested_version
+
+ def get_version(self, paths=None, default="unknown"):
+ """Get version number of installed module, 'None', or 'default'
+
+ Search 'paths' for module. If not found, return 'None'. If found,
+ return the extracted version attribute, or 'default' if no version
+ attribute was specified, or the value cannot be determined without
+ importing the module. The version is formatted according to the
+ requirement's version format (if any), unless it is 'None' or the
+ supplied 'default'.
+ """
+
+ if self.attribute is None:
+ try:
f, p, i = find_module(self.module, paths)
if f:
f.close()
- return default
- except ImportError:
- return None
-
- v = get_module_constant(self.module, self.attribute, default, paths)
-
- if v is not None and v is not default and self.format is not None:
- return self.format(v)
-
- return v
-
- def is_present(self, paths=None):
- """Return true if dependency is present on 'paths'"""
- return self.get_version(paths) is not None
-
- def is_current(self, paths=None):
- """Return true if dependency is present and up-to-date on 'paths'"""
- version = self.get_version(paths)
- if version is None:
- return False
- return self.version_ok(version)
-
-
+ return default
+ except ImportError:
+ return None
+
+ v = get_module_constant(self.module, self.attribute, default, paths)
+
+ if v is not None and v is not default and self.format is not None:
+ return self.format(v)
+
+ return v
+
+ def is_present(self, paths=None):
+ """Return true if dependency is present on 'paths'"""
+ return self.get_version(paths) is not None
+
+ def is_current(self, paths=None):
+ """Return true if dependency is present and up-to-date on 'paths'"""
+ version = self.get_version(paths)
+ if version is None:
+ return False
+ return self.version_ok(version)
+
+
def maybe_close(f):
@contextlib.contextmanager
def empty():
@@ -89,88 +89,88 @@ def maybe_close(f):
return
if not f:
return empty()
-
+
return contextlib.closing(f)
-
-
-def get_module_constant(module, symbol, default=-1, paths=None):
- """Find 'module' by searching 'paths', and extract 'symbol'
-
- Return 'None' if 'module' does not exist on 'paths', or it does not define
- 'symbol'. If the module defines 'symbol' as a constant, return the
- constant. Otherwise, return 'default'."""
-
- try:
+
+
+def get_module_constant(module, symbol, default=-1, paths=None):
+ """Find 'module' by searching 'paths', and extract 'symbol'
+
+ Return 'None' if 'module' does not exist on 'paths', or it does not define
+ 'symbol'. If the module defines 'symbol' as a constant, return the
+ constant. Otherwise, return 'default'."""
+
+ try:
f, path, (suffix, mode, kind) = info = find_module(module, paths)
- except ImportError:
- # Module doesn't exist
- return None
-
+ except ImportError:
+ # Module doesn't exist
+ return None
+
with maybe_close(f):
if kind == PY_COMPILED:
f.read(8) # skip magic & date
- code = marshal.load(f)
+ code = marshal.load(f)
elif kind == PY_FROZEN:
code = py27compat.get_frozen_object(module, paths)
elif kind == PY_SOURCE:
- code = compile(f.read(), path, 'exec')
- else:
- # Not something we can parse; we'll have to import it. :(
+ code = compile(f.read(), path, 'exec')
+ else:
+ # Not something we can parse; we'll have to import it. :(
imported = py27compat.get_module(module, paths, info)
return getattr(imported, symbol, None)
-
- return extract_constant(code, symbol, default)
-
-
-def extract_constant(code, symbol, default=-1):
- """Extract the constant value of 'symbol' from 'code'
-
- If the name 'symbol' is bound to a constant value by the Python code
- object 'code', return that value. If 'symbol' is bound to an expression,
- return 'default'. Otherwise, return 'None'.
-
- Return value is based on the first assignment to 'symbol'. 'symbol' must
- be a global, or at least a non-"fast" local in the code block. That is,
- only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
- must be present in 'code.co_names'.
- """
- if symbol not in code.co_names:
+
+ return extract_constant(code, symbol, default)
+
+
+def extract_constant(code, symbol, default=-1):
+ """Extract the constant value of 'symbol' from 'code'
+
+ If the name 'symbol' is bound to a constant value by the Python code
+ object 'code', return that value. If 'symbol' is bound to an expression,
+ return 'default'. Otherwise, return 'None'.
+
+ Return value is based on the first assignment to 'symbol'. 'symbol' must
+ be a global, or at least a non-"fast" local in the code block. That is,
+ only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
+ must be present in 'code.co_names'.
+ """
+ if symbol not in code.co_names:
# name's not there, can't possibly be an assignment
- return None
-
- name_idx = list(code.co_names).index(symbol)
-
- STORE_NAME = 90
- STORE_GLOBAL = 97
- LOAD_CONST = 100
-
- const = default
-
+ return None
+
+ name_idx = list(code.co_names).index(symbol)
+
+ STORE_NAME = 90
+ STORE_GLOBAL = 97
+ LOAD_CONST = 100
+
+ const = default
+
for byte_code in Bytecode(code):
op = byte_code.opcode
arg = byte_code.arg
-
+
if op == LOAD_CONST:
- const = code.co_consts[arg]
+ const = code.co_consts[arg]
elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):
- return const
- else:
- const = default
-
-
-def _update_globals():
- """
- Patch the globals to remove the objects not available on some platforms.
-
- XXX it'd be better to test assertions about bytecode instead.
- """
-
- if not sys.platform.startswith('java') and sys.platform != 'cli':
- return
- incompatible = 'extract_constant', 'get_module_constant'
- for name in incompatible:
- del globals()[name]
- __all__.remove(name)
-
-
-_update_globals()
+ return const
+ else:
+ const = default
+
+
+def _update_globals():
+ """
+ Patch the globals to remove the objects not available on some platforms.
+
+ XXX it'd be better to test assertions about bytecode instead.
+ """
+
+ if not sys.platform.startswith('java') and sys.platform != 'cli':
+ return
+ incompatible = 'extract_constant', 'get_module_constant'
+ for name in incompatible:
+ del globals()[name]
+ __all__.remove(name)
+
+
+_update_globals()
diff --git a/contrib/python/setuptools/py2/setuptools/dist.py b/contrib/python/setuptools/py2/setuptools/dist.py
index c381b4ac54..f6453a0878 100644
--- a/contrib/python/setuptools/py2/setuptools/dist.py
+++ b/contrib/python/setuptools/py2/setuptools/dist.py
@@ -1,16 +1,16 @@
# -*- coding: utf-8 -*-
-__all__ = ['Distribution']
-
+__all__ = ['Distribution']
+
import io
import sys
-import re
-import os
-import warnings
-import numbers
-import distutils.log
-import distutils.core
-import distutils.cmd
-import distutils.dist
+import re
+import os
+import warnings
+import numbers
+import distutils.log
+import distutils.core
+import distutils.cmd
+import distutils.dist
from distutils.util import strtobool
from distutils.debug import DEBUG
from distutils.fancy_getopt import translate_longopt
@@ -24,28 +24,28 @@ from distutils.errors import (
)
from distutils.util import rfc822_escape
from distutils.version import StrictVersion
-
+
from setuptools.extern import six
from setuptools.extern import packaging
from setuptools.extern import ordered_set
from setuptools.extern.six.moves import map, filter, filterfalse
-
+
from . import SetuptoolsDeprecationWarning
-from setuptools.depends import Require
-from setuptools import windows_support
+from setuptools.depends import Require
+from setuptools import windows_support
from setuptools.monkey import get_unpatched
from setuptools.config import parse_configuration
-import pkg_resources
-
+import pkg_resources
+
__import__('setuptools.extern.packaging.specifiers')
__import__('setuptools.extern.packaging.version')
-
-def _get_unpatched(cls):
+
+def _get_unpatched(cls):
warnings.warn("Do not call this function", DistDeprecationWarning)
return get_unpatched(cls)
-
+
def get_metadata_version(self):
mv = getattr(self, 'metadata_version', None)
@@ -125,9 +125,9 @@ def read_pkg_file(self, file):
# Based on Python 3.5 version
def write_pkg_file(self, file):
"""Write the PKG-INFO format data to a file object.
- """
+ """
version = self.get_metadata_version()
-
+
if six.PY2:
def write_field(key, value):
file.write("%s: %s\n" % (key, self._encode_field(value)))
@@ -163,7 +163,7 @@ def write_pkg_file(self, file):
write_field('Download-URL', self.download_url)
for project_url in self.project_urls.items():
write_field('Project-URL', '%s, %s' % project_url)
-
+
long_desc = rfc822_escape(self.get_long_description())
write_field('Description', long_desc)
@@ -198,64 +198,64 @@ def write_pkg_file(self, file):
for extra in self.provides_extras:
write_field('Provides-Extra', extra)
-
-sequence = tuple, list
-
-def check_importable(dist, attr, value):
- try:
+sequence = tuple, list
+
+
+def check_importable(dist, attr, value):
+ try:
ep = pkg_resources.EntryPoint.parse('x=' + value)
- assert not ep.extras
+ assert not ep.extras
except (TypeError, ValueError, AttributeError, AssertionError):
- raise DistutilsSetupError(
- "%r must be importable 'module:attrs' string (got %r)"
+ raise DistutilsSetupError(
+ "%r must be importable 'module:attrs' string (got %r)"
% (attr, value)
- )
-
-
-def assert_string_list(dist, attr, value):
+ )
+
+
+def assert_string_list(dist, attr, value):
"""Verify that value is a string list"""
- try:
+ try:
# verify that value is a list or tuple to exclude unordered
# or single-use iterables
assert isinstance(value, (list, tuple))
# verify that elements of value are strings
assert ''.join(value) != value
except (TypeError, ValueError, AttributeError, AssertionError):
- raise DistutilsSetupError(
+ raise DistutilsSetupError(
"%r must be a list of strings (got %r)" % (attr, value)
- )
+ )
-def check_nsp(dist, attr, value):
- """Verify that namespace packages are valid"""
+def check_nsp(dist, attr, value):
+ """Verify that namespace packages are valid"""
ns_packages = value
assert_string_list(dist, attr, ns_packages)
for nsp in ns_packages:
- if not dist.has_contents_for(nsp):
- raise DistutilsSetupError(
- "Distribution contains no modules or packages for " +
- "namespace package %r" % nsp
- )
+ if not dist.has_contents_for(nsp):
+ raise DistutilsSetupError(
+ "Distribution contains no modules or packages for " +
+ "namespace package %r" % nsp
+ )
parent, sep, child = nsp.rpartition('.')
if parent and parent not in ns_packages:
distutils.log.warn(
"WARNING: %r is declared as a package namespace, but %r"
" is not: please correct this in setup.py", nsp, parent
)
-
-def check_extras(dist, attr, value):
- """Verify that extras_require mapping is valid"""
- try:
+
+def check_extras(dist, attr, value):
+ """Verify that extras_require mapping is valid"""
+ try:
list(itertools.starmap(_check_extra, value.items()))
except (TypeError, ValueError, AttributeError):
- raise DistutilsSetupError(
- "'extras_require' must be a dictionary whose values are "
- "strings or lists of strings containing valid project/version "
- "requirement specifiers."
- )
-
+ raise DistutilsSetupError(
+ "'extras_require' must be a dictionary whose values are "
+ "strings or lists of strings containing valid project/version "
+ "requirement specifiers."
+ )
+
def _check_extra(extra, reqs):
name, sep, marker = extra.partition(':')
@@ -264,26 +264,26 @@ def _check_extra(extra, reqs):
list(pkg_resources.parse_requirements(reqs))
-def assert_bool(dist, attr, value):
- """Verify that value is True, False, 0, or 1"""
- if bool(value) != value:
- tmpl = "{attr!r} must be a boolean value (got {value!r})"
- raise DistutilsSetupError(tmpl.format(attr=attr, value=value))
-
-
-def check_requirements(dist, attr, value):
- """Verify that install_requires is a valid requirements list"""
- try:
- list(pkg_resources.parse_requirements(value))
+def assert_bool(dist, attr, value):
+ """Verify that value is True, False, 0, or 1"""
+ if bool(value) != value:
+ tmpl = "{attr!r} must be a boolean value (got {value!r})"
+ raise DistutilsSetupError(tmpl.format(attr=attr, value=value))
+
+
+def check_requirements(dist, attr, value):
+ """Verify that install_requires is a valid requirements list"""
+ try:
+ list(pkg_resources.parse_requirements(value))
if isinstance(value, (dict, set)):
raise TypeError("Unordered types are not allowed")
- except (TypeError, ValueError) as error:
- tmpl = (
- "{attr!r} must be a string or list of strings "
- "containing valid project/version requirement specifiers; {error}"
- )
- raise DistutilsSetupError(tmpl.format(attr=attr, error=error))
-
+ except (TypeError, ValueError) as error:
+ tmpl = (
+ "{attr!r} must be a string or list of strings "
+ "containing valid project/version requirement specifiers; {error}"
+ )
+ raise DistutilsSetupError(tmpl.format(attr=attr, error=error))
+
def check_specifier(dist, attr, value):
"""Verify that value is a valid version specifier"""
@@ -297,21 +297,21 @@ def check_specifier(dist, attr, value):
raise DistutilsSetupError(tmpl.format(attr=attr, error=error))
-def check_entry_points(dist, attr, value):
- """Verify that entry_points map is parseable"""
- try:
- pkg_resources.EntryPoint.parse_map(value)
- except ValueError as e:
- raise DistutilsSetupError(e)
-
+def check_entry_points(dist, attr, value):
+ """Verify that entry_points map is parseable"""
+ try:
+ pkg_resources.EntryPoint.parse_map(value)
+ except ValueError as e:
+ raise DistutilsSetupError(e)
-def check_test_suite(dist, attr, value):
- if not isinstance(value, six.string_types):
- raise DistutilsSetupError("test_suite must be a string")
-
-def check_package_data(dist, attr, value):
- """Verify that value is a dictionary of package names to glob lists"""
+def check_test_suite(dist, attr, value):
+ if not isinstance(value, six.string_types):
+ raise DistutilsSetupError("test_suite must be a string")
+
+
+def check_package_data(dist, attr, value):
+ """Verify that value is a dictionary of package names to glob lists"""
if not isinstance(value, dict):
raise DistutilsSetupError(
"{!r} must be a dictionary mapping package names to lists of "
@@ -323,88 +323,88 @@ def check_package_data(dist, attr, value):
.format(attr, k)
)
assert_string_list(dist, 'values of {!r} dict'.format(attr), v)
-
-
-def check_packages(dist, attr, value):
- for pkgname in value:
- if not re.match(r'\w+(\.\w+)*', pkgname):
- distutils.log.warn(
- "WARNING: %r not a valid package name; please use only "
- ".-separated package names in setup.py", pkgname
- )
-
-
+
+
+def check_packages(dist, attr, value):
+ for pkgname in value:
+ if not re.match(r'\w+(\.\w+)*', pkgname):
+ distutils.log.warn(
+ "WARNING: %r not a valid package name; please use only "
+ ".-separated package names in setup.py", pkgname
+ )
+
+
_Distribution = get_unpatched(distutils.core.Distribution)
class Distribution(_Distribution):
- """Distribution with support for features, tests, and package data
-
- This is an enhanced version of 'distutils.dist.Distribution' that
- effectively adds the following new optional keyword arguments to 'setup()':
-
- 'install_requires' -- a string or sequence of strings specifying project
- versions that the distribution requires when installed, in the format
- used by 'pkg_resources.require()'. They will be installed
- automatically when the package is installed. If you wish to use
- packages that are not available in PyPI, or want to give your users an
- alternate download location, you can add a 'find_links' option to the
- '[easy_install]' section of your project's 'setup.cfg' file, and then
- setuptools will scan the listed web pages for links that satisfy the
- requirements.
-
- 'extras_require' -- a dictionary mapping names of optional "extras" to the
- additional requirement(s) that using those extras incurs. For example,
- this::
-
- extras_require = dict(reST = ["docutils>=0.3", "reSTedit"])
-
- indicates that the distribution can optionally provide an extra
- capability called "reST", but it can only be used if docutils and
- reSTedit are installed. If the user installs your package using
- EasyInstall and requests one of your extras, the corresponding
- additional requirements will be installed if needed.
-
- 'features' **deprecated** -- a dictionary mapping option names to
- 'setuptools.Feature'
- objects. Features are a portion of the distribution that can be
- included or excluded based on user options, inter-feature dependencies,
- and availability on the current system. Excluded features are omitted
- from all setup commands, including source and binary distributions, so
- you can create multiple distributions from the same source tree.
- Feature names should be valid Python identifiers, except that they may
- contain the '-' (minus) sign. Features can be included or excluded
- via the command line options '--with-X' and '--without-X', where 'X' is
- the name of the feature. Whether a feature is included by default, and
- whether you are allowed to control this from the command line, is
- determined by the Feature object. See the 'Feature' class for more
- information.
-
- 'test_suite' -- the name of a test suite to run for the 'test' command.
- If the user runs 'python setup.py test', the package will be installed,
- and the named test suite will be run. The format is the same as
- would be used on a 'unittest.py' command line. That is, it is the
- dotted name of an object to import and call to generate a test suite.
-
- 'package_data' -- a dictionary mapping package names to lists of filenames
- or globs to use to find data files contained in the named packages.
- If the dictionary has filenames or globs listed under '""' (the empty
- string), those names will be searched for in every package, in addition
- to any names for the specific package. Data files found using these
- names/globs will be installed along with the package, in the same
- location as the package. Note that globs are allowed to reference
- the contents of non-package subdirectories, as long as you use '/' as
- a path separator. (Globs are automatically converted to
- platform-specific paths at runtime.)
-
- In addition to these new keywords, this class also has several new methods
- for manipulating the distribution's contents. For example, the 'include()'
- and 'exclude()' methods can be thought of as in-place add and subtract
- commands that add or remove packages, modules, extensions, and so on from
- the distribution. They are used by the feature subsystem to configure the
- distribution for the included and excluded features.
- """
-
+ """Distribution with support for features, tests, and package data
+
+ This is an enhanced version of 'distutils.dist.Distribution' that
+ effectively adds the following new optional keyword arguments to 'setup()':
+
+ 'install_requires' -- a string or sequence of strings specifying project
+ versions that the distribution requires when installed, in the format
+ used by 'pkg_resources.require()'. They will be installed
+ automatically when the package is installed. If you wish to use
+ packages that are not available in PyPI, or want to give your users an
+ alternate download location, you can add a 'find_links' option to the
+ '[easy_install]' section of your project's 'setup.cfg' file, and then
+ setuptools will scan the listed web pages for links that satisfy the
+ requirements.
+
+ 'extras_require' -- a dictionary mapping names of optional "extras" to the
+ additional requirement(s) that using those extras incurs. For example,
+ this::
+
+ extras_require = dict(reST = ["docutils>=0.3", "reSTedit"])
+
+ indicates that the distribution can optionally provide an extra
+ capability called "reST", but it can only be used if docutils and
+ reSTedit are installed. If the user installs your package using
+ EasyInstall and requests one of your extras, the corresponding
+ additional requirements will be installed if needed.
+
+ 'features' **deprecated** -- a dictionary mapping option names to
+ 'setuptools.Feature'
+ objects. Features are a portion of the distribution that can be
+ included or excluded based on user options, inter-feature dependencies,
+ and availability on the current system. Excluded features are omitted
+ from all setup commands, including source and binary distributions, so
+ you can create multiple distributions from the same source tree.
+ Feature names should be valid Python identifiers, except that they may
+ contain the '-' (minus) sign. Features can be included or excluded
+ via the command line options '--with-X' and '--without-X', where 'X' is
+ the name of the feature. Whether a feature is included by default, and
+ whether you are allowed to control this from the command line, is
+ determined by the Feature object. See the 'Feature' class for more
+ information.
+
+ 'test_suite' -- the name of a test suite to run for the 'test' command.
+ If the user runs 'python setup.py test', the package will be installed,
+ and the named test suite will be run. The format is the same as
+ would be used on a 'unittest.py' command line. That is, it is the
+ dotted name of an object to import and call to generate a test suite.
+
+ 'package_data' -- a dictionary mapping package names to lists of filenames
+ or globs to use to find data files contained in the named packages.
+ If the dictionary has filenames or globs listed under '""' (the empty
+ string), those names will be searched for in every package, in addition
+ to any names for the specific package. Data files found using these
+ names/globs will be installed along with the package, in the same
+ location as the package. Note that globs are allowed to reference
+ the contents of non-package subdirectories, as long as you use '/' as
+ a path separator. (Globs are automatically converted to
+ platform-specific paths at runtime.)
+
+ In addition to these new keywords, this class also has several new methods
+ for manipulating the distribution's contents. For example, the 'include()'
+ and 'exclude()' methods can be thought of as in-place add and subtract
+ commands that add or remove packages, modules, extensions, and so on from
+ the distribution. They are used by the feature subsystem to configure the
+ distribution for the included and excluded features.
+ """
+
_DISTUTILS_UNSUPPORTED_METADATA = {
'long_description_content_type': None,
'project_urls': dict,
@@ -412,38 +412,38 @@ class Distribution(_Distribution):
'license_files': ordered_set.OrderedSet,
}
- _patched_dist = None
-
- def patch_missing_pkg_info(self, attrs):
- # Fake up a replacement for the data that would normally come from
- # PKG-INFO, but which might not yet be built if this is a fresh
- # checkout.
- #
- if not attrs or 'name' not in attrs or 'version' not in attrs:
- return
- key = pkg_resources.safe_name(str(attrs['name'])).lower()
- dist = pkg_resources.working_set.by_key.get(key)
- if dist is not None and not dist.has_metadata('PKG-INFO'):
- dist._version = pkg_resources.safe_version(str(attrs['version']))
- self._patched_dist = dist
-
- def __init__(self, attrs=None):
- have_package_data = hasattr(self, "package_data")
- if not have_package_data:
- self.package_data = {}
+ _patched_dist = None
+
+ def patch_missing_pkg_info(self, attrs):
+ # Fake up a replacement for the data that would normally come from
+ # PKG-INFO, but which might not yet be built if this is a fresh
+ # checkout.
+ #
+ if not attrs or 'name' not in attrs or 'version' not in attrs:
+ return
+ key = pkg_resources.safe_name(str(attrs['name'])).lower()
+ dist = pkg_resources.working_set.by_key.get(key)
+ if dist is not None and not dist.has_metadata('PKG-INFO'):
+ dist._version = pkg_resources.safe_version(str(attrs['version']))
+ self._patched_dist = dist
+
+ def __init__(self, attrs=None):
+ have_package_data = hasattr(self, "package_data")
+ if not have_package_data:
+ self.package_data = {}
attrs = attrs or {}
if 'features' in attrs or 'require_features' in attrs:
- Feature.warn_deprecated()
- self.require_features = []
- self.features = {}
- self.dist_files = []
+ Feature.warn_deprecated()
+ self.require_features = []
+ self.features = {}
+ self.dist_files = []
# Filter-out setuptools' specific options.
self.src_root = attrs.pop("src_root", None)
- self.patch_missing_pkg_info(attrs)
+ self.patch_missing_pkg_info(attrs)
self.dependency_links = attrs.pop('dependency_links', [])
self.setup_requires = attrs.pop('setup_requires', [])
- for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
- vars(self).setdefault(ep.name, None)
+ for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
+ vars(self).setdefault(ep.name, None)
_Distribution.__init__(self, {
k: v for k, v in attrs.items()
if k not in self._DISTUTILS_UNSUPPORTED_METADATA
@@ -461,29 +461,29 @@ class Distribution(_Distribution):
value = default() if default else None
setattr(self.metadata, option, value)
- if isinstance(self.metadata.version, numbers.Number):
- # Some people apparently take "version number" too literally :)
- self.metadata.version = str(self.metadata.version)
-
- if self.metadata.version is not None:
- try:
- ver = packaging.version.Version(self.metadata.version)
- normalized_version = str(ver)
- if self.metadata.version != normalized_version:
- warnings.warn(
- "Normalizing '%s' to '%s'" % (
- self.metadata.version,
- normalized_version,
- )
- )
- self.metadata.version = normalized_version
- except (packaging.version.InvalidVersion, TypeError):
- warnings.warn(
- "The version specified (%r) is an invalid version, this "
- "may not work as expected with newer versions of "
- "setuptools, pip, and PyPI. Please see PEP 440 for more "
- "details." % self.metadata.version
- )
+ if isinstance(self.metadata.version, numbers.Number):
+ # Some people apparently take "version number" too literally :)
+ self.metadata.version = str(self.metadata.version)
+
+ if self.metadata.version is not None:
+ try:
+ ver = packaging.version.Version(self.metadata.version)
+ normalized_version = str(ver)
+ if self.metadata.version != normalized_version:
+ warnings.warn(
+ "Normalizing '%s' to '%s'" % (
+ self.metadata.version,
+ normalized_version,
+ )
+ )
+ self.metadata.version = normalized_version
+ except (packaging.version.InvalidVersion, TypeError):
+ warnings.warn(
+ "The version specified (%r) is an invalid version, this "
+ "may not work as expected with newer versions of "
+ "setuptools, pip, and PyPI. Please see PEP 440 for more "
+ "details." % self.metadata.version
+ )
self._finalize_requires()
def _finalize_requires(self):
@@ -493,7 +493,7 @@ class Distribution(_Distribution):
"""
if getattr(self, 'python_requires', None):
self.metadata.python_requires = self.python_requires
-
+
if getattr(self, 'extras_require', None):
for extra in self.extras_require.keys():
# Since this gets called multiple times at points where the
@@ -702,29 +702,29 @@ class Distribution(_Distribution):
ignore_option_errors=ignore_option_errors)
self._finalize_requires()
- def parse_command_line(self):
- """Process features after parsing command line options"""
- result = _Distribution.parse_command_line(self)
- if self.features:
- self._finalize_features()
- return result
-
+ def parse_command_line(self):
+ """Process features after parsing command line options"""
+ result = _Distribution.parse_command_line(self)
+ if self.features:
+ self._finalize_features()
+ return result
+
def _feature_attrname(self, name):
- """Convert feature name to corresponding option attribute name"""
+ """Convert feature name to corresponding option attribute name"""
return 'with_' + name.replace('-', '_')
-
- def fetch_build_eggs(self, requires):
- """Resolve pre-setup requirements"""
- resolved_dists = pkg_resources.working_set.resolve(
- pkg_resources.parse_requirements(requires),
- installer=self.fetch_build_egg,
- replace_conflicting=True,
- )
- for dist in resolved_dists:
- pkg_resources.working_set.add(dist, replace=True)
+
+ def fetch_build_eggs(self, requires):
+ """Resolve pre-setup requirements"""
+ resolved_dists = pkg_resources.working_set.resolve(
+ pkg_resources.parse_requirements(requires),
+ installer=self.fetch_build_egg,
+ replace_conflicting=True,
+ )
+ for dist in resolved_dists:
+ pkg_resources.working_set.add(dist, replace=True)
return resolved_dists
-
- def finalize_options(self):
+
+ def finalize_options(self):
"""
Allow plugins to apply arbitrary operations to the
distribution. Each hook may optionally define a 'order'
@@ -732,7 +732,7 @@ class Distribution(_Distribution):
go first and the default is 0.
"""
group = 'setuptools.finalize_distribution_options'
-
+
def by_order(hook):
return getattr(hook, 'order', 0)
eps = map(lambda e: e.load(), pkg_resources.iter_entry_points(group))
@@ -740,533 +740,533 @@ class Distribution(_Distribution):
ep(self)
def _finalize_setup_keywords(self):
- for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
+ for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, ep.name, None)
- if value is not None:
- ep.require(installer=self.fetch_build_egg)
- ep.load()(self, ep.name, value)
+ if value is not None:
+ ep.require(installer=self.fetch_build_egg)
+ ep.load()(self, ep.name, value)
def _finalize_2to3_doctests(self):
- if getattr(self, 'convert_2to3_doctests', None):
- # XXX may convert to set here when we can rely on set being builtin
+ if getattr(self, 'convert_2to3_doctests', None):
+ # XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [
os.path.abspath(p)
for p in self.convert_2to3_doctests
]
- else:
- self.convert_2to3_doctests = []
-
- def get_egg_cache_dir(self):
- egg_cache_dir = os.path.join(os.curdir, '.eggs')
- if not os.path.exists(egg_cache_dir):
- os.mkdir(egg_cache_dir)
- windows_support.hide_file(egg_cache_dir)
- readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
- with open(readme_txt_filename, 'w') as f:
- f.write('This directory contains eggs that were downloaded '
- 'by setuptools to build, test, and run plug-ins.\n\n')
- f.write('This directory caches those eggs to prevent '
- 'repeated downloads.\n\n')
- f.write('However, it is safe to delete this directory.\n\n')
-
- return egg_cache_dir
-
- def fetch_build_egg(self, req):
- """Fetch an egg needed for building"""
+ else:
+ self.convert_2to3_doctests = []
+
+ def get_egg_cache_dir(self):
+ egg_cache_dir = os.path.join(os.curdir, '.eggs')
+ if not os.path.exists(egg_cache_dir):
+ os.mkdir(egg_cache_dir)
+ windows_support.hide_file(egg_cache_dir)
+ readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
+ with open(readme_txt_filename, 'w') as f:
+ f.write('This directory contains eggs that were downloaded '
+ 'by setuptools to build, test, and run plug-ins.\n\n')
+ f.write('This directory caches those eggs to prevent '
+ 'repeated downloads.\n\n')
+ f.write('However, it is safe to delete this directory.\n\n')
+
+ return egg_cache_dir
+
+ def fetch_build_egg(self, req):
+ """Fetch an egg needed for building"""
from setuptools.installer import fetch_build_egg
return fetch_build_egg(self, req)
-
+
def _finalize_feature_opts(self):
- """Add --with-X/--without-X options based on optional features"""
-
+ """Add --with-X/--without-X options based on optional features"""
+
if not self.features:
return
- go = []
- no = self.negative_opt.copy()
-
+ go = []
+ no = self.negative_opt.copy()
+
for name, feature in self.features.items():
self._set_feature(name, None)
- feature.validate(self)
-
- if feature.optional:
- descr = feature.description
- incdef = ' (default)'
+ feature.validate(self)
+
+ if feature.optional:
+ descr = feature.description
+ incdef = ' (default)'
excdef = ''
- if not feature.include_by_default():
- excdef, incdef = incdef, excdef
-
+ if not feature.include_by_default():
+ excdef, incdef = incdef, excdef
+
new = (
('with-' + name, None, 'include ' + descr + incdef),
('without-' + name, None, 'exclude ' + descr + excdef),
)
go.extend(new)
no['without-' + name] = 'with-' + name
-
- self.global_options = self.feature_options = go + self.global_options
- self.negative_opt = self.feature_negopt = no
-
- def _finalize_features(self):
- """Add/remove features and resolve dependencies between them"""
-
- # First, flag all the enabled items (and thus their dependencies)
+
+ self.global_options = self.feature_options = go + self.global_options
+ self.negative_opt = self.feature_negopt = no
+
+ def _finalize_features(self):
+ """Add/remove features and resolve dependencies between them"""
+
+ # First, flag all the enabled items (and thus their dependencies)
for name, feature in self.features.items():
- enabled = self.feature_is_included(name)
- if enabled or (enabled is None and feature.include_by_default()):
- feature.include_in(self)
+ enabled = self.feature_is_included(name)
+ if enabled or (enabled is None and feature.include_by_default()):
+ feature.include_in(self)
self._set_feature(name, 1)
-
- # Then disable the rest, so that off-by-default features don't
- # get flagged as errors when they're required by an enabled feature
+
+ # Then disable the rest, so that off-by-default features don't
+ # get flagged as errors when they're required by an enabled feature
for name, feature in self.features.items():
- if not self.feature_is_included(name):
- feature.exclude_from(self)
+ if not self.feature_is_included(name):
+ feature.exclude_from(self)
self._set_feature(name, 0)
-
- def get_command_class(self, command):
- """Pluggable version of get_command_class()"""
- if command in self.cmdclass:
- return self.cmdclass[command]
-
+
+ def get_command_class(self, command):
+ """Pluggable version of get_command_class()"""
+ if command in self.cmdclass:
+ return self.cmdclass[command]
+
eps = pkg_resources.iter_entry_points('distutils.commands', command)
for ep in eps:
- ep.require(installer=self.fetch_build_egg)
- self.cmdclass[command] = cmdclass = ep.load()
- return cmdclass
- else:
- return _Distribution.get_command_class(self, command)
-
- def print_commands(self):
- for ep in pkg_resources.iter_entry_points('distutils.commands'):
- if ep.name not in self.cmdclass:
- # don't require extras as the commands won't be invoked
- cmdclass = ep.resolve()
- self.cmdclass[ep.name] = cmdclass
- return _Distribution.print_commands(self)
-
- def get_command_list(self):
- for ep in pkg_resources.iter_entry_points('distutils.commands'):
- if ep.name not in self.cmdclass:
- # don't require extras as the commands won't be invoked
- cmdclass = ep.resolve()
- self.cmdclass[ep.name] = cmdclass
- return _Distribution.get_command_list(self)
-
+ ep.require(installer=self.fetch_build_egg)
+ self.cmdclass[command] = cmdclass = ep.load()
+ return cmdclass
+ else:
+ return _Distribution.get_command_class(self, command)
+
+ def print_commands(self):
+ for ep in pkg_resources.iter_entry_points('distutils.commands'):
+ if ep.name not in self.cmdclass:
+ # don't require extras as the commands won't be invoked
+ cmdclass = ep.resolve()
+ self.cmdclass[ep.name] = cmdclass
+ return _Distribution.print_commands(self)
+
+ def get_command_list(self):
+ for ep in pkg_resources.iter_entry_points('distutils.commands'):
+ if ep.name not in self.cmdclass:
+ # don't require extras as the commands won't be invoked
+ cmdclass = ep.resolve()
+ self.cmdclass[ep.name] = cmdclass
+ return _Distribution.get_command_list(self)
+
def _set_feature(self, name, status):
- """Set feature's inclusion status"""
+ """Set feature's inclusion status"""
setattr(self, self._feature_attrname(name), status)
-
+
def feature_is_included(self, name):
- """Return 1 if feature is included, 0 if excluded, 'None' if unknown"""
+ """Return 1 if feature is included, 0 if excluded, 'None' if unknown"""
return getattr(self, self._feature_attrname(name))
-
+
def include_feature(self, name):
- """Request inclusion of feature named 'name'"""
-
+ """Request inclusion of feature named 'name'"""
+
if self.feature_is_included(name) == 0:
- descr = self.features[name].description
- raise DistutilsOptionError(
- descr + " is required, but was excluded or is not available"
- )
- self.features[name].include_in(self)
+ descr = self.features[name].description
+ raise DistutilsOptionError(
+ descr + " is required, but was excluded or is not available"
+ )
+ self.features[name].include_in(self)
self._set_feature(name, 1)
-
+
def include(self, **attrs):
- """Add items to distribution that are named in keyword arguments
-
+ """Add items to distribution that are named in keyword arguments
+
For example, 'dist.include(py_modules=["x"])' would add 'x' to
- the distribution's 'py_modules' attribute, if it was not already
- there.
-
- Currently, this method only supports inclusion for attributes that are
- lists or tuples. If you need to add support for adding to other
- attributes in this or a subclass, you can add an '_include_X' method,
- where 'X' is the name of the attribute. The method will be called with
- the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
- will try to call 'dist._include_foo({"bar":"baz"})', which can then
- handle whatever special inclusion logic is needed.
- """
+ the distribution's 'py_modules' attribute, if it was not already
+ there.
+
+ Currently, this method only supports inclusion for attributes that are
+ lists or tuples. If you need to add support for adding to other
+ attributes in this or a subclass, you can add an '_include_X' method,
+ where 'X' is the name of the attribute. The method will be called with
+ the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
+ will try to call 'dist._include_foo({"bar":"baz"})', which can then
+ handle whatever special inclusion logic is needed.
+ """
for k, v in attrs.items():
include = getattr(self, '_include_' + k, None)
- if include:
- include(v)
- else:
+ if include:
+ include(v)
+ else:
self._include_misc(k, v)
-
+
def exclude_package(self, package):
- """Remove packages, modules, and extensions in named package"""
-
+ """Remove packages, modules, and extensions in named package"""
+
pfx = package + '.'
- if self.packages:
- self.packages = [
- p for p in self.packages
+ if self.packages:
+ self.packages = [
+ p for p in self.packages
if p != package and not p.startswith(pfx)
- ]
-
- if self.py_modules:
- self.py_modules = [
- p for p in self.py_modules
+ ]
+
+ if self.py_modules:
+ self.py_modules = [
+ p for p in self.py_modules
if p != package and not p.startswith(pfx)
- ]
-
- if self.ext_modules:
- self.ext_modules = [
- p for p in self.ext_modules
+ ]
+
+ if self.ext_modules:
+ self.ext_modules = [
+ p for p in self.ext_modules
if p.name != package and not p.name.startswith(pfx)
- ]
-
+ ]
+
def has_contents_for(self, package):
- """Return true if 'exclude_package(package)' would do something"""
-
+ """Return true if 'exclude_package(package)' would do something"""
+
pfx = package + '.'
-
- for p in self.iter_distribution_names():
+
+ for p in self.iter_distribution_names():
if p == package or p.startswith(pfx):
- return True
-
+ return True
+
def _exclude_misc(self, name, value):
- """Handle 'exclude()' for list/tuple attrs without a special handler"""
+ """Handle 'exclude()' for list/tuple attrs without a special handler"""
if not isinstance(value, sequence):
- raise DistutilsSetupError(
- "%s: setting must be a list or tuple (%r)" % (name, value)
- )
- try:
+ raise DistutilsSetupError(
+ "%s: setting must be a list or tuple (%r)" % (name, value)
+ )
+ try:
old = getattr(self, name)
- except AttributeError:
- raise DistutilsSetupError(
- "%s: No such distribution setting" % name
- )
+ except AttributeError:
+ raise DistutilsSetupError(
+ "%s: No such distribution setting" % name
+ )
if old is not None and not isinstance(old, sequence):
- raise DistutilsSetupError(
+ raise DistutilsSetupError(
name + ": this setting cannot be changed via include/exclude"
- )
- elif old:
+ )
+ elif old:
setattr(self, name, [item for item in old if item not in value])
-
+
def _include_misc(self, name, value):
- """Handle 'include()' for list/tuple attrs without a special handler"""
-
+ """Handle 'include()' for list/tuple attrs without a special handler"""
+
if not isinstance(value, sequence):
- raise DistutilsSetupError(
- "%s: setting must be a list (%r)" % (name, value)
- )
- try:
+ raise DistutilsSetupError(
+ "%s: setting must be a list (%r)" % (name, value)
+ )
+ try:
old = getattr(self, name)
- except AttributeError:
- raise DistutilsSetupError(
- "%s: No such distribution setting" % name
- )
- if old is None:
+ except AttributeError:
+ raise DistutilsSetupError(
+ "%s: No such distribution setting" % name
+ )
+ if old is None:
setattr(self, name, value)
elif not isinstance(old, sequence):
- raise DistutilsSetupError(
+ raise DistutilsSetupError(
name + ": this setting cannot be changed via include/exclude"
- )
- else:
+ )
+ else:
new = [item for item in value if item not in old]
setattr(self, name, old + new)
-
+
def exclude(self, **attrs):
- """Remove items from distribution that are named in keyword arguments
-
- For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
- the distribution's 'py_modules' attribute. Excluding packages uses
- the 'exclude_package()' method, so all of the package's contained
- packages, modules, and extensions are also excluded.
-
- Currently, this method only supports exclusion from attributes that are
- lists or tuples. If you need to add support for excluding from other
- attributes in this or a subclass, you can add an '_exclude_X' method,
- where 'X' is the name of the attribute. The method will be called with
- the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})'
- will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
- handle whatever special exclusion logic is needed.
- """
+ """Remove items from distribution that are named in keyword arguments
+
+ For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
+ the distribution's 'py_modules' attribute. Excluding packages uses
+ the 'exclude_package()' method, so all of the package's contained
+ packages, modules, and extensions are also excluded.
+
+ Currently, this method only supports exclusion from attributes that are
+ lists or tuples. If you need to add support for excluding from other
+ attributes in this or a subclass, you can add an '_exclude_X' method,
+ where 'X' is the name of the attribute. The method will be called with
+ the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})'
+ will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
+ handle whatever special exclusion logic is needed.
+ """
for k, v in attrs.items():
exclude = getattr(self, '_exclude_' + k, None)
- if exclude:
- exclude(v)
- else:
+ if exclude:
+ exclude(v)
+ else:
self._exclude_misc(k, v)
-
+
def _exclude_packages(self, packages):
if not isinstance(packages, sequence):
- raise DistutilsSetupError(
- "packages: setting must be a list or tuple (%r)" % (packages,)
- )
- list(map(self.exclude_package, packages))
-
- def _parse_command_opts(self, parser, args):
- # Remove --with-X/--without-X options when processing command args
- self.global_options = self.__class__.global_options
- self.negative_opt = self.__class__.negative_opt
-
- # First, expand any aliases
- command = args[0]
- aliases = self.get_option_dict('aliases')
- while command in aliases:
+ raise DistutilsSetupError(
+ "packages: setting must be a list or tuple (%r)" % (packages,)
+ )
+ list(map(self.exclude_package, packages))
+
+ def _parse_command_opts(self, parser, args):
+ # Remove --with-X/--without-X options when processing command args
+ self.global_options = self.__class__.global_options
+ self.negative_opt = self.__class__.negative_opt
+
+ # First, expand any aliases
+ command = args[0]
+ aliases = self.get_option_dict('aliases')
+ while command in aliases:
src, alias = aliases[command]
del aliases[command] # ensure each alias can expand only once!
- import shlex
+ import shlex
args[:1] = shlex.split(alias, True)
- command = args[0]
-
- nargs = _Distribution._parse_command_opts(self, parser, args)
-
- # Handle commands that want to consume all remaining arguments
- cmd_class = self.get_command_class(command)
+ command = args[0]
+
+ nargs = _Distribution._parse_command_opts(self, parser, args)
+
+ # Handle commands that want to consume all remaining arguments
+ cmd_class = self.get_command_class(command)
if getattr(cmd_class, 'command_consumes_arguments', None):
- self.get_option_dict(command)['args'] = ("command line", nargs)
- if nargs is not None:
- return []
-
- return nargs
-
- def get_cmdline_options(self):
- """Return a '{cmd: {opt:val}}' map of all command-line options
-
- Option names are all long, but do not include the leading '--', and
- contain dashes rather than underscores. If the option doesn't take
- an argument (e.g. '--quiet'), the 'val' is 'None'.
-
- Note that options provided by config files are intentionally excluded.
- """
-
- d = {}
-
+ self.get_option_dict(command)['args'] = ("command line", nargs)
+ if nargs is not None:
+ return []
+
+ return nargs
+
+ def get_cmdline_options(self):
+ """Return a '{cmd: {opt:val}}' map of all command-line options
+
+ Option names are all long, but do not include the leading '--', and
+ contain dashes rather than underscores. If the option doesn't take
+ an argument (e.g. '--quiet'), the 'val' is 'None'.
+
+ Note that options provided by config files are intentionally excluded.
+ """
+
+ d = {}
+
for cmd, opts in self.command_options.items():
-
+
for opt, (src, val) in opts.items():
-
- if src != "command line":
- continue
-
+
+ if src != "command line":
+ continue
+
opt = opt.replace('_', '-')
-
+
if val == 0:
- cmdobj = self.get_command_obj(cmd)
- neg_opt = self.negative_opt.copy()
+ cmdobj = self.get_command_obj(cmd)
+ neg_opt = self.negative_opt.copy()
neg_opt.update(getattr(cmdobj, 'negative_opt', {}))
for neg, pos in neg_opt.items():
if pos == opt:
opt = neg
val = None
- break
- else:
- raise AssertionError("Shouldn't be able to get here")
-
+ break
+ else:
+ raise AssertionError("Shouldn't be able to get here")
+
elif val == 1:
- val = None
-
+ val = None
+
d.setdefault(cmd, {})[opt] = val
-
- return d
-
- def iter_distribution_names(self):
- """Yield all packages, modules, and extension names in distribution"""
-
- for pkg in self.packages or ():
- yield pkg
-
- for module in self.py_modules or ():
- yield module
-
- for ext in self.ext_modules or ():
+
+ return d
+
+ def iter_distribution_names(self):
+ """Yield all packages, modules, and extension names in distribution"""
+
+ for pkg in self.packages or ():
+ yield pkg
+
+ for module in self.py_modules or ():
+ yield module
+
+ for ext in self.ext_modules or ():
if isinstance(ext, tuple):
- name, buildinfo = ext
- else:
- name = ext.name
- if name.endswith('module'):
- name = name[:-6]
- yield name
-
- def handle_display_options(self, option_order):
- """If there were any non-global "display-only" options
- (--help-commands or the metadata display options) on the command
- line, display the requested info and return true; else return
- false.
- """
- import sys
-
- if six.PY2 or self.help_commands:
- return _Distribution.handle_display_options(self, option_order)
-
- # Stdout may be StringIO (e.g. in tests)
- if not isinstance(sys.stdout, io.TextIOWrapper):
- return _Distribution.handle_display_options(self, option_order)
-
- # Don't wrap stdout if utf-8 is already the encoding. Provides
- # workaround for #334.
- if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
- return _Distribution.handle_display_options(self, option_order)
-
- # Print metadata in UTF-8 no matter the platform
- encoding = sys.stdout.encoding
- errors = sys.stdout.errors
- newline = sys.platform != 'win32' and '\n' or None
- line_buffering = sys.stdout.line_buffering
-
- sys.stdout = io.TextIOWrapper(
- sys.stdout.detach(), 'utf-8', errors, newline, line_buffering)
- try:
- return _Distribution.handle_display_options(self, option_order)
- finally:
- sys.stdout = io.TextIOWrapper(
- sys.stdout.detach(), encoding, errors, newline, line_buffering)
-
-
-class Feature:
- """
- **deprecated** -- The `Feature` facility was never completely implemented
- or supported, `has reported issues
+ name, buildinfo = ext
+ else:
+ name = ext.name
+ if name.endswith('module'):
+ name = name[:-6]
+ yield name
+
+ def handle_display_options(self, option_order):
+ """If there were any non-global "display-only" options
+ (--help-commands or the metadata display options) on the command
+ line, display the requested info and return true; else return
+ false.
+ """
+ import sys
+
+ if six.PY2 or self.help_commands:
+ return _Distribution.handle_display_options(self, option_order)
+
+ # Stdout may be StringIO (e.g. in tests)
+ if not isinstance(sys.stdout, io.TextIOWrapper):
+ return _Distribution.handle_display_options(self, option_order)
+
+ # Don't wrap stdout if utf-8 is already the encoding. Provides
+ # workaround for #334.
+ if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
+ return _Distribution.handle_display_options(self, option_order)
+
+ # Print metadata in UTF-8 no matter the platform
+ encoding = sys.stdout.encoding
+ errors = sys.stdout.errors
+ newline = sys.platform != 'win32' and '\n' or None
+ line_buffering = sys.stdout.line_buffering
+
+ sys.stdout = io.TextIOWrapper(
+ sys.stdout.detach(), 'utf-8', errors, newline, line_buffering)
+ try:
+ return _Distribution.handle_display_options(self, option_order)
+ finally:
+ sys.stdout = io.TextIOWrapper(
+ sys.stdout.detach(), encoding, errors, newline, line_buffering)
+
+
+class Feature:
+ """
+ **deprecated** -- The `Feature` facility was never completely implemented
+ or supported, `has reported issues
<https://github.com/pypa/setuptools/issues/58>`_ and will be removed in
- a future version.
-
- A subset of the distribution that can be excluded if unneeded/wanted
-
- Features are created using these keyword arguments:
-
- 'description' -- a short, human readable description of the feature, to
- be used in error messages, and option help messages.
-
- 'standard' -- if true, the feature is included by default if it is
- available on the current system. Otherwise, the feature is only
- included if requested via a command line '--with-X' option, or if
- another included feature requires it. The default setting is 'False'.
-
- 'available' -- if true, the feature is available for installation on the
- current system. The default setting is 'True'.
-
- 'optional' -- if true, the feature's inclusion can be controlled from the
- command line, using the '--with-X' or '--without-X' options. If
- false, the feature's inclusion status is determined automatically,
- based on 'availabile', 'standard', and whether any other feature
- requires it. The default setting is 'True'.
-
- 'require_features' -- a string or sequence of strings naming features
- that should also be included if this feature is included. Defaults to
- empty list. May also contain 'Require' objects that should be
- added/removed from the distribution.
-
- 'remove' -- a string or list of strings naming packages to be removed
- from the distribution if this feature is *not* included. If the
- feature *is* included, this argument is ignored. This argument exists
- to support removing features that "crosscut" a distribution, such as
- defining a 'tests' feature that removes all the 'tests' subpackages
- provided by other features. The default for this argument is an empty
- list. (Note: the named package(s) or modules must exist in the base
- distribution when the 'setup()' function is initially called.)
-
- other keywords -- any other keyword arguments are saved, and passed to
- the distribution's 'include()' and 'exclude()' methods when the
- feature is included or excluded, respectively. So, for example, you
- could pass 'packages=["a","b"]' to cause packages 'a' and 'b' to be
- added or removed from the distribution as appropriate.
-
- A feature must include at least one 'requires', 'remove', or other
- keyword argument. Otherwise, it can't affect the distribution in any way.
- Note also that you can subclass 'Feature' to create your own specialized
- feature types that modify the distribution in other ways when included or
- excluded. See the docstrings for the various methods here for more detail.
- Aside from the methods, the only feature attributes that distributions look
- at are 'description' and 'optional'.
- """
-
- @staticmethod
- def warn_deprecated():
+ a future version.
+
+ A subset of the distribution that can be excluded if unneeded/wanted
+
+ Features are created using these keyword arguments:
+
+ 'description' -- a short, human readable description of the feature, to
+ be used in error messages, and option help messages.
+
+ 'standard' -- if true, the feature is included by default if it is
+ available on the current system. Otherwise, the feature is only
+ included if requested via a command line '--with-X' option, or if
+ another included feature requires it. The default setting is 'False'.
+
+ 'available' -- if true, the feature is available for installation on the
+ current system. The default setting is 'True'.
+
+ 'optional' -- if true, the feature's inclusion can be controlled from the
+ command line, using the '--with-X' or '--without-X' options. If
+ false, the feature's inclusion status is determined automatically,
+ based on 'availabile', 'standard', and whether any other feature
+ requires it. The default setting is 'True'.
+
+ 'require_features' -- a string or sequence of strings naming features
+ that should also be included if this feature is included. Defaults to
+ empty list. May also contain 'Require' objects that should be
+ added/removed from the distribution.
+
+ 'remove' -- a string or list of strings naming packages to be removed
+ from the distribution if this feature is *not* included. If the
+ feature *is* included, this argument is ignored. This argument exists
+ to support removing features that "crosscut" a distribution, such as
+ defining a 'tests' feature that removes all the 'tests' subpackages
+ provided by other features. The default for this argument is an empty
+ list. (Note: the named package(s) or modules must exist in the base
+ distribution when the 'setup()' function is initially called.)
+
+ other keywords -- any other keyword arguments are saved, and passed to
+ the distribution's 'include()' and 'exclude()' methods when the
+ feature is included or excluded, respectively. So, for example, you
+ could pass 'packages=["a","b"]' to cause packages 'a' and 'b' to be
+ added or removed from the distribution as appropriate.
+
+ A feature must include at least one 'requires', 'remove', or other
+ keyword argument. Otherwise, it can't affect the distribution in any way.
+ Note also that you can subclass 'Feature' to create your own specialized
+ feature types that modify the distribution in other ways when included or
+ excluded. See the docstrings for the various methods here for more detail.
+ Aside from the methods, the only feature attributes that distributions look
+ at are 'description' and 'optional'.
+ """
+
+ @staticmethod
+ def warn_deprecated():
msg = (
- "Features are deprecated and will be removed in a future "
+ "Features are deprecated and will be removed in a future "
"version. See https://github.com/pypa/setuptools/issues/65."
- )
+ )
warnings.warn(msg, DistDeprecationWarning, stacklevel=3)
-
+
def __init__(
self, description, standard=False, available=True,
- optional=True, require_features=(), remove=(), **extras):
- self.warn_deprecated()
-
- self.description = description
- self.standard = standard
- self.available = available
- self.optional = optional
+ optional=True, require_features=(), remove=(), **extras):
+ self.warn_deprecated()
+
+ self.description = description
+ self.standard = standard
+ self.available = available
+ self.optional = optional
if isinstance(require_features, (str, Require)):
- require_features = require_features,
-
- self.require_features = [
+ require_features = require_features,
+
+ self.require_features = [
r for r in require_features if isinstance(r, str)
- ]
+ ]
er = [r for r in require_features if not isinstance(r, str)]
if er:
extras['require_features'] = er
-
+
if isinstance(remove, str):
- remove = remove,
- self.remove = remove
- self.extras = extras
-
- if not remove and not require_features and not extras:
- raise DistutilsSetupError(
+ remove = remove,
+ self.remove = remove
+ self.extras = extras
+
+ if not remove and not require_features and not extras:
+ raise DistutilsSetupError(
"Feature %s: must define 'require_features', 'remove', or "
"at least one of 'packages', 'py_modules', etc."
- )
-
- def include_by_default(self):
- """Should this feature be included by default?"""
- return self.available and self.standard
-
+ )
+
+ def include_by_default(self):
+ """Should this feature be included by default?"""
+ return self.available and self.standard
+
def include_in(self, dist):
- """Ensure feature and its requirements are included in distribution
-
- You may override this in a subclass to perform additional operations on
- the distribution. Note that this method may be called more than once
- per feature, and so should be idempotent.
-
- """
-
- if not self.available:
- raise DistutilsPlatformError(
+ """Ensure feature and its requirements are included in distribution
+
+ You may override this in a subclass to perform additional operations on
+ the distribution. Note that this method may be called more than once
+ per feature, and so should be idempotent.
+
+ """
+
+ if not self.available:
+ raise DistutilsPlatformError(
self.description + " is required, "
- "but is not available on this platform"
- )
-
- dist.include(**self.extras)
-
- for f in self.require_features:
- dist.include_feature(f)
-
+ "but is not available on this platform"
+ )
+
+ dist.include(**self.extras)
+
+ for f in self.require_features:
+ dist.include_feature(f)
+
def exclude_from(self, dist):
- """Ensure feature is excluded from distribution
-
- You may override this in a subclass to perform additional operations on
- the distribution. This method will be called at most once per
- feature, and only after all included features have been asked to
- include themselves.
- """
-
- dist.exclude(**self.extras)
-
- if self.remove:
- for item in self.remove:
- dist.exclude_package(item)
-
+ """Ensure feature is excluded from distribution
+
+ You may override this in a subclass to perform additional operations on
+ the distribution. This method will be called at most once per
+ feature, and only after all included features have been asked to
+ include themselves.
+ """
+
+ dist.exclude(**self.extras)
+
+ if self.remove:
+ for item in self.remove:
+ dist.exclude_package(item)
+
def validate(self, dist):
- """Verify that feature makes sense in context of distribution
-
- This method is called by the distribution just before it parses its
- command line. It checks to ensure that the 'remove' attribute, if any,
- contains only valid package/module names that are present in the base
- distribution when 'setup()' is called. You may override it in a
- subclass to perform any other required validation of the feature
- against a target distribution.
- """
-
- for item in self.remove:
- if not dist.has_contents_for(item):
- raise DistutilsSetupError(
- "%s wants to be able to remove %s, but the distribution"
- " doesn't contain any packages or modules under %s"
- % (self.description, item, item)
- )
+ """Verify that feature makes sense in context of distribution
+
+ This method is called by the distribution just before it parses its
+ command line. It checks to ensure that the 'remove' attribute, if any,
+ contains only valid package/module names that are present in the base
+ distribution when 'setup()' is called. You may override it in a
+ subclass to perform any other required validation of the feature
+ against a target distribution.
+ """
+
+ for item in self.remove:
+ if not dist.has_contents_for(item):
+ raise DistutilsSetupError(
+ "%s wants to be able to remove %s, but the distribution"
+ " doesn't contain any packages or modules under %s"
+ % (self.description, item, item)
+ )
class DistDeprecationWarning(SetuptoolsDeprecationWarning):
diff --git a/contrib/python/setuptools/py2/setuptools/extension.py b/contrib/python/setuptools/py2/setuptools/extension.py
index 679c11263d..29468894f8 100644
--- a/contrib/python/setuptools/py2/setuptools/extension.py
+++ b/contrib/python/setuptools/py2/setuptools/extension.py
@@ -1,57 +1,57 @@
-import re
-import functools
-import distutils.core
-import distutils.errors
-import distutils.extension
-
+import re
+import functools
+import distutils.core
+import distutils.errors
+import distutils.extension
+
from setuptools.extern.six.moves import map
-
+
from .monkey import get_unpatched
-
-
-def _have_cython():
- """
- Return True if Cython can be imported.
- """
+
+
+def _have_cython():
+ """
+ Return True if Cython can be imported.
+ """
cython_impl = 'Cython.Distutils.build_ext'
- try:
- # from (cython_impl) import build_ext
- __import__(cython_impl, fromlist=['build_ext']).build_ext
- return True
- except Exception:
- pass
- return False
-
-
-# for compatibility
-have_pyrex = _have_cython
-
+ try:
+ # from (cython_impl) import build_ext
+ __import__(cython_impl, fromlist=['build_ext']).build_ext
+ return True
+ except Exception:
+ pass
+ return False
+
+
+# for compatibility
+have_pyrex = _have_cython
+
_Extension = get_unpatched(distutils.core.Extension)
-
-class Extension(_Extension):
- """Extension that uses '.c' files in place of '.pyx' files"""
-
+
+class Extension(_Extension):
+ """Extension that uses '.c' files in place of '.pyx' files"""
+
def __init__(self, name, sources, *args, **kw):
# The *args is needed for compatibility as calls may use positional
# arguments. py_limited_api may be set only via keyword.
self.py_limited_api = kw.pop("py_limited_api", False)
_Extension.__init__(self, name, sources, *args, **kw)
- def _convert_pyx_sources_to_lang(self):
- """
- Replace sources with .pyx extensions to sources with the target
- language extension. This mechanism allows language authors to supply
- pre-converted sources but to prefer the .pyx sources.
- """
- if _have_cython():
- # the build has Cython, so allow it to compile the .pyx files
- return
- lang = self.language or ''
- target_ext = '.cpp' if lang.lower() == 'c++' else '.c'
- sub = functools.partial(re.sub, '.pyx$', target_ext)
- self.sources = list(map(sub, self.sources))
-
-
-class Library(Extension):
- """Just like a regular Extension, but built as a library instead"""
+ def _convert_pyx_sources_to_lang(self):
+ """
+ Replace sources with .pyx extensions to sources with the target
+ language extension. This mechanism allows language authors to supply
+ pre-converted sources but to prefer the .pyx sources.
+ """
+ if _have_cython():
+ # the build has Cython, so allow it to compile the .pyx files
+ return
+ lang = self.language or ''
+ target_ext = '.cpp' if lang.lower() == 'c++' else '.c'
+ sub = functools.partial(re.sub, '.pyx$', target_ext)
+ self.sources = list(map(sub, self.sources))
+
+
+class Library(Extension):
+ """Just like a regular Extension, but built as a library instead"""
diff --git a/contrib/python/setuptools/py2/setuptools/launch.py b/contrib/python/setuptools/py2/setuptools/launch.py
index 8c302e90a1..308283ea93 100644
--- a/contrib/python/setuptools/py2/setuptools/launch.py
+++ b/contrib/python/setuptools/py2/setuptools/launch.py
@@ -1,16 +1,16 @@
-"""
-Launch the Python script on the command line after
-setuptools is bootstrapped via import.
-"""
-
-# Note that setuptools gets imported implicitly by the
-# invocation of this script using python -m setuptools.launch
-
-import tokenize
-import sys
-
-
-def run():
+"""
+Launch the Python script on the command line after
+setuptools is bootstrapped via import.
+"""
+
+# Note that setuptools gets imported implicitly by the
+# invocation of this script using python -m setuptools.launch
+
+import tokenize
+import sys
+
+
+def run():
"""
Run the script in sys.argv[1] as if it had
been invoked naturally.
@@ -23,13 +23,13 @@ def run():
__doc__=None,
)
sys.argv[:] = sys.argv[1:]
-
+
open_ = getattr(tokenize, 'open', open)
script = open_(script_name).read()
norm_script = script.replace('\\r\\n', '\\n')
code = compile(norm_script, script_name, 'exec')
exec(code, namespace)
-
-
-if __name__ == '__main__':
+
+
+if __name__ == '__main__':
run()
diff --git a/contrib/python/setuptools/py2/setuptools/lib2to3_ex.py b/contrib/python/setuptools/py2/setuptools/lib2to3_ex.py
index b193707807..4b1a73feb2 100644
--- a/contrib/python/setuptools/py2/setuptools/lib2to3_ex.py
+++ b/contrib/python/setuptools/py2/setuptools/lib2to3_ex.py
@@ -1,62 +1,62 @@
-"""
-Customized Mixin2to3 support:
-
- - adds support for converting doctests
-
-
-This module raises an ImportError on Python 2.
-"""
-
-from distutils.util import Mixin2to3 as _Mixin2to3
-from distutils import log
-from lib2to3.refactor import RefactoringTool, get_fixers_from_package
-
-import setuptools
-
-
-class DistutilsRefactoringTool(RefactoringTool):
- def log_error(self, msg, *args, **kw):
- log.error(msg, *args)
-
- def log_message(self, msg, *args):
- log.info(msg, *args)
-
- def log_debug(self, msg, *args):
- log.debug(msg, *args)
-
-
-class Mixin2to3(_Mixin2to3):
+"""
+Customized Mixin2to3 support:
+
+ - adds support for converting doctests
+
+
+This module raises an ImportError on Python 2.
+"""
+
+from distutils.util import Mixin2to3 as _Mixin2to3
+from distutils import log
+from lib2to3.refactor import RefactoringTool, get_fixers_from_package
+
+import setuptools
+
+
+class DistutilsRefactoringTool(RefactoringTool):
+ def log_error(self, msg, *args, **kw):
+ log.error(msg, *args)
+
+ def log_message(self, msg, *args):
+ log.info(msg, *args)
+
+ def log_debug(self, msg, *args):
+ log.debug(msg, *args)
+
+
+class Mixin2to3(_Mixin2to3):
def run_2to3(self, files, doctests=False):
- # See of the distribution option has been set, otherwise check the
- # setuptools default.
- if self.distribution.use_2to3 is not True:
- return
- if not files:
- return
+ # See of the distribution option has been set, otherwise check the
+ # setuptools default.
+ if self.distribution.use_2to3 is not True:
+ return
+ if not files:
+ return
log.info("Fixing " + " ".join(files))
- self.__build_fixer_names()
- self.__exclude_fixers()
- if doctests:
- if setuptools.run_2to3_on_doctests:
- r = DistutilsRefactoringTool(self.fixer_names)
- r.refactor(files, write=True, doctests_only=True)
- else:
- _Mixin2to3.run_2to3(self, files)
-
- def __build_fixer_names(self):
+ self.__build_fixer_names()
+ self.__exclude_fixers()
+ if doctests:
+ if setuptools.run_2to3_on_doctests:
+ r = DistutilsRefactoringTool(self.fixer_names)
+ r.refactor(files, write=True, doctests_only=True)
+ else:
+ _Mixin2to3.run_2to3(self, files)
+
+ def __build_fixer_names(self):
if self.fixer_names:
return
- self.fixer_names = []
- for p in setuptools.lib2to3_fixer_packages:
- self.fixer_names.extend(get_fixers_from_package(p))
- if self.distribution.use_2to3_fixers is not None:
- for p in self.distribution.use_2to3_fixers:
- self.fixer_names.extend(get_fixers_from_package(p))
-
- def __exclude_fixers(self):
- excluded_fixers = getattr(self, 'exclude_fixers', [])
- if self.distribution.use_2to3_exclude_fixers is not None:
- excluded_fixers.extend(self.distribution.use_2to3_exclude_fixers)
- for fixer_name in excluded_fixers:
- if fixer_name in self.fixer_names:
- self.fixer_names.remove(fixer_name)
+ self.fixer_names = []
+ for p in setuptools.lib2to3_fixer_packages:
+ self.fixer_names.extend(get_fixers_from_package(p))
+ if self.distribution.use_2to3_fixers is not None:
+ for p in self.distribution.use_2to3_fixers:
+ self.fixer_names.extend(get_fixers_from_package(p))
+
+ def __exclude_fixers(self):
+ excluded_fixers = getattr(self, 'exclude_fixers', [])
+ if self.distribution.use_2to3_exclude_fixers is not None:
+ excluded_fixers.extend(self.distribution.use_2to3_exclude_fixers)
+ for fixer_name in excluded_fixers:
+ if fixer_name in self.fixer_names:
+ self.fixer_names.remove(fixer_name)
diff --git a/contrib/python/setuptools/py2/setuptools/package_index.py b/contrib/python/setuptools/py2/setuptools/package_index.py
index 38c661dab0..f419d47167 100644
--- a/contrib/python/setuptools/py2/setuptools/package_index.py
+++ b/contrib/python/setuptools/py2/setuptools/package_index.py
@@ -1,50 +1,50 @@
-"""PyPI and direct package downloading"""
-import sys
-import os
-import re
-import shutil
-import socket
-import base64
-import hashlib
-import itertools
+"""PyPI and direct package downloading"""
+import sys
+import os
+import re
+import shutil
+import socket
+import base64
+import hashlib
+import itertools
import warnings
-from functools import wraps
-
+from functools import wraps
+
from setuptools.extern import six
from setuptools.extern.six.moves import urllib, http_client, configparser, map
-
+
import setuptools
-from pkg_resources import (
- CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST,
+from pkg_resources import (
+ CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST,
Environment, find_distributions, safe_name, safe_version,
to_filename, Requirement, DEVELOP_DIST, EGG_DIST,
-)
-from setuptools import ssl_support
-from distutils import log
-from distutils.errors import DistutilsError
-from fnmatch import translate
-from setuptools.py27compat import get_all_headers
+)
+from setuptools import ssl_support
+from distutils import log
+from distutils.errors import DistutilsError
+from fnmatch import translate
+from setuptools.py27compat import get_all_headers
from setuptools.py33compat import unescape
from setuptools.wheel import Wheel
-
+
__metaclass__ = type
EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$')
HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I)
-PYPI_MD5 = re.compile(
+PYPI_MD5 = re.compile(
r'<a href="([^"#]+)">([^<]+)</a>\n\s+\(<a (?:title="MD5 hash"\n\s+)'
r'href="[^?]+\?:action=show_md5&amp;digest=([0-9a-f]{32})">md5</a>\)'
-)
+)
URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match
-EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split()
-
-__all__ = [
- 'PackageIndex', 'distros_for_url', 'parse_bdist_wininst',
- 'interpret_distro_name',
-]
-
-_SOCKET_TIMEOUT = 15
-
+EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split()
+
+__all__ = [
+ 'PackageIndex', 'distros_for_url', 'parse_bdist_wininst',
+ 'interpret_distro_name',
+]
+
+_SOCKET_TIMEOUT = 15
+
_tmpl = "setuptools/{setuptools.__version__} Python-urllib/{py_major}"
user_agent = _tmpl.format(py_major='{}.{}'.format(*sys.version_info), setuptools=setuptools)
@@ -58,62 +58,62 @@ def parse_requirement_arg(spec):
)
-def parse_bdist_wininst(name):
- """Return (base,pyversion) or (None,None) for possible .exe name"""
-
- lower = name.lower()
- base, py_ver, plat = None, None, None
-
- if lower.endswith('.exe'):
- if lower.endswith('.win32.exe'):
- base = name[:-10]
- plat = 'win32'
+def parse_bdist_wininst(name):
+ """Return (base,pyversion) or (None,None) for possible .exe name"""
+
+ lower = name.lower()
+ base, py_ver, plat = None, None, None
+
+ if lower.endswith('.exe'):
+ if lower.endswith('.win32.exe'):
+ base = name[:-10]
+ plat = 'win32'
elif lower.startswith('.win32-py', -16):
- py_ver = name[-7:-4]
- base = name[:-16]
- plat = 'win32'
- elif lower.endswith('.win-amd64.exe'):
- base = name[:-14]
- plat = 'win-amd64'
+ py_ver = name[-7:-4]
+ base = name[:-16]
+ plat = 'win32'
+ elif lower.endswith('.win-amd64.exe'):
+ base = name[:-14]
+ plat = 'win-amd64'
elif lower.startswith('.win-amd64-py', -20):
- py_ver = name[-7:-4]
- base = name[:-20]
- plat = 'win-amd64'
+ py_ver = name[-7:-4]
+ base = name[:-20]
+ plat = 'win-amd64'
return base, py_ver, plat
-
-
-def egg_info_for_url(url):
- parts = urllib.parse.urlparse(url)
- scheme, server, path, parameters, query, fragment = parts
- base = urllib.parse.unquote(path.split('/')[-1])
+
+
+def egg_info_for_url(url):
+ parts = urllib.parse.urlparse(url)
+ scheme, server, path, parameters, query, fragment = parts
+ base = urllib.parse.unquote(path.split('/')[-1])
if server == 'sourceforge.net' and base == 'download': # XXX Yuck
- base = urllib.parse.unquote(path.split('/')[-2])
+ base = urllib.parse.unquote(path.split('/')[-2])
if '#' in base:
base, fragment = base.split('#', 1)
return base, fragment
-
-def distros_for_url(url, metadata=None):
- """Yield egg or source distribution objects that might be found at a URL"""
- base, fragment = egg_info_for_url(url)
+
+def distros_for_url(url, metadata=None):
+ """Yield egg or source distribution objects that might be found at a URL"""
+ base, fragment = egg_info_for_url(url)
for dist in distros_for_location(url, base, metadata):
yield dist
- if fragment:
- match = EGG_FRAGMENT.match(fragment)
- if match:
- for dist in interpret_distro_name(
+ if fragment:
+ match = EGG_FRAGMENT.match(fragment)
+ if match:
+ for dist in interpret_distro_name(
url, match.group(1), metadata, precedence=CHECKOUT_DIST
- ):
- yield dist
-
+ ):
+ yield dist
+
-def distros_for_location(location, basename, metadata=None):
- """Yield egg or source distribution objects based on basename"""
- if basename.endswith('.egg.zip'):
+def distros_for_location(location, basename, metadata=None):
+ """Yield egg or source distribution objects based on basename"""
+ if basename.endswith('.egg.zip'):
basename = basename[:-4] # strip the .zip
- if basename.endswith('.egg') and '-' in basename:
- # only one, unambiguous interpretation
- return [Distribution.from_location(location, basename, metadata)]
+ if basename.endswith('.egg') and '-' in basename:
+ # only one, unambiguous interpretation
+ return [Distribution.from_location(location, basename, metadata)]
if basename.endswith('.whl') and '-' in basename:
wheel = Wheel(basename)
if not wheel.is_compatible():
@@ -125,508 +125,508 @@ def distros_for_location(location, basename, metadata=None):
# Increase priority over eggs.
precedence=EGG_DIST + 1,
)]
- if basename.endswith('.exe'):
- win_base, py_ver, platform = parse_bdist_wininst(basename)
- if win_base is not None:
- return interpret_distro_name(
- location, win_base, metadata, py_ver, BINARY_DIST, platform
- )
- # Try source distro extensions (.zip, .tgz, etc.)
- #
- for ext in EXTENSIONS:
- if basename.endswith(ext):
- basename = basename[:-len(ext)]
- return interpret_distro_name(location, basename, metadata)
- return [] # no extension matched
-
-
-def distros_for_filename(filename, metadata=None):
- """Yield possible egg or source distribution objects based on a filename"""
- return distros_for_location(
- normalize_path(filename), os.path.basename(filename), metadata
- )
-
-
-def interpret_distro_name(
- location, basename, metadata, py_version=None, precedence=SOURCE_DIST,
- platform=None
+ if basename.endswith('.exe'):
+ win_base, py_ver, platform = parse_bdist_wininst(basename)
+ if win_base is not None:
+ return interpret_distro_name(
+ location, win_base, metadata, py_ver, BINARY_DIST, platform
+ )
+ # Try source distro extensions (.zip, .tgz, etc.)
+ #
+ for ext in EXTENSIONS:
+ if basename.endswith(ext):
+ basename = basename[:-len(ext)]
+ return interpret_distro_name(location, basename, metadata)
+ return [] # no extension matched
+
+
+def distros_for_filename(filename, metadata=None):
+ """Yield possible egg or source distribution objects based on a filename"""
+ return distros_for_location(
+ normalize_path(filename), os.path.basename(filename), metadata
+ )
+
+
+def interpret_distro_name(
+ location, basename, metadata, py_version=None, precedence=SOURCE_DIST,
+ platform=None
):
- """Generate alternative interpretations of a source distro name
-
- Note: if `location` is a filesystem filename, you should call
- ``pkg_resources.normalize_path()`` on it before passing it to this
- routine!
- """
- # Generate alternative interpretations of a source distro name
- # Because some packages are ambiguous as to name/versions split
- # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc.
- # So, we generate each possible interepretation (e.g. "adns, python-1.1.0"
- # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice,
- # the spurious interpretations should be ignored, because in the event
- # there's also an "adns" package, the spurious "python-1.1.0" version will
- # compare lower than any numeric version number, and is therefore unlikely
- # to match a request for it. It's still a potential problem, though, and
- # in the long run PyPI and the distutils should go for "safe" names and
- # versions in distribution archive names (sdist and bdist).
-
- parts = basename.split('-')
+ """Generate alternative interpretations of a source distro name
+
+ Note: if `location` is a filesystem filename, you should call
+ ``pkg_resources.normalize_path()`` on it before passing it to this
+ routine!
+ """
+ # Generate alternative interpretations of a source distro name
+ # Because some packages are ambiguous as to name/versions split
+ # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc.
+ # So, we generate each possible interepretation (e.g. "adns, python-1.1.0"
+ # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice,
+ # the spurious interpretations should be ignored, because in the event
+ # there's also an "adns" package, the spurious "python-1.1.0" version will
+ # compare lower than any numeric version number, and is therefore unlikely
+ # to match a request for it. It's still a potential problem, though, and
+ # in the long run PyPI and the distutils should go for "safe" names and
+ # versions in distribution archive names (sdist and bdist).
+
+ parts = basename.split('-')
if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]):
- # it is a bdist_dumb, not an sdist -- bail out
- return
-
+ # it is a bdist_dumb, not an sdist -- bail out
+ return
+
for p in range(1, len(parts) + 1):
- yield Distribution(
- location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]),
+ yield Distribution(
+ location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]),
py_version=py_version, precedence=precedence,
platform=platform
- )
-
-
-# From Python 2.7 docs
-def unique_everseen(iterable, key=None):
- "List unique elements, preserving order. Remember all elements ever seen."
- # unique_everseen('AAAABBBCCDAABBB') --> A B C D
- # unique_everseen('ABBCcAD', str.lower) --> A B C D
- seen = set()
- seen_add = seen.add
- if key is None:
- for element in six.moves.filterfalse(seen.__contains__, iterable):
- seen_add(element)
- yield element
- else:
- for element in iterable:
- k = key(element)
- if k not in seen:
- seen_add(k)
- yield element
-
-
-def unique_values(func):
- """
- Wrap a function returning an iterable such that the resulting iterable
- only ever yields unique items.
- """
-
- @wraps(func)
- def wrapper(*args, **kwargs):
- return unique_everseen(func(*args, **kwargs))
-
- return wrapper
-
+ )
+
+
+# From Python 2.7 docs
+def unique_everseen(iterable, key=None):
+ "List unique elements, preserving order. Remember all elements ever seen."
+ # unique_everseen('AAAABBBCCDAABBB') --> A B C D
+ # unique_everseen('ABBCcAD', str.lower) --> A B C D
+ seen = set()
+ seen_add = seen.add
+ if key is None:
+ for element in six.moves.filterfalse(seen.__contains__, iterable):
+ seen_add(element)
+ yield element
+ else:
+ for element in iterable:
+ k = key(element)
+ if k not in seen:
+ seen_add(k)
+ yield element
+
+
+def unique_values(func):
+ """
+ Wrap a function returning an iterable such that the resulting iterable
+ only ever yields unique items.
+ """
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ return unique_everseen(func(*args, **kwargs))
+
+ return wrapper
+
REL = re.compile(r"""<([^>]*\srel\s*=\s*['"]?([^'">]+)[^>]*)>""", re.I)
-# this line is here to fix emacs' cruddy broken syntax highlighting
-
-
-@unique_values
-def find_external_links(url, page):
- """Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
-
- for match in REL.finditer(page):
- tag, rel = match.groups()
- rels = set(map(str.strip, rel.lower().split(',')))
- if 'homepage' in rels or 'download' in rels:
- for match in HREF.finditer(tag):
- yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
-
- for tag in ("<th>Home Page", "<th>Download URL"):
- pos = page.find(tag)
+# this line is here to fix emacs' cruddy broken syntax highlighting
+
+
+@unique_values
+def find_external_links(url, page):
+ """Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
+
+ for match in REL.finditer(page):
+ tag, rel = match.groups()
+ rels = set(map(str.strip, rel.lower().split(',')))
+ if 'homepage' in rels or 'download' in rels:
+ for match in HREF.finditer(tag):
+ yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
+
+ for tag in ("<th>Home Page", "<th>Download URL"):
+ pos = page.find(tag)
if pos != -1:
match = HREF.search(page, pos)
- if match:
- yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
-
-
+ if match:
+ yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
+
+
class ContentChecker:
- """
- A null content checker that defines the interface for checking content
- """
-
- def feed(self, block):
- """
- Feed a block of data to the hash.
- """
- return
-
- def is_valid(self):
- """
- Check the hash. Return False if validation fails.
- """
- return True
-
- def report(self, reporter, template):
- """
- Call reporter with information about the checker (hash name)
- substituted into the template.
- """
- return
-
-
-class HashChecker(ContentChecker):
- pattern = re.compile(
- r'(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)='
- r'(?P<expected>[a-f0-9]+)'
- )
-
- def __init__(self, hash_name, expected):
- self.hash_name = hash_name
- self.hash = hashlib.new(hash_name)
- self.expected = expected
-
- @classmethod
- def from_url(cls, url):
- "Construct a (possibly null) ContentChecker from a URL"
- fragment = urllib.parse.urlparse(url)[-1]
- if not fragment:
- return ContentChecker()
- match = cls.pattern.search(fragment)
- if not match:
- return ContentChecker()
- return cls(**match.groupdict())
-
- def feed(self, block):
- self.hash.update(block)
-
- def is_valid(self):
- return self.hash.hexdigest() == self.expected
-
- def report(self, reporter, template):
- msg = template % self.hash_name
- return reporter(msg)
-
-
-class PackageIndex(Environment):
- """A distribution index that scans web pages for download URLs"""
-
- def __init__(
+ """
+ A null content checker that defines the interface for checking content
+ """
+
+ def feed(self, block):
+ """
+ Feed a block of data to the hash.
+ """
+ return
+
+ def is_valid(self):
+ """
+ Check the hash. Return False if validation fails.
+ """
+ return True
+
+ def report(self, reporter, template):
+ """
+ Call reporter with information about the checker (hash name)
+ substituted into the template.
+ """
+ return
+
+
+class HashChecker(ContentChecker):
+ pattern = re.compile(
+ r'(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)='
+ r'(?P<expected>[a-f0-9]+)'
+ )
+
+ def __init__(self, hash_name, expected):
+ self.hash_name = hash_name
+ self.hash = hashlib.new(hash_name)
+ self.expected = expected
+
+ @classmethod
+ def from_url(cls, url):
+ "Construct a (possibly null) ContentChecker from a URL"
+ fragment = urllib.parse.urlparse(url)[-1]
+ if not fragment:
+ return ContentChecker()
+ match = cls.pattern.search(fragment)
+ if not match:
+ return ContentChecker()
+ return cls(**match.groupdict())
+
+ def feed(self, block):
+ self.hash.update(block)
+
+ def is_valid(self):
+ return self.hash.hexdigest() == self.expected
+
+ def report(self, reporter, template):
+ msg = template % self.hash_name
+ return reporter(msg)
+
+
+class PackageIndex(Environment):
+ """A distribution index that scans web pages for download URLs"""
+
+ def __init__(
self, index_url="https://pypi.org/simple/", hosts=('*',),
- ca_bundle=None, verify_ssl=True, *args, **kw
+ ca_bundle=None, verify_ssl=True, *args, **kw
):
Environment.__init__(self, *args, **kw)
self.index_url = index_url + "/" [:not index_url.endswith('/')]
- self.scanned_urls = {}
- self.fetched_urls = {}
- self.package_pages = {}
+ self.scanned_urls = {}
+ self.fetched_urls = {}
+ self.package_pages = {}
self.allows = re.compile('|'.join(map(translate, hosts))).match
- self.to_scan = []
+ self.to_scan = []
use_ssl = (
verify_ssl
and ssl_support.is_available
and (ca_bundle or ssl_support.find_ca_bundle())
)
if use_ssl:
- self.opener = ssl_support.opener_for(ca_bundle)
+ self.opener = ssl_support.opener_for(ca_bundle)
else:
self.opener = urllib.request.urlopen
-
- def process_url(self, url, retrieve=False):
- """Evaluate a URL as a possible download, and maybe retrieve it"""
- if url in self.scanned_urls and not retrieve:
- return
- self.scanned_urls[url] = True
- if not URL_SCHEME(url):
- self.process_filename(url)
- return
- else:
- dists = list(distros_for_url(url))
- if dists:
- if not self.url_ok(url):
- return
- self.debug("Found link: %s", url)
-
- if dists or not retrieve or url in self.fetched_urls:
- list(map(self.add, dists))
- return # don't need the actual page
-
- if not self.url_ok(url):
- self.fetched_urls[url] = True
- return
-
- self.info("Reading %s", url)
+
+ def process_url(self, url, retrieve=False):
+ """Evaluate a URL as a possible download, and maybe retrieve it"""
+ if url in self.scanned_urls and not retrieve:
+ return
+ self.scanned_urls[url] = True
+ if not URL_SCHEME(url):
+ self.process_filename(url)
+ return
+ else:
+ dists = list(distros_for_url(url))
+ if dists:
+ if not self.url_ok(url):
+ return
+ self.debug("Found link: %s", url)
+
+ if dists or not retrieve or url in self.fetched_urls:
+ list(map(self.add, dists))
+ return # don't need the actual page
+
+ if not self.url_ok(url):
+ self.fetched_urls[url] = True
+ return
+
+ self.info("Reading %s", url)
self.fetched_urls[url] = True # prevent multiple fetch attempts
tmpl = "Download error on %s: %%s -- Some packages may not be found!"
f = self.open_url(url, tmpl % url)
if f is None:
return
- self.fetched_urls[f.url] = True
- if 'html' not in f.headers.get('content-type', '').lower():
+ self.fetched_urls[f.url] = True
+ if 'html' not in f.headers.get('content-type', '').lower():
f.close() # not html, we can't process it
- return
-
+ return
+
base = f.url # handle redirects
- page = f.read()
+ page = f.read()
if not isinstance(page, str):
# In Python 3 and got bytes but want str.
- if isinstance(f, urllib.error.HTTPError):
- # Errors have no charset, assume latin1:
- charset = 'latin-1'
- else:
- charset = f.headers.get_param('charset') or 'latin-1'
- page = page.decode(charset, "ignore")
- f.close()
- for match in HREF.finditer(page):
- link = urllib.parse.urljoin(base, htmldecode(match.group(1)))
- self.process_url(link)
+ if isinstance(f, urllib.error.HTTPError):
+ # Errors have no charset, assume latin1:
+ charset = 'latin-1'
+ else:
+ charset = f.headers.get_param('charset') or 'latin-1'
+ page = page.decode(charset, "ignore")
+ f.close()
+ for match in HREF.finditer(page):
+ link = urllib.parse.urljoin(base, htmldecode(match.group(1)))
+ self.process_url(link)
if url.startswith(self.index_url) and getattr(f, 'code', None) != 404:
- page = self.process_index(url, page)
-
- def process_filename(self, fn, nested=False):
- # process filenames or directories
- if not os.path.exists(fn):
- self.warn("Not found: %s", fn)
- return
-
- if os.path.isdir(fn) and not nested:
- path = os.path.realpath(fn)
- for item in os.listdir(path):
+ page = self.process_index(url, page)
+
+ def process_filename(self, fn, nested=False):
+ # process filenames or directories
+ if not os.path.exists(fn):
+ self.warn("Not found: %s", fn)
+ return
+
+ if os.path.isdir(fn) and not nested:
+ path = os.path.realpath(fn)
+ for item in os.listdir(path):
self.process_filename(os.path.join(path, item), True)
-
- dists = distros_for_filename(fn)
- if dists:
- self.debug("Found: %s", fn)
- list(map(self.add, dists))
-
- def url_ok(self, url, fatal=False):
- s = URL_SCHEME(url)
+
+ dists = distros_for_filename(fn)
+ if dists:
+ self.debug("Found: %s", fn)
+ list(map(self.add, dists))
+
+ def url_ok(self, url, fatal=False):
+ s = URL_SCHEME(url)
is_file = s and s.group(1).lower() == 'file'
if is_file or self.allows(urllib.parse.urlparse(url)[1]):
- return True
+ return True
msg = (
"\nNote: Bypassing %s (disallowed host; see "
"http://bit.ly/2hrImnY for details).\n")
- if fatal:
- raise DistutilsError(msg % url)
- else:
- self.warn(msg, url)
-
- def scan_egg_links(self, search_path):
- dirs = filter(os.path.isdir, search_path)
- egg_links = (
- (path, entry)
- for path in dirs
- for entry in os.listdir(path)
- if entry.endswith('.egg-link')
- )
- list(itertools.starmap(self.scan_egg_link, egg_links))
-
- def scan_egg_link(self, path, entry):
- with open(os.path.join(path, entry)) as raw_lines:
- # filter non-empty lines
- lines = list(filter(None, map(str.strip, raw_lines)))
-
- if len(lines) != 2:
- # format is not recognized; punt
- return
-
- egg_path, setup_path = lines
-
- for dist in find_distributions(os.path.join(path, egg_path)):
- dist.location = os.path.join(path, *lines)
- dist.precedence = SOURCE_DIST
- self.add(dist)
-
+ if fatal:
+ raise DistutilsError(msg % url)
+ else:
+ self.warn(msg, url)
+
+ def scan_egg_links(self, search_path):
+ dirs = filter(os.path.isdir, search_path)
+ egg_links = (
+ (path, entry)
+ for path in dirs
+ for entry in os.listdir(path)
+ if entry.endswith('.egg-link')
+ )
+ list(itertools.starmap(self.scan_egg_link, egg_links))
+
+ def scan_egg_link(self, path, entry):
+ with open(os.path.join(path, entry)) as raw_lines:
+ # filter non-empty lines
+ lines = list(filter(None, map(str.strip, raw_lines)))
+
+ if len(lines) != 2:
+ # format is not recognized; punt
+ return
+
+ egg_path, setup_path = lines
+
+ for dist in find_distributions(os.path.join(path, egg_path)):
+ dist.location = os.path.join(path, *lines)
+ dist.precedence = SOURCE_DIST
+ self.add(dist)
+
def process_index(self, url, page):
- """Process the contents of a PyPI page"""
-
- def scan(link):
- # Process a URL to see if it's for a package page
- if link.startswith(self.index_url):
- parts = list(map(
- urllib.parse.unquote, link[len(self.index_url):].split('/')
- ))
+ """Process the contents of a PyPI page"""
+
+ def scan(link):
+ # Process a URL to see if it's for a package page
+ if link.startswith(self.index_url):
+ parts = list(map(
+ urllib.parse.unquote, link[len(self.index_url):].split('/')
+ ))
if len(parts) == 2 and '#' not in parts[1]:
- # it's a package page, sanitize and index it
- pkg = safe_name(parts[0])
- ver = safe_version(parts[1])
+ # it's a package page, sanitize and index it
+ pkg = safe_name(parts[0])
+ ver = safe_version(parts[1])
self.package_pages.setdefault(pkg.lower(), {})[link] = True
- return to_filename(pkg), to_filename(ver)
- return None, None
-
- # process an index page into the package-page index
- for match in HREF.finditer(page):
- try:
- scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))
- except ValueError:
- pass
-
+ return to_filename(pkg), to_filename(ver)
+ return None, None
+
+ # process an index page into the package-page index
+ for match in HREF.finditer(page):
+ try:
+ scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))
+ except ValueError:
+ pass
+
pkg, ver = scan(url) # ensure this page is in the page index
- if pkg:
- # process individual package page
- for new_url in find_external_links(url, page):
- # Process the found URL
- base, frag = egg_info_for_url(new_url)
- if base.endswith('.py') and not frag:
- if ver:
+ if pkg:
+ # process individual package page
+ for new_url in find_external_links(url, page):
+ # Process the found URL
+ base, frag = egg_info_for_url(new_url)
+ if base.endswith('.py') and not frag:
+ if ver:
new_url += '#egg=%s-%s' % (pkg, ver)
- else:
- self.need_version_info(url)
- self.scan_url(new_url)
-
- return PYPI_MD5.sub(
+ else:
+ self.need_version_info(url)
+ self.scan_url(new_url)
+
+ return PYPI_MD5.sub(
lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1, 3, 2), page
- )
- else:
+ )
+ else:
return "" # no sense double-scanning non-package pages
-
- def need_version_info(self, url):
- self.scan_all(
- "Page at %s links to .py file(s) without version info; an index "
- "scan is required.", url
- )
-
- def scan_all(self, msg=None, *args):
- if self.index_url not in self.fetched_urls:
+
+ def need_version_info(self, url):
+ self.scan_all(
+ "Page at %s links to .py file(s) without version info; an index "
+ "scan is required.", url
+ )
+
+ def scan_all(self, msg=None, *args):
+ if self.index_url not in self.fetched_urls:
if msg:
self.warn(msg, *args)
- self.info(
- "Scanning index of all packages (this may take a while)"
- )
- self.scan_url(self.index_url)
-
- def find_packages(self, requirement):
+ self.info(
+ "Scanning index of all packages (this may take a while)"
+ )
+ self.scan_url(self.index_url)
+
+ def find_packages(self, requirement):
self.scan_url(self.index_url + requirement.unsafe_name + '/')
-
- if not self.package_pages.get(requirement.key):
- # Fall back to safe version of the name
+
+ if not self.package_pages.get(requirement.key):
+ # Fall back to safe version of the name
self.scan_url(self.index_url + requirement.project_name + '/')
-
- if not self.package_pages.get(requirement.key):
- # We couldn't find the target package, so search the index page too
- self.not_found_in_index(requirement)
-
+
+ if not self.package_pages.get(requirement.key):
+ # We couldn't find the target package, so search the index page too
+ self.not_found_in_index(requirement)
+
for url in list(self.package_pages.get(requirement.key, ())):
- # scan each page that might be related to the desired package
- self.scan_url(url)
-
- def obtain(self, requirement, installer=None):
- self.prescan()
- self.find_packages(requirement)
- for dist in self[requirement.key]:
- if dist in requirement:
- return dist
- self.debug("%s does not match %s", requirement, dist)
+ # scan each page that might be related to the desired package
+ self.scan_url(url)
+
+ def obtain(self, requirement, installer=None):
+ self.prescan()
+ self.find_packages(requirement)
+ for dist in self[requirement.key]:
+ if dist in requirement:
+ return dist
+ self.debug("%s does not match %s", requirement, dist)
return super(PackageIndex, self).obtain(requirement, installer)
-
- def check_hash(self, checker, filename, tfp):
- """
- checker is a ContentChecker
- """
+
+ def check_hash(self, checker, filename, tfp):
+ """
+ checker is a ContentChecker
+ """
checker.report(
self.debug,
- "Validating %%s checksum for %s" % filename)
- if not checker.is_valid():
- tfp.close()
- os.unlink(filename)
- raise DistutilsError(
- "%s validation failed for %s; "
+ "Validating %%s checksum for %s" % filename)
+ if not checker.is_valid():
+ tfp.close()
+ os.unlink(filename)
+ raise DistutilsError(
+ "%s validation failed for %s; "
"possible download problem?"
% (checker.hash.name, os.path.basename(filename))
- )
-
- def add_find_links(self, urls):
- """Add `urls` to the list that will be prescanned for searches"""
- for url in urls:
- if (
+ )
+
+ def add_find_links(self, urls):
+ """Add `urls` to the list that will be prescanned for searches"""
+ for url in urls:
+ if (
self.to_scan is None # if we have already "gone online"
or not URL_SCHEME(url) # or it's a local file/directory
- or url.startswith('file:')
+ or url.startswith('file:')
or list(distros_for_url(url)) # or a direct package link
- ):
- # then go ahead and process it now
- self.scan_url(url)
- else:
- # otherwise, defer retrieval till later
- self.to_scan.append(url)
-
- def prescan(self):
- """Scan urls scheduled for prescanning (e.g. --find-links)"""
- if self.to_scan:
- list(map(self.scan_url, self.to_scan))
+ ):
+ # then go ahead and process it now
+ self.scan_url(url)
+ else:
+ # otherwise, defer retrieval till later
+ self.to_scan.append(url)
+
+ def prescan(self):
+ """Scan urls scheduled for prescanning (e.g. --find-links)"""
+ if self.to_scan:
+ list(map(self.scan_url, self.to_scan))
self.to_scan = None # from now on, go ahead and process immediately
-
- def not_found_in_index(self, requirement):
+
+ def not_found_in_index(self, requirement):
if self[requirement.key]: # we've seen at least one distro
- meth, msg = self.info, "Couldn't retrieve index page for %r"
+ meth, msg = self.info, "Couldn't retrieve index page for %r"
else: # no distros seen for this name, might be misspelled
meth, msg = (
self.warn,
- "Couldn't find index page for %r (maybe misspelled?)")
- meth(msg, requirement.unsafe_name)
- self.scan_all()
-
- def download(self, spec, tmpdir):
- """Locate and/or download `spec` to `tmpdir`, returning a local path
-
- `spec` may be a ``Requirement`` object, or a string containing a URL,
- an existing local filename, or a project/version requirement spec
- (i.e. the string form of a ``Requirement`` object). If it is the URL
- of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one
- that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is
- automatically created alongside the downloaded file.
-
- If `spec` is a ``Requirement`` object or a string containing a
- project/version requirement spec, this method returns the location of
- a matching distribution (possibly after downloading it to `tmpdir`).
- If `spec` is a locally existing file or directory name, it is simply
- returned unchanged. If `spec` is a URL, it is downloaded to a subpath
- of `tmpdir`, and the local filename is returned. Various errors may be
- raised if a problem occurs during downloading.
- """
+ "Couldn't find index page for %r (maybe misspelled?)")
+ meth(msg, requirement.unsafe_name)
+ self.scan_all()
+
+ def download(self, spec, tmpdir):
+ """Locate and/or download `spec` to `tmpdir`, returning a local path
+
+ `spec` may be a ``Requirement`` object, or a string containing a URL,
+ an existing local filename, or a project/version requirement spec
+ (i.e. the string form of a ``Requirement`` object). If it is the URL
+ of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one
+ that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is
+ automatically created alongside the downloaded file.
+
+ If `spec` is a ``Requirement`` object or a string containing a
+ project/version requirement spec, this method returns the location of
+ a matching distribution (possibly after downloading it to `tmpdir`).
+ If `spec` is a locally existing file or directory name, it is simply
+ returned unchanged. If `spec` is a URL, it is downloaded to a subpath
+ of `tmpdir`, and the local filename is returned. Various errors may be
+ raised if a problem occurs during downloading.
+ """
if not isinstance(spec, Requirement):
- scheme = URL_SCHEME(spec)
- if scheme:
- # It's a url, download it to tmpdir
- found = self._download_url(scheme.group(1), spec, tmpdir)
- base, fragment = egg_info_for_url(spec)
- if base.endswith('.py'):
+ scheme = URL_SCHEME(spec)
+ if scheme:
+ # It's a url, download it to tmpdir
+ found = self._download_url(scheme.group(1), spec, tmpdir)
+ base, fragment = egg_info_for_url(spec)
+ if base.endswith('.py'):
found = self.gen_setup(found, fragment, tmpdir)
- return found
- elif os.path.exists(spec):
- # Existing file or directory, just return it
- return spec
- else:
+ return found
+ elif os.path.exists(spec):
+ # Existing file or directory, just return it
+ return spec
+ else:
spec = parse_requirement_arg(spec)
return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)
-
- def fetch_distribution(
- self, requirement, tmpdir, force_scan=False, source=False,
+
+ def fetch_distribution(
+ self, requirement, tmpdir, force_scan=False, source=False,
develop_ok=False, local_index=None):
- """Obtain a distribution suitable for fulfilling `requirement`
-
- `requirement` must be a ``pkg_resources.Requirement`` instance.
- If necessary, or if the `force_scan` flag is set, the requirement is
- searched for in the (online) package index as well as the locally
- installed packages. If a distribution matching `requirement` is found,
- the returned distribution's ``location`` is the value you would have
- gotten from calling the ``download()`` method with the matching
- distribution's URL or filename. If no matching distribution is found,
- ``None`` is returned.
-
- If the `source` flag is set, only source distributions and source
- checkout links will be considered. Unless the `develop_ok` flag is
- set, development and system eggs (i.e., those using the ``.egg-info``
- format) will be ignored.
- """
- # process a Requirement
- self.info("Searching for %s", requirement)
- skipped = {}
- dist = None
-
- def find(req, env=None):
- if env is None:
- env = self
- # Find a matching distribution; may be called more than once
-
- for dist in env[req.key]:
-
+ """Obtain a distribution suitable for fulfilling `requirement`
+
+ `requirement` must be a ``pkg_resources.Requirement`` instance.
+ If necessary, or if the `force_scan` flag is set, the requirement is
+ searched for in the (online) package index as well as the locally
+ installed packages. If a distribution matching `requirement` is found,
+ the returned distribution's ``location`` is the value you would have
+ gotten from calling the ``download()`` method with the matching
+ distribution's URL or filename. If no matching distribution is found,
+ ``None`` is returned.
+
+ If the `source` flag is set, only source distributions and source
+ checkout links will be considered. Unless the `develop_ok` flag is
+ set, development and system eggs (i.e., those using the ``.egg-info``
+ format) will be ignored.
+ """
+ # process a Requirement
+ self.info("Searching for %s", requirement)
+ skipped = {}
+ dist = None
+
+ def find(req, env=None):
+ if env is None:
+ env = self
+ # Find a matching distribution; may be called more than once
+
+ for dist in env[req.key]:
+
if dist.precedence == DEVELOP_DIST and not develop_ok:
- if dist not in skipped:
+ if dist not in skipped:
self.warn(
"Skipping development or system egg: %s", dist,
)
- skipped[dist] = 1
- continue
-
+ skipped[dist] = 1
+ continue
+
test = (
dist in req
and (dist.precedence <= SOURCE_DIST or not source)
@@ -636,311 +636,311 @@ class PackageIndex(Environment):
dist.download_location = loc
if os.path.exists(dist.download_location):
return dist
-
- if force_scan:
- self.prescan()
- self.find_packages(requirement)
- dist = find(requirement)
-
+
+ if force_scan:
+ self.prescan()
+ self.find_packages(requirement)
+ dist = find(requirement)
+
if not dist and local_index is not None:
dist = find(requirement, local_index)
-
- if dist is None:
- if self.to_scan is not None:
- self.prescan()
- dist = find(requirement)
-
- if dist is None and not force_scan:
- self.find_packages(requirement)
- dist = find(requirement)
-
- if dist is None:
- self.warn(
+
+ if dist is None:
+ if self.to_scan is not None:
+ self.prescan()
+ dist = find(requirement)
+
+ if dist is None and not force_scan:
+ self.find_packages(requirement)
+ dist = find(requirement)
+
+ if dist is None:
+ self.warn(
"No local packages or working download links found for %s%s",
- (source and "a source distribution of " or ""),
- requirement,
- )
- else:
- self.info("Best match: %s", dist)
+ (source and "a source distribution of " or ""),
+ requirement,
+ )
+ else:
+ self.info("Best match: %s", dist)
return dist.clone(location=dist.download_location)
-
- def fetch(self, requirement, tmpdir, force_scan=False, source=False):
- """Obtain a file suitable for fulfilling `requirement`
-
- DEPRECATED; use the ``fetch_distribution()`` method now instead. For
- backward compatibility, this routine is identical but returns the
- ``location`` of the downloaded distribution instead of a distribution
- object.
- """
+
+ def fetch(self, requirement, tmpdir, force_scan=False, source=False):
+ """Obtain a file suitable for fulfilling `requirement`
+
+ DEPRECATED; use the ``fetch_distribution()`` method now instead. For
+ backward compatibility, this routine is identical but returns the
+ ``location`` of the downloaded distribution instead of a distribution
+ object.
+ """
dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
- if dist is not None:
- return dist.location
- return None
-
- def gen_setup(self, filename, fragment, tmpdir):
- match = EGG_FRAGMENT.match(fragment)
- dists = match and [
- d for d in
- interpret_distro_name(filename, match.group(1), None) if d.version
- ] or []
-
+ if dist is not None:
+ return dist.location
+ return None
+
+ def gen_setup(self, filename, fragment, tmpdir):
+ match = EGG_FRAGMENT.match(fragment)
+ dists = match and [
+ d for d in
+ interpret_distro_name(filename, match.group(1), None) if d.version
+ ] or []
+
if len(dists) == 1: # unambiguous ``#egg`` fragment
- basename = os.path.basename(filename)
-
- # Make sure the file has been downloaded to the temp dir.
- if os.path.dirname(filename) != tmpdir:
- dst = os.path.join(tmpdir, basename)
- from setuptools.command.easy_install import samefile
- if not samefile(filename, dst):
- shutil.copy2(filename, dst)
+ basename = os.path.basename(filename)
+
+ # Make sure the file has been downloaded to the temp dir.
+ if os.path.dirname(filename) != tmpdir:
+ dst = os.path.join(tmpdir, basename)
+ from setuptools.command.easy_install import samefile
+ if not samefile(filename, dst):
+ shutil.copy2(filename, dst)
filename = dst
-
- with open(os.path.join(tmpdir, 'setup.py'), 'w') as file:
- file.write(
- "from setuptools import setup\n"
- "setup(name=%r, version=%r, py_modules=[%r])\n"
- % (
- dists[0].project_name, dists[0].version,
- os.path.splitext(basename)[0]
- )
- )
- return filename
-
- elif match:
- raise DistutilsError(
- "Can't unambiguously interpret project/version identifier %r; "
- "any dashes in the name or version should be escaped using "
+
+ with open(os.path.join(tmpdir, 'setup.py'), 'w') as file:
+ file.write(
+ "from setuptools import setup\n"
+ "setup(name=%r, version=%r, py_modules=[%r])\n"
+ % (
+ dists[0].project_name, dists[0].version,
+ os.path.splitext(basename)[0]
+ )
+ )
+ return filename
+
+ elif match:
+ raise DistutilsError(
+ "Can't unambiguously interpret project/version identifier %r; "
+ "any dashes in the name or version should be escaped using "
"underscores. %r" % (fragment, dists)
- )
- else:
- raise DistutilsError(
- "Can't process plain .py files without an '#egg=name-version'"
- " suffix to enable automatic setup script generation."
- )
-
- dl_blocksize = 8192
-
- def _download_to(self, url, filename):
- self.info("Downloading %s", url)
- # Download the file
+ )
+ else:
+ raise DistutilsError(
+ "Can't process plain .py files without an '#egg=name-version'"
+ " suffix to enable automatic setup script generation."
+ )
+
+ dl_blocksize = 8192
+
+ def _download_to(self, url, filename):
+ self.info("Downloading %s", url)
+ # Download the file
fp = None
- try:
- checker = HashChecker.from_url(url)
+ try:
+ checker = HashChecker.from_url(url)
fp = self.open_url(url)
- if isinstance(fp, urllib.error.HTTPError):
- raise DistutilsError(
+ if isinstance(fp, urllib.error.HTTPError):
+ raise DistutilsError(
"Can't download %s: %s %s" % (url, fp.code, fp.msg)
- )
- headers = fp.info()
- blocknum = 0
- bs = self.dl_blocksize
- size = -1
- if "content-length" in headers:
- # Some servers return multiple Content-Length headers :(
- sizes = get_all_headers(headers, 'Content-Length')
- size = max(map(int, sizes))
- self.reporthook(url, filename, blocknum, bs, size)
+ )
+ headers = fp.info()
+ blocknum = 0
+ bs = self.dl_blocksize
+ size = -1
+ if "content-length" in headers:
+ # Some servers return multiple Content-Length headers :(
+ sizes = get_all_headers(headers, 'Content-Length')
+ size = max(map(int, sizes))
+ self.reporthook(url, filename, blocknum, bs, size)
with open(filename, 'wb') as tfp:
- while True:
- block = fp.read(bs)
- if block:
- checker.feed(block)
- tfp.write(block)
- blocknum += 1
- self.reporthook(url, filename, blocknum, bs, size)
- else:
- break
- self.check_hash(checker, filename, tfp)
- return headers
- finally:
+ while True:
+ block = fp.read(bs)
+ if block:
+ checker.feed(block)
+ tfp.write(block)
+ blocknum += 1
+ self.reporthook(url, filename, blocknum, bs, size)
+ else:
+ break
+ self.check_hash(checker, filename, tfp)
+ return headers
+ finally:
if fp:
fp.close()
-
- def reporthook(self, url, filename, blocknum, blksize, size):
+
+ def reporthook(self, url, filename, blocknum, blksize, size):
pass # no-op
-
- def open_url(self, url, warning=None):
- if url.startswith('file:'):
- return local_open(url)
- try:
- return open_with_auth(url, self.opener)
- except (ValueError, http_client.InvalidURL) as v:
- msg = ' '.join([str(arg) for arg in v.args])
- if warning:
- self.warn(warning, msg)
- else:
- raise DistutilsError('%s %s' % (url, msg))
- except urllib.error.HTTPError as v:
- return v
- except urllib.error.URLError as v:
- if warning:
- self.warn(warning, v.reason)
- else:
- raise DistutilsError("Download error for %s: %s"
- % (url, v.reason))
- except http_client.BadStatusLine as v:
- if warning:
- self.warn(warning, v.line)
- else:
- raise DistutilsError(
- '%s returned a bad status line. The server might be '
- 'down, %s' %
- (url, v.line)
- )
+
+ def open_url(self, url, warning=None):
+ if url.startswith('file:'):
+ return local_open(url)
+ try:
+ return open_with_auth(url, self.opener)
+ except (ValueError, http_client.InvalidURL) as v:
+ msg = ' '.join([str(arg) for arg in v.args])
+ if warning:
+ self.warn(warning, msg)
+ else:
+ raise DistutilsError('%s %s' % (url, msg))
+ except urllib.error.HTTPError as v:
+ return v
+ except urllib.error.URLError as v:
+ if warning:
+ self.warn(warning, v.reason)
+ else:
+ raise DistutilsError("Download error for %s: %s"
+ % (url, v.reason))
+ except http_client.BadStatusLine as v:
+ if warning:
+ self.warn(warning, v.line)
+ else:
+ raise DistutilsError(
+ '%s returned a bad status line. The server might be '
+ 'down, %s' %
+ (url, v.line)
+ )
except (http_client.HTTPException, socket.error) as v:
- if warning:
- self.warn(warning, v)
- else:
- raise DistutilsError("Download error for %s: %s"
- % (url, v))
-
- def _download_url(self, scheme, url, tmpdir):
- # Determine download filename
- #
- name, fragment = egg_info_for_url(url)
- if name:
- while '..' in name:
+ if warning:
+ self.warn(warning, v)
+ else:
+ raise DistutilsError("Download error for %s: %s"
+ % (url, v))
+
+ def _download_url(self, scheme, url, tmpdir):
+ # Determine download filename
+ #
+ name, fragment = egg_info_for_url(url)
+ if name:
+ while '..' in name:
name = name.replace('..', '.').replace('\\', '_')
- else:
+ else:
name = "__downloaded__" # default if URL has no path contents
-
- if name.endswith('.egg.zip'):
+
+ if name.endswith('.egg.zip'):
name = name[:-4] # strip the extra .zip before download
-
+
filename = os.path.join(tmpdir, name)
-
- # Download the file
- #
+
+ # Download the file
+ #
if scheme == 'svn' or scheme.startswith('svn+'):
- return self._download_svn(url, filename)
+ return self._download_svn(url, filename)
elif scheme == 'git' or scheme.startswith('git+'):
- return self._download_git(url, filename)
- elif scheme.startswith('hg+'):
- return self._download_hg(url, filename)
+ return self._download_git(url, filename)
+ elif scheme.startswith('hg+'):
+ return self._download_hg(url, filename)
elif scheme == 'file':
- return urllib.request.url2pathname(urllib.parse.urlparse(url)[2])
- else:
+ return urllib.request.url2pathname(urllib.parse.urlparse(url)[2])
+ else:
self.url_ok(url, True) # raises error if not allowed
- return self._attempt_download(url, filename)
-
- def scan_url(self, url):
- self.process_url(url, True)
-
- def _attempt_download(self, url, filename):
- headers = self._download_to(url, filename)
+ return self._attempt_download(url, filename)
+
+ def scan_url(self, url):
+ self.process_url(url, True)
+
+ def _attempt_download(self, url, filename):
+ headers = self._download_to(url, filename)
if 'html' in headers.get('content-type', '').lower():
- return self._download_html(url, headers, filename)
- else:
- return filename
-
- def _download_html(self, url, headers, filename):
- file = open(filename)
- for line in file:
- if line.strip():
- # Check for a subversion index page
- if re.search(r'<title>([^- ]+ - )?Revision \d+:', line):
- # it's a subversion index page:
- file.close()
- os.unlink(filename)
- return self._download_svn(url, filename)
+ return self._download_html(url, headers, filename)
+ else:
+ return filename
+
+ def _download_html(self, url, headers, filename):
+ file = open(filename)
+ for line in file:
+ if line.strip():
+ # Check for a subversion index page
+ if re.search(r'<title>([^- ]+ - )?Revision \d+:', line):
+ # it's a subversion index page:
+ file.close()
+ os.unlink(filename)
+ return self._download_svn(url, filename)
break # not an index page
- file.close()
- os.unlink(filename)
+ file.close()
+ os.unlink(filename)
raise DistutilsError("Unexpected HTML page found at " + url)
-
- def _download_svn(self, url, filename):
+
+ def _download_svn(self, url, filename):
warnings.warn("SVN download support is deprecated", UserWarning)
url = url.split('#', 1)[0] # remove any fragment for svn's sake
- creds = ''
- if url.lower().startswith('svn:') and '@' in url:
- scheme, netloc, path, p, q, f = urllib.parse.urlparse(url)
- if not netloc and path.startswith('//') and '/' in path[2:]:
+ creds = ''
+ if url.lower().startswith('svn:') and '@' in url:
+ scheme, netloc, path, p, q, f = urllib.parse.urlparse(url)
+ if not netloc and path.startswith('//') and '/' in path[2:]:
netloc, path = path[2:].split('/', 1)
auth, host = _splituser(netloc)
- if auth:
- if ':' in auth:
+ if auth:
+ if ':' in auth:
user, pw = auth.split(':', 1)
- creds = " --username=%s --password=%s" % (user, pw)
- else:
+ creds = " --username=%s --password=%s" % (user, pw)
+ else:
creds = " --username=" + auth
- netloc = host
- parts = scheme, netloc, url, p, q, f
- url = urllib.parse.urlunparse(parts)
- self.info("Doing subversion checkout from %s to %s", url, filename)
- os.system("svn checkout%s -q %s %s" % (creds, url, filename))
- return filename
-
- @staticmethod
- def _vcs_split_rev_from_url(url, pop_prefix=False):
- scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)
-
- scheme = scheme.split('+', 1)[-1]
-
- # Some fragment identification fails
+ netloc = host
+ parts = scheme, netloc, url, p, q, f
+ url = urllib.parse.urlunparse(parts)
+ self.info("Doing subversion checkout from %s to %s", url, filename)
+ os.system("svn checkout%s -q %s %s" % (creds, url, filename))
+ return filename
+
+ @staticmethod
+ def _vcs_split_rev_from_url(url, pop_prefix=False):
+ scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)
+
+ scheme = scheme.split('+', 1)[-1]
+
+ # Some fragment identification fails
path = path.split('#', 1)[0]
-
- rev = None
- if '@' in path:
- path, rev = path.rsplit('@', 1)
-
- # Also, discard fragment
- url = urllib.parse.urlunsplit((scheme, netloc, path, query, ''))
-
- return url, rev
-
- def _download_git(self, url, filename):
+
+ rev = None
+ if '@' in path:
+ path, rev = path.rsplit('@', 1)
+
+ # Also, discard fragment
+ url = urllib.parse.urlunsplit((scheme, netloc, path, query, ''))
+
+ return url, rev
+
+ def _download_git(self, url, filename):
filename = filename.split('#', 1)[0]
- url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
-
- self.info("Doing git clone from %s to %s", url, filename)
- os.system("git clone --quiet %s %s" % (url, filename))
-
- if rev is not None:
- self.info("Checking out %s", rev)
+ url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
+
+ self.info("Doing git clone from %s to %s", url, filename)
+ os.system("git clone --quiet %s %s" % (url, filename))
+
+ if rev is not None:
+ self.info("Checking out %s", rev)
os.system("git -C %s checkout --quiet %s" % (
- filename,
- rev,
- ))
-
- return filename
-
- def _download_hg(self, url, filename):
+ filename,
+ rev,
+ ))
+
+ return filename
+
+ def _download_hg(self, url, filename):
filename = filename.split('#', 1)[0]
- url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
-
- self.info("Doing hg clone from %s to %s", url, filename)
- os.system("hg clone --quiet %s %s" % (url, filename))
-
- if rev is not None:
- self.info("Updating to %s", rev)
+ url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
+
+ self.info("Doing hg clone from %s to %s", url, filename)
+ os.system("hg clone --quiet %s %s" % (url, filename))
+
+ if rev is not None:
+ self.info("Updating to %s", rev)
os.system("hg --cwd %s up -C -r %s -q" % (
- filename,
- rev,
- ))
-
- return filename
-
- def debug(self, msg, *args):
- log.debug(msg, *args)
-
- def info(self, msg, *args):
- log.info(msg, *args)
-
- def warn(self, msg, *args):
- log.warn(msg, *args)
-
-
-# This pattern matches a character entity reference (a decimal numeric
-# references, a hexadecimal numeric reference, or a named reference).
-entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub
-
-
-def decode_entity(match):
+ filename,
+ rev,
+ ))
+
+ return filename
+
+ def debug(self, msg, *args):
+ log.debug(msg, *args)
+
+ def info(self, msg, *args):
+ log.info(msg, *args)
+
+ def warn(self, msg, *args):
+ log.warn(msg, *args)
+
+
+# This pattern matches a character entity reference (a decimal numeric
+# references, a hexadecimal numeric reference, or a named reference).
+entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub
+
+
+def decode_entity(match):
what = match.group(0)
return unescape(what)
-
-def htmldecode(text):
+
+def htmldecode(text):
"""
Decode HTML entities in the given text.
@@ -949,146 +949,146 @@ def htmldecode(text):
... '?tokena=A&amp;tokenb=B">package_name-0.1.2.tar.gz')
'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz'
"""
- return entity_sub(decode_entity, text)
-
-
-def socket_timeout(timeout=15):
- def _socket_timeout(func):
- def _socket_timeout(*args, **kwargs):
- old_timeout = socket.getdefaulttimeout()
- socket.setdefaulttimeout(timeout)
- try:
- return func(*args, **kwargs)
- finally:
- socket.setdefaulttimeout(old_timeout)
-
- return _socket_timeout
-
- return _socket_timeout
-
-
-def _encode_auth(auth):
- """
- A function compatible with Python 2.3-3.3 that will encode
- auth from a URL suitable for an HTTP header.
- >>> str(_encode_auth('username%3Apassword'))
- 'dXNlcm5hbWU6cGFzc3dvcmQ='
-
- Long auth strings should not cause a newline to be inserted.
- >>> long_auth = 'username:' + 'password'*10
- >>> chr(10) in str(_encode_auth(long_auth))
- False
- """
- auth_s = urllib.parse.unquote(auth)
- # convert to bytes
- auth_bytes = auth_s.encode()
+ return entity_sub(decode_entity, text)
+
+
+def socket_timeout(timeout=15):
+ def _socket_timeout(func):
+ def _socket_timeout(*args, **kwargs):
+ old_timeout = socket.getdefaulttimeout()
+ socket.setdefaulttimeout(timeout)
+ try:
+ return func(*args, **kwargs)
+ finally:
+ socket.setdefaulttimeout(old_timeout)
+
+ return _socket_timeout
+
+ return _socket_timeout
+
+
+def _encode_auth(auth):
+ """
+ A function compatible with Python 2.3-3.3 that will encode
+ auth from a URL suitable for an HTTP header.
+ >>> str(_encode_auth('username%3Apassword'))
+ 'dXNlcm5hbWU6cGFzc3dvcmQ='
+
+ Long auth strings should not cause a newline to be inserted.
+ >>> long_auth = 'username:' + 'password'*10
+ >>> chr(10) in str(_encode_auth(long_auth))
+ False
+ """
+ auth_s = urllib.parse.unquote(auth)
+ # convert to bytes
+ auth_bytes = auth_s.encode()
encoded_bytes = base64.b64encode(auth_bytes)
- # convert back to a string
- encoded = encoded_bytes.decode()
- # strip the trailing carriage return
+ # convert back to a string
+ encoded = encoded_bytes.decode()
+ # strip the trailing carriage return
return encoded.replace('\n', '')
-
+
class Credential:
- """
- A username/password pair. Use like a namedtuple.
- """
-
- def __init__(self, username, password):
- self.username = username
- self.password = password
-
- def __iter__(self):
- yield self.username
- yield self.password
-
- def __str__(self):
- return '%(username)s:%(password)s' % vars(self)
-
-
-class PyPIConfig(configparser.RawConfigParser):
- def __init__(self):
- """
- Load from ~/.pypirc
- """
- defaults = dict.fromkeys(['username', 'password', 'repository'], '')
- configparser.RawConfigParser.__init__(self, defaults)
-
- rc = os.path.join(os.path.expanduser('~'), '.pypirc')
- if os.path.exists(rc):
- self.read(rc)
-
- @property
- def creds_by_repository(self):
- sections_with_repositories = [
- section for section in self.sections()
- if self.get(section, 'repository').strip()
- ]
-
- return dict(map(self._get_repo_cred, sections_with_repositories))
-
- def _get_repo_cred(self, section):
- repo = self.get(section, 'repository').strip()
- return repo, Credential(
- self.get(section, 'username').strip(),
- self.get(section, 'password').strip(),
- )
-
- def find_credential(self, url):
- """
- If the URL indicated appears to be a repository defined in this
- config, return the credential for that repository.
- """
- for repository, cred in self.creds_by_repository.items():
- if url.startswith(repository):
- return cred
-
-
-def open_with_auth(url, opener=urllib.request.urlopen):
- """Open a urllib2 request, handling HTTP authentication"""
-
+ """
+ A username/password pair. Use like a namedtuple.
+ """
+
+ def __init__(self, username, password):
+ self.username = username
+ self.password = password
+
+ def __iter__(self):
+ yield self.username
+ yield self.password
+
+ def __str__(self):
+ return '%(username)s:%(password)s' % vars(self)
+
+
+class PyPIConfig(configparser.RawConfigParser):
+ def __init__(self):
+ """
+ Load from ~/.pypirc
+ """
+ defaults = dict.fromkeys(['username', 'password', 'repository'], '')
+ configparser.RawConfigParser.__init__(self, defaults)
+
+ rc = os.path.join(os.path.expanduser('~'), '.pypirc')
+ if os.path.exists(rc):
+ self.read(rc)
+
+ @property
+ def creds_by_repository(self):
+ sections_with_repositories = [
+ section for section in self.sections()
+ if self.get(section, 'repository').strip()
+ ]
+
+ return dict(map(self._get_repo_cred, sections_with_repositories))
+
+ def _get_repo_cred(self, section):
+ repo = self.get(section, 'repository').strip()
+ return repo, Credential(
+ self.get(section, 'username').strip(),
+ self.get(section, 'password').strip(),
+ )
+
+ def find_credential(self, url):
+ """
+ If the URL indicated appears to be a repository defined in this
+ config, return the credential for that repository.
+ """
+ for repository, cred in self.creds_by_repository.items():
+ if url.startswith(repository):
+ return cred
+
+
+def open_with_auth(url, opener=urllib.request.urlopen):
+ """Open a urllib2 request, handling HTTP authentication"""
+
parsed = urllib.parse.urlparse(url)
scheme, netloc, path, params, query, frag = parsed
-
- # Double scheme does not raise on Mac OS X as revealed by a
- # failing test. We would expect "nonnumeric port". Refs #20.
- if netloc.endswith(':'):
- raise http_client.InvalidURL("nonnumeric port: ''")
-
- if scheme in ('http', 'https'):
+
+ # Double scheme does not raise on Mac OS X as revealed by a
+ # failing test. We would expect "nonnumeric port". Refs #20.
+ if netloc.endswith(':'):
+ raise http_client.InvalidURL("nonnumeric port: ''")
+
+ if scheme in ('http', 'https'):
auth, address = _splituser(netloc)
- else:
- auth = None
-
- if not auth:
- cred = PyPIConfig().find_credential(url)
- if cred:
- auth = str(cred)
- info = cred.username, url
+ else:
+ auth = None
+
+ if not auth:
+ cred = PyPIConfig().find_credential(url)
+ if cred:
+ auth = str(cred)
+ info = cred.username, url
log.info('Authenticating as %s for %s (from .pypirc)', *info)
-
- if auth:
- auth = "Basic " + _encode_auth(auth)
+
+ if auth:
+ auth = "Basic " + _encode_auth(auth)
parts = scheme, address, path, params, query, frag
- new_url = urllib.parse.urlunparse(parts)
- request = urllib.request.Request(new_url)
- request.add_header("Authorization", auth)
- else:
- request = urllib.request.Request(url)
-
- request.add_header('User-Agent', user_agent)
- fp = opener(request)
-
- if auth:
- # Put authentication info back into request URL if same host,
- # so that links found on the page will work
- s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)
+ new_url = urllib.parse.urlunparse(parts)
+ request = urllib.request.Request(new_url)
+ request.add_header("Authorization", auth)
+ else:
+ request = urllib.request.Request(url)
+
+ request.add_header('User-Agent', user_agent)
+ fp = opener(request)
+
+ if auth:
+ # Put authentication info back into request URL if same host,
+ # so that links found on the page will work
+ s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)
if s2 == scheme and h2 == address:
- parts = s2, netloc, path2, param2, query2, frag2
- fp.url = urllib.parse.urlunparse(parts)
-
- return fp
-
+ parts = s2, netloc, path2, param2, query2, frag2
+ fp.url = urllib.parse.urlunparse(parts)
+
+ return fp
+
# copy of urllib.parse._splituser from Python 3.8
def _splituser(host):
@@ -1097,40 +1097,40 @@ def _splituser(host):
return (user if delim else None), host
-# adding a timeout to avoid freezing package_index
-open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
-
-
-def fix_sf_url(url):
+# adding a timeout to avoid freezing package_index
+open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
+
+
+def fix_sf_url(url):
return url # backward compatibility
-
-
-def local_open(url):
- """Read a local path, with special support for directories"""
- scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
- filename = urllib.request.url2pathname(path)
- if os.path.isfile(filename):
- return urllib.request.urlopen(url)
- elif path.endswith('/') and os.path.isdir(filename):
- files = []
- for f in os.listdir(filename):
- filepath = os.path.join(filename, f)
- if f == 'index.html':
- with open(filepath, 'r') as fp:
- body = fp.read()
- break
- elif os.path.isdir(filepath):
- f += '/'
- files.append('<a href="{name}">{name}</a>'.format(name=f))
- else:
+
+
+def local_open(url):
+ """Read a local path, with special support for directories"""
+ scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
+ filename = urllib.request.url2pathname(path)
+ if os.path.isfile(filename):
+ return urllib.request.urlopen(url)
+ elif path.endswith('/') and os.path.isdir(filename):
+ files = []
+ for f in os.listdir(filename):
+ filepath = os.path.join(filename, f)
+ if f == 'index.html':
+ with open(filepath, 'r') as fp:
+ body = fp.read()
+ break
+ elif os.path.isdir(filepath):
+ f += '/'
+ files.append('<a href="{name}">{name}</a>'.format(name=f))
+ else:
tmpl = (
"<html><head><title>{url}</title>"
- "</head><body>{files}</body></html>")
- body = tmpl.format(url=url, files='\n'.join(files))
- status, message = 200, "OK"
- else:
- status, message, body = 404, "Path not found", "Not found"
-
- headers = {'content-type': 'text/html'}
- body_stream = six.StringIO(body)
- return urllib.error.HTTPError(url, status, message, headers, body_stream)
+ "</head><body>{files}</body></html>")
+ body = tmpl.format(url=url, files='\n'.join(files))
+ status, message = 200, "OK"
+ else:
+ status, message, body = 404, "Path not found", "Not found"
+
+ headers = {'content-type': 'text/html'}
+ body_stream = six.StringIO(body)
+ return urllib.error.HTTPError(url, status, message, headers, body_stream)
diff --git a/contrib/python/setuptools/py2/setuptools/py27compat.py b/contrib/python/setuptools/py2/setuptools/py27compat.py
index 3d030d052b..1d57360f4e 100644
--- a/contrib/python/setuptools/py2/setuptools/py27compat.py
+++ b/contrib/python/setuptools/py2/setuptools/py27compat.py
@@ -1,19 +1,19 @@
-"""
-Compatibility Support for Python 2.7 and earlier
-"""
-
+"""
+Compatibility Support for Python 2.7 and earlier
+"""
+
import sys
import platform
-
+
from setuptools.extern import six
-def get_all_headers(message, key):
+def get_all_headers(message, key):
"""
Given an HTTPMessage, return all headers matching a given key.
"""
return message.get_all(key)
-
+
if six.PY2:
def get_all_headers(message, key):
diff --git a/contrib/python/setuptools/py2/setuptools/py31compat.py b/contrib/python/setuptools/py2/setuptools/py31compat.py
index a01180deda..e1da7ee2a2 100644
--- a/contrib/python/setuptools/py2/setuptools/py31compat.py
+++ b/contrib/python/setuptools/py2/setuptools/py31compat.py
@@ -1,32 +1,32 @@
__all__ = []
-
+
__metaclass__ = type
-
-try:
- # Python >=3.2
- from tempfile import TemporaryDirectory
-except ImportError:
- import shutil
- import tempfile
+
+try:
+ # Python >=3.2
+ from tempfile import TemporaryDirectory
+except ImportError:
+ import shutil
+ import tempfile
class TemporaryDirectory:
- """
- Very simple temporary directory context manager.
- Will try to delete afterward, but will also ignore OS and similar
- errors on deletion.
- """
+ """
+ Very simple temporary directory context manager.
+ Will try to delete afterward, but will also ignore OS and similar
+ errors on deletion.
+ """
def __init__(self, **kwargs):
self.name = None # Handle mkdtemp raising an exception
self.name = tempfile.mkdtemp(**kwargs)
-
- def __enter__(self):
- return self.name
-
- def __exit__(self, exctype, excvalue, exctrace):
- try:
- shutil.rmtree(self.name, True)
+
+ def __enter__(self):
+ return self.name
+
+ def __exit__(self, exctype, excvalue, exctrace):
+ try:
+ shutil.rmtree(self.name, True)
except OSError: # removal errors are not the only possible
- pass
- self.name = None
+ pass
+ self.name = None
diff --git a/contrib/python/setuptools/py2/setuptools/sandbox.py b/contrib/python/setuptools/py2/setuptools/sandbox.py
index 82822a6cf4..685f3f72e3 100644
--- a/contrib/python/setuptools/py2/setuptools/sandbox.py
+++ b/contrib/python/setuptools/py2/setuptools/sandbox.py
@@ -1,241 +1,241 @@
-import os
-import sys
-import tempfile
-import operator
-import functools
-import itertools
-import re
-import contextlib
-import pickle
+import os
+import sys
+import tempfile
+import operator
+import functools
+import itertools
+import re
+import contextlib
+import pickle
import textwrap
-
+
from setuptools.extern import six
from setuptools.extern.six.moves import builtins, map
-
+
import pkg_resources.py31compat
-
-if sys.platform.startswith('java'):
- import org.python.modules.posix.PosixModule as _os
-else:
- _os = sys.modules[os.name]
-try:
- _file = file
-except NameError:
- _file = None
-_open = open
-from distutils.errors import DistutilsError
-from pkg_resources import working_set
-
-
-__all__ = [
- "AbstractSandbox", "DirectorySandbox", "SandboxViolation", "run_setup",
-]
-
-
-def _execfile(filename, globals, locals=None):
- """
- Python 3 implementation of execfile.
- """
- mode = 'rb'
- with open(filename, mode) as stream:
- script = stream.read()
- if locals is None:
- locals = globals
- code = compile(script, filename, 'exec')
- exec(code, globals, locals)
-
-
-@contextlib.contextmanager
-def save_argv(repl=None):
- saved = sys.argv[:]
- if repl is not None:
- sys.argv[:] = repl
- try:
- yield saved
- finally:
- sys.argv[:] = saved
-
-
-@contextlib.contextmanager
-def save_path():
- saved = sys.path[:]
- try:
- yield saved
- finally:
- sys.path[:] = saved
-
-
-@contextlib.contextmanager
-def override_temp(replacement):
- """
- Monkey-patch tempfile.tempdir with replacement, ensuring it exists
- """
+
+if sys.platform.startswith('java'):
+ import org.python.modules.posix.PosixModule as _os
+else:
+ _os = sys.modules[os.name]
+try:
+ _file = file
+except NameError:
+ _file = None
+_open = open
+from distutils.errors import DistutilsError
+from pkg_resources import working_set
+
+
+__all__ = [
+ "AbstractSandbox", "DirectorySandbox", "SandboxViolation", "run_setup",
+]
+
+
+def _execfile(filename, globals, locals=None):
+ """
+ Python 3 implementation of execfile.
+ """
+ mode = 'rb'
+ with open(filename, mode) as stream:
+ script = stream.read()
+ if locals is None:
+ locals = globals
+ code = compile(script, filename, 'exec')
+ exec(code, globals, locals)
+
+
+@contextlib.contextmanager
+def save_argv(repl=None):
+ saved = sys.argv[:]
+ if repl is not None:
+ sys.argv[:] = repl
+ try:
+ yield saved
+ finally:
+ sys.argv[:] = saved
+
+
+@contextlib.contextmanager
+def save_path():
+ saved = sys.path[:]
+ try:
+ yield saved
+ finally:
+ sys.path[:] = saved
+
+
+@contextlib.contextmanager
+def override_temp(replacement):
+ """
+ Monkey-patch tempfile.tempdir with replacement, ensuring it exists
+ """
pkg_resources.py31compat.makedirs(replacement, exist_ok=True)
-
- saved = tempfile.tempdir
-
- tempfile.tempdir = replacement
-
- try:
- yield
- finally:
- tempfile.tempdir = saved
-
-
-@contextlib.contextmanager
-def pushd(target):
- saved = os.getcwd()
- os.chdir(target)
- try:
- yield saved
- finally:
- os.chdir(saved)
-
-
-class UnpickleableException(Exception):
- """
- An exception representing another Exception that could not be pickled.
- """
-
- @staticmethod
- def dump(type, exc):
- """
- Always return a dumped (pickled) type and exc. If exc can't be pickled,
- wrap it in UnpickleableException first.
- """
- try:
- return pickle.dumps(type), pickle.dumps(exc)
- except Exception:
- # get UnpickleableException inside the sandbox
- from setuptools.sandbox import UnpickleableException as cls
- return cls.dump(cls, cls(repr(exc)))
-
-
-class ExceptionSaver:
- """
- A Context Manager that will save an exception, serialized, and restore it
- later.
- """
-
- def __enter__(self):
- return self
-
- def __exit__(self, type, exc, tb):
- if not exc:
- return
-
- # dump the exception
- self._saved = UnpickleableException.dump(type, exc)
- self._tb = tb
-
- # suppress the exception
- return True
-
- def resume(self):
- "restore and re-raise any exception"
-
- if '_saved' not in vars(self):
- return
-
- type, exc = map(pickle.loads, self._saved)
- six.reraise(type, exc, self._tb)
-
-
-@contextlib.contextmanager
-def save_modules():
- """
- Context in which imported modules are saved.
-
- Translates exceptions internal to the context into the equivalent exception
- outside the context.
- """
- saved = sys.modules.copy()
- with ExceptionSaver() as saved_exc:
- yield saved
-
- sys.modules.update(saved)
- # remove any modules imported since
- del_modules = (
- mod_name for mod_name in sys.modules
- if mod_name not in saved
- # exclude any encodings modules. See #285
- and not mod_name.startswith('encodings.')
- )
- _clear_modules(del_modules)
-
- saved_exc.resume()
-
-
-def _clear_modules(module_names):
- for mod_name in list(module_names):
- del sys.modules[mod_name]
-
-
-@contextlib.contextmanager
-def save_pkg_resources_state():
- saved = pkg_resources.__getstate__()
- try:
- yield saved
- finally:
- pkg_resources.__setstate__(saved)
-
-
-@contextlib.contextmanager
-def setup_context(setup_dir):
- temp_dir = os.path.join(setup_dir, 'temp')
- with save_pkg_resources_state():
- with save_modules():
- hide_setuptools()
- with save_path():
- with save_argv():
- with override_temp(temp_dir):
- with pushd(setup_dir):
- # ensure setuptools commands are available
- __import__('setuptools')
- yield
-
-
-def _needs_hiding(mod_name):
- """
- >>> _needs_hiding('setuptools')
- True
- >>> _needs_hiding('pkg_resources')
- True
- >>> _needs_hiding('setuptools_plugin')
- False
- >>> _needs_hiding('setuptools.__init__')
- True
- >>> _needs_hiding('distutils')
- True
- >>> _needs_hiding('os')
- False
- >>> _needs_hiding('Cython')
- True
- """
+
+ saved = tempfile.tempdir
+
+ tempfile.tempdir = replacement
+
+ try:
+ yield
+ finally:
+ tempfile.tempdir = saved
+
+
+@contextlib.contextmanager
+def pushd(target):
+ saved = os.getcwd()
+ os.chdir(target)
+ try:
+ yield saved
+ finally:
+ os.chdir(saved)
+
+
+class UnpickleableException(Exception):
+ """
+ An exception representing another Exception that could not be pickled.
+ """
+
+ @staticmethod
+ def dump(type, exc):
+ """
+ Always return a dumped (pickled) type and exc. If exc can't be pickled,
+ wrap it in UnpickleableException first.
+ """
+ try:
+ return pickle.dumps(type), pickle.dumps(exc)
+ except Exception:
+ # get UnpickleableException inside the sandbox
+ from setuptools.sandbox import UnpickleableException as cls
+ return cls.dump(cls, cls(repr(exc)))
+
+
+class ExceptionSaver:
+ """
+ A Context Manager that will save an exception, serialized, and restore it
+ later.
+ """
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, exc, tb):
+ if not exc:
+ return
+
+ # dump the exception
+ self._saved = UnpickleableException.dump(type, exc)
+ self._tb = tb
+
+ # suppress the exception
+ return True
+
+ def resume(self):
+ "restore and re-raise any exception"
+
+ if '_saved' not in vars(self):
+ return
+
+ type, exc = map(pickle.loads, self._saved)
+ six.reraise(type, exc, self._tb)
+
+
+@contextlib.contextmanager
+def save_modules():
+ """
+ Context in which imported modules are saved.
+
+ Translates exceptions internal to the context into the equivalent exception
+ outside the context.
+ """
+ saved = sys.modules.copy()
+ with ExceptionSaver() as saved_exc:
+ yield saved
+
+ sys.modules.update(saved)
+ # remove any modules imported since
+ del_modules = (
+ mod_name for mod_name in sys.modules
+ if mod_name not in saved
+ # exclude any encodings modules. See #285
+ and not mod_name.startswith('encodings.')
+ )
+ _clear_modules(del_modules)
+
+ saved_exc.resume()
+
+
+def _clear_modules(module_names):
+ for mod_name in list(module_names):
+ del sys.modules[mod_name]
+
+
+@contextlib.contextmanager
+def save_pkg_resources_state():
+ saved = pkg_resources.__getstate__()
+ try:
+ yield saved
+ finally:
+ pkg_resources.__setstate__(saved)
+
+
+@contextlib.contextmanager
+def setup_context(setup_dir):
+ temp_dir = os.path.join(setup_dir, 'temp')
+ with save_pkg_resources_state():
+ with save_modules():
+ hide_setuptools()
+ with save_path():
+ with save_argv():
+ with override_temp(temp_dir):
+ with pushd(setup_dir):
+ # ensure setuptools commands are available
+ __import__('setuptools')
+ yield
+
+
+def _needs_hiding(mod_name):
+ """
+ >>> _needs_hiding('setuptools')
+ True
+ >>> _needs_hiding('pkg_resources')
+ True
+ >>> _needs_hiding('setuptools_plugin')
+ False
+ >>> _needs_hiding('setuptools.__init__')
+ True
+ >>> _needs_hiding('distutils')
+ True
+ >>> _needs_hiding('os')
+ False
+ >>> _needs_hiding('Cython')
+ True
+ """
pattern = re.compile(r'(setuptools|pkg_resources|distutils|Cython)(\.|$)')
- return bool(pattern.match(mod_name))
-
-
-def hide_setuptools():
- """
- Remove references to setuptools' modules from sys.modules to allow the
- invocation to import the most appropriate setuptools. This technique is
- necessary to avoid issues such as #315 where setuptools upgrading itself
- would fail to find a function declared in the metadata.
- """
- modules = filter(_needs_hiding, sys.modules)
- _clear_modules(modules)
-
-
-def run_setup(setup_script, args):
- """Run a distutils setup script, sandboxed in its directory"""
- setup_dir = os.path.abspath(os.path.dirname(setup_script))
- with setup_context(setup_dir):
- try:
+ return bool(pattern.match(mod_name))
+
+
+def hide_setuptools():
+ """
+ Remove references to setuptools' modules from sys.modules to allow the
+ invocation to import the most appropriate setuptools. This technique is
+ necessary to avoid issues such as #315 where setuptools upgrading itself
+ would fail to find a function declared in the metadata.
+ """
+ modules = filter(_needs_hiding, sys.modules)
+ _clear_modules(modules)
+
+
+def run_setup(setup_script, args):
+ """Run a distutils setup script, sandboxed in its directory"""
+ setup_dir = os.path.abspath(os.path.dirname(setup_script))
+ with setup_context(setup_dir):
+ try:
sys.argv[:] = [setup_script] + list(args)
- sys.path.insert(0, setup_dir)
- # reset to include setup dir, w/clean callback list
- working_set.__init__()
+ sys.path.insert(0, setup_dir)
+ # reset to include setup dir, w/clean callback list
+ working_set.__init__()
working_set.callbacks.append(lambda dist: dist.activate())
# __file__ should be a byte string on Python 2 (#712)
@@ -247,28 +247,28 @@ def run_setup(setup_script, args):
with DirectorySandbox(setup_dir):
ns = dict(__file__=dunder_file, __name__='__main__')
- _execfile(setup_script, ns)
- except SystemExit as v:
- if v.args and v.args[0]:
- raise
- # Normal exit, just return
-
-
-class AbstractSandbox:
- """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts"""
-
- _active = False
-
- def __init__(self):
- self._attrs = [
- name for name in dir(_os)
+ _execfile(setup_script, ns)
+ except SystemExit as v:
+ if v.args and v.args[0]:
+ raise
+ # Normal exit, just return
+
+
+class AbstractSandbox:
+ """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts"""
+
+ _active = False
+
+ def __init__(self):
+ self._attrs = [
+ name for name in dir(_os)
if not name.startswith('_') and hasattr(self, name)
- ]
-
- def _copy(self, source):
- for name in self._attrs:
+ ]
+
+ def _copy(self, source):
+ for name in self._attrs:
setattr(os, name, getattr(source, name))
-
+
def __enter__(self):
self._copy(self)
if _file:
@@ -283,209 +283,209 @@ class AbstractSandbox:
builtins.open = _open
self._copy(_os)
- def run(self, func):
- """Run 'func' under os sandboxing"""
+ def run(self, func):
+ """Run 'func' under os sandboxing"""
with self:
- return func()
-
- def _mk_dual_path_wrapper(name):
+ return func()
+
+ def _mk_dual_path_wrapper(name):
original = getattr(_os, name)
def wrap(self, src, dst, *args, **kw):
- if self._active:
+ if self._active:
src, dst = self._remap_pair(name, src, dst, *args, **kw)
return original(src, dst, *args, **kw)
- return wrap
-
- for name in ["rename", "link", "symlink"]:
+ return wrap
+
+ for name in ["rename", "link", "symlink"]:
if hasattr(_os, name):
locals()[name] = _mk_dual_path_wrapper(name)
-
- def _mk_single_path_wrapper(name, original=None):
+
+ def _mk_single_path_wrapper(name, original=None):
original = original or getattr(_os, name)
def wrap(self, path, *args, **kw):
- if self._active:
+ if self._active:
path = self._remap_input(name, path, *args, **kw)
return original(path, *args, **kw)
- return wrap
-
- if _file:
- _file = _mk_single_path_wrapper('file', _file)
- _open = _mk_single_path_wrapper('open', _open)
- for name in [
- "stat", "listdir", "chdir", "open", "chmod", "chown", "mkdir",
- "remove", "unlink", "rmdir", "utime", "lchown", "chroot", "lstat",
- "startfile", "mkfifo", "mknod", "pathconf", "access"
- ]:
+ return wrap
+
+ if _file:
+ _file = _mk_single_path_wrapper('file', _file)
+ _open = _mk_single_path_wrapper('open', _open)
+ for name in [
+ "stat", "listdir", "chdir", "open", "chmod", "chown", "mkdir",
+ "remove", "unlink", "rmdir", "utime", "lchown", "chroot", "lstat",
+ "startfile", "mkfifo", "mknod", "pathconf", "access"
+ ]:
if hasattr(_os, name):
locals()[name] = _mk_single_path_wrapper(name)
-
- def _mk_single_with_return(name):
+
+ def _mk_single_with_return(name):
original = getattr(_os, name)
def wrap(self, path, *args, **kw):
- if self._active:
+ if self._active:
path = self._remap_input(name, path, *args, **kw)
return self._remap_output(name, original(path, *args, **kw))
return original(path, *args, **kw)
- return wrap
-
- for name in ['readlink', 'tempnam']:
+ return wrap
+
+ for name in ['readlink', 'tempnam']:
if hasattr(_os, name):
locals()[name] = _mk_single_with_return(name)
-
- def _mk_query(name):
+
+ def _mk_query(name):
original = getattr(_os, name)
def wrap(self, *args, **kw):
retval = original(*args, **kw)
- if self._active:
- return self._remap_output(name, retval)
- return retval
+ if self._active:
+ return self._remap_output(name, retval)
+ return retval
- return wrap
-
- for name in ['getcwd', 'tmpnam']:
+ return wrap
+
+ for name in ['getcwd', 'tmpnam']:
if hasattr(_os, name):
locals()[name] = _mk_query(name)
-
+
def _validate_path(self, path):
- """Called to remap or validate any path, whether input or output"""
- return path
-
+ """Called to remap or validate any path, whether input or output"""
+ return path
+
def _remap_input(self, operation, path, *args, **kw):
- """Called for path inputs"""
- return self._validate_path(path)
-
+ """Called for path inputs"""
+ return self._validate_path(path)
+
def _remap_output(self, operation, path):
- """Called for path outputs"""
- return self._validate_path(path)
-
+ """Called for path outputs"""
+ return self._validate_path(path)
+
def _remap_pair(self, operation, src, dst, *args, **kw):
- """Called for path pairs like rename, link, and symlink operations"""
- return (
+ """Called for path pairs like rename, link, and symlink operations"""
+ return (
self._remap_input(operation + '-from', src, *args, **kw),
self._remap_input(operation + '-to', dst, *args, **kw)
- )
-
-
-if hasattr(os, 'devnull'):
- _EXCEPTIONS = [os.devnull,]
-else:
- _EXCEPTIONS = []
-
-
-class DirectorySandbox(AbstractSandbox):
- """Restrict operations to a single subdirectory - pseudo-chroot"""
-
- write_ops = dict.fromkeys([
- "open", "chmod", "chown", "mkdir", "remove", "unlink", "rmdir",
- "utime", "lchown", "chroot", "mkfifo", "mknod", "tempnam",
- ])
-
- _exception_patterns = [
- # Allow lib2to3 to attempt to save a pickled grammar object (#121)
+ )
+
+
+if hasattr(os, 'devnull'):
+ _EXCEPTIONS = [os.devnull,]
+else:
+ _EXCEPTIONS = []
+
+
+class DirectorySandbox(AbstractSandbox):
+ """Restrict operations to a single subdirectory - pseudo-chroot"""
+
+ write_ops = dict.fromkeys([
+ "open", "chmod", "chown", "mkdir", "remove", "unlink", "rmdir",
+ "utime", "lchown", "chroot", "mkfifo", "mknod", "tempnam",
+ ])
+
+ _exception_patterns = [
+ # Allow lib2to3 to attempt to save a pickled grammar object (#121)
r'.*lib2to3.*\.pickle$',
- ]
- "exempt writing to paths that match the pattern"
-
- def __init__(self, sandbox, exceptions=_EXCEPTIONS):
- self._sandbox = os.path.normcase(os.path.realpath(sandbox))
+ ]
+ "exempt writing to paths that match the pattern"
+
+ def __init__(self, sandbox, exceptions=_EXCEPTIONS):
+ self._sandbox = os.path.normcase(os.path.realpath(sandbox))
self._prefix = os.path.join(self._sandbox, '')
- self._exceptions = [
- os.path.normcase(os.path.realpath(path))
- for path in exceptions
- ]
- AbstractSandbox.__init__(self)
-
- def _violation(self, operation, *args, **kw):
- from setuptools.sandbox import SandboxViolation
- raise SandboxViolation(operation, args, kw)
-
- if _file:
-
- def _file(self, path, mode='r', *args, **kw):
- if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
- self._violation("file", path, mode, *args, **kw)
+ self._exceptions = [
+ os.path.normcase(os.path.realpath(path))
+ for path in exceptions
+ ]
+ AbstractSandbox.__init__(self)
+
+ def _violation(self, operation, *args, **kw):
+ from setuptools.sandbox import SandboxViolation
+ raise SandboxViolation(operation, args, kw)
+
+ if _file:
+
+ def _file(self, path, mode='r', *args, **kw):
+ if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
+ self._violation("file", path, mode, *args, **kw)
return _file(path, mode, *args, **kw)
-
- def _open(self, path, mode='r', *args, **kw):
- if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
- self._violation("open", path, mode, *args, **kw)
+
+ def _open(self, path, mode='r', *args, **kw):
+ if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
+ self._violation("open", path, mode, *args, **kw)
return _open(path, mode, *args, **kw)
-
- def tmpnam(self):
- self._violation("tmpnam")
-
- def _ok(self, path):
- active = self._active
- try:
- self._active = False
- realpath = os.path.normcase(os.path.realpath(path))
- return (
- self._exempted(realpath)
- or realpath == self._sandbox
- or realpath.startswith(self._prefix)
- )
- finally:
- self._active = active
-
- def _exempted(self, filepath):
- start_matches = (
- filepath.startswith(exception)
- for exception in self._exceptions
- )
- pattern_matches = (
- re.match(pattern, filepath)
- for pattern in self._exception_patterns
- )
- candidates = itertools.chain(start_matches, pattern_matches)
- return any(candidates)
-
- def _remap_input(self, operation, path, *args, **kw):
- """Called for path inputs"""
- if operation in self.write_ops and not self._ok(path):
- self._violation(operation, os.path.realpath(path), *args, **kw)
- return path
-
- def _remap_pair(self, operation, src, dst, *args, **kw):
- """Called for path pairs like rename, link, and symlink operations"""
- if not self._ok(src) or not self._ok(dst):
- self._violation(operation, src, dst, *args, **kw)
+
+ def tmpnam(self):
+ self._violation("tmpnam")
+
+ def _ok(self, path):
+ active = self._active
+ try:
+ self._active = False
+ realpath = os.path.normcase(os.path.realpath(path))
+ return (
+ self._exempted(realpath)
+ or realpath == self._sandbox
+ or realpath.startswith(self._prefix)
+ )
+ finally:
+ self._active = active
+
+ def _exempted(self, filepath):
+ start_matches = (
+ filepath.startswith(exception)
+ for exception in self._exceptions
+ )
+ pattern_matches = (
+ re.match(pattern, filepath)
+ for pattern in self._exception_patterns
+ )
+ candidates = itertools.chain(start_matches, pattern_matches)
+ return any(candidates)
+
+ def _remap_input(self, operation, path, *args, **kw):
+ """Called for path inputs"""
+ if operation in self.write_ops and not self._ok(path):
+ self._violation(operation, os.path.realpath(path), *args, **kw)
+ return path
+
+ def _remap_pair(self, operation, src, dst, *args, **kw):
+ """Called for path pairs like rename, link, and symlink operations"""
+ if not self._ok(src) or not self._ok(dst):
+ self._violation(operation, src, dst, *args, **kw)
return (src, dst)
-
- def open(self, file, flags, mode=0o777, *args, **kw):
- """Called for low-level os.open()"""
- if flags & WRITE_FLAGS and not self._ok(file):
- self._violation("os.open", file, flags, mode, *args, **kw)
+
+ def open(self, file, flags, mode=0o777, *args, **kw):
+ """Called for low-level os.open()"""
+ if flags & WRITE_FLAGS and not self._ok(file):
+ self._violation("os.open", file, flags, mode, *args, **kw)
return _os.open(file, flags, mode, *args, **kw)
-
-WRITE_FLAGS = functools.reduce(
- operator.or_, [getattr(_os, a, 0) for a in
- "O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split()]
-)
-
-class SandboxViolation(DistutilsError):
- """A setup script attempted to modify the filesystem outside the sandbox"""
-
+WRITE_FLAGS = functools.reduce(
+ operator.or_, [getattr(_os, a, 0) for a in
+ "O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split()]
+)
+
+
+class SandboxViolation(DistutilsError):
+ """A setup script attempted to modify the filesystem outside the sandbox"""
+
tmpl = textwrap.dedent("""
SandboxViolation: {cmd}{args!r} {kwargs}
-
+
The package setup script has attempted to modify files on your system
that are not within the EasyInstall build area, and has been aborted.
-
+
This package cannot be safely installed by EasyInstall, and may not
support alternate installation locations even if you run its setup
script by hand. Please inform the package's author and the EasyInstall
maintainers to find out if a fix or workaround is available.
""").lstrip()
-
+
def __str__(self):
cmd, args, kwargs = self.args
return self.tmpl.format(**locals())
diff --git a/contrib/python/setuptools/py2/setuptools/script.tmpl b/contrib/python/setuptools/py2/setuptools/script.tmpl
index df8f68d6b4..ff5efbcab3 100644
--- a/contrib/python/setuptools/py2/setuptools/script.tmpl
+++ b/contrib/python/setuptools/py2/setuptools/script.tmpl
@@ -1,3 +1,3 @@
-# EASY-INSTALL-SCRIPT: %(spec)r,%(script_name)r
-__requires__ = %(spec)r
-__import__('pkg_resources').run_script(%(spec)r, %(script_name)r)
+# EASY-INSTALL-SCRIPT: %(spec)r,%(script_name)r
+__requires__ = %(spec)r
+__import__('pkg_resources').run_script(%(spec)r, %(script_name)r)
diff --git a/contrib/python/setuptools/py2/setuptools/site-patch.py b/contrib/python/setuptools/py2/setuptools/site-patch.py
index 16e75879fd..40b00de0a7 100644
--- a/contrib/python/setuptools/py2/setuptools/site-patch.py
+++ b/contrib/python/setuptools/py2/setuptools/site-patch.py
@@ -1,74 +1,74 @@
-def __boot():
- import sys
- import os
- PYTHONPATH = os.environ.get('PYTHONPATH')
+def __boot():
+ import sys
+ import os
+ PYTHONPATH = os.environ.get('PYTHONPATH')
if PYTHONPATH is None or (sys.platform == 'win32' and not PYTHONPATH):
- PYTHONPATH = []
- else:
- PYTHONPATH = PYTHONPATH.split(os.pathsep)
-
+ PYTHONPATH = []
+ else:
+ PYTHONPATH = PYTHONPATH.split(os.pathsep)
+
pic = getattr(sys, 'path_importer_cache', {})
- stdpath = sys.path[len(PYTHONPATH):]
- mydir = os.path.dirname(__file__)
-
- for item in stdpath:
+ stdpath = sys.path[len(PYTHONPATH):]
+ mydir = os.path.dirname(__file__)
+
+ for item in stdpath:
if item == mydir or not item:
continue # skip if current dir. on Windows, or my own directory
- importer = pic.get(item)
- if importer is not None:
- loader = importer.find_module('site')
- if loader is not None:
- # This should actually reload the current module
- loader.load_module('site')
- break
- else:
- try:
+ importer = pic.get(item)
+ if importer is not None:
+ loader = importer.find_module('site')
+ if loader is not None:
+ # This should actually reload the current module
+ loader.load_module('site')
+ break
+ else:
+ try:
import imp # Avoid import loop in Python 3
stream, path, descr = imp.find_module('site', [item])
- except ImportError:
- continue
- if stream is None:
- continue
- try:
- # This should actually reload the current module
+ except ImportError:
+ continue
+ if stream is None:
+ continue
+ try:
+ # This should actually reload the current module
imp.load_module('site', stream, path, descr)
- finally:
- stream.close()
- break
- else:
- raise ImportError("Couldn't find the real 'site' module")
-
+ finally:
+ stream.close()
+ break
+ else:
+ raise ImportError("Couldn't find the real 'site' module")
+
known_paths = dict([(makepath(item)[1], 1) for item in sys.path]) # 2.2 comp
-
+
oldpos = getattr(sys, '__egginsert', 0) # save old insertion position
sys.__egginsert = 0 # and reset the current one
-
- for item in PYTHONPATH:
- addsitedir(item)
-
+
+ for item in PYTHONPATH:
+ addsitedir(item)
+
sys.__egginsert += oldpos # restore effective old position
-
- d, nd = makepath(stdpath[0])
- insert_at = None
- new_path = []
-
- for item in sys.path:
- p, np = makepath(item)
-
+
+ d, nd = makepath(stdpath[0])
+ insert_at = None
+ new_path = []
+
+ for item in sys.path:
+ p, np = makepath(item)
+
if np == nd and insert_at is None:
- # We've hit the first 'system' path entry, so added entries go here
- insert_at = len(new_path)
-
- if np in known_paths or insert_at is None:
- new_path.append(item)
- else:
- # new path after the insert point, back-insert it
- new_path.insert(insert_at, item)
- insert_at += 1
-
- sys.path[:] = new_path
-
+ # We've hit the first 'system' path entry, so added entries go here
+ insert_at = len(new_path)
+
+ if np in known_paths or insert_at is None:
+ new_path.append(item)
+ else:
+ # new path after the insert point, back-insert it
+ new_path.insert(insert_at, item)
+ insert_at += 1
+
+ sys.path[:] = new_path
+
if __name__ == 'site':
- __boot()
- del __boot
+ __boot()
+ del __boot
diff --git a/contrib/python/setuptools/py2/setuptools/ssl_support.py b/contrib/python/setuptools/py2/setuptools/ssl_support.py
index 7f5aa7f577..226db694bb 100644
--- a/contrib/python/setuptools/py2/setuptools/ssl_support.py
+++ b/contrib/python/setuptools/py2/setuptools/ssl_support.py
@@ -1,191 +1,191 @@
-import os
-import socket
-import atexit
-import re
+import os
+import socket
+import atexit
+import re
import functools
-
+
from setuptools.extern.six.moves import urllib, http_client, map, filter
-
-from pkg_resources import ResolutionError, ExtractionError
-
-try:
- import ssl
-except ImportError:
- ssl = None
-
-__all__ = [
- 'VerifyingHTTPSHandler', 'find_ca_bundle', 'is_available', 'cert_paths',
- 'opener_for'
-]
-
-cert_paths = """
-/etc/pki/tls/certs/ca-bundle.crt
-/etc/ssl/certs/ca-certificates.crt
-/usr/share/ssl/certs/ca-bundle.crt
-/usr/local/share/certs/ca-root.crt
-/etc/ssl/cert.pem
-/System/Library/OpenSSL/certs/cert.pem
-/usr/local/share/certs/ca-root-nss.crt
+
+from pkg_resources import ResolutionError, ExtractionError
+
+try:
+ import ssl
+except ImportError:
+ ssl = None
+
+__all__ = [
+ 'VerifyingHTTPSHandler', 'find_ca_bundle', 'is_available', 'cert_paths',
+ 'opener_for'
+]
+
+cert_paths = """
+/etc/pki/tls/certs/ca-bundle.crt
+/etc/ssl/certs/ca-certificates.crt
+/usr/share/ssl/certs/ca-bundle.crt
+/usr/local/share/certs/ca-root.crt
+/etc/ssl/cert.pem
+/System/Library/OpenSSL/certs/cert.pem
+/usr/local/share/certs/ca-root-nss.crt
/etc/ssl/ca-bundle.pem
-""".strip().split()
-
-try:
- HTTPSHandler = urllib.request.HTTPSHandler
- HTTPSConnection = http_client.HTTPSConnection
-except AttributeError:
- HTTPSHandler = HTTPSConnection = object
-
-is_available = ssl is not None and object not in (HTTPSHandler, HTTPSConnection)
-
-
-try:
- from ssl import CertificateError, match_hostname
-except ImportError:
- try:
- from backports.ssl_match_hostname import CertificateError
- from backports.ssl_match_hostname import match_hostname
- except ImportError:
- CertificateError = None
- match_hostname = None
-
-if not CertificateError:
-
- class CertificateError(ValueError):
- pass
-
-
-if not match_hostname:
-
- def _dnsname_match(dn, hostname, max_wildcards=1):
- """Matching according to RFC 6125, section 6.4.3
-
+""".strip().split()
+
+try:
+ HTTPSHandler = urllib.request.HTTPSHandler
+ HTTPSConnection = http_client.HTTPSConnection
+except AttributeError:
+ HTTPSHandler = HTTPSConnection = object
+
+is_available = ssl is not None and object not in (HTTPSHandler, HTTPSConnection)
+
+
+try:
+ from ssl import CertificateError, match_hostname
+except ImportError:
+ try:
+ from backports.ssl_match_hostname import CertificateError
+ from backports.ssl_match_hostname import match_hostname
+ except ImportError:
+ CertificateError = None
+ match_hostname = None
+
+if not CertificateError:
+
+ class CertificateError(ValueError):
+ pass
+
+
+if not match_hostname:
+
+ def _dnsname_match(dn, hostname, max_wildcards=1):
+ """Matching according to RFC 6125, section 6.4.3
+
https://tools.ietf.org/html/rfc6125#section-6.4.3
- """
- pats = []
- if not dn:
- return False
-
- # Ported from python3-syntax:
- # leftmost, *remainder = dn.split(r'.')
- parts = dn.split(r'.')
- leftmost = parts[0]
- remainder = parts[1:]
-
- wildcards = leftmost.count('*')
- if wildcards > max_wildcards:
- # Issue #17980: avoid denials of service by refusing more
- # than one wildcard per fragment. A survey of established
- # policy among SSL implementations showed it to be a
- # reasonable choice.
- raise CertificateError(
- "too many wildcards in certificate DNS name: " + repr(dn))
-
- # speed up common case w/o wildcards
- if not wildcards:
- return dn.lower() == hostname.lower()
-
- # RFC 6125, section 6.4.3, subitem 1.
- # The client SHOULD NOT attempt to match a presented identifier in which
- # the wildcard character comprises a label other than the left-most label.
- if leftmost == '*':
- # When '*' is a fragment by itself, it matches a non-empty dotless
- # fragment.
- pats.append('[^.]+')
- elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
- # RFC 6125, section 6.4.3, subitem 3.
- # The client SHOULD NOT attempt to match a presented identifier
- # where the wildcard character is embedded within an A-label or
- # U-label of an internationalized domain name.
- pats.append(re.escape(leftmost))
- else:
- # Otherwise, '*' matches any dotless string, e.g. www*
- pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
-
- # add the remaining fragments, ignore any wildcards
- for frag in remainder:
- pats.append(re.escape(frag))
-
- pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
- return pat.match(hostname)
-
- def match_hostname(cert, hostname):
- """Verify that *cert* (in decoded format as returned by
- SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
- rules are followed, but IP addresses are not accepted for *hostname*.
-
- CertificateError is raised on failure. On success, the function
- returns nothing.
- """
- if not cert:
- raise ValueError("empty or no certificate")
- dnsnames = []
- san = cert.get('subjectAltName', ())
- for key, value in san:
- if key == 'DNS':
- if _dnsname_match(value, hostname):
- return
- dnsnames.append(value)
- if not dnsnames:
- # The subject is only checked when there is no dNSName entry
- # in subjectAltName
- for sub in cert.get('subject', ()):
- for key, value in sub:
- # XXX according to RFC 2818, the most specific Common Name
- # must be used.
- if key == 'commonName':
- if _dnsname_match(value, hostname):
- return
- dnsnames.append(value)
- if len(dnsnames) > 1:
- raise CertificateError("hostname %r "
- "doesn't match either of %s"
- % (hostname, ', '.join(map(repr, dnsnames))))
- elif len(dnsnames) == 1:
- raise CertificateError("hostname %r "
- "doesn't match %r"
- % (hostname, dnsnames[0]))
- else:
- raise CertificateError("no appropriate commonName or "
- "subjectAltName fields were found")
-
-
-class VerifyingHTTPSHandler(HTTPSHandler):
- """Simple verifying handler: no auth, subclasses, timeouts, etc."""
-
- def __init__(self, ca_bundle):
- self.ca_bundle = ca_bundle
- HTTPSHandler.__init__(self)
-
- def https_open(self, req):
- return self.do_open(
- lambda host, **kw: VerifyingHTTPSConn(host, self.ca_bundle, **kw), req
- )
-
-
-class VerifyingHTTPSConn(HTTPSConnection):
- """Simple verifying connection: no auth, subclasses, timeouts, etc."""
-
- def __init__(self, host, ca_bundle, **kw):
- HTTPSConnection.__init__(self, host, **kw)
- self.ca_bundle = ca_bundle
-
- def connect(self):
- sock = socket.create_connection(
- (self.host, self.port), getattr(self, 'source_address', None)
- )
-
- # Handle the socket if a (proxy) tunnel is present
- if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
- self.sock = sock
- self._tunnel()
- # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7
- # change self.host to mean the proxy server host when tunneling is
- # being used. Adapt, since we are interested in the destination
- # host for the match_hostname() comparison.
- actual_host = self._tunnel_host
- else:
- actual_host = self.host
-
+ """
+ pats = []
+ if not dn:
+ return False
+
+ # Ported from python3-syntax:
+ # leftmost, *remainder = dn.split(r'.')
+ parts = dn.split(r'.')
+ leftmost = parts[0]
+ remainder = parts[1:]
+
+ wildcards = leftmost.count('*')
+ if wildcards > max_wildcards:
+ # Issue #17980: avoid denials of service by refusing more
+ # than one wildcard per fragment. A survey of established
+ # policy among SSL implementations showed it to be a
+ # reasonable choice.
+ raise CertificateError(
+ "too many wildcards in certificate DNS name: " + repr(dn))
+
+ # speed up common case w/o wildcards
+ if not wildcards:
+ return dn.lower() == hostname.lower()
+
+ # RFC 6125, section 6.4.3, subitem 1.
+ # The client SHOULD NOT attempt to match a presented identifier in which
+ # the wildcard character comprises a label other than the left-most label.
+ if leftmost == '*':
+ # When '*' is a fragment by itself, it matches a non-empty dotless
+ # fragment.
+ pats.append('[^.]+')
+ elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
+ # RFC 6125, section 6.4.3, subitem 3.
+ # The client SHOULD NOT attempt to match a presented identifier
+ # where the wildcard character is embedded within an A-label or
+ # U-label of an internationalized domain name.
+ pats.append(re.escape(leftmost))
+ else:
+ # Otherwise, '*' matches any dotless string, e.g. www*
+ pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
+
+ # add the remaining fragments, ignore any wildcards
+ for frag in remainder:
+ pats.append(re.escape(frag))
+
+ pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
+ return pat.match(hostname)
+
+ def match_hostname(cert, hostname):
+ """Verify that *cert* (in decoded format as returned by
+ SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
+ rules are followed, but IP addresses are not accepted for *hostname*.
+
+ CertificateError is raised on failure. On success, the function
+ returns nothing.
+ """
+ if not cert:
+ raise ValueError("empty or no certificate")
+ dnsnames = []
+ san = cert.get('subjectAltName', ())
+ for key, value in san:
+ if key == 'DNS':
+ if _dnsname_match(value, hostname):
+ return
+ dnsnames.append(value)
+ if not dnsnames:
+ # The subject is only checked when there is no dNSName entry
+ # in subjectAltName
+ for sub in cert.get('subject', ()):
+ for key, value in sub:
+ # XXX according to RFC 2818, the most specific Common Name
+ # must be used.
+ if key == 'commonName':
+ if _dnsname_match(value, hostname):
+ return
+ dnsnames.append(value)
+ if len(dnsnames) > 1:
+ raise CertificateError("hostname %r "
+ "doesn't match either of %s"
+ % (hostname, ', '.join(map(repr, dnsnames))))
+ elif len(dnsnames) == 1:
+ raise CertificateError("hostname %r "
+ "doesn't match %r"
+ % (hostname, dnsnames[0]))
+ else:
+ raise CertificateError("no appropriate commonName or "
+ "subjectAltName fields were found")
+
+
+class VerifyingHTTPSHandler(HTTPSHandler):
+ """Simple verifying handler: no auth, subclasses, timeouts, etc."""
+
+ def __init__(self, ca_bundle):
+ self.ca_bundle = ca_bundle
+ HTTPSHandler.__init__(self)
+
+ def https_open(self, req):
+ return self.do_open(
+ lambda host, **kw: VerifyingHTTPSConn(host, self.ca_bundle, **kw), req
+ )
+
+
+class VerifyingHTTPSConn(HTTPSConnection):
+ """Simple verifying connection: no auth, subclasses, timeouts, etc."""
+
+ def __init__(self, host, ca_bundle, **kw):
+ HTTPSConnection.__init__(self, host, **kw)
+ self.ca_bundle = ca_bundle
+
+ def connect(self):
+ sock = socket.create_connection(
+ (self.host, self.port), getattr(self, 'source_address', None)
+ )
+
+ # Handle the socket if a (proxy) tunnel is present
+ if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
+ self.sock = sock
+ self._tunnel()
+ # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7
+ # change self.host to mean the proxy server host when tunneling is
+ # being used. Adapt, since we are interested in the destination
+ # host for the match_hostname() comparison.
+ actual_host = self._tunnel_host
+ else:
+ actual_host = self.host
+
if hasattr(ssl, 'create_default_context'):
ctx = ssl.create_default_context(cafile=self.ca_bundle)
self.sock = ctx.wrap_socket(sock, server_hostname=actual_host)
@@ -194,21 +194,21 @@ class VerifyingHTTPSConn(HTTPSConnection):
self.sock = ssl.wrap_socket(
sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
)
- try:
- match_hostname(self.sock.getpeercert(), actual_host)
- except CertificateError:
- self.sock.shutdown(socket.SHUT_RDWR)
- self.sock.close()
- raise
-
-
-def opener_for(ca_bundle=None):
- """Get a urlopen() replacement that uses ca_bundle for verification"""
- return urllib.request.build_opener(
- VerifyingHTTPSHandler(ca_bundle or find_ca_bundle())
- ).open
-
-
+ try:
+ match_hostname(self.sock.getpeercert(), actual_host)
+ except CertificateError:
+ self.sock.shutdown(socket.SHUT_RDWR)
+ self.sock.close()
+ raise
+
+
+def opener_for(ca_bundle=None):
+ """Get a urlopen() replacement that uses ca_bundle for verification"""
+ return urllib.request.build_opener(
+ VerifyingHTTPSHandler(ca_bundle or find_ca_bundle())
+ ).open
+
+
# from jaraco.functools
def once(func):
@functools.wraps(func)
@@ -217,34 +217,34 @@ def once(func):
func.always_returns = func(*args, **kwargs)
return func.always_returns
return wrapper
-
+
@once
-def get_win_certfile():
- try:
+def get_win_certfile():
+ try:
import wincertstore
- except ImportError:
- return None
-
+ except ImportError:
+ return None
+
class CertFile(wincertstore.CertFile):
def __init__(self):
super(CertFile, self).__init__()
- atexit.register(self.close)
-
- def close(self):
- try:
+ atexit.register(self.close)
+
+ def close(self):
+ try:
super(CertFile, self).close()
- except OSError:
- pass
-
+ except OSError:
+ pass
+
_wincerts = CertFile()
_wincerts.addstore('CA')
_wincerts.addstore('ROOT')
- return _wincerts.name
-
-
-def find_ca_bundle():
- """Return an existing CA bundle path, or None"""
+ return _wincerts.name
+
+
+def find_ca_bundle():
+ """Return an existing CA bundle path, or None"""
extant_cert_paths = filter(os.path.isfile, cert_paths)
return (
get_win_certfile()
@@ -254,7 +254,7 @@ def find_ca_bundle():
def _certifi_where():
- try:
+ try:
return __import__('certifi').where()
- except (ImportError, ResolutionError, ExtractionError):
+ except (ImportError, ResolutionError, ExtractionError):
pass
diff --git a/contrib/python/setuptools/py2/setuptools/unicode_utils.py b/contrib/python/setuptools/py2/setuptools/unicode_utils.py
index 9128c79f74..7c63efd20b 100644
--- a/contrib/python/setuptools/py2/setuptools/unicode_utils.py
+++ b/contrib/python/setuptools/py2/setuptools/unicode_utils.py
@@ -1,44 +1,44 @@
-import unicodedata
-import sys
-
+import unicodedata
+import sys
+
from setuptools.extern import six
-
-
-# HFS Plus uses decomposed UTF-8
-def decompose(path):
- if isinstance(path, six.text_type):
- return unicodedata.normalize('NFD', path)
- try:
- path = path.decode('utf-8')
- path = unicodedata.normalize('NFD', path)
- path = path.encode('utf-8')
- except UnicodeError:
- pass # Not UTF-8
- return path
-
-
-def filesys_decode(path):
- """
- Ensure that the given path is decoded,
- NONE when no expected encoding works
- """
-
- if isinstance(path, six.text_type):
- return path
-
- fs_enc = sys.getfilesystemencoding() or 'utf-8'
- candidates = fs_enc, 'utf-8'
-
- for enc in candidates:
- try:
- return path.decode(enc)
- except UnicodeDecodeError:
- continue
-
-
-def try_encode(string, enc):
- "turn unicode encoding into a functional routine"
- try:
- return string.encode(enc)
- except UnicodeEncodeError:
- return None
+
+
+# HFS Plus uses decomposed UTF-8
+def decompose(path):
+ if isinstance(path, six.text_type):
+ return unicodedata.normalize('NFD', path)
+ try:
+ path = path.decode('utf-8')
+ path = unicodedata.normalize('NFD', path)
+ path = path.encode('utf-8')
+ except UnicodeError:
+ pass # Not UTF-8
+ return path
+
+
+def filesys_decode(path):
+ """
+ Ensure that the given path is decoded,
+ NONE when no expected encoding works
+ """
+
+ if isinstance(path, six.text_type):
+ return path
+
+ fs_enc = sys.getfilesystemencoding() or 'utf-8'
+ candidates = fs_enc, 'utf-8'
+
+ for enc in candidates:
+ try:
+ return path.decode(enc)
+ except UnicodeDecodeError:
+ continue
+
+
+def try_encode(string, enc):
+ "turn unicode encoding into a functional routine"
+ try:
+ return string.encode(enc)
+ except UnicodeEncodeError:
+ return None
diff --git a/contrib/python/setuptools/py2/setuptools/windows_support.py b/contrib/python/setuptools/py2/setuptools/windows_support.py
index a4a389fede..cb977cff95 100644
--- a/contrib/python/setuptools/py2/setuptools/windows_support.py
+++ b/contrib/python/setuptools/py2/setuptools/windows_support.py
@@ -1,29 +1,29 @@
-import platform
-import ctypes
-
-
-def windows_only(func):
- if platform.system() != 'Windows':
- return lambda *args, **kwargs: None
- return func
-
-
-@windows_only
-def hide_file(path):
- """
- Set the hidden attribute on a file or directory.
-
- From http://stackoverflow.com/questions/19622133/
-
- `path` must be text.
- """
- __import__('ctypes.wintypes')
- SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
- SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
- SetFileAttributes.restype = ctypes.wintypes.BOOL
-
- FILE_ATTRIBUTE_HIDDEN = 0x02
-
- ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
- if not ret:
- raise ctypes.WinError()
+import platform
+import ctypes
+
+
+def windows_only(func):
+ if platform.system() != 'Windows':
+ return lambda *args, **kwargs: None
+ return func
+
+
+@windows_only
+def hide_file(path):
+ """
+ Set the hidden attribute on a file or directory.
+
+ From http://stackoverflow.com/questions/19622133/
+
+ `path` must be text.
+ """
+ __import__('ctypes.wintypes')
+ SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
+ SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
+ SetFileAttributes.restype = ctypes.wintypes.BOOL
+
+ FILE_ATTRIBUTE_HIDDEN = 0x02
+
+ ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
+ if not ret:
+ raise ctypes.WinError()
diff --git a/contrib/python/setuptools/py2/ya.make b/contrib/python/setuptools/py2/ya.make
index f096e3524e..4c36dcf1ab 100644
--- a/contrib/python/setuptools/py2/ya.make
+++ b/contrib/python/setuptools/py2/ya.make
@@ -1,9 +1,9 @@
PY2_LIBRARY()
-
+
LICENSE(MIT)
OWNER(g:python-contrib borman orivej)
-
+
VERSION(44.1.1)
PEERDIR(
@@ -16,10 +16,10 @@ NO_CHECK_IMPORTS(
NO_LINT()
-PY_SRCS(
- TOP_LEVEL
+PY_SRCS(
+ TOP_LEVEL
easy_install.py
- pkg_resources/__init__.py
+ pkg_resources/__init__.py
pkg_resources/_vendor/__init__.py
pkg_resources/_vendor/appdirs.py
pkg_resources/_vendor/packaging/__about__.py
@@ -35,7 +35,7 @@ PY_SRCS(
pkg_resources/_vendor/six.py
pkg_resources/extern/__init__.py
pkg_resources/py31compat.py
- setuptools/__init__.py
+ setuptools/__init__.py
setuptools/_deprecation_warning.py
setuptools/_imp.py
setuptools/_vendor/__init__.py
@@ -52,61 +52,61 @@ PY_SRCS(
setuptools/_vendor/packaging/version.py
setuptools/_vendor/pyparsing.py
setuptools/_vendor/six.py
- setuptools/archive_util.py
+ setuptools/archive_util.py
setuptools/build_meta.py
- setuptools/command/__init__.py
- setuptools/command/alias.py
- setuptools/command/bdist_egg.py
- setuptools/command/bdist_rpm.py
- setuptools/command/bdist_wininst.py
+ setuptools/command/__init__.py
+ setuptools/command/alias.py
+ setuptools/command/bdist_egg.py
+ setuptools/command/bdist_rpm.py
+ setuptools/command/bdist_wininst.py
setuptools/command/build_clib.py
- setuptools/command/build_ext.py
- setuptools/command/build_py.py
- setuptools/command/develop.py
+ setuptools/command/build_ext.py
+ setuptools/command/build_py.py
+ setuptools/command/develop.py
setuptools/command/dist_info.py
- setuptools/command/easy_install.py
- setuptools/command/egg_info.py
- setuptools/command/install.py
- setuptools/command/install_egg_info.py
- setuptools/command/install_lib.py
- setuptools/command/install_scripts.py
+ setuptools/command/easy_install.py
+ setuptools/command/egg_info.py
+ setuptools/command/install.py
+ setuptools/command/install_egg_info.py
+ setuptools/command/install_lib.py
+ setuptools/command/install_scripts.py
setuptools/command/py36compat.py
- setuptools/command/register.py
- setuptools/command/rotate.py
- setuptools/command/saveopts.py
- setuptools/command/sdist.py
- setuptools/command/setopt.py
- setuptools/command/test.py
+ setuptools/command/register.py
+ setuptools/command/rotate.py
+ setuptools/command/saveopts.py
+ setuptools/command/sdist.py
+ setuptools/command/setopt.py
+ setuptools/command/test.py
setuptools/command/upload.py
- setuptools/command/upload_docs.py
+ setuptools/command/upload_docs.py
setuptools/config.py
setuptools/dep_util.py
- setuptools/depends.py
- setuptools/dist.py
+ setuptools/depends.py
+ setuptools/dist.py
setuptools/errors.py
- setuptools/extension.py
+ setuptools/extension.py
setuptools/extern/__init__.py
setuptools/glob.py
setuptools/installer.py
- setuptools/launch.py
- setuptools/lib2to3_ex.py
+ setuptools/launch.py
+ setuptools/lib2to3_ex.py
setuptools/monkey.py
setuptools/msvc.py
setuptools/namespaces.py
- setuptools/package_index.py
- setuptools/py27compat.py
- setuptools/py31compat.py
+ setuptools/package_index.py
+ setuptools/py27compat.py
+ setuptools/py31compat.py
setuptools/py33compat.py
setuptools/py34compat.py
- setuptools/sandbox.py
- setuptools/site-patch.py
- setuptools/ssl_support.py
- setuptools/unicode_utils.py
- setuptools/version.py
+ setuptools/sandbox.py
+ setuptools/site-patch.py
+ setuptools/ssl_support.py
+ setuptools/unicode_utils.py
+ setuptools/version.py
setuptools/wheel.py
- setuptools/windows_support.py
-)
-
+ setuptools/windows_support.py
+)
+
RESOURCE_FILES(
PREFIX contrib/python/setuptools/py2/
.dist-info/METADATA
@@ -114,4 +114,4 @@ RESOURCE_FILES(
.dist-info/top_level.txt
)
-END()
+END()
diff --git a/contrib/python/setuptools/py3/pkg_resources/__init__.py b/contrib/python/setuptools/py3/pkg_resources/__init__.py
index b5959b688c..6b947a49a7 100644
--- a/contrib/python/setuptools/py3/pkg_resources/__init__.py
+++ b/contrib/python/setuptools/py3/pkg_resources/__init__.py
@@ -1,90 +1,90 @@
-"""
-Package resource API
---------------------
-
-A resource is a logical file contained within a package, or a logical
-subdirectory thereof. The package resource API expects resource names
-to have their path parts separated with ``/``, *not* whatever the local
-path separator is. Do not use os.path operations to manipulate resource
-names being passed into the API.
-
-The package resource API is designed to work with normal filesystem packages,
-.egg files, and unpacked .egg files. It can also work in a limited way with
-.zip files and with custom PEP 302 loaders that support the ``get_data()``
-method.
-"""
-
-import sys
-import os
-import io
-import time
-import re
-import types
-import zipfile
-import zipimport
-import warnings
-import stat
-import functools
-import pkgutil
-import operator
-import platform
-import collections
-import plistlib
-import email.parser
+"""
+Package resource API
+--------------------
+
+A resource is a logical file contained within a package, or a logical
+subdirectory thereof. The package resource API expects resource names
+to have their path parts separated with ``/``, *not* whatever the local
+path separator is. Do not use os.path operations to manipulate resource
+names being passed into the API.
+
+The package resource API is designed to work with normal filesystem packages,
+.egg files, and unpacked .egg files. It can also work in a limited way with
+.zip files and with custom PEP 302 loaders that support the ``get_data()``
+method.
+"""
+
+import sys
+import os
+import io
+import time
+import re
+import types
+import zipfile
+import zipimport
+import warnings
+import stat
+import functools
+import pkgutil
+import operator
+import platform
+import collections
+import plistlib
+import email.parser
import errno
-import tempfile
-import textwrap
+import tempfile
+import textwrap
import itertools
import inspect
import ntpath
import posixpath
import importlib
-from pkgutil import get_importer
-
-try:
- import _imp
-except ImportError:
- # Python 3.2 compatibility
- import imp as _imp
-
+from pkgutil import get_importer
+
+try:
+ import _imp
+except ImportError:
+ # Python 3.2 compatibility
+ import imp as _imp
+
try:
FileExistsError
except NameError:
FileExistsError = OSError
-
-# capture these to bypass sandboxing
-from os import utime
-try:
- from os import mkdir, rename, unlink
- WRITE_SUPPORT = True
-except ImportError:
- # no write support, probably under GAE
- WRITE_SUPPORT = False
-
-from os import open as os_open
-from os.path import isdir, split
-
-try:
- import importlib.machinery as importlib_machinery
- # access attribute to force import under delayed import mechanisms.
- importlib_machinery.__name__
-except ImportError:
- importlib_machinery = None
-
+
+# capture these to bypass sandboxing
+from os import utime
+try:
+ from os import mkdir, rename, unlink
+ WRITE_SUPPORT = True
+except ImportError:
+ # no write support, probably under GAE
+ WRITE_SUPPORT = False
+
+from os import open as os_open
+from os.path import isdir, split
+
+try:
+ import importlib.machinery as importlib_machinery
+ # access attribute to force import under delayed import mechanisms.
+ importlib_machinery.__name__
+except ImportError:
+ importlib_machinery = None
+
from pkg_resources.extern import appdirs
from pkg_resources.extern import packaging
__import__('pkg_resources.extern.packaging.version')
__import__('pkg_resources.extern.packaging.specifiers')
__import__('pkg_resources.extern.packaging.requirements')
__import__('pkg_resources.extern.packaging.markers')
-
+
if sys.version_info < (3, 5):
raise RuntimeError("Python 3.5 or later is required")
-# declare some globals that will be defined later to
-# satisfy the linters.
-require = None
-working_set = None
+# declare some globals that will be defined later to
+# satisfy the linters.
+require = None
+working_set = None
add_activation_listener = None
resources_stream = None
cleanup_resources = None
@@ -100,833 +100,833 @@ resource_exists = None
_distribution_finders = None
_namespace_handlers = None
_namespace_packages = None
-
-
-class PEP440Warning(RuntimeWarning):
- """
- Used when there is an issue with a version or specifier not complying with
- PEP 440.
- """
-
-
-def parse_version(v):
- try:
+
+
+class PEP440Warning(RuntimeWarning):
+ """
+ Used when there is an issue with a version or specifier not complying with
+ PEP 440.
+ """
+
+
+def parse_version(v):
+ try:
return packaging.version.Version(v)
- except packaging.version.InvalidVersion:
+ except packaging.version.InvalidVersion:
warnings.warn(
f"{v} is an invalid version and will not be supported in "
"a future release",
PkgResourcesDeprecationWarning,
)
return packaging.version.LegacyVersion(v)
-
-
-_state_vars = {}
-
-
-def _declare_state(vartype, **kw):
- globals().update(kw)
- _state_vars.update(dict.fromkeys(kw, vartype))
-
-
-def __getstate__():
- state = {}
- g = globals()
- for k, v in _state_vars.items():
+
+
+_state_vars = {}
+
+
+def _declare_state(vartype, **kw):
+ globals().update(kw)
+ _state_vars.update(dict.fromkeys(kw, vartype))
+
+
+def __getstate__():
+ state = {}
+ g = globals()
+ for k, v in _state_vars.items():
state[k] = g['_sget_' + v](g[k])
- return state
-
+ return state
-def __setstate__(state):
- g = globals()
- for k, v in state.items():
+
+def __setstate__(state):
+ g = globals()
+ for k, v in state.items():
g['_sset_' + _state_vars[k]](k, g[k], v)
- return state
-
-
-def _sget_dict(val):
- return val.copy()
-
-
-def _sset_dict(key, ob, state):
- ob.clear()
- ob.update(state)
-
-
-def _sget_object(val):
- return val.__getstate__()
-
-
-def _sset_object(key, ob, state):
- ob.__setstate__(state)
-
-
-_sget_none = _sset_none = lambda *args: None
-
-
-def get_supported_platform():
- """Return this platform's maximum compatible version.
-
- distutils.util.get_platform() normally reports the minimum version
+ return state
+
+
+def _sget_dict(val):
+ return val.copy()
+
+
+def _sset_dict(key, ob, state):
+ ob.clear()
+ ob.update(state)
+
+
+def _sget_object(val):
+ return val.__getstate__()
+
+
+def _sset_object(key, ob, state):
+ ob.__setstate__(state)
+
+
+_sget_none = _sset_none = lambda *args: None
+
+
+def get_supported_platform():
+ """Return this platform's maximum compatible version.
+
+ distutils.util.get_platform() normally reports the minimum version
of macOS that would be required to *use* extensions produced by
- distutils. But what we want when checking compatibility is to know the
+ distutils. But what we want when checking compatibility is to know the
version of macOS that we are *running*. To allow usage of packages that
explicitly require a newer version of macOS, we must also know the
- current version of the OS.
-
- If this condition occurs for any other platform with a version in its
- platform strings, this function should be extended accordingly.
- """
- plat = get_build_platform()
- m = macosVersionString.match(plat)
- if m is not None and sys.platform == "darwin":
- try:
+ current version of the OS.
+
+ If this condition occurs for any other platform with a version in its
+ platform strings, this function should be extended accordingly.
+ """
+ plat = get_build_platform()
+ m = macosVersionString.match(plat)
+ if m is not None and sys.platform == "darwin":
+ try:
plat = 'macosx-%s-%s' % ('.'.join(_macos_vers()[:2]), m.group(3))
- except ValueError:
+ except ValueError:
# not macOS
- pass
- return plat
-
+ pass
+ return plat
+
-__all__ = [
- # Basic resource access and distribution/entry point discovery
+__all__ = [
+ # Basic resource access and distribution/entry point discovery
'require', 'run_script', 'get_provider', 'get_distribution',
- 'load_entry_point', 'get_entry_map', 'get_entry_info',
- 'iter_entry_points',
- 'resource_string', 'resource_stream', 'resource_filename',
- 'resource_listdir', 'resource_exists', 'resource_isdir',
-
- # Environmental control
- 'declare_namespace', 'working_set', 'add_activation_listener',
- 'find_distributions', 'set_extraction_path', 'cleanup_resources',
- 'get_default_cache',
-
- # Primary implementation classes
- 'Environment', 'WorkingSet', 'ResourceManager',
- 'Distribution', 'Requirement', 'EntryPoint',
-
- # Exceptions
- 'ResolutionError', 'VersionConflict', 'DistributionNotFound',
- 'UnknownExtra', 'ExtractionError',
-
- # Warnings
- 'PEP440Warning',
-
- # Parsing functions and string utilities
- 'parse_requirements', 'parse_version', 'safe_name', 'safe_version',
- 'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',
- 'safe_extra', 'to_filename', 'invalid_marker', 'evaluate_marker',
-
- # filesystem utilities
- 'ensure_directory', 'normalize_path',
-
- # Distribution "precedence" constants
- 'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',
-
- # "Provider" interfaces, implementations, and registration/lookup APIs
- 'IMetadataProvider', 'IResourceProvider', 'FileMetadata',
- 'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',
- 'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',
- 'register_finder', 'register_namespace_handler', 'register_loader_type',
- 'fixup_namespace_packages', 'get_importer',
-
+ 'load_entry_point', 'get_entry_map', 'get_entry_info',
+ 'iter_entry_points',
+ 'resource_string', 'resource_stream', 'resource_filename',
+ 'resource_listdir', 'resource_exists', 'resource_isdir',
+
+ # Environmental control
+ 'declare_namespace', 'working_set', 'add_activation_listener',
+ 'find_distributions', 'set_extraction_path', 'cleanup_resources',
+ 'get_default_cache',
+
+ # Primary implementation classes
+ 'Environment', 'WorkingSet', 'ResourceManager',
+ 'Distribution', 'Requirement', 'EntryPoint',
+
+ # Exceptions
+ 'ResolutionError', 'VersionConflict', 'DistributionNotFound',
+ 'UnknownExtra', 'ExtractionError',
+
+ # Warnings
+ 'PEP440Warning',
+
+ # Parsing functions and string utilities
+ 'parse_requirements', 'parse_version', 'safe_name', 'safe_version',
+ 'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',
+ 'safe_extra', 'to_filename', 'invalid_marker', 'evaluate_marker',
+
+ # filesystem utilities
+ 'ensure_directory', 'normalize_path',
+
+ # Distribution "precedence" constants
+ 'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',
+
+ # "Provider" interfaces, implementations, and registration/lookup APIs
+ 'IMetadataProvider', 'IResourceProvider', 'FileMetadata',
+ 'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',
+ 'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',
+ 'register_finder', 'register_namespace_handler', 'register_loader_type',
+ 'fixup_namespace_packages', 'get_importer',
+
# Warnings
'PkgResourcesDeprecationWarning',
- # Deprecated/backward compatibility only
- 'run_main', 'AvailableDistributions',
-]
-
+ # Deprecated/backward compatibility only
+ 'run_main', 'AvailableDistributions',
+]
+
-class ResolutionError(Exception):
- """Abstract base for dependency resolution errors"""
+class ResolutionError(Exception):
+ """Abstract base for dependency resolution errors"""
- def __repr__(self):
+ def __repr__(self):
return self.__class__.__name__ + repr(self.args)
-
-
-class VersionConflict(ResolutionError):
- """
- An already-installed version conflicts with the requested version.
-
- Should be initialized with the installed Distribution and the requested
- Requirement.
- """
-
- _template = "{self.dist} is installed but {self.req} is required"
-
- @property
- def dist(self):
- return self.args[0]
-
- @property
- def req(self):
- return self.args[1]
-
- def report(self):
- return self._template.format(**locals())
-
- def with_context(self, required_by):
- """
- If required_by is non-empty, return a version of self that is a
- ContextualVersionConflict.
- """
- if not required_by:
- return self
- args = self.args + (required_by,)
- return ContextualVersionConflict(*args)
-
-
-class ContextualVersionConflict(VersionConflict):
- """
- A VersionConflict that accepts a third parameter, the set of the
- requirements that required the installed Distribution.
- """
-
- _template = VersionConflict._template + ' by {self.required_by}'
-
- @property
- def required_by(self):
- return self.args[2]
-
-
-class DistributionNotFound(ResolutionError):
- """A requested distribution was not found"""
-
- _template = ("The '{self.req}' distribution was not found "
- "and is required by {self.requirers_str}")
-
- @property
- def req(self):
- return self.args[0]
-
- @property
- def requirers(self):
- return self.args[1]
-
- @property
- def requirers_str(self):
- if not self.requirers:
- return 'the application'
- return ', '.join(self.requirers)
-
- def report(self):
- return self._template.format(**locals())
-
- def __str__(self):
- return self.report()
-
-
-class UnknownExtra(ResolutionError):
- """Distribution doesn't have an "extra feature" of the given name"""
-
-
-_provider_factories = {}
-
+
+
+class VersionConflict(ResolutionError):
+ """
+ An already-installed version conflicts with the requested version.
+
+ Should be initialized with the installed Distribution and the requested
+ Requirement.
+ """
+
+ _template = "{self.dist} is installed but {self.req} is required"
+
+ @property
+ def dist(self):
+ return self.args[0]
+
+ @property
+ def req(self):
+ return self.args[1]
+
+ def report(self):
+ return self._template.format(**locals())
+
+ def with_context(self, required_by):
+ """
+ If required_by is non-empty, return a version of self that is a
+ ContextualVersionConflict.
+ """
+ if not required_by:
+ return self
+ args = self.args + (required_by,)
+ return ContextualVersionConflict(*args)
+
+
+class ContextualVersionConflict(VersionConflict):
+ """
+ A VersionConflict that accepts a third parameter, the set of the
+ requirements that required the installed Distribution.
+ """
+
+ _template = VersionConflict._template + ' by {self.required_by}'
+
+ @property
+ def required_by(self):
+ return self.args[2]
+
+
+class DistributionNotFound(ResolutionError):
+ """A requested distribution was not found"""
+
+ _template = ("The '{self.req}' distribution was not found "
+ "and is required by {self.requirers_str}")
+
+ @property
+ def req(self):
+ return self.args[0]
+
+ @property
+ def requirers(self):
+ return self.args[1]
+
+ @property
+ def requirers_str(self):
+ if not self.requirers:
+ return 'the application'
+ return ', '.join(self.requirers)
+
+ def report(self):
+ return self._template.format(**locals())
+
+ def __str__(self):
+ return self.report()
+
+
+class UnknownExtra(ResolutionError):
+ """Distribution doesn't have an "extra feature" of the given name"""
+
+
+_provider_factories = {}
+
PY_MAJOR = '{}.{}'.format(*sys.version_info)
-EGG_DIST = 3
-BINARY_DIST = 2
-SOURCE_DIST = 1
-CHECKOUT_DIST = 0
-DEVELOP_DIST = -1
-
-
-def register_loader_type(loader_type, provider_factory):
- """Register `provider_factory` to make providers for `loader_type`
-
- `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
- and `provider_factory` is a function that, passed a *module* object,
- returns an ``IResourceProvider`` for that module.
- """
- _provider_factories[loader_type] = provider_factory
-
-
-def get_provider(moduleOrReq):
- """Return an IResourceProvider for the named module or requirement"""
- if isinstance(moduleOrReq, Requirement):
- return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
- try:
- module = sys.modules[moduleOrReq]
- except KeyError:
- __import__(moduleOrReq)
- module = sys.modules[moduleOrReq]
- loader = getattr(module, '__loader__', None)
- return _find_adapter(_provider_factories, loader)(module)
-
+EGG_DIST = 3
+BINARY_DIST = 2
+SOURCE_DIST = 1
+CHECKOUT_DIST = 0
+DEVELOP_DIST = -1
+
+
+def register_loader_type(loader_type, provider_factory):
+ """Register `provider_factory` to make providers for `loader_type`
+
+ `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
+ and `provider_factory` is a function that, passed a *module* object,
+ returns an ``IResourceProvider`` for that module.
+ """
+ _provider_factories[loader_type] = provider_factory
+
+
+def get_provider(moduleOrReq):
+ """Return an IResourceProvider for the named module or requirement"""
+ if isinstance(moduleOrReq, Requirement):
+ return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
+ try:
+ module = sys.modules[moduleOrReq]
+ except KeyError:
+ __import__(moduleOrReq)
+ module = sys.modules[moduleOrReq]
+ loader = getattr(module, '__loader__', None)
+ return _find_adapter(_provider_factories, loader)(module)
+
def _macos_vers(_cache=[]):
- if not _cache:
- version = platform.mac_ver()[0]
- # fallback for MacPorts
- if version == '':
- plist = '/System/Library/CoreServices/SystemVersion.plist'
- if os.path.exists(plist):
- if hasattr(plistlib, 'readPlist'):
- plist_content = plistlib.readPlist(plist)
- if 'ProductVersion' in plist_content:
- version = plist_content['ProductVersion']
-
- _cache.append(version.split('.'))
- return _cache[0]
-
+ if not _cache:
+ version = platform.mac_ver()[0]
+ # fallback for MacPorts
+ if version == '':
+ plist = '/System/Library/CoreServices/SystemVersion.plist'
+ if os.path.exists(plist):
+ if hasattr(plistlib, 'readPlist'):
+ plist_content = plistlib.readPlist(plist)
+ if 'ProductVersion' in plist_content:
+ version = plist_content['ProductVersion']
+
+ _cache.append(version.split('.'))
+ return _cache[0]
+
def _macos_arch(machine):
- return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
-
+ return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
-def get_build_platform():
- """Return this platform's string for platform-specific distributions
-
- XXX Currently this is the same as ``distutils.util.get_platform()``, but it
+
+def get_build_platform():
+ """Return this platform's string for platform-specific distributions
+
+ XXX Currently this is the same as ``distutils.util.get_platform()``, but it
needs some hacks for Linux and macOS.
- """
+ """
from sysconfig import get_platform
-
- plat = get_platform()
- if sys.platform == "darwin" and not plat.startswith('macosx-'):
- try:
+
+ plat = get_platform()
+ if sys.platform == "darwin" and not plat.startswith('macosx-'):
+ try:
version = _macos_vers()
- machine = os.uname()[4].replace(" ", "_")
+ machine = os.uname()[4].replace(" ", "_")
return "macosx-%d.%d-%s" % (
int(version[0]), int(version[1]),
_macos_arch(machine),
)
- except ValueError:
- # if someone is running a non-Mac darwin system, this will fall
- # through to the default implementation
- pass
- return plat
-
-
-macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
-darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
-# XXX backward compat
-get_platform = get_build_platform
-
-
-def compatible_platforms(provided, required):
- """Can code for the `provided` platform run on the `required` platform?
-
- Returns true if either platform is ``None``, or the platforms are equal.
-
- XXX Needs compatibility checks for Linux and other unixy OSes.
- """
+ except ValueError:
+ # if someone is running a non-Mac darwin system, this will fall
+ # through to the default implementation
+ pass
+ return plat
+
+
+macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
+darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
+# XXX backward compat
+get_platform = get_build_platform
+
+
+def compatible_platforms(provided, required):
+ """Can code for the `provided` platform run on the `required` platform?
+
+ Returns true if either platform is ``None``, or the platforms are equal.
+
+ XXX Needs compatibility checks for Linux and other unixy OSes.
+ """
if provided is None or required is None or provided == required:
- # easy case
- return True
-
+ # easy case
+ return True
+
# macOS special cases
- reqMac = macosVersionString.match(required)
- if reqMac:
- provMac = macosVersionString.match(provided)
-
- # is this a Mac package?
- if not provMac:
- # this is backwards compatibility for packages built before
- # setuptools 0.6. All packages built after this point will
+ reqMac = macosVersionString.match(required)
+ if reqMac:
+ provMac = macosVersionString.match(provided)
+
+ # is this a Mac package?
+ if not provMac:
+ # this is backwards compatibility for packages built before
+ # setuptools 0.6. All packages built after this point will
# use the new macOS designation.
- provDarwin = darwinVersionString.match(provided)
- if provDarwin:
- dversion = int(provDarwin.group(1))
- macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
- if dversion == 7 and macosversion >= "10.3" or \
- dversion == 8 and macosversion >= "10.4":
- return True
+ provDarwin = darwinVersionString.match(provided)
+ if provDarwin:
+ dversion = int(provDarwin.group(1))
+ macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
+ if dversion == 7 and macosversion >= "10.3" or \
+ dversion == 8 and macosversion >= "10.4":
+ return True
# egg isn't macOS or legacy darwin
- return False
-
- # are they the same major version and machine type?
- if provMac.group(1) != reqMac.group(1) or \
- provMac.group(3) != reqMac.group(3):
- return False
-
- # is the required OS major update >= the provided one?
- if int(provMac.group(2)) > int(reqMac.group(2)):
- return False
-
- return True
-
- # XXX Linux and other platforms' special cases should go here
- return False
-
-
-def run_script(dist_spec, script_name):
- """Locate distribution `dist_spec` and run its `script_name` script"""
- ns = sys._getframe(1).f_globals
- name = ns['__name__']
- ns.clear()
- ns['__name__'] = name
- require(dist_spec)[0].run_script(script_name, ns)
-
-
-# backward compatibility
-run_main = run_script
-
-
-def get_distribution(dist):
- """Return a current distribution object for a Requirement or string"""
+ return False
+
+ # are they the same major version and machine type?
+ if provMac.group(1) != reqMac.group(1) or \
+ provMac.group(3) != reqMac.group(3):
+ return False
+
+ # is the required OS major update >= the provided one?
+ if int(provMac.group(2)) > int(reqMac.group(2)):
+ return False
+
+ return True
+
+ # XXX Linux and other platforms' special cases should go here
+ return False
+
+
+def run_script(dist_spec, script_name):
+ """Locate distribution `dist_spec` and run its `script_name` script"""
+ ns = sys._getframe(1).f_globals
+ name = ns['__name__']
+ ns.clear()
+ ns['__name__'] = name
+ require(dist_spec)[0].run_script(script_name, ns)
+
+
+# backward compatibility
+run_main = run_script
+
+
+def get_distribution(dist):
+ """Return a current distribution object for a Requirement or string"""
if isinstance(dist, str):
- dist = Requirement.parse(dist)
- if isinstance(dist, Requirement):
- dist = get_provider(dist)
- if not isinstance(dist, Distribution):
- raise TypeError("Expected string, Requirement, or Distribution", dist)
- return dist
-
-
-def load_entry_point(dist, group, name):
- """Return `name` entry point of `group` for `dist` or raise ImportError"""
- return get_distribution(dist).load_entry_point(group, name)
-
-
-def get_entry_map(dist, group=None):
- """Return the entry point map for `group`, or the full entry map"""
- return get_distribution(dist).get_entry_map(group)
-
-
-def get_entry_info(dist, group, name):
- """Return the EntryPoint object for `group`+`name`, or ``None``"""
- return get_distribution(dist).get_entry_info(group, name)
-
-
-class IMetadataProvider:
- def has_metadata(name):
- """Does the package's distribution contain the named metadata?"""
-
- def get_metadata(name):
- """The named metadata resource as a string"""
-
- def get_metadata_lines(name):
- """Yield named metadata resource as list of non-blank non-comment lines
-
- Leading and trailing whitespace is stripped from each line, and lines
- with ``#`` as the first non-blank character are omitted."""
-
- def metadata_isdir(name):
- """Is the named metadata a directory? (like ``os.path.isdir()``)"""
-
- def metadata_listdir(name):
- """List of metadata names in the directory (like ``os.listdir()``)"""
-
- def run_script(script_name, namespace):
- """Execute the named script in the supplied namespace dictionary"""
-
-
-class IResourceProvider(IMetadataProvider):
- """An object that provides access to package resources"""
-
- def get_resource_filename(manager, resource_name):
- """Return a true filesystem path for `resource_name`
-
- `manager` must be an ``IResourceManager``"""
-
- def get_resource_stream(manager, resource_name):
- """Return a readable file-like object for `resource_name`
-
- `manager` must be an ``IResourceManager``"""
-
- def get_resource_string(manager, resource_name):
- """Return a string containing the contents of `resource_name`
-
- `manager` must be an ``IResourceManager``"""
-
- def has_resource(resource_name):
- """Does the package contain the named resource?"""
-
- def resource_isdir(resource_name):
- """Is the named resource a directory? (like ``os.path.isdir()``)"""
-
- def resource_listdir(resource_name):
- """List of resource names in the directory (like ``os.listdir()``)"""
-
-
+ dist = Requirement.parse(dist)
+ if isinstance(dist, Requirement):
+ dist = get_provider(dist)
+ if not isinstance(dist, Distribution):
+ raise TypeError("Expected string, Requirement, or Distribution", dist)
+ return dist
+
+
+def load_entry_point(dist, group, name):
+ """Return `name` entry point of `group` for `dist` or raise ImportError"""
+ return get_distribution(dist).load_entry_point(group, name)
+
+
+def get_entry_map(dist, group=None):
+ """Return the entry point map for `group`, or the full entry map"""
+ return get_distribution(dist).get_entry_map(group)
+
+
+def get_entry_info(dist, group, name):
+ """Return the EntryPoint object for `group`+`name`, or ``None``"""
+ return get_distribution(dist).get_entry_info(group, name)
+
+
+class IMetadataProvider:
+ def has_metadata(name):
+ """Does the package's distribution contain the named metadata?"""
+
+ def get_metadata(name):
+ """The named metadata resource as a string"""
+
+ def get_metadata_lines(name):
+ """Yield named metadata resource as list of non-blank non-comment lines
+
+ Leading and trailing whitespace is stripped from each line, and lines
+ with ``#`` as the first non-blank character are omitted."""
+
+ def metadata_isdir(name):
+ """Is the named metadata a directory? (like ``os.path.isdir()``)"""
+
+ def metadata_listdir(name):
+ """List of metadata names in the directory (like ``os.listdir()``)"""
+
+ def run_script(script_name, namespace):
+ """Execute the named script in the supplied namespace dictionary"""
+
+
+class IResourceProvider(IMetadataProvider):
+ """An object that provides access to package resources"""
+
+ def get_resource_filename(manager, resource_name):
+ """Return a true filesystem path for `resource_name`
+
+ `manager` must be an ``IResourceManager``"""
+
+ def get_resource_stream(manager, resource_name):
+ """Return a readable file-like object for `resource_name`
+
+ `manager` must be an ``IResourceManager``"""
+
+ def get_resource_string(manager, resource_name):
+ """Return a string containing the contents of `resource_name`
+
+ `manager` must be an ``IResourceManager``"""
+
+ def has_resource(resource_name):
+ """Does the package contain the named resource?"""
+
+ def resource_isdir(resource_name):
+ """Is the named resource a directory? (like ``os.path.isdir()``)"""
+
+ def resource_listdir(resource_name):
+ """List of resource names in the directory (like ``os.listdir()``)"""
+
+
class WorkingSet:
- """A collection of active distributions on sys.path (or a similar list)"""
-
- def __init__(self, entries=None):
- """Create working set from list of path entries (default=sys.path)"""
- self.entries = []
- self.entry_keys = {}
- self.by_key = {}
- self.callbacks = []
-
- if entries is None:
- entries = sys.path
-
- for entry in entries:
- self.add_entry(entry)
-
- @classmethod
- def _build_master(cls):
- """
- Prepare the master working set.
- """
- ws = cls()
- try:
- from __main__ import __requires__
- except ImportError:
- # The main program does not list any requirements
- return ws
-
- # ensure the requirements are met
- try:
- ws.require(__requires__)
- except VersionConflict:
- return cls._build_from_requirements(__requires__)
-
- return ws
-
- @classmethod
- def _build_from_requirements(cls, req_spec):
- """
- Build a working set from a requirement spec. Rewrites sys.path.
- """
- # try it without defaults already on sys.path
- # by starting with an empty path
- ws = cls([])
- reqs = parse_requirements(req_spec)
- dists = ws.resolve(reqs, Environment())
- for dist in dists:
- ws.add(dist)
-
- # add any missing entries from sys.path
- for entry in sys.path:
- if entry not in ws.entries:
- ws.add_entry(entry)
-
- # then copy back to sys.path
- sys.path[:] = ws.entries
- return ws
-
- def add_entry(self, entry):
- """Add a path item to ``.entries``, finding any distributions on it
-
- ``find_distributions(entry, True)`` is used to find distributions
- corresponding to the path entry, and they are added. `entry` is
- always appended to ``.entries``, even if it is already present.
- (This is because ``sys.path`` can contain the same value more than
- once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
- equal ``sys.path``.)
- """
- self.entry_keys.setdefault(entry, [])
- self.entries.append(entry)
- for dist in find_distributions(entry, True):
- self.add(dist, entry, False)
-
- def __contains__(self, dist):
- """True if `dist` is the active distribution for its project"""
- return self.by_key.get(dist.key) == dist
-
- def find(self, req):
- """Find a distribution matching requirement `req`
-
- If there is an active distribution for the requested project, this
- returns it as long as it meets the version requirement specified by
- `req`. But, if there is an active distribution for the project and it
- does *not* meet the `req` requirement, ``VersionConflict`` is raised.
- If there is no active distribution for the requested project, ``None``
- is returned.
- """
- dist = self.by_key.get(req.key)
- if dist is not None and dist not in req:
- # XXX add more info
- raise VersionConflict(dist, req)
- return dist
-
- def iter_entry_points(self, group, name=None):
- """Yield entry point objects from `group` matching `name`
-
- If `name` is None, yields all entry points in `group` from all
- distributions in the working set, otherwise only ones matching
- both `group` and `name` are yielded (in distribution order).
- """
+ """A collection of active distributions on sys.path (or a similar list)"""
+
+ def __init__(self, entries=None):
+ """Create working set from list of path entries (default=sys.path)"""
+ self.entries = []
+ self.entry_keys = {}
+ self.by_key = {}
+ self.callbacks = []
+
+ if entries is None:
+ entries = sys.path
+
+ for entry in entries:
+ self.add_entry(entry)
+
+ @classmethod
+ def _build_master(cls):
+ """
+ Prepare the master working set.
+ """
+ ws = cls()
+ try:
+ from __main__ import __requires__
+ except ImportError:
+ # The main program does not list any requirements
+ return ws
+
+ # ensure the requirements are met
+ try:
+ ws.require(__requires__)
+ except VersionConflict:
+ return cls._build_from_requirements(__requires__)
+
+ return ws
+
+ @classmethod
+ def _build_from_requirements(cls, req_spec):
+ """
+ Build a working set from a requirement spec. Rewrites sys.path.
+ """
+ # try it without defaults already on sys.path
+ # by starting with an empty path
+ ws = cls([])
+ reqs = parse_requirements(req_spec)
+ dists = ws.resolve(reqs, Environment())
+ for dist in dists:
+ ws.add(dist)
+
+ # add any missing entries from sys.path
+ for entry in sys.path:
+ if entry not in ws.entries:
+ ws.add_entry(entry)
+
+ # then copy back to sys.path
+ sys.path[:] = ws.entries
+ return ws
+
+ def add_entry(self, entry):
+ """Add a path item to ``.entries``, finding any distributions on it
+
+ ``find_distributions(entry, True)`` is used to find distributions
+ corresponding to the path entry, and they are added. `entry` is
+ always appended to ``.entries``, even if it is already present.
+ (This is because ``sys.path`` can contain the same value more than
+ once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
+ equal ``sys.path``.)
+ """
+ self.entry_keys.setdefault(entry, [])
+ self.entries.append(entry)
+ for dist in find_distributions(entry, True):
+ self.add(dist, entry, False)
+
+ def __contains__(self, dist):
+ """True if `dist` is the active distribution for its project"""
+ return self.by_key.get(dist.key) == dist
+
+ def find(self, req):
+ """Find a distribution matching requirement `req`
+
+ If there is an active distribution for the requested project, this
+ returns it as long as it meets the version requirement specified by
+ `req`. But, if there is an active distribution for the project and it
+ does *not* meet the `req` requirement, ``VersionConflict`` is raised.
+ If there is no active distribution for the requested project, ``None``
+ is returned.
+ """
+ dist = self.by_key.get(req.key)
+ if dist is not None and dist not in req:
+ # XXX add more info
+ raise VersionConflict(dist, req)
+ return dist
+
+ def iter_entry_points(self, group, name=None):
+ """Yield entry point objects from `group` matching `name`
+
+ If `name` is None, yields all entry points in `group` from all
+ distributions in the working set, otherwise only ones matching
+ both `group` and `name` are yielded (in distribution order).
+ """
return (
entry
for dist in self
for entry in dist.get_entry_map(group).values()
if name is None or name == entry.name
)
-
- def run_script(self, requires, script_name):
- """Locate distribution for `requires` and run `script_name` script"""
- ns = sys._getframe(1).f_globals
- name = ns['__name__']
- ns.clear()
- ns['__name__'] = name
- self.require(requires)[0].run_script(script_name, ns)
-
- def __iter__(self):
- """Yield distributions for non-duplicate projects in the working set
-
- The yield order is the order in which the items' path entries were
- added to the working set.
- """
- seen = {}
- for item in self.entries:
- if item not in self.entry_keys:
- # workaround a cache issue
- continue
-
- for key in self.entry_keys[item]:
- if key not in seen:
+
+ def run_script(self, requires, script_name):
+ """Locate distribution for `requires` and run `script_name` script"""
+ ns = sys._getframe(1).f_globals
+ name = ns['__name__']
+ ns.clear()
+ ns['__name__'] = name
+ self.require(requires)[0].run_script(script_name, ns)
+
+ def __iter__(self):
+ """Yield distributions for non-duplicate projects in the working set
+
+ The yield order is the order in which the items' path entries were
+ added to the working set.
+ """
+ seen = {}
+ for item in self.entries:
+ if item not in self.entry_keys:
+ # workaround a cache issue
+ continue
+
+ for key in self.entry_keys[item]:
+ if key not in seen:
seen[key] = 1
- yield self.by_key[key]
-
- def add(self, dist, entry=None, insert=True, replace=False):
- """Add `dist` to working set, associated with `entry`
-
- If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
- On exit from this routine, `entry` is added to the end of the working
- set's ``.entries`` (if it wasn't already present).
-
- `dist` is only added to the working set if it's for a project that
- doesn't already have a distribution in the set, unless `replace=True`.
- If it's added, any callbacks registered with the ``subscribe()`` method
- will be called.
- """
- if insert:
- dist.insert_on(self.entries, entry, replace=replace)
-
- if entry is None:
- entry = dist.location
+ yield self.by_key[key]
+
+ def add(self, dist, entry=None, insert=True, replace=False):
+ """Add `dist` to working set, associated with `entry`
+
+ If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
+ On exit from this routine, `entry` is added to the end of the working
+ set's ``.entries`` (if it wasn't already present).
+
+ `dist` is only added to the working set if it's for a project that
+ doesn't already have a distribution in the set, unless `replace=True`.
+ If it's added, any callbacks registered with the ``subscribe()`` method
+ will be called.
+ """
+ if insert:
+ dist.insert_on(self.entries, entry, replace=replace)
+
+ if entry is None:
+ entry = dist.location
keys = self.entry_keys.setdefault(entry, [])
keys2 = self.entry_keys.setdefault(dist.location, [])
- if not replace and dist.key in self.by_key:
- # ignore hidden distros
- return
-
- self.by_key[dist.key] = dist
- if dist.key not in keys:
- keys.append(dist.key)
- if dist.key not in keys2:
- keys2.append(dist.key)
- self._added_new(dist)
-
+ if not replace and dist.key in self.by_key:
+ # ignore hidden distros
+ return
+
+ self.by_key[dist.key] = dist
+ if dist.key not in keys:
+ keys.append(dist.key)
+ if dist.key not in keys2:
+ keys2.append(dist.key)
+ self._added_new(dist)
+
# FIXME: 'WorkingSet.resolve' is too complex (11)
def resolve(self, requirements, env=None, installer=None, # noqa: C901
replace_conflicting=False, extras=None):
- """List all distributions needed to (recursively) meet `requirements`
-
- `requirements` must be a sequence of ``Requirement`` objects. `env`,
- if supplied, should be an ``Environment`` instance. If
- not supplied, it defaults to all distributions available within any
- entry or distribution in the working set. `installer`, if supplied,
- will be invoked with each requirement that cannot be met by an
- already-installed distribution; it should return a ``Distribution`` or
- ``None``.
-
+ """List all distributions needed to (recursively) meet `requirements`
+
+ `requirements` must be a sequence of ``Requirement`` objects. `env`,
+ if supplied, should be an ``Environment`` instance. If
+ not supplied, it defaults to all distributions available within any
+ entry or distribution in the working set. `installer`, if supplied,
+ will be invoked with each requirement that cannot be met by an
+ already-installed distribution; it should return a ``Distribution`` or
+ ``None``.
+
Unless `replace_conflicting=True`, raises a VersionConflict exception
if
- any requirements are found on the path that have the correct name but
- the wrong version. Otherwise, if an `installer` is supplied it will be
- invoked to obtain the correct version of the requirement and activate
- it.
+ any requirements are found on the path that have the correct name but
+ the wrong version. Otherwise, if an `installer` is supplied it will be
+ invoked to obtain the correct version of the requirement and activate
+ it.
`extras` is a list of the extras to be used with these requirements.
This is important because extra requirements may look like `my_req;
extra = "my_extra"`, which would otherwise be interpreted as a purely
optional requirement. Instead, we want to be able to assert that these
requirements are truly required.
- """
-
- # set up the stack
- requirements = list(requirements)[::-1]
- # set of processed requirements
- processed = {}
- # key -> dist
- best = {}
- to_activate = []
-
+ """
+
+ # set up the stack
+ requirements = list(requirements)[::-1]
+ # set of processed requirements
+ processed = {}
+ # key -> dist
+ best = {}
+ to_activate = []
+
req_extras = _ReqExtras()
- # Mapping of requirement to set of distributions that required it;
- # useful for reporting info about conflicts.
- required_by = collections.defaultdict(set)
-
- while requirements:
- # process dependencies breadth-first
- req = requirements.pop(0)
- if req in processed:
- # Ignore cyclic or redundant dependencies
- continue
+ # Mapping of requirement to set of distributions that required it;
+ # useful for reporting info about conflicts.
+ required_by = collections.defaultdict(set)
+
+ while requirements:
+ # process dependencies breadth-first
+ req = requirements.pop(0)
+ if req in processed:
+ # Ignore cyclic or redundant dependencies
+ continue
if not req_extras.markers_pass(req, extras):
continue
- dist = best.get(req.key)
- if dist is None:
- # Find the best distribution and add it to the map
- dist = self.by_key.get(req.key)
- if dist is None or (dist not in req and replace_conflicting):
- ws = self
- if env is None:
- if dist is None:
- env = Environment(self.entries)
- else:
- # Use an empty environment and workingset to avoid
- # any further conflicts with the conflicting
- # distribution
- env = Environment([])
- ws = WorkingSet([])
+ dist = best.get(req.key)
+ if dist is None:
+ # Find the best distribution and add it to the map
+ dist = self.by_key.get(req.key)
+ if dist is None or (dist not in req and replace_conflicting):
+ ws = self
+ if env is None:
+ if dist is None:
+ env = Environment(self.entries)
+ else:
+ # Use an empty environment and workingset to avoid
+ # any further conflicts with the conflicting
+ # distribution
+ env = Environment([])
+ ws = WorkingSet([])
dist = best[req.key] = env.best_match(
req, ws, installer,
replace_conflicting=replace_conflicting
)
- if dist is None:
- requirers = required_by.get(req, None)
- raise DistributionNotFound(req, requirers)
- to_activate.append(dist)
- if dist not in req:
- # Oops, the "best" so far conflicts with a dependency
- dependent_req = required_by[req]
- raise VersionConflict(dist, req).with_context(dependent_req)
-
- # push the new requirements onto the stack
- new_requirements = dist.requires(req.extras)[::-1]
- requirements.extend(new_requirements)
-
- # Register the new requirements needed by req
- for new_requirement in new_requirements:
- required_by[new_requirement].add(req.project_name)
+ if dist is None:
+ requirers = required_by.get(req, None)
+ raise DistributionNotFound(req, requirers)
+ to_activate.append(dist)
+ if dist not in req:
+ # Oops, the "best" so far conflicts with a dependency
+ dependent_req = required_by[req]
+ raise VersionConflict(dist, req).with_context(dependent_req)
+
+ # push the new requirements onto the stack
+ new_requirements = dist.requires(req.extras)[::-1]
+ requirements.extend(new_requirements)
+
+ # Register the new requirements needed by req
+ for new_requirement in new_requirements:
+ required_by[new_requirement].add(req.project_name)
req_extras[new_requirement] = req.extras
-
- processed[req] = True
-
- # return list of distros to activate
- return to_activate
-
+
+ processed[req] = True
+
+ # return list of distros to activate
+ return to_activate
+
def find_plugins(
self, plugin_env, full_env=None, installer=None, fallback=True):
- """Find all activatable distributions in `plugin_env`
-
- Example usage::
-
- distributions, errors = working_set.find_plugins(
- Environment(plugin_dirlist)
- )
- # add plugins+libs to sys.path
- map(working_set.add, distributions)
- # display errors
- print('Could not load', errors)
-
- The `plugin_env` should be an ``Environment`` instance that contains
- only distributions that are in the project's "plugin directory" or
- directories. The `full_env`, if supplied, should be an ``Environment``
- contains all currently-available distributions. If `full_env` is not
- supplied, one is created automatically from the ``WorkingSet`` this
- method is called on, which will typically mean that every directory on
- ``sys.path`` will be scanned for distributions.
-
- `installer` is a standard installer callback as used by the
- ``resolve()`` method. The `fallback` flag indicates whether we should
- attempt to resolve older versions of a plugin if the newest version
- cannot be resolved.
-
- This method returns a 2-tuple: (`distributions`, `error_info`), where
- `distributions` is a list of the distributions found in `plugin_env`
- that were loadable, along with any other distributions that are needed
- to resolve their dependencies. `error_info` is a dictionary mapping
- unloadable plugin distributions to an exception instance describing the
- error that occurred. Usually this will be a ``DistributionNotFound`` or
- ``VersionConflict`` instance.
- """
-
- plugin_projects = list(plugin_env)
- # scan project names in alphabetic order
- plugin_projects.sort()
-
- error_info = {}
- distributions = {}
-
- if full_env is None:
- env = Environment(self.entries)
- env += plugin_env
- else:
- env = full_env + plugin_env
-
- shadow_set = self.__class__([])
- # put all our entries in shadow_set
- list(map(shadow_set.add, self))
-
- for project_name in plugin_projects:
-
- for dist in plugin_env[project_name]:
-
- req = [dist.as_requirement()]
-
- try:
- resolvees = shadow_set.resolve(req, env, installer)
-
- except ResolutionError as v:
- # save error info
- error_info[dist] = v
- if fallback:
- # try the next older version of project
- continue
- else:
- # give up on this project, keep going
- break
-
- else:
- list(map(shadow_set.add, resolvees))
- distributions.update(dict.fromkeys(resolvees))
-
- # success, no need to try any more versions of this project
- break
-
- distributions = list(distributions)
- distributions.sort()
-
- return distributions, error_info
-
- def require(self, *requirements):
- """Ensure that distributions matching `requirements` are activated
-
- `requirements` must be a string or a (possibly-nested) sequence
- thereof, specifying the distributions and versions required. The
- return value is a sequence of the distributions that needed to be
- activated to fulfill the requirements; all relevant distributions are
- included, even if they were already activated in this working set.
- """
- needed = self.resolve(parse_requirements(requirements))
-
- for dist in needed:
- self.add(dist)
-
- return needed
-
+ """Find all activatable distributions in `plugin_env`
+
+ Example usage::
+
+ distributions, errors = working_set.find_plugins(
+ Environment(plugin_dirlist)
+ )
+ # add plugins+libs to sys.path
+ map(working_set.add, distributions)
+ # display errors
+ print('Could not load', errors)
+
+ The `plugin_env` should be an ``Environment`` instance that contains
+ only distributions that are in the project's "plugin directory" or
+ directories. The `full_env`, if supplied, should be an ``Environment``
+ contains all currently-available distributions. If `full_env` is not
+ supplied, one is created automatically from the ``WorkingSet`` this
+ method is called on, which will typically mean that every directory on
+ ``sys.path`` will be scanned for distributions.
+
+ `installer` is a standard installer callback as used by the
+ ``resolve()`` method. The `fallback` flag indicates whether we should
+ attempt to resolve older versions of a plugin if the newest version
+ cannot be resolved.
+
+ This method returns a 2-tuple: (`distributions`, `error_info`), where
+ `distributions` is a list of the distributions found in `plugin_env`
+ that were loadable, along with any other distributions that are needed
+ to resolve their dependencies. `error_info` is a dictionary mapping
+ unloadable plugin distributions to an exception instance describing the
+ error that occurred. Usually this will be a ``DistributionNotFound`` or
+ ``VersionConflict`` instance.
+ """
+
+ plugin_projects = list(plugin_env)
+ # scan project names in alphabetic order
+ plugin_projects.sort()
+
+ error_info = {}
+ distributions = {}
+
+ if full_env is None:
+ env = Environment(self.entries)
+ env += plugin_env
+ else:
+ env = full_env + plugin_env
+
+ shadow_set = self.__class__([])
+ # put all our entries in shadow_set
+ list(map(shadow_set.add, self))
+
+ for project_name in plugin_projects:
+
+ for dist in plugin_env[project_name]:
+
+ req = [dist.as_requirement()]
+
+ try:
+ resolvees = shadow_set.resolve(req, env, installer)
+
+ except ResolutionError as v:
+ # save error info
+ error_info[dist] = v
+ if fallback:
+ # try the next older version of project
+ continue
+ else:
+ # give up on this project, keep going
+ break
+
+ else:
+ list(map(shadow_set.add, resolvees))
+ distributions.update(dict.fromkeys(resolvees))
+
+ # success, no need to try any more versions of this project
+ break
+
+ distributions = list(distributions)
+ distributions.sort()
+
+ return distributions, error_info
+
+ def require(self, *requirements):
+ """Ensure that distributions matching `requirements` are activated
+
+ `requirements` must be a string or a (possibly-nested) sequence
+ thereof, specifying the distributions and versions required. The
+ return value is a sequence of the distributions that needed to be
+ activated to fulfill the requirements; all relevant distributions are
+ included, even if they were already activated in this working set.
+ """
+ needed = self.resolve(parse_requirements(requirements))
+
+ for dist in needed:
+ self.add(dist)
+
+ return needed
+
def subscribe(self, callback, existing=True):
"""Invoke `callback` for all distributions
If `existing=True` (default),
call on all existing ones, as well.
"""
- if callback in self.callbacks:
- return
- self.callbacks.append(callback)
+ if callback in self.callbacks:
+ return
+ self.callbacks.append(callback)
if not existing:
return
- for dist in self:
- callback(dist)
-
- def _added_new(self, dist):
- for callback in self.callbacks:
- callback(dist)
-
- def __getstate__(self):
- return (
- self.entries[:], self.entry_keys.copy(), self.by_key.copy(),
- self.callbacks[:]
- )
-
- def __setstate__(self, e_k_b_c):
- entries, keys, by_key, callbacks = e_k_b_c
- self.entries = entries[:]
- self.entry_keys = keys.copy()
- self.by_key = by_key.copy()
- self.callbacks = callbacks[:]
-
-
+ for dist in self:
+ callback(dist)
+
+ def _added_new(self, dist):
+ for callback in self.callbacks:
+ callback(dist)
+
+ def __getstate__(self):
+ return (
+ self.entries[:], self.entry_keys.copy(), self.by_key.copy(),
+ self.callbacks[:]
+ )
+
+ def __setstate__(self, e_k_b_c):
+ entries, keys, by_key, callbacks = e_k_b_c
+ self.entries = entries[:]
+ self.entry_keys = keys.copy()
+ self.by_key = by_key.copy()
+ self.callbacks = callbacks[:]
+
+
class _ReqExtras(dict):
"""
Map each requirement to the extras that demanded it.
@@ -948,354 +948,354 @@ class _ReqExtras(dict):
class Environment:
- """Searchable snapshot of distributions on a search path"""
-
+ """Searchable snapshot of distributions on a search path"""
+
def __init__(
self, search_path=None, platform=get_supported_platform(),
- python=PY_MAJOR):
- """Snapshot distributions available on a search path
-
- Any distributions found on `search_path` are added to the environment.
- `search_path` should be a sequence of ``sys.path`` items. If not
- supplied, ``sys.path`` is used.
-
- `platform` is an optional string specifying the name of the platform
- that platform-specific distributions must be compatible with. If
- unspecified, it defaults to the current platform. `python` is an
+ python=PY_MAJOR):
+ """Snapshot distributions available on a search path
+
+ Any distributions found on `search_path` are added to the environment.
+ `search_path` should be a sequence of ``sys.path`` items. If not
+ supplied, ``sys.path`` is used.
+
+ `platform` is an optional string specifying the name of the platform
+ that platform-specific distributions must be compatible with. If
+ unspecified, it defaults to the current platform. `python` is an
optional string naming the desired version of Python (e.g. ``'3.6'``);
- it defaults to the current version.
-
- You may explicitly set `platform` (and/or `python`) to ``None`` if you
- wish to map *all* distributions, not just those compatible with the
- running platform or Python version.
- """
- self._distmap = {}
- self.platform = platform
- self.python = python
- self.scan(search_path)
-
- def can_add(self, dist):
- """Is distribution `dist` acceptable for this environment?
-
- The distribution must match the platform and python version
- requirements specified when this environment was created, or False
- is returned.
- """
+ it defaults to the current version.
+
+ You may explicitly set `platform` (and/or `python`) to ``None`` if you
+ wish to map *all* distributions, not just those compatible with the
+ running platform or Python version.
+ """
+ self._distmap = {}
+ self.platform = platform
+ self.python = python
+ self.scan(search_path)
+
+ def can_add(self, dist):
+ """Is distribution `dist` acceptable for this environment?
+
+ The distribution must match the platform and python version
+ requirements specified when this environment was created, or False
+ is returned.
+ """
py_compat = (
self.python is None
or dist.py_version is None
or dist.py_version == self.python
)
return py_compat and compatible_platforms(dist.platform, self.platform)
-
- def remove(self, dist):
- """Remove `dist` from the environment"""
- self._distmap[dist.key].remove(dist)
-
- def scan(self, search_path=None):
- """Scan `search_path` for distributions usable in this environment
-
- Any distributions found are added to the environment.
- `search_path` should be a sequence of ``sys.path`` items. If not
- supplied, ``sys.path`` is used. Only distributions conforming to
- the platform/python version defined at initialization are added.
- """
- if search_path is None:
- search_path = sys.path
-
- for item in search_path:
- for dist in find_distributions(item):
- self.add(dist)
-
- def __getitem__(self, project_name):
- """Return a newest-to-oldest list of distributions for `project_name`
-
- Uses case-insensitive `project_name` comparison, assuming all the
- project's distributions use their project's name converted to all
- lowercase as their key.
-
- """
- distribution_key = project_name.lower()
- return self._distmap.get(distribution_key, [])
-
- def add(self, dist):
- """Add `dist` if we ``can_add()`` it and it has not already been added
- """
- if self.can_add(dist) and dist.has_version():
- dists = self._distmap.setdefault(dist.key, [])
- if dist not in dists:
- dists.append(dist)
- dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
-
+
+ def remove(self, dist):
+ """Remove `dist` from the environment"""
+ self._distmap[dist.key].remove(dist)
+
+ def scan(self, search_path=None):
+ """Scan `search_path` for distributions usable in this environment
+
+ Any distributions found are added to the environment.
+ `search_path` should be a sequence of ``sys.path`` items. If not
+ supplied, ``sys.path`` is used. Only distributions conforming to
+ the platform/python version defined at initialization are added.
+ """
+ if search_path is None:
+ search_path = sys.path
+
+ for item in search_path:
+ for dist in find_distributions(item):
+ self.add(dist)
+
+ def __getitem__(self, project_name):
+ """Return a newest-to-oldest list of distributions for `project_name`
+
+ Uses case-insensitive `project_name` comparison, assuming all the
+ project's distributions use their project's name converted to all
+ lowercase as their key.
+
+ """
+ distribution_key = project_name.lower()
+ return self._distmap.get(distribution_key, [])
+
+ def add(self, dist):
+ """Add `dist` if we ``can_add()`` it and it has not already been added
+ """
+ if self.can_add(dist) and dist.has_version():
+ dists = self._distmap.setdefault(dist.key, [])
+ if dist not in dists:
+ dists.append(dist)
+ dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
+
def best_match(
self, req, working_set, installer=None, replace_conflicting=False):
- """Find distribution best matching `req` and usable on `working_set`
-
- This calls the ``find(req)`` method of the `working_set` to see if a
- suitable distribution is already active. (This may raise
- ``VersionConflict`` if an unsuitable version of the project is already
- active in the specified `working_set`.) If a suitable distribution
- isn't active, this method returns the newest distribution in the
- environment that meets the ``Requirement`` in `req`. If no suitable
- distribution is found, and `installer` is supplied, then the result of
- calling the environment's ``obtain(req, installer)`` method will be
- returned.
- """
+ """Find distribution best matching `req` and usable on `working_set`
+
+ This calls the ``find(req)`` method of the `working_set` to see if a
+ suitable distribution is already active. (This may raise
+ ``VersionConflict`` if an unsuitable version of the project is already
+ active in the specified `working_set`.) If a suitable distribution
+ isn't active, this method returns the newest distribution in the
+ environment that meets the ``Requirement`` in `req`. If no suitable
+ distribution is found, and `installer` is supplied, then the result of
+ calling the environment's ``obtain(req, installer)`` method will be
+ returned.
+ """
try:
dist = working_set.find(req)
except VersionConflict:
if not replace_conflicting:
raise
dist = None
- if dist is not None:
- return dist
- for dist in self[req.key]:
- if dist in req:
- return dist
- # try to download/install
- return self.obtain(req, installer)
-
- def obtain(self, requirement, installer=None):
- """Obtain a distribution matching `requirement` (e.g. via download)
-
- Obtain a distro that matches requirement (e.g. via download). In the
- base ``Environment`` class, this routine just returns
- ``installer(requirement)``, unless `installer` is None, in which case
- None is returned instead. This method is a hook that allows subclasses
- to attempt other ways of obtaining a distribution before falling back
- to the `installer` argument."""
- if installer is not None:
- return installer(requirement)
-
- def __iter__(self):
- """Yield the unique project names of the available distributions"""
- for key in self._distmap.keys():
- if self[key]:
- yield key
-
- def __iadd__(self, other):
- """In-place addition of a distribution or environment"""
- if isinstance(other, Distribution):
- self.add(other)
- elif isinstance(other, Environment):
- for project in other:
- for dist in other[project]:
- self.add(dist)
- else:
- raise TypeError("Can't add %r to environment" % (other,))
- return self
-
- def __add__(self, other):
- """Add an environment or distribution to an environment"""
- new = self.__class__([], platform=None, python=None)
- for env in self, other:
- new += env
- return new
-
-
-# XXX backward compatibility
-AvailableDistributions = Environment
-
-
-class ExtractionError(RuntimeError):
- """An error occurred extracting a resource
-
- The following attributes are available from instances of this exception:
-
- manager
- The resource manager that raised this exception
-
- cache_path
- The base directory for resource extraction
-
- original_error
- The exception instance that caused extraction to fail
- """
-
-
-class ResourceManager:
- """Manage resource extraction and packages"""
- extraction_path = None
-
- def __init__(self):
- self.cached_files = {}
-
- def resource_exists(self, package_or_requirement, resource_name):
- """Does the named resource exist?"""
- return get_provider(package_or_requirement).has_resource(resource_name)
-
- def resource_isdir(self, package_or_requirement, resource_name):
- """Is the named resource an existing directory?"""
- return get_provider(package_or_requirement).resource_isdir(
- resource_name
- )
-
- def resource_filename(self, package_or_requirement, resource_name):
- """Return a true filesystem path for specified resource"""
- return get_provider(package_or_requirement).get_resource_filename(
- self, resource_name
- )
-
- def resource_stream(self, package_or_requirement, resource_name):
- """Return a readable file-like object for specified resource"""
- return get_provider(package_or_requirement).get_resource_stream(
- self, resource_name
- )
-
- def resource_string(self, package_or_requirement, resource_name):
- """Return specified resource as a string"""
- return get_provider(package_or_requirement).get_resource_string(
- self, resource_name
- )
-
- def resource_listdir(self, package_or_requirement, resource_name):
- """List the contents of the named resource directory"""
- return get_provider(package_or_requirement).resource_listdir(
- resource_name
- )
-
- def extraction_error(self):
- """Give an error message for problems extracting file(s)"""
-
- old_exc = sys.exc_info()[1]
- cache_path = self.extraction_path or get_default_cache()
-
- tmpl = textwrap.dedent("""
- Can't extract file(s) to egg cache
-
+ if dist is not None:
+ return dist
+ for dist in self[req.key]:
+ if dist in req:
+ return dist
+ # try to download/install
+ return self.obtain(req, installer)
+
+ def obtain(self, requirement, installer=None):
+ """Obtain a distribution matching `requirement` (e.g. via download)
+
+ Obtain a distro that matches requirement (e.g. via download). In the
+ base ``Environment`` class, this routine just returns
+ ``installer(requirement)``, unless `installer` is None, in which case
+ None is returned instead. This method is a hook that allows subclasses
+ to attempt other ways of obtaining a distribution before falling back
+ to the `installer` argument."""
+ if installer is not None:
+ return installer(requirement)
+
+ def __iter__(self):
+ """Yield the unique project names of the available distributions"""
+ for key in self._distmap.keys():
+ if self[key]:
+ yield key
+
+ def __iadd__(self, other):
+ """In-place addition of a distribution or environment"""
+ if isinstance(other, Distribution):
+ self.add(other)
+ elif isinstance(other, Environment):
+ for project in other:
+ for dist in other[project]:
+ self.add(dist)
+ else:
+ raise TypeError("Can't add %r to environment" % (other,))
+ return self
+
+ def __add__(self, other):
+ """Add an environment or distribution to an environment"""
+ new = self.__class__([], platform=None, python=None)
+ for env in self, other:
+ new += env
+ return new
+
+
+# XXX backward compatibility
+AvailableDistributions = Environment
+
+
+class ExtractionError(RuntimeError):
+ """An error occurred extracting a resource
+
+ The following attributes are available from instances of this exception:
+
+ manager
+ The resource manager that raised this exception
+
+ cache_path
+ The base directory for resource extraction
+
+ original_error
+ The exception instance that caused extraction to fail
+ """
+
+
+class ResourceManager:
+ """Manage resource extraction and packages"""
+ extraction_path = None
+
+ def __init__(self):
+ self.cached_files = {}
+
+ def resource_exists(self, package_or_requirement, resource_name):
+ """Does the named resource exist?"""
+ return get_provider(package_or_requirement).has_resource(resource_name)
+
+ def resource_isdir(self, package_or_requirement, resource_name):
+ """Is the named resource an existing directory?"""
+ return get_provider(package_or_requirement).resource_isdir(
+ resource_name
+ )
+
+ def resource_filename(self, package_or_requirement, resource_name):
+ """Return a true filesystem path for specified resource"""
+ return get_provider(package_or_requirement).get_resource_filename(
+ self, resource_name
+ )
+
+ def resource_stream(self, package_or_requirement, resource_name):
+ """Return a readable file-like object for specified resource"""
+ return get_provider(package_or_requirement).get_resource_stream(
+ self, resource_name
+ )
+
+ def resource_string(self, package_or_requirement, resource_name):
+ """Return specified resource as a string"""
+ return get_provider(package_or_requirement).get_resource_string(
+ self, resource_name
+ )
+
+ def resource_listdir(self, package_or_requirement, resource_name):
+ """List the contents of the named resource directory"""
+ return get_provider(package_or_requirement).resource_listdir(
+ resource_name
+ )
+
+ def extraction_error(self):
+ """Give an error message for problems extracting file(s)"""
+
+ old_exc = sys.exc_info()[1]
+ cache_path = self.extraction_path or get_default_cache()
+
+ tmpl = textwrap.dedent("""
+ Can't extract file(s) to egg cache
+
The following error occurred while trying to extract file(s)
to the Python egg cache:
-
- {old_exc}
-
- The Python egg cache directory is currently set to:
-
- {cache_path}
-
+
+ {old_exc}
+
+ The Python egg cache directory is currently set to:
+
+ {cache_path}
+
Perhaps your account does not have write access to this directory?
You can change the cache directory by setting the PYTHON_EGG_CACHE
environment variable to point to an accessible directory.
- """).lstrip()
- err = ExtractionError(tmpl.format(**locals()))
- err.manager = self
- err.cache_path = cache_path
- err.original_error = old_exc
- raise err
-
- def get_cache_path(self, archive_name, names=()):
- """Return absolute location in cache for `archive_name` and `names`
-
- The parent directory of the resulting path will be created if it does
- not already exist. `archive_name` should be the base filename of the
- enclosing egg (which may not be the name of the enclosing zipfile!),
- including its ".egg" extension. `names`, if provided, should be a
- sequence of path name parts "under" the egg's extraction location.
-
- This method should only be called by resource providers that need to
- obtain an extraction location, and only for names they intend to
- extract, as it tracks the generated names for possible cleanup later.
- """
- extract_path = self.extraction_path or get_default_cache()
+ """).lstrip()
+ err = ExtractionError(tmpl.format(**locals()))
+ err.manager = self
+ err.cache_path = cache_path
+ err.original_error = old_exc
+ raise err
+
+ def get_cache_path(self, archive_name, names=()):
+ """Return absolute location in cache for `archive_name` and `names`
+
+ The parent directory of the resulting path will be created if it does
+ not already exist. `archive_name` should be the base filename of the
+ enclosing egg (which may not be the name of the enclosing zipfile!),
+ including its ".egg" extension. `names`, if provided, should be a
+ sequence of path name parts "under" the egg's extraction location.
+
+ This method should only be called by resource providers that need to
+ obtain an extraction location, and only for names they intend to
+ extract, as it tracks the generated names for possible cleanup later.
+ """
+ extract_path = self.extraction_path or get_default_cache()
target_path = os.path.join(extract_path, archive_name + '-tmp', *names)
- try:
- _bypass_ensure_directory(target_path)
+ try:
+ _bypass_ensure_directory(target_path)
except Exception:
- self.extraction_error()
-
- self._warn_unsafe_extraction_path(extract_path)
-
- self.cached_files[target_path] = 1
- return target_path
-
- @staticmethod
- def _warn_unsafe_extraction_path(path):
- """
- If the default extraction path is overridden and set to an insecure
- location, such as /tmp, it opens up an opportunity for an attacker to
- replace an extracted file with an unauthorized payload. Warn the user
- if a known insecure location is used.
-
- See Distribute #375 for more details.
- """
- if os.name == 'nt' and not path.startswith(os.environ['windir']):
- # On Windows, permissions are generally restrictive by default
- # and temp directories are not writable by other users, so
- # bypass the warning.
- return
- mode = os.stat(path).st_mode
- if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
+ self.extraction_error()
+
+ self._warn_unsafe_extraction_path(extract_path)
+
+ self.cached_files[target_path] = 1
+ return target_path
+
+ @staticmethod
+ def _warn_unsafe_extraction_path(path):
+ """
+ If the default extraction path is overridden and set to an insecure
+ location, such as /tmp, it opens up an opportunity for an attacker to
+ replace an extracted file with an unauthorized payload. Warn the user
+ if a known insecure location is used.
+
+ See Distribute #375 for more details.
+ """
+ if os.name == 'nt' and not path.startswith(os.environ['windir']):
+ # On Windows, permissions are generally restrictive by default
+ # and temp directories are not writable by other users, so
+ # bypass the warning.
+ return
+ mode = os.stat(path).st_mode
+ if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
msg = (
"Extraction path is writable by group/others "
"and vulnerable to attack when "
"used with get_resource_filename ({path}). "
"Consider a more secure "
- "location (set with .set_extraction_path or the "
+ "location (set with .set_extraction_path or the "
"PYTHON_EGG_CACHE environment variable)."
).format(**locals())
- warnings.warn(msg, UserWarning)
-
- def postprocess(self, tempname, filename):
- """Perform any platform-specific postprocessing of `tempname`
-
- This is where Mac header rewrites should be done; other platforms don't
- have anything special they should do.
-
- Resource providers should call this method ONLY after successfully
- extracting a compressed resource. They must NOT call it on resources
- that are already in the filesystem.
-
- `tempname` is the current (temporary) name of the file, and `filename`
- is the name it will be renamed to by the caller after this routine
- returns.
- """
-
- if os.name == 'posix':
- # Make the resource executable
- mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
- os.chmod(tempname, mode)
-
- def set_extraction_path(self, path):
- """Set the base path where resources will be extracted to, if needed.
-
- If you do not call this routine before any extractions take place, the
- path defaults to the return value of ``get_default_cache()``. (Which
- is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
- platform-specific fallbacks. See that routine's documentation for more
- details.)
-
- Resources are extracted to subdirectories of this path based upon
- information given by the ``IResourceProvider``. You may set this to a
- temporary directory, but then you must call ``cleanup_resources()`` to
- delete the extracted files when done. There is no guarantee that
- ``cleanup_resources()`` will be able to remove all extracted files.
-
- (Note: you may not change the extraction path for a given resource
- manager once resources have been extracted, unless you first call
- ``cleanup_resources()``.)
- """
- if self.cached_files:
- raise ValueError(
- "Can't change extraction path, files already extracted"
- )
-
- self.extraction_path = path
-
- def cleanup_resources(self, force=False):
- """
- Delete all extracted resource files and directories, returning a list
- of the file and directory names that could not be successfully removed.
- This function does not have any concurrency protection, so it should
- generally only be called when the extraction path is a temporary
- directory exclusive to a single process. This method is not
- automatically called; you must call it explicitly or register it as an
- ``atexit`` function if you wish to ensure cleanup of a temporary
- directory used for extractions.
- """
- # XXX
-
-
-def get_default_cache():
- """
+ warnings.warn(msg, UserWarning)
+
+ def postprocess(self, tempname, filename):
+ """Perform any platform-specific postprocessing of `tempname`
+
+ This is where Mac header rewrites should be done; other platforms don't
+ have anything special they should do.
+
+ Resource providers should call this method ONLY after successfully
+ extracting a compressed resource. They must NOT call it on resources
+ that are already in the filesystem.
+
+ `tempname` is the current (temporary) name of the file, and `filename`
+ is the name it will be renamed to by the caller after this routine
+ returns.
+ """
+
+ if os.name == 'posix':
+ # Make the resource executable
+ mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
+ os.chmod(tempname, mode)
+
+ def set_extraction_path(self, path):
+ """Set the base path where resources will be extracted to, if needed.
+
+ If you do not call this routine before any extractions take place, the
+ path defaults to the return value of ``get_default_cache()``. (Which
+ is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
+ platform-specific fallbacks. See that routine's documentation for more
+ details.)
+
+ Resources are extracted to subdirectories of this path based upon
+ information given by the ``IResourceProvider``. You may set this to a
+ temporary directory, but then you must call ``cleanup_resources()`` to
+ delete the extracted files when done. There is no guarantee that
+ ``cleanup_resources()`` will be able to remove all extracted files.
+
+ (Note: you may not change the extraction path for a given resource
+ manager once resources have been extracted, unless you first call
+ ``cleanup_resources()``.)
+ """
+ if self.cached_files:
+ raise ValueError(
+ "Can't change extraction path, files already extracted"
+ )
+
+ self.extraction_path = path
+
+ def cleanup_resources(self, force=False):
+ """
+ Delete all extracted resource files and directories, returning a list
+ of the file and directory names that could not be successfully removed.
+ This function does not have any concurrency protection, so it should
+ generally only be called when the extraction path is a temporary
+ directory exclusive to a single process. This method is not
+ automatically called; you must call it explicitly or register it as an
+ ``atexit`` function if you wish to ensure cleanup of a temporary
+ directory used for extractions.
+ """
+ # XXX
+
+
+def get_default_cache():
+ """
Return the ``PYTHON_EGG_CACHE`` environment variable
or a platform-relevant user cache dir for an app
named "Python-Eggs".
@@ -1304,45 +1304,45 @@ def get_default_cache():
os.environ.get('PYTHON_EGG_CACHE')
or appdirs.user_cache_dir(appname='Python-Eggs')
)
-
-
-def safe_name(name):
- """Convert an arbitrary string to a standard distribution name
-
- Any runs of non-alphanumeric/. characters are replaced with a single '-'.
- """
- return re.sub('[^A-Za-z0-9.]+', '-', name)
-
-
-def safe_version(version):
- """
- Convert an arbitrary string to a standard version string
- """
- try:
- # normalize the version
- return str(packaging.version.Version(version))
- except packaging.version.InvalidVersion:
+
+
+def safe_name(name):
+ """Convert an arbitrary string to a standard distribution name
+
+ Any runs of non-alphanumeric/. characters are replaced with a single '-'.
+ """
+ return re.sub('[^A-Za-z0-9.]+', '-', name)
+
+
+def safe_version(version):
+ """
+ Convert an arbitrary string to a standard version string
+ """
+ try:
+ # normalize the version
+ return str(packaging.version.Version(version))
+ except packaging.version.InvalidVersion:
version = version.replace(' ', '.')
- return re.sub('[^A-Za-z0-9.]+', '-', version)
-
-
-def safe_extra(extra):
- """Convert an arbitrary string to a standard 'extra' name
-
- Any runs of non-alphanumeric characters are replaced with a single '_',
- and the result is always lowercased.
- """
+ return re.sub('[^A-Za-z0-9.]+', '-', version)
+
+
+def safe_extra(extra):
+ """Convert an arbitrary string to a standard 'extra' name
+
+ Any runs of non-alphanumeric characters are replaced with a single '_',
+ and the result is always lowercased.
+ """
return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()
-
-
-def to_filename(name):
- """Convert a project or version name to its filename-escaped form
-
- Any '-' characters are currently replaced with '_'.
- """
+
+
+def to_filename(name):
+ """Convert a project or version name to its filename-escaped form
+
+ Any '-' characters are currently replaced with '_'.
+ """
return name.replace('-', '_')
-
-
+
+
def invalid_marker(text):
"""
Validate text as a PEP 508 environment marker; return an exception
@@ -1355,14 +1355,14 @@ def invalid_marker(text):
e.lineno = None
return e
return False
-
-
+
+
def evaluate_marker(text, extra=None):
"""
Evaluate a PEP 508 environment marker.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
-
+
This implementation uses the 'pyparsing' module.
"""
try:
@@ -1370,38 +1370,38 @@ def evaluate_marker(text, extra=None):
return marker.evaluate()
except packaging.markers.InvalidMarker as e:
raise SyntaxError(e) from e
-
-
-class NullProvider:
- """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
-
- egg_name = None
- egg_info = None
- loader = None
-
- def __init__(self, module):
- self.loader = getattr(module, '__loader__', None)
- self.module_path = os.path.dirname(getattr(module, '__file__', ''))
-
- def get_resource_filename(self, manager, resource_name):
- return self._fn(self.module_path, resource_name)
-
- def get_resource_stream(self, manager, resource_name):
- return io.BytesIO(self.get_resource_string(manager, resource_name))
-
- def get_resource_string(self, manager, resource_name):
- return self._get(self._fn(self.module_path, resource_name))
-
- def has_resource(self, resource_name):
- return self._has(self._fn(self.module_path, resource_name))
-
+
+
+class NullProvider:
+ """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
+
+ egg_name = None
+ egg_info = None
+ loader = None
+
+ def __init__(self, module):
+ self.loader = getattr(module, '__loader__', None)
+ self.module_path = os.path.dirname(getattr(module, '__file__', ''))
+
+ def get_resource_filename(self, manager, resource_name):
+ return self._fn(self.module_path, resource_name)
+
+ def get_resource_stream(self, manager, resource_name):
+ return io.BytesIO(self.get_resource_string(manager, resource_name))
+
+ def get_resource_string(self, manager, resource_name):
+ return self._get(self._fn(self.module_path, resource_name))
+
+ def has_resource(self, resource_name):
+ return self._has(self._fn(self.module_path, resource_name))
+
def _get_metadata_path(self, name):
return self._fn(self.egg_info, name)
- def has_metadata(self, name):
+ def has_metadata(self, name):
if not self.egg_info:
return self.egg_info
-
+
path = self._get_metadata_path(name)
return self._has(path)
@@ -1417,69 +1417,69 @@ class NullProvider:
# troubleshooting, and without changing the exception type.
exc.reason += ' in {} file at path: {}'.format(name, path)
raise
-
- def get_metadata_lines(self, name):
- return yield_lines(self.get_metadata(name))
-
- def resource_isdir(self, resource_name):
- return self._isdir(self._fn(self.module_path, resource_name))
-
- def metadata_isdir(self, name):
- return self.egg_info and self._isdir(self._fn(self.egg_info, name))
-
- def resource_listdir(self, resource_name):
- return self._listdir(self._fn(self.module_path, resource_name))
-
- def metadata_listdir(self, name):
- if self.egg_info:
- return self._listdir(self._fn(self.egg_info, name))
- return []
-
- def run_script(self, script_name, namespace):
+
+ def get_metadata_lines(self, name):
+ return yield_lines(self.get_metadata(name))
+
+ def resource_isdir(self, resource_name):
+ return self._isdir(self._fn(self.module_path, resource_name))
+
+ def metadata_isdir(self, name):
+ return self.egg_info and self._isdir(self._fn(self.egg_info, name))
+
+ def resource_listdir(self, resource_name):
+ return self._listdir(self._fn(self.module_path, resource_name))
+
+ def metadata_listdir(self, name):
+ if self.egg_info:
+ return self._listdir(self._fn(self.egg_info, name))
+ return []
+
+ def run_script(self, script_name, namespace):
script = 'scripts/' + script_name
- if not self.has_metadata(script):
+ if not self.has_metadata(script):
raise ResolutionError(
"Script {script!r} not found in metadata at {self.egg_info!r}"
.format(**locals()),
)
- script_text = self.get_metadata(script).replace('\r\n', '\n')
- script_text = script_text.replace('\r', '\n')
- script_filename = self._fn(self.egg_info, script)
- namespace['__file__'] = script_filename
- if os.path.exists(script_filename):
+ script_text = self.get_metadata(script).replace('\r\n', '\n')
+ script_text = script_text.replace('\r', '\n')
+ script_filename = self._fn(self.egg_info, script)
+ namespace['__file__'] = script_filename
+ if os.path.exists(script_filename):
with open(script_filename) as fid:
source = fid.read()
- code = compile(source, script_filename, 'exec')
- exec(code, namespace, namespace)
- else:
- from linecache import cache
- cache[script_filename] = (
- len(script_text), 0, script_text.split('\n'), script_filename
- )
+ code = compile(source, script_filename, 'exec')
+ exec(code, namespace, namespace)
+ else:
+ from linecache import cache
+ cache[script_filename] = (
+ len(script_text), 0, script_text.split('\n'), script_filename
+ )
script_code = compile(script_text, script_filename, 'exec')
- exec(script_code, namespace, namespace)
-
- def _has(self, path):
- raise NotImplementedError(
- "Can't perform this operation for unregistered loader type"
- )
-
- def _isdir(self, path):
- raise NotImplementedError(
- "Can't perform this operation for unregistered loader type"
- )
-
- def _listdir(self, path):
- raise NotImplementedError(
- "Can't perform this operation for unregistered loader type"
- )
-
- def _fn(self, base, resource_name):
+ exec(script_code, namespace, namespace)
+
+ def _has(self, path):
+ raise NotImplementedError(
+ "Can't perform this operation for unregistered loader type"
+ )
+
+ def _isdir(self, path):
+ raise NotImplementedError(
+ "Can't perform this operation for unregistered loader type"
+ )
+
+ def _listdir(self, path):
+ raise NotImplementedError(
+ "Can't perform this operation for unregistered loader type"
+ )
+
+ def _fn(self, base, resource_name):
self._validate_resource_path(resource_name)
- if resource_name:
- return os.path.join(base, *resource_name.split('/'))
- return base
-
+ if resource_name:
+ return os.path.join(base, *resource_name.split('/'))
+ return base
+
@staticmethod
def _validate_resource_path(path):
"""
@@ -1555,17 +1555,17 @@ is not allowed.
stacklevel=4,
)
- def _get(self, path):
- if hasattr(self.loader, 'get_data'):
- return self.loader.get_data(path)
- raise NotImplementedError(
- "Can't perform this operation for loaders without 'get_data()'"
- )
-
-
-register_loader_type(object, NullProvider)
-
-
+ def _get(self, path):
+ if hasattr(self.loader, 'get_data'):
+ return self.loader.get_data(path)
+ raise NotImplementedError(
+ "Can't perform this operation for loaders without 'get_data()'"
+ )
+
+
+register_loader_type(object, NullProvider)
+
+
def _parents(path):
"""
yield all parents of path including path
@@ -1577,61 +1577,61 @@ def _parents(path):
path, _ = os.path.split(path)
-class EggProvider(NullProvider):
- """Provider based on a virtual filesystem"""
-
- def __init__(self, module):
- NullProvider.__init__(self, module)
- self._setup_prefix()
-
- def _setup_prefix(self):
+class EggProvider(NullProvider):
+ """Provider based on a virtual filesystem"""
+
+ def __init__(self, module):
+ NullProvider.__init__(self, module)
+ self._setup_prefix()
+
+ def _setup_prefix(self):
# Assume that metadata may be nested inside a "basket"
# of multiple eggs and use module_path instead of .archive.
eggs = filter(_is_egg_path, _parents(self.module_path))
egg = next(eggs, None)
egg and self._set_egg(egg)
-
+
def _set_egg(self, path):
self.egg_name = os.path.basename(path)
self.egg_info = os.path.join(path, 'EGG-INFO')
self.egg_root = path
-class DefaultProvider(EggProvider):
- """Provides access to package resources in the filesystem"""
-
- def _has(self, path):
- return os.path.exists(path)
-
- def _isdir(self, path):
- return os.path.isdir(path)
-
- def _listdir(self, path):
- return os.listdir(path)
-
- def get_resource_stream(self, manager, resource_name):
- return open(self._fn(self.module_path, resource_name), 'rb')
-
- def _get(self, path):
- with open(path, 'rb') as stream:
- return stream.read()
-
- @classmethod
- def _register(cls):
+class DefaultProvider(EggProvider):
+ """Provides access to package resources in the filesystem"""
+
+ def _has(self, path):
+ return os.path.exists(path)
+
+ def _isdir(self, path):
+ return os.path.isdir(path)
+
+ def _listdir(self, path):
+ return os.listdir(path)
+
+ def get_resource_stream(self, manager, resource_name):
+ return open(self._fn(self.module_path, resource_name), 'rb')
+
+ def _get(self, path):
+ with open(path, 'rb') as stream:
+ return stream.read()
+
+ @classmethod
+ def _register(cls):
loader_names = 'SourceFileLoader', 'SourcelessFileLoader',
for name in loader_names:
loader_cls = getattr(importlib_machinery, name, type(None))
register_loader_type(loader_cls, cls)
-
-
-DefaultProvider._register()
-
-
-class EmptyProvider(NullProvider):
- """Provider that returns nothing for all requests"""
-
- module_path = None
-
+
+
+DefaultProvider._register()
+
+
+class EmptyProvider(NullProvider):
+ """Provider that returns nothing for all requests"""
+
+ module_path = None
+
_isdir = _has = lambda self, path: False
def _get(self, path):
@@ -1640,261 +1640,261 @@ class EmptyProvider(NullProvider):
def _listdir(self, path):
return []
- def __init__(self):
- pass
-
-
-empty_provider = EmptyProvider()
-
-
-class ZipManifests(dict):
- """
- zip manifest builder
- """
-
- @classmethod
- def build(cls, path):
- """
- Build a dictionary similar to the zipimport directory
- caches, except instead of tuples, store ZipInfo objects.
-
- Use a platform-specific path separator (os.sep) for the path keys
- for compatibility with pypy on Windows.
- """
+ def __init__(self):
+ pass
+
+
+empty_provider = EmptyProvider()
+
+
+class ZipManifests(dict):
+ """
+ zip manifest builder
+ """
+
+ @classmethod
+ def build(cls, path):
+ """
+ Build a dictionary similar to the zipimport directory
+ caches, except instead of tuples, store ZipInfo objects.
+
+ Use a platform-specific path separator (os.sep) for the path keys
+ for compatibility with pypy on Windows.
+ """
with zipfile.ZipFile(path) as zfile:
- items = (
- (
- name.replace('/', os.sep),
- zfile.getinfo(name),
- )
- for name in zfile.namelist()
- )
- return dict(items)
-
- load = build
-
-
-class MemoizedZipManifests(ZipManifests):
- """
- Memoized zipfile manifests.
- """
- manifest_mod = collections.namedtuple('manifest_mod', 'manifest mtime')
-
- def load(self, path):
- """
- Load a manifest at path or return a suitable manifest already loaded.
- """
- path = os.path.normpath(path)
- mtime = os.stat(path).st_mtime
-
- if path not in self or self[path].mtime != mtime:
- manifest = self.build(path)
- self[path] = self.manifest_mod(manifest, mtime)
-
- return self[path].manifest
-
-
-class ZipProvider(EggProvider):
- """Resource support for zips and eggs"""
-
- eagers = None
- _zip_manifests = MemoizedZipManifests()
-
- def __init__(self, module):
- EggProvider.__init__(self, module)
+ items = (
+ (
+ name.replace('/', os.sep),
+ zfile.getinfo(name),
+ )
+ for name in zfile.namelist()
+ )
+ return dict(items)
+
+ load = build
+
+
+class MemoizedZipManifests(ZipManifests):
+ """
+ Memoized zipfile manifests.
+ """
+ manifest_mod = collections.namedtuple('manifest_mod', 'manifest mtime')
+
+ def load(self, path):
+ """
+ Load a manifest at path or return a suitable manifest already loaded.
+ """
+ path = os.path.normpath(path)
+ mtime = os.stat(path).st_mtime
+
+ if path not in self or self[path].mtime != mtime:
+ manifest = self.build(path)
+ self[path] = self.manifest_mod(manifest, mtime)
+
+ return self[path].manifest
+
+
+class ZipProvider(EggProvider):
+ """Resource support for zips and eggs"""
+
+ eagers = None
+ _zip_manifests = MemoizedZipManifests()
+
+ def __init__(self, module):
+ EggProvider.__init__(self, module)
self.zip_pre = self.loader.archive + os.sep
-
- def _zipinfo_name(self, fspath):
- # Convert a virtual filename (full path to file) into a zipfile subpath
- # usable with the zipimport directory cache for our target archive
+
+ def _zipinfo_name(self, fspath):
+ # Convert a virtual filename (full path to file) into a zipfile subpath
+ # usable with the zipimport directory cache for our target archive
fspath = fspath.rstrip(os.sep)
if fspath == self.loader.archive:
return ''
- if fspath.startswith(self.zip_pre):
- return fspath[len(self.zip_pre):]
- raise AssertionError(
- "%s is not a subpath of %s" % (fspath, self.zip_pre)
- )
-
- def _parts(self, zip_path):
- # Convert a zipfile subpath into an egg-relative path part list.
- # pseudo-fs path
+ if fspath.startswith(self.zip_pre):
+ return fspath[len(self.zip_pre):]
+ raise AssertionError(
+ "%s is not a subpath of %s" % (fspath, self.zip_pre)
+ )
+
+ def _parts(self, zip_path):
+ # Convert a zipfile subpath into an egg-relative path part list.
+ # pseudo-fs path
fspath = self.zip_pre + zip_path
if fspath.startswith(self.egg_root + os.sep):
return fspath[len(self.egg_root) + 1:].split(os.sep)
- raise AssertionError(
- "%s is not a subpath of %s" % (fspath, self.egg_root)
- )
-
- @property
- def zipinfo(self):
- return self._zip_manifests.load(self.loader.archive)
-
- def get_resource_filename(self, manager, resource_name):
- if not self.egg_name:
- raise NotImplementedError(
- "resource_filename() only supported for .egg, not .zip"
- )
- # no need to lock for extraction, since we use temp names
- zip_path = self._resource_to_zip(resource_name)
- eagers = self._get_eager_resources()
- if '/'.join(self._parts(zip_path)) in eagers:
- for name in eagers:
- self._extract_resource(manager, self._eager_to_zip(name))
- return self._extract_resource(manager, zip_path)
-
- @staticmethod
- def _get_date_and_size(zip_stat):
- size = zip_stat.file_size
- # ymdhms+wday, yday, dst
- date_time = zip_stat.date_time + (0, 0, -1)
- # 1980 offset already done
- timestamp = time.mktime(date_time)
- return timestamp, size
-
+ raise AssertionError(
+ "%s is not a subpath of %s" % (fspath, self.egg_root)
+ )
+
+ @property
+ def zipinfo(self):
+ return self._zip_manifests.load(self.loader.archive)
+
+ def get_resource_filename(self, manager, resource_name):
+ if not self.egg_name:
+ raise NotImplementedError(
+ "resource_filename() only supported for .egg, not .zip"
+ )
+ # no need to lock for extraction, since we use temp names
+ zip_path = self._resource_to_zip(resource_name)
+ eagers = self._get_eager_resources()
+ if '/'.join(self._parts(zip_path)) in eagers:
+ for name in eagers:
+ self._extract_resource(manager, self._eager_to_zip(name))
+ return self._extract_resource(manager, zip_path)
+
+ @staticmethod
+ def _get_date_and_size(zip_stat):
+ size = zip_stat.file_size
+ # ymdhms+wday, yday, dst
+ date_time = zip_stat.date_time + (0, 0, -1)
+ # 1980 offset already done
+ timestamp = time.mktime(date_time)
+ return timestamp, size
+
# FIXME: 'ZipProvider._extract_resource' is too complex (12)
def _extract_resource(self, manager, zip_path): # noqa: C901
-
- if zip_path in self._index():
- for name in self._index()[zip_path]:
- last = self._extract_resource(
- manager, os.path.join(zip_path, name)
- )
- # return the extracted directory name
- return os.path.dirname(last)
-
- timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
-
- if not WRITE_SUPPORT:
- raise IOError('"os.rename" and "os.unlink" are not supported '
- 'on this platform')
- try:
-
- real_path = manager.get_cache_path(
- self.egg_name, self._parts(zip_path)
- )
-
- if self._is_current(real_path, zip_path):
- return real_path
-
+
+ if zip_path in self._index():
+ for name in self._index()[zip_path]:
+ last = self._extract_resource(
+ manager, os.path.join(zip_path, name)
+ )
+ # return the extracted directory name
+ return os.path.dirname(last)
+
+ timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
+
+ if not WRITE_SUPPORT:
+ raise IOError('"os.rename" and "os.unlink" are not supported '
+ 'on this platform')
+ try:
+
+ real_path = manager.get_cache_path(
+ self.egg_name, self._parts(zip_path)
+ )
+
+ if self._is_current(real_path, zip_path):
+ return real_path
+
outf, tmpnam = _mkstemp(
".$extract",
dir=os.path.dirname(real_path),
)
- os.write(outf, self.loader.get_data(zip_path))
- os.close(outf)
- utime(tmpnam, (timestamp, timestamp))
- manager.postprocess(tmpnam, real_path)
-
- try:
- rename(tmpnam, real_path)
-
- except os.error:
- if os.path.isfile(real_path):
- if self._is_current(real_path, zip_path):
- # the file became current since it was checked above,
- # so proceed.
- return real_path
- # Windows, del old file and retry
+ os.write(outf, self.loader.get_data(zip_path))
+ os.close(outf)
+ utime(tmpnam, (timestamp, timestamp))
+ manager.postprocess(tmpnam, real_path)
+
+ try:
+ rename(tmpnam, real_path)
+
+ except os.error:
+ if os.path.isfile(real_path):
+ if self._is_current(real_path, zip_path):
+ # the file became current since it was checked above,
+ # so proceed.
+ return real_path
+ # Windows, del old file and retry
elif os.name == 'nt':
- unlink(real_path)
- rename(tmpnam, real_path)
- return real_path
- raise
-
- except os.error:
- # report a user-friendly error
- manager.extraction_error()
-
- return real_path
-
- def _is_current(self, file_path, zip_path):
- """
- Return True if the file_path is current for this zip_path
- """
- timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
- if not os.path.isfile(file_path):
- return False
- stat = os.stat(file_path)
+ unlink(real_path)
+ rename(tmpnam, real_path)
+ return real_path
+ raise
+
+ except os.error:
+ # report a user-friendly error
+ manager.extraction_error()
+
+ return real_path
+
+ def _is_current(self, file_path, zip_path):
+ """
+ Return True if the file_path is current for this zip_path
+ """
+ timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
+ if not os.path.isfile(file_path):
+ return False
+ stat = os.stat(file_path)
if stat.st_size != size or stat.st_mtime != timestamp:
- return False
- # check that the contents match
- zip_contents = self.loader.get_data(zip_path)
- with open(file_path, 'rb') as f:
- file_contents = f.read()
- return zip_contents == file_contents
-
- def _get_eager_resources(self):
- if self.eagers is None:
- eagers = []
- for name in ('native_libs.txt', 'eager_resources.txt'):
- if self.has_metadata(name):
- eagers.extend(self.get_metadata_lines(name))
- self.eagers = eagers
- return self.eagers
-
- def _index(self):
- try:
- return self._dirindex
- except AttributeError:
- ind = {}
- for path in self.zipinfo:
- parts = path.split(os.sep)
- while parts:
- parent = os.sep.join(parts[:-1])
- if parent in ind:
- ind[parent].append(parts[-1])
- break
- else:
- ind[parent] = [parts.pop()]
- self._dirindex = ind
- return ind
-
- def _has(self, fspath):
- zip_path = self._zipinfo_name(fspath)
- return zip_path in self.zipinfo or zip_path in self._index()
-
- def _isdir(self, fspath):
- return self._zipinfo_name(fspath) in self._index()
-
- def _listdir(self, fspath):
- return list(self._index().get(self._zipinfo_name(fspath), ()))
-
- def _eager_to_zip(self, resource_name):
- return self._zipinfo_name(self._fn(self.egg_root, resource_name))
-
- def _resource_to_zip(self, resource_name):
- return self._zipinfo_name(self._fn(self.module_path, resource_name))
-
-
-register_loader_type(zipimport.zipimporter, ZipProvider)
-
-
-class FileMetadata(EmptyProvider):
- """Metadata handler for standalone PKG-INFO files
-
- Usage::
-
- metadata = FileMetadata("/path/to/PKG-INFO")
-
- This provider rejects all data and metadata requests except for PKG-INFO,
- which is treated as existing, and will be the contents of the file at
- the provided location.
- """
-
- def __init__(self, path):
- self.path = path
-
+ return False
+ # check that the contents match
+ zip_contents = self.loader.get_data(zip_path)
+ with open(file_path, 'rb') as f:
+ file_contents = f.read()
+ return zip_contents == file_contents
+
+ def _get_eager_resources(self):
+ if self.eagers is None:
+ eagers = []
+ for name in ('native_libs.txt', 'eager_resources.txt'):
+ if self.has_metadata(name):
+ eagers.extend(self.get_metadata_lines(name))
+ self.eagers = eagers
+ return self.eagers
+
+ def _index(self):
+ try:
+ return self._dirindex
+ except AttributeError:
+ ind = {}
+ for path in self.zipinfo:
+ parts = path.split(os.sep)
+ while parts:
+ parent = os.sep.join(parts[:-1])
+ if parent in ind:
+ ind[parent].append(parts[-1])
+ break
+ else:
+ ind[parent] = [parts.pop()]
+ self._dirindex = ind
+ return ind
+
+ def _has(self, fspath):
+ zip_path = self._zipinfo_name(fspath)
+ return zip_path in self.zipinfo or zip_path in self._index()
+
+ def _isdir(self, fspath):
+ return self._zipinfo_name(fspath) in self._index()
+
+ def _listdir(self, fspath):
+ return list(self._index().get(self._zipinfo_name(fspath), ()))
+
+ def _eager_to_zip(self, resource_name):
+ return self._zipinfo_name(self._fn(self.egg_root, resource_name))
+
+ def _resource_to_zip(self, resource_name):
+ return self._zipinfo_name(self._fn(self.module_path, resource_name))
+
+
+register_loader_type(zipimport.zipimporter, ZipProvider)
+
+
+class FileMetadata(EmptyProvider):
+ """Metadata handler for standalone PKG-INFO files
+
+ Usage::
+
+ metadata = FileMetadata("/path/to/PKG-INFO")
+
+ This provider rejects all data and metadata requests except for PKG-INFO,
+ which is treated as existing, and will be the contents of the file at
+ the provided location.
+ """
+
+ def __init__(self, path):
+ self.path = path
+
def _get_metadata_path(self, name):
return self.path
- def has_metadata(self, name):
+ def has_metadata(self, name):
return name == 'PKG-INFO' and os.path.isfile(self.path)
-
- def get_metadata(self, name):
+
+ def get_metadata(self, name):
if name != 'PKG-INFO':
raise KeyError("No metadata except PKG-INFO is available")
-
+
with io.open(self.path, encoding='utf-8', errors="replace") as f:
metadata = f.read()
self._warn_on_replacement(metadata)
@@ -1907,106 +1907,106 @@ class FileMetadata(EmptyProvider):
msg = tmpl.format(**locals())
warnings.warn(msg)
- def get_metadata_lines(self, name):
- return yield_lines(self.get_metadata(name))
-
-
-class PathMetadata(DefaultProvider):
- """Metadata provider for egg directories
-
- Usage::
-
- # Development eggs:
-
- egg_info = "/path/to/PackageName.egg-info"
- base_dir = os.path.dirname(egg_info)
- metadata = PathMetadata(base_dir, egg_info)
- dist_name = os.path.splitext(os.path.basename(egg_info))[0]
- dist = Distribution(basedir, project_name=dist_name, metadata=metadata)
-
- # Unpacked egg directories:
-
- egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
- metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
- dist = Distribution.from_filename(egg_path, metadata=metadata)
- """
-
- def __init__(self, path, egg_info):
- self.module_path = path
- self.egg_info = egg_info
-
-
-class EggMetadata(ZipProvider):
- """Metadata provider for .egg files"""
-
- def __init__(self, importer):
- """Create a metadata provider from a zipimporter"""
-
+ def get_metadata_lines(self, name):
+ return yield_lines(self.get_metadata(name))
+
+
+class PathMetadata(DefaultProvider):
+ """Metadata provider for egg directories
+
+ Usage::
+
+ # Development eggs:
+
+ egg_info = "/path/to/PackageName.egg-info"
+ base_dir = os.path.dirname(egg_info)
+ metadata = PathMetadata(base_dir, egg_info)
+ dist_name = os.path.splitext(os.path.basename(egg_info))[0]
+ dist = Distribution(basedir, project_name=dist_name, metadata=metadata)
+
+ # Unpacked egg directories:
+
+ egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
+ metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
+ dist = Distribution.from_filename(egg_path, metadata=metadata)
+ """
+
+ def __init__(self, path, egg_info):
+ self.module_path = path
+ self.egg_info = egg_info
+
+
+class EggMetadata(ZipProvider):
+ """Metadata provider for .egg files"""
+
+ def __init__(self, importer):
+ """Create a metadata provider from a zipimporter"""
+
self.zip_pre = importer.archive + os.sep
- self.loader = importer
- if importer.prefix:
- self.module_path = os.path.join(importer.archive, importer.prefix)
- else:
- self.module_path = importer.archive
- self._setup_prefix()
-
-
+ self.loader = importer
+ if importer.prefix:
+ self.module_path = os.path.join(importer.archive, importer.prefix)
+ else:
+ self.module_path = importer.archive
+ self._setup_prefix()
+
+
_declare_state('dict', _distribution_finders={})
-def register_finder(importer_type, distribution_finder):
- """Register `distribution_finder` to find distributions in sys.path items
-
- `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
- handler), and `distribution_finder` is a callable that, passed a path
- item and the importer instance, yields ``Distribution`` instances found on
- that path item. See ``pkg_resources.find_on_path`` for an example."""
- _distribution_finders[importer_type] = distribution_finder
-
-
-def find_distributions(path_item, only=False):
- """Yield distributions accessible via `path_item`"""
- importer = get_importer(path_item)
- finder = _find_adapter(_distribution_finders, importer)
- return finder(importer, path_item, only)
-
-
-def find_eggs_in_zip(importer, path_item, only=False):
- """
- Find eggs in zip files; possibly multiple nested eggs.
- """
- if importer.archive.endswith('.whl'):
- # wheels are not supported with this finder
- # they don't have PKG-INFO metadata, and won't ever contain eggs
- return
- metadata = EggMetadata(importer)
- if metadata.has_metadata('PKG-INFO'):
- yield Distribution.from_filename(path_item, metadata=metadata)
- if only:
- # don't yield nested distros
- return
+def register_finder(importer_type, distribution_finder):
+ """Register `distribution_finder` to find distributions in sys.path items
+
+ `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
+ handler), and `distribution_finder` is a callable that, passed a path
+ item and the importer instance, yields ``Distribution`` instances found on
+ that path item. See ``pkg_resources.find_on_path`` for an example."""
+ _distribution_finders[importer_type] = distribution_finder
+
+
+def find_distributions(path_item, only=False):
+ """Yield distributions accessible via `path_item`"""
+ importer = get_importer(path_item)
+ finder = _find_adapter(_distribution_finders, importer)
+ return finder(importer, path_item, only)
+
+
+def find_eggs_in_zip(importer, path_item, only=False):
+ """
+ Find eggs in zip files; possibly multiple nested eggs.
+ """
+ if importer.archive.endswith('.whl'):
+ # wheels are not supported with this finder
+ # they don't have PKG-INFO metadata, and won't ever contain eggs
+ return
+ metadata = EggMetadata(importer)
+ if metadata.has_metadata('PKG-INFO'):
+ yield Distribution.from_filename(path_item, metadata=metadata)
+ if only:
+ # don't yield nested distros
+ return
for subitem in metadata.resource_listdir(''):
if _is_egg_path(subitem):
- subpath = os.path.join(path_item, subitem)
+ subpath = os.path.join(path_item, subitem)
dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
for dist in dists:
- yield dist
+ yield dist
elif subitem.lower().endswith(('.dist-info', '.egg-info')):
subpath = os.path.join(path_item, subitem)
submeta = EggMetadata(zipimport.zipimporter(subpath))
submeta.egg_info = subpath
yield Distribution.from_location(path_item, subitem, submeta)
-
-register_finder(zipimport.zipimporter, find_eggs_in_zip)
-
-def find_nothing(importer, path_item, only=False):
- return ()
+register_finder(zipimport.zipimporter, find_eggs_in_zip)
+
+
+def find_nothing(importer, path_item, only=False):
+ return ()
+
+register_finder(object, find_nothing)
-register_finder(object, find_nothing)
-
def _by_version_descending(names):
"""
@@ -2043,15 +2043,15 @@ def _by_version_descending(names):
return sorted(names, key=_by_version, reverse=True)
-def find_on_path(importer, path_item, only=False):
- """Yield distributions accessible on a sys.path directory"""
- path_item = _normalize_cached(path_item)
-
+def find_on_path(importer, path_item, only=False):
+ """Yield distributions accessible on a sys.path directory"""
+ path_item = _normalize_cached(path_item)
+
if _is_unpacked_egg(path_item):
yield Distribution.from_filename(
path_item, metadata=PathMetadata(
path_item, os.path.join(path_item, 'EGG-INFO')
- )
+ )
)
return
@@ -2169,39 +2169,39 @@ def resolve_egg_link(path):
return next(dist_groups, ())
-register_finder(pkgutil.ImpImporter, find_on_path)
-
-if hasattr(importlib_machinery, 'FileFinder'):
- register_finder(importlib_machinery.FileFinder, find_on_path)
-
-_declare_state('dict', _namespace_handlers={})
-_declare_state('dict', _namespace_packages={})
-
-
-def register_namespace_handler(importer_type, namespace_handler):
- """Register `namespace_handler` to declare namespace packages
-
- `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
- handler), and `namespace_handler` is a callable like this::
-
- def namespace_handler(importer, path_entry, moduleName, module):
- # return a path_entry to use for child packages
-
- Namespace handlers are only called if the importer object has already
- agreed that it can handle the relevant path item, and they should only
- return a subpath if the module __path__ does not already contain an
- equivalent subpath. For an example namespace handler, see
- ``pkg_resources.file_ns_handler``.
- """
- _namespace_handlers[importer_type] = namespace_handler
-
-
-def _handle_ns(packageName, path_item):
- """Ensure that named package includes a subpath of path_item (if needed)"""
-
- importer = get_importer(path_item)
- if importer is None:
- return None
+register_finder(pkgutil.ImpImporter, find_on_path)
+
+if hasattr(importlib_machinery, 'FileFinder'):
+ register_finder(importlib_machinery.FileFinder, find_on_path)
+
+_declare_state('dict', _namespace_handlers={})
+_declare_state('dict', _namespace_packages={})
+
+
+def register_namespace_handler(importer_type, namespace_handler):
+ """Register `namespace_handler` to declare namespace packages
+
+ `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
+ handler), and `namespace_handler` is a callable like this::
+
+ def namespace_handler(importer, path_entry, moduleName, module):
+ # return a path_entry to use for child packages
+
+ Namespace handlers are only called if the importer object has already
+ agreed that it can handle the relevant path item, and they should only
+ return a subpath if the module __path__ does not already contain an
+ equivalent subpath. For an example namespace handler, see
+ ``pkg_resources.file_ns_handler``.
+ """
+ _namespace_handlers[importer_type] = namespace_handler
+
+
+def _handle_ns(packageName, path_item):
+ """Ensure that named package includes a subpath of path_item (if needed)"""
+
+ importer = get_importer(path_item)
+ if importer is None:
+ return None
# use find_spec (PEP 451) and fall-back to find_module (PEP 302)
try:
@@ -2212,34 +2212,34 @@ def _handle_ns(packageName, path_item):
warnings.simplefilter("ignore")
loader = importer.find_module(packageName)
- if loader is None:
- return None
- module = sys.modules.get(packageName)
- if module is None:
- module = sys.modules[packageName] = types.ModuleType(packageName)
- module.__path__ = []
- _set_parent_ns(packageName)
+ if loader is None:
+ return None
+ module = sys.modules.get(packageName)
+ if module is None:
+ module = sys.modules[packageName] = types.ModuleType(packageName)
+ module.__path__ = []
+ _set_parent_ns(packageName)
elif not hasattr(module, '__path__'):
- raise TypeError("Not a package:", packageName)
- handler = _find_adapter(_namespace_handlers, importer)
- subpath = handler(importer, path_item, packageName, module)
- if subpath is not None:
- path = module.__path__
- path.append(subpath)
+ raise TypeError("Not a package:", packageName)
+ handler = _find_adapter(_namespace_handlers, importer)
+ subpath = handler(importer, path_item, packageName, module)
+ if subpath is not None:
+ path = module.__path__
+ path.append(subpath)
importlib.import_module(packageName)
- _rebuild_mod_path(path, packageName, module)
- return subpath
-
-
-def _rebuild_mod_path(orig_path, package_name, module):
- """
- Rebuild module.__path__ ensuring that all entries are ordered
- corresponding to their sys.path order
- """
- sys_path = [_normalize_cached(p) for p in sys.path]
+ _rebuild_mod_path(path, packageName, module)
+ return subpath
+
+
+def _rebuild_mod_path(orig_path, package_name, module):
+ """
+ Rebuild module.__path__ ensuring that all entries are ordered
+ corresponding to their sys.path order
+ """
+ sys_path = [_normalize_cached(p) for p in sys.path]
def safe_sys_path_index(entry):
- """
+ """
Workaround for #520 and #513.
"""
try:
@@ -2249,13 +2249,13 @@ def _rebuild_mod_path(orig_path, package_name, module):
def position_in_sys_path(path):
"""
- Return the ordinal of the path based on its position in sys.path
- """
+ Return the ordinal of the path based on its position in sys.path
+ """
path_parts = path.split(os.sep)
module_parts = package_name.count('.') + 1
parts = path_parts[:-module_parts]
return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))
-
+
new_path = sorted(orig_path, key=position_in_sys_path)
new_path = [_normalize_cached(p) for p in new_path]
@@ -2263,86 +2263,86 @@ def _rebuild_mod_path(orig_path, package_name, module):
module.__path__[:] = new_path
else:
module.__path__ = new_path
-
-
-def declare_namespace(packageName):
- """Declare that package 'packageName' is a namespace package"""
-
- _imp.acquire_lock()
- try:
- if packageName in _namespace_packages:
- return
-
+
+
+def declare_namespace(packageName):
+ """Declare that package 'packageName' is a namespace package"""
+
+ _imp.acquire_lock()
+ try:
+ if packageName in _namespace_packages:
+ return
+
path = sys.path
parent, _, _ = packageName.rpartition('.')
if parent:
- declare_namespace(parent)
- if parent not in _namespace_packages:
- __import__(parent)
- try:
- path = sys.modules[parent].__path__
+ declare_namespace(parent)
+ if parent not in _namespace_packages:
+ __import__(parent)
+ try:
+ path = sys.modules[parent].__path__
except AttributeError as e:
raise TypeError("Not a package:", parent) from e
-
- # Track what packages are namespaces, so when new path items are added,
- # they can be updated
+
+ # Track what packages are namespaces, so when new path items are added,
+ # they can be updated
_namespace_packages.setdefault(parent or None, []).append(packageName)
_namespace_packages.setdefault(packageName, [])
-
- for path_item in path:
- # Ensure all the parent's path items are reflected in the child,
- # if they apply
- _handle_ns(packageName, path_item)
-
- finally:
- _imp.release_lock()
-
-
-def fixup_namespace_packages(path_item, parent=None):
- """Ensure that previously-declared namespace packages include path_item"""
- _imp.acquire_lock()
- try:
+
+ for path_item in path:
+ # Ensure all the parent's path items are reflected in the child,
+ # if they apply
+ _handle_ns(packageName, path_item)
+
+ finally:
+ _imp.release_lock()
+
+
+def fixup_namespace_packages(path_item, parent=None):
+ """Ensure that previously-declared namespace packages include path_item"""
+ _imp.acquire_lock()
+ try:
for package in _namespace_packages.get(parent, ()):
- subpath = _handle_ns(package, path_item)
- if subpath:
- fixup_namespace_packages(subpath, package)
- finally:
- _imp.release_lock()
-
-
-def file_ns_handler(importer, path_item, packageName, module):
- """Compute an ns-package subpath for a filesystem or zipfile importer"""
-
- subpath = os.path.join(path_item, packageName.split('.')[-1])
- normalized = _normalize_cached(subpath)
- for item in module.__path__:
+ subpath = _handle_ns(package, path_item)
+ if subpath:
+ fixup_namespace_packages(subpath, package)
+ finally:
+ _imp.release_lock()
+
+
+def file_ns_handler(importer, path_item, packageName, module):
+ """Compute an ns-package subpath for a filesystem or zipfile importer"""
+
+ subpath = os.path.join(path_item, packageName.split('.')[-1])
+ normalized = _normalize_cached(subpath)
+ for item in module.__path__:
if _normalize_cached(item) == normalized:
- break
- else:
- # Only return the path if it's not already there
- return subpath
-
-
-register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)
-register_namespace_handler(zipimport.zipimporter, file_ns_handler)
-
-if hasattr(importlib_machinery, 'FileFinder'):
- register_namespace_handler(importlib_machinery.FileFinder, file_ns_handler)
-
-
-def null_ns_handler(importer, path_item, packageName, module):
- return None
-
-
-register_namespace_handler(object, null_ns_handler)
-
-
-def normalize_path(filename):
- """Normalize a file/dir name for comparison purposes"""
+ break
+ else:
+ # Only return the path if it's not already there
+ return subpath
+
+
+register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)
+register_namespace_handler(zipimport.zipimporter, file_ns_handler)
+
+if hasattr(importlib_machinery, 'FileFinder'):
+ register_namespace_handler(importlib_machinery.FileFinder, file_ns_handler)
+
+
+def null_ns_handler(importer, path_item, packageName, module):
+ return None
+
+
+register_namespace_handler(object, null_ns_handler)
+
+
+def normalize_path(filename):
+ """Normalize a file/dir name for comparison purposes"""
return os.path.normcase(os.path.realpath(os.path.normpath(
_cygwin_patch(filename))))
-
+
def _cygwin_patch(filename): # pragma: nocover
"""
@@ -2355,13 +2355,13 @@ def _cygwin_patch(filename): # pragma: nocover
return os.path.abspath(filename) if sys.platform == 'cygwin' else filename
-def _normalize_cached(filename, _cache={}):
- try:
- return _cache[filename]
- except KeyError:
- _cache[filename] = result = normalize_path(filename)
- return result
-
+def _normalize_cached(filename, _cache={}):
+ try:
+ return _cache[filename]
+ except KeyError:
+ _cache[filename] = result = normalize_path(filename)
+ return result
+
def _is_egg_path(path):
"""
@@ -2378,27 +2378,27 @@ def _is_zip_egg(path):
)
-def _is_unpacked_egg(path):
- """
- Determine if given path appears to be an unpacked egg.
- """
- return (
+def _is_unpacked_egg(path):
+ """
+ Determine if given path appears to be an unpacked egg.
+ """
+ return (
path.lower().endswith('.egg') and
os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO'))
- )
-
-
-def _set_parent_ns(packageName):
- parts = packageName.split('.')
- name = parts.pop()
- if parts:
- parent = '.'.join(parts)
- setattr(sys.modules[parent], name, sys.modules[packageName])
-
-
+ )
+
+
+def _set_parent_ns(packageName):
+ parts = packageName.split('.')
+ name = parts.pop()
+ if parts:
+ parent = '.'.join(parts)
+ setattr(sys.modules[parent], name, sys.modules[packageName])
+
+
def _nonblank(str):
return str and not str.startswith('#')
-
+
@functools.singledispatch
def yield_lines(iterable):
@@ -2411,310 +2411,310 @@ def _(text):
return filter(_nonblank, map(str.strip, text.splitlines()))
-MODULE = re.compile(r"\w+(\.\w+)*$").match
-EGG_NAME = re.compile(
- r"""
- (?P<name>[^-]+) (
- -(?P<ver>[^-]+) (
- -py(?P<pyver>[^-]+) (
- -(?P<plat>.+)
- )?
- )?
- )?
- """,
- re.VERBOSE | re.IGNORECASE,
-).match
-
-
+MODULE = re.compile(r"\w+(\.\w+)*$").match
+EGG_NAME = re.compile(
+ r"""
+ (?P<name>[^-]+) (
+ -(?P<ver>[^-]+) (
+ -py(?P<pyver>[^-]+) (
+ -(?P<plat>.+)
+ )?
+ )?
+ )?
+ """,
+ re.VERBOSE | re.IGNORECASE,
+).match
+
+
class EntryPoint:
- """Object representing an advertised importable object"""
-
- def __init__(self, name, module_name, attrs=(), extras=(), dist=None):
- if not MODULE(module_name):
- raise ValueError("Invalid module name", module_name)
- self.name = name
- self.module_name = module_name
- self.attrs = tuple(attrs)
+ """Object representing an advertised importable object"""
+
+ def __init__(self, name, module_name, attrs=(), extras=(), dist=None):
+ if not MODULE(module_name):
+ raise ValueError("Invalid module name", module_name)
+ self.name = name
+ self.module_name = module_name
+ self.attrs = tuple(attrs)
self.extras = tuple(extras)
- self.dist = dist
-
- def __str__(self):
- s = "%s = %s" % (self.name, self.module_name)
- if self.attrs:
- s += ':' + '.'.join(self.attrs)
- if self.extras:
- s += ' [%s]' % ','.join(self.extras)
- return s
-
- def __repr__(self):
- return "EntryPoint.parse(%r)" % str(self)
-
- def load(self, require=True, *args, **kwargs):
- """
- Require packages for this EntryPoint, then resolve it.
- """
- if not require or args or kwargs:
- warnings.warn(
- "Parameters to load are deprecated. Call .resolve and "
- ".require separately.",
+ self.dist = dist
+
+ def __str__(self):
+ s = "%s = %s" % (self.name, self.module_name)
+ if self.attrs:
+ s += ':' + '.'.join(self.attrs)
+ if self.extras:
+ s += ' [%s]' % ','.join(self.extras)
+ return s
+
+ def __repr__(self):
+ return "EntryPoint.parse(%r)" % str(self)
+
+ def load(self, require=True, *args, **kwargs):
+ """
+ Require packages for this EntryPoint, then resolve it.
+ """
+ if not require or args or kwargs:
+ warnings.warn(
+ "Parameters to load are deprecated. Call .resolve and "
+ ".require separately.",
PkgResourcesDeprecationWarning,
- stacklevel=2,
- )
- if require:
- self.require(*args, **kwargs)
- return self.resolve()
-
- def resolve(self):
- """
- Resolve the entry point from its module and attrs.
- """
- module = __import__(self.module_name, fromlist=['__name__'], level=0)
- try:
- return functools.reduce(getattr, self.attrs, module)
- except AttributeError as exc:
+ stacklevel=2,
+ )
+ if require:
+ self.require(*args, **kwargs)
+ return self.resolve()
+
+ def resolve(self):
+ """
+ Resolve the entry point from its module and attrs.
+ """
+ module = __import__(self.module_name, fromlist=['__name__'], level=0)
+ try:
+ return functools.reduce(getattr, self.attrs, module)
+ except AttributeError as exc:
raise ImportError(str(exc)) from exc
-
- def require(self, env=None, installer=None):
- if self.extras and not self.dist:
- raise UnknownExtra("Can't require() without a distribution", self)
+
+ def require(self, env=None, installer=None):
+ if self.extras and not self.dist:
+ raise UnknownExtra("Can't require() without a distribution", self)
# Get the requirements for this entry point with all its extras and
# then resolve them. We have to pass `extras` along when resolving so
# that the working set knows what extras we want. Otherwise, for
# dist-info distributions, the working set will assume that the
# requirements for that extra are purely optional and skip over them.
- reqs = self.dist.requires(self.extras)
+ reqs = self.dist.requires(self.extras)
items = working_set.resolve(reqs, env, installer, extras=self.extras)
- list(map(working_set.add, items))
-
- pattern = re.compile(
- r'\s*'
- r'(?P<name>.+?)\s*'
- r'=\s*'
- r'(?P<module>[\w.]+)\s*'
- r'(:\s*(?P<attr>[\w.]+))?\s*'
- r'(?P<extras>\[.*\])?\s*$'
- )
-
- @classmethod
- def parse(cls, src, dist=None):
- """Parse a single entry point from string `src`
-
- Entry point syntax follows the form::
-
- name = some.module:some.attr [extra1, extra2]
-
- The entry name and module name are required, but the ``:attrs`` and
- ``[extras]`` parts are optional
- """
- m = cls.pattern.match(src)
- if not m:
- msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
- raise ValueError(msg, src)
- res = m.groupdict()
- extras = cls._parse_extras(res['extras'])
- attrs = res['attr'].split('.') if res['attr'] else ()
- return cls(res['name'], res['module'], attrs, extras, dist)
-
- @classmethod
- def _parse_extras(cls, extras_spec):
- if not extras_spec:
- return ()
- req = Requirement.parse('x' + extras_spec)
- if req.specs:
- raise ValueError()
- return req.extras
-
- @classmethod
- def parse_group(cls, group, lines, dist=None):
- """Parse an entry point group"""
- if not MODULE(group):
- raise ValueError("Invalid group name", group)
- this = {}
- for line in yield_lines(lines):
- ep = cls.parse(line, dist)
- if ep.name in this:
- raise ValueError("Duplicate entry point", group, ep.name)
+ list(map(working_set.add, items))
+
+ pattern = re.compile(
+ r'\s*'
+ r'(?P<name>.+?)\s*'
+ r'=\s*'
+ r'(?P<module>[\w.]+)\s*'
+ r'(:\s*(?P<attr>[\w.]+))?\s*'
+ r'(?P<extras>\[.*\])?\s*$'
+ )
+
+ @classmethod
+ def parse(cls, src, dist=None):
+ """Parse a single entry point from string `src`
+
+ Entry point syntax follows the form::
+
+ name = some.module:some.attr [extra1, extra2]
+
+ The entry name and module name are required, but the ``:attrs`` and
+ ``[extras]`` parts are optional
+ """
+ m = cls.pattern.match(src)
+ if not m:
+ msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
+ raise ValueError(msg, src)
+ res = m.groupdict()
+ extras = cls._parse_extras(res['extras'])
+ attrs = res['attr'].split('.') if res['attr'] else ()
+ return cls(res['name'], res['module'], attrs, extras, dist)
+
+ @classmethod
+ def _parse_extras(cls, extras_spec):
+ if not extras_spec:
+ return ()
+ req = Requirement.parse('x' + extras_spec)
+ if req.specs:
+ raise ValueError()
+ return req.extras
+
+ @classmethod
+ def parse_group(cls, group, lines, dist=None):
+ """Parse an entry point group"""
+ if not MODULE(group):
+ raise ValueError("Invalid group name", group)
+ this = {}
+ for line in yield_lines(lines):
+ ep = cls.parse(line, dist)
+ if ep.name in this:
+ raise ValueError("Duplicate entry point", group, ep.name)
this[ep.name] = ep
- return this
-
- @classmethod
- def parse_map(cls, data, dist=None):
- """Parse a map of entry point groups"""
- if isinstance(data, dict):
- data = data.items()
- else:
- data = split_sections(data)
- maps = {}
- for group, lines in data:
- if group is None:
- if not lines:
- continue
- raise ValueError("Entry points must be listed in groups")
- group = group.strip()
- if group in maps:
- raise ValueError("Duplicate group name", group)
- maps[group] = cls.parse_group(group, lines, dist)
- return maps
-
-
-def _version_from_file(lines):
- """
- Given an iterable of lines from a Metadata file, return
- the value of the Version field, if present, or None otherwise.
- """
+ return this
+
+ @classmethod
+ def parse_map(cls, data, dist=None):
+ """Parse a map of entry point groups"""
+ if isinstance(data, dict):
+ data = data.items()
+ else:
+ data = split_sections(data)
+ maps = {}
+ for group, lines in data:
+ if group is None:
+ if not lines:
+ continue
+ raise ValueError("Entry points must be listed in groups")
+ group = group.strip()
+ if group in maps:
+ raise ValueError("Duplicate group name", group)
+ maps[group] = cls.parse_group(group, lines, dist)
+ return maps
+
+
+def _version_from_file(lines):
+ """
+ Given an iterable of lines from a Metadata file, return
+ the value of the Version field, if present, or None otherwise.
+ """
def is_version_line(line):
return line.lower().startswith('version:')
- version_lines = filter(is_version_line, lines)
- line = next(iter(version_lines), '')
- _, _, value = line.partition(':')
- return safe_version(value.strip()) or None
-
-
+ version_lines = filter(is_version_line, lines)
+ line = next(iter(version_lines), '')
+ _, _, value = line.partition(':')
+ return safe_version(value.strip()) or None
+
+
class Distribution:
- """Wrap an actual or potential sys.path entry w/metadata"""
- PKG_INFO = 'PKG-INFO'
-
+ """Wrap an actual or potential sys.path entry w/metadata"""
+ PKG_INFO = 'PKG-INFO'
+
def __init__(
self, location=None, metadata=None, project_name=None,
- version=None, py_version=PY_MAJOR, platform=None,
- precedence=EGG_DIST):
- self.project_name = safe_name(project_name or 'Unknown')
- if version is not None:
- self._version = safe_version(version)
- self.py_version = py_version
- self.platform = platform
- self.location = location
- self.precedence = precedence
- self._provider = metadata or empty_provider
-
- @classmethod
- def from_location(cls, location, basename, metadata=None, **kw):
+ version=None, py_version=PY_MAJOR, platform=None,
+ precedence=EGG_DIST):
+ self.project_name = safe_name(project_name or 'Unknown')
+ if version is not None:
+ self._version = safe_version(version)
+ self.py_version = py_version
+ self.platform = platform
+ self.location = location
+ self.precedence = precedence
+ self._provider = metadata or empty_provider
+
+ @classmethod
+ def from_location(cls, location, basename, metadata=None, **kw):
project_name, version, py_version, platform = [None] * 4
- basename, ext = os.path.splitext(basename)
- if ext.lower() in _distributionImpl:
- cls = _distributionImpl[ext.lower()]
-
- match = EGG_NAME(basename)
- if match:
- project_name, version, py_version, platform = match.group(
- 'name', 'ver', 'pyver', 'plat'
- )
- return cls(
- location, metadata, project_name=project_name, version=version,
- py_version=py_version, platform=platform, **kw
- )._reload_version()
-
- def _reload_version(self):
- return self
-
- @property
- def hashcmp(self):
- return (
- self.parsed_version,
- self.precedence,
- self.key,
+ basename, ext = os.path.splitext(basename)
+ if ext.lower() in _distributionImpl:
+ cls = _distributionImpl[ext.lower()]
+
+ match = EGG_NAME(basename)
+ if match:
+ project_name, version, py_version, platform = match.group(
+ 'name', 'ver', 'pyver', 'plat'
+ )
+ return cls(
+ location, metadata, project_name=project_name, version=version,
+ py_version=py_version, platform=platform, **kw
+ )._reload_version()
+
+ def _reload_version(self):
+ return self
+
+ @property
+ def hashcmp(self):
+ return (
+ self.parsed_version,
+ self.precedence,
+ self.key,
self.location,
- self.py_version or '',
- self.platform or '',
- )
-
- def __hash__(self):
- return hash(self.hashcmp)
-
- def __lt__(self, other):
- return self.hashcmp < other.hashcmp
-
- def __le__(self, other):
- return self.hashcmp <= other.hashcmp
-
- def __gt__(self, other):
- return self.hashcmp > other.hashcmp
-
- def __ge__(self, other):
- return self.hashcmp >= other.hashcmp
-
- def __eq__(self, other):
- if not isinstance(other, self.__class__):
- # It's not a Distribution, so they are not equal
- return False
- return self.hashcmp == other.hashcmp
-
- def __ne__(self, other):
- return not self == other
-
- # These properties have to be lazy so that we don't have to load any
- # metadata until/unless it's actually needed. (i.e., some distributions
- # may not know their name or version without loading PKG-INFO)
-
- @property
- def key(self):
- try:
- return self._key
- except AttributeError:
- self._key = key = self.project_name.lower()
- return key
-
- @property
- def parsed_version(self):
- if not hasattr(self, "_parsed_version"):
- self._parsed_version = parse_version(self.version)
-
- return self._parsed_version
-
- def _warn_legacy_version(self):
- LV = packaging.version.LegacyVersion
- is_legacy = isinstance(self._parsed_version, LV)
- if not is_legacy:
- return
-
- # While an empty version is technically a legacy version and
- # is not a valid PEP 440 version, it's also unlikely to
- # actually come from someone and instead it is more likely that
- # it comes from setuptools attempting to parse a filename and
- # including it in the list. So for that we'll gate this warning
- # on if the version is anything at all or not.
- if not self.version:
- return
-
- tmpl = textwrap.dedent("""
- '{project_name} ({version})' is being parsed as a legacy,
- non PEP 440,
- version. You may find odd behavior and sort order.
- In particular it will be sorted as less than 0.0. It
- is recommended to migrate to PEP 440 compatible
- versions.
- """).strip().replace('\n', ' ')
-
- warnings.warn(tmpl.format(**vars(self)), PEP440Warning)
-
- @property
- def version(self):
- try:
- return self._version
+ self.py_version or '',
+ self.platform or '',
+ )
+
+ def __hash__(self):
+ return hash(self.hashcmp)
+
+ def __lt__(self, other):
+ return self.hashcmp < other.hashcmp
+
+ def __le__(self, other):
+ return self.hashcmp <= other.hashcmp
+
+ def __gt__(self, other):
+ return self.hashcmp > other.hashcmp
+
+ def __ge__(self, other):
+ return self.hashcmp >= other.hashcmp
+
+ def __eq__(self, other):
+ if not isinstance(other, self.__class__):
+ # It's not a Distribution, so they are not equal
+ return False
+ return self.hashcmp == other.hashcmp
+
+ def __ne__(self, other):
+ return not self == other
+
+ # These properties have to be lazy so that we don't have to load any
+ # metadata until/unless it's actually needed. (i.e., some distributions
+ # may not know their name or version without loading PKG-INFO)
+
+ @property
+ def key(self):
+ try:
+ return self._key
+ except AttributeError:
+ self._key = key = self.project_name.lower()
+ return key
+
+ @property
+ def parsed_version(self):
+ if not hasattr(self, "_parsed_version"):
+ self._parsed_version = parse_version(self.version)
+
+ return self._parsed_version
+
+ def _warn_legacy_version(self):
+ LV = packaging.version.LegacyVersion
+ is_legacy = isinstance(self._parsed_version, LV)
+ if not is_legacy:
+ return
+
+ # While an empty version is technically a legacy version and
+ # is not a valid PEP 440 version, it's also unlikely to
+ # actually come from someone and instead it is more likely that
+ # it comes from setuptools attempting to parse a filename and
+ # including it in the list. So for that we'll gate this warning
+ # on if the version is anything at all or not.
+ if not self.version:
+ return
+
+ tmpl = textwrap.dedent("""
+ '{project_name} ({version})' is being parsed as a legacy,
+ non PEP 440,
+ version. You may find odd behavior and sort order.
+ In particular it will be sorted as less than 0.0. It
+ is recommended to migrate to PEP 440 compatible
+ versions.
+ """).strip().replace('\n', ' ')
+
+ warnings.warn(tmpl.format(**vars(self)), PEP440Warning)
+
+ @property
+ def version(self):
+ try:
+ return self._version
except AttributeError as e:
version = self._get_version()
- if version is None:
+ if version is None:
path = self._get_metadata_path_for_display(self.PKG_INFO)
msg = (
"Missing 'Version:' header and/or {} file at path: {}"
).format(self.PKG_INFO, path)
raise ValueError(msg, self) from e
- return version
-
- @property
- def _dep_map(self):
+ return version
+
+ @property
+ def _dep_map(self):
"""
A map of extra to its list of (direct) requirements
for this distribution, including the null extra.
"""
- try:
- return self.__dep_map
- except AttributeError:
+ try:
+ return self.__dep_map
+ except AttributeError:
self.__dep_map = self._filter_extras(self._build_dep_map())
return self.__dep_map
-
+
@staticmethod
def _filter_extras(dm):
"""
@@ -2744,20 +2744,20 @@ class Distribution:
dm.setdefault(extra, []).extend(parse_requirements(reqs))
return dm
- def requires(self, extras=()):
- """List of Requirements needed for this distro if `extras` are used"""
- dm = self._dep_map
- deps = []
- deps.extend(dm.get(None, ()))
- for ext in extras:
- try:
- deps.extend(dm[safe_extra(ext)])
+ def requires(self, extras=()):
+ """List of Requirements needed for this distro if `extras` are used"""
+ dm = self._dep_map
+ deps = []
+ deps.extend(dm.get(None, ()))
+ for ext in extras:
+ try:
+ deps.extend(dm[safe_extra(ext)])
except KeyError as e:
- raise UnknownExtra(
- "%s has no such extra feature %r" % (self, ext)
+ raise UnknownExtra(
+ "%s has no such extra feature %r" % (self, ext)
) from e
- return deps
-
+ return deps
+
def _get_metadata_path_for_display(self, name):
"""
Return the path to the given metadata file, if available.
@@ -2775,11 +2775,11 @@ class Distribution:
return path
- def _get_metadata(self, name):
- if self.has_metadata(name):
- for line in self.get_metadata_lines(name):
- yield line
-
+ def _get_metadata(self, name):
+ if self.has_metadata(name):
+ for line in self.get_metadata_lines(name):
+ yield line
+
def _get_version(self):
lines = self._get_metadata(self.PKG_INFO)
version = _version_from_file(lines)
@@ -2787,47 +2787,47 @@ class Distribution:
return version
def activate(self, path=None, replace=False):
- """Ensure distribution is importable on `path` (default=sys.path)"""
- if path is None:
- path = sys.path
+ """Ensure distribution is importable on `path` (default=sys.path)"""
+ if path is None:
+ path = sys.path
self.insert_on(path, replace=replace)
- if path is sys.path:
- fixup_namespace_packages(self.location)
- for pkg in self._get_metadata('namespace_packages.txt'):
- if pkg in sys.modules:
- declare_namespace(pkg)
-
- def egg_name(self):
- """Return what this distribution's standard .egg filename should be"""
- filename = "%s-%s-py%s" % (
- to_filename(self.project_name), to_filename(self.version),
- self.py_version or PY_MAJOR
- )
-
- if self.platform:
- filename += '-' + self.platform
- return filename
-
- def __repr__(self):
- if self.location:
- return "%s (%s)" % (self, self.location)
- else:
- return str(self)
-
- def __str__(self):
- try:
- version = getattr(self, 'version', None)
- except ValueError:
- version = None
- version = version or "[unknown version]"
- return "%s %s" % (self.project_name, version)
-
- def __getattr__(self, attr):
- """Delegate all unrecognized public attributes to .metadata provider"""
- if attr.startswith('_'):
- raise AttributeError(attr)
- return getattr(self._provider, attr)
-
+ if path is sys.path:
+ fixup_namespace_packages(self.location)
+ for pkg in self._get_metadata('namespace_packages.txt'):
+ if pkg in sys.modules:
+ declare_namespace(pkg)
+
+ def egg_name(self):
+ """Return what this distribution's standard .egg filename should be"""
+ filename = "%s-%s-py%s" % (
+ to_filename(self.project_name), to_filename(self.version),
+ self.py_version or PY_MAJOR
+ )
+
+ if self.platform:
+ filename += '-' + self.platform
+ return filename
+
+ def __repr__(self):
+ if self.location:
+ return "%s (%s)" % (self, self.location)
+ else:
+ return str(self)
+
+ def __str__(self):
+ try:
+ version = getattr(self, 'version', None)
+ except ValueError:
+ version = None
+ version = version or "[unknown version]"
+ return "%s %s" % (self.project_name, version)
+
+ def __getattr__(self, attr):
+ """Delegate all unrecognized public attributes to .metadata provider"""
+ if attr.startswith('_'):
+ raise AttributeError(attr)
+ return getattr(self._provider, attr)
+
def __dir__(self):
return list(
set(super(Distribution, self).__dir__())
@@ -2837,49 +2837,49 @@ class Distribution:
)
)
- @classmethod
- def from_filename(cls, filename, metadata=None, **kw):
- return cls.from_location(
- _normalize_cached(filename), os.path.basename(filename), metadata,
- **kw
- )
-
- def as_requirement(self):
- """Return a ``Requirement`` that matches this distribution exactly"""
- if isinstance(self.parsed_version, packaging.version.Version):
- spec = "%s==%s" % (self.project_name, self.parsed_version)
- else:
- spec = "%s===%s" % (self.project_name, self.parsed_version)
-
- return Requirement.parse(spec)
-
- def load_entry_point(self, group, name):
- """Return the `name` entry point of `group` or raise ImportError"""
- ep = self.get_entry_info(group, name)
- if ep is None:
- raise ImportError("Entry point %r not found" % ((group, name),))
- return ep.load()
-
- def get_entry_map(self, group=None):
- """Return the entry point map for `group`, or the full entry map"""
- try:
- ep_map = self._ep_map
- except AttributeError:
- ep_map = self._ep_map = EntryPoint.parse_map(
- self._get_metadata('entry_points.txt'), self
- )
- if group is not None:
+ @classmethod
+ def from_filename(cls, filename, metadata=None, **kw):
+ return cls.from_location(
+ _normalize_cached(filename), os.path.basename(filename), metadata,
+ **kw
+ )
+
+ def as_requirement(self):
+ """Return a ``Requirement`` that matches this distribution exactly"""
+ if isinstance(self.parsed_version, packaging.version.Version):
+ spec = "%s==%s" % (self.project_name, self.parsed_version)
+ else:
+ spec = "%s===%s" % (self.project_name, self.parsed_version)
+
+ return Requirement.parse(spec)
+
+ def load_entry_point(self, group, name):
+ """Return the `name` entry point of `group` or raise ImportError"""
+ ep = self.get_entry_info(group, name)
+ if ep is None:
+ raise ImportError("Entry point %r not found" % ((group, name),))
+ return ep.load()
+
+ def get_entry_map(self, group=None):
+ """Return the entry point map for `group`, or the full entry map"""
+ try:
+ ep_map = self._ep_map
+ except AttributeError:
+ ep_map = self._ep_map = EntryPoint.parse_map(
+ self._get_metadata('entry_points.txt'), self
+ )
+ if group is not None:
return ep_map.get(group, {})
- return ep_map
-
- def get_entry_info(self, group, name):
- """Return the EntryPoint object for `group`+`name`, or ``None``"""
- return self.get_entry_map(group).get(name)
-
+ return ep_map
+
+ def get_entry_info(self, group, name):
+ """Return the EntryPoint object for `group`+`name`, or ``None``"""
+ return self.get_entry_map(group).get(name)
+
# FIXME: 'Distribution.insert_on' is too complex (13)
def insert_on(self, path, loc=None, replace=False): # noqa: C901
"""Ensure self.location is on path
-
+
If replace=False (default):
- If location is already in path anywhere, do nothing.
- Else:
@@ -2897,195 +2897,195 @@ class Distribution:
- Else: add it to the front of path.
"""
- loc = loc or self.location
- if not loc:
- return
-
- nloc = _normalize_cached(loc)
- bdir = os.path.dirname(nloc)
+ loc = loc or self.location
+ if not loc:
+ return
+
+ nloc = _normalize_cached(loc)
+ bdir = os.path.dirname(nloc)
npath = [(p and _normalize_cached(p) or p) for p in path]
-
- for p, item in enumerate(npath):
- if item == nloc:
+
+ for p, item in enumerate(npath):
+ if item == nloc:
if replace:
break
else:
# don't modify path (even removing duplicates) if
# found and not replace
return
- elif item == bdir and self.precedence == EGG_DIST:
- # if it's an .egg, give it precedence over its directory
+ elif item == bdir and self.precedence == EGG_DIST:
+ # if it's an .egg, give it precedence over its directory
# UNLESS it's already been added to sys.path and replace=False
if (not replace) and nloc in npath[p:]:
return
- if path is sys.path:
- self.check_version_conflict()
- path.insert(p, loc)
- npath.insert(p, nloc)
- break
- else:
- if path is sys.path:
- self.check_version_conflict()
- if replace:
- path.insert(0, loc)
- else:
- path.append(loc)
- return
-
- # p is the spot where we found or inserted loc; now remove duplicates
- while True:
- try:
+ if path is sys.path:
+ self.check_version_conflict()
+ path.insert(p, loc)
+ npath.insert(p, nloc)
+ break
+ else:
+ if path is sys.path:
+ self.check_version_conflict()
+ if replace:
+ path.insert(0, loc)
+ else:
+ path.append(loc)
+ return
+
+ # p is the spot where we found or inserted loc; now remove duplicates
+ while True:
+ try:
np = npath.index(nloc, p + 1)
- except ValueError:
- break
- else:
- del npath[np], path[np]
- # ha!
- p = np
-
- return
-
- def check_version_conflict(self):
- if self.key == 'setuptools':
- # ignore the inevitable setuptools self-conflicts :(
- return
-
- nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
- loc = normalize_path(self.location)
- for modname in self._get_metadata('top_level.txt'):
- if (modname not in sys.modules or modname in nsp
- or modname in _namespace_packages):
- continue
- if modname in ('pkg_resources', 'setuptools', 'site'):
- continue
- fn = getattr(sys.modules[modname], '__file__', None)
- if fn and (normalize_path(fn).startswith(loc) or
- fn.startswith(self.location)):
- continue
- issue_warning(
- "Module %s was already imported from %s, but %s is being added"
- " to sys.path" % (modname, fn, self.location),
- )
-
- def has_version(self):
- try:
- self.version
- except ValueError:
- issue_warning("Unbuilt egg for " + repr(self))
- return False
- return True
-
+ except ValueError:
+ break
+ else:
+ del npath[np], path[np]
+ # ha!
+ p = np
+
+ return
+
+ def check_version_conflict(self):
+ if self.key == 'setuptools':
+ # ignore the inevitable setuptools self-conflicts :(
+ return
+
+ nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
+ loc = normalize_path(self.location)
+ for modname in self._get_metadata('top_level.txt'):
+ if (modname not in sys.modules or modname in nsp
+ or modname in _namespace_packages):
+ continue
+ if modname in ('pkg_resources', 'setuptools', 'site'):
+ continue
+ fn = getattr(sys.modules[modname], '__file__', None)
+ if fn and (normalize_path(fn).startswith(loc) or
+ fn.startswith(self.location)):
+ continue
+ issue_warning(
+ "Module %s was already imported from %s, but %s is being added"
+ " to sys.path" % (modname, fn, self.location),
+ )
+
+ def has_version(self):
+ try:
+ self.version
+ except ValueError:
+ issue_warning("Unbuilt egg for " + repr(self))
+ return False
+ return True
+
def clone(self, **kw):
- """Copy this distribution, substituting in any changed keyword args"""
- names = 'project_name version py_version platform location precedence'
- for attr in names.split():
- kw.setdefault(attr, getattr(self, attr, None))
- kw.setdefault('metadata', self._provider)
- return self.__class__(**kw)
-
- @property
- def extras(self):
- return [dep for dep in self._dep_map if dep]
-
-
-class EggInfoDistribution(Distribution):
- def _reload_version(self):
- """
- Packages installed by distutils (e.g. numpy or scipy),
- which uses an old safe_version, and so
- their version numbers can get mangled when
- converted to filenames (e.g., 1.11.0.dev0+2329eae to
- 1.11.0.dev0_2329eae). These distributions will not be
- parsed properly
- downstream by Distribution and safe_version, so
- take an extra step and try to get the version number from
- the metadata file itself instead of the filename.
- """
+ """Copy this distribution, substituting in any changed keyword args"""
+ names = 'project_name version py_version platform location precedence'
+ for attr in names.split():
+ kw.setdefault(attr, getattr(self, attr, None))
+ kw.setdefault('metadata', self._provider)
+ return self.__class__(**kw)
+
+ @property
+ def extras(self):
+ return [dep for dep in self._dep_map if dep]
+
+
+class EggInfoDistribution(Distribution):
+ def _reload_version(self):
+ """
+ Packages installed by distutils (e.g. numpy or scipy),
+ which uses an old safe_version, and so
+ their version numbers can get mangled when
+ converted to filenames (e.g., 1.11.0.dev0+2329eae to
+ 1.11.0.dev0_2329eae). These distributions will not be
+ parsed properly
+ downstream by Distribution and safe_version, so
+ take an extra step and try to get the version number from
+ the metadata file itself instead of the filename.
+ """
md_version = self._get_version()
- if md_version:
- self._version = md_version
- return self
-
-
-class DistInfoDistribution(Distribution):
+ if md_version:
+ self._version = md_version
+ return self
+
+
+class DistInfoDistribution(Distribution):
"""
Wrap an actual or potential sys.path entry
w/metadata, .dist-info style.
"""
- PKG_INFO = 'METADATA'
- EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
-
- @property
- def _parsed_pkg_info(self):
- """Parse and cache metadata"""
- try:
- return self._pkg_info
- except AttributeError:
- metadata = self.get_metadata(self.PKG_INFO)
- self._pkg_info = email.parser.Parser().parsestr(metadata)
- return self._pkg_info
-
- @property
- def _dep_map(self):
- try:
- return self.__dep_map
- except AttributeError:
- self.__dep_map = self._compute_dependencies()
- return self.__dep_map
-
- def _compute_dependencies(self):
- """Recompute this distribution's dependencies."""
- dm = self.__dep_map = {None: []}
-
- reqs = []
- # Including any condition expressions
- for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
+ PKG_INFO = 'METADATA'
+ EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
+
+ @property
+ def _parsed_pkg_info(self):
+ """Parse and cache metadata"""
+ try:
+ return self._pkg_info
+ except AttributeError:
+ metadata = self.get_metadata(self.PKG_INFO)
+ self._pkg_info = email.parser.Parser().parsestr(metadata)
+ return self._pkg_info
+
+ @property
+ def _dep_map(self):
+ try:
+ return self.__dep_map
+ except AttributeError:
+ self.__dep_map = self._compute_dependencies()
+ return self.__dep_map
+
+ def _compute_dependencies(self):
+ """Recompute this distribution's dependencies."""
+ dm = self.__dep_map = {None: []}
+
+ reqs = []
+ # Including any condition expressions
+ for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
reqs.extend(parse_requirements(req))
-
- def reqs_for_extra(extra):
- for req in reqs:
+
+ def reqs_for_extra(extra):
+ for req in reqs:
if not req.marker or req.marker.evaluate({'extra': extra}):
- yield req
-
- common = frozenset(reqs_for_extra(None))
- dm[None].extend(common)
-
- for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
+ yield req
+
+ common = frozenset(reqs_for_extra(None))
+ dm[None].extend(common)
+
+ for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
s_extra = safe_extra(extra.strip())
dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common)
-
- return dm
-
-
-_distributionImpl = {
- '.egg': Distribution,
- '.egg-info': EggInfoDistribution,
- '.dist-info': DistInfoDistribution,
+
+ return dm
+
+
+_distributionImpl = {
+ '.egg': Distribution,
+ '.egg-info': EggInfoDistribution,
+ '.dist-info': DistInfoDistribution,
}
-
-
+
+
def issue_warning(*args, **kw):
- level = 1
- g = globals()
- try:
- # find the first stack frame that is *not* code in
- # the pkg_resources module, to use for the warning
- while sys._getframe(level).f_globals is g:
- level += 1
- except ValueError:
- pass
- warnings.warn(stacklevel=level + 1, *args, **kw)
-
-
-def parse_requirements(strs):
- """Yield ``Requirement`` objects for each specification in `strs`
-
- `strs` must be a string, or a (possibly-nested) iterable thereof.
- """
- # create a steppable iterator, so we can handle \-continuations
- lines = iter(yield_lines(strs))
-
- for line in lines:
+ level = 1
+ g = globals()
+ try:
+ # find the first stack frame that is *not* code in
+ # the pkg_resources module, to use for the warning
+ while sys._getframe(level).f_globals is g:
+ level += 1
+ except ValueError:
+ pass
+ warnings.warn(stacklevel=level + 1, *args, **kw)
+
+
+def parse_requirements(strs):
+ """Yield ``Requirement`` objects for each specification in `strs`
+
+ `strs` must be a string, or a (possibly-nested) iterable thereof.
+ """
+ # create a steppable iterator, so we can handle \-continuations
+ lines = iter(yield_lines(strs))
+
+ for line in lines:
# Drop comments -- a hash without a space may be in a URL.
if ' #' in line:
line = line[:line.find(' #')]
@@ -3097,64 +3097,64 @@ def parse_requirements(strs):
except StopIteration:
return
yield Requirement(line)
-
-
+
+
class RequirementParseError(packaging.requirements.InvalidRequirement):
"Compatibility wrapper for InvalidRequirement"
class Requirement(packaging.requirements.Requirement):
def __init__(self, requirement_string):
- """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
+ """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
super(Requirement, self).__init__(requirement_string)
self.unsafe_name = self.name
project_name = safe_name(self.name)
- self.project_name, self.key = project_name, project_name.lower()
+ self.project_name, self.key = project_name, project_name.lower()
self.specs = [
(spec.operator, spec.version) for spec in self.specifier]
self.extras = tuple(map(safe_extra, self.extras))
- self.hashCmp = (
- self.key,
+ self.hashCmp = (
+ self.key,
self.url,
- self.specifier,
- frozenset(self.extras),
+ self.specifier,
+ frozenset(self.extras),
str(self.marker) if self.marker else None,
- )
- self.__hash = hash(self.hashCmp)
-
- def __eq__(self, other):
- return (
- isinstance(other, Requirement) and
- self.hashCmp == other.hashCmp
- )
-
- def __ne__(self, other):
- return not self == other
-
- def __contains__(self, item):
- if isinstance(item, Distribution):
- if item.key != self.key:
- return False
-
- item = item.version
-
- # Allow prereleases always in order to match the previous behavior of
- # this method. In the future this should be smarter and follow PEP 440
- # more accurately.
- return self.specifier.contains(item, prereleases=True)
-
- def __hash__(self):
- return self.__hash
-
+ )
+ self.__hash = hash(self.hashCmp)
+
+ def __eq__(self, other):
+ return (
+ isinstance(other, Requirement) and
+ self.hashCmp == other.hashCmp
+ )
+
+ def __ne__(self, other):
+ return not self == other
+
+ def __contains__(self, item):
+ if isinstance(item, Distribution):
+ if item.key != self.key:
+ return False
+
+ item = item.version
+
+ # Allow prereleases always in order to match the previous behavior of
+ # this method. In the future this should be smarter and follow PEP 440
+ # more accurately.
+ return self.specifier.contains(item, prereleases=True)
+
+ def __hash__(self):
+ return self.__hash
+
def __repr__(self):
return "Requirement.parse(%r)" % str(self)
-
- @staticmethod
- def parse(s):
- req, = parse_requirements(s)
- return req
-
-
+
+ @staticmethod
+ def parse(s):
+ req, = parse_requirements(s)
+ return req
+
+
def _always_object(classes):
"""
Ensure object appears in the mro even
@@ -3165,70 +3165,70 @@ def _always_object(classes):
return classes
-def _find_adapter(registry, ob):
- """Return an adapter factory for `ob` from `registry`"""
+def _find_adapter(registry, ob):
+ """Return an adapter factory for `ob` from `registry`"""
types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
for t in types:
- if t in registry:
- return registry[t]
-
-
-def ensure_directory(path):
- """Ensure that the parent directory of `path` exists"""
- dirname = os.path.dirname(path)
+ if t in registry:
+ return registry[t]
+
+
+def ensure_directory(path):
+ """Ensure that the parent directory of `path` exists"""
+ dirname = os.path.dirname(path)
os.makedirs(dirname, exist_ok=True)
-
-
-def _bypass_ensure_directory(path):
- """Sandbox-bypassing version of ensure_directory()"""
- if not WRITE_SUPPORT:
- raise IOError('"os.mkdir" not supported on this platform.')
- dirname, filename = split(path)
- if dirname and filename and not isdir(dirname):
- _bypass_ensure_directory(dirname)
+
+
+def _bypass_ensure_directory(path):
+ """Sandbox-bypassing version of ensure_directory()"""
+ if not WRITE_SUPPORT:
+ raise IOError('"os.mkdir" not supported on this platform.')
+ dirname, filename = split(path)
+ if dirname and filename and not isdir(dirname):
+ _bypass_ensure_directory(dirname)
try:
mkdir(dirname, 0o755)
except FileExistsError:
pass
-
-
-def split_sections(s):
- """Split a string or iterable thereof into (section, content) pairs
-
- Each ``section`` is a stripped version of the section header ("[section]")
- and each ``content`` is a list of stripped lines excluding blank lines and
- comment-only lines. If there are any such lines before the first section
- header, they're returned in a first ``section`` of ``None``.
- """
- section = None
- content = []
- for line in yield_lines(s):
- if line.startswith("["):
- if line.endswith("]"):
- if section or content:
- yield section, content
- section = line[1:-1].strip()
- content = []
- else:
- raise ValueError("Invalid section heading", line)
- else:
- content.append(line)
-
- # wrap up last segment
- yield section, content
-
+
+
+def split_sections(s):
+ """Split a string or iterable thereof into (section, content) pairs
+
+ Each ``section`` is a stripped version of the section header ("[section]")
+ and each ``content`` is a list of stripped lines excluding blank lines and
+ comment-only lines. If there are any such lines before the first section
+ header, they're returned in a first ``section`` of ``None``.
+ """
+ section = None
+ content = []
+ for line in yield_lines(s):
+ if line.startswith("["):
+ if line.endswith("]"):
+ if section or content:
+ yield section, content
+ section = line[1:-1].strip()
+ content = []
+ else:
+ raise ValueError("Invalid section heading", line)
+ else:
+ content.append(line)
+
+ # wrap up last segment
+ yield section, content
+
def _mkstemp(*args, **kw):
- old_open = os.open
- try:
- # temporarily bypass sandboxing
- os.open = os_open
+ old_open = os.open
+ try:
+ # temporarily bypass sandboxing
+ os.open = os_open
return tempfile.mkstemp(*args, **kw)
- finally:
- # and then put it back
- os.open = old_open
-
-
+ finally:
+ # and then put it back
+ os.open = old_open
+
+
# Yandex resource support
from __res import Y_PYTHON_SOURCE_ROOT, ResourceImporter, executable
from library.python import resource
@@ -3313,31 +3313,31 @@ register_finder(ResourceImporter, find_in_res)
register_loader_type(ResourceImporter, ResProvider.from_module)
-# Silence the PEP440Warning by default, so that end users don't get hit by it
-# randomly just because they use pkg_resources. We want to append the rule
-# because we want earlier uses of filterwarnings to take precedence over this
-# one.
-warnings.filterwarnings("ignore", category=PEP440Warning, append=True)
-
-
-# from jaraco.functools 1.3
-def _call_aside(f, *args, **kwargs):
- f(*args, **kwargs)
- return f
-
-
-@_call_aside
-def _initialize(g=globals()):
- "Set up global resource manager (deliberately not state-saved)"
- manager = ResourceManager()
- g['_manager'] = manager
+# Silence the PEP440Warning by default, so that end users don't get hit by it
+# randomly just because they use pkg_resources. We want to append the rule
+# because we want earlier uses of filterwarnings to take precedence over this
+# one.
+warnings.filterwarnings("ignore", category=PEP440Warning, append=True)
+
+
+# from jaraco.functools 1.3
+def _call_aside(f, *args, **kwargs):
+ f(*args, **kwargs)
+ return f
+
+
+@_call_aside
+def _initialize(g=globals()):
+ "Set up global resource manager (deliberately not state-saved)"
+ manager = ResourceManager()
+ g['_manager'] = manager
g.update(
(name, getattr(manager, name))
for name in dir(manager)
if not name.startswith('_')
)
-
-
+
+
class PkgResourcesDeprecationWarning(Warning):
"""
Base class for warning about deprecations in ``pkg_resources``
@@ -3347,28 +3347,28 @@ class PkgResourcesDeprecationWarning(Warning):
"""
-@_call_aside
-def _initialize_master_working_set():
- """
- Prepare the master working set and make the ``require()``
- API available.
-
- This function has explicit effects on the global state
- of pkg_resources. It is intended to be invoked once at
- the initialization of this module.
-
- Invocation by other packages is unsupported and done
- at their own risk.
- """
- working_set = WorkingSet._build_master()
- _declare_state('object', working_set=working_set)
-
- require = working_set.require
- iter_entry_points = working_set.iter_entry_points
- add_activation_listener = working_set.subscribe
- run_script = working_set.run_script
- # backward compatibility
- run_main = run_script
+@_call_aside
+def _initialize_master_working_set():
+ """
+ Prepare the master working set and make the ``require()``
+ API available.
+
+ This function has explicit effects on the global state
+ of pkg_resources. It is intended to be invoked once at
+ the initialization of this module.
+
+ Invocation by other packages is unsupported and done
+ at their own risk.
+ """
+ working_set = WorkingSet._build_master()
+ _declare_state('object', working_set=working_set)
+
+ require = working_set.require
+ iter_entry_points = working_set.iter_entry_points
+ add_activation_listener = working_set.subscribe
+ run_script = working_set.run_script
+ # backward compatibility
+ run_main = run_script
# Activate all distributions already on sys.path with replace=False and
# ensure that all distributions added to the working set in the future
# (e.g. by calling ``require()``) will get activated as well,
@@ -3382,6 +3382,6 @@ def _initialize_master_working_set():
existing=False,
)
working_set.entries = []
- # match order
- list(map(working_set.add_entry, sys.path))
- globals().update(locals())
+ # match order
+ list(map(working_set.add_entry, sys.path))
+ globals().update(locals())
diff --git a/contrib/python/setuptools/py3/setuptools/__init__.py b/contrib/python/setuptools/py3/setuptools/__init__.py
index 11abd83c3d..9d6f0bc0dd 100644
--- a/contrib/python/setuptools/py3/setuptools/__init__.py
+++ b/contrib/python/setuptools/py3/setuptools/__init__.py
@@ -1,26 +1,26 @@
-"""Extensions to the 'distutils' for large or complex distributions"""
-
+"""Extensions to the 'distutils' for large or complex distributions"""
+
from fnmatch import fnmatchcase
import functools
-import os
+import os
import re
import _distutils_hack.override # noqa: F401
-import distutils.core
+import distutils.core
from distutils.errors import DistutilsOptionError
-from distutils.util import convert_path
-
+from distutils.util import convert_path
+
from ._deprecation_warning import SetuptoolsDeprecationWarning
-
-import setuptools.version
-from setuptools.extension import Extension
+
+import setuptools.version
+from setuptools.extension import Extension
from setuptools.dist import Distribution
-from setuptools.depends import Require
+from setuptools.depends import Require
from . import monkey
-
-__all__ = [
+
+__all__ = [
'setup',
'Distribution',
'Command',
@@ -29,36 +29,36 @@ __all__ = [
'SetuptoolsDeprecationWarning',
'find_packages',
'find_namespace_packages',
-]
-
-__version__ = setuptools.version.__version__
-
-bootstrap_install_from = None
-
-
+]
+
+__version__ = setuptools.version.__version__
+
+bootstrap_install_from = None
+
+
class PackageFinder:
"""
Generate a list of all Python packages found within a directory
"""
- @classmethod
- def find(cls, where='.', exclude=(), include=('*',)):
- """Return a list all Python packages found within directory 'where'
-
+ @classmethod
+ def find(cls, where='.', exclude=(), include=('*',)):
+ """Return a list all Python packages found within directory 'where'
+
'where' is the root directory which will be searched for packages. It
should be supplied as a "cross-platform" (i.e. URL-style) path; it will
be converted to the appropriate local path syntax.
- 'exclude' is a sequence of package names to exclude; '*' can be used
- as a wildcard in the names, such that 'foo.*' will exclude all
- subpackages of 'foo' (but not 'foo' itself).
-
- 'include' is a sequence of package names to include. If it's
- specified, only the named packages will be included. If it's not
- specified, all found packages will be included. 'include' can contain
- shell style wildcard patterns just like 'exclude'.
- """
-
+ 'exclude' is a sequence of package names to exclude; '*' can be used
+ as a wildcard in the names, such that 'foo.*' will exclude all
+ subpackages of 'foo' (but not 'foo' itself).
+
+ 'include' is a sequence of package names to include. If it's
+ specified, only the named packages will be included. If it's not
+ specified, all found packages will be included. 'include' can contain
+ shell style wildcard patterns just like 'exclude'.
+ """
+
return list(
cls._find_packages_iter(
convert_path(where),
@@ -66,23 +66,23 @@ class PackageFinder:
cls._build_filter(*include),
)
)
-
+
@classmethod
def _find_packages_iter(cls, where, exclude, include):
- """
+ """
All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter.
- """
+ """
for root, dirs, files in os.walk(where, followlinks=True):
# Copy dirs to iterate over it, then empty dirs.
all_dirs = dirs[:]
dirs[:] = []
-
+
for dir in all_dirs:
full_path = os.path.join(root, dir)
rel_path = os.path.relpath(full_path, where)
package = rel_path.replace(os.path.sep, '.')
-
+
# Skip directory trees that are not valid packages
if '.' in dir or not cls._looks_like_package(full_path):
continue
@@ -95,30 +95,30 @@ class PackageFinder:
# down there, even if the parent was excluded.
dirs.append(dir)
- @staticmethod
- def _looks_like_package(path):
+ @staticmethod
+ def _looks_like_package(path):
"""Does a directory look like a package?"""
- return os.path.isfile(os.path.join(path, '__init__.py'))
-
- @staticmethod
- def _build_filter(*patterns):
- """
- Given a list of patterns, return a callable that will be true only if
+ return os.path.isfile(os.path.join(path, '__init__.py'))
+
+ @staticmethod
+ def _build_filter(*patterns):
+ """
+ Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
- """
- return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
-
+ """
+ return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
-class PEP420PackageFinder(PackageFinder):
- @staticmethod
- def _looks_like_package(path):
- return True
-
-find_packages = PackageFinder.find
+class PEP420PackageFinder(PackageFinder):
+ @staticmethod
+ def _looks_like_package(path):
+ return True
+
+
+find_packages = PackageFinder.find
find_namespace_packages = PEP420PackageFinder.find
-
-
+
+
def _install_setup_requires(attrs):
# Note: do not use `setuptools.Distribution` directly, as
# our PEP 517 backend patch `distutils.core.Distribution`.
@@ -157,21 +157,21 @@ setup.__doc__ = distutils.core.setup.__doc__
_Command = monkey.get_unpatched(distutils.core.Command)
-
-
-class Command(_Command):
- __doc__ = _Command.__doc__
-
- command_consumes_arguments = False
-
- def __init__(self, dist, **kw):
- """
- Construct the command for dist, updating
- vars(self) with any keyword parameters.
- """
- _Command.__init__(self, dist)
- vars(self).update(kw)
-
+
+
+class Command(_Command):
+ __doc__ = _Command.__doc__
+
+ command_consumes_arguments = False
+
+ def __init__(self, dist, **kw):
+ """
+ Construct the command for dist, updating
+ vars(self) with any keyword parameters.
+ """
+ _Command.__init__(self, dist)
+ vars(self).update(kw)
+
def _ensure_stringlike(self, option, what, default=None):
val = getattr(self, option)
if val is None:
@@ -204,36 +204,36 @@ class Command(_Command):
"'%s' must be a list of strings (got %r)" % (option, val)
)
- def reinitialize_command(self, command, reinit_subcommands=0, **kw):
- cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
- vars(cmd).update(kw)
- return cmd
-
-
-def _find_all_simple(path):
- """
- Find all files under 'path'
- """
- results = (
- os.path.join(base, file)
- for base, dirs, files in os.walk(path, followlinks=True)
- for file in files
- )
- return filter(os.path.isfile, results)
-
-
-def findall(dir=os.curdir):
- """
- Find all files under 'dir' and return the list of full filenames.
- Unless dir is '.', return full filenames with dir prepended.
- """
- files = _find_all_simple(dir)
- if dir == os.curdir:
- make_rel = functools.partial(os.path.relpath, start=dir)
- files = map(make_rel, files)
- return list(files)
-
-
+ def reinitialize_command(self, command, reinit_subcommands=0, **kw):
+ cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
+ vars(cmd).update(kw)
+ return cmd
+
+
+def _find_all_simple(path):
+ """
+ Find all files under 'path'
+ """
+ results = (
+ os.path.join(base, file)
+ for base, dirs, files in os.walk(path, followlinks=True)
+ for file in files
+ )
+ return filter(os.path.isfile, results)
+
+
+def findall(dir=os.curdir):
+ """
+ Find all files under 'dir' and return the list of full filenames.
+ Unless dir is '.', return full filenames with dir prepended.
+ """
+ files = _find_all_simple(dir)
+ if dir == os.curdir:
+ make_rel = functools.partial(os.path.relpath, start=dir)
+ files = map(make_rel, files)
+ return list(files)
+
+
class sic(str):
"""Treat this string as-is (https://en.wikipedia.org/wiki/Sic)"""
diff --git a/contrib/python/setuptools/py3/setuptools/archive_util.py b/contrib/python/setuptools/py3/setuptools/archive_util.py
index 1172c588bd..0f70284822 100644
--- a/contrib/python/setuptools/py3/setuptools/archive_util.py
+++ b/contrib/python/setuptools/py3/setuptools/archive_util.py
@@ -1,13 +1,13 @@
-"""Utilities for extracting common archive formats"""
-
-import zipfile
-import tarfile
-import os
-import shutil
-import posixpath
-import contextlib
-from distutils.errors import DistutilsError
-
+"""Utilities for extracting common archive formats"""
+
+import zipfile
+import tarfile
+import os
+import shutil
+import posixpath
+import contextlib
+from distutils.errors import DistutilsError
+
from pkg_resources import ensure_directory
__all__ = [
@@ -16,115 +16,115 @@ __all__ = [
]
-class UnrecognizedFormat(DistutilsError):
- """Couldn't recognize the archive type"""
-
+class UnrecognizedFormat(DistutilsError):
+ """Couldn't recognize the archive type"""
+
def default_filter(src, dst):
- """The default progress/filter callback; returns True for all files"""
- return dst
-
-
+ """The default progress/filter callback; returns True for all files"""
+ return dst
+
+
def unpack_archive(
filename, extract_dir, progress_filter=default_filter,
- drivers=None):
- """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
-
- `progress_filter` is a function taking two arguments: a source path
- internal to the archive ('/'-separated), and a filesystem path where it
- will be extracted. The callback must return the desired extract path
- (which may be the same as the one passed in), or else ``None`` to skip
- that file or directory. The callback can thus be used to report on the
- progress of the extraction, as well as to filter the items extracted or
- alter their extraction paths.
-
- `drivers`, if supplied, must be a non-empty sequence of functions with the
- same signature as this function (minus the `drivers` argument), that raise
- ``UnrecognizedFormat`` if they do not support extracting the designated
- archive type. The `drivers` are tried in sequence until one is found that
- does not raise an error, or until all are exhausted (in which case
- ``UnrecognizedFormat`` is raised). If you do not supply a sequence of
- drivers, the module's ``extraction_drivers`` constant will be used, which
- means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that
- order.
- """
- for driver in drivers or extraction_drivers:
- try:
- driver(filename, extract_dir, progress_filter)
- except UnrecognizedFormat:
- continue
- else:
- return
- else:
- raise UnrecognizedFormat(
- "Not a recognized archive type: %s" % filename
- )
-
-
-def unpack_directory(filename, extract_dir, progress_filter=default_filter):
- """"Unpack" a directory, using the same interface as for archives
-
- Raises ``UnrecognizedFormat`` if `filename` is not a directory
- """
- if not os.path.isdir(filename):
- raise UnrecognizedFormat("%s is not a directory" % filename)
-
- paths = {
- filename: ('', extract_dir),
- }
- for base, dirs, files in os.walk(filename):
- src, dst = paths[base]
- for d in dirs:
- paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d)
- for f in files:
- target = os.path.join(dst, f)
- target = progress_filter(src + f, target)
- if not target:
- # skip non-files
- continue
- ensure_directory(target)
- f = os.path.join(base, f)
- shutil.copyfile(f, target)
- shutil.copystat(f, target)
-
-
-def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
- """Unpack zip `filename` to `extract_dir`
-
- Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
- by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation
- of the `progress_filter` argument.
- """
-
- if not zipfile.is_zipfile(filename):
- raise UnrecognizedFormat("%s is not a zip file" % (filename,))
-
+ drivers=None):
+ """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
+
+ `progress_filter` is a function taking two arguments: a source path
+ internal to the archive ('/'-separated), and a filesystem path where it
+ will be extracted. The callback must return the desired extract path
+ (which may be the same as the one passed in), or else ``None`` to skip
+ that file or directory. The callback can thus be used to report on the
+ progress of the extraction, as well as to filter the items extracted or
+ alter their extraction paths.
+
+ `drivers`, if supplied, must be a non-empty sequence of functions with the
+ same signature as this function (minus the `drivers` argument), that raise
+ ``UnrecognizedFormat`` if they do not support extracting the designated
+ archive type. The `drivers` are tried in sequence until one is found that
+ does not raise an error, or until all are exhausted (in which case
+ ``UnrecognizedFormat`` is raised). If you do not supply a sequence of
+ drivers, the module's ``extraction_drivers`` constant will be used, which
+ means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that
+ order.
+ """
+ for driver in drivers or extraction_drivers:
+ try:
+ driver(filename, extract_dir, progress_filter)
+ except UnrecognizedFormat:
+ continue
+ else:
+ return
+ else:
+ raise UnrecognizedFormat(
+ "Not a recognized archive type: %s" % filename
+ )
+
+
+def unpack_directory(filename, extract_dir, progress_filter=default_filter):
+ """"Unpack" a directory, using the same interface as for archives
+
+ Raises ``UnrecognizedFormat`` if `filename` is not a directory
+ """
+ if not os.path.isdir(filename):
+ raise UnrecognizedFormat("%s is not a directory" % filename)
+
+ paths = {
+ filename: ('', extract_dir),
+ }
+ for base, dirs, files in os.walk(filename):
+ src, dst = paths[base]
+ for d in dirs:
+ paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d)
+ for f in files:
+ target = os.path.join(dst, f)
+ target = progress_filter(src + f, target)
+ if not target:
+ # skip non-files
+ continue
+ ensure_directory(target)
+ f = os.path.join(base, f)
+ shutil.copyfile(f, target)
+ shutil.copystat(f, target)
+
+
+def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
+ """Unpack zip `filename` to `extract_dir`
+
+ Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
+ by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation
+ of the `progress_filter` argument.
+ """
+
+ if not zipfile.is_zipfile(filename):
+ raise UnrecognizedFormat("%s is not a zip file" % (filename,))
+
with zipfile.ZipFile(filename) as z:
- for info in z.infolist():
- name = info.filename
-
- # don't extract absolute paths or ones with .. in them
- if name.startswith('/') or '..' in name.split('/'):
- continue
-
- target = os.path.join(extract_dir, *name.split('/'))
- target = progress_filter(name, target)
- if not target:
- continue
- if name.endswith('/'):
- # directory
- ensure_directory(target)
- else:
- # file
- ensure_directory(target)
- data = z.read(info.filename)
- with open(target, 'wb') as f:
- f.write(data)
- unix_attributes = info.external_attr >> 16
- if unix_attributes:
- os.chmod(target, unix_attributes)
-
-
+ for info in z.infolist():
+ name = info.filename
+
+ # don't extract absolute paths or ones with .. in them
+ if name.startswith('/') or '..' in name.split('/'):
+ continue
+
+ target = os.path.join(extract_dir, *name.split('/'))
+ target = progress_filter(name, target)
+ if not target:
+ continue
+ if name.endswith('/'):
+ # directory
+ ensure_directory(target)
+ else:
+ # file
+ ensure_directory(target)
+ data = z.read(info.filename)
+ with open(target, 'wb') as f:
+ f.write(data)
+ unix_attributes = info.external_attr >> 16
+ if unix_attributes:
+ os.chmod(target, unix_attributes)
+
+
def _resolve_tar_file_or_dir(tar_obj, tar_member_obj):
"""Resolve any links and extract link targets as normal files."""
while tar_member_obj is not None and (
@@ -175,20 +175,20 @@ def _iter_open_tar(tar_obj, extract_dir, progress_filter):
yield member, final_dst
-def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
- """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
-
- Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
- by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
- of the `progress_filter` argument.
- """
- try:
- tarobj = tarfile.open(filename)
+def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
+ """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
+
+ Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
+ by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
+ of the `progress_filter` argument.
+ """
+ try:
+ tarobj = tarfile.open(filename)
except tarfile.TarError as e:
- raise UnrecognizedFormat(
- "%s is not a compressed or uncompressed tar file" % (filename,)
+ raise UnrecognizedFormat(
+ "%s is not a compressed or uncompressed tar file" % (filename,)
) from e
-
+
for member, final_dst in _iter_open_tar(
tarobj, extract_dir, progress_filter,
):
@@ -198,8 +198,8 @@ def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
except tarfile.ExtractError:
# chown/chmod/mkfifo/mknode/makedev failed
pass
-
+
return True
-
-extraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile
+
+extraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile
diff --git a/contrib/python/setuptools/py3/setuptools/command/__init__.py b/contrib/python/setuptools/py3/setuptools/command/__init__.py
index 48180605ee..b966dcea57 100644
--- a/contrib/python/setuptools/py3/setuptools/command/__init__.py
+++ b/contrib/python/setuptools/py3/setuptools/command/__init__.py
@@ -1,8 +1,8 @@
-from distutils.command.bdist import bdist
-import sys
-
-if 'egg' not in bdist.format_commands:
- bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
- bdist.format_commands.append('egg')
-
-del bdist, sys
+from distutils.command.bdist import bdist
+import sys
+
+if 'egg' not in bdist.format_commands:
+ bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
+ bdist.format_commands.append('egg')
+
+del bdist, sys
diff --git a/contrib/python/setuptools/py3/setuptools/command/alias.py b/contrib/python/setuptools/py3/setuptools/command/alias.py
index e96a50c7e1..452a9244ea 100644
--- a/contrib/python/setuptools/py3/setuptools/command/alias.py
+++ b/contrib/python/setuptools/py3/setuptools/command/alias.py
@@ -1,78 +1,78 @@
-from distutils.errors import DistutilsOptionError
-
-from setuptools.command.setopt import edit_config, option_base, config_file
-
-
-def shquote(arg):
- """Quote an argument for later parsing by shlex.split()"""
- for c in '"', "'", "\\", "#":
- if c in arg:
- return repr(arg)
- if arg.split() != [arg]:
- return repr(arg)
- return arg
-
-
-class alias(option_base):
- """Define a shortcut that invokes one or more commands"""
-
- description = "define a shortcut to invoke one or more commands"
- command_consumes_arguments = True
-
- user_options = [
- ('remove', 'r', 'remove (unset) the alias'),
- ] + option_base.user_options
-
- boolean_options = option_base.boolean_options + ['remove']
-
- def initialize_options(self):
- option_base.initialize_options(self)
- self.args = None
- self.remove = None
-
- def finalize_options(self):
- option_base.finalize_options(self)
- if self.remove and len(self.args) != 1:
- raise DistutilsOptionError(
- "Must specify exactly one argument (the alias name) when "
- "using --remove"
- )
-
- def run(self):
- aliases = self.distribution.get_option_dict('aliases')
-
- if not self.args:
- print("Command Aliases")
- print("---------------")
- for alias in aliases:
- print("setup.py alias", format_alias(alias, aliases))
- return
-
- elif len(self.args) == 1:
- alias, = self.args
- if self.remove:
- command = None
- elif alias in aliases:
- print("setup.py alias", format_alias(alias, aliases))
- return
- else:
- print("No alias definition found for %r" % alias)
- return
- else:
- alias = self.args[0]
- command = ' '.join(map(shquote, self.args[1:]))
-
- edit_config(self.filename, {'aliases': {alias: command}}, self.dry_run)
-
-
-def format_alias(name, aliases):
- source, command = aliases[name]
- if source == config_file('global'):
- source = '--global-config '
- elif source == config_file('user'):
- source = '--user-config '
- elif source == config_file('local'):
- source = ''
- else:
- source = '--filename=%r' % source
- return source + name + ' ' + command
+from distutils.errors import DistutilsOptionError
+
+from setuptools.command.setopt import edit_config, option_base, config_file
+
+
+def shquote(arg):
+ """Quote an argument for later parsing by shlex.split()"""
+ for c in '"', "'", "\\", "#":
+ if c in arg:
+ return repr(arg)
+ if arg.split() != [arg]:
+ return repr(arg)
+ return arg
+
+
+class alias(option_base):
+ """Define a shortcut that invokes one or more commands"""
+
+ description = "define a shortcut to invoke one or more commands"
+ command_consumes_arguments = True
+
+ user_options = [
+ ('remove', 'r', 'remove (unset) the alias'),
+ ] + option_base.user_options
+
+ boolean_options = option_base.boolean_options + ['remove']
+
+ def initialize_options(self):
+ option_base.initialize_options(self)
+ self.args = None
+ self.remove = None
+
+ def finalize_options(self):
+ option_base.finalize_options(self)
+ if self.remove and len(self.args) != 1:
+ raise DistutilsOptionError(
+ "Must specify exactly one argument (the alias name) when "
+ "using --remove"
+ )
+
+ def run(self):
+ aliases = self.distribution.get_option_dict('aliases')
+
+ if not self.args:
+ print("Command Aliases")
+ print("---------------")
+ for alias in aliases:
+ print("setup.py alias", format_alias(alias, aliases))
+ return
+
+ elif len(self.args) == 1:
+ alias, = self.args
+ if self.remove:
+ command = None
+ elif alias in aliases:
+ print("setup.py alias", format_alias(alias, aliases))
+ return
+ else:
+ print("No alias definition found for %r" % alias)
+ return
+ else:
+ alias = self.args[0]
+ command = ' '.join(map(shquote, self.args[1:]))
+
+ edit_config(self.filename, {'aliases': {alias: command}}, self.dry_run)
+
+
+def format_alias(name, aliases):
+ source, command = aliases[name]
+ if source == config_file('global'):
+ source = '--global-config '
+ elif source == config_file('user'):
+ source = '--user-config '
+ elif source == config_file('local'):
+ source = ''
+ else:
+ source = '--filename=%r' % source
+ return source + name + ' ' + command
diff --git a/contrib/python/setuptools/py3/setuptools/command/bdist_egg.py b/contrib/python/setuptools/py3/setuptools/command/bdist_egg.py
index 0caee01d3c..e6b1609f7b 100644
--- a/contrib/python/setuptools/py3/setuptools/command/bdist_egg.py
+++ b/contrib/python/setuptools/py3/setuptools/command/bdist_egg.py
@@ -1,35 +1,35 @@
-"""setuptools.command.bdist_egg
-
-Build .egg distributions"""
-
-from distutils.dir_util import remove_tree, mkpath
-from distutils import log
-from types import CodeType
-import sys
-import os
+"""setuptools.command.bdist_egg
+
+Build .egg distributions"""
+
+from distutils.dir_util import remove_tree, mkpath
+from distutils import log
+from types import CodeType
+import sys
+import os
import re
import textwrap
-import marshal
-
-from pkg_resources import get_build_platform, Distribution, ensure_directory
-from setuptools.extension import Library
-from setuptools import Command
-
+import marshal
+
+from pkg_resources import get_build_platform, Distribution, ensure_directory
+from setuptools.extension import Library
+from setuptools import Command
+
from sysconfig import get_path, get_python_version
-
-
+
+
def _get_purelib():
return get_path("purelib")
-
-
-def strip_module(filename):
- if '.' in filename:
- filename = os.path.splitext(filename)[0]
- if filename.endswith('module'):
- filename = filename[:-6]
- return filename
-
-
+
+
+def strip_module(filename):
+ if '.' in filename:
+ filename = os.path.splitext(filename)[0]
+ if filename.endswith('module'):
+ filename = filename[:-6]
+ return filename
+
+
def sorted_walk(dir):
"""Do os.walk in a reproducible way,
independent of indeterministic filesystem readdir order
@@ -40,207 +40,207 @@ def sorted_walk(dir):
yield base, dirs, files
-def write_stub(resource, pyfile):
- _stub_template = textwrap.dedent("""
- def __bootstrap__():
- global __bootstrap__, __loader__, __file__
+def write_stub(resource, pyfile):
+ _stub_template = textwrap.dedent("""
+ def __bootstrap__():
+ global __bootstrap__, __loader__, __file__
import sys, pkg_resources, importlib.util
- __file__ = pkg_resources.resource_filename(__name__, %r)
- __loader__ = None; del __bootstrap__, __loader__
+ __file__ = pkg_resources.resource_filename(__name__, %r)
+ __loader__ = None; del __bootstrap__, __loader__
spec = importlib.util.spec_from_file_location(__name__,__file__)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
- __bootstrap__()
- """).lstrip()
- with open(pyfile, 'w') as f:
- f.write(_stub_template % resource)
-
-
-class bdist_egg(Command):
- description = "create an \"egg\" distribution"
-
- user_options = [
- ('bdist-dir=', 'b',
- "temporary directory for creating the distribution"),
- ('plat-name=', 'p', "platform name to embed in generated filenames "
- "(default: %s)" % get_build_platform()),
- ('exclude-source-files', None,
- "remove all .py files from the generated egg"),
- ('keep-temp', 'k',
- "keep the pseudo-installation tree around after " +
- "creating the distribution archive"),
- ('dist-dir=', 'd',
- "directory to put final built distributions in"),
- ('skip-build', None,
- "skip rebuilding everything (for testing/debugging)"),
- ]
-
- boolean_options = [
- 'keep-temp', 'skip-build', 'exclude-source-files'
- ]
-
- def initialize_options(self):
- self.bdist_dir = None
- self.plat_name = None
- self.keep_temp = 0
- self.dist_dir = None
- self.skip_build = 0
- self.egg_output = None
- self.exclude_source_files = None
-
- def finalize_options(self):
- ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
- self.egg_info = ei_cmd.egg_info
-
- if self.bdist_dir is None:
- bdist_base = self.get_finalized_command('bdist').bdist_base
- self.bdist_dir = os.path.join(bdist_base, 'egg')
-
- if self.plat_name is None:
- self.plat_name = get_build_platform()
-
- self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
-
- if self.egg_output is None:
-
- # Compute filename of the output egg
- basename = Distribution(
- None, None, ei_cmd.egg_name, ei_cmd.egg_version,
- get_python_version(),
- self.distribution.has_ext_modules() and self.plat_name
- ).egg_name()
-
- self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
-
- def do_install_data(self):
- # Hack for packages that install data to install's --install-lib
- self.get_finalized_command('install').install_lib = self.bdist_dir
-
- site_packages = os.path.normcase(os.path.realpath(_get_purelib()))
- old, self.distribution.data_files = self.distribution.data_files, []
-
- for item in old:
- if isinstance(item, tuple) and len(item) == 2:
- if os.path.isabs(item[0]):
- realpath = os.path.realpath(item[0])
- normalized = os.path.normcase(realpath)
- if normalized == site_packages or normalized.startswith(
- site_packages + os.sep
- ):
- item = realpath[len(site_packages) + 1:], item[1]
- # XXX else: raise ???
- self.distribution.data_files.append(item)
-
- try:
+ __bootstrap__()
+ """).lstrip()
+ with open(pyfile, 'w') as f:
+ f.write(_stub_template % resource)
+
+
+class bdist_egg(Command):
+ description = "create an \"egg\" distribution"
+
+ user_options = [
+ ('bdist-dir=', 'b',
+ "temporary directory for creating the distribution"),
+ ('plat-name=', 'p', "platform name to embed in generated filenames "
+ "(default: %s)" % get_build_platform()),
+ ('exclude-source-files', None,
+ "remove all .py files from the generated egg"),
+ ('keep-temp', 'k',
+ "keep the pseudo-installation tree around after " +
+ "creating the distribution archive"),
+ ('dist-dir=', 'd',
+ "directory to put final built distributions in"),
+ ('skip-build', None,
+ "skip rebuilding everything (for testing/debugging)"),
+ ]
+
+ boolean_options = [
+ 'keep-temp', 'skip-build', 'exclude-source-files'
+ ]
+
+ def initialize_options(self):
+ self.bdist_dir = None
+ self.plat_name = None
+ self.keep_temp = 0
+ self.dist_dir = None
+ self.skip_build = 0
+ self.egg_output = None
+ self.exclude_source_files = None
+
+ def finalize_options(self):
+ ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
+ self.egg_info = ei_cmd.egg_info
+
+ if self.bdist_dir is None:
+ bdist_base = self.get_finalized_command('bdist').bdist_base
+ self.bdist_dir = os.path.join(bdist_base, 'egg')
+
+ if self.plat_name is None:
+ self.plat_name = get_build_platform()
+
+ self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
+
+ if self.egg_output is None:
+
+ # Compute filename of the output egg
+ basename = Distribution(
+ None, None, ei_cmd.egg_name, ei_cmd.egg_version,
+ get_python_version(),
+ self.distribution.has_ext_modules() and self.plat_name
+ ).egg_name()
+
+ self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
+
+ def do_install_data(self):
+ # Hack for packages that install data to install's --install-lib
+ self.get_finalized_command('install').install_lib = self.bdist_dir
+
+ site_packages = os.path.normcase(os.path.realpath(_get_purelib()))
+ old, self.distribution.data_files = self.distribution.data_files, []
+
+ for item in old:
+ if isinstance(item, tuple) and len(item) == 2:
+ if os.path.isabs(item[0]):
+ realpath = os.path.realpath(item[0])
+ normalized = os.path.normcase(realpath)
+ if normalized == site_packages or normalized.startswith(
+ site_packages + os.sep
+ ):
+ item = realpath[len(site_packages) + 1:], item[1]
+ # XXX else: raise ???
+ self.distribution.data_files.append(item)
+
+ try:
log.info("installing package data to %s", self.bdist_dir)
- self.call_command('install_data', force=0, root=None)
- finally:
- self.distribution.data_files = old
-
- def get_outputs(self):
- return [self.egg_output]
-
- def call_command(self, cmdname, **kw):
- """Invoke reinitialized command `cmdname` with keyword args"""
- for dirname in INSTALL_DIRECTORY_ATTRS:
- kw.setdefault(dirname, self.bdist_dir)
- kw.setdefault('skip_build', self.skip_build)
- kw.setdefault('dry_run', self.dry_run)
- cmd = self.reinitialize_command(cmdname, **kw)
- self.run_command(cmdname)
- return cmd
-
+ self.call_command('install_data', force=0, root=None)
+ finally:
+ self.distribution.data_files = old
+
+ def get_outputs(self):
+ return [self.egg_output]
+
+ def call_command(self, cmdname, **kw):
+ """Invoke reinitialized command `cmdname` with keyword args"""
+ for dirname in INSTALL_DIRECTORY_ATTRS:
+ kw.setdefault(dirname, self.bdist_dir)
+ kw.setdefault('skip_build', self.skip_build)
+ kw.setdefault('dry_run', self.dry_run)
+ cmd = self.reinitialize_command(cmdname, **kw)
+ self.run_command(cmdname)
+ return cmd
+
def run(self): # noqa: C901 # is too complex (14) # FIXME
- # Generate metadata first
- self.run_command("egg_info")
- # We run install_lib before install_data, because some data hacks
- # pull their data path from the install_lib command.
+ # Generate metadata first
+ self.run_command("egg_info")
+ # We run install_lib before install_data, because some data hacks
+ # pull their data path from the install_lib command.
log.info("installing library code to %s", self.bdist_dir)
- instcmd = self.get_finalized_command('install')
- old_root = instcmd.root
- instcmd.root = None
- if self.distribution.has_c_libraries() and not self.skip_build:
- self.run_command('build_clib')
- cmd = self.call_command('install_lib', warn_dir=0)
- instcmd.root = old_root
-
- all_outputs, ext_outputs = self.get_ext_outputs()
- self.stubs = []
- to_compile = []
- for (p, ext_name) in enumerate(ext_outputs):
- filename, ext = os.path.splitext(ext_name)
- pyfile = os.path.join(self.bdist_dir, strip_module(filename) +
- '.py')
- self.stubs.append(pyfile)
+ instcmd = self.get_finalized_command('install')
+ old_root = instcmd.root
+ instcmd.root = None
+ if self.distribution.has_c_libraries() and not self.skip_build:
+ self.run_command('build_clib')
+ cmd = self.call_command('install_lib', warn_dir=0)
+ instcmd.root = old_root
+
+ all_outputs, ext_outputs = self.get_ext_outputs()
+ self.stubs = []
+ to_compile = []
+ for (p, ext_name) in enumerate(ext_outputs):
+ filename, ext = os.path.splitext(ext_name)
+ pyfile = os.path.join(self.bdist_dir, strip_module(filename) +
+ '.py')
+ self.stubs.append(pyfile)
log.info("creating stub loader for %s", ext_name)
- if not self.dry_run:
- write_stub(os.path.basename(ext_name), pyfile)
- to_compile.append(pyfile)
- ext_outputs[p] = ext_name.replace(os.sep, '/')
-
- if to_compile:
- cmd.byte_compile(to_compile)
- if self.distribution.data_files:
- self.do_install_data()
-
- # Make the EGG-INFO directory
- archive_root = self.bdist_dir
- egg_info = os.path.join(archive_root, 'EGG-INFO')
- self.mkpath(egg_info)
- if self.distribution.scripts:
- script_dir = os.path.join(egg_info, 'scripts')
+ if not self.dry_run:
+ write_stub(os.path.basename(ext_name), pyfile)
+ to_compile.append(pyfile)
+ ext_outputs[p] = ext_name.replace(os.sep, '/')
+
+ if to_compile:
+ cmd.byte_compile(to_compile)
+ if self.distribution.data_files:
+ self.do_install_data()
+
+ # Make the EGG-INFO directory
+ archive_root = self.bdist_dir
+ egg_info = os.path.join(archive_root, 'EGG-INFO')
+ self.mkpath(egg_info)
+ if self.distribution.scripts:
+ script_dir = os.path.join(egg_info, 'scripts')
log.info("installing scripts to %s", script_dir)
- self.call_command('install_scripts', install_dir=script_dir,
- no_ep=1)
-
- self.copy_metadata_to(egg_info)
- native_libs = os.path.join(egg_info, "native_libs.txt")
- if all_outputs:
+ self.call_command('install_scripts', install_dir=script_dir,
+ no_ep=1)
+
+ self.copy_metadata_to(egg_info)
+ native_libs = os.path.join(egg_info, "native_libs.txt")
+ if all_outputs:
log.info("writing %s", native_libs)
- if not self.dry_run:
- ensure_directory(native_libs)
- libs_file = open(native_libs, 'wt')
- libs_file.write('\n'.join(all_outputs))
- libs_file.write('\n')
- libs_file.close()
- elif os.path.isfile(native_libs):
+ if not self.dry_run:
+ ensure_directory(native_libs)
+ libs_file = open(native_libs, 'wt')
+ libs_file.write('\n'.join(all_outputs))
+ libs_file.write('\n')
+ libs_file.close()
+ elif os.path.isfile(native_libs):
log.info("removing %s", native_libs)
- if not self.dry_run:
- os.unlink(native_libs)
-
- write_safety_flag(
- os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()
- )
-
- if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):
- log.warn(
- "WARNING: 'depends.txt' will not be used by setuptools 0.6!\n"
- "Use the install_requires/extras_require setup() args instead."
- )
-
- if self.exclude_source_files:
- self.zap_pyfiles()
-
- # Make the archive
- make_zipfile(self.egg_output, archive_root, verbose=self.verbose,
- dry_run=self.dry_run, mode=self.gen_header())
- if not self.keep_temp:
- remove_tree(self.bdist_dir, dry_run=self.dry_run)
-
- # Add to 'Distribution.dist_files' so that the "upload" command works
- getattr(self.distribution, 'dist_files', []).append(
- ('bdist_egg', get_python_version(), self.egg_output))
-
- def zap_pyfiles(self):
- log.info("Removing .py files from temporary directory")
- for base, dirs, files in walk_egg(self.bdist_dir):
- for name in files:
+ if not self.dry_run:
+ os.unlink(native_libs)
+
+ write_safety_flag(
+ os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()
+ )
+
+ if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):
+ log.warn(
+ "WARNING: 'depends.txt' will not be used by setuptools 0.6!\n"
+ "Use the install_requires/extras_require setup() args instead."
+ )
+
+ if self.exclude_source_files:
+ self.zap_pyfiles()
+
+ # Make the archive
+ make_zipfile(self.egg_output, archive_root, verbose=self.verbose,
+ dry_run=self.dry_run, mode=self.gen_header())
+ if not self.keep_temp:
+ remove_tree(self.bdist_dir, dry_run=self.dry_run)
+
+ # Add to 'Distribution.dist_files' so that the "upload" command works
+ getattr(self.distribution, 'dist_files', []).append(
+ ('bdist_egg', get_python_version(), self.egg_output))
+
+ def zap_pyfiles(self):
+ log.info("Removing .py files from temporary directory")
+ for base, dirs, files in walk_egg(self.bdist_dir):
+ for name in files:
path = os.path.join(base, name)
- if name.endswith('.py'):
- log.debug("Deleting %s", path)
- os.unlink(path)
-
+ if name.endswith('.py'):
+ log.debug("Deleting %s", path)
+ os.unlink(path)
+
if base.endswith('__pycache__'):
path_old = path
@@ -257,200 +257,200 @@ class bdist_egg(Command):
pass
os.rename(path_old, path_new)
- def zip_safe(self):
- safe = getattr(self.distribution, 'zip_safe', None)
- if safe is not None:
- return safe
- log.warn("zip_safe flag not set; analyzing archive contents...")
- return analyze_egg(self.bdist_dir, self.stubs)
-
- def gen_header(self):
+ def zip_safe(self):
+ safe = getattr(self.distribution, 'zip_safe', None)
+ if safe is not None:
+ return safe
+ log.warn("zip_safe flag not set; analyzing archive contents...")
+ return analyze_egg(self.bdist_dir, self.stubs)
+
+ def gen_header(self):
return 'w'
-
- def copy_metadata_to(self, target_dir):
- "Copy metadata (egg info) to the target_dir"
- # normalize the path (so that a forward-slash in egg_info will
- # match using startswith below)
- norm_egg_info = os.path.normpath(self.egg_info)
- prefix = os.path.join(norm_egg_info, '')
- for path in self.ei_cmd.filelist.files:
- if path.startswith(prefix):
- target = os.path.join(target_dir, path[len(prefix):])
- ensure_directory(target)
- self.copy_file(path, target)
-
- def get_ext_outputs(self):
- """Get a list of relative paths to C extensions in the output distro"""
-
- all_outputs = []
- ext_outputs = []
-
- paths = {self.bdist_dir: ''}
+
+ def copy_metadata_to(self, target_dir):
+ "Copy metadata (egg info) to the target_dir"
+ # normalize the path (so that a forward-slash in egg_info will
+ # match using startswith below)
+ norm_egg_info = os.path.normpath(self.egg_info)
+ prefix = os.path.join(norm_egg_info, '')
+ for path in self.ei_cmd.filelist.files:
+ if path.startswith(prefix):
+ target = os.path.join(target_dir, path[len(prefix):])
+ ensure_directory(target)
+ self.copy_file(path, target)
+
+ def get_ext_outputs(self):
+ """Get a list of relative paths to C extensions in the output distro"""
+
+ all_outputs = []
+ ext_outputs = []
+
+ paths = {self.bdist_dir: ''}
for base, dirs, files in sorted_walk(self.bdist_dir):
- for filename in files:
- if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS:
- all_outputs.append(paths[base] + filename)
- for filename in dirs:
- paths[os.path.join(base, filename)] = (paths[base] +
- filename + '/')
-
- if self.distribution.has_ext_modules():
- build_cmd = self.get_finalized_command('build_ext')
- for ext in build_cmd.extensions:
- if isinstance(ext, Library):
- continue
- fullname = build_cmd.get_ext_fullname(ext.name)
- filename = build_cmd.get_ext_filename(fullname)
- if not os.path.basename(filename).startswith('dl-'):
- if os.path.exists(os.path.join(self.bdist_dir, filename)):
- ext_outputs.append(filename)
-
- return all_outputs, ext_outputs
-
-
-NATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())
-
-
-def walk_egg(egg_dir):
- """Walk an unpacked egg's contents, skipping the metadata directory"""
+ for filename in files:
+ if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS:
+ all_outputs.append(paths[base] + filename)
+ for filename in dirs:
+ paths[os.path.join(base, filename)] = (paths[base] +
+ filename + '/')
+
+ if self.distribution.has_ext_modules():
+ build_cmd = self.get_finalized_command('build_ext')
+ for ext in build_cmd.extensions:
+ if isinstance(ext, Library):
+ continue
+ fullname = build_cmd.get_ext_fullname(ext.name)
+ filename = build_cmd.get_ext_filename(fullname)
+ if not os.path.basename(filename).startswith('dl-'):
+ if os.path.exists(os.path.join(self.bdist_dir, filename)):
+ ext_outputs.append(filename)
+
+ return all_outputs, ext_outputs
+
+
+NATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())
+
+
+def walk_egg(egg_dir):
+ """Walk an unpacked egg's contents, skipping the metadata directory"""
walker = sorted_walk(egg_dir)
- base, dirs, files = next(walker)
- if 'EGG-INFO' in dirs:
- dirs.remove('EGG-INFO')
- yield base, dirs, files
- for bdf in walker:
- yield bdf
-
-
-def analyze_egg(egg_dir, stubs):
- # check for existing flag in EGG-INFO
- for flag, fn in safety_flags.items():
- if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
- return flag
- if not can_scan():
- return False
- safe = True
- for base, dirs, files in walk_egg(egg_dir):
- for name in files:
- if name.endswith('.py') or name.endswith('.pyw'):
- continue
- elif name.endswith('.pyc') or name.endswith('.pyo'):
- # always scan, even if we already know we're not safe
- safe = scan_module(egg_dir, base, name, stubs) and safe
- return safe
-
-
-def write_safety_flag(egg_dir, safe):
- # Write or remove zip safety flag file(s)
- for flag, fn in safety_flags.items():
- fn = os.path.join(egg_dir, fn)
- if os.path.exists(fn):
- if safe is None or bool(safe) != flag:
- os.unlink(fn)
- elif safe is not None and bool(safe) == flag:
- f = open(fn, 'wt')
- f.write('\n')
- f.close()
-
-
-safety_flags = {
- True: 'zip-safe',
- False: 'not-zip-safe',
-}
-
-
-def scan_module(egg_dir, base, name, stubs):
- """Check whether module possibly uses unsafe-for-zipfile stuff"""
-
- filename = os.path.join(base, name)
- if filename[:-1] in stubs:
- return True # Extension module
- pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
- module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
+ base, dirs, files = next(walker)
+ if 'EGG-INFO' in dirs:
+ dirs.remove('EGG-INFO')
+ yield base, dirs, files
+ for bdf in walker:
+ yield bdf
+
+
+def analyze_egg(egg_dir, stubs):
+ # check for existing flag in EGG-INFO
+ for flag, fn in safety_flags.items():
+ if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
+ return flag
+ if not can_scan():
+ return False
+ safe = True
+ for base, dirs, files in walk_egg(egg_dir):
+ for name in files:
+ if name.endswith('.py') or name.endswith('.pyw'):
+ continue
+ elif name.endswith('.pyc') or name.endswith('.pyo'):
+ # always scan, even if we already know we're not safe
+ safe = scan_module(egg_dir, base, name, stubs) and safe
+ return safe
+
+
+def write_safety_flag(egg_dir, safe):
+ # Write or remove zip safety flag file(s)
+ for flag, fn in safety_flags.items():
+ fn = os.path.join(egg_dir, fn)
+ if os.path.exists(fn):
+ if safe is None or bool(safe) != flag:
+ os.unlink(fn)
+ elif safe is not None and bool(safe) == flag:
+ f = open(fn, 'wt')
+ f.write('\n')
+ f.close()
+
+
+safety_flags = {
+ True: 'zip-safe',
+ False: 'not-zip-safe',
+}
+
+
+def scan_module(egg_dir, base, name, stubs):
+ """Check whether module possibly uses unsafe-for-zipfile stuff"""
+
+ filename = os.path.join(base, name)
+ if filename[:-1] in stubs:
+ return True # Extension module
+ pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
+ module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
if sys.version_info < (3, 7):
skip = 12 # skip magic & date & file size
- else:
+ else:
skip = 16 # skip magic & reserved? & date & file size
- f = open(filename, 'rb')
- f.read(skip)
- code = marshal.load(f)
- f.close()
- safe = True
- symbols = dict.fromkeys(iter_symbols(code))
- for bad in ['__file__', '__path__']:
- if bad in symbols:
- log.warn("%s: module references %s", module, bad)
- safe = False
- if 'inspect' in symbols:
- for bad in [
- 'getsource', 'getabsfile', 'getsourcefile', 'getfile'
- 'getsourcelines', 'findsource', 'getcomments', 'getframeinfo',
- 'getinnerframes', 'getouterframes', 'stack', 'trace'
- ]:
- if bad in symbols:
- log.warn("%s: module MAY be using inspect.%s", module, bad)
- safe = False
- return safe
-
-
-def iter_symbols(code):
- """Yield names and strings used by `code` and its nested code objects"""
- for name in code.co_names:
- yield name
- for const in code.co_consts:
+ f = open(filename, 'rb')
+ f.read(skip)
+ code = marshal.load(f)
+ f.close()
+ safe = True
+ symbols = dict.fromkeys(iter_symbols(code))
+ for bad in ['__file__', '__path__']:
+ if bad in symbols:
+ log.warn("%s: module references %s", module, bad)
+ safe = False
+ if 'inspect' in symbols:
+ for bad in [
+ 'getsource', 'getabsfile', 'getsourcefile', 'getfile'
+ 'getsourcelines', 'findsource', 'getcomments', 'getframeinfo',
+ 'getinnerframes', 'getouterframes', 'stack', 'trace'
+ ]:
+ if bad in symbols:
+ log.warn("%s: module MAY be using inspect.%s", module, bad)
+ safe = False
+ return safe
+
+
+def iter_symbols(code):
+ """Yield names and strings used by `code` and its nested code objects"""
+ for name in code.co_names:
+ yield name
+ for const in code.co_consts:
if isinstance(const, str):
- yield const
- elif isinstance(const, CodeType):
- for name in iter_symbols(const):
- yield name
-
-
-def can_scan():
- if not sys.platform.startswith('java') and sys.platform != 'cli':
- # CPython, PyPy, etc.
- return True
- log.warn("Unable to analyze compiled code on this platform.")
- log.warn("Please ask the author to include a 'zip_safe'"
- " setting (either True or False) in the package's setup.py")
-
-
-# Attribute names of options for commands that might need to be convinced to
-# install to the egg build directory
-
-INSTALL_DIRECTORY_ATTRS = [
- 'install_lib', 'install_dir', 'install_data', 'install_base'
-]
-
-
-def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
- mode='w'):
- """Create a zip file from all the files under 'base_dir'. The output
- zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
- Python module (if available) or the InfoZIP "zip" utility (if installed
- and found on the default search path). If neither tool is available,
- raises DistutilsExecError. Returns the name of the output zip file.
- """
- import zipfile
-
- mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
- log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
-
- def visit(z, dirname, names):
- for name in names:
- path = os.path.normpath(os.path.join(dirname, name))
- if os.path.isfile(path):
- p = path[len(base_dir) + 1:]
- if not dry_run:
- z.write(path, p)
+ yield const
+ elif isinstance(const, CodeType):
+ for name in iter_symbols(const):
+ yield name
+
+
+def can_scan():
+ if not sys.platform.startswith('java') and sys.platform != 'cli':
+ # CPython, PyPy, etc.
+ return True
+ log.warn("Unable to analyze compiled code on this platform.")
+ log.warn("Please ask the author to include a 'zip_safe'"
+ " setting (either True or False) in the package's setup.py")
+
+
+# Attribute names of options for commands that might need to be convinced to
+# install to the egg build directory
+
+INSTALL_DIRECTORY_ATTRS = [
+ 'install_lib', 'install_dir', 'install_data', 'install_base'
+]
+
+
+def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
+ mode='w'):
+ """Create a zip file from all the files under 'base_dir'. The output
+ zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
+ Python module (if available) or the InfoZIP "zip" utility (if installed
+ and found on the default search path). If neither tool is available,
+ raises DistutilsExecError. Returns the name of the output zip file.
+ """
+ import zipfile
+
+ mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
+ log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
+
+ def visit(z, dirname, names):
+ for name in names:
+ path = os.path.normpath(os.path.join(dirname, name))
+ if os.path.isfile(path):
+ p = path[len(base_dir) + 1:]
+ if not dry_run:
+ z.write(path, p)
log.debug("adding '%s'", p)
-
- compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED
- if not dry_run:
- z = zipfile.ZipFile(zip_filename, mode, compression=compression)
+
+ compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED
+ if not dry_run:
+ z = zipfile.ZipFile(zip_filename, mode, compression=compression)
for dirname, dirs, files in sorted_walk(base_dir):
- visit(z, dirname, files)
- z.close()
- else:
+ visit(z, dirname, files)
+ z.close()
+ else:
for dirname, dirs, files in sorted_walk(base_dir):
- visit(None, dirname, files)
- return zip_filename
+ visit(None, dirname, files)
+ return zip_filename
diff --git a/contrib/python/setuptools/py3/setuptools/command/bdist_rpm.py b/contrib/python/setuptools/py3/setuptools/command/bdist_rpm.py
index 1957977d3a..98bf5dea84 100644
--- a/contrib/python/setuptools/py3/setuptools/command/bdist_rpm.py
+++ b/contrib/python/setuptools/py3/setuptools/command/bdist_rpm.py
@@ -1,40 +1,40 @@
-import distutils.command.bdist_rpm as orig
+import distutils.command.bdist_rpm as orig
import warnings
-
+
from setuptools import SetuptoolsDeprecationWarning
-
-
-class bdist_rpm(orig.bdist_rpm):
- """
- Override the default bdist_rpm behavior to do the following:
-
- 1. Run egg_info to ensure the name and version are properly calculated.
- 2. Always run 'install' using --single-version-externally-managed to
- disable eggs in RPM distributions.
- """
-
- def run(self):
+
+
+class bdist_rpm(orig.bdist_rpm):
+ """
+ Override the default bdist_rpm behavior to do the following:
+
+ 1. Run egg_info to ensure the name and version are properly calculated.
+ 2. Always run 'install' using --single-version-externally-managed to
+ disable eggs in RPM distributions.
+ """
+
+ def run(self):
warnings.warn(
"bdist_rpm is deprecated and will be removed in a future "
"version. Use bdist_wheel (wheel packages) instead.",
SetuptoolsDeprecationWarning,
)
- # ensure distro name is up-to-date
- self.run_command('egg_info')
-
- orig.bdist_rpm.run(self)
-
- def _make_spec_file(self):
- spec = orig.bdist_rpm._make_spec_file(self)
- spec = [
- line.replace(
- "setup.py install ",
- "setup.py install --single-version-externally-managed "
- ).replace(
- "%setup",
- "%setup -n %{name}-%{unmangled_version}"
+ # ensure distro name is up-to-date
+ self.run_command('egg_info')
+
+ orig.bdist_rpm.run(self)
+
+ def _make_spec_file(self):
+ spec = orig.bdist_rpm._make_spec_file(self)
+ spec = [
+ line.replace(
+ "setup.py install ",
+ "setup.py install --single-version-externally-managed "
+ ).replace(
+ "%setup",
+ "%setup -n %{name}-%{unmangled_version}"
)
- for line in spec
- ]
- return spec
+ for line in spec
+ ]
+ return spec
diff --git a/contrib/python/setuptools/py3/setuptools/command/build_ext.py b/contrib/python/setuptools/py3/setuptools/command/build_ext.py
index a3a0468c42..c59eff8bbf 100644
--- a/contrib/python/setuptools/py3/setuptools/command/build_ext.py
+++ b/contrib/python/setuptools/py3/setuptools/command/build_ext.py
@@ -2,29 +2,29 @@ import os
import sys
import itertools
from importlib.machinery import EXTENSION_SUFFIXES
-from distutils.command.build_ext import build_ext as _du_build_ext
-from distutils.file_util import copy_file
-from distutils.ccompiler import new_compiler
+from distutils.command.build_ext import build_ext as _du_build_ext
+from distutils.file_util import copy_file
+from distutils.ccompiler import new_compiler
from distutils.sysconfig import customize_compiler, get_config_var
-from distutils.errors import DistutilsError
-from distutils import log
-
-from setuptools.extension import Library
-
-try:
- # Attempt to use Cython for building extensions, if available
- from Cython.Distutils.build_ext import build_ext as _build_ext
+from distutils.errors import DistutilsError
+from distutils import log
+
+from setuptools.extension import Library
+
+try:
+ # Attempt to use Cython for building extensions, if available
+ from Cython.Distutils.build_ext import build_ext as _build_ext
# Additionally, assert that the compiler module will load
# also. Ref #1229.
__import__('Cython.Compiler.Main')
-except ImportError:
- _build_ext = _du_build_ext
-
+except ImportError:
+ _build_ext = _du_build_ext
+
# make sure _config_vars is initialized
get_config_var("LDSHARED")
from distutils.sysconfig import _config_vars as _CONFIG_VARS # noqa
-
-
+
+
def _customize_compiler_for_shlib(compiler):
if sys.platform == "darwin":
# building .dylib requires additional compiler flags on OSX; here we
@@ -45,20 +45,20 @@ def _customize_compiler_for_shlib(compiler):
customize_compiler(compiler)
-have_rtld = False
-use_stubs = False
-libtype = 'shared'
-
-if sys.platform == "darwin":
- use_stubs = True
-elif os.name != 'nt':
- try:
- import dl
- use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')
- except ImportError:
- pass
-
-
+have_rtld = False
+use_stubs = False
+libtype = 'shared'
+
+if sys.platform == "darwin":
+ use_stubs = True
+elif os.name != 'nt':
+ try:
+ import dl
+ use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')
+ except ImportError:
+ pass
+
+
def if_dl(s):
return s if have_rtld else ''
@@ -72,38 +72,38 @@ def get_abi3_suffix():
return suffix
-class build_ext(_build_ext):
- def run(self):
- """Build extensions in build directory, then copy if --inplace"""
- old_inplace, self.inplace = self.inplace, 0
- _build_ext.run(self)
- self.inplace = old_inplace
- if old_inplace:
- self.copy_extensions_to_source()
-
- def copy_extensions_to_source(self):
- build_py = self.get_finalized_command('build_py')
- for ext in self.extensions:
- fullname = self.get_ext_fullname(ext.name)
- filename = self.get_ext_filename(fullname)
- modpath = fullname.split('.')
- package = '.'.join(modpath[:-1])
- package_dir = build_py.get_package_dir(package)
- dest_filename = os.path.join(package_dir,
- os.path.basename(filename))
- src_filename = os.path.join(self.build_lib, filename)
-
- # Always copy, even if source is older than destination, to ensure
- # that the right extensions for the current Python/platform are
- # used.
- copy_file(
- src_filename, dest_filename, verbose=self.verbose,
- dry_run=self.dry_run
- )
- if ext._needs_stub:
- self.write_stub(package_dir or os.curdir, ext, True)
-
- def get_ext_filename(self, fullname):
+class build_ext(_build_ext):
+ def run(self):
+ """Build extensions in build directory, then copy if --inplace"""
+ old_inplace, self.inplace = self.inplace, 0
+ _build_ext.run(self)
+ self.inplace = old_inplace
+ if old_inplace:
+ self.copy_extensions_to_source()
+
+ def copy_extensions_to_source(self):
+ build_py = self.get_finalized_command('build_py')
+ for ext in self.extensions:
+ fullname = self.get_ext_fullname(ext.name)
+ filename = self.get_ext_filename(fullname)
+ modpath = fullname.split('.')
+ package = '.'.join(modpath[:-1])
+ package_dir = build_py.get_package_dir(package)
+ dest_filename = os.path.join(package_dir,
+ os.path.basename(filename))
+ src_filename = os.path.join(self.build_lib, filename)
+
+ # Always copy, even if source is older than destination, to ensure
+ # that the right extensions for the current Python/platform are
+ # used.
+ copy_file(
+ src_filename, dest_filename, verbose=self.verbose,
+ dry_run=self.dry_run
+ )
+ if ext._needs_stub:
+ self.write_stub(package_dir or os.curdir, ext, True)
+
+ def get_ext_filename(self, fullname):
so_ext = os.getenv('SETUPTOOLS_EXT_SUFFIX')
if so_ext:
filename = os.path.join(*fullname.split('.')) + so_ext
@@ -111,218 +111,218 @@ class build_ext(_build_ext):
filename = _build_ext.get_ext_filename(self, fullname)
so_ext = get_config_var('EXT_SUFFIX')
- if fullname in self.ext_map:
- ext = self.ext_map[fullname]
+ if fullname in self.ext_map:
+ ext = self.ext_map[fullname]
use_abi3 = getattr(ext, 'py_limited_api') and get_abi3_suffix()
if use_abi3:
filename = filename[:-len(so_ext)]
so_ext = get_abi3_suffix()
filename = filename + so_ext
- if isinstance(ext, Library):
- fn, ext = os.path.splitext(filename)
- return self.shlib_compiler.library_filename(fn, libtype)
- elif use_stubs and ext._links_to_dynamic:
- d, fn = os.path.split(filename)
- return os.path.join(d, 'dl-' + fn)
- return filename
-
- def initialize_options(self):
- _build_ext.initialize_options(self)
- self.shlib_compiler = None
- self.shlibs = []
- self.ext_map = {}
-
- def finalize_options(self):
- _build_ext.finalize_options(self)
- self.extensions = self.extensions or []
- self.check_extensions_list(self.extensions)
- self.shlibs = [ext for ext in self.extensions
- if isinstance(ext, Library)]
- if self.shlibs:
- self.setup_shlib_compiler()
- for ext in self.extensions:
- ext._full_name = self.get_ext_fullname(ext.name)
- for ext in self.extensions:
- fullname = ext._full_name
- self.ext_map[fullname] = ext
-
- # distutils 3.1 will also ask for module names
- # XXX what to do with conflicts?
- self.ext_map[fullname.split('.')[-1]] = ext
-
- ltd = self.shlibs and self.links_to_dynamic(ext) or False
- ns = ltd and use_stubs and not isinstance(ext, Library)
- ext._links_to_dynamic = ltd
- ext._needs_stub = ns
- filename = ext._file_name = self.get_ext_filename(fullname)
- libdir = os.path.dirname(os.path.join(self.build_lib, filename))
- if ltd and libdir not in ext.library_dirs:
- ext.library_dirs.append(libdir)
- if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs:
- ext.runtime_library_dirs.append(os.curdir)
-
- def setup_shlib_compiler(self):
- compiler = self.shlib_compiler = new_compiler(
- compiler=self.compiler, dry_run=self.dry_run, force=self.force
- )
+ if isinstance(ext, Library):
+ fn, ext = os.path.splitext(filename)
+ return self.shlib_compiler.library_filename(fn, libtype)
+ elif use_stubs and ext._links_to_dynamic:
+ d, fn = os.path.split(filename)
+ return os.path.join(d, 'dl-' + fn)
+ return filename
+
+ def initialize_options(self):
+ _build_ext.initialize_options(self)
+ self.shlib_compiler = None
+ self.shlibs = []
+ self.ext_map = {}
+
+ def finalize_options(self):
+ _build_ext.finalize_options(self)
+ self.extensions = self.extensions or []
+ self.check_extensions_list(self.extensions)
+ self.shlibs = [ext for ext in self.extensions
+ if isinstance(ext, Library)]
+ if self.shlibs:
+ self.setup_shlib_compiler()
+ for ext in self.extensions:
+ ext._full_name = self.get_ext_fullname(ext.name)
+ for ext in self.extensions:
+ fullname = ext._full_name
+ self.ext_map[fullname] = ext
+
+ # distutils 3.1 will also ask for module names
+ # XXX what to do with conflicts?
+ self.ext_map[fullname.split('.')[-1]] = ext
+
+ ltd = self.shlibs and self.links_to_dynamic(ext) or False
+ ns = ltd and use_stubs and not isinstance(ext, Library)
+ ext._links_to_dynamic = ltd
+ ext._needs_stub = ns
+ filename = ext._file_name = self.get_ext_filename(fullname)
+ libdir = os.path.dirname(os.path.join(self.build_lib, filename))
+ if ltd and libdir not in ext.library_dirs:
+ ext.library_dirs.append(libdir)
+ if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs:
+ ext.runtime_library_dirs.append(os.curdir)
+
+ def setup_shlib_compiler(self):
+ compiler = self.shlib_compiler = new_compiler(
+ compiler=self.compiler, dry_run=self.dry_run, force=self.force
+ )
_customize_compiler_for_shlib(compiler)
-
- if self.include_dirs is not None:
- compiler.set_include_dirs(self.include_dirs)
- if self.define is not None:
- # 'define' option is a list of (name,value) tuples
- for (name, value) in self.define:
- compiler.define_macro(name, value)
- if self.undef is not None:
- for macro in self.undef:
- compiler.undefine_macro(macro)
- if self.libraries is not None:
- compiler.set_libraries(self.libraries)
- if self.library_dirs is not None:
- compiler.set_library_dirs(self.library_dirs)
- if self.rpath is not None:
- compiler.set_runtime_library_dirs(self.rpath)
- if self.link_objects is not None:
- compiler.set_link_objects(self.link_objects)
-
- # hack so distutils' build_extension() builds a library instead
- compiler.link_shared_object = link_shared_object.__get__(compiler)
-
- def get_export_symbols(self, ext):
- if isinstance(ext, Library):
- return ext.export_symbols
- return _build_ext.get_export_symbols(self, ext)
-
- def build_extension(self, ext):
- ext._convert_pyx_sources_to_lang()
- _compiler = self.compiler
- try:
- if isinstance(ext, Library):
- self.compiler = self.shlib_compiler
- _build_ext.build_extension(self, ext)
- if ext._needs_stub:
- cmd = self.get_finalized_command('build_py').build_lib
- self.write_stub(cmd, ext)
- finally:
- self.compiler = _compiler
-
- def links_to_dynamic(self, ext):
- """Return true if 'ext' links to a dynamic lib in the same package"""
- # XXX this should check to ensure the lib is actually being built
- # XXX as dynamic, and not just using a locally-found version or a
- # XXX static-compiled version
- libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
- pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])
- return any(pkg + libname in libnames for libname in ext.libraries)
-
- def get_outputs(self):
- return _build_ext.get_outputs(self) + self.__get_stubs_outputs()
-
- def __get_stubs_outputs(self):
- # assemble the base name for each extension that needs a stub
- ns_ext_bases = (
- os.path.join(self.build_lib, *ext._full_name.split('.'))
- for ext in self.extensions
- if ext._needs_stub
- )
- # pair each base with the extension
- pairs = itertools.product(ns_ext_bases, self.__get_output_extensions())
- return list(base + fnext for base, fnext in pairs)
-
- def __get_output_extensions(self):
- yield '.py'
- yield '.pyc'
- if self.get_finalized_command('build_py').optimize:
- yield '.pyo'
-
- def write_stub(self, output_dir, ext, compile=False):
- log.info("writing stub loader for %s to %s", ext._full_name,
- output_dir)
- stub_file = (os.path.join(output_dir, *ext._full_name.split('.')) +
- '.py')
- if compile and os.path.exists(stub_file):
- raise DistutilsError(stub_file + " already exists! Please delete.")
- if not self.dry_run:
- f = open(stub_file, 'w')
- f.write(
- '\n'.join([
- "def __bootstrap__():",
- " global __bootstrap__, __file__, __loader__",
+
+ if self.include_dirs is not None:
+ compiler.set_include_dirs(self.include_dirs)
+ if self.define is not None:
+ # 'define' option is a list of (name,value) tuples
+ for (name, value) in self.define:
+ compiler.define_macro(name, value)
+ if self.undef is not None:
+ for macro in self.undef:
+ compiler.undefine_macro(macro)
+ if self.libraries is not None:
+ compiler.set_libraries(self.libraries)
+ if self.library_dirs is not None:
+ compiler.set_library_dirs(self.library_dirs)
+ if self.rpath is not None:
+ compiler.set_runtime_library_dirs(self.rpath)
+ if self.link_objects is not None:
+ compiler.set_link_objects(self.link_objects)
+
+ # hack so distutils' build_extension() builds a library instead
+ compiler.link_shared_object = link_shared_object.__get__(compiler)
+
+ def get_export_symbols(self, ext):
+ if isinstance(ext, Library):
+ return ext.export_symbols
+ return _build_ext.get_export_symbols(self, ext)
+
+ def build_extension(self, ext):
+ ext._convert_pyx_sources_to_lang()
+ _compiler = self.compiler
+ try:
+ if isinstance(ext, Library):
+ self.compiler = self.shlib_compiler
+ _build_ext.build_extension(self, ext)
+ if ext._needs_stub:
+ cmd = self.get_finalized_command('build_py').build_lib
+ self.write_stub(cmd, ext)
+ finally:
+ self.compiler = _compiler
+
+ def links_to_dynamic(self, ext):
+ """Return true if 'ext' links to a dynamic lib in the same package"""
+ # XXX this should check to ensure the lib is actually being built
+ # XXX as dynamic, and not just using a locally-found version or a
+ # XXX static-compiled version
+ libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
+ pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])
+ return any(pkg + libname in libnames for libname in ext.libraries)
+
+ def get_outputs(self):
+ return _build_ext.get_outputs(self) + self.__get_stubs_outputs()
+
+ def __get_stubs_outputs(self):
+ # assemble the base name for each extension that needs a stub
+ ns_ext_bases = (
+ os.path.join(self.build_lib, *ext._full_name.split('.'))
+ for ext in self.extensions
+ if ext._needs_stub
+ )
+ # pair each base with the extension
+ pairs = itertools.product(ns_ext_bases, self.__get_output_extensions())
+ return list(base + fnext for base, fnext in pairs)
+
+ def __get_output_extensions(self):
+ yield '.py'
+ yield '.pyc'
+ if self.get_finalized_command('build_py').optimize:
+ yield '.pyo'
+
+ def write_stub(self, output_dir, ext, compile=False):
+ log.info("writing stub loader for %s to %s", ext._full_name,
+ output_dir)
+ stub_file = (os.path.join(output_dir, *ext._full_name.split('.')) +
+ '.py')
+ if compile and os.path.exists(stub_file):
+ raise DistutilsError(stub_file + " already exists! Please delete.")
+ if not self.dry_run:
+ f = open(stub_file, 'w')
+ f.write(
+ '\n'.join([
+ "def __bootstrap__():",
+ " global __bootstrap__, __file__, __loader__",
" import sys, os, pkg_resources, importlib.util" +
if_dl(", dl"),
- " __file__ = pkg_resources.resource_filename"
- "(__name__,%r)"
- % os.path.basename(ext._file_name),
- " del __bootstrap__",
- " if '__loader__' in globals():",
- " del __loader__",
- if_dl(" old_flags = sys.getdlopenflags()"),
- " old_dir = os.getcwd()",
- " try:",
- " os.chdir(os.path.dirname(__file__))",
- if_dl(" sys.setdlopenflags(dl.RTLD_NOW)"),
+ " __file__ = pkg_resources.resource_filename"
+ "(__name__,%r)"
+ % os.path.basename(ext._file_name),
+ " del __bootstrap__",
+ " if '__loader__' in globals():",
+ " del __loader__",
+ if_dl(" old_flags = sys.getdlopenflags()"),
+ " old_dir = os.getcwd()",
+ " try:",
+ " os.chdir(os.path.dirname(__file__))",
+ if_dl(" sys.setdlopenflags(dl.RTLD_NOW)"),
" spec = importlib.util.spec_from_file_location(",
" __name__, __file__)",
" mod = importlib.util.module_from_spec(spec)",
" spec.loader.exec_module(mod)",
- " finally:",
- if_dl(" sys.setdlopenflags(old_flags)"),
- " os.chdir(old_dir)",
- "__bootstrap__()",
- "" # terminal \n
- ])
- )
- f.close()
- if compile:
- from distutils.util import byte_compile
-
- byte_compile([stub_file], optimize=0,
- force=True, dry_run=self.dry_run)
- optimize = self.get_finalized_command('install_lib').optimize
- if optimize > 0:
- byte_compile([stub_file], optimize=optimize,
- force=True, dry_run=self.dry_run)
- if os.path.exists(stub_file) and not self.dry_run:
- os.unlink(stub_file)
-
-
-if use_stubs or os.name == 'nt':
- # Build shared libraries
- #
- def link_shared_object(
- self, objects, output_libname, output_dir=None, libraries=None,
- library_dirs=None, runtime_library_dirs=None, export_symbols=None,
- debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
- target_lang=None):
- self.link(
- self.SHARED_LIBRARY, objects, output_libname,
- output_dir, libraries, library_dirs, runtime_library_dirs,
- export_symbols, debug, extra_preargs, extra_postargs,
- build_temp, target_lang
- )
-else:
- # Build static libraries everywhere else
- libtype = 'static'
-
- def link_shared_object(
- self, objects, output_libname, output_dir=None, libraries=None,
- library_dirs=None, runtime_library_dirs=None, export_symbols=None,
- debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
- target_lang=None):
- # XXX we need to either disallow these attrs on Library instances,
- # or warn/abort here if set, or something...
- # libraries=None, library_dirs=None, runtime_library_dirs=None,
- # export_symbols=None, extra_preargs=None, extra_postargs=None,
- # build_temp=None
-
- assert output_dir is None # distutils build_ext doesn't pass this
- output_dir, filename = os.path.split(output_libname)
- basename, ext = os.path.splitext(filename)
- if self.library_filename("x").startswith('lib'):
- # strip 'lib' prefix; this is kludgy if some platform uses
- # a different prefix
- basename = basename[3:]
-
- self.create_static_lib(
- objects, basename, output_dir, debug, target_lang
- )
+ " finally:",
+ if_dl(" sys.setdlopenflags(old_flags)"),
+ " os.chdir(old_dir)",
+ "__bootstrap__()",
+ "" # terminal \n
+ ])
+ )
+ f.close()
+ if compile:
+ from distutils.util import byte_compile
+
+ byte_compile([stub_file], optimize=0,
+ force=True, dry_run=self.dry_run)
+ optimize = self.get_finalized_command('install_lib').optimize
+ if optimize > 0:
+ byte_compile([stub_file], optimize=optimize,
+ force=True, dry_run=self.dry_run)
+ if os.path.exists(stub_file) and not self.dry_run:
+ os.unlink(stub_file)
+
+
+if use_stubs or os.name == 'nt':
+ # Build shared libraries
+ #
+ def link_shared_object(
+ self, objects, output_libname, output_dir=None, libraries=None,
+ library_dirs=None, runtime_library_dirs=None, export_symbols=None,
+ debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
+ target_lang=None):
+ self.link(
+ self.SHARED_LIBRARY, objects, output_libname,
+ output_dir, libraries, library_dirs, runtime_library_dirs,
+ export_symbols, debug, extra_preargs, extra_postargs,
+ build_temp, target_lang
+ )
+else:
+ # Build static libraries everywhere else
+ libtype = 'static'
+
+ def link_shared_object(
+ self, objects, output_libname, output_dir=None, libraries=None,
+ library_dirs=None, runtime_library_dirs=None, export_symbols=None,
+ debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
+ target_lang=None):
+ # XXX we need to either disallow these attrs on Library instances,
+ # or warn/abort here if set, or something...
+ # libraries=None, library_dirs=None, runtime_library_dirs=None,
+ # export_symbols=None, extra_preargs=None, extra_postargs=None,
+ # build_temp=None
+
+ assert output_dir is None # distutils build_ext doesn't pass this
+ output_dir, filename = os.path.split(output_libname)
+ basename, ext = os.path.splitext(filename)
+ if self.library_filename("x").startswith('lib'):
+ # strip 'lib' prefix; this is kludgy if some platform uses
+ # a different prefix
+ basename = basename[3:]
+
+ self.create_static_lib(
+ objects, basename, output_dir, debug, target_lang
+ )
diff --git a/contrib/python/setuptools/py3/setuptools/command/build_py.py b/contrib/python/setuptools/py3/setuptools/command/build_py.py
index 1c35af7674..c3fdc0927c 100644
--- a/contrib/python/setuptools/py3/setuptools/command/build_py.py
+++ b/contrib/python/setuptools/py3/setuptools/command/build_py.py
@@ -1,72 +1,72 @@
-from glob import glob
-from distutils.util import convert_path
-import distutils.command.build_py as orig
-import os
-import fnmatch
-import textwrap
-import io
-import distutils.errors
-import itertools
+from glob import glob
+from distutils.util import convert_path
+import distutils.command.build_py as orig
+import os
+import fnmatch
+import textwrap
+import io
+import distutils.errors
+import itertools
import stat
from setuptools.extern.more_itertools import unique_everseen
-
+
def make_writable(target):
os.chmod(target, os.stat(target).st_mode | stat.S_IWRITE)
class build_py(orig.build_py):
- """Enhanced 'build_py' command that includes data files with packages
-
- The data files are specified via a 'package_data' argument to 'setup()'.
- See 'setuptools.dist.Distribution' for more details.
-
- Also, this version of the 'build_py' command allows you to specify both
- 'py_modules' and 'packages' in the same setup operation.
- """
-
- def finalize_options(self):
- orig.build_py.finalize_options(self)
- self.package_data = self.distribution.package_data
+ """Enhanced 'build_py' command that includes data files with packages
+
+ The data files are specified via a 'package_data' argument to 'setup()'.
+ See 'setuptools.dist.Distribution' for more details.
+
+ Also, this version of the 'build_py' command allows you to specify both
+ 'py_modules' and 'packages' in the same setup operation.
+ """
+
+ def finalize_options(self):
+ orig.build_py.finalize_options(self)
+ self.package_data = self.distribution.package_data
self.exclude_package_data = self.distribution.exclude_package_data or {}
- if 'data_files' in self.__dict__:
- del self.__dict__['data_files']
- self.__updated_files = []
-
- def run(self):
- """Build modules, packages, and copy data files to build directory"""
- if not self.py_modules and not self.packages:
- return
-
- if self.py_modules:
- self.build_modules()
-
- if self.packages:
- self.build_packages()
- self.build_package_data()
-
- # Only compile actual .py files, using our base class' idea of what our
- # output files are.
- self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=0))
-
- def __getattr__(self, attr):
- "lazily compute data files"
- if attr == 'data_files':
- self.data_files = self._get_data_files()
- return self.data_files
- return orig.build_py.__getattr__(self, attr)
-
- def build_module(self, module, module_file, package):
+ if 'data_files' in self.__dict__:
+ del self.__dict__['data_files']
+ self.__updated_files = []
+
+ def run(self):
+ """Build modules, packages, and copy data files to build directory"""
+ if not self.py_modules and not self.packages:
+ return
+
+ if self.py_modules:
+ self.build_modules()
+
+ if self.packages:
+ self.build_packages()
+ self.build_package_data()
+
+ # Only compile actual .py files, using our base class' idea of what our
+ # output files are.
+ self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=0))
+
+ def __getattr__(self, attr):
+ "lazily compute data files"
+ if attr == 'data_files':
+ self.data_files = self._get_data_files()
+ return self.data_files
+ return orig.build_py.__getattr__(self, attr)
+
+ def build_module(self, module, module_file, package):
outfile, copied = orig.build_py.build_module(self, module, module_file, package)
- if copied:
- self.__updated_files.append(outfile)
- return outfile, copied
-
- def _get_data_files(self):
- """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
- self.analyze_manifest()
- return list(map(self._get_pkg_data_files, self.packages or ()))
-
+ if copied:
+ self.__updated_files.append(outfile)
+ return outfile, copied
+
+ def _get_data_files(self):
+ """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
+ self.analyze_manifest()
+ return list(map(self._get_pkg_data_files, self.packages or ()))
+
def get_data_files_without_manifest(self):
"""
Generate list of ``(package,src_dir,build_dir,filenames)`` tuples,
@@ -77,22 +77,22 @@ class build_py(orig.build_py):
self.__dict__.setdefault('manifest_files', {})
return list(map(self._get_pkg_data_files, self.packages or ()))
- def _get_pkg_data_files(self, package):
- # Locate package source directory
- src_dir = self.get_package_dir(package)
-
- # Compute package build directory
- build_dir = os.path.join(*([self.build_lib] + package.split('.')))
-
- # Strip directory from globbed filenames
- filenames = [
- os.path.relpath(file, src_dir)
- for file in self.find_data_files(package, src_dir)
- ]
- return package, src_dir, build_dir, filenames
-
- def find_data_files(self, package, src_dir):
- """Return filenames for package's data files in 'src_dir'"""
+ def _get_pkg_data_files(self, package):
+ # Locate package source directory
+ src_dir = self.get_package_dir(package)
+
+ # Compute package build directory
+ build_dir = os.path.join(*([self.build_lib] + package.split('.')))
+
+ # Strip directory from globbed filenames
+ filenames = [
+ os.path.relpath(file, src_dir)
+ for file in self.find_data_files(package, src_dir)
+ ]
+ return package, src_dir, build_dir, filenames
+
+ def find_data_files(self, package, src_dir):
+ """Return filenames for package's data files in 'src_dir'"""
patterns = self._get_platform_patterns(
self.package_data,
package,
@@ -106,94 +106,94 @@ class build_py(orig.build_py):
self.manifest_files.get(package, []),
glob_files,
)
- return self.exclude_data_files(package, src_dir, files)
-
- def build_package_data(self):
- """Copy data files into build directory"""
- for package, src_dir, build_dir, filenames in self.data_files:
- for filename in filenames:
- target = os.path.join(build_dir, filename)
- self.mkpath(os.path.dirname(target))
- srcfile = os.path.join(src_dir, filename)
- outf, copied = self.copy_file(srcfile, target)
+ return self.exclude_data_files(package, src_dir, files)
+
+ def build_package_data(self):
+ """Copy data files into build directory"""
+ for package, src_dir, build_dir, filenames in self.data_files:
+ for filename in filenames:
+ target = os.path.join(build_dir, filename)
+ self.mkpath(os.path.dirname(target))
+ srcfile = os.path.join(src_dir, filename)
+ outf, copied = self.copy_file(srcfile, target)
make_writable(target)
- srcfile = os.path.abspath(srcfile)
-
- def analyze_manifest(self):
- self.manifest_files = mf = {}
- if not self.distribution.include_package_data:
- return
- src_dirs = {}
- for package in self.packages or ():
- # Locate package source directory
- src_dirs[assert_relative(self.get_package_dir(package))] = package
-
- self.run_command('egg_info')
- ei_cmd = self.get_finalized_command('egg_info')
- for path in ei_cmd.filelist.files:
- d, f = os.path.split(assert_relative(path))
- prev = None
- oldf = f
- while d and d != prev and d not in src_dirs:
- prev = d
- d, df = os.path.split(d)
- f = os.path.join(df, f)
- if d in src_dirs:
- if path.endswith('.py') and f == oldf:
- continue # it's a module, not data
- mf.setdefault(src_dirs[d], []).append(path)
-
- def get_data_files(self):
- pass # Lazily compute data files in _get_data_files() function.
-
- def check_package(self, package, package_dir):
- """Check namespace packages' __init__ for declare_namespace"""
- try:
- return self.packages_checked[package]
- except KeyError:
- pass
-
- init_py = orig.build_py.check_package(self, package, package_dir)
- self.packages_checked[package] = init_py
-
- if not init_py or not self.distribution.namespace_packages:
- return init_py
-
- for pkg in self.distribution.namespace_packages:
- if pkg == package or pkg.startswith(package + '.'):
- break
- else:
- return init_py
-
- with io.open(init_py, 'rb') as f:
- contents = f.read()
- if b'declare_namespace' not in contents:
- raise distutils.errors.DistutilsError(
- "Namespace package problem: %s is a namespace package, but "
- "its\n__init__.py does not call declare_namespace()! Please "
- 'fix it.\n(See the setuptools manual under '
- '"Namespace Packages" for details.)\n"' % (package,)
- )
- return init_py
-
- def initialize_options(self):
- self.packages_checked = {}
- orig.build_py.initialize_options(self)
-
- def get_package_dir(self, package):
- res = orig.build_py.get_package_dir(self, package)
- if self.distribution.src_root is not None:
- return os.path.join(self.distribution.src_root, res)
- return res
-
- def exclude_data_files(self, package, src_dir, files):
- """Filter filenames for package's data files in 'src_dir'"""
+ srcfile = os.path.abspath(srcfile)
+
+ def analyze_manifest(self):
+ self.manifest_files = mf = {}
+ if not self.distribution.include_package_data:
+ return
+ src_dirs = {}
+ for package in self.packages or ():
+ # Locate package source directory
+ src_dirs[assert_relative(self.get_package_dir(package))] = package
+
+ self.run_command('egg_info')
+ ei_cmd = self.get_finalized_command('egg_info')
+ for path in ei_cmd.filelist.files:
+ d, f = os.path.split(assert_relative(path))
+ prev = None
+ oldf = f
+ while d and d != prev and d not in src_dirs:
+ prev = d
+ d, df = os.path.split(d)
+ f = os.path.join(df, f)
+ if d in src_dirs:
+ if path.endswith('.py') and f == oldf:
+ continue # it's a module, not data
+ mf.setdefault(src_dirs[d], []).append(path)
+
+ def get_data_files(self):
+ pass # Lazily compute data files in _get_data_files() function.
+
+ def check_package(self, package, package_dir):
+ """Check namespace packages' __init__ for declare_namespace"""
+ try:
+ return self.packages_checked[package]
+ except KeyError:
+ pass
+
+ init_py = orig.build_py.check_package(self, package, package_dir)
+ self.packages_checked[package] = init_py
+
+ if not init_py or not self.distribution.namespace_packages:
+ return init_py
+
+ for pkg in self.distribution.namespace_packages:
+ if pkg == package or pkg.startswith(package + '.'):
+ break
+ else:
+ return init_py
+
+ with io.open(init_py, 'rb') as f:
+ contents = f.read()
+ if b'declare_namespace' not in contents:
+ raise distutils.errors.DistutilsError(
+ "Namespace package problem: %s is a namespace package, but "
+ "its\n__init__.py does not call declare_namespace()! Please "
+ 'fix it.\n(See the setuptools manual under '
+ '"Namespace Packages" for details.)\n"' % (package,)
+ )
+ return init_py
+
+ def initialize_options(self):
+ self.packages_checked = {}
+ orig.build_py.initialize_options(self)
+
+ def get_package_dir(self, package):
+ res = orig.build_py.get_package_dir(self, package)
+ if self.distribution.src_root is not None:
+ return os.path.join(self.distribution.src_root, res)
+ return res
+
+ def exclude_data_files(self, package, src_dir, files):
+ """Filter filenames for package's data files in 'src_dir'"""
files = list(files)
patterns = self._get_platform_patterns(
self.exclude_package_data,
package,
src_dir,
- )
+ )
match_groups = (fnmatch.filter(files, pattern) for pattern in patterns)
# flatten the groups of matches into an iterable of matches
matches = itertools.chain.from_iterable(match_groups)
@@ -201,7 +201,7 @@ class build_py(orig.build_py):
keepers = (fn for fn in files if fn not in bad)
# ditch dupes
return list(unique_everseen(keepers))
-
+
@staticmethod
def _get_platform_patterns(spec, package, src_dir):
"""
@@ -219,24 +219,24 @@ class build_py(orig.build_py):
os.path.join(src_dir, convert_path(pattern))
for pattern in raw_patterns
)
-
-def assert_relative(path):
- if not os.path.isabs(path):
- return path
- from distutils.errors import DistutilsSetupError
-
+
+def assert_relative(path):
+ if not os.path.isabs(path):
+ return path
+ from distutils.errors import DistutilsSetupError
+
msg = (
textwrap.dedent(
"""
- Error: setup script specifies an absolute path:
-
- %s
-
- setup() arguments must *always* be /-separated paths relative to the
- setup.py directory, *never* absolute paths.
+ Error: setup script specifies an absolute path:
+
+ %s
+
+ setup() arguments must *always* be /-separated paths relative to the
+ setup.py directory, *never* absolute paths.
"""
).lstrip()
% path
)
- raise DistutilsSetupError(msg)
+ raise DistutilsSetupError(msg)
diff --git a/contrib/python/setuptools/py3/setuptools/command/develop.py b/contrib/python/setuptools/py3/setuptools/command/develop.py
index ec70008518..24fb0a7c81 100644
--- a/contrib/python/setuptools/py3/setuptools/command/develop.py
+++ b/contrib/python/setuptools/py3/setuptools/command/develop.py
@@ -1,83 +1,83 @@
-from distutils.util import convert_path
-from distutils import log
-from distutils.errors import DistutilsError, DistutilsOptionError
-import os
-import glob
-import io
-
+from distutils.util import convert_path
+from distutils import log
+from distutils.errors import DistutilsError, DistutilsOptionError
+import os
+import glob
+import io
+
import pkg_resources
-from setuptools.command.easy_install import easy_install
+from setuptools.command.easy_install import easy_install
from setuptools import namespaces
-import setuptools
-
-
+import setuptools
+
+
class develop(namespaces.DevelopInstaller, easy_install):
- """Set up package for development"""
-
- description = "install package in 'development mode'"
-
- user_options = easy_install.user_options + [
- ("uninstall", "u", "Uninstall this source package"),
- ("egg-path=", None, "Set the path to be used in the .egg-link file"),
- ]
-
- boolean_options = easy_install.boolean_options + ['uninstall']
-
- command_consumes_arguments = False # override base
-
- def run(self):
- if self.uninstall:
- self.multi_version = True
- self.uninstall_link()
+ """Set up package for development"""
+
+ description = "install package in 'development mode'"
+
+ user_options = easy_install.user_options + [
+ ("uninstall", "u", "Uninstall this source package"),
+ ("egg-path=", None, "Set the path to be used in the .egg-link file"),
+ ]
+
+ boolean_options = easy_install.boolean_options + ['uninstall']
+
+ command_consumes_arguments = False # override base
+
+ def run(self):
+ if self.uninstall:
+ self.multi_version = True
+ self.uninstall_link()
self.uninstall_namespaces()
- else:
- self.install_for_development()
- self.warn_deprecated_options()
-
- def initialize_options(self):
- self.uninstall = None
- self.egg_path = None
- easy_install.initialize_options(self)
- self.setup_path = None
- self.always_copy_from = '.' # always copy eggs installed in curdir
-
- def finalize_options(self):
- ei = self.get_finalized_command("egg_info")
- if ei.broken_egg_info:
- template = "Please rename %r to %r before using 'develop'"
- args = ei.egg_info, ei.broken_egg_info
- raise DistutilsError(template % args)
- self.args = [ei.egg_name]
-
- easy_install.finalize_options(self)
- self.expand_basedirs()
- self.expand_dirs()
- # pick up setup-dir .egg files only: no .egg-info
- self.package_index.scan(glob.glob('*.egg'))
-
- egg_link_fn = ei.egg_name + '.egg-link'
- self.egg_link = os.path.join(self.install_dir, egg_link_fn)
- self.egg_base = ei.egg_base
- if self.egg_path is None:
- self.egg_path = os.path.abspath(ei.egg_base)
-
+ else:
+ self.install_for_development()
+ self.warn_deprecated_options()
+
+ def initialize_options(self):
+ self.uninstall = None
+ self.egg_path = None
+ easy_install.initialize_options(self)
+ self.setup_path = None
+ self.always_copy_from = '.' # always copy eggs installed in curdir
+
+ def finalize_options(self):
+ ei = self.get_finalized_command("egg_info")
+ if ei.broken_egg_info:
+ template = "Please rename %r to %r before using 'develop'"
+ args = ei.egg_info, ei.broken_egg_info
+ raise DistutilsError(template % args)
+ self.args = [ei.egg_name]
+
+ easy_install.finalize_options(self)
+ self.expand_basedirs()
+ self.expand_dirs()
+ # pick up setup-dir .egg files only: no .egg-info
+ self.package_index.scan(glob.glob('*.egg'))
+
+ egg_link_fn = ei.egg_name + '.egg-link'
+ self.egg_link = os.path.join(self.install_dir, egg_link_fn)
+ self.egg_base = ei.egg_base
+ if self.egg_path is None:
+ self.egg_path = os.path.abspath(ei.egg_base)
+
target = pkg_resources.normalize_path(self.egg_base)
egg_path = pkg_resources.normalize_path(
os.path.join(self.install_dir, self.egg_path)
)
- if egg_path != target:
- raise DistutilsOptionError(
- "--egg-path must be a relative path from the install"
- " directory to " + target
- )
-
- # Make a distribution for the package's source
+ if egg_path != target:
+ raise DistutilsOptionError(
+ "--egg-path must be a relative path from the install"
+ " directory to " + target
+ )
+
+ # Make a distribution for the package's source
self.dist = pkg_resources.Distribution(
- target,
+ target,
pkg_resources.PathMetadata(target, os.path.abspath(ei.egg_info)),
project_name=ei.egg_name,
- )
-
+ )
+
self.setup_path = self._resolve_setup_path(
self.egg_base,
self.install_dir,
@@ -98,96 +98,96 @@ class develop(namespaces.DevelopInstaller, easy_install):
os.path.join(install_dir, egg_path, path_to_setup)
)
if resolved != pkg_resources.normalize_path(os.curdir):
- raise DistutilsOptionError(
- "Can't get a consistent path to setup script from"
+ raise DistutilsOptionError(
+ "Can't get a consistent path to setup script from"
" installation directory",
resolved,
pkg_resources.normalize_path(os.curdir),
)
return path_to_setup
-
- def install_for_development(self):
+
+ def install_for_development(self):
self.run_command('egg_info')
-
+
# Build extensions in-place
self.reinitialize_command('build_ext', inplace=1)
self.run_command('build_ext')
-
- if setuptools.bootstrap_install_from:
- self.easy_install(setuptools.bootstrap_install_from)
- setuptools.bootstrap_install_from = None
-
+
+ if setuptools.bootstrap_install_from:
+ self.easy_install(setuptools.bootstrap_install_from)
+ setuptools.bootstrap_install_from = None
+
self.install_namespaces()
- # create an .egg-link in the installation dir, pointing to our egg
- log.info("Creating %s (link to %s)", self.egg_link, self.egg_base)
- if not self.dry_run:
- with open(self.egg_link, "w") as f:
- f.write(self.egg_path + "\n" + self.setup_path)
- # postprocess the installed distro, fixing up .pth, installing scripts,
- # and handling requirements
- self.process_distribution(None, self.dist, not self.no_deps)
-
- def uninstall_link(self):
- if os.path.exists(self.egg_link):
- log.info("Removing %s (link to %s)", self.egg_link, self.egg_base)
- egg_link_file = open(self.egg_link)
- contents = [line.rstrip() for line in egg_link_file]
- egg_link_file.close()
+ # create an .egg-link in the installation dir, pointing to our egg
+ log.info("Creating %s (link to %s)", self.egg_link, self.egg_base)
+ if not self.dry_run:
+ with open(self.egg_link, "w") as f:
+ f.write(self.egg_path + "\n" + self.setup_path)
+ # postprocess the installed distro, fixing up .pth, installing scripts,
+ # and handling requirements
+ self.process_distribution(None, self.dist, not self.no_deps)
+
+ def uninstall_link(self):
+ if os.path.exists(self.egg_link):
+ log.info("Removing %s (link to %s)", self.egg_link, self.egg_base)
+ egg_link_file = open(self.egg_link)
+ contents = [line.rstrip() for line in egg_link_file]
+ egg_link_file.close()
if contents not in ([self.egg_path], [self.egg_path, self.setup_path]):
- log.warn("Link points to %s: uninstall aborted", contents)
- return
- if not self.dry_run:
- os.unlink(self.egg_link)
- if not self.dry_run:
- self.update_pth(self.dist) # remove any .pth link to us
- if self.distribution.scripts:
- # XXX should also check for entry point scripts!
- log.warn("Note: you must uninstall or replace scripts manually!")
-
- def install_egg_scripts(self, dist):
- if dist is not self.dist:
- # Installing a dependency, so fall back to normal behavior
- return easy_install.install_egg_scripts(self, dist)
-
- # create wrapper scripts in the script dir, pointing to dist.scripts
-
- # new-style...
- self.install_wrapper_scripts(dist)
-
- # ...and old-style
- for script_name in self.distribution.scripts or []:
- script_path = os.path.abspath(convert_path(script_name))
- script_name = os.path.basename(script_path)
- with io.open(script_path) as strm:
- script_text = strm.read()
- self.install_script(dist, script_name, script_text, script_path)
-
- def install_wrapper_scripts(self, dist):
- dist = VersionlessRequirement(dist)
- return easy_install.install_wrapper_scripts(self, dist)
-
-
+ log.warn("Link points to %s: uninstall aborted", contents)
+ return
+ if not self.dry_run:
+ os.unlink(self.egg_link)
+ if not self.dry_run:
+ self.update_pth(self.dist) # remove any .pth link to us
+ if self.distribution.scripts:
+ # XXX should also check for entry point scripts!
+ log.warn("Note: you must uninstall or replace scripts manually!")
+
+ def install_egg_scripts(self, dist):
+ if dist is not self.dist:
+ # Installing a dependency, so fall back to normal behavior
+ return easy_install.install_egg_scripts(self, dist)
+
+ # create wrapper scripts in the script dir, pointing to dist.scripts
+
+ # new-style...
+ self.install_wrapper_scripts(dist)
+
+ # ...and old-style
+ for script_name in self.distribution.scripts or []:
+ script_path = os.path.abspath(convert_path(script_name))
+ script_name = os.path.basename(script_path)
+ with io.open(script_path) as strm:
+ script_text = strm.read()
+ self.install_script(dist, script_name, script_text, script_path)
+
+ def install_wrapper_scripts(self, dist):
+ dist = VersionlessRequirement(dist)
+ return easy_install.install_wrapper_scripts(self, dist)
+
+
class VersionlessRequirement:
- """
- Adapt a pkg_resources.Distribution to simply return the project
- name as the 'requirement' so that scripts will work across
- multiple versions.
-
+ """
+ Adapt a pkg_resources.Distribution to simply return the project
+ name as the 'requirement' so that scripts will work across
+ multiple versions.
+
>>> from pkg_resources import Distribution
- >>> dist = Distribution(project_name='foo', version='1.0')
- >>> str(dist.as_requirement())
- 'foo==1.0'
- >>> adapted_dist = VersionlessRequirement(dist)
- >>> str(adapted_dist.as_requirement())
- 'foo'
- """
-
- def __init__(self, dist):
- self.__dist = dist
-
- def __getattr__(self, name):
- return getattr(self.__dist, name)
-
- def as_requirement(self):
- return self.project_name
+ >>> dist = Distribution(project_name='foo', version='1.0')
+ >>> str(dist.as_requirement())
+ 'foo==1.0'
+ >>> adapted_dist = VersionlessRequirement(dist)
+ >>> str(adapted_dist.as_requirement())
+ 'foo'
+ """
+
+ def __init__(self, dist):
+ self.__dist = dist
+
+ def __getattr__(self, name):
+ return getattr(self.__dist, name)
+
+ def as_requirement(self):
+ return self.project_name
diff --git a/contrib/python/setuptools/py3/setuptools/command/easy_install.py b/contrib/python/setuptools/py3/setuptools/command/easy_install.py
index c8b87493a5..fc848d0d1c 100644
--- a/contrib/python/setuptools/py3/setuptools/command/easy_install.py
+++ b/contrib/python/setuptools/py3/setuptools/command/easy_install.py
@@ -1,100 +1,100 @@
-"""
-Easy Install
-------------
-
-A tool for doing automatic download/extract/build of distutils-based Python
-packages. For detailed documentation, see the accompanying EasyInstall.txt
-file, or visit the `EasyInstall home page`__.
-
+"""
+Easy Install
+------------
+
+A tool for doing automatic download/extract/build of distutils-based Python
+packages. For detailed documentation, see the accompanying EasyInstall.txt
+file, or visit the `EasyInstall home page`__.
+
__ https://setuptools.pypa.io/en/latest/deprecated/easy_install.html
-
-"""
-
-from glob import glob
-from distutils.util import get_platform
-from distutils.util import convert_path, subst_vars
+
+"""
+
+from glob import glob
+from distutils.util import get_platform
+from distutils.util import convert_path, subst_vars
from distutils.errors import (
DistutilsArgError, DistutilsOptionError,
DistutilsError, DistutilsPlatformError,
)
-from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
-from distutils import log, dir_util
-from distutils.command.build_scripts import first_line_re
-from distutils.spawn import find_executable
-import sys
-import os
-import zipimport
-import shutil
-import tempfile
-import zipfile
-import re
-import stat
-import random
-import textwrap
-import warnings
-import site
-import struct
-import contextlib
-import subprocess
-import shlex
-import io
+from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
+from distutils import log, dir_util
+from distutils.command.build_scripts import first_line_re
+from distutils.spawn import find_executable
+import sys
+import os
+import zipimport
+import shutil
+import tempfile
+import zipfile
+import re
+import stat
+import random
+import textwrap
+import warnings
+import site
+import struct
+import contextlib
+import subprocess
+import shlex
+import io
import configparser
-
-
+
+
from sysconfig import get_config_vars, get_path
from setuptools import SetuptoolsDeprecationWarning
-from setuptools import Command
-from setuptools.sandbox import run_setup
-from setuptools.command import setopt
-from setuptools.archive_util import unpack_archive
+from setuptools import Command
+from setuptools.sandbox import run_setup
+from setuptools.command import setopt
+from setuptools.archive_util import unpack_archive
from setuptools.package_index import (
PackageIndex, parse_requirement_arg, URL_SCHEME,
)
-from setuptools.command import bdist_egg, egg_info
+from setuptools.command import bdist_egg, egg_info
from setuptools.wheel import Wheel
-from pkg_resources import (
- yield_lines, normalize_path, resource_string, ensure_directory,
- get_distribution, find_distributions, Environment, Requirement,
- Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound,
- VersionConflict, DEVELOP_DIST,
-)
+from pkg_resources import (
+ yield_lines, normalize_path, resource_string, ensure_directory,
+ get_distribution, find_distributions, Environment, Requirement,
+ Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound,
+ VersionConflict, DEVELOP_DIST,
+)
import pkg_resources
-
-# Turn on PEP440Warnings
-warnings.filterwarnings("default", category=pkg_resources.PEP440Warning)
-
-__all__ = [
- 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg',
+
+# Turn on PEP440Warnings
+warnings.filterwarnings("default", category=pkg_resources.PEP440Warning)
+
+__all__ = [
+ 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg',
'get_exe_prefixes',
-]
-
-
-def is_64bit():
- return struct.calcsize("P") == 8
-
-
-def samefile(p1, p2):
+]
+
+
+def is_64bit():
+ return struct.calcsize("P") == 8
+
+
+def samefile(p1, p2):
"""
Determine if two paths reference the same file.
Augments os.path.samefile to work on Windows and
suppresses errors if the path doesn't exist.
"""
- both_exist = os.path.exists(p1) and os.path.exists(p2)
- use_samefile = hasattr(os.path, 'samefile') and both_exist
- if use_samefile:
- return os.path.samefile(p1, p2)
- norm_p1 = os.path.normpath(os.path.normcase(p1))
- norm_p2 = os.path.normpath(os.path.normcase(p2))
- return norm_p1 == norm_p2
-
-
+ both_exist = os.path.exists(p1) and os.path.exists(p2)
+ use_samefile = hasattr(os.path, 'samefile') and both_exist
+ if use_samefile:
+ return os.path.samefile(p1, p2)
+ norm_p1 = os.path.normpath(os.path.normcase(p1))
+ norm_p2 = os.path.normpath(os.path.normcase(p2))
+ return norm_p1 == norm_p2
+
+
def _to_bytes(s):
return s.encode('utf8')
-
+
def isascii(s):
try:
s.encode('ascii')
@@ -102,294 +102,294 @@ def isascii(s):
except UnicodeError:
return False
-
+
def _one_liner(text):
return textwrap.dedent(text).strip().replace('\n', '; ')
-
-
-class easy_install(Command):
- """Manage a download/build/install process"""
- description = "Find/get/install Python packages"
- command_consumes_arguments = True
-
- user_options = [
- ('prefix=', None, "installation prefix"),
- ("zip-ok", "z", "install package as a zipfile"),
- ("multi-version", "m", "make apps have to require() a version"),
- ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"),
- ("install-dir=", "d", "install package to DIR"),
- ("script-dir=", "s", "install scripts to DIR"),
- ("exclude-scripts", "x", "Don't install scripts"),
- ("always-copy", "a", "Copy all needed packages to install dir"),
- ("index-url=", "i", "base URL of Python Package Index"),
- ("find-links=", "f", "additional URL(s) to search for packages"),
- ("build-directory=", "b",
- "download/extract/build in DIR; keep the results"),
- ('optimize=', 'O',
- "also compile with optimization: -O1 for \"python -O\", "
- "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
- ('record=', None,
- "filename in which to record list of installed files"),
- ('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
- ('site-dirs=', 'S', "list of directories where .pth files work"),
- ('editable', 'e', "Install specified packages in editable form"),
- ('no-deps', 'N', "don't install dependencies"),
- ('allow-hosts=', 'H', "pattern(s) that hostnames must match"),
- ('local-snapshots-ok', 'l',
- "allow building eggs from local checkouts"),
- ('version', None, "print version information and exit"),
- ('no-find-links', None,
+
+
+class easy_install(Command):
+ """Manage a download/build/install process"""
+ description = "Find/get/install Python packages"
+ command_consumes_arguments = True
+
+ user_options = [
+ ('prefix=', None, "installation prefix"),
+ ("zip-ok", "z", "install package as a zipfile"),
+ ("multi-version", "m", "make apps have to require() a version"),
+ ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"),
+ ("install-dir=", "d", "install package to DIR"),
+ ("script-dir=", "s", "install scripts to DIR"),
+ ("exclude-scripts", "x", "Don't install scripts"),
+ ("always-copy", "a", "Copy all needed packages to install dir"),
+ ("index-url=", "i", "base URL of Python Package Index"),
+ ("find-links=", "f", "additional URL(s) to search for packages"),
+ ("build-directory=", "b",
+ "download/extract/build in DIR; keep the results"),
+ ('optimize=', 'O',
+ "also compile with optimization: -O1 for \"python -O\", "
+ "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
+ ('record=', None,
+ "filename in which to record list of installed files"),
+ ('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
+ ('site-dirs=', 'S', "list of directories where .pth files work"),
+ ('editable', 'e', "Install specified packages in editable form"),
+ ('no-deps', 'N', "don't install dependencies"),
+ ('allow-hosts=', 'H', "pattern(s) that hostnames must match"),
+ ('local-snapshots-ok', 'l',
+ "allow building eggs from local checkouts"),
+ ('version', None, "print version information and exit"),
+ ('no-find-links', None,
"Don't load find-links defined in packages being installed"),
('user', None, "install in user site-package '%s'" % site.USER_SITE)
- ]
- boolean_options = [
- 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy',
- 'editable',
+ ]
+ boolean_options = [
+ 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy',
+ 'editable',
'no-deps', 'local-snapshots-ok', 'version',
'user'
- ]
-
- negative_opt = {'always-unzip': 'zip-ok'}
- create_index = PackageIndex
-
- def initialize_options(self):
+ ]
+
+ negative_opt = {'always-unzip': 'zip-ok'}
+ create_index = PackageIndex
+
+ def initialize_options(self):
warnings.warn(
"easy_install command is deprecated. "
"Use build and pip and other standards-based tools.",
EasyInstallDeprecationWarning,
)
- # the --user option seems to be an opt-in one,
- # so the default should be False.
- self.user = 0
- self.zip_ok = self.local_snapshots_ok = None
- self.install_dir = self.script_dir = self.exclude_scripts = None
- self.index_url = None
- self.find_links = None
- self.build_directory = None
- self.args = None
- self.optimize = self.record = None
- self.upgrade = self.always_copy = self.multi_version = None
- self.editable = self.no_deps = self.allow_hosts = None
- self.root = self.prefix = self.no_report = None
- self.version = None
- self.install_purelib = None # for pure module distributions
- self.install_platlib = None # non-pure (dists w/ extensions)
- self.install_headers = None # for C/C++ headers
- self.install_lib = None # set to either purelib or platlib
- self.install_scripts = None
- self.install_data = None
- self.install_base = None
- self.install_platbase = None
- if site.ENABLE_USER_SITE:
- self.install_userbase = site.USER_BASE
- self.install_usersite = site.USER_SITE
- else:
- self.install_userbase = None
- self.install_usersite = None
- self.no_find_links = None
-
- # Options not specifiable via command line
- self.package_index = None
- self.pth_file = self.always_copy_from = None
- self.site_dirs = None
- self.installed_projects = {}
- # Always read easy_install options, even if we are subclassed, or have
- # an independent instance created. This ensures that defaults will
- # always come from the standard configuration file(s)' "easy_install"
- # section, even if this is a "develop" or "install" command, or some
- # other embedding.
- self._dry_run = None
- self.verbose = self.distribution.verbose
- self.distribution._set_command_options(
- self, self.distribution.get_option_dict('easy_install')
- )
-
- def delete_blockers(self, blockers):
- extant_blockers = (
- filename for filename in blockers
- if os.path.exists(filename) or os.path.islink(filename)
- )
- list(map(self._delete_path, extant_blockers))
-
- def _delete_path(self, path):
- log.info("Deleting %s", path)
- if self.dry_run:
- return
-
- is_tree = os.path.isdir(path) and not os.path.islink(path)
- remover = rmtree if is_tree else os.unlink
- remover(path)
-
- @staticmethod
- def _render_version():
- """
- Render the Setuptools version and installation details, then exit.
- """
+ # the --user option seems to be an opt-in one,
+ # so the default should be False.
+ self.user = 0
+ self.zip_ok = self.local_snapshots_ok = None
+ self.install_dir = self.script_dir = self.exclude_scripts = None
+ self.index_url = None
+ self.find_links = None
+ self.build_directory = None
+ self.args = None
+ self.optimize = self.record = None
+ self.upgrade = self.always_copy = self.multi_version = None
+ self.editable = self.no_deps = self.allow_hosts = None
+ self.root = self.prefix = self.no_report = None
+ self.version = None
+ self.install_purelib = None # for pure module distributions
+ self.install_platlib = None # non-pure (dists w/ extensions)
+ self.install_headers = None # for C/C++ headers
+ self.install_lib = None # set to either purelib or platlib
+ self.install_scripts = None
+ self.install_data = None
+ self.install_base = None
+ self.install_platbase = None
+ if site.ENABLE_USER_SITE:
+ self.install_userbase = site.USER_BASE
+ self.install_usersite = site.USER_SITE
+ else:
+ self.install_userbase = None
+ self.install_usersite = None
+ self.no_find_links = None
+
+ # Options not specifiable via command line
+ self.package_index = None
+ self.pth_file = self.always_copy_from = None
+ self.site_dirs = None
+ self.installed_projects = {}
+ # Always read easy_install options, even if we are subclassed, or have
+ # an independent instance created. This ensures that defaults will
+ # always come from the standard configuration file(s)' "easy_install"
+ # section, even if this is a "develop" or "install" command, or some
+ # other embedding.
+ self._dry_run = None
+ self.verbose = self.distribution.verbose
+ self.distribution._set_command_options(
+ self, self.distribution.get_option_dict('easy_install')
+ )
+
+ def delete_blockers(self, blockers):
+ extant_blockers = (
+ filename for filename in blockers
+ if os.path.exists(filename) or os.path.islink(filename)
+ )
+ list(map(self._delete_path, extant_blockers))
+
+ def _delete_path(self, path):
+ log.info("Deleting %s", path)
+ if self.dry_run:
+ return
+
+ is_tree = os.path.isdir(path) and not os.path.islink(path)
+ remover = rmtree if is_tree else os.unlink
+ remover(path)
+
+ @staticmethod
+ def _render_version():
+ """
+ Render the Setuptools version and installation details, then exit.
+ """
ver = '{}.{}'.format(*sys.version_info)
- dist = get_distribution('setuptools')
- tmpl = 'setuptools {dist.version} from {dist.location} (Python {ver})'
- print(tmpl.format(**locals()))
- raise SystemExit()
-
+ dist = get_distribution('setuptools')
+ tmpl = 'setuptools {dist.version} from {dist.location} (Python {ver})'
+ print(tmpl.format(**locals()))
+ raise SystemExit()
+
def finalize_options(self): # noqa: C901 # is too complex (25) # FIXME
- self.version and self._render_version()
-
- py_version = sys.version.split()[0]
- prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix')
-
- self.config_vars = {
- 'dist_name': self.distribution.get_name(),
- 'dist_version': self.distribution.get_version(),
- 'dist_fullname': self.distribution.get_fullname(),
- 'py_version': py_version,
- 'py_version_short': py_version[0:3],
- 'py_version_nodot': py_version[0] + py_version[2],
- 'sys_prefix': prefix,
- 'prefix': prefix,
- 'sys_exec_prefix': exec_prefix,
- 'exec_prefix': exec_prefix,
- # Only python 3.2+ has abiflags
- 'abiflags': getattr(sys, 'abiflags', ''),
- }
-
- if site.ENABLE_USER_SITE:
- self.config_vars['userbase'] = self.install_userbase
- self.config_vars['usersite'] = self.install_usersite
-
+ self.version and self._render_version()
+
+ py_version = sys.version.split()[0]
+ prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix')
+
+ self.config_vars = {
+ 'dist_name': self.distribution.get_name(),
+ 'dist_version': self.distribution.get_version(),
+ 'dist_fullname': self.distribution.get_fullname(),
+ 'py_version': py_version,
+ 'py_version_short': py_version[0:3],
+ 'py_version_nodot': py_version[0] + py_version[2],
+ 'sys_prefix': prefix,
+ 'prefix': prefix,
+ 'sys_exec_prefix': exec_prefix,
+ 'exec_prefix': exec_prefix,
+ # Only python 3.2+ has abiflags
+ 'abiflags': getattr(sys, 'abiflags', ''),
+ }
+
+ if site.ENABLE_USER_SITE:
+ self.config_vars['userbase'] = self.install_userbase
+ self.config_vars['usersite'] = self.install_usersite
+
elif self.user:
log.warn("WARNING: The user site-packages directory is disabled.")
- self._fix_install_dir_for_user_site()
-
- self.expand_basedirs()
- self.expand_dirs()
-
+ self._fix_install_dir_for_user_site()
+
+ self.expand_basedirs()
+ self.expand_dirs()
+
self._expand(
'install_dir', 'script_dir', 'build_directory',
'site_dirs',
)
- # If a non-default installation directory was specified, default the
- # script directory to match it.
- if self.script_dir is None:
- self.script_dir = self.install_dir
-
- if self.no_find_links is None:
- self.no_find_links = False
-
- # Let install_dir get set by install_lib command, which in turn
- # gets its info from the install command, and takes into account
- # --prefix and --home and all that other crud.
- self.set_undefined_options(
- 'install_lib', ('install_dir', 'install_dir')
- )
- # Likewise, set default script_dir from 'install_scripts.install_dir'
- self.set_undefined_options(
- 'install_scripts', ('install_dir', 'script_dir')
- )
-
- if self.user and self.install_purelib:
- self.install_dir = self.install_purelib
- self.script_dir = self.install_scripts
- # default --record from the install command
- self.set_undefined_options('install', ('record', 'record'))
- # Should this be moved to the if statement below? It's not used
- # elsewhere
- normpath = map(normalize_path, sys.path)
- self.all_site_dirs = get_site_dirs()
- if self.site_dirs is not None:
- site_dirs = [
- os.path.expanduser(s.strip()) for s in
- self.site_dirs.split(',')
- ]
- for d in site_dirs:
- if not os.path.isdir(d):
- log.warn("%s (in --site-dirs) does not exist", d)
- elif normalize_path(d) not in normpath:
- raise DistutilsOptionError(
- d + " (in --site-dirs) is not on sys.path"
- )
- else:
- self.all_site_dirs.append(normalize_path(d))
- if not self.editable:
- self.check_site_dir()
+ # If a non-default installation directory was specified, default the
+ # script directory to match it.
+ if self.script_dir is None:
+ self.script_dir = self.install_dir
+
+ if self.no_find_links is None:
+ self.no_find_links = False
+
+ # Let install_dir get set by install_lib command, which in turn
+ # gets its info from the install command, and takes into account
+ # --prefix and --home and all that other crud.
+ self.set_undefined_options(
+ 'install_lib', ('install_dir', 'install_dir')
+ )
+ # Likewise, set default script_dir from 'install_scripts.install_dir'
+ self.set_undefined_options(
+ 'install_scripts', ('install_dir', 'script_dir')
+ )
+
+ if self.user and self.install_purelib:
+ self.install_dir = self.install_purelib
+ self.script_dir = self.install_scripts
+ # default --record from the install command
+ self.set_undefined_options('install', ('record', 'record'))
+ # Should this be moved to the if statement below? It's not used
+ # elsewhere
+ normpath = map(normalize_path, sys.path)
+ self.all_site_dirs = get_site_dirs()
+ if self.site_dirs is not None:
+ site_dirs = [
+ os.path.expanduser(s.strip()) for s in
+ self.site_dirs.split(',')
+ ]
+ for d in site_dirs:
+ if not os.path.isdir(d):
+ log.warn("%s (in --site-dirs) does not exist", d)
+ elif normalize_path(d) not in normpath:
+ raise DistutilsOptionError(
+ d + " (in --site-dirs) is not on sys.path"
+ )
+ else:
+ self.all_site_dirs.append(normalize_path(d))
+ if not self.editable:
+ self.check_site_dir()
self.index_url = self.index_url or "https://pypi.org/simple/"
- self.shadow_path = self.all_site_dirs[:]
- for path_item in self.install_dir, normalize_path(self.script_dir):
- if path_item not in self.shadow_path:
- self.shadow_path.insert(0, path_item)
-
- if self.allow_hosts is not None:
- hosts = [s.strip() for s in self.allow_hosts.split(',')]
- else:
- hosts = ['*']
- if self.package_index is None:
- self.package_index = self.create_index(
- self.index_url, search_path=self.shadow_path, hosts=hosts,
- )
- self.local_index = Environment(self.shadow_path + sys.path)
-
- if self.find_links is not None:
+ self.shadow_path = self.all_site_dirs[:]
+ for path_item in self.install_dir, normalize_path(self.script_dir):
+ if path_item not in self.shadow_path:
+ self.shadow_path.insert(0, path_item)
+
+ if self.allow_hosts is not None:
+ hosts = [s.strip() for s in self.allow_hosts.split(',')]
+ else:
+ hosts = ['*']
+ if self.package_index is None:
+ self.package_index = self.create_index(
+ self.index_url, search_path=self.shadow_path, hosts=hosts,
+ )
+ self.local_index = Environment(self.shadow_path + sys.path)
+
+ if self.find_links is not None:
if isinstance(self.find_links, str):
- self.find_links = self.find_links.split()
- else:
- self.find_links = []
- if self.local_snapshots_ok:
- self.package_index.scan_egg_links(self.shadow_path + sys.path)
- if not self.no_find_links:
- self.package_index.add_find_links(self.find_links)
- self.set_undefined_options('install_lib', ('optimize', 'optimize'))
- if not isinstance(self.optimize, int):
- try:
- self.optimize = int(self.optimize)
- if not (0 <= self.optimize <= 2):
- raise ValueError
+ self.find_links = self.find_links.split()
+ else:
+ self.find_links = []
+ if self.local_snapshots_ok:
+ self.package_index.scan_egg_links(self.shadow_path + sys.path)
+ if not self.no_find_links:
+ self.package_index.add_find_links(self.find_links)
+ self.set_undefined_options('install_lib', ('optimize', 'optimize'))
+ if not isinstance(self.optimize, int):
+ try:
+ self.optimize = int(self.optimize)
+ if not (0 <= self.optimize <= 2):
+ raise ValueError
except ValueError as e:
raise DistutilsOptionError(
"--optimize must be 0, 1, or 2"
) from e
-
- if self.editable and not self.build_directory:
- raise DistutilsArgError(
- "Must specify a build directory (-b) when using --editable"
- )
- if not self.args:
- raise DistutilsArgError(
- "No urls, filenames, or requirements specified (see --help)")
-
- self.outputs = []
-
- def _fix_install_dir_for_user_site(self):
- """
- Fix the install_dir if "--user" was used.
- """
- if not self.user or not site.ENABLE_USER_SITE:
- return
-
- self.create_home_path()
- if self.install_userbase is None:
- msg = "User base directory is not specified"
- raise DistutilsPlatformError(msg)
- self.install_base = self.install_platbase = self.install_userbase
- scheme_name = os.name.replace('posix', 'unix') + '_user'
- self.select_scheme(scheme_name)
-
- def _expand_attrs(self, attrs):
- for attr in attrs:
- val = getattr(self, attr)
- if val is not None:
- if os.name == 'posix' or os.name == 'nt':
- val = os.path.expanduser(val)
- val = subst_vars(val, self.config_vars)
- setattr(self, attr, val)
-
- def expand_basedirs(self):
- """Calls `os.path.expanduser` on install_base, install_platbase and
- root."""
- self._expand_attrs(['install_base', 'install_platbase', 'root'])
-
- def expand_dirs(self):
- """Calls `os.path.expanduser` on install dirs."""
+
+ if self.editable and not self.build_directory:
+ raise DistutilsArgError(
+ "Must specify a build directory (-b) when using --editable"
+ )
+ if not self.args:
+ raise DistutilsArgError(
+ "No urls, filenames, or requirements specified (see --help)")
+
+ self.outputs = []
+
+ def _fix_install_dir_for_user_site(self):
+ """
+ Fix the install_dir if "--user" was used.
+ """
+ if not self.user or not site.ENABLE_USER_SITE:
+ return
+
+ self.create_home_path()
+ if self.install_userbase is None:
+ msg = "User base directory is not specified"
+ raise DistutilsPlatformError(msg)
+ self.install_base = self.install_platbase = self.install_userbase
+ scheme_name = os.name.replace('posix', 'unix') + '_user'
+ self.select_scheme(scheme_name)
+
+ def _expand_attrs(self, attrs):
+ for attr in attrs:
+ val = getattr(self, attr)
+ if val is not None:
+ if os.name == 'posix' or os.name == 'nt':
+ val = os.path.expanduser(val)
+ val = subst_vars(val, self.config_vars)
+ setattr(self, attr, val)
+
+ def expand_basedirs(self):
+ """Calls `os.path.expanduser` on install_base, install_platbase and
+ root."""
+ self._expand_attrs(['install_base', 'install_platbase', 'root'])
+
+ def expand_dirs(self):
+ """Calls `os.path.expanduser` on install dirs."""
dirs = [
'install_purelib',
'install_platlib',
@@ -399,7 +399,7 @@ class easy_install(Command):
'install_data',
]
self._expand_attrs(dirs)
-
+
def run(self, show_deprecation=True):
if show_deprecation:
self.announce(
@@ -407,231 +407,231 @@ class easy_install(Command):
"and will be removed in a future version.",
log.WARN,
)
- if self.verbose != self.distribution.verbose:
- log.set_verbosity(self.verbose)
- try:
- for spec in self.args:
- self.easy_install(spec, not self.no_deps)
- if self.record:
- outputs = self.outputs
- if self.root: # strip any package prefix
- root_len = len(self.root)
- for counter in range(len(outputs)):
- outputs[counter] = outputs[counter][root_len:]
- from distutils import file_util
-
- self.execute(
- file_util.write_file, (self.record, outputs),
- "writing list of installed files to '%s'" %
- self.record
- )
- self.warn_deprecated_options()
- finally:
- log.set_verbosity(self.distribution.verbose)
-
- def pseudo_tempname(self):
- """Return a pseudo-tempname base in the install directory.
- This code is intentionally naive; if a malicious party can write to
- the target directory you're already in deep doodoo.
- """
- try:
- pid = os.getpid()
+ if self.verbose != self.distribution.verbose:
+ log.set_verbosity(self.verbose)
+ try:
+ for spec in self.args:
+ self.easy_install(spec, not self.no_deps)
+ if self.record:
+ outputs = self.outputs
+ if self.root: # strip any package prefix
+ root_len = len(self.root)
+ for counter in range(len(outputs)):
+ outputs[counter] = outputs[counter][root_len:]
+ from distutils import file_util
+
+ self.execute(
+ file_util.write_file, (self.record, outputs),
+ "writing list of installed files to '%s'" %
+ self.record
+ )
+ self.warn_deprecated_options()
+ finally:
+ log.set_verbosity(self.distribution.verbose)
+
+ def pseudo_tempname(self):
+ """Return a pseudo-tempname base in the install directory.
+ This code is intentionally naive; if a malicious party can write to
+ the target directory you're already in deep doodoo.
+ """
+ try:
+ pid = os.getpid()
except Exception:
- pid = random.randint(0, sys.maxsize)
- return os.path.join(self.install_dir, "test-easy-install-%s" % pid)
-
- def warn_deprecated_options(self):
- pass
-
+ pid = random.randint(0, sys.maxsize)
+ return os.path.join(self.install_dir, "test-easy-install-%s" % pid)
+
+ def warn_deprecated_options(self):
+ pass
+
def check_site_dir(self): # noqa: C901 # is too complex (12) # FIXME
- """Verify that self.install_dir is .pth-capable dir, if needed"""
-
- instdir = normalize_path(self.install_dir)
- pth_file = os.path.join(instdir, 'easy-install.pth')
-
+ """Verify that self.install_dir is .pth-capable dir, if needed"""
+
+ instdir = normalize_path(self.install_dir)
+ pth_file = os.path.join(instdir, 'easy-install.pth')
+
if not os.path.exists(instdir):
try:
os.makedirs(instdir)
except (OSError, IOError):
self.cant_write_to_target()
- # Is it a configured, PYTHONPATH, implicit, or explicit site dir?
- is_site_dir = instdir in self.all_site_dirs
-
- if not is_site_dir and not self.multi_version:
- # No? Then directly test whether it does .pth file processing
- is_site_dir = self.check_pth_processing()
- else:
- # make sure we can write to target dir
- testfile = self.pseudo_tempname() + '.write-test'
- test_exists = os.path.exists(testfile)
- try:
- if test_exists:
- os.unlink(testfile)
- open(testfile, 'w').close()
- os.unlink(testfile)
- except (OSError, IOError):
- self.cant_write_to_target()
-
- if not is_site_dir and not self.multi_version:
+ # Is it a configured, PYTHONPATH, implicit, or explicit site dir?
+ is_site_dir = instdir in self.all_site_dirs
+
+ if not is_site_dir and not self.multi_version:
+ # No? Then directly test whether it does .pth file processing
+ is_site_dir = self.check_pth_processing()
+ else:
+ # make sure we can write to target dir
+ testfile = self.pseudo_tempname() + '.write-test'
+ test_exists = os.path.exists(testfile)
+ try:
+ if test_exists:
+ os.unlink(testfile)
+ open(testfile, 'w').close()
+ os.unlink(testfile)
+ except (OSError, IOError):
+ self.cant_write_to_target()
+
+ if not is_site_dir and not self.multi_version:
# Can't install non-multi to non-site dir with easy_install
pythonpath = os.environ.get('PYTHONPATH', '')
log.warn(self.__no_default_msg, self.install_dir, pythonpath)
-
- if is_site_dir:
- if self.pth_file is None:
- self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
- else:
- self.pth_file = None
-
+
+ if is_site_dir:
+ if self.pth_file is None:
+ self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
+ else:
+ self.pth_file = None
+
if self.multi_version and not os.path.exists(pth_file):
self.pth_file = None # don't create a .pth file
- self.install_dir = instdir
-
- __cant_write_msg = textwrap.dedent("""
- can't create or remove files in install directory
-
- The following error occurred while trying to add or remove files in the
- installation directory:
-
- %s
-
- The installation directory you specified (via --install-dir, --prefix, or
- the distutils default setting) was:
-
- %s
+ self.install_dir = instdir
+
+ __cant_write_msg = textwrap.dedent("""
+ can't create or remove files in install directory
+
+ The following error occurred while trying to add or remove files in the
+ installation directory:
+
+ %s
+
+ The installation directory you specified (via --install-dir, --prefix, or
+ the distutils default setting) was:
+
+ %s
""").lstrip() # noqa
-
- __not_exists_id = textwrap.dedent("""
- This directory does not currently exist. Please create it and try again, or
- choose a different installation directory (using the -d or --install-dir
- option).
+
+ __not_exists_id = textwrap.dedent("""
+ This directory does not currently exist. Please create it and try again, or
+ choose a different installation directory (using the -d or --install-dir
+ option).
""").lstrip() # noqa
-
- __access_msg = textwrap.dedent("""
- Perhaps your account does not have write access to this directory? If the
- installation directory is a system-owned directory, you may need to sign in
- as the administrator or "root" account. If you do not have administrative
- access to this machine, you may wish to choose a different installation
- directory, preferably one that is listed in your PYTHONPATH environment
- variable.
-
- For information on other options, you may wish to consult the
- documentation at:
-
+
+ __access_msg = textwrap.dedent("""
+ Perhaps your account does not have write access to this directory? If the
+ installation directory is a system-owned directory, you may need to sign in
+ as the administrator or "root" account. If you do not have administrative
+ access to this machine, you may wish to choose a different installation
+ directory, preferably one that is listed in your PYTHONPATH environment
+ variable.
+
+ For information on other options, you may wish to consult the
+ documentation at:
+
https://setuptools.pypa.io/en/latest/deprecated/easy_install.html
-
- Please make the appropriate changes for your system and try again.
+
+ Please make the appropriate changes for your system and try again.
""").lstrip() # noqa
-
- def cant_write_to_target(self):
- msg = self.__cant_write_msg % (sys.exc_info()[1], self.install_dir,)
-
- if not os.path.exists(self.install_dir):
- msg += '\n' + self.__not_exists_id
- else:
- msg += '\n' + self.__access_msg
- raise DistutilsError(msg)
-
- def check_pth_processing(self):
- """Empirically verify whether .pth files are supported in inst. dir"""
- instdir = self.install_dir
- log.info("Checking .pth file support in %s", instdir)
- pth_file = self.pseudo_tempname() + ".pth"
- ok_file = pth_file + '.ok'
- ok_exists = os.path.exists(ok_file)
+
+ def cant_write_to_target(self):
+ msg = self.__cant_write_msg % (sys.exc_info()[1], self.install_dir,)
+
+ if not os.path.exists(self.install_dir):
+ msg += '\n' + self.__not_exists_id
+ else:
+ msg += '\n' + self.__access_msg
+ raise DistutilsError(msg)
+
+ def check_pth_processing(self):
+ """Empirically verify whether .pth files are supported in inst. dir"""
+ instdir = self.install_dir
+ log.info("Checking .pth file support in %s", instdir)
+ pth_file = self.pseudo_tempname() + ".pth"
+ ok_file = pth_file + '.ok'
+ ok_exists = os.path.exists(ok_file)
tmpl = _one_liner("""
import os
f = open({ok_file!r}, 'w')
f.write('OK')
f.close()
""") + '\n'
- try:
- if ok_exists:
- os.unlink(ok_file)
- dirname = os.path.dirname(ok_file)
+ try:
+ if ok_exists:
+ os.unlink(ok_file)
+ dirname = os.path.dirname(ok_file)
os.makedirs(dirname, exist_ok=True)
- f = open(pth_file, 'w')
- except (OSError, IOError):
- self.cant_write_to_target()
- else:
- try:
+ f = open(pth_file, 'w')
+ except (OSError, IOError):
+ self.cant_write_to_target()
+ else:
+ try:
f.write(tmpl.format(**locals()))
- f.close()
- f = None
- executable = sys.executable
- if os.name == 'nt':
- dirname, basename = os.path.split(executable)
- alt = os.path.join(dirname, 'pythonw.exe')
+ f.close()
+ f = None
+ executable = sys.executable
+ if os.name == 'nt':
+ dirname, basename = os.path.split(executable)
+ alt = os.path.join(dirname, 'pythonw.exe')
use_alt = (
basename.lower() == 'python.exe' and
os.path.exists(alt)
)
if use_alt:
- # use pythonw.exe to avoid opening a console window
- executable = alt
-
- from distutils.spawn import spawn
-
- spawn([executable, '-E', '-c', 'pass'], 0)
-
- if os.path.exists(ok_file):
- log.info(
- "TEST PASSED: %s appears to support .pth files",
- instdir
- )
- return True
- finally:
- if f:
- f.close()
- if os.path.exists(ok_file):
- os.unlink(ok_file)
- if os.path.exists(pth_file):
- os.unlink(pth_file)
- if not self.multi_version:
- log.warn("TEST FAILED: %s does NOT support .pth files", instdir)
- return False
-
- def install_egg_scripts(self, dist):
- """Write all the scripts for `dist`, unless scripts are excluded"""
- if not self.exclude_scripts and dist.metadata_isdir('scripts'):
- for script_name in dist.metadata_listdir('scripts'):
- if dist.metadata_isdir('scripts/' + script_name):
- # The "script" is a directory, likely a Python 3
- # __pycache__ directory, so skip it.
- continue
- self.install_script(
- dist, script_name,
- dist.get_metadata('scripts/' + script_name)
- )
- self.install_wrapper_scripts(dist)
-
- def add_output(self, path):
- if os.path.isdir(path):
- for base, dirs, files in os.walk(path):
- for filename in files:
- self.outputs.append(os.path.join(base, filename))
- else:
- self.outputs.append(path)
-
- def not_editable(self, spec):
- if self.editable:
- raise DistutilsArgError(
- "Invalid argument %r: you can't use filenames or URLs "
- "with --editable (except via the --find-links option)."
- % (spec,)
- )
-
- def check_editable(self, spec):
- if not self.editable:
- return
-
- if os.path.exists(os.path.join(self.build_directory, spec.key)):
- raise DistutilsArgError(
- "%r already exists in %s; can't do a checkout there" %
- (spec.key, self.build_directory)
- )
-
+ # use pythonw.exe to avoid opening a console window
+ executable = alt
+
+ from distutils.spawn import spawn
+
+ spawn([executable, '-E', '-c', 'pass'], 0)
+
+ if os.path.exists(ok_file):
+ log.info(
+ "TEST PASSED: %s appears to support .pth files",
+ instdir
+ )
+ return True
+ finally:
+ if f:
+ f.close()
+ if os.path.exists(ok_file):
+ os.unlink(ok_file)
+ if os.path.exists(pth_file):
+ os.unlink(pth_file)
+ if not self.multi_version:
+ log.warn("TEST FAILED: %s does NOT support .pth files", instdir)
+ return False
+
+ def install_egg_scripts(self, dist):
+ """Write all the scripts for `dist`, unless scripts are excluded"""
+ if not self.exclude_scripts and dist.metadata_isdir('scripts'):
+ for script_name in dist.metadata_listdir('scripts'):
+ if dist.metadata_isdir('scripts/' + script_name):
+ # The "script" is a directory, likely a Python 3
+ # __pycache__ directory, so skip it.
+ continue
+ self.install_script(
+ dist, script_name,
+ dist.get_metadata('scripts/' + script_name)
+ )
+ self.install_wrapper_scripts(dist)
+
+ def add_output(self, path):
+ if os.path.isdir(path):
+ for base, dirs, files in os.walk(path):
+ for filename in files:
+ self.outputs.append(os.path.join(base, filename))
+ else:
+ self.outputs.append(path)
+
+ def not_editable(self, spec):
+ if self.editable:
+ raise DistutilsArgError(
+ "Invalid argument %r: you can't use filenames or URLs "
+ "with --editable (except via the --find-links option)."
+ % (spec,)
+ )
+
+ def check_editable(self, spec):
+ if not self.editable:
+ return
+
+ if os.path.exists(os.path.join(self.build_directory, spec.key)):
+ raise DistutilsArgError(
+ "%r already exists in %s; can't do a checkout there" %
+ (spec.key, self.build_directory)
+ )
+
@contextlib.contextmanager
def _tmpdir(self):
tmpdir = tempfile.mkdtemp(prefix=u"easy_install-")
@@ -641,211 +641,211 @@ class easy_install(Command):
finally:
os.path.exists(tmpdir) and rmtree(tmpdir)
- def easy_install(self, spec, deps=False):
+ def easy_install(self, spec, deps=False):
with self._tmpdir() as tmpdir:
- if not isinstance(spec, Requirement):
- if URL_SCHEME(spec):
- # It's a url, download it to tmpdir and process
- self.not_editable(spec)
+ if not isinstance(spec, Requirement):
+ if URL_SCHEME(spec):
+ # It's a url, download it to tmpdir and process
+ self.not_editable(spec)
dl = self.package_index.download(spec, tmpdir)
return self.install_item(None, dl, tmpdir, deps, True)
-
- elif os.path.exists(spec):
- # Existing file or directory, just process it directly
- self.not_editable(spec)
- return self.install_item(None, spec, tmpdir, deps, True)
- else:
- spec = parse_requirement_arg(spec)
-
- self.check_editable(spec)
- dist = self.package_index.fetch_distribution(
- spec, tmpdir, self.upgrade, self.editable,
- not self.always_copy, self.local_index
- )
- if dist is None:
- msg = "Could not find suitable distribution for %r" % spec
- if self.always_copy:
- msg += " (--always-copy skips system and development eggs)"
- raise DistutilsError(msg)
- elif dist.precedence == DEVELOP_DIST:
- # .egg-info dists don't need installing, just process deps
- self.process_distribution(spec, dist, deps, "Using")
- return dist
- else:
- return self.install_item(spec, dist.location, tmpdir, deps)
-
- def install_item(self, spec, download, tmpdir, deps, install_needed=False):
-
- # Installation is also needed if file in tmpdir or is not an egg
- install_needed = install_needed or self.always_copy
- install_needed = install_needed or os.path.dirname(download) == tmpdir
- install_needed = install_needed or not download.endswith('.egg')
- install_needed = install_needed or (
- self.always_copy_from is not None and
- os.path.dirname(normalize_path(download)) ==
- normalize_path(self.always_copy_from)
- )
-
- if spec and not install_needed:
- # at this point, we know it's a local .egg, we just don't know if
- # it's already installed.
- for dist in self.local_index[spec.project_name]:
- if dist.location == download:
- break
- else:
- install_needed = True # it's not in the local index
-
- log.info("Processing %s", os.path.basename(download))
-
- if install_needed:
- dists = self.install_eggs(spec, download, tmpdir)
- for dist in dists:
- self.process_distribution(spec, dist, deps)
- else:
- dists = [self.egg_distribution(download)]
- self.process_distribution(spec, dists[0], deps, "Using")
-
- if spec is not None:
- for dist in dists:
- if dist in spec:
- return dist
-
- def select_scheme(self, name):
- """Sets the install directories by applying the install schemes."""
- # it's the caller's problem if they supply a bad name!
- scheme = INSTALL_SCHEMES[name]
- for key in SCHEME_KEYS:
- attrname = 'install_' + key
- if getattr(self, attrname) is None:
- setattr(self, attrname, scheme[key])
-
+
+ elif os.path.exists(spec):
+ # Existing file or directory, just process it directly
+ self.not_editable(spec)
+ return self.install_item(None, spec, tmpdir, deps, True)
+ else:
+ spec = parse_requirement_arg(spec)
+
+ self.check_editable(spec)
+ dist = self.package_index.fetch_distribution(
+ spec, tmpdir, self.upgrade, self.editable,
+ not self.always_copy, self.local_index
+ )
+ if dist is None:
+ msg = "Could not find suitable distribution for %r" % spec
+ if self.always_copy:
+ msg += " (--always-copy skips system and development eggs)"
+ raise DistutilsError(msg)
+ elif dist.precedence == DEVELOP_DIST:
+ # .egg-info dists don't need installing, just process deps
+ self.process_distribution(spec, dist, deps, "Using")
+ return dist
+ else:
+ return self.install_item(spec, dist.location, tmpdir, deps)
+
+ def install_item(self, spec, download, tmpdir, deps, install_needed=False):
+
+ # Installation is also needed if file in tmpdir or is not an egg
+ install_needed = install_needed or self.always_copy
+ install_needed = install_needed or os.path.dirname(download) == tmpdir
+ install_needed = install_needed or not download.endswith('.egg')
+ install_needed = install_needed or (
+ self.always_copy_from is not None and
+ os.path.dirname(normalize_path(download)) ==
+ normalize_path(self.always_copy_from)
+ )
+
+ if spec and not install_needed:
+ # at this point, we know it's a local .egg, we just don't know if
+ # it's already installed.
+ for dist in self.local_index[spec.project_name]:
+ if dist.location == download:
+ break
+ else:
+ install_needed = True # it's not in the local index
+
+ log.info("Processing %s", os.path.basename(download))
+
+ if install_needed:
+ dists = self.install_eggs(spec, download, tmpdir)
+ for dist in dists:
+ self.process_distribution(spec, dist, deps)
+ else:
+ dists = [self.egg_distribution(download)]
+ self.process_distribution(spec, dists[0], deps, "Using")
+
+ if spec is not None:
+ for dist in dists:
+ if dist in spec:
+ return dist
+
+ def select_scheme(self, name):
+ """Sets the install directories by applying the install schemes."""
+ # it's the caller's problem if they supply a bad name!
+ scheme = INSTALL_SCHEMES[name]
+ for key in SCHEME_KEYS:
+ attrname = 'install_' + key
+ if getattr(self, attrname) is None:
+ setattr(self, attrname, scheme[key])
+
# FIXME: 'easy_install.process_distribution' is too complex (12)
def process_distribution( # noqa: C901
self, requirement, dist, deps=True, *info,
):
- self.update_pth(dist)
- self.package_index.add(dist)
- if dist in self.local_index[dist.key]:
- self.local_index.remove(dist)
- self.local_index.add(dist)
- self.install_egg_scripts(dist)
- self.installed_projects[dist.key] = dist
- log.info(self.installation_report(requirement, dist, *info))
- if (dist.has_metadata('dependency_links.txt') and
- not self.no_find_links):
- self.package_index.add_find_links(
- dist.get_metadata_lines('dependency_links.txt')
- )
- if not deps and not self.always_copy:
- return
- elif requirement is not None and dist.key != requirement.key:
- log.warn("Skipping dependencies for %s", dist)
- return # XXX this is not the distribution we were looking for
- elif requirement is None or dist not in requirement:
- # if we wound up with a different version, resolve what we've got
- distreq = dist.as_requirement()
+ self.update_pth(dist)
+ self.package_index.add(dist)
+ if dist in self.local_index[dist.key]:
+ self.local_index.remove(dist)
+ self.local_index.add(dist)
+ self.install_egg_scripts(dist)
+ self.installed_projects[dist.key] = dist
+ log.info(self.installation_report(requirement, dist, *info))
+ if (dist.has_metadata('dependency_links.txt') and
+ not self.no_find_links):
+ self.package_index.add_find_links(
+ dist.get_metadata_lines('dependency_links.txt')
+ )
+ if not deps and not self.always_copy:
+ return
+ elif requirement is not None and dist.key != requirement.key:
+ log.warn("Skipping dependencies for %s", dist)
+ return # XXX this is not the distribution we were looking for
+ elif requirement is None or dist not in requirement:
+ # if we wound up with a different version, resolve what we've got
+ distreq = dist.as_requirement()
requirement = Requirement(str(distreq))
- log.info("Processing dependencies for %s", requirement)
- try:
- distros = WorkingSet([]).resolve(
- [requirement], self.local_index, self.easy_install
- )
- except DistributionNotFound as e:
+ log.info("Processing dependencies for %s", requirement)
+ try:
+ distros = WorkingSet([]).resolve(
+ [requirement], self.local_index, self.easy_install
+ )
+ except DistributionNotFound as e:
raise DistutilsError(str(e)) from e
- except VersionConflict as e:
+ except VersionConflict as e:
raise DistutilsError(e.report()) from e
- if self.always_copy or self.always_copy_from:
- # Force all the relevant distros to be copied or activated
- for dist in distros:
- if dist.key not in self.installed_projects:
- self.easy_install(dist.as_requirement())
- log.info("Finished processing dependencies for %s", requirement)
-
- def should_unzip(self, dist):
- if self.zip_ok is not None:
- return not self.zip_ok
- if dist.has_metadata('not-zip-safe'):
- return True
- if not dist.has_metadata('zip-safe'):
- return True
- return False
-
- def maybe_move(self, spec, dist_filename, setup_base):
- dst = os.path.join(self.build_directory, spec.key)
- if os.path.exists(dst):
+ if self.always_copy or self.always_copy_from:
+ # Force all the relevant distros to be copied or activated
+ for dist in distros:
+ if dist.key not in self.installed_projects:
+ self.easy_install(dist.as_requirement())
+ log.info("Finished processing dependencies for %s", requirement)
+
+ def should_unzip(self, dist):
+ if self.zip_ok is not None:
+ return not self.zip_ok
+ if dist.has_metadata('not-zip-safe'):
+ return True
+ if not dist.has_metadata('zip-safe'):
+ return True
+ return False
+
+ def maybe_move(self, spec, dist_filename, setup_base):
+ dst = os.path.join(self.build_directory, spec.key)
+ if os.path.exists(dst):
msg = (
"%r already exists in %s; build directory %s will not be kept"
)
- log.warn(msg, spec.key, self.build_directory, setup_base)
- return setup_base
- if os.path.isdir(dist_filename):
- setup_base = dist_filename
- else:
- if os.path.dirname(dist_filename) == setup_base:
- os.unlink(dist_filename) # get it out of the tmp dir
- contents = os.listdir(setup_base)
- if len(contents) == 1:
- dist_filename = os.path.join(setup_base, contents[0])
- if os.path.isdir(dist_filename):
- # if the only thing there is a directory, move it instead
- setup_base = dist_filename
- ensure_directory(dst)
- shutil.move(setup_base, dst)
- return dst
-
- def install_wrapper_scripts(self, dist):
- if self.exclude_scripts:
- return
- for args in ScriptWriter.best().get_args(dist):
- self.write_script(*args)
-
- def install_script(self, dist, script_name, script_text, dev_path=None):
- """Generate a legacy script wrapper and install it"""
- spec = str(dist.as_requirement())
- is_script = is_python_script(script_text, script_name)
-
- if is_script:
- body = self._load_template(dev_path) % locals()
- script_text = ScriptWriter.get_header(script_text) + body
+ log.warn(msg, spec.key, self.build_directory, setup_base)
+ return setup_base
+ if os.path.isdir(dist_filename):
+ setup_base = dist_filename
+ else:
+ if os.path.dirname(dist_filename) == setup_base:
+ os.unlink(dist_filename) # get it out of the tmp dir
+ contents = os.listdir(setup_base)
+ if len(contents) == 1:
+ dist_filename = os.path.join(setup_base, contents[0])
+ if os.path.isdir(dist_filename):
+ # if the only thing there is a directory, move it instead
+ setup_base = dist_filename
+ ensure_directory(dst)
+ shutil.move(setup_base, dst)
+ return dst
+
+ def install_wrapper_scripts(self, dist):
+ if self.exclude_scripts:
+ return
+ for args in ScriptWriter.best().get_args(dist):
+ self.write_script(*args)
+
+ def install_script(self, dist, script_name, script_text, dev_path=None):
+ """Generate a legacy script wrapper and install it"""
+ spec = str(dist.as_requirement())
+ is_script = is_python_script(script_text, script_name)
+
+ if is_script:
+ body = self._load_template(dev_path) % locals()
+ script_text = ScriptWriter.get_header(script_text) + body
self.write_script(script_name, _to_bytes(script_text), 'b')
-
- @staticmethod
- def _load_template(dev_path):
- """
- There are a couple of template scripts in the package. This
- function loads one of them and prepares it for use.
- """
+
+ @staticmethod
+ def _load_template(dev_path):
+ """
+ There are a couple of template scripts in the package. This
+ function loads one of them and prepares it for use.
+ """
# See https://github.com/pypa/setuptools/issues/134 for info
- # on script file naming and downstream issues with SVR4
- name = 'script.tmpl'
- if dev_path:
- name = name.replace('.tmpl', ' (dev).tmpl')
-
- raw_bytes = resource_string('setuptools', name)
- return raw_bytes.decode('utf-8')
-
- def write_script(self, script_name, contents, mode="t", blockers=()):
- """Write an executable file to the scripts directory"""
- self.delete_blockers( # clean up old .py/.pyw w/o a script
- [os.path.join(self.script_dir, x) for x in blockers]
- )
- log.info("Installing %s script to %s", script_name, self.script_dir)
- target = os.path.join(self.script_dir, script_name)
- self.add_output(target)
-
+ # on script file naming and downstream issues with SVR4
+ name = 'script.tmpl'
+ if dev_path:
+ name = name.replace('.tmpl', ' (dev).tmpl')
+
+ raw_bytes = resource_string('setuptools', name)
+ return raw_bytes.decode('utf-8')
+
+ def write_script(self, script_name, contents, mode="t", blockers=()):
+ """Write an executable file to the scripts directory"""
+ self.delete_blockers( # clean up old .py/.pyw w/o a script
+ [os.path.join(self.script_dir, x) for x in blockers]
+ )
+ log.info("Installing %s script to %s", script_name, self.script_dir)
+ target = os.path.join(self.script_dir, script_name)
+ self.add_output(target)
+
if self.dry_run:
return
- mask = current_umask()
+ mask = current_umask()
ensure_directory(target)
if os.path.exists(target):
os.unlink(target)
with open(target, "w" + mode) as f:
f.write(contents)
chmod(target, 0o777 - mask)
-
- def install_eggs(self, spec, dist_filename, tmpdir):
- # .egg dirs or files are already built, so just return them
+
+ def install_eggs(self, spec, dist_filename, tmpdir):
+ # .egg dirs or files are already built, so just return them
installer_map = {
'.egg': self.install_egg,
'.exe': self.install_exe,
@@ -859,86 +859,86 @@ class easy_install(Command):
pass
else:
return [install_dist(dist_filename, tmpdir)]
-
- # Anything else, try to extract and build
- setup_base = tmpdir
- if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
- unpack_archive(dist_filename, tmpdir, self.unpack_progress)
- elif os.path.isdir(dist_filename):
- setup_base = os.path.abspath(dist_filename)
-
- if (setup_base.startswith(tmpdir) # something we downloaded
- and self.build_directory and spec is not None):
- setup_base = self.maybe_move(spec, dist_filename, setup_base)
-
- # Find the setup.py file
- setup_script = os.path.join(setup_base, 'setup.py')
-
- if not os.path.exists(setup_script):
- setups = glob(os.path.join(setup_base, '*', 'setup.py'))
- if not setups:
- raise DistutilsError(
- "Couldn't find a setup script in %s" %
- os.path.abspath(dist_filename)
- )
- if len(setups) > 1:
- raise DistutilsError(
- "Multiple setup scripts in %s" %
- os.path.abspath(dist_filename)
- )
- setup_script = setups[0]
-
- # Now run it, and return the result
- if self.editable:
- log.info(self.report_editable(spec, setup_script))
- return []
- else:
- return self.build_and_install(setup_script, setup_base)
-
- def egg_distribution(self, egg_path):
- if os.path.isdir(egg_path):
- metadata = PathMetadata(egg_path, os.path.join(egg_path,
- 'EGG-INFO'))
- else:
- metadata = EggMetadata(zipimport.zipimporter(egg_path))
- return Distribution.from_filename(egg_path, metadata=metadata)
-
+
+ # Anything else, try to extract and build
+ setup_base = tmpdir
+ if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
+ unpack_archive(dist_filename, tmpdir, self.unpack_progress)
+ elif os.path.isdir(dist_filename):
+ setup_base = os.path.abspath(dist_filename)
+
+ if (setup_base.startswith(tmpdir) # something we downloaded
+ and self.build_directory and spec is not None):
+ setup_base = self.maybe_move(spec, dist_filename, setup_base)
+
+ # Find the setup.py file
+ setup_script = os.path.join(setup_base, 'setup.py')
+
+ if not os.path.exists(setup_script):
+ setups = glob(os.path.join(setup_base, '*', 'setup.py'))
+ if not setups:
+ raise DistutilsError(
+ "Couldn't find a setup script in %s" %
+ os.path.abspath(dist_filename)
+ )
+ if len(setups) > 1:
+ raise DistutilsError(
+ "Multiple setup scripts in %s" %
+ os.path.abspath(dist_filename)
+ )
+ setup_script = setups[0]
+
+ # Now run it, and return the result
+ if self.editable:
+ log.info(self.report_editable(spec, setup_script))
+ return []
+ else:
+ return self.build_and_install(setup_script, setup_base)
+
+ def egg_distribution(self, egg_path):
+ if os.path.isdir(egg_path):
+ metadata = PathMetadata(egg_path, os.path.join(egg_path,
+ 'EGG-INFO'))
+ else:
+ metadata = EggMetadata(zipimport.zipimporter(egg_path))
+ return Distribution.from_filename(egg_path, metadata=metadata)
+
# FIXME: 'easy_install.install_egg' is too complex (11)
def install_egg(self, egg_path, tmpdir): # noqa: C901
destination = os.path.join(
self.install_dir,
os.path.basename(egg_path),
)
- destination = os.path.abspath(destination)
- if not self.dry_run:
- ensure_directory(destination)
-
- dist = self.egg_distribution(egg_path)
- if not samefile(egg_path, destination):
- if os.path.isdir(destination) and not os.path.islink(destination):
- dir_util.remove_tree(destination, dry_run=self.dry_run)
- elif os.path.exists(destination):
+ destination = os.path.abspath(destination)
+ if not self.dry_run:
+ ensure_directory(destination)
+
+ dist = self.egg_distribution(egg_path)
+ if not samefile(egg_path, destination):
+ if os.path.isdir(destination) and not os.path.islink(destination):
+ dir_util.remove_tree(destination, dry_run=self.dry_run)
+ elif os.path.exists(destination):
self.execute(
os.unlink,
(destination,),
"Removing " + destination,
)
- try:
- new_dist_is_zipped = False
- if os.path.isdir(egg_path):
- if egg_path.startswith(tmpdir):
- f, m = shutil.move, "Moving"
- else:
- f, m = shutil.copytree, "Copying"
- elif self.should_unzip(dist):
- self.mkpath(destination)
- f, m = self.unpack_and_compile, "Extracting"
- else:
- new_dist_is_zipped = True
- if egg_path.startswith(tmpdir):
- f, m = shutil.move, "Moving"
- else:
- f, m = shutil.copy2, "Copying"
+ try:
+ new_dist_is_zipped = False
+ if os.path.isdir(egg_path):
+ if egg_path.startswith(tmpdir):
+ f, m = shutil.move, "Moving"
+ else:
+ f, m = shutil.copytree, "Copying"
+ elif self.should_unzip(dist):
+ self.mkpath(destination)
+ f, m = self.unpack_and_compile, "Extracting"
+ else:
+ new_dist_is_zipped = True
+ if egg_path.startswith(tmpdir):
+ f, m = shutil.move, "Moving"
+ else:
+ f, m = shutil.copy2, "Copying"
self.execute(
f,
(egg_path, destination),
@@ -952,111 +952,111 @@ class easy_install(Command):
fix_zipimporter_caches=new_dist_is_zipped,
)
except Exception:
- update_dist_caches(destination, fix_zipimporter_caches=False)
- raise
-
- self.add_output(destination)
- return self.egg_distribution(destination)
-
- def install_exe(self, dist_filename, tmpdir):
- # See if it's valid, get data
- cfg = extract_wininst_cfg(dist_filename)
- if cfg is None:
- raise DistutilsError(
- "%s is not a valid distutils Windows .exe" % dist_filename
- )
- # Create a dummy distribution object until we build the real distro
- dist = Distribution(
- None,
- project_name=cfg.get('metadata', 'name'),
- version=cfg.get('metadata', 'version'), platform=get_platform(),
- )
-
- # Convert the .exe to an unpacked egg
+ update_dist_caches(destination, fix_zipimporter_caches=False)
+ raise
+
+ self.add_output(destination)
+ return self.egg_distribution(destination)
+
+ def install_exe(self, dist_filename, tmpdir):
+ # See if it's valid, get data
+ cfg = extract_wininst_cfg(dist_filename)
+ if cfg is None:
+ raise DistutilsError(
+ "%s is not a valid distutils Windows .exe" % dist_filename
+ )
+ # Create a dummy distribution object until we build the real distro
+ dist = Distribution(
+ None,
+ project_name=cfg.get('metadata', 'name'),
+ version=cfg.get('metadata', 'version'), platform=get_platform(),
+ )
+
+ # Convert the .exe to an unpacked egg
egg_path = os.path.join(tmpdir, dist.egg_name() + '.egg')
dist.location = egg_path
- egg_tmp = egg_path + '.tmp'
- _egg_info = os.path.join(egg_tmp, 'EGG-INFO')
- pkg_inf = os.path.join(_egg_info, 'PKG-INFO')
- ensure_directory(pkg_inf) # make sure EGG-INFO dir exists
- dist._provider = PathMetadata(egg_tmp, _egg_info) # XXX
- self.exe_to_egg(dist_filename, egg_tmp)
-
- # Write EGG-INFO/PKG-INFO
- if not os.path.exists(pkg_inf):
- f = open(pkg_inf, 'w')
- f.write('Metadata-Version: 1.0\n')
- for k, v in cfg.items('metadata'):
- if k != 'target_version':
- f.write('%s: %s\n' % (k.replace('_', '-').title(), v))
- f.close()
- script_dir = os.path.join(_egg_info, 'scripts')
- # delete entry-point scripts to avoid duping
+ egg_tmp = egg_path + '.tmp'
+ _egg_info = os.path.join(egg_tmp, 'EGG-INFO')
+ pkg_inf = os.path.join(_egg_info, 'PKG-INFO')
+ ensure_directory(pkg_inf) # make sure EGG-INFO dir exists
+ dist._provider = PathMetadata(egg_tmp, _egg_info) # XXX
+ self.exe_to_egg(dist_filename, egg_tmp)
+
+ # Write EGG-INFO/PKG-INFO
+ if not os.path.exists(pkg_inf):
+ f = open(pkg_inf, 'w')
+ f.write('Metadata-Version: 1.0\n')
+ for k, v in cfg.items('metadata'):
+ if k != 'target_version':
+ f.write('%s: %s\n' % (k.replace('_', '-').title(), v))
+ f.close()
+ script_dir = os.path.join(_egg_info, 'scripts')
+ # delete entry-point scripts to avoid duping
self.delete_blockers([
os.path.join(script_dir, args[0])
for args in ScriptWriter.get_args(dist)
])
- # Build .egg file from tmpdir
- bdist_egg.make_zipfile(
+ # Build .egg file from tmpdir
+ bdist_egg.make_zipfile(
egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run,
- )
- # install the .egg
- return self.install_egg(egg_path, tmpdir)
-
+ )
+ # install the .egg
+ return self.install_egg(egg_path, tmpdir)
+
# FIXME: 'easy_install.exe_to_egg' is too complex (12)
def exe_to_egg(self, dist_filename, egg_tmp): # noqa: C901
- """Extract a bdist_wininst to the directories an egg would use"""
- # Check for .pth file and set up prefix translations
- prefixes = get_exe_prefixes(dist_filename)
- to_compile = []
- native_libs = []
- top_level = {}
-
- def process(src, dst):
- s = src.lower()
- for old, new in prefixes:
- if s.startswith(old):
- src = new + src[len(old):]
- parts = src.split('/')
- dst = os.path.join(egg_tmp, *parts)
- dl = dst.lower()
- if dl.endswith('.pyd') or dl.endswith('.dll'):
- parts[-1] = bdist_egg.strip_module(parts[-1])
- top_level[os.path.splitext(parts[0])[0]] = 1
- native_libs.append(src)
- elif dl.endswith('.py') and old != 'SCRIPTS/':
- top_level[os.path.splitext(parts[0])[0]] = 1
- to_compile.append(dst)
- return dst
- if not src.endswith('.pth'):
- log.warn("WARNING: can't process %s", src)
- return None
-
- # extract, tracking .pyd/.dll->native_libs and .py -> to_compile
- unpack_archive(dist_filename, egg_tmp, process)
- stubs = []
- for res in native_libs:
- if res.lower().endswith('.pyd'): # create stubs for .pyd's
- parts = res.split('/')
- resource = parts[-1]
- parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py'
- pyfile = os.path.join(egg_tmp, *parts)
- to_compile.append(pyfile)
- stubs.append(pyfile)
- bdist_egg.write_stub(resource, pyfile)
- self.byte_compile(to_compile) # compile .py's
- bdist_egg.write_safety_flag(
- os.path.join(egg_tmp, 'EGG-INFO'),
- bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag
-
- for name in 'top_level', 'native_libs':
- if locals()[name]:
- txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt')
- if not os.path.exists(txt):
- f = open(txt, 'w')
- f.write('\n'.join(locals()[name]) + '\n')
- f.close()
-
+ """Extract a bdist_wininst to the directories an egg would use"""
+ # Check for .pth file and set up prefix translations
+ prefixes = get_exe_prefixes(dist_filename)
+ to_compile = []
+ native_libs = []
+ top_level = {}
+
+ def process(src, dst):
+ s = src.lower()
+ for old, new in prefixes:
+ if s.startswith(old):
+ src = new + src[len(old):]
+ parts = src.split('/')
+ dst = os.path.join(egg_tmp, *parts)
+ dl = dst.lower()
+ if dl.endswith('.pyd') or dl.endswith('.dll'):
+ parts[-1] = bdist_egg.strip_module(parts[-1])
+ top_level[os.path.splitext(parts[0])[0]] = 1
+ native_libs.append(src)
+ elif dl.endswith('.py') and old != 'SCRIPTS/':
+ top_level[os.path.splitext(parts[0])[0]] = 1
+ to_compile.append(dst)
+ return dst
+ if not src.endswith('.pth'):
+ log.warn("WARNING: can't process %s", src)
+ return None
+
+ # extract, tracking .pyd/.dll->native_libs and .py -> to_compile
+ unpack_archive(dist_filename, egg_tmp, process)
+ stubs = []
+ for res in native_libs:
+ if res.lower().endswith('.pyd'): # create stubs for .pyd's
+ parts = res.split('/')
+ resource = parts[-1]
+ parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py'
+ pyfile = os.path.join(egg_tmp, *parts)
+ to_compile.append(pyfile)
+ stubs.append(pyfile)
+ bdist_egg.write_stub(resource, pyfile)
+ self.byte_compile(to_compile) # compile .py's
+ bdist_egg.write_safety_flag(
+ os.path.join(egg_tmp, 'EGG-INFO'),
+ bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag
+
+ for name in 'top_level', 'native_libs':
+ if locals()[name]:
+ txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt')
+ if not os.path.exists(txt):
+ f = open(txt, 'w')
+ f.write('\n'.join(locals()[name]) + '\n')
+ f.close()
+
def install_wheel(self, wheel_path, tmpdir):
wheel = Wheel(wheel_path)
assert wheel.is_compatible()
@@ -1086,155 +1086,155 @@ class easy_install(Command):
self.add_output(destination)
return self.egg_distribution(destination)
- __mv_warning = textwrap.dedent("""
- Because this distribution was installed --multi-version, before you can
- import modules from this package in an application, you will need to
- 'import pkg_resources' and then use a 'require()' call similar to one of
- these examples, in order to select the desired version:
-
- pkg_resources.require("%(name)s") # latest installed version
- pkg_resources.require("%(name)s==%(version)s") # this exact version
- pkg_resources.require("%(name)s>=%(version)s") # this version or higher
+ __mv_warning = textwrap.dedent("""
+ Because this distribution was installed --multi-version, before you can
+ import modules from this package in an application, you will need to
+ 'import pkg_resources' and then use a 'require()' call similar to one of
+ these examples, in order to select the desired version:
+
+ pkg_resources.require("%(name)s") # latest installed version
+ pkg_resources.require("%(name)s==%(version)s") # this exact version
+ pkg_resources.require("%(name)s>=%(version)s") # this version or higher
""").lstrip() # noqa
-
- __id_warning = textwrap.dedent("""
- Note also that the installation directory must be on sys.path at runtime for
- this to work. (e.g. by being the application's script directory, by being on
- PYTHONPATH, or by being added to sys.path by your code.)
+
+ __id_warning = textwrap.dedent("""
+ Note also that the installation directory must be on sys.path at runtime for
+ this to work. (e.g. by being the application's script directory, by being on
+ PYTHONPATH, or by being added to sys.path by your code.)
""") # noqa
-
- def installation_report(self, req, dist, what="Installed"):
- """Helpful installation message for display to package users"""
- msg = "\n%(what)s %(eggloc)s%(extras)s"
- if self.multi_version and not self.no_report:
- msg += '\n' + self.__mv_warning
- if self.install_dir not in map(normalize_path, sys.path):
- msg += '\n' + self.__id_warning
-
- eggloc = dist.location
- name = dist.project_name
- version = dist.version
- extras = '' # TODO: self.report_extras(req, dist)
- return msg % locals()
-
- __editable_msg = textwrap.dedent("""
- Extracted editable version of %(spec)s to %(dirname)s
-
- If it uses setuptools in its setup script, you can activate it in
- "development" mode by going to that directory and running::
-
- %(python)s setup.py develop
-
- See the setuptools documentation for the "develop" command for more info.
+
+ def installation_report(self, req, dist, what="Installed"):
+ """Helpful installation message for display to package users"""
+ msg = "\n%(what)s %(eggloc)s%(extras)s"
+ if self.multi_version and not self.no_report:
+ msg += '\n' + self.__mv_warning
+ if self.install_dir not in map(normalize_path, sys.path):
+ msg += '\n' + self.__id_warning
+
+ eggloc = dist.location
+ name = dist.project_name
+ version = dist.version
+ extras = '' # TODO: self.report_extras(req, dist)
+ return msg % locals()
+
+ __editable_msg = textwrap.dedent("""
+ Extracted editable version of %(spec)s to %(dirname)s
+
+ If it uses setuptools in its setup script, you can activate it in
+ "development" mode by going to that directory and running::
+
+ %(python)s setup.py develop
+
+ See the setuptools documentation for the "develop" command for more info.
""").lstrip() # noqa
-
- def report_editable(self, spec, setup_script):
- dirname = os.path.dirname(setup_script)
- python = sys.executable
- return '\n' + self.__editable_msg % locals()
-
- def run_setup(self, setup_script, setup_base, args):
- sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
- sys.modules.setdefault('distutils.command.egg_info', egg_info)
-
- args = list(args)
- if self.verbose > 2:
- v = 'v' * (self.verbose - 1)
- args.insert(0, '-' + v)
- elif self.verbose < 2:
- args.insert(0, '-q')
- if self.dry_run:
- args.insert(0, '-n')
- log.info(
- "Running %s %s", setup_script[len(setup_base) + 1:], ' '.join(args)
- )
- try:
- run_setup(setup_script, args)
- except SystemExit as v:
+
+ def report_editable(self, spec, setup_script):
+ dirname = os.path.dirname(setup_script)
+ python = sys.executable
+ return '\n' + self.__editable_msg % locals()
+
+ def run_setup(self, setup_script, setup_base, args):
+ sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
+ sys.modules.setdefault('distutils.command.egg_info', egg_info)
+
+ args = list(args)
+ if self.verbose > 2:
+ v = 'v' * (self.verbose - 1)
+ args.insert(0, '-' + v)
+ elif self.verbose < 2:
+ args.insert(0, '-q')
+ if self.dry_run:
+ args.insert(0, '-n')
+ log.info(
+ "Running %s %s", setup_script[len(setup_base) + 1:], ' '.join(args)
+ )
+ try:
+ run_setup(setup_script, args)
+ except SystemExit as v:
raise DistutilsError(
"Setup script exited with %s" % (v.args[0],)
) from v
-
- def build_and_install(self, setup_script, setup_base):
- args = ['bdist_egg', '--dist-dir']
-
- dist_dir = tempfile.mkdtemp(
- prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
- )
- try:
- self._set_fetcher_options(os.path.dirname(setup_script))
- args.append(dist_dir)
-
- self.run_setup(setup_script, setup_base, args)
- all_eggs = Environment([dist_dir])
- eggs = []
- for key in all_eggs:
- for dist in all_eggs[key]:
- eggs.append(self.install_egg(dist.location, setup_base))
- if not eggs and not self.dry_run:
- log.warn("No eggs found in %s (setup script problem?)",
- dist_dir)
- return eggs
- finally:
- rmtree(dist_dir)
- log.set_verbosity(self.verbose) # restore our log verbosity
-
- def _set_fetcher_options(self, base):
- """
- When easy_install is about to run bdist_egg on a source dist, that
- source dist might have 'setup_requires' directives, requiring
- additional fetching. Ensure the fetcher options given to easy_install
- are available to that command as well.
- """
- # find the fetch options from easy_install and write them out
- # to the setup.cfg file.
- ei_opts = self.distribution.get_option_dict('easy_install').copy()
- fetch_directives = (
+
+ def build_and_install(self, setup_script, setup_base):
+ args = ['bdist_egg', '--dist-dir']
+
+ dist_dir = tempfile.mkdtemp(
+ prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
+ )
+ try:
+ self._set_fetcher_options(os.path.dirname(setup_script))
+ args.append(dist_dir)
+
+ self.run_setup(setup_script, setup_base, args)
+ all_eggs = Environment([dist_dir])
+ eggs = []
+ for key in all_eggs:
+ for dist in all_eggs[key]:
+ eggs.append(self.install_egg(dist.location, setup_base))
+ if not eggs and not self.dry_run:
+ log.warn("No eggs found in %s (setup script problem?)",
+ dist_dir)
+ return eggs
+ finally:
+ rmtree(dist_dir)
+ log.set_verbosity(self.verbose) # restore our log verbosity
+
+ def _set_fetcher_options(self, base):
+ """
+ When easy_install is about to run bdist_egg on a source dist, that
+ source dist might have 'setup_requires' directives, requiring
+ additional fetching. Ensure the fetcher options given to easy_install
+ are available to that command as well.
+ """
+ # find the fetch options from easy_install and write them out
+ # to the setup.cfg file.
+ ei_opts = self.distribution.get_option_dict('easy_install').copy()
+ fetch_directives = (
'find_links', 'site_dirs', 'index_url', 'optimize', 'allow_hosts',
- )
- fetch_options = {}
- for key, val in ei_opts.items():
- if key not in fetch_directives:
- continue
+ )
+ fetch_options = {}
+ for key, val in ei_opts.items():
+ if key not in fetch_directives:
+ continue
fetch_options[key] = val[1]
- # create a settings dictionary suitable for `edit_config`
- settings = dict(easy_install=fetch_options)
- cfg_filename = os.path.join(base, 'setup.cfg')
- setopt.edit_config(cfg_filename, settings)
-
+ # create a settings dictionary suitable for `edit_config`
+ settings = dict(easy_install=fetch_options)
+ cfg_filename = os.path.join(base, 'setup.cfg')
+ setopt.edit_config(cfg_filename, settings)
+
def update_pth(self, dist): # noqa: C901 # is too complex (11) # FIXME
- if self.pth_file is None:
- return
-
- for d in self.pth_file[dist.key]: # drop old entries
+ if self.pth_file is None:
+ return
+
+ for d in self.pth_file[dist.key]: # drop old entries
if not self.multi_version and d.location == dist.location:
continue
-
+
log.info("Removing %s from easy-install.pth file", d)
self.pth_file.remove(d)
if d.location in self.shadow_path:
self.shadow_path.remove(d.location)
- if not self.multi_version:
- if dist.location in self.pth_file.paths:
- log.info(
- "%s is already the active version in easy-install.pth",
+ if not self.multi_version:
+ if dist.location in self.pth_file.paths:
+ log.info(
+ "%s is already the active version in easy-install.pth",
dist,
- )
- else:
- log.info("Adding %s to easy-install.pth file", dist)
- self.pth_file.add(dist) # add new entry
- if dist.location not in self.shadow_path:
- self.shadow_path.append(dist.location)
-
+ )
+ else:
+ log.info("Adding %s to easy-install.pth file", dist)
+ self.pth_file.add(dist) # add new entry
+ if dist.location not in self.shadow_path:
+ self.shadow_path.append(dist.location)
+
if self.dry_run:
return
-
+
self.pth_file.save()
-
+
if dist.key != 'setuptools':
return
-
+
# Ensure that setuptools itself never becomes unavailable!
# XXX should this check for latest version?
filename = os.path.join(self.install_dir, 'setuptools.pth')
@@ -1243,132 +1243,132 @@ class easy_install(Command):
with open(filename, 'wt') as f:
f.write(self.pth_file.make_relative(dist.location) + '\n')
- def unpack_progress(self, src, dst):
- # Progress filter for unpacking
- log.debug("Unpacking %s to %s", src, dst)
- return dst # only unpack-and-compile skips files for dry run
-
- def unpack_and_compile(self, egg_path, destination):
- to_compile = []
- to_chmod = []
-
- def pf(src, dst):
- if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
- to_compile.append(dst)
- elif dst.endswith('.dll') or dst.endswith('.so'):
- to_chmod.append(dst)
- self.unpack_progress(src, dst)
- return not self.dry_run and dst or None
-
- unpack_archive(egg_path, destination, pf)
- self.byte_compile(to_compile)
- if not self.dry_run:
- for f in to_chmod:
- mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755
- chmod(f, mode)
-
- def byte_compile(self, to_compile):
- if sys.dont_write_bytecode:
- return
-
- from distutils.util import byte_compile
-
- try:
- # try to make the byte compile messages quieter
- log.set_verbosity(self.verbose - 1)
-
- byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run)
- if self.optimize:
- byte_compile(
- to_compile, optimize=self.optimize, force=1,
+ def unpack_progress(self, src, dst):
+ # Progress filter for unpacking
+ log.debug("Unpacking %s to %s", src, dst)
+ return dst # only unpack-and-compile skips files for dry run
+
+ def unpack_and_compile(self, egg_path, destination):
+ to_compile = []
+ to_chmod = []
+
+ def pf(src, dst):
+ if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
+ to_compile.append(dst)
+ elif dst.endswith('.dll') or dst.endswith('.so'):
+ to_chmod.append(dst)
+ self.unpack_progress(src, dst)
+ return not self.dry_run and dst or None
+
+ unpack_archive(egg_path, destination, pf)
+ self.byte_compile(to_compile)
+ if not self.dry_run:
+ for f in to_chmod:
+ mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755
+ chmod(f, mode)
+
+ def byte_compile(self, to_compile):
+ if sys.dont_write_bytecode:
+ return
+
+ from distutils.util import byte_compile
+
+ try:
+ # try to make the byte compile messages quieter
+ log.set_verbosity(self.verbose - 1)
+
+ byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run)
+ if self.optimize:
+ byte_compile(
+ to_compile, optimize=self.optimize, force=1,
dry_run=self.dry_run,
- )
- finally:
- log.set_verbosity(self.verbose) # restore original verbosity
-
- __no_default_msg = textwrap.dedent("""
- bad install directory or PYTHONPATH
-
- You are attempting to install a package to a directory that is not
- on PYTHONPATH and which Python does not read ".pth" files from. The
- installation directory you specified (via --install-dir, --prefix, or
- the distutils default setting) was:
-
- %s
-
- and your PYTHONPATH environment variable currently contains:
-
- %r
-
- Here are some of your options for correcting the problem:
-
- * You can choose a different installation directory, i.e., one that is
- on PYTHONPATH or supports .pth files
-
- * You can add the installation directory to the PYTHONPATH environment
- variable. (It must then also be on PYTHONPATH whenever you run
- Python and want to use the package(s) you are installing.)
-
- * You can set up the installation directory to support ".pth" files by
- using one of the approaches described here:
-
+ )
+ finally:
+ log.set_verbosity(self.verbose) # restore original verbosity
+
+ __no_default_msg = textwrap.dedent("""
+ bad install directory or PYTHONPATH
+
+ You are attempting to install a package to a directory that is not
+ on PYTHONPATH and which Python does not read ".pth" files from. The
+ installation directory you specified (via --install-dir, --prefix, or
+ the distutils default setting) was:
+
+ %s
+
+ and your PYTHONPATH environment variable currently contains:
+
+ %r
+
+ Here are some of your options for correcting the problem:
+
+ * You can choose a different installation directory, i.e., one that is
+ on PYTHONPATH or supports .pth files
+
+ * You can add the installation directory to the PYTHONPATH environment
+ variable. (It must then also be on PYTHONPATH whenever you run
+ Python and want to use the package(s) you are installing.)
+
+ * You can set up the installation directory to support ".pth" files by
+ using one of the approaches described here:
+
https://setuptools.pypa.io/en/latest/deprecated/easy_install.html#custom-installation-locations
-
+
Please make the appropriate changes for your system and try again.
""").strip()
-
- def create_home_path(self):
- """Create directories under ~."""
- if not self.user:
- return
- home = convert_path(os.path.expanduser("~"))
+
+ def create_home_path(self):
+ """Create directories under ~."""
+ if not self.user:
+ return
+ home = convert_path(os.path.expanduser("~"))
for name, path in self.config_vars.items():
- if path.startswith(home) and not os.path.isdir(path):
- self.debug_print("os.makedirs('%s', 0o700)" % path)
- os.makedirs(path, 0o700)
-
- INSTALL_SCHEMES = dict(
- posix=dict(
- install_dir='$base/lib/python$py_version_short/site-packages',
- script_dir='$base/bin',
- ),
- )
-
- DEFAULT_SCHEME = dict(
- install_dir='$base/Lib/site-packages',
- script_dir='$base/Scripts',
- )
-
- def _expand(self, *attrs):
- config_vars = self.get_finalized_command('install').config_vars
-
- if self.prefix:
- # Set default install_dir/scripts from --prefix
- config_vars = config_vars.copy()
- config_vars['base'] = self.prefix
- scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME)
- for attr, val in scheme.items():
- if getattr(self, attr, None) is None:
- setattr(self, attr, val)
-
- from distutils.util import subst_vars
-
- for attr in attrs:
- val = getattr(self, attr)
- if val is not None:
- val = subst_vars(val, config_vars)
- if os.name == 'posix':
- val = os.path.expanduser(val)
- setattr(self, attr, val)
-
-
+ if path.startswith(home) and not os.path.isdir(path):
+ self.debug_print("os.makedirs('%s', 0o700)" % path)
+ os.makedirs(path, 0o700)
+
+ INSTALL_SCHEMES = dict(
+ posix=dict(
+ install_dir='$base/lib/python$py_version_short/site-packages',
+ script_dir='$base/bin',
+ ),
+ )
+
+ DEFAULT_SCHEME = dict(
+ install_dir='$base/Lib/site-packages',
+ script_dir='$base/Scripts',
+ )
+
+ def _expand(self, *attrs):
+ config_vars = self.get_finalized_command('install').config_vars
+
+ if self.prefix:
+ # Set default install_dir/scripts from --prefix
+ config_vars = config_vars.copy()
+ config_vars['base'] = self.prefix
+ scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME)
+ for attr, val in scheme.items():
+ if getattr(self, attr, None) is None:
+ setattr(self, attr, val)
+
+ from distutils.util import subst_vars
+
+ for attr in attrs:
+ val = getattr(self, attr)
+ if val is not None:
+ val = subst_vars(val, config_vars)
+ if os.name == 'posix':
+ val = os.path.expanduser(val)
+ setattr(self, attr, val)
+
+
def _pythonpath():
items = os.environ.get('PYTHONPATH', '').split(os.pathsep)
return filter(None, items)
-def get_site_dirs():
+def get_site_dirs():
"""
Return a list of 'site' dirs
"""
@@ -1378,10 +1378,10 @@ def get_site_dirs():
# start with PYTHONPATH
sitedirs.extend(_pythonpath())
- prefixes = [sys.prefix]
- if sys.exec_prefix != sys.prefix:
- prefixes.append(sys.exec_prefix)
- for prefix in prefixes:
+ prefixes = [sys.prefix]
+ if sys.exec_prefix != sys.prefix:
+ prefixes.append(sys.exec_prefix)
+ for prefix in prefixes:
if not prefix:
continue
@@ -1423,60 +1423,60 @@ def get_site_dirs():
'site-packages',
)
sitedirs.append(home_sp)
- lib_paths = get_path('purelib'), get_path('platlib')
-
+ lib_paths = get_path('purelib'), get_path('platlib')
+
sitedirs.extend(s for s in lib_paths if s not in sitedirs)
- if site.ENABLE_USER_SITE:
- sitedirs.append(site.USER_SITE)
-
+ if site.ENABLE_USER_SITE:
+ sitedirs.append(site.USER_SITE)
+
with contextlib.suppress(AttributeError):
sitedirs.extend(site.getsitepackages())
- sitedirs = list(map(normalize_path, sitedirs))
-
- return sitedirs
-
-
+ sitedirs = list(map(normalize_path, sitedirs))
+
+ return sitedirs
+
+
def expand_paths(inputs): # noqa: C901 # is too complex (11) # FIXME
- """Yield sys.path directories that might contain "old-style" packages"""
-
- seen = {}
-
- for dirname in inputs:
- dirname = normalize_path(dirname)
- if dirname in seen:
- continue
-
- seen[dirname] = 1
- if not os.path.isdir(dirname):
- continue
-
- files = os.listdir(dirname)
- yield dirname, files
-
- for name in files:
- if not name.endswith('.pth'):
- # We only care about the .pth files
- continue
- if name in ('easy-install.pth', 'setuptools.pth'):
- # Ignore .pth files that we control
- continue
-
- # Read the .pth file
- f = open(os.path.join(dirname, name))
- lines = list(yield_lines(f))
- f.close()
-
- # Yield existing non-dupe, non-import directory lines from it
- for line in lines:
+ """Yield sys.path directories that might contain "old-style" packages"""
+
+ seen = {}
+
+ for dirname in inputs:
+ dirname = normalize_path(dirname)
+ if dirname in seen:
+ continue
+
+ seen[dirname] = 1
+ if not os.path.isdir(dirname):
+ continue
+
+ files = os.listdir(dirname)
+ yield dirname, files
+
+ for name in files:
+ if not name.endswith('.pth'):
+ # We only care about the .pth files
+ continue
+ if name in ('easy-install.pth', 'setuptools.pth'):
+ # Ignore .pth files that we control
+ continue
+
+ # Read the .pth file
+ f = open(os.path.join(dirname, name))
+ lines = list(yield_lines(f))
+ f.close()
+
+ # Yield existing non-dupe, non-import directory lines from it
+ for line in lines:
if line.startswith("import"):
continue
-
+
line = normalize_path(line.rstrip())
if line in seen:
continue
-
+
seen[line] = 1
if not os.path.isdir(line):
continue
@@ -1484,542 +1484,542 @@ def expand_paths(inputs): # noqa: C901 # is too complex (11) # FIXME
yield line, os.listdir(line)
-def extract_wininst_cfg(dist_filename):
- """Extract configuration data from a bdist_wininst .exe
-
- Returns a configparser.RawConfigParser, or None
- """
- f = open(dist_filename, 'rb')
- try:
- endrec = zipfile._EndRecData(f)
- if endrec is None:
- return None
-
- prepended = (endrec[9] - endrec[5]) - endrec[6]
- if prepended < 12: # no wininst data here
- return None
- f.seek(prepended - 12)
-
- tag, cfglen, bmlen = struct.unpack("<iii", f.read(12))
- if tag not in (0x1234567A, 0x1234567B):
- return None # not a valid tag
-
- f.seek(prepended - (12 + cfglen))
+def extract_wininst_cfg(dist_filename):
+ """Extract configuration data from a bdist_wininst .exe
+
+ Returns a configparser.RawConfigParser, or None
+ """
+ f = open(dist_filename, 'rb')
+ try:
+ endrec = zipfile._EndRecData(f)
+ if endrec is None:
+ return None
+
+ prepended = (endrec[9] - endrec[5]) - endrec[6]
+ if prepended < 12: # no wininst data here
+ return None
+ f.seek(prepended - 12)
+
+ tag, cfglen, bmlen = struct.unpack("<iii", f.read(12))
+ if tag not in (0x1234567A, 0x1234567B):
+ return None # not a valid tag
+
+ f.seek(prepended - (12 + cfglen))
init = {'version': '', 'target_version': ''}
cfg = configparser.RawConfigParser(init)
- try:
- part = f.read(cfglen)
- # Read up to the first null byte.
- config = part.split(b'\0', 1)[0]
- # Now the config is in bytes, but for RawConfigParser, it should
- # be text, so decode it.
- config = config.decode(sys.getfilesystemencoding())
+ try:
+ part = f.read(cfglen)
+ # Read up to the first null byte.
+ config = part.split(b'\0', 1)[0]
+ # Now the config is in bytes, but for RawConfigParser, it should
+ # be text, so decode it.
+ config = config.decode(sys.getfilesystemencoding())
cfg.read_file(io.StringIO(config))
- except configparser.Error:
- return None
- if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
- return None
- return cfg
-
- finally:
- f.close()
-
-
-def get_exe_prefixes(exe_filename):
- """Get exe->egg path translations for a given .exe file"""
-
- prefixes = [
+ except configparser.Error:
+ return None
+ if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
+ return None
+ return cfg
+
+ finally:
+ f.close()
+
+
+def get_exe_prefixes(exe_filename):
+ """Get exe->egg path translations for a given .exe file"""
+
+ prefixes = [
('PURELIB/', ''),
('PLATLIB/pywin32_system32', ''),
- ('PLATLIB/', ''),
- ('SCRIPTS/', 'EGG-INFO/scripts/'),
- ('DATA/lib/site-packages', ''),
- ]
- z = zipfile.ZipFile(exe_filename)
- try:
- for info in z.infolist():
- name = info.filename
- parts = name.split('/')
- if len(parts) == 3 and parts[2] == 'PKG-INFO':
- if parts[1].endswith('.egg-info'):
- prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/'))
- break
- if len(parts) != 2 or not name.endswith('.pth'):
- continue
- if name.endswith('-nspkg.pth'):
- continue
- if parts[0].upper() in ('PURELIB', 'PLATLIB'):
+ ('PLATLIB/', ''),
+ ('SCRIPTS/', 'EGG-INFO/scripts/'),
+ ('DATA/lib/site-packages', ''),
+ ]
+ z = zipfile.ZipFile(exe_filename)
+ try:
+ for info in z.infolist():
+ name = info.filename
+ parts = name.split('/')
+ if len(parts) == 3 and parts[2] == 'PKG-INFO':
+ if parts[1].endswith('.egg-info'):
+ prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/'))
+ break
+ if len(parts) != 2 or not name.endswith('.pth'):
+ continue
+ if name.endswith('-nspkg.pth'):
+ continue
+ if parts[0].upper() in ('PURELIB', 'PLATLIB'):
contents = z.read(name).decode()
- for pth in yield_lines(contents):
- pth = pth.strip().replace('\\', '/')
- if not pth.startswith('import'):
- prefixes.append((('%s/%s/' % (parts[0], pth)), ''))
- finally:
- z.close()
- prefixes = [(x.lower(), y) for x, y in prefixes]
- prefixes.sort()
- prefixes.reverse()
- return prefixes
-
-
-class PthDistributions(Environment):
- """A .pth file with Distribution paths in it"""
-
- dirty = False
-
- def __init__(self, filename, sitedirs=()):
- self.filename = filename
- self.sitedirs = list(map(normalize_path, sitedirs))
- self.basedir = normalize_path(os.path.dirname(self.filename))
- self._load()
- Environment.__init__(self, [], None, None)
- for path in yield_lines(self.paths):
- list(map(self.add, find_distributions(path, True)))
-
- def _load(self):
- self.paths = []
- saw_import = False
- seen = dict.fromkeys(self.sitedirs)
- if os.path.isfile(self.filename):
- f = open(self.filename, 'rt')
- for line in f:
- if line.startswith('import'):
- saw_import = True
- continue
- path = line.rstrip()
- self.paths.append(path)
- if not path.strip() or path.strip().startswith('#'):
- continue
- # skip non-existent paths, in case somebody deleted a package
- # manually, and duplicate paths as well
- path = self.paths[-1] = normalize_path(
- os.path.join(self.basedir, path)
- )
- if not os.path.exists(path) or path in seen:
- self.paths.pop() # skip it
- self.dirty = True # we cleaned up, so we're dirty now :)
- continue
- seen[path] = 1
- f.close()
-
- if self.paths and not saw_import:
- self.dirty = True # ensure anything we touch has import wrappers
- while self.paths and not self.paths[-1].strip():
- self.paths.pop()
-
- def save(self):
- """Write changed .pth file back to disk"""
- if not self.dirty:
- return
-
- rel_paths = list(map(self.make_relative, self.paths))
- if rel_paths:
- log.debug("Saving %s", self.filename)
- lines = self._wrap_lines(rel_paths)
- data = '\n'.join(lines) + '\n'
-
- if os.path.islink(self.filename):
- os.unlink(self.filename)
- with open(self.filename, 'wt') as f:
- f.write(data)
-
- elif os.path.exists(self.filename):
- log.debug("Deleting empty %s", self.filename)
- os.unlink(self.filename)
-
- self.dirty = False
-
- @staticmethod
- def _wrap_lines(lines):
- return lines
-
- def add(self, dist):
- """Add `dist` to the distribution map"""
- new_path = (
- dist.location not in self.paths and (
- dist.location not in self.sitedirs or
- # account for '.' being in PYTHONPATH
- dist.location == os.getcwd()
- )
- )
- if new_path:
- self.paths.append(dist.location)
- self.dirty = True
- Environment.add(self, dist)
-
- def remove(self, dist):
- """Remove `dist` from the distribution map"""
- while dist.location in self.paths:
- self.paths.remove(dist.location)
- self.dirty = True
- Environment.remove(self, dist)
-
- def make_relative(self, path):
- npath, last = os.path.split(normalize_path(path))
- baselen = len(self.basedir)
- parts = [last]
- sep = os.altsep == '/' and '/' or os.sep
- while len(npath) >= baselen:
- if npath == self.basedir:
- parts.append(os.curdir)
- parts.reverse()
- return sep.join(parts)
- npath, last = os.path.split(npath)
- parts.append(last)
- else:
- return path
-
-
-class RewritePthDistributions(PthDistributions):
- @classmethod
- def _wrap_lines(cls, lines):
- yield cls.prelude
- for line in lines:
- yield line
- yield cls.postlude
-
+ for pth in yield_lines(contents):
+ pth = pth.strip().replace('\\', '/')
+ if not pth.startswith('import'):
+ prefixes.append((('%s/%s/' % (parts[0], pth)), ''))
+ finally:
+ z.close()
+ prefixes = [(x.lower(), y) for x, y in prefixes]
+ prefixes.sort()
+ prefixes.reverse()
+ return prefixes
+
+
+class PthDistributions(Environment):
+ """A .pth file with Distribution paths in it"""
+
+ dirty = False
+
+ def __init__(self, filename, sitedirs=()):
+ self.filename = filename
+ self.sitedirs = list(map(normalize_path, sitedirs))
+ self.basedir = normalize_path(os.path.dirname(self.filename))
+ self._load()
+ Environment.__init__(self, [], None, None)
+ for path in yield_lines(self.paths):
+ list(map(self.add, find_distributions(path, True)))
+
+ def _load(self):
+ self.paths = []
+ saw_import = False
+ seen = dict.fromkeys(self.sitedirs)
+ if os.path.isfile(self.filename):
+ f = open(self.filename, 'rt')
+ for line in f:
+ if line.startswith('import'):
+ saw_import = True
+ continue
+ path = line.rstrip()
+ self.paths.append(path)
+ if not path.strip() or path.strip().startswith('#'):
+ continue
+ # skip non-existent paths, in case somebody deleted a package
+ # manually, and duplicate paths as well
+ path = self.paths[-1] = normalize_path(
+ os.path.join(self.basedir, path)
+ )
+ if not os.path.exists(path) or path in seen:
+ self.paths.pop() # skip it
+ self.dirty = True # we cleaned up, so we're dirty now :)
+ continue
+ seen[path] = 1
+ f.close()
+
+ if self.paths and not saw_import:
+ self.dirty = True # ensure anything we touch has import wrappers
+ while self.paths and not self.paths[-1].strip():
+ self.paths.pop()
+
+ def save(self):
+ """Write changed .pth file back to disk"""
+ if not self.dirty:
+ return
+
+ rel_paths = list(map(self.make_relative, self.paths))
+ if rel_paths:
+ log.debug("Saving %s", self.filename)
+ lines = self._wrap_lines(rel_paths)
+ data = '\n'.join(lines) + '\n'
+
+ if os.path.islink(self.filename):
+ os.unlink(self.filename)
+ with open(self.filename, 'wt') as f:
+ f.write(data)
+
+ elif os.path.exists(self.filename):
+ log.debug("Deleting empty %s", self.filename)
+ os.unlink(self.filename)
+
+ self.dirty = False
+
+ @staticmethod
+ def _wrap_lines(lines):
+ return lines
+
+ def add(self, dist):
+ """Add `dist` to the distribution map"""
+ new_path = (
+ dist.location not in self.paths and (
+ dist.location not in self.sitedirs or
+ # account for '.' being in PYTHONPATH
+ dist.location == os.getcwd()
+ )
+ )
+ if new_path:
+ self.paths.append(dist.location)
+ self.dirty = True
+ Environment.add(self, dist)
+
+ def remove(self, dist):
+ """Remove `dist` from the distribution map"""
+ while dist.location in self.paths:
+ self.paths.remove(dist.location)
+ self.dirty = True
+ Environment.remove(self, dist)
+
+ def make_relative(self, path):
+ npath, last = os.path.split(normalize_path(path))
+ baselen = len(self.basedir)
+ parts = [last]
+ sep = os.altsep == '/' and '/' or os.sep
+ while len(npath) >= baselen:
+ if npath == self.basedir:
+ parts.append(os.curdir)
+ parts.reverse()
+ return sep.join(parts)
+ npath, last = os.path.split(npath)
+ parts.append(last)
+ else:
+ return path
+
+
+class RewritePthDistributions(PthDistributions):
+ @classmethod
+ def _wrap_lines(cls, lines):
+ yield cls.prelude
+ for line in lines:
+ yield line
+ yield cls.postlude
+
prelude = _one_liner("""
- import sys
- sys.__plen = len(sys.path)
- """)
+ import sys
+ sys.__plen = len(sys.path)
+ """)
postlude = _one_liner("""
- import sys
- new = sys.path[sys.__plen:]
- del sys.path[sys.__plen:]
- p = getattr(sys, '__egginsert', 0)
- sys.path[p:p] = new
- sys.__egginsert = p + len(new)
- """)
-
-
+ import sys
+ new = sys.path[sys.__plen:]
+ del sys.path[sys.__plen:]
+ p = getattr(sys, '__egginsert', 0)
+ sys.path[p:p] = new
+ sys.__egginsert = p + len(new)
+ """)
+
+
if os.environ.get('SETUPTOOLS_SYS_PATH_TECHNIQUE', 'raw') == 'rewrite':
- PthDistributions = RewritePthDistributions
-
-
-def _first_line_re():
- """
- Return a regular expression based on first_line_re suitable for matching
- strings.
- """
- if isinstance(first_line_re.pattern, str):
- return first_line_re
-
- # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
- return re.compile(first_line_re.pattern.decode())
-
-
-def auto_chmod(func, arg, exc):
+ PthDistributions = RewritePthDistributions
+
+
+def _first_line_re():
+ """
+ Return a regular expression based on first_line_re suitable for matching
+ strings.
+ """
+ if isinstance(first_line_re.pattern, str):
+ return first_line_re
+
+ # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
+ return re.compile(first_line_re.pattern.decode())
+
+
+def auto_chmod(func, arg, exc):
if func in [os.unlink, os.remove] and os.name == 'nt':
- chmod(arg, stat.S_IWRITE)
- return func(arg)
- et, ev, _ = sys.exc_info()
+ chmod(arg, stat.S_IWRITE)
+ return func(arg)
+ et, ev, _ = sys.exc_info()
# TODO: This code doesn't make sense. What is it trying to do?
raise (ev[0], ev[1] + (" %s %s" % (func, arg)))
-
-
-def update_dist_caches(dist_path, fix_zipimporter_caches):
- """
- Fix any globally cached `dist_path` related data
-
- `dist_path` should be a path of a newly installed egg distribution (zipped
- or unzipped).
-
- sys.path_importer_cache contains finder objects that have been cached when
- importing data from the original distribution. Any such finders need to be
- cleared since the replacement distribution might be packaged differently,
- e.g. a zipped egg distribution might get replaced with an unzipped egg
- folder or vice versa. Having the old finders cached may then cause Python
- to attempt loading modules from the replacement distribution using an
- incorrect loader.
-
- zipimport.zipimporter objects are Python loaders charged with importing
- data packaged inside zip archives. If stale loaders referencing the
- original distribution, are left behind, they can fail to load modules from
- the replacement distribution. E.g. if an old zipimport.zipimporter instance
- is used to load data from a new zipped egg archive, it may cause the
- operation to attempt to locate the requested data in the wrong location -
- one indicated by the original distribution's zip archive directory
- information. Such an operation may then fail outright, e.g. report having
- read a 'bad local file header', or even worse, it may fail silently &
- return invalid data.
-
- zipimport._zip_directory_cache contains cached zip archive directory
- information for all existing zipimport.zipimporter instances and all such
- instances connected to the same archive share the same cached directory
- information.
-
- If asked, and the underlying Python implementation allows it, we can fix
- all existing zipimport.zipimporter instances instead of having to track
- them down and remove them one by one, by updating their shared cached zip
- archive directory information. This, of course, assumes that the
- replacement distribution is packaged as a zipped egg.
-
- If not asked to fix existing zipimport.zipimporter instances, we still do
- our best to clear any remaining zipimport.zipimporter related cached data
- that might somehow later get used when attempting to load data from the new
- distribution and thus cause such load operations to fail. Note that when
- tracking down such remaining stale data, we can not catch every conceivable
- usage from here, and we clear only those that we know of and have found to
- cause problems if left alive. Any remaining caches should be updated by
- whomever is in charge of maintaining them, i.e. they should be ready to
- handle us replacing their zip archives with new distributions at runtime.
-
- """
- # There are several other known sources of stale zipimport.zipimporter
- # instances that we do not clear here, but might if ever given a reason to
- # do so:
- # * Global setuptools pkg_resources.working_set (a.k.a. 'master working
- # set') may contain distributions which may in turn contain their
- # zipimport.zipimporter loaders.
- # * Several zipimport.zipimporter loaders held by local variables further
- # up the function call stack when running the setuptools installation.
- # * Already loaded modules may have their __loader__ attribute set to the
- # exact loader instance used when importing them. Python 3.4 docs state
- # that this information is intended mostly for introspection and so is
- # not expected to cause us problems.
- normalized_path = normalize_path(dist_path)
- _uncache(normalized_path, sys.path_importer_cache)
- if fix_zipimporter_caches:
- _replace_zip_directory_cache_data(normalized_path)
- else:
- # Here, even though we do not want to fix existing and now stale
- # zipimporter cache information, we still want to remove it. Related to
- # Python's zip archive directory information cache, we clear each of
- # its stale entries in two phases:
- # 1. Clear the entry so attempting to access zip archive information
- # via any existing stale zipimport.zipimporter instances fails.
- # 2. Remove the entry from the cache so any newly constructed
- # zipimport.zipimporter instances do not end up using old stale
- # zip archive directory information.
- # This whole stale data removal step does not seem strictly necessary,
- # but has been left in because it was done before we started replacing
- # the zip archive directory information cache content if possible, and
- # there are no relevant unit tests that we can depend on to tell us if
- # this is really needed.
- _remove_and_clear_zip_directory_cache_data(normalized_path)
-
-
-def _collect_zipimporter_cache_entries(normalized_path, cache):
- """
- Return zipimporter cache entry keys related to a given normalized path.
-
- Alternative path spellings (e.g. those using different character case or
- those using alternative path separators) related to the same path are
- included. Any sub-path entries are included as well, i.e. those
- corresponding to zip archives embedded in other zip archives.
-
- """
- result = []
- prefix_len = len(normalized_path)
- for p in cache:
- np = normalize_path(p)
- if (np.startswith(normalized_path) and
- np[prefix_len:prefix_len + 1] in (os.sep, '')):
- result.append(p)
- return result
-
-
-def _update_zipimporter_cache(normalized_path, cache, updater=None):
- """
- Update zipimporter cache data for a given normalized path.
-
- Any sub-path entries are processed as well, i.e. those corresponding to zip
- archives embedded in other zip archives.
-
- Given updater is a callable taking a cache entry key and the original entry
- (after already removing the entry from the cache), and expected to update
- the entry and possibly return a new one to be inserted in its place.
- Returning None indicates that the entry should not be replaced with a new
- one. If no updater is given, the cache entries are simply removed without
- any additional processing, the same as if the updater simply returned None.
-
- """
- for p in _collect_zipimporter_cache_entries(normalized_path, cache):
- # N.B. pypy's custom zipimport._zip_directory_cache implementation does
- # not support the complete dict interface:
- # * Does not support item assignment, thus not allowing this function
- # to be used only for removing existing cache entries.
- # * Does not support the dict.pop() method, forcing us to use the
- # get/del patterns instead. For more detailed information see the
- # following links:
+
+
+def update_dist_caches(dist_path, fix_zipimporter_caches):
+ """
+ Fix any globally cached `dist_path` related data
+
+ `dist_path` should be a path of a newly installed egg distribution (zipped
+ or unzipped).
+
+ sys.path_importer_cache contains finder objects that have been cached when
+ importing data from the original distribution. Any such finders need to be
+ cleared since the replacement distribution might be packaged differently,
+ e.g. a zipped egg distribution might get replaced with an unzipped egg
+ folder or vice versa. Having the old finders cached may then cause Python
+ to attempt loading modules from the replacement distribution using an
+ incorrect loader.
+
+ zipimport.zipimporter objects are Python loaders charged with importing
+ data packaged inside zip archives. If stale loaders referencing the
+ original distribution, are left behind, they can fail to load modules from
+ the replacement distribution. E.g. if an old zipimport.zipimporter instance
+ is used to load data from a new zipped egg archive, it may cause the
+ operation to attempt to locate the requested data in the wrong location -
+ one indicated by the original distribution's zip archive directory
+ information. Such an operation may then fail outright, e.g. report having
+ read a 'bad local file header', or even worse, it may fail silently &
+ return invalid data.
+
+ zipimport._zip_directory_cache contains cached zip archive directory
+ information for all existing zipimport.zipimporter instances and all such
+ instances connected to the same archive share the same cached directory
+ information.
+
+ If asked, and the underlying Python implementation allows it, we can fix
+ all existing zipimport.zipimporter instances instead of having to track
+ them down and remove them one by one, by updating their shared cached zip
+ archive directory information. This, of course, assumes that the
+ replacement distribution is packaged as a zipped egg.
+
+ If not asked to fix existing zipimport.zipimporter instances, we still do
+ our best to clear any remaining zipimport.zipimporter related cached data
+ that might somehow later get used when attempting to load data from the new
+ distribution and thus cause such load operations to fail. Note that when
+ tracking down such remaining stale data, we can not catch every conceivable
+ usage from here, and we clear only those that we know of and have found to
+ cause problems if left alive. Any remaining caches should be updated by
+ whomever is in charge of maintaining them, i.e. they should be ready to
+ handle us replacing their zip archives with new distributions at runtime.
+
+ """
+ # There are several other known sources of stale zipimport.zipimporter
+ # instances that we do not clear here, but might if ever given a reason to
+ # do so:
+ # * Global setuptools pkg_resources.working_set (a.k.a. 'master working
+ # set') may contain distributions which may in turn contain their
+ # zipimport.zipimporter loaders.
+ # * Several zipimport.zipimporter loaders held by local variables further
+ # up the function call stack when running the setuptools installation.
+ # * Already loaded modules may have their __loader__ attribute set to the
+ # exact loader instance used when importing them. Python 3.4 docs state
+ # that this information is intended mostly for introspection and so is
+ # not expected to cause us problems.
+ normalized_path = normalize_path(dist_path)
+ _uncache(normalized_path, sys.path_importer_cache)
+ if fix_zipimporter_caches:
+ _replace_zip_directory_cache_data(normalized_path)
+ else:
+ # Here, even though we do not want to fix existing and now stale
+ # zipimporter cache information, we still want to remove it. Related to
+ # Python's zip archive directory information cache, we clear each of
+ # its stale entries in two phases:
+ # 1. Clear the entry so attempting to access zip archive information
+ # via any existing stale zipimport.zipimporter instances fails.
+ # 2. Remove the entry from the cache so any newly constructed
+ # zipimport.zipimporter instances do not end up using old stale
+ # zip archive directory information.
+ # This whole stale data removal step does not seem strictly necessary,
+ # but has been left in because it was done before we started replacing
+ # the zip archive directory information cache content if possible, and
+ # there are no relevant unit tests that we can depend on to tell us if
+ # this is really needed.
+ _remove_and_clear_zip_directory_cache_data(normalized_path)
+
+
+def _collect_zipimporter_cache_entries(normalized_path, cache):
+ """
+ Return zipimporter cache entry keys related to a given normalized path.
+
+ Alternative path spellings (e.g. those using different character case or
+ those using alternative path separators) related to the same path are
+ included. Any sub-path entries are included as well, i.e. those
+ corresponding to zip archives embedded in other zip archives.
+
+ """
+ result = []
+ prefix_len = len(normalized_path)
+ for p in cache:
+ np = normalize_path(p)
+ if (np.startswith(normalized_path) and
+ np[prefix_len:prefix_len + 1] in (os.sep, '')):
+ result.append(p)
+ return result
+
+
+def _update_zipimporter_cache(normalized_path, cache, updater=None):
+ """
+ Update zipimporter cache data for a given normalized path.
+
+ Any sub-path entries are processed as well, i.e. those corresponding to zip
+ archives embedded in other zip archives.
+
+ Given updater is a callable taking a cache entry key and the original entry
+ (after already removing the entry from the cache), and expected to update
+ the entry and possibly return a new one to be inserted in its place.
+ Returning None indicates that the entry should not be replaced with a new
+ one. If no updater is given, the cache entries are simply removed without
+ any additional processing, the same as if the updater simply returned None.
+
+ """
+ for p in _collect_zipimporter_cache_entries(normalized_path, cache):
+ # N.B. pypy's custom zipimport._zip_directory_cache implementation does
+ # not support the complete dict interface:
+ # * Does not support item assignment, thus not allowing this function
+ # to be used only for removing existing cache entries.
+ # * Does not support the dict.pop() method, forcing us to use the
+ # get/del patterns instead. For more detailed information see the
+ # following links:
# https://github.com/pypa/setuptools/issues/202#issuecomment-202913420
# http://bit.ly/2h9itJX
- old_entry = cache[p]
- del cache[p]
- new_entry = updater and updater(p, old_entry)
- if new_entry is not None:
- cache[p] = new_entry
-
-
-def _uncache(normalized_path, cache):
- _update_zipimporter_cache(normalized_path, cache)
-
-
-def _remove_and_clear_zip_directory_cache_data(normalized_path):
- def clear_and_remove_cached_zip_archive_directory_data(path, old_entry):
- old_entry.clear()
-
- _update_zipimporter_cache(
- normalized_path, zipimport._zip_directory_cache,
- updater=clear_and_remove_cached_zip_archive_directory_data)
-
-
-# PyPy Python implementation does not allow directly writing to the
-# zipimport._zip_directory_cache and so prevents us from attempting to correct
-# its content. The best we can do there is clear the problematic cache content
-# and have PyPy repopulate it as needed. The downside is that if there are any
-# stale zipimport.zipimporter instances laying around, attempting to use them
-# will fail due to not having its zip archive directory information available
-# instead of being automatically corrected to use the new correct zip archive
-# directory information.
-if '__pypy__' in sys.builtin_module_names:
- _replace_zip_directory_cache_data = \
- _remove_and_clear_zip_directory_cache_data
-else:
-
- def _replace_zip_directory_cache_data(normalized_path):
- def replace_cached_zip_archive_directory_data(path, old_entry):
- # N.B. In theory, we could load the zip directory information just
- # once for all updated path spellings, and then copy it locally and
- # update its contained path strings to contain the correct
- # spelling, but that seems like a way too invasive move (this cache
- # structure is not officially documented anywhere and could in
- # theory change with new Python releases) for no significant
- # benefit.
- old_entry.clear()
- zipimport.zipimporter(path)
- old_entry.update(zipimport._zip_directory_cache[path])
- return old_entry
-
- _update_zipimporter_cache(
- normalized_path, zipimport._zip_directory_cache,
- updater=replace_cached_zip_archive_directory_data)
-
-
-def is_python(text, filename='<string>'):
- "Is this string a valid Python script?"
- try:
- compile(text, filename, 'exec')
- except (SyntaxError, TypeError):
- return False
- else:
- return True
-
-
-def is_sh(executable):
- """Determine if the specified executable is a .sh (contains a #! line)"""
- try:
- with io.open(executable, encoding='latin-1') as fp:
- magic = fp.read(2)
- except (OSError, IOError):
- return executable
- return magic == '#!'
-
-
-def nt_quote_arg(arg):
- """Quote a command line argument according to Windows parsing rules"""
- return subprocess.list2cmdline([arg])
-
-
-def is_python_script(script_text, filename):
- """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
- """
- if filename.endswith('.py') or filename.endswith('.pyw'):
- return True # extension says it's Python
- if is_python(script_text, filename):
- return True # it's syntactically valid Python
- if script_text.startswith('#!'):
- # It begins with a '#!' line, so check if 'python' is in it somewhere
- return 'python' in script_text.splitlines()[0].lower()
-
- return False # Not any Python I can recognize
-
-
-try:
- from os import chmod as _chmod
-except ImportError:
- # Jython compatibility
- def _chmod(*args):
- pass
-
-
-def chmod(path, mode):
- log.debug("changing mode of %s to %o", path, mode)
- try:
- _chmod(path, mode)
- except os.error as e:
- log.debug("chmod failed: %s", e)
-
-
-class CommandSpec(list):
- """
- A command spec for a #! header, specified as a list of arguments akin to
- those passed to Popen.
- """
-
- options = []
- split_args = dict()
-
- @classmethod
- def best(cls):
- """
- Choose the best CommandSpec class based on environmental conditions.
- """
- return cls
-
- @classmethod
- def _sys_executable(cls):
- _default = os.path.normpath(sys.executable)
- return os.environ.get('__PYVENV_LAUNCHER__', _default)
-
- @classmethod
- def from_param(cls, param):
- """
- Construct a CommandSpec from a parameter to build_scripts, which may
- be None.
- """
- if isinstance(param, cls):
- return param
- if isinstance(param, list):
- return cls(param)
- if param is None:
- return cls.from_environment()
- # otherwise, assume it's a string.
- return cls.from_string(param)
-
- @classmethod
- def from_environment(cls):
- return cls([cls._sys_executable()])
-
- @classmethod
- def from_string(cls, string):
- """
- Construct a command spec from a simple string representing a command
- line parseable by shlex.split.
- """
- items = shlex.split(string, **cls.split_args)
- return cls(items)
-
- def install_options(self, script_text):
- self.options = shlex.split(self._extract_options(script_text))
- cmdline = subprocess.list2cmdline(self)
- if not isascii(cmdline):
- self.options[:0] = ['-x']
-
- @staticmethod
- def _extract_options(orig_script):
- """
- Extract any options from the first line of the script.
- """
- first = (orig_script + '\n').splitlines()[0]
- match = _first_line_re().match(first)
- options = match.group(1) or '' if match else ''
- return options.strip()
-
- def as_header(self):
- return self._render(self + list(self.options))
-
- @staticmethod
+ old_entry = cache[p]
+ del cache[p]
+ new_entry = updater and updater(p, old_entry)
+ if new_entry is not None:
+ cache[p] = new_entry
+
+
+def _uncache(normalized_path, cache):
+ _update_zipimporter_cache(normalized_path, cache)
+
+
+def _remove_and_clear_zip_directory_cache_data(normalized_path):
+ def clear_and_remove_cached_zip_archive_directory_data(path, old_entry):
+ old_entry.clear()
+
+ _update_zipimporter_cache(
+ normalized_path, zipimport._zip_directory_cache,
+ updater=clear_and_remove_cached_zip_archive_directory_data)
+
+
+# PyPy Python implementation does not allow directly writing to the
+# zipimport._zip_directory_cache and so prevents us from attempting to correct
+# its content. The best we can do there is clear the problematic cache content
+# and have PyPy repopulate it as needed. The downside is that if there are any
+# stale zipimport.zipimporter instances laying around, attempting to use them
+# will fail due to not having its zip archive directory information available
+# instead of being automatically corrected to use the new correct zip archive
+# directory information.
+if '__pypy__' in sys.builtin_module_names:
+ _replace_zip_directory_cache_data = \
+ _remove_and_clear_zip_directory_cache_data
+else:
+
+ def _replace_zip_directory_cache_data(normalized_path):
+ def replace_cached_zip_archive_directory_data(path, old_entry):
+ # N.B. In theory, we could load the zip directory information just
+ # once for all updated path spellings, and then copy it locally and
+ # update its contained path strings to contain the correct
+ # spelling, but that seems like a way too invasive move (this cache
+ # structure is not officially documented anywhere and could in
+ # theory change with new Python releases) for no significant
+ # benefit.
+ old_entry.clear()
+ zipimport.zipimporter(path)
+ old_entry.update(zipimport._zip_directory_cache[path])
+ return old_entry
+
+ _update_zipimporter_cache(
+ normalized_path, zipimport._zip_directory_cache,
+ updater=replace_cached_zip_archive_directory_data)
+
+
+def is_python(text, filename='<string>'):
+ "Is this string a valid Python script?"
+ try:
+ compile(text, filename, 'exec')
+ except (SyntaxError, TypeError):
+ return False
+ else:
+ return True
+
+
+def is_sh(executable):
+ """Determine if the specified executable is a .sh (contains a #! line)"""
+ try:
+ with io.open(executable, encoding='latin-1') as fp:
+ magic = fp.read(2)
+ except (OSError, IOError):
+ return executable
+ return magic == '#!'
+
+
+def nt_quote_arg(arg):
+ """Quote a command line argument according to Windows parsing rules"""
+ return subprocess.list2cmdline([arg])
+
+
+def is_python_script(script_text, filename):
+ """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
+ """
+ if filename.endswith('.py') or filename.endswith('.pyw'):
+ return True # extension says it's Python
+ if is_python(script_text, filename):
+ return True # it's syntactically valid Python
+ if script_text.startswith('#!'):
+ # It begins with a '#!' line, so check if 'python' is in it somewhere
+ return 'python' in script_text.splitlines()[0].lower()
+
+ return False # Not any Python I can recognize
+
+
+try:
+ from os import chmod as _chmod
+except ImportError:
+ # Jython compatibility
+ def _chmod(*args):
+ pass
+
+
+def chmod(path, mode):
+ log.debug("changing mode of %s to %o", path, mode)
+ try:
+ _chmod(path, mode)
+ except os.error as e:
+ log.debug("chmod failed: %s", e)
+
+
+class CommandSpec(list):
+ """
+ A command spec for a #! header, specified as a list of arguments akin to
+ those passed to Popen.
+ """
+
+ options = []
+ split_args = dict()
+
+ @classmethod
+ def best(cls):
+ """
+ Choose the best CommandSpec class based on environmental conditions.
+ """
+ return cls
+
+ @classmethod
+ def _sys_executable(cls):
+ _default = os.path.normpath(sys.executable)
+ return os.environ.get('__PYVENV_LAUNCHER__', _default)
+
+ @classmethod
+ def from_param(cls, param):
+ """
+ Construct a CommandSpec from a parameter to build_scripts, which may
+ be None.
+ """
+ if isinstance(param, cls):
+ return param
+ if isinstance(param, list):
+ return cls(param)
+ if param is None:
+ return cls.from_environment()
+ # otherwise, assume it's a string.
+ return cls.from_string(param)
+
+ @classmethod
+ def from_environment(cls):
+ return cls([cls._sys_executable()])
+
+ @classmethod
+ def from_string(cls, string):
+ """
+ Construct a command spec from a simple string representing a command
+ line parseable by shlex.split.
+ """
+ items = shlex.split(string, **cls.split_args)
+ return cls(items)
+
+ def install_options(self, script_text):
+ self.options = shlex.split(self._extract_options(script_text))
+ cmdline = subprocess.list2cmdline(self)
+ if not isascii(cmdline):
+ self.options[:0] = ['-x']
+
+ @staticmethod
+ def _extract_options(orig_script):
+ """
+ Extract any options from the first line of the script.
+ """
+ first = (orig_script + '\n').splitlines()[0]
+ match = _first_line_re().match(first)
+ options = match.group(1) or '' if match else ''
+ return options.strip()
+
+ def as_header(self):
+ return self._render(self + list(self.options))
+
+ @staticmethod
def _strip_quotes(item):
_QUOTES = '"\''
for q in _QUOTES:
@@ -2028,31 +2028,31 @@ class CommandSpec(list):
return item
@staticmethod
- def _render(items):
+ def _render(items):
cmdline = subprocess.list2cmdline(
CommandSpec._strip_quotes(item.strip()) for item in items)
- return '#!' + cmdline + '\n'
-
-
-# For pbr compat; will be removed in a future version.
-sys_executable = CommandSpec._sys_executable()
-
-
-class WindowsCommandSpec(CommandSpec):
- split_args = dict(posix=False)
-
-
+ return '#!' + cmdline + '\n'
+
+
+# For pbr compat; will be removed in a future version.
+sys_executable = CommandSpec._sys_executable()
+
+
+class WindowsCommandSpec(CommandSpec):
+ split_args = dict(posix=False)
+
+
class ScriptWriter:
- """
- Encapsulates behavior around writing entry point scripts for console and
- gui apps.
- """
-
+ """
+ Encapsulates behavior around writing entry point scripts for console and
+ gui apps.
+ """
+
template = textwrap.dedent(r"""
- # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r
+ # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r
import re
- import sys
-
+ import sys
+
# for compatibility with easy_install; see #2198
__requires__ = %(spec)r
@@ -2078,221 +2078,221 @@ class ScriptWriter:
globals().setdefault('load_entry_point', importlib_load_entry_point)
- if __name__ == '__main__':
+ if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(load_entry_point(%(spec)r, %(group)r, %(name)r)())
""").lstrip()
-
- command_spec_class = CommandSpec
-
- @classmethod
- def get_script_args(cls, dist, executable=None, wininst=False):
- # for backward compatibility
+
+ command_spec_class = CommandSpec
+
+ @classmethod
+ def get_script_args(cls, dist, executable=None, wininst=False):
+ # for backward compatibility
warnings.warn("Use get_args", EasyInstallDeprecationWarning)
- writer = (WindowsScriptWriter if wininst else ScriptWriter).best()
- header = cls.get_script_header("", executable, wininst)
- return writer.get_args(dist, header)
-
- @classmethod
- def get_script_header(cls, script_text, executable=None, wininst=False):
- # for backward compatibility
+ writer = (WindowsScriptWriter if wininst else ScriptWriter).best()
+ header = cls.get_script_header("", executable, wininst)
+ return writer.get_args(dist, header)
+
+ @classmethod
+ def get_script_header(cls, script_text, executable=None, wininst=False):
+ # for backward compatibility
warnings.warn(
"Use get_header", EasyInstallDeprecationWarning, stacklevel=2)
- if wininst:
- executable = "python.exe"
+ if wininst:
+ executable = "python.exe"
return cls.get_header(script_text, executable)
-
- @classmethod
- def get_args(cls, dist, header=None):
- """
- Yield write_script() argument tuples for a distribution's
- console_scripts and gui_scripts entry points.
- """
- if header is None:
- header = cls.get_header()
- spec = str(dist.as_requirement())
- for type_ in 'console', 'gui':
- group = type_ + '_scripts'
- for name, ep in dist.get_entry_map(group).items():
- cls._ensure_safe_name(name)
- script_text = cls.template % locals()
- args = cls._get_script_args(type_, name, header, script_text)
- for res in args:
- yield res
-
- @staticmethod
- def _ensure_safe_name(name):
- """
- Prevent paths in *_scripts entry point names.
- """
- has_path_sep = re.search(r'[\\/]', name)
- if has_path_sep:
- raise ValueError("Path separators not allowed in script names")
-
- @classmethod
- def get_writer(cls, force_windows):
- # for backward compatibility
+
+ @classmethod
+ def get_args(cls, dist, header=None):
+ """
+ Yield write_script() argument tuples for a distribution's
+ console_scripts and gui_scripts entry points.
+ """
+ if header is None:
+ header = cls.get_header()
+ spec = str(dist.as_requirement())
+ for type_ in 'console', 'gui':
+ group = type_ + '_scripts'
+ for name, ep in dist.get_entry_map(group).items():
+ cls._ensure_safe_name(name)
+ script_text = cls.template % locals()
+ args = cls._get_script_args(type_, name, header, script_text)
+ for res in args:
+ yield res
+
+ @staticmethod
+ def _ensure_safe_name(name):
+ """
+ Prevent paths in *_scripts entry point names.
+ """
+ has_path_sep = re.search(r'[\\/]', name)
+ if has_path_sep:
+ raise ValueError("Path separators not allowed in script names")
+
+ @classmethod
+ def get_writer(cls, force_windows):
+ # for backward compatibility
warnings.warn("Use best", EasyInstallDeprecationWarning)
- return WindowsScriptWriter.best() if force_windows else cls.best()
-
- @classmethod
- def best(cls):
- """
- Select the best ScriptWriter for this environment.
- """
- if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):
- return WindowsScriptWriter.best()
- else:
- return cls
-
- @classmethod
- def _get_script_args(cls, type_, name, header, script_text):
- # Simply write the stub with no extension.
- yield (name, header + script_text)
-
- @classmethod
- def get_header(cls, script_text="", executable=None):
- """Create a #! line, getting options (if any) from script_text"""
- cmd = cls.command_spec_class.best().from_param(executable)
- cmd.install_options(script_text)
- return cmd.as_header()
-
-
-class WindowsScriptWriter(ScriptWriter):
- command_spec_class = WindowsCommandSpec
-
- @classmethod
- def get_writer(cls):
- # for backward compatibility
+ return WindowsScriptWriter.best() if force_windows else cls.best()
+
+ @classmethod
+ def best(cls):
+ """
+ Select the best ScriptWriter for this environment.
+ """
+ if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):
+ return WindowsScriptWriter.best()
+ else:
+ return cls
+
+ @classmethod
+ def _get_script_args(cls, type_, name, header, script_text):
+ # Simply write the stub with no extension.
+ yield (name, header + script_text)
+
+ @classmethod
+ def get_header(cls, script_text="", executable=None):
+ """Create a #! line, getting options (if any) from script_text"""
+ cmd = cls.command_spec_class.best().from_param(executable)
+ cmd.install_options(script_text)
+ return cmd.as_header()
+
+
+class WindowsScriptWriter(ScriptWriter):
+ command_spec_class = WindowsCommandSpec
+
+ @classmethod
+ def get_writer(cls):
+ # for backward compatibility
warnings.warn("Use best", EasyInstallDeprecationWarning)
- return cls.best()
-
- @classmethod
- def best(cls):
- """
- Select the best ScriptWriter suitable for Windows
- """
- writer_lookup = dict(
- executable=WindowsExecutableLauncherWriter,
- natural=cls,
- )
- # for compatibility, use the executable launcher by default
- launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable')
- return writer_lookup[launcher]
-
- @classmethod
- def _get_script_args(cls, type_, name, header, script_text):
- "For Windows, add a .py extension"
- ext = dict(console='.pya', gui='.pyw')[type_]
- if ext not in os.environ['PATHEXT'].lower().split(';'):
+ return cls.best()
+
+ @classmethod
+ def best(cls):
+ """
+ Select the best ScriptWriter suitable for Windows
+ """
+ writer_lookup = dict(
+ executable=WindowsExecutableLauncherWriter,
+ natural=cls,
+ )
+ # for compatibility, use the executable launcher by default
+ launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable')
+ return writer_lookup[launcher]
+
+ @classmethod
+ def _get_script_args(cls, type_, name, header, script_text):
+ "For Windows, add a .py extension"
+ ext = dict(console='.pya', gui='.pyw')[type_]
+ if ext not in os.environ['PATHEXT'].lower().split(';'):
msg = (
"{ext} not listed in PATHEXT; scripts will not be "
"recognized as executables."
).format(**locals())
warnings.warn(msg, UserWarning)
- old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
- old.remove(ext)
- header = cls._adjust_header(type_, header)
- blockers = [name + x for x in old]
- yield name + ext, header + script_text, 't', blockers
-
- @classmethod
- def _adjust_header(cls, type_, orig_header):
- """
+ old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
+ old.remove(ext)
+ header = cls._adjust_header(type_, header)
+ blockers = [name + x for x in old]
+ yield name + ext, header + script_text, 't', blockers
+
+ @classmethod
+ def _adjust_header(cls, type_, orig_header):
+ """
Make sure 'pythonw' is used for gui and 'python' is used for
- console (regardless of what sys.executable is).
- """
- pattern = 'pythonw.exe'
- repl = 'python.exe'
- if type_ == 'gui':
- pattern, repl = repl, pattern
- pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE)
- new_header = pattern_ob.sub(string=orig_header, repl=repl)
- return new_header if cls._use_header(new_header) else orig_header
-
- @staticmethod
- def _use_header(new_header):
- """
- Should _adjust_header use the replaced header?
-
- On non-windows systems, always use. On
- Windows systems, only use the replaced header if it resolves
- to an executable on the system.
- """
- clean_header = new_header[2:-1].strip('"')
- return sys.platform != 'win32' or find_executable(clean_header)
-
-
-class WindowsExecutableLauncherWriter(WindowsScriptWriter):
- @classmethod
- def _get_script_args(cls, type_, name, header, script_text):
- """
- For Windows, add a .py extension and an .exe launcher
- """
- if type_ == 'gui':
- launcher_type = 'gui'
- ext = '-script.pyw'
- old = ['.pyw']
- else:
- launcher_type = 'cli'
- ext = '-script.py'
- old = ['.py', '.pyc', '.pyo']
- hdr = cls._adjust_header(type_, header)
- blockers = [name + x for x in old]
- yield (name + ext, hdr + script_text, 't', blockers)
- yield (
- name + '.exe', get_win_launcher(launcher_type),
- 'b' # write in binary mode
- )
- if not is_64bit():
- # install a manifest for the launcher to prevent Windows
- # from detecting it as an installer (which it will for
- # launchers like easy_install.exe). Consider only
- # adding a manifest for launchers detected as installers.
- # See Distribute #143 for details.
- m_name = name + '.exe.manifest'
- yield (m_name, load_launcher_manifest(name), 't')
-
-
-# for backward-compatibility
-get_script_args = ScriptWriter.get_script_args
-get_script_header = ScriptWriter.get_script_header
-
-
-def get_win_launcher(type):
- """
- Load the Windows launcher (executable) suitable for launching a script.
-
- `type` should be either 'cli' or 'gui'
-
- Returns the executable as a byte string.
- """
- launcher_fn = '%s.exe' % type
- if is_64bit():
+ console (regardless of what sys.executable is).
+ """
+ pattern = 'pythonw.exe'
+ repl = 'python.exe'
+ if type_ == 'gui':
+ pattern, repl = repl, pattern
+ pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE)
+ new_header = pattern_ob.sub(string=orig_header, repl=repl)
+ return new_header if cls._use_header(new_header) else orig_header
+
+ @staticmethod
+ def _use_header(new_header):
+ """
+ Should _adjust_header use the replaced header?
+
+ On non-windows systems, always use. On
+ Windows systems, only use the replaced header if it resolves
+ to an executable on the system.
+ """
+ clean_header = new_header[2:-1].strip('"')
+ return sys.platform != 'win32' or find_executable(clean_header)
+
+
+class WindowsExecutableLauncherWriter(WindowsScriptWriter):
+ @classmethod
+ def _get_script_args(cls, type_, name, header, script_text):
+ """
+ For Windows, add a .py extension and an .exe launcher
+ """
+ if type_ == 'gui':
+ launcher_type = 'gui'
+ ext = '-script.pyw'
+ old = ['.pyw']
+ else:
+ launcher_type = 'cli'
+ ext = '-script.py'
+ old = ['.py', '.pyc', '.pyo']
+ hdr = cls._adjust_header(type_, header)
+ blockers = [name + x for x in old]
+ yield (name + ext, hdr + script_text, 't', blockers)
+ yield (
+ name + '.exe', get_win_launcher(launcher_type),
+ 'b' # write in binary mode
+ )
+ if not is_64bit():
+ # install a manifest for the launcher to prevent Windows
+ # from detecting it as an installer (which it will for
+ # launchers like easy_install.exe). Consider only
+ # adding a manifest for launchers detected as installers.
+ # See Distribute #143 for details.
+ m_name = name + '.exe.manifest'
+ yield (m_name, load_launcher_manifest(name), 't')
+
+
+# for backward-compatibility
+get_script_args = ScriptWriter.get_script_args
+get_script_header = ScriptWriter.get_script_header
+
+
+def get_win_launcher(type):
+ """
+ Load the Windows launcher (executable) suitable for launching a script.
+
+ `type` should be either 'cli' or 'gui'
+
+ Returns the executable as a byte string.
+ """
+ launcher_fn = '%s.exe' % type
+ if is_64bit():
if get_platform() == "win-arm64":
launcher_fn = launcher_fn.replace(".", "-arm64.")
else:
launcher_fn = launcher_fn.replace(".", "-64.")
- else:
- launcher_fn = launcher_fn.replace(".", "-32.")
- return resource_string('setuptools', launcher_fn)
-
-
-def load_launcher_manifest(name):
- manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')
+ else:
+ launcher_fn = launcher_fn.replace(".", "-32.")
+ return resource_string('setuptools', launcher_fn)
+
+
+def load_launcher_manifest(name):
+ manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')
return manifest.decode('utf-8') % vars()
-
-
-def rmtree(path, ignore_errors=False, onerror=auto_chmod):
+
+
+def rmtree(path, ignore_errors=False, onerror=auto_chmod):
return shutil.rmtree(path, ignore_errors, onerror)
-
-
-def current_umask():
- tmp = os.umask(0o022)
- os.umask(tmp)
- return tmp
-
-
+
+
+def current_umask():
+ tmp = os.umask(0o022)
+ os.umask(tmp)
+ return tmp
+
+
class EasyInstallDeprecationWarning(SetuptoolsDeprecationWarning):
"""
Warning for EasyInstall deprecations, bypassing suppression.
diff --git a/contrib/python/setuptools/py3/setuptools/command/egg_info.py b/contrib/python/setuptools/py3/setuptools/command/egg_info.py
index 2f2f768fef..f2210292e3 100644
--- a/contrib/python/setuptools/py3/setuptools/command/egg_info.py
+++ b/contrib/python/setuptools/py3/setuptools/command/egg_info.py
@@ -1,36 +1,36 @@
-"""setuptools.command.egg_info
-
-Create a distribution's .egg-info directory and contents"""
-
-from distutils.filelist import FileList as _FileList
+"""setuptools.command.egg_info
+
+Create a distribution's .egg-info directory and contents"""
+
+from distutils.filelist import FileList as _FileList
from distutils.errors import DistutilsInternalError
-from distutils.util import convert_path
-from distutils import log
-import distutils.errors
-import distutils.filelist
+from distutils.util import convert_path
+from distutils import log
+import distutils.errors
+import distutils.filelist
import functools
-import os
-import re
-import sys
-import io
-import warnings
-import time
+import os
+import re
+import sys
+import io
+import warnings
+import time
import collections
-
-from setuptools import Command
-from setuptools.command.sdist import sdist
-from setuptools.command.sdist import walk_revctrl
-from setuptools.command.setopt import edit_config
-from setuptools.command import bdist_egg
-from pkg_resources import (
- parse_requirements, safe_name, parse_version,
- safe_version, yield_lines, EntryPoint, iter_entry_points, to_filename)
-import setuptools.unicode_utils as unicode_utils
+
+from setuptools import Command
+from setuptools.command.sdist import sdist
+from setuptools.command.sdist import walk_revctrl
+from setuptools.command.setopt import edit_config
+from setuptools.command import bdist_egg
+from pkg_resources import (
+ parse_requirements, safe_name, parse_version,
+ safe_version, yield_lines, EntryPoint, iter_entry_points, to_filename)
+import setuptools.unicode_utils as unicode_utils
from setuptools.glob import glob
-
+
from setuptools.extern import packaging
from setuptools import SetuptoolsDeprecationWarning
-
+
def translate_pattern(glob): # noqa: C901 # is too complex (14) # FIXME
"""
@@ -40,7 +40,7 @@ def translate_pattern(glob): # noqa: C901 # is too complex (14) # FIXME
directories.
"""
pat = ''
-
+
# This will split on '/' within [character classes]. This is deliberate.
chunks = glob.split(os.path.sep)
@@ -147,28 +147,28 @@ class InfoCommon:
class egg_info(InfoCommon, Command):
- description = "create a distribution's .egg-info directory"
-
- user_options = [
- ('egg-base=', 'e', "directory containing .egg-info directories"
- " (default: top of the source tree)"),
- ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
- ('tag-build=', 'b', "Specify explicit tag to add to version number"),
- ('no-date', 'D', "Don't include date stamp [default]"),
- ]
-
+ description = "create a distribution's .egg-info directory"
+
+ user_options = [
+ ('egg-base=', 'e', "directory containing .egg-info directories"
+ " (default: top of the source tree)"),
+ ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
+ ('tag-build=', 'b', "Specify explicit tag to add to version number"),
+ ('no-date', 'D', "Don't include date stamp [default]"),
+ ]
+
boolean_options = ['tag-date']
negative_opt = {
'no-date': 'tag-date',
}
-
- def initialize_options(self):
+
+ def initialize_options(self):
self.egg_base = None
- self.egg_name = None
+ self.egg_name = None
self.egg_info = None
- self.egg_version = None
- self.broken_egg_info = False
-
+ self.egg_version = None
+ self.broken_egg_info = False
+
####################################
# allow the 'tag_svn_revision' to be detected and
# set, supporting sdists built on older Setuptools.
@@ -181,7 +181,7 @@ class egg_info(InfoCommon, Command):
pass
####################################
- def save_version_info(self, filename):
+ def save_version_info(self, filename):
"""
Materialize the value of date into the
build tag. Install build keys in a deterministic order
@@ -193,138 +193,138 @@ class egg_info(InfoCommon, Command):
egg_info['tag_build'] = self.tags()
egg_info['tag_date'] = 0
edit_config(filename, dict(egg_info=egg_info))
-
- def finalize_options(self):
+
+ def finalize_options(self):
# Note: we need to capture the current value returned
# by `self.tagged_version()`, so we can later update
# `self.distribution.metadata.version` without
# repercussions.
self.egg_name = self.name
- self.egg_version = self.tagged_version()
- parsed_version = parse_version(self.egg_version)
-
- try:
- is_version = isinstance(parsed_version, packaging.version.Version)
- spec = (
- "%s==%s" if is_version else "%s===%s"
- )
- list(
- parse_requirements(spec % (self.egg_name, self.egg_version))
- )
+ self.egg_version = self.tagged_version()
+ parsed_version = parse_version(self.egg_version)
+
+ try:
+ is_version = isinstance(parsed_version, packaging.version.Version)
+ spec = (
+ "%s==%s" if is_version else "%s===%s"
+ )
+ list(
+ parse_requirements(spec % (self.egg_name, self.egg_version))
+ )
except ValueError as e:
- raise distutils.errors.DistutilsOptionError(
- "Invalid distribution name or version syntax: %s-%s" %
- (self.egg_name, self.egg_version)
+ raise distutils.errors.DistutilsOptionError(
+ "Invalid distribution name or version syntax: %s-%s" %
+ (self.egg_name, self.egg_version)
) from e
-
- if self.egg_base is None:
- dirs = self.distribution.package_dir
- self.egg_base = (dirs or {}).get('', os.curdir)
-
- self.ensure_dirname('egg_base')
- self.egg_info = to_filename(self.egg_name) + '.egg-info'
- if self.egg_base != os.curdir:
- self.egg_info = os.path.join(self.egg_base, self.egg_info)
- if '-' in self.egg_name:
- self.check_broken_egg_info()
-
- # Set package version for the benefit of dumber commands
- # (e.g. sdist, bdist_wininst, etc.)
- #
- self.distribution.metadata.version = self.egg_version
-
- # If we bootstrapped around the lack of a PKG-INFO, as might be the
- # case in a fresh checkout, make sure that any special tags get added
- # to the version info
- #
- pd = self.distribution._patched_dist
- if pd is not None and pd.key == self.egg_name.lower():
- pd._version = self.egg_version
- pd._parsed_version = parse_version(self.egg_version)
- self.distribution._patched_dist = None
-
- def write_or_delete_file(self, what, filename, data, force=False):
- """Write `data` to `filename` or delete if empty
-
- If `data` is non-empty, this routine is the same as ``write_file()``.
- If `data` is empty but not ``None``, this is the same as calling
- ``delete_file(filename)`. If `data` is ``None``, then this is a no-op
- unless `filename` exists, in which case a warning is issued about the
- orphaned file (if `force` is false), or deleted (if `force` is true).
- """
- if data:
- self.write_file(what, filename, data)
- elif os.path.exists(filename):
- if data is None and not force:
- log.warn(
- "%s not set in setup(), but %s exists", what, filename
- )
- return
- else:
- self.delete_file(filename)
-
- def write_file(self, what, filename, data):
- """Write `data` to `filename` (if not a dry run) after announcing it
-
- `what` is used in a log message to identify what is being written
- to the file.
- """
- log.info("writing %s to %s", what, filename)
+
+ if self.egg_base is None:
+ dirs = self.distribution.package_dir
+ self.egg_base = (dirs or {}).get('', os.curdir)
+
+ self.ensure_dirname('egg_base')
+ self.egg_info = to_filename(self.egg_name) + '.egg-info'
+ if self.egg_base != os.curdir:
+ self.egg_info = os.path.join(self.egg_base, self.egg_info)
+ if '-' in self.egg_name:
+ self.check_broken_egg_info()
+
+ # Set package version for the benefit of dumber commands
+ # (e.g. sdist, bdist_wininst, etc.)
+ #
+ self.distribution.metadata.version = self.egg_version
+
+ # If we bootstrapped around the lack of a PKG-INFO, as might be the
+ # case in a fresh checkout, make sure that any special tags get added
+ # to the version info
+ #
+ pd = self.distribution._patched_dist
+ if pd is not None and pd.key == self.egg_name.lower():
+ pd._version = self.egg_version
+ pd._parsed_version = parse_version(self.egg_version)
+ self.distribution._patched_dist = None
+
+ def write_or_delete_file(self, what, filename, data, force=False):
+ """Write `data` to `filename` or delete if empty
+
+ If `data` is non-empty, this routine is the same as ``write_file()``.
+ If `data` is empty but not ``None``, this is the same as calling
+ ``delete_file(filename)`. If `data` is ``None``, then this is a no-op
+ unless `filename` exists, in which case a warning is issued about the
+ orphaned file (if `force` is false), or deleted (if `force` is true).
+ """
+ if data:
+ self.write_file(what, filename, data)
+ elif os.path.exists(filename):
+ if data is None and not force:
+ log.warn(
+ "%s not set in setup(), but %s exists", what, filename
+ )
+ return
+ else:
+ self.delete_file(filename)
+
+ def write_file(self, what, filename, data):
+ """Write `data` to `filename` (if not a dry run) after announcing it
+
+ `what` is used in a log message to identify what is being written
+ to the file.
+ """
+ log.info("writing %s to %s", what, filename)
data = data.encode("utf-8")
- if not self.dry_run:
- f = open(filename, 'wb')
- f.write(data)
- f.close()
-
- def delete_file(self, filename):
- """Delete `filename` (if not a dry run) after announcing it"""
- log.info("deleting %s", filename)
- if not self.dry_run:
- os.unlink(filename)
-
- def run(self):
- self.mkpath(self.egg_info)
+ if not self.dry_run:
+ f = open(filename, 'wb')
+ f.write(data)
+ f.close()
+
+ def delete_file(self, filename):
+ """Delete `filename` (if not a dry run) after announcing it"""
+ log.info("deleting %s", filename)
+ if not self.dry_run:
+ os.unlink(filename)
+
+ def run(self):
+ self.mkpath(self.egg_info)
os.utime(self.egg_info, None)
- installer = self.distribution.fetch_build_egg
- for ep in iter_entry_points('egg_info.writers'):
- ep.require(installer=installer)
- writer = ep.resolve()
- writer(self, ep.name, os.path.join(self.egg_info, ep.name))
-
- # Get rid of native_libs.txt if it was put there by older bdist_egg
- nl = os.path.join(self.egg_info, "native_libs.txt")
- if os.path.exists(nl):
- self.delete_file(nl)
-
- self.find_sources()
-
- def find_sources(self):
- """Generate SOURCES.txt manifest file"""
- manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
- mm = manifest_maker(self.distribution)
- mm.manifest = manifest_filename
- mm.run()
- self.filelist = mm.filelist
-
- def check_broken_egg_info(self):
- bei = self.egg_name + '.egg-info'
- if self.egg_base != os.curdir:
- bei = os.path.join(self.egg_base, bei)
- if os.path.exists(bei):
- log.warn(
- "-" * 78 + '\n'
- "Note: Your current .egg-info directory has a '-' in its name;"
- '\nthis will not work correctly with "setup.py develop".\n\n'
- 'Please rename %s to %s to correct this problem.\n' + '-' * 78,
- bei, self.egg_info
- )
- self.broken_egg_info = self.egg_info
- self.egg_info = bei # make it work for now
-
-
-class FileList(_FileList):
+ installer = self.distribution.fetch_build_egg
+ for ep in iter_entry_points('egg_info.writers'):
+ ep.require(installer=installer)
+ writer = ep.resolve()
+ writer(self, ep.name, os.path.join(self.egg_info, ep.name))
+
+ # Get rid of native_libs.txt if it was put there by older bdist_egg
+ nl = os.path.join(self.egg_info, "native_libs.txt")
+ if os.path.exists(nl):
+ self.delete_file(nl)
+
+ self.find_sources()
+
+ def find_sources(self):
+ """Generate SOURCES.txt manifest file"""
+ manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
+ mm = manifest_maker(self.distribution)
+ mm.manifest = manifest_filename
+ mm.run()
+ self.filelist = mm.filelist
+
+ def check_broken_egg_info(self):
+ bei = self.egg_name + '.egg-info'
+ if self.egg_base != os.curdir:
+ bei = os.path.join(self.egg_base, bei)
+ if os.path.exists(bei):
+ log.warn(
+ "-" * 78 + '\n'
+ "Note: Your current .egg-info directory has a '-' in its name;"
+ '\nthis will not work correctly with "setup.py develop".\n\n'
+ 'Please rename %s to %s to correct this problem.\n' + '-' * 78,
+ bei, self.egg_info
+ )
+ self.broken_egg_info = self.egg_info
+ self.egg_info = bei # make it work for now
+
+
+class FileList(_FileList):
# Implementations of the various MANIFEST.in commands
-
+
def process_template_line(self, line):
# Parse the line: split it up, make sure the right number of words
# is there, and return the relevant words. 'action' is always
@@ -477,96 +477,96 @@ class FileList(_FileList):
match = translate_pattern(os.path.join('**', pattern))
return self._remove_files(match.match)
- def append(self, item):
- if item.endswith('\r'): # Fix older sdists built on Windows
- item = item[:-1]
- path = convert_path(item)
-
- if self._safe_path(path):
- self.files.append(path)
-
- def extend(self, paths):
- self.files.extend(filter(self._safe_path, paths))
-
- def _repair(self):
- """
- Replace self.files with only safe paths
-
- Because some owners of FileList manipulate the underlying
- ``files`` attribute directly, this method must be called to
- repair those paths.
- """
- self.files = list(filter(self._safe_path, self.files))
-
- def _safe_path(self, path):
- enc_warn = "'%s' not %s encodable -- skipping"
-
- # To avoid accidental trans-codings errors, first to unicode
- u_path = unicode_utils.filesys_decode(path)
- if u_path is None:
- log.warn("'%s' in unexpected encoding -- skipping" % path)
- return False
-
- # Must ensure utf-8 encodability
- utf8_path = unicode_utils.try_encode(u_path, "utf-8")
- if utf8_path is None:
- log.warn(enc_warn, path, 'utf-8')
- return False
-
- try:
- # accept is either way checks out
- if os.path.exists(u_path) or os.path.exists(utf8_path):
- return True
- # this will catch any encode errors decoding u_path
- except UnicodeEncodeError:
- log.warn(enc_warn, path, sys.getfilesystemencoding())
-
-
-class manifest_maker(sdist):
- template = "MANIFEST.in"
-
- def initialize_options(self):
- self.use_defaults = 1
- self.prune = 1
- self.manifest_only = 1
- self.force_manifest = 1
-
- def finalize_options(self):
- pass
-
- def run(self):
- self.filelist = FileList()
- if not os.path.exists(self.manifest):
- self.write_manifest() # it must exist so it'll get in the list
- self.add_defaults()
- if os.path.exists(self.template):
- self.read_template()
+ def append(self, item):
+ if item.endswith('\r'): # Fix older sdists built on Windows
+ item = item[:-1]
+ path = convert_path(item)
+
+ if self._safe_path(path):
+ self.files.append(path)
+
+ def extend(self, paths):
+ self.files.extend(filter(self._safe_path, paths))
+
+ def _repair(self):
+ """
+ Replace self.files with only safe paths
+
+ Because some owners of FileList manipulate the underlying
+ ``files`` attribute directly, this method must be called to
+ repair those paths.
+ """
+ self.files = list(filter(self._safe_path, self.files))
+
+ def _safe_path(self, path):
+ enc_warn = "'%s' not %s encodable -- skipping"
+
+ # To avoid accidental trans-codings errors, first to unicode
+ u_path = unicode_utils.filesys_decode(path)
+ if u_path is None:
+ log.warn("'%s' in unexpected encoding -- skipping" % path)
+ return False
+
+ # Must ensure utf-8 encodability
+ utf8_path = unicode_utils.try_encode(u_path, "utf-8")
+ if utf8_path is None:
+ log.warn(enc_warn, path, 'utf-8')
+ return False
+
+ try:
+ # accept is either way checks out
+ if os.path.exists(u_path) or os.path.exists(utf8_path):
+ return True
+ # this will catch any encode errors decoding u_path
+ except UnicodeEncodeError:
+ log.warn(enc_warn, path, sys.getfilesystemencoding())
+
+
+class manifest_maker(sdist):
+ template = "MANIFEST.in"
+
+ def initialize_options(self):
+ self.use_defaults = 1
+ self.prune = 1
+ self.manifest_only = 1
+ self.force_manifest = 1
+
+ def finalize_options(self):
+ pass
+
+ def run(self):
+ self.filelist = FileList()
+ if not os.path.exists(self.manifest):
+ self.write_manifest() # it must exist so it'll get in the list
+ self.add_defaults()
+ if os.path.exists(self.template):
+ self.read_template()
self.add_license_files()
- self.prune_file_list()
- self.filelist.sort()
- self.filelist.remove_duplicates()
- self.write_manifest()
-
- def _manifest_normalize(self, path):
- path = unicode_utils.filesys_decode(path)
- return path.replace(os.sep, '/')
-
- def write_manifest(self):
- """
- Write the file list in 'self.filelist' to the manifest file
- named by 'self.manifest'.
- """
- self.filelist._repair()
-
- # Now _repairs should encodability, but not unicode
- files = [self._manifest_normalize(f) for f in self.filelist.files]
- msg = "writing manifest file '%s'" % self.manifest
- self.execute(write_file, (self.manifest, files), msg)
-
+ self.prune_file_list()
+ self.filelist.sort()
+ self.filelist.remove_duplicates()
+ self.write_manifest()
+
+ def _manifest_normalize(self, path):
+ path = unicode_utils.filesys_decode(path)
+ return path.replace(os.sep, '/')
+
+ def write_manifest(self):
+ """
+ Write the file list in 'self.filelist' to the manifest file
+ named by 'self.manifest'.
+ """
+ self.filelist._repair()
+
+ # Now _repairs should encodability, but not unicode
+ files = [self._manifest_normalize(f) for f in self.filelist.files]
+ msg = "writing manifest file '%s'" % self.manifest
+ self.execute(write_file, (self.manifest, files), msg)
+
def warn(self, msg):
if not self._should_suppress_warning(msg):
- sdist.warn(self, msg)
-
+ sdist.warn(self, msg)
+
@staticmethod
def _should_suppress_warning(msg):
"""
@@ -574,24 +574,24 @@ class manifest_maker(sdist):
"""
return re.match(r"standard file .*not found", msg)
- def add_defaults(self):
- sdist.add_defaults(self)
- self.filelist.append(self.template)
- self.filelist.append(self.manifest)
- rcfiles = list(walk_revctrl())
- if rcfiles:
- self.filelist.extend(rcfiles)
- elif os.path.exists(self.manifest):
- self.read_manifest()
+ def add_defaults(self):
+ sdist.add_defaults(self)
+ self.filelist.append(self.template)
+ self.filelist.append(self.manifest)
+ rcfiles = list(walk_revctrl())
+ if rcfiles:
+ self.filelist.extend(rcfiles)
+ elif os.path.exists(self.manifest):
+ self.read_manifest()
if os.path.exists("setup.py"):
# setup.py should be included by default, even if it's not
# the script called to create the sdist
self.filelist.append("setup.py")
- ei_cmd = self.get_finalized_command('egg_info')
+ ei_cmd = self.get_finalized_command('egg_info')
self.filelist.graft(ei_cmd.egg_info)
-
+
def add_license_files(self):
license_files = self.distribution.metadata.license_files or []
for lf in license_files:
@@ -599,22 +599,22 @@ class manifest_maker(sdist):
pass
self.filelist.extend(license_files)
- def prune_file_list(self):
- build = self.get_finalized_command('build')
- base_dir = self.distribution.get_fullname()
+ def prune_file_list(self):
+ build = self.get_finalized_command('build')
+ base_dir = self.distribution.get_fullname()
self.filelist.prune(build.build_base)
self.filelist.prune(base_dir)
- sep = re.escape(os.sep)
- self.filelist.exclude_pattern(r'(^|' + sep + r')(RCS|CVS|\.svn)' + sep,
- is_regex=1)
-
+ sep = re.escape(os.sep)
+ self.filelist.exclude_pattern(r'(^|' + sep + r')(RCS|CVS|\.svn)' + sep,
+ is_regex=1)
+
def _safe_data_files(self, build_py):
"""
The parent class implementation of this method
(``sdist``) will try to include data files, which
might cause recursion problems when
``include_package_data=True``.
-
+
Therefore, avoid triggering any attempt of
analyzing/building the manifest again.
"""
@@ -630,125 +630,125 @@ class manifest_maker(sdist):
return build_py.get_data_files()
-def write_file(filename, contents):
- """Create a file with the specified name and write 'contents' (a
- sequence of strings without line terminators) to it.
- """
- contents = "\n".join(contents)
-
- # assuming the contents has been vetted for utf-8 encoding
- contents = contents.encode("utf-8")
-
- with open(filename, "wb") as f: # always write POSIX-style manifest
- f.write(contents)
-
-
-def write_pkg_info(cmd, basename, filename):
- log.info("writing %s", filename)
- if not cmd.dry_run:
- metadata = cmd.distribution.metadata
- metadata.version, oldver = cmd.egg_version, metadata.version
- metadata.name, oldname = cmd.egg_name, metadata.name
-
- try:
- # write unescaped data to PKG-INFO, so older pkg_resources
- # can still parse it
- metadata.write_pkg_info(cmd.egg_info)
- finally:
- metadata.name, metadata.version = oldname, oldver
-
- safe = getattr(cmd.distribution, 'zip_safe', None)
-
- bdist_egg.write_safety_flag(cmd.egg_info, safe)
-
-
-def warn_depends_obsolete(cmd, basename, filename):
- if os.path.exists(filename):
- log.warn(
- "WARNING: 'depends.txt' is not used by setuptools 0.6!\n"
- "Use the install_requires/extras_require setup() args instead."
- )
-
-
-def _write_requirements(stream, reqs):
- lines = yield_lines(reqs or ())
+def write_file(filename, contents):
+ """Create a file with the specified name and write 'contents' (a
+ sequence of strings without line terminators) to it.
+ """
+ contents = "\n".join(contents)
+
+ # assuming the contents has been vetted for utf-8 encoding
+ contents = contents.encode("utf-8")
+
+ with open(filename, "wb") as f: # always write POSIX-style manifest
+ f.write(contents)
+
+
+def write_pkg_info(cmd, basename, filename):
+ log.info("writing %s", filename)
+ if not cmd.dry_run:
+ metadata = cmd.distribution.metadata
+ metadata.version, oldver = cmd.egg_version, metadata.version
+ metadata.name, oldname = cmd.egg_name, metadata.name
+
+ try:
+ # write unescaped data to PKG-INFO, so older pkg_resources
+ # can still parse it
+ metadata.write_pkg_info(cmd.egg_info)
+ finally:
+ metadata.name, metadata.version = oldname, oldver
+
+ safe = getattr(cmd.distribution, 'zip_safe', None)
+
+ bdist_egg.write_safety_flag(cmd.egg_info, safe)
+
+
+def warn_depends_obsolete(cmd, basename, filename):
+ if os.path.exists(filename):
+ log.warn(
+ "WARNING: 'depends.txt' is not used by setuptools 0.6!\n"
+ "Use the install_requires/extras_require setup() args instead."
+ )
+
+
+def _write_requirements(stream, reqs):
+ lines = yield_lines(reqs or ())
def append_cr(line):
return line + '\n'
- lines = map(append_cr, lines)
- stream.writelines(lines)
-
-
-def write_requirements(cmd, basename, filename):
- dist = cmd.distribution
+ lines = map(append_cr, lines)
+ stream.writelines(lines)
+
+
+def write_requirements(cmd, basename, filename):
+ dist = cmd.distribution
data = io.StringIO()
- _write_requirements(data, dist.install_requires)
- extras_require = dist.extras_require or {}
- for extra in sorted(extras_require):
- data.write('\n[{extra}]\n'.format(**vars()))
- _write_requirements(data, extras_require[extra])
- cmd.write_or_delete_file("requirements", filename, data.getvalue())
-
-
-def write_setup_requirements(cmd, basename, filename):
+ _write_requirements(data, dist.install_requires)
+ extras_require = dist.extras_require or {}
+ for extra in sorted(extras_require):
+ data.write('\n[{extra}]\n'.format(**vars()))
+ _write_requirements(data, extras_require[extra])
+ cmd.write_or_delete_file("requirements", filename, data.getvalue())
+
+
+def write_setup_requirements(cmd, basename, filename):
data = io.StringIO()
- _write_requirements(data, cmd.distribution.setup_requires)
- cmd.write_or_delete_file("setup-requirements", filename, data.getvalue())
-
-
-def write_toplevel_names(cmd, basename, filename):
- pkgs = dict.fromkeys(
- [
- k.split('.', 1)[0]
- for k in cmd.distribution.iter_distribution_names()
- ]
- )
- cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n')
-
-
-def overwrite_arg(cmd, basename, filename):
- write_arg(cmd, basename, filename, True)
-
-
-def write_arg(cmd, basename, filename, force=False):
- argname = os.path.splitext(basename)[0]
- value = getattr(cmd.distribution, argname, None)
- if value is not None:
- value = '\n'.join(value) + '\n'
- cmd.write_or_delete_file(argname, filename, value, force)
-
-
-def write_entries(cmd, basename, filename):
- ep = cmd.distribution.entry_points
-
+ _write_requirements(data, cmd.distribution.setup_requires)
+ cmd.write_or_delete_file("setup-requirements", filename, data.getvalue())
+
+
+def write_toplevel_names(cmd, basename, filename):
+ pkgs = dict.fromkeys(
+ [
+ k.split('.', 1)[0]
+ for k in cmd.distribution.iter_distribution_names()
+ ]
+ )
+ cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n')
+
+
+def overwrite_arg(cmd, basename, filename):
+ write_arg(cmd, basename, filename, True)
+
+
+def write_arg(cmd, basename, filename, force=False):
+ argname = os.path.splitext(basename)[0]
+ value = getattr(cmd.distribution, argname, None)
+ if value is not None:
+ value = '\n'.join(value) + '\n'
+ cmd.write_or_delete_file(argname, filename, value, force)
+
+
+def write_entries(cmd, basename, filename):
+ ep = cmd.distribution.entry_points
+
if isinstance(ep, str) or ep is None:
- data = ep
- elif ep is not None:
- data = []
- for section, contents in sorted(ep.items()):
+ data = ep
+ elif ep is not None:
+ data = []
+ for section, contents in sorted(ep.items()):
if not isinstance(contents, str):
- contents = EntryPoint.parse_group(section, contents)
- contents = '\n'.join(sorted(map(str, contents.values())))
- data.append('[%s]\n%s\n\n' % (section, contents))
- data = ''.join(data)
-
- cmd.write_or_delete_file('entry points', filename, data, True)
-
-
-def get_pkg_info_revision():
- """
- Get a -r### off of PKG-INFO Version in case this is an sdist of
- a subversion revision.
- """
+ contents = EntryPoint.parse_group(section, contents)
+ contents = '\n'.join(sorted(map(str, contents.values())))
+ data.append('[%s]\n%s\n\n' % (section, contents))
+ data = ''.join(data)
+
+ cmd.write_or_delete_file('entry points', filename, data, True)
+
+
+def get_pkg_info_revision():
+ """
+ Get a -r### off of PKG-INFO Version in case this is an sdist of
+ a subversion revision.
+ """
warnings.warn(
"get_pkg_info_revision is deprecated.", EggInfoDeprecationWarning)
- if os.path.exists('PKG-INFO'):
- with io.open('PKG-INFO') as f:
- for line in f:
- match = re.match(r"Version:.*-r(\d+)\s*$", line)
- if match:
- return int(match.group(1))
- return 0
+ if os.path.exists('PKG-INFO'):
+ with io.open('PKG-INFO') as f:
+ for line in f:
+ match = re.match(r"Version:.*-r(\d+)\s*$", line)
+ if match:
+ return int(match.group(1))
+ return 0
class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning):
diff --git a/contrib/python/setuptools/py3/setuptools/command/install.py b/contrib/python/setuptools/py3/setuptools/command/install.py
index 0997eb482f..35e54d2043 100644
--- a/contrib/python/setuptools/py3/setuptools/command/install.py
+++ b/contrib/python/setuptools/py3/setuptools/command/install.py
@@ -1,35 +1,35 @@
-from distutils.errors import DistutilsArgError
-import inspect
-import glob
-import warnings
-import platform
-import distutils.command.install as orig
-
-import setuptools
-
-# Prior to numpy 1.9, NumPy relies on the '_install' name, so provide it for
+from distutils.errors import DistutilsArgError
+import inspect
+import glob
+import warnings
+import platform
+import distutils.command.install as orig
+
+import setuptools
+
+# Prior to numpy 1.9, NumPy relies on the '_install' name, so provide it for
# now. See https://github.com/pypa/setuptools/issues/199/
-_install = orig.install
-
-
-class install(orig.install):
- """Use easy_install to install the package, w/dependencies"""
-
- user_options = orig.install.user_options + [
- ('old-and-unmanageable', None, "Try not to use this!"),
- ('single-version-externally-managed', None,
- "used by system package builders to create 'flat' eggs"),
- ]
- boolean_options = orig.install.boolean_options + [
- 'old-and-unmanageable', 'single-version-externally-managed',
- ]
- new_commands = [
- ('install_egg_info', lambda self: True),
- ('install_scripts', lambda self: True),
- ]
- _nc = dict(new_commands)
-
- def initialize_options(self):
+_install = orig.install
+
+
+class install(orig.install):
+ """Use easy_install to install the package, w/dependencies"""
+
+ user_options = orig.install.user_options + [
+ ('old-and-unmanageable', None, "Try not to use this!"),
+ ('single-version-externally-managed', None,
+ "used by system package builders to create 'flat' eggs"),
+ ]
+ boolean_options = orig.install.boolean_options + [
+ 'old-and-unmanageable', 'single-version-externally-managed',
+ ]
+ new_commands = [
+ ('install_egg_info', lambda self: True),
+ ('install_scripts', lambda self: True),
+ ]
+ _nc = dict(new_commands)
+
+ def initialize_options(self):
warnings.warn(
"setup.py install is deprecated. "
@@ -37,96 +37,96 @@ class install(orig.install):
setuptools.SetuptoolsDeprecationWarning,
)
- orig.install.initialize_options(self)
- self.old_and_unmanageable = None
- self.single_version_externally_managed = None
-
- def finalize_options(self):
- orig.install.finalize_options(self)
- if self.root:
- self.single_version_externally_managed = True
- elif self.single_version_externally_managed:
- if not self.root and not self.record:
- raise DistutilsArgError(
- "You must specify --record or --root when building system"
- " packages"
- )
-
- def handle_extra_path(self):
- if self.root or self.single_version_externally_managed:
- # explicit backward-compatibility mode, allow extra_path to work
- return orig.install.handle_extra_path(self)
-
- # Ignore extra_path when installing an egg (or being run by another
- # command without --root or --single-version-externally-managed
- self.path_file = None
- self.extra_dirs = ''
-
- def run(self):
- # Explicit request for old-style install? Just do it
- if self.old_and_unmanageable or self.single_version_externally_managed:
- return orig.install.run(self)
-
- if not self._called_from_setup(inspect.currentframe()):
- # Run in backward-compatibility mode to support bdist_* commands.
- orig.install.run(self)
- else:
- self.do_egg_install()
-
- @staticmethod
- def _called_from_setup(run_frame):
- """
- Attempt to detect whether run() was called from setup() or by another
- command. If called by setup(), the parent caller will be the
- 'run_command' method in 'distutils.dist', and *its* caller will be
- the 'run_commands' method. If called any other way, the
- immediate caller *might* be 'run_command', but it won't have been
- called by 'run_commands'. Return True in that case or if a call stack
- is unavailable. Return False otherwise.
- """
- if run_frame is None:
- msg = "Call stack not available. bdist_* commands may fail."
- warnings.warn(msg)
- if platform.python_implementation() == 'IronPython':
- msg = "For best results, pass -X:Frames to enable call stack."
- warnings.warn(msg)
- return True
- res = inspect.getouterframes(run_frame)[2]
- caller, = res[:1]
- info = inspect.getframeinfo(caller)
- caller_module = caller.f_globals.get('__name__', '')
- return (
- caller_module == 'distutils.dist'
- and info.function == 'run_commands'
- )
-
- def do_egg_install(self):
-
- easy_install = self.distribution.get_command_class('easy_install')
-
- cmd = easy_install(
- self.distribution, args="x", root=self.root, record=self.record,
- )
- cmd.ensure_finalized() # finalize before bdist_egg munges install cmd
- cmd.always_copy_from = '.' # make sure local-dir eggs get installed
-
- # pick up setup-dir .egg files only: no .egg-info
- cmd.package_index.scan(glob.glob('*.egg'))
-
- self.run_command('bdist_egg')
- args = [self.distribution.get_command_obj('bdist_egg').egg_output]
-
- if setuptools.bootstrap_install_from:
- # Bootstrap self-installation of setuptools
- args.insert(0, setuptools.bootstrap_install_from)
-
- cmd.args = args
+ orig.install.initialize_options(self)
+ self.old_and_unmanageable = None
+ self.single_version_externally_managed = None
+
+ def finalize_options(self):
+ orig.install.finalize_options(self)
+ if self.root:
+ self.single_version_externally_managed = True
+ elif self.single_version_externally_managed:
+ if not self.root and not self.record:
+ raise DistutilsArgError(
+ "You must specify --record or --root when building system"
+ " packages"
+ )
+
+ def handle_extra_path(self):
+ if self.root or self.single_version_externally_managed:
+ # explicit backward-compatibility mode, allow extra_path to work
+ return orig.install.handle_extra_path(self)
+
+ # Ignore extra_path when installing an egg (or being run by another
+ # command without --root or --single-version-externally-managed
+ self.path_file = None
+ self.extra_dirs = ''
+
+ def run(self):
+ # Explicit request for old-style install? Just do it
+ if self.old_and_unmanageable or self.single_version_externally_managed:
+ return orig.install.run(self)
+
+ if not self._called_from_setup(inspect.currentframe()):
+ # Run in backward-compatibility mode to support bdist_* commands.
+ orig.install.run(self)
+ else:
+ self.do_egg_install()
+
+ @staticmethod
+ def _called_from_setup(run_frame):
+ """
+ Attempt to detect whether run() was called from setup() or by another
+ command. If called by setup(), the parent caller will be the
+ 'run_command' method in 'distutils.dist', and *its* caller will be
+ the 'run_commands' method. If called any other way, the
+ immediate caller *might* be 'run_command', but it won't have been
+ called by 'run_commands'. Return True in that case or if a call stack
+ is unavailable. Return False otherwise.
+ """
+ if run_frame is None:
+ msg = "Call stack not available. bdist_* commands may fail."
+ warnings.warn(msg)
+ if platform.python_implementation() == 'IronPython':
+ msg = "For best results, pass -X:Frames to enable call stack."
+ warnings.warn(msg)
+ return True
+ res = inspect.getouterframes(run_frame)[2]
+ caller, = res[:1]
+ info = inspect.getframeinfo(caller)
+ caller_module = caller.f_globals.get('__name__', '')
+ return (
+ caller_module == 'distutils.dist'
+ and info.function == 'run_commands'
+ )
+
+ def do_egg_install(self):
+
+ easy_install = self.distribution.get_command_class('easy_install')
+
+ cmd = easy_install(
+ self.distribution, args="x", root=self.root, record=self.record,
+ )
+ cmd.ensure_finalized() # finalize before bdist_egg munges install cmd
+ cmd.always_copy_from = '.' # make sure local-dir eggs get installed
+
+ # pick up setup-dir .egg files only: no .egg-info
+ cmd.package_index.scan(glob.glob('*.egg'))
+
+ self.run_command('bdist_egg')
+ args = [self.distribution.get_command_obj('bdist_egg').egg_output]
+
+ if setuptools.bootstrap_install_from:
+ # Bootstrap self-installation of setuptools
+ args.insert(0, setuptools.bootstrap_install_from)
+
+ cmd.args = args
cmd.run(show_deprecation=False)
- setuptools.bootstrap_install_from = None
-
-
-# XXX Python 3.1 doesn't see _nc if this is inside the class
-install.sub_commands = (
- [cmd for cmd in orig.install.sub_commands if cmd[0] not in install._nc] +
- install.new_commands
-)
+ setuptools.bootstrap_install_from = None
+
+
+# XXX Python 3.1 doesn't see _nc if this is inside the class
+install.sub_commands = (
+ [cmd for cmd in orig.install.sub_commands if cmd[0] not in install._nc] +
+ install.new_commands
+)
diff --git a/contrib/python/setuptools/py3/setuptools/command/install_egg_info.py b/contrib/python/setuptools/py3/setuptools/command/install_egg_info.py
index 10bdb832a9..edc4718b68 100644
--- a/contrib/python/setuptools/py3/setuptools/command/install_egg_info.py
+++ b/contrib/python/setuptools/py3/setuptools/command/install_egg_info.py
@@ -1,62 +1,62 @@
-from distutils import log, dir_util
-import os
-
-from setuptools import Command
+from distutils import log, dir_util
+import os
+
+from setuptools import Command
from setuptools import namespaces
-from setuptools.archive_util import unpack_archive
-import pkg_resources
-
-
+from setuptools.archive_util import unpack_archive
+import pkg_resources
+
+
class install_egg_info(namespaces.Installer, Command):
- """Install an .egg-info directory for the package"""
-
- description = "Install an .egg-info directory for the package"
-
- user_options = [
- ('install-dir=', 'd', "directory to install to"),
- ]
-
- def initialize_options(self):
- self.install_dir = None
-
- def finalize_options(self):
- self.set_undefined_options('install_lib',
- ('install_dir', 'install_dir'))
- ei_cmd = self.get_finalized_command("egg_info")
- basename = pkg_resources.Distribution(
- None, None, ei_cmd.egg_name, ei_cmd.egg_version
- ).egg_name() + '.egg-info'
- self.source = ei_cmd.egg_info
- self.target = os.path.join(self.install_dir, basename)
+ """Install an .egg-info directory for the package"""
+
+ description = "Install an .egg-info directory for the package"
+
+ user_options = [
+ ('install-dir=', 'd', "directory to install to"),
+ ]
+
+ def initialize_options(self):
+ self.install_dir = None
+
+ def finalize_options(self):
+ self.set_undefined_options('install_lib',
+ ('install_dir', 'install_dir'))
+ ei_cmd = self.get_finalized_command("egg_info")
+ basename = pkg_resources.Distribution(
+ None, None, ei_cmd.egg_name, ei_cmd.egg_version
+ ).egg_name() + '.egg-info'
+ self.source = ei_cmd.egg_info
+ self.target = os.path.join(self.install_dir, basename)
self.outputs = []
-
- def run(self):
- self.run_command('egg_info')
- if os.path.isdir(self.target) and not os.path.islink(self.target):
- dir_util.remove_tree(self.target, dry_run=self.dry_run)
- elif os.path.exists(self.target):
- self.execute(os.unlink, (self.target,), "Removing " + self.target)
- if not self.dry_run:
- pkg_resources.ensure_directory(self.target)
- self.execute(
- self.copytree, (), "Copying %s to %s" % (self.source, self.target)
- )
- self.install_namespaces()
-
- def get_outputs(self):
- return self.outputs
-
- def copytree(self):
- # Copy the .egg-info tree to site-packages
- def skimmer(src, dst):
- # filter out source-control directories; note that 'src' is always
- # a '/'-separated path, regardless of platform. 'dst' is a
- # platform-specific path.
- for skip in '.svn/', 'CVS/':
- if src.startswith(skip) or '/' + skip in src:
- return None
- self.outputs.append(dst)
- log.debug("Copying %s to %s", src, dst)
- return dst
-
- unpack_archive(self.source, self.target, skimmer)
+
+ def run(self):
+ self.run_command('egg_info')
+ if os.path.isdir(self.target) and not os.path.islink(self.target):
+ dir_util.remove_tree(self.target, dry_run=self.dry_run)
+ elif os.path.exists(self.target):
+ self.execute(os.unlink, (self.target,), "Removing " + self.target)
+ if not self.dry_run:
+ pkg_resources.ensure_directory(self.target)
+ self.execute(
+ self.copytree, (), "Copying %s to %s" % (self.source, self.target)
+ )
+ self.install_namespaces()
+
+ def get_outputs(self):
+ return self.outputs
+
+ def copytree(self):
+ # Copy the .egg-info tree to site-packages
+ def skimmer(src, dst):
+ # filter out source-control directories; note that 'src' is always
+ # a '/'-separated path, regardless of platform. 'dst' is a
+ # platform-specific path.
+ for skip in '.svn/', 'CVS/':
+ if src.startswith(skip) or '/' + skip in src:
+ return None
+ self.outputs.append(dst)
+ log.debug("Copying %s to %s", src, dst)
+ return dst
+
+ unpack_archive(self.source, self.target, skimmer)
diff --git a/contrib/python/setuptools/py3/setuptools/command/install_lib.py b/contrib/python/setuptools/py3/setuptools/command/install_lib.py
index 6b0cfa46d3..2e9d8757a5 100644
--- a/contrib/python/setuptools/py3/setuptools/command/install_lib.py
+++ b/contrib/python/setuptools/py3/setuptools/command/install_lib.py
@@ -1,122 +1,122 @@
-import os
+import os
import sys
-from itertools import product, starmap
-import distutils.command.install_lib as orig
-
-
-class install_lib(orig.install_lib):
- """Don't add compiled flags to filenames of non-Python files"""
-
- def run(self):
- self.build()
- outfiles = self.install()
- if outfiles is not None:
- # always compile, in case we have any extension stubs to deal with
- self.byte_compile(outfiles)
-
- def get_exclusions(self):
- """
- Return a collections.Sized collections.Container of paths to be
- excluded for single_version_externally_managed installations.
- """
- all_packages = (
- pkg
- for ns_pkg in self._get_SVEM_NSPs()
- for pkg in self._all_packages(ns_pkg)
- )
-
- excl_specs = product(all_packages, self._gen_exclusion_paths())
- return set(starmap(self._exclude_pkg_path, excl_specs))
-
- def _exclude_pkg_path(self, pkg, exclusion_path):
- """
- Given a package name and exclusion path within that package,
- compute the full exclusion path.
- """
- parts = pkg.split('.') + [exclusion_path]
- return os.path.join(self.install_dir, *parts)
-
- @staticmethod
- def _all_packages(pkg_name):
- """
- >>> list(install_lib._all_packages('foo.bar.baz'))
- ['foo.bar.baz', 'foo.bar', 'foo']
- """
- while pkg_name:
- yield pkg_name
- pkg_name, sep, child = pkg_name.rpartition('.')
-
- def _get_SVEM_NSPs(self):
- """
- Get namespace packages (list) but only for
- single_version_externally_managed installations and empty otherwise.
- """
- # TODO: is it necessary to short-circuit here? i.e. what's the cost
- # if get_finalized_command is called even when namespace_packages is
- # False?
- if not self.distribution.namespace_packages:
- return []
-
- install_cmd = self.get_finalized_command('install')
- svem = install_cmd.single_version_externally_managed
-
- return self.distribution.namespace_packages if svem else []
-
- @staticmethod
- def _gen_exclusion_paths():
- """
- Generate file paths to be excluded for namespace packages (bytecode
- cache files).
- """
- # always exclude the package module itself
- yield '__init__.py'
-
- yield '__init__.pyc'
- yield '__init__.pyo'
-
+from itertools import product, starmap
+import distutils.command.install_lib as orig
+
+
+class install_lib(orig.install_lib):
+ """Don't add compiled flags to filenames of non-Python files"""
+
+ def run(self):
+ self.build()
+ outfiles = self.install()
+ if outfiles is not None:
+ # always compile, in case we have any extension stubs to deal with
+ self.byte_compile(outfiles)
+
+ def get_exclusions(self):
+ """
+ Return a collections.Sized collections.Container of paths to be
+ excluded for single_version_externally_managed installations.
+ """
+ all_packages = (
+ pkg
+ for ns_pkg in self._get_SVEM_NSPs()
+ for pkg in self._all_packages(ns_pkg)
+ )
+
+ excl_specs = product(all_packages, self._gen_exclusion_paths())
+ return set(starmap(self._exclude_pkg_path, excl_specs))
+
+ def _exclude_pkg_path(self, pkg, exclusion_path):
+ """
+ Given a package name and exclusion path within that package,
+ compute the full exclusion path.
+ """
+ parts = pkg.split('.') + [exclusion_path]
+ return os.path.join(self.install_dir, *parts)
+
+ @staticmethod
+ def _all_packages(pkg_name):
+ """
+ >>> list(install_lib._all_packages('foo.bar.baz'))
+ ['foo.bar.baz', 'foo.bar', 'foo']
+ """
+ while pkg_name:
+ yield pkg_name
+ pkg_name, sep, child = pkg_name.rpartition('.')
+
+ def _get_SVEM_NSPs(self):
+ """
+ Get namespace packages (list) but only for
+ single_version_externally_managed installations and empty otherwise.
+ """
+ # TODO: is it necessary to short-circuit here? i.e. what's the cost
+ # if get_finalized_command is called even when namespace_packages is
+ # False?
+ if not self.distribution.namespace_packages:
+ return []
+
+ install_cmd = self.get_finalized_command('install')
+ svem = install_cmd.single_version_externally_managed
+
+ return self.distribution.namespace_packages if svem else []
+
+ @staticmethod
+ def _gen_exclusion_paths():
+ """
+ Generate file paths to be excluded for namespace packages (bytecode
+ cache files).
+ """
+ # always exclude the package module itself
+ yield '__init__.py'
+
+ yield '__init__.pyc'
+ yield '__init__.pyo'
+
if not hasattr(sys, 'implementation'):
- return
-
+ return
+
base = os.path.join(
'__pycache__', '__init__.' + sys.implementation.cache_tag)
- yield base + '.pyc'
- yield base + '.pyo'
- yield base + '.opt-1.pyc'
- yield base + '.opt-2.pyc'
-
- def copy_tree(
- self, infile, outfile,
- preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1
- ):
- assert preserve_mode and preserve_times and not preserve_symlinks
- exclude = self.get_exclusions()
-
- if not exclude:
- return orig.install_lib.copy_tree(self, infile, outfile)
-
- # Exclude namespace package __init__.py* files from the output
-
- from setuptools.archive_util import unpack_directory
- from distutils import log
-
- outfiles = []
-
- def pf(src, dst):
- if dst in exclude:
- log.warn("Skipping installation of %s (namespace package)",
- dst)
- return False
-
- log.info("copying %s -> %s", src, os.path.dirname(dst))
- outfiles.append(dst)
- return dst
-
- unpack_directory(infile, outfile, pf)
- return outfiles
-
- def get_outputs(self):
- outputs = orig.install_lib.get_outputs(self)
- exclude = self.get_exclusions()
- if exclude:
- return [f for f in outputs if f not in exclude]
- return outputs
+ yield base + '.pyc'
+ yield base + '.pyo'
+ yield base + '.opt-1.pyc'
+ yield base + '.opt-2.pyc'
+
+ def copy_tree(
+ self, infile, outfile,
+ preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1
+ ):
+ assert preserve_mode and preserve_times and not preserve_symlinks
+ exclude = self.get_exclusions()
+
+ if not exclude:
+ return orig.install_lib.copy_tree(self, infile, outfile)
+
+ # Exclude namespace package __init__.py* files from the output
+
+ from setuptools.archive_util import unpack_directory
+ from distutils import log
+
+ outfiles = []
+
+ def pf(src, dst):
+ if dst in exclude:
+ log.warn("Skipping installation of %s (namespace package)",
+ dst)
+ return False
+
+ log.info("copying %s -> %s", src, os.path.dirname(dst))
+ outfiles.append(dst)
+ return dst
+
+ unpack_directory(infile, outfile, pf)
+ return outfiles
+
+ def get_outputs(self):
+ outputs = orig.install_lib.get_outputs(self)
+ exclude = self.get_exclusions()
+ if exclude:
+ return [f for f in outputs if f not in exclude]
+ return outputs
diff --git a/contrib/python/setuptools/py3/setuptools/command/install_scripts.py b/contrib/python/setuptools/py3/setuptools/command/install_scripts.py
index 5f83b5e019..9cd8eb0627 100644
--- a/contrib/python/setuptools/py3/setuptools/command/install_scripts.py
+++ b/contrib/python/setuptools/py3/setuptools/command/install_scripts.py
@@ -1,69 +1,69 @@
-from distutils import log
-import distutils.command.install_scripts as orig
+from distutils import log
+import distutils.command.install_scripts as orig
from distutils.errors import DistutilsModuleError
-import os
+import os
import sys
-
-from pkg_resources import Distribution, PathMetadata, ensure_directory
-
-
-class install_scripts(orig.install_scripts):
- """Do normal script install, plus any egg_info wrapper scripts"""
-
- def initialize_options(self):
- orig.install_scripts.initialize_options(self)
- self.no_ep = False
-
- def run(self):
- import setuptools.command.easy_install as ei
-
- self.run_command("egg_info")
- if self.distribution.scripts:
- orig.install_scripts.run(self) # run first to set up self.outfiles
- else:
- self.outfiles = []
- if self.no_ep:
- # don't install entry point scripts into .egg file!
- return
-
- ei_cmd = self.get_finalized_command("egg_info")
- dist = Distribution(
- ei_cmd.egg_base, PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),
- ei_cmd.egg_name, ei_cmd.egg_version,
- )
- bs_cmd = self.get_finalized_command('build_scripts')
- exec_param = getattr(bs_cmd, 'executable', None)
+
+from pkg_resources import Distribution, PathMetadata, ensure_directory
+
+
+class install_scripts(orig.install_scripts):
+ """Do normal script install, plus any egg_info wrapper scripts"""
+
+ def initialize_options(self):
+ orig.install_scripts.initialize_options(self)
+ self.no_ep = False
+
+ def run(self):
+ import setuptools.command.easy_install as ei
+
+ self.run_command("egg_info")
+ if self.distribution.scripts:
+ orig.install_scripts.run(self) # run first to set up self.outfiles
+ else:
+ self.outfiles = []
+ if self.no_ep:
+ # don't install entry point scripts into .egg file!
+ return
+
+ ei_cmd = self.get_finalized_command("egg_info")
+ dist = Distribution(
+ ei_cmd.egg_base, PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),
+ ei_cmd.egg_name, ei_cmd.egg_version,
+ )
+ bs_cmd = self.get_finalized_command('build_scripts')
+ exec_param = getattr(bs_cmd, 'executable', None)
try:
bw_cmd = self.get_finalized_command("bdist_wininst")
is_wininst = getattr(bw_cmd, '_is_running', False)
except (ImportError, DistutilsModuleError):
is_wininst = False
- writer = ei.ScriptWriter
- if is_wininst:
- exec_param = "python.exe"
- writer = ei.WindowsScriptWriter
+ writer = ei.ScriptWriter
+ if is_wininst:
+ exec_param = "python.exe"
+ writer = ei.WindowsScriptWriter
if exec_param == sys.executable:
# In case the path to the Python executable contains a space, wrap
# it so it's not split up.
exec_param = [exec_param]
- # resolve the writer to the environment
- writer = writer.best()
- cmd = writer.command_spec_class.best().from_param(exec_param)
- for args in writer.get_args(dist, cmd.as_header()):
- self.write_script(*args)
-
- def write_script(self, script_name, contents, mode="t", *ignored):
- """Write an executable file to the scripts directory"""
- from setuptools.command.easy_install import chmod, current_umask
-
- log.info("Installing %s script to %s", script_name, self.install_dir)
- target = os.path.join(self.install_dir, script_name)
- self.outfiles.append(target)
-
- mask = current_umask()
- if not self.dry_run:
- ensure_directory(target)
- f = open(target, "w" + mode)
- f.write(contents)
- f.close()
- chmod(target, 0o777 - mask)
+ # resolve the writer to the environment
+ writer = writer.best()
+ cmd = writer.command_spec_class.best().from_param(exec_param)
+ for args in writer.get_args(dist, cmd.as_header()):
+ self.write_script(*args)
+
+ def write_script(self, script_name, contents, mode="t", *ignored):
+ """Write an executable file to the scripts directory"""
+ from setuptools.command.easy_install import chmod, current_umask
+
+ log.info("Installing %s script to %s", script_name, self.install_dir)
+ target = os.path.join(self.install_dir, script_name)
+ self.outfiles.append(target)
+
+ mask = current_umask()
+ if not self.dry_run:
+ ensure_directory(target)
+ f = open(target, "w" + mode)
+ f.write(contents)
+ f.close()
+ chmod(target, 0o777 - mask)
diff --git a/contrib/python/setuptools/py3/setuptools/command/register.py b/contrib/python/setuptools/py3/setuptools/command/register.py
index dbe5e619f7..b8266b9a60 100644
--- a/contrib/python/setuptools/py3/setuptools/command/register.py
+++ b/contrib/python/setuptools/py3/setuptools/command/register.py
@@ -1,13 +1,13 @@
from distutils import log
-import distutils.command.register as orig
-
+import distutils.command.register as orig
+
from setuptools.errors import RemovedCommandError
-
-class register(orig.register):
+
+class register(orig.register):
"""Formerly used to register packages on PyPI."""
-
- def run(self):
+
+ def run(self):
msg = (
"The register command has been removed, use twine to upload "
+ "instead (https://pypi.org/p/twine)"
diff --git a/contrib/python/setuptools/py3/setuptools/command/rotate.py b/contrib/python/setuptools/py3/setuptools/command/rotate.py
index dd51ae188c..74795ba922 100644
--- a/contrib/python/setuptools/py3/setuptools/command/rotate.py
+++ b/contrib/python/setuptools/py3/setuptools/command/rotate.py
@@ -1,63 +1,63 @@
-from distutils.util import convert_path
-from distutils import log
-from distutils.errors import DistutilsOptionError
-import os
+from distutils.util import convert_path
+from distutils import log
+from distutils.errors import DistutilsOptionError
+import os
import shutil
-
-from setuptools import Command
-
-
-class rotate(Command):
- """Delete older distributions"""
-
- description = "delete older distributions, keeping N newest files"
- user_options = [
- ('match=', 'm', "patterns to match (required)"),
- ('dist-dir=', 'd', "directory where the distributions are"),
- ('keep=', 'k', "number of matching distributions to keep"),
- ]
-
- boolean_options = []
-
- def initialize_options(self):
- self.match = None
- self.dist_dir = None
- self.keep = None
-
- def finalize_options(self):
- if self.match is None:
- raise DistutilsOptionError(
- "Must specify one or more (comma-separated) match patterns "
- "(e.g. '.zip' or '.egg')"
- )
- if self.keep is None:
- raise DistutilsOptionError("Must specify number of files to keep")
- try:
- self.keep = int(self.keep)
+
+from setuptools import Command
+
+
+class rotate(Command):
+ """Delete older distributions"""
+
+ description = "delete older distributions, keeping N newest files"
+ user_options = [
+ ('match=', 'm', "patterns to match (required)"),
+ ('dist-dir=', 'd', "directory where the distributions are"),
+ ('keep=', 'k', "number of matching distributions to keep"),
+ ]
+
+ boolean_options = []
+
+ def initialize_options(self):
+ self.match = None
+ self.dist_dir = None
+ self.keep = None
+
+ def finalize_options(self):
+ if self.match is None:
+ raise DistutilsOptionError(
+ "Must specify one or more (comma-separated) match patterns "
+ "(e.g. '.zip' or '.egg')"
+ )
+ if self.keep is None:
+ raise DistutilsOptionError("Must specify number of files to keep")
+ try:
+ self.keep = int(self.keep)
except ValueError as e:
raise DistutilsOptionError("--keep must be an integer") from e
if isinstance(self.match, str):
- self.match = [
- convert_path(p.strip()) for p in self.match.split(',')
- ]
- self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
-
- def run(self):
- self.run_command("egg_info")
- from glob import glob
-
- for pattern in self.match:
- pattern = self.distribution.get_name() + '*' + pattern
- files = glob(os.path.join(self.dist_dir, pattern))
- files = [(os.path.getmtime(f), f) for f in files]
- files.sort()
- files.reverse()
-
- log.info("%d file(s) matching %s", len(files), pattern)
- files = files[self.keep:]
- for (t, f) in files:
- log.info("Deleting %s", f)
- if not self.dry_run:
+ self.match = [
+ convert_path(p.strip()) for p in self.match.split(',')
+ ]
+ self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
+
+ def run(self):
+ self.run_command("egg_info")
+ from glob import glob
+
+ for pattern in self.match:
+ pattern = self.distribution.get_name() + '*' + pattern
+ files = glob(os.path.join(self.dist_dir, pattern))
+ files = [(os.path.getmtime(f), f) for f in files]
+ files.sort()
+ files.reverse()
+
+ log.info("%d file(s) matching %s", len(files), pattern)
+ files = files[self.keep:]
+ for (t, f) in files:
+ log.info("Deleting %s", f)
+ if not self.dry_run:
if os.path.isdir(f):
shutil.rmtree(f)
else:
diff --git a/contrib/python/setuptools/py3/setuptools/command/saveopts.py b/contrib/python/setuptools/py3/setuptools/command/saveopts.py
index 3ce03df53c..611cec5528 100644
--- a/contrib/python/setuptools/py3/setuptools/command/saveopts.py
+++ b/contrib/python/setuptools/py3/setuptools/command/saveopts.py
@@ -1,22 +1,22 @@
-from setuptools.command.setopt import edit_config, option_base
-
-
-class saveopts(option_base):
- """Save command-line options to a file"""
-
- description = "save supplied options to setup.cfg or other config file"
-
- def run(self):
- dist = self.distribution
- settings = {}
-
- for cmd in dist.command_options:
-
- if cmd == 'saveopts':
- continue # don't save our own options!
-
- for opt, (src, val) in dist.get_option_dict(cmd).items():
- if src == "command line":
- settings.setdefault(cmd, {})[opt] = val
-
- edit_config(self.filename, settings, self.dry_run)
+from setuptools.command.setopt import edit_config, option_base
+
+
+class saveopts(option_base):
+ """Save command-line options to a file"""
+
+ description = "save supplied options to setup.cfg or other config file"
+
+ def run(self):
+ dist = self.distribution
+ settings = {}
+
+ for cmd in dist.command_options:
+
+ if cmd == 'saveopts':
+ continue # don't save our own options!
+
+ for opt, (src, val) in dist.get_option_dict(cmd).items():
+ if src == "command line":
+ settings.setdefault(cmd, {})[opt] = val
+
+ edit_config(self.filename, settings, self.dry_run)
diff --git a/contrib/python/setuptools/py3/setuptools/command/sdist.py b/contrib/python/setuptools/py3/setuptools/command/sdist.py
index 50201e6714..0285b690fc 100644
--- a/contrib/python/setuptools/py3/setuptools/command/sdist.py
+++ b/contrib/python/setuptools/py3/setuptools/command/sdist.py
@@ -1,66 +1,66 @@
-from distutils import log
-import distutils.command.sdist as orig
-import os
-import sys
-import io
+from distutils import log
+import distutils.command.sdist as orig
+import os
+import sys
+import io
import contextlib
-
+
from .py36compat import sdist_add_defaults
-
-import pkg_resources
-
-_default_revctrl = list
-
-
-def walk_revctrl(dirname=''):
- """Find all files under revision control"""
- for ep in pkg_resources.iter_entry_points('setuptools.file_finders'):
- for item in ep.load()(dirname):
- yield item
-
-
+
+import pkg_resources
+
+_default_revctrl = list
+
+
+def walk_revctrl(dirname=''):
+ """Find all files under revision control"""
+ for ep in pkg_resources.iter_entry_points('setuptools.file_finders'):
+ for item in ep.load()(dirname):
+ yield item
+
+
class sdist(sdist_add_defaults, orig.sdist):
- """Smart sdist that finds anything supported by revision control"""
-
- user_options = [
- ('formats=', None,
- "formats for source distribution (comma-separated list)"),
- ('keep-temp', 'k',
- "keep the distribution tree around after creating " +
- "archive file(s)"),
- ('dist-dir=', 'd',
- "directory to put the source distribution archive(s) in "
- "[default: dist]"),
+ """Smart sdist that finds anything supported by revision control"""
+
+ user_options = [
+ ('formats=', None,
+ "formats for source distribution (comma-separated list)"),
+ ('keep-temp', 'k',
+ "keep the distribution tree around after creating " +
+ "archive file(s)"),
+ ('dist-dir=', 'd',
+ "directory to put the source distribution archive(s) in "
+ "[default: dist]"),
('owner=', 'u',
"Owner name used when creating a tar file [default: current user]"),
('group=', 'g',
"Group name used when creating a tar file [default: current group]"),
- ]
-
- negative_opt = {}
-
+ ]
+
+ negative_opt = {}
+
README_EXTENSIONS = ['', '.rst', '.txt', '.md']
READMES = tuple('README{0}'.format(ext) for ext in README_EXTENSIONS)
- def run(self):
- self.run_command('egg_info')
- ei_cmd = self.get_finalized_command('egg_info')
- self.filelist = ei_cmd.filelist
- self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt'))
- self.check_readme()
-
- # Run sub commands
- for cmd_name in self.get_sub_commands():
- self.run_command(cmd_name)
-
- self.make_distribution()
-
- dist_files = getattr(self.distribution, 'dist_files', [])
- for file in self.archive_files:
- data = ('sdist', '', file)
- if data not in dist_files:
- dist_files.append(data)
-
+ def run(self):
+ self.run_command('egg_info')
+ ei_cmd = self.get_finalized_command('egg_info')
+ self.filelist = ei_cmd.filelist
+ self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt'))
+ self.check_readme()
+
+ # Run sub commands
+ for cmd_name in self.get_sub_commands():
+ self.run_command(cmd_name)
+
+ self.make_distribution()
+
+ dist_files = getattr(self.distribution, 'dist_files', [])
+ for file in self.archive_files:
+ data = ('sdist', '', file)
+ if data not in dist_files:
+ dist_files.append(data)
+
def initialize_options(self):
orig.sdist.initialize_options(self)
@@ -107,11 +107,11 @@ class sdist(sdist_add_defaults, orig.sdist):
def _add_defaults_python(self):
"""getting python files"""
- if self.distribution.has_pure_modules():
- build_py = self.get_finalized_command('build_py')
- self.filelist.extend(build_py.get_source_files())
+ if self.distribution.has_pure_modules():
+ build_py = self.get_finalized_command('build_py')
+ self.filelist.extend(build_py.get_source_files())
self._add_data_files(self._safe_data_files(build_py))
-
+
def _safe_data_files(self, build_py):
"""
Since the ``sdist`` class is also used to compute the MANIFEST
@@ -140,57 +140,57 @@ class sdist(sdist_add_defaults, orig.sdist):
super()._add_defaults_data_files()
except TypeError:
log.warn("data_files contains unexpected objects")
-
- def check_readme(self):
+
+ def check_readme(self):
for f in self.READMES:
- if os.path.exists(f):
- return
- else:
- self.warn(
- "standard file not found: should have one of " +
+ if os.path.exists(f):
+ return
+ else:
+ self.warn(
+ "standard file not found: should have one of " +
', '.join(self.READMES)
- )
-
- def make_release_tree(self, base_dir, files):
- orig.sdist.make_release_tree(self, base_dir, files)
-
- # Save any egg_info command line options used to create this sdist
- dest = os.path.join(base_dir, 'setup.cfg')
- if hasattr(os, 'link') and os.path.exists(dest):
- # unlink and re-copy, since it might be hard-linked, and
- # we don't want to change the source version
- os.unlink(dest)
- self.copy_file('setup.cfg', dest)
-
- self.get_finalized_command('egg_info').save_version_info(dest)
-
- def _manifest_is_not_generated(self):
- # check for special comment used in 2.7.1 and higher
- if not os.path.isfile(self.manifest):
- return False
-
- with io.open(self.manifest, 'rb') as fp:
- first_line = fp.readline()
- return (first_line !=
- '# file GENERATED by distutils, do NOT edit\n'.encode())
-
- def read_manifest(self):
- """Read the manifest file (named by 'self.manifest') and use it to
- fill in 'self.filelist', the list of files to include in the source
- distribution.
- """
- log.info("reading manifest file '%s'", self.manifest)
+ )
+
+ def make_release_tree(self, base_dir, files):
+ orig.sdist.make_release_tree(self, base_dir, files)
+
+ # Save any egg_info command line options used to create this sdist
+ dest = os.path.join(base_dir, 'setup.cfg')
+ if hasattr(os, 'link') and os.path.exists(dest):
+ # unlink and re-copy, since it might be hard-linked, and
+ # we don't want to change the source version
+ os.unlink(dest)
+ self.copy_file('setup.cfg', dest)
+
+ self.get_finalized_command('egg_info').save_version_info(dest)
+
+ def _manifest_is_not_generated(self):
+ # check for special comment used in 2.7.1 and higher
+ if not os.path.isfile(self.manifest):
+ return False
+
+ with io.open(self.manifest, 'rb') as fp:
+ first_line = fp.readline()
+ return (first_line !=
+ '# file GENERATED by distutils, do NOT edit\n'.encode())
+
+ def read_manifest(self):
+ """Read the manifest file (named by 'self.manifest') and use it to
+ fill in 'self.filelist', the list of files to include in the source
+ distribution.
+ """
+ log.info("reading manifest file '%s'", self.manifest)
manifest = open(self.manifest, 'rb')
- for line in manifest:
- # The manifest must contain UTF-8. See #303.
+ for line in manifest:
+ # The manifest must contain UTF-8. See #303.
try:
line = line.decode('UTF-8')
except UnicodeDecodeError:
log.warn("%r not UTF-8 decodable -- skipping" % line)
continue
- # ignore comments and blank lines
- line = line.strip()
- if line.startswith('#') or not line:
- continue
- self.filelist.append(line)
- manifest.close()
+ # ignore comments and blank lines
+ line = line.strip()
+ if line.startswith('#') or not line:
+ continue
+ self.filelist.append(line)
+ manifest.close()
diff --git a/contrib/python/setuptools/py3/setuptools/command/setopt.py b/contrib/python/setuptools/py3/setuptools/command/setopt.py
index 7750080f25..6358c0451b 100644
--- a/contrib/python/setuptools/py3/setuptools/command/setopt.py
+++ b/contrib/python/setuptools/py3/setuptools/command/setopt.py
@@ -1,149 +1,149 @@
-from distutils.util import convert_path
-from distutils import log
-from distutils.errors import DistutilsOptionError
-import distutils
-import os
+from distutils.util import convert_path
+from distutils import log
+from distutils.errors import DistutilsOptionError
+import distutils
+import os
import configparser
-
-from setuptools import Command
-
-__all__ = ['config_file', 'edit_config', 'option_base', 'setopt']
-
-
-def config_file(kind="local"):
- """Get the filename of the distutils, local, global, or per-user config
-
- `kind` must be one of "local", "global", or "user"
- """
- if kind == 'local':
- return 'setup.cfg'
- if kind == 'global':
- return os.path.join(
- os.path.dirname(distutils.__file__), 'distutils.cfg'
- )
- if kind == 'user':
- dot = os.name == 'posix' and '.' or ''
- return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot))
- raise ValueError(
- "config_file() type must be 'local', 'global', or 'user'", kind
- )
-
-
-def edit_config(filename, settings, dry_run=False):
- """Edit a configuration file to include `settings`
-
- `settings` is a dictionary of dictionaries or ``None`` values, keyed by
- command/section name. A ``None`` value means to delete the entire section,
- while a dictionary lists settings to be changed or deleted in that section.
- A setting of ``None`` means to delete that setting.
- """
- log.debug("Reading configuration from %s", filename)
- opts = configparser.RawConfigParser()
+
+from setuptools import Command
+
+__all__ = ['config_file', 'edit_config', 'option_base', 'setopt']
+
+
+def config_file(kind="local"):
+ """Get the filename of the distutils, local, global, or per-user config
+
+ `kind` must be one of "local", "global", or "user"
+ """
+ if kind == 'local':
+ return 'setup.cfg'
+ if kind == 'global':
+ return os.path.join(
+ os.path.dirname(distutils.__file__), 'distutils.cfg'
+ )
+ if kind == 'user':
+ dot = os.name == 'posix' and '.' or ''
+ return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot))
+ raise ValueError(
+ "config_file() type must be 'local', 'global', or 'user'", kind
+ )
+
+
+def edit_config(filename, settings, dry_run=False):
+ """Edit a configuration file to include `settings`
+
+ `settings` is a dictionary of dictionaries or ``None`` values, keyed by
+ command/section name. A ``None`` value means to delete the entire section,
+ while a dictionary lists settings to be changed or deleted in that section.
+ A setting of ``None`` means to delete that setting.
+ """
+ log.debug("Reading configuration from %s", filename)
+ opts = configparser.RawConfigParser()
opts.optionxform = lambda x: x
- opts.read([filename])
- for section, options in settings.items():
- if options is None:
- log.info("Deleting section [%s] from %s", section, filename)
- opts.remove_section(section)
- else:
- if not opts.has_section(section):
- log.debug("Adding new section [%s] to %s", section, filename)
- opts.add_section(section)
- for option, value in options.items():
- if value is None:
- log.debug(
- "Deleting %s.%s from %s",
- section, option, filename
- )
- opts.remove_option(section, option)
- if not opts.options(section):
- log.info("Deleting empty [%s] section from %s",
- section, filename)
- opts.remove_section(section)
- else:
- log.debug(
- "Setting %s.%s to %r in %s",
- section, option, value, filename
- )
- opts.set(section, option, value)
-
- log.info("Writing %s", filename)
- if not dry_run:
- with open(filename, 'w') as f:
- opts.write(f)
-
-
-class option_base(Command):
- """Abstract base class for commands that mess with config files"""
-
- user_options = [
- ('global-config', 'g',
- "save options to the site-wide distutils.cfg file"),
- ('user-config', 'u',
- "save options to the current user's pydistutils.cfg file"),
- ('filename=', 'f',
- "configuration file to use (default=setup.cfg)"),
- ]
-
- boolean_options = [
- 'global-config', 'user-config',
- ]
-
- def initialize_options(self):
- self.global_config = None
- self.user_config = None
- self.filename = None
-
- def finalize_options(self):
- filenames = []
- if self.global_config:
- filenames.append(config_file('global'))
- if self.user_config:
- filenames.append(config_file('user'))
- if self.filename is not None:
- filenames.append(self.filename)
- if not filenames:
- filenames.append(config_file('local'))
- if len(filenames) > 1:
- raise DistutilsOptionError(
- "Must specify only one configuration file option",
- filenames
- )
- self.filename, = filenames
-
-
-class setopt(option_base):
- """Save command-line options to a file"""
-
- description = "set an option in setup.cfg or another config file"
-
- user_options = [
- ('command=', 'c', 'command to set an option for'),
- ('option=', 'o', 'option to set'),
- ('set-value=', 's', 'value of the option'),
- ('remove', 'r', 'remove (unset) the value'),
- ] + option_base.user_options
-
- boolean_options = option_base.boolean_options + ['remove']
-
- def initialize_options(self):
- option_base.initialize_options(self)
- self.command = None
- self.option = None
- self.set_value = None
- self.remove = None
-
- def finalize_options(self):
- option_base.finalize_options(self)
- if self.command is None or self.option is None:
- raise DistutilsOptionError("Must specify --command *and* --option")
- if self.set_value is None and not self.remove:
- raise DistutilsOptionError("Must specify --set-value or --remove")
-
- def run(self):
- edit_config(
- self.filename, {
- self.command: {self.option.replace('-', '_'): self.set_value}
- },
- self.dry_run
- )
+ opts.read([filename])
+ for section, options in settings.items():
+ if options is None:
+ log.info("Deleting section [%s] from %s", section, filename)
+ opts.remove_section(section)
+ else:
+ if not opts.has_section(section):
+ log.debug("Adding new section [%s] to %s", section, filename)
+ opts.add_section(section)
+ for option, value in options.items():
+ if value is None:
+ log.debug(
+ "Deleting %s.%s from %s",
+ section, option, filename
+ )
+ opts.remove_option(section, option)
+ if not opts.options(section):
+ log.info("Deleting empty [%s] section from %s",
+ section, filename)
+ opts.remove_section(section)
+ else:
+ log.debug(
+ "Setting %s.%s to %r in %s",
+ section, option, value, filename
+ )
+ opts.set(section, option, value)
+
+ log.info("Writing %s", filename)
+ if not dry_run:
+ with open(filename, 'w') as f:
+ opts.write(f)
+
+
+class option_base(Command):
+ """Abstract base class for commands that mess with config files"""
+
+ user_options = [
+ ('global-config', 'g',
+ "save options to the site-wide distutils.cfg file"),
+ ('user-config', 'u',
+ "save options to the current user's pydistutils.cfg file"),
+ ('filename=', 'f',
+ "configuration file to use (default=setup.cfg)"),
+ ]
+
+ boolean_options = [
+ 'global-config', 'user-config',
+ ]
+
+ def initialize_options(self):
+ self.global_config = None
+ self.user_config = None
+ self.filename = None
+
+ def finalize_options(self):
+ filenames = []
+ if self.global_config:
+ filenames.append(config_file('global'))
+ if self.user_config:
+ filenames.append(config_file('user'))
+ if self.filename is not None:
+ filenames.append(self.filename)
+ if not filenames:
+ filenames.append(config_file('local'))
+ if len(filenames) > 1:
+ raise DistutilsOptionError(
+ "Must specify only one configuration file option",
+ filenames
+ )
+ self.filename, = filenames
+
+
+class setopt(option_base):
+ """Save command-line options to a file"""
+
+ description = "set an option in setup.cfg or another config file"
+
+ user_options = [
+ ('command=', 'c', 'command to set an option for'),
+ ('option=', 'o', 'option to set'),
+ ('set-value=', 's', 'value of the option'),
+ ('remove', 'r', 'remove (unset) the value'),
+ ] + option_base.user_options
+
+ boolean_options = option_base.boolean_options + ['remove']
+
+ def initialize_options(self):
+ option_base.initialize_options(self)
+ self.command = None
+ self.option = None
+ self.set_value = None
+ self.remove = None
+
+ def finalize_options(self):
+ option_base.finalize_options(self)
+ if self.command is None or self.option is None:
+ raise DistutilsOptionError("Must specify --command *and* --option")
+ if self.set_value is None and not self.remove:
+ raise DistutilsOptionError("Must specify --set-value or --remove")
+
+ def run(self):
+ edit_config(
+ self.filename, {
+ self.command: {self.option.replace('-', '_'): self.set_value}
+ },
+ self.dry_run
+ )
diff --git a/contrib/python/setuptools/py3/setuptools/command/test.py b/contrib/python/setuptools/py3/setuptools/command/test.py
index 52c6fcd22a..4a389e4d07 100644
--- a/contrib/python/setuptools/py3/setuptools/command/test.py
+++ b/contrib/python/setuptools/py3/setuptools/command/test.py
@@ -6,8 +6,8 @@ import itertools
import unittest
from distutils.errors import DistutilsError, DistutilsOptionError
from distutils import log
-from unittest import TestLoader
-
+from unittest import TestLoader
+
from pkg_resources import (
resource_listdir,
resource_exists,
@@ -18,113 +18,113 @@ from pkg_resources import (
require,
EntryPoint,
)
-from setuptools import Command
+from setuptools import Command
from setuptools.extern.more_itertools import unique_everseen
-
-
-class ScanningLoader(TestLoader):
+
+
+class ScanningLoader(TestLoader):
def __init__(self):
TestLoader.__init__(self)
self._visited = set()
- def loadTestsFromModule(self, module, pattern=None):
- """Return a suite of all tests cases contained in the given module
-
- If the module is a package, load tests from all the modules in it.
- If the module has an ``additional_tests`` function, call it and add
- the return value to the tests.
- """
+ def loadTestsFromModule(self, module, pattern=None):
+ """Return a suite of all tests cases contained in the given module
+
+ If the module is a package, load tests from all the modules in it.
+ If the module has an ``additional_tests`` function, call it and add
+ the return value to the tests.
+ """
if module in self._visited:
return None
self._visited.add(module)
- tests = []
- tests.append(TestLoader.loadTestsFromModule(self, module))
-
- if hasattr(module, "additional_tests"):
- tests.append(module.additional_tests())
-
- if hasattr(module, '__path__'):
- for file in resource_listdir(module.__name__, ''):
- if file.endswith('.py') and file != '__init__.py':
- submodule = module.__name__ + '.' + file[:-3]
- else:
- if resource_exists(module.__name__, file + '/__init__.py'):
- submodule = module.__name__ + '.' + file
- else:
- continue
- tests.append(self.loadTestsFromName(submodule))
-
- if len(tests) != 1:
- return self.suiteClass(tests)
- else:
- return tests[0] # don't create a nested suite for only one return
-
-
-# adapted from jaraco.classes.properties:NonDataProperty
+ tests = []
+ tests.append(TestLoader.loadTestsFromModule(self, module))
+
+ if hasattr(module, "additional_tests"):
+ tests.append(module.additional_tests())
+
+ if hasattr(module, '__path__'):
+ for file in resource_listdir(module.__name__, ''):
+ if file.endswith('.py') and file != '__init__.py':
+ submodule = module.__name__ + '.' + file[:-3]
+ else:
+ if resource_exists(module.__name__, file + '/__init__.py'):
+ submodule = module.__name__ + '.' + file
+ else:
+ continue
+ tests.append(self.loadTestsFromName(submodule))
+
+ if len(tests) != 1:
+ return self.suiteClass(tests)
+ else:
+ return tests[0] # don't create a nested suite for only one return
+
+
+# adapted from jaraco.classes.properties:NonDataProperty
class NonDataProperty:
- def __init__(self, fget):
- self.fget = fget
-
- def __get__(self, obj, objtype=None):
- if obj is None:
- return self
- return self.fget(obj)
-
-
-class test(Command):
- """Command to run unit tests after in-place build"""
-
+ def __init__(self, fget):
+ self.fget = fget
+
+ def __get__(self, obj, objtype=None):
+ if obj is None:
+ return self
+ return self.fget(obj)
+
+
+class test(Command):
+ """Command to run unit tests after in-place build"""
+
description = "run unit tests after in-place build (deprecated)"
-
- user_options = [
- ('test-module=', 'm', "Run 'test_suite' in specified module"),
+
+ user_options = [
+ ('test-module=', 'm', "Run 'test_suite' in specified module"),
(
'test-suite=',
's',
"Run single test, case or suite (e.g. 'module.test_suite')",
),
- ('test-runner=', 'r', "Test runner to use"),
- ]
-
- def initialize_options(self):
- self.test_suite = None
- self.test_module = None
- self.test_loader = None
- self.test_runner = None
-
- def finalize_options(self):
-
- if self.test_suite and self.test_module:
- msg = "You may specify a module or a suite, but not both"
- raise DistutilsOptionError(msg)
-
- if self.test_suite is None:
- if self.test_module is None:
- self.test_suite = self.distribution.test_suite
- else:
- self.test_suite = self.test_module + ".test_suite"
-
- if self.test_loader is None:
- self.test_loader = getattr(self.distribution, 'test_loader', None)
- if self.test_loader is None:
- self.test_loader = "setuptools.command.test:ScanningLoader"
- if self.test_runner is None:
- self.test_runner = getattr(self.distribution, 'test_runner', None)
-
- @NonDataProperty
- def test_args(self):
- return list(self._test_args())
-
- def _test_args(self):
+ ('test-runner=', 'r', "Test runner to use"),
+ ]
+
+ def initialize_options(self):
+ self.test_suite = None
+ self.test_module = None
+ self.test_loader = None
+ self.test_runner = None
+
+ def finalize_options(self):
+
+ if self.test_suite and self.test_module:
+ msg = "You may specify a module or a suite, but not both"
+ raise DistutilsOptionError(msg)
+
+ if self.test_suite is None:
+ if self.test_module is None:
+ self.test_suite = self.distribution.test_suite
+ else:
+ self.test_suite = self.test_module + ".test_suite"
+
+ if self.test_loader is None:
+ self.test_loader = getattr(self.distribution, 'test_loader', None)
+ if self.test_loader is None:
+ self.test_loader = "setuptools.command.test:ScanningLoader"
+ if self.test_runner is None:
+ self.test_runner = getattr(self.distribution, 'test_runner', None)
+
+ @NonDataProperty
+ def test_args(self):
+ return list(self._test_args())
+
+ def _test_args(self):
if not self.test_suite and sys.version_info >= (2, 7):
yield 'discover'
- if self.verbose:
- yield '--verbose'
- if self.test_suite:
- yield self.test_suite
-
- def with_project_on_sys_path(self, func):
+ if self.verbose:
+ yield '--verbose'
+ if self.test_suite:
+ yield self.test_suite
+
+ def with_project_on_sys_path(self, func):
"""
Backward compatibility for project_on_sys_path context.
"""
@@ -134,30 +134,30 @@ class test(Command):
@contextlib.contextmanager
def project_on_sys_path(self, include_dists=[]):
self.run_command('egg_info')
-
+
# Build extensions in-place
self.reinitialize_command('build_ext', inplace=1)
self.run_command('build_ext')
-
- ei_cmd = self.get_finalized_command("egg_info")
-
- old_path = sys.path[:]
- old_modules = sys.modules.copy()
-
- try:
+
+ ei_cmd = self.get_finalized_command("egg_info")
+
+ old_path = sys.path[:]
+ old_modules = sys.modules.copy()
+
+ try:
project_path = normalize_path(ei_cmd.egg_base)
sys.path.insert(0, project_path)
- working_set.__init__()
- add_activation_listener(lambda dist: dist.activate())
- require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version))
+ working_set.__init__()
+ add_activation_listener(lambda dist: dist.activate())
+ require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version))
with self.paths_on_pythonpath([project_path]):
yield
- finally:
- sys.path[:] = old_path
- sys.modules.clear()
- sys.modules.update(old_modules)
- working_set.__init__()
-
+ finally:
+ sys.path[:] = old_path
+ sys.modules.clear()
+ sys.modules.update(old_modules)
+ working_set.__init__()
+
@staticmethod
@contextlib.contextmanager
def paths_on_pythonpath(paths):
@@ -199,7 +199,7 @@ class test(Command):
)
return itertools.chain(ir_d, tr_d, er_d)
- def run(self):
+ def run(self):
self.announce(
"WARNING: Testing via this command is deprecated and will be "
"removed in a future version. Users looking for a generic test "
@@ -209,12 +209,12 @@ class test(Command):
)
installed_dists = self.install_dists(self.distribution)
-
- cmd = ' '.join(self._argv)
- if self.dry_run:
- self.announce('skipping "%s" (dry run)' % cmd)
+
+ cmd = ' '.join(self._argv)
+ if self.dry_run:
+ self.announce('skipping "%s" (dry run)' % cmd)
return
-
+
self.announce('running "%s"' % cmd)
paths = map(operator.attrgetter('location'), installed_dists)
@@ -222,31 +222,31 @@ class test(Command):
with self.project_on_sys_path():
self.run_tests()
- def run_tests(self):
+ def run_tests(self):
test = unittest.main(
None,
None,
self._argv,
- testLoader=self._resolve_as_ep(self.test_loader),
- testRunner=self._resolve_as_ep(self.test_runner),
+ testLoader=self._resolve_as_ep(self.test_loader),
+ testRunner=self._resolve_as_ep(self.test_runner),
exit=False,
- )
+ )
if not test.result.wasSuccessful():
msg = 'Test failed: %s' % test.result
self.announce(msg, log.ERROR)
raise DistutilsError(msg)
-
- @property
- def _argv(self):
- return ['unittest'] + self.test_args
-
- @staticmethod
- def _resolve_as_ep(val):
- """
- Load the indicated attribute value, called, as a as if it were
- specified as an entry point.
- """
- if val is None:
- return
- parsed = EntryPoint.parse("x=" + val)
- return parsed.resolve()()
+
+ @property
+ def _argv(self):
+ return ['unittest'] + self.test_args
+
+ @staticmethod
+ def _resolve_as_ep(val):
+ """
+ Load the indicated attribute value, called, as a as if it were
+ specified as an entry point.
+ """
+ if val is None:
+ return
+ parsed = EntryPoint.parse("x=" + val)
+ return parsed.resolve()()
diff --git a/contrib/python/setuptools/py3/setuptools/command/upload_docs.py b/contrib/python/setuptools/py3/setuptools/command/upload_docs.py
index 7dbf039316..845bff4421 100644
--- a/contrib/python/setuptools/py3/setuptools/command/upload_docs.py
+++ b/contrib/python/setuptools/py3/setuptools/command/upload_docs.py
@@ -1,105 +1,105 @@
-# -*- coding: utf-8 -*-
-"""upload_docs
-
-Implements a Distutils 'upload_docs' subcommand (upload documentation to
+# -*- coding: utf-8 -*-
+"""upload_docs
+
+Implements a Distutils 'upload_docs' subcommand (upload documentation to
sites other than PyPi such as devpi).
-"""
-
-from base64 import standard_b64encode
-from distutils import log
-from distutils.errors import DistutilsOptionError
-import os
-import socket
-import zipfile
-import tempfile
-import shutil
+"""
+
+from base64 import standard_b64encode
+from distutils import log
+from distutils.errors import DistutilsOptionError
+import os
+import socket
+import zipfile
+import tempfile
+import shutil
import itertools
import functools
import http.client
import urllib.parse
-
-from pkg_resources import iter_entry_points
+
+from pkg_resources import iter_entry_points
from .upload import upload
-
-
+
+
def _encode(s):
return s.encode('utf-8', 'surrogateescape')
-
-
+
+
class upload_docs(upload):
# override the default repository as upload_docs isn't
# supported by Warehouse (and won't be).
DEFAULT_REPOSITORY = 'https://pypi.python.org/pypi/'
-
+
description = 'Upload documentation to sites other than PyPi such as devpi'
-
- user_options = [
- ('repository=', 'r',
- "url of repository [default: %s]" % upload.DEFAULT_REPOSITORY),
- ('show-response', None,
- 'display full response text from server'),
- ('upload-dir=', None, 'directory to upload'),
- ]
- boolean_options = upload.boolean_options
-
- def has_sphinx(self):
- if self.upload_dir is None:
- for ep in iter_entry_points('distutils.commands', 'build_sphinx'):
- return True
-
- sub_commands = [('build_sphinx', has_sphinx)]
-
- def initialize_options(self):
- upload.initialize_options(self)
- self.upload_dir = None
- self.target_dir = None
-
- def finalize_options(self):
- upload.finalize_options(self)
- if self.upload_dir is None:
- if self.has_sphinx():
- build_sphinx = self.get_finalized_command('build_sphinx')
+
+ user_options = [
+ ('repository=', 'r',
+ "url of repository [default: %s]" % upload.DEFAULT_REPOSITORY),
+ ('show-response', None,
+ 'display full response text from server'),
+ ('upload-dir=', None, 'directory to upload'),
+ ]
+ boolean_options = upload.boolean_options
+
+ def has_sphinx(self):
+ if self.upload_dir is None:
+ for ep in iter_entry_points('distutils.commands', 'build_sphinx'):
+ return True
+
+ sub_commands = [('build_sphinx', has_sphinx)]
+
+ def initialize_options(self):
+ upload.initialize_options(self)
+ self.upload_dir = None
+ self.target_dir = None
+
+ def finalize_options(self):
+ upload.finalize_options(self)
+ if self.upload_dir is None:
+ if self.has_sphinx():
+ build_sphinx = self.get_finalized_command('build_sphinx')
self.target_dir = dict(build_sphinx.builder_target_dirs)['html']
- else:
- build = self.get_finalized_command('build')
- self.target_dir = os.path.join(build.build_base, 'docs')
- else:
- self.ensure_dirname('upload_dir')
- self.target_dir = self.upload_dir
+ else:
+ build = self.get_finalized_command('build')
+ self.target_dir = os.path.join(build.build_base, 'docs')
+ else:
+ self.ensure_dirname('upload_dir')
+ self.target_dir = self.upload_dir
if 'pypi.python.org' in self.repository:
log.warn("Upload_docs command is deprecated for PyPi. Use RTD instead.")
- self.announce('Using upload directory %s' % self.target_dir)
-
- def create_zipfile(self, filename):
- zip_file = zipfile.ZipFile(filename, "w")
- try:
- self.mkpath(self.target_dir) # just in case
- for root, dirs, files in os.walk(self.target_dir):
- if root == self.target_dir and not files:
+ self.announce('Using upload directory %s' % self.target_dir)
+
+ def create_zipfile(self, filename):
+ zip_file = zipfile.ZipFile(filename, "w")
+ try:
+ self.mkpath(self.target_dir) # just in case
+ for root, dirs, files in os.walk(self.target_dir):
+ if root == self.target_dir and not files:
tmpl = "no files found in upload directory '%s'"
raise DistutilsOptionError(tmpl % self.target_dir)
- for name in files:
- full = os.path.join(root, name)
- relative = root[len(self.target_dir):].lstrip(os.path.sep)
- dest = os.path.join(relative, name)
- zip_file.write(full, dest)
- finally:
- zip_file.close()
-
- def run(self):
- # Run sub commands
- for cmd_name in self.get_sub_commands():
- self.run_command(cmd_name)
-
- tmp_dir = tempfile.mkdtemp()
- name = self.distribution.metadata.get_name()
- zip_file = os.path.join(tmp_dir, "%s.zip" % name)
- try:
- self.create_zipfile(zip_file)
- self.upload_file(zip_file)
- finally:
- shutil.rmtree(tmp_dir)
-
+ for name in files:
+ full = os.path.join(root, name)
+ relative = root[len(self.target_dir):].lstrip(os.path.sep)
+ dest = os.path.join(relative, name)
+ zip_file.write(full, dest)
+ finally:
+ zip_file.close()
+
+ def run(self):
+ # Run sub commands
+ for cmd_name in self.get_sub_commands():
+ self.run_command(cmd_name)
+
+ tmp_dir = tempfile.mkdtemp()
+ name = self.distribution.metadata.get_name()
+ zip_file = os.path.join(tmp_dir, "%s.zip" % name)
+ try:
+ self.create_zipfile(zip_file)
+ self.upload_file(zip_file)
+ finally:
+ shutil.rmtree(tmp_dir)
+
@staticmethod
def _build_part(item, sep_boundary):
key, values = item
@@ -139,64 +139,64 @@ class upload_docs(upload):
content_type = 'multipart/form-data; boundary=%s' % boundary
return b''.join(body_items), content_type
- def upload_file(self, filename):
+ def upload_file(self, filename):
with open(filename, 'rb') as f:
content = f.read()
- meta = self.distribution.metadata
- data = {
- ':action': 'doc_upload',
- 'name': meta.get_name(),
- 'content': (os.path.basename(filename), content),
- }
- # set up the authentication
+ meta = self.distribution.metadata
+ data = {
+ ':action': 'doc_upload',
+ 'name': meta.get_name(),
+ 'content': (os.path.basename(filename), content),
+ }
+ # set up the authentication
credentials = _encode(self.username + ':' + self.password)
credentials = standard_b64encode(credentials).decode('ascii')
- auth = "Basic " + credentials
-
+ auth = "Basic " + credentials
+
body, ct = self._build_multipart(data)
-
+
msg = "Submitting documentation to %s" % (self.repository)
self.announce(msg, log.INFO)
-
- # build the Request
- # We can't use urllib2 since we need to send the Basic
- # auth right with the first request
- schema, netloc, url, params, query, fragments = \
- urllib.parse.urlparse(self.repository)
- assert not params and not query and not fragments
- if schema == 'http':
+
+ # build the Request
+ # We can't use urllib2 since we need to send the Basic
+ # auth right with the first request
+ schema, netloc, url, params, query, fragments = \
+ urllib.parse.urlparse(self.repository)
+ assert not params and not query and not fragments
+ if schema == 'http':
conn = http.client.HTTPConnection(netloc)
- elif schema == 'https':
+ elif schema == 'https':
conn = http.client.HTTPSConnection(netloc)
- else:
- raise AssertionError("unsupported schema " + schema)
-
- data = ''
- try:
- conn.connect()
- conn.putrequest("POST", url)
+ else:
+ raise AssertionError("unsupported schema " + schema)
+
+ data = ''
+ try:
+ conn.connect()
+ conn.putrequest("POST", url)
content_type = ct
- conn.putheader('Content-type', content_type)
- conn.putheader('Content-length', str(len(body)))
- conn.putheader('Authorization', auth)
- conn.endheaders()
- conn.send(body)
- except socket.error as e:
- self.announce(str(e), log.ERROR)
- return
-
- r = conn.getresponse()
- if r.status == 200:
+ conn.putheader('Content-type', content_type)
+ conn.putheader('Content-length', str(len(body)))
+ conn.putheader('Authorization', auth)
+ conn.endheaders()
+ conn.send(body)
+ except socket.error as e:
+ self.announce(str(e), log.ERROR)
+ return
+
+ r = conn.getresponse()
+ if r.status == 200:
msg = 'Server response (%s): %s' % (r.status, r.reason)
self.announce(msg, log.INFO)
- elif r.status == 301:
- location = r.getheader('Location')
- if location is None:
- location = 'https://pythonhosted.org/%s/' % meta.get_name()
+ elif r.status == 301:
+ location = r.getheader('Location')
+ if location is None:
+ location = 'https://pythonhosted.org/%s/' % meta.get_name()
msg = 'Upload successful. Visit %s' % location
self.announce(msg, log.INFO)
- else:
+ else:
msg = 'Upload failed (%s): %s' % (r.status, r.reason)
self.announce(msg, log.ERROR)
- if self.show_response:
- print('-' * 75, r.read(), '-' * 75)
+ if self.show_response:
+ print('-' * 75, r.read(), '-' * 75)
diff --git a/contrib/python/setuptools/py3/setuptools/depends.py b/contrib/python/setuptools/py3/setuptools/depends.py
index 3108f7ca42..adffd12db8 100644
--- a/contrib/python/setuptools/py3/setuptools/depends.py
+++ b/contrib/python/setuptools/py3/setuptools/depends.py
@@ -1,87 +1,87 @@
-import sys
-import marshal
+import sys
+import marshal
import contextlib
import dis
-
+
from setuptools.extern.packaging import version
from ._imp import find_module, PY_COMPILED, PY_FROZEN, PY_SOURCE
from . import _imp
-
-__all__ = [
- 'Require', 'find_module', 'get_module_constant', 'extract_constant'
-]
-
-class Require:
- """A prerequisite to building or installing a distribution"""
-
+__all__ = [
+ 'Require', 'find_module', 'get_module_constant', 'extract_constant'
+]
+
+
+class Require:
+ """A prerequisite to building or installing a distribution"""
+
def __init__(
self, name, requested_version, module, homepage='',
- attribute=None, format=None):
-
- if format is None and requested_version is not None:
+ attribute=None, format=None):
+
+ if format is None and requested_version is not None:
format = version.Version
-
- if format is not None:
- requested_version = format(requested_version)
- if attribute is None:
- attribute = '__version__'
-
- self.__dict__.update(locals())
- del self.self
-
- def full_name(self):
- """Return full package/distribution name, w/version"""
- if self.requested_version is not None:
+
+ if format is not None:
+ requested_version = format(requested_version)
+ if attribute is None:
+ attribute = '__version__'
+
+ self.__dict__.update(locals())
+ del self.self
+
+ def full_name(self):
+ """Return full package/distribution name, w/version"""
+ if self.requested_version is not None:
return '%s-%s' % (self.name, self.requested_version)
- return self.name
-
- def version_ok(self, version):
- """Is 'version' sufficiently up-to-date?"""
- return self.attribute is None or self.format is None or \
+ return self.name
+
+ def version_ok(self, version):
+ """Is 'version' sufficiently up-to-date?"""
+ return self.attribute is None or self.format is None or \
str(version) != "unknown" and self.format(version) >= self.requested_version
-
- def get_version(self, paths=None, default="unknown"):
- """Get version number of installed module, 'None', or 'default'
-
- Search 'paths' for module. If not found, return 'None'. If found,
- return the extracted version attribute, or 'default' if no version
- attribute was specified, or the value cannot be determined without
- importing the module. The version is formatted according to the
- requirement's version format (if any), unless it is 'None' or the
- supplied 'default'.
- """
-
- if self.attribute is None:
- try:
+
+ def get_version(self, paths=None, default="unknown"):
+ """Get version number of installed module, 'None', or 'default'
+
+ Search 'paths' for module. If not found, return 'None'. If found,
+ return the extracted version attribute, or 'default' if no version
+ attribute was specified, or the value cannot be determined without
+ importing the module. The version is formatted according to the
+ requirement's version format (if any), unless it is 'None' or the
+ supplied 'default'.
+ """
+
+ if self.attribute is None:
+ try:
f, p, i = find_module(self.module, paths)
if f:
f.close()
- return default
- except ImportError:
- return None
-
- v = get_module_constant(self.module, self.attribute, default, paths)
-
- if v is not None and v is not default and self.format is not None:
- return self.format(v)
-
- return v
-
- def is_present(self, paths=None):
- """Return true if dependency is present on 'paths'"""
- return self.get_version(paths) is not None
-
- def is_current(self, paths=None):
- """Return true if dependency is present and up-to-date on 'paths'"""
- version = self.get_version(paths)
- if version is None:
- return False
+ return default
+ except ImportError:
+ return None
+
+ v = get_module_constant(self.module, self.attribute, default, paths)
+
+ if v is not None and v is not default and self.format is not None:
+ return self.format(v)
+
+ return v
+
+ def is_present(self, paths=None):
+ """Return true if dependency is present on 'paths'"""
+ return self.get_version(paths) is not None
+
+ def is_current(self, paths=None):
+ """Return true if dependency is present and up-to-date on 'paths'"""
+ version = self.get_version(paths)
+ if version is None:
+ return False
return self.version_ok(str(version))
-
-
+
+
def maybe_close(f):
@contextlib.contextmanager
def empty():
@@ -89,88 +89,88 @@ def maybe_close(f):
return
if not f:
return empty()
-
+
return contextlib.closing(f)
-
-
-def get_module_constant(module, symbol, default=-1, paths=None):
- """Find 'module' by searching 'paths', and extract 'symbol'
-
- Return 'None' if 'module' does not exist on 'paths', or it does not define
- 'symbol'. If the module defines 'symbol' as a constant, return the
- constant. Otherwise, return 'default'."""
-
- try:
+
+
+def get_module_constant(module, symbol, default=-1, paths=None):
+ """Find 'module' by searching 'paths', and extract 'symbol'
+
+ Return 'None' if 'module' does not exist on 'paths', or it does not define
+ 'symbol'. If the module defines 'symbol' as a constant, return the
+ constant. Otherwise, return 'default'."""
+
+ try:
f, path, (suffix, mode, kind) = info = find_module(module, paths)
- except ImportError:
- # Module doesn't exist
- return None
-
+ except ImportError:
+ # Module doesn't exist
+ return None
+
with maybe_close(f):
if kind == PY_COMPILED:
f.read(8) # skip magic & date
- code = marshal.load(f)
+ code = marshal.load(f)
elif kind == PY_FROZEN:
code = _imp.get_frozen_object(module, paths)
elif kind == PY_SOURCE:
- code = compile(f.read(), path, 'exec')
- else:
- # Not something we can parse; we'll have to import it. :(
+ code = compile(f.read(), path, 'exec')
+ else:
+ # Not something we can parse; we'll have to import it. :(
imported = _imp.get_module(module, paths, info)
return getattr(imported, symbol, None)
-
- return extract_constant(code, symbol, default)
-
-
-def extract_constant(code, symbol, default=-1):
- """Extract the constant value of 'symbol' from 'code'
-
- If the name 'symbol' is bound to a constant value by the Python code
- object 'code', return that value. If 'symbol' is bound to an expression,
- return 'default'. Otherwise, return 'None'.
-
- Return value is based on the first assignment to 'symbol'. 'symbol' must
- be a global, or at least a non-"fast" local in the code block. That is,
- only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
- must be present in 'code.co_names'.
- """
- if symbol not in code.co_names:
+
+ return extract_constant(code, symbol, default)
+
+
+def extract_constant(code, symbol, default=-1):
+ """Extract the constant value of 'symbol' from 'code'
+
+ If the name 'symbol' is bound to a constant value by the Python code
+ object 'code', return that value. If 'symbol' is bound to an expression,
+ return 'default'. Otherwise, return 'None'.
+
+ Return value is based on the first assignment to 'symbol'. 'symbol' must
+ be a global, or at least a non-"fast" local in the code block. That is,
+ only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
+ must be present in 'code.co_names'.
+ """
+ if symbol not in code.co_names:
# name's not there, can't possibly be an assignment
- return None
-
- name_idx = list(code.co_names).index(symbol)
-
- STORE_NAME = 90
- STORE_GLOBAL = 97
- LOAD_CONST = 100
-
- const = default
-
+ return None
+
+ name_idx = list(code.co_names).index(symbol)
+
+ STORE_NAME = 90
+ STORE_GLOBAL = 97
+ LOAD_CONST = 100
+
+ const = default
+
for byte_code in dis.Bytecode(code):
op = byte_code.opcode
arg = byte_code.arg
-
+
if op == LOAD_CONST:
- const = code.co_consts[arg]
+ const = code.co_consts[arg]
elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):
- return const
- else:
- const = default
-
-
-def _update_globals():
- """
- Patch the globals to remove the objects not available on some platforms.
-
- XXX it'd be better to test assertions about bytecode instead.
- """
-
- if not sys.platform.startswith('java') and sys.platform != 'cli':
- return
- incompatible = 'extract_constant', 'get_module_constant'
- for name in incompatible:
- del globals()[name]
- __all__.remove(name)
-
-
-_update_globals()
+ return const
+ else:
+ const = default
+
+
+def _update_globals():
+ """
+ Patch the globals to remove the objects not available on some platforms.
+
+ XXX it'd be better to test assertions about bytecode instead.
+ """
+
+ if not sys.platform.startswith('java') and sys.platform != 'cli':
+ return
+ incompatible = 'extract_constant', 'get_module_constant'
+ for name in incompatible:
+ del globals()[name]
+ __all__.remove(name)
+
+
+_update_globals()
diff --git a/contrib/python/setuptools/py3/setuptools/dist.py b/contrib/python/setuptools/py3/setuptools/dist.py
index cf4e8465f6..37a10d1dcd 100644
--- a/contrib/python/setuptools/py3/setuptools/dist.py
+++ b/contrib/python/setuptools/py3/setuptools/dist.py
@@ -1,16 +1,16 @@
# -*- coding: utf-8 -*-
-__all__ = ['Distribution']
-
+__all__ = ['Distribution']
+
import io
import sys
-import re
-import os
-import warnings
-import numbers
-import distutils.log
-import distutils.core
-import distutils.cmd
-import distutils.dist
+import re
+import os
+import warnings
+import numbers
+import distutils.log
+import distutils.core
+import distutils.cmd
+import distutils.dist
import distutils.command
from distutils.util import strtobool
from distutils.debug import DEBUG
@@ -25,32 +25,32 @@ from email import message_from_file
from distutils.errors import DistutilsOptionError, DistutilsSetupError
from distutils.util import rfc822_escape
-
+
from setuptools.extern import packaging
from setuptools.extern import ordered_set
from setuptools.extern.more_itertools import unique_everseen
-
+
from . import SetuptoolsDeprecationWarning
import setuptools
import setuptools.command
-from setuptools import windows_support
+from setuptools import windows_support
from setuptools.monkey import get_unpatched
from setuptools.config import parse_configuration
-import pkg_resources
+import pkg_resources
from setuptools.extern.packaging import version
-
+
if TYPE_CHECKING:
from email.message import Message
__import__('setuptools.extern.packaging.specifiers')
__import__('setuptools.extern.packaging.version')
-
-def _get_unpatched(cls):
+
+def _get_unpatched(cls):
warnings.warn("Do not call this function", DistDeprecationWarning)
return get_unpatched(cls)
-
+
def get_metadata_version(self):
mv = getattr(self, 'metadata_version', None)
@@ -163,7 +163,7 @@ def single_line(val):
def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
"""Write the PKG-INFO format data to a file object."""
version = self.get_metadata_version()
-
+
def write_field(key, value):
file.write("%s: %s\n" % (key, value))
@@ -191,7 +191,7 @@ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
write_field('Download-URL', self.download_url)
for project_url in self.project_urls.items():
write_field('Project-URL', '%s, %s' % project_url)
-
+
keywords = ','.join(self.get_keywords())
if keywords:
write_field('Keywords', keywords)
@@ -218,47 +218,47 @@ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
write_field('Provides-Extra', extra)
self._write_list(file, 'License-File', self.license_files or [])
-
+
file.write("\n%s\n\n" % self.get_long_description())
-sequence = tuple, list
-
+sequence = tuple, list
-def check_importable(dist, attr, value):
- try:
+
+def check_importable(dist, attr, value):
+ try:
ep = pkg_resources.EntryPoint.parse('x=' + value)
- assert not ep.extras
+ assert not ep.extras
except (TypeError, ValueError, AttributeError, AssertionError) as e:
- raise DistutilsSetupError(
+ raise DistutilsSetupError(
"%r must be importable 'module:attrs' string (got %r)" % (attr, value)
) from e
-
-
-def assert_string_list(dist, attr, value):
+
+
+def assert_string_list(dist, attr, value):
"""Verify that value is a string list"""
- try:
+ try:
# verify that value is a list or tuple to exclude unordered
# or single-use iterables
assert isinstance(value, (list, tuple))
# verify that elements of value are strings
assert ''.join(value) != value
except (TypeError, ValueError, AttributeError, AssertionError) as e:
- raise DistutilsSetupError(
+ raise DistutilsSetupError(
"%r must be a list of strings (got %r)" % (attr, value)
) from e
-def check_nsp(dist, attr, value):
- """Verify that namespace packages are valid"""
+def check_nsp(dist, attr, value):
+ """Verify that namespace packages are valid"""
ns_packages = value
assert_string_list(dist, attr, ns_packages)
for nsp in ns_packages:
- if not dist.has_contents_for(nsp):
- raise DistutilsSetupError(
+ if not dist.has_contents_for(nsp):
+ raise DistutilsSetupError(
"Distribution contains no modules or packages for "
+ "namespace package %r" % nsp
- )
+ )
parent, sep, child = nsp.rpartition('.')
if parent and parent not in ns_packages:
distutils.log.warn(
@@ -267,19 +267,19 @@ def check_nsp(dist, attr, value):
nsp,
parent,
)
-
-def check_extras(dist, attr, value):
- """Verify that extras_require mapping is valid"""
- try:
+
+def check_extras(dist, attr, value):
+ """Verify that extras_require mapping is valid"""
+ try:
list(itertools.starmap(_check_extra, value.items()))
except (TypeError, ValueError, AttributeError) as e:
- raise DistutilsSetupError(
- "'extras_require' must be a dictionary whose values are "
- "strings or lists of strings containing valid project/version "
- "requirement specifiers."
+ raise DistutilsSetupError(
+ "'extras_require' must be a dictionary whose values are "
+ "strings or lists of strings containing valid project/version "
+ "requirement specifiers."
) from e
-
+
def _check_extra(extra, reqs):
name, sep, marker = extra.partition(':')
@@ -288,13 +288,13 @@ def _check_extra(extra, reqs):
list(pkg_resources.parse_requirements(reqs))
-def assert_bool(dist, attr, value):
- """Verify that value is True, False, 0, or 1"""
- if bool(value) != value:
- tmpl = "{attr!r} must be a boolean value (got {value!r})"
- raise DistutilsSetupError(tmpl.format(attr=attr, value=value))
-
-
+def assert_bool(dist, attr, value):
+ """Verify that value is True, False, 0, or 1"""
+ if bool(value) != value:
+ tmpl = "{attr!r} must be a boolean value (got {value!r})"
+ raise DistutilsSetupError(tmpl.format(attr=attr, value=value))
+
+
def invalid_unless_false(dist, attr, value):
if not value:
warnings.warn(f"{attr} is ignored.", DistDeprecationWarning)
@@ -302,19 +302,19 @@ def invalid_unless_false(dist, attr, value):
raise DistutilsSetupError(f"{attr} is invalid.")
-def check_requirements(dist, attr, value):
- """Verify that install_requires is a valid requirements list"""
- try:
- list(pkg_resources.parse_requirements(value))
+def check_requirements(dist, attr, value):
+ """Verify that install_requires is a valid requirements list"""
+ try:
+ list(pkg_resources.parse_requirements(value))
if isinstance(value, (dict, set)):
raise TypeError("Unordered types are not allowed")
- except (TypeError, ValueError) as error:
- tmpl = (
- "{attr!r} must be a string or list of strings "
- "containing valid project/version requirement specifiers; {error}"
- )
+ except (TypeError, ValueError) as error:
+ tmpl = (
+ "{attr!r} must be a string or list of strings "
+ "containing valid project/version requirement specifiers; {error}"
+ )
raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) from error
-
+
def check_specifier(dist, attr, value):
"""Verify that value is a valid version specifier"""
@@ -327,21 +327,21 @@ def check_specifier(dist, attr, value):
raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) from error
-def check_entry_points(dist, attr, value):
- """Verify that entry_points map is parseable"""
- try:
- pkg_resources.EntryPoint.parse_map(value)
- except ValueError as e:
+def check_entry_points(dist, attr, value):
+ """Verify that entry_points map is parseable"""
+ try:
+ pkg_resources.EntryPoint.parse_map(value)
+ except ValueError as e:
raise DistutilsSetupError(e) from e
-
-def check_test_suite(dist, attr, value):
+
+def check_test_suite(dist, attr, value):
if not isinstance(value, str):
- raise DistutilsSetupError("test_suite must be a string")
-
+ raise DistutilsSetupError("test_suite must be a string")
-def check_package_data(dist, attr, value):
- """Verify that value is a dictionary of package names to glob lists"""
+
+def check_package_data(dist, attr, value):
+ """Verify that value is a dictionary of package names to glob lists"""
if not isinstance(value, dict):
raise DistutilsSetupError(
"{!r} must be a dictionary mapping package names to lists of "
@@ -353,73 +353,73 @@ def check_package_data(dist, attr, value):
"keys of {!r} dict must be strings (got {!r})".format(attr, k)
)
assert_string_list(dist, 'values of {!r} dict'.format(attr), v)
-
-def check_packages(dist, attr, value):
- for pkgname in value:
- if not re.match(r'\w+(\.\w+)*', pkgname):
- distutils.log.warn(
- "WARNING: %r not a valid package name; please use only "
+
+def check_packages(dist, attr, value):
+ for pkgname in value:
+ if not re.match(r'\w+(\.\w+)*', pkgname):
+ distutils.log.warn(
+ "WARNING: %r not a valid package name; please use only "
".-separated package names in setup.py",
pkgname,
- )
-
-
+ )
+
+
_Distribution = get_unpatched(distutils.core.Distribution)
class Distribution(_Distribution):
"""Distribution with support for tests and package data
-
- This is an enhanced version of 'distutils.dist.Distribution' that
- effectively adds the following new optional keyword arguments to 'setup()':
-
- 'install_requires' -- a string or sequence of strings specifying project
- versions that the distribution requires when installed, in the format
- used by 'pkg_resources.require()'. They will be installed
- automatically when the package is installed. If you wish to use
- packages that are not available in PyPI, or want to give your users an
- alternate download location, you can add a 'find_links' option to the
- '[easy_install]' section of your project's 'setup.cfg' file, and then
- setuptools will scan the listed web pages for links that satisfy the
- requirements.
-
- 'extras_require' -- a dictionary mapping names of optional "extras" to the
- additional requirement(s) that using those extras incurs. For example,
- this::
-
- extras_require = dict(reST = ["docutils>=0.3", "reSTedit"])
-
- indicates that the distribution can optionally provide an extra
- capability called "reST", but it can only be used if docutils and
- reSTedit are installed. If the user installs your package using
- EasyInstall and requests one of your extras, the corresponding
- additional requirements will be installed if needed.
-
- 'test_suite' -- the name of a test suite to run for the 'test' command.
- If the user runs 'python setup.py test', the package will be installed,
- and the named test suite will be run. The format is the same as
- would be used on a 'unittest.py' command line. That is, it is the
- dotted name of an object to import and call to generate a test suite.
-
- 'package_data' -- a dictionary mapping package names to lists of filenames
- or globs to use to find data files contained in the named packages.
- If the dictionary has filenames or globs listed under '""' (the empty
- string), those names will be searched for in every package, in addition
- to any names for the specific package. Data files found using these
- names/globs will be installed along with the package, in the same
- location as the package. Note that globs are allowed to reference
- the contents of non-package subdirectories, as long as you use '/' as
- a path separator. (Globs are automatically converted to
- platform-specific paths at runtime.)
-
- In addition to these new keywords, this class also has several new methods
- for manipulating the distribution's contents. For example, the 'include()'
- and 'exclude()' methods can be thought of as in-place add and subtract
- commands that add or remove packages, modules, extensions, and so on from
+
+ This is an enhanced version of 'distutils.dist.Distribution' that
+ effectively adds the following new optional keyword arguments to 'setup()':
+
+ 'install_requires' -- a string or sequence of strings specifying project
+ versions that the distribution requires when installed, in the format
+ used by 'pkg_resources.require()'. They will be installed
+ automatically when the package is installed. If you wish to use
+ packages that are not available in PyPI, or want to give your users an
+ alternate download location, you can add a 'find_links' option to the
+ '[easy_install]' section of your project's 'setup.cfg' file, and then
+ setuptools will scan the listed web pages for links that satisfy the
+ requirements.
+
+ 'extras_require' -- a dictionary mapping names of optional "extras" to the
+ additional requirement(s) that using those extras incurs. For example,
+ this::
+
+ extras_require = dict(reST = ["docutils>=0.3", "reSTedit"])
+
+ indicates that the distribution can optionally provide an extra
+ capability called "reST", but it can only be used if docutils and
+ reSTedit are installed. If the user installs your package using
+ EasyInstall and requests one of your extras, the corresponding
+ additional requirements will be installed if needed.
+
+ 'test_suite' -- the name of a test suite to run for the 'test' command.
+ If the user runs 'python setup.py test', the package will be installed,
+ and the named test suite will be run. The format is the same as
+ would be used on a 'unittest.py' command line. That is, it is the
+ dotted name of an object to import and call to generate a test suite.
+
+ 'package_data' -- a dictionary mapping package names to lists of filenames
+ or globs to use to find data files contained in the named packages.
+ If the dictionary has filenames or globs listed under '""' (the empty
+ string), those names will be searched for in every package, in addition
+ to any names for the specific package. Data files found using these
+ names/globs will be installed along with the package, in the same
+ location as the package. Note that globs are allowed to reference
+ the contents of non-package subdirectories, as long as you use '/' as
+ a path separator. (Globs are automatically converted to
+ platform-specific paths at runtime.)
+
+ In addition to these new keywords, this class also has several new methods
+ for manipulating the distribution's contents. For example, the 'include()'
+ and 'exclude()' methods can be thought of as in-place add and subtract
+ commands that add or remove packages, modules, extensions, and so on from
the distribution.
- """
-
+ """
+
_DISTUTILS_UNSUPPORTED_METADATA = {
'long_description_content_type': lambda: None,
'project_urls': dict,
@@ -428,34 +428,34 @@ class Distribution(_Distribution):
'license_files': lambda: None,
}
- _patched_dist = None
-
- def patch_missing_pkg_info(self, attrs):
- # Fake up a replacement for the data that would normally come from
- # PKG-INFO, but which might not yet be built if this is a fresh
- # checkout.
- #
- if not attrs or 'name' not in attrs or 'version' not in attrs:
- return
- key = pkg_resources.safe_name(str(attrs['name'])).lower()
- dist = pkg_resources.working_set.by_key.get(key)
- if dist is not None and not dist.has_metadata('PKG-INFO'):
- dist._version = pkg_resources.safe_version(str(attrs['version']))
- self._patched_dist = dist
-
- def __init__(self, attrs=None):
- have_package_data = hasattr(self, "package_data")
- if not have_package_data:
- self.package_data = {}
+ _patched_dist = None
+
+ def patch_missing_pkg_info(self, attrs):
+ # Fake up a replacement for the data that would normally come from
+ # PKG-INFO, but which might not yet be built if this is a fresh
+ # checkout.
+ #
+ if not attrs or 'name' not in attrs or 'version' not in attrs:
+ return
+ key = pkg_resources.safe_name(str(attrs['name'])).lower()
+ dist = pkg_resources.working_set.by_key.get(key)
+ if dist is not None and not dist.has_metadata('PKG-INFO'):
+ dist._version = pkg_resources.safe_version(str(attrs['version']))
+ self._patched_dist = dist
+
+ def __init__(self, attrs=None):
+ have_package_data = hasattr(self, "package_data")
+ if not have_package_data:
+ self.package_data = {}
attrs = attrs or {}
- self.dist_files = []
+ self.dist_files = []
# Filter-out setuptools' specific options.
self.src_root = attrs.pop("src_root", None)
- self.patch_missing_pkg_info(attrs)
+ self.patch_missing_pkg_info(attrs)
self.dependency_links = attrs.pop('dependency_links', [])
self.setup_requires = attrs.pop('setup_requires', [])
- for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
- vars(self).setdefault(ep.name, None)
+ for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
+ vars(self).setdefault(ep.name, None)
_Distribution.__init__(
self,
{
@@ -497,19 +497,19 @@ class Distribution(_Distribution):
@staticmethod
def _validate_version(version):
if isinstance(version, numbers.Number):
- # Some people apparently take "version number" too literally :)
+ # Some people apparently take "version number" too literally :)
version = str(version)
-
+
if version is not None:
- try:
+ try:
packaging.version.Version(version)
- except (packaging.version.InvalidVersion, TypeError):
- warnings.warn(
- "The version specified (%r) is an invalid version, this "
- "may not work as expected with newer versions of "
- "setuptools, pip, and PyPI. Please see PEP 440 for more "
+ except (packaging.version.InvalidVersion, TypeError):
+ warnings.warn(
+ "The version specified (%r) is an invalid version, this "
+ "may not work as expected with newer versions of "
+ "setuptools, pip, and PyPI. Please see PEP 440 for more "
"details." % version
- )
+ )
return setuptools.sic(version)
return version
@@ -520,7 +520,7 @@ class Distribution(_Distribution):
"""
if getattr(self, 'python_requires', None):
self.metadata.python_requires = self.python_requires
-
+
if getattr(self, 'extras_require', None):
for extra in self.extras_require.keys():
# Since this gets called multiple times at points where the
@@ -807,18 +807,18 @@ class Distribution(_Distribution):
self._finalize_requires()
self._finalize_license_files()
- def fetch_build_eggs(self, requires):
- """Resolve pre-setup requirements"""
- resolved_dists = pkg_resources.working_set.resolve(
- pkg_resources.parse_requirements(requires),
- installer=self.fetch_build_egg,
- replace_conflicting=True,
- )
- for dist in resolved_dists:
- pkg_resources.working_set.add(dist, replace=True)
+ def fetch_build_eggs(self, requires):
+ """Resolve pre-setup requirements"""
+ resolved_dists = pkg_resources.working_set.resolve(
+ pkg_resources.parse_requirements(requires),
+ installer=self.fetch_build_egg,
+ replace_conflicting=True,
+ )
+ for dist in resolved_dists:
+ pkg_resources.working_set.add(dist, replace=True)
return resolved_dists
-
- def finalize_options(self):
+
+ def finalize_options(self):
"""
Allow plugins to apply arbitrary operations to the
distribution. Each hook may optionally define a 'order'
@@ -826,7 +826,7 @@ class Distribution(_Distribution):
go first and the default is 0.
"""
group = 'setuptools.finalize_distribution_options'
-
+
def by_order(hook):
return getattr(hook, 'order', 0)
@@ -851,19 +851,19 @@ class Distribution(_Distribution):
return ep.name in removed
def _finalize_setup_keywords(self):
- for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
+ for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, ep.name, None)
- if value is not None:
- ep.require(installer=self.fetch_build_egg)
- ep.load()(self, ep.name, value)
-
- def get_egg_cache_dir(self):
- egg_cache_dir = os.path.join(os.curdir, '.eggs')
- if not os.path.exists(egg_cache_dir):
- os.mkdir(egg_cache_dir)
- windows_support.hide_file(egg_cache_dir)
- readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
- with open(readme_txt_filename, 'w') as f:
+ if value is not None:
+ ep.require(installer=self.fetch_build_egg)
+ ep.load()(self, ep.name, value)
+
+ def get_egg_cache_dir(self):
+ egg_cache_dir = os.path.join(os.curdir, '.eggs')
+ if not os.path.exists(egg_cache_dir):
+ os.mkdir(egg_cache_dir)
+ windows_support.hide_file(egg_cache_dir)
+ readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
+ with open(readme_txt_filename, 'w') as f:
f.write(
'This directory contains eggs that were downloaded '
'by setuptools to build, test, and run plug-ins.\n\n'
@@ -872,285 +872,285 @@ class Distribution(_Distribution):
'This directory caches those eggs to prevent '
'repeated downloads.\n\n'
)
- f.write('However, it is safe to delete this directory.\n\n')
-
- return egg_cache_dir
-
- def fetch_build_egg(self, req):
- """Fetch an egg needed for building"""
+ f.write('However, it is safe to delete this directory.\n\n')
+
+ return egg_cache_dir
+
+ def fetch_build_egg(self, req):
+ """Fetch an egg needed for building"""
from setuptools.installer import fetch_build_egg
return fetch_build_egg(self, req)
-
- def get_command_class(self, command):
- """Pluggable version of get_command_class()"""
- if command in self.cmdclass:
- return self.cmdclass[command]
-
+
+ def get_command_class(self, command):
+ """Pluggable version of get_command_class()"""
+ if command in self.cmdclass:
+ return self.cmdclass[command]
+
eps = pkg_resources.iter_entry_points('distutils.commands', command)
for ep in eps:
- ep.require(installer=self.fetch_build_egg)
- self.cmdclass[command] = cmdclass = ep.load()
- return cmdclass
- else:
- return _Distribution.get_command_class(self, command)
-
- def print_commands(self):
- for ep in pkg_resources.iter_entry_points('distutils.commands'):
- if ep.name not in self.cmdclass:
- # don't require extras as the commands won't be invoked
- cmdclass = ep.resolve()
- self.cmdclass[ep.name] = cmdclass
- return _Distribution.print_commands(self)
-
- def get_command_list(self):
- for ep in pkg_resources.iter_entry_points('distutils.commands'):
- if ep.name not in self.cmdclass:
- # don't require extras as the commands won't be invoked
- cmdclass = ep.resolve()
- self.cmdclass[ep.name] = cmdclass
- return _Distribution.get_command_list(self)
-
+ ep.require(installer=self.fetch_build_egg)
+ self.cmdclass[command] = cmdclass = ep.load()
+ return cmdclass
+ else:
+ return _Distribution.get_command_class(self, command)
+
+ def print_commands(self):
+ for ep in pkg_resources.iter_entry_points('distutils.commands'):
+ if ep.name not in self.cmdclass:
+ # don't require extras as the commands won't be invoked
+ cmdclass = ep.resolve()
+ self.cmdclass[ep.name] = cmdclass
+ return _Distribution.print_commands(self)
+
+ def get_command_list(self):
+ for ep in pkg_resources.iter_entry_points('distutils.commands'):
+ if ep.name not in self.cmdclass:
+ # don't require extras as the commands won't be invoked
+ cmdclass = ep.resolve()
+ self.cmdclass[ep.name] = cmdclass
+ return _Distribution.get_command_list(self)
+
def include(self, **attrs):
- """Add items to distribution that are named in keyword arguments
-
+ """Add items to distribution that are named in keyword arguments
+
For example, 'dist.include(py_modules=["x"])' would add 'x' to
- the distribution's 'py_modules' attribute, if it was not already
- there.
-
- Currently, this method only supports inclusion for attributes that are
- lists or tuples. If you need to add support for adding to other
- attributes in this or a subclass, you can add an '_include_X' method,
- where 'X' is the name of the attribute. The method will be called with
- the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
- will try to call 'dist._include_foo({"bar":"baz"})', which can then
- handle whatever special inclusion logic is needed.
- """
+ the distribution's 'py_modules' attribute, if it was not already
+ there.
+
+ Currently, this method only supports inclusion for attributes that are
+ lists or tuples. If you need to add support for adding to other
+ attributes in this or a subclass, you can add an '_include_X' method,
+ where 'X' is the name of the attribute. The method will be called with
+ the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
+ will try to call 'dist._include_foo({"bar":"baz"})', which can then
+ handle whatever special inclusion logic is needed.
+ """
for k, v in attrs.items():
include = getattr(self, '_include_' + k, None)
- if include:
- include(v)
- else:
+ if include:
+ include(v)
+ else:
self._include_misc(k, v)
-
+
def exclude_package(self, package):
- """Remove packages, modules, and extensions in named package"""
-
+ """Remove packages, modules, and extensions in named package"""
+
pfx = package + '.'
- if self.packages:
- self.packages = [
+ if self.packages:
+ self.packages = [
p for p in self.packages if p != package and not p.startswith(pfx)
- ]
-
- if self.py_modules:
- self.py_modules = [
+ ]
+
+ if self.py_modules:
+ self.py_modules = [
p for p in self.py_modules if p != package and not p.startswith(pfx)
- ]
-
- if self.ext_modules:
- self.ext_modules = [
+ ]
+
+ if self.ext_modules:
+ self.ext_modules = [
p
for p in self.ext_modules
if p.name != package and not p.name.startswith(pfx)
- ]
-
+ ]
+
def has_contents_for(self, package):
- """Return true if 'exclude_package(package)' would do something"""
-
+ """Return true if 'exclude_package(package)' would do something"""
+
pfx = package + '.'
-
- for p in self.iter_distribution_names():
+
+ for p in self.iter_distribution_names():
if p == package or p.startswith(pfx):
- return True
-
+ return True
+
def _exclude_misc(self, name, value):
- """Handle 'exclude()' for list/tuple attrs without a special handler"""
+ """Handle 'exclude()' for list/tuple attrs without a special handler"""
if not isinstance(value, sequence):
- raise DistutilsSetupError(
- "%s: setting must be a list or tuple (%r)" % (name, value)
- )
- try:
+ raise DistutilsSetupError(
+ "%s: setting must be a list or tuple (%r)" % (name, value)
+ )
+ try:
old = getattr(self, name)
except AttributeError as e:
raise DistutilsSetupError("%s: No such distribution setting" % name) from e
if old is not None and not isinstance(old, sequence):
- raise DistutilsSetupError(
+ raise DistutilsSetupError(
name + ": this setting cannot be changed via include/exclude"
- )
- elif old:
+ )
+ elif old:
setattr(self, name, [item for item in old if item not in value])
-
+
def _include_misc(self, name, value):
- """Handle 'include()' for list/tuple attrs without a special handler"""
-
+ """Handle 'include()' for list/tuple attrs without a special handler"""
+
if not isinstance(value, sequence):
raise DistutilsSetupError("%s: setting must be a list (%r)" % (name, value))
- try:
+ try:
old = getattr(self, name)
except AttributeError as e:
raise DistutilsSetupError("%s: No such distribution setting" % name) from e
- if old is None:
+ if old is None:
setattr(self, name, value)
elif not isinstance(old, sequence):
- raise DistutilsSetupError(
+ raise DistutilsSetupError(
name + ": this setting cannot be changed via include/exclude"
- )
- else:
+ )
+ else:
new = [item for item in value if item not in old]
setattr(self, name, old + new)
-
+
def exclude(self, **attrs):
- """Remove items from distribution that are named in keyword arguments
-
- For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
- the distribution's 'py_modules' attribute. Excluding packages uses
- the 'exclude_package()' method, so all of the package's contained
- packages, modules, and extensions are also excluded.
-
- Currently, this method only supports exclusion from attributes that are
- lists or tuples. If you need to add support for excluding from other
- attributes in this or a subclass, you can add an '_exclude_X' method,
- where 'X' is the name of the attribute. The method will be called with
- the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})'
- will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
- handle whatever special exclusion logic is needed.
- """
+ """Remove items from distribution that are named in keyword arguments
+
+ For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
+ the distribution's 'py_modules' attribute. Excluding packages uses
+ the 'exclude_package()' method, so all of the package's contained
+ packages, modules, and extensions are also excluded.
+
+ Currently, this method only supports exclusion from attributes that are
+ lists or tuples. If you need to add support for excluding from other
+ attributes in this or a subclass, you can add an '_exclude_X' method,
+ where 'X' is the name of the attribute. The method will be called with
+ the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})'
+ will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
+ handle whatever special exclusion logic is needed.
+ """
for k, v in attrs.items():
exclude = getattr(self, '_exclude_' + k, None)
- if exclude:
- exclude(v)
- else:
+ if exclude:
+ exclude(v)
+ else:
self._exclude_misc(k, v)
-
+
def _exclude_packages(self, packages):
if not isinstance(packages, sequence):
- raise DistutilsSetupError(
- "packages: setting must be a list or tuple (%r)" % (packages,)
- )
- list(map(self.exclude_package, packages))
-
- def _parse_command_opts(self, parser, args):
- # Remove --with-X/--without-X options when processing command args
- self.global_options = self.__class__.global_options
- self.negative_opt = self.__class__.negative_opt
-
- # First, expand any aliases
- command = args[0]
- aliases = self.get_option_dict('aliases')
- while command in aliases:
+ raise DistutilsSetupError(
+ "packages: setting must be a list or tuple (%r)" % (packages,)
+ )
+ list(map(self.exclude_package, packages))
+
+ def _parse_command_opts(self, parser, args):
+ # Remove --with-X/--without-X options when processing command args
+ self.global_options = self.__class__.global_options
+ self.negative_opt = self.__class__.negative_opt
+
+ # First, expand any aliases
+ command = args[0]
+ aliases = self.get_option_dict('aliases')
+ while command in aliases:
src, alias = aliases[command]
del aliases[command] # ensure each alias can expand only once!
- import shlex
+ import shlex
args[:1] = shlex.split(alias, True)
- command = args[0]
-
- nargs = _Distribution._parse_command_opts(self, parser, args)
-
- # Handle commands that want to consume all remaining arguments
- cmd_class = self.get_command_class(command)
+ command = args[0]
+
+ nargs = _Distribution._parse_command_opts(self, parser, args)
+
+ # Handle commands that want to consume all remaining arguments
+ cmd_class = self.get_command_class(command)
if getattr(cmd_class, 'command_consumes_arguments', None):
- self.get_option_dict(command)['args'] = ("command line", nargs)
- if nargs is not None:
- return []
-
- return nargs
-
- def get_cmdline_options(self):
- """Return a '{cmd: {opt:val}}' map of all command-line options
-
- Option names are all long, but do not include the leading '--', and
- contain dashes rather than underscores. If the option doesn't take
- an argument (e.g. '--quiet'), the 'val' is 'None'.
-
- Note that options provided by config files are intentionally excluded.
- """
-
- d = {}
-
+ self.get_option_dict(command)['args'] = ("command line", nargs)
+ if nargs is not None:
+ return []
+
+ return nargs
+
+ def get_cmdline_options(self):
+ """Return a '{cmd: {opt:val}}' map of all command-line options
+
+ Option names are all long, but do not include the leading '--', and
+ contain dashes rather than underscores. If the option doesn't take
+ an argument (e.g. '--quiet'), the 'val' is 'None'.
+
+ Note that options provided by config files are intentionally excluded.
+ """
+
+ d = {}
+
for cmd, opts in self.command_options.items():
-
+
for opt, (src, val) in opts.items():
-
- if src != "command line":
- continue
-
+
+ if src != "command line":
+ continue
+
opt = opt.replace('_', '-')
-
+
if val == 0:
- cmdobj = self.get_command_obj(cmd)
- neg_opt = self.negative_opt.copy()
+ cmdobj = self.get_command_obj(cmd)
+ neg_opt = self.negative_opt.copy()
neg_opt.update(getattr(cmdobj, 'negative_opt', {}))
for neg, pos in neg_opt.items():
if pos == opt:
opt = neg
val = None
- break
- else:
- raise AssertionError("Shouldn't be able to get here")
-
+ break
+ else:
+ raise AssertionError("Shouldn't be able to get here")
+
elif val == 1:
- val = None
-
+ val = None
+
d.setdefault(cmd, {})[opt] = val
-
- return d
-
- def iter_distribution_names(self):
- """Yield all packages, modules, and extension names in distribution"""
-
- for pkg in self.packages or ():
- yield pkg
-
- for module in self.py_modules or ():
- yield module
-
- for ext in self.ext_modules or ():
+
+ return d
+
+ def iter_distribution_names(self):
+ """Yield all packages, modules, and extension names in distribution"""
+
+ for pkg in self.packages or ():
+ yield pkg
+
+ for module in self.py_modules or ():
+ yield module
+
+ for ext in self.ext_modules or ():
if isinstance(ext, tuple):
- name, buildinfo = ext
- else:
- name = ext.name
- if name.endswith('module'):
- name = name[:-6]
- yield name
-
- def handle_display_options(self, option_order):
- """If there were any non-global "display-only" options
- (--help-commands or the metadata display options) on the command
- line, display the requested info and return true; else return
- false.
- """
- import sys
-
+ name, buildinfo = ext
+ else:
+ name = ext.name
+ if name.endswith('module'):
+ name = name[:-6]
+ yield name
+
+ def handle_display_options(self, option_order):
+ """If there were any non-global "display-only" options
+ (--help-commands or the metadata display options) on the command
+ line, display the requested info and return true; else return
+ false.
+ """
+ import sys
+
if self.help_commands:
- return _Distribution.handle_display_options(self, option_order)
-
- # Stdout may be StringIO (e.g. in tests)
- if not isinstance(sys.stdout, io.TextIOWrapper):
- return _Distribution.handle_display_options(self, option_order)
-
- # Don't wrap stdout if utf-8 is already the encoding. Provides
- # workaround for #334.
- if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
- return _Distribution.handle_display_options(self, option_order)
-
- # Print metadata in UTF-8 no matter the platform
- encoding = sys.stdout.encoding
- errors = sys.stdout.errors
- newline = sys.platform != 'win32' and '\n' or None
- line_buffering = sys.stdout.line_buffering
-
- sys.stdout = io.TextIOWrapper(
+ return _Distribution.handle_display_options(self, option_order)
+
+ # Stdout may be StringIO (e.g. in tests)
+ if not isinstance(sys.stdout, io.TextIOWrapper):
+ return _Distribution.handle_display_options(self, option_order)
+
+ # Don't wrap stdout if utf-8 is already the encoding. Provides
+ # workaround for #334.
+ if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
+ return _Distribution.handle_display_options(self, option_order)
+
+ # Print metadata in UTF-8 no matter the platform
+ encoding = sys.stdout.encoding
+ errors = sys.stdout.errors
+ newline = sys.platform != 'win32' and '\n' or None
+ line_buffering = sys.stdout.line_buffering
+
+ sys.stdout = io.TextIOWrapper(
sys.stdout.detach(), 'utf-8', errors, newline, line_buffering
)
- try:
- return _Distribution.handle_display_options(self, option_order)
- finally:
- sys.stdout = io.TextIOWrapper(
+ try:
+ return _Distribution.handle_display_options(self, option_order)
+ finally:
+ sys.stdout = io.TextIOWrapper(
sys.stdout.detach(), encoding, errors, newline, line_buffering
)
-
-
+
+
class DistDeprecationWarning(SetuptoolsDeprecationWarning):
"""Class for warning about deprecations in dist in
setuptools. Not ignored by default, unlike DeprecationWarning."""
diff --git a/contrib/python/setuptools/py3/setuptools/extension.py b/contrib/python/setuptools/py3/setuptools/extension.py
index d733f35bc6..1820722a49 100644
--- a/contrib/python/setuptools/py3/setuptools/extension.py
+++ b/contrib/python/setuptools/py3/setuptools/extension.py
@@ -1,55 +1,55 @@
-import re
-import functools
-import distutils.core
-import distutils.errors
-import distutils.extension
-
+import re
+import functools
+import distutils.core
+import distutils.errors
+import distutils.extension
+
from .monkey import get_unpatched
-
-
-def _have_cython():
- """
- Return True if Cython can be imported.
- """
+
+
+def _have_cython():
+ """
+ Return True if Cython can be imported.
+ """
cython_impl = 'Cython.Distutils.build_ext'
- try:
- # from (cython_impl) import build_ext
- __import__(cython_impl, fromlist=['build_ext']).build_ext
- return True
- except Exception:
- pass
- return False
-
-
-# for compatibility
-have_pyrex = _have_cython
-
+ try:
+ # from (cython_impl) import build_ext
+ __import__(cython_impl, fromlist=['build_ext']).build_ext
+ return True
+ except Exception:
+ pass
+ return False
+
+
+# for compatibility
+have_pyrex = _have_cython
+
_Extension = get_unpatched(distutils.core.Extension)
-
-class Extension(_Extension):
- """Extension that uses '.c' files in place of '.pyx' files"""
-
+
+class Extension(_Extension):
+ """Extension that uses '.c' files in place of '.pyx' files"""
+
def __init__(self, name, sources, *args, **kw):
# The *args is needed for compatibility as calls may use positional
# arguments. py_limited_api may be set only via keyword.
self.py_limited_api = kw.pop("py_limited_api", False)
_Extension.__init__(self, name, sources, *args, **kw)
- def _convert_pyx_sources_to_lang(self):
- """
- Replace sources with .pyx extensions to sources with the target
- language extension. This mechanism allows language authors to supply
- pre-converted sources but to prefer the .pyx sources.
- """
- if _have_cython():
- # the build has Cython, so allow it to compile the .pyx files
- return
- lang = self.language or ''
- target_ext = '.cpp' if lang.lower() == 'c++' else '.c'
- sub = functools.partial(re.sub, '.pyx$', target_ext)
- self.sources = list(map(sub, self.sources))
-
-
-class Library(Extension):
- """Just like a regular Extension, but built as a library instead"""
+ def _convert_pyx_sources_to_lang(self):
+ """
+ Replace sources with .pyx extensions to sources with the target
+ language extension. This mechanism allows language authors to supply
+ pre-converted sources but to prefer the .pyx sources.
+ """
+ if _have_cython():
+ # the build has Cython, so allow it to compile the .pyx files
+ return
+ lang = self.language or ''
+ target_ext = '.cpp' if lang.lower() == 'c++' else '.c'
+ sub = functools.partial(re.sub, '.pyx$', target_ext)
+ self.sources = list(map(sub, self.sources))
+
+
+class Library(Extension):
+ """Just like a regular Extension, but built as a library instead"""
diff --git a/contrib/python/setuptools/py3/setuptools/launch.py b/contrib/python/setuptools/py3/setuptools/launch.py
index 4d0600e539..0208fdf33b 100644
--- a/contrib/python/setuptools/py3/setuptools/launch.py
+++ b/contrib/python/setuptools/py3/setuptools/launch.py
@@ -1,16 +1,16 @@
-"""
-Launch the Python script on the command line after
-setuptools is bootstrapped via import.
-"""
-
-# Note that setuptools gets imported implicitly by the
-# invocation of this script using python -m setuptools.launch
-
-import tokenize
-import sys
-
-
-def run():
+"""
+Launch the Python script on the command line after
+setuptools is bootstrapped via import.
+"""
+
+# Note that setuptools gets imported implicitly by the
+# invocation of this script using python -m setuptools.launch
+
+import tokenize
+import sys
+
+
+def run():
"""
Run the script in sys.argv[1] as if it had
been invoked naturally.
@@ -23,14 +23,14 @@ def run():
__doc__=None,
)
sys.argv[:] = sys.argv[1:]
-
+
open_ = getattr(tokenize, 'open', open)
with open_(script_name) as fid:
script = fid.read()
norm_script = script.replace('\\r\\n', '\\n')
code = compile(norm_script, script_name, 'exec')
exec(code, namespace)
-
-
-if __name__ == '__main__':
+
+
+if __name__ == '__main__':
run()
diff --git a/contrib/python/setuptools/py3/setuptools/package_index.py b/contrib/python/setuptools/py3/setuptools/package_index.py
index 449e684568..270e7f3c91 100644
--- a/contrib/python/setuptools/py3/setuptools/package_index.py
+++ b/contrib/python/setuptools/py3/setuptools/package_index.py
@@ -1,13 +1,13 @@
-"""PyPI and direct package downloading"""
-import sys
-import os
-import re
+"""PyPI and direct package downloading"""
+import sys
+import os
+import re
import io
-import shutil
-import socket
-import base64
-import hashlib
-import itertools
+import shutil
+import socket
+import base64
+import hashlib
+import itertools
import warnings
import configparser
import html
@@ -15,37 +15,37 @@ import http.client
import urllib.parse
import urllib.request
import urllib.error
-from functools import wraps
-
+from functools import wraps
+
import setuptools
-from pkg_resources import (
- CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST,
+from pkg_resources import (
+ CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST,
Environment, find_distributions, safe_name, safe_version,
to_filename, Requirement, DEVELOP_DIST, EGG_DIST, parse_version,
-)
-from distutils import log
-from distutils.errors import DistutilsError
-from fnmatch import translate
+)
+from distutils import log
+from distutils.errors import DistutilsError
+from fnmatch import translate
from setuptools.wheel import Wheel
from setuptools.extern.more_itertools import unique_everseen
-
+
EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$')
HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I)
-PYPI_MD5 = re.compile(
+PYPI_MD5 = re.compile(
r'<a href="([^"#]+)">([^<]+)</a>\n\s+\(<a (?:title="MD5 hash"\n\s+)'
r'href="[^?]+\?:action=show_md5&amp;digest=([0-9a-f]{32})">md5</a>\)'
-)
+)
URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match
-EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split()
-
-__all__ = [
- 'PackageIndex', 'distros_for_url', 'parse_bdist_wininst',
- 'interpret_distro_name',
-]
-
-_SOCKET_TIMEOUT = 15
-
+EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split()
+
+__all__ = [
+ 'PackageIndex', 'distros_for_url', 'parse_bdist_wininst',
+ 'interpret_distro_name',
+]
+
+_SOCKET_TIMEOUT = 15
+
_tmpl = "setuptools/{setuptools.__version__} Python-urllib/{py_major}"
user_agent = _tmpl.format(
py_major='{}.{}'.format(*sys.version_info), setuptools=setuptools)
@@ -60,62 +60,62 @@ def parse_requirement_arg(spec):
) from e
-def parse_bdist_wininst(name):
- """Return (base,pyversion) or (None,None) for possible .exe name"""
-
- lower = name.lower()
- base, py_ver, plat = None, None, None
-
- if lower.endswith('.exe'):
- if lower.endswith('.win32.exe'):
- base = name[:-10]
- plat = 'win32'
+def parse_bdist_wininst(name):
+ """Return (base,pyversion) or (None,None) for possible .exe name"""
+
+ lower = name.lower()
+ base, py_ver, plat = None, None, None
+
+ if lower.endswith('.exe'):
+ if lower.endswith('.win32.exe'):
+ base = name[:-10]
+ plat = 'win32'
elif lower.startswith('.win32-py', -16):
- py_ver = name[-7:-4]
- base = name[:-16]
- plat = 'win32'
- elif lower.endswith('.win-amd64.exe'):
- base = name[:-14]
- plat = 'win-amd64'
+ py_ver = name[-7:-4]
+ base = name[:-16]
+ plat = 'win32'
+ elif lower.endswith('.win-amd64.exe'):
+ base = name[:-14]
+ plat = 'win-amd64'
elif lower.startswith('.win-amd64-py', -20):
- py_ver = name[-7:-4]
- base = name[:-20]
- plat = 'win-amd64'
+ py_ver = name[-7:-4]
+ base = name[:-20]
+ plat = 'win-amd64'
return base, py_ver, plat
-
-
-def egg_info_for_url(url):
- parts = urllib.parse.urlparse(url)
- scheme, server, path, parameters, query, fragment = parts
- base = urllib.parse.unquote(path.split('/')[-1])
+
+
+def egg_info_for_url(url):
+ parts = urllib.parse.urlparse(url)
+ scheme, server, path, parameters, query, fragment = parts
+ base = urllib.parse.unquote(path.split('/')[-1])
if server == 'sourceforge.net' and base == 'download': # XXX Yuck
- base = urllib.parse.unquote(path.split('/')[-2])
+ base = urllib.parse.unquote(path.split('/')[-2])
if '#' in base:
base, fragment = base.split('#', 1)
return base, fragment
-
-def distros_for_url(url, metadata=None):
- """Yield egg or source distribution objects that might be found at a URL"""
- base, fragment = egg_info_for_url(url)
+
+def distros_for_url(url, metadata=None):
+ """Yield egg or source distribution objects that might be found at a URL"""
+ base, fragment = egg_info_for_url(url)
for dist in distros_for_location(url, base, metadata):
yield dist
- if fragment:
- match = EGG_FRAGMENT.match(fragment)
- if match:
- for dist in interpret_distro_name(
+ if fragment:
+ match = EGG_FRAGMENT.match(fragment)
+ if match:
+ for dist in interpret_distro_name(
url, match.group(1), metadata, precedence=CHECKOUT_DIST
- ):
- yield dist
-
+ ):
+ yield dist
+
-def distros_for_location(location, basename, metadata=None):
- """Yield egg or source distribution objects based on basename"""
- if basename.endswith('.egg.zip'):
+def distros_for_location(location, basename, metadata=None):
+ """Yield egg or source distribution objects based on basename"""
+ if basename.endswith('.egg.zip'):
basename = basename[:-4] # strip the .zip
- if basename.endswith('.egg') and '-' in basename:
- # only one, unambiguous interpretation
- return [Distribution.from_location(location, basename, metadata)]
+ if basename.endswith('.egg') and '-' in basename:
+ # only one, unambiguous interpretation
+ return [Distribution.from_location(location, basename, metadata)]
if basename.endswith('.whl') and '-' in basename:
wheel = Wheel(basename)
if not wheel.is_compatible():
@@ -127,173 +127,173 @@ def distros_for_location(location, basename, metadata=None):
# Increase priority over eggs.
precedence=EGG_DIST + 1,
)]
- if basename.endswith('.exe'):
- win_base, py_ver, platform = parse_bdist_wininst(basename)
- if win_base is not None:
- return interpret_distro_name(
- location, win_base, metadata, py_ver, BINARY_DIST, platform
- )
- # Try source distro extensions (.zip, .tgz, etc.)
- #
- for ext in EXTENSIONS:
- if basename.endswith(ext):
- basename = basename[:-len(ext)]
- return interpret_distro_name(location, basename, metadata)
- return [] # no extension matched
-
-
-def distros_for_filename(filename, metadata=None):
- """Yield possible egg or source distribution objects based on a filename"""
- return distros_for_location(
- normalize_path(filename), os.path.basename(filename), metadata
- )
-
-
-def interpret_distro_name(
- location, basename, metadata, py_version=None, precedence=SOURCE_DIST,
- platform=None
+ if basename.endswith('.exe'):
+ win_base, py_ver, platform = parse_bdist_wininst(basename)
+ if win_base is not None:
+ return interpret_distro_name(
+ location, win_base, metadata, py_ver, BINARY_DIST, platform
+ )
+ # Try source distro extensions (.zip, .tgz, etc.)
+ #
+ for ext in EXTENSIONS:
+ if basename.endswith(ext):
+ basename = basename[:-len(ext)]
+ return interpret_distro_name(location, basename, metadata)
+ return [] # no extension matched
+
+
+def distros_for_filename(filename, metadata=None):
+ """Yield possible egg or source distribution objects based on a filename"""
+ return distros_for_location(
+ normalize_path(filename), os.path.basename(filename), metadata
+ )
+
+
+def interpret_distro_name(
+ location, basename, metadata, py_version=None, precedence=SOURCE_DIST,
+ platform=None
):
- """Generate alternative interpretations of a source distro name
-
- Note: if `location` is a filesystem filename, you should call
- ``pkg_resources.normalize_path()`` on it before passing it to this
- routine!
- """
- # Generate alternative interpretations of a source distro name
- # Because some packages are ambiguous as to name/versions split
- # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc.
+ """Generate alternative interpretations of a source distro name
+
+ Note: if `location` is a filesystem filename, you should call
+ ``pkg_resources.normalize_path()`` on it before passing it to this
+ routine!
+ """
+ # Generate alternative interpretations of a source distro name
+ # Because some packages are ambiguous as to name/versions split
+ # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc.
# So, we generate each possible interpretation (e.g. "adns, python-1.1.0"
- # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice,
- # the spurious interpretations should be ignored, because in the event
- # there's also an "adns" package, the spurious "python-1.1.0" version will
- # compare lower than any numeric version number, and is therefore unlikely
- # to match a request for it. It's still a potential problem, though, and
- # in the long run PyPI and the distutils should go for "safe" names and
- # versions in distribution archive names (sdist and bdist).
-
- parts = basename.split('-')
+ # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice,
+ # the spurious interpretations should be ignored, because in the event
+ # there's also an "adns" package, the spurious "python-1.1.0" version will
+ # compare lower than any numeric version number, and is therefore unlikely
+ # to match a request for it. It's still a potential problem, though, and
+ # in the long run PyPI and the distutils should go for "safe" names and
+ # versions in distribution archive names (sdist and bdist).
+
+ parts = basename.split('-')
if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]):
- # it is a bdist_dumb, not an sdist -- bail out
- return
-
+ # it is a bdist_dumb, not an sdist -- bail out
+ return
+
for p in range(1, len(parts) + 1):
- yield Distribution(
- location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]),
+ yield Distribution(
+ location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]),
py_version=py_version, precedence=precedence,
platform=platform
- )
-
+ )
+
-def unique_values(func):
- """
- Wrap a function returning an iterable such that the resulting iterable
- only ever yields unique items.
- """
+def unique_values(func):
+ """
+ Wrap a function returning an iterable such that the resulting iterable
+ only ever yields unique items.
+ """
- @wraps(func)
- def wrapper(*args, **kwargs):
- return unique_everseen(func(*args, **kwargs))
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ return unique_everseen(func(*args, **kwargs))
+
+ return wrapper
- return wrapper
-
REL = re.compile(r"""<([^>]*\srel\s*=\s*['"]?([^'">]+)[^>]*)>""", re.I)
-# this line is here to fix emacs' cruddy broken syntax highlighting
-
-
-@unique_values
-def find_external_links(url, page):
- """Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
-
- for match in REL.finditer(page):
- tag, rel = match.groups()
- rels = set(map(str.strip, rel.lower().split(',')))
- if 'homepage' in rels or 'download' in rels:
- for match in HREF.finditer(tag):
- yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
-
- for tag in ("<th>Home Page", "<th>Download URL"):
- pos = page.find(tag)
+# this line is here to fix emacs' cruddy broken syntax highlighting
+
+
+@unique_values
+def find_external_links(url, page):
+ """Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
+
+ for match in REL.finditer(page):
+ tag, rel = match.groups()
+ rels = set(map(str.strip, rel.lower().split(',')))
+ if 'homepage' in rels or 'download' in rels:
+ for match in HREF.finditer(tag):
+ yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
+
+ for tag in ("<th>Home Page", "<th>Download URL"):
+ pos = page.find(tag)
if pos != -1:
match = HREF.search(page, pos)
- if match:
- yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
-
-
+ if match:
+ yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
+
+
class ContentChecker:
- """
- A null content checker that defines the interface for checking content
- """
-
- def feed(self, block):
- """
- Feed a block of data to the hash.
- """
- return
-
- def is_valid(self):
- """
- Check the hash. Return False if validation fails.
- """
- return True
-
- def report(self, reporter, template):
- """
- Call reporter with information about the checker (hash name)
- substituted into the template.
- """
- return
-
-
-class HashChecker(ContentChecker):
- pattern = re.compile(
- r'(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)='
- r'(?P<expected>[a-f0-9]+)'
- )
-
- def __init__(self, hash_name, expected):
- self.hash_name = hash_name
- self.hash = hashlib.new(hash_name)
- self.expected = expected
-
- @classmethod
- def from_url(cls, url):
- "Construct a (possibly null) ContentChecker from a URL"
- fragment = urllib.parse.urlparse(url)[-1]
- if not fragment:
- return ContentChecker()
- match = cls.pattern.search(fragment)
- if not match:
- return ContentChecker()
- return cls(**match.groupdict())
-
- def feed(self, block):
- self.hash.update(block)
-
- def is_valid(self):
- return self.hash.hexdigest() == self.expected
-
- def report(self, reporter, template):
- msg = template % self.hash_name
- return reporter(msg)
-
-
-class PackageIndex(Environment):
- """A distribution index that scans web pages for download URLs"""
-
- def __init__(
+ """
+ A null content checker that defines the interface for checking content
+ """
+
+ def feed(self, block):
+ """
+ Feed a block of data to the hash.
+ """
+ return
+
+ def is_valid(self):
+ """
+ Check the hash. Return False if validation fails.
+ """
+ return True
+
+ def report(self, reporter, template):
+ """
+ Call reporter with information about the checker (hash name)
+ substituted into the template.
+ """
+ return
+
+
+class HashChecker(ContentChecker):
+ pattern = re.compile(
+ r'(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)='
+ r'(?P<expected>[a-f0-9]+)'
+ )
+
+ def __init__(self, hash_name, expected):
+ self.hash_name = hash_name
+ self.hash = hashlib.new(hash_name)
+ self.expected = expected
+
+ @classmethod
+ def from_url(cls, url):
+ "Construct a (possibly null) ContentChecker from a URL"
+ fragment = urllib.parse.urlparse(url)[-1]
+ if not fragment:
+ return ContentChecker()
+ match = cls.pattern.search(fragment)
+ if not match:
+ return ContentChecker()
+ return cls(**match.groupdict())
+
+ def feed(self, block):
+ self.hash.update(block)
+
+ def is_valid(self):
+ return self.hash.hexdigest() == self.expected
+
+ def report(self, reporter, template):
+ msg = template % self.hash_name
+ return reporter(msg)
+
+
+class PackageIndex(Environment):
+ """A distribution index that scans web pages for download URLs"""
+
+ def __init__(
self, index_url="https://pypi.org/simple/", hosts=('*',),
- ca_bundle=None, verify_ssl=True, *args, **kw
+ ca_bundle=None, verify_ssl=True, *args, **kw
):
Environment.__init__(self, *args, **kw)
self.index_url = index_url + "/" [:not index_url.endswith('/')]
- self.scanned_urls = {}
- self.fetched_urls = {}
- self.package_pages = {}
+ self.scanned_urls = {}
+ self.fetched_urls = {}
+ self.package_pages = {}
self.allows = re.compile('|'.join(map(translate, hosts))).match
- self.to_scan = []
+ self.to_scan = []
self.opener = urllib.request.urlopen
-
+
def add(self, dist):
# ignore invalid versions
try:
@@ -304,29 +304,29 @@ class PackageIndex(Environment):
# FIXME: 'PackageIndex.process_url' is too complex (14)
def process_url(self, url, retrieve=False): # noqa: C901
- """Evaluate a URL as a possible download, and maybe retrieve it"""
- if url in self.scanned_urls and not retrieve:
- return
- self.scanned_urls[url] = True
- if not URL_SCHEME(url):
- self.process_filename(url)
- return
- else:
- dists = list(distros_for_url(url))
- if dists:
- if not self.url_ok(url):
- return
- self.debug("Found link: %s", url)
-
- if dists or not retrieve or url in self.fetched_urls:
- list(map(self.add, dists))
- return # don't need the actual page
-
- if not self.url_ok(url):
- self.fetched_urls[url] = True
- return
-
- self.info("Reading %s", url)
+ """Evaluate a URL as a possible download, and maybe retrieve it"""
+ if url in self.scanned_urls and not retrieve:
+ return
+ self.scanned_urls[url] = True
+ if not URL_SCHEME(url):
+ self.process_filename(url)
+ return
+ else:
+ dists = list(distros_for_url(url))
+ if dists:
+ if not self.url_ok(url):
+ return
+ self.debug("Found link: %s", url)
+
+ if dists or not retrieve or url in self.fetched_urls:
+ list(map(self.add, dists))
+ return # don't need the actual page
+
+ if not self.url_ok(url):
+ self.fetched_urls[url] = True
+ return
+
+ self.info("Reading %s", url)
self.fetched_urls[url] = True # prevent multiple fetch attempts
tmpl = "Download error on %s: %%s -- Some packages may not be found!"
f = self.open_url(url, tmpl % url)
@@ -334,83 +334,83 @@ class PackageIndex(Environment):
return
if isinstance(f, urllib.error.HTTPError) and f.code == 401:
self.info("Authentication error: %s" % f.msg)
- self.fetched_urls[f.url] = True
- if 'html' not in f.headers.get('content-type', '').lower():
+ self.fetched_urls[f.url] = True
+ if 'html' not in f.headers.get('content-type', '').lower():
f.close() # not html, we can't process it
- return
-
+ return
+
base = f.url # handle redirects
- page = f.read()
+ page = f.read()
if not isinstance(page, str):
# In Python 3 and got bytes but want str.
- if isinstance(f, urllib.error.HTTPError):
- # Errors have no charset, assume latin1:
- charset = 'latin-1'
- else:
- charset = f.headers.get_param('charset') or 'latin-1'
- page = page.decode(charset, "ignore")
- f.close()
- for match in HREF.finditer(page):
- link = urllib.parse.urljoin(base, htmldecode(match.group(1)))
- self.process_url(link)
+ if isinstance(f, urllib.error.HTTPError):
+ # Errors have no charset, assume latin1:
+ charset = 'latin-1'
+ else:
+ charset = f.headers.get_param('charset') or 'latin-1'
+ page = page.decode(charset, "ignore")
+ f.close()
+ for match in HREF.finditer(page):
+ link = urllib.parse.urljoin(base, htmldecode(match.group(1)))
+ self.process_url(link)
if url.startswith(self.index_url) and getattr(f, 'code', None) != 404:
- page = self.process_index(url, page)
-
- def process_filename(self, fn, nested=False):
- # process filenames or directories
- if not os.path.exists(fn):
- self.warn("Not found: %s", fn)
- return
-
- if os.path.isdir(fn) and not nested:
- path = os.path.realpath(fn)
- for item in os.listdir(path):
+ page = self.process_index(url, page)
+
+ def process_filename(self, fn, nested=False):
+ # process filenames or directories
+ if not os.path.exists(fn):
+ self.warn("Not found: %s", fn)
+ return
+
+ if os.path.isdir(fn) and not nested:
+ path = os.path.realpath(fn)
+ for item in os.listdir(path):
self.process_filename(os.path.join(path, item), True)
-
- dists = distros_for_filename(fn)
- if dists:
- self.debug("Found: %s", fn)
- list(map(self.add, dists))
-
- def url_ok(self, url, fatal=False):
- s = URL_SCHEME(url)
+
+ dists = distros_for_filename(fn)
+ if dists:
+ self.debug("Found: %s", fn)
+ list(map(self.add, dists))
+
+ def url_ok(self, url, fatal=False):
+ s = URL_SCHEME(url)
is_file = s and s.group(1).lower() == 'file'
if is_file or self.allows(urllib.parse.urlparse(url)[1]):
- return True
+ return True
msg = (
"\nNote: Bypassing %s (disallowed host; see "
"http://bit.ly/2hrImnY for details).\n")
- if fatal:
- raise DistutilsError(msg % url)
- else:
- self.warn(msg, url)
-
- def scan_egg_links(self, search_path):
- dirs = filter(os.path.isdir, search_path)
- egg_links = (
- (path, entry)
- for path in dirs
- for entry in os.listdir(path)
- if entry.endswith('.egg-link')
- )
- list(itertools.starmap(self.scan_egg_link, egg_links))
-
- def scan_egg_link(self, path, entry):
- with open(os.path.join(path, entry)) as raw_lines:
- # filter non-empty lines
- lines = list(filter(None, map(str.strip, raw_lines)))
-
- if len(lines) != 2:
- # format is not recognized; punt
- return
-
- egg_path, setup_path = lines
-
- for dist in find_distributions(os.path.join(path, egg_path)):
- dist.location = os.path.join(path, *lines)
- dist.precedence = SOURCE_DIST
- self.add(dist)
-
+ if fatal:
+ raise DistutilsError(msg % url)
+ else:
+ self.warn(msg, url)
+
+ def scan_egg_links(self, search_path):
+ dirs = filter(os.path.isdir, search_path)
+ egg_links = (
+ (path, entry)
+ for path in dirs
+ for entry in os.listdir(path)
+ if entry.endswith('.egg-link')
+ )
+ list(itertools.starmap(self.scan_egg_link, egg_links))
+
+ def scan_egg_link(self, path, entry):
+ with open(os.path.join(path, entry)) as raw_lines:
+ # filter non-empty lines
+ lines = list(filter(None, map(str.strip, raw_lines)))
+
+ if len(lines) != 2:
+ # format is not recognized; punt
+ return
+
+ egg_path, setup_path = lines
+
+ for dist in find_distributions(os.path.join(path, egg_path)):
+ dist.location = os.path.join(path, *lines)
+ dist.precedence = SOURCE_DIST
+ self.add(dist)
+
def _scan(self, link):
# Process a URL to see if it's for a package page
NO_MATCH_SENTINEL = None, None
@@ -430,19 +430,19 @@ class PackageIndex(Environment):
return to_filename(pkg), to_filename(ver)
def process_index(self, url, page):
- """Process the contents of a PyPI page"""
+ """Process the contents of a PyPI page"""
- # process an index page into the package-page index
- for match in HREF.finditer(page):
- try:
+ # process an index page into the package-page index
+ for match in HREF.finditer(page):
+ try:
self._scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))
- except ValueError:
- pass
-
+ except ValueError:
+ pass
+
pkg, ver = self._scan(url) # ensure this page is in the page index
if not pkg:
return "" # no sense double-scanning non-package pages
-
+
# process individual package page
for new_url in find_external_links(url, page):
# Process the found URL
@@ -458,165 +458,165 @@ class PackageIndex(Environment):
lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1, 3, 2), page
)
- def need_version_info(self, url):
- self.scan_all(
- "Page at %s links to .py file(s) without version info; an index "
- "scan is required.", url
- )
-
- def scan_all(self, msg=None, *args):
- if self.index_url not in self.fetched_urls:
+ def need_version_info(self, url):
+ self.scan_all(
+ "Page at %s links to .py file(s) without version info; an index "
+ "scan is required.", url
+ )
+
+ def scan_all(self, msg=None, *args):
+ if self.index_url not in self.fetched_urls:
if msg:
self.warn(msg, *args)
- self.info(
- "Scanning index of all packages (this may take a while)"
- )
- self.scan_url(self.index_url)
-
- def find_packages(self, requirement):
+ self.info(
+ "Scanning index of all packages (this may take a while)"
+ )
+ self.scan_url(self.index_url)
+
+ def find_packages(self, requirement):
self.scan_url(self.index_url + requirement.unsafe_name + '/')
-
- if not self.package_pages.get(requirement.key):
- # Fall back to safe version of the name
+
+ if not self.package_pages.get(requirement.key):
+ # Fall back to safe version of the name
self.scan_url(self.index_url + requirement.project_name + '/')
-
- if not self.package_pages.get(requirement.key):
- # We couldn't find the target package, so search the index page too
- self.not_found_in_index(requirement)
-
+
+ if not self.package_pages.get(requirement.key):
+ # We couldn't find the target package, so search the index page too
+ self.not_found_in_index(requirement)
+
for url in list(self.package_pages.get(requirement.key, ())):
- # scan each page that might be related to the desired package
- self.scan_url(url)
-
- def obtain(self, requirement, installer=None):
- self.prescan()
- self.find_packages(requirement)
- for dist in self[requirement.key]:
- if dist in requirement:
- return dist
- self.debug("%s does not match %s", requirement, dist)
+ # scan each page that might be related to the desired package
+ self.scan_url(url)
+
+ def obtain(self, requirement, installer=None):
+ self.prescan()
+ self.find_packages(requirement)
+ for dist in self[requirement.key]:
+ if dist in requirement:
+ return dist
+ self.debug("%s does not match %s", requirement, dist)
return super(PackageIndex, self).obtain(requirement, installer)
-
- def check_hash(self, checker, filename, tfp):
- """
- checker is a ContentChecker
- """
+
+ def check_hash(self, checker, filename, tfp):
+ """
+ checker is a ContentChecker
+ """
checker.report(
self.debug,
- "Validating %%s checksum for %s" % filename)
- if not checker.is_valid():
- tfp.close()
- os.unlink(filename)
- raise DistutilsError(
- "%s validation failed for %s; "
+ "Validating %%s checksum for %s" % filename)
+ if not checker.is_valid():
+ tfp.close()
+ os.unlink(filename)
+ raise DistutilsError(
+ "%s validation failed for %s; "
"possible download problem?"
% (checker.hash.name, os.path.basename(filename))
- )
-
- def add_find_links(self, urls):
- """Add `urls` to the list that will be prescanned for searches"""
- for url in urls:
- if (
+ )
+
+ def add_find_links(self, urls):
+ """Add `urls` to the list that will be prescanned for searches"""
+ for url in urls:
+ if (
self.to_scan is None # if we have already "gone online"
or not URL_SCHEME(url) # or it's a local file/directory
- or url.startswith('file:')
+ or url.startswith('file:')
or list(distros_for_url(url)) # or a direct package link
- ):
- # then go ahead and process it now
- self.scan_url(url)
- else:
- # otherwise, defer retrieval till later
- self.to_scan.append(url)
-
- def prescan(self):
- """Scan urls scheduled for prescanning (e.g. --find-links)"""
- if self.to_scan:
- list(map(self.scan_url, self.to_scan))
+ ):
+ # then go ahead and process it now
+ self.scan_url(url)
+ else:
+ # otherwise, defer retrieval till later
+ self.to_scan.append(url)
+
+ def prescan(self):
+ """Scan urls scheduled for prescanning (e.g. --find-links)"""
+ if self.to_scan:
+ list(map(self.scan_url, self.to_scan))
self.to_scan = None # from now on, go ahead and process immediately
-
- def not_found_in_index(self, requirement):
+
+ def not_found_in_index(self, requirement):
if self[requirement.key]: # we've seen at least one distro
- meth, msg = self.info, "Couldn't retrieve index page for %r"
+ meth, msg = self.info, "Couldn't retrieve index page for %r"
else: # no distros seen for this name, might be misspelled
meth, msg = (
self.warn,
- "Couldn't find index page for %r (maybe misspelled?)")
- meth(msg, requirement.unsafe_name)
- self.scan_all()
-
- def download(self, spec, tmpdir):
- """Locate and/or download `spec` to `tmpdir`, returning a local path
-
- `spec` may be a ``Requirement`` object, or a string containing a URL,
- an existing local filename, or a project/version requirement spec
- (i.e. the string form of a ``Requirement`` object). If it is the URL
- of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one
- that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is
- automatically created alongside the downloaded file.
-
- If `spec` is a ``Requirement`` object or a string containing a
- project/version requirement spec, this method returns the location of
- a matching distribution (possibly after downloading it to `tmpdir`).
- If `spec` is a locally existing file or directory name, it is simply
- returned unchanged. If `spec` is a URL, it is downloaded to a subpath
- of `tmpdir`, and the local filename is returned. Various errors may be
- raised if a problem occurs during downloading.
- """
+ "Couldn't find index page for %r (maybe misspelled?)")
+ meth(msg, requirement.unsafe_name)
+ self.scan_all()
+
+ def download(self, spec, tmpdir):
+ """Locate and/or download `spec` to `tmpdir`, returning a local path
+
+ `spec` may be a ``Requirement`` object, or a string containing a URL,
+ an existing local filename, or a project/version requirement spec
+ (i.e. the string form of a ``Requirement`` object). If it is the URL
+ of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one
+ that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is
+ automatically created alongside the downloaded file.
+
+ If `spec` is a ``Requirement`` object or a string containing a
+ project/version requirement spec, this method returns the location of
+ a matching distribution (possibly after downloading it to `tmpdir`).
+ If `spec` is a locally existing file or directory name, it is simply
+ returned unchanged. If `spec` is a URL, it is downloaded to a subpath
+ of `tmpdir`, and the local filename is returned. Various errors may be
+ raised if a problem occurs during downloading.
+ """
if not isinstance(spec, Requirement):
- scheme = URL_SCHEME(spec)
- if scheme:
- # It's a url, download it to tmpdir
- found = self._download_url(scheme.group(1), spec, tmpdir)
- base, fragment = egg_info_for_url(spec)
- if base.endswith('.py'):
+ scheme = URL_SCHEME(spec)
+ if scheme:
+ # It's a url, download it to tmpdir
+ found = self._download_url(scheme.group(1), spec, tmpdir)
+ base, fragment = egg_info_for_url(spec)
+ if base.endswith('.py'):
found = self.gen_setup(found, fragment, tmpdir)
- return found
- elif os.path.exists(spec):
- # Existing file or directory, just return it
- return spec
- else:
+ return found
+ elif os.path.exists(spec):
+ # Existing file or directory, just return it
+ return spec
+ else:
spec = parse_requirement_arg(spec)
return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)
-
+
def fetch_distribution( # noqa: C901 # is too complex (14) # FIXME
- self, requirement, tmpdir, force_scan=False, source=False,
+ self, requirement, tmpdir, force_scan=False, source=False,
develop_ok=False, local_index=None):
- """Obtain a distribution suitable for fulfilling `requirement`
-
- `requirement` must be a ``pkg_resources.Requirement`` instance.
- If necessary, or if the `force_scan` flag is set, the requirement is
- searched for in the (online) package index as well as the locally
- installed packages. If a distribution matching `requirement` is found,
- the returned distribution's ``location`` is the value you would have
- gotten from calling the ``download()`` method with the matching
- distribution's URL or filename. If no matching distribution is found,
- ``None`` is returned.
-
- If the `source` flag is set, only source distributions and source
- checkout links will be considered. Unless the `develop_ok` flag is
- set, development and system eggs (i.e., those using the ``.egg-info``
- format) will be ignored.
- """
- # process a Requirement
- self.info("Searching for %s", requirement)
- skipped = {}
- dist = None
-
- def find(req, env=None):
- if env is None:
- env = self
- # Find a matching distribution; may be called more than once
-
- for dist in env[req.key]:
-
+ """Obtain a distribution suitable for fulfilling `requirement`
+
+ `requirement` must be a ``pkg_resources.Requirement`` instance.
+ If necessary, or if the `force_scan` flag is set, the requirement is
+ searched for in the (online) package index as well as the locally
+ installed packages. If a distribution matching `requirement` is found,
+ the returned distribution's ``location`` is the value you would have
+ gotten from calling the ``download()`` method with the matching
+ distribution's URL or filename. If no matching distribution is found,
+ ``None`` is returned.
+
+ If the `source` flag is set, only source distributions and source
+ checkout links will be considered. Unless the `develop_ok` flag is
+ set, development and system eggs (i.e., those using the ``.egg-info``
+ format) will be ignored.
+ """
+ # process a Requirement
+ self.info("Searching for %s", requirement)
+ skipped = {}
+ dist = None
+
+ def find(req, env=None):
+ if env is None:
+ env = self
+ # Find a matching distribution; may be called more than once
+
+ for dist in env[req.key]:
+
if dist.precedence == DEVELOP_DIST and not develop_ok:
- if dist not in skipped:
+ if dist not in skipped:
self.warn(
"Skipping development or system egg: %s", dist,
)
- skipped[dist] = 1
- continue
-
+ skipped[dist] = 1
+ continue
+
test = (
dist in req
and (dist.precedence <= SOURCE_DIST or not source)
@@ -626,312 +626,312 @@ class PackageIndex(Environment):
dist.download_location = loc
if os.path.exists(dist.download_location):
return dist
-
- if force_scan:
- self.prescan()
- self.find_packages(requirement)
- dist = find(requirement)
-
+
+ if force_scan:
+ self.prescan()
+ self.find_packages(requirement)
+ dist = find(requirement)
+
if not dist and local_index is not None:
dist = find(requirement, local_index)
-
- if dist is None:
- if self.to_scan is not None:
- self.prescan()
- dist = find(requirement)
-
- if dist is None and not force_scan:
- self.find_packages(requirement)
- dist = find(requirement)
-
- if dist is None:
- self.warn(
+
+ if dist is None:
+ if self.to_scan is not None:
+ self.prescan()
+ dist = find(requirement)
+
+ if dist is None and not force_scan:
+ self.find_packages(requirement)
+ dist = find(requirement)
+
+ if dist is None:
+ self.warn(
"No local packages or working download links found for %s%s",
- (source and "a source distribution of " or ""),
- requirement,
- )
- else:
- self.info("Best match: %s", dist)
+ (source and "a source distribution of " or ""),
+ requirement,
+ )
+ else:
+ self.info("Best match: %s", dist)
return dist.clone(location=dist.download_location)
-
- def fetch(self, requirement, tmpdir, force_scan=False, source=False):
- """Obtain a file suitable for fulfilling `requirement`
-
- DEPRECATED; use the ``fetch_distribution()`` method now instead. For
- backward compatibility, this routine is identical but returns the
- ``location`` of the downloaded distribution instead of a distribution
- object.
- """
+
+ def fetch(self, requirement, tmpdir, force_scan=False, source=False):
+ """Obtain a file suitable for fulfilling `requirement`
+
+ DEPRECATED; use the ``fetch_distribution()`` method now instead. For
+ backward compatibility, this routine is identical but returns the
+ ``location`` of the downloaded distribution instead of a distribution
+ object.
+ """
dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
- if dist is not None:
- return dist.location
- return None
-
- def gen_setup(self, filename, fragment, tmpdir):
- match = EGG_FRAGMENT.match(fragment)
- dists = match and [
- d for d in
- interpret_distro_name(filename, match.group(1), None) if d.version
- ] or []
-
+ if dist is not None:
+ return dist.location
+ return None
+
+ def gen_setup(self, filename, fragment, tmpdir):
+ match = EGG_FRAGMENT.match(fragment)
+ dists = match and [
+ d for d in
+ interpret_distro_name(filename, match.group(1), None) if d.version
+ ] or []
+
if len(dists) == 1: # unambiguous ``#egg`` fragment
- basename = os.path.basename(filename)
-
- # Make sure the file has been downloaded to the temp dir.
- if os.path.dirname(filename) != tmpdir:
- dst = os.path.join(tmpdir, basename)
- from setuptools.command.easy_install import samefile
- if not samefile(filename, dst):
- shutil.copy2(filename, dst)
+ basename = os.path.basename(filename)
+
+ # Make sure the file has been downloaded to the temp dir.
+ if os.path.dirname(filename) != tmpdir:
+ dst = os.path.join(tmpdir, basename)
+ from setuptools.command.easy_install import samefile
+ if not samefile(filename, dst):
+ shutil.copy2(filename, dst)
filename = dst
-
- with open(os.path.join(tmpdir, 'setup.py'), 'w') as file:
- file.write(
- "from setuptools import setup\n"
- "setup(name=%r, version=%r, py_modules=[%r])\n"
- % (
- dists[0].project_name, dists[0].version,
- os.path.splitext(basename)[0]
- )
- )
- return filename
-
- elif match:
- raise DistutilsError(
- "Can't unambiguously interpret project/version identifier %r; "
- "any dashes in the name or version should be escaped using "
+
+ with open(os.path.join(tmpdir, 'setup.py'), 'w') as file:
+ file.write(
+ "from setuptools import setup\n"
+ "setup(name=%r, version=%r, py_modules=[%r])\n"
+ % (
+ dists[0].project_name, dists[0].version,
+ os.path.splitext(basename)[0]
+ )
+ )
+ return filename
+
+ elif match:
+ raise DistutilsError(
+ "Can't unambiguously interpret project/version identifier %r; "
+ "any dashes in the name or version should be escaped using "
"underscores. %r" % (fragment, dists)
- )
- else:
- raise DistutilsError(
- "Can't process plain .py files without an '#egg=name-version'"
- " suffix to enable automatic setup script generation."
- )
-
- dl_blocksize = 8192
-
- def _download_to(self, url, filename):
- self.info("Downloading %s", url)
- # Download the file
+ )
+ else:
+ raise DistutilsError(
+ "Can't process plain .py files without an '#egg=name-version'"
+ " suffix to enable automatic setup script generation."
+ )
+
+ dl_blocksize = 8192
+
+ def _download_to(self, url, filename):
+ self.info("Downloading %s", url)
+ # Download the file
fp = None
- try:
- checker = HashChecker.from_url(url)
+ try:
+ checker = HashChecker.from_url(url)
fp = self.open_url(url)
- if isinstance(fp, urllib.error.HTTPError):
- raise DistutilsError(
+ if isinstance(fp, urllib.error.HTTPError):
+ raise DistutilsError(
"Can't download %s: %s %s" % (url, fp.code, fp.msg)
- )
- headers = fp.info()
- blocknum = 0
- bs = self.dl_blocksize
- size = -1
- if "content-length" in headers:
- # Some servers return multiple Content-Length headers :(
+ )
+ headers = fp.info()
+ blocknum = 0
+ bs = self.dl_blocksize
+ size = -1
+ if "content-length" in headers:
+ # Some servers return multiple Content-Length headers :(
sizes = headers.get_all('Content-Length')
- size = max(map(int, sizes))
- self.reporthook(url, filename, blocknum, bs, size)
+ size = max(map(int, sizes))
+ self.reporthook(url, filename, blocknum, bs, size)
with open(filename, 'wb') as tfp:
- while True:
- block = fp.read(bs)
- if block:
- checker.feed(block)
- tfp.write(block)
- blocknum += 1
- self.reporthook(url, filename, blocknum, bs, size)
- else:
- break
- self.check_hash(checker, filename, tfp)
- return headers
- finally:
+ while True:
+ block = fp.read(bs)
+ if block:
+ checker.feed(block)
+ tfp.write(block)
+ blocknum += 1
+ self.reporthook(url, filename, blocknum, bs, size)
+ else:
+ break
+ self.check_hash(checker, filename, tfp)
+ return headers
+ finally:
if fp:
fp.close()
-
- def reporthook(self, url, filename, blocknum, blksize, size):
+
+ def reporthook(self, url, filename, blocknum, blksize, size):
pass # no-op
-
+
# FIXME:
def open_url(self, url, warning=None): # noqa: C901 # is too complex (12)
- if url.startswith('file:'):
- return local_open(url)
- try:
- return open_with_auth(url, self.opener)
+ if url.startswith('file:'):
+ return local_open(url)
+ try:
+ return open_with_auth(url, self.opener)
except (ValueError, http.client.InvalidURL) as v:
- msg = ' '.join([str(arg) for arg in v.args])
- if warning:
- self.warn(warning, msg)
- else:
+ msg = ' '.join([str(arg) for arg in v.args])
+ if warning:
+ self.warn(warning, msg)
+ else:
raise DistutilsError('%s %s' % (url, msg)) from v
- except urllib.error.HTTPError as v:
- return v
- except urllib.error.URLError as v:
- if warning:
- self.warn(warning, v.reason)
- else:
- raise DistutilsError("Download error for %s: %s"
+ except urllib.error.HTTPError as v:
+ return v
+ except urllib.error.URLError as v:
+ if warning:
+ self.warn(warning, v.reason)
+ else:
+ raise DistutilsError("Download error for %s: %s"
% (url, v.reason)) from v
except http.client.BadStatusLine as v:
- if warning:
- self.warn(warning, v.line)
- else:
- raise DistutilsError(
- '%s returned a bad status line. The server might be '
- 'down, %s' %
- (url, v.line)
+ if warning:
+ self.warn(warning, v.line)
+ else:
+ raise DistutilsError(
+ '%s returned a bad status line. The server might be '
+ 'down, %s' %
+ (url, v.line)
) from v
except (http.client.HTTPException, socket.error) as v:
- if warning:
- self.warn(warning, v)
- else:
- raise DistutilsError("Download error for %s: %s"
+ if warning:
+ self.warn(warning, v)
+ else:
+ raise DistutilsError("Download error for %s: %s"
% (url, v)) from v
-
- def _download_url(self, scheme, url, tmpdir):
- # Determine download filename
- #
- name, fragment = egg_info_for_url(url)
- if name:
- while '..' in name:
+
+ def _download_url(self, scheme, url, tmpdir):
+ # Determine download filename
+ #
+ name, fragment = egg_info_for_url(url)
+ if name:
+ while '..' in name:
name = name.replace('..', '.').replace('\\', '_')
- else:
+ else:
name = "__downloaded__" # default if URL has no path contents
-
- if name.endswith('.egg.zip'):
+
+ if name.endswith('.egg.zip'):
name = name[:-4] # strip the extra .zip before download
-
+
filename = os.path.join(tmpdir, name)
-
- # Download the file
- #
+
+ # Download the file
+ #
if scheme == 'svn' or scheme.startswith('svn+'):
- return self._download_svn(url, filename)
+ return self._download_svn(url, filename)
elif scheme == 'git' or scheme.startswith('git+'):
- return self._download_git(url, filename)
- elif scheme.startswith('hg+'):
- return self._download_hg(url, filename)
+ return self._download_git(url, filename)
+ elif scheme.startswith('hg+'):
+ return self._download_hg(url, filename)
elif scheme == 'file':
- return urllib.request.url2pathname(urllib.parse.urlparse(url)[2])
- else:
+ return urllib.request.url2pathname(urllib.parse.urlparse(url)[2])
+ else:
self.url_ok(url, True) # raises error if not allowed
- return self._attempt_download(url, filename)
-
- def scan_url(self, url):
- self.process_url(url, True)
-
- def _attempt_download(self, url, filename):
- headers = self._download_to(url, filename)
+ return self._attempt_download(url, filename)
+
+ def scan_url(self, url):
+ self.process_url(url, True)
+
+ def _attempt_download(self, url, filename):
+ headers = self._download_to(url, filename)
if 'html' in headers.get('content-type', '').lower():
- return self._download_html(url, headers, filename)
- else:
- return filename
-
- def _download_html(self, url, headers, filename):
- file = open(filename)
- for line in file:
- if line.strip():
- # Check for a subversion index page
- if re.search(r'<title>([^- ]+ - )?Revision \d+:', line):
- # it's a subversion index page:
- file.close()
- os.unlink(filename)
- return self._download_svn(url, filename)
+ return self._download_html(url, headers, filename)
+ else:
+ return filename
+
+ def _download_html(self, url, headers, filename):
+ file = open(filename)
+ for line in file:
+ if line.strip():
+ # Check for a subversion index page
+ if re.search(r'<title>([^- ]+ - )?Revision \d+:', line):
+ # it's a subversion index page:
+ file.close()
+ os.unlink(filename)
+ return self._download_svn(url, filename)
break # not an index page
- file.close()
- os.unlink(filename)
+ file.close()
+ os.unlink(filename)
raise DistutilsError("Unexpected HTML page found at " + url)
-
- def _download_svn(self, url, filename):
+
+ def _download_svn(self, url, filename):
warnings.warn("SVN download support is deprecated", UserWarning)
url = url.split('#', 1)[0] # remove any fragment for svn's sake
- creds = ''
- if url.lower().startswith('svn:') and '@' in url:
- scheme, netloc, path, p, q, f = urllib.parse.urlparse(url)
- if not netloc and path.startswith('//') and '/' in path[2:]:
+ creds = ''
+ if url.lower().startswith('svn:') and '@' in url:
+ scheme, netloc, path, p, q, f = urllib.parse.urlparse(url)
+ if not netloc and path.startswith('//') and '/' in path[2:]:
netloc, path = path[2:].split('/', 1)
auth, host = _splituser(netloc)
- if auth:
- if ':' in auth:
+ if auth:
+ if ':' in auth:
user, pw = auth.split(':', 1)
- creds = " --username=%s --password=%s" % (user, pw)
- else:
+ creds = " --username=%s --password=%s" % (user, pw)
+ else:
creds = " --username=" + auth
- netloc = host
- parts = scheme, netloc, url, p, q, f
- url = urllib.parse.urlunparse(parts)
- self.info("Doing subversion checkout from %s to %s", url, filename)
- os.system("svn checkout%s -q %s %s" % (creds, url, filename))
- return filename
-
- @staticmethod
- def _vcs_split_rev_from_url(url, pop_prefix=False):
- scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)
-
- scheme = scheme.split('+', 1)[-1]
-
- # Some fragment identification fails
+ netloc = host
+ parts = scheme, netloc, url, p, q, f
+ url = urllib.parse.urlunparse(parts)
+ self.info("Doing subversion checkout from %s to %s", url, filename)
+ os.system("svn checkout%s -q %s %s" % (creds, url, filename))
+ return filename
+
+ @staticmethod
+ def _vcs_split_rev_from_url(url, pop_prefix=False):
+ scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)
+
+ scheme = scheme.split('+', 1)[-1]
+
+ # Some fragment identification fails
path = path.split('#', 1)[0]
-
- rev = None
- if '@' in path:
- path, rev = path.rsplit('@', 1)
-
- # Also, discard fragment
- url = urllib.parse.urlunsplit((scheme, netloc, path, query, ''))
-
- return url, rev
-
- def _download_git(self, url, filename):
+
+ rev = None
+ if '@' in path:
+ path, rev = path.rsplit('@', 1)
+
+ # Also, discard fragment
+ url = urllib.parse.urlunsplit((scheme, netloc, path, query, ''))
+
+ return url, rev
+
+ def _download_git(self, url, filename):
filename = filename.split('#', 1)[0]
- url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
-
- self.info("Doing git clone from %s to %s", url, filename)
- os.system("git clone --quiet %s %s" % (url, filename))
-
- if rev is not None:
- self.info("Checking out %s", rev)
+ url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
+
+ self.info("Doing git clone from %s to %s", url, filename)
+ os.system("git clone --quiet %s %s" % (url, filename))
+
+ if rev is not None:
+ self.info("Checking out %s", rev)
os.system("git -C %s checkout --quiet %s" % (
- filename,
- rev,
- ))
-
- return filename
-
- def _download_hg(self, url, filename):
+ filename,
+ rev,
+ ))
+
+ return filename
+
+ def _download_hg(self, url, filename):
filename = filename.split('#', 1)[0]
- url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
-
- self.info("Doing hg clone from %s to %s", url, filename)
- os.system("hg clone --quiet %s %s" % (url, filename))
-
- if rev is not None:
- self.info("Updating to %s", rev)
+ url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
+
+ self.info("Doing hg clone from %s to %s", url, filename)
+ os.system("hg clone --quiet %s %s" % (url, filename))
+
+ if rev is not None:
+ self.info("Updating to %s", rev)
os.system("hg --cwd %s up -C -r %s -q" % (
- filename,
- rev,
- ))
-
- return filename
-
- def debug(self, msg, *args):
- log.debug(msg, *args)
-
- def info(self, msg, *args):
- log.info(msg, *args)
-
- def warn(self, msg, *args):
- log.warn(msg, *args)
-
-
-# This pattern matches a character entity reference (a decimal numeric
-# references, a hexadecimal numeric reference, or a named reference).
-entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub
-
-
-def decode_entity(match):
+ filename,
+ rev,
+ ))
+
+ return filename
+
+ def debug(self, msg, *args):
+ log.debug(msg, *args)
+
+ def info(self, msg, *args):
+ log.info(msg, *args)
+
+ def warn(self, msg, *args):
+ log.warn(msg, *args)
+
+
+# This pattern matches a character entity reference (a decimal numeric
+# references, a hexadecimal numeric reference, or a named reference).
+entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub
+
+
+def decode_entity(match):
what = match.group(0)
return html.unescape(what)
-
-def htmldecode(text):
+
+def htmldecode(text):
"""
Decode HTML entities in the given text.
@@ -940,145 +940,145 @@ def htmldecode(text):
... '?tokena=A&amp;tokenb=B">package_name-0.1.2.tar.gz')
'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz'
"""
- return entity_sub(decode_entity, text)
-
-
-def socket_timeout(timeout=15):
- def _socket_timeout(func):
- def _socket_timeout(*args, **kwargs):
- old_timeout = socket.getdefaulttimeout()
- socket.setdefaulttimeout(timeout)
- try:
- return func(*args, **kwargs)
- finally:
- socket.setdefaulttimeout(old_timeout)
-
- return _socket_timeout
-
- return _socket_timeout
-
-
-def _encode_auth(auth):
- """
+ return entity_sub(decode_entity, text)
+
+
+def socket_timeout(timeout=15):
+ def _socket_timeout(func):
+ def _socket_timeout(*args, **kwargs):
+ old_timeout = socket.getdefaulttimeout()
+ socket.setdefaulttimeout(timeout)
+ try:
+ return func(*args, **kwargs)
+ finally:
+ socket.setdefaulttimeout(old_timeout)
+
+ return _socket_timeout
+
+ return _socket_timeout
+
+
+def _encode_auth(auth):
+ """
Encode auth from a URL suitable for an HTTP header.
- >>> str(_encode_auth('username%3Apassword'))
- 'dXNlcm5hbWU6cGFzc3dvcmQ='
-
- Long auth strings should not cause a newline to be inserted.
- >>> long_auth = 'username:' + 'password'*10
- >>> chr(10) in str(_encode_auth(long_auth))
- False
- """
- auth_s = urllib.parse.unquote(auth)
- # convert to bytes
- auth_bytes = auth_s.encode()
+ >>> str(_encode_auth('username%3Apassword'))
+ 'dXNlcm5hbWU6cGFzc3dvcmQ='
+
+ Long auth strings should not cause a newline to be inserted.
+ >>> long_auth = 'username:' + 'password'*10
+ >>> chr(10) in str(_encode_auth(long_auth))
+ False
+ """
+ auth_s = urllib.parse.unquote(auth)
+ # convert to bytes
+ auth_bytes = auth_s.encode()
encoded_bytes = base64.b64encode(auth_bytes)
- # convert back to a string
- encoded = encoded_bytes.decode()
- # strip the trailing carriage return
+ # convert back to a string
+ encoded = encoded_bytes.decode()
+ # strip the trailing carriage return
return encoded.replace('\n', '')
-
+
class Credential:
- """
- A username/password pair. Use like a namedtuple.
- """
-
- def __init__(self, username, password):
- self.username = username
- self.password = password
-
- def __iter__(self):
- yield self.username
- yield self.password
-
- def __str__(self):
- return '%(username)s:%(password)s' % vars(self)
-
-
-class PyPIConfig(configparser.RawConfigParser):
- def __init__(self):
- """
- Load from ~/.pypirc
- """
- defaults = dict.fromkeys(['username', 'password', 'repository'], '')
- configparser.RawConfigParser.__init__(self, defaults)
-
- rc = os.path.join(os.path.expanduser('~'), '.pypirc')
- if os.path.exists(rc):
- self.read(rc)
-
- @property
- def creds_by_repository(self):
- sections_with_repositories = [
- section for section in self.sections()
- if self.get(section, 'repository').strip()
- ]
-
- return dict(map(self._get_repo_cred, sections_with_repositories))
-
- def _get_repo_cred(self, section):
- repo = self.get(section, 'repository').strip()
- return repo, Credential(
- self.get(section, 'username').strip(),
- self.get(section, 'password').strip(),
- )
-
- def find_credential(self, url):
- """
- If the URL indicated appears to be a repository defined in this
- config, return the credential for that repository.
- """
- for repository, cred in self.creds_by_repository.items():
- if url.startswith(repository):
- return cred
-
-
-def open_with_auth(url, opener=urllib.request.urlopen):
- """Open a urllib2 request, handling HTTP authentication"""
-
+ """
+ A username/password pair. Use like a namedtuple.
+ """
+
+ def __init__(self, username, password):
+ self.username = username
+ self.password = password
+
+ def __iter__(self):
+ yield self.username
+ yield self.password
+
+ def __str__(self):
+ return '%(username)s:%(password)s' % vars(self)
+
+
+class PyPIConfig(configparser.RawConfigParser):
+ def __init__(self):
+ """
+ Load from ~/.pypirc
+ """
+ defaults = dict.fromkeys(['username', 'password', 'repository'], '')
+ configparser.RawConfigParser.__init__(self, defaults)
+
+ rc = os.path.join(os.path.expanduser('~'), '.pypirc')
+ if os.path.exists(rc):
+ self.read(rc)
+
+ @property
+ def creds_by_repository(self):
+ sections_with_repositories = [
+ section for section in self.sections()
+ if self.get(section, 'repository').strip()
+ ]
+
+ return dict(map(self._get_repo_cred, sections_with_repositories))
+
+ def _get_repo_cred(self, section):
+ repo = self.get(section, 'repository').strip()
+ return repo, Credential(
+ self.get(section, 'username').strip(),
+ self.get(section, 'password').strip(),
+ )
+
+ def find_credential(self, url):
+ """
+ If the URL indicated appears to be a repository defined in this
+ config, return the credential for that repository.
+ """
+ for repository, cred in self.creds_by_repository.items():
+ if url.startswith(repository):
+ return cred
+
+
+def open_with_auth(url, opener=urllib.request.urlopen):
+ """Open a urllib2 request, handling HTTP authentication"""
+
parsed = urllib.parse.urlparse(url)
scheme, netloc, path, params, query, frag = parsed
-
+
# Double scheme does not raise on macOS as revealed by a
- # failing test. We would expect "nonnumeric port". Refs #20.
- if netloc.endswith(':'):
+ # failing test. We would expect "nonnumeric port". Refs #20.
+ if netloc.endswith(':'):
raise http.client.InvalidURL("nonnumeric port: ''")
-
- if scheme in ('http', 'https'):
+
+ if scheme in ('http', 'https'):
auth, address = _splituser(netloc)
- else:
- auth = None
-
- if not auth:
- cred = PyPIConfig().find_credential(url)
- if cred:
- auth = str(cred)
- info = cred.username, url
+ else:
+ auth = None
+
+ if not auth:
+ cred = PyPIConfig().find_credential(url)
+ if cred:
+ auth = str(cred)
+ info = cred.username, url
log.info('Authenticating as %s for %s (from .pypirc)', *info)
-
- if auth:
- auth = "Basic " + _encode_auth(auth)
+
+ if auth:
+ auth = "Basic " + _encode_auth(auth)
parts = scheme, address, path, params, query, frag
- new_url = urllib.parse.urlunparse(parts)
- request = urllib.request.Request(new_url)
- request.add_header("Authorization", auth)
- else:
- request = urllib.request.Request(url)
-
- request.add_header('User-Agent', user_agent)
- fp = opener(request)
-
- if auth:
- # Put authentication info back into request URL if same host,
- # so that links found on the page will work
- s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)
+ new_url = urllib.parse.urlunparse(parts)
+ request = urllib.request.Request(new_url)
+ request.add_header("Authorization", auth)
+ else:
+ request = urllib.request.Request(url)
+
+ request.add_header('User-Agent', user_agent)
+ fp = opener(request)
+
+ if auth:
+ # Put authentication info back into request URL if same host,
+ # so that links found on the page will work
+ s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)
if s2 == scheme and h2 == address:
- parts = s2, netloc, path2, param2, query2, frag2
- fp.url = urllib.parse.urlunparse(parts)
-
- return fp
-
+ parts = s2, netloc, path2, param2, query2, frag2
+ fp.url = urllib.parse.urlunparse(parts)
+
+ return fp
+
# copy of urllib.parse._splituser from Python 3.8
def _splituser(host):
@@ -1088,40 +1088,40 @@ def _splituser(host):
return (user if delim else None), host
-# adding a timeout to avoid freezing package_index
-open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
-
-
-def fix_sf_url(url):
+# adding a timeout to avoid freezing package_index
+open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
+
+
+def fix_sf_url(url):
return url # backward compatibility
-
-
-def local_open(url):
- """Read a local path, with special support for directories"""
- scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
- filename = urllib.request.url2pathname(path)
- if os.path.isfile(filename):
- return urllib.request.urlopen(url)
- elif path.endswith('/') and os.path.isdir(filename):
- files = []
- for f in os.listdir(filename):
- filepath = os.path.join(filename, f)
- if f == 'index.html':
- with open(filepath, 'r') as fp:
- body = fp.read()
- break
- elif os.path.isdir(filepath):
- f += '/'
- files.append('<a href="{name}">{name}</a>'.format(name=f))
- else:
+
+
+def local_open(url):
+ """Read a local path, with special support for directories"""
+ scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
+ filename = urllib.request.url2pathname(path)
+ if os.path.isfile(filename):
+ return urllib.request.urlopen(url)
+ elif path.endswith('/') and os.path.isdir(filename):
+ files = []
+ for f in os.listdir(filename):
+ filepath = os.path.join(filename, f)
+ if f == 'index.html':
+ with open(filepath, 'r') as fp:
+ body = fp.read()
+ break
+ elif os.path.isdir(filepath):
+ f += '/'
+ files.append('<a href="{name}">{name}</a>'.format(name=f))
+ else:
tmpl = (
"<html><head><title>{url}</title>"
- "</head><body>{files}</body></html>")
- body = tmpl.format(url=url, files='\n'.join(files))
- status, message = 200, "OK"
- else:
- status, message, body = 404, "Path not found", "Not found"
-
- headers = {'content-type': 'text/html'}
+ "</head><body>{files}</body></html>")
+ body = tmpl.format(url=url, files='\n'.join(files))
+ status, message = 200, "OK"
+ else:
+ status, message, body = 404, "Path not found", "Not found"
+
+ headers = {'content-type': 'text/html'}
body_stream = io.StringIO(body)
- return urllib.error.HTTPError(url, status, message, headers, body_stream)
+ return urllib.error.HTTPError(url, status, message, headers, body_stream)
diff --git a/contrib/python/setuptools/py3/setuptools/sandbox.py b/contrib/python/setuptools/py3/setuptools/sandbox.py
index e1673b87e1..034fc80d20 100644
--- a/contrib/python/setuptools/py3/setuptools/sandbox.py
+++ b/contrib/python/setuptools/py3/setuptools/sandbox.py
@@ -1,203 +1,203 @@
-import os
-import sys
-import tempfile
-import operator
-import functools
-import itertools
-import re
-import contextlib
-import pickle
+import os
+import sys
+import tempfile
+import operator
+import functools
+import itertools
+import re
+import contextlib
+import pickle
import textwrap
import builtins
-
+
import pkg_resources
from distutils.errors import DistutilsError
from pkg_resources import working_set
-
-if sys.platform.startswith('java'):
- import org.python.modules.posix.PosixModule as _os
-else:
- _os = sys.modules[os.name]
-try:
- _file = file
-except NameError:
- _file = None
-_open = open
-
-
-__all__ = [
+
+if sys.platform.startswith('java'):
+ import org.python.modules.posix.PosixModule as _os
+else:
+ _os = sys.modules[os.name]
+try:
+ _file = file
+except NameError:
+ _file = None
+_open = open
+
+
+__all__ = [
"AbstractSandbox",
"DirectorySandbox",
"SandboxViolation",
"run_setup",
-]
-
-
-def _execfile(filename, globals, locals=None):
- """
- Python 3 implementation of execfile.
- """
- mode = 'rb'
- with open(filename, mode) as stream:
- script = stream.read()
- if locals is None:
- locals = globals
- code = compile(script, filename, 'exec')
- exec(code, globals, locals)
-
-
-@contextlib.contextmanager
-def save_argv(repl=None):
- saved = sys.argv[:]
- if repl is not None:
- sys.argv[:] = repl
- try:
- yield saved
- finally:
- sys.argv[:] = saved
-
-
-@contextlib.contextmanager
-def save_path():
- saved = sys.path[:]
- try:
- yield saved
- finally:
- sys.path[:] = saved
-
-
-@contextlib.contextmanager
-def override_temp(replacement):
- """
- Monkey-patch tempfile.tempdir with replacement, ensuring it exists
- """
+]
+
+
+def _execfile(filename, globals, locals=None):
+ """
+ Python 3 implementation of execfile.
+ """
+ mode = 'rb'
+ with open(filename, mode) as stream:
+ script = stream.read()
+ if locals is None:
+ locals = globals
+ code = compile(script, filename, 'exec')
+ exec(code, globals, locals)
+
+
+@contextlib.contextmanager
+def save_argv(repl=None):
+ saved = sys.argv[:]
+ if repl is not None:
+ sys.argv[:] = repl
+ try:
+ yield saved
+ finally:
+ sys.argv[:] = saved
+
+
+@contextlib.contextmanager
+def save_path():
+ saved = sys.path[:]
+ try:
+ yield saved
+ finally:
+ sys.path[:] = saved
+
+
+@contextlib.contextmanager
+def override_temp(replacement):
+ """
+ Monkey-patch tempfile.tempdir with replacement, ensuring it exists
+ """
os.makedirs(replacement, exist_ok=True)
-
- saved = tempfile.tempdir
-
- tempfile.tempdir = replacement
-
- try:
- yield
- finally:
- tempfile.tempdir = saved
-
-
-@contextlib.contextmanager
-def pushd(target):
- saved = os.getcwd()
- os.chdir(target)
- try:
- yield saved
- finally:
- os.chdir(saved)
-
-
-class UnpickleableException(Exception):
- """
- An exception representing another Exception that could not be pickled.
- """
-
- @staticmethod
- def dump(type, exc):
- """
- Always return a dumped (pickled) type and exc. If exc can't be pickled,
- wrap it in UnpickleableException first.
- """
- try:
- return pickle.dumps(type), pickle.dumps(exc)
- except Exception:
- # get UnpickleableException inside the sandbox
- from setuptools.sandbox import UnpickleableException as cls
-
- return cls.dump(cls, cls(repr(exc)))
-
-
-class ExceptionSaver:
- """
- A Context Manager that will save an exception, serialized, and restore it
- later.
- """
-
- def __enter__(self):
- return self
-
- def __exit__(self, type, exc, tb):
- if not exc:
- return
-
- # dump the exception
- self._saved = UnpickleableException.dump(type, exc)
- self._tb = tb
-
- # suppress the exception
- return True
-
- def resume(self):
- "restore and re-raise any exception"
-
- if '_saved' not in vars(self):
- return
-
- type, exc = map(pickle.loads, self._saved)
+
+ saved = tempfile.tempdir
+
+ tempfile.tempdir = replacement
+
+ try:
+ yield
+ finally:
+ tempfile.tempdir = saved
+
+
+@contextlib.contextmanager
+def pushd(target):
+ saved = os.getcwd()
+ os.chdir(target)
+ try:
+ yield saved
+ finally:
+ os.chdir(saved)
+
+
+class UnpickleableException(Exception):
+ """
+ An exception representing another Exception that could not be pickled.
+ """
+
+ @staticmethod
+ def dump(type, exc):
+ """
+ Always return a dumped (pickled) type and exc. If exc can't be pickled,
+ wrap it in UnpickleableException first.
+ """
+ try:
+ return pickle.dumps(type), pickle.dumps(exc)
+ except Exception:
+ # get UnpickleableException inside the sandbox
+ from setuptools.sandbox import UnpickleableException as cls
+
+ return cls.dump(cls, cls(repr(exc)))
+
+
+class ExceptionSaver:
+ """
+ A Context Manager that will save an exception, serialized, and restore it
+ later.
+ """
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, exc, tb):
+ if not exc:
+ return
+
+ # dump the exception
+ self._saved = UnpickleableException.dump(type, exc)
+ self._tb = tb
+
+ # suppress the exception
+ return True
+
+ def resume(self):
+ "restore and re-raise any exception"
+
+ if '_saved' not in vars(self):
+ return
+
+ type, exc = map(pickle.loads, self._saved)
raise exc.with_traceback(self._tb)
-
-
-@contextlib.contextmanager
-def save_modules():
- """
- Context in which imported modules are saved.
-
- Translates exceptions internal to the context into the equivalent exception
- outside the context.
- """
- saved = sys.modules.copy()
- with ExceptionSaver() as saved_exc:
- yield saved
-
- sys.modules.update(saved)
- # remove any modules imported since
- del_modules = (
+
+
+@contextlib.contextmanager
+def save_modules():
+ """
+ Context in which imported modules are saved.
+
+ Translates exceptions internal to the context into the equivalent exception
+ outside the context.
+ """
+ saved = sys.modules.copy()
+ with ExceptionSaver() as saved_exc:
+ yield saved
+
+ sys.modules.update(saved)
+ # remove any modules imported since
+ del_modules = (
mod_name
for mod_name in sys.modules
- if mod_name not in saved
- # exclude any encodings modules. See #285
- and not mod_name.startswith('encodings.')
- )
- _clear_modules(del_modules)
-
- saved_exc.resume()
-
-
-def _clear_modules(module_names):
- for mod_name in list(module_names):
- del sys.modules[mod_name]
-
-
-@contextlib.contextmanager
-def save_pkg_resources_state():
- saved = pkg_resources.__getstate__()
- try:
- yield saved
- finally:
- pkg_resources.__setstate__(saved)
-
-
-@contextlib.contextmanager
-def setup_context(setup_dir):
- temp_dir = os.path.join(setup_dir, 'temp')
- with save_pkg_resources_state():
- with save_modules():
- with save_path():
+ if mod_name not in saved
+ # exclude any encodings modules. See #285
+ and not mod_name.startswith('encodings.')
+ )
+ _clear_modules(del_modules)
+
+ saved_exc.resume()
+
+
+def _clear_modules(module_names):
+ for mod_name in list(module_names):
+ del sys.modules[mod_name]
+
+
+@contextlib.contextmanager
+def save_pkg_resources_state():
+ saved = pkg_resources.__getstate__()
+ try:
+ yield saved
+ finally:
+ pkg_resources.__setstate__(saved)
+
+
+@contextlib.contextmanager
+def setup_context(setup_dir):
+ temp_dir = os.path.join(setup_dir, 'temp')
+ with save_pkg_resources_state():
+ with save_modules():
+ with save_path():
hide_setuptools()
- with save_argv():
- with override_temp(temp_dir):
- with pushd(setup_dir):
- # ensure setuptools commands are available
- __import__('setuptools')
- yield
-
-
+ with save_argv():
+ with override_temp(temp_dir):
+ with pushd(setup_dir):
+ # ensure setuptools commands are available
+ __import__('setuptools')
+ yield
+
+
_MODULES_TO_HIDE = {
'setuptools',
'distutils',
@@ -207,78 +207,78 @@ _MODULES_TO_HIDE = {
}
-def _needs_hiding(mod_name):
- """
- >>> _needs_hiding('setuptools')
- True
- >>> _needs_hiding('pkg_resources')
- True
- >>> _needs_hiding('setuptools_plugin')
- False
- >>> _needs_hiding('setuptools.__init__')
- True
- >>> _needs_hiding('distutils')
- True
- >>> _needs_hiding('os')
- False
- >>> _needs_hiding('Cython')
- True
- """
+def _needs_hiding(mod_name):
+ """
+ >>> _needs_hiding('setuptools')
+ True
+ >>> _needs_hiding('pkg_resources')
+ True
+ >>> _needs_hiding('setuptools_plugin')
+ False
+ >>> _needs_hiding('setuptools.__init__')
+ True
+ >>> _needs_hiding('distutils')
+ True
+ >>> _needs_hiding('os')
+ False
+ >>> _needs_hiding('Cython')
+ True
+ """
base_module = mod_name.split('.', 1)[0]
return base_module in _MODULES_TO_HIDE
-
-
-def hide_setuptools():
- """
- Remove references to setuptools' modules from sys.modules to allow the
- invocation to import the most appropriate setuptools. This technique is
- necessary to avoid issues such as #315 where setuptools upgrading itself
- would fail to find a function declared in the metadata.
- """
+
+
+def hide_setuptools():
+ """
+ Remove references to setuptools' modules from sys.modules to allow the
+ invocation to import the most appropriate setuptools. This technique is
+ necessary to avoid issues such as #315 where setuptools upgrading itself
+ would fail to find a function declared in the metadata.
+ """
_distutils_hack = sys.modules.get('_distutils_hack', None)
if _distutils_hack is not None:
_distutils_hack.remove_shim()
- modules = filter(_needs_hiding, sys.modules)
- _clear_modules(modules)
-
-
-def run_setup(setup_script, args):
- """Run a distutils setup script, sandboxed in its directory"""
- setup_dir = os.path.abspath(os.path.dirname(setup_script))
- with setup_context(setup_dir):
- try:
+ modules = filter(_needs_hiding, sys.modules)
+ _clear_modules(modules)
+
+
+def run_setup(setup_script, args):
+ """Run a distutils setup script, sandboxed in its directory"""
+ setup_dir = os.path.abspath(os.path.dirname(setup_script))
+ with setup_context(setup_dir):
+ try:
sys.argv[:] = [setup_script] + list(args)
- sys.path.insert(0, setup_dir)
- # reset to include setup dir, w/clean callback list
- working_set.__init__()
+ sys.path.insert(0, setup_dir)
+ # reset to include setup dir, w/clean callback list
+ working_set.__init__()
working_set.callbacks.append(lambda dist: dist.activate())
with DirectorySandbox(setup_dir):
ns = dict(__file__=setup_script, __name__='__main__')
- _execfile(setup_script, ns)
- except SystemExit as v:
- if v.args and v.args[0]:
- raise
- # Normal exit, just return
-
-
-class AbstractSandbox:
- """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts"""
-
- _active = False
-
- def __init__(self):
- self._attrs = [
+ _execfile(setup_script, ns)
+ except SystemExit as v:
+ if v.args and v.args[0]:
+ raise
+ # Normal exit, just return
+
+
+class AbstractSandbox:
+ """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts"""
+
+ _active = False
+
+ def __init__(self):
+ self._attrs = [
name
for name in dir(_os)
if not name.startswith('_') and hasattr(self, name)
- ]
-
- def _copy(self, source):
- for name in self._attrs:
+ ]
+
+ def _copy(self, source):
+ for name in self._attrs:
setattr(os, name, getattr(source, name))
-
+
def __enter__(self):
self._copy(self)
if _file:
@@ -293,39 +293,39 @@ class AbstractSandbox:
builtins.open = _open
self._copy(_os)
- def run(self, func):
- """Run 'func' under os sandboxing"""
+ def run(self, func):
+ """Run 'func' under os sandboxing"""
with self:
- return func()
-
- def _mk_dual_path_wrapper(name):
+ return func()
+
+ def _mk_dual_path_wrapper(name):
original = getattr(_os, name)
def wrap(self, src, dst, *args, **kw):
- if self._active:
+ if self._active:
src, dst = self._remap_pair(name, src, dst, *args, **kw)
return original(src, dst, *args, **kw)
- return wrap
-
- for name in ["rename", "link", "symlink"]:
+ return wrap
+
+ for name in ["rename", "link", "symlink"]:
if hasattr(_os, name):
locals()[name] = _mk_dual_path_wrapper(name)
-
- def _mk_single_path_wrapper(name, original=None):
+
+ def _mk_single_path_wrapper(name, original=None):
original = original or getattr(_os, name)
def wrap(self, path, *args, **kw):
- if self._active:
+ if self._active:
path = self._remap_input(name, path, *args, **kw)
return original(path, *args, **kw)
- return wrap
-
- if _file:
- _file = _mk_single_path_wrapper('file', _file)
- _open = _mk_single_path_wrapper('open', _open)
- for name in [
+ return wrap
+
+ if _file:
+ _file = _mk_single_path_wrapper('file', _file)
+ _open = _mk_single_path_wrapper('open', _open)
+ for name in [
"stat",
"listdir",
"chdir",
@@ -345,69 +345,69 @@ class AbstractSandbox:
"mknod",
"pathconf",
"access",
- ]:
+ ]:
if hasattr(_os, name):
locals()[name] = _mk_single_path_wrapper(name)
-
- def _mk_single_with_return(name):
+
+ def _mk_single_with_return(name):
original = getattr(_os, name)
def wrap(self, path, *args, **kw):
- if self._active:
+ if self._active:
path = self._remap_input(name, path, *args, **kw)
return self._remap_output(name, original(path, *args, **kw))
return original(path, *args, **kw)
- return wrap
-
- for name in ['readlink', 'tempnam']:
+ return wrap
+
+ for name in ['readlink', 'tempnam']:
if hasattr(_os, name):
locals()[name] = _mk_single_with_return(name)
-
- def _mk_query(name):
+
+ def _mk_query(name):
original = getattr(_os, name)
def wrap(self, *args, **kw):
retval = original(*args, **kw)
- if self._active:
- return self._remap_output(name, retval)
- return retval
+ if self._active:
+ return self._remap_output(name, retval)
+ return retval
+
+ return wrap
- return wrap
-
- for name in ['getcwd', 'tmpnam']:
+ for name in ['getcwd', 'tmpnam']:
if hasattr(_os, name):
locals()[name] = _mk_query(name)
-
+
def _validate_path(self, path):
- """Called to remap or validate any path, whether input or output"""
- return path
-
+ """Called to remap or validate any path, whether input or output"""
+ return path
+
def _remap_input(self, operation, path, *args, **kw):
- """Called for path inputs"""
- return self._validate_path(path)
-
+ """Called for path inputs"""
+ return self._validate_path(path)
+
def _remap_output(self, operation, path):
- """Called for path outputs"""
- return self._validate_path(path)
-
+ """Called for path outputs"""
+ return self._validate_path(path)
+
def _remap_pair(self, operation, src, dst, *args, **kw):
- """Called for path pairs like rename, link, and symlink operations"""
- return (
+ """Called for path pairs like rename, link, and symlink operations"""
+ return (
self._remap_input(operation + '-from', src, *args, **kw),
self._remap_input(operation + '-to', dst, *args, **kw),
- )
-
-
-if hasattr(os, 'devnull'):
+ )
+
+
+if hasattr(os, 'devnull'):
_EXCEPTIONS = [os.devnull]
-else:
- _EXCEPTIONS = []
-
-
-class DirectorySandbox(AbstractSandbox):
- """Restrict operations to a single subdirectory - pseudo-chroot"""
-
+else:
+ _EXCEPTIONS = []
+
+
+class DirectorySandbox(AbstractSandbox):
+ """Restrict operations to a single subdirectory - pseudo-chroot"""
+
write_ops = dict.fromkeys(
[
"open",
@@ -425,106 +425,106 @@ class DirectorySandbox(AbstractSandbox):
"tempnam",
]
)
-
+
_exception_patterns = []
- "exempt writing to paths that match the pattern"
-
- def __init__(self, sandbox, exceptions=_EXCEPTIONS):
- self._sandbox = os.path.normcase(os.path.realpath(sandbox))
+ "exempt writing to paths that match the pattern"
+
+ def __init__(self, sandbox, exceptions=_EXCEPTIONS):
+ self._sandbox = os.path.normcase(os.path.realpath(sandbox))
self._prefix = os.path.join(self._sandbox, '')
- self._exceptions = [
+ self._exceptions = [
os.path.normcase(os.path.realpath(path)) for path in exceptions
- ]
- AbstractSandbox.__init__(self)
-
- def _violation(self, operation, *args, **kw):
- from setuptools.sandbox import SandboxViolation
-
- raise SandboxViolation(operation, args, kw)
-
- if _file:
-
- def _file(self, path, mode='r', *args, **kw):
- if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
- self._violation("file", path, mode, *args, **kw)
+ ]
+ AbstractSandbox.__init__(self)
+
+ def _violation(self, operation, *args, **kw):
+ from setuptools.sandbox import SandboxViolation
+
+ raise SandboxViolation(operation, args, kw)
+
+ if _file:
+
+ def _file(self, path, mode='r', *args, **kw):
+ if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
+ self._violation("file", path, mode, *args, **kw)
return _file(path, mode, *args, **kw)
-
- def _open(self, path, mode='r', *args, **kw):
- if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
- self._violation("open", path, mode, *args, **kw)
+
+ def _open(self, path, mode='r', *args, **kw):
+ if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
+ self._violation("open", path, mode, *args, **kw)
return _open(path, mode, *args, **kw)
-
- def tmpnam(self):
- self._violation("tmpnam")
-
- def _ok(self, path):
- active = self._active
- try:
- self._active = False
- realpath = os.path.normcase(os.path.realpath(path))
- return (
- self._exempted(realpath)
- or realpath == self._sandbox
- or realpath.startswith(self._prefix)
- )
- finally:
- self._active = active
-
- def _exempted(self, filepath):
- start_matches = (
+
+ def tmpnam(self):
+ self._violation("tmpnam")
+
+ def _ok(self, path):
+ active = self._active
+ try:
+ self._active = False
+ realpath = os.path.normcase(os.path.realpath(path))
+ return (
+ self._exempted(realpath)
+ or realpath == self._sandbox
+ or realpath.startswith(self._prefix)
+ )
+ finally:
+ self._active = active
+
+ def _exempted(self, filepath):
+ start_matches = (
filepath.startswith(exception) for exception in self._exceptions
- )
- pattern_matches = (
+ )
+ pattern_matches = (
re.match(pattern, filepath) for pattern in self._exception_patterns
- )
- candidates = itertools.chain(start_matches, pattern_matches)
- return any(candidates)
-
- def _remap_input(self, operation, path, *args, **kw):
- """Called for path inputs"""
- if operation in self.write_ops and not self._ok(path):
- self._violation(operation, os.path.realpath(path), *args, **kw)
- return path
-
- def _remap_pair(self, operation, src, dst, *args, **kw):
- """Called for path pairs like rename, link, and symlink operations"""
- if not self._ok(src) or not self._ok(dst):
- self._violation(operation, src, dst, *args, **kw)
+ )
+ candidates = itertools.chain(start_matches, pattern_matches)
+ return any(candidates)
+
+ def _remap_input(self, operation, path, *args, **kw):
+ """Called for path inputs"""
+ if operation in self.write_ops and not self._ok(path):
+ self._violation(operation, os.path.realpath(path), *args, **kw)
+ return path
+
+ def _remap_pair(self, operation, src, dst, *args, **kw):
+ """Called for path pairs like rename, link, and symlink operations"""
+ if not self._ok(src) or not self._ok(dst):
+ self._violation(operation, src, dst, *args, **kw)
return (src, dst)
-
- def open(self, file, flags, mode=0o777, *args, **kw):
- """Called for low-level os.open()"""
- if flags & WRITE_FLAGS and not self._ok(file):
- self._violation("os.open", file, flags, mode, *args, **kw)
+
+ def open(self, file, flags, mode=0o777, *args, **kw):
+ """Called for low-level os.open()"""
+ if flags & WRITE_FLAGS and not self._ok(file):
+ self._violation("os.open", file, flags, mode, *args, **kw)
return _os.open(file, flags, mode, *args, **kw)
-
-WRITE_FLAGS = functools.reduce(
+
+WRITE_FLAGS = functools.reduce(
operator.or_,
[
getattr(_os, a, 0)
for a in "O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split()
],
-)
-
+)
+
+
+class SandboxViolation(DistutilsError):
+ """A setup script attempted to modify the filesystem outside the sandbox"""
-class SandboxViolation(DistutilsError):
- """A setup script attempted to modify the filesystem outside the sandbox"""
-
tmpl = textwrap.dedent(
"""
SandboxViolation: {cmd}{args!r} {kwargs}
-
+
The package setup script has attempted to modify files on your system
that are not within the EasyInstall build area, and has been aborted.
-
+
This package cannot be safely installed by EasyInstall, and may not
support alternate installation locations even if you run its setup
script by hand. Please inform the package's author and the EasyInstall
maintainers to find out if a fix or workaround is available.
"""
).lstrip()
-
+
def __str__(self):
cmd, args, kwargs = self.args
return self.tmpl.format(**locals())
diff --git a/contrib/python/setuptools/py3/setuptools/script.tmpl b/contrib/python/setuptools/py3/setuptools/script.tmpl
index df8f68d6b4..ff5efbcab3 100644
--- a/contrib/python/setuptools/py3/setuptools/script.tmpl
+++ b/contrib/python/setuptools/py3/setuptools/script.tmpl
@@ -1,3 +1,3 @@
-# EASY-INSTALL-SCRIPT: %(spec)r,%(script_name)r
-__requires__ = %(spec)r
-__import__('pkg_resources').run_script(%(spec)r, %(script_name)r)
+# EASY-INSTALL-SCRIPT: %(spec)r,%(script_name)r
+__requires__ = %(spec)r
+__import__('pkg_resources').run_script(%(spec)r, %(script_name)r)
diff --git a/contrib/python/setuptools/py3/setuptools/unicode_utils.py b/contrib/python/setuptools/py3/setuptools/unicode_utils.py
index 9ab86b9def..e84e65e3e1 100644
--- a/contrib/python/setuptools/py3/setuptools/unicode_utils.py
+++ b/contrib/python/setuptools/py3/setuptools/unicode_utils.py
@@ -1,42 +1,42 @@
-import unicodedata
-import sys
-
-
-# HFS Plus uses decomposed UTF-8
-def decompose(path):
+import unicodedata
+import sys
+
+
+# HFS Plus uses decomposed UTF-8
+def decompose(path):
if isinstance(path, str):
- return unicodedata.normalize('NFD', path)
- try:
- path = path.decode('utf-8')
- path = unicodedata.normalize('NFD', path)
- path = path.encode('utf-8')
- except UnicodeError:
- pass # Not UTF-8
- return path
-
-
-def filesys_decode(path):
- """
- Ensure that the given path is decoded,
- NONE when no expected encoding works
- """
-
+ return unicodedata.normalize('NFD', path)
+ try:
+ path = path.decode('utf-8')
+ path = unicodedata.normalize('NFD', path)
+ path = path.encode('utf-8')
+ except UnicodeError:
+ pass # Not UTF-8
+ return path
+
+
+def filesys_decode(path):
+ """
+ Ensure that the given path is decoded,
+ NONE when no expected encoding works
+ """
+
if isinstance(path, str):
- return path
-
- fs_enc = sys.getfilesystemencoding() or 'utf-8'
- candidates = fs_enc, 'utf-8'
-
- for enc in candidates:
- try:
- return path.decode(enc)
- except UnicodeDecodeError:
- continue
-
-
-def try_encode(string, enc):
- "turn unicode encoding into a functional routine"
- try:
- return string.encode(enc)
- except UnicodeEncodeError:
- return None
+ return path
+
+ fs_enc = sys.getfilesystemencoding() or 'utf-8'
+ candidates = fs_enc, 'utf-8'
+
+ for enc in candidates:
+ try:
+ return path.decode(enc)
+ except UnicodeDecodeError:
+ continue
+
+
+def try_encode(string, enc):
+ "turn unicode encoding into a functional routine"
+ try:
+ return string.encode(enc)
+ except UnicodeEncodeError:
+ return None
diff --git a/contrib/python/setuptools/py3/setuptools/windows_support.py b/contrib/python/setuptools/py3/setuptools/windows_support.py
index a4a389fede..cb977cff95 100644
--- a/contrib/python/setuptools/py3/setuptools/windows_support.py
+++ b/contrib/python/setuptools/py3/setuptools/windows_support.py
@@ -1,29 +1,29 @@
-import platform
-import ctypes
-
-
-def windows_only(func):
- if platform.system() != 'Windows':
- return lambda *args, **kwargs: None
- return func
-
-
-@windows_only
-def hide_file(path):
- """
- Set the hidden attribute on a file or directory.
-
- From http://stackoverflow.com/questions/19622133/
-
- `path` must be text.
- """
- __import__('ctypes.wintypes')
- SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
- SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
- SetFileAttributes.restype = ctypes.wintypes.BOOL
-
- FILE_ATTRIBUTE_HIDDEN = 0x02
-
- ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
- if not ret:
- raise ctypes.WinError()
+import platform
+import ctypes
+
+
+def windows_only(func):
+ if platform.system() != 'Windows':
+ return lambda *args, **kwargs: None
+ return func
+
+
+@windows_only
+def hide_file(path):
+ """
+ Set the hidden attribute on a file or directory.
+
+ From http://stackoverflow.com/questions/19622133/
+
+ `path` must be text.
+ """
+ __import__('ctypes.wintypes')
+ SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
+ SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
+ SetFileAttributes.restype = ctypes.wintypes.BOOL
+
+ FILE_ATTRIBUTE_HIDDEN = 0x02
+
+ ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
+ if not ret:
+ raise ctypes.WinError()
diff --git a/contrib/python/setuptools/py3/ya.make b/contrib/python/setuptools/py3/ya.make
index 4ef4576cde..5682b6f782 100644
--- a/contrib/python/setuptools/py3/ya.make
+++ b/contrib/python/setuptools/py3/ya.make
@@ -1,9 +1,9 @@
PY3_LIBRARY()
-
+
OWNER(borman orivej g:python-contrib)
VERSION(59.7.0)
-
+
LICENSE(MIT)
PEERDIR(
@@ -16,11 +16,11 @@ NO_CHECK_IMPORTS(
setuptools.*
)
-PY_SRCS(
- TOP_LEVEL
+PY_SRCS(
+ TOP_LEVEL
_distutils_hack/__init__.py
_distutils_hack/override.py
- pkg_resources/__init__.py
+ pkg_resources/__init__.py
pkg_resources/_vendor/__init__.py
pkg_resources/_vendor/appdirs.py
pkg_resources/_vendor/packaging/__about__.py
@@ -36,7 +36,7 @@ PY_SRCS(
pkg_resources/_vendor/packaging/version.py
pkg_resources/_vendor/pyparsing.py
pkg_resources/extern/__init__.py
- setuptools/__init__.py
+ setuptools/__init__.py
setuptools/_deprecation_warning.py
setuptools/_distutils/__init__.py
setuptools/_distutils/_msvccompiler.py
@@ -110,54 +110,54 @@ PY_SRCS(
setuptools/_vendor/packaging/utils.py
setuptools/_vendor/packaging/version.py
setuptools/_vendor/pyparsing.py
- setuptools/archive_util.py
+ setuptools/archive_util.py
setuptools/build_meta.py
- setuptools/command/__init__.py
- setuptools/command/alias.py
- setuptools/command/bdist_egg.py
- setuptools/command/bdist_rpm.py
+ setuptools/command/__init__.py
+ setuptools/command/alias.py
+ setuptools/command/bdist_egg.py
+ setuptools/command/bdist_rpm.py
setuptools/command/build_clib.py
- setuptools/command/build_ext.py
- setuptools/command/build_py.py
- setuptools/command/develop.py
+ setuptools/command/build_ext.py
+ setuptools/command/build_py.py
+ setuptools/command/develop.py
setuptools/command/dist_info.py
- setuptools/command/easy_install.py
- setuptools/command/egg_info.py
- setuptools/command/install.py
- setuptools/command/install_egg_info.py
- setuptools/command/install_lib.py
- setuptools/command/install_scripts.py
+ setuptools/command/easy_install.py
+ setuptools/command/egg_info.py
+ setuptools/command/install.py
+ setuptools/command/install_egg_info.py
+ setuptools/command/install_lib.py
+ setuptools/command/install_scripts.py
setuptools/command/py36compat.py
- setuptools/command/register.py
- setuptools/command/rotate.py
- setuptools/command/saveopts.py
- setuptools/command/sdist.py
- setuptools/command/setopt.py
- setuptools/command/test.py
+ setuptools/command/register.py
+ setuptools/command/rotate.py
+ setuptools/command/saveopts.py
+ setuptools/command/sdist.py
+ setuptools/command/setopt.py
+ setuptools/command/test.py
setuptools/command/upload.py
- setuptools/command/upload_docs.py
+ setuptools/command/upload_docs.py
setuptools/config.py
setuptools/dep_util.py
- setuptools/depends.py
- setuptools/dist.py
+ setuptools/depends.py
+ setuptools/dist.py
setuptools/errors.py
- setuptools/extension.py
+ setuptools/extension.py
setuptools/extern/__init__.py
setuptools/glob.py
setuptools/installer.py
- setuptools/launch.py
+ setuptools/launch.py
setuptools/monkey.py
setuptools/msvc.py
setuptools/namespaces.py
- setuptools/package_index.py
+ setuptools/package_index.py
setuptools/py34compat.py
- setuptools/sandbox.py
- setuptools/unicode_utils.py
- setuptools/version.py
+ setuptools/sandbox.py
+ setuptools/unicode_utils.py
+ setuptools/version.py
setuptools/wheel.py
- setuptools/windows_support.py
-)
-
+ setuptools/windows_support.py
+)
+
RESOURCE_FILES(
PREFIX contrib/python/setuptools/py3/
.dist-info/METADATA
@@ -165,4 +165,4 @@ RESOURCE_FILES(
.dist-info/top_level.txt
)
-END()
+END()
diff --git a/contrib/python/setuptools/ya.make b/contrib/python/setuptools/ya.make
index d70489e494..535a2d61fa 100644
--- a/contrib/python/setuptools/ya.make
+++ b/contrib/python/setuptools/ya.make
@@ -1,9 +1,9 @@
PY23_LIBRARY()
-
+
LICENSE(Service-Py23-Proxy)
OWNER(g:python-contrib)
-
+
IF (PYTHON2)
PEERDIR(contrib/python/setuptools/py2)
ELSE()
@@ -13,7 +13,7 @@ ENDIF()
NO_LINT()
END()
-
+
RECURSE(
py2
py3
diff --git a/contrib/python/traitlets/py2/COPYING.md b/contrib/python/traitlets/py2/COPYING.md
index e314a9d376..39ca730a63 100644
--- a/contrib/python/traitlets/py2/COPYING.md
+++ b/contrib/python/traitlets/py2/COPYING.md
@@ -1,62 +1,62 @@
-# Licensing terms
-
-Traitlets is adapted from enthought.traits, Copyright (c) Enthought, Inc.,
-under the terms of the Modified BSD License.
-
-This project is licensed under the terms of the Modified BSD License
-(also known as New or Revised or 3-Clause BSD), as follows:
-
-- Copyright (c) 2001-, IPython Development Team
-
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-Redistributions of source code must retain the above copyright notice, this
-list of conditions and the following disclaimer.
-
-Redistributions in binary form must reproduce the above copyright notice, this
-list of conditions and the following disclaimer in the documentation and/or
-other materials provided with the distribution.
-
-Neither the name of the IPython Development Team nor the names of its
-contributors may be used to endorse or promote products derived from this
-software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-## About the IPython Development Team
-
-The IPython Development Team is the set of all contributors to the IPython project.
-This includes all of the IPython subprojects.
-
-The core team that coordinates development on GitHub can be found here:
-https://github.com/jupyter/.
-
-## Our Copyright Policy
-
-IPython uses a shared copyright model. Each contributor maintains copyright
-over their contributions to IPython. But, it is important to note that these
-contributions are typically only changes to the repositories. Thus, the IPython
-source code, in its entirety is not the copyright of any single person or
-institution. Instead, it is the collective copyright of the entire IPython
-Development Team. If individual contributors want to maintain a record of what
-changes/contributions they have specific copyright on, they should indicate
-their copyright in the commit message of the change, when they commit the
-change to one of the IPython repositories.
-
-With this in mind, the following banner should be used in any source code file
-to indicate the copyright and license terms:
-
- # Copyright (c) IPython Development Team.
- # Distributed under the terms of the Modified BSD License.
+# Licensing terms
+
+Traitlets is adapted from enthought.traits, Copyright (c) Enthought, Inc.,
+under the terms of the Modified BSD License.
+
+This project is licensed under the terms of the Modified BSD License
+(also known as New or Revised or 3-Clause BSD), as follows:
+
+- Copyright (c) 2001-, IPython Development Team
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+
+Redistributions in binary form must reproduce the above copyright notice, this
+list of conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution.
+
+Neither the name of the IPython Development Team nor the names of its
+contributors may be used to endorse or promote products derived from this
+software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+## About the IPython Development Team
+
+The IPython Development Team is the set of all contributors to the IPython project.
+This includes all of the IPython subprojects.
+
+The core team that coordinates development on GitHub can be found here:
+https://github.com/jupyter/.
+
+## Our Copyright Policy
+
+IPython uses a shared copyright model. Each contributor maintains copyright
+over their contributions to IPython. But, it is important to note that these
+contributions are typically only changes to the repositories. Thus, the IPython
+source code, in its entirety is not the copyright of any single person or
+institution. Instead, it is the collective copyright of the entire IPython
+Development Team. If individual contributors want to maintain a record of what
+changes/contributions they have specific copyright on, they should indicate
+their copyright in the commit message of the change, when they commit the
+change to one of the IPython repositories.
+
+With this in mind, the following banner should be used in any source code file
+to indicate the copyright and license terms:
+
+ # Copyright (c) IPython Development Team.
+ # Distributed under the terms of the Modified BSD License.
diff --git a/contrib/python/traitlets/py2/traitlets/__init__.py b/contrib/python/traitlets/py2/traitlets/__init__.py
index 39933e5a79..b609adb565 100644
--- a/contrib/python/traitlets/py2/traitlets/__init__.py
+++ b/contrib/python/traitlets/py2/traitlets/__init__.py
@@ -1,3 +1,3 @@
-from .traitlets import *
-from .utils.importstring import import_item
-from ._version import version_info, __version__
+from .traitlets import *
+from .utils.importstring import import_item
+from ._version import version_info, __version__
diff --git a/contrib/python/traitlets/py2/traitlets/_version.py b/contrib/python/traitlets/py2/traitlets/_version.py
index 6cc5c82a4f..ed16b3c1e1 100644
--- a/contrib/python/traitlets/py2/traitlets/_version.py
+++ b/contrib/python/traitlets/py2/traitlets/_version.py
@@ -1,2 +1,2 @@
version_info = (4, 3, 3)
-__version__ = '.'.join(map(str, version_info))
+__version__ = '.'.join(map(str, version_info))
diff --git a/contrib/python/traitlets/py2/traitlets/config/__init__.py b/contrib/python/traitlets/py2/traitlets/config/__init__.py
index 1531ee5930..0ae7d63171 100644
--- a/contrib/python/traitlets/py2/traitlets/config/__init__.py
+++ b/contrib/python/traitlets/py2/traitlets/config/__init__.py
@@ -1,8 +1,8 @@
-# encoding: utf-8
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from .application import *
-from .configurable import *
-from .loader import Config
+# encoding: utf-8
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from .application import *
+from .configurable import *
+from .loader import Config
diff --git a/contrib/python/traitlets/py2/traitlets/config/application.py b/contrib/python/traitlets/py2/traitlets/config/application.py
index c0467e6c48..d3a4c45e77 100644
--- a/contrib/python/traitlets/py2/traitlets/config/application.py
+++ b/contrib/python/traitlets/py2/traitlets/config/application.py
@@ -1,68 +1,68 @@
-# encoding: utf-8
-"""A base class for a configurable application."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
+# encoding: utf-8
+"""A base class for a configurable application."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
from copy import deepcopy
-import json
-import logging
-import os
-import re
-import sys
+import json
+import logging
+import os
+import re
+import sys
from collections import defaultdict, OrderedDict
-
-from decorator import decorator
-
-from traitlets.config.configurable import Configurable, SingletonConfigurable
-from traitlets.config.loader import (
- KVArgParseConfigLoader, PyFileConfigLoader, Config, ArgumentError, ConfigFileNotFound, JSONFileConfigLoader
-)
-
-from traitlets.traitlets import (
+
+from decorator import decorator
+
+from traitlets.config.configurable import Configurable, SingletonConfigurable
+from traitlets.config.loader import (
+ KVArgParseConfigLoader, PyFileConfigLoader, Config, ArgumentError, ConfigFileNotFound, JSONFileConfigLoader
+)
+
+from traitlets.traitlets import (
Bool, Unicode, List, Enum, Dict, Instance, TraitError, observe, observe_compat, default,
-)
-from ipython_genutils.importstring import import_item
-from ipython_genutils.text import indent, wrap_paragraphs, dedent
-from ipython_genutils import py3compat
-
+)
+from ipython_genutils.importstring import import_item
+from ipython_genutils.text import indent, wrap_paragraphs, dedent
+from ipython_genutils import py3compat
+
import six
-#-----------------------------------------------------------------------------
-# Descriptions for the various sections
-#-----------------------------------------------------------------------------
-
-# merge flags&aliases into options
-option_description = """
-Arguments that take values are actually convenience aliases to full
-Configurables, whose aliases are listed on the help line. For more information
-on full configurables, see '--help-all'.
-""".strip() # trim newlines of front and back
-
-keyvalue_description = """
-Parameters are set from command-line arguments of the form:
-`--Class.trait=value`.
-This line is evaluated in Python, so simple expressions are allowed, e.g.::
-`--C.a='range(3)'` For setting C.a=[0,1,2].
-""".strip() # trim newlines of front and back
-
-# sys.argv can be missing, for example when python is embedded. See the docs
-# for details: http://docs.python.org/2/c-api/intro.html#embedding-python
-if not hasattr(sys, "argv"):
- sys.argv = [""]
-
-subcommand_description = """
-Subcommands are launched as `{app} cmd [args]`. For information on using
-subcommand 'cmd', do: `{app} cmd -h`.
-"""
-# get running program name
-
-#-----------------------------------------------------------------------------
-# Application class
-#-----------------------------------------------------------------------------
-
+#-----------------------------------------------------------------------------
+# Descriptions for the various sections
+#-----------------------------------------------------------------------------
+
+# merge flags&aliases into options
+option_description = """
+Arguments that take values are actually convenience aliases to full
+Configurables, whose aliases are listed on the help line. For more information
+on full configurables, see '--help-all'.
+""".strip() # trim newlines of front and back
+
+keyvalue_description = """
+Parameters are set from command-line arguments of the form:
+`--Class.trait=value`.
+This line is evaluated in Python, so simple expressions are allowed, e.g.::
+`--C.a='range(3)'` For setting C.a=[0,1,2].
+""".strip() # trim newlines of front and back
+
+# sys.argv can be missing, for example when python is embedded. See the docs
+# for details: http://docs.python.org/2/c-api/intro.html#embedding-python
+if not hasattr(sys, "argv"):
+ sys.argv = [""]
+
+subcommand_description = """
+Subcommands are launched as `{app} cmd [args]`. For information on using
+subcommand 'cmd', do: `{app} cmd -h`.
+"""
+# get running program name
+
+#-----------------------------------------------------------------------------
+# Application class
+#-----------------------------------------------------------------------------
+
_envvar = os.environ.get('TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR','')
@@ -74,194 +74,194 @@ else:
raise ValueError("Unsupported value for environment variable: 'TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
-@decorator
-def catch_config_error(method, app, *args, **kwargs):
- """Method decorator for catching invalid config (Trait/ArgumentErrors) during init.
-
- On a TraitError (generally caused by bad config), this will print the trait's
- message, and exit the app.
-
- For use on init methods, to prevent invoking excepthook on invalid input.
- """
- try:
- return method(app, *args, **kwargs)
- except (TraitError, ArgumentError) as e:
- app.print_help()
- app.log.fatal("Bad config encountered during initialization:")
- app.log.fatal(str(e))
- app.log.debug("Config at the time: %s", app.config)
- app.exit(1)
-
-
-class ApplicationError(Exception):
- pass
-
-
-class LevelFormatter(logging.Formatter):
- """Formatter with additional `highlevel` record
-
- This field is empty if log level is less than highlevel_limit,
- otherwise it is formatted with self.highlevel_format.
-
- Useful for adding 'WARNING' to warning messages,
- without adding 'INFO' to info, etc.
- """
- highlevel_limit = logging.WARN
- highlevel_format = " %(levelname)s |"
-
- def format(self, record):
- if record.levelno >= self.highlevel_limit:
- record.highlevel = self.highlevel_format % record.__dict__
- else:
- record.highlevel = ""
- return super(LevelFormatter, self).format(record)
-
-
-class Application(SingletonConfigurable):
- """A singleton application with full configuration support."""
-
- # The name of the application, will usually match the name of the command
- # line application
- name = Unicode(u'application')
-
- # The description of the application that is printed at the beginning
- # of the help.
- description = Unicode(u'This is an application.')
- # default section descriptions
- option_description = Unicode(option_description)
- keyvalue_description = Unicode(keyvalue_description)
- subcommand_description = Unicode(subcommand_description)
-
- python_config_loader_class = PyFileConfigLoader
- json_config_loader_class = JSONFileConfigLoader
-
- # The usage and example string that goes at the end of the help string.
- examples = Unicode()
-
- # A sequence of Configurable subclasses whose config=True attributes will
- # be exposed at the command line.
- classes = []
-
- def _classes_inc_parents(self):
- """Iterate through configurable classes, including configurable parents
-
- Children should always be after parents, and each class should only be
- yielded once.
- """
- seen = set()
- for c in self.classes:
- # We want to sort parents before children, so we reverse the MRO
- for parent in reversed(c.mro()):
- if issubclass(parent, Configurable) and (parent not in seen):
- seen.add(parent)
- yield parent
-
- # The version string of this application.
- version = Unicode(u'0.0')
-
- # the argv used to initialize the application
- argv = List()
-
+@decorator
+def catch_config_error(method, app, *args, **kwargs):
+ """Method decorator for catching invalid config (Trait/ArgumentErrors) during init.
+
+ On a TraitError (generally caused by bad config), this will print the trait's
+ message, and exit the app.
+
+ For use on init methods, to prevent invoking excepthook on invalid input.
+ """
+ try:
+ return method(app, *args, **kwargs)
+ except (TraitError, ArgumentError) as e:
+ app.print_help()
+ app.log.fatal("Bad config encountered during initialization:")
+ app.log.fatal(str(e))
+ app.log.debug("Config at the time: %s", app.config)
+ app.exit(1)
+
+
+class ApplicationError(Exception):
+ pass
+
+
+class LevelFormatter(logging.Formatter):
+ """Formatter with additional `highlevel` record
+
+ This field is empty if log level is less than highlevel_limit,
+ otherwise it is formatted with self.highlevel_format.
+
+ Useful for adding 'WARNING' to warning messages,
+ without adding 'INFO' to info, etc.
+ """
+ highlevel_limit = logging.WARN
+ highlevel_format = " %(levelname)s |"
+
+ def format(self, record):
+ if record.levelno >= self.highlevel_limit:
+ record.highlevel = self.highlevel_format % record.__dict__
+ else:
+ record.highlevel = ""
+ return super(LevelFormatter, self).format(record)
+
+
+class Application(SingletonConfigurable):
+ """A singleton application with full configuration support."""
+
+ # The name of the application, will usually match the name of the command
+ # line application
+ name = Unicode(u'application')
+
+ # The description of the application that is printed at the beginning
+ # of the help.
+ description = Unicode(u'This is an application.')
+ # default section descriptions
+ option_description = Unicode(option_description)
+ keyvalue_description = Unicode(keyvalue_description)
+ subcommand_description = Unicode(subcommand_description)
+
+ python_config_loader_class = PyFileConfigLoader
+ json_config_loader_class = JSONFileConfigLoader
+
+ # The usage and example string that goes at the end of the help string.
+ examples = Unicode()
+
+ # A sequence of Configurable subclasses whose config=True attributes will
+ # be exposed at the command line.
+ classes = []
+
+ def _classes_inc_parents(self):
+ """Iterate through configurable classes, including configurable parents
+
+ Children should always be after parents, and each class should only be
+ yielded once.
+ """
+ seen = set()
+ for c in self.classes:
+ # We want to sort parents before children, so we reverse the MRO
+ for parent in reversed(c.mro()):
+ if issubclass(parent, Configurable) and (parent not in seen):
+ seen.add(parent)
+ yield parent
+
+ # The version string of this application.
+ version = Unicode(u'0.0')
+
+ # the argv used to initialize the application
+ argv = List()
+
# Whether failing to load config files should prevent startup
raise_config_file_errors = Bool(TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR)
- # The log level for the application
- log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'),
- default_value=logging.WARN,
- help="Set the log level by value or name.").tag(config=True)
-
- @observe('log_level')
- @observe_compat
- def _log_level_changed(self, change):
- """Adjust the log level when log_level is set."""
+ # The log level for the application
+ log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'),
+ default_value=logging.WARN,
+ help="Set the log level by value or name.").tag(config=True)
+
+ @observe('log_level')
+ @observe_compat
+ def _log_level_changed(self, change):
+ """Adjust the log level when log_level is set."""
new = change.new
if isinstance(new, six.string_types):
- new = getattr(logging, new)
- self.log_level = new
- self.log.setLevel(new)
+ new = getattr(logging, new)
+ self.log_level = new
+ self.log.setLevel(new)
- _log_formatter_cls = LevelFormatter
+ _log_formatter_cls = LevelFormatter
log_datefmt = Unicode("%Y-%m-%d %H:%M:%S",
- help="The date format used by logging formatters for %(asctime)s"
- ).tag(config=True)
-
- log_format = Unicode("[%(name)s]%(highlevel)s %(message)s",
- help="The Logging format template",
- ).tag(config=True)
-
- @observe('log_datefmt', 'log_format')
- @observe_compat
- def _log_format_changed(self, change):
- """Change the log formatter when log_format is set."""
- _log_handler = self.log.handlers[0]
- _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
- _log_handler.setFormatter(_log_formatter)
-
- @default('log')
- def _log_default(self):
- """Start logging for this application.
-
- The default is to log to stderr using a StreamHandler, if no default
- handler already exists. The log level starts at logging.WARN, but this
- can be adjusted by setting the ``log_level`` attribute.
- """
- log = logging.getLogger(self.__class__.__name__)
- log.setLevel(self.log_level)
- log.propagate = False
- _log = log # copied from Logger.hasHandlers() (new in Python 3.2)
- while _log:
- if _log.handlers:
- return log
- if not _log.propagate:
- break
- else:
- _log = _log.parent
+ help="The date format used by logging formatters for %(asctime)s"
+ ).tag(config=True)
+
+ log_format = Unicode("[%(name)s]%(highlevel)s %(message)s",
+ help="The Logging format template",
+ ).tag(config=True)
+
+ @observe('log_datefmt', 'log_format')
+ @observe_compat
+ def _log_format_changed(self, change):
+ """Change the log formatter when log_format is set."""
+ _log_handler = self.log.handlers[0]
+ _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
+ _log_handler.setFormatter(_log_formatter)
+
+ @default('log')
+ def _log_default(self):
+ """Start logging for this application.
+
+ The default is to log to stderr using a StreamHandler, if no default
+ handler already exists. The log level starts at logging.WARN, but this
+ can be adjusted by setting the ``log_level`` attribute.
+ """
+ log = logging.getLogger(self.__class__.__name__)
+ log.setLevel(self.log_level)
+ log.propagate = False
+ _log = log # copied from Logger.hasHandlers() (new in Python 3.2)
+ while _log:
+ if _log.handlers:
+ return log
+ if not _log.propagate:
+ break
+ else:
+ _log = _log.parent
if sys.executable and sys.executable.endswith('pythonw.exe'):
- # this should really go to a file, but file-logging is only
- # hooked up in parallel applications
- _log_handler = logging.StreamHandler(open(os.devnull, 'w'))
- else:
- _log_handler = logging.StreamHandler()
- _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
- _log_handler.setFormatter(_log_formatter)
- log.addHandler(_log_handler)
- return log
-
- # the alias map for configurables
- aliases = Dict({'log-level' : 'Application.log_level'})
-
- # flags for loading Configurables or store_const style flags
- # flags are loaded from this dict by '--key' flags
- # this must be a dict of two-tuples, the first element being the Config/dict
- # and the second being the help string for the flag
- flags = Dict()
- @observe('flags')
- @observe_compat
- def _flags_changed(self, change):
- """ensure flags dict is valid"""
+ # this should really go to a file, but file-logging is only
+ # hooked up in parallel applications
+ _log_handler = logging.StreamHandler(open(os.devnull, 'w'))
+ else:
+ _log_handler = logging.StreamHandler()
+ _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
+ _log_handler.setFormatter(_log_formatter)
+ log.addHandler(_log_handler)
+ return log
+
+ # the alias map for configurables
+ aliases = Dict({'log-level' : 'Application.log_level'})
+
+ # flags for loading Configurables or store_const style flags
+ # flags are loaded from this dict by '--key' flags
+ # this must be a dict of two-tuples, the first element being the Config/dict
+ # and the second being the help string for the flag
+ flags = Dict()
+ @observe('flags')
+ @observe_compat
+ def _flags_changed(self, change):
+ """ensure flags dict is valid"""
new = change.new
- for key, value in new.items():
- assert len(value) == 2, "Bad flag: %r:%s" % (key, value)
- assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s" % (key, value)
+ for key, value in new.items():
+ assert len(value) == 2, "Bad flag: %r:%s" % (key, value)
+ assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s" % (key, value)
assert isinstance(value[1], six.string_types), "Bad flag: %r:%s" % (key, value)
-
-
- # subcommands for launching other applications
- # if this is not empty, this will be a parent Application
- # this must be a dict of two-tuples,
- # the first element being the application class/import string
- # and the second being the help string for the subcommand
- subcommands = Dict()
- # parse_command_line will initialize a subapp, if requested
- subapp = Instance('traitlets.config.application.Application', allow_none=True)
-
- # extra command-line arguments that don't set config values
- extra_args = List(Unicode())
-
+
+
+ # subcommands for launching other applications
+ # if this is not empty, this will be a parent Application
+ # this must be a dict of two-tuples,
+ # the first element being the application class/import string
+ # and the second being the help string for the subcommand
+ subcommands = Dict()
+ # parse_command_line will initialize a subapp, if requested
+ subapp = Instance('traitlets.config.application.Application', allow_none=True)
+
+ # extra command-line arguments that don't set config values
+ extra_args = List(Unicode())
+
cli_config = Instance(Config, (), {},
help="""The subset of our configuration that came from the command-line
-
+
We re-load this configuration after loading config files,
to ensure that it maintains highest priority.
"""
@@ -269,10 +269,10 @@ class Application(SingletonConfigurable):
_loaded_config_files = List()
- def __init__(self, **kwargs):
- SingletonConfigurable.__init__(self, **kwargs)
- # Ensure my class is in self.classes, so my attributes appear in command line
- # options and config files.
+ def __init__(self, **kwargs):
+ SingletonConfigurable.__init__(self, **kwargs)
+ # Ensure my class is in self.classes, so my attributes appear in command line
+ # options and config files.
cls = self.__class__
if cls not in self.classes:
if self.classes is cls.classes:
@@ -281,302 +281,302 @@ class Application(SingletonConfigurable):
else:
self.classes.insert(0, self.__class__)
- @observe('config')
- @observe_compat
- def _config_changed(self, change):
- super(Application, self)._config_changed(change)
- self.log.debug('Config changed:')
+ @observe('config')
+ @observe_compat
+ def _config_changed(self, change):
+ super(Application, self)._config_changed(change)
+ self.log.debug('Config changed:')
self.log.debug(repr(change.new))
-
- @catch_config_error
- def initialize(self, argv=None):
- """Do the basic steps to configure me.
-
- Override in subclasses.
- """
- self.parse_command_line(argv)
-
-
- def start(self):
- """Start the app mainloop.
-
- Override in subclasses.
- """
- if self.subapp is not None:
- return self.subapp.start()
-
- def print_alias_help(self):
- """Print the alias part of the help."""
- if not self.aliases:
- return
-
- lines = []
- classdict = {}
- for cls in self.classes:
- # include all parents (up to, but excluding Configurable) in available names
- for c in cls.mro()[:-3]:
- classdict[c.__name__] = c
-
+
+ @catch_config_error
+ def initialize(self, argv=None):
+ """Do the basic steps to configure me.
+
+ Override in subclasses.
+ """
+ self.parse_command_line(argv)
+
+
+ def start(self):
+ """Start the app mainloop.
+
+ Override in subclasses.
+ """
+ if self.subapp is not None:
+ return self.subapp.start()
+
+ def print_alias_help(self):
+ """Print the alias part of the help."""
+ if not self.aliases:
+ return
+
+ lines = []
+ classdict = {}
+ for cls in self.classes:
+ # include all parents (up to, but excluding Configurable) in available names
+ for c in cls.mro()[:-3]:
+ classdict[c.__name__] = c
+
for alias, longname in self.aliases.items():
- classname, traitname = longname.split('.',1)
- cls = classdict[classname]
-
- trait = cls.class_traits(config=True)[traitname]
- help = cls.class_get_trait_help(trait).splitlines()
- # reformat first line
- help[0] = help[0].replace(longname, alias) + ' (%s)'%longname
- if len(alias) == 1:
- help[0] = help[0].replace('--%s='%alias, '-%s '%alias)
- lines.extend(help)
- # lines.append('')
- print(os.linesep.join(lines))
-
- def print_flag_help(self):
- """Print the flag part of the help."""
- if not self.flags:
- return
-
- lines = []
+ classname, traitname = longname.split('.',1)
+ cls = classdict[classname]
+
+ trait = cls.class_traits(config=True)[traitname]
+ help = cls.class_get_trait_help(trait).splitlines()
+ # reformat first line
+ help[0] = help[0].replace(longname, alias) + ' (%s)'%longname
+ if len(alias) == 1:
+ help[0] = help[0].replace('--%s='%alias, '-%s '%alias)
+ lines.extend(help)
+ # lines.append('')
+ print(os.linesep.join(lines))
+
+ def print_flag_help(self):
+ """Print the flag part of the help."""
+ if not self.flags:
+ return
+
+ lines = []
for m, (cfg,help) in self.flags.items():
- prefix = '--' if len(m) > 1 else '-'
- lines.append(prefix+m)
- lines.append(indent(dedent(help.strip())))
- # lines.append('')
- print(os.linesep.join(lines))
-
- def print_options(self):
- if not self.flags and not self.aliases:
- return
- lines = ['Options']
- lines.append('-'*len(lines[0]))
- lines.append('')
- for p in wrap_paragraphs(self.option_description):
- lines.append(p)
- lines.append('')
- print(os.linesep.join(lines))
- self.print_flag_help()
- self.print_alias_help()
- print()
-
- def print_subcommands(self):
- """Print the subcommand part of the help."""
- if not self.subcommands:
- return
-
- lines = ["Subcommands"]
- lines.append('-'*len(lines[0]))
- lines.append('')
- for p in wrap_paragraphs(self.subcommand_description.format(
- app=self.name)):
- lines.append(p)
- lines.append('')
+ prefix = '--' if len(m) > 1 else '-'
+ lines.append(prefix+m)
+ lines.append(indent(dedent(help.strip())))
+ # lines.append('')
+ print(os.linesep.join(lines))
+
+ def print_options(self):
+ if not self.flags and not self.aliases:
+ return
+ lines = ['Options']
+ lines.append('-'*len(lines[0]))
+ lines.append('')
+ for p in wrap_paragraphs(self.option_description):
+ lines.append(p)
+ lines.append('')
+ print(os.linesep.join(lines))
+ self.print_flag_help()
+ self.print_alias_help()
+ print()
+
+ def print_subcommands(self):
+ """Print the subcommand part of the help."""
+ if not self.subcommands:
+ return
+
+ lines = ["Subcommands"]
+ lines.append('-'*len(lines[0]))
+ lines.append('')
+ for p in wrap_paragraphs(self.subcommand_description.format(
+ app=self.name)):
+ lines.append(p)
+ lines.append('')
for subc, (cls, help) in self.subcommands.items():
- lines.append(subc)
- if help:
- lines.append(indent(dedent(help.strip())))
- lines.append('')
- print(os.linesep.join(lines))
-
- def print_help(self, classes=False):
- """Print the help for each Configurable class in self.classes.
-
- If classes=False (the default), only flags and aliases are printed.
- """
- self.print_description()
- self.print_subcommands()
- self.print_options()
-
- if classes:
- help_classes = self.classes
- if help_classes:
- print("Class parameters")
- print("----------------")
- print()
- for p in wrap_paragraphs(self.keyvalue_description):
- print(p)
- print()
-
- for cls in help_classes:
- cls.class_print_help()
- print()
- else:
- print("To see all available configurables, use `--help-all`")
- print()
-
- self.print_examples()
-
- def document_config_options(self):
- """Generate rST format documentation for the config options this application
-
- Returns a multiline string.
- """
- return '\n'.join(c.class_config_rst_doc()
- for c in self._classes_inc_parents())
-
-
- def print_description(self):
- """Print the application description."""
- for p in wrap_paragraphs(self.description):
- print(p)
- print()
-
- def print_examples(self):
- """Print usage and examples.
-
- This usage string goes at the end of the command line help string
- and should contain examples of the application's usage.
- """
- if self.examples:
- print("Examples")
- print("--------")
- print()
- print(indent(dedent(self.examples.strip())))
- print()
-
- def print_version(self):
- """Print the version string."""
- print(self.version)
-
- @catch_config_error
- def initialize_subcommand(self, subc, argv=None):
- """Initialize a subcommand with argv."""
- subapp,help = self.subcommands.get(subc)
-
+ lines.append(subc)
+ if help:
+ lines.append(indent(dedent(help.strip())))
+ lines.append('')
+ print(os.linesep.join(lines))
+
+ def print_help(self, classes=False):
+ """Print the help for each Configurable class in self.classes.
+
+ If classes=False (the default), only flags and aliases are printed.
+ """
+ self.print_description()
+ self.print_subcommands()
+ self.print_options()
+
+ if classes:
+ help_classes = self.classes
+ if help_classes:
+ print("Class parameters")
+ print("----------------")
+ print()
+ for p in wrap_paragraphs(self.keyvalue_description):
+ print(p)
+ print()
+
+ for cls in help_classes:
+ cls.class_print_help()
+ print()
+ else:
+ print("To see all available configurables, use `--help-all`")
+ print()
+
+ self.print_examples()
+
+ def document_config_options(self):
+ """Generate rST format documentation for the config options this application
+
+ Returns a multiline string.
+ """
+ return '\n'.join(c.class_config_rst_doc()
+ for c in self._classes_inc_parents())
+
+
+ def print_description(self):
+ """Print the application description."""
+ for p in wrap_paragraphs(self.description):
+ print(p)
+ print()
+
+ def print_examples(self):
+ """Print usage and examples.
+
+ This usage string goes at the end of the command line help string
+ and should contain examples of the application's usage.
+ """
+ if self.examples:
+ print("Examples")
+ print("--------")
+ print()
+ print(indent(dedent(self.examples.strip())))
+ print()
+
+ def print_version(self):
+ """Print the version string."""
+ print(self.version)
+
+ @catch_config_error
+ def initialize_subcommand(self, subc, argv=None):
+ """Initialize a subcommand with argv."""
+ subapp,help = self.subcommands.get(subc)
+
if isinstance(subapp, six.string_types):
- subapp = import_item(subapp)
-
- # clear existing instances
- self.__class__.clear_instance()
- # instantiate
+ subapp = import_item(subapp)
+
+ # clear existing instances
+ self.__class__.clear_instance()
+ # instantiate
self.subapp = subapp.instance(parent=self)
- # and initialize subapp
- self.subapp.initialize(argv)
-
- def flatten_flags(self):
- """flatten flags and aliases, so cl-args override as expected.
-
- This prevents issues such as an alias pointing to InteractiveShell,
- but a config file setting the same trait in TerminalInteraciveShell
- getting inappropriate priority over the command-line arg.
-
- Only aliases with exactly one descendent in the class list
- will be promoted.
-
- """
- # build a tree of classes in our list that inherit from a particular
- # it will be a dict by parent classname of classes in our list
- # that are descendents
- mro_tree = defaultdict(list)
- for cls in self.classes:
- clsname = cls.__name__
- for parent in cls.mro()[1:-3]:
- # exclude cls itself and Configurable,HasTraits,object
- mro_tree[parent.__name__].append(clsname)
- # flatten aliases, which have the form:
- # { 'alias' : 'Class.trait' }
- aliases = {}
+ # and initialize subapp
+ self.subapp.initialize(argv)
+
+ def flatten_flags(self):
+ """flatten flags and aliases, so cl-args override as expected.
+
+ This prevents issues such as an alias pointing to InteractiveShell,
+ but a config file setting the same trait in TerminalInteraciveShell
+ getting inappropriate priority over the command-line arg.
+
+ Only aliases with exactly one descendent in the class list
+ will be promoted.
+
+ """
+ # build a tree of classes in our list that inherit from a particular
+ # it will be a dict by parent classname of classes in our list
+ # that are descendents
+ mro_tree = defaultdict(list)
+ for cls in self.classes:
+ clsname = cls.__name__
+ for parent in cls.mro()[1:-3]:
+ # exclude cls itself and Configurable,HasTraits,object
+ mro_tree[parent.__name__].append(clsname)
+ # flatten aliases, which have the form:
+ # { 'alias' : 'Class.trait' }
+ aliases = {}
for alias, cls_trait in self.aliases.items():
- cls,trait = cls_trait.split('.',1)
- children = mro_tree[cls]
- if len(children) == 1:
- # exactly one descendent, promote alias
- cls = children[0]
- aliases[alias] = '.'.join([cls,trait])
-
- # flatten flags, which are of the form:
- # { 'key' : ({'Cls' : {'trait' : value}}, 'help')}
- flags = {}
+ cls,trait = cls_trait.split('.',1)
+ children = mro_tree[cls]
+ if len(children) == 1:
+ # exactly one descendent, promote alias
+ cls = children[0]
+ aliases[alias] = '.'.join([cls,trait])
+
+ # flatten flags, which are of the form:
+ # { 'key' : ({'Cls' : {'trait' : value}}, 'help')}
+ flags = {}
for key, (flagdict, help) in self.flags.items():
- newflag = {}
+ newflag = {}
for cls, subdict in flagdict.items():
- children = mro_tree[cls]
- # exactly one descendent, promote flag section
- if len(children) == 1:
- cls = children[0]
- newflag[cls] = subdict
- flags[key] = (newflag, help)
- return flags, aliases
-
- @catch_config_error
- def parse_command_line(self, argv=None):
- """Parse the command line arguments."""
- argv = sys.argv[1:] if argv is None else argv
- self.argv = [ py3compat.cast_unicode(arg) for arg in argv ]
-
- if argv and argv[0] == 'help':
- # turn `ipython help notebook` into `ipython notebook -h`
- argv = argv[1:] + ['-h']
-
- if self.subcommands and len(argv) > 0:
- # we have subcommands, and one may have been specified
- subc, subargv = argv[0], argv[1:]
- if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands:
- # it's a subcommand, and *not* a flag or class parameter
- return self.initialize_subcommand(subc, subargv)
-
- # Arguments after a '--' argument are for the script IPython may be
- # about to run, not IPython iteslf. For arguments parsed here (help and
- # version), we want to only search the arguments up to the first
- # occurrence of '--', which we're calling interpreted_argv.
- try:
- interpreted_argv = argv[:argv.index('--')]
- except ValueError:
- interpreted_argv = argv
-
- if any(x in interpreted_argv for x in ('-h', '--help-all', '--help')):
- self.print_help('--help-all' in interpreted_argv)
- self.exit(0)
-
- if '--version' in interpreted_argv or '-V' in interpreted_argv:
- self.print_version()
- self.exit(0)
-
- # flatten flags&aliases, so cl-args get appropriate priority:
- flags,aliases = self.flatten_flags()
- loader = KVArgParseConfigLoader(argv=argv, aliases=aliases,
- flags=flags, log=self.log)
+ children = mro_tree[cls]
+ # exactly one descendent, promote flag section
+ if len(children) == 1:
+ cls = children[0]
+ newflag[cls] = subdict
+ flags[key] = (newflag, help)
+ return flags, aliases
+
+ @catch_config_error
+ def parse_command_line(self, argv=None):
+ """Parse the command line arguments."""
+ argv = sys.argv[1:] if argv is None else argv
+ self.argv = [ py3compat.cast_unicode(arg) for arg in argv ]
+
+ if argv and argv[0] == 'help':
+ # turn `ipython help notebook` into `ipython notebook -h`
+ argv = argv[1:] + ['-h']
+
+ if self.subcommands and len(argv) > 0:
+ # we have subcommands, and one may have been specified
+ subc, subargv = argv[0], argv[1:]
+ if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands:
+ # it's a subcommand, and *not* a flag or class parameter
+ return self.initialize_subcommand(subc, subargv)
+
+ # Arguments after a '--' argument are for the script IPython may be
+ # about to run, not IPython iteslf. For arguments parsed here (help and
+ # version), we want to only search the arguments up to the first
+ # occurrence of '--', which we're calling interpreted_argv.
+ try:
+ interpreted_argv = argv[:argv.index('--')]
+ except ValueError:
+ interpreted_argv = argv
+
+ if any(x in interpreted_argv for x in ('-h', '--help-all', '--help')):
+ self.print_help('--help-all' in interpreted_argv)
+ self.exit(0)
+
+ if '--version' in interpreted_argv or '-V' in interpreted_argv:
+ self.print_version()
+ self.exit(0)
+
+ # flatten flags&aliases, so cl-args get appropriate priority:
+ flags,aliases = self.flatten_flags()
+ loader = KVArgParseConfigLoader(argv=argv, aliases=aliases,
+ flags=flags, log=self.log)
self.cli_config = deepcopy(loader.load_config())
self.update_config(self.cli_config)
- # store unparsed args in extra_args
- self.extra_args = loader.extra_args
-
- @classmethod
+ # store unparsed args in extra_args
+ self.extra_args = loader.extra_args
+
+ @classmethod
def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False):
- """Load config files (py,json) by filename and path.
-
- yield each config object in turn.
- """
-
- if not isinstance(path, list):
- path = [path]
- for path in path[::-1]:
- # path list is in descending priority order, so load files backwards:
- pyloader = cls.python_config_loader_class(basefilename+'.py', path=path, log=log)
- if log:
+ """Load config files (py,json) by filename and path.
+
+ yield each config object in turn.
+ """
+
+ if not isinstance(path, list):
+ path = [path]
+ for path in path[::-1]:
+ # path list is in descending priority order, so load files backwards:
+ pyloader = cls.python_config_loader_class(basefilename+'.py', path=path, log=log)
+ if log:
log.debug("Looking for %s in %s", basefilename, path or os.getcwd())
- jsonloader = cls.json_config_loader_class(basefilename+'.json', path=path, log=log)
+ jsonloader = cls.json_config_loader_class(basefilename+'.json', path=path, log=log)
loaded = []
filenames = []
- for loader in [pyloader, jsonloader]:
+ for loader in [pyloader, jsonloader]:
config = None
- try:
- config = loader.load_config()
- except ConfigFileNotFound:
- pass
- except Exception:
- # try to get the full filename, but it will be empty in the
- # unlikely event that the error raised before filefind finished
- filename = loader.full_filename or basefilename
- # problem while running the file
+ try:
+ config = loader.load_config()
+ except ConfigFileNotFound:
+ pass
+ except Exception:
+ # try to get the full filename, but it will be empty in the
+ # unlikely event that the error raised before filefind finished
+ filename = loader.full_filename or basefilename
+ # problem while running the file
if raise_config_file_errors:
raise
- if log:
- log.error("Exception while loading config file %s",
- filename, exc_info=True)
- else:
- if log:
- log.debug("Loaded config file: %s", loader.full_filename)
- if config:
+ if log:
+ log.error("Exception while loading config file %s",
+ filename, exc_info=True)
+ else:
+ if log:
+ log.debug("Loaded config file: %s", loader.full_filename)
+ if config:
for filename, earlier_config in zip(filenames, loaded):
collisions = earlier_config.collisions(config)
if collisions and log:
@@ -587,16 +587,16 @@ class Application(SingletonConfigurable):
yield (config, loader.full_filename)
loaded.append(config)
filenames.append(loader.full_filename)
-
+
@property
def loaded_config_files(self):
"""Currently loaded configuration files"""
return self._loaded_config_files[:]
-
- @catch_config_error
- def load_config_file(self, filename, path=None):
- """Load config files by filename and path."""
- filename, ext = os.path.splitext(filename)
+
+ @catch_config_error
+ def load_config_file(self, filename, path=None):
+ """Load config files by filename and path."""
+ filename, ext = os.path.splitext(filename)
new_config = Config()
for (config, filename) in self._load_config_files(filename, path=path, log=self.log,
raise_config_file_errors=self.raise_config_file_errors,
@@ -607,8 +607,8 @@ class Application(SingletonConfigurable):
# add self.cli_config to preserve CLI config priority
new_config.merge(self.cli_config)
self.update_config(new_config)
-
-
+
+
def _classes_in_config_sample(self):
"""
Yields only classes with own traits, and their subclasses.
@@ -641,71 +641,71 @@ class Application(SingletonConfigurable):
if inc_yes:
yield cl
- def generate_config_file(self):
- """generate default config file from Configurables"""
- lines = ["# Configuration file for %s." % self.name]
- lines.append('')
+ def generate_config_file(self):
+ """generate default config file from Configurables"""
+ lines = ["# Configuration file for %s." % self.name]
+ lines.append('')
for cls in self._classes_in_config_sample():
- lines.append(cls.class_config_section())
- return '\n'.join(lines)
-
- def exit(self, exit_status=0):
- self.log.debug("Exiting application: %s" % self.name)
- sys.exit(exit_status)
-
- @classmethod
- def launch_instance(cls, argv=None, **kwargs):
- """Launch a global instance of this Application
-
- If a global instance already exists, this reinitializes and starts it
- """
- app = cls.instance(**kwargs)
- app.initialize(argv)
- app.start()
-
-#-----------------------------------------------------------------------------
-# utility functions, for convenience
-#-----------------------------------------------------------------------------
-
-def boolean_flag(name, configurable, set_help='', unset_help=''):
- """Helper for building basic --trait, --no-trait flags.
-
- Parameters
- ----------
-
- name : str
- The name of the flag.
- configurable : str
- The 'Class.trait' string of the trait to be set/unset with the flag
- set_help : unicode
- help string for --name flag
- unset_help : unicode
- help string for --no-name flag
-
- Returns
- -------
-
- cfg : dict
- A dict with two keys: 'name', and 'no-name', for setting and unsetting
- the trait, respectively.
- """
- # default helpstrings
- set_help = set_help or "set %s=True"%configurable
- unset_help = unset_help or "set %s=False"%configurable
-
- cls,trait = configurable.split('.')
-
- setter = {cls : {trait : True}}
- unsetter = {cls : {trait : False}}
- return {name : (setter, set_help), 'no-'+name : (unsetter, unset_help)}
-
-
-def get_config():
- """Get the config object for the global Application instance, if there is one
-
- otherwise return an empty config object
- """
- if Application.initialized():
- return Application.instance().config
- else:
- return Config()
+ lines.append(cls.class_config_section())
+ return '\n'.join(lines)
+
+ def exit(self, exit_status=0):
+ self.log.debug("Exiting application: %s" % self.name)
+ sys.exit(exit_status)
+
+ @classmethod
+ def launch_instance(cls, argv=None, **kwargs):
+ """Launch a global instance of this Application
+
+ If a global instance already exists, this reinitializes and starts it
+ """
+ app = cls.instance(**kwargs)
+ app.initialize(argv)
+ app.start()
+
+#-----------------------------------------------------------------------------
+# utility functions, for convenience
+#-----------------------------------------------------------------------------
+
+def boolean_flag(name, configurable, set_help='', unset_help=''):
+ """Helper for building basic --trait, --no-trait flags.
+
+ Parameters
+ ----------
+
+ name : str
+ The name of the flag.
+ configurable : str
+ The 'Class.trait' string of the trait to be set/unset with the flag
+ set_help : unicode
+ help string for --name flag
+ unset_help : unicode
+ help string for --no-name flag
+
+ Returns
+ -------
+
+ cfg : dict
+ A dict with two keys: 'name', and 'no-name', for setting and unsetting
+ the trait, respectively.
+ """
+ # default helpstrings
+ set_help = set_help or "set %s=True"%configurable
+ unset_help = unset_help or "set %s=False"%configurable
+
+ cls,trait = configurable.split('.')
+
+ setter = {cls : {trait : True}}
+ unsetter = {cls : {trait : False}}
+ return {name : (setter, set_help), 'no-'+name : (unsetter, unset_help)}
+
+
+def get_config():
+ """Get the config object for the global Application instance, if there is one
+
+ otherwise return an empty config object
+ """
+ if Application.initialized():
+ return Application.instance().config
+ else:
+ return Config()
diff --git a/contrib/python/traitlets/py2/traitlets/config/configurable.py b/contrib/python/traitlets/py2/traitlets/config/configurable.py
index acb81cb208..1174fcf017 100644
--- a/contrib/python/traitlets/py2/traitlets/config/configurable.py
+++ b/contrib/python/traitlets/py2/traitlets/config/configurable.py
@@ -1,191 +1,191 @@
-# encoding: utf-8
-"""A base class for objects that are configurable."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
+# encoding: utf-8
+"""A base class for objects that are configurable."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
from __future__ import print_function, absolute_import
-
-from copy import deepcopy
+
+from copy import deepcopy
import warnings
-
+
from .loader import Config, LazyConfigValue, _is_section_key
-from traitlets.traitlets import HasTraits, Instance, observe, observe_compat, default
-from ipython_genutils.text import indent, dedent, wrap_paragraphs
-
-
-#-----------------------------------------------------------------------------
-# Helper classes for Configurables
-#-----------------------------------------------------------------------------
-
-
-class ConfigurableError(Exception):
- pass
-
-
-class MultipleInstanceError(ConfigurableError):
- pass
-
-#-----------------------------------------------------------------------------
-# Configurable implementation
-#-----------------------------------------------------------------------------
-
-class Configurable(HasTraits):
-
- config = Instance(Config, (), {})
- parent = Instance('traitlets.config.configurable.Configurable', allow_none=True)
-
- def __init__(self, **kwargs):
- """Create a configurable given a config config.
-
- Parameters
- ----------
- config : Config
- If this is empty, default values are used. If config is a
- :class:`Config` instance, it will be used to configure the
- instance.
- parent : Configurable instance, optional
- The parent Configurable instance of this object.
-
- Notes
- -----
- Subclasses of Configurable must call the :meth:`__init__` method of
- :class:`Configurable` *before* doing anything else and using
- :func:`super`::
-
- class MyConfigurable(Configurable):
- def __init__(self, config=None):
- super(MyConfigurable, self).__init__(config=config)
- # Then any other code you need to finish initialization.
-
- This ensures that instances will be configured properly.
- """
- parent = kwargs.pop('parent', None)
- if parent is not None:
- # config is implied from parent
- if kwargs.get('config', None) is None:
- kwargs['config'] = parent.config
- self.parent = parent
-
- config = kwargs.pop('config', None)
-
- # load kwarg traits, other than config
- super(Configurable, self).__init__(**kwargs)
-
- # load config
- if config is not None:
- # We used to deepcopy, but for now we are trying to just save
- # by reference. This *could* have side effects as all components
- # will share config. In fact, I did find such a side effect in
- # _config_changed below. If a config attribute value was a mutable type
- # all instances of a component were getting the same copy, effectively
- # making that a class attribute.
- # self.config = deepcopy(config)
- self.config = config
- else:
- # allow _config_default to return something
- self._load_config(self.config)
-
- # Ensure explicit kwargs are applied after loading config.
- # This is usually redundant, but ensures config doesn't override
- # explicitly assigned values.
- for key, value in kwargs.items():
- setattr(self, key, value)
-
- #-------------------------------------------------------------------------
- # Static trait notifiations
- #-------------------------------------------------------------------------
-
- @classmethod
- def section_names(cls):
- """return section names as a list"""
- return [c.__name__ for c in reversed(cls.__mro__) if
- issubclass(c, Configurable) and issubclass(cls, c)
- ]
-
- def _find_my_config(self, cfg):
- """extract my config from a global Config object
-
- will construct a Config object of only the config values that apply to me
- based on my mro(), as well as those of my parent(s) if they exist.
-
- If I am Bar and my parent is Foo, and their parent is Tim,
- this will return merge following config sections, in this order::
-
- [Bar, Foo.bar, Tim.Foo.Bar]
-
- With the last item being the highest priority.
- """
- cfgs = [cfg]
- if self.parent:
- cfgs.append(self.parent._find_my_config(cfg))
- my_config = Config()
- for c in cfgs:
- for sname in self.section_names():
- # Don't do a blind getattr as that would cause the config to
- # dynamically create the section with name Class.__name__.
- if c._has_section(sname):
- my_config.merge(c[sname])
- return my_config
-
- def _load_config(self, cfg, section_names=None, traits=None):
- """load traits from a Config object"""
-
- if traits is None:
- traits = self.traits(config=True)
- if section_names is None:
- section_names = self.section_names()
-
- my_config = self._find_my_config(cfg)
-
- # hold trait notifications until after all config has been loaded
- with self.hold_trait_notifications():
+from traitlets.traitlets import HasTraits, Instance, observe, observe_compat, default
+from ipython_genutils.text import indent, dedent, wrap_paragraphs
+
+
+#-----------------------------------------------------------------------------
+# Helper classes for Configurables
+#-----------------------------------------------------------------------------
+
+
+class ConfigurableError(Exception):
+ pass
+
+
+class MultipleInstanceError(ConfigurableError):
+ pass
+
+#-----------------------------------------------------------------------------
+# Configurable implementation
+#-----------------------------------------------------------------------------
+
+class Configurable(HasTraits):
+
+ config = Instance(Config, (), {})
+ parent = Instance('traitlets.config.configurable.Configurable', allow_none=True)
+
+ def __init__(self, **kwargs):
+ """Create a configurable given a config config.
+
+ Parameters
+ ----------
+ config : Config
+ If this is empty, default values are used. If config is a
+ :class:`Config` instance, it will be used to configure the
+ instance.
+ parent : Configurable instance, optional
+ The parent Configurable instance of this object.
+
+ Notes
+ -----
+ Subclasses of Configurable must call the :meth:`__init__` method of
+ :class:`Configurable` *before* doing anything else and using
+ :func:`super`::
+
+ class MyConfigurable(Configurable):
+ def __init__(self, config=None):
+ super(MyConfigurable, self).__init__(config=config)
+ # Then any other code you need to finish initialization.
+
+ This ensures that instances will be configured properly.
+ """
+ parent = kwargs.pop('parent', None)
+ if parent is not None:
+ # config is implied from parent
+ if kwargs.get('config', None) is None:
+ kwargs['config'] = parent.config
+ self.parent = parent
+
+ config = kwargs.pop('config', None)
+
+ # load kwarg traits, other than config
+ super(Configurable, self).__init__(**kwargs)
+
+ # load config
+ if config is not None:
+ # We used to deepcopy, but for now we are trying to just save
+ # by reference. This *could* have side effects as all components
+ # will share config. In fact, I did find such a side effect in
+ # _config_changed below. If a config attribute value was a mutable type
+ # all instances of a component were getting the same copy, effectively
+ # making that a class attribute.
+ # self.config = deepcopy(config)
+ self.config = config
+ else:
+ # allow _config_default to return something
+ self._load_config(self.config)
+
+ # Ensure explicit kwargs are applied after loading config.
+ # This is usually redundant, but ensures config doesn't override
+ # explicitly assigned values.
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+
+ #-------------------------------------------------------------------------
+ # Static trait notifiations
+ #-------------------------------------------------------------------------
+
+ @classmethod
+ def section_names(cls):
+ """return section names as a list"""
+ return [c.__name__ for c in reversed(cls.__mro__) if
+ issubclass(c, Configurable) and issubclass(cls, c)
+ ]
+
+ def _find_my_config(self, cfg):
+ """extract my config from a global Config object
+
+ will construct a Config object of only the config values that apply to me
+ based on my mro(), as well as those of my parent(s) if they exist.
+
+ If I am Bar and my parent is Foo, and their parent is Tim,
+ this will return merge following config sections, in this order::
+
+ [Bar, Foo.bar, Tim.Foo.Bar]
+
+ With the last item being the highest priority.
+ """
+ cfgs = [cfg]
+ if self.parent:
+ cfgs.append(self.parent._find_my_config(cfg))
+ my_config = Config()
+ for c in cfgs:
+ for sname in self.section_names():
+ # Don't do a blind getattr as that would cause the config to
+ # dynamically create the section with name Class.__name__.
+ if c._has_section(sname):
+ my_config.merge(c[sname])
+ return my_config
+
+ def _load_config(self, cfg, section_names=None, traits=None):
+ """load traits from a Config object"""
+
+ if traits is None:
+ traits = self.traits(config=True)
+ if section_names is None:
+ section_names = self.section_names()
+
+ my_config = self._find_my_config(cfg)
+
+ # hold trait notifications until after all config has been loaded
+ with self.hold_trait_notifications():
for name, config_value in my_config.items():
- if name in traits:
- if isinstance(config_value, LazyConfigValue):
- # ConfigValue is a wrapper for using append / update on containers
- # without having to copy the initial value
- initial = getattr(self, name)
- config_value = config_value.get_value(initial)
- # We have to do a deepcopy here if we don't deepcopy the entire
- # config object. If we don't, a mutable config_value will be
- # shared by all instances, effectively making it a class attribute.
- setattr(self, name, deepcopy(config_value))
+ if name in traits:
+ if isinstance(config_value, LazyConfigValue):
+ # ConfigValue is a wrapper for using append / update on containers
+ # without having to copy the initial value
+ initial = getattr(self, name)
+ config_value = config_value.get_value(initial)
+ # We have to do a deepcopy here if we don't deepcopy the entire
+ # config object. If we don't, a mutable config_value will be
+ # shared by all instances, effectively making it a class attribute.
+ setattr(self, name, deepcopy(config_value))
elif not _is_section_key(name) and not isinstance(config_value, Config):
- from difflib import get_close_matches
+ from difflib import get_close_matches
if isinstance(self, LoggingConfigurable):
warn = self.log.warning
else:
warn = lambda msg: warnings.warn(msg, stacklevel=9)
- matches = get_close_matches(name, traits)
+ matches = get_close_matches(name, traits)
msg = u"Config option `{option}` not recognized by `{klass}`.".format(
option=name, klass=self.__class__.__name__)
- if len(matches) == 1:
+ if len(matches) == 1:
msg += u" Did you mean `{matches}`?".format(matches=matches[0])
- elif len(matches) >= 1:
+ elif len(matches) >= 1:
msg +=" Did you mean one of: `{matches}`?".format(matches=', '.join(sorted(matches)))
warn(msg)
-
- @observe('config')
- @observe_compat
- def _config_changed(self, change):
- """Update all the class traits having ``config=True`` in metadata.
-
- For any class trait with a ``config`` metadata attribute that is
- ``True``, we update the trait with the value of the corresponding
- config entry.
- """
- # Get all traits with a config metadata entry that is True
- traits = self.traits(config=True)
-
- # We auto-load config section for this class as well as any parent
- # classes that are Configurable subclasses. This starts with Configurable
- # and works down the mro loading the config for each section.
- section_names = self.section_names()
+
+ @observe('config')
+ @observe_compat
+ def _config_changed(self, change):
+ """Update all the class traits having ``config=True`` in metadata.
+
+ For any class trait with a ``config`` metadata attribute that is
+ ``True``, we update the trait with the value of the corresponding
+ config entry.
+ """
+ # Get all traits with a config metadata entry that is True
+ traits = self.traits(config=True)
+
+ # We auto-load config section for this class as well as any parent
+ # classes that are Configurable subclasses. This starts with Configurable
+ # and works down the mro loading the config for each section.
+ section_names = self.section_names()
self._load_config(change.new, traits=traits, section_names=section_names)
-
- def update_config(self, config):
+
+ def update_config(self, config):
"""Update config and load the new values"""
# traitlets prior to 4.2 created a copy of self.config in order to trigger change events.
# Some projects (IPython < 5) relied upon one side effect of this,
@@ -197,236 +197,236 @@ class Configurable(HasTraits):
# load config
self._load_config(config)
# merge it into self.config
- self.config.merge(config)
+ self.config.merge(config)
# TODO: trigger change event if/when dict-update change events take place
# DO NOT trigger full trait-change
-
- @classmethod
- def class_get_help(cls, inst=None):
- """Get the help string for this class in ReST format.
-
- If `inst` is given, it's current trait values will be used in place of
- class defaults.
- """
- assert inst is None or isinstance(inst, cls)
- final_help = []
- final_help.append(u'%s options' % cls.__name__)
- final_help.append(len(final_help[0])*u'-')
- for k, v in sorted(cls.class_traits(config=True).items()):
- help = cls.class_get_trait_help(v, inst)
- final_help.append(help)
- return '\n'.join(final_help)
-
- @classmethod
- def class_get_trait_help(cls, trait, inst=None):
- """Get the help string for a single trait.
-
- If `inst` is given, it's current trait values will be used in place of
- the class default.
- """
- assert inst is None or isinstance(inst, cls)
- lines = []
- header = "--%s.%s=<%s>" % (cls.__name__, trait.name, trait.__class__.__name__)
- lines.append(header)
- if inst is not None:
- lines.append(indent('Current: %r' % getattr(inst, trait.name), 4))
- else:
- try:
- dvr = trait.default_value_repr()
- except Exception:
- dvr = None # ignore defaults we can't construct
- if dvr is not None:
- if len(dvr) > 64:
- dvr = dvr[:61]+'...'
- lines.append(indent('Default: %s' % dvr, 4))
- if 'Enum' in trait.__class__.__name__:
- # include Enum choices
- lines.append(indent('Choices: %r' % (trait.values,)))
-
- help = trait.help
- if help != '':
- help = '\n'.join(wrap_paragraphs(help, 76))
- lines.append(indent(help, 4))
- return '\n'.join(lines)
-
- @classmethod
- def class_print_help(cls, inst=None):
- """Get the help string for a single trait and print it."""
- print(cls.class_get_help(inst))
-
- @classmethod
- def class_config_section(cls):
- """Get the config class config section"""
- def c(s):
- """return a commented, wrapped block."""
- s = '\n\n'.join(wrap_paragraphs(s, 78))
-
+
+ @classmethod
+ def class_get_help(cls, inst=None):
+ """Get the help string for this class in ReST format.
+
+ If `inst` is given, it's current trait values will be used in place of
+ class defaults.
+ """
+ assert inst is None or isinstance(inst, cls)
+ final_help = []
+ final_help.append(u'%s options' % cls.__name__)
+ final_help.append(len(final_help[0])*u'-')
+ for k, v in sorted(cls.class_traits(config=True).items()):
+ help = cls.class_get_trait_help(v, inst)
+ final_help.append(help)
+ return '\n'.join(final_help)
+
+ @classmethod
+ def class_get_trait_help(cls, trait, inst=None):
+ """Get the help string for a single trait.
+
+ If `inst` is given, it's current trait values will be used in place of
+ the class default.
+ """
+ assert inst is None or isinstance(inst, cls)
+ lines = []
+ header = "--%s.%s=<%s>" % (cls.__name__, trait.name, trait.__class__.__name__)
+ lines.append(header)
+ if inst is not None:
+ lines.append(indent('Current: %r' % getattr(inst, trait.name), 4))
+ else:
+ try:
+ dvr = trait.default_value_repr()
+ except Exception:
+ dvr = None # ignore defaults we can't construct
+ if dvr is not None:
+ if len(dvr) > 64:
+ dvr = dvr[:61]+'...'
+ lines.append(indent('Default: %s' % dvr, 4))
+ if 'Enum' in trait.__class__.__name__:
+ # include Enum choices
+ lines.append(indent('Choices: %r' % (trait.values,)))
+
+ help = trait.help
+ if help != '':
+ help = '\n'.join(wrap_paragraphs(help, 76))
+ lines.append(indent(help, 4))
+ return '\n'.join(lines)
+
+ @classmethod
+ def class_print_help(cls, inst=None):
+ """Get the help string for a single trait and print it."""
+ print(cls.class_get_help(inst))
+
+ @classmethod
+ def class_config_section(cls):
+ """Get the config class config section"""
+ def c(s):
+ """return a commented, wrapped block."""
+ s = '\n\n'.join(wrap_paragraphs(s, 78))
+
return '## ' + s.replace('\n', '\n# ')
-
- # section header
- breaker = '#' + '-'*78
+
+ # section header
+ breaker = '#' + '-'*78
parent_classes = ','.join(p.__name__ for p in cls.__bases__)
s = "# %s(%s) configuration" % (cls.__name__, parent_classes)
- lines = [breaker, s, breaker, '']
- # get the description trait
- desc = cls.class_traits().get('description')
- if desc:
- desc = desc.default_value
+ lines = [breaker, s, breaker, '']
+ # get the description trait
+ desc = cls.class_traits().get('description')
+ if desc:
+ desc = desc.default_value
if not desc:
# no description from trait, use __doc__
- desc = getattr(cls, '__doc__', '')
- if desc:
- lines.append(c(desc))
- lines.append('')
-
- for name, trait in sorted(cls.class_own_traits(config=True).items()):
- lines.append(c(trait.help))
+ desc = getattr(cls, '__doc__', '')
+ if desc:
+ lines.append(c(desc))
+ lines.append('')
+
+ for name, trait in sorted(cls.class_own_traits(config=True).items()):
+ lines.append(c(trait.help))
lines.append('#c.%s.%s = %s' % (cls.__name__, name, trait.default_value_repr()))
- lines.append('')
- return '\n'.join(lines)
-
- @classmethod
- def class_config_rst_doc(cls):
- """Generate rST documentation for this class' config options.
-
- Excludes traits defined on parent classes.
- """
- lines = []
- classname = cls.__name__
- for k, trait in sorted(cls.class_own_traits(config=True).items()):
- ttype = trait.__class__.__name__
-
- termline = classname + '.' + trait.name
-
- # Choices or type
- if 'Enum' in ttype:
- # include Enum choices
- termline += ' : ' + '|'.join(repr(x) for x in trait.values)
- else:
- termline += ' : ' + ttype
- lines.append(termline)
-
- # Default value
- try:
- dvr = trait.default_value_repr()
- except Exception:
- dvr = None # ignore defaults we can't construct
- if dvr is not None:
- if len(dvr) > 64:
- dvr = dvr[:61]+'...'
- # Double up backslashes, so they get to the rendered docs
- dvr = dvr.replace('\\n', '\\\\n')
- lines.append(' Default: ``%s``' % dvr)
- lines.append('')
-
- help = trait.help or 'No description'
- lines.append(indent(dedent(help), 4))
-
- # Blank line
- lines.append('')
-
- return '\n'.join(lines)
-
-
-
-class LoggingConfigurable(Configurable):
- """A parent class for Configurables that log.
-
- Subclasses have a log trait, and the default behavior
- is to get the logger from the currently running Application.
- """
-
- log = Instance('logging.Logger')
- @default('log')
- def _log_default(self):
- from traitlets import log
- return log.get_logger()
-
-
-class SingletonConfigurable(LoggingConfigurable):
- """A configurable that only allows one instance.
-
- This class is for classes that should only have one instance of itself
- or *any* subclass. To create and retrieve such a class use the
- :meth:`SingletonConfigurable.instance` method.
- """
-
- _instance = None
-
- @classmethod
- def _walk_mro(cls):
- """Walk the cls.mro() for parent classes that are also singletons
-
- For use in instance()
- """
-
- for subclass in cls.mro():
- if issubclass(cls, subclass) and \
- issubclass(subclass, SingletonConfigurable) and \
- subclass != SingletonConfigurable:
- yield subclass
-
- @classmethod
- def clear_instance(cls):
- """unset _instance for this class and singleton parents.
- """
- if not cls.initialized():
- return
- for subclass in cls._walk_mro():
- if isinstance(subclass._instance, cls):
- # only clear instances that are instances
- # of the calling class
- subclass._instance = None
-
- @classmethod
- def instance(cls, *args, **kwargs):
- """Returns a global instance of this class.
-
- This method create a new instance if none have previously been created
- and returns a previously created instance is one already exists.
-
- The arguments and keyword arguments passed to this method are passed
- on to the :meth:`__init__` method of the class upon instantiation.
-
- Examples
- --------
-
- Create a singleton class using instance, and retrieve it::
-
- >>> from traitlets.config.configurable import SingletonConfigurable
- >>> class Foo(SingletonConfigurable): pass
- >>> foo = Foo.instance()
- >>> foo == Foo.instance()
- True
-
- Create a subclass that is retrived using the base class instance::
-
- >>> class Bar(SingletonConfigurable): pass
- >>> class Bam(Bar): pass
- >>> bam = Bam.instance()
- >>> bam == Bar.instance()
- True
- """
- # Create and save the instance
- if cls._instance is None:
- inst = cls(*args, **kwargs)
- # Now make sure that the instance will also be returned by
- # parent classes' _instance attribute.
- for subclass in cls._walk_mro():
- subclass._instance = inst
-
- if isinstance(cls._instance, cls):
- return cls._instance
- else:
- raise MultipleInstanceError(
- 'Multiple incompatible subclass instances of '
- '%s are being created.' % cls.__name__
- )
-
- @classmethod
- def initialized(cls):
- """Has an instance been created?"""
- return hasattr(cls, "_instance") and cls._instance is not None
-
-
-
+ lines.append('')
+ return '\n'.join(lines)
+
+ @classmethod
+ def class_config_rst_doc(cls):
+ """Generate rST documentation for this class' config options.
+
+ Excludes traits defined on parent classes.
+ """
+ lines = []
+ classname = cls.__name__
+ for k, trait in sorted(cls.class_own_traits(config=True).items()):
+ ttype = trait.__class__.__name__
+
+ termline = classname + '.' + trait.name
+
+ # Choices or type
+ if 'Enum' in ttype:
+ # include Enum choices
+ termline += ' : ' + '|'.join(repr(x) for x in trait.values)
+ else:
+ termline += ' : ' + ttype
+ lines.append(termline)
+
+ # Default value
+ try:
+ dvr = trait.default_value_repr()
+ except Exception:
+ dvr = None # ignore defaults we can't construct
+ if dvr is not None:
+ if len(dvr) > 64:
+ dvr = dvr[:61]+'...'
+ # Double up backslashes, so they get to the rendered docs
+ dvr = dvr.replace('\\n', '\\\\n')
+ lines.append(' Default: ``%s``' % dvr)
+ lines.append('')
+
+ help = trait.help or 'No description'
+ lines.append(indent(dedent(help), 4))
+
+ # Blank line
+ lines.append('')
+
+ return '\n'.join(lines)
+
+
+
+class LoggingConfigurable(Configurable):
+ """A parent class for Configurables that log.
+
+ Subclasses have a log trait, and the default behavior
+ is to get the logger from the currently running Application.
+ """
+
+ log = Instance('logging.Logger')
+ @default('log')
+ def _log_default(self):
+ from traitlets import log
+ return log.get_logger()
+
+
+class SingletonConfigurable(LoggingConfigurable):
+ """A configurable that only allows one instance.
+
+ This class is for classes that should only have one instance of itself
+ or *any* subclass. To create and retrieve such a class use the
+ :meth:`SingletonConfigurable.instance` method.
+ """
+
+ _instance = None
+
+ @classmethod
+ def _walk_mro(cls):
+ """Walk the cls.mro() for parent classes that are also singletons
+
+ For use in instance()
+ """
+
+ for subclass in cls.mro():
+ if issubclass(cls, subclass) and \
+ issubclass(subclass, SingletonConfigurable) and \
+ subclass != SingletonConfigurable:
+ yield subclass
+
+ @classmethod
+ def clear_instance(cls):
+ """unset _instance for this class and singleton parents.
+ """
+ if not cls.initialized():
+ return
+ for subclass in cls._walk_mro():
+ if isinstance(subclass._instance, cls):
+ # only clear instances that are instances
+ # of the calling class
+ subclass._instance = None
+
+ @classmethod
+ def instance(cls, *args, **kwargs):
+ """Returns a global instance of this class.
+
+ This method create a new instance if none have previously been created
+ and returns a previously created instance is one already exists.
+
+ The arguments and keyword arguments passed to this method are passed
+ on to the :meth:`__init__` method of the class upon instantiation.
+
+ Examples
+ --------
+
+ Create a singleton class using instance, and retrieve it::
+
+ >>> from traitlets.config.configurable import SingletonConfigurable
+ >>> class Foo(SingletonConfigurable): pass
+ >>> foo = Foo.instance()
+ >>> foo == Foo.instance()
+ True
+
+ Create a subclass that is retrived using the base class instance::
+
+ >>> class Bar(SingletonConfigurable): pass
+ >>> class Bam(Bar): pass
+ >>> bam = Bam.instance()
+ >>> bam == Bar.instance()
+ True
+ """
+ # Create and save the instance
+ if cls._instance is None:
+ inst = cls(*args, **kwargs)
+ # Now make sure that the instance will also be returned by
+ # parent classes' _instance attribute.
+ for subclass in cls._walk_mro():
+ subclass._instance = inst
+
+ if isinstance(cls._instance, cls):
+ return cls._instance
+ else:
+ raise MultipleInstanceError(
+ 'Multiple incompatible subclass instances of '
+ '%s are being created.' % cls.__name__
+ )
+
+ @classmethod
+ def initialized(cls):
+ """Has an instance been created?"""
+ return hasattr(cls, "_instance") and cls._instance is not None
+
+
+
diff --git a/contrib/python/traitlets/py2/traitlets/config/loader.py b/contrib/python/traitlets/py2/traitlets/config/loader.py
index 883ef695ac..803b36276f 100644
--- a/contrib/python/traitlets/py2/traitlets/config/loader.py
+++ b/contrib/python/traitlets/py2/traitlets/config/loader.py
@@ -1,392 +1,392 @@
-# encoding: utf-8
-"""A simple configuration system."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import argparse
-import copy
-import logging
-import os
-import re
-import sys
-import json
-from ast import literal_eval
-
-from ipython_genutils.path import filefind
-from ipython_genutils import py3compat
-from ipython_genutils.encoding import DEFAULT_ENCODING
+# encoding: utf-8
+"""A simple configuration system."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import argparse
+import copy
+import logging
+import os
+import re
+import sys
+import json
+from ast import literal_eval
+
+from ipython_genutils.path import filefind
+from ipython_genutils import py3compat
+from ipython_genutils.encoding import DEFAULT_ENCODING
from six import text_type
-from traitlets.traitlets import HasTraits, List, Any
-
-#-----------------------------------------------------------------------------
-# Exceptions
-#-----------------------------------------------------------------------------
-
-
-class ConfigError(Exception):
- pass
-
-class ConfigLoaderError(ConfigError):
- pass
-
-class ConfigFileNotFound(ConfigError):
- pass
-
-class ArgumentError(ConfigLoaderError):
- pass
-
-#-----------------------------------------------------------------------------
-# Argparse fix
-#-----------------------------------------------------------------------------
-
-# Unfortunately argparse by default prints help messages to stderr instead of
-# stdout. This makes it annoying to capture long help screens at the command
-# line, since one must know how to pipe stderr, which many users don't know how
-# to do. So we override the print_help method with one that defaults to
-# stdout and use our class instead.
-
-class ArgumentParser(argparse.ArgumentParser):
- """Simple argparse subclass that prints help to stdout by default."""
-
- def print_help(self, file=None):
- if file is None:
- file = sys.stdout
- return super(ArgumentParser, self).print_help(file)
-
- print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
-
-#-----------------------------------------------------------------------------
-# Config class for holding config information
-#-----------------------------------------------------------------------------
-
-class LazyConfigValue(HasTraits):
- """Proxy object for exposing methods on configurable containers
-
- Exposes:
-
- - append, extend, insert on lists
- - update on dicts
- - update, add on sets
- """
-
- _value = None
-
- # list methods
- _extend = List()
- _prepend = List()
-
- def append(self, obj):
- self._extend.append(obj)
-
- def extend(self, other):
- self._extend.extend(other)
-
- def prepend(self, other):
- """like list.extend, but for the front"""
- self._prepend[:0] = other
-
- _inserts = List()
- def insert(self, index, other):
- if not isinstance(index, int):
- raise TypeError("An integer is required")
- self._inserts.append((index, other))
-
- # dict methods
- # update is used for both dict and set
- _update = Any()
- def update(self, other):
- if self._update is None:
- if isinstance(other, dict):
- self._update = {}
- else:
- self._update = set()
- self._update.update(other)
-
- # set methods
- def add(self, obj):
- self.update({obj})
-
- def get_value(self, initial):
- """construct the value from the initial one
-
- after applying any insert / extend / update changes
- """
- if self._value is not None:
- return self._value
- value = copy.deepcopy(initial)
- if isinstance(value, list):
- for idx, obj in self._inserts:
- value.insert(idx, obj)
- value[:0] = self._prepend
- value.extend(self._extend)
-
- elif isinstance(value, dict):
- if self._update:
- value.update(self._update)
- elif isinstance(value, set):
- if self._update:
- value.update(self._update)
- self._value = value
- return value
-
- def to_dict(self):
- """return JSONable dict form of my data
-
- Currently update as dict or set, extend, prepend as lists, and inserts as list of tuples.
- """
- d = {}
- if self._update:
- d['update'] = self._update
- if self._extend:
- d['extend'] = self._extend
- if self._prepend:
- d['prepend'] = self._prepend
- elif self._inserts:
- d['inserts'] = self._inserts
- return d
-
-
-def _is_section_key(key):
- """Is a Config key a section name (does it start with a capital)?"""
- if key and key[0].upper()==key[0] and not key.startswith('_'):
- return True
- else:
- return False
-
-
-class Config(dict):
- """An attribute based dict that can do smart merges."""
-
- def __init__(self, *args, **kwds):
- dict.__init__(self, *args, **kwds)
- self._ensure_subconfig()
-
- def _ensure_subconfig(self):
- """ensure that sub-dicts that should be Config objects are
-
- casts dicts that are under section keys to Config objects,
- which is necessary for constructing Config objects from dict literals.
- """
- for key in self:
- obj = self[key]
- if _is_section_key(key) \
- and isinstance(obj, dict) \
- and not isinstance(obj, Config):
- setattr(self, key, Config(obj))
-
- def _merge(self, other):
- """deprecated alias, use Config.merge()"""
- self.merge(other)
-
- def merge(self, other):
- """merge another config object into this one"""
- to_update = {}
+from traitlets.traitlets import HasTraits, List, Any
+
+#-----------------------------------------------------------------------------
+# Exceptions
+#-----------------------------------------------------------------------------
+
+
+class ConfigError(Exception):
+ pass
+
+class ConfigLoaderError(ConfigError):
+ pass
+
+class ConfigFileNotFound(ConfigError):
+ pass
+
+class ArgumentError(ConfigLoaderError):
+ pass
+
+#-----------------------------------------------------------------------------
+# Argparse fix
+#-----------------------------------------------------------------------------
+
+# Unfortunately argparse by default prints help messages to stderr instead of
+# stdout. This makes it annoying to capture long help screens at the command
+# line, since one must know how to pipe stderr, which many users don't know how
+# to do. So we override the print_help method with one that defaults to
+# stdout and use our class instead.
+
+class ArgumentParser(argparse.ArgumentParser):
+ """Simple argparse subclass that prints help to stdout by default."""
+
+ def print_help(self, file=None):
+ if file is None:
+ file = sys.stdout
+ return super(ArgumentParser, self).print_help(file)
+
+ print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
+
+#-----------------------------------------------------------------------------
+# Config class for holding config information
+#-----------------------------------------------------------------------------
+
+class LazyConfigValue(HasTraits):
+ """Proxy object for exposing methods on configurable containers
+
+ Exposes:
+
+ - append, extend, insert on lists
+ - update on dicts
+ - update, add on sets
+ """
+
+ _value = None
+
+ # list methods
+ _extend = List()
+ _prepend = List()
+
+ def append(self, obj):
+ self._extend.append(obj)
+
+ def extend(self, other):
+ self._extend.extend(other)
+
+ def prepend(self, other):
+ """like list.extend, but for the front"""
+ self._prepend[:0] = other
+
+ _inserts = List()
+ def insert(self, index, other):
+ if not isinstance(index, int):
+ raise TypeError("An integer is required")
+ self._inserts.append((index, other))
+
+ # dict methods
+ # update is used for both dict and set
+ _update = Any()
+ def update(self, other):
+ if self._update is None:
+ if isinstance(other, dict):
+ self._update = {}
+ else:
+ self._update = set()
+ self._update.update(other)
+
+ # set methods
+ def add(self, obj):
+ self.update({obj})
+
+ def get_value(self, initial):
+ """construct the value from the initial one
+
+ after applying any insert / extend / update changes
+ """
+ if self._value is not None:
+ return self._value
+ value = copy.deepcopy(initial)
+ if isinstance(value, list):
+ for idx, obj in self._inserts:
+ value.insert(idx, obj)
+ value[:0] = self._prepend
+ value.extend(self._extend)
+
+ elif isinstance(value, dict):
+ if self._update:
+ value.update(self._update)
+ elif isinstance(value, set):
+ if self._update:
+ value.update(self._update)
+ self._value = value
+ return value
+
+ def to_dict(self):
+ """return JSONable dict form of my data
+
+ Currently update as dict or set, extend, prepend as lists, and inserts as list of tuples.
+ """
+ d = {}
+ if self._update:
+ d['update'] = self._update
+ if self._extend:
+ d['extend'] = self._extend
+ if self._prepend:
+ d['prepend'] = self._prepend
+ elif self._inserts:
+ d['inserts'] = self._inserts
+ return d
+
+
+def _is_section_key(key):
+ """Is a Config key a section name (does it start with a capital)?"""
+ if key and key[0].upper()==key[0] and not key.startswith('_'):
+ return True
+ else:
+ return False
+
+
+class Config(dict):
+ """An attribute based dict that can do smart merges."""
+
+ def __init__(self, *args, **kwds):
+ dict.__init__(self, *args, **kwds)
+ self._ensure_subconfig()
+
+ def _ensure_subconfig(self):
+ """ensure that sub-dicts that should be Config objects are
+
+ casts dicts that are under section keys to Config objects,
+ which is necessary for constructing Config objects from dict literals.
+ """
+ for key in self:
+ obj = self[key]
+ if _is_section_key(key) \
+ and isinstance(obj, dict) \
+ and not isinstance(obj, Config):
+ setattr(self, key, Config(obj))
+
+ def _merge(self, other):
+ """deprecated alias, use Config.merge()"""
+ self.merge(other)
+
+ def merge(self, other):
+ """merge another config object into this one"""
+ to_update = {}
for k, v in other.items():
- if k not in self:
- to_update[k] = v
- else: # I have this key
- if isinstance(v, Config) and isinstance(self[k], Config):
- # Recursively merge common sub Configs
- self[k].merge(v)
- else:
- # Plain updates for non-Configs
- to_update[k] = v
-
- self.update(to_update)
-
- def collisions(self, other):
- """Check for collisions between two config objects.
-
- Returns a dict of the form {"Class": {"trait": "collision message"}}`,
- indicating which values have been ignored.
-
- An empty dict indicates no collisions.
- """
- collisions = {}
- for section in self:
- if section not in other:
- continue
- mine = self[section]
- theirs = other[section]
- for key in mine:
- if key in theirs and mine[key] != theirs[key]:
- collisions.setdefault(section, {})
- collisions[section][key] = "%r ignored, using %r" % (mine[key], theirs[key])
- return collisions
-
- def __contains__(self, key):
- # allow nested contains of the form `"Section.key" in config`
- if '.' in key:
- first, remainder = key.split('.', 1)
- if first not in self:
- return False
- return remainder in self[first]
-
- return super(Config, self).__contains__(key)
-
- # .has_key is deprecated for dictionaries.
- has_key = __contains__
-
- def _has_section(self, key):
- return _is_section_key(key) and key in self
-
- def copy(self):
- return type(self)(dict.copy(self))
-
- def __copy__(self):
- return self.copy()
-
- def __deepcopy__(self, memo):
- new_config = type(self)()
- for key, value in self.items():
- if isinstance(value, (Config, LazyConfigValue)):
- # deep copy config objects
- value = copy.deepcopy(value, memo)
- elif type(value) in {dict, list, set, tuple}:
- # shallow copy plain container traits
- value = copy.copy(value)
- new_config[key] = value
- return new_config
-
- def __getitem__(self, key):
- try:
- return dict.__getitem__(self, key)
- except KeyError:
- if _is_section_key(key):
- c = Config()
- dict.__setitem__(self, key, c)
- return c
- elif not key.startswith('_'):
- # undefined, create lazy value, used for container methods
- v = LazyConfigValue()
- dict.__setitem__(self, key, v)
- return v
- else:
- raise KeyError
-
- def __setitem__(self, key, value):
- if _is_section_key(key):
- if not isinstance(value, Config):
- raise ValueError('values whose keys begin with an uppercase '
- 'char must be Config instances: %r, %r' % (key, value))
- dict.__setitem__(self, key, value)
-
- def __getattr__(self, key):
- if key.startswith('__'):
- return dict.__getattr__(self, key)
- try:
- return self.__getitem__(key)
- except KeyError as e:
- raise AttributeError(e)
-
- def __setattr__(self, key, value):
- if key.startswith('__'):
- return dict.__setattr__(self, key, value)
- try:
- self.__setitem__(key, value)
- except KeyError as e:
- raise AttributeError(e)
-
- def __delattr__(self, key):
- if key.startswith('__'):
- return dict.__delattr__(self, key)
- try:
- dict.__delitem__(self, key)
- except KeyError as e:
- raise AttributeError(e)
-
-
-#-----------------------------------------------------------------------------
-# Config loading classes
-#-----------------------------------------------------------------------------
-
-
-class ConfigLoader(object):
- """A object for loading configurations from just about anywhere.
-
- The resulting configuration is packaged as a :class:`Config`.
-
- Notes
- -----
- A :class:`ConfigLoader` does one thing: load a config from a source
- (file, command line arguments) and returns the data as a :class:`Config` object.
- There are lots of things that :class:`ConfigLoader` does not do. It does
- not implement complex logic for finding config files. It does not handle
- default values or merge multiple configs. These things need to be
- handled elsewhere.
- """
-
- def _log_default(self):
- from traitlets.log import get_logger
- return get_logger()
-
- def __init__(self, log=None):
- """A base class for config loaders.
-
- log : instance of :class:`logging.Logger` to use.
- By default loger of :meth:`traitlets.config.application.Application.instance()`
- will be used
-
- Examples
- --------
-
- >>> cl = ConfigLoader()
- >>> config = cl.load_config()
- >>> config
- {}
- """
- self.clear()
- if log is None:
- self.log = self._log_default()
- self.log.debug('Using default logger')
- else:
- self.log = log
-
- def clear(self):
- self.config = Config()
-
- def load_config(self):
- """Load a config from somewhere, return a :class:`Config` instance.
-
- Usually, this will cause self.config to be set and then returned.
- However, in most cases, :meth:`ConfigLoader.clear` should be called
- to erase any previous state.
- """
- self.clear()
- return self.config
-
-
-class FileConfigLoader(ConfigLoader):
- """A base class for file based configurations.
-
- As we add more file based config loaders, the common logic should go
- here.
- """
-
- def __init__(self, filename, path=None, **kw):
- """Build a config loader for a filename and path.
-
- Parameters
- ----------
- filename : str
- The file name of the config file.
- path : str, list, tuple
- The path to search for the config file on, or a sequence of
- paths to try in order.
- """
- super(FileConfigLoader, self).__init__(**kw)
- self.filename = filename
- self.path = path
- self.full_filename = ''
-
- def _find_file(self):
- """Try to find the file by searching the paths."""
- self.full_filename = filefind(self.filename, self.path)
-
-class JSONFileConfigLoader(FileConfigLoader):
+ if k not in self:
+ to_update[k] = v
+ else: # I have this key
+ if isinstance(v, Config) and isinstance(self[k], Config):
+ # Recursively merge common sub Configs
+ self[k].merge(v)
+ else:
+ # Plain updates for non-Configs
+ to_update[k] = v
+
+ self.update(to_update)
+
+ def collisions(self, other):
+ """Check for collisions between two config objects.
+
+ Returns a dict of the form {"Class": {"trait": "collision message"}}`,
+ indicating which values have been ignored.
+
+ An empty dict indicates no collisions.
+ """
+ collisions = {}
+ for section in self:
+ if section not in other:
+ continue
+ mine = self[section]
+ theirs = other[section]
+ for key in mine:
+ if key in theirs and mine[key] != theirs[key]:
+ collisions.setdefault(section, {})
+ collisions[section][key] = "%r ignored, using %r" % (mine[key], theirs[key])
+ return collisions
+
+ def __contains__(self, key):
+ # allow nested contains of the form `"Section.key" in config`
+ if '.' in key:
+ first, remainder = key.split('.', 1)
+ if first not in self:
+ return False
+ return remainder in self[first]
+
+ return super(Config, self).__contains__(key)
+
+ # .has_key is deprecated for dictionaries.
+ has_key = __contains__
+
+ def _has_section(self, key):
+ return _is_section_key(key) and key in self
+
+ def copy(self):
+ return type(self)(dict.copy(self))
+
+ def __copy__(self):
+ return self.copy()
+
+ def __deepcopy__(self, memo):
+ new_config = type(self)()
+ for key, value in self.items():
+ if isinstance(value, (Config, LazyConfigValue)):
+ # deep copy config objects
+ value = copy.deepcopy(value, memo)
+ elif type(value) in {dict, list, set, tuple}:
+ # shallow copy plain container traits
+ value = copy.copy(value)
+ new_config[key] = value
+ return new_config
+
+ def __getitem__(self, key):
+ try:
+ return dict.__getitem__(self, key)
+ except KeyError:
+ if _is_section_key(key):
+ c = Config()
+ dict.__setitem__(self, key, c)
+ return c
+ elif not key.startswith('_'):
+ # undefined, create lazy value, used for container methods
+ v = LazyConfigValue()
+ dict.__setitem__(self, key, v)
+ return v
+ else:
+ raise KeyError
+
+ def __setitem__(self, key, value):
+ if _is_section_key(key):
+ if not isinstance(value, Config):
+ raise ValueError('values whose keys begin with an uppercase '
+ 'char must be Config instances: %r, %r' % (key, value))
+ dict.__setitem__(self, key, value)
+
+ def __getattr__(self, key):
+ if key.startswith('__'):
+ return dict.__getattr__(self, key)
+ try:
+ return self.__getitem__(key)
+ except KeyError as e:
+ raise AttributeError(e)
+
+ def __setattr__(self, key, value):
+ if key.startswith('__'):
+ return dict.__setattr__(self, key, value)
+ try:
+ self.__setitem__(key, value)
+ except KeyError as e:
+ raise AttributeError(e)
+
+ def __delattr__(self, key):
+ if key.startswith('__'):
+ return dict.__delattr__(self, key)
+ try:
+ dict.__delitem__(self, key)
+ except KeyError as e:
+ raise AttributeError(e)
+
+
+#-----------------------------------------------------------------------------
+# Config loading classes
+#-----------------------------------------------------------------------------
+
+
+class ConfigLoader(object):
+ """A object for loading configurations from just about anywhere.
+
+ The resulting configuration is packaged as a :class:`Config`.
+
+ Notes
+ -----
+ A :class:`ConfigLoader` does one thing: load a config from a source
+ (file, command line arguments) and returns the data as a :class:`Config` object.
+ There are lots of things that :class:`ConfigLoader` does not do. It does
+ not implement complex logic for finding config files. It does not handle
+ default values or merge multiple configs. These things need to be
+ handled elsewhere.
+ """
+
+ def _log_default(self):
+ from traitlets.log import get_logger
+ return get_logger()
+
+ def __init__(self, log=None):
+ """A base class for config loaders.
+
+ log : instance of :class:`logging.Logger` to use.
+ By default loger of :meth:`traitlets.config.application.Application.instance()`
+ will be used
+
+ Examples
+ --------
+
+ >>> cl = ConfigLoader()
+ >>> config = cl.load_config()
+ >>> config
+ {}
+ """
+ self.clear()
+ if log is None:
+ self.log = self._log_default()
+ self.log.debug('Using default logger')
+ else:
+ self.log = log
+
+ def clear(self):
+ self.config = Config()
+
+ def load_config(self):
+ """Load a config from somewhere, return a :class:`Config` instance.
+
+ Usually, this will cause self.config to be set and then returned.
+ However, in most cases, :meth:`ConfigLoader.clear` should be called
+ to erase any previous state.
+ """
+ self.clear()
+ return self.config
+
+
+class FileConfigLoader(ConfigLoader):
+ """A base class for file based configurations.
+
+ As we add more file based config loaders, the common logic should go
+ here.
+ """
+
+ def __init__(self, filename, path=None, **kw):
+ """Build a config loader for a filename and path.
+
+ Parameters
+ ----------
+ filename : str
+ The file name of the config file.
+ path : str, list, tuple
+ The path to search for the config file on, or a sequence of
+ paths to try in order.
+ """
+ super(FileConfigLoader, self).__init__(**kw)
+ self.filename = filename
+ self.path = path
+ self.full_filename = ''
+
+ def _find_file(self):
+ """Try to find the file by searching the paths."""
+ self.full_filename = filefind(self.filename, self.path)
+
+class JSONFileConfigLoader(FileConfigLoader):
"""A JSON file loader for config
-
+
Can also act as a context manager that rewrite the configuration file to disk on exit.
Example::
@@ -396,36 +396,36 @@ class JSONFileConfigLoader(FileConfigLoader):
"""
- def load_config(self):
- """Load the config from a file and return it as a Config object."""
- self.clear()
- try:
- self._find_file()
- except IOError as e:
- raise ConfigFileNotFound(str(e))
- dct = self._read_file_as_dict()
- self.config = self._convert_to_config(dct)
- return self.config
-
- def _read_file_as_dict(self):
- with open(self.full_filename) as f:
- return json.load(f)
-
- def _convert_to_config(self, dictionary):
- if 'version' in dictionary:
- version = dictionary.pop('version')
- else:
- version = 1
-
- if version == 1:
- return Config(dictionary)
- else:
- raise ValueError('Unknown version of JSON config file: {version}'.format(version=version))
-
+ def load_config(self):
+ """Load the config from a file and return it as a Config object."""
+ self.clear()
+ try:
+ self._find_file()
+ except IOError as e:
+ raise ConfigFileNotFound(str(e))
+ dct = self._read_file_as_dict()
+ self.config = self._convert_to_config(dct)
+ return self.config
+
+ def _read_file_as_dict(self):
+ with open(self.full_filename) as f:
+ return json.load(f)
+
+ def _convert_to_config(self, dictionary):
+ if 'version' in dictionary:
+ version = dictionary.pop('version')
+ else:
+ version = 1
+
+ if version == 1:
+ return Config(dictionary)
+ else:
+ raise ValueError('Unknown version of JSON config file: {version}'.format(version=version))
+
def __enter__(self):
self.load_config()
return self.config
-
+
def __exit__(self, exc_type, exc_value, traceback):
"""
Exit the context manager but do not handle any errors.
@@ -440,418 +440,418 @@ class JSONFileConfigLoader(FileConfigLoader):
-class PyFileConfigLoader(FileConfigLoader):
- """A config loader for pure python files.
-
- This is responsible for locating a Python config file by filename and
- path, then executing it to construct a Config object.
- """
-
- def load_config(self):
- """Load the config from a file and return it as a Config object."""
- self.clear()
- try:
- self._find_file()
- except IOError as e:
- raise ConfigFileNotFound(str(e))
- self._read_file_as_dict()
- return self.config
-
- def load_subconfig(self, fname, path=None):
- """Injected into config file namespace as load_subconfig"""
- if path is None:
- path = self.path
-
- loader = self.__class__(fname, path)
- try:
- sub_config = loader.load_config()
- except ConfigFileNotFound:
- # Pass silently if the sub config is not there,
- # treat it as an empty config file.
- pass
- else:
- self.config.merge(sub_config)
-
- def _read_file_as_dict(self):
- """Load the config file into self.config, with recursive loading."""
- def get_config():
- """Unnecessary now, but a deprecation warning is more trouble than it's worth."""
- return self.config
-
- namespace = dict(
- c=self.config,
- load_subconfig=self.load_subconfig,
- get_config=get_config,
- __file__=self.full_filename,
- )
- fs_encoding = sys.getfilesystemencoding() or 'ascii'
- conf_filename = self.full_filename.encode(fs_encoding)
- py3compat.execfile(conf_filename, namespace)
-
-
-class CommandLineConfigLoader(ConfigLoader):
- """A config loader for command line arguments.
-
- As we add more command line based loaders, the common logic should go
- here.
- """
-
- def _exec_config_str(self, lhs, rhs):
- """execute self.config.<lhs> = <rhs>
-
- * expands ~ with expanduser
- * tries to assign with literal_eval, otherwise assigns with just the string,
- allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not*
- equivalent are `--C.a=4` and `--C.a='4'`.
- """
- rhs = os.path.expanduser(rhs)
- try:
- # Try to see if regular Python syntax will work. This
- # won't handle strings as the quote marks are removed
- # by the system shell.
- value = literal_eval(rhs)
- except (NameError, SyntaxError, ValueError):
- # This case happens if the rhs is a string.
- value = rhs
-
- exec(u'self.config.%s = value' % lhs)
-
- def _load_flag(self, cfg):
- """update self.config from a flag, which can be a dict or Config"""
- if isinstance(cfg, (dict, Config)):
- # don't clobber whole config sections, update
- # each section from config:
+class PyFileConfigLoader(FileConfigLoader):
+ """A config loader for pure python files.
+
+ This is responsible for locating a Python config file by filename and
+ path, then executing it to construct a Config object.
+ """
+
+ def load_config(self):
+ """Load the config from a file and return it as a Config object."""
+ self.clear()
+ try:
+ self._find_file()
+ except IOError as e:
+ raise ConfigFileNotFound(str(e))
+ self._read_file_as_dict()
+ return self.config
+
+ def load_subconfig(self, fname, path=None):
+ """Injected into config file namespace as load_subconfig"""
+ if path is None:
+ path = self.path
+
+ loader = self.__class__(fname, path)
+ try:
+ sub_config = loader.load_config()
+ except ConfigFileNotFound:
+ # Pass silently if the sub config is not there,
+ # treat it as an empty config file.
+ pass
+ else:
+ self.config.merge(sub_config)
+
+ def _read_file_as_dict(self):
+ """Load the config file into self.config, with recursive loading."""
+ def get_config():
+ """Unnecessary now, but a deprecation warning is more trouble than it's worth."""
+ return self.config
+
+ namespace = dict(
+ c=self.config,
+ load_subconfig=self.load_subconfig,
+ get_config=get_config,
+ __file__=self.full_filename,
+ )
+ fs_encoding = sys.getfilesystemencoding() or 'ascii'
+ conf_filename = self.full_filename.encode(fs_encoding)
+ py3compat.execfile(conf_filename, namespace)
+
+
+class CommandLineConfigLoader(ConfigLoader):
+ """A config loader for command line arguments.
+
+ As we add more command line based loaders, the common logic should go
+ here.
+ """
+
+ def _exec_config_str(self, lhs, rhs):
+ """execute self.config.<lhs> = <rhs>
+
+ * expands ~ with expanduser
+ * tries to assign with literal_eval, otherwise assigns with just the string,
+ allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not*
+ equivalent are `--C.a=4` and `--C.a='4'`.
+ """
+ rhs = os.path.expanduser(rhs)
+ try:
+ # Try to see if regular Python syntax will work. This
+ # won't handle strings as the quote marks are removed
+ # by the system shell.
+ value = literal_eval(rhs)
+ except (NameError, SyntaxError, ValueError):
+ # This case happens if the rhs is a string.
+ value = rhs
+
+ exec(u'self.config.%s = value' % lhs)
+
+ def _load_flag(self, cfg):
+ """update self.config from a flag, which can be a dict or Config"""
+ if isinstance(cfg, (dict, Config)):
+ # don't clobber whole config sections, update
+ # each section from config:
for sec,c in cfg.items():
- self.config[sec].update(c)
- else:
- raise TypeError("Invalid flag: %r" % cfg)
-
-# raw --identifier=value pattern
-# but *also* accept '-' as wordsep, for aliases
-# accepts: --foo=a
-# --Class.trait=value
-# --alias-name=value
-# rejects: -foo=value
-# --foo
-# --Class.trait
-kv_pattern = re.compile(r'\-\-[A-Za-z][\w\-]*(\.[\w\-]+)*\=.*')
-
-# just flags, no assignments, with two *or one* leading '-'
-# accepts: --foo
-# -foo-bar-again
-# rejects: --anything=anything
-# --two.word
-
-flag_pattern = re.compile(r'\-\-?\w+[\-\w]*$')
-
-class KeyValueConfigLoader(CommandLineConfigLoader):
- """A config loader that loads key value pairs from the command line.
-
- This allows command line options to be gives in the following form::
-
- ipython --profile="foo" --InteractiveShell.autocall=False
- """
-
- def __init__(self, argv=None, aliases=None, flags=None, **kw):
- """Create a key value pair config loader.
-
- Parameters
- ----------
- argv : list
- A list that has the form of sys.argv[1:] which has unicode
- elements of the form u"key=value". If this is None (default),
- then sys.argv[1:] will be used.
- aliases : dict
- A dict of aliases for configurable traits.
- Keys are the short aliases, Values are the resolved trait.
- Of the form: `{'alias' : 'Configurable.trait'}`
- flags : dict
- A dict of flags, keyed by str name. Vaues can be Config objects,
- dicts, or "key=value" strings. If Config or dict, when the flag
- is triggered, The flag is loaded as `self.config.update(m)`.
-
- Returns
- -------
- config : Config
- The resulting Config object.
-
- Examples
- --------
-
- >>> from traitlets.config.loader import KeyValueConfigLoader
- >>> cl = KeyValueConfigLoader()
- >>> d = cl.load_config(["--A.name='brian'","--B.number=0"])
- >>> sorted(d.items())
- [('A', {'name': 'brian'}), ('B', {'number': 0})]
- """
- super(KeyValueConfigLoader, self).__init__(**kw)
- if argv is None:
- argv = sys.argv[1:]
- self.argv = argv
- self.aliases = aliases or {}
- self.flags = flags or {}
-
-
- def clear(self):
- super(KeyValueConfigLoader, self).clear()
- self.extra_args = []
-
-
- def _decode_argv(self, argv, enc=None):
- """decode argv if bytes, using stdin.encoding, falling back on default enc"""
- uargv = []
- if enc is None:
- enc = DEFAULT_ENCODING
- for arg in argv:
+ self.config[sec].update(c)
+ else:
+ raise TypeError("Invalid flag: %r" % cfg)
+
+# raw --identifier=value pattern
+# but *also* accept '-' as wordsep, for aliases
+# accepts: --foo=a
+# --Class.trait=value
+# --alias-name=value
+# rejects: -foo=value
+# --foo
+# --Class.trait
+kv_pattern = re.compile(r'\-\-[A-Za-z][\w\-]*(\.[\w\-]+)*\=.*')
+
+# just flags, no assignments, with two *or one* leading '-'
+# accepts: --foo
+# -foo-bar-again
+# rejects: --anything=anything
+# --two.word
+
+flag_pattern = re.compile(r'\-\-?\w+[\-\w]*$')
+
+class KeyValueConfigLoader(CommandLineConfigLoader):
+ """A config loader that loads key value pairs from the command line.
+
+ This allows command line options to be gives in the following form::
+
+ ipython --profile="foo" --InteractiveShell.autocall=False
+ """
+
+ def __init__(self, argv=None, aliases=None, flags=None, **kw):
+ """Create a key value pair config loader.
+
+ Parameters
+ ----------
+ argv : list
+ A list that has the form of sys.argv[1:] which has unicode
+ elements of the form u"key=value". If this is None (default),
+ then sys.argv[1:] will be used.
+ aliases : dict
+ A dict of aliases for configurable traits.
+ Keys are the short aliases, Values are the resolved trait.
+ Of the form: `{'alias' : 'Configurable.trait'}`
+ flags : dict
+ A dict of flags, keyed by str name. Vaues can be Config objects,
+ dicts, or "key=value" strings. If Config or dict, when the flag
+ is triggered, The flag is loaded as `self.config.update(m)`.
+
+ Returns
+ -------
+ config : Config
+ The resulting Config object.
+
+ Examples
+ --------
+
+ >>> from traitlets.config.loader import KeyValueConfigLoader
+ >>> cl = KeyValueConfigLoader()
+ >>> d = cl.load_config(["--A.name='brian'","--B.number=0"])
+ >>> sorted(d.items())
+ [('A', {'name': 'brian'}), ('B', {'number': 0})]
+ """
+ super(KeyValueConfigLoader, self).__init__(**kw)
+ if argv is None:
+ argv = sys.argv[1:]
+ self.argv = argv
+ self.aliases = aliases or {}
+ self.flags = flags or {}
+
+
+ def clear(self):
+ super(KeyValueConfigLoader, self).clear()
+ self.extra_args = []
+
+
+ def _decode_argv(self, argv, enc=None):
+ """decode argv if bytes, using stdin.encoding, falling back on default enc"""
+ uargv = []
+ if enc is None:
+ enc = DEFAULT_ENCODING
+ for arg in argv:
if not isinstance(arg, text_type):
- # only decode if not already decoded
- arg = arg.decode(enc)
- uargv.append(arg)
- return uargv
-
-
- def load_config(self, argv=None, aliases=None, flags=None):
- """Parse the configuration and generate the Config object.
-
- After loading, any arguments that are not key-value or
- flags will be stored in self.extra_args - a list of
- unparsed command-line arguments. This is used for
- arguments such as input files or subcommands.
-
- Parameters
- ----------
- argv : list, optional
- A list that has the form of sys.argv[1:] which has unicode
- elements of the form u"key=value". If this is None (default),
- then self.argv will be used.
- aliases : dict
- A dict of aliases for configurable traits.
- Keys are the short aliases, Values are the resolved trait.
- Of the form: `{'alias' : 'Configurable.trait'}`
- flags : dict
- A dict of flags, keyed by str name. Values can be Config objects
- or dicts. When the flag is triggered, The config is loaded as
- `self.config.update(cfg)`.
- """
- self.clear()
- if argv is None:
- argv = self.argv
- if aliases is None:
- aliases = self.aliases
- if flags is None:
- flags = self.flags
-
- # ensure argv is a list of unicode strings:
- uargv = self._decode_argv(argv)
- for idx,raw in enumerate(uargv):
- # strip leading '-'
- item = raw.lstrip('-')
-
- if raw == '--':
- # don't parse arguments after '--'
- # this is useful for relaying arguments to scripts, e.g.
- # ipython -i foo.py --matplotlib=qt -- args after '--' go-to-foo.py
- self.extra_args.extend(uargv[idx+1:])
- break
-
- if kv_pattern.match(raw):
- lhs,rhs = item.split('=',1)
- # Substitute longnames for aliases.
- if lhs in aliases:
- lhs = aliases[lhs]
- if '.' not in lhs:
- # probably a mistyped alias, but not technically illegal
- self.log.warning("Unrecognized alias: '%s', it will probably have no effect.", raw)
- try:
- self._exec_config_str(lhs, rhs)
- except Exception:
- raise ArgumentError("Invalid argument: '%s'" % raw)
-
- elif flag_pattern.match(raw):
- if item in flags:
- cfg,help = flags[item]
- self._load_flag(cfg)
- else:
- raise ArgumentError("Unrecognized flag: '%s'"%raw)
- elif raw.startswith('-'):
- kv = '--'+item
- if kv_pattern.match(kv):
- raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv))
- else:
- raise ArgumentError("Invalid argument: '%s'"%raw)
- else:
- # keep all args that aren't valid in a list,
- # in case our parent knows what to do with them.
- self.extra_args.append(item)
- return self.config
-
-class ArgParseConfigLoader(CommandLineConfigLoader):
- """A loader that uses the argparse module to load from the command line."""
-
- def __init__(self, argv=None, aliases=None, flags=None, log=None, *parser_args, **parser_kw):
- """Create a config loader for use with argparse.
-
- Parameters
- ----------
-
- argv : optional, list
- If given, used to read command-line arguments from, otherwise
- sys.argv[1:] is used.
-
- parser_args : tuple
- A tuple of positional arguments that will be passed to the
- constructor of :class:`argparse.ArgumentParser`.
-
- parser_kw : dict
- A tuple of keyword arguments that will be passed to the
- constructor of :class:`argparse.ArgumentParser`.
-
- Returns
- -------
- config : Config
- The resulting Config object.
- """
- super(CommandLineConfigLoader, self).__init__(log=log)
- self.clear()
- if argv is None:
- argv = sys.argv[1:]
- self.argv = argv
- self.aliases = aliases or {}
- self.flags = flags or {}
-
- self.parser_args = parser_args
- self.version = parser_kw.pop("version", None)
- kwargs = dict(argument_default=argparse.SUPPRESS)
- kwargs.update(parser_kw)
- self.parser_kw = kwargs
-
- def load_config(self, argv=None, aliases=None, flags=None):
- """Parse command line arguments and return as a Config object.
-
- Parameters
- ----------
-
- args : optional, list
- If given, a list with the structure of sys.argv[1:] to parse
- arguments from. If not given, the instance's self.argv attribute
- (given at construction time) is used."""
- self.clear()
- if argv is None:
- argv = self.argv
- if aliases is None:
- aliases = self.aliases
- if flags is None:
- flags = self.flags
- self._create_parser(aliases, flags)
- self._parse_args(argv)
- self._convert_to_config()
- return self.config
-
- def get_extra_args(self):
- if hasattr(self, 'extra_args'):
- return self.extra_args
- else:
- return []
-
- def _create_parser(self, aliases=None, flags=None):
- self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
- self._add_arguments(aliases, flags)
-
- def _add_arguments(self, aliases=None, flags=None):
- raise NotImplementedError("subclasses must implement _add_arguments")
-
- def _parse_args(self, args):
- """self.parser->self.parsed_data"""
- # decode sys.argv to support unicode command-line options
- enc = DEFAULT_ENCODING
- uargs = [py3compat.cast_unicode(a, enc) for a in args]
- self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
-
- def _convert_to_config(self):
- """self.parsed_data->self.config"""
+ # only decode if not already decoded
+ arg = arg.decode(enc)
+ uargv.append(arg)
+ return uargv
+
+
+ def load_config(self, argv=None, aliases=None, flags=None):
+ """Parse the configuration and generate the Config object.
+
+ After loading, any arguments that are not key-value or
+ flags will be stored in self.extra_args - a list of
+ unparsed command-line arguments. This is used for
+ arguments such as input files or subcommands.
+
+ Parameters
+ ----------
+ argv : list, optional
+ A list that has the form of sys.argv[1:] which has unicode
+ elements of the form u"key=value". If this is None (default),
+ then self.argv will be used.
+ aliases : dict
+ A dict of aliases for configurable traits.
+ Keys are the short aliases, Values are the resolved trait.
+ Of the form: `{'alias' : 'Configurable.trait'}`
+ flags : dict
+ A dict of flags, keyed by str name. Values can be Config objects
+ or dicts. When the flag is triggered, The config is loaded as
+ `self.config.update(cfg)`.
+ """
+ self.clear()
+ if argv is None:
+ argv = self.argv
+ if aliases is None:
+ aliases = self.aliases
+ if flags is None:
+ flags = self.flags
+
+ # ensure argv is a list of unicode strings:
+ uargv = self._decode_argv(argv)
+ for idx,raw in enumerate(uargv):
+ # strip leading '-'
+ item = raw.lstrip('-')
+
+ if raw == '--':
+ # don't parse arguments after '--'
+ # this is useful for relaying arguments to scripts, e.g.
+ # ipython -i foo.py --matplotlib=qt -- args after '--' go-to-foo.py
+ self.extra_args.extend(uargv[idx+1:])
+ break
+
+ if kv_pattern.match(raw):
+ lhs,rhs = item.split('=',1)
+ # Substitute longnames for aliases.
+ if lhs in aliases:
+ lhs = aliases[lhs]
+ if '.' not in lhs:
+ # probably a mistyped alias, but not technically illegal
+ self.log.warning("Unrecognized alias: '%s', it will probably have no effect.", raw)
+ try:
+ self._exec_config_str(lhs, rhs)
+ except Exception:
+ raise ArgumentError("Invalid argument: '%s'" % raw)
+
+ elif flag_pattern.match(raw):
+ if item in flags:
+ cfg,help = flags[item]
+ self._load_flag(cfg)
+ else:
+ raise ArgumentError("Unrecognized flag: '%s'"%raw)
+ elif raw.startswith('-'):
+ kv = '--'+item
+ if kv_pattern.match(kv):
+ raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv))
+ else:
+ raise ArgumentError("Invalid argument: '%s'"%raw)
+ else:
+ # keep all args that aren't valid in a list,
+ # in case our parent knows what to do with them.
+ self.extra_args.append(item)
+ return self.config
+
+class ArgParseConfigLoader(CommandLineConfigLoader):
+ """A loader that uses the argparse module to load from the command line."""
+
+ def __init__(self, argv=None, aliases=None, flags=None, log=None, *parser_args, **parser_kw):
+ """Create a config loader for use with argparse.
+
+ Parameters
+ ----------
+
+ argv : optional, list
+ If given, used to read command-line arguments from, otherwise
+ sys.argv[1:] is used.
+
+ parser_args : tuple
+ A tuple of positional arguments that will be passed to the
+ constructor of :class:`argparse.ArgumentParser`.
+
+ parser_kw : dict
+ A tuple of keyword arguments that will be passed to the
+ constructor of :class:`argparse.ArgumentParser`.
+
+ Returns
+ -------
+ config : Config
+ The resulting Config object.
+ """
+ super(CommandLineConfigLoader, self).__init__(log=log)
+ self.clear()
+ if argv is None:
+ argv = sys.argv[1:]
+ self.argv = argv
+ self.aliases = aliases or {}
+ self.flags = flags or {}
+
+ self.parser_args = parser_args
+ self.version = parser_kw.pop("version", None)
+ kwargs = dict(argument_default=argparse.SUPPRESS)
+ kwargs.update(parser_kw)
+ self.parser_kw = kwargs
+
+ def load_config(self, argv=None, aliases=None, flags=None):
+ """Parse command line arguments and return as a Config object.
+
+ Parameters
+ ----------
+
+ args : optional, list
+ If given, a list with the structure of sys.argv[1:] to parse
+ arguments from. If not given, the instance's self.argv attribute
+ (given at construction time) is used."""
+ self.clear()
+ if argv is None:
+ argv = self.argv
+ if aliases is None:
+ aliases = self.aliases
+ if flags is None:
+ flags = self.flags
+ self._create_parser(aliases, flags)
+ self._parse_args(argv)
+ self._convert_to_config()
+ return self.config
+
+ def get_extra_args(self):
+ if hasattr(self, 'extra_args'):
+ return self.extra_args
+ else:
+ return []
+
+ def _create_parser(self, aliases=None, flags=None):
+ self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
+ self._add_arguments(aliases, flags)
+
+ def _add_arguments(self, aliases=None, flags=None):
+ raise NotImplementedError("subclasses must implement _add_arguments")
+
+ def _parse_args(self, args):
+ """self.parser->self.parsed_data"""
+ # decode sys.argv to support unicode command-line options
+ enc = DEFAULT_ENCODING
+ uargs = [py3compat.cast_unicode(a, enc) for a in args]
+ self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
+
+ def _convert_to_config(self):
+ """self.parsed_data->self.config"""
for k, v in vars(self.parsed_data).items():
- exec("self.config.%s = v"%k, locals(), globals())
-
-class KVArgParseConfigLoader(ArgParseConfigLoader):
- """A config loader that loads aliases and flags with argparse,
- but will use KVLoader for the rest. This allows better parsing
- of common args, such as `ipython -c 'print 5'`, but still gets
- arbitrary config with `ipython --InteractiveShell.use_readline=False`"""
-
- def _add_arguments(self, aliases=None, flags=None):
- self.alias_flags = {}
- # print aliases, flags
- if aliases is None:
- aliases = self.aliases
- if flags is None:
- flags = self.flags
- paa = self.parser.add_argument
+ exec("self.config.%s = v"%k, locals(), globals())
+
+class KVArgParseConfigLoader(ArgParseConfigLoader):
+ """A config loader that loads aliases and flags with argparse,
+ but will use KVLoader for the rest. This allows better parsing
+ of common args, such as `ipython -c 'print 5'`, but still gets
+ arbitrary config with `ipython --InteractiveShell.use_readline=False`"""
+
+ def _add_arguments(self, aliases=None, flags=None):
+ self.alias_flags = {}
+ # print aliases, flags
+ if aliases is None:
+ aliases = self.aliases
+ if flags is None:
+ flags = self.flags
+ paa = self.parser.add_argument
for key,value in aliases.items():
- if key in flags:
- # flags
- nargs = '?'
- else:
- nargs = None
- if len(key) is 1:
+ if key in flags:
+ # flags
+ nargs = '?'
+ else:
+ nargs = None
+ if len(key) is 1:
paa('-'+key, '--'+key, type=text_type, dest=value, nargs=nargs)
- else:
+ else:
paa('--'+key, type=text_type, dest=value, nargs=nargs)
for key, (value, help) in flags.items():
- if key in self.aliases:
- #
- self.alias_flags[self.aliases[key]] = value
- continue
- if len(key) is 1:
- paa('-'+key, '--'+key, action='append_const', dest='_flags', const=value)
- else:
- paa('--'+key, action='append_const', dest='_flags', const=value)
-
- def _convert_to_config(self):
- """self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
- # remove subconfigs list from namespace before transforming the Namespace
- if '_flags' in self.parsed_data:
- subcs = self.parsed_data._flags
- del self.parsed_data._flags
- else:
- subcs = []
-
+ if key in self.aliases:
+ #
+ self.alias_flags[self.aliases[key]] = value
+ continue
+ if len(key) is 1:
+ paa('-'+key, '--'+key, action='append_const', dest='_flags', const=value)
+ else:
+ paa('--'+key, action='append_const', dest='_flags', const=value)
+
+ def _convert_to_config(self):
+ """self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
+ # remove subconfigs list from namespace before transforming the Namespace
+ if '_flags' in self.parsed_data:
+ subcs = self.parsed_data._flags
+ del self.parsed_data._flags
+ else:
+ subcs = []
+
for k, v in vars(self.parsed_data).items():
- if v is None:
- # it was a flag that shares the name of an alias
- subcs.append(self.alias_flags[k])
- else:
- # eval the KV assignment
- self._exec_config_str(k, v)
-
- for subc in subcs:
- self._load_flag(subc)
-
- if self.extra_args:
- sub_parser = KeyValueConfigLoader(log=self.log)
- sub_parser.load_config(self.extra_args)
- self.config.merge(sub_parser.config)
- self.extra_args = sub_parser.extra_args
-
-
-def load_pyconfig_files(config_files, path):
- """Load multiple Python config files, merging each of them in turn.
-
- Parameters
- ==========
- config_files : list of str
- List of config files names to load and merge into the config.
- path : unicode
- The full path to the location of the config files.
- """
- config = Config()
- for cf in config_files:
- loader = PyFileConfigLoader(cf, path=path)
- try:
- next_config = loader.load_config()
- except ConfigFileNotFound:
- pass
- except:
- raise
- else:
- config.merge(next_config)
- return config
+ if v is None:
+ # it was a flag that shares the name of an alias
+ subcs.append(self.alias_flags[k])
+ else:
+ # eval the KV assignment
+ self._exec_config_str(k, v)
+
+ for subc in subcs:
+ self._load_flag(subc)
+
+ if self.extra_args:
+ sub_parser = KeyValueConfigLoader(log=self.log)
+ sub_parser.load_config(self.extra_args)
+ self.config.merge(sub_parser.config)
+ self.extra_args = sub_parser.extra_args
+
+
+def load_pyconfig_files(config_files, path):
+ """Load multiple Python config files, merging each of them in turn.
+
+ Parameters
+ ==========
+ config_files : list of str
+ List of config files names to load and merge into the config.
+ path : unicode
+ The full path to the location of the config files.
+ """
+ config = Config()
+ for cf in config_files:
+ loader = PyFileConfigLoader(cf, path=path)
+ try:
+ next_config = loader.load_config()
+ except ConfigFileNotFound:
+ pass
+ except:
+ raise
+ else:
+ config.merge(next_config)
+ return config
diff --git a/contrib/python/traitlets/py2/traitlets/config/manager.py b/contrib/python/traitlets/py2/traitlets/config/manager.py
index 89dc167943..5e5ebde9af 100644
--- a/contrib/python/traitlets/py2/traitlets/config/manager.py
+++ b/contrib/python/traitlets/py2/traitlets/config/manager.py
@@ -1,88 +1,88 @@
-"""Manager to read and modify config data in JSON files.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-import errno
-import io
-import json
-import os
-
+"""Manager to read and modify config data in JSON files.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+import errno
+import io
+import json
+import os
+
from six import PY3
-from traitlets.config import LoggingConfigurable
-from traitlets.traitlets import Unicode
-
-
-def recursive_update(target, new):
- """Recursively update one dictionary using another.
-
- None values will delete their keys.
- """
- for k, v in new.items():
- if isinstance(v, dict):
- if k not in target:
- target[k] = {}
- recursive_update(target[k], v)
- if not target[k]:
- # Prune empty subdicts
- del target[k]
-
- elif v is None:
- target.pop(k, None)
-
- else:
- target[k] = v
-
-
-class BaseJSONConfigManager(LoggingConfigurable):
- """General JSON config manager
-
- Deals with persisting/storing config in a json file
- """
-
- config_dir = Unicode('.')
-
- def ensure_config_dir_exists(self):
- try:
- os.makedirs(self.config_dir, 0o755)
- except OSError as e:
- if e.errno != errno.EEXIST:
- raise
-
- def file_name(self, section_name):
- return os.path.join(self.config_dir, section_name+'.json')
-
- def get(self, section_name):
- """Retrieve the config data for the specified section.
-
- Returns the data as a dictionary, or an empty dictionary if the file
- doesn't exist.
- """
- filename = self.file_name(section_name)
- if os.path.isfile(filename):
- with io.open(filename, encoding='utf-8') as f:
- return json.load(f)
- else:
- return {}
-
- def set(self, section_name, data):
- """Store the given config data.
- """
- filename = self.file_name(section_name)
- self.ensure_config_dir_exists()
-
- if PY3:
- f = io.open(filename, 'w', encoding='utf-8')
- else:
- f = open(filename, 'wb')
- with f:
- json.dump(data, f, indent=2)
-
- def update(self, section_name, new_data):
- """Modify the config section by recursively updating it with new_data.
-
- Returns the modified config data as a dictionary.
- """
- data = self.get(section_name)
- recursive_update(data, new_data)
- self.set(section_name, data)
- return data
+from traitlets.config import LoggingConfigurable
+from traitlets.traitlets import Unicode
+
+
+def recursive_update(target, new):
+ """Recursively update one dictionary using another.
+
+ None values will delete their keys.
+ """
+ for k, v in new.items():
+ if isinstance(v, dict):
+ if k not in target:
+ target[k] = {}
+ recursive_update(target[k], v)
+ if not target[k]:
+ # Prune empty subdicts
+ del target[k]
+
+ elif v is None:
+ target.pop(k, None)
+
+ else:
+ target[k] = v
+
+
+class BaseJSONConfigManager(LoggingConfigurable):
+ """General JSON config manager
+
+ Deals with persisting/storing config in a json file
+ """
+
+ config_dir = Unicode('.')
+
+ def ensure_config_dir_exists(self):
+ try:
+ os.makedirs(self.config_dir, 0o755)
+ except OSError as e:
+ if e.errno != errno.EEXIST:
+ raise
+
+ def file_name(self, section_name):
+ return os.path.join(self.config_dir, section_name+'.json')
+
+ def get(self, section_name):
+ """Retrieve the config data for the specified section.
+
+ Returns the data as a dictionary, or an empty dictionary if the file
+ doesn't exist.
+ """
+ filename = self.file_name(section_name)
+ if os.path.isfile(filename):
+ with io.open(filename, encoding='utf-8') as f:
+ return json.load(f)
+ else:
+ return {}
+
+ def set(self, section_name, data):
+ """Store the given config data.
+ """
+ filename = self.file_name(section_name)
+ self.ensure_config_dir_exists()
+
+ if PY3:
+ f = io.open(filename, 'w', encoding='utf-8')
+ else:
+ f = open(filename, 'wb')
+ with f:
+ json.dump(data, f, indent=2)
+
+ def update(self, section_name, new_data):
+ """Modify the config section by recursively updating it with new_data.
+
+ Returns the modified config data as a dictionary.
+ """
+ data = self.get(section_name)
+ recursive_update(data, new_data)
+ self.set(section_name, data)
+ return data
diff --git a/contrib/python/traitlets/py2/traitlets/log.py b/contrib/python/traitlets/py2/traitlets/log.py
index 559735bd1a..af86b325f5 100644
--- a/contrib/python/traitlets/py2/traitlets/log.py
+++ b/contrib/python/traitlets/py2/traitlets/log.py
@@ -1,27 +1,27 @@
-"""Grab the global logger instance."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import logging
-
-_logger = None
-
-def get_logger():
- """Grab the global logger instance.
+"""Grab the global logger instance."""
- If a global Application is instantiated, grab its logger.
- Otherwise, grab the root logger.
- """
- global _logger
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
- if _logger is None:
- from .config import Application
- if Application.initialized():
- _logger = Application.instance().log
- else:
+import logging
+
+_logger = None
+
+def get_logger():
+ """Grab the global logger instance.
+
+ If a global Application is instantiated, grab its logger.
+ Otherwise, grab the root logger.
+ """
+ global _logger
+
+ if _logger is None:
+ from .config import Application
+ if Application.initialized():
+ _logger = Application.instance().log
+ else:
_logger = logging.getLogger('traitlets')
# Add a NullHandler to silence warnings about not being
# initialized, per best practice for libraries.
_logger.addHandler(logging.NullHandler())
- return _logger
+ return _logger
diff --git a/contrib/python/traitlets/py2/traitlets/traitlets.py b/contrib/python/traitlets/py2/traitlets/traitlets.py
index 233c047dc2..c07daf7400 100644
--- a/contrib/python/traitlets/py2/traitlets/traitlets.py
+++ b/contrib/python/traitlets/py2/traitlets/traitlets.py
@@ -1,98 +1,98 @@
-# encoding: utf-8
-"""
-A lightweight Traits like module.
-
-This is designed to provide a lightweight, simple, pure Python version of
-many of the capabilities of enthought.traits. This includes:
-
-* Validation
-* Type specification with defaults
-* Static and dynamic notification
-* Basic predefined types
-* An API that is similar to enthought.traits
-
-We don't support:
-
-* Delegation
-* Automatic GUI generation
-* A full set of trait types. Most importantly, we don't provide container
- traits (list, dict, tuple) that can trigger notifications if their
- contents change.
-* API compatibility with enthought.traits
-
-There are also some important difference in our design:
-
-* enthought.traits does not validate default values. We do.
-
-We choose to create this module because we need these capabilities, but
-we need them to be pure Python so they work in all Python implementations,
-including Jython and IronPython.
-
-Inheritance diagram:
-
-.. inheritance-diagram:: traitlets.traitlets
- :parts: 3
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-#
-# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
-# also under the terms of the Modified BSD License.
-
-import contextlib
-import inspect
+# encoding: utf-8
+"""
+A lightweight Traits like module.
+
+This is designed to provide a lightweight, simple, pure Python version of
+many of the capabilities of enthought.traits. This includes:
+
+* Validation
+* Type specification with defaults
+* Static and dynamic notification
+* Basic predefined types
+* An API that is similar to enthought.traits
+
+We don't support:
+
+* Delegation
+* Automatic GUI generation
+* A full set of trait types. Most importantly, we don't provide container
+ traits (list, dict, tuple) that can trigger notifications if their
+ contents change.
+* API compatibility with enthought.traits
+
+There are also some important difference in our design:
+
+* enthought.traits does not validate default values. We do.
+
+We choose to create this module because we need these capabilities, but
+we need them to be pure Python so they work in all Python implementations,
+including Jython and IronPython.
+
+Inheritance diagram:
+
+.. inheritance-diagram:: traitlets.traitlets
+ :parts: 3
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+#
+# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
+# also under the terms of the Modified BSD License.
+
+import contextlib
+import inspect
import os
-import re
-import sys
-import types
+import re
+import sys
+import types
import enum
-try:
- from types import ClassType, InstanceType
- ClassTypes = (ClassType, type)
-except:
- ClassTypes = (type,)
-from warnings import warn, warn_explicit
-
+try:
+ from types import ClassType, InstanceType
+ ClassTypes = (ClassType, type)
+except:
+ ClassTypes = (type,)
+from warnings import warn, warn_explicit
+
import six
-
-from .utils.getargspec import getargspec
-from .utils.importstring import import_item
-from .utils.sentinel import Sentinel
+
+from .utils.getargspec import getargspec
+from .utils.importstring import import_item
+from .utils.sentinel import Sentinel
from .utils.bunch import Bunch
-
-SequenceTypes = (list, tuple, set, frozenset)
-
-#-----------------------------------------------------------------------------
-# Basic classes
-#-----------------------------------------------------------------------------
-
-
-Undefined = Sentinel('Undefined', 'traitlets',
-'''
-Used in Traitlets to specify that no defaults are set in kwargs
-'''
-)
-
-All = Sentinel('All', 'traitlets',
-'''
-Used in Traitlets to listen to all types of notification or to notifications
-from all trait attributes.
-'''
-)
-
-# Deprecated alias
-NoDefaultSpecified = Undefined
-
-class TraitError(Exception):
- pass
-
-#-----------------------------------------------------------------------------
-# Utilities
-#-----------------------------------------------------------------------------
-
+
+SequenceTypes = (list, tuple, set, frozenset)
+
+#-----------------------------------------------------------------------------
+# Basic classes
+#-----------------------------------------------------------------------------
+
+
+Undefined = Sentinel('Undefined', 'traitlets',
+'''
+Used in Traitlets to specify that no defaults are set in kwargs
+'''
+)
+
+All = Sentinel('All', 'traitlets',
+'''
+Used in Traitlets to listen to all types of notification or to notifications
+from all trait attributes.
+'''
+)
+
+# Deprecated alias
+NoDefaultSpecified = Undefined
+
+class TraitError(Exception):
+ pass
+
+#-----------------------------------------------------------------------------
+# Utilities
+#-----------------------------------------------------------------------------
+
from ipython_genutils.py3compat import cast_unicode_py2
-
+
_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
def isidentifier(s):
@@ -117,331 +117,331 @@ def _should_warn(key):
else:
return False
-def _deprecated_method(method, cls, method_name, msg):
- """Show deprecation warning about a magic method definition.
-
- Uses warn_explicit to bind warning to method definition instead of triggering code,
- which isn't relevant.
- """
+def _deprecated_method(method, cls, method_name, msg):
+ """Show deprecation warning about a magic method definition.
+
+ Uses warn_explicit to bind warning to method definition instead of triggering code,
+ which isn't relevant.
+ """
warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format(
- classname=cls.__name__, method_name=method_name, msg=msg
- )
-
- for parent in inspect.getmro(cls):
- if method_name in parent.__dict__:
- cls = parent
- break
+ classname=cls.__name__, method_name=method_name, msg=msg
+ )
+
+ for parent in inspect.getmro(cls):
+ if method_name in parent.__dict__:
+ cls = parent
+ break
# limit deprecation messages to once per package
package_name = cls.__module__.split('.', 1)[0]
key = (package_name, msg)
if not _should_warn(key):
return
- try:
- fname = inspect.getsourcefile(method) or "<unknown>"
- lineno = inspect.getsourcelines(method)[1] or 0
+ try:
+ fname = inspect.getsourcefile(method) or "<unknown>"
+ lineno = inspect.getsourcelines(method)[1] or 0
except (IOError, TypeError) as e:
- # Failed to inspect for some reason
- warn(warn_msg + ('\n(inspection failed) %s' % e), DeprecationWarning)
- else:
- warn_explicit(warn_msg, DeprecationWarning, fname, lineno)
-
-def class_of(object):
- """ Returns a string containing the class name of an object with the
- correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
- 'a PlotValue').
- """
+ # Failed to inspect for some reason
+ warn(warn_msg + ('\n(inspection failed) %s' % e), DeprecationWarning)
+ else:
+ warn_explicit(warn_msg, DeprecationWarning, fname, lineno)
+
+def class_of(object):
+ """ Returns a string containing the class name of an object with the
+ correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
+ 'a PlotValue').
+ """
if isinstance( object, six.string_types ):
- return add_article( object )
-
- return add_article( object.__class__.__name__ )
-
-
-def add_article(name):
- """ Returns a string containing the correct indefinite article ('a' or 'an')
- prefixed to the specified string.
- """
- if name[:1].lower() in 'aeiou':
- return 'an ' + name
-
- return 'a ' + name
-
-
-def repr_type(obj):
- """ Return a string representation of a value and its type for readable
- error messages.
- """
- the_type = type(obj)
+ return add_article( object )
+
+ return add_article( object.__class__.__name__ )
+
+
+def add_article(name):
+ """ Returns a string containing the correct indefinite article ('a' or 'an')
+ prefixed to the specified string.
+ """
+ if name[:1].lower() in 'aeiou':
+ return 'an ' + name
+
+ return 'a ' + name
+
+
+def repr_type(obj):
+ """ Return a string representation of a value and its type for readable
+ error messages.
+ """
+ the_type = type(obj)
if six.PY2 and the_type is InstanceType:
- # Old-style class.
- the_type = obj.__class__
- msg = '%r %r' % (obj, the_type)
- return msg
-
-
-def is_trait(t):
- """ Returns whether the given value is an instance or subclass of TraitType.
- """
- return (isinstance(t, TraitType) or
- (isinstance(t, type) and issubclass(t, TraitType)))
-
-
-def parse_notifier_name(names):
- """Convert the name argument to a list of names.
-
- Examples
- --------
-
- >>> parse_notifier_name([])
- [All]
- >>> parse_notifier_name('a')
- ['a']
- >>> parse_notifier_name(['a', 'b'])
- ['a', 'b']
- >>> parse_notifier_name(All)
- [All]
- """
+ # Old-style class.
+ the_type = obj.__class__
+ msg = '%r %r' % (obj, the_type)
+ return msg
+
+
+def is_trait(t):
+ """ Returns whether the given value is an instance or subclass of TraitType.
+ """
+ return (isinstance(t, TraitType) or
+ (isinstance(t, type) and issubclass(t, TraitType)))
+
+
+def parse_notifier_name(names):
+ """Convert the name argument to a list of names.
+
+ Examples
+ --------
+
+ >>> parse_notifier_name([])
+ [All]
+ >>> parse_notifier_name('a')
+ ['a']
+ >>> parse_notifier_name(['a', 'b'])
+ ['a', 'b']
+ >>> parse_notifier_name(All)
+ [All]
+ """
if names is All or isinstance(names, six.string_types):
- return [names]
+ return [names]
else:
- if not names or All in names:
- return [All]
- for n in names:
+ if not names or All in names:
+ return [All]
+ for n in names:
if not isinstance(n, six.string_types):
raise TypeError("names must be strings, not %r" % n)
- return names
-
-
-class _SimpleTest:
- def __init__ ( self, value ): self.value = value
- def __call__ ( self, test ):
- return test == self.value
- def __repr__(self):
- return "<SimpleTest(%r)" % self.value
- def __str__(self):
- return self.__repr__()
-
-
-def getmembers(object, predicate=None):
- """A safe version of inspect.getmembers that handles missing attributes.
-
- This is useful when there are descriptor based attributes that for
- some reason raise AttributeError even though they exist. This happens
- in zope.inteface with the __provides__ attribute.
- """
- results = []
- for key in dir(object):
- try:
- value = getattr(object, key)
- except AttributeError:
- pass
- else:
- if not predicate or predicate(value):
- results.append((key, value))
- results.sort()
- return results
-
-def _validate_link(*tuples):
- """Validate arguments for traitlet link functions"""
- for t in tuples:
- if not len(t) == 2:
- raise TypeError("Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t)
- obj, trait_name = t
- if not isinstance(obj, HasTraits):
- raise TypeError("Each object must be HasTraits, not %r" % type(obj))
- if not trait_name in obj.traits():
- raise TypeError("%r has no trait %r" % (obj, trait_name))
-
-class link(object):
- """Link traits from different objects together so they remain in sync.
-
- Parameters
- ----------
- source : (object / attribute name) pair
- target : (object / attribute name) pair
-
- Examples
- --------
-
- >>> c = link((src, 'value'), (tgt, 'value'))
- >>> src.value = 5 # updates other objects as well
- """
- updating = False
-
- def __init__(self, source, target):
- _validate_link(source, target)
- self.source, self.target = source, target
- try:
- setattr(target[0], target[1], getattr(source[0], source[1]))
- finally:
- source[0].observe(self._update_target, names=source[1])
- target[0].observe(self._update_source, names=target[1])
-
- @contextlib.contextmanager
- def _busy_updating(self):
- self.updating = True
- try:
- yield
- finally:
- self.updating = False
-
- def _update_target(self, change):
- if self.updating:
- return
- with self._busy_updating():
+ return names
+
+
+class _SimpleTest:
+ def __init__ ( self, value ): self.value = value
+ def __call__ ( self, test ):
+ return test == self.value
+ def __repr__(self):
+ return "<SimpleTest(%r)" % self.value
+ def __str__(self):
+ return self.__repr__()
+
+
+def getmembers(object, predicate=None):
+ """A safe version of inspect.getmembers that handles missing attributes.
+
+ This is useful when there are descriptor based attributes that for
+ some reason raise AttributeError even though they exist. This happens
+ in zope.inteface with the __provides__ attribute.
+ """
+ results = []
+ for key in dir(object):
+ try:
+ value = getattr(object, key)
+ except AttributeError:
+ pass
+ else:
+ if not predicate or predicate(value):
+ results.append((key, value))
+ results.sort()
+ return results
+
+def _validate_link(*tuples):
+ """Validate arguments for traitlet link functions"""
+ for t in tuples:
+ if not len(t) == 2:
+ raise TypeError("Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t)
+ obj, trait_name = t
+ if not isinstance(obj, HasTraits):
+ raise TypeError("Each object must be HasTraits, not %r" % type(obj))
+ if not trait_name in obj.traits():
+ raise TypeError("%r has no trait %r" % (obj, trait_name))
+
+class link(object):
+ """Link traits from different objects together so they remain in sync.
+
+ Parameters
+ ----------
+ source : (object / attribute name) pair
+ target : (object / attribute name) pair
+
+ Examples
+ --------
+
+ >>> c = link((src, 'value'), (tgt, 'value'))
+ >>> src.value = 5 # updates other objects as well
+ """
+ updating = False
+
+ def __init__(self, source, target):
+ _validate_link(source, target)
+ self.source, self.target = source, target
+ try:
+ setattr(target[0], target[1], getattr(source[0], source[1]))
+ finally:
+ source[0].observe(self._update_target, names=source[1])
+ target[0].observe(self._update_source, names=target[1])
+
+ @contextlib.contextmanager
+ def _busy_updating(self):
+ self.updating = True
+ try:
+ yield
+ finally:
+ self.updating = False
+
+ def _update_target(self, change):
+ if self.updating:
+ return
+ with self._busy_updating():
setattr(self.target[0], self.target[1], change.new)
-
- def _update_source(self, change):
- if self.updating:
- return
- with self._busy_updating():
+
+ def _update_source(self, change):
+ if self.updating:
+ return
+ with self._busy_updating():
setattr(self.source[0], self.source[1], change.new)
-
- def unlink(self):
- self.source[0].unobserve(self._update_target, names=self.source[1])
- self.target[0].unobserve(self._update_source, names=self.target[1])
- self.source, self.target = None, None
-
-
-class directional_link(object):
- """Link the trait of a source object with traits of target objects.
-
- Parameters
- ----------
- source : (object, attribute name) pair
- target : (object, attribute name) pair
- transform: callable (optional)
- Data transformation between source and target.
-
- Examples
- --------
-
- >>> c = directional_link((src, 'value'), (tgt, 'value'))
- >>> src.value = 5 # updates target objects
- >>> tgt.value = 6 # does not update source object
- """
- updating = False
-
- def __init__(self, source, target, transform=None):
- self._transform = transform if transform else lambda x: x
- _validate_link(source, target)
- self.source, self.target = source, target
- try:
- setattr(target[0], target[1],
- self._transform(getattr(source[0], source[1])))
- finally:
- self.source[0].observe(self._update, names=self.source[1])
-
- @contextlib.contextmanager
- def _busy_updating(self):
- self.updating = True
- try:
- yield
- finally:
- self.updating = False
-
- def _update(self, change):
- if self.updating:
- return
- with self._busy_updating():
- setattr(self.target[0], self.target[1],
+
+ def unlink(self):
+ self.source[0].unobserve(self._update_target, names=self.source[1])
+ self.target[0].unobserve(self._update_source, names=self.target[1])
+ self.source, self.target = None, None
+
+
+class directional_link(object):
+ """Link the trait of a source object with traits of target objects.
+
+ Parameters
+ ----------
+ source : (object, attribute name) pair
+ target : (object, attribute name) pair
+ transform: callable (optional)
+ Data transformation between source and target.
+
+ Examples
+ --------
+
+ >>> c = directional_link((src, 'value'), (tgt, 'value'))
+ >>> src.value = 5 # updates target objects
+ >>> tgt.value = 6 # does not update source object
+ """
+ updating = False
+
+ def __init__(self, source, target, transform=None):
+ self._transform = transform if transform else lambda x: x
+ _validate_link(source, target)
+ self.source, self.target = source, target
+ try:
+ setattr(target[0], target[1],
+ self._transform(getattr(source[0], source[1])))
+ finally:
+ self.source[0].observe(self._update, names=self.source[1])
+
+ @contextlib.contextmanager
+ def _busy_updating(self):
+ self.updating = True
+ try:
+ yield
+ finally:
+ self.updating = False
+
+ def _update(self, change):
+ if self.updating:
+ return
+ with self._busy_updating():
+ setattr(self.target[0], self.target[1],
self._transform(change.new))
-
- def unlink(self):
- self.source[0].unobserve(self._update, names=self.source[1])
- self.source, self.target = None, None
-
-dlink = directional_link
-
-
-#-----------------------------------------------------------------------------
+
+ def unlink(self):
+ self.source[0].unobserve(self._update, names=self.source[1])
+ self.source, self.target = None, None
+
+dlink = directional_link
+
+
+#-----------------------------------------------------------------------------
# Base Descriptor Class
-#-----------------------------------------------------------------------------
-
-
-class BaseDescriptor(object):
- """Base descriptor class
-
- Notes
- -----
- This implements Python's descriptor prototol.
-
- This class is the base class for all such descriptors. The
- only magic we use is a custom metaclass for the main :class:`HasTraits`
- class that does the following:
-
- 1. Sets the :attr:`name` attribute of every :class:`BaseDescriptor`
- instance in the class dict to the name of the attribute.
- 2. Sets the :attr:`this_class` attribute of every :class:`BaseDescriptor`
- instance in the class dict to the *class* that declared the trait.
- This is used by the :class:`This` trait to allow subclasses to
- accept superclasses for :class:`This` values.
- """
-
- name = None
- this_class = None
-
- def class_init(self, cls, name):
- """Part of the initialization which may depend on the underlying
- HasDescriptors class.
-
- It is typically overloaded for specific types.
-
- This method is called by :meth:`MetaHasDescriptors.__init__`
- passing the class (`cls`) and `name` under which the descriptor
- has been assigned.
- """
- self.this_class = cls
- self.name = name
-
- def instance_init(self, obj):
- """Part of the initialization which may depend on the underlying
- HasDescriptors instance.
-
- It is typically overloaded for specific types.
-
- This method is called by :meth:`HasTraits.__new__` and in the
- :meth:`BaseDescriptor.instance_init` method of descriptors holding
- other descriptors.
- """
- pass
-
-
-class TraitType(BaseDescriptor):
- """A base class for all trait types.
- """
-
- metadata = {}
- default_value = Undefined
- allow_none = False
- read_only = False
- info_text = 'any value'
-
+#-----------------------------------------------------------------------------
+
+
+class BaseDescriptor(object):
+ """Base descriptor class
+
+ Notes
+ -----
+ This implements Python's descriptor prototol.
+
+ This class is the base class for all such descriptors. The
+ only magic we use is a custom metaclass for the main :class:`HasTraits`
+ class that does the following:
+
+ 1. Sets the :attr:`name` attribute of every :class:`BaseDescriptor`
+ instance in the class dict to the name of the attribute.
+ 2. Sets the :attr:`this_class` attribute of every :class:`BaseDescriptor`
+ instance in the class dict to the *class* that declared the trait.
+ This is used by the :class:`This` trait to allow subclasses to
+ accept superclasses for :class:`This` values.
+ """
+
+ name = None
+ this_class = None
+
+ def class_init(self, cls, name):
+ """Part of the initialization which may depend on the underlying
+ HasDescriptors class.
+
+ It is typically overloaded for specific types.
+
+ This method is called by :meth:`MetaHasDescriptors.__init__`
+ passing the class (`cls`) and `name` under which the descriptor
+ has been assigned.
+ """
+ self.this_class = cls
+ self.name = name
+
+ def instance_init(self, obj):
+ """Part of the initialization which may depend on the underlying
+ HasDescriptors instance.
+
+ It is typically overloaded for specific types.
+
+ This method is called by :meth:`HasTraits.__new__` and in the
+ :meth:`BaseDescriptor.instance_init` method of descriptors holding
+ other descriptors.
+ """
+ pass
+
+
+class TraitType(BaseDescriptor):
+ """A base class for all trait types.
+ """
+
+ metadata = {}
+ default_value = Undefined
+ allow_none = False
+ read_only = False
+ info_text = 'any value'
+
def __init__(self, default_value=Undefined, allow_none=False, read_only=None, help=None,
config=None, **kwargs):
- """Declare a traitlet.
-
- If *allow_none* is True, None is a valid value in addition to any
- values that are normally valid. The default is up to the subclass.
- For most trait types, the default value for ``allow_none`` is False.
-
- Extra metadata can be associated with the traitlet using the .tag() convenience method
- or by using the traitlet instance's .metadata dictionary.
- """
- if default_value is not Undefined:
- self.default_value = default_value
+ """Declare a traitlet.
+
+ If *allow_none* is True, None is a valid value in addition to any
+ values that are normally valid. The default is up to the subclass.
+ For most trait types, the default value for ``allow_none`` is False.
+
+ Extra metadata can be associated with the traitlet using the .tag() convenience method
+ or by using the traitlet instance's .metadata dictionary.
+ """
+ if default_value is not Undefined:
+ self.default_value = default_value
if allow_none:
- self.allow_none = allow_none
- if read_only is not None:
- self.read_only = read_only
- self.help = help if help is not None else ''
-
+ self.allow_none = allow_none
+ if read_only is not None:
+ self.read_only = read_only
+ self.help = help if help is not None else ''
+
if len(kwargs) > 0:
- stacklevel = 1
- f = inspect.currentframe()
- # count supers to determine stacklevel for warning
- while f.f_code.co_name == '__init__':
- stacklevel += 1
- f = f.f_back
+ stacklevel = 1
+ f = inspect.currentframe()
+ # count supers to determine stacklevel for warning
+ while f.f_code.co_name == '__init__':
+ stacklevel += 1
+ f = f.f_back
mod = f.f_globals.get('__name__') or ''
pkg = mod.split('.', 1)[0]
key = tuple(['metadata-tag', pkg] + sorted(kwargs))
@@ -450,365 +450,365 @@ class TraitType(BaseDescriptor):
"With traitlets 4.1, metadata should be set using the .tag() method, "
"e.g., Int().tag(key1='value1', key2='value2')" % (kwargs,),
DeprecationWarning, stacklevel=stacklevel)
- if len(self.metadata) > 0:
- self.metadata = self.metadata.copy()
+ if len(self.metadata) > 0:
+ self.metadata = self.metadata.copy()
self.metadata.update(kwargs)
- else:
+ else:
self.metadata = kwargs
- else:
- self.metadata = self.metadata.copy()
+ else:
+ self.metadata = self.metadata.copy()
if config is not None:
self.metadata['config'] = config
-
- # We add help to the metadata during a deprecation period so that
- # code that looks for the help string there can find it.
- if help is not None:
- self.metadata['help'] = help
-
- def get_default_value(self):
- """DEPRECATED: Retrieve the static default value for this trait.
-
- Use self.default_value instead
- """
+
+ # We add help to the metadata during a deprecation period so that
+ # code that looks for the help string there can find it.
+ if help is not None:
+ self.metadata['help'] = help
+
+ def get_default_value(self):
+ """DEPRECATED: Retrieve the static default value for this trait.
+
+ Use self.default_value instead
+ """
warn("get_default_value is deprecated in traitlets 4.0: use the .default_value attribute", DeprecationWarning,
- stacklevel=2)
- return self.default_value
-
- def init_default_value(self, obj):
- """DEPRECATED: Set the static default value for the trait type.
- """
+ stacklevel=2)
+ return self.default_value
+
+ def init_default_value(self, obj):
+ """DEPRECATED: Set the static default value for the trait type.
+ """
warn("init_default_value is deprecated in traitlets 4.0, and may be removed in the future", DeprecationWarning,
- stacklevel=2)
- value = self._validate(obj, self.default_value)
- obj._trait_values[self.name] = value
- return value
-
- def _dynamic_default_callable(self, obj):
- """Retrieve a callable to calculate the default for this traitlet.
-
- This looks for:
-
+ stacklevel=2)
+ value = self._validate(obj, self.default_value)
+ obj._trait_values[self.name] = value
+ return value
+
+ def _dynamic_default_callable(self, obj):
+ """Retrieve a callable to calculate the default for this traitlet.
+
+ This looks for:
+
* default generators registered with the @default descriptor.
- * obj._{name}_default() on the class with the traitlet, or a subclass
- that obj belongs to.
- * trait.make_dynamic_default, which is defined by Instance
-
- If neither exist, it returns None
- """
- # Traitlets without a name are not on the instance, e.g. in List or Union
- if self.name:
-
- # Only look for default handlers in classes derived from self.this_class.
- mro = type(obj).mro()
- meth_name = '_%s_default' % self.name
- for cls in mro[:mro.index(self.this_class) + 1]:
- if hasattr(cls, '_trait_default_generators'):
- default_handler = cls._trait_default_generators.get(self.name)
- if default_handler is not None and default_handler.this_class == cls:
- return types.MethodType(default_handler.func, obj)
-
- if meth_name in cls.__dict__:
- method = getattr(obj, meth_name)
- return method
-
- return getattr(self, 'make_dynamic_default', None)
-
- def instance_init(self, obj):
- # If no dynamic initialiser is present, and the trait implementation or
- # use provides a static default, transfer that to obj._trait_values.
+ * obj._{name}_default() on the class with the traitlet, or a subclass
+ that obj belongs to.
+ * trait.make_dynamic_default, which is defined by Instance
+
+ If neither exist, it returns None
+ """
+ # Traitlets without a name are not on the instance, e.g. in List or Union
+ if self.name:
+
+ # Only look for default handlers in classes derived from self.this_class.
+ mro = type(obj).mro()
+ meth_name = '_%s_default' % self.name
+ for cls in mro[:mro.index(self.this_class) + 1]:
+ if hasattr(cls, '_trait_default_generators'):
+ default_handler = cls._trait_default_generators.get(self.name)
+ if default_handler is not None and default_handler.this_class == cls:
+ return types.MethodType(default_handler.func, obj)
+
+ if meth_name in cls.__dict__:
+ method = getattr(obj, meth_name)
+ return method
+
+ return getattr(self, 'make_dynamic_default', None)
+
+ def instance_init(self, obj):
+ # If no dynamic initialiser is present, and the trait implementation or
+ # use provides a static default, transfer that to obj._trait_values.
with obj.cross_validation_lock:
if (self._dynamic_default_callable(obj) is None) \
and (self.default_value is not Undefined):
v = self._validate(obj, self.default_value)
if self.name is not None:
obj._trait_values[self.name] = v
-
+
def get(self, obj, cls=None):
- try:
- value = obj._trait_values[self.name]
- except KeyError:
- # Check for a dynamic initializer.
- dynamic_default = self._dynamic_default_callable(obj)
- if dynamic_default is None:
- raise TraitError("No default value found for %s trait of %r"
- % (self.name, obj))
- value = self._validate(obj, dynamic_default())
- obj._trait_values[self.name] = value
- return value
- except Exception:
- # This should never be reached.
- raise TraitError('Unexpected error in TraitType: '
- 'default value not set properly')
- else:
- return value
-
- def __get__(self, obj, cls=None):
- """Get the value of the trait by self.name for the instance.
-
- Default values are instantiated when :meth:`HasTraits.__new__`
- is called. Thus by the time this method gets called either the
- default value or a user defined value (they called :meth:`__set__`)
- is in the :class:`HasTraits` instance.
- """
- if obj is None:
- return self
- else:
- return self.get(obj, cls)
-
- def set(self, obj, value):
- new_value = self._validate(obj, value)
- try:
- old_value = obj._trait_values[self.name]
- except KeyError:
- old_value = self.default_value
-
- obj._trait_values[self.name] = new_value
- try:
- silent = bool(old_value == new_value)
- except:
- # if there is an error in comparing, default to notify
- silent = False
- if silent is not True:
- # we explicitly compare silent to True just in case the equality
- # comparison above returns something other than True/False
- obj._notify_trait(self.name, old_value, new_value)
-
- def __set__(self, obj, value):
- """Set the value of the trait by self.name for the instance.
-
- Values pass through a validation stage where errors are raised when
- impropper types, or types that cannot be coerced, are encountered.
- """
- if self.read_only:
- raise TraitError('The "%s" trait is read-only.' % self.name)
- else:
- self.set(obj, value)
-
- def _validate(self, obj, value):
- if value is None and self.allow_none:
- return value
- if hasattr(self, 'validate'):
- value = self.validate(obj, value)
- if obj._cross_validation_lock is False:
- value = self._cross_validate(obj, value)
- return value
-
- def _cross_validate(self, obj, value):
- if self.name in obj._trait_validators:
+ try:
+ value = obj._trait_values[self.name]
+ except KeyError:
+ # Check for a dynamic initializer.
+ dynamic_default = self._dynamic_default_callable(obj)
+ if dynamic_default is None:
+ raise TraitError("No default value found for %s trait of %r"
+ % (self.name, obj))
+ value = self._validate(obj, dynamic_default())
+ obj._trait_values[self.name] = value
+ return value
+ except Exception:
+ # This should never be reached.
+ raise TraitError('Unexpected error in TraitType: '
+ 'default value not set properly')
+ else:
+ return value
+
+ def __get__(self, obj, cls=None):
+ """Get the value of the trait by self.name for the instance.
+
+ Default values are instantiated when :meth:`HasTraits.__new__`
+ is called. Thus by the time this method gets called either the
+ default value or a user defined value (they called :meth:`__set__`)
+ is in the :class:`HasTraits` instance.
+ """
+ if obj is None:
+ return self
+ else:
+ return self.get(obj, cls)
+
+ def set(self, obj, value):
+ new_value = self._validate(obj, value)
+ try:
+ old_value = obj._trait_values[self.name]
+ except KeyError:
+ old_value = self.default_value
+
+ obj._trait_values[self.name] = new_value
+ try:
+ silent = bool(old_value == new_value)
+ except:
+ # if there is an error in comparing, default to notify
+ silent = False
+ if silent is not True:
+ # we explicitly compare silent to True just in case the equality
+ # comparison above returns something other than True/False
+ obj._notify_trait(self.name, old_value, new_value)
+
+ def __set__(self, obj, value):
+ """Set the value of the trait by self.name for the instance.
+
+ Values pass through a validation stage where errors are raised when
+ impropper types, or types that cannot be coerced, are encountered.
+ """
+ if self.read_only:
+ raise TraitError('The "%s" trait is read-only.' % self.name)
+ else:
+ self.set(obj, value)
+
+ def _validate(self, obj, value):
+ if value is None and self.allow_none:
+ return value
+ if hasattr(self, 'validate'):
+ value = self.validate(obj, value)
+ if obj._cross_validation_lock is False:
+ value = self._cross_validate(obj, value)
+ return value
+
+ def _cross_validate(self, obj, value):
+ if self.name in obj._trait_validators:
proposal = Bunch({'trait': self, 'value': value, 'owner': obj})
- value = obj._trait_validators[self.name](obj, proposal)
- elif hasattr(obj, '_%s_validate' % self.name):
- meth_name = '_%s_validate' % self.name
- cross_validate = getattr(obj, meth_name)
- _deprecated_method(cross_validate, obj.__class__, meth_name,
- "use @validate decorator instead.")
- value = cross_validate(value, self)
- return value
-
- def __or__(self, other):
- if isinstance(other, Union):
- return Union([self] + other.trait_types)
- else:
- return Union([self, other])
-
- def info(self):
- return self.info_text
-
- def error(self, obj, value):
- if obj is not None:
- e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
- % (self.name, class_of(obj),
- self.info(), repr_type(value))
- else:
- e = "The '%s' trait must be %s, but a value of %r was specified." \
- % (self.name, self.info(), repr_type(value))
- raise TraitError(e)
-
- def get_metadata(self, key, default=None):
- """DEPRECATED: Get a metadata value.
-
- Use .metadata[key] or .metadata.get(key, default) instead.
- """
- if key == 'help':
- msg = "use the instance .help string directly, like x.help"
- else:
- msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)"
+ value = obj._trait_validators[self.name](obj, proposal)
+ elif hasattr(obj, '_%s_validate' % self.name):
+ meth_name = '_%s_validate' % self.name
+ cross_validate = getattr(obj, meth_name)
+ _deprecated_method(cross_validate, obj.__class__, meth_name,
+ "use @validate decorator instead.")
+ value = cross_validate(value, self)
+ return value
+
+ def __or__(self, other):
+ if isinstance(other, Union):
+ return Union([self] + other.trait_types)
+ else:
+ return Union([self, other])
+
+ def info(self):
+ return self.info_text
+
+ def error(self, obj, value):
+ if obj is not None:
+ e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
+ % (self.name, class_of(obj),
+ self.info(), repr_type(value))
+ else:
+ e = "The '%s' trait must be %s, but a value of %r was specified." \
+ % (self.name, self.info(), repr_type(value))
+ raise TraitError(e)
+
+ def get_metadata(self, key, default=None):
+ """DEPRECATED: Get a metadata value.
+
+ Use .metadata[key] or .metadata.get(key, default) instead.
+ """
+ if key == 'help':
+ msg = "use the instance .help string directly, like x.help"
+ else:
+ msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)"
warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
- return self.metadata.get(key, default)
-
- def set_metadata(self, key, value):
- """DEPRECATED: Set a metadata key/value.
-
- Use .metadata[key] = value instead.
- """
- if key == 'help':
- msg = "use the instance .help string directly, like x.help = value"
- else:
- msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value"
+ return self.metadata.get(key, default)
+
+ def set_metadata(self, key, value):
+ """DEPRECATED: Set a metadata key/value.
+
+ Use .metadata[key] = value instead.
+ """
+ if key == 'help':
+ msg = "use the instance .help string directly, like x.help = value"
+ else:
+ msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value"
warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
- self.metadata[key] = value
-
- def tag(self, **metadata):
- """Sets metadata and returns self.
-
- This allows convenient metadata tagging when initializing the trait, such as:
-
- >>> Int(0).tag(config=True, sync=True)
- """
+ self.metadata[key] = value
+
+ def tag(self, **metadata):
+ """Sets metadata and returns self.
+
+ This allows convenient metadata tagging when initializing the trait, such as:
+
+ >>> Int(0).tag(config=True, sync=True)
+ """
maybe_constructor_keywords = set(metadata.keys()).intersection({'help','allow_none', 'read_only', 'default_value'})
if maybe_constructor_keywords:
warn('The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s '%
maybe_constructor_keywords, UserWarning, stacklevel=2)
- self.metadata.update(metadata)
- return self
-
- def default_value_repr(self):
- return repr(self.default_value)
-
-#-----------------------------------------------------------------------------
-# The HasTraits implementation
-#-----------------------------------------------------------------------------
-
-class _CallbackWrapper(object):
- """An object adapting a on_trait_change callback into an observe callback.
-
- The comparison operator __eq__ is implemented to enable removal of wrapped
- callbacks.
- """
-
- def __init__(self, cb):
- self.cb = cb
- # Bound methods have an additional 'self' argument.
- offset = -1 if isinstance(self.cb, types.MethodType) else 0
- self.nargs = len(getargspec(cb)[0]) + offset
- if (self.nargs > 4):
- raise TraitError('a trait changed callback must have 0-4 arguments.')
-
- def __eq__(self, other):
- # The wrapper is equal to the wrapped element
- if isinstance(other, _CallbackWrapper):
- return self.cb == other.cb
- else:
- return self.cb == other
-
- def __call__(self, change):
- # The wrapper is callable
- if self.nargs == 0:
- self.cb()
- elif self.nargs == 1:
+ self.metadata.update(metadata)
+ return self
+
+ def default_value_repr(self):
+ return repr(self.default_value)
+
+#-----------------------------------------------------------------------------
+# The HasTraits implementation
+#-----------------------------------------------------------------------------
+
+class _CallbackWrapper(object):
+ """An object adapting a on_trait_change callback into an observe callback.
+
+ The comparison operator __eq__ is implemented to enable removal of wrapped
+ callbacks.
+ """
+
+ def __init__(self, cb):
+ self.cb = cb
+ # Bound methods have an additional 'self' argument.
+ offset = -1 if isinstance(self.cb, types.MethodType) else 0
+ self.nargs = len(getargspec(cb)[0]) + offset
+ if (self.nargs > 4):
+ raise TraitError('a trait changed callback must have 0-4 arguments.')
+
+ def __eq__(self, other):
+ # The wrapper is equal to the wrapped element
+ if isinstance(other, _CallbackWrapper):
+ return self.cb == other.cb
+ else:
+ return self.cb == other
+
+ def __call__(self, change):
+ # The wrapper is callable
+ if self.nargs == 0:
+ self.cb()
+ elif self.nargs == 1:
self.cb(change.name)
- elif self.nargs == 2:
+ elif self.nargs == 2:
self.cb(change.name, change.new)
- elif self.nargs == 3:
+ elif self.nargs == 3:
self.cb(change.name, change.old, change.new)
- elif self.nargs == 4:
+ elif self.nargs == 4:
self.cb(change.name, change.old, change.new, change.owner)
-
-def _callback_wrapper(cb):
- if isinstance(cb, _CallbackWrapper):
- return cb
- else:
- return _CallbackWrapper(cb)
-
-
-class MetaHasDescriptors(type):
- """A metaclass for HasDescriptors.
-
- This metaclass makes sure that any TraitType class attributes are
- instantiated and sets their name attribute.
- """
-
- def __new__(mcls, name, bases, classdict):
- """Create the HasDescriptors class."""
+
+def _callback_wrapper(cb):
+ if isinstance(cb, _CallbackWrapper):
+ return cb
+ else:
+ return _CallbackWrapper(cb)
+
+
+class MetaHasDescriptors(type):
+ """A metaclass for HasDescriptors.
+
+ This metaclass makes sure that any TraitType class attributes are
+ instantiated and sets their name attribute.
+ """
+
+ def __new__(mcls, name, bases, classdict):
+ """Create the HasDescriptors class."""
for k, v in classdict.items():
- # ----------------------------------------------------------------
- # Support of deprecated behavior allowing for TraitType types
- # to be used instead of TraitType instances.
- if inspect.isclass(v) and issubclass(v, TraitType):
+ # ----------------------------------------------------------------
+ # Support of deprecated behavior allowing for TraitType types
+ # to be used instead of TraitType instances.
+ if inspect.isclass(v) and issubclass(v, TraitType):
warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
" Passing types is deprecated in traitlets 4.1.",
- DeprecationWarning, stacklevel=2)
- classdict[k] = v()
- # ----------------------------------------------------------------
-
- return super(MetaHasDescriptors, mcls).__new__(mcls, name, bases, classdict)
-
- def __init__(cls, name, bases, classdict):
- """Finish initializing the HasDescriptors class."""
- super(MetaHasDescriptors, cls).__init__(name, bases, classdict)
- cls.setup_class(classdict)
-
- def setup_class(cls, classdict):
- """Setup descriptor instance on the class
-
- This sets the :attr:`this_class` and :attr:`name` attributes of each
- BaseDescriptor in the class dict of the newly created ``cls`` before
- calling their :attr:`class_init` method.
- """
+ DeprecationWarning, stacklevel=2)
+ classdict[k] = v()
+ # ----------------------------------------------------------------
+
+ return super(MetaHasDescriptors, mcls).__new__(mcls, name, bases, classdict)
+
+ def __init__(cls, name, bases, classdict):
+ """Finish initializing the HasDescriptors class."""
+ super(MetaHasDescriptors, cls).__init__(name, bases, classdict)
+ cls.setup_class(classdict)
+
+ def setup_class(cls, classdict):
+ """Setup descriptor instance on the class
+
+ This sets the :attr:`this_class` and :attr:`name` attributes of each
+ BaseDescriptor in the class dict of the newly created ``cls`` before
+ calling their :attr:`class_init` method.
+ """
for k, v in classdict.items():
- if isinstance(v, BaseDescriptor):
- v.class_init(cls, k)
-
-
-class MetaHasTraits(MetaHasDescriptors):
- """A metaclass for HasTraits."""
-
- def setup_class(cls, classdict):
- cls._trait_default_generators = {}
- super(MetaHasTraits, cls).setup_class(classdict)
-
-
-def observe(*names, **kwargs):
- """A decorator which can be used to observe Traits on a class.
-
+ if isinstance(v, BaseDescriptor):
+ v.class_init(cls, k)
+
+
+class MetaHasTraits(MetaHasDescriptors):
+ """A metaclass for HasTraits."""
+
+ def setup_class(cls, classdict):
+ cls._trait_default_generators = {}
+ super(MetaHasTraits, cls).setup_class(classdict)
+
+
+def observe(*names, **kwargs):
+ """A decorator which can be used to observe Traits on a class.
+
The handler passed to the decorator will be called with one ``change``
dict argument. The change dictionary at least holds a 'type' key and a
'name' key, corresponding respectively to the type of notification and the
name of the attribute that triggered the notification.
-
- Other keys may be passed depending on the value of 'type'. In the case
- where type is 'change', we also have the following keys:
- * ``owner`` : the HasTraits instance
- * ``old`` : the old value of the modified trait attribute
- * ``new`` : the new value of the modified trait attribute
- * ``name`` : the name of the modified trait attribute.
-
- Parameters
- ----------
- *names
- The str names of the Traits to observe on the object.
+
+ Other keys may be passed depending on the value of 'type'. In the case
+ where type is 'change', we also have the following keys:
+ * ``owner`` : the HasTraits instance
+ * ``old`` : the old value of the modified trait attribute
+ * ``new`` : the new value of the modified trait attribute
+ * ``name`` : the name of the modified trait attribute.
+
+ Parameters
+ ----------
+ *names
+ The str names of the Traits to observe on the object.
type: str, kwarg-only
The type of event to observe (e.g. 'change')
- """
+ """
if not names:
raise TypeError("Please specify at least one trait name to observe.")
for name in names:
if name is not All and not isinstance(name, six.string_types):
raise TypeError("trait names to observe must be strings or All, not %r" % name)
- return ObserveHandler(names, type=kwargs.get('type', 'change'))
-
-
-def observe_compat(func):
- """Backward-compatibility shim decorator for observers
-
- Use with:
-
- @observe('name')
- @observe_compat
- def _foo_changed(self, change):
- ...
-
- With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work.
- Allows adoption of new observer API without breaking subclasses that override and super.
- """
- def compatible_observer(self, change_or_name, old=Undefined, new=Undefined):
- if isinstance(change_or_name, dict):
- change = change_or_name
- else:
- clsname = self.__class__.__name__
+ return ObserveHandler(names, type=kwargs.get('type', 'change'))
+
+
+def observe_compat(func):
+ """Backward-compatibility shim decorator for observers
+
+ Use with:
+
+ @observe('name')
+ @observe_compat
+ def _foo_changed(self, change):
+ ...
+
+ With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work.
+ Allows adoption of new observer API without breaking subclasses that override and super.
+ """
+ def compatible_observer(self, change_or_name, old=Undefined, new=Undefined):
+ if isinstance(change_or_name, dict):
+ change = change_or_name
+ else:
+ clsname = self.__class__.__name__
warn("A parent of %s._%s_changed has adopted the new (traitlets 4.1) @observe(change) API" % (
- clsname, change_or_name), DeprecationWarning)
+ clsname, change_or_name), DeprecationWarning)
change = Bunch(
type='change',
old=old,
@@ -816,182 +816,182 @@ def observe_compat(func):
name=change_or_name,
owner=self,
)
- return func(self, change)
- return compatible_observer
-
-
-def validate(*names):
- """A decorator to register cross validator of HasTraits object's state
- when a Trait is set.
-
- The handler passed to the decorator must have one ``proposal`` dict argument.
- The proposal dictionary must hold the following keys:
- * ``owner`` : the HasTraits instance
- * ``value`` : the proposed value for the modified trait attribute
- * ``trait`` : the TraitType instance associated with the attribute
-
- Parameters
- ----------
- names
- The str names of the Traits to validate.
-
- Notes
- -----
+ return func(self, change)
+ return compatible_observer
+
+
+def validate(*names):
+ """A decorator to register cross validator of HasTraits object's state
+ when a Trait is set.
+
+ The handler passed to the decorator must have one ``proposal`` dict argument.
+ The proposal dictionary must hold the following keys:
+ * ``owner`` : the HasTraits instance
+ * ``value`` : the proposed value for the modified trait attribute
+ * ``trait`` : the TraitType instance associated with the attribute
+
+ Parameters
+ ----------
+ names
+ The str names of the Traits to validate.
+
+ Notes
+ -----
Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
- the registered cross validator could potentially make changes to attributes
- of the ``HasTraits`` instance. However, we recommend not to do so. The reason
- is that the cross-validation of attributes may run in arbitrary order when
+ the registered cross validator could potentially make changes to attributes
+ of the ``HasTraits`` instance. However, we recommend not to do so. The reason
+ is that the cross-validation of attributes may run in arbitrary order when
exiting the ``hold_trait_notifications`` context, and such changes may not
- commute.
- """
+ commute.
+ """
if not names:
raise TypeError("Please specify at least one trait name to validate.")
for name in names:
if name is not All and not isinstance(name, six.string_types):
raise TypeError("trait names to validate must be strings or All, not %r" % name)
- return ValidateHandler(names)
-
-
-def default(name):
- """ A decorator which assigns a dynamic default for a Trait on a HasTraits object.
-
- Parameters
- ----------
- name
- The str name of the Trait on the object whose default should be generated.
-
- Notes
- -----
- Unlike observers and validators which are properties of the HasTraits
- instance, default value generators are class-level properties.
-
- Besides, default generators are only invoked if they are registered in
- subclasses of `this_type`.
-
- ::
-
- class A(HasTraits):
- bar = Int()
-
- @default('bar')
- def get_bar_default(self):
- return 11
-
-
- class B(A):
- bar = Float() # This trait ignores the default generator defined in
- # the base class A
-
-
- class C(B):
-
- @default('bar')
- def some_other_default(self): # This default generator should not be
- return 3.0 # ignored since it is defined in a
- # class derived from B.a.this_class.
- """
+ return ValidateHandler(names)
+
+
+def default(name):
+ """ A decorator which assigns a dynamic default for a Trait on a HasTraits object.
+
+ Parameters
+ ----------
+ name
+ The str name of the Trait on the object whose default should be generated.
+
+ Notes
+ -----
+ Unlike observers and validators which are properties of the HasTraits
+ instance, default value generators are class-level properties.
+
+ Besides, default generators are only invoked if they are registered in
+ subclasses of `this_type`.
+
+ ::
+
+ class A(HasTraits):
+ bar = Int()
+
+ @default('bar')
+ def get_bar_default(self):
+ return 11
+
+
+ class B(A):
+ bar = Float() # This trait ignores the default generator defined in
+ # the base class A
+
+
+ class C(B):
+
+ @default('bar')
+ def some_other_default(self): # This default generator should not be
+ return 3.0 # ignored since it is defined in a
+ # class derived from B.a.this_class.
+ """
if not isinstance(name, six.string_types):
raise TypeError("Trait name must be a string or All, not %r" % name)
- return DefaultHandler(name)
-
-
-class EventHandler(BaseDescriptor):
-
- def _init_call(self, func):
- self.func = func
- return self
-
- def __call__(self, *args, **kwargs):
+ return DefaultHandler(name)
+
+
+class EventHandler(BaseDescriptor):
+
+ def _init_call(self, func):
+ self.func = func
+ return self
+
+ def __call__(self, *args, **kwargs):
"""Pass `*args` and `**kwargs` to the handler's function if it exists."""
- if hasattr(self, 'func'):
- return self.func(*args, **kwargs)
- else:
- return self._init_call(*args, **kwargs)
-
- def __get__(self, inst, cls=None):
- if inst is None:
- return self
- return types.MethodType(self.func, inst)
-
-
-class ObserveHandler(EventHandler):
-
- def __init__(self, names, type):
- self.trait_names = names
- self.type = type
-
- def instance_init(self, inst):
- inst.observe(self, self.trait_names, type=self.type)
-
-
-class ValidateHandler(EventHandler):
-
- def __init__(self, names):
- self.trait_names = names
-
- def instance_init(self, inst):
- inst._register_validator(self, self.trait_names)
-
-
-class DefaultHandler(EventHandler):
-
- def __init__(self, name):
- self.trait_name = name
-
- def class_init(self, cls, name):
- super(DefaultHandler, self).class_init(cls, name)
- cls._trait_default_generators[self.trait_name] = self
-
-
+ if hasattr(self, 'func'):
+ return self.func(*args, **kwargs)
+ else:
+ return self._init_call(*args, **kwargs)
+
+ def __get__(self, inst, cls=None):
+ if inst is None:
+ return self
+ return types.MethodType(self.func, inst)
+
+
+class ObserveHandler(EventHandler):
+
+ def __init__(self, names, type):
+ self.trait_names = names
+ self.type = type
+
+ def instance_init(self, inst):
+ inst.observe(self, self.trait_names, type=self.type)
+
+
+class ValidateHandler(EventHandler):
+
+ def __init__(self, names):
+ self.trait_names = names
+
+ def instance_init(self, inst):
+ inst._register_validator(self, self.trait_names)
+
+
+class DefaultHandler(EventHandler):
+
+ def __init__(self, name):
+ self.trait_name = name
+
+ def class_init(self, cls, name):
+ super(DefaultHandler, self).class_init(cls, name)
+ cls._trait_default_generators[self.trait_name] = self
+
+
class HasDescriptors(six.with_metaclass(MetaHasDescriptors, object)):
- """The base class for all classes that have descriptors.
- """
-
+ """The base class for all classes that have descriptors.
+ """
+
def __new__(cls, *args, **kwargs):
- # This is needed because object.__new__ only accepts
- # the cls argument.
- new_meth = super(HasDescriptors, cls).__new__
- if new_meth is object.__new__:
- inst = new_meth(cls)
- else:
+ # This is needed because object.__new__ only accepts
+ # the cls argument.
+ new_meth = super(HasDescriptors, cls).__new__
+ if new_meth is object.__new__:
+ inst = new_meth(cls)
+ else:
inst = new_meth(cls, *args, **kwargs)
inst.setup_instance(*args, **kwargs)
- return inst
-
+ return inst
+
def setup_instance(self, *args, **kwargs):
"""
This is called **before** self.__init__ is called.
"""
self._cross_validation_lock = False
- cls = self.__class__
- for key in dir(cls):
- # Some descriptors raise AttributeError like zope.interface's
- # __provides__ attributes even though they exist. This causes
- # AttributeErrors even though they are listed in dir(cls).
- try:
- value = getattr(cls, key)
- except AttributeError:
- pass
- else:
- if isinstance(value, BaseDescriptor):
- value.instance_init(self)
-
-
+ cls = self.__class__
+ for key in dir(cls):
+ # Some descriptors raise AttributeError like zope.interface's
+ # __provides__ attributes even though they exist. This causes
+ # AttributeErrors even though they are listed in dir(cls).
+ try:
+ value = getattr(cls, key)
+ except AttributeError:
+ pass
+ else:
+ if isinstance(value, BaseDescriptor):
+ value.instance_init(self)
+
+
class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
-
+
def setup_instance(self, *args, **kwargs):
- self._trait_values = {}
- self._trait_notifiers = {}
- self._trait_validators = {}
+ self._trait_values = {}
+ self._trait_notifiers = {}
+ self._trait_validators = {}
super(HasTraits, self).setup_instance(*args, **kwargs)
-
+
def __init__(self, *args, **kwargs):
- # Allow trait values to be set using keyword arguments.
- # We need to use setattr for this to trigger validation and
- # notifications.
+ # Allow trait values to be set using keyword arguments.
+ # We need to use setattr for this to trigger validation and
+ # notifications.
super_args = args
super_kwargs = {}
- with self.hold_trait_notifications():
+ with self.hold_trait_notifications():
for key, value in kwargs.items():
if self.has_trait(key):
setattr(self, key, value)
@@ -1017,35 +1017,35 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
DeprecationWarning,
stacklevel=2,
)
-
- def __getstate__(self):
- d = self.__dict__.copy()
- # event handlers stored on an instance are
- # expected to be reinstantiated during a
- # recall of instance_init during __setstate__
- d['_trait_notifiers'] = {}
- d['_trait_validators'] = {}
- return d
-
- def __setstate__(self, state):
- self.__dict__ = state.copy()
-
- # event handlers are reassigned to self
- cls = self.__class__
- for key in dir(cls):
- # Some descriptors raise AttributeError like zope.interface's
- # __provides__ attributes even though they exist. This causes
- # AttributeErrors even though they are listed in dir(cls).
- try:
- value = getattr(cls, key)
- except AttributeError:
- pass
- else:
- if isinstance(value, EventHandler):
- value.instance_init(self)
-
+
+ def __getstate__(self):
+ d = self.__dict__.copy()
+ # event handlers stored on an instance are
+ # expected to be reinstantiated during a
+ # recall of instance_init during __setstate__
+ d['_trait_notifiers'] = {}
+ d['_trait_validators'] = {}
+ return d
+
+ def __setstate__(self, state):
+ self.__dict__ = state.copy()
+
+ # event handlers are reassigned to self
+ cls = self.__class__
+ for key in dir(cls):
+ # Some descriptors raise AttributeError like zope.interface's
+ # __provides__ attributes even though they exist. This causes
+ # AttributeErrors even though they are listed in dir(cls).
+ try:
+ value = getattr(cls, key)
+ except AttributeError:
+ pass
+ else:
+ if isinstance(value, EventHandler):
+ value.instance_init(self)
+
@property
- @contextlib.contextmanager
+ @contextlib.contextmanager
def cross_validation_lock(self):
"""
A contextmanager for running a block with our cross validation lock set
@@ -1065,72 +1065,72 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
self._cross_validation_lock = False
@contextlib.contextmanager
- def hold_trait_notifications(self):
- """Context manager for bundling trait change notifications and cross
- validation.
-
- Use this when doing multiple trait assignments (init, config), to avoid
- race conditions in trait notifiers requesting other trait values.
- All trait notifications will fire after all values have been assigned.
- """
+ def hold_trait_notifications(self):
+ """Context manager for bundling trait change notifications and cross
+ validation.
+
+ Use this when doing multiple trait assignments (init, config), to avoid
+ race conditions in trait notifiers requesting other trait values.
+ All trait notifications will fire after all values have been assigned.
+ """
if self._cross_validation_lock:
- yield
- return
- else:
- cache = {}
- notify_change = self.notify_change
-
- def compress(past_changes, change):
- """Merges the provided change with the last if possible."""
- if past_changes is None:
- return [change]
- else:
+ yield
+ return
+ else:
+ cache = {}
+ notify_change = self.notify_change
+
+ def compress(past_changes, change):
+ """Merges the provided change with the last if possible."""
+ if past_changes is None:
+ return [change]
+ else:
if past_changes[-1]['type'] == 'change' and change.type == 'change':
past_changes[-1]['new'] = change.new
- else:
- # In case of changes other than 'change', append the notification.
- past_changes.append(change)
- return past_changes
-
- def hold(change):
+ else:
+ # In case of changes other than 'change', append the notification.
+ past_changes.append(change)
+ return past_changes
+
+ def hold(change):
name = change.name
- cache[name] = compress(cache.get(name), change)
-
- try:
- # Replace notify_change with `hold`, caching and compressing
- # notifications, disable cross validation and yield.
- self.notify_change = hold
- self._cross_validation_lock = True
- yield
- # Cross validate final values when context is released.
- for name in list(cache.keys()):
- trait = getattr(self.__class__, name)
- value = trait._cross_validate(self, getattr(self, name))
+ cache[name] = compress(cache.get(name), change)
+
+ try:
+ # Replace notify_change with `hold`, caching and compressing
+ # notifications, disable cross validation and yield.
+ self.notify_change = hold
+ self._cross_validation_lock = True
+ yield
+ # Cross validate final values when context is released.
+ for name in list(cache.keys()):
+ trait = getattr(self.__class__, name)
+ value = trait._cross_validate(self, getattr(self, name))
self.set_trait(name, value)
- except TraitError as e:
- # Roll back in case of TraitError during final cross validation.
- self.notify_change = lambda x: None
- for name, changes in cache.items():
- for change in changes[::-1]:
- # TODO: Separate in a rollback function per notification type.
+ except TraitError as e:
+ # Roll back in case of TraitError during final cross validation.
+ self.notify_change = lambda x: None
+ for name, changes in cache.items():
+ for change in changes[::-1]:
+ # TODO: Separate in a rollback function per notification type.
if change.type == 'change':
if change.old is not Undefined:
self.set_trait(name, change.old)
- else:
- self._trait_values.pop(name)
- cache = {}
- raise e
- finally:
- self._cross_validation_lock = False
+ else:
+ self._trait_values.pop(name)
+ cache = {}
+ raise e
+ finally:
+ self._cross_validation_lock = False
# Restore method retrieval from class
del self.notify_change
-
- # trigger delayed notifications
- for changes in cache.values():
- for change in changes:
- self.notify_change(change)
-
- def _notify_trait(self, name, old_value, new_value):
+
+ # trigger delayed notifications
+ for changes in cache.values():
+ for change in changes:
+ self.notify_change(change)
+
+ def _notify_trait(self, name, old_value, new_value):
self.notify_change(Bunch(
name=name,
old=old_value,
@@ -1138,194 +1138,194 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
owner=self,
type='change',
))
-
- def notify_change(self, change):
+
+ def notify_change(self, change):
if not isinstance(change, Bunch):
# cast to bunch if given a dict
change = Bunch(change)
name, type = change.name, change.type
-
- callables = []
- callables.extend(self._trait_notifiers.get(name, {}).get(type, []))
- callables.extend(self._trait_notifiers.get(name, {}).get(All, []))
- callables.extend(self._trait_notifiers.get(All, {}).get(type, []))
- callables.extend(self._trait_notifiers.get(All, {}).get(All, []))
-
- # Now static ones
- magic_name = '_%s_changed' % name
- if hasattr(self, magic_name):
- class_value = getattr(self.__class__, magic_name)
- if not isinstance(class_value, ObserveHandler):
- _deprecated_method(class_value, self.__class__, magic_name,
- "use @observe and @unobserve instead.")
- cb = getattr(self, magic_name)
- # Only append the magic method if it was not manually registered
- if cb not in callables:
- callables.append(_callback_wrapper(cb))
-
- # Call them all now
- # Traits catches and logs errors here. I allow them to raise
- for c in callables:
- # Bound methods have an additional 'self' argument.
-
- if isinstance(c, _CallbackWrapper):
- c = c.__call__
+
+ callables = []
+ callables.extend(self._trait_notifiers.get(name, {}).get(type, []))
+ callables.extend(self._trait_notifiers.get(name, {}).get(All, []))
+ callables.extend(self._trait_notifiers.get(All, {}).get(type, []))
+ callables.extend(self._trait_notifiers.get(All, {}).get(All, []))
+
+ # Now static ones
+ magic_name = '_%s_changed' % name
+ if hasattr(self, magic_name):
+ class_value = getattr(self.__class__, magic_name)
+ if not isinstance(class_value, ObserveHandler):
+ _deprecated_method(class_value, self.__class__, magic_name,
+ "use @observe and @unobserve instead.")
+ cb = getattr(self, magic_name)
+ # Only append the magic method if it was not manually registered
+ if cb not in callables:
+ callables.append(_callback_wrapper(cb))
+
+ # Call them all now
+ # Traits catches and logs errors here. I allow them to raise
+ for c in callables:
+ # Bound methods have an additional 'self' argument.
+
+ if isinstance(c, _CallbackWrapper):
+ c = c.__call__
elif isinstance(c, EventHandler) and c.name is not None:
- c = getattr(self, c.name)
-
- c(change)
-
- def _add_notifiers(self, handler, name, type):
- if name not in self._trait_notifiers:
- nlist = []
- self._trait_notifiers[name] = {type: nlist}
- else:
- if type not in self._trait_notifiers[name]:
- nlist = []
- self._trait_notifiers[name][type] = nlist
- else:
- nlist = self._trait_notifiers[name][type]
- if handler not in nlist:
- nlist.append(handler)
-
- def _remove_notifiers(self, handler, name, type):
- try:
- if handler is None:
- del self._trait_notifiers[name][type]
- else:
- self._trait_notifiers[name][type].remove(handler)
- except KeyError:
- pass
-
- def on_trait_change(self, handler=None, name=None, remove=False):
- """DEPRECATED: Setup a handler to be called when a trait changes.
-
- This is used to setup dynamic notifications of trait changes.
-
- Static handlers can be created by creating methods on a HasTraits
- subclass with the naming convention '_[traitname]_changed'. Thus,
- to create static handler for the trait 'a', create the method
- _a_changed(self, name, old, new) (fewer arguments can be used, see
- below).
-
- If `remove` is True and `handler` is not specified, all change
- handlers for the specified name are uninstalled.
-
- Parameters
- ----------
- handler : callable, None
- A callable that is called when a trait changes. Its
- signature can be handler(), handler(name), handler(name, new),
- handler(name, old, new), or handler(name, old, new, self).
- name : list, str, None
- If None, the handler will apply to all traits. If a list
- of str, handler will apply to all names in the list. If a
- str, the handler will apply just to that name.
- remove : bool
- If False (the default), then install the handler. If True
- then unintall it.
- """
+ c = getattr(self, c.name)
+
+ c(change)
+
+ def _add_notifiers(self, handler, name, type):
+ if name not in self._trait_notifiers:
+ nlist = []
+ self._trait_notifiers[name] = {type: nlist}
+ else:
+ if type not in self._trait_notifiers[name]:
+ nlist = []
+ self._trait_notifiers[name][type] = nlist
+ else:
+ nlist = self._trait_notifiers[name][type]
+ if handler not in nlist:
+ nlist.append(handler)
+
+ def _remove_notifiers(self, handler, name, type):
+ try:
+ if handler is None:
+ del self._trait_notifiers[name][type]
+ else:
+ self._trait_notifiers[name][type].remove(handler)
+ except KeyError:
+ pass
+
+ def on_trait_change(self, handler=None, name=None, remove=False):
+ """DEPRECATED: Setup a handler to be called when a trait changes.
+
+ This is used to setup dynamic notifications of trait changes.
+
+ Static handlers can be created by creating methods on a HasTraits
+ subclass with the naming convention '_[traitname]_changed'. Thus,
+ to create static handler for the trait 'a', create the method
+ _a_changed(self, name, old, new) (fewer arguments can be used, see
+ below).
+
+ If `remove` is True and `handler` is not specified, all change
+ handlers for the specified name are uninstalled.
+
+ Parameters
+ ----------
+ handler : callable, None
+ A callable that is called when a trait changes. Its
+ signature can be handler(), handler(name), handler(name, new),
+ handler(name, old, new), or handler(name, old, new, self).
+ name : list, str, None
+ If None, the handler will apply to all traits. If a list
+ of str, handler will apply to all names in the list. If a
+ str, the handler will apply just to that name.
+ remove : bool
+ If False (the default), then install the handler. If True
+ then unintall it.
+ """
warn("on_trait_change is deprecated in traitlets 4.1: use observe instead",
- DeprecationWarning, stacklevel=2)
- if name is None:
- name = All
- if remove:
- self.unobserve(_callback_wrapper(handler), names=name)
- else:
- self.observe(_callback_wrapper(handler), names=name)
-
- def observe(self, handler, names=All, type='change'):
- """Setup a handler to be called when a trait changes.
-
- This is used to setup dynamic notifications of trait changes.
-
- Parameters
- ----------
- handler : callable
- A callable that is called when a trait changes. Its
+ DeprecationWarning, stacklevel=2)
+ if name is None:
+ name = All
+ if remove:
+ self.unobserve(_callback_wrapper(handler), names=name)
+ else:
+ self.observe(_callback_wrapper(handler), names=name)
+
+ def observe(self, handler, names=All, type='change'):
+ """Setup a handler to be called when a trait changes.
+
+ This is used to setup dynamic notifications of trait changes.
+
+ Parameters
+ ----------
+ handler : callable
+ A callable that is called when a trait changes. Its
signature should be ``handler(change)``, where ``change`` is a
dictionary. The change dictionary at least holds a 'type' key.
- * ``type``: the type of notification.
- Other keys may be passed depending on the value of 'type'. In the
- case where type is 'change', we also have the following keys:
- * ``owner`` : the HasTraits instance
- * ``old`` : the old value of the modified trait attribute
- * ``new`` : the new value of the modified trait attribute
- * ``name`` : the name of the modified trait attribute.
- names : list, str, All
- If names is All, the handler will apply to all traits. If a list
- of str, handler will apply to all names in the list. If a
- str, the handler will apply just to that name.
- type : str, All (default: 'change')
- The type of notification to filter by. If equal to All, then all
- notifications are passed to the observe handler.
- """
- names = parse_notifier_name(names)
- for n in names:
- self._add_notifiers(handler, n, type)
-
- def unobserve(self, handler, names=All, type='change'):
- """Remove a trait change handler.
-
+ * ``type``: the type of notification.
+ Other keys may be passed depending on the value of 'type'. In the
+ case where type is 'change', we also have the following keys:
+ * ``owner`` : the HasTraits instance
+ * ``old`` : the old value of the modified trait attribute
+ * ``new`` : the new value of the modified trait attribute
+ * ``name`` : the name of the modified trait attribute.
+ names : list, str, All
+ If names is All, the handler will apply to all traits. If a list
+ of str, handler will apply to all names in the list. If a
+ str, the handler will apply just to that name.
+ type : str, All (default: 'change')
+ The type of notification to filter by. If equal to All, then all
+ notifications are passed to the observe handler.
+ """
+ names = parse_notifier_name(names)
+ for n in names:
+ self._add_notifiers(handler, n, type)
+
+ def unobserve(self, handler, names=All, type='change'):
+ """Remove a trait change handler.
+
This is used to unregister handlers to trait change notifications.
-
- Parameters
- ----------
- handler : callable
- The callable called when a trait attribute changes.
- names : list, str, All (default: All)
- The names of the traits for which the specified handler should be
- uninstalled. If names is All, the specified handler is uninstalled
- from the list of notifiers corresponding to all changes.
- type : str or All (default: 'change')
- The type of notification to filter by. If All, the specified handler
- is uninstalled from the list of notifiers corresponding to all types.
- """
- names = parse_notifier_name(names)
- for n in names:
- self._remove_notifiers(handler, n, type)
-
- def unobserve_all(self, name=All):
- """Remove trait change handlers of any type for the specified name.
- If name is not specified, removes all trait notifiers."""
- if name is All:
- self._trait_notifiers = {}
- else:
- try:
- del self._trait_notifiers[name]
- except KeyError:
- pass
-
- def _register_validator(self, handler, names):
+
+ Parameters
+ ----------
+ handler : callable
+ The callable called when a trait attribute changes.
+ names : list, str, All (default: All)
+ The names of the traits for which the specified handler should be
+ uninstalled. If names is All, the specified handler is uninstalled
+ from the list of notifiers corresponding to all changes.
+ type : str or All (default: 'change')
+ The type of notification to filter by. If All, the specified handler
+ is uninstalled from the list of notifiers corresponding to all types.
+ """
+ names = parse_notifier_name(names)
+ for n in names:
+ self._remove_notifiers(handler, n, type)
+
+ def unobserve_all(self, name=All):
+ """Remove trait change handlers of any type for the specified name.
+ If name is not specified, removes all trait notifiers."""
+ if name is All:
+ self._trait_notifiers = {}
+ else:
+ try:
+ del self._trait_notifiers[name]
+ except KeyError:
+ pass
+
+ def _register_validator(self, handler, names):
"""Setup a handler to be called when a trait should be cross validated.
-
- This is used to setup dynamic notifications for cross-validation.
-
- If a validator is already registered for any of the provided names, a
+
+ This is used to setup dynamic notifications for cross-validation.
+
+ If a validator is already registered for any of the provided names, a
TraitError is raised and no new validator is registered.
-
- Parameters
- ----------
- handler : callable
- A callable that is called when the given trait is cross-validated.
+
+ Parameters
+ ----------
+ handler : callable
+ A callable that is called when the given trait is cross-validated.
Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
with the following attributes/keys:
- * ``owner`` : the HasTraits instance
- * ``value`` : the proposed value for the modified trait attribute
- * ``trait`` : the TraitType instance associated with the attribute
- names : List of strings
- The names of the traits that should be cross-validated
- """
- for name in names:
- magic_name = '_%s_validate' % name
- if hasattr(self, magic_name):
- class_value = getattr(self.__class__, magic_name)
- if not isinstance(class_value, ValidateHandler):
- _deprecated_method(class_value, self.__class, magic_name,
- "use @validate decorator instead.")
- for name in names:
- self._trait_validators[name] = handler
-
+ * ``owner`` : the HasTraits instance
+ * ``value`` : the proposed value for the modified trait attribute
+ * ``trait`` : the TraitType instance associated with the attribute
+ names : List of strings
+ The names of the traits that should be cross-validated
+ """
+ for name in names:
+ magic_name = '_%s_validate' % name
+ if hasattr(self, magic_name):
+ class_value = getattr(self.__class__, magic_name)
+ if not isinstance(class_value, ValidateHandler):
+ _deprecated_method(class_value, self.__class, magic_name,
+ "use @validate decorator instead.")
+ for name in names:
+ self._trait_validators[name] = handler
+
def add_traits(self, **traits):
"""Dynamically add trait attributes to the HasTraits instance."""
self.__class__ = type(self.__class__.__name__, (self.__class__,),
@@ -1342,123 +1342,123 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
else:
getattr(cls, name).set(self, value)
- @classmethod
- def class_trait_names(cls, **metadata):
- """Get a list of all the names of this class' traits.
-
- This method is just like the :meth:`trait_names` method,
- but is unbound.
- """
+ @classmethod
+ def class_trait_names(cls, **metadata):
+ """Get a list of all the names of this class' traits.
+
+ This method is just like the :meth:`trait_names` method,
+ but is unbound.
+ """
return list(cls.class_traits(**metadata))
-
- @classmethod
- def class_traits(cls, **metadata):
- """Get a ``dict`` of all the traits of this class. The dictionary
- is keyed on the name and the values are the TraitType objects.
-
- This method is just like the :meth:`traits` method, but is unbound.
-
- The TraitTypes returned don't know anything about the values
- that the various HasTrait's instances are holding.
-
- The metadata kwargs allow functions to be passed in which
- filter traits based on metadata values. The functions should
- take a single value as an argument and return a boolean. If
- any function returns False, then the trait is not included in
- the output. If a metadata key doesn't exist, None will be passed
- to the function.
- """
- traits = dict([memb for memb in getmembers(cls) if
- isinstance(memb[1], TraitType)])
-
- if len(metadata) == 0:
- return traits
-
- result = {}
- for name, trait in traits.items():
- for meta_name, meta_eval in metadata.items():
- if type(meta_eval) is not types.FunctionType:
- meta_eval = _SimpleTest(meta_eval)
- if not meta_eval(trait.metadata.get(meta_name, None)):
- break
- else:
- result[name] = trait
-
- return result
-
- @classmethod
- def class_own_traits(cls, **metadata):
- """Get a dict of all the traitlets defined on this class, not a parent.
-
- Works like `class_traits`, except for excluding traits from parents.
- """
- sup = super(cls, cls)
- return {n: t for (n, t) in cls.class_traits(**metadata).items()
- if getattr(sup, n, None) is not t}
-
- def has_trait(self, name):
- """Returns True if the object has a trait with the specified name."""
- return isinstance(getattr(self.__class__, name, None), TraitType)
-
- def trait_names(self, **metadata):
- """Get a list of all the names of this class' traits."""
+
+ @classmethod
+ def class_traits(cls, **metadata):
+ """Get a ``dict`` of all the traits of this class. The dictionary
+ is keyed on the name and the values are the TraitType objects.
+
+ This method is just like the :meth:`traits` method, but is unbound.
+
+ The TraitTypes returned don't know anything about the values
+ that the various HasTrait's instances are holding.
+
+ The metadata kwargs allow functions to be passed in which
+ filter traits based on metadata values. The functions should
+ take a single value as an argument and return a boolean. If
+ any function returns False, then the trait is not included in
+ the output. If a metadata key doesn't exist, None will be passed
+ to the function.
+ """
+ traits = dict([memb for memb in getmembers(cls) if
+ isinstance(memb[1], TraitType)])
+
+ if len(metadata) == 0:
+ return traits
+
+ result = {}
+ for name, trait in traits.items():
+ for meta_name, meta_eval in metadata.items():
+ if type(meta_eval) is not types.FunctionType:
+ meta_eval = _SimpleTest(meta_eval)
+ if not meta_eval(trait.metadata.get(meta_name, None)):
+ break
+ else:
+ result[name] = trait
+
+ return result
+
+ @classmethod
+ def class_own_traits(cls, **metadata):
+ """Get a dict of all the traitlets defined on this class, not a parent.
+
+ Works like `class_traits`, except for excluding traits from parents.
+ """
+ sup = super(cls, cls)
+ return {n: t for (n, t) in cls.class_traits(**metadata).items()
+ if getattr(sup, n, None) is not t}
+
+ def has_trait(self, name):
+ """Returns True if the object has a trait with the specified name."""
+ return isinstance(getattr(self.__class__, name, None), TraitType)
+
+ def trait_names(self, **metadata):
+ """Get a list of all the names of this class' traits."""
return list(self.traits(**metadata))
-
- def traits(self, **metadata):
- """Get a ``dict`` of all the traits of this class. The dictionary
- is keyed on the name and the values are the TraitType objects.
-
- The TraitTypes returned don't know anything about the values
- that the various HasTrait's instances are holding.
-
- The metadata kwargs allow functions to be passed in which
- filter traits based on metadata values. The functions should
- take a single value as an argument and return a boolean. If
- any function returns False, then the trait is not included in
- the output. If a metadata key doesn't exist, None will be passed
- to the function.
- """
- traits = dict([memb for memb in getmembers(self.__class__) if
- isinstance(memb[1], TraitType)])
-
- if len(metadata) == 0:
- return traits
-
- result = {}
- for name, trait in traits.items():
- for meta_name, meta_eval in metadata.items():
- if type(meta_eval) is not types.FunctionType:
- meta_eval = _SimpleTest(meta_eval)
- if not meta_eval(trait.metadata.get(meta_name, None)):
- break
- else:
- result[name] = trait
-
- return result
-
- def trait_metadata(self, traitname, key, default=None):
- """Get metadata values for trait by key."""
- try:
- trait = getattr(self.__class__, traitname)
- except AttributeError:
- raise TraitError("Class %s does not have a trait named %s" %
- (self.__class__.__name__, traitname))
+
+ def traits(self, **metadata):
+ """Get a ``dict`` of all the traits of this class. The dictionary
+ is keyed on the name and the values are the TraitType objects.
+
+ The TraitTypes returned don't know anything about the values
+ that the various HasTrait's instances are holding.
+
+ The metadata kwargs allow functions to be passed in which
+ filter traits based on metadata values. The functions should
+ take a single value as an argument and return a boolean. If
+ any function returns False, then the trait is not included in
+ the output. If a metadata key doesn't exist, None will be passed
+ to the function.
+ """
+ traits = dict([memb for memb in getmembers(self.__class__) if
+ isinstance(memb[1], TraitType)])
+
+ if len(metadata) == 0:
+ return traits
+
+ result = {}
+ for name, trait in traits.items():
+ for meta_name, meta_eval in metadata.items():
+ if type(meta_eval) is not types.FunctionType:
+ meta_eval = _SimpleTest(meta_eval)
+ if not meta_eval(trait.metadata.get(meta_name, None)):
+ break
+ else:
+ result[name] = trait
+
+ return result
+
+ def trait_metadata(self, traitname, key, default=None):
+ """Get metadata values for trait by key."""
+ try:
+ trait = getattr(self.__class__, traitname)
+ except AttributeError:
+ raise TraitError("Class %s does not have a trait named %s" %
+ (self.__class__.__name__, traitname))
metadata_name = '_' + traitname + '_metadata'
if hasattr(self, metadata_name) and key in getattr(self, metadata_name):
return getattr(self, metadata_name).get(key, default)
- else:
- return trait.metadata.get(key, default)
-
+ else:
+ return trait.metadata.get(key, default)
+
@classmethod
def class_own_trait_events(cls, name):
"""Get a dict of all event handlers defined on this class, not a parent.
-
+
Works like ``event_handlers``, except for excluding traits from parents.
"""
sup = super(cls, cls)
return {n: e for (n, e) in cls.events(name).items()
if getattr(sup, n, None) is not e}
-
+
@classmethod
def trait_events(cls, name=None):
"""Get a ``dict`` of all the event handlers of this class.
@@ -1485,329 +1485,329 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
events[k] = v
return events
-#-----------------------------------------------------------------------------
-# Actual TraitTypes implementations/subclasses
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# TraitTypes subclasses for handling classes and instances of classes
-#-----------------------------------------------------------------------------
-
-
-class ClassBasedTraitType(TraitType):
- """
- A trait with error reporting and string -> type resolution for Type,
- Instance and This.
- """
-
- def _resolve_string(self, string):
- """
- Resolve a string supplied for a type into an actual object.
- """
- return import_item(string)
-
- def error(self, obj, value):
- kind = type(value)
+#-----------------------------------------------------------------------------
+# Actual TraitTypes implementations/subclasses
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# TraitTypes subclasses for handling classes and instances of classes
+#-----------------------------------------------------------------------------
+
+
+class ClassBasedTraitType(TraitType):
+ """
+ A trait with error reporting and string -> type resolution for Type,
+ Instance and This.
+ """
+
+ def _resolve_string(self, string):
+ """
+ Resolve a string supplied for a type into an actual object.
+ """
+ return import_item(string)
+
+ def error(self, obj, value):
+ kind = type(value)
if six.PY2 and kind is InstanceType:
- msg = 'class %s' % value.__class__.__name__
- else:
- msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
-
- if obj is not None:
- e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
- % (self.name, class_of(obj),
- self.info(), msg)
- else:
- e = "The '%s' trait must be %s, but a value of %r was specified." \
- % (self.name, self.info(), msg)
-
- raise TraitError(e)
-
-
-class Type(ClassBasedTraitType):
- """A trait whose value must be a subclass of a specified class."""
-
+ msg = 'class %s' % value.__class__.__name__
+ else:
+ msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
+
+ if obj is not None:
+ e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
+ % (self.name, class_of(obj),
+ self.info(), msg)
+ else:
+ e = "The '%s' trait must be %s, but a value of %r was specified." \
+ % (self.name, self.info(), msg)
+
+ raise TraitError(e)
+
+
+class Type(ClassBasedTraitType):
+ """A trait whose value must be a subclass of a specified class."""
+
def __init__ (self, default_value=Undefined, klass=None, **kwargs):
- """Construct a Type trait
-
- A Type trait specifies that its values must be subclasses of
- a particular class.
-
- If only ``default_value`` is given, it is used for the ``klass`` as
- well. If neither are given, both default to ``object``.
-
- Parameters
- ----------
- default_value : class, str or None
- The default value must be a subclass of klass. If an str,
- the str must be a fully specified class name, like 'foo.bar.Bah'.
- The string is resolved into real class, when the parent
- :class:`HasTraits` class is instantiated.
- klass : class, str [ default object ]
- Values of this trait must be a subclass of klass. The klass
- may be specified in a string like: 'foo.bar.MyClass'.
- The string is resolved into real class, when the parent
- :class:`HasTraits` class is instantiated.
- allow_none : bool [ default False ]
- Indicates whether None is allowed as an assignable value.
- """
- if default_value is Undefined:
- new_default_value = object if (klass is None) else klass
- else:
- new_default_value = default_value
-
- if klass is None:
- if (default_value is None) or (default_value is Undefined):
- klass = object
- else:
- klass = default_value
-
+ """Construct a Type trait
+
+ A Type trait specifies that its values must be subclasses of
+ a particular class.
+
+ If only ``default_value`` is given, it is used for the ``klass`` as
+ well. If neither are given, both default to ``object``.
+
+ Parameters
+ ----------
+ default_value : class, str or None
+ The default value must be a subclass of klass. If an str,
+ the str must be a fully specified class name, like 'foo.bar.Bah'.
+ The string is resolved into real class, when the parent
+ :class:`HasTraits` class is instantiated.
+ klass : class, str [ default object ]
+ Values of this trait must be a subclass of klass. The klass
+ may be specified in a string like: 'foo.bar.MyClass'.
+ The string is resolved into real class, when the parent
+ :class:`HasTraits` class is instantiated.
+ allow_none : bool [ default False ]
+ Indicates whether None is allowed as an assignable value.
+ """
+ if default_value is Undefined:
+ new_default_value = object if (klass is None) else klass
+ else:
+ new_default_value = default_value
+
+ if klass is None:
+ if (default_value is None) or (default_value is Undefined):
+ klass = object
+ else:
+ klass = default_value
+
if not (inspect.isclass(klass) or isinstance(klass, six.string_types)):
- raise TraitError("A Type trait must specify a class.")
-
- self.klass = klass
-
+ raise TraitError("A Type trait must specify a class.")
+
+ self.klass = klass
+
super(Type, self).__init__(new_default_value, **kwargs)
-
- def validate(self, obj, value):
- """Validates that the value is a valid object instance."""
+
+ def validate(self, obj, value):
+ """Validates that the value is a valid object instance."""
if isinstance(value, six.string_types):
- try:
- value = self._resolve_string(value)
- except ImportError:
- raise TraitError("The '%s' trait of %s instance must be a type, but "
- "%r could not be imported" % (self.name, obj, value))
- try:
- if issubclass(value, self.klass):
- return value
- except:
- pass
-
- self.error(obj, value)
-
- def info(self):
- """ Returns a description of the trait."""
+ try:
+ value = self._resolve_string(value)
+ except ImportError:
+ raise TraitError("The '%s' trait of %s instance must be a type, but "
+ "%r could not be imported" % (self.name, obj, value))
+ try:
+ if issubclass(value, self.klass):
+ return value
+ except:
+ pass
+
+ self.error(obj, value)
+
+ def info(self):
+ """ Returns a description of the trait."""
if isinstance(self.klass, six.string_types):
- klass = self.klass
- else:
+ klass = self.klass
+ else:
klass = self.klass.__module__ + '.' + self.klass.__name__
- result = "a subclass of '%s'" % klass
- if self.allow_none:
- return result + ' or None'
- return result
-
- def instance_init(self, obj):
- self._resolve_classes()
- super(Type, self).instance_init(obj)
-
- def _resolve_classes(self):
+ result = "a subclass of '%s'" % klass
+ if self.allow_none:
+ return result + ' or None'
+ return result
+
+ def instance_init(self, obj):
+ self._resolve_classes()
+ super(Type, self).instance_init(obj)
+
+ def _resolve_classes(self):
if isinstance(self.klass, six.string_types):
- self.klass = self._resolve_string(self.klass)
+ self.klass = self._resolve_string(self.klass)
if isinstance(self.default_value, six.string_types):
- self.default_value = self._resolve_string(self.default_value)
-
- def default_value_repr(self):
- value = self.default_value
+ self.default_value = self._resolve_string(self.default_value)
+
+ def default_value_repr(self):
+ value = self.default_value
if isinstance(value, six.string_types):
- return repr(value)
- else:
- return repr('{}.{}'.format(value.__module__, value.__name__))
-
-
-class Instance(ClassBasedTraitType):
- """A trait whose value must be an instance of a specified class.
-
- The value can also be an instance of a subclass of the specified class.
-
- Subclasses can declare default classes by overriding the klass attribute
- """
-
- klass = None
-
+ return repr(value)
+ else:
+ return repr('{}.{}'.format(value.__module__, value.__name__))
+
+
+class Instance(ClassBasedTraitType):
+ """A trait whose value must be an instance of a specified class.
+
+ The value can also be an instance of a subclass of the specified class.
+
+ Subclasses can declare default classes by overriding the klass attribute
+ """
+
+ klass = None
+
def __init__(self, klass=None, args=None, kw=None, **kwargs):
- """Construct an Instance trait.
-
- This trait allows values that are instances of a particular
- class or its subclasses. Our implementation is quite different
- from that of enthough.traits as we don't allow instances to be used
- for klass and we handle the ``args`` and ``kw`` arguments differently.
-
- Parameters
- ----------
- klass : class, str
- The class that forms the basis for the trait. Class names
- can also be specified as strings, like 'foo.bar.Bar'.
- args : tuple
- Positional arguments for generating the default value.
- kw : dict
- Keyword arguments for generating the default value.
- allow_none : bool [ default False ]
- Indicates whether None is allowed as a value.
-
- Notes
- -----
- If both ``args`` and ``kw`` are None, then the default value is None.
- If ``args`` is a tuple and ``kw`` is a dict, then the default is
- created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is
- None, the None is replaced by ``()`` or ``{}``, respectively.
- """
- if klass is None:
- klass = self.klass
+ """Construct an Instance trait.
+
+ This trait allows values that are instances of a particular
+ class or its subclasses. Our implementation is quite different
+ from that of enthough.traits as we don't allow instances to be used
+ for klass and we handle the ``args`` and ``kw`` arguments differently.
+
+ Parameters
+ ----------
+ klass : class, str
+ The class that forms the basis for the trait. Class names
+ can also be specified as strings, like 'foo.bar.Bar'.
+ args : tuple
+ Positional arguments for generating the default value.
+ kw : dict
+ Keyword arguments for generating the default value.
+ allow_none : bool [ default False ]
+ Indicates whether None is allowed as a value.
+
+ Notes
+ -----
+ If both ``args`` and ``kw`` are None, then the default value is None.
+ If ``args`` is a tuple and ``kw`` is a dict, then the default is
+ created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is
+ None, the None is replaced by ``()`` or ``{}``, respectively.
+ """
+ if klass is None:
+ klass = self.klass
if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, six.string_types)):
- self.klass = klass
- else:
- raise TraitError('The klass attribute must be a class'
- ' not: %r' % klass)
-
- if (kw is not None) and not isinstance(kw, dict):
- raise TraitError("The 'kw' argument must be a dict or None.")
- if (args is not None) and not isinstance(args, tuple):
- raise TraitError("The 'args' argument must be a tuple or None.")
-
- self.default_args = args
- self.default_kwargs = kw
-
+ self.klass = klass
+ else:
+ raise TraitError('The klass attribute must be a class'
+ ' not: %r' % klass)
+
+ if (kw is not None) and not isinstance(kw, dict):
+ raise TraitError("The 'kw' argument must be a dict or None.")
+ if (args is not None) and not isinstance(args, tuple):
+ raise TraitError("The 'args' argument must be a tuple or None.")
+
+ self.default_args = args
+ self.default_kwargs = kw
+
super(Instance, self).__init__(**kwargs)
-
- def validate(self, obj, value):
- if isinstance(value, self.klass):
- return value
- else:
- self.error(obj, value)
-
- def info(self):
+
+ def validate(self, obj, value):
+ if isinstance(value, self.klass):
+ return value
+ else:
+ self.error(obj, value)
+
+ def info(self):
if isinstance(self.klass, six.string_types):
- klass = self.klass
- else:
- klass = self.klass.__name__
- result = class_of(klass)
- if self.allow_none:
- return result + ' or None'
-
- return result
-
- def instance_init(self, obj):
- self._resolve_classes()
- super(Instance, self).instance_init(obj)
-
- def _resolve_classes(self):
+ klass = self.klass
+ else:
+ klass = self.klass.__name__
+ result = class_of(klass)
+ if self.allow_none:
+ return result + ' or None'
+
+ return result
+
+ def instance_init(self, obj):
+ self._resolve_classes()
+ super(Instance, self).instance_init(obj)
+
+ def _resolve_classes(self):
if isinstance(self.klass, six.string_types):
- self.klass = self._resolve_string(self.klass)
-
- def make_dynamic_default(self):
- if (self.default_args is None) and (self.default_kwargs is None):
- return None
- return self.klass(*(self.default_args or ()),
- **(self.default_kwargs or {}))
-
- def default_value_repr(self):
- return repr(self.make_dynamic_default())
-
-
-class ForwardDeclaredMixin(object):
- """
- Mixin for forward-declared versions of Instance and Type.
- """
- def _resolve_string(self, string):
- """
- Find the specified class name by looking for it in the module in which
- our this_class attribute was defined.
- """
- modname = self.this_class.__module__
- return import_item('.'.join([modname, string]))
-
-
-class ForwardDeclaredType(ForwardDeclaredMixin, Type):
- """
- Forward-declared version of Type.
- """
- pass
-
-
-class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance):
- """
- Forward-declared version of Instance.
- """
- pass
-
-
-class This(ClassBasedTraitType):
- """A trait for instances of the class containing this trait.
-
- Because how how and when class bodies are executed, the ``This``
- trait can only have a default value of None. This, and because we
- always validate default values, ``allow_none`` is *always* true.
- """
-
- info_text = 'an instance of the same type as the receiver or None'
-
+ self.klass = self._resolve_string(self.klass)
+
+ def make_dynamic_default(self):
+ if (self.default_args is None) and (self.default_kwargs is None):
+ return None
+ return self.klass(*(self.default_args or ()),
+ **(self.default_kwargs or {}))
+
+ def default_value_repr(self):
+ return repr(self.make_dynamic_default())
+
+
+class ForwardDeclaredMixin(object):
+ """
+ Mixin for forward-declared versions of Instance and Type.
+ """
+ def _resolve_string(self, string):
+ """
+ Find the specified class name by looking for it in the module in which
+ our this_class attribute was defined.
+ """
+ modname = self.this_class.__module__
+ return import_item('.'.join([modname, string]))
+
+
+class ForwardDeclaredType(ForwardDeclaredMixin, Type):
+ """
+ Forward-declared version of Type.
+ """
+ pass
+
+
+class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance):
+ """
+ Forward-declared version of Instance.
+ """
+ pass
+
+
+class This(ClassBasedTraitType):
+ """A trait for instances of the class containing this trait.
+
+ Because how how and when class bodies are executed, the ``This``
+ trait can only have a default value of None. This, and because we
+ always validate default values, ``allow_none`` is *always* true.
+ """
+
+ info_text = 'an instance of the same type as the receiver or None'
+
def __init__(self, **kwargs):
super(This, self).__init__(None, **kwargs)
-
- def validate(self, obj, value):
- # What if value is a superclass of obj.__class__? This is
- # complicated if it was the superclass that defined the This
- # trait.
- if isinstance(value, self.this_class) or (value is None):
- return value
- else:
- self.error(obj, value)
-
-
-class Union(TraitType):
- """A trait type representing a Union type."""
-
+
+ def validate(self, obj, value):
+ # What if value is a superclass of obj.__class__? This is
+ # complicated if it was the superclass that defined the This
+ # trait.
+ if isinstance(value, self.this_class) or (value is None):
+ return value
+ else:
+ self.error(obj, value)
+
+
+class Union(TraitType):
+ """A trait type representing a Union type."""
+
def __init__(self, trait_types, **kwargs):
- """Construct a Union trait.
-
- This trait allows values that are allowed by at least one of the
- specified trait types. A Union traitlet cannot have metadata on
- its own, besides the metadata of the listed types.
-
- Parameters
- ----------
- trait_types: sequence
- The list of trait types of length at least 1.
-
- Notes
- -----
- Union([Float(), Bool(), Int()]) attempts to validate the provided values
- with the validation function of Float, then Bool, and finally Int.
- """
- self.trait_types = trait_types
+ """Construct a Union trait.
+
+ This trait allows values that are allowed by at least one of the
+ specified trait types. A Union traitlet cannot have metadata on
+ its own, besides the metadata of the listed types.
+
+ Parameters
+ ----------
+ trait_types: sequence
+ The list of trait types of length at least 1.
+
+ Notes
+ -----
+ Union([Float(), Bool(), Int()]) attempts to validate the provided values
+ with the validation function of Float, then Bool, and finally Int.
+ """
+ self.trait_types = trait_types
self.info_text = " or ".join([tt.info() for tt in self.trait_types])
super(Union, self).__init__(**kwargs)
-
- def class_init(self, cls, name):
- for trait_type in self.trait_types:
- trait_type.class_init(cls, None)
- super(Union, self).class_init(cls, name)
-
- def instance_init(self, obj):
- for trait_type in self.trait_types:
- trait_type.instance_init(obj)
- super(Union, self).instance_init(obj)
-
- def validate(self, obj, value):
+
+ def class_init(self, cls, name):
+ for trait_type in self.trait_types:
+ trait_type.class_init(cls, None)
+ super(Union, self).class_init(cls, name)
+
+ def instance_init(self, obj):
+ for trait_type in self.trait_types:
+ trait_type.instance_init(obj)
+ super(Union, self).instance_init(obj)
+
+ def validate(self, obj, value):
with obj.cross_validation_lock:
- for trait_type in self.trait_types:
- try:
- v = trait_type._validate(obj, value)
+ for trait_type in self.trait_types:
+ try:
+ v = trait_type._validate(obj, value)
# In the case of an element trait, the name is None
if self.name is not None:
setattr(obj, '_' + self.name + '_metadata', trait_type.metadata)
- return v
- except TraitError:
- continue
- self.error(obj, value)
-
- def __or__(self, other):
- if isinstance(other, Union):
- return Union(self.trait_types + other.trait_types)
- else:
- return Union(self.trait_types + [other])
-
+ return v
+ except TraitError:
+ continue
+ self.error(obj, value)
+
+ def __or__(self, other):
+ if isinstance(other, Union):
+ return Union(self.trait_types + other.trait_types)
+ else:
+ return Union(self.trait_types + [other])
+
def make_dynamic_default(self):
if self.default_value is not Undefined:
return self.default_value
@@ -1818,17 +1818,17 @@ class Union(TraitType):
return trait_type.make_dynamic_default()
-#-----------------------------------------------------------------------------
-# Basic TraitTypes implementations/subclasses
-#-----------------------------------------------------------------------------
-
-
-class Any(TraitType):
- """A trait which allows any value."""
- default_value = None
- info_text = 'any value'
-
-
+#-----------------------------------------------------------------------------
+# Basic TraitTypes implementations/subclasses
+#-----------------------------------------------------------------------------
+
+
+class Any(TraitType):
+ """A trait which allows any value."""
+ default_value = None
+ info_text = 'any value'
+
+
def _validate_bounds(trait, obj, value):
"""
Validate that a number to be applied to a trait is between bounds.
@@ -1853,42 +1853,42 @@ def _validate_bounds(trait, obj, value):
return value
-class Int(TraitType):
- """An int trait."""
-
- default_value = 0
- info_text = 'an int'
-
+class Int(TraitType):
+ """An int trait."""
+
+ default_value = 0
+ info_text = 'an int'
+
def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
- self.min = kwargs.pop('min', None)
- self.max = kwargs.pop('max', None)
- super(Int, self).__init__(default_value=default_value,
- allow_none=allow_none, **kwargs)
-
- def validate(self, obj, value):
- if not isinstance(value, int):
- self.error(obj, value)
+ self.min = kwargs.pop('min', None)
+ self.max = kwargs.pop('max', None)
+ super(Int, self).__init__(default_value=default_value,
+ allow_none=allow_none, **kwargs)
+
+ def validate(self, obj, value):
+ if not isinstance(value, int):
+ self.error(obj, value)
return _validate_bounds(self, obj, value)
-
-
-class CInt(Int):
- """A casting version of the int trait."""
-
- def validate(self, obj, value):
- try:
+
+
+class CInt(Int):
+ """A casting version of the int trait."""
+
+ def validate(self, obj, value):
+ try:
value = int(value)
- except:
- self.error(obj, value)
+ except:
+ self.error(obj, value)
return _validate_bounds(self, obj, value)
-
+
if six.PY2:
- class Long(TraitType):
- """A long integer trait."""
-
- default_value = 0
- info_text = 'a long'
-
+ class Long(TraitType):
+ """A long integer trait."""
+
+ default_value = 0
+ info_text = 'a long'
+
def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
self.min = kwargs.pop('min', None)
self.max = kwargs.pop('max', None)
@@ -1897,36 +1897,36 @@ if six.PY2:
allow_none=allow_none, **kwargs)
def _validate_long(self, obj, value):
- if isinstance(value, long):
- return value
- if isinstance(value, int):
- return long(value)
- self.error(obj, value)
-
+ if isinstance(value, long):
+ return value
+ if isinstance(value, int):
+ return long(value)
+ self.error(obj, value)
+
def validate(self, obj, value):
value = self._validate_long(obj, value)
return _validate_bounds(self, obj, value)
-
- class CLong(Long):
- """A casting version of the long integer trait."""
-
- def validate(self, obj, value):
- try:
+
+ class CLong(Long):
+ """A casting version of the long integer trait."""
+
+ def validate(self, obj, value):
+ try:
value = long(value)
- except:
- self.error(obj, value)
+ except:
+ self.error(obj, value)
return _validate_bounds(self, obj, value)
-
-
- class Integer(TraitType):
- """An integer trait.
-
- Longs that are unnecessary (<= sys.maxint) are cast to ints."""
-
- default_value = 0
- info_text = 'an integer'
-
+
+
+ class Integer(TraitType):
+ """An integer trait.
+
+ Longs that are unnecessary (<= sys.maxint) are cast to ints."""
+
+ default_value = 0
+ info_text = 'an integer'
+
def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
self.min = kwargs.pop('min', None)
self.max = kwargs.pop('max', None)
@@ -1935,674 +1935,674 @@ if six.PY2:
allow_none=allow_none, **kwargs)
def _validate_int(self, obj, value):
- if isinstance(value, int):
- return value
- if isinstance(value, long):
- # downcast longs that fit in int:
- # note that int(n > sys.maxint) returns a long, so
- # we don't need a condition on this cast
- return int(value)
- if sys.platform == "cli":
- from System import Int64
- if isinstance(value, Int64):
- return int(value)
- self.error(obj, value)
-
+ if isinstance(value, int):
+ return value
+ if isinstance(value, long):
+ # downcast longs that fit in int:
+ # note that int(n > sys.maxint) returns a long, so
+ # we don't need a condition on this cast
+ return int(value)
+ if sys.platform == "cli":
+ from System import Int64
+ if isinstance(value, Int64):
+ return int(value)
+ self.error(obj, value)
+
def validate(self, obj, value):
value = self._validate_int(obj, value)
return _validate_bounds(self, obj, value)
-
+
else:
Long, CLong = Int, CInt
Integer = Int
-class Float(TraitType):
- """A float trait."""
-
- default_value = 0.0
- info_text = 'a float'
-
+class Float(TraitType):
+ """A float trait."""
+
+ default_value = 0.0
+ info_text = 'a float'
+
def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
- self.min = kwargs.pop('min', -float('inf'))
- self.max = kwargs.pop('max', float('inf'))
+ self.min = kwargs.pop('min', -float('inf'))
+ self.max = kwargs.pop('max', float('inf'))
super(Float, self).__init__(default_value=default_value,
- allow_none=allow_none, **kwargs)
-
- def validate(self, obj, value):
- if isinstance(value, int):
- value = float(value)
- if not isinstance(value, float):
- self.error(obj, value)
+ allow_none=allow_none, **kwargs)
+
+ def validate(self, obj, value):
+ if isinstance(value, int):
+ value = float(value)
+ if not isinstance(value, float):
+ self.error(obj, value)
return _validate_bounds(self, obj, value)
-
-
-class CFloat(Float):
- """A casting version of the float trait."""
-
- def validate(self, obj, value):
- try:
+
+
+class CFloat(Float):
+ """A casting version of the float trait."""
+
+ def validate(self, obj, value):
+ try:
value = float(value)
- except:
- self.error(obj, value)
+ except:
+ self.error(obj, value)
return _validate_bounds(self, obj, value)
-
-
-class Complex(TraitType):
- """A trait for complex numbers."""
-
- default_value = 0.0 + 0.0j
- info_text = 'a complex number'
-
- def validate(self, obj, value):
- if isinstance(value, complex):
- return value
- if isinstance(value, (float, int)):
- return complex(value)
- self.error(obj, value)
-
-
-class CComplex(Complex):
- """A casting version of the complex number trait."""
-
- def validate (self, obj, value):
- try:
- return complex(value)
- except:
- self.error(obj, value)
-
-# We should always be explicit about whether we're using bytes or unicode, both
-# for Python 3 conversion and for reliable unicode behaviour on Python 2. So
-# we don't have a Str type.
-class Bytes(TraitType):
- """A trait for byte strings."""
-
- default_value = b''
- info_text = 'a bytes object'
-
- def validate(self, obj, value):
- if isinstance(value, bytes):
- return value
- self.error(obj, value)
-
-
-class CBytes(Bytes):
- """A casting version of the byte string trait."""
-
- def validate(self, obj, value):
- try:
- return bytes(value)
- except:
- self.error(obj, value)
-
-
-class Unicode(TraitType):
- """A trait for unicode strings."""
-
- default_value = u''
- info_text = 'a unicode string'
-
- def validate(self, obj, value):
+
+
+class Complex(TraitType):
+ """A trait for complex numbers."""
+
+ default_value = 0.0 + 0.0j
+ info_text = 'a complex number'
+
+ def validate(self, obj, value):
+ if isinstance(value, complex):
+ return value
+ if isinstance(value, (float, int)):
+ return complex(value)
+ self.error(obj, value)
+
+
+class CComplex(Complex):
+ """A casting version of the complex number trait."""
+
+ def validate (self, obj, value):
+ try:
+ return complex(value)
+ except:
+ self.error(obj, value)
+
+# We should always be explicit about whether we're using bytes or unicode, both
+# for Python 3 conversion and for reliable unicode behaviour on Python 2. So
+# we don't have a Str type.
+class Bytes(TraitType):
+ """A trait for byte strings."""
+
+ default_value = b''
+ info_text = 'a bytes object'
+
+ def validate(self, obj, value):
+ if isinstance(value, bytes):
+ return value
+ self.error(obj, value)
+
+
+class CBytes(Bytes):
+ """A casting version of the byte string trait."""
+
+ def validate(self, obj, value):
+ try:
+ return bytes(value)
+ except:
+ self.error(obj, value)
+
+
+class Unicode(TraitType):
+ """A trait for unicode strings."""
+
+ default_value = u''
+ info_text = 'a unicode string'
+
+ def validate(self, obj, value):
if isinstance(value, six.text_type):
- return value
- if isinstance(value, bytes):
- try:
- return value.decode('ascii', 'strict')
- except UnicodeDecodeError:
- msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
- raise TraitError(msg.format(value, self.name, class_of(obj)))
- self.error(obj, value)
-
-
-class CUnicode(Unicode):
- """A casting version of the unicode trait."""
-
- def validate(self, obj, value):
- try:
+ return value
+ if isinstance(value, bytes):
+ try:
+ return value.decode('ascii', 'strict')
+ except UnicodeDecodeError:
+ msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
+ raise TraitError(msg.format(value, self.name, class_of(obj)))
+ self.error(obj, value)
+
+
+class CUnicode(Unicode):
+ """A casting version of the unicode trait."""
+
+ def validate(self, obj, value):
+ try:
return six.text_type(value)
- except:
- self.error(obj, value)
-
-
-class ObjectName(TraitType):
- """A string holding a valid object name in this version of Python.
-
- This does not check that the name exists in any scope."""
- info_text = "a valid object identifier in Python"
-
+ except:
+ self.error(obj, value)
+
+
+class ObjectName(TraitType):
+ """A string holding a valid object name in this version of Python.
+
+ This does not check that the name exists in any scope."""
+ info_text = "a valid object identifier in Python"
+
if six.PY2:
- # Python 2:
- def coerce_str(self, obj, value):
- "In Python 2, coerce ascii-only unicode to str"
- if isinstance(value, unicode):
- try:
- return str(value)
- except UnicodeEncodeError:
- self.error(obj, value)
- return value
+ # Python 2:
+ def coerce_str(self, obj, value):
+ "In Python 2, coerce ascii-only unicode to str"
+ if isinstance(value, unicode):
+ try:
+ return str(value)
+ except UnicodeEncodeError:
+ self.error(obj, value)
+ return value
else:
coerce_str = staticmethod(lambda _,s: s)
-
- def validate(self, obj, value):
- value = self.coerce_str(obj, value)
-
+
+ def validate(self, obj, value):
+ value = self.coerce_str(obj, value)
+
if isinstance(value, six.string_types) and isidentifier(value):
- return value
- self.error(obj, value)
-
-class DottedObjectName(ObjectName):
- """A string holding a valid dotted object name in Python, such as A.b3._c"""
- def validate(self, obj, value):
- value = self.coerce_str(obj, value)
-
+ return value
+ self.error(obj, value)
+
+class DottedObjectName(ObjectName):
+ """A string holding a valid dotted object name in Python, such as A.b3._c"""
+ def validate(self, obj, value):
+ value = self.coerce_str(obj, value)
+
if isinstance(value, six.string_types) and all(isidentifier(a)
for a in value.split('.')):
- return value
- self.error(obj, value)
-
-
-class Bool(TraitType):
- """A boolean (True, False) trait."""
-
- default_value = False
- info_text = 'a boolean'
-
- def validate(self, obj, value):
- if isinstance(value, bool):
- return value
- self.error(obj, value)
-
-
-class CBool(Bool):
- """A casting version of the boolean trait."""
-
- def validate(self, obj, value):
- try:
- return bool(value)
- except:
- self.error(obj, value)
-
-
-class Enum(TraitType):
- """An enum whose value must be in a given sequence."""
-
+ return value
+ self.error(obj, value)
+
+
+class Bool(TraitType):
+ """A boolean (True, False) trait."""
+
+ default_value = False
+ info_text = 'a boolean'
+
+ def validate(self, obj, value):
+ if isinstance(value, bool):
+ return value
+ self.error(obj, value)
+
+
+class CBool(Bool):
+ """A casting version of the boolean trait."""
+
+ def validate(self, obj, value):
+ try:
+ return bool(value)
+ except:
+ self.error(obj, value)
+
+
+class Enum(TraitType):
+ """An enum whose value must be in a given sequence."""
+
def __init__(self, values, default_value=Undefined, **kwargs):
- self.values = values
+ self.values = values
if kwargs.get('allow_none', False) and default_value is Undefined:
- default_value = None
+ default_value = None
super(Enum, self).__init__(default_value, **kwargs)
-
- def validate(self, obj, value):
- if value in self.values:
- return value
- self.error(obj, value)
-
- def info(self):
- """ Returns a description of the trait."""
- result = 'any of ' + repr(self.values)
- if self.allow_none:
- return result + ' or None'
- return result
-
-class CaselessStrEnum(Enum):
- """An enum of strings where the case should be ignored."""
+
+ def validate(self, obj, value):
+ if value in self.values:
+ return value
+ self.error(obj, value)
+
+ def info(self):
+ """ Returns a description of the trait."""
+ result = 'any of ' + repr(self.values)
+ if self.allow_none:
+ return result + ' or None'
+ return result
+
+class CaselessStrEnum(Enum):
+ """An enum of strings where the case should be ignored."""
def __init__(self, values, default_value=Undefined, **kwargs):
values = [cast_unicode_py2(value) for value in values]
super(CaselessStrEnum, self).__init__(values, default_value=default_value, **kwargs)
- def validate(self, obj, value):
- if isinstance(value, str):
+ def validate(self, obj, value):
+ if isinstance(value, str):
value = cast_unicode_py2(value)
if not isinstance(value, six.string_types):
- self.error(obj, value)
-
- for v in self.values:
- if v.lower() == value.lower():
- return v
- self.error(obj, value)
-
-class Container(Instance):
- """An instance of a container (list, set, etc.)
-
- To be subclassed by overriding klass.
- """
- klass = None
- _cast_types = ()
- _valid_defaults = SequenceTypes
- _trait = None
-
+ self.error(obj, value)
+
+ for v in self.values:
+ if v.lower() == value.lower():
+ return v
+ self.error(obj, value)
+
+class Container(Instance):
+ """An instance of a container (list, set, etc.)
+
+ To be subclassed by overriding klass.
+ """
+ klass = None
+ _cast_types = ()
+ _valid_defaults = SequenceTypes
+ _trait = None
+
def __init__(self, trait=None, default_value=None, **kwargs):
- """Create a container trait type from a list, set, or tuple.
-
- The default value is created by doing ``List(default_value)``,
- which creates a copy of the ``default_value``.
-
- ``trait`` can be specified, which restricts the type of elements
- in the container to that TraitType.
-
- If only one arg is given and it is not a Trait, it is taken as
- ``default_value``:
-
- ``c = List([1, 2, 3])``
-
- Parameters
- ----------
-
- trait : TraitType [ optional ]
- the type for restricting the contents of the Container. If unspecified,
- types are not checked.
-
- default_value : SequenceType [ optional ]
- The default value for the Trait. Must be list/tuple/set, and
- will be cast to the container type.
-
- allow_none : bool [ default False ]
- Whether to allow the value to be None
-
+ """Create a container trait type from a list, set, or tuple.
+
+ The default value is created by doing ``List(default_value)``,
+ which creates a copy of the ``default_value``.
+
+ ``trait`` can be specified, which restricts the type of elements
+ in the container to that TraitType.
+
+ If only one arg is given and it is not a Trait, it is taken as
+ ``default_value``:
+
+ ``c = List([1, 2, 3])``
+
+ Parameters
+ ----------
+
+ trait : TraitType [ optional ]
+ the type for restricting the contents of the Container. If unspecified,
+ types are not checked.
+
+ default_value : SequenceType [ optional ]
+ The default value for the Trait. Must be list/tuple/set, and
+ will be cast to the container type.
+
+ allow_none : bool [ default False ]
+ Whether to allow the value to be None
+
**kwargs : any
- further keys for extensions to the Trait (e.g. config)
-
- """
- # allow List([values]):
- if default_value is None and not is_trait(trait):
- default_value = trait
- trait = None
-
- if default_value is None:
- args = ()
- elif isinstance(default_value, self._valid_defaults):
- args = (default_value,)
- else:
- raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
-
- if is_trait(trait):
- if isinstance(trait, type):
+ further keys for extensions to the Trait (e.g. config)
+
+ """
+ # allow List([values]):
+ if default_value is None and not is_trait(trait):
+ default_value = trait
+ trait = None
+
+ if default_value is None:
+ args = ()
+ elif isinstance(default_value, self._valid_defaults):
+ args = (default_value,)
+ else:
+ raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
+
+ if is_trait(trait):
+ if isinstance(trait, type):
warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
" Passing types is deprecated in traitlets 4.1.",
- DeprecationWarning, stacklevel=3)
- self._trait = trait() if isinstance(trait, type) else trait
- elif trait is not None:
- raise TypeError("`trait` must be a Trait or None, got %s" % repr_type(trait))
-
+ DeprecationWarning, stacklevel=3)
+ self._trait = trait() if isinstance(trait, type) else trait
+ elif trait is not None:
+ raise TypeError("`trait` must be a Trait or None, got %s" % repr_type(trait))
+
super(Container,self).__init__(klass=self.klass, args=args, **kwargs)
-
- def element_error(self, obj, element, validator):
- e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
- % (self.name, class_of(obj), validator.info(), repr_type(element))
- raise TraitError(e)
-
- def validate(self, obj, value):
- if isinstance(value, self._cast_types):
- value = self.klass(value)
- value = super(Container, self).validate(obj, value)
- if value is None:
- return value
-
- value = self.validate_elements(obj, value)
-
- return value
-
- def validate_elements(self, obj, value):
- validated = []
- if self._trait is None or isinstance(self._trait, Any):
- return value
- for v in value:
- try:
- v = self._trait._validate(obj, v)
- except TraitError:
- self.element_error(obj, v, self._trait)
- else:
- validated.append(v)
- return self.klass(validated)
-
- def class_init(self, cls, name):
- if isinstance(self._trait, TraitType):
- self._trait.class_init(cls, None)
- super(Container, self).class_init(cls, name)
-
- def instance_init(self, obj):
- if isinstance(self._trait, TraitType):
- self._trait.instance_init(obj)
- super(Container, self).instance_init(obj)
-
-
-class List(Container):
- """An instance of a Python list."""
- klass = list
- _cast_types = (tuple,)
-
+
+ def element_error(self, obj, element, validator):
+ e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
+ % (self.name, class_of(obj), validator.info(), repr_type(element))
+ raise TraitError(e)
+
+ def validate(self, obj, value):
+ if isinstance(value, self._cast_types):
+ value = self.klass(value)
+ value = super(Container, self).validate(obj, value)
+ if value is None:
+ return value
+
+ value = self.validate_elements(obj, value)
+
+ return value
+
+ def validate_elements(self, obj, value):
+ validated = []
+ if self._trait is None or isinstance(self._trait, Any):
+ return value
+ for v in value:
+ try:
+ v = self._trait._validate(obj, v)
+ except TraitError:
+ self.element_error(obj, v, self._trait)
+ else:
+ validated.append(v)
+ return self.klass(validated)
+
+ def class_init(self, cls, name):
+ if isinstance(self._trait, TraitType):
+ self._trait.class_init(cls, None)
+ super(Container, self).class_init(cls, name)
+
+ def instance_init(self, obj):
+ if isinstance(self._trait, TraitType):
+ self._trait.instance_init(obj)
+ super(Container, self).instance_init(obj)
+
+
+class List(Container):
+ """An instance of a Python list."""
+ klass = list
+ _cast_types = (tuple,)
+
def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize, **kwargs):
- """Create a List trait type from a list, set, or tuple.
-
- The default value is created by doing ``list(default_value)``,
- which creates a copy of the ``default_value``.
-
- ``trait`` can be specified, which restricts the type of elements
- in the container to that TraitType.
-
- If only one arg is given and it is not a Trait, it is taken as
- ``default_value``:
-
- ``c = List([1, 2, 3])``
-
- Parameters
- ----------
-
- trait : TraitType [ optional ]
- the type for restricting the contents of the Container.
- If unspecified, types are not checked.
-
- default_value : SequenceType [ optional ]
- The default value for the Trait. Must be list/tuple/set, and
- will be cast to the container type.
-
- minlen : Int [ default 0 ]
- The minimum length of the input list
-
- maxlen : Int [ default sys.maxsize ]
- The maximum length of the input list
- """
- self._minlen = minlen
- self._maxlen = maxlen
- super(List, self).__init__(trait=trait, default_value=default_value,
+ """Create a List trait type from a list, set, or tuple.
+
+ The default value is created by doing ``list(default_value)``,
+ which creates a copy of the ``default_value``.
+
+ ``trait`` can be specified, which restricts the type of elements
+ in the container to that TraitType.
+
+ If only one arg is given and it is not a Trait, it is taken as
+ ``default_value``:
+
+ ``c = List([1, 2, 3])``
+
+ Parameters
+ ----------
+
+ trait : TraitType [ optional ]
+ the type for restricting the contents of the Container.
+ If unspecified, types are not checked.
+
+ default_value : SequenceType [ optional ]
+ The default value for the Trait. Must be list/tuple/set, and
+ will be cast to the container type.
+
+ minlen : Int [ default 0 ]
+ The minimum length of the input list
+
+ maxlen : Int [ default sys.maxsize ]
+ The maximum length of the input list
+ """
+ self._minlen = minlen
+ self._maxlen = maxlen
+ super(List, self).__init__(trait=trait, default_value=default_value,
**kwargs)
-
- def length_error(self, obj, value):
- e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \
- % (self.name, class_of(obj), self._minlen, self._maxlen, value)
- raise TraitError(e)
-
- def validate_elements(self, obj, value):
- length = len(value)
- if length < self._minlen or length > self._maxlen:
- self.length_error(obj, value)
-
- return super(List, self).validate_elements(obj, value)
-
- def validate(self, obj, value):
- value = super(List, self).validate(obj, value)
- value = self.validate_elements(obj, value)
- return value
-
-
-class Set(List):
- """An instance of a Python set."""
- klass = set
- _cast_types = (tuple, list)
-
- # Redefine __init__ just to make the docstring more accurate.
- def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize,
+
+ def length_error(self, obj, value):
+ e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \
+ % (self.name, class_of(obj), self._minlen, self._maxlen, value)
+ raise TraitError(e)
+
+ def validate_elements(self, obj, value):
+ length = len(value)
+ if length < self._minlen or length > self._maxlen:
+ self.length_error(obj, value)
+
+ return super(List, self).validate_elements(obj, value)
+
+ def validate(self, obj, value):
+ value = super(List, self).validate(obj, value)
+ value = self.validate_elements(obj, value)
+ return value
+
+
+class Set(List):
+ """An instance of a Python set."""
+ klass = set
+ _cast_types = (tuple, list)
+
+ # Redefine __init__ just to make the docstring more accurate.
+ def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize,
**kwargs):
- """Create a Set trait type from a list, set, or tuple.
-
- The default value is created by doing ``set(default_value)``,
- which creates a copy of the ``default_value``.
-
- ``trait`` can be specified, which restricts the type of elements
- in the container to that TraitType.
-
- If only one arg is given and it is not a Trait, it is taken as
- ``default_value``:
-
- ``c = Set({1, 2, 3})``
-
- Parameters
- ----------
-
- trait : TraitType [ optional ]
- the type for restricting the contents of the Container.
- If unspecified, types are not checked.
-
- default_value : SequenceType [ optional ]
- The default value for the Trait. Must be list/tuple/set, and
- will be cast to the container type.
-
- minlen : Int [ default 0 ]
- The minimum length of the input list
-
- maxlen : Int [ default sys.maxsize ]
- The maximum length of the input list
- """
+ """Create a Set trait type from a list, set, or tuple.
+
+ The default value is created by doing ``set(default_value)``,
+ which creates a copy of the ``default_value``.
+
+ ``trait`` can be specified, which restricts the type of elements
+ in the container to that TraitType.
+
+ If only one arg is given and it is not a Trait, it is taken as
+ ``default_value``:
+
+ ``c = Set({1, 2, 3})``
+
+ Parameters
+ ----------
+
+ trait : TraitType [ optional ]
+ the type for restricting the contents of the Container.
+ If unspecified, types are not checked.
+
+ default_value : SequenceType [ optional ]
+ The default value for the Trait. Must be list/tuple/set, and
+ will be cast to the container type.
+
+ minlen : Int [ default 0 ]
+ The minimum length of the input list
+
+ maxlen : Int [ default sys.maxsize ]
+ The maximum length of the input list
+ """
super(Set, self).__init__(trait, default_value, minlen, maxlen, **kwargs)
-
-
-class Tuple(Container):
- """An instance of a Python tuple."""
- klass = tuple
- _cast_types = (list,)
-
+
+
+class Tuple(Container):
+ """An instance of a Python tuple."""
+ klass = tuple
+ _cast_types = (list,)
+
def __init__(self, *traits, **kwargs):
- """Create a tuple from a list, set, or tuple.
-
- Create a fixed-type tuple with Traits:
-
- ``t = Tuple(Int(), Str(), CStr())``
-
- would be length 3, with Int,Str,CStr for each element.
-
- If only one arg is given and it is not a Trait, it is taken as
- default_value:
-
- ``t = Tuple((1, 2, 3))``
-
- Otherwise, ``default_value`` *must* be specified by keyword.
-
- Parameters
- ----------
-
- `*traits` : TraitTypes [ optional ]
- the types for restricting the contents of the Tuple. If unspecified,
- types are not checked. If specified, then each positional argument
- corresponds to an element of the tuple. Tuples defined with traits
- are of fixed length.
-
- default_value : SequenceType [ optional ]
- The default value for the Tuple. Must be list/tuple/set, and
- will be cast to a tuple. If ``traits`` are specified,
- ``default_value`` must conform to the shape and type they specify.
- """
+ """Create a tuple from a list, set, or tuple.
+
+ Create a fixed-type tuple with Traits:
+
+ ``t = Tuple(Int(), Str(), CStr())``
+
+ would be length 3, with Int,Str,CStr for each element.
+
+ If only one arg is given and it is not a Trait, it is taken as
+ default_value:
+
+ ``t = Tuple((1, 2, 3))``
+
+ Otherwise, ``default_value`` *must* be specified by keyword.
+
+ Parameters
+ ----------
+
+ `*traits` : TraitTypes [ optional ]
+ the types for restricting the contents of the Tuple. If unspecified,
+ types are not checked. If specified, then each positional argument
+ corresponds to an element of the tuple. Tuples defined with traits
+ are of fixed length.
+
+ default_value : SequenceType [ optional ]
+ The default value for the Tuple. Must be list/tuple/set, and
+ will be cast to a tuple. If ``traits`` are specified,
+ ``default_value`` must conform to the shape and type they specify.
+ """
default_value = kwargs.pop('default_value', Undefined)
- # allow Tuple((values,)):
- if len(traits) == 1 and default_value is Undefined and not is_trait(traits[0]):
- default_value = traits[0]
- traits = ()
-
- if default_value is Undefined:
- args = ()
- elif isinstance(default_value, self._valid_defaults):
- args = (default_value,)
- else:
- raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
-
- self._traits = []
- for trait in traits:
- if isinstance(trait, type):
+ # allow Tuple((values,)):
+ if len(traits) == 1 and default_value is Undefined and not is_trait(traits[0]):
+ default_value = traits[0]
+ traits = ()
+
+ if default_value is Undefined:
+ args = ()
+ elif isinstance(default_value, self._valid_defaults):
+ args = (default_value,)
+ else:
+ raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
+
+ self._traits = []
+ for trait in traits:
+ if isinstance(trait, type):
warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
" Passing types is deprecated in traitlets 4.1.",
- DeprecationWarning, stacklevel=2)
- t = trait() if isinstance(trait, type) else trait
- self._traits.append(t)
-
- if self._traits and default_value is None:
- # don't allow default to be an empty container if length is specified
- args = None
+ DeprecationWarning, stacklevel=2)
+ t = trait() if isinstance(trait, type) else trait
+ self._traits.append(t)
+
+ if self._traits and default_value is None:
+ # don't allow default to be an empty container if length is specified
+ args = None
super(Container,self).__init__(klass=self.klass, args=args, **kwargs)
-
- def validate_elements(self, obj, value):
- if not self._traits:
- # nothing to validate
- return value
- if len(value) != len(self._traits):
- e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \
- % (self.name, class_of(obj), len(self._traits), repr_type(value))
- raise TraitError(e)
-
- validated = []
- for t, v in zip(self._traits, value):
- try:
- v = t._validate(obj, v)
- except TraitError:
- self.element_error(obj, v, t)
- else:
- validated.append(v)
- return tuple(validated)
-
- def class_init(self, cls, name):
- for trait in self._traits:
- if isinstance(trait, TraitType):
- trait.class_init(cls, None)
- super(Container, self).class_init(cls, name)
-
- def instance_init(self, obj):
- for trait in self._traits:
- if isinstance(trait, TraitType):
- trait.instance_init(obj)
- super(Container, self).instance_init(obj)
-
-
-class Dict(Instance):
- """An instance of a Python dict."""
- _trait = None
-
- def __init__(self, trait=None, traits=None, default_value=Undefined,
+
+ def validate_elements(self, obj, value):
+ if not self._traits:
+ # nothing to validate
+ return value
+ if len(value) != len(self._traits):
+ e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \
+ % (self.name, class_of(obj), len(self._traits), repr_type(value))
+ raise TraitError(e)
+
+ validated = []
+ for t, v in zip(self._traits, value):
+ try:
+ v = t._validate(obj, v)
+ except TraitError:
+ self.element_error(obj, v, t)
+ else:
+ validated.append(v)
+ return tuple(validated)
+
+ def class_init(self, cls, name):
+ for trait in self._traits:
+ if isinstance(trait, TraitType):
+ trait.class_init(cls, None)
+ super(Container, self).class_init(cls, name)
+
+ def instance_init(self, obj):
+ for trait in self._traits:
+ if isinstance(trait, TraitType):
+ trait.instance_init(obj)
+ super(Container, self).instance_init(obj)
+
+
+class Dict(Instance):
+ """An instance of a Python dict."""
+ _trait = None
+
+ def __init__(self, trait=None, traits=None, default_value=Undefined,
**kwargs):
"""Create a dict trait type from a Python dict.
-
- The default value is created by doing ``dict(default_value)``,
- which creates a copy of the ``default_value``.
-
+
+ The default value is created by doing ``dict(default_value)``,
+ which creates a copy of the ``default_value``.
+
Parameters
----------
- trait : TraitType [ optional ]
+ trait : TraitType [ optional ]
The specified trait type to check and use to restrict contents of
the Container. If unspecified, trait types are not checked.
-
+
traits : Dictionary of trait types [ optional ]
A Python dictionary containing the types that are valid for
restricting the content of the Dict Container for certain keys.
-
- default_value : SequenceType [ optional ]
- The default value for the Dict. Must be dict, tuple, or None, and
- will be cast to a dict if not None. If `trait` is specified, the
- `default_value` must conform to the constraints it specifies.
- """
- # Handling positional arguments
- if default_value is Undefined and trait is not None:
- if not is_trait(trait):
- default_value = trait
- trait = None
-
- # Handling default value
- if default_value is Undefined:
- default_value = {}
- if default_value is None:
- args = None
- elif isinstance(default_value, dict):
- args = (default_value,)
- elif isinstance(default_value, SequenceTypes):
- args = (default_value,)
- else:
- raise TypeError('default value of Dict was %s' % default_value)
-
- # Case where a type of TraitType is provided rather than an instance
- if is_trait(trait):
- if isinstance(trait, type):
+
+ default_value : SequenceType [ optional ]
+ The default value for the Dict. Must be dict, tuple, or None, and
+ will be cast to a dict if not None. If `trait` is specified, the
+ `default_value` must conform to the constraints it specifies.
+ """
+ # Handling positional arguments
+ if default_value is Undefined and trait is not None:
+ if not is_trait(trait):
+ default_value = trait
+ trait = None
+
+ # Handling default value
+ if default_value is Undefined:
+ default_value = {}
+ if default_value is None:
+ args = None
+ elif isinstance(default_value, dict):
+ args = (default_value,)
+ elif isinstance(default_value, SequenceTypes):
+ args = (default_value,)
+ else:
+ raise TypeError('default value of Dict was %s' % default_value)
+
+ # Case where a type of TraitType is provided rather than an instance
+ if is_trait(trait):
+ if isinstance(trait, type):
warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
" Passing types is deprecated in traitlets 4.1.",
- DeprecationWarning, stacklevel=2)
- self._trait = trait() if isinstance(trait, type) else trait
- elif trait is not None:
- raise TypeError("`trait` must be a Trait or None, got %s" % repr_type(trait))
-
- self._traits = traits
-
+ DeprecationWarning, stacklevel=2)
+ self._trait = trait() if isinstance(trait, type) else trait
+ elif trait is not None:
+ raise TypeError("`trait` must be a Trait or None, got %s" % repr_type(trait))
+
+ self._traits = traits
+
super(Dict, self).__init__(klass=dict, args=args, **kwargs)
-
- def element_error(self, obj, element, validator):
- e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
- % (self.name, class_of(obj), validator.info(), repr_type(element))
- raise TraitError(e)
-
- def validate(self, obj, value):
- value = super(Dict, self).validate(obj, value)
- if value is None:
- return value
- value = self.validate_elements(obj, value)
- return value
-
- def validate_elements(self, obj, value):
+
+ def element_error(self, obj, element, validator):
+ e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
+ % (self.name, class_of(obj), validator.info(), repr_type(element))
+ raise TraitError(e)
+
+ def validate(self, obj, value):
+ value = super(Dict, self).validate(obj, value)
+ if value is None:
+ return value
+ value = self.validate_elements(obj, value)
+ return value
+
+ def validate_elements(self, obj, value):
use_dict = bool(self._traits)
default_to = (self._trait or Any())
if not use_dict and isinstance(default_to, Any):
- return value
+ return value
- validated = {}
- for key in value:
+ validated = {}
+ for key in value:
if use_dict and key in self._traits:
validate_with = self._traits[key]
else:
validate_with = default_to
- try:
+ try:
v = value[key]
if not isinstance(validate_with, Any):
v = validate_with._validate(obj, v)
- except TraitError:
+ except TraitError:
self.element_error(obj, v, validate_with)
- else:
- validated[key] = v
-
- return self.klass(validated)
-
- def class_init(self, cls, name):
- if isinstance(self._trait, TraitType):
- self._trait.class_init(cls, None)
- if self._traits is not None:
- for trait in self._traits.values():
- trait.class_init(cls, None)
- super(Dict, self).class_init(cls, name)
-
- def instance_init(self, obj):
- if isinstance(self._trait, TraitType):
- self._trait.instance_init(obj)
- if self._traits is not None:
- for trait in self._traits.values():
- trait.instance_init(obj)
- super(Dict, self).instance_init(obj)
-
-
-class TCPAddress(TraitType):
- """A trait for an (ip, port) tuple.
-
- This allows for both IPv4 IP addresses as well as hostnames.
- """
-
- default_value = ('127.0.0.1', 0)
- info_text = 'an (ip, port) tuple'
-
- def validate(self, obj, value):
- if isinstance(value, tuple):
- if len(value) == 2:
+ else:
+ validated[key] = v
+
+ return self.klass(validated)
+
+ def class_init(self, cls, name):
+ if isinstance(self._trait, TraitType):
+ self._trait.class_init(cls, None)
+ if self._traits is not None:
+ for trait in self._traits.values():
+ trait.class_init(cls, None)
+ super(Dict, self).class_init(cls, name)
+
+ def instance_init(self, obj):
+ if isinstance(self._trait, TraitType):
+ self._trait.instance_init(obj)
+ if self._traits is not None:
+ for trait in self._traits.values():
+ trait.instance_init(obj)
+ super(Dict, self).instance_init(obj)
+
+
+class TCPAddress(TraitType):
+ """A trait for an (ip, port) tuple.
+
+ This allows for both IPv4 IP addresses as well as hostnames.
+ """
+
+ default_value = ('127.0.0.1', 0)
+ info_text = 'an (ip, port) tuple'
+
+ def validate(self, obj, value):
+ if isinstance(value, tuple):
+ if len(value) == 2:
if isinstance(value[0], six.string_types) and isinstance(value[1], int):
- port = value[1]
- if port >= 0 and port <= 65535:
- return value
- self.error(obj, value)
-
-class CRegExp(TraitType):
- """A casting compiled regular expression trait.
-
- Accepts both strings and compiled regular expressions. The resulting
- attribute will be a compiled regular expression."""
-
- info_text = 'a regular expression'
-
- def validate(self, obj, value):
- try:
- return re.compile(value)
- except:
- self.error(obj, value)
+ port = value[1]
+ if port >= 0 and port <= 65535:
+ return value
+ self.error(obj, value)
+
+class CRegExp(TraitType):
+ """A casting compiled regular expression trait.
+
+ Accepts both strings and compiled regular expressions. The resulting
+ attribute will be a compiled regular expression."""
+
+ info_text = 'a regular expression'
+
+ def validate(self, obj, value):
+ try:
+ return re.compile(value)
+ except:
+ self.error(obj, value)
class UseEnum(TraitType):
diff --git a/contrib/python/traitlets/py2/traitlets/utils/getargspec.py b/contrib/python/traitlets/py2/traitlets/utils/getargspec.py
index 5c79b29549..0a047379fe 100644
--- a/contrib/python/traitlets/py2/traitlets/utils/getargspec.py
+++ b/contrib/python/traitlets/py2/traitlets/utils/getargspec.py
@@ -1,86 +1,86 @@
-# -*- coding: utf-8 -*-
-"""
- getargspec excerpted from:
-
- sphinx.util.inspect
- ~~~~~~~~~~~~~~~~~~~
- Helpers for inspecting Python modules.
- :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import inspect
+# -*- coding: utf-8 -*-
+"""
+ getargspec excerpted from:
+
+ sphinx.util.inspect
+ ~~~~~~~~~~~~~~~~~~~
+ Helpers for inspecting Python modules.
+ :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import inspect
from six import PY3
-
-# Unmodified from sphinx below this line
-
-if PY3:
- from functools import partial
-
- def getargspec(func):
- """Like inspect.getargspec but supports functools.partial as well."""
- if inspect.ismethod(func):
- func = func.__func__
- if type(func) is partial:
- orig_func = func.func
- argspec = getargspec(orig_func)
- args = list(argspec[0])
- defaults = list(argspec[3] or ())
- kwoargs = list(argspec[4])
- kwodefs = dict(argspec[5] or {})
- if func.args:
- args = args[len(func.args):]
- for arg in func.keywords or ():
- try:
- i = args.index(arg) - len(args)
- del args[i]
- try:
- del defaults[i]
- except IndexError:
- pass
- except ValueError: # must be a kwonly arg
- i = kwoargs.index(arg)
- del kwoargs[i]
- del kwodefs[arg]
- return inspect.FullArgSpec(args, argspec[1], argspec[2],
- tuple(defaults), kwoargs,
- kwodefs, argspec[6])
- while hasattr(func, '__wrapped__'):
- func = func.__wrapped__
- if not inspect.isfunction(func):
- raise TypeError('%r is not a Python function' % func)
- return inspect.getfullargspec(func)
-
-else: # 2.6, 2.7
- from functools import partial
-
- def getargspec(func):
- """Like inspect.getargspec but supports functools.partial as well."""
- if inspect.ismethod(func):
- func = func.__func__
- parts = 0, ()
- if type(func) is partial:
- keywords = func.keywords
- if keywords is None:
- keywords = {}
- parts = len(func.args), keywords.keys()
- func = func.func
- if not inspect.isfunction(func):
- raise TypeError('%r is not a Python function' % func)
- args, varargs, varkw = inspect.getargs(func.__code__)
- func_defaults = func.__defaults__
- if func_defaults is None:
- func_defaults = []
- else:
- func_defaults = list(func_defaults)
- if parts[0]:
- args = args[parts[0]:]
- if parts[1]:
- for arg in parts[1]:
- i = args.index(arg) - len(args)
- del args[i]
- try:
- del func_defaults[i]
- except IndexError:
- pass
- return inspect.ArgSpec(args, varargs, varkw, func_defaults)
+
+# Unmodified from sphinx below this line
+
+if PY3:
+ from functools import partial
+
+ def getargspec(func):
+ """Like inspect.getargspec but supports functools.partial as well."""
+ if inspect.ismethod(func):
+ func = func.__func__
+ if type(func) is partial:
+ orig_func = func.func
+ argspec = getargspec(orig_func)
+ args = list(argspec[0])
+ defaults = list(argspec[3] or ())
+ kwoargs = list(argspec[4])
+ kwodefs = dict(argspec[5] or {})
+ if func.args:
+ args = args[len(func.args):]
+ for arg in func.keywords or ():
+ try:
+ i = args.index(arg) - len(args)
+ del args[i]
+ try:
+ del defaults[i]
+ except IndexError:
+ pass
+ except ValueError: # must be a kwonly arg
+ i = kwoargs.index(arg)
+ del kwoargs[i]
+ del kwodefs[arg]
+ return inspect.FullArgSpec(args, argspec[1], argspec[2],
+ tuple(defaults), kwoargs,
+ kwodefs, argspec[6])
+ while hasattr(func, '__wrapped__'):
+ func = func.__wrapped__
+ if not inspect.isfunction(func):
+ raise TypeError('%r is not a Python function' % func)
+ return inspect.getfullargspec(func)
+
+else: # 2.6, 2.7
+ from functools import partial
+
+ def getargspec(func):
+ """Like inspect.getargspec but supports functools.partial as well."""
+ if inspect.ismethod(func):
+ func = func.__func__
+ parts = 0, ()
+ if type(func) is partial:
+ keywords = func.keywords
+ if keywords is None:
+ keywords = {}
+ parts = len(func.args), keywords.keys()
+ func = func.func
+ if not inspect.isfunction(func):
+ raise TypeError('%r is not a Python function' % func)
+ args, varargs, varkw = inspect.getargs(func.__code__)
+ func_defaults = func.__defaults__
+ if func_defaults is None:
+ func_defaults = []
+ else:
+ func_defaults = list(func_defaults)
+ if parts[0]:
+ args = args[parts[0]:]
+ if parts[1]:
+ for arg in parts[1]:
+ i = args.index(arg) - len(args)
+ del args[i]
+ try:
+ del func_defaults[i]
+ except IndexError:
+ pass
+ return inspect.ArgSpec(args, varargs, varkw, func_defaults)
diff --git a/contrib/python/traitlets/py2/traitlets/utils/importstring.py b/contrib/python/traitlets/py2/traitlets/utils/importstring.py
index 873ab9635c..5b4f643f41 100644
--- a/contrib/python/traitlets/py2/traitlets/utils/importstring.py
+++ b/contrib/python/traitlets/py2/traitlets/utils/importstring.py
@@ -1,42 +1,42 @@
-# encoding: utf-8
-"""
-A simple utility to import something by its string name.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
+# encoding: utf-8
+"""
+A simple utility to import something by its string name.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
from ipython_genutils.py3compat import cast_bytes_py2
from six import string_types
-
-def import_item(name):
- """Import and return ``bar`` given the string ``foo.bar``.
-
- Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
- executing the code ``from foo import bar``.
-
- Parameters
- ----------
- name : string
- The fully qualified name of the module/package being imported.
-
- Returns
- -------
- mod : module object
- The module that was imported.
- """
- if not isinstance(name, string_types):
- raise TypeError("import_item accepts strings, not '%s'." % type(name))
- name = cast_bytes_py2(name)
- parts = name.rsplit('.', 1)
- if len(parts) == 2:
- # called with 'foo.bar....'
- package, obj = parts
- module = __import__(package, fromlist=[obj])
- try:
- pak = getattr(module, obj)
- except AttributeError:
- raise ImportError('No module named %s' % obj)
- return pak
- else:
- # called with un-dotted string
- return __import__(parts[0])
+
+def import_item(name):
+ """Import and return ``bar`` given the string ``foo.bar``.
+
+ Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
+ executing the code ``from foo import bar``.
+
+ Parameters
+ ----------
+ name : string
+ The fully qualified name of the module/package being imported.
+
+ Returns
+ -------
+ mod : module object
+ The module that was imported.
+ """
+ if not isinstance(name, string_types):
+ raise TypeError("import_item accepts strings, not '%s'." % type(name))
+ name = cast_bytes_py2(name)
+ parts = name.rsplit('.', 1)
+ if len(parts) == 2:
+ # called with 'foo.bar....'
+ package, obj = parts
+ module = __import__(package, fromlist=[obj])
+ try:
+ pak = getattr(module, obj)
+ except AttributeError:
+ raise ImportError('No module named %s' % obj)
+ return pak
+ else:
+ # called with un-dotted string
+ return __import__(parts[0])
diff --git a/contrib/python/traitlets/py2/traitlets/utils/sentinel.py b/contrib/python/traitlets/py2/traitlets/utils/sentinel.py
index 7af2558c1a..dc57a2591c 100644
--- a/contrib/python/traitlets/py2/traitlets/utils/sentinel.py
+++ b/contrib/python/traitlets/py2/traitlets/utils/sentinel.py
@@ -1,17 +1,17 @@
-"""Sentinel class for constants with useful reprs"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-class Sentinel(object):
-
- def __init__(self, name, module, docstring=None):
- self.name = name
- self.module = module
- if docstring:
- self.__doc__ = docstring
-
-
- def __repr__(self):
- return str(self.module)+'.'+self.name
-
+"""Sentinel class for constants with useful reprs"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+class Sentinel(object):
+
+ def __init__(self, name, module, docstring=None):
+ self.name = name
+ self.module = module
+ if docstring:
+ self.__doc__ = docstring
+
+
+ def __repr__(self):
+ return str(self.module)+'.'+self.name
+
diff --git a/contrib/python/traitlets/py2/ya.make b/contrib/python/traitlets/py2/ya.make
index ae62d588b4..4a60107101 100644
--- a/contrib/python/traitlets/py2/ya.make
+++ b/contrib/python/traitlets/py2/ya.make
@@ -1,49 +1,49 @@
# Generated by devtools/yamaker (pypi).
PY2_LIBRARY()
-
+
PROVIDES(python_traitlets)
OWNER(borman nslus g:python-contrib)
VERSION(4.3.3)
-
+
LICENSE(BSD-3-Clause)
-PEERDIR(
+PEERDIR(
contrib/python/decorator
contrib/python/enum34
contrib/python/ipython-genutils
contrib/python/six
-)
-
+)
+
NO_LINT()
-PY_SRCS(
- TOP_LEVEL
- traitlets/__init__.py
- traitlets/_version.py
- traitlets/config/__init__.py
- traitlets/config/application.py
- traitlets/config/configurable.py
- traitlets/config/loader.py
- traitlets/config/manager.py
- traitlets/log.py
- traitlets/traitlets.py
- traitlets/utils/__init__.py
+PY_SRCS(
+ TOP_LEVEL
+ traitlets/__init__.py
+ traitlets/_version.py
+ traitlets/config/__init__.py
+ traitlets/config/application.py
+ traitlets/config/configurable.py
+ traitlets/config/loader.py
+ traitlets/config/manager.py
+ traitlets/log.py
+ traitlets/traitlets.py
+ traitlets/utils/__init__.py
traitlets/utils/bunch.py
- traitlets/utils/getargspec.py
- traitlets/utils/importstring.py
- traitlets/utils/sentinel.py
-)
-
+ traitlets/utils/getargspec.py
+ traitlets/utils/importstring.py
+ traitlets/utils/sentinel.py
+)
+
RESOURCE_FILES(
PREFIX contrib/python/traitlets/py2/
.dist-info/METADATA
.dist-info/top_level.txt
)
-END()
+END()
RECURSE_FOR_TESTS(
tests
diff --git a/contrib/python/traitlets/py3/COPYING.md b/contrib/python/traitlets/py3/COPYING.md
index e314a9d376..39ca730a63 100644
--- a/contrib/python/traitlets/py3/COPYING.md
+++ b/contrib/python/traitlets/py3/COPYING.md
@@ -1,62 +1,62 @@
-# Licensing terms
-
-Traitlets is adapted from enthought.traits, Copyright (c) Enthought, Inc.,
-under the terms of the Modified BSD License.
-
-This project is licensed under the terms of the Modified BSD License
-(also known as New or Revised or 3-Clause BSD), as follows:
-
-- Copyright (c) 2001-, IPython Development Team
-
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-Redistributions of source code must retain the above copyright notice, this
-list of conditions and the following disclaimer.
-
-Redistributions in binary form must reproduce the above copyright notice, this
-list of conditions and the following disclaimer in the documentation and/or
-other materials provided with the distribution.
-
-Neither the name of the IPython Development Team nor the names of its
-contributors may be used to endorse or promote products derived from this
-software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-## About the IPython Development Team
-
-The IPython Development Team is the set of all contributors to the IPython project.
-This includes all of the IPython subprojects.
-
-The core team that coordinates development on GitHub can be found here:
-https://github.com/jupyter/.
-
-## Our Copyright Policy
-
-IPython uses a shared copyright model. Each contributor maintains copyright
-over their contributions to IPython. But, it is important to note that these
-contributions are typically only changes to the repositories. Thus, the IPython
-source code, in its entirety is not the copyright of any single person or
-institution. Instead, it is the collective copyright of the entire IPython
-Development Team. If individual contributors want to maintain a record of what
-changes/contributions they have specific copyright on, they should indicate
-their copyright in the commit message of the change, when they commit the
-change to one of the IPython repositories.
-
-With this in mind, the following banner should be used in any source code file
-to indicate the copyright and license terms:
-
- # Copyright (c) IPython Development Team.
- # Distributed under the terms of the Modified BSD License.
+# Licensing terms
+
+Traitlets is adapted from enthought.traits, Copyright (c) Enthought, Inc.,
+under the terms of the Modified BSD License.
+
+This project is licensed under the terms of the Modified BSD License
+(also known as New or Revised or 3-Clause BSD), as follows:
+
+- Copyright (c) 2001-, IPython Development Team
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+
+Redistributions in binary form must reproduce the above copyright notice, this
+list of conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution.
+
+Neither the name of the IPython Development Team nor the names of its
+contributors may be used to endorse or promote products derived from this
+software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+## About the IPython Development Team
+
+The IPython Development Team is the set of all contributors to the IPython project.
+This includes all of the IPython subprojects.
+
+The core team that coordinates development on GitHub can be found here:
+https://github.com/jupyter/.
+
+## Our Copyright Policy
+
+IPython uses a shared copyright model. Each contributor maintains copyright
+over their contributions to IPython. But, it is important to note that these
+contributions are typically only changes to the repositories. Thus, the IPython
+source code, in its entirety is not the copyright of any single person or
+institution. Instead, it is the collective copyright of the entire IPython
+Development Team. If individual contributors want to maintain a record of what
+changes/contributions they have specific copyright on, they should indicate
+their copyright in the commit message of the change, when they commit the
+change to one of the IPython repositories.
+
+With this in mind, the following banner should be used in any source code file
+to indicate the copyright and license terms:
+
+ # Copyright (c) IPython Development Team.
+ # Distributed under the terms of the Modified BSD License.
diff --git a/contrib/python/traitlets/py3/traitlets/__init__.py b/contrib/python/traitlets/py3/traitlets/__init__.py
index 1b8675a879..ad5ba73c86 100644
--- a/contrib/python/traitlets/py3/traitlets/__init__.py
+++ b/contrib/python/traitlets/py3/traitlets/__init__.py
@@ -1,11 +1,11 @@
from warnings import warn
from . import traitlets
-from .traitlets import *
-from .utils.importstring import import_item
+from .traitlets import *
+from .utils.importstring import import_item
from .utils.decorators import signature_has_traits
from .utils.bunch import Bunch
-from ._version import version_info, __version__
+from ._version import version_info, __version__
class Sentinel(traitlets.Sentinel):
diff --git a/contrib/python/traitlets/py3/traitlets/config/__init__.py b/contrib/python/traitlets/py3/traitlets/config/__init__.py
index 1531ee5930..0ae7d63171 100644
--- a/contrib/python/traitlets/py3/traitlets/config/__init__.py
+++ b/contrib/python/traitlets/py3/traitlets/config/__init__.py
@@ -1,8 +1,8 @@
-# encoding: utf-8
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from .application import *
-from .configurable import *
-from .loader import Config
+# encoding: utf-8
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from .application import *
+from .configurable import *
+from .loader import Config
diff --git a/contrib/python/traitlets/py3/traitlets/config/application.py b/contrib/python/traitlets/py3/traitlets/config/application.py
index 6cdb801008..99a6ef7ee0 100644
--- a/contrib/python/traitlets/py3/traitlets/config/application.py
+++ b/contrib/python/traitlets/py3/traitlets/config/application.py
@@ -1,68 +1,68 @@
-"""A base class for a configurable application."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-
+"""A base class for a configurable application."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+
from collections import defaultdict, OrderedDict
from copy import deepcopy
import functools
-import json
-import logging
-import os
+import json
+import logging
+import os
import pprint
-import re
-import sys
+import re
+import sys
import warnings
-
-from traitlets.config.configurable import Configurable, SingletonConfigurable
-from traitlets.config.loader import (
- KVArgParseConfigLoader, PyFileConfigLoader, Config, ArgumentError, ConfigFileNotFound, JSONFileConfigLoader
-)
-from traitlets.traitlets import (
+
+from traitlets.config.configurable import Configurable, SingletonConfigurable
+from traitlets.config.loader import (
+ KVArgParseConfigLoader, PyFileConfigLoader, Config, ArgumentError, ConfigFileNotFound, JSONFileConfigLoader
+)
+from traitlets.traitlets import (
Bool, Unicode, List, Enum, Dict, Instance, TraitError, observe, observe_compat, default,
-)
+)
from ..utils.importstring import import_item
from ..utils import cast_unicode
from traitlets.utils.text import indent, wrap_paragraphs
from textwrap import dedent
-
-#-----------------------------------------------------------------------------
-# Descriptions for the various sections
-#-----------------------------------------------------------------------------
-# merge flags&aliases into options
-option_description = """
+
+#-----------------------------------------------------------------------------
+# Descriptions for the various sections
+#-----------------------------------------------------------------------------
+# merge flags&aliases into options
+option_description = """
The options below are convenience aliases to configurable class-options,
as listed in the "Equivalent to" description-line of the aliases.
To see all configurable class-options for some <cmd>, use:
<cmd> --help-all
""".strip() # trim newlines of front and back
-
-keyvalue_description = """
+
+keyvalue_description = """
The command-line option below sets the respective configurable class-parameter:
--Class.parameter=value
This line is evaluated in Python, so simple expressions are allowed.
For instance, to set `C.a=[0,1,2]`, you may type this:
--C.a='range(3)'
-""".strip() # trim newlines of front and back
-
-# sys.argv can be missing, for example when python is embedded. See the docs
-# for details: http://docs.python.org/2/c-api/intro.html#embedding-python
-if not hasattr(sys, "argv"):
- sys.argv = [""]
-
-subcommand_description = """
-Subcommands are launched as `{app} cmd [args]`. For information on using
-subcommand 'cmd', do: `{app} cmd -h`.
-"""
-# get running program name
-
-#-----------------------------------------------------------------------------
-# Application class
-#-----------------------------------------------------------------------------
-
+""".strip() # trim newlines of front and back
+
+# sys.argv can be missing, for example when python is embedded. See the docs
+# for details: http://docs.python.org/2/c-api/intro.html#embedding-python
+if not hasattr(sys, "argv"):
+ sys.argv = [""]
+
+subcommand_description = """
+Subcommands are launched as `{app} cmd [args]`. For information on using
+subcommand 'cmd', do: `{app} cmd -h`.
+"""
+# get running program name
+
+#-----------------------------------------------------------------------------
+# Application class
+#-----------------------------------------------------------------------------
+
_envvar = os.environ.get('TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR','')
@@ -75,13 +75,13 @@ else:
def catch_config_error(method):
- """Method decorator for catching invalid config (Trait/ArgumentErrors) during init.
-
- On a TraitError (generally caused by bad config), this will print the trait's
- message, and exit the app.
+ """Method decorator for catching invalid config (Trait/ArgumentErrors) during init.
+
+ On a TraitError (generally caused by bad config), this will print the trait's
+ message, and exit the app.
- For use on init methods, to prevent invoking excepthook on invalid input.
- """
+ For use on init methods, to prevent invoking excepthook on invalid input.
+ """
@functools.wraps(method)
def inner(app, *args, **kwargs):
try:
@@ -90,116 +90,116 @@ def catch_config_error(method):
app.log.fatal("Bad config encountered during initialization: %s", e)
app.log.debug("Config at the time: %s", app.config)
app.exit(1)
-
+
return inner
-
-class ApplicationError(Exception):
- pass
-
-
-class LevelFormatter(logging.Formatter):
- """Formatter with additional `highlevel` record
-
- This field is empty if log level is less than highlevel_limit,
- otherwise it is formatted with self.highlevel_format.
-
- Useful for adding 'WARNING' to warning messages,
- without adding 'INFO' to info, etc.
- """
- highlevel_limit = logging.WARN
- highlevel_format = " %(levelname)s |"
-
- def format(self, record):
- if record.levelno >= self.highlevel_limit:
- record.highlevel = self.highlevel_format % record.__dict__
- else:
- record.highlevel = ""
- return super(LevelFormatter, self).format(record)
-
-
-class Application(SingletonConfigurable):
- """A singleton application with full configuration support."""
-
- # The name of the application, will usually match the name of the command
- # line application
+
+class ApplicationError(Exception):
+ pass
+
+
+class LevelFormatter(logging.Formatter):
+ """Formatter with additional `highlevel` record
+
+ This field is empty if log level is less than highlevel_limit,
+ otherwise it is formatted with self.highlevel_format.
+
+ Useful for adding 'WARNING' to warning messages,
+ without adding 'INFO' to info, etc.
+ """
+ highlevel_limit = logging.WARN
+ highlevel_format = " %(levelname)s |"
+
+ def format(self, record):
+ if record.levelno >= self.highlevel_limit:
+ record.highlevel = self.highlevel_format % record.__dict__
+ else:
+ record.highlevel = ""
+ return super(LevelFormatter, self).format(record)
+
+
+class Application(SingletonConfigurable):
+ """A singleton application with full configuration support."""
+
+ # The name of the application, will usually match the name of the command
+ # line application
name = Unicode('application')
-
- # The description of the application that is printed at the beginning
- # of the help.
+
+ # The description of the application that is printed at the beginning
+ # of the help.
description = Unicode('This is an application.')
- # default section descriptions
- option_description = Unicode(option_description)
- keyvalue_description = Unicode(keyvalue_description)
- subcommand_description = Unicode(subcommand_description)
-
- python_config_loader_class = PyFileConfigLoader
- json_config_loader_class = JSONFileConfigLoader
-
- # The usage and example string that goes at the end of the help string.
- examples = Unicode()
-
- # A sequence of Configurable subclasses whose config=True attributes will
- # be exposed at the command line.
- classes = []
-
+ # default section descriptions
+ option_description = Unicode(option_description)
+ keyvalue_description = Unicode(keyvalue_description)
+ subcommand_description = Unicode(subcommand_description)
+
+ python_config_loader_class = PyFileConfigLoader
+ json_config_loader_class = JSONFileConfigLoader
+
+ # The usage and example string that goes at the end of the help string.
+ examples = Unicode()
+
+ # A sequence of Configurable subclasses whose config=True attributes will
+ # be exposed at the command line.
+ classes = []
+
def _classes_inc_parents(self, classes=None):
- """Iterate through configurable classes, including configurable parents
-
+ """Iterate through configurable classes, including configurable parents
+
:param classes:
The list of classes to iterate; if not set, uses :attr:`classes`.
- Children should always be after parents, and each class should only be
- yielded once.
- """
+ Children should always be after parents, and each class should only be
+ yielded once.
+ """
if classes is None:
classes = self.classes
- seen = set()
+ seen = set()
for c in classes:
- # We want to sort parents before children, so we reverse the MRO
- for parent in reversed(c.mro()):
- if issubclass(parent, Configurable) and (parent not in seen):
- seen.add(parent)
- yield parent
-
- # The version string of this application.
+ # We want to sort parents before children, so we reverse the MRO
+ for parent in reversed(c.mro()):
+ if issubclass(parent, Configurable) and (parent not in seen):
+ seen.add(parent)
+ yield parent
+
+ # The version string of this application.
version = Unicode('0.0')
- # the argv used to initialize the application
- argv = List()
-
+ # the argv used to initialize the application
+ argv = List()
+
# Whether failing to load config files should prevent startup
raise_config_file_errors = Bool(TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR)
- # The log level for the application
- log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'),
- default_value=logging.WARN,
- help="Set the log level by value or name.").tag(config=True)
-
- @observe('log_level')
- @observe_compat
- def _log_level_changed(self, change):
- """Adjust the log level when log_level is set."""
+ # The log level for the application
+ log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'),
+ default_value=logging.WARN,
+ help="Set the log level by value or name.").tag(config=True)
+
+ @observe('log_level')
+ @observe_compat
+ def _log_level_changed(self, change):
+ """Adjust the log level when log_level is set."""
new = change.new
if isinstance(new, str):
- new = getattr(logging, new)
- self.log_level = new
- self.log.setLevel(new)
+ new = getattr(logging, new)
+ self.log_level = new
+ self.log.setLevel(new)
- _log_formatter_cls = LevelFormatter
+ _log_formatter_cls = LevelFormatter
log_datefmt = Unicode("%Y-%m-%d %H:%M:%S",
- help="The date format used by logging formatters for %(asctime)s"
- ).tag(config=True)
-
- log_format = Unicode("[%(name)s]%(highlevel)s %(message)s",
- help="The Logging format template",
- ).tag(config=True)
-
- @observe('log_datefmt', 'log_format')
- @observe_compat
- def _log_format_changed(self, change):
- """Change the log formatter when log_format is set."""
+ help="The date format used by logging formatters for %(asctime)s"
+ ).tag(config=True)
+
+ log_format = Unicode("[%(name)s]%(highlevel)s %(message)s",
+ help="The Logging format template",
+ ).tag(config=True)
+
+ @observe('log_datefmt', 'log_format')
+ @observe_compat
+ def _log_format_changed(self, change):
+ """Change the log formatter when log_format is set."""
_log_handler = self._get_log_handler()
if not _log_handler:
warnings.warn(
@@ -207,48 +207,48 @@ class Application(SingletonConfigurable):
RuntimeWarning,
)
return
- _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
- _log_handler.setFormatter(_log_formatter)
-
- @default('log')
- def _log_default(self):
- """Start logging for this application.
-
- The default is to log to stderr using a StreamHandler, if no default
- handler already exists. The log level starts at logging.WARN, but this
- can be adjusted by setting the ``log_level`` attribute.
- """
- log = logging.getLogger(self.__class__.__name__)
- log.setLevel(self.log_level)
- log.propagate = False
- _log = log # copied from Logger.hasHandlers() (new in Python 3.2)
- while _log:
- if _log.handlers:
- return log
- if not _log.propagate:
- break
- else:
- _log = _log.parent
+ _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
+ _log_handler.setFormatter(_log_formatter)
+
+ @default('log')
+ def _log_default(self):
+ """Start logging for this application.
+
+ The default is to log to stderr using a StreamHandler, if no default
+ handler already exists. The log level starts at logging.WARN, but this
+ can be adjusted by setting the ``log_level`` attribute.
+ """
+ log = logging.getLogger(self.__class__.__name__)
+ log.setLevel(self.log_level)
+ log.propagate = False
+ _log = log # copied from Logger.hasHandlers() (new in Python 3.2)
+ while _log:
+ if _log.handlers:
+ return log
+ if not _log.propagate:
+ break
+ else:
+ _log = _log.parent
if sys.executable and sys.executable.endswith('pythonw.exe'):
- # this should really go to a file, but file-logging is only
- # hooked up in parallel applications
- _log_handler = logging.StreamHandler(open(os.devnull, 'w'))
- else:
- _log_handler = logging.StreamHandler()
- _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
- _log_handler.setFormatter(_log_formatter)
- log.addHandler(_log_handler)
- return log
-
+ # this should really go to a file, but file-logging is only
+ # hooked up in parallel applications
+ _log_handler = logging.StreamHandler(open(os.devnull, 'w'))
+ else:
+ _log_handler = logging.StreamHandler()
+ _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
+ _log_handler.setFormatter(_log_formatter)
+ log.addHandler(_log_handler)
+ return log
+
#: the alias map for configurables
#: Keys might strings or tuples for additional options; single-letter alias accessed like `-v`.
#: Values might be like "Class.trait" strings of two-tuples: (Class.trait, help-text).
aliases = {'log-level' : 'Application.log_level'}
-
- # flags for loading Configurables or store_const style flags
- # flags are loaded from this dict by '--key' flags
- # this must be a dict of two-tuples, the first element being the Config/dict
- # and the second being the help string for the flag
+
+ # flags for loading Configurables or store_const style flags
+ # flags are loaded from this dict by '--key' flags
+ # this must be a dict of two-tuples, the first element being the Config/dict
+ # and the second being the help string for the flag
flags = {
'debug': ({
'Application': {
@@ -266,22 +266,22 @@ class Application(SingletonConfigurable):
},
}, "Show the application's configuration (json format)"),
}
-
- # subcommands for launching other applications
- # if this is not empty, this will be a parent Application
- # this must be a dict of two-tuples,
- # the first element being the application class/import string
- # and the second being the help string for the subcommand
- subcommands = Dict()
- # parse_command_line will initialize a subapp, if requested
- subapp = Instance('traitlets.config.application.Application', allow_none=True)
-
- # extra command-line arguments that don't set config values
- extra_args = List(Unicode())
-
+
+ # subcommands for launching other applications
+ # if this is not empty, this will be a parent Application
+ # this must be a dict of two-tuples,
+ # the first element being the application class/import string
+ # and the second being the help string for the subcommand
+ subcommands = Dict()
+ # parse_command_line will initialize a subapp, if requested
+ subapp = Instance('traitlets.config.application.Application', allow_none=True)
+
+ # extra command-line arguments that don't set config values
+ extra_args = List(Unicode())
+
cli_config = Instance(Config, (), {},
help="""The subset of our configuration that came from the command-line
-
+
We re-load this configuration after loading config files,
to ensure that it maintains highest priority.
"""
@@ -307,10 +307,10 @@ class Application(SingletonConfigurable):
self._save_start = self.start
self.start = self.start_show_config
- def __init__(self, **kwargs):
- SingletonConfigurable.__init__(self, **kwargs)
- # Ensure my class is in self.classes, so my attributes appear in command line
- # options and config files.
+ def __init__(self, **kwargs):
+ SingletonConfigurable.__init__(self, **kwargs)
+ # Ensure my class is in self.classes, so my attributes appear in command line
+ # options and config files.
cls = self.__class__
if cls not in self.classes:
if self.classes is cls.classes:
@@ -319,29 +319,29 @@ class Application(SingletonConfigurable):
else:
self.classes.insert(0, self.__class__)
- @observe('config')
- @observe_compat
- def _config_changed(self, change):
- super(Application, self)._config_changed(change)
+ @observe('config')
+ @observe_compat
+ def _config_changed(self, change):
+ super(Application, self)._config_changed(change)
self.log.debug('Config changed: %r', change.new)
-
- @catch_config_error
- def initialize(self, argv=None):
- """Do the basic steps to configure me.
-
- Override in subclasses.
- """
- self.parse_command_line(argv)
-
-
- def start(self):
- """Start the app mainloop.
-
- Override in subclasses.
- """
- if self.subapp is not None:
- return self.subapp.start()
-
+
+ @catch_config_error
+ def initialize(self, argv=None):
+ """Do the basic steps to configure me.
+
+ Override in subclasses.
+ """
+ self.parse_command_line(argv)
+
+
+ def start(self):
+ """Start the app mainloop.
+
+ Override in subclasses.
+ """
+ if self.subapp is not None:
+ return self.subapp.start()
+
def start_show_config(self):
"""start function used when show_config is True"""
config = self.config.copy()
@@ -379,21 +379,21 @@ class Application(SingletonConfigurable):
pprint.pformat(value, **pformat_kwargs),
))
- def print_alias_help(self):
+ def print_alias_help(self):
"""Print the alias parts of the help."""
print('\n'.join(self.emit_alias_help()))
def emit_alias_help(self):
"""Yield the lines for alias part of the help."""
- if not self.aliases:
- return
-
- classdict = {}
- for cls in self.classes:
- # include all parents (up to, but excluding Configurable) in available names
- for c in cls.mro()[:-3]:
- classdict[c.__name__] = c
-
+ if not self.aliases:
+ return
+
+ classdict = {}
+ for cls in self.classes:
+ # include all parents (up to, but excluding Configurable) in available names
+ for c in cls.mro()[:-3]:
+ classdict[c.__name__] = c
+
for alias, longname in self.aliases.items():
try:
if isinstance(longname, tuple):
@@ -403,10 +403,10 @@ class Application(SingletonConfigurable):
classname, traitname = longname.split('.')[-2:]
longname = classname + '.' + traitname
cls = classdict[classname]
-
+
trait = cls.class_traits(config=True)[traitname]
fhelp = cls.class_get_trait_help(trait, helptext=fhelp).splitlines()
-
+
if not isinstance(alias, tuple):
alias = (alias, )
alias = sorted(alias, key=len)
@@ -423,15 +423,15 @@ class Application(SingletonConfigurable):
alias, ex)
raise
- def print_flag_help(self):
- """Print the flag part of the help."""
+ def print_flag_help(self):
+ """Print the flag part of the help."""
print('\n'.join(self.emit_flag_help()))
def emit_flag_help(self):
"""Yield the lines for the flag part of the help."""
- if not self.flags:
- return
-
+ if not self.flags:
+ return
+
for flags, (cfg, fhelp) in self.flags.items():
try:
if not isinstance(flags, tuple):
@@ -451,50 +451,50 @@ class Application(SingletonConfigurable):
self.log.error('Failed collecting help-message for flag %r, due to: %s',
flags, ex)
raise
-
- def print_options(self):
+
+ def print_options(self):
"""Print the options part of the help."""
print('\n'.join(self.emit_options_help()))
def emit_options_help(self):
"""Yield the lines for the options part of the help."""
- if not self.flags and not self.aliases:
- return
+ if not self.flags and not self.aliases:
+ return
header = 'Options'
yield header
yield '=' * len(header)
- for p in wrap_paragraphs(self.option_description):
+ for p in wrap_paragraphs(self.option_description):
yield p
yield ''
-
+
for l in self.emit_flag_help():
yield l
for l in self.emit_alias_help():
yield l
yield ''
- def print_subcommands(self):
- """Print the subcommand part of the help."""
+ def print_subcommands(self):
+ """Print the subcommand part of the help."""
print('\n'.join(self.emit_subcommands_help()))
def emit_subcommands_help(self):
"""Yield the lines for the subcommand part of the help."""
- if not self.subcommands:
- return
-
+ if not self.subcommands:
+ return
+
header = "Subcommands"
yield header
yield '=' * len(header)
- for p in wrap_paragraphs(self.subcommand_description.format(
- app=self.name)):
+ for p in wrap_paragraphs(self.subcommand_description.format(
+ app=self.name)):
yield p
yield ''
for subc, (cls, help) in self.subcommands.items():
yield subc
- if help:
+ if help:
yield indent(dedent(help.strip()))
yield ''
-
+
def emit_help_epilogue(self, classes):
"""Yield the very bottom lines of the help message.
@@ -504,13 +504,13 @@ class Application(SingletonConfigurable):
yield "To see all available configurables, use `--help-all`."
yield ''
- def print_help(self, classes=False):
- """Print the help for each Configurable class in self.classes.
-
- If classes=False (the default), only flags and aliases are printed.
- """
+ def print_help(self, classes=False):
+ """Print the help for each Configurable class in self.classes.
+
+ If classes=False (the default), only flags and aliases are printed.
+ """
print('\n'.join(self.emit_help(classes=classes)))
-
+
def emit_help(self, classes=False):
"""Yield the help-lines for each Configurable class in self.classes.
@@ -523,71 +523,71 @@ class Application(SingletonConfigurable):
for l in self.emit_options_help():
yield l
- if classes:
+ if classes:
help_classes = self._classes_with_config_traits()
- if help_classes:
+ if help_classes:
yield "Class options"
yield "============="
- for p in wrap_paragraphs(self.keyvalue_description):
+ for p in wrap_paragraphs(self.keyvalue_description):
yield p
yield ''
-
- for cls in help_classes:
+
+ for cls in help_classes:
yield cls.class_get_help()
yield ''
for l in self.emit_examples():
yield l
-
+
for l in self.emit_help_epilogue(classes):
yield l
-
- def document_config_options(self):
- """Generate rST format documentation for the config options this application
-
- Returns a multiline string.
- """
- return '\n'.join(c.class_config_rst_doc()
- for c in self._classes_inc_parents())
-
- def print_description(self):
- """Print the application description."""
+
+ def document_config_options(self):
+ """Generate rST format documentation for the config options this application
+
+ Returns a multiline string.
+ """
+ return '\n'.join(c.class_config_rst_doc()
+ for c in self._classes_inc_parents())
+
+ def print_description(self):
+ """Print the application description."""
print('\n'.join(self.emit_description()))
-
+
def emit_description(self):
"""Yield lines with the application description."""
for p in wrap_paragraphs(self.description or self.__doc__):
yield p
yield ''
- def print_examples(self):
+ def print_examples(self):
"""Print usage and examples (see `emit_examples()`). """
print('\n'.join(self.emit_examples()))
-
+
def emit_examples(self):
"""Yield lines with the usage and examples.
- This usage string goes at the end of the command line help string
- and should contain examples of the application's usage.
- """
- if self.examples:
+ This usage string goes at the end of the command line help string
+ and should contain examples of the application's usage.
+ """
+ if self.examples:
yield "Examples"
yield "--------"
yield ''
yield indent(dedent(self.examples.strip()))
yield ''
-
- def print_version(self):
- """Print the version string."""
- print(self.version)
-
- @catch_config_error
- def initialize_subcommand(self, subc, argv=None):
- """Initialize a subcommand with argv."""
+
+ def print_version(self):
+ """Print the version string."""
+ print(self.version)
+
+ @catch_config_error
+ def initialize_subcommand(self, subc, argv=None):
+ """Initialize a subcommand with argv."""
subapp, _ = self.subcommands.get(subc)
-
+
if isinstance(subapp, str):
- subapp = import_item(subapp)
-
+ subapp = import_item(subapp)
+
## Cannot issubclass() on a non-type (SOhttp://stackoverflow.com/questions/8692430)
if isinstance(subapp, type) and issubclass(subapp, Application):
# Clear existing instances before...
@@ -601,55 +601,55 @@ class Application(SingletonConfigurable):
raise AssertionError("Invalid mappings for subcommand '%s'!" % subc)
# ... and finally initialize subapp.
- self.subapp.initialize(argv)
+ self.subapp.initialize(argv)
- def flatten_flags(self):
+ def flatten_flags(self):
"""Flatten flags and aliases for loaders, so cl-args override as expected.
- This prevents issues such as an alias pointing to InteractiveShell,
- but a config file setting the same trait in TerminalInteraciveShell
- getting inappropriate priority over the command-line arg.
+ This prevents issues such as an alias pointing to InteractiveShell,
+ but a config file setting the same trait in TerminalInteraciveShell
+ getting inappropriate priority over the command-line arg.
Also, loaders expect ``(key: longname)`` and not ````key: (longname, help)`` items.
-
- Only aliases with exactly one descendent in the class list
- will be promoted.
-
- """
- # build a tree of classes in our list that inherit from a particular
- # it will be a dict by parent classname of classes in our list
- # that are descendents
- mro_tree = defaultdict(list)
- for cls in self.classes:
- clsname = cls.__name__
- for parent in cls.mro()[1:-3]:
- # exclude cls itself and Configurable,HasTraits,object
- mro_tree[parent.__name__].append(clsname)
- # flatten aliases, which have the form:
- # { 'alias' : 'Class.trait' }
- aliases = {}
+
+ Only aliases with exactly one descendent in the class list
+ will be promoted.
+
+ """
+ # build a tree of classes in our list that inherit from a particular
+ # it will be a dict by parent classname of classes in our list
+ # that are descendents
+ mro_tree = defaultdict(list)
+ for cls in self.classes:
+ clsname = cls.__name__
+ for parent in cls.mro()[1:-3]:
+ # exclude cls itself and Configurable,HasTraits,object
+ mro_tree[parent.__name__].append(clsname)
+ # flatten aliases, which have the form:
+ # { 'alias' : 'Class.trait' }
+ aliases = {}
for alias, longname in self.aliases.items():
if isinstance(longname, tuple):
longname, _ = longname
cls, trait = longname.split('.', 1)
- children = mro_tree[cls]
- if len(children) == 1:
- # exactly one descendent, promote alias
- cls = children[0]
+ children = mro_tree[cls]
+ if len(children) == 1:
+ # exactly one descendent, promote alias
+ cls = children[0]
if not isinstance(aliases, tuple):
alias = (alias, )
for al in alias:
aliases[al] = '.'.join([cls,trait])
- # flatten flags, which are of the form:
- # { 'key' : ({'Cls' : {'trait' : value}}, 'help')}
- flags = {}
+ # flatten flags, which are of the form:
+ # { 'key' : ({'Cls' : {'trait' : value}}, 'help')}
+ flags = {}
for key, (flagdict, help) in self.flags.items():
- newflag = {}
+ newflag = {}
for cls, subdict in flagdict.items():
- children = mro_tree[cls]
- # exactly one descendent, promote flag section
- if len(children) == 1:
- cls = children[0]
+ children = mro_tree[cls]
+ # exactly one descendent, promote flag section
+ if len(children) == 1:
+ cls = children[0]
if cls in newflag:
newflag[cls].update(subdict)
@@ -660,48 +660,48 @@ class Application(SingletonConfigurable):
key = (key, )
for k in key:
flags[k] = (newflag, help)
- return flags, aliases
-
+ return flags, aliases
+
def _create_loader(self, argv, aliases, flags, classes):
return KVArgParseConfigLoader(argv, aliases, flags, classes=classes,
log=self.log)
- @catch_config_error
- def parse_command_line(self, argv=None):
- """Parse the command line arguments."""
+ @catch_config_error
+ def parse_command_line(self, argv=None):
+ """Parse the command line arguments."""
assert not isinstance(argv, str)
- argv = sys.argv[1:] if argv is None else argv
+ argv = sys.argv[1:] if argv is None else argv
self.argv = [cast_unicode(arg) for arg in argv ]
- if argv and argv[0] == 'help':
- # turn `ipython help notebook` into `ipython notebook -h`
- argv = argv[1:] + ['-h']
-
- if self.subcommands and len(argv) > 0:
- # we have subcommands, and one may have been specified
- subc, subargv = argv[0], argv[1:]
- if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands:
- # it's a subcommand, and *not* a flag or class parameter
- return self.initialize_subcommand(subc, subargv)
-
- # Arguments after a '--' argument are for the script IPython may be
- # about to run, not IPython iteslf. For arguments parsed here (help and
- # version), we want to only search the arguments up to the first
- # occurrence of '--', which we're calling interpreted_argv.
- try:
- interpreted_argv = argv[:argv.index('--')]
- except ValueError:
- interpreted_argv = argv
-
- if any(x in interpreted_argv for x in ('-h', '--help-all', '--help')):
- self.print_help('--help-all' in interpreted_argv)
- self.exit(0)
-
- if '--version' in interpreted_argv or '-V' in interpreted_argv:
- self.print_version()
- self.exit(0)
-
- # flatten flags&aliases, so cl-args get appropriate priority:
+ if argv and argv[0] == 'help':
+ # turn `ipython help notebook` into `ipython notebook -h`
+ argv = argv[1:] + ['-h']
+
+ if self.subcommands and len(argv) > 0:
+ # we have subcommands, and one may have been specified
+ subc, subargv = argv[0], argv[1:]
+ if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands:
+ # it's a subcommand, and *not* a flag or class parameter
+ return self.initialize_subcommand(subc, subargv)
+
+ # Arguments after a '--' argument are for the script IPython may be
+ # about to run, not IPython iteslf. For arguments parsed here (help and
+ # version), we want to only search the arguments up to the first
+ # occurrence of '--', which we're calling interpreted_argv.
+ try:
+ interpreted_argv = argv[:argv.index('--')]
+ except ValueError:
+ interpreted_argv = argv
+
+ if any(x in interpreted_argv for x in ('-h', '--help-all', '--help')):
+ self.print_help('--help-all' in interpreted_argv)
+ self.exit(0)
+
+ if '--version' in interpreted_argv or '-V' in interpreted_argv:
+ self.print_version()
+ self.exit(0)
+
+ # flatten flags&aliases, so cl-args get appropriate priority:
flags, aliases = self.flatten_flags()
classes = tuple(self._classes_with_config_traits())
loader = self._create_loader(argv, aliases, flags, classes=classes)
@@ -712,46 +712,46 @@ class Application(SingletonConfigurable):
# help output is huge, and comes after the error
raise
self.update_config(self.cli_config)
- # store unparsed args in extra_args
- self.extra_args = loader.extra_args
-
- @classmethod
+ # store unparsed args in extra_args
+ self.extra_args = loader.extra_args
+
+ @classmethod
def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False):
- """Load config files (py,json) by filename and path.
-
- yield each config object in turn.
- """
-
- if not isinstance(path, list):
- path = [path]
- for path in path[::-1]:
- # path list is in descending priority order, so load files backwards:
- pyloader = cls.python_config_loader_class(basefilename+'.py', path=path, log=log)
- if log:
+ """Load config files (py,json) by filename and path.
+
+ yield each config object in turn.
+ """
+
+ if not isinstance(path, list):
+ path = [path]
+ for path in path[::-1]:
+ # path list is in descending priority order, so load files backwards:
+ pyloader = cls.python_config_loader_class(basefilename+'.py', path=path, log=log)
+ if log:
log.debug("Looking for %s in %s", basefilename, path or os.getcwd())
- jsonloader = cls.json_config_loader_class(basefilename+'.json', path=path, log=log)
+ jsonloader = cls.json_config_loader_class(basefilename+'.json', path=path, log=log)
loaded = []
filenames = []
- for loader in [pyloader, jsonloader]:
+ for loader in [pyloader, jsonloader]:
config = None
- try:
- config = loader.load_config()
- except ConfigFileNotFound:
- pass
- except Exception:
- # try to get the full filename, but it will be empty in the
- # unlikely event that the error raised before filefind finished
- filename = loader.full_filename or basefilename
- # problem while running the file
+ try:
+ config = loader.load_config()
+ except ConfigFileNotFound:
+ pass
+ except Exception:
+ # try to get the full filename, but it will be empty in the
+ # unlikely event that the error raised before filefind finished
+ filename = loader.full_filename or basefilename
+ # problem while running the file
if raise_config_file_errors:
raise
- if log:
- log.error("Exception while loading config file %s",
- filename, exc_info=True)
- else:
- if log:
- log.debug("Loaded config file: %s", loader.full_filename)
- if config:
+ if log:
+ log.error("Exception while loading config file %s",
+ filename, exc_info=True)
+ else:
+ if log:
+ log.debug("Loaded config file: %s", loader.full_filename)
+ if config:
for filename, earlier_config in zip(filenames, loaded):
collisions = earlier_config.collisions(config)
if collisions and log:
@@ -762,16 +762,16 @@ class Application(SingletonConfigurable):
yield (config, loader.full_filename)
loaded.append(config)
filenames.append(loader.full_filename)
-
+
@property
def loaded_config_files(self):
"""Currently loaded configuration files"""
return self._loaded_config_files[:]
-
- @catch_config_error
- def load_config_file(self, filename, path=None):
- """Load config files by filename and path."""
- filename, ext = os.path.splitext(filename)
+
+ @catch_config_error
+ def load_config_file(self, filename, path=None):
+ """Load config files by filename and path."""
+ filename, ext = os.path.splitext(filename)
new_config = Config()
for (config, filename) in self._load_config_files(filename, path=path, log=self.log,
raise_config_file_errors=self.raise_config_file_errors,
@@ -782,7 +782,7 @@ class Application(SingletonConfigurable):
# add self.cli_config to preserve CLI config priority
new_config.merge(self.cli_config)
self.update_config(new_config)
-
+
def _classes_with_config_traits(self, classes=None):
"""
Yields only classes with configurable traits, and their subclasses.
@@ -822,76 +822,76 @@ class Application(SingletonConfigurable):
yield cl
def generate_config_file(self, classes=None):
- """generate default config file from Configurables"""
- lines = ["# Configuration file for %s." % self.name]
- lines.append('')
+ """generate default config file from Configurables"""
+ lines = ["# Configuration file for %s." % self.name]
+ lines.append('')
classes = self.classes if classes is None else classes
config_classes = list(self._classes_with_config_traits(classes))
for cls in config_classes:
lines.append(cls.class_config_section(config_classes))
- return '\n'.join(lines)
-
- def exit(self, exit_status=0):
- self.log.debug("Exiting application: %s" % self.name)
- sys.exit(exit_status)
-
- @classmethod
- def launch_instance(cls, argv=None, **kwargs):
- """Launch a global instance of this Application
-
- If a global instance already exists, this reinitializes and starts it
- """
- app = cls.instance(**kwargs)
- app.initialize(argv)
- app.start()
-
-#-----------------------------------------------------------------------------
-# utility functions, for convenience
-#-----------------------------------------------------------------------------
-
+ return '\n'.join(lines)
+
+ def exit(self, exit_status=0):
+ self.log.debug("Exiting application: %s" % self.name)
+ sys.exit(exit_status)
+
+ @classmethod
+ def launch_instance(cls, argv=None, **kwargs):
+ """Launch a global instance of this Application
+
+ If a global instance already exists, this reinitializes and starts it
+ """
+ app = cls.instance(**kwargs)
+ app.initialize(argv)
+ app.start()
+
+#-----------------------------------------------------------------------------
+# utility functions, for convenience
+#-----------------------------------------------------------------------------
+
default_aliases = Application.aliases
default_flags = Application.flags
-def boolean_flag(name, configurable, set_help='', unset_help=''):
- """Helper for building basic --trait, --no-trait flags.
-
- Parameters
- ----------
- name : str
- The name of the flag.
- configurable : str
- The 'Class.trait' string of the trait to be set/unset with the flag
- set_help : unicode
- help string for --name flag
- unset_help : unicode
- help string for --no-name flag
-
- Returns
- -------
- cfg : dict
- A dict with two keys: 'name', and 'no-name', for setting and unsetting
- the trait, respectively.
- """
- # default helpstrings
- set_help = set_help or "set %s=True"%configurable
- unset_help = unset_help or "set %s=False"%configurable
-
- cls,trait = configurable.split('.')
-
- setter = {cls : {trait : True}}
- unsetter = {cls : {trait : False}}
- return {name : (setter, set_help), 'no-'+name : (unsetter, unset_help)}
-
-
-def get_config():
- """Get the config object for the global Application instance, if there is one
-
- otherwise return an empty config object
- """
- if Application.initialized():
- return Application.instance().config
- else:
- return Config()
+def boolean_flag(name, configurable, set_help='', unset_help=''):
+ """Helper for building basic --trait, --no-trait flags.
+
+ Parameters
+ ----------
+ name : str
+ The name of the flag.
+ configurable : str
+ The 'Class.trait' string of the trait to be set/unset with the flag
+ set_help : unicode
+ help string for --name flag
+ unset_help : unicode
+ help string for --no-name flag
+
+ Returns
+ -------
+ cfg : dict
+ A dict with two keys: 'name', and 'no-name', for setting and unsetting
+ the trait, respectively.
+ """
+ # default helpstrings
+ set_help = set_help or "set %s=True"%configurable
+ unset_help = unset_help or "set %s=False"%configurable
+
+ cls,trait = configurable.split('.')
+
+ setter = {cls : {trait : True}}
+ unsetter = {cls : {trait : False}}
+ return {name : (setter, set_help), 'no-'+name : (unsetter, unset_help)}
+
+
+def get_config():
+ """Get the config object for the global Application instance, if there is one
+
+ otherwise return an empty config object
+ """
+ if Application.initialized():
+ return Application.instance().config
+ else:
+ return Config()
if __name__ == '__main__':
diff --git a/contrib/python/traitlets/py3/traitlets/config/configurable.py b/contrib/python/traitlets/py3/traitlets/config/configurable.py
index d6dd93e114..3b2044a01b 100644
--- a/contrib/python/traitlets/py3/traitlets/config/configurable.py
+++ b/contrib/python/traitlets/py3/traitlets/config/configurable.py
@@ -1,13 +1,13 @@
-"""A base class for objects that are configurable."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-
-from copy import deepcopy
+"""A base class for objects that are configurable."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+
+from copy import deepcopy
import logging
import warnings
-
+
from .loader import Config, LazyConfigValue, DeferredConfig, _is_section_key
from traitlets.traitlets import (
Any,
@@ -22,67 +22,67 @@ from traitlets.traitlets import (
)
from traitlets.utils.text import indent, wrap_paragraphs
from textwrap import dedent
-
-
-
-
-#-----------------------------------------------------------------------------
-# Helper classes for Configurables
-#-----------------------------------------------------------------------------
-
-
-class ConfigurableError(Exception):
- pass
-
-
-class MultipleInstanceError(ConfigurableError):
- pass
-
-#-----------------------------------------------------------------------------
-# Configurable implementation
-#-----------------------------------------------------------------------------
-
-class Configurable(HasTraits):
-
- config = Instance(Config, (), {})
- parent = Instance('traitlets.config.configurable.Configurable', allow_none=True)
-
- def __init__(self, **kwargs):
- """Create a configurable given a config config.
-
- Parameters
- ----------
- config : Config
- If this is empty, default values are used. If config is a
- :class:`Config` instance, it will be used to configure the
- instance.
- parent : Configurable instance, optional
- The parent Configurable instance of this object.
-
- Notes
- -----
- Subclasses of Configurable must call the :meth:`__init__` method of
- :class:`Configurable` *before* doing anything else and using
- :func:`super`::
-
- class MyConfigurable(Configurable):
- def __init__(self, config=None):
- super(MyConfigurable, self).__init__(config=config)
- # Then any other code you need to finish initialization.
-
- This ensures that instances will be configured properly.
- """
- parent = kwargs.pop('parent', None)
- if parent is not None:
- # config is implied from parent
- if kwargs.get('config', None) is None:
- kwargs['config'] = parent.config
- self.parent = parent
-
- config = kwargs.pop('config', None)
-
- # load kwarg traits, other than config
- super(Configurable, self).__init__(**kwargs)
+
+
+
+
+#-----------------------------------------------------------------------------
+# Helper classes for Configurables
+#-----------------------------------------------------------------------------
+
+
+class ConfigurableError(Exception):
+ pass
+
+
+class MultipleInstanceError(ConfigurableError):
+ pass
+
+#-----------------------------------------------------------------------------
+# Configurable implementation
+#-----------------------------------------------------------------------------
+
+class Configurable(HasTraits):
+
+ config = Instance(Config, (), {})
+ parent = Instance('traitlets.config.configurable.Configurable', allow_none=True)
+
+ def __init__(self, **kwargs):
+ """Create a configurable given a config config.
+
+ Parameters
+ ----------
+ config : Config
+ If this is empty, default values are used. If config is a
+ :class:`Config` instance, it will be used to configure the
+ instance.
+ parent : Configurable instance, optional
+ The parent Configurable instance of this object.
+
+ Notes
+ -----
+ Subclasses of Configurable must call the :meth:`__init__` method of
+ :class:`Configurable` *before* doing anything else and using
+ :func:`super`::
+
+ class MyConfigurable(Configurable):
+ def __init__(self, config=None):
+ super(MyConfigurable, self).__init__(config=config)
+ # Then any other code you need to finish initialization.
+
+ This ensures that instances will be configured properly.
+ """
+ parent = kwargs.pop('parent', None)
+ if parent is not None:
+ # config is implied from parent
+ if kwargs.get('config', None) is None:
+ kwargs['config'] = parent.config
+ self.parent = parent
+
+ config = kwargs.pop('config', None)
+
+ # load kwarg traits, other than config
+ super(Configurable, self).__init__(**kwargs)
# record traits set by config
config_override_names = set()
@@ -95,122 +95,122 @@ class Configurable(HasTraits):
config_override_names.add(change.name)
self.observe(notice_config_override)
- # load config
- if config is not None:
- # We used to deepcopy, but for now we are trying to just save
- # by reference. This *could* have side effects as all components
- # will share config. In fact, I did find such a side effect in
- # _config_changed below. If a config attribute value was a mutable type
- # all instances of a component were getting the same copy, effectively
- # making that a class attribute.
- # self.config = deepcopy(config)
- self.config = config
- else:
- # allow _config_default to return something
- self._load_config(self.config)
+ # load config
+ if config is not None:
+ # We used to deepcopy, but for now we are trying to just save
+ # by reference. This *could* have side effects as all components
+ # will share config. In fact, I did find such a side effect in
+ # _config_changed below. If a config attribute value was a mutable type
+ # all instances of a component were getting the same copy, effectively
+ # making that a class attribute.
+ # self.config = deepcopy(config)
+ self.config = config
+ else:
+ # allow _config_default to return something
+ self._load_config(self.config)
self.unobserve(notice_config_override)
for name in config_override_names:
setattr(self, name, kwargs[name])
-
- #-------------------------------------------------------------------------
- # Static trait notifiations
- #-------------------------------------------------------------------------
- @classmethod
- def section_names(cls):
- """return section names as a list"""
- return [c.__name__ for c in reversed(cls.__mro__) if
- issubclass(c, Configurable) and issubclass(cls, c)
- ]
+ #-------------------------------------------------------------------------
+ # Static trait notifiations
+ #-------------------------------------------------------------------------
+
+ @classmethod
+ def section_names(cls):
+ """return section names as a list"""
+ return [c.__name__ for c in reversed(cls.__mro__) if
+ issubclass(c, Configurable) and issubclass(cls, c)
+ ]
- def _find_my_config(self, cfg):
- """extract my config from a global Config object
+ def _find_my_config(self, cfg):
+ """extract my config from a global Config object
- will construct a Config object of only the config values that apply to me
- based on my mro(), as well as those of my parent(s) if they exist.
+ will construct a Config object of only the config values that apply to me
+ based on my mro(), as well as those of my parent(s) if they exist.
- If I am Bar and my parent is Foo, and their parent is Tim,
- this will return merge following config sections, in this order::
+ If I am Bar and my parent is Foo, and their parent is Tim,
+ this will return merge following config sections, in this order::
[Bar, Foo.Bar, Tim.Foo.Bar]
- With the last item being the highest priority.
- """
- cfgs = [cfg]
- if self.parent:
- cfgs.append(self.parent._find_my_config(cfg))
- my_config = Config()
- for c in cfgs:
- for sname in self.section_names():
- # Don't do a blind getattr as that would cause the config to
- # dynamically create the section with name Class.__name__.
- if c._has_section(sname):
- my_config.merge(c[sname])
- return my_config
-
- def _load_config(self, cfg, section_names=None, traits=None):
- """load traits from a Config object"""
-
- if traits is None:
- traits = self.traits(config=True)
- if section_names is None:
- section_names = self.section_names()
-
- my_config = self._find_my_config(cfg)
-
- # hold trait notifications until after all config has been loaded
- with self.hold_trait_notifications():
+ With the last item being the highest priority.
+ """
+ cfgs = [cfg]
+ if self.parent:
+ cfgs.append(self.parent._find_my_config(cfg))
+ my_config = Config()
+ for c in cfgs:
+ for sname in self.section_names():
+ # Don't do a blind getattr as that would cause the config to
+ # dynamically create the section with name Class.__name__.
+ if c._has_section(sname):
+ my_config.merge(c[sname])
+ return my_config
+
+ def _load_config(self, cfg, section_names=None, traits=None):
+ """load traits from a Config object"""
+
+ if traits is None:
+ traits = self.traits(config=True)
+ if section_names is None:
+ section_names = self.section_names()
+
+ my_config = self._find_my_config(cfg)
+
+ # hold trait notifications until after all config has been loaded
+ with self.hold_trait_notifications():
for name, config_value in my_config.items():
- if name in traits:
- if isinstance(config_value, LazyConfigValue):
- # ConfigValue is a wrapper for using append / update on containers
- # without having to copy the initial value
- initial = getattr(self, name)
- config_value = config_value.get_value(initial)
+ if name in traits:
+ if isinstance(config_value, LazyConfigValue):
+ # ConfigValue is a wrapper for using append / update on containers
+ # without having to copy the initial value
+ initial = getattr(self, name)
+ config_value = config_value.get_value(initial)
elif isinstance(config_value, DeferredConfig):
# DeferredConfig tends to come from CLI/environment variables
config_value = config_value.get_value(traits[name])
- # We have to do a deepcopy here if we don't deepcopy the entire
- # config object. If we don't, a mutable config_value will be
- # shared by all instances, effectively making it a class attribute.
- setattr(self, name, deepcopy(config_value))
+ # We have to do a deepcopy here if we don't deepcopy the entire
+ # config object. If we don't, a mutable config_value will be
+ # shared by all instances, effectively making it a class attribute.
+ setattr(self, name, deepcopy(config_value))
elif not _is_section_key(name) and not isinstance(config_value, Config):
- from difflib import get_close_matches
+ from difflib import get_close_matches
if isinstance(self, LoggingConfigurable):
warn = self.log.warning
else:
warn = lambda msg: warnings.warn(msg, stacklevel=9)
- matches = get_close_matches(name, traits)
+ matches = get_close_matches(name, traits)
msg = "Config option `{option}` not recognized by `{klass}`.".format(
option=name, klass=self.__class__.__name__)
- if len(matches) == 1:
+ if len(matches) == 1:
msg += " Did you mean `{matches}`?".format(matches=matches[0])
- elif len(matches) >= 1:
+ elif len(matches) >= 1:
msg +=" Did you mean one of: `{matches}`?".format(matches=', '.join(sorted(matches)))
warn(msg)
-
- @observe('config')
- @observe_compat
- def _config_changed(self, change):
- """Update all the class traits having ``config=True`` in metadata.
-
- For any class trait with a ``config`` metadata attribute that is
- ``True``, we update the trait with the value of the corresponding
- config entry.
- """
- # Get all traits with a config metadata entry that is True
- traits = self.traits(config=True)
-
- # We auto-load config section for this class as well as any parent
- # classes that are Configurable subclasses. This starts with Configurable
- # and works down the mro loading the config for each section.
- section_names = self.section_names()
+
+ @observe('config')
+ @observe_compat
+ def _config_changed(self, change):
+ """Update all the class traits having ``config=True`` in metadata.
+
+ For any class trait with a ``config`` metadata attribute that is
+ ``True``, we update the trait with the value of the corresponding
+ config entry.
+ """
+ # Get all traits with a config metadata entry that is True
+ traits = self.traits(config=True)
+
+ # We auto-load config section for this class as well as any parent
+ # classes that are Configurable subclasses. This starts with Configurable
+ # and works down the mro loading the config for each section.
+ section_names = self.section_names()
self._load_config(change.new, traits=traits, section_names=section_names)
-
- def update_config(self, config):
+
+ def update_config(self, config):
"""Update config and load the new values"""
# traitlets prior to 4.2 created a copy of self.config in order to trigger change events.
# Some projects (IPython < 5) relied upon one side effect of this,
@@ -222,28 +222,28 @@ class Configurable(HasTraits):
# load config
self._load_config(config)
# merge it into self.config
- self.config.merge(config)
+ self.config.merge(config)
# TODO: trigger change event if/when dict-update change events take place
# DO NOT trigger full trait-change
-
- @classmethod
- def class_get_help(cls, inst=None):
- """Get the help string for this class in ReST format.
-
- If `inst` is given, it's current trait values will be used in place of
- class defaults.
- """
- assert inst is None or isinstance(inst, cls)
- final_help = []
+
+ @classmethod
+ def class_get_help(cls, inst=None):
+ """Get the help string for this class in ReST format.
+
+ If `inst` is given, it's current trait values will be used in place of
+ class defaults.
+ """
+ assert inst is None or isinstance(inst, cls)
+ final_help = []
base_classes = ', '.join(p.__name__ for p in cls.__bases__)
final_help.append('%s(%s) options' % (cls.__name__, base_classes))
final_help.append(len(final_help[0])*'-')
- for k, v in sorted(cls.class_traits(config=True).items()):
- help = cls.class_get_trait_help(v, inst)
- final_help.append(help)
- return '\n'.join(final_help)
-
- @classmethod
+ for k, v in sorted(cls.class_traits(config=True).items()):
+ help = cls.class_get_trait_help(v, inst)
+ final_help.append(help)
+ return '\n'.join(final_help)
+
+ @classmethod
def class_get_trait_help(cls, trait, inst=None, helptext=None):
"""Get the helptext string for a single trait.
@@ -252,9 +252,9 @@ class Configurable(HasTraits):
the class default.
:param helptext:
If not given, uses the `help` attribute of the current trait.
- """
- assert inst is None or isinstance(inst, cls)
- lines = []
+ """
+ assert inst is None or isinstance(inst, cls)
+ lines = []
header = "--%s.%s" % (cls.__name__, trait.name)
if isinstance(trait, (Container, Dict)):
multiplicity = trait.metadata.get('multiplicity', 'append')
@@ -269,7 +269,7 @@ class Configurable(HasTraits):
else:
header = '%s=<%s>' % (header, trait.__class__.__name__)
#header = "--%s.%s=<%s>" % (cls.__name__, trait.name, trait.__class__.__name__)
- lines.append(header)
+ lines.append(header)
if helptext is None:
helptext = trait.help
@@ -281,26 +281,26 @@ class Configurable(HasTraits):
# include Enum choices
lines.append(indent('Choices: %s' % trait.info()))
- if inst is not None:
+ if inst is not None:
lines.append(indent("Current: %r" % (getattr(inst, trait.name),)))
- else:
- try:
- dvr = trait.default_value_repr()
- except Exception:
- dvr = None # ignore defaults we can't construct
- if dvr is not None:
- if len(dvr) > 64:
+ else:
+ try:
+ dvr = trait.default_value_repr()
+ except Exception:
+ dvr = None # ignore defaults we can't construct
+ if dvr is not None:
+ if len(dvr) > 64:
dvr = dvr[:61] + "..."
lines.append(indent("Default: %s" % dvr))
-
- return '\n'.join(lines)
-
- @classmethod
- def class_print_help(cls, inst=None):
- """Get the help string for a single trait and print it."""
- print(cls.class_get_help(inst))
-
- @classmethod
+
+ return '\n'.join(lines)
+
+ @classmethod
+ def class_print_help(cls, inst=None):
+ """Get the help string for a single trait and print it."""
+ print(cls.class_get_help(inst))
+
+ @classmethod
def _defining_class(cls, trait, classes):
"""Get the class that defines a trait
@@ -336,13 +336,13 @@ class Configurable(HasTraits):
The list of other classes in the config file.
Used to reduce redundant information.
"""
- def c(s):
- """return a commented, wrapped block."""
- s = '\n\n'.join(wrap_paragraphs(s, 78))
-
+ def c(s):
+ """return a commented, wrapped block."""
+ s = '\n\n'.join(wrap_paragraphs(s, 78))
+
return '## ' + s.replace('\n', '\n# ')
-
- # section header
+
+ # section header
breaker = '#' + '-' * 78
parent_classes = ', '.join(
p.__name__ for p in cls.__bases__
@@ -351,17 +351,17 @@ class Configurable(HasTraits):
s = "# %s(%s) configuration" % (cls.__name__, parent_classes)
lines = [breaker, s, breaker]
- # get the description trait
- desc = cls.class_traits().get('description')
- if desc:
- desc = desc.default_value
+ # get the description trait
+ desc = cls.class_traits().get('description')
+ if desc:
+ desc = desc.default_value
if not desc:
# no description from trait, use __doc__
- desc = getattr(cls, '__doc__', '')
- if desc:
- lines.append(c(desc))
- lines.append('')
-
+ desc = getattr(cls, '__doc__', '')
+ if desc:
+ lines.append(c(desc))
+ lines.append('')
+
for name, trait in sorted(cls.class_traits(config=True).items()):
default_repr = trait.default_value_repr()
@@ -385,60 +385,60 @@ class Configurable(HasTraits):
lines.append('# See also: %s.%s' % (defining_class.__name__, name))
lines.append('# c.%s.%s = %s' % (cls.__name__, name, default_repr))
- lines.append('')
- return '\n'.join(lines)
-
- @classmethod
- def class_config_rst_doc(cls):
- """Generate rST documentation for this class' config options.
-
- Excludes traits defined on parent classes.
- """
- lines = []
- classname = cls.__name__
+ lines.append('')
+ return '\n'.join(lines)
+
+ @classmethod
+ def class_config_rst_doc(cls):
+ """Generate rST documentation for this class' config options.
+
+ Excludes traits defined on parent classes.
+ """
+ lines = []
+ classname = cls.__name__
for k, trait in sorted(cls.class_traits(config=True).items()):
- ttype = trait.__class__.__name__
-
- termline = classname + '.' + trait.name
-
- # Choices or type
- if 'Enum' in ttype:
- # include Enum choices
+ ttype = trait.__class__.__name__
+
+ termline = classname + '.' + trait.name
+
+ # Choices or type
+ if 'Enum' in ttype:
+ # include Enum choices
termline += ' : ' + trait.info_rst()
- else:
- termline += ' : ' + ttype
- lines.append(termline)
-
- # Default value
- try:
- dvr = trait.default_value_repr()
- except Exception:
- dvr = None # ignore defaults we can't construct
- if dvr is not None:
- if len(dvr) > 64:
- dvr = dvr[:61]+'...'
- # Double up backslashes, so they get to the rendered docs
+ else:
+ termline += ' : ' + ttype
+ lines.append(termline)
+
+ # Default value
+ try:
+ dvr = trait.default_value_repr()
+ except Exception:
+ dvr = None # ignore defaults we can't construct
+ if dvr is not None:
+ if len(dvr) > 64:
+ dvr = dvr[:61]+'...'
+ # Double up backslashes, so they get to the rendered docs
dvr = dvr.replace("\\n", "\\\\n")
lines.append(indent("Default: ``%s``" % dvr))
lines.append("")
-
- help = trait.help or 'No description'
+
+ help = trait.help or 'No description'
lines.append(indent(dedent(help)))
-
- # Blank line
- lines.append('')
-
- return '\n'.join(lines)
-
-
-
-class LoggingConfigurable(Configurable):
- """A parent class for Configurables that log.
-
- Subclasses have a log trait, and the default behavior
- is to get the logger from the currently running Application.
- """
-
+
+ # Blank line
+ lines.append('')
+
+ return '\n'.join(lines)
+
+
+
+class LoggingConfigurable(Configurable):
+ """A parent class for Configurables that log.
+
+ Subclasses have a log trait, and the default behavior
+ is to get the logger from the currently running Application.
+ """
+
log = Any(help="Logger or LoggerAdapter instance")
@validate("log")
@@ -452,15 +452,15 @@ class LoggingConfigurable(Configurable):
return proposal.value
@default("log")
- def _log_default(self):
+ def _log_default(self):
if isinstance(self.parent, LoggingConfigurable):
return self.parent.log
- from traitlets import log
- return log.get_logger()
-
+ from traitlets import log
+ return log.get_logger()
+
def _get_log_handler(self):
"""Return the default Handler
-
+
Returns None if none can be found
"""
logger = self.log
@@ -472,89 +472,89 @@ class LoggingConfigurable(Configurable):
return logger.handlers[0]
-class SingletonConfigurable(LoggingConfigurable):
- """A configurable that only allows one instance.
-
- This class is for classes that should only have one instance of itself
- or *any* subclass. To create and retrieve such a class use the
- :meth:`SingletonConfigurable.instance` method.
- """
-
- _instance = None
-
- @classmethod
- def _walk_mro(cls):
- """Walk the cls.mro() for parent classes that are also singletons
-
- For use in instance()
- """
-
- for subclass in cls.mro():
- if issubclass(cls, subclass) and \
- issubclass(subclass, SingletonConfigurable) and \
- subclass != SingletonConfigurable:
- yield subclass
-
- @classmethod
- def clear_instance(cls):
- """unset _instance for this class and singleton parents.
- """
- if not cls.initialized():
- return
- for subclass in cls._walk_mro():
- if isinstance(subclass._instance, cls):
- # only clear instances that are instances
- # of the calling class
- subclass._instance = None
-
- @classmethod
- def instance(cls, *args, **kwargs):
- """Returns a global instance of this class.
-
- This method create a new instance if none have previously been created
- and returns a previously created instance is one already exists.
-
- The arguments and keyword arguments passed to this method are passed
- on to the :meth:`__init__` method of the class upon instantiation.
-
- Examples
- --------
- Create a singleton class using instance, and retrieve it::
-
- >>> from traitlets.config.configurable import SingletonConfigurable
- >>> class Foo(SingletonConfigurable): pass
- >>> foo = Foo.instance()
- >>> foo == Foo.instance()
- True
-
- Create a subclass that is retrived using the base class instance::
-
- >>> class Bar(SingletonConfigurable): pass
- >>> class Bam(Bar): pass
- >>> bam = Bam.instance()
- >>> bam == Bar.instance()
- True
- """
- # Create and save the instance
- if cls._instance is None:
- inst = cls(*args, **kwargs)
- # Now make sure that the instance will also be returned by
- # parent classes' _instance attribute.
- for subclass in cls._walk_mro():
- subclass._instance = inst
-
- if isinstance(cls._instance, cls):
- return cls._instance
- else:
- raise MultipleInstanceError(
+class SingletonConfigurable(LoggingConfigurable):
+ """A configurable that only allows one instance.
+
+ This class is for classes that should only have one instance of itself
+ or *any* subclass. To create and retrieve such a class use the
+ :meth:`SingletonConfigurable.instance` method.
+ """
+
+ _instance = None
+
+ @classmethod
+ def _walk_mro(cls):
+ """Walk the cls.mro() for parent classes that are also singletons
+
+ For use in instance()
+ """
+
+ for subclass in cls.mro():
+ if issubclass(cls, subclass) and \
+ issubclass(subclass, SingletonConfigurable) and \
+ subclass != SingletonConfigurable:
+ yield subclass
+
+ @classmethod
+ def clear_instance(cls):
+ """unset _instance for this class and singleton parents.
+ """
+ if not cls.initialized():
+ return
+ for subclass in cls._walk_mro():
+ if isinstance(subclass._instance, cls):
+ # only clear instances that are instances
+ # of the calling class
+ subclass._instance = None
+
+ @classmethod
+ def instance(cls, *args, **kwargs):
+ """Returns a global instance of this class.
+
+ This method create a new instance if none have previously been created
+ and returns a previously created instance is one already exists.
+
+ The arguments and keyword arguments passed to this method are passed
+ on to the :meth:`__init__` method of the class upon instantiation.
+
+ Examples
+ --------
+ Create a singleton class using instance, and retrieve it::
+
+ >>> from traitlets.config.configurable import SingletonConfigurable
+ >>> class Foo(SingletonConfigurable): pass
+ >>> foo = Foo.instance()
+ >>> foo == Foo.instance()
+ True
+
+ Create a subclass that is retrived using the base class instance::
+
+ >>> class Bar(SingletonConfigurable): pass
+ >>> class Bam(Bar): pass
+ >>> bam = Bam.instance()
+ >>> bam == Bar.instance()
+ True
+ """
+ # Create and save the instance
+ if cls._instance is None:
+ inst = cls(*args, **kwargs)
+ # Now make sure that the instance will also be returned by
+ # parent classes' _instance attribute.
+ for subclass in cls._walk_mro():
+ subclass._instance = inst
+
+ if isinstance(cls._instance, cls):
+ return cls._instance
+ else:
+ raise MultipleInstanceError(
"An incompatible sibling of '%s' is already instanciated"
" as singleton: %s" % (cls.__name__, type(cls._instance).__name__)
- )
-
- @classmethod
- def initialized(cls):
- """Has an instance been created?"""
- return hasattr(cls, "_instance") and cls._instance is not None
-
-
-
+ )
+
+ @classmethod
+ def initialized(cls):
+ """Has an instance been created?"""
+ return hasattr(cls, "_instance") and cls._instance is not None
+
+
+
diff --git a/contrib/python/traitlets/py3/traitlets/config/loader.py b/contrib/python/traitlets/py3/traitlets/config/loader.py
index 3af27bc22f..5360f889ab 100644
--- a/contrib/python/traitlets/py3/traitlets/config/loader.py
+++ b/contrib/python/traitlets/py3/traitlets/config/loader.py
@@ -1,49 +1,49 @@
-"""A simple configuration system."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import argparse
-import copy
-import os
-import re
-import sys
-import json
+"""A simple configuration system."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import argparse
+import copy
+import os
+import re
+import sys
+import json
import warnings
-
+
from ..utils import cast_unicode, filefind
from traitlets.traitlets import (
HasTraits, Container, List, Dict, Any, Undefined,
)
-
-#-----------------------------------------------------------------------------
-# Exceptions
-#-----------------------------------------------------------------------------
-
-
-class ConfigError(Exception):
- pass
-
-class ConfigLoaderError(ConfigError):
- pass
-
-class ConfigFileNotFound(ConfigError):
- pass
-
-class ArgumentError(ConfigLoaderError):
- pass
-
-#-----------------------------------------------------------------------------
-# Argparse fix
-#-----------------------------------------------------------------------------
-
-# Unfortunately argparse by default prints help messages to stderr instead of
-# stdout. This makes it annoying to capture long help screens at the command
-# line, since one must know how to pipe stderr, which many users don't know how
-# to do. So we override the print_help method with one that defaults to
-# stdout and use our class instead.
-
+
+#-----------------------------------------------------------------------------
+# Exceptions
+#-----------------------------------------------------------------------------
+
+
+class ConfigError(Exception):
+ pass
+
+class ConfigLoaderError(ConfigError):
+ pass
+
+class ConfigFileNotFound(ConfigError):
+ pass
+
+class ArgumentError(ConfigLoaderError):
+ pass
+
+#-----------------------------------------------------------------------------
+# Argparse fix
+#-----------------------------------------------------------------------------
+
+# Unfortunately argparse by default prints help messages to stderr instead of
+# stdout. This makes it annoying to capture long help screens at the command
+# line, since one must know how to pipe stderr, which many users don't know how
+# to do. So we override the print_help method with one that defaults to
+# stdout and use our class instead.
+
class _Sentinel:
def __repr__(self):
@@ -56,55 +56,55 @@ class _Sentinel:
_deprecated = _Sentinel()
-class ArgumentParser(argparse.ArgumentParser):
- """Simple argparse subclass that prints help to stdout by default."""
-
- def print_help(self, file=None):
- if file is None:
- file = sys.stdout
- return super(ArgumentParser, self).print_help(file)
-
- print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
-
-#-----------------------------------------------------------------------------
-# Config class for holding config information
-#-----------------------------------------------------------------------------
-
+class ArgumentParser(argparse.ArgumentParser):
+ """Simple argparse subclass that prints help to stdout by default."""
+
+ def print_help(self, file=None):
+ if file is None:
+ file = sys.stdout
+ return super(ArgumentParser, self).print_help(file)
+
+ print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
+
+#-----------------------------------------------------------------------------
+# Config class for holding config information
+#-----------------------------------------------------------------------------
+
def execfile(fname, glob):
with open(fname, 'rb') as f:
exec(compile(f.read(), fname, 'exec'), glob, glob)
-class LazyConfigValue(HasTraits):
- """Proxy object for exposing methods on configurable containers
+class LazyConfigValue(HasTraits):
+ """Proxy object for exposing methods on configurable containers
These methods allow appending/extending/updating
to add to non-empty defaults instead of clobbering them.
- Exposes:
+ Exposes:
- - append, extend, insert on lists
- - update on dicts
- - update, add on sets
- """
+ - append, extend, insert on lists
+ - update on dicts
+ - update, add on sets
+ """
- _value = None
+ _value = None
- # list methods
- _extend = List()
- _prepend = List()
+ # list methods
+ _extend = List()
+ _prepend = List()
_inserts = List()
- def append(self, obj):
+ def append(self, obj):
"""Append an item to a List"""
- self._extend.append(obj)
+ self._extend.append(obj)
- def extend(self, other):
+ def extend(self, other):
"""Extend a list"""
- self._extend.extend(other)
+ self._extend.extend(other)
- def prepend(self, other):
- """like list.extend, but for the front"""
- self._prepend[:0] = other
+ def prepend(self, other):
+ """like list.extend, but for the front"""
+ self._prepend[:0] = other
def merge_into(self, other):
@@ -140,86 +140,86 @@ class LazyConfigValue(HasTraits):
# other is a container, reify now.
return self.get_value(other)
- def insert(self, index, other):
- if not isinstance(index, int):
- raise TypeError("An integer is required")
- self._inserts.append((index, other))
+ def insert(self, index, other):
+ if not isinstance(index, int):
+ raise TypeError("An integer is required")
+ self._inserts.append((index, other))
- # dict methods
- # update is used for both dict and set
- _update = Any()
+ # dict methods
+ # update is used for both dict and set
+ _update = Any()
- def update(self, other):
+ def update(self, other):
"""Update either a set or dict"""
- if self._update is None:
- if isinstance(other, dict):
- self._update = {}
- else:
- self._update = set()
- self._update.update(other)
-
- # set methods
- def add(self, obj):
+ if self._update is None:
+ if isinstance(other, dict):
+ self._update = {}
+ else:
+ self._update = set()
+ self._update.update(other)
+
+ # set methods
+ def add(self, obj):
"""Add an item to a set"""
- self.update({obj})
-
- def get_value(self, initial):
- """construct the value from the initial one
-
- after applying any insert / extend / update changes
- """
- if self._value is not None:
- return self._value
- value = copy.deepcopy(initial)
- if isinstance(value, list):
- for idx, obj in self._inserts:
- value.insert(idx, obj)
- value[:0] = self._prepend
- value.extend(self._extend)
-
- elif isinstance(value, dict):
- if self._update:
- value.update(self._update)
- elif isinstance(value, set):
- if self._update:
- value.update(self._update)
- self._value = value
- return value
-
- def to_dict(self):
- """return JSONable dict form of my data
-
- Currently update as dict or set, extend, prepend as lists, and inserts as list of tuples.
- """
- d = {}
- if self._update:
- d['update'] = self._update
- if self._extend:
- d['extend'] = self._extend
- if self._prepend:
- d['prepend'] = self._prepend
- elif self._inserts:
- d['inserts'] = self._inserts
- return d
-
+ self.update({obj})
+
+ def get_value(self, initial):
+ """construct the value from the initial one
+
+ after applying any insert / extend / update changes
+ """
+ if self._value is not None:
+ return self._value
+ value = copy.deepcopy(initial)
+ if isinstance(value, list):
+ for idx, obj in self._inserts:
+ value.insert(idx, obj)
+ value[:0] = self._prepend
+ value.extend(self._extend)
+
+ elif isinstance(value, dict):
+ if self._update:
+ value.update(self._update)
+ elif isinstance(value, set):
+ if self._update:
+ value.update(self._update)
+ self._value = value
+ return value
+
+ def to_dict(self):
+ """return JSONable dict form of my data
+
+ Currently update as dict or set, extend, prepend as lists, and inserts as list of tuples.
+ """
+ d = {}
+ if self._update:
+ d['update'] = self._update
+ if self._extend:
+ d['extend'] = self._extend
+ if self._prepend:
+ d['prepend'] = self._prepend
+ elif self._inserts:
+ d['inserts'] = self._inserts
+ return d
+
def __repr__(self):
if self._value is not None:
return "<%s value=%r>" % (self.__class__.__name__, self._value)
else:
return "<%s %r>" % (self.__class__.__name__, self.to_dict())
-
-
-def _is_section_key(key):
- """Is a Config key a section name (does it start with a capital)?"""
- if key and key[0].upper()==key[0] and not key.startswith('_'):
- return True
- else:
- return False
-
-
-class Config(dict):
+
+
+def _is_section_key(key):
+ """Is a Config key a section name (does it start with a capital)?"""
+ if key and key[0].upper()==key[0] and not key.startswith('_'):
+ return True
+ else:
+ return False
+
+
+class Config(dict):
"""An attribute-based dict that can do smart merges.
-
+
Accessing a field on a config object for the first time populates the key
with either a nested Config object for keys starting with capitals
or :class:`.LazyConfigValue` for lowercase keys,
@@ -231,147 +231,147 @@ class Config(dict):
"""
- def __init__(self, *args, **kwds):
- dict.__init__(self, *args, **kwds)
- self._ensure_subconfig()
-
- def _ensure_subconfig(self):
- """ensure that sub-dicts that should be Config objects are
-
- casts dicts that are under section keys to Config objects,
- which is necessary for constructing Config objects from dict literals.
- """
- for key in self:
- obj = self[key]
- if _is_section_key(key) \
- and isinstance(obj, dict) \
- and not isinstance(obj, Config):
- setattr(self, key, Config(obj))
-
- def _merge(self, other):
- """deprecated alias, use Config.merge()"""
- self.merge(other)
-
- def merge(self, other):
- """merge another config object into this one"""
- to_update = {}
+ def __init__(self, *args, **kwds):
+ dict.__init__(self, *args, **kwds)
+ self._ensure_subconfig()
+
+ def _ensure_subconfig(self):
+ """ensure that sub-dicts that should be Config objects are
+
+ casts dicts that are under section keys to Config objects,
+ which is necessary for constructing Config objects from dict literals.
+ """
+ for key in self:
+ obj = self[key]
+ if _is_section_key(key) \
+ and isinstance(obj, dict) \
+ and not isinstance(obj, Config):
+ setattr(self, key, Config(obj))
+
+ def _merge(self, other):
+ """deprecated alias, use Config.merge()"""
+ self.merge(other)
+
+ def merge(self, other):
+ """merge another config object into this one"""
+ to_update = {}
for k, v in other.items():
- if k not in self:
- to_update[k] = v
- else: # I have this key
- if isinstance(v, Config) and isinstance(self[k], Config):
- # Recursively merge common sub Configs
- self[k].merge(v)
+ if k not in self:
+ to_update[k] = v
+ else: # I have this key
+ if isinstance(v, Config) and isinstance(self[k], Config):
+ # Recursively merge common sub Configs
+ self[k].merge(v)
elif isinstance(v, LazyConfigValue):
self[k] = v.merge_into(self[k])
- else:
- # Plain updates for non-Configs
- to_update[k] = v
-
- self.update(to_update)
-
- def collisions(self, other):
- """Check for collisions between two config objects.
-
- Returns a dict of the form {"Class": {"trait": "collision message"}}`,
- indicating which values have been ignored.
-
- An empty dict indicates no collisions.
- """
- collisions = {}
- for section in self:
- if section not in other:
- continue
- mine = self[section]
- theirs = other[section]
- for key in mine:
- if key in theirs and mine[key] != theirs[key]:
- collisions.setdefault(section, {})
- collisions[section][key] = "%r ignored, using %r" % (mine[key], theirs[key])
- return collisions
-
- def __contains__(self, key):
- # allow nested contains of the form `"Section.key" in config`
- if '.' in key:
- first, remainder = key.split('.', 1)
- if first not in self:
- return False
- return remainder in self[first]
-
- return super(Config, self).__contains__(key)
-
- # .has_key is deprecated for dictionaries.
- has_key = __contains__
-
- def _has_section(self, key):
- return _is_section_key(key) and key in self
-
- def copy(self):
- return type(self)(dict.copy(self))
-
- def __copy__(self):
- return self.copy()
-
- def __deepcopy__(self, memo):
- new_config = type(self)()
- for key, value in self.items():
- if isinstance(value, (Config, LazyConfigValue)):
- # deep copy config objects
- value = copy.deepcopy(value, memo)
- elif type(value) in {dict, list, set, tuple}:
- # shallow copy plain container traits
- value = copy.copy(value)
- new_config[key] = value
- return new_config
-
- def __getitem__(self, key):
- try:
- return dict.__getitem__(self, key)
- except KeyError:
- if _is_section_key(key):
- c = Config()
- dict.__setitem__(self, key, c)
- return c
- elif not key.startswith('_'):
- # undefined, create lazy value, used for container methods
- v = LazyConfigValue()
- dict.__setitem__(self, key, v)
- return v
- else:
- raise KeyError
-
- def __setitem__(self, key, value):
- if _is_section_key(key):
- if not isinstance(value, Config):
- raise ValueError('values whose keys begin with an uppercase '
- 'char must be Config instances: %r, %r' % (key, value))
- dict.__setitem__(self, key, value)
-
- def __getattr__(self, key):
- if key.startswith('__'):
- return dict.__getattr__(self, key)
- try:
- return self.__getitem__(key)
- except KeyError as e:
- raise AttributeError(e)
-
- def __setattr__(self, key, value):
- if key.startswith('__'):
- return dict.__setattr__(self, key, value)
- try:
- self.__setitem__(key, value)
- except KeyError as e:
- raise AttributeError(e)
-
- def __delattr__(self, key):
- if key.startswith('__'):
- return dict.__delattr__(self, key)
- try:
- dict.__delitem__(self, key)
- except KeyError as e:
- raise AttributeError(e)
-
-
+ else:
+ # Plain updates for non-Configs
+ to_update[k] = v
+
+ self.update(to_update)
+
+ def collisions(self, other):
+ """Check for collisions between two config objects.
+
+ Returns a dict of the form {"Class": {"trait": "collision message"}}`,
+ indicating which values have been ignored.
+
+ An empty dict indicates no collisions.
+ """
+ collisions = {}
+ for section in self:
+ if section not in other:
+ continue
+ mine = self[section]
+ theirs = other[section]
+ for key in mine:
+ if key in theirs and mine[key] != theirs[key]:
+ collisions.setdefault(section, {})
+ collisions[section][key] = "%r ignored, using %r" % (mine[key], theirs[key])
+ return collisions
+
+ def __contains__(self, key):
+ # allow nested contains of the form `"Section.key" in config`
+ if '.' in key:
+ first, remainder = key.split('.', 1)
+ if first not in self:
+ return False
+ return remainder in self[first]
+
+ return super(Config, self).__contains__(key)
+
+ # .has_key is deprecated for dictionaries.
+ has_key = __contains__
+
+ def _has_section(self, key):
+ return _is_section_key(key) and key in self
+
+ def copy(self):
+ return type(self)(dict.copy(self))
+
+ def __copy__(self):
+ return self.copy()
+
+ def __deepcopy__(self, memo):
+ new_config = type(self)()
+ for key, value in self.items():
+ if isinstance(value, (Config, LazyConfigValue)):
+ # deep copy config objects
+ value = copy.deepcopy(value, memo)
+ elif type(value) in {dict, list, set, tuple}:
+ # shallow copy plain container traits
+ value = copy.copy(value)
+ new_config[key] = value
+ return new_config
+
+ def __getitem__(self, key):
+ try:
+ return dict.__getitem__(self, key)
+ except KeyError:
+ if _is_section_key(key):
+ c = Config()
+ dict.__setitem__(self, key, c)
+ return c
+ elif not key.startswith('_'):
+ # undefined, create lazy value, used for container methods
+ v = LazyConfigValue()
+ dict.__setitem__(self, key, v)
+ return v
+ else:
+ raise KeyError
+
+ def __setitem__(self, key, value):
+ if _is_section_key(key):
+ if not isinstance(value, Config):
+ raise ValueError('values whose keys begin with an uppercase '
+ 'char must be Config instances: %r, %r' % (key, value))
+ dict.__setitem__(self, key, value)
+
+ def __getattr__(self, key):
+ if key.startswith('__'):
+ return dict.__getattr__(self, key)
+ try:
+ return self.__getitem__(key)
+ except KeyError as e:
+ raise AttributeError(e)
+
+ def __setattr__(self, key, value):
+ if key.startswith('__'):
+ return dict.__setattr__(self, key, value)
+ try:
+ self.__setitem__(key, value)
+ except KeyError as e:
+ raise AttributeError(e)
+
+ def __delattr__(self, key):
+ if key.startswith('__'):
+ return dict.__delattr__(self, key)
+ try:
+ dict.__delitem__(self, key)
+ except KeyError as e:
+ raise AttributeError(e)
+
+
class DeferredConfig:
"""Class for deferred-evaluation of config from CLI"""
pass
@@ -455,95 +455,95 @@ class DeferredConfigList(list, DeferredConfig):
return '%s(%s)' % (self.__class__.__name__, self._super_repr())
-#-----------------------------------------------------------------------------
-# Config loading classes
-#-----------------------------------------------------------------------------
-
-
-class ConfigLoader(object):
- """A object for loading configurations from just about anywhere.
-
- The resulting configuration is packaged as a :class:`Config`.
-
- Notes
- -----
- A :class:`ConfigLoader` does one thing: load a config from a source
- (file, command line arguments) and returns the data as a :class:`Config` object.
- There are lots of things that :class:`ConfigLoader` does not do. It does
- not implement complex logic for finding config files. It does not handle
- default values or merge multiple configs. These things need to be
- handled elsewhere.
- """
-
- def _log_default(self):
- from traitlets.log import get_logger
- return get_logger()
-
- def __init__(self, log=None):
- """A base class for config loaders.
-
- log : instance of :class:`logging.Logger` to use.
+#-----------------------------------------------------------------------------
+# Config loading classes
+#-----------------------------------------------------------------------------
+
+
+class ConfigLoader(object):
+ """A object for loading configurations from just about anywhere.
+
+ The resulting configuration is packaged as a :class:`Config`.
+
+ Notes
+ -----
+ A :class:`ConfigLoader` does one thing: load a config from a source
+ (file, command line arguments) and returns the data as a :class:`Config` object.
+ There are lots of things that :class:`ConfigLoader` does not do. It does
+ not implement complex logic for finding config files. It does not handle
+ default values or merge multiple configs. These things need to be
+ handled elsewhere.
+ """
+
+ def _log_default(self):
+ from traitlets.log import get_logger
+ return get_logger()
+
+ def __init__(self, log=None):
+ """A base class for config loaders.
+
+ log : instance of :class:`logging.Logger` to use.
By default logger of :meth:`traitlets.config.application.Application.instance()`
- will be used
-
- Examples
- --------
- >>> cl = ConfigLoader()
- >>> config = cl.load_config()
- >>> config
- {}
- """
- self.clear()
- if log is None:
- self.log = self._log_default()
- self.log.debug('Using default logger')
- else:
- self.log = log
-
- def clear(self):
- self.config = Config()
-
- def load_config(self):
- """Load a config from somewhere, return a :class:`Config` instance.
-
- Usually, this will cause self.config to be set and then returned.
- However, in most cases, :meth:`ConfigLoader.clear` should be called
- to erase any previous state.
- """
- self.clear()
- return self.config
-
-
-class FileConfigLoader(ConfigLoader):
- """A base class for file based configurations.
-
- As we add more file based config loaders, the common logic should go
- here.
- """
-
- def __init__(self, filename, path=None, **kw):
- """Build a config loader for a filename and path.
-
- Parameters
- ----------
- filename : str
- The file name of the config file.
- path : str, list, tuple
- The path to search for the config file on, or a sequence of
- paths to try in order.
- """
- super(FileConfigLoader, self).__init__(**kw)
- self.filename = filename
- self.path = path
- self.full_filename = ''
-
- def _find_file(self):
- """Try to find the file by searching the paths."""
- self.full_filename = filefind(self.filename, self.path)
-
-class JSONFileConfigLoader(FileConfigLoader):
+ will be used
+
+ Examples
+ --------
+ >>> cl = ConfigLoader()
+ >>> config = cl.load_config()
+ >>> config
+ {}
+ """
+ self.clear()
+ if log is None:
+ self.log = self._log_default()
+ self.log.debug('Using default logger')
+ else:
+ self.log = log
+
+ def clear(self):
+ self.config = Config()
+
+ def load_config(self):
+ """Load a config from somewhere, return a :class:`Config` instance.
+
+ Usually, this will cause self.config to be set and then returned.
+ However, in most cases, :meth:`ConfigLoader.clear` should be called
+ to erase any previous state.
+ """
+ self.clear()
+ return self.config
+
+
+class FileConfigLoader(ConfigLoader):
+ """A base class for file based configurations.
+
+ As we add more file based config loaders, the common logic should go
+ here.
+ """
+
+ def __init__(self, filename, path=None, **kw):
+ """Build a config loader for a filename and path.
+
+ Parameters
+ ----------
+ filename : str
+ The file name of the config file.
+ path : str, list, tuple
+ The path to search for the config file on, or a sequence of
+ paths to try in order.
+ """
+ super(FileConfigLoader, self).__init__(**kw)
+ self.filename = filename
+ self.path = path
+ self.full_filename = ''
+
+ def _find_file(self):
+ """Try to find the file by searching the paths."""
+ self.full_filename = filefind(self.filename, self.path)
+
+class JSONFileConfigLoader(FileConfigLoader):
"""A JSON file loader for config
-
+
Can also act as a context manager that rewrite the configuration file to disk on exit.
Example::
@@ -553,36 +553,36 @@ class JSONFileConfigLoader(FileConfigLoader):
"""
- def load_config(self):
- """Load the config from a file and return it as a Config object."""
- self.clear()
- try:
- self._find_file()
- except IOError as e:
- raise ConfigFileNotFound(str(e))
- dct = self._read_file_as_dict()
- self.config = self._convert_to_config(dct)
- return self.config
-
- def _read_file_as_dict(self):
- with open(self.full_filename) as f:
- return json.load(f)
-
- def _convert_to_config(self, dictionary):
- if 'version' in dictionary:
- version = dictionary.pop('version')
- else:
- version = 1
-
- if version == 1:
- return Config(dictionary)
- else:
- raise ValueError('Unknown version of JSON config file: {version}'.format(version=version))
-
+ def load_config(self):
+ """Load the config from a file and return it as a Config object."""
+ self.clear()
+ try:
+ self._find_file()
+ except IOError as e:
+ raise ConfigFileNotFound(str(e))
+ dct = self._read_file_as_dict()
+ self.config = self._convert_to_config(dct)
+ return self.config
+
+ def _read_file_as_dict(self):
+ with open(self.full_filename) as f:
+ return json.load(f)
+
+ def _convert_to_config(self, dictionary):
+ if 'version' in dictionary:
+ version = dictionary.pop('version')
+ else:
+ version = 1
+
+ if version == 1:
+ return Config(dictionary)
+ else:
+ raise ValueError('Unknown version of JSON config file: {version}'.format(version=version))
+
def __enter__(self):
self.load_config()
return self.config
-
+
def __exit__(self, exc_type, exc_value, traceback):
"""
Exit the context manager but do not handle any errors.
@@ -597,68 +597,68 @@ class JSONFileConfigLoader(FileConfigLoader):
-class PyFileConfigLoader(FileConfigLoader):
- """A config loader for pure python files.
-
- This is responsible for locating a Python config file by filename and
- path, then executing it to construct a Config object.
- """
-
- def load_config(self):
- """Load the config from a file and return it as a Config object."""
- self.clear()
- try:
- self._find_file()
- except IOError as e:
- raise ConfigFileNotFound(str(e))
- self._read_file_as_dict()
- return self.config
-
- def load_subconfig(self, fname, path=None):
- """Injected into config file namespace as load_subconfig"""
- if path is None:
- path = self.path
-
- loader = self.__class__(fname, path)
- try:
- sub_config = loader.load_config()
- except ConfigFileNotFound:
- # Pass silently if the sub config is not there,
- # treat it as an empty config file.
- pass
- else:
- self.config.merge(sub_config)
-
- def _read_file_as_dict(self):
- """Load the config file into self.config, with recursive loading."""
- def get_config():
- """Unnecessary now, but a deprecation warning is more trouble than it's worth."""
- return self.config
-
- namespace = dict(
- c=self.config,
- load_subconfig=self.load_subconfig,
- get_config=get_config,
- __file__=self.full_filename,
- )
+class PyFileConfigLoader(FileConfigLoader):
+ """A config loader for pure python files.
+
+ This is responsible for locating a Python config file by filename and
+ path, then executing it to construct a Config object.
+ """
+
+ def load_config(self):
+ """Load the config from a file and return it as a Config object."""
+ self.clear()
+ try:
+ self._find_file()
+ except IOError as e:
+ raise ConfigFileNotFound(str(e))
+ self._read_file_as_dict()
+ return self.config
+
+ def load_subconfig(self, fname, path=None):
+ """Injected into config file namespace as load_subconfig"""
+ if path is None:
+ path = self.path
+
+ loader = self.__class__(fname, path)
+ try:
+ sub_config = loader.load_config()
+ except ConfigFileNotFound:
+ # Pass silently if the sub config is not there,
+ # treat it as an empty config file.
+ pass
+ else:
+ self.config.merge(sub_config)
+
+ def _read_file_as_dict(self):
+ """Load the config file into self.config, with recursive loading."""
+ def get_config():
+ """Unnecessary now, but a deprecation warning is more trouble than it's worth."""
+ return self.config
+
+ namespace = dict(
+ c=self.config,
+ load_subconfig=self.load_subconfig,
+ get_config=get_config,
+ __file__=self.full_filename,
+ )
conf_filename = self.full_filename
with open(conf_filename, 'rb') as f:
exec(compile(f.read(), conf_filename, 'exec'), namespace, namespace)
-
-
-class CommandLineConfigLoader(ConfigLoader):
- """A config loader for command line arguments.
-
- As we add more command line based loaders, the common logic should go
- here.
- """
-
+
+
+class CommandLineConfigLoader(ConfigLoader):
+ """A config loader for command line arguments.
+
+ As we add more command line based loaders, the common logic should go
+ here.
+ """
+
def _exec_config_str(self, lhs, rhs, trait=None):
- """execute self.config.<lhs> = <rhs>
+ """execute self.config.<lhs> = <rhs>
- * expands ~ with expanduser
+ * expands ~ with expanduser
* interprets value with trait if available
- """
+ """
value = rhs
if isinstance(value, DeferredConfig):
if trait:
@@ -672,41 +672,41 @@ class CommandLineConfigLoader(ConfigLoader):
value = trait.from_string(value)
else:
value = DeferredConfigString(value)
-
+
*path, key = lhs.split(".")
section = self.config
for part in path:
section = section[part]
section[key] = value
return
-
- def _load_flag(self, cfg):
- """update self.config from a flag, which can be a dict or Config"""
- if isinstance(cfg, (dict, Config)):
- # don't clobber whole config sections, update
- # each section from config:
+
+ def _load_flag(self, cfg):
+ """update self.config from a flag, which can be a dict or Config"""
+ if isinstance(cfg, (dict, Config)):
+ # don't clobber whole config sections, update
+ # each section from config:
for sec, c in cfg.items():
- self.config[sec].update(c)
- else:
- raise TypeError("Invalid flag: %r" % cfg)
-
+ self.config[sec].update(c)
+ else:
+ raise TypeError("Invalid flag: %r" % cfg)
+
# match --Class.trait keys for argparse
# matches:
# --Class.trait
# --x
# -x
-
+
class_trait_opt_pattern = re.compile(r'^\-?\-[A-Za-z][\w]*(\.[\w]+)*$')
-
+
_DOT_REPLACEMENT = "__DOT__"
_DASH_REPLACEMENT = "__DASH__"
-
-
+
+
class _KVAction(argparse.Action):
"""Custom argparse action for handling --Class.trait=x
-
+
Always
- """
+ """
def __call__(self, parser, namespace, values, option_string=None):
if isinstance(values, str):
values = [values]
@@ -718,11 +718,11 @@ class _KVAction(argparse.Action):
items = DeferredConfigList(items)
items.extend(values)
setattr(namespace, self.dest, items)
-
-
+
+
class _DefaultOptionDict(dict):
"""Like the default options dict
-
+
but acts as if all --Class.trait options are predefined
"""
def _add_kv_action(self, key):
@@ -732,31 +732,31 @@ class _DefaultOptionDict(dict):
# use metavar for display purposes
metavar=key.lstrip("-"),
)
-
+
def __contains__(self, key):
if '=' in key:
return False
if super().__contains__(key):
return True
-
+
if key.startswith("-") and class_trait_opt_pattern.match(key):
self._add_kv_action(key)
return True
return False
-
+
def __getitem__(self, key):
if key in self:
return super().__getitem__(key)
else:
raise KeyError(key)
-
+
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
-
-
+
+
class _KVArgParser(argparse.ArgumentParser):
"""subclass of ArgumentParser where any --Class.trait option is implicitly defined"""
def parse_known_args(self, args=None, namespace=None):
@@ -766,23 +766,23 @@ class _KVArgParser(argparse.ArgumentParser):
container._option_string_actions = _DefaultOptionDict(
container._option_string_actions)
return super().parse_known_args(args, namespace)
-
-
-class ArgParseConfigLoader(CommandLineConfigLoader):
- """A loader that uses the argparse module to load from the command line."""
-
+
+
+class ArgParseConfigLoader(CommandLineConfigLoader):
+ """A loader that uses the argparse module to load from the command line."""
+
parser_class = ArgumentParser
def __init__(self, argv=None, aliases=None, flags=None, log=None, classes=(),
*parser_args, **parser_kw):
- """Create a config loader for use with argparse.
-
- Parameters
- ----------
+ """Create a config loader for use with argparse.
+
+ Parameters
+ ----------
classes : optional, list
The classes to scan for *container* config-traits and decide
for their "multiplicity" when adding them as *argparse* arguments.
- argv : optional, list
+ argv : optional, list
If given, used to read command-line arguments from, otherwise
sys.argv[1:] is used.
*parser_args : tuple
@@ -797,39 +797,39 @@ class ArgParseConfigLoader(CommandLineConfigLoader):
Dict of flags to full traitlests names for CLI parsing
log
Passed to `ConfigLoader`
-
- Returns
- -------
- config : Config
- The resulting Config object.
- """
- super(CommandLineConfigLoader, self).__init__(log=log)
- self.clear()
- if argv is None:
- argv = sys.argv[1:]
- self.argv = argv
- self.aliases = aliases or {}
- self.flags = flags or {}
+
+ Returns
+ -------
+ config : Config
+ The resulting Config object.
+ """
+ super(CommandLineConfigLoader, self).__init__(log=log)
+ self.clear()
+ if argv is None:
+ argv = sys.argv[1:]
+ self.argv = argv
+ self.aliases = aliases or {}
+ self.flags = flags or {}
self.classes = classes
-
- self.parser_args = parser_args
- self.version = parser_kw.pop("version", None)
- kwargs = dict(argument_default=argparse.SUPPRESS)
- kwargs.update(parser_kw)
- self.parser_kw = kwargs
-
+
+ self.parser_args = parser_args
+ self.version = parser_kw.pop("version", None)
+ kwargs = dict(argument_default=argparse.SUPPRESS)
+ kwargs.update(parser_kw)
+ self.parser_kw = kwargs
+
def load_config(self, argv=None, aliases=None, flags=_deprecated, classes=None):
- """Parse command line arguments and return as a Config object.
-
- Parameters
- ----------
+ """Parse command line arguments and return as a Config object.
+
+ Parameters
+ ----------
argv : optional, list
If given, a list with the structure of sys.argv[1:] to parse
arguments from. If not given, the instance's self.argv attribute
(given at construction time) is used.
flags
Deprecated in traitlets 5.0, instanciate the config loader with the flags.
-
+
"""
if flags is not _deprecated:
@@ -840,35 +840,35 @@ class ArgParseConfigLoader(CommandLineConfigLoader):
stacklevel=2,
)
- self.clear()
- if argv is None:
- argv = self.argv
+ self.clear()
+ if argv is None:
+ argv = self.argv
if aliases is not None:
self.aliases = aliases
if classes is not None:
self.classes = classes
self._create_parser()
- self._parse_args(argv)
- self._convert_to_config()
- return self.config
-
- def get_extra_args(self):
- if hasattr(self, 'extra_args'):
- return self.extra_args
- else:
- return []
-
+ self._parse_args(argv)
+ self._convert_to_config()
+ return self.config
+
+ def get_extra_args(self):
+ if hasattr(self, 'extra_args'):
+ return self.extra_args
+ else:
+ return []
+
def _create_parser(self):
self.parser = self.parser_class(*self.parser_args, **self.parser_kw)
self._add_arguments(self.aliases, self.flags, self.classes)
-
+
def _add_arguments(self, aliases, flags, classes):
- raise NotImplementedError("subclasses must implement _add_arguments")
-
- def _parse_args(self, args):
- """self.parser->self.parsed_data"""
+ raise NotImplementedError("subclasses must implement _add_arguments")
+
+ def _parse_args(self, args):
+ """self.parser->self.parsed_data"""
uargs = [cast_unicode(a) for a in args]
-
+
unpacked_aliases = {}
if self.aliases:
unpacked_aliases = {}
@@ -908,15 +908,15 @@ class ArgParseConfigLoader(CommandLineConfigLoader):
self.parsed_data = self.parser.parse_args(to_parse)
self.extra_args = extra_args
- def _convert_to_config(self):
- """self.parsed_data->self.config"""
+ def _convert_to_config(self):
+ """self.parsed_data->self.config"""
for k, v in vars(self.parsed_data).items():
*path, key = k.split(".")
section = self.config
for p in path:
section = section[p]
setattr(section, key, v)
-
+
class _FlagAction(argparse.Action):
"""ArgParse action to handle a flag"""
@@ -937,9 +937,9 @@ class _FlagAction(argparse.Action):
setattr(namespace, self.alias, values)
-class KVArgParseConfigLoader(ArgParseConfigLoader):
- """A config loader that loads aliases and flags with argparse,
-
+class KVArgParseConfigLoader(ArgParseConfigLoader):
+ """A config loader that loads aliases and flags with argparse,
+
as well as arbitrary --Class.trait value
"""
@@ -947,10 +947,10 @@ class KVArgParseConfigLoader(ArgParseConfigLoader):
def _add_arguments(self, aliases, flags, classes):
alias_flags = {}
- paa = self.parser.add_argument
+ paa = self.parser.add_argument
self.parser.set_defaults(_flags=[])
paa("extra_args", nargs="*")
-
+
## An index of all container traits collected::
#
# { <traitname>: (<trait>, <argparse-kwds>) }
@@ -1010,10 +1010,10 @@ class KVArgParseConfigLoader(ArgParseConfigLoader):
keys = ('-' + key, '--' + key) if len(key) == 1 else ('--'+ key,)
paa(*keys, **argparse_kwds)
- def _convert_to_config(self):
- """self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
+ def _convert_to_config(self):
+ """self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
extra_args = self.extra_args
-
+
for lhs, rhs in vars(self.parsed_data).items():
if lhs == "extra_args":
self.extra_args = ["-" if a == _DASH_REPLACEMENT else a for a in rhs] + extra_args
@@ -1021,7 +1021,7 @@ class KVArgParseConfigLoader(ArgParseConfigLoader):
elif lhs == '_flags':
# _flags will be handled later
continue
-
+
lhs = lhs.replace(_DOT_REPLACEMENT, ".")
if '.' not in lhs:
# probably a mistyped alias, but not technically illegal
@@ -1048,12 +1048,12 @@ class KVArgParseConfigLoader(ArgParseConfigLoader):
raise ArgumentError(f"Error loading argument {lhs}={rhs}, {e}")
for subc in self.parsed_data._flags:
- self._load_flag(subc)
-
-
+ self._load_flag(subc)
+
+
class KeyValueConfigLoader(KVArgParseConfigLoader):
"""Deprecated in traitlets 5.0
-
+
Use KVArgParseConfigLoader
"""
def __init__(self, *args, **kwargs):
@@ -1066,25 +1066,25 @@ class KeyValueConfigLoader(KVArgParseConfigLoader):
super().__init__(*args, **kwargs)
-def load_pyconfig_files(config_files, path):
- """Load multiple Python config files, merging each of them in turn.
-
- Parameters
+def load_pyconfig_files(config_files, path):
+ """Load multiple Python config files, merging each of them in turn.
+
+ Parameters
----------
- config_files : list of str
- List of config files names to load and merge into the config.
- path : unicode
- The full path to the location of the config files.
- """
- config = Config()
- for cf in config_files:
- loader = PyFileConfigLoader(cf, path=path)
- try:
- next_config = loader.load_config()
- except ConfigFileNotFound:
- pass
- except:
- raise
- else:
- config.merge(next_config)
- return config
+ config_files : list of str
+ List of config files names to load and merge into the config.
+ path : unicode
+ The full path to the location of the config files.
+ """
+ config = Config()
+ for cf in config_files:
+ loader = PyFileConfigLoader(cf, path=path)
+ try:
+ next_config = loader.load_config()
+ except ConfigFileNotFound:
+ pass
+ except:
+ raise
+ else:
+ config.merge(next_config)
+ return config
diff --git a/contrib/python/traitlets/py3/traitlets/config/manager.py b/contrib/python/traitlets/py3/traitlets/config/manager.py
index 041477b1b9..164053261e 100644
--- a/contrib/python/traitlets/py3/traitlets/config/manager.py
+++ b/contrib/python/traitlets/py3/traitlets/config/manager.py
@@ -1,84 +1,84 @@
-"""Manager to read and modify config data in JSON files.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-import errno
-import io
-import json
-import os
-
-from traitlets.config import LoggingConfigurable
-from traitlets.traitlets import Unicode
-
-
-def recursive_update(target, new):
- """Recursively update one dictionary using another.
-
- None values will delete their keys.
- """
- for k, v in new.items():
- if isinstance(v, dict):
- if k not in target:
- target[k] = {}
- recursive_update(target[k], v)
- if not target[k]:
- # Prune empty subdicts
- del target[k]
-
- elif v is None:
- target.pop(k, None)
-
- else:
- target[k] = v
-
-
-class BaseJSONConfigManager(LoggingConfigurable):
- """General JSON config manager
-
- Deals with persisting/storing config in a json file
- """
-
- config_dir = Unicode('.')
-
- def ensure_config_dir_exists(self):
- try:
- os.makedirs(self.config_dir, 0o755)
- except OSError as e:
- if e.errno != errno.EEXIST:
- raise
-
- def file_name(self, section_name):
- return os.path.join(self.config_dir, section_name+'.json')
-
- def get(self, section_name):
- """Retrieve the config data for the specified section.
-
- Returns the data as a dictionary, or an empty dictionary if the file
- doesn't exist.
- """
- filename = self.file_name(section_name)
- if os.path.isfile(filename):
- with io.open(filename, encoding='utf-8') as f:
- return json.load(f)
- else:
- return {}
-
- def set(self, section_name, data):
- """Store the given config data.
- """
- filename = self.file_name(section_name)
- self.ensure_config_dir_exists()
-
+"""Manager to read and modify config data in JSON files.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+import errno
+import io
+import json
+import os
+
+from traitlets.config import LoggingConfigurable
+from traitlets.traitlets import Unicode
+
+
+def recursive_update(target, new):
+ """Recursively update one dictionary using another.
+
+ None values will delete their keys.
+ """
+ for k, v in new.items():
+ if isinstance(v, dict):
+ if k not in target:
+ target[k] = {}
+ recursive_update(target[k], v)
+ if not target[k]:
+ # Prune empty subdicts
+ del target[k]
+
+ elif v is None:
+ target.pop(k, None)
+
+ else:
+ target[k] = v
+
+
+class BaseJSONConfigManager(LoggingConfigurable):
+ """General JSON config manager
+
+ Deals with persisting/storing config in a json file
+ """
+
+ config_dir = Unicode('.')
+
+ def ensure_config_dir_exists(self):
+ try:
+ os.makedirs(self.config_dir, 0o755)
+ except OSError as e:
+ if e.errno != errno.EEXIST:
+ raise
+
+ def file_name(self, section_name):
+ return os.path.join(self.config_dir, section_name+'.json')
+
+ def get(self, section_name):
+ """Retrieve the config data for the specified section.
+
+ Returns the data as a dictionary, or an empty dictionary if the file
+ doesn't exist.
+ """
+ filename = self.file_name(section_name)
+ if os.path.isfile(filename):
+ with io.open(filename, encoding='utf-8') as f:
+ return json.load(f)
+ else:
+ return {}
+
+ def set(self, section_name, data):
+ """Store the given config data.
+ """
+ filename = self.file_name(section_name)
+ self.ensure_config_dir_exists()
+
f = open(filename, 'w', encoding='utf-8')
- with f:
- json.dump(data, f, indent=2)
-
- def update(self, section_name, new_data):
- """Modify the config section by recursively updating it with new_data.
-
- Returns the modified config data as a dictionary.
- """
- data = self.get(section_name)
- recursive_update(data, new_data)
- self.set(section_name, data)
- return data
+ with f:
+ json.dump(data, f, indent=2)
+
+ def update(self, section_name, new_data):
+ """Modify the config section by recursively updating it with new_data.
+
+ Returns the modified config data as a dictionary.
+ """
+ data = self.get(section_name)
+ recursive_update(data, new_data)
+ self.set(section_name, data)
+ return data
diff --git a/contrib/python/traitlets/py3/traitlets/log.py b/contrib/python/traitlets/py3/traitlets/log.py
index 559735bd1a..af86b325f5 100644
--- a/contrib/python/traitlets/py3/traitlets/log.py
+++ b/contrib/python/traitlets/py3/traitlets/log.py
@@ -1,27 +1,27 @@
-"""Grab the global logger instance."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import logging
-
-_logger = None
-
-def get_logger():
- """Grab the global logger instance.
+"""Grab the global logger instance."""
- If a global Application is instantiated, grab its logger.
- Otherwise, grab the root logger.
- """
- global _logger
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
- if _logger is None:
- from .config import Application
- if Application.initialized():
- _logger = Application.instance().log
- else:
+import logging
+
+_logger = None
+
+def get_logger():
+ """Grab the global logger instance.
+
+ If a global Application is instantiated, grab its logger.
+ Otherwise, grab the root logger.
+ """
+ global _logger
+
+ if _logger is None:
+ from .config import Application
+ if Application.initialized():
+ _logger = Application.instance().log
+ else:
_logger = logging.getLogger('traitlets')
# Add a NullHandler to silence warnings about not being
# initialized, per best practice for libraries.
_logger.addHandler(logging.NullHandler())
- return _logger
+ return _logger
diff --git a/contrib/python/traitlets/py3/traitlets/traitlets.py b/contrib/python/traitlets/py3/traitlets/traitlets.py
index 1a278992a3..6bdf7414d3 100644
--- a/contrib/python/traitlets/py3/traitlets/traitlets.py
+++ b/contrib/python/traitlets/py3/traitlets/traitlets.py
@@ -1,62 +1,62 @@
-"""
-A lightweight Traits like module.
-
-This is designed to provide a lightweight, simple, pure Python version of
-many of the capabilities of enthought.traits. This includes:
-
-* Validation
-* Type specification with defaults
-* Static and dynamic notification
-* Basic predefined types
-* An API that is similar to enthought.traits
-
-We don't support:
-
-* Delegation
-* Automatic GUI generation
-* A full set of trait types. Most importantly, we don't provide container
- traits (list, dict, tuple) that can trigger notifications if their
- contents change.
-* API compatibility with enthought.traits
-
-There are also some important difference in our design:
-
-* enthought.traits does not validate default values. We do.
-
-We choose to create this module because we need these capabilities, but
-we need them to be pure Python so they work in all Python implementations,
-including Jython and IronPython.
-
-Inheritance diagram:
-
-.. inheritance-diagram:: traitlets.traitlets
- :parts: 3
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-#
-# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
-# also under the terms of the Modified BSD License.
-
+"""
+A lightweight Traits like module.
+
+This is designed to provide a lightweight, simple, pure Python version of
+many of the capabilities of enthought.traits. This includes:
+
+* Validation
+* Type specification with defaults
+* Static and dynamic notification
+* Basic predefined types
+* An API that is similar to enthought.traits
+
+We don't support:
+
+* Delegation
+* Automatic GUI generation
+* A full set of trait types. Most importantly, we don't provide container
+ traits (list, dict, tuple) that can trigger notifications if their
+ contents change.
+* API compatibility with enthought.traits
+
+There are also some important difference in our design:
+
+* enthought.traits does not validate default values. We do.
+
+We choose to create this module because we need these capabilities, but
+we need them to be pure Python so they work in all Python implementations,
+including Jython and IronPython.
+
+Inheritance diagram:
+
+.. inheritance-diagram:: traitlets.traitlets
+ :parts: 3
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+#
+# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
+# also under the terms of the Modified BSD License.
+
from ast import literal_eval
-import contextlib
-import inspect
+import contextlib
+import inspect
import os
-import re
-import sys
-import types
+import re
+import sys
+import types
import enum
-from warnings import warn, warn_explicit
-
-from .utils.getargspec import getargspec
-from .utils.importstring import import_item
-from .utils.sentinel import Sentinel
+from warnings import warn, warn_explicit
+
+from .utils.getargspec import getargspec
+from .utils.importstring import import_item
+from .utils.sentinel import Sentinel
from .utils.bunch import Bunch
from .utils.descriptions import describe, class_of, add_article, repr_type
-
-SequenceTypes = (list, tuple, set, frozenset)
-
+
+SequenceTypes = (list, tuple, set, frozenset)
+
# backward compatibility, use to differ between Python 2 and 3.
ClassTypes = (type,)
@@ -85,34 +85,34 @@ __all__ = [
# any TraitType subclass (that doesn't start with _) will be added automatically
-#-----------------------------------------------------------------------------
-# Basic classes
-#-----------------------------------------------------------------------------
-
-
-Undefined = Sentinel('Undefined', 'traitlets',
-'''
-Used in Traitlets to specify that no defaults are set in kwargs
-'''
-)
-
-All = Sentinel('All', 'traitlets',
-'''
-Used in Traitlets to listen to all types of notification or to notifications
-from all trait attributes.
-'''
-)
-
-# Deprecated alias
-NoDefaultSpecified = Undefined
-
-class TraitError(Exception):
- pass
-
-#-----------------------------------------------------------------------------
-# Utilities
-#-----------------------------------------------------------------------------
-
+#-----------------------------------------------------------------------------
+# Basic classes
+#-----------------------------------------------------------------------------
+
+
+Undefined = Sentinel('Undefined', 'traitlets',
+'''
+Used in Traitlets to specify that no defaults are set in kwargs
+'''
+)
+
+All = Sentinel('All', 'traitlets',
+'''
+Used in Traitlets to listen to all types of notification or to notifications
+from all trait attributes.
+'''
+)
+
+# Deprecated alias
+NoDefaultSpecified = Undefined
+
+class TraitError(Exception):
+ pass
+
+#-----------------------------------------------------------------------------
+# Utilities
+#-----------------------------------------------------------------------------
+
_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
def isidentifier(s):
@@ -134,332 +134,332 @@ def _should_warn(key):
else:
return False
-def _deprecated_method(method, cls, method_name, msg):
- """Show deprecation warning about a magic method definition.
-
- Uses warn_explicit to bind warning to method definition instead of triggering code,
- which isn't relevant.
- """
+def _deprecated_method(method, cls, method_name, msg):
+ """Show deprecation warning about a magic method definition.
+
+ Uses warn_explicit to bind warning to method definition instead of triggering code,
+ which isn't relevant.
+ """
warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format(
- classname=cls.__name__, method_name=method_name, msg=msg
- )
-
- for parent in inspect.getmro(cls):
- if method_name in parent.__dict__:
- cls = parent
- break
+ classname=cls.__name__, method_name=method_name, msg=msg
+ )
+
+ for parent in inspect.getmro(cls):
+ if method_name in parent.__dict__:
+ cls = parent
+ break
# limit deprecation messages to once per package
package_name = cls.__module__.split('.', 1)[0]
key = (package_name, msg)
if not _should_warn(key):
return
- try:
- fname = inspect.getsourcefile(method) or "<unknown>"
- lineno = inspect.getsourcelines(method)[1] or 0
+ try:
+ fname = inspect.getsourcefile(method) or "<unknown>"
+ lineno = inspect.getsourcelines(method)[1] or 0
except (OSError, TypeError) as e:
- # Failed to inspect for some reason
- warn(warn_msg + ('\n(inspection failed) %s' % e), DeprecationWarning)
- else:
- warn_explicit(warn_msg, DeprecationWarning, fname, lineno)
-
+ # Failed to inspect for some reason
+ warn(warn_msg + ('\n(inspection failed) %s' % e), DeprecationWarning)
+ else:
+ warn_explicit(warn_msg, DeprecationWarning, fname, lineno)
+
def _safe_literal_eval(s):
"""Safely evaluate an expression
-
+
Returns original string if eval fails.
-
+
Use only where types are ambiguous.
- """
+ """
try:
return literal_eval(s)
except (NameError, SyntaxError, ValueError):
return s
-
-def is_trait(t):
- """ Returns whether the given value is an instance or subclass of TraitType.
- """
- return (isinstance(t, TraitType) or
- (isinstance(t, type) and issubclass(t, TraitType)))
-
-
-def parse_notifier_name(names):
- """Convert the name argument to a list of names.
-
- Examples
- --------
- >>> parse_notifier_name([])
- [All]
+
+def is_trait(t):
+ """ Returns whether the given value is an instance or subclass of TraitType.
+ """
+ return (isinstance(t, TraitType) or
+ (isinstance(t, type) and issubclass(t, TraitType)))
+
+
+def parse_notifier_name(names):
+ """Convert the name argument to a list of names.
+
+ Examples
+ --------
+ >>> parse_notifier_name([])
+ [All]
>>> parse_notifier_name("a")
- ['a']
+ ['a']
>>> parse_notifier_name(["a", "b"])
- ['a', 'b']
- >>> parse_notifier_name(All)
- [All]
- """
+ ['a', 'b']
+ >>> parse_notifier_name(All)
+ [All]
+ """
if names is All or isinstance(names, str):
- return [names]
+ return [names]
else:
- if not names or All in names:
- return [All]
- for n in names:
+ if not names or All in names:
+ return [All]
+ for n in names:
if not isinstance(n, str):
raise TypeError("names must be strings, not %r" % n)
- return names
-
-
-class _SimpleTest:
- def __init__ ( self, value ): self.value = value
- def __call__ ( self, test ):
- return test == self.value
- def __repr__(self):
- return "<SimpleTest(%r)" % self.value
- def __str__(self):
- return self.__repr__()
-
-
-def getmembers(object, predicate=None):
- """A safe version of inspect.getmembers that handles missing attributes.
-
- This is useful when there are descriptor based attributes that for
- some reason raise AttributeError even though they exist. This happens
- in zope.inteface with the __provides__ attribute.
- """
- results = []
- for key in dir(object):
- try:
- value = getattr(object, key)
- except AttributeError:
- pass
- else:
- if not predicate or predicate(value):
- results.append((key, value))
- results.sort()
- return results
-
-def _validate_link(*tuples):
- """Validate arguments for traitlet link functions"""
- for t in tuples:
- if not len(t) == 2:
- raise TypeError("Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t)
- obj, trait_name = t
- if not isinstance(obj, HasTraits):
- raise TypeError("Each object must be HasTraits, not %r" % type(obj))
- if not trait_name in obj.traits():
- raise TypeError("%r has no trait %r" % (obj, trait_name))
-
-class link(object):
- """Link traits from different objects together so they remain in sync.
-
- Parameters
- ----------
- source : (object / attribute name) pair
- target : (object / attribute name) pair
+ return names
+
+
+class _SimpleTest:
+ def __init__ ( self, value ): self.value = value
+ def __call__ ( self, test ):
+ return test == self.value
+ def __repr__(self):
+ return "<SimpleTest(%r)" % self.value
+ def __str__(self):
+ return self.__repr__()
+
+
+def getmembers(object, predicate=None):
+ """A safe version of inspect.getmembers that handles missing attributes.
+
+ This is useful when there are descriptor based attributes that for
+ some reason raise AttributeError even though they exist. This happens
+ in zope.inteface with the __provides__ attribute.
+ """
+ results = []
+ for key in dir(object):
+ try:
+ value = getattr(object, key)
+ except AttributeError:
+ pass
+ else:
+ if not predicate or predicate(value):
+ results.append((key, value))
+ results.sort()
+ return results
+
+def _validate_link(*tuples):
+ """Validate arguments for traitlet link functions"""
+ for t in tuples:
+ if not len(t) == 2:
+ raise TypeError("Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t)
+ obj, trait_name = t
+ if not isinstance(obj, HasTraits):
+ raise TypeError("Each object must be HasTraits, not %r" % type(obj))
+ if not trait_name in obj.traits():
+ raise TypeError("%r has no trait %r" % (obj, trait_name))
+
+class link(object):
+ """Link traits from different objects together so they remain in sync.
+
+ Parameters
+ ----------
+ source : (object / attribute name) pair
+ target : (object / attribute name) pair
transform: iterable with two callables (optional)
Data transformation between source and target and target and source.
-
- Examples
- --------
+
+ Examples
+ --------
>>> c = link((src, "value"), (tgt, "value"))
- >>> src.value = 5 # updates other objects as well
- """
- updating = False
-
+ >>> src.value = 5 # updates other objects as well
+ """
+ updating = False
+
def __init__(self, source, target, transform=None):
- _validate_link(source, target)
- self.source, self.target = source, target
+ _validate_link(source, target)
+ self.source, self.target = source, target
self._transform, self._transform_inv = (
transform if transform else (lambda x: x,) * 2)
self.link()
def link(self):
- try:
+ try:
setattr(self.target[0], self.target[1],
self._transform(getattr(self.source[0], self.source[1])))
- finally:
+ finally:
self.source[0].observe(self._update_target, names=self.source[1])
self.target[0].observe(self._update_source, names=self.target[1])
-
- @contextlib.contextmanager
- def _busy_updating(self):
- self.updating = True
- try:
- yield
- finally:
- self.updating = False
-
- def _update_target(self, change):
- if self.updating:
- return
- with self._busy_updating():
+
+ @contextlib.contextmanager
+ def _busy_updating(self):
+ self.updating = True
+ try:
+ yield
+ finally:
+ self.updating = False
+
+ def _update_target(self, change):
+ if self.updating:
+ return
+ with self._busy_updating():
setattr(self.target[0], self.target[1], self._transform(change.new))
if getattr(self.source[0], self.source[1]) != change.new:
raise TraitError(
"Broken link {}: the source value changed while updating "
"the target.".format(self))
-
- def _update_source(self, change):
- if self.updating:
- return
- with self._busy_updating():
+
+ def _update_source(self, change):
+ if self.updating:
+ return
+ with self._busy_updating():
setattr(self.source[0], self.source[1],
self._transform_inv(change.new))
if getattr(self.target[0], self.target[1]) != change.new:
raise TraitError(
"Broken link {}: the target value changed while updating "
"the source.".format(self))
-
- def unlink(self):
- self.source[0].unobserve(self._update_target, names=self.source[1])
- self.target[0].unobserve(self._update_source, names=self.target[1])
-
-
-class directional_link(object):
- """Link the trait of a source object with traits of target objects.
-
- Parameters
- ----------
- source : (object, attribute name) pair
- target : (object, attribute name) pair
- transform: callable (optional)
- Data transformation between source and target.
-
- Examples
- --------
+
+ def unlink(self):
+ self.source[0].unobserve(self._update_target, names=self.source[1])
+ self.target[0].unobserve(self._update_source, names=self.target[1])
+
+
+class directional_link(object):
+ """Link the trait of a source object with traits of target objects.
+
+ Parameters
+ ----------
+ source : (object, attribute name) pair
+ target : (object, attribute name) pair
+ transform: callable (optional)
+ Data transformation between source and target.
+
+ Examples
+ --------
>>> c = directional_link((src, "value"), (tgt, "value"))
- >>> src.value = 5 # updates target objects
- >>> tgt.value = 6 # does not update source object
- """
- updating = False
-
- def __init__(self, source, target, transform=None):
- self._transform = transform if transform else lambda x: x
- _validate_link(source, target)
- self.source, self.target = source, target
+ >>> src.value = 5 # updates target objects
+ >>> tgt.value = 6 # does not update source object
+ """
+ updating = False
+
+ def __init__(self, source, target, transform=None):
+ self._transform = transform if transform else lambda x: x
+ _validate_link(source, target)
+ self.source, self.target = source, target
self.link()
def link(self):
- try:
+ try:
setattr(self.target[0], self.target[1],
self._transform(getattr(self.source[0], self.source[1])))
- finally:
- self.source[0].observe(self._update, names=self.source[1])
-
- @contextlib.contextmanager
- def _busy_updating(self):
- self.updating = True
- try:
- yield
- finally:
- self.updating = False
-
- def _update(self, change):
- if self.updating:
- return
- with self._busy_updating():
- setattr(self.target[0], self.target[1],
+ finally:
+ self.source[0].observe(self._update, names=self.source[1])
+
+ @contextlib.contextmanager
+ def _busy_updating(self):
+ self.updating = True
+ try:
+ yield
+ finally:
+ self.updating = False
+
+ def _update(self, change):
+ if self.updating:
+ return
+ with self._busy_updating():
+ setattr(self.target[0], self.target[1],
self._transform(change.new))
-
- def unlink(self):
- self.source[0].unobserve(self._update, names=self.source[1])
-
-dlink = directional_link
-
-
-#-----------------------------------------------------------------------------
+
+ def unlink(self):
+ self.source[0].unobserve(self._update, names=self.source[1])
+
+dlink = directional_link
+
+
+#-----------------------------------------------------------------------------
# Base Descriptor Class
-#-----------------------------------------------------------------------------
-
-
-class BaseDescriptor(object):
- """Base descriptor class
-
- Notes
- -----
+#-----------------------------------------------------------------------------
+
+
+class BaseDescriptor(object):
+ """Base descriptor class
+
+ Notes
+ -----
This implements Python's descriptor protocol.
-
- This class is the base class for all such descriptors. The
- only magic we use is a custom metaclass for the main :class:`HasTraits`
- class that does the following:
-
- 1. Sets the :attr:`name` attribute of every :class:`BaseDescriptor`
- instance in the class dict to the name of the attribute.
- 2. Sets the :attr:`this_class` attribute of every :class:`BaseDescriptor`
- instance in the class dict to the *class* that declared the trait.
- This is used by the :class:`This` trait to allow subclasses to
- accept superclasses for :class:`This` values.
- """
-
- name = None
- this_class = None
-
- def class_init(self, cls, name):
- """Part of the initialization which may depend on the underlying
- HasDescriptors class.
-
- It is typically overloaded for specific types.
-
- This method is called by :meth:`MetaHasDescriptors.__init__`
- passing the class (`cls`) and `name` under which the descriptor
- has been assigned.
- """
- self.this_class = cls
- self.name = name
-
+
+ This class is the base class for all such descriptors. The
+ only magic we use is a custom metaclass for the main :class:`HasTraits`
+ class that does the following:
+
+ 1. Sets the :attr:`name` attribute of every :class:`BaseDescriptor`
+ instance in the class dict to the name of the attribute.
+ 2. Sets the :attr:`this_class` attribute of every :class:`BaseDescriptor`
+ instance in the class dict to the *class* that declared the trait.
+ This is used by the :class:`This` trait to allow subclasses to
+ accept superclasses for :class:`This` values.
+ """
+
+ name = None
+ this_class = None
+
+ def class_init(self, cls, name):
+ """Part of the initialization which may depend on the underlying
+ HasDescriptors class.
+
+ It is typically overloaded for specific types.
+
+ This method is called by :meth:`MetaHasDescriptors.__init__`
+ passing the class (`cls`) and `name` under which the descriptor
+ has been assigned.
+ """
+ self.this_class = cls
+ self.name = name
+
def subclass_init(self, cls):
pass
- def instance_init(self, obj):
- """Part of the initialization which may depend on the underlying
- HasDescriptors instance.
-
- It is typically overloaded for specific types.
-
- This method is called by :meth:`HasTraits.__new__` and in the
- :meth:`BaseDescriptor.instance_init` method of descriptors holding
- other descriptors.
- """
- pass
-
-
-class TraitType(BaseDescriptor):
- """A base class for all trait types.
- """
-
- metadata = {}
- allow_none = False
- read_only = False
- info_text = 'any value'
+ def instance_init(self, obj):
+ """Part of the initialization which may depend on the underlying
+ HasDescriptors instance.
+
+ It is typically overloaded for specific types.
+
+ This method is called by :meth:`HasTraits.__new__` and in the
+ :meth:`BaseDescriptor.instance_init` method of descriptors holding
+ other descriptors.
+ """
+ pass
+
+
+class TraitType(BaseDescriptor):
+ """A base class for all trait types.
+ """
+
+ metadata = {}
+ allow_none = False
+ read_only = False
+ info_text = 'any value'
default_value = Undefined
-
+
def __init__(self, default_value=Undefined, allow_none=False, read_only=None, help=None,
config=None, **kwargs):
- """Declare a traitlet.
-
- If *allow_none* is True, None is a valid value in addition to any
- values that are normally valid. The default is up to the subclass.
- For most trait types, the default value for ``allow_none`` is False.
+ """Declare a traitlet.
+
+ If *allow_none* is True, None is a valid value in addition to any
+ values that are normally valid. The default is up to the subclass.
+ For most trait types, the default value for ``allow_none`` is False.
If *read_only* is True, attempts to directly modify a trait attribute raises a TraitError.
- Extra metadata can be associated with the traitlet using the .tag() convenience method
- or by using the traitlet instance's .metadata dictionary.
- """
- if default_value is not Undefined:
- self.default_value = default_value
+ Extra metadata can be associated with the traitlet using the .tag() convenience method
+ or by using the traitlet instance's .metadata dictionary.
+ """
+ if default_value is not Undefined:
+ self.default_value = default_value
if allow_none:
- self.allow_none = allow_none
- if read_only is not None:
- self.read_only = read_only
- self.help = help if help is not None else ''
-
+ self.allow_none = allow_none
+ if read_only is not None:
+ self.read_only = read_only
+ self.help = help if help is not None else ''
+
if len(kwargs) > 0:
- stacklevel = 1
- f = inspect.currentframe()
- # count supers to determine stacklevel for warning
- while f.f_code.co_name == '__init__':
- stacklevel += 1
- f = f.f_back
+ stacklevel = 1
+ f = inspect.currentframe()
+ # count supers to determine stacklevel for warning
+ while f.f_code.co_name == '__init__':
+ stacklevel += 1
+ f = f.f_back
mod = f.f_globals.get('__name__') or ''
pkg = mod.split('.', 1)[0]
key = tuple(['metadata-tag', pkg] + sorted(kwargs))
@@ -468,21 +468,21 @@ class TraitType(BaseDescriptor):
"With traitlets 4.1, metadata should be set using the .tag() method, "
"e.g., Int().tag(key1='value1', key2='value2')" % (kwargs,),
DeprecationWarning, stacklevel=stacklevel)
- if len(self.metadata) > 0:
- self.metadata = self.metadata.copy()
+ if len(self.metadata) > 0:
+ self.metadata = self.metadata.copy()
self.metadata.update(kwargs)
- else:
+ else:
self.metadata = kwargs
- else:
- self.metadata = self.metadata.copy()
+ else:
+ self.metadata = self.metadata.copy()
if config is not None:
self.metadata['config'] = config
-
- # We add help to the metadata during a deprecation period so that
- # code that looks for the help string there can find it.
- if help is not None:
- self.metadata['help'] = help
-
+
+ # We add help to the metadata during a deprecation period so that
+ # code that looks for the help string there can find it.
+ if help is not None:
+ self.metadata['help'] = help
+
def from_string(self, s):
"""Get a value from a config string
@@ -515,28 +515,28 @@ class TraitType(BaseDescriptor):
# Undefined will raise in TraitType.get
return self.default_value
- def get_default_value(self):
- """DEPRECATED: Retrieve the static default value for this trait.
- Use self.default_value instead
- """
+ def get_default_value(self):
+ """DEPRECATED: Retrieve the static default value for this trait.
+ Use self.default_value instead
+ """
warn("get_default_value is deprecated in traitlets 4.0: use the .default_value attribute", DeprecationWarning,
- stacklevel=2)
- return self.default_value
-
- def init_default_value(self, obj):
- """DEPRECATED: Set the static default value for the trait type.
- """
+ stacklevel=2)
+ return self.default_value
+
+ def init_default_value(self, obj):
+ """DEPRECATED: Set the static default value for the trait type.
+ """
warn("init_default_value is deprecated in traitlets 4.0, and may be removed in the future", DeprecationWarning,
- stacklevel=2)
- value = self._validate(obj, self.default_value)
- obj._trait_values[self.name] = value
- return value
-
+ stacklevel=2)
+ value = self._validate(obj, self.default_value)
+ obj._trait_values[self.name] = value
+ return value
+
def get(self, obj, cls=None):
- try:
- value = obj._trait_values[self.name]
- except KeyError:
- # Check for a dynamic initializer.
+ try:
+ value = obj._trait_values[self.name]
+ except KeyError:
+ # Check for a dynamic initializer.
default = obj.trait_defaults(self.name)
if default is Undefined:
warn(
@@ -548,93 +548,93 @@ class TraitType(BaseDescriptor):
)
with obj.cross_validation_lock:
value = self._validate(obj, default)
- obj._trait_values[self.name] = value
+ obj._trait_values[self.name] = value
obj._notify_observers(Bunch(
name=self.name,
value=value,
owner=obj,
type='default',
))
- return value
- except Exception:
- # This should never be reached.
- raise TraitError('Unexpected error in TraitType: '
- 'default value not set properly')
- else:
- return value
-
- def __get__(self, obj, cls=None):
- """Get the value of the trait by self.name for the instance.
-
- Default values are instantiated when :meth:`HasTraits.__new__`
- is called. Thus by the time this method gets called either the
- default value or a user defined value (they called :meth:`__set__`)
- is in the :class:`HasTraits` instance.
- """
- if obj is None:
- return self
- else:
- return self.get(obj, cls)
-
- def set(self, obj, value):
- new_value = self._validate(obj, value)
- try:
- old_value = obj._trait_values[self.name]
- except KeyError:
- old_value = self.default_value
-
- obj._trait_values[self.name] = new_value
- try:
- silent = bool(old_value == new_value)
+ return value
+ except Exception:
+ # This should never be reached.
+ raise TraitError('Unexpected error in TraitType: '
+ 'default value not set properly')
+ else:
+ return value
+
+ def __get__(self, obj, cls=None):
+ """Get the value of the trait by self.name for the instance.
+
+ Default values are instantiated when :meth:`HasTraits.__new__`
+ is called. Thus by the time this method gets called either the
+ default value or a user defined value (they called :meth:`__set__`)
+ is in the :class:`HasTraits` instance.
+ """
+ if obj is None:
+ return self
+ else:
+ return self.get(obj, cls)
+
+ def set(self, obj, value):
+ new_value = self._validate(obj, value)
+ try:
+ old_value = obj._trait_values[self.name]
+ except KeyError:
+ old_value = self.default_value
+
+ obj._trait_values[self.name] = new_value
+ try:
+ silent = bool(old_value == new_value)
except Exception:
- # if there is an error in comparing, default to notify
- silent = False
- if silent is not True:
- # we explicitly compare silent to True just in case the equality
- # comparison above returns something other than True/False
- obj._notify_trait(self.name, old_value, new_value)
-
- def __set__(self, obj, value):
- """Set the value of the trait by self.name for the instance.
-
- Values pass through a validation stage where errors are raised when
- impropper types, or types that cannot be coerced, are encountered.
- """
- if self.read_only:
- raise TraitError('The "%s" trait is read-only.' % self.name)
- else:
- self.set(obj, value)
-
- def _validate(self, obj, value):
- if value is None and self.allow_none:
- return value
- if hasattr(self, 'validate'):
- value = self.validate(obj, value)
- if obj._cross_validation_lock is False:
- value = self._cross_validate(obj, value)
- return value
-
- def _cross_validate(self, obj, value):
- if self.name in obj._trait_validators:
+ # if there is an error in comparing, default to notify
+ silent = False
+ if silent is not True:
+ # we explicitly compare silent to True just in case the equality
+ # comparison above returns something other than True/False
+ obj._notify_trait(self.name, old_value, new_value)
+
+ def __set__(self, obj, value):
+ """Set the value of the trait by self.name for the instance.
+
+ Values pass through a validation stage where errors are raised when
+ impropper types, or types that cannot be coerced, are encountered.
+ """
+ if self.read_only:
+ raise TraitError('The "%s" trait is read-only.' % self.name)
+ else:
+ self.set(obj, value)
+
+ def _validate(self, obj, value):
+ if value is None and self.allow_none:
+ return value
+ if hasattr(self, 'validate'):
+ value = self.validate(obj, value)
+ if obj._cross_validation_lock is False:
+ value = self._cross_validate(obj, value)
+ return value
+
+ def _cross_validate(self, obj, value):
+ if self.name in obj._trait_validators:
proposal = Bunch({'trait': self, 'value': value, 'owner': obj})
- value = obj._trait_validators[self.name](obj, proposal)
- elif hasattr(obj, '_%s_validate' % self.name):
- meth_name = '_%s_validate' % self.name
- cross_validate = getattr(obj, meth_name)
- _deprecated_method(cross_validate, obj.__class__, meth_name,
- "use @validate decorator instead.")
- value = cross_validate(value, self)
- return value
-
- def __or__(self, other):
- if isinstance(other, Union):
- return Union([self] + other.trait_types)
- else:
- return Union([self, other])
-
- def info(self):
- return self.info_text
-
+ value = obj._trait_validators[self.name](obj, proposal)
+ elif hasattr(obj, '_%s_validate' % self.name):
+ meth_name = '_%s_validate' % self.name
+ cross_validate = getattr(obj, meth_name)
+ _deprecated_method(cross_validate, obj.__class__, meth_name,
+ "use @validate decorator instead.")
+ value = cross_validate(value, self)
+ return value
+
+ def __or__(self, other):
+ if isinstance(other, Union):
+ return Union([self] + other.trait_types)
+ else:
+ return Union([self, other])
+
+ def info(self):
+ return self.info_text
+
def error(self, obj, value, error=None, info=None):
"""Raise a TraitError
@@ -676,7 +676,7 @@ class TraitType(BaseDescriptor):
"expected %s, not %s." % (self.name, chain,
error.args[1], describe("the", error.args[0])),)
raise error
- else:
+ else:
# this trait caused an error
if self.name is None:
# this is not the root trait
@@ -690,196 +690,196 @@ class TraitType(BaseDescriptor):
e = "The '%s' trait expected %s, not %s." % (
self.name, self.info(), describe("the", value))
raise TraitError(e)
-
- def get_metadata(self, key, default=None):
- """DEPRECATED: Get a metadata value.
-
- Use .metadata[key] or .metadata.get(key, default) instead.
- """
- if key == 'help':
- msg = "use the instance .help string directly, like x.help"
- else:
- msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)"
+
+ def get_metadata(self, key, default=None):
+ """DEPRECATED: Get a metadata value.
+
+ Use .metadata[key] or .metadata.get(key, default) instead.
+ """
+ if key == 'help':
+ msg = "use the instance .help string directly, like x.help"
+ else:
+ msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)"
warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
- return self.metadata.get(key, default)
-
- def set_metadata(self, key, value):
- """DEPRECATED: Set a metadata key/value.
-
- Use .metadata[key] = value instead.
- """
- if key == 'help':
- msg = "use the instance .help string directly, like x.help = value"
- else:
- msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value"
+ return self.metadata.get(key, default)
+
+ def set_metadata(self, key, value):
+ """DEPRECATED: Set a metadata key/value.
+
+ Use .metadata[key] = value instead.
+ """
+ if key == 'help':
+ msg = "use the instance .help string directly, like x.help = value"
+ else:
+ msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value"
warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
- self.metadata[key] = value
-
- def tag(self, **metadata):
- """Sets metadata and returns self.
-
- This allows convenient metadata tagging when initializing the trait, such as:
-
- >>> Int(0).tag(config=True, sync=True)
- """
+ self.metadata[key] = value
+
+ def tag(self, **metadata):
+ """Sets metadata and returns self.
+
+ This allows convenient metadata tagging when initializing the trait, such as:
+
+ >>> Int(0).tag(config=True, sync=True)
+ """
maybe_constructor_keywords = set(metadata.keys()).intersection({'help','allow_none', 'read_only', 'default_value'})
if maybe_constructor_keywords:
warn('The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s '%
maybe_constructor_keywords, UserWarning, stacklevel=2)
- self.metadata.update(metadata)
- return self
-
- def default_value_repr(self):
- return repr(self.default_value)
-
-#-----------------------------------------------------------------------------
-# The HasTraits implementation
-#-----------------------------------------------------------------------------
-
-class _CallbackWrapper(object):
- """An object adapting a on_trait_change callback into an observe callback.
-
- The comparison operator __eq__ is implemented to enable removal of wrapped
- callbacks.
- """
-
- def __init__(self, cb):
- self.cb = cb
- # Bound methods have an additional 'self' argument.
- offset = -1 if isinstance(self.cb, types.MethodType) else 0
- self.nargs = len(getargspec(cb)[0]) + offset
- if (self.nargs > 4):
- raise TraitError('a trait changed callback must have 0-4 arguments.')
-
- def __eq__(self, other):
- # The wrapper is equal to the wrapped element
- if isinstance(other, _CallbackWrapper):
- return self.cb == other.cb
- else:
- return self.cb == other
-
- def __call__(self, change):
- # The wrapper is callable
- if self.nargs == 0:
- self.cb()
- elif self.nargs == 1:
+ self.metadata.update(metadata)
+ return self
+
+ def default_value_repr(self):
+ return repr(self.default_value)
+
+#-----------------------------------------------------------------------------
+# The HasTraits implementation
+#-----------------------------------------------------------------------------
+
+class _CallbackWrapper(object):
+ """An object adapting a on_trait_change callback into an observe callback.
+
+ The comparison operator __eq__ is implemented to enable removal of wrapped
+ callbacks.
+ """
+
+ def __init__(self, cb):
+ self.cb = cb
+ # Bound methods have an additional 'self' argument.
+ offset = -1 if isinstance(self.cb, types.MethodType) else 0
+ self.nargs = len(getargspec(cb)[0]) + offset
+ if (self.nargs > 4):
+ raise TraitError('a trait changed callback must have 0-4 arguments.')
+
+ def __eq__(self, other):
+ # The wrapper is equal to the wrapped element
+ if isinstance(other, _CallbackWrapper):
+ return self.cb == other.cb
+ else:
+ return self.cb == other
+
+ def __call__(self, change):
+ # The wrapper is callable
+ if self.nargs == 0:
+ self.cb()
+ elif self.nargs == 1:
self.cb(change.name)
- elif self.nargs == 2:
+ elif self.nargs == 2:
self.cb(change.name, change.new)
- elif self.nargs == 3:
+ elif self.nargs == 3:
self.cb(change.name, change.old, change.new)
- elif self.nargs == 4:
+ elif self.nargs == 4:
self.cb(change.name, change.old, change.new, change.owner)
-
-def _callback_wrapper(cb):
- if isinstance(cb, _CallbackWrapper):
- return cb
- else:
- return _CallbackWrapper(cb)
-
-
-class MetaHasDescriptors(type):
- """A metaclass for HasDescriptors.
-
- This metaclass makes sure that any TraitType class attributes are
- instantiated and sets their name attribute.
- """
-
- def __new__(mcls, name, bases, classdict):
- """Create the HasDescriptors class."""
+
+def _callback_wrapper(cb):
+ if isinstance(cb, _CallbackWrapper):
+ return cb
+ else:
+ return _CallbackWrapper(cb)
+
+
+class MetaHasDescriptors(type):
+ """A metaclass for HasDescriptors.
+
+ This metaclass makes sure that any TraitType class attributes are
+ instantiated and sets their name attribute.
+ """
+
+ def __new__(mcls, name, bases, classdict):
+ """Create the HasDescriptors class."""
for k, v in classdict.items():
- # ----------------------------------------------------------------
- # Support of deprecated behavior allowing for TraitType types
- # to be used instead of TraitType instances.
- if inspect.isclass(v) and issubclass(v, TraitType):
+ # ----------------------------------------------------------------
+ # Support of deprecated behavior allowing for TraitType types
+ # to be used instead of TraitType instances.
+ if inspect.isclass(v) and issubclass(v, TraitType):
warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
" Passing types is deprecated in traitlets 4.1.",
- DeprecationWarning, stacklevel=2)
- classdict[k] = v()
- # ----------------------------------------------------------------
-
- return super(MetaHasDescriptors, mcls).__new__(mcls, name, bases, classdict)
-
- def __init__(cls, name, bases, classdict):
- """Finish initializing the HasDescriptors class."""
- super(MetaHasDescriptors, cls).__init__(name, bases, classdict)
- cls.setup_class(classdict)
-
- def setup_class(cls, classdict):
- """Setup descriptor instance on the class
-
- This sets the :attr:`this_class` and :attr:`name` attributes of each
- BaseDescriptor in the class dict of the newly created ``cls`` before
- calling their :attr:`class_init` method.
- """
+ DeprecationWarning, stacklevel=2)
+ classdict[k] = v()
+ # ----------------------------------------------------------------
+
+ return super(MetaHasDescriptors, mcls).__new__(mcls, name, bases, classdict)
+
+ def __init__(cls, name, bases, classdict):
+ """Finish initializing the HasDescriptors class."""
+ super(MetaHasDescriptors, cls).__init__(name, bases, classdict)
+ cls.setup_class(classdict)
+
+ def setup_class(cls, classdict):
+ """Setup descriptor instance on the class
+
+ This sets the :attr:`this_class` and :attr:`name` attributes of each
+ BaseDescriptor in the class dict of the newly created ``cls`` before
+ calling their :attr:`class_init` method.
+ """
for k, v in classdict.items():
- if isinstance(v, BaseDescriptor):
- v.class_init(cls, k)
-
+ if isinstance(v, BaseDescriptor):
+ v.class_init(cls, k)
+
for k, v in getmembers(cls):
if isinstance(v, BaseDescriptor):
v.subclass_init(cls)
-
-
-class MetaHasTraits(MetaHasDescriptors):
- """A metaclass for HasTraits."""
-
- def setup_class(cls, classdict):
- cls._trait_default_generators = {}
- super(MetaHasTraits, cls).setup_class(classdict)
-
-
+
+
+class MetaHasTraits(MetaHasDescriptors):
+ """A metaclass for HasTraits."""
+
+ def setup_class(cls, classdict):
+ cls._trait_default_generators = {}
+ super(MetaHasTraits, cls).setup_class(classdict)
+
+
def observe(*names, type="change"):
- """A decorator which can be used to observe Traits on a class.
-
+ """A decorator which can be used to observe Traits on a class.
+
The handler passed to the decorator will be called with one ``change``
dict argument. The change dictionary at least holds a 'type' key and a
'name' key, corresponding respectively to the type of notification and the
name of the attribute that triggered the notification.
-
- Other keys may be passed depending on the value of 'type'. In the case
- where type is 'change', we also have the following keys:
- * ``owner`` : the HasTraits instance
- * ``old`` : the old value of the modified trait attribute
- * ``new`` : the new value of the modified trait attribute
- * ``name`` : the name of the modified trait attribute.
-
- Parameters
- ----------
- *names
- The str names of the Traits to observe on the object.
+
+ Other keys may be passed depending on the value of 'type'. In the case
+ where type is 'change', we also have the following keys:
+ * ``owner`` : the HasTraits instance
+ * ``old`` : the old value of the modified trait attribute
+ * ``new`` : the new value of the modified trait attribute
+ * ``name`` : the name of the modified trait attribute.
+
+ Parameters
+ ----------
+ *names
+ The str names of the Traits to observe on the object.
type : str, kwarg-only
The type of event to observe (e.g. 'change')
- """
+ """
if not names:
raise TypeError("Please specify at least one trait name to observe.")
for name in names:
if name is not All and not isinstance(name, str):
raise TypeError("trait names to observe must be strings or All, not %r" % name)
return ObserveHandler(names, type=type)
-
-
-def observe_compat(func):
- """Backward-compatibility shim decorator for observers
-
- Use with:
-
- @observe('name')
- @observe_compat
- def _foo_changed(self, change):
- ...
-
- With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work.
- Allows adoption of new observer API without breaking subclasses that override and super.
- """
- def compatible_observer(self, change_or_name, old=Undefined, new=Undefined):
- if isinstance(change_or_name, dict):
- change = change_or_name
- else:
- clsname = self.__class__.__name__
+
+
+def observe_compat(func):
+ """Backward-compatibility shim decorator for observers
+
+ Use with:
+
+ @observe('name')
+ @observe_compat
+ def _foo_changed(self, change):
+ ...
+
+ With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work.
+ Allows adoption of new observer API without breaking subclasses that override and super.
+ """
+ def compatible_observer(self, change_or_name, old=Undefined, new=Undefined):
+ if isinstance(change_or_name, dict):
+ change = change_or_name
+ else:
+ clsname = self.__class__.__name__
warn("A parent of %s._%s_changed has adopted the new (traitlets 4.1) @observe(change) API" % (
- clsname, change_or_name), DeprecationWarning)
+ clsname, change_or_name), DeprecationWarning)
change = Bunch(
type='change',
old=old,
@@ -887,151 +887,151 @@ def observe_compat(func):
name=change_or_name,
owner=self,
)
- return func(self, change)
- return compatible_observer
-
-
-def validate(*names):
- """A decorator to register cross validator of HasTraits object's state
- when a Trait is set.
-
- The handler passed to the decorator must have one ``proposal`` dict argument.
- The proposal dictionary must hold the following keys:
-
- * ``owner`` : the HasTraits instance
- * ``value`` : the proposed value for the modified trait attribute
- * ``trait`` : the TraitType instance associated with the attribute
-
- Parameters
- ----------
+ return func(self, change)
+ return compatible_observer
+
+
+def validate(*names):
+ """A decorator to register cross validator of HasTraits object's state
+ when a Trait is set.
+
+ The handler passed to the decorator must have one ``proposal`` dict argument.
+ The proposal dictionary must hold the following keys:
+
+ * ``owner`` : the HasTraits instance
+ * ``value`` : the proposed value for the modified trait attribute
+ * ``trait`` : the TraitType instance associated with the attribute
+
+ Parameters
+ ----------
*names
- The str names of the Traits to validate.
-
- Notes
- -----
+ The str names of the Traits to validate.
+
+ Notes
+ -----
Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
- the registered cross validator could potentially make changes to attributes
- of the ``HasTraits`` instance. However, we recommend not to do so. The reason
- is that the cross-validation of attributes may run in arbitrary order when
+ the registered cross validator could potentially make changes to attributes
+ of the ``HasTraits`` instance. However, we recommend not to do so. The reason
+ is that the cross-validation of attributes may run in arbitrary order when
exiting the ``hold_trait_notifications`` context, and such changes may not
- commute.
- """
+ commute.
+ """
if not names:
raise TypeError("Please specify at least one trait name to validate.")
for name in names:
if name is not All and not isinstance(name, str):
raise TypeError("trait names to validate must be strings or All, not %r" % name)
- return ValidateHandler(names)
-
-
-def default(name):
- """ A decorator which assigns a dynamic default for a Trait on a HasTraits object.
-
- Parameters
- ----------
- name
- The str name of the Trait on the object whose default should be generated.
-
- Notes
- -----
- Unlike observers and validators which are properties of the HasTraits
- instance, default value generators are class-level properties.
-
- Besides, default generators are only invoked if they are registered in
- subclasses of `this_type`.
-
- ::
-
- class A(HasTraits):
- bar = Int()
-
- @default('bar')
- def get_bar_default(self):
- return 11
-
- class B(A):
- bar = Float() # This trait ignores the default generator defined in
- # the base class A
-
- class C(B):
-
- @default('bar')
- def some_other_default(self): # This default generator should not be
- return 3.0 # ignored since it is defined in a
- # class derived from B.a.this_class.
- """
+ return ValidateHandler(names)
+
+
+def default(name):
+ """ A decorator which assigns a dynamic default for a Trait on a HasTraits object.
+
+ Parameters
+ ----------
+ name
+ The str name of the Trait on the object whose default should be generated.
+
+ Notes
+ -----
+ Unlike observers and validators which are properties of the HasTraits
+ instance, default value generators are class-level properties.
+
+ Besides, default generators are only invoked if they are registered in
+ subclasses of `this_type`.
+
+ ::
+
+ class A(HasTraits):
+ bar = Int()
+
+ @default('bar')
+ def get_bar_default(self):
+ return 11
+
+ class B(A):
+ bar = Float() # This trait ignores the default generator defined in
+ # the base class A
+
+ class C(B):
+
+ @default('bar')
+ def some_other_default(self): # This default generator should not be
+ return 3.0 # ignored since it is defined in a
+ # class derived from B.a.this_class.
+ """
if not isinstance(name, str):
raise TypeError("Trait name must be a string or All, not %r" % name)
- return DefaultHandler(name)
-
-
-class EventHandler(BaseDescriptor):
-
- def _init_call(self, func):
- self.func = func
- return self
-
- def __call__(self, *args, **kwargs):
+ return DefaultHandler(name)
+
+
+class EventHandler(BaseDescriptor):
+
+ def _init_call(self, func):
+ self.func = func
+ return self
+
+ def __call__(self, *args, **kwargs):
"""Pass `*args` and `**kwargs` to the handler's function if it exists."""
- if hasattr(self, 'func'):
- return self.func(*args, **kwargs)
- else:
- return self._init_call(*args, **kwargs)
-
- def __get__(self, inst, cls=None):
- if inst is None:
- return self
- return types.MethodType(self.func, inst)
-
-
-class ObserveHandler(EventHandler):
-
- def __init__(self, names, type):
- self.trait_names = names
- self.type = type
-
- def instance_init(self, inst):
- inst.observe(self, self.trait_names, type=self.type)
-
-
-class ValidateHandler(EventHandler):
-
- def __init__(self, names):
- self.trait_names = names
-
- def instance_init(self, inst):
- inst._register_validator(self, self.trait_names)
-
-
-class DefaultHandler(EventHandler):
-
- def __init__(self, name):
- self.trait_name = name
-
- def class_init(self, cls, name):
+ if hasattr(self, 'func'):
+ return self.func(*args, **kwargs)
+ else:
+ return self._init_call(*args, **kwargs)
+
+ def __get__(self, inst, cls=None):
+ if inst is None:
+ return self
+ return types.MethodType(self.func, inst)
+
+
+class ObserveHandler(EventHandler):
+
+ def __init__(self, names, type):
+ self.trait_names = names
+ self.type = type
+
+ def instance_init(self, inst):
+ inst.observe(self, self.trait_names, type=self.type)
+
+
+class ValidateHandler(EventHandler):
+
+ def __init__(self, names):
+ self.trait_names = names
+
+ def instance_init(self, inst):
+ inst._register_validator(self, self.trait_names)
+
+
+class DefaultHandler(EventHandler):
+
+ def __init__(self, name):
+ self.trait_name = name
+
+ def class_init(self, cls, name):
super().class_init(cls, name)
- cls._trait_default_generators[self.trait_name] = self
-
-
+ cls._trait_default_generators[self.trait_name] = self
+
+
class HasDescriptors(metaclass=MetaHasDescriptors):
- """The base class for all classes that have descriptors.
- """
-
+ """The base class for all classes that have descriptors.
+ """
+
def __new__(*args, **kwargs):
# Pass cls as args[0] to allow "cls" as keyword argument
cls = args[0]
args = args[1:]
- # This is needed because object.__new__ only accepts
- # the cls argument.
- new_meth = super(HasDescriptors, cls).__new__
- if new_meth is object.__new__:
- inst = new_meth(cls)
- else:
+ # This is needed because object.__new__ only accepts
+ # the cls argument.
+ new_meth = super(HasDescriptors, cls).__new__
+ if new_meth is object.__new__:
+ inst = new_meth(cls)
+ else:
inst = new_meth(cls, *args, **kwargs)
inst.setup_instance(*args, **kwargs)
- return inst
-
+ return inst
+
def setup_instance(*args, **kwargs):
"""
This is called **before** self.__init__ is called.
@@ -1041,39 +1041,39 @@ class HasDescriptors(metaclass=MetaHasDescriptors):
args = args[1:]
self._cross_validation_lock = False
- cls = self.__class__
- for key in dir(cls):
- # Some descriptors raise AttributeError like zope.interface's
- # __provides__ attributes even though they exist. This causes
- # AttributeErrors even though they are listed in dir(cls).
- try:
- value = getattr(cls, key)
- except AttributeError:
- pass
- else:
- if isinstance(value, BaseDescriptor):
- value.instance_init(self)
-
-
+ cls = self.__class__
+ for key in dir(cls):
+ # Some descriptors raise AttributeError like zope.interface's
+ # __provides__ attributes even though they exist. This causes
+ # AttributeErrors even though they are listed in dir(cls).
+ try:
+ value = getattr(cls, key)
+ except AttributeError:
+ pass
+ else:
+ if isinstance(value, BaseDescriptor):
+ value.instance_init(self)
+
+
class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
-
+
def setup_instance(*args, **kwargs):
# Pass self as args[0] to allow "self" as keyword argument
self = args[0]
args = args[1:]
- self._trait_values = {}
- self._trait_notifiers = {}
- self._trait_validators = {}
+ self._trait_values = {}
+ self._trait_notifiers = {}
+ self._trait_validators = {}
super(HasTraits, self).setup_instance(*args, **kwargs)
-
+
def __init__(self, *args, **kwargs):
- # Allow trait values to be set using keyword arguments.
- # We need to use setattr for this to trigger validation and
- # notifications.
+ # Allow trait values to be set using keyword arguments.
+ # We need to use setattr for this to trigger validation and
+ # notifications.
super_args = args
super_kwargs = {}
- with self.hold_trait_notifications():
+ with self.hold_trait_notifications():
for key, value in kwargs.items():
if self.has_trait(key):
setattr(self, key, value)
@@ -1099,38 +1099,38 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
DeprecationWarning,
stacklevel=2,
)
-
- def __getstate__(self):
- d = self.__dict__.copy()
- # event handlers stored on an instance are
- # expected to be reinstantiated during a
- # recall of instance_init during __setstate__
- d['_trait_notifiers'] = {}
- d['_trait_validators'] = {}
+
+ def __getstate__(self):
+ d = self.__dict__.copy()
+ # event handlers stored on an instance are
+ # expected to be reinstantiated during a
+ # recall of instance_init during __setstate__
+ d['_trait_notifiers'] = {}
+ d['_trait_validators'] = {}
d['_trait_values'] = self._trait_values.copy()
d['_cross_validation_lock'] = False # FIXME: raise if cloning locked!
- return d
-
- def __setstate__(self, state):
- self.__dict__ = state.copy()
-
- # event handlers are reassigned to self
- cls = self.__class__
- for key in dir(cls):
- # Some descriptors raise AttributeError like zope.interface's
- # __provides__ attributes even though they exist. This causes
- # AttributeErrors even though they are listed in dir(cls).
- try:
- value = getattr(cls, key)
- except AttributeError:
- pass
- else:
- if isinstance(value, EventHandler):
- value.instance_init(self)
-
+ return d
+
+ def __setstate__(self, state):
+ self.__dict__ = state.copy()
+
+ # event handlers are reassigned to self
+ cls = self.__class__
+ for key in dir(cls):
+ # Some descriptors raise AttributeError like zope.interface's
+ # __provides__ attributes even though they exist. This causes
+ # AttributeErrors even though they are listed in dir(cls).
+ try:
+ value = getattr(cls, key)
+ except AttributeError:
+ pass
+ else:
+ if isinstance(value, EventHandler):
+ value.instance_init(self)
+
@property
- @contextlib.contextmanager
+ @contextlib.contextmanager
def cross_validation_lock(self):
"""
A contextmanager for running a block with our cross validation lock set
@@ -1150,72 +1150,72 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
self._cross_validation_lock = False
@contextlib.contextmanager
- def hold_trait_notifications(self):
- """Context manager for bundling trait change notifications and cross
- validation.
-
- Use this when doing multiple trait assignments (init, config), to avoid
- race conditions in trait notifiers requesting other trait values.
- All trait notifications will fire after all values have been assigned.
- """
+ def hold_trait_notifications(self):
+ """Context manager for bundling trait change notifications and cross
+ validation.
+
+ Use this when doing multiple trait assignments (init, config), to avoid
+ race conditions in trait notifiers requesting other trait values.
+ All trait notifications will fire after all values have been assigned.
+ """
if self._cross_validation_lock:
- yield
- return
- else:
- cache = {}
- notify_change = self.notify_change
-
- def compress(past_changes, change):
- """Merges the provided change with the last if possible."""
- if past_changes is None:
- return [change]
- else:
+ yield
+ return
+ else:
+ cache = {}
+ notify_change = self.notify_change
+
+ def compress(past_changes, change):
+ """Merges the provided change with the last if possible."""
+ if past_changes is None:
+ return [change]
+ else:
if past_changes[-1]['type'] == 'change' and change.type == 'change':
past_changes[-1]['new'] = change.new
- else:
- # In case of changes other than 'change', append the notification.
- past_changes.append(change)
- return past_changes
-
- def hold(change):
+ else:
+ # In case of changes other than 'change', append the notification.
+ past_changes.append(change)
+ return past_changes
+
+ def hold(change):
name = change.name
- cache[name] = compress(cache.get(name), change)
-
- try:
- # Replace notify_change with `hold`, caching and compressing
- # notifications, disable cross validation and yield.
- self.notify_change = hold
- self._cross_validation_lock = True
- yield
- # Cross validate final values when context is released.
- for name in list(cache.keys()):
- trait = getattr(self.__class__, name)
- value = trait._cross_validate(self, getattr(self, name))
+ cache[name] = compress(cache.get(name), change)
+
+ try:
+ # Replace notify_change with `hold`, caching and compressing
+ # notifications, disable cross validation and yield.
+ self.notify_change = hold
+ self._cross_validation_lock = True
+ yield
+ # Cross validate final values when context is released.
+ for name in list(cache.keys()):
+ trait = getattr(self.__class__, name)
+ value = trait._cross_validate(self, getattr(self, name))
self.set_trait(name, value)
- except TraitError as e:
- # Roll back in case of TraitError during final cross validation.
- self.notify_change = lambda x: None
- for name, changes in cache.items():
- for change in changes[::-1]:
- # TODO: Separate in a rollback function per notification type.
+ except TraitError as e:
+ # Roll back in case of TraitError during final cross validation.
+ self.notify_change = lambda x: None
+ for name, changes in cache.items():
+ for change in changes[::-1]:
+ # TODO: Separate in a rollback function per notification type.
if change.type == 'change':
if change.old is not Undefined:
self.set_trait(name, change.old)
- else:
- self._trait_values.pop(name)
- cache = {}
- raise e
- finally:
- self._cross_validation_lock = False
+ else:
+ self._trait_values.pop(name)
+ cache = {}
+ raise e
+ finally:
+ self._cross_validation_lock = False
# Restore method retrieval from class
del self.notify_change
-
- # trigger delayed notifications
- for changes in cache.values():
- for change in changes:
- self.notify_change(change)
-
- def _notify_trait(self, name, old_value, new_value):
+
+ # trigger delayed notifications
+ for changes in cache.values():
+ for change in changes:
+ self.notify_change(change)
+
+ def _notify_trait(self, name, old_value, new_value):
self.notify_change(Bunch(
name=name,
old=old_value,
@@ -1223,8 +1223,8 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
owner=self,
type='change',
))
-
- def notify_change(self, change):
+
+ def notify_change(self, change):
"""Notify observers of a change event"""
return self._notify_observers(change)
@@ -1234,188 +1234,188 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
# cast to bunch if given a dict
event = Bunch(event)
name, type = event.name, event.type
-
- callables = []
- callables.extend(self._trait_notifiers.get(name, {}).get(type, []))
- callables.extend(self._trait_notifiers.get(name, {}).get(All, []))
- callables.extend(self._trait_notifiers.get(All, {}).get(type, []))
- callables.extend(self._trait_notifiers.get(All, {}).get(All, []))
-
- # Now static ones
- magic_name = '_%s_changed' % name
+
+ callables = []
+ callables.extend(self._trait_notifiers.get(name, {}).get(type, []))
+ callables.extend(self._trait_notifiers.get(name, {}).get(All, []))
+ callables.extend(self._trait_notifiers.get(All, {}).get(type, []))
+ callables.extend(self._trait_notifiers.get(All, {}).get(All, []))
+
+ # Now static ones
+ magic_name = '_%s_changed' % name
if event.type == "change" and hasattr(self, magic_name):
- class_value = getattr(self.__class__, magic_name)
- if not isinstance(class_value, ObserveHandler):
- _deprecated_method(class_value, self.__class__, magic_name,
- "use @observe and @unobserve instead.")
- cb = getattr(self, magic_name)
- # Only append the magic method if it was not manually registered
- if cb not in callables:
- callables.append(_callback_wrapper(cb))
-
- # Call them all now
- # Traits catches and logs errors here. I allow them to raise
- for c in callables:
- # Bound methods have an additional 'self' argument.
-
- if isinstance(c, _CallbackWrapper):
- c = c.__call__
+ class_value = getattr(self.__class__, magic_name)
+ if not isinstance(class_value, ObserveHandler):
+ _deprecated_method(class_value, self.__class__, magic_name,
+ "use @observe and @unobserve instead.")
+ cb = getattr(self, magic_name)
+ # Only append the magic method if it was not manually registered
+ if cb not in callables:
+ callables.append(_callback_wrapper(cb))
+
+ # Call them all now
+ # Traits catches and logs errors here. I allow them to raise
+ for c in callables:
+ # Bound methods have an additional 'self' argument.
+
+ if isinstance(c, _CallbackWrapper):
+ c = c.__call__
elif isinstance(c, EventHandler) and c.name is not None:
- c = getattr(self, c.name)
+ c = getattr(self, c.name)
c(event)
-
- def _add_notifiers(self, handler, name, type):
- if name not in self._trait_notifiers:
- nlist = []
- self._trait_notifiers[name] = {type: nlist}
- else:
- if type not in self._trait_notifiers[name]:
- nlist = []
- self._trait_notifiers[name][type] = nlist
- else:
- nlist = self._trait_notifiers[name][type]
- if handler not in nlist:
- nlist.append(handler)
-
- def _remove_notifiers(self, handler, name, type):
- try:
- if handler is None:
- del self._trait_notifiers[name][type]
- else:
- self._trait_notifiers[name][type].remove(handler)
- except KeyError:
- pass
-
- def on_trait_change(self, handler=None, name=None, remove=False):
- """DEPRECATED: Setup a handler to be called when a trait changes.
-
- This is used to setup dynamic notifications of trait changes.
-
- Static handlers can be created by creating methods on a HasTraits
- subclass with the naming convention '_[traitname]_changed'. Thus,
- to create static handler for the trait 'a', create the method
- _a_changed(self, name, old, new) (fewer arguments can be used, see
- below).
-
- If `remove` is True and `handler` is not specified, all change
- handlers for the specified name are uninstalled.
-
- Parameters
- ----------
- handler : callable, None
- A callable that is called when a trait changes. Its
- signature can be handler(), handler(name), handler(name, new),
- handler(name, old, new), or handler(name, old, new, self).
- name : list, str, None
- If None, the handler will apply to all traits. If a list
- of str, handler will apply to all names in the list. If a
- str, the handler will apply just to that name.
- remove : bool
- If False (the default), then install the handler. If True
- then unintall it.
- """
+
+ def _add_notifiers(self, handler, name, type):
+ if name not in self._trait_notifiers:
+ nlist = []
+ self._trait_notifiers[name] = {type: nlist}
+ else:
+ if type not in self._trait_notifiers[name]:
+ nlist = []
+ self._trait_notifiers[name][type] = nlist
+ else:
+ nlist = self._trait_notifiers[name][type]
+ if handler not in nlist:
+ nlist.append(handler)
+
+ def _remove_notifiers(self, handler, name, type):
+ try:
+ if handler is None:
+ del self._trait_notifiers[name][type]
+ else:
+ self._trait_notifiers[name][type].remove(handler)
+ except KeyError:
+ pass
+
+ def on_trait_change(self, handler=None, name=None, remove=False):
+ """DEPRECATED: Setup a handler to be called when a trait changes.
+
+ This is used to setup dynamic notifications of trait changes.
+
+ Static handlers can be created by creating methods on a HasTraits
+ subclass with the naming convention '_[traitname]_changed'. Thus,
+ to create static handler for the trait 'a', create the method
+ _a_changed(self, name, old, new) (fewer arguments can be used, see
+ below).
+
+ If `remove` is True and `handler` is not specified, all change
+ handlers for the specified name are uninstalled.
+
+ Parameters
+ ----------
+ handler : callable, None
+ A callable that is called when a trait changes. Its
+ signature can be handler(), handler(name), handler(name, new),
+ handler(name, old, new), or handler(name, old, new, self).
+ name : list, str, None
+ If None, the handler will apply to all traits. If a list
+ of str, handler will apply to all names in the list. If a
+ str, the handler will apply just to that name.
+ remove : bool
+ If False (the default), then install the handler. If True
+ then unintall it.
+ """
warn("on_trait_change is deprecated in traitlets 4.1: use observe instead",
- DeprecationWarning, stacklevel=2)
- if name is None:
- name = All
- if remove:
- self.unobserve(_callback_wrapper(handler), names=name)
- else:
- self.observe(_callback_wrapper(handler), names=name)
-
- def observe(self, handler, names=All, type='change'):
- """Setup a handler to be called when a trait changes.
-
- This is used to setup dynamic notifications of trait changes.
-
- Parameters
- ----------
- handler : callable
- A callable that is called when a trait changes. Its
+ DeprecationWarning, stacklevel=2)
+ if name is None:
+ name = All
+ if remove:
+ self.unobserve(_callback_wrapper(handler), names=name)
+ else:
+ self.observe(_callback_wrapper(handler), names=name)
+
+ def observe(self, handler, names=All, type='change'):
+ """Setup a handler to be called when a trait changes.
+
+ This is used to setup dynamic notifications of trait changes.
+
+ Parameters
+ ----------
+ handler : callable
+ A callable that is called when a trait changes. Its
signature should be ``handler(change)``, where ``change`` is a
dictionary. The change dictionary at least holds a 'type' key.
- * ``type``: the type of notification.
- Other keys may be passed depending on the value of 'type'. In the
- case where type is 'change', we also have the following keys:
- * ``owner`` : the HasTraits instance
- * ``old`` : the old value of the modified trait attribute
- * ``new`` : the new value of the modified trait attribute
- * ``name`` : the name of the modified trait attribute.
- names : list, str, All
- If names is All, the handler will apply to all traits. If a list
- of str, handler will apply to all names in the list. If a
- str, the handler will apply just to that name.
- type : str, All (default: 'change')
- The type of notification to filter by. If equal to All, then all
- notifications are passed to the observe handler.
- """
- names = parse_notifier_name(names)
- for n in names:
- self._add_notifiers(handler, n, type)
-
- def unobserve(self, handler, names=All, type='change'):
- """Remove a trait change handler.
-
+ * ``type``: the type of notification.
+ Other keys may be passed depending on the value of 'type'. In the
+ case where type is 'change', we also have the following keys:
+ * ``owner`` : the HasTraits instance
+ * ``old`` : the old value of the modified trait attribute
+ * ``new`` : the new value of the modified trait attribute
+ * ``name`` : the name of the modified trait attribute.
+ names : list, str, All
+ If names is All, the handler will apply to all traits. If a list
+ of str, handler will apply to all names in the list. If a
+ str, the handler will apply just to that name.
+ type : str, All (default: 'change')
+ The type of notification to filter by. If equal to All, then all
+ notifications are passed to the observe handler.
+ """
+ names = parse_notifier_name(names)
+ for n in names:
+ self._add_notifiers(handler, n, type)
+
+ def unobserve(self, handler, names=All, type='change'):
+ """Remove a trait change handler.
+
This is used to unregister handlers to trait change notifications.
-
- Parameters
- ----------
- handler : callable
- The callable called when a trait attribute changes.
- names : list, str, All (default: All)
- The names of the traits for which the specified handler should be
- uninstalled. If names is All, the specified handler is uninstalled
- from the list of notifiers corresponding to all changes.
- type : str or All (default: 'change')
- The type of notification to filter by. If All, the specified handler
- is uninstalled from the list of notifiers corresponding to all types.
- """
- names = parse_notifier_name(names)
- for n in names:
- self._remove_notifiers(handler, n, type)
-
- def unobserve_all(self, name=All):
- """Remove trait change handlers of any type for the specified name.
- If name is not specified, removes all trait notifiers."""
- if name is All:
- self._trait_notifiers = {}
- else:
- try:
- del self._trait_notifiers[name]
- except KeyError:
- pass
-
- def _register_validator(self, handler, names):
+
+ Parameters
+ ----------
+ handler : callable
+ The callable called when a trait attribute changes.
+ names : list, str, All (default: All)
+ The names of the traits for which the specified handler should be
+ uninstalled. If names is All, the specified handler is uninstalled
+ from the list of notifiers corresponding to all changes.
+ type : str or All (default: 'change')
+ The type of notification to filter by. If All, the specified handler
+ is uninstalled from the list of notifiers corresponding to all types.
+ """
+ names = parse_notifier_name(names)
+ for n in names:
+ self._remove_notifiers(handler, n, type)
+
+ def unobserve_all(self, name=All):
+ """Remove trait change handlers of any type for the specified name.
+ If name is not specified, removes all trait notifiers."""
+ if name is All:
+ self._trait_notifiers = {}
+ else:
+ try:
+ del self._trait_notifiers[name]
+ except KeyError:
+ pass
+
+ def _register_validator(self, handler, names):
"""Setup a handler to be called when a trait should be cross validated.
-
- This is used to setup dynamic notifications for cross-validation.
-
- If a validator is already registered for any of the provided names, a
+
+ This is used to setup dynamic notifications for cross-validation.
+
+ If a validator is already registered for any of the provided names, a
TraitError is raised and no new validator is registered.
-
- Parameters
- ----------
- handler : callable
- A callable that is called when the given trait is cross-validated.
+
+ Parameters
+ ----------
+ handler : callable
+ A callable that is called when the given trait is cross-validated.
Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
with the following attributes/keys:
- * ``owner`` : the HasTraits instance
- * ``value`` : the proposed value for the modified trait attribute
- * ``trait`` : the TraitType instance associated with the attribute
- names : List of strings
- The names of the traits that should be cross-validated
- """
- for name in names:
- magic_name = '_%s_validate' % name
- if hasattr(self, magic_name):
- class_value = getattr(self.__class__, magic_name)
- if not isinstance(class_value, ValidateHandler):
+ * ``owner`` : the HasTraits instance
+ * ``value`` : the proposed value for the modified trait attribute
+ * ``trait`` : the TraitType instance associated with the attribute
+ names : List of strings
+ The names of the traits that should be cross-validated
+ """
+ for name in names:
+ magic_name = '_%s_validate' % name
+ if hasattr(self, magic_name):
+ class_value = getattr(self.__class__, magic_name)
+ if not isinstance(class_value, ValidateHandler):
_deprecated_method(class_value, self.__class__, magic_name,
- "use @validate decorator instead.")
- for name in names:
- self._trait_validators[name] = handler
-
+ "use @validate decorator instead.")
+ for name in names:
+ self._trait_validators[name] = handler
+
def add_traits(self, **traits):
"""Dynamically add trait attributes to the HasTraits instance."""
cls = self.__class__
@@ -1437,63 +1437,63 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
else:
getattr(cls, name).set(self, value)
- @classmethod
- def class_trait_names(cls, **metadata):
- """Get a list of all the names of this class' traits.
-
- This method is just like the :meth:`trait_names` method,
- but is unbound.
- """
+ @classmethod
+ def class_trait_names(cls, **metadata):
+ """Get a list of all the names of this class' traits.
+
+ This method is just like the :meth:`trait_names` method,
+ but is unbound.
+ """
return list(cls.class_traits(**metadata))
-
- @classmethod
- def class_traits(cls, **metadata):
- """Get a ``dict`` of all the traits of this class. The dictionary
- is keyed on the name and the values are the TraitType objects.
-
- This method is just like the :meth:`traits` method, but is unbound.
-
- The TraitTypes returned don't know anything about the values
- that the various HasTrait's instances are holding.
-
- The metadata kwargs allow functions to be passed in which
- filter traits based on metadata values. The functions should
- take a single value as an argument and return a boolean. If
- any function returns False, then the trait is not included in
- the output. If a metadata key doesn't exist, None will be passed
- to the function.
- """
- traits = dict([memb for memb in getmembers(cls) if
- isinstance(memb[1], TraitType)])
-
- if len(metadata) == 0:
- return traits
-
- result = {}
- for name, trait in traits.items():
- for meta_name, meta_eval in metadata.items():
+
+ @classmethod
+ def class_traits(cls, **metadata):
+ """Get a ``dict`` of all the traits of this class. The dictionary
+ is keyed on the name and the values are the TraitType objects.
+
+ This method is just like the :meth:`traits` method, but is unbound.
+
+ The TraitTypes returned don't know anything about the values
+ that the various HasTrait's instances are holding.
+
+ The metadata kwargs allow functions to be passed in which
+ filter traits based on metadata values. The functions should
+ take a single value as an argument and return a boolean. If
+ any function returns False, then the trait is not included in
+ the output. If a metadata key doesn't exist, None will be passed
+ to the function.
+ """
+ traits = dict([memb for memb in getmembers(cls) if
+ isinstance(memb[1], TraitType)])
+
+ if len(metadata) == 0:
+ return traits
+
+ result = {}
+ for name, trait in traits.items():
+ for meta_name, meta_eval in metadata.items():
if not callable(meta_eval):
- meta_eval = _SimpleTest(meta_eval)
- if not meta_eval(trait.metadata.get(meta_name, None)):
- break
- else:
- result[name] = trait
-
- return result
-
- @classmethod
- def class_own_traits(cls, **metadata):
- """Get a dict of all the traitlets defined on this class, not a parent.
-
- Works like `class_traits`, except for excluding traits from parents.
- """
- sup = super(cls, cls)
- return {n: t for (n, t) in cls.class_traits(**metadata).items()
- if getattr(sup, n, None) is not t}
-
- def has_trait(self, name):
- """Returns True if the object has a trait with the specified name."""
- return isinstance(getattr(self.__class__, name, None), TraitType)
+ meta_eval = _SimpleTest(meta_eval)
+ if not meta_eval(trait.metadata.get(meta_name, None)):
+ break
+ else:
+ result[name] = trait
+
+ return result
+
+ @classmethod
+ def class_own_traits(cls, **metadata):
+ """Get a dict of all the traitlets defined on this class, not a parent.
+
+ Works like `class_traits`, except for excluding traits from parents.
+ """
+ sup = super(cls, cls)
+ return {n: t for (n, t) in cls.class_traits(**metadata).items()
+ if getattr(sup, n, None) is not t}
+
+ def has_trait(self, name):
+ """Returns True if the object has a trait with the specified name."""
+ return isinstance(getattr(self.__class__, name, None), TraitType)
def trait_has_value(self, name):
"""Returns True if the specified trait has a value.
@@ -1587,65 +1587,65 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
defaults[n] = self._get_trait_default_generator(n)(self)
return defaults
- def trait_names(self, **metadata):
- """Get a list of all the names of this class' traits."""
+ def trait_names(self, **metadata):
+ """Get a list of all the names of this class' traits."""
return list(self.traits(**metadata))
-
- def traits(self, **metadata):
- """Get a ``dict`` of all the traits of this class. The dictionary
- is keyed on the name and the values are the TraitType objects.
-
- The TraitTypes returned don't know anything about the values
- that the various HasTrait's instances are holding.
-
- The metadata kwargs allow functions to be passed in which
- filter traits based on metadata values. The functions should
- take a single value as an argument and return a boolean. If
- any function returns False, then the trait is not included in
- the output. If a metadata key doesn't exist, None will be passed
- to the function.
- """
- traits = dict([memb for memb in getmembers(self.__class__) if
- isinstance(memb[1], TraitType)])
-
- if len(metadata) == 0:
- return traits
-
- result = {}
- for name, trait in traits.items():
- for meta_name, meta_eval in metadata.items():
+
+ def traits(self, **metadata):
+ """Get a ``dict`` of all the traits of this class. The dictionary
+ is keyed on the name and the values are the TraitType objects.
+
+ The TraitTypes returned don't know anything about the values
+ that the various HasTrait's instances are holding.
+
+ The metadata kwargs allow functions to be passed in which
+ filter traits based on metadata values. The functions should
+ take a single value as an argument and return a boolean. If
+ any function returns False, then the trait is not included in
+ the output. If a metadata key doesn't exist, None will be passed
+ to the function.
+ """
+ traits = dict([memb for memb in getmembers(self.__class__) if
+ isinstance(memb[1], TraitType)])
+
+ if len(metadata) == 0:
+ return traits
+
+ result = {}
+ for name, trait in traits.items():
+ for meta_name, meta_eval in metadata.items():
if not callable(meta_eval):
- meta_eval = _SimpleTest(meta_eval)
- if not meta_eval(trait.metadata.get(meta_name, None)):
- break
- else:
- result[name] = trait
-
- return result
-
- def trait_metadata(self, traitname, key, default=None):
- """Get metadata values for trait by key."""
- try:
- trait = getattr(self.__class__, traitname)
- except AttributeError:
- raise TraitError("Class %s does not have a trait named %s" %
- (self.__class__.__name__, traitname))
+ meta_eval = _SimpleTest(meta_eval)
+ if not meta_eval(trait.metadata.get(meta_name, None)):
+ break
+ else:
+ result[name] = trait
+
+ return result
+
+ def trait_metadata(self, traitname, key, default=None):
+ """Get metadata values for trait by key."""
+ try:
+ trait = getattr(self.__class__, traitname)
+ except AttributeError:
+ raise TraitError("Class %s does not have a trait named %s" %
+ (self.__class__.__name__, traitname))
metadata_name = '_' + traitname + '_metadata'
if hasattr(self, metadata_name) and key in getattr(self, metadata_name):
return getattr(self, metadata_name).get(key, default)
- else:
- return trait.metadata.get(key, default)
-
+ else:
+ return trait.metadata.get(key, default)
+
@classmethod
def class_own_trait_events(cls, name):
"""Get a dict of all event handlers defined on this class, not a parent.
-
+
Works like ``event_handlers``, except for excluding traits from parents.
"""
sup = super(cls, cls)
return {n: e for (n, e) in cls.events(name).items()
if getattr(sup, n, None) is not e}
-
+
@classmethod
def trait_events(cls, name=None):
"""Get a ``dict`` of all the event handlers of this class.
@@ -1672,288 +1672,288 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
events[k] = v
return events
-#-----------------------------------------------------------------------------
-# Actual TraitTypes implementations/subclasses
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# TraitTypes subclasses for handling classes and instances of classes
-#-----------------------------------------------------------------------------
-
-
-class ClassBasedTraitType(TraitType):
- """
- A trait with error reporting and string -> type resolution for Type,
- Instance and This.
- """
-
- def _resolve_string(self, string):
- """
- Resolve a string supplied for a type into an actual object.
- """
- return import_item(string)
-
-
-class Type(ClassBasedTraitType):
- """A trait whose value must be a subclass of a specified class."""
-
+#-----------------------------------------------------------------------------
+# Actual TraitTypes implementations/subclasses
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# TraitTypes subclasses for handling classes and instances of classes
+#-----------------------------------------------------------------------------
+
+
+class ClassBasedTraitType(TraitType):
+ """
+ A trait with error reporting and string -> type resolution for Type,
+ Instance and This.
+ """
+
+ def _resolve_string(self, string):
+ """
+ Resolve a string supplied for a type into an actual object.
+ """
+ return import_item(string)
+
+
+class Type(ClassBasedTraitType):
+ """A trait whose value must be a subclass of a specified class."""
+
def __init__(self, default_value=Undefined, klass=None, **kwargs):
- """Construct a Type trait
-
- A Type trait specifies that its values must be subclasses of
- a particular class.
-
- If only ``default_value`` is given, it is used for the ``klass`` as
- well. If neither are given, both default to ``object``.
-
- Parameters
- ----------
- default_value : class, str or None
- The default value must be a subclass of klass. If an str,
- the str must be a fully specified class name, like 'foo.bar.Bah'.
- The string is resolved into real class, when the parent
- :class:`HasTraits` class is instantiated.
- klass : class, str [ default object ]
- Values of this trait must be a subclass of klass. The klass
- may be specified in a string like: 'foo.bar.MyClass'.
- The string is resolved into real class, when the parent
- :class:`HasTraits` class is instantiated.
- allow_none : bool [ default False ]
- Indicates whether None is allowed as an assignable value.
+ """Construct a Type trait
+
+ A Type trait specifies that its values must be subclasses of
+ a particular class.
+
+ If only ``default_value`` is given, it is used for the ``klass`` as
+ well. If neither are given, both default to ``object``.
+
+ Parameters
+ ----------
+ default_value : class, str or None
+ The default value must be a subclass of klass. If an str,
+ the str must be a fully specified class name, like 'foo.bar.Bah'.
+ The string is resolved into real class, when the parent
+ :class:`HasTraits` class is instantiated.
+ klass : class, str [ default object ]
+ Values of this trait must be a subclass of klass. The klass
+ may be specified in a string like: 'foo.bar.MyClass'.
+ The string is resolved into real class, when the parent
+ :class:`HasTraits` class is instantiated.
+ allow_none : bool [ default False ]
+ Indicates whether None is allowed as an assignable value.
**kwargs
extra kwargs passed to `ClassBasedTraitType`
- """
- if default_value is Undefined:
- new_default_value = object if (klass is None) else klass
- else:
- new_default_value = default_value
-
- if klass is None:
- if (default_value is None) or (default_value is Undefined):
- klass = object
- else:
- klass = default_value
-
+ """
+ if default_value is Undefined:
+ new_default_value = object if (klass is None) else klass
+ else:
+ new_default_value = default_value
+
+ if klass is None:
+ if (default_value is None) or (default_value is Undefined):
+ klass = object
+ else:
+ klass = default_value
+
if not (inspect.isclass(klass) or isinstance(klass, str)):
- raise TraitError("A Type trait must specify a class.")
-
- self.klass = klass
-
+ raise TraitError("A Type trait must specify a class.")
+
+ self.klass = klass
+
super().__init__(new_default_value, **kwargs)
-
- def validate(self, obj, value):
- """Validates that the value is a valid object instance."""
+
+ def validate(self, obj, value):
+ """Validates that the value is a valid object instance."""
if isinstance(value, str):
- try:
- value = self._resolve_string(value)
- except ImportError:
- raise TraitError("The '%s' trait of %s instance must be a type, but "
- "%r could not be imported" % (self.name, obj, value))
- try:
- if issubclass(value, self.klass):
- return value
+ try:
+ value = self._resolve_string(value)
+ except ImportError:
+ raise TraitError("The '%s' trait of %s instance must be a type, but "
+ "%r could not be imported" % (self.name, obj, value))
+ try:
+ if issubclass(value, self.klass):
+ return value
except Exception:
- pass
-
- self.error(obj, value)
-
- def info(self):
- """ Returns a description of the trait."""
+ pass
+
+ self.error(obj, value)
+
+ def info(self):
+ """ Returns a description of the trait."""
if isinstance(self.klass, str):
- klass = self.klass
- else:
+ klass = self.klass
+ else:
klass = self.klass.__module__ + '.' + self.klass.__name__
- result = "a subclass of '%s'" % klass
- if self.allow_none:
- return result + ' or None'
- return result
-
- def instance_init(self, obj):
- self._resolve_classes()
+ result = "a subclass of '%s'" % klass
+ if self.allow_none:
+ return result + ' or None'
+ return result
+
+ def instance_init(self, obj):
+ self._resolve_classes()
super().instance_init(obj)
-
- def _resolve_classes(self):
+
+ def _resolve_classes(self):
if isinstance(self.klass, str):
- self.klass = self._resolve_string(self.klass)
+ self.klass = self._resolve_string(self.klass)
if isinstance(self.default_value, str):
- self.default_value = self._resolve_string(self.default_value)
-
- def default_value_repr(self):
- value = self.default_value
+ self.default_value = self._resolve_string(self.default_value)
+
+ def default_value_repr(self):
+ value = self.default_value
if isinstance(value, str):
- return repr(value)
- else:
+ return repr(value)
+ else:
return repr(f'{value.__module__}.{value.__name__}')
-
-
-class Instance(ClassBasedTraitType):
- """A trait whose value must be an instance of a specified class.
-
- The value can also be an instance of a subclass of the specified class.
-
- Subclasses can declare default classes by overriding the klass attribute
- """
-
- klass = None
-
+
+
+class Instance(ClassBasedTraitType):
+ """A trait whose value must be an instance of a specified class.
+
+ The value can also be an instance of a subclass of the specified class.
+
+ Subclasses can declare default classes by overriding the klass attribute
+ """
+
+ klass = None
+
def __init__(self, klass=None, args=None, kw=None, **kwargs):
- """Construct an Instance trait.
-
- This trait allows values that are instances of a particular
- class or its subclasses. Our implementation is quite different
- from that of enthough.traits as we don't allow instances to be used
- for klass and we handle the ``args`` and ``kw`` arguments differently.
-
- Parameters
- ----------
- klass : class, str
- The class that forms the basis for the trait. Class names
- can also be specified as strings, like 'foo.bar.Bar'.
- args : tuple
- Positional arguments for generating the default value.
- kw : dict
- Keyword arguments for generating the default value.
- allow_none : bool [ default False ]
- Indicates whether None is allowed as a value.
+ """Construct an Instance trait.
+
+ This trait allows values that are instances of a particular
+ class or its subclasses. Our implementation is quite different
+ from that of enthough.traits as we don't allow instances to be used
+ for klass and we handle the ``args`` and ``kw`` arguments differently.
+
+ Parameters
+ ----------
+ klass : class, str
+ The class that forms the basis for the trait. Class names
+ can also be specified as strings, like 'foo.bar.Bar'.
+ args : tuple
+ Positional arguments for generating the default value.
+ kw : dict
+ Keyword arguments for generating the default value.
+ allow_none : bool [ default False ]
+ Indicates whether None is allowed as a value.
**kwargs
Extra kwargs passed to `ClassBasedTraitType`
-
- Notes
- -----
- If both ``args`` and ``kw`` are None, then the default value is None.
- If ``args`` is a tuple and ``kw`` is a dict, then the default is
- created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is
- None, the None is replaced by ``()`` or ``{}``, respectively.
- """
- if klass is None:
- klass = self.klass
+
+ Notes
+ -----
+ If both ``args`` and ``kw`` are None, then the default value is None.
+ If ``args`` is a tuple and ``kw`` is a dict, then the default is
+ created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is
+ None, the None is replaced by ``()`` or ``{}``, respectively.
+ """
+ if klass is None:
+ klass = self.klass
if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, str)):
- self.klass = klass
- else:
- raise TraitError('The klass attribute must be a class'
- ' not: %r' % klass)
-
- if (kw is not None) and not isinstance(kw, dict):
- raise TraitError("The 'kw' argument must be a dict or None.")
- if (args is not None) and not isinstance(args, tuple):
- raise TraitError("The 'args' argument must be a tuple or None.")
-
- self.default_args = args
- self.default_kwargs = kw
-
+ self.klass = klass
+ else:
+ raise TraitError('The klass attribute must be a class'
+ ' not: %r' % klass)
+
+ if (kw is not None) and not isinstance(kw, dict):
+ raise TraitError("The 'kw' argument must be a dict or None.")
+ if (args is not None) and not isinstance(args, tuple):
+ raise TraitError("The 'args' argument must be a tuple or None.")
+
+ self.default_args = args
+ self.default_kwargs = kw
+
super(Instance, self).__init__(**kwargs)
-
- def validate(self, obj, value):
- if isinstance(value, self.klass):
- return value
- else:
- self.error(obj, value)
-
- def info(self):
+
+ def validate(self, obj, value):
+ if isinstance(value, self.klass):
+ return value
+ else:
+ self.error(obj, value)
+
+ def info(self):
if isinstance(self.klass, str):
result = add_article(self.klass)
- else:
+ else:
result = describe("a", self.klass)
- if self.allow_none:
+ if self.allow_none:
result += ' or None'
- return result
-
- def instance_init(self, obj):
- self._resolve_classes()
+ return result
+
+ def instance_init(self, obj):
+ self._resolve_classes()
super().instance_init(obj)
-
- def _resolve_classes(self):
+
+ def _resolve_classes(self):
if isinstance(self.klass, str):
- self.klass = self._resolve_string(self.klass)
-
- def make_dynamic_default(self):
- if (self.default_args is None) and (self.default_kwargs is None):
- return None
- return self.klass(*(self.default_args or ()),
- **(self.default_kwargs or {}))
-
- def default_value_repr(self):
- return repr(self.make_dynamic_default())
-
+ self.klass = self._resolve_string(self.klass)
+
+ def make_dynamic_default(self):
+ if (self.default_args is None) and (self.default_kwargs is None):
+ return None
+ return self.klass(*(self.default_args or ()),
+ **(self.default_kwargs or {}))
+
+ def default_value_repr(self):
+ return repr(self.make_dynamic_default())
+
def from_string(self, s):
return _safe_literal_eval(s)
-
-
-class ForwardDeclaredMixin(object):
- """
- Mixin for forward-declared versions of Instance and Type.
- """
- def _resolve_string(self, string):
- """
- Find the specified class name by looking for it in the module in which
- our this_class attribute was defined.
- """
- modname = self.this_class.__module__
- return import_item('.'.join([modname, string]))
-
-
-class ForwardDeclaredType(ForwardDeclaredMixin, Type):
- """
- Forward-declared version of Type.
- """
- pass
-
-
-class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance):
- """
- Forward-declared version of Instance.
- """
- pass
-
-
-class This(ClassBasedTraitType):
- """A trait for instances of the class containing this trait.
-
- Because how how and when class bodies are executed, the ``This``
- trait can only have a default value of None. This, and because we
- always validate default values, ``allow_none`` is *always* true.
- """
-
- info_text = 'an instance of the same type as the receiver or None'
-
+
+
+class ForwardDeclaredMixin(object):
+ """
+ Mixin for forward-declared versions of Instance and Type.
+ """
+ def _resolve_string(self, string):
+ """
+ Find the specified class name by looking for it in the module in which
+ our this_class attribute was defined.
+ """
+ modname = self.this_class.__module__
+ return import_item('.'.join([modname, string]))
+
+
+class ForwardDeclaredType(ForwardDeclaredMixin, Type):
+ """
+ Forward-declared version of Type.
+ """
+ pass
+
+
+class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance):
+ """
+ Forward-declared version of Instance.
+ """
+ pass
+
+
+class This(ClassBasedTraitType):
+ """A trait for instances of the class containing this trait.
+
+ Because how how and when class bodies are executed, the ``This``
+ trait can only have a default value of None. This, and because we
+ always validate default values, ``allow_none`` is *always* true.
+ """
+
+ info_text = 'an instance of the same type as the receiver or None'
+
def __init__(self, **kwargs):
super(This, self).__init__(None, **kwargs)
-
- def validate(self, obj, value):
- # What if value is a superclass of obj.__class__? This is
- # complicated if it was the superclass that defined the This
- # trait.
- if isinstance(value, self.this_class) or (value is None):
- return value
- else:
- self.error(obj, value)
-
-
-class Union(TraitType):
- """A trait type representing a Union type."""
-
+
+ def validate(self, obj, value):
+ # What if value is a superclass of obj.__class__? This is
+ # complicated if it was the superclass that defined the This
+ # trait.
+ if isinstance(value, self.this_class) or (value is None):
+ return value
+ else:
+ self.error(obj, value)
+
+
+class Union(TraitType):
+ """A trait type representing a Union type."""
+
def __init__(self, trait_types, **kwargs):
- """Construct a Union trait.
-
- This trait allows values that are allowed by at least one of the
- specified trait types. A Union traitlet cannot have metadata on
- its own, besides the metadata of the listed types.
-
- Parameters
- ----------
+ """Construct a Union trait.
+
+ This trait allows values that are allowed by at least one of the
+ specified trait types. A Union traitlet cannot have metadata on
+ its own, besides the metadata of the listed types.
+
+ Parameters
+ ----------
trait_types : sequence
- The list of trait types of length at least 1.
-
- Notes
- -----
- Union([Float(), Bool(), Int()]) attempts to validate the provided values
- with the validation function of Float, then Bool, and finally Int.
- """
+ The list of trait types of length at least 1.
+
+ Notes
+ -----
+ Union([Float(), Bool(), Int()]) attempts to validate the provided values
+ with the validation function of Float, then Bool, and finally Int.
+ """
self.trait_types = list(trait_types)
self.info_text = " or ".join([tt.info() for tt in self.trait_types])
super(Union, self).__init__(**kwargs)
-
+
def default(self, obj=None):
default = super(Union, self).default(obj)
for t in self.trait_types:
@@ -1963,48 +1963,48 @@ class Union(TraitType):
break
return default
- def class_init(self, cls, name):
+ def class_init(self, cls, name):
for trait_type in reversed(self.trait_types):
- trait_type.class_init(cls, None)
- super(Union, self).class_init(cls, name)
-
- def instance_init(self, obj):
+ trait_type.class_init(cls, None)
+ super(Union, self).class_init(cls, name)
+
+ def instance_init(self, obj):
for trait_type in reversed(self.trait_types):
- trait_type.instance_init(obj)
- super(Union, self).instance_init(obj)
-
- def validate(self, obj, value):
+ trait_type.instance_init(obj)
+ super(Union, self).instance_init(obj)
+
+ def validate(self, obj, value):
with obj.cross_validation_lock:
- for trait_type in self.trait_types:
- try:
- v = trait_type._validate(obj, value)
+ for trait_type in self.trait_types:
+ try:
+ v = trait_type._validate(obj, value)
# In the case of an element trait, the name is None
if self.name is not None:
setattr(obj, '_' + self.name + '_metadata', trait_type.metadata)
- return v
- except TraitError:
- continue
- self.error(obj, value)
-
- def __or__(self, other):
- if isinstance(other, Union):
- return Union(self.trait_types + other.trait_types)
- else:
- return Union(self.trait_types + [other])
-
-
-#-----------------------------------------------------------------------------
-# Basic TraitTypes implementations/subclasses
-#-----------------------------------------------------------------------------
-
-
-class Any(TraitType):
- """A trait which allows any value."""
- default_value = None
+ return v
+ except TraitError:
+ continue
+ self.error(obj, value)
+
+ def __or__(self, other):
+ if isinstance(other, Union):
+ return Union(self.trait_types + other.trait_types)
+ else:
+ return Union(self.trait_types + [other])
+
+
+#-----------------------------------------------------------------------------
+# Basic TraitTypes implementations/subclasses
+#-----------------------------------------------------------------------------
+
+
+class Any(TraitType):
+ """A trait which allows any value."""
+ default_value = None
allow_none = True
- info_text = 'any value'
-
-
+ info_text = 'any value'
+
+
def _validate_bounds(trait, obj, value):
"""
Validate that a number to be applied to a trait is between bounds.
@@ -2029,122 +2029,122 @@ def _validate_bounds(trait, obj, value):
return value
-class Int(TraitType):
- """An int trait."""
-
- default_value = 0
- info_text = 'an int'
-
+class Int(TraitType):
+ """An int trait."""
+
+ default_value = 0
+ info_text = 'an int'
+
def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
- self.min = kwargs.pop('min', None)
- self.max = kwargs.pop('max', None)
- super(Int, self).__init__(default_value=default_value,
- allow_none=allow_none, **kwargs)
-
- def validate(self, obj, value):
- if not isinstance(value, int):
- self.error(obj, value)
+ self.min = kwargs.pop('min', None)
+ self.max = kwargs.pop('max', None)
+ super(Int, self).__init__(default_value=default_value,
+ allow_none=allow_none, **kwargs)
+
+ def validate(self, obj, value):
+ if not isinstance(value, int):
+ self.error(obj, value)
return _validate_bounds(self, obj, value)
-
+
def from_string(self, s):
if self.allow_none and s == 'None':
return None
return int(s)
-
-class CInt(Int):
- """A casting version of the int trait."""
-
- def validate(self, obj, value):
- try:
+
+class CInt(Int):
+ """A casting version of the int trait."""
+
+ def validate(self, obj, value):
+ try:
value = int(value)
except Exception:
- self.error(obj, value)
+ self.error(obj, value)
return _validate_bounds(self, obj, value)
-
+
Long, CLong = Int, CInt
Integer = Int
-
-
-class Float(TraitType):
- """A float trait."""
-
- default_value = 0.0
- info_text = 'a float'
-
+
+
+class Float(TraitType):
+ """A float trait."""
+
+ default_value = 0.0
+ info_text = 'a float'
+
def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
- self.min = kwargs.pop('min', -float('inf'))
- self.max = kwargs.pop('max', float('inf'))
+ self.min = kwargs.pop('min', -float('inf'))
+ self.max = kwargs.pop('max', float('inf'))
super(Float, self).__init__(default_value=default_value,
- allow_none=allow_none, **kwargs)
-
- def validate(self, obj, value):
- if isinstance(value, int):
- value = float(value)
- if not isinstance(value, float):
- self.error(obj, value)
+ allow_none=allow_none, **kwargs)
+
+ def validate(self, obj, value):
+ if isinstance(value, int):
+ value = float(value)
+ if not isinstance(value, float):
+ self.error(obj, value)
return _validate_bounds(self, obj, value)
-
+
def from_string(self, s):
if self.allow_none and s == 'None':
return None
return float(s)
-
-class CFloat(Float):
- """A casting version of the float trait."""
-
- def validate(self, obj, value):
- try:
+
+class CFloat(Float):
+ """A casting version of the float trait."""
+
+ def validate(self, obj, value):
+ try:
value = float(value)
except Exception:
- self.error(obj, value)
+ self.error(obj, value)
return _validate_bounds(self, obj, value)
-
-
-class Complex(TraitType):
- """A trait for complex numbers."""
-
- default_value = 0.0 + 0.0j
- info_text = 'a complex number'
-
- def validate(self, obj, value):
- if isinstance(value, complex):
- return value
- if isinstance(value, (float, int)):
- return complex(value)
- self.error(obj, value)
-
+
+
+class Complex(TraitType):
+ """A trait for complex numbers."""
+
+ default_value = 0.0 + 0.0j
+ info_text = 'a complex number'
+
+ def validate(self, obj, value):
+ if isinstance(value, complex):
+ return value
+ if isinstance(value, (float, int)):
+ return complex(value)
+ self.error(obj, value)
+
def from_string(self, s):
if self.allow_none and s == 'None':
return None
return complex(s)
-
-
-class CComplex(Complex):
- """A casting version of the complex number trait."""
-
- def validate (self, obj, value):
- try:
- return complex(value)
+
+
+class CComplex(Complex):
+ """A casting version of the complex number trait."""
+
+ def validate (self, obj, value):
+ try:
+ return complex(value)
except Exception:
- self.error(obj, value)
-
-# We should always be explicit about whether we're using bytes or unicode, both
-# for Python 3 conversion and for reliable unicode behaviour on Python 2. So
-# we don't have a Str type.
-class Bytes(TraitType):
- """A trait for byte strings."""
-
- default_value = b''
- info_text = 'a bytes object'
-
- def validate(self, obj, value):
- if isinstance(value, bytes):
- return value
- self.error(obj, value)
-
+ self.error(obj, value)
+
+# We should always be explicit about whether we're using bytes or unicode, both
+# for Python 3 conversion and for reliable unicode behaviour on Python 2. So
+# we don't have a Str type.
+class Bytes(TraitType):
+ """A trait for byte strings."""
+
+ default_value = b''
+ info_text = 'a bytes object'
+
+ def validate(self, obj, value):
+ if isinstance(value, bytes):
+ return value
+ self.error(obj, value)
+
def from_string(self, s):
if self.allow_none and s == "None":
return None
@@ -2160,35 +2160,35 @@ class Bytes(TraitType):
FutureWarning)
break
return s.encode("utf8")
-
-
-class CBytes(Bytes):
- """A casting version of the byte string trait."""
-
- def validate(self, obj, value):
- try:
- return bytes(value)
+
+
+class CBytes(Bytes):
+ """A casting version of the byte string trait."""
+
+ def validate(self, obj, value):
+ try:
+ return bytes(value)
except Exception:
- self.error(obj, value)
-
-
-class Unicode(TraitType):
- """A trait for unicode strings."""
-
+ self.error(obj, value)
+
+
+class Unicode(TraitType):
+ """A trait for unicode strings."""
+
default_value = ''
- info_text = 'a unicode string'
-
- def validate(self, obj, value):
+ info_text = 'a unicode string'
+
+ def validate(self, obj, value):
if isinstance(value, str):
- return value
- if isinstance(value, bytes):
- try:
- return value.decode('ascii', 'strict')
- except UnicodeDecodeError:
- msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
- raise TraitError(msg.format(value, self.name, class_of(obj)))
- self.error(obj, value)
-
+ return value
+ if isinstance(value, bytes):
+ try:
+ return value.decode('ascii', 'strict')
+ except UnicodeDecodeError:
+ msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
+ raise TraitError(msg.format(value, self.name, class_of(obj)))
+ self.error(obj, value)
+
def from_string(self, s):
if self.allow_none and s == 'None':
return None
@@ -2204,66 +2204,66 @@ class Unicode(TraitType):
"You can use %r instead of %r if you require traitlets >=5." % (s, old_s),
FutureWarning)
return s
-
-class CUnicode(Unicode):
- """A casting version of the unicode trait."""
-
- def validate(self, obj, value):
- try:
+
+class CUnicode(Unicode):
+ """A casting version of the unicode trait."""
+
+ def validate(self, obj, value):
+ try:
return str(value)
except Exception:
- self.error(obj, value)
-
-
-class ObjectName(TraitType):
- """A string holding a valid object name in this version of Python.
-
- This does not check that the name exists in any scope."""
- info_text = "a valid object identifier in Python"
-
+ self.error(obj, value)
+
+
+class ObjectName(TraitType):
+ """A string holding a valid object name in this version of Python.
+
+ This does not check that the name exists in any scope."""
+ info_text = "a valid object identifier in Python"
+
coerce_str = staticmethod(lambda _,s: s)
-
- def validate(self, obj, value):
- value = self.coerce_str(obj, value)
-
+
+ def validate(self, obj, value):
+ value = self.coerce_str(obj, value)
+
if isinstance(value, str) and isidentifier(value):
- return value
- self.error(obj, value)
-
+ return value
+ self.error(obj, value)
+
def from_string(self, s):
if self.allow_none and s == 'None':
return None
return s
-class DottedObjectName(ObjectName):
- """A string holding a valid dotted object name in Python, such as A.b3._c"""
- def validate(self, obj, value):
- value = self.coerce_str(obj, value)
-
+class DottedObjectName(ObjectName):
+ """A string holding a valid dotted object name in Python, such as A.b3._c"""
+ def validate(self, obj, value):
+ value = self.coerce_str(obj, value)
+
if isinstance(value, str) and all(isidentifier(a)
for a in value.split('.')):
- return value
- self.error(obj, value)
-
-
-class Bool(TraitType):
- """A boolean (True, False) trait."""
-
- default_value = False
- info_text = 'a boolean'
-
- def validate(self, obj, value):
- if isinstance(value, bool):
- return value
+ return value
+ self.error(obj, value)
+
+
+class Bool(TraitType):
+ """A boolean (True, False) trait."""
+
+ default_value = False
+ info_text = 'a boolean'
+
+ def validate(self, obj, value):
+ if isinstance(value, bool):
+ return value
elif isinstance(value, int):
if value == 1:
return True
elif value == 0:
return False
- self.error(obj, value)
-
+ self.error(obj, value)
+
def from_string(self, s):
if self.allow_none and s == 'None':
return None
@@ -2274,32 +2274,32 @@ class Bool(TraitType):
return False
else:
raise ValueError("%r is not 1, 0, true, or false")
-
-
-class CBool(Bool):
- """A casting version of the boolean trait."""
-
- def validate(self, obj, value):
- try:
- return bool(value)
+
+
+class CBool(Bool):
+ """A casting version of the boolean trait."""
+
+ def validate(self, obj, value):
+ try:
+ return bool(value)
except Exception:
- self.error(obj, value)
-
-
-class Enum(TraitType):
- """An enum whose value must be in a given sequence."""
-
+ self.error(obj, value)
+
+
+class Enum(TraitType):
+ """An enum whose value must be in a given sequence."""
+
def __init__(self, values, default_value=Undefined, **kwargs):
- self.values = values
+ self.values = values
if kwargs.get('allow_none', False) and default_value is Undefined:
- default_value = None
+ default_value = None
super(Enum, self).__init__(default_value, **kwargs)
-
- def validate(self, obj, value):
- if value in self.values:
- return value
- self.error(obj, value)
-
+
+ def validate(self, obj, value):
+ if value in self.values:
+ return value
+ self.error(obj, value)
+
def _choices_str(self, as_rst=False):
""" Returns a description of the trait choices (not none)."""
choices = self.values
@@ -2310,12 +2310,12 @@ class Enum(TraitType):
return choices
def _info(self, as_rst=False):
- """ Returns a description of the trait."""
+ """ Returns a description of the trait."""
none = (' or %s' % ('`None`' if as_rst else 'None')
if self.allow_none else
'')
return 'any of %s%s' % (self._choices_str(as_rst), none)
-
+
def info(self):
return self._info(as_rst=False)
@@ -2329,21 +2329,21 @@ class Enum(TraitType):
return _safe_literal_eval(s)
-class CaselessStrEnum(Enum):
- """An enum of strings where the case should be ignored."""
+class CaselessStrEnum(Enum):
+ """An enum of strings where the case should be ignored."""
def __init__(self, values, default_value=Undefined, **kwargs):
super().__init__(values, default_value=default_value, **kwargs)
- def validate(self, obj, value):
+ def validate(self, obj, value):
if not isinstance(value, str):
- self.error(obj, value)
-
- for v in self.values:
- if v.lower() == value.lower():
- return v
- self.error(obj, value)
-
+ self.error(obj, value)
+
+ for v in self.values:
+ if v.lower() == value.lower():
+ return v
+ self.error(obj, value)
+
def _info(self, as_rst=False):
""" Returns a description of the trait."""
none = (' or %s' % ('`None`' if as_rst else 'None')
@@ -2408,52 +2408,52 @@ class FuzzyEnum(Enum):
return self._info(as_rst=True)
-class Container(Instance):
- """An instance of a container (list, set, etc.)
-
- To be subclassed by overriding klass.
- """
+class Container(Instance):
+ """An instance of a container (list, set, etc.)
+
+ To be subclassed by overriding klass.
+ """
- klass = None
- _cast_types = ()
- _valid_defaults = SequenceTypes
- _trait = None
+ klass = None
+ _cast_types = ()
+ _valid_defaults = SequenceTypes
+ _trait = None
_literal_from_string_pairs = ("[]", "()")
-
+
def __init__(self, trait=None, default_value=Undefined, **kwargs):
- """Create a container trait type from a list, set, or tuple.
-
- The default value is created by doing ``List(default_value)``,
- which creates a copy of the ``default_value``.
-
- ``trait`` can be specified, which restricts the type of elements
- in the container to that TraitType.
-
- If only one arg is given and it is not a Trait, it is taken as
- ``default_value``:
-
- ``c = List([1, 2, 3])``
-
- Parameters
- ----------
- trait : TraitType [ optional ]
- the type for restricting the contents of the Container. If unspecified,
- types are not checked.
- default_value : SequenceType [ optional ]
- The default value for the Trait. Must be list/tuple/set, and
- will be cast to the container type.
- allow_none : bool [ default False ]
- Whether to allow the value to be None
+ """Create a container trait type from a list, set, or tuple.
+
+ The default value is created by doing ``List(default_value)``,
+ which creates a copy of the ``default_value``.
+
+ ``trait`` can be specified, which restricts the type of elements
+ in the container to that TraitType.
+
+ If only one arg is given and it is not a Trait, it is taken as
+ ``default_value``:
+
+ ``c = List([1, 2, 3])``
+
+ Parameters
+ ----------
+ trait : TraitType [ optional ]
+ the type for restricting the contents of the Container. If unspecified,
+ types are not checked.
+ default_value : SequenceType [ optional ]
+ The default value for the Trait. Must be list/tuple/set, and
+ will be cast to the container type.
+ allow_none : bool [ default False ]
+ Whether to allow the value to be None
**kwargs : any
- further keys for extensions to the Trait (e.g. config)
-
- """
+ further keys for extensions to the Trait (e.g. config)
- # allow List([values]):
+ """
+
+ # allow List([values]):
if trait is not None and default_value is Undefined and not is_trait(trait):
- default_value = trait
- trait = None
-
+ default_value = trait
+ trait = None
+
if default_value is None and not kwargs.get("allow_none", False):
# improve backward-compatibility for possible subclasses
# specifying default_value=None as default,
@@ -2468,68 +2468,68 @@ class Container(Instance):
default_value = Undefined
if default_value is Undefined:
- args = ()
+ args = ()
elif default_value is None:
# default_value back on kwargs for super() to handle
args = ()
kwargs["default_value"] = None
- elif isinstance(default_value, self._valid_defaults):
- args = (default_value,)
- else:
+ elif isinstance(default_value, self._valid_defaults):
+ args = (default_value,)
+ else:
raise TypeError(
"default value of %s was %s" % (self.__class__.__name__, default_value)
)
-
- if is_trait(trait):
- if isinstance(trait, type):
+
+ if is_trait(trait):
+ if isinstance(trait, type):
warn(
"Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
" Passing types is deprecated in traitlets 4.1.",
DeprecationWarning,
stacklevel=3,
)
- self._trait = trait() if isinstance(trait, type) else trait
- elif trait is not None:
+ self._trait = trait() if isinstance(trait, type) else trait
+ elif trait is not None:
raise TypeError(
"`trait` must be a Trait or None, got %s" % repr_type(trait)
)
-
+
super(Container, self).__init__(klass=self.klass, args=args, **kwargs)
-
- def validate(self, obj, value):
- if isinstance(value, self._cast_types):
- value = self.klass(value)
- value = super(Container, self).validate(obj, value)
- if value is None:
- return value
-
- value = self.validate_elements(obj, value)
-
- return value
-
- def validate_elements(self, obj, value):
- validated = []
- if self._trait is None or isinstance(self._trait, Any):
- return value
- for v in value:
- try:
- v = self._trait._validate(obj, v)
+
+ def validate(self, obj, value):
+ if isinstance(value, self._cast_types):
+ value = self.klass(value)
+ value = super(Container, self).validate(obj, value)
+ if value is None:
+ return value
+
+ value = self.validate_elements(obj, value)
+
+ return value
+
+ def validate_elements(self, obj, value):
+ validated = []
+ if self._trait is None or isinstance(self._trait, Any):
+ return value
+ for v in value:
+ try:
+ v = self._trait._validate(obj, v)
except TraitError as error:
self.error(obj, v, error)
- else:
- validated.append(v)
- return self.klass(validated)
-
- def class_init(self, cls, name):
- if isinstance(self._trait, TraitType):
- self._trait.class_init(cls, None)
- super(Container, self).class_init(cls, name)
-
- def instance_init(self, obj):
- if isinstance(self._trait, TraitType):
- self._trait.instance_init(obj)
- super(Container, self).instance_init(obj)
-
+ else:
+ validated.append(v)
+ return self.klass(validated)
+
+ def class_init(self, cls, name):
+ if isinstance(self._trait, TraitType):
+ self._trait.class_init(cls, None)
+ super(Container, self).class_init(cls, name)
+
+ def instance_init(self, obj):
+ if isinstance(self._trait, TraitType):
+ self._trait.instance_init(obj)
+ super(Container, self).instance_init(obj)
+
def from_string(self, s):
"""Load value from a single string"""
if not isinstance(s, str):
@@ -2539,7 +2539,7 @@ class Container(Instance):
except Exception:
test = None
return self.validate(None, test)
-
+
def from_string_list(self, s_list):
"""Return the value from a list of config strings
@@ -2588,11 +2588,11 @@ class Container(Instance):
return s
-class List(Container):
- """An instance of a Python list."""
- klass = list
- _cast_types = (tuple,)
-
+class List(Container):
+ """An instance of a Python list."""
+ klass = list
+ _cast_types = (tuple,)
+
def __init__(
self,
trait=None,
@@ -2601,64 +2601,64 @@ class List(Container):
maxlen=sys.maxsize,
**kwargs,
):
- """Create a List trait type from a list, set, or tuple.
-
- The default value is created by doing ``list(default_value)``,
- which creates a copy of the ``default_value``.
-
- ``trait`` can be specified, which restricts the type of elements
- in the container to that TraitType.
-
- If only one arg is given and it is not a Trait, it is taken as
- ``default_value``:
-
- ``c = List([1, 2, 3])``
-
- Parameters
- ----------
- trait : TraitType [ optional ]
- the type for restricting the contents of the Container.
- If unspecified, types are not checked.
- default_value : SequenceType [ optional ]
- The default value for the Trait. Must be list/tuple/set, and
- will be cast to the container type.
- minlen : Int [ default 0 ]
- The minimum length of the input list
- maxlen : Int [ default sys.maxsize ]
- The maximum length of the input list
- """
- self._minlen = minlen
- self._maxlen = maxlen
- super(List, self).__init__(trait=trait, default_value=default_value,
+ """Create a List trait type from a list, set, or tuple.
+
+ The default value is created by doing ``list(default_value)``,
+ which creates a copy of the ``default_value``.
+
+ ``trait`` can be specified, which restricts the type of elements
+ in the container to that TraitType.
+
+ If only one arg is given and it is not a Trait, it is taken as
+ ``default_value``:
+
+ ``c = List([1, 2, 3])``
+
+ Parameters
+ ----------
+ trait : TraitType [ optional ]
+ the type for restricting the contents of the Container.
+ If unspecified, types are not checked.
+ default_value : SequenceType [ optional ]
+ The default value for the Trait. Must be list/tuple/set, and
+ will be cast to the container type.
+ minlen : Int [ default 0 ]
+ The minimum length of the input list
+ maxlen : Int [ default sys.maxsize ]
+ The maximum length of the input list
+ """
+ self._minlen = minlen
+ self._maxlen = maxlen
+ super(List, self).__init__(trait=trait, default_value=default_value,
**kwargs)
-
- def length_error(self, obj, value):
- e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \
- % (self.name, class_of(obj), self._minlen, self._maxlen, value)
- raise TraitError(e)
-
- def validate_elements(self, obj, value):
- length = len(value)
- if length < self._minlen or length > self._maxlen:
- self.length_error(obj, value)
-
- return super(List, self).validate_elements(obj, value)
-
+
+ def length_error(self, obj, value):
+ e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \
+ % (self.name, class_of(obj), self._minlen, self._maxlen, value)
+ raise TraitError(e)
+
+ def validate_elements(self, obj, value):
+ length = len(value)
+ if length < self._minlen or length > self._maxlen:
+ self.length_error(obj, value)
+
+ return super(List, self).validate_elements(obj, value)
+
def set(self, obj, value):
if isinstance(value, str):
return super().set(obj, [value])
else:
return super().set(obj, value)
-
-class Set(List):
- """An instance of a Python set."""
- klass = set
- _cast_types = (tuple, list)
-
+
+class Set(List):
+ """An instance of a Python set."""
+ klass = set
+ _cast_types = (tuple, list)
+
_literal_from_string_pairs = ("[]", "()", "{}")
- # Redefine __init__ just to make the docstring more accurate.
+ # Redefine __init__ just to make the docstring more accurate.
def __init__(
self,
trait=None,
@@ -2667,84 +2667,84 @@ class Set(List):
maxlen=sys.maxsize,
**kwargs,
):
- """Create a Set trait type from a list, set, or tuple.
-
- The default value is created by doing ``set(default_value)``,
- which creates a copy of the ``default_value``.
-
- ``trait`` can be specified, which restricts the type of elements
- in the container to that TraitType.
-
- If only one arg is given and it is not a Trait, it is taken as
- ``default_value``:
-
- ``c = Set({1, 2, 3})``
-
- Parameters
- ----------
- trait : TraitType [ optional ]
- the type for restricting the contents of the Container.
- If unspecified, types are not checked.
- default_value : SequenceType [ optional ]
- The default value for the Trait. Must be list/tuple/set, and
- will be cast to the container type.
- minlen : Int [ default 0 ]
- The minimum length of the input list
- maxlen : Int [ default sys.maxsize ]
- The maximum length of the input list
- """
+ """Create a Set trait type from a list, set, or tuple.
+
+ The default value is created by doing ``set(default_value)``,
+ which creates a copy of the ``default_value``.
+
+ ``trait`` can be specified, which restricts the type of elements
+ in the container to that TraitType.
+
+ If only one arg is given and it is not a Trait, it is taken as
+ ``default_value``:
+
+ ``c = Set({1, 2, 3})``
+
+ Parameters
+ ----------
+ trait : TraitType [ optional ]
+ the type for restricting the contents of the Container.
+ If unspecified, types are not checked.
+ default_value : SequenceType [ optional ]
+ The default value for the Trait. Must be list/tuple/set, and
+ will be cast to the container type.
+ minlen : Int [ default 0 ]
+ The minimum length of the input list
+ maxlen : Int [ default sys.maxsize ]
+ The maximum length of the input list
+ """
super(Set, self).__init__(trait, default_value, minlen, maxlen, **kwargs)
-
+
def default_value_repr(self):
# Ensure default value is sorted for a reproducible build
list_repr = repr(sorted(self.make_dynamic_default()))
if list_repr == '[]':
return 'set()'
return '{'+list_repr[1:-1]+'}'
-
-class Tuple(Container):
- """An instance of a Python tuple."""
- klass = tuple
- _cast_types = (list,)
-
+class Tuple(Container):
+ """An instance of a Python tuple."""
+
+ klass = tuple
+ _cast_types = (list,)
+
def __init__(self, *traits, **kwargs):
- """Create a tuple from a list, set, or tuple.
-
- Create a fixed-type tuple with Traits:
-
- ``t = Tuple(Int(), Str(), CStr())``
-
- would be length 3, with Int,Str,CStr for each element.
-
- If only one arg is given and it is not a Trait, it is taken as
- default_value:
-
- ``t = Tuple((1, 2, 3))``
-
- Otherwise, ``default_value`` *must* be specified by keyword.
-
- Parameters
- ----------
+ """Create a tuple from a list, set, or tuple.
+
+ Create a fixed-type tuple with Traits:
+
+ ``t = Tuple(Int(), Str(), CStr())``
+
+ would be length 3, with Int,Str,CStr for each element.
+
+ If only one arg is given and it is not a Trait, it is taken as
+ default_value:
+
+ ``t = Tuple((1, 2, 3))``
+
+ Otherwise, ``default_value`` *must* be specified by keyword.
+
+ Parameters
+ ----------
*traits : TraitTypes [ optional ]
- the types for restricting the contents of the Tuple. If unspecified,
- types are not checked. If specified, then each positional argument
- corresponds to an element of the tuple. Tuples defined with traits
- are of fixed length.
- default_value : SequenceType [ optional ]
- The default value for the Tuple. Must be list/tuple/set, and
- will be cast to a tuple. If ``traits`` are specified,
- ``default_value`` must conform to the shape and type they specify.
+ the types for restricting the contents of the Tuple. If unspecified,
+ types are not checked. If specified, then each positional argument
+ corresponds to an element of the tuple. Tuples defined with traits
+ are of fixed length.
+ default_value : SequenceType [ optional ]
+ The default value for the Tuple. Must be list/tuple/set, and
+ will be cast to a tuple. If ``traits`` are specified,
+ ``default_value`` must conform to the shape and type they specify.
**kwargs
Other kwargs passed to `Container`
- """
+ """
default_value = kwargs.pop("default_value", Undefined)
- # allow Tuple((values,)):
- if len(traits) == 1 and default_value is Undefined and not is_trait(traits[0]):
- default_value = traits[0]
- traits = ()
-
+ # allow Tuple((values,)):
+ if len(traits) == 1 and default_value is Undefined and not is_trait(traits[0]):
+ default_value = traits[0]
+ traits = ()
+
if default_value is None and not kwargs.get("allow_none", False):
# improve backward-compatibility for possible subclasses
# specifying default_value=None as default,
@@ -2758,22 +2758,22 @@ class Tuple(Container):
)
default_value = Undefined
- if default_value is Undefined:
- args = ()
+ if default_value is Undefined:
+ args = ()
elif default_value is None:
# default_value back on kwargs for super() to handle
args = ()
kwargs["default_value"] = None
- elif isinstance(default_value, self._valid_defaults):
- args = (default_value,)
- else:
+ elif isinstance(default_value, self._valid_defaults):
+ args = (default_value,)
+ else:
raise TypeError(
"default value of %s was %s" % (self.__class__.__name__, default_value)
)
-
- self._traits = []
- for trait in traits:
- if isinstance(trait, type):
+
+ self._traits = []
+ for trait in traits:
+ if isinstance(trait, type):
warn(
"Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
" Passing types is deprecated in traitlets 4.1.",
@@ -2782,12 +2782,12 @@ class Tuple(Container):
)
trait = trait()
self._traits.append(trait)
-
+
if self._traits and (default_value is None or default_value is Undefined):
- # don't allow default to be an empty container if length is specified
- args = None
+ # don't allow default to be an empty container if length is specified
+ args = None
super(Container, self).__init__(klass=self.klass, args=args, **kwargs)
-
+
def item_from_string(self, s, index):
"""Cast a single item from a string
@@ -2799,41 +2799,41 @@ class Tuple(Container):
return s
return self._traits[index].from_string(s)
- def validate_elements(self, obj, value):
- if not self._traits:
- # nothing to validate
- return value
- if len(value) != len(self._traits):
- e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \
- % (self.name, class_of(obj), len(self._traits), repr_type(value))
- raise TraitError(e)
-
- validated = []
- for t, v in zip(self._traits, value):
- try:
- v = t._validate(obj, v)
+ def validate_elements(self, obj, value):
+ if not self._traits:
+ # nothing to validate
+ return value
+ if len(value) != len(self._traits):
+ e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \
+ % (self.name, class_of(obj), len(self._traits), repr_type(value))
+ raise TraitError(e)
+
+ validated = []
+ for t, v in zip(self._traits, value):
+ try:
+ v = t._validate(obj, v)
except TraitError as error:
self.error(obj, v, error)
- else:
- validated.append(v)
- return tuple(validated)
-
- def class_init(self, cls, name):
- for trait in self._traits:
- if isinstance(trait, TraitType):
- trait.class_init(cls, None)
- super(Container, self).class_init(cls, name)
-
- def instance_init(self, obj):
- for trait in self._traits:
- if isinstance(trait, TraitType):
- trait.instance_init(obj)
- super(Container, self).instance_init(obj)
-
-
-class Dict(Instance):
+ else:
+ validated.append(v)
+ return tuple(validated)
+
+ def class_init(self, cls, name):
+ for trait in self._traits:
+ if isinstance(trait, TraitType):
+ trait.class_init(cls, None)
+ super(Container, self).class_init(cls, name)
+
+ def instance_init(self, obj):
+ for trait in self._traits:
+ if isinstance(trait, TraitType):
+ trait.instance_init(obj)
+ super(Container, self).instance_init(obj)
+
+
+class Dict(Instance):
"""An instance of a Python dict.
-
+
One or more traits can be passed to the constructor
to validate the keys and/or values of the dict.
If you need more detailed validation,
@@ -2851,10 +2851,10 @@ class Dict(Instance):
def __init__(self, value_trait=None, per_key_traits=None, key_trait=None, default_value=Undefined,
**kwargs):
"""Create a dict trait type from a Python dict.
-
- The default value is created by doing ``dict(default_value)``,
- which creates a copy of the ``default_value``.
-
+
+ The default value is created by doing ``dict(default_value)``,
+ which creates a copy of the ``default_value``.
+
Parameters
----------
value_trait : TraitType [ optional ]
@@ -2876,15 +2876,15 @@ class Dict(Instance):
--------
>>> d = Dict(Unicode())
a dict whose values must be text
-
+
>>> d2 = Dict(per_key_traits={"n": Integer(), "s": Unicode()})
d2['n'] must be an integer
d2['s'] must be text
-
+
>>> d3 = Dict(value_trait=Integer(), key_trait=Unicode())
d3's keys must be text
d3's values must be integers
- """
+ """
# handle deprecated keywords
trait = kwargs.pop('trait', None)
@@ -2908,40 +2908,40 @@ class Dict(Instance):
stacklevel=2,
)
- # Handling positional arguments
+ # Handling positional arguments
if default_value is Undefined and value_trait is not None:
if not is_trait(value_trait):
default_value = value_trait
value_trait = None
-
+
if key_trait is None and per_key_traits is not None:
if is_trait(per_key_traits):
key_trait = per_key_traits
per_key_traits = None
- # Handling default value
- if default_value is Undefined:
- default_value = {}
- if default_value is None:
- args = None
- elif isinstance(default_value, dict):
- args = (default_value,)
- elif isinstance(default_value, SequenceTypes):
- args = (default_value,)
- else:
- raise TypeError('default value of Dict was %s' % default_value)
-
- # Case where a type of TraitType is provided rather than an instance
+ # Handling default value
+ if default_value is Undefined:
+ default_value = {}
+ if default_value is None:
+ args = None
+ elif isinstance(default_value, dict):
+ args = (default_value,)
+ elif isinstance(default_value, SequenceTypes):
+ args = (default_value,)
+ else:
+ raise TypeError('default value of Dict was %s' % default_value)
+
+ # Case where a type of TraitType is provided rather than an instance
if is_trait(value_trait):
if isinstance(value_trait, type):
warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
" Passing types is deprecated in traitlets 4.1.",
- DeprecationWarning, stacklevel=2)
+ DeprecationWarning, stacklevel=2)
value_trait = value_trait()
self._value_trait = value_trait
elif value_trait is not None:
raise TypeError("`value_trait` must be a Trait or None, got %s" % repr_type(value_trait))
-
+
if is_trait(key_trait):
if isinstance(key_trait, type):
warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
@@ -2951,32 +2951,32 @@ class Dict(Instance):
self._key_trait = key_trait
elif key_trait is not None:
raise TypeError("`key_trait` must be a Trait or None, got %s" % repr_type(key_trait))
-
+
self._per_key_traits = per_key_traits
super(Dict, self).__init__(klass=dict, args=args, **kwargs)
-
+
def element_error(self, obj, element, validator, side='Values'):
e = side + " of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
- % (self.name, class_of(obj), validator.info(), repr_type(element))
- raise TraitError(e)
-
- def validate(self, obj, value):
- value = super(Dict, self).validate(obj, value)
- if value is None:
- return value
- value = self.validate_elements(obj, value)
- return value
-
- def validate_elements(self, obj, value):
+ % (self.name, class_of(obj), validator.info(), repr_type(element))
+ raise TraitError(e)
+
+ def validate(self, obj, value):
+ value = super(Dict, self).validate(obj, value)
+ if value is None:
+ return value
+ value = self.validate_elements(obj, value)
+ return value
+
+ def validate_elements(self, obj, value):
per_key_override = self._per_key_traits or {}
key_trait = self._key_trait
value_trait = self._value_trait
if not (key_trait or value_trait or per_key_override):
- return value
+ return value
- validated = {}
- for key in value:
+ validated = {}
+ for key in value:
v = value[key]
if key_trait:
try:
@@ -2991,28 +2991,28 @@ class Dict(Instance):
self.element_error(obj, v, active_value_trait, 'Values')
validated[key] = v
- return self.klass(validated)
-
- def class_init(self, cls, name):
+ return self.klass(validated)
+
+ def class_init(self, cls, name):
if isinstance(self._value_trait, TraitType):
self._value_trait.class_init(cls, None)
if isinstance(self._key_trait, TraitType):
self._key_trait.class_init(cls, None)
if self._per_key_traits is not None:
for trait in self._per_key_traits.values():
- trait.class_init(cls, None)
- super(Dict, self).class_init(cls, name)
-
- def instance_init(self, obj):
+ trait.class_init(cls, None)
+ super(Dict, self).class_init(cls, name)
+
+ def instance_init(self, obj):
if isinstance(self._value_trait, TraitType):
self._value_trait.instance_init(obj)
if isinstance(self._key_trait, TraitType):
self._key_trait.instance_init(obj)
if self._per_key_traits is not None:
for trait in self._per_key_traits.values():
- trait.instance_init(obj)
- super(Dict, self).instance_init(obj)
-
+ trait.instance_init(obj)
+ super(Dict, self).instance_init(obj)
+
def from_string(self, s):
"""Load value from a single string"""
if not isinstance(s, str):
@@ -3024,7 +3024,7 @@ class Dict(Instance):
if isinstance(test, dict):
return test
raise
-
+
def from_string_list(self, s_list):
"""Return a dict from a list of config strings.
@@ -3086,24 +3086,24 @@ class Dict(Instance):
return {key: value}
-class TCPAddress(TraitType):
- """A trait for an (ip, port) tuple.
-
- This allows for both IPv4 IP addresses as well as hostnames.
- """
-
- default_value = ('127.0.0.1', 0)
- info_text = 'an (ip, port) tuple'
-
- def validate(self, obj, value):
- if isinstance(value, tuple):
- if len(value) == 2:
+class TCPAddress(TraitType):
+ """A trait for an (ip, port) tuple.
+
+ This allows for both IPv4 IP addresses as well as hostnames.
+ """
+
+ default_value = ('127.0.0.1', 0)
+ info_text = 'an (ip, port) tuple'
+
+ def validate(self, obj, value):
+ if isinstance(value, tuple):
+ if len(value) == 2:
if isinstance(value[0], str) and isinstance(value[1], int):
- port = value[1]
- if port >= 0 and port <= 65535:
- return value
- self.error(obj, value)
-
+ port = value[1]
+ if port >= 0 and port <= 65535:
+ return value
+ self.error(obj, value)
+
def from_string(self, s):
if self.allow_none and s == 'None':
return None
@@ -3114,19 +3114,19 @@ class TCPAddress(TraitType):
return (ip, port)
-class CRegExp(TraitType):
- """A casting compiled regular expression trait.
-
- Accepts both strings and compiled regular expressions. The resulting
- attribute will be a compiled regular expression."""
-
- info_text = 'a regular expression'
-
- def validate(self, obj, value):
- try:
- return re.compile(value)
+class CRegExp(TraitType):
+ """A casting compiled regular expression trait.
+
+ Accepts both strings and compiled regular expressions. The resulting
+ attribute will be a compiled regular expression."""
+
+ info_text = 'a regular expression'
+
+ def validate(self, obj, value):
+ try:
+ return re.compile(value)
except Exception:
- self.error(obj, value)
+ self.error(obj, value)
class UseEnum(TraitType):
diff --git a/contrib/python/traitlets/py3/traitlets/utils/getargspec.py b/contrib/python/traitlets/py3/traitlets/utils/getargspec.py
index 086b21999a..22511437bd 100644
--- a/contrib/python/traitlets/py3/traitlets/utils/getargspec.py
+++ b/contrib/python/traitlets/py3/traitlets/utils/getargspec.py
@@ -1,19 +1,19 @@
-"""
- getargspec excerpted from:
-
- sphinx.util.inspect
- ~~~~~~~~~~~~~~~~~~~
- Helpers for inspecting Python modules.
- :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import inspect
-
-# Unmodified from sphinx below this line
-
+"""
+ getargspec excerpted from:
+
+ sphinx.util.inspect
+ ~~~~~~~~~~~~~~~~~~~
+ Helpers for inspecting Python modules.
+ :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import inspect
+
+# Unmodified from sphinx below this line
+
from functools import partial
-
+
def getargspec(func):
"""Like inspect.getargspec but supports functools.partial as well."""
if inspect.ismethod(func):
@@ -29,12 +29,12 @@ def getargspec(func):
args = args[len(func.args):]
for arg in func.keywords or ():
try:
- i = args.index(arg) - len(args)
- del args[i]
- try:
+ i = args.index(arg) - len(args)
+ del args[i]
+ try:
del defaults[i]
- except IndexError:
- pass
+ except IndexError:
+ pass
except ValueError: # must be a kwonly arg
i = kwoargs.index(arg)
del kwoargs[i]
diff --git a/contrib/python/traitlets/py3/traitlets/utils/importstring.py b/contrib/python/traitlets/py3/traitlets/utils/importstring.py
index 6d9e0986cd..defad8f183 100644
--- a/contrib/python/traitlets/py3/traitlets/utils/importstring.py
+++ b/contrib/python/traitlets/py3/traitlets/utils/importstring.py
@@ -1,38 +1,38 @@
-"""
-A simple utility to import something by its string name.
-"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-
-def import_item(name):
- """Import and return ``bar`` given the string ``foo.bar``.
-
- Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
- executing the code ``from foo import bar``.
-
- Parameters
- ----------
- name : string
+"""
+A simple utility to import something by its string name.
+"""
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+
+def import_item(name):
+ """Import and return ``bar`` given the string ``foo.bar``.
+
+ Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
+ executing the code ``from foo import bar``.
+
+ Parameters
+ ----------
+ name : string
The fully qualified name of the module/package being imported.
-
- Returns
- -------
- mod : module object
+
+ Returns
+ -------
+ mod : module object
The module that was imported.
- """
+ """
if not isinstance(name, str):
- raise TypeError("import_item accepts strings, not '%s'." % type(name))
- parts = name.rsplit('.', 1)
- if len(parts) == 2:
- # called with 'foo.bar....'
- package, obj = parts
- module = __import__(package, fromlist=[obj])
- try:
- pak = getattr(module, obj)
- except AttributeError:
- raise ImportError('No module named %s' % obj)
- return pak
- else:
- # called with un-dotted string
- return __import__(parts[0])
+ raise TypeError("import_item accepts strings, not '%s'." % type(name))
+ parts = name.rsplit('.', 1)
+ if len(parts) == 2:
+ # called with 'foo.bar....'
+ package, obj = parts
+ module = __import__(package, fromlist=[obj])
+ try:
+ pak = getattr(module, obj)
+ except AttributeError:
+ raise ImportError('No module named %s' % obj)
+ return pak
+ else:
+ # called with un-dotted string
+ return __import__(parts[0])
diff --git a/contrib/python/traitlets/py3/traitlets/utils/sentinel.py b/contrib/python/traitlets/py3/traitlets/utils/sentinel.py
index de6b3e508f..0760bec8b5 100644
--- a/contrib/python/traitlets/py3/traitlets/utils/sentinel.py
+++ b/contrib/python/traitlets/py3/traitlets/utils/sentinel.py
@@ -1,20 +1,20 @@
-"""Sentinel class for constants with useful reprs"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
+"""Sentinel class for constants with useful reprs"""
-class Sentinel(object):
-
- def __init__(self, name, module, docstring=None):
- self.name = name
- self.module = module
- if docstring:
- self.__doc__ = docstring
-
- def __repr__(self):
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+
+class Sentinel(object):
+
+ def __init__(self, name, module, docstring=None):
+ self.name = name
+ self.module = module
+ if docstring:
+ self.__doc__ = docstring
+
+ def __repr__(self):
return str(self.module) + '.' + self.name
-
+
def __copy__(self):
return self
diff --git a/contrib/python/traitlets/py3/ya.make b/contrib/python/traitlets/py3/ya.make
index be00a1bd39..46980f21b3 100644
--- a/contrib/python/traitlets/py3/ya.make
+++ b/contrib/python/traitlets/py3/ya.make
@@ -1,49 +1,49 @@
# Generated by devtools/yamaker (pypi).
PY3_LIBRARY()
-
+
PROVIDES(python_traitlets)
OWNER(borman nslus g:python-contrib)
-
+
VERSION(5.1.1)
LICENSE(BSD-3-Clause)
NO_LINT()
-
-PY_SRCS(
- TOP_LEVEL
- traitlets/__init__.py
- traitlets/_version.py
- traitlets/config/__init__.py
- traitlets/config/application.py
- traitlets/config/configurable.py
- traitlets/config/loader.py
- traitlets/config/manager.py
+
+PY_SRCS(
+ TOP_LEVEL
+ traitlets/__init__.py
+ traitlets/_version.py
+ traitlets/config/__init__.py
+ traitlets/config/application.py
+ traitlets/config/configurable.py
+ traitlets/config/loader.py
+ traitlets/config/manager.py
traitlets/config/sphinxdoc.py
- traitlets/log.py
+ traitlets/log.py
traitlets/tests/__init__.py
traitlets/tests/_warnings.py
traitlets/tests/utils.py
- traitlets/traitlets.py
- traitlets/utils/__init__.py
+ traitlets/traitlets.py
+ traitlets/utils/__init__.py
traitlets/utils/bunch.py
traitlets/utils/decorators.py
traitlets/utils/descriptions.py
- traitlets/utils/getargspec.py
- traitlets/utils/importstring.py
- traitlets/utils/sentinel.py
+ traitlets/utils/getargspec.py
+ traitlets/utils/importstring.py
+ traitlets/utils/sentinel.py
traitlets/utils/text.py
-)
-
+)
+
RESOURCE_FILES(
PREFIX contrib/python/traitlets/py3/
.dist-info/METADATA
.dist-info/top_level.txt
)
-END()
+END()
RECURSE_FOR_TESTS(
tests
diff --git a/contrib/python/traitlets/ya.make b/contrib/python/traitlets/ya.make
index 934eb39823..3156aae8c5 100644
--- a/contrib/python/traitlets/ya.make
+++ b/contrib/python/traitlets/ya.make
@@ -1,5 +1,5 @@
PY23_LIBRARY()
-
+
LICENSE(Service-Py23-Proxy)
OWNER(g:python-contrib)
@@ -12,7 +12,7 @@ ENDIF()
NO_LINT()
-END()
+END()
RECURSE(
py2
diff --git a/contrib/python/ya.make b/contrib/python/ya.make
index fcbdd423b0..d01ced9f3a 100644
--- a/contrib/python/ya.make
+++ b/contrib/python/ya.make
@@ -1,4 +1,4 @@
-OWNER(g:contrib g:python-contrib)
+OWNER(g:contrib g:python-contrib)
RECURSE(
absl-py
@@ -37,7 +37,7 @@ RECURSE(
aiosmtplib
aiosocksy
aiosqlite
- aiotg
+ aiotg
aiounittest
aiozipkin
aiozk
@@ -149,7 +149,7 @@ RECURSE(
cherrypy-cors
ciso8601
clang
- clang/example
+ clang/example
cli-helpers
click
click-didyoumean
@@ -161,12 +161,12 @@ RECURSE(
cloudpickle
color
colorama
- coloredlogs
+ coloredlogs
colorhash
colorlog
commoncode
commonmark
- ConfigArgParse
+ ConfigArgParse
configobj
configparser
confluent-kafka
@@ -356,7 +356,7 @@ RECURSE(
fakeredis
falcon
falcon-cors
- falcon-multipart
+ falcon-multipart
fallocate
fancycompleter
fastapi
@@ -551,7 +551,7 @@ RECURSE(
jmespath
json-rpc
json2html
- jsondiff
+ jsondiff
jsonfield
jsonobject
jsonpath-rw
@@ -640,7 +640,7 @@ RECURSE(
mpi4py
mpmath
msal
- msgpack
+ msgpack
mujson
multidict
multitasking
@@ -736,7 +736,7 @@ RECURSE(
pexpect
pgcli
PGPy
- pgspecial
+ pgspecial
phonenumbers
pickleshare
pika
@@ -801,8 +801,8 @@ RECURSE(
pycparser
pycrypto
pycryptodome
- pycurl
- pycurl/example
+ pycurl
+ pycurl/example
pydantic
pydash
PyDispatcher
@@ -824,7 +824,7 @@ RECURSE(
pyjavaproperties
PyJWT
pykdtree
- pyketama
+ pyketama
pylev
pylint
pylxd
@@ -840,7 +840,7 @@ RECURSE(
pynetbox
pyodbc
pyOpenSSL
- pyparsing
+ pyparsing
PyPDF2
pyperclip
PyPika
@@ -987,7 +987,7 @@ RECURSE(
semver
Send2Trash
sentinels
- sentry-sdk
+ sentry-sdk
service-identity
setproctitle
setuptools
@@ -1097,7 +1097,7 @@ RECURSE(
typed-ast
typeguard
typer
- typing
+ typing
typing-extensions
typing-inspect
tzlocal
@@ -1119,31 +1119,31 @@ RECURSE(
user-agents
uvicorn
uvloop
- uwsgi
- uwsgi/bin
- uwsgi/examples
+ uwsgi
+ uwsgi/bin
+ uwsgi/examples
uwsgiconf
- validators
+ validators
validr
- vcrpy
+ vcrpy
viberbot
- vine
+ vine
visitor
- voluptuous
+ voluptuous
w3lib
waitress
walrus
Wand
wasabi
- watchdog
+ watchdog
watchgod
- wcwidth
+ wcwidth
webargs
webauthn
webcolors
webencodings
WebOb
- websocket-client
+ websocket-client
websockets
webstruct
WebTest
@@ -1154,31 +1154,31 @@ RECURSE(
whitenoise
whodap
wmctrl
- wrapt
- ws4py
+ wrapt
+ ws4py
wsgi-intercept
- wsgi-profiler
+ wsgi-profiler
wsproto
wtf-peewee
- WTForms
- WTForms-JSON
- wurlitzer
+ WTForms
+ WTForms-JSON
+ wurlitzer
xhtml2pdf
xlrd
- XlsxWriter
+ XlsxWriter
xlutils
- xlwt
+ xlwt
xmlsec
- xmltodict
+ xmltodict
xxhash
yandex-pgmigrate
- yappi
- yarl
+ yappi
+ yarl
yfinance
youtube-dl
yoyo-migrations
yt-dlp
- zake
+ zake
zeep
zero-downtime-migrations
zope.event
@@ -1186,27 +1186,27 @@ RECURSE(
zope.schema
zstandard
)
-
+
IF (OS_WINDOWS)
RECURSE(
win_unicode_console
)
ENDIF()
-IF (OS_DARWIN)
- RECURSE(
- appnope
- )
-ENDIF ()
-
-IF (OS_LINUX)
- RECURSE(
- pyroute2
- )
-
+IF (OS_DARWIN)
+ RECURSE(
+ appnope
+ )
+ENDIF ()
+
+IF (OS_LINUX)
+ RECURSE(
+ pyroute2
+ )
+
IF (OS_SDK != "ubuntu-12")
- RECURSE(
- cysystemd
- )
- ENDIF()
-ENDIF ()
+ RECURSE(
+ cysystemd
+ )
+ ENDIF()
+ENDIF ()
diff --git a/contrib/restricted/boost/arcadia_test/ya.make b/contrib/restricted/boost/arcadia_test/ya.make
index 79a9340cfd..9d9ba18de9 100644
--- a/contrib/restricted/boost/arcadia_test/ya.make
+++ b/contrib/restricted/boost/arcadia_test/ya.make
@@ -9,7 +9,7 @@ SRCS(
)
PEERDIR(
- contrib/restricted/boost
+ contrib/restricted/boost
)
END()
diff --git a/contrib/restricted/boost/boost_common.inc b/contrib/restricted/boost/boost_common.inc
index 6b6be28d4d..892bae5b39 100644
--- a/contrib/restricted/boost/boost_common.inc
+++ b/contrib/restricted/boost/boost_common.inc
@@ -4,19 +4,19 @@ NO_UTIL()
LICENSE(BSL-1.0)
-SET(BOOST_ROOT contrib/restricted/boost)
-
-PEERDIR(
- ${BOOST_ROOT}
-)
-
-ADDINCL(
- ${BOOST_ROOT}/boost/predef
-)
-
-# XXX: fix selective checkout
-SRCDIR(${BOOST_ROOT}/boost)
-
+SET(BOOST_ROOT contrib/restricted/boost)
+
+PEERDIR(
+ ${BOOST_ROOT}
+)
+
+ADDINCL(
+ ${BOOST_ROOT}/boost/predef
+)
+
+# XXX: fix selective checkout
+SRCDIR(${BOOST_ROOT}/boost)
+
IF (DYNAMIC_BOOST)
CFLAGS(
-DBOOST_ATOMIC_DYN_LINK=1
diff --git a/contrib/restricted/boost/libs/asio/ya.make b/contrib/restricted/boost/libs/asio/ya.make
index 70a3dc72a6..127ba91c55 100644
--- a/contrib/restricted/boost/libs/asio/ya.make
+++ b/contrib/restricted/boost/libs/asio/ya.make
@@ -1,23 +1,23 @@
-LIBRARY()
-
+LIBRARY()
+
WITHOUT_LICENSE_TEXTS()
LICENSE(BSL-1.0)
-VERSION(1.67)
-
+VERSION(1.67)
+
OWNER(
antoshkka
g:cpp-committee
g:cpp-contrib
)
-
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
-
-PEERDIR(
- ${BOOST_ROOT}/libs/date_time
- ${BOOST_ROOT}/libs/system
- contrib/libs/openssl
-)
-
-END()
+
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+
+PEERDIR(
+ ${BOOST_ROOT}/libs/date_time
+ ${BOOST_ROOT}/libs/system
+ contrib/libs/openssl
+)
+
+END()
diff --git a/contrib/restricted/boost/libs/atomic/ya.make b/contrib/restricted/boost/libs/atomic/ya.make
index 9fd7a7f2bd..7bbe714418 100644
--- a/contrib/restricted/boost/libs/atomic/ya.make
+++ b/contrib/restricted/boost/libs/atomic/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCS(
src/lockpool.cpp
diff --git a/contrib/restricted/boost/libs/chrono/ya.make b/contrib/restricted/boost/libs/chrono/ya.make
index 5747d6c2ec..e9f2172645 100644
--- a/contrib/restricted/boost/libs/chrono/ya.make
+++ b/contrib/restricted/boost/libs/chrono/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCS(
src/chrono.cpp
diff --git a/contrib/restricted/boost/libs/container/ya.make b/contrib/restricted/boost/libs/container/ya.make
index c3c5db2a1c..bc9a2cd150 100644
--- a/contrib/restricted/boost/libs/container/ya.make
+++ b/contrib/restricted/boost/libs/container/ya.make
@@ -13,7 +13,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCS(
src/alloc_lib.c
diff --git a/contrib/restricted/boost/libs/context/ya.make b/contrib/restricted/boost/libs/context/ya.make
index b5587231b0..0ed9d696fe 100644
--- a/contrib/restricted/boost/libs/context/ya.make
+++ b/contrib/restricted/boost/libs/context/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
CFLAGS(
-DBOOST_CONTEXT_SOURCE
diff --git a/contrib/restricted/boost/libs/coroutine/ya.make b/contrib/restricted/boost/libs/coroutine/ya.make
index a7ded84844..b0093b9475 100644
--- a/contrib/restricted/boost/libs/coroutine/ya.make
+++ b/contrib/restricted/boost/libs/coroutine/ya.make
@@ -10,10 +10,10 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
PEERDIR(
- ${BOOST_ROOT}/libs/context
+ ${BOOST_ROOT}/libs/context
)
IF (OS_WINDOWS)
diff --git a/contrib/restricted/boost/libs/date_time/ya.make b/contrib/restricted/boost/libs/date_time/ya.make
index 0864ffc302..21ad128e07 100644
--- a/contrib/restricted/boost/libs/date_time/ya.make
+++ b/contrib/restricted/boost/libs/date_time/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCS(
src/gregorian/date_generators.cpp
diff --git a/contrib/restricted/boost/libs/exception/ya.make b/contrib/restricted/boost/libs/exception/ya.make
index 8f5901b2f2..bef34a6144 100644
--- a/contrib/restricted/boost/libs/exception/ya.make
+++ b/contrib/restricted/boost/libs/exception/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCS(
src/clone_current_exception_non_intrusive.cpp
diff --git a/contrib/restricted/boost/libs/filesystem/ya.make b/contrib/restricted/boost/libs/filesystem/ya.make
index 4222417c2d..bfad363675 100644
--- a/contrib/restricted/boost/libs/filesystem/ya.make
+++ b/contrib/restricted/boost/libs/filesystem/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
IF (DYNAMIC_BOOST)
CFLAGS(
@@ -22,9 +22,9 @@ ELSE()
)
ENDIF()
-PEERDIR(
- ${BOOST_ROOT}/libs/system
-)
+PEERDIR(
+ ${BOOST_ROOT}/libs/system
+)
SRCS(
src/codecvt_error_category.cpp
diff --git a/contrib/restricted/boost/libs/iostreams/ya.make b/contrib/restricted/boost/libs/iostreams/ya.make
index 14d10a06f7..a2a0614496 100644
--- a/contrib/restricted/boost/libs/iostreams/ya.make
+++ b/contrib/restricted/boost/libs/iostreams/ya.make
@@ -10,11 +10,11 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
PEERDIR(
- contrib/libs/zlib
- contrib/libs/libbz2
+ contrib/libs/zlib
+ contrib/libs/libbz2
)
CFLAGS(
diff --git a/contrib/restricted/boost/libs/locale/ya.make b/contrib/restricted/boost/libs/locale/ya.make
index 2ebf2e7e2d..c214b86dbc 100644
--- a/contrib/restricted/boost/libs/locale/ya.make
+++ b/contrib/restricted/boost/libs/locale/ya.make
@@ -10,12 +10,12 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
PEERDIR(
contrib/libs/icu
)
-
+
CFLAGS(
-DBOOST_LOCALE_WITH_ICU
-DBOOST_HAS_ICU=1
diff --git a/contrib/restricted/boost/libs/log/ya.make b/contrib/restricted/boost/libs/log/ya.make
index f24945a188..09429ee0cd 100644
--- a/contrib/restricted/boost/libs/log/ya.make
+++ b/contrib/restricted/boost/libs/log/ya.make
@@ -10,10 +10,10 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
ADDINCL(
- ${BOOST_ROOT}/libs/log/src
+ ${BOOST_ROOT}/libs/log/src
)
CFLAGS(
diff --git a/contrib/restricted/boost/libs/program_options/ya.make b/contrib/restricted/boost/libs/program_options/ya.make
index ba313cfdc6..bc228af72f 100644
--- a/contrib/restricted/boost/libs/program_options/ya.make
+++ b/contrib/restricted/boost/libs/program_options/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCS(
src/cmdline.cpp
diff --git a/contrib/restricted/boost/libs/python/arcadia_test/mod/ya.make b/contrib/restricted/boost/libs/python/arcadia_test/mod/ya.make
index 34f605663c..ff4c0e70e4 100644
--- a/contrib/restricted/boost/libs/python/arcadia_test/mod/ya.make
+++ b/contrib/restricted/boost/libs/python/arcadia_test/mod/ya.make
@@ -11,7 +11,7 @@ OWNER(
)
PEERDIR(
- contrib/restricted/boost/libs/python
+ contrib/restricted/boost/libs/python
)
NO_COMPILER_WARNINGS()
diff --git a/contrib/restricted/boost/libs/python/ya.make b/contrib/restricted/boost/libs/python/ya.make
index aacb0f76b2..8a9607986f 100644
--- a/contrib/restricted/boost/libs/python/ya.make
+++ b/contrib/restricted/boost/libs/python/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
CFLAGS(
GLOBAL -DBOOST_PYTHON_STATIC_LIB
diff --git a/contrib/restricted/boost/libs/random/ya.make b/contrib/restricted/boost/libs/random/ya.make
index a19de4fcf0..5d319bcb88 100644
--- a/contrib/restricted/boost/libs/random/ya.make
+++ b/contrib/restricted/boost/libs/random/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCS(
src/random_device.cpp
diff --git a/contrib/restricted/boost/libs/regex/ya.make b/contrib/restricted/boost/libs/regex/ya.make
index d095e2a862..379c0831ae 100644
--- a/contrib/restricted/boost/libs/regex/ya.make
+++ b/contrib/restricted/boost/libs/regex/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
PEERDIR(
contrib/libs/icu
diff --git a/contrib/restricted/boost/libs/serialization/ya.make b/contrib/restricted/boost/libs/serialization/ya.make
index a52141ca8d..5576e6a7ed 100644
--- a/contrib/restricted/boost/libs/serialization/ya.make
+++ b/contrib/restricted/boost/libs/serialization/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCS(
src/archive_exception.cpp
diff --git a/contrib/restricted/boost/libs/system/ya.make b/contrib/restricted/boost/libs/system/ya.make
index a0e3b514c5..4571531ed1 100644
--- a/contrib/restricted/boost/libs/system/ya.make
+++ b/contrib/restricted/boost/libs/system/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCS(
src/error_code.cpp
diff --git a/contrib/restricted/boost/libs/test/targets/lib/ya.make b/contrib/restricted/boost/libs/test/targets/lib/ya.make
index c3aac0dfae..4058af6c64 100644
--- a/contrib/restricted/boost/libs/test/targets/lib/ya.make
+++ b/contrib/restricted/boost/libs/test/targets/lib/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCDIR(${BOOST_ROOT}/libs/test/src)
diff --git a/contrib/restricted/boost/libs/test/targets/prog/ya.make b/contrib/restricted/boost/libs/test/targets/prog/ya.make
index 28ff142945..0111d202fb 100644
--- a/contrib/restricted/boost/libs/test/targets/prog/ya.make
+++ b/contrib/restricted/boost/libs/test/targets/prog/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCDIR(${BOOST_ROOT}/libs/test/src)
diff --git a/contrib/restricted/boost/libs/test/targets/test/ya.make b/contrib/restricted/boost/libs/test/targets/test/ya.make
index 3b001149d2..34111fc0a8 100644
--- a/contrib/restricted/boost/libs/test/targets/test/ya.make
+++ b/contrib/restricted/boost/libs/test/targets/test/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCDIR(${BOOST_ROOT}/libs/test/src)
diff --git a/contrib/restricted/boost/libs/thread/ya.make b/contrib/restricted/boost/libs/thread/ya.make
index b2fd96b706..880df0ebc6 100644
--- a/contrib/restricted/boost/libs/thread/ya.make
+++ b/contrib/restricted/boost/libs/thread/ya.make
@@ -10,11 +10,11 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
-PEERDIR(
- ${BOOST_ROOT}/libs/chrono
- ${BOOST_ROOT}/libs/system
+PEERDIR(
+ ${BOOST_ROOT}/libs/chrono
+ ${BOOST_ROOT}/libs/system
)
IF (OS_WINDOWS)
diff --git a/contrib/restricted/boost/libs/timer/ya.make b/contrib/restricted/boost/libs/timer/ya.make
index ff020fdf37..897693bdf7 100644
--- a/contrib/restricted/boost/libs/timer/ya.make
+++ b/contrib/restricted/boost/libs/timer/ya.make
@@ -10,7 +10,7 @@ OWNER(
g:cpp-contrib
)
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
SRCS(
src/auto_timers_construction.cpp
diff --git a/contrib/restricted/boost/libs/ya.make b/contrib/restricted/boost/libs/ya.make
index 4e6df3366b..c42a994cdc 100644
--- a/contrib/restricted/boost/libs/ya.make
+++ b/contrib/restricted/boost/libs/ya.make
@@ -1,48 +1,48 @@
-LIBRARY()
-
+LIBRARY()
+
LICENSE(BSL-1.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-VERSION(1.67)
-
+VERSION(1.67)
+
OWNER(
antoshkka
g:cpp-committee
g:cpp-contrib
)
-
-INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
-
-# This is an "all batteries included" version of boost with a full set of components
-# It should be avoided in common libraries or projects that care for binary size
-
-PEERDIR(
- ${BOOST_ROOT}/libs/asio
- ${BOOST_ROOT}/libs/atomic
- ${BOOST_ROOT}/libs/chrono
- ${BOOST_ROOT}/libs/context
- ${BOOST_ROOT}/libs/container
- ${BOOST_ROOT}/libs/coroutine
- ${BOOST_ROOT}/libs/date_time
- ${BOOST_ROOT}/libs/exception
- ${BOOST_ROOT}/libs/filesystem
- ${BOOST_ROOT}/libs/iostreams
- ${BOOST_ROOT}/libs/locale
- ${BOOST_ROOT}/libs/program_options
- ${BOOST_ROOT}/libs/random
- ${BOOST_ROOT}/libs/regex
- ${BOOST_ROOT}/libs/timer
- ${BOOST_ROOT}/libs/log
- ${BOOST_ROOT}/libs/serialization
- ${BOOST_ROOT}/libs/system
- ${BOOST_ROOT}/libs/thread
-)
-
-END()
-
+
+INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
+
+# This is an "all batteries included" version of boost with a full set of components
+# It should be avoided in common libraries or projects that care for binary size
+
+PEERDIR(
+ ${BOOST_ROOT}/libs/asio
+ ${BOOST_ROOT}/libs/atomic
+ ${BOOST_ROOT}/libs/chrono
+ ${BOOST_ROOT}/libs/context
+ ${BOOST_ROOT}/libs/container
+ ${BOOST_ROOT}/libs/coroutine
+ ${BOOST_ROOT}/libs/date_time
+ ${BOOST_ROOT}/libs/exception
+ ${BOOST_ROOT}/libs/filesystem
+ ${BOOST_ROOT}/libs/iostreams
+ ${BOOST_ROOT}/libs/locale
+ ${BOOST_ROOT}/libs/program_options
+ ${BOOST_ROOT}/libs/random
+ ${BOOST_ROOT}/libs/regex
+ ${BOOST_ROOT}/libs/timer
+ ${BOOST_ROOT}/libs/log
+ ${BOOST_ROOT}/libs/serialization
+ ${BOOST_ROOT}/libs/system
+ ${BOOST_ROOT}/libs/thread
+)
+
+END()
+
RECURSE(
- asio
+ asio
atomic
chrono
container
diff --git a/contrib/restricted/boost/ya.make b/contrib/restricted/boost/ya.make
index 764e7285e5..77e2dc66c0 100644
--- a/contrib/restricted/boost/ya.make
+++ b/contrib/restricted/boost/ya.make
@@ -20,14 +20,14 @@ OWNER(
g:cpp-contrib
)
-NO_UTIL()
+NO_UTIL()
+
+# This is the header-only version of boost
+# To use a boost library with separate compilation units,
+# one should use `contrib/restricted/boost/libs/$lib`
-# This is the header-only version of boost
-# To use a boost library with separate compilation units,
-# one should use `contrib/restricted/boost/libs/$lib`
-
ADDINCL(
- GLOBAL contrib/restricted/boost
+ GLOBAL contrib/restricted/boost
)
END()
diff --git a/contrib/restricted/googletest/googlemock/gmock_main/ya.make b/contrib/restricted/googletest/googlemock/gmock_main/ya.make
index 07e51143ad..eb95d44b72 100644
--- a/contrib/restricted/googletest/googlemock/gmock_main/ya.make
+++ b/contrib/restricted/googletest/googlemock/gmock_main/ya.make
@@ -1,21 +1,21 @@
# Generated by devtools/yamaker.
-LIBRARY()
-
+LIBRARY()
+
OWNER(
somov
g:cpp-contrib
)
-
+
LICENSE(BSD-3-Clause)
-
+
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-PEERDIR(
+PEERDIR(
contrib/restricted/googletest/googlemock
contrib/restricted/googletest/googletest
-)
-
+)
+
ADDINCL(
GLOBAL contrib/restricted/googletest/googlemock/include
GLOBAL contrib/restricted/googletest/googletest/include
@@ -31,12 +31,12 @@ CFLAGS(
GLOBAL -DGTEST_HAS_ABSL=0
GLOBAL -DGTEST_OS_FUCHSIA=0
GLOBAL -DGTEST_HAS_STD_WSTRING=1
-)
-
+)
+
SRCDIR(contrib/restricted/googletest/googlemock/src)
-SRCS(
+SRCS(
GLOBAL gmock_main.cc
-)
-
-END()
+)
+
+END()
diff --git a/contrib/restricted/googletest/googlemock/ya.make b/contrib/restricted/googletest/googlemock/ya.make
index 8b3c11fe5f..38649ba5fc 100644
--- a/contrib/restricted/googletest/googlemock/ya.make
+++ b/contrib/restricted/googletest/googlemock/ya.make
@@ -18,7 +18,7 @@ PEERDIR(
contrib/restricted/googletest/googletest
)
-ADDINCL(
+ADDINCL(
GLOBAL contrib/restricted/googletest/googlemock/include
GLOBAL contrib/restricted/googletest/googletest/include
contrib/restricted/googletest/googlemock
diff --git a/contrib/restricted/libffi/ChangeLog b/contrib/restricted/libffi/ChangeLog
index 279a89dab2..fad8eaee12 100644
--- a/contrib/restricted/libffi/ChangeLog
+++ b/contrib/restricted/libffi/ChangeLog
@@ -1,10725 +1,10725 @@
-commit 5dcb741f1544c5e18c9dbf96aeb8b61cc556a616
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 23 10:24:58 2019 -0500
-
- Move nested_struct3 test to closures directory
-
-commit 1aca33301a791f503d943f5e3abe2c720296eb8f
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 23 09:42:04 2019 -0500
-
- Add missing closing brace
-
-commit d996cb283cf373936498defa902be040ec20455e
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 23 09:00:14 2019 -0500
-
- Version 3.3
-
-commit c72b82f465148b89f118ee73f8956dafdbac9b65
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 23 08:48:53 2019 -0500
-
- Remove junk file from dist
-
-commit 642d40ee6ae9a779b3c5ad930785d4b33cf94029
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 23 07:49:58 2019 -0500
-
- Account for moved test files
-
-commit 049da08a22b0ca6d63d2be6c209da5ac1335365c
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 23 07:44:26 2019 -0500
-
- Add dejagnu directives accidentally removed
-
-commit 36730f5d87c2a432e1b3bf1a0129fedbf4b0a488
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 22 19:49:38 2019 -0500
-
- Move closure test to closure directory
-
-commit c88c0e92a9fbb4e69513394682c61aa848a035cc
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 22 19:27:34 2019 -0500
-
- More more closure tests to the closure test directory
-
-commit a37cc1755cc276b2b9e601b9b112919f8c882a2e
-Merge: 332a539 247a5e7
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 22 18:55:36 2019 -0500
-
- Merge branch 'master' of github.com:libffi/libffi
-
-commit 332a539e88d26a0524c10a39283a3099d071ca10
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 22 18:54:30 2019 -0500
-
- Move closure tests so we can easily XFAIL them for some targets
-
-commit 1761a10645dadc0840bf1ff3a4998f9a342e8cad
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 22 18:53:09 2019 -0500
-
- Remove gccbug detection. GCC is good now.
-
-commit 247a5e7878379b7af33338d51898d7fb9e82e686
-Author: Michael Haubenwallner <michael.haubenwallner@ssi-schaefer.com>
-Date: Fri Nov 22 20:17:58 2019 +0100
-
- Capture x86-windows host like x86_64-windows (#529)
-
-commit 8e3935fa761d3e6f19ccf5e6733fd40dee637d94
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 22 12:42:26 2019 -0500
-
- Manual clean-ups, and include the PDF in the source distribution.
-
-commit d01088a5194ff1a2250e7dbee04a9a167b582db7
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 21 05:36:06 2019 -0500
-
- Mention more major port contributors
-
-commit 970b7fce4f804df57ec582a0220c22eaeccc239a
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 21 05:04:54 2019 -0500
-
- Update autoconf-archive m4 macros
-
-commit 34a3a661b80c0fa7817c0654ae9fd0686d3b8cd2
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 21 04:59:39 2019 -0500
-
- Fix formatting of README.
-
-commit 91a7fbe94e3884536cf2eb8e644bc79d6b19c80e
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 20 07:16:41 2019 -0500
-
- Fix or1k lack-of-g++ checking in testsuite
-
-commit 31543c799a224ef446cef19a2372b054ecad3822
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 20 06:15:55 2019 -0500
-
- Add work-around for users who manage their own closure memory
-
- As suggested by DJ
-
-commit bd3a4687c0743076f420dee2a02075fd64fa547e
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 19 17:14:23 2019 -0500
-
- No C++ for or1k-unknown-elf
-
-commit d6e4f96b482690e6cdaf67a70bb33d1bfe0acd15
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 19 13:36:49 2019 -0500
-
- No C++ for or1k
-
-commit 497018686d4df0012ea7bf1a4ab41b918b5e65bc
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 19 10:07:16 2019 -0500
-
- Disable type warnings for or1k.
-
-commit 262cf74fd4003a928ca73e96ef8698546e535c46
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 19 10:06:57 2019 -0500
-
- No c++ for or1k-elf
-
-commit 54fc80dfd8d608ec718cade762c358b8fd819f38
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 15:20:00 2019 -0500
-
- Fake TRAVIS_BUILD_DIR
-
-commit 6f734f8a5ff13d106f81741c11c7cb2551706c7f
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 15:13:16 2019 -0500
-
- Adapt for new old ChangeLog file
-
-commit 27d31130cabfe82683fc0e3e82247fd522f45607
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 15:06:51 2019 -0500
-
- Fix DEJAGNU variable
-
-commit da1358816e7b02e6f8431e4df336d0934bcabd4c
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 14:54:14 2019 -0500
-
- Set vars
-
-commit 9a394c24951f3fc5cfbd0ff268278a7b45afc77e
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 14:45:29 2019 -0500
-
- Remove verbosity
-
-commit 14bfbec0fd312001f7922ee6100cbc3155ae585b
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 14:40:30 2019 -0500
-
- Pull before running
-
-commit dfa60e5eb44482d45b8c79b815e6b6789e62ce18
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 14:02:33 2019 -0500
-
- Fix cross builds for or1k
-
-commit a8223271a3d7ff1e8a1553c2a5ed9b4e1a24a774
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 13:59:10 2019 -0500
-
- More cross build debugging
-
-commit 8c9cf44cb2a2d46ddcb148508fb5350438b4a62b
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 13:47:42 2019 -0500
-
- Set path to simulator. Add debugging output.
-
-commit 581048f91e9e25e3b17a2906edd8840f35999918
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 13:17:27 2019 -0500
-
- Be specific when building CI container images
-
-commit bbea6394f9f27de68aac037abb264151d6de9f64
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 13:06:26 2019 -0500
-
- Capture more or1k hosts
-
-commit 97e3b1fe1a0fbdb43bf28fe6198cb26eaa719c93
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 13:02:44 2019 -0500
-
- Add test support for or1k. Fix yaml typo.
-
-commit c88f4d2677d4dc6659a1aa6418e636f8fcf9bd9b
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 12:25:51 2019 -0500
-
- Fix typo for m32r and bfin builds
-
-commit 93c203b347ea7d110355e12f832725f755e10eff
-Merge: d087b59 73dd43a
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 06:35:19 2019 -0500
-
- Merge branch 'master' of github.com:libffi/libffi
-
-commit d087b595637ebb795c0cec1ff0c4409befb486b7
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 06:34:42 2019 -0500
-
- Build/test for m32r-elf and bfin-elf
-
-commit b6804d16453890b78844b1b3c1acf16af98cadb8
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Nov 17 09:19:14 2019 -0500
-
- Mention binary128 long double support for Power
-
-commit 73dd43afc8a447ba98ea02e9aad4c6898dc77fb0
-Author: Samuel Holland <samuel@sholland.org>
-Date: Sun Nov 17 07:22:25 2019 -0600
-
- IEEE754 binary128 long double support for PowerPC64 (#526)
-
- * powerpc: Adjust flags to make room for vector types
-
- * powerpc64 ELFv2 IEEE128 long double support
-
-commit b58bd77236e7d41fc04b4be7edd1c6728626c99b
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 15 11:18:59 2019 -0500
-
- Re-enable mingw32 tests.
-
-commit 6f221e8269aa16f6b5eec41cfd1d7d90a9fbea0c
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 15 11:06:17 2019 -0500
-
- Disable wine builds.
-
-commit 09dc0a71a44c95ee0d2f47de94b6b59534c2ce24
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 15 10:19:00 2019 -0500
-
- Stretch out timeout for test
-
-commit 28a7cc464c21b4955fba28cc55a6f095ddf5838b
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 15 06:07:51 2019 -0500
-
- Consolidate all of the old ChangeLog files into ChangeLog.old.
-
-commit 86d3d3767a40fe1cae10c419a913dd97e7e6cd23
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 13 10:07:00 2019 -0500
-
- Don't build aarch64-linux-gnu
-
-commit db198a19375858879dbcc51a443c193efa0b6c0a
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 13 10:05:36 2019 -0500
-
- Extend timeout for builds.
-
-commit 54af0256a00a40b2218950f93e5415c60f675714
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 13 09:15:05 2019 -0500
-
- Platform test tweaks
-
-commit 3a7580da73b7f16f275277316d00e3497cbb5a8c
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 13 07:59:18 2019 -0500
-
- Mark java raw APIs as deprecated.
-
-commit cda60c1a8aec070a7a822c047d89d0f18cf7c5fc
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 13 06:51:44 2019 -0500
-
- Disable mips64 tests. Fix log grabbing.
-
-commit a34254bdc1dee2857b759a22e657f92aadfa85dc
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 13 06:37:26 2019 -0500
-
- Re-add wine based testing
-
-commit 9bd3a9742c04d2fac489f236163d7e7fbb1b7568
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 13 06:35:40 2019 -0500
-
- Add wine-sim.exp for wine-based testing
-
-commit de6df6dce6420d4643598c228b72da4e455a0da7
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 13 06:32:46 2019 -0500
-
- Fix log file URL extraction. Grab rlgl cli for OSX
-
-commit c8986e871f82b497493d28c36be1a755c2ea6b8d
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 13 06:01:43 2019 -0500
-
- Fix log name extraction
-
-commit 6630764d244aeb3bc0797d0c3c7ccc79084061a8
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 12 22:56:37 2019 -0500
-
- Account for shorter ==LOGFILE== string
-
-commit aa975ec3e4ac07bd7dacec18f1c8282baeb7c398
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 12 22:35:47 2019 -0500
-
- Fix grep matcher
-
-commit 6dd88bc5b3f3d3d975409b7336f4127ae18da4b3
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 12 18:44:27 2019 -0500
-
- Debug
-
-commit 7e318cf50d8c481957b3be76e508054c70cbdf9b
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 12 17:55:35 2019 -0500
-
- Pull test logs from cfarm
-
-commit 5123e9cf0193031bdc580cb221427cbd29ba3677
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 12 09:21:57 2019 -0500
-
- Use rlgl for cfarm test results
-
-commit 486f88f985affa215a9daaadcdc703c8baea9020
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 12 09:20:21 2019 -0500
-
- Use rlgl for cross builds.
-
-commit 042c6671b0456d17af24d61b79cbd3f9261c3f2b
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 12 09:14:20 2019 -0500
-
- Always exit build container successfully. Don't test mingw.
-
-commit 82f7f80aa9ac3cd753bcb6d2b88cc930aee72bcc
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 12 08:58:52 2019 -0500
-
- Run rlgl outside of the build container.
-
-commit 5b297e036e61ad1ecac9c8a3e57895737c55feb7
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 12 05:51:09 2019 -0500
-
- Don't bother dumping logs. Use rlgl instead.
-
-commit 2a8d88d92d56747101078c5592ab2473e6c5cb29
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 11 21:24:58 2019 -0500
-
- Fix rlgl usage
-
-commit 3c2b810e99a10f97d1eb6ba485eb09bfdb158084
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 11 21:11:59 2019 -0500
-
- Test rlgl
-
-commit 2cc11720be0c4d3bbe906be5a4aad3b2dc167072
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 11 16:19:45 2019 -0500
-
- Debug in-container builds
-
-commit 0de0c6a28006902c203e8dc6629cd9ef35d61e09
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Nov 10 08:20:46 2019 -0500
-
- Build both iOS and Macosx
-
-commit 4e3e0586efbbc7828c15fb48e49401840beefcdd
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 12:35:27 2019 -0500
-
- Fix tpyo
-
-commit f764f278160831f7e4d8ee8a48d18f5a7937f742
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 12:17:29 2019 -0500
-
- Change s390x options
-
-commit 188de63c597f23b0ccdb953b076c8cb0711fbcf0
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 12:03:19 2019 -0500
-
- Mark xfail for m68k and alpha.
-
-commit 0da221f8094ec504d91b5f88c74e98b8b9aa9eda
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 12:03:01 2019 -0500
-
- Clean up. Debug s390x cpu support.
-
-commit 7e0fbf41934020c9ff76816fde5000482c7e6a6c
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 11:50:08 2019 -0500
-
- Try coldfire for m68k builds
-
-commit 6a9fa770a436bbb71dbe8311e75123353e6836cc
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 11:37:25 2019 -0500
-
- Add GCC_OPTIONS flag
-
-commit eebcbb1113742df7d41fc3d39eca970a026ad1d1
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 11:26:53 2019 -0500
-
- Compile m68k target for m5208
-
-commit 08cb33ff5824b2ea24b2b62841cca1934a27f36f
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 11:15:13 2019 -0500
-
- Dump supported CPUs
-
-commit 16c935000d459b1aba9e1f7b48e2c1d7dadc8cf1
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 11:00:09 2019 -0500
-
- Fix shell script
-
-commit 588e87461fe48441806be4bb5654f058e1c37649
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 10:56:40 2019 -0500
-
- Print debug output. Use podman when available.
-
-commit 04d14a66ff807a0ac2578ce886ef338aa2066b4d
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 09:23:10 2019 -0500
-
- Set QEMU_CPU within the build containers
-
-commit 28d9c019dbbf6dea1ed127e1a7de829cece86639
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 7 07:36:11 2019 -0500
-
- Set QEMU_CPU for m68k
-
-commit 75464caf658f176848db6f48325c5067cdf94a9b
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 6 22:02:11 2019 -0500
-
- Add alpha and m68k testing
-
-commit 259c497a2f326cc89344766e106cf73e62485a2a
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 6 11:31:17 2019 -0500
-
- Sett CC and CXX for cross builds
-
-commit d23d3959fdb764984cfb888c5d6aed910926dd5f
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 6 11:21:46 2019 -0500
-
- autogen before cross building
-
-commit a6dc8ef270c1f022720aedadb6b0d2678d1bc39e
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 6 11:10:59 2019 -0500
-
- Fix typo. Don't double test.
-
-commit 136a235d3f36408628c0459d8740546acad0ca5a
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 6 10:51:33 2019 -0500
-
- Use the right cross build container image
-
-commit 92f5309def05c66e6c5034c10d620d6fbc7a1018
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 6 10:49:04 2019 -0500
-
- Try s390x and sh4 cross builds/tests
-
-commit d4a28fee720c8f389b138b3f7726157fbcb7eaaf
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 6 06:47:05 2019 -0500
-
- Revert to older test cross compilers
-
-commit 0fb9ee21e68ca3e70cf236a63ba00b5ca32031ff
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 6 06:44:19 2019 -0500
-
- Use older test compiler. Enable s390x testing.
-
-commit 36d281ab70daf7dcf890df9c3f5bdd76f665bb68
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 6 06:30:52 2019 -0500
-
- Test cross-builds for hppa-linux-gnu
-
-commit c95cc4b354f24dbbf5776eb297fa036bcbfed252
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 6 06:30:20 2019 -0500
-
- Reference FFI_BUILDING_DLL
-
-commit 88a76477debe83ed6a75f96394853c891fb1dac4
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Nov 3 06:28:51 2019 -0500
-
- rc2. hack as per: https://github.com/travis-ci/travis-ci/issues/6934
-
-commit 45ba4aefed15be24fdbaaffec805fb02b1343e0f
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 31 19:07:04 2019 -0400
-
- Add sparc64-linux-gnu testing back
-
-commit a26323b7e0824f0becaeaffc8d3b700dc09f741c
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 31 15:32:48 2019 -0400
-
- Don't build sparc. Build mips.
-
-commit f325324818a6aaa9e8a75782d75c412872e6b21c
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 31 14:35:43 2019 -0400
-
- Test mips64el-linux-gnu
-
-commit 39bad2f396de7885c9569144b5bb6e8a639ac011
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 31 12:33:22 2019 -0400
-
- Don't run autogen.sh all the time.
-
-commit 82719cbba06c2fc527df156d728341867d86f82c
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 31 12:23:11 2019 -0400
-
- Test sparc64-linux-gnu on travis
-
-commit 0348d0e4fa585d9a3d9762132a3eee94f918fe3b
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 31 10:53:37 2019 -0400
-
- Try new cfarm build for power
-
-commit 290bc3164bb0e0b3fb912c457b49e61f9a728eef
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Oct 26 10:13:20 2019 -0400
-
- Add make_sunver.pl to distribution.
-
-commit a8efc2f7897b439fdf2144329d35fea820498dc7
-Author: Andreas Schwab <schwab@linux-m68k.org>
-Date: Sat Oct 26 14:57:05 2019 +0200
-
- Fix FFI_STDCALL ABI (#514)
-
- Even for a stdcall function, the stack alignment is still the
- responsibility of the caller. Remember the original, not stack-aligned
- argument size, but align when setting up a stack frame. In
- ffi_closure_inner, return the true argument size, so that
- ffi_[go_]closure_STDCALL doesn't adjust too much.
-
-commit ca112537df7b9cdbccad7541aa3cb43b2a2dac9a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Oct 26 07:26:30 2019 -0400
-
- Add missing build script, make_sunver.pl.
-
-commit 52b066f04fdd81c1037e1cb714a07a2a352bcf9b
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 24 07:03:43 2019 -0400
-
- Update versions to 3.3-rc1
-
-commit 9b10df3be2d8f81876b7cc90ee5d8833ccdf6b34
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 24 06:41:11 2019 -0400
-
- Remove some debugging output
-
-commit ec042885cfa5a9450bfcc87152a41529d26545de
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 24 06:39:00 2019 -0400
-
- Don't test ppc64le with buggy qemu.
-
-commit 90fb897839bb7006a2f751d283e3d23b3bfec1ea
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 24 06:24:14 2019 -0400
-
- Strip build status from README.md at 'make dist' time.
-
-commit 1d6059446fb986d2de933f7ccf6fe38bcdf0c76c
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 24 05:25:11 2019 -0400
-
- Add missing dist files.
-
-commit 825b2a359468af8bf3570a5a0695e8b805c5446f
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Oct 16 16:05:46 2019 -0400
-
- Test on arm32v7-linux-gnu, ppc64le-linux-gnu and aarch64-linux-gnu.
-
- Use docker images and qemu to test libffi for non-x86 architectures on
- travis-ci.
- Use the LIBFFI_TEST_OPTIMIZATION environment variable to
- force specific optimization levels at test time.
-
-commit d2a4095af68f4530571bc3fa613dd7f5e5b815a3
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Oct 14 06:46:52 2019 -0400
-
- Fix comments.
-
-commit 058aa4130445b4ef3c2f77f796c33506873031ca
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Oct 14 05:47:07 2019 -0400
-
- Update copyright year
-
-commit c4f61240ab19401bd86c0dfb271e243e8159abb4
-Author: zhanhb <6323014+zhanhb@users.noreply.github.com>
-Date: Wed Oct 9 18:59:32 2019 +0800
-
- Add long double test (#492)
-
- Required to fix build error on macos with gcc-9
-
-commit 09f9d856112f2f105337e95e32ba9e2da63f65ae
-Author: pichikaudaykiran <51439150+pichikaudaykiran@users.noreply.github.com>
-Date: Wed Oct 9 16:26:06 2019 +0530
-
- Making the change to correct the comment when SUN (#521)
-
- and GCC are used together
-
-commit 55c22092dc54e706a64af3a49ae9d5471a9e8317
-Author: pnallan <46887249+pnallan@users.noreply.github.com>
-Date: Tue Oct 8 18:46:47 2019 +0530
-
- handle compilation warnings with ftruncate API (#508)
-
- * fix me: avoid warning while handle ftruncate API
-
- Signed-off-by: Prasad Nallani <prasad.nallani@intel.com>
-
- * Update closures.c
-
-commit e5f0eb1552f222eb2630e40ee348b090d56412a3
-Author: John Ericson <git@JohnEricson.me>
-Date: Tue Oct 8 06:58:52 2019 -0400
-
- Clean up line endings (#509)
-
- The CLRF visual studio files can be kept that way, but recognized as
- text. The assembly file can be converted to LF.
-
-commit ea9b6639c69cbffeacd1ce0c1953c1997cf29d2e
-Author: Samuel Holland <samuel@sholland.org>
-Date: Tue Oct 8 05:57:28 2019 -0500
-
- PowerPC bugfixes (#520)
-
- * powerpc: Silence warnings about unused labels
-
- * powerpc: Fix a couple of comments
-
- * powerpc: Fix alignment after float structs
-
- * powerpc: Don't pad rvalues copied from FP regs
-
- * powerpc: Add missing check in struct alignment
-
- * powerpc: Support homogeneous long double structs
-
-commit 25cf9cc4a5ce4a272252de3f681d60dafd838ceb
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 8 06:24:55 2019 -0400
-
- Use https for moxie toolchain repo
-
-commit c2a6859012d928b67a83619bd5087674a96b9254
-Author: Paul Monson <paulmon@users.noreply.github.com>
-Date: Wed Aug 7 11:57:45 2019 -0700
-
- fix mingw build and crashing bugs for Python Windows ARM64 (#496)
-
- * fix mingw build and crashing bugs for Python Windows ARM64
-
- * Fix issues found in PR review
-
-commit e0b4f84fb71c6760068c9d1306e77c9382e76d8d
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jun 26 06:18:48 2019 -0400
-
- Clear the apt cache
-
-commit 68668fe4f22dea7b829fb84b724f5a74091f22f2
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jun 26 06:01:15 2019 -0400
-
- More debugging output
-
-commit 1d7635d18ae4aebe4ec1cd129b0b4f71b685131e
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jun 25 23:39:52 2019 -0400
-
- Debug moxie builds in travis
-
-commit d856743e6b02fcb5911491204131e277a7a4e10b
-Author: ossdev07 <39188636+ossdev07@users.noreply.github.com>
-Date: Wed Jun 26 07:31:22 2019 +0530
-
- libffi: added ARM64 support for Windows (#486)
-
- * libffi: added ARM64 support for Windows
-
- 1. ported sysv.S to win64_armasm.S for armasm64 assembler
- 2. added msvc_build folder for visual studio solution
- 3. updated README.md for the same
- 4. MSVC solution created with the changes, and below test suites are tested
- with test script written in python.
-
- libffi.bhaible
- libffi.call
- 5. Basic functionality of above test suites are getting passed
-
- Signed-off-by: ossdev07 <ossdev@puresoftware.com>
-
- * Update README.md
-
-commit 80d07104c33045ea34a4d5185600495dc7461a12
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Apr 28 07:36:24 2019 -0400
-
- uuencode compressed log files for travis
-
-commit fadf1eb530713fde0be9774d926bc8202c97e379
-Author: Sergei Trofimovich <slyfox@gentoo.org>
-Date: Sat Apr 27 20:53:29 2019 +0100
-
- hppa: avoid TEXTREL in .eh_frame section (#447)
-
- Before the change hand-crafted .eh_frame section contained
- ABS relocation and caused TEXTREL tag to be emitted:
-
- ```
- $ ./configure --host=hppa2.0-unknown-linux-gnu LDFLAGS=-Wl,-z,text
- $ make
- ...
- /usr/libexec/gcc/hppa2.0-unknown-linux-gnu/ld:
- read-only segment has dynamic relocations.
- ```
-
- Link failure is caused by absolute address of FDEs
- encoded into .eh_frame entries.
-
- Fixed TEXTREL by using pcrel (instead of ABS) encoding
- for absolute addresses (__PIC__ code) by adding augmentation
- information ("zR" CIE type).
-
- All tests still pass on hppa2.0. The specific tests that still pass
- and exercise this code path:
- testsuite/libffi.call/unwindtest.cc
- testsuite/libffi.call/unwindtest_ffi_call.cc
-
- Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
-
-commit 06bf1a9deaa781b711c4d3718561e7faf303a842
-Author: driver1998 <driver1998.ms@outlook.com>
-Date: Sun Apr 28 03:21:44 2019 +0800
-
- fix x86/x64 MSVC build (#487)
-
-commit db5706ff285c476aa3c0f811ff2b188319ac3ebe
-Author: Paul Monson <paulmon@users.noreply.github.com>
-Date: Fri Apr 26 04:58:58 2019 -0700
-
- add support for 32-bit ARM on Windows (#477)
-
- * add support for 32-bit ARM on Windows
-
- * fix mismatched brace in appveyor.yml
-
- * remove arm platform from appveyor.yml for now
-
- * fix arm build
-
- * fix typo
-
- * fix assembler names
-
- * try Visual Studio 2017
-
- * add windows arm32 to .appveyor.yml
-
- * update README.md
-
-commit d1e9b4b96cc8d237c3532cf83da0d4b99d19abb5
-Merge: 05a1796 a7d6396
-Author: Tom Tromey <tom@tromey.com>
-Date: Tue Apr 9 14:00:10 2019 -0600
-
- Merge pull request #482 from sharkcz/aarch64
-
- fix check for Linux/aarch64
-
-commit a7d6396f06d5e1a726f24b746b509514f466380f
-Author: Dan Horák <dan@danny.cz>
-Date: Fri Mar 29 14:19:20 2019 +0100
-
- fix check for Linux/aarch64
-
- fixes #473
-
-commit 05a1796419f68267250c0b8ae7138da36ab60b01
-Author: Jeremy Huddleston Sequoia <jeremyhu@users.noreply.github.com>
-Date: Tue Feb 19 04:11:28 2019 -0800
-
- Cleanup symbol exports on darwin and add architecture preprocessor checks to assist in building fat binaries (eg: i386+x86_64 on macOS or arm+aarch64 on iOS) (#450)
-
- * x86: Ensure _efi64 suffixed symbols are not exported
-
- * x86: Ensure we do not export ffi_prep_cif_machdep
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
-
- * x86: Ensure we don't export ffi_call_win64, ffi_closure_win64, or ffi_go_closure_win64
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
-
- * closures: Silence a semantic warning
-
- libffi/src/closures.c:175:23: This function declaration is not a prototype
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
-
- * aarch64: Ensure we don't export ffi_prep_cif_machdep
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
-
- * arm: Ensure we don't export ffi_prep_cif_machdep
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
-
- * aarch64, arm, x86: Add architecture preprocessor checks to support easier fat builds (eg: iOS)
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
-
- * x86: Silence some static analysis warnings
-
- libffi/src/x86/ffi64.c:286:21: The left operand of '!=' is a garbage value due to array index out of bounds
- libffi/src/x86/ffi64.c:297:22: The left operand of '!=' is a garbage value due to array index out of bounds
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
-
- * aarch: Use FFI_HIDDEN rather than .hidden
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
-
- * ffi.h: Don't advertise ffi_java_rvalue_to_raw, ffi_prep_java_raw_closure, and ffi_prep_java_raw_closure_loc when FFI_NATIVE_RAW_API is 0
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
-
-commit 3ec522bc1c1c5a7fb66b85d4fb6a0fe80581d597
-Author: dabrain34 <scerveau@gmail.com>
-Date: Tue Feb 19 13:09:09 2019 +0100
-
- Fix cfi checks for old compiler (#453)
-
- cfi_sections can be unsupported when cfi_startproc
- and cfi_endproc are.
-
-commit e1118af50599314a2cbac3eb51a81896e8e21d0c
-Author: Paul Monson <paulmon@users.noreply.github.com>
-Date: Tue Feb 19 03:58:25 2019 -0800
-
- changes for win32 on windows (#468)
-
-commit 44a6c28545186d78642487927952844156fc7ab5
-Author: Florian Weimer <fw@deneb.enyo.de>
-Date: Tue Feb 19 12:55:11 2019 +0100
-
- aarch64: Flush code mapping in addition to data mapping (#471)
-
- This needs a new function, ffi_data_to_code_pointer, to translate
- from data pointers to code pointers.
-
- Fixes issue #470.
-
-commit 042ef8c314a946ef1cd58c6e10cd74e403ef5bf9
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 12 08:50:30 2019 -0500
-
- Remove -Os testing. No ABI impact, and helps trim log lengths.
-
-commit 8fa88373a1d433c675b11200ccd58418e91f81e4
-Merge: 737d4fa 2c5b164
-Author: Tom Tromey <tom@tromey.com>
-Date: Wed Dec 19 14:18:40 2018 -0700
-
- Merge pull request #461 from NativeScript/bektchiev/fix-visibility-hidden-check-in-configure
-
- fix(configure): Correctly detect visibility("hidden") support on Darwin
-
-commit 2c5b164288712cc048048d73a3cd841d845a132c
-Author: Martin Bektchiev <martin.bektchiev@progress.com>
-Date: Wed Dec 19 18:33:08 2018 +0200
-
- fix(configure): Correctly detect visibility("hidden") support on Darwin
-
-commit 737d4faa00d681b4c758057f67e1a02d813d01c2
-Merge: a5ea752 4a84df4
-Author: Tom Tromey <tom@tromey.com>
-Date: Fri Nov 30 08:16:00 2018 -0700
-
- Merge pull request #457 from NativeScript/bektchiev/fix-arm64-q3-q4-args
-
- Fix Q registers parameter passing on ARM64
-
-commit 4a84df4ae9d33bb766fb34ce8a871d84d6e0ed9c
-Author: Martin Bektchiev <martin.bektchiev@progress.com>
-Date: Wed Oct 31 15:53:54 2018 +0200
-
- Fix Q registers parameter passing on ARM64
-
- The second two quads are located at offset 32 not 16
-
-commit a5ea7527cda8d9b7d011eb4004dfcbad54583bd2
-Merge: b11b08c ba73a67
-Author: Tom Tromey <tom@tromey.com>
-Date: Wed Sep 19 07:29:36 2018 -0600
-
- Merge pull request #443 from jeremyhu/master
-
- Update FFI_HIDDEN() to use .private_extern on Apple platforms and use the macro where appropriate
-
-commit b11b08ca8daacb08943ae5ea8c124771a8b82dde
-Merge: 980908b e6eac78
-Author: Tom Tromey <tom@tromey.com>
-Date: Tue Sep 18 08:26:31 2018 -0600
-
- Merge pull request #449 from gpakosz/align-macros
-
- Prefix ALIGN_DOWN macro with FFI_
-
-commit e6eac7863e2bf1a009ea863041b354bdb4af6b67
-Author: Gregory Pakosz <gregory.pakosz@gmail.com>
-Date: Tue Sep 18 15:19:53 2018 +0200
-
- Prefix ALIGN_DOWN macro with FFI_
-
-commit 980908b47bbde09fab88ee4b2b61d8bc5d4378a7
-Merge: 65da63a 4cb776b
-Author: Tom Tromey <tom@tromey.com>
-Date: Sat Aug 11 09:53:15 2018 -0600
-
- Merge pull request #445 from andreas-schwab/master
-
- RISC-V go closures
-
-commit 4cb776bc8075332d2f3e59f51785d621fcda48f6
-Author: Andreas Schwab <schwab@suse.de>
-Date: Thu Aug 9 12:12:29 2018 +0200
-
- RISC-V go closures
-
- This implements go closures for RISC-V. It has been tested on
- riscv64-suse-linux and against the libgo testsuite.
-
-commit ba73a671cb49f8e2c4417723a9dc233e328926ae
-Author: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
-Date: Fri Jul 20 09:37:43 2018 -0700
-
- Update FFI_HIDDEN() to use .private_extern on Apple platforms and use the macro where appropriate
-
- Fix issue #439
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
-
-commit 65da63abc843fe448aaa86015d094cf016f325ba
-Author: Jeremy Huddleston Sequoia <jeremyhu@users.noreply.github.com>
-Date: Mon Jun 25 04:38:58 2018 -0700
-
- Add compact unwind for darwin/i386 (#440)
-
- * x86: Add implementation of compact unwind for ffi_call_i386, et al.
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
-
- * x86: Use __text as the section name to avoid deprecated section name warnings.
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
-
- * darwin: Add missing regular,debug attributes for compact unwind sections
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
-
-commit 2309b58448b0c8349156d687d7fa8709dfb68992
-Author: Shoaib Meenai <shoaib.meenai@gmail.com>
-Date: Sun Jun 17 17:04:24 2018 -0700
-
- Mark sysv.S as SafeSEH compatible (#438)
-
- It contains no exception handler, so we can just emit the special
- @feat.00 symbol to indicate that it's trivially SafeSEH compatible.
- SafeSEH only applies to x86 and not x86-64, hence its inclusion in the
- x86-specific block. See [1] for details.
-
- [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms680547(v=vs.85).aspx#the_.sxdata_section_
-
-commit 1d704051b2da207d715351b8613e74437d8e2eb7
-Author: Jeremy Huddleston Sequoia <jeremyhu@users.noreply.github.com>
-Date: Sun Jun 17 17:01:50 2018 -0700
-
- i386: Fix missing break; in case statement leading to incorrectly returned FFI_BAD_ABI (#437)
-
- * i386: Add missing break triggering dead store static analyzer checks.
-
- Register calling sequence is being reported as bad ABI instead of working as intended.
-
- Found-by: Clang Static Analysis
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
-
- * Mark ffi arm sysv entry points as private_extern.
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
-
- * x86_64: Add implementation of compact unwind for ffi_call_unix64.
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
-
-commit b55baf0b500ccc7636a8a55e0506d9da787ad2dd
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed May 9 13:21:02 2018 -0400
-
- Handle FFI_GNUW64 on non-Windows systems (EFI)
-
-commit 8206253fdf01226173c36f087226d8ea53584566
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed May 9 10:50:46 2018 -0400
-
- Mark some cases as xfail due to GCC bug
-
-commit b5ee395710e2db830749c3c95558c91b66ac111f
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat May 5 07:41:53 2018 -0400
-
- Revert "Remove some symbol exports and cleanup newline warnings (#433)"
-
- This reverts commit a5a0f3cf36dfb4d64316414a872288c3170e6c1d.
-
-commit a5a0f3cf36dfb4d64316414a872288c3170e6c1d
-Author: Jeremy Huddleston Sequoia <jeremyhu@users.noreply.github.com>
-Date: Sat May 5 03:44:33 2018 -0700
-
- Remove some symbol exports and cleanup newline warnings (#433)
-
- * build: Ensure darwin generated sources end with a new line
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
-
- * build: Use .private_extern where missing to prevent exporting symbols that are not API
-
- Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
-
-commit d3c54cf3a2b2bb2e889173b6a0a959517b42c47f
-Author: hjl-tools <hjl.tools@gmail.com>
-Date: Wed May 2 06:19:58 2018 -0700
-
- Re-enable msabi testing (#436)
-
- * Revert "disable msabi testing for now"
-
- This reverts commit 7b7638eb0eac2adfa72f7ec9f254ba287c9947e2.
-
- * x86: Correct testing for 64-bit x86-64
-
- Since passing -m32 to x86-64 compiler will generate i386 code, we
- need to check both __ILP32__ and __i386__ for 64-bit x86-64.
-
- * x86: Check __i386__ instead of i?86-*-* targets
-
- Since passing -m32 to x86-64 compiler will generate i386 code, we need
- to check __i386__ instead of i?86-*-* targets for i386 targets.
-
- * i386: Properly passing integer parameters in registers
-
- For thiscall and fastcall, if the paramter passed as 64-bit integer or
- struct, all following integer paramters will be passed on stack.
-
- * test: Add ABI_ATTR to callback_code
-
- Add ABI_ATTR to callback_code to properly test different ABIs.
-
-commit ebf241663cc0fd0d76e4db8101e842e1630a2c78
-Author: Alan Modra <amodra@gmail.com>
-Date: Wed May 2 13:55:29 2018 +0930
-
- PowerPC64 ELFv1 fp arg fixes
-
- The ELFv1 ABI says: "Single precision floating point values are mapped
- to the second word in a single doubleword" and also "Floating point
- registers f1 through f13 are used consecutively to pass up to 13
- floating point values, one member aggregates passed by value
- containing a floating point value, and to pass complex floating point
- values".
-
- libffi wasn't expecting float args in the second word, and wasn't
- passing one member aggregates in fp registers. This patch fixes those
- problems, making use of the existing ELFv2 homogeneous aggregate
- support since a one element fp struct is a special case of an
- homogeneous aggregate.
-
- I've also set a flag when returning pointers that might be used one
- day. This is just a tidy since the ppc64 assembly support code
- currently doesn't test FLAG_RETURNS_64BITS for integer types..
-
- * src/powerpc/ffi_linux64.c (discover_homogeneous_aggregate):
- Compile for ELFv1 too, handling single element aggregates.
- (ffi_prep_cif_linux64_core): Call discover_homogeneous_aggregate
- for ELFv1. Set FLAG_RETURNS_64BITS for FFI_TYPE_POINTER return.
- (ffi_prep_args64): Call discover_homogeneous_aggregate for ELFv1,
- and handle single element structs containing float or double
- as if the element wasn't wrapped in a struct. Store floats in
- second word of doubleword slot when big-endian.
- (ffi_closure_helper_LINUX64): Similarly.
-
-commit a2c6c7af9ffb9500a944abc666ced0922d0de762
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue May 1 06:46:30 2018 -0400
-
- Add license for build-time tools
-
-commit 4c2206ace07f2fb4bef43cd4bfe952ccb584dcec
-Author: Tom Tromey <tom@tromey.com>
-Date: Sat Apr 28 04:46:10 2018 -0600
-
- Fix two "return" issues in x86/ffi64.c (#431)
-
- Issue #70 pointed out that at least one compiler didn't like:
-
- return ffi_call_efi64(cif, fn, rvalue, avalue);
-
- ... where the return type is "void". This patch splits the statement
- into two.
-
- I also noticed that ffi_call_go here seems to do a double call. I
- suspect a "return" is missing here, so this patch adds it as well.
-
-commit ed3ed4d801a4d417ea304715d4d8ae581a6c6903
-Merge: 8e250c3 b69f95d
-Author: Tom Tromey <tom@tromey.com>
-Date: Fri Apr 27 10:48:51 2018 -0600
-
- Merge pull request #429 from yousong/m4subst
-
- build: fix subst toolexecdir, toolexeclibdir
-
-commit b69f95d6562b6a57c9be36da0cdf2a500adb94e9
-Author: Yousong Zhou <yszhou4tech@gmail.com>
-Date: Thu Apr 26 19:27:54 2018 +0800
-
- build: fix subst toolexecdir, toolexeclibdir
-
- On CentOS 7.4, configure script generated by autogen.sh will output the
- following values when compiling GCC source code
-
- toolexecdir='NONE/$(target_alias)'
- toolexeclibdir='NONE/$(target_alias)/lib'
-
- and cause build error
-
- ... -o libffi.la -rpath NONE/riscv64-bs-linux-gnu/lib ...
- checking for shl_load in -ldld... libtool: link: only absolute run-paths are allowed
-
-commit 8e250c390a45f722387c1881ae5f99849a2d1e22
-Author: Stephen <stephengroat@users.noreply.github.com>
-Date: Wed Apr 25 13:17:32 2018 -0700
-
- update to https for cygwin download (#428)
-
-commit 7d3cab7926d08aad9a8e54420d6878cb17efd185
-Author: Lucas Pluvinage <lucas.pluvinage@gmail.com>
-Date: Sat Apr 21 00:24:50 2018 +0200
-
- xtensa-linux: use cache flush instruction only if it is available (#426)
-
-commit 159b94e5fd4aa2d88e1b5b389092cefd9472a741
-Author: James Cowgill <jcowgill@users.noreply.github.com>
-Date: Thu Apr 19 01:28:23 2018 +0100
-
- Various MIPS Fixes (#425)
-
- * mips: simplify closure #defines
-
- This commit should have no visible effect.
-
- * mips: add special handling of variadic functions
-
- MIPS requires special handling of variadic functions which pass floating
- point arguments:
- * In the o32 ABI, all float arguments are passed in integer registers.
- * In the n32/n64 ABIs, float arguments after the ellipsis are passed in
- integer registers.
-
- Implement this in libffi. To support this in n32/n64 closures, we need to add
- a new mips_nfixedargs field to ffi_cif which will break the libffi ABI.
-
- This fixes the libffi.call/cls_longdouble_va.c test which was failing on
- 64-bit MIPS.
-
- * mips: align argn for all 64-bit types in o32 closure handler
-
- Ensure that argn is pre-aligned for all 64-bit argument types (including
- doubles) and not just integer types.
-
- This fixes closures of the form "f(float, double, <some integer args>)".
- Previously the first integer argument would be read from a2 which is garbage
- at this point (the float arguments have already "consumed" a0-a3). After
- this commit, argn is correctly padded between the "float" and "double"
- arguments so that the first integer argument is read from the stack.
-
- Fixes "double f(float,double,int)" test in #371
-
- * mips: do not read from floating point register if returning a struct
-
- In the o32 ABI, the pointer passed in a0 used to return structures
- indirectly is treated as the first argument for argument allocation purposes.
- This means that it should inhibit floating point registers the same way that
- other integer arguments do.
-
- Fixes "Double f(float,Double,double)" test in #371
-
- * mips: fix pointer cast warnings
-
- Fix two pointer cast warnings when compiled on 64-bit mips by casting
- through uintptr_t.
-
- Fixes mips64el part of #404
-
-commit f2afda08e85b02888350449dcf39a6c37cfb7bc4
-Merge: e27f70b 801c1bd
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Apr 8 18:25:43 2018 -0400
-
- Merge branch 'master' of github.com:/libffi/libffi
-
-commit e27f70b8cf2a537bef84b2cb29ad8ea6209a11b8
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Apr 8 18:25:34 2018 -0400
-
- Fix case where callback arg value is split across regs and stack
-
-commit 801c1bd712ff8c76675b7aa69c29948907f1eeff
-Author: Andreas Krebbel <38103320+Andreas-Krebbel@users.noreply.github.com>
-Date: Thu Apr 5 14:27:32 2018 +0200
-
- Fix issue #421 (#422)
-
- Fantastic - thanks for digging into this.
-
-commit 8660e6935971c5abd7b528eaf54deeccd4bbaccd
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Apr 2 08:30:17 2018 -0400
-
- 3.3 release candidate 0
-
-commit 7b7638eb0eac2adfa72f7ec9f254ba287c9947e2
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Apr 2 08:24:44 2018 -0400
-
- disable msabi testing for now
-
-commit af6773d6ab4db0577bc6b932ab5a2f98a0a8dca2
-Author: fwg <fwg@users.noreply.github.com>
-Date: Mon Apr 2 13:55:31 2018 +0200
-
- Fix appveyor windows build (#420)
-
- * Fix msvcc dll build by adding dllexport decorations to all API declarations
-
- * Fix appveyor build for VS 2013
-
- Use the new -DFFI_BUILDING_DLL for producing a working DLL. Update the
- msvcc.sh wrapper script to successfully compile the testsuite files.
-
- * MSVC build: suppress warnings in testsuite
-
- * fix testsuite on appveyor
-
-commit 48bdb02867edb7e9f3785ccb4bdff1087fb44246
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Mar 29 07:22:57 2018 -0400
-
- Trim some optimization tests
-
-commit f98e0f0d777bf962057e18d036989b2b89fdf416
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Mar 29 07:22:38 2018 -0400
-
- Simplify matrix
-
-commit fa72b054e10acaea33ec8cc395e0ea5b31c9ac9e
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Mar 29 07:10:23 2018 -0400
-
- Remove warning message from clang
-
-commit 746c3ce220cb155a8f3b613550a7ecad76f9fedc
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Mar 29 07:01:14 2018 -0400
-
- Expand ABI tests on x86. Testsuite bug fixes.
-
-commit 2eee934d0cb2beef7c0aa29767eca1ce03452ae9
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 14:45:40 2018 -0400
-
- deal with msvc warnings
-
-commit 206b2974f70f65b4c4c4d9e62b03ee7e0753ee2d
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 14:37:50 2018 -0400
-
- fix quoting issue
-
-commit 499e41c1ec6b760eff2b320ffc87e22de82a9e1d
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 14:35:10 2018 -0400
-
- Don't ignore a file
-
-commit 5b41e9f6d2c099add0e02db8c8054281f96b6d0e
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 14:34:31 2018 -0400
-
- Try different msvc hack
-
-commit e8cf133813e7fa2c606d93abab5b68989e5f6cbc
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 14:12:02 2018 -0400
-
- msvc c99 hack
-
-commit a3e20940898ed2ca96b9df87f34117d06d900e5f
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 11:58:42 2018 -0400
-
- More msvc hacks
-
-commit a82b456e98b0f3fbafe76725d1a1503d458a2178
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 11:49:46 2018 -0400
-
- msvc fixes
-
-commit a2326aaf561798c3bfd5e464b16693a094bf6c45
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 11:36:04 2018 -0400
-
- Remove debug output
-
-commit 85b6b209d7984667ce7d00351fe7e79ef6c4930c
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 11:35:23 2018 -0400
-
- Force literals to float (msvc warning)
-
-commit 2872c460ba8e96416b4f4ee4a0ed183461d8d6c9
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 11:28:40 2018 -0400
-
- Fix msvc linking
-
-commit b40a386c22a2bd164819b4f398b722357222b7c1
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 11:20:21 2018 -0400
-
- Fix library path handling
-
-commit d78c5f64f834c24a769bee78cfb7db4d468b6b21
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 11:14:56 2018 -0400
-
- Deal with libpath
-
-commit f318bb63c5dc623d5a69ffc4a59a330050cac567
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 08:25:26 2018 -0400
-
- Fix library path handling
-
-commit 4f0c9cb39b7599312729278380ce63247bca226b
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 08:10:03 2018 -0400
-
- Use mixed cygpath paths
-
-commit d3693b4665de7ef69b61fb4e483d5686302f9c69
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 08:05:42 2018 -0400
-
- Copy - don't symlink - to support msvc builds
-
-commit 51ce3696cd0da4716d86b73a30bd89e139ec4b74
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 07:35:33 2018 -0400
-
- Use cygpath to convert windows paths
-
-commit 70b93e4d863c1ff2a6498455339e17df3d7fe784
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 07:14:59 2018 -0400
-
- try to fix windows builds
-
-commit 377134d7a946df13b60ff9c9dacc895e82c36178
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 07:06:01 2018 -0400
-
- Reduce verbosity
-
-commit d01ef5b875dedcb9f7b3039b2334cbd594fdfcd4
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 06:23:29 2018 -0400
-
- iOS builds
-
-commit d13583f55fb31a302684cbc62c300ae81eb577e9
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 06:22:57 2018 -0400
-
- Fix -L support
-
-commit d49911544bf9d2b4fab782b0c5e76a68074223df
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 05:59:26 2018 -0400
-
- Fix quoting
-
-commit 8f47ec404fcf5a082fc4537ede8cdf897f4c5226
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 05:35:35 2018 -0400
-
- Don't set AM_MAKEFLAGS
-
-commit df314193dc6cd00978b6e1517866448b604199af
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 05:13:38 2018 -0400
-
- Run tests with lots of debug output
-
-commit b394947518fb15887802fe3bc7f0a337c495d65d
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 05:11:52 2018 -0400
-
- Add -L and -l support
-
-commit 33da6c075299317885385f19680b58a1e9feab5e
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 05:07:08 2018 -0400
-
- Mention C99 and build requirements
-
-commit e6bdbd7888b5c8a90f3c91f4d6caf3c8d574f3b5
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 04:46:04 2018 -0400
-
- Remove reference to wiki
-
-commit 24eb1f88d788399dde5fbb4804767e6b6cbf1bc8
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 04:09:56 2018 -0400
-
- Refactor travis build instructions. Add iOS build
-
-commit ffc3ff162a15ed0ed0e946815c950c69ee0c8343
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 04:02:06 2018 -0400
-
- Add issue template
-
-commit 5c2ca479e726dc2feec43e25475c63361387bf20
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 27 04:01:37 2018 -0400
-
- Remove uninitialized warning. Fix #163.
-
-commit 0081378017c33a4b9b6fbf20efabdd9959d6a48d
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 24 09:05:14 2018 -0400
-
- revert
-
-commit 59d44242e15d2979291fe6793ddfb2681b7480ef
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 24 08:45:59 2018 -0400
-
- Try bhaible tests in appveyor
-
-commit 6f7c29c5a6d2850ce53b99efcc71fcc4e8f8c8cc
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 24 08:40:04 2018 -0400
-
- Formatting fixes
-
-commit f3c2729ee4026c9f70a6656603bac8ba2ec40a5d
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Mar 23 11:47:29 2018 -0400
-
- Add libffi.map.in to extra dist files
-
-commit 6d2233f96a08c5ac01a64e7b84e2bd678eed0a4b
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Mar 23 09:06:08 2018 -0400
-
- Add sparc solaris build notes
-
-commit 99a80d2fc4ede48348af2edfb7126d60609c4b71
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 21:22:55 2018 -0400
-
- Fix formatting
-
-commit a3e87ac8e7b7e609ab84541a69c7e51873efa437
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 20:36:52 2018 -0400
-
- Fix formatting
-
-commit cec3a3a201f17a7f018f25e1a0917bd5206e5a5a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 16:00:04 2018 -0400
-
- Don't align-double for 32-bit x86
-
-commit f34f8039c10c4d8d728bc335dcf2b2a38f6e8b50
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 15:30:00 2018 -0400
-
- Remove debug output
-
-commit f31b915314b12904b858b54cfdf670ceaeda7b2d
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 15:13:21 2018 -0400
-
- Add m4/ax_require_defined.m4
-
-commit a2dc5848b53e9e45ff68e5ef70683b5ffb82592e
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 13:41:15 2018 -0400
-
- travis debug
-
-commit 81d345b2cff039c4389fad283a108ad978b609e0
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 13:32:03 2018 -0400
-
- Update autoconf archive macros
-
-commit 369ef49f71186fc9d6ab15614488ad466fac3fc1
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 12:53:42 2018 -0400
-
- Add missing FFI_GNUW64 enum
-
-commit 56655e58c7f966685c0d5635ee7215733121ae41
-Merge: 43980dd 9bc40d8
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 12:34:18 2018 -0400
-
- Merge branch 'master' of github.com:/libffi/libffi
-
-commit 43980dd10e0d5705e52f24d63988b722e31bf330
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 12:32:10 2018 -0400
-
- Add FFI_GNUW64 ABI for GNU 80-bit long double support
-
-commit 9bc40d87ea5950969b234ed56cd2c6acd883fa0e
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 12:32:10 2018 -0400
-
- Add FFI_GWIN64 ABI for GNU 80-bit long double support
-
-commit d46406088d28b038a0a0f7396d9621f431482f6a
-Author: Ryan C. Underwood <nemesis@icequake.net>
-Date: Sun Mar 18 07:00:42 2018 -0700
-
- Fully allocate file backing writable maps (#389)
-
- When ftruncate() is used on a filesystem supporting sparse files,
- space in the file is not actually allocated. Then, when the file
- is mmap'd and libffi writes to the mapping, SIGBUS is thrown to
- the calling application. Instead, always fully allocate the file
- that will back writable maps.
-
-commit 247e44b3ef653f210de614a749b71449b8c70764
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 18 07:01:54 2018 -0400
-
- Fix return values
-
-commit 1f99701fad1761ffe4e9adf88cfe26f74f427e7c
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 17 22:49:58 2018 -0400
-
- Make tests compile/run standalone
-
-commit d974207cd6373ff282a64038564d99b853dc3fab
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 17 09:03:42 2018 -0400
-
- Formatting fixes. Add 'bug fixes' note.
-
-commit a33bfa9b12993aae2edf669f62e141a84286d4de
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 17 07:17:24 2018 -0400
-
- xfail unwind tests for moxie
-
-commit 8bf05481436ba085df3adfff2b47a879df738d67
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Mar 16 23:54:28 2018 -0400
-
- Install moxie libstdc++
-
-commit 84b383eda67ba75a6456e4b3587f17b749e6e1a1
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Mar 16 23:36:51 2018 -0400
-
- Install moxie-elf-g++
-
-commit 6a801d042ac1212fe8c0e11abb865061e515aa43
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Mar 16 17:53:33 2018 -0400
-
- Fix closure case where 8-byte value is partially passed in register. Fixes cls_many_mixed_float_double test case.
-
-commit 0f0ba9e0ec52e0297c91cb63a889980a6f847219
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Mar 16 07:28:33 2018 -0400
-
- Run dejagnu's runtest with -a option to prevent travis timeouts after 10min
-
-commit 725454196afab82f7da7bd719e8bddf7cd7837dd
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Mar 15 08:17:18 2018 -0400
-
- fix .travis.yml
-
-commit d71051c46a795a0669b2d83804030746f790edf4
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 21:21:06 2018 -0400
-
- fix .travis.yml
-
-commit e86aa54ce3418081dca403217c9216c773b82560
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 21:00:55 2018 -0400
-
- fix .travis.yml
-
-commit 5b538ed61fb13efc8f01bad014c5485231714c96
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 20:32:00 2018 -0400
-
- fix .travis.yml
-
-commit 6ed64a7953178cf07d2793650fcd64caa6b51d53
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 20:22:33 2018 -0400
-
- fix .travis.yml
-
-commit 90809e928f8b5a0cdf0787d799111bc33689a9d1
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 14:09:39 2018 -0400
-
- fix .travis.yml
-
-commit 85e4c62351bd1e45dd6d77916778e18c435f1723
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 13:47:27 2018 -0400
-
- fix .travis.yml
-
-commit aa8a5ec4a4ec4a4460ec3cd4e396e09ceaa3a2fa
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 13:25:04 2018 -0400
-
- fix .travis.yml
-
-commit 7c3e5da401ab7efef83a5bd4e7f64b0df053da0c
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 13:07:04 2018 -0400
-
- fix .travis.yml
-
-commit 19aec1989382fab8bd86c556aa24751a75b8246e
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 12:40:58 2018 -0400
-
- Fix travis.yml
-
-commit bf337b070977fb7e8934fc91e4d0e60209f53448
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 12:15:04 2018 -0400
-
- yaml syntax error fix
-
-commit 076d5a987e016669993154b91525b02978c56727
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 11:13:32 2018 -0400
-
- markdown fixes
-
-commit d2f7e788aecf37971c9be1cd650f78a3e4061e18
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 09:06:38 2018 -0400
-
- Fix test cases with short results
-
-commit 18fe190068563bb2bf52a0993017887f438c85a4
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 08:02:10 2018 -0400
-
- Debug travis output
-
-commit 718a4177f23e9d6c5476d0118d49a3a093d72c6c
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 14 07:40:53 2018 -0400
-
- test
-
-commit 486c34b65deb43d6d9025b2a40284606f97f4e0b
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 23:31:18 2018 -0400
-
- debug
-
-commit 00464aa52022674bdc1f5aa9b2ceb575c9a04b87
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 23:30:52 2018 -0400
-
- debug
-
-commit eb0544d0d42e5aef56ee1df0861bcd0c95102f88
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 23:20:15 2018 -0400
-
- Debug env
-
-commit 9d5bd29d8dfb5f89d0927a175443240a19e93890
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 23:07:10 2018 -0400
-
- Refactor
-
-commit 52a364d7699230be5e883f32b9ac0caaea0300b1
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 22:49:48 2018 -0400
-
- fix moxie build
-
-commit 1a32b3f146f7ade701cea74e3983b16145f93393
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 22:44:13 2018 -0400
-
- fix moxie build
-
-commit e8958c3a64b5e59f0477bcaafaf9c03337d9f445
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 22:36:41 2018 -0400
-
- revert test
-
-commit 58315ae125482c44821cfbdce41e350380024d0e
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 22:35:50 2018 -0400
-
- test
-
-commit 6239c28741a8abc1bd06cb47329d8c5cdb359c90
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 22:13:44 2018 -0400
-
- Add experimental moxie travis build
-
-commit 01db31d94e97e71836fe862826bc8a2a399dd619
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 20:41:55 2018 -0400
-
- Update moxie sub opcode
-
-commit e8f5a43033d53ad631ba477b78a3def61783a1dc
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 09:27:00 2018 -0400
-
- Fix appveyor badge
-
-commit d1689dd3bf78f4975aa6a6a16cbffcb794283acb
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 09:24:37 2018 -0400
-
- Fix travis badge. Add REAME.md to dist files
-
-commit 785351fbc2a49f05535c412067ac51f906612779
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 09:21:49 2018 -0400
-
- Preformat release notes
-
-commit 8c7fbd1616b075e3077346c7bf56befd723a9355
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 09:20:44 2018 -0400
-
- Preformat release notes
-
-commit 54f31b00562e75e6aae2b736c70e6713618640cb
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 09:17:57 2018 -0400
-
- Try to fix table
-
-commit 3a29a27a86624512f405e4c9962276485517caf1
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 09:14:40 2018 -0400
-
- Clean up markdown table
-
-commit fbfc3b048fcf3f699f4495ca70b7e58461a0df4f
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 09:12:21 2018 -0400
-
- Move to markdown
-
-commit a31d3d3ba6644d308b6fb8cea2a60976e0531f4a
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 09:11:24 2018 -0400
-
- Add travis and appveyor build badges
-
-commit 16313cb2746ceed6bc1d25b52604642c14758e01
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 08:52:30 2018 -0400
-
- Support compiler specific warning suppression flags
-
-commit cca6d1fb549e422514df4aad68f2ca9a8313327d
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 08:51:34 2018 -0400
-
- Support compiler specific warning suppression flags
-
-commit 9291f941c2df5ddf967f701b258ac2b3cc9d0820
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 08:37:21 2018 -0400
-
- Add bhaible's missing Makefile
-
-commit bede01d82ec2f1cfe2bb42233fcd408a6e3a6323
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 07:53:33 2018 -0400
-
- Remove stray directory
-
-commit 9aefbb1031c9be7c5121ab24742e025ccff236c4
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 07:51:02 2018 -0400
-
- Update version number to next pre-release
-
-commit ddf7a8f7511a038342f56c08dac718148e2f0151
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 13 07:47:57 2018 -0400
-
- Update test list for dist
-
-commit 6186261cb36a33abbf31430569f83ccd7685474e
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Mar 12 21:53:18 2018 -0400
-
- Add Bruno Haible and Bill Triggs' libffi testsuite
-
-commit 4e8f79d5587ddb8e027f4df213e90f943e286594
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 11 18:21:46 2018 -0400
-
- Next release will be 3.3
-
-commit 3840d49aaa831d649b1597518a2903dfed0d57f3
-Author: Stef O'Rear <sorear2@gmail.com>
-Date: Sun Mar 11 05:55:15 2018 -0700
-
- New RISC-V port (#281)
-
- * Add RISC-V support
-
- This patch adds support for the RISC-V architecture (https://riscv.org).
-
- This patch has been tested using QEMU user-mode emulation and GCC 7.2.0
- in the following configurations:
-
- * -march=rv32imac -mabi=ilp32
- * -march=rv32g -mabi=ilp32d
- * -march=rv64imac -mabi=lp64
- * -march=rv64g -mabi=lp64d
-
- The ABI currently can be found at
- https://github.com/riscv/riscv-elf-psabi-doc/blob/master/riscv-elf.md .
-
- * Add RISC-V to README
-
- * RISC-V: fix configure.host
-
-commit dca52b55bc2ac0213c20849d7e9e19fbc9202023
-Merge: 83d9aba 11de69d
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 11 08:50:01 2018 -0400
-
- Merge pull request #406 from trofi/master
-
- ia64: fix variadic function closures with FP arguments
-
-commit 83d9aba3a44dff8426052312a9445a7ef52f1db1
-Merge: ab15405 b58caef
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 11 08:48:42 2018 -0400
-
- Merge pull request #407 from trofi/ia64-small-struct
-
- ia64: fix small struct return
-
-commit ab154056937782c1c7f7005c8b46c5179bc719cb
-Merge: 9429968 e66fd67
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 11 08:46:58 2018 -0400
-
- Merge pull request #409 from andreas-schwab/master
-
- Revert "Fix passing struct by value on aarch64"
-
-commit e66fd678200db456a2e9860e80451773efa96fe0
-Author: Andreas Schwab <schwab@suse.de>
-Date: Tue Feb 20 10:47:09 2018 +0100
-
- Revert "Fix passing struct by value on aarch64"
-
- This reverts commit 482b37f00467325e3389bab322525099860dd9aa.
-
- That was actually a bug in python, see <https://bugs.python.org/issue30353>.
-
-commit b58caef7fd620408be9239ac24ea89d5bc84f30b
-Author: Sergei Trofimovich <slyfox@gentoo.org>
-Date: Sat Feb 17 19:00:40 2018 +0000
-
- ia64: fix small struct return
-
- This change fixes libffi.call/struct10.c failure on ia64:
- FAIL: libffi.call/struct10.c -W -Wall -Wno-psabi -O0 execution test
-
- .Lst_small_struct handles returns for structs less than 32 bytes
- (following ia64 return value ABI [1]). Subroutine does roughly the
- following:
-
- ```
- mov [sp+0] = r8
- mov [sp+8] = r9
- mov [sp+16] = r10
- mov [sp+24] = r11
- memcpy(destination, source=sp, 12);
- ```
-
- The problem: ia64 ABI guarantees that top 16 bytes of stack are
- scratch space for callee function. Thus it can clobber it. [1]
- says (7.1 Procedure Frames):
- """
- * Scratch area. This 16-byte region is provided as scratch storage
- for procedures that are called by the current procedure. Leaf
- procedures do not need to allocate this region. A procedure may
- use the 16 bytes at the top of its own frame as scratch memory,
- but the contents of this area are not preserved by a procedure call.
- """
-
- In our case 16 top bytes are clobbered by a PLT resolver when memcpy()
- is called for the first time. As a result memcpy implementation reads
- already clobbered data frop top of stack.
-
- The fix is simple: allocate 16 bytes of scrats space prior to memcpy()
- call.
-
- [1]: https://www.intel.com/content/dam/www/public/us/en/documents/guides/itanium-software-runtime-architecture-guide.pdf
-
- Bug: https://bugs.gentoo.org/634190
- Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
-
-commit 45da2fcbcd0ecaba673275d22b04fac3e4376e22
-Author: Sergei Trofimovich <slyfox@gentoo.org>
-Date: Sat Feb 17 18:53:02 2018 +0000
-
- new test: return small struct
-
- The bug originally was discovered in https://bugs.gentoo.org/634190
- where complicated callback was returning invalid data on ia64.
-
- This change adds minimal reproducer that fails only on ia64 as:
-
- FAIL: libffi.call/struct10.c -W -Wall -Wno-psabi -O0 execution test
- FAIL: libffi.call/struct10.c -W -Wall -Wno-psabi -O2 execution test
- FAIL: libffi.call/struct10.c -W -Wall -Wno-psabi -O3 execution test
- FAIL: libffi.call/struct10.c -W -Wall -Wno-psabi -Os execution test
-
- Test passes on amd64. The fix is in the following commit.
-
- Bug: https://bugs.gentoo.org/634190
- Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
-
-commit 11de69ddb788e4d87ef653898878384116ac16c6
-Author: Sergei Trofimovich <slyfox@gentoo.org>
-Date: Sun Feb 11 11:29:39 2018 +0000
-
- ia64: fix variadic function closures with FP arguments
-
- libffi test framework already flagged failures as:
-
- ```
- FAIL: libffi.call/cls_double_va.c -W -Wall -Wno-psabi -O0 output pattern test, is 7.0
- res: 4
- 0.0
- res: 4
- ? should match 7.0
- ?es: 4
- ?.0
- res: 4
- ```
-
- Failure happens here at
-
- ```c
- // testsuite/libffi.call/cls_double_va.c
- ...
- char* format = "%.1f\n";
- double doubleArg = 7;
- ...
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_double_va_fn, NULL,
- code) == FFI_OK);
- res = ((int(*)(char*, ...))(code))(format, doubleArg);
- ```
-
- libffi expects 'doubleArg' to be located in 'f9' (second FP argument) but
- gcc placed it to 'r33' (second GR).
-
- ia64 software [1] manual described argument passing ABI in
- "8.5.2 Register Parameters" as:
-
- """
- If an actual parameter is known to correspond to a floating-point
- formal parameter, the following rules apply:
- a) The actual parameter is passed in the next available floating-point
- parameter register, if one is available. Floating-point parameter
- registers are allocated as needed from the range f8-f15, starting
- with f8.
- b) If all available floating-point parameter registers have been used,
- the actual parameter is passed in the appropriate general register(s).
- (This case can occur only as a result of homogeneous floating-point
- aggregates, described below.)
-
- If a floating-point actual parameter is known to correspond to
- a variable-argument specification in the formal parameter list,
- the following rule applies:
- c) The actual parameter is passed in the appropriate general
- register(s).
-
- If the compiler cannot determine, at the point of call,
- whether the corresponding formal parameter is a varargs parameter,
- it must generate code that satisfies both of the above conditions.
- (The compiler’s determination may be based on prototype declarations,
- language standard assumptions, analysis, or other user options or
- information.)
- """
-
- We have [c] case here and gcc uses only GR for parameter passing.
-
- The change binds known variadic arguments ro GRs instead of FPs as those
- are always expected to be initialized for all variadic call types.
-
- This fixes all 10 failures on ia64-unknown-linux-gnu:
-
- ```
- === libffi Summary ===
- -# of expected passes 1945
- -# of unexpected failures 10
- +
- +# of expected passes 1955
- ```
-
- [1]: https://www.intel.com/content/dam/www/public/us/en/documents/guides/itanium-software-runtime-architecture-guide.pdf
-
- Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
-
-commit 9429968b828de8775cfd7f139374888943f2186a
-Merge: f08b2be 28d3b61
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 10 23:23:33 2018 -0500
-
- Merge pull request #403 from frida/fix/x86-sysv-pic-closure-regression
-
- Fix x86 SysV closure in PIC mode
-
-commit f08b2be6273f471863f1ea1afb0078a96fe73d74
-Merge: c194448 482b37f
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 10 23:21:49 2018 -0500
-
- Merge pull request #405 from andreas-schwab/master
-
- Fix passing struct by value on aarch64
-
-commit 482b37f00467325e3389bab322525099860dd9aa
-Author: Andreas Schwab <schwab@suse.de>
-Date: Mon Sep 18 12:44:08 2017 +0200
-
- Fix passing struct by value on aarch64
-
- This fixes the ctypes test in the python testsuite.
-
-commit 28d3b61bdd8b9fe786cb431165f2fb95f4e275d3
-Author: Ole André Vadla Ravnås <oleavr@gmail.com>
-Date: Sat Jan 20 23:56:17 2018 +0100
-
- Fix x86 SysV closure in PIC mode
-
- The assembly single-line comments swallowed up the remaining assembly
- code of the macros due to lack of line-endings.
-
- This is a regression introduced in b7f6d7a.
-
-commit c194448ef08b4c0183c68dda95a4b8b9cfc47985
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 10 09:38:15 2018 -0500
-
- adjust env usage in travis
-
-commit 5314b1067145d30acdc5bba3bebb788e8acfdaae
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 10 07:22:51 2018 -0500
-
- test static lib
-
-commit bec6135dff061a35065efc106f920940a82c28ee
-Merge: f6ecf10 d15581c
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 10 07:20:04 2018 -0500
-
- Merge pull request #393 from thejunkjon/master
-
- Linker error "recompile with -fPIC" for x86_64
-
-commit f6ecf10ca021e94d496c75cc43c417161edf28b3
-Merge: c50ba18 746dbe3
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Jan 5 16:51:44 2018 -0500
-
- Merge pull request #401 from wzssyqa/jr-r6
-
- mips/ffi.c: fix encoding for jr on r6
-
-commit 746dbe3a6a79a41931c03b51df2972be4d5e5028
-Author: YunQiang Su <wzssyqa@gmail.com>
-Date: Wed Jan 3 10:07:41 2018 +0800
-
- mips/ffi.c: fix encoding for jr on r6
-
- mips/ffi.c: instruction jr has a different encoding for r6
-
-commit c50ba182f43537e29dd92cfd9b2fa7a30549a06e
-Merge: 54cb3e2 af6949b
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 1 15:18:46 2018 -0500
-
- Merge pull request #398 from emaste/master
-
- Enable symbol versioning when ld is LLVM's lld
-
-commit 54cb3e2345ee8e2483d4705a9fb2967b6e5a9bd1
-Merge: 716bfd8 94c102a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Dec 31 07:46:05 2017 -0500
-
- Merge pull request #396 from wzssyqa/master
-
- mips/n32.S: disable .set mips4 on mips r6
-
-commit af6949b7af98404729e04227165d0e32ce550ce8
-Author: Ed Maste <emaste@freebsd.org>
-Date: Sun Dec 17 23:08:12 2017 -0500
-
- Enable symbol versioning when ld is LLVM's lld
-
- Fixes #397
-
-commit 94c102aa69b04337f63498e0e6551fcdce549ae5
-Author: YunQiang Su <wzssyqa@gmail.com>
-Date: Sun Dec 10 14:25:01 2017 +0800
-
- Not set mips on mips r6
-
- MIPS release changed encodes of some instructions, include ll/sc etc.
-
- if .set mips4 on mips r6, as will generate some wrong encode of some instructions.
-
-commit d15581c6969657c79afcff4865bdc8f5ff23a2f7
-Author: jon <thejunkjon@gmail.com>
-Date: Fri Dec 1 00:34:30 2017 -0800
-
- Updating calls to ffi_closure_unix64_inner and ffi_closure_win64_inner to use PLT. Without this fix, statically linking libffi causes the linker error i.e. 'requires dynamic R_X86_64_PC32 reloc against ffi_closure_unix64_inner which may overflow at runtime; recompile with -fPIC)'
-
-commit 716bfd83177689e2244c4707bd513003cff92c68
-Merge: 4fdbb05 cd5e9f8
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Nov 5 09:02:37 2017 -0500
-
- Merge pull request #387 from trofi/master
-
- Makefile.am: add 'src/s390/internal.h' to source tarball
-
-commit cd5e9f8b87cc387d3ffef4db81ee6af200a84183
-Author: Sergei Trofimovich <slyfox@gentoo.org>
-Date: Sun Nov 5 13:56:42 2017 +0000
-
- Makefile.am: add 'src/s390/internal.h' to source tarball
-
- commit 2f530de168e0253ac06e044c832132c496e8788b
- ("s390: Reorganize assembly") introduced new header
- (similar to other arches) but did not add it to source
- tarball.
-
- As a result build from 'make dist' tarballs failed as:
-
- ```
- ../src/s390/ffi.c:34:10: fatal error: internal.h: No such file or directory
- #include "internal.h"
- ^~~~~~~~~~~~
- ```
-
- To fix it the change adds file to 'Makefile.am'.
-
- Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
-
-commit 4fdbb0578e921a9da146c2b040061a3a39fe4fda
-Merge: b302bc3 2bfcd29
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 3 07:05:31 2017 -0400
-
- Merge pull request #320 from 0-wiz-0/master
-
- Support NetBSD with mprotect.
-
-commit b302bc3dfe47e3ea57de11610fced3170c06df28
-Merge: 14eac93 1fb788a
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 3 07:03:55 2017 -0400
-
- Merge pull request #322 from compnerd/aarch64-base
-
- aarch64: fix index base register for AArch64
-
-commit 14eac93869eb109bea1daeb4f00609169d5488ff
-Merge: ad15ae7 9fc9dc5
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 3 06:49:03 2017 -0400
-
- Merge pull request #384 from yan12125/fix-sgidefs-checking
-
- Fix linux detection (closes #303)
-
-commit 9fc9dc535ee7af28f49f86a8ecacb7f575c46ba4
-Author: Yen Chi Hsuan <yan12125@gmail.com>
-Date: Fri Oct 27 16:12:56 2017 +0800
-
- Fix linux detection (closes #303)
-
-commit 1fb788ac898290d8e3044ca4c0a4fb3c3c254ce5
-Author: Saleem Abdulrasool <compnerd@compnerd.org>
-Date: Tue Oct 10 11:37:00 2017 -0700
-
- aarch64: fix index base register for AArch64
-
- The base is passed in `x3`, not in `x2`. This fixes the indexing base
- so that the right value is used.
-
-commit ad15ae762c8b3999e626ebccb9cf454455119555
-Merge: dc2ff5b 5e4fcdc
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Oct 25 13:16:49 2017 -0400
-
- Merge pull request #298 from frida/fix/ios-trampoline-table-complexity
-
- Simplify iOS trampoline table allocation
-
-commit dc2ff5baabf89d473d61ae4b468638f8ea98bb04
-Merge: 927da71 79d1509
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Oct 25 13:11:40 2017 -0400
-
- Merge pull request #323 from compnerd/x86-alloca-alignment
-
- x86: align alloca to 16-byte boundary
-
-commit 927da71662f349f656fc1c5d0aaa533005e24f47
-Merge: a0455c0 181fc4c
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Oct 25 13:05:53 2017 -0400
-
- Merge pull request #379 from jlj/master
-
- Xcode build improvements
-
-commit a0455c031824c6ab3f1a7a6ef9912edad6ebd742
-Merge: 0faf614 9d9d92b
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Oct 25 13:04:23 2017 -0400
-
- Merge pull request #383 from hjl-tools/hjl/master
-
- Hjl/master
-
-commit 0faf614529ae7ac8bc929415a6e1b076ba1b8cc5
-Merge: 8d26e8c 3c372c3
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Oct 25 13:03:55 2017 -0400
-
- Merge pull request #381 from compnerd/ffi-nullptr-deref
-
- arm: fix a level of indirection issue
-
-commit 9d9d92b47f3f73644f808ae38e97d1ea8f4d22df
-Author: H.J. Lu <hjl.tools@gmail.com>
-Date: Wed Oct 25 04:59:31 2017 -0700
-
- Skip WIN64/EFI64 support for x32
-
- Since x32 doesn't support WIN64/EFI64, skip it if __ILP32__ is defined.
-
-commit b2a343ffc68f1af5368281e063c0ca5571c611cc
-Author: H.J. Lu <hjl.tools@gmail.com>
-Date: Wed Oct 25 04:36:49 2017 -0700
-
- Don't include WIN64/EFI64 for x32
-
- Since x32 doesn't support WIN64/EFI64, don't include it for x32. Also
- x32 has sizeof size_t == 4. But TARGET should be X86_64.
-
-commit 3c372c384a94db23fdaf9fe64a4beb86159cf6d3
-Author: Saleem Abdulrasool <compnerd@compnerd.org>
-Date: Tue Oct 24 13:53:56 2017 -0700
-
- arm: fix a level of indirection issue
-
- Rather than relying on the stack being 0'ed out always, do it manually.
- The stack generally happened to be zero, and because the compiler
- realizes that the tests are dealing with chars truncates the read value.
- However, the top 3 nibbles of the value are undefined and may be
- non-zero. The indirection level caused a null-pointer dereference.
-
- Explicitly scribbling on the stack during the allocation causes test
- failures without the original zexting behaviour.
-
-commit 181fc4cc9ca211f3bc8209cecf3b2348b0674e21
-Merge: 8d26e8c 54529ba
-Author: Jean-Luc Jumpertz <jean-luc@celedev.eu>
-Date: Mon Oct 23 15:02:29 2017 +0200
-
- Merge branch 'master' based on ksjogo/libffi
-
- Added a tvOS target in Xcode project. Misc Xcode project cleanup.
- Fix macOS build target in Xcode project.
-
- # Conflicts:
- # src/aarch64/ffi.c
- # src/x86/ffi64.c
-
-commit 54529ba1db9974b5efcbd2e893c44b6b01b0b2c8
-Author: Jean-Luc Jumpertz <jean-luc@celedev.eu>
-Date: Mon Oct 23 09:49:35 2017 +0200
-
- Added a tvOS target in Xcode project. Misc Xcode project cleanup.
-
-commit 79d1509cb06ba9067f56e2c62394d7bc60fa6bf2
-Author: Saleem Abdulrasool <compnerd@compnerd.org>
-Date: Tue Oct 10 11:39:45 2017 -0700
-
- x86: align alloca to 16-byte boundary
-
- Align the stack allocation to a 16-byte boundary. This ensures that the
- stack parameters are 16-byte aligned which is needed for some
- instructions.
-
-commit 8d26e8c6da23b10331181a4bbf837f479ce5d7d2
-Merge: 1c9171e ed7488c
-Author: Tom Tromey <tom@tromey.com>
-Date: Tue Oct 17 10:46:49 2017 -0600
-
- Merge pull request #326 from trofi/master
-
- src/ia64/unix.S: unbreak small struct handling
-
-commit ed7488c003765c7ee71b7da3e8c21f431b043809
-Author: Sergei Trofimovich <slyfox@gentoo.org>
-Date: Tue Oct 17 13:00:51 2017 +0100
-
- src/ia64/unix.S: unbreak small struct handling
-
- commit 6e8a4460833594d5af1b4539178025da0077df19
- added FFI_TYPE_COMPLEX value type (comes after FFI_TYPE_POINTER)
-
- ia64 ffi_closure_unix reiles on the ordering of
- FFI_ enums as ia64 has ia64-specific FFI types:
- small struct and FPU extesions.
-
- As a result all tests handling small structs broke.
-
- The change fixes dispatch table by adding (no-op)
- FFI_TYPE_COMPLEX entry
- This has positive effect of unbreaking most tests
- on ia64:
-
- === libffi Summary ===
-
- -# of expected passes 1595
- -# of unexpected failures 295
- +# of expected passes 1930
- +# of unexpected failures 10
- # of unsupported tests 30
-
- Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
-
-commit 1c9171ec89943d9b4b10a54091c8b5c104eb258d
-Merge: 9f1f874 7ad0ae7
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 10 23:19:57 2017 -0400
-
- Merge pull request #324 from compnerd/arm-zext
-
- arm: zext return value parameters
-
-commit 7ad0ae7f42f3e208431ab66a9032dc9549f978d0
-Author: Saleem Abdulrasool <compnerd@compnerd.org>
-Date: Tue Oct 10 11:44:05 2017 -0700
-
- arm: zext return value parameters
-
- The closure function (invoked as closure->fun in ffi_closure_XXX_inner)
- will only populate the actual number of bytes for the true return type,
- which may be a character. This leaves garbage on the stack when the
- assembly closure function (i.e. ffi_closure_XXX) reads the return value
- off of the stack into r0 as a 4-byte value. ffi_closure_XXX always
- leaves room for at least 4 bytes here, so we can safely set them to 0.
- Otherwise, if there is garbage in any of these bytes, these end up in r0
- and in the returned value as well.
-
-commit 2bfcd29955c02b67fa10a68cc4200f6838181e0f
-Author: Joerg Sonnenberger <joerg@NetBSD.org>
-Date: Mon Oct 2 15:34:03 2017 +0200
-
- Support NetBSD with mprotect.
-
- Signed-off-by: Thomas Klausner <wiz@NetBSD.org>
-
-commit 9f1f8741b2ec0c8898ecff7b93005627b915dd02
-Merge: dca078f 6cf0dea
-Author: Tom Tromey <tom@tromey.com>
-Date: Sun Oct 1 20:25:50 2017 -0600
-
- Merge pull request #319 from angerman/patch-5
-
- Adds `local.exp` to DISTCLEANFILES
-
-commit 6cf0dea78a5a4584eda871e264043974d0453e53
-Author: Moritz Angermann <moritz.angermann@gmail.com>
-Date: Mon Oct 2 10:20:16 2017 +0800
-
- Change CLEANFILES to DISTCLEANFILES
-
-commit dca078f468ff696134195e85fed3f48260115651
-Merge: 540258d bccba9a
-Author: Tom Tromey <tom@tromey.com>
-Date: Sun Oct 1 20:19:53 2017 -0600
-
- Merge pull request #316 from angerman/patch-2
-
- Add `configure.host` and `libtool-version` to the `EXTRA_DIST` files
-
-commit 540258d13e1d427254cbeddacdd2bb1ab2c307d1
-Merge: 93d8e7d 4c6aa78
-Author: Tom Tromey <tom@tromey.com>
-Date: Sun Oct 1 20:17:02 2017 -0600
-
- Merge pull request #317 from angerman/patch-3
-
- Add src/x86/asmnames.h to noinst_HEADERS
-
-commit bccba9a34e8ba0fe671c4b94671fea2efe181b01
-Merge: a1e6ccb 59d65d7
-Author: Moritz Angermann <moritz.angermann@gmail.com>
-Date: Sun Oct 1 12:48:17 2017 +0800
-
- Merged
-
-commit 6b6df1a7bb377651a07663879bd4162f0059dc5c
-Author: Moritz Angermann <moritz.angermann@gmail.com>
-Date: Sun Oct 1 12:37:53 2017 +0800
-
- Adds `local.exp` to CLEANFILES
-
- With #315, #316, #317, #318 and this patch, running
- ```
- AM_DISTCHECK_CONFIGURE_FLAGS=--disable-docs make distcheck
- ```
- should complete successfully.
-
-commit 59d65d74ae72bd24fbf78f045592c5168f0b0784
-Author: Moritz Angermann <moritz.angermann@gmail.com>
-Date: Sun Oct 1 12:23:31 2017 +0800
-
- Include `libtool-version` in the EXTRA_DIST files.
-
-commit 4c6aa78d75f0c426a23c27af74155aa2535021d6
-Author: Moritz Angermann <moritz.angermann@gmail.com>
-Date: Sun Oct 1 11:32:41 2017 +0800
-
- Add src/x86/asmnames.h to noinst_HEADERS
-
- In eaa59755fcbb692a8cb763c7f9f24a350aadbd30, macros from `unix64.S` were extracted into `asmnames.h` to be used with `win64.S` as well. As such these are required by `unix64.S`, which fails to build without them.
-
-commit a1e6ccb67e7d7f2b235016aa6c6733c5743945a1
-Author: Moritz Angermann <moritz.angermann@gmail.com>
-Date: Sun Oct 1 11:28:40 2017 +0800
-
- Add `configure.host` to the `EXTRA_DIST` files
-
- When running `make dist`, `configure.host` would not result in the distribution tarball, however `configure` would try to read it, and as such the tarball would not be buildable.
-
-commit 93d8e7dd17b08ff195af3580584ccd5c2228202f
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Sep 27 21:51:34 2017 -0400
-
- Fix #265
-
-commit 02a5145abbae2e311d5aeeee606c5b5745a99b55
-Merge: 10099d6 7d504f7
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Sep 27 21:43:03 2017 -0400
-
- Merge pull request #263 from ksjogo/master
-
- fix ios builds
-
-commit 10099d6cad8418a10c1508235d1f458993ac51fe
-Merge: c8f1aa3 ed84883
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Sep 27 20:54:09 2017 -0400
-
- Merge pull request #271 from frida/fix/qnx-cache-flushing
-
- arm: Fix cache flushing on QNX
-
-commit c8f1aa3d0459c6f1be6884b324b4d2d785ecfd78
-Merge: db4dad9 50e408c
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Sep 27 20:53:50 2017 -0400
-
- Merge pull request #307 from zw3rk/master
-
- Support -ios triple
-
-commit db4dad97e2589ca700d1b5b54eeb332137a152ad
-Merge: 8a16f2f 9c12209
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Sep 27 20:47:08 2017 -0400
-
- Merge pull request #312 from fjricci/fix_ub
-
- Fix misaligned memory access in ffi_call_int
-
-commit 8a16f2f47fdb6a985d201baa02a1d226562af4d8
-Merge: b230910 0ff9419
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Sep 27 20:45:15 2017 -0400
-
- Merge pull request #308 from trex58/master
-
- This patch enables FFI Go Closure on AIX.
-
-commit a78da73956e4b0af4556f1c0a444bd0f065c3965
-Author: Jean-Luc Jumpertz <jean-luc@celedev.eu>
-Date: Mon Sep 4 15:55:34 2017 +0200
-
- Fix macOS build target in Xcode project.
-
- - Add missing files for desktop platforms in generate-darwin-source-and-headers.py, and in the Xcode project.
- - Add a static library target for macOS.
- - Fix "implicit conversion loses integer precision" warnings for iOS mad macOS targets.
-
-commit 9c12209d2eac40238eefb4255994277918e7eff1
-Author: Francis Ricci <francisjricci@gmail.com>
-Date: Thu Aug 3 10:46:28 2017 -0700
-
- Fix misaligned memory access in ffi_call_int
-
-commit b23091069adce469dc38fbcc9fd8ac9085d3c9d7
-Merge: c0cc9f1 9c6cb58
-Author: Tom Tromey <tom@tromey.com>
-Date: Wed Jul 12 12:43:06 2017 -0600
-
- Merge pull request #309 from rurban/oldgcc
-
- __attribute__ deprecated (msg) only since gcc 4.5
-
-commit 9c6cb58812aa92a4c56a94b2b51bd85b2aebc2a1
-Author: Reini Urban <rurban@cpan.org>
-Date: Sun Jun 18 18:26:05 2017 +0200
-
- __attribute__ deprecated (msg) only since gcc 4.5
-
- make it work with older compilers
-
-commit 50e408ce5d9eb6f14bf82bb3894d0e74e5f19c2c
-Author: Moritz Angermann <moritz.angermann@gmail.com>
-Date: Sun May 21 20:44:10 2017 +0800
-
- add i?86-*-ios -- the iOS simulator (32bit)
-
-commit a08cabe6746343564418383b879d40d3b998c399
-Author: Moritz Angermann <moritz.angermann@gmail.com>
-Date: Sun May 21 20:25:16 2017 +0800
-
- add x86_64-*-ios -- the iOS simulator
-
-commit 0ff9419f2e75652426469e256cb7d0748064ad58
-Author: Tony Reix <tony.reix@bull.net>
-Date: Wed May 17 14:57:53 2017 +0200
-
- This patch enables FFI Go Closure on AIX.
-
-commit 19ab448d84223d2992048bce4e926eac2c44f606
-Author: Moritz Angermann <moritz.angermann@gmail.com>
-Date: Tue May 16 08:32:06 2017 +0800
-
- Support -ios triple
-
- Autoconf hasn’t had an update since 2014, and it doesn’t look like it will soon[1]
- This updates config.{guess,sub}
-
- It adds support for e.g. `-ios`, which allows to have targets like `aarch64-apple-ios`.
-
- It basically does exactly what the config.guess script says:
- > It is advised that you download the most up to date version of the config scripts from
-
- The configure.ac script has been updated to relax `*-apple-darwin*` to `*-apple-*`.
- Similarly the `.gitignore` and `autogen.sh` needed to be updated to respect the
- newer `config.{sub,guess}`
-
- —
- [1]: http://lists.gnu.org/archive/html/autoconf/2016-07/msg00017.html
-
-commit c0cc9f1df9fd4c5e758470f05d0e48123f0638ae
-Merge: b841ae7 bd72848
-Author: Tom Tromey <tom@tromey.com>
-Date: Mon May 8 15:20:39 2017 -0600
-
- Merge pull request #302 from gpakosz/align-macros
-
- Prefix ALIGN macros with FFI_
-
-commit bd72848c7af9302df50a7a11652c77166d17caa8
-Author: Gregory Pakosz <gregory.pakosz@gmail.com>
-Date: Thu Apr 27 13:20:36 2017 +0200
-
- Prefix ALIGN macros with FFI_
-
-commit 7d504f7a8e33f6da27941f5dc5d889fe60b8b9c8
-Author: ksjogo <jogo@kronberger-spiele.de>
-Date: Thu Mar 30 13:32:58 2017 +0200
-
- update for xcode 8.3
-
-commit 57d8ff044cd6320d8ebacacf06455569b4aac27d
-Author: Ole André Vadla Ravnås <oleavr@gmail.com>
-Date: Wed Mar 15 01:43:11 2017 +0100
-
- Simplify iOS trampoline table allocation
-
- By using VM_FLAGS_OVERWRITE there is no need for speculatively
- allocating on a page we just deallocated. This approach eliminates the
- race-condition and gets rid of the retry logic.
-
-commit 7f558a9ba4e74edf54a3e95e983e8a59ddb0cc7c
-Author: ksjogo <jogo@kronberger-spiele.de>
-Date: Mon Jul 25 01:18:30 2016 +0200
-
- set ios deployment target to 7.0
-
-commit e76fa94b6ef9a699ee9edeb85d1731d3bb7abd46
-Author: ksjogo <jogo@kronberger-spiele.de>
-Date: Thu Jul 14 11:28:18 2016 +0200
-
- fix ltmain.sh in xcode builds
-
-commit 22b2fd6f18eed7b32ea959f7f3e56ea09b9ac9bf
-Author: ksjogo <jogo@kronberger-spiele.de>
-Date: Wed Jul 13 14:40:07 2016 +0200
-
- add valid architectures
-
-commit 0040694505411785ec98e660fe81faad9630f515
-Author: Johannes Goslar <johannes.goslar@kronberger-spiele.de>
-Date: Tue Jul 12 16:08:42 2016 +0200
-
- Update Xcodeproj
-
- Include all currently relevent files.
- Call autogen is build script.
- Fix compiler settings.
- Fix mach include.
-
-commit b841ae70a05a5e11de1fca1b4551189db0895cf2
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 19 07:42:09 2017 -0400
-
- remove stray quote
-
-commit a94c999ba0d51ed8ec88685233f5b1ae38e894ea
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 19 07:36:07 2017 -0400
-
- Handle fastcall declaration differently for some Microsoft compilers
-
-commit 69963d39ab7d7f201b4597ed7a24cf438e0a34bf
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 19 07:33:39 2017 -0400
-
- We don't support 32-bit builds with the Microsoft toolchain
-
-commit 073bc9d50c1ce753735944e4228d9a401e964306
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 19 07:25:24 2017 -0400
-
- Enable appveyor ci support
-
-commit a0b14eea2baf9f18c0d29bc5ce4495422381f917
-Merge: fa5a0fe 1e0d107
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Mar 17 09:20:40 2017 -0400
-
- Merge pull request #291 from ramon-garcia/visual-studio-build
-
- Build with Visual C++ (64 bits)
-
-commit fa5a0fe2c6da906cc7c114c8002e5c7092c4dbee
-Merge: 5b91bbd bfab429
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Mar 16 07:50:07 2017 -0400
-
- Merge pull request #238 from KubaKaszycki/master
-
- Update README with a new port
-
-commit 5b91bbd388213ec19044a392c291505e2c0674b9
-Merge: d754c51 982b89c
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Mar 16 00:40:58 2017 -0400
-
- Merge pull request #288 from yan12125/std-includedir
-
- Install public headers in the standard path
-
-commit d754c510f1dd03dc8c2cd7b50bb2a1668715c5cd
-Merge: ebe7f44 41185b5
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Mar 16 00:39:07 2017 -0400
-
- Merge pull request #299 from matijaskala/patch-1
-
- detect other x32 hosts
-
-commit ebe7f447abcfbf1a16dbfca26538fff03faf7c6b
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Mar 16 00:36:10 2017 -0400
-
- Remove osx testing. gcc was symlinked to clang. dejagnu c++ tests fail with clang.
-
-commit c9c2aa24611ec996f45a495f24d690688f3ffed6
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 15 09:58:39 2017 -0400
-
- Revert previous two changes. clang/MacOS problem can only be solved within dejagnu.
-
-commit 5a8fca94059fbf14ac7352ce487c9250cdd67c63
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 15 09:52:39 2017 -0400
-
- Fix typo
-
-commit 5b10a0198188d43fc07c271bc29ff1033e2ac9d3
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 15 09:34:01 2017 -0400
-
- Work around dejagnu/clang problems
-
-commit b6751258072fadadd487a6adf4962bf22b44746d
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 15 08:54:52 2017 -0400
-
- Require sudo for installing packages
-
-commit 41185b565fe17a8f107642f480849ef369ad0baa
-Author: Matija Skala <mskala@gmx.com>
-Date: Wed Mar 15 12:50:41 2017 +0100
-
- detect other x32 hosts
-
- primarily x86_64-pc-linux-muslx32
- while at it, add x86_64-x32-pc-linux-{gnu,musl} as well
-
-commit 6e2e041b6df6a3c3a5ca8a750dedbbd465e5ca97
-Merge: dabbd14 d42ce7b
-Author: Richard Henderson <rth@twiddle.net>
-Date: Tue Mar 14 19:37:45 2017 -0700
-
- Merge pull request #297 from frida/fix/error-path
-
- Fix error path so mutex is unlocked before returning
-
-commit 5e4fcdccb3a841f2daaa5834f726eaeb42950511
-Author: Ole André Vadla Ravnås <oleavr@gmail.com>
-Date: Wed Mar 15 01:43:11 2017 +0100
-
- Simplify iOS trampoline table allocation
-
- By using VM_FLAGS_OVERWRITE there is no need for speculatively
- allocating on a page we just deallocated. This approach eliminates the
- race-condition and gets rid of the retry logic.
-
-commit d42ce7b95c6d5cba7d976cc0c8c85f7645fa6b8f
-Author: Ole André Vadla Ravnås <oleavr@gmail.com>
-Date: Wed Mar 15 01:23:40 2017 +0100
-
- Fix error path so mutex is unlocked before returning
-
- In the unusual case where ffi_trampoline_table_alloc() fails.
-
-commit dabbd145665ffca6fa676eba551f12107cd81131
-Merge: 60e4250 6caabd1
-Author: Tom Tromey <tom@tromey.com>
-Date: Mon Feb 27 21:10:00 2017 -0700
-
- Merge pull request #295 from terrillmoore/patch-1
-
- Correct typos in libffi.texi
-
-commit 6caabd198ec24d090d85d7eca01150b44003c76b
-Author: Terry Moore <tmm@mcci.com>
-Date: Sun Feb 26 15:06:53 2017 -0500
-
- Correct typos in libffi.texi
-
- One "it's" should be "its", and one "is" should be "in".
-
-commit 1e0d107b4b237edd11ca3209a9cf59786f752fe5
-Author: Ramón García Fernández <ramon.garcia.f@gmail.com>
-Date: Sun Jan 8 20:12:59 2017 +0100
-
- Modify configure.host to detect compilation with Microsoft Visual C++ and use assembly with Intel syntax in that case
-
-commit 982b89c01aca99c7bc229914fc1521f96930919b
-Author: Yen Chi Hsuan <yan12125@gmail.com>
-Date: Sun Nov 13 19:17:19 2016 +0800
-
- Install public headers in the standard path
-
-commit 60e4250a77eb3fde500bfd68ec40519fe34b21bd
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Sep 4 09:34:18 2016 -0400
-
- make executable
-
-commit c3caf38895252b82febb76c6bb323c67a4e01929
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Sep 4 09:21:18 2016 -0400
-
- Update travis to test linux 32/64 and osx with a mix of gcc and clang
-
-commit c5b408ee78d097a495ea12467cf082f8008c8e17
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Sep 4 09:17:46 2016 -0400
-
- xfail the unwindtest for osx as per issue #279
-
-commit 256ce51c408766d23b2707cc79b97f673750b3b9
-Merge: 2ded2a4 52a11f6
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Sep 1 13:54:51 2016 -0700
-
- Merge pull request #273 from wbx-github/master
-
- m68k: support ISA-A Coldfire CPUs
-
-commit 2ded2a4f494165c93293afc14ab0be1243cf8c49
-Merge: 408c9c7 e247b56
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Sep 1 13:30:45 2016 -0700
-
- Merge pull request #272 from yousong/mips64-soft-float
-
- Mips64 soft float
-
-commit 408c9c7d5a4cb323c77499b1643858f4bfaf4ca7
-Merge: 06d7c51 b545ff8
-Author: Tom Tromey <tom@tromey.com>
-Date: Tue Aug 23 11:32:17 2016 -0600
-
- Merge pull request #274 from dr-hannibal/ykolerov-unused
-
- ARC: Remove unused variable
-
-commit b545ff81f58233284cd6fca97a470aa3218c23e6
-Author: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
-Date: Tue Aug 23 20:23:37 2016 +0300
-
- ARC: Remove unused variable
-
- Signed-off-by: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
-
-commit 52a11f6d9152a56aa1fb6d04eb40fd76f4cce5ff
-Author: Waldemar Brodkorb <wbx@uclibc-ng.org>
-Date: Sat Aug 20 00:52:19 2016 +0200
-
- m68k: support ISA-A Coldfire CPUs
-
- Fix compilation for m68k/coldfire CPUs like mcf5208.
-
- Signed-off-by: Thorsten Glaser <tg@mirbsd.de>
- Signed-off-by: Waldemar Brodkorb <wbx@uclibc-ng.org>
-
-commit e247b562ac85565dfac33e676e2915489af04183
-Author: Yousong Zhou <yszhou4tech@gmail.com>
-Date: Mon Aug 15 17:34:37 2016 +0800
-
- doc: fix typo
-
- Name of last argument to ffi_get_struct_offsets is `offsets`, not `sizes`
-
- Signed-off-by: Yousong Zhou <yszhou4tech@gmail.com>
-
-commit 7a0d2c83bf2b0422e2d0ed297f847fc1eeb88bb3
-Author: Yousong Zhou <yszhou4tech@gmail.com>
-Date: Mon Aug 15 15:00:13 2016 +0800
-
- mips: fix MIPS softfloat build issue
-
- The patch for o32.S is taken from OpenWrt packages repo 3a7a4bf "libffi:
- fix MIPS softfloat build issue with current binutils"
-
- Signed-off-by: Felix Fietkau <nbd@openwrt.org>
- Signed-off-by: Yousong Zhou <yszhou4tech@gmail.com>
-
-commit 06d7c5190e910356d4212d2a79056df8b70fd27e
-Merge: aa7ed78 301166b
-Author: Tom Tromey <tom@tromey.com>
-Date: Wed Aug 10 15:06:16 2016 -0600
-
- Merge pull request #269 from frida/fix/aarch64-variadic-closures-on-ios
-
- aarch64: Fix handling of variadic closures on iOS
-
-commit aa7ed78c0e0d3fc4daa6a86c35ecbb7c43b5d067
-Merge: 1daa787 4da814b
-Author: Tom Tromey <tom@tromey.com>
-Date: Wed Aug 10 15:03:37 2016 -0600
-
- Merge pull request #268 from frida/fix/aarch64-large-aggregates
-
- aarch64: Fix handling of aggregates larger than 16 bytes
-
-commit 4da814b18a1bf1d2013d988e37485e568d6117d1
-Author: Ole André Vadla Ravnås <oleavr@gmail.com>
-Date: Wed Aug 10 22:48:09 2016 +0200
-
- aarch64: Fix handling of aggregates larger than 16 bytes
-
- Instead of allocating stack space for a pointer we would allocate stack
- space for the actual aggregate size.
-
-commit 1daa78799942c83c905f8d7c5439952e9ffec3bc
-Merge: f03ba20 5e9ac7e
-Author: Tom Tromey <tom@tromey.com>
-Date: Wed Aug 10 14:31:09 2016 -0600
-
- Merge pull request #270 from frida/fix/aarch64-warnings
-
- Fix aarch64 warnings
-
-commit ed8488345eaae41c161ab741b0c44299ee99dc6c
-Author: s1341 <github@shmarya.net>
-Date: Wed Aug 10 14:57:22 2016 +0200
-
- arm: Fix cache flushing on QNX
-
- Use `msync()` directly as `__clear_cache()` is broken in the
- qnx650_gcc4.8.3 toolchain.
-
-commit 5e9ac7e252dbb0b7025027c1b6e1a4f3ec48943f
-Author: Ole André Vadla Ravnås <oleavr@gmail.com>
-Date: Wed Aug 10 15:22:19 2016 +0200
-
- aarch64: Fix warning about unused function on iOS
-
-commit 4d1f11f6a9effce05ba51578b142827834d1f699
-Author: Ole André Vadla Ravnås <oleavr@gmail.com>
-Date: Wed Aug 10 15:21:42 2016 +0200
-
- aarch64: Fix operand size warning reported by Clang
-
-commit 301166b11e913f85d09f67af94264268811f23a9
-Author: Ole André Vadla Ravnås <oleavr@gmail.com>
-Date: Wed Aug 10 15:59:56 2016 +0200
-
- aarch64: Fix handling of variadic closures on iOS
-
-commit f03ba2032850545dc6869bb495170a8c6cbf849d
-Merge: 40e4063 ef8be84
-Author: Tom Tromey <tom@tromey.com>
-Date: Tue Aug 2 10:23:25 2016 -0600
-
- Merge pull request #266 from dr-hannibal/arc-pthread
-
- Make testing easier outside of build directory and especially for ARC
-
-commit ef8be84de5f9e611add396efe908b772eb1cae1d
-Author: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
-Date: Fri Jul 29 21:01:38 2016 +0300
-
- Do not use fabsl() in float2.c test
-
- Some targets may support long double variables but in the same
- time may lack support of long double functions like fabsl().
-
- Signed-off-by: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
-
-commit f3201733d54bf26ac40c432f4305499dd3f20215
-Author: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
-Date: Fri Jul 29 19:18:41 2016 +0300
-
- Fix output expectations in cls_dbls_struct.c test
-
- This test with invalid output expectations may fail on some targets
- (e.g. ARC processors).
-
- Signed-off-by: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
-
-commit f74ea2dc7994b4867f7ab45169e1b2422072cc92
-Author: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
-Date: Thu Jul 28 20:57:09 2016 +0300
-
- Allow setting an arbitary value for blddirffi in testsuite
-
- It is useful when tests are executed not from build directory. So
- the path of the build directory may be passed through site.exp or
- runtest.
-
- Signed-off-by: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
-
-commit 31362d785ed1db52516dfe02ebe8b163c53d29d0
-Author: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
-Date: Thu Jul 28 18:48:23 2016 +0300
-
- ARC: Link tests with pthread library
-
- Signed-off-by: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
-
-commit 40e4063ab4449c644bc106298805fa8c6cfadbd4
-Merge: c0829e6 cf4b2a5
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Jul 7 23:11:38 2016 -0700
-
- Merge pull request #261 from tromey/fix-260
-
- Don't dereference "ecif" before NULL check
-
-commit cf4b2a50413ecb8931eb1a94437497694f189c47
-Author: Tom Tromey <tom@tromey.com>
-Date: Fri Jun 17 10:09:44 2016 +0100
-
- Don't dereference "ecif" before NULL check
-
- Fixes #260
-
-commit c0829e62841100c308cc37ddd6537ca69e856de7
-Merge: 96d9bf4 794a54d
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sun Jun 5 15:05:21 2016 -0700
-
- Merge pull request #259 from rth7680/master
-
- Mark win64.S with GNU-stack note
-
-commit 794a54d4a603639adf1a79d5b5bc15da437457e2
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sun Jun 5 14:57:00 2016 -0700
-
- Mark win64.S with GNU-stack note
-
-commit 96d9bf4b5517bc49c0129e8cfdee43098d3771a2
-Merge: 02089a1 52fbd12
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Jun 3 23:04:56 2016 -0700
-
- Merge pull request #253 from iains/darwin-build
-
- Some Darwin build fixes
-
-commit 52fbd12dca1bddf0b135a24e7136f10af79a06bd
-Author: Iain Sandoe <iain@codesourcery.com>
-Date: Thu May 26 09:00:00 2016 +0100
-
- [Darwin-ppc, build] Fixes for clang build.
-
- clang is experimental on powerpc-darwin, but the changes are appropriate to cctools as as well.
-
- Use the 'official' simplified cmpwi insn, rather than the implied one accepted by cctools.
- Do not re-use a set value.
-
-commit 92810b4bc101fccead2234b7385d4fa5e7a3e56a
-Author: Iain Sandoe <iain@codesourcery.com>
-Date: Thu May 26 08:56:51 2016 +0100
-
- [Darwin-x86, build] Fix up label prefixes, remove .purgem
-
- Darwin uses a label prefix of _.
- cctools assembler will not accept .purgem as a directive.
-
-commit 30b3440cfd378dc67111b1380f2654334d048659
-Author: Iain Sandoe <iain@codesourcery.com>
-Date: Thu May 26 08:55:04 2016 +0100
-
- [Darwin, configure] Allow configure to work for <arch>-*-darwin.
-
- The exec configury is appropriate for all current targets (including using older tools on them).
-
-commit 02089a1b5cf3aa1535172c62add454a2e9375066
-Merge: 5d0365c c884551
-Author: Tom Tromey <tom@tromey.com>
-Date: Mon May 23 09:58:51 2016 -0600
-
- Merge pull request #237 from tschwinge/libffi_feature_test
-
- Simplify/fix libffi_feature_test
-
-commit 5d0365c605c472f40d1195cf7ba04ae08e360cb7
-Merge: 584a140 74b3f52
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu May 19 09:35:38 2016 -0700
-
- Merge pull request #251 from berkerpeksag/delete-test-define
-
- Remove unused FFI_CLOSURE_TEST
-
-commit 74b3f5201432c37e40e24386fa193c838596cec8
-Author: Berker Peksag <berker.peksag@gmail.com>
-Date: Thu May 19 18:05:36 2016 +0300
-
- Remove unused FFI_CLOSURE_TEST
-
- It was here since the first commit c6dddbd (warning: huge diff) and
- it wasn't defined by the configure script. It was probably used
- manually during development.
-
-commit 584a140e7558dff6e4ed4009f39d11dd5e3db0ae
-Merge: c617754 b3496de
-Author: Tom Tromey <tom@tromey.com>
-Date: Thu May 19 06:36:38 2016 -0600
-
- Merge pull request #248 from berkerpeksag/patch-1
-
- Delete empty env in .travis.yml
-
-commit b3496dedbbad6c1f4e5bf4cc100e76b86f3c801e
-Author: Berker Peksag <berker.peksag@gmail.com>
-Date: Thu May 19 10:53:07 2016 +0300
-
- Delete empty env in .travis.yml
-
-commit c61775497e7bdfc892d865c2eb15415d2da7493b
-Merge: 9edaa69 33d9a31
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed May 18 11:10:33 2016 -0700
-
- Merge pull request #247 from rth7680/symver
-
- Add parent to symbol version LIBFFI_BASE_7.1
-
-commit 33d9a31d34cfba63e1294978114be1bddd2de3fd
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed May 18 11:01:55 2016 -0700
-
- Add parent to symbol version LIBFFI_BASE_7.1
-
-commit 9edaa695c54daaf58d62e84032d30d33b7484fa8
-Merge: 0969a1c 8a0a4e2
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed May 18 10:56:19 2016 -0700
-
- Merge pull request #230 from rth7680/symver
-
- Use ELF symbol versioning
-
-commit 0969a1c1b339f845202fa7507b70d193220ceb01
-Merge: 571b1ca 4a677a4
-Author: Tom Tromey <tom@tromey.com>
-Date: Wed May 18 10:09:28 2016 -0600
-
- Merge pull request #232 from berkerpeksag/signcompare
-
- Fix -Wsign-compare warnings in x86/ffi64.c
-
-commit 571b1ca6277dbafc1f340a59ea1c5ee4ddb11c94
-Merge: 069d2e4 1e82e1c
-Author: Tom Tromey <tom@tromey.com>
-Date: Wed May 18 10:08:59 2016 -0600
-
- Merge pull request #233 from berkerpeksag/mremap
-
- Define _GNU_SOURCE on Linux for mremap()
-
-commit 069d2e4e16c5570adec9249d642f2a2ae0ffaa1c
-Merge: a44a5b8 1b4f5ee
-Author: Tom Tromey <tom@tromey.com>
-Date: Wed May 18 10:07:31 2016 -0600
-
- Merge pull request #246 from berkerpeksag/update-github-links
-
- Update project URLs to use libffi/libffi
-
-commit 1b4f5ee6a4989d7eda7766c5864908c389586c6f
-Author: Berker Peksag <berker.peksag@gmail.com>
-Date: Wed May 18 11:12:58 2016 +0300
-
- Update project URLs to use libffi/libffi
-
-commit 1e82e1cda43dacd8b6ab2d9ac4db33523d86f5dc
-Author: Berker Peksag <berker.peksag@gmail.com>
-Date: Mon Mar 7 18:38:10 2016 +0200
-
- Define _GNU_SOURCE on Linux for mremap()
-
- This was committed to CPython's libffi copy in
- https://bugs.python.org/issue10309
-
- mremap() documentation says _GNU_SOURCE needs to
- be defined in order to use mremap(): see the
- synopsis section at http://linux.die.net/man/2/mremap
-
- Original commit: https://hg.python.org/cpython/rev/9986fff720a2
-
- Original patch was written by Hallvard B Furuseth.
-
-commit 4a677a425c18eda4bc5357b2485da57f133f908d
-Author: Berker Peksag <berker.peksag@gmail.com>
-Date: Sat Mar 5 09:58:38 2016 +0200
-
- Fix -Wsign-compare warnings in x86/ffi64.c
-
- This was originally reported on the Python tracker:
-
- httpa://bugs.python.org/issue23958
-
- The original patch was written by Steve R. Hastings.
-
- I've updated it to current master of libffi.
-
-commit a44a5b863aaae98041e11aa3256907bf912ee4d6
-Merge: 9443eae 2627fc9
-Author: Tom Tromey <tom@tromey.com>
-Date: Tue May 17 17:07:27 2016 -0600
-
- Merge pull request #234 from berkerpeksag/disable-docs
-
- Add a note about the --disable-docs switch
-
-commit 9443eaeda867cfdeae92b10bee3cc0506892a4c5
-Merge: 14be9a1 e169ba2
-Author: Tom Tromey <tom@tromey.com>
-Date: Tue May 17 17:04:50 2016 -0600
-
- Merge pull request #242 from somasis/master
-
- Fix usage on musl libc
-
-commit 8a0a4e25ef99f4ec98761f2fc075c2e8409f171b
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed May 4 07:33:41 2016 -1000
-
- Update symbol versioning for ffi_get_struct_offsets
-
- Given that the original symbol versioning patch has shipped
- with gcc-6, it would be kind to keep that as a valid base ABI
- and make subsequent changes to version 7.1.
-
-commit c02c3414440e816aa13a2fe8446484173d3edb0e
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Mar 3 13:51:44 2016 -0800
-
- Use ELF symbol versioning
-
- At the same time, we must bump the (major) ABI version. This needed to be
- done anyway due to ABI breakage in the AArch64 port (see 12cf89ee and the
- corresponding GCC PR70024).
-
-commit 14be9a1d0713deb97edb91fe9800afe971a001d5
-Merge: 1cea273 b50eabf
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed May 4 06:45:05 2016 -1000
-
- Merge pull request #245 from rth7680/tromey-ffi-prep-cif-core-is-private
-
- A rebase of #219
-
-commit b50eabf48927ccaf0184c6224992bbb0a125e969
-Author: Tom Tromey <tom@tromey.com>
-Date: Mon Feb 22 16:00:51 2016 -0700
-
- minor comment cleanup
-
- This patch minor cleans up ffi.h.in comments in a minor way. It fixes
- some typos and capitalizations, adds some periods, and reformats some
- comments to a more GNU-ish style. It also fixes up some stale
- documentation.
-
-commit 6c07077a61fd0dc5ac11759ea1b4345acf486f3c
-Author: Tom Tromey <tom@tromey.com>
-Date: Sun Feb 21 20:08:21 2016 -0700
-
- Change ffi.h.in so that braces match
-
- This is a tiny refactoring to make it so brace-matching works in
- Emacs.
-
-commit 2fbc0369b89a7e6b089e6384b98dba904ec1cf8b
-Author: Tom Tromey <tom@tromey.com>
-Date: Thu Nov 19 16:38:35 2015 -0700
-
- move ffi_prep_cif_core to ffi_common.h
-
-commit 1cea273758ad862bdc2862af864e4ef5b42f31ae
-Merge: 48bfae1 6aafb56
-Author: Tom Tromey <tom@tromey.com>
-Date: Tue May 3 08:23:51 2016 -0600
-
- Merge pull request #231 from berkerpeksag/simplfy-oserror
-
- Simplify error handling in mkdir_p()
-
-commit 48bfae1f37551b7fc894e6a0ea3b98968d2b5c9f
-Merge: 6d87110 d76975d
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon May 2 20:58:57 2016 -1000
-
- Merge pull request #236 from andreas-schwab/master
-
- Define FFI_SIZEOF_JAVA_RAW for aarch64 ILP32
-
-commit 6d8711057bc3a3befa37eed6765231ea5d244078
-Merge: 9de24a3 e5843a3
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sun May 1 11:02:40 2016 -1000
-
- Merge pull request #241 from rth7680/fix-win64
-
- Fix win64 abi calling from unix64
-
-commit e169ba2b83c780058fe626856cfdb5903a85cb97
-Author: Kylie McClain <somasis@exherbo.org>
-Date: Fri Apr 29 21:04:07 2016 -0400
-
- Fix usage on musl libc
-
- A gcc compiled on musl does not define __gnu_linux__, it defines __linux__.
- Only on glibc does __gnu_linux__ get defined, but both define __linux__, so
- we should check for that instead.
-
- With this patch, libffi works perfectly, and passes its testsuite entirely
- on musl libc systems.
-
-commit e5843a3a09976f9d8fa77671e9d6c188c890199d
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Apr 15 16:10:08 2016 -0700
-
- x86: Fix calling convention for ffi_closure_win64_inner
-
- Also enable testing for the cross-abi calls.
-
-commit d06751979bf0e4c9caabf0bca531d74de8cb9152
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon Mar 7 12:14:22 2016 -0500
-
- x86: Copy fix for clang .org from unix64.S
-
- Clang doesn't understand .org with symbolic operands.
-
-commit bfab429ee479723cc65831a7e4327e2866036420
-Author: Jakub Kaszycki <kaszycki@mail.com>
-Date: Fri Apr 1 21:42:41 2016 +0200
-
- Update README with a new port
-
- This is in fact not a NEW port. Apple Mac devices are generally x86-64 now, x86 rarely. If GCC exists for this CPU, it means that libffi has been built too.
-
-commit c88455178151bea14b8561ab6830724c31af255e
-Author: Thomas Schwinge <thomas@codesourcery.com>
-Date: Thu Feb 25 20:10:18 2016 +0100
-
- Simplify/fix libffi_feature_test
-
- As detailed in
- <http://news.gmane.org/find-root.php?message_id=%3C87wppswqqt.fsf%40kepler.schwinge.homeip.net%3E>,
- the original code (originally added in commit
- f1301a54bb80e6ae23f7687c68f36875dae69134 as part of pull request #145) does not
- work (at least not for me, in the GCC environment).
-
-commit d76975dbd2854beca7acbca946c4cbccf9bf7cee
-Author: Andreas Schwab <schwab@suse.de>
-Date: Wed Mar 16 12:23:07 2016 +0100
-
- Define FFI_SIZEOF_JAVA_RAW for aarch64 ILP32
-
- Like x32, aarch64 ILP32 needs to define FFI_SIZEOF_JAVA_RAW. This fixes
- the java interpreter.
-
-commit 9de24a3ff31c7446de29c1adcd9276fd7ba93897
-Merge: ee71806 38a4d72
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Mar 14 13:54:53 2016 -0400
-
- Merge pull request #212 from tromey/struct-layout
-
- add ffi_get_struct_offsets
-
-commit 2627fc98e86e906fd7c9bc16bf345b91ee26d2ba
-Author: Berker Peksag <berker.peksag@gmail.com>
-Date: Mon Mar 7 18:43:03 2016 +0200
-
- Add a note about the --disable-docs switch
-
- Closes #204
-
-commit 6aafb5654d6741927276efff1af72a5b3614da39
-Author: Berker Peksag <berker.peksag@gmail.com>
-Date: Sat Mar 5 08:30:31 2016 +0200
-
- Simplify error handling in mkdir_p()
-
-commit ee718066f763b65d1888f9cc7155d3a1880f80e9
-Merge: f2f234a e59fb55
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Feb 22 20:15:40 2016 -0500
-
- Merge pull request #227 from tromey/fix-documentation-build
-
- Fix documentation build
-
-commit 38a4d72c95936d27cba1ac6e84e3094ffdfaa77c
-Author: Tom Tromey <tom@tromey.com>
-Date: Tue Nov 17 21:18:20 2015 -0700
-
- add ffi_get_struct_offsets
-
-commit e59fb55e09fb8aa846c820a802a03fed408d05a6
-Author: Tom Tromey <tom@tromey.com>
-Date: Mon Feb 22 15:51:27 2016 -0700
-
- remove and ignore texinfo.tex
-
- This file is provided by Automake
-
-commit 6dd5fd5a643c50aff3303ba2add3b6cc7588df78
-Author: Tom Tromey <tom@tromey.com>
-Date: Mon Feb 22 15:34:39 2016 -0700
-
- fix documentation building
-
- An earlier patch added --disable-docs, but went too far, making it
- impossible to build the docs.
-
- It turns out that Automake seemingly has a bug preventing the
- conditional build of an info file. So, this patch works around the
- bug by putting the info_TEXINFOS rule into a new doc/Makefile.am.
-
- Tested by building with and without --disable-docs and looking for the
- existence of doc/libffi.info.
-
-commit f2f234aef203a5e836b83cb772f9473f7ea0d5ce
-Merge: 49b95ed fa7a257
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:50:29 2016 -0500
-
- Merge pull request #190 from havardgraff/master
-
- Add configure-option to disable building docs
-
-commit 49b95edafd712ce27e08b1bb4be2987f14c54ca3
-Merge: 415723b 43fc5bc
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:49:40 2016 -0500
-
- Merge pull request #194 from amodra/master
-
- Correct powerpc sysv stack argument accounting
-
-commit 415723b40ba76f4a9df9b709db1cde0c65162072
-Merge: 7c27fcb 1f6b5a9
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:49:19 2016 -0500
-
- Merge pull request #104 from joshtriplett/efi64
-
- Support the Windows/EFI calling convention on all x86-64 targets
-
-commit 7c27fcbe09534d261b4098467a3ce258daec2807
-Merge: 69143d0 e061243
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:45:00 2016 -0500
-
- Merge pull request #199 from Pan7/master
-
- Fix configuring msvc compiler
-
-commit 69143d06c6276d09790a4e34f2eb6d37528c08c6
-Merge: 755f1e6 505346e
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:44:28 2016 -0500
-
- Merge pull request #197 from foxsen/mips_go_closure
-
- Mips go closure support
-
-commit 755f1e642d97892cb54358d65e06b60d1d6b72a4
-Merge: 183ee6a 4cdedc2
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:43:48 2016 -0500
-
- Merge pull request #193 from rth7680/fix-70
-
- Test case from issue #70
-
-commit 183ee6a6729db8f3ee0b1532d7bd54a6ef305443
-Merge: 0bb71b5 877ea9b
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:43:28 2016 -0500
-
- Merge pull request #206 from edolnx/master
-
- Add configure flag to disable multi-os-directory support
-
-commit 0bb71b52f5a60643ad55f801f1c652855b0e5cc5
-Merge: 296a283 8bec5ca
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:41:10 2016 -0500
-
- Merge pull request #211 from tromey/move-prep-types-out-of-ffi.h
-
- ffi_prep_types is internal-only
-
-commit 296a283a46057a6a643f1f64534324af34b7ed19
-Merge: e7c713a 4805bf9
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:40:21 2016 -0500
-
- Merge pull request #213 from tromey/remove-FFI_TYPE
-
- remove FFI_TYPE typedef
-
-commit e7c713a0b64c425b51f3d9437a8db7ca497e6c31
-Merge: 79666ab f45e9e3
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:40:03 2016 -0500
-
- Merge pull request #214 from tromey/document-enum-support
-
- document (lack of) enum handling in libffi
-
-commit 79666abca87ac67d2d05b477a3ba71ec18b8af0c
-Merge: 20c7c31 89b7605
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:38:40 2016 -0500
-
- Merge pull request #205 from filbranden/tool_opts
-
- Fix dejagnu test support for --tool_opts
-
-commit 20c7c31ca04350670012b28756d4ebc9e7b67a68
-Merge: 6ba2a49 9c14cbf
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 20 06:38:01 2016 -0500
-
- Merge pull request #225 from ehsan/safeseh
-
- Don't clobber safeseh for msvcc.sh -clang-cl in 32-bit mode
-
-commit 89b760503ed017233c98531908dfe8d8affab65e
-Author: Filipe Brandenburger <filbranden@google.com>
-Date: Mon Oct 19 15:33:23 2015 -0700
-
- Fix dejagnu test support for --tool_opts
-
- Right now it concatenates it with the existing options and then appends
- it to that list, fix it to simply append it as is, same as it is done
- with the other variables.
-
- Tested by running the following command which includes gcc options:
- $ make check RUNTESTFLAGS="--tool_opts '-Werror'"
-
- Without this patch, all the tests fail. With it, the test succeed.
- Inspecting the logs shows that -Werror was indeed used when compiling
- the test sources.
-
-commit 9c14cbfc7ff49c2ceb9b65c548ddaced607f0785
-Author: Ehsan Akhgari <ehsan@mozilla.com>
-Date: Thu Jan 28 16:57:18 2016 -0500
-
- Don't clobber safeseh for msvcc.sh -clang-cl in 32-bit mode
-
- The commit fb25cd0 went a bit too far and removed safeseh
- when -clang-cl was passed, but that's only needed in x86-64
- which is already handled by the -m64 flag.
-
- I discovered this when building Firefox x86 with clang-cl.
-
-commit 6ba2a49e226b859ddde9a37c34973cf85380c525
-Merge: 8005600 6a3a6ac
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Jan 2 20:03:41 2016 -0500
-
- Merge pull request #222 from freakboy3742/t181
-
- Fixed #181 -- Corrected problems with ARMv7 build under iOS.
-
-commit 8005600a920f43d89ace7ef3598057392da726e1
-Merge: 70594f7 5e2b18a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Jan 2 16:44:29 2016 -0500
-
- Merge pull request #224 from plicease/travis
-
- update apt-get in travis
-
-commit 5e2b18a65d3f366b2fb02ee27321095c4b5f17ac
-Author: Graham Ollis <plicease@cpan.org>
-Date: Sat Jan 2 07:56:05 2016 -0500
-
- update apt-get in travis
-
-commit 6a3a6acd9fdbdac6f9f9294732b9627895b77715
-Merge: bc4fc07 70594f7
-Author: Russell Keith-Magee <russell@keith-magee.com>
-Date: Mon Dec 21 00:37:37 2015 +0800
-
- Merge branch 'master' into t181
-
-commit bc4fc07aa58df6d7fa90b57d305d58eef96a0416
-Author: Russell Keith-Magee <russell@keith-magee.com>
-Date: Mon Dec 21 00:37:06 2015 +0800
-
- Fixed #181 -- Corrected problems with ARMv7 build under iOS.
-
- Based on a patch from @fealebenpae, with input from @SolaWing and @rth7680,
- and testing from @superdump.
-
-commit 70594f7f8d7410be47ba9a80a566175d937ab626
-Merge: 88deacd 6affad7
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Dec 18 10:24:38 2015 -0500
-
- Merge pull request #221 from tromey/document-closure-ffi_arg
-
- Document closure ffi arg
-
-commit 6affad79111c45982fd29637a46bc756abb128a3
-Author: Tom Tromey <tom@tromey.com>
-Date: Thu Dec 17 16:58:10 2015 -0700
-
- correctly document closure return promotion
-
-commit 8a7cdeb0412f9ef8bbe0a7833d662dbec40b472f
-Author: Tom Tromey <tom@tromey.com>
-Date: Thu Dec 17 16:51:32 2015 -0700
-
- fix formatting of ffi_prep_closure_loc arguments
-
-commit f45e9e35700d7c547ba33b02c4186e746dea204a
-Author: Tom Tromey <tom@tromey.com>
-Date: Thu Nov 19 15:21:14 2015 -0700
-
- document (lack of) enum handling in libffi
-
-commit 4805bf9ccdc176687526e9e7fca0db763cef42fb
-Author: Tom Tromey <tom@tromey.com>
-Date: Thu Nov 19 14:17:42 2015 -0700
-
- remove FFI_TYPE typedef
-
-commit 8bec5ca26a9977e6c05d6bfa1bbbc7f6f99af4e7
-Author: Tom Tromey <tom@tromey.com>
-Date: Wed Nov 11 21:34:43 2015 -0700
-
- ffi_prep_types is internal-only
-
-commit 88deacdd4220b66805b6ad10abd61fa3640afb67
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Nov 15 08:39:17 2015 -0500
-
- speling fix
-
-commit 5973dca595f8595a40709f645e74b06990975db3
-Merge: 2a988c4 473bcbc
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Nov 15 08:36:48 2015 -0500
-
- Merge pull request #209 from tromey/documentation-updates
-
- documentation fixes
-
-commit 2a988c4455d3926c59997b68f7510be63e10c841
-Merge: e9de7e3 ff33ddd
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Nov 15 08:33:46 2015 -0500
-
- Merge pull request #207 from tromey/deprecate-ffi-prep-closure
-
- mark ffi_prep_closure as deprecated
-
-commit 473bcbcad32e9e320a7a5c111cefd0d8ad570245
-Author: Tom Tromey <tom@tromey.com>
-Date: Sat Nov 7 12:01:06 2015 -0700
-
- documentation fixes
-
- Fixes #78. Documentation for #33 and #35, but no fix.
-
-commit ff33ddd1abe72b6d02d2769c0379b06eb7dbb931
-Author: Tom Tromey <tom@tromey.com>
-Date: Sat Nov 7 11:45:04 2015 -0700
-
- mark ffi_prep_closure as deprecated
-
-commit 877ea9bf9ac2c98cb858c12f5a6aeeec13cf978f
-Author: Carl Perry <caperry@edolnx.net>
-Date: Thu Oct 29 22:50:42 2015 -0500
-
- Add configure flag to disable multi-os-directory support
-
- In some environments, installing the library to GCC's
- multi-os-directory is not perferable. This patch adds a switch
- to configure "--disable-multi-os-directory" which will disable
- that check, typically falling back to ${libdir} unless
- cross-compiling.
-
- Original patch was written by Stewart Brodie, and was found at
- https://sourceware.org/ml/libffi-discuss/2013/msg00144.html
-
- I've just updated it to work with the current version.
-
-commit 4cdedc279f96aefda24277184594c0ddd56d3402
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sat Jul 25 14:29:15 2015 -0700
-
- Tidy call.exp test collection
-
- Commit c952a92e20aa6013d8202d0b3fa1d87838c83054 moved all of
- the complex tests to libffi.complex, but failed to remove the
- anti-globbing from libffi.call.
-
-commit 609db2fbe41a56c1a8cd5653d248f08b88ea803f
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sat Jul 25 12:42:04 2015 -0700
-
- Test case from Issue #70
-
-commit e9de7e35f2339598b16cbb375f9992643ed81209
-Merge: d19b6cc 0ebde2d
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Oct 11 10:54:50 2015 -0400
-
- Merge pull request #202 from tromey/note-prep-cif-var-usage
-
- document that there must be ntotalargs types
-
-commit d19b6cc78e956e7ffd48b39fd7c441c22e633ce2
-Merge: 17ffc36 36f3fb9
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Oct 11 10:54:22 2015 -0400
-
- Merge pull request #201 from tromey/fix-texinfo-buglet
-
- Add missing "@" to @var{}
-
-commit 0ebde2d24a3deb7b0cdf5cb1e625b55af2834fde
-Author: Tom Tromey <tom@tromey.com>
-Date: Tue Oct 6 11:42:43 2015 -0600
-
- document that there must be ntotalargs types
-
-commit 36f3fb91412a6f10bd2c6dde01f4d7afa1f2f2c0
-Author: Tom Tromey <tom@tromey.com>
-Date: Mon Oct 5 10:20:05 2015 -0600
-
- Add missing "@" to @var{}
-
-commit e061243958d63080956887e121d275533570f7cc
-Author: Pan7 <panter@gmx.net>
-Date: Mon Sep 14 08:25:09 2015 +0200
-
- Fix configuring msvc compiler
-
-commit 505346e18fe20eee7eb69a23a48f6951858c5267
-Author: Zhang Fuxin <zhangfx@lemote.com>
-Date: Wed Aug 26 09:57:10 2015 +0800
-
- fix type error in unwind code
-
-commit 5953c66bd7510b048b332b4e7450f3fb8d687f8b
-Author: foxsen <2503799872@qq.com>
-Date: Thu Aug 20 20:28:13 2015 +0800
-
- add unwind infor for *go_closure;
- reorder the labels to make thing more clear
-
-commit f0ecd5d40397d4616ba0bf3e2521da2663b5bd97
-Author: Zhang Fuxin <zhangfx@lemote.com>
-Date: Tue Aug 11 12:47:36 2015 +0800
-
- fix O32 stack unwind code
- add missing 1: label
-
-commit 6f0201c803a9a1f0f9b6fd226a42fb8daa223928
-Author: foxsen <2503799872@qq.com>
-Date: Tue Aug 4 18:25:34 2015 +0800
-
- various fixes for go closure support. Now all n64 tests passed.
-
-commit 697dd4e8a03625a9b1448aa696978d8dcc57d438
-Author: foxsen <2503799872@qq.com>
-Date: Tue Aug 4 12:53:33 2015 +0800
-
- add support for go closure support on mips
-
-commit 43fc5bca48715a522b34c1124589575063362a90
-Author: Alan Modra <amodra@gmail.com>
-Date: Mon Aug 3 23:34:05 2015 +0930
-
- Correct powerpc sysv stack argument accounting
-
- ppc32 starts using the stack for integer arg passing when we run out
- of integer arg passing registers. Similarly, we start using the stack
- for floating point args when we run out of floating point registers.
- The decision on where an integer arg goes does not depend on number of
- floating point args, nor does the decision on where a floating point
- arg goes depend on number of integer args. Alignment of stack args
- also simply depends on number of stack args.
-
- This patch untangles the horrible mess we had, with intarg_count being
- wrongly used to count both integer args and stack words.
-
- * src/powerpc/ffi_sysv.c (ffi_prep_cif_sysv_core): Count fprs,
- gprs, and stack words separately.
- (ffi_prep_args_SYSV): Similarly.
-
-commit 1f6b5a91f417ac77d2fe9b0b3eb66293db132e2e
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Jul 26 16:27:34 2015 -0700
-
- Support the WIN64/EFI64 calling convention on all X86_64 platforms
-
- Add a new calling convention FFI_EFI64, alias FFI_WIN64, on all X86_64
- platforms. This allows libffi compiled on a 64-bit x86 platform to call
- EFI functions.
-
- Compile in ffiw64.c and win64.S on all X86_64 platforms. When compiled
- for a platform other than X86_WIN64, ffiw64.c suffixes its functions
- with _efi64, to avoid conflict with the platform's actual
- implementations of those functions.
-
-commit 6de51f3e04e496901ea1bd8f9b44f75c9f01b599
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Jul 26 16:23:55 2015 -0700
-
- src/x86/ffiw64.c: Don't assign a "char *" to an "unsigned char *"
-
- Declare a local variable to match the type of the struct field assigned
- to it, rather than adding unsigned to the type. Fixes a -Wpointer-sign
- warning.
-
-commit eaa59755fcbb692a8cb763c7f9f24a350aadbd30
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Jul 26 17:17:16 2015 -0700
-
- src/x86/win64.S: Handle name mangling and PIC
-
- Move the macros from unix64.S into a shared header asmnames.h and use
- them in win64.S too.
-
-commit c8e82d9fbffd3eeaef0266a1aac64d7bd13ee9c3
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Jul 26 16:18:57 2015 -0700
-
- src/x86/win64.S: Support compiling on non-WIN64 platforms
-
- Non-WIN64 versions of the GNU assembler don't support the .seh_*
- directives for structured exception handling, so wrap them in a macro
- that compiles to nothing.
-
- Handle the registers used for the non-Windows x86-64 calling convention
- when on a non-Windows platform. Distinguish between cases that should
- refer to the native argument registers (defined as arg0, arg1, arg2, and
- arg3) and cases that should always refer to the Windows argument
- registers.
-
-commit fa7a257113e2cfc963a0be9dca5d7b4c73999dcc
-Author: Havard Graff <havard.graff@gmail.com>
-Date: Tue May 12 10:45:13 2015 +0200
-
- Add configure-option to disable building docs
-
-commit e3d2812ce43940aacae5bab2d0e965278cb1e7ea
-Author: Russell Keith-Magee <russell@keith-magee.com>
-Date: Sat Apr 25 19:03:03 2015 +0800
-
- Modified arm/sysv.S to remove directives not allowed by clang.
-
-commit 17ffc3655a531c116e9eb9cc933e50bb1e5c47f8
-Merge: 173757c a5b3eaa
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 29 21:38:26 2015 -0400
-
- Merge pull request #185 from freakboy3742/t184
-
- Fixed #184 -- Corrected source file references in Darwin source generator tool.
-
-commit 173757ce973a2f12ad36ac6cda593581b225f9e3
-Merge: f5ec627 dd9e4c8
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 29 21:38:12 2015 -0400
-
- Merge pull request #186 from freakboy3742/gitignore
-
- Added generated source file to .gitignore.
-
-commit dd9e4c8d46b65104a24a9858accd0936ca44b98f
-Author: Russell Keith-Magee <russell@keith-magee.com>
-Date: Fri Mar 13 08:03:13 2015 +0800
-
- Added generated source file to .gitignore.
-
-commit a5b3eaa279a2e54721d44eeefdfd1962cf63caaf
-Author: Russell Keith-Magee <russell@keith-magee.com>
-Date: Fri Mar 13 07:59:11 2015 +0800
-
- Fixed #184 -- Corrected file references in Darwin source generator tool.
-
-commit f5ec6279a4698a8752093247a500cf76096ff157
-Merge: 06747d3 95df379
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 4 13:58:04 2015 -0500
-
- Merge pull request #178 from rth7680/aa64-ilp32
-
- aarch64: Handle ILP32 ABI
-
-commit 95df3791935d934d92b0c852af1e655285157b70
-Author: Andrew Pinski <apinski@cavium.com>
-Date: Wed Feb 11 08:31:48 2015 -0800
-
- aarch64: Handle ILP32 ABI
-
-commit 06747d318761884e70dfa433a9548219fd779d7d
-Merge: db1b34b 6c53577
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Jan 29 07:22:23 2015 -0500
-
- Merge pull request #176 from 0-wiz-0/master
-
- Handle NetBSD/powerpc the same as FreeBSD and OpenBSD.
-
-commit 6c5357757f188577fffcd2890ef7a0f53e77de20
-Author: Thomas Klausner <wiz@NetBSD.org>
-Date: Thu Jan 29 12:32:28 2015 +0100
-
- Handle NetBSD/powerpc the same as FreeBSD and OpenBSD.
-
- Signed-off-by: Thomas Klausner <wiz@NetBSD.org>
-
-commit db1b34b7e1f5e473d17557e454a29933dfecd1af
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 28 18:08:06 2015 -0500
-
- Remove incomplete sentence
-
-commit 56036a6b58acb9e854719e315a0738f16e354c35
-Merge: 035715b 2104b2a
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 28 18:03:57 2015 -0500
-
- Merge pull request #175 from rth7680/sparc
-
- sparc: Re-introduce hand-written unwind info
-
-commit 035715b3330421806df36ec4ac7ccecc86458540
-Merge: 31a6185 b0e9796
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 28 18:03:06 2015 -0500
-
- Merge pull request #174 from rth7680/fbsd
-
- configure: Run HAVE_AS_X86_PCREL for all X86 targets
-
-commit 2104b2a4fc923b8d82647c3fbbd8a8ca20bb24c8
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon Jan 26 12:43:57 2015 -0800
-
- sparc: Re-introduce hand-written unwind info
-
- Fixes the build with the Solaris assembler.
-
-commit b0e9796344562ea8e1ef28e9b04db6be26ca29fb
-Author: Richard Henderson <rth@twiddle.net>
-Date: Tue Jan 27 22:10:12 2015 -0800
-
- configure: Run HAVE_AS_X86_PCREL for all X86 targets
-
-commit 31a618530737cc8f1666845f8e65a3c097f6d408
-Merge: d6675c1 5363663
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 21 05:55:47 2015 -0500
-
- Merge pull request #170 from fealebenpae/aarch64-trampoline-table
-
- Support closures on ARM64 iOS
-
-commit d6675c16cc2b5a0e32c4538e5a4f555c91e6bb56
-Merge: a25a46a 3ac1610
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 21 05:53:21 2015 -0500
-
- Merge pull request #172 from rth7680/fixes
-
- x86: Fix cygwin32 build
-
-commit 3ac1610aa33c887ea9b14935208943925714a33e
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon Jan 19 20:48:40 2015 +0100
-
- x86: Fix cygwin32 build
-
- The section syntax is just that little bit different.
-
-commit a25a46a7fe4f7ae27fbd6e08a2540678899914e9
-Merge: 5cd411a 1ad0b17
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Jan 16 17:32:07 2015 -0500
-
- Merge pull request #171 from rth7680/fixes
-
- Fixes from mainline gcc
-
-commit 1ad0b17177526be86736e245fbcc21eadaf7cb36
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Jan 16 13:30:05 2015 -0800
-
- sparc: Also mark the return address in unwind info
-
-commit d68c8aed19d459a9fef0847f316dd9473ef263ad
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Jan 16 11:40:33 2015 -0800
-
- sparc: Solaris fixes, part 2
-
- /bin/as seems to only understand single-digit labels
- /bin/as knows nothing about .rept/.endr
-
-commit b740ab7cc955fc2888325e6387207f34400a6c45
-Author: Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-Date: Fri Jan 16 11:32:23 2015 -0800
-
- sparc: Solaris fixes
-
- * /bin/as requires .type fn,#function instead of @function.
- * /bin/as doesn't support .macro/.endm. I'm using preprocessor macros
- instead to implement E in src/sparc/v[89].S.
-
-commit f1560b7bbeb57042a32dfde487c3d21bd9ef6a51
-Author: Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-Date: Fri Jan 16 11:31:37 2015 -0800
-
- x86: Solaris fixes
-
- * Solaris/x86 /bin/as doesn't support .org, so I've just disabled the
- uses in src/x86/{sysv, unix64}.S, as on Darwin.
- * Solaris/x86 needs to use EH_FRAME_FLAGS so manually and compiler
- generated .eh_frame sections match, otherwise libffi.so fails to link:
- * Solaris/x86 /bin/as has different COMDAT syntax; I've disabled it for
- the moment.
-
-commit 536366349ced9d57c873d64e219ba30992a83c06
-Author: Yavor Georgiev <fealebenpae@gmail.com>
-Date: Fri Jan 16 15:19:38 2015 +0200
-
- aarch64: implement the trampoline table workaround for ffi closures on Apple systems
-
- This is a direct copy/paste port of the ARM code, with changes because of Aarch64 pc-relative addressing restrictions.
-
-commit 05e65b4e2064f24669e8cc1c1cece1cbb0577548
-Author: Yavor Georgiev <fealebenpae@gmail.com>
-Date: Fri Jan 16 15:18:04 2015 +0200
-
- aarch64: rewrite range syntax into list to appease Clang
-
- Clang's assembler in Xcode 6 appears to choke when the operand of st4 is a range, but is happy with a list.
-
-commit 5cd411ad5d62b1dadfd02f75f99121801c8be4c9
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jan 13 15:44:03 2015 -0500
-
- New test case for old aarch64 bug
-
-commit e46842b4149e19106a9eb6066ef022d8b6a7ad5d
-Author: Richard Henderson <rth@twiddle.net>
-Date: Tue Jan 13 07:23:48 2015 -0800
-
- Remove extra brackets in configure.host
-
- This table is no longer in configure.ac, needing
- protection from m4.
-
-commit f27c4e46734fa1342236b16161e6006a9d2557e9
-Author: Richard Henderson <rth@twiddle.net>
-Date: Tue Jan 13 07:22:07 2015 -0800
-
- x86: Fix thinko in ffi_raw_call
-
- Missed structure initialization for raw path.
- Apparently there are no tests for this outside gcc.
-
-commit c82cc159426d8d4402375fa1ae3f045b9cf82e16
-Merge: 1c61e73 e1a5ddb
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Jan 10 09:25:26 2015 -0500
-
- Merge pull request #166 from chevah/master
-
- Fix expr error in Solaris 10 when using gcc.
-
-commit 1c61e73ad8e920d6bff337fac02de71f3a66bc38
-Merge: dd0b59a 3fa5d70
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Jan 10 09:23:30 2015 -0500
-
- Merge pull request #165 from rth7680/pcc
-
- Support PCC as producer and consumer
-
-commit dd0b59a5cf63e0f9602c76fc89a4cb62593ff6f1
-Merge: 9131039 b7f6d7a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Jan 10 09:22:55 2015 -0500
-
- Merge pull request #164 from rth7680/darwin
-
- Fix build on darwin
-
-commit 9131039c93b6ecd1c3946905a3b6dafb5dc4ee40
-Merge: 4ca2262 7282d32
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Jan 10 09:22:42 2015 -0500
-
- Merge pull request #160 from nobu/msvc-no-complex
-
- x86: MSVC does not support Complex type
-
-commit 4ca2262ad61189276b2d95aab652a23c8db2a5b9
-Merge: 58bf7d6 5f8881a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Jan 10 09:21:37 2015 -0500
-
- Merge pull request #159 from nobu/fix-void-arith
-
- x86: Fix void pointer arithmetic
-
-commit e1a5ddb3067f83563cb8a6b8ac4d0f58d4699262
-Author: Mișu Moldovan <dumol@chevah.com>
-Date: Wed Jan 7 17:51:07 2015 +0200
-
- Fix expr error in Solaris 10 when using gcc.
-
-commit 3fa5d70cbb18b39a5e44f1c7984dedf73446bf6c
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon Jan 5 13:03:06 2015 -0800
-
- x86: Avoid fastcall when building with pcc
-
- Apparently, PCC doesn't support the fastcall calling convention.
- Nor does it issue a warning or error for the attribute that it
- does not understand.
-
-commit a03d2310ed53bb8b3a4610af04015ef9df6ea36c
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Dec 24 16:03:34 2014 -0800
-
- x86: Load structure return address into eax
-
-commit b7f6d7aa9b0d7b19eec28a945251e09a4b65b275
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Dec 10 13:37:36 2014 -0800
-
- x86: Reinstate hand-written unwind info for sysv.S
-
-commit 6cedf81ca7cbad01b3fcc2c4475d860095bfb062
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Dec 10 09:43:58 2014 -0800
-
- x86: Expand FFI_GO_CLOSURE
-
- If we're going to have to hand-write unwind info for darwin,
- these macros make the job harder.
-
-commit ae842a515b6e2a486d73ce8f9dbe5fee6c3fd1ff
-Author: Iain Sandoe <iain@codesourcery.com>
-Date: Tue Nov 25 11:43:40 2014 +0100
-
- x86: More Darwin unwind fixups
-
- EHFrame{N} IIRC is a special cue to ld64 that it should treat the unwind
- in the object as "special/legacy" .. [these days everything is .cfi_xxxx
- (except, cctools-as, as you noted)] .. without that much confusion arises
- with ld64's atom-isation of the eh_frame section.
-
- xxxx.eh labels are not needed for darwin ld64 >= 85.2.1 (i.e. darwin9,
- xcode 3.1.4) to all intents and purposes, that's all that matters now,
- since I think that anyone trying to build on 10.4/darwin8/xcode2.5 would
- have to use a later ld64 (from odcctools) for other reasons.
-
-commit 8fa3c9f24b5ef6da2f24a9f071984d033dd9e00c
-Author: Richard Henderson <rth@twiddle.net>
-Date: Tue Nov 25 09:27:54 2014 +0100
-
- x86: Reinstate hand-written unwind info for unix64.S
-
- One more try to get default Darwin to work.
-
-commit 5f35e0ffcc05a72ce0aacf228dc06d1262754660
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon Nov 24 16:26:50 2014 +0100
-
- x86: Avoid using gas local labels
-
- Which are unsupported by Darwin cctools as.
- Thankfully this doesn't uglify the source too much.
-
-commit ed1ca2777c35fe2f2751de255df3e16f17bdbd8d
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon Nov 24 13:02:03 2014 +0100
-
- x86: Remove use of .cfi_escape
-
- The unwind info isn't 100% correct at all points during the epilogue,
- and not annotating is just as incorrect as the annotation. This works
- better on systems that do not support DW_OP_call_frame_cfa.
-
-commit 1b12593d7e595c03e5c06377feaeb8ad1b813681
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon Nov 24 12:55:43 2014 +0100
-
- x86: Honor alignment of arguments
-
- Darwin aligns long-double to 16, and thus all of the long double
- tests were failing due to not honoring that. We ought to be able
- to devise a test case for GCC using __attribute__((aligned)) that
- would have failed too.
-
-commit 042b8dafeeee82667e00660fb1edeab72fd9de47
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon Nov 24 11:24:02 2014 +0100
-
- x86: Use .balign not .align
-
- The Apple assembler defaults to power of two alignment, rather than
- byte alignment like everyone else. Force byte alignment by using
- the proper directive.
-
-commit 0172bc029cd943dce99f82b9d857c51e746574e5
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon Nov 24 10:42:02 2014 +0100
-
- x86: Disable .org for Darwin
-
-commit 9f112619c187e135132b765adeedef89ee354eb2
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sat Nov 22 20:02:43 2014 +0100
-
- x86: Best guess at update for Darwin
-
-commit 7282d3289c6f6e2cc21e2c2b554c33af00ac3474
-Author: Nobuyoshi Nakada <nobu@ruby-lang.org>
-Date: Mon Dec 22 17:14:40 2014 +0900
-
- x86: MSVC does not support Complex type
-
-commit 5f8881a5913a9554cbc2b5fed7057627b9bb9ece
-Author: Nobuyoshi Nakada <nobu@ruby-lang.org>
-Date: Mon Dec 22 17:08:08 2014 +0900
-
- x86: Fix void pointer arithmetic
-
-commit 58bf7d65d8896f198624c591cc31e6e01a09cc31
-Merge: 75b2199 7ba30b1
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Dec 20 10:20:40 2014 -0500
-
- Merge pull request #158 from rth7680/s390
-
- S390
-
-commit 7ba30b19060dfefefeb91970a862e5b215606602
-Author: Richard Henderson <rth@redhat.com>
-Date: Fri Dec 19 11:38:17 2014 -0500
-
- s390: Inline and tidy ffi_prep_args
-
- As per discussion with Ulrich Weigand, document the restrictions
- on the code within ffi_call_int as we simultaneously prepare
- stack frames for ffi_call_SYSV and the target function.
-
-commit f69ec6f35db93163b7f33e43129d274995c8122d
-Author: Richard Henderson <rth@redhat.com>
-Date: Thu Dec 18 16:21:07 2014 -0500
-
- s390: Use pc-relative insns in 31-bit mode
-
- It's silly to stick to esa/390 features when the compiler won't.
- Detect when brasl and larl are used by the compiler and then use
- them in the assembly.
-
-commit 2f530de168e0253ac06e044c832132c496e8788b
-Author: Richard Henderson <rth@redhat.com>
-Date: Thu Dec 18 16:01:59 2014 -0500
-
- s390: Reorganize assembly
-
- Avoid using ffi_prep_args as a callback; do all the work setting
- up the frame within ffi_call_int directly. Save fewer registers
- in ffi_closure_SYSV.
-
-commit 97512ded052678993ffcfa3aec0035cce1585138
-Author: Richard Henderson <rth@redhat.com>
-Date: Thu Dec 18 16:01:15 2014 -0500
-
- s390: Avoid aliasing warnings
-
-commit c860ca9ac0fc7ee44124c5637dda751f55e4fa3f
-Author: Richard Henderson <rth@redhat.com>
-Date: Wed Dec 17 13:24:03 2014 -0500
-
- s390: Kill trailing whitespace
-
-commit 02b7c89967307cea91714fb6e4e53048e1b5396e
-Author: Dominik Vogt <vogt@linux.vnet.ibm.com>
-Date: Wed Dec 17 13:20:51 2014 -0500
-
- s390: Go closure support
-
-commit 75b2199f264f42de814528ccf4bfd2ef427665b5
-Merge: 8a3a272 2f65246
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Dec 12 10:13:56 2014 -0500
-
- Merge pull request #157 from rth7680/x86
-
- Two fixes for x86
-
-commit 8a3a2723aaa615cb95ee1c798469d7a3b2d95d31
-Merge: 9ae3bc8 542e004
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Dec 12 10:13:27 2014 -0500
-
- Merge pull request #156 from rth7680/sparc
-
- sparc: Define FFI_TARGET_SPECIFIC_VARIADIC for v9
-
-commit 2f652469684d6d2b3e54705294c7e81cffe1341f
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Dec 11 14:16:00 2014 -0800
-
- x86: Handle void arguments as if an empty structure
-
- Since libffi currently doesn't allow empty structures, libgo
- currently maps them to ffi_type_void. Given that we'll abort
- on this case, handle it gracefully.
-
-commit 097ccfd6a6b94a3c3b5bfc269a7afd1dc4f7a051
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Dec 10 13:25:14 2014 -0800
-
- x86: Fix some unwind errors
-
-commit 9ae3bc870ee07820b60d368f137ea3b5daca850e
-Author: James Greenhalgh <james.greenhalgh@arm.com>
-Date: Sat Dec 6 23:58:41 2014 -0500
-
- Fix for https://github.com/atgreen/libffi/issues/141
-
-commit a5a40960bb6ccb029d2d9d4e18d37f6e0dacb913
-Merge: 9ca4370 590663b
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 19 21:13:50 2014 -0500
-
- Merge pull request #151 from amodra/master
-
- powerpc: go closures for linux
-
-commit 590663b30b1f35b6136cf55d8870a2394ed78c21
-Author: Richard Henderson <rth@twiddle.net>
-Date: Tue Nov 18 12:56:58 2014 +1030
-
- powerpc: Fix ffi_go_closure_linux64
-
- Unlike ffi_closure_LINUX64, this entry point is called normally,
- so we already have the TOC in R2 and the closure in R11.
-
- * powerpc/linux64_closure.S (ffi_closure_LINUX64): Remove a
- register dependency chain.
- (ffi_go_closure_linux64): Don't load r11 or r2.
-
-commit fa1040c111b3e423bc9c7e78d9af89470c0fa2fb
-Author: Alan Modra <amodra@gmail.com>
-Date: Mon Nov 10 09:42:31 2014 +1030
-
- GO closures for powerpc linux
-
- Plus .cfi async unwind info, rearrangement of ffi_call_linux64 and
- ffi_call_SYSV function params to avoid register copies, tweaks to
- trampolines.
-
- * src/powerpc/ffitarget.h (FFI_GO_CLOSURES): Define.
- * src/powerpc/ffi.c (ffi_call_int): New function with extra
- closure param, and args rearranged on ffi_call_linux64 and
- ffi_call_SYSV calls, extracted from ..
- (ffi_call): ..here.
- (ffi_call_go, ffi_prep_go_closure): New functions.
- * src/powerpc/ffi_linux64.c (ffi_prep_closure_loc_linux64): Make
- hidden. Only flush insn part of ELFv2 trampoline. Don't shuffle
- ELFv1 trampoline.
- (ffi_closure_helper_LINUX64): Replace closure param with cif, fun,
- user_data params.
- * src/powerpc/ffi_powerpc.h (ffi_go_closure_sysv): Declare.
- (ffi_go_closure_linux64): Declare.
- (ffi_call_SYSV, fi_call_LINUX64): Update.
- (ffi_prep_closure_loc_sysv, ffi_prep_closure_loc_linux64): Declare.
- (ffi_closure_helper_SYSV, ffi_closure_helper_LINUX64): Update.
- * src/powerpc/ffi_sysv.c (ASM_NEEDS_REGISTERS): Increase to 6.
- (ffi_prep_closure_loc_sysv): Use bcl in trampoline, put data words
- last, flush just the insn part.
- (ffi_closure_helper_SYSV): Replace closure param with cif, fun and
- user_data params.
- * src/powerpc/linux64.S (ffi_call_LINUX64): Replace hand-written
- .eh_frame with .cfi directives. Adjust for changed param order.
- Pass extra "closure" param to user function in static chain. Add
- .cfi directives to describe epilogue. Don't provide traceback
- table for ELFv2 or _CALL_LINUX.
- * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Replace
- hand-written .eh_frame with .cfi directives. Adjust for changed
- ffi_closure_helper_LINUX64 params. Add .cfi directives to
- describe epilogue. Don't provide traceback table for ELFv2 or
- _CALL_LINUX.
- (ffi_go_closure_linux64): New function.
- * src/powerpc/sysv.S: Remove redundant .globl ffi_prep_args_SYSV.
- (ffi_call_SYSV): Make hidden. Replace hand-written .eh_frame with
- .cfi directives. Adjust for changed params. Pass extra "closure"
- param to user function in static chain. Add .cfi directives to
- describe epilogue.
- * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Make hidden.
- Replace hand-written .eh_frame with .cfi directives. Adjust for
- changed ffi_closure_helper_SYSV params. Add .cfi directives to
- describe epilogue. Don't just use nops in the dead __NO_FPRS__
- epilogues.
- (ffi_go_closure_sysv): New function.
-
-commit d3d06f4c94847402a08f0e4e2af2e4d726ed3180
-Author: Alan Modra <amodra@gmail.com>
-Date: Mon Nov 10 13:50:05 2014 +1030
-
- Fix powerpc breakage from 6e8a4460
-
- * src/powerpc/ffitarget.h: #error on unexpected FFI_TYPE_LAST.
- (FFI_PPC_TYPE_LAST): Define.
- (FFI_TYPE_UINT128): Define in terms of FFI_PPC_TYPE_LAST.
- (FFI_SYSV_TYPE_SMALL_STRUCT, FFI_V2_TYPE_FLOAT_HOMOG): Likewise.
- (FFI_V2_TYPE_DOUBLE_HOMOG, FFI_V2_TYPE_SMALL_STRUCT): Likewise.
-
-commit 9ca43706f9e59ee3a0b288884c90fd51d8926a9b
-Merge: 5211c72 a9ed0c3
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 19 11:32:08 2014 -0500
-
- Merge pull request #148 from gpakosz/dlmalloc-preprocessor-fix
-
- dlmalloc: change defined(i386) to defined(__i386__)
-
-commit 542e004710e3f1d7c137bba305a16538cd6257d6
-Author: Richard Henderson <rth@twiddle.net>
-Date: Tue Nov 18 05:07:00 2014 -0800
-
- sparc: Define FFI_TARGET_SPECIFIC_VARIADIC for v9
-
- This is a port of
-
- http://gcc.gnu.org/viewcvs?rev=207763&root=gcc&view=rev
-
- aka GCC PR libffi/60073, to the rewritten Sparc codebase.
- Supposedly, we should have seen failures with the existing
- libffi.call/cls_double_va.c testcase, but I hadn't.
- Perhaps a gcc newer than 4.6.3 is required to see that...
-
-commit a9ed0c3a0428f5fd4ed2166fa95a608595e11a4d
-Author: Gregory Pakosz <gpakosz@myscript.com>
-Date: Tue Nov 18 09:37:07 2014 +0100
-
- dlmalloc: change defined(i386) to defined(__i386__)
-
- When compiling with --std==c99, GCC and clang don't define i386 but __i386__
-
-commit 5211c7207ec81dfdfa9acdcd86b49b9ff66b9d91
-Merge: 3316b66 ccdd7bb
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 17 09:07:07 2014 -0500
-
- Merge pull request #147 from rth7680/go/alpha
-
- testsuite: Fix alpha static chain register name
-
-commit ccdd7bb8566b2fd1da5c4b5c8eaa2db43a69e720
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sun Nov 16 12:12:23 2014 +0100
-
- testsuite: Fix alpha static chain register name
-
-commit 3316b666e3074fe0eebff4fe0458979961b26651
-Merge: b698638 dea49e2
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 15 07:31:41 2014 -0500
-
- Merge pull request #145 from rth7680/master
-
- Configure and testsuite cleanups, v2
-
-commit b698638d7601de994410c5c1b2f5c2c648015b7b
-Merge: a353d5b 771fabc
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 15 07:29:58 2014 -0500
-
- Merge pull request #144 from atrosinenko/testsuite-fp-comparison-fix
-
- Floating point number comparison fix for testsuite
-
-commit a353d5b16cfbb60f1a42bdec74b0f272701f3ecb
-Merge: 4aa702a e029c70
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 15 07:27:21 2014 -0500
-
- Merge pull request #143 from adamkaplan/patch-1
-
- Update i386 & armv7 minimum iOS version to 7.0
-
-commit dea49e2020b2fc97ba9293200f316f7a7b3ca73b
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Nov 14 13:05:14 2014 +0100
-
- x86: Fix typo in ffi_prep_go_closure
-
- Used the wrong register for THISCALL and FASTCALL.
-
-commit c9f5b6648b0f052bbca8b50615284dd975e9ed29
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Nov 14 13:04:33 2014 +0100
-
- testsuite: Add trivial tests for Go closures
-
-commit c952a92e20aa6013d8202d0b3fa1d87838c83054
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Nov 14 11:00:14 2014 +0100
-
- testsuite: Move complex tests to their own subdirectory
-
- It seems a bit silly to isolate them by globbing vs "*complex*"
- when we can just as easily put them in their own subdirectory.
-
-commit f1301a54bb80e6ae23f7687c68f36875dae69134
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Nov 14 10:50:29 2014 +0100
-
- testsuite: Use feature test rather than enumeration for complex
-
-commit b5ade2fb5d9ba06519484677a5474e5dad48c2e3
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Nov 13 09:06:10 2014 -0800
-
- testsuite: Detect clang
-
- Clang doesn't like the -Wno-psabi argument that we want to pass to GCC.
- Since clang is detected as GCC via __GNUC__, use ax_cv_c_compiler_vendor.
-
-commit 5d69d57a053c5049df29242def492159e1fadbae
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Nov 13 13:50:39 2014 +0100
-
- configure: Move target source selection into configure.host
-
- This eliminates the AM_CONDITIONAL ugliness, which eliminates
- just a bit of extra boilerplate for a new target.
-
- At the same time, properly categorize the EXTRA_DIST files
- into SOURCES and HEADERS, for the generation of ctags.
-
-commit 771fabc6d5379e64e5ab9e5f1ca6eb5960617432
-Author: Anatoly Trosinenko <anatoly.trosinenko@gmail.com>
-Date: Fri Nov 14 14:21:35 2014 +0300
-
- Take a float absolute value using fabs() instead of abs().
-
- Replace integer abs() by floating point fabs() in the approximate
- equality check for float values.
-
-commit 9622ede2e24067a09380c63da8d5007ec1f03dc4
-Author: Anatoly Trosinenko <anatoly.trosinenko@gmail.com>
-Date: Fri Nov 14 13:18:04 2014 +0300
-
- Fix floating point number comparisons in testsuite/libffi.call/float[123].c.
-
- Rewrite the checks for approximate equality of floating point return
- values to be in the form "fabs(a - b) < EPS" instead of just
- "a - b < EPS".
-
-commit e029c70fa7da7a489157b2a2a88349aaffb051de
-Author: Adam <adkapx@gmail.com>
-Date: Thu Nov 13 15:08:16 2014 -0500
-
- Update i386 & armv7 minimum iOS version to 7.0
-
- iOS 5 (and any below 7.1) is deprecated. Apple doesn't distribute the supporting libraries for this platform anymore as of Xcode 6, so it causes a linker error.
-
-commit 57f52484573613e2def21171184f50bd72209cac
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Nov 13 12:42:54 2014 +0100
-
- configure: Split out configure.host
-
- Split out the host case statement to a separate file, so that
- we don't have to regenerate configure.in for changes therein.
-
-commit f8632815a6515a6709802ad23909585664ba1b9d
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Nov 13 12:32:35 2014 +0100
-
- powerpc: Delete patch output
-
- Clearly added by mistake.
-
-commit 4aa702a0e0ffc9b8a672af380103f607d339a822
-Merge: 20562ac 8d5debc
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 12 08:08:57 2014 -0500
-
- Merge branch 'rth7680-go-closure'
-
-commit 8d5debc7904aa5c4f1fbf5d5b26450ec5a5b43c6
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 12 08:04:51 2014 -0500
-
- Update in preparation for next release
-
-commit 56735e05fed77a3920a8cac262666c9eb0e75b66
-Merge: 20562ac 0e303c0
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Nov 12 07:11:53 2014 -0500
-
- Merge branch 'go-closure' of https://github.com/rth7680/libffi into rth7680-go-closure
-
- Conflicts:
- src/aarch64/ffi.c
-
-commit 20562ac0427c3578250d04c6e34fb0127d4551cf
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 12 07:00:59 2014 -0500
-
- Fix for AArch64. Release as 3.2.1.
-
-commit 0e303c065779afb42cfdb2ea20c0e1a557dc16f0
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Nov 12 03:58:58 2014 -0800
-
- x86: Work around clang bugs
-
- http://llvm.org/bugs/show_bug.cgi?21500
- http://llvm.org/bugs/show_bug.cgi?21501
- http://llvm.org/bugs/show_bug.cgi?21515
-
-commit 6eec410f1512d0584276db5f4b83711330e830d7
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sun Oct 26 15:29:04 2014 -0700
-
- sparc: Re-add abi compliant structure support
-
- The original code, removed in the "rewrite" patch, was incorrect for
- large structures, and required dynamic allocation of a trampoline on
- every ffi_call.
-
- Instead, allocate a 4k entry table of all possible structure returns.
- The table is 80k, but is read-only and dynamically paged, which ought
- to be better than allocating the trampoline.
-
- This is difficult to test with gcc. One can only use -O0 at present.
- See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63668.
-
-commit 92022496ef7a9439f48a2ef11e460c300ac863d7
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sun Oct 26 14:48:28 2014 -0700
-
- sparc: Add support for Go closures
-
-commit ad89c2d9e93d5a713ae4113567b4ca6c4fbbf17c
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sun Oct 26 13:16:03 2014 -0700
-
- sparc: Add support for complex types
-
-commit 20da5b41324de524ea3ee1f84f402828b7c332dc
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sat Oct 25 16:24:41 2014 -0700
-
- sparc: Handle more cases of structure return directly
-
-commit 0686c2e71c8e094cf003f199e3f578bcdede43ba
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sat Oct 25 14:52:45 2014 -0700
-
- sparc: Preprocess float point struct return
-
- We can eliminate recursion and speed structure return
- by flattening a nested structure tree into a bitmask.
-
-commit 2b27890ba77db6a23d37fc70897109e4b2803c2d
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 24 16:10:48 2014 -0700
-
- sparc: Rewrite everything
-
- It's impossible to call between v8 and v9 ABIs, because of the stack bias
- in the v9 ABI. So let's not pretend it's just not implemented yet. Split
- the v9 code out to a separate file.
-
- The register windows prevent ffi_call from setting up the entire stack
- frame the assembly, but we needn't make an indirect call back to prep_args.
-
-commit 5d7b54450582f31d0d5d3ecca7f330b70446f195
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 24 11:45:53 2014 -0700
-
- sparc: Tidy up symbols
-
- Assembly to use local labels, .type annotation, hidden annotation.
- I do retain the _prefix for the symbols, but given that it wasn't
- done consistently across all symbols, I doubt it's actually needed.
-
-commit fd4f7cc0cabae66a91e40f8645791740b9416bc1
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 24 11:11:53 2014 -0700
-
- sparc: Eliminate long double ifdefs
-
-commit ab83cbb90b280195e636976098d3674f5ffc1d0a
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Oct 29 14:38:42 2014 -0400
-
- arm: Add support for Go closures
-
-commit 6fa617dabc3d99e19d47ac9bc4127c56e3163008
-Author: Richard Henderson <rth@twiddle.net>
-Date: Tue Oct 21 11:27:11 2014 -0400
-
- arm: Add argument space for the hidden struct return pointer
-
- This should have been failing all along, but it's only
- exposed by the complex_int test case.
-
-commit a529bec27b64ab846ab2643ecbeb22e01f35c7dc
-Author: Richard Henderson <rth@twiddle.net>
-Date: Tue Oct 21 11:26:59 2014 -0400
-
- arm: Add support for complex types
-
-commit 5e88ebe62717b8e1e2f8d96c10f78a7134caa765
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon Oct 20 15:10:43 2014 -0400
-
- arm: Remove internal FFI_TYPE constants
-
- These have been replaced by the contents of internal.h.
-
-commit a4b785ea695e929b91d64e1e8b514411ae8bafe8
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 02:07:32 2014 -0400
-
- arm: Rewrite ffi_closure
-
- Move the push of the argument registers into ffi_closure_SYSV,
- reducing the size of the trampoline.
-
-commit e7f15f60e86ad8931b2c4a516945d0b76b4bda20
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 01:27:16 2014 -0400
-
- arm: Rewrite ffi_call
-
- Use the trick to allocate the stack frame for ffi_call_SYSV
- within ffi_call itself.
-
-commit a74a3aaddbcc730d9aa0a4787f136c9cc19b82b3
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 01:21:22 2014 -0400
-
- arm: Rewrite vfp_type_p
-
- Do not modify the ffi_type. Rearrange the tests so that we
- quickly eliminate structures that cannot match. Return an
- encoded value of element count and base type.
-
-commit 0d39b4bb692b1a8e4f3354badcd9e123f8276bd4
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 01:02:52 2014 -0400
-
- arm: Deref ffi_put_arg arguments
-
-commit 57b24fb3f5471262ce57e1a912774d6e7de5ada7
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 00:53:21 2014 -0400
-
- arm: Deref ffi_align argument
-
-commit c129bea82a25c9b0f3af3bf48c35c55257092f87
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Oct 15 17:28:53 2014 -0400
-
- arm: Reindent arm/ffi.c
-
-commit 9761b7bb70b4c47dc11dc74830964a0b3b3176d3
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 21:26:52 2014 -0700
-
- alpha: Add support for Go closures
-
-commit f41bec3b576aa5ff8915b1188446c2dc086dfe64
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 20:46:48 2014 -0700
-
- alpha: Add support for complex types
-
-commit 5f917371afcb4d3363fd33b547844c47264f6d4e
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 13:47:26 2014 -0700
-
- alpha: Clean up conversion of float values
-
- Don't use "real" conversion to double, lest we raise
- exceptions when passing signalling nans.
-
-commit 32a26b75ba92665fa093b539318e83d916e3effb
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 12:33:53 2014 -0700
-
- alpha: Reorganize cif flags
-
- Unties the backend from changes to FFI_TYPE_* constants, and allows
- compilation to succeed after the addition of FFI_TYPE_COMPLEX.
-
- Delete the hand-written unwind info.
-
-commit c6352b664c31835b9527d747f8a29b4754cabb0e
-Author: Richard Henderson <rth@redhat.com>
-Date: Thu Oct 23 00:26:14 2014 -0400
-
- aarch64: Add support for Go closures
-
-commit 0e41c73b092064e986d484270a13046479d6bda3
-Author: Richard Henderson <rth@redhat.com>
-Date: Wed Oct 22 23:48:12 2014 -0400
-
- aarch64: Move x8 out of call_context
-
- Reduces stack size. It was only used by the closure, and there
- are available argument registers.
-
-commit a992f8789b5202ca180e67b16b47ee834160665c
-Author: Richard Henderson <rth@redhat.com>
-Date: Wed Oct 22 22:58:09 2014 -0400
-
- aarch64: Add support for complex types
-
-commit 658b2b56001e293848ea22b70068bd7f8daa7205
-Author: Richard Henderson <rth@redhat.com>
-Date: Wed Oct 22 22:36:07 2014 -0400
-
- aarch64: Remove aarch64_flags
-
- This field was useless from the start, since the normal flags
- field is available for backend use.
-
-commit 4a3cbcaa4f1d3834e0b74c9a841c3f51c5e0454c
-Author: Richard Henderson <rth@redhat.com>
-Date: Wed Oct 22 22:32:13 2014 -0400
-
- aarch64: Unify scalar fp and hfa handling
-
- Since an HFA of a single element is exactly the same as scalar,
- this tidies things up a bit.
-
-commit 12cf89ee04dc01650f71bc38ce414c953c83199a
-Author: Richard Henderson <rth@redhat.com>
-Date: Wed Oct 22 21:53:30 2014 -0400
-
- aarch64: Move return value handling into ffi_closure_SYSV
-
- As with the change to ffi_call_SYSV, this avoids copying data
- into a temporary buffer.
-
-commit 4fe1aea1211aaf228c2db867b8ac6f1620de72d4
-Author: Richard Henderson <rth@redhat.com>
-Date: Wed Oct 22 17:06:19 2014 -0400
-
- aarch64: Move return value handling into ffi_call_SYSV
-
- This lets us pass return data directly to the caller of ffi_call
- in most cases, rather than storing it into temporary storage first.
-
-commit 325471ea6a7bf954943485458a1bd391635dfaa8
-Author: Richard Henderson <rth@redhat.com>
-Date: Wed Oct 22 13:58:59 2014 -0400
-
- aarch64: Merge prep_args with ffi_call
-
- Use the trick to allocate the stack frame for ffi_call_SYSV
- within ffi_call itself.
-
-commit 8c8161cb623585d5d0c783b9d494b9b74ada6ced
-Author: Richard Henderson <rth@redhat.com>
-Date: Wed Oct 22 12:52:07 2014 -0400
-
- aarch64: Tidy up abi manipulation
-
- Avoid false abstraction, like get_x_addr. Avoid recomputing data
- about the type being manipulated. Use NEON insns for HFA manipulation.
-
- Note that some of the inline assembly will go away in a subsequent patch.
-
-commit b55e03665ddf2423df9baee0d3172892ba781c26
-Author: Richard Henderson <rth@redhat.com>
-Date: Wed Oct 22 12:33:59 2014 -0400
-
- aarch64: Treat void return as not passed in registers
-
- This lets us do less post-processing when there's no return value.
-
-commit 2e32f9bf6ffa6782b70fafe96bdf21c5aa44f534
-Author: Richard Henderson <rth@redhat.com>
-Date: Tue Oct 21 22:49:05 2014 -0400
-
- aarch64: Use correct return registers
-
- There are fewer return registers than argument registers.
-
-commit 95a04af134431ccc8230aca1641541a5e8fcbdc9
-Author: Richard Henderson <rth@redhat.com>
-Date: Tue Oct 21 22:41:07 2014 -0400
-
- aarch64: Reduce the size of register_context
-
- We don't need to store 32 general and vector registers.
- Only 8 of each are used for parameter passing.
-
-commit 77c4cddca6aeb6e545e21f235e29323e05f5a3a3
-Author: Richard Henderson <rth@redhat.com>
-Date: Tue Oct 21 13:30:40 2014 -0400
-
- aarch64: Simplify AARCH64_STACK_ALIGN
-
- The iOS abi doesn't require padding between arguments, but
- that's not what AARCH64_STACK_ALIGN meant. The hardware will
- in fact trap if the SP register is not 16 byte aligned.
-
-commit b5f147d84761dc673ffe01d6af82bcde4ea47928
-Author: Richard Henderson <rth@redhat.com>
-Date: Tue Oct 21 13:27:57 2014 -0400
-
- aarch64: Always distinguish LONGDOUBLE
-
- Avoid if-deffery by forcing FFI_TYPE_LONGDOUBLE different
- from FFI_TYPE_DOUBLE. This will simply be unused on hosts
- that define them identically.
-
-commit 38b54b9c180af13a3371e70a151a1a97e105b03f
-Author: Richard Henderson <rth@redhat.com>
-Date: Tue Oct 21 13:17:39 2014 -0400
-
- aarch64: Improve is_hfa
-
- The set of functions get_homogeneous_type, element_count, and is_hfa
- are all intertwined and recompute data. Return a compound quantity
- from is_hfa that contains all the data and avoids the recomputation.
-
-commit 18b74ce54afab45fcf2a7d4eb86bb2ce9db8cec8
-Author: Richard Henderson <rth@redhat.com>
-Date: Tue Oct 21 13:00:34 2014 -0400
-
- aarch64: Fix non-apple compilation
-
-commit 2650f47fe8388f3281ec00e2d1e3bc777c1d3544
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Nov 6 10:57:04 2014 -0800
-
- x86: Use win32 name mangling for fastcall functions
-
-commit f8c64e2486c956109bf5255a0c0a85f24cc86c72
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Nov 5 17:04:29 2014 +0100
-
- x86: Add support for Go closures
-
-commit 198f469e91076f84ab6ac38055ad12a5490101cd
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Nov 5 16:34:41 2014 +0100
-
- x86: Add support for Complex
-
-commit b21ec1ce783f09335c0e6c6f96ccc7e89da5a1b4
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Nov 5 10:15:25 2014 +0100
-
- x86: Rewrite closures
-
- Move everything into sysv.S, removing win32.S and freebsd.S.
- Handle all abis with a single ffi_closure_inner function.
- Move complexity of the raw THISCALL trampoline into assembly
- instead of the trampoline itself.
- Only push the context for the REGISTER abi; let the rest
- receive it in a register.
-
-commit b9ac94f3af9b1ca1853850911b7d3bc058296c71
-Author: Richard Henderson <rth@twiddle.net>
-Date: Sat Nov 1 15:10:34 2014 -0700
-
- x86: Rewrite ffi_call
-
- Decouple the assembly from FFI_TYPE_*. Merge prep_args with ffi_call,
- passing the frame and the stack to the assembly.
-
- Note that this patch isn't really standalone, as this breaks closures.
-
-commit 159d3788eb52b89ed6bc5dd6ebb85c02cd150232
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 31 12:07:02 2014 -0700
-
- x86: Convert to gas generated unwind info
-
-commit e7b0056d60f29675072454a575eed98053fc63d6
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Oct 30 13:57:39 2014 -0700
-
- x86: Force FFI_TYPE_LONGDOUBLE different from FFI_TYPE_DOUBLE
-
- There are few abis that set double = long double. Eliminate the
- conditional compilation and let this code simply be unused there.
-
-commit 4b2fad8fd583f1d9c36db0044c4d46316207aa49
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Oct 30 12:41:31 2014 -0700
-
- x86: Remove some conditional compilation
-
- Removal of ifdefs made possible to due to ffi_abi unification.
-
-commit ef76205647bca77796882d31f6ab5e889f461f07
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Oct 30 12:13:31 2014 -0700
-
- x86: Tidy ffi_abi
-
- The x86_64 unix port only handles one ABI; don't define all of the
- other symbols. The UNIX64 symbol retains the same value.
-
- The i386 ports ought to have the same symbols, even if we can't yet
- unify the values without incrementing the libffi soname.
-
-commit 7cf841324f3d15c46833e0f2ddf8a98c4b24711e
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Nov 7 06:56:55 2014 -0800
-
- testsuite: Add two dg-do run markers
-
- Caught by clang warning about unused -L parameter.
-
-commit fc501750f41e2ee7f4268f490f590ce97a25a818
-Author: Richard Henderson <rth@twiddle.net>
-Date: Wed Nov 5 16:33:44 2014 +0100
-
- testsuite: Fix return_complex2 vs excessive precision
-
- Use the previously computed rc2 to validate, rather than
- recomputing a floating point result with excess precision.
-
-commit 610c90bf7131de70318dc981a529a63ae36981b8
-Author: Richard Henderson <rth@twiddle.net>
-Date: Tue Oct 28 11:21:50 2014 -0700
-
- x86_64: Add support for complex types
-
-commit 32c56831636a489a1c5084e42ffbd935902b1033
-Author: Richard Henderson <rth@twiddle.net>
-Date: Tue Oct 28 11:17:35 2014 -0700
-
- x86_64: Decouple return types from FFI_TYPE constants
-
- We can better support structure returns, and as prep for
- complex types.
-
-commit 2e9dc1655600eb8928ebab13fa246187b6205109
-Author: Richard Henderson <rth@twiddle.net>
-Date: Mon Oct 27 13:41:39 2014 -0700
-
- x86_64: Fixups for x32
-
-commit ebd82769de5fc909ec9678aafca674ece394d173
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Oct 23 23:57:06 2014 -0700
-
- win64: Remove support from ffi.c
-
-commit 99db4d42acc7ee6d2ad206848be38083d7b5e094
-Author: Richard Henderson <rth@twiddle.net>
-Date: Thu Oct 23 14:12:18 2014 -0700
-
- win64: Rewrite
-
- It's way too different from the 32-bit ABIs with which it is
- currently associated. As seen from all of the existing XFAILs.
-
-commit 6b62fb4a26d7363548a92f1a156562cfa648726e
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 11:11:58 2014 -0700
-
- x86-64: Support go closures
-
- Dumps all of the hand-coded unwind info for gas generated. Move jump
- table data into .rodata. Adjust ffi_call_unix64 to load the static
- chain. Split out sse portions of ffi_closure_unix64 to
- ffi_closure_unix64_sse rather than test cif->flags at runtime.
-
-commit 89bbde8b4e802625bdbf830ea14e938beea79835
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 10:55:11 2014 -0700
-
- Add ffi_cfi.h
-
- Have one copy of the HAVE_AS_CFI_PSEUDO_OP code
- to share between all backends.
-
-commit e951d64c085267a30036907d02f94a70dee4c9d9
-Author: Richard Henderson <rth@twiddle.net>
-Date: Fri Oct 17 10:12:25 2014 -0700
-
- Add entry points for interacting with Go
-
- A "ffi_go_closure" is intended to be compatible with the
- function descriptors used by Go, and ffi_call_go sets up
- the static chain parameter for calling a Go function.
-
- The entry points are disabled when a backend has not been
- updated, much like we do for "normal" closures.
-
-commit a0bdc5250cd36f1d2578358e33299fd2408091ac
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 11 09:43:01 2014 -0500
-
- Fix typo
-
-commit 67c0c0705318d2e567fd48e680d63dca3619a235
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 11 07:30:49 2014 -0500
-
- Final 3.2 changes
-
-commit ee826b933bbdeb68ee81876ffb508c3908eed371
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 11 07:29:26 2014 -0500
-
- Final 3.2 changes
-
-commit c81a705d53be97899d314953987936213244b1ba
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 4 13:29:58 2014 -0500
-
- Mention OpenRISC
-
-commit 6a17ad540d7ddb7a812687f4380bd0ef2d2865bb
-Merge: 990eb9d 0f316ab
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Sep 28 00:54:00 2014 -0400
-
- Merge pull request #134 from s-macke/openrisc
-
- Add OpenRISC support
-
-commit 990eb9d4c244324771a7d878a168bb8eba1850c0
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Sep 28 00:50:29 2014 -0400
-
- Only run the complex type tests on supported platforms.
-
-commit 0f316ab7c11b8315a838a6ae4645d36ff2c46f4c
-Author: Sebastian Macke <sebastian@macke.de>
-Date: Sat Sep 27 00:19:15 2014 +0000
-
- Add OpenRISC support
-
- This patch adds support for the OpenRISC architecture.
- (http://opencores.org/or1k/Main_Page)
-
- This patch has been tested under Linux with QEMU-user emulation support.
- - 32 Bit
- - big endian
- - delayed instructions
- This is the only available configuration under Linux.
-
- The description of the ABI can be found on the official website.
-
- Is passes the testsuite except of the unwindtest_ffi_call.cc
- testcase, which seems to be a problem of gcc and not libffi.
- Some testcases of the gcc testsuite still fail.
-
- Signed-off-by: Sebastian Macke <sebastian@macke.de>
-
-commit 6695983d2f0857caab220862de12f3f94a55bcf6
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Sep 20 07:44:37 2014 -0400
-
- Add complex type support. Mostly broken right now
-
-commit fbbf48fbdf9b1491af0aefc00523a1b5d8bb9349
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Sep 20 07:43:51 2014 -0400
-
- Compile tests with -Wno-psabi when using GCC
-
-commit ae8d2554c5f192be54dadc9f99a1449b4df1b222
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Sep 20 07:08:37 2014 -0400
-
- Update version to 3.2
-
-commit b2ca59d39d2192021316561ea9dda3d35d8d35d9
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Sep 20 07:08:05 2014 -0400
-
- More README updates for 3.2
-
-commit f920a01ad8eafc79daaf331499ef9a97696c46a7
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Sep 20 06:54:06 2014 -0400
-
- Update release notes.
-
-commit bfcbf329c5e4bebdb32134d4e53260e17e4e66cc
-Author: Bernd Edlinger <bernd.edlinger@hotmail.de>
-Date: Sat Sep 20 06:51:45 2014 -0400
-
- 2014-05-11 Bernd Edlinger <bernd.edlinger@hotmail.de>
-
- Fix current cygwin-64 build problems.
- * src/java_raw_api.c: Remove if !defined(FFI_NO_RAW_API).
- * src/x86/ffi.c: Add if defined(__CYGWIN__).
- * src/x86/win64.S (ffi_closure_win64, ffi_call_win64): Added
- handling for FFI_TYPE_UINT64, FFI_TYPE_POINTER and FFI_TYPE_INT.
- Added SEH information. Fixed formatting.
-
-commit 32cb2ce81db9457c6bd43a2587d7fa23a2edb9b1
-Author: Jakub Jelinek <jakub@redhat.com>
-Date: Sat Sep 20 06:39:55 2014 -0400
-
- 2014-09-10 Jakub Jelinek <jakub@redhat.com>
-
- * src/powerpc/linux64.S: Emit .note.GNU-stack even when
- POWERPC64 is not defined.
- * src/powerpc/linux64_closure.S: Likewise. Also test _CALL_ELF == 2.
-
-commit aaf3101ba81af8f488502881648e3f687721671e
-Author: Matthias Klose <doko@ubuntu.com>
-Date: Sat Sep 20 06:37:04 2014 -0400
-
- Fix -Werror=declaration-after-statement problem
-
-commit 6e8a4460833594d5af1b4539178025da0077df19
-Author: Dominik Vogt <vogt@linux.vnet.ibm.com>
-Date: Sat Sep 20 06:21:19 2014 -0400
-
- 2014-07-22 Dominik Vogt <vogt@linux.vnet.ibm.com>
-
- * src/types.c (FFI_TYPEDEF, FFI_NONCONST_TYPEDEF): Merge the macros by
- adding another argument that controls whether the result is const or not
- (FFI_LDBL_CONST): Temporary macro to reduce ifdef confusion
- * src/prep_cif.c (ffi_prep_cif_core): Replace list of systems with new
- macro FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
- * src/pa/ffitarget.h (FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION):
- Define.
- * src/s390/ffitarget.h (FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION):
- Define.
- * src/x86/ffitarget.h (FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION):
- Define.
-
- 2014-07-22 Dominik Vogt <vogt@linux.vnet.ibm.com>
-
- * doc/libffi.texi (Primitive Types): Document ffi_type_complex_float,
- ffi_type_complex_double and ffi_type_complex_longdouble
- (Complex Types): New subsection.
- (Complex Type Example): Ditto.
- * testsuite/libffi.call/cls_align_complex_double.c: New
- FFI_TYPE_COMPLEX test.
- * testsuite/libffi.call/cls_align_complex_float.c: Ditto.
- * testsuite/libffi.call/cls_align_complex_longdouble.c: Ditto.
- * testsuite/libffi.call/cls_complex_double.c: Ditto.
- * testsuite/libffi.call/cls_complex_float.c: Ditto.
- * testsuite/libffi.call/cls_complex_longdouble.c: Ditto.
- * testsuite/libffi.call/cls_complex_struct_double.c: Ditto.
- * testsuite/libffi.call/cls_complex_struct_float.c: Ditto.
- * testsuite/libffi.call/cls_complex_struct_longdouble.c: Ditto.
- * testsuite/libffi.call/cls_complex_va_double.c: Ditto.
- * testsuite/libffi.call/cls_complex_va_float.c: Ditto.
- * testsuite/libffi.call/cls_complex_va_longdouble.c: Ditto.
- * testsuite/libffi.call/complex_double.c: Ditto.
- * testsuite/libffi.call/complex_defs_double.c: Ditto.
- * testsuite/libffi.call/complex_float.c: Ditto.
- * testsuite/libffi.call/complex_defs_float.c: Ditto.
- * testsuite/libffi.call/complex_longdouble.c: Ditto.
- * testsuite/libffi.call/complex_defs_longdouble.c: Ditto.
- * testsuite/libffi.call/complex_int.c: Ditto.
- * testsuite/libffi.call/many_complex_double.c: Ditto.
- * testsuite/libffi.call/many_complex_float.c: Ditto.
- * testsuite/libffi.call/many_complex_longdouble.c: Ditto.
- * testsuite/libffi.call/return_complex1_double.c: Ditto.
- * testsuite/libffi.call/return_complex1_float.c: Ditto.
- * testsuite/libffi.call/return_complex1_longdouble.c: Ditto.
- * testsuite/libffi.call/return_complex2_double.c: Ditto.
- * testsuite/libffi.call/return_complex2_float.c: Ditto.
- * testsuite/libffi.call/return_complex2_longdouble.c: Ditto.
- * testsuite/libffi.call/return_complex_double.c: Ditto.
- * testsuite/libffi.call/return_complex_float.c: Ditto.
- * testsuite/libffi.call/return_complex_longdouble.c: Ditto.
- * src/raw_api.c (ffi_raw_to_ptrarray): Handle FFI_TYPE_COMPLEX
- (ffi_ptrarray_to_raw): Ditto.
- * src/prep_cif.c (ffi_prep_cif_core): Abort if FFI_TYPE_COMPLEX is not
- implemented in libffi for the target.
- * src/java_raw_api.c (ffi_java_raw_size): FFI_TYPE_COMPLEX not supported
- yet (abort).
- (ffi_java_raw_to_ptrarray): Ditto.
- (ffi_java_rvalue_to_raw): Ditto.
- (ffi_java_raw_to_rvalue): Ditto.
- * src/debug.c (ffi_type_test): Add debug tests for complex types.
- * include/ffi.h.in (FFI_TYPE_COMPLEX): Add new FFI_TYPE_COMPLEX.
- (FFI_TYPE_LAST): Bump.
- (ffi_type_complex_float): Add new ffi_type_....
- (ffi_type_complex_double): Ditto.
- (ffi_type_complex_longdouble): Ditto.
-
- 2014-07-22 Dominik Vogt <vogt@linux.vnet.ibm.com>
-
- * src/s390/ffitarget.h (FFI_TARGET_HAS_COMPLEX_TYPE): Define to provide
- FFI_TYPE_COMPLEX support.
- * src/s390/ffi.c (ffi_check_struct_type): Implement FFI_TYPE_COMPLEX
- (ffi_prep_args): Ditto.
- (ffi_prep_cif_machdep): Ditto.
- (ffi_closure_helper_SYSV): Ditto.
-
-commit 4c5c4088aa3e4d8103ff9ca441937da64fdd849a
-Merge: 862f53d 5d6340e
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Sep 18 19:10:54 2014 -0400
-
- Merge pull request #132 from nielsAD/master
-
- Pascal and Register calling convention support on x86
-
-commit 862f53de04ff898a128be7eec592bae60930d6df
-Merge: 5df3840 aebf2c3
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Sep 18 19:06:08 2014 -0400
-
- Merge pull request #130 from frida/fix/darwin-aarch64-float-alignment
-
- Fix alignment of FFI_TYPE_FLOAT for Apple's ARM64 ABI
-
-commit 5df384077f3633ec8cf2e08f9199e5a44994dbad
-Merge: 7b7a528 0f4e09d
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Sep 18 19:05:35 2014 -0400
-
- Merge pull request #129 from frida/fix/darwin-aarch64-cif-prep
-
- Fix non-variadic CIF initialization for Apple/ARM64
-
-commit 7b7a5284de7a99edfcee5ac362dbf76251698e1e
-Merge: 4cd5e84 6172a99
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Sep 18 18:28:05 2014 -0400
-
- Merge pull request #124 from knuesel/master
-
- Fix issue with builddir when calling configure with absolute path
-
-commit 4cd5e840122e22636b5838943372c4ed74618e35
-Merge: 1cee07b 08853e3
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Sep 18 18:27:15 2014 -0400
-
- Merge pull request #123 from ehsan/clang-cl
-
- Add support for building with clang-cl
-
-commit 5d6340ef2cf81432da79ac8b0b1b1218ab391438
-Author: nielsAD <niels.a.d@gmail.com>
-Date: Mon Aug 25 17:29:44 2014 +0200
-
- Determine whether register arguments (THISCALL/FASTCALL/REGISTER) are really passed via register to closures. Use stack if not.
-
-commit 6e346487b879b4b056a847268e381ae6efec4c21
-Author: nielsAD <niels.a.d@gmail.com>
-Date: Mon Aug 25 12:23:29 2014 +0200
-
- Fixed THISCALL/FASTCALL closures and added basic support for PASCAL/REGISTER closures.
-
-commit 098dca6b31e42dd0256ed7d966729e31961f1461
-Author: nielsAD <niels.a.d@gmail.com>
-Date: Sat Aug 23 00:18:47 2014 +0200
-
- Support for calling functions with PASCAL and REGISTER calling conventions on x86 Windows/Linux.
- Also changed indentation to be more consistent throughout the (adjusted) files.
-
-commit 08853e32fb6b750cda664ee6d3290d340429dd4d
-Author: Ehsan Akhgari <ehsan@mozilla.com>
-Date: Thu Jul 31 20:33:33 2014 -0400
-
- Enable forcing the usage of the static CRT in libffi's msvc wrapper
-
- This is required for AddressSanitizer builds with clang-cl.
-
-commit aebf2c3023b5ff056a708dc34169f7b549b2ec4f
-Author: Ole André Vadla Ravnås <ole.andre.ravnas@tillitech.com>
-Date: Fri Jul 25 21:40:50 2014 +0200
-
- Fix alignment of FFI_TYPE_FLOAT for Apple's ARM64 ABI
-
-commit 0f4e09d27dc175ce3e95d070b794351663c7220e
-Author: Ole André Vadla Ravnås <ole.andre.ravnas@tillitech.com>
-Date: Sat Jul 26 00:11:06 2014 +0200
-
- Fix non-variadic CIF initialization for Apple/ARM64
-
- Turns out `aarch64_nfixedargs` wasn't initialized in the non-variadic
- case, resulting in undefined behavior when allocating arguments.
-
-commit 6172a995e14bdbc6150aa02a361f710626a5c293
-Author: Jeremie Knuesel <jeremie.knusel@sensefly.com>
-Date: Wed Jun 25 12:28:17 2014 +0200
-
- Fix issue with builddir when calling configure with absolute path
-
-commit fb25cd08ed5a87640b02f0feeb10a09b37cfddbe
-Author: Ehsan Akhgari <ehsan@mozilla.com>
-Date: Wed Jun 11 12:07:24 2014 -0400
-
- Add support for building with clang-cl
-
-commit 1cee07be4712411baa5eb8af22698bc8443a6d6e
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Jun 12 06:30:59 2014 -0400
-
- Remove compiler warning
-
-commit ad0d1d239afc7ad09203847793dcc020856d1035
-Author: Samuli Suominen <ssuominen@gentoo.org>
-Date: Thu Jun 12 06:30:21 2014 -0400
-
- Fix paths in libffi.pc.in
-
-commit df31a85103b0cc232bbc340d7e782a3853c7fad5
-Merge: 69289c1 360aa8c
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Jun 6 08:24:35 2014 -0400
-
- Merge pull request #122 from rvandermeulen/1014976
-
- Don't make --enable-debug imply using the debug CRT in libffi
-
-commit 360aa8ca1ead2fdaefa7b1c6f01ad001d8abae7e
-Author: Mike Hommey <mh+mozilla@glandium.org>
-Date: Mon Jun 2 09:21:10 2014 -0400
-
- Bug 1014976 - Don't make --enable-debug imply using the debug CRT in libffi.
-
-commit 69289c10b0acb4b52c8b5df4cf738193c618db40
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat May 31 08:54:08 2014 -0400
-
- Prepare for libffi 3.1.1
-
-commit 978c9540154d320525488db1b7049277122f736d
-Author: Samuli Suominen <ssuominen@gentoo.org>
-Date: Sat May 31 08:53:10 2014 -0400
-
- Add missing GNU stack markings in win32.S
-
-commit cbc5a3c0200aa6c2cf8d6798d69a21501557c83f
-Author: Ryan Hill <rhill@gentoo.org>
-Date: Sat May 31 08:26:34 2014 -0400
-
- Fix typo
-
-commit 9d8e3018ac3d0d338373bff7eefa9f006746f4ec
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat May 24 23:28:42 2014 -0400
-
- Update current version.
-
-commit 18d56cca5a4ee95ad48b129100adf26231518ed0
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon May 19 18:05:33 2014 -0400
-
- Increment libtool version number
-
-commit 629f1029c47e522e4331988f02f32c203a070e28
-Merge: 0403f33 c1166d4
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon May 19 18:04:28 2014 -0400
-
- Merge pull request #120 from l0kod/tmpfile
-
- Create temporary file with O_TMPFILE and O_CLOEXEC when available
-
-commit c1166d4f653bf6d17ad8c265cf5e8da84e2e76dc
-Author: Mickaël Salaün <mic@digikod.net>
-Date: Mon May 12 19:44:08 2014 +0200
-
- closures: Check for mkostemp(3)
-
-commit 8daeed9570af72eb135c8ded460d2888f05b2e68
-Author: Mickaël Salaün <mic@digikod.net>
-Date: Sun May 11 22:54:58 2014 +0200
-
- closures: Create temporary file with O_TMPFILE and O_CLOEXEC when available
-
- The open_temp_exec_file_dir function can create a temporary file without
- file system accessible link. If the O_TMPFILE flag is not defined (old
- Linux kernel or libc) the behavior is unchanged.
-
- The open_temp_exec_file_name function now need a new argument "flags"
- (like O_CLOEXEC) used for temporary file creation.
-
- The O_TMPFILE flag allow temporary file creation without race condition.
- This feature/fix prevent another process to access the (future)
- executable file from the file system.
-
- The O_CLOEXEC flag automatically close the temporary file for any
- execve. This avoid transmitting (executable) file descriptor to a child
- process.
-
-commit 0403f332b1f478696c30d3d8a0e2f6eef24aaf88
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon May 19 09:41:32 2014 -0400
-
- Update date. Annoucing 3.1 today.
-
-commit 94ac0c168ee7b115409121d88b25a4979446c8da
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon May 19 09:37:21 2014 -0400
-
- Increment libtool library revision number
-
-commit 57465744b6e1295d7202de5a7734df589518f1c8
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun May 11 10:30:22 2014 -0400
-
- Update to version 3.1
-
-commit 0c2251a42df5108b6d9ebe5fe1cf83d0bcdf660e
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun May 11 10:22:30 2014 -0400
-
- Support versions of git older than 1.8.5
-
-commit 70c303cb88e23aaee91c87c56b108c50ab4f3c2f
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun May 11 09:56:40 2014 -0400
-
- Fix testsuite for GCC 4.9.0
-
-commit 52b3457093ed19b2a7c5fcf243c4014c90ce6225
-Author: Magnus Granberg <zorry@gentoo.org>
-Date: Sun May 11 09:55:28 2014 -0400
-
- Check /proc/self/status for PaX status.
-
-commit 7ba4c5d72aa440a4b21fb57e999e67c5957761da
-Author: Dominik Vogt <dominik.vogt@gmx.de>
-Date: Sun May 11 09:52:47 2014 -0400
-
- Use to get correct dir
-
-commit 31e0d4ecff6dc2a6c75a066ee099b52a43f6ba27
-Merge: 1c0e9a7 99909eb
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Apr 23 19:24:47 2014 -0400
-
- Merge pull request #119 from joshtriplett/fastcall-fastball
-
- src/x86/win32.S: Define ffi_closure_FASTCALL in the MASM section, too
-
-commit 99909eb6184b62408d88b6b4e7ab38e84e6d0bf3
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Tue Apr 22 21:17:52 2014 -0700
-
- src/x86/win32.S: Define ffi_closure_FASTCALL in the MASM section, too
-
-commit 1c0e9a7297ced15413c2d2d5d35f6c650c4b46c9
-Merge: 93a24f2 d369522
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Apr 21 12:41:56 2014 -0400
-
- Merge pull request #101 from joshtriplett/fastcall-closures
-
- Support closures for fastcall
-
-commit d36952273d4fafbda91ecc205fc0824f7cc65e70
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Apr 20 12:03:25 2014 -0700
-
- Support fastcall closures
-
- libffi on 32-bit x86 now supports closures for all supported ABIs.
- Thus, rewrite the last remaining duplicated-by-ABI test (closure_stdcall
- and closure_thiscall) to use the generic ABI_NUM/ABI_ATTR mechanism.
-
-commit 93a24f216bcdd1018b976d697179c6d49004015a
-Merge: dd11a04 2349fec
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Apr 12 19:38:07 2014 -0400
-
- Merge pull request #80 from ueno/devel
-
- Fix typo in doc
-
-commit dd11a04061cb49ce1d702545693c24eb1267d648
-Merge: 8fa2812 03ca880
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Apr 12 19:37:21 2014 -0400
-
- Merge pull request #86 from joshtriplett/testsuite-CC-CXX
-
- testsuite ignores CC parameter supplied to configure or make
-
-commit 8fa2812355e685a42abf9a62fbc674d616b2edee
-Merge: 8a58e6b 419503f
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Apr 12 19:32:08 2014 -0400
-
- Merge pull request #116 from frida/fix/darwin-aarch64-variadic
-
- Fix handling of variadic calls on Darwin/AArch64
-
-commit 8a58e6b7805b736def197b8baf8e465a2a3f6913
-Merge: 30b77c5 a539f7f
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Apr 12 19:30:18 2014 -0400
-
- Merge pull request #115 from frida/fix/darwin-aarch64-alignment
-
- Fix alignment of AArch64 assembler functions
-
-commit 30b77c56f95c63ecd83399aafdbad7b07330f2fd
-Merge: dc33cb3 3e2b84d
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Apr 12 19:29:13 2014 -0400
-
- Merge pull request #117 from frida/fix/windows-regression
-
- Fix Windows regression
-
-commit 3e2b84d295531720917bf46afc532fc6d877e3ec
-Author: Ole André Vadla Ravnås <ole.andre.ravnas@tillitech.com>
-Date: Sat Apr 12 01:04:04 2014 +0200
-
- Fix Windows regression
-
- Introduced by b5fed601948237037513a9b7f967c8fc6c9ff1f6.
-
-commit 419503f409c321fe31ff59d963ef34bb913420d0
-Author: Ole André Vadla Ravnås <ole.andre.ravnas@tillitech.com>
-Date: Sun Apr 6 20:54:13 2014 +0200
-
- Fix handling of variadic calls on Darwin/AArch64
-
-commit a539f7ffd6783aa11353d13265520e453c565fb4
-Author: Ole André Vadla Ravnås <ole.andre.ravnas@tillitech.com>
-Date: Sun Apr 6 20:53:02 2014 +0200
-
- Fix alignment of AArch64 assembler functions
-
-commit dc33cb3c998da521a960385c1269c3aef552f69f
-Merge: c860a99 b5fed60
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Apr 5 23:41:22 2014 -0400
-
- Merge pull request #114 from joshtriplett/bounce-on-a-tiny-trampoline
-
- Fix ABI on 32-bit non-Windows x86: go back to trampoline size 10
-
-commit b5fed601948237037513a9b7f967c8fc6c9ff1f6
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sat Apr 5 17:33:42 2014 -0700
-
- Fix ABI on 32-bit non-Windows x86: go back to trampoline size 10
-
- The trampoline size is part of the ABI, so it cannot change. Move the
- logic from the stdcall and thiscall trampolines to the functions they
- call, to reduce them both to 10 bytes.
-
- This drops the previously added support for raw THISCALL closures on
- non-Windows. (Non-raw THISCALL closures still work.)
-
-commit 03ca880081b22efab09ba72268270f83017d3d7b
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Thu Mar 27 08:44:34 2014 -0700
-
- README: Note the testsuite changes to respect $CC and $CXX
-
-commit d74df8c5d8c6722ecb908da98c86cc8e2c755b84
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Thu Mar 27 00:44:12 2014 -0700
-
- README: Update Windows example to set both CC and CXX
-
-commit 7d698125b1f05173f3656a89755a2eb58813b002
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Wed Mar 26 23:17:56 2014 -0700
-
- Use the proper C++ compiler to run C++ tests
-
- Running the C compiler with -shared-libgcc -lstdc++ does not work on
- non-GCC compilers.
-
-commit fa5e88f170cb37c7b2b9bb015c8c5b854ffd8a3e
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Wed Mar 26 23:53:57 2014 -0700
-
- .travis.yml: Make the build command more readable by splitting at &&
-
- "script" can contain multiple commands to run in sequence.
-
-commit 0c3824702d3d59d37f8c177d646303f546187683
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Wed Mar 26 14:51:32 2014 -0700
-
- Always set CC_FOR_TARGET for dejagnu, to make the testsuite respect $CC
-
- This fixes cross-compilation and compilation with CC="gcc -m32".
-
-commit 9946a92af31b30cb7760150d1f8ca6c11b01aeea
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Wed Mar 26 20:18:58 2014 -0700
-
- Stop looking for expect and runtest above top_builddir
-
- Users wishing to test hand-compiled versions of expect and runtest can
- easily enough put them in their path or set EXPECT and RUNTEST
- themselves.
-
-commit acb202325215058639234efb7af1f04c1c8a1f44
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Wed Mar 26 20:18:41 2014 -0700
-
- Stop setting an empty AM_RUNTESTFLAGS
-
-commit c860a992fef5d7cd7bb0975b1632d17a9fafe007
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 25 17:02:51 2014 -0400
-
- Upgrade version to 3.1-rc1
-
-commit 9837073e6203048a162a226798c5d252600219ed
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 25 16:24:14 2014 -0400
-
- Update copyright date and clean up README notes.
-
-commit 18d3baa9f597b026675baa1b4e5a5eeef7577a08
-Merge: afee537 f0c8a31
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 25 16:12:53 2014 -0400
-
- Merge pull request #108 from joshtriplett/freebsd
-
- [3.1 blocker] Fix FreeBSD support
-
-commit afee53738a995e23bd2f89fd0f7b30b380566106
-Merge: 7d24785 b2d610e
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 25 16:12:35 2014 -0400
-
- Merge pull request #106 from joshtriplett/darwin-award
-
- [3.1 blocker] Update OS X build system to include win32.S on 32-bit
-
-commit 7d2478568ed9f03cbf57627f449a2d2cf4d1571c
-Merge: beab5f3 56be47f
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 25 16:12:17 2014 -0400
-
- Merge pull request #110 from joshtriplett/w64
-
- Fix 64-bit Windows support
-
-commit beab5f334d9ec5b8b91d1cc727d1029b40358e7e
-Merge: 28fb197 ef5890e
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 25 16:07:47 2014 -0400
-
- Merge pull request #105 from joshtriplett/win32-relocations
-
- [3.1 blocker] win32.S needs to handle relocations/GOT
-
-commit f0c8a31577172104049283f0a80c723084a5bd77
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Mon Mar 24 22:14:26 2014 -0700
-
- Compile win32.S on FreeBSD
-
-commit b2d610e028b5ce48d1ad7e5d0debc9c321d891b2
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Fri Mar 21 11:10:13 2014 -0700
-
- Compile win32.S on 32-bit Darwin as well
-
-commit be50b87a490e794362cb4a27ada2fbaab202adb8
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Mon Mar 24 21:44:13 2014 -0700
-
- Always use configure to detect whether global symbols need underscores
-
- 64-bit Windows already used this check; make it universal, and use it in
- place of an ifdef on X86_WIN32, to handle non-Windows platforms that use
- the underscore, such as Darwin.
-
-commit 56be47f87629e31afbcb0774aa65735f539ee972
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Mon Mar 24 21:24:53 2014 -0700
-
- Fix a warning on 64-bit Windows
-
- When sizeof(size_t) != sizeof(unsigned), adding a size_t to cif->bytes
- produces a "possible loss of data" warning. However, the size_t in
- question refers to the size of a single parameter. Use a cast to avoid
- the warning.
-
-commit 48a8eda74aad8a21b6f26df5df08fe64c043d208
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Mon Mar 24 21:21:12 2014 -0700
-
- Avoid referencing undefined ABIs on 64-bit Windows builds
-
- 64-bit Windows does not have FFI_STDCALL, FFI_THISCALL, or FFI_FASTCALL.
-
-commit f0f4138f90345d7d67dfa6783a7e1c7cc30d3c6f
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sat Mar 22 10:00:53 2014 -0700
-
- win32.S: Add handling for position-independent code on Darwin
-
- Newer versions of Darwin generate the necessary stub functions
- automatically and just need a call instruction, but accomodating older
- versions as well requires adding the stub.
-
-commit ef5890ebafb7cd2fbf9acf161edb55fe1382871c
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Fri Mar 21 11:01:39 2014 -0700
-
- win32.S: Use shifting for multiplication rather than repeated addition
-
- The jump table code added a register to itself twice to multiply by 4;
- shift the register left by 2 instead.
-
-commit 4fca48901e7e4f53bf490ed22607b2d2d8f4bfcc
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Fri Mar 21 11:00:41 2014 -0700
-
- win32.S: Make the jump tables position-independent
-
- Now that non-Windows platforms include win32.S, it needs to support
- building as position-independent code. This fixes build failures on
- target platforms that do not allow text relocations.
-
-commit 2087dcf736274286f76c69d3988fb6d7cc4fd0f5
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Fri Mar 21 10:57:06 2014 -0700
-
- win32.S: Make calls to ffi_closure_SYSV_inner position-independent
-
- Now that non-Windows platforms include win32.S, it needs to support
- building as position-independent code. This fixes one source of build
- failures on target platforms that do not allow text relocations.
-
-commit 28fb197079cf1d11da4eef7c8c243ab05590c528
-Merge: c697472 c3dd0a1
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Mar 18 12:19:36 2014 -0400
-
- Merge pull request #107 from rvandermeulen/msvcc
-
- Various compatibility fixes and improvements to msvcc.sh.
-
-commit c3dd0a1a0245fc174361a70876e88ae24285f861
-Author: Ryan VanderMeulen <ryanvm@gmail.com>
-Date: Tue Mar 18 12:09:45 2014 -0400
-
- Various compatibility fixes and improvements to msvcc.sh.
-
- * Don't try to mix incompatible optimization flags in debug builds.
- * Workaround ax_cc_maxopt.m4 not supporting MSVC and change -O3 to -O2.
- * Fix MSVC warning by properly passing linker flags to compiler.
- * Make msvcc.sh return 1 if invalid command line options are used rather than silently eating them.
- * Add more comments.
-
-commit c697472fccfbb5b87b007c053cda9ef014b346b9
-Merge: 83fd2bc e48918e
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Mar 17 00:32:42 2014 -0400
-
- Merge pull request #102 from joshtriplett/test-generic
-
- Add ABIs to the test matrix; unify many bits of the testsuite
-
-commit e48918ecf876bc85d040fc50a232059c566553a8
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 20:29:27 2014 -0700
-
- testsuite: Add ABIs to the test matrix; unify tests across ABIs
-
- This eliminates all the *_win32.c tests in favor of the tests they were
- branched from, and expands test coverage to run many more tests on
- stdcall, thiscall, and fastcall.
-
- This same mechanism also supports testing any other target that has
- multiple ABIs.
-
-commit 4d4d368e5a55d9443c4c53b1b70d58ab6d8c941c
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 17:02:05 2014 -0700
-
- testsuite: Replace ffitestcxx.h with ffitest.h
-
- ffitest.h contains a superset of the functionality of ffitestcxx.h;
- make the C++ tests include ffitest.h instead, and remove ffitestcxx.h.
-
-commit 3f97cf3413c46caf2a79f32ac9cda4620972c2d7
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 16:53:42 2014 -0700
-
- testsuite: Unify the C and C++ testsuites
-
- These two testsuites differ only in the source file glob and a couple of
- additional compiler options; unify the remaining bits.
-
-commit 0d9cce8edb937bbe771a6cdd25f671edf06d2128
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 16:22:58 2014 -0700
-
- testsuite: ffitest.h: Parenthesize the CHECK macro
-
-commit 5695ec1444c5323e48fe4314f8c8f027625e67df
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 16:04:58 2014 -0700
-
- testsuite: Factor out a function to run a matrix of tests
-
- This commons up code from libffi.call/call.exp and
- libffi.special/special.exp, unifies the optimization option matrix
- between the two, and makes it easier to add more axes to the matrix
- in the future.
-
-commit dfdb02cc869855d3b68571e5f7aa77ae8c9d254a
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 15:26:26 2014 -0700
-
- testsuite: Introduce a __THISCALL__ compiler-specific macro
-
-commit 83fd2bce0456224483435d4b764063f4513fd464
-Merge: 3658a07 06ff924
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 22:03:29 2014 -0400
-
- Merge pull request #99 from joshtriplett/gitignore
-
- .gitignore: Ignore more generated files
-
-commit 3658a0700a50d37a2fdba04fd9d79ad2f706d9f5
-Merge: d948d0a 46c5d3c
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 21:37:42 2014 -0400
-
- Merge pull request #100 from rvandermeulen/bug-756740
-
- Change double quotes in Makefile.am to single quotes.
-
-commit 46c5d3c30fdc2b43c076ad955078d7c5f1e75b37
-Author: Ryan VanderMeulen <ryanvm@gmail.com>
-Date: Sun Mar 16 21:16:08 2014 -0400
-
- Change double quotes in Makefile.am to single quotes.
-
- This was originally done in PR #84, except the change was made to Makefile.in instead of Makefile.am and was therefore reverted the next time the files were regenerated.
-
-commit 06ff924215a2f9739efa2c059dc595bc4ec1c851
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 16:19:46 2014 -0700
-
- .gitignore: Ignore more generated files
-
- The build process generates doc/libffi.info and fficonfig.h.in, so add
- them to .gitignore.
-
-commit bad8948346e9b8813023a0cc78a3b6eb8d9c14c6
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 15:16:18 2014 -0700
-
- testsuite: Introduce a __STDCALL__ compiler-specific macro
-
- Several tests want to use stdcall, which differs in syntax by compiler,
- so introduce a macro for it in ffitest.h.
-
-commit 98a793fa36a4ab3ba24d059cb80a2891cdb940e1
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 15:20:36 2014 -0700
-
- testsuite: Common up the ifdef blocks for compiler-specific macros
-
-commit d948d0a729c934b0224749338a3ba0a2c8f51c45
-Merge: b61b472 a86bd31
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 10:53:48 2014 -0400
-
- Merge pull request #98 from joshtriplett/unconfigure.host
-
- Merge configure.host into configure.ac
-
-commit a86bd318e2424d879d784ee7b29d6536d7a17c18
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 06:58:59 2014 -0700
-
- Merge configure.host into configure.ac
-
- configure.host only has a single entry, and shows no signs of needing
- more added.
-
-commit b61b472bd0647006d6685238721002017f1d119c
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 09:45:55 2014 -0400
-
- Update version to 3.1-rc0. Clean up README.
-
-commit 7a64e7dbba54e6e9f69954adfb943be1856ff928
-Merge: 11a5c5c eef2e02
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 09:39:08 2014 -0400
-
- Merge pull request #97 from joshtriplett/remove-more-generated-files
-
- Remove more generated files
-
-commit 11a5c5c39f5861011f6c5ddf795da3a32b5f0082
-Merge: 9a62a21 1c68c07
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 09:38:47 2014 -0400
-
- Merge pull request #96 from joshtriplett/sawing-changelogs
-
- Generate ChangeLog from git in make dist; remove it from version control
-
-commit eef2e02a13d7d1c8145d47a64467f654406a3548
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 06:26:03 2014 -0700
-
- doc: Remove autogenerated info file and stamp
-
-commit 9fb403d3c5d9643e0f561cab6d4a07b1e54907ff
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 06:25:52 2014 -0700
-
- fficonfig.h.in: Remove, configure generates it
-
-commit 1c68c07217fda78a779778c1480fedef7a58d5b4
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 06:11:58 2014 -0700
-
- Generate ChangeLog from git in make dist
-
- Archive the existing ChangeLog to ChangeLog.libffi-3.1
-
-commit c65ed55e655711e008282edbdd82ce95d008b4f6
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 05:52:00 2014 -0700
-
- ChangeLog.v1: Fix typo in explanatory header.
-
-commit 9a62a21f5c3a8e1da463229f3170c8ab3031d920
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 09:03:57 2014 -0400
-
- Add missing ChangeLog entry. Clean up some entries.
-
-commit 9bc704c58cb7a049d867837e3a11e2e31886ec66
-Merge: 694447a e892e58
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 08:41:00 2014 -0400
-
- Merge pull request #95 from joshtriplett/news
-
- README: Update news for 3.0.14
-
-commit e892e581d1838a06c18c7ecd50ebd79915cff92b
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 05:38:24 2014 -0700
-
- README: Update news for 3.0.14
-
-commit 694447aa29deadd571efb4e9a26ee3f68ede1493
-Merge: fdc87f3 45a6c21
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 08:32:05 2014 -0400
-
- Merge pull request #93 from joshtriplett/travis-dist
-
- Make Travis check "make dist"
-
-commit 45a6c21efa944b520842e631dc54919b04884744
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 05:29:08 2014 -0700
-
- .travis.yml: Test "make dist" too.
-
-commit fdc87f3b2ea37b58a4a9ae6c35083f544909fe3c
-Merge: 7412b83 e1911f7
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 08:05:51 2014 -0400
-
- Merge pull request #85 from joshtriplett/stdcall
-
- stdcall support on Linux
-
-commit e1911f78df113ca58738b66089a070d4cf747de7
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 03:25:53 2014 -0700
-
- Add support for stdcall, thiscall, and fastcall on non-Windows x86-32
-
- Linux supports the stdcall calling convention, either via functions
- explicitly declared with the stdcall attribute, or via code compiled
- with -mrtd which effectively makes stdcall the default.
-
- This introduces FFI_STDCALL, FFI_THISCALL, and FFI_FASTCALL on
- non-Windows x86-32 platforms, as non-default calling conventions.
-
-commit 7412b838d543aae4fa925862bd5702d3dacbc29a
-Merge: c0cc5fd 9531d05
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 07:58:16 2014 -0400
-
- Merge pull request #90 from joshtriplett/win32-unifdef
-
- prep_cif.c: Remove unnecessary ifdef for X86_WIN32
-
-commit c0cc5fdaa237b67e86f22d2f6e13f3b42d9aae33
-Merge: 98b5296 b3a5da0
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 07:57:59 2014 -0400
-
- Merge pull request #89 from joshtriplett/travis32
-
- .travis.yml: Test on both 32-bit and 64-bit
-
-commit 9531d05f64c2a674e0197158ffad68d69f177bd0
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 01:50:02 2014 -0700
-
- prep_cif.c: Remove unnecessary ifdef for X86_WIN32
-
- ffi_prep_cif_core had a special case for X86_WIN32, checking for
- FFI_THISCALL in addition to the FFI_FIRST_ABI-to-FFI_LAST_ABI range
- before returning FFI_BAD_ABI. However, on X86_WIN32, FFI_THISCALL
- already falls in that range, making the special case unnecessary.
- Remove it.
-
-commit b3a5da068abd2f2983d9e67adbf41b0e0f34e37f
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sat Mar 15 23:27:56 2014 -0700
-
- .travis.yml: Test on both 32-bit and 64-bit
-
-commit 98b52960485a261399f081915f36063de3854a5f
-Merge: 134ce4c f6dd184
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 07:51:33 2014 -0400
-
- Merge pull request #94 from joshtriplett/esp-extra-stackery-perception
-
- ChangeLog: Document testsuite changes to remove fragile stack pointer checks
-
-commit f6dd1845434dd53e22129becdfa092c082df307c
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 04:49:36 2014 -0700
-
- ChangeLog: Document testsuite changes to remove fragile stack pointer checks
-
-commit 134ce4c0266bf994f07518fc534de53f1d3c8de8
-Merge: 2680e9e 9c27932
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 07:47:17 2014 -0400
-
- Merge pull request #91 from joshtriplett/esp-extra-stackery-perception
-
- testsuite: Remove fragile stack pointer checks
-
-commit 9c279328ee12fc869adff63ca81f1230977bd42b
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 02:31:19 2014 -0700
-
- testsuite: Remove fragile stack pointer checks
-
- testsuite/libffi.call/closure_stdcall.c and
- testsuite/libffi.call/closure_thiscall.c include inline assembly to save
- the stack pointer before and after the call, and compare the values.
- However, compilers can and do leave the stack in different states for
- these two pieces of inline assembly, such as by saving a temporary value
- on the stack across the call; observed with gcc -Os, and verified as
- spurious through careful inspection of disassembly.
-
-commit 2680e9ea9b4c87ea8042a61e551bd667493d4bd3
-Merge: 071eab3 82f8cb2
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 07:44:08 2014 -0400
-
- Merge pull request #88 from joshtriplett/such-precision-many-fail-wow
-
- testsuite/libffi.call/many.c: Avoid spurious failure due to excess precision
-
-commit 82f8cb24a1d976db35ae31a4b86cec8926da327d
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 04:27:32 2014 -0700
-
- ChangeLog: Document many.c and many_win32.c changes to avoid spurious failures
-
-commit 88d562a8b5912e99306063fe3bc289bab6ca6ebe
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sat Mar 15 22:08:19 2014 -0700
-
- testsuite/libffi.call/many_win32.c: Avoid spurious failure due to excess precision
-
- The test case testsuite/libffi.call/many_win32.c can spuriously fail due
- to excess floating-point precision. Instrumenting it with some printf
- calls shows differences well above FLT_EPSILON. (Note when
- instrumenting it that multiple computations of the difference, such as
- one in a print and another in the conditional, may produce different
- results.)
-
- Rather than complicating the test suite with architecture-specific flags
- to avoid excess precision, just simplify the floating-point computation
- to avoid a dependency on potential excess precision.
-
-commit c00a49ecd165b2d06c1c9b249d212dc843fa116f
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sat Mar 15 22:08:19 2014 -0700
-
- testsuite/libffi.call/many.c: Avoid spurious failure due to excess precision
-
- The test case testsuite/libffi.call/many.c can spuriously fail due to
- excess floating-point precision. Instrumenting it with some printf
- calls shows differences well above FLT_EPSILON. (Note when
- instrumenting it that multiple computations of the difference, such as
- one in a print and another in the conditional, may produce different
- results.)
-
- Rather than complicating the test suite with architecture-specific flags
- to avoid excess precision, just simplify the floating-point computation
- to avoid a dependency on potential excess precision.
-
-commit 071eab32a7f9fbbef46c0d8f37d9985bc9cceb37
-Merge: 2228c7a 2f44952
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 07:36:52 2014 -0400
-
- Merge pull request #92 from joshtriplett/autogen
-
- Re-add libtool-ldflags
-
-commit 2f44952c95765c1486fad66f57235f8d459a9748
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sun Mar 16 04:35:12 2014 -0700
-
- Re-add libtool-ldflags
-
-commit 2228c7ab190f3c529b9018495467b841fa21cba2
-Merge: 76d19d0 35634db
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 16 07:25:18 2014 -0400
-
- Merge pull request #87 from joshtriplett/autogen
-
- Remove autogenerated files from the repository
-
-commit 35634dbceaac0a1544f7385addc01d21ef1ef6a8
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Sat Mar 15 18:11:16 2014 -0700
-
- Remove autogenerated files from the repository
-
- Add an autogen.sh to regenerate them.
-
-commit 76d19d004e36e99d261ee78261e2f52cea5e4ab1
-Merge: c86d9b6 a1a6f71
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Mar 14 16:54:31 2014 -0400
-
- Ensure the linker supports @unwind sections in libffi.
-
-commit c86d9b6cc6e16ee262844a33b40441374400758c
-Merge: 4efb7db f8cdf11
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Mar 14 16:51:20 2014 -0400
-
- Fix merge
-
-commit 4efb7dbfd9427c478a948cd0d464210123db8de8
-Merge: 634a475 18eb81d
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Mar 14 16:47:57 2014 -0400
-
- Merge pull request #81 from rvandermeulen/bug-756740
-
- Allow building for mipsel with Android NDK r8.
-
-commit a1a6f71bfe4199293043b2e4cfb4c8d3cb1112f9
-Author: Ryan VanderMeulen <ryanvm@gmail.com>
-Date: Mon Mar 10 15:12:47 2014 -0400
-
- Remove stray hunk that shouldn't have been included in this patch.
-
-commit f8cdf11467181f2a9a6b7e748167569aa58e3a81
-Author: Ryan VanderMeulen <ryanvm@gmail.com>
-Date: Mon Mar 10 15:04:58 2014 -0400
-
- Replace double quotes with single quotes in Makefile.in to improve compatibility between some versions of MSYS and gmake. From Mozilla bug 943728.
- https://bugzilla.mozilla.org/show_bug.cgi?id=943728
-
-commit dfa3738732e1bc3a7f4130395ae4bab55fcebb99
-Author: Ryan VanderMeulen <ryanvm@gmail.com>
-Date: Mon Mar 10 14:53:48 2014 -0400
-
- Ensure the linker supports @unwind sections in libffi. From Mozilla bug 756740.
- https://bugzilla.mozilla.org/show_bug.cgi?id=778414
-
- Also tracked as issue #42.
- https://github.com/atgreen/libffi/issues/42
-
-commit 18eb81d032f29d645d0498ba92bddfd651f009ae
-Author: Ryan VanderMeulen <ryanvm@gmail.com>
-Date: Mon Mar 10 14:43:37 2014 -0400
-
- Allow building for mipsel with Android NDK r8. From Mozilla bug 756740.
- https://bugzilla.mozilla.org/show_bug.cgi?id=756740
-
-commit 2349fec9a818fb52fd2f294bcbc7b3156cd113de
-Author: Daiki Ueno <ueno@gnu.org>
-Date: Wed Mar 5 17:53:02 2014 +0900
-
- Fix typo in doc
-
-commit 634a475eaf1bee31c09f7d519e31c13b64cd24df
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 1 18:37:29 2014 -0500
-
- Update Makefile for new darwin scripts
-
-commit c7b67e874bb89859f9a07d1cf9606052b6c0dcc1
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 1 18:34:18 2014 -0500
-
- Add README note
-
-commit a04e30ba3dc303133d459c1ac273ceefe4d49b32
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 17:20:59 2014 -0500
-
- Add missing -DFFI_DEBUG flag
-
-commit 934dc1b5c8d6a9e727bedc72342831eb7d62c35f
-Merge: 11d7aa9 67fbef3
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 01:10:17 2014 -0500
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
-commit 11d7aa9d7a4bbe642944edc0f07cf96db9b270b6
-Merge: b40aeda 3b44d41
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 01:06:48 2014 -0500
-
- Merge pull request #46 from makotokato/android-clang
-
- Fix build failure when using clang for Android
-
-commit 67fbef3b56ff0ef88f9b1a7fe48cb77222fa6cec
-Merge: b40aeda 3b44d41
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 01:06:48 2014 -0500
-
- Merge pull request #46 from makotokato/android-clang
-
- Fix build failure when using clang for Android
-
-commit b40aeda31a74d95a37c723b6243aabac466e67c4
-Merge: 20698ab 53ceaf1
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 01:01:29 2014 -0500
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
-commit 53ceaf14c5eeb16ba09745f0ca87cca367d41a90
-Merge: 860fe66 cc9b518
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 01:01:02 2014 -0500
-
- Merge pull request #40 from wojdyr/master
-
- Correct the -L flag in libffi.pc.in
-
-commit 20698abc6a00092fd7fd3e434a3a29dc0f048f1e
-Merge: 64bd069 1a0b01e
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 00:56:27 2014 -0500
-
- Merge pull request #66 from ppizarro/master
-
- BlackFin fixes - Fatal error when calling a function defined in a shared library from within the function called by FFI
-
-commit 860fe6646f5ae603e99a8d1d722ddddba8b75769
-Merge: 64bd069 1a0b01e
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 00:56:27 2014 -0500
-
- Merge pull request #66 from ppizarro/master
-
- BlackFin fixes - Fatal error when calling a function defined in a shared library from within the function called by FFI
-
-commit 64bd06990a7accf72271516a2110b86cdccd8df4
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 00:52:56 2014 -0500
-
- Add ChangeLog entry for Josh's change
-
-commit edf29c5169b06fcfc241445e152e325bc3c50e0e
-Merge: 33c9954 3998d26
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 00:50:25 2014 -0500
-
- Merge pull request #75 from joshtriplett/longdouble
-
- Fix build error on x86 without distinct long double
-
-commit 33c9954f2eec539011a0f93270aaf013318837ae
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 00:38:41 2014 -0500
-
- Rebuilt with new libtool
-
-commit 926b6989fbd08488b9105943293353d45ac527e0
-Merge: 5a88c85 cc82051
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 00:26:57 2014 -0500
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
- Conflicts:
- ChangeLog
-
-commit 5a88c85fde304052bed1581ed0b6452ac2c68838
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 00:23:04 2014 -0500
-
- Fix spelling errors
-
-commit cc82051c7e80cea772c4b72da026eb7e68d598fc
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 00:23:04 2014 -0500
-
- Fix spelling errors
-
-commit 001aaf4b1b56349596bb6f6b5c1613dcbbd84ea8
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 00:20:17 2014 -0500
-
- When no VFP arguments are present the IP register is used
- uninitialized. Initialize it to the value of FP.
-
- This fixes a number of testsuite failures when configured for
- armv7l-unknown-linux-gnueabihf
-
-commit 49f7729c3ce697c12408c42ccb29cdf4eb66bb85
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 28 00:17:16 2014 -0500
-
- aarch64 fix
-
-commit 447483d51c6aa9df7116f346a73fc1cf795f4c2b
-Merge: 51377bd b4df9cf
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Feb 27 15:42:41 2014 -0500
-
- Fix ChangeLog merge
-
-commit 3998d2604b5c0d45a098ff3119a9fd9710ef429d
-Author: Josh Triplett <josh@joshtriplett.org>
-Date: Mon Feb 17 11:20:33 2014 -0800
-
- Fix build error on x86 without distinct long double
-
- src/x86/ffi64.c: In function 'classify_argument':
- src/x86/ffi64.c:205:5: error: duplicate case value
- case FFI_TYPE_LONGDOUBLE:
- ^
- src/x86/ffi64.c:202:5: error: previously used here
- case FFI_TYPE_DOUBLE:
- ^
-
-commit 51377bda9aed0b2c1309c818460cab9d9ab3d46e
-Merge: f08da54 40927bd
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 15 08:06:29 2014 -0500
-
- Merge pull request #72 from heiher/devel
-
- MIPS N32: Fix call floating point va function
-
-commit f08da5465463e60a28f5e921f23ebf2ba984c148
-Merge: 3dc3f32 fa5f25c
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 15 08:06:11 2014 -0500
-
- Merge pull request #68 from zeldin/master
-
- Linux/ppc64: Remove assumption on contents of r11 in closure
-
-commit 40927bd3e1e7c6007025ba10854fd8a0664e47df
-Author: Heiher <r@hev.cc>
-Date: Tue Jan 21 23:18:27 2014 +0800
-
- Fix call floating point va function
-
- I'm not sure floating-point arguments in GPR or FPR before calling
- variable number arguments function. so, load all arguments to GPR and
- FPR.
-
-commit b4df9cf9cc4a9a9401a53fd6bea1f3c2c283b97b
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Wed Feb 5 14:22:52 2014 -0500
-
- AArch64: Fix void fall-through case when assertions are enabled
-
-commit f466aad0d91a117e42571d1d6fb434fa0433c930
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Tue Jan 21 16:38:31 2014 -0500
-
- AArch64: Fix missing semicolons when assertions are enabled
-
-commit 7ea677733bd98917241852b8901a6b7580728895
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 30 20:58:31 2013 -0500
-
- Remove build-ios from Makefile
-
- Conflicts:
- ChangeLog
-
-commit 6ae046cc59c12b2cd40158d6bcb96f4a59886159
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 30 21:06:51 2013 -0500
-
- Mention Aarch64 on iOS
-
-commit bfc06b3fdb32abe90ce0749aedfec649df85a7ef
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Mon Dec 30 17:36:39 2013 -0500
-
- Update ChangeLog
-
-commit 0a0f12ce1f7be81006b08a3c81a636926d283a9b
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Thu Jan 9 13:50:17 2014 -0500
-
- AArch64: Remove duplicitous element_count call.
-
- This inhibits an analyzer warning by Clang.
-
-commit 4330fdcd92e67c816288d64ab230237065768206
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Thu Jan 9 13:53:30 2014 -0500
-
- Darwin/aarch64: Respect iOS ABI re: stack argument alignment
-
-commit 0a333d6c3973935d4fe02aae76b10e39d3c88e07
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Thu Jan 9 14:03:29 2014 -0500
-
- Darwin/aarch64: Fix size_t assumptions
-
-commit 2c18e3c76aad1b426617db05a4384e7c3a920176
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Mon Dec 30 16:14:02 2013 -0500
-
- Darwin/aarch64: Fix "shadows declaration" warnings
-
-commit 1b8a8e20e344f3c55495ab6eb46bd14e843d4b3e
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Thu Jan 9 13:55:21 2014 -0500
-
- Darwin/aarch64: Use Clang cache invalidation builtin
-
-commit 6030cdcae776f8fb5876a53168f7d1e75d28a242
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Mon Dec 30 15:45:51 2013 -0500
-
- Darwin/aarch64: Account for long double being equal to double
-
-commit 5658b0892683d2e24e4d5842978c184a7ad33858
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Mon Dec 30 16:33:47 2013 -0500
-
- Darwin/aarch64: Use CNAME, restrict .size like ARM
-
-commit 07175780802acec5dc49fdedd6d20a62409a6707
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Mon Dec 30 17:48:22 2013 -0500
-
- Darwin/aarch64: Fix invalid reference in assembly
-
-commit 9da28b44277fea3aeb827c35dd63d609d2524a8b
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Mon Dec 30 16:23:21 2013 -0500
-
- Darwin/x86_64: Fix 64-bit type shortening warnings
-
-commit 821d398f08bd1d540a5b235507812ffeee49b580
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Thu Jan 9 13:15:06 2014 -0500
-
- Darwin: Merge build scripts, redo project, incl. arm64
-
-commit 6eff9ff9e72463b9783be2514f944b6f05692054
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Mon Dec 30 17:48:10 2013 -0500
-
- Darwin/iOS: Improve unified syntax use for LLVM
-
-commit ba0ea99c82aadd5957386a031e3122011bd36d52
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Mon Dec 30 15:27:44 2013 -0500
-
- Fix dlmalloc warnings due to set_segment_flags, sizeof(size_t)
-
-commit 994be3a5c1d0d17b19103396103e128517fd62f9
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Mon Dec 30 15:27:14 2013 -0500
-
- Darwin/iOS: Fix mis-typing of vfp_reg_free
-
-commit a8e0a835ab1f62d03ad6391760e3e8b7732d24f8
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Mon Dec 30 15:26:20 2013 -0500
-
- Darwin/ARM: Assert on NULL dereference
-
- This inhibits an analyzer warning by Clang on all platforms.
-
-commit 13675341581c489ed9df8ba390c8e08a732decb2
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Thu Jan 9 13:42:08 2014 -0500
-
- Darwin/i386: Inhibit Clang previous prototype warnings
-
-commit 66469c381e2e2cc96e7d409266dea0ffe177eeca
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Thu Jan 9 13:41:45 2014 -0500
-
- Darwin/ARM: Inhibit Clang previous prototype warnings
-
-commit 5bfe62a00d2d659eec9f19b39802b6e69844fc27
-Author: Zachary Waldowski <zach@waldowski.me>
-Date: Thu Jan 9 13:41:27 2014 -0500
-
- Darwin/AArch64: Inhibit Clang previous prototype warnings
-
-commit fa5f25c20f76a6ef5e950a7ccbce826672c8a620
-Author: Marcus Comstedt <marcus@mc.pp.se>
-Date: Sat Jan 4 19:00:08 2014 +0100
-
- Linux/ppc64: Remove assumption on contents of r11 in closure
-
-commit 1a0b01e171e9c750437cef2f18917f5a6e32c498
-Author: Paulo Pizarro <paulo.pizarro@gmail.com>
-Date: Thu Jan 2 16:17:59 2014 -0200
-
- When the function called by the ffi called a function defined in a shared library generate a fatal error
- The correction was to take into consideration the GOT.
-
-commit 3dc3f32c35db5ab995a835225f6815369735ceb7
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Dec 5 16:23:25 2013 -0500
-
- Undo iOS ARM64 changes.
-
-commit 356b2cbc304bfe5bdc28b8d1c68d1ff084e9ec37
-Merge: 484a758 07345a3
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 30 22:38:13 2013 -0500
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
-commit 484a7584260e2fbb399ce90083046834271bf9ff
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 30 21:06:51 2013 -0500
-
- Mention Aarch64 on iOS
-
-commit 07345a30ec0a2fa45a7c363d301f57723690cfa0
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 30 21:06:51 2013 -0500
-
- Mention Aarch64 on iOS
-
-commit d4b931c1b872378c35f12ddbb9a6d55e7f17c65e
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 30 20:58:31 2013 -0500
-
- Remove build-ios from Makefile
-
-commit dfbf236d70fc1ec68e6ff193584a154353508e2f
-Merge: 852ac3b bb9740e
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 30 20:54:54 2013 -0500
-
- Merge branch 'master' of github.com:/atgreen/libffi
- Add ChangeLog entry.
-
-commit bb9740e545205f93a525c77aa6d1cbf4ca9371f3
-Merge: ac75368 4d701e0
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 30 17:54:39 2013 -0800
-
- Merge pull request #60 from zwaldowski/ios-redo
-
- Mac/iOS support, including aarch64 port
-
-commit 4d701e03faa475a5eb3b54b90046114a1e27b813
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 13:25:27 2013 -0500
-
- Darwin: Properly export headers from Xcode project
-
-commit 022f12eb9ad2264e838fa5fb453733f5177888f4
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 12:21:38 2013 -0500
-
- Darwin: Freshen gen scripts, remove old build-ios.sh
-
-commit e820fe2025d7ad3df7584407946dfaad2af69599
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 12:03:51 2013 -0500
-
- Darwin/iOS: Include x86_64+aarch64 pieces in library
-
-commit 0278284e470ec91db7cdc15ac3dcd64683305848
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 03:03:37 2013 -0500
-
- Darwin/aarch64: size_t assumptions
-
-commit 9775446b6441c91cd9059215c106aa3bcf949767
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 02:39:34 2013 -0500
-
- Darwin/aarch64: Fix “shadows declaration” warnings
-
-commit 4260badc37705d3618e774dfe61184ac709881c1
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 02:08:14 2013 -0500
-
- Darwin/aarch64: Use Clang cache invalidation builtin
-
-commit 9fa7998d5f9250908cbf12a671479852ebadf9d1
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 02:07:48 2013 -0500
-
- Darwin/aarch64: Inhibit Xcode warning
-
-commit 0e832048a93830575b0976406444e134e649a4f7
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 02:07:34 2013 -0500
-
- Darwin/aarch64: double == long double
-
-commit 602dc22d76931092610234cf063f9f1b8dbc1a51
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 02:06:00 2013 -0500
-
- Darwin/iOS prep script: try and compile for arm64
-
-commit b513dfe79de4725e8a717325a9e3b5b9f69f63dc
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 02:05:22 2013 -0500
-
- Darwin/aarch64: Restrict .size to ELF like arm32.
-
-commit bc978099bf2812de755c076b67ef9c2547607572
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 02:04:57 2013 -0500
-
- Darwin/aarch64: Potentially(?) fix compile error
-
-commit d6bb9314467c6e0683156559d23ca341c43fa3c8
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 02:04:22 2013 -0500
-
- Darwin/aarch64: Use CNAME refs
-
-commit 33c46ce5680eea28d3437c8771ec1d137e226b45
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 04:13:42 2013 -0500
-
- Darwin/Mac: Fix 64/32 shortening warnings
-
-commit 0612081e6c161d9d820742f995975d35da2adbc2
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 03:03:00 2013 -0500
-
- Darwin: Misc size_t warnings
-
-commit 6a6247d179ec3859311c2d8775841b884f309f66
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 02:55:48 2013 -0500
-
- Darwin: Fix dlmalloc warnings due to sizeof(size_t)
-
-commit 4d60d9e1e32de6166ffd63bbe9ce54cf961c78fc
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 04:09:30 2013 -0500
-
- Darwin: Rebuild Xcode project
-
-commit cb719a5c1c2eb391d6a5f5e02484ba4aa990a51b
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 04:09:18 2013 -0500
-
- Darwin/iOS: Fix LLVM 3.3 warning re: memcpy.
-
-commit 21bde92c9abb378f9c456a9d95e6f9b99ef8c920
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 03:43:42 2013 -0500
-
- Darwin: Clean up, modernize generator scripts
-
-commit fd54eab74cef7891e4acaaafb71e783142ecb69e
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Sat Nov 30 03:38:02 2013 -0500
-
- Darwin/Mac: Also exclude OS X generated source
-
-commit 953b6f14c655141f9e7d82550a312c3eeb961091
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Tue Apr 24 11:16:20 2012 -0400
-
- Darwin/iOS: More unified syntax support w/ Clang.
-
- Signed-off-by: Zachary Waldowski <zwaldowski@gmail.com>
-
-commit c713a55379481c339877f2e0003d97cb8d9ed80e
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Tue Apr 24 10:25:29 2012 -0400
-
- Darwin/iOS: Simplify RETLDM arguments for LLVM 3.1
-
- Signed-off-by: Zachary Waldowski <zwaldowski@gmail.com>
-
-commit 16ba1b80028db5cb71cf86e5f79f5e48317f83c8
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Wed Apr 11 23:26:04 2012 -0400
-
- Darwin: Silence Clang warnings.
-
-commit 852ac3bd302d6ed97b1ef65f4cbed69c258a48df
-Merge: ab79d6e ac75368
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 21 21:25:44 2013 -0500
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
- Conflicts:
- ChangeLog
-
-commit ab79d6e21992dd86139ba07530ff888833b78a04
-Author: Alan Modra <amodra@gmail.com>
-Date: Thu Nov 21 06:12:35 2013 -0500
-
- This separates the 32-bit sysv/linux/bsd code from the 64-bit linux
- code, and makes it possible to link code compiled with different
- options to those used to compile libffi. For example, a
- -mlong-double-128 libffi can be used with -mlong-double-64 code.
-
- Using the return value area as a place to pass parameters wasn't such
- a good idea, causing a failure of cls_ulonglong.c. I didn't see this
- when running the mainline gcc libffi testsuite because that version of
- the test is inferior to the upstreamm libffi test.
-
- Using NUM_FPR_ARG_REGISTERS rather than NUM_FPR_ARG_REGISTERS64 meant
- that a parameter save area could be allocated before it was strictly
- necessary. Wrong but harmless. Found when splitting apart ffi.c
- into 32-bit and 64-bit support.
-
-commit ac7536889334d4be50709006d7e23536364d7891
-Author: Alan Modra <amodra@gmail.com>
-Date: Thu Nov 21 06:12:35 2013 -0500
-
- This separates the 32-bit sysv/linux/bsd code from the 64-bit linux
- code, and makes it possible to link code compiled with different
- options to those used to compile libffi. For example, a
- -mlong-double-128 libffi can be used with -mlong-double-64 code.
-
- Using the return value area as a place to pass parameters wasn't such
- a good idea, causing a failure of cls_ulonglong.c. I didn't see this
- when running the mainline gcc libffi testsuite because that version of
- the test is inferior to the upstreamm libffi test.
-
- Using NUM_FPR_ARG_REGISTERS rather than NUM_FPR_ARG_REGISTERS64 meant
- that a parameter save area could be allocated before it was strictly
- necessary. Wrong but harmless. Found when splitting apart ffi.c
- into 32-bit and 64-bit support.
-
-commit 69df91cfb4fa6bcb644350a80bff970f27478a6a
-Merge: 2f45082 aa1f62c
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 06:34:04 2013 -0800
-
- Merge pull request #59 from iains/powerpc-darwin-unwind-fix
-
- Fix PowerPC Darwin FDE encodings to use pcrel correctly. Modernise the picbase labels.
-
-commit aa1f62c0a093c30325dff1d4d2b6b4b22eb96929
-Author: Iain Sandoe <iain@codesourcery.com>
-Date: Mon Nov 18 13:11:56 2013 +0000
-
- Fix PowerPC Darwin FDE encodings to use pcrel correctly. Modernise the picbase labels.
-
-commit 2f450822a8698ba88441c56d152c7dc8924b127f
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 18 06:52:29 2013 -0500
-
- Clean up code to appease modern GCC compiler.
-
-commit 16d56c51aded374730920a4acde76ff3d2860ae1
-Author: Alan Modra <amodra@gmail.com>
-Date: Mon Nov 18 06:36:03 2013 -0500
-
- An #endif in the wrong place would cause compile failure on powerpcle.
- Using bl instead of b doesn't cause runtime failures as you might think,
- but does mess the processor branch prediction.
-
-commit 34f878a5ef28663f6b1d7fd26fb099429ea1579e
-Merge: 83f65b6 1fd0457
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 16 06:57:54 2013 -0500
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
- Conflicts:
- ChangeLog
- src/powerpc/ffi.c
-
-commit 83f65b63d9764a9cc7688fc5cda5ee2bd23faf54
-Author: Alan Modra <amodra@gmail.com>
-Date: Sat Nov 16 06:53:50 2013 -0500
-
- Finally, this adds _CALL_ELF == 2 support. ELFv1 objects can't be
- linked with ELFv2 objects, so this is one case where preprocessor
- tests in ffi.c are fine. Also, there is no need to define a new
- FFI_ELFv2 or somesuch value in enum ffi_abi. FFI_LINUX64 will happily
- serve both ABIs.
-
-commit 1fd045784cac874b5d76b7fa931f67209a8280d3
-Author: Alan Modra <amodra@gmail.com>
-Date: Sat Nov 16 06:53:50 2013 -0500
-
- Finally, this adds _CALL_ELF == 2 support. ELFv1 objects can't be
- linked with ELFv2 objects, so this is one case where preprocessor
- tests in ffi.c are fine. Also, there is no need to define a new
- FFI_ELFv2 or somesuch value in enum ffi_abi. FFI_LINUX64 will happily
- serve both ABIs.
-
-commit 362851379a49ce07d3e36e82c4e5c7b6cc16a352
-Author: Alan Modra <amodra@gmail.com>
-Date: Sat Nov 16 06:52:43 2013 -0500
-
- Andreas' 2013-02-08 change reverted some breakage for struct return
- values from 2011-11-12, but in so doing reintroduced string
- instructions to sysv.S that are not supported on all powerpc variants.
- This patch properly copies the bounce buffer to destination in C code
- rather than in asm.
-
- I have tested this on powerpc64-linux, powerpc-linux and
- powerpc-freebsd. Well, the last on powerpc-linux by lying to
- configure with
-
- CC="gcc -m32 -msvr4-struct-return -mlong-double-64" \
- CXX="g++ -m32 -msvr4-struct-return -mlong-double-64" \
- /src/libffi-current/configure --build=powerpc-freebsd
-
- and then
-
- make && make CC="gcc -m32" CXX="g++ -m32" \
- RUNTESTFLAGS=--target_board=unix/-m32/-msvr4-struct-return/-mlong-double-64\
- check
-
-commit 1c06515d927d9de1582438d4eb5953890e79c5c7
-Author: Alan Modra <amodra@gmail.com>
-Date: Sat Nov 16 06:41:36 2013 -0500
-
- The powerpc64 ABIs align structs passed by value, a fact ignored by
- gcc for quite some time. Since gcc now does the correct alignment,
- libffi needs to follow suit. This ought to be made selectable via
- a new abi value, and the #ifdefs removed from ffi.c along with many
- other #ifdefs present there and in assembly. I'll do that with a
- followup patch sometime.
-
- This is a revised version of
- https://sourceware.org/ml/libffi-discuss/2013/msg00162.html
-
-commit a97cf1fae575d8bfd5259c5c422025ad43911326
-Author: Alan Modra <amodra@gmail.com>
-Date: Sat Nov 16 06:40:13 2013 -0500
-
- This patch prepares for ELFv2, where sizes of these areas change. It
- also makes some minor changes to improve code efficiency.
-
-commit 164283f4ac5972ce2ab5e015cc2ab1014c23276c
-Author: Alan Modra <amodra@gmail.com>
-Date: Sat Nov 16 06:38:55 2013 -0500
-
- The powerpc64 support opted to pass floating point values both in the
- fpr area and the parameter save area, necessary when the backend
- doesn't know if a function argument corresponds to the ellipsis
- arguments of a variadic function. This patch adds powerpc support for
- variadic functions, and changes the code to only pass fp in the ABI
- mandated area. ELFv2 needs this change since the parameter save area
- may not exist there.
-
- This also fixes two faulty tests that used a non-variadic function
- cast to call a variadic function, and spuriously reasoned that this is
- somehow necessary for static functions..
-
-commit 31257b3189f81a199bc2902c22bc5f2d7c54ccde
-Author: Andrew Haley <aph@redhat.com>
-Date: Sat Nov 16 06:35:51 2013 -0500
-
- Fix sample closure code
-
-commit db0ace3a38496af73eae3df02ef353736d16909f
-Author: Andrew Haley <aph@redhat.com>
-Date: Sat Nov 16 06:29:25 2013 -0500
-
- Fix broken test cases
-
-commit de10f5039ed7a53382ddcc95c368d03e535edb98
-Merge: 58c2577 f3657da
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Nov 14 10:56:29 2013 -0500
-
- Merge branch 'master' of https://github.com/bivab/libffi
-
- Conflicts:
- ChangeLog
-
-commit f3657da278dd63afcdd8762894a9bdaea8ef028a
-Author: David Schneider <david.schneider@bivab.de>
-Date: Thu Nov 14 13:02:16 2013 +0100
-
- update Changelog
-
-commit 58c2577a3ff80e7416ef0434769e2af23365719c
-Author: Alan Modra <amodra@gmail.com>
-Date: Wed Nov 13 16:55:36 2013 -0500
-
- This enshrines the current testsuite practice of using ffi_arg for
- returned values. It would be reasonable and logical to use the actual
- return argument type as passed to ffi_prep_cif, but this would mean
- changing a large number of tests that use ffi_arg and all backends
- that write results to an ffi_arg.
-
-commit 8af42f9944f7ed72c81ae360aac6a84dc11f89dc
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 13 16:40:28 2013 -0500
-
- Respect HAVE_ALLOCA_H
-
-commit cdf405d574f479b782454516366bd4f4b9b3415e
-Author: David Schneider <david.schneider@bivab.de>
-Date: Wed Nov 13 15:50:21 2013 +0100
-
- add a testcase for the double/float issue on ARMHF
-
-commit 77f823e31ffb557a466b24f7fba845fbf7831798
-Author: David Schneider <david.schneider@bivab.de>
-Date: Wed Nov 13 14:26:57 2013 +0100
-
- stop trying to assing vfp regs once we are done with the registers
-
-commit 37067ec5036f2a6ed7a4799f83f8f53160460344
-Author: David Schneider <david.schneider@bivab.de>
-Date: Tue Nov 12 19:49:01 2013 +0100
-
- mark all vfp registers as used when done.
-
- To avoid assigning registers the would fit, once arguments have been on
- the stack, we mark all registers as used once we do not find a free
- register for the first time.
-
-commit 2f5b7ce545473a7f6e41193edc29407cbebe82d5
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 9 06:16:32 2013 -0500
-
- UltraSPARC IIi fix. Update README and build configury.
-
-commit becd754434173032f426d22ffcbfe24f55b3c137
-Author: Mark Kettenis <kettenis@gnu.org>
-Date: Wed Nov 6 06:43:49 2013 -0500
-
- Align the stack pointer to 16-bytes.
-
-commit 05c31093409f7b3e6d795fac21d2c954313d8162
-Author: Konstantin Belousov <kib@freebsd.org>
-Date: Wed Nov 6 06:40:58 2013 -0500
-
- Mark executable as not requiring executable stack.
-
-commit cf6bf9818e8394cfcdb07a40c6a5e2ee6b01d333
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 2 17:23:59 2013 -0400
-
- Fix up docs
-
-commit 02177176854d16fc0f1a5958aa34da2f306630ee
-Merge: c242217 c265b4c
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 2 17:11:22 2013 -0400
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
-commit c2422174b3edc0de0b148dfd6b67087bb881c4a6
-Merge: f4b843f d918d47
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 2 14:08:23 2013 -0700
-
- Merge pull request #45 from foss-for-synopsys-dwc-arc-processors/arc_support
-
- arc: Fix build error
-
-commit c265b4cacb9130f042699a85de9c7242b3f49cc3
-Merge: f4b843f d918d47
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 2 14:08:23 2013 -0700
-
- Merge pull request #45 from foss-for-synopsys-dwc-arc-processors/arc_support
-
- arc: Fix build error
-
-commit f4b843f83710ac378c48abd87fe66bb519d30d2e
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 2 17:01:15 2013 -0400
-
- Don't align stack for win32
-
-commit f3cd39345713db8e414cf642b6cb65a4cfe6018c
-Merge: 666f3e7 6aa1590
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 2 13:17:57 2013 -0700
-
- Merge pull request #51 from vbudovski/for_upstream
-
- Don't use 16 byte aligned stack for WIN32
-
-commit 666f3e71b56d92c49fcd2d7f349b8f8ebca0f8a3
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Oct 26 09:12:42 2013 -0400
-
- Add more credits to README. Tidy up.
-
-commit 73ada14e756bad97fad0e6915a821a3c7e079f81
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Oct 26 09:09:45 2013 -0400
-
- Update README
-
-commit d3372c54ce7117e80d389ba875dc5b6b2213c71e
-Author: Mark H Weaver <mhw@netris.org>
-Date: Sat Oct 26 08:30:06 2013 -0400
-
- Fix N32 ABI issue for MIPS.
-
-commit d6716aba8118eb0513885cfe557bedebb7016e8b
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 15 15:42:49 2013 -0400
-
- Update travis-ci build dependencies to include texinfo
-
-commit 16b93a211bcfbe4bd0efdcf94de225a71aa0ee02
-Author: Sandra Loosemore <sandra@codesourcery.com>
-Date: Tue Oct 15 15:33:59 2013 -0400
-
- Add nios2 port.
-
-commit 2f5626ce02fce8267ab48ceb6d7d0ed7d672a75e
-Author: Sandra Loosemore <sandra@codesourcery.com>
-Date: Tue Oct 15 15:32:16 2013 -0400
-
- Fix testsuite bug
-
-commit f64e4a865557e440774436b4c2b2fd7374290e97
-Author: Marcus Shawcroft <marcus.shawcroft@arm.com>
-Date: Tue Oct 15 15:20:14 2013 -0400
-
- Fix many.c testcase for Aarch64
-
-commit 128cd1d2f358f26d9fa75a27cf2b30356f5dd903
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 8 06:45:51 2013 -0400
-
- Fix spelling errors
-
-commit ff06269d707cafbfef2a88afb07a79c9d1480c5f
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 8 06:32:18 2013 -0400
-
- Update README for M88K and VAX
-
-commit d2fcbcdfbea750d1f6a9f493e2e6c4d5ffa71b34
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 8 06:27:46 2013 -0400
-
- Add m88k and VAX support. Update some configury bits.
-
-commit 6aa15900accc0a648cdebf11ec11d11697ebfffd
-Author: Vitaly Budovski <vbudovski@gmail.com>
-Date: Thu Sep 5 12:05:06 2013 +1000
-
- Don't use 16 byte aligned stack for WIN32
-
- This fixes a crash when accessing __stdcall functions in Python ctypes.
-
-commit 3b44d41156149af8da2a58825fefdfa23274ae7a
-Author: Makoto Kato <m_kato@ga2.so-net.ne.jp>
-Date: Wed Jul 10 15:34:53 2013 +0900
-
- Fix build failure when using clang for Android
-
- clang for Android generates __gnu_linux__ define, but gcc for Android doesn't. So we should add check it for Android
-
-commit d918d47809c174d62283306b282749f8db93661f
-Author: Mischa Jonker <mjonker@synopsys.com>
-Date: Mon Jul 8 15:51:36 2013 +0200
-
- arc: Fix build error
-
- One part of the patch for ARC support was missing in the upstreamed
- version.
-
- Signed-off-by: Mischa Jonker <mjonker@synopsys.com>
-
-commit d3d099b40c122550279789200263346f120f6909
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jul 2 16:11:38 2013 -0400
-
- little-endian ppc64 support
-
-commit 0f8690a84c874ec09a090c8c6adfb93c594acac6
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jul 2 15:54:40 2013 -0400
-
- Rebuild for ARC additions
-
-commit f88118b345f27c46f5445d6e4832c498ff9a6d85
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jul 2 15:51:27 2013 -0400
-
- Revert "Merge pull request #36 from abergmeier/emscripten_fix"
-
- This reverts commit 6a4d901dde7b3f87984c563505717cde3113d16e, reversing
- changes made to b50a13b9c07ec09af4b9697e482acdad571e6961.
-
-commit 6a4d901dde7b3f87984c563505717cde3113d16e
-Merge: b50a13b 587002c
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jul 2 12:12:34 2013 -0700
-
- Merge pull request #36 from abergmeier/emscripten_fix
-
- Fixes for building with Emscripten
-
-commit b50a13b9c07ec09af4b9697e482acdad571e6961
-Merge: 767f1f9 b082e15
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jul 2 12:10:26 2013 -0700
-
- Merge pull request #44 from foss-for-synopsys-dwc-arc-processors/arc_support
-
- Add ARC support
-
-commit 767f1f96e5282da44d7340e6815e9820a3f78e39
-Merge: c3c40e0 b8a91d8
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jul 2 12:08:04 2013 -0700
-
- Merge pull request #43 from JensTimmerman/__m128
-
- added include for xmmintrin.h
-
-commit b8a91d81be77d479327fdb6bdd9fdae6d18e6e63
-Author: Jens Timmerman <jens.timmerman@ugent.be>
-Date: Tue Jul 2 10:57:37 2013 +0200
-
- added include for xmmintrin.h
-
-commit b082e15091961373c03d10ed0251f619ebb6ed76
-Author: Mischa Jonker <mjonker@synopsys.com>
-Date: Mon Jun 10 16:19:33 2013 +0200
-
- Add ARC support
-
- This adds support for the ARC architecture to libffi. DesignWare ARC
- is a family of processors from Synopsys, Inc.
-
- This patch has been tested on a little-endian system and passes
- the testsuite.
-
- Signed-off-by: Mischa Jonker <mjonker@synopsys.com>
-
-commit cc9b518687e46b0d1acafdd4bc3f3b281c25a3d9
-Author: Marcin Wojdyr <wojdyr@gmail.com>
-Date: Tue May 14 15:01:23 2013 +0200
-
- Update libffi.pc.in
-
- use -L${toolexeclibdir} instead of -L${libdir}
- to be consistent with Makefile.am
-
-commit 587002c092cffe6e7a8d7028f246c241d03b738c
-Author: Andreas Bergmeier <andreas.bergmeier@gmx.net>
-Date: Fri Apr 19 17:12:24 2013 +0200
-
- Enable disabling of libtool on platforms where it does not work (e.g. LLVM).
- Build libraries normally then.
-
-commit c3c40e0290377d7cf948b072eedd8317c4bf215e
-Merge: ede96e4 4750e3c
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 30 05:24:14 2013 -0700
-
- Merge pull request #34 from davidsch/armhf
-
- Fix ARM hard-float support for large numbers of VFP arguments
-
-commit 4750e3c662fd9569cb3e2d28f539685fd1ca8caf
-Author: David Schneider <david.schneider@bivab.de>
-Date: Thu Mar 28 16:56:36 2013 +0100
-
- update changelog
-
-commit 9708e7cf09f1bf815f4d6485eb1f180fabb35804
-Author: David Schneider <david.schneider@bivab.de>
-Date: Wed Mar 27 19:31:04 2013 +0100
-
- folow the ARM hard-float ABI in ffi_prep_incoming_args_VFP
-
-commit b41120981e5e49ca2da10b94b154775f50da5f36
-Author: David Schneider <david.schneider@bivab.de>
-Date: Wed Mar 27 16:38:35 2013 +0100
-
- create separated versions of ffi_prep_incoming_args_* for SYSV and VFP ABIs.
-
- The different versions will be called depending on the value of cif->abi
-
-commit dd26f1f39c54861c5b91931f0f37a72942c2a072
-Author: David Schneider <david.schneider@bivab.de>
-Date: Thu Mar 28 15:39:01 2013 +0100
-
- add a failing test for closures on ARM hardfloat
-
-commit 3c1608613ab3c2184222b98c5482cddedd6b559b
-Author: David Schneider <david.schneider@bivab.de>
-Date: Tue Mar 26 19:24:47 2013 +0100
-
- extend ffi_prepare_args for FFI_VFP (hard-float ABI), fixing an issue with passing VFP arguments in VFP registers and the stack, while at the same time not using all core registers.
-
-commit 0f2ff2d4c92719be8936179f9ab674f4d1a3fd14
-Author: David Schneider <david.schneider@bivab.de>
-Date: Tue Mar 26 19:22:02 2013 +0100
-
- separate ARM ffi_prepare_args in a version implementing the simple SYSV calling convention and one for the hard-float calling convention
-
-commit 3a352b8a8252400a83de22c7c424bf1887b4a2ef
-Author: David Schneider <david.schneider@bivab.de>
-Date: Tue Mar 26 14:24:04 2013 +0100
-
- move the hardfloat specific argument copying code to the helper function
-
-commit 5df6b7944a4225b6eb329f3886be64e04e966f29
-Author: David Schneider <david.schneider@bivab.de>
-Date: Tue Mar 26 14:02:21 2013 +0100
-
- extract setting of arguments to be passed to a helper function
-
-commit 7d1048c471bb4b1f9d67a9e9f8e95f9a1d2e6d45
-Author: David Schneider <david.schneider@bivab.de>
-Date: Tue Mar 26 11:33:33 2013 +0100
-
- extract code to align the argument storage pointer to a helper function
-
-commit b9f013788f0f384c423ad963475aaacb55598135
-Author: David Schneider <david.schneider@bivab.de>
-Date: Mon Mar 25 13:27:36 2013 +0100
-
- add a testcase, that on ARM hardfloat needs more than the 8 VFP argument registers to pass arguments to a call
-
-commit 2fbdb0f231cafdb77b025d3cd8afe90cda99b3ba
-Author: David Schneider <david.schneider@bivab.de>
-Date: Mon Mar 25 13:26:02 2013 +0100
-
- use the absolute value to check the test result against an epsilon
-
-commit ede96e4eb660bbf3e0fe048135efa8106f48af5d
-Merge: f22ab3c 9e34992
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 17 18:38:21 2013 -0400
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
-commit f22ab3c6877cbdd07f058b68816b0086b1cb0e1e
-Merge: 12b1886 d08124b
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 17 18:34:54 2013 -0400
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
-commit 9e34992a5ea2fda1dba5875bf96dc91a7230f51f
-Merge: 12b1886 d08124b
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 17 18:34:54 2013 -0400
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
-commit 12b1886d7b1f8aa264b1d348bfa47a0e14712df4
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 17 18:32:12 2013 -0400
-
- cygwin fix & updates for 3.0.13
-
-commit d08124bedf2c6d61874fe215404783aeb9f6f1ac
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 17 18:32:12 2013 -0400
-
- cygwin fix & updates for 3.0.13
-
-commit cb32c812d04d1dfa72002cc04924e7e4fef89e02
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Mar 17 09:27:55 2013 -0400
-
- Fix lib install dir
-
-commit efd7866a361a6f636bae8400d26c6811e56ca207
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 16 08:35:57 2013 -0400
-
- 2.0.13rc1
-
-commit ff647ad4dff2f07dd153f295a1f70b1d906cd6ca
-Merge: 4acf005 d9dd417
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 16 08:20:40 2013 -0400
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
- Conflicts:
- ChangeLog
-
-commit 4acf0056f55c757490dae6c29a65b0321327ea8a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 16 08:18:45 2013 -0400
-
- Build fix for soft-float power targets
-
-commit 675c9839224e4268187f1ec6f512127f9db555d0
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 16 08:12:38 2013 -0400
-
- Documentation fix
-
-commit 8a286f570ccd41db81f74ea7f248da62241d898a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 16 08:01:19 2013 -0400
-
- Fix for m68000 systems
-
-commit d9dd417b09566af55b7b3000bb53ccaf2e1d6c92
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 16 08:01:19 2013 -0400
-
- Fix for m68000 systems
-
-commit 215763d012a944d95406b394d6013b80d220e870
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 16 07:57:35 2013 -0400
-
- Update configury.
-
-commit 9180d8f39c9b6afe17b78277c2711a5d9948e824
-Merge: 2fb527a 7e1b326
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 16 07:46:55 2013 -0400
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
-commit 2fb527a017a4943e176a489ff103231b86464b59
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 16 07:46:38 2013 -0400
-
- Add Meta processor support
-
-commit 211a9ebf4d1a9801e15e103566aed2b8c42790be
-Merge: f308faf ee18766
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 16 04:24:40 2013 -0700
-
- Merge pull request #32 from alex/patch-1
-
- Fix for a crasher due to misaligned stack on x86-32.
-
-commit 7e1b32649efd24814e86172e196f390566f9e970
-Merge: f308faf ee18766
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 16 04:24:40 2013 -0700
-
- Merge pull request #32 from alex/patch-1
-
- Fix for a crasher due to misaligned stack on x86-32.
-
-commit ee18766b169811426c14b011fbb46d81e344f926
-Author: Alex Gaynor <alex.gaynor@gmail.com>
-Date: Thu Mar 14 15:00:33 2013 -0700
-
- Fix for a crasher due to misaligned stack on x86-32.
-
- Full information on reproduction (using Python's ctypes available here: http://bugs.python.org/issue17423)
-
-commit f308faf1eabaf8dc24966ab17fbf94368f46b9c7
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Feb 11 14:25:13 2013 -0500
-
- Add moxie support. Release 3.0.12.
-
-commit 4ea22e54e3b143fe05c413f6dddd236af6bcbfb2
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Feb 10 08:48:38 2013 -0500
-
- Update README
-
-commit 10e77227b6ae85f46f28590bfb09ca3608554358
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Feb 10 08:47:26 2013 -0500
-
- mend
-
-commit a9521411a53d58f2bf88199242200ceb0d4dae3a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 9 06:54:40 2013 -0500
-
- sparc v8 and testsuite fixes
-
-commit 70b11b47eea93bf43627588d494d0b3b0d062481
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 8 16:12:19 2013 -0500
-
- Fix small struct passing on ppc
-
-commit 63ba1fa79f7c4ce42de848debe233aab31aecb51
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 8 15:18:19 2013 -0500
-
- Remove xfail for arm*-*-*.
-
-commit 24fbca4c1d57d4ea628c0a8ba643684daf54a37e
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 8 14:19:56 2013 -0500
-
- Fix typo
-
-commit b0fa11cb0a94ce6baca058eab9b10e40475e71d6
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 8 14:17:13 2013 -0500
-
- More man page cleanup
-
-commit 8bd15d139a58a6e46dc90a1cb2d89f59f32f06c7
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 8 13:56:37 2013 -0500
-
- Fix many.c testcase for ppc
-
-commit 7aab825cf198be85490d3cd80e778d415d85ad9b
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 8 13:26:21 2013 -0500
-
- Add missing files to dist
-
-commit cb03ea8f4eb08024e44abe4392edc77b89fbfbad
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 8 12:25:18 2013 -0500
-
- sparc v9 fixes for sun tools
-
-commit 35ee8d44f31dd3d3b88083c837dc351593e13cc2
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 8 07:12:41 2013 -0500
-
- Fix microblaze big-endian struct issue
-
-commit 9db7e1a958fc484ba149efe027008b9a170395fb
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Feb 7 21:06:08 2013 -0500
-
- Fix botched sparc patch. Update version.
-
-commit ce0138e61455f268af326e26908b9680ec2c4bea
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Feb 7 18:04:01 2013 -0500
-
- Update bug report address. rc2.
-
-commit fd07c9e40451e0ec1d0475cd54a83d45ccaea2c0
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Feb 7 18:00:36 2013 -0500
-
- Add cache flushing routine for sun compiler on sparc solaris 2.8
-
-commit ed6ae9501b2bab45daf93b4935eb0c977635b763
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Feb 7 16:43:36 2013 -0500
-
- Add libtool-ldflags. Define toolexeclibdir for non-GCC builds.
-
-commit ffef2e046aaec853be356f0b8770a335185ea9cf
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Feb 7 15:47:01 2013 -0500
-
- x32 and libtool fixes
-
-commit 95eecebb2858dc6f1495a61072ff36d0a8127144
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Feb 7 15:32:46 2013 -0500
-
- Remove a.out cruft from dist
-
-commit 176aa9d2e23d9cd57d6f250692d910b408f9a651
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Feb 7 15:29:22 2013 -0500
-
- Fix GCC usage test and update README
-
-commit f3a4f3fdde89b04d66983a42a25d09161c5d4d54
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Feb 7 09:57:20 2013 -0500
-
- Fixes for AIX xlc compiler.
-
-commit 522f8fef49848927482bc63c94afaea5b84e5ec1
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 6 20:31:31 2013 -0500
-
- Fix man page. Clean out junk.
-
-commit c4dfa259eb4e8e6f4c397868d7fee80aa0bb6a12
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 6 17:43:24 2013 -0500
-
- Bump soversion
-
-commit f62bd63fe6123cadedb8b2b2c72eb549c40fbce9
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 6 17:38:32 2013 -0500
-
- Release candidate 1
-
-commit f7cd61e9e68a4a51147df04d75bfe5b91b9d9286
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 6 17:38:04 2013 -0500
-
- Fix pkgconfig install bits
-
-commit 6a790129427121f7db2d876e7218a3104e6d2741
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 6 17:37:15 2013 -0500
-
- Work around LLVM ABI problem on x86-64
-
-commit 370112938e705128fd5dd4017fc1a1210bd0271a
-Merge: bada2e3 bcc0c28
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Jan 27 05:09:04 2013 -0800
-
- Merge pull request #28 from jralls/master
-
- Reorder x86_64 checks
-
-commit bcc0c28001b6d427d5cd8037d2e3c892babc6b4c
-Author: John Ralls <jralls@ceridwen.us>
-Date: Sat Jan 26 15:21:14 2013 -0800
-
- Reorder x86_64 tests
-
- So that darwin and cygwin/mingw are tested before the generic check --
- which allows them to actually be set.
-
-commit bada2e326d9a9acf3ae40cfa4f5d7a9ba97b2ea8
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 21 08:02:07 2013 -0500
-
- Update README
-
-commit 655bb8f3690feba8e840a5f1854b1d78ed08f692
-Merge: 1035ffb 840f975
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 21 08:01:24 2013 -0500
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
-commit 1035ffb2f468e1a1c401d58cff7e7abb69838e68
-Merge: aeb8719 4086024
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 21 07:55:53 2013 -0500
-
- Update README
-
-commit 840f975866052fdd91b2c224d56e01ae5900b60d
-Merge: aeb8719 4086024
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 21 07:55:53 2013 -0500
-
- Merge branch 'master' of github.com:/atgreen/libffi
-
-commit aeb8719a34756969970603fca4568530d56708af
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 21 07:37:30 2013 -0500
-
- New microblaze support
-
-commit 40860245a4fd91a1b88adc9171ec993c549e45d5
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 21 07:37:30 2013 -0500
-
- New microblaze support
-
-commit 20cae32b152b43679ae65a85db9a1c6bb8a143dd
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 21 07:07:38 2013 -0500
-
- Xtensa support
-
-commit 9742f91782faef4a15941508a22c408fb7d1d227
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 21 07:03:41 2013 -0500
-
- Mention IBM XL compiler support on AIX.
-
-commit f03eab08248f122ce3b623a18df9e19fae1b6e98
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Jan 11 17:14:11 2013 -0500
-
- Remove obsolete inline test functions
-
-commit 05fbe1faedc7b2580d5f14010d00e9e3cee73951
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Jan 11 16:54:40 2013 -0500
-
- xlc compiler support
-
-commit 0b4986a7889ed1864674192228f1162c1b5770a8
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Jan 11 11:19:52 2013 -0500
-
- [travis] install dejagnu with sudo
-
-commit 3c337eef51ab9a4993fc875bfa26289dd6a08881
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Jan 11 11:18:14 2013 -0500
-
- [travis] install dejagnu
-
-commit 90720962ce1baf9fc35d1bde1738102bcd5bd5ed
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Jan 11 10:57:30 2013 -0500
-
- Add first travis config file
-
-commit bff052d9cd5be41ba9e47c76114054af487d3c30
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Jan 11 10:24:32 2013 -0500
-
- 32-bit x86 fix and more
-
-commit cd41aeab6176f839167955c016ecc19f65f75df3
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Jan 10 17:25:45 2013 -0500
-
- Add compiler column to table
-
-commit 8bf987d4df7c4d21435b9211f6cc86abf5904b42
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Jan 10 17:24:51 2013 -0500
-
- Fix for sunpro compiler on Solaris
-
-commit 3ee74fd6dc8ccd32b608bbff73526838fc34f70b
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Jan 10 17:15:03 2013 -0500
-
- Update documentation version.
-
-commit 13e2d7b92557a9511a0414df82bf2df3edc55cba
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Jan 10 10:52:02 2013 -0500
-
- Handle both 32 and 64-bit x86 builds regardless of target triple
-
-commit 5141543000fc86a3d49a907a2313713ee79e504d
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Jan 10 07:35:53 2013 -0500
-
- Don't run EH tests with non-GNU compiler
-
-commit 56ba8d86f47937a0afb81a2b9e77c9d235d9db45
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Jan 10 07:25:10 2013 -0500
-
- Don't use warning checking macro with sun compiler
-
-commit 6a028caec1b2c7904feb4c4f9cb7e1125e1d1b60
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Jan 10 01:19:43 2013 -0500
-
- Don't use GCCisms to define types when
- + building with the SUNPRO compiler.
-
-commit 2d9b3939751b3ef9739049509d353ade10b32a8f
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 9 21:14:54 2013 -0500
-
- Fix for closures with sunpro compiler
-
-commit 8308984e479e3274a36e98e8272b5adbb6b774c2
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jan 8 15:14:21 2013 -0500
-
- Make sure we're running dejagnu tests with the right compiler.
-
-commit f26c7ca67147450db2fe25ea932944e6cf145d5c
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jan 8 14:47:05 2013 -0500
-
- Make compiler options in dejagnu runs compiler specific
-
-commit 74c776e21907fc2e59257c021f23077f8b7966cb
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jan 8 12:25:54 2013 -0500
-
- Switch x86 Solaris to X86 from X86_64
-
-commit 8962c8c8d06803e310bac0ffc8e84ea15daeff3f
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jan 8 12:22:24 2013 -0500
-
- Fix read-only eh_frame test
-
-commit 35ddb69c2b49746d940e919ca226ecc1be94f14a
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jan 8 07:53:37 2013 -0500
-
- Only emit DWARF unwind info when building with GCC
-
-commit f7879bc3f3a8d0bbfcc38771732c160a58ba9cd8
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Jan 8 07:30:28 2013 -0500
-
- Testsuite fix for Solaris vendor compiler
-
-commit 67cea90fc0897021466fd102671019d30db474cd
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 7 06:30:24 2013 -0500
-
- mend
-
-commit 0de3277b18cf54be3b81d509b9be9b47d9bc1e82
-Author: Thorsten Glaser <tg@mirbsd.de>
-Date: Mon Dec 3 00:02:31 2012 +0000
-
- Testsuite fixes (was Re: [PATCH] Fix libffi on m68k-linux-gnu, completely)
-
- Dixi quod…
-
- >although I believe some 3.0.11 checks to be broken:
-
- And indeed, with a few minor changes on top of git master,
- I still get a full run of PASS plus one XPASS on amd64-linux!
-
- With the other patches (from this message’s parent) and
- these applied, I get a full PASS on m68k-linux as well.
-
- So, please git am these three diffs ☺
-
- bye,
- //mirabilos
- --
- FWIW, I'm quite impressed with mksh interactively. I thought it was much
- *much* more bare bones. But it turns out it beats the living hell out of
- ksh93 in that respect. I'd even consider it for my daily use if I hadn't
- wasted half my life on my zsh setup. :-) -- Frank Terbeck in #!/bin/mksh
- From 5cb15a3bad1f0fb360520dd48bfc938c821cdcca Mon Sep 17 00:00:00 2001
- From: Thorsten Glaser <tg@mirbsd.org>
- Date: Sun, 2 Dec 2012 23:20:56 +0000
- Subject: [PATCH 1/2] Fix tests writing to a closure retval via pointer casts
-
- As explained in <Pine.BSM.4.64L.1212022014490.23442@herc.mirbsd.org>
- all other tests that do the same cast to an ffi_arg pointer instead.
-
- PASS on amd64-linux (Xen domU) and m68k-linux (ARAnyM)
-
- Signed-off-by: Thorsten Glaser <tg@mirbsd.org>
-
-commit 8f4772f383abd71cfa141c8a70ba11c1aa4ebe2c
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 7 06:14:53 2013 -0500
-
- m68k fixes for signed 8 and 16-bit calls.
-
-commit ea7f8440d58afbebb181e295ff564fdf3d6590a0
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Jan 4 09:09:32 2013 -0500
-
- remove gcc-ism
-
-commit f06c0f10377ac04eeba5e632dbe5c62c629df4e6
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 09:39:17 2013 -0500
-
- Add missing ChangeLog entry and generated files.
-
-commit 1f8675d4c101d19d67ca0a55ff2ba973349558ad
-Merge: 335f419 f6b58d2
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 06:34:38 2013 -0800
-
- Merge pull request #26 from rofl0r/master
-
- fix build error on ppc when long double == double
-
-commit 335f419a86090cda9f215d149572f9481c3ad034
-Merge: 53236d5 6d6f711
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 06:30:03 2013 -0800
-
- Merge pull request #23 from rurban/master
-
- cygwin/mingw shared libs need libtool LDFLAGS = -no-undefined
-
-commit 53236d5061034cc0a7f4647fc1bd05ba1aeb3d2a
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 09:24:55 2013 -0500
-
- Regenerate files
-
-commit 72222ca3fbe560e13c8dc89ca441b28b7cc74daf
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 09:06:38 2013 -0500
-
- Update texinfo.tex
-
-commit 1e326c95431fc9896422fa36659f3e833852579c
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 09:05:02 2013 -0500
-
- Update config.guess and config.sub
-
-commit cb6671f5b8a9596ff968c6b6c304f70adf71b368
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 08:56:07 2013 -0500
-
- Missing .gitignore changes for xcode support
-
-commit ebbe77966855395a2a47ed2c09a38f93eb0481cf
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 08:54:05 2013 -0500
-
- missed x32 libtool patch.
-
-commit 4394096da0aca0dd422b479a043c18b4f05c5770
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 08:51:35 2013 -0500
-
- missed trampoline_table patch. Move to GCC.
-
-commit ed7a59c3ff7c84bd95c374a5aff21599f705e6dc
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 08:48:01 2013 -0500
-
- Windows symbol export fix. Move to GCC.
-
-commit ccee09a4ff843b11c7d8b6819776f57d187305c7
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 08:41:55 2013 -0500
-
- +2012-03-21 Peter Rosin <peda@lysator.liu.se>
- +
- + * testsuite/lib/target-libpath.exp [*-*-cygwin*, *-*-mingw*]
- + (set_ld_library_path_env_vars): Add the library search dir to PATH
- + (and save PATH for later).
- + (restore_ld_library_path_env_vars): Restore PATH.
-
-commit 089dbce7cc0889eb26444d89ae062c73c69f26f0
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 08:37:35 2013 -0500
-
- med
-
-commit 980a334c42b4b0eff32e55929ec6727d1326b05d
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 07:36:42 2013 -0500
-
- Test GCC update
-
-commit 8bad679ade5000e57cdc9cacde22e8b99840930f
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 08:28:35 2013 -0500
-
- New stand-alone patch
-
-commit 981c32ee115e9f0d6546a74592875e138222a9d1
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Jan 2 07:34:03 2013 -0500
-
- Merge with GCC. Eliminate quilt bits.
-
-commit 61a054929517fb80c437ba71c91f3e20cfff581a
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Nov 28 06:07:41 2012 -0500
-
- Refresh config.guess and config.sub
-
-commit f6b58d2bdc0a24ce94dedce59802f091979df265
-Author: rofl0r <retnyg@gmx.net>
-Date: Thu Nov 22 16:26:21 2012 +0100
-
- fix build on ppc when long double == double
-
-commit 69da33a0761aeac73f9e9646269da61c906d6020
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 12 15:25:47 2012 -0500
-
- Pull in config.sub for aarch64 support and more
-
-commit f680b598b7bdde325ac9349e8c35151c228bf2df
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Nov 6 16:00:40 2012 -0500
-
- Add missing aarch64 configury bits
-
-commit dfadfb19853c57c8623c436d0ef2bdafab24b433
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Oct 31 06:46:41 2012 -0400
-
- Rebase for ppc64 fix
-
-commit e944b8c7eb1e2eeb9c0f3b9742b4d7f476860ce1
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 30 14:06:09 2012 -0400
-
- Add PaX work-around
-
-commit 9ccd51be1fdeb99f8b4f42f905166c2abbba8ac0
-Merge: f342996 fa5d747
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 30 13:37:37 2012 -0400
-
- Fix commit conflicts
-
-commit f342996cb50eb23b868afcff5ac0cdbb6b505d63
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 30 07:42:27 2012 -0400
-
- Darwin12 fix
-
-commit 58e8b66f70cef2e3c9b0e5a707b45d634cbbf5d9
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 30 07:07:19 2012 -0400
-
- AArch64 port
-
-commit fa5d747905472571fd472c07d4726017624f66b3
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 30 07:07:19 2012 -0400
-
- AArch64 port
-
-commit 6993a6686f43f2313b18142c1e96189a27db2aa3
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Oct 30 06:59:32 2012 -0400
-
- Fix autoconf macros
-
-commit 70084e70ddb13b29dd05c751b1904de206bbe790
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Oct 12 23:55:06 2012 -0400
-
- Update Tile* port info
-
-commit 9c00a3f6742d61404b31268cc773e7130ff43331
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Oct 12 16:46:06 2012 -0400
-
- TILE-Gx/TILEPro support
-
-commit 048d2f41c3a6664b4b64bf21e804686662da4160
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Oct 11 10:55:25 2012 -0400
-
- Rebase
-
-commit 6d6f71108064f5069edd7bf771059d3b82640135
-Author: Reini Urban <rurban@cpanel.net>
-Date: Sat Jul 7 12:42:00 2012 -0500
-
- cygwin/mingw shared libs need libtool LDFLAGS = -no-undefined
-
- otherwise only static libs are created.
-
-commit d330f19292da8f39a78a9e2b0ba08df8094e3bc5
-Author: Nicolas Lelong <rotoglup>
-Date: Sat May 5 09:37:02 2012 -0400
-
- iOS build fixes.
-
-commit 09b23cfc1d6d15361eee18818851fd3cacb26559
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Apr 27 08:29:48 2012 -0400
-
- Update README with Blackfin/uClinux support
-
-commit 213ed15c70e72d666154c08e2b41dae3f61f20d3
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Apr 27 01:34:15 2012 -0400
-
- Add blackfin supprt from Alexandre Keunecke.
-
-commit ff3d76fd427382ce7d2b2ed54acdd0bce470ca4f
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Apr 11 23:16:48 2012 -0400
-
- 3.0.11
-
-commit 7e0a412c4fd9cbe77b467a9bf86f56aea62632c3
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Apr 11 22:47:44 2012 -0400
-
- Update files to ship
-
-commit 39e6a5860416f7bad992149817e1da1ba7c460d4
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Wed Apr 11 22:39:46 2012 -0400
-
- More mac/ios build improvements
-
-commit 853cc722a16f8d1254573ef3bb73c7b8f3d8a110
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Apr 10 06:33:33 2012 -0400
-
- Fix typo for darwin targets
-
-commit 3f5023068cda07a3dd6dacbaa875a5b5fc96d4bb
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Apr 6 20:34:51 2012 -0400
-
- mend
-
-commit ebb8e8945681ce0af7a5c47a980287e8ece84b84
-Author: Mike Lewis <mikelikespie@gmail.com>
-Date: Fri Apr 6 20:02:08 2012 -0400
-
- Build iOS library with xcode
-
-commit a098b44f4c592c2192fcdef4fad6108eb3f4301c
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Apr 6 17:04:35 2012 -0400
-
- Reapply missing testsuite changes for arm
-
-commit 10d1e51393f08c14045db85843208f44f9f1e9ba
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Apr 6 11:57:14 2012 -0400
-
- Update to rc4. Upgrade autoconf version.
-
-commit 9bcc884276dc0a807b2605e510b11b1740dd9aa2
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Apr 6 11:53:07 2012 -0400
-
- Fix Linux/x32 reference in README
-
-commit a044a56b1cd2a0924f5ec0d6b5a5089d14fcd1a1
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Apr 6 10:39:10 2012 -0400
-
- Linux/x32 libtool fix
-
-commit 59bb61a36661b972e8443531d3b7bc736e131a4b
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Apr 6 08:26:14 2012 -0400
-
- Update libtool version, README, tests dists
-
-commit f2981454cbe25cf9411b710f46c5f5552003a123
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Apr 5 15:45:19 2012 -0400
-
- Revert debug code changes
-
-commit 39dccddb606f6fdb8dcb177d416e884041da6e30
-Author: Zachary Waldowski <zwaldowski@gmail.com>
-Date: Thu Apr 5 12:32:41 2012 -0400
-
- Fix building with Clang for Darwin (OS X 10.6+ and iOS
- 4.0+)
-
-commit 3afaa9a34a81a305227ae8cf4f12b9d0484d055e
-Author: Peter Rosin <peda@lysator.liu.se>
-Date: Tue Apr 3 07:40:31 2012 -0400
-
- Fix return_uc.c test case on windows.
-
-commit 65f40c35a2873d8328359ec4512bd0736dbe32c7
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Apr 3 07:35:59 2012 -0400
-
- Repair ppc build regression.
-
-commit 0a1ab12a8d15caa894116a82249551f23ef65612
-Author: Peter Rosin <peda@lysator.liu.se>
-Date: Fri Mar 30 08:14:08 2012 -0400
-
- Various MSVC-related changes.
-
-commit e1539266e6c6dde3c99832323586f33f977d1dc0
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Mar 30 00:40:18 2012 -0400
-
- ARM VFP fix for old toolchains
-
-commit 7c5e60b5f47d725036a72162f136272bc407e3a1
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Mar 29 08:48:22 2012 -0400
-
- Rebase on fixed GCC sources
-
-commit e72ed5eeaa9cfb0fdc86f6b3422734177b659f96
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 21 09:52:28 2012 -0400
-
- Fix vararg float test
-
-commit bd78c9c3311244dd5f877c915b0dff91621dd253
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 21 08:09:30 2012 -0400
-
- More cygwin fixes
-
-commit 84d3253f86dad6b4f261231935675d35fd964b05
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Mar 19 23:07:35 2012 -0400
-
- Rebase post GCC merge
-
-commit 964c5b93f80dcaacf73056b7d15a4d2b4b7a217c
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 3 14:46:20 2012 -0500
-
- abi check fixes and Linux/x32 support
-
-commit 6c194233a5f6f1d274669afc5924a9e1f69d4876
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Mar 3 14:17:54 2012 -0500
-
- Add -no-undefined for both 32- and 64-bit x86
- windows-like hosts.
-
-commit 8360bf1cd0aba8db5582266da70467de7e89a57a
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Feb 23 07:01:13 2012 -0500
-
- Ensure that users don't include ffitarget.h directly
-
-commit d578b89619cf3d2baff027b203619dc307fc12e3
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 15 00:18:18 2012 -0500
-
- Fix ABI check regression
-
-commit dee20f8e45c486f5018f31e09bb362992aa498c3
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 10 13:06:46 2012 -0500
-
- Rebased from gcc
-
-commit 4130e1972d001143e5e9f3c6b65f2a6f9524169e
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 3 13:18:27 2012 -0600
-
- Refresh autoconf-archive m4 scripts
-
-commit 1ff9c604bb214b5a305064af1049577ef783730a
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 1 16:34:30 2012 -0600
-
- Rebase from GCC
-
-commit 211060eb8f714af0e935430efa6bb45e8e3ffc5d
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 23 14:24:01 2012 -0500
-
- Alpha fix
-
-commit 78d9c638ba0de6edfbc603fd65d19c6562663248
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 23 14:17:24 2012 -0500
-
- mend
-
-commit afaf3381604bd81803d8a5f3bf4d462299f1aac3
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 23 14:17:13 2012 -0500
-
- mend
-
-commit 9e9c4aeb77de5608d602109f22100c1c0c79faad
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 23 14:11:23 2012 -0500
-
- Add Amiga support
-
-commit 8efc0b1f4027d5a3cbf205e55d422d94e60f3226
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 23 13:47:38 2012 -0500
-
- Unlikely fixes
-
-commit 1df51398ae183dc208ba4599ee867278b04d13d3
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 23 13:43:59 2012 -0500
-
- mend
-
-commit cd2277cc796b96b149cd284ae85326529fe7fb9c
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 23 13:43:38 2012 -0500
-
- mend
-
-commit 164e6fe04b189746c8bd5810c6e3e919770bb9d4
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 23 12:41:06 2012 -0500
-
- m68k fixes
-
-commit c365ee7577bef00cb3c2c0b5224147aea04138d8
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jan 23 11:13:18 2012 -0500
-
- Refresh
-
-commit f22c38bbd93bcc0c04bf26c3e414556b3177c385
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 18 15:13:41 2011 -0500
-
- Update variadic patch
-
-commit 03e9ee321a3c208f88d2432587ce40b2bb2430ba
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Nov 18 15:13:00 2011 -0500
-
- Fix cls_double_va.c and update docs
-
-commit 95f31151ec792809cfb80d385350f9f56d95aa25
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 23:46:05 2011 -0500
-
- Rerun automake
-
-commit 198ed1ef85cf18342627f8d44bc3f12c9975a49d
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 23:45:20 2011 -0500
-
- Update version number
-
-commit 4f17e1f142e805b13959ba2594ee735eae439f4e
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 17:22:24 2011 -0500
-
- Fix last patch
-
-commit ff9454da44859716a5bd4eaa344499288c79694f
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 17:18:51 2011 -0500
-
- Add David Gilbert's variadic function call support
-
-commit ea14ae85e8f54ff046b7fb8a9cfe349475272044
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 16:36:59 2011 -0500
-
- clean up
-
-commit 52891f8a93f9b8de801cca4cf05639422dc9773e
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 16:35:55 2011 -0500
-
- Add powerpc soft float support
-
-commit c8f1bde8e2566c5a87474b4d08aa934d6d28ee75
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 16:21:02 2011 -0500
-
- Remove junk file
-
-commit 6a6e7f862f3cc677e19131587caa619e7f9c7ffd
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 16:20:42 2011 -0500
-
- Fix kfreebsd
-
-commit d52fbed05ccbdee9ed8b9c911cbb4f85b0ff0f2a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 16:13:41 2011 -0500
-
- Add missing ChangeLog entry
-
-commit 322052ce65c4fdac85bedc24726fd0e0094ba521
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 16:11:49 2011 -0500
-
- Fix arm wince alignment issue
-
-commit af18df2bc2f52df81e7b5c619bd86db8489dc873
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 15:52:08 2011 -0500
-
- Remove use of ppc string instructions
-
-commit 236c9391321f83ad40daf03f40c35c9ebc1da6b3
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 07:37:40 2011 -0500
-
- Fix darwin11 build problem
-
-commit c411f140f305ebb00d33c92b7cb2742bcd241b6a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 07:32:36 2011 -0500
-
- Fix ax_enable_builddir macro on BSD systems
-
-commit 3d56106b07735abef6ae9f032e94f560a0ed2f30
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Nov 12 07:20:24 2011 -0500
-
- Rebase
-
-commit 8c01954c50bf8ef2e00a3db166060a1b8f83a20d
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Sep 6 14:26:32 2011 -0400
-
- Build assembly files with debug info
-
-commit fed646a2078969f4ce89c29107f1e72e03f4a977
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Sep 6 09:50:20 2011 -0400
-
- Regenerate configury with missing m4 macros
-
-commit d76441cf71216f8f1e62e7ec852a7f4e21371ec8
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Aug 24 10:14:23 2011 -0400
-
- Update list of supported OpenBSD systems
-
-commit ee6696fdf4768ba6dd037fb6dd99435afa13816e
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Aug 23 12:30:29 2011 -0400
-
- 3.0.11-rc1. soname bump.
-
-commit c6265c36a91eab8175d0e72db84d8225418f2379
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Aug 23 10:31:33 2011 -0400
-
- Version 3.0.10
-
-commit cc5e41bf32d18a14dbdd653d52eacdbdc934c392
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Aug 22 16:34:24 2011 -0400
-
- Fix use of autoconf macros
-
-commit 049d8386ff52399e69a530b55b9feedc8a2589d2
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Aug 22 14:50:10 2011 -0400
-
- Many new patches
-
-commit 3b7efa4e74f0dcebf70b447391987aedd3473306
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Aug 15 13:25:13 2011 -0400
-
- Revert remove-debug-code patch temporarily (for ARM Fedora release)
-
-commit d992ac54a2a9e7e064ffebcb91e05e7cb86185c7
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Jul 29 17:32:53 2011 -0400
-
- Refresh from GCC
-
-commit 2d3fb36420e09304220ee6c0652bae5eccdb965d
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Mar 30 16:54:42 2011 -0400
-
- Fix darwin EH
-
-commit 30ff28e1d8cd9ed5319f1fbe9c7cccacc8161fb3
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Feb 28 15:36:23 2011 -0500
-
- Fix permissions
-
-commit 09f8f310f4f53a24289682d3d28f4399d7bafc3b
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Feb 28 15:36:07 2011 -0500
-
- More AIX fixes. rc9.
-
-commit 53d7b165642c220aa5166ba350b490802f359b54
-Merge: 18dd85d 3000dc2
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Feb 28 15:23:31 2011 -0500
-
- Merge branch 'master' of https://github.com/landonf/libffi-ios
-
-commit 18dd85d6cb9f3f3eea2a3b70eb4e150045905c55
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 25 16:23:04 2011 -0500
-
- rc8. fix last patch.
-
-commit 74ee6ea8b42e60d44a3ae8938b1e42a38c1e66b4
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 25 15:52:14 2011 -0500
-
- rc7. More AIX fixes.
-
-commit 2541679dbd3db0014890f42192dbf8008ab923fa
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 25 15:09:13 2011 -0500
-
- Fix ppc32 bug
-
-commit cbb062cc35c518004f1ab45c847f8ec4f66069ad
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Feb 17 20:39:21 2011 -0500
-
- Another non-GCC configury fix
-
-commit 8cf8878425e9971866fa6b27a3e4914729ad3960
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 15 15:19:49 2011 -0500
-
- Fix ax_cc_maxopt.m4
-
-commit 24b72070c0937f9000744c77a636f07e04786b6a
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Feb 14 15:30:57 2011 -0500
-
- Fix warning and msvcc patches
-
-commit d72c49e556a8c516e97f6722d1be2f1209c21207
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Feb 13 11:41:05 2011 -0500
-
- Add missing msvcc.sh
-
-commit 3000dc237f6017a7445d8404097a4f46b73fdd29
-Merge: 55e4a5a 1fbf9dc
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Feb 13 08:55:53 2011 -0500
-
- Merge remote branch 'upstream/master'
-
-commit 1fbf9dc44feea564e84ad7406d17c5d5906ce0e0
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Feb 13 08:06:39 2011 -0500
-
- Fix bad_abi test. rc5.
-
-commit 90af15ef5c1614b76370c4d13954586fabf9e8e3
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 12 12:29:36 2011 -0500
-
- iOS fixes
-
-commit 55e4a5aa1568558a04aa40f16fc022e459af53e3
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Feb 12 12:13:46 2011 -0500
-
- Add support for building a full armv6/armv7/i386 universal iOS library
-
-commit a0c80f279b8733d001cb5e5c5a3289ecb7a6e56a
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Feb 12 11:43:49 2011 -0500
-
- Update my e-mail address.
-
-commit 8195e0e11df7a53fa474caa9375f73ca1136ed66
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Feb 12 11:27:00 2011 -0500
-
- Fix symbol prefixes on Darwin.
-
-commit 56b3f8cef0f28cefaa0f40fe0cf7c524adef131d
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Feb 12 11:14:54 2011 -0500
-
- Modify the ffi_closure structures to hold table/table entry pointers instead of a code buffer.
-
- This re-integrates commit da2773e02ab26cc11a7f.
-
-commit 28a00f61ff3f64c4eb2269ce2aea3d493274469e
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Feb 12 11:01:48 2011 -0500
-
- Apple assembler support; fixed most gas/ELF-isms.
-
-commit 7f2ea33a80bfced5e48ed7292f3b8f057d54ff8f
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Feb 12 10:39:18 2011 -0500
-
- Replace RETLDM macro.
-
- The macro is incompatible with Apple's assembler; switch to
- a simple inline version.
-
-commit 92ff23e77fa586455b427b71f49e1d9502470e6e
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Feb 12 10:24:49 2011 -0500
-
- Switch to the current iOS 4.2 SDK.
-
-commit 58fb8ca2dfb89ad70284bb9678d3d4dbb658c8a7
-Merge: cc3fbd9 71c792f
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Feb 12 10:23:19 2011 -0500
-
- Merge remote branch 'upstream/master'
-
-commit cc3fbd975ce9366d4c40a6ff6c108f664867bd7c
-Merge: e449a43 f6ab3ed
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Feb 12 10:21:02 2011 -0500
-
- Merge branch 'master' of github.com:landonf/libffi-ios
-
-commit e449a43bbe12f8119399928db1ae26adc71dde14
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Feb 12 10:20:42 2011 -0500
-
- Allow specification of the minimum supported iOS version.
-
-commit 71c792f51bcf3e2f334e5ea1fb1a8b667cb3aedb
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 12 09:33:11 2011 -0500
-
- rc4
-
-commit 7c7c9f327299331022f6000603a35f2310dfe308
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Feb 12 09:29:29 2011 -0500
-
- ungccify parts of the build
-
-commit ed62e48b95a0fa60b685f647cb73c9e190eec35c
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 11 12:23:58 2011 -0500
-
- Fix permissions
-
-commit 17d9e9e68ddb1b915a0b9751713033861b598575
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 11 12:23:20 2011 -0500
-
- Use newer autotools. Only build debug.c when --enable-debug.
-
-commit 6972a4ffda75761eaab7dfbe0fb1516b255e8e0c
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 11 07:32:51 2011 -0500
-
- Fix xlc build on AIX
-
-commit 1833aa0fb9831eb0725b63e35886c0f6d35df480
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Feb 11 07:11:04 2011 -0500
-
- sparc ABI test fix.
-
-commit f1fb139b4e283fffdcf205a903943d5e9d2bb2a2
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 9 18:30:02 2011 -0500
-
- Fix tests
-
-commit 5cb470331d181c84d5d621e88868327a324a5898
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 9 15:23:06 2011 -0500
-
- Fix permissions
-
-commit 269deef6dbbb426695919d3398357fada3bb288c
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 9 15:22:23 2011 -0500
-
- rc3
-
-commit 42695e72504f647444b8e8e9b90bd24f1e3220e1
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 9 15:12:35 2011 -0500
-
- Fix IRIX support
-
-commit a6e56b97f62a3feeb3301c24a2e4cae55e546021
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 9 15:00:42 2011 -0500
-
- Add powerpc64-*-darwin* support
-
-commit 747d6c32d4abb07c10c3a1f93579c3929aaa2487
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 9 14:56:23 2011 -0500
-
- Add Interix support
-
-commit eab6e41cde382aa07de6c011d514a14c0d62eb47
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 9 10:15:02 2011 -0500
-
- Remove README.markdown form libffi-ios
-
-commit 69dbe845f4ee3e6ce8999f17a1e4f2179ef7da89
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 9 07:38:43 2011 -0500
-
- Fix xfails
-
-commit f498318c07b95137fe259d86bdbe15347588b84a
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 9 06:26:46 2011 -0500
-
- Update README for iOS again
-
-commit 630b9c0ac43c7edcbfd892e23c09fb26724f4ac0
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 9 06:24:23 2011 -0500
-
- Update to rc2
-
-commit 0cad4386fa4c9ea5f8ca88b16247db4e5c8fea90
-Author: Anthony Green <green@moxielogic.com>
-Date: Wed Feb 9 06:11:46 2011 -0500
-
- Add ChangeLog entry. Fix copyright headers.
-
-commit 09cb76f2645bd2c151846e9249d8ea707ba01e8c
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 20:39:51 2011 -0500
-
- Add missing change
-
-commit 2e3a48ccdd54340983c46a29a0b41985e3e789ac
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 20:37:26 2011 -0500
-
- Fix make dist
-
-commit 5e4814d9928e236a2a4afe84d6e1d4fdaa473206
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 19:46:28 2011 -0500
-
- fix permissions
-
-commit 5c0cc6f1536aa1738795a97303810a823c7fa2cb
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 19:45:59 2011 -0500
-
- 3.0.10rc1
-
-commit 857fe3de46d2286afa2fe772920ecf4aefa1688f
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 19:39:20 2011 -0500
-
- Clean ups
-
-commit e2214f8adb5577c247452e2cc9f4cbe304d7ca9f
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 19:22:56 2011 -0500
-
- Update README
-
-commit 1106229a5721a659da5c231ec0e8211119615394
-Merge: bc9d0be f6ab3ed
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 19:20:09 2011 -0500
-
- Add iOS support
-
-commit bc9d0be2958ce475757f34dd2c878948aa77a39f
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 17:04:26 2011 -0500
-
- 3.0.10rc0 changes
-
-commit 3b836249feae6d08d3e6887486e4b9961ddafa09
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 14:28:59 2011 -0500
-
- Rebase from GCC
-
-commit a26e3940619faeba6de54824c9540c90b1aab513
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 13:56:12 2011 -0500
-
- copyright updates patch
-
-commit b8099539f00e224107594101e9760b6dc081a056
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 13:50:43 2011 -0500
-
- Fix msvcc.sh botch
-
-commit dc411e8f99113a34656bfd2d3ae51259972488cc
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 10:49:29 2011 -0500
-
- Fix HP-UX build
-
-commit 404585d1348e30ac58203bbd876d9131e5aed874
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 10:44:36 2011 -0500
-
- Fix sparc v8 aggregate type returns for sun's compiler
-
-commit 19ce713188e193e4522740d24c20170411883d2d
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 10:34:23 2011 -0500
-
- grammar fix
-
-commit 89284fe55f1a8ad3bddbea796ee00d0e3ba411ce
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 10:19:19 2011 -0500
-
- Fix AIX build with IBM XLC
-
-commit ba022c338af97cb18d9f8ed5a607fd483a61c09c
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 10:12:48 2011 -0500
-
- fix win64-underscore patch
-
-commit 097e5f3924ee92a3ba6cd72f787da8a3eb14fea3
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 10:11:00 2011 -0500
-
- x86 pcrel test part 2
-
-commit ed2c518d960b91d444be74e5a55779a9c4602f3b
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 10:10:07 2011 -0500
-
- x86 pcrel test
-
-commit 0e5843995f46900ef212531281e08b224464f413
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Feb 8 07:52:40 2011 -0500
-
- Refresh from GCC
-
-commit 5b9cd52784339a42e417174a55e310e214d435f9
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Nov 22 15:19:57 2010 -0500
-
- win64-underscore patch
-
-commit 2db72615b50eb5c0f29725c02c740a2f0d7fc7d9
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Nov 21 10:50:56 2010 -0500
-
- Rebase
-
-commit f6ab3edc23dc8fc7c47a31c896044150c23f04b5
-Author: Landon Fuller <landonf@plausible.coop>
-Date: Wed Oct 27 19:34:51 2010 -0400
-
- Include the license header in the generated output.
-
-commit cef619462887fa0f360e3ee702d1e04f112b5b38
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Wed Oct 27 13:59:30 2010 -0400
-
- Add missing copyright/license header.
-
-commit 53f387b203413c9aa6e31f49dbb70d37d816330b
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 19:57:17 2010 -0700
-
- Minor README fix.
-
-commit 4fbcb5b5fbce11f4b168060e00639db33c85b75b
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 19:50:37 2010 -0700
-
- Minor README fix.
-
-commit 8e7652ef6acab5db7a29f786686a54f05cdbdc7d
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 19:49:39 2010 -0700
-
- Add a libffi-ios-specific github README.
-
-commit 83038cf24aa1a92b62b91ffee1dcc25d79243484
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 14:36:45 2010 -0700
-
- Implement FFI_EXEC_TRAMPOLINE_TABLE allocator for iOS/ARM.
-
- This provides working closure support on iOS/ARM devices where
- PROT_WRITE|PROT_EXEC is not permitted. The code passes basic
- smoke tests, but requires further review.
-
-commit b00ff3e98fdde622cef617030e14d5356dff988f
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 14:22:26 2010 -0700
-
- Rename the generated symbol
-
-commit da2773e02ab26cc11a7fe87e985599f35cdf0649
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 14:21:37 2010 -0700
-
- Modify the ffi_closure structures to hold table/table entry pointers instead of a code buffer.
-
-commit 01d71b7bed41844f80cb9feef20dcc5ece5ba2d0
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 14:21:14 2010 -0700
-
- Regenerated the autoconf script
-
-commit 19afda0069c42e51c81dca7b10a5cf884b4cdce0
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 14:20:52 2010 -0700
-
- Enable AC_SUBST for FFI_EXEC_TRAMPOLINE_TABLE
-
-commit 9e1196444e78aef20028c18891f44ebe39a815fd
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 10:43:06 2010 -0700
-
- Add a hard-coded FFI_EXEC_TRAMPOLINE_TABLE arm implementation.
-
- This implements support for re-mapping a shared table of executable
- trampolines directly in front of a writable configuration page, working
- around PROT_WRITE restrictions for sandboxed applications on Apple's
- iOS.
-
- This implementation is for testing purposes; a proper allocator is still
- necessary, and ARM-specific code needs to be moved out of
- src/closures.c.
-
-commit f38364b399184e682fc3e785084bd497827bc5af
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 10:42:36 2010 -0700
-
- Fix symbol prefix for ffi_closure_SYSV_inner on Darwin.
-
-commit 36849e7716b77aa25e4175d1f4be1b93dbf47aac
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 09:35:04 2010 -0700
-
- Whitespace/comment fixes.
-
-commit b764162526854686e579a48b6ac5981f4eb886a3
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 09:04:34 2010 -0700
-
- Fix the script name (build-iphone.sh -> build-ios.sh)
-
-commit a3d9aa85013341451ea97766485b7a11852d32b2
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 09:03:52 2010 -0700
-
- Update the autogenerated autoconf/automake files.
-
-commit c71480eaf839f26bbdfcd8965f65ac4d8defddc0
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 09:02:05 2010 -0700
-
- Update automake/autoconf to conditionally build src/arm/trampoline.S if FFI_EXEC_TRAMPOLINE_TABLE is enabled.
-
-commit 9af9291b73bc5e27ecd949bec8157f20426d65b8
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 08:52:33 2010 -0700
-
- Add the trampoline table generated by gentramp.sh
-
-commit 68ce0c383ece84f69945d1c8c3fed03f7f9cb5d6
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sun Sep 19 08:38:19 2010 -0700
-
- Add a shell script that generates the ARM trampoline page.
-
- This generates a page of 340 trampolines, aligned within one page. The
- trampolines use pc-relative addressing to reference config data
- (context, jump address) from a page placed directly prior to the
- trampoline page. This can be used on systems -- such as iOS -- that do not
- support writable, executable memory by remapping the executable page
- containing the trampolines directly above a newly allocated writable
- config page.
-
-commit 75af086be8830a8eafe9b1ebda199d788bcb0c62
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Sep 18 18:12:19 2010 -0700
-
- Update autoconf files
-
-commit 1ac92cca9b02ef8d6a769f0de1adccd5c9630355
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Sep 18 18:08:14 2010 -0700
-
- Add autoconf check for W^X platforms that require a trampoline table.
-
- This adds the FFI_EXEC_TRAMPOLINE_TABLE. The flag is enabled for
- arm-apple-darwin, where PROT_EXEC on writable (or formerly writable) pages is
- not permitted for sandboxed binaries.
-
-commit be72fbab29b7190c702d8e1ac3d149855e95879d
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Sep 18 18:02:25 2010 -0700
-
- Use the correct host triple for arm/darwin
-
-commit 70150bdf4509269965c72f2032bf74f285767afe
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Sep 18 16:38:03 2010 -0700
-
- Add missing UNWIND entry; disables .pad on non-EABI targets.
-
-commit 6b452bafaec498df975ba8ac4c99de174e5f74f7
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Sep 18 16:21:32 2010 -0700
-
- Apple assembler support; fixed most gas/ELF-isms.
-
-commit 8ddac835b6f8b54ede764d0ea977dee4c82e2d67
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Sep 18 15:38:06 2010 -0700
-
- Fix placement of the __APPLE__ macro.
-
-commit 69043d02936bb0579ac59b4ee1ed8dec38c38db7
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Sep 18 15:32:08 2010 -0700
-
- Work-around libffi's FP ABI detection.
-
- On iOS, we must use the AAPCS floating point return value calling
- conventions. libffi's ARM implementation will only use these conventions
- if __SOFTFP__ is defined, which is not the case when GCC's
- -mfloat-abi defaults to 'softfp' instead of 'soft'. To work around this
- we manually define __SOFTFP__ for Apple platforms in the ARM-specific
- sysv.S.
-
- See also:
- http://developer.apple.com/library/ios/#documentation/Xcode/Conceptual/iPhoneOSABIReference/Introduction/Introduction.html
- http://infocenter.arm.com/help/topic/com.arm.doc.ihi0042d/IHI0042D_aapcs.pdf
-
-commit a82e6c354ea805114642a6e440abd0832cb1d23f
-Author: Landon Fuller <landonf@bikemonkey.org>
-Date: Sat Sep 18 14:44:24 2010 -0700
-
- Add a stub iOS build script to drive autoconf
-
-commit 84e8de6e9fc19388f6f1102c013b7d0d52940ecc
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Aug 6 01:35:12 2010 -0400
-
- Restore execute permissions
-
-commit 3aeecc9eb1a6feba6549849cdd335c926415a4fc
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Aug 5 15:19:00 2010 -0400
-
- Fix win64-struct-args patch
-
-commit 00d0b59cd13f89ab8b44bd894eb7f0a131fcb472
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Aug 5 14:56:53 2010 -0400
-
- Fix debug build for windows
-
-commit bda487e87064f27965155459a62dc52a744778d0
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Aug 5 09:02:41 2010 -0400
-
- Don't use -safeseh with ml64
-
-commit c1d28ba8d5029795af313ffeb81c97efc6d4c847
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Aug 5 08:48:16 2010 -0400
-
- stdcall-x86-closure-fix
-
-commit 5feacad4a56c85b3f23a267a30b2cf424cd59548
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Aug 5 08:30:04 2010 -0400
-
- define generic symbols carefully
-
-commit 10ea848900bc3018ac213cef52b44cacbe5cbebc
-Author: Anthony Green <green@moxielogic.com>
-Date: Thu Aug 5 08:24:27 2010 -0400
-
- don't copy win64 struct args
-
-commit d14178be4c49c3ada44a9fe9efe11d444372ddab
-Author: Anthony Green <green@moxielogic.com>
-Date: Fri Jul 23 09:14:00 2010 -0400
-
- FFI_LAST_ABI fix
-
-commit 3f5b1375ab1e2b8e3d593e21b27097a4a50f9b83
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Jul 12 14:39:18 2010 -0400
-
- rebase
-
-commit eaf444eabc4c78703c0f98ac0197b1619c1b1bef
-Author: Anthony Green <green@moxielogic.com>
-Date: Sat Jul 10 08:59:09 2010 -0400
-
- Fix selinux test
-
-commit 630974152247f100ece4d44f10c3721bb4599fbf
-Author: Anthony Green <green@gmachine.(none)>
-Date: Wed May 5 20:14:56 2010 -0400
-
- Micharl Kohler's spelling fixes
-
-commit 9dc9a293f3d4589fcaf02dd4288c8cebaefa508e
-Author: Anthony Green <green@gmachine.(none)>
-Date: Tue Apr 13 10:33:52 2010 -0400
-
- Rebase to latest GCC sources
-
-commit f2c2a4fce9b3eca9f39b4f3545118bc256da4a73
-Author: Anthony Green <green@gmachine.(none)>
-Date: Tue Apr 13 10:19:28 2010 -0400
-
- Remove warnings and add OS/2 support
-
-commit c0b69e57d529e33d18b658cc5572a21e3663247c
-Author: Anthony Green <green@gmachine.(none)>
-Date: Tue Mar 30 08:30:22 2010 -0400
-
- Dan Witte's windows build fixes.
-
-commit 59a259f4d348f593b45f452309f4d020a28051c4
-Author: Anthony Green <green@gmachine.(none)>
-Date: Mon Mar 15 05:57:51 2010 -0400
-
- Remove junk file
-
-commit 3de1eb36d37a66829e606421939874d0d60d816d
-Author: Anthony Green <green@gmachine.(none)>
-Date: Mon Mar 15 05:57:24 2010 -0400
-
- fix-comments patch
-
-commit c3813b6d7f8a777700f4c5862190c0db148d4de8
-Author: Anthony Green <green@gmachine.(none)>
-Date: Tue Jan 26 16:48:56 2010 -0500
-
- Rebuild Makefiles with automake 1.11.1 for CVE-2009-4029.
-
-commit 8d27f68baa365bf883b6053c5f6bc819646d5434
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Jan 15 11:35:37 2010 -0500
-
- Mention recent changes in README
-
-commit ff3cd68b8cf2d9a28cad7aa9beff46236eacec8c
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Jan 15 11:27:24 2010 -0500
-
- Add msvc.sh wrapper
-
-commit cadeba6cb53414a1253582f1719c286665de7b6c
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Jan 15 10:46:51 2010 -0500
-
- Microsoft Visual C port
-
-commit 0739e7dc00db766eb64f502ec4137b817638c9a1
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Jan 15 09:48:33 2010 -0500
-
- Add x86 Sun Studio compiler support
-
-commit edfdfd2e85b8d01d2455934f1d7f4d7eb2f3cf1c
-Author: Anthony Green <green@gmachine.(none)>
-Date: Wed Jan 13 02:56:19 2010 -0500
-
- Add closure example doc
-
-commit 7b7a42f221cf171e8d09df34cac6dc1fd8458cc3
-Author: Anthony Green <green@gmachine.(none)>
-Date: Tue Jan 12 09:14:14 2010 -0500
-
- Rebase from GCC
-
-commit 4b18d1f73dc7733137869e4ab5725cb90c1c8fde
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Jan 1 10:24:27 2010 -0500
-
- Add x86-64 MingW to README
-
-commit c3042afaf3f84abbbe9c91bf9bc9896b0d9eb003
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Jan 1 08:08:02 2010 -0500
-
- Reset quilt patches post 3.0.9 merge with GCC
-
-commit b0304e9679bdfec6ac45a57b5c96542697249418
-Author: Anthony Green <green@gmachine.(none)>
-Date: Thu Dec 31 11:32:40 2009 -0500
-
- Update version
-
-commit 2e7e03d014d9c9bf40e97ce75cba089ad052fa6b
-Author: Anthony Green <green@gmachine.(none)>
-Date: Thu Dec 31 07:43:22 2009 -0500
-
- Final updates before 3.0.9
-
-commit aea706c52825c8eee677ffa7fdbdd3aed1725492
-Author: Anthony Green <green@gmachine.(none)>
-Date: Tue Dec 29 10:09:31 2009 -0500
-
- really 3.0.9rc12
-
-commit 0cfe60e9d13f132b88995cfee41f2156344f6fa2
-Author: Anthony Green <green@gmachine.(none)>
-Date: Tue Dec 29 10:06:04 2009 -0500
-
- 3.0.9rc12
-
-commit 14e2e92e8645804b6940b3e96c98e9f7f384a6b2
-Author: Anthony Green <green@gmachine.(none)>
-Date: Sun Dec 27 21:03:33 2009 -0500
-
- 3.0.9rc11
-
-commit 884402787bf8eaf7ec207085037cf8ace2f660ec
-Author: Anthony Green <green@gmachine.(none)>
-Date: Sat Dec 26 12:57:23 2009 -0500
-
- HPUX support and avr32 test fixes.
-
-commit 01c78756aff22efb1f122f8e93e068d7bf2185c7
-Author: Anthony Green <green@gmachine.(none)>
-Date: Sat Dec 26 10:05:18 2009 -0500
-
- 3.0.9rc9
-
-commit 70868464651320268d79c6894db5a50fdc11032a
-Author: Anthony Green <green@gmachine.(none)>
-Date: Sat Dec 26 09:58:03 2009 -0500
-
- Remove xfails for mips and arm
-
-commit 838d4ad920ec85cf5ca3b511221d67f6d9a99024
-Author: Anthony Green <green@gmachine.(none)>
-Date: Sat Dec 26 09:57:27 2009 -0500
-
- Remove a bunch of xfails.
-
-commit 7e37eaaf772f48906e69618c773b0a36c3927de9
-Author: Anthony Green <green@gmachine.(none)>
-Date: Sat Dec 26 07:46:50 2009 -0500
-
- Fix huge_struct for solaris
-
-commit 07cc7a37194bc34064ebed7f2724333a798411c8
-Author: Anthony Green <green@gmachine.(none)>
-Date: Sat Dec 26 07:23:04 2009 -0500
-
- 3.0.9rc8
-
-commit 2b9be16ffabc81326128bc1bbdddff8ddc5d13d3
-Author: Anthony Green <green@gmachine.(none)>
-Date: Sat Dec 26 07:04:45 2009 -0500
-
- 3.0.9rc8
-
-commit 9458d88f676e9a21ab8993a54e16754b11687419
-Author: Anthony Green <green@gmachine.(none)>
-Date: Sat Dec 26 07:02:27 2009 -0500
-
- Rebase from GCC
-
-commit 6a3412417593f068a04dc6163f4269cb295ad5ca
-Author: Anthony Green <green@gmachine.(none)>
-Date: Sat Dec 26 06:51:33 2009 -0500
-
- Add Andreas Schwab's powerpc fix
-
-commit 39c8792ece1043f41f4c395a2ce71f4cf0ff4674
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Dec 25 21:52:28 2009 -0500
-
- 3.0.9rc7
-
-commit 1d04af52e3e24db69f742064694c22f8df5cc70e
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Dec 25 09:50:36 2009 -0500
-
- Updated some mips XFAILs
-
-commit 26e9509c9b7929bc4fcf697071699051a652b1fd
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Dec 25 02:19:23 2009 -0500
-
- Clean up ChangeLog.libffi for older patches.
-
-commit 9c157d3215e4393777f83eb6fa801df6528f40d7
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Dec 25 02:15:40 2009 -0500
-
- Clean up undefine_AC_ARG_VAR_PRECIOUS patch.
-
-commit d22de05b0bfc480766bc1240615ce2830eee71b8
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Dec 25 02:04:23 2009 -0500
-
- Fix patches
-
-commit 1fe3dc7c20dc4dbd8fed0d19c8618027d44ed971
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Dec 25 01:39:00 2009 -0500
-
- Add windows support patch.
-
-commit f7c0bc613a88f7dbc2d18b345c10fa438833c170
-Author: Anthony Green <green@gmachine.(none)>
-Date: Fri Dec 25 01:22:11 2009 -0500
-
- 3.0.9rc6
-
-commit c7fa2da8260258c11ab1dc7ac06fb611a2c1b50f
-Author: Anthony Green <green@gmachine.(none)>
-Date: Thu Dec 24 07:22:44 2009 -0500
-
- 3.0.9rc6
-
-commit da11bece0fde66fc0268db3a01207dda857e25d2
-Author: Anthony Green <green@gmachine.(none)>
-Date: Thu Dec 24 05:34:46 2009 -0500
-
- Release 3.0.9rc5
-
-commit e3399b11edeab546b066bfc18574f3edb905d0dc
-Author: Anthony Green <green@gmachine.(none)>
-Date: Thu Dec 24 01:09:32 2009 -0500
-
- Update README
-
-commit 115ab36fceee69740a01ce49bc27e1908cc237b1
-Author: Anthony Green <green@gmachine.(none)>
-Date: Thu Dec 24 00:22:00 2009 -0500
-
- Update missing changes for 3.0.9r4.
-
-commit f8c7a245bf5a80bd7e730ec03fcad17c8dcfcb07
-Author: Anthony Green <green@gmachine.(none)>
-Date: Wed Dec 23 23:46:22 2009 -0500
-
- Switch to quilt. Rebase to latest GCC.
-
-commit ce806772f02387b9a74f6496a263a368bccd5d59
-Merge: cd98813 dcc1f6b
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Oct 5 00:41:35 2009 -0400
-
- Merge branch 'master' of git@github.com:atgreen/libffi
-
-commit dcc1f6b4f1ffd2713bf68b791a13f85d455c8b1b
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Oct 5 00:29:33 2009 -0400
-
- More clean up.
-
-commit 2829f5941a223b9d851d8ab6318318e6197d7e01
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Oct 5 00:28:03 2009 -0400
-
- Clean up
-
-commit cd98813de517ea64041637e3e78d27a001d6d3b4
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Oct 5 00:25:29 2009 -0400
-
- From Jens Rehsack. Fix for 64-bit AIX.
-
-commit e4a91de766acc47f6c50f13cc11719a65e23ecba
-Author: Anthony Green <green@moxielogic.com>
-Date: Mon Oct 5 00:16:17 2009 -0400
-
- From Abdulaziz Ghuloum. Adds special case for Snow Leopard.
-
-commit 3425a763bcdaadb8b430226f427ec833afdcc96a
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Oct 4 23:57:29 2009 -0400
-
- Fix detection of free/openbsd. From Alexis Ballier.
-
-commit 2340e7a777902de61499d47823ad8d5e0eeb6203
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Oct 4 23:53:17 2009 -0400
-
- AVR support
-
-commit 5cbe2058c128e848446ae79fe15ee54260a90559
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Oct 4 23:53:11 2009 -0400
-
- Initial stand-alone patch.
-
-commit c6dddbd02bad9654ed58cdb0feb360934d105dec
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Oct 4 08:11:33 2009 -0400
-
- Initial commit
-
-commit 5ffc0c37486fb1538bccc0ca7acc807d4f1af932
-Author: Anthony Green <green@moxielogic.com>
-Date: Sun Oct 4 07:58:22 2009 -0400
-
- Update version to 3.0.9rc1. Add more useful things to .gitignore.
-
-commit bd29f83ee9f6fa6b65adee9d3f57834f364d9887
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Sep 29 12:07:26 2009 -0400
-
- Add .gitignore
-
-commit 9474f853f83e3f0167c1b306177321bfcc93e56d
-Author: Anthony Green <green@moxielogic.com>
-Date: Tue Sep 29 11:13:02 2009 -0400
-
- Remove old CVSROOT files.
-
-commit 0c25275ec24bfe2c2c25a000465f0950ef9dd51b
-Author: twall <twall>
-Date: Wed Aug 19 12:57:34 2009 +0000
-
- Apply Dave Korn's cygwin/GCC changes
-
-commit 39228c27ed3f677a95b46380a8d31602b5777e1a
-Author: aph <aph>
-Date: Tue Jun 16 18:00:47 2009 +0000
-
- 2009-06-16 Wim Lewis <wiml@hhhh.org>
-
- * src/powerpc/ffi.c: Avoid clobbering cr3 and cr4, which are
- supposed to be callee-saved.
- * src/powerpc/sysv.S (small_struct_return_value): Fix overrun of
- return buffer for odd-size structs.
-
-commit 5e93cc704d127c2c8ae7f5d2cef621145d43e777
-Author: aph <aph>
-Date: Tue Jun 16 17:41:47 2009 +0000
-
- 2009-06-16 Andreas Tobler <a.tobler@schweiz.org>
-
- PR libffi/40444
- * testsuite/lib/libffi-dg.exp (libffi_target_compile): Add
- allow_stack_execute for Darwin.
-
-commit b509af8959dc371b92392c623522ea6f4946a71d
-Author: aph <aph>
-Date: Tue Jun 16 16:17:52 2009 +0000
-
- 2009-06-16 Andrew Haley <aph@redhat.com>
-
- * configure.ac (TARGETDIR): Add missing blank lines.
- * configure: Regenerate.
-
-commit d57e96dc56ee76fbbb9b59d73aeaa92354db5ecb
-Author: aph <aph>
-Date: Tue Jun 16 09:59:02 2009 +0000
-
- 2009-06-16 Andrew Haley <aph@redhat.com>
-
- * testsuite/libffi.call/cls_align_sint64.c,
- testsuite/libffi.call/cls_align_uint64.c,
- testsuite/libffi.call/cls_longdouble_va.c,
- testsuite/libffi.call/cls_ulonglong.c,
- testsuite/libffi.call/return_ll1.c,
- testsuite/libffi.call/stret_medium2.c: Fix printf format
- specifiers.
- * testsuite/libffi.call/huge_struct.c: Ad x86 XFAILs.
- * testsuite/libffi.call/float2.c: Fix dg-excess-errors.
- * testsuite/libffi.call/ffitest.h,
- testsuite/libffi.special/ffitestcxx.h (PRIdLL, PRIuLL): Define.
-
-commit b01d6d1982c9e020507029bfd5a58a8c60d111fa
-Author: aph <aph>
-Date: Tue Jun 16 09:44:54 2009 +0000
-
- 2009-06-16 Andrew Haley <aph@redhat.com>
-
- * testsuite/libffi.call/err_bad_typedef.c: xfail everywhere.
- * testsuite/libffi.call/err_bad_abi.c: Likewise.
-
-commit 35b6ded138591900a88055a8a8ac1fadc29a76d6
-Author: aph <aph>
-Date: Fri Jun 12 15:29:20 2009 +0000
-
- 2009-06-11 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * testsuite/libffi.call/cls_longdouble_va.c: Add xfail sh*-*-linux-*.
- * testsuite/libffi.call/err_bad_abi.c: Add xfail sh*-*-*.
- * testsuite/libffi.call/err_bad_typedef.c: Likewise.
-
-commit acc46605f2d95d67d69398e7644610f10a157ce3
-Author: aph <aph>
-Date: Fri Jun 12 14:21:28 2009 +0000
-
- 2009-06-12 Andrew Haley <aph@redhat.com>
-
- * ChangeLog.libffi: testsuite/libffi.call/cls_align_sint64.c,
- testsuite/libffi.call/cls_align_uint64.c,
- testsuite/libffi.call/cls_ulonglong.c,
- testsuite/libffi.call/return_ll1.c,
- testsuite/libffi.call/stret_medium2.c: Fix printf format
- specifiers.
- testsuite/libffi.special/unwindtest.cc: include stdint.h.
-
-commit 16d1996ed0797bd7c11aca2b0fe7e7748751aaf6
-Author: twall <twall>
-Date: Thu Jun 11 14:27:42 2009 +0000
-
- update changelog
-
-commit 92a515c33efe91be3cb0258f01c63aff208489c7
-Author: twall <twall>
-Date: Thu Jun 11 14:27:28 2009 +0000
-
- use ffi_closure_alloc instead of stack-based closure
-
-commit e4363160ba9e50167f9ca0a7399d537a1d2cd0ce
-Author: twall <twall>
-Date: Thu Jun 11 14:26:23 2009 +0000
-
- remove unused extern
-
-commit 1dc2781d2ba38f5f000ff70069d617fb21e1d2af
-Author: twall <twall>
-Date: Thu Jun 11 11:36:16 2009 +0000
-
- remove not-yet-applied changelog entries
-
-commit bb27735fe689dac97ec0dc847ed8d3d519620109
-Author: twall <twall>
-Date: Wed Jun 10 10:42:36 2009 +0000
-
- add win64 support
-
-commit b2a54c100c74854a409820817d54617fdda39eb8
-Author: aph <aph>
-Date: Mon Jun 8 16:50:49 2009 +0000
-
- 2009-06-08 Andrew Haley <aph@redhat.com>
-
- * testsuite/libffi.call/err_bad_abi.c: Add xfails.
- * testsuite/libffi.call/cls_longdouble_va.c: Add xfails.
- * testsuite/libffi.call/cls_dbls_struct.c: Add xfail x86_64-*-linux-*.
- * testsuite/libffi.call/err_bad_typedef.c: Add xfails.
-
- * testsuite/libffi.call/stret_medium2.c: Add __UNUSED__ to args.
- * testsuite/libffi.call/stret_medium.c: Likewise.
- * testsuite/libffi.call/stret_large2.c: Likewise.
- * testsuite/libffi.call/stret_large.c: Likewise.
-
-commit 25723e7141f73d3736d7244b980c89d97db852b6
-Author: aph <aph>
-Date: Fri Jun 5 13:03:40 2009 +0000
-
- 2009-06-05 Andrew Haley <aph@redhat.com>
-
- * src/x86/win32.S (_ffi_closure_STDCALL): Import from gcc.
-
-commit 70758199c7cd41f411987360ccb302b497a56dc9
-Author: aph <aph>
-Date: Thu Jun 4 16:29:58 2009 +0000
-
- 2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/powerpc/ffitarget.h: Fix misapplied merge from gcc.
-
-commit e8bb12563f9aa23ddf36fa6a5b92b16b5c3e1a7f
-Author: aph <aph>
-Date: Thu Jun 4 14:59:18 2009 +0000
-
- 2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/mips/o32.S,
- src/mips/n32.S: Fix licence formatting.
-
-commit d66a8e32c3671479e3ce0f6819673e5932ba6b7f
-Author: aph <aph>
-Date: Thu Jun 4 14:43:40 2009 +0000
-
- 2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/x86/darwin.S: Fix licence formatting.
- src/x86/win32.S: Likewise.
- src/sh64/sysv.S: Likewise.
- src/sh/sysv.S: Likewise.
-
-commit 7c3b7fd6b5db746b5b09a718f3044f811372f941
-Author: aph <aph>
-Date: Thu Jun 4 14:39:20 2009 +0000
-
- 2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/sh64/ffi.c: Remove lint directives. Was missing from merge
- of Andreas Tobler's patch from 2006-04-22.
-
-commit 1a2f93a8b362db13638afd9fcb3f2650180bfa17
-Author: aph <aph>
-Date: Thu Jun 4 10:45:51 2009 +0000
-
- 2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/sh/ffi.c: Apply missing hunk from Alexandre Oliva's patch of
- 2007-03-07.
-
-commit 944c95cf7aaaaf7c5fa368cda4673dd38f45020e
-Author: aph <aph>
-Date: Wed Jun 3 17:42:56 2009 +0000
-
- 2009-05-22 Dave Korn <dave.korn.cygwin@gmail.com>
-
- * src/x86/win32.S (_ffi_closure_STDCALL): New function.
- (.eh_frame): Add FDE for it.
-
- 2009-05-22 Dave Korn <dave.korn.cygwin@gmail.com>
-
- * configure.ac: Also check if assembler supports pc-relative
- relocs on X86_WIN32 targets.
- * configure: Regenerate.
- * src/x86/win32.S (ffi_prep_args): Declare extern, not global.
- (_ffi_call_SYSV): Add missing function type symbol .def and
- add EH markup labels.
- (_ffi_call_STDCALL): Likewise.
- (_ffi_closure_SYSV): Likewise.
- (_ffi_closure_raw_SYSV): Likewise.
- (.eh_frame): Add hand-crafted EH data.
-
- 2008-11-21 Eric Botcazou <ebotcazou@adacore.com>
-
- * src/sparc/ffi.c (ffi_prep_cif_machdep): Add support for
- signed/unsigned int8/16 return values.
- * src/sparc/v8.S (ffi_call_v8): Likewise.
- (ffi_closure_v8): Likewise.
-
- 2008-03-26 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/sysv.S: Add .note.GNU-stack on Linux.
- * src/sh64/sysv.S: Likewise.
-
- 2008-03-26 Daniel Jacobowitz <dan@debian.org>
-
- * src/arm/sysv.S: Fix ARM comment marker.
-
-commit 00fa972430bb1535a4b34bf029ebcad500027b0c
-Author: twall <twall>
-Date: Sat Dec 27 16:59:05 2008 +0000
-
- properly glob-match
-
-commit f5179e6794ac35af26fe86e468b8508a7a570c55
-Author: twall <twall>
-Date: Fri Dec 26 19:06:28 2008 +0000
-
- Mark XFAIL on longdouble tests for x86_64/mingw
-
-commit 80e2b5a749208c8a18f994ec5bee84594d051cc8
-Author: twall <twall>
-Date: Mon Dec 22 15:21:15 2008 +0000
-
- clean up tests for win64 use
-
-commit 7063d9996f742576095c7b0eb5016c0f9a670aec
-Author: green <green>
-Date: Fri Dec 19 16:13:46 2008 +0000
-
- Version 3.0.8 with x86-solaris support
-
-commit bdfeb13f0df0a63b19d62597517237b54d92228b
-Author: green <green>
-Date: Fri Dec 19 15:47:44 2008 +0000
-
- Bump to 3.0.7
-
-commit 69205de17d6ac4c11d4ba92d6a5b40a0c5f246b2
-Author: green <green>
-Date: Thu Jul 24 18:03:48 2008 +0000
-
- Many test fixes (failures due to excessive compiler warnings).
-
-commit 260d513fea00b3613fe957a44a157fe72c4ca29e
-Author: green <green>
-Date: Thu Jul 17 13:13:52 2008 +0000
-
- Version 3.0.6. sh/sh64 fixes.
-
-commit 3704031875feabb74e3655ed03cff4c2b3c76ac6
-Author: green <green>
-Date: Thu Apr 3 18:57:57 2008 +0000
-
- Rev 3.0.5.
-
-commit 8406f5f48f7f58a1c982a93a95d521cf82b3241f
-Author: green <green>
-Date: Thu Apr 3 18:57:34 2008 +0000
-
- 3.0.5
-
-commit 23a9e73212b62f9684cedb0ce70e92c59cfdaffa
-Author: green <green>
-Date: Wed Mar 5 00:07:02 2008 +0000
-
- 2008-03-04 Anthony Green <green@redhat.com>
- Blake Chaffin
- hos@tamanegi.org
-
- * testsuite/libffi.call/cls_align_longdouble_split2.c
- testsuite/libffi.call/cls_align_longdouble_split.c
- testsuite/libffi.call/cls_dbls_struct.c
- testsuite/libffi.call/cls_double_va.c
- testsuite/libffi.call/cls_longdouble.c
- testsuite/libffi.call/cls_longdouble_va.c
- testsuite/libffi.call/cls_pointer.c
- testsuite/libffi.call/cls_pointer_stack.c
- testsuite/libffi.call/err_bad_abi.c
- testsuite/libffi.call/err_bad_typedef.c
- testsuite/libffi.call/huge_struct.c
- testsuite/libffi.call/stret_large2.c
- testsuite/libffi.call/stret_large.c
- testsuite/libffi.call/stret_medium2.c
- testsuite/libffi.call/stret_medium.c: New tests from Apple.
-
-commit 429e37d3ad653e52e75bf725c883ab79e859f89a
-Author: green <green>
-Date: Thu Feb 28 04:50:19 2008 +0000
-
- clicky
-
-commit 51e79c428348c033314f54bcb30f7e388c59e347
-Author: green <green>
-Date: Thu Feb 28 04:47:35 2008 +0000
-
- getclicky
-
-commit affcab04e280efeace45a72c4dc6152c0e4f1b7f
-Author: green <green>
-Date: Tue Feb 26 19:01:53 2008 +0000
-
- 2008-02-26 Jakub Jelinek <jakub@redhat.com>
- Anthony Green <green@redhat.com>
-
- * src/alpha/osf.S: Add .note.GNU-stack on Linux.
- * src/s390/sysv.S: Likewise.
- * src/powerpc/linux64.S: Likewise.
- * src/powerpc/linux64_closure.S: Likewise.
- * src/powerpc/ppc_closure.S: Likewise.
- * src/powerpc/sysv.S: Likewise.
- * src/x86/unix64.S: Likewise.
- * src/x86/sysv.S: Likewise.
- * src/sparc/v8.S: Likewise.
- * src/sparc/v9.S: Likewise.
- * src/m68k/sysv.S: Likewise.
- * src/ia64/unix.S: Likewise.
- * src/arm/sysv.S: Likewise.
-
-commit 59689d5522c159a3ac967adb6b891cf5f22c890f
-Author: green <green>
-Date: Tue Feb 26 17:40:51 2008 +0000
-
- 2008-02-26 Anthony Green <green@redhat.com>
- Thomas Heller <theller@ctypes.org>
-
- * src/x86/ffi.c (ffi_closure_SYSV_inner): Change C++ comment to C
- comment.
-
-commit b13c84cf4668828ff8429ba4a2f94cd1eb574ae0
-Author: green <green>
-Date: Tue Feb 26 17:38:15 2008 +0000
-
- 2008-02-26 Anthony Green <green@redhat.org>
- Thomas Heller <theller@ctypes.org>
-
- * include/ffi.h.in: Change void (*)() to void (*)(void).
-
-commit 265289f679ffd24a88ae1aa2cef0e4aa14703cd8
-Author: green <green>
-Date: Tue Feb 26 17:34:36 2008 +0000
-
- 2008-02-26 Anthony Green <green@spindazzle.org>
-
- * src/alpha/ffi.c: Change void (*)() to void (*)(void).
- src/alpha/osf.S, src/arm/ffi.c, src/frv/ffi.c, src/ia64/ffi.c,
- src/ia64/unix.S, src/java_raw_api.c, src/m32r/ffi.c,
- src/mips/ffi.c, src/pa/ffi.c, src/pa/hpux32.S, src/pa/linux.S,
- src/powerpc/ffi.c, src/powerpc/ffi_darwin.c, src/raw_api.c,
- src/s390/ffi.c, src/sh/ffi.c, src/sh64/ffi.c, src/sparc/ffi.c,
- src/x86/ffi.c, src/x86/unix64.S, src/x86/darwin64.S,> src/x86/ffi64.c: Ditto.
-
-commit fb5036cd6d0f909918e90f7d2d9fd80d46682d5d
-Author: green <green>
-Date: Sun Feb 24 17:25:25 2008 +0000
-
- fix date
-
-commit 40bec108e7d0181e6c9928aa7a33187bcc0f3d6f
-Author: green <green>
-Date: Sun Feb 24 17:25:02 2008 +0000
-
- New release
-
-commit b922048fa82ea109a4af269ee47bbc2a586bbac2
-Author: green <green>
-Date: Sun Feb 24 17:24:00 2008 +0000
-
- 2008-02-24 Anthony Green <green@spindazzle.org>
-
- * configure.ac: Accept openbsd*, not just openbsd.
- Bump version to 3.0.4.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision.
- * README: Update for new release.
-
-commit affca4b92d06e5554784c7e9b233029ef83f7d8a
-Author: green <green>
-Date: Fri Feb 22 21:53:29 2008 +0000
-
- sync readme with web page.
-
-commit 3e53d8752ea74859b4c64fbbf935e62a937c4d78
-Author: green <green>
-Date: Fri Feb 22 21:52:38 2008 +0000
-
- New release
-
-commit 4d92f6c8e78fe084be65f3e8b58b859901ba796d
-Author: green <green>
-Date: Fri Feb 22 21:49:46 2008 +0000
-
- 2008-02-22 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 3.0.3.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision.
- * README: Update for new release. Clean up test docs.
-
-commit 0e185fa11a01f816824ba2687ed3715ab6219bef
-Author: green <green>
-Date: Fri Feb 22 21:43:18 2008 +0000
-
- Update configure script.
-
-commit f73986bd211cfbbaa593d1309504d0dc68626191
-Author: green <green>
-Date: Fri Feb 22 21:40:53 2008 +0000
-
- 2008-02-22 Bjoern Koenig <bkoenig@alpha-tierchen.de>
- Andreas Tobler <a.tobler@schweiz.org>
-
- * configure.ac: Add amd64-*-freebsd* target.
- * configure: Regenerate.
-
-commit 0208f68fe5de30c33e7f70ebc281635917013f5a
-Author: green <green>
-Date: Fri Feb 22 21:15:44 2008 +0000
-
- 2008-02-22 Thomas Heller <theller@ctypes.org>
-
- * configure.ac: Add x86 OpenBSD support.
- * configure: Rebuilt.
-
-commit 01adb0e638a86cf0d5e668ed8e08be9b0cd2505f
-Author: green <green>
-Date: Thu Feb 21 16:17:26 2008 +0000
-
- Fix README.
-
-commit 1edd4563225981a14f7d4fb9919b1ed88e38082f
-Author: green <green>
-Date: Thu Feb 21 13:39:01 2008 +0000
-
- 3.0.2
-
-commit c9b542800864e2204db6e83f3843a17813ba6165
-Author: green <green>
-Date: Thu Feb 21 13:36:43 2008 +0000
-
- add missing file
-
-commit d5fa5633d5c8d3c212a2267cfa38fba4091baa2c
-Author: green <green>
-Date: Thu Feb 21 13:36:19 2008 +0000
-
- 2008-02-21 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 3.0.2.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision.
- * README: Update for new release.
-
- 2008-02-21 Björn König <bkoenig@alpha-tierchen.de>
-
- * src/x86/freebsd.S: New file.
- * configure.ac: Add x86 FreeBSD support.
- * Makefile.am: Ditto.
-
-commit ac35bfc6fcadd8880c1efce36724820f9074b318
-Author: green <green>
-Date: Sat Feb 16 01:03:56 2008 +0000
-
- Updated
-
-commit f7942975fee7b0162647dd79e2652615b737e98e
-Author: green <green>
-Date: Sat Feb 16 01:02:00 2008 +0000
-
- 2008-02-15 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 3.0.1.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision.
- * README: Update for new release.
-
- 2008-02-15 David Daney <ddaney@avtrex.com>
-
- * src/mips/ffi.c: Remove extra '>' from include directive.
- (ffi_prep_closure_loc): Use clear_location instead of tramp.
-
-commit 59aa6bb1bfc86a610ac1a8b123443efd75854dd1
-Author: green <green>
-Date: Fri Feb 15 20:52:26 2008 +0000
-
- Add more platforms.
-
-commit 45a45ab99074448be0ae1a8d2ade50d28b60f8de
-Author: green <green>
-Date: Fri Feb 15 19:16:36 2008 +0000
-
- 3.0 notes
-
-commit 4db74cbea888c9f1251b85baf00d99b83d3b994d
-Author: green <green>
-Date: Fri Feb 15 19:10:26 2008 +0000
-
- Update
-
-commit c3e1101ffabf44d8a2ee46e03ba9ab582050a825
-Author: green <green>
-Date: Fri Feb 15 18:43:40 2008 +0000
-
- 2008-02-15 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 3.0.0,
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
-
- 2008-02-15 David Daney <ddaney@avtrex.com>
-
- * src/mips/ffi.c (USE__BUILTIN___CLEAR_CACHE):
- Define (conditionally), and use it to include cachectl.h.
- (ffi_prep_closure_loc): Fix cache flushing.
- * src/mips/ffitarget.h (_ABIN32, _ABI64, _ABIO32): Define.
-
-commit 7e0cc12e9233ad285db41ce8dbdda61ed2a7fb06
-Author: green <green>
-Date: Fri Feb 15 15:51:03 2008 +0000
-
- New release
-
-commit 2d7dc885ec40d53866f29984d595511942c8b686
-Author: green <green>
-Date: Fri Feb 15 15:30:26 2008 +0000
-
- * man/ffi_call.3, man/ffi_prep_cif.3, man/ffi.3:
- Update dates and remove all references to ffi_prep_closure.
- * configure.ac: Bump version to 2.99.9.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
-
-commit a0525f03eeaaed33b1eac80e0c016455cee3615d
-Author: green <green>
-Date: Fri Feb 15 15:14:30 2008 +0000
-
- New release.
-
-commit 2b30dfb3146ee26ad956d00ee05eb835ca1a95b4
-Author: green <green>
-Date: Fri Feb 15 15:12:43 2008 +0000
-
- * man/ffi_prep_closure.3: Delete.
- * man/Makefile.am (EXTRA_DIST): Remove ffi_prep_closure.3.
- (man_MANS): Ditto.
- * man/Makefile.in: Rebuilt.
- * configure.ac: Bump version to 2.99.8.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
-
-commit bf41e64840ebcb6cc31a6f028253c1fde82705d8
-Author: green <green>
-Date: Fri Feb 15 01:56:50 2008 +0000
-
- Update.
-
-commit 4d39ddee677bbb61d621893b91e11eac5e7c4af7
-Author: green <green>
-Date: Fri Feb 15 01:24:06 2008 +0000
-
- * configure.ac: Bump version to 2.99.7.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * include/ffi.h.in LICENSE src/debug.c src/closures.c
- src/ffitest.c src/s390/sysv.S src/s390/ffitarget.h
- src/types.c src/m68k/ffitarget.h src/raw_api.c src/frv/ffi.c
- src/frv/ffitarget.h src/sh/ffi.c src/sh/sysv.S
- src/sh/ffitarget.h src/powerpc/ffitarget.h src/pa/ffi.c
- src/pa/ffitarget.h src/pa/linux.S src/java_raw_api.c
- src/cris/ffitarget.h src/x86/ffi.c src/x86/sysv.S
- src/x86/unix64.S src/x86/win32.S src/x86/ffitarget.h
- src/x86/ffi64.c src/x86/darwin.S src/ia64/ffi.c
- src/ia64/ffitarget.h src/ia64/ia64_flags.h src/ia64/unix.S
- src/sparc/ffi.c src/sparc/v9.S src/sparc/ffitarget.h
- src/sparc/v8.S src/alpha/ffi.c src/alpha/ffitarget.h
- src/alpha/osf.S src/sh64/ffi.c src/sh64/sysv.S
- src/sh64/ffitarget.h src/mips/ffi.c src/mips/ffitarget.h
- src/mips/n32.S src/mips/o32.S src/arm/ffi.c src/arm/sysv.S
- src/arm/ffitarget.h src/prep_cif.c: Update license text.
-
-commit d58b032b41a12bd3d72148da6822ab59dd698ff9
-Author: green <green>
-Date: Fri Feb 15 00:59:25 2008 +0000
-
- New release
-
-commit 91e5478df6d5ac63efbb10f025807b4606afab56
-Author: green <green>
-Date: Fri Feb 15 00:50:30 2008 +0000
-
- Update supported platforms. Bump version.
-
-commit bd0768f877c8f7fd0d36af2191b203d4d057b1ce
-Author: green <green>
-Date: Fri Feb 15 00:45:33 2008 +0000
-
- * configure.ac: Bump version to 2.99.5.
- * configure: Rebuilt.
- * Makefile.am (EXTRA_DIST): Add darwin64.S
- * Makefile.in: Rebuilt.
- * testsuite/lib/libffi-dg.exp: Remove libstdc++ bits from GCC tree.
- * LICENSE: Update WARRANTY.
-
-commit 49d345f767bd2cfee951bceaab6a1a07986cf293
-Author: green <green>
-Date: Thu Feb 14 23:43:27 2008 +0000
-
- update license reference
-
-commit 12ac48fc79b515db7c9accd9fcaa87b0dcefccdb
-Author: green <green>
-Date: Thu Feb 14 23:42:08 2008 +0000
-
- Update WARRANTY
-
-commit 6b91c41da87e78552f2990dfc504a0a3349f340b
-Author: green <green>
-Date: Thu Feb 14 23:38:27 2008 +0000
-
- fix tarball reference
-
-commit 2b59579e3533334bee4788e076b4e520c2ab518c
-Author: green <green>
-Date: Thu Feb 14 23:35:58 2008 +0000
-
- First update in 5 years!
-
-commit 6cbdf3f3a3777a93382a2d508ddef1c353ff0955
-Author: green <green>
-Date: Thu Feb 14 22:44:06 2008 +0000
-
- Fix .pc file bug and bump version
-
-commit 1d1dc81104b209df3cfef0840735c59efae2f655
-Author: green <green>
-Date: Thu Feb 14 22:03:37 2008 +0000
-
- Add man files and info file. Update README. Tag as 2.99.3.
-
-commit f045a2367f793fa8b01534cf2e25bcc46afc8fa1
-Author: tromey <tromey>
-Date: Thu Feb 14 20:46:57 2008 +0000
-
- Move entry from ChangeLog to ChangeLog.libffi
-
-commit 6257f07d1a9efd27fa83639cfba281f5d3188731
-Author: tromey <tromey>
-Date: Thu Feb 14 20:33:17 2008 +0000
-
- * aclocal.m4, Makefile.in, configure, fficonfig.h.in: Rebuilt.
- * mdate-sh, texinfo.tex: New files.
- * Makefile.am (info_TEXINFOS): New variable.
- * doc/libffi.texi: New file.
- * doc/version.texi: Likewise.
-
-commit 4232af563c5509c3760a33e3684a2b958be755e1
-Author: green <green>
-Date: Thu Feb 14 16:19:21 2008 +0000
-
- * Makefile.am (AM_CFLAGS): Don't compile with -D.
- (lib_LTLIBRARIES): Define.
- (toolexeclib_LIBRARIES): Undefine.
- * Makefile.in: Rebuilt.
- * configure.ac: Reset version to 2.99.1.
- * configure.in: Rebuilt.
-
-commit 961543615c31f092b578a4b4cda914db64f9d0fa
-Author: green <green>
-Date: Thu Feb 14 15:57:40 2008 +0000
-
- Fix typo.
-
-commit aeb0abab87222f637fbf352d4effd3b76b52ed26
-Author: green <green>
-Date: Thu Feb 14 15:54:27 2008 +0000
-
- * libffi.pc.in: Usse @PACKAGE_NAME@ and @PACKAGE_VERSION@.
- * configure.ac: Reset version to 2.99.1.
- * configure.in: Rebuilt.
- * Makefile.am (EXTRA_DIST): Add ChangeLog.libffi.
- * Makefile.in: Rebuilt.
- * LICENSE: Update copyright notice.
-
-commit 77fe243556433eae119d8bd7469bfccdd5bd8a1a
-Author: green <green>
-Date: Thu Feb 14 15:37:00 2008 +0000
-
- Fix make dist again
-
-commit d4970cf4529459bf0f0e43c602cac396786c6802
-Author: green <green>
-Date: Thu Feb 14 15:18:56 2008 +0000
-
- Fix make dist
-
-commit f0b1462f2d3024922ad71421bd5c4311fcb16da5
-Author: green <green>
-Date: Thu Feb 14 15:01:41 2008 +0000
-
- Use pkgconfig. Increment libtool CURRENT version.
-
-commit 27e52f33baa069012a5adb2a3807f9ca1f2165ab
-Author: green <green>
-Date: Sun Feb 3 13:59:48 2008 +0000
-
- Fix header installs when using DESTDIR.
-
-commit fadab28eb6e33fb6dcdd7b9323e147142216d548
-Author: twall <twall>
-Date: Sun Feb 3 12:32:22 2008 +0000
-
- update changelog
-
-commit b5e44c8dfa92c87b99762c303cf5574a16db8f27
-Author: twall <twall>
-Date: Sun Feb 3 01:12:32 2008 +0000
-
- offset from code base address, not data base address
-
-commit f359848d1a995c0e44566d815f218729dc996e22
-Author: green <green>
-Date: Fri Feb 1 21:29:43 2008 +0000
-
- Fix header installs.
-
-commit c30df49e157c7bfc8e19e3f8a72b9464fe225e54
-Author: green <green>
-Date: Fri Feb 1 21:13:55 2008 +0000
-
- Revert my broken changes to twall's patch.
-
-commit 675561bb9aa0732c76698df10dd3007b5d0ec759
-Author: green <green>
-Date: Thu Jan 31 13:44:25 2008 +0000
-
- Fix make dist .
-
-commit abc0bbf3813dc43e23d4c23e6fe794dbf287639b
-Author: green <green>
-Date: Thu Jan 31 11:58:57 2008 +0000
-
- Add Tim Wall's x86 windows patch.
-
-commit e332366d15a31198735b593ec8f7fc0558d783b8
-Author: green <green>
-Date: Wed Jan 30 13:21:02 2008 +0000
-
- Add HJ's -fomit-frame-pointer struct return fix
-
-commit d4204240392af5b7750a08671b08e9c22dff5e93
-Author: green <green>
-Date: Wed Jan 30 12:42:34 2008 +0000
-
- Clean up for new automake.
-
-commit f4932dd020df574637c9fb3fc1bb18e5a8f304cc
-Author: green <green>
-Date: Wed Jan 30 12:40:25 2008 +0000
-
- Fixes to run testsuite
-
-commit 085520ddc8db6a916bfc416b871fcb2d00074d40
-Author: green <green>
-Date: Tue Jan 29 15:16:43 2008 +0000
-
- New files from gcc tree.
-
-commit 77175b3f7234e4875a4ef554ed1fe9fdc4133794
-Author: green <green>
-Date: Tue Jan 29 15:15:20 2008 +0000
-
- Latest gcc svn sources
-
-commit 2544e45a0b2b634053df02da3a2ed9680eeed2a1
-Author: green <green>
-Date: Tue Jan 29 14:28:13 2008 +0000
-
- Install ffitarget.h in $prefix/include.
-
-commit 6002211b1cc4daeb587d054b4f83968bda2c981e
-Author: green <green>
-Date: Tue Jan 29 12:30:10 2008 +0000
-
- Add new files.
-
-commit ccabd2b16be883cd03e5f0cd88ccfdd6ca39239d
-Author: green <green>
-Date: Tue Jan 29 12:28:15 2008 +0000
-
- Merge from gcc
-
-commit e680ecfbfca1da8d1823e48bc89b8375e66e128b
-Author: tromey <tromey>
-Date: Sun Dec 24 23:12:15 2006 +0000
-
- Pulled in libffi from gcc trunk.
- Fixed build and install for standalone use.
-
-commit e7ba08965942ce872fdbc69f70f9848cc3d0bad6
-Author: root <root>
-Date: Sun Jun 4 23:22:24 2006 +0000
-
- sourcware.org
-
-commit 0cd4aa24e21aaa964dfbdebc25ec5c8188049375
-Author: root <root>
-Date: Sun May 30 01:51:57 2004 +0000
-
- Add LockDir
-
-commit 5826120fbd940d26cca76ed2522187505581e1ed
-Author: green <green>
-Date: Tue Nov 4 06:09:08 2003 +0000
-
- Add link to Gianni's web site.
-
-commit 220aa4b27db42d7ffaac5056000d5179f00d5ea3
-Author: jsm <jsm>
-Date: Tue Jan 21 08:07:42 2003 +0000
-
- Newer, better, increased from before! (list of acceptable anon usernames)
-
-commit 1c3adc892cc1403dc4d3d7003a2385899836612e
-Author: green <green>
-Date: Fri Dec 6 01:28:03 2002 +0000
-
- Fixed Cygnus references.
-
-commit 4af66bb62fab9a8e318af3bf01e5486596a0c8d4
-Author: green <green>
-Date: Sun Oct 21 19:18:42 2001 +0000
-
- Testsuite fixes.
-
-commit 5435965f9015ce40584c98d3816c3d05e7de1d21
-Author: green <green>
-Date: Mon Apr 23 00:32:03 2001 +0000
-
- * include/ffi_common.h: Delete, after moving contents to...
- * include/ffi_private.h: Subsume contents of ffi_common.h.
- * include/Makefile.am (noinst_HEADERS): Remove ffi_common.h.
- * include/Makefile.in: Rebuilt.
- * arm/ffi.c, m68k/ffi.c, mips/ffi.c, powerpc/ffi.c, s390/ffi.c,
- ia64/ffi.c: Include ffi_private.h, not ffi_common.h.
- * alpha/ffi.c, sparc/ffi.c, x86/ffi.c: Don't include ffi_common.h.
- * types.c, raw_api.c, java_raw_api.c, prep_cif.c: Don't include
- ffi_common.h.
- * debug.c: Include ffi_private.h instead of ffi_common.h.
-
- * mips/ffi.c (calc_n32_struct_flags): Make static.
- (FIX_ARGP): Remove call to debugging routine ffi_stop_here.
-
- * mips/n32.S: Include ffi_private.h.
- * mips/o32.S: Include ffi_private.h.
-
-commit 6fdb7de0fe3b7385e1fd78812ae69d9b3069d994
-Author: green <green>
-Date: Sun Apr 22 19:38:34 2001 +0000
-
- * README: Update some comments.
-
- * Makefile.am (SUBDIRS): Add include so ffi.h gets installed.
- * Makefile.in: Rebuilt.
-
- * include/ffi.h: Change ALPHA to __alpha__ and SPARC to __sparc__.
- * types.c: Ditto.
- * prep_cif.c (ffi_prep_cif): Ditto.
-
- * alpha/ffi.c, alpha/osf.S, sparc/ffi.c, sparc/v8.S, sparc/v9.S:
- Include ffi_private.h.
-
- * include/ffi_private.h (FFI_TYPE_LAST): Define.
-
-commit bc7144b01b9707ef35f1a2e3e6996e005e82953a
-Author: green <green>
-Date: Sun Apr 22 18:28:36 2001 +0000
-
- Moved files from old home
-
-commit e57279831e20368c1aa1d2b35462b8629be73959
-Author: green <green>
-Date: Sun Apr 22 18:23:47 2001 +0000
-
- These are dead.
-
-commit 7247436b5fe71767b29dc02b4da0fe18b08082e6
-Author: green <green>
-Date: Sun Apr 22 18:22:43 2001 +0000
-
- All these files live somewhere else now.
-
-commit a8b0d40ff908e275028f676870c31d0d70274a98
-Author: green <green>
-Date: Sun Apr 22 18:17:14 2001 +0000
-
- Many changes. Not quite there yet.
-
-commit f893d2273355710a290a26faebf5f12c3a34d0e3
-Author: green <green>
-Date: Sun Apr 22 18:13:22 2001 +0000
-
- Moved m68k files
-
-commit 688ddfeced89cbb9d37b53005e1f7f2b9c78a8d7
-Author: green <green>
-Date: Sun Apr 22 18:12:33 2001 +0000
-
- New, target indepentent, header
-
-commit f9e40776d488d5ecf43b3ae21444a1a2f6eca528
-Author: green <green>
-Date: Sun Apr 22 18:11:57 2001 +0000
-
- Many changes.
-
-commit 8c1d2eb47f6bc314c431b75c85c107e8e43c4a76
-Author: green <green>
-Date: Sun Apr 22 18:10:47 2001 +0000
-
- Many changes
-
-commit 1359dfc6582680a158b3caa3efb7a368da4aa12d
-Author: green <green>
-Date: Sun Apr 22 18:10:20 2001 +0000
-
- Moved ia64 files
-
-commit 6e2de5eee316a4579869aff50c7c5f6f478582d8
-Author: green <green>
-Date: Sun Apr 22 18:08:11 2001 +0000
-
- Moved arm files
-
-commit 8807355af34cba8ffe87aee51152dfccec2771fa
-Author: green <green>
-Date: Mon Apr 9 00:58:38 2001 +0000
-
- Many many updates. Merge from gcc and then some.
-
-commit f7e9f91adec4ff1c2e7a13b3de81d2c5a3f55e7e
-Author: green <green>
-Date: Mon Apr 17 03:32:37 2000 +0000
-
- Mnay fixes.
-
-commit c4860de618f4956283f5c8230a2544e403dfe390
-Author: green <green>
-Date: Mon Apr 17 03:18:46 2000 +0000
-
- Merge from libgcj. Merged patches from net. See ChangeLog for details.
-
-commit c578b58314990c3853429297c38ba14015fec5fa
-Author: jsm <jsm>
-Date: Sat Oct 9 20:18:16 1999 +0000
-
- 1999-10-09 Jason Molenda (jsm@bugshack.cygnus.com)
-
- * CVSROOT/auto_checkout, CVSROOT/commit_prep, CVSROOT/log_accum:
- Deleted; generic versions now used for all repositories.
-
- * CVSROOT/commitinfo, CVSROOT/loginfo: Change pathnames to
- generic versions.
-
- * CVSROOT/checkoutlist: Don't try to check out the removed
- files any longer.
-
-commit acdb20051207fed7652dd9f122f65de5458c474c
-Author: jsm <jsm>
-Date: Sat Oct 9 20:18:15 1999 +0000
-
- 1999-10-09 Jason Molenda (jsm@bugshack.cygnus.com)
-
- * CVSROOT/auto_checkout, CVSROOT/commit_prep, CVSROOT/log_accum:
- Deleted; generic versions now used for all repositories.
-
- * CVSROOT/commitinfo, CVSROOT/loginfo: Change pathnames to
- generic versions.
-
- * CVSROOT/checkoutlist: Don't try to check out the removed
- files any longer.
-
-commit e75be655ceedf7ab24c4e99d75eec9efeb979bc7
-Author: green <green>
-Date: Sun Aug 8 13:16:41 1999 +0000
-
- New configury
-
-commit d6669a0dd5b266005325bbf6d5a8ff34574d809e
-Author: green <green>
-Date: Sun Aug 8 13:05:12 1999 +0000
-
- * include/ffi.h.in: Try to work around messy header problem
- with PACKAGE and VERSION.
-
- * configure: Rebuilt.
- * configure.in: Change version to 2.00-beta.
-
- * fficonfig.h.in: Rebuilt.
- * acconfig.h (FFI_NO_STRUCTS, FFI_NO_RAW_API): Define.
-
- * src/x86/ffi.c (ffi_raw_call): Rename.
-
-commit 4819d52b007934a40d6d29a75ee30e857c4a93ae
-Author: green <green>
-Date: Wed Aug 4 18:02:34 1999 +0000
-
- New file for Kresten's closure work
-
-commit 2dbf801eb427cbf5021a9e1e512b5fc523524700
-Author: green <green>
-Date: Wed Aug 4 18:00:05 1999 +0000
-
- Kresten's closure work. Initial checkin.
-
-commit d170961701b0f2bf7e824d7caba2ebe10002ed84
-Author: green <green>
-Date: Thu Jul 8 14:36:52 1999 +0000
-
- * configure.in: Add x86 and powerpc BeOS configurations.
- From Makoto Kato <m_kato@ga2.so-net.ne.jp>.
-
-commit c7747d976924ec6f2229cbcfbbdb98d364e10de9
-Author: jsm <jsm>
-Date: Wed May 12 23:32:16 1999 +0000
-
- 1999-05-12 Jason Molenda (jsm@bugshack.cygnus.com)
- * index.html: Add links to libffi* mail list archives.
-
-commit dd2aa9a8de22e26df3bbc85d068358641f6202f7
-Author: green <green>
-Date: Thu May 6 05:34:36 1999 +0000
-
- * configure.in: Add warning about this being beta code.
- Remove src/Makefile.am from the picture.
- * configure: Rebuilt.
- * Makefile.am: Move logic from src/Makefile.am. Add changes
- to support libffi as a target library.
- * Makefile.in: Rebuilt.
- * aclocal.m4, config.guess, config.sub, ltconfig, ltmain.sh:
- Upgraded to new autoconf, automake, libtool.
- * README: Tweaks.
- * LICENSE: Update copyright date.
- * src/Makefile.am, src/Makefile.in: Removed.
-
-commit 4e9452abed58a3058ccdb446f96a29d50dda1f34
-Author: green <green>
-Date: Wed May 5 22:06:13 1999 +0000
-
- Updated to new automake, libtool, autoconf - nothing works :-)
-
-commit 6d3b2bddaf4967fba8b8656c01bfc77ec0f2800c
-Author: jsm <jsm>
-Date: Mon Apr 26 15:55:28 1999 +0000
-
- 1999-04-26 Jason Molenda (jsm@bugshack.cygnus.com)
- * index.html: Missed a reference to libffi-discuss@cygnus.com. Fixed.
-
-commit ebc6a9c28af831d3d187af8ff17319f0f309bd98
-Author: jsm <jsm>
-Date: Mon Apr 26 15:53:29 1999 +0000
-
- 1999-04-26 Jason Molenda (jsm@bugshack.cygnus.com)
- * index.html: Change links to ftp directory to point to sourceware
- directory.
- Change mailing list subscription forms to point to sourceware lists.
-
-commit 78ffc52a8b257061348c576ccb6fbbf8b48b0fff
-Author: jsm <jsm>
-Date: Sun Apr 18 01:33:21 1999 +0000
-
- Standard sourceware setup.
-
-commit b4d77e827d7ebef7e57ebcd71e71c15c62f1e0a8
-Author: jsm <jsm>
-Date: Mon Nov 30 11:11:25 1998 +0000
-
- Small typeo. (I wouldn't bother except that it made the sentence hard
- for me to parse on a casual read.)
-
-commit bfb73f08fdc987e37070c5fb0b196fbd28872888
-Author: jsm <jsm>
-Date: Mon Nov 30 10:44:55 1998 +0000
-
- A few cleanups. Most notably, point to the correct subscribe cgi-bin
- script.
-
-commit af8b7f037ccee3b7939ee226a1a2bbc2f057b35c
-Author: green <green>
-Date: Mon Nov 30 06:20:05 1998 +0000
-
- * index.html: Reformatted and updated to reflect hosting on
- sourceware.cygnus.com (new mailing lists, etc).
-
-commit 334f0b060942aff8d26badaf7dde7830450dc5da
-Author: green <green>
-Date: Sun Nov 29 16:56:12 1998 +0000
-
- initial snapshot of documentation
-
-commit 3ab5cb4a1dcc7ecd7e773c97582b0099976c4753
-Author: green <green>
-Date: Sun Nov 29 16:56:10 1998 +0000
-
- Initial revision
-
-commit d2a9eb5a8b7cbc8b769809cad59c82b975c178e2
-Merge: d3782ec bc75c54
-Author: green <green>
-Date: Sun Nov 29 16:48:16 1998 +0000
-
- This commit was generated by cvs2svn to compensate for changes in r7, which
- included commits to RCS files with non-trunk default branches.
-
-commit bc75c54bd311658005b065f1bf201b204c81cbca
-Author: green <green>
-Date: Sun Nov 29 16:48:16 1998 +0000
-
- Import of v1 code.
-
-commit d3782ec8160c644421dcea17b605fec6e328f14e
-Author: jsm <jsm>
-Date: Fri Nov 20 20:18:00 1998 +0000
-
- Send commit messages to mailing lists.
-
-commit 8d8d3843c484c2bb70d8375b2b799f75eb03f709
-Author: jsm <jsm>
-Date: Thu Oct 1 22:08:36 1998 +0000
-
- initial checkin
-
-commit 49634f3bf221cc1939abafc788f7e4e31293fe73
-Author: jsm <jsm>
-Date: Thu Oct 1 22:08:35 1998 +0000
-
- Add standard setup.
-
-commit c64a84c7693f8cd400fb94bba3c9bcfd9ad1fc36
-Author: jsm <jsm>
-Date: Thu Oct 1 22:08:34 1998 +0000
-
- Add readers and standard modules file.
-
-commit 9813273b07fd082da573b3b6bfb8d23809b59eea
-Author: jsm <jsm>
-Date: Thu Oct 1 22:08:33 1998 +0000
-
- initial checkin
+commit 5dcb741f1544c5e18c9dbf96aeb8b61cc556a616
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 23 10:24:58 2019 -0500
+
+ Move nested_struct3 test to closures directory
+
+commit 1aca33301a791f503d943f5e3abe2c720296eb8f
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 23 09:42:04 2019 -0500
+
+ Add missing closing brace
+
+commit d996cb283cf373936498defa902be040ec20455e
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 23 09:00:14 2019 -0500
+
+ Version 3.3
+
+commit c72b82f465148b89f118ee73f8956dafdbac9b65
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 23 08:48:53 2019 -0500
+
+ Remove junk file from dist
+
+commit 642d40ee6ae9a779b3c5ad930785d4b33cf94029
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 23 07:49:58 2019 -0500
+
+ Account for moved test files
+
+commit 049da08a22b0ca6d63d2be6c209da5ac1335365c
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 23 07:44:26 2019 -0500
+
+ Add dejagnu directives accidentally removed
+
+commit 36730f5d87c2a432e1b3bf1a0129fedbf4b0a488
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 22 19:49:38 2019 -0500
+
+ Move closure test to closure directory
+
+commit c88c0e92a9fbb4e69513394682c61aa848a035cc
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 22 19:27:34 2019 -0500
+
+ More more closure tests to the closure test directory
+
+commit a37cc1755cc276b2b9e601b9b112919f8c882a2e
+Merge: 332a539 247a5e7
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 22 18:55:36 2019 -0500
+
+ Merge branch 'master' of github.com:libffi/libffi
+
+commit 332a539e88d26a0524c10a39283a3099d071ca10
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 22 18:54:30 2019 -0500
+
+ Move closure tests so we can easily XFAIL them for some targets
+
+commit 1761a10645dadc0840bf1ff3a4998f9a342e8cad
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 22 18:53:09 2019 -0500
+
+ Remove gccbug detection. GCC is good now.
+
+commit 247a5e7878379b7af33338d51898d7fb9e82e686
+Author: Michael Haubenwallner <michael.haubenwallner@ssi-schaefer.com>
+Date: Fri Nov 22 20:17:58 2019 +0100
+
+ Capture x86-windows host like x86_64-windows (#529)
+
+commit 8e3935fa761d3e6f19ccf5e6733fd40dee637d94
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 22 12:42:26 2019 -0500
+
+ Manual clean-ups, and include the PDF in the source distribution.
+
+commit d01088a5194ff1a2250e7dbee04a9a167b582db7
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 21 05:36:06 2019 -0500
+
+ Mention more major port contributors
+
+commit 970b7fce4f804df57ec582a0220c22eaeccc239a
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 21 05:04:54 2019 -0500
+
+ Update autoconf-archive m4 macros
+
+commit 34a3a661b80c0fa7817c0654ae9fd0686d3b8cd2
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 21 04:59:39 2019 -0500
+
+ Fix formatting of README.
+
+commit 91a7fbe94e3884536cf2eb8e644bc79d6b19c80e
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 20 07:16:41 2019 -0500
+
+ Fix or1k lack-of-g++ checking in testsuite
+
+commit 31543c799a224ef446cef19a2372b054ecad3822
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 20 06:15:55 2019 -0500
+
+ Add work-around for users who manage their own closure memory
+
+ As suggested by DJ
+
+commit bd3a4687c0743076f420dee2a02075fd64fa547e
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 19 17:14:23 2019 -0500
+
+ No C++ for or1k-unknown-elf
+
+commit d6e4f96b482690e6cdaf67a70bb33d1bfe0acd15
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 19 13:36:49 2019 -0500
+
+ No C++ for or1k
+
+commit 497018686d4df0012ea7bf1a4ab41b918b5e65bc
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 19 10:07:16 2019 -0500
+
+ Disable type warnings for or1k.
+
+commit 262cf74fd4003a928ca73e96ef8698546e535c46
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 19 10:06:57 2019 -0500
+
+ No c++ for or1k-elf
+
+commit 54fc80dfd8d608ec718cade762c358b8fd819f38
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 15:20:00 2019 -0500
+
+ Fake TRAVIS_BUILD_DIR
+
+commit 6f734f8a5ff13d106f81741c11c7cb2551706c7f
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 15:13:16 2019 -0500
+
+ Adapt for new old ChangeLog file
+
+commit 27d31130cabfe82683fc0e3e82247fd522f45607
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 15:06:51 2019 -0500
+
+ Fix DEJAGNU variable
+
+commit da1358816e7b02e6f8431e4df336d0934bcabd4c
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 14:54:14 2019 -0500
+
+ Set vars
+
+commit 9a394c24951f3fc5cfbd0ff268278a7b45afc77e
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 14:45:29 2019 -0500
+
+ Remove verbosity
+
+commit 14bfbec0fd312001f7922ee6100cbc3155ae585b
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 14:40:30 2019 -0500
+
+ Pull before running
+
+commit dfa60e5eb44482d45b8c79b815e6b6789e62ce18
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 14:02:33 2019 -0500
+
+ Fix cross builds for or1k
+
+commit a8223271a3d7ff1e8a1553c2a5ed9b4e1a24a774
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 13:59:10 2019 -0500
+
+ More cross build debugging
+
+commit 8c9cf44cb2a2d46ddcb148508fb5350438b4a62b
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 13:47:42 2019 -0500
+
+ Set path to simulator. Add debugging output.
+
+commit 581048f91e9e25e3b17a2906edd8840f35999918
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 13:17:27 2019 -0500
+
+ Be specific when building CI container images
+
+commit bbea6394f9f27de68aac037abb264151d6de9f64
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 13:06:26 2019 -0500
+
+ Capture more or1k hosts
+
+commit 97e3b1fe1a0fbdb43bf28fe6198cb26eaa719c93
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 13:02:44 2019 -0500
+
+ Add test support for or1k. Fix yaml typo.
+
+commit c88f4d2677d4dc6659a1aa6418e636f8fcf9bd9b
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 12:25:51 2019 -0500
+
+ Fix typo for m32r and bfin builds
+
+commit 93c203b347ea7d110355e12f832725f755e10eff
+Merge: d087b59 73dd43a
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 06:35:19 2019 -0500
+
+ Merge branch 'master' of github.com:libffi/libffi
+
+commit d087b595637ebb795c0cec1ff0c4409befb486b7
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 06:34:42 2019 -0500
+
+ Build/test for m32r-elf and bfin-elf
+
+commit b6804d16453890b78844b1b3c1acf16af98cadb8
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Nov 17 09:19:14 2019 -0500
+
+ Mention binary128 long double support for Power
+
+commit 73dd43afc8a447ba98ea02e9aad4c6898dc77fb0
+Author: Samuel Holland <samuel@sholland.org>
+Date: Sun Nov 17 07:22:25 2019 -0600
+
+ IEEE754 binary128 long double support for PowerPC64 (#526)
+
+ * powerpc: Adjust flags to make room for vector types
+
+ * powerpc64 ELFv2 IEEE128 long double support
+
+commit b58bd77236e7d41fc04b4be7edd1c6728626c99b
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 15 11:18:59 2019 -0500
+
+ Re-enable mingw32 tests.
+
+commit 6f221e8269aa16f6b5eec41cfd1d7d90a9fbea0c
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 15 11:06:17 2019 -0500
+
+ Disable wine builds.
+
+commit 09dc0a71a44c95ee0d2f47de94b6b59534c2ce24
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 15 10:19:00 2019 -0500
+
+ Stretch out timeout for test
+
+commit 28a7cc464c21b4955fba28cc55a6f095ddf5838b
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 15 06:07:51 2019 -0500
+
+ Consolidate all of the old ChangeLog files into ChangeLog.old.
+
+commit 86d3d3767a40fe1cae10c419a913dd97e7e6cd23
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 13 10:07:00 2019 -0500
+
+ Don't build aarch64-linux-gnu
+
+commit db198a19375858879dbcc51a443c193efa0b6c0a
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 13 10:05:36 2019 -0500
+
+ Extend timeout for builds.
+
+commit 54af0256a00a40b2218950f93e5415c60f675714
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 13 09:15:05 2019 -0500
+
+ Platform test tweaks
+
+commit 3a7580da73b7f16f275277316d00e3497cbb5a8c
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 13 07:59:18 2019 -0500
+
+ Mark java raw APIs as deprecated.
+
+commit cda60c1a8aec070a7a822c047d89d0f18cf7c5fc
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 13 06:51:44 2019 -0500
+
+ Disable mips64 tests. Fix log grabbing.
+
+commit a34254bdc1dee2857b759a22e657f92aadfa85dc
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 13 06:37:26 2019 -0500
+
+ Re-add wine based testing
+
+commit 9bd3a9742c04d2fac489f236163d7e7fbb1b7568
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 13 06:35:40 2019 -0500
+
+ Add wine-sim.exp for wine-based testing
+
+commit de6df6dce6420d4643598c228b72da4e455a0da7
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 13 06:32:46 2019 -0500
+
+ Fix log file URL extraction. Grab rlgl cli for OSX
+
+commit c8986e871f82b497493d28c36be1a755c2ea6b8d
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 13 06:01:43 2019 -0500
+
+ Fix log name extraction
+
+commit 6630764d244aeb3bc0797d0c3c7ccc79084061a8
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 12 22:56:37 2019 -0500
+
+ Account for shorter ==LOGFILE== string
+
+commit aa975ec3e4ac07bd7dacec18f1c8282baeb7c398
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 12 22:35:47 2019 -0500
+
+ Fix grep matcher
+
+commit 6dd88bc5b3f3d3d975409b7336f4127ae18da4b3
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 12 18:44:27 2019 -0500
+
+ Debug
+
+commit 7e318cf50d8c481957b3be76e508054c70cbdf9b
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 12 17:55:35 2019 -0500
+
+ Pull test logs from cfarm
+
+commit 5123e9cf0193031bdc580cb221427cbd29ba3677
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 12 09:21:57 2019 -0500
+
+ Use rlgl for cfarm test results
+
+commit 486f88f985affa215a9daaadcdc703c8baea9020
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 12 09:20:21 2019 -0500
+
+ Use rlgl for cross builds.
+
+commit 042c6671b0456d17af24d61b79cbd3f9261c3f2b
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 12 09:14:20 2019 -0500
+
+ Always exit build container successfully. Don't test mingw.
+
+commit 82f7f80aa9ac3cd753bcb6d2b88cc930aee72bcc
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 12 08:58:52 2019 -0500
+
+ Run rlgl outside of the build container.
+
+commit 5b297e036e61ad1ecac9c8a3e57895737c55feb7
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 12 05:51:09 2019 -0500
+
+ Don't bother dumping logs. Use rlgl instead.
+
+commit 2a8d88d92d56747101078c5592ab2473e6c5cb29
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 11 21:24:58 2019 -0500
+
+ Fix rlgl usage
+
+commit 3c2b810e99a10f97d1eb6ba485eb09bfdb158084
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 11 21:11:59 2019 -0500
+
+ Test rlgl
+
+commit 2cc11720be0c4d3bbe906be5a4aad3b2dc167072
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 11 16:19:45 2019 -0500
+
+ Debug in-container builds
+
+commit 0de0c6a28006902c203e8dc6629cd9ef35d61e09
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Nov 10 08:20:46 2019 -0500
+
+ Build both iOS and Macosx
+
+commit 4e3e0586efbbc7828c15fb48e49401840beefcdd
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 12:35:27 2019 -0500
+
+ Fix tpyo
+
+commit f764f278160831f7e4d8ee8a48d18f5a7937f742
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 12:17:29 2019 -0500
+
+ Change s390x options
+
+commit 188de63c597f23b0ccdb953b076c8cb0711fbcf0
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 12:03:19 2019 -0500
+
+ Mark xfail for m68k and alpha.
+
+commit 0da221f8094ec504d91b5f88c74e98b8b9aa9eda
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 12:03:01 2019 -0500
+
+ Clean up. Debug s390x cpu support.
+
+commit 7e0fbf41934020c9ff76816fde5000482c7e6a6c
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 11:50:08 2019 -0500
+
+ Try coldfire for m68k builds
+
+commit 6a9fa770a436bbb71dbe8311e75123353e6836cc
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 11:37:25 2019 -0500
+
+ Add GCC_OPTIONS flag
+
+commit eebcbb1113742df7d41fc3d39eca970a026ad1d1
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 11:26:53 2019 -0500
+
+ Compile m68k target for m5208
+
+commit 08cb33ff5824b2ea24b2b62841cca1934a27f36f
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 11:15:13 2019 -0500
+
+ Dump supported CPUs
+
+commit 16c935000d459b1aba9e1f7b48e2c1d7dadc8cf1
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 11:00:09 2019 -0500
+
+ Fix shell script
+
+commit 588e87461fe48441806be4bb5654f058e1c37649
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 10:56:40 2019 -0500
+
+ Print debug output. Use podman when available.
+
+commit 04d14a66ff807a0ac2578ce886ef338aa2066b4d
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 09:23:10 2019 -0500
+
+ Set QEMU_CPU within the build containers
+
+commit 28d9c019dbbf6dea1ed127e1a7de829cece86639
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 7 07:36:11 2019 -0500
+
+ Set QEMU_CPU for m68k
+
+commit 75464caf658f176848db6f48325c5067cdf94a9b
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 6 22:02:11 2019 -0500
+
+ Add alpha and m68k testing
+
+commit 259c497a2f326cc89344766e106cf73e62485a2a
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 6 11:31:17 2019 -0500
+
+ Sett CC and CXX for cross builds
+
+commit d23d3959fdb764984cfb888c5d6aed910926dd5f
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 6 11:21:46 2019 -0500
+
+ autogen before cross building
+
+commit a6dc8ef270c1f022720aedadb6b0d2678d1bc39e
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 6 11:10:59 2019 -0500
+
+ Fix typo. Don't double test.
+
+commit 136a235d3f36408628c0459d8740546acad0ca5a
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 6 10:51:33 2019 -0500
+
+ Use the right cross build container image
+
+commit 92f5309def05c66e6c5034c10d620d6fbc7a1018
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 6 10:49:04 2019 -0500
+
+ Try s390x and sh4 cross builds/tests
+
+commit d4a28fee720c8f389b138b3f7726157fbcb7eaaf
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 6 06:47:05 2019 -0500
+
+ Revert to older test cross compilers
+
+commit 0fb9ee21e68ca3e70cf236a63ba00b5ca32031ff
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 6 06:44:19 2019 -0500
+
+ Use older test compiler. Enable s390x testing.
+
+commit 36d281ab70daf7dcf890df9c3f5bdd76f665bb68
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 6 06:30:52 2019 -0500
+
+ Test cross-builds for hppa-linux-gnu
+
+commit c95cc4b354f24dbbf5776eb297fa036bcbfed252
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 6 06:30:20 2019 -0500
+
+ Reference FFI_BUILDING_DLL
+
+commit 88a76477debe83ed6a75f96394853c891fb1dac4
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Nov 3 06:28:51 2019 -0500
+
+ rc2. hack as per: https://github.com/travis-ci/travis-ci/issues/6934
+
+commit 45ba4aefed15be24fdbaaffec805fb02b1343e0f
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 31 19:07:04 2019 -0400
+
+ Add sparc64-linux-gnu testing back
+
+commit a26323b7e0824f0becaeaffc8d3b700dc09f741c
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 31 15:32:48 2019 -0400
+
+ Don't build sparc. Build mips.
+
+commit f325324818a6aaa9e8a75782d75c412872e6b21c
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 31 14:35:43 2019 -0400
+
+ Test mips64el-linux-gnu
+
+commit 39bad2f396de7885c9569144b5bb6e8a639ac011
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 31 12:33:22 2019 -0400
+
+ Don't run autogen.sh all the time.
+
+commit 82719cbba06c2fc527df156d728341867d86f82c
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 31 12:23:11 2019 -0400
+
+ Test sparc64-linux-gnu on travis
+
+commit 0348d0e4fa585d9a3d9762132a3eee94f918fe3b
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 31 10:53:37 2019 -0400
+
+ Try new cfarm build for power
+
+commit 290bc3164bb0e0b3fb912c457b49e61f9a728eef
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Oct 26 10:13:20 2019 -0400
+
+ Add make_sunver.pl to distribution.
+
+commit a8efc2f7897b439fdf2144329d35fea820498dc7
+Author: Andreas Schwab <schwab@linux-m68k.org>
+Date: Sat Oct 26 14:57:05 2019 +0200
+
+ Fix FFI_STDCALL ABI (#514)
+
+ Even for a stdcall function, the stack alignment is still the
+ responsibility of the caller. Remember the original, not stack-aligned
+ argument size, but align when setting up a stack frame. In
+ ffi_closure_inner, return the true argument size, so that
+ ffi_[go_]closure_STDCALL doesn't adjust too much.
+
+commit ca112537df7b9cdbccad7541aa3cb43b2a2dac9a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Oct 26 07:26:30 2019 -0400
+
+ Add missing build script, make_sunver.pl.
+
+commit 52b066f04fdd81c1037e1cb714a07a2a352bcf9b
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 24 07:03:43 2019 -0400
+
+ Update versions to 3.3-rc1
+
+commit 9b10df3be2d8f81876b7cc90ee5d8833ccdf6b34
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 24 06:41:11 2019 -0400
+
+ Remove some debugging output
+
+commit ec042885cfa5a9450bfcc87152a41529d26545de
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 24 06:39:00 2019 -0400
+
+ Don't test ppc64le with buggy qemu.
+
+commit 90fb897839bb7006a2f751d283e3d23b3bfec1ea
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 24 06:24:14 2019 -0400
+
+ Strip build status from README.md at 'make dist' time.
+
+commit 1d6059446fb986d2de933f7ccf6fe38bcdf0c76c
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 24 05:25:11 2019 -0400
+
+ Add missing dist files.
+
+commit 825b2a359468af8bf3570a5a0695e8b805c5446f
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Oct 16 16:05:46 2019 -0400
+
+ Test on arm32v7-linux-gnu, ppc64le-linux-gnu and aarch64-linux-gnu.
+
+ Use docker images and qemu to test libffi for non-x86 architectures on
+ travis-ci.
+ Use the LIBFFI_TEST_OPTIMIZATION environment variable to
+ force specific optimization levels at test time.
+
+commit d2a4095af68f4530571bc3fa613dd7f5e5b815a3
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Oct 14 06:46:52 2019 -0400
+
+ Fix comments.
+
+commit 058aa4130445b4ef3c2f77f796c33506873031ca
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Oct 14 05:47:07 2019 -0400
+
+ Update copyright year
+
+commit c4f61240ab19401bd86c0dfb271e243e8159abb4
+Author: zhanhb <6323014+zhanhb@users.noreply.github.com>
+Date: Wed Oct 9 18:59:32 2019 +0800
+
+ Add long double test (#492)
+
+ Required to fix build error on macos with gcc-9
+
+commit 09f9d856112f2f105337e95e32ba9e2da63f65ae
+Author: pichikaudaykiran <51439150+pichikaudaykiran@users.noreply.github.com>
+Date: Wed Oct 9 16:26:06 2019 +0530
+
+ Making the change to correct the comment when SUN (#521)
+
+ and GCC are used together
+
+commit 55c22092dc54e706a64af3a49ae9d5471a9e8317
+Author: pnallan <46887249+pnallan@users.noreply.github.com>
+Date: Tue Oct 8 18:46:47 2019 +0530
+
+ handle compilation warnings with ftruncate API (#508)
+
+ * fix me: avoid warning while handle ftruncate API
+
+ Signed-off-by: Prasad Nallani <prasad.nallani@intel.com>
+
+ * Update closures.c
+
+commit e5f0eb1552f222eb2630e40ee348b090d56412a3
+Author: John Ericson <git@JohnEricson.me>
+Date: Tue Oct 8 06:58:52 2019 -0400
+
+ Clean up line endings (#509)
+
+ The CLRF visual studio files can be kept that way, but recognized as
+ text. The assembly file can be converted to LF.
+
+commit ea9b6639c69cbffeacd1ce0c1953c1997cf29d2e
+Author: Samuel Holland <samuel@sholland.org>
+Date: Tue Oct 8 05:57:28 2019 -0500
+
+ PowerPC bugfixes (#520)
+
+ * powerpc: Silence warnings about unused labels
+
+ * powerpc: Fix a couple of comments
+
+ * powerpc: Fix alignment after float structs
+
+ * powerpc: Don't pad rvalues copied from FP regs
+
+ * powerpc: Add missing check in struct alignment
+
+ * powerpc: Support homogeneous long double structs
+
+commit 25cf9cc4a5ce4a272252de3f681d60dafd838ceb
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 8 06:24:55 2019 -0400
+
+ Use https for moxie toolchain repo
+
+commit c2a6859012d928b67a83619bd5087674a96b9254
+Author: Paul Monson <paulmon@users.noreply.github.com>
+Date: Wed Aug 7 11:57:45 2019 -0700
+
+ fix mingw build and crashing bugs for Python Windows ARM64 (#496)
+
+ * fix mingw build and crashing bugs for Python Windows ARM64
+
+ * Fix issues found in PR review
+
+commit e0b4f84fb71c6760068c9d1306e77c9382e76d8d
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jun 26 06:18:48 2019 -0400
+
+ Clear the apt cache
+
+commit 68668fe4f22dea7b829fb84b724f5a74091f22f2
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jun 26 06:01:15 2019 -0400
+
+ More debugging output
+
+commit 1d7635d18ae4aebe4ec1cd129b0b4f71b685131e
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jun 25 23:39:52 2019 -0400
+
+ Debug moxie builds in travis
+
+commit d856743e6b02fcb5911491204131e277a7a4e10b
+Author: ossdev07 <39188636+ossdev07@users.noreply.github.com>
+Date: Wed Jun 26 07:31:22 2019 +0530
+
+ libffi: added ARM64 support for Windows (#486)
+
+ * libffi: added ARM64 support for Windows
+
+ 1. ported sysv.S to win64_armasm.S for armasm64 assembler
+ 2. added msvc_build folder for visual studio solution
+ 3. updated README.md for the same
+ 4. MSVC solution created with the changes, and below test suites are tested
+ with test script written in python.
+
+ libffi.bhaible
+ libffi.call
+ 5. Basic functionality of above test suites are getting passed
+
+ Signed-off-by: ossdev07 <ossdev@puresoftware.com>
+
+ * Update README.md
+
+commit 80d07104c33045ea34a4d5185600495dc7461a12
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Apr 28 07:36:24 2019 -0400
+
+ uuencode compressed log files for travis
+
+commit fadf1eb530713fde0be9774d926bc8202c97e379
+Author: Sergei Trofimovich <slyfox@gentoo.org>
+Date: Sat Apr 27 20:53:29 2019 +0100
+
+ hppa: avoid TEXTREL in .eh_frame section (#447)
+
+ Before the change hand-crafted .eh_frame section contained
+ ABS relocation and caused TEXTREL tag to be emitted:
+
+ ```
+ $ ./configure --host=hppa2.0-unknown-linux-gnu LDFLAGS=-Wl,-z,text
+ $ make
+ ...
+ /usr/libexec/gcc/hppa2.0-unknown-linux-gnu/ld:
+ read-only segment has dynamic relocations.
+ ```
+
+ Link failure is caused by absolute address of FDEs
+ encoded into .eh_frame entries.
+
+ Fixed TEXTREL by using pcrel (instead of ABS) encoding
+ for absolute addresses (__PIC__ code) by adding augmentation
+ information ("zR" CIE type).
+
+ All tests still pass on hppa2.0. The specific tests that still pass
+ and exercise this code path:
+ testsuite/libffi.call/unwindtest.cc
+ testsuite/libffi.call/unwindtest_ffi_call.cc
+
+ Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
+
+commit 06bf1a9deaa781b711c4d3718561e7faf303a842
+Author: driver1998 <driver1998.ms@outlook.com>
+Date: Sun Apr 28 03:21:44 2019 +0800
+
+ fix x86/x64 MSVC build (#487)
+
+commit db5706ff285c476aa3c0f811ff2b188319ac3ebe
+Author: Paul Monson <paulmon@users.noreply.github.com>
+Date: Fri Apr 26 04:58:58 2019 -0700
+
+ add support for 32-bit ARM on Windows (#477)
+
+ * add support for 32-bit ARM on Windows
+
+ * fix mismatched brace in appveyor.yml
+
+ * remove arm platform from appveyor.yml for now
+
+ * fix arm build
+
+ * fix typo
+
+ * fix assembler names
+
+ * try Visual Studio 2017
+
+ * add windows arm32 to .appveyor.yml
+
+ * update README.md
+
+commit d1e9b4b96cc8d237c3532cf83da0d4b99d19abb5
+Merge: 05a1796 a7d6396
+Author: Tom Tromey <tom@tromey.com>
+Date: Tue Apr 9 14:00:10 2019 -0600
+
+ Merge pull request #482 from sharkcz/aarch64
+
+ fix check for Linux/aarch64
+
+commit a7d6396f06d5e1a726f24b746b509514f466380f
+Author: Dan Horák <dan@danny.cz>
+Date: Fri Mar 29 14:19:20 2019 +0100
+
+ fix check for Linux/aarch64
+
+ fixes #473
+
+commit 05a1796419f68267250c0b8ae7138da36ab60b01
+Author: Jeremy Huddleston Sequoia <jeremyhu@users.noreply.github.com>
+Date: Tue Feb 19 04:11:28 2019 -0800
+
+ Cleanup symbol exports on darwin and add architecture preprocessor checks to assist in building fat binaries (eg: i386+x86_64 on macOS or arm+aarch64 on iOS) (#450)
+
+ * x86: Ensure _efi64 suffixed symbols are not exported
+
+ * x86: Ensure we do not export ffi_prep_cif_machdep
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
+
+ * x86: Ensure we don't export ffi_call_win64, ffi_closure_win64, or ffi_go_closure_win64
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
+
+ * closures: Silence a semantic warning
+
+ libffi/src/closures.c:175:23: This function declaration is not a prototype
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
+
+ * aarch64: Ensure we don't export ffi_prep_cif_machdep
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
+
+ * arm: Ensure we don't export ffi_prep_cif_machdep
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
+
+ * aarch64, arm, x86: Add architecture preprocessor checks to support easier fat builds (eg: iOS)
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
+
+ * x86: Silence some static analysis warnings
+
+ libffi/src/x86/ffi64.c:286:21: The left operand of '!=' is a garbage value due to array index out of bounds
+ libffi/src/x86/ffi64.c:297:22: The left operand of '!=' is a garbage value due to array index out of bounds
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
+
+ * aarch: Use FFI_HIDDEN rather than .hidden
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
+
+ * ffi.h: Don't advertise ffi_java_rvalue_to_raw, ffi_prep_java_raw_closure, and ffi_prep_java_raw_closure_loc when FFI_NATIVE_RAW_API is 0
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
+
+commit 3ec522bc1c1c5a7fb66b85d4fb6a0fe80581d597
+Author: dabrain34 <scerveau@gmail.com>
+Date: Tue Feb 19 13:09:09 2019 +0100
+
+ Fix cfi checks for old compiler (#453)
+
+ cfi_sections can be unsupported when cfi_startproc
+ and cfi_endproc are.
+
+commit e1118af50599314a2cbac3eb51a81896e8e21d0c
+Author: Paul Monson <paulmon@users.noreply.github.com>
+Date: Tue Feb 19 03:58:25 2019 -0800
+
+ changes for win32 on windows (#468)
+
+commit 44a6c28545186d78642487927952844156fc7ab5
+Author: Florian Weimer <fw@deneb.enyo.de>
+Date: Tue Feb 19 12:55:11 2019 +0100
+
+ aarch64: Flush code mapping in addition to data mapping (#471)
+
+ This needs a new function, ffi_data_to_code_pointer, to translate
+ from data pointers to code pointers.
+
+ Fixes issue #470.
+
+commit 042ef8c314a946ef1cd58c6e10cd74e403ef5bf9
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 12 08:50:30 2019 -0500
+
+ Remove -Os testing. No ABI impact, and helps trim log lengths.
+
+commit 8fa88373a1d433c675b11200ccd58418e91f81e4
+Merge: 737d4fa 2c5b164
+Author: Tom Tromey <tom@tromey.com>
+Date: Wed Dec 19 14:18:40 2018 -0700
+
+ Merge pull request #461 from NativeScript/bektchiev/fix-visibility-hidden-check-in-configure
+
+ fix(configure): Correctly detect visibility("hidden") support on Darwin
+
+commit 2c5b164288712cc048048d73a3cd841d845a132c
+Author: Martin Bektchiev <martin.bektchiev@progress.com>
+Date: Wed Dec 19 18:33:08 2018 +0200
+
+ fix(configure): Correctly detect visibility("hidden") support on Darwin
+
+commit 737d4faa00d681b4c758057f67e1a02d813d01c2
+Merge: a5ea752 4a84df4
+Author: Tom Tromey <tom@tromey.com>
+Date: Fri Nov 30 08:16:00 2018 -0700
+
+ Merge pull request #457 from NativeScript/bektchiev/fix-arm64-q3-q4-args
+
+ Fix Q registers parameter passing on ARM64
+
+commit 4a84df4ae9d33bb766fb34ce8a871d84d6e0ed9c
+Author: Martin Bektchiev <martin.bektchiev@progress.com>
+Date: Wed Oct 31 15:53:54 2018 +0200
+
+ Fix Q registers parameter passing on ARM64
+
+ The second two quads are located at offset 32 not 16
+
+commit a5ea7527cda8d9b7d011eb4004dfcbad54583bd2
+Merge: b11b08c ba73a67
+Author: Tom Tromey <tom@tromey.com>
+Date: Wed Sep 19 07:29:36 2018 -0600
+
+ Merge pull request #443 from jeremyhu/master
+
+ Update FFI_HIDDEN() to use .private_extern on Apple platforms and use the macro where appropriate
+
+commit b11b08ca8daacb08943ae5ea8c124771a8b82dde
+Merge: 980908b e6eac78
+Author: Tom Tromey <tom@tromey.com>
+Date: Tue Sep 18 08:26:31 2018 -0600
+
+ Merge pull request #449 from gpakosz/align-macros
+
+ Prefix ALIGN_DOWN macro with FFI_
+
+commit e6eac7863e2bf1a009ea863041b354bdb4af6b67
+Author: Gregory Pakosz <gregory.pakosz@gmail.com>
+Date: Tue Sep 18 15:19:53 2018 +0200
+
+ Prefix ALIGN_DOWN macro with FFI_
+
+commit 980908b47bbde09fab88ee4b2b61d8bc5d4378a7
+Merge: 65da63a 4cb776b
+Author: Tom Tromey <tom@tromey.com>
+Date: Sat Aug 11 09:53:15 2018 -0600
+
+ Merge pull request #445 from andreas-schwab/master
+
+ RISC-V go closures
+
+commit 4cb776bc8075332d2f3e59f51785d621fcda48f6
+Author: Andreas Schwab <schwab@suse.de>
+Date: Thu Aug 9 12:12:29 2018 +0200
+
+ RISC-V go closures
+
+ This implements go closures for RISC-V. It has been tested on
+ riscv64-suse-linux and against the libgo testsuite.
+
+commit ba73a671cb49f8e2c4417723a9dc233e328926ae
+Author: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
+Date: Fri Jul 20 09:37:43 2018 -0700
+
+ Update FFI_HIDDEN() to use .private_extern on Apple platforms and use the macro where appropriate
+
+ Fix issue #439
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
+
+commit 65da63abc843fe448aaa86015d094cf016f325ba
+Author: Jeremy Huddleston Sequoia <jeremyhu@users.noreply.github.com>
+Date: Mon Jun 25 04:38:58 2018 -0700
+
+ Add compact unwind for darwin/i386 (#440)
+
+ * x86: Add implementation of compact unwind for ffi_call_i386, et al.
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
+
+ * x86: Use __text as the section name to avoid deprecated section name warnings.
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
+
+ * darwin: Add missing regular,debug attributes for compact unwind sections
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
+
+commit 2309b58448b0c8349156d687d7fa8709dfb68992
+Author: Shoaib Meenai <shoaib.meenai@gmail.com>
+Date: Sun Jun 17 17:04:24 2018 -0700
+
+ Mark sysv.S as SafeSEH compatible (#438)
+
+ It contains no exception handler, so we can just emit the special
+ @feat.00 symbol to indicate that it's trivially SafeSEH compatible.
+ SafeSEH only applies to x86 and not x86-64, hence its inclusion in the
+ x86-specific block. See [1] for details.
+
+ [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms680547(v=vs.85).aspx#the_.sxdata_section_
+
+commit 1d704051b2da207d715351b8613e74437d8e2eb7
+Author: Jeremy Huddleston Sequoia <jeremyhu@users.noreply.github.com>
+Date: Sun Jun 17 17:01:50 2018 -0700
+
+ i386: Fix missing break; in case statement leading to incorrectly returned FFI_BAD_ABI (#437)
+
+ * i386: Add missing break triggering dead store static analyzer checks.
+
+ Register calling sequence is being reported as bad ABI instead of working as intended.
+
+ Found-by: Clang Static Analysis
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
+
+ * Mark ffi arm sysv entry points as private_extern.
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
+
+ * x86_64: Add implementation of compact unwind for ffi_call_unix64.
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@apple.com>
+
+commit b55baf0b500ccc7636a8a55e0506d9da787ad2dd
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed May 9 13:21:02 2018 -0400
+
+ Handle FFI_GNUW64 on non-Windows systems (EFI)
+
+commit 8206253fdf01226173c36f087226d8ea53584566
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed May 9 10:50:46 2018 -0400
+
+ Mark some cases as xfail due to GCC bug
+
+commit b5ee395710e2db830749c3c95558c91b66ac111f
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat May 5 07:41:53 2018 -0400
+
+ Revert "Remove some symbol exports and cleanup newline warnings (#433)"
+
+ This reverts commit a5a0f3cf36dfb4d64316414a872288c3170e6c1d.
+
+commit a5a0f3cf36dfb4d64316414a872288c3170e6c1d
+Author: Jeremy Huddleston Sequoia <jeremyhu@users.noreply.github.com>
+Date: Sat May 5 03:44:33 2018 -0700
+
+ Remove some symbol exports and cleanup newline warnings (#433)
+
+ * build: Ensure darwin generated sources end with a new line
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
+
+ * build: Use .private_extern where missing to prevent exporting symbols that are not API
+
+ Signed-off-by: Jeremy Huddleston Sequoia <jeremyhu@macports.org>
+
+commit d3c54cf3a2b2bb2e889173b6a0a959517b42c47f
+Author: hjl-tools <hjl.tools@gmail.com>
+Date: Wed May 2 06:19:58 2018 -0700
+
+ Re-enable msabi testing (#436)
+
+ * Revert "disable msabi testing for now"
+
+ This reverts commit 7b7638eb0eac2adfa72f7ec9f254ba287c9947e2.
+
+ * x86: Correct testing for 64-bit x86-64
+
+ Since passing -m32 to x86-64 compiler will generate i386 code, we
+ need to check both __ILP32__ and __i386__ for 64-bit x86-64.
+
+ * x86: Check __i386__ instead of i?86-*-* targets
+
+ Since passing -m32 to x86-64 compiler will generate i386 code, we need
+ to check __i386__ instead of i?86-*-* targets for i386 targets.
+
+ * i386: Properly passing integer parameters in registers
+
+ For thiscall and fastcall, if the paramter passed as 64-bit integer or
+ struct, all following integer paramters will be passed on stack.
+
+ * test: Add ABI_ATTR to callback_code
+
+ Add ABI_ATTR to callback_code to properly test different ABIs.
+
+commit ebf241663cc0fd0d76e4db8101e842e1630a2c78
+Author: Alan Modra <amodra@gmail.com>
+Date: Wed May 2 13:55:29 2018 +0930
+
+ PowerPC64 ELFv1 fp arg fixes
+
+ The ELFv1 ABI says: "Single precision floating point values are mapped
+ to the second word in a single doubleword" and also "Floating point
+ registers f1 through f13 are used consecutively to pass up to 13
+ floating point values, one member aggregates passed by value
+ containing a floating point value, and to pass complex floating point
+ values".
+
+ libffi wasn't expecting float args in the second word, and wasn't
+ passing one member aggregates in fp registers. This patch fixes those
+ problems, making use of the existing ELFv2 homogeneous aggregate
+ support since a one element fp struct is a special case of an
+ homogeneous aggregate.
+
+ I've also set a flag when returning pointers that might be used one
+ day. This is just a tidy since the ppc64 assembly support code
+ currently doesn't test FLAG_RETURNS_64BITS for integer types..
+
+ * src/powerpc/ffi_linux64.c (discover_homogeneous_aggregate):
+ Compile for ELFv1 too, handling single element aggregates.
+ (ffi_prep_cif_linux64_core): Call discover_homogeneous_aggregate
+ for ELFv1. Set FLAG_RETURNS_64BITS for FFI_TYPE_POINTER return.
+ (ffi_prep_args64): Call discover_homogeneous_aggregate for ELFv1,
+ and handle single element structs containing float or double
+ as if the element wasn't wrapped in a struct. Store floats in
+ second word of doubleword slot when big-endian.
+ (ffi_closure_helper_LINUX64): Similarly.
+
+commit a2c6c7af9ffb9500a944abc666ced0922d0de762
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue May 1 06:46:30 2018 -0400
+
+ Add license for build-time tools
+
+commit 4c2206ace07f2fb4bef43cd4bfe952ccb584dcec
+Author: Tom Tromey <tom@tromey.com>
+Date: Sat Apr 28 04:46:10 2018 -0600
+
+ Fix two "return" issues in x86/ffi64.c (#431)
+
+ Issue #70 pointed out that at least one compiler didn't like:
+
+ return ffi_call_efi64(cif, fn, rvalue, avalue);
+
+ ... where the return type is "void". This patch splits the statement
+ into two.
+
+ I also noticed that ffi_call_go here seems to do a double call. I
+ suspect a "return" is missing here, so this patch adds it as well.
+
+commit ed3ed4d801a4d417ea304715d4d8ae581a6c6903
+Merge: 8e250c3 b69f95d
+Author: Tom Tromey <tom@tromey.com>
+Date: Fri Apr 27 10:48:51 2018 -0600
+
+ Merge pull request #429 from yousong/m4subst
+
+ build: fix subst toolexecdir, toolexeclibdir
+
+commit b69f95d6562b6a57c9be36da0cdf2a500adb94e9
+Author: Yousong Zhou <yszhou4tech@gmail.com>
+Date: Thu Apr 26 19:27:54 2018 +0800
+
+ build: fix subst toolexecdir, toolexeclibdir
+
+ On CentOS 7.4, configure script generated by autogen.sh will output the
+ following values when compiling GCC source code
+
+ toolexecdir='NONE/$(target_alias)'
+ toolexeclibdir='NONE/$(target_alias)/lib'
+
+ and cause build error
+
+ ... -o libffi.la -rpath NONE/riscv64-bs-linux-gnu/lib ...
+ checking for shl_load in -ldld... libtool: link: only absolute run-paths are allowed
+
+commit 8e250c390a45f722387c1881ae5f99849a2d1e22
+Author: Stephen <stephengroat@users.noreply.github.com>
+Date: Wed Apr 25 13:17:32 2018 -0700
+
+ update to https for cygwin download (#428)
+
+commit 7d3cab7926d08aad9a8e54420d6878cb17efd185
+Author: Lucas Pluvinage <lucas.pluvinage@gmail.com>
+Date: Sat Apr 21 00:24:50 2018 +0200
+
+ xtensa-linux: use cache flush instruction only if it is available (#426)
+
+commit 159b94e5fd4aa2d88e1b5b389092cefd9472a741
+Author: James Cowgill <jcowgill@users.noreply.github.com>
+Date: Thu Apr 19 01:28:23 2018 +0100
+
+ Various MIPS Fixes (#425)
+
+ * mips: simplify closure #defines
+
+ This commit should have no visible effect.
+
+ * mips: add special handling of variadic functions
+
+ MIPS requires special handling of variadic functions which pass floating
+ point arguments:
+ * In the o32 ABI, all float arguments are passed in integer registers.
+ * In the n32/n64 ABIs, float arguments after the ellipsis are passed in
+ integer registers.
+
+ Implement this in libffi. To support this in n32/n64 closures, we need to add
+ a new mips_nfixedargs field to ffi_cif which will break the libffi ABI.
+
+ This fixes the libffi.call/cls_longdouble_va.c test which was failing on
+ 64-bit MIPS.
+
+ * mips: align argn for all 64-bit types in o32 closure handler
+
+ Ensure that argn is pre-aligned for all 64-bit argument types (including
+ doubles) and not just integer types.
+
+ This fixes closures of the form "f(float, double, <some integer args>)".
+ Previously the first integer argument would be read from a2 which is garbage
+ at this point (the float arguments have already "consumed" a0-a3). After
+ this commit, argn is correctly padded between the "float" and "double"
+ arguments so that the first integer argument is read from the stack.
+
+ Fixes "double f(float,double,int)" test in #371
+
+ * mips: do not read from floating point register if returning a struct
+
+ In the o32 ABI, the pointer passed in a0 used to return structures
+ indirectly is treated as the first argument for argument allocation purposes.
+ This means that it should inhibit floating point registers the same way that
+ other integer arguments do.
+
+ Fixes "Double f(float,Double,double)" test in #371
+
+ * mips: fix pointer cast warnings
+
+ Fix two pointer cast warnings when compiled on 64-bit mips by casting
+ through uintptr_t.
+
+ Fixes mips64el part of #404
+
+commit f2afda08e85b02888350449dcf39a6c37cfb7bc4
+Merge: e27f70b 801c1bd
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Apr 8 18:25:43 2018 -0400
+
+ Merge branch 'master' of github.com:/libffi/libffi
+
+commit e27f70b8cf2a537bef84b2cb29ad8ea6209a11b8
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Apr 8 18:25:34 2018 -0400
+
+ Fix case where callback arg value is split across regs and stack
+
+commit 801c1bd712ff8c76675b7aa69c29948907f1eeff
+Author: Andreas Krebbel <38103320+Andreas-Krebbel@users.noreply.github.com>
+Date: Thu Apr 5 14:27:32 2018 +0200
+
+ Fix issue #421 (#422)
+
+ Fantastic - thanks for digging into this.
+
+commit 8660e6935971c5abd7b528eaf54deeccd4bbaccd
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Apr 2 08:30:17 2018 -0400
+
+ 3.3 release candidate 0
+
+commit 7b7638eb0eac2adfa72f7ec9f254ba287c9947e2
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Apr 2 08:24:44 2018 -0400
+
+ disable msabi testing for now
+
+commit af6773d6ab4db0577bc6b932ab5a2f98a0a8dca2
+Author: fwg <fwg@users.noreply.github.com>
+Date: Mon Apr 2 13:55:31 2018 +0200
+
+ Fix appveyor windows build (#420)
+
+ * Fix msvcc dll build by adding dllexport decorations to all API declarations
+
+ * Fix appveyor build for VS 2013
+
+ Use the new -DFFI_BUILDING_DLL for producing a working DLL. Update the
+ msvcc.sh wrapper script to successfully compile the testsuite files.
+
+ * MSVC build: suppress warnings in testsuite
+
+ * fix testsuite on appveyor
+
+commit 48bdb02867edb7e9f3785ccb4bdff1087fb44246
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Mar 29 07:22:57 2018 -0400
+
+ Trim some optimization tests
+
+commit f98e0f0d777bf962057e18d036989b2b89fdf416
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Mar 29 07:22:38 2018 -0400
+
+ Simplify matrix
+
+commit fa72b054e10acaea33ec8cc395e0ea5b31c9ac9e
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Mar 29 07:10:23 2018 -0400
+
+ Remove warning message from clang
+
+commit 746c3ce220cb155a8f3b613550a7ecad76f9fedc
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Mar 29 07:01:14 2018 -0400
+
+ Expand ABI tests on x86. Testsuite bug fixes.
+
+commit 2eee934d0cb2beef7c0aa29767eca1ce03452ae9
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 14:45:40 2018 -0400
+
+ deal with msvc warnings
+
+commit 206b2974f70f65b4c4c4d9e62b03ee7e0753ee2d
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 14:37:50 2018 -0400
+
+ fix quoting issue
+
+commit 499e41c1ec6b760eff2b320ffc87e22de82a9e1d
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 14:35:10 2018 -0400
+
+ Don't ignore a file
+
+commit 5b41e9f6d2c099add0e02db8c8054281f96b6d0e
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 14:34:31 2018 -0400
+
+ Try different msvc hack
+
+commit e8cf133813e7fa2c606d93abab5b68989e5f6cbc
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 14:12:02 2018 -0400
+
+ msvc c99 hack
+
+commit a3e20940898ed2ca96b9df87f34117d06d900e5f
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 11:58:42 2018 -0400
+
+ More msvc hacks
+
+commit a82b456e98b0f3fbafe76725d1a1503d458a2178
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 11:49:46 2018 -0400
+
+ msvc fixes
+
+commit a2326aaf561798c3bfd5e464b16693a094bf6c45
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 11:36:04 2018 -0400
+
+ Remove debug output
+
+commit 85b6b209d7984667ce7d00351fe7e79ef6c4930c
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 11:35:23 2018 -0400
+
+ Force literals to float (msvc warning)
+
+commit 2872c460ba8e96416b4f4ee4a0ed183461d8d6c9
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 11:28:40 2018 -0400
+
+ Fix msvc linking
+
+commit b40a386c22a2bd164819b4f398b722357222b7c1
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 11:20:21 2018 -0400
+
+ Fix library path handling
+
+commit d78c5f64f834c24a769bee78cfb7db4d468b6b21
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 11:14:56 2018 -0400
+
+ Deal with libpath
+
+commit f318bb63c5dc623d5a69ffc4a59a330050cac567
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 08:25:26 2018 -0400
+
+ Fix library path handling
+
+commit 4f0c9cb39b7599312729278380ce63247bca226b
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 08:10:03 2018 -0400
+
+ Use mixed cygpath paths
+
+commit d3693b4665de7ef69b61fb4e483d5686302f9c69
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 08:05:42 2018 -0400
+
+ Copy - don't symlink - to support msvc builds
+
+commit 51ce3696cd0da4716d86b73a30bd89e139ec4b74
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 07:35:33 2018 -0400
+
+ Use cygpath to convert windows paths
+
+commit 70b93e4d863c1ff2a6498455339e17df3d7fe784
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 07:14:59 2018 -0400
+
+ try to fix windows builds
+
+commit 377134d7a946df13b60ff9c9dacc895e82c36178
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 07:06:01 2018 -0400
+
+ Reduce verbosity
+
+commit d01ef5b875dedcb9f7b3039b2334cbd594fdfcd4
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 06:23:29 2018 -0400
+
+ iOS builds
+
+commit d13583f55fb31a302684cbc62c300ae81eb577e9
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 06:22:57 2018 -0400
+
+ Fix -L support
+
+commit d49911544bf9d2b4fab782b0c5e76a68074223df
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 05:59:26 2018 -0400
+
+ Fix quoting
+
+commit 8f47ec404fcf5a082fc4537ede8cdf897f4c5226
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 05:35:35 2018 -0400
+
+ Don't set AM_MAKEFLAGS
+
+commit df314193dc6cd00978b6e1517866448b604199af
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 05:13:38 2018 -0400
+
+ Run tests with lots of debug output
+
+commit b394947518fb15887802fe3bc7f0a337c495d65d
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 05:11:52 2018 -0400
+
+ Add -L and -l support
+
+commit 33da6c075299317885385f19680b58a1e9feab5e
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 05:07:08 2018 -0400
+
+ Mention C99 and build requirements
+
+commit e6bdbd7888b5c8a90f3c91f4d6caf3c8d574f3b5
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 04:46:04 2018 -0400
+
+ Remove reference to wiki
+
+commit 24eb1f88d788399dde5fbb4804767e6b6cbf1bc8
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 04:09:56 2018 -0400
+
+ Refactor travis build instructions. Add iOS build
+
+commit ffc3ff162a15ed0ed0e946815c950c69ee0c8343
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 04:02:06 2018 -0400
+
+ Add issue template
+
+commit 5c2ca479e726dc2feec43e25475c63361387bf20
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 27 04:01:37 2018 -0400
+
+ Remove uninitialized warning. Fix #163.
+
+commit 0081378017c33a4b9b6fbf20efabdd9959d6a48d
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 24 09:05:14 2018 -0400
+
+ revert
+
+commit 59d44242e15d2979291fe6793ddfb2681b7480ef
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 24 08:45:59 2018 -0400
+
+ Try bhaible tests in appveyor
+
+commit 6f7c29c5a6d2850ce53b99efcc71fcc4e8f8c8cc
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 24 08:40:04 2018 -0400
+
+ Formatting fixes
+
+commit f3c2729ee4026c9f70a6656603bac8ba2ec40a5d
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Mar 23 11:47:29 2018 -0400
+
+ Add libffi.map.in to extra dist files
+
+commit 6d2233f96a08c5ac01a64e7b84e2bd678eed0a4b
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Mar 23 09:06:08 2018 -0400
+
+ Add sparc solaris build notes
+
+commit 99a80d2fc4ede48348af2edfb7126d60609c4b71
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 21:22:55 2018 -0400
+
+ Fix formatting
+
+commit a3e87ac8e7b7e609ab84541a69c7e51873efa437
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 20:36:52 2018 -0400
+
+ Fix formatting
+
+commit cec3a3a201f17a7f018f25e1a0917bd5206e5a5a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 16:00:04 2018 -0400
+
+ Don't align-double for 32-bit x86
+
+commit f34f8039c10c4d8d728bc335dcf2b2a38f6e8b50
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 15:30:00 2018 -0400
+
+ Remove debug output
+
+commit f31b915314b12904b858b54cfdf670ceaeda7b2d
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 15:13:21 2018 -0400
+
+ Add m4/ax_require_defined.m4
+
+commit a2dc5848b53e9e45ff68e5ef70683b5ffb82592e
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 13:41:15 2018 -0400
+
+ travis debug
+
+commit 81d345b2cff039c4389fad283a108ad978b609e0
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 13:32:03 2018 -0400
+
+ Update autoconf archive macros
+
+commit 369ef49f71186fc9d6ab15614488ad466fac3fc1
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 12:53:42 2018 -0400
+
+ Add missing FFI_GNUW64 enum
+
+commit 56655e58c7f966685c0d5635ee7215733121ae41
+Merge: 43980dd 9bc40d8
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 12:34:18 2018 -0400
+
+ Merge branch 'master' of github.com:/libffi/libffi
+
+commit 43980dd10e0d5705e52f24d63988b722e31bf330
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 12:32:10 2018 -0400
+
+ Add FFI_GNUW64 ABI for GNU 80-bit long double support
+
+commit 9bc40d87ea5950969b234ed56cd2c6acd883fa0e
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 12:32:10 2018 -0400
+
+ Add FFI_GWIN64 ABI for GNU 80-bit long double support
+
+commit d46406088d28b038a0a0f7396d9621f431482f6a
+Author: Ryan C. Underwood <nemesis@icequake.net>
+Date: Sun Mar 18 07:00:42 2018 -0700
+
+ Fully allocate file backing writable maps (#389)
+
+ When ftruncate() is used on a filesystem supporting sparse files,
+ space in the file is not actually allocated. Then, when the file
+ is mmap'd and libffi writes to the mapping, SIGBUS is thrown to
+ the calling application. Instead, always fully allocate the file
+ that will back writable maps.
+
+commit 247e44b3ef653f210de614a749b71449b8c70764
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 18 07:01:54 2018 -0400
+
+ Fix return values
+
+commit 1f99701fad1761ffe4e9adf88cfe26f74f427e7c
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 17 22:49:58 2018 -0400
+
+ Make tests compile/run standalone
+
+commit d974207cd6373ff282a64038564d99b853dc3fab
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 17 09:03:42 2018 -0400
+
+ Formatting fixes. Add 'bug fixes' note.
+
+commit a33bfa9b12993aae2edf669f62e141a84286d4de
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 17 07:17:24 2018 -0400
+
+ xfail unwind tests for moxie
+
+commit 8bf05481436ba085df3adfff2b47a879df738d67
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Mar 16 23:54:28 2018 -0400
+
+ Install moxie libstdc++
+
+commit 84b383eda67ba75a6456e4b3587f17b749e6e1a1
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Mar 16 23:36:51 2018 -0400
+
+ Install moxie-elf-g++
+
+commit 6a801d042ac1212fe8c0e11abb865061e515aa43
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Mar 16 17:53:33 2018 -0400
+
+ Fix closure case where 8-byte value is partially passed in register. Fixes cls_many_mixed_float_double test case.
+
+commit 0f0ba9e0ec52e0297c91cb63a889980a6f847219
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Mar 16 07:28:33 2018 -0400
+
+ Run dejagnu's runtest with -a option to prevent travis timeouts after 10min
+
+commit 725454196afab82f7da7bd719e8bddf7cd7837dd
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Mar 15 08:17:18 2018 -0400
+
+ fix .travis.yml
+
+commit d71051c46a795a0669b2d83804030746f790edf4
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 21:21:06 2018 -0400
+
+ fix .travis.yml
+
+commit e86aa54ce3418081dca403217c9216c773b82560
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 21:00:55 2018 -0400
+
+ fix .travis.yml
+
+commit 5b538ed61fb13efc8f01bad014c5485231714c96
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 20:32:00 2018 -0400
+
+ fix .travis.yml
+
+commit 6ed64a7953178cf07d2793650fcd64caa6b51d53
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 20:22:33 2018 -0400
+
+ fix .travis.yml
+
+commit 90809e928f8b5a0cdf0787d799111bc33689a9d1
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 14:09:39 2018 -0400
+
+ fix .travis.yml
+
+commit 85e4c62351bd1e45dd6d77916778e18c435f1723
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 13:47:27 2018 -0400
+
+ fix .travis.yml
+
+commit aa8a5ec4a4ec4a4460ec3cd4e396e09ceaa3a2fa
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 13:25:04 2018 -0400
+
+ fix .travis.yml
+
+commit 7c3e5da401ab7efef83a5bd4e7f64b0df053da0c
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 13:07:04 2018 -0400
+
+ fix .travis.yml
+
+commit 19aec1989382fab8bd86c556aa24751a75b8246e
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 12:40:58 2018 -0400
+
+ Fix travis.yml
+
+commit bf337b070977fb7e8934fc91e4d0e60209f53448
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 12:15:04 2018 -0400
+
+ yaml syntax error fix
+
+commit 076d5a987e016669993154b91525b02978c56727
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 11:13:32 2018 -0400
+
+ markdown fixes
+
+commit d2f7e788aecf37971c9be1cd650f78a3e4061e18
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 09:06:38 2018 -0400
+
+ Fix test cases with short results
+
+commit 18fe190068563bb2bf52a0993017887f438c85a4
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 08:02:10 2018 -0400
+
+ Debug travis output
+
+commit 718a4177f23e9d6c5476d0118d49a3a093d72c6c
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 14 07:40:53 2018 -0400
+
+ test
+
+commit 486c34b65deb43d6d9025b2a40284606f97f4e0b
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 23:31:18 2018 -0400
+
+ debug
+
+commit 00464aa52022674bdc1f5aa9b2ceb575c9a04b87
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 23:30:52 2018 -0400
+
+ debug
+
+commit eb0544d0d42e5aef56ee1df0861bcd0c95102f88
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 23:20:15 2018 -0400
+
+ Debug env
+
+commit 9d5bd29d8dfb5f89d0927a175443240a19e93890
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 23:07:10 2018 -0400
+
+ Refactor
+
+commit 52a364d7699230be5e883f32b9ac0caaea0300b1
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 22:49:48 2018 -0400
+
+ fix moxie build
+
+commit 1a32b3f146f7ade701cea74e3983b16145f93393
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 22:44:13 2018 -0400
+
+ fix moxie build
+
+commit e8958c3a64b5e59f0477bcaafaf9c03337d9f445
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 22:36:41 2018 -0400
+
+ revert test
+
+commit 58315ae125482c44821cfbdce41e350380024d0e
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 22:35:50 2018 -0400
+
+ test
+
+commit 6239c28741a8abc1bd06cb47329d8c5cdb359c90
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 22:13:44 2018 -0400
+
+ Add experimental moxie travis build
+
+commit 01db31d94e97e71836fe862826bc8a2a399dd619
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 20:41:55 2018 -0400
+
+ Update moxie sub opcode
+
+commit e8f5a43033d53ad631ba477b78a3def61783a1dc
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 09:27:00 2018 -0400
+
+ Fix appveyor badge
+
+commit d1689dd3bf78f4975aa6a6a16cbffcb794283acb
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 09:24:37 2018 -0400
+
+ Fix travis badge. Add REAME.md to dist files
+
+commit 785351fbc2a49f05535c412067ac51f906612779
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 09:21:49 2018 -0400
+
+ Preformat release notes
+
+commit 8c7fbd1616b075e3077346c7bf56befd723a9355
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 09:20:44 2018 -0400
+
+ Preformat release notes
+
+commit 54f31b00562e75e6aae2b736c70e6713618640cb
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 09:17:57 2018 -0400
+
+ Try to fix table
+
+commit 3a29a27a86624512f405e4c9962276485517caf1
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 09:14:40 2018 -0400
+
+ Clean up markdown table
+
+commit fbfc3b048fcf3f699f4495ca70b7e58461a0df4f
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 09:12:21 2018 -0400
+
+ Move to markdown
+
+commit a31d3d3ba6644d308b6fb8cea2a60976e0531f4a
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 09:11:24 2018 -0400
+
+ Add travis and appveyor build badges
+
+commit 16313cb2746ceed6bc1d25b52604642c14758e01
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 08:52:30 2018 -0400
+
+ Support compiler specific warning suppression flags
+
+commit cca6d1fb549e422514df4aad68f2ca9a8313327d
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 08:51:34 2018 -0400
+
+ Support compiler specific warning suppression flags
+
+commit 9291f941c2df5ddf967f701b258ac2b3cc9d0820
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 08:37:21 2018 -0400
+
+ Add bhaible's missing Makefile
+
+commit bede01d82ec2f1cfe2bb42233fcd408a6e3a6323
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 07:53:33 2018 -0400
+
+ Remove stray directory
+
+commit 9aefbb1031c9be7c5121ab24742e025ccff236c4
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 07:51:02 2018 -0400
+
+ Update version number to next pre-release
+
+commit ddf7a8f7511a038342f56c08dac718148e2f0151
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 13 07:47:57 2018 -0400
+
+ Update test list for dist
+
+commit 6186261cb36a33abbf31430569f83ccd7685474e
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Mar 12 21:53:18 2018 -0400
+
+ Add Bruno Haible and Bill Triggs' libffi testsuite
+
+commit 4e8f79d5587ddb8e027f4df213e90f943e286594
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 11 18:21:46 2018 -0400
+
+ Next release will be 3.3
+
+commit 3840d49aaa831d649b1597518a2903dfed0d57f3
+Author: Stef O'Rear <sorear2@gmail.com>
+Date: Sun Mar 11 05:55:15 2018 -0700
+
+ New RISC-V port (#281)
+
+ * Add RISC-V support
+
+ This patch adds support for the RISC-V architecture (https://riscv.org).
+
+ This patch has been tested using QEMU user-mode emulation and GCC 7.2.0
+ in the following configurations:
+
+ * -march=rv32imac -mabi=ilp32
+ * -march=rv32g -mabi=ilp32d
+ * -march=rv64imac -mabi=lp64
+ * -march=rv64g -mabi=lp64d
+
+ The ABI currently can be found at
+ https://github.com/riscv/riscv-elf-psabi-doc/blob/master/riscv-elf.md .
+
+ * Add RISC-V to README
+
+ * RISC-V: fix configure.host
+
+commit dca52b55bc2ac0213c20849d7e9e19fbc9202023
+Merge: 83d9aba 11de69d
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 11 08:50:01 2018 -0400
+
+ Merge pull request #406 from trofi/master
+
+ ia64: fix variadic function closures with FP arguments
+
+commit 83d9aba3a44dff8426052312a9445a7ef52f1db1
+Merge: ab15405 b58caef
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 11 08:48:42 2018 -0400
+
+ Merge pull request #407 from trofi/ia64-small-struct
+
+ ia64: fix small struct return
+
+commit ab154056937782c1c7f7005c8b46c5179bc719cb
+Merge: 9429968 e66fd67
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 11 08:46:58 2018 -0400
+
+ Merge pull request #409 from andreas-schwab/master
+
+ Revert "Fix passing struct by value on aarch64"
+
+commit e66fd678200db456a2e9860e80451773efa96fe0
+Author: Andreas Schwab <schwab@suse.de>
+Date: Tue Feb 20 10:47:09 2018 +0100
+
+ Revert "Fix passing struct by value on aarch64"
+
+ This reverts commit 482b37f00467325e3389bab322525099860dd9aa.
+
+ That was actually a bug in python, see <https://bugs.python.org/issue30353>.
+
+commit b58caef7fd620408be9239ac24ea89d5bc84f30b
+Author: Sergei Trofimovich <slyfox@gentoo.org>
+Date: Sat Feb 17 19:00:40 2018 +0000
+
+ ia64: fix small struct return
+
+ This change fixes libffi.call/struct10.c failure on ia64:
+ FAIL: libffi.call/struct10.c -W -Wall -Wno-psabi -O0 execution test
+
+ .Lst_small_struct handles returns for structs less than 32 bytes
+ (following ia64 return value ABI [1]). Subroutine does roughly the
+ following:
+
+ ```
+ mov [sp+0] = r8
+ mov [sp+8] = r9
+ mov [sp+16] = r10
+ mov [sp+24] = r11
+ memcpy(destination, source=sp, 12);
+ ```
+
+ The problem: ia64 ABI guarantees that top 16 bytes of stack are
+ scratch space for callee function. Thus it can clobber it. [1]
+ says (7.1 Procedure Frames):
+ """
+ * Scratch area. This 16-byte region is provided as scratch storage
+ for procedures that are called by the current procedure. Leaf
+ procedures do not need to allocate this region. A procedure may
+ use the 16 bytes at the top of its own frame as scratch memory,
+ but the contents of this area are not preserved by a procedure call.
+ """
+
+ In our case 16 top bytes are clobbered by a PLT resolver when memcpy()
+ is called for the first time. As a result memcpy implementation reads
+ already clobbered data frop top of stack.
+
+ The fix is simple: allocate 16 bytes of scrats space prior to memcpy()
+ call.
+
+ [1]: https://www.intel.com/content/dam/www/public/us/en/documents/guides/itanium-software-runtime-architecture-guide.pdf
+
+ Bug: https://bugs.gentoo.org/634190
+ Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
+
+commit 45da2fcbcd0ecaba673275d22b04fac3e4376e22
+Author: Sergei Trofimovich <slyfox@gentoo.org>
+Date: Sat Feb 17 18:53:02 2018 +0000
+
+ new test: return small struct
+
+ The bug originally was discovered in https://bugs.gentoo.org/634190
+ where complicated callback was returning invalid data on ia64.
+
+ This change adds minimal reproducer that fails only on ia64 as:
+
+ FAIL: libffi.call/struct10.c -W -Wall -Wno-psabi -O0 execution test
+ FAIL: libffi.call/struct10.c -W -Wall -Wno-psabi -O2 execution test
+ FAIL: libffi.call/struct10.c -W -Wall -Wno-psabi -O3 execution test
+ FAIL: libffi.call/struct10.c -W -Wall -Wno-psabi -Os execution test
+
+ Test passes on amd64. The fix is in the following commit.
+
+ Bug: https://bugs.gentoo.org/634190
+ Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
+
+commit 11de69ddb788e4d87ef653898878384116ac16c6
+Author: Sergei Trofimovich <slyfox@gentoo.org>
+Date: Sun Feb 11 11:29:39 2018 +0000
+
+ ia64: fix variadic function closures with FP arguments
+
+ libffi test framework already flagged failures as:
+
+ ```
+ FAIL: libffi.call/cls_double_va.c -W -Wall -Wno-psabi -O0 output pattern test, is 7.0
+ res: 4
+ 0.0
+ res: 4
+ ? should match 7.0
+ ?es: 4
+ ?.0
+ res: 4
+ ```
+
+ Failure happens here at
+
+ ```c
+ // testsuite/libffi.call/cls_double_va.c
+ ...
+ char* format = "%.1f\n";
+ double doubleArg = 7;
+ ...
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_double_va_fn, NULL,
+ code) == FFI_OK);
+ res = ((int(*)(char*, ...))(code))(format, doubleArg);
+ ```
+
+ libffi expects 'doubleArg' to be located in 'f9' (second FP argument) but
+ gcc placed it to 'r33' (second GR).
+
+ ia64 software [1] manual described argument passing ABI in
+ "8.5.2 Register Parameters" as:
+
+ """
+ If an actual parameter is known to correspond to a floating-point
+ formal parameter, the following rules apply:
+ a) The actual parameter is passed in the next available floating-point
+ parameter register, if one is available. Floating-point parameter
+ registers are allocated as needed from the range f8-f15, starting
+ with f8.
+ b) If all available floating-point parameter registers have been used,
+ the actual parameter is passed in the appropriate general register(s).
+ (This case can occur only as a result of homogeneous floating-point
+ aggregates, described below.)
+
+ If a floating-point actual parameter is known to correspond to
+ a variable-argument specification in the formal parameter list,
+ the following rule applies:
+ c) The actual parameter is passed in the appropriate general
+ register(s).
+
+ If the compiler cannot determine, at the point of call,
+ whether the corresponding formal parameter is a varargs parameter,
+ it must generate code that satisfies both of the above conditions.
+ (The compiler’s determination may be based on prototype declarations,
+ language standard assumptions, analysis, or other user options or
+ information.)
+ """
+
+ We have [c] case here and gcc uses only GR for parameter passing.
+
+ The change binds known variadic arguments ro GRs instead of FPs as those
+ are always expected to be initialized for all variadic call types.
+
+ This fixes all 10 failures on ia64-unknown-linux-gnu:
+
+ ```
+ === libffi Summary ===
+ -# of expected passes 1945
+ -# of unexpected failures 10
+ +
+ +# of expected passes 1955
+ ```
+
+ [1]: https://www.intel.com/content/dam/www/public/us/en/documents/guides/itanium-software-runtime-architecture-guide.pdf
+
+ Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
+
+commit 9429968b828de8775cfd7f139374888943f2186a
+Merge: f08b2be 28d3b61
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 10 23:23:33 2018 -0500
+
+ Merge pull request #403 from frida/fix/x86-sysv-pic-closure-regression
+
+ Fix x86 SysV closure in PIC mode
+
+commit f08b2be6273f471863f1ea1afb0078a96fe73d74
+Merge: c194448 482b37f
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 10 23:21:49 2018 -0500
+
+ Merge pull request #405 from andreas-schwab/master
+
+ Fix passing struct by value on aarch64
+
+commit 482b37f00467325e3389bab322525099860dd9aa
+Author: Andreas Schwab <schwab@suse.de>
+Date: Mon Sep 18 12:44:08 2017 +0200
+
+ Fix passing struct by value on aarch64
+
+ This fixes the ctypes test in the python testsuite.
+
+commit 28d3b61bdd8b9fe786cb431165f2fb95f4e275d3
+Author: Ole André Vadla Ravnås <oleavr@gmail.com>
+Date: Sat Jan 20 23:56:17 2018 +0100
+
+ Fix x86 SysV closure in PIC mode
+
+ The assembly single-line comments swallowed up the remaining assembly
+ code of the macros due to lack of line-endings.
+
+ This is a regression introduced in b7f6d7a.
+
+commit c194448ef08b4c0183c68dda95a4b8b9cfc47985
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 10 09:38:15 2018 -0500
+
+ adjust env usage in travis
+
+commit 5314b1067145d30acdc5bba3bebb788e8acfdaae
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 10 07:22:51 2018 -0500
+
+ test static lib
+
+commit bec6135dff061a35065efc106f920940a82c28ee
+Merge: f6ecf10 d15581c
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 10 07:20:04 2018 -0500
+
+ Merge pull request #393 from thejunkjon/master
+
+ Linker error "recompile with -fPIC" for x86_64
+
+commit f6ecf10ca021e94d496c75cc43c417161edf28b3
+Merge: c50ba18 746dbe3
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Jan 5 16:51:44 2018 -0500
+
+ Merge pull request #401 from wzssyqa/jr-r6
+
+ mips/ffi.c: fix encoding for jr on r6
+
+commit 746dbe3a6a79a41931c03b51df2972be4d5e5028
+Author: YunQiang Su <wzssyqa@gmail.com>
+Date: Wed Jan 3 10:07:41 2018 +0800
+
+ mips/ffi.c: fix encoding for jr on r6
+
+ mips/ffi.c: instruction jr has a different encoding for r6
+
+commit c50ba182f43537e29dd92cfd9b2fa7a30549a06e
+Merge: 54cb3e2 af6949b
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 1 15:18:46 2018 -0500
+
+ Merge pull request #398 from emaste/master
+
+ Enable symbol versioning when ld is LLVM's lld
+
+commit 54cb3e2345ee8e2483d4705a9fb2967b6e5a9bd1
+Merge: 716bfd8 94c102a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Dec 31 07:46:05 2017 -0500
+
+ Merge pull request #396 from wzssyqa/master
+
+ mips/n32.S: disable .set mips4 on mips r6
+
+commit af6949b7af98404729e04227165d0e32ce550ce8
+Author: Ed Maste <emaste@freebsd.org>
+Date: Sun Dec 17 23:08:12 2017 -0500
+
+ Enable symbol versioning when ld is LLVM's lld
+
+ Fixes #397
+
+commit 94c102aa69b04337f63498e0e6551fcdce549ae5
+Author: YunQiang Su <wzssyqa@gmail.com>
+Date: Sun Dec 10 14:25:01 2017 +0800
+
+ Not set mips on mips r6
+
+ MIPS release changed encodes of some instructions, include ll/sc etc.
+
+ if .set mips4 on mips r6, as will generate some wrong encode of some instructions.
+
+commit d15581c6969657c79afcff4865bdc8f5ff23a2f7
+Author: jon <thejunkjon@gmail.com>
+Date: Fri Dec 1 00:34:30 2017 -0800
+
+ Updating calls to ffi_closure_unix64_inner and ffi_closure_win64_inner to use PLT. Without this fix, statically linking libffi causes the linker error i.e. 'requires dynamic R_X86_64_PC32 reloc against ffi_closure_unix64_inner which may overflow at runtime; recompile with -fPIC)'
+
+commit 716bfd83177689e2244c4707bd513003cff92c68
+Merge: 4fdbb05 cd5e9f8
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Nov 5 09:02:37 2017 -0500
+
+ Merge pull request #387 from trofi/master
+
+ Makefile.am: add 'src/s390/internal.h' to source tarball
+
+commit cd5e9f8b87cc387d3ffef4db81ee6af200a84183
+Author: Sergei Trofimovich <slyfox@gentoo.org>
+Date: Sun Nov 5 13:56:42 2017 +0000
+
+ Makefile.am: add 'src/s390/internal.h' to source tarball
+
+ commit 2f530de168e0253ac06e044c832132c496e8788b
+ ("s390: Reorganize assembly") introduced new header
+ (similar to other arches) but did not add it to source
+ tarball.
+
+ As a result build from 'make dist' tarballs failed as:
+
+ ```
+ ../src/s390/ffi.c:34:10: fatal error: internal.h: No such file or directory
+ #include "internal.h"
+ ^~~~~~~~~~~~
+ ```
+
+ To fix it the change adds file to 'Makefile.am'.
+
+ Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
+
+commit 4fdbb0578e921a9da146c2b040061a3a39fe4fda
+Merge: b302bc3 2bfcd29
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 3 07:05:31 2017 -0400
+
+ Merge pull request #320 from 0-wiz-0/master
+
+ Support NetBSD with mprotect.
+
+commit b302bc3dfe47e3ea57de11610fced3170c06df28
+Merge: 14eac93 1fb788a
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 3 07:03:55 2017 -0400
+
+ Merge pull request #322 from compnerd/aarch64-base
+
+ aarch64: fix index base register for AArch64
+
+commit 14eac93869eb109bea1daeb4f00609169d5488ff
+Merge: ad15ae7 9fc9dc5
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 3 06:49:03 2017 -0400
+
+ Merge pull request #384 from yan12125/fix-sgidefs-checking
+
+ Fix linux detection (closes #303)
+
+commit 9fc9dc535ee7af28f49f86a8ecacb7f575c46ba4
+Author: Yen Chi Hsuan <yan12125@gmail.com>
+Date: Fri Oct 27 16:12:56 2017 +0800
+
+ Fix linux detection (closes #303)
+
+commit 1fb788ac898290d8e3044ca4c0a4fb3c3c254ce5
+Author: Saleem Abdulrasool <compnerd@compnerd.org>
+Date: Tue Oct 10 11:37:00 2017 -0700
+
+ aarch64: fix index base register for AArch64
+
+ The base is passed in `x3`, not in `x2`. This fixes the indexing base
+ so that the right value is used.
+
+commit ad15ae762c8b3999e626ebccb9cf454455119555
+Merge: dc2ff5b 5e4fcdc
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Oct 25 13:16:49 2017 -0400
+
+ Merge pull request #298 from frida/fix/ios-trampoline-table-complexity
+
+ Simplify iOS trampoline table allocation
+
+commit dc2ff5baabf89d473d61ae4b468638f8ea98bb04
+Merge: 927da71 79d1509
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Oct 25 13:11:40 2017 -0400
+
+ Merge pull request #323 from compnerd/x86-alloca-alignment
+
+ x86: align alloca to 16-byte boundary
+
+commit 927da71662f349f656fc1c5d0aaa533005e24f47
+Merge: a0455c0 181fc4c
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Oct 25 13:05:53 2017 -0400
+
+ Merge pull request #379 from jlj/master
+
+ Xcode build improvements
+
+commit a0455c031824c6ab3f1a7a6ef9912edad6ebd742
+Merge: 0faf614 9d9d92b
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Oct 25 13:04:23 2017 -0400
+
+ Merge pull request #383 from hjl-tools/hjl/master
+
+ Hjl/master
+
+commit 0faf614529ae7ac8bc929415a6e1b076ba1b8cc5
+Merge: 8d26e8c 3c372c3
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Oct 25 13:03:55 2017 -0400
+
+ Merge pull request #381 from compnerd/ffi-nullptr-deref
+
+ arm: fix a level of indirection issue
+
+commit 9d9d92b47f3f73644f808ae38e97d1ea8f4d22df
+Author: H.J. Lu <hjl.tools@gmail.com>
+Date: Wed Oct 25 04:59:31 2017 -0700
+
+ Skip WIN64/EFI64 support for x32
+
+ Since x32 doesn't support WIN64/EFI64, skip it if __ILP32__ is defined.
+
+commit b2a343ffc68f1af5368281e063c0ca5571c611cc
+Author: H.J. Lu <hjl.tools@gmail.com>
+Date: Wed Oct 25 04:36:49 2017 -0700
+
+ Don't include WIN64/EFI64 for x32
+
+ Since x32 doesn't support WIN64/EFI64, don't include it for x32. Also
+ x32 has sizeof size_t == 4. But TARGET should be X86_64.
+
+commit 3c372c384a94db23fdaf9fe64a4beb86159cf6d3
+Author: Saleem Abdulrasool <compnerd@compnerd.org>
+Date: Tue Oct 24 13:53:56 2017 -0700
+
+ arm: fix a level of indirection issue
+
+ Rather than relying on the stack being 0'ed out always, do it manually.
+ The stack generally happened to be zero, and because the compiler
+ realizes that the tests are dealing with chars truncates the read value.
+ However, the top 3 nibbles of the value are undefined and may be
+ non-zero. The indirection level caused a null-pointer dereference.
+
+ Explicitly scribbling on the stack during the allocation causes test
+ failures without the original zexting behaviour.
+
+commit 181fc4cc9ca211f3bc8209cecf3b2348b0674e21
+Merge: 8d26e8c 54529ba
+Author: Jean-Luc Jumpertz <jean-luc@celedev.eu>
+Date: Mon Oct 23 15:02:29 2017 +0200
+
+ Merge branch 'master' based on ksjogo/libffi
+
+ Added a tvOS target in Xcode project. Misc Xcode project cleanup.
+ Fix macOS build target in Xcode project.
+
+ # Conflicts:
+ # src/aarch64/ffi.c
+ # src/x86/ffi64.c
+
+commit 54529ba1db9974b5efcbd2e893c44b6b01b0b2c8
+Author: Jean-Luc Jumpertz <jean-luc@celedev.eu>
+Date: Mon Oct 23 09:49:35 2017 +0200
+
+ Added a tvOS target in Xcode project. Misc Xcode project cleanup.
+
+commit 79d1509cb06ba9067f56e2c62394d7bc60fa6bf2
+Author: Saleem Abdulrasool <compnerd@compnerd.org>
+Date: Tue Oct 10 11:39:45 2017 -0700
+
+ x86: align alloca to 16-byte boundary
+
+ Align the stack allocation to a 16-byte boundary. This ensures that the
+ stack parameters are 16-byte aligned which is needed for some
+ instructions.
+
+commit 8d26e8c6da23b10331181a4bbf837f479ce5d7d2
+Merge: 1c9171e ed7488c
+Author: Tom Tromey <tom@tromey.com>
+Date: Tue Oct 17 10:46:49 2017 -0600
+
+ Merge pull request #326 from trofi/master
+
+ src/ia64/unix.S: unbreak small struct handling
+
+commit ed7488c003765c7ee71b7da3e8c21f431b043809
+Author: Sergei Trofimovich <slyfox@gentoo.org>
+Date: Tue Oct 17 13:00:51 2017 +0100
+
+ src/ia64/unix.S: unbreak small struct handling
+
+ commit 6e8a4460833594d5af1b4539178025da0077df19
+ added FFI_TYPE_COMPLEX value type (comes after FFI_TYPE_POINTER)
+
+ ia64 ffi_closure_unix reiles on the ordering of
+ FFI_ enums as ia64 has ia64-specific FFI types:
+ small struct and FPU extesions.
+
+ As a result all tests handling small structs broke.
+
+ The change fixes dispatch table by adding (no-op)
+ FFI_TYPE_COMPLEX entry
+ This has positive effect of unbreaking most tests
+ on ia64:
+
+ === libffi Summary ===
+
+ -# of expected passes 1595
+ -# of unexpected failures 295
+ +# of expected passes 1930
+ +# of unexpected failures 10
+ # of unsupported tests 30
+
+ Signed-off-by: Sergei Trofimovich <slyfox@gentoo.org>
+
+commit 1c9171ec89943d9b4b10a54091c8b5c104eb258d
+Merge: 9f1f874 7ad0ae7
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 10 23:19:57 2017 -0400
+
+ Merge pull request #324 from compnerd/arm-zext
+
+ arm: zext return value parameters
+
+commit 7ad0ae7f42f3e208431ab66a9032dc9549f978d0
+Author: Saleem Abdulrasool <compnerd@compnerd.org>
+Date: Tue Oct 10 11:44:05 2017 -0700
+
+ arm: zext return value parameters
+
+ The closure function (invoked as closure->fun in ffi_closure_XXX_inner)
+ will only populate the actual number of bytes for the true return type,
+ which may be a character. This leaves garbage on the stack when the
+ assembly closure function (i.e. ffi_closure_XXX) reads the return value
+ off of the stack into r0 as a 4-byte value. ffi_closure_XXX always
+ leaves room for at least 4 bytes here, so we can safely set them to 0.
+ Otherwise, if there is garbage in any of these bytes, these end up in r0
+ and in the returned value as well.
+
+commit 2bfcd29955c02b67fa10a68cc4200f6838181e0f
+Author: Joerg Sonnenberger <joerg@NetBSD.org>
+Date: Mon Oct 2 15:34:03 2017 +0200
+
+ Support NetBSD with mprotect.
+
+ Signed-off-by: Thomas Klausner <wiz@NetBSD.org>
+
+commit 9f1f8741b2ec0c8898ecff7b93005627b915dd02
+Merge: dca078f 6cf0dea
+Author: Tom Tromey <tom@tromey.com>
+Date: Sun Oct 1 20:25:50 2017 -0600
+
+ Merge pull request #319 from angerman/patch-5
+
+ Adds `local.exp` to DISTCLEANFILES
+
+commit 6cf0dea78a5a4584eda871e264043974d0453e53
+Author: Moritz Angermann <moritz.angermann@gmail.com>
+Date: Mon Oct 2 10:20:16 2017 +0800
+
+ Change CLEANFILES to DISTCLEANFILES
+
+commit dca078f468ff696134195e85fed3f48260115651
+Merge: 540258d bccba9a
+Author: Tom Tromey <tom@tromey.com>
+Date: Sun Oct 1 20:19:53 2017 -0600
+
+ Merge pull request #316 from angerman/patch-2
+
+ Add `configure.host` and `libtool-version` to the `EXTRA_DIST` files
+
+commit 540258d13e1d427254cbeddacdd2bb1ab2c307d1
+Merge: 93d8e7d 4c6aa78
+Author: Tom Tromey <tom@tromey.com>
+Date: Sun Oct 1 20:17:02 2017 -0600
+
+ Merge pull request #317 from angerman/patch-3
+
+ Add src/x86/asmnames.h to noinst_HEADERS
+
+commit bccba9a34e8ba0fe671c4b94671fea2efe181b01
+Merge: a1e6ccb 59d65d7
+Author: Moritz Angermann <moritz.angermann@gmail.com>
+Date: Sun Oct 1 12:48:17 2017 +0800
+
+ Merged
+
+commit 6b6df1a7bb377651a07663879bd4162f0059dc5c
+Author: Moritz Angermann <moritz.angermann@gmail.com>
+Date: Sun Oct 1 12:37:53 2017 +0800
+
+ Adds `local.exp` to CLEANFILES
+
+ With #315, #316, #317, #318 and this patch, running
+ ```
+ AM_DISTCHECK_CONFIGURE_FLAGS=--disable-docs make distcheck
+ ```
+ should complete successfully.
+
+commit 59d65d74ae72bd24fbf78f045592c5168f0b0784
+Author: Moritz Angermann <moritz.angermann@gmail.com>
+Date: Sun Oct 1 12:23:31 2017 +0800
+
+ Include `libtool-version` in the EXTRA_DIST files.
+
+commit 4c6aa78d75f0c426a23c27af74155aa2535021d6
+Author: Moritz Angermann <moritz.angermann@gmail.com>
+Date: Sun Oct 1 11:32:41 2017 +0800
+
+ Add src/x86/asmnames.h to noinst_HEADERS
+
+ In eaa59755fcbb692a8cb763c7f9f24a350aadbd30, macros from `unix64.S` were extracted into `asmnames.h` to be used with `win64.S` as well. As such these are required by `unix64.S`, which fails to build without them.
+
+commit a1e6ccb67e7d7f2b235016aa6c6733c5743945a1
+Author: Moritz Angermann <moritz.angermann@gmail.com>
+Date: Sun Oct 1 11:28:40 2017 +0800
+
+ Add `configure.host` to the `EXTRA_DIST` files
+
+ When running `make dist`, `configure.host` would not result in the distribution tarball, however `configure` would try to read it, and as such the tarball would not be buildable.
+
+commit 93d8e7dd17b08ff195af3580584ccd5c2228202f
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Sep 27 21:51:34 2017 -0400
+
+ Fix #265
+
+commit 02a5145abbae2e311d5aeeee606c5b5745a99b55
+Merge: 10099d6 7d504f7
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Sep 27 21:43:03 2017 -0400
+
+ Merge pull request #263 from ksjogo/master
+
+ fix ios builds
+
+commit 10099d6cad8418a10c1508235d1f458993ac51fe
+Merge: c8f1aa3 ed84883
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Sep 27 20:54:09 2017 -0400
+
+ Merge pull request #271 from frida/fix/qnx-cache-flushing
+
+ arm: Fix cache flushing on QNX
+
+commit c8f1aa3d0459c6f1be6884b324b4d2d785ecfd78
+Merge: db4dad9 50e408c
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Sep 27 20:53:50 2017 -0400
+
+ Merge pull request #307 from zw3rk/master
+
+ Support -ios triple
+
+commit db4dad97e2589ca700d1b5b54eeb332137a152ad
+Merge: 8a16f2f 9c12209
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Sep 27 20:47:08 2017 -0400
+
+ Merge pull request #312 from fjricci/fix_ub
+
+ Fix misaligned memory access in ffi_call_int
+
+commit 8a16f2f47fdb6a985d201baa02a1d226562af4d8
+Merge: b230910 0ff9419
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Sep 27 20:45:15 2017 -0400
+
+ Merge pull request #308 from trex58/master
+
+ This patch enables FFI Go Closure on AIX.
+
+commit a78da73956e4b0af4556f1c0a444bd0f065c3965
+Author: Jean-Luc Jumpertz <jean-luc@celedev.eu>
+Date: Mon Sep 4 15:55:34 2017 +0200
+
+ Fix macOS build target in Xcode project.
+
+ - Add missing files for desktop platforms in generate-darwin-source-and-headers.py, and in the Xcode project.
+ - Add a static library target for macOS.
+ - Fix "implicit conversion loses integer precision" warnings for iOS mad macOS targets.
+
+commit 9c12209d2eac40238eefb4255994277918e7eff1
+Author: Francis Ricci <francisjricci@gmail.com>
+Date: Thu Aug 3 10:46:28 2017 -0700
+
+ Fix misaligned memory access in ffi_call_int
+
+commit b23091069adce469dc38fbcc9fd8ac9085d3c9d7
+Merge: c0cc9f1 9c6cb58
+Author: Tom Tromey <tom@tromey.com>
+Date: Wed Jul 12 12:43:06 2017 -0600
+
+ Merge pull request #309 from rurban/oldgcc
+
+ __attribute__ deprecated (msg) only since gcc 4.5
+
+commit 9c6cb58812aa92a4c56a94b2b51bd85b2aebc2a1
+Author: Reini Urban <rurban@cpan.org>
+Date: Sun Jun 18 18:26:05 2017 +0200
+
+ __attribute__ deprecated (msg) only since gcc 4.5
+
+ make it work with older compilers
+
+commit 50e408ce5d9eb6f14bf82bb3894d0e74e5f19c2c
+Author: Moritz Angermann <moritz.angermann@gmail.com>
+Date: Sun May 21 20:44:10 2017 +0800
+
+ add i?86-*-ios -- the iOS simulator (32bit)
+
+commit a08cabe6746343564418383b879d40d3b998c399
+Author: Moritz Angermann <moritz.angermann@gmail.com>
+Date: Sun May 21 20:25:16 2017 +0800
+
+ add x86_64-*-ios -- the iOS simulator
+
+commit 0ff9419f2e75652426469e256cb7d0748064ad58
+Author: Tony Reix <tony.reix@bull.net>
+Date: Wed May 17 14:57:53 2017 +0200
+
+ This patch enables FFI Go Closure on AIX.
+
+commit 19ab448d84223d2992048bce4e926eac2c44f606
+Author: Moritz Angermann <moritz.angermann@gmail.com>
+Date: Tue May 16 08:32:06 2017 +0800
+
+ Support -ios triple
+
+ Autoconf hasn’t had an update since 2014, and it doesn’t look like it will soon[1]
+ This updates config.{guess,sub}
+
+ It adds support for e.g. `-ios`, which allows to have targets like `aarch64-apple-ios`.
+
+ It basically does exactly what the config.guess script says:
+ > It is advised that you download the most up to date version of the config scripts from
+
+ The configure.ac script has been updated to relax `*-apple-darwin*` to `*-apple-*`.
+ Similarly the `.gitignore` and `autogen.sh` needed to be updated to respect the
+ newer `config.{sub,guess}`
+
+ —
+ [1]: http://lists.gnu.org/archive/html/autoconf/2016-07/msg00017.html
+
+commit c0cc9f1df9fd4c5e758470f05d0e48123f0638ae
+Merge: b841ae7 bd72848
+Author: Tom Tromey <tom@tromey.com>
+Date: Mon May 8 15:20:39 2017 -0600
+
+ Merge pull request #302 from gpakosz/align-macros
+
+ Prefix ALIGN macros with FFI_
+
+commit bd72848c7af9302df50a7a11652c77166d17caa8
+Author: Gregory Pakosz <gregory.pakosz@gmail.com>
+Date: Thu Apr 27 13:20:36 2017 +0200
+
+ Prefix ALIGN macros with FFI_
+
+commit 7d504f7a8e33f6da27941f5dc5d889fe60b8b9c8
+Author: ksjogo <jogo@kronberger-spiele.de>
+Date: Thu Mar 30 13:32:58 2017 +0200
+
+ update for xcode 8.3
+
+commit 57d8ff044cd6320d8ebacacf06455569b4aac27d
+Author: Ole André Vadla Ravnås <oleavr@gmail.com>
+Date: Wed Mar 15 01:43:11 2017 +0100
+
+ Simplify iOS trampoline table allocation
+
+ By using VM_FLAGS_OVERWRITE there is no need for speculatively
+ allocating on a page we just deallocated. This approach eliminates the
+ race-condition and gets rid of the retry logic.
+
+commit 7f558a9ba4e74edf54a3e95e983e8a59ddb0cc7c
+Author: ksjogo <jogo@kronberger-spiele.de>
+Date: Mon Jul 25 01:18:30 2016 +0200
+
+ set ios deployment target to 7.0
+
+commit e76fa94b6ef9a699ee9edeb85d1731d3bb7abd46
+Author: ksjogo <jogo@kronberger-spiele.de>
+Date: Thu Jul 14 11:28:18 2016 +0200
+
+ fix ltmain.sh in xcode builds
+
+commit 22b2fd6f18eed7b32ea959f7f3e56ea09b9ac9bf
+Author: ksjogo <jogo@kronberger-spiele.de>
+Date: Wed Jul 13 14:40:07 2016 +0200
+
+ add valid architectures
+
+commit 0040694505411785ec98e660fe81faad9630f515
+Author: Johannes Goslar <johannes.goslar@kronberger-spiele.de>
+Date: Tue Jul 12 16:08:42 2016 +0200
+
+ Update Xcodeproj
+
+ Include all currently relevent files.
+ Call autogen is build script.
+ Fix compiler settings.
+ Fix mach include.
+
+commit b841ae70a05a5e11de1fca1b4551189db0895cf2
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 19 07:42:09 2017 -0400
+
+ remove stray quote
+
+commit a94c999ba0d51ed8ec88685233f5b1ae38e894ea
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 19 07:36:07 2017 -0400
+
+ Handle fastcall declaration differently for some Microsoft compilers
+
+commit 69963d39ab7d7f201b4597ed7a24cf438e0a34bf
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 19 07:33:39 2017 -0400
+
+ We don't support 32-bit builds with the Microsoft toolchain
+
+commit 073bc9d50c1ce753735944e4228d9a401e964306
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 19 07:25:24 2017 -0400
+
+ Enable appveyor ci support
+
+commit a0b14eea2baf9f18c0d29bc5ce4495422381f917
+Merge: fa5a0fe 1e0d107
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Mar 17 09:20:40 2017 -0400
+
+ Merge pull request #291 from ramon-garcia/visual-studio-build
+
+ Build with Visual C++ (64 bits)
+
+commit fa5a0fe2c6da906cc7c114c8002e5c7092c4dbee
+Merge: 5b91bbd bfab429
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Mar 16 07:50:07 2017 -0400
+
+ Merge pull request #238 from KubaKaszycki/master
+
+ Update README with a new port
+
+commit 5b91bbd388213ec19044a392c291505e2c0674b9
+Merge: d754c51 982b89c
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Mar 16 00:40:58 2017 -0400
+
+ Merge pull request #288 from yan12125/std-includedir
+
+ Install public headers in the standard path
+
+commit d754c510f1dd03dc8c2cd7b50bb2a1668715c5cd
+Merge: ebe7f44 41185b5
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Mar 16 00:39:07 2017 -0400
+
+ Merge pull request #299 from matijaskala/patch-1
+
+ detect other x32 hosts
+
+commit ebe7f447abcfbf1a16dbfca26538fff03faf7c6b
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Mar 16 00:36:10 2017 -0400
+
+ Remove osx testing. gcc was symlinked to clang. dejagnu c++ tests fail with clang.
+
+commit c9c2aa24611ec996f45a495f24d690688f3ffed6
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 15 09:58:39 2017 -0400
+
+ Revert previous two changes. clang/MacOS problem can only be solved within dejagnu.
+
+commit 5a8fca94059fbf14ac7352ce487c9250cdd67c63
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 15 09:52:39 2017 -0400
+
+ Fix typo
+
+commit 5b10a0198188d43fc07c271bc29ff1033e2ac9d3
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 15 09:34:01 2017 -0400
+
+ Work around dejagnu/clang problems
+
+commit b6751258072fadadd487a6adf4962bf22b44746d
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 15 08:54:52 2017 -0400
+
+ Require sudo for installing packages
+
+commit 41185b565fe17a8f107642f480849ef369ad0baa
+Author: Matija Skala <mskala@gmx.com>
+Date: Wed Mar 15 12:50:41 2017 +0100
+
+ detect other x32 hosts
+
+ primarily x86_64-pc-linux-muslx32
+ while at it, add x86_64-x32-pc-linux-{gnu,musl} as well
+
+commit 6e2e041b6df6a3c3a5ca8a750dedbbd465e5ca97
+Merge: dabbd14 d42ce7b
+Author: Richard Henderson <rth@twiddle.net>
+Date: Tue Mar 14 19:37:45 2017 -0700
+
+ Merge pull request #297 from frida/fix/error-path
+
+ Fix error path so mutex is unlocked before returning
+
+commit 5e4fcdccb3a841f2daaa5834f726eaeb42950511
+Author: Ole André Vadla Ravnås <oleavr@gmail.com>
+Date: Wed Mar 15 01:43:11 2017 +0100
+
+ Simplify iOS trampoline table allocation
+
+ By using VM_FLAGS_OVERWRITE there is no need for speculatively
+ allocating on a page we just deallocated. This approach eliminates the
+ race-condition and gets rid of the retry logic.
+
+commit d42ce7b95c6d5cba7d976cc0c8c85f7645fa6b8f
+Author: Ole André Vadla Ravnås <oleavr@gmail.com>
+Date: Wed Mar 15 01:23:40 2017 +0100
+
+ Fix error path so mutex is unlocked before returning
+
+ In the unusual case where ffi_trampoline_table_alloc() fails.
+
+commit dabbd145665ffca6fa676eba551f12107cd81131
+Merge: 60e4250 6caabd1
+Author: Tom Tromey <tom@tromey.com>
+Date: Mon Feb 27 21:10:00 2017 -0700
+
+ Merge pull request #295 from terrillmoore/patch-1
+
+ Correct typos in libffi.texi
+
+commit 6caabd198ec24d090d85d7eca01150b44003c76b
+Author: Terry Moore <tmm@mcci.com>
+Date: Sun Feb 26 15:06:53 2017 -0500
+
+ Correct typos in libffi.texi
+
+ One "it's" should be "its", and one "is" should be "in".
+
+commit 1e0d107b4b237edd11ca3209a9cf59786f752fe5
+Author: Ramón García Fernández <ramon.garcia.f@gmail.com>
+Date: Sun Jan 8 20:12:59 2017 +0100
+
+ Modify configure.host to detect compilation with Microsoft Visual C++ and use assembly with Intel syntax in that case
+
+commit 982b89c01aca99c7bc229914fc1521f96930919b
+Author: Yen Chi Hsuan <yan12125@gmail.com>
+Date: Sun Nov 13 19:17:19 2016 +0800
+
+ Install public headers in the standard path
+
+commit 60e4250a77eb3fde500bfd68ec40519fe34b21bd
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Sep 4 09:34:18 2016 -0400
+
+ make executable
+
+commit c3caf38895252b82febb76c6bb323c67a4e01929
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Sep 4 09:21:18 2016 -0400
+
+ Update travis to test linux 32/64 and osx with a mix of gcc and clang
+
+commit c5b408ee78d097a495ea12467cf082f8008c8e17
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Sep 4 09:17:46 2016 -0400
+
+ xfail the unwindtest for osx as per issue #279
+
+commit 256ce51c408766d23b2707cc79b97f673750b3b9
+Merge: 2ded2a4 52a11f6
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Sep 1 13:54:51 2016 -0700
+
+ Merge pull request #273 from wbx-github/master
+
+ m68k: support ISA-A Coldfire CPUs
+
+commit 2ded2a4f494165c93293afc14ab0be1243cf8c49
+Merge: 408c9c7 e247b56
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Sep 1 13:30:45 2016 -0700
+
+ Merge pull request #272 from yousong/mips64-soft-float
+
+ Mips64 soft float
+
+commit 408c9c7d5a4cb323c77499b1643858f4bfaf4ca7
+Merge: 06d7c51 b545ff8
+Author: Tom Tromey <tom@tromey.com>
+Date: Tue Aug 23 11:32:17 2016 -0600
+
+ Merge pull request #274 from dr-hannibal/ykolerov-unused
+
+ ARC: Remove unused variable
+
+commit b545ff81f58233284cd6fca97a470aa3218c23e6
+Author: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
+Date: Tue Aug 23 20:23:37 2016 +0300
+
+ ARC: Remove unused variable
+
+ Signed-off-by: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
+
+commit 52a11f6d9152a56aa1fb6d04eb40fd76f4cce5ff
+Author: Waldemar Brodkorb <wbx@uclibc-ng.org>
+Date: Sat Aug 20 00:52:19 2016 +0200
+
+ m68k: support ISA-A Coldfire CPUs
+
+ Fix compilation for m68k/coldfire CPUs like mcf5208.
+
+ Signed-off-by: Thorsten Glaser <tg@mirbsd.de>
+ Signed-off-by: Waldemar Brodkorb <wbx@uclibc-ng.org>
+
+commit e247b562ac85565dfac33e676e2915489af04183
+Author: Yousong Zhou <yszhou4tech@gmail.com>
+Date: Mon Aug 15 17:34:37 2016 +0800
+
+ doc: fix typo
+
+ Name of last argument to ffi_get_struct_offsets is `offsets`, not `sizes`
+
+ Signed-off-by: Yousong Zhou <yszhou4tech@gmail.com>
+
+commit 7a0d2c83bf2b0422e2d0ed297f847fc1eeb88bb3
+Author: Yousong Zhou <yszhou4tech@gmail.com>
+Date: Mon Aug 15 15:00:13 2016 +0800
+
+ mips: fix MIPS softfloat build issue
+
+ The patch for o32.S is taken from OpenWrt packages repo 3a7a4bf "libffi:
+ fix MIPS softfloat build issue with current binutils"
+
+ Signed-off-by: Felix Fietkau <nbd@openwrt.org>
+ Signed-off-by: Yousong Zhou <yszhou4tech@gmail.com>
+
+commit 06d7c5190e910356d4212d2a79056df8b70fd27e
+Merge: aa7ed78 301166b
+Author: Tom Tromey <tom@tromey.com>
+Date: Wed Aug 10 15:06:16 2016 -0600
+
+ Merge pull request #269 from frida/fix/aarch64-variadic-closures-on-ios
+
+ aarch64: Fix handling of variadic closures on iOS
+
+commit aa7ed78c0e0d3fc4daa6a86c35ecbb7c43b5d067
+Merge: 1daa787 4da814b
+Author: Tom Tromey <tom@tromey.com>
+Date: Wed Aug 10 15:03:37 2016 -0600
+
+ Merge pull request #268 from frida/fix/aarch64-large-aggregates
+
+ aarch64: Fix handling of aggregates larger than 16 bytes
+
+commit 4da814b18a1bf1d2013d988e37485e568d6117d1
+Author: Ole André Vadla Ravnås <oleavr@gmail.com>
+Date: Wed Aug 10 22:48:09 2016 +0200
+
+ aarch64: Fix handling of aggregates larger than 16 bytes
+
+ Instead of allocating stack space for a pointer we would allocate stack
+ space for the actual aggregate size.
+
+commit 1daa78799942c83c905f8d7c5439952e9ffec3bc
+Merge: f03ba20 5e9ac7e
+Author: Tom Tromey <tom@tromey.com>
+Date: Wed Aug 10 14:31:09 2016 -0600
+
+ Merge pull request #270 from frida/fix/aarch64-warnings
+
+ Fix aarch64 warnings
+
+commit ed8488345eaae41c161ab741b0c44299ee99dc6c
+Author: s1341 <github@shmarya.net>
+Date: Wed Aug 10 14:57:22 2016 +0200
+
+ arm: Fix cache flushing on QNX
+
+ Use `msync()` directly as `__clear_cache()` is broken in the
+ qnx650_gcc4.8.3 toolchain.
+
+commit 5e9ac7e252dbb0b7025027c1b6e1a4f3ec48943f
+Author: Ole André Vadla Ravnås <oleavr@gmail.com>
+Date: Wed Aug 10 15:22:19 2016 +0200
+
+ aarch64: Fix warning about unused function on iOS
+
+commit 4d1f11f6a9effce05ba51578b142827834d1f699
+Author: Ole André Vadla Ravnås <oleavr@gmail.com>
+Date: Wed Aug 10 15:21:42 2016 +0200
+
+ aarch64: Fix operand size warning reported by Clang
+
+commit 301166b11e913f85d09f67af94264268811f23a9
+Author: Ole André Vadla Ravnås <oleavr@gmail.com>
+Date: Wed Aug 10 15:59:56 2016 +0200
+
+ aarch64: Fix handling of variadic closures on iOS
+
+commit f03ba2032850545dc6869bb495170a8c6cbf849d
+Merge: 40e4063 ef8be84
+Author: Tom Tromey <tom@tromey.com>
+Date: Tue Aug 2 10:23:25 2016 -0600
+
+ Merge pull request #266 from dr-hannibal/arc-pthread
+
+ Make testing easier outside of build directory and especially for ARC
+
+commit ef8be84de5f9e611add396efe908b772eb1cae1d
+Author: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
+Date: Fri Jul 29 21:01:38 2016 +0300
+
+ Do not use fabsl() in float2.c test
+
+ Some targets may support long double variables but in the same
+ time may lack support of long double functions like fabsl().
+
+ Signed-off-by: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
+
+commit f3201733d54bf26ac40c432f4305499dd3f20215
+Author: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
+Date: Fri Jul 29 19:18:41 2016 +0300
+
+ Fix output expectations in cls_dbls_struct.c test
+
+ This test with invalid output expectations may fail on some targets
+ (e.g. ARC processors).
+
+ Signed-off-by: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
+
+commit f74ea2dc7994b4867f7ab45169e1b2422072cc92
+Author: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
+Date: Thu Jul 28 20:57:09 2016 +0300
+
+ Allow setting an arbitary value for blddirffi in testsuite
+
+ It is useful when tests are executed not from build directory. So
+ the path of the build directory may be passed through site.exp or
+ runtest.
+
+ Signed-off-by: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
+
+commit 31362d785ed1db52516dfe02ebe8b163c53d29d0
+Author: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
+Date: Thu Jul 28 18:48:23 2016 +0300
+
+ ARC: Link tests with pthread library
+
+ Signed-off-by: Yuriy Kolerov <yuriy.kolerov@synopsys.com>
+
+commit 40e4063ab4449c644bc106298805fa8c6cfadbd4
+Merge: c0829e6 cf4b2a5
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Jul 7 23:11:38 2016 -0700
+
+ Merge pull request #261 from tromey/fix-260
+
+ Don't dereference "ecif" before NULL check
+
+commit cf4b2a50413ecb8931eb1a94437497694f189c47
+Author: Tom Tromey <tom@tromey.com>
+Date: Fri Jun 17 10:09:44 2016 +0100
+
+ Don't dereference "ecif" before NULL check
+
+ Fixes #260
+
+commit c0829e62841100c308cc37ddd6537ca69e856de7
+Merge: 96d9bf4 794a54d
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sun Jun 5 15:05:21 2016 -0700
+
+ Merge pull request #259 from rth7680/master
+
+ Mark win64.S with GNU-stack note
+
+commit 794a54d4a603639adf1a79d5b5bc15da437457e2
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sun Jun 5 14:57:00 2016 -0700
+
+ Mark win64.S with GNU-stack note
+
+commit 96d9bf4b5517bc49c0129e8cfdee43098d3771a2
+Merge: 02089a1 52fbd12
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Jun 3 23:04:56 2016 -0700
+
+ Merge pull request #253 from iains/darwin-build
+
+ Some Darwin build fixes
+
+commit 52fbd12dca1bddf0b135a24e7136f10af79a06bd
+Author: Iain Sandoe <iain@codesourcery.com>
+Date: Thu May 26 09:00:00 2016 +0100
+
+ [Darwin-ppc, build] Fixes for clang build.
+
+ clang is experimental on powerpc-darwin, but the changes are appropriate to cctools as as well.
+
+ Use the 'official' simplified cmpwi insn, rather than the implied one accepted by cctools.
+ Do not re-use a set value.
+
+commit 92810b4bc101fccead2234b7385d4fa5e7a3e56a
+Author: Iain Sandoe <iain@codesourcery.com>
+Date: Thu May 26 08:56:51 2016 +0100
+
+ [Darwin-x86, build] Fix up label prefixes, remove .purgem
+
+ Darwin uses a label prefix of _.
+ cctools assembler will not accept .purgem as a directive.
+
+commit 30b3440cfd378dc67111b1380f2654334d048659
+Author: Iain Sandoe <iain@codesourcery.com>
+Date: Thu May 26 08:55:04 2016 +0100
+
+ [Darwin, configure] Allow configure to work for <arch>-*-darwin.
+
+ The exec configury is appropriate for all current targets (including using older tools on them).
+
+commit 02089a1b5cf3aa1535172c62add454a2e9375066
+Merge: 5d0365c c884551
+Author: Tom Tromey <tom@tromey.com>
+Date: Mon May 23 09:58:51 2016 -0600
+
+ Merge pull request #237 from tschwinge/libffi_feature_test
+
+ Simplify/fix libffi_feature_test
+
+commit 5d0365c605c472f40d1195cf7ba04ae08e360cb7
+Merge: 584a140 74b3f52
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu May 19 09:35:38 2016 -0700
+
+ Merge pull request #251 from berkerpeksag/delete-test-define
+
+ Remove unused FFI_CLOSURE_TEST
+
+commit 74b3f5201432c37e40e24386fa193c838596cec8
+Author: Berker Peksag <berker.peksag@gmail.com>
+Date: Thu May 19 18:05:36 2016 +0300
+
+ Remove unused FFI_CLOSURE_TEST
+
+ It was here since the first commit c6dddbd (warning: huge diff) and
+ it wasn't defined by the configure script. It was probably used
+ manually during development.
+
+commit 584a140e7558dff6e4ed4009f39d11dd5e3db0ae
+Merge: c617754 b3496de
+Author: Tom Tromey <tom@tromey.com>
+Date: Thu May 19 06:36:38 2016 -0600
+
+ Merge pull request #248 from berkerpeksag/patch-1
+
+ Delete empty env in .travis.yml
+
+commit b3496dedbbad6c1f4e5bf4cc100e76b86f3c801e
+Author: Berker Peksag <berker.peksag@gmail.com>
+Date: Thu May 19 10:53:07 2016 +0300
+
+ Delete empty env in .travis.yml
+
+commit c61775497e7bdfc892d865c2eb15415d2da7493b
+Merge: 9edaa69 33d9a31
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed May 18 11:10:33 2016 -0700
+
+ Merge pull request #247 from rth7680/symver
+
+ Add parent to symbol version LIBFFI_BASE_7.1
+
+commit 33d9a31d34cfba63e1294978114be1bddd2de3fd
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed May 18 11:01:55 2016 -0700
+
+ Add parent to symbol version LIBFFI_BASE_7.1
+
+commit 9edaa695c54daaf58d62e84032d30d33b7484fa8
+Merge: 0969a1c 8a0a4e2
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed May 18 10:56:19 2016 -0700
+
+ Merge pull request #230 from rth7680/symver
+
+ Use ELF symbol versioning
+
+commit 0969a1c1b339f845202fa7507b70d193220ceb01
+Merge: 571b1ca 4a677a4
+Author: Tom Tromey <tom@tromey.com>
+Date: Wed May 18 10:09:28 2016 -0600
+
+ Merge pull request #232 from berkerpeksag/signcompare
+
+ Fix -Wsign-compare warnings in x86/ffi64.c
+
+commit 571b1ca6277dbafc1f340a59ea1c5ee4ddb11c94
+Merge: 069d2e4 1e82e1c
+Author: Tom Tromey <tom@tromey.com>
+Date: Wed May 18 10:08:59 2016 -0600
+
+ Merge pull request #233 from berkerpeksag/mremap
+
+ Define _GNU_SOURCE on Linux for mremap()
+
+commit 069d2e4e16c5570adec9249d642f2a2ae0ffaa1c
+Merge: a44a5b8 1b4f5ee
+Author: Tom Tromey <tom@tromey.com>
+Date: Wed May 18 10:07:31 2016 -0600
+
+ Merge pull request #246 from berkerpeksag/update-github-links
+
+ Update project URLs to use libffi/libffi
+
+commit 1b4f5ee6a4989d7eda7766c5864908c389586c6f
+Author: Berker Peksag <berker.peksag@gmail.com>
+Date: Wed May 18 11:12:58 2016 +0300
+
+ Update project URLs to use libffi/libffi
+
+commit 1e82e1cda43dacd8b6ab2d9ac4db33523d86f5dc
+Author: Berker Peksag <berker.peksag@gmail.com>
+Date: Mon Mar 7 18:38:10 2016 +0200
+
+ Define _GNU_SOURCE on Linux for mremap()
+
+ This was committed to CPython's libffi copy in
+ https://bugs.python.org/issue10309
+
+ mremap() documentation says _GNU_SOURCE needs to
+ be defined in order to use mremap(): see the
+ synopsis section at http://linux.die.net/man/2/mremap
+
+ Original commit: https://hg.python.org/cpython/rev/9986fff720a2
+
+ Original patch was written by Hallvard B Furuseth.
+
+commit 4a677a425c18eda4bc5357b2485da57f133f908d
+Author: Berker Peksag <berker.peksag@gmail.com>
+Date: Sat Mar 5 09:58:38 2016 +0200
+
+ Fix -Wsign-compare warnings in x86/ffi64.c
+
+ This was originally reported on the Python tracker:
+
+ httpa://bugs.python.org/issue23958
+
+ The original patch was written by Steve R. Hastings.
+
+ I've updated it to current master of libffi.
+
+commit a44a5b863aaae98041e11aa3256907bf912ee4d6
+Merge: 9443eae 2627fc9
+Author: Tom Tromey <tom@tromey.com>
+Date: Tue May 17 17:07:27 2016 -0600
+
+ Merge pull request #234 from berkerpeksag/disable-docs
+
+ Add a note about the --disable-docs switch
+
+commit 9443eaeda867cfdeae92b10bee3cc0506892a4c5
+Merge: 14be9a1 e169ba2
+Author: Tom Tromey <tom@tromey.com>
+Date: Tue May 17 17:04:50 2016 -0600
+
+ Merge pull request #242 from somasis/master
+
+ Fix usage on musl libc
+
+commit 8a0a4e25ef99f4ec98761f2fc075c2e8409f171b
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed May 4 07:33:41 2016 -1000
+
+ Update symbol versioning for ffi_get_struct_offsets
+
+ Given that the original symbol versioning patch has shipped
+ with gcc-6, it would be kind to keep that as a valid base ABI
+ and make subsequent changes to version 7.1.
+
+commit c02c3414440e816aa13a2fe8446484173d3edb0e
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Mar 3 13:51:44 2016 -0800
+
+ Use ELF symbol versioning
+
+ At the same time, we must bump the (major) ABI version. This needed to be
+ done anyway due to ABI breakage in the AArch64 port (see 12cf89ee and the
+ corresponding GCC PR70024).
+
+commit 14be9a1d0713deb97edb91fe9800afe971a001d5
+Merge: 1cea273 b50eabf
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed May 4 06:45:05 2016 -1000
+
+ Merge pull request #245 from rth7680/tromey-ffi-prep-cif-core-is-private
+
+ A rebase of #219
+
+commit b50eabf48927ccaf0184c6224992bbb0a125e969
+Author: Tom Tromey <tom@tromey.com>
+Date: Mon Feb 22 16:00:51 2016 -0700
+
+ minor comment cleanup
+
+ This patch minor cleans up ffi.h.in comments in a minor way. It fixes
+ some typos and capitalizations, adds some periods, and reformats some
+ comments to a more GNU-ish style. It also fixes up some stale
+ documentation.
+
+commit 6c07077a61fd0dc5ac11759ea1b4345acf486f3c
+Author: Tom Tromey <tom@tromey.com>
+Date: Sun Feb 21 20:08:21 2016 -0700
+
+ Change ffi.h.in so that braces match
+
+ This is a tiny refactoring to make it so brace-matching works in
+ Emacs.
+
+commit 2fbc0369b89a7e6b089e6384b98dba904ec1cf8b
+Author: Tom Tromey <tom@tromey.com>
+Date: Thu Nov 19 16:38:35 2015 -0700
+
+ move ffi_prep_cif_core to ffi_common.h
+
+commit 1cea273758ad862bdc2862af864e4ef5b42f31ae
+Merge: 48bfae1 6aafb56
+Author: Tom Tromey <tom@tromey.com>
+Date: Tue May 3 08:23:51 2016 -0600
+
+ Merge pull request #231 from berkerpeksag/simplfy-oserror
+
+ Simplify error handling in mkdir_p()
+
+commit 48bfae1f37551b7fc894e6a0ea3b98968d2b5c9f
+Merge: 6d87110 d76975d
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon May 2 20:58:57 2016 -1000
+
+ Merge pull request #236 from andreas-schwab/master
+
+ Define FFI_SIZEOF_JAVA_RAW for aarch64 ILP32
+
+commit 6d8711057bc3a3befa37eed6765231ea5d244078
+Merge: 9de24a3 e5843a3
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sun May 1 11:02:40 2016 -1000
+
+ Merge pull request #241 from rth7680/fix-win64
+
+ Fix win64 abi calling from unix64
+
+commit e169ba2b83c780058fe626856cfdb5903a85cb97
+Author: Kylie McClain <somasis@exherbo.org>
+Date: Fri Apr 29 21:04:07 2016 -0400
+
+ Fix usage on musl libc
+
+ A gcc compiled on musl does not define __gnu_linux__, it defines __linux__.
+ Only on glibc does __gnu_linux__ get defined, but both define __linux__, so
+ we should check for that instead.
+
+ With this patch, libffi works perfectly, and passes its testsuite entirely
+ on musl libc systems.
+
+commit e5843a3a09976f9d8fa77671e9d6c188c890199d
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Apr 15 16:10:08 2016 -0700
+
+ x86: Fix calling convention for ffi_closure_win64_inner
+
+ Also enable testing for the cross-abi calls.
+
+commit d06751979bf0e4c9caabf0bca531d74de8cb9152
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon Mar 7 12:14:22 2016 -0500
+
+ x86: Copy fix for clang .org from unix64.S
+
+ Clang doesn't understand .org with symbolic operands.
+
+commit bfab429ee479723cc65831a7e4327e2866036420
+Author: Jakub Kaszycki <kaszycki@mail.com>
+Date: Fri Apr 1 21:42:41 2016 +0200
+
+ Update README with a new port
+
+ This is in fact not a NEW port. Apple Mac devices are generally x86-64 now, x86 rarely. If GCC exists for this CPU, it means that libffi has been built too.
+
+commit c88455178151bea14b8561ab6830724c31af255e
+Author: Thomas Schwinge <thomas@codesourcery.com>
+Date: Thu Feb 25 20:10:18 2016 +0100
+
+ Simplify/fix libffi_feature_test
+
+ As detailed in
+ <http://news.gmane.org/find-root.php?message_id=%3C87wppswqqt.fsf%40kepler.schwinge.homeip.net%3E>,
+ the original code (originally added in commit
+ f1301a54bb80e6ae23f7687c68f36875dae69134 as part of pull request #145) does not
+ work (at least not for me, in the GCC environment).
+
+commit d76975dbd2854beca7acbca946c4cbccf9bf7cee
+Author: Andreas Schwab <schwab@suse.de>
+Date: Wed Mar 16 12:23:07 2016 +0100
+
+ Define FFI_SIZEOF_JAVA_RAW for aarch64 ILP32
+
+ Like x32, aarch64 ILP32 needs to define FFI_SIZEOF_JAVA_RAW. This fixes
+ the java interpreter.
+
+commit 9de24a3ff31c7446de29c1adcd9276fd7ba93897
+Merge: ee71806 38a4d72
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Mar 14 13:54:53 2016 -0400
+
+ Merge pull request #212 from tromey/struct-layout
+
+ add ffi_get_struct_offsets
+
+commit 2627fc98e86e906fd7c9bc16bf345b91ee26d2ba
+Author: Berker Peksag <berker.peksag@gmail.com>
+Date: Mon Mar 7 18:43:03 2016 +0200
+
+ Add a note about the --disable-docs switch
+
+ Closes #204
+
+commit 6aafb5654d6741927276efff1af72a5b3614da39
+Author: Berker Peksag <berker.peksag@gmail.com>
+Date: Sat Mar 5 08:30:31 2016 +0200
+
+ Simplify error handling in mkdir_p()
+
+commit ee718066f763b65d1888f9cc7155d3a1880f80e9
+Merge: f2f234a e59fb55
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Feb 22 20:15:40 2016 -0500
+
+ Merge pull request #227 from tromey/fix-documentation-build
+
+ Fix documentation build
+
+commit 38a4d72c95936d27cba1ac6e84e3094ffdfaa77c
+Author: Tom Tromey <tom@tromey.com>
+Date: Tue Nov 17 21:18:20 2015 -0700
+
+ add ffi_get_struct_offsets
+
+commit e59fb55e09fb8aa846c820a802a03fed408d05a6
+Author: Tom Tromey <tom@tromey.com>
+Date: Mon Feb 22 15:51:27 2016 -0700
+
+ remove and ignore texinfo.tex
+
+ This file is provided by Automake
+
+commit 6dd5fd5a643c50aff3303ba2add3b6cc7588df78
+Author: Tom Tromey <tom@tromey.com>
+Date: Mon Feb 22 15:34:39 2016 -0700
+
+ fix documentation building
+
+ An earlier patch added --disable-docs, but went too far, making it
+ impossible to build the docs.
+
+ It turns out that Automake seemingly has a bug preventing the
+ conditional build of an info file. So, this patch works around the
+ bug by putting the info_TEXINFOS rule into a new doc/Makefile.am.
+
+ Tested by building with and without --disable-docs and looking for the
+ existence of doc/libffi.info.
+
+commit f2f234aef203a5e836b83cb772f9473f7ea0d5ce
+Merge: 49b95ed fa7a257
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:50:29 2016 -0500
+
+ Merge pull request #190 from havardgraff/master
+
+ Add configure-option to disable building docs
+
+commit 49b95edafd712ce27e08b1bb4be2987f14c54ca3
+Merge: 415723b 43fc5bc
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:49:40 2016 -0500
+
+ Merge pull request #194 from amodra/master
+
+ Correct powerpc sysv stack argument accounting
+
+commit 415723b40ba76f4a9df9b709db1cde0c65162072
+Merge: 7c27fcb 1f6b5a9
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:49:19 2016 -0500
+
+ Merge pull request #104 from joshtriplett/efi64
+
+ Support the Windows/EFI calling convention on all x86-64 targets
+
+commit 7c27fcbe09534d261b4098467a3ce258daec2807
+Merge: 69143d0 e061243
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:45:00 2016 -0500
+
+ Merge pull request #199 from Pan7/master
+
+ Fix configuring msvc compiler
+
+commit 69143d06c6276d09790a4e34f2eb6d37528c08c6
+Merge: 755f1e6 505346e
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:44:28 2016 -0500
+
+ Merge pull request #197 from foxsen/mips_go_closure
+
+ Mips go closure support
+
+commit 755f1e642d97892cb54358d65e06b60d1d6b72a4
+Merge: 183ee6a 4cdedc2
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:43:48 2016 -0500
+
+ Merge pull request #193 from rth7680/fix-70
+
+ Test case from issue #70
+
+commit 183ee6a6729db8f3ee0b1532d7bd54a6ef305443
+Merge: 0bb71b5 877ea9b
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:43:28 2016 -0500
+
+ Merge pull request #206 from edolnx/master
+
+ Add configure flag to disable multi-os-directory support
+
+commit 0bb71b52f5a60643ad55f801f1c652855b0e5cc5
+Merge: 296a283 8bec5ca
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:41:10 2016 -0500
+
+ Merge pull request #211 from tromey/move-prep-types-out-of-ffi.h
+
+ ffi_prep_types is internal-only
+
+commit 296a283a46057a6a643f1f64534324af34b7ed19
+Merge: e7c713a 4805bf9
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:40:21 2016 -0500
+
+ Merge pull request #213 from tromey/remove-FFI_TYPE
+
+ remove FFI_TYPE typedef
+
+commit e7c713a0b64c425b51f3d9437a8db7ca497e6c31
+Merge: 79666ab f45e9e3
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:40:03 2016 -0500
+
+ Merge pull request #214 from tromey/document-enum-support
+
+ document (lack of) enum handling in libffi
+
+commit 79666abca87ac67d2d05b477a3ba71ec18b8af0c
+Merge: 20c7c31 89b7605
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:38:40 2016 -0500
+
+ Merge pull request #205 from filbranden/tool_opts
+
+ Fix dejagnu test support for --tool_opts
+
+commit 20c7c31ca04350670012b28756d4ebc9e7b67a68
+Merge: 6ba2a49 9c14cbf
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 20 06:38:01 2016 -0500
+
+ Merge pull request #225 from ehsan/safeseh
+
+ Don't clobber safeseh for msvcc.sh -clang-cl in 32-bit mode
+
+commit 89b760503ed017233c98531908dfe8d8affab65e
+Author: Filipe Brandenburger <filbranden@google.com>
+Date: Mon Oct 19 15:33:23 2015 -0700
+
+ Fix dejagnu test support for --tool_opts
+
+ Right now it concatenates it with the existing options and then appends
+ it to that list, fix it to simply append it as is, same as it is done
+ with the other variables.
+
+ Tested by running the following command which includes gcc options:
+ $ make check RUNTESTFLAGS="--tool_opts '-Werror'"
+
+ Without this patch, all the tests fail. With it, the test succeed.
+ Inspecting the logs shows that -Werror was indeed used when compiling
+ the test sources.
+
+commit 9c14cbfc7ff49c2ceb9b65c548ddaced607f0785
+Author: Ehsan Akhgari <ehsan@mozilla.com>
+Date: Thu Jan 28 16:57:18 2016 -0500
+
+ Don't clobber safeseh for msvcc.sh -clang-cl in 32-bit mode
+
+ The commit fb25cd0 went a bit too far and removed safeseh
+ when -clang-cl was passed, but that's only needed in x86-64
+ which is already handled by the -m64 flag.
+
+ I discovered this when building Firefox x86 with clang-cl.
+
+commit 6ba2a49e226b859ddde9a37c34973cf85380c525
+Merge: 8005600 6a3a6ac
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Jan 2 20:03:41 2016 -0500
+
+ Merge pull request #222 from freakboy3742/t181
+
+ Fixed #181 -- Corrected problems with ARMv7 build under iOS.
+
+commit 8005600a920f43d89ace7ef3598057392da726e1
+Merge: 70594f7 5e2b18a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Jan 2 16:44:29 2016 -0500
+
+ Merge pull request #224 from plicease/travis
+
+ update apt-get in travis
+
+commit 5e2b18a65d3f366b2fb02ee27321095c4b5f17ac
+Author: Graham Ollis <plicease@cpan.org>
+Date: Sat Jan 2 07:56:05 2016 -0500
+
+ update apt-get in travis
+
+commit 6a3a6acd9fdbdac6f9f9294732b9627895b77715
+Merge: bc4fc07 70594f7
+Author: Russell Keith-Magee <russell@keith-magee.com>
+Date: Mon Dec 21 00:37:37 2015 +0800
+
+ Merge branch 'master' into t181
+
+commit bc4fc07aa58df6d7fa90b57d305d58eef96a0416
+Author: Russell Keith-Magee <russell@keith-magee.com>
+Date: Mon Dec 21 00:37:06 2015 +0800
+
+ Fixed #181 -- Corrected problems with ARMv7 build under iOS.
+
+ Based on a patch from @fealebenpae, with input from @SolaWing and @rth7680,
+ and testing from @superdump.
+
+commit 70594f7f8d7410be47ba9a80a566175d937ab626
+Merge: 88deacd 6affad7
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Dec 18 10:24:38 2015 -0500
+
+ Merge pull request #221 from tromey/document-closure-ffi_arg
+
+ Document closure ffi arg
+
+commit 6affad79111c45982fd29637a46bc756abb128a3
+Author: Tom Tromey <tom@tromey.com>
+Date: Thu Dec 17 16:58:10 2015 -0700
+
+ correctly document closure return promotion
+
+commit 8a7cdeb0412f9ef8bbe0a7833d662dbec40b472f
+Author: Tom Tromey <tom@tromey.com>
+Date: Thu Dec 17 16:51:32 2015 -0700
+
+ fix formatting of ffi_prep_closure_loc arguments
+
+commit f45e9e35700d7c547ba33b02c4186e746dea204a
+Author: Tom Tromey <tom@tromey.com>
+Date: Thu Nov 19 15:21:14 2015 -0700
+
+ document (lack of) enum handling in libffi
+
+commit 4805bf9ccdc176687526e9e7fca0db763cef42fb
+Author: Tom Tromey <tom@tromey.com>
+Date: Thu Nov 19 14:17:42 2015 -0700
+
+ remove FFI_TYPE typedef
+
+commit 8bec5ca26a9977e6c05d6bfa1bbbc7f6f99af4e7
+Author: Tom Tromey <tom@tromey.com>
+Date: Wed Nov 11 21:34:43 2015 -0700
+
+ ffi_prep_types is internal-only
+
+commit 88deacdd4220b66805b6ad10abd61fa3640afb67
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Nov 15 08:39:17 2015 -0500
+
+ speling fix
+
+commit 5973dca595f8595a40709f645e74b06990975db3
+Merge: 2a988c4 473bcbc
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Nov 15 08:36:48 2015 -0500
+
+ Merge pull request #209 from tromey/documentation-updates
+
+ documentation fixes
+
+commit 2a988c4455d3926c59997b68f7510be63e10c841
+Merge: e9de7e3 ff33ddd
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Nov 15 08:33:46 2015 -0500
+
+ Merge pull request #207 from tromey/deprecate-ffi-prep-closure
+
+ mark ffi_prep_closure as deprecated
+
+commit 473bcbcad32e9e320a7a5c111cefd0d8ad570245
+Author: Tom Tromey <tom@tromey.com>
+Date: Sat Nov 7 12:01:06 2015 -0700
+
+ documentation fixes
+
+ Fixes #78. Documentation for #33 and #35, but no fix.
+
+commit ff33ddd1abe72b6d02d2769c0379b06eb7dbb931
+Author: Tom Tromey <tom@tromey.com>
+Date: Sat Nov 7 11:45:04 2015 -0700
+
+ mark ffi_prep_closure as deprecated
+
+commit 877ea9bf9ac2c98cb858c12f5a6aeeec13cf978f
+Author: Carl Perry <caperry@edolnx.net>
+Date: Thu Oct 29 22:50:42 2015 -0500
+
+ Add configure flag to disable multi-os-directory support
+
+ In some environments, installing the library to GCC's
+ multi-os-directory is not perferable. This patch adds a switch
+ to configure "--disable-multi-os-directory" which will disable
+ that check, typically falling back to ${libdir} unless
+ cross-compiling.
+
+ Original patch was written by Stewart Brodie, and was found at
+ https://sourceware.org/ml/libffi-discuss/2013/msg00144.html
+
+ I've just updated it to work with the current version.
+
+commit 4cdedc279f96aefda24277184594c0ddd56d3402
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sat Jul 25 14:29:15 2015 -0700
+
+ Tidy call.exp test collection
+
+ Commit c952a92e20aa6013d8202d0b3fa1d87838c83054 moved all of
+ the complex tests to libffi.complex, but failed to remove the
+ anti-globbing from libffi.call.
+
+commit 609db2fbe41a56c1a8cd5653d248f08b88ea803f
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sat Jul 25 12:42:04 2015 -0700
+
+ Test case from Issue #70
+
+commit e9de7e35f2339598b16cbb375f9992643ed81209
+Merge: d19b6cc 0ebde2d
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Oct 11 10:54:50 2015 -0400
+
+ Merge pull request #202 from tromey/note-prep-cif-var-usage
+
+ document that there must be ntotalargs types
+
+commit d19b6cc78e956e7ffd48b39fd7c441c22e633ce2
+Merge: 17ffc36 36f3fb9
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Oct 11 10:54:22 2015 -0400
+
+ Merge pull request #201 from tromey/fix-texinfo-buglet
+
+ Add missing "@" to @var{}
+
+commit 0ebde2d24a3deb7b0cdf5cb1e625b55af2834fde
+Author: Tom Tromey <tom@tromey.com>
+Date: Tue Oct 6 11:42:43 2015 -0600
+
+ document that there must be ntotalargs types
+
+commit 36f3fb91412a6f10bd2c6dde01f4d7afa1f2f2c0
+Author: Tom Tromey <tom@tromey.com>
+Date: Mon Oct 5 10:20:05 2015 -0600
+
+ Add missing "@" to @var{}
+
+commit e061243958d63080956887e121d275533570f7cc
+Author: Pan7 <panter@gmx.net>
+Date: Mon Sep 14 08:25:09 2015 +0200
+
+ Fix configuring msvc compiler
+
+commit 505346e18fe20eee7eb69a23a48f6951858c5267
+Author: Zhang Fuxin <zhangfx@lemote.com>
+Date: Wed Aug 26 09:57:10 2015 +0800
+
+ fix type error in unwind code
+
+commit 5953c66bd7510b048b332b4e7450f3fb8d687f8b
+Author: foxsen <2503799872@qq.com>
+Date: Thu Aug 20 20:28:13 2015 +0800
+
+ add unwind infor for *go_closure;
+ reorder the labels to make thing more clear
+
+commit f0ecd5d40397d4616ba0bf3e2521da2663b5bd97
+Author: Zhang Fuxin <zhangfx@lemote.com>
+Date: Tue Aug 11 12:47:36 2015 +0800
+
+ fix O32 stack unwind code
+ add missing 1: label
+
+commit 6f0201c803a9a1f0f9b6fd226a42fb8daa223928
+Author: foxsen <2503799872@qq.com>
+Date: Tue Aug 4 18:25:34 2015 +0800
+
+ various fixes for go closure support. Now all n64 tests passed.
+
+commit 697dd4e8a03625a9b1448aa696978d8dcc57d438
+Author: foxsen <2503799872@qq.com>
+Date: Tue Aug 4 12:53:33 2015 +0800
+
+ add support for go closure support on mips
+
+commit 43fc5bca48715a522b34c1124589575063362a90
+Author: Alan Modra <amodra@gmail.com>
+Date: Mon Aug 3 23:34:05 2015 +0930
+
+ Correct powerpc sysv stack argument accounting
+
+ ppc32 starts using the stack for integer arg passing when we run out
+ of integer arg passing registers. Similarly, we start using the stack
+ for floating point args when we run out of floating point registers.
+ The decision on where an integer arg goes does not depend on number of
+ floating point args, nor does the decision on where a floating point
+ arg goes depend on number of integer args. Alignment of stack args
+ also simply depends on number of stack args.
+
+ This patch untangles the horrible mess we had, with intarg_count being
+ wrongly used to count both integer args and stack words.
+
+ * src/powerpc/ffi_sysv.c (ffi_prep_cif_sysv_core): Count fprs,
+ gprs, and stack words separately.
+ (ffi_prep_args_SYSV): Similarly.
+
+commit 1f6b5a91f417ac77d2fe9b0b3eb66293db132e2e
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Jul 26 16:27:34 2015 -0700
+
+ Support the WIN64/EFI64 calling convention on all X86_64 platforms
+
+ Add a new calling convention FFI_EFI64, alias FFI_WIN64, on all X86_64
+ platforms. This allows libffi compiled on a 64-bit x86 platform to call
+ EFI functions.
+
+ Compile in ffiw64.c and win64.S on all X86_64 platforms. When compiled
+ for a platform other than X86_WIN64, ffiw64.c suffixes its functions
+ with _efi64, to avoid conflict with the platform's actual
+ implementations of those functions.
+
+commit 6de51f3e04e496901ea1bd8f9b44f75c9f01b599
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Jul 26 16:23:55 2015 -0700
+
+ src/x86/ffiw64.c: Don't assign a "char *" to an "unsigned char *"
+
+ Declare a local variable to match the type of the struct field assigned
+ to it, rather than adding unsigned to the type. Fixes a -Wpointer-sign
+ warning.
+
+commit eaa59755fcbb692a8cb763c7f9f24a350aadbd30
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Jul 26 17:17:16 2015 -0700
+
+ src/x86/win64.S: Handle name mangling and PIC
+
+ Move the macros from unix64.S into a shared header asmnames.h and use
+ them in win64.S too.
+
+commit c8e82d9fbffd3eeaef0266a1aac64d7bd13ee9c3
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Jul 26 16:18:57 2015 -0700
+
+ src/x86/win64.S: Support compiling on non-WIN64 platforms
+
+ Non-WIN64 versions of the GNU assembler don't support the .seh_*
+ directives for structured exception handling, so wrap them in a macro
+ that compiles to nothing.
+
+ Handle the registers used for the non-Windows x86-64 calling convention
+ when on a non-Windows platform. Distinguish between cases that should
+ refer to the native argument registers (defined as arg0, arg1, arg2, and
+ arg3) and cases that should always refer to the Windows argument
+ registers.
+
+commit fa7a257113e2cfc963a0be9dca5d7b4c73999dcc
+Author: Havard Graff <havard.graff@gmail.com>
+Date: Tue May 12 10:45:13 2015 +0200
+
+ Add configure-option to disable building docs
+
+commit e3d2812ce43940aacae5bab2d0e965278cb1e7ea
+Author: Russell Keith-Magee <russell@keith-magee.com>
+Date: Sat Apr 25 19:03:03 2015 +0800
+
+ Modified arm/sysv.S to remove directives not allowed by clang.
+
+commit 17ffc3655a531c116e9eb9cc933e50bb1e5c47f8
+Merge: 173757c a5b3eaa
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 29 21:38:26 2015 -0400
+
+ Merge pull request #185 from freakboy3742/t184
+
+ Fixed #184 -- Corrected source file references in Darwin source generator tool.
+
+commit 173757ce973a2f12ad36ac6cda593581b225f9e3
+Merge: f5ec627 dd9e4c8
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 29 21:38:12 2015 -0400
+
+ Merge pull request #186 from freakboy3742/gitignore
+
+ Added generated source file to .gitignore.
+
+commit dd9e4c8d46b65104a24a9858accd0936ca44b98f
+Author: Russell Keith-Magee <russell@keith-magee.com>
+Date: Fri Mar 13 08:03:13 2015 +0800
+
+ Added generated source file to .gitignore.
+
+commit a5b3eaa279a2e54721d44eeefdfd1962cf63caaf
+Author: Russell Keith-Magee <russell@keith-magee.com>
+Date: Fri Mar 13 07:59:11 2015 +0800
+
+ Fixed #184 -- Corrected file references in Darwin source generator tool.
+
+commit f5ec6279a4698a8752093247a500cf76096ff157
+Merge: 06747d3 95df379
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 4 13:58:04 2015 -0500
+
+ Merge pull request #178 from rth7680/aa64-ilp32
+
+ aarch64: Handle ILP32 ABI
+
+commit 95df3791935d934d92b0c852af1e655285157b70
+Author: Andrew Pinski <apinski@cavium.com>
+Date: Wed Feb 11 08:31:48 2015 -0800
+
+ aarch64: Handle ILP32 ABI
+
+commit 06747d318761884e70dfa433a9548219fd779d7d
+Merge: db1b34b 6c53577
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Jan 29 07:22:23 2015 -0500
+
+ Merge pull request #176 from 0-wiz-0/master
+
+ Handle NetBSD/powerpc the same as FreeBSD and OpenBSD.
+
+commit 6c5357757f188577fffcd2890ef7a0f53e77de20
+Author: Thomas Klausner <wiz@NetBSD.org>
+Date: Thu Jan 29 12:32:28 2015 +0100
+
+ Handle NetBSD/powerpc the same as FreeBSD and OpenBSD.
+
+ Signed-off-by: Thomas Klausner <wiz@NetBSD.org>
+
+commit db1b34b7e1f5e473d17557e454a29933dfecd1af
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 28 18:08:06 2015 -0500
+
+ Remove incomplete sentence
+
+commit 56036a6b58acb9e854719e315a0738f16e354c35
+Merge: 035715b 2104b2a
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 28 18:03:57 2015 -0500
+
+ Merge pull request #175 from rth7680/sparc
+
+ sparc: Re-introduce hand-written unwind info
+
+commit 035715b3330421806df36ec4ac7ccecc86458540
+Merge: 31a6185 b0e9796
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 28 18:03:06 2015 -0500
+
+ Merge pull request #174 from rth7680/fbsd
+
+ configure: Run HAVE_AS_X86_PCREL for all X86 targets
+
+commit 2104b2a4fc923b8d82647c3fbbd8a8ca20bb24c8
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon Jan 26 12:43:57 2015 -0800
+
+ sparc: Re-introduce hand-written unwind info
+
+ Fixes the build with the Solaris assembler.
+
+commit b0e9796344562ea8e1ef28e9b04db6be26ca29fb
+Author: Richard Henderson <rth@twiddle.net>
+Date: Tue Jan 27 22:10:12 2015 -0800
+
+ configure: Run HAVE_AS_X86_PCREL for all X86 targets
+
+commit 31a618530737cc8f1666845f8e65a3c097f6d408
+Merge: d6675c1 5363663
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 21 05:55:47 2015 -0500
+
+ Merge pull request #170 from fealebenpae/aarch64-trampoline-table
+
+ Support closures on ARM64 iOS
+
+commit d6675c16cc2b5a0e32c4538e5a4f555c91e6bb56
+Merge: a25a46a 3ac1610
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 21 05:53:21 2015 -0500
+
+ Merge pull request #172 from rth7680/fixes
+
+ x86: Fix cygwin32 build
+
+commit 3ac1610aa33c887ea9b14935208943925714a33e
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon Jan 19 20:48:40 2015 +0100
+
+ x86: Fix cygwin32 build
+
+ The section syntax is just that little bit different.
+
+commit a25a46a7fe4f7ae27fbd6e08a2540678899914e9
+Merge: 5cd411a 1ad0b17
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Jan 16 17:32:07 2015 -0500
+
+ Merge pull request #171 from rth7680/fixes
+
+ Fixes from mainline gcc
+
+commit 1ad0b17177526be86736e245fbcc21eadaf7cb36
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Jan 16 13:30:05 2015 -0800
+
+ sparc: Also mark the return address in unwind info
+
+commit d68c8aed19d459a9fef0847f316dd9473ef263ad
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Jan 16 11:40:33 2015 -0800
+
+ sparc: Solaris fixes, part 2
+
+ /bin/as seems to only understand single-digit labels
+ /bin/as knows nothing about .rept/.endr
+
+commit b740ab7cc955fc2888325e6387207f34400a6c45
+Author: Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+Date: Fri Jan 16 11:32:23 2015 -0800
+
+ sparc: Solaris fixes
+
+ * /bin/as requires .type fn,#function instead of @function.
+ * /bin/as doesn't support .macro/.endm. I'm using preprocessor macros
+ instead to implement E in src/sparc/v[89].S.
+
+commit f1560b7bbeb57042a32dfde487c3d21bd9ef6a51
+Author: Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+Date: Fri Jan 16 11:31:37 2015 -0800
+
+ x86: Solaris fixes
+
+ * Solaris/x86 /bin/as doesn't support .org, so I've just disabled the
+ uses in src/x86/{sysv, unix64}.S, as on Darwin.
+ * Solaris/x86 needs to use EH_FRAME_FLAGS so manually and compiler
+ generated .eh_frame sections match, otherwise libffi.so fails to link:
+ * Solaris/x86 /bin/as has different COMDAT syntax; I've disabled it for
+ the moment.
+
+commit 536366349ced9d57c873d64e219ba30992a83c06
+Author: Yavor Georgiev <fealebenpae@gmail.com>
+Date: Fri Jan 16 15:19:38 2015 +0200
+
+ aarch64: implement the trampoline table workaround for ffi closures on Apple systems
+
+ This is a direct copy/paste port of the ARM code, with changes because of Aarch64 pc-relative addressing restrictions.
+
+commit 05e65b4e2064f24669e8cc1c1cece1cbb0577548
+Author: Yavor Georgiev <fealebenpae@gmail.com>
+Date: Fri Jan 16 15:18:04 2015 +0200
+
+ aarch64: rewrite range syntax into list to appease Clang
+
+ Clang's assembler in Xcode 6 appears to choke when the operand of st4 is a range, but is happy with a list.
+
+commit 5cd411ad5d62b1dadfd02f75f99121801c8be4c9
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jan 13 15:44:03 2015 -0500
+
+ New test case for old aarch64 bug
+
+commit e46842b4149e19106a9eb6066ef022d8b6a7ad5d
+Author: Richard Henderson <rth@twiddle.net>
+Date: Tue Jan 13 07:23:48 2015 -0800
+
+ Remove extra brackets in configure.host
+
+ This table is no longer in configure.ac, needing
+ protection from m4.
+
+commit f27c4e46734fa1342236b16161e6006a9d2557e9
+Author: Richard Henderson <rth@twiddle.net>
+Date: Tue Jan 13 07:22:07 2015 -0800
+
+ x86: Fix thinko in ffi_raw_call
+
+ Missed structure initialization for raw path.
+ Apparently there are no tests for this outside gcc.
+
+commit c82cc159426d8d4402375fa1ae3f045b9cf82e16
+Merge: 1c61e73 e1a5ddb
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Jan 10 09:25:26 2015 -0500
+
+ Merge pull request #166 from chevah/master
+
+ Fix expr error in Solaris 10 when using gcc.
+
+commit 1c61e73ad8e920d6bff337fac02de71f3a66bc38
+Merge: dd0b59a 3fa5d70
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Jan 10 09:23:30 2015 -0500
+
+ Merge pull request #165 from rth7680/pcc
+
+ Support PCC as producer and consumer
+
+commit dd0b59a5cf63e0f9602c76fc89a4cb62593ff6f1
+Merge: 9131039 b7f6d7a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Jan 10 09:22:55 2015 -0500
+
+ Merge pull request #164 from rth7680/darwin
+
+ Fix build on darwin
+
+commit 9131039c93b6ecd1c3946905a3b6dafb5dc4ee40
+Merge: 4ca2262 7282d32
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Jan 10 09:22:42 2015 -0500
+
+ Merge pull request #160 from nobu/msvc-no-complex
+
+ x86: MSVC does not support Complex type
+
+commit 4ca2262ad61189276b2d95aab652a23c8db2a5b9
+Merge: 58bf7d6 5f8881a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Jan 10 09:21:37 2015 -0500
+
+ Merge pull request #159 from nobu/fix-void-arith
+
+ x86: Fix void pointer arithmetic
+
+commit e1a5ddb3067f83563cb8a6b8ac4d0f58d4699262
+Author: Mișu Moldovan <dumol@chevah.com>
+Date: Wed Jan 7 17:51:07 2015 +0200
+
+ Fix expr error in Solaris 10 when using gcc.
+
+commit 3fa5d70cbb18b39a5e44f1c7984dedf73446bf6c
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon Jan 5 13:03:06 2015 -0800
+
+ x86: Avoid fastcall when building with pcc
+
+ Apparently, PCC doesn't support the fastcall calling convention.
+ Nor does it issue a warning or error for the attribute that it
+ does not understand.
+
+commit a03d2310ed53bb8b3a4610af04015ef9df6ea36c
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Dec 24 16:03:34 2014 -0800
+
+ x86: Load structure return address into eax
+
+commit b7f6d7aa9b0d7b19eec28a945251e09a4b65b275
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Dec 10 13:37:36 2014 -0800
+
+ x86: Reinstate hand-written unwind info for sysv.S
+
+commit 6cedf81ca7cbad01b3fcc2c4475d860095bfb062
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Dec 10 09:43:58 2014 -0800
+
+ x86: Expand FFI_GO_CLOSURE
+
+ If we're going to have to hand-write unwind info for darwin,
+ these macros make the job harder.
+
+commit ae842a515b6e2a486d73ce8f9dbe5fee6c3fd1ff
+Author: Iain Sandoe <iain@codesourcery.com>
+Date: Tue Nov 25 11:43:40 2014 +0100
+
+ x86: More Darwin unwind fixups
+
+ EHFrame{N} IIRC is a special cue to ld64 that it should treat the unwind
+ in the object as "special/legacy" .. [these days everything is .cfi_xxxx
+ (except, cctools-as, as you noted)] .. without that much confusion arises
+ with ld64's atom-isation of the eh_frame section.
+
+ xxxx.eh labels are not needed for darwin ld64 >= 85.2.1 (i.e. darwin9,
+ xcode 3.1.4) to all intents and purposes, that's all that matters now,
+ since I think that anyone trying to build on 10.4/darwin8/xcode2.5 would
+ have to use a later ld64 (from odcctools) for other reasons.
+
+commit 8fa3c9f24b5ef6da2f24a9f071984d033dd9e00c
+Author: Richard Henderson <rth@twiddle.net>
+Date: Tue Nov 25 09:27:54 2014 +0100
+
+ x86: Reinstate hand-written unwind info for unix64.S
+
+ One more try to get default Darwin to work.
+
+commit 5f35e0ffcc05a72ce0aacf228dc06d1262754660
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon Nov 24 16:26:50 2014 +0100
+
+ x86: Avoid using gas local labels
+
+ Which are unsupported by Darwin cctools as.
+ Thankfully this doesn't uglify the source too much.
+
+commit ed1ca2777c35fe2f2751de255df3e16f17bdbd8d
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon Nov 24 13:02:03 2014 +0100
+
+ x86: Remove use of .cfi_escape
+
+ The unwind info isn't 100% correct at all points during the epilogue,
+ and not annotating is just as incorrect as the annotation. This works
+ better on systems that do not support DW_OP_call_frame_cfa.
+
+commit 1b12593d7e595c03e5c06377feaeb8ad1b813681
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon Nov 24 12:55:43 2014 +0100
+
+ x86: Honor alignment of arguments
+
+ Darwin aligns long-double to 16, and thus all of the long double
+ tests were failing due to not honoring that. We ought to be able
+ to devise a test case for GCC using __attribute__((aligned)) that
+ would have failed too.
+
+commit 042b8dafeeee82667e00660fb1edeab72fd9de47
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon Nov 24 11:24:02 2014 +0100
+
+ x86: Use .balign not .align
+
+ The Apple assembler defaults to power of two alignment, rather than
+ byte alignment like everyone else. Force byte alignment by using
+ the proper directive.
+
+commit 0172bc029cd943dce99f82b9d857c51e746574e5
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon Nov 24 10:42:02 2014 +0100
+
+ x86: Disable .org for Darwin
+
+commit 9f112619c187e135132b765adeedef89ee354eb2
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sat Nov 22 20:02:43 2014 +0100
+
+ x86: Best guess at update for Darwin
+
+commit 7282d3289c6f6e2cc21e2c2b554c33af00ac3474
+Author: Nobuyoshi Nakada <nobu@ruby-lang.org>
+Date: Mon Dec 22 17:14:40 2014 +0900
+
+ x86: MSVC does not support Complex type
+
+commit 5f8881a5913a9554cbc2b5fed7057627b9bb9ece
+Author: Nobuyoshi Nakada <nobu@ruby-lang.org>
+Date: Mon Dec 22 17:08:08 2014 +0900
+
+ x86: Fix void pointer arithmetic
+
+commit 58bf7d65d8896f198624c591cc31e6e01a09cc31
+Merge: 75b2199 7ba30b1
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Dec 20 10:20:40 2014 -0500
+
+ Merge pull request #158 from rth7680/s390
+
+ S390
+
+commit 7ba30b19060dfefefeb91970a862e5b215606602
+Author: Richard Henderson <rth@redhat.com>
+Date: Fri Dec 19 11:38:17 2014 -0500
+
+ s390: Inline and tidy ffi_prep_args
+
+ As per discussion with Ulrich Weigand, document the restrictions
+ on the code within ffi_call_int as we simultaneously prepare
+ stack frames for ffi_call_SYSV and the target function.
+
+commit f69ec6f35db93163b7f33e43129d274995c8122d
+Author: Richard Henderson <rth@redhat.com>
+Date: Thu Dec 18 16:21:07 2014 -0500
+
+ s390: Use pc-relative insns in 31-bit mode
+
+ It's silly to stick to esa/390 features when the compiler won't.
+ Detect when brasl and larl are used by the compiler and then use
+ them in the assembly.
+
+commit 2f530de168e0253ac06e044c832132c496e8788b
+Author: Richard Henderson <rth@redhat.com>
+Date: Thu Dec 18 16:01:59 2014 -0500
+
+ s390: Reorganize assembly
+
+ Avoid using ffi_prep_args as a callback; do all the work setting
+ up the frame within ffi_call_int directly. Save fewer registers
+ in ffi_closure_SYSV.
+
+commit 97512ded052678993ffcfa3aec0035cce1585138
+Author: Richard Henderson <rth@redhat.com>
+Date: Thu Dec 18 16:01:15 2014 -0500
+
+ s390: Avoid aliasing warnings
+
+commit c860ca9ac0fc7ee44124c5637dda751f55e4fa3f
+Author: Richard Henderson <rth@redhat.com>
+Date: Wed Dec 17 13:24:03 2014 -0500
+
+ s390: Kill trailing whitespace
+
+commit 02b7c89967307cea91714fb6e4e53048e1b5396e
+Author: Dominik Vogt <vogt@linux.vnet.ibm.com>
+Date: Wed Dec 17 13:20:51 2014 -0500
+
+ s390: Go closure support
+
+commit 75b2199f264f42de814528ccf4bfd2ef427665b5
+Merge: 8a3a272 2f65246
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Dec 12 10:13:56 2014 -0500
+
+ Merge pull request #157 from rth7680/x86
+
+ Two fixes for x86
+
+commit 8a3a2723aaa615cb95ee1c798469d7a3b2d95d31
+Merge: 9ae3bc8 542e004
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Dec 12 10:13:27 2014 -0500
+
+ Merge pull request #156 from rth7680/sparc
+
+ sparc: Define FFI_TARGET_SPECIFIC_VARIADIC for v9
+
+commit 2f652469684d6d2b3e54705294c7e81cffe1341f
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Dec 11 14:16:00 2014 -0800
+
+ x86: Handle void arguments as if an empty structure
+
+ Since libffi currently doesn't allow empty structures, libgo
+ currently maps them to ffi_type_void. Given that we'll abort
+ on this case, handle it gracefully.
+
+commit 097ccfd6a6b94a3c3b5bfc269a7afd1dc4f7a051
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Dec 10 13:25:14 2014 -0800
+
+ x86: Fix some unwind errors
+
+commit 9ae3bc870ee07820b60d368f137ea3b5daca850e
+Author: James Greenhalgh <james.greenhalgh@arm.com>
+Date: Sat Dec 6 23:58:41 2014 -0500
+
+ Fix for https://github.com/atgreen/libffi/issues/141
+
+commit a5a40960bb6ccb029d2d9d4e18d37f6e0dacb913
+Merge: 9ca4370 590663b
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 19 21:13:50 2014 -0500
+
+ Merge pull request #151 from amodra/master
+
+ powerpc: go closures for linux
+
+commit 590663b30b1f35b6136cf55d8870a2394ed78c21
+Author: Richard Henderson <rth@twiddle.net>
+Date: Tue Nov 18 12:56:58 2014 +1030
+
+ powerpc: Fix ffi_go_closure_linux64
+
+ Unlike ffi_closure_LINUX64, this entry point is called normally,
+ so we already have the TOC in R2 and the closure in R11.
+
+ * powerpc/linux64_closure.S (ffi_closure_LINUX64): Remove a
+ register dependency chain.
+ (ffi_go_closure_linux64): Don't load r11 or r2.
+
+commit fa1040c111b3e423bc9c7e78d9af89470c0fa2fb
+Author: Alan Modra <amodra@gmail.com>
+Date: Mon Nov 10 09:42:31 2014 +1030
+
+ GO closures for powerpc linux
+
+ Plus .cfi async unwind info, rearrangement of ffi_call_linux64 and
+ ffi_call_SYSV function params to avoid register copies, tweaks to
+ trampolines.
+
+ * src/powerpc/ffitarget.h (FFI_GO_CLOSURES): Define.
+ * src/powerpc/ffi.c (ffi_call_int): New function with extra
+ closure param, and args rearranged on ffi_call_linux64 and
+ ffi_call_SYSV calls, extracted from ..
+ (ffi_call): ..here.
+ (ffi_call_go, ffi_prep_go_closure): New functions.
+ * src/powerpc/ffi_linux64.c (ffi_prep_closure_loc_linux64): Make
+ hidden. Only flush insn part of ELFv2 trampoline. Don't shuffle
+ ELFv1 trampoline.
+ (ffi_closure_helper_LINUX64): Replace closure param with cif, fun,
+ user_data params.
+ * src/powerpc/ffi_powerpc.h (ffi_go_closure_sysv): Declare.
+ (ffi_go_closure_linux64): Declare.
+ (ffi_call_SYSV, fi_call_LINUX64): Update.
+ (ffi_prep_closure_loc_sysv, ffi_prep_closure_loc_linux64): Declare.
+ (ffi_closure_helper_SYSV, ffi_closure_helper_LINUX64): Update.
+ * src/powerpc/ffi_sysv.c (ASM_NEEDS_REGISTERS): Increase to 6.
+ (ffi_prep_closure_loc_sysv): Use bcl in trampoline, put data words
+ last, flush just the insn part.
+ (ffi_closure_helper_SYSV): Replace closure param with cif, fun and
+ user_data params.
+ * src/powerpc/linux64.S (ffi_call_LINUX64): Replace hand-written
+ .eh_frame with .cfi directives. Adjust for changed param order.
+ Pass extra "closure" param to user function in static chain. Add
+ .cfi directives to describe epilogue. Don't provide traceback
+ table for ELFv2 or _CALL_LINUX.
+ * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Replace
+ hand-written .eh_frame with .cfi directives. Adjust for changed
+ ffi_closure_helper_LINUX64 params. Add .cfi directives to
+ describe epilogue. Don't provide traceback table for ELFv2 or
+ _CALL_LINUX.
+ (ffi_go_closure_linux64): New function.
+ * src/powerpc/sysv.S: Remove redundant .globl ffi_prep_args_SYSV.
+ (ffi_call_SYSV): Make hidden. Replace hand-written .eh_frame with
+ .cfi directives. Adjust for changed params. Pass extra "closure"
+ param to user function in static chain. Add .cfi directives to
+ describe epilogue.
+ * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Make hidden.
+ Replace hand-written .eh_frame with .cfi directives. Adjust for
+ changed ffi_closure_helper_SYSV params. Add .cfi directives to
+ describe epilogue. Don't just use nops in the dead __NO_FPRS__
+ epilogues.
+ (ffi_go_closure_sysv): New function.
+
+commit d3d06f4c94847402a08f0e4e2af2e4d726ed3180
+Author: Alan Modra <amodra@gmail.com>
+Date: Mon Nov 10 13:50:05 2014 +1030
+
+ Fix powerpc breakage from 6e8a4460
+
+ * src/powerpc/ffitarget.h: #error on unexpected FFI_TYPE_LAST.
+ (FFI_PPC_TYPE_LAST): Define.
+ (FFI_TYPE_UINT128): Define in terms of FFI_PPC_TYPE_LAST.
+ (FFI_SYSV_TYPE_SMALL_STRUCT, FFI_V2_TYPE_FLOAT_HOMOG): Likewise.
+ (FFI_V2_TYPE_DOUBLE_HOMOG, FFI_V2_TYPE_SMALL_STRUCT): Likewise.
+
+commit 9ca43706f9e59ee3a0b288884c90fd51d8926a9b
+Merge: 5211c72 a9ed0c3
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 19 11:32:08 2014 -0500
+
+ Merge pull request #148 from gpakosz/dlmalloc-preprocessor-fix
+
+ dlmalloc: change defined(i386) to defined(__i386__)
+
+commit 542e004710e3f1d7c137bba305a16538cd6257d6
+Author: Richard Henderson <rth@twiddle.net>
+Date: Tue Nov 18 05:07:00 2014 -0800
+
+ sparc: Define FFI_TARGET_SPECIFIC_VARIADIC for v9
+
+ This is a port of
+
+ http://gcc.gnu.org/viewcvs?rev=207763&root=gcc&view=rev
+
+ aka GCC PR libffi/60073, to the rewritten Sparc codebase.
+ Supposedly, we should have seen failures with the existing
+ libffi.call/cls_double_va.c testcase, but I hadn't.
+ Perhaps a gcc newer than 4.6.3 is required to see that...
+
+commit a9ed0c3a0428f5fd4ed2166fa95a608595e11a4d
+Author: Gregory Pakosz <gpakosz@myscript.com>
+Date: Tue Nov 18 09:37:07 2014 +0100
+
+ dlmalloc: change defined(i386) to defined(__i386__)
+
+ When compiling with --std==c99, GCC and clang don't define i386 but __i386__
+
+commit 5211c7207ec81dfdfa9acdcd86b49b9ff66b9d91
+Merge: 3316b66 ccdd7bb
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 17 09:07:07 2014 -0500
+
+ Merge pull request #147 from rth7680/go/alpha
+
+ testsuite: Fix alpha static chain register name
+
+commit ccdd7bb8566b2fd1da5c4b5c8eaa2db43a69e720
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sun Nov 16 12:12:23 2014 +0100
+
+ testsuite: Fix alpha static chain register name
+
+commit 3316b666e3074fe0eebff4fe0458979961b26651
+Merge: b698638 dea49e2
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 15 07:31:41 2014 -0500
+
+ Merge pull request #145 from rth7680/master
+
+ Configure and testsuite cleanups, v2
+
+commit b698638d7601de994410c5c1b2f5c2c648015b7b
+Merge: a353d5b 771fabc
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 15 07:29:58 2014 -0500
+
+ Merge pull request #144 from atrosinenko/testsuite-fp-comparison-fix
+
+ Floating point number comparison fix for testsuite
+
+commit a353d5b16cfbb60f1a42bdec74b0f272701f3ecb
+Merge: 4aa702a e029c70
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 15 07:27:21 2014 -0500
+
+ Merge pull request #143 from adamkaplan/patch-1
+
+ Update i386 & armv7 minimum iOS version to 7.0
+
+commit dea49e2020b2fc97ba9293200f316f7a7b3ca73b
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Nov 14 13:05:14 2014 +0100
+
+ x86: Fix typo in ffi_prep_go_closure
+
+ Used the wrong register for THISCALL and FASTCALL.
+
+commit c9f5b6648b0f052bbca8b50615284dd975e9ed29
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Nov 14 13:04:33 2014 +0100
+
+ testsuite: Add trivial tests for Go closures
+
+commit c952a92e20aa6013d8202d0b3fa1d87838c83054
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Nov 14 11:00:14 2014 +0100
+
+ testsuite: Move complex tests to their own subdirectory
+
+ It seems a bit silly to isolate them by globbing vs "*complex*"
+ when we can just as easily put them in their own subdirectory.
+
+commit f1301a54bb80e6ae23f7687c68f36875dae69134
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Nov 14 10:50:29 2014 +0100
+
+ testsuite: Use feature test rather than enumeration for complex
+
+commit b5ade2fb5d9ba06519484677a5474e5dad48c2e3
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Nov 13 09:06:10 2014 -0800
+
+ testsuite: Detect clang
+
+ Clang doesn't like the -Wno-psabi argument that we want to pass to GCC.
+ Since clang is detected as GCC via __GNUC__, use ax_cv_c_compiler_vendor.
+
+commit 5d69d57a053c5049df29242def492159e1fadbae
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Nov 13 13:50:39 2014 +0100
+
+ configure: Move target source selection into configure.host
+
+ This eliminates the AM_CONDITIONAL ugliness, which eliminates
+ just a bit of extra boilerplate for a new target.
+
+ At the same time, properly categorize the EXTRA_DIST files
+ into SOURCES and HEADERS, for the generation of ctags.
+
+commit 771fabc6d5379e64e5ab9e5f1ca6eb5960617432
+Author: Anatoly Trosinenko <anatoly.trosinenko@gmail.com>
+Date: Fri Nov 14 14:21:35 2014 +0300
+
+ Take a float absolute value using fabs() instead of abs().
+
+ Replace integer abs() by floating point fabs() in the approximate
+ equality check for float values.
+
+commit 9622ede2e24067a09380c63da8d5007ec1f03dc4
+Author: Anatoly Trosinenko <anatoly.trosinenko@gmail.com>
+Date: Fri Nov 14 13:18:04 2014 +0300
+
+ Fix floating point number comparisons in testsuite/libffi.call/float[123].c.
+
+ Rewrite the checks for approximate equality of floating point return
+ values to be in the form "fabs(a - b) < EPS" instead of just
+ "a - b < EPS".
+
+commit e029c70fa7da7a489157b2a2a88349aaffb051de
+Author: Adam <adkapx@gmail.com>
+Date: Thu Nov 13 15:08:16 2014 -0500
+
+ Update i386 & armv7 minimum iOS version to 7.0
+
+ iOS 5 (and any below 7.1) is deprecated. Apple doesn't distribute the supporting libraries for this platform anymore as of Xcode 6, so it causes a linker error.
+
+commit 57f52484573613e2def21171184f50bd72209cac
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Nov 13 12:42:54 2014 +0100
+
+ configure: Split out configure.host
+
+ Split out the host case statement to a separate file, so that
+ we don't have to regenerate configure.in for changes therein.
+
+commit f8632815a6515a6709802ad23909585664ba1b9d
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Nov 13 12:32:35 2014 +0100
+
+ powerpc: Delete patch output
+
+ Clearly added by mistake.
+
+commit 4aa702a0e0ffc9b8a672af380103f607d339a822
+Merge: 20562ac 8d5debc
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 12 08:08:57 2014 -0500
+
+ Merge branch 'rth7680-go-closure'
+
+commit 8d5debc7904aa5c4f1fbf5d5b26450ec5a5b43c6
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 12 08:04:51 2014 -0500
+
+ Update in preparation for next release
+
+commit 56735e05fed77a3920a8cac262666c9eb0e75b66
+Merge: 20562ac 0e303c0
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Nov 12 07:11:53 2014 -0500
+
+ Merge branch 'go-closure' of https://github.com/rth7680/libffi into rth7680-go-closure
+
+ Conflicts:
+ src/aarch64/ffi.c
+
+commit 20562ac0427c3578250d04c6e34fb0127d4551cf
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 12 07:00:59 2014 -0500
+
+ Fix for AArch64. Release as 3.2.1.
+
+commit 0e303c065779afb42cfdb2ea20c0e1a557dc16f0
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Nov 12 03:58:58 2014 -0800
+
+ x86: Work around clang bugs
+
+ http://llvm.org/bugs/show_bug.cgi?21500
+ http://llvm.org/bugs/show_bug.cgi?21501
+ http://llvm.org/bugs/show_bug.cgi?21515
+
+commit 6eec410f1512d0584276db5f4b83711330e830d7
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sun Oct 26 15:29:04 2014 -0700
+
+ sparc: Re-add abi compliant structure support
+
+ The original code, removed in the "rewrite" patch, was incorrect for
+ large structures, and required dynamic allocation of a trampoline on
+ every ffi_call.
+
+ Instead, allocate a 4k entry table of all possible structure returns.
+ The table is 80k, but is read-only and dynamically paged, which ought
+ to be better than allocating the trampoline.
+
+ This is difficult to test with gcc. One can only use -O0 at present.
+ See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63668.
+
+commit 92022496ef7a9439f48a2ef11e460c300ac863d7
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sun Oct 26 14:48:28 2014 -0700
+
+ sparc: Add support for Go closures
+
+commit ad89c2d9e93d5a713ae4113567b4ca6c4fbbf17c
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sun Oct 26 13:16:03 2014 -0700
+
+ sparc: Add support for complex types
+
+commit 20da5b41324de524ea3ee1f84f402828b7c332dc
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sat Oct 25 16:24:41 2014 -0700
+
+ sparc: Handle more cases of structure return directly
+
+commit 0686c2e71c8e094cf003f199e3f578bcdede43ba
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sat Oct 25 14:52:45 2014 -0700
+
+ sparc: Preprocess float point struct return
+
+ We can eliminate recursion and speed structure return
+ by flattening a nested structure tree into a bitmask.
+
+commit 2b27890ba77db6a23d37fc70897109e4b2803c2d
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 24 16:10:48 2014 -0700
+
+ sparc: Rewrite everything
+
+ It's impossible to call between v8 and v9 ABIs, because of the stack bias
+ in the v9 ABI. So let's not pretend it's just not implemented yet. Split
+ the v9 code out to a separate file.
+
+ The register windows prevent ffi_call from setting up the entire stack
+ frame the assembly, but we needn't make an indirect call back to prep_args.
+
+commit 5d7b54450582f31d0d5d3ecca7f330b70446f195
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 24 11:45:53 2014 -0700
+
+ sparc: Tidy up symbols
+
+ Assembly to use local labels, .type annotation, hidden annotation.
+ I do retain the _prefix for the symbols, but given that it wasn't
+ done consistently across all symbols, I doubt it's actually needed.
+
+commit fd4f7cc0cabae66a91e40f8645791740b9416bc1
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 24 11:11:53 2014 -0700
+
+ sparc: Eliminate long double ifdefs
+
+commit ab83cbb90b280195e636976098d3674f5ffc1d0a
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Oct 29 14:38:42 2014 -0400
+
+ arm: Add support for Go closures
+
+commit 6fa617dabc3d99e19d47ac9bc4127c56e3163008
+Author: Richard Henderson <rth@twiddle.net>
+Date: Tue Oct 21 11:27:11 2014 -0400
+
+ arm: Add argument space for the hidden struct return pointer
+
+ This should have been failing all along, but it's only
+ exposed by the complex_int test case.
+
+commit a529bec27b64ab846ab2643ecbeb22e01f35c7dc
+Author: Richard Henderson <rth@twiddle.net>
+Date: Tue Oct 21 11:26:59 2014 -0400
+
+ arm: Add support for complex types
+
+commit 5e88ebe62717b8e1e2f8d96c10f78a7134caa765
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon Oct 20 15:10:43 2014 -0400
+
+ arm: Remove internal FFI_TYPE constants
+
+ These have been replaced by the contents of internal.h.
+
+commit a4b785ea695e929b91d64e1e8b514411ae8bafe8
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 02:07:32 2014 -0400
+
+ arm: Rewrite ffi_closure
+
+ Move the push of the argument registers into ffi_closure_SYSV,
+ reducing the size of the trampoline.
+
+commit e7f15f60e86ad8931b2c4a516945d0b76b4bda20
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 01:27:16 2014 -0400
+
+ arm: Rewrite ffi_call
+
+ Use the trick to allocate the stack frame for ffi_call_SYSV
+ within ffi_call itself.
+
+commit a74a3aaddbcc730d9aa0a4787f136c9cc19b82b3
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 01:21:22 2014 -0400
+
+ arm: Rewrite vfp_type_p
+
+ Do not modify the ffi_type. Rearrange the tests so that we
+ quickly eliminate structures that cannot match. Return an
+ encoded value of element count and base type.
+
+commit 0d39b4bb692b1a8e4f3354badcd9e123f8276bd4
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 01:02:52 2014 -0400
+
+ arm: Deref ffi_put_arg arguments
+
+commit 57b24fb3f5471262ce57e1a912774d6e7de5ada7
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 00:53:21 2014 -0400
+
+ arm: Deref ffi_align argument
+
+commit c129bea82a25c9b0f3af3bf48c35c55257092f87
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Oct 15 17:28:53 2014 -0400
+
+ arm: Reindent arm/ffi.c
+
+commit 9761b7bb70b4c47dc11dc74830964a0b3b3176d3
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 21:26:52 2014 -0700
+
+ alpha: Add support for Go closures
+
+commit f41bec3b576aa5ff8915b1188446c2dc086dfe64
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 20:46:48 2014 -0700
+
+ alpha: Add support for complex types
+
+commit 5f917371afcb4d3363fd33b547844c47264f6d4e
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 13:47:26 2014 -0700
+
+ alpha: Clean up conversion of float values
+
+ Don't use "real" conversion to double, lest we raise
+ exceptions when passing signalling nans.
+
+commit 32a26b75ba92665fa093b539318e83d916e3effb
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 12:33:53 2014 -0700
+
+ alpha: Reorganize cif flags
+
+ Unties the backend from changes to FFI_TYPE_* constants, and allows
+ compilation to succeed after the addition of FFI_TYPE_COMPLEX.
+
+ Delete the hand-written unwind info.
+
+commit c6352b664c31835b9527d747f8a29b4754cabb0e
+Author: Richard Henderson <rth@redhat.com>
+Date: Thu Oct 23 00:26:14 2014 -0400
+
+ aarch64: Add support for Go closures
+
+commit 0e41c73b092064e986d484270a13046479d6bda3
+Author: Richard Henderson <rth@redhat.com>
+Date: Wed Oct 22 23:48:12 2014 -0400
+
+ aarch64: Move x8 out of call_context
+
+ Reduces stack size. It was only used by the closure, and there
+ are available argument registers.
+
+commit a992f8789b5202ca180e67b16b47ee834160665c
+Author: Richard Henderson <rth@redhat.com>
+Date: Wed Oct 22 22:58:09 2014 -0400
+
+ aarch64: Add support for complex types
+
+commit 658b2b56001e293848ea22b70068bd7f8daa7205
+Author: Richard Henderson <rth@redhat.com>
+Date: Wed Oct 22 22:36:07 2014 -0400
+
+ aarch64: Remove aarch64_flags
+
+ This field was useless from the start, since the normal flags
+ field is available for backend use.
+
+commit 4a3cbcaa4f1d3834e0b74c9a841c3f51c5e0454c
+Author: Richard Henderson <rth@redhat.com>
+Date: Wed Oct 22 22:32:13 2014 -0400
+
+ aarch64: Unify scalar fp and hfa handling
+
+ Since an HFA of a single element is exactly the same as scalar,
+ this tidies things up a bit.
+
+commit 12cf89ee04dc01650f71bc38ce414c953c83199a
+Author: Richard Henderson <rth@redhat.com>
+Date: Wed Oct 22 21:53:30 2014 -0400
+
+ aarch64: Move return value handling into ffi_closure_SYSV
+
+ As with the change to ffi_call_SYSV, this avoids copying data
+ into a temporary buffer.
+
+commit 4fe1aea1211aaf228c2db867b8ac6f1620de72d4
+Author: Richard Henderson <rth@redhat.com>
+Date: Wed Oct 22 17:06:19 2014 -0400
+
+ aarch64: Move return value handling into ffi_call_SYSV
+
+ This lets us pass return data directly to the caller of ffi_call
+ in most cases, rather than storing it into temporary storage first.
+
+commit 325471ea6a7bf954943485458a1bd391635dfaa8
+Author: Richard Henderson <rth@redhat.com>
+Date: Wed Oct 22 13:58:59 2014 -0400
+
+ aarch64: Merge prep_args with ffi_call
+
+ Use the trick to allocate the stack frame for ffi_call_SYSV
+ within ffi_call itself.
+
+commit 8c8161cb623585d5d0c783b9d494b9b74ada6ced
+Author: Richard Henderson <rth@redhat.com>
+Date: Wed Oct 22 12:52:07 2014 -0400
+
+ aarch64: Tidy up abi manipulation
+
+ Avoid false abstraction, like get_x_addr. Avoid recomputing data
+ about the type being manipulated. Use NEON insns for HFA manipulation.
+
+ Note that some of the inline assembly will go away in a subsequent patch.
+
+commit b55e03665ddf2423df9baee0d3172892ba781c26
+Author: Richard Henderson <rth@redhat.com>
+Date: Wed Oct 22 12:33:59 2014 -0400
+
+ aarch64: Treat void return as not passed in registers
+
+ This lets us do less post-processing when there's no return value.
+
+commit 2e32f9bf6ffa6782b70fafe96bdf21c5aa44f534
+Author: Richard Henderson <rth@redhat.com>
+Date: Tue Oct 21 22:49:05 2014 -0400
+
+ aarch64: Use correct return registers
+
+ There are fewer return registers than argument registers.
+
+commit 95a04af134431ccc8230aca1641541a5e8fcbdc9
+Author: Richard Henderson <rth@redhat.com>
+Date: Tue Oct 21 22:41:07 2014 -0400
+
+ aarch64: Reduce the size of register_context
+
+ We don't need to store 32 general and vector registers.
+ Only 8 of each are used for parameter passing.
+
+commit 77c4cddca6aeb6e545e21f235e29323e05f5a3a3
+Author: Richard Henderson <rth@redhat.com>
+Date: Tue Oct 21 13:30:40 2014 -0400
+
+ aarch64: Simplify AARCH64_STACK_ALIGN
+
+ The iOS abi doesn't require padding between arguments, but
+ that's not what AARCH64_STACK_ALIGN meant. The hardware will
+ in fact trap if the SP register is not 16 byte aligned.
+
+commit b5f147d84761dc673ffe01d6af82bcde4ea47928
+Author: Richard Henderson <rth@redhat.com>
+Date: Tue Oct 21 13:27:57 2014 -0400
+
+ aarch64: Always distinguish LONGDOUBLE
+
+ Avoid if-deffery by forcing FFI_TYPE_LONGDOUBLE different
+ from FFI_TYPE_DOUBLE. This will simply be unused on hosts
+ that define them identically.
+
+commit 38b54b9c180af13a3371e70a151a1a97e105b03f
+Author: Richard Henderson <rth@redhat.com>
+Date: Tue Oct 21 13:17:39 2014 -0400
+
+ aarch64: Improve is_hfa
+
+ The set of functions get_homogeneous_type, element_count, and is_hfa
+ are all intertwined and recompute data. Return a compound quantity
+ from is_hfa that contains all the data and avoids the recomputation.
+
+commit 18b74ce54afab45fcf2a7d4eb86bb2ce9db8cec8
+Author: Richard Henderson <rth@redhat.com>
+Date: Tue Oct 21 13:00:34 2014 -0400
+
+ aarch64: Fix non-apple compilation
+
+commit 2650f47fe8388f3281ec00e2d1e3bc777c1d3544
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Nov 6 10:57:04 2014 -0800
+
+ x86: Use win32 name mangling for fastcall functions
+
+commit f8c64e2486c956109bf5255a0c0a85f24cc86c72
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Nov 5 17:04:29 2014 +0100
+
+ x86: Add support for Go closures
+
+commit 198f469e91076f84ab6ac38055ad12a5490101cd
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Nov 5 16:34:41 2014 +0100
+
+ x86: Add support for Complex
+
+commit b21ec1ce783f09335c0e6c6f96ccc7e89da5a1b4
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Nov 5 10:15:25 2014 +0100
+
+ x86: Rewrite closures
+
+ Move everything into sysv.S, removing win32.S and freebsd.S.
+ Handle all abis with a single ffi_closure_inner function.
+ Move complexity of the raw THISCALL trampoline into assembly
+ instead of the trampoline itself.
+ Only push the context for the REGISTER abi; let the rest
+ receive it in a register.
+
+commit b9ac94f3af9b1ca1853850911b7d3bc058296c71
+Author: Richard Henderson <rth@twiddle.net>
+Date: Sat Nov 1 15:10:34 2014 -0700
+
+ x86: Rewrite ffi_call
+
+ Decouple the assembly from FFI_TYPE_*. Merge prep_args with ffi_call,
+ passing the frame and the stack to the assembly.
+
+ Note that this patch isn't really standalone, as this breaks closures.
+
+commit 159d3788eb52b89ed6bc5dd6ebb85c02cd150232
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 31 12:07:02 2014 -0700
+
+ x86: Convert to gas generated unwind info
+
+commit e7b0056d60f29675072454a575eed98053fc63d6
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Oct 30 13:57:39 2014 -0700
+
+ x86: Force FFI_TYPE_LONGDOUBLE different from FFI_TYPE_DOUBLE
+
+ There are few abis that set double = long double. Eliminate the
+ conditional compilation and let this code simply be unused there.
+
+commit 4b2fad8fd583f1d9c36db0044c4d46316207aa49
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Oct 30 12:41:31 2014 -0700
+
+ x86: Remove some conditional compilation
+
+ Removal of ifdefs made possible to due to ffi_abi unification.
+
+commit ef76205647bca77796882d31f6ab5e889f461f07
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Oct 30 12:13:31 2014 -0700
+
+ x86: Tidy ffi_abi
+
+ The x86_64 unix port only handles one ABI; don't define all of the
+ other symbols. The UNIX64 symbol retains the same value.
+
+ The i386 ports ought to have the same symbols, even if we can't yet
+ unify the values without incrementing the libffi soname.
+
+commit 7cf841324f3d15c46833e0f2ddf8a98c4b24711e
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Nov 7 06:56:55 2014 -0800
+
+ testsuite: Add two dg-do run markers
+
+ Caught by clang warning about unused -L parameter.
+
+commit fc501750f41e2ee7f4268f490f590ce97a25a818
+Author: Richard Henderson <rth@twiddle.net>
+Date: Wed Nov 5 16:33:44 2014 +0100
+
+ testsuite: Fix return_complex2 vs excessive precision
+
+ Use the previously computed rc2 to validate, rather than
+ recomputing a floating point result with excess precision.
+
+commit 610c90bf7131de70318dc981a529a63ae36981b8
+Author: Richard Henderson <rth@twiddle.net>
+Date: Tue Oct 28 11:21:50 2014 -0700
+
+ x86_64: Add support for complex types
+
+commit 32c56831636a489a1c5084e42ffbd935902b1033
+Author: Richard Henderson <rth@twiddle.net>
+Date: Tue Oct 28 11:17:35 2014 -0700
+
+ x86_64: Decouple return types from FFI_TYPE constants
+
+ We can better support structure returns, and as prep for
+ complex types.
+
+commit 2e9dc1655600eb8928ebab13fa246187b6205109
+Author: Richard Henderson <rth@twiddle.net>
+Date: Mon Oct 27 13:41:39 2014 -0700
+
+ x86_64: Fixups for x32
+
+commit ebd82769de5fc909ec9678aafca674ece394d173
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Oct 23 23:57:06 2014 -0700
+
+ win64: Remove support from ffi.c
+
+commit 99db4d42acc7ee6d2ad206848be38083d7b5e094
+Author: Richard Henderson <rth@twiddle.net>
+Date: Thu Oct 23 14:12:18 2014 -0700
+
+ win64: Rewrite
+
+ It's way too different from the 32-bit ABIs with which it is
+ currently associated. As seen from all of the existing XFAILs.
+
+commit 6b62fb4a26d7363548a92f1a156562cfa648726e
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 11:11:58 2014 -0700
+
+ x86-64: Support go closures
+
+ Dumps all of the hand-coded unwind info for gas generated. Move jump
+ table data into .rodata. Adjust ffi_call_unix64 to load the static
+ chain. Split out sse portions of ffi_closure_unix64 to
+ ffi_closure_unix64_sse rather than test cif->flags at runtime.
+
+commit 89bbde8b4e802625bdbf830ea14e938beea79835
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 10:55:11 2014 -0700
+
+ Add ffi_cfi.h
+
+ Have one copy of the HAVE_AS_CFI_PSEUDO_OP code
+ to share between all backends.
+
+commit e951d64c085267a30036907d02f94a70dee4c9d9
+Author: Richard Henderson <rth@twiddle.net>
+Date: Fri Oct 17 10:12:25 2014 -0700
+
+ Add entry points for interacting with Go
+
+ A "ffi_go_closure" is intended to be compatible with the
+ function descriptors used by Go, and ffi_call_go sets up
+ the static chain parameter for calling a Go function.
+
+ The entry points are disabled when a backend has not been
+ updated, much like we do for "normal" closures.
+
+commit a0bdc5250cd36f1d2578358e33299fd2408091ac
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 11 09:43:01 2014 -0500
+
+ Fix typo
+
+commit 67c0c0705318d2e567fd48e680d63dca3619a235
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 11 07:30:49 2014 -0500
+
+ Final 3.2 changes
+
+commit ee826b933bbdeb68ee81876ffb508c3908eed371
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 11 07:29:26 2014 -0500
+
+ Final 3.2 changes
+
+commit c81a705d53be97899d314953987936213244b1ba
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 4 13:29:58 2014 -0500
+
+ Mention OpenRISC
+
+commit 6a17ad540d7ddb7a812687f4380bd0ef2d2865bb
+Merge: 990eb9d 0f316ab
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Sep 28 00:54:00 2014 -0400
+
+ Merge pull request #134 from s-macke/openrisc
+
+ Add OpenRISC support
+
+commit 990eb9d4c244324771a7d878a168bb8eba1850c0
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Sep 28 00:50:29 2014 -0400
+
+ Only run the complex type tests on supported platforms.
+
+commit 0f316ab7c11b8315a838a6ae4645d36ff2c46f4c
+Author: Sebastian Macke <sebastian@macke.de>
+Date: Sat Sep 27 00:19:15 2014 +0000
+
+ Add OpenRISC support
+
+ This patch adds support for the OpenRISC architecture.
+ (http://opencores.org/or1k/Main_Page)
+
+ This patch has been tested under Linux with QEMU-user emulation support.
+ - 32 Bit
+ - big endian
+ - delayed instructions
+ This is the only available configuration under Linux.
+
+ The description of the ABI can be found on the official website.
+
+ Is passes the testsuite except of the unwindtest_ffi_call.cc
+ testcase, which seems to be a problem of gcc and not libffi.
+ Some testcases of the gcc testsuite still fail.
+
+ Signed-off-by: Sebastian Macke <sebastian@macke.de>
+
+commit 6695983d2f0857caab220862de12f3f94a55bcf6
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Sep 20 07:44:37 2014 -0400
+
+ Add complex type support. Mostly broken right now
+
+commit fbbf48fbdf9b1491af0aefc00523a1b5d8bb9349
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Sep 20 07:43:51 2014 -0400
+
+ Compile tests with -Wno-psabi when using GCC
+
+commit ae8d2554c5f192be54dadc9f99a1449b4df1b222
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Sep 20 07:08:37 2014 -0400
+
+ Update version to 3.2
+
+commit b2ca59d39d2192021316561ea9dda3d35d8d35d9
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Sep 20 07:08:05 2014 -0400
+
+ More README updates for 3.2
+
+commit f920a01ad8eafc79daaf331499ef9a97696c46a7
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Sep 20 06:54:06 2014 -0400
+
+ Update release notes.
+
+commit bfcbf329c5e4bebdb32134d4e53260e17e4e66cc
+Author: Bernd Edlinger <bernd.edlinger@hotmail.de>
+Date: Sat Sep 20 06:51:45 2014 -0400
+
+ 2014-05-11 Bernd Edlinger <bernd.edlinger@hotmail.de>
+
+ Fix current cygwin-64 build problems.
+ * src/java_raw_api.c: Remove if !defined(FFI_NO_RAW_API).
+ * src/x86/ffi.c: Add if defined(__CYGWIN__).
+ * src/x86/win64.S (ffi_closure_win64, ffi_call_win64): Added
+ handling for FFI_TYPE_UINT64, FFI_TYPE_POINTER and FFI_TYPE_INT.
+ Added SEH information. Fixed formatting.
+
+commit 32cb2ce81db9457c6bd43a2587d7fa23a2edb9b1
+Author: Jakub Jelinek <jakub@redhat.com>
+Date: Sat Sep 20 06:39:55 2014 -0400
+
+ 2014-09-10 Jakub Jelinek <jakub@redhat.com>
+
+ * src/powerpc/linux64.S: Emit .note.GNU-stack even when
+ POWERPC64 is not defined.
+ * src/powerpc/linux64_closure.S: Likewise. Also test _CALL_ELF == 2.
+
+commit aaf3101ba81af8f488502881648e3f687721671e
+Author: Matthias Klose <doko@ubuntu.com>
+Date: Sat Sep 20 06:37:04 2014 -0400
+
+ Fix -Werror=declaration-after-statement problem
+
+commit 6e8a4460833594d5af1b4539178025da0077df19
+Author: Dominik Vogt <vogt@linux.vnet.ibm.com>
+Date: Sat Sep 20 06:21:19 2014 -0400
+
+ 2014-07-22 Dominik Vogt <vogt@linux.vnet.ibm.com>
+
+ * src/types.c (FFI_TYPEDEF, FFI_NONCONST_TYPEDEF): Merge the macros by
+ adding another argument that controls whether the result is const or not
+ (FFI_LDBL_CONST): Temporary macro to reduce ifdef confusion
+ * src/prep_cif.c (ffi_prep_cif_core): Replace list of systems with new
+ macro FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+ * src/pa/ffitarget.h (FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION):
+ Define.
+ * src/s390/ffitarget.h (FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION):
+ Define.
+ * src/x86/ffitarget.h (FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION):
+ Define.
+
+ 2014-07-22 Dominik Vogt <vogt@linux.vnet.ibm.com>
+
+ * doc/libffi.texi (Primitive Types): Document ffi_type_complex_float,
+ ffi_type_complex_double and ffi_type_complex_longdouble
+ (Complex Types): New subsection.
+ (Complex Type Example): Ditto.
+ * testsuite/libffi.call/cls_align_complex_double.c: New
+ FFI_TYPE_COMPLEX test.
+ * testsuite/libffi.call/cls_align_complex_float.c: Ditto.
+ * testsuite/libffi.call/cls_align_complex_longdouble.c: Ditto.
+ * testsuite/libffi.call/cls_complex_double.c: Ditto.
+ * testsuite/libffi.call/cls_complex_float.c: Ditto.
+ * testsuite/libffi.call/cls_complex_longdouble.c: Ditto.
+ * testsuite/libffi.call/cls_complex_struct_double.c: Ditto.
+ * testsuite/libffi.call/cls_complex_struct_float.c: Ditto.
+ * testsuite/libffi.call/cls_complex_struct_longdouble.c: Ditto.
+ * testsuite/libffi.call/cls_complex_va_double.c: Ditto.
+ * testsuite/libffi.call/cls_complex_va_float.c: Ditto.
+ * testsuite/libffi.call/cls_complex_va_longdouble.c: Ditto.
+ * testsuite/libffi.call/complex_double.c: Ditto.
+ * testsuite/libffi.call/complex_defs_double.c: Ditto.
+ * testsuite/libffi.call/complex_float.c: Ditto.
+ * testsuite/libffi.call/complex_defs_float.c: Ditto.
+ * testsuite/libffi.call/complex_longdouble.c: Ditto.
+ * testsuite/libffi.call/complex_defs_longdouble.c: Ditto.
+ * testsuite/libffi.call/complex_int.c: Ditto.
+ * testsuite/libffi.call/many_complex_double.c: Ditto.
+ * testsuite/libffi.call/many_complex_float.c: Ditto.
+ * testsuite/libffi.call/many_complex_longdouble.c: Ditto.
+ * testsuite/libffi.call/return_complex1_double.c: Ditto.
+ * testsuite/libffi.call/return_complex1_float.c: Ditto.
+ * testsuite/libffi.call/return_complex1_longdouble.c: Ditto.
+ * testsuite/libffi.call/return_complex2_double.c: Ditto.
+ * testsuite/libffi.call/return_complex2_float.c: Ditto.
+ * testsuite/libffi.call/return_complex2_longdouble.c: Ditto.
+ * testsuite/libffi.call/return_complex_double.c: Ditto.
+ * testsuite/libffi.call/return_complex_float.c: Ditto.
+ * testsuite/libffi.call/return_complex_longdouble.c: Ditto.
+ * src/raw_api.c (ffi_raw_to_ptrarray): Handle FFI_TYPE_COMPLEX
+ (ffi_ptrarray_to_raw): Ditto.
+ * src/prep_cif.c (ffi_prep_cif_core): Abort if FFI_TYPE_COMPLEX is not
+ implemented in libffi for the target.
+ * src/java_raw_api.c (ffi_java_raw_size): FFI_TYPE_COMPLEX not supported
+ yet (abort).
+ (ffi_java_raw_to_ptrarray): Ditto.
+ (ffi_java_rvalue_to_raw): Ditto.
+ (ffi_java_raw_to_rvalue): Ditto.
+ * src/debug.c (ffi_type_test): Add debug tests for complex types.
+ * include/ffi.h.in (FFI_TYPE_COMPLEX): Add new FFI_TYPE_COMPLEX.
+ (FFI_TYPE_LAST): Bump.
+ (ffi_type_complex_float): Add new ffi_type_....
+ (ffi_type_complex_double): Ditto.
+ (ffi_type_complex_longdouble): Ditto.
+
+ 2014-07-22 Dominik Vogt <vogt@linux.vnet.ibm.com>
+
+ * src/s390/ffitarget.h (FFI_TARGET_HAS_COMPLEX_TYPE): Define to provide
+ FFI_TYPE_COMPLEX support.
+ * src/s390/ffi.c (ffi_check_struct_type): Implement FFI_TYPE_COMPLEX
+ (ffi_prep_args): Ditto.
+ (ffi_prep_cif_machdep): Ditto.
+ (ffi_closure_helper_SYSV): Ditto.
+
+commit 4c5c4088aa3e4d8103ff9ca441937da64fdd849a
+Merge: 862f53d 5d6340e
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Sep 18 19:10:54 2014 -0400
+
+ Merge pull request #132 from nielsAD/master
+
+ Pascal and Register calling convention support on x86
+
+commit 862f53de04ff898a128be7eec592bae60930d6df
+Merge: 5df3840 aebf2c3
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Sep 18 19:06:08 2014 -0400
+
+ Merge pull request #130 from frida/fix/darwin-aarch64-float-alignment
+
+ Fix alignment of FFI_TYPE_FLOAT for Apple's ARM64 ABI
+
+commit 5df384077f3633ec8cf2e08f9199e5a44994dbad
+Merge: 7b7a528 0f4e09d
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Sep 18 19:05:35 2014 -0400
+
+ Merge pull request #129 from frida/fix/darwin-aarch64-cif-prep
+
+ Fix non-variadic CIF initialization for Apple/ARM64
+
+commit 7b7a5284de7a99edfcee5ac362dbf76251698e1e
+Merge: 4cd5e84 6172a99
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Sep 18 18:28:05 2014 -0400
+
+ Merge pull request #124 from knuesel/master
+
+ Fix issue with builddir when calling configure with absolute path
+
+commit 4cd5e840122e22636b5838943372c4ed74618e35
+Merge: 1cee07b 08853e3
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Sep 18 18:27:15 2014 -0400
+
+ Merge pull request #123 from ehsan/clang-cl
+
+ Add support for building with clang-cl
+
+commit 5d6340ef2cf81432da79ac8b0b1b1218ab391438
+Author: nielsAD <niels.a.d@gmail.com>
+Date: Mon Aug 25 17:29:44 2014 +0200
+
+ Determine whether register arguments (THISCALL/FASTCALL/REGISTER) are really passed via register to closures. Use stack if not.
+
+commit 6e346487b879b4b056a847268e381ae6efec4c21
+Author: nielsAD <niels.a.d@gmail.com>
+Date: Mon Aug 25 12:23:29 2014 +0200
+
+ Fixed THISCALL/FASTCALL closures and added basic support for PASCAL/REGISTER closures.
+
+commit 098dca6b31e42dd0256ed7d966729e31961f1461
+Author: nielsAD <niels.a.d@gmail.com>
+Date: Sat Aug 23 00:18:47 2014 +0200
+
+ Support for calling functions with PASCAL and REGISTER calling conventions on x86 Windows/Linux.
+ Also changed indentation to be more consistent throughout the (adjusted) files.
+
+commit 08853e32fb6b750cda664ee6d3290d340429dd4d
+Author: Ehsan Akhgari <ehsan@mozilla.com>
+Date: Thu Jul 31 20:33:33 2014 -0400
+
+ Enable forcing the usage of the static CRT in libffi's msvc wrapper
+
+ This is required for AddressSanitizer builds with clang-cl.
+
+commit aebf2c3023b5ff056a708dc34169f7b549b2ec4f
+Author: Ole André Vadla Ravnås <ole.andre.ravnas@tillitech.com>
+Date: Fri Jul 25 21:40:50 2014 +0200
+
+ Fix alignment of FFI_TYPE_FLOAT for Apple's ARM64 ABI
+
+commit 0f4e09d27dc175ce3e95d070b794351663c7220e
+Author: Ole André Vadla Ravnås <ole.andre.ravnas@tillitech.com>
+Date: Sat Jul 26 00:11:06 2014 +0200
+
+ Fix non-variadic CIF initialization for Apple/ARM64
+
+ Turns out `aarch64_nfixedargs` wasn't initialized in the non-variadic
+ case, resulting in undefined behavior when allocating arguments.
+
+commit 6172a995e14bdbc6150aa02a361f710626a5c293
+Author: Jeremie Knuesel <jeremie.knusel@sensefly.com>
+Date: Wed Jun 25 12:28:17 2014 +0200
+
+ Fix issue with builddir when calling configure with absolute path
+
+commit fb25cd08ed5a87640b02f0feeb10a09b37cfddbe
+Author: Ehsan Akhgari <ehsan@mozilla.com>
+Date: Wed Jun 11 12:07:24 2014 -0400
+
+ Add support for building with clang-cl
+
+commit 1cee07be4712411baa5eb8af22698bc8443a6d6e
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Jun 12 06:30:59 2014 -0400
+
+ Remove compiler warning
+
+commit ad0d1d239afc7ad09203847793dcc020856d1035
+Author: Samuli Suominen <ssuominen@gentoo.org>
+Date: Thu Jun 12 06:30:21 2014 -0400
+
+ Fix paths in libffi.pc.in
+
+commit df31a85103b0cc232bbc340d7e782a3853c7fad5
+Merge: 69289c1 360aa8c
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Jun 6 08:24:35 2014 -0400
+
+ Merge pull request #122 from rvandermeulen/1014976
+
+ Don't make --enable-debug imply using the debug CRT in libffi
+
+commit 360aa8ca1ead2fdaefa7b1c6f01ad001d8abae7e
+Author: Mike Hommey <mh+mozilla@glandium.org>
+Date: Mon Jun 2 09:21:10 2014 -0400
+
+ Bug 1014976 - Don't make --enable-debug imply using the debug CRT in libffi.
+
+commit 69289c10b0acb4b52c8b5df4cf738193c618db40
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat May 31 08:54:08 2014 -0400
+
+ Prepare for libffi 3.1.1
+
+commit 978c9540154d320525488db1b7049277122f736d
+Author: Samuli Suominen <ssuominen@gentoo.org>
+Date: Sat May 31 08:53:10 2014 -0400
+
+ Add missing GNU stack markings in win32.S
+
+commit cbc5a3c0200aa6c2cf8d6798d69a21501557c83f
+Author: Ryan Hill <rhill@gentoo.org>
+Date: Sat May 31 08:26:34 2014 -0400
+
+ Fix typo
+
+commit 9d8e3018ac3d0d338373bff7eefa9f006746f4ec
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat May 24 23:28:42 2014 -0400
+
+ Update current version.
+
+commit 18d56cca5a4ee95ad48b129100adf26231518ed0
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon May 19 18:05:33 2014 -0400
+
+ Increment libtool version number
+
+commit 629f1029c47e522e4331988f02f32c203a070e28
+Merge: 0403f33 c1166d4
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon May 19 18:04:28 2014 -0400
+
+ Merge pull request #120 from l0kod/tmpfile
+
+ Create temporary file with O_TMPFILE and O_CLOEXEC when available
+
+commit c1166d4f653bf6d17ad8c265cf5e8da84e2e76dc
+Author: Mickaël Salaün <mic@digikod.net>
+Date: Mon May 12 19:44:08 2014 +0200
+
+ closures: Check for mkostemp(3)
+
+commit 8daeed9570af72eb135c8ded460d2888f05b2e68
+Author: Mickaël Salaün <mic@digikod.net>
+Date: Sun May 11 22:54:58 2014 +0200
+
+ closures: Create temporary file with O_TMPFILE and O_CLOEXEC when available
+
+ The open_temp_exec_file_dir function can create a temporary file without
+ file system accessible link. If the O_TMPFILE flag is not defined (old
+ Linux kernel or libc) the behavior is unchanged.
+
+ The open_temp_exec_file_name function now need a new argument "flags"
+ (like O_CLOEXEC) used for temporary file creation.
+
+ The O_TMPFILE flag allow temporary file creation without race condition.
+ This feature/fix prevent another process to access the (future)
+ executable file from the file system.
+
+ The O_CLOEXEC flag automatically close the temporary file for any
+ execve. This avoid transmitting (executable) file descriptor to a child
+ process.
+
+commit 0403f332b1f478696c30d3d8a0e2f6eef24aaf88
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon May 19 09:41:32 2014 -0400
+
+ Update date. Annoucing 3.1 today.
+
+commit 94ac0c168ee7b115409121d88b25a4979446c8da
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon May 19 09:37:21 2014 -0400
+
+ Increment libtool library revision number
+
+commit 57465744b6e1295d7202de5a7734df589518f1c8
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun May 11 10:30:22 2014 -0400
+
+ Update to version 3.1
+
+commit 0c2251a42df5108b6d9ebe5fe1cf83d0bcdf660e
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun May 11 10:22:30 2014 -0400
+
+ Support versions of git older than 1.8.5
+
+commit 70c303cb88e23aaee91c87c56b108c50ab4f3c2f
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun May 11 09:56:40 2014 -0400
+
+ Fix testsuite for GCC 4.9.0
+
+commit 52b3457093ed19b2a7c5fcf243c4014c90ce6225
+Author: Magnus Granberg <zorry@gentoo.org>
+Date: Sun May 11 09:55:28 2014 -0400
+
+ Check /proc/self/status for PaX status.
+
+commit 7ba4c5d72aa440a4b21fb57e999e67c5957761da
+Author: Dominik Vogt <dominik.vogt@gmx.de>
+Date: Sun May 11 09:52:47 2014 -0400
+
+ Use to get correct dir
+
+commit 31e0d4ecff6dc2a6c75a066ee099b52a43f6ba27
+Merge: 1c0e9a7 99909eb
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Apr 23 19:24:47 2014 -0400
+
+ Merge pull request #119 from joshtriplett/fastcall-fastball
+
+ src/x86/win32.S: Define ffi_closure_FASTCALL in the MASM section, too
+
+commit 99909eb6184b62408d88b6b4e7ab38e84e6d0bf3
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Tue Apr 22 21:17:52 2014 -0700
+
+ src/x86/win32.S: Define ffi_closure_FASTCALL in the MASM section, too
+
+commit 1c0e9a7297ced15413c2d2d5d35f6c650c4b46c9
+Merge: 93a24f2 d369522
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Apr 21 12:41:56 2014 -0400
+
+ Merge pull request #101 from joshtriplett/fastcall-closures
+
+ Support closures for fastcall
+
+commit d36952273d4fafbda91ecc205fc0824f7cc65e70
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Apr 20 12:03:25 2014 -0700
+
+ Support fastcall closures
+
+ libffi on 32-bit x86 now supports closures for all supported ABIs.
+ Thus, rewrite the last remaining duplicated-by-ABI test (closure_stdcall
+ and closure_thiscall) to use the generic ABI_NUM/ABI_ATTR mechanism.
+
+commit 93a24f216bcdd1018b976d697179c6d49004015a
+Merge: dd11a04 2349fec
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Apr 12 19:38:07 2014 -0400
+
+ Merge pull request #80 from ueno/devel
+
+ Fix typo in doc
+
+commit dd11a04061cb49ce1d702545693c24eb1267d648
+Merge: 8fa2812 03ca880
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Apr 12 19:37:21 2014 -0400
+
+ Merge pull request #86 from joshtriplett/testsuite-CC-CXX
+
+ testsuite ignores CC parameter supplied to configure or make
+
+commit 8fa2812355e685a42abf9a62fbc674d616b2edee
+Merge: 8a58e6b 419503f
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Apr 12 19:32:08 2014 -0400
+
+ Merge pull request #116 from frida/fix/darwin-aarch64-variadic
+
+ Fix handling of variadic calls on Darwin/AArch64
+
+commit 8a58e6b7805b736def197b8baf8e465a2a3f6913
+Merge: 30b77c5 a539f7f
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Apr 12 19:30:18 2014 -0400
+
+ Merge pull request #115 from frida/fix/darwin-aarch64-alignment
+
+ Fix alignment of AArch64 assembler functions
+
+commit 30b77c56f95c63ecd83399aafdbad7b07330f2fd
+Merge: dc33cb3 3e2b84d
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Apr 12 19:29:13 2014 -0400
+
+ Merge pull request #117 from frida/fix/windows-regression
+
+ Fix Windows regression
+
+commit 3e2b84d295531720917bf46afc532fc6d877e3ec
+Author: Ole André Vadla Ravnås <ole.andre.ravnas@tillitech.com>
+Date: Sat Apr 12 01:04:04 2014 +0200
+
+ Fix Windows regression
+
+ Introduced by b5fed601948237037513a9b7f967c8fc6c9ff1f6.
+
+commit 419503f409c321fe31ff59d963ef34bb913420d0
+Author: Ole André Vadla Ravnås <ole.andre.ravnas@tillitech.com>
+Date: Sun Apr 6 20:54:13 2014 +0200
+
+ Fix handling of variadic calls on Darwin/AArch64
+
+commit a539f7ffd6783aa11353d13265520e453c565fb4
+Author: Ole André Vadla Ravnås <ole.andre.ravnas@tillitech.com>
+Date: Sun Apr 6 20:53:02 2014 +0200
+
+ Fix alignment of AArch64 assembler functions
+
+commit dc33cb3c998da521a960385c1269c3aef552f69f
+Merge: c860a99 b5fed60
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Apr 5 23:41:22 2014 -0400
+
+ Merge pull request #114 from joshtriplett/bounce-on-a-tiny-trampoline
+
+ Fix ABI on 32-bit non-Windows x86: go back to trampoline size 10
+
+commit b5fed601948237037513a9b7f967c8fc6c9ff1f6
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sat Apr 5 17:33:42 2014 -0700
+
+ Fix ABI on 32-bit non-Windows x86: go back to trampoline size 10
+
+ The trampoline size is part of the ABI, so it cannot change. Move the
+ logic from the stdcall and thiscall trampolines to the functions they
+ call, to reduce them both to 10 bytes.
+
+ This drops the previously added support for raw THISCALL closures on
+ non-Windows. (Non-raw THISCALL closures still work.)
+
+commit 03ca880081b22efab09ba72268270f83017d3d7b
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Thu Mar 27 08:44:34 2014 -0700
+
+ README: Note the testsuite changes to respect $CC and $CXX
+
+commit d74df8c5d8c6722ecb908da98c86cc8e2c755b84
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Thu Mar 27 00:44:12 2014 -0700
+
+ README: Update Windows example to set both CC and CXX
+
+commit 7d698125b1f05173f3656a89755a2eb58813b002
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Wed Mar 26 23:17:56 2014 -0700
+
+ Use the proper C++ compiler to run C++ tests
+
+ Running the C compiler with -shared-libgcc -lstdc++ does not work on
+ non-GCC compilers.
+
+commit fa5e88f170cb37c7b2b9bb015c8c5b854ffd8a3e
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Wed Mar 26 23:53:57 2014 -0700
+
+ .travis.yml: Make the build command more readable by splitting at &&
+
+ "script" can contain multiple commands to run in sequence.
+
+commit 0c3824702d3d59d37f8c177d646303f546187683
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Wed Mar 26 14:51:32 2014 -0700
+
+ Always set CC_FOR_TARGET for dejagnu, to make the testsuite respect $CC
+
+ This fixes cross-compilation and compilation with CC="gcc -m32".
+
+commit 9946a92af31b30cb7760150d1f8ca6c11b01aeea
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Wed Mar 26 20:18:58 2014 -0700
+
+ Stop looking for expect and runtest above top_builddir
+
+ Users wishing to test hand-compiled versions of expect and runtest can
+ easily enough put them in their path or set EXPECT and RUNTEST
+ themselves.
+
+commit acb202325215058639234efb7af1f04c1c8a1f44
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Wed Mar 26 20:18:41 2014 -0700
+
+ Stop setting an empty AM_RUNTESTFLAGS
+
+commit c860a992fef5d7cd7bb0975b1632d17a9fafe007
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 25 17:02:51 2014 -0400
+
+ Upgrade version to 3.1-rc1
+
+commit 9837073e6203048a162a226798c5d252600219ed
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 25 16:24:14 2014 -0400
+
+ Update copyright date and clean up README notes.
+
+commit 18d3baa9f597b026675baa1b4e5a5eeef7577a08
+Merge: afee537 f0c8a31
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 25 16:12:53 2014 -0400
+
+ Merge pull request #108 from joshtriplett/freebsd
+
+ [3.1 blocker] Fix FreeBSD support
+
+commit afee53738a995e23bd2f89fd0f7b30b380566106
+Merge: 7d24785 b2d610e
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 25 16:12:35 2014 -0400
+
+ Merge pull request #106 from joshtriplett/darwin-award
+
+ [3.1 blocker] Update OS X build system to include win32.S on 32-bit
+
+commit 7d2478568ed9f03cbf57627f449a2d2cf4d1571c
+Merge: beab5f3 56be47f
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 25 16:12:17 2014 -0400
+
+ Merge pull request #110 from joshtriplett/w64
+
+ Fix 64-bit Windows support
+
+commit beab5f334d9ec5b8b91d1cc727d1029b40358e7e
+Merge: 28fb197 ef5890e
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 25 16:07:47 2014 -0400
+
+ Merge pull request #105 from joshtriplett/win32-relocations
+
+ [3.1 blocker] win32.S needs to handle relocations/GOT
+
+commit f0c8a31577172104049283f0a80c723084a5bd77
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Mon Mar 24 22:14:26 2014 -0700
+
+ Compile win32.S on FreeBSD
+
+commit b2d610e028b5ce48d1ad7e5d0debc9c321d891b2
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Fri Mar 21 11:10:13 2014 -0700
+
+ Compile win32.S on 32-bit Darwin as well
+
+commit be50b87a490e794362cb4a27ada2fbaab202adb8
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Mon Mar 24 21:44:13 2014 -0700
+
+ Always use configure to detect whether global symbols need underscores
+
+ 64-bit Windows already used this check; make it universal, and use it in
+ place of an ifdef on X86_WIN32, to handle non-Windows platforms that use
+ the underscore, such as Darwin.
+
+commit 56be47f87629e31afbcb0774aa65735f539ee972
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Mon Mar 24 21:24:53 2014 -0700
+
+ Fix a warning on 64-bit Windows
+
+ When sizeof(size_t) != sizeof(unsigned), adding a size_t to cif->bytes
+ produces a "possible loss of data" warning. However, the size_t in
+ question refers to the size of a single parameter. Use a cast to avoid
+ the warning.
+
+commit 48a8eda74aad8a21b6f26df5df08fe64c043d208
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Mon Mar 24 21:21:12 2014 -0700
+
+ Avoid referencing undefined ABIs on 64-bit Windows builds
+
+ 64-bit Windows does not have FFI_STDCALL, FFI_THISCALL, or FFI_FASTCALL.
+
+commit f0f4138f90345d7d67dfa6783a7e1c7cc30d3c6f
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sat Mar 22 10:00:53 2014 -0700
+
+ win32.S: Add handling for position-independent code on Darwin
+
+ Newer versions of Darwin generate the necessary stub functions
+ automatically and just need a call instruction, but accomodating older
+ versions as well requires adding the stub.
+
+commit ef5890ebafb7cd2fbf9acf161edb55fe1382871c
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Fri Mar 21 11:01:39 2014 -0700
+
+ win32.S: Use shifting for multiplication rather than repeated addition
+
+ The jump table code added a register to itself twice to multiply by 4;
+ shift the register left by 2 instead.
+
+commit 4fca48901e7e4f53bf490ed22607b2d2d8f4bfcc
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Fri Mar 21 11:00:41 2014 -0700
+
+ win32.S: Make the jump tables position-independent
+
+ Now that non-Windows platforms include win32.S, it needs to support
+ building as position-independent code. This fixes build failures on
+ target platforms that do not allow text relocations.
+
+commit 2087dcf736274286f76c69d3988fb6d7cc4fd0f5
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Fri Mar 21 10:57:06 2014 -0700
+
+ win32.S: Make calls to ffi_closure_SYSV_inner position-independent
+
+ Now that non-Windows platforms include win32.S, it needs to support
+ building as position-independent code. This fixes one source of build
+ failures on target platforms that do not allow text relocations.
+
+commit 28fb197079cf1d11da4eef7c8c243ab05590c528
+Merge: c697472 c3dd0a1
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Mar 18 12:19:36 2014 -0400
+
+ Merge pull request #107 from rvandermeulen/msvcc
+
+ Various compatibility fixes and improvements to msvcc.sh.
+
+commit c3dd0a1a0245fc174361a70876e88ae24285f861
+Author: Ryan VanderMeulen <ryanvm@gmail.com>
+Date: Tue Mar 18 12:09:45 2014 -0400
+
+ Various compatibility fixes and improvements to msvcc.sh.
+
+ * Don't try to mix incompatible optimization flags in debug builds.
+ * Workaround ax_cc_maxopt.m4 not supporting MSVC and change -O3 to -O2.
+ * Fix MSVC warning by properly passing linker flags to compiler.
+ * Make msvcc.sh return 1 if invalid command line options are used rather than silently eating them.
+ * Add more comments.
+
+commit c697472fccfbb5b87b007c053cda9ef014b346b9
+Merge: 83fd2bc e48918e
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Mar 17 00:32:42 2014 -0400
+
+ Merge pull request #102 from joshtriplett/test-generic
+
+ Add ABIs to the test matrix; unify many bits of the testsuite
+
+commit e48918ecf876bc85d040fc50a232059c566553a8
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 20:29:27 2014 -0700
+
+ testsuite: Add ABIs to the test matrix; unify tests across ABIs
+
+ This eliminates all the *_win32.c tests in favor of the tests they were
+ branched from, and expands test coverage to run many more tests on
+ stdcall, thiscall, and fastcall.
+
+ This same mechanism also supports testing any other target that has
+ multiple ABIs.
+
+commit 4d4d368e5a55d9443c4c53b1b70d58ab6d8c941c
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 17:02:05 2014 -0700
+
+ testsuite: Replace ffitestcxx.h with ffitest.h
+
+ ffitest.h contains a superset of the functionality of ffitestcxx.h;
+ make the C++ tests include ffitest.h instead, and remove ffitestcxx.h.
+
+commit 3f97cf3413c46caf2a79f32ac9cda4620972c2d7
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 16:53:42 2014 -0700
+
+ testsuite: Unify the C and C++ testsuites
+
+ These two testsuites differ only in the source file glob and a couple of
+ additional compiler options; unify the remaining bits.
+
+commit 0d9cce8edb937bbe771a6cdd25f671edf06d2128
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 16:22:58 2014 -0700
+
+ testsuite: ffitest.h: Parenthesize the CHECK macro
+
+commit 5695ec1444c5323e48fe4314f8c8f027625e67df
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 16:04:58 2014 -0700
+
+ testsuite: Factor out a function to run a matrix of tests
+
+ This commons up code from libffi.call/call.exp and
+ libffi.special/special.exp, unifies the optimization option matrix
+ between the two, and makes it easier to add more axes to the matrix
+ in the future.
+
+commit dfdb02cc869855d3b68571e5f7aa77ae8c9d254a
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 15:26:26 2014 -0700
+
+ testsuite: Introduce a __THISCALL__ compiler-specific macro
+
+commit 83fd2bce0456224483435d4b764063f4513fd464
+Merge: 3658a07 06ff924
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 22:03:29 2014 -0400
+
+ Merge pull request #99 from joshtriplett/gitignore
+
+ .gitignore: Ignore more generated files
+
+commit 3658a0700a50d37a2fdba04fd9d79ad2f706d9f5
+Merge: d948d0a 46c5d3c
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 21:37:42 2014 -0400
+
+ Merge pull request #100 from rvandermeulen/bug-756740
+
+ Change double quotes in Makefile.am to single quotes.
+
+commit 46c5d3c30fdc2b43c076ad955078d7c5f1e75b37
+Author: Ryan VanderMeulen <ryanvm@gmail.com>
+Date: Sun Mar 16 21:16:08 2014 -0400
+
+ Change double quotes in Makefile.am to single quotes.
+
+ This was originally done in PR #84, except the change was made to Makefile.in instead of Makefile.am and was therefore reverted the next time the files were regenerated.
+
+commit 06ff924215a2f9739efa2c059dc595bc4ec1c851
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 16:19:46 2014 -0700
+
+ .gitignore: Ignore more generated files
+
+ The build process generates doc/libffi.info and fficonfig.h.in, so add
+ them to .gitignore.
+
+commit bad8948346e9b8813023a0cc78a3b6eb8d9c14c6
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 15:16:18 2014 -0700
+
+ testsuite: Introduce a __STDCALL__ compiler-specific macro
+
+ Several tests want to use stdcall, which differs in syntax by compiler,
+ so introduce a macro for it in ffitest.h.
+
+commit 98a793fa36a4ab3ba24d059cb80a2891cdb940e1
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 15:20:36 2014 -0700
+
+ testsuite: Common up the ifdef blocks for compiler-specific macros
+
+commit d948d0a729c934b0224749338a3ba0a2c8f51c45
+Merge: b61b472 a86bd31
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 10:53:48 2014 -0400
+
+ Merge pull request #98 from joshtriplett/unconfigure.host
+
+ Merge configure.host into configure.ac
+
+commit a86bd318e2424d879d784ee7b29d6536d7a17c18
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 06:58:59 2014 -0700
+
+ Merge configure.host into configure.ac
+
+ configure.host only has a single entry, and shows no signs of needing
+ more added.
+
+commit b61b472bd0647006d6685238721002017f1d119c
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 09:45:55 2014 -0400
+
+ Update version to 3.1-rc0. Clean up README.
+
+commit 7a64e7dbba54e6e9f69954adfb943be1856ff928
+Merge: 11a5c5c eef2e02
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 09:39:08 2014 -0400
+
+ Merge pull request #97 from joshtriplett/remove-more-generated-files
+
+ Remove more generated files
+
+commit 11a5c5c39f5861011f6c5ddf795da3a32b5f0082
+Merge: 9a62a21 1c68c07
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 09:38:47 2014 -0400
+
+ Merge pull request #96 from joshtriplett/sawing-changelogs
+
+ Generate ChangeLog from git in make dist; remove it from version control
+
+commit eef2e02a13d7d1c8145d47a64467f654406a3548
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 06:26:03 2014 -0700
+
+ doc: Remove autogenerated info file and stamp
+
+commit 9fb403d3c5d9643e0f561cab6d4a07b1e54907ff
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 06:25:52 2014 -0700
+
+ fficonfig.h.in: Remove, configure generates it
+
+commit 1c68c07217fda78a779778c1480fedef7a58d5b4
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 06:11:58 2014 -0700
+
+ Generate ChangeLog from git in make dist
+
+ Archive the existing ChangeLog to ChangeLog.libffi-3.1
+
+commit c65ed55e655711e008282edbdd82ce95d008b4f6
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 05:52:00 2014 -0700
+
+ ChangeLog.v1: Fix typo in explanatory header.
+
+commit 9a62a21f5c3a8e1da463229f3170c8ab3031d920
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 09:03:57 2014 -0400
+
+ Add missing ChangeLog entry. Clean up some entries.
+
+commit 9bc704c58cb7a049d867837e3a11e2e31886ec66
+Merge: 694447a e892e58
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 08:41:00 2014 -0400
+
+ Merge pull request #95 from joshtriplett/news
+
+ README: Update news for 3.0.14
+
+commit e892e581d1838a06c18c7ecd50ebd79915cff92b
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 05:38:24 2014 -0700
+
+ README: Update news for 3.0.14
+
+commit 694447aa29deadd571efb4e9a26ee3f68ede1493
+Merge: fdc87f3 45a6c21
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 08:32:05 2014 -0400
+
+ Merge pull request #93 from joshtriplett/travis-dist
+
+ Make Travis check "make dist"
+
+commit 45a6c21efa944b520842e631dc54919b04884744
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 05:29:08 2014 -0700
+
+ .travis.yml: Test "make dist" too.
+
+commit fdc87f3b2ea37b58a4a9ae6c35083f544909fe3c
+Merge: 7412b83 e1911f7
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 08:05:51 2014 -0400
+
+ Merge pull request #85 from joshtriplett/stdcall
+
+ stdcall support on Linux
+
+commit e1911f78df113ca58738b66089a070d4cf747de7
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 03:25:53 2014 -0700
+
+ Add support for stdcall, thiscall, and fastcall on non-Windows x86-32
+
+ Linux supports the stdcall calling convention, either via functions
+ explicitly declared with the stdcall attribute, or via code compiled
+ with -mrtd which effectively makes stdcall the default.
+
+ This introduces FFI_STDCALL, FFI_THISCALL, and FFI_FASTCALL on
+ non-Windows x86-32 platforms, as non-default calling conventions.
+
+commit 7412b838d543aae4fa925862bd5702d3dacbc29a
+Merge: c0cc5fd 9531d05
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 07:58:16 2014 -0400
+
+ Merge pull request #90 from joshtriplett/win32-unifdef
+
+ prep_cif.c: Remove unnecessary ifdef for X86_WIN32
+
+commit c0cc5fdaa237b67e86f22d2f6e13f3b42d9aae33
+Merge: 98b5296 b3a5da0
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 07:57:59 2014 -0400
+
+ Merge pull request #89 from joshtriplett/travis32
+
+ .travis.yml: Test on both 32-bit and 64-bit
+
+commit 9531d05f64c2a674e0197158ffad68d69f177bd0
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 01:50:02 2014 -0700
+
+ prep_cif.c: Remove unnecessary ifdef for X86_WIN32
+
+ ffi_prep_cif_core had a special case for X86_WIN32, checking for
+ FFI_THISCALL in addition to the FFI_FIRST_ABI-to-FFI_LAST_ABI range
+ before returning FFI_BAD_ABI. However, on X86_WIN32, FFI_THISCALL
+ already falls in that range, making the special case unnecessary.
+ Remove it.
+
+commit b3a5da068abd2f2983d9e67adbf41b0e0f34e37f
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sat Mar 15 23:27:56 2014 -0700
+
+ .travis.yml: Test on both 32-bit and 64-bit
+
+commit 98b52960485a261399f081915f36063de3854a5f
+Merge: 134ce4c f6dd184
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 07:51:33 2014 -0400
+
+ Merge pull request #94 from joshtriplett/esp-extra-stackery-perception
+
+ ChangeLog: Document testsuite changes to remove fragile stack pointer checks
+
+commit f6dd1845434dd53e22129becdfa092c082df307c
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 04:49:36 2014 -0700
+
+ ChangeLog: Document testsuite changes to remove fragile stack pointer checks
+
+commit 134ce4c0266bf994f07518fc534de53f1d3c8de8
+Merge: 2680e9e 9c27932
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 07:47:17 2014 -0400
+
+ Merge pull request #91 from joshtriplett/esp-extra-stackery-perception
+
+ testsuite: Remove fragile stack pointer checks
+
+commit 9c279328ee12fc869adff63ca81f1230977bd42b
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 02:31:19 2014 -0700
+
+ testsuite: Remove fragile stack pointer checks
+
+ testsuite/libffi.call/closure_stdcall.c and
+ testsuite/libffi.call/closure_thiscall.c include inline assembly to save
+ the stack pointer before and after the call, and compare the values.
+ However, compilers can and do leave the stack in different states for
+ these two pieces of inline assembly, such as by saving a temporary value
+ on the stack across the call; observed with gcc -Os, and verified as
+ spurious through careful inspection of disassembly.
+
+commit 2680e9ea9b4c87ea8042a61e551bd667493d4bd3
+Merge: 071eab3 82f8cb2
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 07:44:08 2014 -0400
+
+ Merge pull request #88 from joshtriplett/such-precision-many-fail-wow
+
+ testsuite/libffi.call/many.c: Avoid spurious failure due to excess precision
+
+commit 82f8cb24a1d976db35ae31a4b86cec8926da327d
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 04:27:32 2014 -0700
+
+ ChangeLog: Document many.c and many_win32.c changes to avoid spurious failures
+
+commit 88d562a8b5912e99306063fe3bc289bab6ca6ebe
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sat Mar 15 22:08:19 2014 -0700
+
+ testsuite/libffi.call/many_win32.c: Avoid spurious failure due to excess precision
+
+ The test case testsuite/libffi.call/many_win32.c can spuriously fail due
+ to excess floating-point precision. Instrumenting it with some printf
+ calls shows differences well above FLT_EPSILON. (Note when
+ instrumenting it that multiple computations of the difference, such as
+ one in a print and another in the conditional, may produce different
+ results.)
+
+ Rather than complicating the test suite with architecture-specific flags
+ to avoid excess precision, just simplify the floating-point computation
+ to avoid a dependency on potential excess precision.
+
+commit c00a49ecd165b2d06c1c9b249d212dc843fa116f
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sat Mar 15 22:08:19 2014 -0700
+
+ testsuite/libffi.call/many.c: Avoid spurious failure due to excess precision
+
+ The test case testsuite/libffi.call/many.c can spuriously fail due to
+ excess floating-point precision. Instrumenting it with some printf
+ calls shows differences well above FLT_EPSILON. (Note when
+ instrumenting it that multiple computations of the difference, such as
+ one in a print and another in the conditional, may produce different
+ results.)
+
+ Rather than complicating the test suite with architecture-specific flags
+ to avoid excess precision, just simplify the floating-point computation
+ to avoid a dependency on potential excess precision.
+
+commit 071eab32a7f9fbbef46c0d8f37d9985bc9cceb37
+Merge: 2228c7a 2f44952
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 07:36:52 2014 -0400
+
+ Merge pull request #92 from joshtriplett/autogen
+
+ Re-add libtool-ldflags
+
+commit 2f44952c95765c1486fad66f57235f8d459a9748
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sun Mar 16 04:35:12 2014 -0700
+
+ Re-add libtool-ldflags
+
+commit 2228c7ab190f3c529b9018495467b841fa21cba2
+Merge: 76d19d0 35634db
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 16 07:25:18 2014 -0400
+
+ Merge pull request #87 from joshtriplett/autogen
+
+ Remove autogenerated files from the repository
+
+commit 35634dbceaac0a1544f7385addc01d21ef1ef6a8
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Sat Mar 15 18:11:16 2014 -0700
+
+ Remove autogenerated files from the repository
+
+ Add an autogen.sh to regenerate them.
+
+commit 76d19d004e36e99d261ee78261e2f52cea5e4ab1
+Merge: c86d9b6 a1a6f71
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Mar 14 16:54:31 2014 -0400
+
+ Ensure the linker supports @unwind sections in libffi.
+
+commit c86d9b6cc6e16ee262844a33b40441374400758c
+Merge: 4efb7db f8cdf11
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Mar 14 16:51:20 2014 -0400
+
+ Fix merge
+
+commit 4efb7dbfd9427c478a948cd0d464210123db8de8
+Merge: 634a475 18eb81d
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Mar 14 16:47:57 2014 -0400
+
+ Merge pull request #81 from rvandermeulen/bug-756740
+
+ Allow building for mipsel with Android NDK r8.
+
+commit a1a6f71bfe4199293043b2e4cfb4c8d3cb1112f9
+Author: Ryan VanderMeulen <ryanvm@gmail.com>
+Date: Mon Mar 10 15:12:47 2014 -0400
+
+ Remove stray hunk that shouldn't have been included in this patch.
+
+commit f8cdf11467181f2a9a6b7e748167569aa58e3a81
+Author: Ryan VanderMeulen <ryanvm@gmail.com>
+Date: Mon Mar 10 15:04:58 2014 -0400
+
+ Replace double quotes with single quotes in Makefile.in to improve compatibility between some versions of MSYS and gmake. From Mozilla bug 943728.
+ https://bugzilla.mozilla.org/show_bug.cgi?id=943728
+
+commit dfa3738732e1bc3a7f4130395ae4bab55fcebb99
+Author: Ryan VanderMeulen <ryanvm@gmail.com>
+Date: Mon Mar 10 14:53:48 2014 -0400
+
+ Ensure the linker supports @unwind sections in libffi. From Mozilla bug 756740.
+ https://bugzilla.mozilla.org/show_bug.cgi?id=778414
+
+ Also tracked as issue #42.
+ https://github.com/atgreen/libffi/issues/42
+
+commit 18eb81d032f29d645d0498ba92bddfd651f009ae
+Author: Ryan VanderMeulen <ryanvm@gmail.com>
+Date: Mon Mar 10 14:43:37 2014 -0400
+
+ Allow building for mipsel with Android NDK r8. From Mozilla bug 756740.
+ https://bugzilla.mozilla.org/show_bug.cgi?id=756740
+
+commit 2349fec9a818fb52fd2f294bcbc7b3156cd113de
+Author: Daiki Ueno <ueno@gnu.org>
+Date: Wed Mar 5 17:53:02 2014 +0900
+
+ Fix typo in doc
+
+commit 634a475eaf1bee31c09f7d519e31c13b64cd24df
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 1 18:37:29 2014 -0500
+
+ Update Makefile for new darwin scripts
+
+commit c7b67e874bb89859f9a07d1cf9606052b6c0dcc1
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 1 18:34:18 2014 -0500
+
+ Add README note
+
+commit a04e30ba3dc303133d459c1ac273ceefe4d49b32
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 17:20:59 2014 -0500
+
+ Add missing -DFFI_DEBUG flag
+
+commit 934dc1b5c8d6a9e727bedc72342831eb7d62c35f
+Merge: 11d7aa9 67fbef3
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 01:10:17 2014 -0500
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+commit 11d7aa9d7a4bbe642944edc0f07cf96db9b270b6
+Merge: b40aeda 3b44d41
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 01:06:48 2014 -0500
+
+ Merge pull request #46 from makotokato/android-clang
+
+ Fix build failure when using clang for Android
+
+commit 67fbef3b56ff0ef88f9b1a7fe48cb77222fa6cec
+Merge: b40aeda 3b44d41
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 01:06:48 2014 -0500
+
+ Merge pull request #46 from makotokato/android-clang
+
+ Fix build failure when using clang for Android
+
+commit b40aeda31a74d95a37c723b6243aabac466e67c4
+Merge: 20698ab 53ceaf1
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 01:01:29 2014 -0500
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+commit 53ceaf14c5eeb16ba09745f0ca87cca367d41a90
+Merge: 860fe66 cc9b518
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 01:01:02 2014 -0500
+
+ Merge pull request #40 from wojdyr/master
+
+ Correct the -L flag in libffi.pc.in
+
+commit 20698abc6a00092fd7fd3e434a3a29dc0f048f1e
+Merge: 64bd069 1a0b01e
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 00:56:27 2014 -0500
+
+ Merge pull request #66 from ppizarro/master
+
+ BlackFin fixes - Fatal error when calling a function defined in a shared library from within the function called by FFI
+
+commit 860fe6646f5ae603e99a8d1d722ddddba8b75769
+Merge: 64bd069 1a0b01e
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 00:56:27 2014 -0500
+
+ Merge pull request #66 from ppizarro/master
+
+ BlackFin fixes - Fatal error when calling a function defined in a shared library from within the function called by FFI
+
+commit 64bd06990a7accf72271516a2110b86cdccd8df4
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 00:52:56 2014 -0500
+
+ Add ChangeLog entry for Josh's change
+
+commit edf29c5169b06fcfc241445e152e325bc3c50e0e
+Merge: 33c9954 3998d26
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 00:50:25 2014 -0500
+
+ Merge pull request #75 from joshtriplett/longdouble
+
+ Fix build error on x86 without distinct long double
+
+commit 33c9954f2eec539011a0f93270aaf013318837ae
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 00:38:41 2014 -0500
+
+ Rebuilt with new libtool
+
+commit 926b6989fbd08488b9105943293353d45ac527e0
+Merge: 5a88c85 cc82051
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 00:26:57 2014 -0500
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+ Conflicts:
+ ChangeLog
+
+commit 5a88c85fde304052bed1581ed0b6452ac2c68838
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 00:23:04 2014 -0500
+
+ Fix spelling errors
+
+commit cc82051c7e80cea772c4b72da026eb7e68d598fc
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 00:23:04 2014 -0500
+
+ Fix spelling errors
+
+commit 001aaf4b1b56349596bb6f6b5c1613dcbbd84ea8
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 00:20:17 2014 -0500
+
+ When no VFP arguments are present the IP register is used
+ uninitialized. Initialize it to the value of FP.
+
+ This fixes a number of testsuite failures when configured for
+ armv7l-unknown-linux-gnueabihf
+
+commit 49f7729c3ce697c12408c42ccb29cdf4eb66bb85
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 28 00:17:16 2014 -0500
+
+ aarch64 fix
+
+commit 447483d51c6aa9df7116f346a73fc1cf795f4c2b
+Merge: 51377bd b4df9cf
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Feb 27 15:42:41 2014 -0500
+
+ Fix ChangeLog merge
+
+commit 3998d2604b5c0d45a098ff3119a9fd9710ef429d
+Author: Josh Triplett <josh@joshtriplett.org>
+Date: Mon Feb 17 11:20:33 2014 -0800
+
+ Fix build error on x86 without distinct long double
+
+ src/x86/ffi64.c: In function 'classify_argument':
+ src/x86/ffi64.c:205:5: error: duplicate case value
+ case FFI_TYPE_LONGDOUBLE:
+ ^
+ src/x86/ffi64.c:202:5: error: previously used here
+ case FFI_TYPE_DOUBLE:
+ ^
+
+commit 51377bda9aed0b2c1309c818460cab9d9ab3d46e
+Merge: f08da54 40927bd
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 15 08:06:29 2014 -0500
+
+ Merge pull request #72 from heiher/devel
+
+ MIPS N32: Fix call floating point va function
+
+commit f08da5465463e60a28f5e921f23ebf2ba984c148
+Merge: 3dc3f32 fa5f25c
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 15 08:06:11 2014 -0500
+
+ Merge pull request #68 from zeldin/master
+
+ Linux/ppc64: Remove assumption on contents of r11 in closure
+
+commit 40927bd3e1e7c6007025ba10854fd8a0664e47df
+Author: Heiher <r@hev.cc>
+Date: Tue Jan 21 23:18:27 2014 +0800
+
+ Fix call floating point va function
+
+ I'm not sure floating-point arguments in GPR or FPR before calling
+ variable number arguments function. so, load all arguments to GPR and
+ FPR.
+
+commit b4df9cf9cc4a9a9401a53fd6bea1f3c2c283b97b
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Wed Feb 5 14:22:52 2014 -0500
+
+ AArch64: Fix void fall-through case when assertions are enabled
+
+commit f466aad0d91a117e42571d1d6fb434fa0433c930
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Tue Jan 21 16:38:31 2014 -0500
+
+ AArch64: Fix missing semicolons when assertions are enabled
+
+commit 7ea677733bd98917241852b8901a6b7580728895
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 30 20:58:31 2013 -0500
+
+ Remove build-ios from Makefile
+
+ Conflicts:
+ ChangeLog
+
+commit 6ae046cc59c12b2cd40158d6bcb96f4a59886159
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 30 21:06:51 2013 -0500
+
+ Mention Aarch64 on iOS
+
+commit bfc06b3fdb32abe90ce0749aedfec649df85a7ef
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Mon Dec 30 17:36:39 2013 -0500
+
+ Update ChangeLog
+
+commit 0a0f12ce1f7be81006b08a3c81a636926d283a9b
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Thu Jan 9 13:50:17 2014 -0500
+
+ AArch64: Remove duplicitous element_count call.
+
+ This inhibits an analyzer warning by Clang.
+
+commit 4330fdcd92e67c816288d64ab230237065768206
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Thu Jan 9 13:53:30 2014 -0500
+
+ Darwin/aarch64: Respect iOS ABI re: stack argument alignment
+
+commit 0a333d6c3973935d4fe02aae76b10e39d3c88e07
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Thu Jan 9 14:03:29 2014 -0500
+
+ Darwin/aarch64: Fix size_t assumptions
+
+commit 2c18e3c76aad1b426617db05a4384e7c3a920176
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Mon Dec 30 16:14:02 2013 -0500
+
+ Darwin/aarch64: Fix "shadows declaration" warnings
+
+commit 1b8a8e20e344f3c55495ab6eb46bd14e843d4b3e
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Thu Jan 9 13:55:21 2014 -0500
+
+ Darwin/aarch64: Use Clang cache invalidation builtin
+
+commit 6030cdcae776f8fb5876a53168f7d1e75d28a242
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Mon Dec 30 15:45:51 2013 -0500
+
+ Darwin/aarch64: Account for long double being equal to double
+
+commit 5658b0892683d2e24e4d5842978c184a7ad33858
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Mon Dec 30 16:33:47 2013 -0500
+
+ Darwin/aarch64: Use CNAME, restrict .size like ARM
+
+commit 07175780802acec5dc49fdedd6d20a62409a6707
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Mon Dec 30 17:48:22 2013 -0500
+
+ Darwin/aarch64: Fix invalid reference in assembly
+
+commit 9da28b44277fea3aeb827c35dd63d609d2524a8b
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Mon Dec 30 16:23:21 2013 -0500
+
+ Darwin/x86_64: Fix 64-bit type shortening warnings
+
+commit 821d398f08bd1d540a5b235507812ffeee49b580
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Thu Jan 9 13:15:06 2014 -0500
+
+ Darwin: Merge build scripts, redo project, incl. arm64
+
+commit 6eff9ff9e72463b9783be2514f944b6f05692054
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Mon Dec 30 17:48:10 2013 -0500
+
+ Darwin/iOS: Improve unified syntax use for LLVM
+
+commit ba0ea99c82aadd5957386a031e3122011bd36d52
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Mon Dec 30 15:27:44 2013 -0500
+
+ Fix dlmalloc warnings due to set_segment_flags, sizeof(size_t)
+
+commit 994be3a5c1d0d17b19103396103e128517fd62f9
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Mon Dec 30 15:27:14 2013 -0500
+
+ Darwin/iOS: Fix mis-typing of vfp_reg_free
+
+commit a8e0a835ab1f62d03ad6391760e3e8b7732d24f8
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Mon Dec 30 15:26:20 2013 -0500
+
+ Darwin/ARM: Assert on NULL dereference
+
+ This inhibits an analyzer warning by Clang on all platforms.
+
+commit 13675341581c489ed9df8ba390c8e08a732decb2
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Thu Jan 9 13:42:08 2014 -0500
+
+ Darwin/i386: Inhibit Clang previous prototype warnings
+
+commit 66469c381e2e2cc96e7d409266dea0ffe177eeca
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Thu Jan 9 13:41:45 2014 -0500
+
+ Darwin/ARM: Inhibit Clang previous prototype warnings
+
+commit 5bfe62a00d2d659eec9f19b39802b6e69844fc27
+Author: Zachary Waldowski <zach@waldowski.me>
+Date: Thu Jan 9 13:41:27 2014 -0500
+
+ Darwin/AArch64: Inhibit Clang previous prototype warnings
+
+commit fa5f25c20f76a6ef5e950a7ccbce826672c8a620
+Author: Marcus Comstedt <marcus@mc.pp.se>
+Date: Sat Jan 4 19:00:08 2014 +0100
+
+ Linux/ppc64: Remove assumption on contents of r11 in closure
+
+commit 1a0b01e171e9c750437cef2f18917f5a6e32c498
+Author: Paulo Pizarro <paulo.pizarro@gmail.com>
+Date: Thu Jan 2 16:17:59 2014 -0200
+
+ When the function called by the ffi called a function defined in a shared library generate a fatal error
+ The correction was to take into consideration the GOT.
+
+commit 3dc3f32c35db5ab995a835225f6815369735ceb7
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Dec 5 16:23:25 2013 -0500
+
+ Undo iOS ARM64 changes.
+
+commit 356b2cbc304bfe5bdc28b8d1c68d1ff084e9ec37
+Merge: 484a758 07345a3
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 30 22:38:13 2013 -0500
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+commit 484a7584260e2fbb399ce90083046834271bf9ff
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 30 21:06:51 2013 -0500
+
+ Mention Aarch64 on iOS
+
+commit 07345a30ec0a2fa45a7c363d301f57723690cfa0
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 30 21:06:51 2013 -0500
+
+ Mention Aarch64 on iOS
+
+commit d4b931c1b872378c35f12ddbb9a6d55e7f17c65e
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 30 20:58:31 2013 -0500
+
+ Remove build-ios from Makefile
+
+commit dfbf236d70fc1ec68e6ff193584a154353508e2f
+Merge: 852ac3b bb9740e
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 30 20:54:54 2013 -0500
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+ Add ChangeLog entry.
+
+commit bb9740e545205f93a525c77aa6d1cbf4ca9371f3
+Merge: ac75368 4d701e0
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 30 17:54:39 2013 -0800
+
+ Merge pull request #60 from zwaldowski/ios-redo
+
+ Mac/iOS support, including aarch64 port
+
+commit 4d701e03faa475a5eb3b54b90046114a1e27b813
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 13:25:27 2013 -0500
+
+ Darwin: Properly export headers from Xcode project
+
+commit 022f12eb9ad2264e838fa5fb453733f5177888f4
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 12:21:38 2013 -0500
+
+ Darwin: Freshen gen scripts, remove old build-ios.sh
+
+commit e820fe2025d7ad3df7584407946dfaad2af69599
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 12:03:51 2013 -0500
+
+ Darwin/iOS: Include x86_64+aarch64 pieces in library
+
+commit 0278284e470ec91db7cdc15ac3dcd64683305848
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 03:03:37 2013 -0500
+
+ Darwin/aarch64: size_t assumptions
+
+commit 9775446b6441c91cd9059215c106aa3bcf949767
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 02:39:34 2013 -0500
+
+ Darwin/aarch64: Fix “shadows declaration” warnings
+
+commit 4260badc37705d3618e774dfe61184ac709881c1
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 02:08:14 2013 -0500
+
+ Darwin/aarch64: Use Clang cache invalidation builtin
+
+commit 9fa7998d5f9250908cbf12a671479852ebadf9d1
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 02:07:48 2013 -0500
+
+ Darwin/aarch64: Inhibit Xcode warning
+
+commit 0e832048a93830575b0976406444e134e649a4f7
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 02:07:34 2013 -0500
+
+ Darwin/aarch64: double == long double
+
+commit 602dc22d76931092610234cf063f9f1b8dbc1a51
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 02:06:00 2013 -0500
+
+ Darwin/iOS prep script: try and compile for arm64
+
+commit b513dfe79de4725e8a717325a9e3b5b9f69f63dc
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 02:05:22 2013 -0500
+
+ Darwin/aarch64: Restrict .size to ELF like arm32.
+
+commit bc978099bf2812de755c076b67ef9c2547607572
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 02:04:57 2013 -0500
+
+ Darwin/aarch64: Potentially(?) fix compile error
+
+commit d6bb9314467c6e0683156559d23ca341c43fa3c8
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 02:04:22 2013 -0500
+
+ Darwin/aarch64: Use CNAME refs
+
+commit 33c46ce5680eea28d3437c8771ec1d137e226b45
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 04:13:42 2013 -0500
+
+ Darwin/Mac: Fix 64/32 shortening warnings
+
+commit 0612081e6c161d9d820742f995975d35da2adbc2
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 03:03:00 2013 -0500
+
+ Darwin: Misc size_t warnings
+
+commit 6a6247d179ec3859311c2d8775841b884f309f66
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 02:55:48 2013 -0500
+
+ Darwin: Fix dlmalloc warnings due to sizeof(size_t)
+
+commit 4d60d9e1e32de6166ffd63bbe9ce54cf961c78fc
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 04:09:30 2013 -0500
+
+ Darwin: Rebuild Xcode project
+
+commit cb719a5c1c2eb391d6a5f5e02484ba4aa990a51b
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 04:09:18 2013 -0500
+
+ Darwin/iOS: Fix LLVM 3.3 warning re: memcpy.
+
+commit 21bde92c9abb378f9c456a9d95e6f9b99ef8c920
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 03:43:42 2013 -0500
+
+ Darwin: Clean up, modernize generator scripts
+
+commit fd54eab74cef7891e4acaaafb71e783142ecb69e
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Sat Nov 30 03:38:02 2013 -0500
+
+ Darwin/Mac: Also exclude OS X generated source
+
+commit 953b6f14c655141f9e7d82550a312c3eeb961091
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Tue Apr 24 11:16:20 2012 -0400
+
+ Darwin/iOS: More unified syntax support w/ Clang.
+
+ Signed-off-by: Zachary Waldowski <zwaldowski@gmail.com>
+
+commit c713a55379481c339877f2e0003d97cb8d9ed80e
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Tue Apr 24 10:25:29 2012 -0400
+
+ Darwin/iOS: Simplify RETLDM arguments for LLVM 3.1
+
+ Signed-off-by: Zachary Waldowski <zwaldowski@gmail.com>
+
+commit 16ba1b80028db5cb71cf86e5f79f5e48317f83c8
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Wed Apr 11 23:26:04 2012 -0400
+
+ Darwin: Silence Clang warnings.
+
+commit 852ac3bd302d6ed97b1ef65f4cbed69c258a48df
+Merge: ab79d6e ac75368
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 21 21:25:44 2013 -0500
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+ Conflicts:
+ ChangeLog
+
+commit ab79d6e21992dd86139ba07530ff888833b78a04
+Author: Alan Modra <amodra@gmail.com>
+Date: Thu Nov 21 06:12:35 2013 -0500
+
+ This separates the 32-bit sysv/linux/bsd code from the 64-bit linux
+ code, and makes it possible to link code compiled with different
+ options to those used to compile libffi. For example, a
+ -mlong-double-128 libffi can be used with -mlong-double-64 code.
+
+ Using the return value area as a place to pass parameters wasn't such
+ a good idea, causing a failure of cls_ulonglong.c. I didn't see this
+ when running the mainline gcc libffi testsuite because that version of
+ the test is inferior to the upstreamm libffi test.
+
+ Using NUM_FPR_ARG_REGISTERS rather than NUM_FPR_ARG_REGISTERS64 meant
+ that a parameter save area could be allocated before it was strictly
+ necessary. Wrong but harmless. Found when splitting apart ffi.c
+ into 32-bit and 64-bit support.
+
+commit ac7536889334d4be50709006d7e23536364d7891
+Author: Alan Modra <amodra@gmail.com>
+Date: Thu Nov 21 06:12:35 2013 -0500
+
+ This separates the 32-bit sysv/linux/bsd code from the 64-bit linux
+ code, and makes it possible to link code compiled with different
+ options to those used to compile libffi. For example, a
+ -mlong-double-128 libffi can be used with -mlong-double-64 code.
+
+ Using the return value area as a place to pass parameters wasn't such
+ a good idea, causing a failure of cls_ulonglong.c. I didn't see this
+ when running the mainline gcc libffi testsuite because that version of
+ the test is inferior to the upstreamm libffi test.
+
+ Using NUM_FPR_ARG_REGISTERS rather than NUM_FPR_ARG_REGISTERS64 meant
+ that a parameter save area could be allocated before it was strictly
+ necessary. Wrong but harmless. Found when splitting apart ffi.c
+ into 32-bit and 64-bit support.
+
+commit 69df91cfb4fa6bcb644350a80bff970f27478a6a
+Merge: 2f45082 aa1f62c
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 06:34:04 2013 -0800
+
+ Merge pull request #59 from iains/powerpc-darwin-unwind-fix
+
+ Fix PowerPC Darwin FDE encodings to use pcrel correctly. Modernise the picbase labels.
+
+commit aa1f62c0a093c30325dff1d4d2b6b4b22eb96929
+Author: Iain Sandoe <iain@codesourcery.com>
+Date: Mon Nov 18 13:11:56 2013 +0000
+
+ Fix PowerPC Darwin FDE encodings to use pcrel correctly. Modernise the picbase labels.
+
+commit 2f450822a8698ba88441c56d152c7dc8924b127f
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 18 06:52:29 2013 -0500
+
+ Clean up code to appease modern GCC compiler.
+
+commit 16d56c51aded374730920a4acde76ff3d2860ae1
+Author: Alan Modra <amodra@gmail.com>
+Date: Mon Nov 18 06:36:03 2013 -0500
+
+ An #endif in the wrong place would cause compile failure on powerpcle.
+ Using bl instead of b doesn't cause runtime failures as you might think,
+ but does mess the processor branch prediction.
+
+commit 34f878a5ef28663f6b1d7fd26fb099429ea1579e
+Merge: 83f65b6 1fd0457
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 16 06:57:54 2013 -0500
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+ Conflicts:
+ ChangeLog
+ src/powerpc/ffi.c
+
+commit 83f65b63d9764a9cc7688fc5cda5ee2bd23faf54
+Author: Alan Modra <amodra@gmail.com>
+Date: Sat Nov 16 06:53:50 2013 -0500
+
+ Finally, this adds _CALL_ELF == 2 support. ELFv1 objects can't be
+ linked with ELFv2 objects, so this is one case where preprocessor
+ tests in ffi.c are fine. Also, there is no need to define a new
+ FFI_ELFv2 or somesuch value in enum ffi_abi. FFI_LINUX64 will happily
+ serve both ABIs.
+
+commit 1fd045784cac874b5d76b7fa931f67209a8280d3
+Author: Alan Modra <amodra@gmail.com>
+Date: Sat Nov 16 06:53:50 2013 -0500
+
+ Finally, this adds _CALL_ELF == 2 support. ELFv1 objects can't be
+ linked with ELFv2 objects, so this is one case where preprocessor
+ tests in ffi.c are fine. Also, there is no need to define a new
+ FFI_ELFv2 or somesuch value in enum ffi_abi. FFI_LINUX64 will happily
+ serve both ABIs.
+
+commit 362851379a49ce07d3e36e82c4e5c7b6cc16a352
+Author: Alan Modra <amodra@gmail.com>
+Date: Sat Nov 16 06:52:43 2013 -0500
+
+ Andreas' 2013-02-08 change reverted some breakage for struct return
+ values from 2011-11-12, but in so doing reintroduced string
+ instructions to sysv.S that are not supported on all powerpc variants.
+ This patch properly copies the bounce buffer to destination in C code
+ rather than in asm.
+
+ I have tested this on powerpc64-linux, powerpc-linux and
+ powerpc-freebsd. Well, the last on powerpc-linux by lying to
+ configure with
+
+ CC="gcc -m32 -msvr4-struct-return -mlong-double-64" \
+ CXX="g++ -m32 -msvr4-struct-return -mlong-double-64" \
+ /src/libffi-current/configure --build=powerpc-freebsd
+
+ and then
+
+ make && make CC="gcc -m32" CXX="g++ -m32" \
+ RUNTESTFLAGS=--target_board=unix/-m32/-msvr4-struct-return/-mlong-double-64\
+ check
+
+commit 1c06515d927d9de1582438d4eb5953890e79c5c7
+Author: Alan Modra <amodra@gmail.com>
+Date: Sat Nov 16 06:41:36 2013 -0500
+
+ The powerpc64 ABIs align structs passed by value, a fact ignored by
+ gcc for quite some time. Since gcc now does the correct alignment,
+ libffi needs to follow suit. This ought to be made selectable via
+ a new abi value, and the #ifdefs removed from ffi.c along with many
+ other #ifdefs present there and in assembly. I'll do that with a
+ followup patch sometime.
+
+ This is a revised version of
+ https://sourceware.org/ml/libffi-discuss/2013/msg00162.html
+
+commit a97cf1fae575d8bfd5259c5c422025ad43911326
+Author: Alan Modra <amodra@gmail.com>
+Date: Sat Nov 16 06:40:13 2013 -0500
+
+ This patch prepares for ELFv2, where sizes of these areas change. It
+ also makes some minor changes to improve code efficiency.
+
+commit 164283f4ac5972ce2ab5e015cc2ab1014c23276c
+Author: Alan Modra <amodra@gmail.com>
+Date: Sat Nov 16 06:38:55 2013 -0500
+
+ The powerpc64 support opted to pass floating point values both in the
+ fpr area and the parameter save area, necessary when the backend
+ doesn't know if a function argument corresponds to the ellipsis
+ arguments of a variadic function. This patch adds powerpc support for
+ variadic functions, and changes the code to only pass fp in the ABI
+ mandated area. ELFv2 needs this change since the parameter save area
+ may not exist there.
+
+ This also fixes two faulty tests that used a non-variadic function
+ cast to call a variadic function, and spuriously reasoned that this is
+ somehow necessary for static functions..
+
+commit 31257b3189f81a199bc2902c22bc5f2d7c54ccde
+Author: Andrew Haley <aph@redhat.com>
+Date: Sat Nov 16 06:35:51 2013 -0500
+
+ Fix sample closure code
+
+commit db0ace3a38496af73eae3df02ef353736d16909f
+Author: Andrew Haley <aph@redhat.com>
+Date: Sat Nov 16 06:29:25 2013 -0500
+
+ Fix broken test cases
+
+commit de10f5039ed7a53382ddcc95c368d03e535edb98
+Merge: 58c2577 f3657da
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Nov 14 10:56:29 2013 -0500
+
+ Merge branch 'master' of https://github.com/bivab/libffi
+
+ Conflicts:
+ ChangeLog
+
+commit f3657da278dd63afcdd8762894a9bdaea8ef028a
+Author: David Schneider <david.schneider@bivab.de>
+Date: Thu Nov 14 13:02:16 2013 +0100
+
+ update Changelog
+
+commit 58c2577a3ff80e7416ef0434769e2af23365719c
+Author: Alan Modra <amodra@gmail.com>
+Date: Wed Nov 13 16:55:36 2013 -0500
+
+ This enshrines the current testsuite practice of using ffi_arg for
+ returned values. It would be reasonable and logical to use the actual
+ return argument type as passed to ffi_prep_cif, but this would mean
+ changing a large number of tests that use ffi_arg and all backends
+ that write results to an ffi_arg.
+
+commit 8af42f9944f7ed72c81ae360aac6a84dc11f89dc
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 13 16:40:28 2013 -0500
+
+ Respect HAVE_ALLOCA_H
+
+commit cdf405d574f479b782454516366bd4f4b9b3415e
+Author: David Schneider <david.schneider@bivab.de>
+Date: Wed Nov 13 15:50:21 2013 +0100
+
+ add a testcase for the double/float issue on ARMHF
+
+commit 77f823e31ffb557a466b24f7fba845fbf7831798
+Author: David Schneider <david.schneider@bivab.de>
+Date: Wed Nov 13 14:26:57 2013 +0100
+
+ stop trying to assing vfp regs once we are done with the registers
+
+commit 37067ec5036f2a6ed7a4799f83f8f53160460344
+Author: David Schneider <david.schneider@bivab.de>
+Date: Tue Nov 12 19:49:01 2013 +0100
+
+ mark all vfp registers as used when done.
+
+ To avoid assigning registers the would fit, once arguments have been on
+ the stack, we mark all registers as used once we do not find a free
+ register for the first time.
+
+commit 2f5b7ce545473a7f6e41193edc29407cbebe82d5
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 9 06:16:32 2013 -0500
+
+ UltraSPARC IIi fix. Update README and build configury.
+
+commit becd754434173032f426d22ffcbfe24f55b3c137
+Author: Mark Kettenis <kettenis@gnu.org>
+Date: Wed Nov 6 06:43:49 2013 -0500
+
+ Align the stack pointer to 16-bytes.
+
+commit 05c31093409f7b3e6d795fac21d2c954313d8162
+Author: Konstantin Belousov <kib@freebsd.org>
+Date: Wed Nov 6 06:40:58 2013 -0500
+
+ Mark executable as not requiring executable stack.
+
+commit cf6bf9818e8394cfcdb07a40c6a5e2ee6b01d333
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 2 17:23:59 2013 -0400
+
+ Fix up docs
+
+commit 02177176854d16fc0f1a5958aa34da2f306630ee
+Merge: c242217 c265b4c
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 2 17:11:22 2013 -0400
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+commit c2422174b3edc0de0b148dfd6b67087bb881c4a6
+Merge: f4b843f d918d47
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 2 14:08:23 2013 -0700
+
+ Merge pull request #45 from foss-for-synopsys-dwc-arc-processors/arc_support
+
+ arc: Fix build error
+
+commit c265b4cacb9130f042699a85de9c7242b3f49cc3
+Merge: f4b843f d918d47
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 2 14:08:23 2013 -0700
+
+ Merge pull request #45 from foss-for-synopsys-dwc-arc-processors/arc_support
+
+ arc: Fix build error
+
+commit f4b843f83710ac378c48abd87fe66bb519d30d2e
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 2 17:01:15 2013 -0400
+
+ Don't align stack for win32
+
+commit f3cd39345713db8e414cf642b6cb65a4cfe6018c
+Merge: 666f3e7 6aa1590
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 2 13:17:57 2013 -0700
+
+ Merge pull request #51 from vbudovski/for_upstream
+
+ Don't use 16 byte aligned stack for WIN32
+
+commit 666f3e71b56d92c49fcd2d7f349b8f8ebca0f8a3
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Oct 26 09:12:42 2013 -0400
+
+ Add more credits to README. Tidy up.
+
+commit 73ada14e756bad97fad0e6915a821a3c7e079f81
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Oct 26 09:09:45 2013 -0400
+
+ Update README
+
+commit d3372c54ce7117e80d389ba875dc5b6b2213c71e
+Author: Mark H Weaver <mhw@netris.org>
+Date: Sat Oct 26 08:30:06 2013 -0400
+
+ Fix N32 ABI issue for MIPS.
+
+commit d6716aba8118eb0513885cfe557bedebb7016e8b
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 15 15:42:49 2013 -0400
+
+ Update travis-ci build dependencies to include texinfo
+
+commit 16b93a211bcfbe4bd0efdcf94de225a71aa0ee02
+Author: Sandra Loosemore <sandra@codesourcery.com>
+Date: Tue Oct 15 15:33:59 2013 -0400
+
+ Add nios2 port.
+
+commit 2f5626ce02fce8267ab48ceb6d7d0ed7d672a75e
+Author: Sandra Loosemore <sandra@codesourcery.com>
+Date: Tue Oct 15 15:32:16 2013 -0400
+
+ Fix testsuite bug
+
+commit f64e4a865557e440774436b4c2b2fd7374290e97
+Author: Marcus Shawcroft <marcus.shawcroft@arm.com>
+Date: Tue Oct 15 15:20:14 2013 -0400
+
+ Fix many.c testcase for Aarch64
+
+commit 128cd1d2f358f26d9fa75a27cf2b30356f5dd903
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 8 06:45:51 2013 -0400
+
+ Fix spelling errors
+
+commit ff06269d707cafbfef2a88afb07a79c9d1480c5f
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 8 06:32:18 2013 -0400
+
+ Update README for M88K and VAX
+
+commit d2fcbcdfbea750d1f6a9f493e2e6c4d5ffa71b34
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 8 06:27:46 2013 -0400
+
+ Add m88k and VAX support. Update some configury bits.
+
+commit 6aa15900accc0a648cdebf11ec11d11697ebfffd
+Author: Vitaly Budovski <vbudovski@gmail.com>
+Date: Thu Sep 5 12:05:06 2013 +1000
+
+ Don't use 16 byte aligned stack for WIN32
+
+ This fixes a crash when accessing __stdcall functions in Python ctypes.
+
+commit 3b44d41156149af8da2a58825fefdfa23274ae7a
+Author: Makoto Kato <m_kato@ga2.so-net.ne.jp>
+Date: Wed Jul 10 15:34:53 2013 +0900
+
+ Fix build failure when using clang for Android
+
+ clang for Android generates __gnu_linux__ define, but gcc for Android doesn't. So we should add check it for Android
+
+commit d918d47809c174d62283306b282749f8db93661f
+Author: Mischa Jonker <mjonker@synopsys.com>
+Date: Mon Jul 8 15:51:36 2013 +0200
+
+ arc: Fix build error
+
+ One part of the patch for ARC support was missing in the upstreamed
+ version.
+
+ Signed-off-by: Mischa Jonker <mjonker@synopsys.com>
+
+commit d3d099b40c122550279789200263346f120f6909
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jul 2 16:11:38 2013 -0400
+
+ little-endian ppc64 support
+
+commit 0f8690a84c874ec09a090c8c6adfb93c594acac6
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jul 2 15:54:40 2013 -0400
+
+ Rebuild for ARC additions
+
+commit f88118b345f27c46f5445d6e4832c498ff9a6d85
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jul 2 15:51:27 2013 -0400
+
+ Revert "Merge pull request #36 from abergmeier/emscripten_fix"
+
+ This reverts commit 6a4d901dde7b3f87984c563505717cde3113d16e, reversing
+ changes made to b50a13b9c07ec09af4b9697e482acdad571e6961.
+
+commit 6a4d901dde7b3f87984c563505717cde3113d16e
+Merge: b50a13b 587002c
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jul 2 12:12:34 2013 -0700
+
+ Merge pull request #36 from abergmeier/emscripten_fix
+
+ Fixes for building with Emscripten
+
+commit b50a13b9c07ec09af4b9697e482acdad571e6961
+Merge: 767f1f9 b082e15
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jul 2 12:10:26 2013 -0700
+
+ Merge pull request #44 from foss-for-synopsys-dwc-arc-processors/arc_support
+
+ Add ARC support
+
+commit 767f1f96e5282da44d7340e6815e9820a3f78e39
+Merge: c3c40e0 b8a91d8
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jul 2 12:08:04 2013 -0700
+
+ Merge pull request #43 from JensTimmerman/__m128
+
+ added include for xmmintrin.h
+
+commit b8a91d81be77d479327fdb6bdd9fdae6d18e6e63
+Author: Jens Timmerman <jens.timmerman@ugent.be>
+Date: Tue Jul 2 10:57:37 2013 +0200
+
+ added include for xmmintrin.h
+
+commit b082e15091961373c03d10ed0251f619ebb6ed76
+Author: Mischa Jonker <mjonker@synopsys.com>
+Date: Mon Jun 10 16:19:33 2013 +0200
+
+ Add ARC support
+
+ This adds support for the ARC architecture to libffi. DesignWare ARC
+ is a family of processors from Synopsys, Inc.
+
+ This patch has been tested on a little-endian system and passes
+ the testsuite.
+
+ Signed-off-by: Mischa Jonker <mjonker@synopsys.com>
+
+commit cc9b518687e46b0d1acafdd4bc3f3b281c25a3d9
+Author: Marcin Wojdyr <wojdyr@gmail.com>
+Date: Tue May 14 15:01:23 2013 +0200
+
+ Update libffi.pc.in
+
+ use -L${toolexeclibdir} instead of -L${libdir}
+ to be consistent with Makefile.am
+
+commit 587002c092cffe6e7a8d7028f246c241d03b738c
+Author: Andreas Bergmeier <andreas.bergmeier@gmx.net>
+Date: Fri Apr 19 17:12:24 2013 +0200
+
+ Enable disabling of libtool on platforms where it does not work (e.g. LLVM).
+ Build libraries normally then.
+
+commit c3c40e0290377d7cf948b072eedd8317c4bf215e
+Merge: ede96e4 4750e3c
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 30 05:24:14 2013 -0700
+
+ Merge pull request #34 from davidsch/armhf
+
+ Fix ARM hard-float support for large numbers of VFP arguments
+
+commit 4750e3c662fd9569cb3e2d28f539685fd1ca8caf
+Author: David Schneider <david.schneider@bivab.de>
+Date: Thu Mar 28 16:56:36 2013 +0100
+
+ update changelog
+
+commit 9708e7cf09f1bf815f4d6485eb1f180fabb35804
+Author: David Schneider <david.schneider@bivab.de>
+Date: Wed Mar 27 19:31:04 2013 +0100
+
+ folow the ARM hard-float ABI in ffi_prep_incoming_args_VFP
+
+commit b41120981e5e49ca2da10b94b154775f50da5f36
+Author: David Schneider <david.schneider@bivab.de>
+Date: Wed Mar 27 16:38:35 2013 +0100
+
+ create separated versions of ffi_prep_incoming_args_* for SYSV and VFP ABIs.
+
+ The different versions will be called depending on the value of cif->abi
+
+commit dd26f1f39c54861c5b91931f0f37a72942c2a072
+Author: David Schneider <david.schneider@bivab.de>
+Date: Thu Mar 28 15:39:01 2013 +0100
+
+ add a failing test for closures on ARM hardfloat
+
+commit 3c1608613ab3c2184222b98c5482cddedd6b559b
+Author: David Schneider <david.schneider@bivab.de>
+Date: Tue Mar 26 19:24:47 2013 +0100
+
+ extend ffi_prepare_args for FFI_VFP (hard-float ABI), fixing an issue with passing VFP arguments in VFP registers and the stack, while at the same time not using all core registers.
+
+commit 0f2ff2d4c92719be8936179f9ab674f4d1a3fd14
+Author: David Schneider <david.schneider@bivab.de>
+Date: Tue Mar 26 19:22:02 2013 +0100
+
+ separate ARM ffi_prepare_args in a version implementing the simple SYSV calling convention and one for the hard-float calling convention
+
+commit 3a352b8a8252400a83de22c7c424bf1887b4a2ef
+Author: David Schneider <david.schneider@bivab.de>
+Date: Tue Mar 26 14:24:04 2013 +0100
+
+ move the hardfloat specific argument copying code to the helper function
+
+commit 5df6b7944a4225b6eb329f3886be64e04e966f29
+Author: David Schneider <david.schneider@bivab.de>
+Date: Tue Mar 26 14:02:21 2013 +0100
+
+ extract setting of arguments to be passed to a helper function
+
+commit 7d1048c471bb4b1f9d67a9e9f8e95f9a1d2e6d45
+Author: David Schneider <david.schneider@bivab.de>
+Date: Tue Mar 26 11:33:33 2013 +0100
+
+ extract code to align the argument storage pointer to a helper function
+
+commit b9f013788f0f384c423ad963475aaacb55598135
+Author: David Schneider <david.schneider@bivab.de>
+Date: Mon Mar 25 13:27:36 2013 +0100
+
+ add a testcase, that on ARM hardfloat needs more than the 8 VFP argument registers to pass arguments to a call
+
+commit 2fbdb0f231cafdb77b025d3cd8afe90cda99b3ba
+Author: David Schneider <david.schneider@bivab.de>
+Date: Mon Mar 25 13:26:02 2013 +0100
+
+ use the absolute value to check the test result against an epsilon
+
+commit ede96e4eb660bbf3e0fe048135efa8106f48af5d
+Merge: f22ab3c 9e34992
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 17 18:38:21 2013 -0400
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+commit f22ab3c6877cbdd07f058b68816b0086b1cb0e1e
+Merge: 12b1886 d08124b
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 17 18:34:54 2013 -0400
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+commit 9e34992a5ea2fda1dba5875bf96dc91a7230f51f
+Merge: 12b1886 d08124b
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 17 18:34:54 2013 -0400
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+commit 12b1886d7b1f8aa264b1d348bfa47a0e14712df4
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 17 18:32:12 2013 -0400
+
+ cygwin fix & updates for 3.0.13
+
+commit d08124bedf2c6d61874fe215404783aeb9f6f1ac
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 17 18:32:12 2013 -0400
+
+ cygwin fix & updates for 3.0.13
+
+commit cb32c812d04d1dfa72002cc04924e7e4fef89e02
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Mar 17 09:27:55 2013 -0400
+
+ Fix lib install dir
+
+commit efd7866a361a6f636bae8400d26c6811e56ca207
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 16 08:35:57 2013 -0400
+
+ 2.0.13rc1
+
+commit ff647ad4dff2f07dd153f295a1f70b1d906cd6ca
+Merge: 4acf005 d9dd417
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 16 08:20:40 2013 -0400
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+ Conflicts:
+ ChangeLog
+
+commit 4acf0056f55c757490dae6c29a65b0321327ea8a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 16 08:18:45 2013 -0400
+
+ Build fix for soft-float power targets
+
+commit 675c9839224e4268187f1ec6f512127f9db555d0
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 16 08:12:38 2013 -0400
+
+ Documentation fix
+
+commit 8a286f570ccd41db81f74ea7f248da62241d898a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 16 08:01:19 2013 -0400
+
+ Fix for m68000 systems
+
+commit d9dd417b09566af55b7b3000bb53ccaf2e1d6c92
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 16 08:01:19 2013 -0400
+
+ Fix for m68000 systems
+
+commit 215763d012a944d95406b394d6013b80d220e870
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 16 07:57:35 2013 -0400
+
+ Update configury.
+
+commit 9180d8f39c9b6afe17b78277c2711a5d9948e824
+Merge: 2fb527a 7e1b326
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 16 07:46:55 2013 -0400
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+commit 2fb527a017a4943e176a489ff103231b86464b59
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 16 07:46:38 2013 -0400
+
+ Add Meta processor support
+
+commit 211a9ebf4d1a9801e15e103566aed2b8c42790be
+Merge: f308faf ee18766
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 16 04:24:40 2013 -0700
+
+ Merge pull request #32 from alex/patch-1
+
+ Fix for a crasher due to misaligned stack on x86-32.
+
+commit 7e1b32649efd24814e86172e196f390566f9e970
+Merge: f308faf ee18766
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 16 04:24:40 2013 -0700
+
+ Merge pull request #32 from alex/patch-1
+
+ Fix for a crasher due to misaligned stack on x86-32.
+
+commit ee18766b169811426c14b011fbb46d81e344f926
+Author: Alex Gaynor <alex.gaynor@gmail.com>
+Date: Thu Mar 14 15:00:33 2013 -0700
+
+ Fix for a crasher due to misaligned stack on x86-32.
+
+ Full information on reproduction (using Python's ctypes available here: http://bugs.python.org/issue17423)
+
+commit f308faf1eabaf8dc24966ab17fbf94368f46b9c7
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Feb 11 14:25:13 2013 -0500
+
+ Add moxie support. Release 3.0.12.
+
+commit 4ea22e54e3b143fe05c413f6dddd236af6bcbfb2
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Feb 10 08:48:38 2013 -0500
+
+ Update README
+
+commit 10e77227b6ae85f46f28590bfb09ca3608554358
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Feb 10 08:47:26 2013 -0500
+
+ mend
+
+commit a9521411a53d58f2bf88199242200ceb0d4dae3a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 9 06:54:40 2013 -0500
+
+ sparc v8 and testsuite fixes
+
+commit 70b11b47eea93bf43627588d494d0b3b0d062481
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 8 16:12:19 2013 -0500
+
+ Fix small struct passing on ppc
+
+commit 63ba1fa79f7c4ce42de848debe233aab31aecb51
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 8 15:18:19 2013 -0500
+
+ Remove xfail for arm*-*-*.
+
+commit 24fbca4c1d57d4ea628c0a8ba643684daf54a37e
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 8 14:19:56 2013 -0500
+
+ Fix typo
+
+commit b0fa11cb0a94ce6baca058eab9b10e40475e71d6
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 8 14:17:13 2013 -0500
+
+ More man page cleanup
+
+commit 8bd15d139a58a6e46dc90a1cb2d89f59f32f06c7
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 8 13:56:37 2013 -0500
+
+ Fix many.c testcase for ppc
+
+commit 7aab825cf198be85490d3cd80e778d415d85ad9b
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 8 13:26:21 2013 -0500
+
+ Add missing files to dist
+
+commit cb03ea8f4eb08024e44abe4392edc77b89fbfbad
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 8 12:25:18 2013 -0500
+
+ sparc v9 fixes for sun tools
+
+commit 35ee8d44f31dd3d3b88083c837dc351593e13cc2
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 8 07:12:41 2013 -0500
+
+ Fix microblaze big-endian struct issue
+
+commit 9db7e1a958fc484ba149efe027008b9a170395fb
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Feb 7 21:06:08 2013 -0500
+
+ Fix botched sparc patch. Update version.
+
+commit ce0138e61455f268af326e26908b9680ec2c4bea
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Feb 7 18:04:01 2013 -0500
+
+ Update bug report address. rc2.
+
+commit fd07c9e40451e0ec1d0475cd54a83d45ccaea2c0
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Feb 7 18:00:36 2013 -0500
+
+ Add cache flushing routine for sun compiler on sparc solaris 2.8
+
+commit ed6ae9501b2bab45daf93b4935eb0c977635b763
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Feb 7 16:43:36 2013 -0500
+
+ Add libtool-ldflags. Define toolexeclibdir for non-GCC builds.
+
+commit ffef2e046aaec853be356f0b8770a335185ea9cf
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Feb 7 15:47:01 2013 -0500
+
+ x32 and libtool fixes
+
+commit 95eecebb2858dc6f1495a61072ff36d0a8127144
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Feb 7 15:32:46 2013 -0500
+
+ Remove a.out cruft from dist
+
+commit 176aa9d2e23d9cd57d6f250692d910b408f9a651
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Feb 7 15:29:22 2013 -0500
+
+ Fix GCC usage test and update README
+
+commit f3a4f3fdde89b04d66983a42a25d09161c5d4d54
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Feb 7 09:57:20 2013 -0500
+
+ Fixes for AIX xlc compiler.
+
+commit 522f8fef49848927482bc63c94afaea5b84e5ec1
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 6 20:31:31 2013 -0500
+
+ Fix man page. Clean out junk.
+
+commit c4dfa259eb4e8e6f4c397868d7fee80aa0bb6a12
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 6 17:43:24 2013 -0500
+
+ Bump soversion
+
+commit f62bd63fe6123cadedb8b2b2c72eb549c40fbce9
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 6 17:38:32 2013 -0500
+
+ Release candidate 1
+
+commit f7cd61e9e68a4a51147df04d75bfe5b91b9d9286
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 6 17:38:04 2013 -0500
+
+ Fix pkgconfig install bits
+
+commit 6a790129427121f7db2d876e7218a3104e6d2741
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 6 17:37:15 2013 -0500
+
+ Work around LLVM ABI problem on x86-64
+
+commit 370112938e705128fd5dd4017fc1a1210bd0271a
+Merge: bada2e3 bcc0c28
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Jan 27 05:09:04 2013 -0800
+
+ Merge pull request #28 from jralls/master
+
+ Reorder x86_64 checks
+
+commit bcc0c28001b6d427d5cd8037d2e3c892babc6b4c
+Author: John Ralls <jralls@ceridwen.us>
+Date: Sat Jan 26 15:21:14 2013 -0800
+
+ Reorder x86_64 tests
+
+ So that darwin and cygwin/mingw are tested before the generic check --
+ which allows them to actually be set.
+
+commit bada2e326d9a9acf3ae40cfa4f5d7a9ba97b2ea8
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 21 08:02:07 2013 -0500
+
+ Update README
+
+commit 655bb8f3690feba8e840a5f1854b1d78ed08f692
+Merge: 1035ffb 840f975
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 21 08:01:24 2013 -0500
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+commit 1035ffb2f468e1a1c401d58cff7e7abb69838e68
+Merge: aeb8719 4086024
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 21 07:55:53 2013 -0500
+
+ Update README
+
+commit 840f975866052fdd91b2c224d56e01ae5900b60d
+Merge: aeb8719 4086024
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 21 07:55:53 2013 -0500
+
+ Merge branch 'master' of github.com:/atgreen/libffi
+
+commit aeb8719a34756969970603fca4568530d56708af
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 21 07:37:30 2013 -0500
+
+ New microblaze support
+
+commit 40860245a4fd91a1b88adc9171ec993c549e45d5
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 21 07:37:30 2013 -0500
+
+ New microblaze support
+
+commit 20cae32b152b43679ae65a85db9a1c6bb8a143dd
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 21 07:07:38 2013 -0500
+
+ Xtensa support
+
+commit 9742f91782faef4a15941508a22c408fb7d1d227
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 21 07:03:41 2013 -0500
+
+ Mention IBM XL compiler support on AIX.
+
+commit f03eab08248f122ce3b623a18df9e19fae1b6e98
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Jan 11 17:14:11 2013 -0500
+
+ Remove obsolete inline test functions
+
+commit 05fbe1faedc7b2580d5f14010d00e9e3cee73951
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Jan 11 16:54:40 2013 -0500
+
+ xlc compiler support
+
+commit 0b4986a7889ed1864674192228f1162c1b5770a8
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Jan 11 11:19:52 2013 -0500
+
+ [travis] install dejagnu with sudo
+
+commit 3c337eef51ab9a4993fc875bfa26289dd6a08881
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Jan 11 11:18:14 2013 -0500
+
+ [travis] install dejagnu
+
+commit 90720962ce1baf9fc35d1bde1738102bcd5bd5ed
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Jan 11 10:57:30 2013 -0500
+
+ Add first travis config file
+
+commit bff052d9cd5be41ba9e47c76114054af487d3c30
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Jan 11 10:24:32 2013 -0500
+
+ 32-bit x86 fix and more
+
+commit cd41aeab6176f839167955c016ecc19f65f75df3
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Jan 10 17:25:45 2013 -0500
+
+ Add compiler column to table
+
+commit 8bf987d4df7c4d21435b9211f6cc86abf5904b42
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Jan 10 17:24:51 2013 -0500
+
+ Fix for sunpro compiler on Solaris
+
+commit 3ee74fd6dc8ccd32b608bbff73526838fc34f70b
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Jan 10 17:15:03 2013 -0500
+
+ Update documentation version.
+
+commit 13e2d7b92557a9511a0414df82bf2df3edc55cba
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Jan 10 10:52:02 2013 -0500
+
+ Handle both 32 and 64-bit x86 builds regardless of target triple
+
+commit 5141543000fc86a3d49a907a2313713ee79e504d
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Jan 10 07:35:53 2013 -0500
+
+ Don't run EH tests with non-GNU compiler
+
+commit 56ba8d86f47937a0afb81a2b9e77c9d235d9db45
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Jan 10 07:25:10 2013 -0500
+
+ Don't use warning checking macro with sun compiler
+
+commit 6a028caec1b2c7904feb4c4f9cb7e1125e1d1b60
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Jan 10 01:19:43 2013 -0500
+
+ Don't use GCCisms to define types when
+ + building with the SUNPRO compiler.
+
+commit 2d9b3939751b3ef9739049509d353ade10b32a8f
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 9 21:14:54 2013 -0500
+
+ Fix for closures with sunpro compiler
+
+commit 8308984e479e3274a36e98e8272b5adbb6b774c2
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jan 8 15:14:21 2013 -0500
+
+ Make sure we're running dejagnu tests with the right compiler.
+
+commit f26c7ca67147450db2fe25ea932944e6cf145d5c
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jan 8 14:47:05 2013 -0500
+
+ Make compiler options in dejagnu runs compiler specific
+
+commit 74c776e21907fc2e59257c021f23077f8b7966cb
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jan 8 12:25:54 2013 -0500
+
+ Switch x86 Solaris to X86 from X86_64
+
+commit 8962c8c8d06803e310bac0ffc8e84ea15daeff3f
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jan 8 12:22:24 2013 -0500
+
+ Fix read-only eh_frame test
+
+commit 35ddb69c2b49746d940e919ca226ecc1be94f14a
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jan 8 07:53:37 2013 -0500
+
+ Only emit DWARF unwind info when building with GCC
+
+commit f7879bc3f3a8d0bbfcc38771732c160a58ba9cd8
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Jan 8 07:30:28 2013 -0500
+
+ Testsuite fix for Solaris vendor compiler
+
+commit 67cea90fc0897021466fd102671019d30db474cd
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 7 06:30:24 2013 -0500
+
+ mend
+
+commit 0de3277b18cf54be3b81d509b9be9b47d9bc1e82
+Author: Thorsten Glaser <tg@mirbsd.de>
+Date: Mon Dec 3 00:02:31 2012 +0000
+
+ Testsuite fixes (was Re: [PATCH] Fix libffi on m68k-linux-gnu, completely)
+
+ Dixi quod…
+
+ >although I believe some 3.0.11 checks to be broken:
+
+ And indeed, with a few minor changes on top of git master,
+ I still get a full run of PASS plus one XPASS on amd64-linux!
+
+ With the other patches (from this message’s parent) and
+ these applied, I get a full PASS on m68k-linux as well.
+
+ So, please git am these three diffs ☺
+
+ bye,
+ //mirabilos
+ --
+ FWIW, I'm quite impressed with mksh interactively. I thought it was much
+ *much* more bare bones. But it turns out it beats the living hell out of
+ ksh93 in that respect. I'd even consider it for my daily use if I hadn't
+ wasted half my life on my zsh setup. :-) -- Frank Terbeck in #!/bin/mksh
+ From 5cb15a3bad1f0fb360520dd48bfc938c821cdcca Mon Sep 17 00:00:00 2001
+ From: Thorsten Glaser <tg@mirbsd.org>
+ Date: Sun, 2 Dec 2012 23:20:56 +0000
+ Subject: [PATCH 1/2] Fix tests writing to a closure retval via pointer casts
+
+ As explained in <Pine.BSM.4.64L.1212022014490.23442@herc.mirbsd.org>
+ all other tests that do the same cast to an ffi_arg pointer instead.
+
+ PASS on amd64-linux (Xen domU) and m68k-linux (ARAnyM)
+
+ Signed-off-by: Thorsten Glaser <tg@mirbsd.org>
+
+commit 8f4772f383abd71cfa141c8a70ba11c1aa4ebe2c
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 7 06:14:53 2013 -0500
+
+ m68k fixes for signed 8 and 16-bit calls.
+
+commit ea7f8440d58afbebb181e295ff564fdf3d6590a0
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Jan 4 09:09:32 2013 -0500
+
+ remove gcc-ism
+
+commit f06c0f10377ac04eeba5e632dbe5c62c629df4e6
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 09:39:17 2013 -0500
+
+ Add missing ChangeLog entry and generated files.
+
+commit 1f8675d4c101d19d67ca0a55ff2ba973349558ad
+Merge: 335f419 f6b58d2
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 06:34:38 2013 -0800
+
+ Merge pull request #26 from rofl0r/master
+
+ fix build error on ppc when long double == double
+
+commit 335f419a86090cda9f215d149572f9481c3ad034
+Merge: 53236d5 6d6f711
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 06:30:03 2013 -0800
+
+ Merge pull request #23 from rurban/master
+
+ cygwin/mingw shared libs need libtool LDFLAGS = -no-undefined
+
+commit 53236d5061034cc0a7f4647fc1bd05ba1aeb3d2a
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 09:24:55 2013 -0500
+
+ Regenerate files
+
+commit 72222ca3fbe560e13c8dc89ca441b28b7cc74daf
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 09:06:38 2013 -0500
+
+ Update texinfo.tex
+
+commit 1e326c95431fc9896422fa36659f3e833852579c
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 09:05:02 2013 -0500
+
+ Update config.guess and config.sub
+
+commit cb6671f5b8a9596ff968c6b6c304f70adf71b368
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 08:56:07 2013 -0500
+
+ Missing .gitignore changes for xcode support
+
+commit ebbe77966855395a2a47ed2c09a38f93eb0481cf
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 08:54:05 2013 -0500
+
+ missed x32 libtool patch.
+
+commit 4394096da0aca0dd422b479a043c18b4f05c5770
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 08:51:35 2013 -0500
+
+ missed trampoline_table patch. Move to GCC.
+
+commit ed7a59c3ff7c84bd95c374a5aff21599f705e6dc
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 08:48:01 2013 -0500
+
+ Windows symbol export fix. Move to GCC.
+
+commit ccee09a4ff843b11c7d8b6819776f57d187305c7
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 08:41:55 2013 -0500
+
+ +2012-03-21 Peter Rosin <peda@lysator.liu.se>
+ +
+ + * testsuite/lib/target-libpath.exp [*-*-cygwin*, *-*-mingw*]
+ + (set_ld_library_path_env_vars): Add the library search dir to PATH
+ + (and save PATH for later).
+ + (restore_ld_library_path_env_vars): Restore PATH.
+
+commit 089dbce7cc0889eb26444d89ae062c73c69f26f0
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 08:37:35 2013 -0500
+
+ med
+
+commit 980a334c42b4b0eff32e55929ec6727d1326b05d
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 07:36:42 2013 -0500
+
+ Test GCC update
+
+commit 8bad679ade5000e57cdc9cacde22e8b99840930f
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 08:28:35 2013 -0500
+
+ New stand-alone patch
+
+commit 981c32ee115e9f0d6546a74592875e138222a9d1
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Jan 2 07:34:03 2013 -0500
+
+ Merge with GCC. Eliminate quilt bits.
+
+commit 61a054929517fb80c437ba71c91f3e20cfff581a
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Nov 28 06:07:41 2012 -0500
+
+ Refresh config.guess and config.sub
+
+commit f6b58d2bdc0a24ce94dedce59802f091979df265
+Author: rofl0r <retnyg@gmx.net>
+Date: Thu Nov 22 16:26:21 2012 +0100
+
+ fix build on ppc when long double == double
+
+commit 69da33a0761aeac73f9e9646269da61c906d6020
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 12 15:25:47 2012 -0500
+
+ Pull in config.sub for aarch64 support and more
+
+commit f680b598b7bdde325ac9349e8c35151c228bf2df
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Nov 6 16:00:40 2012 -0500
+
+ Add missing aarch64 configury bits
+
+commit dfadfb19853c57c8623c436d0ef2bdafab24b433
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Oct 31 06:46:41 2012 -0400
+
+ Rebase for ppc64 fix
+
+commit e944b8c7eb1e2eeb9c0f3b9742b4d7f476860ce1
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 30 14:06:09 2012 -0400
+
+ Add PaX work-around
+
+commit 9ccd51be1fdeb99f8b4f42f905166c2abbba8ac0
+Merge: f342996 fa5d747
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 30 13:37:37 2012 -0400
+
+ Fix commit conflicts
+
+commit f342996cb50eb23b868afcff5ac0cdbb6b505d63
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 30 07:42:27 2012 -0400
+
+ Darwin12 fix
+
+commit 58e8b66f70cef2e3c9b0e5a707b45d634cbbf5d9
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 30 07:07:19 2012 -0400
+
+ AArch64 port
+
+commit fa5d747905472571fd472c07d4726017624f66b3
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 30 07:07:19 2012 -0400
+
+ AArch64 port
+
+commit 6993a6686f43f2313b18142c1e96189a27db2aa3
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Oct 30 06:59:32 2012 -0400
+
+ Fix autoconf macros
+
+commit 70084e70ddb13b29dd05c751b1904de206bbe790
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Oct 12 23:55:06 2012 -0400
+
+ Update Tile* port info
+
+commit 9c00a3f6742d61404b31268cc773e7130ff43331
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Oct 12 16:46:06 2012 -0400
+
+ TILE-Gx/TILEPro support
+
+commit 048d2f41c3a6664b4b64bf21e804686662da4160
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Oct 11 10:55:25 2012 -0400
+
+ Rebase
+
+commit 6d6f71108064f5069edd7bf771059d3b82640135
+Author: Reini Urban <rurban@cpanel.net>
+Date: Sat Jul 7 12:42:00 2012 -0500
+
+ cygwin/mingw shared libs need libtool LDFLAGS = -no-undefined
+
+ otherwise only static libs are created.
+
+commit d330f19292da8f39a78a9e2b0ba08df8094e3bc5
+Author: Nicolas Lelong <rotoglup>
+Date: Sat May 5 09:37:02 2012 -0400
+
+ iOS build fixes.
+
+commit 09b23cfc1d6d15361eee18818851fd3cacb26559
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Apr 27 08:29:48 2012 -0400
+
+ Update README with Blackfin/uClinux support
+
+commit 213ed15c70e72d666154c08e2b41dae3f61f20d3
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Apr 27 01:34:15 2012 -0400
+
+ Add blackfin supprt from Alexandre Keunecke.
+
+commit ff3d76fd427382ce7d2b2ed54acdd0bce470ca4f
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Apr 11 23:16:48 2012 -0400
+
+ 3.0.11
+
+commit 7e0a412c4fd9cbe77b467a9bf86f56aea62632c3
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Apr 11 22:47:44 2012 -0400
+
+ Update files to ship
+
+commit 39e6a5860416f7bad992149817e1da1ba7c460d4
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Wed Apr 11 22:39:46 2012 -0400
+
+ More mac/ios build improvements
+
+commit 853cc722a16f8d1254573ef3bb73c7b8f3d8a110
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Apr 10 06:33:33 2012 -0400
+
+ Fix typo for darwin targets
+
+commit 3f5023068cda07a3dd6dacbaa875a5b5fc96d4bb
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Apr 6 20:34:51 2012 -0400
+
+ mend
+
+commit ebb8e8945681ce0af7a5c47a980287e8ece84b84
+Author: Mike Lewis <mikelikespie@gmail.com>
+Date: Fri Apr 6 20:02:08 2012 -0400
+
+ Build iOS library with xcode
+
+commit a098b44f4c592c2192fcdef4fad6108eb3f4301c
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Apr 6 17:04:35 2012 -0400
+
+ Reapply missing testsuite changes for arm
+
+commit 10d1e51393f08c14045db85843208f44f9f1e9ba
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Apr 6 11:57:14 2012 -0400
+
+ Update to rc4. Upgrade autoconf version.
+
+commit 9bcc884276dc0a807b2605e510b11b1740dd9aa2
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Apr 6 11:53:07 2012 -0400
+
+ Fix Linux/x32 reference in README
+
+commit a044a56b1cd2a0924f5ec0d6b5a5089d14fcd1a1
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Apr 6 10:39:10 2012 -0400
+
+ Linux/x32 libtool fix
+
+commit 59bb61a36661b972e8443531d3b7bc736e131a4b
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Apr 6 08:26:14 2012 -0400
+
+ Update libtool version, README, tests dists
+
+commit f2981454cbe25cf9411b710f46c5f5552003a123
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Apr 5 15:45:19 2012 -0400
+
+ Revert debug code changes
+
+commit 39dccddb606f6fdb8dcb177d416e884041da6e30
+Author: Zachary Waldowski <zwaldowski@gmail.com>
+Date: Thu Apr 5 12:32:41 2012 -0400
+
+ Fix building with Clang for Darwin (OS X 10.6+ and iOS
+ 4.0+)
+
+commit 3afaa9a34a81a305227ae8cf4f12b9d0484d055e
+Author: Peter Rosin <peda@lysator.liu.se>
+Date: Tue Apr 3 07:40:31 2012 -0400
+
+ Fix return_uc.c test case on windows.
+
+commit 65f40c35a2873d8328359ec4512bd0736dbe32c7
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Apr 3 07:35:59 2012 -0400
+
+ Repair ppc build regression.
+
+commit 0a1ab12a8d15caa894116a82249551f23ef65612
+Author: Peter Rosin <peda@lysator.liu.se>
+Date: Fri Mar 30 08:14:08 2012 -0400
+
+ Various MSVC-related changes.
+
+commit e1539266e6c6dde3c99832323586f33f977d1dc0
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Mar 30 00:40:18 2012 -0400
+
+ ARM VFP fix for old toolchains
+
+commit 7c5e60b5f47d725036a72162f136272bc407e3a1
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Mar 29 08:48:22 2012 -0400
+
+ Rebase on fixed GCC sources
+
+commit e72ed5eeaa9cfb0fdc86f6b3422734177b659f96
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 21 09:52:28 2012 -0400
+
+ Fix vararg float test
+
+commit bd78c9c3311244dd5f877c915b0dff91621dd253
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 21 08:09:30 2012 -0400
+
+ More cygwin fixes
+
+commit 84d3253f86dad6b4f261231935675d35fd964b05
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Mar 19 23:07:35 2012 -0400
+
+ Rebase post GCC merge
+
+commit 964c5b93f80dcaacf73056b7d15a4d2b4b7a217c
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 3 14:46:20 2012 -0500
+
+ abi check fixes and Linux/x32 support
+
+commit 6c194233a5f6f1d274669afc5924a9e1f69d4876
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Mar 3 14:17:54 2012 -0500
+
+ Add -no-undefined for both 32- and 64-bit x86
+ windows-like hosts.
+
+commit 8360bf1cd0aba8db5582266da70467de7e89a57a
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Feb 23 07:01:13 2012 -0500
+
+ Ensure that users don't include ffitarget.h directly
+
+commit d578b89619cf3d2baff027b203619dc307fc12e3
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 15 00:18:18 2012 -0500
+
+ Fix ABI check regression
+
+commit dee20f8e45c486f5018f31e09bb362992aa498c3
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 10 13:06:46 2012 -0500
+
+ Rebased from gcc
+
+commit 4130e1972d001143e5e9f3c6b65f2a6f9524169e
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 3 13:18:27 2012 -0600
+
+ Refresh autoconf-archive m4 scripts
+
+commit 1ff9c604bb214b5a305064af1049577ef783730a
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 1 16:34:30 2012 -0600
+
+ Rebase from GCC
+
+commit 211060eb8f714af0e935430efa6bb45e8e3ffc5d
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 23 14:24:01 2012 -0500
+
+ Alpha fix
+
+commit 78d9c638ba0de6edfbc603fd65d19c6562663248
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 23 14:17:24 2012 -0500
+
+ mend
+
+commit afaf3381604bd81803d8a5f3bf4d462299f1aac3
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 23 14:17:13 2012 -0500
+
+ mend
+
+commit 9e9c4aeb77de5608d602109f22100c1c0c79faad
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 23 14:11:23 2012 -0500
+
+ Add Amiga support
+
+commit 8efc0b1f4027d5a3cbf205e55d422d94e60f3226
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 23 13:47:38 2012 -0500
+
+ Unlikely fixes
+
+commit 1df51398ae183dc208ba4599ee867278b04d13d3
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 23 13:43:59 2012 -0500
+
+ mend
+
+commit cd2277cc796b96b149cd284ae85326529fe7fb9c
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 23 13:43:38 2012 -0500
+
+ mend
+
+commit 164e6fe04b189746c8bd5810c6e3e919770bb9d4
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 23 12:41:06 2012 -0500
+
+ m68k fixes
+
+commit c365ee7577bef00cb3c2c0b5224147aea04138d8
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jan 23 11:13:18 2012 -0500
+
+ Refresh
+
+commit f22c38bbd93bcc0c04bf26c3e414556b3177c385
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 18 15:13:41 2011 -0500
+
+ Update variadic patch
+
+commit 03e9ee321a3c208f88d2432587ce40b2bb2430ba
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Nov 18 15:13:00 2011 -0500
+
+ Fix cls_double_va.c and update docs
+
+commit 95f31151ec792809cfb80d385350f9f56d95aa25
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 23:46:05 2011 -0500
+
+ Rerun automake
+
+commit 198ed1ef85cf18342627f8d44bc3f12c9975a49d
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 23:45:20 2011 -0500
+
+ Update version number
+
+commit 4f17e1f142e805b13959ba2594ee735eae439f4e
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 17:22:24 2011 -0500
+
+ Fix last patch
+
+commit ff9454da44859716a5bd4eaa344499288c79694f
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 17:18:51 2011 -0500
+
+ Add David Gilbert's variadic function call support
+
+commit ea14ae85e8f54ff046b7fb8a9cfe349475272044
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 16:36:59 2011 -0500
+
+ clean up
+
+commit 52891f8a93f9b8de801cca4cf05639422dc9773e
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 16:35:55 2011 -0500
+
+ Add powerpc soft float support
+
+commit c8f1bde8e2566c5a87474b4d08aa934d6d28ee75
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 16:21:02 2011 -0500
+
+ Remove junk file
+
+commit 6a6e7f862f3cc677e19131587caa619e7f9c7ffd
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 16:20:42 2011 -0500
+
+ Fix kfreebsd
+
+commit d52fbed05ccbdee9ed8b9c911cbb4f85b0ff0f2a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 16:13:41 2011 -0500
+
+ Add missing ChangeLog entry
+
+commit 322052ce65c4fdac85bedc24726fd0e0094ba521
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 16:11:49 2011 -0500
+
+ Fix arm wince alignment issue
+
+commit af18df2bc2f52df81e7b5c619bd86db8489dc873
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 15:52:08 2011 -0500
+
+ Remove use of ppc string instructions
+
+commit 236c9391321f83ad40daf03f40c35c9ebc1da6b3
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 07:37:40 2011 -0500
+
+ Fix darwin11 build problem
+
+commit c411f140f305ebb00d33c92b7cb2742bcd241b6a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 07:32:36 2011 -0500
+
+ Fix ax_enable_builddir macro on BSD systems
+
+commit 3d56106b07735abef6ae9f032e94f560a0ed2f30
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Nov 12 07:20:24 2011 -0500
+
+ Rebase
+
+commit 8c01954c50bf8ef2e00a3db166060a1b8f83a20d
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Sep 6 14:26:32 2011 -0400
+
+ Build assembly files with debug info
+
+commit fed646a2078969f4ce89c29107f1e72e03f4a977
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Sep 6 09:50:20 2011 -0400
+
+ Regenerate configury with missing m4 macros
+
+commit d76441cf71216f8f1e62e7ec852a7f4e21371ec8
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Aug 24 10:14:23 2011 -0400
+
+ Update list of supported OpenBSD systems
+
+commit ee6696fdf4768ba6dd037fb6dd99435afa13816e
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Aug 23 12:30:29 2011 -0400
+
+ 3.0.11-rc1. soname bump.
+
+commit c6265c36a91eab8175d0e72db84d8225418f2379
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Aug 23 10:31:33 2011 -0400
+
+ Version 3.0.10
+
+commit cc5e41bf32d18a14dbdd653d52eacdbdc934c392
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Aug 22 16:34:24 2011 -0400
+
+ Fix use of autoconf macros
+
+commit 049d8386ff52399e69a530b55b9feedc8a2589d2
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Aug 22 14:50:10 2011 -0400
+
+ Many new patches
+
+commit 3b7efa4e74f0dcebf70b447391987aedd3473306
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Aug 15 13:25:13 2011 -0400
+
+ Revert remove-debug-code patch temporarily (for ARM Fedora release)
+
+commit d992ac54a2a9e7e064ffebcb91e05e7cb86185c7
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Jul 29 17:32:53 2011 -0400
+
+ Refresh from GCC
+
+commit 2d3fb36420e09304220ee6c0652bae5eccdb965d
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Mar 30 16:54:42 2011 -0400
+
+ Fix darwin EH
+
+commit 30ff28e1d8cd9ed5319f1fbe9c7cccacc8161fb3
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Feb 28 15:36:23 2011 -0500
+
+ Fix permissions
+
+commit 09f8f310f4f53a24289682d3d28f4399d7bafc3b
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Feb 28 15:36:07 2011 -0500
+
+ More AIX fixes. rc9.
+
+commit 53d7b165642c220aa5166ba350b490802f359b54
+Merge: 18dd85d 3000dc2
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Feb 28 15:23:31 2011 -0500
+
+ Merge branch 'master' of https://github.com/landonf/libffi-ios
+
+commit 18dd85d6cb9f3f3eea2a3b70eb4e150045905c55
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 25 16:23:04 2011 -0500
+
+ rc8. fix last patch.
+
+commit 74ee6ea8b42e60d44a3ae8938b1e42a38c1e66b4
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 25 15:52:14 2011 -0500
+
+ rc7. More AIX fixes.
+
+commit 2541679dbd3db0014890f42192dbf8008ab923fa
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 25 15:09:13 2011 -0500
+
+ Fix ppc32 bug
+
+commit cbb062cc35c518004f1ab45c847f8ec4f66069ad
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Feb 17 20:39:21 2011 -0500
+
+ Another non-GCC configury fix
+
+commit 8cf8878425e9971866fa6b27a3e4914729ad3960
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 15 15:19:49 2011 -0500
+
+ Fix ax_cc_maxopt.m4
+
+commit 24b72070c0937f9000744c77a636f07e04786b6a
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Feb 14 15:30:57 2011 -0500
+
+ Fix warning and msvcc patches
+
+commit d72c49e556a8c516e97f6722d1be2f1209c21207
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Feb 13 11:41:05 2011 -0500
+
+ Add missing msvcc.sh
+
+commit 3000dc237f6017a7445d8404097a4f46b73fdd29
+Merge: 55e4a5a 1fbf9dc
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Feb 13 08:55:53 2011 -0500
+
+ Merge remote branch 'upstream/master'
+
+commit 1fbf9dc44feea564e84ad7406d17c5d5906ce0e0
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Feb 13 08:06:39 2011 -0500
+
+ Fix bad_abi test. rc5.
+
+commit 90af15ef5c1614b76370c4d13954586fabf9e8e3
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 12 12:29:36 2011 -0500
+
+ iOS fixes
+
+commit 55e4a5aa1568558a04aa40f16fc022e459af53e3
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Feb 12 12:13:46 2011 -0500
+
+ Add support for building a full armv6/armv7/i386 universal iOS library
+
+commit a0c80f279b8733d001cb5e5c5a3289ecb7a6e56a
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Feb 12 11:43:49 2011 -0500
+
+ Update my e-mail address.
+
+commit 8195e0e11df7a53fa474caa9375f73ca1136ed66
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Feb 12 11:27:00 2011 -0500
+
+ Fix symbol prefixes on Darwin.
+
+commit 56b3f8cef0f28cefaa0f40fe0cf7c524adef131d
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Feb 12 11:14:54 2011 -0500
+
+ Modify the ffi_closure structures to hold table/table entry pointers instead of a code buffer.
+
+ This re-integrates commit da2773e02ab26cc11a7f.
+
+commit 28a00f61ff3f64c4eb2269ce2aea3d493274469e
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Feb 12 11:01:48 2011 -0500
+
+ Apple assembler support; fixed most gas/ELF-isms.
+
+commit 7f2ea33a80bfced5e48ed7292f3b8f057d54ff8f
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Feb 12 10:39:18 2011 -0500
+
+ Replace RETLDM macro.
+
+ The macro is incompatible with Apple's assembler; switch to
+ a simple inline version.
+
+commit 92ff23e77fa586455b427b71f49e1d9502470e6e
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Feb 12 10:24:49 2011 -0500
+
+ Switch to the current iOS 4.2 SDK.
+
+commit 58fb8ca2dfb89ad70284bb9678d3d4dbb658c8a7
+Merge: cc3fbd9 71c792f
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Feb 12 10:23:19 2011 -0500
+
+ Merge remote branch 'upstream/master'
+
+commit cc3fbd975ce9366d4c40a6ff6c108f664867bd7c
+Merge: e449a43 f6ab3ed
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Feb 12 10:21:02 2011 -0500
+
+ Merge branch 'master' of github.com:landonf/libffi-ios
+
+commit e449a43bbe12f8119399928db1ae26adc71dde14
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Feb 12 10:20:42 2011 -0500
+
+ Allow specification of the minimum supported iOS version.
+
+commit 71c792f51bcf3e2f334e5ea1fb1a8b667cb3aedb
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 12 09:33:11 2011 -0500
+
+ rc4
+
+commit 7c7c9f327299331022f6000603a35f2310dfe308
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Feb 12 09:29:29 2011 -0500
+
+ ungccify parts of the build
+
+commit ed62e48b95a0fa60b685f647cb73c9e190eec35c
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 11 12:23:58 2011 -0500
+
+ Fix permissions
+
+commit 17d9e9e68ddb1b915a0b9751713033861b598575
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 11 12:23:20 2011 -0500
+
+ Use newer autotools. Only build debug.c when --enable-debug.
+
+commit 6972a4ffda75761eaab7dfbe0fb1516b255e8e0c
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 11 07:32:51 2011 -0500
+
+ Fix xlc build on AIX
+
+commit 1833aa0fb9831eb0725b63e35886c0f6d35df480
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Feb 11 07:11:04 2011 -0500
+
+ sparc ABI test fix.
+
+commit f1fb139b4e283fffdcf205a903943d5e9d2bb2a2
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 9 18:30:02 2011 -0500
+
+ Fix tests
+
+commit 5cb470331d181c84d5d621e88868327a324a5898
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 9 15:23:06 2011 -0500
+
+ Fix permissions
+
+commit 269deef6dbbb426695919d3398357fada3bb288c
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 9 15:22:23 2011 -0500
+
+ rc3
+
+commit 42695e72504f647444b8e8e9b90bd24f1e3220e1
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 9 15:12:35 2011 -0500
+
+ Fix IRIX support
+
+commit a6e56b97f62a3feeb3301c24a2e4cae55e546021
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 9 15:00:42 2011 -0500
+
+ Add powerpc64-*-darwin* support
+
+commit 747d6c32d4abb07c10c3a1f93579c3929aaa2487
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 9 14:56:23 2011 -0500
+
+ Add Interix support
+
+commit eab6e41cde382aa07de6c011d514a14c0d62eb47
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 9 10:15:02 2011 -0500
+
+ Remove README.markdown form libffi-ios
+
+commit 69dbe845f4ee3e6ce8999f17a1e4f2179ef7da89
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 9 07:38:43 2011 -0500
+
+ Fix xfails
+
+commit f498318c07b95137fe259d86bdbe15347588b84a
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 9 06:26:46 2011 -0500
+
+ Update README for iOS again
+
+commit 630b9c0ac43c7edcbfd892e23c09fb26724f4ac0
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 9 06:24:23 2011 -0500
+
+ Update to rc2
+
+commit 0cad4386fa4c9ea5f8ca88b16247db4e5c8fea90
+Author: Anthony Green <green@moxielogic.com>
+Date: Wed Feb 9 06:11:46 2011 -0500
+
+ Add ChangeLog entry. Fix copyright headers.
+
+commit 09cb76f2645bd2c151846e9249d8ea707ba01e8c
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 20:39:51 2011 -0500
+
+ Add missing change
+
+commit 2e3a48ccdd54340983c46a29a0b41985e3e789ac
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 20:37:26 2011 -0500
+
+ Fix make dist
+
+commit 5e4814d9928e236a2a4afe84d6e1d4fdaa473206
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 19:46:28 2011 -0500
+
+ fix permissions
+
+commit 5c0cc6f1536aa1738795a97303810a823c7fa2cb
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 19:45:59 2011 -0500
+
+ 3.0.10rc1
+
+commit 857fe3de46d2286afa2fe772920ecf4aefa1688f
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 19:39:20 2011 -0500
+
+ Clean ups
+
+commit e2214f8adb5577c247452e2cc9f4cbe304d7ca9f
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 19:22:56 2011 -0500
+
+ Update README
+
+commit 1106229a5721a659da5c231ec0e8211119615394
+Merge: bc9d0be f6ab3ed
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 19:20:09 2011 -0500
+
+ Add iOS support
+
+commit bc9d0be2958ce475757f34dd2c878948aa77a39f
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 17:04:26 2011 -0500
+
+ 3.0.10rc0 changes
+
+commit 3b836249feae6d08d3e6887486e4b9961ddafa09
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 14:28:59 2011 -0500
+
+ Rebase from GCC
+
+commit a26e3940619faeba6de54824c9540c90b1aab513
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 13:56:12 2011 -0500
+
+ copyright updates patch
+
+commit b8099539f00e224107594101e9760b6dc081a056
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 13:50:43 2011 -0500
+
+ Fix msvcc.sh botch
+
+commit dc411e8f99113a34656bfd2d3ae51259972488cc
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 10:49:29 2011 -0500
+
+ Fix HP-UX build
+
+commit 404585d1348e30ac58203bbd876d9131e5aed874
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 10:44:36 2011 -0500
+
+ Fix sparc v8 aggregate type returns for sun's compiler
+
+commit 19ce713188e193e4522740d24c20170411883d2d
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 10:34:23 2011 -0500
+
+ grammar fix
+
+commit 89284fe55f1a8ad3bddbea796ee00d0e3ba411ce
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 10:19:19 2011 -0500
+
+ Fix AIX build with IBM XLC
+
+commit ba022c338af97cb18d9f8ed5a607fd483a61c09c
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 10:12:48 2011 -0500
+
+ fix win64-underscore patch
+
+commit 097e5f3924ee92a3ba6cd72f787da8a3eb14fea3
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 10:11:00 2011 -0500
+
+ x86 pcrel test part 2
+
+commit ed2c518d960b91d444be74e5a55779a9c4602f3b
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 10:10:07 2011 -0500
+
+ x86 pcrel test
+
+commit 0e5843995f46900ef212531281e08b224464f413
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Feb 8 07:52:40 2011 -0500
+
+ Refresh from GCC
+
+commit 5b9cd52784339a42e417174a55e310e214d435f9
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Nov 22 15:19:57 2010 -0500
+
+ win64-underscore patch
+
+commit 2db72615b50eb5c0f29725c02c740a2f0d7fc7d9
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Nov 21 10:50:56 2010 -0500
+
+ Rebase
+
+commit f6ab3edc23dc8fc7c47a31c896044150c23f04b5
+Author: Landon Fuller <landonf@plausible.coop>
+Date: Wed Oct 27 19:34:51 2010 -0400
+
+ Include the license header in the generated output.
+
+commit cef619462887fa0f360e3ee702d1e04f112b5b38
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Wed Oct 27 13:59:30 2010 -0400
+
+ Add missing copyright/license header.
+
+commit 53f387b203413c9aa6e31f49dbb70d37d816330b
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 19:57:17 2010 -0700
+
+ Minor README fix.
+
+commit 4fbcb5b5fbce11f4b168060e00639db33c85b75b
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 19:50:37 2010 -0700
+
+ Minor README fix.
+
+commit 8e7652ef6acab5db7a29f786686a54f05cdbdc7d
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 19:49:39 2010 -0700
+
+ Add a libffi-ios-specific github README.
+
+commit 83038cf24aa1a92b62b91ffee1dcc25d79243484
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 14:36:45 2010 -0700
+
+ Implement FFI_EXEC_TRAMPOLINE_TABLE allocator for iOS/ARM.
+
+ This provides working closure support on iOS/ARM devices where
+ PROT_WRITE|PROT_EXEC is not permitted. The code passes basic
+ smoke tests, but requires further review.
+
+commit b00ff3e98fdde622cef617030e14d5356dff988f
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 14:22:26 2010 -0700
+
+ Rename the generated symbol
+
+commit da2773e02ab26cc11a7fe87e985599f35cdf0649
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 14:21:37 2010 -0700
+
+ Modify the ffi_closure structures to hold table/table entry pointers instead of a code buffer.
+
+commit 01d71b7bed41844f80cb9feef20dcc5ece5ba2d0
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 14:21:14 2010 -0700
+
+ Regenerated the autoconf script
+
+commit 19afda0069c42e51c81dca7b10a5cf884b4cdce0
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 14:20:52 2010 -0700
+
+ Enable AC_SUBST for FFI_EXEC_TRAMPOLINE_TABLE
+
+commit 9e1196444e78aef20028c18891f44ebe39a815fd
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 10:43:06 2010 -0700
+
+ Add a hard-coded FFI_EXEC_TRAMPOLINE_TABLE arm implementation.
+
+ This implements support for re-mapping a shared table of executable
+ trampolines directly in front of a writable configuration page, working
+ around PROT_WRITE restrictions for sandboxed applications on Apple's
+ iOS.
+
+ This implementation is for testing purposes; a proper allocator is still
+ necessary, and ARM-specific code needs to be moved out of
+ src/closures.c.
+
+commit f38364b399184e682fc3e785084bd497827bc5af
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 10:42:36 2010 -0700
+
+ Fix symbol prefix for ffi_closure_SYSV_inner on Darwin.
+
+commit 36849e7716b77aa25e4175d1f4be1b93dbf47aac
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 09:35:04 2010 -0700
+
+ Whitespace/comment fixes.
+
+commit b764162526854686e579a48b6ac5981f4eb886a3
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 09:04:34 2010 -0700
+
+ Fix the script name (build-iphone.sh -> build-ios.sh)
+
+commit a3d9aa85013341451ea97766485b7a11852d32b2
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 09:03:52 2010 -0700
+
+ Update the autogenerated autoconf/automake files.
+
+commit c71480eaf839f26bbdfcd8965f65ac4d8defddc0
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 09:02:05 2010 -0700
+
+ Update automake/autoconf to conditionally build src/arm/trampoline.S if FFI_EXEC_TRAMPOLINE_TABLE is enabled.
+
+commit 9af9291b73bc5e27ecd949bec8157f20426d65b8
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 08:52:33 2010 -0700
+
+ Add the trampoline table generated by gentramp.sh
+
+commit 68ce0c383ece84f69945d1c8c3fed03f7f9cb5d6
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sun Sep 19 08:38:19 2010 -0700
+
+ Add a shell script that generates the ARM trampoline page.
+
+ This generates a page of 340 trampolines, aligned within one page. The
+ trampolines use pc-relative addressing to reference config data
+ (context, jump address) from a page placed directly prior to the
+ trampoline page. This can be used on systems -- such as iOS -- that do not
+ support writable, executable memory by remapping the executable page
+ containing the trampolines directly above a newly allocated writable
+ config page.
+
+commit 75af086be8830a8eafe9b1ebda199d788bcb0c62
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Sep 18 18:12:19 2010 -0700
+
+ Update autoconf files
+
+commit 1ac92cca9b02ef8d6a769f0de1adccd5c9630355
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Sep 18 18:08:14 2010 -0700
+
+ Add autoconf check for W^X platforms that require a trampoline table.
+
+ This adds the FFI_EXEC_TRAMPOLINE_TABLE. The flag is enabled for
+ arm-apple-darwin, where PROT_EXEC on writable (or formerly writable) pages is
+ not permitted for sandboxed binaries.
+
+commit be72fbab29b7190c702d8e1ac3d149855e95879d
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Sep 18 18:02:25 2010 -0700
+
+ Use the correct host triple for arm/darwin
+
+commit 70150bdf4509269965c72f2032bf74f285767afe
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Sep 18 16:38:03 2010 -0700
+
+ Add missing UNWIND entry; disables .pad on non-EABI targets.
+
+commit 6b452bafaec498df975ba8ac4c99de174e5f74f7
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Sep 18 16:21:32 2010 -0700
+
+ Apple assembler support; fixed most gas/ELF-isms.
+
+commit 8ddac835b6f8b54ede764d0ea977dee4c82e2d67
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Sep 18 15:38:06 2010 -0700
+
+ Fix placement of the __APPLE__ macro.
+
+commit 69043d02936bb0579ac59b4ee1ed8dec38c38db7
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Sep 18 15:32:08 2010 -0700
+
+ Work-around libffi's FP ABI detection.
+
+ On iOS, we must use the AAPCS floating point return value calling
+ conventions. libffi's ARM implementation will only use these conventions
+ if __SOFTFP__ is defined, which is not the case when GCC's
+ -mfloat-abi defaults to 'softfp' instead of 'soft'. To work around this
+ we manually define __SOFTFP__ for Apple platforms in the ARM-specific
+ sysv.S.
+
+ See also:
+ http://developer.apple.com/library/ios/#documentation/Xcode/Conceptual/iPhoneOSABIReference/Introduction/Introduction.html
+ http://infocenter.arm.com/help/topic/com.arm.doc.ihi0042d/IHI0042D_aapcs.pdf
+
+commit a82e6c354ea805114642a6e440abd0832cb1d23f
+Author: Landon Fuller <landonf@bikemonkey.org>
+Date: Sat Sep 18 14:44:24 2010 -0700
+
+ Add a stub iOS build script to drive autoconf
+
+commit 84e8de6e9fc19388f6f1102c013b7d0d52940ecc
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Aug 6 01:35:12 2010 -0400
+
+ Restore execute permissions
+
+commit 3aeecc9eb1a6feba6549849cdd335c926415a4fc
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Aug 5 15:19:00 2010 -0400
+
+ Fix win64-struct-args patch
+
+commit 00d0b59cd13f89ab8b44bd894eb7f0a131fcb472
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Aug 5 14:56:53 2010 -0400
+
+ Fix debug build for windows
+
+commit bda487e87064f27965155459a62dc52a744778d0
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Aug 5 09:02:41 2010 -0400
+
+ Don't use -safeseh with ml64
+
+commit c1d28ba8d5029795af313ffeb81c97efc6d4c847
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Aug 5 08:48:16 2010 -0400
+
+ stdcall-x86-closure-fix
+
+commit 5feacad4a56c85b3f23a267a30b2cf424cd59548
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Aug 5 08:30:04 2010 -0400
+
+ define generic symbols carefully
+
+commit 10ea848900bc3018ac213cef52b44cacbe5cbebc
+Author: Anthony Green <green@moxielogic.com>
+Date: Thu Aug 5 08:24:27 2010 -0400
+
+ don't copy win64 struct args
+
+commit d14178be4c49c3ada44a9fe9efe11d444372ddab
+Author: Anthony Green <green@moxielogic.com>
+Date: Fri Jul 23 09:14:00 2010 -0400
+
+ FFI_LAST_ABI fix
+
+commit 3f5b1375ab1e2b8e3d593e21b27097a4a50f9b83
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Jul 12 14:39:18 2010 -0400
+
+ rebase
+
+commit eaf444eabc4c78703c0f98ac0197b1619c1b1bef
+Author: Anthony Green <green@moxielogic.com>
+Date: Sat Jul 10 08:59:09 2010 -0400
+
+ Fix selinux test
+
+commit 630974152247f100ece4d44f10c3721bb4599fbf
+Author: Anthony Green <green@gmachine.(none)>
+Date: Wed May 5 20:14:56 2010 -0400
+
+ Micharl Kohler's spelling fixes
+
+commit 9dc9a293f3d4589fcaf02dd4288c8cebaefa508e
+Author: Anthony Green <green@gmachine.(none)>
+Date: Tue Apr 13 10:33:52 2010 -0400
+
+ Rebase to latest GCC sources
+
+commit f2c2a4fce9b3eca9f39b4f3545118bc256da4a73
+Author: Anthony Green <green@gmachine.(none)>
+Date: Tue Apr 13 10:19:28 2010 -0400
+
+ Remove warnings and add OS/2 support
+
+commit c0b69e57d529e33d18b658cc5572a21e3663247c
+Author: Anthony Green <green@gmachine.(none)>
+Date: Tue Mar 30 08:30:22 2010 -0400
+
+ Dan Witte's windows build fixes.
+
+commit 59a259f4d348f593b45f452309f4d020a28051c4
+Author: Anthony Green <green@gmachine.(none)>
+Date: Mon Mar 15 05:57:51 2010 -0400
+
+ Remove junk file
+
+commit 3de1eb36d37a66829e606421939874d0d60d816d
+Author: Anthony Green <green@gmachine.(none)>
+Date: Mon Mar 15 05:57:24 2010 -0400
+
+ fix-comments patch
+
+commit c3813b6d7f8a777700f4c5862190c0db148d4de8
+Author: Anthony Green <green@gmachine.(none)>
+Date: Tue Jan 26 16:48:56 2010 -0500
+
+ Rebuild Makefiles with automake 1.11.1 for CVE-2009-4029.
+
+commit 8d27f68baa365bf883b6053c5f6bc819646d5434
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Jan 15 11:35:37 2010 -0500
+
+ Mention recent changes in README
+
+commit ff3cd68b8cf2d9a28cad7aa9beff46236eacec8c
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Jan 15 11:27:24 2010 -0500
+
+ Add msvc.sh wrapper
+
+commit cadeba6cb53414a1253582f1719c286665de7b6c
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Jan 15 10:46:51 2010 -0500
+
+ Microsoft Visual C port
+
+commit 0739e7dc00db766eb64f502ec4137b817638c9a1
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Jan 15 09:48:33 2010 -0500
+
+ Add x86 Sun Studio compiler support
+
+commit edfdfd2e85b8d01d2455934f1d7f4d7eb2f3cf1c
+Author: Anthony Green <green@gmachine.(none)>
+Date: Wed Jan 13 02:56:19 2010 -0500
+
+ Add closure example doc
+
+commit 7b7a42f221cf171e8d09df34cac6dc1fd8458cc3
+Author: Anthony Green <green@gmachine.(none)>
+Date: Tue Jan 12 09:14:14 2010 -0500
+
+ Rebase from GCC
+
+commit 4b18d1f73dc7733137869e4ab5725cb90c1c8fde
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Jan 1 10:24:27 2010 -0500
+
+ Add x86-64 MingW to README
+
+commit c3042afaf3f84abbbe9c91bf9bc9896b0d9eb003
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Jan 1 08:08:02 2010 -0500
+
+ Reset quilt patches post 3.0.9 merge with GCC
+
+commit b0304e9679bdfec6ac45a57b5c96542697249418
+Author: Anthony Green <green@gmachine.(none)>
+Date: Thu Dec 31 11:32:40 2009 -0500
+
+ Update version
+
+commit 2e7e03d014d9c9bf40e97ce75cba089ad052fa6b
+Author: Anthony Green <green@gmachine.(none)>
+Date: Thu Dec 31 07:43:22 2009 -0500
+
+ Final updates before 3.0.9
+
+commit aea706c52825c8eee677ffa7fdbdd3aed1725492
+Author: Anthony Green <green@gmachine.(none)>
+Date: Tue Dec 29 10:09:31 2009 -0500
+
+ really 3.0.9rc12
+
+commit 0cfe60e9d13f132b88995cfee41f2156344f6fa2
+Author: Anthony Green <green@gmachine.(none)>
+Date: Tue Dec 29 10:06:04 2009 -0500
+
+ 3.0.9rc12
+
+commit 14e2e92e8645804b6940b3e96c98e9f7f384a6b2
+Author: Anthony Green <green@gmachine.(none)>
+Date: Sun Dec 27 21:03:33 2009 -0500
+
+ 3.0.9rc11
+
+commit 884402787bf8eaf7ec207085037cf8ace2f660ec
+Author: Anthony Green <green@gmachine.(none)>
+Date: Sat Dec 26 12:57:23 2009 -0500
+
+ HPUX support and avr32 test fixes.
+
+commit 01c78756aff22efb1f122f8e93e068d7bf2185c7
+Author: Anthony Green <green@gmachine.(none)>
+Date: Sat Dec 26 10:05:18 2009 -0500
+
+ 3.0.9rc9
+
+commit 70868464651320268d79c6894db5a50fdc11032a
+Author: Anthony Green <green@gmachine.(none)>
+Date: Sat Dec 26 09:58:03 2009 -0500
+
+ Remove xfails for mips and arm
+
+commit 838d4ad920ec85cf5ca3b511221d67f6d9a99024
+Author: Anthony Green <green@gmachine.(none)>
+Date: Sat Dec 26 09:57:27 2009 -0500
+
+ Remove a bunch of xfails.
+
+commit 7e37eaaf772f48906e69618c773b0a36c3927de9
+Author: Anthony Green <green@gmachine.(none)>
+Date: Sat Dec 26 07:46:50 2009 -0500
+
+ Fix huge_struct for solaris
+
+commit 07cc7a37194bc34064ebed7f2724333a798411c8
+Author: Anthony Green <green@gmachine.(none)>
+Date: Sat Dec 26 07:23:04 2009 -0500
+
+ 3.0.9rc8
+
+commit 2b9be16ffabc81326128bc1bbdddff8ddc5d13d3
+Author: Anthony Green <green@gmachine.(none)>
+Date: Sat Dec 26 07:04:45 2009 -0500
+
+ 3.0.9rc8
+
+commit 9458d88f676e9a21ab8993a54e16754b11687419
+Author: Anthony Green <green@gmachine.(none)>
+Date: Sat Dec 26 07:02:27 2009 -0500
+
+ Rebase from GCC
+
+commit 6a3412417593f068a04dc6163f4269cb295ad5ca
+Author: Anthony Green <green@gmachine.(none)>
+Date: Sat Dec 26 06:51:33 2009 -0500
+
+ Add Andreas Schwab's powerpc fix
+
+commit 39c8792ece1043f41f4c395a2ce71f4cf0ff4674
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Dec 25 21:52:28 2009 -0500
+
+ 3.0.9rc7
+
+commit 1d04af52e3e24db69f742064694c22f8df5cc70e
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Dec 25 09:50:36 2009 -0500
+
+ Updated some mips XFAILs
+
+commit 26e9509c9b7929bc4fcf697071699051a652b1fd
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Dec 25 02:19:23 2009 -0500
+
+ Clean up ChangeLog.libffi for older patches.
+
+commit 9c157d3215e4393777f83eb6fa801df6528f40d7
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Dec 25 02:15:40 2009 -0500
+
+ Clean up undefine_AC_ARG_VAR_PRECIOUS patch.
+
+commit d22de05b0bfc480766bc1240615ce2830eee71b8
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Dec 25 02:04:23 2009 -0500
+
+ Fix patches
+
+commit 1fe3dc7c20dc4dbd8fed0d19c8618027d44ed971
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Dec 25 01:39:00 2009 -0500
+
+ Add windows support patch.
+
+commit f7c0bc613a88f7dbc2d18b345c10fa438833c170
+Author: Anthony Green <green@gmachine.(none)>
+Date: Fri Dec 25 01:22:11 2009 -0500
+
+ 3.0.9rc6
+
+commit c7fa2da8260258c11ab1dc7ac06fb611a2c1b50f
+Author: Anthony Green <green@gmachine.(none)>
+Date: Thu Dec 24 07:22:44 2009 -0500
+
+ 3.0.9rc6
+
+commit da11bece0fde66fc0268db3a01207dda857e25d2
+Author: Anthony Green <green@gmachine.(none)>
+Date: Thu Dec 24 05:34:46 2009 -0500
+
+ Release 3.0.9rc5
+
+commit e3399b11edeab546b066bfc18574f3edb905d0dc
+Author: Anthony Green <green@gmachine.(none)>
+Date: Thu Dec 24 01:09:32 2009 -0500
+
+ Update README
+
+commit 115ab36fceee69740a01ce49bc27e1908cc237b1
+Author: Anthony Green <green@gmachine.(none)>
+Date: Thu Dec 24 00:22:00 2009 -0500
+
+ Update missing changes for 3.0.9r4.
+
+commit f8c7a245bf5a80bd7e730ec03fcad17c8dcfcb07
+Author: Anthony Green <green@gmachine.(none)>
+Date: Wed Dec 23 23:46:22 2009 -0500
+
+ Switch to quilt. Rebase to latest GCC.
+
+commit ce806772f02387b9a74f6496a263a368bccd5d59
+Merge: cd98813 dcc1f6b
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Oct 5 00:41:35 2009 -0400
+
+ Merge branch 'master' of git@github.com:atgreen/libffi
+
+commit dcc1f6b4f1ffd2713bf68b791a13f85d455c8b1b
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Oct 5 00:29:33 2009 -0400
+
+ More clean up.
+
+commit 2829f5941a223b9d851d8ab6318318e6197d7e01
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Oct 5 00:28:03 2009 -0400
+
+ Clean up
+
+commit cd98813de517ea64041637e3e78d27a001d6d3b4
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Oct 5 00:25:29 2009 -0400
+
+ From Jens Rehsack. Fix for 64-bit AIX.
+
+commit e4a91de766acc47f6c50f13cc11719a65e23ecba
+Author: Anthony Green <green@moxielogic.com>
+Date: Mon Oct 5 00:16:17 2009 -0400
+
+ From Abdulaziz Ghuloum. Adds special case for Snow Leopard.
+
+commit 3425a763bcdaadb8b430226f427ec833afdcc96a
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Oct 4 23:57:29 2009 -0400
+
+ Fix detection of free/openbsd. From Alexis Ballier.
+
+commit 2340e7a777902de61499d47823ad8d5e0eeb6203
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Oct 4 23:53:17 2009 -0400
+
+ AVR support
+
+commit 5cbe2058c128e848446ae79fe15ee54260a90559
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Oct 4 23:53:11 2009 -0400
+
+ Initial stand-alone patch.
+
+commit c6dddbd02bad9654ed58cdb0feb360934d105dec
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Oct 4 08:11:33 2009 -0400
+
+ Initial commit
+
+commit 5ffc0c37486fb1538bccc0ca7acc807d4f1af932
+Author: Anthony Green <green@moxielogic.com>
+Date: Sun Oct 4 07:58:22 2009 -0400
+
+ Update version to 3.0.9rc1. Add more useful things to .gitignore.
+
+commit bd29f83ee9f6fa6b65adee9d3f57834f364d9887
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Sep 29 12:07:26 2009 -0400
+
+ Add .gitignore
+
+commit 9474f853f83e3f0167c1b306177321bfcc93e56d
+Author: Anthony Green <green@moxielogic.com>
+Date: Tue Sep 29 11:13:02 2009 -0400
+
+ Remove old CVSROOT files.
+
+commit 0c25275ec24bfe2c2c25a000465f0950ef9dd51b
+Author: twall <twall>
+Date: Wed Aug 19 12:57:34 2009 +0000
+
+ Apply Dave Korn's cygwin/GCC changes
+
+commit 39228c27ed3f677a95b46380a8d31602b5777e1a
+Author: aph <aph>
+Date: Tue Jun 16 18:00:47 2009 +0000
+
+ 2009-06-16 Wim Lewis <wiml@hhhh.org>
+
+ * src/powerpc/ffi.c: Avoid clobbering cr3 and cr4, which are
+ supposed to be callee-saved.
+ * src/powerpc/sysv.S (small_struct_return_value): Fix overrun of
+ return buffer for odd-size structs.
+
+commit 5e93cc704d127c2c8ae7f5d2cef621145d43e777
+Author: aph <aph>
+Date: Tue Jun 16 17:41:47 2009 +0000
+
+ 2009-06-16 Andreas Tobler <a.tobler@schweiz.org>
+
+ PR libffi/40444
+ * testsuite/lib/libffi-dg.exp (libffi_target_compile): Add
+ allow_stack_execute for Darwin.
+
+commit b509af8959dc371b92392c623522ea6f4946a71d
+Author: aph <aph>
+Date: Tue Jun 16 16:17:52 2009 +0000
+
+ 2009-06-16 Andrew Haley <aph@redhat.com>
+
+ * configure.ac (TARGETDIR): Add missing blank lines.
+ * configure: Regenerate.
+
+commit d57e96dc56ee76fbbb9b59d73aeaa92354db5ecb
+Author: aph <aph>
+Date: Tue Jun 16 09:59:02 2009 +0000
+
+ 2009-06-16 Andrew Haley <aph@redhat.com>
+
+ * testsuite/libffi.call/cls_align_sint64.c,
+ testsuite/libffi.call/cls_align_uint64.c,
+ testsuite/libffi.call/cls_longdouble_va.c,
+ testsuite/libffi.call/cls_ulonglong.c,
+ testsuite/libffi.call/return_ll1.c,
+ testsuite/libffi.call/stret_medium2.c: Fix printf format
+ specifiers.
+ * testsuite/libffi.call/huge_struct.c: Ad x86 XFAILs.
+ * testsuite/libffi.call/float2.c: Fix dg-excess-errors.
+ * testsuite/libffi.call/ffitest.h,
+ testsuite/libffi.special/ffitestcxx.h (PRIdLL, PRIuLL): Define.
+
+commit b01d6d1982c9e020507029bfd5a58a8c60d111fa
+Author: aph <aph>
+Date: Tue Jun 16 09:44:54 2009 +0000
+
+ 2009-06-16 Andrew Haley <aph@redhat.com>
+
+ * testsuite/libffi.call/err_bad_typedef.c: xfail everywhere.
+ * testsuite/libffi.call/err_bad_abi.c: Likewise.
+
+commit 35b6ded138591900a88055a8a8ac1fadc29a76d6
+Author: aph <aph>
+Date: Fri Jun 12 15:29:20 2009 +0000
+
+ 2009-06-11 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * testsuite/libffi.call/cls_longdouble_va.c: Add xfail sh*-*-linux-*.
+ * testsuite/libffi.call/err_bad_abi.c: Add xfail sh*-*-*.
+ * testsuite/libffi.call/err_bad_typedef.c: Likewise.
+
+commit acc46605f2d95d67d69398e7644610f10a157ce3
+Author: aph <aph>
+Date: Fri Jun 12 14:21:28 2009 +0000
+
+ 2009-06-12 Andrew Haley <aph@redhat.com>
+
+ * ChangeLog.libffi: testsuite/libffi.call/cls_align_sint64.c,
+ testsuite/libffi.call/cls_align_uint64.c,
+ testsuite/libffi.call/cls_ulonglong.c,
+ testsuite/libffi.call/return_ll1.c,
+ testsuite/libffi.call/stret_medium2.c: Fix printf format
+ specifiers.
+ testsuite/libffi.special/unwindtest.cc: include stdint.h.
+
+commit 16d1996ed0797bd7c11aca2b0fe7e7748751aaf6
+Author: twall <twall>
+Date: Thu Jun 11 14:27:42 2009 +0000
+
+ update changelog
+
+commit 92a515c33efe91be3cb0258f01c63aff208489c7
+Author: twall <twall>
+Date: Thu Jun 11 14:27:28 2009 +0000
+
+ use ffi_closure_alloc instead of stack-based closure
+
+commit e4363160ba9e50167f9ca0a7399d537a1d2cd0ce
+Author: twall <twall>
+Date: Thu Jun 11 14:26:23 2009 +0000
+
+ remove unused extern
+
+commit 1dc2781d2ba38f5f000ff70069d617fb21e1d2af
+Author: twall <twall>
+Date: Thu Jun 11 11:36:16 2009 +0000
+
+ remove not-yet-applied changelog entries
+
+commit bb27735fe689dac97ec0dc847ed8d3d519620109
+Author: twall <twall>
+Date: Wed Jun 10 10:42:36 2009 +0000
+
+ add win64 support
+
+commit b2a54c100c74854a409820817d54617fdda39eb8
+Author: aph <aph>
+Date: Mon Jun 8 16:50:49 2009 +0000
+
+ 2009-06-08 Andrew Haley <aph@redhat.com>
+
+ * testsuite/libffi.call/err_bad_abi.c: Add xfails.
+ * testsuite/libffi.call/cls_longdouble_va.c: Add xfails.
+ * testsuite/libffi.call/cls_dbls_struct.c: Add xfail x86_64-*-linux-*.
+ * testsuite/libffi.call/err_bad_typedef.c: Add xfails.
+
+ * testsuite/libffi.call/stret_medium2.c: Add __UNUSED__ to args.
+ * testsuite/libffi.call/stret_medium.c: Likewise.
+ * testsuite/libffi.call/stret_large2.c: Likewise.
+ * testsuite/libffi.call/stret_large.c: Likewise.
+
+commit 25723e7141f73d3736d7244b980c89d97db852b6
+Author: aph <aph>
+Date: Fri Jun 5 13:03:40 2009 +0000
+
+ 2009-06-05 Andrew Haley <aph@redhat.com>
+
+ * src/x86/win32.S (_ffi_closure_STDCALL): Import from gcc.
+
+commit 70758199c7cd41f411987360ccb302b497a56dc9
+Author: aph <aph>
+Date: Thu Jun 4 16:29:58 2009 +0000
+
+ 2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/powerpc/ffitarget.h: Fix misapplied merge from gcc.
+
+commit e8bb12563f9aa23ddf36fa6a5b92b16b5c3e1a7f
+Author: aph <aph>
+Date: Thu Jun 4 14:59:18 2009 +0000
+
+ 2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/mips/o32.S,
+ src/mips/n32.S: Fix licence formatting.
+
+commit d66a8e32c3671479e3ce0f6819673e5932ba6b7f
+Author: aph <aph>
+Date: Thu Jun 4 14:43:40 2009 +0000
+
+ 2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/x86/darwin.S: Fix licence formatting.
+ src/x86/win32.S: Likewise.
+ src/sh64/sysv.S: Likewise.
+ src/sh/sysv.S: Likewise.
+
+commit 7c3b7fd6b5db746b5b09a718f3044f811372f941
+Author: aph <aph>
+Date: Thu Jun 4 14:39:20 2009 +0000
+
+ 2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/sh64/ffi.c: Remove lint directives. Was missing from merge
+ of Andreas Tobler's patch from 2006-04-22.
+
+commit 1a2f93a8b362db13638afd9fcb3f2650180bfa17
+Author: aph <aph>
+Date: Thu Jun 4 10:45:51 2009 +0000
+
+ 2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/sh/ffi.c: Apply missing hunk from Alexandre Oliva's patch of
+ 2007-03-07.
+
+commit 944c95cf7aaaaf7c5fa368cda4673dd38f45020e
+Author: aph <aph>
+Date: Wed Jun 3 17:42:56 2009 +0000
+
+ 2009-05-22 Dave Korn <dave.korn.cygwin@gmail.com>
+
+ * src/x86/win32.S (_ffi_closure_STDCALL): New function.
+ (.eh_frame): Add FDE for it.
+
+ 2009-05-22 Dave Korn <dave.korn.cygwin@gmail.com>
+
+ * configure.ac: Also check if assembler supports pc-relative
+ relocs on X86_WIN32 targets.
+ * configure: Regenerate.
+ * src/x86/win32.S (ffi_prep_args): Declare extern, not global.
+ (_ffi_call_SYSV): Add missing function type symbol .def and
+ add EH markup labels.
+ (_ffi_call_STDCALL): Likewise.
+ (_ffi_closure_SYSV): Likewise.
+ (_ffi_closure_raw_SYSV): Likewise.
+ (.eh_frame): Add hand-crafted EH data.
+
+ 2008-11-21 Eric Botcazou <ebotcazou@adacore.com>
+
+ * src/sparc/ffi.c (ffi_prep_cif_machdep): Add support for
+ signed/unsigned int8/16 return values.
+ * src/sparc/v8.S (ffi_call_v8): Likewise.
+ (ffi_closure_v8): Likewise.
+
+ 2008-03-26 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/sysv.S: Add .note.GNU-stack on Linux.
+ * src/sh64/sysv.S: Likewise.
+
+ 2008-03-26 Daniel Jacobowitz <dan@debian.org>
+
+ * src/arm/sysv.S: Fix ARM comment marker.
+
+commit 00fa972430bb1535a4b34bf029ebcad500027b0c
+Author: twall <twall>
+Date: Sat Dec 27 16:59:05 2008 +0000
+
+ properly glob-match
+
+commit f5179e6794ac35af26fe86e468b8508a7a570c55
+Author: twall <twall>
+Date: Fri Dec 26 19:06:28 2008 +0000
+
+ Mark XFAIL on longdouble tests for x86_64/mingw
+
+commit 80e2b5a749208c8a18f994ec5bee84594d051cc8
+Author: twall <twall>
+Date: Mon Dec 22 15:21:15 2008 +0000
+
+ clean up tests for win64 use
+
+commit 7063d9996f742576095c7b0eb5016c0f9a670aec
+Author: green <green>
+Date: Fri Dec 19 16:13:46 2008 +0000
+
+ Version 3.0.8 with x86-solaris support
+
+commit bdfeb13f0df0a63b19d62597517237b54d92228b
+Author: green <green>
+Date: Fri Dec 19 15:47:44 2008 +0000
+
+ Bump to 3.0.7
+
+commit 69205de17d6ac4c11d4ba92d6a5b40a0c5f246b2
+Author: green <green>
+Date: Thu Jul 24 18:03:48 2008 +0000
+
+ Many test fixes (failures due to excessive compiler warnings).
+
+commit 260d513fea00b3613fe957a44a157fe72c4ca29e
+Author: green <green>
+Date: Thu Jul 17 13:13:52 2008 +0000
+
+ Version 3.0.6. sh/sh64 fixes.
+
+commit 3704031875feabb74e3655ed03cff4c2b3c76ac6
+Author: green <green>
+Date: Thu Apr 3 18:57:57 2008 +0000
+
+ Rev 3.0.5.
+
+commit 8406f5f48f7f58a1c982a93a95d521cf82b3241f
+Author: green <green>
+Date: Thu Apr 3 18:57:34 2008 +0000
+
+ 3.0.5
+
+commit 23a9e73212b62f9684cedb0ce70e92c59cfdaffa
+Author: green <green>
+Date: Wed Mar 5 00:07:02 2008 +0000
+
+ 2008-03-04 Anthony Green <green@redhat.com>
+ Blake Chaffin
+ hos@tamanegi.org
+
+ * testsuite/libffi.call/cls_align_longdouble_split2.c
+ testsuite/libffi.call/cls_align_longdouble_split.c
+ testsuite/libffi.call/cls_dbls_struct.c
+ testsuite/libffi.call/cls_double_va.c
+ testsuite/libffi.call/cls_longdouble.c
+ testsuite/libffi.call/cls_longdouble_va.c
+ testsuite/libffi.call/cls_pointer.c
+ testsuite/libffi.call/cls_pointer_stack.c
+ testsuite/libffi.call/err_bad_abi.c
+ testsuite/libffi.call/err_bad_typedef.c
+ testsuite/libffi.call/huge_struct.c
+ testsuite/libffi.call/stret_large2.c
+ testsuite/libffi.call/stret_large.c
+ testsuite/libffi.call/stret_medium2.c
+ testsuite/libffi.call/stret_medium.c: New tests from Apple.
+
+commit 429e37d3ad653e52e75bf725c883ab79e859f89a
+Author: green <green>
+Date: Thu Feb 28 04:50:19 2008 +0000
+
+ clicky
+
+commit 51e79c428348c033314f54bcb30f7e388c59e347
+Author: green <green>
+Date: Thu Feb 28 04:47:35 2008 +0000
+
+ getclicky
+
+commit affcab04e280efeace45a72c4dc6152c0e4f1b7f
+Author: green <green>
+Date: Tue Feb 26 19:01:53 2008 +0000
+
+ 2008-02-26 Jakub Jelinek <jakub@redhat.com>
+ Anthony Green <green@redhat.com>
+
+ * src/alpha/osf.S: Add .note.GNU-stack on Linux.
+ * src/s390/sysv.S: Likewise.
+ * src/powerpc/linux64.S: Likewise.
+ * src/powerpc/linux64_closure.S: Likewise.
+ * src/powerpc/ppc_closure.S: Likewise.
+ * src/powerpc/sysv.S: Likewise.
+ * src/x86/unix64.S: Likewise.
+ * src/x86/sysv.S: Likewise.
+ * src/sparc/v8.S: Likewise.
+ * src/sparc/v9.S: Likewise.
+ * src/m68k/sysv.S: Likewise.
+ * src/ia64/unix.S: Likewise.
+ * src/arm/sysv.S: Likewise.
+
+commit 59689d5522c159a3ac967adb6b891cf5f22c890f
+Author: green <green>
+Date: Tue Feb 26 17:40:51 2008 +0000
+
+ 2008-02-26 Anthony Green <green@redhat.com>
+ Thomas Heller <theller@ctypes.org>
+
+ * src/x86/ffi.c (ffi_closure_SYSV_inner): Change C++ comment to C
+ comment.
+
+commit b13c84cf4668828ff8429ba4a2f94cd1eb574ae0
+Author: green <green>
+Date: Tue Feb 26 17:38:15 2008 +0000
+
+ 2008-02-26 Anthony Green <green@redhat.org>
+ Thomas Heller <theller@ctypes.org>
+
+ * include/ffi.h.in: Change void (*)() to void (*)(void).
+
+commit 265289f679ffd24a88ae1aa2cef0e4aa14703cd8
+Author: green <green>
+Date: Tue Feb 26 17:34:36 2008 +0000
+
+ 2008-02-26 Anthony Green <green@spindazzle.org>
+
+ * src/alpha/ffi.c: Change void (*)() to void (*)(void).
+ src/alpha/osf.S, src/arm/ffi.c, src/frv/ffi.c, src/ia64/ffi.c,
+ src/ia64/unix.S, src/java_raw_api.c, src/m32r/ffi.c,
+ src/mips/ffi.c, src/pa/ffi.c, src/pa/hpux32.S, src/pa/linux.S,
+ src/powerpc/ffi.c, src/powerpc/ffi_darwin.c, src/raw_api.c,
+ src/s390/ffi.c, src/sh/ffi.c, src/sh64/ffi.c, src/sparc/ffi.c,
+ src/x86/ffi.c, src/x86/unix64.S, src/x86/darwin64.S,> src/x86/ffi64.c: Ditto.
+
+commit fb5036cd6d0f909918e90f7d2d9fd80d46682d5d
+Author: green <green>
+Date: Sun Feb 24 17:25:25 2008 +0000
+
+ fix date
+
+commit 40bec108e7d0181e6c9928aa7a33187bcc0f3d6f
+Author: green <green>
+Date: Sun Feb 24 17:25:02 2008 +0000
+
+ New release
+
+commit b922048fa82ea109a4af269ee47bbc2a586bbac2
+Author: green <green>
+Date: Sun Feb 24 17:24:00 2008 +0000
+
+ 2008-02-24 Anthony Green <green@spindazzle.org>
+
+ * configure.ac: Accept openbsd*, not just openbsd.
+ Bump version to 3.0.4.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision.
+ * README: Update for new release.
+
+commit affca4b92d06e5554784c7e9b233029ef83f7d8a
+Author: green <green>
+Date: Fri Feb 22 21:53:29 2008 +0000
+
+ sync readme with web page.
+
+commit 3e53d8752ea74859b4c64fbbf935e62a937c4d78
+Author: green <green>
+Date: Fri Feb 22 21:52:38 2008 +0000
+
+ New release
+
+commit 4d92f6c8e78fe084be65f3e8b58b859901ba796d
+Author: green <green>
+Date: Fri Feb 22 21:49:46 2008 +0000
+
+ 2008-02-22 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 3.0.3.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision.
+ * README: Update for new release. Clean up test docs.
+
+commit 0e185fa11a01f816824ba2687ed3715ab6219bef
+Author: green <green>
+Date: Fri Feb 22 21:43:18 2008 +0000
+
+ Update configure script.
+
+commit f73986bd211cfbbaa593d1309504d0dc68626191
+Author: green <green>
+Date: Fri Feb 22 21:40:53 2008 +0000
+
+ 2008-02-22 Bjoern Koenig <bkoenig@alpha-tierchen.de>
+ Andreas Tobler <a.tobler@schweiz.org>
+
+ * configure.ac: Add amd64-*-freebsd* target.
+ * configure: Regenerate.
+
+commit 0208f68fe5de30c33e7f70ebc281635917013f5a
+Author: green <green>
+Date: Fri Feb 22 21:15:44 2008 +0000
+
+ 2008-02-22 Thomas Heller <theller@ctypes.org>
+
+ * configure.ac: Add x86 OpenBSD support.
+ * configure: Rebuilt.
+
+commit 01adb0e638a86cf0d5e668ed8e08be9b0cd2505f
+Author: green <green>
+Date: Thu Feb 21 16:17:26 2008 +0000
+
+ Fix README.
+
+commit 1edd4563225981a14f7d4fb9919b1ed88e38082f
+Author: green <green>
+Date: Thu Feb 21 13:39:01 2008 +0000
+
+ 3.0.2
+
+commit c9b542800864e2204db6e83f3843a17813ba6165
+Author: green <green>
+Date: Thu Feb 21 13:36:43 2008 +0000
+
+ add missing file
+
+commit d5fa5633d5c8d3c212a2267cfa38fba4091baa2c
+Author: green <green>
+Date: Thu Feb 21 13:36:19 2008 +0000
+
+ 2008-02-21 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 3.0.2.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision.
+ * README: Update for new release.
+
+ 2008-02-21 Björn König <bkoenig@alpha-tierchen.de>
+
+ * src/x86/freebsd.S: New file.
+ * configure.ac: Add x86 FreeBSD support.
+ * Makefile.am: Ditto.
+
+commit ac35bfc6fcadd8880c1efce36724820f9074b318
+Author: green <green>
+Date: Sat Feb 16 01:03:56 2008 +0000
+
+ Updated
+
+commit f7942975fee7b0162647dd79e2652615b737e98e
+Author: green <green>
+Date: Sat Feb 16 01:02:00 2008 +0000
+
+ 2008-02-15 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 3.0.1.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision.
+ * README: Update for new release.
+
+ 2008-02-15 David Daney <ddaney@avtrex.com>
+
+ * src/mips/ffi.c: Remove extra '>' from include directive.
+ (ffi_prep_closure_loc): Use clear_location instead of tramp.
+
+commit 59aa6bb1bfc86a610ac1a8b123443efd75854dd1
+Author: green <green>
+Date: Fri Feb 15 20:52:26 2008 +0000
+
+ Add more platforms.
+
+commit 45a45ab99074448be0ae1a8d2ade50d28b60f8de
+Author: green <green>
+Date: Fri Feb 15 19:16:36 2008 +0000
+
+ 3.0 notes
+
+commit 4db74cbea888c9f1251b85baf00d99b83d3b994d
+Author: green <green>
+Date: Fri Feb 15 19:10:26 2008 +0000
+
+ Update
+
+commit c3e1101ffabf44d8a2ee46e03ba9ab582050a825
+Author: green <green>
+Date: Fri Feb 15 18:43:40 2008 +0000
+
+ 2008-02-15 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 3.0.0,
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+
+ 2008-02-15 David Daney <ddaney@avtrex.com>
+
+ * src/mips/ffi.c (USE__BUILTIN___CLEAR_CACHE):
+ Define (conditionally), and use it to include cachectl.h.
+ (ffi_prep_closure_loc): Fix cache flushing.
+ * src/mips/ffitarget.h (_ABIN32, _ABI64, _ABIO32): Define.
+
+commit 7e0cc12e9233ad285db41ce8dbdda61ed2a7fb06
+Author: green <green>
+Date: Fri Feb 15 15:51:03 2008 +0000
+
+ New release
+
+commit 2d7dc885ec40d53866f29984d595511942c8b686
+Author: green <green>
+Date: Fri Feb 15 15:30:26 2008 +0000
+
+ * man/ffi_call.3, man/ffi_prep_cif.3, man/ffi.3:
+ Update dates and remove all references to ffi_prep_closure.
+ * configure.ac: Bump version to 2.99.9.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+
+commit a0525f03eeaaed33b1eac80e0c016455cee3615d
+Author: green <green>
+Date: Fri Feb 15 15:14:30 2008 +0000
+
+ New release.
+
+commit 2b30dfb3146ee26ad956d00ee05eb835ca1a95b4
+Author: green <green>
+Date: Fri Feb 15 15:12:43 2008 +0000
+
+ * man/ffi_prep_closure.3: Delete.
+ * man/Makefile.am (EXTRA_DIST): Remove ffi_prep_closure.3.
+ (man_MANS): Ditto.
+ * man/Makefile.in: Rebuilt.
+ * configure.ac: Bump version to 2.99.8.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+
+commit bf41e64840ebcb6cc31a6f028253c1fde82705d8
+Author: green <green>
+Date: Fri Feb 15 01:56:50 2008 +0000
+
+ Update.
+
+commit 4d39ddee677bbb61d621893b91e11eac5e7c4af7
+Author: green <green>
+Date: Fri Feb 15 01:24:06 2008 +0000
+
+ * configure.ac: Bump version to 2.99.7.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * include/ffi.h.in LICENSE src/debug.c src/closures.c
+ src/ffitest.c src/s390/sysv.S src/s390/ffitarget.h
+ src/types.c src/m68k/ffitarget.h src/raw_api.c src/frv/ffi.c
+ src/frv/ffitarget.h src/sh/ffi.c src/sh/sysv.S
+ src/sh/ffitarget.h src/powerpc/ffitarget.h src/pa/ffi.c
+ src/pa/ffitarget.h src/pa/linux.S src/java_raw_api.c
+ src/cris/ffitarget.h src/x86/ffi.c src/x86/sysv.S
+ src/x86/unix64.S src/x86/win32.S src/x86/ffitarget.h
+ src/x86/ffi64.c src/x86/darwin.S src/ia64/ffi.c
+ src/ia64/ffitarget.h src/ia64/ia64_flags.h src/ia64/unix.S
+ src/sparc/ffi.c src/sparc/v9.S src/sparc/ffitarget.h
+ src/sparc/v8.S src/alpha/ffi.c src/alpha/ffitarget.h
+ src/alpha/osf.S src/sh64/ffi.c src/sh64/sysv.S
+ src/sh64/ffitarget.h src/mips/ffi.c src/mips/ffitarget.h
+ src/mips/n32.S src/mips/o32.S src/arm/ffi.c src/arm/sysv.S
+ src/arm/ffitarget.h src/prep_cif.c: Update license text.
+
+commit d58b032b41a12bd3d72148da6822ab59dd698ff9
+Author: green <green>
+Date: Fri Feb 15 00:59:25 2008 +0000
+
+ New release
+
+commit 91e5478df6d5ac63efbb10f025807b4606afab56
+Author: green <green>
+Date: Fri Feb 15 00:50:30 2008 +0000
+
+ Update supported platforms. Bump version.
+
+commit bd0768f877c8f7fd0d36af2191b203d4d057b1ce
+Author: green <green>
+Date: Fri Feb 15 00:45:33 2008 +0000
+
+ * configure.ac: Bump version to 2.99.5.
+ * configure: Rebuilt.
+ * Makefile.am (EXTRA_DIST): Add darwin64.S
+ * Makefile.in: Rebuilt.
+ * testsuite/lib/libffi-dg.exp: Remove libstdc++ bits from GCC tree.
+ * LICENSE: Update WARRANTY.
+
+commit 49d345f767bd2cfee951bceaab6a1a07986cf293
+Author: green <green>
+Date: Thu Feb 14 23:43:27 2008 +0000
+
+ update license reference
+
+commit 12ac48fc79b515db7c9accd9fcaa87b0dcefccdb
+Author: green <green>
+Date: Thu Feb 14 23:42:08 2008 +0000
+
+ Update WARRANTY
+
+commit 6b91c41da87e78552f2990dfc504a0a3349f340b
+Author: green <green>
+Date: Thu Feb 14 23:38:27 2008 +0000
+
+ fix tarball reference
+
+commit 2b59579e3533334bee4788e076b4e520c2ab518c
+Author: green <green>
+Date: Thu Feb 14 23:35:58 2008 +0000
+
+ First update in 5 years!
+
+commit 6cbdf3f3a3777a93382a2d508ddef1c353ff0955
+Author: green <green>
+Date: Thu Feb 14 22:44:06 2008 +0000
+
+ Fix .pc file bug and bump version
+
+commit 1d1dc81104b209df3cfef0840735c59efae2f655
+Author: green <green>
+Date: Thu Feb 14 22:03:37 2008 +0000
+
+ Add man files and info file. Update README. Tag as 2.99.3.
+
+commit f045a2367f793fa8b01534cf2e25bcc46afc8fa1
+Author: tromey <tromey>
+Date: Thu Feb 14 20:46:57 2008 +0000
+
+ Move entry from ChangeLog to ChangeLog.libffi
+
+commit 6257f07d1a9efd27fa83639cfba281f5d3188731
+Author: tromey <tromey>
+Date: Thu Feb 14 20:33:17 2008 +0000
+
+ * aclocal.m4, Makefile.in, configure, fficonfig.h.in: Rebuilt.
+ * mdate-sh, texinfo.tex: New files.
+ * Makefile.am (info_TEXINFOS): New variable.
+ * doc/libffi.texi: New file.
+ * doc/version.texi: Likewise.
+
+commit 4232af563c5509c3760a33e3684a2b958be755e1
+Author: green <green>
+Date: Thu Feb 14 16:19:21 2008 +0000
+
+ * Makefile.am (AM_CFLAGS): Don't compile with -D.
+ (lib_LTLIBRARIES): Define.
+ (toolexeclib_LIBRARIES): Undefine.
+ * Makefile.in: Rebuilt.
+ * configure.ac: Reset version to 2.99.1.
+ * configure.in: Rebuilt.
+
+commit 961543615c31f092b578a4b4cda914db64f9d0fa
+Author: green <green>
+Date: Thu Feb 14 15:57:40 2008 +0000
+
+ Fix typo.
+
+commit aeb0abab87222f637fbf352d4effd3b76b52ed26
+Author: green <green>
+Date: Thu Feb 14 15:54:27 2008 +0000
+
+ * libffi.pc.in: Usse @PACKAGE_NAME@ and @PACKAGE_VERSION@.
+ * configure.ac: Reset version to 2.99.1.
+ * configure.in: Rebuilt.
+ * Makefile.am (EXTRA_DIST): Add ChangeLog.libffi.
+ * Makefile.in: Rebuilt.
+ * LICENSE: Update copyright notice.
+
+commit 77fe243556433eae119d8bd7469bfccdd5bd8a1a
+Author: green <green>
+Date: Thu Feb 14 15:37:00 2008 +0000
+
+ Fix make dist again
+
+commit d4970cf4529459bf0f0e43c602cac396786c6802
+Author: green <green>
+Date: Thu Feb 14 15:18:56 2008 +0000
+
+ Fix make dist
+
+commit f0b1462f2d3024922ad71421bd5c4311fcb16da5
+Author: green <green>
+Date: Thu Feb 14 15:01:41 2008 +0000
+
+ Use pkgconfig. Increment libtool CURRENT version.
+
+commit 27e52f33baa069012a5adb2a3807f9ca1f2165ab
+Author: green <green>
+Date: Sun Feb 3 13:59:48 2008 +0000
+
+ Fix header installs when using DESTDIR.
+
+commit fadab28eb6e33fb6dcdd7b9323e147142216d548
+Author: twall <twall>
+Date: Sun Feb 3 12:32:22 2008 +0000
+
+ update changelog
+
+commit b5e44c8dfa92c87b99762c303cf5574a16db8f27
+Author: twall <twall>
+Date: Sun Feb 3 01:12:32 2008 +0000
+
+ offset from code base address, not data base address
+
+commit f359848d1a995c0e44566d815f218729dc996e22
+Author: green <green>
+Date: Fri Feb 1 21:29:43 2008 +0000
+
+ Fix header installs.
+
+commit c30df49e157c7bfc8e19e3f8a72b9464fe225e54
+Author: green <green>
+Date: Fri Feb 1 21:13:55 2008 +0000
+
+ Revert my broken changes to twall's patch.
+
+commit 675561bb9aa0732c76698df10dd3007b5d0ec759
+Author: green <green>
+Date: Thu Jan 31 13:44:25 2008 +0000
+
+ Fix make dist .
+
+commit abc0bbf3813dc43e23d4c23e6fe794dbf287639b
+Author: green <green>
+Date: Thu Jan 31 11:58:57 2008 +0000
+
+ Add Tim Wall's x86 windows patch.
+
+commit e332366d15a31198735b593ec8f7fc0558d783b8
+Author: green <green>
+Date: Wed Jan 30 13:21:02 2008 +0000
+
+ Add HJ's -fomit-frame-pointer struct return fix
+
+commit d4204240392af5b7750a08671b08e9c22dff5e93
+Author: green <green>
+Date: Wed Jan 30 12:42:34 2008 +0000
+
+ Clean up for new automake.
+
+commit f4932dd020df574637c9fb3fc1bb18e5a8f304cc
+Author: green <green>
+Date: Wed Jan 30 12:40:25 2008 +0000
+
+ Fixes to run testsuite
+
+commit 085520ddc8db6a916bfc416b871fcb2d00074d40
+Author: green <green>
+Date: Tue Jan 29 15:16:43 2008 +0000
+
+ New files from gcc tree.
+
+commit 77175b3f7234e4875a4ef554ed1fe9fdc4133794
+Author: green <green>
+Date: Tue Jan 29 15:15:20 2008 +0000
+
+ Latest gcc svn sources
+
+commit 2544e45a0b2b634053df02da3a2ed9680eeed2a1
+Author: green <green>
+Date: Tue Jan 29 14:28:13 2008 +0000
+
+ Install ffitarget.h in $prefix/include.
+
+commit 6002211b1cc4daeb587d054b4f83968bda2c981e
+Author: green <green>
+Date: Tue Jan 29 12:30:10 2008 +0000
+
+ Add new files.
+
+commit ccabd2b16be883cd03e5f0cd88ccfdd6ca39239d
+Author: green <green>
+Date: Tue Jan 29 12:28:15 2008 +0000
+
+ Merge from gcc
+
+commit e680ecfbfca1da8d1823e48bc89b8375e66e128b
+Author: tromey <tromey>
+Date: Sun Dec 24 23:12:15 2006 +0000
+
+ Pulled in libffi from gcc trunk.
+ Fixed build and install for standalone use.
+
+commit e7ba08965942ce872fdbc69f70f9848cc3d0bad6
+Author: root <root>
+Date: Sun Jun 4 23:22:24 2006 +0000
+
+ sourcware.org
+
+commit 0cd4aa24e21aaa964dfbdebc25ec5c8188049375
+Author: root <root>
+Date: Sun May 30 01:51:57 2004 +0000
+
+ Add LockDir
+
+commit 5826120fbd940d26cca76ed2522187505581e1ed
+Author: green <green>
+Date: Tue Nov 4 06:09:08 2003 +0000
+
+ Add link to Gianni's web site.
+
+commit 220aa4b27db42d7ffaac5056000d5179f00d5ea3
+Author: jsm <jsm>
+Date: Tue Jan 21 08:07:42 2003 +0000
+
+ Newer, better, increased from before! (list of acceptable anon usernames)
+
+commit 1c3adc892cc1403dc4d3d7003a2385899836612e
+Author: green <green>
+Date: Fri Dec 6 01:28:03 2002 +0000
+
+ Fixed Cygnus references.
+
+commit 4af66bb62fab9a8e318af3bf01e5486596a0c8d4
+Author: green <green>
+Date: Sun Oct 21 19:18:42 2001 +0000
+
+ Testsuite fixes.
+
+commit 5435965f9015ce40584c98d3816c3d05e7de1d21
+Author: green <green>
+Date: Mon Apr 23 00:32:03 2001 +0000
+
+ * include/ffi_common.h: Delete, after moving contents to...
+ * include/ffi_private.h: Subsume contents of ffi_common.h.
+ * include/Makefile.am (noinst_HEADERS): Remove ffi_common.h.
+ * include/Makefile.in: Rebuilt.
+ * arm/ffi.c, m68k/ffi.c, mips/ffi.c, powerpc/ffi.c, s390/ffi.c,
+ ia64/ffi.c: Include ffi_private.h, not ffi_common.h.
+ * alpha/ffi.c, sparc/ffi.c, x86/ffi.c: Don't include ffi_common.h.
+ * types.c, raw_api.c, java_raw_api.c, prep_cif.c: Don't include
+ ffi_common.h.
+ * debug.c: Include ffi_private.h instead of ffi_common.h.
+
+ * mips/ffi.c (calc_n32_struct_flags): Make static.
+ (FIX_ARGP): Remove call to debugging routine ffi_stop_here.
+
+ * mips/n32.S: Include ffi_private.h.
+ * mips/o32.S: Include ffi_private.h.
+
+commit 6fdb7de0fe3b7385e1fd78812ae69d9b3069d994
+Author: green <green>
+Date: Sun Apr 22 19:38:34 2001 +0000
+
+ * README: Update some comments.
+
+ * Makefile.am (SUBDIRS): Add include so ffi.h gets installed.
+ * Makefile.in: Rebuilt.
+
+ * include/ffi.h: Change ALPHA to __alpha__ and SPARC to __sparc__.
+ * types.c: Ditto.
+ * prep_cif.c (ffi_prep_cif): Ditto.
+
+ * alpha/ffi.c, alpha/osf.S, sparc/ffi.c, sparc/v8.S, sparc/v9.S:
+ Include ffi_private.h.
+
+ * include/ffi_private.h (FFI_TYPE_LAST): Define.
+
+commit bc7144b01b9707ef35f1a2e3e6996e005e82953a
+Author: green <green>
+Date: Sun Apr 22 18:28:36 2001 +0000
+
+ Moved files from old home
+
+commit e57279831e20368c1aa1d2b35462b8629be73959
+Author: green <green>
+Date: Sun Apr 22 18:23:47 2001 +0000
+
+ These are dead.
+
+commit 7247436b5fe71767b29dc02b4da0fe18b08082e6
+Author: green <green>
+Date: Sun Apr 22 18:22:43 2001 +0000
+
+ All these files live somewhere else now.
+
+commit a8b0d40ff908e275028f676870c31d0d70274a98
+Author: green <green>
+Date: Sun Apr 22 18:17:14 2001 +0000
+
+ Many changes. Not quite there yet.
+
+commit f893d2273355710a290a26faebf5f12c3a34d0e3
+Author: green <green>
+Date: Sun Apr 22 18:13:22 2001 +0000
+
+ Moved m68k files
+
+commit 688ddfeced89cbb9d37b53005e1f7f2b9c78a8d7
+Author: green <green>
+Date: Sun Apr 22 18:12:33 2001 +0000
+
+ New, target indepentent, header
+
+commit f9e40776d488d5ecf43b3ae21444a1a2f6eca528
+Author: green <green>
+Date: Sun Apr 22 18:11:57 2001 +0000
+
+ Many changes.
+
+commit 8c1d2eb47f6bc314c431b75c85c107e8e43c4a76
+Author: green <green>
+Date: Sun Apr 22 18:10:47 2001 +0000
+
+ Many changes
+
+commit 1359dfc6582680a158b3caa3efb7a368da4aa12d
+Author: green <green>
+Date: Sun Apr 22 18:10:20 2001 +0000
+
+ Moved ia64 files
+
+commit 6e2de5eee316a4579869aff50c7c5f6f478582d8
+Author: green <green>
+Date: Sun Apr 22 18:08:11 2001 +0000
+
+ Moved arm files
+
+commit 8807355af34cba8ffe87aee51152dfccec2771fa
+Author: green <green>
+Date: Mon Apr 9 00:58:38 2001 +0000
+
+ Many many updates. Merge from gcc and then some.
+
+commit f7e9f91adec4ff1c2e7a13b3de81d2c5a3f55e7e
+Author: green <green>
+Date: Mon Apr 17 03:32:37 2000 +0000
+
+ Mnay fixes.
+
+commit c4860de618f4956283f5c8230a2544e403dfe390
+Author: green <green>
+Date: Mon Apr 17 03:18:46 2000 +0000
+
+ Merge from libgcj. Merged patches from net. See ChangeLog for details.
+
+commit c578b58314990c3853429297c38ba14015fec5fa
+Author: jsm <jsm>
+Date: Sat Oct 9 20:18:16 1999 +0000
+
+ 1999-10-09 Jason Molenda (jsm@bugshack.cygnus.com)
+
+ * CVSROOT/auto_checkout, CVSROOT/commit_prep, CVSROOT/log_accum:
+ Deleted; generic versions now used for all repositories.
+
+ * CVSROOT/commitinfo, CVSROOT/loginfo: Change pathnames to
+ generic versions.
+
+ * CVSROOT/checkoutlist: Don't try to check out the removed
+ files any longer.
+
+commit acdb20051207fed7652dd9f122f65de5458c474c
+Author: jsm <jsm>
+Date: Sat Oct 9 20:18:15 1999 +0000
+
+ 1999-10-09 Jason Molenda (jsm@bugshack.cygnus.com)
+
+ * CVSROOT/auto_checkout, CVSROOT/commit_prep, CVSROOT/log_accum:
+ Deleted; generic versions now used for all repositories.
+
+ * CVSROOT/commitinfo, CVSROOT/loginfo: Change pathnames to
+ generic versions.
+
+ * CVSROOT/checkoutlist: Don't try to check out the removed
+ files any longer.
+
+commit e75be655ceedf7ab24c4e99d75eec9efeb979bc7
+Author: green <green>
+Date: Sun Aug 8 13:16:41 1999 +0000
+
+ New configury
+
+commit d6669a0dd5b266005325bbf6d5a8ff34574d809e
+Author: green <green>
+Date: Sun Aug 8 13:05:12 1999 +0000
+
+ * include/ffi.h.in: Try to work around messy header problem
+ with PACKAGE and VERSION.
+
+ * configure: Rebuilt.
+ * configure.in: Change version to 2.00-beta.
+
+ * fficonfig.h.in: Rebuilt.
+ * acconfig.h (FFI_NO_STRUCTS, FFI_NO_RAW_API): Define.
+
+ * src/x86/ffi.c (ffi_raw_call): Rename.
+
+commit 4819d52b007934a40d6d29a75ee30e857c4a93ae
+Author: green <green>
+Date: Wed Aug 4 18:02:34 1999 +0000
+
+ New file for Kresten's closure work
+
+commit 2dbf801eb427cbf5021a9e1e512b5fc523524700
+Author: green <green>
+Date: Wed Aug 4 18:00:05 1999 +0000
+
+ Kresten's closure work. Initial checkin.
+
+commit d170961701b0f2bf7e824d7caba2ebe10002ed84
+Author: green <green>
+Date: Thu Jul 8 14:36:52 1999 +0000
+
+ * configure.in: Add x86 and powerpc BeOS configurations.
+ From Makoto Kato <m_kato@ga2.so-net.ne.jp>.
+
+commit c7747d976924ec6f2229cbcfbbdb98d364e10de9
+Author: jsm <jsm>
+Date: Wed May 12 23:32:16 1999 +0000
+
+ 1999-05-12 Jason Molenda (jsm@bugshack.cygnus.com)
+ * index.html: Add links to libffi* mail list archives.
+
+commit dd2aa9a8de22e26df3bbc85d068358641f6202f7
+Author: green <green>
+Date: Thu May 6 05:34:36 1999 +0000
+
+ * configure.in: Add warning about this being beta code.
+ Remove src/Makefile.am from the picture.
+ * configure: Rebuilt.
+ * Makefile.am: Move logic from src/Makefile.am. Add changes
+ to support libffi as a target library.
+ * Makefile.in: Rebuilt.
+ * aclocal.m4, config.guess, config.sub, ltconfig, ltmain.sh:
+ Upgraded to new autoconf, automake, libtool.
+ * README: Tweaks.
+ * LICENSE: Update copyright date.
+ * src/Makefile.am, src/Makefile.in: Removed.
+
+commit 4e9452abed58a3058ccdb446f96a29d50dda1f34
+Author: green <green>
+Date: Wed May 5 22:06:13 1999 +0000
+
+ Updated to new automake, libtool, autoconf - nothing works :-)
+
+commit 6d3b2bddaf4967fba8b8656c01bfc77ec0f2800c
+Author: jsm <jsm>
+Date: Mon Apr 26 15:55:28 1999 +0000
+
+ 1999-04-26 Jason Molenda (jsm@bugshack.cygnus.com)
+ * index.html: Missed a reference to libffi-discuss@cygnus.com. Fixed.
+
+commit ebc6a9c28af831d3d187af8ff17319f0f309bd98
+Author: jsm <jsm>
+Date: Mon Apr 26 15:53:29 1999 +0000
+
+ 1999-04-26 Jason Molenda (jsm@bugshack.cygnus.com)
+ * index.html: Change links to ftp directory to point to sourceware
+ directory.
+ Change mailing list subscription forms to point to sourceware lists.
+
+commit 78ffc52a8b257061348c576ccb6fbbf8b48b0fff
+Author: jsm <jsm>
+Date: Sun Apr 18 01:33:21 1999 +0000
+
+ Standard sourceware setup.
+
+commit b4d77e827d7ebef7e57ebcd71e71c15c62f1e0a8
+Author: jsm <jsm>
+Date: Mon Nov 30 11:11:25 1998 +0000
+
+ Small typeo. (I wouldn't bother except that it made the sentence hard
+ for me to parse on a casual read.)
+
+commit bfb73f08fdc987e37070c5fb0b196fbd28872888
+Author: jsm <jsm>
+Date: Mon Nov 30 10:44:55 1998 +0000
+
+ A few cleanups. Most notably, point to the correct subscribe cgi-bin
+ script.
+
+commit af8b7f037ccee3b7939ee226a1a2bbc2f057b35c
+Author: green <green>
+Date: Mon Nov 30 06:20:05 1998 +0000
+
+ * index.html: Reformatted and updated to reflect hosting on
+ sourceware.cygnus.com (new mailing lists, etc).
+
+commit 334f0b060942aff8d26badaf7dde7830450dc5da
+Author: green <green>
+Date: Sun Nov 29 16:56:12 1998 +0000
+
+ initial snapshot of documentation
+
+commit 3ab5cb4a1dcc7ecd7e773c97582b0099976c4753
+Author: green <green>
+Date: Sun Nov 29 16:56:10 1998 +0000
+
+ Initial revision
+
+commit d2a9eb5a8b7cbc8b769809cad59c82b975c178e2
+Merge: d3782ec bc75c54
+Author: green <green>
+Date: Sun Nov 29 16:48:16 1998 +0000
+
+ This commit was generated by cvs2svn to compensate for changes in r7, which
+ included commits to RCS files with non-trunk default branches.
+
+commit bc75c54bd311658005b065f1bf201b204c81cbca
+Author: green <green>
+Date: Sun Nov 29 16:48:16 1998 +0000
+
+ Import of v1 code.
+
+commit d3782ec8160c644421dcea17b605fec6e328f14e
+Author: jsm <jsm>
+Date: Fri Nov 20 20:18:00 1998 +0000
+
+ Send commit messages to mailing lists.
+
+commit 8d8d3843c484c2bb70d8375b2b799f75eb03f709
+Author: jsm <jsm>
+Date: Thu Oct 1 22:08:36 1998 +0000
+
+ initial checkin
+
+commit 49634f3bf221cc1939abafc788f7e4e31293fe73
+Author: jsm <jsm>
+Date: Thu Oct 1 22:08:35 1998 +0000
+
+ Add standard setup.
+
+commit c64a84c7693f8cd400fb94bba3c9bcfd9ad1fc36
+Author: jsm <jsm>
+Date: Thu Oct 1 22:08:34 1998 +0000
+
+ Add readers and standard modules file.
+
+commit 9813273b07fd082da573b3b6bfb8d23809b59eea
+Author: jsm <jsm>
+Date: Thu Oct 1 22:08:33 1998 +0000
+
+ initial checkin
diff --git a/contrib/restricted/libffi/ChangeLog.old b/contrib/restricted/libffi/ChangeLog.old
index 738714fb00..8de1ca75f1 100644
--- a/contrib/restricted/libffi/ChangeLog.old
+++ b/contrib/restricted/libffi/ChangeLog.old
@@ -1,7407 +1,7407 @@
-Libffi change logs used to be maintained in separate ChangeLog files.
-These days we generate them directly from the git commit messages.
-The old ChangeLog files are saved here in order to maintain the historical
-record.
-
-=============================================================================
-From the old ChangeLog.libffi-3.1 file...
-
-2014-03-16 Josh Triplett <josh@joshtriplett.org>
-
- * ChangeLog: Archive to ChangeLog.libffi-3.1 and delete. Future
- changelogs will come from git, with autogenerated snapshots shipped in
- distributed tarballs.
-
-2014-03-16 Josh Triplett <josh@joshtriplett.org>
-
- Add support for stdcall, thiscall, and fastcall on non-Windows
- x86-32.
-
- Linux supports the stdcall calling convention, either via
- functions explicitly declared with the stdcall attribute, or via
- code compiled with -mrtd which effectively makes stdcall the
- default.
-
- This introduces FFI_STDCALL, FFI_THISCALL, and FFI_FASTCALL on
- non-Windows x86-32 platforms, as non-default calling conventions.
-
- * Makefile.am: Compile in src/x86/win32.S on non-Windows x86-32.
- * src/x86/ffitarget.h: Add FFI_STDCALL, FFI_THISCALL, and
- FFI_FASTCALL on non-Windows x86-32. Increase trampoline size to
- accomodate these calling conventions, and unify some ifdeffery.
- * src/x86/ffi.c: Add support for FFI_STDCALL, FFI_THISCALL, and
- FFI_FASTCALL on non-Windows x86-32 platforms; update ifdeffery.
- * src/x86/win32.S: Support compiling on non-Windows x86-32
- platforms. On those platforms, avoid redefining the SYSV symbols
- already provided by src/x86/sysv.S.
- * testsuite/libffi.call/closure_stdcall.c: Run on non-Windows.
- #define __stdcall if needed.
- * testsuite/libffi.call/closure_thiscall.c: Run on non-Windows.
- #define __fastcall if needed.
- * testsuite/libffi.call/fastthis1_win32.c: Run on non-Windows.
- * testsuite/libffi.call/fastthis2_win32.c: Ditto.
- * testsuite/libffi.call/fastthis3_win32.c: Ditto.
- * testsuite/libffi.call/many2_win32.c: Ditto.
- * testsuite/libffi.call/many_win32.c: Ditto.
- * testsuite/libffi.call/strlen2_win32.c: Ditto.
- * testsuite/libffi.call/strlen_win32.c: Ditto.
- * testsuite/libffi.call/struct1_win32.c: Ditto.
- * testsuite/libffi.call/struct2_win32.c: Ditto.
-
-2014-03-16 Josh Triplett <josh@joshtriplett.org>
-
- * prep_cif.c: Remove unnecessary ifdef for X86_WIN32.
- ffi_prep_cif_core had a special case for X86_WIN32, checking for
- FFI_THISCALL in addition to the FFI_FIRST_ABI-to-FFI_LAST_ABI
- range before returning FFI_BAD_ABI. However, on X86_WIN32,
- FFI_THISCALL already falls in that range, making the special case
- unnecessary. Remove it.
-
-2014-03-16 Josh Triplett <josh@joshtriplett.org>
-
- * testsuite/libffi.call/closure_stdcall.c,
- testsuite/libffi.call/closure_thiscall.c: Remove fragile stack
- pointer checks. These files included inline assembly to save the
- stack pointer before and after the call, and compare the values.
- However, compilers can and do leave the stack in different states
- for these two pieces of inline assembly, such as by saving a
- temporary value on the stack across the call; observed with gcc
- -Os, and verified as spurious through careful inspection of
- disassembly.
-
-2014-03-16 Josh Triplett <josh@joshtriplett.org>
-
- * testsuite/libffi.call/many.c: Avoid spurious failure due to
- excess floating-point precision.
- * testsuite/libffi.call/many_win32.c: Ditto.
-
-2014-03-16 Josh Triplett <josh@joshtriplett.org>
-
- * libtool-ldflags: Re-add.
-
-2014-03-16 Josh Triplett <josh@joshtriplett.org>
-
- * Makefile.in, aclocal.m4, compile, config.guess, config.sub,
- configure, depcomp, include/Makefile.in, install-sh,
- libtool-ldflags, ltmain.sh, m4/libtool.m4, m4/ltoptions.m4,
- m4/ltsugar.m4, m4/ltversion.m4, m4/lt~obsolete.m4,
- man/Makefile.in, mdate-sh, missing, testsuite/Makefile.in: Delete
- autogenerated files from version control.
- * .gitignore: Add autogenerated files.
- * autogen.sh: New script to generate the autogenerated files.
- * README: Document requirement to run autogen.sh when building
- directly from version control.
- * .travis.yml: Run autogen.sh
-
-2014-03-14 Anthony Green <green@moxielogic.com>
-
- * configure, Makefile.in: Rebuilt.
-
-2014-03-10 Mike Hommey <mh+mozilla@glandium.org>
-
- * configure.ac: Allow building for mipsel with Android NDK r8.
- * Makefile.am (AM_MAKEFLAGS): Replace double quotes with single
- quotes.
-
-2014-03-10 Landry Breuil <landry@openbsd.org>
-
- * configure.ac: Ensure the linker supports @unwind sections in libffi.
-
-2014-03-01 Anthony Green <green@moxielogic.com>
-
- * Makefile.am (EXTRA_DIST): Replace old scripts with
- generate-darwin-source-and-headers.py.
- * Makefile.in: Rebuilt.
-
-2014-02-28 Anthony Green <green@moxielogic.com>
-
- * Makefile.am (AM_CFLAGS): Reintroduce missing -DFFI_DEBUG for
- --enable-debug builds.
- * Makefile.in: Rebuilt.
-
-2014-02-28 Makoto Kato <m_kato@ga2.so-net.ne.jp>
-
- * src/closures.c: Fix build failure when using clang for Android.
-
-2014-02-28 Marcin Wojdyr <wojdyr@gmail.com>
-
- * libffi.pc.in (toolexeclibdir): use -L${toolexeclibdir} instead
- of -L${libdir}.
-
-2014-02-28 Paulo Pizarro <paulo.pizarro@gmail.com>
-
- * src/bfin/sysv.S: Calling functions in shared libraries requires
- considering the GOT.
-
-2014-02-28 Josh Triplett <josh@joshtriplett.org>
-
- * src/x86/ffi64.c (classify_argument): Handle case where
- FFI_TYPE_LONGDOUBLE == FFI_TYPE_DOUBLE.
-
-2014-02-28 Anthony Green <green@moxielogic.com>
-
- * ltmain.sh: Generate with libtool-2.4.2.418.
- * m4/libtool.m4, m4/ltoptions.m4, m4/ltversion.m4: Ditto.
- * configure: Rebuilt.
-
-2014-02-28 Dominik Vogt <vogt@linux.vnet.ibm.com>
-
- * configure.ac (AC_ARG_ENABLE struct): Fix typo in help
- message.
- (AC_ARG_ENABLE raw_api): Ditto.
- * configure, fficonfig.h.in: Rebuilt.
-
-2014-02-28 Will Newton <will.newton@linaro.org>
-
- * src/arm/sysv.S: Initialize IP register with FP.
-
-2014-02-28 Yufeng Zhang <yufeng.zhang@arm.com>
-
- * src/aarch64/sysv.S (ffi_closure_SYSV): Use x29 as the
- main CFA reg; update cfi_rel_offset.
-
-2014-02-15 Marcus Comstedt <marcus@mc.pp.se>
-
- * src/powerpc/ffi_linux64.c, src/powerpc/linux64_closure.S: Remove
- assumption on contents of r11 in closure.
-
-2014-02-09 Heiher <r@hev.cc>
-
- * src/mips/n32.S: Fix call floating point va function.
-
-2014-01-21 Zachary Waldowski <zach@waldowski.me>
-
- * src/aarch64/ffi.c: Fix missing semicolons on assertions under
- debug mode.
-
-2013-12-30 Zachary Waldowski <zach@waldowski.me>
-
- * .gitignore: Exclude darwin_* generated source and build_* trees.
- * src/aarch64/ffi.c, src/arm/ffi.c, src/x86/ffi.c: Inhibit Clang
- previous prototype warnings.
- * src/arm/ffi.c: Prevent NULL dereference, fix short type warning
- * src/dlmalloc.c: Fix warnings from set_segment_flags return type,
- and the native use of size_t for malloc on platforms
- * src/arm/sysv.S: Use unified syntax. Clang clean-ups for
- ARM_FUNC_START.
- * generate-osx-source-and-headers.py: Remove.
- * build-ios.sh: Remove.
- * libffi.xcodeproj/project.pbxproj: Rebuild targets. Include
- x86_64+aarch64 pieces in library. Export headers properly.
- * src/x86/ffi64.c: More Clang warning clean-ups.
- * src/closures.c (open_temp_exec_file_dir): Use size_t.
- * src/prep_cif.c (ffi_prep_cif_core): Cast ALIGN result.
- * src/aarch64/sysv.S: Use CNAME for global symbols. Only use
- .size for ELF targets.
- * src/aarch64/ffi.c: Clean up for double == long double. Clean up
- from Clang warnings. Use Clang cache invalidation builtin. Use
- size_t in place of unsigned in many places. Accommodate for
- differences in Apple AArch64 ABI.
-
-2013-12-02 Daniel Rodríguez Troitiño <drodrigueztroitino@yahoo.es>
-
- * generate-darwin-source-and-headers.py: Clean up, modernize,
- merged version of previous scripts.
-
-2013-11-21 Anthony Green <green@moxielogic.com>
-
- * configure, Makefile.in, include/Makefile.in, include/ffi.h.in,
- man/Makefile.in, testsuite/Makefile.in, fficonfig.h.in: Rebuilt.
-
-2013-11-21 Alan Modra <amodra@gmail.com>
-
- * Makefile.am (EXTRA_DIST): Add new src/powerpc files.
- (nodist_libffi_la_SOURCES <POWERPC, POWERPC_FREEBSD>): Likewise.
- * configure.ac (HAVE_LONG_DOUBLE_VARIANT): Define for powerpc.
- * include/ffi.h.in (ffi_prep_types): Declare.
- * src/prep_cif.c (ffi_prep_cif_core): Call ffi_prep_types.
- * src/types.c (FFI_NONCONST_TYPEDEF): Define and use for
- HAVE_LONG_DOUBLE_VARIANT.
- * src/powerpc/ffi_powerpc.h: New file.
- * src/powerpc/ffi.c: Split into..
- * src/powerpc/ffi_sysv.c: ..new file, and..
- * src/powerpc/ffi_linux64.c: ..new file, rewriting parts.
- * src/powerpc/ffitarget.h (enum ffi_abi): Rewrite powerpc ABI
- selection as bits controlling features.
- * src/powerpc/linux64.S: For consistency, use POWERPC64 rather
- than __powerpc64__.
- * src/powerpc/linux64_closure.S: Likewise.
- * src/powerpc/ppc_closure.S: Likewise. Move .note.FNU-stack
- inside guard.
- * src/powerpc/sysv.S: Likewise.
- * configure: Regenerate.
- * fficonfig.h.in: Regenerate.
- * Makefile.in: Regenerate.
-
-2013-11-20 Alan Modra <amodra@gmail.com>
-
- * src/powerpc/ffi.c (ffi_prep_cif_machdep_core): Use
- NUM_FPR_ARG_REGISTERS64 and NUM_GPR_ARG_REGISTERS64 not their
- 32-bit versions for 64-bit code.
- * src/powerpc/linux64_closure.S: Don't use the return value area
- as a parameter save area on ELFv2.
-
-2013-11-18 Iain Sandoe <iain@codesourcery.com>
-
- * src/powerpc/darwin.S (EH): Correct use of pcrel FDE encoding.
- * src/powerpc/darwin_closure.S (EH): Likewise. Modernise picbase
- labels.
-
-2013-11-18 Anthony Green <green@moxielogic.com>
-
- * src/arm/ffi.c (ffi_call): Hoist declaration of temp to top of
- function.
- * src/arm/ffi.c (ffi_closure_inner): Moderize function declaration
- to appease compiler.
- Thanks for Gregory P. Smith <greg@krypto.org>.
-
-2013-11-18 Anthony Green <green@moxielogic.com>
-
- * README (tested): Mention PowerPC ELFv2.
-
-2013-11-16 Alan Modra <amodra@gmail.com>
-
- * src/powerpc/ppc_closure.S: Move errant #endif to where it belongs.
- Don't bl .Luint128.
-
-2013-11-16 Alan Modra <amodra@gmail.com>
-
- * src/powerpc/ffi.c (ffi_prep_cif_machdep_core): Use #if _CALL_ELF
- test to select parameter save sizing for ELFv2 vs. ELFv1.
- * src/powerpc/ffitarget.h (FFI_V2_TYPE_FLOAT_HOMOG,
- FFI_V2_TYPE_DOUBLE_HOMOG, FFI_V2_TYPE_SMALL_STRUCT): Define.
- (FFI_TRAMPOLINE_SIZE): Define variant for ELFv2.
- * src/powerpc/ffi.c (FLAG_ARG_NEEDS_PSAVE): Define.
- (discover_homogeneous_aggregate): New function.
- (ffi_prep_args64): Adjust start of param save area for ELFv2.
- Handle homogenous floating point struct parms.
- (ffi_prep_cif_machdep_core): Adjust space calculation for ELFv2.
- Handle ELFv2 return values. Set FLAG_ARG_NEEDS_PSAVE. Handle
- homogenous floating point structs.
- (ffi_call): Increase size of smst_buffer for ELFv2. Handle ELFv2.
- (flush_icache): Compile for ELFv2.
- (ffi_prep_closure_loc): Set up ELFv2 trampoline.
- (ffi_closure_helper_LINUX64): Don't return all structs directly
- to caller. Handle homogenous floating point structs. Handle
- ELFv2 struct return values.
- * src/powerpc/linux64.S (ffi_call_LINUX64): Set up r2 for
- ELFv2. Adjust toc save location. Call function pointer using
- r12. Handle FLAG_RETURNS_SMST. Don't predict branches.
- * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Set up r2
- for ELFv2. Define ELFv2 versions of STACKFRAME, PARMSAVE, and
- RETVAL. Handle possibly missing parameter save area. Handle
- ELFv2 return values.
- (.note.GNU-stack): Move inside outer #ifdef.
-
-2013-11-16 Alan Modra <amodra@gmail.com>
-
- * src/powerpc/ffi.c (ffi_prep_cif_machdep): Revert 2013-02-08
- change. Do not consume an int arg when returning a small struct
- for FFI_SYSV ABI.
- (ffi_call): Only use bounce buffer when FLAG_RETURNS_SMST.
- Properly copy bounce buffer to destination.
- * src/powerpc/sysv.S: Revert 2013-02-08 change.
- * src/powerpc/ppc_closure.S: Remove stray '+'.
-
-2013-11-16 Alan Modra <amodra@gmail.com>
-
- * src/powerpc/ffi.c (ffi_prep_args64): Align struct parameters
- according to __STRUCT_PARM_ALIGN__.
- (ffi_prep_cif_machdep_core): Likewise.
- (ffi_closure_helper_LINUX64): Likewise.
-
-2013-11-16 Alan Modra <amodra@gmail.com>
-
- * src/powerpc/linux64.S (ffi_call_LINUX64): Tweak restore of r28.
- (.note.GNU-stack): Move inside outer #ifdef.
- * src/powerpc/linux64_closure.S (STACKFRAME, PARMSAVE,
- RETVAL): Define and use throughout.
- (ffi_closure_LINUX64): Save fprs before buying stack.
- (.note.GNU-stack): Move inside outer #ifdef.
-
-2013-11-16 Alan Modra <amodra@gmail.com>
-
- * src/powerpc/ffitarget.h (FFI_TARGET_SPECIFIC_VARIADIC): Define.
- (FFI_EXTRA_CIF_FIELDS): Define.
- * src/powerpc/ffi.c (ffi_prep_args64): Save fprs as per the
- ABI, not to both fpr and param save area.
- (ffi_prep_cif_machdep_core): Renamed from ffi_prep_cif_machdep.
- Keep initial flags. Formatting. Remove dead FFI_LINUX_SOFT_FLOAT
- code.
- (ffi_prep_cif_machdep, ffi_prep_cif_machdep_var): New functions.
- (ffi_closure_helper_LINUX64): Pass floating point as per ABI,
- not to both fpr and parameter save areas.
-
- * libffi/testsuite/libffi.call/cls_double_va.c (main): Correct
- function cast and don't call ffi_prep_cif.
- * libffi/testsuite/libffi.call/cls_longdouble_va.c (main): Likewise.
-
-2013-11-15 Andrew Haley <aph@redhat.com>
-
- * doc/libffi.texi (Closure Example): Fix the sample code.
- * doc/libffi.info, doc/stamp-vti, doc/version.texi: Rebuilt.
-
-2013-11-15 Andrew Haley <aph@redhat.com>
-
- * testsuite/libffi.call/va_struct1.c (main): Fix broken test.
- * testsuite/libffi.call/cls_uint_va.c (cls_ret_T_fn): Likewise
- * testsuite/libffi.call/cls_struct_va1.c (test_fn): Likewise.
- * testsuite/libffi.call/va_1.c (main): Likewise.
-
-2013-11-14 David Schneider <david.schneider@bivab.de>
-
- * src/arm/ffi.c: Fix register allocation for mixed float and
- doubles.
- * testsuite/libffi.call/cls_many_mixed_float_double.c: Testcase
- for many mixed float and double arguments.
-
-2013-11-13 Alan Modra <amodra@gmail.com>
-
- * doc/libffi.texi (Simple Example): Correct example code.
- * doc/libffi.info, doc/stamp-vti, doc/version.texi: Rebuilt.
-
-2013-11-13 Anthony Green <green@moxielogic.com>
-
- * include/ffi_common.h: Respect HAVE_ALLOCA_H for GNU compiler
- based build. (Thanks to tmr111116 on github)
-
-2013-11-09 Anthony Green <green@moxielogic.com>
-
- * m4/libtool.m4: Refresh.
- * configure, Makefile.in: Rebuilt.
- * README: Add more notes about next release.
-
-2013-11-09 Shigeharu TAKENO <shige@iee.niit.ac.jp>
-
- * m4/ax_gcc_archflag.m4 (ax_gcc_arch): Don't recognize
- UltraSPARC-IIi as ultrasparc3.
-
-2013-11-06 Mark Kettenis <kettenis@gnu.org>
-
- * src/x86/freebsd.S (ffi_call_SYSV): Align the stack pointer to
- 16-bytes.
-
-2013-11-06 Konstantin Belousov <kib@freebsd.org>
-
- * src/x86/freebsd.S (ffi_closure_raw_SYSV): Mark the assembler
- source as not requiring executable stack.
-
-2013-11-02 Anthony Green <green@moxielogic.com>
-
- * doc/libffi.texi (The Basics): Clarify return value buffer size
- requirements. Also, NULL result buffer pointers are no longer
- supported.
- * doc/libffi.info: Rebuilt.
-
-2013-11-02 Mischa Jonker <mjonker@synopsys.com>
-
- * Makefile.am (nodist_libffi_la_SOURCES): Fix build error.
- * Makefile.in: Rebuilt.
-
-2013-11-02 David Schneider <david.schneider@bivab.de>
-
- * src/arm/ffi.c: more robust argument handling for closures on arm hardfloat
- * testsuite/libffi.call/many_mixed.c: New file.
- * testsuite/libffi.call/cls_many_mixed_args.c: More tests.
-
-2013-11-02 Vitaly Budovski
-
- * src/x86/ffi.c (ffi_prep_cif_machdep): Don't align stack for win32.
-
-2013-10-23 Mark H Weaver <mhw@netris.org>
-
- * src/mips/ffi.c: Fix handling of uint32_t arguments on the
- MIPS N32 ABI.
-
-2013-10-13 Sandra Loosemore <sandra@codesourcery.com>
-
- * README: Add Nios II to table of supported platforms.
- * Makefile.am (EXTRA_DIST): Add nios2 files.
- (nodist_libffi_la_SOURCES): Likewise.
- * Makefile.in: Regenerated.
- * configure.ac (nios2*-linux*): New host.
- (NIOS2): Add AM_CONDITIONAL.
- * configure: Regenerated.
- * src/nios2/ffi.c: New.
- * src/nios2/ffitarget.h: New.
- * src/nios2/sysv.S: New.
- * src/prep_cif.c (initialize_aggregate): Handle extra structure
- alignment via FFI_AGGREGATE_ALIGNMENT.
- (ffi_prep_cif_core): Conditionalize structure return for NIOS2.
-
-2013-10-10 Sandra Loosemore <sandra@codesourcery.com>
-
- * testsuite/libffi.call/cls_many_mixed_args.c (cls_ret_double_fn):
- Fix uninitialized variable.
-
-2013-10-11 Marcus Shawcroft <marcus.shawcroft@arm.com>
-
- * testsuite/libffi.call/many.c (many): Replace * with +.
-
-2013-10-08 Ondřej Bílka <neleai@seznam.cz>
-
- * src/aarch64/ffi.c, src/aarch64/sysv.S, src/arm/ffi.c,
- src/arm/gentramp.sh, src/bfin/sysv.S, src/closures.c,
- src/dlmalloc.c, src/ia64/ffi.c, src/microblaze/ffi.c,
- src/microblaze/sysv.S, src/powerpc/darwin_closure.S,
- src/powerpc/ffi.c, src/powerpc/ffi_darwin.c, src/sh/ffi.c,
- src/tile/tile.S, testsuite/libffi.call/nested_struct11.c: Fix
- spelling errors.
-
-2013-10-08 Anthony Green <green@moxielogic.com>
-
- * aclocal.m4, compile, config.guess, config.sub, depcomp,
- install-sh, mdate-sh, missing, texinfo.tex: Update from upstream.
- * configure.ac: Update version to 3.0.14-rc0.
- * Makefile.in, configure, Makefile.in, include/Makefile.in,
- man/Makefile.in, testsuite/Makefile.in: Rebuilt.
- * README: Mention M88K and VAX.
-
-2013-07-15 Miod Vallat <miod@openbsd.org>
-
- * Makefile.am,
- configure.ac,
- src/m88k/ffi.c,
- src/m88k/ffitarget.h,
- src/m88k/obsd.S,
- src/vax/elfbsd.S,
- src/vax/ffi.c,
- src/vax/ffitarget.h: Add m88k and vax support.
-
-2013-06-24 Alan Modra <amodra@gmail.com>
-
- * src/powerpc/ffi.c (ffi_prep_args_SYSV): Move var declaration
- before statements.
- (ffi_prep_args64): Support little-endian.
- (ffi_closure_helper_SYSV, ffi_closure_helper_LINUX64): Likewise.
- * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Likewise.
- * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Likewise.
-
-2013-06-12 Mischa Jonker <mjonker@synopsys.com>
-
- * configure.ac: Add support for ARC.
- * Makefile.am: Likewise.
- * README: Add ARC details.
- * src/arc/arcompact.S: New.
- * src/arc/ffi.c: Likewise.
- * src/arc/ffitarget.h: Likewise.
-
-2013-03-28 David Schneider <david.schneider@bivab.de>
-
- * src/arm/ffi.c: Fix support for ARM hard-float calling convention.
- * src/arm/sysv.S: call different methods for SYSV and VFP ABIs.
- * testsuite/libffi.call/cls_many_mixed_args.c: testcase for a closure with
- mixed arguments, many doubles.
- * testsuite/libffi.call/many_double.c: testcase for calling a function using
- more than 8 doubles.
- * testcase/libffi.call/many.c: use absolute value to check result against an
- epsilon
-
-2013-03-17 Anthony Green <green@moxielogic.com>
-
- * README: Update for 3.0.13.
- * configure.ac: Ditto.
- * configure: Rebuilt.
- * doc/*: Update version.
-
-2013-03-17 Dave Korn <dave.korn.cygwin@gmail.com>
-
- * src/closures.c (is_emutramp_enabled
- [!FFI_MMAP_EXEC_EMUTRAMP_PAX]): Move default definition outside
- enclosing #if scope.
-
-2013-03-17 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Only modify toolexecdir in certain cases.
- * configure: Rebuilt.
-
-2013-03-16 Gilles Talis <gilles.talis@gmail.com>
-
- * src/powerpc/ffi.c (ffi_prep_args_SYSV): Don't use
- fparg_count,etc on __NO_FPRS__ targets.
-
-2013-03-16 Alan Hourihane <alanh@fairlite.co.uk>
-
- * src/m68k/sysv.S (epilogue): Don't use extb instruction on
- m680000 machines.
-
-2013-03-16 Alex Gaynor <alex.gaynor@gmail.com>
-
- * src/x86/ffi.c (ffi_prep_cif_machdep): Always align stack.
-
-2013-03-13 Markos Chandras <markos.chandras@imgtec.com>
-
- * configure.ac: Add support for Imagination Technologies Meta.
- * Makefile.am: Likewise.
- * README: Add Imagination Technologies Meta details.
- * src/metag/ffi.c: New.
- * src/metag/ffitarget.h: Likewise.
- * src/metag/sysv.S: Likewise.
-
-2013-02-24 Andreas Schwab <schwab@linux-m68k.org>
-
- * doc/libffi.texi (Structures): Fix missing category argument of
- @deftp.
-
-2013-02-11 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Update release number to 3.0.12.
- * configure: Rebuilt.
- * README: Update release info.
-
-2013-02-10 Anthony Green <green@moxielogic.com>
-
- * README: Add Moxie.
- * src/moxie/ffi.c: Created.
- * src/moxie/eabi.S: Created.
- * src/moxie/ffitarget.h: Created.
- * Makefile.am (nodist_libffi_la_SOURCES): Add Moxie.
- * Makefile.in: Rebuilt.
- * configure.ac: Add Moxie.
- * configure: Rebuilt.
- * testsuite/libffi.call/huge_struct.c: Disable format string
- warnings for moxie*-*-elf tests.
-
-2013-02-10 Anthony Green <green@moxielogic.com>
-
- * Makefile.am (LTLDFLAGS): Fix reference.
- * Makefile.in: Rebuilt.
-
-2013-02-10 Anthony Green <green@moxielogic.com>
-
- * README: Update supported platforms. Update test results link.
-
-2013-02-09 Anthony Green <green@moxielogic.com>
-
- * testsuite/libffi.call/negint.c: Remove forced -O2.
- * testsuite/libffi.call/many2.c (foo): Remove GCCism.
- * testsuite/libffi.call/ffitest.h: Add default PRIuPTR definition.
-
- * src/sparc/v8.S (ffi_closure_v8): Import ancient ulonglong
- closure return type fix developed by Martin v. Löwis for cpython
- fork.
-
-2013-02-08 Andreas Tobler <andreast@fgznet.ch>
-
- * src/powerpc/ffi.c (ffi_prep_cif_machdep): Fix small struct
- support.
- * src/powerpc/sysv.S: Ditto.
-
-2013-02-08 Anthony Green <green@moxielogic.com>
-
- * testsuite/libffi.call/cls_longdouble.c: Remove xfail for
- arm*-*-*.
-
-2013-02-08 Anthony Green <green@moxielogic.com>
-
- * src/sparc/ffi.c (ffi_prep_closure_loc): Fix cache flushing for GCC.
-
-2013-02-08 Matthias Klose <doko@ubuntu.com>
-
- * man/ffi_prep_cif.3: Clean up for debian linter.
-
-2013-02-08 Peter Bergner <bergner@vnet.ibm.com>
-
- * src/powerpc/ffi.c (ffi_prep_args_SYSV): Account for FP args pushed
- on the stack.
-
-2013-02-08 Anthony Green <green@moxielogic.com>
-
- * Makefile.am (EXTRA_DIST): Add missing files.
- * testsuite/Makefile.am (EXTRA_DIST): Ditto.
- * Makefile.in: Rebuilt.
-
-2013-02-08 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Move sparc asm config checks to within functions
- for compatibility with sun tools.
- * configure: Rebuilt.
- * src/sparc/ffi.c (ffi_prep_closure_loc): Flush cache on v9
- systems.
- * src/sparc/v8.S (ffi_flush_icache): Implement a sparc v9 cache
- flusher.
-
-2013-02-08 Nathan Rossi <nathan.rossi@xilinx.com>
-
- * src/microblaze/ffi.c (ffi_closure_call_SYSV): Fix handling of
- small big-endian structures.
- (ffi_prep_args): Ditto.
-
-2013-02-07 Anthony Green <green@moxielogic.com>
-
- * src/sparc/v8.S (ffi_call_v8): Fix typo from last patch
- (effectively hiding ffi_call_v8).
-
-2013-02-07 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Update bug reporting address.
- * configure.in: Rebuild.
-
- * src/sparc/v8.S (ffi_flush_icache): Out-of-line cache flusher for
- Sun compiler.
- * src/sparc/ffi.c (ffi_call): Remove warning.
- Call ffi_flush_icache for non-GCC builds.
- (ffi_prep_closure_loc): Use ffi_flush_icache.
-
- * Makefile.am (EXTRA_DIST): Add libtool-ldflags.
- * Makefile.in: Rebuilt.
- * libtool-ldflags: New file.
-
-2013-02-07 Daniel Schepler <dschepler@gmail.com>
-
- * configure.ac: Correctly identify x32 systems as 64-bit.
- * m4/libtool.m4: Remove libtool expr error.
- * aclocal.m4, configure: Rebuilt.
-
-2013-02-07 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Fix GCC usage test.
- * configure: Rebuilt.
- * README: Mention LLVM/GCC x86_64 issue.
- * testsuite/Makefile.in: Rebuilt.
-
-2013-02-07 Anthony Green <green@moxielogic.com>
-
- * testsuite/libffi.call/cls_double_va.c (main): Replace // style
- comments with /* */ for xlc compiler.
- * testsuite/libffi.call/stret_large.c (main): Ditto.
- * testsuite/libffi.call/stret_large2.c (main): Ditto.
- * testsuite/libffi.call/nested_struct1.c (main): Ditto.
- * testsuite/libffi.call/huge_struct.c (main): Ditto.
- * testsuite/libffi.call/float_va.c (main): Ditto.
- * testsuite/libffi.call/cls_struct_va1.c (main): Ditto.
- * testsuite/libffi.call/cls_pointer_stack.c (main): Ditto.
- * testsuite/libffi.call/cls_pointer.c (main): Ditto.
- * testsuite/libffi.call/cls_longdouble_va.c (main): Ditto.
-
-2013-02-06 Anthony Green <green@moxielogic.com>
-
- * man/ffi_prep_cif.3: Clean up for debian lintian checker.
-
-2013-02-06 Anthony Green <green@moxielogic.com>
-
- * Makefile.am (pkgconfigdir): Add missing pkgconfig install bits.
- * Makefile.in: Rebuild.
-
-2013-02-02 Mark H Weaver <mhw@netris.org>
-
- * src/x86/ffi64.c (ffi_call): Sign-extend integer arguments passed
- via general purpose registers.
-
-2013-01-21 Nathan Rossi <nathan.rossi@xilinx.com>
-
- * README: Add MicroBlaze details.
- * Makefile.am: Add MicroBlaze support.
- * configure.ac: Likewise.
- * src/microblaze/ffi.c: New.
- * src/microblaze/ffitarget.h: Likewise.
- * src/microblaze/sysv.S: Likewise.
-
-2013-01-21 Nathan Rossi <nathan.rossi@xilinx.com>
- * testsuite/libffi.call/return_uc.c: Fixed issue.
-
-2013-01-21 Chris Zankel <chris@zankel.net>
-
- * README: Add Xtensa support.
- * Makefile.am: Likewise.
- * configure.ac: Likewise.
- * Makefile.in Regenerate.
- * configure: Likewise.
- * src/prep_cif.c: Handle Xtensa.
- * src/xtensa: New directory.
- * src/xtensa/ffi.c: New file.
- * src/xtensa/ffitarget.h: Ditto.
- * src/xtensa/sysv.S: Ditto.
-
-2013-01-11 Anthony Green <green@moxielogic.com>
-
- * src/powerpc/ffi_darwin.c (ffi_prep_args): Replace // style
- comments with /* */ for xlc compiler.
- * src/powerpc/aix.S (ffi_call_AIX): Ditto.
- * testsuite/libffi.call/ffitest.h (allocate_mmap): Delete
- deprecated inline function.
- * testsuite/libffi.special/ffitestcxx.h: Ditto.
- * README: Add update for AIX support.
-
-2013-01-11 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Robustify pc relative reloc check.
- * m4/ax_cc_maxopt.m4: Don't -malign-double. This is an ABI
- changing option for 32-bit x86.
- * aclocal.m4, configure: Rebuilt.
- * README: Update supported target list.
-
-2013-01-10 Anthony Green <green@moxielogic.com>
-
- * README (tested): Add Compiler column to table.
-
-2013-01-10 Anthony Green <green@moxielogic.com>
-
- * src/x86/ffi64.c (struct register_args): Make sse array and array
- of unions for sunpro compiler compatibility.
-
-2013-01-10 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Test target platform size_t size. Handle both 32
- and 64-bit builds for x86_64-* and i?86-* targets (allowing for
- CFLAG option to change default settings).
- * configure, aclocal.m4: Rebuilt.
-
-2013-01-10 Anthony Green <green@moxielogic.com>
-
- * testsuite/libffi.special/special.exp: Only run exception
- handling tests when using GNU compiler.
-
- * m4/ax_compiler_vendor.m4: New file.
- * configure.ac: Test for compiler vendor and don't use
- AX_CFLAGS_WARN_ALL with the sun compiler.
- * aclocal.m4, configure: Rebuilt.
-
-2013-01-10 Anthony Green <green@moxielogic.com>
-
- * include/ffi_common.h: Don't use GCCisms to define types when
- building with the SUNPRO compiler.
-
-2013-01-10 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Put local.exp in the right place.
- * configure: Rebuilt.
-
- * src/x86/ffi.c: Update comment about regparm function attributes.
- * src/x86/sysv.S (ffi_closure_SYSV): The SUNPRO compiler requires
- that all function arguments be passed on the stack (no regparm
- support).
-
-2013-01-08 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Generate local.exp. This sets CC_FOR_TARGET
- when we are using the vendor compiler.
- * testsuite/Makefile.am (EXTRA_DEJAGNU_SITE_CONFIG): Point to
- ../local.exp.
- * configure, testsuite/Makefile.in: Rebuilt.
-
- * testsuite/libffi.call/call.exp: Run tests with different
- options, depending on whether or not we are using gcc or the
- vendor compiler.
- * testsuite/lib/libffi.exp (libffi-init): Set using_gcc based on
- whether or not we are building/testing with gcc.
-
-2013-01-08 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Switch x86 solaris target to X86 by default.
- * configure: Rebuilt.
-
-2013-01-08 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Fix test for read-only eh_frame.
- * configure: Rebuilt.
-
-2013-01-08 Anthony Green <green@moxielogic.com>
-
- * src/x86/sysv.S, src/x86/unix64.S: Only emit DWARF unwind info
- when building with the GNU toolchain.
- * testsuite/libffi.call/ffitest.h (CHECK): Fix for Solaris vendor
- compiler.
-
-2013-01-07 Thorsten Glaser <tg@mirbsd.org>
-
- * testsuite/libffi.call/cls_uchar_va.c,
- testsuite/libffi.call/cls_ushort_va.c,
- testsuite/libffi.call/va_1.c: Testsuite fixes.
-
-2013-01-07 Thorsten Glaser <tg@mirbsd.org>
-
- * src/m68k/ffi.c (CIF_FLAGS_SINT8, CIF_FLAGS_SINT16): Define.
- (ffi_prep_cif_machdep): Fix 8-bit and 16-bit signed calls.
- * src/m68k/sysv.S (ffi_call_SYSV, ffi_closure_SYSV): Ditto.
-
-2013-01-04 Anthony Green <green@moxielogic.com>
-
- * Makefile.am (AM_CFLAGS): Don't automatically add -fexceptions
- and -Wall. This is set in the configure script after testing for
- GCC.
- * Makefile.in: Rebuilt.
-
-2013-01-02 rofl0r <https://github.com/rofl0r>
-
- * src/powerpc/ffi.c (ffi_prep_cif_machdep): Fix build error on ppc
- when long double == double.
-
-2013-01-02 Reini Urban <rurban@x-ray.at>
-
- * Makefile.am (libffi_la_LDFLAGS): Add -no-undefined to LDFLAGS
- (required for shared libs on cygwin/mingw).
- * Makefile.in: Rebuilt.
-
-2012-10-31 Alan Modra <amodra@gmail.co>
-
- * src/powerpc/linux64_closure.S: Add new ABI support.
- * src/powerpc/linux64.S: Likewise.
-
-2012-10-30 Magnus Granberg <zorry@gentoo.org>
- Pavel Labushev <pavel.labushev@runbox.ru>
-
- * configure.ac: New options pax_emutramp
- * configure, fficonfig.h.in: Regenerated
- * src/closures.c: New function emutramp_enabled_check() and
- checks.
-
-2012-10-30 Frederick Cheung <frederick.cheung@gmail.com>
-
- * configure.ac: Enable FFI_MAP_EXEC_WRIT for Darwin 12 (mountain
- lion) and future version.
- * configure: Rebuild.
-
-2012-10-30 James Greenhalgh <james.greenhalgh at arm.com>
- Marcus Shawcroft <marcus.shawcroft at arm.com>
-
- * README: Add details of aarch64 port.
- * src/aarch64/ffi.c: New.
- * src/aarch64/ffitarget.h: Likewise.
- * src/aarch64/sysv.S: Likewise.
- * Makefile.am: Support aarch64.
- * configure.ac: Support aarch64.
- * Makefile.in, configure: Rebuilt.
-
-2012-10-30 James Greenhalgh <james.greenhalgh at arm.com>
- Marcus Shawcroft <marcus.shawcroft at arm.com>
-
- * testsuite/lib/libffi.exp: Add support for aarch64.
- * testsuite/libffi.call/cls_struct_va1.c: New.
- * testsuite/libffi.call/cls_uchar_va.c: Likewise.
- * testsuite/libffi.call/cls_uint_va.c: Likewise.
- * testsuite/libffi.call/cls_ulong_va.c: Likewise.
- * testsuite/libffi.call/cls_ushort_va.c: Likewise.
- * testsuite/libffi.call/nested_struct11.c: Likewise.
- * testsuite/libffi.call/uninitialized.c: Likewise.
- * testsuite/libffi.call/va_1.c: Likewise.
- * testsuite/libffi.call/va_struct1.c: Likewise.
- * testsuite/libffi.call/va_struct2.c: Likewise.
- * testsuite/libffi.call/va_struct3.c: Likewise.
-
-2012-10-12 Walter Lee <walt@tilera.com>
-
- * Makefile.am: Add TILE-Gx/TILEPro support.
- * configure.ac: Likewise.
- * Makefile.in: Regenerate.
- * configure: Likewise.
- * src/prep_cif.c (ffi_prep_cif_core): Handle TILE-Gx/TILEPro.
- * src/tile: New directory.
- * src/tile/ffi.c: New file.
- * src/tile/ffitarget.h: Ditto.
- * src/tile/tile.S: Ditto.
-
-2012-10-12 Matthias Klose <doko@ubuntu.com>
-
- * generate-osx-source-and-headers.py: Normalize whitespace.
-
-2012-09-14 David Edelsohn <dje.gcc@gmail.com>
-
- * configure: Regenerated.
-
-2012-08-26 Andrew Pinski <apinski@cavium.com>
-
- PR libffi/53014
- * src/mips/ffi.c (ffi_prep_closure_loc): Allow n32 with soft-float and n64 with
- soft-float.
-
-2012-08-08 Uros Bizjak <ubizjak@gmail.com>
-
- * src/s390/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test,
- just return FFI_BAD_ABI when things are wrong.
-
-2012-07-18 H.J. Lu <hongjiu.lu@intel.com>
-
- PR libffi/53982
- PR libffi/53973
- * src/x86/ffitarget.h: Check __ILP32__ instead of __LP64__ for x32.
- (FFI_SIZEOF_JAVA_RAW): Defined to 4 for x32.
-
-2012-05-16 H.J. Lu <hongjiu.lu@intel.com>
-
- * configure: Regenerated.
-
-2012-05-05 Nicolas Lelong
-
- * libffi.xcodeproj/project.pbxproj: Fixes.
- * README: Update for iOS builds.
-
-2012-04-23 Alexandre Keunecke I. de Mendonca <alexandre.keunecke@gmail.com>
-
- * configure.ac: Add Blackfin/sysv support
- * Makefile.am: Add Blackfin/sysv support
- * src/bfin/ffi.c: Add Blackfin/sysv support
- * src/bfin/ffitarget.h: Add Blackfin/sysv support
-
-2012-04-11 Anthony Green <green@moxielogic.com>
-
- * Makefile.am (EXTRA_DIST): Add new script.
- * Makefile.in: Rebuilt.
-
-2012-04-11 Zachary Waldowski <zwaldowski@gmail.com>
-
- * generate-ios-source-and-headers.py,
- libffi.xcodeproj/project.pbxproj: Support a Mac static library via
- Xcode. Set iOS compatibility to 4.0. Move iOS trampoline
- generation into an Xcode "run script" phase. Include both as
- Xcode build scripts. Don't always regenerate config files.
-
-2012-04-10 Anthony Green <green@moxielogic.com>
-
- * src/powerpc/ffi_darwin.c (ffi_prep_args): Add missing semicolon.
-
-2012-04-06 Anthony Green <green@moxielogic.com>
-
- * Makefile.am (EXTRA_DIST): Add new iOS/xcode files.
- * Makefile.in: Rebuilt.
-
-2012-04-06 Mike Lewis <mikelikespie@gmail.com>
-
- * generate-ios-source-and-headers.py: New file.
- * libffi.xcodeproj/project.pbxproj: New file.
- * README: Update instructions on building iOS binary.
- * build-ios.sh: Delete.
-
-2012-04-06 Anthony Green <green@moxielogic.com>
-
- * src/x86/ffi64.c (UINT128): Define differently for Intel and GNU
- compilers, then use it.
-
-2012-04-06 H.J. Lu <hongjiu.lu@intel.com>
-
- * m4/libtool.m4 (_LT_ENABLE_LOCK): Support x32.
-
-2012-04-06 Anthony Green <green@moxielogic.com>
-
- * testsuite/Makefile.am (EXTRA_DIST): Add missing test cases.
- * testsuite/Makefile.in: Rebuilt.
-
-2012-04-05 Zachary Waldowski <zwaldowski@gmail.com>
-
- * include/ffi.h.in: Add missing trampoline table fields.
- * src/arm/sysv.S: Fix ENTRY definition, and wrap symbol references
- in CNAME.
- * src/x86/ffi.c: Wrap Windows specific code in ifdefs.
-
-2012-04-02 Peter Bergner <bergner@vnet.ibm.com>
-
- * src/powerpc/ffi.c (ffi_prep_args_SYSV): Declare double_tmp.
- Silence casting pointer to integer of different size warning.
- Delete goto to previously deleted label.
- (ffi_call): Silence possibly undefined warning.
- (ffi_closure_helper_SYSV): Declare variable type.
-
-2012-04-02 Peter Rosin <peda@lysator.liu.se>
-
- * src/x86/win32.S (ffi_call_win32): Sign/zero extend the return
- value in the Intel version as is already done for the AT&T version.
- (ffi_closure_SYSV): Likewise.
- (ffi_closure_raw_SYSV): Likewise.
- (ffi_closure_STDCALL): Likewise.
-
-2012-03-29 Peter Rosin <peda@lysator.liu.se>
-
- * src/x86/win32.S (ffi_closure_raw_THISCALL): Unify the frame
- generation, fix the ENDP label and remove the surplus third arg
- from the 'lea' insn.
-
-2012-03-29 Peter Rosin <peda@lysator.liu.se>
-
- * src/x86/win32.S (ffi_closure_raw_SYSV): Make the 'stubraw' label
- visible outside the PROC, so that ffi_closure_raw_THISCALL can see
- it. Also instruct the assembler to add a frame to the function.
-
-2012-03-23 Peter Rosin <peda@lysator.liu.se>
-
- * Makefile.am (AM_CPPFLAGS): Add -DFFI_BUILDING.
- * Makefile.in: Rebuilt.
- * include/ffi.h.in [MSVC]: Add __declspec(dllimport) decorations
- to all data exports, when compiling libffi clients using MSVC.
-
-2012-03-29 Peter Rosin <peda@lysator.liu.se>
-
- * src/x86/ffitarget.h (ffi_abi): Add new ABI FFI_MS_CDECL and
- make it the default for MSVC.
- (FFI_TYPE_MS_STRUCT): New structure return convention.
- * src/x86/ffi.c (ffi_prep_cif_machdep): Tweak the structure
- return convention for FFI_MS_CDECL to be FFI_TYPE_MS_STRUCT
- instead of an ordinary FFI_TYPE_STRUCT.
- (ffi_prep_args): Treat FFI_TYPE_MS_STRUCT as FFI_TYPE_STRUCT.
- (ffi_call): Likewise.
- (ffi_prep_incoming_args_SYSV): Likewise.
- (ffi_raw_call): Likewise.
- (ffi_prep_closure_loc): Treat FFI_MS_CDECL as FFI_SYSV.
- * src/x86/win32.S (ffi_closure_SYSV): For FFI_TYPE_MS_STRUCT,
- return a pointer to the result structure in eax and don't pop
- that pointer from the stack, the caller takes care of it.
- (ffi_call_win32): Treat FFI_TYPE_MS_STRUCT as FFI_TYPE_STRUCT.
- (ffi_closure_raw_SYSV): Likewise.
-
-2012-03-22 Peter Rosin <peda@lysator.liu.se>
-
- * testsuite/libffi.call/closure_stdcall.c [MSVC]: Add inline
- assembly version with Intel syntax.
- * testsuite/libffi.call/closure_thiscall.c [MSVC]: Likewise.
-
-2012-03-23 Peter Rosin <peda@lysator.liu.se>
-
- * testsuite/libffi.call/ffitest.h: Provide abstration of
- __attribute__((fastcall)) in the form of a __FASTCALL__
- define. Define it to __fastcall for MSVC.
- * testsuite/libffi.call/fastthis1_win32.c: Use the above.
- * testsuite/libffi.call/fastthis2_win32.c: Likewise.
- * testsuite/libffi.call/fastthis3_win32.c: Likewise.
- * testsuite/libffi.call/strlen2_win32.c: Likewise.
- * testsuite/libffi.call/struct1_win32.c: Likewise.
- * testsuite/libffi.call/struct2_win32.c: Likewise.
-
-2012-03-22 Peter Rosin <peda@lysator.liu.se>
-
- * src/x86/win32.S [MSVC] (ffi_closure_THISCALL): Remove the manual
- frame on function entry, MASM adds one automatically.
-
-2012-03-22 Peter Rosin <peda@lysator.liu.se>
-
- * testsuite/libffi.call/ffitest.h [MSVC]: Add kludge for missing
- bits in the MSVC headers.
-
-2012-03-22 Peter Rosin <peda@lysator.liu.se>
-
- * testsuite/libffi.call/cls_12byte.c: Adjust to the C89 style
- with no declarations after statements.
- * testsuite/libffi.call/cls_16byte.c: Likewise.
- * testsuite/libffi.call/cls_18byte.c: Likewise.
- * testsuite/libffi.call/cls_19byte.c: Likewise.
- * testsuite/libffi.call/cls_1_1byte.c: Likewise.
- * testsuite/libffi.call/cls_20byte.c: Likewise.
- * testsuite/libffi.call/cls_20byte1.c: Likewise.
- * testsuite/libffi.call/cls_24byte.c: Likewise.
- * testsuite/libffi.call/cls_2byte.c: Likewise.
- * testsuite/libffi.call/cls_3_1byte.c: Likewise.
- * testsuite/libffi.call/cls_3byte1.c: Likewise.
- * testsuite/libffi.call/cls_3byte2.c: Likewise.
- * testsuite/libffi.call/cls_4_1byte.c: Likewise.
- * testsuite/libffi.call/cls_4byte.c: Likewise.
- * testsuite/libffi.call/cls_5_1_byte.c: Likewise.
- * testsuite/libffi.call/cls_5byte.c: Likewise.
- * testsuite/libffi.call/cls_64byte.c: Likewise.
- * testsuite/libffi.call/cls_6_1_byte.c: Likewise.
- * testsuite/libffi.call/cls_6byte.c: Likewise.
- * testsuite/libffi.call/cls_7_1_byte.c: Likewise.
- * testsuite/libffi.call/cls_7byte.c: Likewise.
- * testsuite/libffi.call/cls_8byte.c: Likewise.
- * testsuite/libffi.call/cls_9byte1.c: Likewise.
- * testsuite/libffi.call/cls_9byte2.c: Likewise.
- * testsuite/libffi.call/cls_align_double.c: Likewise.
- * testsuite/libffi.call/cls_align_float.c: Likewise.
- * testsuite/libffi.call/cls_align_longdouble.c: Likewise.
- * testsuite/libffi.call/cls_align_longdouble_split.c: Likewise.
- * testsuite/libffi.call/cls_align_longdouble_split2.c: Likewise.
- * testsuite/libffi.call/cls_align_pointer.c: Likewise.
- * testsuite/libffi.call/cls_align_sint16.c: Likewise.
- * testsuite/libffi.call/cls_align_sint32.c: Likewise.
- * testsuite/libffi.call/cls_align_sint64.c: Likewise.
- * testsuite/libffi.call/cls_align_uint16.c: Likewise.
- * testsuite/libffi.call/cls_align_uint32.c: Likewise.
- * testsuite/libffi.call/cls_align_uint64.c: Likewise.
- * testsuite/libffi.call/cls_dbls_struct.c: Likewise.
- * testsuite/libffi.call/cls_pointer_stack.c: Likewise.
- * testsuite/libffi.call/err_bad_typedef.c: Likewise.
- * testsuite/libffi.call/huge_struct.c: Likewise.
- * testsuite/libffi.call/nested_struct.c: Likewise.
- * testsuite/libffi.call/nested_struct1.c: Likewise.
- * testsuite/libffi.call/nested_struct10.c: Likewise.
- * testsuite/libffi.call/nested_struct2.c: Likewise.
- * testsuite/libffi.call/nested_struct3.c: Likewise.
- * testsuite/libffi.call/nested_struct4.c: Likewise.
- * testsuite/libffi.call/nested_struct5.c: Likewise.
- * testsuite/libffi.call/nested_struct6.c: Likewise.
- * testsuite/libffi.call/nested_struct7.c: Likewise.
- * testsuite/libffi.call/nested_struct8.c: Likewise.
- * testsuite/libffi.call/nested_struct9.c: Likewise.
- * testsuite/libffi.call/stret_large.c: Likewise.
- * testsuite/libffi.call/stret_large2.c: Likewise.
- * testsuite/libffi.call/stret_medium.c: Likewise.
- * testsuite/libffi.call/stret_medium2.c: Likewise.
- * testsuite/libffi.call/struct1.c: Likewise.
- * testsuite/libffi.call/struct1_win32.c: Likewise.
- * testsuite/libffi.call/struct2.c: Likewise.
- * testsuite/libffi.call/struct2_win32.c: Likewise.
- * testsuite/libffi.call/struct3.c: Likewise.
- * testsuite/libffi.call/struct4.c: Likewise.
- * testsuite/libffi.call/struct5.c: Likewise.
- * testsuite/libffi.call/struct6.c: Likewise.
- * testsuite/libffi.call/struct7.c: Likewise.
- * testsuite/libffi.call/struct8.c: Likewise.
- * testsuite/libffi.call/struct9.c: Likewise.
- * testsuite/libffi.call/testclosure.c: Likewise.
-
-2012-03-21 Peter Rosin <peda@lysator.liu.se>
-
- * testsuite/libffi.call/float_va.c (float_va_fn): Use %f when
- printing doubles (%lf is for long doubles).
- (main): Likewise.
-
-2012-03-21 Peter Rosin <peda@lysator.liu.se>
-
- * testsuite/lib/target-libpath.exp [*-*-cygwin*, *-*-mingw*]
- (set_ld_library_path_env_vars): Add the library search dir to PATH
- (and save PATH for later).
- (restore_ld_library_path_env_vars): Restore PATH.
-
-2012-03-21 Peter Rosin <peda@lysator.liu.se>
-
- * testsuite/lib/target-libpath.exp [*-*-cygwin*, *-*-mingw*]
- (set_ld_library_path_env_vars): Add the library search dir to PATH
- (and save PATH for later).
- (restore_ld_library_path_env_vars): Restore PATH.
-
-2012-03-20 Peter Rosin <peda@lysator.liu.se>
-
- * testsuite/libffi.call/strlen2_win32.c (main): Remove bug.
- * src/x86/win32.S [MSVC] (ffi_closure_SYSV): Make the 'stub' label
- visible outside the PROC, so that ffi_closure_THISCALL can see it.
-
-2012-03-20 Peter Rosin <peda@lysator.liu.se>
-
- * testsuite/libffi.call/strlen2_win32.c (main): Remove bug.
- * src/x86/win32.S [MSVC] (ffi_closure_SYSV): Make the 'stub' label
- visible outside the PROC, so that ffi_closure_THISCALL can see it.
-
-2012-03-19 Alan Hourihane <alanh@fairlite.co.uk>
-
- * src/m68k/ffi.c: Add MINT support.
- * src/m68k/sysv.S: Ditto.
-
-2012-03-06 Chung-Lin Tang <cltang@codesourcery.com>
-
- * src/arm/ffi.c (ffi_call): Add __ARM_EABI__ guard around call to
- ffi_call_VFP().
- (ffi_prep_closure_loc): Add __ARM_EABI__ guard around use of
- ffi_closure_VFP.
- * src/arm/sysv.S: Add __ARM_EABI__ guard around VFP code.
-
-2012-03-19 chennam <csit@axway.com>
-
- * src/powerpc/ffi_darwin.c (ffi_prep_closure_loc): Fix AIX closure
- support.
-
-2012-03-13 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test,
- just return FFI_BAD_ABI when things are wrong.
- * src/sh64/ffi.c (ffi_prep_closure_loc): Ditto.
-
-2012-03-09 David Edelsohn <dje.gcc@gmail.com>
-
- * src/powerpc/aix_closure.S (ffi_closure_ASM): Adjust for Darwin64
- change to return value of ffi_closure_helper_DARWIN and load type
- from return type.
-
-2012-03-03 H.J. Lu <hongjiu.lu@intel.com>
-
- * src/x86/ffi64.c (ffi_call): Cast the return value to unsigned
- long.
- (ffi_prep_closure_loc): Cast to 64bit address in trampoline.
- (ffi_closure_unix64_inner): Cast return pointer to unsigned long
- first.
-
- * src/x86/ffitarget.h (FFI_SIZEOF_ARG): Defined to 8 for x32.
- (ffi_arg): Set to unsigned long long for x32.
- (ffi_sarg): Set to long long for x32.
-
-2012-03-03 H.J. Lu <hongjiu.lu@intel.com>
-
- * src/prep_cif.c (ffi_prep_cif_core): Properly check bad ABI.
-
-2012-03-03 Andoni Morales Alastruey <ylatuya@gmail.com>
-
- * configure.ac: Add -no-undefined for both 32- and 64-bit x86
- windows-like hosts.
- * configure: Rebuilt.
-
-2012-02-27 Mikael Pettersson <mikpe@it.uu.se>
-
- PR libffi/52223
- * Makefile.am (FLAGS_TO_PASS): Define.
- * Makefile.in: Regenerate.
-
-2012-02-23 Anthony Green <green@moxielogic.com>
-
- * src/*/ffitarget.h: Ensure that users never include ffitarget.h
- directly.
-
-2012-02-23 Kai Tietz <ktietz@redhat.com>
-
- PR libffi/52221
- * src/x86/ffi.c (ffi_closure_raw_THISCALL): New
- prototype.
- (ffi_prep_raw_closure_loc): Use ffi_closure_raw_THISCALL for
- thiscall-convention.
- (ffi_raw_call): Use ffi_prep_args_raw.
- * src/x86/win32.S (ffi_closure_raw_THISCALL): Add
- implementation for stub.
-
-2012-02-10 Kai Tietz <ktietz@redhat.com>
-
- * configure.ac (AM_LTLDFLAGS): Add -no-undefine for x64
- windows target.
- * configure: Regenerated.
-
-2012-02-08 Kai Tietz <ktietz@redhat.com>
-
- * src/prep_cif.c (ffi_prep_cif): Allow for X86_WIN32
- also FFI_THISCALL.
- * src/x86/ffi.c (ffi_closure_THISCALL): Add prototype.
- (FFI_INIT_TRAMPOLINE_THISCALL): New trampoline code.
- (ffi_prep_closure_loc): Add FFI_THISCALL support.
- * src/x86/ffitarget.h (FFI_TRAMPOLINE_SIZE): Adjust size.
- * src/x86/win32.S (ffi_closure_THISCALL): New closure code
- for thiscall-calling convention.
- * testsuite/libffi.call/closure_thiscall.c: New test.
-
-2012-01-28 Kai Tietz <ktietz@redhat.com>
-
- * src/libffi/src/x86/ffi.c (ffi_call_win32): Add new
- argument to prototype for specify calling-convention.
- (ffi_call): Add support for stdcall/thiscall convention.
- (ffi_prep_args): Likewise.
- (ffi_raw_call): Likewise.
- * src/x86/ffitarget.h (ffi_abi): Add FFI_THISCALL and
- FFI_FASTCALL.
- * src/x86/win32.S (_ffi_call_win32): Add support for
- fastcall/thiscall calling-convention calls.
- * testsuite/libffi.call/fastthis1_win32.c: New test.
- * testsuite/libffi.call/fastthis2_win32.c: New test.
- * testsuite/libffi.call/fastthis3_win32.c: New test.
- * testsuite/libffi.call/strlen2_win32.c: New test.
- * testsuite/libffi.call/many2_win32.c: New test.
- * testsuite/libffi.call/struct1_win32.c: New test.
- * testsuite/libffi.call/struct2_win32.c: New test.
-
-2012-01-23 Uros Bizjak <ubizjak@gmail.com>
-
- * src/alpha/ffi.c (ffi_prep_closure_loc): Check for bad ABI.
-
-2012-01-23 Anthony Green <green@moxielogic.com>
- Chris Young <cdyoung@ntlworld.com>
-
- * configure.ac: Add Amiga support.
- * configure: Rebuilt.
-
-2012-01-23 Dmitry Nadezhin <dmitry.nadezhin@gmail.com>
-
- * include/ffi_common.h (LIKELY, UNLIKELY): Fix definitions.
-
-2012-01-23 Andreas Schwab <schwab@linux-m68k.org>
-
- * src/m68k/sysv.S (ffi_call_SYSV): Properly test for plain
- mc68000. Test for __HAVE_68881__ in addition to __MC68881__.
-
-2012-01-19 Jakub Jelinek <jakub@redhat.com>
-
- PR rtl-optimization/48496
- * src/ia64/ffi.c (ffi_call): Fix up aliasing violations.
-
-2012-01-09 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * configure.ac (i?86-*-*): Set TARGET to X86_64.
- * configure: Regenerate.
-
-2011-12-07 Andrew Pinski <apinski@cavium.com>
-
- PR libffi/50051
- * src/mips/n32.S: Add ".set mips4".
-
-2011-11-21 Andreas Tobler <andreast@fgznet.ch>
-
- * configure: Regenerate.
-
-2011-11-12 David Gilbert <david.gilbert@linaro.org>
-
- * doc/libffi.texi, include/ffi.h.in, include/ffi_common.h,
- man/Makefile.am, man/ffi.3, man/ffi_prep_cif.3,
- man/ffi_prep_cif_var.3, src/arm/ffi.c, src/arm/ffitarget.h,
- src/cris/ffi.c, src/prep_cif.c,
- testsuite/libffi.call/cls_double_va.c,
- testsuite/libffi.call/cls_longdouble_va.c,
- testsuite/libffi.call/float_va.c: Many changes to support variadic
- function calls.
-
-2011-11-12 Kyle Moffett <Kyle.D.Moffett@boeing.com>
-
- * src/powerpc/ffi.c, src/powerpc/ffitarget.h,
- src/powerpc/ppc_closure.S, src/powerpc/sysv.S: Many changes for
- softfloat powerpc variants.
-
-2011-11-12 Petr Salinger <Petr.Salinger@seznam.cz>
-
- * configure.ac (FFI_EXEC_TRAMPOLINE_TABLE): Fix kfreebsd support.
- * configure: Rebuilt.
-
-2011-11-12 Timothy Wall <twall@users.sf.net>
-
- * src/arm/ffi.c (ffi_prep_args, ffi_prep_incoming_args_SYSV): Max
- alignment of 4 for wince on ARM.
-
-2011-11-12 Kyle Moffett <Kyle.D.Moffett@boeing.com>
- Anthony Green <green@moxielogic.com>
-
- * src/ppc/sysv.S, src/ppc/ffi.c: Remove use of ppc string
- instructions (not available on some cores, like the PPC440).
-
-2011-11-12 Kimura Wataru <kimuraw@i.nifty.jp>
-
- * m4/ax_enable_builddir: Change from string comparison to numeric
- comparison for wc output.
- * configure.ac: Enable FFI_MMAP_EXEC_WRIT for darwin11 aka Mac OS
- X 10.7.
- * configure: Rebuilt.
-
-2011-11-12 Anthony Green <green@moxielogic.com>
-
- * Makefile.am (AM_CCASFLAGS): Add -g option to build assembly
- files with debug info.
- * Makefile.in: Rebuilt.
-
-2011-11-12 Jasper Lievisse Adriaanse <jasper@openbsd.org>
-
- * README: Update list of supported OpenBSD systems.
-
-2011-11-12 Anthony Green <green@moxielogic.com>
-
- * libtool-version: Update.
- * Makefile.am (nodist_libffi_la_SOURCES): Add src/debug.c if
- FFI_DEBUG.
- (libffi_la_SOURCES): Remove src/debug.c
- (EXTRA_DIST): Add src/debug.c
- * Makefile.in: Rebuilt.
- * README: Update for 3.0.11.
-
-2011-11-10 Richard Henderson <rth@redhat.com>
-
- * configure.ac (GCC_AS_CFI_PSEUDO_OP): Use it instead of inline check.
- * configure, aclocal.m4: Rebuild.
-
-2011-09-04 Iain Sandoe <iains@gcc.gnu.org>
-
- PR libffi/49594
- * src/powerpc/darwin_closure.S (stubs): Make the stub binding
- helper reference track the architecture pointer size.
-
-2011-08-25 Andrew Haley <aph@redhat.com>
-
- * src/arm/ffi.c (FFI_INIT_TRAMPOLINE): Remove hard-coded assembly
- instructions.
- * src/arm/sysv.S (ffi_arm_trampoline): Put them here instead.
-
-2011-07-11 Andrew Haley <aph@redhat.com>
-
- * src/arm/ffi.c (FFI_INIT_TRAMPOLINE): Clear icache.
-
-2011-06-29 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * testsuite/libffi.call/cls_double_va.c: Move PR number to comment.
- * testsuite/libffi.call/cls_longdouble_va.c: Likewise.
-
-2011-06-29 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- PR libffi/46660
- * testsuite/libffi.call/cls_double_va.c: xfail dg-output on
- mips-sgi-irix6*.
- * testsuite/libffi.call/cls_longdouble_va.c: Likewise.
-
-2011-06-14 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * testsuite/libffi.call/huge_struct.c (test_large_fn): Use PRIu8,
- PRId8 instead of %hhu, %hhd.
- * testsuite/libffi.call/ffitest.h [__alpha__ && __osf__] (PRId8,
- PRIu8): Define.
- [__sgi__] (PRId8, PRIu8): Define.
-
-2011-04-29 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * src/alpha/osf.S (UA_SI, FDE_ENCODING, FDE_ENCODE, FDE_ARANGE):
- Define.
- Use them to handle ELF vs. ECOFF differences.
- [__osf__] (_GLOBAL__F_ffi_call_osf): Define.
-
-2011-03-30 Timothy Wall <twall@users.sf.net>
-
- * src/powerpc/darwin.S: Fix unknown FDE encoding.
- * src/powerpc/darwin_closure.S: ditto.
-
-2011-02-25 Anthony Green <green@moxielogic.com>
-
- * src/powerpc/ffi.c (ffi_prep_closure_loc): Allow for more
- 32-bit ABIs.
-
-2011-02-15 Anthony Green <green@moxielogic.com>
-
- * m4/ax_cc_maxopt.m4: Don't -malign-double or use -ffast-math.
- * configure: Rebuilt.
-
-2011-02-13 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
-
- * configure: Regenerate.
-
-2011-02-13 Anthony Green <green@moxielogic.com>
-
- * include/ffi_common.h (UNLIKELY, LIKELY): Define.
- * src/x86/ffi64.c (UNLIKELY, LIKELY): Remove definition.
- * src/prep_cif.c (UNLIKELY, LIKELY): Remove definition.
-
- * src/prep_cif.c (initialize_aggregate): Convert assertion into
- FFI_BAD_TYPEDEF return. Initialize arg size and alignment to 0.
-
- * src/pa/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test,
- just return FFI_BAD_ABI when things are wrong.
- * src/arm/ffi.c (ffi_prep_closure_loc): Ditto.
- * src/powerpc/ffi.c (ffi_prep_closure_loc): Ditto.
- * src/mips/ffi.c (ffi_prep_closure_loc): Ditto.
- * src/ia64/ffi.c (ffi_prep_closure_loc): Ditto.
- * src/avr32/ffi.c (ffi_prep_closure_loc): Ditto.
-
-2011-02-11 Anthony Green <green@moxielogic.com>
-
- * src/sparc/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test,
- just return FFI_BAD_ABI when things are wrong.
-
-2012-02-11 Eric Botcazou <ebotcazou@adacore.com>
-
- * src/sparc/v9.S (STACKFRAME): Bump to 176.
-
-2011-02-09 Stuart Shelton <srcshelton@gmail.com>
-
- http://bugs.gentoo.org/show_bug.cgi?id=286911
- * src/mips/ffitarget.h: Clean up error messages.
- * src/java_raw_api.c (ffi_java_translate_args): Cast raw arg to
- ffi_raw*.
- * include/ffi.h.in: Add pragma for SGI compiler.
-
-2011-02-09 Anthony Green <green@moxielogic.com>
-
- * configure.ac: Add powerpc64-*-darwin* support.
-
-2011-02-09 Anthony Green <green@moxielogic.com>
-
- * README: Mention Interix.
-
-2011-02-09 Jonathan Callen <abcd@gentoo.org>
-
- * configure.ac: Add Interix to win32/cygwin/mingw case.
- * configure: Ditto.
- * src/closures.c: Treat Interix like Cygwin, instead of as a
- generic win32.
-
-2011-02-09 Anthony Green <green@moxielogic.com>
-
- * testsuite/libffi.call/err_bad_typedef.c: Remove xfail.
- * testsuite/libffi.call/err_bad_abi.c: Remove xfail.
- * src/x86/ffi64.c (UNLIKELY, LIKELY): Define.
- (ffi_prep_closure_loc): Check for bad ABI.
- * src/prep_cif.c (UNLIKELY, LIKELY): Define.
- (initialize_aggregate): Check for bad types.
-
-2011-02-09 Landon Fuller <landonf@plausible.coop>
-
- * Makefile.am (EXTRA_DIST): Add build-ios.sh, src/arm/gentramp.sh,
- src/arm/trampoline.S.
- (nodist_libffi_la_SOURCES): Add src/arc/trampoline.S.
- * configure.ac (FFI_EXEC_TRAMPOLINE_TABLE): Define.
- * src/arm/ffi.c (ffi_trampoline_table)
- (ffi_closure_trampoline_table_page, ffi_trampoline_table_entry)
- (FFI_TRAMPOLINE_CODELOC_CONFIG, FFI_TRAMPOLINE_CONFIG_PAGE_OFFSET)
- (FFI_TRAMPOLINE_COUNT, ffi_trampoline_lock, ffi_trampoline_tables)
- (ffi_trampoline_table_alloc, ffi_closure_alloc, ffi_closure_free):
- Define for FFI_EXEC_TRAMPOLINE_TABLE case (iOS).
- (ffi_prep_closure_loc): Handl FFI_EXEC_TRAMPOLINE_TABLE case
- separately.
- * src/arm/sysv.S: Handle Apple iOS host.
- * src/closures.c: Handle FFI_EXEC_TRAMPOLINE_TABLE case.
- * build-ios.sh: New file.
- * fficonfig.h.in, configure, Makefile.in: Rebuilt.
- * README: Mention ARM iOS.
-
-2011-02-08 Oren Held <orenhe@il.ibm.com>
-
- * src/dlmalloc.c (_STRUCT_MALLINFO): Define in order to avoid
- redefinition of mallinfo on HP-UX.
-
-2011-02-08 Ginn Chen <ginn.chen@oracle.com>
-
- * src/sparc/ffi.c (ffi_call): Make compatible with Solaris Studio
- aggregate return ABI. Flush cache.
- (ffi_prep_closure_loc): Flush cache.
-
-2011-02-11 Anthony Green <green@moxielogic.com>
-
- From Tom Honermann <tom.honermann@oracle.com>:
- * src/powerpc/aix.S (ffi_call_AIX): Support for xlc toolchain on
- AIX. Declare .ffi_prep_args. Insert nops after branch
- instructions so that the AIX linker can insert TOC reload
- instructions.
- * src/powerpc/aix_closure.S: Declare .ffi_closure_helper_DARWIN.
-
-2011-02-08 Ed <ed@kdtc.net>
-
- * src/powerpc/asm.h: Fix grammar nit in comment.
-
-2011-02-08 Uli Link <ul.mcamafia@linkitup.de>
-
- * include/ffi.h.in (FFI_64_BIT_MAX): Define and use.
-
-2011-02-09 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- PR libffi/46661
- * testsuite/libffi.call/cls_pointer.c (main): Cast void * to
- uintptr_t first.
- * testsuite/libffi.call/cls_pointer_stack.c (main): Likewise.
-
-2011-02-08 Rafael Avila de Espindola <respindola@mozilla.com>
-
- * configure.ac: Fix x86 test for pc related relocs.
- * configure: Rebuilt.
-
-2011-02-07 Joel Sherrill <joel.sherrill@oarcorp.com>
-
- * libffi/src/m68k/ffi.c: Add RTEMS support for cache flushing.
- Handle case when CPU variant does not have long double support.
- * libffi/src/m68k/sysv.S: Add support for mc68000, Coldfire,
- and cores with soft floating point.
-
-2011-02-07 Joel Sherrill <joel.sherrill@oarcorp.com>
-
- * configure.ac: Add mips*-*-rtems* support.
- * configure: Regenerate.
- * src/mips/ffitarget.h: Ensure needed constants are available
- for targets which do not have sgidefs.h.
-
-2011-01-26 Dave Korn <dave.korn.cygwin@gmail.com>
-
- PR target/40125
- * configure.ac (AM_LTLDFLAGS): Add -bindir option for windows DLLs.
- * configure: Regenerate.
-
-2010-12-18 Iain Sandoe <iains@gcc.gnu.org>
-
- PR libffi/29152
- PR libffi/42378
- * src/powerpc/darwin_closure.S: Provide Darwin64 implementation,
- update comments.
- * src/powerpc/ffitarget.h (POWERPC_DARWIN64): New,
- (FFI_TRAMPOLINE_SIZE): Update for Darwin64.
- * src/powerpc/darwin.S: Provide Darwin64 implementation,
- update comments.
- * src/powerpc/ffi_darwin.c: Likewise.
-
-2010-12-06 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * configure.ac (libffi_cv_as_ascii_pseudo_op): Use double
- backslashes.
- (libffi_cv_as_string_pseudo_op): Likewise.
- * configure: Regenerate.
-
-2010-12-03 Chung-Lin Tang <cltang@codesourcery.com>
-
- * src/arm/sysv.S (ffi_closure_SYSV): Add UNWIND to .pad directive.
- (ffi_closure_VFP): Same.
- (ffi_call_VFP): Move down to before ffi_closure_VFP. Add '.fpu vfp'
- directive.
-
-2010-12-01 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * testsuite/libffi.call/ffitest.h [__sgi] (PRId64, PRIu64): Define.
- (PRIuPTR): Define.
-
-2010-11-29 Richard Henderson <rth@redhat.com>
- Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * src/x86/sysv.S (FDE_ENCODING, FDE_ENCODE): Define.
- (.eh_frame): Use FDE_ENCODING.
- (.LASFDE1, .LASFDE2, LASFDE3): Simplify with FDE_ENCODE.
-
-2010-11-22 Jacek Caban <jacek@codeweavers.com>
-
- * configure.ac: Check for symbol underscores on mingw-w64.
- * configure: Rebuilt.
- * src/x86/win64.S: Correctly access extern symbols in respect to
- underscores.
-
-2010-11-15 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * testsuite/lib/libffi-dg.exp: Rename ...
- * testsuite/lib/libffi.exp: ... to this.
- * libffi/testsuite/libffi.call/call.exp: Don't load libffi-dg.exp.
- * libffi/testsuite/libffi.special/special.exp: Likewise.
-
-2010-10-28 Chung-Lin Tang <cltang@codesourcery.com>
-
- * src/arm/ffi.c (ffi_prep_args): Add VFP register argument handling
- code, new parameter, and return value. Update comments.
- (ffi_prep_cif_machdep): Add case for VFP struct return values. Add
- call to layout_vfp_args().
- (ffi_call_SYSV): Update declaration.
- (ffi_call_VFP): New declaration.
- (ffi_call): Add VFP struct return conditions. Call ffi_call_VFP()
- when ABI is FFI_VFP.
- (ffi_closure_VFP): New declaration.
- (ffi_closure_SYSV_inner): Add new vfp_args parameter, update call to
- ffi_prep_incoming_args_SYSV().
- (ffi_prep_incoming_args_SYSV): Update parameters. Add VFP argument
- case handling.
- (ffi_prep_closure_loc): Pass ffi_closure_VFP to trampoline
- construction under VFP hard-float.
- (rec_vfp_type_p): New function.
- (vfp_type_p): Same.
- (place_vfp_arg): Same.
- (layout_vfp_args): Same.
- * src/arm/ffitarget.h (ffi_abi): Add FFI_VFP. Define FFI_DEFAULT_ABI
- based on __ARM_PCS_VFP.
- (FFI_EXTRA_CIF_FIELDS): Define for adding VFP hard-float specific
- fields.
- (FFI_TYPE_STRUCT_VFP_FLOAT): Define internally used type code.
- (FFI_TYPE_STRUCT_VFP_DOUBLE): Same.
- * src/arm/sysv.S (ffi_call_SYSV): Change call of ffi_prep_args() to
- direct call. Move function pointer load upwards.
- (ffi_call_VFP): New function.
- (ffi_closure_VFP): Same.
-
- * testsuite/lib/libffi-dg.exp (check-flags): New function.
- (dg-skip-if): New function.
- * testsuite/libffi.call/cls_double_va.c: Skip if target is arm*-*-*
- and compiler options include -mfloat-abi=hard.
- * testsuite/libffi.call/cls_longdouble_va.c: Same.
-
-2010-10-01 Jakub Jelinek <jakub@redhat.com>
-
- PR libffi/45677
- * src/x86/ffi64.c (ffi_prep_cif_machdep): Ensure cif->bytes is
- a multiple of 8.
- * testsuite/libffi.call/many2.c: New test.
-
-2010-08-20 Mark Wielaard <mjw@redhat.com>
-
- * src/closures.c (open_temp_exec_file_mnt): Check if getmntent_r
- returns NULL.
-
-2010-08-09 Andreas Tobler <andreast@fgznet.ch>
-
- * configure.ac: Add target powerpc64-*-freebsd*.
- * configure: Regenerate.
- * testsuite/libffi.call/cls_align_longdouble_split.c: Pass
- -mlong-double-128 only to linux targets.
- * testsuite/libffi.call/cls_align_longdouble_split2.c: Likewise.
- * testsuite/libffi.call/cls_longdouble.c: Likewise.
- * testsuite/libffi.call/huge_struct.c: Likewise.
-
-2010-08-05 Dan Witte <dwitte@mozilla.com>
-
- * Makefile.am: Pass FFI_DEBUG define to msvcc.sh for linking to the
- debug CRT when --enable-debug is given.
- * configure.ac: Define it.
- * msvcc.sh: Translate -g and -DFFI_DEBUG appropriately.
-
-2010-08-04 Dan Witte <dwitte@mozilla.com>
-
- * src/x86/ffitarget.h: Add X86_ANY define for all x86/x86_64
- platforms.
- * src/x86/ffi.c: Remove redundant ifdef checks.
- * src/prep_cif.c: Push stack space computation into src/x86/ffi.c
- for X86_ANY so return value space doesn't get added twice.
-
-2010-08-03 Neil Rashbrooke <neil@parkwaycc.co.uk>
-
- * msvcc.sh: Don't pass -safeseh to ml64 because behavior is buggy.
-
-2010-07-22 Dan Witte <dwitte@mozilla.com>
-
- * src/*/ffitarget.h: Make FFI_LAST_ABI one past the last valid ABI.
- * src/prep_cif.c: Fix ABI assertion.
- * src/cris/ffi.c: Ditto.
-
-2010-07-10 Evan Phoenix <evan@fallingsnow.net>
-
- * src/closures.c (selinux_enabled_check): Fix strncmp usage bug.
-
-2010-07-07 Dan Horák <dan@danny.cz>
-
- * include/ffi.h.in: Protect #define with #ifndef.
- * src/powerpc/ffitarget.h: Ditto.
- * src/s390/ffitarget.h: Ditto.
- * src/sparc/ffitarget.h: Ditto.
-
-2010-07-07 Neil Roberts <neil@linux.intel.com>
-
- * src/x86/sysv.S (ffi_call_SYSV): Align the stack pointer to
- 16-bytes.
-
-2010-07-02 Jakub Jelinek <jakub@redhat.com>
-
- * Makefile.am (AM_MAKEFLAGS): Pass also mandir to submakes.
- * Makefile.in: Regenerated.
-
-2010-05-19 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * configure.ac (libffi_cv_as_x86_pcrel): Check for illegal in as
- output, too.
- (libffi_cv_as_ascii_pseudo_op): Check for .ascii.
- (libffi_cv_as_string_pseudo_op): Check for .string.
- * configure: Regenerate.
- * fficonfig.h.in: Regenerate.
- * src/x86/sysv.S (.eh_frame): Use .ascii, .string or error.
-
-2010-05-11 Dan Witte <dwitte@mozilla.com>
-
- * doc/libffi.tex: Document previous change.
-
-2010-05-11 Makoto Kato <m_kato@ga2.so-net.ne.jp>
-
- * src/x86/ffi.c (ffi_call): Don't copy structs passed by value.
-
-2010-05-05 Michael Kohler <michaelkohler@live.com>
-
- * src/dlmalloc.c (dlfree): Fix spelling.
- * src/ia64/ffi.c (ffi_prep_cif_machdep): Ditto.
- * configure.ac: Ditto.
- * configure: Rebuilt.
-
-2010-04-13 Dan Witte <dwitte@mozilla.com>
-
- * msvcc.sh: Build with -W3 instead of -Wall.
- * src/powerpc/ffi_darwin.c: Remove build warnings.
- * src/x86/ffi.c: Ditto.
- * src/x86/ffitarget.h: Ditto.
-
-2010-04-12 Dan Witte <dwitte@mozilla.com>
- Walter Meinl <wuno@lsvw.de>
-
- * configure.ac: Add OS/2 support.
- * configure: Rebuilt.
- * src/closures.c: Ditto.
- * src/dlmalloc.c: Ditto.
- * src/x86/win32.S: Ditto.
-
-2010-04-07 Jakub Jelinek <jakub@redhat.com>
-
- * testsuite/libffi.call/err_bad_abi.c: Remove unused args variable.
-
-2010-04-02 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
-
- * Makefile.in: Regenerate.
- * aclocal.m4: Regenerate.
- * include/Makefile.in: Regenerate.
- * man/Makefile.in: Regenerate.
- * testsuite/Makefile.in: Regenerate.
-
-2010-03-30 Dan Witte <dwitte@mozilla.com>
-
- * msvcc.sh: Disable build warnings.
- * README (tested): Clarify windows build procedure.
-
-2010-03-15 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * configure.ac (libffi_cv_as_x86_64_unwind_section_type): New test.
- * configure: Regenerate.
- * fficonfig.h.in: Regenerate.
- * libffi/src/x86/unix64.S (.eh_frame)
- [HAVE_AS_X86_64_UNWIND_SECTION_TYPE]: Use @unwind section type.
-
-2010-03-14 Matthias Klose <doko@ubuntu.com>
-
- * src/x86/ffi64.c: Fix typo in comment.
- * src/x86/ffi.c: Use /* ... */ comment style.
-
-2010-02-24 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * doc/libffi.texi (The Closure API): Fix typo.
- * doc/libffi.info: Remove.
-
-2010-02-15 Matthias Klose <doko@ubuntu.com>
-
- * src/arm/sysv.S (__ARM_ARCH__): Define for processor
- __ARM_ARCH_7EM__.
-
-2010-01-15 Anthony Green <green@redhat.com>
-
- * README: Add notes on building with Microsoft Visual C++.
-
-2010-01-15 Daniel Witte <dwitte@mozilla.com>
-
- * msvcc.sh: New file.
-
- * src/x86/win32.S: Port assembly routines to MSVC and #ifdef.
- * src/x86/ffi.c: Tweak function declaration and remove excess
- parens.
- * include/ffi.h.in: Add __declspec(align(8)) to typedef struct
- ffi_closure.
-
- * src/x86/ffi.c: Merge ffi_call_SYSV and ffi_call_STDCALL into new
- function ffi_call_win32 on X86_WIN32.
- * src/x86/win32.S (ffi_call_SYSV): Rename to ffi_call_win32.
- (ffi_call_STDCALL): Remove.
-
- * src/prep_cif.c (ffi_prep_cif): Move stack space allocation code
- to ffi_prep_cif_machdep for x86.
- * src/x86/ffi.c (ffi_prep_cif_machdep): To here.
-
-2010-01-15 Oliver Kiddle <okiddle@yahoo.co.uk>
-
- * src/x86/ffitarget.h (ffi_abi): Check for __i386 and __amd64 for
- Sun Studio compiler compatibility.
-
-2010-01-12 Conrad Irwin <conrad.irwin@gmail.com>
-
- * doc/libffi.texi: Add closure example.
-
-2010-01-07 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- PR libffi/40701
- * testsuite/libffi.call/ffitest.h [__alpha__ && __osf__] (PRIdLL,
- PRIuLL, PRId64, PRIu64, PRIuPTR): Define.
- * testsuite/libffi.call/cls_align_sint64.c: Add -Wno-format on
- alpha*-dec-osf*.
- * testsuite/libffi.call/cls_align_uint64.c: Likewise.
- * testsuite/libffi.call/cls_ulonglong.c: Likewise.
- * testsuite/libffi.call/return_ll1.c: Likewise.
- * testsuite/libffi.call/stret_medium2.c: Likewise.
- * testsuite/libffi.special/ffitestcxx.h (allocate_mmap): Cast
- MAP_FAILED to char *.
-
-2010-01-06 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- * src/mips/n32.S: Use .abicalls and .eh_frame with __GNUC__.
-
-2009-12-31 Anthony Green <green@redhat.com>
-
- * README: Update for libffi 3.0.9.
-
-2009-12-27 Matthias Klose <doko@ubuntu.com>
-
- * configure.ac (HAVE_LONG_DOUBLE): Define for mips when
- appropriate.
- * configure: Rebuilt.
-
-2009-12-26 Anthony Green <green@redhat.com>
-
- * testsuite/libffi.call/cls_longdouble_va.c: Mark as xfail for
- avr32*-*-*.
- * testsuite/libffi.call/cls_double_va.c: Ditto.
-
-2009-12-26 Andreas Tobler <a.tobler@schweiz.org>
-
- * testsuite/libffi.call/ffitest.h: Conditionally include stdint.h
- and inttypes.h.
- * testsuite/libffi.special/unwindtest.cc: Ditto.
-
-2009-12-26 Andreas Tobler <a.tobler@schweiz.org>
-
- * configure.ac: Add amd64-*-openbsd*.
- * configure: Rebuilt.
- * testsuite/lib/libffi-dg.exp (libffi_target_compile): Link
- openbsd programs with -lpthread.
-
-2009-12-26 Anthony Green <green@redhat.com>
-
- * testsuite/libffi.call/cls_double_va.c,
- testsuite/libffi.call/cls_longdouble.c,
- testsuite/libffi.call/cls_longdouble_va.c,
- testsuite/libffi.call/cls_pointer.c,
- testsuite/libffi.call/cls_pointer_stack.c: Remove xfail for
- mips*-*-* and arm*-*-*.
- * testsuite/libffi.call/cls_align_longdouble_split.c,
- testsuite/libffi.call/cls_align_longdouble_split2.c,
- testsuite/libffi.call/stret_medium2.c,
- testsuite/libffi.call/stret_medium.c,
- testsuite/libffi.call/stret_large.c,
- testsuite/libffi.call/stret_large2.c: Remove xfail for arm*-*-*.
-
-2009-12-31 Kay Tietz <ktietz70@googlemail.com>
-
- * testsuite/libffi.call/ffitest.h,
- testsuite/libffi.special/ffitestcxx.h (PRIdLL, PRuLL): Fix
- definitions.
-
-2009-12-31 Carlo Bramini <carlo.bramix@libero.it>
-
- * configure.ac (AM_LTLDFLAGS): Define for windows hosts.
- * Makefile.am (libffi_la_LDFLAGS): Add AM_LTLDFLAGS.
- * configure: Rebuilt.
- * Makefile.in: Rebuilt.
-
-2009-12-31 Anthony Green <green@redhat.com>
- Blake Chaffin.
-
- * testsuite/libffi.call/huge_struct.c: New test case from Blake
- Chaffin @ Apple.
-
-2009-12-28 David Edelsohn <edelsohn@gnu.org>
-
- * src/powerpc/ffi_darwin.c (ffi_prep_args): Copy abi and nargs to
- local variables.
- (aix_adjust_aggregate_sizes): New function.
- (ffi_prep_cif_machdep): Call it.
-
-2009-12-26 Andreas Tobler <a.tobler@schweiz.org>
-
- * configure.ac: Define FFI_MMAP_EXEC_WRIT for the given targets.
- * configure: Regenerate.
- * fficonfig.h.in: Likewise.
- * src/closures.c: Remove the FFI_MMAP_EXEC_WRIT definition for
- Solaris/x86.
-
-2009-12-26 Andreas Schwab <schwab@linux-m68k.org>
-
- * src/powerpc/ffi.c (ffi_prep_args_SYSV): Advance intarg_count
- when a float arguments is passed in memory.
- (ffi_closure_helper_SYSV): Mark general registers as used up when
- a 64bit or soft-float long double argument is passed in memory.
-
-2009-12-25 Matthias Klose <doko@ubuntu.com>
-
- * man/ffi_call.3: Fix #include in examples.
- * doc/libffi.texi: Add dircategory.
-
-2009-12-25 Frank Everdij <f.p.x.everdij@tudelft.nl>
-
- * include/ffi.h.in: Placed '__GNUC__' ifdef around
- '__attribute__((aligned(8)))' in ffi_closure, fixes compile for
- IRIX MIPSPro c99.
- * include/ffi_common.h: Added '__sgi' define to non
- '__attribute__((__mode__()))' integer typedefs.
- * src/mips/ffi.c (ffi_call, ffi_closure_mips_inner_O32,
- ffi_closure_mips_inner_N32): Added 'defined(_MIPSEB)' to BE check.
- (ffi_closure_mips_inner_O32, ffi_closure_mips_inner_N32): Added
- FFI_LONGDOUBLE support and alignment(N32 only).
- * src/mips/ffitarget.h: Corrected '#include <sgidefs.h>' for IRIX and
- fixed non '__attribute__((__mode__()))' integer typedefs.
- * src/mips/n32.S: Put '#ifdef linux' around '.abicalls' and '.eh_frame'
- since they are Linux/GNU Assembler specific.
-
-2009-12-25 Bradley Smith <brad@brad-smith.co.uk>
-
- * configure.ac, Makefile.am, src/avr32/ffi.c,
- src/avr32/ffitarget.h,
- src/avr32/sysv.S: Add AVR32 port.
- * configure, Makefile.in: Rebuilt.
-
-2009-12-21 Andreas Tobler <a.tobler@schweiz.org>
-
- * configure.ac: Make i?86 build on FreeBSD and OpenBSD.
- * configure: Regenerate.
-
-2009-12-15 John David Anglin <dave.anglin@nrc-cnrc.gc.ca>
-
- * testsuite/libffi.call/ffitest.h: Define PRIuPTR on PA HP-UX.
-
-2009-12-13 John David Anglin <dave.anglin@nrc-cnrc.gc.ca>
-
- * src/pa/ffi.c (ffi_closure_inner_pa32): Handle FFI_TYPE_LONGDOUBLE
- type on HP-UX.
-
-2012-02-13 Kai Tietz <ktietz@redhat.com>
-
- PR libffi/52221
- * src/x86/ffi.c (ffi_prep_raw_closure_loc): Add thiscall
- support for X86_WIN32.
- (FFI_INIT_TRAMPOLINE_THISCALL): Fix displacement.
-
-2009-12-11 Eric Botcazou <ebotcazou@adacore.com>
-
- * src/sparc/ffi.c (ffi_closure_sparc_inner_v9): Properly align 'long
- double' arguments.
-
-2009-12-11 Eric Botcazou <ebotcazou@adacore.com>
-
- * testsuite/libffi.call/ffitest.h: Define PRIuPTR on Solaris < 10.
-
-2009-12-10 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
-
- PR libffi/40700
- * src/closures.c [X86_64 && __sun__ && __svr4__]
- (FFI_MMAP_EXEC_WRIT): Define.
-
-2009-12-08 David Daney <ddaney@caviumnetworks.com>
-
- * testsuite/libffi.call/stret_medium.c: Remove xfail for mips*-*-*
- * testsuite/libffi.call/cls_align_longdouble_split2.c: Same.
- * testsuite/libffi.call/stret_large.c: Same.
- * testsuite/libffi.call/cls_align_longdouble_split.c: Same.
- * testsuite/libffi.call/stret_large2.c: Same.
- * testsuite/libffi.call/stret_medium2.c: Same.
-
-2009-12-07 David Edelsohn <edelsohn@gnu.org>
-
- * src/powerpc/aix_closure.S (libffi_closure_ASM): Fix tablejump
- typo.
-
-2009-12-05 David Edelsohn <edelsohn@gnu.org>
-
- * src/powerpc/aix.S: Update AIX32 code to be consistent with AIX64
- code.
- * src/powerpc/aix_closure.S: Same.
-
-2009-12-05 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
-
- * Makefile.in: Regenerate.
- * configure: Regenerate.
- * include/Makefile.in: Regenerate.
- * man/Makefile.in: Regenerate.
- * testsuite/Makefile.in: Regenerate.
-
-2009-12-04 David Edelsohn <edelsohn@gnu.org>
-
- * src/powerpc/aix_closure.S: Reorganize 64-bit code to match
- linux64_closure.S.
-
-2009-12-04 Uros Bizjak <ubizjak@gmail.com>
-
- PR libffi/41908
- * src/x86/ffi64.c (classify_argument): Update from
- gcc/config/i386/i386.c.
- (ffi_closure_unix64_inner): Do not use the address of two consecutive
- SSE registers directly.
- * testsuite/libffi.call/cls_dbls_struct.c (main): Remove xfail
- for x86_64 linux targets.
-
-2009-12-04 David Edelsohn <edelsohn@gnu.org>
-
- * src/powerpc/ffi_darwin.c (ffi_closure_helper_DARWIN): Increment
- pfr for long double split between fpr13 and stack.
-
-2009-12-03 David Edelsohn <edelsohn@gnu.org>
-
- * src/powerpc/ffi_darwin.c (ffi_prep_args): Increment next_arg and
- fparg_count twice for long double.
-
-2009-12-03 David Edelsohn <edelsohn@gnu.org>
-
- PR libffi/42243
- * src/powerpc/ffi_darwin.c (ffi_prep_args): Remove extra parentheses.
-
-2009-12-03 Uros Bizjak <ubizjak@gmail.com>
-
- * testsuite/libffi.call/cls_longdouble_va.c (main): Fix format string.
- Remove xfails for x86 linux targets.
-
-2009-12-02 David Edelsohn <edelsohn@gnu.org>
-
- * src/powerpc/ffi_darwin.c (ffi_prep_args): Fix typo in INT64
- case.
-
-2009-12-01 David Edelsohn <edelsohn@gnu.org>
-
- * src/powerpc/aix.S (ffi_call_AIX): Convert to more standard
- register usage. Call ffi_prep_args directly. Add long double
- return value support.
- * src/powerpc/ffi_darwin.c (ffi_prep_args): Double arg increment
- applies to FFI_TYPE_DOUBLE. Correct fpr_base increment typo.
- Separate FFI_TYPE_SINT32 and FFI_TYPE_UINT32 cases.
- (ffi_prep_cif_machdep): Only 16 byte stack alignment in 64 bit
- mode.
- (ffi_closure_helper_DARWIN): Remove nf and ng counters. Move temp
- into case.
- * src/powerpc/aix_closure.S: Maintain 16 byte stack alignment.
- Allocate result area between params and FPRs.
-
-2009-11-30 David Edelsohn <edelsohn@gnu.org>
-
- PR target/35484
- * src/powerpc/ffitarget.h (POWERPC64): Define for PPC64 Linux and
- AIX64.
- * src/powerpc/aix.S: Implement AIX64 version.
- * src/powerpc/aix_closure.S: Implement AIX64 version.
- (ffi_closure_ASM): Use extsb, lha and displament addresses.
- * src/powerpc/ffi_darwin.c (ffi_prep_args): Implement AIX64
- support.
- (ffi_prep_cif_machdep): Same.
- (ffi_call): Same.
- (ffi_closure_helper_DARWIN): Same.
-
-2009-11-02 Andreas Tobler <a.tobler@schweiz.org>
-
- PR libffi/41908
- * testsuite/libffi.call/testclosure.c: New test.
-
-2009-09-28 Kai Tietz <kai.tietz@onevision.com>
-
- * src/x86/win64.S (_ffi_call_win64 stack): Remove for gnu
- assembly version use of ___chkstk.
-
-2009-09-23 Matthias Klose <doko@ubuntu.com>
-
- PR libffi/40242, PR libffi/41443
- * src/arm/sysv.S (__ARM_ARCH__): Define for processors
- __ARM_ARCH_6T2__, __ARM_ARCH_6M__, __ARM_ARCH_7__,
- __ARM_ARCH_7A__, __ARM_ARCH_7R__, __ARM_ARCH_7M__.
- Change the conditionals to __SOFTFP__ || __ARM_EABI__
- for -mfloat-abi=softfp to work.
-
-2009-09-17 Loren J. Rittle <ljrittle@acm.org>
-
- PR testsuite/32843 (strikes again)
- * src/x86/ffi.c (ffi_prep_cif_machdep): Add X86_FREEBSD to
- enable proper extension on char and short.
-
-2009-09-15 David Daney <ddaney@caviumnetworks.com>
-
- * src/java_raw_api.c (ffi_java_raw_to_rvalue): Remove special
- handling for FFI_TYPE_POINTER.
- * src/mips/ffitarget.h (FFI_TYPE_STRUCT_D_SOFT,
- FFI_TYPE_STRUCT_F_SOFT, FFI_TYPE_STRUCT_DD_SOFT,
- FFI_TYPE_STRUCT_FF_SOFT, FFI_TYPE_STRUCT_FD_SOFT,
- FFI_TYPE_STRUCT_DF_SOFT, FFI_TYPE_STRUCT_SOFT): New defines.
- (FFI_N32_SOFT_FLOAT, FFI_N64_SOFT_FLOAT): New ffi_abi enumerations.
- (enum ffi_abi): Set FFI_DEFAULT_ABI for soft-float.
- * src/mips/n32.S (ffi_call_N32): Add handling for soft-float
- structure and pointer returns.
- (ffi_closure_N32): Add handling for pointer returns.
- * src/mips/ffi.c (ffi_prep_args, calc_n32_struct_flags,
- calc_n32_return_struct_flags): Handle soft-float.
- (ffi_prep_cif_machdep): Handle soft-float, fix pointer handling.
- (ffi_call_N32): Declare proper argument types.
- (ffi_call, copy_struct_N32, ffi_closure_mips_inner_N32): Handle
- soft-float.
-
-2009-08-24 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
-
- * configure.ac (AC_PREREQ): Bump to 2.64.
-
-2009-08-22 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
-
- * Makefile.am (install-html, install-pdf): Remove.
- * Makefile.in: Regenerate.
-
- * Makefile.in: Regenerate.
- * aclocal.m4: Regenerate.
- * configure: Regenerate.
- * fficonfig.h.in: Regenerate.
- * include/Makefile.in: Regenerate.
- * man/Makefile.in: Regenerate.
- * testsuite/Makefile.in: Regenerate.
-
-2011-08-22 Jasper Lievisse Adriaanse <jasper@openbsd.org>
-
- * configure.ac: Add OpenBSD/hppa and OpenBSD/powerpc support.
- * configure: Rebuilt.
-
-2009-07-30 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
-
- * configure.ac (_AC_ARG_VAR_PRECIOUS): Use m4_rename_force.
-
-2009-07-24 Dave Korn <dave.korn.cygwin@gmail.com>
-
- PR libffi/40807
- * src/x86/ffi.c (ffi_prep_cif_machdep): Also use sign/zero-extending
- return types for X86_WIN32.
- * src/x86/win32.S (_ffi_call_SYSV): Handle omitted return types.
- (_ffi_call_STDCALL, _ffi_closure_SYSV, _ffi_closure_raw_SYSV,
- _ffi_closure_STDCALL): Likewise.
-
- * src/closures.c (is_selinux_enabled): Define to const 0 for Cygwin.
- (dlmmap, dlmunmap): Also use these functions on Cygwin.
-
-2009-07-11 Richard Sandiford <rdsandiford@googlemail.com>
-
- PR testsuite/40699
- PR testsuite/40707
- PR testsuite/40709
- * testsuite/lib/libffi-dg.exp: Revert 2009-07-02, 2009-07-01 and
- 2009-06-30 commits.
-
-2009-07-01 Richard Sandiford <r.sandiford@uk.ibm.com>
-
- * testsuite/lib/libffi-dg.exp (libffi-init): Set ld_library_path
- to "" before adding paths. (This reinstates an assignment that
- was removed by my 2009-06-30 commit, but changes the initial
- value from "." to "".)
-
-2009-07-01 H.J. Lu <hongjiu.lu@intel.com>
-
- PR testsuite/40601
- * testsuite/lib/libffi-dg.exp (libffi-init): Properly set
- gccdir. Adjust ld_library_path for gcc only if gccdir isn't
- empty.
-
-2009-06-30 Richard Sandiford <r.sandiford@uk.ibm.com>
-
- * testsuite/lib/libffi-dg.exp (libffi-init): Don't add "."
- to ld_library_path. Use add_path. Add just find_libgcc_s
- to ld_library_path, not every libgcc multilib directory.
-
-2009-06-16 Wim Lewis <wiml@hhhh.org>
-
- * src/powerpc/ffi.c: Avoid clobbering cr3 and cr4, which are
- supposed to be callee-saved.
- * src/powerpc/sysv.S (small_struct_return_value): Fix overrun of
- return buffer for odd-size structs.
-
-2009-06-16 Andreas Tobler <a.tobler@schweiz.org>
-
- PR libffi/40444
- * testsuite/lib/libffi-dg.exp (libffi_target_compile): Add
- allow_stack_execute for Darwin.
-
-2009-06-16 Andrew Haley <aph@redhat.com>
-
- * configure.ac (TARGETDIR): Add missing blank lines.
- * configure: Regenerate.
-
-2009-06-16 Andrew Haley <aph@redhat.com>
-
- * testsuite/libffi.call/cls_align_sint64.c,
- testsuite/libffi.call/cls_align_uint64.c,
- testsuite/libffi.call/cls_longdouble_va.c,
- testsuite/libffi.call/cls_ulonglong.c,
- testsuite/libffi.call/return_ll1.c,
- testsuite/libffi.call/stret_medium2.c: Fix printf format
- specifiers.
- * testsuite/libffi.call/ffitest.h,
- testsuite/libffi.special/ffitestcxx.h (PRIdLL, PRIuLL): Define.
-
-2009-06-15 Andrew Haley <aph@redhat.com>
-
- * testsuite/libffi.call/err_bad_typedef.c: xfail everywhere.
- * testsuite/libffi.call/err_bad_abi.c: Likewise.
-
-2009-06-12 Andrew Haley <aph@redhat.com>
-
- * Makefile.am: Remove info_TEXINFOS.
-
-2009-06-12 Andrew Haley <aph@redhat.com>
-
- * ChangeLog.libffi: testsuite/libffi.call/cls_align_sint64.c,
- testsuite/libffi.call/cls_align_uint64.c,
- testsuite/libffi.call/cls_ulonglong.c,
- testsuite/libffi.call/return_ll1.c,
- testsuite/libffi.call/stret_medium2.c: Fix printf format
- specifiers.
- testsuite/libffi.special/unwindtest.cc: include stdint.h.
-
-2009-06-11 Timothy Wall <twall@users.sf.net>
-
- * Makefile.am,
- configure.ac,
- include/ffi.h.in,
- include/ffi_common.h,
- src/closures.c,
- src/dlmalloc.c,
- src/x86/ffi.c,
- src/x86/ffitarget.h,
- src/x86/win64.S (new),
- README: Added win64 support (mingw or MSVC)
- * Makefile.in,
- include/Makefile.in,
- man/Makefile.in,
- testsuite/Makefile.in,
- configure,
- aclocal.m4: Regenerated
- * ltcf-c.sh: properly escape cygwin/w32 path
- * man/ffi_call.3: Clarify size requirements for return value.
- * src/x86/ffi64.c: Fix filename in comment.
- * src/x86/win32.S: Remove unused extern.
-
- * testsuite/libffi.call/closure_fn0.c,
- testsuite/libffi.call/closure_fn1.c,
- testsuite/libffi.call/closure_fn2.c,
- testsuite/libffi.call/closure_fn3.c,
- testsuite/libffi.call/closure_fn4.c,
- testsuite/libffi.call/closure_fn5.c,
- testsuite/libffi.call/closure_fn6.c,
- testsuite/libffi.call/closure_stdcall.c,
- testsuite/libffi.call/cls_12byte.c,
- testsuite/libffi.call/cls_16byte.c,
- testsuite/libffi.call/cls_18byte.c,
- testsuite/libffi.call/cls_19byte.c,
- testsuite/libffi.call/cls_1_1byte.c,
- testsuite/libffi.call/cls_20byte.c,
- testsuite/libffi.call/cls_20byte1.c,
- testsuite/libffi.call/cls_24byte.c,
- testsuite/libffi.call/cls_2byte.c,
- testsuite/libffi.call/cls_3_1byte.c,
- testsuite/libffi.call/cls_3byte1.c,
- testsuite/libffi.call/cls_3byte2.c,
- testsuite/libffi.call/cls_4_1byte.c,
- testsuite/libffi.call/cls_4byte.c,
- testsuite/libffi.call/cls_5_1_byte.c,
- testsuite/libffi.call/cls_5byte.c,
- testsuite/libffi.call/cls_64byte.c,
- testsuite/libffi.call/cls_6_1_byte.c,
- testsuite/libffi.call/cls_6byte.c,
- testsuite/libffi.call/cls_7_1_byte.c,
- testsuite/libffi.call/cls_7byte.c,
- testsuite/libffi.call/cls_8byte.c,
- testsuite/libffi.call/cls_9byte1.c,
- testsuite/libffi.call/cls_9byte2.c,
- testsuite/libffi.call/cls_align_double.c,
- testsuite/libffi.call/cls_align_float.c,
- testsuite/libffi.call/cls_align_longdouble.c,
- testsuite/libffi.call/cls_align_longdouble_split.c,
- testsuite/libffi.call/cls_align_longdouble_split2.c,
- testsuite/libffi.call/cls_align_pointer.c,
- testsuite/libffi.call/cls_align_sint16.c,
- testsuite/libffi.call/cls_align_sint32.c,
- testsuite/libffi.call/cls_align_sint64.c,
- testsuite/libffi.call/cls_align_uint16.c,
- testsuite/libffi.call/cls_align_uint32.c,
- testsuite/libffi.call/cls_align_uint64.c,
- testsuite/libffi.call/cls_dbls_struct.c,
- testsuite/libffi.call/cls_double.c,
- testsuite/libffi.call/cls_double_va.c,
- testsuite/libffi.call/cls_float.c,
- testsuite/libffi.call/cls_longdouble.c,
- testsuite/libffi.call/cls_longdouble_va.c,
- testsuite/libffi.call/cls_multi_schar.c,
- testsuite/libffi.call/cls_multi_sshort.c,
- testsuite/libffi.call/cls_multi_sshortchar.c,
- testsuite/libffi.call/cls_multi_uchar.c,
- testsuite/libffi.call/cls_multi_ushort.c,
- testsuite/libffi.call/cls_multi_ushortchar.c,
- testsuite/libffi.call/cls_pointer.c,
- testsuite/libffi.call/cls_pointer_stack.c,
- testsuite/libffi.call/cls_schar.c,
- testsuite/libffi.call/cls_sint.c,
- testsuite/libffi.call/cls_sshort.c,
- testsuite/libffi.call/cls_uchar.c,
- testsuite/libffi.call/cls_uint.c,
- testsuite/libffi.call/cls_ulonglong.c,
- testsuite/libffi.call/cls_ushort.c,
- testsuite/libffi.call/err_bad_abi.c,
- testsuite/libffi.call/err_bad_typedef.c,
- testsuite/libffi.call/float2.c,
- testsuite/libffi.call/huge_struct.c,
- testsuite/libffi.call/nested_struct.c,
- testsuite/libffi.call/nested_struct1.c,
- testsuite/libffi.call/nested_struct10.c,
- testsuite/libffi.call/nested_struct2.c,
- testsuite/libffi.call/nested_struct3.c,
- testsuite/libffi.call/nested_struct4.c,
- testsuite/libffi.call/nested_struct5.c,
- testsuite/libffi.call/nested_struct6.c,
- testsuite/libffi.call/nested_struct7.c,
- testsuite/libffi.call/nested_struct8.c,
- testsuite/libffi.call/nested_struct9.c,
- testsuite/libffi.call/problem1.c,
- testsuite/libffi.call/return_ldl.c,
- testsuite/libffi.call/return_ll1.c,
- testsuite/libffi.call/stret_large.c,
- testsuite/libffi.call/stret_large2.c,
- testsuite/libffi.call/stret_medium.c,
- testsuite/libffi.call/stret_medium2.c,
- testsuite/libffi.special/unwindtest.cc: use ffi_closure_alloc instead
- of checking for MMAP. Use intptr_t instead of long casts.
-
-2009-06-11 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * testsuite/libffi.call/cls_longdouble_va.c: Add xfail sh*-*-linux-*.
- * testsuite/libffi.call/err_bad_abi.c: Add xfail sh*-*-*.
- * testsuite/libffi.call/err_bad_typedef.c: Likewise.
-
-2009-06-09 Andrew Haley <aph@redhat.com>
-
- * src/x86/freebsd.S: Add missing file.
-
-2009-06-08 Andrew Haley <aph@redhat.com>
-
- Import from libffi 3.0.8:
-
- * doc/libffi.texi: New file.
- * doc/libffi.info: Likewise.
- * doc/stamp-vti: Likewise.
- * man/Makefile.am: New file.
- * man/ffi_call.3: New file.
-
- * Makefile.am (EXTRA_DIST): Add src/x86/darwin64.S,
- src/dlmalloc.c.
- (nodist_libffi_la_SOURCES): Add X86_FREEBSD.
-
- * configure.ac: Bump version to 3.0.8.
- parisc*-*-linux*: Add.
- i386-*-freebsd* | i386-*-openbsd*: Add.
- powerpc-*-beos*: Add.
- AM_CONDITIONAL X86_FREEBSD: Add.
- AC_CONFIG_FILES: Add man/Makefile.
-
- * include/ffi.h.in (FFI_FN): Change void (*)() to void (*)(void).
-
-2009-06-08 Andrew Haley <aph@redhat.com>
-
- * README: Import from libffi 3.0.8.
-
-2009-06-08 Andrew Haley <aph@redhat.com>
-
- * testsuite/libffi.call/err_bad_abi.c: Add xfails.
- * testsuite/libffi.call/cls_longdouble_va.c: Add xfails.
- * testsuite/libffi.call/cls_dbls_struct.c: Add xfail x86_64-*-linux-*.
- * testsuite/libffi.call/err_bad_typedef.c: Add xfails.
-
- * testsuite/libffi.call/stret_medium2.c: Add __UNUSED__ to args.
- * testsuite/libffi.call/stret_medium.c: Likewise.
- * testsuite/libffi.call/stret_large2.c: Likewise.
- * testsuite/libffi.call/stret_large.c: Likewise.
-
-2008-12-26 Timothy Wall <twall@users.sf.net>
-
- * testsuite/libffi.call/cls_longdouble.c,
- testsuite/libffi.call/cls_longdouble_va.c,
- testsuite/libffi.call/cls_align_longdouble.c,
- testsuite/libffi.call/cls_align_longdouble_split.c,
- testsuite/libffi.call/cls_align_longdouble_split2.c: mark expected
- failures on x86_64 cygwin/mingw.
-
-2008-12-22 Timothy Wall <twall@users.sf.net>
-
- * testsuite/libffi.call/closure_fn0.c,
- testsuite/libffi.call/closure_fn1.c,
- testsuite/libffi.call/closure_fn2.c,
- testsuite/libffi.call/closure_fn3.c,
- testsuite/libffi.call/closure_fn4.c,
- testsuite/libffi.call/closure_fn5.c,
- testsuite/libffi.call/closure_fn6.c,
- testsuite/libffi.call/closure_loc_fn0.c,
- testsuite/libffi.call/closure_stdcall.c,
- testsuite/libffi.call/cls_align_pointer.c,
- testsuite/libffi.call/cls_pointer.c,
- testsuite/libffi.call/cls_pointer_stack.c: use portable cast from
- pointer to integer (intptr_t).
- * testsuite/libffi.call/cls_longdouble.c: disable for win64.
-
-2008-07-24 Anthony Green <green@redhat.com>
-
- * testsuite/libffi.call/cls_dbls_struct.c,
- testsuite/libffi.call/cls_double_va.c,
- testsuite/libffi.call/cls_longdouble.c,
- testsuite/libffi.call/cls_longdouble_va.c,
- testsuite/libffi.call/cls_pointer.c,
- testsuite/libffi.call/cls_pointer_stack.c,
- testsuite/libffi.call/err_bad_abi.c: Clean up failures from
- compiler warnings.
-
-2008-03-04 Anthony Green <green@redhat.com>
- Blake Chaffin
- hos@tamanegi.org
-
- * testsuite/libffi.call/cls_align_longdouble_split2.c
- testsuite/libffi.call/cls_align_longdouble_split.c
- testsuite/libffi.call/cls_dbls_struct.c
- testsuite/libffi.call/cls_double_va.c
- testsuite/libffi.call/cls_longdouble.c
- testsuite/libffi.call/cls_longdouble_va.c
- testsuite/libffi.call/cls_pointer.c
- testsuite/libffi.call/cls_pointer_stack.c
- testsuite/libffi.call/err_bad_abi.c
- testsuite/libffi.call/err_bad_typedef.c
- testsuite/libffi.call/stret_large2.c
- testsuite/libffi.call/stret_large.c
- testsuite/libffi.call/stret_medium2.c
- testsuite/libffi.call/stret_medium.c: New tests from Apple.
-
-2009-06-05 Andrew Haley <aph@redhat.com>
-
- * src/x86/ffitarget.h, src/x86/ffi.c: Merge stdcall changes from
- libffi.
-
-2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/x86/ffitarget.h, src/x86/win32.S, src/x86/ffi.c: Back out
- stdcall changes.
-
-2008-02-26 Anthony Green <green@redhat.com>
- Thomas Heller <theller@ctypes.org>
-
- * src/x86/ffi.c (ffi_closure_SYSV_inner): Change C++ comment to C
- comment.
-
-2008-02-03 Timothy Wall <twall@users.sf.net>
-
- * src/x86/ffi.c (FFI_INIT_TRAMPOLINE_STDCALL): Calculate jump return
- offset based on code pointer, not data pointer.
-
-2008-01-31 Timothy Wall <twall@users.sf.net>
-
- * testsuite/libffi.call/closure_stdcall.c: Add test for stdcall
- closures.
- * src/x86/ffitarget.h: Increase size of trampoline for stdcall
- closures.
- * src/x86/win32.S: Add assembly for stdcall closure.
- * src/x86/ffi.c: Initialize stdcall closure trampoline.
-
-2009-06-04 Andrew Haley <aph@redhat.com>
-
- * include/ffi.h.in: Change void (*)() to void (*)(void).
- * src/x86/ffi.c: Likewise.
-
-2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/powerpc/ppc_closure.S: Insert licence header.
- * src/powerpc/linux64_closure.S: Likewise.
- * src/m68k/sysv.S: Likewise.
-
- * src/sh64/ffi.c: Change void (*)() to void (*)(void).
- * src/powerpc/ffi.c: Likewise.
- * src/powerpc/ffi_darwin.c: Likewise.
- * src/m32r/ffi.c: Likewise.
- * src/sh64/ffi.c: Likewise.
- * src/x86/ffi64.c: Likewise.
- * src/alpha/ffi.c: Likewise.
- * src/alpha/osf.S: Likewise.
- * src/frv/ffi.c: Likewise.
- * src/s390/ffi.c: Likewise.
- * src/pa/ffi.c: Likewise.
- * src/pa/hpux32.S: Likewise.
- * src/ia64/unix.S: Likewise.
- * src/ia64/ffi.c: Likewise.
- * src/sparc/ffi.c: Likewise.
- * src/mips/ffi.c: Likewise.
- * src/sh/ffi.c: Likewise.
-
-2008-02-15 David Daney <ddaney@avtrex.com>
-
- * src/mips/ffi.c (USE__BUILTIN___CLEAR_CACHE):
- Define (conditionally), and use it to include cachectl.h.
- (ffi_prep_closure_loc): Fix cache flushing.
- * src/mips/ffitarget.h (_ABIN32, _ABI64, _ABIO32): Define.
-
-2009-06-04 Andrew Haley <aph@redhat.com>
-
- include/ffi.h.in,
- src/arm/ffitarget.h,
- src/arm/ffi.c,
- src/arm/sysv.S,
- src/powerpc/ffitarget.h,
- src/closures.c,
- src/sh64/ffitarget.h,
- src/sh64/ffi.c,
- src/sh64/sysv.S,
- src/types.c,
- src/x86/ffi64.c,
- src/x86/ffitarget.h,
- src/x86/win32.S,
- src/x86/darwin.S,
- src/x86/ffi.c,
- src/x86/sysv.S,
- src/x86/unix64.S,
- src/alpha/ffitarget.h,
- src/alpha/ffi.c,
- src/alpha/osf.S,
- src/m68k/ffitarget.h,
- src/frv/ffitarget.h,
- src/frv/ffi.c,
- src/s390/ffitarget.h,
- src/s390/sysv.S,
- src/cris/ffitarget.h,
- src/pa/linux.S,
- src/pa/ffitarget.h,
- src/pa/ffi.c,
- src/raw_api.c,
- src/ia64/ffitarget.h,
- src/ia64/unix.S,
- src/ia64/ffi.c,
- src/ia64/ia64_flags.h,
- src/java_raw_api.c,
- src/debug.c,
- src/sparc/v9.S,
- src/sparc/ffitarget.h,
- src/sparc/ffi.c,
- src/sparc/v8.S,
- src/mips/ffitarget.h,
- src/mips/n32.S,
- src/mips/o32.S,
- src/mips/ffi.c,
- src/prep_cif.c,
- src/sh/ffitarget.h,
- src/sh/ffi.c,
- src/sh/sysv.S: Update license text.
-
-2009-05-22 Dave Korn <dave.korn.cygwin@gmail.com>
-
- * src/x86/win32.S (_ffi_closure_STDCALL): New function.
- (.eh_frame): Add FDE for it.
-
-2009-05-22 Dave Korn <dave.korn.cygwin@gmail.com>
-
- * configure.ac: Also check if assembler supports pc-relative
- relocs on X86_WIN32 targets.
- * configure: Regenerate.
- * src/x86/win32.S (ffi_prep_args): Declare extern, not global.
- (_ffi_call_SYSV): Add missing function type symbol .def and
- add EH markup labels.
- (_ffi_call_STDCALL): Likewise.
- (_ffi_closure_SYSV): Likewise.
- (_ffi_closure_raw_SYSV): Likewise.
- (.eh_frame): Add hand-crafted EH data.
-
-2009-04-09 Jakub Jelinek <jakub@redhat.com>
-
- * testsuite/lib/libffi-dg.exp: Change copyright header to refer to
- version 3 of the GNU General Public License and to point readers
- at the COPYING3 file and the FSF's license web page.
- * testsuite/libffi.call/call.exp: Likewise.
- * testsuite/libffi.special/special.exp: Likewise.
-
-2009-03-01 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
-
- * configure: Regenerate.
-
-2008-12-18 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- PR libffi/26048
- * configure.ac (HAVE_AS_X86_PCREL): New test.
- * configure: Regenerate.
- * fficonfig.h.in: Regenerate.
- * src/x86/sysv.S [!FFI_NO_RAW_API]: Precalculate
- RAW_CLOSURE_CIF_OFFSET, RAW_CLOSURE_FUN_OFFSET,
- RAW_CLOSURE_USER_DATA_OFFSET for the Solaris 10/x86 assembler.
- (.eh_frame): Only use SYMBOL-. iff HAVE_AS_X86_PCREL.
- * src/x86/unix64.S (.Lstore_table): Move to .text section.
- (.Lload_table): Likewise.
- (.eh_frame): Only use SYMBOL-. iff HAVE_AS_X86_PCREL.
-
-2008-12-18 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
-
- * configure: Regenerate.
-
-2008-11-21 Eric Botcazou <ebotcazou@adacore.com>
-
- * src/sparc/ffi.c (ffi_prep_cif_machdep): Add support for
- signed/unsigned int8/16 return values.
- * src/sparc/v8.S (ffi_call_v8): Likewise.
- (ffi_closure_v8): Likewise.
-
-2008-09-26 Peter O'Gorman <pogma@thewrittenword.com>
- Steve Ellcey <sje@cup.hp.com>
-
- * configure: Regenerate for new libtool.
- * Makefile.in: Ditto.
- * include/Makefile.in: Ditto.
- * aclocal.m4: Ditto.
-
-2008-08-25 Andreas Tobler <a.tobler@schweiz.org>
-
- * src/powerpc/ffitarget.h (ffi_abi): Add FFI_LINUX and
- FFI_LINUX_SOFT_FLOAT to the POWERPC_FREEBSD enum.
- Add note about flag bits used for FFI_SYSV_TYPE_SMALL_STRUCT.
- Adjust copyright notice.
- * src/powerpc/ffi.c: Add two new flags to indicate if we have one
- register or two register to use for FFI_SYSV structs.
- (ffi_prep_cif_machdep): Pass the right register flag introduced above.
- (ffi_closure_helper_SYSV): Fix the return type for
- FFI_SYSV_TYPE_SMALL_STRUCT. Comment.
- Adjust copyright notice.
-
-2008-07-16 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/ffi.c (ffi_prep_closure_loc): Turn INSN into an unsigned
- int.
-
-2008-06-17 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
-
- * configure: Regenerate.
- * include/Makefile.in: Regenerate.
- * testsuite/Makefile.in: Regenerate.
-
-2008-06-07 Joseph Myers <joseph@codesourcery.com>
-
- * configure.ac (parisc*-*-linux*, powerpc-*-sysv*,
- powerpc-*-beos*): Remove.
- * configure: Regenerate.
-
-2008-05-09 Julian Brown <julian@codesourcery.com>
-
- * Makefile.am (LTLDFLAGS): New.
- (libffi_la_LDFLAGS): Use above.
- * Makefile.in: Regenerate.
-
-2008-04-18 Paolo Bonzini <bonzini@gnu.org>
-
- PR bootstrap/35457
- * aclocal.m4: Regenerate.
- * configure: Regenerate.
-
-2008-03-26 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/sysv.S: Add .note.GNU-stack on Linux.
- * src/sh64/sysv.S: Likewise.
-
-2008-03-26 Daniel Jacobowitz <dan@debian.org>
-
- * src/arm/sysv.S: Fix ARM comment marker.
-
-2008-03-26 Jakub Jelinek <jakub@redhat.com>
-
- * src/alpha/osf.S: Add .note.GNU-stack on Linux.
- * src/s390/sysv.S: Likewise.
- * src/powerpc/ppc_closure.S: Likewise.
- * src/powerpc/sysv.S: Likewise.
- * src/x86/unix64.S: Likewise.
- * src/x86/sysv.S: Likewise.
- * src/sparc/v8.S: Likewise.
- * src/sparc/v9.S: Likewise.
- * src/m68k/sysv.S: Likewise.
- * src/arm/sysv.S: Likewise.
-
-2008-03-16 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
-
- * aclocal.m4: Regenerate.
- * configure: Likewise.
- * Makefile.in: Likewise.
- * include/Makefile.in: Likewise.
- * testsuite/Makefile.in: Likewise.
-
-2008-02-12 Bjoern Koenig <bkoenig@alpha-tierchen.de>
- Andreas Tobler <a.tobler@schweiz.org>
-
- * configure.ac: Add amd64-*-freebsd* target.
- * configure: Regenerate.
-
-2008-01-30 H.J. Lu <hongjiu.lu@intel.com>
-
- PR libffi/34612
- * src/x86/sysv.S (ffi_closure_SYSV): Pop 4 byte from stack when
- returning struct.
-
- * testsuite/libffi.call/call.exp: Add "-O2 -fomit-frame-pointer"
- tests.
-
-2008-01-24 David Edelsohn <edelsohn@gnu.org>
-
- * configure: Regenerate.
-
-2008-01-06 Andreas Tobler <a.tobler@schweiz.org>
-
- * src/x86/ffi.c (ffi_prep_cif_machdep): Fix thinko.
-
-2008-01-05 Andreas Tobler <a.tobler@schweiz.org>
-
- PR testsuite/32843
- * src/x86/ffi.c (ffi_prep_cif_machdep): Add code for
- signed/unsigned int8/16 for X86_DARWIN.
- Updated copyright info.
- Handle one and two byte structs with special cif->flags.
- * src/x86/ffitarget.h: Add special types for one and two byte structs.
- Updated copyright info.
- * src/x86/darwin.S (ffi_call_SYSV): Rewrite to use a jump table like
- sysv.S
- Remove code to pop args from the stack after call.
- Special-case signed/unsigned for int8/16, one and two byte structs.
- (ffi_closure_raw_SYSV): Handle FFI_TYPE_UINT8,
- FFI_TYPE_SINT8, FFI_TYPE_UINT16, FFI_TYPE_SINT16, FFI_TYPE_UINT32,
- FFI_TYPE_SINT32.
- Updated copyright info.
-
-2007-12-08 David Daney <ddaney@avtrex.com>
-
- * src/mips/n32.S (ffi_call_N32): Replace dadd with ADDU, dsub with
- SUBU, add with ADDU and use smaller code sequences.
-
-2007-12-07 David Daney <ddaney@avtrex.com>
-
- * src/mips/ffi.c (ffi_prep_cif_machdep): Handle long double return
- type.
-
-2007-12-06 David Daney <ddaney@avtrex.com>
-
- * include/ffi.h.in (FFI_SIZEOF_JAVA_RAW): Define if not already
- defined.
- (ffi_java_raw): New typedef.
- (ffi_java_raw_call, ffi_java_ptrarray_to_raw,
- ffi_java_raw_to_ptrarray): Change parameter types from ffi_raw to
- ffi_java_raw.
- (ffi_java_raw_closure) : Same.
- (ffi_prep_java_raw_closure, ffi_prep_java_raw_closure_loc): Change
- parameter types.
- * src/java_raw_api.c (ffi_java_raw_size): Replace FFI_SIZEOF_ARG with
- FFI_SIZEOF_JAVA_RAW.
- (ffi_java_raw_to_ptrarray): Change type of raw to ffi_java_raw.
- Replace FFI_SIZEOF_ARG with FFI_SIZEOF_JAVA_RAW. Use
- sizeof(ffi_java_raw) for alignment calculations.
- (ffi_java_ptrarray_to_raw): Same.
- (ffi_java_rvalue_to_raw): Add special handling for FFI_TYPE_POINTER
- if FFI_SIZEOF_JAVA_RAW == 4.
- (ffi_java_raw_to_rvalue): Same.
- (ffi_java_raw_call): Change type of raw to ffi_java_raw.
- (ffi_java_translate_args): Same.
- (ffi_prep_java_raw_closure_loc, ffi_prep_java_raw_closure): Change
- parameter types.
- * src/mips/ffitarget.h (FFI_SIZEOF_JAVA_RAW): Define for N32 ABI.
-
-2007-12-06 David Daney <ddaney@avtrex.com>
-
- * src/mips/n32.S (ffi_closure_N32): Use 64-bit add instruction on
- pointer values.
-
-2007-12-01 Andreas Tobler <a.tobler@schweiz.org>
-
- PR libffi/31937
- * src/powerpc/ffitarget.h: Introduce new ABI FFI_LINUX_SOFT_FLOAT.
- Add local FFI_TYPE_UINT128 to handle soft-float long-double-128.
- * src/powerpc/ffi.c: Distinguish between __NO_FPRS__ and not and
- set the NUM_FPR_ARG_REGISTERS according to.
- Add support for potential soft-float support under hard-float
- architecture.
- (ffi_prep_args_SYSV): Set NUM_FPR_ARG_REGISTERS to 0 in case of
- FFI_LINUX_SOFT_FLOAT, handle float, doubles and long-doubles according
- to the FFI_LINUX_SOFT_FLOAT ABI.
- (ffi_prep_cif_machdep): Likewise.
- (ffi_closure_helper_SYSV): Likewise.
- * src/powerpc/ppc_closure.S: Make sure not to store float/double
- on archs where __NO_FPRS__ is true.
- Add FFI_TYPE_UINT128 support.
- * src/powerpc/sysv.S: Add support for soft-float long-double-128.
- Adjust copyright notice.
-
-2007-11-25 Andreas Tobler <a.tobler@schweiz.org>
-
- * src/closures.c: Move defintion of MAYBE_UNUSED from here to ...
- * include/ffi_common.h: ... here.
- Update copyright.
-
-2007-11-17 Andreas Tobler <a.tobler@schweiz.org>
-
- * src/powerpc/sysv.S: Load correct cr to compare if we have long double.
- * src/powerpc/linux64.S: Likewise.
- * src/powerpc/ffi.c: Add a comment to show which part goes into cr6.
- * testsuite/libffi.call/return_ldl.c: New test.
-
-2007-09-04 <aph@redhat.com>
-
- * src/arm/sysv.S (UNWIND): New.
- (Whole file): Conditionally compile unwinder directives.
- * src/arm/sysv.S: Add unwinder directives.
-
- * src/arm/ffi.c (ffi_prep_args): Align structs by at least 4 bytes.
- Only treat r0 as a struct address if we're actually returning a
- struct by address.
- Only copy the bytes that are actually within a struct.
- (ffi_prep_cif_machdep): A Composite Type not larger than 4 bytes
- is returned in r0, not passed by address.
- (ffi_call): Allocate a word-sized temporary for the case where
- a composite is returned in r0.
- (ffi_prep_incoming_args_SYSV): Align as necessary.
-
-2007-08-05 Steven Newbury <s_j_newbury@yahoo.co.uk>
-
- * src/arm/ffi.c (FFI_INIT_TRAMPOLINE): Use __clear_cache instead of
- directly using the sys_cacheflush syscall.
-
-2007-07-27 Andrew Haley <aph@redhat.com>
-
- * src/arm/sysv.S (ffi_closure_SYSV): Add soft-float.
-
-2007-09-03 Maciej W. Rozycki <macro@linux-mips.org>
-
- * Makefile.am: Unify MIPS_IRIX and MIPS_LINUX into MIPS.
- * configure.ac: Likewise.
- * Makefile.in: Regenerate.
- * include/Makefile.in: Likewise.
- * testsuite/Makefile.in: Likewise.
- * configure: Likewise.
-
-2007-08-24 David Daney <ddaney@avtrex.com>
-
- * testsuite/libffi.call/return_sl.c: New test.
-
-2007-08-10 David Daney <ddaney@avtrex.com>
-
- * testsuite/libffi.call/cls_multi_ushort.c,
- testsuite/libffi.call/cls_align_uint16.c,
- testsuite/libffi.call/nested_struct1.c,
- testsuite/libffi.call/nested_struct3.c,
- testsuite/libffi.call/cls_7_1_byte.c,
- testsuite/libffi.call/nested_struct5.c,
- testsuite/libffi.call/cls_double.c,
- testsuite/libffi.call/nested_struct7.c,
- testsuite/libffi.call/cls_sint.c,
- testsuite/libffi.call/nested_struct9.c,
- testsuite/libffi.call/cls_20byte1.c,
- testsuite/libffi.call/cls_multi_sshortchar.c,
- testsuite/libffi.call/cls_align_sint64.c,
- testsuite/libffi.call/cls_3byte2.c,
- testsuite/libffi.call/cls_multi_schar.c,
- testsuite/libffi.call/cls_multi_uchar.c,
- testsuite/libffi.call/cls_19byte.c,
- testsuite/libffi.call/cls_9byte1.c,
- testsuite/libffi.call/cls_align_float.c,
- testsuite/libffi.call/closure_fn1.c,
- testsuite/libffi.call/problem1.c,
- testsuite/libffi.call/closure_fn3.c,
- testsuite/libffi.call/cls_sshort.c,
- testsuite/libffi.call/closure_fn5.c,
- testsuite/libffi.call/cls_align_double.c,
- testsuite/libffi.call/nested_struct.c,
- testsuite/libffi.call/cls_2byte.c,
- testsuite/libffi.call/nested_struct10.c,
- testsuite/libffi.call/cls_4byte.c,
- testsuite/libffi.call/cls_6byte.c,
- testsuite/libffi.call/cls_8byte.c,
- testsuite/libffi.call/cls_multi_sshort.c,
- testsuite/libffi.call/cls_align_sint16.c,
- testsuite/libffi.call/cls_align_uint32.c,
- testsuite/libffi.call/cls_20byte.c,
- testsuite/libffi.call/cls_float.c,
- testsuite/libffi.call/nested_struct2.c,
- testsuite/libffi.call/cls_5_1_byte.c,
- testsuite/libffi.call/nested_struct4.c,
- testsuite/libffi.call/cls_24byte.c,
- testsuite/libffi.call/nested_struct6.c,
- testsuite/libffi.call/cls_64byte.c,
- testsuite/libffi.call/nested_struct8.c,
- testsuite/libffi.call/cls_uint.c,
- testsuite/libffi.call/cls_multi_ushortchar.c,
- testsuite/libffi.call/cls_schar.c,
- testsuite/libffi.call/cls_uchar.c,
- testsuite/libffi.call/cls_align_uint64.c,
- testsuite/libffi.call/cls_ulonglong.c,
- testsuite/libffi.call/cls_align_longdouble.c,
- testsuite/libffi.call/cls_1_1byte.c,
- testsuite/libffi.call/cls_12byte.c,
- testsuite/libffi.call/cls_3_1byte.c,
- testsuite/libffi.call/cls_3byte1.c,
- testsuite/libffi.call/cls_4_1byte.c,
- testsuite/libffi.call/cls_6_1_byte.c,
- testsuite/libffi.call/cls_16byte.c,
- testsuite/libffi.call/cls_18byte.c,
- testsuite/libffi.call/closure_fn0.c,
- testsuite/libffi.call/cls_9byte2.c,
- testsuite/libffi.call/closure_fn2.c,
- testsuite/libffi.call/closure_fn4.c,
- testsuite/libffi.call/cls_ushort.c,
- testsuite/libffi.call/closure_fn6.c,
- testsuite/libffi.call/cls_5byte.c,
- testsuite/libffi.call/cls_align_pointer.c,
- testsuite/libffi.call/cls_7byte.c,
- testsuite/libffi.call/cls_align_sint32.c,
- testsuite/libffi.special/unwindtest_ffi_call.cc,
- testsuite/libffi.special/unwindtest.cc: Remove xfail for mips64*-*-*.
-
-2007-08-10 David Daney <ddaney@avtrex.com>
-
- PR libffi/28313
- * configure.ac: Don't treat mips64 as a special case.
- * Makefile.am (nodist_libffi_la_SOURCES): Add n32.S.
- * configure: Regenerate
- * Makefile.in: Ditto.
- * fficonfig.h.in: Ditto.
- * src/mips/ffitarget.h (REG_L, REG_S, SUBU, ADDU, SRL, LI): Indent.
- (LA, EH_FRAME_ALIGN, FDE_ADDR_BYTES): New preprocessor macros.
- (FFI_DEFAULT_ABI): Set for n64 case.
- (FFI_CLOSURES, FFI_TRAMPOLINE_SIZE): Define for n32 and n64 cases.
- * src/mips/n32.S (ffi_call_N32): Add debug macros and labels for FDE.
- (ffi_closure_N32): New function.
- (.eh_frame): New section
- * src/mips/o32.S: Clean up comments.
- (ffi_closure_O32): Pass ffi_closure parameter in $12.
- * src/mips/ffi.c: Use FFI_MIPS_N32 instead of
- _MIPS_SIM == _ABIN32 throughout.
- (FFI_MIPS_STOP_HERE): New, use in place of
- ffi_stop_here.
- (ffi_prep_args): Use unsigned long to hold pointer values. Rewrite
- to support n32/n64 ABIs.
- (calc_n32_struct_flags): Rewrite.
- (calc_n32_return_struct_flags): Remove unused variable. Reverse
- position of flag bits.
- (ffi_prep_cif_machdep): Rewrite n32 portion.
- (ffi_call): Enable for n64. Add special handling for small structure
- return values.
- (ffi_prep_closure_loc): Add n32 and n64 support.
- (ffi_closure_mips_inner_O32): Add cast to silence warning.
- (copy_struct_N32, ffi_closure_mips_inner_N32): New functions.
-
-2007-08-08 David Daney <ddaney@avtrex.com>
-
- * testsuite/libffi.call/ffitest.h (ffi_type_mylong): Remove definition.
- * testsuite/libffi.call/cls_align_uint16.c (main): Use correct type
- specifiers.
- * testsuite/libffi.call/nested_struct1.c (main): Ditto.
- * testsuite/libffi.call/cls_sint.c (main): Ditto.
- * testsuite/libffi.call/nested_struct9.c (main): Ditto.
- * testsuite/libffi.call/cls_20byte1.c (main): Ditto.
- * testsuite/libffi.call/cls_9byte1.c (main): Ditto.
- * testsuite/libffi.call/closure_fn1.c (main): Ditto.
- * testsuite/libffi.call/closure_fn3.c (main): Ditto.
- * testsuite/libffi.call/return_dbl2.c (main): Ditto.
- * testsuite/libffi.call/cls_sshort.c (main): Ditto.
- * testsuite/libffi.call/return_fl3.c (main): Ditto.
- * testsuite/libffi.call/closure_fn5.c (main): Ditto.
- * testsuite/libffi.call/nested_struct.c (main): Ditto.
- * testsuite/libffi.call/nested_struct10.c (main): Ditto.
- * testsuite/libffi.call/return_ll1.c (main): Ditto.
- * testsuite/libffi.call/cls_8byte.c (main): Ditto.
- * testsuite/libffi.call/cls_align_uint32.c (main): Ditto.
- * testsuite/libffi.call/cls_align_sint16.c (main): Ditto.
- * testsuite/libffi.call/cls_20byte.c (main): Ditto.
- * testsuite/libffi.call/nested_struct2.c (main): Ditto.
- * testsuite/libffi.call/cls_24byte.c (main): Ditto.
- * testsuite/libffi.call/nested_struct6.c (main): Ditto.
- * testsuite/libffi.call/cls_uint.c (main): Ditto.
- * testsuite/libffi.call/cls_12byte.c (main): Ditto.
- * testsuite/libffi.call/cls_16byte.c (main): Ditto.
- * testsuite/libffi.call/closure_fn0.c (main): Ditto.
- * testsuite/libffi.call/cls_9byte2.c (main): Ditto.
- * testsuite/libffi.call/closure_fn2.c (main): Ditto.
- * testsuite/libffi.call/return_dbl1.c (main): Ditto.
- * testsuite/libffi.call/closure_fn4.c (main): Ditto.
- * testsuite/libffi.call/closure_fn6.c (main): Ditto.
- * testsuite/libffi.call/cls_align_sint32.c (main): Ditto.
-
-2007-08-07 Andrew Haley <aph@redhat.com>
-
- * src/x86/sysv.S (ffi_closure_raw_SYSV): Fix typo in previous
- checkin.
-
-2007-08-06 Andrew Haley <aph@redhat.com>
-
- PR testsuite/32843
- * src/x86/sysv.S (ffi_closure_raw_SYSV): Handle FFI_TYPE_UINT8,
- FFI_TYPE_SINT8, FFI_TYPE_UINT16, FFI_TYPE_SINT16, FFI_TYPE_UINT32,
- FFI_TYPE_SINT32.
-
-2007-08-02 David Daney <ddaney@avtrex.com>
-
- * testsuite/libffi.call/return_ul.c (main): Define return type as
- ffi_arg. Use proper printf conversion specifier.
-
-2007-07-30 Andrew Haley <aph@redhat.com>
-
- PR testsuite/32843
- * src/x86/ffi.c (ffi_prep_cif_machdep): in x86 case, add code for
- signed/unsigned int8/16.
- * src/x86/sysv.S (ffi_call_SYSV): Rewrite to:
- Use a jump table.
- Remove code to pop args from the stack after call.
- Special-case signed/unsigned int8/16.
- * testsuite/libffi.call/return_sc.c (main): Revert.
-
-2007-07-26 Richard Guenther <rguenther@suse.de>
-
- PR testsuite/32843
- * testsuite/libffi.call/return_sc.c (main): Verify call
- result as signed char, not ffi_arg.
-
-2007-07-16 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * configure.ac (i?86-*-solaris2.1[0-9]): Set TARGET to X86_64.
- * configure: Regenerate.
-
-2007-07-11 David Daney <ddaney@avtrex.com>
-
- * src/mips/ffi.c: Don't include sys/cachectl.h.
- (ffi_prep_closure_loc): Use __builtin___clear_cache() instead of
- cacheflush().
-
-2007-05-18 Aurelien Jarno <aurelien@aurel32.net>
-
- * src/arm/ffi.c (ffi_prep_closure_loc): Renamed and ajusted
- from (ffi_prep_closure): ... this.
- (FFI_INIT_TRAMPOLINE): Adjust.
-
-2005-12-31 Phil Blundell <pb@reciva.com>
-
- * src/arm/ffi.c (ffi_prep_incoming_args_SYSV,
- ffi_closure_SYSV_inner, ffi_prep_closure): New, add closure support.
- * src/arm/sysv.S(ffi_closure_SYSV): Likewise.
- * src/arm/ffitarget.h (FFI_TRAMPOLINE_SIZE): Likewise.
- (FFI_CLOSURES): Enable closure support.
-
-2007-07-03 Andrew Haley <aph@hedges.billgatliff.com>
-
- * testsuite/libffi.call/cls_multi_ushort.c,
- testsuite/libffi.call/cls_align_uint16.c,
- testsuite/libffi.call/nested_struct1.c,
- testsuite/libffi.call/nested_struct3.c,
- testsuite/libffi.call/cls_7_1_byte.c,
- testsuite/libffi.call/cls_double.c,
- testsuite/libffi.call/nested_struct5.c,
- testsuite/libffi.call/nested_struct7.c,
- testsuite/libffi.call/cls_sint.c,
- testsuite/libffi.call/nested_struct9.c,
- testsuite/libffi.call/cls_20byte1.c,
- testsuite/libffi.call/cls_multi_sshortchar.c,
- testsuite/libffi.call/cls_align_sint64.c,
- testsuite/libffi.call/cls_3byte2.c,
- testsuite/libffi.call/cls_multi_schar.c,
- testsuite/libffi.call/cls_multi_uchar.c,
- testsuite/libffi.call/cls_19byte.c,
- testsuite/libffi.call/cls_9byte1.c,
- testsuite/libffi.call/cls_align_float.c,
- testsuite/libffi.call/closure_fn1.c,
- testsuite/libffi.call/problem1.c,
- testsuite/libffi.call/closure_fn3.c,
- testsuite/libffi.call/cls_sshort.c,
- testsuite/libffi.call/closure_fn5.c,
- testsuite/libffi.call/cls_align_double.c,
- testsuite/libffi.call/cls_2byte.c,
- testsuite/libffi.call/nested_struct.c,
- testsuite/libffi.call/nested_struct10.c,
- testsuite/libffi.call/cls_4byte.c,
- testsuite/libffi.call/cls_6byte.c,
- testsuite/libffi.call/cls_8byte.c,
- testsuite/libffi.call/cls_multi_sshort.c,
- testsuite/libffi.call/cls_align_uint32.c,
- testsuite/libffi.call/cls_align_sint16.c,
- testsuite/libffi.call/cls_float.c,
- testsuite/libffi.call/cls_20byte.c,
- testsuite/libffi.call/cls_5_1_byte.c,
- testsuite/libffi.call/nested_struct2.c,
- testsuite/libffi.call/cls_24byte.c,
- testsuite/libffi.call/nested_struct4.c,
- testsuite/libffi.call/nested_struct6.c,
- testsuite/libffi.call/cls_64byte.c,
- testsuite/libffi.call/nested_struct8.c,
- testsuite/libffi.call/cls_uint.c,
- testsuite/libffi.call/cls_multi_ushortchar.c,
- testsuite/libffi.call/cls_schar.c,
- testsuite/libffi.call/cls_uchar.c,
- testsuite/libffi.call/cls_align_uint64.c,
- testsuite/libffi.call/cls_ulonglong.c,
- testsuite/libffi.call/cls_align_longdouble.c,
- testsuite/libffi.call/cls_1_1byte.c,
- testsuite/libffi.call/cls_12byte.c,
- testsuite/libffi.call/cls_3_1byte.c,
- testsuite/libffi.call/cls_3byte1.c,
- testsuite/libffi.call/cls_4_1byte.c,
- testsuite/libffi.call/cls_6_1_byte.c,
- testsuite/libffi.call/cls_16byte.c,
- testsuite/libffi.call/cls_18byte.c,
- testsuite/libffi.call/closure_fn0.c,
- testsuite/libffi.call/cls_9byte2.c,
- testsuite/libffi.call/closure_fn2.c,
- testsuite/libffi.call/closure_fn4.c,
- testsuite/libffi.call/cls_ushort.c,
- testsuite/libffi.call/closure_fn6.c,
- testsuite/libffi.call/cls_5byte.c,
- testsuite/libffi.call/cls_align_pointer.c,
- testsuite/libffi.call/cls_7byte.c,
- testsuite/libffi.call/cls_align_sint32.c,
- testsuite/libffi.special/unwindtest_ffi_call.cc,
- testsuite/libffi.special/unwindtest.cc: Enable for ARM.
-
-2007-07-05 H.J. Lu <hongjiu.lu@intel.com>
-
- * aclocal.m4: Regenerated.
-
-2007-06-02 Paolo Bonzini <bonzini@gnu.org>
-
- * configure: Regenerate.
-
-2007-05-23 Steve Ellcey <sje@cup.hp.com>
-
- * Makefile.in: Regenerate.
- * configure: Regenerate.
- * aclocal.m4: Regenerate.
- * include/Makefile.in: Regenerate.
- * testsuite/Makefile.in: Regenerate.
-
-2007-05-10 Roman Zippel <zippel@linux-m68k.org>
-
- * src/m68k/ffi.c (ffi_prep_incoming_args_SYSV,
- ffi_closure_SYSV_inner,ffi_prep_closure): New, add closure support.
- * src/m68k/sysv.S(ffi_closure_SYSV,ffi_closure_struct_SYSV): Likewise.
- * src/m68k/ffitarget.h (FFI_TRAMPOLINE_SIZE): Likewise.
- (FFI_CLOSURES): Enable closure support.
-
-2007-05-10 Roman Zippel <zippel@linux-m68k.org>
-
- * configure.ac (HAVE_AS_CFI_PSEUDO_OP): New test.
- * configure: Regenerate.
- * fficonfig.h.in: Regenerate.
- * src/m68k/sysv.S (CFI_STARTPROC,CFI_ENDPROC,
- CFI_OFFSET,CFI_DEF_CFA): New macros.
- (ffi_call_SYSV): Add callframe annotation.
-
-2007-05-10 Roman Zippel <zippel@linux-m68k.org>
-
- * src/m68k/ffi.c (ffi_prep_args,ffi_prep_cif_machdep): Fix
- numerous test suite failures.
- * src/m68k/sysv.S (ffi_call_SYSV): Likewise.
-
-2007-04-11 Paolo Bonzini <bonzini@gnu.org>
-
- * Makefile.am (EXTRA_DIST): Bring up to date.
- * Makefile.in: Regenerate.
- * src/frv/eabi.S: Remove RCS keyword.
-
-2007-04-06 Richard Henderson <rth@redhat.com>
-
- * configure.ac: Tidy target case.
- (HAVE_LONG_DOUBLE): Allow the target to override.
- * configure: Regenerate.
- * include/ffi.h.in: Don't define ffi_type_foo if
- LIBFFI_HIDE_BASIC_TYPES is defined.
- (ffi_type_longdouble): If not HAVE_LONG_DOUBLE, define
- to ffi_type_double.
- * types.c (LIBFFI_HIDE_BASIC_TYPES): Define.
- (FFI_TYPEDEF, ffi_type_void): Mark the data const.
- (ffi_type_longdouble): Special case for Alpha. Don't define
- if long double == double.
-
- * src/alpha/ffi.c (FFI_TYPE_LONGDOUBLE): Assert unique value.
- (ffi_prep_cif_machdep): Handle it as the 128-bit type.
- (ffi_call, ffi_closure_osf_inner): Likewise.
- (ffi_closure_osf_inner): Likewise. Mark hidden.
- (ffi_call_osf, ffi_closure_osf): Mark hidden.
- * src/alpha/ffitarget.h (FFI_LAST_ABI): Tidy definition.
- * src/alpha/osf.S (ffi_call_osf, ffi_closure_osf): Mark hidden.
- (load_table): Handle 128-bit long double.
-
- * testsuite/libffi.call/float4.c: Add -mieee for alpha.
-
-2007-04-06 Tom Tromey <tromey@redhat.com>
-
- PR libffi/31491:
- * README: Fixed bug in example.
-
-2007-04-03 Jakub Jelinek <jakub@redhat.com>
-
- * src/closures.c: Include sys/statfs.h.
- (_GNU_SOURCE): Define on Linux.
- (FFI_MMAP_EXEC_SELINUX): Define.
- (selinux_enabled): New variable.
- (selinux_enabled_check): New function.
- (is_selinux_enabled): Define.
- (dlmmap): Use it.
-
-2007-03-24 Uros Bizjak <ubizjak@gmail.com>
-
- * testsuite/libffi.call/return_fl2.c (return_fl): Mark as static.
- Use 'volatile float sum' to create sum of floats to avoid false
- negative due to excess precision on ix86 targets.
- (main): Ditto.
-
-2007-03-08 Alexandre Oliva <aoliva@redhat.com>
-
- * src/powerpc/ffi.c (flush_icache): Fix left-over from previous
- patch.
- (ffi_prep_closure_loc): Remove unneeded casts. Add needed ones.
-
-2007-03-07 Alexandre Oliva <aoliva@redhat.com>
-
- * include/ffi.h.in (ffi_closure_alloc, ffi_closure_free): New.
- (ffi_prep_closure_loc): New.
- (ffi_prep_raw_closure_loc): New.
- (ffi_prep_java_raw_closure_loc): New.
- * src/closures.c: New file.
- * src/dlmalloc.c [FFI_MMAP_EXEC_WRIT] (struct malloc_segment):
- Replace sflags with exec_offset.
- [FFI_MMAP_EXEC_WRIT] (mmap_exec_offset, add_segment_exec_offset,
- sub_segment_exec_offset): New macros.
- (get_segment_flags, set_segment_flags, check_segment_merge): New
- macros.
- (is_mmapped_segment, is_extern_segment): Use get_segment_flags.
- (add_segment, sys_alloc, create_mspace, create_mspace_with_base,
- destroy_mspace): Use new macros.
- (sys_alloc): Silence warning.
- * Makefile.am (libffi_la_SOURCES): Add src/closures.c.
- * Makefile.in: Rebuilt.
- * src/prep_cif [FFI_CLOSURES] (ffi_prep_closure): Implement in
- terms of ffi_prep_closure_loc.
- * src/raw_api.c (ffi_prep_raw_closure_loc): Renamed and adjusted
- from...
- (ffi_prep_raw_closure): ... this. Re-implement in terms of the
- renamed version.
- * src/java_raw_api (ffi_prep_java_raw_closure_loc): Renamed and
- adjusted from...
- (ffi_prep_java_raw_closure): ... this. Re-implement in terms of
- the renamed version.
- * src/alpha/ffi.c (ffi_prep_closure_loc): Renamed from
- (ffi_prep_closure): ... this.
- * src/pa/ffi.c: Likewise.
- * src/cris/ffi.c: Likewise. Adjust.
- * src/frv/ffi.c: Likewise.
- * src/ia64/ffi.c: Likewise.
- * src/mips/ffi.c: Likewise.
- * src/powerpc/ffi_darwin.c: Likewise.
- * src/s390/ffi.c: Likewise.
- * src/sh/ffi.c: Likewise.
- * src/sh64/ffi.c: Likewise.
- * src/sparc/ffi.c: Likewise.
- * src/x86/ffi64.c: Likewise.
- * src/x86/ffi.c: Likewise.
- (FFI_INIT_TRAMPOLINE): Adjust.
- (ffi_prep_raw_closure_loc): Renamed and adjusted from...
- (ffi_prep_raw_closure): ... this.
- * src/powerpc/ffi.c (ffi_prep_closure_loc): Renamed from
- (ffi_prep_closure): ... this.
- (flush_icache): Adjust.
-
-2007-03-07 Alexandre Oliva <aoliva@redhat.com>
-
- * src/dlmalloc.c: New file, imported version 2.8.3 of Doug
- Lea's malloc.
-
-2007-03-01 Brooks Moses <brooks.moses@codesourcery.com>
-
- * Makefile.am: Add dummy install-pdf target.
- * Makefile.in: Regenerate
-
-2007-02-13 Andreas Krebbel <krebbel1@de.ibm.com>
-
- * src/s390/ffi.c (ffi_prep_args, ffi_prep_cif_machdep,
- ffi_closure_helper_SYSV): Add long double handling.
-
-2007-02-02 Jakub Jelinek <jakub@redhat.com>
-
- * src/powerpc/linux64.S (ffi_call_LINUX64): Move restore of r2
- immediately after bctrl instruction.
-
-2007-01-18 Alexandre Oliva <aoliva@redhat.com>
-
- * Makefile.am (all-recursive, install-recursive,
- mostlyclean-recursive, clean-recursive, distclean-recursive,
- maintainer-clean-recursive): Add missing targets.
- * Makefile.in: Rebuilt.
-
-2006-12-14 Andreas Tobler <a.tobler@schweiz.org>
-
- * configure.ac: Add TARGET for x86_64-*-darwin*.
- * Makefile.am (nodist_libffi_la_SOURCES): Add rules for 64-bit sources
- for X86_DARWIN.
- * src/x86/ffitarget.h: Set trampoline size for x86_64-*-darwin*.
- * src/x86/darwin64.S: New file for x86_64-*-darwin* support.
- * configure: Regenerate.
- * Makefile.in: Regenerate.
- * include/Makefile.in: Regenerate.
- * testsuite/Makefile.in: Regenerate.
- * testsuite/libffi.special/unwindtest_ffi_call.cc: New test case for
- ffi_call only.
-
-2006-12-13 Andreas Tobler <a.tobler@schweiz.org>
-
- * aclocal.m4: Regenerate with aclocal -I .. as written in the
- Makefile.am.
-
-2006-10-31 Geoffrey Keating <geoffk@apple.com>
-
- * src/powerpc/ffi_darwin.c (darwin_adjust_aggregate_sizes): New.
- (ffi_prep_cif_machdep): Call darwin_adjust_aggregate_sizes for
- Darwin.
- * testsuite/libffi.call/nested_struct4.c: Remove Darwin XFAIL.
- * testsuite/libffi.call/nested_struct6.c: Remove Darwin XFAIL.
-
-2006-10-10 Paolo Bonzini <bonzini@gnu.org>
- Sandro Tolaini <tolaini@libero.it>
-
- * configure.ac [i*86-*-darwin*]: Set X86_DARWIN symbol and
- conditional.
- * configure: Regenerated.
- * Makefile.am (nodist_libffi_la_SOURCES) [X86_DARWIN]: New case.
- (EXTRA_DIST): Add src/x86/darwin.S.
- * Makefile.in: Regenerated.
- * include/Makefile.in: Regenerated.
- * testsuite/Makefile.in: Regenerated.
-
- * src/x86/ffi.c (ffi_prep_cif_machdep) [X86_DARWIN]: Treat like
- X86_WIN32, and additionally align stack to 16 bytes.
- * src/x86/darwin.S: New, based on sysv.S.
- * src/prep_cif.c (ffi_prep_cif) [X86_DARWIN]: Align > 8-byte structs.
-
-2006-09-12 David Daney <ddaney@avtrex.com>
-
- PR libffi/23935
- * include/Makefile.am: Install both ffi.h and ffitarget.h in
- $(libdir)/gcc/$(target_alias)/$(gcc_version)/include.
- * aclocal.m4: Regenerated for automake 1.9.6.
- * Makefile.in: Regenerated.
- * include/Makefile.in: Regenerated.
- * testsuite/Makefile.in: Regenerated.
-
-2006-08-17 Andreas Tobler <a.tobler@schweiz.ch>
-
- * include/ffi_common.h (struct): Revert accidental commit.
-
-2006-08-15 Andreas Tobler <a.tobler@schweiz.ch>
-
- * include/ffi_common.h: Remove lint directives.
- * include/ffi.h.in: Likewise.
-
-2006-07-25 Torsten Schoenfeld <kaffeetisch@gmx.de>
-
- * include/ffi.h.in (ffi_type_ulong, ffi_type_slong): Define correctly
- for 32-bit architectures.
- * testsuite/libffi.call/return_ul.c: New test case.
-
-2006-07-19 David Daney <ddaney@avtrex.com>
-
- * testsuite/libffi.call/closure_fn6.c: Remove xfail for mips,
- xfail remains for mips64.
-
-2006-05-23 Carlos O'Donell <carlos@codesourcery.com>
-
- * Makefile.am: Add install-html target. Add install-html to .PHONY
- * Makefile.in: Regenerate.
- * aclocal.m4: Regenerate.
- * include/Makefile.in: Regenerate.
- * testsuite/Makefile.in: Regenerate.
-
-2006-05-18 John David Anglin <dave.anglin@nrc-cnrc.gc.ca>
-
- * pa/ffi.c (ffi_prep_args_pa32): Load floating point arguments from
- stack slot.
-
-2006-04-22 Andreas Tobler <a.tobler@schweiz.ch>
-
- * README: Remove notice about 'Crazy Comments'.
- * src/debug.c: Remove lint directives. Cleanup white spaces.
- * src/java_raw_api.c: Likewise.
- * src/prep_cif.c: Likewise.
- * src/raw_api.c: Likewise.
- * src/ffitest.c: Delete. No longer needed, all test cases migrated
- to the testsuite.
- * src/arm/ffi.c: Remove lint directives.
- * src/m32r/ffi.c: Likewise.
- * src/pa/ffi.c: Likewise.
- * src/powerpc/ffi.c: Likewise.
- * src/powerpc/ffi_darwin.c: Likewise.
- * src/sh/ffi.c: Likewise.
- * src/sh64/ffi.c: Likewise.
- * src/x86/ffi.c: Likewise.
- * testsuite/libffi.call/float2.c: Likewise.
- * testsuite/libffi.call/promotion.c: Likewise.
- * testsuite/libffi.call/struct1.c: Likewise.
-
-2006-04-13 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/pa/hpux32.S: Correct unwind offset calculation for
- ffi_closure_pa32.
- * src/pa/linux.S: Likewise.
-
-2006-04-12 James E Wilson <wilson@specifix.com>
-
- PR libgcj/26483
- * src/ia64/ffi.c (stf_spill, ldf_fill): Rewrite as macros.
- (hfa_type_load): Call stf_spill.
- (hfa_type_store): Call ldf_fill.
- (ffi_call): Adjust calls to above routines. Add local temps for
- macro result.
-
-2006-04-10 Matthias Klose <doko@debian.org>
-
- * testsuite/lib/libffi-dg.exp (libffi-init): Recognize multilib
- directory names containing underscores.
-
-2006-04-07 James E Wilson <wilson@specifix.com>
-
- * testsuite/libffi.call/float4.c: New testcase.
-
-2006-04-05 John David Anglin <dave.anglin@nrc-cnrc.gc.ca>
- Andreas Tobler <a.tobler@schweiz.ch>
-
- * Makefile.am: Add PA_HPUX port.
- * Makefile.in: Regenerate.
- * include/Makefile.in: Likewise.
- * testsuite/Makefile.in: Likewise.
- * configure.ac: Add PA_HPUX rules.
- * configure: Regenerate.
- * src/pa/ffitarget.h: Rename linux target to PA_LINUX.
- Add PA_HPUX and PA64_HPUX.
- Rename FFI_LINUX ABI to FFI_PA32 ABI.
- (FFI_TRAMPOLINE_SIZE): Define for 32-bit HP-UX targets.
- (FFI_TYPE_SMALL_STRUCT2): Define.
- (FFI_TYPE_SMALL_STRUCT4): Likewise.
- (FFI_TYPE_SMALL_STRUCT8): Likewise.
- (FFI_TYPE_SMALL_STRUCT3): Redefine.
- (FFI_TYPE_SMALL_STRUCT5): Likewise.
- (FFI_TYPE_SMALL_STRUCT6): Likewise.
- (FFI_TYPE_SMALL_STRUCT7): Likewise.
- * src/pa/ffi.c (ROUND_DOWN): Delete.
- (fldw, fstw, fldd, fstd): Use '__asm__'.
- (ffi_struct_type): Add support for FFI_TYPE_SMALL_STRUCT2,
- FFI_TYPE_SMALL_STRUCT4 and FFI_TYPE_SMALL_STRUCT8.
- (ffi_prep_args_LINUX): Rename to ffi_prep_args_pa32. Update comment.
- Simplify incrementing of stack slot variable. Change type of local
- 'n' to unsigned int.
- (ffi_size_stack_LINUX): Rename to ffi_size_stack_pa32. Handle long
- double on PA_HPUX.
- (ffi_prep_cif_machdep): Likewise.
- (ffi_call): Likewise.
- (ffi_closure_inner_LINUX): Rename to ffi_closure_inner_pa32. Change
- return type to ffi_status. Simplify incrementing of stack slot
- variable. Only copy floating point argument registers when PA_LINUX
- is true. Reformat debug statement.
- Add support for FFI_TYPE_SMALL_STRUCT2, FFI_TYPE_SMALL_STRUCT4 and
- FFI_TYPE_SMALL_STRUCT8.
- (ffi_closure_LINUX): Rename to ffi_closure_pa32. Add 'extern' to
- declaration.
- (ffi_prep_closure): Make linux trampoline conditional on PA_LINUX.
- Add nops to cache flush. Add trampoline for PA_HPUX.
- * src/pa/hpux32.S: New file.
- * src/pa/linux.S (ffi_call_LINUX): Rename to ffi_call_pa32. Rename
- ffi_prep_args_LINUX to ffi_prep_args_pa32.
- Localize labels. Add support for 2, 4 and 8-byte small structs. Handle
- unaligned destinations in 3, 5, 6 and 7-byte small structs. Order
- argument type checks so that common argument types appear first.
- (ffi_closure_LINUX): Rename to ffi_closure_pa32. Rename
- ffi_closure_inner_LINUX to ffi_closure_inner_pa32.
-
-2006-03-24 Alan Modra <amodra@bigpond.net.au>
-
- * src/powerpc/ffitarget.h (enum ffi_abi): Add FFI_LINUX. Default
- for 32-bit using IBM extended double format. Fix FFI_LAST_ABI.
- * src/powerpc/ffi.c (ffi_prep_args_SYSV): Handle linux variant of
- FFI_TYPE_LONGDOUBLE.
- (ffi_prep_args64): Assert using IBM extended double.
- (ffi_prep_cif_machdep): Don't munge FFI_TYPE_LONGDOUBLE type.
- Handle FFI_LINUX FFI_TYPE_LONGDOUBLE return and args.
- (ffi_call): Handle FFI_LINUX.
- (ffi_closure_helper_SYSV): Non FFI_LINUX long double return needs
- gpr3 return pointer as for struct return. Handle FFI_LINUX
- FFI_TYPE_LONGDOUBLE return and args. Don't increment "nf"
- unnecessarily.
- * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Load both f1 and f2
- for FFI_TYPE_LONGDOUBLE. Move epilogue insns into case table.
- Don't use r6 as pointer to results, instead use sp offset. Don't
- make a special call to load lr with case table address, instead
- use offset from previous call.
- * src/powerpc/sysv.S (ffi_call_SYSV): Save long double return.
- * src/powerpc/linux64.S (ffi_call_LINUX64): Simplify long double
- return.
-
-2006-03-15 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh64/ffi.c (ffi_prep_cif_machdep): Handle float arguments
- passed with FP registers correctly.
- (ffi_closure_helper_SYSV): Likewise.
- * src/sh64/sysv.S: Likewise.
-
-2006-03-01 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.special/unwindtest.cc (closure_test_fn): Mark cif,
- args and userdata unused.
- (closure_test_fn1): Mark cif and userdata unused.
- (main): Remove unused res.
-
-2006-02-28 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/call.exp: Adjust FSF address. Add test runs for
- -O2, -O3, -Os and the warning flags -W -Wall.
- * testsuite/libffi.special/special.exp: Likewise.
- * testsuite/libffi.call/ffitest.h: Add an __UNUSED__ macro to mark
- unused parameter unused for gcc or else do nothing.
- * testsuite/libffi.special/ffitestcxx.h: Likewise.
- * testsuite/libffi.call/cls_12byte.c (cls_struct_12byte_gn): Mark cif
- and userdata unused.
- * testsuite/libffi.call/cls_16byte.c (cls_struct_16byte_gn): Likewise.
- * testsuite/libffi.call/cls_18byte.c (cls_struct_18byte_gn): Likewise.
- * testsuite/libffi.call/cls_19byte.c (cls_struct_19byte_gn): Likewise.
- * testsuite/libffi.call/cls_1_1byte.c (cls_struct_1_1byte_gn): Likewise.
- * testsuite/libffi.call/cls_20byte.c (cls_struct_20byte_gn): Likewise.
- * testsuite/libffi.call/cls_20byte1.c (cls_struct_20byte_gn): Likewise.
- * testsuite/libffi.call/cls_24byte.c (cls_struct_24byte_gn): Likewise.
- * testsuite/libffi.call/cls_2byte.c (cls_struct_2byte_gn): Likewise.
- * testsuite/libffi.call/cls_3_1byte.c (cls_struct_3_1byte_gn): Likewise.
- * testsuite/libffi.call/cls_3byte1.c (cls_struct_3byte_gn): Likewise.
- * testsuite/libffi.call/cls_3byte2.c (cls_struct_3byte_gn1): Likewise.
- * testsuite/libffi.call/cls_4_1byte.c (cls_struct_4_1byte_gn): Likewise.
- * testsuite/libffi.call/cls_4byte.c (cls_struct_4byte_gn): Likewise.
- * testsuite/libffi.call/cls_5_1_byte.c (cls_struct_5byte_gn): Likewise.
- * testsuite/libffi.call/cls_5byte.c (cls_struct_5byte_gn): Likewise.
- * testsuite/libffi.call/cls_64byte.c (cls_struct_64byte_gn): Likewise.
- * testsuite/libffi.call/cls_6_1_byte.c (cls_struct_6byte_gn): Likewise.
- * testsuite/libffi.call/cls_6byte.c (cls_struct_6byte_gn): Likewise.
- * testsuite/libffi.call/cls_7_1_byte.c (cls_struct_7byte_gn): Likewise.
- * testsuite/libffi.call/cls_7byte.c (cls_struct_7byte_gn): Likewise.
- * testsuite/libffi.call/cls_8byte.c (cls_struct_8byte_gn): Likewise.
- * testsuite/libffi.call/cls_9byte1.c (cls_struct_9byte_gn): Likewise.
- * testsuite/libffi.call/cls_9byte2.c (cls_struct_9byte_gn): Likewise.
- * testsuite/libffi.call/cls_align_double.c (cls_struct_align_gn):
- Likewise.
- * testsuite/libffi.call/cls_align_float.c (cls_struct_align_gn):
- Likewise.
- * testsuite/libffi.call/cls_align_longdouble.c (cls_struct_align_gn):
- Likewise.
- * testsuite/libffi.call/cls_align_pointer.c (cls_struct_align_fn): Cast
- void* to avoid compiler warning.
- (main): Likewise.
- (cls_struct_align_gn): Mark cif and userdata unused.
- * testsuite/libffi.call/cls_align_sint16.c (cls_struct_align_gn):
- Likewise.
- * testsuite/libffi.call/cls_align_sint32.c (cls_struct_align_gn):
- Likewise.
- * testsuite/libffi.call/cls_align_sint64.c (cls_struct_align_gn):
- Likewise.
- * testsuite/libffi.call/cls_align_uint16.c (cls_struct_align_gn):
- Likewise.
- * testsuite/libffi.call/cls_align_uint32.c (cls_struct_align_gn):
- Likewise.
- * testsuite/libffi.call/cls_double.c (cls_ret_double_fn): Likewise.
- * testsuite/libffi.call/cls_float.c (cls_ret_float_fn): Likewise.
- * testsuite/libffi.call/cls_multi_schar.c (test_func_gn): Mark cif and
- data unused.
- (main): Cast res_call to silence gcc.
- * testsuite/libffi.call/cls_multi_sshort.c (test_func_gn): Mark cif and
- data unused.
- (main): Cast res_call to silence gcc.
- * testsuite/libffi.call/cls_multi_sshortchar.c (test_func_gn): Mark cif
- and data unused.
- (main): Cast res_call to silence gcc.
- * testsuite/libffi.call/cls_multi_uchar.c (test_func_gn): Mark cif and
- data unused.
- (main): Cast res_call to silence gcc.
- * testsuite/libffi.call/cls_multi_ushort.c (test_func_gn): Mark cif and
- data unused.
- (main): Cast res_call to silence gcc.
- * testsuite/libffi.call/cls_multi_ushortchar.c (test_func_gn): Mark cif
- and data unused.
- (main): Cast res_call to silence gcc.
- * testsuite/libffi.call/cls_schar.c (cls_ret_schar_fn): Mark cif and
- userdata unused.
- (cls_ret_schar_fn): Cast printf parameter to silence gcc.
- * testsuite/libffi.call/cls_sint.c (cls_ret_sint_fn): Mark cif and
- userdata unused.
- (cls_ret_sint_fn): Cast printf parameter to silence gcc.
- * testsuite/libffi.call/cls_sshort.c (cls_ret_sshort_fn): Mark cif and
- userdata unused.
- (cls_ret_sshort_fn): Cast printf parameter to silence gcc.
- * testsuite/libffi.call/cls_uchar.c (cls_ret_uchar_fn): Mark cif and
- userdata unused.
- (cls_ret_uchar_fn): Cast printf parameter to silence gcc.
- * testsuite/libffi.call/cls_uint.c (cls_ret_uint_fn): Mark cif and
- userdata unused.
- (cls_ret_uint_fn): Cast printf parameter to silence gcc.
- * testsuite/libffi.call/cls_ulonglong.c (cls_ret_ulonglong_fn): Mark cif
- and userdata unused.
- * testsuite/libffi.call/cls_ushort.c (cls_ret_ushort_fn): Mark cif and
- userdata unused.
- (cls_ret_ushort_fn): Cast printf parameter to silence gcc.
- * testsuite/libffi.call/float.c (floating): Remove unused parameter e.
- * testsuite/libffi.call/float1.c (main): Remove unused variable i.
- Cleanup white spaces.
- * testsuite/libffi.call/negint.c (checking): Remove unused variable i.
- * testsuite/libffi.call/nested_struct.c (cls_struct_combined_gn): Mark
- cif and userdata unused.
- * testsuite/libffi.call/nested_struct1.c (cls_struct_combined_gn):
- Likewise.
- * testsuite/libffi.call/nested_struct10.c (B_gn): Likewise.
- * testsuite/libffi.call/nested_struct2.c (B_fn): Adjust printf
- formatters to silence gcc.
- (B_gn): Mark cif and userdata unused.
- * testsuite/libffi.call/nested_struct3.c (B_gn): Mark cif and userdata
- unused.
- * testsuite/libffi.call/nested_struct4.c: Mention related PR.
- (B_gn): Mark cif and userdata unused.
- * testsuite/libffi.call/nested_struct5.c (B_gn): Mark cif and userdata
- unused.
- * testsuite/libffi.call/nested_struct6.c: Mention related PR.
- (B_gn): Mark cif and userdata unused.
- * testsuite/libffi.call/nested_struct7.c (B_gn): Mark cif and userdata
- unused.
- * testsuite/libffi.call/nested_struct8.c (B_gn): Likewise.
- * testsuite/libffi.call/nested_struct9.c (B_gn): Likewise.
- * testsuite/libffi.call/problem1.c (stub): Likewise.
- * testsuite/libffi.call/pyobjc-tc.c (main): Cast the result to silence
- gcc.
- * testsuite/libffi.call/return_fl2.c (return_fl): Add the note mentioned
- in the last commit for this test case in the test case itself.
- * testsuite/libffi.call/closure_fn0.c (closure_test_fn0): Mark cif as
- unused.
- * testsuite/libffi.call/closure_fn1.c (closure_test_fn1): Likewise.
- * testsuite/libffi.call/closure_fn2.c (closure_test_fn2): Likewise.
- * testsuite/libffi.call/closure_fn3.c (closure_test_fn3): Likewise.
- * testsuite/libffi.call/closure_fn4.c (closure_test_fn0): Likewise.
- * testsuite/libffi.call/closure_fn5.c (closure_test_fn5): Likewise.
- * testsuite/libffi.call/closure_fn6.c (closure_test_fn0): Likewise.
-
-2006-02-22 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/sysv.S: Fix register numbers in the FDE for
- ffi_closure_SYSV.
-
-2006-02-20 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/return_fl2.c (return_fl): Remove static
- declaration to avoid a false negative on ix86. See PR323.
-
-2006-02-18 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/ffi.c (ffi_closure_helper_SYSV): Remove unused variable
- and cast integer to void * if needed. Update the pointer to
- the FP register saved area correctly.
-
-2006-02-17 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/nested_struct6.c: XFAIL this test until PR25630
- is fixed.
- * testsuite/libffi.call/nested_struct4.c: Likewise.
-
-2006-02-16 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/return_dbl.c: New test case.
- * testsuite/libffi.call/return_dbl1.c: Likewise.
- * testsuite/libffi.call/return_dbl2.c: Likewise.
- * testsuite/libffi.call/return_fl.c: Likewise.
- * testsuite/libffi.call/return_fl1.c: Likewise.
- * testsuite/libffi.call/return_fl2.c: Likewise.
- * testsuite/libffi.call/return_fl3.c: Likewise.
- * testsuite/libffi.call/closure_fn6.c: Likewise.
-
- * testsuite/libffi.call/nested_struct2.c: Remove ffi_type_mylong
- definition.
- * testsuite/libffi.call/ffitest.h: Add ffi_type_mylong definition
- here to be used by other test cases too.
-
- * testsuite/libffi.call/nested_struct10.c: New test case.
- * testsuite/libffi.call/nested_struct9.c: Likewise.
- * testsuite/libffi.call/nested_struct8.c: Likewise.
- * testsuite/libffi.call/nested_struct7.c: Likewise.
- * testsuite/libffi.call/nested_struct6.c: Likewise.
- * testsuite/libffi.call/nested_struct5.c: Likewise.
- * testsuite/libffi.call/nested_struct4.c: Likewise.
-
-2006-01-21 Andreas Tobler <a.tobler@schweiz.ch>
-
- * configure.ac: Enable libffi for sparc64-*-freebsd*.
- * configure: Rebuilt.
-
-2006-01-18 Jakub Jelinek <jakub@redhat.com>
-
- * src/powerpc/sysv.S (smst_two_register): Don't call __ashldi3,
- instead do the shifting inline.
- * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Don't compute %r5
- shift count unconditionally. Simplify load sequences for 1, 2, 3, 4
- and 8 byte structs, for the remaining struct sizes don't call
- __lshrdi3, instead do the shifting inline.
-
-2005-12-07 Thiemo Seufer <ths@networkno.de>
-
- * src/mips/ffitarget.h: Remove obsolete sgidefs.h include. Add
- missing parentheses.
- * src/mips/o32.S (ffi_call_O32): Code formatting. Define
- and use A3_OFF, FP_OFF, RA_OFF. Micro-optimizations.
- (ffi_closure_O32): Likewise, but with newly defined A3_OFF2,
- A2_OFF2, A1_OFF2, A0_OFF2, RA_OFF2, FP_OFF2, S0_OFF2, GP_OFF2,
- V1_OFF2, V0_OFF2, FA_1_1_OFF2, FA_1_0_OFF2, FA_0_1_OFF2,
- FA_0_0_OFF2.
- * src/mips/ffi.c (ffi_prep_args): Code formatting. Fix
- endianness bugs.
- (ffi_prep_closure): Improve trampoline instruction scheduling.
- (ffi_closure_mips_inner_O32): Fix endianness bugs.
-
-2005-12-03 Alan Modra <amodra@bigpond.net.au>
-
- * src/powerpc/ffi.c: Formatting.
- (ffi_prep_args_SYSV): Avoid possible aliasing problems by using unions.
- (ffi_prep_args64): Likewise.
-
-2005-09-30 Geoffrey Keating <geoffk@apple.com>
-
- * testsuite/lib/libffi-dg.exp (libffi_target_compile): For
- darwin, use -shared-libgcc not -lgcc_s, and explain why.
-
-2005-09-26 Tom Tromey <tromey@redhat.com>
-
- * testsuite/libffi.call/float1.c (value_type): New typedef.
- (CANARY): New define.
- (main): Check for result buffer overflow.
- * src/powerpc/linux64.S: Handle linux64 long double returns.
- * src/powerpc/ffi.c (FLAG_RETURNS_128BITS): New constant.
- (ffi_prep_cif_machdep): Handle linux64 long double returns.
-
-2005-08-25 Alan Modra <amodra@bigpond.net.au>
-
- PR target/23404
- * src/powerpc/ffi.c (ffi_prep_args_SYSV): Correct placement of stack
- homed fp args.
- (ffi_status ffi_prep_cif_machdep): Correct stack sizing for same.
-
-2005-08-11 Jakub Jelinek <jakub@redhat.com>
-
- * configure.ac (HAVE_HIDDEN_VISIBILITY_ATTRIBUTE): New test.
- (AH_BOTTOM): Add FFI_HIDDEN definition.
- * configure: Rebuilt.
- * fficonfig.h.in: Rebuilt.
- * src/powerpc/ffi.c (hidden): Remove.
- (ffi_closure_LINUX64, ffi_prep_args64, ffi_call_LINUX64,
- ffi_closure_helper_LINUX64): Use FFI_HIDDEN instead of hidden.
- * src/powerpc/linux64_closure.S (ffi_closure_LINUX64,
- .ffi_closure_LINUX64): Use FFI_HIDDEN instead of .hidden.
- * src/x86/ffi.c (ffi_closure_SYSV, ffi_closure_raw_SYSV): Remove,
- add FFI_HIDDEN to its prototype.
- (ffi_closure_SYSV_inner): New.
- * src/x86/sysv.S (ffi_closure_SYSV, ffi_closure_raw_SYSV): New.
- * src/x86/win32.S (ffi_closure_SYSV, ffi_closure_raw_SYSV): New.
-
-2005-08-10 Alfred M. Szmidt <ams@gnu.org>
-
- PR libffi/21819:
- * configure: Rebuilt.
- * configure.ac: Handle i*86-*-gnu*.
-
-2005-08-09 Jakub Jelinek <jakub@redhat.com>
-
- * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Use
- DW_CFA_offset_extended_sf rather than
- DW_CFA_GNU_negative_offset_extended.
- * src/powerpc/sysv.S (ffi_call_SYSV): Likewise.
-
-2005-07-22 SUGIOKA Toshinobu <sugioka@itonet.co.jp>
-
- * src/sh/sysv.S (ffi_call_SYSV): Stop argument popping correctly
- on sh3.
- (ffi_closure_SYSV): Change the stack layout for sh3 struct argument.
- * src/sh/ffi.c (ffi_prep_args): Fix sh3 argument copy, when it is
- partially on register.
- (ffi_closure_helper_SYSV): Likewise.
- (ffi_prep_cif_machdep): Don't set too many cif->flags.
-
-2005-07-20 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/ffi.c (ffi_call): Handle small structures correctly.
- Remove empty line.
- * src/sh64/ffi.c (simple_type): Remove.
- (return_type): Handle small structures correctly.
- (ffi_prep_args): Likewise.
- (ffi_call): Likewise.
- (ffi_closure_helper_SYSV): Likewise.
- * src/sh64/sysv.S (ffi_call_SYSV): Handle 1, 2 and 4-byte return.
- Emit position independent code if PIC and remove wrong datalabel
- prefixes from EH data.
-
-2005-07-19 Andreas Tobler <a.tobler@schweiz.ch>
-
- * Makefile.am (nodist_libffi_la_SOURCES): Add POWERPC_FREEBSD.
- * Makefile.in: Regenerate.
- * include/Makefile.in: Likewise.
- * testsuite/Makefile.in: Likewise.
- * configure.ac: Add POWERPC_FREEBSD rules.
- * configure: Regenerate.
- * src/powerpc/ffitarget.h: Add POWERPC_FREEBSD rules.
- (FFI_SYSV_TYPE_SMALL_STRUCT): Define.
- * src/powerpc/ffi.c: Add flags to handle small structure returns
- in ffi_call_SYSV.
- (ffi_prep_cif_machdep): Handle small structures for SYSV 4 ABI.
- Aka FFI_SYSV.
- (ffi_closure_helper_SYSV): Likewise.
- * src/powerpc/ppc_closure.S: Add return types for small structures.
- * src/powerpc/sysv.S: Add bits to handle small structures for
- final SYSV 4 ABI.
-
-2005-07-10 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/cls_5_1_byte.c: New test file.
- * testsuite/libffi.call/cls_6_1_byte.c: Likewise.
- * testsuite/libffi.call/cls_7_1_byte.c: Likewise.
-
-2005-07-05 Randolph Chung <tausq@debian.org>
-
- * src/pa/ffi.c (ffi_struct_type): Rename FFI_TYPE_SMALL_STRUCT1
- as FFI_TYPE_SMALL_STRUCT3. Break out handling for 5-7 byte
- structures. Kill compilation warnings.
- (ffi_closure_inner_LINUX): Print return values as hex in debug
- message. Rename FFI_TYPE_SMALL_STRUCT1 as FFI_TYPE_SMALL_STRUCT3.
- Properly handle 5-7 byte structure returns.
- * src/pa/ffitarget.h (FFI_TYPE_SMALL_STRUCT1)
- (FFI_TYPE_SMALL_STRUCT2): Remove.
- (FFI_TYPE_SMALL_STRUCT3, FFI_TYPE_SMALL_STRUCT5)
- (FFI_TYPE_SMALL_STRUCT6, FFI_TYPE_SMALL_STRUCT7): Define.
- * src/pa/linux.S: Mark source file as using PA1.1 assembly.
- (checksmst1, checksmst2): Remove.
- (checksmst3): Optimize handling of 3-byte struct returns.
- (checksmst567): Properly handle 5-7 byte struct returns.
-
-2005-06-15 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- PR libgcj/21943
- * src/mips/n32.S: Enforce PIC code.
- * src/mips/o32.S: Likewise.
-
-2005-06-15 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * configure.ac: Treat i*86-*-solaris2.10 and up as X86_64.
- * configure: Regenerate.
-
-2005-06-01 Alan Modra <amodra@bigpond.net.au>
-
- * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Don't use JUMPTARGET
- to call ffi_closure_helper_SYSV. Append @local instead.
- * src/powerpc/sysv.S (ffi_call_SYSV): Likewise for ffi_prep_args_SYSV.
-
-2005-05-17 Kelley Cook <kcook@gcc.gnu.org>
-
- * configure.ac: Use AC_C_BIGENDIAN instead of AC_C_BIGENDIAN_CROSS.
- Use AC_CHECK_SIZEOF instead of AC_COMPILE_CHECK_SIZEOF.
- * Makefile.am (ACLOCAL_AMFLAGS): Remove -I ../config.
- * aclocal.m4, configure, fficonfig.h.in, Makefile.in,
- include/Makefile.in, testsuite/Makefile.in: Regenerate.
-
-2005-05-09 Mike Stump <mrs@apple.com>
-
- * configure: Regenerate.
-
-2005-05-08 Richard Henderson <rth@redhat.com>
-
- PR libffi/21285
- * src/alpha/osf.S: Update unwind into to match code.
-
-2005-05-04 Andreas Degert <ad@papyrus-gmbh.de>
- Richard Henderson <rth@redhat.com>
-
- * src/x86/ffi64.c (ffi_prep_cif_machdep): Save sse-used flag in
- bit 11 of flags.
- (ffi_call): Mask return type field. Pass ssecount to ffi_call_unix64.
- (ffi_prep_closure): Set carry bit if sse-used flag set.
- * src/x86/unix64.S (ffi_call_unix64): Add ssecount argument.
- Only load sse registers if ssecount non-zero.
- (ffi_closure_unix64): Only save sse registers if carry set on entry.
-
-2005-04-29 Ralf Corsepius <ralf.corsepius@rtems.org>
-
- * configure.ac: Add i*86-*-rtems*, sparc*-*-rtems*,
- powerpc-*rtems*, arm*-*-rtems*, sh-*-rtems*.
- * configure: Regenerate.
-
-2005-04-20 Hans-Peter Nilsson <hp@axis.com>
-
- * testsuite/lib/libffi-dg.exp (libffi-dg-test-1): In regsub use,
- have Tcl8.3-compatible intermediate variable.
-
-2005-04-18 Simon Posnjak <simon.posnjak@siol.net>
- Hans-Peter Nilsson <hp@axis.com>
-
- * Makefile.am: Add CRIS support.
- * configure.ac: Likewise.
- * Makefile.in, configure, testsuite/Makefile.in,
- include/Makefile.in: Regenerate.
- * src/cris: New directory.
- * src/cris/ffi.c, src/cris/sysv.S, src/cris/ffitarget.h: New files.
- * src/prep_cif.c (ffi_prep_cif): Wrap in #ifndef __CRIS__.
-
- * testsuite/lib/libffi-dg.exp (libffi-dg-test-1): Replace \n with
- \r?\n in output tests.
-
-2005-04-12 Mike Stump <mrs@apple.com>
-
- * configure: Regenerate.
-
-2005-03-30 Hans Boehm <Hans.Boehm@hp.com>
-
- * src/ia64/ffitarget.h (ffi_arg): Use long long instead of DI.
-
-2005-03-30 Steve Ellcey <sje@cup.hp.com>
-
- * src/ia64/ffitarget.h (ffi_arg) ADD DI attribute.
- (ffi_sarg) Ditto.
- * src/ia64/unix.S (ffi_closure_unix): Extend gp
- to 64 bits in ILP32 mode.
- Load 64 bits even for short data.
-
-2005-03-23 Mike Stump <mrs@apple.com>
-
- * src/powerpc/darwin.S: Update for -m64 multilib.
- * src/powerpc/darwin_closure.S: Likewise.
-
-2005-03-21 Zack Weinberg <zack@codesourcery.com>
-
- * configure.ac: Do not invoke TL_AC_GCC_VERSION.
- Do not set tool_include_dir.
- * aclocal.m4, configure, Makefile.in, testsuite/Makefile.in:
- Regenerate.
- * include/Makefile.am: Set gcc_version and toollibffidir.
- * include/Makefile.in: Regenerate.
-
-2005-02-22 Andrew Haley <aph@redhat.com>
-
- * src/powerpc/ffi.c (ffi_prep_cif_machdep): Bump alignment to
- odd-numbered register pairs for 64-bit integer types.
-
-2005-02-23 Andreas Tobler <a.tobler@schweiz.ch>
-
- PR libffi/20104
- * testsuite/libffi.call/return_ll1.c: New test case.
-
-2005-02-11 Janis Johnson <janis187@us.ibm.com>
-
- * testsuite/libffi.call/cls_align_longdouble.c: Remove dg-options.
- * testsuite/libffi.call/float.c: Ditto.
- * testsuite/libffi.call/float2.c: Ditto.
- * testsuite/libffi.call/float3.c: Ditto.
-
-2005-02-08 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/frv/ffitarget.h: Remove PPC stuff which does not belong to frv.
-
-2005-01-12 Eric Botcazou <ebotcazou@libertysurf.fr>
-
- * testsuite/libffi.special/special.exp (cxx_options): Add
- -shared-libgcc.
-
-2004-12-31 Richard Henderson <rth@redhat.com>
-
- * src/types.c (FFI_AGGREGATE_TYPEDEF): Remove.
- (FFI_TYPEDEF): Rename from FFI_INTEGRAL_TYPEDEF. Replace size and
- offset parameters with a type parameter; deduce size and structure
- alignment. Update all users.
-
-2004-12-31 Richard Henderson <rth@redhat.com>
-
- * src/types.c (FFI_TYPE_POINTER): Define with sizeof.
- (FFI_TYPE_LONGDOUBLE): Fix for ia64.
- * src/ia64/ffitarget.h (struct ffi_ia64_trampoline_struct): Move
- into ffi_prep_closure.
- * src/ia64/ia64_flags.h, src/ia64/ffi.c, src/ia64/unix.S: Rewrite
- from scratch.
-
-2004-12-27 Richard Henderson <rth@redhat.com>
-
- * src/x86/unix64.S: Fix typo in unwind info.
-
-2004-12-25 Richard Henderson <rth@redhat.com>
-
- * src/x86/ffi64.c (struct register_args): Rename from stackLayout.
- (enum x86_64_reg_class): Add X86_64_COMPLEX_X87_CLASS.
- (merge_classes): Check for it.
- (SSE_CLASS_P): New.
- (classify_argument): Pass byte_offset by value; perform all updates
- inside struct case.
- (examine_argument): Add classes argument; handle
- X86_64_COMPLEX_X87_CLASS.
- (ffi_prep_args): Merge into ...
- (ffi_call): ... here. Share stack frame with ffi_call_unix64.
- (ffi_prep_cif_machdep): Setup cif->flags for proper structure return.
- (ffi_fill_return_value): Remove.
- (ffi_prep_closure): Remove dead assert.
- (ffi_closure_unix64_inner): Rename from ffi_closure_UNIX64_inner.
- Rewrite to use struct register_args instead of va_list. Create
- flags for handling structure returns.
- * src/x86/unix64.S: Remove dead strings.
- (ffi_call_unix64): Rename from ffi_call_UNIX64. Rewrite to share
- stack frame with ffi_call. Handle structure returns properly.
- (float2sse, floatfloat2sse, double2sse): Remove.
- (sse2float, sse2double, sse2floatfloat): Remove.
- (ffi_closure_unix64): Rename from ffi_closure_UNIX64. Rewrite
- to handle structure returns properly.
-
-2004-12-08 David Edelsohn <edelsohn@gnu.org>
-
- * Makefile.am (AM_MAKEFLAGS): Remove duplicate LIBCFLAGS and
- PICFLAG.
- * Makefile.in: Regenerated.
-
-2004-12-02 Richard Sandiford <rsandifo@redhat.com>
-
- * configure.ac: Use TL_AC_GCC_VERSION to set gcc_version.
- * configure, aclocal.m4, Makefile.in: Regenerate.
- * include/Makefile.in, testsuite/Makefile.in: Regenerate.
-
-2004-11-29 Kelley Cook <kcook@gcc.gnu.org>
-
- * configure: Regenerate for libtool change.
-
-2004-11-25 Kelley Cook <kcook@gcc.gnu.org>
-
- * configure: Regenerate for libtool reversion.
-
-2004-11-24 Kelley Cook <kcook@gcc.gnu.org>
-
- * configure: Regenerate for libtool change.
-
-2004-11-23 John David Anglin <dave.anglin@nrc-cnrc.gc.ca>
-
- * testsuite/lib/libffi-dg.exp: Use new procs in target-libpath.exp.
-
-2004-11-23 Richard Sandiford <rsandifo@redhat.com>
-
- * src/mips/o32.S (ffi_call_O32, ffi_closure_O32): Use jalr instead
- of jal. Use an absolute encoding for the frame information.
-
-2004-11-23 Kelley Cook <kcook@gcc.gnu.org>
-
- * Makefile.am: Remove no-dependencies. Add ACLOCAL_AMFLAGS.
- * acinclude.m4: Delete logic for sincludes.
- * aclocal.m4, Makefile.in, configure: Regenerate.
- * include/Makefile: Likewise.
- * testsuite/Makefile: Likewise.
-
-2004-11-22 Eric Botcazou <ebotcazou@libertysurf.fr>
-
- * src/sparc/ffi.c (ffi_prep_closure): Align doubles and 64-bit integers
- on a 8-byte boundary.
- * src/sparc/v8.S (ffi_closure_v8): Reserve frame space for arguments.
-
-2004-10-27 Richard Earnshaw <rearnsha@arm.com>
-
- * src/arm/ffi.c (ffi_prep_cif_machdep): Handle functions that return
- long long values. Round stack allocation to a multiple of 8 bytes
- for ATPCS compatibility.
- * src/arm/sysv.S (ffi_call_SYSV): Rework to avoid use of APCS register
- names. Handle returning long long types. Add Thumb and interworking
- support. Improve soft-float code.
-
-2004-10-27 Richard Earnshaw <rearnsha@arm.com>
-
- * testsuite/lib/libffi-db.exp (load_gcc_lib): New function.
- (libffi_exit): New function.
- (libffi_init): Build the testglue wrapper if needed.
-
-2004-10-25 Eric Botcazou <ebotcazou@libertysurf.fr>
-
- PR other/18138
- * testsuite/lib/libffi-dg.exp: Accept more than one multilib libgcc.
-
-2004-10-25 Kazuhiro Inaoka <inaoka.kazuhiro@renesas.com>
-
- * src/m32r/libffitarget.h (FFI_CLOSURES): Set to 0.
-
-2004-10-20 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/sysv.S (ffi_call_SYSV): Don't align for double data.
- * testsuite/libffi.call/float3.c: New test case.
-
-2004-10-18 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/ffi.c (ffi_prep_closure): Set T bit in trampoline for
- the function returning a structure pointed with R2.
- * src/sh/sysv.S (ffi_closure_SYSV): Use R2 as the pointer to
- the structure return value if T bit set. Emit position
- independent code and EH data if PIC.
-
-2004-10-13 Kazuhiro Inaoka <inaoka.kazuhiro@renesas.com>
-
- * Makefile.am: Add m32r support.
- * configure.ac: Likewise.
- * Makefile.in: Regenerate.
- * confiugre: Regenerate.
- * src/types.c: Add m32r port to FFI_INTERNAL_TYPEDEF
- (uint64, sint64, double, longdouble)
- * src/m32r: New directory.
- * src/m32r/ffi.c: New file.
- * src/m32r/sysv.S: Likewise.
- * src/m32r/ffitarget.h: Likewise.
-
-2004-10-02 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * testsuite/libffi.call/negint.c: New test case.
-
-2004-09-14 H.J. Lu <hongjiu.lu@intel.com>
-
- PR libgcj/17465
- * testsuite/lib/libffi-dg.exp: Don't use global ld_library_path.
- Set up LD_LIBRARY_PATH, SHLIB_PATH, LD_LIBRARYN32_PATH,
- LD_LIBRARY64_PATH, LD_LIBRARY_PATH_32, LD_LIBRARY_PATH_64 and
- DYLD_LIBRARY_PATH.
-
-2004-09-05 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/many_win32.c: Remove whitespaces.
- * testsuite/libffi.call/promotion.c: Likewise.
- * testsuite/libffi.call/return_ll.c: Remove unused var. Cleanup
- whitespaces.
- * testsuite/libffi.call/return_sc.c: Likewise.
- * testsuite/libffi.call/return_uc.c: Likewise.
-
-2004-09-05 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/powerpc/darwin.S: Fix comments and identation.
- * src/powerpc/darwin_closure.S: Likewise.
-
-2004-09-02 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/powerpc/ffi_darwin.c: Add flag for longdouble return values.
- (ffi_prep_args): Handle longdouble arguments.
- (ffi_prep_cif_machdep): Set flags for longdouble. Calculate space for
- longdouble.
- (ffi_closure_helper_DARWIN): Add closure handling for longdouble.
- * src/powerpc/darwin.S (_ffi_call_DARWIN): Add handling of longdouble
- values.
- * src/powerpc/darwin_closure.S (_ffi_closure_ASM): Likewise.
- * src/types.c: Defined longdouble size and alignment for darwin.
-
-2004-09-02 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/powerpc/aix.S: Remove whitespaces.
- * src/powerpc/aix_closure.S: Likewise.
- * src/powerpc/asm.h: Likewise.
- * src/powerpc/ffi.c: Likewise.
- * src/powerpc/ffitarget.h: Likewise.
- * src/powerpc/linux64.S: Likewise.
- * src/powerpc/linux64_closure.S: Likewise.
- * src/powerpc/ppc_closure.S: Likewise.
- * src/powerpc/sysv.S: Likewise.
-
-2004-08-30 Anthony Green <green@redhat.com>
-
- * Makefile.am: Add frv support.
- * Makefile.in, testsuite/Makefile.in: Rebuilt.
- * configure.ac: Read configure.host.
- * configure.in: Read configure.host.
- * configure.host: New file. frv-elf needs libgloss.
- * include/ffi.h.in: Force ffi_closure to have a nice big (8)
- alignment. This is needed to frv and shouldn't harm the others.
- * include/ffi_common.h (ALIGN_DOWN): New macro.
- * src/frv/ffi.c, src/frv/ffitarget.h, src/frv/eabi.S: New files.
-
-2004-08-24 David Daney <daney@avtrex.com>
-
- * testsuite/libffi.call/closure_fn0.c: Xfail mips64* instead of mips*.
- * testsuite/libffi.call/closure_fn1.c: Likewise.
- * testsuite/libffi.call/closure_fn2.c Likewise.
- * testsuite/libffi.call/closure_fn3.c: Likewise.
- * testsuite/libffi.call/closure_fn4.c: Likewise.
- * testsuite/libffi.call/closure_fn5.c: Likewise.
- * testsuite/libffi.call/cls_18byte.c: Likewise.
- * testsuite/libffi.call/cls_19byte.c: Likewise.
- * testsuite/libffi.call/cls_1_1byte.c: Likewise.
- * testsuite/libffi.call/cls_20byte.c: Likewise.
- * testsuite/libffi.call/cls_20byte1.c: Likewise.
- * testsuite/libffi.call/cls_24byte.c: Likewise.
- * testsuite/libffi.call/cls_2byte.c: Likewise.
- * testsuite/libffi.call/cls_3_1byte.c: Likewise.
- * testsuite/libffi.call/cls_3byte1.c: Likewise.
- * testsuite/libffi.call/cls_3byte2.c: Likewise.
- * testsuite/libffi.call/cls_4_1byte.c: Likewise.
- * testsuite/libffi.call/cls_4byte.c: Likewise.
- * testsuite/libffi.call/cls_64byte.c: Likewise.
- * testsuite/libffi.call/cls_6byte.c: Likewise.
- * testsuite/libffi.call/cls_7byte.c: Likewise.
- * testsuite/libffi.call/cls_8byte.c: Likewise.
- * testsuite/libffi.call/cls_9byte1.c: Likewise.
- * testsuite/libffi.call/cls_9byte2.c: Likewise.
- * testsuite/libffi.call/cls_align_double.c: Likewise.
- * testsuite/libffi.call/cls_align_float.c: Likewise.
- * testsuite/libffi.call/cls_align_longdouble.c: Likewise.
- * testsuite/libffi.call/cls_align_pointer.c: Likewise.
- * testsuite/libffi.call/cls_align_sint16.c: Likewise.
- * testsuite/libffi.call/cls_align_sint32.c: Likewise.
- * testsuite/libffi.call/cls_align_sint64.c: Likewise.
- * testsuite/libffi.call/cls_align_uint16.c: Likewise.
- * testsuite/libffi.call/cls_align_uint32.c: Likewise.
- * testsuite/libffi.call/cls_align_uint64.c: Likewise.
- * testsuite/libffi.call/cls_double.c: Likewise.
- * testsuite/libffi.call/cls_float.c: Likewise.
- * testsuite/libffi.call/cls_multi_schar.c: Likewise.
- * testsuite/libffi.call/cls_multi_sshort.c: Likewise.
- * testsuite/libffi.call/cls_multi_sshortchar.c: Likewise.
- * testsuite/libffi.call/cls_multi_uchar.c: Likewise.
- * testsuite/libffi.call/cls_multi_ushort.c: Likewise.
- * testsuite/libffi.call/cls_multi_ushortchar.c: Likewise.
- * testsuite/libffi.call/cls_schar.c: Likewise.
- * testsuite/libffi.call/cls_sint.c: Likewise.
- * testsuite/libffi.call/cls_sshort.c: Likewise.
- * testsuite/libffi.call/cls_uchar.c: Likewise.
- * testsuite/libffi.call/cls_uint.c: Likewise.
- * testsuite/libffi.call/cls_ulonglong.c: Likewise.
- * testsuite/libffi.call/cls_ushort.c: Likewise.
- * testsuite/libffi.call/nested_struct.c: Likewise.
- * testsuite/libffi.call/nested_struct1.c: Likewise.
- * testsuite/libffi.call/nested_struct2.c: Likewise.
- * testsuite/libffi.call/nested_struct3.c: Likewise.
- * testsuite/libffi.call/problem1.c: Likewise.
- * testsuite/libffi.special/unwindtest.cc: Likewise.
- * testsuite/libffi.call/cls_12byte.c: Likewise and set return value
- to zero.
- * testsuite/libffi.call/cls_16byte.c: Likewise.
- * testsuite/libffi.call/cls_5byte.c: Likewise.
-
-2004-08-23 David Daney <daney@avtrex.com>
-
- PR libgcj/13141
- * src/mips/ffitarget.h (FFI_O32_SOFT_FLOAT): New ABI.
- * src/mips/ffi.c (ffi_prep_args): Fix alignment calculation.
- (ffi_prep_cif_machdep): Handle FFI_O32_SOFT_FLOAT floating point
- parameters and return types.
- (ffi_call): Handle FFI_O32_SOFT_FLOAT ABI.
- (ffi_prep_closure): Ditto.
- (ffi_closure_mips_inner_O32): Handle FFI_O32_SOFT_FLOAT ABI, fix
- alignment calculations.
- * src/mips/o32.S (ffi_closure_O32): Don't use floating point
- instructions if FFI_O32_SOFT_FLOAT, make stack frame ABI compliant.
-
-2004-08-14 Casey Marshall <csm@gnu.org>
-
- * src/mips/ffi.c (ffi_pref_cif_machdep): set `cif->flags' to
- contain `FFI_TYPE_UINT64' as return type for any 64-bit
- integer (O32 ABI only).
- (ffi_prep_closure): new function.
- (ffi_closure_mips_inner_O32): new function.
- * src/mips/ffitarget.h: Define `FFI_CLOSURES' and
- `FFI_TRAMPOLINE_SIZE' appropriately if the ABI is o32.
- * src/mips/o32.S (ffi_call_O32): add labels for .eh_frame. Return
- 64 bit integers correctly.
- (ffi_closure_O32): new function.
- Added DWARF-2 unwind info for both functions.
-
-2004-08-10 Andrew Haley <aph@redhat.com>
-
- * src/x86/ffi64.c (ffi_prep_args ): 8-align all stack arguments.
-
-2004-08-01 Robert Millan <robertmh@gnu.org>
-
- * configure.ac: Detect knetbsd-gnu and kfreebsd-gnu.
- * configure: Regenerate.
-
-2004-07-30 Maciej W. Rozycki <macro@linux-mips.org>
-
- * acinclude.m4 (AC_FUNC_MMAP_BLACKLIST): Check for <sys/mman.h>
- and mmap() explicitly instead of relying on preset autoconf cache
- variables.
- * aclocal.m4: Regenerate.
- * configure: Regenerate.
-
-2004-07-11 Ulrich Weigand <uweigand@de.ibm.com>
-
- * src/s390/ffi.c (ffi_prep_args): Fix C aliasing violation.
- (ffi_check_float_struct): Remove unused prototype.
-
-2004-06-30 Geoffrey Keating <geoffk@apple.com>
-
- * src/powerpc/ffi_darwin.c (flush_icache): ';' is a comment
- character on Darwin, use '\n\t' instead.
-
-2004-06-26 Matthias Klose <doko@debian.org>
-
- * libtool-version: Fix typo in revision/age.
-
-2004-06-17 Matthias Klose <doko@debian.org>
-
- * libtool-version: New.
- * Makefile.am (libffi_la_LDFLAGS): Use -version-info for soname.
- * Makefile.in: Regenerate.
-
-2004-06-15 Paolo Bonzini <bonzini@gnu.org>
-
- * Makefile.am: Remove useless multilib rules.
- * Makefile.in: Regenerate.
- * aclocal.m4: Regenerate with automake 1.8.5.
- * configure.ac: Remove useless multilib configury.
- * configure: Regenerate.
-
-2004-06-15 Paolo Bonzini <bonzini@gnu.org>
-
- * .cvsignore: New file.
-
-2004-06-10 Jakub Jelinek <jakub@redhat.com>
-
- * src/ia64/unix.S (ffi_call_unix): Insert group barrier break
- fp_done.
- (ffi_closure_UNIX): Fix f14/f15 adjustment if FLOAT_SZ is ever
- changed from 8.
-
-2004-06-06 Sean McNeil <sean@mcneil.com>
-
- * configure.ac: Add x86_64-*-freebsd* support.
- * configure: Regenerate.
-
-2004-04-26 Joe Buck <jbuck@welsh-buck.org>
-
- Bug 15093
- * configure.ac: Test for existence of mmap and sys/mman.h before
- checking blacklist. Fix suggested by Jim Wilson.
- * configure: Regenerate.
-
-2004-04-26 Matt Austern <austern@apple.com>
-
- * src/powerpc/darwin.S: Go through a non-lazy pointer for initial
- FDE location.
- * src/powerpc/darwin_closure.S: Likewise.
-
-2004-04-24 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/cls_multi_schar.c (main): Fix initialization
- error. Reported by Thomas Heller <theller@python.net>.
- * testsuite/libffi.call/cls_multi_sshort.c (main): Likewise.
- * testsuite/libffi.call/cls_multi_ushort.c (main): Likewise.
-
-2004-03-20 Matthias Klose <doko@debian.org>
-
- * src/pa/linux.S: Fix typo.
-
-2004-03-19 Matthias Klose <doko@debian.org>
-
- * Makefile.am: Update.
- * Makefile.in: Regenerate.
- * src/pa/ffi.h.in: Remove.
- * src/pa/ffitarget.h: New file.
-
-2004-02-10 Randolph Chung <tausq@debian.org>
-
- * Makefile.am: Add PA support.
- * Makefile.in: Regenerate.
- * include/Makefile.in: Regenerate.
- * configure.ac: Add PA target.
- * configure: Regenerate.
- * src/pa/ffi.c: New file.
- * src/pa/ffi.h.in: Add PA support.
- * src/pa/linux.S: New file.
- * prep_cif.c: Add PA support.
-
-2004-03-16 Hosaka Yuji <hos@tamanegi.org>
-
- * src/types.c: Fix alignment size of X86_WIN32 case int64 and
- double.
- * src/x86/ffi.c (ffi_prep_args): Replace ecif->cif->rtype->type
- with ecif->cif->flags.
- (ffi_call, ffi_prep_incoming_args_SYSV): Replace cif->rtype->type
- with cif->flags.
- (ffi_prep_cif_machdep): Add X86_WIN32 struct case.
- (ffi_closure_SYSV): Add 1 or 2-bytes struct case for X86_WIN32.
- * src/x86/win32.S (retstruct1b, retstruct2b, sc_retstruct1b,
- sc_retstruct2b): Add for 1 or 2-bytes struct case.
-
-2004-03-15 Kelley Cook <kcook@gcc.gnu.org>
-
- * configure.in: Rename file to ...
- * configure.ac: ... this.
- * fficonfig.h.in: Regenerate.
- * Makefile.in: Regenerate.
- * include/Makefile.in: Regenerate.
- * testsuite/Makefile.in: Regenerate.
-
-2004-03-12 Matt Austern <austern@apple.com>
-
- * src/powerpc/darwin.S: Fix EH information so it corresponds to
- changes in EH format resulting from addition of linkonce support.
- * src/powerpc/darwin_closure.S: Likewise.
-
-2004-03-11 Andreas Tobler <a.tobler@schweiz.ch>
- Paolo Bonzini <bonzini@gnu.org>
-
- * Makefile.am (AUTOMAKE_OPTIONS): Set them.
- Remove VPATH. Remove rules for object files. Remove multilib support.
- (AM_CCASFLAGS): Add.
- * configure.in (AC_CONFIG_HEADERS): Relace AM_CONFIG_HEADER.
- (AC_PREREQ): Bump version to 2.59.
- (AC_INIT): Fill with version info and bug address.
- (ORIGINAL_LD_FOR_MULTILIBS): Remove.
- (AM_ENABLE_MULTILIB): Use this instead of AC_ARG_ENABLE.
- De-precious CC so that the right flags are passed down to multilibs.
- (AC_MSG_ERROR): Replace obsolete macro AC_ERROR.
- (AC_CONFIG_FILES): Replace obsolete macro AC_LINK_FILES.
- (AC_OUTPUT): Reorganize the output with AC_CONFIG_COMMANDS.
- * configure: Rebuilt.
- * aclocal.m4: Likewise.
- * Makefile.in, include/Makefile.in, testsuite/Makefile.in: Likewise.
- * fficonfig.h.in: Likewise.
-
-2004-03-11 Andreas Schwab <schwab@suse.de>
-
- * src/ia64/ffi.c (ffi_prep_incoming_args_UNIX): Get floating point
- arguments from fp registers only for the first 8 parameter slots.
- Don't convert a float parameter when passed in memory.
-
-2004-03-09 Hans-Peter Nilsson <hp@axis.com>
-
- * configure: Regenerate for config/accross.m4 correction.
-
-2004-02-25 Matt Kraai <kraai@alumni.cmu.edu>
-
- * src/powerpc/ffi.c (ffi_prep_args_SYSV): Change
- ecif->cif->bytes to bytes.
- (ffi_prep_cif_machdep): Add braces around nested if statement.
-
-2004-02-09 Alan Modra <amodra@bigpond.net.au>
-
- * src/types.c (pointer): POWERPC64 has 8 byte pointers.
-
- * src/powerpc/ffi.c (ffi_prep_args64): Correct long double handling.
- (ffi_closure_helper_LINUX64): Fix typo.
- * testsuite/libffi.call/cls_align_longdouble.c: Pass -mlong-double-128
- for powerpc64-*-*.
- * testsuite/libffi.call/float.c: Likewise.
- * testsuite/libffi.call/float2.c: Likewise.
-
-2004-02-08 Alan Modra <amodra@bigpond.net.au>
-
- * src/powerpc/ffi.c (ffi_prep_cif_machdep <FFI_LINUX64>): Correct
- long double function return and long double arg handling.
- (ffi_closure_helper_LINUX64): Formatting. Delete unused "ng" var.
- Use "end_pfr" instead of "nf". Correct long double handling.
- Localise "temp".
- * src/powerpc/linux64.S (ffi_call_LINUX64): Save f2 long double
- return value.
- * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Allocate
- space for long double return value. Adjust stack frame and offsets.
- Load f2 long double return.
-
-2004-02-07 Alan Modra <amodra@bigpond.net.au>
-
- * src/types.c: Use 16 byte long double for POWERPC64.
-
-2004-01-25 Eric Botcazou <ebotcazou@libertysurf.fr>
-
- * src/sparc/ffi.c (ffi_prep_args_v9): Shift the parameter array
- when the structure return address is passed in %o0.
- (ffi_V9_return_struct): Rename into ffi_v9_layout_struct.
- (ffi_v9_layout_struct): Align the field following a nested structure
- on a word boundary. Use memmove instead of memcpy.
- (ffi_call): Update call to ffi_V9_return_struct.
- (ffi_prep_closure): Define 'ctx' only for V8.
- (ffi_closure_sparc_inner): Clone into ffi_closure_sparc_inner_v8
- and ffi_closure_sparc_inner_v9.
- (ffi_closure_sparc_inner_v8): Return long doubles by reference.
- Always skip the structure return address. For structures and long
- doubles, copy the argument directly.
- (ffi_closure_sparc_inner_v9): Skip the structure return address only
- if required. Shift the maximum floating-point slot accordingly. For
- big structures, copy the argument directly; otherwise, left-justify the
- argument and call ffi_v9_layout_struct to lay out the structure on
- the stack.
- * src/sparc/v8.S: Undef STACKFRAME before defining it.
- (ffi_closure_v8): Pass the structure return address. Update call to
- ffi_closure_sparc_inner_v8. Short-circuit FFI_TYPE_INT handling.
- Skip the 'unimp' insn when returning long doubles and structures.
- * src/sparc/v9.S: Undef STACKFRAME before defining it.
- (ffi_closure_v9): Increase the frame size by 2 words. Short-circuit
- FFI_TYPE_INT handling. Load structures both in integers and
- floating-point registers on return.
- * README: Update status of the SPARC port.
-
-2004-01-24 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/pyobjc-tc.c (main): Treat result value
- as of type ffi_arg.
- * testsuite/libffi.call/struct3.c (main): Fix CHECK.
-
-2004-01-22 Ulrich Weigand <uweigand@de.ibm.com>
-
- * testsuite/libffi.call/cls_uint.c (cls_ret_uint_fn): Treat result
- value as of type ffi_arg, not unsigned int.
-
-2004-01-21 Michael Ritzert <ritzert@t-online.de>
-
- * ffi64.c (ffi_prep_args): Cast the RHS of an assignment instead
- of the LHS.
-
-2004-01-12 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/lib/libffi-dg.exp: Set LD_LIBRARY_PATH_32 for
- Solaris.
-
-2004-01-08 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * testsuite/libffi.call/ffitest.h (allocate_mmap): Cast MAP_FAILED
- to void *.
-
-2003-12-10 Richard Henderson <rth@redhat.com>
-
- * testsuite/libffi.call/cls_align_pointer.c: Cast pointers to
- size_t instead of int.
-
-2003-12-04 Hosaka Yuji <hos@tamanegi.org>
-
- * testsuite/libffi.call/many_win32.c: Include <float.h>.
- * testsuite/libffi.call/many_win32.c (main): Replace variable
- int i with unsigned long ul.
-
- * testsuite/libffi.call/cls_align_uint64.c: New test case.
- * testsuite/libffi.call/cls_align_sint64.c: Likewise.
- * testsuite/libffi.call/cls_align_uint32.c: Likewise.
- * testsuite/libffi.call/cls_align_sint32.c: Likewise.
- * testsuite/libffi.call/cls_align_uint16.c: Likewise.
- * testsuite/libffi.call/cls_align_sint16.c: Likewise.
- * testsuite/libffi.call/cls_align_float.c: Likewise.
- * testsuite/libffi.call/cls_align_double.c: Likewise.
- * testsuite/libffi.call/cls_align_longdouble.c: Likewise.
- * testsuite/libffi.call/cls_align_pointer.c: Likewise.
-
-2003-12-02 Hosaka Yuji <hos@tamanegi.org>
-
- PR other/13221
- * src/x86/ffi.c (ffi_prep_args, ffi_prep_incoming_args_SYSV):
- Align arguments to 32 bits.
-
-2003-12-01 Andreas Tobler <a.tobler@schweiz.ch>
-
- PR other/13221
- * testsuite/libffi.call/cls_multi_sshort.c: New test case.
- * testsuite/libffi.call/cls_multi_sshortchar.c: Likewise.
- * testsuite/libffi.call/cls_multi_uchar.c: Likewise.
- * testsuite/libffi.call/cls_multi_schar.c: Likewise.
- * testsuite/libffi.call/cls_multi_ushortchar.c: Likewise.
- * testsuite/libffi.call/cls_multi_ushort.c: Likewise.
-
- * testsuite/libffi.special/unwindtest.cc: Cosmetics.
-
-2003-11-26 Kaveh R. Ghazi <ghazi@caip.rutgers.edu>
-
- * testsuite/libffi.call/ffitest.h: Include <fcntl.h>.
- * testsuite/libffi.special/ffitestcxx.h: Likewise.
-
-2003-11-22 Andreas Tobler <a.tobler@schweiz.ch>
-
- * Makefile.in: Rebuilt.
- * configure: Likewise.
- * testsuite/libffi.special/unwindtest.cc: Convert the mmap to
- the right type.
-
-2003-11-21 Andreas Jaeger <aj@suse.de>
- Andreas Tobler <a.tobler@schweiz.ch>
-
- * acinclude.m4: Add AC_FUNC_MMAP_BLACKLIST.
- * configure.in: Call AC_FUNC_MMAP_BLACKLIST.
- * Makefile.in: Rebuilt.
- * aclocal.m4: Likewise.
- * configure: Likewise.
- * fficonfig.h.in: Likewise.
- * testsuite/lib/libffi-dg.exp: Add include dir.
- * testsuite/libffi.call/ffitest.h: Add MMAP definitions.
- * testsuite/libffi.special/ffitestcxx.h: Likewise.
- * testsuite/libffi.call/closure_fn0.c: Use MMAP functionality
- for ffi_closure if available.
- * testsuite/libffi.call/closure_fn1.c: Likewise.
- * testsuite/libffi.call/closure_fn2.c: Likewise.
- * testsuite/libffi.call/closure_fn3.c: Likewise.
- * testsuite/libffi.call/closure_fn4.c: Likewise.
- * testsuite/libffi.call/closure_fn5.c: Likewise.
- * testsuite/libffi.call/cls_12byte.c: Likewise.
- * testsuite/libffi.call/cls_16byte.c: Likewise.
- * testsuite/libffi.call/cls_18byte.c: Likewise.
- * testsuite/libffi.call/cls_19byte.c: Likewise.
- * testsuite/libffi.call/cls_1_1byte.c: Likewise.
- * testsuite/libffi.call/cls_20byte.c: Likewise.
- * testsuite/libffi.call/cls_20byte1.c: Likewise.
- * testsuite/libffi.call/cls_24byte.c: Likewise.
- * testsuite/libffi.call/cls_2byte.c: Likewise.
- * testsuite/libffi.call/cls_3_1byte.c: Likewise.
- * testsuite/libffi.call/cls_3byte1.c: Likewise.
- * testsuite/libffi.call/cls_3byte2.c: Likewise.
- * testsuite/libffi.call/cls_4_1byte.c: Likewise.
- * testsuite/libffi.call/cls_4byte.c: Likewise.
- * testsuite/libffi.call/cls_5byte.c: Likewise.
- * testsuite/libffi.call/cls_64byte.c: Likewise.
- * testsuite/libffi.call/cls_6byte.c: Likewise.
- * testsuite/libffi.call/cls_7byte.c: Likewise.
- * testsuite/libffi.call/cls_8byte.c: Likewise.
- * testsuite/libffi.call/cls_9byte1.c: Likewise.
- * testsuite/libffi.call/cls_9byte2.c: Likewise.
- * testsuite/libffi.call/cls_double.c: Likewise.
- * testsuite/libffi.call/cls_float.c: Likewise.
- * testsuite/libffi.call/cls_schar.c: Likewise.
- * testsuite/libffi.call/cls_sint.c: Likewise.
- * testsuite/libffi.call/cls_sshort.c: Likewise.
- * testsuite/libffi.call/cls_uchar.c: Likewise.
- * testsuite/libffi.call/cls_uint.c: Likewise.
- * testsuite/libffi.call/cls_ulonglong.c: Likewise.
- * testsuite/libffi.call/cls_ushort.c: Likewise.
- * testsuite/libffi.call/nested_struct.c: Likewise.
- * testsuite/libffi.call/nested_struct1.c: Likewise.
- * testsuite/libffi.call/nested_struct2.c: Likewise.
- * testsuite/libffi.call/nested_struct3.c: Likewise.
- * testsuite/libffi.call/problem1.c: Likewise.
- * testsuite/libffi.special/unwindtest.cc: Likewise.
-
-2003-11-20 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/lib/libffi-dg.exp: Make the -lgcc_s conditional.
-
-2003-11-19 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/lib/libffi-dg.exp: Add DYLD_LIBRARY_PATH for darwin.
- Add -lgcc_s to additional flags.
-
-2003-11-12 Andreas Tobler <a.tobler@schweiz.ch>
-
- * configure.in, include/Makefile.am: PR libgcj/11147, install
- the ffitarget.h header file in a gcc versioned and target
- dependent place.
- * configure: Regenerated.
- * Makefile.in, include/Makefile.in: Likewise.
- * testsuite/Makefile.in: Likewise.
-
-2003-11-09 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/closure_fn0.c: Print result and check
- with dg-output to make debugging easier.
- * testsuite/libffi.call/closure_fn1.c: Likewise.
- * testsuite/libffi.call/closure_fn2.c: Likewise.
- * testsuite/libffi.call/closure_fn3.c: Likewise.
- * testsuite/libffi.call/closure_fn4.c: Likewise.
- * testsuite/libffi.call/closure_fn5.c: Likewise.
- * testsuite/libffi.call/cls_12byte.c: Likewise.
- * testsuite/libffi.call/cls_16byte.c: Likewise.
- * testsuite/libffi.call/cls_18byte.c: Likewise.
- * testsuite/libffi.call/cls_19byte.c: Likewise.
- * testsuite/libffi.call/cls_1_1byte.c: Likewise.
- * testsuite/libffi.call/cls_20byte.c: Likewise.
- * testsuite/libffi.call/cls_20byte1.c: Likewise.
- * testsuite/libffi.call/cls_24byte.c: Likewise.
- * testsuite/libffi.call/cls_2byte.c: Likewise.
- * testsuite/libffi.call/cls_3_1byte.c: Likewise.
- * testsuite/libffi.call/cls_3byte1.c: Likewise.
- * testsuite/libffi.call/cls_3byte2.c: Likewise.
- * testsuite/libffi.call/cls_4_1byte.c: Likewise.
- * testsuite/libffi.call/cls_4byte.c: Likewise.
- * testsuite/libffi.call/cls_5byte.c: Likewise.
- * testsuite/libffi.call/cls_64byte.c: Likewise.
- * testsuite/libffi.call/cls_6byte.c: Likewise.
- * testsuite/libffi.call/cls_7byte.c: Likewise.
- * testsuite/libffi.call/cls_8byte.c: Likewise.
- * testsuite/libffi.call/cls_9byte1.c: Likewise.
- * testsuite/libffi.call/cls_9byte2.c: Likewise.
- * testsuite/libffi.call/cls_double.c: Likewise.
- * testsuite/libffi.call/cls_float.c: Likewise.
- * testsuite/libffi.call/cls_schar.c: Likewise.
- * testsuite/libffi.call/cls_sint.c: Likewise.
- * testsuite/libffi.call/cls_sshort.c: Likewise.
- * testsuite/libffi.call/cls_uchar.c: Likewise.
- * testsuite/libffi.call/cls_uint.c: Likewise.
- * testsuite/libffi.call/cls_ulonglong.c: Likewise.
- * testsuite/libffi.call/cls_ushort.c: Likewise.
- * testsuite/libffi.call/problem1.c: Likewise.
-
- * testsuite/libffi.special/unwindtest.cc: Make ffi_closure
- static.
-
-2003-11-08 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/cls_9byte2.c: New test case.
- * testsuite/libffi.call/cls_9byte1.c: Likewise.
- * testsuite/libffi.call/cls_64byte.c: Likewise.
- * testsuite/libffi.call/cls_20byte1.c: Likewise.
- * testsuite/libffi.call/cls_19byte.c: Likewise.
- * testsuite/libffi.call/cls_18byte.c: Likewise.
- * testsuite/libffi.call/closure_fn4.c: Likewise.
- * testsuite/libffi.call/closure_fn5.c: Likewise.
- * testsuite/libffi.call/cls_schar.c: Likewise.
- * testsuite/libffi.call/cls_sint.c: Likewise.
- * testsuite/libffi.call/cls_sshort.c: Likewise.
- * testsuite/libffi.call/nested_struct2.c: Likewise.
- * testsuite/libffi.call/nested_struct3.c: Likewise.
-
-2003-11-08 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/cls_double.c: Do a check on the result.
- * testsuite/libffi.call/cls_uchar.c: Likewise.
- * testsuite/libffi.call/cls_uint.c: Likewise.
- * testsuite/libffi.call/cls_ulonglong.c: Likewise.
- * testsuite/libffi.call/cls_ushort.c: Likewise.
- * testsuite/libffi.call/return_sc.c: Cleanup whitespaces.
-
-2003-11-06 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/prep_cif.c (ffi_prep_cif): Move the validity check after
- the initialization.
-
-2003-10-23 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/java_raw_api.c (ffi_java_ptrarray_to_raw): Replace
- FFI_ASSERT(FALSE) with FFI_ASSERT(0).
-
-2003-10-22 David Daney <ddaney@avtrex.com>
-
- * src/mips/ffitarget.h: Replace undefined UINT32 and friends with
- __attribute__((__mode__(__SI__))) and friends.
-
-2003-10-22 Andreas Schwab <schwab@suse.de>
-
- * src/ia64/ffi.c: Replace FALSE/TRUE with false/true.
-
-2003-10-21 Andreas Tobler <a.tobler@schweiz.ch>
-
- * configure.in: AC_LINK_FILES(ffitarget.h).
- * configure: Regenerate.
- * Makefile.in: Likewise.
- * include/Makefile.in: Likewise.
- * testsuite/Makefile.in: Likewise.
- * fficonfig.h.in: Likewise.
-
-2003-10-21 Paolo Bonzini <bonzini@gnu.org>
- Richard Henderson <rth@redhat.com>
-
- Avoid that ffi.h includes fficonfig.h.
-
- * Makefile.am (EXTRA_DIST): Include ffitarget.h files
- (TARGET_SRC_MIPS_GCC): Renamed to TARGET_SRC_MIPS_IRIX.
- (TARGET_SRC_MIPS_SGI): Removed.
- (MIPS_GCC): Renamed to TARGET_SRC_MIPS_IRIX.
- (MIPS_SGI): Removed.
- (CLEANFILES): Removed.
- (mostlyclean-am, clean-am, mostlyclean-sub, clean-sub): New
- targets.
- * acconfig.h: Removed.
- * configure.in: Compute sizeofs only for double and long double.
- Use them to define and subst HAVE_LONG_DOUBLE. Include comments
- into AC_DEFINE instead of using acconfig.h. Create
- include/ffitarget.h instead of include/fficonfig.h. Rename
- MIPS_GCC to MIPS_IRIX, drop MIPS_SGI since we are in gcc's tree.
- AC_DEFINE EH_FRAME_FLAGS.
- * include/Makefile.am (DISTCLEANFILES): New automake macro.
- (hack_DATA): Add ffitarget.h.
- * include/ffi.h.in: Remove all system specific definitions.
- Declare raw API even if it is not installed, why bother?
- Use limits.h instead of SIZEOF_* to define ffi_type_*. Do
- not define EH_FRAME_FLAGS, it is in fficonfig.h now. Include
- ffitarget.h instead of fficonfig.h. Remove ALIGN macro.
- (UINT_ARG, INT_ARG): Removed, use ffi_arg and ffi_sarg instead.
- * include/ffi_common.h (bool): Do not define.
- (ffi_assert): Accept failed assertion.
- (ffi_type_test): Return void and accept file/line.
- (FFI_ASSERT): Pass stringized failed assertion.
- (FFI_ASSERT_AT): New macro.
- (FFI_ASSERT_VALID_TYPE): New macro.
- (UINT8, SINT8, UINT16, SINT16, UINT32, SINT32,
- UINT64, SINT64): Define here with gcc's __attribute__ macro
- instead of in ffi.h
- (FLOAT32, ALIGN): Define here instead of in ffi.h
- * include/ffi-mips.h: Removed. Its content moved to
- src/mips/ffitarget.h after separating assembly and C sections.
- * src/alpha/ffi.c, src/alpha/ffi.c, src/java_raw_api.c
- src/prep_cif.c, src/raw_api.c, src/ia64/ffi.c,
- src/mips/ffi.c, src/mips/n32.S, src/mips/o32.S,
- src/mips/ffitarget.h, src/sparc/ffi.c, src/x86/ffi64.c:
- SIZEOF_ARG -> FFI_SIZEOF_ARG.
- * src/ia64/ffi.c: Include stdbool.h (provided by GCC 2.95+).
- * src/debug.c (ffi_assert): Accept stringized failed assertion.
- (ffi_type_test): Rewritten.
- * src/prep-cif.c (initialize_aggregate, ffi_prep_cif): Call
- FFI_ASSERT_VALID_TYPE.
- * src/alpha/ffitarget.h, src/arm/ffitarget.h,
- src/ia64/ffitarget.h, src/m68k/ffitarget.h,
- src/mips/ffitarget.h, src/powerpc/ffitarget.h,
- src/s390/ffitarget.h, src/sh/ffitarget.h,
- src/sh64/ffitarget.h, src/sparc/ffitarget.h,
- src/x86/ffitarget.h: New files.
- * src/alpha/osf.S, src/arm/sysv.S, src/ia64/unix.S,
- src/m68k/sysv.S, src/mips/n32.S, src/mips/o32.S,
- src/powerpc/aix.S, src/powerpc/darwin.S,
- src/powerpc/ffi_darwin.c, src/powerpc/linux64.S,
- src/powerpc/linux64_closure.S, src/powerpc/ppc_closure.S,
- src/powerpc/sysv.S, src/s390/sysv.S, src/sh/sysv.S,
- src/sh64/sysv.S, src/sparc/v8.S, src/sparc/v9.S,
- src/x86/sysv.S, src/x86/unix64.S, src/x86/win32.S:
- include fficonfig.h
-
-2003-10-20 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * src/mips/ffi.c: Use _ABIN32, _ABIO32 instead of external
- _MIPS_SIM_NABI32, _MIPS_SIM_ABI32.
-
-2003-10-19 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/powerpc/ffi_darwin.c (ffi_prep_args): Declare bytes again.
- Used when FFI_DEBUG = 1.
-
-2003-10-14 Alan Modra <amodra@bigpond.net.au>
-
- * src/types.c (double, longdouble): Default POWERPC64 to 8 byte size
- and align.
-
-2003-10-06 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * include/ffi_mips.h: Define FFI_MIPS_N32 for N32/N64 ABIs,
- FFI_MIPS_O32 for O32 ABI.
-
-2003-10-01 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/lib/libffi-dg.exp: Set LD_LIBRARY_PATH_64 for
- SPARC64. Cleanup whitespaces.
-
-2003-09-19 Andreas Tobler <a.tobler@schweiz.ch>
-
- * testsuite/libffi.call/closure_fn0.c: Xfail mips, arm,
- strongarm, xscale. Cleanup whitespaces.
- * testsuite/libffi.call/closure_fn1.c: Likewise.
- * testsuite/libffi.call/closure_fn2.c: Likewise.
- * testsuite/libffi.call/closure_fn3.c: Likewise.
- * testsuite/libffi.call/cls_12byte.c: Likewise.
- * testsuite/libffi.call/cls_16byte.c: Likewise.
- * testsuite/libffi.call/cls_1_1byte.c: Likewise.
- * testsuite/libffi.call/cls_20byte.c: Likewise.
- * testsuite/libffi.call/cls_24byte.c: Likewise.
- * testsuite/libffi.call/cls_2byte.c: Likewise.
- * testsuite/libffi.call/cls_3_1byte.c: Likewise.
- * testsuite/libffi.call/cls_3byte1.c: Likewise.
- * testsuite/libffi.call/cls_3byte2.c: Likewise.
- * testsuite/libffi.call/cls_4_1byte.c: Likewise.
- * testsuite/libffi.call/cls_4byte.c: Likewise.
- * testsuite/libffi.call/cls_5byte.c: Likewise.
- * testsuite/libffi.call/cls_6byte.c: Likewise.
- * testsuite/libffi.call/cls_7byte.c: Likewise.
- * testsuite/libffi.call/cls_8byte.c: Likewise.
- * testsuite/libffi.call/cls_double.c: Likewise.
- * testsuite/libffi.call/cls_float.c: Likewise.
- * testsuite/libffi.call/cls_uchar.c: Likewise.
- * testsuite/libffi.call/cls_uint.c: Likewise.
- * testsuite/libffi.call/cls_ulonglong.c: Likewise.
- * testsuite/libffi.call/cls_ushort.c: Likewise.
- * testsuite/libffi.call/nested_struct.c: Likewise.
- * testsuite/libffi.call/nested_struct1.c: Likewise.
- * testsuite/libffi.call/problem1.c: Likewise.
- * testsuite/libffi.special/unwindtest.cc: Likewise.
- * testsuite/libffi.call/pyobjc-tc.c: Cleanup whitespaces.
-
-2003-09-18 David Edelsohn <edelsohn@gnu.org>
-
- * src/powerpc/aix.S: Cleanup whitespaces.
- * src/powerpc/aix_closure.S: Likewise.
-
-2003-09-18 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/powerpc/darwin.S: Cleanup whitespaces, comment formatting.
- * src/powerpc/darwin_closure.S: Likewise.
- * src/powerpc/ffi_darwin.c: Likewise.
-
-2003-09-18 Andreas Tobler <a.tobler@schweiz.ch>
- David Edelsohn <edelsohn@gnu.org>
-
- * src/types.c (double): Add AIX and Darwin to the right TYPEDEF.
- * src/powerpc/aix_closure.S: Remove the pointer to the outgoing
- parameter stack.
- * src/powerpc/darwin_closure.S: Likewise.
- * src/powerpc/ffi_darwin.c (ffi_prep_args): Handle structures
- according to the Darwin/AIX ABI.
- (ffi_prep_cif_machdep): Likewise.
- (ffi_closure_helper_DARWIN): Likewise.
- Remove the outgoing parameter stack logic. Simplify the evaluation
- of the different CASE types.
- (ffi_prep_clousure): Avoid the casts on lvalues. Change the branch
- statement in the trampoline code.
-
-2003-09-18 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/ffi.c (ffi_prep_args): Take account into the alignement
- for the register size.
- (ffi_closure_helper_SYSV): Handle the structure return value
- address correctly.
- (ffi_closure_helper_SYSV): Return the appropriate type when
- the registers are used for the structure return value.
- * src/sh/sysv.S (ffi_closure_SYSV): Fix the stack layout for
- the 64-bit return value. Update copyright years.
-
-2003-09-17 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * testsuite/lib/libffi-dg.exp (libffi_target_compile): Search in
- srcdir for ffi_mips.h.
-
-2003-09-12 Alan Modra <amodra@bigpond.net.au>
-
- * src/prep_cif.c (initialize_aggregate): Include tail padding in
- structure size.
- * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Correct
- placement of float result.
- * testsuite/libffi.special/unwindtest.cc (closure_test_fn1): Correct
- cast of "resp" for big-endian 64 bit machines.
-
-2003-09-11 Alan Modra <amodra@bigpond.net.au>
-
- * src/types.c (double, longdouble): Merge identical SH and ARM
- typedefs, and add POWERPC64.
- * src/powerpc/ffi.c (ffi_prep_args64): Correct next_arg calc for
- struct split over gpr and rest.
- (ffi_prep_cif_machdep): Correct intarg_count for structures.
- * src/powerpc/linux64.S (ffi_call_LINUX64): Fix gpr offsets.
-
-2003-09-09 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/powerpc/ffi.c (ffi_closure_helper_SYSV) Handle struct
- passing correctly.
-
-2003-09-09 Alan Modra <amodra@bigpond.net.au>
-
- * configure: Regenerate.
-
-2003-09-04 Andreas Tobler <a.tobler@schweiz.ch>
-
- * Makefile.am: Remove build rules for ffitest.
- * Makefile.in: Rebuilt.
-
-2003-09-04 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/java_raw_api.c: Include <stdlib.h> to fix compiler warning
- about implicit declaration of abort().
-
-2003-09-04 Andreas Tobler <a.tobler@schweiz.ch>
-
- * Makefile.am: Add dejagnu test framework. Fixes PR other/11411.
- * Makefile.in: Rebuilt.
- * configure.in: Add dejagnu test framework.
- * configure: Rebuilt.
-
- * testsuite/Makefile.am: New file.
- * testsuite/Makefile.in: Built
- * testsuite/lib/libffi-dg.exp: New file.
- * testsuite/config/default.exp: Likewise.
- * testsuite/libffi.call/call.exp: Likewise.
- * testsuite/libffi.call/ffitest.h: Likewise.
- * testsuite/libffi.call/closure_fn0.c: Likewise.
- * testsuite/libffi.call/closure_fn1.c: Likewise.
- * testsuite/libffi.call/closure_fn2.c: Likewise.
- * testsuite/libffi.call/closure_fn3.c: Likewise.
- * testsuite/libffi.call/cls_1_1byte.c: Likewise.
- * testsuite/libffi.call/cls_3_1byte.c: Likewise.
- * testsuite/libffi.call/cls_4_1byte.c: Likewise.
- * testsuite/libffi.call/cls_2byte.c: Likewise.
- * testsuite/libffi.call/cls_3byte1.c: Likewise.
- * testsuite/libffi.call/cls_3byte2.c: Likewise.
- * testsuite/libffi.call/cls_4byte.c: Likewise.
- * testsuite/libffi.call/cls_5byte.c: Likewise.
- * testsuite/libffi.call/cls_6byte.c: Likewise.
- * testsuite/libffi.call/cls_7byte.c: Likewise.
- * testsuite/libffi.call/cls_8byte.c: Likewise.
- * testsuite/libffi.call/cls_12byte.c: Likewise.
- * testsuite/libffi.call/cls_16byte.c: Likewise.
- * testsuite/libffi.call/cls_20byte.c: Likewise.
- * testsuite/libffi.call/cls_24byte.c: Likewise.
- * testsuite/libffi.call/cls_double.c: Likewise.
- * testsuite/libffi.call/cls_float.c: Likewise.
- * testsuite/libffi.call/cls_uchar.c: Likewise.
- * testsuite/libffi.call/cls_uint.c: Likewise.
- * testsuite/libffi.call/cls_ulonglong.c: Likewise.
- * testsuite/libffi.call/cls_ushort.c: Likewise.
- * testsuite/libffi.call/float.c: Likewise.
- * testsuite/libffi.call/float1.c: Likewise.
- * testsuite/libffi.call/float2.c: Likewise.
- * testsuite/libffi.call/many.c: Likewise.
- * testsuite/libffi.call/many_win32.c: Likewise.
- * testsuite/libffi.call/nested_struct.c: Likewise.
- * testsuite/libffi.call/nested_struct1.c: Likewise.
- * testsuite/libffi.call/pyobjc-tc.c: Likewise.
- * testsuite/libffi.call/problem1.c: Likewise.
- * testsuite/libffi.call/promotion.c: Likewise.
- * testsuite/libffi.call/return_ll.c: Likewise.
- * testsuite/libffi.call/return_sc.c: Likewise.
- * testsuite/libffi.call/return_uc.c: Likewise.
- * testsuite/libffi.call/strlen.c: Likewise.
- * testsuite/libffi.call/strlen_win32.c: Likewise.
- * testsuite/libffi.call/struct1.c: Likewise.
- * testsuite/libffi.call/struct2.c: Likewise.
- * testsuite/libffi.call/struct3.c: Likewise.
- * testsuite/libffi.call/struct4.c: Likewise.
- * testsuite/libffi.call/struct5.c: Likewise.
- * testsuite/libffi.call/struct6.c: Likewise.
- * testsuite/libffi.call/struct7.c: Likewise.
- * testsuite/libffi.call/struct8.c: Likewise.
- * testsuite/libffi.call/struct9.c: Likewise.
- * testsuite/libffi.special/special.exp: New file.
- * testsuite/libffi.special/ffitestcxx.h: Likewise.
- * testsuite/libffi.special/unwindtest.cc: Likewise.
-
-
-2003-08-13 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/ffi.c (OFS_INT16): Set 0 for little endian case. Update
- copyright years.
-
-2003-08-02 Alan Modra <amodra@bigpond.net.au>
-
- * src/powerpc/ffi.c (ffi_prep_args64): Modify for changed gcc
- structure passing.
- (ffi_closure_helper_LINUX64): Likewise.
- * src/powerpc/linux64.S: Remove code writing to parm save area.
- * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Use return
- address in lr from ffi_closure_helper_LINUX64 call to calculate
- table address. Optimize function tail.
-
-2003-07-28 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/sparc/ffi.c: Handle all floating point registers.
- * src/sparc/v9.S: Likewise. Fixes second part of PR target/11410.
-
-2003-07-11 Gerald Pfeifer <pfeifer@dbai.tuwien.ac.at>
-
- * README: Note that libffi is not part of GCC. Update the project
- URL and status.
-
-2003-06-19 Franz Sirl <Franz.Sirl-kernel@lauterbach.com>
-
- * src/powerpc/ppc_closure.S: Include ffi.h.
-
-2003-06-13 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * src/x86/sysv.S: Avoid gas-only .uleb128/.sleb128 directives.
- Use C style comments.
-
-2003-06-13 Kaz Kojima <kkojima@rr.iij4u.or.jp>
-
- * Makefile.am: Add SHmedia support. Fix a typo of SH support.
- * Makefile.in: Regenerate.
- * configure.in (sh64-*-linux*, sh5*-*-linux*): Add target.
- * configure: Regenerate.
- * include/ffi.h.in: Add SHmedia support.
- * src/sh64/ffi.c: New file.
- * src/sh64/sysv.S: New file.
-
-2003-05-16 Jakub Jelinek <jakub@redhat.com>
-
- * configure.in (HAVE_RO_EH_FRAME): Check whether .eh_frame section
- should be read-only.
- * configure: Rebuilt.
- * fficonfig.h.in: Rebuilt.
- * include/ffi.h.in (EH_FRAME_FLAGS): Define.
- * src/alpha/osf.S: Use EH_FRAME_FLAGS.
- * src/powerpc/linux64.S: Likewise.
- * src/powerpc/linux64_closure.S: Likewise. Include ffi.h.
- * src/powerpc/sysv.S: Use EH_FRAME_FLAGS. Use pcrel encoding
- if -fpic/-fPIC/-mrelocatable.
- * src/powerpc/powerpc_closure.S: Likewise.
- * src/sparc/v8.S: If HAVE_RO_EH_FRAME is defined, don't include
- #write in .eh_frame flags.
- * src/sparc/v9.S: Likewise.
- * src/x86/unix64.S: Use EH_FRAME_FLAGS.
- * src/x86/sysv.S: Likewise. Use pcrel encoding if -fpic/-fPIC.
- * src/s390/sysv.S: Use EH_FRAME_FLAGS. Include ffi.h.
-
-2003-05-07 Jeff Sturm <jsturm@one-point.com>
-
- Fixes PR bootstrap/10656
- * configure.in (HAVE_AS_REGISTER_PSEUDO_OP): Test assembler
- support for .register pseudo-op.
- * src/sparc/v8.S: Use it.
- * fficonfig.h.in: Rebuilt.
- * configure: Rebuilt.
-
-2003-04-18 Jakub Jelinek <jakub@redhat.com>
-
- * include/ffi.h.in (POWERPC64): Define if 64-bit.
- (enum ffi_abi): Add FFI_LINUX64 on POWERPC.
- Make it the default on POWERPC64.
- (FFI_TRAMPOLINE_SIZE): Define to 24 on POWERPC64.
- * configure.in: Change powerpc-*-linux* into powerpc*-*-linux*.
- * configure: Rebuilt.
- * src/powerpc/ffi.c (hidden): Define.
- (ffi_prep_args_SYSV): Renamed from
- ffi_prep_args. Cast pointers to unsigned long to shut up warnings.
- (NUM_GPR_ARG_REGISTERS64, NUM_FPR_ARG_REGISTERS64,
- ASM_NEEDS_REGISTERS64): New.
- (ffi_prep_args64): New function.
- (ffi_prep_cif_machdep): Handle FFI_LINUX64 ABI.
- (ffi_call): Likewise.
- (ffi_prep_closure): Likewise.
- (flush_icache): Surround by #ifndef POWERPC64.
- (ffi_dblfl): New union type.
- (ffi_closure_helper_SYSV): Use it to avoid aliasing problems.
- (ffi_closure_helper_LINUX64): New function.
- * src/powerpc/ppc_closure.S: Surround whole file by #ifndef
- __powerpc64__.
- * src/powerpc/sysv.S: Likewise.
- (ffi_call_SYSV): Rename ffi_prep_args to ffi_prep_args_SYSV.
- * src/powerpc/linux64.S: New file.
- * src/powerpc/linux64_closure.S: New file.
- * Makefile.am (EXTRA_DIST): Add src/powerpc/linux64.S and
- src/powerpc/linux64_closure.S.
- (TARGET_SRC_POWERPC): Likewise.
-
- * src/ffitest.c (closure_test_fn, closure_test_fn1, closure_test_fn2,
- closure_test_fn3): Fix result printing on big-endian 64-bit
- machines.
- (main): Print tst2_arg instead of uninitialized tst2_result.
-
- * src/ffitest.c (main): Hide what closure pointer really points to
- from the compiler.
-
-2003-04-16 Richard Earnshaw <rearnsha@arm.com>
-
- * configure.in (arm-*-netbsdelf*): Add configuration.
- (configure): Regenerated.
-
-2003-04-04 Loren J. Rittle <ljrittle@acm.org>
-
- * include/Makefile.in: Regenerate.
-
-2003-03-21 Zdenek Dvorak <rakdver@atrey.karlin.mff.cuni.cz>
-
- * libffi/include/ffi.h.in: Define X86 instead of X86_64 in 32
- bit mode.
- * libffi/src/x86/ffi.c (ffi_closure_SYSV, ffi_closure_raw_SYSV):
- Receive closure pointer through parameter, read args using
- __builtin_dwarf_cfa.
- (FFI_INIT_TRAMPOLINE): Send closure reference through eax.
-
-2003-03-12 Andreas Schwab <schwab@suse.de>
-
- * configure.in: Avoid trailing /. in toolexeclibdir.
- * configure: Rebuilt.
-
-2003-03-03 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/powerpc/darwin_closure.S: Recode to fit dynamic libraries.
-
-2003-02-06 Andreas Tobler <a.tobler@schweiz.ch>
-
- * libffi/src/powerpc/darwin_closure.S:
- Fix alignement bug, allocate 8 bytes for the result.
- * libffi/src/powerpc/aix_closure.S:
- Likewise.
- * libffi/src/powerpc/ffi_darwin.c:
- Update stackframe description for aix/darwin_closure.S.
-
-2003-02-06 Jakub Jelinek <jakub@redhat.com>
-
- * src/s390/ffi.c (ffi_closure_helper_SYSV): Add hidden visibility
- attribute.
-
-2003-01-31 Christian Cornelssen <ccorn@cs.tu-berlin.de>,
- Andreas Schwab <schwab@suse.de>
-
- * configure.in: Adjust command to source config-ml.in to account
- for changes to the libffi_basedir definition.
- (libffi_basedir): Remove ${srcdir} from value and include trailing
- slash if nonempty.
-
- * configure: Regenerate.
-
-2003-01-29 Franz Sirl <Franz.Sirl-kernel@lauterbach.com>
-
- * src/powerpc/ppc_closure.S: Recode to fit shared libs.
-
-2003-01-28 Andrew Haley <aph@redhat.com>
-
- * include/ffi.h.in: Enable FFI_CLOSURES for x86_64.
- * src/x86/ffi64.c (ffi_prep_closure): New.
- (ffi_closure_UNIX64_inner): New.
- * src/x86/unix64.S (ffi_closure_UNIX64): New.
-
-2003-01-27 Alexandre Oliva <aoliva@redhat.com>
-
- * configure.in (toolexecdir, toolexeclibdir): Set and AC_SUBST.
- Remove USE_LIBDIR conditional.
- * Makefile.am (toolexecdir, toolexeclibdir): Don't override.
- * Makefile.in, configure: Rebuilt.
-
-2003-01027 David Edelsohn <edelsohn@gnu.org>
-
- * Makefile.am (TARGET_SRC_POWERPC_AIX): Fix typo.
- * Makefile.in: Regenerate.
-
-2003-01-22 Andrew Haley <aph@redhat.com>
-
- * src/powerpc/darwin.S (_ffi_call_AIX): Add Augmentation size to
- unwind info.
-
-2003-01-21 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/powerpc/darwin.S: Add unwind info.
- * src/powerpc/darwin_closure.S: Likewise.
-
-2003-01-14 Andrew Haley <aph@redhat.com>
-
- * src/x86/ffi64.c (ffi_prep_args): Check for void retval.
- (ffi_prep_cif_machdep): Likewise.
- * src/x86/unix64.S: Add unwind info.
-
-2003-01-14 Andreas Jaeger <aj@suse.de>
-
- * src/ffitest.c (main): Only use ffi_closures if those are
- supported.
-
-2003-01-13 Andreas Tobler <a.tobler@schweiz.ch>
-
- * libffi/src/ffitest.c
- add closure testcases
-
-2003-01-13 Kevin B. Hendricks <khendricks@ivey.uwo.ca>
-
- * libffi/src/powerpc/ffi.c
- fix alignment bug for float (4 byte aligned iso 8 byte)
-
-2003-01-09 Geoffrey Keating <geoffk@apple.com>
-
- * src/powerpc/ffi_darwin.c: Remove RCS version string.
- * src/powerpc/darwin.S: Remove RCS version string.
-
-2003-01-03 Jeff Sturm <jsturm@one-point.com>
-
- * include/ffi.h.in: Add closure defines for SPARC, SPARC64.
- * src/ffitest.c (main): Use static storage for closure.
- * src/sparc/ffi.c (ffi_prep_closure, ffi_closure_sparc_inner): New.
- * src/sparc/v8.S (ffi_closure_v8): New.
- * src/sparc/v9.S (ffi_closure_v9): New.
-
-2002-11-10 Ranjit Mathew <rmathew@hotmail.com>
-
- * include/ffi.h.in: Added FFI_STDCALL ffi_type
- enumeration for X86_WIN32.
- * src/x86/win32.S: Added ffi_call_STDCALL function
- definition.
- * src/x86/ffi.c (ffi_call/ffi_raw_call): Added
- switch cases for recognising FFI_STDCALL and
- calling ffi_call_STDCALL if target is X86_WIN32.
- * src/ffitest.c (my_stdcall_strlen/stdcall_many):
- stdcall versions of the "my_strlen" and "many"
- test functions (for X86_WIN32).
- Added test cases to test stdcall invocation using
- these functions.
-
-2002-12-02 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/sysv.S: Add DWARF2 unwind info.
-
-2002-11-27 Ulrich Weigand <uweigand@de.ibm.com>
-
- * src/s390/sysv.S (.eh_frame section): Make section read-only.
-
-2002-11-26 Jim Wilson <wilson@redhat.com>
-
- * src/types.c (FFI_TYPE_POINTER): Has size 8 on IA64.
-
-2002-11-23 H.J. Lu <hjl@gnu.org>
-
- * acinclude.m4: Add dummy AM_PROG_LIBTOOL.
- Include ../config/accross.m4.
- * aclocal.m4; Rebuild.
- * configure: Likewise.
-
-2002-11-15 Ulrich Weigand <uweigand@de.ibm.com>
-
- * src/s390/sysv.S (.eh_frame section): Adapt to pcrel FDE encoding.
-
-2002-11-11 DJ Delorie <dj@redhat.com>
-
- * configure.in: Look for common files in the right place.
-
-2002-10-08 Ulrich Weigand <uweigand@de.ibm.com>
-
- * src/java_raw_api.c (ffi_java_raw_to_ptrarray): Interpret
- raw data as _Jv_word values, not ffi_raw.
- (ffi_java_ptrarray_to_raw): Likewise.
- (ffi_java_rvalue_to_raw): New function.
- (ffi_java_raw_call): Call it.
- (ffi_java_raw_to_rvalue): New function.
- (ffi_java_translate_args): Call it.
- * src/ffitest.c (closure_test_fn): Interpret return value
- as ffi_arg, not int.
- * src/s390/ffi.c (ffi_prep_cif_machdep): Add missing
- FFI_TYPE_POINTER case.
- (ffi_closure_helper_SYSV): Likewise. Also, assume return
- values extended to word size.
-
-2002-10-02 Andreas Jaeger <aj@suse.de>
-
- * src/x86/ffi64.c (ffi_prep_cif_machdep): Remove debug output.
-
-2002-10-01 Bo Thorsen <bo@smetana.suse.de>
-
- * include/ffi.h.in: Fix i386 win32 compilation.
-
-2002-09-30 Ulrich Weigand <uweigand@de.ibm.com>
-
- * configure.in: Add s390x-*-linux-* target.
- * configure: Regenerate.
- * include/ffi.h.in: Define S390X for s390x targets.
- (FFI_CLOSURES): Define for s390/s390x.
- (FFI_TRAMPOLINE_SIZE): Likewise.
- (FFI_NATIVE_RAW_API): Likewise.
- * src/prep_cif.c (ffi_prep_cif): Do not compute stack space for s390.
- * src/types.c (FFI_TYPE_POINTER): Use 8-byte pointers on s390x.
- * src/s390/ffi.c: Major rework of existing code. Add support for
- s390x targets. Add closure support.
- * src/s390/sysv.S: Likewise.
-
-2002-09-29 Richard Earnshaw <rearnsha@arm.com>
-
- * src/arm/sysv.S: Fix typo.
-
-2002-09-28 Richard Earnshaw <rearnsha@arm.com>
-
- * src/arm/sysv.S: If we don't have machine/asm.h and the pre-processor
- has defined __USER_LABEL_PREFIX__, then use it in CNAME.
- (ffi_call_SYSV): Handle soft-float.
-
-2002-09-27 Bo Thorsen <bo@suse.de>
-
- * include/ffi.h.in: Fix multilib x86-64 support.
-
-2002-09-22 Kaveh R. Ghazi <ghazi@caip.rutgers.edu>
-
- * Makefile.am (all-multi): Fix multilib parallel build.
-
-2002-07-19 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * configure.in (sh[34]*-*-linux*): Add brackets.
- * configure: Regenerate.
-
-2002-07-18 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * Makefile.am: Add SH support.
- * Makefile.in: Regenerate.
- * configure.in (sh-*-linux*, sh[34]*-*-linux*): Add target.
- * configure: Regenerate.
- * include/ffi.h.in: Add SH support.
- * src/sh/ffi.c: New file.
- * src/sh/sysv.S: New file.
- * src/types.c: Add SH support.
-
-2002-07-16 Bo Thorsen <bo@suse.de>
-
- * src/x86/ffi64.c: New file that adds x86-64 support.
- * src/x86/unix64.S: New file that handles argument setup for
- x86-64.
- * src/x86/sysv.S: Don't use this on x86-64.
- * src/x86/ffi.c: Don't use this on x86-64.
- Remove unused vars.
- * src/prep_cif.c (ffi_prep_cif): Don't do stack size calculation
- for x86-64.
- * src/ffitest.c (struct6): New test that tests a special case in
- the x86-64 ABI.
- (struct7): Likewise.
- (struct8): Likewise.
- (struct9): Likewise.
- (closure_test_fn): Silence warning about this when it's not used.
- (main): Add the new tests.
- (main): Fix a couple of wrong casts and silence some compiler warnings.
- * include/ffi.h.in: Add x86-64 ABI definition.
- * fficonfig.h.in: Regenerate.
- * Makefile.am: Add x86-64 support.
- * configure.in: Likewise.
- * Makefile.in: Regenerate.
- * configure: Likewise.
-
-2002-06-24 Bo Thorsen <bo@suse.de>
-
- * src/types.c: Merge settings for similar architectures.
- Add x86-64 sizes and alignments.
-
-2002-06-23 Bo Thorsen <bo@suse.de>
-
- * src/arm/ffi.c (ffi_prep_args): Remove unused vars.
- * src/sparc/ffi.c (ffi_prep_args_v8): Likewise.
- * src/mips/ffi.c (ffi_prep_args): Likewise.
- * src/m68k/ffi.c (ffi_prep_args): Likewise.
-
-2002-07-18 H.J. Lu (hjl@gnu.org)
-
- * Makefile.am (TARGET_SRC_MIPS_LINUX): New.
- (libffi_la_SOURCES): Support MIPS_LINUX.
- (libffi_convenience_la_SOURCES): Likewise.
- * Makefile.in: Regenerated.
-
- * configure.in (mips64*-*): Skip.
- (mips*-*-linux*): New.
- * configure: Regenerated.
-
- * src/mips/ffi.c: Include <sgidefs.h>.
-
-2002-06-06 Ulrich Weigand <uweigand@de.ibm.com>
-
- * src/s390/sysv.S: Save/restore %r6. Add DWARF-2 unwind info.
-
-2002-05-27 Roger Sayle <roger@eyesopen.com>
-
- * src/x86/ffi.c (ffi_prep_args): Remove reference to avn.
-
-2002-05-27 Bo Thorsen <bo@suse.de>
-
- * src/x86/ffi.c (ffi_prep_args): Remove unused variable and
- fix formatting.
-
-2002-05-13 Andreas Tobler <a.tobler@schweiz.ch>
-
- * src/powerpc/ffi_darwin.c (ffi_prep_closure): Declare fd at
- beginning of function (for older apple cc).
-
-2002-05-08 Alexandre Oliva <aoliva@redhat.com>
-
- * configure.in (ORIGINAL_LD_FOR_MULTILIBS): Preserve LD at
- script entry, and set LD to it when configuring multilibs.
- * configure: Rebuilt.
-
-2002-05-05 Jason Thorpe <thorpej@wasabisystems.com>
-
- * configure.in (sparc64-*-netbsd*): Add target.
- (sparc-*-netbsdelf*): Likewise.
- * configure: Regenerate.
-
-2002-04-28 David S. Miller <davem@redhat.com>
-
- * configure.in, configure: Fix SPARC test in previous change.
-
-2002-04-29 Gerhard Tonn <GerhardTonn@swol.de>
-
- * Makefile.am: Add Linux for S/390 support.
- * Makefile.in: Regenerate.
- * configure.in: Add Linux for S/390 support.
- * configure: Regenerate.
- * include/ffi.h.in: Add Linux for S/390 support.
- * src/s390/ffi.c: New file from libffi CVS tree.
- * src/s390/sysv.S: New file from libffi CVS tree.
-
-2002-04-28 Jakub Jelinek <jakub@redhat.com>
-
- * configure.in (HAVE_AS_SPARC_UA_PCREL): Check for working
- %r_disp32().
- * src/sparc/v8.S: Use it.
- * src/sparc/v9.S: Likewise.
- * fficonfig.h.in: Rebuilt.
- * configure: Rebuilt.
-
-2002-04-08 Hans Boehm <Hans_Boehm@hp.com>
-
- * src/java_raw_api.c (ffi_java_raw_size): Handle FFI_TYPE_DOUBLE
- correctly.
- * src/ia64/unix.S: Add unwind information. Fix comments.
- Save sp in a way that's compatible with unwind info.
- (ffi_call_unix): Correctly restore sp in all cases.
- * src/ia64/ffi.c: Add, fix comments.
-
-2002-04-08 Jakub Jelinek <jakub@redhat.com>
-
- * src/sparc/v8.S: Make .eh_frame dependent on target word size.
-
-2002-04-06 Jason Thorpe <thorpej@wasabisystems.com>
-
- * configure.in (alpha*-*-netbsd*): Add target.
- * configure: Regenerate.
-
-2002-04-04 Jeff Sturm <jsturm@one-point.com>
-
- * src/sparc/v8.S: Add unwind info.
- * src/sparc/v9.S: Likewise.
-
-2002-03-30 Krister Walfridsson <cato@df.lth.se>
-
- * configure.in: Enable i*86-*-netbsdelf*.
- * configure: Rebuilt.
-
-2002-03-29 David Billinghurst <David.Billinghurst@riotinto.com>
-
- PR other/2620
- * src/mips/n32.s: Delete
- * src/mips/o32.s: Delete
-
-2002-03-21 Loren J. Rittle <ljrittle@acm.org>
-
- * configure.in: Enable alpha*-*-freebsd*.
- * configure: Rebuilt.
-
-2002-03-17 Bryce McKinlay <bryce@waitaki.otago.ac.nz>
-
- * Makefile.am: libfficonvenience -> libffi_convenience.
- * Makefile.in: Rebuilt.
-
- * Makefile.am: Define ffitest_OBJECTS.
- * Makefile.in: Rebuilt.
-
-2002-03-07 Andreas Tobler <toa@pop.agri.ch>
- David Edelsohn <edelsohn@gnu.org>
-
- * Makefile.am (EXTRA_DIST): Add Darwin and AIX closure files.
- (TARGET_SRC_POWERPC_AIX): Add aix_closure.S.
- (TARGET_SRC_POWERPC_DARWIN): Add darwin_closure.S.
- * Makefile.in: Regenerate.
- * include/ffi.h.in: Add AIX and Darwin closure definitions.
- * src/powerpc/ffi_darwin.c (ffi_prep_closure): New function.
- (flush_icache, flush_range): New functions.
- (ffi_closure_helper_DARWIN): New function.
- * src/powerpc/aix_closure.S: New file.
- * src/powerpc/darwin_closure.S: New file.
-
-2002-02-24 Jeff Sturm <jsturm@one-point.com>
-
- * include/ffi.h.in: Add typedef for ffi_arg.
- * src/ffitest.c (main): Declare rint with ffi_arg.
-
-2002-02-21 Andreas Tobler <toa@pop.agri.ch>
-
- * src/powerpc/ffi_darwin.c (ffi_prep_args): Skip appropriate
- number of GPRs for floating-point arguments.
-
-2002-01-31 Anthony Green <green@redhat.com>
-
- * configure: Rebuilt.
- * configure.in: Replace CHECK_SIZEOF and endian tests with
- cross-compiler friendly macros.
- * aclocal.m4 (AC_COMPILE_CHECK_SIZEOF, AC_C_BIGENDIAN_CROSS): New
- macros.
-
-2002-01-18 David Edelsohn <edelsohn@gnu.org>
-
- * src/powerpc/darwin.S (_ffi_call_AIX): New.
- * src/powerpc/aix.S (ffi_call_DARWIN): New.
-
-2002-01-17 David Edelsohn <edelsohn@gnu.org>
-
- * Makefile.am (EXTRA_DIST): Add Darwin and AIX files.
- (TARGET_SRC_POWERPC_AIX): New.
- (POWERPC_AIX): New stanza.
- * Makefile.in: Regenerate.
- * configure.in: Add AIX case.
- * configure: Regenerate.
- * include/ffi.h.in (ffi_abi): Add FFI_AIX.
- * src/powerpc/ffi_darwin.c (ffi_status): Use "long" to scale frame
- size. Fix "long double" support.
- (ffi_call): Add FFI_AIX case.
- * src/powerpc/aix.S: New.
-
-2001-10-09 John Hornkvist <john@toastedmarshmallow.com>
-
- Implement Darwin PowerPC ABI.
- * configure.in: Handle powerpc-*-darwin*.
- * Makefile.am: Set source files for POWERPC_DARWIN.
- * configure: Rebuilt.
- * Makefile.in: Rebuilt.
- * include/ffi.h.in: Define FFI_DARWIN and FFI_DEFAULT_ABI for
- POWERPC_DARWIN.
- * src/powerpc/darwin.S: New file.
- * src/powerpc/ffi_darwin.c: New file.
-
-2001-10-07 Joseph S. Myers <jsm28@cam.ac.uk>
-
- * src/x86/ffi.c: Fix spelling error of "separate" as "seperate".
-
-2001-07-16 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * src/x86/sysv.S: Avoid gas-only .balign directive.
- Use C style comments.
-
-2001-07-16 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * src/alpha/ffi.c (ffi_prep_closure): Avoid gas-only mnemonic.
- Fixes PR bootstrap/3563.
-
-2001-06-26 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * src/alpha/osf.S (ffi_closure_osf): Use .rdata for ECOFF.
-
-2001-06-25 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * configure.in: Recognize sparc*-sun-* host.
- * configure: Regenerate.
-
-2001-06-06 Andrew Haley <aph@redhat.com>
-
- * src/alpha/osf.S (__FRAME_BEGIN__): Conditionalize for ELF.
-
-2001-06-03 Andrew Haley <aph@redhat.com>
-
- * src/alpha/osf.S: Add unwind info.
- * src/powerpc/sysv.S: Add unwind info.
- * src/powerpc/ppc_closure.S: Likewise.
-
-2000-05-31 Jeff Sturm <jsturm@one-point.com>
-
- * configure.in: Fix AC_ARG_ENABLE usage.
- * configure: Rebuilt.
-
-2001-05-06 Bryce McKinlay <bryce@waitaki.otago.ac.nz>
-
- * configure.in: Remove warning about beta code.
- * configure: Rebuilt.
-
-2001-04-25 Hans Boehm <Hans_Boehm@hp.com>
-
- * src/ia64/unix.S: Restore stack pointer when returning from
- ffi_closure_UNIX.
- * src/ia64/ffi.c: Fix typo in comment.
-
-2001-04-18 Jim Wilson <wilson@redhat.com>
-
- * src/ia64/unix.S: Delete unnecessary increment and decrement of loc2
- to eliminate RAW DV.
-
-2001-04-12 Bryce McKinlay <bryce@albatross.co.nz>
-
- * Makefile.am: Make a libtool convenience library.
- * Makefile.in: Rebuilt.
-
-2001-03-29 Bryce McKinlay <bryce@albatross.co.nz>
-
- * configure.in: Use different syntax for subdirectory creation.
- * configure: Rebuilt.
-
-2001-03-27 Jon Beniston <jon@beniston.com>
-
- * configure.in: Added X86_WIN32 target (Win32, CygWin, MingW).
- * configure: Rebuilt.
- * Makefile.am: Added X86_WIN32 target support.
- * Makefile.in: Rebuilt.
-
- * include/ffi.h.in: Added X86_WIN32 target support.
-
- * src/ffitest.c: Doesn't run structure tests for X86_WIN32 targets.
- * src/types.c: Added X86_WIN32 target support.
-
- * src/x86/win32.S: New file. Based on sysv.S, but with EH
- stuff removed and made to work with CygWin's gas.
-
-2001-03-26 Bryce McKinlay <bryce@albatross.co.nz>
-
- * configure.in: Make target subdirectory in build dir.
- * Makefile.am: Override suffix based rules to specify correct output
- subdirectory.
- * Makefile.in: Rebuilt.
- * configure: Rebuilt.
-
-2001-03-23 Kevin B Hendricks <khendricks@ivey.uwo.ca>
-
- * src/powerpc/ppc_closure.S: New file.
- * src/powerpc/ffi.c (ffi_prep_args): Fixed ABI compatibility bug
- involving long long and register pairs.
- (ffi_prep_closure): New function.
- (flush_icache): Likewise.
- (ffi_closure_helper_SYSV): Likewise.
- * include/ffi.h.in (FFI_CLOSURES): Define on PPC.
- (FFI_TRAMPOLINE_SIZE): Likewise.
- (FFI_NATIVE_RAW_API): Likewise.
- * Makefile.in: Rebuilt.
- * Makefile.am (EXTRA_DIST): Added src/powerpc/ppc_closure.S.
- (TARGET_SRC_POWERPC): Likewise.
-
-2001-03-19 Tom Tromey <tromey@redhat.com>
-
- * Makefile.in: Rebuilt.
- * Makefile.am (ffitest_LDFLAGS): New macro.
-
-2001-03-02 Nick Clifton <nickc@redhat.com>
-
- * include/ffi.h.in: Remove RCS ident string.
- * include/ffi_mips.h: Remove RCS ident string.
- * src/debug.c: Remove RCS ident string.
- * src/ffitest.c: Remove RCS ident string.
- * src/prep_cif.c: Remove RCS ident string.
- * src/types.c: Remove RCS ident string.
- * src/alpha/ffi.c: Remove RCS ident string.
- * src/alpha/osf.S: Remove RCS ident string.
- * src/arm/ffi.c: Remove RCS ident string.
- * src/arm/sysv.S: Remove RCS ident string.
- * src/mips/ffi.c: Remove RCS ident string.
- * src/mips/n32.S: Remove RCS ident string.
- * src/mips/o32.S: Remove RCS ident string.
- * src/sparc/ffi.c: Remove RCS ident string.
- * src/sparc/v8.S: Remove RCS ident string.
- * src/sparc/v9.S: Remove RCS ident string.
- * src/x86/ffi.c: Remove RCS ident string.
- * src/x86/sysv.S: Remove RCS ident string.
-
-2001-02-08 Joseph S. Myers <jsm28@cam.ac.uk>
-
- * include/ffi.h.in: Change sourceware.cygnus.com references to
- gcc.gnu.org.
-
-2000-12-09 Richard Henderson <rth@redhat.com>
-
- * src/alpha/ffi.c (ffi_call): Simplify struct return test.
- (ffi_closure_osf_inner): Index rather than increment avalue
- and arg_types. Give ffi_closure_osf the raw return value type.
- * src/alpha/osf.S (ffi_closure_osf): Handle return value type
- promotion.
-
-2000-12-07 Richard Henderson <rth@redhat.com>
-
- * src/raw_api.c (ffi_translate_args): Fix typo.
- (ffi_prep_closure): Likewise.
-
- * include/ffi.h.in [ALPHA]: Define FFI_CLOSURES and
- FFI_TRAMPOLINE_SIZE.
- * src/alpha/ffi.c (ffi_prep_cif_machdep): Adjust minimal
- cif->bytes for new ffi_call_osf implementation.
- (ffi_prep_args): Absorb into ...
- (ffi_call): ... here. Do all stack allocation here and
- avoid a callback function.
- (ffi_prep_closure, ffi_closure_osf_inner): New.
- * src/alpha/osf.S (ffi_call_osf): Reimplement with no callback.
- (ffi_closure_osf): New.
-
-2000-09-10 Alexandre Oliva <aoliva@redhat.com>
-
- * config.guess, config.sub, install-sh: Removed.
- * ltconfig, ltmain.sh, missing, mkinstalldirs: Likewise.
- * Makefile.in: Rebuilt.
-
- * acinclude.m4: Include libtool macros from the top level.
- * aclocal.m4, configure: Rebuilt.
-
-2000-08-22 Alexandre Oliva <aoliva@redhat.com>
-
- * configure.in [i*86-*-freebsd*] (TARGET, TARGETDIR): Set.
- * configure: Rebuilt.
-
-2000-05-11 Scott Bambrough <scottb@netwinder.org>
-
- * libffi/src/arm/sysv.S (ffi_call_SYSV): Doubles are not saved to
- memory correctly. Use conditional instructions, not branches where
- possible.
-
-2000-05-04 Tom Tromey <tromey@cygnus.com>
-
- * configure: Rebuilt.
- * configure.in: Match `arm*-*-linux-*'.
- From Chris Dornan <cdornan@arm.com>.
-
-2000-04-28 Jakub Jelinek <jakub@redhat.com>
-
- * Makefile.am (SUBDIRS): Define.
- (AM_MAKEFLAGS): Likewise.
- (Multilib support.): Add section.
- * Makefile.in: Rebuilt.
- * ltconfig (extra_compiler_flags, extra_compiler_flags_value):
- New variables. Set for gcc using -print-multi-lib. Export them
- to libtool.
- (sparc64-*-linux-gnu*): Use libsuff 64 for search paths.
- * ltmain.sh (B|b|V): Don't throw away gcc's -B, -b and -V options
- for -shared links.
- (extra_compiler_flags_value, extra_compiler_flags): Check these
- for extra compiler options which need to be passed down in
- compiler_flags.
-
-2000-04-16 Anthony Green <green@redhat.com>
-
- * configure: Rebuilt.
- * configure.in: Change i*86-pc-linux* to i*86-*-linux*.
-
-2000-04-14 Jakub Jelinek <jakub@redhat.com>
-
- * include/ffi.h.in (SPARC64): Define for 64bit SPARC builds.
- Set SPARC FFI_DEFAULT_ABI based on SPARC64 define.
- * src/sparc/ffi.c (ffi_prep_args_v8): Renamed from ffi_prep_args.
- Replace all void * sizeofs with sizeof(int).
- Only compare type with FFI_TYPE_LONGDOUBLE if LONGDOUBLE is
- different than DOUBLE.
- Remove FFI_TYPE_SINT32 and FFI_TYPE_UINT32 cases (handled elsewhere).
- (ffi_prep_args_v9): New function.
- (ffi_prep_cif_machdep): Handle V9 ABI and long long on V8.
- (ffi_V9_return_struct): New function.
- (ffi_call): Handle FFI_V9 ABI from 64bit code and FFI_V8 ABI from
- 32bit code (not yet cross-arch calls).
- * src/sparc/v8.S: Add struct return delay nop.
- Handle long long.
- * src/sparc/v9.S: New file.
- * src/prep_cif.c (ffi_prep_cif): Return structure pointer
- is used on sparc64 only for structures larger than 32 bytes.
- Pass by reference for structures is done for structure arguments
- larger than 16 bytes.
- * src/ffitest.c (main): Use 64bit rint on sparc64.
- Run long long tests on sparc.
- * src/types.c (FFI_TYPE_POINTER): Pointer is 64bit on alpha and
- sparc64.
- (FFI_TYPE_LONGDOUBLE): long double is 128 bit aligned to 128 bits
- on sparc64.
- * configure.in (sparc-*-linux*): New supported target.
- (sparc64-*-linux*): Likewise.
- * configure: Rebuilt.
- * Makefile.am: Add v9.S to SPARC files.
- * Makefile.in: Likewise.
- (LINK): Surround $(CCLD) into double quotes, so that multilib
- compiles work correctly.
-
-2000-04-04 Alexandre Petit-Bianco <apbianco@cygnus.com>
-
- * configure: Rebuilt.
- * configure.in: (i*86-*-solaris*): New libffi target. Patch
- proposed by Bryce McKinlay.
-
-2000-03-20 Tom Tromey <tromey@cygnus.com>
-
- * Makefile.in: Hand edit for java_raw_api.lo.
-
-2000-03-08 Bryce McKinlay <bryce@albatross.co.nz>
-
- * config.guess, config.sub: Update from the gcc tree.
- Fix for PR libgcj/168.
-
-2000-03-03 Tom Tromey <tromey@cygnus.com>
-
- * Makefile.in: Fixed ia64 by hand.
-
- * configure: Rebuilt.
- * configure.in (--enable-multilib): New option.
- (libffi_basedir): New subst.
- (AC_OUTPUT): Added multilib code.
-
-2000-03-02 Tom Tromey <tromey@cygnus.com>
-
- * Makefile.in: Rebuilt.
- * Makefile.am (TARGET_SRC_IA64): Use `ia64', not `alpha', as
- directory name.
-
-2000-02-25 Hans Boehm <boehm@acm.org>
-
- * src/ia64/ffi.c, src/ia64/ia64_flags.h, src/ia64/unix.S: New
- files.
- * src/raw_api.c (ffi_translate_args): Fixed typo in argument
- list.
- (ffi_prep_raw_closure): Use ffi_translate_args, not
- ffi_closure_translate.
- * src/java_raw_api.c: New file.
- * src/ffitest.c (closure_test_fn): New function.
- (main): Define `rint' as long long on IA64. Added new test when
- FFI_CLOSURES is defined.
- * include/ffi.h.in (ALIGN): Use size_t, not unsigned.
- (ffi_abi): Recognize IA64.
- (ffi_raw): Added `flt' field.
- Added "Java raw API" code.
- * configure.in: Recognize ia64.
- * Makefile.am (TARGET_SRC_IA64): New macro.
- (libffi_la_common_SOURCES): Added java_raw_api.c.
- (libffi_la_SOURCES): Define in IA64 case.
-
-2000-01-04 Tom Tromey <tromey@cygnus.com>
-
- * Makefile.in: Rebuilt with newer automake.
-
-1999-12-31 Tom Tromey <tromey@cygnus.com>
-
- * Makefile.am (INCLUDES): Added -I$(top_srcdir)/src.
-
-1999-09-01 Tom Tromey <tromey@cygnus.com>
-
- * include/ffi.h.in: Removed PACKAGE and VERSION defines and
- undefs.
- * fficonfig.h.in: Rebuilt.
- * configure: Rebuilt.
- * configure.in: Pass 3rd argument to AM_INIT_AUTOMAKE.
- Use AM_PROG_LIBTOOL (automake 1.4 compatibility).
- * acconfig.h: Don't #undef PACKAGE or VERSION.
-
-1999-08-09 Anthony Green <green@cygnus.com>
-
- * include/ffi.h.in: Try to work around messy header problem
- with PACKAGE and VERSION.
-
- * configure: Rebuilt.
- * configure.in: Change version to 2.00-beta.
-
- * fficonfig.h.in: Rebuilt.
- * acconfig.h (FFI_NO_STRUCTS, FFI_NO_RAW_API): Define.
-
- * src/x86/ffi.c (ffi_raw_call): Rename.
-
-1999-08-02 Kresten Krab Thorup <krab@dominiq.is.s.u-tokyo.ac.jp>
-
- * src/x86/ffi.c (ffi_closure_SYSV): New function.
- (ffi_prep_incoming_args_SYSV): Ditto.
- (ffi_prep_closure): Ditto.
- (ffi_closure_raw_SYSV): Ditto.
- (ffi_prep_raw_closure): More ditto.
- (ffi_call_raw): Final ditto.
-
- * include/ffi.h.in: Add definitions for closure and raw API.
-
- * src/x86/ffi.c (ffi_prep_cif_machdep): Added case for
- FFI_TYPE_UINT64.
-
- * Makefile.am (libffi_la_common_SOURCES): Added raw_api.c
-
- * src/raw_api.c: New file.
-
- * include/ffi.h.in (ffi_raw): New type.
- (UINT_ARG, SINT_ARG): New defines.
- (ffi_closure, ffi_raw_closure): New types.
- (ffi_prep_closure, ffi_prep_raw_closure): New declarations.
-
- * configure.in: Add check for endianness and sizeof void*.
-
- * src/x86/sysv.S (ffi_call_SYSV): Call fixup routine via argument,
- instead of directly.
-
- * configure: Rebuilt.
-
-Thu Jul 8 14:28:42 1999 Anthony Green <green@cygnus.com>
-
- * configure.in: Add x86 and powerpc BeOS configurations.
- From Makoto Kato <m_kato@ga2.so-net.ne.jp>.
-
-1999-05-09 Anthony Green <green@cygnus.com>
-
- * configure.in: Add warning about this being beta code.
- Remove src/Makefile.am from the picture.
- * configure: Rebuilt.
-
- * Makefile.am: Move logic from src/Makefile.am. Add changes
- to support libffi as a target library.
- * Makefile.in: Rebuilt.
-
- * aclocal.m4, config.guess, config.sub, ltconfig, ltmain.sh:
- Upgraded to new autoconf, automake, libtool.
-
- * README: Tweaks.
-
- * LICENSE: Update copyright date.
-
- * src/Makefile.am, src/Makefile.in: Removed.
-
-1998-11-29 Anthony Green <green@cygnus.com>
-
- * include/ChangeLog: Removed.
- * src/ChangeLog: Removed.
- * src/mips/ChangeLog: Removed.
- * src/sparc/ChangeLog: Remboved.
- * src/x86/ChangeLog: Removed.
-
- * ChangeLog.v1: Created.
-
-=============================================================================
-From the old ChangeLog.libffi file....
-
-2011-02-08 Andreas Tobler <andreast@fgznet.ch>
-
- * testsuite/lib/libffi.exp: Tweak for stand-alone mode.
-
-2009-12-25 Samuli Suominen <ssuominen@gentoo.org>
-
- * configure.ac: Undefine _AC_ARG_VAR_PRECIOUS for autoconf 2.64.
- * configure: Rebuilt.
- * fficonfig.h.in: Rebuilt.
-
-2009-06-16 Andrew Haley <aph@redhat.com>
-
- * testsuite/libffi.call/cls_align_sint64.c,
- testsuite/libffi.call/cls_align_uint64.c,
- testsuite/libffi.call/cls_longdouble_va.c,
- testsuite/libffi.call/cls_ulonglong.c,
- testsuite/libffi.call/return_ll1.c,
- testsuite/libffi.call/stret_medium2.c: Fix printf format
- specifiers.
- * testsuite/libffi.call/huge_struct.c: Ad x86 XFAILs.
- * testsuite/libffi.call/float2.c: Fix dg-excess-errors.
- * testsuite/libffi.call/ffitest.h,
- testsuite/libffi.special/ffitestcxx.h (PRIdLL, PRIuLL): Define.
-
-2009-06-12 Andrew Haley <aph@redhat.com>
-
- * testsuite/libffi.call/cls_align_sint64.c,
- testsuite/libffi.call/cls_align_uint64.c,
- testsuite/libffi.call/cls_ulonglong.c,
- testsuite/libffi.call/return_ll1.c,
- testsuite/libffi.call/stret_medium2.c: Fix printf format
- specifiers.
- testsuite/libffi.special/unwindtest.cc: include stdint.h.
-
-2009-06-11 Timothy Wall <twall@users.sf.net>
-
- * Makefile.am,
- configure.ac,
- include/ffi.h.in,
- include/ffi_common.h,
- src/closures.c,
- src/dlmalloc.c,
- src/x86/ffi.c,
- src/x86/ffitarget.h,
- src/x86/win64.S (new),
- README: Added win64 support (mingw or MSVC)
- * Makefile.in,
- include/Makefile.in,
- man/Makefile.in,
- testsuite/Makefile.in,
- configure,
- aclocal.m4: Regenerated
- * ltcf-c.sh: properly escape cygwin/w32 path
- * man/ffi_call.3: Clarify size requirements for return value.
- * src/x86/ffi64.c: Fix filename in comment.
- * src/x86/win32.S: Remove unused extern.
-
- * testsuite/libffi.call/closure_fn0.c,
- testsuite/libffi.call/closure_fn1.c,
- testsuite/libffi.call/closure_fn2.c,
- testsuite/libffi.call/closure_fn3.c,
- testsuite/libffi.call/closure_fn4.c,
- testsuite/libffi.call/closure_fn5.c,
- testsuite/libffi.call/closure_fn6.c,
- testsuite/libffi.call/closure_stdcall.c,
- testsuite/libffi.call/cls_12byte.c,
- testsuite/libffi.call/cls_16byte.c,
- testsuite/libffi.call/cls_18byte.c,
- testsuite/libffi.call/cls_19byte.c,
- testsuite/libffi.call/cls_1_1byte.c,
- testsuite/libffi.call/cls_20byte.c,
- testsuite/libffi.call/cls_20byte1.c,
- testsuite/libffi.call/cls_24byte.c,
- testsuite/libffi.call/cls_2byte.c,
- testsuite/libffi.call/cls_3_1byte.c,
- testsuite/libffi.call/cls_3byte1.c,
- testsuite/libffi.call/cls_3byte2.c,
- testsuite/libffi.call/cls_4_1byte.c,
- testsuite/libffi.call/cls_4byte.c,
- testsuite/libffi.call/cls_5_1_byte.c,
- testsuite/libffi.call/cls_5byte.c,
- testsuite/libffi.call/cls_64byte.c,
- testsuite/libffi.call/cls_6_1_byte.c,
- testsuite/libffi.call/cls_6byte.c,
- testsuite/libffi.call/cls_7_1_byte.c,
- testsuite/libffi.call/cls_7byte.c,
- testsuite/libffi.call/cls_8byte.c,
- testsuite/libffi.call/cls_9byte1.c,
- testsuite/libffi.call/cls_9byte2.c,
- testsuite/libffi.call/cls_align_double.c,
- testsuite/libffi.call/cls_align_float.c,
- testsuite/libffi.call/cls_align_longdouble.c,
- testsuite/libffi.call/cls_align_longdouble_split.c,
- testsuite/libffi.call/cls_align_longdouble_split2.c,
- testsuite/libffi.call/cls_align_pointer.c,
- testsuite/libffi.call/cls_align_sint16.c,
- testsuite/libffi.call/cls_align_sint32.c,
- testsuite/libffi.call/cls_align_sint64.c,
- testsuite/libffi.call/cls_align_uint16.c,
- testsuite/libffi.call/cls_align_uint32.c,
- testsuite/libffi.call/cls_align_uint64.c,
- testsuite/libffi.call/cls_dbls_struct.c,
- testsuite/libffi.call/cls_double.c,
- testsuite/libffi.call/cls_double_va.c,
- testsuite/libffi.call/cls_float.c,
- testsuite/libffi.call/cls_longdouble.c,
- testsuite/libffi.call/cls_longdouble_va.c,
- testsuite/libffi.call/cls_multi_schar.c,
- testsuite/libffi.call/cls_multi_sshort.c,
- testsuite/libffi.call/cls_multi_sshortchar.c,
- testsuite/libffi.call/cls_multi_uchar.c,
- testsuite/libffi.call/cls_multi_ushort.c,
- testsuite/libffi.call/cls_multi_ushortchar.c,
- testsuite/libffi.call/cls_pointer.c,
- testsuite/libffi.call/cls_pointer_stack.c,
- testsuite/libffi.call/cls_schar.c,
- testsuite/libffi.call/cls_sint.c,
- testsuite/libffi.call/cls_sshort.c,
- testsuite/libffi.call/cls_uchar.c,
- testsuite/libffi.call/cls_uint.c,
- testsuite/libffi.call/cls_ulonglong.c,
- testsuite/libffi.call/cls_ushort.c,
- testsuite/libffi.call/err_bad_abi.c,
- testsuite/libffi.call/err_bad_typedef.c,
- testsuite/libffi.call/float2.c,
- testsuite/libffi.call/huge_struct.c,
- testsuite/libffi.call/nested_struct.c,
- testsuite/libffi.call/nested_struct1.c,
- testsuite/libffi.call/nested_struct10.c,
- testsuite/libffi.call/nested_struct2.c,
- testsuite/libffi.call/nested_struct3.c,
- testsuite/libffi.call/nested_struct4.c,
- testsuite/libffi.call/nested_struct5.c,
- testsuite/libffi.call/nested_struct6.c,
- testsuite/libffi.call/nested_struct7.c,
- testsuite/libffi.call/nested_struct8.c,
- testsuite/libffi.call/nested_struct9.c,
- testsuite/libffi.call/problem1.c,
- testsuite/libffi.call/return_ldl.c,
- testsuite/libffi.call/return_ll1.c,
- testsuite/libffi.call/stret_large.c,
- testsuite/libffi.call/stret_large2.c,
- testsuite/libffi.call/stret_medium.c,
- testsuite/libffi.call/stret_medium2.c,
- testsuite/libffi.special/unwindtest.cc: use ffi_closure_alloc instead
- of checking for MMAP. Use intptr_t instead of long casts.
-
-2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/powerpc/ffitarget.h: Fix misapplied merge from gcc.
-
-2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/mips/o32.S,
- src/mips/n32.S: Fix licence formatting.
-
-2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/x86/darwin.S: Fix licence formatting.
- src/x86/win32.S: Likewise.
- src/sh64/sysv.S: Likewise.
- src/sh/sysv.S: Likewise.
-
-2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/sh64/ffi.c: Remove lint directives. Was missing from merge
- of Andreas Tobler's patch from 2006-04-22.
-
-2009-06-04 Andrew Haley <aph@redhat.com>
-
- * src/sh/ffi.c: Apply missing hunk from Alexandre Oliva's patch of
- 2007-03-07.
-
-2008-12-26 Timothy Wall <twall@users.sf.net>
-
- * testsuite/libffi.call/cls_longdouble.c,
- testsuite/libffi.call/cls_longdouble_va.c,
- testsuite/libffi.call/cls_align_longdouble.c,
- testsuite/libffi.call/cls_align_longdouble_split.c,
- testsuite/libffi.call/cls_align_longdouble_split2.c: mark expected
- failures on x86_64 cygwin/mingw.
-
-2008-12-22 Timothy Wall <twall@users.sf.net>
-
- * testsuite/libffi.call/closure_fn0.c,
- testsuite/libffi.call/closure_fn1.c,
- testsuite/libffi.call/closure_fn2.c,
- testsuite/libffi.call/closure_fn3.c,
- testsuite/libffi.call/closure_fn4.c,
- testsuite/libffi.call/closure_fn5.c,
- testsuite/libffi.call/closure_fn6.c,
- testsuite/libffi.call/closure_loc_fn0.c,
- testsuite/libffi.call/closure_stdcall.c,
- testsuite/libffi.call/cls_align_pointer.c,
- testsuite/libffi.call/cls_pointer.c,
- testsuite/libffi.call/cls_pointer_stack.c: use portable cast from
- pointer to integer (intptr_t).
- * testsuite/libffi.call/cls_longdouble.c: disable for win64.
-
-2008-12-19 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 3.0.8.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision.
- * README: Update for new release.
-
-2008-11-11 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 3.0.7.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision.
- * README: Update for new release.
-
-2008-08-25 Andreas Tobler <a.tobler@schweiz.org>
-
- * src/powerpc/ffitarget.h (ffi_abi): Add FFI_LINUX and
- FFI_LINUX_SOFT_FLOAT to the POWERPC_FREEBSD enum.
- Add note about flag bits used for FFI_SYSV_TYPE_SMALL_STRUCT.
- Adjust copyright notice.
- * src/powerpc/ffi.c: Add two new flags to indicate if we have one
- register or two register to use for FFI_SYSV structs.
- (ffi_prep_cif_machdep): Pass the right register flag introduced above.
- (ffi_closure_helper_SYSV): Fix the return type for
- FFI_SYSV_TYPE_SMALL_STRUCT. Comment.
- Adjust copyright notice.
-
-2008-07-24 Anthony Green <green@redhat.com>
-
- * testsuite/libffi.call/cls_dbls_struct.c,
- testsuite/libffi.call/cls_double_va.c,
- testsuite/libffi.call/cls_longdouble.c,
- testsuite/libffi.call/cls_longdouble_va.c,
- testsuite/libffi.call/cls_pointer.c,
- testsuite/libffi.call/cls_pointer_stack.c,
- testsuite/libffi.call/err_bad_abi.c: Clean up failures from
- compiler warnings.
-
-2008-07-17 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 3.0.6.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision. Add documentation.
- * README: Update for new release.
-
-2008-07-16 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/ffi.c (ffi_prep_closure_loc): Turn INSN into an unsigned
- int.
-
-2008-07-16 Kaz Kojima <kkojima@gcc.gnu.org>
-
- * src/sh/sysv.S: Add .note.GNU-stack on Linux.
- * src/sh64/sysv.S: Likewise.
-
-2008-04-03 Anthony Green <green@redhat.com>
-
- * libffi.pc.in (Libs): Add -L${libdir}.
- * configure.ac: Bump version to 3.0.5.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision.
- * README: Update for new release.
-
-2008-04-03 Anthony Green <green@redhat.com>
- Xerces Ranby <xerxes@zafena.se>
-
- * include/ffi.h.in: Wrap definition of target architecture to
- protect from double definitions.
-
-2008-03-22 Moriyoshi Koizumi <moriyoshi@gmail.com>
-
- * src/x86/ffi.c (ffi_prep_closure_loc): Fix for bug revealed in
- closure_loc_fn0.c.
- * testsuite/libffi.call/closure_loc_fn0.c (closure_loc_test_fn0):
- New test.
-
-2008-03-04 Anthony Green <green@redhat.com>
- Blake Chaffin
- hos@tamanegi.org
-
- * testsuite/libffi.call/cls_align_longdouble_split2.c
- testsuite/libffi.call/cls_align_longdouble_split.c
- testsuite/libffi.call/cls_dbls_struct.c
- testsuite/libffi.call/cls_double_va.c
- testsuite/libffi.call/cls_longdouble.c
- testsuite/libffi.call/cls_longdouble_va.c
- testsuite/libffi.call/cls_pointer.c
- testsuite/libffi.call/cls_pointer_stack.c
- testsuite/libffi.call/err_bad_abi.c
- testsuite/libffi.call/err_bad_typedef.c
- testsuite/libffi.call/huge_struct.c
- testsuite/libffi.call/stret_large2.c
- testsuite/libffi.call/stret_large.c
- testsuite/libffi.call/stret_medium2.c
- testsuite/libffi.call/stret_medium.c: New tests from Apple.
-
-2008-02-26 Jakub Jelinek <jakub@redhat.com>
- Anthony Green <green@redhat.com>
-
- * src/alpha/osf.S: Add .note.GNU-stack on Linux.
- * src/s390/sysv.S: Likewise.
- * src/powerpc/linux64.S: Likewise.
- * src/powerpc/linux64_closure.S: Likewise.
- * src/powerpc/ppc_closure.S: Likewise.
- * src/powerpc/sysv.S: Likewise.
- * src/x86/unix64.S: Likewise.
- * src/x86/sysv.S: Likewise.
- * src/sparc/v8.S: Likewise.
- * src/sparc/v9.S: Likewise.
- * src/m68k/sysv.S: Likewise.
- * src/ia64/unix.S: Likewise.
- * src/arm/sysv.S: Likewise.
-
-2008-02-26 Anthony Green <green@redhat.com>
- Thomas Heller <theller@ctypes.org>
-
- * src/x86/ffi.c (ffi_closure_SYSV_inner): Change C++ comment to C
- comment.
-
-2008-02-26 Anthony Green <green@redhat.org>
- Thomas Heller <theller@ctypes.org>
-
- * include/ffi.h.in: Change void (*)() to void (*)(void).
-
-2008-02-26 Anthony Green <green@redhat.org>
- Thomas Heller <theller@ctypes.org>
-
- * src/alpha/ffi.c: Change void (*)() to void (*)(void).
- src/alpha/osf.S, src/arm/ffi.c, src/frv/ffi.c, src/ia64/ffi.c,
- src/ia64/unix.S, src/java_raw_api.c, src/m32r/ffi.c,
- src/mips/ffi.c, src/pa/ffi.c, src/pa/hpux32.S, src/pa/linux.S,
- src/powerpc/ffi.c, src/powerpc/ffi_darwin.c, src/raw_api.c,
- src/s390/ffi.c, src/sh/ffi.c, src/sh64/ffi.c, src/sparc/ffi.c,
- src/x86/ffi.c, src/x86/unix64.S, src/x86/darwin64.S,
- src/x86/ffi64.c: Ditto.
-
-2008-02-24 Anthony Green <green@redhat.org>
-
- * configure.ac: Accept openbsd*, not just openbsd.
- Bump version to 3.0.4.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision.
- * README: Update for new release.
-
-2008-02-22 Anthony Green <green@redhat.com>
-
- * README: Clean up list of tested platforms.
-
-2008-02-22 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 3.0.3.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision.
- * README: Update for new release. Clean up test docs.
-
-2008-02-22 Bjoern Koenig <bkoenig@alpha-tierchen.de>
- Andreas Tobler <a.tobler@schweiz.org>
-
- * configure.ac: Add amd64-*-freebsd* target.
- * configure: Regenerate.
-
-2008-02-22 Thomas Heller <theller@ctypes.org>
-
- * configure.ac: Add x86 OpenBSD support.
- * configure: Rebuilt.
-
-2008-02-21 Thomas Heller <theller@ctypes.org>
-
- * README: Change "make test" to "make check".
-
-2008-02-21 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 3.0.2.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision.
- * README: Update for new release.
-
-2008-02-21 Björn König <bkoenig@alpha-tierchen.de>
-
- * src/x86/freebsd.S: New file.
- * configure.ac: Add x86 FreeBSD support.
- * Makefile.am: Ditto.
-
-2008-02-15 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 3.0.1.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * libtool-version: Increment revision.
- * README: Update for new release.
-
-2008-02-15 David Daney <ddaney@avtrex.com>
-
- * src/mips/ffi.c: Remove extra '>' from include directive.
- (ffi_prep_closure_loc): Use clear_location instead of tramp.
-
-2008-02-15 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 3.0.0.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
-
-2008-02-15 David Daney <ddaney@avtrex.com>
-
- * src/mips/ffi.c (USE__BUILTIN___CLEAR_CACHE):
- Define (conditionally), and use it to include cachectl.h.
- (ffi_prep_closure_loc): Fix cache flushing.
- * src/mips/ffitarget.h (_ABIN32, _ABI64, _ABIO32): Define.
-
-2008-02-15 Anthony Green <green@redhat.com>
-
- * man/ffi_call.3, man/ffi_prep_cif.3, man/ffi.3:
- Update dates and remove all references to ffi_prep_closure.
- * configure.ac: Bump version to 2.99.9.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
-
-2008-02-15 Anthony Green <green@redhat.com>
-
- * man/ffi_prep_closure.3: Delete.
- * man/Makefile.am (EXTRA_DIST): Remove ffi_prep_closure.3.
- (man_MANS): Ditto.
- * man/Makefile.in: Rebuilt.
- * configure.ac: Bump version to 2.99.8.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
-
-2008-02-14 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 2.99.7.
- * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
- * include/ffi.h.in LICENSE src/debug.c src/closures.c
- src/ffitest.c src/s390/sysv.S src/s390/ffitarget.h
- src/types.c src/m68k/ffitarget.h src/raw_api.c src/frv/ffi.c
- src/frv/ffitarget.h src/sh/ffi.c src/sh/sysv.S
- src/sh/ffitarget.h src/powerpc/ffitarget.h src/pa/ffi.c
- src/pa/ffitarget.h src/pa/linux.S src/java_raw_api.c
- src/cris/ffitarget.h src/x86/ffi.c src/x86/sysv.S
- src/x86/unix64.S src/x86/win32.S src/x86/ffitarget.h
- src/x86/ffi64.c src/x86/darwin.S src/ia64/ffi.c
- src/ia64/ffitarget.h src/ia64/ia64_flags.h src/ia64/unix.S
- src/sparc/ffi.c src/sparc/v9.S src/sparc/ffitarget.h
- src/sparc/v8.S src/alpha/ffi.c src/alpha/ffitarget.h
- src/alpha/osf.S src/sh64/ffi.c src/sh64/sysv.S
- src/sh64/ffitarget.h src/mips/ffi.c src/mips/ffitarget.h
- src/mips/n32.S src/mips/o32.S src/arm/ffi.c src/arm/sysv.S
- src/arm/ffitarget.h src/prep_cif.c: Update license text.
-
-2008-02-14 Anthony Green <green@redhat.com>
-
- * README: Update tested platforms.
- * configure.ac: Bump version to 2.99.6.
- * configure: Rebuilt.
-
-2008-02-14 Anthony Green <green@redhat.com>
-
- * configure.ac: Bump version to 2.99.5.
- * configure: Rebuilt.
- * Makefile.am (EXTRA_DIST): Add darwin64.S
- * Makefile.in: Rebuilt.
- * testsuite/lib/libffi-dg.exp: Remove libstdc++ bits from GCC tree.
- * LICENSE: Update WARRANTY.
-
-2008-02-14 Anthony Green <green@redhat.com>
-
- * libffi.pc.in (libdir): Fix libdir definition.
- * configure.ac: Bump version to 2.99.4.
- * configure: Rebuilt.
-
-2008-02-14 Anthony Green <green@redhat.com>
-
- * README: Update.
- * libffi.info: New file.
- * doc/stamp-vti: New file.
- * configure.ac: Bump version to 2.99.3.
- * configure: Rebuilt.
-
-2008-02-14 Anthony Green <green@redhat.com>
-
- * Makefile.am (SUBDIRS): Add man dir.
- * Makefile.in: Rebuilt.
- * configure.ac: Create Makefile.
- * configure: Rebuilt.
- * man/ffi_call.3 man/ffi_prep_cif.3 man/ffi_prep_closure.3
- man/Makefile.am man/Makefile.in: New files.
-
-2008-02-14 Tom Tromey <tromey@redhat.com>
-
- * aclocal.m4, Makefile.in, configure, fficonfig.h.in: Rebuilt.
- * mdate-sh, texinfo.tex: New files.
- * Makefile.am (info_TEXINFOS): New variable.
- * doc/libffi.texi: New file.
- * doc/version.texi: Likewise.
-
-2008-02-14 Anthony Green <green@redhat.com>
-
- * Makefile.am (AM_CFLAGS): Don't compile with -D$(TARGET).
- (lib_LTLIBRARIES): Define.
- (toolexeclib_LIBRARIES): Undefine.
- * Makefile.in: Rebuilt.
- * configure.ac: Reset version to 2.99.1.
- * configure.in: Rebuilt.
-
-2008-02-14 Anthony Green <green@redhat.com>
-
- * libffi.pc.in: Use @PACKAGE_NAME@ and @PACKAGE_VERSION@.
- * configure.ac: Reset version to 2.99.1.
- * configure.in: Rebuilt.
- * Makefile.am (EXTRA_DIST): Add ChangeLog.libffi.
- * Makefile.in: Rebuilt.
- * LICENSE: Update copyright notice.
-
-2008-02-14 Anthony Green <green@redhat.com>
-
- * include/Makefile.am (nodist_includes_HEADERS): Define. Don't
- distribute ffitarget.h or ffi.h from the build include dir.
- * Makefile.in: Rebuilt.
-
-2008-02-14 Anthony Green <green@redhat.com>
-
- * include/Makefile.am (includesdir): Install headers under libdir.
- (pkgconfigdir): Define. Install libffi.pc.
- * include/Makefile.in: Rebuilt.
- * libffi.pc.in: Create.
- * libtool-version: Increment CURRENT
- * configure.ac: Add libffi.pc.in
- * configure: Rebuilt.
-
-2008-02-03 Anthony Green <green@redhat.com>
-
- * include/Makefile.am (includesdir): Fix header install with
- DESTDIR.
- * include/Makefile.in: Rebuilt.
-
-2008-02-03 Timothy Wall <twall@users.sf.net>
-
- * src/x86/ffi.c (FFI_INIT_TRAMPOLINE_STDCALL): Calculate jump return
- offset based on code pointer, not data pointer.
-
-2008-02-01 Anthony Green <green@redhat.com>
-
- * include/Makefile.am: Fix header installs.
- * Makefile.am: Ditto.
- * include/Makefile.in: Rebuilt.
- * Makefile.in: Ditto.
-
-2008-02-01 Anthony Green <green@redhat.com>
-
- * src/x86/ffi.c (FFI_INIT_TRAMPOLINE_STDCALL,
- FFI_INIT_TRAMPOLINE): Revert my broken changes to twall's last
- patch.
-
-2008-01-31 Anthony Green <green@redhat.com>
-
- * Makefile.am (EXTRA_DIST): Add missing files.
- * testsuite/Makefile.am: Ditto.
- * Makefile.in, testsuite/Makefile.in: Rebuilt.
-
-2008-01-31 Timothy Wall <twall@users.sf.net>
-
- * testsuite/libffi.call/closure_stdcall.c: Add test for stdcall
- closures.
- * src/x86/ffitarget.h: Increase size of trampoline for stdcall
- closures.
- * src/x86/win32.S: Add assembly for stdcall closure.
- * src/x86/ffi.c: Initialize stdcall closure trampoline.
-
-2008-01-30 H.J. Lu <hongjiu.lu@intel.com>
-
- PR libffi/34612
- * src/x86/sysv.S (ffi_closure_SYSV): Pop 4 byte from stack when
- returning struct.
-
- * testsuite/libffi.call/call.exp: Add "-O2 -fomit-frame-pointer"
- tests.
-
-2008-01-30 Anthony Green <green@redhat.com>
-
- * Makefile.am, include/Makefile.am: Move headers to
- libffi_la_SOURCES for new automake.
- * Makefile.in, include/Makefile.in: Rebuilt.
-
- * testsuite/lib/wrapper.exp: Copied from gcc tree to allow for
- execution outside of gcc tree.
- * testsuite/lib/target-libpath.exp: Ditto.
-
- * testsuite/lib/libffi-dg.exp: Many changes to allow for execution
- outside of gcc tree.
-
-
-=============================================================================
-From the old ChangeLog.libgcj file....
-
-2004-01-14 Kelley Cook <kcook@gcc.gnu.org>
-
- * configure.in: Add in AC_PREREQ(2.13)
-
-2003-02-20 Alexandre Oliva <aoliva@redhat.com>
-
- * configure.in: Propagate ORIGINAL_LD_FOR_MULTILIBS to
- config.status.
- * configure: Rebuilt.
-
-2002-01-27 Alexandre Oliva <aoliva@redhat.com>
-
- * configure.in (toolexecdir, toolexeclibdir): Set and AC_SUBST.
- Remove USE_LIBDIR conditional.
- * Makefile.am (toolexecdir, toolexeclibdir): Don't override.
- * Makefile.in, configure: Rebuilt.
-
-Mon Aug 9 18:33:38 1999 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
-
- * include/Makefile.in: Rebuilt.
- * Makefile.in: Rebuilt
- * Makefile.am (toolexeclibdir): Add $(MULTISUBDIR) even for native
- builds.
- Use USE_LIBDIR.
-
- * configure: Rebuilt.
- * configure.in (USE_LIBDIR): Define for native builds.
- Use lowercase in configure --help explanations.
-
-1999-08-08 Anthony Green <green@cygnus.com>
-
- * include/ffi.h.in (FFI_FN): Remove `...'.
-
-1999-08-08 Anthony Green <green@cygnus.com>
-
- * Makefile.in: Rebuilt.
- * Makefile.am (AM_CFLAGS): Compile with -fexceptions.
-
- * src/x86/sysv.S: Add exception handling metadata.
-
-
-=============================================================================
-
-The libffi version 1 ChangeLog archive.
-
-Version 1 of libffi had per-directory ChangeLogs. Current and future
-versions have a single ChangeLog file in the root directory. The
-version 1 ChangeLogs have all been concatenated into this file for
-future reference only.
-
---- libffi ----------------------------------------------------------------
-
-Mon Oct 5 02:17:50 1998 Anthony Green <green@cygnus.com>
-
- * configure.in: Boosted rev.
- * configure, Makefile.in, aclocal.m4: Rebuilt.
- * README: Boosted rev and updated release notes.
-
-Mon Oct 5 01:03:03 1998 Anthony Green <green@cygnus.com>
-
- * configure.in: Boosted rev.
- * configure, Makefile.in, aclocal.m4: Rebuilt.
- * README: Boosted rev and updated release notes.
-
-1998-07-25 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de>
-
- * m68k/ffi.c (ffi_prep_cif_machdep): Use bitmask for cif->flags.
- Correctly handle small structures.
- (ffi_prep_args): Also handle small structures.
- (ffi_call): Pass size of return type to ffi_call_SYSV.
- * m68k/sysv.S: Adjust for above changes. Correctly align small
- structures in the return value.
-
- * types.c (uint64, sint64) [M68K]: Change alignment to 4.
-
-Fri Apr 17 17:26:58 1998 Anthony Green <green@hoser.cygnus.com>
-
- * configure.in: Boosted rev.
- * configure,Makefile.in,aclocal.m4: Rebuilt.
- * README: Boosted rev and added release notes.
-
-Sun Feb 22 00:50:41 1998 Geoff Keating <geoffk@ozemail.com.au>
-
- * configure.in: Add PowerPC config bits.
-
-1998-02-14 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de>
-
- * configure.in: Add m68k config bits. Change AC_CANONICAL_SYSTEM
- to AC_CANONICAL_HOST, this is not a compiler. Use $host instead
- of $target. Remove AC_CHECK_SIZEOF(char), we already know the
- result. Fix argument of AC_ARG_ENABLE.
- * configure, fficonfig.h.in: Rebuilt.
-
-Tue Feb 10 20:53:40 1998 Richard Henderson <rth@cygnus.com>
-
- * configure.in: Add Alpha config bits.
-
-Tue May 13 13:39:20 1997 Anthony Green <green@hoser.cygnus.com>
-
- * README: Updated dates and reworded Irix comments.
-
- * configure.in: Removed AC_PROG_RANLIB.
-
- * Makefile.in, aclocal.m4, config.guess, config.sub, configure,
- ltmain.sh, */Makefile.in: libtoolized again and rebuilt with
- automake and autoconf.
-
-Sat May 10 18:44:50 1997 Tom Tromey <tromey@cygnus.com>
-
- * configure, aclocal.m4: Rebuilt.
- * configure.in: Don't compute EXTRADIST; now handled in
- src/Makefile.in. Removed macros implied by AM_INIT_AUTOMAKE.
- Don't run AM_MAINTAINER_MODE.
-
-Thu May 8 14:34:05 1997 Anthony Green <green@hoser.cygnus.com>
-
- * missing, ltmain.sh, ltconfig.sh: Created. These are new files
- required by automake and libtool.
-
- * README: Boosted rev to 1.14. Added notes.
-
- * acconfig.h: Moved PACKAGE and VERSION for new automake.
-
- * configure.in: Changes for libtool.
-
- * Makefile.am (check): make test now make check. Uses libtool now.
-
- * Makefile.in, configure.in, aclocal.h, fficonfig.h.in: Rebuilt.
-
-Thu May 1 16:27:07 1997 Anthony Green <green@hoser.cygnus.com>
-
- * missing: Added file required by new automake.
-
-Tue Nov 26 14:10:42 1996 Anthony Green <green@csk3.cygnus.com>
-
- * acconfig.h: Added USING_PURIFY flag. This is defined when
- --enable-purify-safety was used at configure time.
-
- * configure.in (allsources): Added --enable-purify-safety switch.
- (VERSION): Boosted rev to 1.13.
- * configure: Rebuilt.
-
-Fri Nov 22 06:46:12 1996 Anthony Green <green@rtl.cygnus.com>
-
- * configure.in (VERSION): Boosted rev to 1.12.
- Removed special CFLAGS hack for gcc.
- * configure: Rebuilt.
-
- * README: Boosted rev to 1.12. Added notes.
-
- * Many files: Cygnus Support changed to Cygnus Solutions.
-
-Wed Oct 30 11:15:25 1996 Anthony Green <green@rtl.cygnus.com>
-
- * configure.in (VERSION): Boosted rev to 1.11.
- * configure: Rebuilt.
-
- * README: Boosted rev to 1.11. Added notes about GNU make.
-
-Tue Oct 29 12:25:12 1996 Anthony Green <green@rtl.cygnus.com>
-
- * configure.in: Fixed -Wall trick.
- (VERSION): Boosted rev.
- * configure: Rebuilt
-
- * acconfig.h: Needed for --enable-debug configure switch.
-
- * README: Boosted rev to 1.09. Added more notes on building
- libffi, and LCLint.
-
- * configure.in: Added --enable-debug switch. Boosted rev to
- 1.09.
- * configure: Rebuilt
-
-Tue Oct 15 13:11:28 1996 Anthony Green <green@hoser.cygnus.com>
-
- * configure.in (VERSION): Boosted rev to 1.08
- * configure: Rebuilt.
-
- * README: Added n32 bug fix notes.
-
- * Makefile.am: Added "make lint" production.
- * Makefile.in: Rebuilt.
-
-Mon Oct 14 10:54:46 1996 Anthony Green <green@rtl.cygnus.com>
-
- * README: Added web page reference.
-
- * configure.in, README: Boosted rev to 1.05
- * configure: Rebuilt.
-
- * README: Fixed n32 sample code.
-
-Fri Oct 11 17:09:28 1996 Anthony Green <green@rtl.cygnus.com>
-
- * README: Added sparc notes.
-
- * configure.in, README: Boosted rev to 1.04.
- * configure: Rebuilt.
-
-Thu Oct 10 10:31:03 1996 Anthony Green <green@rtl.cygnus.com>
-
- * configure.in, README: Boosted rev to 1.03.
- * configure: Rebuilt.
-
- * README: Added struct notes.
-
- * Makefile.am (EXTRA_DIST): Added LICENSE to distribution.
- * Makefile.in: Rebuilt.
-
- * README: Removed Linux section. No special notes now
- because aggregates arg/return types work.
-
-Wed Oct 9 16:16:42 1996 Anthony Green <green@rtl.cygnus.com>
-
- * README, configure.in (VERSION): Boosted rev to 1.02
- * configure: Rebuilt.
-
-Tue Oct 8 11:56:33 1996 Anthony Green <green@rtl.cygnus.com>
-
- * README (NOTE): Added n32 notes.
-
- * Makefile.am: Added test production.
- * Makefile: Rebuilt
-
- * README: spell checked!
-
- * configure.in (VERSION): Boosted rev to 1.01
- * configure: Rebuilt.
-
-Mon Oct 7 15:50:22 1996 Anthony Green <green@rtl.cygnus.com>
-
- * configure.in: Added nasty bit to support SGI tools.
- * configure: Rebuilt.
-
- * README: Added SGI notes. Added note about automake bug.
-
-Mon Oct 7 11:00:28 1996 Anthony Green <green@hoser.cygnus.com>
-
- * README: Rewrote intro, and fixed examples.
-
-Fri Oct 4 10:19:55 1996 Anthony Green <green@hoser.cygnus.com>
-
- * configure.in: -D$TARGET is no longer used as a compiler switch.
- It is now inserted into ffi.h at configure time.
- * configure: Rebuilt.
-
- * FFI_ABI and FFI_STATUS are now ffi_abi and ffi_status.
-
-Thu Oct 3 13:47:34 1996 Anthony Green <green@hoser.cygnus.com>
-
- * README, LICENSE: Created. Wrote some docs.
-
- * configure.in: Don't barf on i586-unknown-linuxaout.
- Added EXTRADIST code for "make dist".
- * configure: Rebuilt.
-
- * */Makefile.in: Rebuilt with patched automake.
-
-Tue Oct 1 17:12:25 1996 Anthony Green <green@rtl.cygnus.com>
-
- * Makefile.am, aclocal.m4, config.guess, config.sub,
- configure.in, fficonfig.h.in, install-sh, mkinstalldirs,
- stamp-h.in: Created
- * Makefile.in, configure: Generated
-
---- libffi/include --------------------------------------------------------
-
-Tue Feb 24 13:09:36 1998 Anthony Green <green@gerbil.cygnus.com>
-
- * ffi_mips.h: Updated FFI_TYPE_STRUCT_* values based on
- ffi.h.in changes. This is a work-around for SGI's "simple"
- assembler.
-
-Sun Feb 22 00:51:55 1998 Geoff Keating <geoffk@ozemail.com.au>
-
- * ffi.h.in: PowerPC support.
-
-1998-02-14 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de>
-
- * ffi.h.in: Add m68k support.
- (FFI_TYPE_LONGDOUBLE): Make it a separate value.
-
-Tue Feb 10 20:55:16 1998 Richard Henderson <rth@cygnus.com>
-
- * ffi.h.in (SIZEOF_ARG): Use a pointer type by default.
-
- * ffi.h.in: Alpha support.
-
-Fri Nov 22 06:48:45 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.h.in, ffi_common.h: Cygnus Support -> Cygnus Solutions.
-
-Wed Nov 20 22:31:01 1996 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.h.in: Added ffi_type_void definition.
-
-Tue Oct 29 12:22:40 1996 Anthony Green <green@rtl.cygnus.com>
-
- * Makefile.am (hack_DATA): Always install ffi_mips.h.
-
- * ffi.h.in: Removed FFI_DEBUG. It's now in the correct
- place (acconfig.h).
- Added #include <stddef.h> for size_t definition.
-
-Tue Oct 15 17:23:35 1996 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.h.in, ffi_common.h, ffi_mips.h: More clean up.
- Commented out #define of FFI_DEBUG.
-
-Tue Oct 15 13:01:06 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi_common.h: Added bool definition.
-
- * ffi.h.in, ffi_common.h: Clean up based on LCLint output.
- Added funny /*@...@*/ comments to annotate source.
-
-Mon Oct 14 12:29:23 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.h.in: Interface changes based on feedback from Jim
- Blandy.
-
-Fri Oct 11 16:49:35 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.h.in: Small change for sparc support.
-
-Thu Oct 10 14:53:37 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi_mips.h: Added FFI_TYPE_STRUCT_* definitions for
- special structure return types.
-
-Wed Oct 9 13:55:57 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.h.in: Added SIZEOF_ARG definition for X86
-
-Tue Oct 8 11:40:36 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.h.in (FFI_FN): Added macro for eliminating compiler warnings.
- Use it to case your function pointers to the proper type.
-
- * ffi_mips.h (SIZEOF_ARG): Added magic to fix type promotion bug.
-
- * Makefile.am (EXTRA_DIST): Added ffi_mips.h to EXTRA_DIST.
- * Makefile: Rebuilt.
-
- * ffi_mips.h: Created. Moved all common mips definitions here.
-
-Mon Oct 7 10:58:12 1996 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.h.in: The SGI assember is very picky about parens. Redefined
- some macros to avoid problems.
-
- * ffi.h.in: Added FFI_DEFAULT_ABI definitions. Also added
- externs for pointer, and 64bit integral ffi_types.
-
-Fri Oct 4 09:51:37 1996 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.h.in: Added FFI_ABI member to ffi_cif and changed
- function prototypes accordingly.
- Added #define @TARGET@. Now programs including ffi.h don't
- have to specify this themselves.
-
-Thu Oct 3 15:36:44 1996 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.h.in: Changed ffi_prep_cif's values from void* to void**
-
- * Makefile.am (EXTRA_DIST): Added EXTRA_DIST for "make dist"
- to work.
- * Makefile.in: Regenerated.
-
-Wed Oct 2 10:16:59 1996 Anthony Green <green@hoser.cygnus.com>
-
- * Makefile.am: Created
- * Makefile.in: Generated
-
- * ffi_common.h: Added rcsid comment
-
-Tue Oct 1 17:13:51 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.h.in, ffi_common.h: Created
-
---- libffi/src ------------------------------------------------------------
-
-Mon Oct 5 02:17:50 1998 Anthony Green <green@cygnus.com>
-
- * arm/ffi.c, arm/sysv.S: Created.
-
- * Makefile.am: Added arm files.
- * Makefile.in: Rebuilt.
-
-Mon Oct 5 01:41:38 1998 Anthony Green <green@rtl.cygnus.com>
-
- * Makefile.am (libffi_la_LDFLAGS): Incremented revision.
-
-Sun Oct 4 16:27:17 1998 Anthony Green <green@cygnus.com>
-
- * alpha/osf.S (ffi_call_osf): Patch for DU assembler.
-
- * ffitest.c (main): long long and long double return values work
- for x86.
-
-Fri Apr 17 11:50:58 1998 Anthony Green <green@hoser.cygnus.com>
-
- * Makefile.in: Rebuilt.
-
- * ffitest.c (main): Floating point tests not executed for systems
- with broken lond double (SunOS 4 w/ GCC).
-
- * types.c: Fixed x86 alignment info for long long types.
-
-Thu Apr 16 07:15:28 1998 Anthony Green <green@ada.cygnus.com>
-
- * ffitest.c: Added more notes about GCC bugs under Irix 6.
-
-Wed Apr 15 08:42:22 1998 Anthony Green <green@hoser.cygnus.com>
-
- * ffitest.c (struct5): New test function.
- (main): New test with struct5.
-
-Thu Mar 5 10:48:11 1998 Anthony Green <green@tootie.to.cygnus.com>
-
- * prep_cif.c (initialize_aggregate): Fix assertion for
- nested structures.
-
-Tue Feb 24 16:33:41 1998 Anthony Green <green@hoser.cygnus.com>
-
- * prep_cif.c (ffi_prep_cif): Added long double support for sparc.
-
-Sun Feb 22 00:52:18 1998 Geoff Keating <geoffk@ozemail.com.au>
-
- * powerpc/asm.h: New file.
- * powerpc/ffi.c: New file.
- * powerpc/sysv.S: New file.
- * Makefile.am: PowerPC port.
- * ffitest.c (main): Allow all tests to run even in presence of gcc
- bug on PowerPC.
-
-1998-02-17 Anthony Green <green@hoser.cygnus.com>
-
- * mips/ffi.c: Fixed comment typo.
-
- * x86/ffi.c (ffi_prep_cif_machdep), x86/sysv.S (retfloat):
- Fixed x86 long double return handling.
-
- * types.c: Fixed x86 long double alignment info.
-
-1998-02-14 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de>
-
- * types.c: Add m68k support.
-
- * ffitest.c (floating): Add long double parameter.
- (return_ll, ldblit): New functions to test long long and long
- double return value.
- (main): Fix type error in assignment of ts[1-4]_type.elements.
- Add tests for long long and long double arguments and return
- values.
-
- * prep_cif.c (ffi_prep_cif) [M68K]: Don't allocate argument for
- struct value pointer.
-
- * m68k/ffi.c, m68k/sysv.S: New files.
- * Makefile.am: Add bits for m68k port. Add kludge to work around
- automake deficiency.
- (test): Don't require "." in $PATH.
- * Makefile.in: Rebuilt.
-
-Wed Feb 11 07:36:50 1998 Anthony Green <green@hoser.cygnus.com>
-
- * Makefile.in: Rebuilt.
-
-Tue Feb 10 20:56:00 1998 Richard Henderson <rth@cygnus.com>
-
- * alpha/ffi.c, alpha/osf.S: New files.
- * Makefile.am: Alpha port.
-
-Tue Nov 18 14:12:07 1997 Anthony Green <green@hoser.cygnus.com>
-
- * mips/ffi.c (ffi_prep_cif_machdep): Initialize rstruct_flag
- for n32.
-
-Tue Jun 3 17:18:20 1997 Anthony Green <green@hoser.cygnus.com>
-
- * ffitest.c (main): Added hack to get structure tests working
- correctly.
-
-Sat May 10 19:06:42 1997 Tom Tromey <tromey@cygnus.com>
-
- * Makefile.in: Rebuilt.
- * Makefile.am (EXTRA_DIST): Explicitly list all distributable
- files in subdirs.
- (VERSION, CC): Removed.
-
-Thu May 8 17:19:01 1997 Anthony Green <green@hoser.cygnus.com>
-
- * Makefile.am: Many changes for new automake and libtool.
- * Makefile.in: Rebuilt.
-
-Fri Nov 22 06:57:56 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffitest.c (main): Fixed test case for non mips machines.
-
-Wed Nov 20 22:31:59 1996 Anthony Green <green@hoser.cygnus.com>
-
- * types.c: Added ffi_type_void declaration.
-
-Tue Oct 29 13:07:19 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffitest.c (main): Fixed character constants.
- (main): Emit warning for structure test 3 failure on Sun.
-
- * Makefile.am (VPATH): Fixed VPATH def'n so automake won't
- strip it out.
- Moved distdir hack from libffi to automake.
- (ffitest): Added missing -c for $(COMPILE) (change in automake).
- * Makefile.in: Rebuilt.
-
-Tue Oct 15 13:08:20 1996 Anthony Green <green@hoser.cygnus.com>
-
- * Makefile.am: Added "make lint" production.
- * Makefile.in: Rebuilt.
-
- * prep_cif.c (STACK_ARG_SIZE): Improved STACK_ARG_SIZE macro.
- Clean up based on LCLint output. Added funny /*@...@*/ comments to
- annotate source.
-
- * ffitest.c, debug.c: Cleaned up code.
-
-Mon Oct 14 12:26:56 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffitest.c: Changes based on interface changes.
-
- * prep_cif.c (ffi_prep_cif): Cleaned up interface based on
- feedback from Jim Blandy.
-
-Fri Oct 11 15:53:18 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffitest.c: Reordered tests while porting to sparc.
- Made changes to handle lame structure passing for sparc.
- Removed calls to fflush().
-
- * prep_cif.c (ffi_prep_cif): Added special case for sparc
- aggregate type arguments.
-
-Thu Oct 10 09:56:51 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffitest.c (main): Added structure passing/returning tests.
-
- * prep_cif.c (ffi_prep_cif): Perform proper initialization
- of structure return types if needed.
- (initialize_aggregate): Bug fix
-
-Wed Oct 9 16:04:20 1996 Anthony Green <green@rtl.cygnus.com>
-
- * types.c: Added special definitions for x86 (double doesn't
- need double word alignment).
-
- * ffitest.c: Added many tests
-
-Tue Oct 8 09:19:22 1996 Anthony Green <green@rtl.cygnus.com>
-
- * prep_cif.c (ffi_prep_cif): Fixed assertion.
-
- * debug.c (ffi_assert): Must return a non void now.
-
- * Makefile.am: Added test production.
- * Makefile: Rebuilt.
-
- * ffitest.c (main): Created.
-
- * types.c: Created. Stripped common code out of */ffi.c.
-
- * prep_cif.c: Added missing stdlib.h include.
-
- * debug.c (ffi_type_test): Used "a" to eliminate compiler
- warnings in non-debug builds. Included ffi_common.h.
-
-Mon Oct 7 15:36:42 1996 Anthony Green <green@rtl.cygnus.com>
-
- * Makefile.am: Added a rule for .s -> .o
- This is required by the SGI compiler.
- * Makefile: Rebuilt.
-
-Fri Oct 4 09:51:08 1996 Anthony Green <green@hoser.cygnus.com>
-
- * prep_cif.c (initialize_aggregate): Moved abi specification
- to ffi_prep_cif().
-
-Thu Oct 3 15:37:37 1996 Anthony Green <green@hoser.cygnus.com>
-
- * prep_cif.c (ffi_prep_cif): Changed values from void* to void**.
- (initialize_aggregate): Fixed aggregate type initialization.
-
- * Makefile.am (EXTRA_DIST): Added support code for "make dist".
- * Makefile.in: Regenerated.
-
-Wed Oct 2 11:41:57 1996 Anthony Green <green@hoser.cygnus.com>
-
- * debug.c, prep_cif: Created.
-
- * Makefile.am: Added debug.o and prep_cif.o to OBJ.
- * Makefile.in: Regenerated.
-
- * Makefile.am (INCLUDES): Added missing -I../include
- * Makefile.in: Regenerated.
-
-Tue Oct 1 17:11:51 1996 Anthony Green <green@rtl.cygnus.com>
-
- * error.c, Makefile.am: Created.
- * Makefile.in: Generated.
-
---- libffi/src/x86 --------------------------------------------------------
-
-Sun Oct 4 16:27:17 1998 Anthony Green <green@cygnus.com>
-
- * sysv.S (retlongdouble): Fixed long long return value support.
- * ffi.c (ffi_prep_cif_machdep): Ditto.
-
-Wed May 13 04:30:33 1998 Anthony Green <green@raft.ppp.tsoft.net>
-
- * ffi.c (ffi_prep_cif_machdep): Fixed long double return value
- support.
-
-Wed Apr 15 08:43:20 1998 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.c (ffi_prep_args): small struct support was missing.
-
-Thu May 8 16:53:58 1997 Anthony Green <green@hoser.cygnus.com>
-
- * objects.mak: Removed.
-
-Mon Dec 2 15:12:58 1996 Tom Tromey <tromey@cygnus.com>
-
- * sysv.S: Use .balign, for a.out Linux boxes.
-
-Tue Oct 15 13:06:50 1996 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.c: Clean up based on LCLint output.
- Added funny /*@...@*/ comments to annotate source.
-
-Fri Oct 11 16:43:38 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.c (ffi_call): Added assertion for bad ABIs.
-
-Wed Oct 9 13:57:27 1996 Anthony Green <green@rtl.cygnus.com>
-
- * sysv.S (retdouble): Fixed double return problems.
-
- * ffi.c (ffi_call): Corrected fn arg definition.
- (ffi_prep_cif_machdep): Fixed double return problems
-
-Tue Oct 8 12:12:49 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.c: Moved ffi_type definitions to types.c.
- (ffi_prep_args): Fixed type promotion bug.
-
-Mon Oct 7 15:53:06 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.c (FFI_*_TYPEDEF): Removed redundant ';'
-
-Fri Oct 4 09:54:53 1996 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.c (ffi_call): Removed FFI_ABI arg, and swapped
- remaining args.
-
-Wed Oct 2 10:07:05 1996 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.c, sysv.S, objects.mak: Created.
- (ffi_prep_cif): cif->rvalue no longer initialized to NULL.
- (ffi_prep_cif_machdep): Moved machine independent cif processing
- to src/prep_cif.c. Introduced ffi_prep_cif_machdep().
-
---- libffi/src/mips -------------------------------------------------------
-
-Tue Feb 17 17:18:07 1998 Anthony Green <green@hoser.cygnus.com>
-
- * o32.S: Fixed typo in comment.
-
- * ffi.c (ffi_prep_cif_machdep): Fixed argument processing.
-
-Thu May 8 16:53:58 1997 Anthony Green <green@hoser.cygnus.com>
-
- * o32.s, n32.s: Wrappers for SGI tool support.
-
- * objects.mak: Removed.
-
-Tue Oct 29 14:37:45 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.c (ffi_prep_args): Changed int z to size_t z.
-
-Tue Oct 15 13:17:25 1996 Anthony Green <green@hoser.cygnus.com>
-
- * n32.S: Fixed bad stack munging.
-
- * ffi.c: Moved prototypes for ffi_call_?32() to here from
- ffi_mips.h because extended_cif is not defined in ffi_mips.h.
-
-Mon Oct 14 12:42:02 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.c: Interface changes based on feedback from Jim Blandy.
-
-Thu Oct 10 11:22:16 1996 Anthony Green <green@rtl.cygnus.com>
-
- * n32.S, ffi.c: Lots of changes to support passing and
- returning structures with the n32 calling convention.
-
- * n32.S: Fixed fn pointer bug.
-
- * ffi.c (ffi_prep_cif_machdep): Fix for o32 structure
- return values.
- (ffi_prep_args): Fixed n32 structure passing when structures
- partially fit in registers.
-
-Wed Oct 9 13:49:25 1996 Anthony Green <green@rtl.cygnus.com>
-
- * objects.mak: Added n32.o.
-
- * n32.S: Created.
-
- * ffi.c (ffi_prep_args): Added magic to support proper
- n32 processing.
-
-Tue Oct 8 10:37:35 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.c: Moved ffi_type definitions to types.c.
- (ffi_prep_args): Fixed type promotion bug.
-
- * o32.S: This code is only built for o32 compiles.
- A lot of the #define cruft has moved to ffi_mips.h.
-
- * ffi.c (ffi_prep_cif_machdep): Fixed arg flags. Second arg
- is only processed if the first is either a float or double.
-
-Mon Oct 7 15:33:59 1996 Anthony Green <green@rtl.cygnus.com>
-
- * o32.S: Modified to compile under each of o32, n32 and n64.
-
- * ffi.c (FFI_*_TYPEDEF): Removed redundant ';'
-
-Fri Oct 4 09:53:25 1996 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.c (ffi_call): Removed FFI_ABI arg, and swapped
- remaining args.
-
-Wed Oct 2 17:41:22 1996 Anthony Green <green@rtl.cygnus.com>
-
- * o32.S: Removed crufty definitions.
-
-Wed Oct 2 12:53:42 1996 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.c (ffi_prep_cif): cif->rvalue no longer initialized to NULL.
- (ffi_prep_cif_machdep): Moved all machine independent cif processing
- to src/prep_cif.c. Introduced ffi_prep_cif_machdep. Return types
- of FFI_TYPE_STRUCT are no different than FFI_TYPE_INT.
-
-Tue Oct 1 17:11:02 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.c, o32.S, object.mak: Created
-
---- libffi/src/sparc ------------------------------------------------------
-
-Tue Feb 24 16:33:18 1998 Anthony Green <green@hoser.cygnus.com>
-
- * ffi.c (ffi_prep_args): Added long double support.
-
-Thu May 8 16:53:58 1997 Anthony Green <green@hoser.cygnus.com>
-
- * objects.mak: Removed.
-
-Thu May 1 16:07:56 1997 Anthony Green <green@hoser.cygnus.com>
-
- * v8.S: Fixed minor portability problem reported by
- Russ McManus <mcmanr@eq.gs.com>.
-
-Tue Nov 26 14:12:43 1996 Anthony Green <green@csk3.cygnus.com>
-
- * v8.S: Used STACKFRAME define elsewhere.
-
- * ffi.c (ffi_prep_args): Zero out space when USING_PURIFY
- is set.
- (ffi_prep_cif_machdep): Allocate the correct stack frame
- space for functions with < 6 args.
-
-Tue Oct 29 15:08:55 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.c (ffi_prep_args): int z is now size_t z.
-
-Mon Oct 14 13:31:24 1996 Anthony Green <green@rtl.cygnus.com>
-
- * v8.S (ffi_call_V8): Gordon rewrites this again. It looks
- great now.
-
- * ffi.c (ffi_call): The comment about hijacked registers
- is no longer valid after gordoni hacked v8.S.
-
- * v8.S (ffi_call_V8): Rewrote with gordoni. Much simpler.
-
- * v8.S, ffi.c: ffi_call() had changed to accept more than
- two args, so v8.S had to change (because it hijacks incoming
- arg registers).
-
- * ffi.c: Interface changes based on feedback from Jim Blandy.
-
-Thu Oct 10 17:48:16 1996 Anthony Green <green@rtl.cygnus.com>
-
- * ffi.c, v8.S, objects.mak: Created.
-
-
+Libffi change logs used to be maintained in separate ChangeLog files.
+These days we generate them directly from the git commit messages.
+The old ChangeLog files are saved here in order to maintain the historical
+record.
+
+=============================================================================
+From the old ChangeLog.libffi-3.1 file...
+
+2014-03-16 Josh Triplett <josh@joshtriplett.org>
+
+ * ChangeLog: Archive to ChangeLog.libffi-3.1 and delete. Future
+ changelogs will come from git, with autogenerated snapshots shipped in
+ distributed tarballs.
+
+2014-03-16 Josh Triplett <josh@joshtriplett.org>
+
+ Add support for stdcall, thiscall, and fastcall on non-Windows
+ x86-32.
+
+ Linux supports the stdcall calling convention, either via
+ functions explicitly declared with the stdcall attribute, or via
+ code compiled with -mrtd which effectively makes stdcall the
+ default.
+
+ This introduces FFI_STDCALL, FFI_THISCALL, and FFI_FASTCALL on
+ non-Windows x86-32 platforms, as non-default calling conventions.
+
+ * Makefile.am: Compile in src/x86/win32.S on non-Windows x86-32.
+ * src/x86/ffitarget.h: Add FFI_STDCALL, FFI_THISCALL, and
+ FFI_FASTCALL on non-Windows x86-32. Increase trampoline size to
+ accomodate these calling conventions, and unify some ifdeffery.
+ * src/x86/ffi.c: Add support for FFI_STDCALL, FFI_THISCALL, and
+ FFI_FASTCALL on non-Windows x86-32 platforms; update ifdeffery.
+ * src/x86/win32.S: Support compiling on non-Windows x86-32
+ platforms. On those platforms, avoid redefining the SYSV symbols
+ already provided by src/x86/sysv.S.
+ * testsuite/libffi.call/closure_stdcall.c: Run on non-Windows.
+ #define __stdcall if needed.
+ * testsuite/libffi.call/closure_thiscall.c: Run on non-Windows.
+ #define __fastcall if needed.
+ * testsuite/libffi.call/fastthis1_win32.c: Run on non-Windows.
+ * testsuite/libffi.call/fastthis2_win32.c: Ditto.
+ * testsuite/libffi.call/fastthis3_win32.c: Ditto.
+ * testsuite/libffi.call/many2_win32.c: Ditto.
+ * testsuite/libffi.call/many_win32.c: Ditto.
+ * testsuite/libffi.call/strlen2_win32.c: Ditto.
+ * testsuite/libffi.call/strlen_win32.c: Ditto.
+ * testsuite/libffi.call/struct1_win32.c: Ditto.
+ * testsuite/libffi.call/struct2_win32.c: Ditto.
+
+2014-03-16 Josh Triplett <josh@joshtriplett.org>
+
+ * prep_cif.c: Remove unnecessary ifdef for X86_WIN32.
+ ffi_prep_cif_core had a special case for X86_WIN32, checking for
+ FFI_THISCALL in addition to the FFI_FIRST_ABI-to-FFI_LAST_ABI
+ range before returning FFI_BAD_ABI. However, on X86_WIN32,
+ FFI_THISCALL already falls in that range, making the special case
+ unnecessary. Remove it.
+
+2014-03-16 Josh Triplett <josh@joshtriplett.org>
+
+ * testsuite/libffi.call/closure_stdcall.c,
+ testsuite/libffi.call/closure_thiscall.c: Remove fragile stack
+ pointer checks. These files included inline assembly to save the
+ stack pointer before and after the call, and compare the values.
+ However, compilers can and do leave the stack in different states
+ for these two pieces of inline assembly, such as by saving a
+ temporary value on the stack across the call; observed with gcc
+ -Os, and verified as spurious through careful inspection of
+ disassembly.
+
+2014-03-16 Josh Triplett <josh@joshtriplett.org>
+
+ * testsuite/libffi.call/many.c: Avoid spurious failure due to
+ excess floating-point precision.
+ * testsuite/libffi.call/many_win32.c: Ditto.
+
+2014-03-16 Josh Triplett <josh@joshtriplett.org>
+
+ * libtool-ldflags: Re-add.
+
+2014-03-16 Josh Triplett <josh@joshtriplett.org>
+
+ * Makefile.in, aclocal.m4, compile, config.guess, config.sub,
+ configure, depcomp, include/Makefile.in, install-sh,
+ libtool-ldflags, ltmain.sh, m4/libtool.m4, m4/ltoptions.m4,
+ m4/ltsugar.m4, m4/ltversion.m4, m4/lt~obsolete.m4,
+ man/Makefile.in, mdate-sh, missing, testsuite/Makefile.in: Delete
+ autogenerated files from version control.
+ * .gitignore: Add autogenerated files.
+ * autogen.sh: New script to generate the autogenerated files.
+ * README: Document requirement to run autogen.sh when building
+ directly from version control.
+ * .travis.yml: Run autogen.sh
+
+2014-03-14 Anthony Green <green@moxielogic.com>
+
+ * configure, Makefile.in: Rebuilt.
+
+2014-03-10 Mike Hommey <mh+mozilla@glandium.org>
+
+ * configure.ac: Allow building for mipsel with Android NDK r8.
+ * Makefile.am (AM_MAKEFLAGS): Replace double quotes with single
+ quotes.
+
+2014-03-10 Landry Breuil <landry@openbsd.org>
+
+ * configure.ac: Ensure the linker supports @unwind sections in libffi.
+
+2014-03-01 Anthony Green <green@moxielogic.com>
+
+ * Makefile.am (EXTRA_DIST): Replace old scripts with
+ generate-darwin-source-and-headers.py.
+ * Makefile.in: Rebuilt.
+
+2014-02-28 Anthony Green <green@moxielogic.com>
+
+ * Makefile.am (AM_CFLAGS): Reintroduce missing -DFFI_DEBUG for
+ --enable-debug builds.
+ * Makefile.in: Rebuilt.
+
+2014-02-28 Makoto Kato <m_kato@ga2.so-net.ne.jp>
+
+ * src/closures.c: Fix build failure when using clang for Android.
+
+2014-02-28 Marcin Wojdyr <wojdyr@gmail.com>
+
+ * libffi.pc.in (toolexeclibdir): use -L${toolexeclibdir} instead
+ of -L${libdir}.
+
+2014-02-28 Paulo Pizarro <paulo.pizarro@gmail.com>
+
+ * src/bfin/sysv.S: Calling functions in shared libraries requires
+ considering the GOT.
+
+2014-02-28 Josh Triplett <josh@joshtriplett.org>
+
+ * src/x86/ffi64.c (classify_argument): Handle case where
+ FFI_TYPE_LONGDOUBLE == FFI_TYPE_DOUBLE.
+
+2014-02-28 Anthony Green <green@moxielogic.com>
+
+ * ltmain.sh: Generate with libtool-2.4.2.418.
+ * m4/libtool.m4, m4/ltoptions.m4, m4/ltversion.m4: Ditto.
+ * configure: Rebuilt.
+
+2014-02-28 Dominik Vogt <vogt@linux.vnet.ibm.com>
+
+ * configure.ac (AC_ARG_ENABLE struct): Fix typo in help
+ message.
+ (AC_ARG_ENABLE raw_api): Ditto.
+ * configure, fficonfig.h.in: Rebuilt.
+
+2014-02-28 Will Newton <will.newton@linaro.org>
+
+ * src/arm/sysv.S: Initialize IP register with FP.
+
+2014-02-28 Yufeng Zhang <yufeng.zhang@arm.com>
+
+ * src/aarch64/sysv.S (ffi_closure_SYSV): Use x29 as the
+ main CFA reg; update cfi_rel_offset.
+
+2014-02-15 Marcus Comstedt <marcus@mc.pp.se>
+
+ * src/powerpc/ffi_linux64.c, src/powerpc/linux64_closure.S: Remove
+ assumption on contents of r11 in closure.
+
+2014-02-09 Heiher <r@hev.cc>
+
+ * src/mips/n32.S: Fix call floating point va function.
+
+2014-01-21 Zachary Waldowski <zach@waldowski.me>
+
+ * src/aarch64/ffi.c: Fix missing semicolons on assertions under
+ debug mode.
+
+2013-12-30 Zachary Waldowski <zach@waldowski.me>
+
+ * .gitignore: Exclude darwin_* generated source and build_* trees.
+ * src/aarch64/ffi.c, src/arm/ffi.c, src/x86/ffi.c: Inhibit Clang
+ previous prototype warnings.
+ * src/arm/ffi.c: Prevent NULL dereference, fix short type warning
+ * src/dlmalloc.c: Fix warnings from set_segment_flags return type,
+ and the native use of size_t for malloc on platforms
+ * src/arm/sysv.S: Use unified syntax. Clang clean-ups for
+ ARM_FUNC_START.
+ * generate-osx-source-and-headers.py: Remove.
+ * build-ios.sh: Remove.
+ * libffi.xcodeproj/project.pbxproj: Rebuild targets. Include
+ x86_64+aarch64 pieces in library. Export headers properly.
+ * src/x86/ffi64.c: More Clang warning clean-ups.
+ * src/closures.c (open_temp_exec_file_dir): Use size_t.
+ * src/prep_cif.c (ffi_prep_cif_core): Cast ALIGN result.
+ * src/aarch64/sysv.S: Use CNAME for global symbols. Only use
+ .size for ELF targets.
+ * src/aarch64/ffi.c: Clean up for double == long double. Clean up
+ from Clang warnings. Use Clang cache invalidation builtin. Use
+ size_t in place of unsigned in many places. Accommodate for
+ differences in Apple AArch64 ABI.
+
+2013-12-02 Daniel Rodríguez Troitiño <drodrigueztroitino@yahoo.es>
+
+ * generate-darwin-source-and-headers.py: Clean up, modernize,
+ merged version of previous scripts.
+
+2013-11-21 Anthony Green <green@moxielogic.com>
+
+ * configure, Makefile.in, include/Makefile.in, include/ffi.h.in,
+ man/Makefile.in, testsuite/Makefile.in, fficonfig.h.in: Rebuilt.
+
+2013-11-21 Alan Modra <amodra@gmail.com>
+
+ * Makefile.am (EXTRA_DIST): Add new src/powerpc files.
+ (nodist_libffi_la_SOURCES <POWERPC, POWERPC_FREEBSD>): Likewise.
+ * configure.ac (HAVE_LONG_DOUBLE_VARIANT): Define for powerpc.
+ * include/ffi.h.in (ffi_prep_types): Declare.
+ * src/prep_cif.c (ffi_prep_cif_core): Call ffi_prep_types.
+ * src/types.c (FFI_NONCONST_TYPEDEF): Define and use for
+ HAVE_LONG_DOUBLE_VARIANT.
+ * src/powerpc/ffi_powerpc.h: New file.
+ * src/powerpc/ffi.c: Split into..
+ * src/powerpc/ffi_sysv.c: ..new file, and..
+ * src/powerpc/ffi_linux64.c: ..new file, rewriting parts.
+ * src/powerpc/ffitarget.h (enum ffi_abi): Rewrite powerpc ABI
+ selection as bits controlling features.
+ * src/powerpc/linux64.S: For consistency, use POWERPC64 rather
+ than __powerpc64__.
+ * src/powerpc/linux64_closure.S: Likewise.
+ * src/powerpc/ppc_closure.S: Likewise. Move .note.FNU-stack
+ inside guard.
+ * src/powerpc/sysv.S: Likewise.
+ * configure: Regenerate.
+ * fficonfig.h.in: Regenerate.
+ * Makefile.in: Regenerate.
+
+2013-11-20 Alan Modra <amodra@gmail.com>
+
+ * src/powerpc/ffi.c (ffi_prep_cif_machdep_core): Use
+ NUM_FPR_ARG_REGISTERS64 and NUM_GPR_ARG_REGISTERS64 not their
+ 32-bit versions for 64-bit code.
+ * src/powerpc/linux64_closure.S: Don't use the return value area
+ as a parameter save area on ELFv2.
+
+2013-11-18 Iain Sandoe <iain@codesourcery.com>
+
+ * src/powerpc/darwin.S (EH): Correct use of pcrel FDE encoding.
+ * src/powerpc/darwin_closure.S (EH): Likewise. Modernise picbase
+ labels.
+
+2013-11-18 Anthony Green <green@moxielogic.com>
+
+ * src/arm/ffi.c (ffi_call): Hoist declaration of temp to top of
+ function.
+ * src/arm/ffi.c (ffi_closure_inner): Moderize function declaration
+ to appease compiler.
+ Thanks for Gregory P. Smith <greg@krypto.org>.
+
+2013-11-18 Anthony Green <green@moxielogic.com>
+
+ * README (tested): Mention PowerPC ELFv2.
+
+2013-11-16 Alan Modra <amodra@gmail.com>
+
+ * src/powerpc/ppc_closure.S: Move errant #endif to where it belongs.
+ Don't bl .Luint128.
+
+2013-11-16 Alan Modra <amodra@gmail.com>
+
+ * src/powerpc/ffi.c (ffi_prep_cif_machdep_core): Use #if _CALL_ELF
+ test to select parameter save sizing for ELFv2 vs. ELFv1.
+ * src/powerpc/ffitarget.h (FFI_V2_TYPE_FLOAT_HOMOG,
+ FFI_V2_TYPE_DOUBLE_HOMOG, FFI_V2_TYPE_SMALL_STRUCT): Define.
+ (FFI_TRAMPOLINE_SIZE): Define variant for ELFv2.
+ * src/powerpc/ffi.c (FLAG_ARG_NEEDS_PSAVE): Define.
+ (discover_homogeneous_aggregate): New function.
+ (ffi_prep_args64): Adjust start of param save area for ELFv2.
+ Handle homogenous floating point struct parms.
+ (ffi_prep_cif_machdep_core): Adjust space calculation for ELFv2.
+ Handle ELFv2 return values. Set FLAG_ARG_NEEDS_PSAVE. Handle
+ homogenous floating point structs.
+ (ffi_call): Increase size of smst_buffer for ELFv2. Handle ELFv2.
+ (flush_icache): Compile for ELFv2.
+ (ffi_prep_closure_loc): Set up ELFv2 trampoline.
+ (ffi_closure_helper_LINUX64): Don't return all structs directly
+ to caller. Handle homogenous floating point structs. Handle
+ ELFv2 struct return values.
+ * src/powerpc/linux64.S (ffi_call_LINUX64): Set up r2 for
+ ELFv2. Adjust toc save location. Call function pointer using
+ r12. Handle FLAG_RETURNS_SMST. Don't predict branches.
+ * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Set up r2
+ for ELFv2. Define ELFv2 versions of STACKFRAME, PARMSAVE, and
+ RETVAL. Handle possibly missing parameter save area. Handle
+ ELFv2 return values.
+ (.note.GNU-stack): Move inside outer #ifdef.
+
+2013-11-16 Alan Modra <amodra@gmail.com>
+
+ * src/powerpc/ffi.c (ffi_prep_cif_machdep): Revert 2013-02-08
+ change. Do not consume an int arg when returning a small struct
+ for FFI_SYSV ABI.
+ (ffi_call): Only use bounce buffer when FLAG_RETURNS_SMST.
+ Properly copy bounce buffer to destination.
+ * src/powerpc/sysv.S: Revert 2013-02-08 change.
+ * src/powerpc/ppc_closure.S: Remove stray '+'.
+
+2013-11-16 Alan Modra <amodra@gmail.com>
+
+ * src/powerpc/ffi.c (ffi_prep_args64): Align struct parameters
+ according to __STRUCT_PARM_ALIGN__.
+ (ffi_prep_cif_machdep_core): Likewise.
+ (ffi_closure_helper_LINUX64): Likewise.
+
+2013-11-16 Alan Modra <amodra@gmail.com>
+
+ * src/powerpc/linux64.S (ffi_call_LINUX64): Tweak restore of r28.
+ (.note.GNU-stack): Move inside outer #ifdef.
+ * src/powerpc/linux64_closure.S (STACKFRAME, PARMSAVE,
+ RETVAL): Define and use throughout.
+ (ffi_closure_LINUX64): Save fprs before buying stack.
+ (.note.GNU-stack): Move inside outer #ifdef.
+
+2013-11-16 Alan Modra <amodra@gmail.com>
+
+ * src/powerpc/ffitarget.h (FFI_TARGET_SPECIFIC_VARIADIC): Define.
+ (FFI_EXTRA_CIF_FIELDS): Define.
+ * src/powerpc/ffi.c (ffi_prep_args64): Save fprs as per the
+ ABI, not to both fpr and param save area.
+ (ffi_prep_cif_machdep_core): Renamed from ffi_prep_cif_machdep.
+ Keep initial flags. Formatting. Remove dead FFI_LINUX_SOFT_FLOAT
+ code.
+ (ffi_prep_cif_machdep, ffi_prep_cif_machdep_var): New functions.
+ (ffi_closure_helper_LINUX64): Pass floating point as per ABI,
+ not to both fpr and parameter save areas.
+
+ * libffi/testsuite/libffi.call/cls_double_va.c (main): Correct
+ function cast and don't call ffi_prep_cif.
+ * libffi/testsuite/libffi.call/cls_longdouble_va.c (main): Likewise.
+
+2013-11-15 Andrew Haley <aph@redhat.com>
+
+ * doc/libffi.texi (Closure Example): Fix the sample code.
+ * doc/libffi.info, doc/stamp-vti, doc/version.texi: Rebuilt.
+
+2013-11-15 Andrew Haley <aph@redhat.com>
+
+ * testsuite/libffi.call/va_struct1.c (main): Fix broken test.
+ * testsuite/libffi.call/cls_uint_va.c (cls_ret_T_fn): Likewise
+ * testsuite/libffi.call/cls_struct_va1.c (test_fn): Likewise.
+ * testsuite/libffi.call/va_1.c (main): Likewise.
+
+2013-11-14 David Schneider <david.schneider@bivab.de>
+
+ * src/arm/ffi.c: Fix register allocation for mixed float and
+ doubles.
+ * testsuite/libffi.call/cls_many_mixed_float_double.c: Testcase
+ for many mixed float and double arguments.
+
+2013-11-13 Alan Modra <amodra@gmail.com>
+
+ * doc/libffi.texi (Simple Example): Correct example code.
+ * doc/libffi.info, doc/stamp-vti, doc/version.texi: Rebuilt.
+
+2013-11-13 Anthony Green <green@moxielogic.com>
+
+ * include/ffi_common.h: Respect HAVE_ALLOCA_H for GNU compiler
+ based build. (Thanks to tmr111116 on github)
+
+2013-11-09 Anthony Green <green@moxielogic.com>
+
+ * m4/libtool.m4: Refresh.
+ * configure, Makefile.in: Rebuilt.
+ * README: Add more notes about next release.
+
+2013-11-09 Shigeharu TAKENO <shige@iee.niit.ac.jp>
+
+ * m4/ax_gcc_archflag.m4 (ax_gcc_arch): Don't recognize
+ UltraSPARC-IIi as ultrasparc3.
+
+2013-11-06 Mark Kettenis <kettenis@gnu.org>
+
+ * src/x86/freebsd.S (ffi_call_SYSV): Align the stack pointer to
+ 16-bytes.
+
+2013-11-06 Konstantin Belousov <kib@freebsd.org>
+
+ * src/x86/freebsd.S (ffi_closure_raw_SYSV): Mark the assembler
+ source as not requiring executable stack.
+
+2013-11-02 Anthony Green <green@moxielogic.com>
+
+ * doc/libffi.texi (The Basics): Clarify return value buffer size
+ requirements. Also, NULL result buffer pointers are no longer
+ supported.
+ * doc/libffi.info: Rebuilt.
+
+2013-11-02 Mischa Jonker <mjonker@synopsys.com>
+
+ * Makefile.am (nodist_libffi_la_SOURCES): Fix build error.
+ * Makefile.in: Rebuilt.
+
+2013-11-02 David Schneider <david.schneider@bivab.de>
+
+ * src/arm/ffi.c: more robust argument handling for closures on arm hardfloat
+ * testsuite/libffi.call/many_mixed.c: New file.
+ * testsuite/libffi.call/cls_many_mixed_args.c: More tests.
+
+2013-11-02 Vitaly Budovski
+
+ * src/x86/ffi.c (ffi_prep_cif_machdep): Don't align stack for win32.
+
+2013-10-23 Mark H Weaver <mhw@netris.org>
+
+ * src/mips/ffi.c: Fix handling of uint32_t arguments on the
+ MIPS N32 ABI.
+
+2013-10-13 Sandra Loosemore <sandra@codesourcery.com>
+
+ * README: Add Nios II to table of supported platforms.
+ * Makefile.am (EXTRA_DIST): Add nios2 files.
+ (nodist_libffi_la_SOURCES): Likewise.
+ * Makefile.in: Regenerated.
+ * configure.ac (nios2*-linux*): New host.
+ (NIOS2): Add AM_CONDITIONAL.
+ * configure: Regenerated.
+ * src/nios2/ffi.c: New.
+ * src/nios2/ffitarget.h: New.
+ * src/nios2/sysv.S: New.
+ * src/prep_cif.c (initialize_aggregate): Handle extra structure
+ alignment via FFI_AGGREGATE_ALIGNMENT.
+ (ffi_prep_cif_core): Conditionalize structure return for NIOS2.
+
+2013-10-10 Sandra Loosemore <sandra@codesourcery.com>
+
+ * testsuite/libffi.call/cls_many_mixed_args.c (cls_ret_double_fn):
+ Fix uninitialized variable.
+
+2013-10-11 Marcus Shawcroft <marcus.shawcroft@arm.com>
+
+ * testsuite/libffi.call/many.c (many): Replace * with +.
+
+2013-10-08 Ondřej Bílka <neleai@seznam.cz>
+
+ * src/aarch64/ffi.c, src/aarch64/sysv.S, src/arm/ffi.c,
+ src/arm/gentramp.sh, src/bfin/sysv.S, src/closures.c,
+ src/dlmalloc.c, src/ia64/ffi.c, src/microblaze/ffi.c,
+ src/microblaze/sysv.S, src/powerpc/darwin_closure.S,
+ src/powerpc/ffi.c, src/powerpc/ffi_darwin.c, src/sh/ffi.c,
+ src/tile/tile.S, testsuite/libffi.call/nested_struct11.c: Fix
+ spelling errors.
+
+2013-10-08 Anthony Green <green@moxielogic.com>
+
+ * aclocal.m4, compile, config.guess, config.sub, depcomp,
+ install-sh, mdate-sh, missing, texinfo.tex: Update from upstream.
+ * configure.ac: Update version to 3.0.14-rc0.
+ * Makefile.in, configure, Makefile.in, include/Makefile.in,
+ man/Makefile.in, testsuite/Makefile.in: Rebuilt.
+ * README: Mention M88K and VAX.
+
+2013-07-15 Miod Vallat <miod@openbsd.org>
+
+ * Makefile.am,
+ configure.ac,
+ src/m88k/ffi.c,
+ src/m88k/ffitarget.h,
+ src/m88k/obsd.S,
+ src/vax/elfbsd.S,
+ src/vax/ffi.c,
+ src/vax/ffitarget.h: Add m88k and vax support.
+
+2013-06-24 Alan Modra <amodra@gmail.com>
+
+ * src/powerpc/ffi.c (ffi_prep_args_SYSV): Move var declaration
+ before statements.
+ (ffi_prep_args64): Support little-endian.
+ (ffi_closure_helper_SYSV, ffi_closure_helper_LINUX64): Likewise.
+ * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Likewise.
+ * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Likewise.
+
+2013-06-12 Mischa Jonker <mjonker@synopsys.com>
+
+ * configure.ac: Add support for ARC.
+ * Makefile.am: Likewise.
+ * README: Add ARC details.
+ * src/arc/arcompact.S: New.
+ * src/arc/ffi.c: Likewise.
+ * src/arc/ffitarget.h: Likewise.
+
+2013-03-28 David Schneider <david.schneider@bivab.de>
+
+ * src/arm/ffi.c: Fix support for ARM hard-float calling convention.
+ * src/arm/sysv.S: call different methods for SYSV and VFP ABIs.
+ * testsuite/libffi.call/cls_many_mixed_args.c: testcase for a closure with
+ mixed arguments, many doubles.
+ * testsuite/libffi.call/many_double.c: testcase for calling a function using
+ more than 8 doubles.
+ * testcase/libffi.call/many.c: use absolute value to check result against an
+ epsilon
+
+2013-03-17 Anthony Green <green@moxielogic.com>
+
+ * README: Update for 3.0.13.
+ * configure.ac: Ditto.
+ * configure: Rebuilt.
+ * doc/*: Update version.
+
+2013-03-17 Dave Korn <dave.korn.cygwin@gmail.com>
+
+ * src/closures.c (is_emutramp_enabled
+ [!FFI_MMAP_EXEC_EMUTRAMP_PAX]): Move default definition outside
+ enclosing #if scope.
+
+2013-03-17 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Only modify toolexecdir in certain cases.
+ * configure: Rebuilt.
+
+2013-03-16 Gilles Talis <gilles.talis@gmail.com>
+
+ * src/powerpc/ffi.c (ffi_prep_args_SYSV): Don't use
+ fparg_count,etc on __NO_FPRS__ targets.
+
+2013-03-16 Alan Hourihane <alanh@fairlite.co.uk>
+
+ * src/m68k/sysv.S (epilogue): Don't use extb instruction on
+ m680000 machines.
+
+2013-03-16 Alex Gaynor <alex.gaynor@gmail.com>
+
+ * src/x86/ffi.c (ffi_prep_cif_machdep): Always align stack.
+
+2013-03-13 Markos Chandras <markos.chandras@imgtec.com>
+
+ * configure.ac: Add support for Imagination Technologies Meta.
+ * Makefile.am: Likewise.
+ * README: Add Imagination Technologies Meta details.
+ * src/metag/ffi.c: New.
+ * src/metag/ffitarget.h: Likewise.
+ * src/metag/sysv.S: Likewise.
+
+2013-02-24 Andreas Schwab <schwab@linux-m68k.org>
+
+ * doc/libffi.texi (Structures): Fix missing category argument of
+ @deftp.
+
+2013-02-11 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Update release number to 3.0.12.
+ * configure: Rebuilt.
+ * README: Update release info.
+
+2013-02-10 Anthony Green <green@moxielogic.com>
+
+ * README: Add Moxie.
+ * src/moxie/ffi.c: Created.
+ * src/moxie/eabi.S: Created.
+ * src/moxie/ffitarget.h: Created.
+ * Makefile.am (nodist_libffi_la_SOURCES): Add Moxie.
+ * Makefile.in: Rebuilt.
+ * configure.ac: Add Moxie.
+ * configure: Rebuilt.
+ * testsuite/libffi.call/huge_struct.c: Disable format string
+ warnings for moxie*-*-elf tests.
+
+2013-02-10 Anthony Green <green@moxielogic.com>
+
+ * Makefile.am (LTLDFLAGS): Fix reference.
+ * Makefile.in: Rebuilt.
+
+2013-02-10 Anthony Green <green@moxielogic.com>
+
+ * README: Update supported platforms. Update test results link.
+
+2013-02-09 Anthony Green <green@moxielogic.com>
+
+ * testsuite/libffi.call/negint.c: Remove forced -O2.
+ * testsuite/libffi.call/many2.c (foo): Remove GCCism.
+ * testsuite/libffi.call/ffitest.h: Add default PRIuPTR definition.
+
+ * src/sparc/v8.S (ffi_closure_v8): Import ancient ulonglong
+ closure return type fix developed by Martin v. Löwis for cpython
+ fork.
+
+2013-02-08 Andreas Tobler <andreast@fgznet.ch>
+
+ * src/powerpc/ffi.c (ffi_prep_cif_machdep): Fix small struct
+ support.
+ * src/powerpc/sysv.S: Ditto.
+
+2013-02-08 Anthony Green <green@moxielogic.com>
+
+ * testsuite/libffi.call/cls_longdouble.c: Remove xfail for
+ arm*-*-*.
+
+2013-02-08 Anthony Green <green@moxielogic.com>
+
+ * src/sparc/ffi.c (ffi_prep_closure_loc): Fix cache flushing for GCC.
+
+2013-02-08 Matthias Klose <doko@ubuntu.com>
+
+ * man/ffi_prep_cif.3: Clean up for debian linter.
+
+2013-02-08 Peter Bergner <bergner@vnet.ibm.com>
+
+ * src/powerpc/ffi.c (ffi_prep_args_SYSV): Account for FP args pushed
+ on the stack.
+
+2013-02-08 Anthony Green <green@moxielogic.com>
+
+ * Makefile.am (EXTRA_DIST): Add missing files.
+ * testsuite/Makefile.am (EXTRA_DIST): Ditto.
+ * Makefile.in: Rebuilt.
+
+2013-02-08 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Move sparc asm config checks to within functions
+ for compatibility with sun tools.
+ * configure: Rebuilt.
+ * src/sparc/ffi.c (ffi_prep_closure_loc): Flush cache on v9
+ systems.
+ * src/sparc/v8.S (ffi_flush_icache): Implement a sparc v9 cache
+ flusher.
+
+2013-02-08 Nathan Rossi <nathan.rossi@xilinx.com>
+
+ * src/microblaze/ffi.c (ffi_closure_call_SYSV): Fix handling of
+ small big-endian structures.
+ (ffi_prep_args): Ditto.
+
+2013-02-07 Anthony Green <green@moxielogic.com>
+
+ * src/sparc/v8.S (ffi_call_v8): Fix typo from last patch
+ (effectively hiding ffi_call_v8).
+
+2013-02-07 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Update bug reporting address.
+ * configure.in: Rebuild.
+
+ * src/sparc/v8.S (ffi_flush_icache): Out-of-line cache flusher for
+ Sun compiler.
+ * src/sparc/ffi.c (ffi_call): Remove warning.
+ Call ffi_flush_icache for non-GCC builds.
+ (ffi_prep_closure_loc): Use ffi_flush_icache.
+
+ * Makefile.am (EXTRA_DIST): Add libtool-ldflags.
+ * Makefile.in: Rebuilt.
+ * libtool-ldflags: New file.
+
+2013-02-07 Daniel Schepler <dschepler@gmail.com>
+
+ * configure.ac: Correctly identify x32 systems as 64-bit.
+ * m4/libtool.m4: Remove libtool expr error.
+ * aclocal.m4, configure: Rebuilt.
+
+2013-02-07 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Fix GCC usage test.
+ * configure: Rebuilt.
+ * README: Mention LLVM/GCC x86_64 issue.
+ * testsuite/Makefile.in: Rebuilt.
+
+2013-02-07 Anthony Green <green@moxielogic.com>
+
+ * testsuite/libffi.call/cls_double_va.c (main): Replace // style
+ comments with /* */ for xlc compiler.
+ * testsuite/libffi.call/stret_large.c (main): Ditto.
+ * testsuite/libffi.call/stret_large2.c (main): Ditto.
+ * testsuite/libffi.call/nested_struct1.c (main): Ditto.
+ * testsuite/libffi.call/huge_struct.c (main): Ditto.
+ * testsuite/libffi.call/float_va.c (main): Ditto.
+ * testsuite/libffi.call/cls_struct_va1.c (main): Ditto.
+ * testsuite/libffi.call/cls_pointer_stack.c (main): Ditto.
+ * testsuite/libffi.call/cls_pointer.c (main): Ditto.
+ * testsuite/libffi.call/cls_longdouble_va.c (main): Ditto.
+
+2013-02-06 Anthony Green <green@moxielogic.com>
+
+ * man/ffi_prep_cif.3: Clean up for debian lintian checker.
+
+2013-02-06 Anthony Green <green@moxielogic.com>
+
+ * Makefile.am (pkgconfigdir): Add missing pkgconfig install bits.
+ * Makefile.in: Rebuild.
+
+2013-02-02 Mark H Weaver <mhw@netris.org>
+
+ * src/x86/ffi64.c (ffi_call): Sign-extend integer arguments passed
+ via general purpose registers.
+
+2013-01-21 Nathan Rossi <nathan.rossi@xilinx.com>
+
+ * README: Add MicroBlaze details.
+ * Makefile.am: Add MicroBlaze support.
+ * configure.ac: Likewise.
+ * src/microblaze/ffi.c: New.
+ * src/microblaze/ffitarget.h: Likewise.
+ * src/microblaze/sysv.S: Likewise.
+
+2013-01-21 Nathan Rossi <nathan.rossi@xilinx.com>
+ * testsuite/libffi.call/return_uc.c: Fixed issue.
+
+2013-01-21 Chris Zankel <chris@zankel.net>
+
+ * README: Add Xtensa support.
+ * Makefile.am: Likewise.
+ * configure.ac: Likewise.
+ * Makefile.in Regenerate.
+ * configure: Likewise.
+ * src/prep_cif.c: Handle Xtensa.
+ * src/xtensa: New directory.
+ * src/xtensa/ffi.c: New file.
+ * src/xtensa/ffitarget.h: Ditto.
+ * src/xtensa/sysv.S: Ditto.
+
+2013-01-11 Anthony Green <green@moxielogic.com>
+
+ * src/powerpc/ffi_darwin.c (ffi_prep_args): Replace // style
+ comments with /* */ for xlc compiler.
+ * src/powerpc/aix.S (ffi_call_AIX): Ditto.
+ * testsuite/libffi.call/ffitest.h (allocate_mmap): Delete
+ deprecated inline function.
+ * testsuite/libffi.special/ffitestcxx.h: Ditto.
+ * README: Add update for AIX support.
+
+2013-01-11 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Robustify pc relative reloc check.
+ * m4/ax_cc_maxopt.m4: Don't -malign-double. This is an ABI
+ changing option for 32-bit x86.
+ * aclocal.m4, configure: Rebuilt.
+ * README: Update supported target list.
+
+2013-01-10 Anthony Green <green@moxielogic.com>
+
+ * README (tested): Add Compiler column to table.
+
+2013-01-10 Anthony Green <green@moxielogic.com>
+
+ * src/x86/ffi64.c (struct register_args): Make sse array and array
+ of unions for sunpro compiler compatibility.
+
+2013-01-10 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Test target platform size_t size. Handle both 32
+ and 64-bit builds for x86_64-* and i?86-* targets (allowing for
+ CFLAG option to change default settings).
+ * configure, aclocal.m4: Rebuilt.
+
+2013-01-10 Anthony Green <green@moxielogic.com>
+
+ * testsuite/libffi.special/special.exp: Only run exception
+ handling tests when using GNU compiler.
+
+ * m4/ax_compiler_vendor.m4: New file.
+ * configure.ac: Test for compiler vendor and don't use
+ AX_CFLAGS_WARN_ALL with the sun compiler.
+ * aclocal.m4, configure: Rebuilt.
+
+2013-01-10 Anthony Green <green@moxielogic.com>
+
+ * include/ffi_common.h: Don't use GCCisms to define types when
+ building with the SUNPRO compiler.
+
+2013-01-10 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Put local.exp in the right place.
+ * configure: Rebuilt.
+
+ * src/x86/ffi.c: Update comment about regparm function attributes.
+ * src/x86/sysv.S (ffi_closure_SYSV): The SUNPRO compiler requires
+ that all function arguments be passed on the stack (no regparm
+ support).
+
+2013-01-08 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Generate local.exp. This sets CC_FOR_TARGET
+ when we are using the vendor compiler.
+ * testsuite/Makefile.am (EXTRA_DEJAGNU_SITE_CONFIG): Point to
+ ../local.exp.
+ * configure, testsuite/Makefile.in: Rebuilt.
+
+ * testsuite/libffi.call/call.exp: Run tests with different
+ options, depending on whether or not we are using gcc or the
+ vendor compiler.
+ * testsuite/lib/libffi.exp (libffi-init): Set using_gcc based on
+ whether or not we are building/testing with gcc.
+
+2013-01-08 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Switch x86 solaris target to X86 by default.
+ * configure: Rebuilt.
+
+2013-01-08 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Fix test for read-only eh_frame.
+ * configure: Rebuilt.
+
+2013-01-08 Anthony Green <green@moxielogic.com>
+
+ * src/x86/sysv.S, src/x86/unix64.S: Only emit DWARF unwind info
+ when building with the GNU toolchain.
+ * testsuite/libffi.call/ffitest.h (CHECK): Fix for Solaris vendor
+ compiler.
+
+2013-01-07 Thorsten Glaser <tg@mirbsd.org>
+
+ * testsuite/libffi.call/cls_uchar_va.c,
+ testsuite/libffi.call/cls_ushort_va.c,
+ testsuite/libffi.call/va_1.c: Testsuite fixes.
+
+2013-01-07 Thorsten Glaser <tg@mirbsd.org>
+
+ * src/m68k/ffi.c (CIF_FLAGS_SINT8, CIF_FLAGS_SINT16): Define.
+ (ffi_prep_cif_machdep): Fix 8-bit and 16-bit signed calls.
+ * src/m68k/sysv.S (ffi_call_SYSV, ffi_closure_SYSV): Ditto.
+
+2013-01-04 Anthony Green <green@moxielogic.com>
+
+ * Makefile.am (AM_CFLAGS): Don't automatically add -fexceptions
+ and -Wall. This is set in the configure script after testing for
+ GCC.
+ * Makefile.in: Rebuilt.
+
+2013-01-02 rofl0r <https://github.com/rofl0r>
+
+ * src/powerpc/ffi.c (ffi_prep_cif_machdep): Fix build error on ppc
+ when long double == double.
+
+2013-01-02 Reini Urban <rurban@x-ray.at>
+
+ * Makefile.am (libffi_la_LDFLAGS): Add -no-undefined to LDFLAGS
+ (required for shared libs on cygwin/mingw).
+ * Makefile.in: Rebuilt.
+
+2012-10-31 Alan Modra <amodra@gmail.co>
+
+ * src/powerpc/linux64_closure.S: Add new ABI support.
+ * src/powerpc/linux64.S: Likewise.
+
+2012-10-30 Magnus Granberg <zorry@gentoo.org>
+ Pavel Labushev <pavel.labushev@runbox.ru>
+
+ * configure.ac: New options pax_emutramp
+ * configure, fficonfig.h.in: Regenerated
+ * src/closures.c: New function emutramp_enabled_check() and
+ checks.
+
+2012-10-30 Frederick Cheung <frederick.cheung@gmail.com>
+
+ * configure.ac: Enable FFI_MAP_EXEC_WRIT for Darwin 12 (mountain
+ lion) and future version.
+ * configure: Rebuild.
+
+2012-10-30 James Greenhalgh <james.greenhalgh at arm.com>
+ Marcus Shawcroft <marcus.shawcroft at arm.com>
+
+ * README: Add details of aarch64 port.
+ * src/aarch64/ffi.c: New.
+ * src/aarch64/ffitarget.h: Likewise.
+ * src/aarch64/sysv.S: Likewise.
+ * Makefile.am: Support aarch64.
+ * configure.ac: Support aarch64.
+ * Makefile.in, configure: Rebuilt.
+
+2012-10-30 James Greenhalgh <james.greenhalgh at arm.com>
+ Marcus Shawcroft <marcus.shawcroft at arm.com>
+
+ * testsuite/lib/libffi.exp: Add support for aarch64.
+ * testsuite/libffi.call/cls_struct_va1.c: New.
+ * testsuite/libffi.call/cls_uchar_va.c: Likewise.
+ * testsuite/libffi.call/cls_uint_va.c: Likewise.
+ * testsuite/libffi.call/cls_ulong_va.c: Likewise.
+ * testsuite/libffi.call/cls_ushort_va.c: Likewise.
+ * testsuite/libffi.call/nested_struct11.c: Likewise.
+ * testsuite/libffi.call/uninitialized.c: Likewise.
+ * testsuite/libffi.call/va_1.c: Likewise.
+ * testsuite/libffi.call/va_struct1.c: Likewise.
+ * testsuite/libffi.call/va_struct2.c: Likewise.
+ * testsuite/libffi.call/va_struct3.c: Likewise.
+
+2012-10-12 Walter Lee <walt@tilera.com>
+
+ * Makefile.am: Add TILE-Gx/TILEPro support.
+ * configure.ac: Likewise.
+ * Makefile.in: Regenerate.
+ * configure: Likewise.
+ * src/prep_cif.c (ffi_prep_cif_core): Handle TILE-Gx/TILEPro.
+ * src/tile: New directory.
+ * src/tile/ffi.c: New file.
+ * src/tile/ffitarget.h: Ditto.
+ * src/tile/tile.S: Ditto.
+
+2012-10-12 Matthias Klose <doko@ubuntu.com>
+
+ * generate-osx-source-and-headers.py: Normalize whitespace.
+
+2012-09-14 David Edelsohn <dje.gcc@gmail.com>
+
+ * configure: Regenerated.
+
+2012-08-26 Andrew Pinski <apinski@cavium.com>
+
+ PR libffi/53014
+ * src/mips/ffi.c (ffi_prep_closure_loc): Allow n32 with soft-float and n64 with
+ soft-float.
+
+2012-08-08 Uros Bizjak <ubizjak@gmail.com>
+
+ * src/s390/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test,
+ just return FFI_BAD_ABI when things are wrong.
+
+2012-07-18 H.J. Lu <hongjiu.lu@intel.com>
+
+ PR libffi/53982
+ PR libffi/53973
+ * src/x86/ffitarget.h: Check __ILP32__ instead of __LP64__ for x32.
+ (FFI_SIZEOF_JAVA_RAW): Defined to 4 for x32.
+
+2012-05-16 H.J. Lu <hongjiu.lu@intel.com>
+
+ * configure: Regenerated.
+
+2012-05-05 Nicolas Lelong
+
+ * libffi.xcodeproj/project.pbxproj: Fixes.
+ * README: Update for iOS builds.
+
+2012-04-23 Alexandre Keunecke I. de Mendonca <alexandre.keunecke@gmail.com>
+
+ * configure.ac: Add Blackfin/sysv support
+ * Makefile.am: Add Blackfin/sysv support
+ * src/bfin/ffi.c: Add Blackfin/sysv support
+ * src/bfin/ffitarget.h: Add Blackfin/sysv support
+
+2012-04-11 Anthony Green <green@moxielogic.com>
+
+ * Makefile.am (EXTRA_DIST): Add new script.
+ * Makefile.in: Rebuilt.
+
+2012-04-11 Zachary Waldowski <zwaldowski@gmail.com>
+
+ * generate-ios-source-and-headers.py,
+ libffi.xcodeproj/project.pbxproj: Support a Mac static library via
+ Xcode. Set iOS compatibility to 4.0. Move iOS trampoline
+ generation into an Xcode "run script" phase. Include both as
+ Xcode build scripts. Don't always regenerate config files.
+
+2012-04-10 Anthony Green <green@moxielogic.com>
+
+ * src/powerpc/ffi_darwin.c (ffi_prep_args): Add missing semicolon.
+
+2012-04-06 Anthony Green <green@moxielogic.com>
+
+ * Makefile.am (EXTRA_DIST): Add new iOS/xcode files.
+ * Makefile.in: Rebuilt.
+
+2012-04-06 Mike Lewis <mikelikespie@gmail.com>
+
+ * generate-ios-source-and-headers.py: New file.
+ * libffi.xcodeproj/project.pbxproj: New file.
+ * README: Update instructions on building iOS binary.
+ * build-ios.sh: Delete.
+
+2012-04-06 Anthony Green <green@moxielogic.com>
+
+ * src/x86/ffi64.c (UINT128): Define differently for Intel and GNU
+ compilers, then use it.
+
+2012-04-06 H.J. Lu <hongjiu.lu@intel.com>
+
+ * m4/libtool.m4 (_LT_ENABLE_LOCK): Support x32.
+
+2012-04-06 Anthony Green <green@moxielogic.com>
+
+ * testsuite/Makefile.am (EXTRA_DIST): Add missing test cases.
+ * testsuite/Makefile.in: Rebuilt.
+
+2012-04-05 Zachary Waldowski <zwaldowski@gmail.com>
+
+ * include/ffi.h.in: Add missing trampoline table fields.
+ * src/arm/sysv.S: Fix ENTRY definition, and wrap symbol references
+ in CNAME.
+ * src/x86/ffi.c: Wrap Windows specific code in ifdefs.
+
+2012-04-02 Peter Bergner <bergner@vnet.ibm.com>
+
+ * src/powerpc/ffi.c (ffi_prep_args_SYSV): Declare double_tmp.
+ Silence casting pointer to integer of different size warning.
+ Delete goto to previously deleted label.
+ (ffi_call): Silence possibly undefined warning.
+ (ffi_closure_helper_SYSV): Declare variable type.
+
+2012-04-02 Peter Rosin <peda@lysator.liu.se>
+
+ * src/x86/win32.S (ffi_call_win32): Sign/zero extend the return
+ value in the Intel version as is already done for the AT&T version.
+ (ffi_closure_SYSV): Likewise.
+ (ffi_closure_raw_SYSV): Likewise.
+ (ffi_closure_STDCALL): Likewise.
+
+2012-03-29 Peter Rosin <peda@lysator.liu.se>
+
+ * src/x86/win32.S (ffi_closure_raw_THISCALL): Unify the frame
+ generation, fix the ENDP label and remove the surplus third arg
+ from the 'lea' insn.
+
+2012-03-29 Peter Rosin <peda@lysator.liu.se>
+
+ * src/x86/win32.S (ffi_closure_raw_SYSV): Make the 'stubraw' label
+ visible outside the PROC, so that ffi_closure_raw_THISCALL can see
+ it. Also instruct the assembler to add a frame to the function.
+
+2012-03-23 Peter Rosin <peda@lysator.liu.se>
+
+ * Makefile.am (AM_CPPFLAGS): Add -DFFI_BUILDING.
+ * Makefile.in: Rebuilt.
+ * include/ffi.h.in [MSVC]: Add __declspec(dllimport) decorations
+ to all data exports, when compiling libffi clients using MSVC.
+
+2012-03-29 Peter Rosin <peda@lysator.liu.se>
+
+ * src/x86/ffitarget.h (ffi_abi): Add new ABI FFI_MS_CDECL and
+ make it the default for MSVC.
+ (FFI_TYPE_MS_STRUCT): New structure return convention.
+ * src/x86/ffi.c (ffi_prep_cif_machdep): Tweak the structure
+ return convention for FFI_MS_CDECL to be FFI_TYPE_MS_STRUCT
+ instead of an ordinary FFI_TYPE_STRUCT.
+ (ffi_prep_args): Treat FFI_TYPE_MS_STRUCT as FFI_TYPE_STRUCT.
+ (ffi_call): Likewise.
+ (ffi_prep_incoming_args_SYSV): Likewise.
+ (ffi_raw_call): Likewise.
+ (ffi_prep_closure_loc): Treat FFI_MS_CDECL as FFI_SYSV.
+ * src/x86/win32.S (ffi_closure_SYSV): For FFI_TYPE_MS_STRUCT,
+ return a pointer to the result structure in eax and don't pop
+ that pointer from the stack, the caller takes care of it.
+ (ffi_call_win32): Treat FFI_TYPE_MS_STRUCT as FFI_TYPE_STRUCT.
+ (ffi_closure_raw_SYSV): Likewise.
+
+2012-03-22 Peter Rosin <peda@lysator.liu.se>
+
+ * testsuite/libffi.call/closure_stdcall.c [MSVC]: Add inline
+ assembly version with Intel syntax.
+ * testsuite/libffi.call/closure_thiscall.c [MSVC]: Likewise.
+
+2012-03-23 Peter Rosin <peda@lysator.liu.se>
+
+ * testsuite/libffi.call/ffitest.h: Provide abstration of
+ __attribute__((fastcall)) in the form of a __FASTCALL__
+ define. Define it to __fastcall for MSVC.
+ * testsuite/libffi.call/fastthis1_win32.c: Use the above.
+ * testsuite/libffi.call/fastthis2_win32.c: Likewise.
+ * testsuite/libffi.call/fastthis3_win32.c: Likewise.
+ * testsuite/libffi.call/strlen2_win32.c: Likewise.
+ * testsuite/libffi.call/struct1_win32.c: Likewise.
+ * testsuite/libffi.call/struct2_win32.c: Likewise.
+
+2012-03-22 Peter Rosin <peda@lysator.liu.se>
+
+ * src/x86/win32.S [MSVC] (ffi_closure_THISCALL): Remove the manual
+ frame on function entry, MASM adds one automatically.
+
+2012-03-22 Peter Rosin <peda@lysator.liu.se>
+
+ * testsuite/libffi.call/ffitest.h [MSVC]: Add kludge for missing
+ bits in the MSVC headers.
+
+2012-03-22 Peter Rosin <peda@lysator.liu.se>
+
+ * testsuite/libffi.call/cls_12byte.c: Adjust to the C89 style
+ with no declarations after statements.
+ * testsuite/libffi.call/cls_16byte.c: Likewise.
+ * testsuite/libffi.call/cls_18byte.c: Likewise.
+ * testsuite/libffi.call/cls_19byte.c: Likewise.
+ * testsuite/libffi.call/cls_1_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_20byte.c: Likewise.
+ * testsuite/libffi.call/cls_20byte1.c: Likewise.
+ * testsuite/libffi.call/cls_24byte.c: Likewise.
+ * testsuite/libffi.call/cls_2byte.c: Likewise.
+ * testsuite/libffi.call/cls_3_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_3byte1.c: Likewise.
+ * testsuite/libffi.call/cls_3byte2.c: Likewise.
+ * testsuite/libffi.call/cls_4_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_4byte.c: Likewise.
+ * testsuite/libffi.call/cls_5_1_byte.c: Likewise.
+ * testsuite/libffi.call/cls_5byte.c: Likewise.
+ * testsuite/libffi.call/cls_64byte.c: Likewise.
+ * testsuite/libffi.call/cls_6_1_byte.c: Likewise.
+ * testsuite/libffi.call/cls_6byte.c: Likewise.
+ * testsuite/libffi.call/cls_7_1_byte.c: Likewise.
+ * testsuite/libffi.call/cls_7byte.c: Likewise.
+ * testsuite/libffi.call/cls_8byte.c: Likewise.
+ * testsuite/libffi.call/cls_9byte1.c: Likewise.
+ * testsuite/libffi.call/cls_9byte2.c: Likewise.
+ * testsuite/libffi.call/cls_align_double.c: Likewise.
+ * testsuite/libffi.call/cls_align_float.c: Likewise.
+ * testsuite/libffi.call/cls_align_longdouble.c: Likewise.
+ * testsuite/libffi.call/cls_align_longdouble_split.c: Likewise.
+ * testsuite/libffi.call/cls_align_longdouble_split2.c: Likewise.
+ * testsuite/libffi.call/cls_align_pointer.c: Likewise.
+ * testsuite/libffi.call/cls_align_sint16.c: Likewise.
+ * testsuite/libffi.call/cls_align_sint32.c: Likewise.
+ * testsuite/libffi.call/cls_align_sint64.c: Likewise.
+ * testsuite/libffi.call/cls_align_uint16.c: Likewise.
+ * testsuite/libffi.call/cls_align_uint32.c: Likewise.
+ * testsuite/libffi.call/cls_align_uint64.c: Likewise.
+ * testsuite/libffi.call/cls_dbls_struct.c: Likewise.
+ * testsuite/libffi.call/cls_pointer_stack.c: Likewise.
+ * testsuite/libffi.call/err_bad_typedef.c: Likewise.
+ * testsuite/libffi.call/huge_struct.c: Likewise.
+ * testsuite/libffi.call/nested_struct.c: Likewise.
+ * testsuite/libffi.call/nested_struct1.c: Likewise.
+ * testsuite/libffi.call/nested_struct10.c: Likewise.
+ * testsuite/libffi.call/nested_struct2.c: Likewise.
+ * testsuite/libffi.call/nested_struct3.c: Likewise.
+ * testsuite/libffi.call/nested_struct4.c: Likewise.
+ * testsuite/libffi.call/nested_struct5.c: Likewise.
+ * testsuite/libffi.call/nested_struct6.c: Likewise.
+ * testsuite/libffi.call/nested_struct7.c: Likewise.
+ * testsuite/libffi.call/nested_struct8.c: Likewise.
+ * testsuite/libffi.call/nested_struct9.c: Likewise.
+ * testsuite/libffi.call/stret_large.c: Likewise.
+ * testsuite/libffi.call/stret_large2.c: Likewise.
+ * testsuite/libffi.call/stret_medium.c: Likewise.
+ * testsuite/libffi.call/stret_medium2.c: Likewise.
+ * testsuite/libffi.call/struct1.c: Likewise.
+ * testsuite/libffi.call/struct1_win32.c: Likewise.
+ * testsuite/libffi.call/struct2.c: Likewise.
+ * testsuite/libffi.call/struct2_win32.c: Likewise.
+ * testsuite/libffi.call/struct3.c: Likewise.
+ * testsuite/libffi.call/struct4.c: Likewise.
+ * testsuite/libffi.call/struct5.c: Likewise.
+ * testsuite/libffi.call/struct6.c: Likewise.
+ * testsuite/libffi.call/struct7.c: Likewise.
+ * testsuite/libffi.call/struct8.c: Likewise.
+ * testsuite/libffi.call/struct9.c: Likewise.
+ * testsuite/libffi.call/testclosure.c: Likewise.
+
+2012-03-21 Peter Rosin <peda@lysator.liu.se>
+
+ * testsuite/libffi.call/float_va.c (float_va_fn): Use %f when
+ printing doubles (%lf is for long doubles).
+ (main): Likewise.
+
+2012-03-21 Peter Rosin <peda@lysator.liu.se>
+
+ * testsuite/lib/target-libpath.exp [*-*-cygwin*, *-*-mingw*]
+ (set_ld_library_path_env_vars): Add the library search dir to PATH
+ (and save PATH for later).
+ (restore_ld_library_path_env_vars): Restore PATH.
+
+2012-03-21 Peter Rosin <peda@lysator.liu.se>
+
+ * testsuite/lib/target-libpath.exp [*-*-cygwin*, *-*-mingw*]
+ (set_ld_library_path_env_vars): Add the library search dir to PATH
+ (and save PATH for later).
+ (restore_ld_library_path_env_vars): Restore PATH.
+
+2012-03-20 Peter Rosin <peda@lysator.liu.se>
+
+ * testsuite/libffi.call/strlen2_win32.c (main): Remove bug.
+ * src/x86/win32.S [MSVC] (ffi_closure_SYSV): Make the 'stub' label
+ visible outside the PROC, so that ffi_closure_THISCALL can see it.
+
+2012-03-20 Peter Rosin <peda@lysator.liu.se>
+
+ * testsuite/libffi.call/strlen2_win32.c (main): Remove bug.
+ * src/x86/win32.S [MSVC] (ffi_closure_SYSV): Make the 'stub' label
+ visible outside the PROC, so that ffi_closure_THISCALL can see it.
+
+2012-03-19 Alan Hourihane <alanh@fairlite.co.uk>
+
+ * src/m68k/ffi.c: Add MINT support.
+ * src/m68k/sysv.S: Ditto.
+
+2012-03-06 Chung-Lin Tang <cltang@codesourcery.com>
+
+ * src/arm/ffi.c (ffi_call): Add __ARM_EABI__ guard around call to
+ ffi_call_VFP().
+ (ffi_prep_closure_loc): Add __ARM_EABI__ guard around use of
+ ffi_closure_VFP.
+ * src/arm/sysv.S: Add __ARM_EABI__ guard around VFP code.
+
+2012-03-19 chennam <csit@axway.com>
+
+ * src/powerpc/ffi_darwin.c (ffi_prep_closure_loc): Fix AIX closure
+ support.
+
+2012-03-13 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test,
+ just return FFI_BAD_ABI when things are wrong.
+ * src/sh64/ffi.c (ffi_prep_closure_loc): Ditto.
+
+2012-03-09 David Edelsohn <dje.gcc@gmail.com>
+
+ * src/powerpc/aix_closure.S (ffi_closure_ASM): Adjust for Darwin64
+ change to return value of ffi_closure_helper_DARWIN and load type
+ from return type.
+
+2012-03-03 H.J. Lu <hongjiu.lu@intel.com>
+
+ * src/x86/ffi64.c (ffi_call): Cast the return value to unsigned
+ long.
+ (ffi_prep_closure_loc): Cast to 64bit address in trampoline.
+ (ffi_closure_unix64_inner): Cast return pointer to unsigned long
+ first.
+
+ * src/x86/ffitarget.h (FFI_SIZEOF_ARG): Defined to 8 for x32.
+ (ffi_arg): Set to unsigned long long for x32.
+ (ffi_sarg): Set to long long for x32.
+
+2012-03-03 H.J. Lu <hongjiu.lu@intel.com>
+
+ * src/prep_cif.c (ffi_prep_cif_core): Properly check bad ABI.
+
+2012-03-03 Andoni Morales Alastruey <ylatuya@gmail.com>
+
+ * configure.ac: Add -no-undefined for both 32- and 64-bit x86
+ windows-like hosts.
+ * configure: Rebuilt.
+
+2012-02-27 Mikael Pettersson <mikpe@it.uu.se>
+
+ PR libffi/52223
+ * Makefile.am (FLAGS_TO_PASS): Define.
+ * Makefile.in: Regenerate.
+
+2012-02-23 Anthony Green <green@moxielogic.com>
+
+ * src/*/ffitarget.h: Ensure that users never include ffitarget.h
+ directly.
+
+2012-02-23 Kai Tietz <ktietz@redhat.com>
+
+ PR libffi/52221
+ * src/x86/ffi.c (ffi_closure_raw_THISCALL): New
+ prototype.
+ (ffi_prep_raw_closure_loc): Use ffi_closure_raw_THISCALL for
+ thiscall-convention.
+ (ffi_raw_call): Use ffi_prep_args_raw.
+ * src/x86/win32.S (ffi_closure_raw_THISCALL): Add
+ implementation for stub.
+
+2012-02-10 Kai Tietz <ktietz@redhat.com>
+
+ * configure.ac (AM_LTLDFLAGS): Add -no-undefine for x64
+ windows target.
+ * configure: Regenerated.
+
+2012-02-08 Kai Tietz <ktietz@redhat.com>
+
+ * src/prep_cif.c (ffi_prep_cif): Allow for X86_WIN32
+ also FFI_THISCALL.
+ * src/x86/ffi.c (ffi_closure_THISCALL): Add prototype.
+ (FFI_INIT_TRAMPOLINE_THISCALL): New trampoline code.
+ (ffi_prep_closure_loc): Add FFI_THISCALL support.
+ * src/x86/ffitarget.h (FFI_TRAMPOLINE_SIZE): Adjust size.
+ * src/x86/win32.S (ffi_closure_THISCALL): New closure code
+ for thiscall-calling convention.
+ * testsuite/libffi.call/closure_thiscall.c: New test.
+
+2012-01-28 Kai Tietz <ktietz@redhat.com>
+
+ * src/libffi/src/x86/ffi.c (ffi_call_win32): Add new
+ argument to prototype for specify calling-convention.
+ (ffi_call): Add support for stdcall/thiscall convention.
+ (ffi_prep_args): Likewise.
+ (ffi_raw_call): Likewise.
+ * src/x86/ffitarget.h (ffi_abi): Add FFI_THISCALL and
+ FFI_FASTCALL.
+ * src/x86/win32.S (_ffi_call_win32): Add support for
+ fastcall/thiscall calling-convention calls.
+ * testsuite/libffi.call/fastthis1_win32.c: New test.
+ * testsuite/libffi.call/fastthis2_win32.c: New test.
+ * testsuite/libffi.call/fastthis3_win32.c: New test.
+ * testsuite/libffi.call/strlen2_win32.c: New test.
+ * testsuite/libffi.call/many2_win32.c: New test.
+ * testsuite/libffi.call/struct1_win32.c: New test.
+ * testsuite/libffi.call/struct2_win32.c: New test.
+
+2012-01-23 Uros Bizjak <ubizjak@gmail.com>
+
+ * src/alpha/ffi.c (ffi_prep_closure_loc): Check for bad ABI.
+
+2012-01-23 Anthony Green <green@moxielogic.com>
+ Chris Young <cdyoung@ntlworld.com>
+
+ * configure.ac: Add Amiga support.
+ * configure: Rebuilt.
+
+2012-01-23 Dmitry Nadezhin <dmitry.nadezhin@gmail.com>
+
+ * include/ffi_common.h (LIKELY, UNLIKELY): Fix definitions.
+
+2012-01-23 Andreas Schwab <schwab@linux-m68k.org>
+
+ * src/m68k/sysv.S (ffi_call_SYSV): Properly test for plain
+ mc68000. Test for __HAVE_68881__ in addition to __MC68881__.
+
+2012-01-19 Jakub Jelinek <jakub@redhat.com>
+
+ PR rtl-optimization/48496
+ * src/ia64/ffi.c (ffi_call): Fix up aliasing violations.
+
+2012-01-09 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * configure.ac (i?86-*-*): Set TARGET to X86_64.
+ * configure: Regenerate.
+
+2011-12-07 Andrew Pinski <apinski@cavium.com>
+
+ PR libffi/50051
+ * src/mips/n32.S: Add ".set mips4".
+
+2011-11-21 Andreas Tobler <andreast@fgznet.ch>
+
+ * configure: Regenerate.
+
+2011-11-12 David Gilbert <david.gilbert@linaro.org>
+
+ * doc/libffi.texi, include/ffi.h.in, include/ffi_common.h,
+ man/Makefile.am, man/ffi.3, man/ffi_prep_cif.3,
+ man/ffi_prep_cif_var.3, src/arm/ffi.c, src/arm/ffitarget.h,
+ src/cris/ffi.c, src/prep_cif.c,
+ testsuite/libffi.call/cls_double_va.c,
+ testsuite/libffi.call/cls_longdouble_va.c,
+ testsuite/libffi.call/float_va.c: Many changes to support variadic
+ function calls.
+
+2011-11-12 Kyle Moffett <Kyle.D.Moffett@boeing.com>
+
+ * src/powerpc/ffi.c, src/powerpc/ffitarget.h,
+ src/powerpc/ppc_closure.S, src/powerpc/sysv.S: Many changes for
+ softfloat powerpc variants.
+
+2011-11-12 Petr Salinger <Petr.Salinger@seznam.cz>
+
+ * configure.ac (FFI_EXEC_TRAMPOLINE_TABLE): Fix kfreebsd support.
+ * configure: Rebuilt.
+
+2011-11-12 Timothy Wall <twall@users.sf.net>
+
+ * src/arm/ffi.c (ffi_prep_args, ffi_prep_incoming_args_SYSV): Max
+ alignment of 4 for wince on ARM.
+
+2011-11-12 Kyle Moffett <Kyle.D.Moffett@boeing.com>
+ Anthony Green <green@moxielogic.com>
+
+ * src/ppc/sysv.S, src/ppc/ffi.c: Remove use of ppc string
+ instructions (not available on some cores, like the PPC440).
+
+2011-11-12 Kimura Wataru <kimuraw@i.nifty.jp>
+
+ * m4/ax_enable_builddir: Change from string comparison to numeric
+ comparison for wc output.
+ * configure.ac: Enable FFI_MMAP_EXEC_WRIT for darwin11 aka Mac OS
+ X 10.7.
+ * configure: Rebuilt.
+
+2011-11-12 Anthony Green <green@moxielogic.com>
+
+ * Makefile.am (AM_CCASFLAGS): Add -g option to build assembly
+ files with debug info.
+ * Makefile.in: Rebuilt.
+
+2011-11-12 Jasper Lievisse Adriaanse <jasper@openbsd.org>
+
+ * README: Update list of supported OpenBSD systems.
+
+2011-11-12 Anthony Green <green@moxielogic.com>
+
+ * libtool-version: Update.
+ * Makefile.am (nodist_libffi_la_SOURCES): Add src/debug.c if
+ FFI_DEBUG.
+ (libffi_la_SOURCES): Remove src/debug.c
+ (EXTRA_DIST): Add src/debug.c
+ * Makefile.in: Rebuilt.
+ * README: Update for 3.0.11.
+
+2011-11-10 Richard Henderson <rth@redhat.com>
+
+ * configure.ac (GCC_AS_CFI_PSEUDO_OP): Use it instead of inline check.
+ * configure, aclocal.m4: Rebuild.
+
+2011-09-04 Iain Sandoe <iains@gcc.gnu.org>
+
+ PR libffi/49594
+ * src/powerpc/darwin_closure.S (stubs): Make the stub binding
+ helper reference track the architecture pointer size.
+
+2011-08-25 Andrew Haley <aph@redhat.com>
+
+ * src/arm/ffi.c (FFI_INIT_TRAMPOLINE): Remove hard-coded assembly
+ instructions.
+ * src/arm/sysv.S (ffi_arm_trampoline): Put them here instead.
+
+2011-07-11 Andrew Haley <aph@redhat.com>
+
+ * src/arm/ffi.c (FFI_INIT_TRAMPOLINE): Clear icache.
+
+2011-06-29 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * testsuite/libffi.call/cls_double_va.c: Move PR number to comment.
+ * testsuite/libffi.call/cls_longdouble_va.c: Likewise.
+
+2011-06-29 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ PR libffi/46660
+ * testsuite/libffi.call/cls_double_va.c: xfail dg-output on
+ mips-sgi-irix6*.
+ * testsuite/libffi.call/cls_longdouble_va.c: Likewise.
+
+2011-06-14 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * testsuite/libffi.call/huge_struct.c (test_large_fn): Use PRIu8,
+ PRId8 instead of %hhu, %hhd.
+ * testsuite/libffi.call/ffitest.h [__alpha__ && __osf__] (PRId8,
+ PRIu8): Define.
+ [__sgi__] (PRId8, PRIu8): Define.
+
+2011-04-29 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * src/alpha/osf.S (UA_SI, FDE_ENCODING, FDE_ENCODE, FDE_ARANGE):
+ Define.
+ Use them to handle ELF vs. ECOFF differences.
+ [__osf__] (_GLOBAL__F_ffi_call_osf): Define.
+
+2011-03-30 Timothy Wall <twall@users.sf.net>
+
+ * src/powerpc/darwin.S: Fix unknown FDE encoding.
+ * src/powerpc/darwin_closure.S: ditto.
+
+2011-02-25 Anthony Green <green@moxielogic.com>
+
+ * src/powerpc/ffi.c (ffi_prep_closure_loc): Allow for more
+ 32-bit ABIs.
+
+2011-02-15 Anthony Green <green@moxielogic.com>
+
+ * m4/ax_cc_maxopt.m4: Don't -malign-double or use -ffast-math.
+ * configure: Rebuilt.
+
+2011-02-13 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
+
+ * configure: Regenerate.
+
+2011-02-13 Anthony Green <green@moxielogic.com>
+
+ * include/ffi_common.h (UNLIKELY, LIKELY): Define.
+ * src/x86/ffi64.c (UNLIKELY, LIKELY): Remove definition.
+ * src/prep_cif.c (UNLIKELY, LIKELY): Remove definition.
+
+ * src/prep_cif.c (initialize_aggregate): Convert assertion into
+ FFI_BAD_TYPEDEF return. Initialize arg size and alignment to 0.
+
+ * src/pa/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test,
+ just return FFI_BAD_ABI when things are wrong.
+ * src/arm/ffi.c (ffi_prep_closure_loc): Ditto.
+ * src/powerpc/ffi.c (ffi_prep_closure_loc): Ditto.
+ * src/mips/ffi.c (ffi_prep_closure_loc): Ditto.
+ * src/ia64/ffi.c (ffi_prep_closure_loc): Ditto.
+ * src/avr32/ffi.c (ffi_prep_closure_loc): Ditto.
+
+2011-02-11 Anthony Green <green@moxielogic.com>
+
+ * src/sparc/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test,
+ just return FFI_BAD_ABI when things are wrong.
+
+2012-02-11 Eric Botcazou <ebotcazou@adacore.com>
+
+ * src/sparc/v9.S (STACKFRAME): Bump to 176.
+
+2011-02-09 Stuart Shelton <srcshelton@gmail.com>
+
+ http://bugs.gentoo.org/show_bug.cgi?id=286911
+ * src/mips/ffitarget.h: Clean up error messages.
+ * src/java_raw_api.c (ffi_java_translate_args): Cast raw arg to
+ ffi_raw*.
+ * include/ffi.h.in: Add pragma for SGI compiler.
+
+2011-02-09 Anthony Green <green@moxielogic.com>
+
+ * configure.ac: Add powerpc64-*-darwin* support.
+
+2011-02-09 Anthony Green <green@moxielogic.com>
+
+ * README: Mention Interix.
+
+2011-02-09 Jonathan Callen <abcd@gentoo.org>
+
+ * configure.ac: Add Interix to win32/cygwin/mingw case.
+ * configure: Ditto.
+ * src/closures.c: Treat Interix like Cygwin, instead of as a
+ generic win32.
+
+2011-02-09 Anthony Green <green@moxielogic.com>
+
+ * testsuite/libffi.call/err_bad_typedef.c: Remove xfail.
+ * testsuite/libffi.call/err_bad_abi.c: Remove xfail.
+ * src/x86/ffi64.c (UNLIKELY, LIKELY): Define.
+ (ffi_prep_closure_loc): Check for bad ABI.
+ * src/prep_cif.c (UNLIKELY, LIKELY): Define.
+ (initialize_aggregate): Check for bad types.
+
+2011-02-09 Landon Fuller <landonf@plausible.coop>
+
+ * Makefile.am (EXTRA_DIST): Add build-ios.sh, src/arm/gentramp.sh,
+ src/arm/trampoline.S.
+ (nodist_libffi_la_SOURCES): Add src/arc/trampoline.S.
+ * configure.ac (FFI_EXEC_TRAMPOLINE_TABLE): Define.
+ * src/arm/ffi.c (ffi_trampoline_table)
+ (ffi_closure_trampoline_table_page, ffi_trampoline_table_entry)
+ (FFI_TRAMPOLINE_CODELOC_CONFIG, FFI_TRAMPOLINE_CONFIG_PAGE_OFFSET)
+ (FFI_TRAMPOLINE_COUNT, ffi_trampoline_lock, ffi_trampoline_tables)
+ (ffi_trampoline_table_alloc, ffi_closure_alloc, ffi_closure_free):
+ Define for FFI_EXEC_TRAMPOLINE_TABLE case (iOS).
+ (ffi_prep_closure_loc): Handl FFI_EXEC_TRAMPOLINE_TABLE case
+ separately.
+ * src/arm/sysv.S: Handle Apple iOS host.
+ * src/closures.c: Handle FFI_EXEC_TRAMPOLINE_TABLE case.
+ * build-ios.sh: New file.
+ * fficonfig.h.in, configure, Makefile.in: Rebuilt.
+ * README: Mention ARM iOS.
+
+2011-02-08 Oren Held <orenhe@il.ibm.com>
+
+ * src/dlmalloc.c (_STRUCT_MALLINFO): Define in order to avoid
+ redefinition of mallinfo on HP-UX.
+
+2011-02-08 Ginn Chen <ginn.chen@oracle.com>
+
+ * src/sparc/ffi.c (ffi_call): Make compatible with Solaris Studio
+ aggregate return ABI. Flush cache.
+ (ffi_prep_closure_loc): Flush cache.
+
+2011-02-11 Anthony Green <green@moxielogic.com>
+
+ From Tom Honermann <tom.honermann@oracle.com>:
+ * src/powerpc/aix.S (ffi_call_AIX): Support for xlc toolchain on
+ AIX. Declare .ffi_prep_args. Insert nops after branch
+ instructions so that the AIX linker can insert TOC reload
+ instructions.
+ * src/powerpc/aix_closure.S: Declare .ffi_closure_helper_DARWIN.
+
+2011-02-08 Ed <ed@kdtc.net>
+
+ * src/powerpc/asm.h: Fix grammar nit in comment.
+
+2011-02-08 Uli Link <ul.mcamafia@linkitup.de>
+
+ * include/ffi.h.in (FFI_64_BIT_MAX): Define and use.
+
+2011-02-09 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ PR libffi/46661
+ * testsuite/libffi.call/cls_pointer.c (main): Cast void * to
+ uintptr_t first.
+ * testsuite/libffi.call/cls_pointer_stack.c (main): Likewise.
+
+2011-02-08 Rafael Avila de Espindola <respindola@mozilla.com>
+
+ * configure.ac: Fix x86 test for pc related relocs.
+ * configure: Rebuilt.
+
+2011-02-07 Joel Sherrill <joel.sherrill@oarcorp.com>
+
+ * libffi/src/m68k/ffi.c: Add RTEMS support for cache flushing.
+ Handle case when CPU variant does not have long double support.
+ * libffi/src/m68k/sysv.S: Add support for mc68000, Coldfire,
+ and cores with soft floating point.
+
+2011-02-07 Joel Sherrill <joel.sherrill@oarcorp.com>
+
+ * configure.ac: Add mips*-*-rtems* support.
+ * configure: Regenerate.
+ * src/mips/ffitarget.h: Ensure needed constants are available
+ for targets which do not have sgidefs.h.
+
+2011-01-26 Dave Korn <dave.korn.cygwin@gmail.com>
+
+ PR target/40125
+ * configure.ac (AM_LTLDFLAGS): Add -bindir option for windows DLLs.
+ * configure: Regenerate.
+
+2010-12-18 Iain Sandoe <iains@gcc.gnu.org>
+
+ PR libffi/29152
+ PR libffi/42378
+ * src/powerpc/darwin_closure.S: Provide Darwin64 implementation,
+ update comments.
+ * src/powerpc/ffitarget.h (POWERPC_DARWIN64): New,
+ (FFI_TRAMPOLINE_SIZE): Update for Darwin64.
+ * src/powerpc/darwin.S: Provide Darwin64 implementation,
+ update comments.
+ * src/powerpc/ffi_darwin.c: Likewise.
+
+2010-12-06 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * configure.ac (libffi_cv_as_ascii_pseudo_op): Use double
+ backslashes.
+ (libffi_cv_as_string_pseudo_op): Likewise.
+ * configure: Regenerate.
+
+2010-12-03 Chung-Lin Tang <cltang@codesourcery.com>
+
+ * src/arm/sysv.S (ffi_closure_SYSV): Add UNWIND to .pad directive.
+ (ffi_closure_VFP): Same.
+ (ffi_call_VFP): Move down to before ffi_closure_VFP. Add '.fpu vfp'
+ directive.
+
+2010-12-01 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * testsuite/libffi.call/ffitest.h [__sgi] (PRId64, PRIu64): Define.
+ (PRIuPTR): Define.
+
+2010-11-29 Richard Henderson <rth@redhat.com>
+ Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * src/x86/sysv.S (FDE_ENCODING, FDE_ENCODE): Define.
+ (.eh_frame): Use FDE_ENCODING.
+ (.LASFDE1, .LASFDE2, LASFDE3): Simplify with FDE_ENCODE.
+
+2010-11-22 Jacek Caban <jacek@codeweavers.com>
+
+ * configure.ac: Check for symbol underscores on mingw-w64.
+ * configure: Rebuilt.
+ * src/x86/win64.S: Correctly access extern symbols in respect to
+ underscores.
+
+2010-11-15 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * testsuite/lib/libffi-dg.exp: Rename ...
+ * testsuite/lib/libffi.exp: ... to this.
+ * libffi/testsuite/libffi.call/call.exp: Don't load libffi-dg.exp.
+ * libffi/testsuite/libffi.special/special.exp: Likewise.
+
+2010-10-28 Chung-Lin Tang <cltang@codesourcery.com>
+
+ * src/arm/ffi.c (ffi_prep_args): Add VFP register argument handling
+ code, new parameter, and return value. Update comments.
+ (ffi_prep_cif_machdep): Add case for VFP struct return values. Add
+ call to layout_vfp_args().
+ (ffi_call_SYSV): Update declaration.
+ (ffi_call_VFP): New declaration.
+ (ffi_call): Add VFP struct return conditions. Call ffi_call_VFP()
+ when ABI is FFI_VFP.
+ (ffi_closure_VFP): New declaration.
+ (ffi_closure_SYSV_inner): Add new vfp_args parameter, update call to
+ ffi_prep_incoming_args_SYSV().
+ (ffi_prep_incoming_args_SYSV): Update parameters. Add VFP argument
+ case handling.
+ (ffi_prep_closure_loc): Pass ffi_closure_VFP to trampoline
+ construction under VFP hard-float.
+ (rec_vfp_type_p): New function.
+ (vfp_type_p): Same.
+ (place_vfp_arg): Same.
+ (layout_vfp_args): Same.
+ * src/arm/ffitarget.h (ffi_abi): Add FFI_VFP. Define FFI_DEFAULT_ABI
+ based on __ARM_PCS_VFP.
+ (FFI_EXTRA_CIF_FIELDS): Define for adding VFP hard-float specific
+ fields.
+ (FFI_TYPE_STRUCT_VFP_FLOAT): Define internally used type code.
+ (FFI_TYPE_STRUCT_VFP_DOUBLE): Same.
+ * src/arm/sysv.S (ffi_call_SYSV): Change call of ffi_prep_args() to
+ direct call. Move function pointer load upwards.
+ (ffi_call_VFP): New function.
+ (ffi_closure_VFP): Same.
+
+ * testsuite/lib/libffi-dg.exp (check-flags): New function.
+ (dg-skip-if): New function.
+ * testsuite/libffi.call/cls_double_va.c: Skip if target is arm*-*-*
+ and compiler options include -mfloat-abi=hard.
+ * testsuite/libffi.call/cls_longdouble_va.c: Same.
+
+2010-10-01 Jakub Jelinek <jakub@redhat.com>
+
+ PR libffi/45677
+ * src/x86/ffi64.c (ffi_prep_cif_machdep): Ensure cif->bytes is
+ a multiple of 8.
+ * testsuite/libffi.call/many2.c: New test.
+
+2010-08-20 Mark Wielaard <mjw@redhat.com>
+
+ * src/closures.c (open_temp_exec_file_mnt): Check if getmntent_r
+ returns NULL.
+
+2010-08-09 Andreas Tobler <andreast@fgznet.ch>
+
+ * configure.ac: Add target powerpc64-*-freebsd*.
+ * configure: Regenerate.
+ * testsuite/libffi.call/cls_align_longdouble_split.c: Pass
+ -mlong-double-128 only to linux targets.
+ * testsuite/libffi.call/cls_align_longdouble_split2.c: Likewise.
+ * testsuite/libffi.call/cls_longdouble.c: Likewise.
+ * testsuite/libffi.call/huge_struct.c: Likewise.
+
+2010-08-05 Dan Witte <dwitte@mozilla.com>
+
+ * Makefile.am: Pass FFI_DEBUG define to msvcc.sh for linking to the
+ debug CRT when --enable-debug is given.
+ * configure.ac: Define it.
+ * msvcc.sh: Translate -g and -DFFI_DEBUG appropriately.
+
+2010-08-04 Dan Witte <dwitte@mozilla.com>
+
+ * src/x86/ffitarget.h: Add X86_ANY define for all x86/x86_64
+ platforms.
+ * src/x86/ffi.c: Remove redundant ifdef checks.
+ * src/prep_cif.c: Push stack space computation into src/x86/ffi.c
+ for X86_ANY so return value space doesn't get added twice.
+
+2010-08-03 Neil Rashbrooke <neil@parkwaycc.co.uk>
+
+ * msvcc.sh: Don't pass -safeseh to ml64 because behavior is buggy.
+
+2010-07-22 Dan Witte <dwitte@mozilla.com>
+
+ * src/*/ffitarget.h: Make FFI_LAST_ABI one past the last valid ABI.
+ * src/prep_cif.c: Fix ABI assertion.
+ * src/cris/ffi.c: Ditto.
+
+2010-07-10 Evan Phoenix <evan@fallingsnow.net>
+
+ * src/closures.c (selinux_enabled_check): Fix strncmp usage bug.
+
+2010-07-07 Dan Horák <dan@danny.cz>
+
+ * include/ffi.h.in: Protect #define with #ifndef.
+ * src/powerpc/ffitarget.h: Ditto.
+ * src/s390/ffitarget.h: Ditto.
+ * src/sparc/ffitarget.h: Ditto.
+
+2010-07-07 Neil Roberts <neil@linux.intel.com>
+
+ * src/x86/sysv.S (ffi_call_SYSV): Align the stack pointer to
+ 16-bytes.
+
+2010-07-02 Jakub Jelinek <jakub@redhat.com>
+
+ * Makefile.am (AM_MAKEFLAGS): Pass also mandir to submakes.
+ * Makefile.in: Regenerated.
+
+2010-05-19 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * configure.ac (libffi_cv_as_x86_pcrel): Check for illegal in as
+ output, too.
+ (libffi_cv_as_ascii_pseudo_op): Check for .ascii.
+ (libffi_cv_as_string_pseudo_op): Check for .string.
+ * configure: Regenerate.
+ * fficonfig.h.in: Regenerate.
+ * src/x86/sysv.S (.eh_frame): Use .ascii, .string or error.
+
+2010-05-11 Dan Witte <dwitte@mozilla.com>
+
+ * doc/libffi.tex: Document previous change.
+
+2010-05-11 Makoto Kato <m_kato@ga2.so-net.ne.jp>
+
+ * src/x86/ffi.c (ffi_call): Don't copy structs passed by value.
+
+2010-05-05 Michael Kohler <michaelkohler@live.com>
+
+ * src/dlmalloc.c (dlfree): Fix spelling.
+ * src/ia64/ffi.c (ffi_prep_cif_machdep): Ditto.
+ * configure.ac: Ditto.
+ * configure: Rebuilt.
+
+2010-04-13 Dan Witte <dwitte@mozilla.com>
+
+ * msvcc.sh: Build with -W3 instead of -Wall.
+ * src/powerpc/ffi_darwin.c: Remove build warnings.
+ * src/x86/ffi.c: Ditto.
+ * src/x86/ffitarget.h: Ditto.
+
+2010-04-12 Dan Witte <dwitte@mozilla.com>
+ Walter Meinl <wuno@lsvw.de>
+
+ * configure.ac: Add OS/2 support.
+ * configure: Rebuilt.
+ * src/closures.c: Ditto.
+ * src/dlmalloc.c: Ditto.
+ * src/x86/win32.S: Ditto.
+
+2010-04-07 Jakub Jelinek <jakub@redhat.com>
+
+ * testsuite/libffi.call/err_bad_abi.c: Remove unused args variable.
+
+2010-04-02 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
+
+ * Makefile.in: Regenerate.
+ * aclocal.m4: Regenerate.
+ * include/Makefile.in: Regenerate.
+ * man/Makefile.in: Regenerate.
+ * testsuite/Makefile.in: Regenerate.
+
+2010-03-30 Dan Witte <dwitte@mozilla.com>
+
+ * msvcc.sh: Disable build warnings.
+ * README (tested): Clarify windows build procedure.
+
+2010-03-15 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * configure.ac (libffi_cv_as_x86_64_unwind_section_type): New test.
+ * configure: Regenerate.
+ * fficonfig.h.in: Regenerate.
+ * libffi/src/x86/unix64.S (.eh_frame)
+ [HAVE_AS_X86_64_UNWIND_SECTION_TYPE]: Use @unwind section type.
+
+2010-03-14 Matthias Klose <doko@ubuntu.com>
+
+ * src/x86/ffi64.c: Fix typo in comment.
+ * src/x86/ffi.c: Use /* ... */ comment style.
+
+2010-02-24 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * doc/libffi.texi (The Closure API): Fix typo.
+ * doc/libffi.info: Remove.
+
+2010-02-15 Matthias Klose <doko@ubuntu.com>
+
+ * src/arm/sysv.S (__ARM_ARCH__): Define for processor
+ __ARM_ARCH_7EM__.
+
+2010-01-15 Anthony Green <green@redhat.com>
+
+ * README: Add notes on building with Microsoft Visual C++.
+
+2010-01-15 Daniel Witte <dwitte@mozilla.com>
+
+ * msvcc.sh: New file.
+
+ * src/x86/win32.S: Port assembly routines to MSVC and #ifdef.
+ * src/x86/ffi.c: Tweak function declaration and remove excess
+ parens.
+ * include/ffi.h.in: Add __declspec(align(8)) to typedef struct
+ ffi_closure.
+
+ * src/x86/ffi.c: Merge ffi_call_SYSV and ffi_call_STDCALL into new
+ function ffi_call_win32 on X86_WIN32.
+ * src/x86/win32.S (ffi_call_SYSV): Rename to ffi_call_win32.
+ (ffi_call_STDCALL): Remove.
+
+ * src/prep_cif.c (ffi_prep_cif): Move stack space allocation code
+ to ffi_prep_cif_machdep for x86.
+ * src/x86/ffi.c (ffi_prep_cif_machdep): To here.
+
+2010-01-15 Oliver Kiddle <okiddle@yahoo.co.uk>
+
+ * src/x86/ffitarget.h (ffi_abi): Check for __i386 and __amd64 for
+ Sun Studio compiler compatibility.
+
+2010-01-12 Conrad Irwin <conrad.irwin@gmail.com>
+
+ * doc/libffi.texi: Add closure example.
+
+2010-01-07 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ PR libffi/40701
+ * testsuite/libffi.call/ffitest.h [__alpha__ && __osf__] (PRIdLL,
+ PRIuLL, PRId64, PRIu64, PRIuPTR): Define.
+ * testsuite/libffi.call/cls_align_sint64.c: Add -Wno-format on
+ alpha*-dec-osf*.
+ * testsuite/libffi.call/cls_align_uint64.c: Likewise.
+ * testsuite/libffi.call/cls_ulonglong.c: Likewise.
+ * testsuite/libffi.call/return_ll1.c: Likewise.
+ * testsuite/libffi.call/stret_medium2.c: Likewise.
+ * testsuite/libffi.special/ffitestcxx.h (allocate_mmap): Cast
+ MAP_FAILED to char *.
+
+2010-01-06 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ * src/mips/n32.S: Use .abicalls and .eh_frame with __GNUC__.
+
+2009-12-31 Anthony Green <green@redhat.com>
+
+ * README: Update for libffi 3.0.9.
+
+2009-12-27 Matthias Klose <doko@ubuntu.com>
+
+ * configure.ac (HAVE_LONG_DOUBLE): Define for mips when
+ appropriate.
+ * configure: Rebuilt.
+
+2009-12-26 Anthony Green <green@redhat.com>
+
+ * testsuite/libffi.call/cls_longdouble_va.c: Mark as xfail for
+ avr32*-*-*.
+ * testsuite/libffi.call/cls_double_va.c: Ditto.
+
+2009-12-26 Andreas Tobler <a.tobler@schweiz.org>
+
+ * testsuite/libffi.call/ffitest.h: Conditionally include stdint.h
+ and inttypes.h.
+ * testsuite/libffi.special/unwindtest.cc: Ditto.
+
+2009-12-26 Andreas Tobler <a.tobler@schweiz.org>
+
+ * configure.ac: Add amd64-*-openbsd*.
+ * configure: Rebuilt.
+ * testsuite/lib/libffi-dg.exp (libffi_target_compile): Link
+ openbsd programs with -lpthread.
+
+2009-12-26 Anthony Green <green@redhat.com>
+
+ * testsuite/libffi.call/cls_double_va.c,
+ testsuite/libffi.call/cls_longdouble.c,
+ testsuite/libffi.call/cls_longdouble_va.c,
+ testsuite/libffi.call/cls_pointer.c,
+ testsuite/libffi.call/cls_pointer_stack.c: Remove xfail for
+ mips*-*-* and arm*-*-*.
+ * testsuite/libffi.call/cls_align_longdouble_split.c,
+ testsuite/libffi.call/cls_align_longdouble_split2.c,
+ testsuite/libffi.call/stret_medium2.c,
+ testsuite/libffi.call/stret_medium.c,
+ testsuite/libffi.call/stret_large.c,
+ testsuite/libffi.call/stret_large2.c: Remove xfail for arm*-*-*.
+
+2009-12-31 Kay Tietz <ktietz70@googlemail.com>
+
+ * testsuite/libffi.call/ffitest.h,
+ testsuite/libffi.special/ffitestcxx.h (PRIdLL, PRuLL): Fix
+ definitions.
+
+2009-12-31 Carlo Bramini <carlo.bramix@libero.it>
+
+ * configure.ac (AM_LTLDFLAGS): Define for windows hosts.
+ * Makefile.am (libffi_la_LDFLAGS): Add AM_LTLDFLAGS.
+ * configure: Rebuilt.
+ * Makefile.in: Rebuilt.
+
+2009-12-31 Anthony Green <green@redhat.com>
+ Blake Chaffin.
+
+ * testsuite/libffi.call/huge_struct.c: New test case from Blake
+ Chaffin @ Apple.
+
+2009-12-28 David Edelsohn <edelsohn@gnu.org>
+
+ * src/powerpc/ffi_darwin.c (ffi_prep_args): Copy abi and nargs to
+ local variables.
+ (aix_adjust_aggregate_sizes): New function.
+ (ffi_prep_cif_machdep): Call it.
+
+2009-12-26 Andreas Tobler <a.tobler@schweiz.org>
+
+ * configure.ac: Define FFI_MMAP_EXEC_WRIT for the given targets.
+ * configure: Regenerate.
+ * fficonfig.h.in: Likewise.
+ * src/closures.c: Remove the FFI_MMAP_EXEC_WRIT definition for
+ Solaris/x86.
+
+2009-12-26 Andreas Schwab <schwab@linux-m68k.org>
+
+ * src/powerpc/ffi.c (ffi_prep_args_SYSV): Advance intarg_count
+ when a float arguments is passed in memory.
+ (ffi_closure_helper_SYSV): Mark general registers as used up when
+ a 64bit or soft-float long double argument is passed in memory.
+
+2009-12-25 Matthias Klose <doko@ubuntu.com>
+
+ * man/ffi_call.3: Fix #include in examples.
+ * doc/libffi.texi: Add dircategory.
+
+2009-12-25 Frank Everdij <f.p.x.everdij@tudelft.nl>
+
+ * include/ffi.h.in: Placed '__GNUC__' ifdef around
+ '__attribute__((aligned(8)))' in ffi_closure, fixes compile for
+ IRIX MIPSPro c99.
+ * include/ffi_common.h: Added '__sgi' define to non
+ '__attribute__((__mode__()))' integer typedefs.
+ * src/mips/ffi.c (ffi_call, ffi_closure_mips_inner_O32,
+ ffi_closure_mips_inner_N32): Added 'defined(_MIPSEB)' to BE check.
+ (ffi_closure_mips_inner_O32, ffi_closure_mips_inner_N32): Added
+ FFI_LONGDOUBLE support and alignment(N32 only).
+ * src/mips/ffitarget.h: Corrected '#include <sgidefs.h>' for IRIX and
+ fixed non '__attribute__((__mode__()))' integer typedefs.
+ * src/mips/n32.S: Put '#ifdef linux' around '.abicalls' and '.eh_frame'
+ since they are Linux/GNU Assembler specific.
+
+2009-12-25 Bradley Smith <brad@brad-smith.co.uk>
+
+ * configure.ac, Makefile.am, src/avr32/ffi.c,
+ src/avr32/ffitarget.h,
+ src/avr32/sysv.S: Add AVR32 port.
+ * configure, Makefile.in: Rebuilt.
+
+2009-12-21 Andreas Tobler <a.tobler@schweiz.org>
+
+ * configure.ac: Make i?86 build on FreeBSD and OpenBSD.
+ * configure: Regenerate.
+
+2009-12-15 John David Anglin <dave.anglin@nrc-cnrc.gc.ca>
+
+ * testsuite/libffi.call/ffitest.h: Define PRIuPTR on PA HP-UX.
+
+2009-12-13 John David Anglin <dave.anglin@nrc-cnrc.gc.ca>
+
+ * src/pa/ffi.c (ffi_closure_inner_pa32): Handle FFI_TYPE_LONGDOUBLE
+ type on HP-UX.
+
+2012-02-13 Kai Tietz <ktietz@redhat.com>
+
+ PR libffi/52221
+ * src/x86/ffi.c (ffi_prep_raw_closure_loc): Add thiscall
+ support for X86_WIN32.
+ (FFI_INIT_TRAMPOLINE_THISCALL): Fix displacement.
+
+2009-12-11 Eric Botcazou <ebotcazou@adacore.com>
+
+ * src/sparc/ffi.c (ffi_closure_sparc_inner_v9): Properly align 'long
+ double' arguments.
+
+2009-12-11 Eric Botcazou <ebotcazou@adacore.com>
+
+ * testsuite/libffi.call/ffitest.h: Define PRIuPTR on Solaris < 10.
+
+2009-12-10 Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
+
+ PR libffi/40700
+ * src/closures.c [X86_64 && __sun__ && __svr4__]
+ (FFI_MMAP_EXEC_WRIT): Define.
+
+2009-12-08 David Daney <ddaney@caviumnetworks.com>
+
+ * testsuite/libffi.call/stret_medium.c: Remove xfail for mips*-*-*
+ * testsuite/libffi.call/cls_align_longdouble_split2.c: Same.
+ * testsuite/libffi.call/stret_large.c: Same.
+ * testsuite/libffi.call/cls_align_longdouble_split.c: Same.
+ * testsuite/libffi.call/stret_large2.c: Same.
+ * testsuite/libffi.call/stret_medium2.c: Same.
+
+2009-12-07 David Edelsohn <edelsohn@gnu.org>
+
+ * src/powerpc/aix_closure.S (libffi_closure_ASM): Fix tablejump
+ typo.
+
+2009-12-05 David Edelsohn <edelsohn@gnu.org>
+
+ * src/powerpc/aix.S: Update AIX32 code to be consistent with AIX64
+ code.
+ * src/powerpc/aix_closure.S: Same.
+
+2009-12-05 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
+
+ * Makefile.in: Regenerate.
+ * configure: Regenerate.
+ * include/Makefile.in: Regenerate.
+ * man/Makefile.in: Regenerate.
+ * testsuite/Makefile.in: Regenerate.
+
+2009-12-04 David Edelsohn <edelsohn@gnu.org>
+
+ * src/powerpc/aix_closure.S: Reorganize 64-bit code to match
+ linux64_closure.S.
+
+2009-12-04 Uros Bizjak <ubizjak@gmail.com>
+
+ PR libffi/41908
+ * src/x86/ffi64.c (classify_argument): Update from
+ gcc/config/i386/i386.c.
+ (ffi_closure_unix64_inner): Do not use the address of two consecutive
+ SSE registers directly.
+ * testsuite/libffi.call/cls_dbls_struct.c (main): Remove xfail
+ for x86_64 linux targets.
+
+2009-12-04 David Edelsohn <edelsohn@gnu.org>
+
+ * src/powerpc/ffi_darwin.c (ffi_closure_helper_DARWIN): Increment
+ pfr for long double split between fpr13 and stack.
+
+2009-12-03 David Edelsohn <edelsohn@gnu.org>
+
+ * src/powerpc/ffi_darwin.c (ffi_prep_args): Increment next_arg and
+ fparg_count twice for long double.
+
+2009-12-03 David Edelsohn <edelsohn@gnu.org>
+
+ PR libffi/42243
+ * src/powerpc/ffi_darwin.c (ffi_prep_args): Remove extra parentheses.
+
+2009-12-03 Uros Bizjak <ubizjak@gmail.com>
+
+ * testsuite/libffi.call/cls_longdouble_va.c (main): Fix format string.
+ Remove xfails for x86 linux targets.
+
+2009-12-02 David Edelsohn <edelsohn@gnu.org>
+
+ * src/powerpc/ffi_darwin.c (ffi_prep_args): Fix typo in INT64
+ case.
+
+2009-12-01 David Edelsohn <edelsohn@gnu.org>
+
+ * src/powerpc/aix.S (ffi_call_AIX): Convert to more standard
+ register usage. Call ffi_prep_args directly. Add long double
+ return value support.
+ * src/powerpc/ffi_darwin.c (ffi_prep_args): Double arg increment
+ applies to FFI_TYPE_DOUBLE. Correct fpr_base increment typo.
+ Separate FFI_TYPE_SINT32 and FFI_TYPE_UINT32 cases.
+ (ffi_prep_cif_machdep): Only 16 byte stack alignment in 64 bit
+ mode.
+ (ffi_closure_helper_DARWIN): Remove nf and ng counters. Move temp
+ into case.
+ * src/powerpc/aix_closure.S: Maintain 16 byte stack alignment.
+ Allocate result area between params and FPRs.
+
+2009-11-30 David Edelsohn <edelsohn@gnu.org>
+
+ PR target/35484
+ * src/powerpc/ffitarget.h (POWERPC64): Define for PPC64 Linux and
+ AIX64.
+ * src/powerpc/aix.S: Implement AIX64 version.
+ * src/powerpc/aix_closure.S: Implement AIX64 version.
+ (ffi_closure_ASM): Use extsb, lha and displament addresses.
+ * src/powerpc/ffi_darwin.c (ffi_prep_args): Implement AIX64
+ support.
+ (ffi_prep_cif_machdep): Same.
+ (ffi_call): Same.
+ (ffi_closure_helper_DARWIN): Same.
+
+2009-11-02 Andreas Tobler <a.tobler@schweiz.org>
+
+ PR libffi/41908
+ * testsuite/libffi.call/testclosure.c: New test.
+
+2009-09-28 Kai Tietz <kai.tietz@onevision.com>
+
+ * src/x86/win64.S (_ffi_call_win64 stack): Remove for gnu
+ assembly version use of ___chkstk.
+
+2009-09-23 Matthias Klose <doko@ubuntu.com>
+
+ PR libffi/40242, PR libffi/41443
+ * src/arm/sysv.S (__ARM_ARCH__): Define for processors
+ __ARM_ARCH_6T2__, __ARM_ARCH_6M__, __ARM_ARCH_7__,
+ __ARM_ARCH_7A__, __ARM_ARCH_7R__, __ARM_ARCH_7M__.
+ Change the conditionals to __SOFTFP__ || __ARM_EABI__
+ for -mfloat-abi=softfp to work.
+
+2009-09-17 Loren J. Rittle <ljrittle@acm.org>
+
+ PR testsuite/32843 (strikes again)
+ * src/x86/ffi.c (ffi_prep_cif_machdep): Add X86_FREEBSD to
+ enable proper extension on char and short.
+
+2009-09-15 David Daney <ddaney@caviumnetworks.com>
+
+ * src/java_raw_api.c (ffi_java_raw_to_rvalue): Remove special
+ handling for FFI_TYPE_POINTER.
+ * src/mips/ffitarget.h (FFI_TYPE_STRUCT_D_SOFT,
+ FFI_TYPE_STRUCT_F_SOFT, FFI_TYPE_STRUCT_DD_SOFT,
+ FFI_TYPE_STRUCT_FF_SOFT, FFI_TYPE_STRUCT_FD_SOFT,
+ FFI_TYPE_STRUCT_DF_SOFT, FFI_TYPE_STRUCT_SOFT): New defines.
+ (FFI_N32_SOFT_FLOAT, FFI_N64_SOFT_FLOAT): New ffi_abi enumerations.
+ (enum ffi_abi): Set FFI_DEFAULT_ABI for soft-float.
+ * src/mips/n32.S (ffi_call_N32): Add handling for soft-float
+ structure and pointer returns.
+ (ffi_closure_N32): Add handling for pointer returns.
+ * src/mips/ffi.c (ffi_prep_args, calc_n32_struct_flags,
+ calc_n32_return_struct_flags): Handle soft-float.
+ (ffi_prep_cif_machdep): Handle soft-float, fix pointer handling.
+ (ffi_call_N32): Declare proper argument types.
+ (ffi_call, copy_struct_N32, ffi_closure_mips_inner_N32): Handle
+ soft-float.
+
+2009-08-24 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
+
+ * configure.ac (AC_PREREQ): Bump to 2.64.
+
+2009-08-22 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
+
+ * Makefile.am (install-html, install-pdf): Remove.
+ * Makefile.in: Regenerate.
+
+ * Makefile.in: Regenerate.
+ * aclocal.m4: Regenerate.
+ * configure: Regenerate.
+ * fficonfig.h.in: Regenerate.
+ * include/Makefile.in: Regenerate.
+ * man/Makefile.in: Regenerate.
+ * testsuite/Makefile.in: Regenerate.
+
+2011-08-22 Jasper Lievisse Adriaanse <jasper@openbsd.org>
+
+ * configure.ac: Add OpenBSD/hppa and OpenBSD/powerpc support.
+ * configure: Rebuilt.
+
+2009-07-30 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
+
+ * configure.ac (_AC_ARG_VAR_PRECIOUS): Use m4_rename_force.
+
+2009-07-24 Dave Korn <dave.korn.cygwin@gmail.com>
+
+ PR libffi/40807
+ * src/x86/ffi.c (ffi_prep_cif_machdep): Also use sign/zero-extending
+ return types for X86_WIN32.
+ * src/x86/win32.S (_ffi_call_SYSV): Handle omitted return types.
+ (_ffi_call_STDCALL, _ffi_closure_SYSV, _ffi_closure_raw_SYSV,
+ _ffi_closure_STDCALL): Likewise.
+
+ * src/closures.c (is_selinux_enabled): Define to const 0 for Cygwin.
+ (dlmmap, dlmunmap): Also use these functions on Cygwin.
+
+2009-07-11 Richard Sandiford <rdsandiford@googlemail.com>
+
+ PR testsuite/40699
+ PR testsuite/40707
+ PR testsuite/40709
+ * testsuite/lib/libffi-dg.exp: Revert 2009-07-02, 2009-07-01 and
+ 2009-06-30 commits.
+
+2009-07-01 Richard Sandiford <r.sandiford@uk.ibm.com>
+
+ * testsuite/lib/libffi-dg.exp (libffi-init): Set ld_library_path
+ to "" before adding paths. (This reinstates an assignment that
+ was removed by my 2009-06-30 commit, but changes the initial
+ value from "." to "".)
+
+2009-07-01 H.J. Lu <hongjiu.lu@intel.com>
+
+ PR testsuite/40601
+ * testsuite/lib/libffi-dg.exp (libffi-init): Properly set
+ gccdir. Adjust ld_library_path for gcc only if gccdir isn't
+ empty.
+
+2009-06-30 Richard Sandiford <r.sandiford@uk.ibm.com>
+
+ * testsuite/lib/libffi-dg.exp (libffi-init): Don't add "."
+ to ld_library_path. Use add_path. Add just find_libgcc_s
+ to ld_library_path, not every libgcc multilib directory.
+
+2009-06-16 Wim Lewis <wiml@hhhh.org>
+
+ * src/powerpc/ffi.c: Avoid clobbering cr3 and cr4, which are
+ supposed to be callee-saved.
+ * src/powerpc/sysv.S (small_struct_return_value): Fix overrun of
+ return buffer for odd-size structs.
+
+2009-06-16 Andreas Tobler <a.tobler@schweiz.org>
+
+ PR libffi/40444
+ * testsuite/lib/libffi-dg.exp (libffi_target_compile): Add
+ allow_stack_execute for Darwin.
+
+2009-06-16 Andrew Haley <aph@redhat.com>
+
+ * configure.ac (TARGETDIR): Add missing blank lines.
+ * configure: Regenerate.
+
+2009-06-16 Andrew Haley <aph@redhat.com>
+
+ * testsuite/libffi.call/cls_align_sint64.c,
+ testsuite/libffi.call/cls_align_uint64.c,
+ testsuite/libffi.call/cls_longdouble_va.c,
+ testsuite/libffi.call/cls_ulonglong.c,
+ testsuite/libffi.call/return_ll1.c,
+ testsuite/libffi.call/stret_medium2.c: Fix printf format
+ specifiers.
+ * testsuite/libffi.call/ffitest.h,
+ testsuite/libffi.special/ffitestcxx.h (PRIdLL, PRIuLL): Define.
+
+2009-06-15 Andrew Haley <aph@redhat.com>
+
+ * testsuite/libffi.call/err_bad_typedef.c: xfail everywhere.
+ * testsuite/libffi.call/err_bad_abi.c: Likewise.
+
+2009-06-12 Andrew Haley <aph@redhat.com>
+
+ * Makefile.am: Remove info_TEXINFOS.
+
+2009-06-12 Andrew Haley <aph@redhat.com>
+
+ * ChangeLog.libffi: testsuite/libffi.call/cls_align_sint64.c,
+ testsuite/libffi.call/cls_align_uint64.c,
+ testsuite/libffi.call/cls_ulonglong.c,
+ testsuite/libffi.call/return_ll1.c,
+ testsuite/libffi.call/stret_medium2.c: Fix printf format
+ specifiers.
+ testsuite/libffi.special/unwindtest.cc: include stdint.h.
+
+2009-06-11 Timothy Wall <twall@users.sf.net>
+
+ * Makefile.am,
+ configure.ac,
+ include/ffi.h.in,
+ include/ffi_common.h,
+ src/closures.c,
+ src/dlmalloc.c,
+ src/x86/ffi.c,
+ src/x86/ffitarget.h,
+ src/x86/win64.S (new),
+ README: Added win64 support (mingw or MSVC)
+ * Makefile.in,
+ include/Makefile.in,
+ man/Makefile.in,
+ testsuite/Makefile.in,
+ configure,
+ aclocal.m4: Regenerated
+ * ltcf-c.sh: properly escape cygwin/w32 path
+ * man/ffi_call.3: Clarify size requirements for return value.
+ * src/x86/ffi64.c: Fix filename in comment.
+ * src/x86/win32.S: Remove unused extern.
+
+ * testsuite/libffi.call/closure_fn0.c,
+ testsuite/libffi.call/closure_fn1.c,
+ testsuite/libffi.call/closure_fn2.c,
+ testsuite/libffi.call/closure_fn3.c,
+ testsuite/libffi.call/closure_fn4.c,
+ testsuite/libffi.call/closure_fn5.c,
+ testsuite/libffi.call/closure_fn6.c,
+ testsuite/libffi.call/closure_stdcall.c,
+ testsuite/libffi.call/cls_12byte.c,
+ testsuite/libffi.call/cls_16byte.c,
+ testsuite/libffi.call/cls_18byte.c,
+ testsuite/libffi.call/cls_19byte.c,
+ testsuite/libffi.call/cls_1_1byte.c,
+ testsuite/libffi.call/cls_20byte.c,
+ testsuite/libffi.call/cls_20byte1.c,
+ testsuite/libffi.call/cls_24byte.c,
+ testsuite/libffi.call/cls_2byte.c,
+ testsuite/libffi.call/cls_3_1byte.c,
+ testsuite/libffi.call/cls_3byte1.c,
+ testsuite/libffi.call/cls_3byte2.c,
+ testsuite/libffi.call/cls_4_1byte.c,
+ testsuite/libffi.call/cls_4byte.c,
+ testsuite/libffi.call/cls_5_1_byte.c,
+ testsuite/libffi.call/cls_5byte.c,
+ testsuite/libffi.call/cls_64byte.c,
+ testsuite/libffi.call/cls_6_1_byte.c,
+ testsuite/libffi.call/cls_6byte.c,
+ testsuite/libffi.call/cls_7_1_byte.c,
+ testsuite/libffi.call/cls_7byte.c,
+ testsuite/libffi.call/cls_8byte.c,
+ testsuite/libffi.call/cls_9byte1.c,
+ testsuite/libffi.call/cls_9byte2.c,
+ testsuite/libffi.call/cls_align_double.c,
+ testsuite/libffi.call/cls_align_float.c,
+ testsuite/libffi.call/cls_align_longdouble.c,
+ testsuite/libffi.call/cls_align_longdouble_split.c,
+ testsuite/libffi.call/cls_align_longdouble_split2.c,
+ testsuite/libffi.call/cls_align_pointer.c,
+ testsuite/libffi.call/cls_align_sint16.c,
+ testsuite/libffi.call/cls_align_sint32.c,
+ testsuite/libffi.call/cls_align_sint64.c,
+ testsuite/libffi.call/cls_align_uint16.c,
+ testsuite/libffi.call/cls_align_uint32.c,
+ testsuite/libffi.call/cls_align_uint64.c,
+ testsuite/libffi.call/cls_dbls_struct.c,
+ testsuite/libffi.call/cls_double.c,
+ testsuite/libffi.call/cls_double_va.c,
+ testsuite/libffi.call/cls_float.c,
+ testsuite/libffi.call/cls_longdouble.c,
+ testsuite/libffi.call/cls_longdouble_va.c,
+ testsuite/libffi.call/cls_multi_schar.c,
+ testsuite/libffi.call/cls_multi_sshort.c,
+ testsuite/libffi.call/cls_multi_sshortchar.c,
+ testsuite/libffi.call/cls_multi_uchar.c,
+ testsuite/libffi.call/cls_multi_ushort.c,
+ testsuite/libffi.call/cls_multi_ushortchar.c,
+ testsuite/libffi.call/cls_pointer.c,
+ testsuite/libffi.call/cls_pointer_stack.c,
+ testsuite/libffi.call/cls_schar.c,
+ testsuite/libffi.call/cls_sint.c,
+ testsuite/libffi.call/cls_sshort.c,
+ testsuite/libffi.call/cls_uchar.c,
+ testsuite/libffi.call/cls_uint.c,
+ testsuite/libffi.call/cls_ulonglong.c,
+ testsuite/libffi.call/cls_ushort.c,
+ testsuite/libffi.call/err_bad_abi.c,
+ testsuite/libffi.call/err_bad_typedef.c,
+ testsuite/libffi.call/float2.c,
+ testsuite/libffi.call/huge_struct.c,
+ testsuite/libffi.call/nested_struct.c,
+ testsuite/libffi.call/nested_struct1.c,
+ testsuite/libffi.call/nested_struct10.c,
+ testsuite/libffi.call/nested_struct2.c,
+ testsuite/libffi.call/nested_struct3.c,
+ testsuite/libffi.call/nested_struct4.c,
+ testsuite/libffi.call/nested_struct5.c,
+ testsuite/libffi.call/nested_struct6.c,
+ testsuite/libffi.call/nested_struct7.c,
+ testsuite/libffi.call/nested_struct8.c,
+ testsuite/libffi.call/nested_struct9.c,
+ testsuite/libffi.call/problem1.c,
+ testsuite/libffi.call/return_ldl.c,
+ testsuite/libffi.call/return_ll1.c,
+ testsuite/libffi.call/stret_large.c,
+ testsuite/libffi.call/stret_large2.c,
+ testsuite/libffi.call/stret_medium.c,
+ testsuite/libffi.call/stret_medium2.c,
+ testsuite/libffi.special/unwindtest.cc: use ffi_closure_alloc instead
+ of checking for MMAP. Use intptr_t instead of long casts.
+
+2009-06-11 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * testsuite/libffi.call/cls_longdouble_va.c: Add xfail sh*-*-linux-*.
+ * testsuite/libffi.call/err_bad_abi.c: Add xfail sh*-*-*.
+ * testsuite/libffi.call/err_bad_typedef.c: Likewise.
+
+2009-06-09 Andrew Haley <aph@redhat.com>
+
+ * src/x86/freebsd.S: Add missing file.
+
+2009-06-08 Andrew Haley <aph@redhat.com>
+
+ Import from libffi 3.0.8:
+
+ * doc/libffi.texi: New file.
+ * doc/libffi.info: Likewise.
+ * doc/stamp-vti: Likewise.
+ * man/Makefile.am: New file.
+ * man/ffi_call.3: New file.
+
+ * Makefile.am (EXTRA_DIST): Add src/x86/darwin64.S,
+ src/dlmalloc.c.
+ (nodist_libffi_la_SOURCES): Add X86_FREEBSD.
+
+ * configure.ac: Bump version to 3.0.8.
+ parisc*-*-linux*: Add.
+ i386-*-freebsd* | i386-*-openbsd*: Add.
+ powerpc-*-beos*: Add.
+ AM_CONDITIONAL X86_FREEBSD: Add.
+ AC_CONFIG_FILES: Add man/Makefile.
+
+ * include/ffi.h.in (FFI_FN): Change void (*)() to void (*)(void).
+
+2009-06-08 Andrew Haley <aph@redhat.com>
+
+ * README: Import from libffi 3.0.8.
+
+2009-06-08 Andrew Haley <aph@redhat.com>
+
+ * testsuite/libffi.call/err_bad_abi.c: Add xfails.
+ * testsuite/libffi.call/cls_longdouble_va.c: Add xfails.
+ * testsuite/libffi.call/cls_dbls_struct.c: Add xfail x86_64-*-linux-*.
+ * testsuite/libffi.call/err_bad_typedef.c: Add xfails.
+
+ * testsuite/libffi.call/stret_medium2.c: Add __UNUSED__ to args.
+ * testsuite/libffi.call/stret_medium.c: Likewise.
+ * testsuite/libffi.call/stret_large2.c: Likewise.
+ * testsuite/libffi.call/stret_large.c: Likewise.
+
+2008-12-26 Timothy Wall <twall@users.sf.net>
+
+ * testsuite/libffi.call/cls_longdouble.c,
+ testsuite/libffi.call/cls_longdouble_va.c,
+ testsuite/libffi.call/cls_align_longdouble.c,
+ testsuite/libffi.call/cls_align_longdouble_split.c,
+ testsuite/libffi.call/cls_align_longdouble_split2.c: mark expected
+ failures on x86_64 cygwin/mingw.
+
+2008-12-22 Timothy Wall <twall@users.sf.net>
+
+ * testsuite/libffi.call/closure_fn0.c,
+ testsuite/libffi.call/closure_fn1.c,
+ testsuite/libffi.call/closure_fn2.c,
+ testsuite/libffi.call/closure_fn3.c,
+ testsuite/libffi.call/closure_fn4.c,
+ testsuite/libffi.call/closure_fn5.c,
+ testsuite/libffi.call/closure_fn6.c,
+ testsuite/libffi.call/closure_loc_fn0.c,
+ testsuite/libffi.call/closure_stdcall.c,
+ testsuite/libffi.call/cls_align_pointer.c,
+ testsuite/libffi.call/cls_pointer.c,
+ testsuite/libffi.call/cls_pointer_stack.c: use portable cast from
+ pointer to integer (intptr_t).
+ * testsuite/libffi.call/cls_longdouble.c: disable for win64.
+
+2008-07-24 Anthony Green <green@redhat.com>
+
+ * testsuite/libffi.call/cls_dbls_struct.c,
+ testsuite/libffi.call/cls_double_va.c,
+ testsuite/libffi.call/cls_longdouble.c,
+ testsuite/libffi.call/cls_longdouble_va.c,
+ testsuite/libffi.call/cls_pointer.c,
+ testsuite/libffi.call/cls_pointer_stack.c,
+ testsuite/libffi.call/err_bad_abi.c: Clean up failures from
+ compiler warnings.
+
+2008-03-04 Anthony Green <green@redhat.com>
+ Blake Chaffin
+ hos@tamanegi.org
+
+ * testsuite/libffi.call/cls_align_longdouble_split2.c
+ testsuite/libffi.call/cls_align_longdouble_split.c
+ testsuite/libffi.call/cls_dbls_struct.c
+ testsuite/libffi.call/cls_double_va.c
+ testsuite/libffi.call/cls_longdouble.c
+ testsuite/libffi.call/cls_longdouble_va.c
+ testsuite/libffi.call/cls_pointer.c
+ testsuite/libffi.call/cls_pointer_stack.c
+ testsuite/libffi.call/err_bad_abi.c
+ testsuite/libffi.call/err_bad_typedef.c
+ testsuite/libffi.call/stret_large2.c
+ testsuite/libffi.call/stret_large.c
+ testsuite/libffi.call/stret_medium2.c
+ testsuite/libffi.call/stret_medium.c: New tests from Apple.
+
+2009-06-05 Andrew Haley <aph@redhat.com>
+
+ * src/x86/ffitarget.h, src/x86/ffi.c: Merge stdcall changes from
+ libffi.
+
+2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/x86/ffitarget.h, src/x86/win32.S, src/x86/ffi.c: Back out
+ stdcall changes.
+
+2008-02-26 Anthony Green <green@redhat.com>
+ Thomas Heller <theller@ctypes.org>
+
+ * src/x86/ffi.c (ffi_closure_SYSV_inner): Change C++ comment to C
+ comment.
+
+2008-02-03 Timothy Wall <twall@users.sf.net>
+
+ * src/x86/ffi.c (FFI_INIT_TRAMPOLINE_STDCALL): Calculate jump return
+ offset based on code pointer, not data pointer.
+
+2008-01-31 Timothy Wall <twall@users.sf.net>
+
+ * testsuite/libffi.call/closure_stdcall.c: Add test for stdcall
+ closures.
+ * src/x86/ffitarget.h: Increase size of trampoline for stdcall
+ closures.
+ * src/x86/win32.S: Add assembly for stdcall closure.
+ * src/x86/ffi.c: Initialize stdcall closure trampoline.
+
+2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * include/ffi.h.in: Change void (*)() to void (*)(void).
+ * src/x86/ffi.c: Likewise.
+
+2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/powerpc/ppc_closure.S: Insert licence header.
+ * src/powerpc/linux64_closure.S: Likewise.
+ * src/m68k/sysv.S: Likewise.
+
+ * src/sh64/ffi.c: Change void (*)() to void (*)(void).
+ * src/powerpc/ffi.c: Likewise.
+ * src/powerpc/ffi_darwin.c: Likewise.
+ * src/m32r/ffi.c: Likewise.
+ * src/sh64/ffi.c: Likewise.
+ * src/x86/ffi64.c: Likewise.
+ * src/alpha/ffi.c: Likewise.
+ * src/alpha/osf.S: Likewise.
+ * src/frv/ffi.c: Likewise.
+ * src/s390/ffi.c: Likewise.
+ * src/pa/ffi.c: Likewise.
+ * src/pa/hpux32.S: Likewise.
+ * src/ia64/unix.S: Likewise.
+ * src/ia64/ffi.c: Likewise.
+ * src/sparc/ffi.c: Likewise.
+ * src/mips/ffi.c: Likewise.
+ * src/sh/ffi.c: Likewise.
+
+2008-02-15 David Daney <ddaney@avtrex.com>
+
+ * src/mips/ffi.c (USE__BUILTIN___CLEAR_CACHE):
+ Define (conditionally), and use it to include cachectl.h.
+ (ffi_prep_closure_loc): Fix cache flushing.
+ * src/mips/ffitarget.h (_ABIN32, _ABI64, _ABIO32): Define.
+
+2009-06-04 Andrew Haley <aph@redhat.com>
+
+ include/ffi.h.in,
+ src/arm/ffitarget.h,
+ src/arm/ffi.c,
+ src/arm/sysv.S,
+ src/powerpc/ffitarget.h,
+ src/closures.c,
+ src/sh64/ffitarget.h,
+ src/sh64/ffi.c,
+ src/sh64/sysv.S,
+ src/types.c,
+ src/x86/ffi64.c,
+ src/x86/ffitarget.h,
+ src/x86/win32.S,
+ src/x86/darwin.S,
+ src/x86/ffi.c,
+ src/x86/sysv.S,
+ src/x86/unix64.S,
+ src/alpha/ffitarget.h,
+ src/alpha/ffi.c,
+ src/alpha/osf.S,
+ src/m68k/ffitarget.h,
+ src/frv/ffitarget.h,
+ src/frv/ffi.c,
+ src/s390/ffitarget.h,
+ src/s390/sysv.S,
+ src/cris/ffitarget.h,
+ src/pa/linux.S,
+ src/pa/ffitarget.h,
+ src/pa/ffi.c,
+ src/raw_api.c,
+ src/ia64/ffitarget.h,
+ src/ia64/unix.S,
+ src/ia64/ffi.c,
+ src/ia64/ia64_flags.h,
+ src/java_raw_api.c,
+ src/debug.c,
+ src/sparc/v9.S,
+ src/sparc/ffitarget.h,
+ src/sparc/ffi.c,
+ src/sparc/v8.S,
+ src/mips/ffitarget.h,
+ src/mips/n32.S,
+ src/mips/o32.S,
+ src/mips/ffi.c,
+ src/prep_cif.c,
+ src/sh/ffitarget.h,
+ src/sh/ffi.c,
+ src/sh/sysv.S: Update license text.
+
+2009-05-22 Dave Korn <dave.korn.cygwin@gmail.com>
+
+ * src/x86/win32.S (_ffi_closure_STDCALL): New function.
+ (.eh_frame): Add FDE for it.
+
+2009-05-22 Dave Korn <dave.korn.cygwin@gmail.com>
+
+ * configure.ac: Also check if assembler supports pc-relative
+ relocs on X86_WIN32 targets.
+ * configure: Regenerate.
+ * src/x86/win32.S (ffi_prep_args): Declare extern, not global.
+ (_ffi_call_SYSV): Add missing function type symbol .def and
+ add EH markup labels.
+ (_ffi_call_STDCALL): Likewise.
+ (_ffi_closure_SYSV): Likewise.
+ (_ffi_closure_raw_SYSV): Likewise.
+ (.eh_frame): Add hand-crafted EH data.
+
+2009-04-09 Jakub Jelinek <jakub@redhat.com>
+
+ * testsuite/lib/libffi-dg.exp: Change copyright header to refer to
+ version 3 of the GNU General Public License and to point readers
+ at the COPYING3 file and the FSF's license web page.
+ * testsuite/libffi.call/call.exp: Likewise.
+ * testsuite/libffi.special/special.exp: Likewise.
+
+2009-03-01 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
+
+ * configure: Regenerate.
+
+2008-12-18 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ PR libffi/26048
+ * configure.ac (HAVE_AS_X86_PCREL): New test.
+ * configure: Regenerate.
+ * fficonfig.h.in: Regenerate.
+ * src/x86/sysv.S [!FFI_NO_RAW_API]: Precalculate
+ RAW_CLOSURE_CIF_OFFSET, RAW_CLOSURE_FUN_OFFSET,
+ RAW_CLOSURE_USER_DATA_OFFSET for the Solaris 10/x86 assembler.
+ (.eh_frame): Only use SYMBOL-. iff HAVE_AS_X86_PCREL.
+ * src/x86/unix64.S (.Lstore_table): Move to .text section.
+ (.Lload_table): Likewise.
+ (.eh_frame): Only use SYMBOL-. iff HAVE_AS_X86_PCREL.
+
+2008-12-18 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
+
+ * configure: Regenerate.
+
+2008-11-21 Eric Botcazou <ebotcazou@adacore.com>
+
+ * src/sparc/ffi.c (ffi_prep_cif_machdep): Add support for
+ signed/unsigned int8/16 return values.
+ * src/sparc/v8.S (ffi_call_v8): Likewise.
+ (ffi_closure_v8): Likewise.
+
+2008-09-26 Peter O'Gorman <pogma@thewrittenword.com>
+ Steve Ellcey <sje@cup.hp.com>
+
+ * configure: Regenerate for new libtool.
+ * Makefile.in: Ditto.
+ * include/Makefile.in: Ditto.
+ * aclocal.m4: Ditto.
+
+2008-08-25 Andreas Tobler <a.tobler@schweiz.org>
+
+ * src/powerpc/ffitarget.h (ffi_abi): Add FFI_LINUX and
+ FFI_LINUX_SOFT_FLOAT to the POWERPC_FREEBSD enum.
+ Add note about flag bits used for FFI_SYSV_TYPE_SMALL_STRUCT.
+ Adjust copyright notice.
+ * src/powerpc/ffi.c: Add two new flags to indicate if we have one
+ register or two register to use for FFI_SYSV structs.
+ (ffi_prep_cif_machdep): Pass the right register flag introduced above.
+ (ffi_closure_helper_SYSV): Fix the return type for
+ FFI_SYSV_TYPE_SMALL_STRUCT. Comment.
+ Adjust copyright notice.
+
+2008-07-16 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/ffi.c (ffi_prep_closure_loc): Turn INSN into an unsigned
+ int.
+
+2008-06-17 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
+
+ * configure: Regenerate.
+ * include/Makefile.in: Regenerate.
+ * testsuite/Makefile.in: Regenerate.
+
+2008-06-07 Joseph Myers <joseph@codesourcery.com>
+
+ * configure.ac (parisc*-*-linux*, powerpc-*-sysv*,
+ powerpc-*-beos*): Remove.
+ * configure: Regenerate.
+
+2008-05-09 Julian Brown <julian@codesourcery.com>
+
+ * Makefile.am (LTLDFLAGS): New.
+ (libffi_la_LDFLAGS): Use above.
+ * Makefile.in: Regenerate.
+
+2008-04-18 Paolo Bonzini <bonzini@gnu.org>
+
+ PR bootstrap/35457
+ * aclocal.m4: Regenerate.
+ * configure: Regenerate.
+
+2008-03-26 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/sysv.S: Add .note.GNU-stack on Linux.
+ * src/sh64/sysv.S: Likewise.
+
+2008-03-26 Daniel Jacobowitz <dan@debian.org>
+
+ * src/arm/sysv.S: Fix ARM comment marker.
+
+2008-03-26 Jakub Jelinek <jakub@redhat.com>
+
+ * src/alpha/osf.S: Add .note.GNU-stack on Linux.
+ * src/s390/sysv.S: Likewise.
+ * src/powerpc/ppc_closure.S: Likewise.
+ * src/powerpc/sysv.S: Likewise.
+ * src/x86/unix64.S: Likewise.
+ * src/x86/sysv.S: Likewise.
+ * src/sparc/v8.S: Likewise.
+ * src/sparc/v9.S: Likewise.
+ * src/m68k/sysv.S: Likewise.
+ * src/arm/sysv.S: Likewise.
+
+2008-03-16 Ralf Wildenhues <Ralf.Wildenhues@gmx.de>
+
+ * aclocal.m4: Regenerate.
+ * configure: Likewise.
+ * Makefile.in: Likewise.
+ * include/Makefile.in: Likewise.
+ * testsuite/Makefile.in: Likewise.
+
+2008-02-12 Bjoern Koenig <bkoenig@alpha-tierchen.de>
+ Andreas Tobler <a.tobler@schweiz.org>
+
+ * configure.ac: Add amd64-*-freebsd* target.
+ * configure: Regenerate.
+
+2008-01-30 H.J. Lu <hongjiu.lu@intel.com>
+
+ PR libffi/34612
+ * src/x86/sysv.S (ffi_closure_SYSV): Pop 4 byte from stack when
+ returning struct.
+
+ * testsuite/libffi.call/call.exp: Add "-O2 -fomit-frame-pointer"
+ tests.
+
+2008-01-24 David Edelsohn <edelsohn@gnu.org>
+
+ * configure: Regenerate.
+
+2008-01-06 Andreas Tobler <a.tobler@schweiz.org>
+
+ * src/x86/ffi.c (ffi_prep_cif_machdep): Fix thinko.
+
+2008-01-05 Andreas Tobler <a.tobler@schweiz.org>
+
+ PR testsuite/32843
+ * src/x86/ffi.c (ffi_prep_cif_machdep): Add code for
+ signed/unsigned int8/16 for X86_DARWIN.
+ Updated copyright info.
+ Handle one and two byte structs with special cif->flags.
+ * src/x86/ffitarget.h: Add special types for one and two byte structs.
+ Updated copyright info.
+ * src/x86/darwin.S (ffi_call_SYSV): Rewrite to use a jump table like
+ sysv.S
+ Remove code to pop args from the stack after call.
+ Special-case signed/unsigned for int8/16, one and two byte structs.
+ (ffi_closure_raw_SYSV): Handle FFI_TYPE_UINT8,
+ FFI_TYPE_SINT8, FFI_TYPE_UINT16, FFI_TYPE_SINT16, FFI_TYPE_UINT32,
+ FFI_TYPE_SINT32.
+ Updated copyright info.
+
+2007-12-08 David Daney <ddaney@avtrex.com>
+
+ * src/mips/n32.S (ffi_call_N32): Replace dadd with ADDU, dsub with
+ SUBU, add with ADDU and use smaller code sequences.
+
+2007-12-07 David Daney <ddaney@avtrex.com>
+
+ * src/mips/ffi.c (ffi_prep_cif_machdep): Handle long double return
+ type.
+
+2007-12-06 David Daney <ddaney@avtrex.com>
+
+ * include/ffi.h.in (FFI_SIZEOF_JAVA_RAW): Define if not already
+ defined.
+ (ffi_java_raw): New typedef.
+ (ffi_java_raw_call, ffi_java_ptrarray_to_raw,
+ ffi_java_raw_to_ptrarray): Change parameter types from ffi_raw to
+ ffi_java_raw.
+ (ffi_java_raw_closure) : Same.
+ (ffi_prep_java_raw_closure, ffi_prep_java_raw_closure_loc): Change
+ parameter types.
+ * src/java_raw_api.c (ffi_java_raw_size): Replace FFI_SIZEOF_ARG with
+ FFI_SIZEOF_JAVA_RAW.
+ (ffi_java_raw_to_ptrarray): Change type of raw to ffi_java_raw.
+ Replace FFI_SIZEOF_ARG with FFI_SIZEOF_JAVA_RAW. Use
+ sizeof(ffi_java_raw) for alignment calculations.
+ (ffi_java_ptrarray_to_raw): Same.
+ (ffi_java_rvalue_to_raw): Add special handling for FFI_TYPE_POINTER
+ if FFI_SIZEOF_JAVA_RAW == 4.
+ (ffi_java_raw_to_rvalue): Same.
+ (ffi_java_raw_call): Change type of raw to ffi_java_raw.
+ (ffi_java_translate_args): Same.
+ (ffi_prep_java_raw_closure_loc, ffi_prep_java_raw_closure): Change
+ parameter types.
+ * src/mips/ffitarget.h (FFI_SIZEOF_JAVA_RAW): Define for N32 ABI.
+
+2007-12-06 David Daney <ddaney@avtrex.com>
+
+ * src/mips/n32.S (ffi_closure_N32): Use 64-bit add instruction on
+ pointer values.
+
+2007-12-01 Andreas Tobler <a.tobler@schweiz.org>
+
+ PR libffi/31937
+ * src/powerpc/ffitarget.h: Introduce new ABI FFI_LINUX_SOFT_FLOAT.
+ Add local FFI_TYPE_UINT128 to handle soft-float long-double-128.
+ * src/powerpc/ffi.c: Distinguish between __NO_FPRS__ and not and
+ set the NUM_FPR_ARG_REGISTERS according to.
+ Add support for potential soft-float support under hard-float
+ architecture.
+ (ffi_prep_args_SYSV): Set NUM_FPR_ARG_REGISTERS to 0 in case of
+ FFI_LINUX_SOFT_FLOAT, handle float, doubles and long-doubles according
+ to the FFI_LINUX_SOFT_FLOAT ABI.
+ (ffi_prep_cif_machdep): Likewise.
+ (ffi_closure_helper_SYSV): Likewise.
+ * src/powerpc/ppc_closure.S: Make sure not to store float/double
+ on archs where __NO_FPRS__ is true.
+ Add FFI_TYPE_UINT128 support.
+ * src/powerpc/sysv.S: Add support for soft-float long-double-128.
+ Adjust copyright notice.
+
+2007-11-25 Andreas Tobler <a.tobler@schweiz.org>
+
+ * src/closures.c: Move defintion of MAYBE_UNUSED from here to ...
+ * include/ffi_common.h: ... here.
+ Update copyright.
+
+2007-11-17 Andreas Tobler <a.tobler@schweiz.org>
+
+ * src/powerpc/sysv.S: Load correct cr to compare if we have long double.
+ * src/powerpc/linux64.S: Likewise.
+ * src/powerpc/ffi.c: Add a comment to show which part goes into cr6.
+ * testsuite/libffi.call/return_ldl.c: New test.
+
+2007-09-04 <aph@redhat.com>
+
+ * src/arm/sysv.S (UNWIND): New.
+ (Whole file): Conditionally compile unwinder directives.
+ * src/arm/sysv.S: Add unwinder directives.
+
+ * src/arm/ffi.c (ffi_prep_args): Align structs by at least 4 bytes.
+ Only treat r0 as a struct address if we're actually returning a
+ struct by address.
+ Only copy the bytes that are actually within a struct.
+ (ffi_prep_cif_machdep): A Composite Type not larger than 4 bytes
+ is returned in r0, not passed by address.
+ (ffi_call): Allocate a word-sized temporary for the case where
+ a composite is returned in r0.
+ (ffi_prep_incoming_args_SYSV): Align as necessary.
+
+2007-08-05 Steven Newbury <s_j_newbury@yahoo.co.uk>
+
+ * src/arm/ffi.c (FFI_INIT_TRAMPOLINE): Use __clear_cache instead of
+ directly using the sys_cacheflush syscall.
+
+2007-07-27 Andrew Haley <aph@redhat.com>
+
+ * src/arm/sysv.S (ffi_closure_SYSV): Add soft-float.
+
+2007-09-03 Maciej W. Rozycki <macro@linux-mips.org>
+
+ * Makefile.am: Unify MIPS_IRIX and MIPS_LINUX into MIPS.
+ * configure.ac: Likewise.
+ * Makefile.in: Regenerate.
+ * include/Makefile.in: Likewise.
+ * testsuite/Makefile.in: Likewise.
+ * configure: Likewise.
+
+2007-08-24 David Daney <ddaney@avtrex.com>
+
+ * testsuite/libffi.call/return_sl.c: New test.
+
+2007-08-10 David Daney <ddaney@avtrex.com>
+
+ * testsuite/libffi.call/cls_multi_ushort.c,
+ testsuite/libffi.call/cls_align_uint16.c,
+ testsuite/libffi.call/nested_struct1.c,
+ testsuite/libffi.call/nested_struct3.c,
+ testsuite/libffi.call/cls_7_1_byte.c,
+ testsuite/libffi.call/nested_struct5.c,
+ testsuite/libffi.call/cls_double.c,
+ testsuite/libffi.call/nested_struct7.c,
+ testsuite/libffi.call/cls_sint.c,
+ testsuite/libffi.call/nested_struct9.c,
+ testsuite/libffi.call/cls_20byte1.c,
+ testsuite/libffi.call/cls_multi_sshortchar.c,
+ testsuite/libffi.call/cls_align_sint64.c,
+ testsuite/libffi.call/cls_3byte2.c,
+ testsuite/libffi.call/cls_multi_schar.c,
+ testsuite/libffi.call/cls_multi_uchar.c,
+ testsuite/libffi.call/cls_19byte.c,
+ testsuite/libffi.call/cls_9byte1.c,
+ testsuite/libffi.call/cls_align_float.c,
+ testsuite/libffi.call/closure_fn1.c,
+ testsuite/libffi.call/problem1.c,
+ testsuite/libffi.call/closure_fn3.c,
+ testsuite/libffi.call/cls_sshort.c,
+ testsuite/libffi.call/closure_fn5.c,
+ testsuite/libffi.call/cls_align_double.c,
+ testsuite/libffi.call/nested_struct.c,
+ testsuite/libffi.call/cls_2byte.c,
+ testsuite/libffi.call/nested_struct10.c,
+ testsuite/libffi.call/cls_4byte.c,
+ testsuite/libffi.call/cls_6byte.c,
+ testsuite/libffi.call/cls_8byte.c,
+ testsuite/libffi.call/cls_multi_sshort.c,
+ testsuite/libffi.call/cls_align_sint16.c,
+ testsuite/libffi.call/cls_align_uint32.c,
+ testsuite/libffi.call/cls_20byte.c,
+ testsuite/libffi.call/cls_float.c,
+ testsuite/libffi.call/nested_struct2.c,
+ testsuite/libffi.call/cls_5_1_byte.c,
+ testsuite/libffi.call/nested_struct4.c,
+ testsuite/libffi.call/cls_24byte.c,
+ testsuite/libffi.call/nested_struct6.c,
+ testsuite/libffi.call/cls_64byte.c,
+ testsuite/libffi.call/nested_struct8.c,
+ testsuite/libffi.call/cls_uint.c,
+ testsuite/libffi.call/cls_multi_ushortchar.c,
+ testsuite/libffi.call/cls_schar.c,
+ testsuite/libffi.call/cls_uchar.c,
+ testsuite/libffi.call/cls_align_uint64.c,
+ testsuite/libffi.call/cls_ulonglong.c,
+ testsuite/libffi.call/cls_align_longdouble.c,
+ testsuite/libffi.call/cls_1_1byte.c,
+ testsuite/libffi.call/cls_12byte.c,
+ testsuite/libffi.call/cls_3_1byte.c,
+ testsuite/libffi.call/cls_3byte1.c,
+ testsuite/libffi.call/cls_4_1byte.c,
+ testsuite/libffi.call/cls_6_1_byte.c,
+ testsuite/libffi.call/cls_16byte.c,
+ testsuite/libffi.call/cls_18byte.c,
+ testsuite/libffi.call/closure_fn0.c,
+ testsuite/libffi.call/cls_9byte2.c,
+ testsuite/libffi.call/closure_fn2.c,
+ testsuite/libffi.call/closure_fn4.c,
+ testsuite/libffi.call/cls_ushort.c,
+ testsuite/libffi.call/closure_fn6.c,
+ testsuite/libffi.call/cls_5byte.c,
+ testsuite/libffi.call/cls_align_pointer.c,
+ testsuite/libffi.call/cls_7byte.c,
+ testsuite/libffi.call/cls_align_sint32.c,
+ testsuite/libffi.special/unwindtest_ffi_call.cc,
+ testsuite/libffi.special/unwindtest.cc: Remove xfail for mips64*-*-*.
+
+2007-08-10 David Daney <ddaney@avtrex.com>
+
+ PR libffi/28313
+ * configure.ac: Don't treat mips64 as a special case.
+ * Makefile.am (nodist_libffi_la_SOURCES): Add n32.S.
+ * configure: Regenerate
+ * Makefile.in: Ditto.
+ * fficonfig.h.in: Ditto.
+ * src/mips/ffitarget.h (REG_L, REG_S, SUBU, ADDU, SRL, LI): Indent.
+ (LA, EH_FRAME_ALIGN, FDE_ADDR_BYTES): New preprocessor macros.
+ (FFI_DEFAULT_ABI): Set for n64 case.
+ (FFI_CLOSURES, FFI_TRAMPOLINE_SIZE): Define for n32 and n64 cases.
+ * src/mips/n32.S (ffi_call_N32): Add debug macros and labels for FDE.
+ (ffi_closure_N32): New function.
+ (.eh_frame): New section
+ * src/mips/o32.S: Clean up comments.
+ (ffi_closure_O32): Pass ffi_closure parameter in $12.
+ * src/mips/ffi.c: Use FFI_MIPS_N32 instead of
+ _MIPS_SIM == _ABIN32 throughout.
+ (FFI_MIPS_STOP_HERE): New, use in place of
+ ffi_stop_here.
+ (ffi_prep_args): Use unsigned long to hold pointer values. Rewrite
+ to support n32/n64 ABIs.
+ (calc_n32_struct_flags): Rewrite.
+ (calc_n32_return_struct_flags): Remove unused variable. Reverse
+ position of flag bits.
+ (ffi_prep_cif_machdep): Rewrite n32 portion.
+ (ffi_call): Enable for n64. Add special handling for small structure
+ return values.
+ (ffi_prep_closure_loc): Add n32 and n64 support.
+ (ffi_closure_mips_inner_O32): Add cast to silence warning.
+ (copy_struct_N32, ffi_closure_mips_inner_N32): New functions.
+
+2007-08-08 David Daney <ddaney@avtrex.com>
+
+ * testsuite/libffi.call/ffitest.h (ffi_type_mylong): Remove definition.
+ * testsuite/libffi.call/cls_align_uint16.c (main): Use correct type
+ specifiers.
+ * testsuite/libffi.call/nested_struct1.c (main): Ditto.
+ * testsuite/libffi.call/cls_sint.c (main): Ditto.
+ * testsuite/libffi.call/nested_struct9.c (main): Ditto.
+ * testsuite/libffi.call/cls_20byte1.c (main): Ditto.
+ * testsuite/libffi.call/cls_9byte1.c (main): Ditto.
+ * testsuite/libffi.call/closure_fn1.c (main): Ditto.
+ * testsuite/libffi.call/closure_fn3.c (main): Ditto.
+ * testsuite/libffi.call/return_dbl2.c (main): Ditto.
+ * testsuite/libffi.call/cls_sshort.c (main): Ditto.
+ * testsuite/libffi.call/return_fl3.c (main): Ditto.
+ * testsuite/libffi.call/closure_fn5.c (main): Ditto.
+ * testsuite/libffi.call/nested_struct.c (main): Ditto.
+ * testsuite/libffi.call/nested_struct10.c (main): Ditto.
+ * testsuite/libffi.call/return_ll1.c (main): Ditto.
+ * testsuite/libffi.call/cls_8byte.c (main): Ditto.
+ * testsuite/libffi.call/cls_align_uint32.c (main): Ditto.
+ * testsuite/libffi.call/cls_align_sint16.c (main): Ditto.
+ * testsuite/libffi.call/cls_20byte.c (main): Ditto.
+ * testsuite/libffi.call/nested_struct2.c (main): Ditto.
+ * testsuite/libffi.call/cls_24byte.c (main): Ditto.
+ * testsuite/libffi.call/nested_struct6.c (main): Ditto.
+ * testsuite/libffi.call/cls_uint.c (main): Ditto.
+ * testsuite/libffi.call/cls_12byte.c (main): Ditto.
+ * testsuite/libffi.call/cls_16byte.c (main): Ditto.
+ * testsuite/libffi.call/closure_fn0.c (main): Ditto.
+ * testsuite/libffi.call/cls_9byte2.c (main): Ditto.
+ * testsuite/libffi.call/closure_fn2.c (main): Ditto.
+ * testsuite/libffi.call/return_dbl1.c (main): Ditto.
+ * testsuite/libffi.call/closure_fn4.c (main): Ditto.
+ * testsuite/libffi.call/closure_fn6.c (main): Ditto.
+ * testsuite/libffi.call/cls_align_sint32.c (main): Ditto.
+
+2007-08-07 Andrew Haley <aph@redhat.com>
+
+ * src/x86/sysv.S (ffi_closure_raw_SYSV): Fix typo in previous
+ checkin.
+
+2007-08-06 Andrew Haley <aph@redhat.com>
+
+ PR testsuite/32843
+ * src/x86/sysv.S (ffi_closure_raw_SYSV): Handle FFI_TYPE_UINT8,
+ FFI_TYPE_SINT8, FFI_TYPE_UINT16, FFI_TYPE_SINT16, FFI_TYPE_UINT32,
+ FFI_TYPE_SINT32.
+
+2007-08-02 David Daney <ddaney@avtrex.com>
+
+ * testsuite/libffi.call/return_ul.c (main): Define return type as
+ ffi_arg. Use proper printf conversion specifier.
+
+2007-07-30 Andrew Haley <aph@redhat.com>
+
+ PR testsuite/32843
+ * src/x86/ffi.c (ffi_prep_cif_machdep): in x86 case, add code for
+ signed/unsigned int8/16.
+ * src/x86/sysv.S (ffi_call_SYSV): Rewrite to:
+ Use a jump table.
+ Remove code to pop args from the stack after call.
+ Special-case signed/unsigned int8/16.
+ * testsuite/libffi.call/return_sc.c (main): Revert.
+
+2007-07-26 Richard Guenther <rguenther@suse.de>
+
+ PR testsuite/32843
+ * testsuite/libffi.call/return_sc.c (main): Verify call
+ result as signed char, not ffi_arg.
+
+2007-07-16 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * configure.ac (i?86-*-solaris2.1[0-9]): Set TARGET to X86_64.
+ * configure: Regenerate.
+
+2007-07-11 David Daney <ddaney@avtrex.com>
+
+ * src/mips/ffi.c: Don't include sys/cachectl.h.
+ (ffi_prep_closure_loc): Use __builtin___clear_cache() instead of
+ cacheflush().
+
+2007-05-18 Aurelien Jarno <aurelien@aurel32.net>
+
+ * src/arm/ffi.c (ffi_prep_closure_loc): Renamed and ajusted
+ from (ffi_prep_closure): ... this.
+ (FFI_INIT_TRAMPOLINE): Adjust.
+
+2005-12-31 Phil Blundell <pb@reciva.com>
+
+ * src/arm/ffi.c (ffi_prep_incoming_args_SYSV,
+ ffi_closure_SYSV_inner, ffi_prep_closure): New, add closure support.
+ * src/arm/sysv.S(ffi_closure_SYSV): Likewise.
+ * src/arm/ffitarget.h (FFI_TRAMPOLINE_SIZE): Likewise.
+ (FFI_CLOSURES): Enable closure support.
+
+2007-07-03 Andrew Haley <aph@hedges.billgatliff.com>
+
+ * testsuite/libffi.call/cls_multi_ushort.c,
+ testsuite/libffi.call/cls_align_uint16.c,
+ testsuite/libffi.call/nested_struct1.c,
+ testsuite/libffi.call/nested_struct3.c,
+ testsuite/libffi.call/cls_7_1_byte.c,
+ testsuite/libffi.call/cls_double.c,
+ testsuite/libffi.call/nested_struct5.c,
+ testsuite/libffi.call/nested_struct7.c,
+ testsuite/libffi.call/cls_sint.c,
+ testsuite/libffi.call/nested_struct9.c,
+ testsuite/libffi.call/cls_20byte1.c,
+ testsuite/libffi.call/cls_multi_sshortchar.c,
+ testsuite/libffi.call/cls_align_sint64.c,
+ testsuite/libffi.call/cls_3byte2.c,
+ testsuite/libffi.call/cls_multi_schar.c,
+ testsuite/libffi.call/cls_multi_uchar.c,
+ testsuite/libffi.call/cls_19byte.c,
+ testsuite/libffi.call/cls_9byte1.c,
+ testsuite/libffi.call/cls_align_float.c,
+ testsuite/libffi.call/closure_fn1.c,
+ testsuite/libffi.call/problem1.c,
+ testsuite/libffi.call/closure_fn3.c,
+ testsuite/libffi.call/cls_sshort.c,
+ testsuite/libffi.call/closure_fn5.c,
+ testsuite/libffi.call/cls_align_double.c,
+ testsuite/libffi.call/cls_2byte.c,
+ testsuite/libffi.call/nested_struct.c,
+ testsuite/libffi.call/nested_struct10.c,
+ testsuite/libffi.call/cls_4byte.c,
+ testsuite/libffi.call/cls_6byte.c,
+ testsuite/libffi.call/cls_8byte.c,
+ testsuite/libffi.call/cls_multi_sshort.c,
+ testsuite/libffi.call/cls_align_uint32.c,
+ testsuite/libffi.call/cls_align_sint16.c,
+ testsuite/libffi.call/cls_float.c,
+ testsuite/libffi.call/cls_20byte.c,
+ testsuite/libffi.call/cls_5_1_byte.c,
+ testsuite/libffi.call/nested_struct2.c,
+ testsuite/libffi.call/cls_24byte.c,
+ testsuite/libffi.call/nested_struct4.c,
+ testsuite/libffi.call/nested_struct6.c,
+ testsuite/libffi.call/cls_64byte.c,
+ testsuite/libffi.call/nested_struct8.c,
+ testsuite/libffi.call/cls_uint.c,
+ testsuite/libffi.call/cls_multi_ushortchar.c,
+ testsuite/libffi.call/cls_schar.c,
+ testsuite/libffi.call/cls_uchar.c,
+ testsuite/libffi.call/cls_align_uint64.c,
+ testsuite/libffi.call/cls_ulonglong.c,
+ testsuite/libffi.call/cls_align_longdouble.c,
+ testsuite/libffi.call/cls_1_1byte.c,
+ testsuite/libffi.call/cls_12byte.c,
+ testsuite/libffi.call/cls_3_1byte.c,
+ testsuite/libffi.call/cls_3byte1.c,
+ testsuite/libffi.call/cls_4_1byte.c,
+ testsuite/libffi.call/cls_6_1_byte.c,
+ testsuite/libffi.call/cls_16byte.c,
+ testsuite/libffi.call/cls_18byte.c,
+ testsuite/libffi.call/closure_fn0.c,
+ testsuite/libffi.call/cls_9byte2.c,
+ testsuite/libffi.call/closure_fn2.c,
+ testsuite/libffi.call/closure_fn4.c,
+ testsuite/libffi.call/cls_ushort.c,
+ testsuite/libffi.call/closure_fn6.c,
+ testsuite/libffi.call/cls_5byte.c,
+ testsuite/libffi.call/cls_align_pointer.c,
+ testsuite/libffi.call/cls_7byte.c,
+ testsuite/libffi.call/cls_align_sint32.c,
+ testsuite/libffi.special/unwindtest_ffi_call.cc,
+ testsuite/libffi.special/unwindtest.cc: Enable for ARM.
+
+2007-07-05 H.J. Lu <hongjiu.lu@intel.com>
+
+ * aclocal.m4: Regenerated.
+
+2007-06-02 Paolo Bonzini <bonzini@gnu.org>
+
+ * configure: Regenerate.
+
+2007-05-23 Steve Ellcey <sje@cup.hp.com>
+
+ * Makefile.in: Regenerate.
+ * configure: Regenerate.
+ * aclocal.m4: Regenerate.
+ * include/Makefile.in: Regenerate.
+ * testsuite/Makefile.in: Regenerate.
+
+2007-05-10 Roman Zippel <zippel@linux-m68k.org>
+
+ * src/m68k/ffi.c (ffi_prep_incoming_args_SYSV,
+ ffi_closure_SYSV_inner,ffi_prep_closure): New, add closure support.
+ * src/m68k/sysv.S(ffi_closure_SYSV,ffi_closure_struct_SYSV): Likewise.
+ * src/m68k/ffitarget.h (FFI_TRAMPOLINE_SIZE): Likewise.
+ (FFI_CLOSURES): Enable closure support.
+
+2007-05-10 Roman Zippel <zippel@linux-m68k.org>
+
+ * configure.ac (HAVE_AS_CFI_PSEUDO_OP): New test.
+ * configure: Regenerate.
+ * fficonfig.h.in: Regenerate.
+ * src/m68k/sysv.S (CFI_STARTPROC,CFI_ENDPROC,
+ CFI_OFFSET,CFI_DEF_CFA): New macros.
+ (ffi_call_SYSV): Add callframe annotation.
+
+2007-05-10 Roman Zippel <zippel@linux-m68k.org>
+
+ * src/m68k/ffi.c (ffi_prep_args,ffi_prep_cif_machdep): Fix
+ numerous test suite failures.
+ * src/m68k/sysv.S (ffi_call_SYSV): Likewise.
+
+2007-04-11 Paolo Bonzini <bonzini@gnu.org>
+
+ * Makefile.am (EXTRA_DIST): Bring up to date.
+ * Makefile.in: Regenerate.
+ * src/frv/eabi.S: Remove RCS keyword.
+
+2007-04-06 Richard Henderson <rth@redhat.com>
+
+ * configure.ac: Tidy target case.
+ (HAVE_LONG_DOUBLE): Allow the target to override.
+ * configure: Regenerate.
+ * include/ffi.h.in: Don't define ffi_type_foo if
+ LIBFFI_HIDE_BASIC_TYPES is defined.
+ (ffi_type_longdouble): If not HAVE_LONG_DOUBLE, define
+ to ffi_type_double.
+ * types.c (LIBFFI_HIDE_BASIC_TYPES): Define.
+ (FFI_TYPEDEF, ffi_type_void): Mark the data const.
+ (ffi_type_longdouble): Special case for Alpha. Don't define
+ if long double == double.
+
+ * src/alpha/ffi.c (FFI_TYPE_LONGDOUBLE): Assert unique value.
+ (ffi_prep_cif_machdep): Handle it as the 128-bit type.
+ (ffi_call, ffi_closure_osf_inner): Likewise.
+ (ffi_closure_osf_inner): Likewise. Mark hidden.
+ (ffi_call_osf, ffi_closure_osf): Mark hidden.
+ * src/alpha/ffitarget.h (FFI_LAST_ABI): Tidy definition.
+ * src/alpha/osf.S (ffi_call_osf, ffi_closure_osf): Mark hidden.
+ (load_table): Handle 128-bit long double.
+
+ * testsuite/libffi.call/float4.c: Add -mieee for alpha.
+
+2007-04-06 Tom Tromey <tromey@redhat.com>
+
+ PR libffi/31491:
+ * README: Fixed bug in example.
+
+2007-04-03 Jakub Jelinek <jakub@redhat.com>
+
+ * src/closures.c: Include sys/statfs.h.
+ (_GNU_SOURCE): Define on Linux.
+ (FFI_MMAP_EXEC_SELINUX): Define.
+ (selinux_enabled): New variable.
+ (selinux_enabled_check): New function.
+ (is_selinux_enabled): Define.
+ (dlmmap): Use it.
+
+2007-03-24 Uros Bizjak <ubizjak@gmail.com>
+
+ * testsuite/libffi.call/return_fl2.c (return_fl): Mark as static.
+ Use 'volatile float sum' to create sum of floats to avoid false
+ negative due to excess precision on ix86 targets.
+ (main): Ditto.
+
+2007-03-08 Alexandre Oliva <aoliva@redhat.com>
+
+ * src/powerpc/ffi.c (flush_icache): Fix left-over from previous
+ patch.
+ (ffi_prep_closure_loc): Remove unneeded casts. Add needed ones.
+
+2007-03-07 Alexandre Oliva <aoliva@redhat.com>
+
+ * include/ffi.h.in (ffi_closure_alloc, ffi_closure_free): New.
+ (ffi_prep_closure_loc): New.
+ (ffi_prep_raw_closure_loc): New.
+ (ffi_prep_java_raw_closure_loc): New.
+ * src/closures.c: New file.
+ * src/dlmalloc.c [FFI_MMAP_EXEC_WRIT] (struct malloc_segment):
+ Replace sflags with exec_offset.
+ [FFI_MMAP_EXEC_WRIT] (mmap_exec_offset, add_segment_exec_offset,
+ sub_segment_exec_offset): New macros.
+ (get_segment_flags, set_segment_flags, check_segment_merge): New
+ macros.
+ (is_mmapped_segment, is_extern_segment): Use get_segment_flags.
+ (add_segment, sys_alloc, create_mspace, create_mspace_with_base,
+ destroy_mspace): Use new macros.
+ (sys_alloc): Silence warning.
+ * Makefile.am (libffi_la_SOURCES): Add src/closures.c.
+ * Makefile.in: Rebuilt.
+ * src/prep_cif [FFI_CLOSURES] (ffi_prep_closure): Implement in
+ terms of ffi_prep_closure_loc.
+ * src/raw_api.c (ffi_prep_raw_closure_loc): Renamed and adjusted
+ from...
+ (ffi_prep_raw_closure): ... this. Re-implement in terms of the
+ renamed version.
+ * src/java_raw_api (ffi_prep_java_raw_closure_loc): Renamed and
+ adjusted from...
+ (ffi_prep_java_raw_closure): ... this. Re-implement in terms of
+ the renamed version.
+ * src/alpha/ffi.c (ffi_prep_closure_loc): Renamed from
+ (ffi_prep_closure): ... this.
+ * src/pa/ffi.c: Likewise.
+ * src/cris/ffi.c: Likewise. Adjust.
+ * src/frv/ffi.c: Likewise.
+ * src/ia64/ffi.c: Likewise.
+ * src/mips/ffi.c: Likewise.
+ * src/powerpc/ffi_darwin.c: Likewise.
+ * src/s390/ffi.c: Likewise.
+ * src/sh/ffi.c: Likewise.
+ * src/sh64/ffi.c: Likewise.
+ * src/sparc/ffi.c: Likewise.
+ * src/x86/ffi64.c: Likewise.
+ * src/x86/ffi.c: Likewise.
+ (FFI_INIT_TRAMPOLINE): Adjust.
+ (ffi_prep_raw_closure_loc): Renamed and adjusted from...
+ (ffi_prep_raw_closure): ... this.
+ * src/powerpc/ffi.c (ffi_prep_closure_loc): Renamed from
+ (ffi_prep_closure): ... this.
+ (flush_icache): Adjust.
+
+2007-03-07 Alexandre Oliva <aoliva@redhat.com>
+
+ * src/dlmalloc.c: New file, imported version 2.8.3 of Doug
+ Lea's malloc.
+
+2007-03-01 Brooks Moses <brooks.moses@codesourcery.com>
+
+ * Makefile.am: Add dummy install-pdf target.
+ * Makefile.in: Regenerate
+
+2007-02-13 Andreas Krebbel <krebbel1@de.ibm.com>
+
+ * src/s390/ffi.c (ffi_prep_args, ffi_prep_cif_machdep,
+ ffi_closure_helper_SYSV): Add long double handling.
+
+2007-02-02 Jakub Jelinek <jakub@redhat.com>
+
+ * src/powerpc/linux64.S (ffi_call_LINUX64): Move restore of r2
+ immediately after bctrl instruction.
+
+2007-01-18 Alexandre Oliva <aoliva@redhat.com>
+
+ * Makefile.am (all-recursive, install-recursive,
+ mostlyclean-recursive, clean-recursive, distclean-recursive,
+ maintainer-clean-recursive): Add missing targets.
+ * Makefile.in: Rebuilt.
+
+2006-12-14 Andreas Tobler <a.tobler@schweiz.org>
+
+ * configure.ac: Add TARGET for x86_64-*-darwin*.
+ * Makefile.am (nodist_libffi_la_SOURCES): Add rules for 64-bit sources
+ for X86_DARWIN.
+ * src/x86/ffitarget.h: Set trampoline size for x86_64-*-darwin*.
+ * src/x86/darwin64.S: New file for x86_64-*-darwin* support.
+ * configure: Regenerate.
+ * Makefile.in: Regenerate.
+ * include/Makefile.in: Regenerate.
+ * testsuite/Makefile.in: Regenerate.
+ * testsuite/libffi.special/unwindtest_ffi_call.cc: New test case for
+ ffi_call only.
+
+2006-12-13 Andreas Tobler <a.tobler@schweiz.org>
+
+ * aclocal.m4: Regenerate with aclocal -I .. as written in the
+ Makefile.am.
+
+2006-10-31 Geoffrey Keating <geoffk@apple.com>
+
+ * src/powerpc/ffi_darwin.c (darwin_adjust_aggregate_sizes): New.
+ (ffi_prep_cif_machdep): Call darwin_adjust_aggregate_sizes for
+ Darwin.
+ * testsuite/libffi.call/nested_struct4.c: Remove Darwin XFAIL.
+ * testsuite/libffi.call/nested_struct6.c: Remove Darwin XFAIL.
+
+2006-10-10 Paolo Bonzini <bonzini@gnu.org>
+ Sandro Tolaini <tolaini@libero.it>
+
+ * configure.ac [i*86-*-darwin*]: Set X86_DARWIN symbol and
+ conditional.
+ * configure: Regenerated.
+ * Makefile.am (nodist_libffi_la_SOURCES) [X86_DARWIN]: New case.
+ (EXTRA_DIST): Add src/x86/darwin.S.
+ * Makefile.in: Regenerated.
+ * include/Makefile.in: Regenerated.
+ * testsuite/Makefile.in: Regenerated.
+
+ * src/x86/ffi.c (ffi_prep_cif_machdep) [X86_DARWIN]: Treat like
+ X86_WIN32, and additionally align stack to 16 bytes.
+ * src/x86/darwin.S: New, based on sysv.S.
+ * src/prep_cif.c (ffi_prep_cif) [X86_DARWIN]: Align > 8-byte structs.
+
+2006-09-12 David Daney <ddaney@avtrex.com>
+
+ PR libffi/23935
+ * include/Makefile.am: Install both ffi.h and ffitarget.h in
+ $(libdir)/gcc/$(target_alias)/$(gcc_version)/include.
+ * aclocal.m4: Regenerated for automake 1.9.6.
+ * Makefile.in: Regenerated.
+ * include/Makefile.in: Regenerated.
+ * testsuite/Makefile.in: Regenerated.
+
+2006-08-17 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * include/ffi_common.h (struct): Revert accidental commit.
+
+2006-08-15 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * include/ffi_common.h: Remove lint directives.
+ * include/ffi.h.in: Likewise.
+
+2006-07-25 Torsten Schoenfeld <kaffeetisch@gmx.de>
+
+ * include/ffi.h.in (ffi_type_ulong, ffi_type_slong): Define correctly
+ for 32-bit architectures.
+ * testsuite/libffi.call/return_ul.c: New test case.
+
+2006-07-19 David Daney <ddaney@avtrex.com>
+
+ * testsuite/libffi.call/closure_fn6.c: Remove xfail for mips,
+ xfail remains for mips64.
+
+2006-05-23 Carlos O'Donell <carlos@codesourcery.com>
+
+ * Makefile.am: Add install-html target. Add install-html to .PHONY
+ * Makefile.in: Regenerate.
+ * aclocal.m4: Regenerate.
+ * include/Makefile.in: Regenerate.
+ * testsuite/Makefile.in: Regenerate.
+
+2006-05-18 John David Anglin <dave.anglin@nrc-cnrc.gc.ca>
+
+ * pa/ffi.c (ffi_prep_args_pa32): Load floating point arguments from
+ stack slot.
+
+2006-04-22 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * README: Remove notice about 'Crazy Comments'.
+ * src/debug.c: Remove lint directives. Cleanup white spaces.
+ * src/java_raw_api.c: Likewise.
+ * src/prep_cif.c: Likewise.
+ * src/raw_api.c: Likewise.
+ * src/ffitest.c: Delete. No longer needed, all test cases migrated
+ to the testsuite.
+ * src/arm/ffi.c: Remove lint directives.
+ * src/m32r/ffi.c: Likewise.
+ * src/pa/ffi.c: Likewise.
+ * src/powerpc/ffi.c: Likewise.
+ * src/powerpc/ffi_darwin.c: Likewise.
+ * src/sh/ffi.c: Likewise.
+ * src/sh64/ffi.c: Likewise.
+ * src/x86/ffi.c: Likewise.
+ * testsuite/libffi.call/float2.c: Likewise.
+ * testsuite/libffi.call/promotion.c: Likewise.
+ * testsuite/libffi.call/struct1.c: Likewise.
+
+2006-04-13 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/pa/hpux32.S: Correct unwind offset calculation for
+ ffi_closure_pa32.
+ * src/pa/linux.S: Likewise.
+
+2006-04-12 James E Wilson <wilson@specifix.com>
+
+ PR libgcj/26483
+ * src/ia64/ffi.c (stf_spill, ldf_fill): Rewrite as macros.
+ (hfa_type_load): Call stf_spill.
+ (hfa_type_store): Call ldf_fill.
+ (ffi_call): Adjust calls to above routines. Add local temps for
+ macro result.
+
+2006-04-10 Matthias Klose <doko@debian.org>
+
+ * testsuite/lib/libffi-dg.exp (libffi-init): Recognize multilib
+ directory names containing underscores.
+
+2006-04-07 James E Wilson <wilson@specifix.com>
+
+ * testsuite/libffi.call/float4.c: New testcase.
+
+2006-04-05 John David Anglin <dave.anglin@nrc-cnrc.gc.ca>
+ Andreas Tobler <a.tobler@schweiz.ch>
+
+ * Makefile.am: Add PA_HPUX port.
+ * Makefile.in: Regenerate.
+ * include/Makefile.in: Likewise.
+ * testsuite/Makefile.in: Likewise.
+ * configure.ac: Add PA_HPUX rules.
+ * configure: Regenerate.
+ * src/pa/ffitarget.h: Rename linux target to PA_LINUX.
+ Add PA_HPUX and PA64_HPUX.
+ Rename FFI_LINUX ABI to FFI_PA32 ABI.
+ (FFI_TRAMPOLINE_SIZE): Define for 32-bit HP-UX targets.
+ (FFI_TYPE_SMALL_STRUCT2): Define.
+ (FFI_TYPE_SMALL_STRUCT4): Likewise.
+ (FFI_TYPE_SMALL_STRUCT8): Likewise.
+ (FFI_TYPE_SMALL_STRUCT3): Redefine.
+ (FFI_TYPE_SMALL_STRUCT5): Likewise.
+ (FFI_TYPE_SMALL_STRUCT6): Likewise.
+ (FFI_TYPE_SMALL_STRUCT7): Likewise.
+ * src/pa/ffi.c (ROUND_DOWN): Delete.
+ (fldw, fstw, fldd, fstd): Use '__asm__'.
+ (ffi_struct_type): Add support for FFI_TYPE_SMALL_STRUCT2,
+ FFI_TYPE_SMALL_STRUCT4 and FFI_TYPE_SMALL_STRUCT8.
+ (ffi_prep_args_LINUX): Rename to ffi_prep_args_pa32. Update comment.
+ Simplify incrementing of stack slot variable. Change type of local
+ 'n' to unsigned int.
+ (ffi_size_stack_LINUX): Rename to ffi_size_stack_pa32. Handle long
+ double on PA_HPUX.
+ (ffi_prep_cif_machdep): Likewise.
+ (ffi_call): Likewise.
+ (ffi_closure_inner_LINUX): Rename to ffi_closure_inner_pa32. Change
+ return type to ffi_status. Simplify incrementing of stack slot
+ variable. Only copy floating point argument registers when PA_LINUX
+ is true. Reformat debug statement.
+ Add support for FFI_TYPE_SMALL_STRUCT2, FFI_TYPE_SMALL_STRUCT4 and
+ FFI_TYPE_SMALL_STRUCT8.
+ (ffi_closure_LINUX): Rename to ffi_closure_pa32. Add 'extern' to
+ declaration.
+ (ffi_prep_closure): Make linux trampoline conditional on PA_LINUX.
+ Add nops to cache flush. Add trampoline for PA_HPUX.
+ * src/pa/hpux32.S: New file.
+ * src/pa/linux.S (ffi_call_LINUX): Rename to ffi_call_pa32. Rename
+ ffi_prep_args_LINUX to ffi_prep_args_pa32.
+ Localize labels. Add support for 2, 4 and 8-byte small structs. Handle
+ unaligned destinations in 3, 5, 6 and 7-byte small structs. Order
+ argument type checks so that common argument types appear first.
+ (ffi_closure_LINUX): Rename to ffi_closure_pa32. Rename
+ ffi_closure_inner_LINUX to ffi_closure_inner_pa32.
+
+2006-03-24 Alan Modra <amodra@bigpond.net.au>
+
+ * src/powerpc/ffitarget.h (enum ffi_abi): Add FFI_LINUX. Default
+ for 32-bit using IBM extended double format. Fix FFI_LAST_ABI.
+ * src/powerpc/ffi.c (ffi_prep_args_SYSV): Handle linux variant of
+ FFI_TYPE_LONGDOUBLE.
+ (ffi_prep_args64): Assert using IBM extended double.
+ (ffi_prep_cif_machdep): Don't munge FFI_TYPE_LONGDOUBLE type.
+ Handle FFI_LINUX FFI_TYPE_LONGDOUBLE return and args.
+ (ffi_call): Handle FFI_LINUX.
+ (ffi_closure_helper_SYSV): Non FFI_LINUX long double return needs
+ gpr3 return pointer as for struct return. Handle FFI_LINUX
+ FFI_TYPE_LONGDOUBLE return and args. Don't increment "nf"
+ unnecessarily.
+ * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Load both f1 and f2
+ for FFI_TYPE_LONGDOUBLE. Move epilogue insns into case table.
+ Don't use r6 as pointer to results, instead use sp offset. Don't
+ make a special call to load lr with case table address, instead
+ use offset from previous call.
+ * src/powerpc/sysv.S (ffi_call_SYSV): Save long double return.
+ * src/powerpc/linux64.S (ffi_call_LINUX64): Simplify long double
+ return.
+
+2006-03-15 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh64/ffi.c (ffi_prep_cif_machdep): Handle float arguments
+ passed with FP registers correctly.
+ (ffi_closure_helper_SYSV): Likewise.
+ * src/sh64/sysv.S: Likewise.
+
+2006-03-01 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.special/unwindtest.cc (closure_test_fn): Mark cif,
+ args and userdata unused.
+ (closure_test_fn1): Mark cif and userdata unused.
+ (main): Remove unused res.
+
+2006-02-28 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/call.exp: Adjust FSF address. Add test runs for
+ -O2, -O3, -Os and the warning flags -W -Wall.
+ * testsuite/libffi.special/special.exp: Likewise.
+ * testsuite/libffi.call/ffitest.h: Add an __UNUSED__ macro to mark
+ unused parameter unused for gcc or else do nothing.
+ * testsuite/libffi.special/ffitestcxx.h: Likewise.
+ * testsuite/libffi.call/cls_12byte.c (cls_struct_12byte_gn): Mark cif
+ and userdata unused.
+ * testsuite/libffi.call/cls_16byte.c (cls_struct_16byte_gn): Likewise.
+ * testsuite/libffi.call/cls_18byte.c (cls_struct_18byte_gn): Likewise.
+ * testsuite/libffi.call/cls_19byte.c (cls_struct_19byte_gn): Likewise.
+ * testsuite/libffi.call/cls_1_1byte.c (cls_struct_1_1byte_gn): Likewise.
+ * testsuite/libffi.call/cls_20byte.c (cls_struct_20byte_gn): Likewise.
+ * testsuite/libffi.call/cls_20byte1.c (cls_struct_20byte_gn): Likewise.
+ * testsuite/libffi.call/cls_24byte.c (cls_struct_24byte_gn): Likewise.
+ * testsuite/libffi.call/cls_2byte.c (cls_struct_2byte_gn): Likewise.
+ * testsuite/libffi.call/cls_3_1byte.c (cls_struct_3_1byte_gn): Likewise.
+ * testsuite/libffi.call/cls_3byte1.c (cls_struct_3byte_gn): Likewise.
+ * testsuite/libffi.call/cls_3byte2.c (cls_struct_3byte_gn1): Likewise.
+ * testsuite/libffi.call/cls_4_1byte.c (cls_struct_4_1byte_gn): Likewise.
+ * testsuite/libffi.call/cls_4byte.c (cls_struct_4byte_gn): Likewise.
+ * testsuite/libffi.call/cls_5_1_byte.c (cls_struct_5byte_gn): Likewise.
+ * testsuite/libffi.call/cls_5byte.c (cls_struct_5byte_gn): Likewise.
+ * testsuite/libffi.call/cls_64byte.c (cls_struct_64byte_gn): Likewise.
+ * testsuite/libffi.call/cls_6_1_byte.c (cls_struct_6byte_gn): Likewise.
+ * testsuite/libffi.call/cls_6byte.c (cls_struct_6byte_gn): Likewise.
+ * testsuite/libffi.call/cls_7_1_byte.c (cls_struct_7byte_gn): Likewise.
+ * testsuite/libffi.call/cls_7byte.c (cls_struct_7byte_gn): Likewise.
+ * testsuite/libffi.call/cls_8byte.c (cls_struct_8byte_gn): Likewise.
+ * testsuite/libffi.call/cls_9byte1.c (cls_struct_9byte_gn): Likewise.
+ * testsuite/libffi.call/cls_9byte2.c (cls_struct_9byte_gn): Likewise.
+ * testsuite/libffi.call/cls_align_double.c (cls_struct_align_gn):
+ Likewise.
+ * testsuite/libffi.call/cls_align_float.c (cls_struct_align_gn):
+ Likewise.
+ * testsuite/libffi.call/cls_align_longdouble.c (cls_struct_align_gn):
+ Likewise.
+ * testsuite/libffi.call/cls_align_pointer.c (cls_struct_align_fn): Cast
+ void* to avoid compiler warning.
+ (main): Likewise.
+ (cls_struct_align_gn): Mark cif and userdata unused.
+ * testsuite/libffi.call/cls_align_sint16.c (cls_struct_align_gn):
+ Likewise.
+ * testsuite/libffi.call/cls_align_sint32.c (cls_struct_align_gn):
+ Likewise.
+ * testsuite/libffi.call/cls_align_sint64.c (cls_struct_align_gn):
+ Likewise.
+ * testsuite/libffi.call/cls_align_uint16.c (cls_struct_align_gn):
+ Likewise.
+ * testsuite/libffi.call/cls_align_uint32.c (cls_struct_align_gn):
+ Likewise.
+ * testsuite/libffi.call/cls_double.c (cls_ret_double_fn): Likewise.
+ * testsuite/libffi.call/cls_float.c (cls_ret_float_fn): Likewise.
+ * testsuite/libffi.call/cls_multi_schar.c (test_func_gn): Mark cif and
+ data unused.
+ (main): Cast res_call to silence gcc.
+ * testsuite/libffi.call/cls_multi_sshort.c (test_func_gn): Mark cif and
+ data unused.
+ (main): Cast res_call to silence gcc.
+ * testsuite/libffi.call/cls_multi_sshortchar.c (test_func_gn): Mark cif
+ and data unused.
+ (main): Cast res_call to silence gcc.
+ * testsuite/libffi.call/cls_multi_uchar.c (test_func_gn): Mark cif and
+ data unused.
+ (main): Cast res_call to silence gcc.
+ * testsuite/libffi.call/cls_multi_ushort.c (test_func_gn): Mark cif and
+ data unused.
+ (main): Cast res_call to silence gcc.
+ * testsuite/libffi.call/cls_multi_ushortchar.c (test_func_gn): Mark cif
+ and data unused.
+ (main): Cast res_call to silence gcc.
+ * testsuite/libffi.call/cls_schar.c (cls_ret_schar_fn): Mark cif and
+ userdata unused.
+ (cls_ret_schar_fn): Cast printf parameter to silence gcc.
+ * testsuite/libffi.call/cls_sint.c (cls_ret_sint_fn): Mark cif and
+ userdata unused.
+ (cls_ret_sint_fn): Cast printf parameter to silence gcc.
+ * testsuite/libffi.call/cls_sshort.c (cls_ret_sshort_fn): Mark cif and
+ userdata unused.
+ (cls_ret_sshort_fn): Cast printf parameter to silence gcc.
+ * testsuite/libffi.call/cls_uchar.c (cls_ret_uchar_fn): Mark cif and
+ userdata unused.
+ (cls_ret_uchar_fn): Cast printf parameter to silence gcc.
+ * testsuite/libffi.call/cls_uint.c (cls_ret_uint_fn): Mark cif and
+ userdata unused.
+ (cls_ret_uint_fn): Cast printf parameter to silence gcc.
+ * testsuite/libffi.call/cls_ulonglong.c (cls_ret_ulonglong_fn): Mark cif
+ and userdata unused.
+ * testsuite/libffi.call/cls_ushort.c (cls_ret_ushort_fn): Mark cif and
+ userdata unused.
+ (cls_ret_ushort_fn): Cast printf parameter to silence gcc.
+ * testsuite/libffi.call/float.c (floating): Remove unused parameter e.
+ * testsuite/libffi.call/float1.c (main): Remove unused variable i.
+ Cleanup white spaces.
+ * testsuite/libffi.call/negint.c (checking): Remove unused variable i.
+ * testsuite/libffi.call/nested_struct.c (cls_struct_combined_gn): Mark
+ cif and userdata unused.
+ * testsuite/libffi.call/nested_struct1.c (cls_struct_combined_gn):
+ Likewise.
+ * testsuite/libffi.call/nested_struct10.c (B_gn): Likewise.
+ * testsuite/libffi.call/nested_struct2.c (B_fn): Adjust printf
+ formatters to silence gcc.
+ (B_gn): Mark cif and userdata unused.
+ * testsuite/libffi.call/nested_struct3.c (B_gn): Mark cif and userdata
+ unused.
+ * testsuite/libffi.call/nested_struct4.c: Mention related PR.
+ (B_gn): Mark cif and userdata unused.
+ * testsuite/libffi.call/nested_struct5.c (B_gn): Mark cif and userdata
+ unused.
+ * testsuite/libffi.call/nested_struct6.c: Mention related PR.
+ (B_gn): Mark cif and userdata unused.
+ * testsuite/libffi.call/nested_struct7.c (B_gn): Mark cif and userdata
+ unused.
+ * testsuite/libffi.call/nested_struct8.c (B_gn): Likewise.
+ * testsuite/libffi.call/nested_struct9.c (B_gn): Likewise.
+ * testsuite/libffi.call/problem1.c (stub): Likewise.
+ * testsuite/libffi.call/pyobjc-tc.c (main): Cast the result to silence
+ gcc.
+ * testsuite/libffi.call/return_fl2.c (return_fl): Add the note mentioned
+ in the last commit for this test case in the test case itself.
+ * testsuite/libffi.call/closure_fn0.c (closure_test_fn0): Mark cif as
+ unused.
+ * testsuite/libffi.call/closure_fn1.c (closure_test_fn1): Likewise.
+ * testsuite/libffi.call/closure_fn2.c (closure_test_fn2): Likewise.
+ * testsuite/libffi.call/closure_fn3.c (closure_test_fn3): Likewise.
+ * testsuite/libffi.call/closure_fn4.c (closure_test_fn0): Likewise.
+ * testsuite/libffi.call/closure_fn5.c (closure_test_fn5): Likewise.
+ * testsuite/libffi.call/closure_fn6.c (closure_test_fn0): Likewise.
+
+2006-02-22 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/sysv.S: Fix register numbers in the FDE for
+ ffi_closure_SYSV.
+
+2006-02-20 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/return_fl2.c (return_fl): Remove static
+ declaration to avoid a false negative on ix86. See PR323.
+
+2006-02-18 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/ffi.c (ffi_closure_helper_SYSV): Remove unused variable
+ and cast integer to void * if needed. Update the pointer to
+ the FP register saved area correctly.
+
+2006-02-17 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/nested_struct6.c: XFAIL this test until PR25630
+ is fixed.
+ * testsuite/libffi.call/nested_struct4.c: Likewise.
+
+2006-02-16 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/return_dbl.c: New test case.
+ * testsuite/libffi.call/return_dbl1.c: Likewise.
+ * testsuite/libffi.call/return_dbl2.c: Likewise.
+ * testsuite/libffi.call/return_fl.c: Likewise.
+ * testsuite/libffi.call/return_fl1.c: Likewise.
+ * testsuite/libffi.call/return_fl2.c: Likewise.
+ * testsuite/libffi.call/return_fl3.c: Likewise.
+ * testsuite/libffi.call/closure_fn6.c: Likewise.
+
+ * testsuite/libffi.call/nested_struct2.c: Remove ffi_type_mylong
+ definition.
+ * testsuite/libffi.call/ffitest.h: Add ffi_type_mylong definition
+ here to be used by other test cases too.
+
+ * testsuite/libffi.call/nested_struct10.c: New test case.
+ * testsuite/libffi.call/nested_struct9.c: Likewise.
+ * testsuite/libffi.call/nested_struct8.c: Likewise.
+ * testsuite/libffi.call/nested_struct7.c: Likewise.
+ * testsuite/libffi.call/nested_struct6.c: Likewise.
+ * testsuite/libffi.call/nested_struct5.c: Likewise.
+ * testsuite/libffi.call/nested_struct4.c: Likewise.
+
+2006-01-21 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * configure.ac: Enable libffi for sparc64-*-freebsd*.
+ * configure: Rebuilt.
+
+2006-01-18 Jakub Jelinek <jakub@redhat.com>
+
+ * src/powerpc/sysv.S (smst_two_register): Don't call __ashldi3,
+ instead do the shifting inline.
+ * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Don't compute %r5
+ shift count unconditionally. Simplify load sequences for 1, 2, 3, 4
+ and 8 byte structs, for the remaining struct sizes don't call
+ __lshrdi3, instead do the shifting inline.
+
+2005-12-07 Thiemo Seufer <ths@networkno.de>
+
+ * src/mips/ffitarget.h: Remove obsolete sgidefs.h include. Add
+ missing parentheses.
+ * src/mips/o32.S (ffi_call_O32): Code formatting. Define
+ and use A3_OFF, FP_OFF, RA_OFF. Micro-optimizations.
+ (ffi_closure_O32): Likewise, but with newly defined A3_OFF2,
+ A2_OFF2, A1_OFF2, A0_OFF2, RA_OFF2, FP_OFF2, S0_OFF2, GP_OFF2,
+ V1_OFF2, V0_OFF2, FA_1_1_OFF2, FA_1_0_OFF2, FA_0_1_OFF2,
+ FA_0_0_OFF2.
+ * src/mips/ffi.c (ffi_prep_args): Code formatting. Fix
+ endianness bugs.
+ (ffi_prep_closure): Improve trampoline instruction scheduling.
+ (ffi_closure_mips_inner_O32): Fix endianness bugs.
+
+2005-12-03 Alan Modra <amodra@bigpond.net.au>
+
+ * src/powerpc/ffi.c: Formatting.
+ (ffi_prep_args_SYSV): Avoid possible aliasing problems by using unions.
+ (ffi_prep_args64): Likewise.
+
+2005-09-30 Geoffrey Keating <geoffk@apple.com>
+
+ * testsuite/lib/libffi-dg.exp (libffi_target_compile): For
+ darwin, use -shared-libgcc not -lgcc_s, and explain why.
+
+2005-09-26 Tom Tromey <tromey@redhat.com>
+
+ * testsuite/libffi.call/float1.c (value_type): New typedef.
+ (CANARY): New define.
+ (main): Check for result buffer overflow.
+ * src/powerpc/linux64.S: Handle linux64 long double returns.
+ * src/powerpc/ffi.c (FLAG_RETURNS_128BITS): New constant.
+ (ffi_prep_cif_machdep): Handle linux64 long double returns.
+
+2005-08-25 Alan Modra <amodra@bigpond.net.au>
+
+ PR target/23404
+ * src/powerpc/ffi.c (ffi_prep_args_SYSV): Correct placement of stack
+ homed fp args.
+ (ffi_status ffi_prep_cif_machdep): Correct stack sizing for same.
+
+2005-08-11 Jakub Jelinek <jakub@redhat.com>
+
+ * configure.ac (HAVE_HIDDEN_VISIBILITY_ATTRIBUTE): New test.
+ (AH_BOTTOM): Add FFI_HIDDEN definition.
+ * configure: Rebuilt.
+ * fficonfig.h.in: Rebuilt.
+ * src/powerpc/ffi.c (hidden): Remove.
+ (ffi_closure_LINUX64, ffi_prep_args64, ffi_call_LINUX64,
+ ffi_closure_helper_LINUX64): Use FFI_HIDDEN instead of hidden.
+ * src/powerpc/linux64_closure.S (ffi_closure_LINUX64,
+ .ffi_closure_LINUX64): Use FFI_HIDDEN instead of .hidden.
+ * src/x86/ffi.c (ffi_closure_SYSV, ffi_closure_raw_SYSV): Remove,
+ add FFI_HIDDEN to its prototype.
+ (ffi_closure_SYSV_inner): New.
+ * src/x86/sysv.S (ffi_closure_SYSV, ffi_closure_raw_SYSV): New.
+ * src/x86/win32.S (ffi_closure_SYSV, ffi_closure_raw_SYSV): New.
+
+2005-08-10 Alfred M. Szmidt <ams@gnu.org>
+
+ PR libffi/21819:
+ * configure: Rebuilt.
+ * configure.ac: Handle i*86-*-gnu*.
+
+2005-08-09 Jakub Jelinek <jakub@redhat.com>
+
+ * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Use
+ DW_CFA_offset_extended_sf rather than
+ DW_CFA_GNU_negative_offset_extended.
+ * src/powerpc/sysv.S (ffi_call_SYSV): Likewise.
+
+2005-07-22 SUGIOKA Toshinobu <sugioka@itonet.co.jp>
+
+ * src/sh/sysv.S (ffi_call_SYSV): Stop argument popping correctly
+ on sh3.
+ (ffi_closure_SYSV): Change the stack layout for sh3 struct argument.
+ * src/sh/ffi.c (ffi_prep_args): Fix sh3 argument copy, when it is
+ partially on register.
+ (ffi_closure_helper_SYSV): Likewise.
+ (ffi_prep_cif_machdep): Don't set too many cif->flags.
+
+2005-07-20 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/ffi.c (ffi_call): Handle small structures correctly.
+ Remove empty line.
+ * src/sh64/ffi.c (simple_type): Remove.
+ (return_type): Handle small structures correctly.
+ (ffi_prep_args): Likewise.
+ (ffi_call): Likewise.
+ (ffi_closure_helper_SYSV): Likewise.
+ * src/sh64/sysv.S (ffi_call_SYSV): Handle 1, 2 and 4-byte return.
+ Emit position independent code if PIC and remove wrong datalabel
+ prefixes from EH data.
+
+2005-07-19 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * Makefile.am (nodist_libffi_la_SOURCES): Add POWERPC_FREEBSD.
+ * Makefile.in: Regenerate.
+ * include/Makefile.in: Likewise.
+ * testsuite/Makefile.in: Likewise.
+ * configure.ac: Add POWERPC_FREEBSD rules.
+ * configure: Regenerate.
+ * src/powerpc/ffitarget.h: Add POWERPC_FREEBSD rules.
+ (FFI_SYSV_TYPE_SMALL_STRUCT): Define.
+ * src/powerpc/ffi.c: Add flags to handle small structure returns
+ in ffi_call_SYSV.
+ (ffi_prep_cif_machdep): Handle small structures for SYSV 4 ABI.
+ Aka FFI_SYSV.
+ (ffi_closure_helper_SYSV): Likewise.
+ * src/powerpc/ppc_closure.S: Add return types for small structures.
+ * src/powerpc/sysv.S: Add bits to handle small structures for
+ final SYSV 4 ABI.
+
+2005-07-10 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/cls_5_1_byte.c: New test file.
+ * testsuite/libffi.call/cls_6_1_byte.c: Likewise.
+ * testsuite/libffi.call/cls_7_1_byte.c: Likewise.
+
+2005-07-05 Randolph Chung <tausq@debian.org>
+
+ * src/pa/ffi.c (ffi_struct_type): Rename FFI_TYPE_SMALL_STRUCT1
+ as FFI_TYPE_SMALL_STRUCT3. Break out handling for 5-7 byte
+ structures. Kill compilation warnings.
+ (ffi_closure_inner_LINUX): Print return values as hex in debug
+ message. Rename FFI_TYPE_SMALL_STRUCT1 as FFI_TYPE_SMALL_STRUCT3.
+ Properly handle 5-7 byte structure returns.
+ * src/pa/ffitarget.h (FFI_TYPE_SMALL_STRUCT1)
+ (FFI_TYPE_SMALL_STRUCT2): Remove.
+ (FFI_TYPE_SMALL_STRUCT3, FFI_TYPE_SMALL_STRUCT5)
+ (FFI_TYPE_SMALL_STRUCT6, FFI_TYPE_SMALL_STRUCT7): Define.
+ * src/pa/linux.S: Mark source file as using PA1.1 assembly.
+ (checksmst1, checksmst2): Remove.
+ (checksmst3): Optimize handling of 3-byte struct returns.
+ (checksmst567): Properly handle 5-7 byte struct returns.
+
+2005-06-15 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ PR libgcj/21943
+ * src/mips/n32.S: Enforce PIC code.
+ * src/mips/o32.S: Likewise.
+
+2005-06-15 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * configure.ac: Treat i*86-*-solaris2.10 and up as X86_64.
+ * configure: Regenerate.
+
+2005-06-01 Alan Modra <amodra@bigpond.net.au>
+
+ * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Don't use JUMPTARGET
+ to call ffi_closure_helper_SYSV. Append @local instead.
+ * src/powerpc/sysv.S (ffi_call_SYSV): Likewise for ffi_prep_args_SYSV.
+
+2005-05-17 Kelley Cook <kcook@gcc.gnu.org>
+
+ * configure.ac: Use AC_C_BIGENDIAN instead of AC_C_BIGENDIAN_CROSS.
+ Use AC_CHECK_SIZEOF instead of AC_COMPILE_CHECK_SIZEOF.
+ * Makefile.am (ACLOCAL_AMFLAGS): Remove -I ../config.
+ * aclocal.m4, configure, fficonfig.h.in, Makefile.in,
+ include/Makefile.in, testsuite/Makefile.in: Regenerate.
+
+2005-05-09 Mike Stump <mrs@apple.com>
+
+ * configure: Regenerate.
+
+2005-05-08 Richard Henderson <rth@redhat.com>
+
+ PR libffi/21285
+ * src/alpha/osf.S: Update unwind into to match code.
+
+2005-05-04 Andreas Degert <ad@papyrus-gmbh.de>
+ Richard Henderson <rth@redhat.com>
+
+ * src/x86/ffi64.c (ffi_prep_cif_machdep): Save sse-used flag in
+ bit 11 of flags.
+ (ffi_call): Mask return type field. Pass ssecount to ffi_call_unix64.
+ (ffi_prep_closure): Set carry bit if sse-used flag set.
+ * src/x86/unix64.S (ffi_call_unix64): Add ssecount argument.
+ Only load sse registers if ssecount non-zero.
+ (ffi_closure_unix64): Only save sse registers if carry set on entry.
+
+2005-04-29 Ralf Corsepius <ralf.corsepius@rtems.org>
+
+ * configure.ac: Add i*86-*-rtems*, sparc*-*-rtems*,
+ powerpc-*rtems*, arm*-*-rtems*, sh-*-rtems*.
+ * configure: Regenerate.
+
+2005-04-20 Hans-Peter Nilsson <hp@axis.com>
+
+ * testsuite/lib/libffi-dg.exp (libffi-dg-test-1): In regsub use,
+ have Tcl8.3-compatible intermediate variable.
+
+2005-04-18 Simon Posnjak <simon.posnjak@siol.net>
+ Hans-Peter Nilsson <hp@axis.com>
+
+ * Makefile.am: Add CRIS support.
+ * configure.ac: Likewise.
+ * Makefile.in, configure, testsuite/Makefile.in,
+ include/Makefile.in: Regenerate.
+ * src/cris: New directory.
+ * src/cris/ffi.c, src/cris/sysv.S, src/cris/ffitarget.h: New files.
+ * src/prep_cif.c (ffi_prep_cif): Wrap in #ifndef __CRIS__.
+
+ * testsuite/lib/libffi-dg.exp (libffi-dg-test-1): Replace \n with
+ \r?\n in output tests.
+
+2005-04-12 Mike Stump <mrs@apple.com>
+
+ * configure: Regenerate.
+
+2005-03-30 Hans Boehm <Hans.Boehm@hp.com>
+
+ * src/ia64/ffitarget.h (ffi_arg): Use long long instead of DI.
+
+2005-03-30 Steve Ellcey <sje@cup.hp.com>
+
+ * src/ia64/ffitarget.h (ffi_arg) ADD DI attribute.
+ (ffi_sarg) Ditto.
+ * src/ia64/unix.S (ffi_closure_unix): Extend gp
+ to 64 bits in ILP32 mode.
+ Load 64 bits even for short data.
+
+2005-03-23 Mike Stump <mrs@apple.com>
+
+ * src/powerpc/darwin.S: Update for -m64 multilib.
+ * src/powerpc/darwin_closure.S: Likewise.
+
+2005-03-21 Zack Weinberg <zack@codesourcery.com>
+
+ * configure.ac: Do not invoke TL_AC_GCC_VERSION.
+ Do not set tool_include_dir.
+ * aclocal.m4, configure, Makefile.in, testsuite/Makefile.in:
+ Regenerate.
+ * include/Makefile.am: Set gcc_version and toollibffidir.
+ * include/Makefile.in: Regenerate.
+
+2005-02-22 Andrew Haley <aph@redhat.com>
+
+ * src/powerpc/ffi.c (ffi_prep_cif_machdep): Bump alignment to
+ odd-numbered register pairs for 64-bit integer types.
+
+2005-02-23 Andreas Tobler <a.tobler@schweiz.ch>
+
+ PR libffi/20104
+ * testsuite/libffi.call/return_ll1.c: New test case.
+
+2005-02-11 Janis Johnson <janis187@us.ibm.com>
+
+ * testsuite/libffi.call/cls_align_longdouble.c: Remove dg-options.
+ * testsuite/libffi.call/float.c: Ditto.
+ * testsuite/libffi.call/float2.c: Ditto.
+ * testsuite/libffi.call/float3.c: Ditto.
+
+2005-02-08 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/frv/ffitarget.h: Remove PPC stuff which does not belong to frv.
+
+2005-01-12 Eric Botcazou <ebotcazou@libertysurf.fr>
+
+ * testsuite/libffi.special/special.exp (cxx_options): Add
+ -shared-libgcc.
+
+2004-12-31 Richard Henderson <rth@redhat.com>
+
+ * src/types.c (FFI_AGGREGATE_TYPEDEF): Remove.
+ (FFI_TYPEDEF): Rename from FFI_INTEGRAL_TYPEDEF. Replace size and
+ offset parameters with a type parameter; deduce size and structure
+ alignment. Update all users.
+
+2004-12-31 Richard Henderson <rth@redhat.com>
+
+ * src/types.c (FFI_TYPE_POINTER): Define with sizeof.
+ (FFI_TYPE_LONGDOUBLE): Fix for ia64.
+ * src/ia64/ffitarget.h (struct ffi_ia64_trampoline_struct): Move
+ into ffi_prep_closure.
+ * src/ia64/ia64_flags.h, src/ia64/ffi.c, src/ia64/unix.S: Rewrite
+ from scratch.
+
+2004-12-27 Richard Henderson <rth@redhat.com>
+
+ * src/x86/unix64.S: Fix typo in unwind info.
+
+2004-12-25 Richard Henderson <rth@redhat.com>
+
+ * src/x86/ffi64.c (struct register_args): Rename from stackLayout.
+ (enum x86_64_reg_class): Add X86_64_COMPLEX_X87_CLASS.
+ (merge_classes): Check for it.
+ (SSE_CLASS_P): New.
+ (classify_argument): Pass byte_offset by value; perform all updates
+ inside struct case.
+ (examine_argument): Add classes argument; handle
+ X86_64_COMPLEX_X87_CLASS.
+ (ffi_prep_args): Merge into ...
+ (ffi_call): ... here. Share stack frame with ffi_call_unix64.
+ (ffi_prep_cif_machdep): Setup cif->flags for proper structure return.
+ (ffi_fill_return_value): Remove.
+ (ffi_prep_closure): Remove dead assert.
+ (ffi_closure_unix64_inner): Rename from ffi_closure_UNIX64_inner.
+ Rewrite to use struct register_args instead of va_list. Create
+ flags for handling structure returns.
+ * src/x86/unix64.S: Remove dead strings.
+ (ffi_call_unix64): Rename from ffi_call_UNIX64. Rewrite to share
+ stack frame with ffi_call. Handle structure returns properly.
+ (float2sse, floatfloat2sse, double2sse): Remove.
+ (sse2float, sse2double, sse2floatfloat): Remove.
+ (ffi_closure_unix64): Rename from ffi_closure_UNIX64. Rewrite
+ to handle structure returns properly.
+
+2004-12-08 David Edelsohn <edelsohn@gnu.org>
+
+ * Makefile.am (AM_MAKEFLAGS): Remove duplicate LIBCFLAGS and
+ PICFLAG.
+ * Makefile.in: Regenerated.
+
+2004-12-02 Richard Sandiford <rsandifo@redhat.com>
+
+ * configure.ac: Use TL_AC_GCC_VERSION to set gcc_version.
+ * configure, aclocal.m4, Makefile.in: Regenerate.
+ * include/Makefile.in, testsuite/Makefile.in: Regenerate.
+
+2004-11-29 Kelley Cook <kcook@gcc.gnu.org>
+
+ * configure: Regenerate for libtool change.
+
+2004-11-25 Kelley Cook <kcook@gcc.gnu.org>
+
+ * configure: Regenerate for libtool reversion.
+
+2004-11-24 Kelley Cook <kcook@gcc.gnu.org>
+
+ * configure: Regenerate for libtool change.
+
+2004-11-23 John David Anglin <dave.anglin@nrc-cnrc.gc.ca>
+
+ * testsuite/lib/libffi-dg.exp: Use new procs in target-libpath.exp.
+
+2004-11-23 Richard Sandiford <rsandifo@redhat.com>
+
+ * src/mips/o32.S (ffi_call_O32, ffi_closure_O32): Use jalr instead
+ of jal. Use an absolute encoding for the frame information.
+
+2004-11-23 Kelley Cook <kcook@gcc.gnu.org>
+
+ * Makefile.am: Remove no-dependencies. Add ACLOCAL_AMFLAGS.
+ * acinclude.m4: Delete logic for sincludes.
+ * aclocal.m4, Makefile.in, configure: Regenerate.
+ * include/Makefile: Likewise.
+ * testsuite/Makefile: Likewise.
+
+2004-11-22 Eric Botcazou <ebotcazou@libertysurf.fr>
+
+ * src/sparc/ffi.c (ffi_prep_closure): Align doubles and 64-bit integers
+ on a 8-byte boundary.
+ * src/sparc/v8.S (ffi_closure_v8): Reserve frame space for arguments.
+
+2004-10-27 Richard Earnshaw <rearnsha@arm.com>
+
+ * src/arm/ffi.c (ffi_prep_cif_machdep): Handle functions that return
+ long long values. Round stack allocation to a multiple of 8 bytes
+ for ATPCS compatibility.
+ * src/arm/sysv.S (ffi_call_SYSV): Rework to avoid use of APCS register
+ names. Handle returning long long types. Add Thumb and interworking
+ support. Improve soft-float code.
+
+2004-10-27 Richard Earnshaw <rearnsha@arm.com>
+
+ * testsuite/lib/libffi-db.exp (load_gcc_lib): New function.
+ (libffi_exit): New function.
+ (libffi_init): Build the testglue wrapper if needed.
+
+2004-10-25 Eric Botcazou <ebotcazou@libertysurf.fr>
+
+ PR other/18138
+ * testsuite/lib/libffi-dg.exp: Accept more than one multilib libgcc.
+
+2004-10-25 Kazuhiro Inaoka <inaoka.kazuhiro@renesas.com>
+
+ * src/m32r/libffitarget.h (FFI_CLOSURES): Set to 0.
+
+2004-10-20 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/sysv.S (ffi_call_SYSV): Don't align for double data.
+ * testsuite/libffi.call/float3.c: New test case.
+
+2004-10-18 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/ffi.c (ffi_prep_closure): Set T bit in trampoline for
+ the function returning a structure pointed with R2.
+ * src/sh/sysv.S (ffi_closure_SYSV): Use R2 as the pointer to
+ the structure return value if T bit set. Emit position
+ independent code and EH data if PIC.
+
+2004-10-13 Kazuhiro Inaoka <inaoka.kazuhiro@renesas.com>
+
+ * Makefile.am: Add m32r support.
+ * configure.ac: Likewise.
+ * Makefile.in: Regenerate.
+ * confiugre: Regenerate.
+ * src/types.c: Add m32r port to FFI_INTERNAL_TYPEDEF
+ (uint64, sint64, double, longdouble)
+ * src/m32r: New directory.
+ * src/m32r/ffi.c: New file.
+ * src/m32r/sysv.S: Likewise.
+ * src/m32r/ffitarget.h: Likewise.
+
+2004-10-02 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * testsuite/libffi.call/negint.c: New test case.
+
+2004-09-14 H.J. Lu <hongjiu.lu@intel.com>
+
+ PR libgcj/17465
+ * testsuite/lib/libffi-dg.exp: Don't use global ld_library_path.
+ Set up LD_LIBRARY_PATH, SHLIB_PATH, LD_LIBRARYN32_PATH,
+ LD_LIBRARY64_PATH, LD_LIBRARY_PATH_32, LD_LIBRARY_PATH_64 and
+ DYLD_LIBRARY_PATH.
+
+2004-09-05 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/many_win32.c: Remove whitespaces.
+ * testsuite/libffi.call/promotion.c: Likewise.
+ * testsuite/libffi.call/return_ll.c: Remove unused var. Cleanup
+ whitespaces.
+ * testsuite/libffi.call/return_sc.c: Likewise.
+ * testsuite/libffi.call/return_uc.c: Likewise.
+
+2004-09-05 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/powerpc/darwin.S: Fix comments and identation.
+ * src/powerpc/darwin_closure.S: Likewise.
+
+2004-09-02 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/powerpc/ffi_darwin.c: Add flag for longdouble return values.
+ (ffi_prep_args): Handle longdouble arguments.
+ (ffi_prep_cif_machdep): Set flags for longdouble. Calculate space for
+ longdouble.
+ (ffi_closure_helper_DARWIN): Add closure handling for longdouble.
+ * src/powerpc/darwin.S (_ffi_call_DARWIN): Add handling of longdouble
+ values.
+ * src/powerpc/darwin_closure.S (_ffi_closure_ASM): Likewise.
+ * src/types.c: Defined longdouble size and alignment for darwin.
+
+2004-09-02 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/powerpc/aix.S: Remove whitespaces.
+ * src/powerpc/aix_closure.S: Likewise.
+ * src/powerpc/asm.h: Likewise.
+ * src/powerpc/ffi.c: Likewise.
+ * src/powerpc/ffitarget.h: Likewise.
+ * src/powerpc/linux64.S: Likewise.
+ * src/powerpc/linux64_closure.S: Likewise.
+ * src/powerpc/ppc_closure.S: Likewise.
+ * src/powerpc/sysv.S: Likewise.
+
+2004-08-30 Anthony Green <green@redhat.com>
+
+ * Makefile.am: Add frv support.
+ * Makefile.in, testsuite/Makefile.in: Rebuilt.
+ * configure.ac: Read configure.host.
+ * configure.in: Read configure.host.
+ * configure.host: New file. frv-elf needs libgloss.
+ * include/ffi.h.in: Force ffi_closure to have a nice big (8)
+ alignment. This is needed to frv and shouldn't harm the others.
+ * include/ffi_common.h (ALIGN_DOWN): New macro.
+ * src/frv/ffi.c, src/frv/ffitarget.h, src/frv/eabi.S: New files.
+
+2004-08-24 David Daney <daney@avtrex.com>
+
+ * testsuite/libffi.call/closure_fn0.c: Xfail mips64* instead of mips*.
+ * testsuite/libffi.call/closure_fn1.c: Likewise.
+ * testsuite/libffi.call/closure_fn2.c Likewise.
+ * testsuite/libffi.call/closure_fn3.c: Likewise.
+ * testsuite/libffi.call/closure_fn4.c: Likewise.
+ * testsuite/libffi.call/closure_fn5.c: Likewise.
+ * testsuite/libffi.call/cls_18byte.c: Likewise.
+ * testsuite/libffi.call/cls_19byte.c: Likewise.
+ * testsuite/libffi.call/cls_1_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_20byte.c: Likewise.
+ * testsuite/libffi.call/cls_20byte1.c: Likewise.
+ * testsuite/libffi.call/cls_24byte.c: Likewise.
+ * testsuite/libffi.call/cls_2byte.c: Likewise.
+ * testsuite/libffi.call/cls_3_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_3byte1.c: Likewise.
+ * testsuite/libffi.call/cls_3byte2.c: Likewise.
+ * testsuite/libffi.call/cls_4_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_4byte.c: Likewise.
+ * testsuite/libffi.call/cls_64byte.c: Likewise.
+ * testsuite/libffi.call/cls_6byte.c: Likewise.
+ * testsuite/libffi.call/cls_7byte.c: Likewise.
+ * testsuite/libffi.call/cls_8byte.c: Likewise.
+ * testsuite/libffi.call/cls_9byte1.c: Likewise.
+ * testsuite/libffi.call/cls_9byte2.c: Likewise.
+ * testsuite/libffi.call/cls_align_double.c: Likewise.
+ * testsuite/libffi.call/cls_align_float.c: Likewise.
+ * testsuite/libffi.call/cls_align_longdouble.c: Likewise.
+ * testsuite/libffi.call/cls_align_pointer.c: Likewise.
+ * testsuite/libffi.call/cls_align_sint16.c: Likewise.
+ * testsuite/libffi.call/cls_align_sint32.c: Likewise.
+ * testsuite/libffi.call/cls_align_sint64.c: Likewise.
+ * testsuite/libffi.call/cls_align_uint16.c: Likewise.
+ * testsuite/libffi.call/cls_align_uint32.c: Likewise.
+ * testsuite/libffi.call/cls_align_uint64.c: Likewise.
+ * testsuite/libffi.call/cls_double.c: Likewise.
+ * testsuite/libffi.call/cls_float.c: Likewise.
+ * testsuite/libffi.call/cls_multi_schar.c: Likewise.
+ * testsuite/libffi.call/cls_multi_sshort.c: Likewise.
+ * testsuite/libffi.call/cls_multi_sshortchar.c: Likewise.
+ * testsuite/libffi.call/cls_multi_uchar.c: Likewise.
+ * testsuite/libffi.call/cls_multi_ushort.c: Likewise.
+ * testsuite/libffi.call/cls_multi_ushortchar.c: Likewise.
+ * testsuite/libffi.call/cls_schar.c: Likewise.
+ * testsuite/libffi.call/cls_sint.c: Likewise.
+ * testsuite/libffi.call/cls_sshort.c: Likewise.
+ * testsuite/libffi.call/cls_uchar.c: Likewise.
+ * testsuite/libffi.call/cls_uint.c: Likewise.
+ * testsuite/libffi.call/cls_ulonglong.c: Likewise.
+ * testsuite/libffi.call/cls_ushort.c: Likewise.
+ * testsuite/libffi.call/nested_struct.c: Likewise.
+ * testsuite/libffi.call/nested_struct1.c: Likewise.
+ * testsuite/libffi.call/nested_struct2.c: Likewise.
+ * testsuite/libffi.call/nested_struct3.c: Likewise.
+ * testsuite/libffi.call/problem1.c: Likewise.
+ * testsuite/libffi.special/unwindtest.cc: Likewise.
+ * testsuite/libffi.call/cls_12byte.c: Likewise and set return value
+ to zero.
+ * testsuite/libffi.call/cls_16byte.c: Likewise.
+ * testsuite/libffi.call/cls_5byte.c: Likewise.
+
+2004-08-23 David Daney <daney@avtrex.com>
+
+ PR libgcj/13141
+ * src/mips/ffitarget.h (FFI_O32_SOFT_FLOAT): New ABI.
+ * src/mips/ffi.c (ffi_prep_args): Fix alignment calculation.
+ (ffi_prep_cif_machdep): Handle FFI_O32_SOFT_FLOAT floating point
+ parameters and return types.
+ (ffi_call): Handle FFI_O32_SOFT_FLOAT ABI.
+ (ffi_prep_closure): Ditto.
+ (ffi_closure_mips_inner_O32): Handle FFI_O32_SOFT_FLOAT ABI, fix
+ alignment calculations.
+ * src/mips/o32.S (ffi_closure_O32): Don't use floating point
+ instructions if FFI_O32_SOFT_FLOAT, make stack frame ABI compliant.
+
+2004-08-14 Casey Marshall <csm@gnu.org>
+
+ * src/mips/ffi.c (ffi_pref_cif_machdep): set `cif->flags' to
+ contain `FFI_TYPE_UINT64' as return type for any 64-bit
+ integer (O32 ABI only).
+ (ffi_prep_closure): new function.
+ (ffi_closure_mips_inner_O32): new function.
+ * src/mips/ffitarget.h: Define `FFI_CLOSURES' and
+ `FFI_TRAMPOLINE_SIZE' appropriately if the ABI is o32.
+ * src/mips/o32.S (ffi_call_O32): add labels for .eh_frame. Return
+ 64 bit integers correctly.
+ (ffi_closure_O32): new function.
+ Added DWARF-2 unwind info for both functions.
+
+2004-08-10 Andrew Haley <aph@redhat.com>
+
+ * src/x86/ffi64.c (ffi_prep_args ): 8-align all stack arguments.
+
+2004-08-01 Robert Millan <robertmh@gnu.org>
+
+ * configure.ac: Detect knetbsd-gnu and kfreebsd-gnu.
+ * configure: Regenerate.
+
+2004-07-30 Maciej W. Rozycki <macro@linux-mips.org>
+
+ * acinclude.m4 (AC_FUNC_MMAP_BLACKLIST): Check for <sys/mman.h>
+ and mmap() explicitly instead of relying on preset autoconf cache
+ variables.
+ * aclocal.m4: Regenerate.
+ * configure: Regenerate.
+
+2004-07-11 Ulrich Weigand <uweigand@de.ibm.com>
+
+ * src/s390/ffi.c (ffi_prep_args): Fix C aliasing violation.
+ (ffi_check_float_struct): Remove unused prototype.
+
+2004-06-30 Geoffrey Keating <geoffk@apple.com>
+
+ * src/powerpc/ffi_darwin.c (flush_icache): ';' is a comment
+ character on Darwin, use '\n\t' instead.
+
+2004-06-26 Matthias Klose <doko@debian.org>
+
+ * libtool-version: Fix typo in revision/age.
+
+2004-06-17 Matthias Klose <doko@debian.org>
+
+ * libtool-version: New.
+ * Makefile.am (libffi_la_LDFLAGS): Use -version-info for soname.
+ * Makefile.in: Regenerate.
+
+2004-06-15 Paolo Bonzini <bonzini@gnu.org>
+
+ * Makefile.am: Remove useless multilib rules.
+ * Makefile.in: Regenerate.
+ * aclocal.m4: Regenerate with automake 1.8.5.
+ * configure.ac: Remove useless multilib configury.
+ * configure: Regenerate.
+
+2004-06-15 Paolo Bonzini <bonzini@gnu.org>
+
+ * .cvsignore: New file.
+
+2004-06-10 Jakub Jelinek <jakub@redhat.com>
+
+ * src/ia64/unix.S (ffi_call_unix): Insert group barrier break
+ fp_done.
+ (ffi_closure_UNIX): Fix f14/f15 adjustment if FLOAT_SZ is ever
+ changed from 8.
+
+2004-06-06 Sean McNeil <sean@mcneil.com>
+
+ * configure.ac: Add x86_64-*-freebsd* support.
+ * configure: Regenerate.
+
+2004-04-26 Joe Buck <jbuck@welsh-buck.org>
+
+ Bug 15093
+ * configure.ac: Test for existence of mmap and sys/mman.h before
+ checking blacklist. Fix suggested by Jim Wilson.
+ * configure: Regenerate.
+
+2004-04-26 Matt Austern <austern@apple.com>
+
+ * src/powerpc/darwin.S: Go through a non-lazy pointer for initial
+ FDE location.
+ * src/powerpc/darwin_closure.S: Likewise.
+
+2004-04-24 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/cls_multi_schar.c (main): Fix initialization
+ error. Reported by Thomas Heller <theller@python.net>.
+ * testsuite/libffi.call/cls_multi_sshort.c (main): Likewise.
+ * testsuite/libffi.call/cls_multi_ushort.c (main): Likewise.
+
+2004-03-20 Matthias Klose <doko@debian.org>
+
+ * src/pa/linux.S: Fix typo.
+
+2004-03-19 Matthias Klose <doko@debian.org>
+
+ * Makefile.am: Update.
+ * Makefile.in: Regenerate.
+ * src/pa/ffi.h.in: Remove.
+ * src/pa/ffitarget.h: New file.
+
+2004-02-10 Randolph Chung <tausq@debian.org>
+
+ * Makefile.am: Add PA support.
+ * Makefile.in: Regenerate.
+ * include/Makefile.in: Regenerate.
+ * configure.ac: Add PA target.
+ * configure: Regenerate.
+ * src/pa/ffi.c: New file.
+ * src/pa/ffi.h.in: Add PA support.
+ * src/pa/linux.S: New file.
+ * prep_cif.c: Add PA support.
+
+2004-03-16 Hosaka Yuji <hos@tamanegi.org>
+
+ * src/types.c: Fix alignment size of X86_WIN32 case int64 and
+ double.
+ * src/x86/ffi.c (ffi_prep_args): Replace ecif->cif->rtype->type
+ with ecif->cif->flags.
+ (ffi_call, ffi_prep_incoming_args_SYSV): Replace cif->rtype->type
+ with cif->flags.
+ (ffi_prep_cif_machdep): Add X86_WIN32 struct case.
+ (ffi_closure_SYSV): Add 1 or 2-bytes struct case for X86_WIN32.
+ * src/x86/win32.S (retstruct1b, retstruct2b, sc_retstruct1b,
+ sc_retstruct2b): Add for 1 or 2-bytes struct case.
+
+2004-03-15 Kelley Cook <kcook@gcc.gnu.org>
+
+ * configure.in: Rename file to ...
+ * configure.ac: ... this.
+ * fficonfig.h.in: Regenerate.
+ * Makefile.in: Regenerate.
+ * include/Makefile.in: Regenerate.
+ * testsuite/Makefile.in: Regenerate.
+
+2004-03-12 Matt Austern <austern@apple.com>
+
+ * src/powerpc/darwin.S: Fix EH information so it corresponds to
+ changes in EH format resulting from addition of linkonce support.
+ * src/powerpc/darwin_closure.S: Likewise.
+
+2004-03-11 Andreas Tobler <a.tobler@schweiz.ch>
+ Paolo Bonzini <bonzini@gnu.org>
+
+ * Makefile.am (AUTOMAKE_OPTIONS): Set them.
+ Remove VPATH. Remove rules for object files. Remove multilib support.
+ (AM_CCASFLAGS): Add.
+ * configure.in (AC_CONFIG_HEADERS): Relace AM_CONFIG_HEADER.
+ (AC_PREREQ): Bump version to 2.59.
+ (AC_INIT): Fill with version info and bug address.
+ (ORIGINAL_LD_FOR_MULTILIBS): Remove.
+ (AM_ENABLE_MULTILIB): Use this instead of AC_ARG_ENABLE.
+ De-precious CC so that the right flags are passed down to multilibs.
+ (AC_MSG_ERROR): Replace obsolete macro AC_ERROR.
+ (AC_CONFIG_FILES): Replace obsolete macro AC_LINK_FILES.
+ (AC_OUTPUT): Reorganize the output with AC_CONFIG_COMMANDS.
+ * configure: Rebuilt.
+ * aclocal.m4: Likewise.
+ * Makefile.in, include/Makefile.in, testsuite/Makefile.in: Likewise.
+ * fficonfig.h.in: Likewise.
+
+2004-03-11 Andreas Schwab <schwab@suse.de>
+
+ * src/ia64/ffi.c (ffi_prep_incoming_args_UNIX): Get floating point
+ arguments from fp registers only for the first 8 parameter slots.
+ Don't convert a float parameter when passed in memory.
+
+2004-03-09 Hans-Peter Nilsson <hp@axis.com>
+
+ * configure: Regenerate for config/accross.m4 correction.
+
+2004-02-25 Matt Kraai <kraai@alumni.cmu.edu>
+
+ * src/powerpc/ffi.c (ffi_prep_args_SYSV): Change
+ ecif->cif->bytes to bytes.
+ (ffi_prep_cif_machdep): Add braces around nested if statement.
+
+2004-02-09 Alan Modra <amodra@bigpond.net.au>
+
+ * src/types.c (pointer): POWERPC64 has 8 byte pointers.
+
+ * src/powerpc/ffi.c (ffi_prep_args64): Correct long double handling.
+ (ffi_closure_helper_LINUX64): Fix typo.
+ * testsuite/libffi.call/cls_align_longdouble.c: Pass -mlong-double-128
+ for powerpc64-*-*.
+ * testsuite/libffi.call/float.c: Likewise.
+ * testsuite/libffi.call/float2.c: Likewise.
+
+2004-02-08 Alan Modra <amodra@bigpond.net.au>
+
+ * src/powerpc/ffi.c (ffi_prep_cif_machdep <FFI_LINUX64>): Correct
+ long double function return and long double arg handling.
+ (ffi_closure_helper_LINUX64): Formatting. Delete unused "ng" var.
+ Use "end_pfr" instead of "nf". Correct long double handling.
+ Localise "temp".
+ * src/powerpc/linux64.S (ffi_call_LINUX64): Save f2 long double
+ return value.
+ * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Allocate
+ space for long double return value. Adjust stack frame and offsets.
+ Load f2 long double return.
+
+2004-02-07 Alan Modra <amodra@bigpond.net.au>
+
+ * src/types.c: Use 16 byte long double for POWERPC64.
+
+2004-01-25 Eric Botcazou <ebotcazou@libertysurf.fr>
+
+ * src/sparc/ffi.c (ffi_prep_args_v9): Shift the parameter array
+ when the structure return address is passed in %o0.
+ (ffi_V9_return_struct): Rename into ffi_v9_layout_struct.
+ (ffi_v9_layout_struct): Align the field following a nested structure
+ on a word boundary. Use memmove instead of memcpy.
+ (ffi_call): Update call to ffi_V9_return_struct.
+ (ffi_prep_closure): Define 'ctx' only for V8.
+ (ffi_closure_sparc_inner): Clone into ffi_closure_sparc_inner_v8
+ and ffi_closure_sparc_inner_v9.
+ (ffi_closure_sparc_inner_v8): Return long doubles by reference.
+ Always skip the structure return address. For structures and long
+ doubles, copy the argument directly.
+ (ffi_closure_sparc_inner_v9): Skip the structure return address only
+ if required. Shift the maximum floating-point slot accordingly. For
+ big structures, copy the argument directly; otherwise, left-justify the
+ argument and call ffi_v9_layout_struct to lay out the structure on
+ the stack.
+ * src/sparc/v8.S: Undef STACKFRAME before defining it.
+ (ffi_closure_v8): Pass the structure return address. Update call to
+ ffi_closure_sparc_inner_v8. Short-circuit FFI_TYPE_INT handling.
+ Skip the 'unimp' insn when returning long doubles and structures.
+ * src/sparc/v9.S: Undef STACKFRAME before defining it.
+ (ffi_closure_v9): Increase the frame size by 2 words. Short-circuit
+ FFI_TYPE_INT handling. Load structures both in integers and
+ floating-point registers on return.
+ * README: Update status of the SPARC port.
+
+2004-01-24 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/pyobjc-tc.c (main): Treat result value
+ as of type ffi_arg.
+ * testsuite/libffi.call/struct3.c (main): Fix CHECK.
+
+2004-01-22 Ulrich Weigand <uweigand@de.ibm.com>
+
+ * testsuite/libffi.call/cls_uint.c (cls_ret_uint_fn): Treat result
+ value as of type ffi_arg, not unsigned int.
+
+2004-01-21 Michael Ritzert <ritzert@t-online.de>
+
+ * ffi64.c (ffi_prep_args): Cast the RHS of an assignment instead
+ of the LHS.
+
+2004-01-12 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/lib/libffi-dg.exp: Set LD_LIBRARY_PATH_32 for
+ Solaris.
+
+2004-01-08 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * testsuite/libffi.call/ffitest.h (allocate_mmap): Cast MAP_FAILED
+ to void *.
+
+2003-12-10 Richard Henderson <rth@redhat.com>
+
+ * testsuite/libffi.call/cls_align_pointer.c: Cast pointers to
+ size_t instead of int.
+
+2003-12-04 Hosaka Yuji <hos@tamanegi.org>
+
+ * testsuite/libffi.call/many_win32.c: Include <float.h>.
+ * testsuite/libffi.call/many_win32.c (main): Replace variable
+ int i with unsigned long ul.
+
+ * testsuite/libffi.call/cls_align_uint64.c: New test case.
+ * testsuite/libffi.call/cls_align_sint64.c: Likewise.
+ * testsuite/libffi.call/cls_align_uint32.c: Likewise.
+ * testsuite/libffi.call/cls_align_sint32.c: Likewise.
+ * testsuite/libffi.call/cls_align_uint16.c: Likewise.
+ * testsuite/libffi.call/cls_align_sint16.c: Likewise.
+ * testsuite/libffi.call/cls_align_float.c: Likewise.
+ * testsuite/libffi.call/cls_align_double.c: Likewise.
+ * testsuite/libffi.call/cls_align_longdouble.c: Likewise.
+ * testsuite/libffi.call/cls_align_pointer.c: Likewise.
+
+2003-12-02 Hosaka Yuji <hos@tamanegi.org>
+
+ PR other/13221
+ * src/x86/ffi.c (ffi_prep_args, ffi_prep_incoming_args_SYSV):
+ Align arguments to 32 bits.
+
+2003-12-01 Andreas Tobler <a.tobler@schweiz.ch>
+
+ PR other/13221
+ * testsuite/libffi.call/cls_multi_sshort.c: New test case.
+ * testsuite/libffi.call/cls_multi_sshortchar.c: Likewise.
+ * testsuite/libffi.call/cls_multi_uchar.c: Likewise.
+ * testsuite/libffi.call/cls_multi_schar.c: Likewise.
+ * testsuite/libffi.call/cls_multi_ushortchar.c: Likewise.
+ * testsuite/libffi.call/cls_multi_ushort.c: Likewise.
+
+ * testsuite/libffi.special/unwindtest.cc: Cosmetics.
+
+2003-11-26 Kaveh R. Ghazi <ghazi@caip.rutgers.edu>
+
+ * testsuite/libffi.call/ffitest.h: Include <fcntl.h>.
+ * testsuite/libffi.special/ffitestcxx.h: Likewise.
+
+2003-11-22 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * Makefile.in: Rebuilt.
+ * configure: Likewise.
+ * testsuite/libffi.special/unwindtest.cc: Convert the mmap to
+ the right type.
+
+2003-11-21 Andreas Jaeger <aj@suse.de>
+ Andreas Tobler <a.tobler@schweiz.ch>
+
+ * acinclude.m4: Add AC_FUNC_MMAP_BLACKLIST.
+ * configure.in: Call AC_FUNC_MMAP_BLACKLIST.
+ * Makefile.in: Rebuilt.
+ * aclocal.m4: Likewise.
+ * configure: Likewise.
+ * fficonfig.h.in: Likewise.
+ * testsuite/lib/libffi-dg.exp: Add include dir.
+ * testsuite/libffi.call/ffitest.h: Add MMAP definitions.
+ * testsuite/libffi.special/ffitestcxx.h: Likewise.
+ * testsuite/libffi.call/closure_fn0.c: Use MMAP functionality
+ for ffi_closure if available.
+ * testsuite/libffi.call/closure_fn1.c: Likewise.
+ * testsuite/libffi.call/closure_fn2.c: Likewise.
+ * testsuite/libffi.call/closure_fn3.c: Likewise.
+ * testsuite/libffi.call/closure_fn4.c: Likewise.
+ * testsuite/libffi.call/closure_fn5.c: Likewise.
+ * testsuite/libffi.call/cls_12byte.c: Likewise.
+ * testsuite/libffi.call/cls_16byte.c: Likewise.
+ * testsuite/libffi.call/cls_18byte.c: Likewise.
+ * testsuite/libffi.call/cls_19byte.c: Likewise.
+ * testsuite/libffi.call/cls_1_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_20byte.c: Likewise.
+ * testsuite/libffi.call/cls_20byte1.c: Likewise.
+ * testsuite/libffi.call/cls_24byte.c: Likewise.
+ * testsuite/libffi.call/cls_2byte.c: Likewise.
+ * testsuite/libffi.call/cls_3_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_3byte1.c: Likewise.
+ * testsuite/libffi.call/cls_3byte2.c: Likewise.
+ * testsuite/libffi.call/cls_4_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_4byte.c: Likewise.
+ * testsuite/libffi.call/cls_5byte.c: Likewise.
+ * testsuite/libffi.call/cls_64byte.c: Likewise.
+ * testsuite/libffi.call/cls_6byte.c: Likewise.
+ * testsuite/libffi.call/cls_7byte.c: Likewise.
+ * testsuite/libffi.call/cls_8byte.c: Likewise.
+ * testsuite/libffi.call/cls_9byte1.c: Likewise.
+ * testsuite/libffi.call/cls_9byte2.c: Likewise.
+ * testsuite/libffi.call/cls_double.c: Likewise.
+ * testsuite/libffi.call/cls_float.c: Likewise.
+ * testsuite/libffi.call/cls_schar.c: Likewise.
+ * testsuite/libffi.call/cls_sint.c: Likewise.
+ * testsuite/libffi.call/cls_sshort.c: Likewise.
+ * testsuite/libffi.call/cls_uchar.c: Likewise.
+ * testsuite/libffi.call/cls_uint.c: Likewise.
+ * testsuite/libffi.call/cls_ulonglong.c: Likewise.
+ * testsuite/libffi.call/cls_ushort.c: Likewise.
+ * testsuite/libffi.call/nested_struct.c: Likewise.
+ * testsuite/libffi.call/nested_struct1.c: Likewise.
+ * testsuite/libffi.call/nested_struct2.c: Likewise.
+ * testsuite/libffi.call/nested_struct3.c: Likewise.
+ * testsuite/libffi.call/problem1.c: Likewise.
+ * testsuite/libffi.special/unwindtest.cc: Likewise.
+
+2003-11-20 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/lib/libffi-dg.exp: Make the -lgcc_s conditional.
+
+2003-11-19 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/lib/libffi-dg.exp: Add DYLD_LIBRARY_PATH for darwin.
+ Add -lgcc_s to additional flags.
+
+2003-11-12 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * configure.in, include/Makefile.am: PR libgcj/11147, install
+ the ffitarget.h header file in a gcc versioned and target
+ dependent place.
+ * configure: Regenerated.
+ * Makefile.in, include/Makefile.in: Likewise.
+ * testsuite/Makefile.in: Likewise.
+
+2003-11-09 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/closure_fn0.c: Print result and check
+ with dg-output to make debugging easier.
+ * testsuite/libffi.call/closure_fn1.c: Likewise.
+ * testsuite/libffi.call/closure_fn2.c: Likewise.
+ * testsuite/libffi.call/closure_fn3.c: Likewise.
+ * testsuite/libffi.call/closure_fn4.c: Likewise.
+ * testsuite/libffi.call/closure_fn5.c: Likewise.
+ * testsuite/libffi.call/cls_12byte.c: Likewise.
+ * testsuite/libffi.call/cls_16byte.c: Likewise.
+ * testsuite/libffi.call/cls_18byte.c: Likewise.
+ * testsuite/libffi.call/cls_19byte.c: Likewise.
+ * testsuite/libffi.call/cls_1_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_20byte.c: Likewise.
+ * testsuite/libffi.call/cls_20byte1.c: Likewise.
+ * testsuite/libffi.call/cls_24byte.c: Likewise.
+ * testsuite/libffi.call/cls_2byte.c: Likewise.
+ * testsuite/libffi.call/cls_3_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_3byte1.c: Likewise.
+ * testsuite/libffi.call/cls_3byte2.c: Likewise.
+ * testsuite/libffi.call/cls_4_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_4byte.c: Likewise.
+ * testsuite/libffi.call/cls_5byte.c: Likewise.
+ * testsuite/libffi.call/cls_64byte.c: Likewise.
+ * testsuite/libffi.call/cls_6byte.c: Likewise.
+ * testsuite/libffi.call/cls_7byte.c: Likewise.
+ * testsuite/libffi.call/cls_8byte.c: Likewise.
+ * testsuite/libffi.call/cls_9byte1.c: Likewise.
+ * testsuite/libffi.call/cls_9byte2.c: Likewise.
+ * testsuite/libffi.call/cls_double.c: Likewise.
+ * testsuite/libffi.call/cls_float.c: Likewise.
+ * testsuite/libffi.call/cls_schar.c: Likewise.
+ * testsuite/libffi.call/cls_sint.c: Likewise.
+ * testsuite/libffi.call/cls_sshort.c: Likewise.
+ * testsuite/libffi.call/cls_uchar.c: Likewise.
+ * testsuite/libffi.call/cls_uint.c: Likewise.
+ * testsuite/libffi.call/cls_ulonglong.c: Likewise.
+ * testsuite/libffi.call/cls_ushort.c: Likewise.
+ * testsuite/libffi.call/problem1.c: Likewise.
+
+ * testsuite/libffi.special/unwindtest.cc: Make ffi_closure
+ static.
+
+2003-11-08 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/cls_9byte2.c: New test case.
+ * testsuite/libffi.call/cls_9byte1.c: Likewise.
+ * testsuite/libffi.call/cls_64byte.c: Likewise.
+ * testsuite/libffi.call/cls_20byte1.c: Likewise.
+ * testsuite/libffi.call/cls_19byte.c: Likewise.
+ * testsuite/libffi.call/cls_18byte.c: Likewise.
+ * testsuite/libffi.call/closure_fn4.c: Likewise.
+ * testsuite/libffi.call/closure_fn5.c: Likewise.
+ * testsuite/libffi.call/cls_schar.c: Likewise.
+ * testsuite/libffi.call/cls_sint.c: Likewise.
+ * testsuite/libffi.call/cls_sshort.c: Likewise.
+ * testsuite/libffi.call/nested_struct2.c: Likewise.
+ * testsuite/libffi.call/nested_struct3.c: Likewise.
+
+2003-11-08 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/cls_double.c: Do a check on the result.
+ * testsuite/libffi.call/cls_uchar.c: Likewise.
+ * testsuite/libffi.call/cls_uint.c: Likewise.
+ * testsuite/libffi.call/cls_ulonglong.c: Likewise.
+ * testsuite/libffi.call/cls_ushort.c: Likewise.
+ * testsuite/libffi.call/return_sc.c: Cleanup whitespaces.
+
+2003-11-06 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/prep_cif.c (ffi_prep_cif): Move the validity check after
+ the initialization.
+
+2003-10-23 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/java_raw_api.c (ffi_java_ptrarray_to_raw): Replace
+ FFI_ASSERT(FALSE) with FFI_ASSERT(0).
+
+2003-10-22 David Daney <ddaney@avtrex.com>
+
+ * src/mips/ffitarget.h: Replace undefined UINT32 and friends with
+ __attribute__((__mode__(__SI__))) and friends.
+
+2003-10-22 Andreas Schwab <schwab@suse.de>
+
+ * src/ia64/ffi.c: Replace FALSE/TRUE with false/true.
+
+2003-10-21 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * configure.in: AC_LINK_FILES(ffitarget.h).
+ * configure: Regenerate.
+ * Makefile.in: Likewise.
+ * include/Makefile.in: Likewise.
+ * testsuite/Makefile.in: Likewise.
+ * fficonfig.h.in: Likewise.
+
+2003-10-21 Paolo Bonzini <bonzini@gnu.org>
+ Richard Henderson <rth@redhat.com>
+
+ Avoid that ffi.h includes fficonfig.h.
+
+ * Makefile.am (EXTRA_DIST): Include ffitarget.h files
+ (TARGET_SRC_MIPS_GCC): Renamed to TARGET_SRC_MIPS_IRIX.
+ (TARGET_SRC_MIPS_SGI): Removed.
+ (MIPS_GCC): Renamed to TARGET_SRC_MIPS_IRIX.
+ (MIPS_SGI): Removed.
+ (CLEANFILES): Removed.
+ (mostlyclean-am, clean-am, mostlyclean-sub, clean-sub): New
+ targets.
+ * acconfig.h: Removed.
+ * configure.in: Compute sizeofs only for double and long double.
+ Use them to define and subst HAVE_LONG_DOUBLE. Include comments
+ into AC_DEFINE instead of using acconfig.h. Create
+ include/ffitarget.h instead of include/fficonfig.h. Rename
+ MIPS_GCC to MIPS_IRIX, drop MIPS_SGI since we are in gcc's tree.
+ AC_DEFINE EH_FRAME_FLAGS.
+ * include/Makefile.am (DISTCLEANFILES): New automake macro.
+ (hack_DATA): Add ffitarget.h.
+ * include/ffi.h.in: Remove all system specific definitions.
+ Declare raw API even if it is not installed, why bother?
+ Use limits.h instead of SIZEOF_* to define ffi_type_*. Do
+ not define EH_FRAME_FLAGS, it is in fficonfig.h now. Include
+ ffitarget.h instead of fficonfig.h. Remove ALIGN macro.
+ (UINT_ARG, INT_ARG): Removed, use ffi_arg and ffi_sarg instead.
+ * include/ffi_common.h (bool): Do not define.
+ (ffi_assert): Accept failed assertion.
+ (ffi_type_test): Return void and accept file/line.
+ (FFI_ASSERT): Pass stringized failed assertion.
+ (FFI_ASSERT_AT): New macro.
+ (FFI_ASSERT_VALID_TYPE): New macro.
+ (UINT8, SINT8, UINT16, SINT16, UINT32, SINT32,
+ UINT64, SINT64): Define here with gcc's __attribute__ macro
+ instead of in ffi.h
+ (FLOAT32, ALIGN): Define here instead of in ffi.h
+ * include/ffi-mips.h: Removed. Its content moved to
+ src/mips/ffitarget.h after separating assembly and C sections.
+ * src/alpha/ffi.c, src/alpha/ffi.c, src/java_raw_api.c
+ src/prep_cif.c, src/raw_api.c, src/ia64/ffi.c,
+ src/mips/ffi.c, src/mips/n32.S, src/mips/o32.S,
+ src/mips/ffitarget.h, src/sparc/ffi.c, src/x86/ffi64.c:
+ SIZEOF_ARG -> FFI_SIZEOF_ARG.
+ * src/ia64/ffi.c: Include stdbool.h (provided by GCC 2.95+).
+ * src/debug.c (ffi_assert): Accept stringized failed assertion.
+ (ffi_type_test): Rewritten.
+ * src/prep-cif.c (initialize_aggregate, ffi_prep_cif): Call
+ FFI_ASSERT_VALID_TYPE.
+ * src/alpha/ffitarget.h, src/arm/ffitarget.h,
+ src/ia64/ffitarget.h, src/m68k/ffitarget.h,
+ src/mips/ffitarget.h, src/powerpc/ffitarget.h,
+ src/s390/ffitarget.h, src/sh/ffitarget.h,
+ src/sh64/ffitarget.h, src/sparc/ffitarget.h,
+ src/x86/ffitarget.h: New files.
+ * src/alpha/osf.S, src/arm/sysv.S, src/ia64/unix.S,
+ src/m68k/sysv.S, src/mips/n32.S, src/mips/o32.S,
+ src/powerpc/aix.S, src/powerpc/darwin.S,
+ src/powerpc/ffi_darwin.c, src/powerpc/linux64.S,
+ src/powerpc/linux64_closure.S, src/powerpc/ppc_closure.S,
+ src/powerpc/sysv.S, src/s390/sysv.S, src/sh/sysv.S,
+ src/sh64/sysv.S, src/sparc/v8.S, src/sparc/v9.S,
+ src/x86/sysv.S, src/x86/unix64.S, src/x86/win32.S:
+ include fficonfig.h
+
+2003-10-20 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * src/mips/ffi.c: Use _ABIN32, _ABIO32 instead of external
+ _MIPS_SIM_NABI32, _MIPS_SIM_ABI32.
+
+2003-10-19 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/powerpc/ffi_darwin.c (ffi_prep_args): Declare bytes again.
+ Used when FFI_DEBUG = 1.
+
+2003-10-14 Alan Modra <amodra@bigpond.net.au>
+
+ * src/types.c (double, longdouble): Default POWERPC64 to 8 byte size
+ and align.
+
+2003-10-06 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * include/ffi_mips.h: Define FFI_MIPS_N32 for N32/N64 ABIs,
+ FFI_MIPS_O32 for O32 ABI.
+
+2003-10-01 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/lib/libffi-dg.exp: Set LD_LIBRARY_PATH_64 for
+ SPARC64. Cleanup whitespaces.
+
+2003-09-19 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * testsuite/libffi.call/closure_fn0.c: Xfail mips, arm,
+ strongarm, xscale. Cleanup whitespaces.
+ * testsuite/libffi.call/closure_fn1.c: Likewise.
+ * testsuite/libffi.call/closure_fn2.c: Likewise.
+ * testsuite/libffi.call/closure_fn3.c: Likewise.
+ * testsuite/libffi.call/cls_12byte.c: Likewise.
+ * testsuite/libffi.call/cls_16byte.c: Likewise.
+ * testsuite/libffi.call/cls_1_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_20byte.c: Likewise.
+ * testsuite/libffi.call/cls_24byte.c: Likewise.
+ * testsuite/libffi.call/cls_2byte.c: Likewise.
+ * testsuite/libffi.call/cls_3_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_3byte1.c: Likewise.
+ * testsuite/libffi.call/cls_3byte2.c: Likewise.
+ * testsuite/libffi.call/cls_4_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_4byte.c: Likewise.
+ * testsuite/libffi.call/cls_5byte.c: Likewise.
+ * testsuite/libffi.call/cls_6byte.c: Likewise.
+ * testsuite/libffi.call/cls_7byte.c: Likewise.
+ * testsuite/libffi.call/cls_8byte.c: Likewise.
+ * testsuite/libffi.call/cls_double.c: Likewise.
+ * testsuite/libffi.call/cls_float.c: Likewise.
+ * testsuite/libffi.call/cls_uchar.c: Likewise.
+ * testsuite/libffi.call/cls_uint.c: Likewise.
+ * testsuite/libffi.call/cls_ulonglong.c: Likewise.
+ * testsuite/libffi.call/cls_ushort.c: Likewise.
+ * testsuite/libffi.call/nested_struct.c: Likewise.
+ * testsuite/libffi.call/nested_struct1.c: Likewise.
+ * testsuite/libffi.call/problem1.c: Likewise.
+ * testsuite/libffi.special/unwindtest.cc: Likewise.
+ * testsuite/libffi.call/pyobjc-tc.c: Cleanup whitespaces.
+
+2003-09-18 David Edelsohn <edelsohn@gnu.org>
+
+ * src/powerpc/aix.S: Cleanup whitespaces.
+ * src/powerpc/aix_closure.S: Likewise.
+
+2003-09-18 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/powerpc/darwin.S: Cleanup whitespaces, comment formatting.
+ * src/powerpc/darwin_closure.S: Likewise.
+ * src/powerpc/ffi_darwin.c: Likewise.
+
+2003-09-18 Andreas Tobler <a.tobler@schweiz.ch>
+ David Edelsohn <edelsohn@gnu.org>
+
+ * src/types.c (double): Add AIX and Darwin to the right TYPEDEF.
+ * src/powerpc/aix_closure.S: Remove the pointer to the outgoing
+ parameter stack.
+ * src/powerpc/darwin_closure.S: Likewise.
+ * src/powerpc/ffi_darwin.c (ffi_prep_args): Handle structures
+ according to the Darwin/AIX ABI.
+ (ffi_prep_cif_machdep): Likewise.
+ (ffi_closure_helper_DARWIN): Likewise.
+ Remove the outgoing parameter stack logic. Simplify the evaluation
+ of the different CASE types.
+ (ffi_prep_clousure): Avoid the casts on lvalues. Change the branch
+ statement in the trampoline code.
+
+2003-09-18 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/ffi.c (ffi_prep_args): Take account into the alignement
+ for the register size.
+ (ffi_closure_helper_SYSV): Handle the structure return value
+ address correctly.
+ (ffi_closure_helper_SYSV): Return the appropriate type when
+ the registers are used for the structure return value.
+ * src/sh/sysv.S (ffi_closure_SYSV): Fix the stack layout for
+ the 64-bit return value. Update copyright years.
+
+2003-09-17 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * testsuite/lib/libffi-dg.exp (libffi_target_compile): Search in
+ srcdir for ffi_mips.h.
+
+2003-09-12 Alan Modra <amodra@bigpond.net.au>
+
+ * src/prep_cif.c (initialize_aggregate): Include tail padding in
+ structure size.
+ * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Correct
+ placement of float result.
+ * testsuite/libffi.special/unwindtest.cc (closure_test_fn1): Correct
+ cast of "resp" for big-endian 64 bit machines.
+
+2003-09-11 Alan Modra <amodra@bigpond.net.au>
+
+ * src/types.c (double, longdouble): Merge identical SH and ARM
+ typedefs, and add POWERPC64.
+ * src/powerpc/ffi.c (ffi_prep_args64): Correct next_arg calc for
+ struct split over gpr and rest.
+ (ffi_prep_cif_machdep): Correct intarg_count for structures.
+ * src/powerpc/linux64.S (ffi_call_LINUX64): Fix gpr offsets.
+
+2003-09-09 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/powerpc/ffi.c (ffi_closure_helper_SYSV) Handle struct
+ passing correctly.
+
+2003-09-09 Alan Modra <amodra@bigpond.net.au>
+
+ * configure: Regenerate.
+
+2003-09-04 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * Makefile.am: Remove build rules for ffitest.
+ * Makefile.in: Rebuilt.
+
+2003-09-04 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/java_raw_api.c: Include <stdlib.h> to fix compiler warning
+ about implicit declaration of abort().
+
+2003-09-04 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * Makefile.am: Add dejagnu test framework. Fixes PR other/11411.
+ * Makefile.in: Rebuilt.
+ * configure.in: Add dejagnu test framework.
+ * configure: Rebuilt.
+
+ * testsuite/Makefile.am: New file.
+ * testsuite/Makefile.in: Built
+ * testsuite/lib/libffi-dg.exp: New file.
+ * testsuite/config/default.exp: Likewise.
+ * testsuite/libffi.call/call.exp: Likewise.
+ * testsuite/libffi.call/ffitest.h: Likewise.
+ * testsuite/libffi.call/closure_fn0.c: Likewise.
+ * testsuite/libffi.call/closure_fn1.c: Likewise.
+ * testsuite/libffi.call/closure_fn2.c: Likewise.
+ * testsuite/libffi.call/closure_fn3.c: Likewise.
+ * testsuite/libffi.call/cls_1_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_3_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_4_1byte.c: Likewise.
+ * testsuite/libffi.call/cls_2byte.c: Likewise.
+ * testsuite/libffi.call/cls_3byte1.c: Likewise.
+ * testsuite/libffi.call/cls_3byte2.c: Likewise.
+ * testsuite/libffi.call/cls_4byte.c: Likewise.
+ * testsuite/libffi.call/cls_5byte.c: Likewise.
+ * testsuite/libffi.call/cls_6byte.c: Likewise.
+ * testsuite/libffi.call/cls_7byte.c: Likewise.
+ * testsuite/libffi.call/cls_8byte.c: Likewise.
+ * testsuite/libffi.call/cls_12byte.c: Likewise.
+ * testsuite/libffi.call/cls_16byte.c: Likewise.
+ * testsuite/libffi.call/cls_20byte.c: Likewise.
+ * testsuite/libffi.call/cls_24byte.c: Likewise.
+ * testsuite/libffi.call/cls_double.c: Likewise.
+ * testsuite/libffi.call/cls_float.c: Likewise.
+ * testsuite/libffi.call/cls_uchar.c: Likewise.
+ * testsuite/libffi.call/cls_uint.c: Likewise.
+ * testsuite/libffi.call/cls_ulonglong.c: Likewise.
+ * testsuite/libffi.call/cls_ushort.c: Likewise.
+ * testsuite/libffi.call/float.c: Likewise.
+ * testsuite/libffi.call/float1.c: Likewise.
+ * testsuite/libffi.call/float2.c: Likewise.
+ * testsuite/libffi.call/many.c: Likewise.
+ * testsuite/libffi.call/many_win32.c: Likewise.
+ * testsuite/libffi.call/nested_struct.c: Likewise.
+ * testsuite/libffi.call/nested_struct1.c: Likewise.
+ * testsuite/libffi.call/pyobjc-tc.c: Likewise.
+ * testsuite/libffi.call/problem1.c: Likewise.
+ * testsuite/libffi.call/promotion.c: Likewise.
+ * testsuite/libffi.call/return_ll.c: Likewise.
+ * testsuite/libffi.call/return_sc.c: Likewise.
+ * testsuite/libffi.call/return_uc.c: Likewise.
+ * testsuite/libffi.call/strlen.c: Likewise.
+ * testsuite/libffi.call/strlen_win32.c: Likewise.
+ * testsuite/libffi.call/struct1.c: Likewise.
+ * testsuite/libffi.call/struct2.c: Likewise.
+ * testsuite/libffi.call/struct3.c: Likewise.
+ * testsuite/libffi.call/struct4.c: Likewise.
+ * testsuite/libffi.call/struct5.c: Likewise.
+ * testsuite/libffi.call/struct6.c: Likewise.
+ * testsuite/libffi.call/struct7.c: Likewise.
+ * testsuite/libffi.call/struct8.c: Likewise.
+ * testsuite/libffi.call/struct9.c: Likewise.
+ * testsuite/libffi.special/special.exp: New file.
+ * testsuite/libffi.special/ffitestcxx.h: Likewise.
+ * testsuite/libffi.special/unwindtest.cc: Likewise.
+
+
+2003-08-13 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/ffi.c (OFS_INT16): Set 0 for little endian case. Update
+ copyright years.
+
+2003-08-02 Alan Modra <amodra@bigpond.net.au>
+
+ * src/powerpc/ffi.c (ffi_prep_args64): Modify for changed gcc
+ structure passing.
+ (ffi_closure_helper_LINUX64): Likewise.
+ * src/powerpc/linux64.S: Remove code writing to parm save area.
+ * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Use return
+ address in lr from ffi_closure_helper_LINUX64 call to calculate
+ table address. Optimize function tail.
+
+2003-07-28 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/sparc/ffi.c: Handle all floating point registers.
+ * src/sparc/v9.S: Likewise. Fixes second part of PR target/11410.
+
+2003-07-11 Gerald Pfeifer <pfeifer@dbai.tuwien.ac.at>
+
+ * README: Note that libffi is not part of GCC. Update the project
+ URL and status.
+
+2003-06-19 Franz Sirl <Franz.Sirl-kernel@lauterbach.com>
+
+ * src/powerpc/ppc_closure.S: Include ffi.h.
+
+2003-06-13 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * src/x86/sysv.S: Avoid gas-only .uleb128/.sleb128 directives.
+ Use C style comments.
+
+2003-06-13 Kaz Kojima <kkojima@rr.iij4u.or.jp>
+
+ * Makefile.am: Add SHmedia support. Fix a typo of SH support.
+ * Makefile.in: Regenerate.
+ * configure.in (sh64-*-linux*, sh5*-*-linux*): Add target.
+ * configure: Regenerate.
+ * include/ffi.h.in: Add SHmedia support.
+ * src/sh64/ffi.c: New file.
+ * src/sh64/sysv.S: New file.
+
+2003-05-16 Jakub Jelinek <jakub@redhat.com>
+
+ * configure.in (HAVE_RO_EH_FRAME): Check whether .eh_frame section
+ should be read-only.
+ * configure: Rebuilt.
+ * fficonfig.h.in: Rebuilt.
+ * include/ffi.h.in (EH_FRAME_FLAGS): Define.
+ * src/alpha/osf.S: Use EH_FRAME_FLAGS.
+ * src/powerpc/linux64.S: Likewise.
+ * src/powerpc/linux64_closure.S: Likewise. Include ffi.h.
+ * src/powerpc/sysv.S: Use EH_FRAME_FLAGS. Use pcrel encoding
+ if -fpic/-fPIC/-mrelocatable.
+ * src/powerpc/powerpc_closure.S: Likewise.
+ * src/sparc/v8.S: If HAVE_RO_EH_FRAME is defined, don't include
+ #write in .eh_frame flags.
+ * src/sparc/v9.S: Likewise.
+ * src/x86/unix64.S: Use EH_FRAME_FLAGS.
+ * src/x86/sysv.S: Likewise. Use pcrel encoding if -fpic/-fPIC.
+ * src/s390/sysv.S: Use EH_FRAME_FLAGS. Include ffi.h.
+
+2003-05-07 Jeff Sturm <jsturm@one-point.com>
+
+ Fixes PR bootstrap/10656
+ * configure.in (HAVE_AS_REGISTER_PSEUDO_OP): Test assembler
+ support for .register pseudo-op.
+ * src/sparc/v8.S: Use it.
+ * fficonfig.h.in: Rebuilt.
+ * configure: Rebuilt.
+
+2003-04-18 Jakub Jelinek <jakub@redhat.com>
+
+ * include/ffi.h.in (POWERPC64): Define if 64-bit.
+ (enum ffi_abi): Add FFI_LINUX64 on POWERPC.
+ Make it the default on POWERPC64.
+ (FFI_TRAMPOLINE_SIZE): Define to 24 on POWERPC64.
+ * configure.in: Change powerpc-*-linux* into powerpc*-*-linux*.
+ * configure: Rebuilt.
+ * src/powerpc/ffi.c (hidden): Define.
+ (ffi_prep_args_SYSV): Renamed from
+ ffi_prep_args. Cast pointers to unsigned long to shut up warnings.
+ (NUM_GPR_ARG_REGISTERS64, NUM_FPR_ARG_REGISTERS64,
+ ASM_NEEDS_REGISTERS64): New.
+ (ffi_prep_args64): New function.
+ (ffi_prep_cif_machdep): Handle FFI_LINUX64 ABI.
+ (ffi_call): Likewise.
+ (ffi_prep_closure): Likewise.
+ (flush_icache): Surround by #ifndef POWERPC64.
+ (ffi_dblfl): New union type.
+ (ffi_closure_helper_SYSV): Use it to avoid aliasing problems.
+ (ffi_closure_helper_LINUX64): New function.
+ * src/powerpc/ppc_closure.S: Surround whole file by #ifndef
+ __powerpc64__.
+ * src/powerpc/sysv.S: Likewise.
+ (ffi_call_SYSV): Rename ffi_prep_args to ffi_prep_args_SYSV.
+ * src/powerpc/linux64.S: New file.
+ * src/powerpc/linux64_closure.S: New file.
+ * Makefile.am (EXTRA_DIST): Add src/powerpc/linux64.S and
+ src/powerpc/linux64_closure.S.
+ (TARGET_SRC_POWERPC): Likewise.
+
+ * src/ffitest.c (closure_test_fn, closure_test_fn1, closure_test_fn2,
+ closure_test_fn3): Fix result printing on big-endian 64-bit
+ machines.
+ (main): Print tst2_arg instead of uninitialized tst2_result.
+
+ * src/ffitest.c (main): Hide what closure pointer really points to
+ from the compiler.
+
+2003-04-16 Richard Earnshaw <rearnsha@arm.com>
+
+ * configure.in (arm-*-netbsdelf*): Add configuration.
+ (configure): Regenerated.
+
+2003-04-04 Loren J. Rittle <ljrittle@acm.org>
+
+ * include/Makefile.in: Regenerate.
+
+2003-03-21 Zdenek Dvorak <rakdver@atrey.karlin.mff.cuni.cz>
+
+ * libffi/include/ffi.h.in: Define X86 instead of X86_64 in 32
+ bit mode.
+ * libffi/src/x86/ffi.c (ffi_closure_SYSV, ffi_closure_raw_SYSV):
+ Receive closure pointer through parameter, read args using
+ __builtin_dwarf_cfa.
+ (FFI_INIT_TRAMPOLINE): Send closure reference through eax.
+
+2003-03-12 Andreas Schwab <schwab@suse.de>
+
+ * configure.in: Avoid trailing /. in toolexeclibdir.
+ * configure: Rebuilt.
+
+2003-03-03 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/powerpc/darwin_closure.S: Recode to fit dynamic libraries.
+
+2003-02-06 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * libffi/src/powerpc/darwin_closure.S:
+ Fix alignement bug, allocate 8 bytes for the result.
+ * libffi/src/powerpc/aix_closure.S:
+ Likewise.
+ * libffi/src/powerpc/ffi_darwin.c:
+ Update stackframe description for aix/darwin_closure.S.
+
+2003-02-06 Jakub Jelinek <jakub@redhat.com>
+
+ * src/s390/ffi.c (ffi_closure_helper_SYSV): Add hidden visibility
+ attribute.
+
+2003-01-31 Christian Cornelssen <ccorn@cs.tu-berlin.de>,
+ Andreas Schwab <schwab@suse.de>
+
+ * configure.in: Adjust command to source config-ml.in to account
+ for changes to the libffi_basedir definition.
+ (libffi_basedir): Remove ${srcdir} from value and include trailing
+ slash if nonempty.
+
+ * configure: Regenerate.
+
+2003-01-29 Franz Sirl <Franz.Sirl-kernel@lauterbach.com>
+
+ * src/powerpc/ppc_closure.S: Recode to fit shared libs.
+
+2003-01-28 Andrew Haley <aph@redhat.com>
+
+ * include/ffi.h.in: Enable FFI_CLOSURES for x86_64.
+ * src/x86/ffi64.c (ffi_prep_closure): New.
+ (ffi_closure_UNIX64_inner): New.
+ * src/x86/unix64.S (ffi_closure_UNIX64): New.
+
+2003-01-27 Alexandre Oliva <aoliva@redhat.com>
+
+ * configure.in (toolexecdir, toolexeclibdir): Set and AC_SUBST.
+ Remove USE_LIBDIR conditional.
+ * Makefile.am (toolexecdir, toolexeclibdir): Don't override.
+ * Makefile.in, configure: Rebuilt.
+
+2003-01027 David Edelsohn <edelsohn@gnu.org>
+
+ * Makefile.am (TARGET_SRC_POWERPC_AIX): Fix typo.
+ * Makefile.in: Regenerate.
+
+2003-01-22 Andrew Haley <aph@redhat.com>
+
+ * src/powerpc/darwin.S (_ffi_call_AIX): Add Augmentation size to
+ unwind info.
+
+2003-01-21 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/powerpc/darwin.S: Add unwind info.
+ * src/powerpc/darwin_closure.S: Likewise.
+
+2003-01-14 Andrew Haley <aph@redhat.com>
+
+ * src/x86/ffi64.c (ffi_prep_args): Check for void retval.
+ (ffi_prep_cif_machdep): Likewise.
+ * src/x86/unix64.S: Add unwind info.
+
+2003-01-14 Andreas Jaeger <aj@suse.de>
+
+ * src/ffitest.c (main): Only use ffi_closures if those are
+ supported.
+
+2003-01-13 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * libffi/src/ffitest.c
+ add closure testcases
+
+2003-01-13 Kevin B. Hendricks <khendricks@ivey.uwo.ca>
+
+ * libffi/src/powerpc/ffi.c
+ fix alignment bug for float (4 byte aligned iso 8 byte)
+
+2003-01-09 Geoffrey Keating <geoffk@apple.com>
+
+ * src/powerpc/ffi_darwin.c: Remove RCS version string.
+ * src/powerpc/darwin.S: Remove RCS version string.
+
+2003-01-03 Jeff Sturm <jsturm@one-point.com>
+
+ * include/ffi.h.in: Add closure defines for SPARC, SPARC64.
+ * src/ffitest.c (main): Use static storage for closure.
+ * src/sparc/ffi.c (ffi_prep_closure, ffi_closure_sparc_inner): New.
+ * src/sparc/v8.S (ffi_closure_v8): New.
+ * src/sparc/v9.S (ffi_closure_v9): New.
+
+2002-11-10 Ranjit Mathew <rmathew@hotmail.com>
+
+ * include/ffi.h.in: Added FFI_STDCALL ffi_type
+ enumeration for X86_WIN32.
+ * src/x86/win32.S: Added ffi_call_STDCALL function
+ definition.
+ * src/x86/ffi.c (ffi_call/ffi_raw_call): Added
+ switch cases for recognising FFI_STDCALL and
+ calling ffi_call_STDCALL if target is X86_WIN32.
+ * src/ffitest.c (my_stdcall_strlen/stdcall_many):
+ stdcall versions of the "my_strlen" and "many"
+ test functions (for X86_WIN32).
+ Added test cases to test stdcall invocation using
+ these functions.
+
+2002-12-02 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/sysv.S: Add DWARF2 unwind info.
+
+2002-11-27 Ulrich Weigand <uweigand@de.ibm.com>
+
+ * src/s390/sysv.S (.eh_frame section): Make section read-only.
+
+2002-11-26 Jim Wilson <wilson@redhat.com>
+
+ * src/types.c (FFI_TYPE_POINTER): Has size 8 on IA64.
+
+2002-11-23 H.J. Lu <hjl@gnu.org>
+
+ * acinclude.m4: Add dummy AM_PROG_LIBTOOL.
+ Include ../config/accross.m4.
+ * aclocal.m4; Rebuild.
+ * configure: Likewise.
+
+2002-11-15 Ulrich Weigand <uweigand@de.ibm.com>
+
+ * src/s390/sysv.S (.eh_frame section): Adapt to pcrel FDE encoding.
+
+2002-11-11 DJ Delorie <dj@redhat.com>
+
+ * configure.in: Look for common files in the right place.
+
+2002-10-08 Ulrich Weigand <uweigand@de.ibm.com>
+
+ * src/java_raw_api.c (ffi_java_raw_to_ptrarray): Interpret
+ raw data as _Jv_word values, not ffi_raw.
+ (ffi_java_ptrarray_to_raw): Likewise.
+ (ffi_java_rvalue_to_raw): New function.
+ (ffi_java_raw_call): Call it.
+ (ffi_java_raw_to_rvalue): New function.
+ (ffi_java_translate_args): Call it.
+ * src/ffitest.c (closure_test_fn): Interpret return value
+ as ffi_arg, not int.
+ * src/s390/ffi.c (ffi_prep_cif_machdep): Add missing
+ FFI_TYPE_POINTER case.
+ (ffi_closure_helper_SYSV): Likewise. Also, assume return
+ values extended to word size.
+
+2002-10-02 Andreas Jaeger <aj@suse.de>
+
+ * src/x86/ffi64.c (ffi_prep_cif_machdep): Remove debug output.
+
+2002-10-01 Bo Thorsen <bo@smetana.suse.de>
+
+ * include/ffi.h.in: Fix i386 win32 compilation.
+
+2002-09-30 Ulrich Weigand <uweigand@de.ibm.com>
+
+ * configure.in: Add s390x-*-linux-* target.
+ * configure: Regenerate.
+ * include/ffi.h.in: Define S390X for s390x targets.
+ (FFI_CLOSURES): Define for s390/s390x.
+ (FFI_TRAMPOLINE_SIZE): Likewise.
+ (FFI_NATIVE_RAW_API): Likewise.
+ * src/prep_cif.c (ffi_prep_cif): Do not compute stack space for s390.
+ * src/types.c (FFI_TYPE_POINTER): Use 8-byte pointers on s390x.
+ * src/s390/ffi.c: Major rework of existing code. Add support for
+ s390x targets. Add closure support.
+ * src/s390/sysv.S: Likewise.
+
+2002-09-29 Richard Earnshaw <rearnsha@arm.com>
+
+ * src/arm/sysv.S: Fix typo.
+
+2002-09-28 Richard Earnshaw <rearnsha@arm.com>
+
+ * src/arm/sysv.S: If we don't have machine/asm.h and the pre-processor
+ has defined __USER_LABEL_PREFIX__, then use it in CNAME.
+ (ffi_call_SYSV): Handle soft-float.
+
+2002-09-27 Bo Thorsen <bo@suse.de>
+
+ * include/ffi.h.in: Fix multilib x86-64 support.
+
+2002-09-22 Kaveh R. Ghazi <ghazi@caip.rutgers.edu>
+
+ * Makefile.am (all-multi): Fix multilib parallel build.
+
+2002-07-19 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * configure.in (sh[34]*-*-linux*): Add brackets.
+ * configure: Regenerate.
+
+2002-07-18 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * Makefile.am: Add SH support.
+ * Makefile.in: Regenerate.
+ * configure.in (sh-*-linux*, sh[34]*-*-linux*): Add target.
+ * configure: Regenerate.
+ * include/ffi.h.in: Add SH support.
+ * src/sh/ffi.c: New file.
+ * src/sh/sysv.S: New file.
+ * src/types.c: Add SH support.
+
+2002-07-16 Bo Thorsen <bo@suse.de>
+
+ * src/x86/ffi64.c: New file that adds x86-64 support.
+ * src/x86/unix64.S: New file that handles argument setup for
+ x86-64.
+ * src/x86/sysv.S: Don't use this on x86-64.
+ * src/x86/ffi.c: Don't use this on x86-64.
+ Remove unused vars.
+ * src/prep_cif.c (ffi_prep_cif): Don't do stack size calculation
+ for x86-64.
+ * src/ffitest.c (struct6): New test that tests a special case in
+ the x86-64 ABI.
+ (struct7): Likewise.
+ (struct8): Likewise.
+ (struct9): Likewise.
+ (closure_test_fn): Silence warning about this when it's not used.
+ (main): Add the new tests.
+ (main): Fix a couple of wrong casts and silence some compiler warnings.
+ * include/ffi.h.in: Add x86-64 ABI definition.
+ * fficonfig.h.in: Regenerate.
+ * Makefile.am: Add x86-64 support.
+ * configure.in: Likewise.
+ * Makefile.in: Regenerate.
+ * configure: Likewise.
+
+2002-06-24 Bo Thorsen <bo@suse.de>
+
+ * src/types.c: Merge settings for similar architectures.
+ Add x86-64 sizes and alignments.
+
+2002-06-23 Bo Thorsen <bo@suse.de>
+
+ * src/arm/ffi.c (ffi_prep_args): Remove unused vars.
+ * src/sparc/ffi.c (ffi_prep_args_v8): Likewise.
+ * src/mips/ffi.c (ffi_prep_args): Likewise.
+ * src/m68k/ffi.c (ffi_prep_args): Likewise.
+
+2002-07-18 H.J. Lu (hjl@gnu.org)
+
+ * Makefile.am (TARGET_SRC_MIPS_LINUX): New.
+ (libffi_la_SOURCES): Support MIPS_LINUX.
+ (libffi_convenience_la_SOURCES): Likewise.
+ * Makefile.in: Regenerated.
+
+ * configure.in (mips64*-*): Skip.
+ (mips*-*-linux*): New.
+ * configure: Regenerated.
+
+ * src/mips/ffi.c: Include <sgidefs.h>.
+
+2002-06-06 Ulrich Weigand <uweigand@de.ibm.com>
+
+ * src/s390/sysv.S: Save/restore %r6. Add DWARF-2 unwind info.
+
+2002-05-27 Roger Sayle <roger@eyesopen.com>
+
+ * src/x86/ffi.c (ffi_prep_args): Remove reference to avn.
+
+2002-05-27 Bo Thorsen <bo@suse.de>
+
+ * src/x86/ffi.c (ffi_prep_args): Remove unused variable and
+ fix formatting.
+
+2002-05-13 Andreas Tobler <a.tobler@schweiz.ch>
+
+ * src/powerpc/ffi_darwin.c (ffi_prep_closure): Declare fd at
+ beginning of function (for older apple cc).
+
+2002-05-08 Alexandre Oliva <aoliva@redhat.com>
+
+ * configure.in (ORIGINAL_LD_FOR_MULTILIBS): Preserve LD at
+ script entry, and set LD to it when configuring multilibs.
+ * configure: Rebuilt.
+
+2002-05-05 Jason Thorpe <thorpej@wasabisystems.com>
+
+ * configure.in (sparc64-*-netbsd*): Add target.
+ (sparc-*-netbsdelf*): Likewise.
+ * configure: Regenerate.
+
+2002-04-28 David S. Miller <davem@redhat.com>
+
+ * configure.in, configure: Fix SPARC test in previous change.
+
+2002-04-29 Gerhard Tonn <GerhardTonn@swol.de>
+
+ * Makefile.am: Add Linux for S/390 support.
+ * Makefile.in: Regenerate.
+ * configure.in: Add Linux for S/390 support.
+ * configure: Regenerate.
+ * include/ffi.h.in: Add Linux for S/390 support.
+ * src/s390/ffi.c: New file from libffi CVS tree.
+ * src/s390/sysv.S: New file from libffi CVS tree.
+
+2002-04-28 Jakub Jelinek <jakub@redhat.com>
+
+ * configure.in (HAVE_AS_SPARC_UA_PCREL): Check for working
+ %r_disp32().
+ * src/sparc/v8.S: Use it.
+ * src/sparc/v9.S: Likewise.
+ * fficonfig.h.in: Rebuilt.
+ * configure: Rebuilt.
+
+2002-04-08 Hans Boehm <Hans_Boehm@hp.com>
+
+ * src/java_raw_api.c (ffi_java_raw_size): Handle FFI_TYPE_DOUBLE
+ correctly.
+ * src/ia64/unix.S: Add unwind information. Fix comments.
+ Save sp in a way that's compatible with unwind info.
+ (ffi_call_unix): Correctly restore sp in all cases.
+ * src/ia64/ffi.c: Add, fix comments.
+
+2002-04-08 Jakub Jelinek <jakub@redhat.com>
+
+ * src/sparc/v8.S: Make .eh_frame dependent on target word size.
+
+2002-04-06 Jason Thorpe <thorpej@wasabisystems.com>
+
+ * configure.in (alpha*-*-netbsd*): Add target.
+ * configure: Regenerate.
+
+2002-04-04 Jeff Sturm <jsturm@one-point.com>
+
+ * src/sparc/v8.S: Add unwind info.
+ * src/sparc/v9.S: Likewise.
+
+2002-03-30 Krister Walfridsson <cato@df.lth.se>
+
+ * configure.in: Enable i*86-*-netbsdelf*.
+ * configure: Rebuilt.
+
+2002-03-29 David Billinghurst <David.Billinghurst@riotinto.com>
+
+ PR other/2620
+ * src/mips/n32.s: Delete
+ * src/mips/o32.s: Delete
+
+2002-03-21 Loren J. Rittle <ljrittle@acm.org>
+
+ * configure.in: Enable alpha*-*-freebsd*.
+ * configure: Rebuilt.
+
+2002-03-17 Bryce McKinlay <bryce@waitaki.otago.ac.nz>
+
+ * Makefile.am: libfficonvenience -> libffi_convenience.
+ * Makefile.in: Rebuilt.
+
+ * Makefile.am: Define ffitest_OBJECTS.
+ * Makefile.in: Rebuilt.
+
+2002-03-07 Andreas Tobler <toa@pop.agri.ch>
+ David Edelsohn <edelsohn@gnu.org>
+
+ * Makefile.am (EXTRA_DIST): Add Darwin and AIX closure files.
+ (TARGET_SRC_POWERPC_AIX): Add aix_closure.S.
+ (TARGET_SRC_POWERPC_DARWIN): Add darwin_closure.S.
+ * Makefile.in: Regenerate.
+ * include/ffi.h.in: Add AIX and Darwin closure definitions.
+ * src/powerpc/ffi_darwin.c (ffi_prep_closure): New function.
+ (flush_icache, flush_range): New functions.
+ (ffi_closure_helper_DARWIN): New function.
+ * src/powerpc/aix_closure.S: New file.
+ * src/powerpc/darwin_closure.S: New file.
+
+2002-02-24 Jeff Sturm <jsturm@one-point.com>
+
+ * include/ffi.h.in: Add typedef for ffi_arg.
+ * src/ffitest.c (main): Declare rint with ffi_arg.
+
+2002-02-21 Andreas Tobler <toa@pop.agri.ch>
+
+ * src/powerpc/ffi_darwin.c (ffi_prep_args): Skip appropriate
+ number of GPRs for floating-point arguments.
+
+2002-01-31 Anthony Green <green@redhat.com>
+
+ * configure: Rebuilt.
+ * configure.in: Replace CHECK_SIZEOF and endian tests with
+ cross-compiler friendly macros.
+ * aclocal.m4 (AC_COMPILE_CHECK_SIZEOF, AC_C_BIGENDIAN_CROSS): New
+ macros.
+
+2002-01-18 David Edelsohn <edelsohn@gnu.org>
+
+ * src/powerpc/darwin.S (_ffi_call_AIX): New.
+ * src/powerpc/aix.S (ffi_call_DARWIN): New.
+
+2002-01-17 David Edelsohn <edelsohn@gnu.org>
+
+ * Makefile.am (EXTRA_DIST): Add Darwin and AIX files.
+ (TARGET_SRC_POWERPC_AIX): New.
+ (POWERPC_AIX): New stanza.
+ * Makefile.in: Regenerate.
+ * configure.in: Add AIX case.
+ * configure: Regenerate.
+ * include/ffi.h.in (ffi_abi): Add FFI_AIX.
+ * src/powerpc/ffi_darwin.c (ffi_status): Use "long" to scale frame
+ size. Fix "long double" support.
+ (ffi_call): Add FFI_AIX case.
+ * src/powerpc/aix.S: New.
+
+2001-10-09 John Hornkvist <john@toastedmarshmallow.com>
+
+ Implement Darwin PowerPC ABI.
+ * configure.in: Handle powerpc-*-darwin*.
+ * Makefile.am: Set source files for POWERPC_DARWIN.
+ * configure: Rebuilt.
+ * Makefile.in: Rebuilt.
+ * include/ffi.h.in: Define FFI_DARWIN and FFI_DEFAULT_ABI for
+ POWERPC_DARWIN.
+ * src/powerpc/darwin.S: New file.
+ * src/powerpc/ffi_darwin.c: New file.
+
+2001-10-07 Joseph S. Myers <jsm28@cam.ac.uk>
+
+ * src/x86/ffi.c: Fix spelling error of "separate" as "seperate".
+
+2001-07-16 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * src/x86/sysv.S: Avoid gas-only .balign directive.
+ Use C style comments.
+
+2001-07-16 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * src/alpha/ffi.c (ffi_prep_closure): Avoid gas-only mnemonic.
+ Fixes PR bootstrap/3563.
+
+2001-06-26 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * src/alpha/osf.S (ffi_closure_osf): Use .rdata for ECOFF.
+
+2001-06-25 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * configure.in: Recognize sparc*-sun-* host.
+ * configure: Regenerate.
+
+2001-06-06 Andrew Haley <aph@redhat.com>
+
+ * src/alpha/osf.S (__FRAME_BEGIN__): Conditionalize for ELF.
+
+2001-06-03 Andrew Haley <aph@redhat.com>
+
+ * src/alpha/osf.S: Add unwind info.
+ * src/powerpc/sysv.S: Add unwind info.
+ * src/powerpc/ppc_closure.S: Likewise.
+
+2000-05-31 Jeff Sturm <jsturm@one-point.com>
+
+ * configure.in: Fix AC_ARG_ENABLE usage.
+ * configure: Rebuilt.
+
+2001-05-06 Bryce McKinlay <bryce@waitaki.otago.ac.nz>
+
+ * configure.in: Remove warning about beta code.
+ * configure: Rebuilt.
+
+2001-04-25 Hans Boehm <Hans_Boehm@hp.com>
+
+ * src/ia64/unix.S: Restore stack pointer when returning from
+ ffi_closure_UNIX.
+ * src/ia64/ffi.c: Fix typo in comment.
+
+2001-04-18 Jim Wilson <wilson@redhat.com>
+
+ * src/ia64/unix.S: Delete unnecessary increment and decrement of loc2
+ to eliminate RAW DV.
+
+2001-04-12 Bryce McKinlay <bryce@albatross.co.nz>
+
+ * Makefile.am: Make a libtool convenience library.
+ * Makefile.in: Rebuilt.
+
+2001-03-29 Bryce McKinlay <bryce@albatross.co.nz>
+
+ * configure.in: Use different syntax for subdirectory creation.
+ * configure: Rebuilt.
+
+2001-03-27 Jon Beniston <jon@beniston.com>
+
+ * configure.in: Added X86_WIN32 target (Win32, CygWin, MingW).
+ * configure: Rebuilt.
+ * Makefile.am: Added X86_WIN32 target support.
+ * Makefile.in: Rebuilt.
+
+ * include/ffi.h.in: Added X86_WIN32 target support.
+
+ * src/ffitest.c: Doesn't run structure tests for X86_WIN32 targets.
+ * src/types.c: Added X86_WIN32 target support.
+
+ * src/x86/win32.S: New file. Based on sysv.S, but with EH
+ stuff removed and made to work with CygWin's gas.
+
+2001-03-26 Bryce McKinlay <bryce@albatross.co.nz>
+
+ * configure.in: Make target subdirectory in build dir.
+ * Makefile.am: Override suffix based rules to specify correct output
+ subdirectory.
+ * Makefile.in: Rebuilt.
+ * configure: Rebuilt.
+
+2001-03-23 Kevin B Hendricks <khendricks@ivey.uwo.ca>
+
+ * src/powerpc/ppc_closure.S: New file.
+ * src/powerpc/ffi.c (ffi_prep_args): Fixed ABI compatibility bug
+ involving long long and register pairs.
+ (ffi_prep_closure): New function.
+ (flush_icache): Likewise.
+ (ffi_closure_helper_SYSV): Likewise.
+ * include/ffi.h.in (FFI_CLOSURES): Define on PPC.
+ (FFI_TRAMPOLINE_SIZE): Likewise.
+ (FFI_NATIVE_RAW_API): Likewise.
+ * Makefile.in: Rebuilt.
+ * Makefile.am (EXTRA_DIST): Added src/powerpc/ppc_closure.S.
+ (TARGET_SRC_POWERPC): Likewise.
+
+2001-03-19 Tom Tromey <tromey@redhat.com>
+
+ * Makefile.in: Rebuilt.
+ * Makefile.am (ffitest_LDFLAGS): New macro.
+
+2001-03-02 Nick Clifton <nickc@redhat.com>
+
+ * include/ffi.h.in: Remove RCS ident string.
+ * include/ffi_mips.h: Remove RCS ident string.
+ * src/debug.c: Remove RCS ident string.
+ * src/ffitest.c: Remove RCS ident string.
+ * src/prep_cif.c: Remove RCS ident string.
+ * src/types.c: Remove RCS ident string.
+ * src/alpha/ffi.c: Remove RCS ident string.
+ * src/alpha/osf.S: Remove RCS ident string.
+ * src/arm/ffi.c: Remove RCS ident string.
+ * src/arm/sysv.S: Remove RCS ident string.
+ * src/mips/ffi.c: Remove RCS ident string.
+ * src/mips/n32.S: Remove RCS ident string.
+ * src/mips/o32.S: Remove RCS ident string.
+ * src/sparc/ffi.c: Remove RCS ident string.
+ * src/sparc/v8.S: Remove RCS ident string.
+ * src/sparc/v9.S: Remove RCS ident string.
+ * src/x86/ffi.c: Remove RCS ident string.
+ * src/x86/sysv.S: Remove RCS ident string.
+
+2001-02-08 Joseph S. Myers <jsm28@cam.ac.uk>
+
+ * include/ffi.h.in: Change sourceware.cygnus.com references to
+ gcc.gnu.org.
+
+2000-12-09 Richard Henderson <rth@redhat.com>
+
+ * src/alpha/ffi.c (ffi_call): Simplify struct return test.
+ (ffi_closure_osf_inner): Index rather than increment avalue
+ and arg_types. Give ffi_closure_osf the raw return value type.
+ * src/alpha/osf.S (ffi_closure_osf): Handle return value type
+ promotion.
+
+2000-12-07 Richard Henderson <rth@redhat.com>
+
+ * src/raw_api.c (ffi_translate_args): Fix typo.
+ (ffi_prep_closure): Likewise.
+
+ * include/ffi.h.in [ALPHA]: Define FFI_CLOSURES and
+ FFI_TRAMPOLINE_SIZE.
+ * src/alpha/ffi.c (ffi_prep_cif_machdep): Adjust minimal
+ cif->bytes for new ffi_call_osf implementation.
+ (ffi_prep_args): Absorb into ...
+ (ffi_call): ... here. Do all stack allocation here and
+ avoid a callback function.
+ (ffi_prep_closure, ffi_closure_osf_inner): New.
+ * src/alpha/osf.S (ffi_call_osf): Reimplement with no callback.
+ (ffi_closure_osf): New.
+
+2000-09-10 Alexandre Oliva <aoliva@redhat.com>
+
+ * config.guess, config.sub, install-sh: Removed.
+ * ltconfig, ltmain.sh, missing, mkinstalldirs: Likewise.
+ * Makefile.in: Rebuilt.
+
+ * acinclude.m4: Include libtool macros from the top level.
+ * aclocal.m4, configure: Rebuilt.
+
+2000-08-22 Alexandre Oliva <aoliva@redhat.com>
+
+ * configure.in [i*86-*-freebsd*] (TARGET, TARGETDIR): Set.
+ * configure: Rebuilt.
+
+2000-05-11 Scott Bambrough <scottb@netwinder.org>
+
+ * libffi/src/arm/sysv.S (ffi_call_SYSV): Doubles are not saved to
+ memory correctly. Use conditional instructions, not branches where
+ possible.
+
+2000-05-04 Tom Tromey <tromey@cygnus.com>
+
+ * configure: Rebuilt.
+ * configure.in: Match `arm*-*-linux-*'.
+ From Chris Dornan <cdornan@arm.com>.
+
+2000-04-28 Jakub Jelinek <jakub@redhat.com>
+
+ * Makefile.am (SUBDIRS): Define.
+ (AM_MAKEFLAGS): Likewise.
+ (Multilib support.): Add section.
+ * Makefile.in: Rebuilt.
+ * ltconfig (extra_compiler_flags, extra_compiler_flags_value):
+ New variables. Set for gcc using -print-multi-lib. Export them
+ to libtool.
+ (sparc64-*-linux-gnu*): Use libsuff 64 for search paths.
+ * ltmain.sh (B|b|V): Don't throw away gcc's -B, -b and -V options
+ for -shared links.
+ (extra_compiler_flags_value, extra_compiler_flags): Check these
+ for extra compiler options which need to be passed down in
+ compiler_flags.
+
+2000-04-16 Anthony Green <green@redhat.com>
+
+ * configure: Rebuilt.
+ * configure.in: Change i*86-pc-linux* to i*86-*-linux*.
+
+2000-04-14 Jakub Jelinek <jakub@redhat.com>
+
+ * include/ffi.h.in (SPARC64): Define for 64bit SPARC builds.
+ Set SPARC FFI_DEFAULT_ABI based on SPARC64 define.
+ * src/sparc/ffi.c (ffi_prep_args_v8): Renamed from ffi_prep_args.
+ Replace all void * sizeofs with sizeof(int).
+ Only compare type with FFI_TYPE_LONGDOUBLE if LONGDOUBLE is
+ different than DOUBLE.
+ Remove FFI_TYPE_SINT32 and FFI_TYPE_UINT32 cases (handled elsewhere).
+ (ffi_prep_args_v9): New function.
+ (ffi_prep_cif_machdep): Handle V9 ABI and long long on V8.
+ (ffi_V9_return_struct): New function.
+ (ffi_call): Handle FFI_V9 ABI from 64bit code and FFI_V8 ABI from
+ 32bit code (not yet cross-arch calls).
+ * src/sparc/v8.S: Add struct return delay nop.
+ Handle long long.
+ * src/sparc/v9.S: New file.
+ * src/prep_cif.c (ffi_prep_cif): Return structure pointer
+ is used on sparc64 only for structures larger than 32 bytes.
+ Pass by reference for structures is done for structure arguments
+ larger than 16 bytes.
+ * src/ffitest.c (main): Use 64bit rint on sparc64.
+ Run long long tests on sparc.
+ * src/types.c (FFI_TYPE_POINTER): Pointer is 64bit on alpha and
+ sparc64.
+ (FFI_TYPE_LONGDOUBLE): long double is 128 bit aligned to 128 bits
+ on sparc64.
+ * configure.in (sparc-*-linux*): New supported target.
+ (sparc64-*-linux*): Likewise.
+ * configure: Rebuilt.
+ * Makefile.am: Add v9.S to SPARC files.
+ * Makefile.in: Likewise.
+ (LINK): Surround $(CCLD) into double quotes, so that multilib
+ compiles work correctly.
+
+2000-04-04 Alexandre Petit-Bianco <apbianco@cygnus.com>
+
+ * configure: Rebuilt.
+ * configure.in: (i*86-*-solaris*): New libffi target. Patch
+ proposed by Bryce McKinlay.
+
+2000-03-20 Tom Tromey <tromey@cygnus.com>
+
+ * Makefile.in: Hand edit for java_raw_api.lo.
+
+2000-03-08 Bryce McKinlay <bryce@albatross.co.nz>
+
+ * config.guess, config.sub: Update from the gcc tree.
+ Fix for PR libgcj/168.
+
+2000-03-03 Tom Tromey <tromey@cygnus.com>
+
+ * Makefile.in: Fixed ia64 by hand.
+
+ * configure: Rebuilt.
+ * configure.in (--enable-multilib): New option.
+ (libffi_basedir): New subst.
+ (AC_OUTPUT): Added multilib code.
+
+2000-03-02 Tom Tromey <tromey@cygnus.com>
+
+ * Makefile.in: Rebuilt.
+ * Makefile.am (TARGET_SRC_IA64): Use `ia64', not `alpha', as
+ directory name.
+
+2000-02-25 Hans Boehm <boehm@acm.org>
+
+ * src/ia64/ffi.c, src/ia64/ia64_flags.h, src/ia64/unix.S: New
+ files.
+ * src/raw_api.c (ffi_translate_args): Fixed typo in argument
+ list.
+ (ffi_prep_raw_closure): Use ffi_translate_args, not
+ ffi_closure_translate.
+ * src/java_raw_api.c: New file.
+ * src/ffitest.c (closure_test_fn): New function.
+ (main): Define `rint' as long long on IA64. Added new test when
+ FFI_CLOSURES is defined.
+ * include/ffi.h.in (ALIGN): Use size_t, not unsigned.
+ (ffi_abi): Recognize IA64.
+ (ffi_raw): Added `flt' field.
+ Added "Java raw API" code.
+ * configure.in: Recognize ia64.
+ * Makefile.am (TARGET_SRC_IA64): New macro.
+ (libffi_la_common_SOURCES): Added java_raw_api.c.
+ (libffi_la_SOURCES): Define in IA64 case.
+
+2000-01-04 Tom Tromey <tromey@cygnus.com>
+
+ * Makefile.in: Rebuilt with newer automake.
+
+1999-12-31 Tom Tromey <tromey@cygnus.com>
+
+ * Makefile.am (INCLUDES): Added -I$(top_srcdir)/src.
+
+1999-09-01 Tom Tromey <tromey@cygnus.com>
+
+ * include/ffi.h.in: Removed PACKAGE and VERSION defines and
+ undefs.
+ * fficonfig.h.in: Rebuilt.
+ * configure: Rebuilt.
+ * configure.in: Pass 3rd argument to AM_INIT_AUTOMAKE.
+ Use AM_PROG_LIBTOOL (automake 1.4 compatibility).
+ * acconfig.h: Don't #undef PACKAGE or VERSION.
+
+1999-08-09 Anthony Green <green@cygnus.com>
+
+ * include/ffi.h.in: Try to work around messy header problem
+ with PACKAGE and VERSION.
+
+ * configure: Rebuilt.
+ * configure.in: Change version to 2.00-beta.
+
+ * fficonfig.h.in: Rebuilt.
+ * acconfig.h (FFI_NO_STRUCTS, FFI_NO_RAW_API): Define.
+
+ * src/x86/ffi.c (ffi_raw_call): Rename.
+
+1999-08-02 Kresten Krab Thorup <krab@dominiq.is.s.u-tokyo.ac.jp>
+
+ * src/x86/ffi.c (ffi_closure_SYSV): New function.
+ (ffi_prep_incoming_args_SYSV): Ditto.
+ (ffi_prep_closure): Ditto.
+ (ffi_closure_raw_SYSV): Ditto.
+ (ffi_prep_raw_closure): More ditto.
+ (ffi_call_raw): Final ditto.
+
+ * include/ffi.h.in: Add definitions for closure and raw API.
+
+ * src/x86/ffi.c (ffi_prep_cif_machdep): Added case for
+ FFI_TYPE_UINT64.
+
+ * Makefile.am (libffi_la_common_SOURCES): Added raw_api.c
+
+ * src/raw_api.c: New file.
+
+ * include/ffi.h.in (ffi_raw): New type.
+ (UINT_ARG, SINT_ARG): New defines.
+ (ffi_closure, ffi_raw_closure): New types.
+ (ffi_prep_closure, ffi_prep_raw_closure): New declarations.
+
+ * configure.in: Add check for endianness and sizeof void*.
+
+ * src/x86/sysv.S (ffi_call_SYSV): Call fixup routine via argument,
+ instead of directly.
+
+ * configure: Rebuilt.
+
+Thu Jul 8 14:28:42 1999 Anthony Green <green@cygnus.com>
+
+ * configure.in: Add x86 and powerpc BeOS configurations.
+ From Makoto Kato <m_kato@ga2.so-net.ne.jp>.
+
+1999-05-09 Anthony Green <green@cygnus.com>
+
+ * configure.in: Add warning about this being beta code.
+ Remove src/Makefile.am from the picture.
+ * configure: Rebuilt.
+
+ * Makefile.am: Move logic from src/Makefile.am. Add changes
+ to support libffi as a target library.
+ * Makefile.in: Rebuilt.
+
+ * aclocal.m4, config.guess, config.sub, ltconfig, ltmain.sh:
+ Upgraded to new autoconf, automake, libtool.
+
+ * README: Tweaks.
+
+ * LICENSE: Update copyright date.
+
+ * src/Makefile.am, src/Makefile.in: Removed.
+
+1998-11-29 Anthony Green <green@cygnus.com>
+
+ * include/ChangeLog: Removed.
+ * src/ChangeLog: Removed.
+ * src/mips/ChangeLog: Removed.
+ * src/sparc/ChangeLog: Remboved.
+ * src/x86/ChangeLog: Removed.
+
+ * ChangeLog.v1: Created.
+
+=============================================================================
+From the old ChangeLog.libffi file....
+
+2011-02-08 Andreas Tobler <andreast@fgznet.ch>
+
+ * testsuite/lib/libffi.exp: Tweak for stand-alone mode.
+
+2009-12-25 Samuli Suominen <ssuominen@gentoo.org>
+
+ * configure.ac: Undefine _AC_ARG_VAR_PRECIOUS for autoconf 2.64.
+ * configure: Rebuilt.
+ * fficonfig.h.in: Rebuilt.
+
+2009-06-16 Andrew Haley <aph@redhat.com>
+
+ * testsuite/libffi.call/cls_align_sint64.c,
+ testsuite/libffi.call/cls_align_uint64.c,
+ testsuite/libffi.call/cls_longdouble_va.c,
+ testsuite/libffi.call/cls_ulonglong.c,
+ testsuite/libffi.call/return_ll1.c,
+ testsuite/libffi.call/stret_medium2.c: Fix printf format
+ specifiers.
+ * testsuite/libffi.call/huge_struct.c: Ad x86 XFAILs.
+ * testsuite/libffi.call/float2.c: Fix dg-excess-errors.
+ * testsuite/libffi.call/ffitest.h,
+ testsuite/libffi.special/ffitestcxx.h (PRIdLL, PRIuLL): Define.
+
+2009-06-12 Andrew Haley <aph@redhat.com>
+
+ * testsuite/libffi.call/cls_align_sint64.c,
+ testsuite/libffi.call/cls_align_uint64.c,
+ testsuite/libffi.call/cls_ulonglong.c,
+ testsuite/libffi.call/return_ll1.c,
+ testsuite/libffi.call/stret_medium2.c: Fix printf format
+ specifiers.
+ testsuite/libffi.special/unwindtest.cc: include stdint.h.
+
+2009-06-11 Timothy Wall <twall@users.sf.net>
+
+ * Makefile.am,
+ configure.ac,
+ include/ffi.h.in,
+ include/ffi_common.h,
+ src/closures.c,
+ src/dlmalloc.c,
+ src/x86/ffi.c,
+ src/x86/ffitarget.h,
+ src/x86/win64.S (new),
+ README: Added win64 support (mingw or MSVC)
+ * Makefile.in,
+ include/Makefile.in,
+ man/Makefile.in,
+ testsuite/Makefile.in,
+ configure,
+ aclocal.m4: Regenerated
+ * ltcf-c.sh: properly escape cygwin/w32 path
+ * man/ffi_call.3: Clarify size requirements for return value.
+ * src/x86/ffi64.c: Fix filename in comment.
+ * src/x86/win32.S: Remove unused extern.
+
+ * testsuite/libffi.call/closure_fn0.c,
+ testsuite/libffi.call/closure_fn1.c,
+ testsuite/libffi.call/closure_fn2.c,
+ testsuite/libffi.call/closure_fn3.c,
+ testsuite/libffi.call/closure_fn4.c,
+ testsuite/libffi.call/closure_fn5.c,
+ testsuite/libffi.call/closure_fn6.c,
+ testsuite/libffi.call/closure_stdcall.c,
+ testsuite/libffi.call/cls_12byte.c,
+ testsuite/libffi.call/cls_16byte.c,
+ testsuite/libffi.call/cls_18byte.c,
+ testsuite/libffi.call/cls_19byte.c,
+ testsuite/libffi.call/cls_1_1byte.c,
+ testsuite/libffi.call/cls_20byte.c,
+ testsuite/libffi.call/cls_20byte1.c,
+ testsuite/libffi.call/cls_24byte.c,
+ testsuite/libffi.call/cls_2byte.c,
+ testsuite/libffi.call/cls_3_1byte.c,
+ testsuite/libffi.call/cls_3byte1.c,
+ testsuite/libffi.call/cls_3byte2.c,
+ testsuite/libffi.call/cls_4_1byte.c,
+ testsuite/libffi.call/cls_4byte.c,
+ testsuite/libffi.call/cls_5_1_byte.c,
+ testsuite/libffi.call/cls_5byte.c,
+ testsuite/libffi.call/cls_64byte.c,
+ testsuite/libffi.call/cls_6_1_byte.c,
+ testsuite/libffi.call/cls_6byte.c,
+ testsuite/libffi.call/cls_7_1_byte.c,
+ testsuite/libffi.call/cls_7byte.c,
+ testsuite/libffi.call/cls_8byte.c,
+ testsuite/libffi.call/cls_9byte1.c,
+ testsuite/libffi.call/cls_9byte2.c,
+ testsuite/libffi.call/cls_align_double.c,
+ testsuite/libffi.call/cls_align_float.c,
+ testsuite/libffi.call/cls_align_longdouble.c,
+ testsuite/libffi.call/cls_align_longdouble_split.c,
+ testsuite/libffi.call/cls_align_longdouble_split2.c,
+ testsuite/libffi.call/cls_align_pointer.c,
+ testsuite/libffi.call/cls_align_sint16.c,
+ testsuite/libffi.call/cls_align_sint32.c,
+ testsuite/libffi.call/cls_align_sint64.c,
+ testsuite/libffi.call/cls_align_uint16.c,
+ testsuite/libffi.call/cls_align_uint32.c,
+ testsuite/libffi.call/cls_align_uint64.c,
+ testsuite/libffi.call/cls_dbls_struct.c,
+ testsuite/libffi.call/cls_double.c,
+ testsuite/libffi.call/cls_double_va.c,
+ testsuite/libffi.call/cls_float.c,
+ testsuite/libffi.call/cls_longdouble.c,
+ testsuite/libffi.call/cls_longdouble_va.c,
+ testsuite/libffi.call/cls_multi_schar.c,
+ testsuite/libffi.call/cls_multi_sshort.c,
+ testsuite/libffi.call/cls_multi_sshortchar.c,
+ testsuite/libffi.call/cls_multi_uchar.c,
+ testsuite/libffi.call/cls_multi_ushort.c,
+ testsuite/libffi.call/cls_multi_ushortchar.c,
+ testsuite/libffi.call/cls_pointer.c,
+ testsuite/libffi.call/cls_pointer_stack.c,
+ testsuite/libffi.call/cls_schar.c,
+ testsuite/libffi.call/cls_sint.c,
+ testsuite/libffi.call/cls_sshort.c,
+ testsuite/libffi.call/cls_uchar.c,
+ testsuite/libffi.call/cls_uint.c,
+ testsuite/libffi.call/cls_ulonglong.c,
+ testsuite/libffi.call/cls_ushort.c,
+ testsuite/libffi.call/err_bad_abi.c,
+ testsuite/libffi.call/err_bad_typedef.c,
+ testsuite/libffi.call/float2.c,
+ testsuite/libffi.call/huge_struct.c,
+ testsuite/libffi.call/nested_struct.c,
+ testsuite/libffi.call/nested_struct1.c,
+ testsuite/libffi.call/nested_struct10.c,
+ testsuite/libffi.call/nested_struct2.c,
+ testsuite/libffi.call/nested_struct3.c,
+ testsuite/libffi.call/nested_struct4.c,
+ testsuite/libffi.call/nested_struct5.c,
+ testsuite/libffi.call/nested_struct6.c,
+ testsuite/libffi.call/nested_struct7.c,
+ testsuite/libffi.call/nested_struct8.c,
+ testsuite/libffi.call/nested_struct9.c,
+ testsuite/libffi.call/problem1.c,
+ testsuite/libffi.call/return_ldl.c,
+ testsuite/libffi.call/return_ll1.c,
+ testsuite/libffi.call/stret_large.c,
+ testsuite/libffi.call/stret_large2.c,
+ testsuite/libffi.call/stret_medium.c,
+ testsuite/libffi.call/stret_medium2.c,
+ testsuite/libffi.special/unwindtest.cc: use ffi_closure_alloc instead
+ of checking for MMAP. Use intptr_t instead of long casts.
+
+2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/powerpc/ffitarget.h: Fix misapplied merge from gcc.
+
+2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/mips/o32.S,
+ src/mips/n32.S: Fix licence formatting.
+
+2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/x86/darwin.S: Fix licence formatting.
+ src/x86/win32.S: Likewise.
+ src/sh64/sysv.S: Likewise.
+ src/sh/sysv.S: Likewise.
+
+2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/sh64/ffi.c: Remove lint directives. Was missing from merge
+ of Andreas Tobler's patch from 2006-04-22.
+
+2009-06-04 Andrew Haley <aph@redhat.com>
+
+ * src/sh/ffi.c: Apply missing hunk from Alexandre Oliva's patch of
+ 2007-03-07.
+
+2008-12-26 Timothy Wall <twall@users.sf.net>
+
+ * testsuite/libffi.call/cls_longdouble.c,
+ testsuite/libffi.call/cls_longdouble_va.c,
+ testsuite/libffi.call/cls_align_longdouble.c,
+ testsuite/libffi.call/cls_align_longdouble_split.c,
+ testsuite/libffi.call/cls_align_longdouble_split2.c: mark expected
+ failures on x86_64 cygwin/mingw.
+
+2008-12-22 Timothy Wall <twall@users.sf.net>
+
+ * testsuite/libffi.call/closure_fn0.c,
+ testsuite/libffi.call/closure_fn1.c,
+ testsuite/libffi.call/closure_fn2.c,
+ testsuite/libffi.call/closure_fn3.c,
+ testsuite/libffi.call/closure_fn4.c,
+ testsuite/libffi.call/closure_fn5.c,
+ testsuite/libffi.call/closure_fn6.c,
+ testsuite/libffi.call/closure_loc_fn0.c,
+ testsuite/libffi.call/closure_stdcall.c,
+ testsuite/libffi.call/cls_align_pointer.c,
+ testsuite/libffi.call/cls_pointer.c,
+ testsuite/libffi.call/cls_pointer_stack.c: use portable cast from
+ pointer to integer (intptr_t).
+ * testsuite/libffi.call/cls_longdouble.c: disable for win64.
+
+2008-12-19 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 3.0.8.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision.
+ * README: Update for new release.
+
+2008-11-11 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 3.0.7.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision.
+ * README: Update for new release.
+
+2008-08-25 Andreas Tobler <a.tobler@schweiz.org>
+
+ * src/powerpc/ffitarget.h (ffi_abi): Add FFI_LINUX and
+ FFI_LINUX_SOFT_FLOAT to the POWERPC_FREEBSD enum.
+ Add note about flag bits used for FFI_SYSV_TYPE_SMALL_STRUCT.
+ Adjust copyright notice.
+ * src/powerpc/ffi.c: Add two new flags to indicate if we have one
+ register or two register to use for FFI_SYSV structs.
+ (ffi_prep_cif_machdep): Pass the right register flag introduced above.
+ (ffi_closure_helper_SYSV): Fix the return type for
+ FFI_SYSV_TYPE_SMALL_STRUCT. Comment.
+ Adjust copyright notice.
+
+2008-07-24 Anthony Green <green@redhat.com>
+
+ * testsuite/libffi.call/cls_dbls_struct.c,
+ testsuite/libffi.call/cls_double_va.c,
+ testsuite/libffi.call/cls_longdouble.c,
+ testsuite/libffi.call/cls_longdouble_va.c,
+ testsuite/libffi.call/cls_pointer.c,
+ testsuite/libffi.call/cls_pointer_stack.c,
+ testsuite/libffi.call/err_bad_abi.c: Clean up failures from
+ compiler warnings.
+
+2008-07-17 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 3.0.6.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision. Add documentation.
+ * README: Update for new release.
+
+2008-07-16 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/ffi.c (ffi_prep_closure_loc): Turn INSN into an unsigned
+ int.
+
+2008-07-16 Kaz Kojima <kkojima@gcc.gnu.org>
+
+ * src/sh/sysv.S: Add .note.GNU-stack on Linux.
+ * src/sh64/sysv.S: Likewise.
+
+2008-04-03 Anthony Green <green@redhat.com>
+
+ * libffi.pc.in (Libs): Add -L${libdir}.
+ * configure.ac: Bump version to 3.0.5.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision.
+ * README: Update for new release.
+
+2008-04-03 Anthony Green <green@redhat.com>
+ Xerces Ranby <xerxes@zafena.se>
+
+ * include/ffi.h.in: Wrap definition of target architecture to
+ protect from double definitions.
+
+2008-03-22 Moriyoshi Koizumi <moriyoshi@gmail.com>
+
+ * src/x86/ffi.c (ffi_prep_closure_loc): Fix for bug revealed in
+ closure_loc_fn0.c.
+ * testsuite/libffi.call/closure_loc_fn0.c (closure_loc_test_fn0):
+ New test.
+
+2008-03-04 Anthony Green <green@redhat.com>
+ Blake Chaffin
+ hos@tamanegi.org
+
+ * testsuite/libffi.call/cls_align_longdouble_split2.c
+ testsuite/libffi.call/cls_align_longdouble_split.c
+ testsuite/libffi.call/cls_dbls_struct.c
+ testsuite/libffi.call/cls_double_va.c
+ testsuite/libffi.call/cls_longdouble.c
+ testsuite/libffi.call/cls_longdouble_va.c
+ testsuite/libffi.call/cls_pointer.c
+ testsuite/libffi.call/cls_pointer_stack.c
+ testsuite/libffi.call/err_bad_abi.c
+ testsuite/libffi.call/err_bad_typedef.c
+ testsuite/libffi.call/huge_struct.c
+ testsuite/libffi.call/stret_large2.c
+ testsuite/libffi.call/stret_large.c
+ testsuite/libffi.call/stret_medium2.c
+ testsuite/libffi.call/stret_medium.c: New tests from Apple.
+
+2008-02-26 Jakub Jelinek <jakub@redhat.com>
+ Anthony Green <green@redhat.com>
+
+ * src/alpha/osf.S: Add .note.GNU-stack on Linux.
+ * src/s390/sysv.S: Likewise.
+ * src/powerpc/linux64.S: Likewise.
+ * src/powerpc/linux64_closure.S: Likewise.
+ * src/powerpc/ppc_closure.S: Likewise.
+ * src/powerpc/sysv.S: Likewise.
+ * src/x86/unix64.S: Likewise.
+ * src/x86/sysv.S: Likewise.
+ * src/sparc/v8.S: Likewise.
+ * src/sparc/v9.S: Likewise.
+ * src/m68k/sysv.S: Likewise.
+ * src/ia64/unix.S: Likewise.
+ * src/arm/sysv.S: Likewise.
+
+2008-02-26 Anthony Green <green@redhat.com>
+ Thomas Heller <theller@ctypes.org>
+
+ * src/x86/ffi.c (ffi_closure_SYSV_inner): Change C++ comment to C
+ comment.
+
+2008-02-26 Anthony Green <green@redhat.org>
+ Thomas Heller <theller@ctypes.org>
+
+ * include/ffi.h.in: Change void (*)() to void (*)(void).
+
+2008-02-26 Anthony Green <green@redhat.org>
+ Thomas Heller <theller@ctypes.org>
+
+ * src/alpha/ffi.c: Change void (*)() to void (*)(void).
+ src/alpha/osf.S, src/arm/ffi.c, src/frv/ffi.c, src/ia64/ffi.c,
+ src/ia64/unix.S, src/java_raw_api.c, src/m32r/ffi.c,
+ src/mips/ffi.c, src/pa/ffi.c, src/pa/hpux32.S, src/pa/linux.S,
+ src/powerpc/ffi.c, src/powerpc/ffi_darwin.c, src/raw_api.c,
+ src/s390/ffi.c, src/sh/ffi.c, src/sh64/ffi.c, src/sparc/ffi.c,
+ src/x86/ffi.c, src/x86/unix64.S, src/x86/darwin64.S,
+ src/x86/ffi64.c: Ditto.
+
+2008-02-24 Anthony Green <green@redhat.org>
+
+ * configure.ac: Accept openbsd*, not just openbsd.
+ Bump version to 3.0.4.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision.
+ * README: Update for new release.
+
+2008-02-22 Anthony Green <green@redhat.com>
+
+ * README: Clean up list of tested platforms.
+
+2008-02-22 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 3.0.3.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision.
+ * README: Update for new release. Clean up test docs.
+
+2008-02-22 Bjoern Koenig <bkoenig@alpha-tierchen.de>
+ Andreas Tobler <a.tobler@schweiz.org>
+
+ * configure.ac: Add amd64-*-freebsd* target.
+ * configure: Regenerate.
+
+2008-02-22 Thomas Heller <theller@ctypes.org>
+
+ * configure.ac: Add x86 OpenBSD support.
+ * configure: Rebuilt.
+
+2008-02-21 Thomas Heller <theller@ctypes.org>
+
+ * README: Change "make test" to "make check".
+
+2008-02-21 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 3.0.2.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision.
+ * README: Update for new release.
+
+2008-02-21 Björn König <bkoenig@alpha-tierchen.de>
+
+ * src/x86/freebsd.S: New file.
+ * configure.ac: Add x86 FreeBSD support.
+ * Makefile.am: Ditto.
+
+2008-02-15 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 3.0.1.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * libtool-version: Increment revision.
+ * README: Update for new release.
+
+2008-02-15 David Daney <ddaney@avtrex.com>
+
+ * src/mips/ffi.c: Remove extra '>' from include directive.
+ (ffi_prep_closure_loc): Use clear_location instead of tramp.
+
+2008-02-15 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 3.0.0.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+
+2008-02-15 David Daney <ddaney@avtrex.com>
+
+ * src/mips/ffi.c (USE__BUILTIN___CLEAR_CACHE):
+ Define (conditionally), and use it to include cachectl.h.
+ (ffi_prep_closure_loc): Fix cache flushing.
+ * src/mips/ffitarget.h (_ABIN32, _ABI64, _ABIO32): Define.
+
+2008-02-15 Anthony Green <green@redhat.com>
+
+ * man/ffi_call.3, man/ffi_prep_cif.3, man/ffi.3:
+ Update dates and remove all references to ffi_prep_closure.
+ * configure.ac: Bump version to 2.99.9.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+
+2008-02-15 Anthony Green <green@redhat.com>
+
+ * man/ffi_prep_closure.3: Delete.
+ * man/Makefile.am (EXTRA_DIST): Remove ffi_prep_closure.3.
+ (man_MANS): Ditto.
+ * man/Makefile.in: Rebuilt.
+ * configure.ac: Bump version to 2.99.8.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+
+2008-02-14 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 2.99.7.
+ * configure, doc/stamp-vti, doc/version.texi: Rebuilt.
+ * include/ffi.h.in LICENSE src/debug.c src/closures.c
+ src/ffitest.c src/s390/sysv.S src/s390/ffitarget.h
+ src/types.c src/m68k/ffitarget.h src/raw_api.c src/frv/ffi.c
+ src/frv/ffitarget.h src/sh/ffi.c src/sh/sysv.S
+ src/sh/ffitarget.h src/powerpc/ffitarget.h src/pa/ffi.c
+ src/pa/ffitarget.h src/pa/linux.S src/java_raw_api.c
+ src/cris/ffitarget.h src/x86/ffi.c src/x86/sysv.S
+ src/x86/unix64.S src/x86/win32.S src/x86/ffitarget.h
+ src/x86/ffi64.c src/x86/darwin.S src/ia64/ffi.c
+ src/ia64/ffitarget.h src/ia64/ia64_flags.h src/ia64/unix.S
+ src/sparc/ffi.c src/sparc/v9.S src/sparc/ffitarget.h
+ src/sparc/v8.S src/alpha/ffi.c src/alpha/ffitarget.h
+ src/alpha/osf.S src/sh64/ffi.c src/sh64/sysv.S
+ src/sh64/ffitarget.h src/mips/ffi.c src/mips/ffitarget.h
+ src/mips/n32.S src/mips/o32.S src/arm/ffi.c src/arm/sysv.S
+ src/arm/ffitarget.h src/prep_cif.c: Update license text.
+
+2008-02-14 Anthony Green <green@redhat.com>
+
+ * README: Update tested platforms.
+ * configure.ac: Bump version to 2.99.6.
+ * configure: Rebuilt.
+
+2008-02-14 Anthony Green <green@redhat.com>
+
+ * configure.ac: Bump version to 2.99.5.
+ * configure: Rebuilt.
+ * Makefile.am (EXTRA_DIST): Add darwin64.S
+ * Makefile.in: Rebuilt.
+ * testsuite/lib/libffi-dg.exp: Remove libstdc++ bits from GCC tree.
+ * LICENSE: Update WARRANTY.
+
+2008-02-14 Anthony Green <green@redhat.com>
+
+ * libffi.pc.in (libdir): Fix libdir definition.
+ * configure.ac: Bump version to 2.99.4.
+ * configure: Rebuilt.
+
+2008-02-14 Anthony Green <green@redhat.com>
+
+ * README: Update.
+ * libffi.info: New file.
+ * doc/stamp-vti: New file.
+ * configure.ac: Bump version to 2.99.3.
+ * configure: Rebuilt.
+
+2008-02-14 Anthony Green <green@redhat.com>
+
+ * Makefile.am (SUBDIRS): Add man dir.
+ * Makefile.in: Rebuilt.
+ * configure.ac: Create Makefile.
+ * configure: Rebuilt.
+ * man/ffi_call.3 man/ffi_prep_cif.3 man/ffi_prep_closure.3
+ man/Makefile.am man/Makefile.in: New files.
+
+2008-02-14 Tom Tromey <tromey@redhat.com>
+
+ * aclocal.m4, Makefile.in, configure, fficonfig.h.in: Rebuilt.
+ * mdate-sh, texinfo.tex: New files.
+ * Makefile.am (info_TEXINFOS): New variable.
+ * doc/libffi.texi: New file.
+ * doc/version.texi: Likewise.
+
+2008-02-14 Anthony Green <green@redhat.com>
+
+ * Makefile.am (AM_CFLAGS): Don't compile with -D$(TARGET).
+ (lib_LTLIBRARIES): Define.
+ (toolexeclib_LIBRARIES): Undefine.
+ * Makefile.in: Rebuilt.
+ * configure.ac: Reset version to 2.99.1.
+ * configure.in: Rebuilt.
+
+2008-02-14 Anthony Green <green@redhat.com>
+
+ * libffi.pc.in: Use @PACKAGE_NAME@ and @PACKAGE_VERSION@.
+ * configure.ac: Reset version to 2.99.1.
+ * configure.in: Rebuilt.
+ * Makefile.am (EXTRA_DIST): Add ChangeLog.libffi.
+ * Makefile.in: Rebuilt.
+ * LICENSE: Update copyright notice.
+
+2008-02-14 Anthony Green <green@redhat.com>
+
+ * include/Makefile.am (nodist_includes_HEADERS): Define. Don't
+ distribute ffitarget.h or ffi.h from the build include dir.
+ * Makefile.in: Rebuilt.
+
+2008-02-14 Anthony Green <green@redhat.com>
+
+ * include/Makefile.am (includesdir): Install headers under libdir.
+ (pkgconfigdir): Define. Install libffi.pc.
+ * include/Makefile.in: Rebuilt.
+ * libffi.pc.in: Create.
+ * libtool-version: Increment CURRENT
+ * configure.ac: Add libffi.pc.in
+ * configure: Rebuilt.
+
+2008-02-03 Anthony Green <green@redhat.com>
+
+ * include/Makefile.am (includesdir): Fix header install with
+ DESTDIR.
+ * include/Makefile.in: Rebuilt.
+
+2008-02-03 Timothy Wall <twall@users.sf.net>
+
+ * src/x86/ffi.c (FFI_INIT_TRAMPOLINE_STDCALL): Calculate jump return
+ offset based on code pointer, not data pointer.
+
+2008-02-01 Anthony Green <green@redhat.com>
+
+ * include/Makefile.am: Fix header installs.
+ * Makefile.am: Ditto.
+ * include/Makefile.in: Rebuilt.
+ * Makefile.in: Ditto.
+
+2008-02-01 Anthony Green <green@redhat.com>
+
+ * src/x86/ffi.c (FFI_INIT_TRAMPOLINE_STDCALL,
+ FFI_INIT_TRAMPOLINE): Revert my broken changes to twall's last
+ patch.
+
+2008-01-31 Anthony Green <green@redhat.com>
+
+ * Makefile.am (EXTRA_DIST): Add missing files.
+ * testsuite/Makefile.am: Ditto.
+ * Makefile.in, testsuite/Makefile.in: Rebuilt.
+
+2008-01-31 Timothy Wall <twall@users.sf.net>
+
+ * testsuite/libffi.call/closure_stdcall.c: Add test for stdcall
+ closures.
+ * src/x86/ffitarget.h: Increase size of trampoline for stdcall
+ closures.
+ * src/x86/win32.S: Add assembly for stdcall closure.
+ * src/x86/ffi.c: Initialize stdcall closure trampoline.
+
+2008-01-30 H.J. Lu <hongjiu.lu@intel.com>
+
+ PR libffi/34612
+ * src/x86/sysv.S (ffi_closure_SYSV): Pop 4 byte from stack when
+ returning struct.
+
+ * testsuite/libffi.call/call.exp: Add "-O2 -fomit-frame-pointer"
+ tests.
+
+2008-01-30 Anthony Green <green@redhat.com>
+
+ * Makefile.am, include/Makefile.am: Move headers to
+ libffi_la_SOURCES for new automake.
+ * Makefile.in, include/Makefile.in: Rebuilt.
+
+ * testsuite/lib/wrapper.exp: Copied from gcc tree to allow for
+ execution outside of gcc tree.
+ * testsuite/lib/target-libpath.exp: Ditto.
+
+ * testsuite/lib/libffi-dg.exp: Many changes to allow for execution
+ outside of gcc tree.
+
+
+=============================================================================
+From the old ChangeLog.libgcj file....
+
+2004-01-14 Kelley Cook <kcook@gcc.gnu.org>
+
+ * configure.in: Add in AC_PREREQ(2.13)
+
+2003-02-20 Alexandre Oliva <aoliva@redhat.com>
+
+ * configure.in: Propagate ORIGINAL_LD_FOR_MULTILIBS to
+ config.status.
+ * configure: Rebuilt.
+
+2002-01-27 Alexandre Oliva <aoliva@redhat.com>
+
+ * configure.in (toolexecdir, toolexeclibdir): Set and AC_SUBST.
+ Remove USE_LIBDIR conditional.
+ * Makefile.am (toolexecdir, toolexeclibdir): Don't override.
+ * Makefile.in, configure: Rebuilt.
+
+Mon Aug 9 18:33:38 1999 Rainer Orth <ro@TechFak.Uni-Bielefeld.DE>
+
+ * include/Makefile.in: Rebuilt.
+ * Makefile.in: Rebuilt
+ * Makefile.am (toolexeclibdir): Add $(MULTISUBDIR) even for native
+ builds.
+ Use USE_LIBDIR.
+
+ * configure: Rebuilt.
+ * configure.in (USE_LIBDIR): Define for native builds.
+ Use lowercase in configure --help explanations.
+
+1999-08-08 Anthony Green <green@cygnus.com>
+
+ * include/ffi.h.in (FFI_FN): Remove `...'.
+
+1999-08-08 Anthony Green <green@cygnus.com>
+
+ * Makefile.in: Rebuilt.
+ * Makefile.am (AM_CFLAGS): Compile with -fexceptions.
+
+ * src/x86/sysv.S: Add exception handling metadata.
+
+
+=============================================================================
+
+The libffi version 1 ChangeLog archive.
+
+Version 1 of libffi had per-directory ChangeLogs. Current and future
+versions have a single ChangeLog file in the root directory. The
+version 1 ChangeLogs have all been concatenated into this file for
+future reference only.
+
+--- libffi ----------------------------------------------------------------
+
+Mon Oct 5 02:17:50 1998 Anthony Green <green@cygnus.com>
+
+ * configure.in: Boosted rev.
+ * configure, Makefile.in, aclocal.m4: Rebuilt.
+ * README: Boosted rev and updated release notes.
+
+Mon Oct 5 01:03:03 1998 Anthony Green <green@cygnus.com>
+
+ * configure.in: Boosted rev.
+ * configure, Makefile.in, aclocal.m4: Rebuilt.
+ * README: Boosted rev and updated release notes.
+
+1998-07-25 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de>
+
+ * m68k/ffi.c (ffi_prep_cif_machdep): Use bitmask for cif->flags.
+ Correctly handle small structures.
+ (ffi_prep_args): Also handle small structures.
+ (ffi_call): Pass size of return type to ffi_call_SYSV.
+ * m68k/sysv.S: Adjust for above changes. Correctly align small
+ structures in the return value.
+
+ * types.c (uint64, sint64) [M68K]: Change alignment to 4.
+
+Fri Apr 17 17:26:58 1998 Anthony Green <green@hoser.cygnus.com>
+
+ * configure.in: Boosted rev.
+ * configure,Makefile.in,aclocal.m4: Rebuilt.
+ * README: Boosted rev and added release notes.
+
+Sun Feb 22 00:50:41 1998 Geoff Keating <geoffk@ozemail.com.au>
+
+ * configure.in: Add PowerPC config bits.
+
+1998-02-14 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de>
+
+ * configure.in: Add m68k config bits. Change AC_CANONICAL_SYSTEM
+ to AC_CANONICAL_HOST, this is not a compiler. Use $host instead
+ of $target. Remove AC_CHECK_SIZEOF(char), we already know the
+ result. Fix argument of AC_ARG_ENABLE.
+ * configure, fficonfig.h.in: Rebuilt.
+
+Tue Feb 10 20:53:40 1998 Richard Henderson <rth@cygnus.com>
+
+ * configure.in: Add Alpha config bits.
+
+Tue May 13 13:39:20 1997 Anthony Green <green@hoser.cygnus.com>
+
+ * README: Updated dates and reworded Irix comments.
+
+ * configure.in: Removed AC_PROG_RANLIB.
+
+ * Makefile.in, aclocal.m4, config.guess, config.sub, configure,
+ ltmain.sh, */Makefile.in: libtoolized again and rebuilt with
+ automake and autoconf.
+
+Sat May 10 18:44:50 1997 Tom Tromey <tromey@cygnus.com>
+
+ * configure, aclocal.m4: Rebuilt.
+ * configure.in: Don't compute EXTRADIST; now handled in
+ src/Makefile.in. Removed macros implied by AM_INIT_AUTOMAKE.
+ Don't run AM_MAINTAINER_MODE.
+
+Thu May 8 14:34:05 1997 Anthony Green <green@hoser.cygnus.com>
+
+ * missing, ltmain.sh, ltconfig.sh: Created. These are new files
+ required by automake and libtool.
+
+ * README: Boosted rev to 1.14. Added notes.
+
+ * acconfig.h: Moved PACKAGE and VERSION for new automake.
+
+ * configure.in: Changes for libtool.
+
+ * Makefile.am (check): make test now make check. Uses libtool now.
+
+ * Makefile.in, configure.in, aclocal.h, fficonfig.h.in: Rebuilt.
+
+Thu May 1 16:27:07 1997 Anthony Green <green@hoser.cygnus.com>
+
+ * missing: Added file required by new automake.
+
+Tue Nov 26 14:10:42 1996 Anthony Green <green@csk3.cygnus.com>
+
+ * acconfig.h: Added USING_PURIFY flag. This is defined when
+ --enable-purify-safety was used at configure time.
+
+ * configure.in (allsources): Added --enable-purify-safety switch.
+ (VERSION): Boosted rev to 1.13.
+ * configure: Rebuilt.
+
+Fri Nov 22 06:46:12 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * configure.in (VERSION): Boosted rev to 1.12.
+ Removed special CFLAGS hack for gcc.
+ * configure: Rebuilt.
+
+ * README: Boosted rev to 1.12. Added notes.
+
+ * Many files: Cygnus Support changed to Cygnus Solutions.
+
+Wed Oct 30 11:15:25 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * configure.in (VERSION): Boosted rev to 1.11.
+ * configure: Rebuilt.
+
+ * README: Boosted rev to 1.11. Added notes about GNU make.
+
+Tue Oct 29 12:25:12 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * configure.in: Fixed -Wall trick.
+ (VERSION): Boosted rev.
+ * configure: Rebuilt
+
+ * acconfig.h: Needed for --enable-debug configure switch.
+
+ * README: Boosted rev to 1.09. Added more notes on building
+ libffi, and LCLint.
+
+ * configure.in: Added --enable-debug switch. Boosted rev to
+ 1.09.
+ * configure: Rebuilt
+
+Tue Oct 15 13:11:28 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * configure.in (VERSION): Boosted rev to 1.08
+ * configure: Rebuilt.
+
+ * README: Added n32 bug fix notes.
+
+ * Makefile.am: Added "make lint" production.
+ * Makefile.in: Rebuilt.
+
+Mon Oct 14 10:54:46 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * README: Added web page reference.
+
+ * configure.in, README: Boosted rev to 1.05
+ * configure: Rebuilt.
+
+ * README: Fixed n32 sample code.
+
+Fri Oct 11 17:09:28 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * README: Added sparc notes.
+
+ * configure.in, README: Boosted rev to 1.04.
+ * configure: Rebuilt.
+
+Thu Oct 10 10:31:03 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * configure.in, README: Boosted rev to 1.03.
+ * configure: Rebuilt.
+
+ * README: Added struct notes.
+
+ * Makefile.am (EXTRA_DIST): Added LICENSE to distribution.
+ * Makefile.in: Rebuilt.
+
+ * README: Removed Linux section. No special notes now
+ because aggregates arg/return types work.
+
+Wed Oct 9 16:16:42 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * README, configure.in (VERSION): Boosted rev to 1.02
+ * configure: Rebuilt.
+
+Tue Oct 8 11:56:33 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * README (NOTE): Added n32 notes.
+
+ * Makefile.am: Added test production.
+ * Makefile: Rebuilt
+
+ * README: spell checked!
+
+ * configure.in (VERSION): Boosted rev to 1.01
+ * configure: Rebuilt.
+
+Mon Oct 7 15:50:22 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * configure.in: Added nasty bit to support SGI tools.
+ * configure: Rebuilt.
+
+ * README: Added SGI notes. Added note about automake bug.
+
+Mon Oct 7 11:00:28 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * README: Rewrote intro, and fixed examples.
+
+Fri Oct 4 10:19:55 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * configure.in: -D$TARGET is no longer used as a compiler switch.
+ It is now inserted into ffi.h at configure time.
+ * configure: Rebuilt.
+
+ * FFI_ABI and FFI_STATUS are now ffi_abi and ffi_status.
+
+Thu Oct 3 13:47:34 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * README, LICENSE: Created. Wrote some docs.
+
+ * configure.in: Don't barf on i586-unknown-linuxaout.
+ Added EXTRADIST code for "make dist".
+ * configure: Rebuilt.
+
+ * */Makefile.in: Rebuilt with patched automake.
+
+Tue Oct 1 17:12:25 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * Makefile.am, aclocal.m4, config.guess, config.sub,
+ configure.in, fficonfig.h.in, install-sh, mkinstalldirs,
+ stamp-h.in: Created
+ * Makefile.in, configure: Generated
+
+--- libffi/include --------------------------------------------------------
+
+Tue Feb 24 13:09:36 1998 Anthony Green <green@gerbil.cygnus.com>
+
+ * ffi_mips.h: Updated FFI_TYPE_STRUCT_* values based on
+ ffi.h.in changes. This is a work-around for SGI's "simple"
+ assembler.
+
+Sun Feb 22 00:51:55 1998 Geoff Keating <geoffk@ozemail.com.au>
+
+ * ffi.h.in: PowerPC support.
+
+1998-02-14 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de>
+
+ * ffi.h.in: Add m68k support.
+ (FFI_TYPE_LONGDOUBLE): Make it a separate value.
+
+Tue Feb 10 20:55:16 1998 Richard Henderson <rth@cygnus.com>
+
+ * ffi.h.in (SIZEOF_ARG): Use a pointer type by default.
+
+ * ffi.h.in: Alpha support.
+
+Fri Nov 22 06:48:45 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.h.in, ffi_common.h: Cygnus Support -> Cygnus Solutions.
+
+Wed Nov 20 22:31:01 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.h.in: Added ffi_type_void definition.
+
+Tue Oct 29 12:22:40 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * Makefile.am (hack_DATA): Always install ffi_mips.h.
+
+ * ffi.h.in: Removed FFI_DEBUG. It's now in the correct
+ place (acconfig.h).
+ Added #include <stddef.h> for size_t definition.
+
+Tue Oct 15 17:23:35 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.h.in, ffi_common.h, ffi_mips.h: More clean up.
+ Commented out #define of FFI_DEBUG.
+
+Tue Oct 15 13:01:06 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi_common.h: Added bool definition.
+
+ * ffi.h.in, ffi_common.h: Clean up based on LCLint output.
+ Added funny /*@...@*/ comments to annotate source.
+
+Mon Oct 14 12:29:23 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.h.in: Interface changes based on feedback from Jim
+ Blandy.
+
+Fri Oct 11 16:49:35 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.h.in: Small change for sparc support.
+
+Thu Oct 10 14:53:37 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi_mips.h: Added FFI_TYPE_STRUCT_* definitions for
+ special structure return types.
+
+Wed Oct 9 13:55:57 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.h.in: Added SIZEOF_ARG definition for X86
+
+Tue Oct 8 11:40:36 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.h.in (FFI_FN): Added macro for eliminating compiler warnings.
+ Use it to case your function pointers to the proper type.
+
+ * ffi_mips.h (SIZEOF_ARG): Added magic to fix type promotion bug.
+
+ * Makefile.am (EXTRA_DIST): Added ffi_mips.h to EXTRA_DIST.
+ * Makefile: Rebuilt.
+
+ * ffi_mips.h: Created. Moved all common mips definitions here.
+
+Mon Oct 7 10:58:12 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.h.in: The SGI assember is very picky about parens. Redefined
+ some macros to avoid problems.
+
+ * ffi.h.in: Added FFI_DEFAULT_ABI definitions. Also added
+ externs for pointer, and 64bit integral ffi_types.
+
+Fri Oct 4 09:51:37 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.h.in: Added FFI_ABI member to ffi_cif and changed
+ function prototypes accordingly.
+ Added #define @TARGET@. Now programs including ffi.h don't
+ have to specify this themselves.
+
+Thu Oct 3 15:36:44 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.h.in: Changed ffi_prep_cif's values from void* to void**
+
+ * Makefile.am (EXTRA_DIST): Added EXTRA_DIST for "make dist"
+ to work.
+ * Makefile.in: Regenerated.
+
+Wed Oct 2 10:16:59 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * Makefile.am: Created
+ * Makefile.in: Generated
+
+ * ffi_common.h: Added rcsid comment
+
+Tue Oct 1 17:13:51 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.h.in, ffi_common.h: Created
+
+--- libffi/src ------------------------------------------------------------
+
+Mon Oct 5 02:17:50 1998 Anthony Green <green@cygnus.com>
+
+ * arm/ffi.c, arm/sysv.S: Created.
+
+ * Makefile.am: Added arm files.
+ * Makefile.in: Rebuilt.
+
+Mon Oct 5 01:41:38 1998 Anthony Green <green@rtl.cygnus.com>
+
+ * Makefile.am (libffi_la_LDFLAGS): Incremented revision.
+
+Sun Oct 4 16:27:17 1998 Anthony Green <green@cygnus.com>
+
+ * alpha/osf.S (ffi_call_osf): Patch for DU assembler.
+
+ * ffitest.c (main): long long and long double return values work
+ for x86.
+
+Fri Apr 17 11:50:58 1998 Anthony Green <green@hoser.cygnus.com>
+
+ * Makefile.in: Rebuilt.
+
+ * ffitest.c (main): Floating point tests not executed for systems
+ with broken lond double (SunOS 4 w/ GCC).
+
+ * types.c: Fixed x86 alignment info for long long types.
+
+Thu Apr 16 07:15:28 1998 Anthony Green <green@ada.cygnus.com>
+
+ * ffitest.c: Added more notes about GCC bugs under Irix 6.
+
+Wed Apr 15 08:42:22 1998 Anthony Green <green@hoser.cygnus.com>
+
+ * ffitest.c (struct5): New test function.
+ (main): New test with struct5.
+
+Thu Mar 5 10:48:11 1998 Anthony Green <green@tootie.to.cygnus.com>
+
+ * prep_cif.c (initialize_aggregate): Fix assertion for
+ nested structures.
+
+Tue Feb 24 16:33:41 1998 Anthony Green <green@hoser.cygnus.com>
+
+ * prep_cif.c (ffi_prep_cif): Added long double support for sparc.
+
+Sun Feb 22 00:52:18 1998 Geoff Keating <geoffk@ozemail.com.au>
+
+ * powerpc/asm.h: New file.
+ * powerpc/ffi.c: New file.
+ * powerpc/sysv.S: New file.
+ * Makefile.am: PowerPC port.
+ * ffitest.c (main): Allow all tests to run even in presence of gcc
+ bug on PowerPC.
+
+1998-02-17 Anthony Green <green@hoser.cygnus.com>
+
+ * mips/ffi.c: Fixed comment typo.
+
+ * x86/ffi.c (ffi_prep_cif_machdep), x86/sysv.S (retfloat):
+ Fixed x86 long double return handling.
+
+ * types.c: Fixed x86 long double alignment info.
+
+1998-02-14 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de>
+
+ * types.c: Add m68k support.
+
+ * ffitest.c (floating): Add long double parameter.
+ (return_ll, ldblit): New functions to test long long and long
+ double return value.
+ (main): Fix type error in assignment of ts[1-4]_type.elements.
+ Add tests for long long and long double arguments and return
+ values.
+
+ * prep_cif.c (ffi_prep_cif) [M68K]: Don't allocate argument for
+ struct value pointer.
+
+ * m68k/ffi.c, m68k/sysv.S: New files.
+ * Makefile.am: Add bits for m68k port. Add kludge to work around
+ automake deficiency.
+ (test): Don't require "." in $PATH.
+ * Makefile.in: Rebuilt.
+
+Wed Feb 11 07:36:50 1998 Anthony Green <green@hoser.cygnus.com>
+
+ * Makefile.in: Rebuilt.
+
+Tue Feb 10 20:56:00 1998 Richard Henderson <rth@cygnus.com>
+
+ * alpha/ffi.c, alpha/osf.S: New files.
+ * Makefile.am: Alpha port.
+
+Tue Nov 18 14:12:07 1997 Anthony Green <green@hoser.cygnus.com>
+
+ * mips/ffi.c (ffi_prep_cif_machdep): Initialize rstruct_flag
+ for n32.
+
+Tue Jun 3 17:18:20 1997 Anthony Green <green@hoser.cygnus.com>
+
+ * ffitest.c (main): Added hack to get structure tests working
+ correctly.
+
+Sat May 10 19:06:42 1997 Tom Tromey <tromey@cygnus.com>
+
+ * Makefile.in: Rebuilt.
+ * Makefile.am (EXTRA_DIST): Explicitly list all distributable
+ files in subdirs.
+ (VERSION, CC): Removed.
+
+Thu May 8 17:19:01 1997 Anthony Green <green@hoser.cygnus.com>
+
+ * Makefile.am: Many changes for new automake and libtool.
+ * Makefile.in: Rebuilt.
+
+Fri Nov 22 06:57:56 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffitest.c (main): Fixed test case for non mips machines.
+
+Wed Nov 20 22:31:59 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * types.c: Added ffi_type_void declaration.
+
+Tue Oct 29 13:07:19 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffitest.c (main): Fixed character constants.
+ (main): Emit warning for structure test 3 failure on Sun.
+
+ * Makefile.am (VPATH): Fixed VPATH def'n so automake won't
+ strip it out.
+ Moved distdir hack from libffi to automake.
+ (ffitest): Added missing -c for $(COMPILE) (change in automake).
+ * Makefile.in: Rebuilt.
+
+Tue Oct 15 13:08:20 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * Makefile.am: Added "make lint" production.
+ * Makefile.in: Rebuilt.
+
+ * prep_cif.c (STACK_ARG_SIZE): Improved STACK_ARG_SIZE macro.
+ Clean up based on LCLint output. Added funny /*@...@*/ comments to
+ annotate source.
+
+ * ffitest.c, debug.c: Cleaned up code.
+
+Mon Oct 14 12:26:56 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffitest.c: Changes based on interface changes.
+
+ * prep_cif.c (ffi_prep_cif): Cleaned up interface based on
+ feedback from Jim Blandy.
+
+Fri Oct 11 15:53:18 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffitest.c: Reordered tests while porting to sparc.
+ Made changes to handle lame structure passing for sparc.
+ Removed calls to fflush().
+
+ * prep_cif.c (ffi_prep_cif): Added special case for sparc
+ aggregate type arguments.
+
+Thu Oct 10 09:56:51 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffitest.c (main): Added structure passing/returning tests.
+
+ * prep_cif.c (ffi_prep_cif): Perform proper initialization
+ of structure return types if needed.
+ (initialize_aggregate): Bug fix
+
+Wed Oct 9 16:04:20 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * types.c: Added special definitions for x86 (double doesn't
+ need double word alignment).
+
+ * ffitest.c: Added many tests
+
+Tue Oct 8 09:19:22 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * prep_cif.c (ffi_prep_cif): Fixed assertion.
+
+ * debug.c (ffi_assert): Must return a non void now.
+
+ * Makefile.am: Added test production.
+ * Makefile: Rebuilt.
+
+ * ffitest.c (main): Created.
+
+ * types.c: Created. Stripped common code out of */ffi.c.
+
+ * prep_cif.c: Added missing stdlib.h include.
+
+ * debug.c (ffi_type_test): Used "a" to eliminate compiler
+ warnings in non-debug builds. Included ffi_common.h.
+
+Mon Oct 7 15:36:42 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * Makefile.am: Added a rule for .s -> .o
+ This is required by the SGI compiler.
+ * Makefile: Rebuilt.
+
+Fri Oct 4 09:51:08 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * prep_cif.c (initialize_aggregate): Moved abi specification
+ to ffi_prep_cif().
+
+Thu Oct 3 15:37:37 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * prep_cif.c (ffi_prep_cif): Changed values from void* to void**.
+ (initialize_aggregate): Fixed aggregate type initialization.
+
+ * Makefile.am (EXTRA_DIST): Added support code for "make dist".
+ * Makefile.in: Regenerated.
+
+Wed Oct 2 11:41:57 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * debug.c, prep_cif: Created.
+
+ * Makefile.am: Added debug.o and prep_cif.o to OBJ.
+ * Makefile.in: Regenerated.
+
+ * Makefile.am (INCLUDES): Added missing -I../include
+ * Makefile.in: Regenerated.
+
+Tue Oct 1 17:11:51 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * error.c, Makefile.am: Created.
+ * Makefile.in: Generated.
+
+--- libffi/src/x86 --------------------------------------------------------
+
+Sun Oct 4 16:27:17 1998 Anthony Green <green@cygnus.com>
+
+ * sysv.S (retlongdouble): Fixed long long return value support.
+ * ffi.c (ffi_prep_cif_machdep): Ditto.
+
+Wed May 13 04:30:33 1998 Anthony Green <green@raft.ppp.tsoft.net>
+
+ * ffi.c (ffi_prep_cif_machdep): Fixed long double return value
+ support.
+
+Wed Apr 15 08:43:20 1998 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.c (ffi_prep_args): small struct support was missing.
+
+Thu May 8 16:53:58 1997 Anthony Green <green@hoser.cygnus.com>
+
+ * objects.mak: Removed.
+
+Mon Dec 2 15:12:58 1996 Tom Tromey <tromey@cygnus.com>
+
+ * sysv.S: Use .balign, for a.out Linux boxes.
+
+Tue Oct 15 13:06:50 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.c: Clean up based on LCLint output.
+ Added funny /*@...@*/ comments to annotate source.
+
+Fri Oct 11 16:43:38 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.c (ffi_call): Added assertion for bad ABIs.
+
+Wed Oct 9 13:57:27 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * sysv.S (retdouble): Fixed double return problems.
+
+ * ffi.c (ffi_call): Corrected fn arg definition.
+ (ffi_prep_cif_machdep): Fixed double return problems
+
+Tue Oct 8 12:12:49 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.c: Moved ffi_type definitions to types.c.
+ (ffi_prep_args): Fixed type promotion bug.
+
+Mon Oct 7 15:53:06 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.c (FFI_*_TYPEDEF): Removed redundant ';'
+
+Fri Oct 4 09:54:53 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.c (ffi_call): Removed FFI_ABI arg, and swapped
+ remaining args.
+
+Wed Oct 2 10:07:05 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.c, sysv.S, objects.mak: Created.
+ (ffi_prep_cif): cif->rvalue no longer initialized to NULL.
+ (ffi_prep_cif_machdep): Moved machine independent cif processing
+ to src/prep_cif.c. Introduced ffi_prep_cif_machdep().
+
+--- libffi/src/mips -------------------------------------------------------
+
+Tue Feb 17 17:18:07 1998 Anthony Green <green@hoser.cygnus.com>
+
+ * o32.S: Fixed typo in comment.
+
+ * ffi.c (ffi_prep_cif_machdep): Fixed argument processing.
+
+Thu May 8 16:53:58 1997 Anthony Green <green@hoser.cygnus.com>
+
+ * o32.s, n32.s: Wrappers for SGI tool support.
+
+ * objects.mak: Removed.
+
+Tue Oct 29 14:37:45 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.c (ffi_prep_args): Changed int z to size_t z.
+
+Tue Oct 15 13:17:25 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * n32.S: Fixed bad stack munging.
+
+ * ffi.c: Moved prototypes for ffi_call_?32() to here from
+ ffi_mips.h because extended_cif is not defined in ffi_mips.h.
+
+Mon Oct 14 12:42:02 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.c: Interface changes based on feedback from Jim Blandy.
+
+Thu Oct 10 11:22:16 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * n32.S, ffi.c: Lots of changes to support passing and
+ returning structures with the n32 calling convention.
+
+ * n32.S: Fixed fn pointer bug.
+
+ * ffi.c (ffi_prep_cif_machdep): Fix for o32 structure
+ return values.
+ (ffi_prep_args): Fixed n32 structure passing when structures
+ partially fit in registers.
+
+Wed Oct 9 13:49:25 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * objects.mak: Added n32.o.
+
+ * n32.S: Created.
+
+ * ffi.c (ffi_prep_args): Added magic to support proper
+ n32 processing.
+
+Tue Oct 8 10:37:35 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.c: Moved ffi_type definitions to types.c.
+ (ffi_prep_args): Fixed type promotion bug.
+
+ * o32.S: This code is only built for o32 compiles.
+ A lot of the #define cruft has moved to ffi_mips.h.
+
+ * ffi.c (ffi_prep_cif_machdep): Fixed arg flags. Second arg
+ is only processed if the first is either a float or double.
+
+Mon Oct 7 15:33:59 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * o32.S: Modified to compile under each of o32, n32 and n64.
+
+ * ffi.c (FFI_*_TYPEDEF): Removed redundant ';'
+
+Fri Oct 4 09:53:25 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.c (ffi_call): Removed FFI_ABI arg, and swapped
+ remaining args.
+
+Wed Oct 2 17:41:22 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * o32.S: Removed crufty definitions.
+
+Wed Oct 2 12:53:42 1996 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.c (ffi_prep_cif): cif->rvalue no longer initialized to NULL.
+ (ffi_prep_cif_machdep): Moved all machine independent cif processing
+ to src/prep_cif.c. Introduced ffi_prep_cif_machdep. Return types
+ of FFI_TYPE_STRUCT are no different than FFI_TYPE_INT.
+
+Tue Oct 1 17:11:02 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.c, o32.S, object.mak: Created
+
+--- libffi/src/sparc ------------------------------------------------------
+
+Tue Feb 24 16:33:18 1998 Anthony Green <green@hoser.cygnus.com>
+
+ * ffi.c (ffi_prep_args): Added long double support.
+
+Thu May 8 16:53:58 1997 Anthony Green <green@hoser.cygnus.com>
+
+ * objects.mak: Removed.
+
+Thu May 1 16:07:56 1997 Anthony Green <green@hoser.cygnus.com>
+
+ * v8.S: Fixed minor portability problem reported by
+ Russ McManus <mcmanr@eq.gs.com>.
+
+Tue Nov 26 14:12:43 1996 Anthony Green <green@csk3.cygnus.com>
+
+ * v8.S: Used STACKFRAME define elsewhere.
+
+ * ffi.c (ffi_prep_args): Zero out space when USING_PURIFY
+ is set.
+ (ffi_prep_cif_machdep): Allocate the correct stack frame
+ space for functions with < 6 args.
+
+Tue Oct 29 15:08:55 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.c (ffi_prep_args): int z is now size_t z.
+
+Mon Oct 14 13:31:24 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * v8.S (ffi_call_V8): Gordon rewrites this again. It looks
+ great now.
+
+ * ffi.c (ffi_call): The comment about hijacked registers
+ is no longer valid after gordoni hacked v8.S.
+
+ * v8.S (ffi_call_V8): Rewrote with gordoni. Much simpler.
+
+ * v8.S, ffi.c: ffi_call() had changed to accept more than
+ two args, so v8.S had to change (because it hijacks incoming
+ arg registers).
+
+ * ffi.c: Interface changes based on feedback from Jim Blandy.
+
+Thu Oct 10 17:48:16 1996 Anthony Green <green@rtl.cygnus.com>
+
+ * ffi.c, v8.S, objects.mak: Created.
+
+
diff --git a/contrib/restricted/libffi/LICENSE b/contrib/restricted/libffi/LICENSE
index 38225e65ce..acb2f7a07d 100644
--- a/contrib/restricted/libffi/LICENSE
+++ b/contrib/restricted/libffi/LICENSE
@@ -1,21 +1,21 @@
-libffi - Copyright (c) 1996-2019 Anthony Green, Red Hat, Inc and others.
-See source files for details.
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-``Software''), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+libffi - Copyright (c) 1996-2019 Anthony Green, Red Hat, Inc and others.
+See source files for details.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+``Software''), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/contrib/restricted/libffi/LICENSE-BUILDTOOLS b/contrib/restricted/libffi/LICENSE-BUILDTOOLS
index 192ae10cfa..d1d626e008 100644
--- a/contrib/restricted/libffi/LICENSE-BUILDTOOLS
+++ b/contrib/restricted/libffi/LICENSE-BUILDTOOLS
@@ -1,353 +1,353 @@
-The libffi source distribution contains certain code that is not part
-of libffi, and is only used as tooling to assist with the building and
-testing of libffi. This includes the msvcc.sh script used to wrap the
-Microsoft compiler with GNU compatible command-line options,
-make_sunver.pl, and the libffi test code distributed in the
-testsuite/libffi.bhaible directory. This code is distributed with
-libffi for the purpose of convenience only, and libffi is in no way
-derived from this code.
-
-msvcc.sh an testsuite/libffi.bhaible are both distributed under the
-terms of the GNU GPL version 2, as below.
-
-
-
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 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.
-
- 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 Lesser 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 Street, 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 Lesser General
-Public License instead of this License.
+The libffi source distribution contains certain code that is not part
+of libffi, and is only used as tooling to assist with the building and
+testing of libffi. This includes the msvcc.sh script used to wrap the
+Microsoft compiler with GNU compatible command-line options,
+make_sunver.pl, and the libffi test code distributed in the
+testsuite/libffi.bhaible directory. This code is distributed with
+libffi for the purpose of convenience only, and libffi is in no way
+derived from this code.
+
+msvcc.sh an testsuite/libffi.bhaible are both distributed under the
+terms of the GNU GPL version 2, as below.
+
+
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 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.
+
+ 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 Lesser 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 Street, 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 Lesser General
+Public License instead of this License.
diff --git a/contrib/restricted/libffi/README.md b/contrib/restricted/libffi/README.md
index c3da3ad41d..737fd41e68 100644
--- a/contrib/restricted/libffi/README.md
+++ b/contrib/restricted/libffi/README.md
@@ -1,472 +1,472 @@
-
-libffi-3.3 was released on November 23, 2019. Check the libffi web
-page for updates: <URL:http://sourceware.org/libffi/>.
-
-
-What is libffi?
-===============
-
-Compilers for high level languages generate code that follow certain
-conventions. These conventions are necessary, in part, for separate
-compilation to work. One such convention is the "calling
-convention". The "calling convention" is essentially a set of
-assumptions made by the compiler about where function arguments will
-be found on entry to a function. A "calling convention" also specifies
-where the return value for a function is found.
-
-Some programs may not know at the time of compilation what arguments
-are to be passed to a function. For instance, an interpreter may be
-told at run-time about the number and types of arguments used to call
-a given function. Libffi can be used in such programs to provide a
-bridge from the interpreter program to compiled code.
-
-The libffi library provides a portable, high level programming
-interface to various calling conventions. This allows a programmer to
-call any function specified by a call interface description at run
-time.
-
-FFI stands for Foreign Function Interface. A foreign function
-interface is the popular name for the interface that allows code
-written in one language to call code written in another language. The
-libffi library really only provides the lowest, machine dependent
-layer of a fully featured foreign function interface. A layer must
-exist above libffi that handles type conversions for values passed
-between the two languages.
-
-
-Supported Platforms
-===================
-
-Libffi has been ported to many different platforms.
-
-At the time of release, the following basic configurations have been
-tested:
-
-| Architecture | Operating System | Compiler |
-| --------------- | ---------------- | ----------------------- |
-| AArch64 (ARM64) | iOS | Clang |
-| AArch64 | Linux | GCC |
-| AArch64 | Windows | MSVC |
-| Alpha | Linux | GCC |
-| Alpha | Tru64 | GCC |
-| ARC | Linux | GCC |
-| ARM | Linux | GCC |
-| ARM | iOS | GCC |
-| ARM | Windows | MSVC |
-| AVR32 | Linux | GCC |
-| Blackfin | uClinux | GCC |
-| HPPA | HPUX | GCC |
-| IA-64 | Linux | GCC |
-| M68K | FreeMiNT | GCC |
-| M68K | Linux | GCC |
-| M68K | RTEMS | GCC |
-| M88K | OpenBSD/mvme88k | GCC |
-| Meta | Linux | GCC |
-| MicroBlaze | Linux | GCC |
-| MIPS | IRIX | GCC |
-| MIPS | Linux | GCC |
-| MIPS | RTEMS | GCC |
-| MIPS64 | Linux | GCC |
-| Moxie | Bare metal | GCC |
-| Nios II | Linux | GCC |
-| OpenRISC | Linux | GCC |
-| PowerPC 32-bit | AIX | IBM XL C |
-| PowerPC 64-bit | AIX | IBM XL C |
-| PowerPC | AMIGA | GCC |
-| PowerPC | Linux | GCC |
-| PowerPC | Mac OSX | GCC |
-| PowerPC | FreeBSD | GCC |
-| PowerPC 64-bit | FreeBSD | GCC |
-| PowerPC 64-bit | Linux ELFv1 | GCC |
-| PowerPC 64-bit | Linux ELFv2 | GCC |
-| RISC-V 32-bit | Linux | GCC |
-| RISC-V 64-bit | Linux | GCC |
-| S390 | Linux | GCC |
-| S390X | Linux | GCC |
-| SPARC | Linux | GCC |
-| SPARC | Solaris | GCC |
-| SPARC | Solaris | Oracle Solaris Studio C |
-| SPARC64 | Linux | GCC |
-| SPARC64 | FreeBSD | GCC |
-| SPARC64 | Solaris | Oracle Solaris Studio C |
-| TILE-Gx/TILEPro | Linux | GCC |
-| VAX | OpenBSD/vax | GCC |
-| X86 | FreeBSD | GCC |
-| X86 | GNU HURD | GCC |
-| X86 | Interix | GCC |
-| X86 | kFreeBSD | GCC |
-| X86 | Linux | GCC |
-| X86 | Mac OSX | GCC |
-| X86 | OpenBSD | GCC |
-| X86 | OS/2 | GCC |
-| X86 | Solaris | GCC |
-| X86 | Solaris | Oracle Solaris Studio C |
-| X86 | Windows/Cygwin | GCC |
-| X86 | Windows/MingW | GCC |
-| X86-64 | FreeBSD | GCC |
-| X86-64 | Linux | GCC |
-| X86-64 | Linux/x32 | GCC |
-| X86-64 | OpenBSD | GCC |
-| X86-64 | Solaris | Oracle Solaris Studio C |
-| X86-64 | Windows/Cygwin | GCC |
-| X86-64 | Windows/MingW | GCC |
-| X86-64 | Mac OSX | GCC |
-| Xtensa | Linux | GCC |
-
-Please send additional platform test results to
-libffi-discuss@sourceware.org.
-
-Installing libffi
-=================
-
-First you must configure the distribution for your particular
-system. Go to the directory you wish to build libffi in and run the
-"configure" program found in the root directory of the libffi source
-distribution. Note that building libffi requires a C99 compatible
-compiler.
-
-If you're building libffi directly from git hosted sources, configure
-won't exist yet; run ./autogen.sh first. This will require that you
-install autoconf, automake and libtool.
-
-You may want to tell configure where to install the libffi library and
-header files. To do that, use the ``--prefix`` configure switch. Libffi
-will install under /usr/local by default.
-
-If you want to enable extra run-time debugging checks use the the
-``--enable-debug`` configure switch. This is useful when your program dies
-mysteriously while using libffi.
-
-Another useful configure switch is ``--enable-purify-safety``. Using this
-will add some extra code which will suppress certain warnings when you
-are using Purify with libffi. Only use this switch when using
-Purify, as it will slow down the library.
-
-If you don't want to build documentation, use the ``--disable-docs``
-configure switch.
-
-It's also possible to build libffi on Windows platforms with
-Microsoft's Visual C++ compiler. In this case, use the msvcc.sh
-wrapper script during configuration like so:
-
- path/to/configure CC=path/to/msvcc.sh CXX=path/to/msvcc.sh LD=link CPP="cl -nologo -EP" CPPFLAGS="-DFFI_BUILDING_DLL"
-
-For 64-bit Windows builds, use ``CC="path/to/msvcc.sh -m64"`` and
-``CXX="path/to/msvcc.sh -m64"``. You may also need to specify
-``--build`` appropriately.
-
-It is also possible to build libffi on Windows platforms with the LLVM
-project's clang-cl compiler, like below:
-
- path/to/configure CC="path/to/msvcc.sh -clang-cl" CXX="path/to/msvcc.sh -clang-cl" LD=link CPP="clang-cl -EP"
-
-When building with MSVC under a MingW environment, you may need to
-remove the line in configure that sets 'fix_srcfile_path' to a 'cygpath'
-command. ('cygpath' is not present in MingW, and is not required when
-using MingW-style paths.)
-
-To build static library for ARM64 with MSVC using visual studio solution, msvc_build folder have
- aarch64/Ffi_staticLib.sln
- required header files in aarch64/aarch64_include/
-
-
-SPARC Solaris builds require the use of the GNU assembler and linker.
-Point ``AS`` and ``LD`` environment variables at those tool prior to
-configuration.
-
-For iOS builds, the ``libffi.xcodeproj`` Xcode project is available.
-
-Configure has many other options. Use ``configure --help`` to see them all.
-
-Once configure has finished, type "make". Note that you must be using
-GNU make. You can ftp GNU make from ftp.gnu.org:/pub/gnu/make .
-
-To ensure that libffi is working as advertised, type "make check".
-This will require that you have DejaGNU installed.
-
-To install the library and header files, type ``make install``.
-
-
-History
-=======
-
-See the git log for details at http://github.com/libffi/libffi.
-
- 3.3 Nov-23-19
- Add RISC-V support.
- New API in support of GO closures.
- Add IEEE754 binary128 long double support for 64-bit Power
- Default to Microsoft's 64 bit long double ABI with Visual C++.
- GNU compiler uses 80 bits (128 in memory) FFI_GNUW64 ABI.
- Add Windows on ARM64 (WOA) support.
- Add Windows 32-bit ARM support.
- Raw java (gcj) API deprecated.
- Add pre-built PDF documentation to source distribution.
- Many new tests cases and bug fixes.
-
- 3.2.1 Nov-12-14
- Build fix for non-iOS AArch64 targets.
-
- 3.2 Nov-11-14
- Add C99 Complex Type support (currently only supported on
- s390).
- Add support for PASCAL and REGISTER calling conventions on x86
- Windows/Linux.
- Add OpenRISC and Cygwin-64 support.
- Bug fixes.
-
- 3.1 May-19-14
- Add AArch64 (ARM64) iOS support.
- Add Nios II support.
- Add m88k and DEC VAX support.
- Add support for stdcall, thiscall, and fastcall on non-Windows
- 32-bit x86 targets such as Linux.
- Various Android, MIPS N32, x86, FreeBSD and UltraSPARC IIi
- fixes.
- Make the testsuite more robust: eliminate several spurious
- failures, and respect the $CC and $CXX environment variables.
- Archive off the manually maintained ChangeLog in favor of git
- log.
-
- 3.0.13 Mar-17-13
- Add Meta support.
- Add missing Moxie bits.
- Fix stack alignment bug on 32-bit x86.
- Build fix for m68000 targets.
- Build fix for soft-float Power targets.
- Fix the install dir location for some platforms when building
- with GCC (OS X, Solaris).
- Fix Cygwin regression.
-
- 3.0.12 Feb-11-13
- Add Moxie support.
- Add AArch64 support.
- Add Blackfin support.
- Add TILE-Gx/TILEPro support.
- Add MicroBlaze support.
- Add Xtensa support.
- Add support for PaX enabled kernels with MPROTECT.
- Add support for native vendor compilers on
- Solaris and AIX.
- Work around LLVM/GCC interoperability issue on x86_64.
-
- 3.0.11 Apr-11-12
- Lots of build fixes.
- Add support for variadic functions (ffi_prep_cif_var).
- Add Linux/x32 support.
- Add thiscall, fastcall and MSVC cdecl support on Windows.
- Add Amiga and newer MacOS support.
- Add m68k FreeMiNT support.
- Integration with iOS' xcode build tools.
- Fix Octeon and MC68881 support.
- Fix code pessimizations.
-
- 3.0.10 Aug-23-11
- Add support for Apple's iOS.
- Add support for ARM VFP ABI.
- Add RTEMS support for MIPS and M68K.
- Fix instruction cache clearing problems on
- ARM and SPARC.
- Fix the N64 build on mips-sgi-irix6.5.
- Enable builds with Microsoft's compiler.
- Enable x86 builds with Oracle's Solaris compiler.
- Fix support for calling code compiled with Oracle's Sparc
- Solaris compiler.
- Testsuite fixes for Tru64 Unix.
- Additional platform support.
-
- 3.0.9 Dec-31-09
- Add AVR32 and win64 ports. Add ARM softfp support.
- Many fixes for AIX, Solaris, HP-UX, *BSD.
- Several PowerPC and x86-64 bug fixes.
- Build DLL for windows.
-
- 3.0.8 Dec-19-08
- Add *BSD, BeOS, and PA-Linux support.
-
- 3.0.7 Nov-11-08
- Fix for ppc FreeBSD.
- (thanks to Andreas Tobler)
-
- 3.0.6 Jul-17-08
- Fix for closures on sh.
- Mark the sh/sh64 stack as non-executable.
- (both thanks to Kaz Kojima)
-
- 3.0.5 Apr-3-08
- Fix libffi.pc file.
- Fix #define ARM for IcedTea users.
- Fix x86 closure bug.
-
- 3.0.4 Feb-24-08
- Fix x86 OpenBSD configury.
-
- 3.0.3 Feb-22-08
- Enable x86 OpenBSD thanks to Thomas Heller, and
- x86-64 FreeBSD thanks to Björn König and Andreas Tobler.
- Clean up test instruction in README.
-
- 3.0.2 Feb-21-08
- Improved x86 FreeBSD support.
- Thanks to Björn König.
-
- 3.0.1 Feb-15-08
- Fix instruction cache flushing bug on MIPS.
- Thanks to David Daney.
-
- 3.0.0 Feb-15-08
- Many changes, mostly thanks to the GCC project.
- Cygnus Solutions is now Red Hat.
-
- [10 years go by...]
-
- 1.20 Oct-5-98
- Raffaele Sena produces ARM port.
-
- 1.19 Oct-5-98
- Fixed x86 long double and long long return support.
- m68k bug fixes from Andreas Schwab.
- Patch for DU assembler compatibility for the Alpha from Richard
- Henderson.
-
- 1.18 Apr-17-98
- Bug fixes and MIPS configuration changes.
-
- 1.17 Feb-24-98
- Bug fixes and m68k port from Andreas Schwab. PowerPC port from
- Geoffrey Keating. Various bug x86, Sparc and MIPS bug fixes.
-
- 1.16 Feb-11-98
- Richard Henderson produces Alpha port.
-
- 1.15 Dec-4-97
- Fixed an n32 ABI bug. New libtool, auto* support.
-
- 1.14 May-13-97
- libtool is now used to generate shared and static libraries.
- Fixed a minor portability problem reported by Russ McManus
- <mcmanr@eq.gs.com>.
-
- 1.13 Dec-2-96
- Added --enable-purify-safety to keep Purify from complaining
- about certain low level code.
- Sparc fix for calling functions with < 6 args.
- Linux x86 a.out fix.
-
- 1.12 Nov-22-96
- Added missing ffi_type_void, needed for supporting void return
- types. Fixed test case for non MIPS machines. Cygnus Support
- is now Cygnus Solutions.
-
- 1.11 Oct-30-96
- Added notes about GNU make.
-
- 1.10 Oct-29-96
- Added configuration fix for non GNU compilers.
-
- 1.09 Oct-29-96
- Added --enable-debug configure switch. Clean-ups based on LCLint
- feedback. ffi_mips.h is always installed. Many configuration
- fixes. Fixed ffitest.c for sparc builds.
-
- 1.08 Oct-15-96
- Fixed n32 problem. Many clean-ups.
-
- 1.07 Oct-14-96
- Gordon Irlam rewrites v8.S again. Bug fixes.
-
- 1.06 Oct-14-96
- Gordon Irlam improved the sparc port.
-
- 1.05 Oct-14-96
- Interface changes based on feedback.
-
- 1.04 Oct-11-96
- Sparc port complete (modulo struct passing bug).
-
- 1.03 Oct-10-96
- Passing struct args, and returning struct values works for
- all architectures/calling conventions. Expanded tests.
-
- 1.02 Oct-9-96
- Added SGI n32 support. Fixed bugs in both o32 and Linux support.
- Added "make test".
-
- 1.01 Oct-8-96
- Fixed float passing bug in mips version. Restructured some
- of the code. Builds cleanly with SGI tools.
-
- 1.00 Oct-7-96
- First release. No public announcement.
-
-Authors & Credits
-=================
-
-libffi was originally written by Anthony Green <green@moxielogic.com>.
-
-The developers of the GNU Compiler Collection project have made
-innumerable valuable contributions. See the ChangeLog file for
-details.
-
-Some of the ideas behind libffi were inspired by Gianni Mariani's free
-gencall library for Silicon Graphics machines.
-
-The closure mechanism was designed and implemented by Kresten Krab
-Thorup.
-
-Major processor architecture ports were contributed by the following
-developers:
-
- aarch64 Marcus Shawcroft, James Greenhalgh
- alpha Richard Henderson
- arc Hackers at Synopsis
- arm Raffaele Sena
- avr32 Bradley Smith
- blackfin Alexandre Keunecke I. de Mendonca
- cris Simon Posnjak, Hans-Peter Nilsson
- frv Anthony Green
- ia64 Hans Boehm
- m32r Kazuhiro Inaoka
- m68k Andreas Schwab
- m88k Miod Vallat
- metag Hackers at Imagination Technologies
- microblaze Nathan Rossi
- mips Anthony Green, Casey Marshall
- mips64 David Daney
- moxie Anthony Green
- nios ii Sandra Loosemore
- openrisc Sebastian Macke
- pa Randolph Chung, Dave Anglin, Andreas Tobler
- powerpc Geoffrey Keating, Andreas Tobler,
- David Edelsohn, John Hornkvist
- powerpc64 Jakub Jelinek
- riscv Michael Knyszek, Andrew Waterman, Stef O'Rear
- s390 Gerhard Tonn, Ulrich Weigand
- sh Kaz Kojima
- sh64 Kaz Kojima
- sparc Anthony Green, Gordon Irlam
- tile-gx/tilepro Walter Lee
- vax Miod Vallat
- x86 Anthony Green, Jon Beniston
- x86-64 Bo Thorsen
- xtensa Chris Zankel
-
-Jesper Skov and Andrew Haley both did more than their fair share of
-stepping through the code and tracking down bugs.
-
-Thanks also to Tom Tromey for bug fixes, documentation and
-configuration help.
-
-Thanks to Jim Blandy, who provided some useful feedback on the libffi
-interface.
-
-Andreas Tobler has done a tremendous amount of work on the testsuite.
-
-Alex Oliva solved the executable page problem for SElinux.
-
-The list above is almost certainly incomplete and inaccurate. I'm
-happy to make corrections or additions upon request.
-
-If you have a problem, or have found a bug, please send a note to the
-author at green@moxielogic.com, or the project mailing list at
-libffi-discuss@sourceware.org.
+
+libffi-3.3 was released on November 23, 2019. Check the libffi web
+page for updates: <URL:http://sourceware.org/libffi/>.
+
+
+What is libffi?
+===============
+
+Compilers for high level languages generate code that follow certain
+conventions. These conventions are necessary, in part, for separate
+compilation to work. One such convention is the "calling
+convention". The "calling convention" is essentially a set of
+assumptions made by the compiler about where function arguments will
+be found on entry to a function. A "calling convention" also specifies
+where the return value for a function is found.
+
+Some programs may not know at the time of compilation what arguments
+are to be passed to a function. For instance, an interpreter may be
+told at run-time about the number and types of arguments used to call
+a given function. Libffi can be used in such programs to provide a
+bridge from the interpreter program to compiled code.
+
+The libffi library provides a portable, high level programming
+interface to various calling conventions. This allows a programmer to
+call any function specified by a call interface description at run
+time.
+
+FFI stands for Foreign Function Interface. A foreign function
+interface is the popular name for the interface that allows code
+written in one language to call code written in another language. The
+libffi library really only provides the lowest, machine dependent
+layer of a fully featured foreign function interface. A layer must
+exist above libffi that handles type conversions for values passed
+between the two languages.
+
+
+Supported Platforms
+===================
+
+Libffi has been ported to many different platforms.
+
+At the time of release, the following basic configurations have been
+tested:
+
+| Architecture | Operating System | Compiler |
+| --------------- | ---------------- | ----------------------- |
+| AArch64 (ARM64) | iOS | Clang |
+| AArch64 | Linux | GCC |
+| AArch64 | Windows | MSVC |
+| Alpha | Linux | GCC |
+| Alpha | Tru64 | GCC |
+| ARC | Linux | GCC |
+| ARM | Linux | GCC |
+| ARM | iOS | GCC |
+| ARM | Windows | MSVC |
+| AVR32 | Linux | GCC |
+| Blackfin | uClinux | GCC |
+| HPPA | HPUX | GCC |
+| IA-64 | Linux | GCC |
+| M68K | FreeMiNT | GCC |
+| M68K | Linux | GCC |
+| M68K | RTEMS | GCC |
+| M88K | OpenBSD/mvme88k | GCC |
+| Meta | Linux | GCC |
+| MicroBlaze | Linux | GCC |
+| MIPS | IRIX | GCC |
+| MIPS | Linux | GCC |
+| MIPS | RTEMS | GCC |
+| MIPS64 | Linux | GCC |
+| Moxie | Bare metal | GCC |
+| Nios II | Linux | GCC |
+| OpenRISC | Linux | GCC |
+| PowerPC 32-bit | AIX | IBM XL C |
+| PowerPC 64-bit | AIX | IBM XL C |
+| PowerPC | AMIGA | GCC |
+| PowerPC | Linux | GCC |
+| PowerPC | Mac OSX | GCC |
+| PowerPC | FreeBSD | GCC |
+| PowerPC 64-bit | FreeBSD | GCC |
+| PowerPC 64-bit | Linux ELFv1 | GCC |
+| PowerPC 64-bit | Linux ELFv2 | GCC |
+| RISC-V 32-bit | Linux | GCC |
+| RISC-V 64-bit | Linux | GCC |
+| S390 | Linux | GCC |
+| S390X | Linux | GCC |
+| SPARC | Linux | GCC |
+| SPARC | Solaris | GCC |
+| SPARC | Solaris | Oracle Solaris Studio C |
+| SPARC64 | Linux | GCC |
+| SPARC64 | FreeBSD | GCC |
+| SPARC64 | Solaris | Oracle Solaris Studio C |
+| TILE-Gx/TILEPro | Linux | GCC |
+| VAX | OpenBSD/vax | GCC |
+| X86 | FreeBSD | GCC |
+| X86 | GNU HURD | GCC |
+| X86 | Interix | GCC |
+| X86 | kFreeBSD | GCC |
+| X86 | Linux | GCC |
+| X86 | Mac OSX | GCC |
+| X86 | OpenBSD | GCC |
+| X86 | OS/2 | GCC |
+| X86 | Solaris | GCC |
+| X86 | Solaris | Oracle Solaris Studio C |
+| X86 | Windows/Cygwin | GCC |
+| X86 | Windows/MingW | GCC |
+| X86-64 | FreeBSD | GCC |
+| X86-64 | Linux | GCC |
+| X86-64 | Linux/x32 | GCC |
+| X86-64 | OpenBSD | GCC |
+| X86-64 | Solaris | Oracle Solaris Studio C |
+| X86-64 | Windows/Cygwin | GCC |
+| X86-64 | Windows/MingW | GCC |
+| X86-64 | Mac OSX | GCC |
+| Xtensa | Linux | GCC |
+
+Please send additional platform test results to
+libffi-discuss@sourceware.org.
+
+Installing libffi
+=================
+
+First you must configure the distribution for your particular
+system. Go to the directory you wish to build libffi in and run the
+"configure" program found in the root directory of the libffi source
+distribution. Note that building libffi requires a C99 compatible
+compiler.
+
+If you're building libffi directly from git hosted sources, configure
+won't exist yet; run ./autogen.sh first. This will require that you
+install autoconf, automake and libtool.
+
+You may want to tell configure where to install the libffi library and
+header files. To do that, use the ``--prefix`` configure switch. Libffi
+will install under /usr/local by default.
+
+If you want to enable extra run-time debugging checks use the the
+``--enable-debug`` configure switch. This is useful when your program dies
+mysteriously while using libffi.
+
+Another useful configure switch is ``--enable-purify-safety``. Using this
+will add some extra code which will suppress certain warnings when you
+are using Purify with libffi. Only use this switch when using
+Purify, as it will slow down the library.
+
+If you don't want to build documentation, use the ``--disable-docs``
+configure switch.
+
+It's also possible to build libffi on Windows platforms with
+Microsoft's Visual C++ compiler. In this case, use the msvcc.sh
+wrapper script during configuration like so:
+
+ path/to/configure CC=path/to/msvcc.sh CXX=path/to/msvcc.sh LD=link CPP="cl -nologo -EP" CPPFLAGS="-DFFI_BUILDING_DLL"
+
+For 64-bit Windows builds, use ``CC="path/to/msvcc.sh -m64"`` and
+``CXX="path/to/msvcc.sh -m64"``. You may also need to specify
+``--build`` appropriately.
+
+It is also possible to build libffi on Windows platforms with the LLVM
+project's clang-cl compiler, like below:
+
+ path/to/configure CC="path/to/msvcc.sh -clang-cl" CXX="path/to/msvcc.sh -clang-cl" LD=link CPP="clang-cl -EP"
+
+When building with MSVC under a MingW environment, you may need to
+remove the line in configure that sets 'fix_srcfile_path' to a 'cygpath'
+command. ('cygpath' is not present in MingW, and is not required when
+using MingW-style paths.)
+
+To build static library for ARM64 with MSVC using visual studio solution, msvc_build folder have
+ aarch64/Ffi_staticLib.sln
+ required header files in aarch64/aarch64_include/
+
+
+SPARC Solaris builds require the use of the GNU assembler and linker.
+Point ``AS`` and ``LD`` environment variables at those tool prior to
+configuration.
+
+For iOS builds, the ``libffi.xcodeproj`` Xcode project is available.
+
+Configure has many other options. Use ``configure --help`` to see them all.
+
+Once configure has finished, type "make". Note that you must be using
+GNU make. You can ftp GNU make from ftp.gnu.org:/pub/gnu/make .
+
+To ensure that libffi is working as advertised, type "make check".
+This will require that you have DejaGNU installed.
+
+To install the library and header files, type ``make install``.
+
+
+History
+=======
+
+See the git log for details at http://github.com/libffi/libffi.
+
+ 3.3 Nov-23-19
+ Add RISC-V support.
+ New API in support of GO closures.
+ Add IEEE754 binary128 long double support for 64-bit Power
+ Default to Microsoft's 64 bit long double ABI with Visual C++.
+ GNU compiler uses 80 bits (128 in memory) FFI_GNUW64 ABI.
+ Add Windows on ARM64 (WOA) support.
+ Add Windows 32-bit ARM support.
+ Raw java (gcj) API deprecated.
+ Add pre-built PDF documentation to source distribution.
+ Many new tests cases and bug fixes.
+
+ 3.2.1 Nov-12-14
+ Build fix for non-iOS AArch64 targets.
+
+ 3.2 Nov-11-14
+ Add C99 Complex Type support (currently only supported on
+ s390).
+ Add support for PASCAL and REGISTER calling conventions on x86
+ Windows/Linux.
+ Add OpenRISC and Cygwin-64 support.
+ Bug fixes.
+
+ 3.1 May-19-14
+ Add AArch64 (ARM64) iOS support.
+ Add Nios II support.
+ Add m88k and DEC VAX support.
+ Add support for stdcall, thiscall, and fastcall on non-Windows
+ 32-bit x86 targets such as Linux.
+ Various Android, MIPS N32, x86, FreeBSD and UltraSPARC IIi
+ fixes.
+ Make the testsuite more robust: eliminate several spurious
+ failures, and respect the $CC and $CXX environment variables.
+ Archive off the manually maintained ChangeLog in favor of git
+ log.
+
+ 3.0.13 Mar-17-13
+ Add Meta support.
+ Add missing Moxie bits.
+ Fix stack alignment bug on 32-bit x86.
+ Build fix for m68000 targets.
+ Build fix for soft-float Power targets.
+ Fix the install dir location for some platforms when building
+ with GCC (OS X, Solaris).
+ Fix Cygwin regression.
+
+ 3.0.12 Feb-11-13
+ Add Moxie support.
+ Add AArch64 support.
+ Add Blackfin support.
+ Add TILE-Gx/TILEPro support.
+ Add MicroBlaze support.
+ Add Xtensa support.
+ Add support for PaX enabled kernels with MPROTECT.
+ Add support for native vendor compilers on
+ Solaris and AIX.
+ Work around LLVM/GCC interoperability issue on x86_64.
+
+ 3.0.11 Apr-11-12
+ Lots of build fixes.
+ Add support for variadic functions (ffi_prep_cif_var).
+ Add Linux/x32 support.
+ Add thiscall, fastcall and MSVC cdecl support on Windows.
+ Add Amiga and newer MacOS support.
+ Add m68k FreeMiNT support.
+ Integration with iOS' xcode build tools.
+ Fix Octeon and MC68881 support.
+ Fix code pessimizations.
+
+ 3.0.10 Aug-23-11
+ Add support for Apple's iOS.
+ Add support for ARM VFP ABI.
+ Add RTEMS support for MIPS and M68K.
+ Fix instruction cache clearing problems on
+ ARM and SPARC.
+ Fix the N64 build on mips-sgi-irix6.5.
+ Enable builds with Microsoft's compiler.
+ Enable x86 builds with Oracle's Solaris compiler.
+ Fix support for calling code compiled with Oracle's Sparc
+ Solaris compiler.
+ Testsuite fixes for Tru64 Unix.
+ Additional platform support.
+
+ 3.0.9 Dec-31-09
+ Add AVR32 and win64 ports. Add ARM softfp support.
+ Many fixes for AIX, Solaris, HP-UX, *BSD.
+ Several PowerPC and x86-64 bug fixes.
+ Build DLL for windows.
+
+ 3.0.8 Dec-19-08
+ Add *BSD, BeOS, and PA-Linux support.
+
+ 3.0.7 Nov-11-08
+ Fix for ppc FreeBSD.
+ (thanks to Andreas Tobler)
+
+ 3.0.6 Jul-17-08
+ Fix for closures on sh.
+ Mark the sh/sh64 stack as non-executable.
+ (both thanks to Kaz Kojima)
+
+ 3.0.5 Apr-3-08
+ Fix libffi.pc file.
+ Fix #define ARM for IcedTea users.
+ Fix x86 closure bug.
+
+ 3.0.4 Feb-24-08
+ Fix x86 OpenBSD configury.
+
+ 3.0.3 Feb-22-08
+ Enable x86 OpenBSD thanks to Thomas Heller, and
+ x86-64 FreeBSD thanks to Björn König and Andreas Tobler.
+ Clean up test instruction in README.
+
+ 3.0.2 Feb-21-08
+ Improved x86 FreeBSD support.
+ Thanks to Björn König.
+
+ 3.0.1 Feb-15-08
+ Fix instruction cache flushing bug on MIPS.
+ Thanks to David Daney.
+
+ 3.0.0 Feb-15-08
+ Many changes, mostly thanks to the GCC project.
+ Cygnus Solutions is now Red Hat.
+
+ [10 years go by...]
+
+ 1.20 Oct-5-98
+ Raffaele Sena produces ARM port.
+
+ 1.19 Oct-5-98
+ Fixed x86 long double and long long return support.
+ m68k bug fixes from Andreas Schwab.
+ Patch for DU assembler compatibility for the Alpha from Richard
+ Henderson.
+
+ 1.18 Apr-17-98
+ Bug fixes and MIPS configuration changes.
+
+ 1.17 Feb-24-98
+ Bug fixes and m68k port from Andreas Schwab. PowerPC port from
+ Geoffrey Keating. Various bug x86, Sparc and MIPS bug fixes.
+
+ 1.16 Feb-11-98
+ Richard Henderson produces Alpha port.
+
+ 1.15 Dec-4-97
+ Fixed an n32 ABI bug. New libtool, auto* support.
+
+ 1.14 May-13-97
+ libtool is now used to generate shared and static libraries.
+ Fixed a minor portability problem reported by Russ McManus
+ <mcmanr@eq.gs.com>.
+
+ 1.13 Dec-2-96
+ Added --enable-purify-safety to keep Purify from complaining
+ about certain low level code.
+ Sparc fix for calling functions with < 6 args.
+ Linux x86 a.out fix.
+
+ 1.12 Nov-22-96
+ Added missing ffi_type_void, needed for supporting void return
+ types. Fixed test case for non MIPS machines. Cygnus Support
+ is now Cygnus Solutions.
+
+ 1.11 Oct-30-96
+ Added notes about GNU make.
+
+ 1.10 Oct-29-96
+ Added configuration fix for non GNU compilers.
+
+ 1.09 Oct-29-96
+ Added --enable-debug configure switch. Clean-ups based on LCLint
+ feedback. ffi_mips.h is always installed. Many configuration
+ fixes. Fixed ffitest.c for sparc builds.
+
+ 1.08 Oct-15-96
+ Fixed n32 problem. Many clean-ups.
+
+ 1.07 Oct-14-96
+ Gordon Irlam rewrites v8.S again. Bug fixes.
+
+ 1.06 Oct-14-96
+ Gordon Irlam improved the sparc port.
+
+ 1.05 Oct-14-96
+ Interface changes based on feedback.
+
+ 1.04 Oct-11-96
+ Sparc port complete (modulo struct passing bug).
+
+ 1.03 Oct-10-96
+ Passing struct args, and returning struct values works for
+ all architectures/calling conventions. Expanded tests.
+
+ 1.02 Oct-9-96
+ Added SGI n32 support. Fixed bugs in both o32 and Linux support.
+ Added "make test".
+
+ 1.01 Oct-8-96
+ Fixed float passing bug in mips version. Restructured some
+ of the code. Builds cleanly with SGI tools.
+
+ 1.00 Oct-7-96
+ First release. No public announcement.
+
+Authors & Credits
+=================
+
+libffi was originally written by Anthony Green <green@moxielogic.com>.
+
+The developers of the GNU Compiler Collection project have made
+innumerable valuable contributions. See the ChangeLog file for
+details.
+
+Some of the ideas behind libffi were inspired by Gianni Mariani's free
+gencall library for Silicon Graphics machines.
+
+The closure mechanism was designed and implemented by Kresten Krab
+Thorup.
+
+Major processor architecture ports were contributed by the following
+developers:
+
+ aarch64 Marcus Shawcroft, James Greenhalgh
+ alpha Richard Henderson
+ arc Hackers at Synopsis
+ arm Raffaele Sena
+ avr32 Bradley Smith
+ blackfin Alexandre Keunecke I. de Mendonca
+ cris Simon Posnjak, Hans-Peter Nilsson
+ frv Anthony Green
+ ia64 Hans Boehm
+ m32r Kazuhiro Inaoka
+ m68k Andreas Schwab
+ m88k Miod Vallat
+ metag Hackers at Imagination Technologies
+ microblaze Nathan Rossi
+ mips Anthony Green, Casey Marshall
+ mips64 David Daney
+ moxie Anthony Green
+ nios ii Sandra Loosemore
+ openrisc Sebastian Macke
+ pa Randolph Chung, Dave Anglin, Andreas Tobler
+ powerpc Geoffrey Keating, Andreas Tobler,
+ David Edelsohn, John Hornkvist
+ powerpc64 Jakub Jelinek
+ riscv Michael Knyszek, Andrew Waterman, Stef O'Rear
+ s390 Gerhard Tonn, Ulrich Weigand
+ sh Kaz Kojima
+ sh64 Kaz Kojima
+ sparc Anthony Green, Gordon Irlam
+ tile-gx/tilepro Walter Lee
+ vax Miod Vallat
+ x86 Anthony Green, Jon Beniston
+ x86-64 Bo Thorsen
+ xtensa Chris Zankel
+
+Jesper Skov and Andrew Haley both did more than their fair share of
+stepping through the code and tracking down bugs.
+
+Thanks also to Tom Tromey for bug fixes, documentation and
+configuration help.
+
+Thanks to Jim Blandy, who provided some useful feedback on the libffi
+interface.
+
+Andreas Tobler has done a tremendous amount of work on the testsuite.
+
+Alex Oliva solved the executable page problem for SElinux.
+
+The list above is almost certainly incomplete and inaccurate. I'm
+happy to make corrections or additions upon request.
+
+If you have a problem, or have found a bug, please send a note to the
+author at green@moxielogic.com, or the project mailing list at
+libffi-discuss@sourceware.org.
diff --git a/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/fficonfig.h b/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/fficonfig.h
index 77a69b1512..6c7c57c886 100644
--- a/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/fficonfig.h
+++ b/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "aw"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-#define FFI_EXEC_TRAMPOLINE_TABLE 1
-
-/* Define this if you want to enable pax emulated trampolines */
-/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-/* #undef FFI_MMAP_EXEC_WRIT */
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-/* #undef HAVE_AS_X86_PCREL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-/* #undef HAVE_LONG_DOUBLE */
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-#define HAVE_MKOSTEMP 1
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-/* #undef HAVE_MMAP_DEV_ZERO */
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-/* #undef HAVE_RO_EH_FRAME */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 8
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 8
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-#define SYMBOL_UNDERSCORE 1
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "aw"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+#define FFI_EXEC_TRAMPOLINE_TABLE 1
+
+/* Define this if you want to enable pax emulated trampolines */
+/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+/* #undef FFI_MMAP_EXEC_WRIT */
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+/* #undef HAVE_AS_CFI_PSEUDO_OP */
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+/* #undef HAVE_AS_X86_PCREL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+/* #undef HAVE_LONG_DOUBLE */
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+#define HAVE_MKOSTEMP 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+/* #undef HAVE_MMAP_DEV_ZERO */
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+/* #undef HAVE_RO_EH_FRAME */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 8
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+#define SYMBOL_UNDERSCORE 1
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include/ffi.h b/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include/ffi.h
index 5d12ce9895..8b35bda83c 100644
--- a/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include/ffi.h
+++ b/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef AARCH64
-#define AARCH64
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 0
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 0
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef AARCH64
+#define AARCH64
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 0
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 0
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 1
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 1
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 1
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 1
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 1
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 1
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 0
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 0
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include/ffitarget.h b/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include/ffitarget.h
index ddce8f21eb..ecb6d2deae 100644
--- a/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include/ffitarget.h
@@ -1,92 +1,92 @@
-/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-``Software''), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-#ifndef LIBFFI_ASM
-#ifdef __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef signed long long ffi_sarg;
-#elif defined(_M_ARM64)
-#define FFI_SIZEOF_ARG 8
-typedef unsigned long long ffi_arg;
-typedef signed long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-
-typedef enum ffi_abi
- {
- FFI_FIRST_ABI = 0,
- FFI_SYSV,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
- } ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_NATIVE_RAW_API 0
-
-#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#define FFI_TRAMPOLINE_SIZE 16
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET 16
-#else
-#error "No trampoline table implementation"
-#endif
-
-#else
-#define FFI_TRAMPOLINE_SIZE 24
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
-#endif
-
-#ifdef _M_ARM64
-#define FFI_EXTRA_CIF_FIELDS unsigned is_variadic
-#endif
-
-/* ---- Internal ---- */
-
-#if defined (__APPLE__)
-#define FFI_TARGET_SPECIFIC_VARIADIC
-#define FFI_EXTRA_CIF_FIELDS unsigned aarch64_nfixedargs
-#elif !defined(_M_ARM64)
-/* iOS and Windows reserve x18 for the system. Disable Go closures until
- a new static chain is chosen. */
-#define FFI_GO_CLOSURES 1
-#endif
-
-#ifndef _M_ARM64
-/* No complex type on Windows */
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-#endif
+/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+``Software''), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+#ifndef LIBFFI_ASM
+#ifdef __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef signed long long ffi_sarg;
+#elif defined(_M_ARM64)
+#define FFI_SIZEOF_ARG 8
+typedef unsigned long long ffi_arg;
+typedef signed long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+
+typedef enum ffi_abi
+ {
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+ } ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_NATIVE_RAW_API 0
+
+#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#define FFI_TRAMPOLINE_SIZE 16
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET 16
+#else
+#error "No trampoline table implementation"
+#endif
+
+#else
+#define FFI_TRAMPOLINE_SIZE 24
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
+#endif
+
+#ifdef _M_ARM64
+#define FFI_EXTRA_CIF_FIELDS unsigned is_variadic
+#endif
+
+/* ---- Internal ---- */
+
+#if defined (__APPLE__)
+#define FFI_TARGET_SPECIFIC_VARIADIC
+#define FFI_EXTRA_CIF_FIELDS unsigned aarch64_nfixedargs
+#elif !defined(_M_ARM64)
+/* iOS and Windows reserve x18 for the system. Disable Go closures until
+ a new static chain is chosen. */
+#define FFI_GO_CLOSURES 1
+#endif
+
+#ifndef _M_ARM64
+/* No complex type on Windows */
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/fficonfig.h b/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/fficonfig.h
index bd95699647..50f3985294 100644
--- a/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/fficonfig.h
+++ b/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "a"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-#define FFI_MMAP_EXEC_WRIT 1
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-/* #undef HAVE_AS_X86_PCREL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-#define HAVE_LONG_DOUBLE 1
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-/* #undef HAVE_MKOSTEMP */
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-#define HAVE_MMAP_DEV_ZERO 1
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-#define HAVE_RO_EH_FRAME 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-#define LIBFFI_GNU_SYMBOL_VERSIONING 1
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 16
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 8
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-/* #undef SYMBOL_UNDERSCORE */
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "a"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+#define FFI_MMAP_EXEC_WRIT 1
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+/* #undef HAVE_AS_CFI_PSEUDO_OP */
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+/* #undef HAVE_AS_X86_PCREL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+#define HAVE_LONG_DOUBLE 1
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+/* #undef HAVE_MKOSTEMP */
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+#define HAVE_MMAP_DEV_ZERO 1
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+#define HAVE_RO_EH_FRAME 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+#define LIBFFI_GNU_SYMBOL_VERSIONING 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 16
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+/* #undef SYMBOL_UNDERSCORE */
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include/ffi.h b/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include/ffi.h
index 8da6eab3a9..631c77ae35 100644
--- a/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include/ffi.h
+++ b/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef AARCH64
-#define AARCH64
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 1
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 1
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef AARCH64
+#define AARCH64
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 1
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 1
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 1
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 1
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include/ffitarget.h b/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include/ffitarget.h
index ddce8f21eb..ecb6d2deae 100644
--- a/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include/ffitarget.h
@@ -1,92 +1,92 @@
-/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-``Software''), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-#ifndef LIBFFI_ASM
-#ifdef __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef signed long long ffi_sarg;
-#elif defined(_M_ARM64)
-#define FFI_SIZEOF_ARG 8
-typedef unsigned long long ffi_arg;
-typedef signed long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-
-typedef enum ffi_abi
- {
- FFI_FIRST_ABI = 0,
- FFI_SYSV,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
- } ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_NATIVE_RAW_API 0
-
-#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#define FFI_TRAMPOLINE_SIZE 16
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET 16
-#else
-#error "No trampoline table implementation"
-#endif
-
-#else
-#define FFI_TRAMPOLINE_SIZE 24
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
-#endif
-
-#ifdef _M_ARM64
-#define FFI_EXTRA_CIF_FIELDS unsigned is_variadic
-#endif
-
-/* ---- Internal ---- */
-
-#if defined (__APPLE__)
-#define FFI_TARGET_SPECIFIC_VARIADIC
-#define FFI_EXTRA_CIF_FIELDS unsigned aarch64_nfixedargs
-#elif !defined(_M_ARM64)
-/* iOS and Windows reserve x18 for the system. Disable Go closures until
- a new static chain is chosen. */
-#define FFI_GO_CLOSURES 1
-#endif
-
-#ifndef _M_ARM64
-/* No complex type on Windows */
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-#endif
+/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+``Software''), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+#ifndef LIBFFI_ASM
+#ifdef __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef signed long long ffi_sarg;
+#elif defined(_M_ARM64)
+#define FFI_SIZEOF_ARG 8
+typedef unsigned long long ffi_arg;
+typedef signed long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+
+typedef enum ffi_abi
+ {
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+ } ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_NATIVE_RAW_API 0
+
+#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#define FFI_TRAMPOLINE_SIZE 16
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET 16
+#else
+#error "No trampoline table implementation"
+#endif
+
+#else
+#define FFI_TRAMPOLINE_SIZE 24
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
+#endif
+
+#ifdef _M_ARM64
+#define FFI_EXTRA_CIF_FIELDS unsigned is_variadic
+#endif
+
+/* ---- Internal ---- */
+
+#if defined (__APPLE__)
+#define FFI_TARGET_SPECIFIC_VARIADIC
+#define FFI_EXTRA_CIF_FIELDS unsigned aarch64_nfixedargs
+#elif !defined(_M_ARM64)
+/* iOS and Windows reserve x18 for the system. Disable Go closures until
+ a new static chain is chosen. */
+#define FFI_GO_CLOSURES 1
+#endif
+
+#ifndef _M_ARM64
+/* No complex type on Windows */
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/fficonfig.h b/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/fficonfig.h
index 89392162c7..41cc3cb9e8 100644
--- a/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/fficonfig.h
+++ b/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "aw"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-#define FFI_MMAP_EXEC_EMUTRAMP_PAX 1
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-/* #undef FFI_MMAP_EXEC_WRIT */
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-#define HAVE_AS_CFI_PSEUDO_OP 1
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-/* #undef HAVE_AS_X86_PCREL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-#define HAVE_LONG_DOUBLE 1
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-#define HAVE_MKOSTEMP 1
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-#define HAVE_MMAP_DEV_ZERO 1
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-/* #undef HAVE_RO_EH_FRAME */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-#define LIBFFI_GNU_SYMBOL_VERSIONING 1
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 16
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 8
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-/* #undef SYMBOL_UNDERSCORE */
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "aw"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+#define FFI_MMAP_EXEC_EMUTRAMP_PAX 1
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+/* #undef FFI_MMAP_EXEC_WRIT */
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+#define HAVE_AS_CFI_PSEUDO_OP 1
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+/* #undef HAVE_AS_X86_PCREL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+#define HAVE_LONG_DOUBLE 1
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+#define HAVE_MKOSTEMP 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+#define HAVE_MMAP_DEV_ZERO 1
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+/* #undef HAVE_RO_EH_FRAME */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+#define LIBFFI_GNU_SYMBOL_VERSIONING 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 16
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+/* #undef SYMBOL_UNDERSCORE */
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include/ffi.h b/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include/ffi.h
index 8da6eab3a9..631c77ae35 100644
--- a/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include/ffi.h
+++ b/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef AARCH64
-#define AARCH64
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 1
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 1
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef AARCH64
+#define AARCH64
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 1
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 1
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 1
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 1
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include/ffitarget.h b/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include/ffitarget.h
index ddce8f21eb..ecb6d2deae 100644
--- a/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include/ffitarget.h
@@ -1,92 +1,92 @@
-/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-``Software''), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-#ifndef LIBFFI_ASM
-#ifdef __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef signed long long ffi_sarg;
-#elif defined(_M_ARM64)
-#define FFI_SIZEOF_ARG 8
-typedef unsigned long long ffi_arg;
-typedef signed long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-
-typedef enum ffi_abi
- {
- FFI_FIRST_ABI = 0,
- FFI_SYSV,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
- } ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_NATIVE_RAW_API 0
-
-#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#define FFI_TRAMPOLINE_SIZE 16
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET 16
-#else
-#error "No trampoline table implementation"
-#endif
-
-#else
-#define FFI_TRAMPOLINE_SIZE 24
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
-#endif
-
-#ifdef _M_ARM64
-#define FFI_EXTRA_CIF_FIELDS unsigned is_variadic
-#endif
-
-/* ---- Internal ---- */
-
-#if defined (__APPLE__)
-#define FFI_TARGET_SPECIFIC_VARIADIC
-#define FFI_EXTRA_CIF_FIELDS unsigned aarch64_nfixedargs
-#elif !defined(_M_ARM64)
-/* iOS and Windows reserve x18 for the system. Disable Go closures until
- a new static chain is chosen. */
-#define FFI_GO_CLOSURES 1
-#endif
-
-#ifndef _M_ARM64
-/* No complex type on Windows */
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-#endif
+/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+``Software''), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+#ifndef LIBFFI_ASM
+#ifdef __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef signed long long ffi_sarg;
+#elif defined(_M_ARM64)
+#define FFI_SIZEOF_ARG 8
+typedef unsigned long long ffi_arg;
+typedef signed long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+
+typedef enum ffi_abi
+ {
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+ } ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_NATIVE_RAW_API 0
+
+#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#define FFI_TRAMPOLINE_SIZE 16
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET 16
+#else
+#error "No trampoline table implementation"
+#endif
+
+#else
+#define FFI_TRAMPOLINE_SIZE 24
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
+#endif
+
+#ifdef _M_ARM64
+#define FFI_EXTRA_CIF_FIELDS unsigned is_variadic
+#endif
+
+/* ---- Internal ---- */
+
+#if defined (__APPLE__)
+#define FFI_TARGET_SPECIFIC_VARIADIC
+#define FFI_EXTRA_CIF_FIELDS unsigned aarch64_nfixedargs
+#elif !defined(_M_ARM64)
+/* iOS and Windows reserve x18 for the system. Disable Go closures until
+ a new static chain is chosen. */
+#define FFI_GO_CLOSURES 1
+#endif
+
+#ifndef _M_ARM64
+/* No complex type on Windows */
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/armv7-apple-iphoneos/fficonfig.h b/contrib/restricted/libffi/configs/armv7-apple-iphoneos/fficonfig.h
index 94e11e6232..b0980e6542 100644
--- a/contrib/restricted/libffi/configs/armv7-apple-iphoneos/fficonfig.h
+++ b/contrib/restricted/libffi/configs/armv7-apple-iphoneos/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "aw"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-#define FFI_EXEC_TRAMPOLINE_TABLE 1
-
-/* Define this if you want to enable pax emulated trampolines */
-/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-/* #undef FFI_MMAP_EXEC_WRIT */
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-/* #undef HAVE_AS_X86_PCREL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-/* #undef HAVE_LONG_DOUBLE */
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-#define HAVE_MKOSTEMP 1
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-/* #undef HAVE_MMAP_DEV_ZERO */
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-/* #undef HAVE_RO_EH_FRAME */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 8
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 4
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-#define SYMBOL_UNDERSCORE 1
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "aw"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+#define FFI_EXEC_TRAMPOLINE_TABLE 1
+
+/* Define this if you want to enable pax emulated trampolines */
+/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+/* #undef FFI_MMAP_EXEC_WRIT */
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+/* #undef HAVE_AS_CFI_PSEUDO_OP */
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+/* #undef HAVE_AS_X86_PCREL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+/* #undef HAVE_LONG_DOUBLE */
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+#define HAVE_MKOSTEMP 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+/* #undef HAVE_MMAP_DEV_ZERO */
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+/* #undef HAVE_RO_EH_FRAME */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 8
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 4
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+#define SYMBOL_UNDERSCORE 1
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/armv7-apple-iphoneos/include/ffi.h b/contrib/restricted/libffi/configs/armv7-apple-iphoneos/include/ffi.h
index 4eb0121e98..0aebca13b1 100644
--- a/contrib/restricted/libffi/configs/armv7-apple-iphoneos/include/ffi.h
+++ b/contrib/restricted/libffi/configs/armv7-apple-iphoneos/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef ARM
-#define ARM
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 0
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 0
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef ARM
+#define ARM
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 0
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 0
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 1
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 1
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 1
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 1
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 1
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 1
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 0
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 0
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/armv7-apple-iphoneos/include/ffitarget.h b/contrib/restricted/libffi/configs/armv7-apple-iphoneos/include/ffitarget.h
index 24e1de72b9..cb57b84880 100644
--- a/contrib/restricted/libffi/configs/armv7-apple-iphoneos/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/armv7-apple-iphoneos/include/ffitarget.h
@@ -1,89 +1,89 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012 Anthony Green
- Copyright (c) 2010 CodeSourcery
- Copyright (c) 1996-2003 Red Hat, Inc.
-
- Target configuration macros for ARM.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-#ifndef LIBFFI_ASM
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-
-typedef enum ffi_abi {
- FFI_FIRST_ABI = 0,
- FFI_SYSV,
- FFI_VFP,
- FFI_LAST_ABI,
-#if defined(__ARM_PCS_VFP) || defined(_M_ARM)
- FFI_DEFAULT_ABI = FFI_VFP,
-#else
- FFI_DEFAULT_ABI = FFI_SYSV,
-#endif
-} ffi_abi;
-#endif
-
-#define FFI_EXTRA_CIF_FIELDS \
- int vfp_used; \
- unsigned short vfp_reg_free, vfp_nargs; \
- signed char vfp_args[16] \
-
-#define FFI_TARGET_SPECIFIC_VARIADIC
-#ifndef _M_ARM
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-#define FFI_NATIVE_RAW_API 0
-
-#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#define FFI_TRAMPOLINE_SIZE 12
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET 8
-#else
-#error "No trampoline table implementation"
-#endif
-
-#else
-#ifdef _MSC_VER
-#define FFI_TRAMPOLINE_SIZE 16
-#define FFI_TRAMPOLINE_CLOSURE_FUNCTION 12
-#else
-#define FFI_TRAMPOLINE_SIZE 12
-#endif
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
-#endif
-
-#endif
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012 Anthony Green
+ Copyright (c) 2010 CodeSourcery
+ Copyright (c) 1996-2003 Red Hat, Inc.
+
+ Target configuration macros for ARM.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+#ifndef LIBFFI_ASM
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+
+typedef enum ffi_abi {
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV,
+ FFI_VFP,
+ FFI_LAST_ABI,
+#if defined(__ARM_PCS_VFP) || defined(_M_ARM)
+ FFI_DEFAULT_ABI = FFI_VFP,
+#else
+ FFI_DEFAULT_ABI = FFI_SYSV,
+#endif
+} ffi_abi;
+#endif
+
+#define FFI_EXTRA_CIF_FIELDS \
+ int vfp_used; \
+ unsigned short vfp_reg_free, vfp_nargs; \
+ signed char vfp_args[16] \
+
+#define FFI_TARGET_SPECIFIC_VARIADIC
+#ifndef _M_ARM
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+#define FFI_NATIVE_RAW_API 0
+
+#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#define FFI_TRAMPOLINE_SIZE 12
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET 8
+#else
+#error "No trampoline table implementation"
+#endif
+
+#else
+#ifdef _MSC_VER
+#define FFI_TRAMPOLINE_SIZE 16
+#define FFI_TRAMPOLINE_CLOSURE_FUNCTION 12
+#else
+#define FFI_TRAMPOLINE_SIZE 12
+#endif
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/fficonfig.h b/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/fficonfig.h
index a098633b3b..4c696ad40b 100644
--- a/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/fficonfig.h
+++ b/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "aw"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-#define FFI_MMAP_EXEC_WRIT 1
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-/* #undef HAVE_AS_X86_PCREL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-/* #undef HAVE_LONG_DOUBLE */
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-/* #undef HAVE_MKOSTEMP */
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-#define HAVE_MMAP_DEV_ZERO 1
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-/* #undef HAVE_RO_EH_FRAME */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-#define LIBFFI_GNU_SYMBOL_VERSIONING 1
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 8
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 4
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-/* #undef SYMBOL_UNDERSCORE */
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "aw"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+#define FFI_MMAP_EXEC_WRIT 1
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+/* #undef HAVE_AS_CFI_PSEUDO_OP */
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+/* #undef HAVE_AS_X86_PCREL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+/* #undef HAVE_LONG_DOUBLE */
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+/* #undef HAVE_MKOSTEMP */
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+#define HAVE_MMAP_DEV_ZERO 1
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+/* #undef HAVE_RO_EH_FRAME */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+#define LIBFFI_GNU_SYMBOL_VERSIONING 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 8
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 4
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+/* #undef SYMBOL_UNDERSCORE */
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include/ffi.h b/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include/ffi.h
index 81f2818ebe..d65ed91847 100644
--- a/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include/ffi.h
+++ b/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef ARM
-#define ARM
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 0
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 0
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef ARM
+#define ARM
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 0
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 0
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 0
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 0
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include/ffitarget.h b/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include/ffitarget.h
index 24e1de72b9..cb57b84880 100644
--- a/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include/ffitarget.h
@@ -1,89 +1,89 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012 Anthony Green
- Copyright (c) 2010 CodeSourcery
- Copyright (c) 1996-2003 Red Hat, Inc.
-
- Target configuration macros for ARM.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-#ifndef LIBFFI_ASM
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-
-typedef enum ffi_abi {
- FFI_FIRST_ABI = 0,
- FFI_SYSV,
- FFI_VFP,
- FFI_LAST_ABI,
-#if defined(__ARM_PCS_VFP) || defined(_M_ARM)
- FFI_DEFAULT_ABI = FFI_VFP,
-#else
- FFI_DEFAULT_ABI = FFI_SYSV,
-#endif
-} ffi_abi;
-#endif
-
-#define FFI_EXTRA_CIF_FIELDS \
- int vfp_used; \
- unsigned short vfp_reg_free, vfp_nargs; \
- signed char vfp_args[16] \
-
-#define FFI_TARGET_SPECIFIC_VARIADIC
-#ifndef _M_ARM
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-#define FFI_NATIVE_RAW_API 0
-
-#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#define FFI_TRAMPOLINE_SIZE 12
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET 8
-#else
-#error "No trampoline table implementation"
-#endif
-
-#else
-#ifdef _MSC_VER
-#define FFI_TRAMPOLINE_SIZE 16
-#define FFI_TRAMPOLINE_CLOSURE_FUNCTION 12
-#else
-#define FFI_TRAMPOLINE_SIZE 12
-#endif
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
-#endif
-
-#endif
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012 Anthony Green
+ Copyright (c) 2010 CodeSourcery
+ Copyright (c) 1996-2003 Red Hat, Inc.
+
+ Target configuration macros for ARM.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+#ifndef LIBFFI_ASM
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+
+typedef enum ffi_abi {
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV,
+ FFI_VFP,
+ FFI_LAST_ABI,
+#if defined(__ARM_PCS_VFP) || defined(_M_ARM)
+ FFI_DEFAULT_ABI = FFI_VFP,
+#else
+ FFI_DEFAULT_ABI = FFI_SYSV,
+#endif
+} ffi_abi;
+#endif
+
+#define FFI_EXTRA_CIF_FIELDS \
+ int vfp_used; \
+ unsigned short vfp_reg_free, vfp_nargs; \
+ signed char vfp_args[16] \
+
+#define FFI_TARGET_SPECIFIC_VARIADIC
+#ifndef _M_ARM
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+#define FFI_NATIVE_RAW_API 0
+
+#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#define FFI_TRAMPOLINE_SIZE 12
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET 8
+#else
+#error "No trampoline table implementation"
+#endif
+
+#else
+#ifdef _MSC_VER
+#define FFI_TRAMPOLINE_SIZE 16
+#define FFI_TRAMPOLINE_CLOSURE_FUNCTION 12
+#else
+#define FFI_TRAMPOLINE_SIZE 12
+#endif
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/fficonfig.h b/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/fficonfig.h
index 41ec90550d..6f213c2151 100644
--- a/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/fficonfig.h
+++ b/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "aw"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-#define FFI_MMAP_EXEC_EMUTRAMP_PAX 1
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-/* #undef FFI_MMAP_EXEC_WRIT */
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-#define HAVE_AS_CFI_PSEUDO_OP 1
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-/* #undef HAVE_AS_X86_PCREL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-/* #undef HAVE_LONG_DOUBLE */
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-#define HAVE_MKOSTEMP 1
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-#define HAVE_MMAP_DEV_ZERO 1
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-/* #undef HAVE_RO_EH_FRAME */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-#define LIBFFI_GNU_SYMBOL_VERSIONING 1
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 8
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 4
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-/* #undef SYMBOL_UNDERSCORE */
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "aw"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+#define FFI_MMAP_EXEC_EMUTRAMP_PAX 1
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+/* #undef FFI_MMAP_EXEC_WRIT */
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+#define HAVE_AS_CFI_PSEUDO_OP 1
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+/* #undef HAVE_AS_X86_PCREL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+/* #undef HAVE_LONG_DOUBLE */
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+#define HAVE_MKOSTEMP 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+#define HAVE_MMAP_DEV_ZERO 1
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+/* #undef HAVE_RO_EH_FRAME */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+#define LIBFFI_GNU_SYMBOL_VERSIONING 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 8
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 4
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+/* #undef SYMBOL_UNDERSCORE */
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include/ffi.h b/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include/ffi.h
index 81f2818ebe..d65ed91847 100644
--- a/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include/ffi.h
+++ b/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef ARM
-#define ARM
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 0
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 0
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef ARM
+#define ARM
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 0
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 0
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 0
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 0
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include/ffitarget.h b/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include/ffitarget.h
index 24e1de72b9..cb57b84880 100644
--- a/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include/ffitarget.h
@@ -1,89 +1,89 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012 Anthony Green
- Copyright (c) 2010 CodeSourcery
- Copyright (c) 1996-2003 Red Hat, Inc.
-
- Target configuration macros for ARM.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-#ifndef LIBFFI_ASM
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-
-typedef enum ffi_abi {
- FFI_FIRST_ABI = 0,
- FFI_SYSV,
- FFI_VFP,
- FFI_LAST_ABI,
-#if defined(__ARM_PCS_VFP) || defined(_M_ARM)
- FFI_DEFAULT_ABI = FFI_VFP,
-#else
- FFI_DEFAULT_ABI = FFI_SYSV,
-#endif
-} ffi_abi;
-#endif
-
-#define FFI_EXTRA_CIF_FIELDS \
- int vfp_used; \
- unsigned short vfp_reg_free, vfp_nargs; \
- signed char vfp_args[16] \
-
-#define FFI_TARGET_SPECIFIC_VARIADIC
-#ifndef _M_ARM
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-#define FFI_NATIVE_RAW_API 0
-
-#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#define FFI_TRAMPOLINE_SIZE 12
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET 8
-#else
-#error "No trampoline table implementation"
-#endif
-
-#else
-#ifdef _MSC_VER
-#define FFI_TRAMPOLINE_SIZE 16
-#define FFI_TRAMPOLINE_CLOSURE_FUNCTION 12
-#else
-#define FFI_TRAMPOLINE_SIZE 12
-#endif
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
-#endif
-
-#endif
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012 Anthony Green
+ Copyright (c) 2010 CodeSourcery
+ Copyright (c) 1996-2003 Red Hat, Inc.
+
+ Target configuration macros for ARM.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+#ifndef LIBFFI_ASM
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+
+typedef enum ffi_abi {
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV,
+ FFI_VFP,
+ FFI_LAST_ABI,
+#if defined(__ARM_PCS_VFP) || defined(_M_ARM)
+ FFI_DEFAULT_ABI = FFI_VFP,
+#else
+ FFI_DEFAULT_ABI = FFI_SYSV,
+#endif
+} ffi_abi;
+#endif
+
+#define FFI_EXTRA_CIF_FIELDS \
+ int vfp_used; \
+ unsigned short vfp_reg_free, vfp_nargs; \
+ signed char vfp_args[16] \
+
+#define FFI_TARGET_SPECIFIC_VARIADIC
+#ifndef _M_ARM
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+#define FFI_NATIVE_RAW_API 0
+
+#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#define FFI_TRAMPOLINE_SIZE 12
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET 8
+#else
+#error "No trampoline table implementation"
+#endif
+
+#else
+#ifdef _MSC_VER
+#define FFI_TRAMPOLINE_SIZE 16
+#define FFI_TRAMPOLINE_CLOSURE_FUNCTION 12
+#else
+#define FFI_TRAMPOLINE_SIZE 12
+#endif
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/fficonfig.h b/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/fficonfig.h
index 875ac36170..e4cf69feda 100644
--- a/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/fficonfig.h
+++ b/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "aw"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-#define FFI_MMAP_EXEC_WRIT 1
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-#define HAVE_AS_X86_PCREL 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-#define HAVE_LONG_DOUBLE 1
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-#define HAVE_MKOSTEMP 1
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-/* #undef HAVE_MMAP_DEV_ZERO */
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-/* #undef HAVE_RO_EH_FRAME */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 16
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 4
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-#define SYMBOL_UNDERSCORE 1
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "aw"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+#define FFI_MMAP_EXEC_WRIT 1
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+/* #undef HAVE_AS_CFI_PSEUDO_OP */
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+#define HAVE_AS_X86_PCREL 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+#define HAVE_LONG_DOUBLE 1
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+#define HAVE_MKOSTEMP 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+/* #undef HAVE_MMAP_DEV_ZERO */
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+/* #undef HAVE_RO_EH_FRAME */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 16
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 4
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+#define SYMBOL_UNDERSCORE 1
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include/ffi.h b/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include/ffi.h
index 60db946f5f..4f406a1bea 100644
--- a/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include/ffi.h
+++ b/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef X86_DARWIN
-#define X86_DARWIN
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 1
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 1
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef X86_DARWIN
+#define X86_DARWIN
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 1
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 1
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 1
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 1
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include/ffitarget.h b/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include/ffitarget.h
index 23c8505403..85ccedfedc 100644
--- a/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include/ffitarget.h
@@ -1,147 +1,147 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
- Copyright (c) 1996-2003, 2010 Red Hat, Inc.
- Copyright (C) 2008 Free Software Foundation, Inc.
-
- Target configuration macros for x86 and x86-64.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-/* ---- System specific configurations ----------------------------------- */
-
-/* For code common to all platforms on x86 and x86_64. */
-#define X86_ANY
-
-#if defined (X86_64) && defined (__i386__)
-#undef X86_64
-#define X86
-#endif
-
-#ifdef X86_WIN64
-#define FFI_SIZEOF_ARG 8
-#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
-#endif
-
-#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
-#ifndef _MSC_VER
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Generic type definitions ----------------------------------------- */
-
-#ifndef LIBFFI_ASM
-#ifdef X86_WIN64
-#ifdef _MSC_VER
-typedef unsigned __int64 ffi_arg;
-typedef __int64 ffi_sarg;
-#else
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#endif
-#else
-#if defined __x86_64__ && defined __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-#endif
-
-typedef enum ffi_abi {
-#if defined(X86_WIN64)
- FFI_FIRST_ABI = 0,
- FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
- FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
- FFI_LAST_ABI,
-#ifdef __GNUC__
- FFI_DEFAULT_ABI = FFI_GNUW64
-#else
- FFI_DEFAULT_ABI = FFI_WIN64
-#endif
-
-#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
- FFI_FIRST_ABI = 1,
- FFI_UNIX64,
- FFI_WIN64,
- FFI_EFI64 = FFI_WIN64,
- FFI_GNUW64,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_UNIX64
-
-#elif defined(X86_WIN32)
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_STDCALL = 2,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_MS_CDECL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_MS_CDECL
-#else
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_STDCALL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_MS_CDECL = 8,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
-#endif
-} ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-
-#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
-#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
-#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
-#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
-
-#if defined (X86_64) || defined(X86_WIN64) \
- || (defined (__x86_64__) && defined (X86_DARWIN))
-# define FFI_TRAMPOLINE_SIZE 24
-# define FFI_NATIVE_RAW_API 0
-#else
-# define FFI_TRAMPOLINE_SIZE 12
-# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
-#endif
-
-#endif
-
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
+ Copyright (c) 1996-2003, 2010 Red Hat, Inc.
+ Copyright (C) 2008 Free Software Foundation, Inc.
+
+ Target configuration macros for x86 and x86-64.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+/* ---- System specific configurations ----------------------------------- */
+
+/* For code common to all platforms on x86 and x86_64. */
+#define X86_ANY
+
+#if defined (X86_64) && defined (__i386__)
+#undef X86_64
+#define X86
+#endif
+
+#ifdef X86_WIN64
+#define FFI_SIZEOF_ARG 8
+#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
+#endif
+
+#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+#ifndef _MSC_VER
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Generic type definitions ----------------------------------------- */
+
+#ifndef LIBFFI_ASM
+#ifdef X86_WIN64
+#ifdef _MSC_VER
+typedef unsigned __int64 ffi_arg;
+typedef __int64 ffi_sarg;
+#else
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#endif
+#else
+#if defined __x86_64__ && defined __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+#endif
+
+typedef enum ffi_abi {
+#if defined(X86_WIN64)
+ FFI_FIRST_ABI = 0,
+ FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
+ FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
+ FFI_LAST_ABI,
+#ifdef __GNUC__
+ FFI_DEFAULT_ABI = FFI_GNUW64
+#else
+ FFI_DEFAULT_ABI = FFI_WIN64
+#endif
+
+#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
+ FFI_FIRST_ABI = 1,
+ FFI_UNIX64,
+ FFI_WIN64,
+ FFI_EFI64 = FFI_WIN64,
+ FFI_GNUW64,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_UNIX64
+
+#elif defined(X86_WIN32)
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_STDCALL = 2,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_MS_CDECL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_MS_CDECL
+#else
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_STDCALL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_MS_CDECL = 8,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+#endif
+} ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+
+#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
+#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
+#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
+#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
+
+#if defined (X86_64) || defined(X86_WIN64) \
+ || (defined (__x86_64__) && defined (X86_DARWIN))
+# define FFI_TRAMPOLINE_SIZE 24
+# define FFI_NATIVE_RAW_API 0
+#else
+# define FFI_TRAMPOLINE_SIZE 12
+# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
+#endif
+
+#endif
+
diff --git a/contrib/restricted/libffi/configs/i386-microsoft-windows/fficonfig.h b/contrib/restricted/libffi/configs/i386-microsoft-windows/fficonfig.h
index 7e20e2ee7c..a1cc6192c2 100755
--- a/contrib/restricted/libffi/configs/i386-microsoft-windows/fficonfig.h
+++ b/contrib/restricted/libffi/configs/i386-microsoft-windows/fficonfig.h
@@ -1,224 +1,224 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-/* #undef EH_FRAME_FLAGS */
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to
- alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
-
-/* Cannot use malloc on this target, so, we revert to
- alternative means */
-/* #undef FFI_MMAP_EXEC_WRIT */
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-/* #undef HAVE_ALLOCA_H */
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-#define HAVE_AS_X86_PCREL 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-/* #undef HAVE_DLFCN_H */
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-/* #undef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE */
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-/* #undef HAVE_LONG_DOUBLE */
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-/* #undef HAVE_MEMCPY */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-/* #undef HAVE_MKOSTEMP */
-
-/* Define to 1 if you have the `mmap' function. */
-/* #undef HAVE_MMAP */
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-/* #undef HAVE_MMAP_ANON */
-
-/* Define if mmap of /dev/zero works. */
-/* #undef HAVE_MMAP_DEV_ZERO */
-
-/* Define if read-only mmap of a plain file works. */
-/* #undef HAVE_MMAP_FILE */
-
-/* Define if your compiler supports pointer authentication. */
-/* #undef HAVE_PTRAUTH */
-
-/* Define if .eh_frame sections should be read-only. */
-/* #undef HAVE_RO_EH_FRAME */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-/* #undef HAVE_STRINGS_H */
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-/* #undef HAVE_SYS_MMAN_H */
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-/* #undef HAVE_UNISTD_H */
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
-
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
- */
-#define LT_OBJDIR ".libs/"
-
-/* Define to 1 if your C compiler doesn't accept -c and -o together. */
-/* #undef NO_MINUS_C_MINUS_O */
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 8
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 4
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-#define SYMBOL_UNDERSCORE 1
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+/* #undef EH_FRAME_FLAGS */
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to
+ alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
+
+/* Cannot use malloc on this target, so, we revert to
+ alternative means */
+/* #undef FFI_MMAP_EXEC_WRIT */
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+/* #undef HAVE_ALLOCA_H */
+
+/* Define if your assembler supports .cfi_* directives. */
+/* #undef HAVE_AS_CFI_PSEUDO_OP */
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+#define HAVE_AS_X86_PCREL 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+/* #undef HAVE_DLFCN_H */
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+/* #undef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+/* #undef HAVE_LONG_DOUBLE */
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+/* #undef HAVE_MEMCPY */
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+/* #undef HAVE_MKOSTEMP */
+
+/* Define to 1 if you have the `mmap' function. */
+/* #undef HAVE_MMAP */
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+/* #undef HAVE_MMAP_ANON */
+
+/* Define if mmap of /dev/zero works. */
+/* #undef HAVE_MMAP_DEV_ZERO */
+
+/* Define if read-only mmap of a plain file works. */
+/* #undef HAVE_MMAP_FILE */
+
+/* Define if your compiler supports pointer authentication. */
+/* #undef HAVE_PTRAUTH */
+
+/* Define if .eh_frame sections should be read-only. */
+/* #undef HAVE_RO_EH_FRAME */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+/* #undef HAVE_STRINGS_H */
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+/* #undef HAVE_SYS_MMAN_H */
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+/* #undef HAVE_UNISTD_H */
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
+
+/* Define to the sub-directory in which libtool stores uninstalled libraries.
+ */
+#define LT_OBJDIR ".libs/"
+
+/* Define to 1 if your C compiler doesn't accept -c and -o together. */
+/* #undef NO_MINUS_C_MINUS_O */
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 8
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 4
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+#define SYMBOL_UNDERSCORE 1
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/i386-microsoft-windows/include/ffi.h b/contrib/restricted/libffi/configs/i386-microsoft-windows/include/ffi.h
index d088112a93..cbd41acce7 100755
--- a/contrib/restricted/libffi/configs/i386-microsoft-windows/include/ffi.h
+++ b/contrib/restricted/libffi/configs/i386-microsoft-windows/include/ffi.h
@@ -1,523 +1,523 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef X86_WIN32
-#define X86_WIN32
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 0
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 0
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef X86_WIN32
+#define X86_WIN32
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 0
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 0
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+#if defined(PA_LINUX) || defined(PA_HPUX)
+#define FFI_CLOSURE_PTR(X) ((void *)((unsigned int)(X) | 2))
+#define FFI_RESTORE_PTR(X) ((void *)((unsigned int)(X) & ~3))
+#else
+#define FFI_CLOSURE_PTR(X) (X)
+#define FFI_RESTORE_PTR(X) (X)
+#endif
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-#if defined(PA_LINUX) || defined(PA_HPUX)
-#define FFI_CLOSURE_PTR(X) ((void *)((unsigned int)(X) | 2))
-#define FFI_RESTORE_PTR(X) ((void *)((unsigned int)(X) & ~3))
-#else
-#define FFI_CLOSURE_PTR(X) (X)
-#define FFI_RESTORE_PTR(X) (X)
-#endif
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 0
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 0
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/i386-microsoft-windows/include/ffitarget.h b/contrib/restricted/libffi/configs/i386-microsoft-windows/include/ffitarget.h
index 563afd1375..a34f3e5b70 100755
--- a/contrib/restricted/libffi/configs/i386-microsoft-windows/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/i386-microsoft-windows/include/ffitarget.h
@@ -1,160 +1,160 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
- Copyright (c) 1996-2003, 2010 Red Hat, Inc.
- Copyright (C) 2008 Free Software Foundation, Inc.
-
- Target configuration macros for x86 and x86-64.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-/* ---- System specific configurations ----------------------------------- */
-
-/* For code common to all platforms on x86 and x86_64. */
-#define X86_ANY
-
-#if defined (X86_64) && defined (__i386__)
-#undef X86_64
-#define X86
-#endif
-
-#ifdef X86_WIN64
-#define FFI_SIZEOF_ARG 8
-#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
-#endif
-
-#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
-#ifndef _MSC_VER
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Generic type definitions ----------------------------------------- */
-
-#ifndef LIBFFI_ASM
-#ifdef X86_WIN64
-#ifdef _MSC_VER
-typedef unsigned __int64 ffi_arg;
-typedef __int64 ffi_sarg;
-#else
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#endif
-#else
-#if defined __x86_64__ && defined __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-#endif
-
-typedef enum ffi_abi {
-#if defined(X86_WIN64)
- FFI_FIRST_ABI = 0,
- FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
- FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
- FFI_LAST_ABI,
-#ifdef __GNUC__
- FFI_DEFAULT_ABI = FFI_GNUW64
-#else
- FFI_DEFAULT_ABI = FFI_WIN64
-#endif
-
-#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
- FFI_FIRST_ABI = 1,
- FFI_UNIX64,
- FFI_WIN64,
- FFI_EFI64 = FFI_WIN64,
- FFI_GNUW64,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_UNIX64
-
-#elif defined(X86_WIN32)
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_STDCALL = 2,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_MS_CDECL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_MS_CDECL
-#else
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_STDCALL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_MS_CDECL = 8,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
-#endif
-} ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-
-#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
-#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
-#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
-#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
-
-#if defined (X86_64) || defined(X86_WIN64) \
- || (defined (__x86_64__) && defined (X86_DARWIN))
-/* 4 bytes of ENDBR64 + 7 bytes of LEA + 6 bytes of JMP + 7 bytes of NOP
- + 8 bytes of pointer. */
-# define FFI_TRAMPOLINE_SIZE 32
-# define FFI_NATIVE_RAW_API 0
-#else
-/* 4 bytes of ENDBR32 + 5 bytes of MOV + 5 bytes of JMP + 2 unused
- bytes. */
-# define FFI_TRAMPOLINE_SIZE 16
-# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
-#endif
-
-#if !defined(GENERATE_LIBFFI_MAP) && defined(__ASSEMBLER__) \
- && defined(__CET__)
-# include <cet.h>
-# define _CET_NOTRACK notrack
-#else
-# define _CET_ENDBR
-# define _CET_NOTRACK
-#endif
-
-#endif
-
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
+ Copyright (c) 1996-2003, 2010 Red Hat, Inc.
+ Copyright (C) 2008 Free Software Foundation, Inc.
+
+ Target configuration macros for x86 and x86-64.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+/* ---- System specific configurations ----------------------------------- */
+
+/* For code common to all platforms on x86 and x86_64. */
+#define X86_ANY
+
+#if defined (X86_64) && defined (__i386__)
+#undef X86_64
+#define X86
+#endif
+
+#ifdef X86_WIN64
+#define FFI_SIZEOF_ARG 8
+#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
+#endif
+
+#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+#ifndef _MSC_VER
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Generic type definitions ----------------------------------------- */
+
+#ifndef LIBFFI_ASM
+#ifdef X86_WIN64
+#ifdef _MSC_VER
+typedef unsigned __int64 ffi_arg;
+typedef __int64 ffi_sarg;
+#else
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#endif
+#else
+#if defined __x86_64__ && defined __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+#endif
+
+typedef enum ffi_abi {
+#if defined(X86_WIN64)
+ FFI_FIRST_ABI = 0,
+ FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
+ FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
+ FFI_LAST_ABI,
+#ifdef __GNUC__
+ FFI_DEFAULT_ABI = FFI_GNUW64
+#else
+ FFI_DEFAULT_ABI = FFI_WIN64
+#endif
+
+#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
+ FFI_FIRST_ABI = 1,
+ FFI_UNIX64,
+ FFI_WIN64,
+ FFI_EFI64 = FFI_WIN64,
+ FFI_GNUW64,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_UNIX64
+
+#elif defined(X86_WIN32)
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_STDCALL = 2,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_MS_CDECL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_MS_CDECL
+#else
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_STDCALL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_MS_CDECL = 8,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+#endif
+} ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+
+#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
+#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
+#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
+#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
+
+#if defined (X86_64) || defined(X86_WIN64) \
+ || (defined (__x86_64__) && defined (X86_DARWIN))
+/* 4 bytes of ENDBR64 + 7 bytes of LEA + 6 bytes of JMP + 7 bytes of NOP
+ + 8 bytes of pointer. */
+# define FFI_TRAMPOLINE_SIZE 32
+# define FFI_NATIVE_RAW_API 0
+#else
+/* 4 bytes of ENDBR32 + 5 bytes of MOV + 5 bytes of JMP + 2 unused
+ bytes. */
+# define FFI_TRAMPOLINE_SIZE 16
+# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
+#endif
+
+#if !defined(GENERATE_LIBFFI_MAP) && defined(__ASSEMBLER__) \
+ && defined(__CET__)
+# include <cet.h>
+# define _CET_NOTRACK notrack
+#else
+# define _CET_ENDBR
+# define _CET_NOTRACK
+#endif
+
+#endif
+
diff --git a/contrib/restricted/libffi/configs/i386-microsoft-windows/sysv_intel.masm b/contrib/restricted/libffi/configs/i386-microsoft-windows/sysv_intel.masm
index e04d4fb48a..47022c1324 100644
--- a/contrib/restricted/libffi/configs/i386-microsoft-windows/sysv_intel.masm
+++ b/contrib/restricted/libffi/configs/i386-microsoft-windows/sysv_intel.masm
@@ -1,1961 +1,1961 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- .686P
- .MODEL FLAT
-
-EXTRN @ffi_closure_inner@8:PROC
-_TEXT SEGMENT
-
-
-
-
-
-
-
-
-
-
-
-
-ALIGN 16
-PUBLIC @ffi_call_i386@8
-@ffi_call_i386@8 PROC
-LUW0:
-
-
-
-
-
- mov eax, [esp]
- mov [ecx], ebp
- mov [ecx+4], eax
-
-
-
-
-
-
-
-
- mov ebp, ecx
-LUW1:
-
-
-
- mov esp, edx
- mov eax, [20+0*4+ebp]
- mov edx, [20+1*4+ebp]
- mov ecx, [20+2*4+ebp]
-
- call dword ptr [ebp+8]
-
- mov ecx, [12+ebp]
- mov [ebp+8], ebx
-LUW2:
-
-
- and ecx, 15
- lea ebx, [Lstore_table + ecx * 8]
- mov ecx, [ebp+16]
- jmp ebx
-
- ALIGN 8
-Lstore_table:
-ALIGN 8; ORG Lstore_table + 0 * 8
- fstp DWORD PTR [ecx]
- jmp Le1
-ALIGN 8; ORG Lstore_table + 1 * 8
- fstp QWORD PTR [ecx]
- jmp Le1
-ALIGN 8; ORG Lstore_table + 2 * 8
- fstp QWORD PTR [ecx]
- jmp Le1
-ALIGN 8; ORG Lstore_table + 3 * 8
- movsx eax, al
- mov [ecx], eax
- jmp Le1
-ALIGN 8; ORG Lstore_table + 4 * 8
- movsx eax, ax
- mov [ecx], eax
- jmp Le1
-ALIGN 8; ORG Lstore_table + 5 * 8
- movzx eax, al
- mov [ecx], eax
- jmp Le1
-ALIGN 8; ORG Lstore_table + 6 * 8
- movzx eax, ax
- mov [ecx], eax
- jmp Le1
-ALIGN 8; ORG Lstore_table + 7 * 8
- mov [ecx+4], edx
-
-ALIGN 8; ORG Lstore_table + X86_RET_int 32 * 8
- mov [ecx], eax
-
-ALIGN 8; ORG Lstore_table + 9 * 8
-Le1:
- mov ebx, [ebp+8]
- mov esp, ebp
- pop ebp
-LUW3:
-
-
-
-
- ret
-LUW4:
-
-
-ALIGN 8; ORG Lstore_table + 10 * 8
- jmp Le1
-ALIGN 8; ORG Lstore_table + 11 * 8
- jmp Le1
-ALIGN 8; ORG Lstore_table + 12 * 8
- mov [ecx], al
- jmp Le1
-ALIGN 8; ORG Lstore_table + 13 * 8
- mov [ecx], ax
- jmp Le1
-
-
-ALIGN 8; ORG Lstore_table + 14 * 8
- int 3
-ALIGN 8; ORG Lstore_table + 15 * 8
- int 3
-
-LUW5:
-
-@ffi_call_i386@8 ENDP
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-FFI_CLOSURE_SAVE_REGS MACRO
- mov [esp + 0+16+0*4], eax
- mov [esp + 0+16+1*4], edx
- mov [esp + 0+16+2*4], ecx
-ENDM
-
-FFI_CLOSURE_COPY_TRAMP_DATA MACRO
- mov edx, [eax+12]
- mov ecx, [eax+12+4]
- mov eax, [eax+12+8];
- mov [esp+0+28], edx
- mov [esp+0+32], ecx
- mov [esp+0+36], eax
-ENDM
-
-
-FFI_CLOSURE_PREP_CALL MACRO
- mov ecx, esp
- lea edx, [esp+(40 + 4)+4]
-ENDM
-
-
-
-
-
-
-
-
-
-FFI_CLOSURE_CALL_INNER MACRO UWN
- call @ffi_closure_inner@8
-ENDM
-
-FFI_CLOSURE_MASK_AND_JUMP MACRO LABEL
- and eax, 15
- lea edx, [LABEL+eax*8]
- mov eax, [esp+0]
- jmp edx
-ENDM
-
-ALIGN 16
-PUBLIC ffi_go_closure_EAX
-ffi_go_closure_EAX PROC C
-LUW6:
-
- sub esp, (40 + 4)
-LUW7:
-
- FFI_CLOSURE_SAVE_REGS
- mov edx, [eax+4]
- mov ecx, [eax +8]
- mov [esp+0+28], edx
- mov [esp+0+32], ecx
- mov [esp+0+36], eax
- jmp Ldo_closure_i386
-LUW8:
-
-ffi_go_closure_EAX ENDP
-
-ALIGN 16
-PUBLIC ffi_go_closure_ECX
-ffi_go_closure_ECX PROC C
-LUW9:
-
- sub esp, (40 + 4)
-LUW10:
-
- FFI_CLOSURE_SAVE_REGS
- mov edx, [ecx+4]
- mov eax, [ecx+8]
- mov [esp+0+28], edx
- mov [esp+0+32], eax
- mov [esp+0+36], ecx
- jmp Ldo_closure_i386
-LUW11:
-
-ffi_go_closure_ECX ENDP
-
-
-
-
-ALIGN 16
-PUBLIC ffi_closure_i386
-ffi_closure_i386 PROC C
-LUW12:
-
- sub esp, (40 + 4)
-LUW13:
-
-
- FFI_CLOSURE_SAVE_REGS
- FFI_CLOSURE_COPY_TRAMP_DATA
-
-
-Ldo_closure_i386::
-
- FFI_CLOSURE_PREP_CALL
- FFI_CLOSURE_CALL_INNER(14)
- FFI_CLOSURE_MASK_AND_JUMP Lload_table2
-
- ALIGN 8
-Lload_table2:
-ALIGN 8; ORG Lload_table2 + 0 * 8
- fld dword ptr [esp+0]
- jmp Le2
-ALIGN 8; ORG Lload_table2 + 1 * 8
- fld qword ptr [esp+0]
- jmp Le2
-ALIGN 8; ORG Lload_table2 + 2 * 8
- fld qword ptr [esp+0]
- jmp Le2
-ALIGN 8; ORG Lload_table2 + 3 * 8
- movsx eax, al
- jmp Le2
-ALIGN 8; ORG Lload_table2 + 4 * 8
- movsx eax, ax
- jmp Le2
-ALIGN 8; ORG Lload_table2 + 5 * 8
- movzx eax, al
- jmp Le2
-ALIGN 8; ORG Lload_table2 + 6 * 8
- movzx eax, ax
- jmp Le2
-ALIGN 8; ORG Lload_table2 + 7 * 8
- mov edx, [esp+0+4]
- jmp Le2
-ALIGN 8; ORG Lload_table2 + 8 * 8
- nop
-
-ALIGN 8; ORG Lload_table2 + 9 * 8
-Le2:
- add esp, (40 + 4)
-LUW16:
-
- ret
-LUW17:
-
-ALIGN 8; ORG Lload_table2 + 10 * 8
- add esp, (40 + 4)
-LUW18:
-
- ret 4
-LUW19:
-
-ALIGN 8; ORG Lload_table2 + 11 * 8
- jmp Le2
-ALIGN 8; ORG Lload_table2 + 12 * 8
- movzx eax, al
- jmp Le2
-ALIGN 8; ORG Lload_table2 + 13 * 8
- movzx eax, ax
- jmp Le2
-
-
-ALIGN 8; ORG Lload_table2 + 14 * 8
- int 3
-ALIGN 8; ORG Lload_table2 + 15 * 8
- int 3
-
-LUW20:
-
-ffi_closure_i386 ENDP
-
-ALIGN 16
-PUBLIC ffi_go_closure_STDCALL
-ffi_go_closure_STDCALL PROC C
-LUW21:
-
- sub esp, (40 + 4)
-LUW22:
-
- FFI_CLOSURE_SAVE_REGS
- mov edx, [ecx+4]
- mov eax, [ecx+8]
- mov [esp+0+28], edx
- mov [esp+0+32], eax
- mov [esp+0+36], ecx
- jmp Ldo_closure_STDCALL
-LUW23:
-
-ffi_go_closure_STDCALL ENDP
-
-
-
-
-ALIGN 16
-PUBLIC ffi_closure_REGISTER
-ffi_closure_REGISTER PROC C
-LUW24:
-
-
-
- sub esp, (40 + 4)-4
-LUW25:
-
- FFI_CLOSURE_SAVE_REGS
- mov ecx, [esp+(40 + 4)-4]
- mov eax, [esp+(40 + 4)]
- mov [esp+(40 + 4)], ecx
- jmp Ldo_closure_REGISTER
-LUW26:
-
-ffi_closure_REGISTER ENDP
-
-
-
-
-
-ALIGN 16
-PUBLIC ffi_closure_STDCALL
-ffi_closure_STDCALL PROC C
-LUW27:
-
- sub esp, (40 + 4)
-LUW28:
-
-
- FFI_CLOSURE_SAVE_REGS
-
-
-Ldo_closure_REGISTER::
-
- FFI_CLOSURE_COPY_TRAMP_DATA
-
-
-Ldo_closure_STDCALL::
-
- FFI_CLOSURE_PREP_CALL
- FFI_CLOSURE_CALL_INNER(29)
-
- mov ecx, eax
- shr ecx, 4
- lea ecx, [esp+(40 + 4)+ecx]
- mov edx, [esp+(40 + 4)]
- mov [ecx], edx
-
-
-
-
-
-
-
- FFI_CLOSURE_MASK_AND_JUMP Lload_table3
-
- ALIGN 8
-Lload_table3:
-ALIGN 8; ORG Lload_table3 + 0 * 8
- fld DWORD PTR [esp+0]
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 1 * 8
- fld QWORD PTR [esp+0]
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 2 * 8
- fld QWORD PTR [esp+0]
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 3 * 8
- movsx eax, al
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 4 * 8
- movsx eax, ax
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 5 * 8
- movzx eax, al
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 6 * 8
- movzx eax, ax
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 7 * 8
- mov edx, [esp+0+4]
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + X86_RET_int 32 * 8
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 9 * 8
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 10 * 8
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 11 * 8
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 12 * 8
- movzx eax, al
- mov esp, ecx
- ret
-ALIGN 8; ORG Lload_table3 + 13 * 8
- movzx eax, ax
- mov esp, ecx
- ret
-
-
-ALIGN 8; ORG Lload_table3 + 14 * 8
- int 3
-ALIGN 8; ORG Lload_table3 + 15 * 8
- int 3
-
-LUW31:
-
-ffi_closure_STDCALL ENDP
-
-
-
-
-
-ALIGN 16
-PUBLIC ffi_closure_raw_SYSV
-ffi_closure_raw_SYSV PROC C
-LUW32:
-
- sub esp, (16+16+12)
-LUW33:
-
- mov [esp+(16+16+12)-4], ebx
-LUW34:
-
-
- mov edx, [eax+12+8]
- mov [esp+12], edx
- lea edx, [esp+(16+16+12)+4]
- mov [esp+8], edx
- lea edx, [esp+16]
- mov [esp+4], edx
- mov ebx, [eax+12]
- mov [esp], ebx
- call DWORD PTR [eax+12+4]
-
- mov eax, [ebx+20]
- and eax, 15
-
-
-
-
-
- lea ecx, [Lload_table4+eax+8]
-
- mov ebx, [esp+(16+16+12)-4]
-LUW35:
-
- mov eax, [esp+16]
- jmp dword ptr [ecx]
-
- ALIGN 8
-Lload_table4:
-ALIGN 8; ORG Lload_table4 + 0 * 8
- fld DWORD PTR [esp +16]
- jmp Le4
-ALIGN 8; ORG Lload_table4 + 1 * 8
- fld QWORD PTR [esp +16]
- jmp Le4
-ALIGN 8; ORG Lload_table4 + 2 * 8
- fld QWORD PTR [esp +16]
- jmp Le4
-ALIGN 8; ORG Lload_table4 + 3 * 8
- movsx eax, al
- jmp Le4
-ALIGN 8; ORG Lload_table4 + 4 * 8
- movsx eax, ax
- jmp Le4
-ALIGN 8; ORG Lload_table4 + 5 * 8
- movzx eax, al
- jmp Le4
-ALIGN 8; ORG Lload_table4 + 6 * 8
- movzx eax, ax
- jmp Le4
-ALIGN 8; ORG Lload_table4 + 7 * 8
- mov edx, [esp+16+4]
- jmp Le4
-ALIGN 8; ORG Lload_table4 + X86_RET_int 32 * 8
- nop
-
-ALIGN 8; ORG Lload_table4 + 9 * 8
-Le4:
- add esp, (16+16+12)
-LUW36:
-
- ret
-LUW37:
-
-ALIGN 8; ORG Lload_table4 + 10 * 8
- add esp, (16+16+12)
-LUW38:
-
- ret 4
-LUW39:
-
-ALIGN 8; ORG Lload_table4 + 11 * 8
- jmp Le4
-ALIGN 8; ORG Lload_table4 + 12 * 8
- movzx eax, al
- jmp Le4
-ALIGN 8; ORG Lload_table4 + 13 * 8
- movzx eax, ax
- jmp Le4
-
-
-ALIGN 8; ORG Lload_table4 + 14 * 8
- int 3
-ALIGN 8; ORG Lload_table4 + 15 * 8
- int 3
-
-LUW40:
-
-ffi_closure_raw_SYSV ENDP
-
-
-
-ALIGN 16
-PUBLIC ffi_closure_raw_THISCALL
-ffi_closure_raw_THISCALL PROC C
-LUW41:
-
-
-
- pop edx
-LUW42:
-
-
- push ecx
-LUW43:
-
- push edx
-LUW44:
-
-
- sub esp, (16+16+8)
-LUW45:
-
- mov [esp+(16+16+8)-4], ebx
-LUW46:
-
-
- mov edx, [eax+12+8]
- mov [esp+12], edx
- lea edx, [esp+(16+16+8)+4]
- mov [esp+8], edx
- lea edx, [esp+16]
- mov [esp+4], edx
- mov ebx, [eax+12]
- mov [esp], ebx
- call DWORD PTR [eax+12+4]
-
- mov eax, [ebx+20]
- and eax, 15
-
-
-
-
-
- lea ecx, [Lload_table5+eax*8]
-
- mov ebx, [esp+(16+16+8)-4]
-LUW47:
-
- mov eax, [esp+16]
- jmp DWORD PTR [ecx]
-
- AlIGN 4
-Lload_table5:
-ALIGN 8; ORG Lload_table5 + 0 * 8
- fld DWORD PTR [esp +16]
- jmp Le5
-ALIGN 8; ORG Lload_table5 + 1 * 8
- fld QWORD PTR [esp +16]
- jmp Le5
-ALIGN 8; ORG Lload_table5 + 2 * 8
- fld QWORD PTR [esp+16]
- jmp Le5
-ALIGN 8; ORG Lload_table5 + 3 * 8
- movsx eax, al
- jmp Le5
-ALIGN 8; ORG Lload_table5 + 4 * 8
- movsx eax, ax
- jmp Le5
-ALIGN 8; ORG Lload_table5 + 5 * 8
- movzx eax, al
- jmp Le5
-ALIGN 8; ORG Lload_table5 + 6 * 8
- movzx eax, ax
- jmp Le5
-ALIGN 8; ORG Lload_table5 + 7 * 8
- mov edx, [esp+16+4]
- jmp Le5
-ALIGN 8; ORG Lload_table5 + X86_RET_int 32 * 8
- nop
-
-ALIGN 8; ORG Lload_table5 + 9 * 8
-Le5:
- add esp, (16+16+8)
-LUW48:
-
-
- ret 4
-LUW49:
-
-ALIGN 8; ORG Lload_table5 + 10 * 8
- add esp, (16+16+8)
-LUW50:
-
- ret 8
-LUW51:
-
-ALIGN 8; ORG Lload_table5 + 11 * 8
- jmp Le5
-ALIGN 8; ORG Lload_table5 + 12 * 8
- movzx eax, al
- jmp Le5
-ALIGN 8; ORG Lload_table5 + 13 * 8
- movzx eax, ax
- jmp Le5
-
-
-ALIGN 8; ORG Lload_table5 + 14 * 8
- int 3
-ALIGN 8; ORG Lload_table5 + 15 * 8
- int 3
-
-LUW52:
-
-ffi_closure_raw_THISCALL ENDP
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-END
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ .686P
+ .MODEL FLAT
+
+EXTRN @ffi_closure_inner@8:PROC
+_TEXT SEGMENT
+
+
+
+
+
+
+
+
+
+
+
+
+ALIGN 16
+PUBLIC @ffi_call_i386@8
+@ffi_call_i386@8 PROC
+LUW0:
+
+
+
+
+
+ mov eax, [esp]
+ mov [ecx], ebp
+ mov [ecx+4], eax
+
+
+
+
+
+
+
+
+ mov ebp, ecx
+LUW1:
+
+
+
+ mov esp, edx
+ mov eax, [20+0*4+ebp]
+ mov edx, [20+1*4+ebp]
+ mov ecx, [20+2*4+ebp]
+
+ call dword ptr [ebp+8]
+
+ mov ecx, [12+ebp]
+ mov [ebp+8], ebx
+LUW2:
+
+
+ and ecx, 15
+ lea ebx, [Lstore_table + ecx * 8]
+ mov ecx, [ebp+16]
+ jmp ebx
+
+ ALIGN 8
+Lstore_table:
+ALIGN 8; ORG Lstore_table + 0 * 8
+ fstp DWORD PTR [ecx]
+ jmp Le1
+ALIGN 8; ORG Lstore_table + 1 * 8
+ fstp QWORD PTR [ecx]
+ jmp Le1
+ALIGN 8; ORG Lstore_table + 2 * 8
+ fstp QWORD PTR [ecx]
+ jmp Le1
+ALIGN 8; ORG Lstore_table + 3 * 8
+ movsx eax, al
+ mov [ecx], eax
+ jmp Le1
+ALIGN 8; ORG Lstore_table + 4 * 8
+ movsx eax, ax
+ mov [ecx], eax
+ jmp Le1
+ALIGN 8; ORG Lstore_table + 5 * 8
+ movzx eax, al
+ mov [ecx], eax
+ jmp Le1
+ALIGN 8; ORG Lstore_table + 6 * 8
+ movzx eax, ax
+ mov [ecx], eax
+ jmp Le1
+ALIGN 8; ORG Lstore_table + 7 * 8
+ mov [ecx+4], edx
+
+ALIGN 8; ORG Lstore_table + X86_RET_int 32 * 8
+ mov [ecx], eax
+
+ALIGN 8; ORG Lstore_table + 9 * 8
+Le1:
+ mov ebx, [ebp+8]
+ mov esp, ebp
+ pop ebp
+LUW3:
+
+
+
+
+ ret
+LUW4:
+
+
+ALIGN 8; ORG Lstore_table + 10 * 8
+ jmp Le1
+ALIGN 8; ORG Lstore_table + 11 * 8
+ jmp Le1
+ALIGN 8; ORG Lstore_table + 12 * 8
+ mov [ecx], al
+ jmp Le1
+ALIGN 8; ORG Lstore_table + 13 * 8
+ mov [ecx], ax
+ jmp Le1
+
+
+ALIGN 8; ORG Lstore_table + 14 * 8
+ int 3
+ALIGN 8; ORG Lstore_table + 15 * 8
+ int 3
+
+LUW5:
+
+@ffi_call_i386@8 ENDP
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+FFI_CLOSURE_SAVE_REGS MACRO
+ mov [esp + 0+16+0*4], eax
+ mov [esp + 0+16+1*4], edx
+ mov [esp + 0+16+2*4], ecx
+ENDM
+
+FFI_CLOSURE_COPY_TRAMP_DATA MACRO
+ mov edx, [eax+12]
+ mov ecx, [eax+12+4]
+ mov eax, [eax+12+8];
+ mov [esp+0+28], edx
+ mov [esp+0+32], ecx
+ mov [esp+0+36], eax
+ENDM
+
+
+FFI_CLOSURE_PREP_CALL MACRO
+ mov ecx, esp
+ lea edx, [esp+(40 + 4)+4]
+ENDM
+
+
+
+
+
+
+
+
+
+FFI_CLOSURE_CALL_INNER MACRO UWN
+ call @ffi_closure_inner@8
+ENDM
+
+FFI_CLOSURE_MASK_AND_JUMP MACRO LABEL
+ and eax, 15
+ lea edx, [LABEL+eax*8]
+ mov eax, [esp+0]
+ jmp edx
+ENDM
+
+ALIGN 16
+PUBLIC ffi_go_closure_EAX
+ffi_go_closure_EAX PROC C
+LUW6:
+
+ sub esp, (40 + 4)
+LUW7:
+
+ FFI_CLOSURE_SAVE_REGS
+ mov edx, [eax+4]
+ mov ecx, [eax +8]
+ mov [esp+0+28], edx
+ mov [esp+0+32], ecx
+ mov [esp+0+36], eax
+ jmp Ldo_closure_i386
+LUW8:
+
+ffi_go_closure_EAX ENDP
+
+ALIGN 16
+PUBLIC ffi_go_closure_ECX
+ffi_go_closure_ECX PROC C
+LUW9:
+
+ sub esp, (40 + 4)
+LUW10:
+
+ FFI_CLOSURE_SAVE_REGS
+ mov edx, [ecx+4]
+ mov eax, [ecx+8]
+ mov [esp+0+28], edx
+ mov [esp+0+32], eax
+ mov [esp+0+36], ecx
+ jmp Ldo_closure_i386
+LUW11:
+
+ffi_go_closure_ECX ENDP
+
+
+
+
+ALIGN 16
+PUBLIC ffi_closure_i386
+ffi_closure_i386 PROC C
+LUW12:
+
+ sub esp, (40 + 4)
+LUW13:
+
+
+ FFI_CLOSURE_SAVE_REGS
+ FFI_CLOSURE_COPY_TRAMP_DATA
+
+
+Ldo_closure_i386::
+
+ FFI_CLOSURE_PREP_CALL
+ FFI_CLOSURE_CALL_INNER(14)
+ FFI_CLOSURE_MASK_AND_JUMP Lload_table2
+
+ ALIGN 8
+Lload_table2:
+ALIGN 8; ORG Lload_table2 + 0 * 8
+ fld dword ptr [esp+0]
+ jmp Le2
+ALIGN 8; ORG Lload_table2 + 1 * 8
+ fld qword ptr [esp+0]
+ jmp Le2
+ALIGN 8; ORG Lload_table2 + 2 * 8
+ fld qword ptr [esp+0]
+ jmp Le2
+ALIGN 8; ORG Lload_table2 + 3 * 8
+ movsx eax, al
+ jmp Le2
+ALIGN 8; ORG Lload_table2 + 4 * 8
+ movsx eax, ax
+ jmp Le2
+ALIGN 8; ORG Lload_table2 + 5 * 8
+ movzx eax, al
+ jmp Le2
+ALIGN 8; ORG Lload_table2 + 6 * 8
+ movzx eax, ax
+ jmp Le2
+ALIGN 8; ORG Lload_table2 + 7 * 8
+ mov edx, [esp+0+4]
+ jmp Le2
+ALIGN 8; ORG Lload_table2 + 8 * 8
+ nop
+
+ALIGN 8; ORG Lload_table2 + 9 * 8
+Le2:
+ add esp, (40 + 4)
+LUW16:
+
+ ret
+LUW17:
+
+ALIGN 8; ORG Lload_table2 + 10 * 8
+ add esp, (40 + 4)
+LUW18:
+
+ ret 4
+LUW19:
+
+ALIGN 8; ORG Lload_table2 + 11 * 8
+ jmp Le2
+ALIGN 8; ORG Lload_table2 + 12 * 8
+ movzx eax, al
+ jmp Le2
+ALIGN 8; ORG Lload_table2 + 13 * 8
+ movzx eax, ax
+ jmp Le2
+
+
+ALIGN 8; ORG Lload_table2 + 14 * 8
+ int 3
+ALIGN 8; ORG Lload_table2 + 15 * 8
+ int 3
+
+LUW20:
+
+ffi_closure_i386 ENDP
+
+ALIGN 16
+PUBLIC ffi_go_closure_STDCALL
+ffi_go_closure_STDCALL PROC C
+LUW21:
+
+ sub esp, (40 + 4)
+LUW22:
+
+ FFI_CLOSURE_SAVE_REGS
+ mov edx, [ecx+4]
+ mov eax, [ecx+8]
+ mov [esp+0+28], edx
+ mov [esp+0+32], eax
+ mov [esp+0+36], ecx
+ jmp Ldo_closure_STDCALL
+LUW23:
+
+ffi_go_closure_STDCALL ENDP
+
+
+
+
+ALIGN 16
+PUBLIC ffi_closure_REGISTER
+ffi_closure_REGISTER PROC C
+LUW24:
+
+
+
+ sub esp, (40 + 4)-4
+LUW25:
+
+ FFI_CLOSURE_SAVE_REGS
+ mov ecx, [esp+(40 + 4)-4]
+ mov eax, [esp+(40 + 4)]
+ mov [esp+(40 + 4)], ecx
+ jmp Ldo_closure_REGISTER
+LUW26:
+
+ffi_closure_REGISTER ENDP
+
+
+
+
+
+ALIGN 16
+PUBLIC ffi_closure_STDCALL
+ffi_closure_STDCALL PROC C
+LUW27:
+
+ sub esp, (40 + 4)
+LUW28:
+
+
+ FFI_CLOSURE_SAVE_REGS
+
+
+Ldo_closure_REGISTER::
+
+ FFI_CLOSURE_COPY_TRAMP_DATA
+
+
+Ldo_closure_STDCALL::
+
+ FFI_CLOSURE_PREP_CALL
+ FFI_CLOSURE_CALL_INNER(29)
+
+ mov ecx, eax
+ shr ecx, 4
+ lea ecx, [esp+(40 + 4)+ecx]
+ mov edx, [esp+(40 + 4)]
+ mov [ecx], edx
+
+
+
+
+
+
+
+ FFI_CLOSURE_MASK_AND_JUMP Lload_table3
+
+ ALIGN 8
+Lload_table3:
+ALIGN 8; ORG Lload_table3 + 0 * 8
+ fld DWORD PTR [esp+0]
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 1 * 8
+ fld QWORD PTR [esp+0]
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 2 * 8
+ fld QWORD PTR [esp+0]
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 3 * 8
+ movsx eax, al
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 4 * 8
+ movsx eax, ax
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 5 * 8
+ movzx eax, al
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 6 * 8
+ movzx eax, ax
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 7 * 8
+ mov edx, [esp+0+4]
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + X86_RET_int 32 * 8
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 9 * 8
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 10 * 8
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 11 * 8
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 12 * 8
+ movzx eax, al
+ mov esp, ecx
+ ret
+ALIGN 8; ORG Lload_table3 + 13 * 8
+ movzx eax, ax
+ mov esp, ecx
+ ret
+
+
+ALIGN 8; ORG Lload_table3 + 14 * 8
+ int 3
+ALIGN 8; ORG Lload_table3 + 15 * 8
+ int 3
+
+LUW31:
+
+ffi_closure_STDCALL ENDP
+
+
+
+
+
+ALIGN 16
+PUBLIC ffi_closure_raw_SYSV
+ffi_closure_raw_SYSV PROC C
+LUW32:
+
+ sub esp, (16+16+12)
+LUW33:
+
+ mov [esp+(16+16+12)-4], ebx
+LUW34:
+
+
+ mov edx, [eax+12+8]
+ mov [esp+12], edx
+ lea edx, [esp+(16+16+12)+4]
+ mov [esp+8], edx
+ lea edx, [esp+16]
+ mov [esp+4], edx
+ mov ebx, [eax+12]
+ mov [esp], ebx
+ call DWORD PTR [eax+12+4]
+
+ mov eax, [ebx+20]
+ and eax, 15
+
+
+
+
+
+ lea ecx, [Lload_table4+eax+8]
+
+ mov ebx, [esp+(16+16+12)-4]
+LUW35:
+
+ mov eax, [esp+16]
+ jmp dword ptr [ecx]
+
+ ALIGN 8
+Lload_table4:
+ALIGN 8; ORG Lload_table4 + 0 * 8
+ fld DWORD PTR [esp +16]
+ jmp Le4
+ALIGN 8; ORG Lload_table4 + 1 * 8
+ fld QWORD PTR [esp +16]
+ jmp Le4
+ALIGN 8; ORG Lload_table4 + 2 * 8
+ fld QWORD PTR [esp +16]
+ jmp Le4
+ALIGN 8; ORG Lload_table4 + 3 * 8
+ movsx eax, al
+ jmp Le4
+ALIGN 8; ORG Lload_table4 + 4 * 8
+ movsx eax, ax
+ jmp Le4
+ALIGN 8; ORG Lload_table4 + 5 * 8
+ movzx eax, al
+ jmp Le4
+ALIGN 8; ORG Lload_table4 + 6 * 8
+ movzx eax, ax
+ jmp Le4
+ALIGN 8; ORG Lload_table4 + 7 * 8
+ mov edx, [esp+16+4]
+ jmp Le4
+ALIGN 8; ORG Lload_table4 + X86_RET_int 32 * 8
+ nop
+
+ALIGN 8; ORG Lload_table4 + 9 * 8
+Le4:
+ add esp, (16+16+12)
+LUW36:
+
+ ret
+LUW37:
+
+ALIGN 8; ORG Lload_table4 + 10 * 8
+ add esp, (16+16+12)
+LUW38:
+
+ ret 4
+LUW39:
+
+ALIGN 8; ORG Lload_table4 + 11 * 8
+ jmp Le4
+ALIGN 8; ORG Lload_table4 + 12 * 8
+ movzx eax, al
+ jmp Le4
+ALIGN 8; ORG Lload_table4 + 13 * 8
+ movzx eax, ax
+ jmp Le4
+
+
+ALIGN 8; ORG Lload_table4 + 14 * 8
+ int 3
+ALIGN 8; ORG Lload_table4 + 15 * 8
+ int 3
+
+LUW40:
+
+ffi_closure_raw_SYSV ENDP
+
+
+
+ALIGN 16
+PUBLIC ffi_closure_raw_THISCALL
+ffi_closure_raw_THISCALL PROC C
+LUW41:
+
+
+
+ pop edx
+LUW42:
+
+
+ push ecx
+LUW43:
+
+ push edx
+LUW44:
+
+
+ sub esp, (16+16+8)
+LUW45:
+
+ mov [esp+(16+16+8)-4], ebx
+LUW46:
+
+
+ mov edx, [eax+12+8]
+ mov [esp+12], edx
+ lea edx, [esp+(16+16+8)+4]
+ mov [esp+8], edx
+ lea edx, [esp+16]
+ mov [esp+4], edx
+ mov ebx, [eax+12]
+ mov [esp], ebx
+ call DWORD PTR [eax+12+4]
+
+ mov eax, [ebx+20]
+ and eax, 15
+
+
+
+
+
+ lea ecx, [Lload_table5+eax*8]
+
+ mov ebx, [esp+(16+16+8)-4]
+LUW47:
+
+ mov eax, [esp+16]
+ jmp DWORD PTR [ecx]
+
+ AlIGN 4
+Lload_table5:
+ALIGN 8; ORG Lload_table5 + 0 * 8
+ fld DWORD PTR [esp +16]
+ jmp Le5
+ALIGN 8; ORG Lload_table5 + 1 * 8
+ fld QWORD PTR [esp +16]
+ jmp Le5
+ALIGN 8; ORG Lload_table5 + 2 * 8
+ fld QWORD PTR [esp+16]
+ jmp Le5
+ALIGN 8; ORG Lload_table5 + 3 * 8
+ movsx eax, al
+ jmp Le5
+ALIGN 8; ORG Lload_table5 + 4 * 8
+ movsx eax, ax
+ jmp Le5
+ALIGN 8; ORG Lload_table5 + 5 * 8
+ movzx eax, al
+ jmp Le5
+ALIGN 8; ORG Lload_table5 + 6 * 8
+ movzx eax, ax
+ jmp Le5
+ALIGN 8; ORG Lload_table5 + 7 * 8
+ mov edx, [esp+16+4]
+ jmp Le5
+ALIGN 8; ORG Lload_table5 + X86_RET_int 32 * 8
+ nop
+
+ALIGN 8; ORG Lload_table5 + 9 * 8
+Le5:
+ add esp, (16+16+8)
+LUW48:
+
+
+ ret 4
+LUW49:
+
+ALIGN 8; ORG Lload_table5 + 10 * 8
+ add esp, (16+16+8)
+LUW50:
+
+ ret 8
+LUW51:
+
+ALIGN 8; ORG Lload_table5 + 11 * 8
+ jmp Le5
+ALIGN 8; ORG Lload_table5 + 12 * 8
+ movzx eax, al
+ jmp Le5
+ALIGN 8; ORG Lload_table5 + 13 * 8
+ movzx eax, ax
+ jmp Le5
+
+
+ALIGN 8; ORG Lload_table5 + 14 * 8
+ int 3
+ALIGN 8; ORG Lload_table5 + 15 * 8
+ int 3
+
+LUW52:
+
+ffi_closure_raw_THISCALL ENDP
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+END
diff --git a/contrib/restricted/libffi/configs/i686-pc-linux-android16/fficonfig.h b/contrib/restricted/libffi/configs/i686-pc-linux-android16/fficonfig.h
index c957e73e66..58cdf8c2eb 100644
--- a/contrib/restricted/libffi/configs/i686-pc-linux-android16/fficonfig.h
+++ b/contrib/restricted/libffi/configs/i686-pc-linux-android16/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "a"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-#define FFI_MMAP_EXEC_WRIT 1
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-#define HAVE_AS_X86_PCREL 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-/* #undef HAVE_LONG_DOUBLE */
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-/* #undef HAVE_MKOSTEMP */
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-#define HAVE_MMAP_DEV_ZERO 1
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-#define HAVE_RO_EH_FRAME 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-#define LIBFFI_GNU_SYMBOL_VERSIONING 1
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 8
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 4
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-/* #undef SYMBOL_UNDERSCORE */
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "a"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+#define FFI_MMAP_EXEC_WRIT 1
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+/* #undef HAVE_AS_CFI_PSEUDO_OP */
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+#define HAVE_AS_X86_PCREL 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+/* #undef HAVE_LONG_DOUBLE */
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+/* #undef HAVE_MKOSTEMP */
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+#define HAVE_MMAP_DEV_ZERO 1
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+#define HAVE_RO_EH_FRAME 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+#define LIBFFI_GNU_SYMBOL_VERSIONING 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 8
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 4
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+/* #undef SYMBOL_UNDERSCORE */
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/i686-pc-linux-android16/include/ffi.h b/contrib/restricted/libffi/configs/i686-pc-linux-android16/include/ffi.h
index 35e667a9af..b0f7592a05 100644
--- a/contrib/restricted/libffi/configs/i686-pc-linux-android16/include/ffi.h
+++ b/contrib/restricted/libffi/configs/i686-pc-linux-android16/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef X86
-#define X86
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 0
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 0
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef X86
+#define X86
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 0
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 0
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 0
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 0
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/i686-pc-linux-android16/include/ffitarget.h b/contrib/restricted/libffi/configs/i686-pc-linux-android16/include/ffitarget.h
index 23c8505403..85ccedfedc 100644
--- a/contrib/restricted/libffi/configs/i686-pc-linux-android16/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/i686-pc-linux-android16/include/ffitarget.h
@@ -1,147 +1,147 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
- Copyright (c) 1996-2003, 2010 Red Hat, Inc.
- Copyright (C) 2008 Free Software Foundation, Inc.
-
- Target configuration macros for x86 and x86-64.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-/* ---- System specific configurations ----------------------------------- */
-
-/* For code common to all platforms on x86 and x86_64. */
-#define X86_ANY
-
-#if defined (X86_64) && defined (__i386__)
-#undef X86_64
-#define X86
-#endif
-
-#ifdef X86_WIN64
-#define FFI_SIZEOF_ARG 8
-#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
-#endif
-
-#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
-#ifndef _MSC_VER
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Generic type definitions ----------------------------------------- */
-
-#ifndef LIBFFI_ASM
-#ifdef X86_WIN64
-#ifdef _MSC_VER
-typedef unsigned __int64 ffi_arg;
-typedef __int64 ffi_sarg;
-#else
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#endif
-#else
-#if defined __x86_64__ && defined __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-#endif
-
-typedef enum ffi_abi {
-#if defined(X86_WIN64)
- FFI_FIRST_ABI = 0,
- FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
- FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
- FFI_LAST_ABI,
-#ifdef __GNUC__
- FFI_DEFAULT_ABI = FFI_GNUW64
-#else
- FFI_DEFAULT_ABI = FFI_WIN64
-#endif
-
-#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
- FFI_FIRST_ABI = 1,
- FFI_UNIX64,
- FFI_WIN64,
- FFI_EFI64 = FFI_WIN64,
- FFI_GNUW64,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_UNIX64
-
-#elif defined(X86_WIN32)
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_STDCALL = 2,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_MS_CDECL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_MS_CDECL
-#else
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_STDCALL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_MS_CDECL = 8,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
-#endif
-} ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-
-#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
-#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
-#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
-#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
-
-#if defined (X86_64) || defined(X86_WIN64) \
- || (defined (__x86_64__) && defined (X86_DARWIN))
-# define FFI_TRAMPOLINE_SIZE 24
-# define FFI_NATIVE_RAW_API 0
-#else
-# define FFI_TRAMPOLINE_SIZE 12
-# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
-#endif
-
-#endif
-
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
+ Copyright (c) 1996-2003, 2010 Red Hat, Inc.
+ Copyright (C) 2008 Free Software Foundation, Inc.
+
+ Target configuration macros for x86 and x86-64.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+/* ---- System specific configurations ----------------------------------- */
+
+/* For code common to all platforms on x86 and x86_64. */
+#define X86_ANY
+
+#if defined (X86_64) && defined (__i386__)
+#undef X86_64
+#define X86
+#endif
+
+#ifdef X86_WIN64
+#define FFI_SIZEOF_ARG 8
+#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
+#endif
+
+#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+#ifndef _MSC_VER
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Generic type definitions ----------------------------------------- */
+
+#ifndef LIBFFI_ASM
+#ifdef X86_WIN64
+#ifdef _MSC_VER
+typedef unsigned __int64 ffi_arg;
+typedef __int64 ffi_sarg;
+#else
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#endif
+#else
+#if defined __x86_64__ && defined __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+#endif
+
+typedef enum ffi_abi {
+#if defined(X86_WIN64)
+ FFI_FIRST_ABI = 0,
+ FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
+ FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
+ FFI_LAST_ABI,
+#ifdef __GNUC__
+ FFI_DEFAULT_ABI = FFI_GNUW64
+#else
+ FFI_DEFAULT_ABI = FFI_WIN64
+#endif
+
+#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
+ FFI_FIRST_ABI = 1,
+ FFI_UNIX64,
+ FFI_WIN64,
+ FFI_EFI64 = FFI_WIN64,
+ FFI_GNUW64,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_UNIX64
+
+#elif defined(X86_WIN32)
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_STDCALL = 2,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_MS_CDECL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_MS_CDECL
+#else
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_STDCALL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_MS_CDECL = 8,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+#endif
+} ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+
+#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
+#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
+#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
+#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
+
+#if defined (X86_64) || defined(X86_WIN64) \
+ || (defined (__x86_64__) && defined (X86_DARWIN))
+# define FFI_TRAMPOLINE_SIZE 24
+# define FFI_NATIVE_RAW_API 0
+#else
+# define FFI_TRAMPOLINE_SIZE 12
+# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
+#endif
+
+#endif
+
diff --git a/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/fficonfig.h b/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/fficonfig.h
index f767119a2f..e258f46aea 100644
--- a/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/fficonfig.h
+++ b/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "a"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-#define FFI_MMAP_EXEC_EMUTRAMP_PAX 1
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-/* #undef FFI_MMAP_EXEC_WRIT */
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-#define HAVE_AS_CFI_PSEUDO_OP 1
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-/* #undef HAVE_AS_X86_PCREL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-/* #undef HAVE_LONG_DOUBLE */
-
-/* Define if you support more than one size of the long double type */
-#define HAVE_LONG_DOUBLE_VARIANT 1
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-#define HAVE_MKOSTEMP 1
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-#define HAVE_MMAP_DEV_ZERO 1
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-#define HAVE_RO_EH_FRAME 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-#define LIBFFI_GNU_SYMBOL_VERSIONING 1
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 16
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 8
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-/* #undef SYMBOL_UNDERSCORE */
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "a"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+#define FFI_MMAP_EXEC_EMUTRAMP_PAX 1
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+/* #undef FFI_MMAP_EXEC_WRIT */
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+#define HAVE_AS_CFI_PSEUDO_OP 1
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+/* #undef HAVE_AS_X86_PCREL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+/* #undef HAVE_LONG_DOUBLE */
+
+/* Define if you support more than one size of the long double type */
+#define HAVE_LONG_DOUBLE_VARIANT 1
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+#define HAVE_MKOSTEMP 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+#define HAVE_MMAP_DEV_ZERO 1
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+#define HAVE_RO_EH_FRAME 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+#define LIBFFI_GNU_SYMBOL_VERSIONING 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 16
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+/* #undef SYMBOL_UNDERSCORE */
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include/ffi.h b/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include/ffi.h
index 3d81d28902..3b1a1bc7a0 100644
--- a/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include/ffi.h
+++ b/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef POWERPC
-#define POWERPC
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 1
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 1
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef POWERPC
+#define POWERPC
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 1
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 1
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 1
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 1
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include/ffitarget.h b/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include/ffitarget.h
index 1a25a43141..7fb9a93908 100644
--- a/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include/ffitarget.h
@@ -1,204 +1,204 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012 Anthony Green
- Copyright (C) 2007, 2008, 2010 Free Software Foundation, Inc
- Copyright (c) 1996-2003 Red Hat, Inc.
-
- Target configuration macros for PowerPC.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-/* ---- System specific configurations ----------------------------------- */
-
-#if defined (POWERPC) && defined (__powerpc64__) /* linux64 */
-#ifndef POWERPC64
-#define POWERPC64
-#endif
-#elif defined (POWERPC_DARWIN) && defined (__ppc64__) /* Darwin64 */
-#ifndef POWERPC64
-#define POWERPC64
-#endif
-#ifndef POWERPC_DARWIN64
-#define POWERPC_DARWIN64
-#endif
-#elif defined (POWERPC_AIX) && defined (__64BIT__) /* AIX64 */
-#ifndef POWERPC64
-#define POWERPC64
-#endif
-#endif
-
-#ifndef LIBFFI_ASM
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-
-typedef enum ffi_abi {
- FFI_FIRST_ABI = 0,
-
-#if defined (POWERPC_AIX)
- FFI_AIX,
- FFI_DARWIN,
- FFI_DEFAULT_ABI = FFI_AIX,
- FFI_LAST_ABI
-
-#elif defined (POWERPC_DARWIN)
- FFI_AIX,
- FFI_DARWIN,
- FFI_DEFAULT_ABI = FFI_DARWIN,
- FFI_LAST_ABI
-
-#else
- /* The FFI_COMPAT values are used by old code. Since libffi may be
- a shared library we have to support old values for backwards
- compatibility. */
- FFI_COMPAT_SYSV,
- FFI_COMPAT_GCC_SYSV,
- FFI_COMPAT_LINUX64,
- FFI_COMPAT_LINUX,
- FFI_COMPAT_LINUX_SOFT_FLOAT,
-
-# if defined (POWERPC64)
- /* This bit, always set in new code, must not be set in any of the
- old FFI_COMPAT values that might be used for 64-bit linux. We
- only need worry about FFI_COMPAT_LINUX64, but to be safe avoid
- all old values. */
- FFI_LINUX = 8,
- /* This and following bits can reuse FFI_COMPAT values. */
- FFI_LINUX_STRUCT_ALIGN = 1,
- FFI_LINUX_LONG_DOUBLE_128 = 2,
- FFI_LINUX_LONG_DOUBLE_IEEE128 = 4,
- FFI_DEFAULT_ABI = (FFI_LINUX
-# ifdef __STRUCT_PARM_ALIGN__
- | FFI_LINUX_STRUCT_ALIGN
-# endif
-# ifdef __LONG_DOUBLE_128__
- | FFI_LINUX_LONG_DOUBLE_128
-# ifdef __LONG_DOUBLE_IEEE128__
- | FFI_LINUX_LONG_DOUBLE_IEEE128
-# endif
-# endif
- ),
- FFI_LAST_ABI = 16
-
-# else
- /* This bit, always set in new code, must not be set in any of the
- old FFI_COMPAT values that might be used for 32-bit linux/sysv/bsd. */
- FFI_SYSV = 8,
- /* This and following bits can reuse FFI_COMPAT values. */
- FFI_SYSV_SOFT_FLOAT = 1,
- FFI_SYSV_STRUCT_RET = 2,
- FFI_SYSV_IBM_LONG_DOUBLE = 4,
- FFI_SYSV_LONG_DOUBLE_128 = 16,
-
- FFI_DEFAULT_ABI = (FFI_SYSV
-# ifdef __NO_FPRS__
- | FFI_SYSV_SOFT_FLOAT
-# endif
-# if (defined (__SVR4_STRUCT_RETURN) \
- || defined (POWERPC_FREEBSD) && !defined (__AIX_STRUCT_RETURN))
- | FFI_SYSV_STRUCT_RET
-# endif
-# if __LDBL_MANT_DIG__ == 106
- | FFI_SYSV_IBM_LONG_DOUBLE
-# endif
-# ifdef __LONG_DOUBLE_128__
- | FFI_SYSV_LONG_DOUBLE_128
-# endif
- ),
- FFI_LAST_ABI = 32
-# endif
-#endif
-
-} ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_NATIVE_RAW_API 0
-#if defined (POWERPC) || defined (POWERPC_FREEBSD)
-# define FFI_GO_CLOSURES 1
-# define FFI_TARGET_SPECIFIC_VARIADIC 1
-# define FFI_EXTRA_CIF_FIELDS unsigned nfixedargs
-#endif
-#if defined (POWERPC_AIX)
-# define FFI_GO_CLOSURES 1
-#endif
-
-/* ppc_closure.S and linux64_closure.S expect this. */
-#define FFI_PPC_TYPE_LAST FFI_TYPE_POINTER
-
-/* We define additional types below. If generic types are added that
- must be supported by powerpc libffi then it is likely that
- FFI_PPC_TYPE_LAST needs increasing *and* the jump tables in
- ppc_closure.S and linux64_closure.S be extended. */
-
-#if !(FFI_TYPE_LAST == FFI_PPC_TYPE_LAST \
- || (FFI_TYPE_LAST == FFI_TYPE_COMPLEX \
- && !defined FFI_TARGET_HAS_COMPLEX_TYPE))
-# error "You likely have a broken powerpc libffi"
-#endif
-
-/* Needed for soft-float long-double-128 support. */
-#define FFI_TYPE_UINT128 (FFI_PPC_TYPE_LAST + 1)
-
-/* Needed for FFI_SYSV small structure returns. */
-#define FFI_SYSV_TYPE_SMALL_STRUCT (FFI_PPC_TYPE_LAST + 2)
-
-/* Used by ELFv2 for homogenous structure returns. */
-#define FFI_V2_TYPE_VECTOR (FFI_PPC_TYPE_LAST + 1)
-#define FFI_V2_TYPE_VECTOR_HOMOG (FFI_PPC_TYPE_LAST + 2)
-#define FFI_V2_TYPE_FLOAT_HOMOG (FFI_PPC_TYPE_LAST + 3)
-#define FFI_V2_TYPE_DOUBLE_HOMOG (FFI_PPC_TYPE_LAST + 4)
-#define FFI_V2_TYPE_SMALL_STRUCT (FFI_PPC_TYPE_LAST + 5)
-
-#if _CALL_ELF == 2
-# define FFI_TRAMPOLINE_SIZE 32
-#else
-# if defined(POWERPC64) || defined(POWERPC_AIX)
-# if defined(POWERPC_DARWIN64)
-# define FFI_TRAMPOLINE_SIZE 48
-# else
-# define FFI_TRAMPOLINE_SIZE 24
-# endif
-# else /* POWERPC || POWERPC_AIX */
-# define FFI_TRAMPOLINE_SIZE 40
-# endif
-#endif
-
-#ifndef LIBFFI_ASM
-#if defined(POWERPC_DARWIN) || defined(POWERPC_AIX)
-struct ffi_aix_trampoline_struct {
- void * code_pointer; /* Pointer to ffi_closure_ASM */
- void * toc; /* TOC */
- void * static_chain; /* Pointer to closure */
-};
-#endif
-#endif
-
-#endif
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012 Anthony Green
+ Copyright (C) 2007, 2008, 2010 Free Software Foundation, Inc
+ Copyright (c) 1996-2003 Red Hat, Inc.
+
+ Target configuration macros for PowerPC.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+/* ---- System specific configurations ----------------------------------- */
+
+#if defined (POWERPC) && defined (__powerpc64__) /* linux64 */
+#ifndef POWERPC64
+#define POWERPC64
+#endif
+#elif defined (POWERPC_DARWIN) && defined (__ppc64__) /* Darwin64 */
+#ifndef POWERPC64
+#define POWERPC64
+#endif
+#ifndef POWERPC_DARWIN64
+#define POWERPC_DARWIN64
+#endif
+#elif defined (POWERPC_AIX) && defined (__64BIT__) /* AIX64 */
+#ifndef POWERPC64
+#define POWERPC64
+#endif
+#endif
+
+#ifndef LIBFFI_ASM
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+
+typedef enum ffi_abi {
+ FFI_FIRST_ABI = 0,
+
+#if defined (POWERPC_AIX)
+ FFI_AIX,
+ FFI_DARWIN,
+ FFI_DEFAULT_ABI = FFI_AIX,
+ FFI_LAST_ABI
+
+#elif defined (POWERPC_DARWIN)
+ FFI_AIX,
+ FFI_DARWIN,
+ FFI_DEFAULT_ABI = FFI_DARWIN,
+ FFI_LAST_ABI
+
+#else
+ /* The FFI_COMPAT values are used by old code. Since libffi may be
+ a shared library we have to support old values for backwards
+ compatibility. */
+ FFI_COMPAT_SYSV,
+ FFI_COMPAT_GCC_SYSV,
+ FFI_COMPAT_LINUX64,
+ FFI_COMPAT_LINUX,
+ FFI_COMPAT_LINUX_SOFT_FLOAT,
+
+# if defined (POWERPC64)
+ /* This bit, always set in new code, must not be set in any of the
+ old FFI_COMPAT values that might be used for 64-bit linux. We
+ only need worry about FFI_COMPAT_LINUX64, but to be safe avoid
+ all old values. */
+ FFI_LINUX = 8,
+ /* This and following bits can reuse FFI_COMPAT values. */
+ FFI_LINUX_STRUCT_ALIGN = 1,
+ FFI_LINUX_LONG_DOUBLE_128 = 2,
+ FFI_LINUX_LONG_DOUBLE_IEEE128 = 4,
+ FFI_DEFAULT_ABI = (FFI_LINUX
+# ifdef __STRUCT_PARM_ALIGN__
+ | FFI_LINUX_STRUCT_ALIGN
+# endif
+# ifdef __LONG_DOUBLE_128__
+ | FFI_LINUX_LONG_DOUBLE_128
+# ifdef __LONG_DOUBLE_IEEE128__
+ | FFI_LINUX_LONG_DOUBLE_IEEE128
+# endif
+# endif
+ ),
+ FFI_LAST_ABI = 16
+
+# else
+ /* This bit, always set in new code, must not be set in any of the
+ old FFI_COMPAT values that might be used for 32-bit linux/sysv/bsd. */
+ FFI_SYSV = 8,
+ /* This and following bits can reuse FFI_COMPAT values. */
+ FFI_SYSV_SOFT_FLOAT = 1,
+ FFI_SYSV_STRUCT_RET = 2,
+ FFI_SYSV_IBM_LONG_DOUBLE = 4,
+ FFI_SYSV_LONG_DOUBLE_128 = 16,
+
+ FFI_DEFAULT_ABI = (FFI_SYSV
+# ifdef __NO_FPRS__
+ | FFI_SYSV_SOFT_FLOAT
+# endif
+# if (defined (__SVR4_STRUCT_RETURN) \
+ || defined (POWERPC_FREEBSD) && !defined (__AIX_STRUCT_RETURN))
+ | FFI_SYSV_STRUCT_RET
+# endif
+# if __LDBL_MANT_DIG__ == 106
+ | FFI_SYSV_IBM_LONG_DOUBLE
+# endif
+# ifdef __LONG_DOUBLE_128__
+ | FFI_SYSV_LONG_DOUBLE_128
+# endif
+ ),
+ FFI_LAST_ABI = 32
+# endif
+#endif
+
+} ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_NATIVE_RAW_API 0
+#if defined (POWERPC) || defined (POWERPC_FREEBSD)
+# define FFI_GO_CLOSURES 1
+# define FFI_TARGET_SPECIFIC_VARIADIC 1
+# define FFI_EXTRA_CIF_FIELDS unsigned nfixedargs
+#endif
+#if defined (POWERPC_AIX)
+# define FFI_GO_CLOSURES 1
+#endif
+
+/* ppc_closure.S and linux64_closure.S expect this. */
+#define FFI_PPC_TYPE_LAST FFI_TYPE_POINTER
+
+/* We define additional types below. If generic types are added that
+ must be supported by powerpc libffi then it is likely that
+ FFI_PPC_TYPE_LAST needs increasing *and* the jump tables in
+ ppc_closure.S and linux64_closure.S be extended. */
+
+#if !(FFI_TYPE_LAST == FFI_PPC_TYPE_LAST \
+ || (FFI_TYPE_LAST == FFI_TYPE_COMPLEX \
+ && !defined FFI_TARGET_HAS_COMPLEX_TYPE))
+# error "You likely have a broken powerpc libffi"
+#endif
+
+/* Needed for soft-float long-double-128 support. */
+#define FFI_TYPE_UINT128 (FFI_PPC_TYPE_LAST + 1)
+
+/* Needed for FFI_SYSV small structure returns. */
+#define FFI_SYSV_TYPE_SMALL_STRUCT (FFI_PPC_TYPE_LAST + 2)
+
+/* Used by ELFv2 for homogenous structure returns. */
+#define FFI_V2_TYPE_VECTOR (FFI_PPC_TYPE_LAST + 1)
+#define FFI_V2_TYPE_VECTOR_HOMOG (FFI_PPC_TYPE_LAST + 2)
+#define FFI_V2_TYPE_FLOAT_HOMOG (FFI_PPC_TYPE_LAST + 3)
+#define FFI_V2_TYPE_DOUBLE_HOMOG (FFI_PPC_TYPE_LAST + 4)
+#define FFI_V2_TYPE_SMALL_STRUCT (FFI_PPC_TYPE_LAST + 5)
+
+#if _CALL_ELF == 2
+# define FFI_TRAMPOLINE_SIZE 32
+#else
+# if defined(POWERPC64) || defined(POWERPC_AIX)
+# if defined(POWERPC_DARWIN64)
+# define FFI_TRAMPOLINE_SIZE 48
+# else
+# define FFI_TRAMPOLINE_SIZE 24
+# endif
+# else /* POWERPC || POWERPC_AIX */
+# define FFI_TRAMPOLINE_SIZE 40
+# endif
+#endif
+
+#ifndef LIBFFI_ASM
+#if defined(POWERPC_DARWIN) || defined(POWERPC_AIX)
+struct ffi_aix_trampoline_struct {
+ void * code_pointer; /* Pointer to ffi_closure_ASM */
+ void * toc; /* TOC */
+ void * static_chain; /* Pointer to closure */
+};
+#endif
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/fficonfig.h b/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/fficonfig.h
index f0564e816c..4657e49a17 100644
--- a/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/fficonfig.h
+++ b/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "aw"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-#define FFI_MMAP_EXEC_WRIT 1
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-#define HAVE_AS_X86_PCREL 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-#define HAVE_LONG_DOUBLE 1
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-#define HAVE_MKOSTEMP 1
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-/* #undef HAVE_MMAP_DEV_ZERO */
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-/* #undef HAVE_RO_EH_FRAME */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 16
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 8
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-#define SYMBOL_UNDERSCORE 1
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "aw"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+#define FFI_MMAP_EXEC_WRIT 1
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+/* #undef HAVE_AS_CFI_PSEUDO_OP */
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+#define HAVE_AS_X86_PCREL 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+#define HAVE_LONG_DOUBLE 1
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+#define HAVE_MKOSTEMP 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+/* #undef HAVE_MMAP_DEV_ZERO */
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+/* #undef HAVE_RO_EH_FRAME */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 16
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+#define SYMBOL_UNDERSCORE 1
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include/ffi.h b/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include/ffi.h
index bbf64b6769..acbb378366 100644
--- a/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include/ffi.h
+++ b/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef X86_64
-#define X86_64
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 1
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 1
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef X86_64
+#define X86_64
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 1
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 1
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 1
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 1
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include/ffitarget.h b/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include/ffitarget.h
index 23c8505403..85ccedfedc 100644
--- a/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include/ffitarget.h
@@ -1,147 +1,147 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
- Copyright (c) 1996-2003, 2010 Red Hat, Inc.
- Copyright (C) 2008 Free Software Foundation, Inc.
-
- Target configuration macros for x86 and x86-64.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-/* ---- System specific configurations ----------------------------------- */
-
-/* For code common to all platforms on x86 and x86_64. */
-#define X86_ANY
-
-#if defined (X86_64) && defined (__i386__)
-#undef X86_64
-#define X86
-#endif
-
-#ifdef X86_WIN64
-#define FFI_SIZEOF_ARG 8
-#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
-#endif
-
-#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
-#ifndef _MSC_VER
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Generic type definitions ----------------------------------------- */
-
-#ifndef LIBFFI_ASM
-#ifdef X86_WIN64
-#ifdef _MSC_VER
-typedef unsigned __int64 ffi_arg;
-typedef __int64 ffi_sarg;
-#else
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#endif
-#else
-#if defined __x86_64__ && defined __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-#endif
-
-typedef enum ffi_abi {
-#if defined(X86_WIN64)
- FFI_FIRST_ABI = 0,
- FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
- FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
- FFI_LAST_ABI,
-#ifdef __GNUC__
- FFI_DEFAULT_ABI = FFI_GNUW64
-#else
- FFI_DEFAULT_ABI = FFI_WIN64
-#endif
-
-#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
- FFI_FIRST_ABI = 1,
- FFI_UNIX64,
- FFI_WIN64,
- FFI_EFI64 = FFI_WIN64,
- FFI_GNUW64,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_UNIX64
-
-#elif defined(X86_WIN32)
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_STDCALL = 2,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_MS_CDECL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_MS_CDECL
-#else
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_STDCALL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_MS_CDECL = 8,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
-#endif
-} ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-
-#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
-#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
-#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
-#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
-
-#if defined (X86_64) || defined(X86_WIN64) \
- || (defined (__x86_64__) && defined (X86_DARWIN))
-# define FFI_TRAMPOLINE_SIZE 24
-# define FFI_NATIVE_RAW_API 0
-#else
-# define FFI_TRAMPOLINE_SIZE 12
-# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
-#endif
-
-#endif
-
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
+ Copyright (c) 1996-2003, 2010 Red Hat, Inc.
+ Copyright (C) 2008 Free Software Foundation, Inc.
+
+ Target configuration macros for x86 and x86-64.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+/* ---- System specific configurations ----------------------------------- */
+
+/* For code common to all platforms on x86 and x86_64. */
+#define X86_ANY
+
+#if defined (X86_64) && defined (__i386__)
+#undef X86_64
+#define X86
+#endif
+
+#ifdef X86_WIN64
+#define FFI_SIZEOF_ARG 8
+#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
+#endif
+
+#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+#ifndef _MSC_VER
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Generic type definitions ----------------------------------------- */
+
+#ifndef LIBFFI_ASM
+#ifdef X86_WIN64
+#ifdef _MSC_VER
+typedef unsigned __int64 ffi_arg;
+typedef __int64 ffi_sarg;
+#else
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#endif
+#else
+#if defined __x86_64__ && defined __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+#endif
+
+typedef enum ffi_abi {
+#if defined(X86_WIN64)
+ FFI_FIRST_ABI = 0,
+ FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
+ FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
+ FFI_LAST_ABI,
+#ifdef __GNUC__
+ FFI_DEFAULT_ABI = FFI_GNUW64
+#else
+ FFI_DEFAULT_ABI = FFI_WIN64
+#endif
+
+#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
+ FFI_FIRST_ABI = 1,
+ FFI_UNIX64,
+ FFI_WIN64,
+ FFI_EFI64 = FFI_WIN64,
+ FFI_GNUW64,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_UNIX64
+
+#elif defined(X86_WIN32)
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_STDCALL = 2,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_MS_CDECL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_MS_CDECL
+#else
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_STDCALL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_MS_CDECL = 8,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+#endif
+} ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+
+#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
+#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
+#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
+#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
+
+#if defined (X86_64) || defined(X86_WIN64) \
+ || (defined (__x86_64__) && defined (X86_DARWIN))
+# define FFI_TRAMPOLINE_SIZE 24
+# define FFI_NATIVE_RAW_API 0
+#else
+# define FFI_TRAMPOLINE_SIZE 12
+# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
+#endif
+
+#endif
+
diff --git a/contrib/restricted/libffi/configs/x86_64-apple-macosx/fficonfig.h b/contrib/restricted/libffi/configs/x86_64-apple-macosx/fficonfig.h
index f0564e816c..4657e49a17 100644
--- a/contrib/restricted/libffi/configs/x86_64-apple-macosx/fficonfig.h
+++ b/contrib/restricted/libffi/configs/x86_64-apple-macosx/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "aw"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-#define FFI_MMAP_EXEC_WRIT 1
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-#define HAVE_AS_X86_PCREL 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-#define HAVE_LONG_DOUBLE 1
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-#define HAVE_MKOSTEMP 1
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-/* #undef HAVE_MMAP_DEV_ZERO */
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-/* #undef HAVE_RO_EH_FRAME */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 16
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 8
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-#define SYMBOL_UNDERSCORE 1
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "aw"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+#define FFI_MMAP_EXEC_WRIT 1
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+/* #undef HAVE_AS_CFI_PSEUDO_OP */
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+#define HAVE_AS_X86_PCREL 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+#define HAVE_LONG_DOUBLE 1
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+#define HAVE_MKOSTEMP 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+/* #undef HAVE_MMAP_DEV_ZERO */
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+/* #undef HAVE_RO_EH_FRAME */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 16
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+#define SYMBOL_UNDERSCORE 1
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/x86_64-apple-macosx/include/ffi.h b/contrib/restricted/libffi/configs/x86_64-apple-macosx/include/ffi.h
index bbf64b6769..acbb378366 100644
--- a/contrib/restricted/libffi/configs/x86_64-apple-macosx/include/ffi.h
+++ b/contrib/restricted/libffi/configs/x86_64-apple-macosx/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef X86_64
-#define X86_64
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 1
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 1
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef X86_64
+#define X86_64
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 1
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 1
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 1
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 1
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/x86_64-apple-macosx/include/ffitarget.h b/contrib/restricted/libffi/configs/x86_64-apple-macosx/include/ffitarget.h
index 23c8505403..85ccedfedc 100644
--- a/contrib/restricted/libffi/configs/x86_64-apple-macosx/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/x86_64-apple-macosx/include/ffitarget.h
@@ -1,147 +1,147 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
- Copyright (c) 1996-2003, 2010 Red Hat, Inc.
- Copyright (C) 2008 Free Software Foundation, Inc.
-
- Target configuration macros for x86 and x86-64.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-/* ---- System specific configurations ----------------------------------- */
-
-/* For code common to all platforms on x86 and x86_64. */
-#define X86_ANY
-
-#if defined (X86_64) && defined (__i386__)
-#undef X86_64
-#define X86
-#endif
-
-#ifdef X86_WIN64
-#define FFI_SIZEOF_ARG 8
-#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
-#endif
-
-#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
-#ifndef _MSC_VER
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Generic type definitions ----------------------------------------- */
-
-#ifndef LIBFFI_ASM
-#ifdef X86_WIN64
-#ifdef _MSC_VER
-typedef unsigned __int64 ffi_arg;
-typedef __int64 ffi_sarg;
-#else
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#endif
-#else
-#if defined __x86_64__ && defined __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-#endif
-
-typedef enum ffi_abi {
-#if defined(X86_WIN64)
- FFI_FIRST_ABI = 0,
- FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
- FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
- FFI_LAST_ABI,
-#ifdef __GNUC__
- FFI_DEFAULT_ABI = FFI_GNUW64
-#else
- FFI_DEFAULT_ABI = FFI_WIN64
-#endif
-
-#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
- FFI_FIRST_ABI = 1,
- FFI_UNIX64,
- FFI_WIN64,
- FFI_EFI64 = FFI_WIN64,
- FFI_GNUW64,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_UNIX64
-
-#elif defined(X86_WIN32)
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_STDCALL = 2,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_MS_CDECL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_MS_CDECL
-#else
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_STDCALL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_MS_CDECL = 8,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
-#endif
-} ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-
-#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
-#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
-#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
-#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
-
-#if defined (X86_64) || defined(X86_WIN64) \
- || (defined (__x86_64__) && defined (X86_DARWIN))
-# define FFI_TRAMPOLINE_SIZE 24
-# define FFI_NATIVE_RAW_API 0
-#else
-# define FFI_TRAMPOLINE_SIZE 12
-# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
-#endif
-
-#endif
-
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
+ Copyright (c) 1996-2003, 2010 Red Hat, Inc.
+ Copyright (C) 2008 Free Software Foundation, Inc.
+
+ Target configuration macros for x86 and x86-64.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+/* ---- System specific configurations ----------------------------------- */
+
+/* For code common to all platforms on x86 and x86_64. */
+#define X86_ANY
+
+#if defined (X86_64) && defined (__i386__)
+#undef X86_64
+#define X86
+#endif
+
+#ifdef X86_WIN64
+#define FFI_SIZEOF_ARG 8
+#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
+#endif
+
+#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+#ifndef _MSC_VER
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Generic type definitions ----------------------------------------- */
+
+#ifndef LIBFFI_ASM
+#ifdef X86_WIN64
+#ifdef _MSC_VER
+typedef unsigned __int64 ffi_arg;
+typedef __int64 ffi_sarg;
+#else
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#endif
+#else
+#if defined __x86_64__ && defined __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+#endif
+
+typedef enum ffi_abi {
+#if defined(X86_WIN64)
+ FFI_FIRST_ABI = 0,
+ FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
+ FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
+ FFI_LAST_ABI,
+#ifdef __GNUC__
+ FFI_DEFAULT_ABI = FFI_GNUW64
+#else
+ FFI_DEFAULT_ABI = FFI_WIN64
+#endif
+
+#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
+ FFI_FIRST_ABI = 1,
+ FFI_UNIX64,
+ FFI_WIN64,
+ FFI_EFI64 = FFI_WIN64,
+ FFI_GNUW64,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_UNIX64
+
+#elif defined(X86_WIN32)
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_STDCALL = 2,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_MS_CDECL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_MS_CDECL
+#else
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_STDCALL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_MS_CDECL = 8,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+#endif
+} ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+
+#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
+#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
+#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
+#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
+
+#if defined (X86_64) || defined(X86_WIN64) \
+ || (defined (__x86_64__) && defined (X86_DARWIN))
+# define FFI_TRAMPOLINE_SIZE 24
+# define FFI_NATIVE_RAW_API 0
+#else
+# define FFI_TRAMPOLINE_SIZE 12
+# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
+#endif
+
+#endif
+
diff --git a/contrib/restricted/libffi/configs/x86_64-microsoft-windows/fficonfig.h b/contrib/restricted/libffi/configs/x86_64-microsoft-windows/fficonfig.h
index 58bc5527fe..738e1e4472 100755
--- a/contrib/restricted/libffi/configs/x86_64-microsoft-windows/fficonfig.h
+++ b/contrib/restricted/libffi/configs/x86_64-microsoft-windows/fficonfig.h
@@ -1,224 +1,224 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-/* #undef EH_FRAME_FLAGS */
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to
- alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
-
-/* Cannot use malloc on this target, so, we revert to
- alternative means */
-/* #undef FFI_MMAP_EXEC_WRIT */
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-/* #undef HAVE_ALLOCA_H */
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
-
-/* Define if your assembler supports PC relative relocs. */
-#define HAVE_AS_X86_PCREL 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-/* #undef HAVE_DLFCN_H */
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-/* #undef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE */
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-/* #undef HAVE_LONG_DOUBLE */
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-/* #undef HAVE_MEMCPY */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-/* #undef HAVE_MKOSTEMP */
-
-/* Define to 1 if you have the `mmap' function. */
-/* #undef HAVE_MMAP */
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-/* #undef HAVE_MMAP_ANON */
-
-/* Define if mmap of /dev/zero works. */
-/* #undef HAVE_MMAP_DEV_ZERO */
-
-/* Define if read-only mmap of a plain file works. */
-/* #undef HAVE_MMAP_FILE */
-
-/* Define if your compiler supports pointer authentication. */
-/* #undef HAVE_PTRAUTH */
-
-/* Define if .eh_frame sections should be read-only. */
-/* #undef HAVE_RO_EH_FRAME */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-/* #undef HAVE_STRINGS_H */
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-/* #undef HAVE_SYS_MMAN_H */
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-/* #undef HAVE_UNISTD_H */
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
-
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
- */
-#define LT_OBJDIR ".libs/"
-
-/* Define to 1 if your C compiler doesn't accept -c and -o together. */
-/* #undef NO_MINUS_C_MINUS_O */
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 8
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 8
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-/* #undef SYMBOL_UNDERSCORE */
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+/* #undef EH_FRAME_FLAGS */
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to
+ alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
+
+/* Cannot use malloc on this target, so, we revert to
+ alternative means */
+/* #undef FFI_MMAP_EXEC_WRIT */
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+/* #undef HAVE_ALLOCA_H */
+
+/* Define if your assembler supports .cfi_* directives. */
+/* #undef HAVE_AS_CFI_PSEUDO_OP */
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
+
+/* Define if your assembler supports PC relative relocs. */
+#define HAVE_AS_X86_PCREL 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+/* #undef HAVE_DLFCN_H */
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+/* #undef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+/* #undef HAVE_LONG_DOUBLE */
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+/* #undef HAVE_MEMCPY */
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+/* #undef HAVE_MKOSTEMP */
+
+/* Define to 1 if you have the `mmap' function. */
+/* #undef HAVE_MMAP */
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+/* #undef HAVE_MMAP_ANON */
+
+/* Define if mmap of /dev/zero works. */
+/* #undef HAVE_MMAP_DEV_ZERO */
+
+/* Define if read-only mmap of a plain file works. */
+/* #undef HAVE_MMAP_FILE */
+
+/* Define if your compiler supports pointer authentication. */
+/* #undef HAVE_PTRAUTH */
+
+/* Define if .eh_frame sections should be read-only. */
+/* #undef HAVE_RO_EH_FRAME */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+/* #undef HAVE_STRINGS_H */
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+/* #undef HAVE_SYS_MMAN_H */
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+/* #undef HAVE_UNISTD_H */
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
+
+/* Define to the sub-directory in which libtool stores uninstalled libraries.
+ */
+#define LT_OBJDIR ".libs/"
+
+/* Define to 1 if your C compiler doesn't accept -c and -o together. */
+/* #undef NO_MINUS_C_MINUS_O */
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 8
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+/* #undef SYMBOL_UNDERSCORE */
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/x86_64-microsoft-windows/include/ffi.h b/contrib/restricted/libffi/configs/x86_64-microsoft-windows/include/ffi.h
index 25ca9cc34e..242481e6f8 100755
--- a/contrib/restricted/libffi/configs/x86_64-microsoft-windows/include/ffi.h
+++ b/contrib/restricted/libffi/configs/x86_64-microsoft-windows/include/ffi.h
@@ -1,523 +1,523 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef X86_WIN64
-#define X86_WIN64
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 0
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 0
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef X86_WIN64
+#define X86_WIN64
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 0
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 0
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+#if defined(PA_LINUX) || defined(PA_HPUX)
+#define FFI_CLOSURE_PTR(X) ((void *)((unsigned int)(X) | 2))
+#define FFI_RESTORE_PTR(X) ((void *)((unsigned int)(X) & ~3))
+#else
+#define FFI_CLOSURE_PTR(X) (X)
+#define FFI_RESTORE_PTR(X) (X)
+#endif
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-#if defined(PA_LINUX) || defined(PA_HPUX)
-#define FFI_CLOSURE_PTR(X) ((void *)((unsigned int)(X) | 2))
-#define FFI_RESTORE_PTR(X) ((void *)((unsigned int)(X) & ~3))
-#else
-#define FFI_CLOSURE_PTR(X) (X)
-#define FFI_RESTORE_PTR(X) (X)
-#endif
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 0
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 0
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/x86_64-microsoft-windows/include/ffitarget.h b/contrib/restricted/libffi/configs/x86_64-microsoft-windows/include/ffitarget.h
index 563afd1375..a34f3e5b70 100755
--- a/contrib/restricted/libffi/configs/x86_64-microsoft-windows/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/x86_64-microsoft-windows/include/ffitarget.h
@@ -1,160 +1,160 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
- Copyright (c) 1996-2003, 2010 Red Hat, Inc.
- Copyright (C) 2008 Free Software Foundation, Inc.
-
- Target configuration macros for x86 and x86-64.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-/* ---- System specific configurations ----------------------------------- */
-
-/* For code common to all platforms on x86 and x86_64. */
-#define X86_ANY
-
-#if defined (X86_64) && defined (__i386__)
-#undef X86_64
-#define X86
-#endif
-
-#ifdef X86_WIN64
-#define FFI_SIZEOF_ARG 8
-#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
-#endif
-
-#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
-#ifndef _MSC_VER
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Generic type definitions ----------------------------------------- */
-
-#ifndef LIBFFI_ASM
-#ifdef X86_WIN64
-#ifdef _MSC_VER
-typedef unsigned __int64 ffi_arg;
-typedef __int64 ffi_sarg;
-#else
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#endif
-#else
-#if defined __x86_64__ && defined __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-#endif
-
-typedef enum ffi_abi {
-#if defined(X86_WIN64)
- FFI_FIRST_ABI = 0,
- FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
- FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
- FFI_LAST_ABI,
-#ifdef __GNUC__
- FFI_DEFAULT_ABI = FFI_GNUW64
-#else
- FFI_DEFAULT_ABI = FFI_WIN64
-#endif
-
-#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
- FFI_FIRST_ABI = 1,
- FFI_UNIX64,
- FFI_WIN64,
- FFI_EFI64 = FFI_WIN64,
- FFI_GNUW64,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_UNIX64
-
-#elif defined(X86_WIN32)
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_STDCALL = 2,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_MS_CDECL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_MS_CDECL
-#else
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_STDCALL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_MS_CDECL = 8,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
-#endif
-} ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-
-#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
-#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
-#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
-#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
-
-#if defined (X86_64) || defined(X86_WIN64) \
- || (defined (__x86_64__) && defined (X86_DARWIN))
-/* 4 bytes of ENDBR64 + 7 bytes of LEA + 6 bytes of JMP + 7 bytes of NOP
- + 8 bytes of pointer. */
-# define FFI_TRAMPOLINE_SIZE 32
-# define FFI_NATIVE_RAW_API 0
-#else
-/* 4 bytes of ENDBR32 + 5 bytes of MOV + 5 bytes of JMP + 2 unused
- bytes. */
-# define FFI_TRAMPOLINE_SIZE 16
-# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
-#endif
-
-#if !defined(GENERATE_LIBFFI_MAP) && defined(__ASSEMBLER__) \
- && defined(__CET__)
-# include <cet.h>
-# define _CET_NOTRACK notrack
-#else
-# define _CET_ENDBR
-# define _CET_NOTRACK
-#endif
-
-#endif
-
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
+ Copyright (c) 1996-2003, 2010 Red Hat, Inc.
+ Copyright (C) 2008 Free Software Foundation, Inc.
+
+ Target configuration macros for x86 and x86-64.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+/* ---- System specific configurations ----------------------------------- */
+
+/* For code common to all platforms on x86 and x86_64. */
+#define X86_ANY
+
+#if defined (X86_64) && defined (__i386__)
+#undef X86_64
+#define X86
+#endif
+
+#ifdef X86_WIN64
+#define FFI_SIZEOF_ARG 8
+#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
+#endif
+
+#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+#ifndef _MSC_VER
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Generic type definitions ----------------------------------------- */
+
+#ifndef LIBFFI_ASM
+#ifdef X86_WIN64
+#ifdef _MSC_VER
+typedef unsigned __int64 ffi_arg;
+typedef __int64 ffi_sarg;
+#else
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#endif
+#else
+#if defined __x86_64__ && defined __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+#endif
+
+typedef enum ffi_abi {
+#if defined(X86_WIN64)
+ FFI_FIRST_ABI = 0,
+ FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
+ FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
+ FFI_LAST_ABI,
+#ifdef __GNUC__
+ FFI_DEFAULT_ABI = FFI_GNUW64
+#else
+ FFI_DEFAULT_ABI = FFI_WIN64
+#endif
+
+#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
+ FFI_FIRST_ABI = 1,
+ FFI_UNIX64,
+ FFI_WIN64,
+ FFI_EFI64 = FFI_WIN64,
+ FFI_GNUW64,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_UNIX64
+
+#elif defined(X86_WIN32)
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_STDCALL = 2,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_MS_CDECL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_MS_CDECL
+#else
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_STDCALL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_MS_CDECL = 8,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+#endif
+} ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+
+#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
+#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
+#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
+#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
+
+#if defined (X86_64) || defined(X86_WIN64) \
+ || (defined (__x86_64__) && defined (X86_DARWIN))
+/* 4 bytes of ENDBR64 + 7 bytes of LEA + 6 bytes of JMP + 7 bytes of NOP
+ + 8 bytes of pointer. */
+# define FFI_TRAMPOLINE_SIZE 32
+# define FFI_NATIVE_RAW_API 0
+#else
+/* 4 bytes of ENDBR32 + 5 bytes of MOV + 5 bytes of JMP + 2 unused
+ bytes. */
+# define FFI_TRAMPOLINE_SIZE 16
+# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
+#endif
+
+#if !defined(GENERATE_LIBFFI_MAP) && defined(__ASSEMBLER__) \
+ && defined(__CET__)
+# include <cet.h>
+# define _CET_NOTRACK notrack
+#else
+# define _CET_ENDBR
+# define _CET_NOTRACK
+#endif
+
+#endif
+
diff --git a/contrib/restricted/libffi/configs/x86_64-microsoft-windows/win64_intel.masm b/contrib/restricted/libffi/configs/x86_64-microsoft-windows/win64_intel.masm
index 83d68387f8..d033d2d2d1 100644
--- a/contrib/restricted/libffi/configs/x86_64-microsoft-windows/win64_intel.masm
+++ b/contrib/restricted/libffi/configs/x86_64-microsoft-windows/win64_intel.masm
@@ -1,1204 +1,1204 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- .CODE
- extern abort:near
- extern ffi_closure_win64_inner:near
-
-
-
-
-
-
-
- ALIGN 8
- PUBLIC ffi_call_win64
-
- ; .safesh ffi_call_win64
-ffi_call_win64 proc frame
-
-
- mov RAX, [RSP] ; movq (%rsp), %rax
- mov [rdx], RBP ; movq %rbp, (rdx)
- mov [rdx + 8], RAX; movq %rax, 8(rdx)
- mov RBP, rdx; movq rdx, %rbp
-
-
- .pushreg rbp
- .setframe rbp, 0
- .endprolog
- mov RSP, rcx ; movq rcx, %rsp
-
- mov R10, r8 ; movq r8, %r10
-
-
- mov RCX, [RSP] ; movq (%rsp), %rcx
- movsd XMM0, qword ptr [RSP] ; movsd (%rsp), %xmm0
- mov RDX, [RSP + 8] ;movq 8(%rsp), %rdx
- movsd XMM1, qword ptr [RSP + 8]; movsd 8(%rsp), %xmm1
- mov R8, [RSP + 16] ; movq 16(%rsp), %r8
- movsd XMM2, qword ptr [RSP + 16] ; movsd 16(%rsp), %xmm2
- mov R9, [RSP + 24] ; movq 24(%rsp), %r9
- movsd XMM3, qword ptr [RSP + 24] ;movsd 24(%rsp), %xmm3
-
- CALL qword ptr [RBP + 16] ; call *16(%rbp)
-
- mov ECX, [RBP + 24] ; movl 24(%rbp), %ecx
- mov R8, [RBP + 32] ; movq 32(%rbp), %r8
- LEA R10, ffi_call_win64_tab ; leaq 0f(%rip), %r10
- CMP ECX, (15 + 3) ; cmpl $FFI_TYPE_SMALL_STRUCT_4B, %ecx
- LEA R10, [R10 + RCX*8] ; leaq (%r10, %rcx, 8), %r10
- JA L99 ; ja 99f
- JMP R10 ; jmp *%r10
-
-
-
-epilogue macro
- LEAVE
-
-
-
- RET
-
-endm
-
- ALIGN 8
-ffi_call_win64_tab LABEL NEAR
-ALIGN 8; ORG 0b + 0 * 8
- epilogue
-ALIGN 8; ORG 0b + 1 * 8
- movsxd rax, eax ; movslq %eax, %rax
- mov qword ptr [r8], rax; movq %rax, (%r8)
- epilogue
-ALIGN 8; ORG 0b + 2 * 8
- movss dword ptr [r8], xmm0 ; movss %xmm0, (%r8)
- epilogue
-ALIGN 8; ORG 0b + 3 * 8
- movsd qword ptr[r8], xmm0; movsd %xmm0, (%r8)
- epilogue
-ALIGN 8; ORG 0b + 3 * 8
- call abort
-ALIGN 8; ORG 0b + 5 * 8
- movzx eax, al ;movzbl %al, %eax
- mov qword ptr[r8], rax; movq %rax, (%r8)
- epilogue
-ALIGN 8; ORG 0b + 6 * 8
- movsx rax, al ; movsbq %al, %rax
- jmp L98
-ALIGN 8; ORG 0b + 7 * 8
- movzx eax, ax ; movzwl %ax, %eax
- mov qword ptr[r8], rax; movq %rax, (%r8)
- epilogue
-ALIGN 8; ORG 0b + 8 * 8
- movsx rax, ax; movswq %ax, %rax
- jmp L98
-ALIGN 8; ORG 0b + 9 * 8
- mov eax, eax; movl %eax, %eax
- mov qword ptr[r8], rax ; movq %rax, (%r8)
- epilogue
-ALIGN 8; ORG 0b + 10 * 8
- movsxd rax, eax; movslq %eax, %rax
- mov qword ptr [r8], rax; movq %rax, (%r8)
- epilogue
-ALIGN 8; ORG 0b + 11 * 8
-L98 LABEL near
- mov qword ptr [r8], rax ; movq %rax, (%r8)
- epilogue
-ALIGN 8; ORG 0b + 12 * 8
- mov qword ptr [r8], rax;movq %rax, (%r8)
- epilogue
-ALIGN 8; ORG 0b + 13 * 8
- epilogue
-ALIGN 8; ORG 0b + 14 * 8
- mov qword ptr [r8], rax ;movq %rax, (%r8)
- epilogue
-ALIGN 8; ORG 0b + 15 * 8
- call abort
-ALIGN 8; ORG 0b + (15 + 1) * 8
- mov byte ptr [r8], al ; movb %al, (%r8)
- epilogue
-ALIGN 8; ORG 0b + (15 + 2) * 8
- mov word ptr [r8], ax ; movw %ax, (%r8)
- epilogue
-ALIGN 8; ORG 0b + (15 + 3) * 8
- mov dword ptr [r8], eax ; movl %eax, (%r8)
- epilogue
-
- align 8
-L99 LABEL near
- call abort
-
- epilogue
-
-
- ffi_call_win64 endp
-
-
-
-
-
-
-
-
- align 8
- PUBLIC ffi_go_closure_win64
-
-ffi_go_closure_win64 proc
-
-
- mov qword ptr [rsp + 8], rcx; movq %rcx, 8(%rsp)
- mov qword ptr [rsp + 16], rdx; movq %rdx, 16(%rsp)
- mov qword ptr [rsp + 24], r8; movq %r8, 24(%rsp)
- mov qword ptr [rsp + 32], r9 ;movq %r9, 32(%rsp)
-
- mov rcx, qword ptr [r10 + 8]; movq 8(%r10), %rcx
- mov rdx, qword ptr [r10 + 16]; movq 16(%r10), %rdx
- mov r8, r10 ; movq %r10, %r8
- jmp ffi_closure_win64_2
-
- ffi_go_closure_win64 endp
-
- align 8
-
-PUBLIC ffi_closure_win64
-ffi_closure_win64 PROC FRAME
-
-
- mov qword ptr [rsp + 8], rcx; movq %rcx, 8(%rsp)
- mov qword ptr [rsp + 16], rdx; movq %rdx, 16(%rsp)
- mov qword ptr [rsp + 24], r8; movq %r8, 24(%rsp)
- mov qword ptr [rsp + 32], r9; movq %r9, 32(%rsp)
-
- mov rcx, qword ptr [24 + r10] ;movq 24(%r10), %rcx
- mov rdx, qword ptr [24 + 8 + r10] ; movq 24+8(%r10), %rdx
- mov r8, qword ptr [24+16+r10] ;movq 24+16(%r10), %r8
-ffi_closure_win64_2 LABEL near
- sub rsp, (32+8+16+32) ;subq $ffi_clo_FS, %rsp
-
- .allocstack (32+8+16+32)
- .endprolog
-
-
- movsd qword ptr [(32+8+16) + rsp], xmm0 ; movsd %xmm0, (32+8+16)(%rsp)
- movsd qword ptr [(32+8+16)+8+rsp], xmm1 ; movsd %xmm1, (32+8+16)+8(%rsp)
- movsd qword ptr [(32+8+16)+16+rsp], xmm2 ; movsd %xmm2, (32+8+16)+16(%rsp)
- movsd qword ptr [(32+8+16)+24+rsp], xmm3 ; movsd %xmm3, (32+8+16)+24(%rsp)
-
- lea r9, [(32+8) + rsp] ; leaq (32+8)(%rsp), %r9
- call ffi_closure_win64_inner
-
-
-
- mov rax, qword ptr [(32+8) + rsp] ;movq (32+8)(%rsp), %rax
- movsd xmm0, qword ptr [rsp + (32+8)] ;movsd (32+8)(%rsp), %xmm0
-
- add rsp, (32+8+16+32) ;addq $ffi_clo_FS, %rsp
-
- ret
-
-
- ffi_closure_win64 endp
-
-
-
-
-_text ends
-end
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ .CODE
+ extern abort:near
+ extern ffi_closure_win64_inner:near
+
+
+
+
+
+
+
+ ALIGN 8
+ PUBLIC ffi_call_win64
+
+ ; .safesh ffi_call_win64
+ffi_call_win64 proc frame
+
+
+ mov RAX, [RSP] ; movq (%rsp), %rax
+ mov [rdx], RBP ; movq %rbp, (rdx)
+ mov [rdx + 8], RAX; movq %rax, 8(rdx)
+ mov RBP, rdx; movq rdx, %rbp
+
+
+ .pushreg rbp
+ .setframe rbp, 0
+ .endprolog
+ mov RSP, rcx ; movq rcx, %rsp
+
+ mov R10, r8 ; movq r8, %r10
+
+
+ mov RCX, [RSP] ; movq (%rsp), %rcx
+ movsd XMM0, qword ptr [RSP] ; movsd (%rsp), %xmm0
+ mov RDX, [RSP + 8] ;movq 8(%rsp), %rdx
+ movsd XMM1, qword ptr [RSP + 8]; movsd 8(%rsp), %xmm1
+ mov R8, [RSP + 16] ; movq 16(%rsp), %r8
+ movsd XMM2, qword ptr [RSP + 16] ; movsd 16(%rsp), %xmm2
+ mov R9, [RSP + 24] ; movq 24(%rsp), %r9
+ movsd XMM3, qword ptr [RSP + 24] ;movsd 24(%rsp), %xmm3
+
+ CALL qword ptr [RBP + 16] ; call *16(%rbp)
+
+ mov ECX, [RBP + 24] ; movl 24(%rbp), %ecx
+ mov R8, [RBP + 32] ; movq 32(%rbp), %r8
+ LEA R10, ffi_call_win64_tab ; leaq 0f(%rip), %r10
+ CMP ECX, (15 + 3) ; cmpl $FFI_TYPE_SMALL_STRUCT_4B, %ecx
+ LEA R10, [R10 + RCX*8] ; leaq (%r10, %rcx, 8), %r10
+ JA L99 ; ja 99f
+ JMP R10 ; jmp *%r10
+
+
+
+epilogue macro
+ LEAVE
+
+
+
+ RET
+
+endm
+
+ ALIGN 8
+ffi_call_win64_tab LABEL NEAR
+ALIGN 8; ORG 0b + 0 * 8
+ epilogue
+ALIGN 8; ORG 0b + 1 * 8
+ movsxd rax, eax ; movslq %eax, %rax
+ mov qword ptr [r8], rax; movq %rax, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + 2 * 8
+ movss dword ptr [r8], xmm0 ; movss %xmm0, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + 3 * 8
+ movsd qword ptr[r8], xmm0; movsd %xmm0, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + 3 * 8
+ call abort
+ALIGN 8; ORG 0b + 5 * 8
+ movzx eax, al ;movzbl %al, %eax
+ mov qword ptr[r8], rax; movq %rax, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + 6 * 8
+ movsx rax, al ; movsbq %al, %rax
+ jmp L98
+ALIGN 8; ORG 0b + 7 * 8
+ movzx eax, ax ; movzwl %ax, %eax
+ mov qword ptr[r8], rax; movq %rax, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + 8 * 8
+ movsx rax, ax; movswq %ax, %rax
+ jmp L98
+ALIGN 8; ORG 0b + 9 * 8
+ mov eax, eax; movl %eax, %eax
+ mov qword ptr[r8], rax ; movq %rax, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + 10 * 8
+ movsxd rax, eax; movslq %eax, %rax
+ mov qword ptr [r8], rax; movq %rax, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + 11 * 8
+L98 LABEL near
+ mov qword ptr [r8], rax ; movq %rax, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + 12 * 8
+ mov qword ptr [r8], rax;movq %rax, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + 13 * 8
+ epilogue
+ALIGN 8; ORG 0b + 14 * 8
+ mov qword ptr [r8], rax ;movq %rax, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + 15 * 8
+ call abort
+ALIGN 8; ORG 0b + (15 + 1) * 8
+ mov byte ptr [r8], al ; movb %al, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + (15 + 2) * 8
+ mov word ptr [r8], ax ; movw %ax, (%r8)
+ epilogue
+ALIGN 8; ORG 0b + (15 + 3) * 8
+ mov dword ptr [r8], eax ; movl %eax, (%r8)
+ epilogue
+
+ align 8
+L99 LABEL near
+ call abort
+
+ epilogue
+
+
+ ffi_call_win64 endp
+
+
+
+
+
+
+
+
+ align 8
+ PUBLIC ffi_go_closure_win64
+
+ffi_go_closure_win64 proc
+
+
+ mov qword ptr [rsp + 8], rcx; movq %rcx, 8(%rsp)
+ mov qword ptr [rsp + 16], rdx; movq %rdx, 16(%rsp)
+ mov qword ptr [rsp + 24], r8; movq %r8, 24(%rsp)
+ mov qword ptr [rsp + 32], r9 ;movq %r9, 32(%rsp)
+
+ mov rcx, qword ptr [r10 + 8]; movq 8(%r10), %rcx
+ mov rdx, qword ptr [r10 + 16]; movq 16(%r10), %rdx
+ mov r8, r10 ; movq %r10, %r8
+ jmp ffi_closure_win64_2
+
+ ffi_go_closure_win64 endp
+
+ align 8
+
+PUBLIC ffi_closure_win64
+ffi_closure_win64 PROC FRAME
+
+
+ mov qword ptr [rsp + 8], rcx; movq %rcx, 8(%rsp)
+ mov qword ptr [rsp + 16], rdx; movq %rdx, 16(%rsp)
+ mov qword ptr [rsp + 24], r8; movq %r8, 24(%rsp)
+ mov qword ptr [rsp + 32], r9; movq %r9, 32(%rsp)
+
+ mov rcx, qword ptr [24 + r10] ;movq 24(%r10), %rcx
+ mov rdx, qword ptr [24 + 8 + r10] ; movq 24+8(%r10), %rdx
+ mov r8, qword ptr [24+16+r10] ;movq 24+16(%r10), %r8
+ffi_closure_win64_2 LABEL near
+ sub rsp, (32+8+16+32) ;subq $ffi_clo_FS, %rsp
+
+ .allocstack (32+8+16+32)
+ .endprolog
+
+
+ movsd qword ptr [(32+8+16) + rsp], xmm0 ; movsd %xmm0, (32+8+16)(%rsp)
+ movsd qword ptr [(32+8+16)+8+rsp], xmm1 ; movsd %xmm1, (32+8+16)+8(%rsp)
+ movsd qword ptr [(32+8+16)+16+rsp], xmm2 ; movsd %xmm2, (32+8+16)+16(%rsp)
+ movsd qword ptr [(32+8+16)+24+rsp], xmm3 ; movsd %xmm3, (32+8+16)+24(%rsp)
+
+ lea r9, [(32+8) + rsp] ; leaq (32+8)(%rsp), %r9
+ call ffi_closure_win64_inner
+
+
+
+ mov rax, qword ptr [(32+8) + rsp] ;movq (32+8)(%rsp), %rax
+ movsd xmm0, qword ptr [rsp + (32+8)] ;movsd (32+8)(%rsp), %xmm0
+
+ add rsp, (32+8+16+32) ;addq $ffi_clo_FS, %rsp
+
+ ret
+
+
+ ffi_closure_win64 endp
+
+
+
+
+_text ends
+end
diff --git a/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/fficonfig.h b/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/fficonfig.h
index 1bf03524c4..1a8e02aa11 100644
--- a/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/fficonfig.h
+++ b/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "a"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-#define FFI_MMAP_EXEC_WRIT 1
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-#define HAVE_AS_X86_64_UNWIND_SECTION_TYPE 1
-
-/* Define if your assembler supports PC relative relocs. */
-#define HAVE_AS_X86_PCREL 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-#define HAVE_LONG_DOUBLE 1
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-/* #undef HAVE_MKOSTEMP */
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-#define HAVE_MMAP_DEV_ZERO 1
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-#define HAVE_RO_EH_FRAME 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-#define LIBFFI_GNU_SYMBOL_VERSIONING 1
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 16
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 8
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-/* #undef SYMBOL_UNDERSCORE */
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "a"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+#define FFI_MMAP_EXEC_WRIT 1
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+/* #undef HAVE_AS_CFI_PSEUDO_OP */
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+#define HAVE_AS_X86_64_UNWIND_SECTION_TYPE 1
+
+/* Define if your assembler supports PC relative relocs. */
+#define HAVE_AS_X86_PCREL 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+#define HAVE_LONG_DOUBLE 1
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+/* #undef HAVE_MKOSTEMP */
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+#define HAVE_MMAP_DEV_ZERO 1
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+#define HAVE_RO_EH_FRAME 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+#define LIBFFI_GNU_SYMBOL_VERSIONING 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 16
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+/* #undef SYMBOL_UNDERSCORE */
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include/ffi.h b/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include/ffi.h
index bbf64b6769..acbb378366 100644
--- a/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include/ffi.h
+++ b/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef X86_64
-#define X86_64
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 1
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 1
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef X86_64
+#define X86_64
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 1
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 1
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 1
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 1
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include/ffitarget.h b/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include/ffitarget.h
index 23c8505403..85ccedfedc 100644
--- a/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include/ffitarget.h
@@ -1,147 +1,147 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
- Copyright (c) 1996-2003, 2010 Red Hat, Inc.
- Copyright (C) 2008 Free Software Foundation, Inc.
-
- Target configuration macros for x86 and x86-64.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-/* ---- System specific configurations ----------------------------------- */
-
-/* For code common to all platforms on x86 and x86_64. */
-#define X86_ANY
-
-#if defined (X86_64) && defined (__i386__)
-#undef X86_64
-#define X86
-#endif
-
-#ifdef X86_WIN64
-#define FFI_SIZEOF_ARG 8
-#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
-#endif
-
-#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
-#ifndef _MSC_VER
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Generic type definitions ----------------------------------------- */
-
-#ifndef LIBFFI_ASM
-#ifdef X86_WIN64
-#ifdef _MSC_VER
-typedef unsigned __int64 ffi_arg;
-typedef __int64 ffi_sarg;
-#else
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#endif
-#else
-#if defined __x86_64__ && defined __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-#endif
-
-typedef enum ffi_abi {
-#if defined(X86_WIN64)
- FFI_FIRST_ABI = 0,
- FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
- FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
- FFI_LAST_ABI,
-#ifdef __GNUC__
- FFI_DEFAULT_ABI = FFI_GNUW64
-#else
- FFI_DEFAULT_ABI = FFI_WIN64
-#endif
-
-#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
- FFI_FIRST_ABI = 1,
- FFI_UNIX64,
- FFI_WIN64,
- FFI_EFI64 = FFI_WIN64,
- FFI_GNUW64,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_UNIX64
-
-#elif defined(X86_WIN32)
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_STDCALL = 2,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_MS_CDECL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_MS_CDECL
-#else
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_STDCALL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_MS_CDECL = 8,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
-#endif
-} ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-
-#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
-#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
-#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
-#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
-
-#if defined (X86_64) || defined(X86_WIN64) \
- || (defined (__x86_64__) && defined (X86_DARWIN))
-# define FFI_TRAMPOLINE_SIZE 24
-# define FFI_NATIVE_RAW_API 0
-#else
-# define FFI_TRAMPOLINE_SIZE 12
-# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
-#endif
-
-#endif
-
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
+ Copyright (c) 1996-2003, 2010 Red Hat, Inc.
+ Copyright (C) 2008 Free Software Foundation, Inc.
+
+ Target configuration macros for x86 and x86-64.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+/* ---- System specific configurations ----------------------------------- */
+
+/* For code common to all platforms on x86 and x86_64. */
+#define X86_ANY
+
+#if defined (X86_64) && defined (__i386__)
+#undef X86_64
+#define X86
+#endif
+
+#ifdef X86_WIN64
+#define FFI_SIZEOF_ARG 8
+#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
+#endif
+
+#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+#ifndef _MSC_VER
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Generic type definitions ----------------------------------------- */
+
+#ifndef LIBFFI_ASM
+#ifdef X86_WIN64
+#ifdef _MSC_VER
+typedef unsigned __int64 ffi_arg;
+typedef __int64 ffi_sarg;
+#else
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#endif
+#else
+#if defined __x86_64__ && defined __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+#endif
+
+typedef enum ffi_abi {
+#if defined(X86_WIN64)
+ FFI_FIRST_ABI = 0,
+ FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
+ FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
+ FFI_LAST_ABI,
+#ifdef __GNUC__
+ FFI_DEFAULT_ABI = FFI_GNUW64
+#else
+ FFI_DEFAULT_ABI = FFI_WIN64
+#endif
+
+#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
+ FFI_FIRST_ABI = 1,
+ FFI_UNIX64,
+ FFI_WIN64,
+ FFI_EFI64 = FFI_WIN64,
+ FFI_GNUW64,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_UNIX64
+
+#elif defined(X86_WIN32)
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_STDCALL = 2,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_MS_CDECL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_MS_CDECL
+#else
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_STDCALL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_MS_CDECL = 8,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+#endif
+} ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+
+#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
+#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
+#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
+#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
+
+#if defined (X86_64) || defined(X86_WIN64) \
+ || (defined (__x86_64__) && defined (X86_DARWIN))
+# define FFI_TRAMPOLINE_SIZE 24
+# define FFI_NATIVE_RAW_API 0
+#else
+# define FFI_TRAMPOLINE_SIZE 12
+# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
+#endif
+
+#endif
+
diff --git a/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/fficonfig.h b/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/fficonfig.h
index eaabe46946..b36ac096c3 100644
--- a/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/fficonfig.h
+++ b/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/fficonfig.h
@@ -1,215 +1,215 @@
-/* fficonfig.h. Generated from fficonfig.h.in by configure. */
-/* fficonfig.h.in. Generated from configure.ac by autoheader. */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
- systems. This function is required for `alloca.c' support on those systems.
- */
-/* #undef CRAY_STACKSEG_END */
-
-/* Define to 1 if using `alloca.c'. */
-/* #undef C_ALLOCA */
-
-/* Define to the flags needed for the .section .eh_frame directive. */
-#define EH_FRAME_FLAGS "a"
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
-/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
-
-/* Define this if you want to enable pax emulated trampolines */
-#define FFI_MMAP_EXEC_EMUTRAMP_PAX 1
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-/* #undef FFI_MMAP_EXEC_WRIT */
-
-/* Define this if you do not want support for the raw API. */
-/* #undef FFI_NO_RAW_API */
-
-/* Define this if you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
-
-/* Define to 1 if you have `alloca', as a function or macro. */
-#define HAVE_ALLOCA 1
-
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
- */
-#define HAVE_ALLOCA_H 1
-
-/* Define if your assembler supports .cfi_* directives. */
-#define HAVE_AS_CFI_PSEUDO_OP 1
-
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if the compiler uses zarch features. */
-/* #undef HAVE_AS_S390_ZARCH */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
- */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports unwind section type. */
-#define HAVE_AS_X86_64_UNWIND_SECTION_TYPE 1
-
-/* Define if your assembler supports PC relative relocs. */
-#define HAVE_AS_X86_PCREL 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define if you have the long double type and it is bigger than a double */
-#define HAVE_LONG_DOUBLE 1
-
-/* Define if you support more than one size of the long double type */
-/* #undef HAVE_LONG_DOUBLE_VARIANT */
-
-/* Define to 1 if you have the `memcpy' function. */
-#define HAVE_MEMCPY 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkostemp' function. */
-#define HAVE_MKOSTEMP 1
-
-/* Define to 1 if you have the `mmap' function. */
-#define HAVE_MMAP 1
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-#define HAVE_MMAP_ANON 1
-
-/* Define if mmap of /dev/zero works. */
-#define HAVE_MMAP_DEV_ZERO 1
-
-/* Define if read-only mmap of a plain file works. */
-#define HAVE_MMAP_FILE 1
-
-/* Define if .eh_frame sections should be read-only. */
-#define HAVE_RO_EH_FRAME 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#define HAVE_SYS_MMAN_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if GNU symbol versioning is used for libatomic. */
-#define LIBFFI_GNU_SYMBOL_VERSIONING 1
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Name of package */
-#define PACKAGE "libffi"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libffi"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libffi 3.3"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libffi"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "3.3"
-
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 16
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 8
-
-/* If using the C implementation of alloca, define if you know the
- direction of stack growth for your system; otherwise it will be
- automatically deduced at runtime.
- STACK_DIRECTION > 0 => grows toward higher addresses
- STACK_DIRECTION < 0 => grows toward lower addresses
- STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if symbols are underscored. */
-/* #undef SYMBOL_UNDERSCORE */
-
-/* Define this if you are using Purify and want to suppress spurious messages.
- */
-/* #undef USING_PURIFY */
-
-/* Version number of package */
-#define VERSION "3.3"
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
- significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-# define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* # undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#ifdef __APPLE__
-#define FFI_HIDDEN(name) .private_extern name
-#else
-#define FFI_HIDDEN(name) .hidden name
-#endif
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-
+/* fficonfig.h. Generated from fficonfig.h.in by configure. */
+/* fficonfig.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+ systems. This function is required for `alloca.c' support on those systems.
+ */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to the flags needed for the .section .eh_frame directive. */
+#define EH_FRAME_FLAGS "a"
+
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
+
+/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
+/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
+
+/* Define this if you want to enable pax emulated trampolines */
+#define FFI_MMAP_EXEC_EMUTRAMP_PAX 1
+
+/* Cannot use malloc on this target, so, we revert to alternative means */
+/* #undef FFI_MMAP_EXEC_WRIT */
+
+/* Define this if you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
+
+/* Define this if you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
+#define HAVE_ALLOCA_H 1
+
+/* Define if your assembler supports .cfi_* directives. */
+#define HAVE_AS_CFI_PSEUDO_OP 1
+
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
+
+/* Define if the compiler uses zarch features. */
+/* #undef HAVE_AS_S390_ZARCH */
+
+/* Define if your assembler and linker support unaligned PC relative relocs.
+ */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
+
+/* Define if your assembler supports unwind section type. */
+#define HAVE_AS_X86_64_UNWIND_SECTION_TYPE 1
+
+/* Define if your assembler supports PC relative relocs. */
+#define HAVE_AS_X86_PCREL 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define if __attribute__((visibility("hidden"))) is supported. */
+#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define if you have the long double type and it is bigger than a double */
+#define HAVE_LONG_DOUBLE 1
+
+/* Define if you support more than one size of the long double type */
+/* #undef HAVE_LONG_DOUBLE_VARIANT */
+
+/* Define to 1 if you have the `memcpy' function. */
+#define HAVE_MEMCPY 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkostemp' function. */
+#define HAVE_MKOSTEMP 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define HAVE_MMAP 1
+
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+#define HAVE_MMAP_ANON 1
+
+/* Define if mmap of /dev/zero works. */
+#define HAVE_MMAP_DEV_ZERO 1
+
+/* Define if read-only mmap of a plain file works. */
+#define HAVE_MMAP_FILE 1
+
+/* Define if .eh_frame sections should be read-only. */
+#define HAVE_RO_EH_FRAME 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if GNU symbol versioning is used for libatomic. */
+#define LIBFFI_GNU_SYMBOL_VERSIONING 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libffi"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libffi"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libffi 3.3"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libffi"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "3.3"
+
+/* The size of `double', as computed by sizeof. */
+#define SIZEOF_DOUBLE 8
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 16
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* If using the C implementation of alloca, define if you know the
+ direction of stack growth for your system; otherwise it will be
+ automatically deduced at runtime.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if symbols are underscored. */
+/* #undef SYMBOL_UNDERSCORE */
+
+/* Define this if you are using Purify and want to suppress spurious messages.
+ */
+/* #undef USING_PURIFY */
+
+/* Version number of package */
+#define VERSION "3.3"
+
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* # undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+
+#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+#ifdef LIBFFI_ASM
+#ifdef __APPLE__
+#define FFI_HIDDEN(name) .private_extern name
+#else
+#define FFI_HIDDEN(name) .hidden name
+#endif
+#else
+#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
+#endif
+#else
+#ifdef LIBFFI_ASM
+#define FFI_HIDDEN(name)
+#else
+#define FFI_HIDDEN
+#endif
+#endif
+
diff --git a/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include/ffi.h b/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include/ffi.h
index bbf64b6769..acbb378366 100644
--- a/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include/ffi.h
+++ b/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include/ffi.h
@@ -1,515 +1,515 @@
-/* -----------------------------------------------------------------*-C-*-
- libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
- - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the ``Software''), to deal in the Software without
- restriction, including without limitation the rights to use, copy,
- modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-/* -------------------------------------------------------------------
- Most of the API is documented in doc/libffi.texi.
-
- The raw API is designed to bypass some of the argument packing and
- unpacking on architectures for which it can be avoided. Routines
- are provided to emulate the raw API if the underlying platform
- doesn't allow faster implementation.
-
- More details on the raw API can be found in:
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
-
- and
-
- http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
- -------------------------------------------------------------------- */
-
-#ifndef LIBFFI_H
-#define LIBFFI_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Specify which architecture libffi is configured for. */
-#ifndef X86_64
-#define X86_64
-#endif
-
-/* ---- System configuration information --------------------------------- */
-
-#include <ffitarget.h>
-
-#ifndef LIBFFI_ASM
-
-#if defined(_MSC_VER) && !defined(__clang__)
-#define __attribute__(X)
-#endif
-
-#include <stddef.h>
-#include <limits.h>
-
-/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
- But we can find it either under the correct ANSI name, or under GNU
- C's internal name. */
-
-#define FFI_64_BIT_MAX 9223372036854775807
-
-#ifdef LONG_LONG_MAX
-# define FFI_LONG_LONG_MAX LONG_LONG_MAX
-#else
-# ifdef LLONG_MAX
-# define FFI_LONG_LONG_MAX LLONG_MAX
-# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif /* _AIX52 or newer */
-# else
-# ifdef __GNUC__
-# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
-# endif
-# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
-# ifndef __PPC64__
-# if defined (__IBMC__) || defined (__IBMCPP__)
-# define FFI_LONG_LONG_MAX LONGLONG_MAX
-# endif
-# endif /* __PPC64__ */
-# undef FFI_64_BIT_MAX
-# define FFI_64_BIT_MAX 9223372036854775807LL
-# endif
-# endif
-#endif
-
-/* The closure code assumes that this works on pointers, i.e. a size_t
- can hold a pointer. */
-
-typedef struct _ffi_type
-{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
-} ffi_type;
-
-/* Need minimal decorations for DLLs to work on Windows. GCC has
- autoimport and autoexport. Always mark externally visible symbols
- as dllimport for MSVC clients, even if it means an extra indirection
- when using the static version of the library.
- Besides, as a workaround, they can define FFI_BUILDING if they
- *know* they are going to link with the static library. */
-#if defined _MSC_VER
-# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
-# define FFI_API __declspec(dllexport)
-# elif !defined FFI_BUILDING /* Importing libffi.DLL */
-# define FFI_API __declspec(dllimport)
-# else /* Building/linking static library */
-# define FFI_API
-# endif
-#else
-# define FFI_API
-#endif
-
-/* The externally visible type declarations also need the MSVC DLL
- decorations, or they will not be exported from the object file. */
-#if defined LIBFFI_HIDE_BASIC_TYPES
-# define FFI_EXTERN FFI_API
-#else
-# define FFI_EXTERN extern FFI_API
-#endif
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
-#if SCHAR_MAX == 127
-# define ffi_type_uchar ffi_type_uint8
-# define ffi_type_schar ffi_type_sint8
-#else
- #error "char size not supported"
-#endif
-
-#if SHRT_MAX == 32767
-# define ffi_type_ushort ffi_type_uint16
-# define ffi_type_sshort ffi_type_sint16
-#elif SHRT_MAX == 2147483647
-# define ffi_type_ushort ffi_type_uint32
-# define ffi_type_sshort ffi_type_sint32
-#else
- #error "short size not supported"
-#endif
-
-#if INT_MAX == 32767
-# define ffi_type_uint ffi_type_uint16
-# define ffi_type_sint ffi_type_sint16
-#elif INT_MAX == 2147483647
-# define ffi_type_uint ffi_type_uint32
-# define ffi_type_sint ffi_type_sint32
-#elif INT_MAX == 9223372036854775807
-# define ffi_type_uint ffi_type_uint64
-# define ffi_type_sint ffi_type_sint64
-#else
- #error "int size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
- #error "no 64-bit data type supported"
-# endif
-#elif LONG_MAX != FFI_64_BIT_MAX
- #error "long size not supported"
-#endif
-
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong ffi_type_uint32
-# define ffi_type_slong ffi_type_sint32
-#elif LONG_MAX == FFI_64_BIT_MAX
-# define ffi_type_ulong ffi_type_uint64
-# define ffi_type_slong ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
-
-/* These are defined in types.c. */
-FFI_EXTERN ffi_type ffi_type_void;
-FFI_EXTERN ffi_type ffi_type_uint8;
-FFI_EXTERN ffi_type ffi_type_sint8;
-FFI_EXTERN ffi_type ffi_type_uint16;
-FFI_EXTERN ffi_type ffi_type_sint16;
-FFI_EXTERN ffi_type ffi_type_uint32;
-FFI_EXTERN ffi_type ffi_type_sint32;
-FFI_EXTERN ffi_type ffi_type_uint64;
-FFI_EXTERN ffi_type ffi_type_sint64;
-FFI_EXTERN ffi_type ffi_type_float;
-FFI_EXTERN ffi_type ffi_type_double;
-FFI_EXTERN ffi_type ffi_type_pointer;
-
-#if 1
-FFI_EXTERN ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_EXTERN ffi_type ffi_type_complex_float;
-FFI_EXTERN ffi_type ffi_type_complex_double;
-#if 1
-FFI_EXTERN ffi_type ffi_type_complex_longdouble;
-#else
-#define ffi_type_complex_longdouble ffi_type_complex_double
-#endif
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
-
-typedef enum {
- FFI_OK = 0,
- FFI_BAD_TYPEDEF,
- FFI_BAD_ABI
-} ffi_status;
-
-typedef struct {
- ffi_abi abi;
- unsigned nargs;
- ffi_type **arg_types;
- ffi_type *rtype;
- unsigned bytes;
- unsigned flags;
-#ifdef FFI_EXTRA_CIF_FIELDS
- FFI_EXTRA_CIF_FIELDS;
-#endif
-} ffi_cif;
-
-/* ---- Definitions for the raw API -------------------------------------- */
-
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-# define FFI_SIZEOF_ARG 4
-# elif LONG_MAX == FFI_64_BIT_MAX
-# define FFI_SIZEOF_ARG 8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
-#endif
-
-typedef union {
- ffi_sarg sint;
- ffi_arg uint;
- float flt;
- char data[FFI_SIZEOF_ARG];
- void* ptr;
-} ffi_raw;
-
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
- sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
-typedef union {
- signed int sint;
- unsigned int uint;
- float flt;
- char data[FFI_SIZEOF_JAVA_RAW];
- void* ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-FFI_API
-void ffi_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_raw *avalue);
-
-FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
-FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
-FFI_API size_t ffi_raw_size (ffi_cif *cif);
-
-/* This is analogous to the raw API, except it uses Java parameter
- packing, even on 64-bit machines. I.e. on 64-bit machines longs
- and doubles are followed by an empty 64-bit word. */
-
-#if !FFI_NATIVE_RAW_API
+/* -----------------------------------------------------------------*-C-*-
+ libffi 3.3 - Copyright (c) 2011, 2014, 2019 Anthony Green
+ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the ``Software''), to deal in the Software without
+ restriction, including without limitation the rights to use, copy,
+ modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+/* -------------------------------------------------------------------
+ Most of the API is documented in doc/libffi.texi.
+
+ The raw API is designed to bypass some of the argument packing and
+ unpacking on architectures for which it can be avoided. Routines
+ are provided to emulate the raw API if the underlying platform
+ doesn't allow faster implementation.
+
+ More details on the raw API can be found in:
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
+
+ and
+
+ http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
+ -------------------------------------------------------------------- */
+
+#ifndef LIBFFI_H
+#define LIBFFI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Specify which architecture libffi is configured for. */
+#ifndef X86_64
+#define X86_64
+#endif
+
+/* ---- System configuration information --------------------------------- */
+
+#include <ffitarget.h>
+
+#ifndef LIBFFI_ASM
+
+#if defined(_MSC_VER) && !defined(__clang__)
+#define __attribute__(X)
+#endif
+
+#include <stddef.h>
+#include <limits.h>
+
+/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+ But we can find it either under the correct ANSI name, or under GNU
+ C's internal name. */
+
+#define FFI_64_BIT_MAX 9223372036854775807
+
+#ifdef LONG_LONG_MAX
+# define FFI_LONG_LONG_MAX LONG_LONG_MAX
+#else
+# ifdef LLONG_MAX
+# define FFI_LONG_LONG_MAX LLONG_MAX
+# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif /* _AIX52 or newer */
+# else
+# ifdef __GNUC__
+# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
+# endif
+# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
+# ifndef __PPC64__
+# if defined (__IBMC__) || defined (__IBMCPP__)
+# define FFI_LONG_LONG_MAX LONGLONG_MAX
+# endif
+# endif /* __PPC64__ */
+# undef FFI_64_BIT_MAX
+# define FFI_64_BIT_MAX 9223372036854775807LL
+# endif
+# endif
+#endif
+
+/* The closure code assumes that this works on pointers, i.e. a size_t
+ can hold a pointer. */
+
+typedef struct _ffi_type
+{
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
+} ffi_type;
+
+/* Need minimal decorations for DLLs to work on Windows. GCC has
+ autoimport and autoexport. Always mark externally visible symbols
+ as dllimport for MSVC clients, even if it means an extra indirection
+ when using the static version of the library.
+ Besides, as a workaround, they can define FFI_BUILDING if they
+ *know* they are going to link with the static library. */
+#if defined _MSC_VER
+# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
+# define FFI_API __declspec(dllexport)
+# elif !defined FFI_BUILDING /* Importing libffi.DLL */
+# define FFI_API __declspec(dllimport)
+# else /* Building/linking static library */
+# define FFI_API
+# endif
+#else
+# define FFI_API
+#endif
+
+/* The externally visible type declarations also need the MSVC DLL
+ decorations, or they will not be exported from the object file. */
+#if defined LIBFFI_HIDE_BASIC_TYPES
+# define FFI_EXTERN FFI_API
+#else
+# define FFI_EXTERN extern FFI_API
+#endif
+
+#ifndef LIBFFI_HIDE_BASIC_TYPES
+#if SCHAR_MAX == 127
+# define ffi_type_uchar ffi_type_uint8
+# define ffi_type_schar ffi_type_sint8
+#else
+ #error "char size not supported"
+#endif
+
+#if SHRT_MAX == 32767
+# define ffi_type_ushort ffi_type_uint16
+# define ffi_type_sshort ffi_type_sint16
+#elif SHRT_MAX == 2147483647
+# define ffi_type_ushort ffi_type_uint32
+# define ffi_type_sshort ffi_type_sint32
+#else
+ #error "short size not supported"
+#endif
+
+#if INT_MAX == 32767
+# define ffi_type_uint ffi_type_uint16
+# define ffi_type_sint ffi_type_sint16
+#elif INT_MAX == 2147483647
+# define ffi_type_uint ffi_type_uint32
+# define ffi_type_sint ffi_type_sint32
+#elif INT_MAX == 9223372036854775807
+# define ffi_type_uint ffi_type_uint64
+# define ffi_type_sint ffi_type_sint64
+#else
+ #error "int size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
+ #error "no 64-bit data type supported"
+# endif
+#elif LONG_MAX != FFI_64_BIT_MAX
+ #error "long size not supported"
+#endif
+
+#if LONG_MAX == 2147483647
+# define ffi_type_ulong ffi_type_uint32
+# define ffi_type_slong ffi_type_sint32
+#elif LONG_MAX == FFI_64_BIT_MAX
+# define ffi_type_ulong ffi_type_uint64
+# define ffi_type_slong ffi_type_sint64
+#else
+ #error "long size not supported"
+#endif
+
+/* These are defined in types.c. */
+FFI_EXTERN ffi_type ffi_type_void;
+FFI_EXTERN ffi_type ffi_type_uint8;
+FFI_EXTERN ffi_type ffi_type_sint8;
+FFI_EXTERN ffi_type ffi_type_uint16;
+FFI_EXTERN ffi_type ffi_type_sint16;
+FFI_EXTERN ffi_type ffi_type_uint32;
+FFI_EXTERN ffi_type ffi_type_sint32;
+FFI_EXTERN ffi_type ffi_type_uint64;
+FFI_EXTERN ffi_type ffi_type_sint64;
+FFI_EXTERN ffi_type ffi_type_float;
+FFI_EXTERN ffi_type ffi_type_double;
+FFI_EXTERN ffi_type ffi_type_pointer;
+
+#if 1
+FFI_EXTERN ffi_type ffi_type_longdouble;
+#else
+#define ffi_type_longdouble ffi_type_double
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_EXTERN ffi_type ffi_type_complex_float;
+FFI_EXTERN ffi_type ffi_type_complex_double;
+#if 1
+FFI_EXTERN ffi_type ffi_type_complex_longdouble;
+#else
+#define ffi_type_complex_longdouble ffi_type_complex_double
+#endif
+#endif
+#endif /* LIBFFI_HIDE_BASIC_TYPES */
+
+typedef enum {
+ FFI_OK = 0,
+ FFI_BAD_TYPEDEF,
+ FFI_BAD_ABI
+} ffi_status;
+
+typedef struct {
+ ffi_abi abi;
+ unsigned nargs;
+ ffi_type **arg_types;
+ ffi_type *rtype;
+ unsigned bytes;
+ unsigned flags;
+#ifdef FFI_EXTRA_CIF_FIELDS
+ FFI_EXTRA_CIF_FIELDS;
+#endif
+} ffi_cif;
+
+/* ---- Definitions for the raw API -------------------------------------- */
+
+#ifndef FFI_SIZEOF_ARG
+# if LONG_MAX == 2147483647
+# define FFI_SIZEOF_ARG 4
+# elif LONG_MAX == FFI_64_BIT_MAX
+# define FFI_SIZEOF_ARG 8
+# endif
+#endif
+
+#ifndef FFI_SIZEOF_JAVA_RAW
+# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#endif
+
+typedef union {
+ ffi_sarg sint;
+ ffi_arg uint;
+ float flt;
+ char data[FFI_SIZEOF_ARG];
+ void* ptr;
+} ffi_raw;
+
+#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
+/* This is a special case for mips64/n32 ABI (and perhaps others) where
+ sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
+typedef union {
+ signed int sint;
+ unsigned int uint;
+ float flt;
+ char data[FFI_SIZEOF_JAVA_RAW];
+ void* ptr;
+} ffi_java_raw;
+#else
+typedef ffi_raw ffi_java_raw;
+#endif
+
+
FFI_API
-void ffi_java_raw_call (ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- ffi_java_raw *avalue) __attribute__((deprecated));
-#endif
-
+void ffi_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_raw *avalue);
+
+FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
+FFI_API size_t ffi_raw_size (ffi_cif *cif);
+
+/* This is analogous to the raw API, except it uses Java parameter
+ packing, even on 64-bit machines. I.e. on 64-bit machines longs
+ and doubles are followed by an empty 64-bit word. */
+
+#if !FFI_NATIVE_RAW_API
+FFI_API
+void ffi_java_raw_call (ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ ffi_java_raw *avalue) __attribute__((deprecated));
+#endif
+
+FFI_API
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
+FFI_API
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
+FFI_API
+size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#if FFI_CLOSURES
+
+#ifdef _MSC_VER
+__declspec(align(8))
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+ void *user_data;
+} ffi_closure
+#ifdef __GNUC__
+ __attribute__((aligned (8)))
+#endif
+ ;
+
+#ifndef __GNUC__
+# ifdef __sgi
+# pragma pack 0
+# endif
+#endif
+
+FFI_API void *ffi_closure_alloc (size_t size, void **code);
+FFI_API void ffi_closure_free (void *);
+
+FFI_API ffi_status
+ffi_prep_closure (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data)
+#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
+ __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
+#elif defined(__GNUC__) && __GNUC__ >= 3
+ __attribute__((deprecated))
+#endif
+ ;
+
+FFI_API ffi_status
+ffi_prep_closure_loc (ffi_closure*,
+ ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void*codeloc);
+
+#ifdef __sgi
+# pragma pack 8
+#endif
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the transaltion, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
+ void *user_data;
+
+} ffi_raw_closure;
+
+typedef struct {
+#if 0
+ void *trampoline_table;
+ void *trampoline_table_entry;
+#else
+ char tramp[FFI_TRAMPOLINE_SIZE];
+#endif
+
+ ffi_cif *cif;
+
+#if !FFI_NATIVE_RAW_API
+
+ /* If this is enabled, then a raw closure has the same layout
+ as a regular closure. We use this to install an intermediate
+ handler to do the translation, void** -> ffi_raw*. */
+
+ void (*translate_args)(ffi_cif*,void*,void**,void*);
+ void *this_closure;
+
+#endif
+
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
+ void *user_data;
+
+} ffi_java_raw_closure;
+
+FFI_API ffi_status
+ffi_prep_raw_closure (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data);
+
+FFI_API ffi_status
+ffi_prep_raw_closure_loc (ffi_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
+ void *user_data,
+ void *codeloc);
+
+#if !FFI_NATIVE_RAW_API
+FFI_API ffi_status
+ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data) __attribute__((deprecated));
+
+FFI_API ffi_status
+ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
+ ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+ void *user_data,
+ void *codeloc) __attribute__((deprecated));
+#endif
+
+#endif /* FFI_CLOSURES */
+
+#if FFI_GO_CLOSURES
+
+typedef struct {
+ void *tramp;
+ ffi_cif *cif;
+ void (*fun)(ffi_cif*,void*,void**,void*);
+} ffi_go_closure;
+
+FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
+ void (*fun)(ffi_cif*,void*,void**,void*));
+
+FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+
+#endif /* FFI_GO_CLOSURES */
+
+/* ---- Public interface definition -------------------------------------- */
+
FFI_API
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated));
-FFI_API
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated));
-FFI_API
-size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#if FFI_CLOSURES
-
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
- void *user_data;
-} ffi_closure
-#ifdef __GNUC__
- __attribute__((aligned (8)))
-#endif
- ;
-
-#ifndef __GNUC__
-# ifdef __sgi
-# pragma pack 0
-# endif
-#endif
-
-FFI_API void *ffi_closure_alloc (size_t size, void **code);
-FFI_API void ffi_closure_free (void *);
-
-FFI_API ffi_status
-ffi_prep_closure (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data)
-#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
- __attribute__((deprecated ("use ffi_prep_closure_loc instead")))
-#elif defined(__GNUC__) && __GNUC__ >= 3
- __attribute__((deprecated))
-#endif
- ;
-
-FFI_API ffi_status
-ffi_prep_closure_loc (ffi_closure*,
- ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void*codeloc);
-
-#ifdef __sgi
-# pragma pack 8
-#endif
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the transaltion, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
- void *user_data;
-
-} ffi_raw_closure;
-
-typedef struct {
-#if 0
- void *trampoline_table;
- void *trampoline_table_entry;
-#else
- char tramp[FFI_TRAMPOLINE_SIZE];
-#endif
-
- ffi_cif *cif;
-
-#if !FFI_NATIVE_RAW_API
-
- /* If this is enabled, then a raw closure has the same layout
- as a regular closure. We use this to install an intermediate
- handler to do the translation, void** -> ffi_raw*. */
-
- void (*translate_args)(ffi_cif*,void*,void**,void*);
- void *this_closure;
-
-#endif
-
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
- void *user_data;
-
-} ffi_java_raw_closure;
-
-FFI_API ffi_status
-ffi_prep_raw_closure (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data);
-
-FFI_API ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
- void *user_data,
- void *codeloc);
-
-#if !FFI_NATIVE_RAW_API
-FFI_API ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data) __attribute__((deprecated));
-
-FFI_API ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
- ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
- void *user_data,
- void *codeloc) __attribute__((deprecated));
-#endif
-
-#endif /* FFI_CLOSURES */
-
-#if FFI_GO_CLOSURES
-
-typedef struct {
- void *tramp;
- ffi_cif *cif;
- void (*fun)(ffi_cif*,void*,void**,void*);
-} ffi_go_closure;
-
-FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
- void (*fun)(ffi_cif*,void*,void**,void*));
-
-FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-
-#endif /* FFI_GO_CLOSURES */
-
-/* ---- Public interface definition -------------------------------------- */
-
-FFI_API
-ffi_status ffi_prep_cif(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-ffi_status ffi_prep_cif_var(ffi_cif *cif,
- ffi_abi abi,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-FFI_API
-void ffi_call(ffi_cif *cif,
- void (*fn)(void),
- void *rvalue,
- void **avalue);
-
-FFI_API
-ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
- size_t *offsets);
-
-/* Useful for eliminating compiler warnings. */
-#define FFI_FN(f) ((void (*)(void))f)
-
-/* ---- Definitions shared with assembly code ---------------------------- */
-
-#endif
-
-/* If these change, update src/mips/ffitarget.h. */
-#define FFI_TYPE_VOID 0
-#define FFI_TYPE_INT 1
-#define FFI_TYPE_FLOAT 2
-#define FFI_TYPE_DOUBLE 3
-#if 1
-#define FFI_TYPE_LONGDOUBLE 4
-#else
-#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
-#endif
-#define FFI_TYPE_UINT8 5
-#define FFI_TYPE_SINT8 6
-#define FFI_TYPE_UINT16 7
-#define FFI_TYPE_SINT16 8
-#define FFI_TYPE_UINT32 9
-#define FFI_TYPE_SINT32 10
-#define FFI_TYPE_UINT64 11
-#define FFI_TYPE_SINT64 12
-#define FFI_TYPE_STRUCT 13
-#define FFI_TYPE_POINTER 14
-#define FFI_TYPE_COMPLEX 15
-
-/* This should always refer to the last type code (for sanity checks). */
-#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+ffi_status ffi_prep_cif(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+ffi_status ffi_prep_cif_var(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+FFI_API
+void ffi_call(ffi_cif *cif,
+ void (*fn)(void),
+ void *rvalue,
+ void **avalue);
+
+FFI_API
+ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
+ size_t *offsets);
+
+/* Useful for eliminating compiler warnings. */
+#define FFI_FN(f) ((void (*)(void))f)
+
+/* ---- Definitions shared with assembly code ---------------------------- */
+
+#endif
+
+/* If these change, update src/mips/ffitarget.h. */
+#define FFI_TYPE_VOID 0
+#define FFI_TYPE_INT 1
+#define FFI_TYPE_FLOAT 2
+#define FFI_TYPE_DOUBLE 3
+#if 1
+#define FFI_TYPE_LONGDOUBLE 4
+#else
+#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
+#endif
+#define FFI_TYPE_UINT8 5
+#define FFI_TYPE_SINT8 6
+#define FFI_TYPE_UINT16 7
+#define FFI_TYPE_SINT16 8
+#define FFI_TYPE_UINT32 9
+#define FFI_TYPE_SINT32 10
+#define FFI_TYPE_UINT64 11
+#define FFI_TYPE_SINT64 12
+#define FFI_TYPE_STRUCT 13
+#define FFI_TYPE_POINTER 14
+#define FFI_TYPE_COMPLEX 15
+
+/* This should always refer to the last type code (for sanity checks). */
+#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include/ffitarget.h b/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include/ffitarget.h
index 23c8505403..85ccedfedc 100644
--- a/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include/ffitarget.h
+++ b/contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include/ffitarget.h
@@ -1,147 +1,147 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
- Copyright (c) 1996-2003, 2010 Red Hat, Inc.
- Copyright (C) 2008 Free Software Foundation, Inc.
-
- Target configuration macros for x86 and x86-64.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-/* ---- System specific configurations ----------------------------------- */
-
-/* For code common to all platforms on x86 and x86_64. */
-#define X86_ANY
-
-#if defined (X86_64) && defined (__i386__)
-#undef X86_64
-#define X86
-#endif
-
-#ifdef X86_WIN64
-#define FFI_SIZEOF_ARG 8
-#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
-#endif
-
-#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
-#ifndef _MSC_VER
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Generic type definitions ----------------------------------------- */
-
-#ifndef LIBFFI_ASM
-#ifdef X86_WIN64
-#ifdef _MSC_VER
-typedef unsigned __int64 ffi_arg;
-typedef __int64 ffi_sarg;
-#else
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#endif
-#else
-#if defined __x86_64__ && defined __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-#endif
-
-typedef enum ffi_abi {
-#if defined(X86_WIN64)
- FFI_FIRST_ABI = 0,
- FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
- FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
- FFI_LAST_ABI,
-#ifdef __GNUC__
- FFI_DEFAULT_ABI = FFI_GNUW64
-#else
- FFI_DEFAULT_ABI = FFI_WIN64
-#endif
-
-#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
- FFI_FIRST_ABI = 1,
- FFI_UNIX64,
- FFI_WIN64,
- FFI_EFI64 = FFI_WIN64,
- FFI_GNUW64,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_UNIX64
-
-#elif defined(X86_WIN32)
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_STDCALL = 2,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_MS_CDECL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_MS_CDECL
-#else
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_STDCALL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_MS_CDECL = 8,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
-#endif
-} ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-
-#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
-#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
-#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
-#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
-
-#if defined (X86_64) || defined(X86_WIN64) \
- || (defined (__x86_64__) && defined (X86_DARWIN))
-# define FFI_TRAMPOLINE_SIZE 24
-# define FFI_NATIVE_RAW_API 0
-#else
-# define FFI_TRAMPOLINE_SIZE 12
-# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
-#endif
-
-#endif
-
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
+ Copyright (c) 1996-2003, 2010 Red Hat, Inc.
+ Copyright (C) 2008 Free Software Foundation, Inc.
+
+ Target configuration macros for x86 and x86-64.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+/* ---- System specific configurations ----------------------------------- */
+
+/* For code common to all platforms on x86 and x86_64. */
+#define X86_ANY
+
+#if defined (X86_64) && defined (__i386__)
+#undef X86_64
+#define X86
+#endif
+
+#ifdef X86_WIN64
+#define FFI_SIZEOF_ARG 8
+#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
+#endif
+
+#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+#ifndef _MSC_VER
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Generic type definitions ----------------------------------------- */
+
+#ifndef LIBFFI_ASM
+#ifdef X86_WIN64
+#ifdef _MSC_VER
+typedef unsigned __int64 ffi_arg;
+typedef __int64 ffi_sarg;
+#else
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#endif
+#else
+#if defined __x86_64__ && defined __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+#endif
+
+typedef enum ffi_abi {
+#if defined(X86_WIN64)
+ FFI_FIRST_ABI = 0,
+ FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
+ FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
+ FFI_LAST_ABI,
+#ifdef __GNUC__
+ FFI_DEFAULT_ABI = FFI_GNUW64
+#else
+ FFI_DEFAULT_ABI = FFI_WIN64
+#endif
+
+#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
+ FFI_FIRST_ABI = 1,
+ FFI_UNIX64,
+ FFI_WIN64,
+ FFI_EFI64 = FFI_WIN64,
+ FFI_GNUW64,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_UNIX64
+
+#elif defined(X86_WIN32)
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_STDCALL = 2,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_MS_CDECL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_MS_CDECL
+#else
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_STDCALL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_MS_CDECL = 8,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+#endif
+} ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+
+#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
+#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
+#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
+#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
+
+#if defined (X86_64) || defined(X86_WIN64) \
+ || (defined (__x86_64__) && defined (X86_DARWIN))
+# define FFI_TRAMPOLINE_SIZE 24
+# define FFI_NATIVE_RAW_API 0
+#else
+# define FFI_TRAMPOLINE_SIZE 12
+# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
+#endif
+
+#endif
+
diff --git a/contrib/restricted/libffi/include/ffi_cfi.h b/contrib/restricted/libffi/include/ffi_cfi.h
index 1405b2f1eb..244ce572be 100644
--- a/contrib/restricted/libffi/include/ffi_cfi.h
+++ b/contrib/restricted/libffi/include/ffi_cfi.h
@@ -1,55 +1,55 @@
-/* -----------------------------------------------------------------------
- ffi_cfi.h - Copyright (c) 2014 Red Hat, Inc.
-
- Conditionally assemble cfi directives. Only necessary for building libffi.
- ----------------------------------------------------------------------- */
-
-#ifndef FFI_CFI_H
-#define FFI_CFI_H
-
-#ifdef HAVE_AS_CFI_PSEUDO_OP
-
-# define cfi_startproc .cfi_startproc
-# define cfi_endproc .cfi_endproc
-# define cfi_def_cfa(reg, off) .cfi_def_cfa reg, off
-# define cfi_def_cfa_register(reg) .cfi_def_cfa_register reg
-# define cfi_def_cfa_offset(off) .cfi_def_cfa_offset off
-# define cfi_adjust_cfa_offset(off) .cfi_adjust_cfa_offset off
-# define cfi_offset(reg, off) .cfi_offset reg, off
-# define cfi_rel_offset(reg, off) .cfi_rel_offset reg, off
-# define cfi_register(r1, r2) .cfi_register r1, r2
-# define cfi_return_column(reg) .cfi_return_column reg
-# define cfi_restore(reg) .cfi_restore reg
-# define cfi_same_value(reg) .cfi_same_value reg
-# define cfi_undefined(reg) .cfi_undefined reg
-# define cfi_remember_state .cfi_remember_state
-# define cfi_restore_state .cfi_restore_state
-# define cfi_window_save .cfi_window_save
-# define cfi_personality(enc, exp) .cfi_personality enc, exp
-# define cfi_lsda(enc, exp) .cfi_lsda enc, exp
-# define cfi_escape(...) .cfi_escape __VA_ARGS__
-
-#else
-
-# define cfi_startproc
-# define cfi_endproc
-# define cfi_def_cfa(reg, off)
-# define cfi_def_cfa_register(reg)
-# define cfi_def_cfa_offset(off)
-# define cfi_adjust_cfa_offset(off)
-# define cfi_offset(reg, off)
-# define cfi_rel_offset(reg, off)
-# define cfi_register(r1, r2)
-# define cfi_return_column(reg)
-# define cfi_restore(reg)
-# define cfi_same_value(reg)
-# define cfi_undefined(reg)
-# define cfi_remember_state
-# define cfi_restore_state
-# define cfi_window_save
-# define cfi_personality(enc, exp)
-# define cfi_lsda(enc, exp)
-# define cfi_escape(...)
-
-#endif /* HAVE_AS_CFI_PSEUDO_OP */
-#endif /* FFI_CFI_H */
+/* -----------------------------------------------------------------------
+ ffi_cfi.h - Copyright (c) 2014 Red Hat, Inc.
+
+ Conditionally assemble cfi directives. Only necessary for building libffi.
+ ----------------------------------------------------------------------- */
+
+#ifndef FFI_CFI_H
+#define FFI_CFI_H
+
+#ifdef HAVE_AS_CFI_PSEUDO_OP
+
+# define cfi_startproc .cfi_startproc
+# define cfi_endproc .cfi_endproc
+# define cfi_def_cfa(reg, off) .cfi_def_cfa reg, off
+# define cfi_def_cfa_register(reg) .cfi_def_cfa_register reg
+# define cfi_def_cfa_offset(off) .cfi_def_cfa_offset off
+# define cfi_adjust_cfa_offset(off) .cfi_adjust_cfa_offset off
+# define cfi_offset(reg, off) .cfi_offset reg, off
+# define cfi_rel_offset(reg, off) .cfi_rel_offset reg, off
+# define cfi_register(r1, r2) .cfi_register r1, r2
+# define cfi_return_column(reg) .cfi_return_column reg
+# define cfi_restore(reg) .cfi_restore reg
+# define cfi_same_value(reg) .cfi_same_value reg
+# define cfi_undefined(reg) .cfi_undefined reg
+# define cfi_remember_state .cfi_remember_state
+# define cfi_restore_state .cfi_restore_state
+# define cfi_window_save .cfi_window_save
+# define cfi_personality(enc, exp) .cfi_personality enc, exp
+# define cfi_lsda(enc, exp) .cfi_lsda enc, exp
+# define cfi_escape(...) .cfi_escape __VA_ARGS__
+
+#else
+
+# define cfi_startproc
+# define cfi_endproc
+# define cfi_def_cfa(reg, off)
+# define cfi_def_cfa_register(reg)
+# define cfi_def_cfa_offset(off)
+# define cfi_adjust_cfa_offset(off)
+# define cfi_offset(reg, off)
+# define cfi_rel_offset(reg, off)
+# define cfi_register(r1, r2)
+# define cfi_return_column(reg)
+# define cfi_restore(reg)
+# define cfi_same_value(reg)
+# define cfi_undefined(reg)
+# define cfi_remember_state
+# define cfi_restore_state
+# define cfi_window_save
+# define cfi_personality(enc, exp)
+# define cfi_lsda(enc, exp)
+# define cfi_escape(...)
+
+#endif /* HAVE_AS_CFI_PSEUDO_OP */
+#endif /* FFI_CFI_H */
diff --git a/contrib/restricted/libffi/include/ffi_common.h b/contrib/restricted/libffi/include/ffi_common.h
index 8d233086cd..76b9dd6faf 100644
--- a/contrib/restricted/libffi/include/ffi_common.h
+++ b/contrib/restricted/libffi/include/ffi_common.h
@@ -1,8 +1,8 @@
/* -----------------------------------------------------------------------
- ffi_common.h - Copyright (C) 2011, 2012, 2013 Anthony Green
+ ffi_common.h - Copyright (C) 2011, 2012, 2013 Anthony Green
Copyright (C) 2007 Free Software Foundation, Inc
Copyright (c) 1996 Red Hat, Inc.
-
+
Common internal definitions and macros. Only necessary for building
libffi.
----------------------------------------------------------------------- */
@@ -19,14 +19,14 @@ extern "C" {
/* Do not move this. Some versions of AIX are very picky about where
this is positioned. */
#ifdef __GNUC__
-# if HAVE_ALLOCA_H
-# include <alloca.h>
-# else
- /* mingw64 defines this already in malloc.h. */
-# ifndef alloca
-# define alloca __builtin_alloca
-# endif
-# endif
+# if HAVE_ALLOCA_H
+# include <alloca.h>
+# else
+ /* mingw64 defines this already in malloc.h. */
+# ifndef alloca
+# define alloca __builtin_alloca
+# endif
+# endif
# define MAYBE_UNUSED __attribute__((__unused__))
#else
# define MAYBE_UNUSED
@@ -34,7 +34,7 @@ extern "C" {
# include <alloca.h>
# else
# ifdef _AIX
-# pragma alloca
+# pragma alloca
# else
# ifndef alloca /* predefined by HP cc +Olibcalls */
# ifdef _MSC_VER
@@ -44,7 +44,7 @@ char *alloca ();
# endif
# endif
# endif
-# endif
+# endif
#endif
/* Check for the existence of memcpy. */
@@ -74,35 +74,35 @@ void ffi_type_test(ffi_type *a, char *file, int line);
#define FFI_ASSERT_VALID_TYPE(x)
#endif
-/* v cast to size_t and aligned up to a multiple of a */
-#define FFI_ALIGN(v, a) (((((size_t) (v))-1) | ((a)-1))+1)
-/* v cast to size_t and aligned down to a multiple of a */
-#define FFI_ALIGN_DOWN(v, a) (((size_t) (v)) & -a)
+/* v cast to size_t and aligned up to a multiple of a */
+#define FFI_ALIGN(v, a) (((((size_t) (v))-1) | ((a)-1))+1)
+/* v cast to size_t and aligned down to a multiple of a */
+#define FFI_ALIGN_DOWN(v, a) (((size_t) (v)) & -a)
/* Perform machine dependent cif processing */
ffi_status ffi_prep_cif_machdep(ffi_cif *cif);
ffi_status ffi_prep_cif_machdep_var(ffi_cif *cif,
unsigned int nfixedargs, unsigned int ntotalargs);
-
-#if HAVE_LONG_DOUBLE_VARIANT
-/* Used to adjust size/alignment of ffi types. */
-void ffi_prep_types (ffi_abi abi);
-#endif
-
-/* Used internally, but overridden by some architectures */
-ffi_status ffi_prep_cif_core(ffi_cif *cif,
- ffi_abi abi,
- unsigned int isvariadic,
- unsigned int nfixedargs,
- unsigned int ntotalargs,
- ffi_type *rtype,
- ffi_type **atypes);
-
-/* Translate a data pointer to a code pointer. Needed for closures on
- some targets. */
-void *ffi_data_to_code_pointer (void *data) FFI_HIDDEN;
-
+
+#if HAVE_LONG_DOUBLE_VARIANT
+/* Used to adjust size/alignment of ffi types. */
+void ffi_prep_types (ffi_abi abi);
+#endif
+
+/* Used internally, but overridden by some architectures */
+ffi_status ffi_prep_cif_core(ffi_cif *cif,
+ ffi_abi abi,
+ unsigned int isvariadic,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs,
+ ffi_type *rtype,
+ ffi_type **atypes);
+
+/* Translate a data pointer to a code pointer. Needed for closures on
+ some targets. */
+void *ffi_data_to_code_pointer (void *data) FFI_HIDDEN;
+
/* Extended cif, used in callback from assembly routine */
typedef struct
{
diff --git a/contrib/restricted/libffi/src/aarch64/ffi.c b/contrib/restricted/libffi/src/aarch64/ffi.c
index 84d44ab74a..1ebf43c192 100644
--- a/contrib/restricted/libffi/src/aarch64/ffi.c
+++ b/contrib/restricted/libffi/src/aarch64/ffi.c
@@ -1,1009 +1,1009 @@
-/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-``Software''), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-
-#if defined(__aarch64__) || defined(__arm64__)|| defined (_M_ARM64)
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <fficonfig.h>
-#include <ffi.h>
-#include <ffi_common.h>
-#include "internal.h"
-#ifdef _M_ARM64
-#include <windows.h> /* FlushInstructionCache */
-#endif
-
-/* Force FFI_TYPE_LONGDOUBLE to be different than FFI_TYPE_DOUBLE;
- all further uses in this file will refer to the 128-bit type. */
-#if FFI_TYPE_DOUBLE != FFI_TYPE_LONGDOUBLE
-# if FFI_TYPE_LONGDOUBLE != 4
-# error FFI_TYPE_LONGDOUBLE out of date
-# endif
-#else
-# undef FFI_TYPE_LONGDOUBLE
-# define FFI_TYPE_LONGDOUBLE 4
-#endif
-
-union _d
-{
- UINT64 d;
- UINT32 s[2];
-};
-
-struct _v
-{
- union _d d[2] __attribute__((aligned(16)));
-};
-
-struct call_context
-{
- struct _v v[N_V_ARG_REG];
- UINT64 x[N_X_ARG_REG];
-};
-
-#if FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#include <mach/vm_param.h>
-#endif
-
-#else
-
-#if defined (__clang__) && defined (__APPLE__)
-extern void sys_icache_invalidate (void *start, size_t len);
-#endif
-
-static inline void
-ffi_clear_cache (void *start, void *end)
-{
-#if defined (__clang__) && defined (__APPLE__)
- sys_icache_invalidate (start, (char *)end - (char *)start);
-#elif defined (__GNUC__)
- __builtin___clear_cache (start, end);
-#elif defined (_M_ARM64)
- FlushInstructionCache(GetCurrentProcess(), start, (char*)end - (char*)start);
-#else
-#error "Missing builtin to flush instruction cache"
-#endif
-}
-
-#endif
-
-/* A subroutine of is_vfp_type. Given a structure type, return the type code
- of the first non-structure element. Recurse for structure elements.
- Return -1 if the structure is in fact empty, i.e. no nested elements. */
-
-static int
-is_hfa0 (const ffi_type *ty)
-{
- ffi_type **elements = ty->elements;
- int i, ret = -1;
-
- if (elements != NULL)
- for (i = 0; elements[i]; ++i)
- {
- ret = elements[i]->type;
- if (ret == FFI_TYPE_STRUCT || ret == FFI_TYPE_COMPLEX)
- {
- ret = is_hfa0 (elements[i]);
- if (ret < 0)
- continue;
- }
- break;
- }
-
- return ret;
-}
-
-/* A subroutine of is_vfp_type. Given a structure type, return true if all
- of the non-structure elements are the same as CANDIDATE. */
-
-static int
-is_hfa1 (const ffi_type *ty, int candidate)
-{
- ffi_type **elements = ty->elements;
- int i;
-
- if (elements != NULL)
- for (i = 0; elements[i]; ++i)
- {
- int t = elements[i]->type;
- if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
- {
- if (!is_hfa1 (elements[i], candidate))
- return 0;
- }
- else if (t != candidate)
- return 0;
- }
-
- return 1;
-}
-
-/* Determine if TY may be allocated to the FP registers. This is both an
- fp scalar type as well as an homogenous floating point aggregate (HFA).
- That is, a structure consisting of 1 to 4 members of all the same type,
- where that type is an fp scalar.
-
- Returns non-zero iff TY is an HFA. The result is the AARCH64_RET_*
- constant for the type. */
-
-static int
-is_vfp_type (const ffi_type *ty)
-{
- ffi_type **elements;
- int candidate, i;
- size_t size, ele_count;
-
- /* Quickest tests first. */
- candidate = ty->type;
- switch (candidate)
- {
- default:
- return 0;
- case FFI_TYPE_FLOAT:
- case FFI_TYPE_DOUBLE:
- case FFI_TYPE_LONGDOUBLE:
- ele_count = 1;
- goto done;
- case FFI_TYPE_COMPLEX:
- candidate = ty->elements[0]->type;
- switch (candidate)
- {
- case FFI_TYPE_FLOAT:
- case FFI_TYPE_DOUBLE:
- case FFI_TYPE_LONGDOUBLE:
- ele_count = 2;
- goto done;
- }
- return 0;
- case FFI_TYPE_STRUCT:
- break;
- }
-
- /* No HFA types are smaller than 4 bytes, or larger than 64 bytes. */
- size = ty->size;
- if (size < 4 || size > 64)
- return 0;
-
- /* Find the type of the first non-structure member. */
- elements = ty->elements;
- candidate = elements[0]->type;
- if (candidate == FFI_TYPE_STRUCT || candidate == FFI_TYPE_COMPLEX)
- {
- for (i = 0; ; ++i)
- {
- candidate = is_hfa0 (elements[i]);
- if (candidate >= 0)
- break;
- }
- }
-
- /* If the first member is not a floating point type, it's not an HFA.
- Also quickly re-check the size of the structure. */
- switch (candidate)
- {
- case FFI_TYPE_FLOAT:
- ele_count = size / sizeof(float);
- if (size != ele_count * sizeof(float))
- return 0;
- break;
- case FFI_TYPE_DOUBLE:
- ele_count = size / sizeof(double);
- if (size != ele_count * sizeof(double))
- return 0;
- break;
- case FFI_TYPE_LONGDOUBLE:
- ele_count = size / sizeof(long double);
- if (size != ele_count * sizeof(long double))
- return 0;
- break;
- default:
- return 0;
- }
- if (ele_count > 4)
- return 0;
-
- /* Finally, make sure that all scalar elements are the same type. */
- for (i = 0; elements[i]; ++i)
- {
- int t = elements[i]->type;
- if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
- {
- if (!is_hfa1 (elements[i], candidate))
- return 0;
- }
- else if (t != candidate)
- return 0;
- }
-
- /* All tests succeeded. Encode the result. */
- done:
- return candidate * 4 + (4 - (int)ele_count);
-}
-
-/* Representation of the procedure call argument marshalling
- state.
-
- The terse state variable names match the names used in the AARCH64
- PCS. */
-
-struct arg_state
-{
- unsigned ngrn; /* Next general-purpose register number. */
- unsigned nsrn; /* Next vector register number. */
- size_t nsaa; /* Next stack offset. */
-
-#if defined (__APPLE__)
- unsigned allocating_variadic;
-#endif
-};
-
-/* Initialize a procedure call argument marshalling state. */
-static void
-arg_init (struct arg_state *state)
-{
- state->ngrn = 0;
- state->nsrn = 0;
- state->nsaa = 0;
-#if defined (__APPLE__)
- state->allocating_variadic = 0;
-#endif
-}
-
-/* Allocate an aligned slot on the stack and return a pointer to it. */
-static void *
-allocate_to_stack (struct arg_state *state, void *stack,
- size_t alignment, size_t size)
-{
- size_t nsaa = state->nsaa;
-
- /* Round up the NSAA to the larger of 8 or the natural
- alignment of the argument's type. */
-#if defined (__APPLE__)
- if (state->allocating_variadic && alignment < 8)
- alignment = 8;
-#else
- if (alignment < 8)
- alignment = 8;
-#endif
-
- nsaa = FFI_ALIGN (nsaa, alignment);
- state->nsaa = nsaa + size;
-
- return (char *)stack + nsaa;
-}
-
-static ffi_arg
-extend_integer_type (void *source, int type)
-{
- switch (type)
- {
- case FFI_TYPE_UINT8:
- return *(UINT8 *) source;
- case FFI_TYPE_SINT8:
- return *(SINT8 *) source;
- case FFI_TYPE_UINT16:
- return *(UINT16 *) source;
- case FFI_TYPE_SINT16:
- return *(SINT16 *) source;
- case FFI_TYPE_UINT32:
- return *(UINT32 *) source;
- case FFI_TYPE_INT:
- case FFI_TYPE_SINT32:
- return *(SINT32 *) source;
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- return *(UINT64 *) source;
- break;
- case FFI_TYPE_POINTER:
- return *(uintptr_t *) source;
- default:
- abort();
- }
-}
-
-#if defined(_MSC_VER)
-void extend_hfa_type (void *dest, void *src, int h);
-#else
-static void
-extend_hfa_type (void *dest, void *src, int h)
-{
- ssize_t f = h - AARCH64_RET_S4;
- void *x0;
-
- asm volatile (
- "adr %0, 0f\n"
-" add %0, %0, %1\n"
-" br %0\n"
-"0: ldp s16, s17, [%3]\n" /* S4 */
-" ldp s18, s19, [%3, #8]\n"
-" b 4f\n"
-" ldp s16, s17, [%3]\n" /* S3 */
-" ldr s18, [%3, #8]\n"
-" b 3f\n"
-" ldp s16, s17, [%3]\n" /* S2 */
-" b 2f\n"
-" nop\n"
-" ldr s16, [%3]\n" /* S1 */
-" b 1f\n"
-" nop\n"
-" ldp d16, d17, [%3]\n" /* D4 */
-" ldp d18, d19, [%3, #16]\n"
-" b 4f\n"
-" ldp d16, d17, [%3]\n" /* D3 */
-" ldr d18, [%3, #16]\n"
-" b 3f\n"
-" ldp d16, d17, [%3]\n" /* D2 */
-" b 2f\n"
-" nop\n"
-" ldr d16, [%3]\n" /* D1 */
-" b 1f\n"
-" nop\n"
-" ldp q16, q17, [%3]\n" /* Q4 */
-" ldp q18, q19, [%3, #32]\n"
-" b 4f\n"
-" ldp q16, q17, [%3]\n" /* Q3 */
-" ldr q18, [%3, #32]\n"
-" b 3f\n"
-" ldp q16, q17, [%3]\n" /* Q2 */
-" b 2f\n"
-" nop\n"
-" ldr q16, [%3]\n" /* Q1 */
-" b 1f\n"
-"4: str q19, [%2, #48]\n"
-"3: str q18, [%2, #32]\n"
-"2: str q17, [%2, #16]\n"
-"1: str q16, [%2]"
- : "=&r"(x0)
- : "r"(f * 12), "r"(dest), "r"(src)
- : "memory", "v16", "v17", "v18", "v19");
-}
-#endif
-
-#if defined(_MSC_VER)
-void* compress_hfa_type (void *dest, void *src, int h);
-#else
-static void *
-compress_hfa_type (void *dest, void *reg, int h)
-{
- switch (h)
- {
- case AARCH64_RET_S1:
- if (dest == reg)
- {
-#ifdef __AARCH64EB__
- dest += 12;
-#endif
- }
- else
- *(float *)dest = *(float *)reg;
- break;
- case AARCH64_RET_S2:
- asm ("ldp q16, q17, [%1]\n\t"
- "st2 { v16.s, v17.s }[0], [%0]"
- : : "r"(dest), "r"(reg) : "memory", "v16", "v17");
- break;
- case AARCH64_RET_S3:
- asm ("ldp q16, q17, [%1]\n\t"
- "ldr q18, [%1, #32]\n\t"
- "st3 { v16.s, v17.s, v18.s }[0], [%0]"
- : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18");
- break;
- case AARCH64_RET_S4:
- asm ("ldp q16, q17, [%1]\n\t"
- "ldp q18, q19, [%1, #32]\n\t"
- "st4 { v16.s, v17.s, v18.s, v19.s }[0], [%0]"
- : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18", "v19");
- break;
-
- case AARCH64_RET_D1:
- if (dest == reg)
- {
-#ifdef __AARCH64EB__
- dest += 8;
-#endif
- }
- else
- *(double *)dest = *(double *)reg;
- break;
- case AARCH64_RET_D2:
- asm ("ldp q16, q17, [%1]\n\t"
- "st2 { v16.d, v17.d }[0], [%0]"
- : : "r"(dest), "r"(reg) : "memory", "v16", "v17");
- break;
- case AARCH64_RET_D3:
- asm ("ldp q16, q17, [%1]\n\t"
- "ldr q18, [%1, #32]\n\t"
- "st3 { v16.d, v17.d, v18.d }[0], [%0]"
- : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18");
- break;
- case AARCH64_RET_D4:
- asm ("ldp q16, q17, [%1]\n\t"
- "ldp q18, q19, [%1, #32]\n\t"
- "st4 { v16.d, v17.d, v18.d, v19.d }[0], [%0]"
- : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18", "v19");
- break;
-
- default:
- if (dest != reg)
- return memcpy (dest, reg, 16 * (4 - (h & 3)));
- break;
- }
- return dest;
-}
-#endif
-
-/* Either allocate an appropriate register for the argument type, or if
- none are available, allocate a stack slot and return a pointer
- to the allocated space. */
-
-static void *
-allocate_int_to_reg_or_stack (struct call_context *context,
- struct arg_state *state,
- void *stack, size_t size)
-{
- if (state->ngrn < N_X_ARG_REG)
- return &context->x[state->ngrn++];
-
- state->ngrn = N_X_ARG_REG;
- return allocate_to_stack (state, stack, size, size);
-}
-
-ffi_status FFI_HIDDEN
-ffi_prep_cif_machdep (ffi_cif *cif)
-{
- ffi_type *rtype = cif->rtype;
- size_t bytes = cif->bytes;
- int flags, i, n;
-
- switch (rtype->type)
- {
- case FFI_TYPE_VOID:
- flags = AARCH64_RET_VOID;
- break;
- case FFI_TYPE_UINT8:
- flags = AARCH64_RET_UINT8;
- break;
- case FFI_TYPE_UINT16:
- flags = AARCH64_RET_UINT16;
- break;
- case FFI_TYPE_UINT32:
- flags = AARCH64_RET_UINT32;
- break;
- case FFI_TYPE_SINT8:
- flags = AARCH64_RET_SINT8;
- break;
- case FFI_TYPE_SINT16:
- flags = AARCH64_RET_SINT16;
- break;
- case FFI_TYPE_INT:
- case FFI_TYPE_SINT32:
- flags = AARCH64_RET_SINT32;
- break;
- case FFI_TYPE_SINT64:
- case FFI_TYPE_UINT64:
- flags = AARCH64_RET_INT64;
- break;
- case FFI_TYPE_POINTER:
- flags = (sizeof(void *) == 4 ? AARCH64_RET_UINT32 : AARCH64_RET_INT64);
- break;
-
- case FFI_TYPE_FLOAT:
- case FFI_TYPE_DOUBLE:
- case FFI_TYPE_LONGDOUBLE:
- case FFI_TYPE_STRUCT:
- case FFI_TYPE_COMPLEX:
- flags = is_vfp_type (rtype);
- if (flags == 0)
- {
- size_t s = rtype->size;
- if (s > 16)
- {
- flags = AARCH64_RET_VOID | AARCH64_RET_IN_MEM;
- bytes += 8;
- }
- else if (s == 16)
- flags = AARCH64_RET_INT128;
- else if (s == 8)
- flags = AARCH64_RET_INT64;
- else
- flags = AARCH64_RET_INT128 | AARCH64_RET_NEED_COPY;
- }
- break;
-
- default:
- abort();
- }
-
- for (i = 0, n = cif->nargs; i < n; i++)
- if (is_vfp_type (cif->arg_types[i]))
- {
- flags |= AARCH64_FLAG_ARG_V;
- break;
- }
-
- /* Round the stack up to a multiple of the stack alignment requirement. */
- cif->bytes = (unsigned) FFI_ALIGN(bytes, 16);
- cif->flags = flags;
-#if defined (__APPLE__)
- cif->aarch64_nfixedargs = 0;
-#endif
-
- return FFI_OK;
-}
-
-#if defined (__APPLE__)
-/* Perform Apple-specific cif processing for variadic calls */
-ffi_status FFI_HIDDEN
-ffi_prep_cif_machdep_var(ffi_cif *cif, unsigned int nfixedargs,
- unsigned int ntotalargs)
-{
- ffi_status status = ffi_prep_cif_machdep (cif);
- cif->aarch64_nfixedargs = nfixedargs;
- return status;
-}
-#endif /* __APPLE__ */
-
-extern void ffi_call_SYSV (struct call_context *context, void *frame,
- void (*fn)(void), void *rvalue, int flags,
- void *closure) FFI_HIDDEN;
-
-/* Call a function with the provided arguments and capture the return
- value. */
-static void
-ffi_call_int (ffi_cif *cif, void (*fn)(void), void *orig_rvalue,
- void **avalue, void *closure)
-{
- struct call_context *context;
- void *stack, *frame, *rvalue;
- struct arg_state state;
- size_t stack_bytes, rtype_size, rsize;
- int i, nargs, flags;
- ffi_type *rtype;
-
- flags = cif->flags;
- rtype = cif->rtype;
- rtype_size = rtype->size;
- stack_bytes = cif->bytes;
-
- /* If the target function returns a structure via hidden pointer,
- then we cannot allow a null rvalue. Otherwise, mash a null
- rvalue to void return type. */
- rsize = 0;
- if (flags & AARCH64_RET_IN_MEM)
- {
- if (orig_rvalue == NULL)
- rsize = rtype_size;
- }
- else if (orig_rvalue == NULL)
- flags &= AARCH64_FLAG_ARG_V;
- else if (flags & AARCH64_RET_NEED_COPY)
- rsize = 16;
-
- /* Allocate consectutive stack for everything we'll need. */
- context = alloca (sizeof(struct call_context) + stack_bytes + 32 + rsize);
- stack = context + 1;
- frame = (void*)((uintptr_t)stack + (uintptr_t)stack_bytes);
- rvalue = (rsize ? (void*)((uintptr_t)frame + 32) : orig_rvalue);
-
- arg_init (&state);
- for (i = 0, nargs = cif->nargs; i < nargs; i++)
- {
- ffi_type *ty = cif->arg_types[i];
- size_t s = ty->size;
- void *a = avalue[i];
- int h, t;
-
- t = ty->type;
- switch (t)
- {
- case FFI_TYPE_VOID:
- FFI_ASSERT (0);
- break;
-
- /* If the argument is a basic type the argument is allocated to an
- appropriate register, or if none are available, to the stack. */
- case FFI_TYPE_INT:
- case FFI_TYPE_UINT8:
- case FFI_TYPE_SINT8:
- case FFI_TYPE_UINT16:
- case FFI_TYPE_SINT16:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- case FFI_TYPE_POINTER:
- do_pointer:
- {
- ffi_arg ext = extend_integer_type (a, t);
- if (state.ngrn < N_X_ARG_REG)
- context->x[state.ngrn++] = ext;
- else
- {
- void *d = allocate_to_stack (&state, stack, ty->alignment, s);
- state.ngrn = N_X_ARG_REG;
- /* Note that the default abi extends each argument
- to a full 64-bit slot, while the iOS abi allocates
- only enough space. */
-#ifdef __APPLE__
- memcpy(d, a, s);
-#else
- *(ffi_arg *)d = ext;
-#endif
- }
- }
- break;
-
- case FFI_TYPE_FLOAT:
- case FFI_TYPE_DOUBLE:
- case FFI_TYPE_LONGDOUBLE:
- case FFI_TYPE_STRUCT:
- case FFI_TYPE_COMPLEX:
- {
- void *dest;
-
- h = is_vfp_type (ty);
- if (h)
- {
- int elems = 4 - (h & 3);
-#ifdef _M_ARM64 /* for handling armasm calling convention */
- if (cif->is_variadic)
- {
- if (state.ngrn + elems <= N_X_ARG_REG)
- {
- dest = &context->x[state.ngrn];
- state.ngrn += elems;
- extend_hfa_type(dest, a, h);
- break;
- }
- state.nsrn = N_X_ARG_REG;
- dest = allocate_to_stack(&state, stack, ty->alignment, s);
- }
- else
- {
-#endif /* for handling armasm calling convention */
- if (state.nsrn + elems <= N_V_ARG_REG)
- {
- dest = &context->v[state.nsrn];
- state.nsrn += elems;
- extend_hfa_type (dest, a, h);
- break;
- }
- state.nsrn = N_V_ARG_REG;
- dest = allocate_to_stack (&state, stack, ty->alignment, s);
-#ifdef _M_ARM64 /* for handling armasm calling convention */
- }
-#endif /* for handling armasm calling convention */
- }
- else if (s > 16)
- {
- /* If the argument is a composite type that is larger than 16
- bytes, then the argument has been copied to memory, and
- the argument is replaced by a pointer to the copy. */
- a = &avalue[i];
- t = FFI_TYPE_POINTER;
- s = sizeof (void *);
- goto do_pointer;
- }
- else
- {
- size_t n = (s + 7) / 8;
- if (state.ngrn + n <= N_X_ARG_REG)
- {
- /* If the argument is a composite type and the size in
- double-words is not more than the number of available
- X registers, then the argument is copied into
- consecutive X registers. */
- dest = &context->x[state.ngrn];
- state.ngrn += (unsigned int)n;
- }
- else
- {
- /* Otherwise, there are insufficient X registers. Further
- X register allocations are prevented, the NSAA is
- adjusted and the argument is copied to memory at the
- adjusted NSAA. */
- state.ngrn = N_X_ARG_REG;
- dest = allocate_to_stack (&state, stack, ty->alignment, s);
- }
- }
- memcpy (dest, a, s);
- }
- break;
-
- default:
- abort();
- }
-
-#if defined (__APPLE__)
- if (i + 1 == cif->aarch64_nfixedargs)
- {
- state.ngrn = N_X_ARG_REG;
- state.nsrn = N_V_ARG_REG;
- state.allocating_variadic = 1;
- }
-#endif
- }
-
- ffi_call_SYSV (context, frame, fn, rvalue, flags, closure);
-
- if (flags & AARCH64_RET_NEED_COPY)
- memcpy (orig_rvalue, rvalue, rtype_size);
-}
-
-void
-ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue)
-{
- ffi_call_int (cif, fn, rvalue, avalue, NULL);
-}
-
-#ifdef FFI_GO_CLOSURES
-void
-ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue,
- void **avalue, void *closure)
-{
- ffi_call_int (cif, fn, rvalue, avalue, closure);
-}
-#endif /* FFI_GO_CLOSURES */
-
-/* Build a trampoline. */
-
-extern void ffi_closure_SYSV (void) FFI_HIDDEN;
-extern void ffi_closure_SYSV_V (void) FFI_HIDDEN;
-
-ffi_status
-ffi_prep_closure_loc (ffi_closure *closure,
- ffi_cif* cif,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- void *codeloc)
-{
- if (cif->abi != FFI_SYSV)
- return FFI_BAD_ABI;
-
- void (*start)(void);
-
- if (cif->flags & AARCH64_FLAG_ARG_V)
- start = ffi_closure_SYSV_V;
- else
- start = ffi_closure_SYSV;
-
-#if FFI_EXEC_TRAMPOLINE_TABLE
-#ifdef __MACH__
- void **config = (void **)((uint8_t *)codeloc - PAGE_MAX_SIZE);
- config[0] = closure;
- config[1] = start;
-#endif
-#else
- static const unsigned char trampoline[16] = {
- 0x90, 0x00, 0x00, 0x58, /* ldr x16, tramp+16 */
- 0xf1, 0xff, 0xff, 0x10, /* adr x17, tramp+0 */
- 0x00, 0x02, 0x1f, 0xd6 /* br x16 */
- };
- char *tramp = closure->tramp;
-
- memcpy (tramp, trampoline, sizeof(trampoline));
-
- *(UINT64 *)(tramp + 16) = (uintptr_t)start;
-
- ffi_clear_cache(tramp, tramp + FFI_TRAMPOLINE_SIZE);
-
- /* Also flush the cache for code mapping. */
-#ifdef _M_ARM64
- // Not using dlmalloc.c for Windows ARM64 builds
- // so calling ffi_data_to_code_pointer() isn't necessary
- unsigned char *tramp_code = tramp;
- #else
- unsigned char *tramp_code = ffi_data_to_code_pointer (tramp);
- #endif
- ffi_clear_cache (tramp_code, tramp_code + FFI_TRAMPOLINE_SIZE);
-#endif
-
- closure->cif = cif;
- closure->fun = fun;
- closure->user_data = user_data;
-
- return FFI_OK;
-}
-
-#ifdef FFI_GO_CLOSURES
-extern void ffi_go_closure_SYSV (void) FFI_HIDDEN;
-extern void ffi_go_closure_SYSV_V (void) FFI_HIDDEN;
-
-ffi_status
-ffi_prep_go_closure (ffi_go_closure *closure, ffi_cif* cif,
- void (*fun)(ffi_cif*,void*,void**,void*))
-{
- void (*start)(void);
-
- if (cif->abi != FFI_SYSV)
- return FFI_BAD_ABI;
-
- if (cif->flags & AARCH64_FLAG_ARG_V)
- start = ffi_go_closure_SYSV_V;
- else
- start = ffi_go_closure_SYSV;
-
- closure->tramp = start;
- closure->cif = cif;
- closure->fun = fun;
-
- return FFI_OK;
-}
-#endif /* FFI_GO_CLOSURES */
-
-/* Primary handler to setup and invoke a function within a closure.
-
- A closure when invoked enters via the assembler wrapper
- ffi_closure_SYSV(). The wrapper allocates a call context on the
- stack, saves the interesting registers (from the perspective of
- the calling convention) into the context then passes control to
- ffi_closure_SYSV_inner() passing the saved context and a pointer to
- the stack at the point ffi_closure_SYSV() was invoked.
-
- On the return path the assembler wrapper will reload call context
- registers.
-
- ffi_closure_SYSV_inner() marshalls the call context into ffi value
- descriptors, invokes the wrapped function, then marshalls the return
- value back into the call context. */
-
-int FFI_HIDDEN
-ffi_closure_SYSV_inner (ffi_cif *cif,
- void (*fun)(ffi_cif*,void*,void**,void*),
- void *user_data,
- struct call_context *context,
- void *stack, void *rvalue, void *struct_rvalue)
-{
- void **avalue = (void**) alloca (cif->nargs * sizeof (void*));
- int i, h, nargs, flags;
- struct arg_state state;
-
- arg_init (&state);
-
- for (i = 0, nargs = cif->nargs; i < nargs; i++)
- {
- ffi_type *ty = cif->arg_types[i];
- int t = ty->type;
- size_t n, s = ty->size;
-
- switch (t)
- {
- case FFI_TYPE_VOID:
- FFI_ASSERT (0);
- break;
-
- case FFI_TYPE_INT:
- case FFI_TYPE_UINT8:
- case FFI_TYPE_SINT8:
- case FFI_TYPE_UINT16:
- case FFI_TYPE_SINT16:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- case FFI_TYPE_POINTER:
- avalue[i] = allocate_int_to_reg_or_stack (context, &state, stack, s);
- break;
-
- case FFI_TYPE_FLOAT:
- case FFI_TYPE_DOUBLE:
- case FFI_TYPE_LONGDOUBLE:
- case FFI_TYPE_STRUCT:
- case FFI_TYPE_COMPLEX:
- h = is_vfp_type (ty);
- if (h)
- {
- n = 4 - (h & 3);
-#ifdef _M_ARM64 /* for handling armasm calling convention */
- if (cif->is_variadic)
- {
- if (state.ngrn + n <= N_X_ARG_REG)
- {
- void *reg = &context->x[state.ngrn];
- state.ngrn += (unsigned int)n;
-
- /* Eeek! We need a pointer to the structure, however the
- homogeneous float elements are being passed in individual
- registers, therefore for float and double the structure
- is not represented as a contiguous sequence of bytes in
- our saved register context. We don't need the original
- contents of the register storage, so we reformat the
- structure into the same memory. */
- avalue[i] = compress_hfa_type(reg, reg, h);
- }
- else
- {
- state.ngrn = N_X_ARG_REG;
- state.nsrn = N_V_ARG_REG;
- avalue[i] = allocate_to_stack(&state, stack,
- ty->alignment, s);
- }
- }
- else
- {
-#endif /* for handling armasm calling convention */
- if (state.nsrn + n <= N_V_ARG_REG)
- {
- void *reg = &context->v[state.nsrn];
- state.nsrn += (unsigned int)n;
- avalue[i] = compress_hfa_type(reg, reg, h);
- }
- else
- {
- state.nsrn = N_V_ARG_REG;
- avalue[i] = allocate_to_stack(&state, stack,
- ty->alignment, s);
- }
-#ifdef _M_ARM64 /* for handling armasm calling convention */
- }
-#endif /* for handling armasm calling convention */
- }
- else if (s > 16)
- {
- /* Replace Composite type of size greater than 16 with a
- pointer. */
- avalue[i] = *(void **)
- allocate_int_to_reg_or_stack (context, &state, stack,
- sizeof (void *));
- }
- else
- {
- n = (s + 7) / 8;
- if (state.ngrn + n <= N_X_ARG_REG)
- {
- avalue[i] = &context->x[state.ngrn];
- state.ngrn += (unsigned int)n;
- }
- else
- {
- state.ngrn = N_X_ARG_REG;
- avalue[i] = allocate_to_stack(&state, stack,
- ty->alignment, s);
- }
- }
- break;
-
- default:
- abort();
- }
-
-#if defined (__APPLE__)
- if (i + 1 == cif->aarch64_nfixedargs)
- {
- state.ngrn = N_X_ARG_REG;
- state.nsrn = N_V_ARG_REG;
- state.allocating_variadic = 1;
- }
-#endif
- }
-
- flags = cif->flags;
- if (flags & AARCH64_RET_IN_MEM)
- rvalue = struct_rvalue;
-
- fun (cif, rvalue, avalue, user_data);
-
- return flags;
-}
-
-#endif /* (__aarch64__) || defined(__arm64__)|| defined (_M_ARM64)*/
+/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+``Software''), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+
+#if defined(__aarch64__) || defined(__arm64__)|| defined (_M_ARM64)
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <fficonfig.h>
+#include <ffi.h>
+#include <ffi_common.h>
+#include "internal.h"
+#ifdef _M_ARM64
+#include <windows.h> /* FlushInstructionCache */
+#endif
+
+/* Force FFI_TYPE_LONGDOUBLE to be different than FFI_TYPE_DOUBLE;
+ all further uses in this file will refer to the 128-bit type. */
+#if FFI_TYPE_DOUBLE != FFI_TYPE_LONGDOUBLE
+# if FFI_TYPE_LONGDOUBLE != 4
+# error FFI_TYPE_LONGDOUBLE out of date
+# endif
+#else
+# undef FFI_TYPE_LONGDOUBLE
+# define FFI_TYPE_LONGDOUBLE 4
+#endif
+
+union _d
+{
+ UINT64 d;
+ UINT32 s[2];
+};
+
+struct _v
+{
+ union _d d[2] __attribute__((aligned(16)));
+};
+
+struct call_context
+{
+ struct _v v[N_V_ARG_REG];
+ UINT64 x[N_X_ARG_REG];
+};
+
+#if FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#include <mach/vm_param.h>
+#endif
+
+#else
+
+#if defined (__clang__) && defined (__APPLE__)
+extern void sys_icache_invalidate (void *start, size_t len);
+#endif
+
+static inline void
+ffi_clear_cache (void *start, void *end)
+{
+#if defined (__clang__) && defined (__APPLE__)
+ sys_icache_invalidate (start, (char *)end - (char *)start);
+#elif defined (__GNUC__)
+ __builtin___clear_cache (start, end);
+#elif defined (_M_ARM64)
+ FlushInstructionCache(GetCurrentProcess(), start, (char*)end - (char*)start);
+#else
+#error "Missing builtin to flush instruction cache"
+#endif
+}
+
+#endif
+
+/* A subroutine of is_vfp_type. Given a structure type, return the type code
+ of the first non-structure element. Recurse for structure elements.
+ Return -1 if the structure is in fact empty, i.e. no nested elements. */
+
+static int
+is_hfa0 (const ffi_type *ty)
+{
+ ffi_type **elements = ty->elements;
+ int i, ret = -1;
+
+ if (elements != NULL)
+ for (i = 0; elements[i]; ++i)
+ {
+ ret = elements[i]->type;
+ if (ret == FFI_TYPE_STRUCT || ret == FFI_TYPE_COMPLEX)
+ {
+ ret = is_hfa0 (elements[i]);
+ if (ret < 0)
+ continue;
+ }
+ break;
+ }
+
+ return ret;
+}
+
+/* A subroutine of is_vfp_type. Given a structure type, return true if all
+ of the non-structure elements are the same as CANDIDATE. */
+
+static int
+is_hfa1 (const ffi_type *ty, int candidate)
+{
+ ffi_type **elements = ty->elements;
+ int i;
+
+ if (elements != NULL)
+ for (i = 0; elements[i]; ++i)
+ {
+ int t = elements[i]->type;
+ if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
+ {
+ if (!is_hfa1 (elements[i], candidate))
+ return 0;
+ }
+ else if (t != candidate)
+ return 0;
+ }
+
+ return 1;
+}
+
+/* Determine if TY may be allocated to the FP registers. This is both an
+ fp scalar type as well as an homogenous floating point aggregate (HFA).
+ That is, a structure consisting of 1 to 4 members of all the same type,
+ where that type is an fp scalar.
+
+ Returns non-zero iff TY is an HFA. The result is the AARCH64_RET_*
+ constant for the type. */
+
+static int
+is_vfp_type (const ffi_type *ty)
+{
+ ffi_type **elements;
+ int candidate, i;
+ size_t size, ele_count;
+
+ /* Quickest tests first. */
+ candidate = ty->type;
+ switch (candidate)
+ {
+ default:
+ return 0;
+ case FFI_TYPE_FLOAT:
+ case FFI_TYPE_DOUBLE:
+ case FFI_TYPE_LONGDOUBLE:
+ ele_count = 1;
+ goto done;
+ case FFI_TYPE_COMPLEX:
+ candidate = ty->elements[0]->type;
+ switch (candidate)
+ {
+ case FFI_TYPE_FLOAT:
+ case FFI_TYPE_DOUBLE:
+ case FFI_TYPE_LONGDOUBLE:
+ ele_count = 2;
+ goto done;
+ }
+ return 0;
+ case FFI_TYPE_STRUCT:
+ break;
+ }
+
+ /* No HFA types are smaller than 4 bytes, or larger than 64 bytes. */
+ size = ty->size;
+ if (size < 4 || size > 64)
+ return 0;
+
+ /* Find the type of the first non-structure member. */
+ elements = ty->elements;
+ candidate = elements[0]->type;
+ if (candidate == FFI_TYPE_STRUCT || candidate == FFI_TYPE_COMPLEX)
+ {
+ for (i = 0; ; ++i)
+ {
+ candidate = is_hfa0 (elements[i]);
+ if (candidate >= 0)
+ break;
+ }
+ }
+
+ /* If the first member is not a floating point type, it's not an HFA.
+ Also quickly re-check the size of the structure. */
+ switch (candidate)
+ {
+ case FFI_TYPE_FLOAT:
+ ele_count = size / sizeof(float);
+ if (size != ele_count * sizeof(float))
+ return 0;
+ break;
+ case FFI_TYPE_DOUBLE:
+ ele_count = size / sizeof(double);
+ if (size != ele_count * sizeof(double))
+ return 0;
+ break;
+ case FFI_TYPE_LONGDOUBLE:
+ ele_count = size / sizeof(long double);
+ if (size != ele_count * sizeof(long double))
+ return 0;
+ break;
+ default:
+ return 0;
+ }
+ if (ele_count > 4)
+ return 0;
+
+ /* Finally, make sure that all scalar elements are the same type. */
+ for (i = 0; elements[i]; ++i)
+ {
+ int t = elements[i]->type;
+ if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
+ {
+ if (!is_hfa1 (elements[i], candidate))
+ return 0;
+ }
+ else if (t != candidate)
+ return 0;
+ }
+
+ /* All tests succeeded. Encode the result. */
+ done:
+ return candidate * 4 + (4 - (int)ele_count);
+}
+
+/* Representation of the procedure call argument marshalling
+ state.
+
+ The terse state variable names match the names used in the AARCH64
+ PCS. */
+
+struct arg_state
+{
+ unsigned ngrn; /* Next general-purpose register number. */
+ unsigned nsrn; /* Next vector register number. */
+ size_t nsaa; /* Next stack offset. */
+
+#if defined (__APPLE__)
+ unsigned allocating_variadic;
+#endif
+};
+
+/* Initialize a procedure call argument marshalling state. */
+static void
+arg_init (struct arg_state *state)
+{
+ state->ngrn = 0;
+ state->nsrn = 0;
+ state->nsaa = 0;
+#if defined (__APPLE__)
+ state->allocating_variadic = 0;
+#endif
+}
+
+/* Allocate an aligned slot on the stack and return a pointer to it. */
+static void *
+allocate_to_stack (struct arg_state *state, void *stack,
+ size_t alignment, size_t size)
+{
+ size_t nsaa = state->nsaa;
+
+ /* Round up the NSAA to the larger of 8 or the natural
+ alignment of the argument's type. */
+#if defined (__APPLE__)
+ if (state->allocating_variadic && alignment < 8)
+ alignment = 8;
+#else
+ if (alignment < 8)
+ alignment = 8;
+#endif
+
+ nsaa = FFI_ALIGN (nsaa, alignment);
+ state->nsaa = nsaa + size;
+
+ return (char *)stack + nsaa;
+}
+
+static ffi_arg
+extend_integer_type (void *source, int type)
+{
+ switch (type)
+ {
+ case FFI_TYPE_UINT8:
+ return *(UINT8 *) source;
+ case FFI_TYPE_SINT8:
+ return *(SINT8 *) source;
+ case FFI_TYPE_UINT16:
+ return *(UINT16 *) source;
+ case FFI_TYPE_SINT16:
+ return *(SINT16 *) source;
+ case FFI_TYPE_UINT32:
+ return *(UINT32 *) source;
+ case FFI_TYPE_INT:
+ case FFI_TYPE_SINT32:
+ return *(SINT32 *) source;
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ return *(UINT64 *) source;
+ break;
+ case FFI_TYPE_POINTER:
+ return *(uintptr_t *) source;
+ default:
+ abort();
+ }
+}
+
+#if defined(_MSC_VER)
+void extend_hfa_type (void *dest, void *src, int h);
+#else
+static void
+extend_hfa_type (void *dest, void *src, int h)
+{
+ ssize_t f = h - AARCH64_RET_S4;
+ void *x0;
+
+ asm volatile (
+ "adr %0, 0f\n"
+" add %0, %0, %1\n"
+" br %0\n"
+"0: ldp s16, s17, [%3]\n" /* S4 */
+" ldp s18, s19, [%3, #8]\n"
+" b 4f\n"
+" ldp s16, s17, [%3]\n" /* S3 */
+" ldr s18, [%3, #8]\n"
+" b 3f\n"
+" ldp s16, s17, [%3]\n" /* S2 */
+" b 2f\n"
+" nop\n"
+" ldr s16, [%3]\n" /* S1 */
+" b 1f\n"
+" nop\n"
+" ldp d16, d17, [%3]\n" /* D4 */
+" ldp d18, d19, [%3, #16]\n"
+" b 4f\n"
+" ldp d16, d17, [%3]\n" /* D3 */
+" ldr d18, [%3, #16]\n"
+" b 3f\n"
+" ldp d16, d17, [%3]\n" /* D2 */
+" b 2f\n"
+" nop\n"
+" ldr d16, [%3]\n" /* D1 */
+" b 1f\n"
+" nop\n"
+" ldp q16, q17, [%3]\n" /* Q4 */
+" ldp q18, q19, [%3, #32]\n"
+" b 4f\n"
+" ldp q16, q17, [%3]\n" /* Q3 */
+" ldr q18, [%3, #32]\n"
+" b 3f\n"
+" ldp q16, q17, [%3]\n" /* Q2 */
+" b 2f\n"
+" nop\n"
+" ldr q16, [%3]\n" /* Q1 */
+" b 1f\n"
+"4: str q19, [%2, #48]\n"
+"3: str q18, [%2, #32]\n"
+"2: str q17, [%2, #16]\n"
+"1: str q16, [%2]"
+ : "=&r"(x0)
+ : "r"(f * 12), "r"(dest), "r"(src)
+ : "memory", "v16", "v17", "v18", "v19");
+}
+#endif
+
+#if defined(_MSC_VER)
+void* compress_hfa_type (void *dest, void *src, int h);
+#else
+static void *
+compress_hfa_type (void *dest, void *reg, int h)
+{
+ switch (h)
+ {
+ case AARCH64_RET_S1:
+ if (dest == reg)
+ {
+#ifdef __AARCH64EB__
+ dest += 12;
+#endif
+ }
+ else
+ *(float *)dest = *(float *)reg;
+ break;
+ case AARCH64_RET_S2:
+ asm ("ldp q16, q17, [%1]\n\t"
+ "st2 { v16.s, v17.s }[0], [%0]"
+ : : "r"(dest), "r"(reg) : "memory", "v16", "v17");
+ break;
+ case AARCH64_RET_S3:
+ asm ("ldp q16, q17, [%1]\n\t"
+ "ldr q18, [%1, #32]\n\t"
+ "st3 { v16.s, v17.s, v18.s }[0], [%0]"
+ : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18");
+ break;
+ case AARCH64_RET_S4:
+ asm ("ldp q16, q17, [%1]\n\t"
+ "ldp q18, q19, [%1, #32]\n\t"
+ "st4 { v16.s, v17.s, v18.s, v19.s }[0], [%0]"
+ : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18", "v19");
+ break;
+
+ case AARCH64_RET_D1:
+ if (dest == reg)
+ {
+#ifdef __AARCH64EB__
+ dest += 8;
+#endif
+ }
+ else
+ *(double *)dest = *(double *)reg;
+ break;
+ case AARCH64_RET_D2:
+ asm ("ldp q16, q17, [%1]\n\t"
+ "st2 { v16.d, v17.d }[0], [%0]"
+ : : "r"(dest), "r"(reg) : "memory", "v16", "v17");
+ break;
+ case AARCH64_RET_D3:
+ asm ("ldp q16, q17, [%1]\n\t"
+ "ldr q18, [%1, #32]\n\t"
+ "st3 { v16.d, v17.d, v18.d }[0], [%0]"
+ : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18");
+ break;
+ case AARCH64_RET_D4:
+ asm ("ldp q16, q17, [%1]\n\t"
+ "ldp q18, q19, [%1, #32]\n\t"
+ "st4 { v16.d, v17.d, v18.d, v19.d }[0], [%0]"
+ : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18", "v19");
+ break;
+
+ default:
+ if (dest != reg)
+ return memcpy (dest, reg, 16 * (4 - (h & 3)));
+ break;
+ }
+ return dest;
+}
+#endif
+
+/* Either allocate an appropriate register for the argument type, or if
+ none are available, allocate a stack slot and return a pointer
+ to the allocated space. */
+
+static void *
+allocate_int_to_reg_or_stack (struct call_context *context,
+ struct arg_state *state,
+ void *stack, size_t size)
+{
+ if (state->ngrn < N_X_ARG_REG)
+ return &context->x[state->ngrn++];
+
+ state->ngrn = N_X_ARG_REG;
+ return allocate_to_stack (state, stack, size, size);
+}
+
+ffi_status FFI_HIDDEN
+ffi_prep_cif_machdep (ffi_cif *cif)
+{
+ ffi_type *rtype = cif->rtype;
+ size_t bytes = cif->bytes;
+ int flags, i, n;
+
+ switch (rtype->type)
+ {
+ case FFI_TYPE_VOID:
+ flags = AARCH64_RET_VOID;
+ break;
+ case FFI_TYPE_UINT8:
+ flags = AARCH64_RET_UINT8;
+ break;
+ case FFI_TYPE_UINT16:
+ flags = AARCH64_RET_UINT16;
+ break;
+ case FFI_TYPE_UINT32:
+ flags = AARCH64_RET_UINT32;
+ break;
+ case FFI_TYPE_SINT8:
+ flags = AARCH64_RET_SINT8;
+ break;
+ case FFI_TYPE_SINT16:
+ flags = AARCH64_RET_SINT16;
+ break;
+ case FFI_TYPE_INT:
+ case FFI_TYPE_SINT32:
+ flags = AARCH64_RET_SINT32;
+ break;
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_UINT64:
+ flags = AARCH64_RET_INT64;
+ break;
+ case FFI_TYPE_POINTER:
+ flags = (sizeof(void *) == 4 ? AARCH64_RET_UINT32 : AARCH64_RET_INT64);
+ break;
+
+ case FFI_TYPE_FLOAT:
+ case FFI_TYPE_DOUBLE:
+ case FFI_TYPE_LONGDOUBLE:
+ case FFI_TYPE_STRUCT:
+ case FFI_TYPE_COMPLEX:
+ flags = is_vfp_type (rtype);
+ if (flags == 0)
+ {
+ size_t s = rtype->size;
+ if (s > 16)
+ {
+ flags = AARCH64_RET_VOID | AARCH64_RET_IN_MEM;
+ bytes += 8;
+ }
+ else if (s == 16)
+ flags = AARCH64_RET_INT128;
+ else if (s == 8)
+ flags = AARCH64_RET_INT64;
+ else
+ flags = AARCH64_RET_INT128 | AARCH64_RET_NEED_COPY;
+ }
+ break;
+
+ default:
+ abort();
+ }
+
+ for (i = 0, n = cif->nargs; i < n; i++)
+ if (is_vfp_type (cif->arg_types[i]))
+ {
+ flags |= AARCH64_FLAG_ARG_V;
+ break;
+ }
+
+ /* Round the stack up to a multiple of the stack alignment requirement. */
+ cif->bytes = (unsigned) FFI_ALIGN(bytes, 16);
+ cif->flags = flags;
+#if defined (__APPLE__)
+ cif->aarch64_nfixedargs = 0;
+#endif
+
+ return FFI_OK;
+}
+
+#if defined (__APPLE__)
+/* Perform Apple-specific cif processing for variadic calls */
+ffi_status FFI_HIDDEN
+ffi_prep_cif_machdep_var(ffi_cif *cif, unsigned int nfixedargs,
+ unsigned int ntotalargs)
+{
+ ffi_status status = ffi_prep_cif_machdep (cif);
+ cif->aarch64_nfixedargs = nfixedargs;
+ return status;
+}
+#endif /* __APPLE__ */
+
+extern void ffi_call_SYSV (struct call_context *context, void *frame,
+ void (*fn)(void), void *rvalue, int flags,
+ void *closure) FFI_HIDDEN;
+
+/* Call a function with the provided arguments and capture the return
+ value. */
+static void
+ffi_call_int (ffi_cif *cif, void (*fn)(void), void *orig_rvalue,
+ void **avalue, void *closure)
+{
+ struct call_context *context;
+ void *stack, *frame, *rvalue;
+ struct arg_state state;
+ size_t stack_bytes, rtype_size, rsize;
+ int i, nargs, flags;
+ ffi_type *rtype;
+
+ flags = cif->flags;
+ rtype = cif->rtype;
+ rtype_size = rtype->size;
+ stack_bytes = cif->bytes;
+
+ /* If the target function returns a structure via hidden pointer,
+ then we cannot allow a null rvalue. Otherwise, mash a null
+ rvalue to void return type. */
+ rsize = 0;
+ if (flags & AARCH64_RET_IN_MEM)
+ {
+ if (orig_rvalue == NULL)
+ rsize = rtype_size;
+ }
+ else if (orig_rvalue == NULL)
+ flags &= AARCH64_FLAG_ARG_V;
+ else if (flags & AARCH64_RET_NEED_COPY)
+ rsize = 16;
+
+ /* Allocate consectutive stack for everything we'll need. */
+ context = alloca (sizeof(struct call_context) + stack_bytes + 32 + rsize);
+ stack = context + 1;
+ frame = (void*)((uintptr_t)stack + (uintptr_t)stack_bytes);
+ rvalue = (rsize ? (void*)((uintptr_t)frame + 32) : orig_rvalue);
+
+ arg_init (&state);
+ for (i = 0, nargs = cif->nargs; i < nargs; i++)
+ {
+ ffi_type *ty = cif->arg_types[i];
+ size_t s = ty->size;
+ void *a = avalue[i];
+ int h, t;
+
+ t = ty->type;
+ switch (t)
+ {
+ case FFI_TYPE_VOID:
+ FFI_ASSERT (0);
+ break;
+
+ /* If the argument is a basic type the argument is allocated to an
+ appropriate register, or if none are available, to the stack. */
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_POINTER:
+ do_pointer:
+ {
+ ffi_arg ext = extend_integer_type (a, t);
+ if (state.ngrn < N_X_ARG_REG)
+ context->x[state.ngrn++] = ext;
+ else
+ {
+ void *d = allocate_to_stack (&state, stack, ty->alignment, s);
+ state.ngrn = N_X_ARG_REG;
+ /* Note that the default abi extends each argument
+ to a full 64-bit slot, while the iOS abi allocates
+ only enough space. */
+#ifdef __APPLE__
+ memcpy(d, a, s);
+#else
+ *(ffi_arg *)d = ext;
+#endif
+ }
+ }
+ break;
+
+ case FFI_TYPE_FLOAT:
+ case FFI_TYPE_DOUBLE:
+ case FFI_TYPE_LONGDOUBLE:
+ case FFI_TYPE_STRUCT:
+ case FFI_TYPE_COMPLEX:
+ {
+ void *dest;
+
+ h = is_vfp_type (ty);
+ if (h)
+ {
+ int elems = 4 - (h & 3);
+#ifdef _M_ARM64 /* for handling armasm calling convention */
+ if (cif->is_variadic)
+ {
+ if (state.ngrn + elems <= N_X_ARG_REG)
+ {
+ dest = &context->x[state.ngrn];
+ state.ngrn += elems;
+ extend_hfa_type(dest, a, h);
+ break;
+ }
+ state.nsrn = N_X_ARG_REG;
+ dest = allocate_to_stack(&state, stack, ty->alignment, s);
+ }
+ else
+ {
+#endif /* for handling armasm calling convention */
+ if (state.nsrn + elems <= N_V_ARG_REG)
+ {
+ dest = &context->v[state.nsrn];
+ state.nsrn += elems;
+ extend_hfa_type (dest, a, h);
+ break;
+ }
+ state.nsrn = N_V_ARG_REG;
+ dest = allocate_to_stack (&state, stack, ty->alignment, s);
+#ifdef _M_ARM64 /* for handling armasm calling convention */
+ }
+#endif /* for handling armasm calling convention */
+ }
+ else if (s > 16)
+ {
+ /* If the argument is a composite type that is larger than 16
+ bytes, then the argument has been copied to memory, and
+ the argument is replaced by a pointer to the copy. */
+ a = &avalue[i];
+ t = FFI_TYPE_POINTER;
+ s = sizeof (void *);
+ goto do_pointer;
+ }
+ else
+ {
+ size_t n = (s + 7) / 8;
+ if (state.ngrn + n <= N_X_ARG_REG)
+ {
+ /* If the argument is a composite type and the size in
+ double-words is not more than the number of available
+ X registers, then the argument is copied into
+ consecutive X registers. */
+ dest = &context->x[state.ngrn];
+ state.ngrn += (unsigned int)n;
+ }
+ else
+ {
+ /* Otherwise, there are insufficient X registers. Further
+ X register allocations are prevented, the NSAA is
+ adjusted and the argument is copied to memory at the
+ adjusted NSAA. */
+ state.ngrn = N_X_ARG_REG;
+ dest = allocate_to_stack (&state, stack, ty->alignment, s);
+ }
+ }
+ memcpy (dest, a, s);
+ }
+ break;
+
+ default:
+ abort();
+ }
+
+#if defined (__APPLE__)
+ if (i + 1 == cif->aarch64_nfixedargs)
+ {
+ state.ngrn = N_X_ARG_REG;
+ state.nsrn = N_V_ARG_REG;
+ state.allocating_variadic = 1;
+ }
+#endif
+ }
+
+ ffi_call_SYSV (context, frame, fn, rvalue, flags, closure);
+
+ if (flags & AARCH64_RET_NEED_COPY)
+ memcpy (orig_rvalue, rvalue, rtype_size);
+}
+
+void
+ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue)
+{
+ ffi_call_int (cif, fn, rvalue, avalue, NULL);
+}
+
+#ifdef FFI_GO_CLOSURES
+void
+ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue,
+ void **avalue, void *closure)
+{
+ ffi_call_int (cif, fn, rvalue, avalue, closure);
+}
+#endif /* FFI_GO_CLOSURES */
+
+/* Build a trampoline. */
+
+extern void ffi_closure_SYSV (void) FFI_HIDDEN;
+extern void ffi_closure_SYSV_V (void) FFI_HIDDEN;
+
+ffi_status
+ffi_prep_closure_loc (ffi_closure *closure,
+ ffi_cif* cif,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ void *codeloc)
+{
+ if (cif->abi != FFI_SYSV)
+ return FFI_BAD_ABI;
+
+ void (*start)(void);
+
+ if (cif->flags & AARCH64_FLAG_ARG_V)
+ start = ffi_closure_SYSV_V;
+ else
+ start = ffi_closure_SYSV;
+
+#if FFI_EXEC_TRAMPOLINE_TABLE
+#ifdef __MACH__
+ void **config = (void **)((uint8_t *)codeloc - PAGE_MAX_SIZE);
+ config[0] = closure;
+ config[1] = start;
+#endif
+#else
+ static const unsigned char trampoline[16] = {
+ 0x90, 0x00, 0x00, 0x58, /* ldr x16, tramp+16 */
+ 0xf1, 0xff, 0xff, 0x10, /* adr x17, tramp+0 */
+ 0x00, 0x02, 0x1f, 0xd6 /* br x16 */
+ };
+ char *tramp = closure->tramp;
+
+ memcpy (tramp, trampoline, sizeof(trampoline));
+
+ *(UINT64 *)(tramp + 16) = (uintptr_t)start;
+
+ ffi_clear_cache(tramp, tramp + FFI_TRAMPOLINE_SIZE);
+
+ /* Also flush the cache for code mapping. */
+#ifdef _M_ARM64
+ // Not using dlmalloc.c for Windows ARM64 builds
+ // so calling ffi_data_to_code_pointer() isn't necessary
+ unsigned char *tramp_code = tramp;
+ #else
+ unsigned char *tramp_code = ffi_data_to_code_pointer (tramp);
+ #endif
+ ffi_clear_cache (tramp_code, tramp_code + FFI_TRAMPOLINE_SIZE);
+#endif
+
+ closure->cif = cif;
+ closure->fun = fun;
+ closure->user_data = user_data;
+
+ return FFI_OK;
+}
+
+#ifdef FFI_GO_CLOSURES
+extern void ffi_go_closure_SYSV (void) FFI_HIDDEN;
+extern void ffi_go_closure_SYSV_V (void) FFI_HIDDEN;
+
+ffi_status
+ffi_prep_go_closure (ffi_go_closure *closure, ffi_cif* cif,
+ void (*fun)(ffi_cif*,void*,void**,void*))
+{
+ void (*start)(void);
+
+ if (cif->abi != FFI_SYSV)
+ return FFI_BAD_ABI;
+
+ if (cif->flags & AARCH64_FLAG_ARG_V)
+ start = ffi_go_closure_SYSV_V;
+ else
+ start = ffi_go_closure_SYSV;
+
+ closure->tramp = start;
+ closure->cif = cif;
+ closure->fun = fun;
+
+ return FFI_OK;
+}
+#endif /* FFI_GO_CLOSURES */
+
+/* Primary handler to setup and invoke a function within a closure.
+
+ A closure when invoked enters via the assembler wrapper
+ ffi_closure_SYSV(). The wrapper allocates a call context on the
+ stack, saves the interesting registers (from the perspective of
+ the calling convention) into the context then passes control to
+ ffi_closure_SYSV_inner() passing the saved context and a pointer to
+ the stack at the point ffi_closure_SYSV() was invoked.
+
+ On the return path the assembler wrapper will reload call context
+ registers.
+
+ ffi_closure_SYSV_inner() marshalls the call context into ffi value
+ descriptors, invokes the wrapped function, then marshalls the return
+ value back into the call context. */
+
+int FFI_HIDDEN
+ffi_closure_SYSV_inner (ffi_cif *cif,
+ void (*fun)(ffi_cif*,void*,void**,void*),
+ void *user_data,
+ struct call_context *context,
+ void *stack, void *rvalue, void *struct_rvalue)
+{
+ void **avalue = (void**) alloca (cif->nargs * sizeof (void*));
+ int i, h, nargs, flags;
+ struct arg_state state;
+
+ arg_init (&state);
+
+ for (i = 0, nargs = cif->nargs; i < nargs; i++)
+ {
+ ffi_type *ty = cif->arg_types[i];
+ int t = ty->type;
+ size_t n, s = ty->size;
+
+ switch (t)
+ {
+ case FFI_TYPE_VOID:
+ FFI_ASSERT (0);
+ break;
+
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_POINTER:
+ avalue[i] = allocate_int_to_reg_or_stack (context, &state, stack, s);
+ break;
+
+ case FFI_TYPE_FLOAT:
+ case FFI_TYPE_DOUBLE:
+ case FFI_TYPE_LONGDOUBLE:
+ case FFI_TYPE_STRUCT:
+ case FFI_TYPE_COMPLEX:
+ h = is_vfp_type (ty);
+ if (h)
+ {
+ n = 4 - (h & 3);
+#ifdef _M_ARM64 /* for handling armasm calling convention */
+ if (cif->is_variadic)
+ {
+ if (state.ngrn + n <= N_X_ARG_REG)
+ {
+ void *reg = &context->x[state.ngrn];
+ state.ngrn += (unsigned int)n;
+
+ /* Eeek! We need a pointer to the structure, however the
+ homogeneous float elements are being passed in individual
+ registers, therefore for float and double the structure
+ is not represented as a contiguous sequence of bytes in
+ our saved register context. We don't need the original
+ contents of the register storage, so we reformat the
+ structure into the same memory. */
+ avalue[i] = compress_hfa_type(reg, reg, h);
+ }
+ else
+ {
+ state.ngrn = N_X_ARG_REG;
+ state.nsrn = N_V_ARG_REG;
+ avalue[i] = allocate_to_stack(&state, stack,
+ ty->alignment, s);
+ }
+ }
+ else
+ {
+#endif /* for handling armasm calling convention */
+ if (state.nsrn + n <= N_V_ARG_REG)
+ {
+ void *reg = &context->v[state.nsrn];
+ state.nsrn += (unsigned int)n;
+ avalue[i] = compress_hfa_type(reg, reg, h);
+ }
+ else
+ {
+ state.nsrn = N_V_ARG_REG;
+ avalue[i] = allocate_to_stack(&state, stack,
+ ty->alignment, s);
+ }
+#ifdef _M_ARM64 /* for handling armasm calling convention */
+ }
+#endif /* for handling armasm calling convention */
+ }
+ else if (s > 16)
+ {
+ /* Replace Composite type of size greater than 16 with a
+ pointer. */
+ avalue[i] = *(void **)
+ allocate_int_to_reg_or_stack (context, &state, stack,
+ sizeof (void *));
+ }
+ else
+ {
+ n = (s + 7) / 8;
+ if (state.ngrn + n <= N_X_ARG_REG)
+ {
+ avalue[i] = &context->x[state.ngrn];
+ state.ngrn += (unsigned int)n;
+ }
+ else
+ {
+ state.ngrn = N_X_ARG_REG;
+ avalue[i] = allocate_to_stack(&state, stack,
+ ty->alignment, s);
+ }
+ }
+ break;
+
+ default:
+ abort();
+ }
+
+#if defined (__APPLE__)
+ if (i + 1 == cif->aarch64_nfixedargs)
+ {
+ state.ngrn = N_X_ARG_REG;
+ state.nsrn = N_V_ARG_REG;
+ state.allocating_variadic = 1;
+ }
+#endif
+ }
+
+ flags = cif->flags;
+ if (flags & AARCH64_RET_IN_MEM)
+ rvalue = struct_rvalue;
+
+ fun (cif, rvalue, avalue, user_data);
+
+ return flags;
+}
+
+#endif /* (__aarch64__) || defined(__arm64__)|| defined (_M_ARM64)*/
diff --git a/contrib/restricted/libffi/src/aarch64/ffitarget.h b/contrib/restricted/libffi/src/aarch64/ffitarget.h
index ddce8f21eb..ecb6d2deae 100644
--- a/contrib/restricted/libffi/src/aarch64/ffitarget.h
+++ b/contrib/restricted/libffi/src/aarch64/ffitarget.h
@@ -1,92 +1,92 @@
-/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-``Software''), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-#ifndef LIBFFI_ASM
-#ifdef __ILP32__
-#define FFI_SIZEOF_ARG 8
-#define FFI_SIZEOF_JAVA_RAW 4
-typedef unsigned long long ffi_arg;
-typedef signed long long ffi_sarg;
-#elif defined(_M_ARM64)
-#define FFI_SIZEOF_ARG 8
-typedef unsigned long long ffi_arg;
-typedef signed long long ffi_sarg;
-#else
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-#endif
-
-typedef enum ffi_abi
- {
- FFI_FIRST_ABI = 0,
- FFI_SYSV,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_SYSV
- } ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_NATIVE_RAW_API 0
-
-#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#define FFI_TRAMPOLINE_SIZE 16
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET 16
-#else
-#error "No trampoline table implementation"
-#endif
-
-#else
-#define FFI_TRAMPOLINE_SIZE 24
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
-#endif
-
-#ifdef _M_ARM64
-#define FFI_EXTRA_CIF_FIELDS unsigned is_variadic
-#endif
-
-/* ---- Internal ---- */
-
-#if defined (__APPLE__)
-#define FFI_TARGET_SPECIFIC_VARIADIC
-#define FFI_EXTRA_CIF_FIELDS unsigned aarch64_nfixedargs
-#elif !defined(_M_ARM64)
-/* iOS and Windows reserve x18 for the system. Disable Go closures until
- a new static chain is chosen. */
-#define FFI_GO_CLOSURES 1
-#endif
-
-#ifndef _M_ARM64
-/* No complex type on Windows */
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-#endif
+/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+``Software''), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+#ifndef LIBFFI_ASM
+#ifdef __ILP32__
+#define FFI_SIZEOF_ARG 8
+#define FFI_SIZEOF_JAVA_RAW 4
+typedef unsigned long long ffi_arg;
+typedef signed long long ffi_sarg;
+#elif defined(_M_ARM64)
+#define FFI_SIZEOF_ARG 8
+typedef unsigned long long ffi_arg;
+typedef signed long long ffi_sarg;
+#else
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+#endif
+
+typedef enum ffi_abi
+ {
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_SYSV
+ } ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_NATIVE_RAW_API 0
+
+#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#define FFI_TRAMPOLINE_SIZE 16
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET 16
+#else
+#error "No trampoline table implementation"
+#endif
+
+#else
+#define FFI_TRAMPOLINE_SIZE 24
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
+#endif
+
+#ifdef _M_ARM64
+#define FFI_EXTRA_CIF_FIELDS unsigned is_variadic
+#endif
+
+/* ---- Internal ---- */
+
+#if defined (__APPLE__)
+#define FFI_TARGET_SPECIFIC_VARIADIC
+#define FFI_EXTRA_CIF_FIELDS unsigned aarch64_nfixedargs
+#elif !defined(_M_ARM64)
+/* iOS and Windows reserve x18 for the system. Disable Go closures until
+ a new static chain is chosen. */
+#define FFI_GO_CLOSURES 1
+#endif
+
+#ifndef _M_ARM64
+/* No complex type on Windows */
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/src/aarch64/internal.h b/contrib/restricted/libffi/src/aarch64/internal.h
index 2691dafa98..9c3e07725a 100644
--- a/contrib/restricted/libffi/src/aarch64/internal.h
+++ b/contrib/restricted/libffi/src/aarch64/internal.h
@@ -1,67 +1,67 @@
-/*
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-``Software''), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-
-#define AARCH64_RET_VOID 0
-#define AARCH64_RET_INT64 1
-#define AARCH64_RET_INT128 2
-
-#define AARCH64_RET_UNUSED3 3
-#define AARCH64_RET_UNUSED4 4
-#define AARCH64_RET_UNUSED5 5
-#define AARCH64_RET_UNUSED6 6
-#define AARCH64_RET_UNUSED7 7
-
-/* Note that FFI_TYPE_FLOAT == 2, _DOUBLE == 3, _LONGDOUBLE == 4,
- so _S4 through _Q1 are layed out as (TYPE * 4) + (4 - COUNT). */
-#define AARCH64_RET_S4 8
-#define AARCH64_RET_S3 9
-#define AARCH64_RET_S2 10
-#define AARCH64_RET_S1 11
-
-#define AARCH64_RET_D4 12
-#define AARCH64_RET_D3 13
-#define AARCH64_RET_D2 14
-#define AARCH64_RET_D1 15
-
-#define AARCH64_RET_Q4 16
-#define AARCH64_RET_Q3 17
-#define AARCH64_RET_Q2 18
-#define AARCH64_RET_Q1 19
-
-/* Note that each of the sub-64-bit integers gets two entries. */
-#define AARCH64_RET_UINT8 20
-#define AARCH64_RET_UINT16 22
-#define AARCH64_RET_UINT32 24
-
-#define AARCH64_RET_SINT8 26
-#define AARCH64_RET_SINT16 28
-#define AARCH64_RET_SINT32 30
-
-#define AARCH64_RET_MASK 31
-
-#define AARCH64_RET_IN_MEM (1 << 5)
-#define AARCH64_RET_NEED_COPY (1 << 6)
-
-#define AARCH64_FLAG_ARG_V_BIT 7
-#define AARCH64_FLAG_ARG_V (1 << AARCH64_FLAG_ARG_V_BIT)
-
-#define N_X_ARG_REG 8
-#define N_V_ARG_REG 8
-#define CALL_CONTEXT_SIZE (N_V_ARG_REG * 16 + N_X_ARG_REG * 8)
+/*
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+``Software''), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+
+#define AARCH64_RET_VOID 0
+#define AARCH64_RET_INT64 1
+#define AARCH64_RET_INT128 2
+
+#define AARCH64_RET_UNUSED3 3
+#define AARCH64_RET_UNUSED4 4
+#define AARCH64_RET_UNUSED5 5
+#define AARCH64_RET_UNUSED6 6
+#define AARCH64_RET_UNUSED7 7
+
+/* Note that FFI_TYPE_FLOAT == 2, _DOUBLE == 3, _LONGDOUBLE == 4,
+ so _S4 through _Q1 are layed out as (TYPE * 4) + (4 - COUNT). */
+#define AARCH64_RET_S4 8
+#define AARCH64_RET_S3 9
+#define AARCH64_RET_S2 10
+#define AARCH64_RET_S1 11
+
+#define AARCH64_RET_D4 12
+#define AARCH64_RET_D3 13
+#define AARCH64_RET_D2 14
+#define AARCH64_RET_D1 15
+
+#define AARCH64_RET_Q4 16
+#define AARCH64_RET_Q3 17
+#define AARCH64_RET_Q2 18
+#define AARCH64_RET_Q1 19
+
+/* Note that each of the sub-64-bit integers gets two entries. */
+#define AARCH64_RET_UINT8 20
+#define AARCH64_RET_UINT16 22
+#define AARCH64_RET_UINT32 24
+
+#define AARCH64_RET_SINT8 26
+#define AARCH64_RET_SINT16 28
+#define AARCH64_RET_SINT32 30
+
+#define AARCH64_RET_MASK 31
+
+#define AARCH64_RET_IN_MEM (1 << 5)
+#define AARCH64_RET_NEED_COPY (1 << 6)
+
+#define AARCH64_FLAG_ARG_V_BIT 7
+#define AARCH64_FLAG_ARG_V (1 << AARCH64_FLAG_ARG_V_BIT)
+
+#define N_X_ARG_REG 8
+#define N_V_ARG_REG 8
+#define CALL_CONTEXT_SIZE (N_V_ARG_REG * 16 + N_X_ARG_REG * 8)
diff --git a/contrib/restricted/libffi/src/aarch64/sysv.S b/contrib/restricted/libffi/src/aarch64/sysv.S
index 4d8d85139a..6761ee1ea9 100644
--- a/contrib/restricted/libffi/src/aarch64/sysv.S
+++ b/contrib/restricted/libffi/src/aarch64/sysv.S
@@ -1,440 +1,440 @@
-/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-``Software''), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-
-#if defined(__aarch64__) || defined(__arm64__)
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
-#include <ffi_cfi.h>
-#include "internal.h"
-
-#ifdef HAVE_MACHINE_ASM_H
-#include <machine/asm.h>
-#else
-#ifdef __USER_LABEL_PREFIX__
-#define CONCAT1(a, b) CONCAT2(a, b)
-#define CONCAT2(a, b) a ## b
-
-/* Use the right prefix for global labels. */
-#define CNAME(x) CONCAT1 (__USER_LABEL_PREFIX__, x)
-#else
-#define CNAME(x) x
-#endif
-#endif
-
-#ifdef __AARCH64EB__
-# define BE(X) X
-#else
-# define BE(X) 0
-#endif
-
-#ifdef __ILP32__
-#define PTR_REG(n) w##n
-#else
-#define PTR_REG(n) x##n
-#endif
-
-#ifdef __ILP32__
-#define PTR_SIZE 4
-#else
-#define PTR_SIZE 8
-#endif
-
- .text
- .align 4
-
-/* ffi_call_SYSV
- extern void ffi_call_SYSV (void *stack, void *frame,
- void (*fn)(void), void *rvalue,
- int flags, void *closure);
-
- Therefore on entry we have:
-
- x0 stack
- x1 frame
- x2 fn
- x3 rvalue
- x4 flags
- x5 closure
-*/
-
- cfi_startproc
-CNAME(ffi_call_SYSV):
- /* Use a stack frame allocated by our caller. */
- cfi_def_cfa(x1, 32);
- stp x29, x30, [x1]
- mov x29, x1
- mov sp, x0
- cfi_def_cfa_register(x29)
- cfi_rel_offset (x29, 0)
- cfi_rel_offset (x30, 8)
-
- mov x9, x2 /* save fn */
- mov x8, x3 /* install structure return */
-#ifdef FFI_GO_CLOSURES
- mov x18, x5 /* install static chain */
-#endif
- stp x3, x4, [x29, #16] /* save rvalue and flags */
-
- /* Load the vector argument passing registers, if necessary. */
- tbz w4, #AARCH64_FLAG_ARG_V_BIT, 1f
- ldp q0, q1, [sp, #0]
- ldp q2, q3, [sp, #32]
- ldp q4, q5, [sp, #64]
- ldp q6, q7, [sp, #96]
-1:
- /* Load the core argument passing registers, including
- the structure return pointer. */
- ldp x0, x1, [sp, #16*N_V_ARG_REG + 0]
- ldp x2, x3, [sp, #16*N_V_ARG_REG + 16]
- ldp x4, x5, [sp, #16*N_V_ARG_REG + 32]
- ldp x6, x7, [sp, #16*N_V_ARG_REG + 48]
-
- /* Deallocate the context, leaving the stacked arguments. */
- add sp, sp, #CALL_CONTEXT_SIZE
-
- blr x9 /* call fn */
-
- ldp x3, x4, [x29, #16] /* reload rvalue and flags */
-
- /* Partially deconstruct the stack frame. */
- mov sp, x29
- cfi_def_cfa_register (sp)
- ldp x29, x30, [x29]
-
- /* Save the return value as directed. */
- adr x5, 0f
- and w4, w4, #AARCH64_RET_MASK
- add x5, x5, x4, lsl #3
- br x5
-
- /* Note that each table entry is 2 insns, and thus 8 bytes.
- For integer data, note that we're storing into ffi_arg
- and therefore we want to extend to 64 bits; these types
- have two consecutive entries allocated for them. */
- .align 4
-0: ret /* VOID */
- nop
-1: str x0, [x3] /* INT64 */
- ret
-2: stp x0, x1, [x3] /* INT128 */
- ret
-3: brk #1000 /* UNUSED */
- ret
-4: brk #1000 /* UNUSED */
- ret
-5: brk #1000 /* UNUSED */
- ret
-6: brk #1000 /* UNUSED */
- ret
-7: brk #1000 /* UNUSED */
- ret
-8: st4 { v0.s, v1.s, v2.s, v3.s }[0], [x3] /* S4 */
- ret
-9: st3 { v0.s, v1.s, v2.s }[0], [x3] /* S3 */
- ret
-10: stp s0, s1, [x3] /* S2 */
- ret
-11: str s0, [x3] /* S1 */
- ret
-12: st4 { v0.d, v1.d, v2.d, v3.d }[0], [x3] /* D4 */
- ret
-13: st3 { v0.d, v1.d, v2.d }[0], [x3] /* D3 */
- ret
-14: stp d0, d1, [x3] /* D2 */
- ret
-15: str d0, [x3] /* D1 */
- ret
-16: str q3, [x3, #48] /* Q4 */
- nop
-17: str q2, [x3, #32] /* Q3 */
- nop
-18: stp q0, q1, [x3] /* Q2 */
- ret
-19: str q0, [x3] /* Q1 */
- ret
-20: uxtb w0, w0 /* UINT8 */
- str x0, [x3]
-21: ret /* reserved */
- nop
-22: uxth w0, w0 /* UINT16 */
- str x0, [x3]
-23: ret /* reserved */
- nop
-24: mov w0, w0 /* UINT32 */
- str x0, [x3]
-25: ret /* reserved */
- nop
-26: sxtb x0, w0 /* SINT8 */
- str x0, [x3]
-27: ret /* reserved */
- nop
-28: sxth x0, w0 /* SINT16 */
- str x0, [x3]
-29: ret /* reserved */
- nop
-30: sxtw x0, w0 /* SINT32 */
- str x0, [x3]
-31: ret /* reserved */
- nop
-
- cfi_endproc
-
- .globl CNAME(ffi_call_SYSV)
- FFI_HIDDEN(CNAME(ffi_call_SYSV))
-#ifdef __ELF__
- .type CNAME(ffi_call_SYSV), #function
- .size CNAME(ffi_call_SYSV), .-CNAME(ffi_call_SYSV)
-#endif
-
-/* ffi_closure_SYSV
-
- Closure invocation glue. This is the low level code invoked directly by
- the closure trampoline to setup and call a closure.
-
- On entry x17 points to a struct ffi_closure, x16 has been clobbered
- all other registers are preserved.
-
- We allocate a call context and save the argument passing registers,
- then invoked the generic C ffi_closure_SYSV_inner() function to do all
- the real work, on return we load the result passing registers back from
- the call context.
-*/
-
-#define ffi_closure_SYSV_FS (8*2 + CALL_CONTEXT_SIZE + 64)
-
- .align 4
-CNAME(ffi_closure_SYSV_V):
- cfi_startproc
- stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
- cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
- cfi_rel_offset (x29, 0)
- cfi_rel_offset (x30, 8)
-
- /* Save the argument passing vector registers. */
- stp q0, q1, [sp, #16 + 0]
- stp q2, q3, [sp, #16 + 32]
- stp q4, q5, [sp, #16 + 64]
- stp q6, q7, [sp, #16 + 96]
- b 0f
- cfi_endproc
-
- .globl CNAME(ffi_closure_SYSV_V)
- FFI_HIDDEN(CNAME(ffi_closure_SYSV_V))
-#ifdef __ELF__
- .type CNAME(ffi_closure_SYSV_V), #function
- .size CNAME(ffi_closure_SYSV_V), . - CNAME(ffi_closure_SYSV_V)
-#endif
-
- .align 4
- cfi_startproc
-CNAME(ffi_closure_SYSV):
- stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
- cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
- cfi_rel_offset (x29, 0)
- cfi_rel_offset (x30, 8)
-0:
- mov x29, sp
-
- /* Save the argument passing core registers. */
- stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0]
- stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16]
- stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32]
- stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48]
-
- /* Load ffi_closure_inner arguments. */
- ldp PTR_REG(0), PTR_REG(1), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET] /* load cif, fn */
- ldr PTR_REG(2), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET+PTR_SIZE*2] /* load user_data */
-.Ldo_closure:
- add x3, sp, #16 /* load context */
- add x4, sp, #ffi_closure_SYSV_FS /* load stack */
- add x5, sp, #16+CALL_CONTEXT_SIZE /* load rvalue */
- mov x6, x8 /* load struct_rval */
- bl CNAME(ffi_closure_SYSV_inner)
-
- /* Load the return value as directed. */
- adr x1, 0f
- and w0, w0, #AARCH64_RET_MASK
- add x1, x1, x0, lsl #3
- add x3, sp, #16+CALL_CONTEXT_SIZE
- br x1
-
- /* Note that each table entry is 2 insns, and thus 8 bytes. */
- .align 4
-0: b 99f /* VOID */
- nop
-1: ldr x0, [x3] /* INT64 */
- b 99f
-2: ldp x0, x1, [x3] /* INT128 */
- b 99f
-3: brk #1000 /* UNUSED */
- nop
-4: brk #1000 /* UNUSED */
- nop
-5: brk #1000 /* UNUSED */
- nop
-6: brk #1000 /* UNUSED */
- nop
-7: brk #1000 /* UNUSED */
- nop
-8: ldr s3, [x3, #12] /* S4 */
- nop
-9: ldr s2, [x3, #8] /* S3 */
- nop
-10: ldp s0, s1, [x3] /* S2 */
- b 99f
-11: ldr s0, [x3] /* S1 */
- b 99f
-12: ldr d3, [x3, #24] /* D4 */
- nop
-13: ldr d2, [x3, #16] /* D3 */
- nop
-14: ldp d0, d1, [x3] /* D2 */
- b 99f
-15: ldr d0, [x3] /* D1 */
- b 99f
-16: ldr q3, [x3, #48] /* Q4 */
- nop
-17: ldr q2, [x3, #32] /* Q3 */
- nop
-18: ldp q0, q1, [x3] /* Q2 */
- b 99f
-19: ldr q0, [x3] /* Q1 */
- b 99f
-20: ldrb w0, [x3, #BE(7)] /* UINT8 */
- b 99f
-21: brk #1000 /* reserved */
- nop
-22: ldrh w0, [x3, #BE(6)] /* UINT16 */
- b 99f
-23: brk #1000 /* reserved */
- nop
-24: ldr w0, [x3, #BE(4)] /* UINT32 */
- b 99f
-25: brk #1000 /* reserved */
- nop
-26: ldrsb x0, [x3, #BE(7)] /* SINT8 */
- b 99f
-27: brk #1000 /* reserved */
- nop
-28: ldrsh x0, [x3, #BE(6)] /* SINT16 */
- b 99f
-29: brk #1000 /* reserved */
- nop
-30: ldrsw x0, [x3, #BE(4)] /* SINT32 */
- nop
-31: /* reserved */
-99: ldp x29, x30, [sp], #ffi_closure_SYSV_FS
- cfi_adjust_cfa_offset (-ffi_closure_SYSV_FS)
- cfi_restore (x29)
- cfi_restore (x30)
- ret
- cfi_endproc
-
- .globl CNAME(ffi_closure_SYSV)
- FFI_HIDDEN(CNAME(ffi_closure_SYSV))
-#ifdef __ELF__
- .type CNAME(ffi_closure_SYSV), #function
- .size CNAME(ffi_closure_SYSV), . - CNAME(ffi_closure_SYSV)
-#endif
-
-#if FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#include <mach/machine/vm_param.h>
- .align PAGE_MAX_SHIFT
-CNAME(ffi_closure_trampoline_table_page):
- .rept PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE
- adr x16, -PAGE_MAX_SIZE
- ldp x17, x16, [x16]
- br x16
- nop /* each entry in the trampoline config page is 2*sizeof(void*) so the trampoline itself cannot be smaller that 16 bytes */
- .endr
-
- .globl CNAME(ffi_closure_trampoline_table_page)
- FFI_HIDDEN(CNAME(ffi_closure_trampoline_table_page))
- #ifdef __ELF__
- .type CNAME(ffi_closure_trampoline_table_page), #function
- .size CNAME(ffi_closure_trampoline_table_page), . - CNAME(ffi_closure_trampoline_table_page)
- #endif
-#endif
-
-#endif /* FFI_EXEC_TRAMPOLINE_TABLE */
-
-#ifdef FFI_GO_CLOSURES
- .align 4
-CNAME(ffi_go_closure_SYSV_V):
- cfi_startproc
- stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
- cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
- cfi_rel_offset (x29, 0)
- cfi_rel_offset (x30, 8)
-
- /* Save the argument passing vector registers. */
- stp q0, q1, [sp, #16 + 0]
- stp q2, q3, [sp, #16 + 32]
- stp q4, q5, [sp, #16 + 64]
- stp q6, q7, [sp, #16 + 96]
- b 0f
- cfi_endproc
-
- .globl CNAME(ffi_go_closure_SYSV_V)
- FFI_HIDDEN(CNAME(ffi_go_closure_SYSV_V))
-#ifdef __ELF__
- .type CNAME(ffi_go_closure_SYSV_V), #function
- .size CNAME(ffi_go_closure_SYSV_V), . - CNAME(ffi_go_closure_SYSV_V)
-#endif
-
- .align 4
- cfi_startproc
-CNAME(ffi_go_closure_SYSV):
- stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
- cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
- cfi_rel_offset (x29, 0)
- cfi_rel_offset (x30, 8)
-0:
- mov x29, sp
-
- /* Save the argument passing core registers. */
- stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0]
- stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16]
- stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32]
- stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48]
-
- /* Load ffi_closure_inner arguments. */
- ldp PTR_REG(0), PTR_REG(1), [x18, #PTR_SIZE]/* load cif, fn */
- mov x2, x18 /* load user_data */
- b .Ldo_closure
- cfi_endproc
-
- .globl CNAME(ffi_go_closure_SYSV)
- FFI_HIDDEN(CNAME(ffi_go_closure_SYSV))
-#ifdef __ELF__
- .type CNAME(ffi_go_closure_SYSV), #function
- .size CNAME(ffi_go_closure_SYSV), . - CNAME(ffi_go_closure_SYSV)
-#endif
-#endif /* FFI_GO_CLOSURES */
-#endif /* __arm64__ */
-
-#if defined __ELF__ && defined __linux__
- .section .note.GNU-stack,"",%progbits
-#endif
-
+/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+``Software''), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+
+#if defined(__aarch64__) || defined(__arm64__)
+#define LIBFFI_ASM
+#include <fficonfig.h>
+#include <ffi.h>
+#include <ffi_cfi.h>
+#include "internal.h"
+
+#ifdef HAVE_MACHINE_ASM_H
+#include <machine/asm.h>
+#else
+#ifdef __USER_LABEL_PREFIX__
+#define CONCAT1(a, b) CONCAT2(a, b)
+#define CONCAT2(a, b) a ## b
+
+/* Use the right prefix for global labels. */
+#define CNAME(x) CONCAT1 (__USER_LABEL_PREFIX__, x)
+#else
+#define CNAME(x) x
+#endif
+#endif
+
+#ifdef __AARCH64EB__
+# define BE(X) X
+#else
+# define BE(X) 0
+#endif
+
+#ifdef __ILP32__
+#define PTR_REG(n) w##n
+#else
+#define PTR_REG(n) x##n
+#endif
+
+#ifdef __ILP32__
+#define PTR_SIZE 4
+#else
+#define PTR_SIZE 8
+#endif
+
+ .text
+ .align 4
+
+/* ffi_call_SYSV
+ extern void ffi_call_SYSV (void *stack, void *frame,
+ void (*fn)(void), void *rvalue,
+ int flags, void *closure);
+
+ Therefore on entry we have:
+
+ x0 stack
+ x1 frame
+ x2 fn
+ x3 rvalue
+ x4 flags
+ x5 closure
+*/
+
+ cfi_startproc
+CNAME(ffi_call_SYSV):
+ /* Use a stack frame allocated by our caller. */
+ cfi_def_cfa(x1, 32);
+ stp x29, x30, [x1]
+ mov x29, x1
+ mov sp, x0
+ cfi_def_cfa_register(x29)
+ cfi_rel_offset (x29, 0)
+ cfi_rel_offset (x30, 8)
+
+ mov x9, x2 /* save fn */
+ mov x8, x3 /* install structure return */
+#ifdef FFI_GO_CLOSURES
+ mov x18, x5 /* install static chain */
+#endif
+ stp x3, x4, [x29, #16] /* save rvalue and flags */
+
+ /* Load the vector argument passing registers, if necessary. */
+ tbz w4, #AARCH64_FLAG_ARG_V_BIT, 1f
+ ldp q0, q1, [sp, #0]
+ ldp q2, q3, [sp, #32]
+ ldp q4, q5, [sp, #64]
+ ldp q6, q7, [sp, #96]
+1:
+ /* Load the core argument passing registers, including
+ the structure return pointer. */
+ ldp x0, x1, [sp, #16*N_V_ARG_REG + 0]
+ ldp x2, x3, [sp, #16*N_V_ARG_REG + 16]
+ ldp x4, x5, [sp, #16*N_V_ARG_REG + 32]
+ ldp x6, x7, [sp, #16*N_V_ARG_REG + 48]
+
+ /* Deallocate the context, leaving the stacked arguments. */
+ add sp, sp, #CALL_CONTEXT_SIZE
+
+ blr x9 /* call fn */
+
+ ldp x3, x4, [x29, #16] /* reload rvalue and flags */
+
+ /* Partially deconstruct the stack frame. */
+ mov sp, x29
+ cfi_def_cfa_register (sp)
+ ldp x29, x30, [x29]
+
+ /* Save the return value as directed. */
+ adr x5, 0f
+ and w4, w4, #AARCH64_RET_MASK
+ add x5, x5, x4, lsl #3
+ br x5
+
+ /* Note that each table entry is 2 insns, and thus 8 bytes.
+ For integer data, note that we're storing into ffi_arg
+ and therefore we want to extend to 64 bits; these types
+ have two consecutive entries allocated for them. */
+ .align 4
+0: ret /* VOID */
+ nop
+1: str x0, [x3] /* INT64 */
+ ret
+2: stp x0, x1, [x3] /* INT128 */
+ ret
+3: brk #1000 /* UNUSED */
+ ret
+4: brk #1000 /* UNUSED */
+ ret
+5: brk #1000 /* UNUSED */
+ ret
+6: brk #1000 /* UNUSED */
+ ret
+7: brk #1000 /* UNUSED */
+ ret
+8: st4 { v0.s, v1.s, v2.s, v3.s }[0], [x3] /* S4 */
+ ret
+9: st3 { v0.s, v1.s, v2.s }[0], [x3] /* S3 */
+ ret
+10: stp s0, s1, [x3] /* S2 */
+ ret
+11: str s0, [x3] /* S1 */
+ ret
+12: st4 { v0.d, v1.d, v2.d, v3.d }[0], [x3] /* D4 */
+ ret
+13: st3 { v0.d, v1.d, v2.d }[0], [x3] /* D3 */
+ ret
+14: stp d0, d1, [x3] /* D2 */
+ ret
+15: str d0, [x3] /* D1 */
+ ret
+16: str q3, [x3, #48] /* Q4 */
+ nop
+17: str q2, [x3, #32] /* Q3 */
+ nop
+18: stp q0, q1, [x3] /* Q2 */
+ ret
+19: str q0, [x3] /* Q1 */
+ ret
+20: uxtb w0, w0 /* UINT8 */
+ str x0, [x3]
+21: ret /* reserved */
+ nop
+22: uxth w0, w0 /* UINT16 */
+ str x0, [x3]
+23: ret /* reserved */
+ nop
+24: mov w0, w0 /* UINT32 */
+ str x0, [x3]
+25: ret /* reserved */
+ nop
+26: sxtb x0, w0 /* SINT8 */
+ str x0, [x3]
+27: ret /* reserved */
+ nop
+28: sxth x0, w0 /* SINT16 */
+ str x0, [x3]
+29: ret /* reserved */
+ nop
+30: sxtw x0, w0 /* SINT32 */
+ str x0, [x3]
+31: ret /* reserved */
+ nop
+
+ cfi_endproc
+
+ .globl CNAME(ffi_call_SYSV)
+ FFI_HIDDEN(CNAME(ffi_call_SYSV))
+#ifdef __ELF__
+ .type CNAME(ffi_call_SYSV), #function
+ .size CNAME(ffi_call_SYSV), .-CNAME(ffi_call_SYSV)
+#endif
+
+/* ffi_closure_SYSV
+
+ Closure invocation glue. This is the low level code invoked directly by
+ the closure trampoline to setup and call a closure.
+
+ On entry x17 points to a struct ffi_closure, x16 has been clobbered
+ all other registers are preserved.
+
+ We allocate a call context and save the argument passing registers,
+ then invoked the generic C ffi_closure_SYSV_inner() function to do all
+ the real work, on return we load the result passing registers back from
+ the call context.
+*/
+
+#define ffi_closure_SYSV_FS (8*2 + CALL_CONTEXT_SIZE + 64)
+
+ .align 4
+CNAME(ffi_closure_SYSV_V):
+ cfi_startproc
+ stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
+ cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
+ cfi_rel_offset (x29, 0)
+ cfi_rel_offset (x30, 8)
+
+ /* Save the argument passing vector registers. */
+ stp q0, q1, [sp, #16 + 0]
+ stp q2, q3, [sp, #16 + 32]
+ stp q4, q5, [sp, #16 + 64]
+ stp q6, q7, [sp, #16 + 96]
+ b 0f
+ cfi_endproc
+
+ .globl CNAME(ffi_closure_SYSV_V)
+ FFI_HIDDEN(CNAME(ffi_closure_SYSV_V))
+#ifdef __ELF__
+ .type CNAME(ffi_closure_SYSV_V), #function
+ .size CNAME(ffi_closure_SYSV_V), . - CNAME(ffi_closure_SYSV_V)
+#endif
+
+ .align 4
+ cfi_startproc
+CNAME(ffi_closure_SYSV):
+ stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
+ cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
+ cfi_rel_offset (x29, 0)
+ cfi_rel_offset (x30, 8)
+0:
+ mov x29, sp
+
+ /* Save the argument passing core registers. */
+ stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0]
+ stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16]
+ stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32]
+ stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48]
+
+ /* Load ffi_closure_inner arguments. */
+ ldp PTR_REG(0), PTR_REG(1), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET] /* load cif, fn */
+ ldr PTR_REG(2), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET+PTR_SIZE*2] /* load user_data */
+.Ldo_closure:
+ add x3, sp, #16 /* load context */
+ add x4, sp, #ffi_closure_SYSV_FS /* load stack */
+ add x5, sp, #16+CALL_CONTEXT_SIZE /* load rvalue */
+ mov x6, x8 /* load struct_rval */
+ bl CNAME(ffi_closure_SYSV_inner)
+
+ /* Load the return value as directed. */
+ adr x1, 0f
+ and w0, w0, #AARCH64_RET_MASK
+ add x1, x1, x0, lsl #3
+ add x3, sp, #16+CALL_CONTEXT_SIZE
+ br x1
+
+ /* Note that each table entry is 2 insns, and thus 8 bytes. */
+ .align 4
+0: b 99f /* VOID */
+ nop
+1: ldr x0, [x3] /* INT64 */
+ b 99f
+2: ldp x0, x1, [x3] /* INT128 */
+ b 99f
+3: brk #1000 /* UNUSED */
+ nop
+4: brk #1000 /* UNUSED */
+ nop
+5: brk #1000 /* UNUSED */
+ nop
+6: brk #1000 /* UNUSED */
+ nop
+7: brk #1000 /* UNUSED */
+ nop
+8: ldr s3, [x3, #12] /* S4 */
+ nop
+9: ldr s2, [x3, #8] /* S3 */
+ nop
+10: ldp s0, s1, [x3] /* S2 */
+ b 99f
+11: ldr s0, [x3] /* S1 */
+ b 99f
+12: ldr d3, [x3, #24] /* D4 */
+ nop
+13: ldr d2, [x3, #16] /* D3 */
+ nop
+14: ldp d0, d1, [x3] /* D2 */
+ b 99f
+15: ldr d0, [x3] /* D1 */
+ b 99f
+16: ldr q3, [x3, #48] /* Q4 */
+ nop
+17: ldr q2, [x3, #32] /* Q3 */
+ nop
+18: ldp q0, q1, [x3] /* Q2 */
+ b 99f
+19: ldr q0, [x3] /* Q1 */
+ b 99f
+20: ldrb w0, [x3, #BE(7)] /* UINT8 */
+ b 99f
+21: brk #1000 /* reserved */
+ nop
+22: ldrh w0, [x3, #BE(6)] /* UINT16 */
+ b 99f
+23: brk #1000 /* reserved */
+ nop
+24: ldr w0, [x3, #BE(4)] /* UINT32 */
+ b 99f
+25: brk #1000 /* reserved */
+ nop
+26: ldrsb x0, [x3, #BE(7)] /* SINT8 */
+ b 99f
+27: brk #1000 /* reserved */
+ nop
+28: ldrsh x0, [x3, #BE(6)] /* SINT16 */
+ b 99f
+29: brk #1000 /* reserved */
+ nop
+30: ldrsw x0, [x3, #BE(4)] /* SINT32 */
+ nop
+31: /* reserved */
+99: ldp x29, x30, [sp], #ffi_closure_SYSV_FS
+ cfi_adjust_cfa_offset (-ffi_closure_SYSV_FS)
+ cfi_restore (x29)
+ cfi_restore (x30)
+ ret
+ cfi_endproc
+
+ .globl CNAME(ffi_closure_SYSV)
+ FFI_HIDDEN(CNAME(ffi_closure_SYSV))
+#ifdef __ELF__
+ .type CNAME(ffi_closure_SYSV), #function
+ .size CNAME(ffi_closure_SYSV), . - CNAME(ffi_closure_SYSV)
+#endif
+
+#if FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#include <mach/machine/vm_param.h>
+ .align PAGE_MAX_SHIFT
+CNAME(ffi_closure_trampoline_table_page):
+ .rept PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE
+ adr x16, -PAGE_MAX_SIZE
+ ldp x17, x16, [x16]
+ br x16
+ nop /* each entry in the trampoline config page is 2*sizeof(void*) so the trampoline itself cannot be smaller that 16 bytes */
+ .endr
+
+ .globl CNAME(ffi_closure_trampoline_table_page)
+ FFI_HIDDEN(CNAME(ffi_closure_trampoline_table_page))
+ #ifdef __ELF__
+ .type CNAME(ffi_closure_trampoline_table_page), #function
+ .size CNAME(ffi_closure_trampoline_table_page), . - CNAME(ffi_closure_trampoline_table_page)
+ #endif
+#endif
+
+#endif /* FFI_EXEC_TRAMPOLINE_TABLE */
+
+#ifdef FFI_GO_CLOSURES
+ .align 4
+CNAME(ffi_go_closure_SYSV_V):
+ cfi_startproc
+ stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
+ cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
+ cfi_rel_offset (x29, 0)
+ cfi_rel_offset (x30, 8)
+
+ /* Save the argument passing vector registers. */
+ stp q0, q1, [sp, #16 + 0]
+ stp q2, q3, [sp, #16 + 32]
+ stp q4, q5, [sp, #16 + 64]
+ stp q6, q7, [sp, #16 + 96]
+ b 0f
+ cfi_endproc
+
+ .globl CNAME(ffi_go_closure_SYSV_V)
+ FFI_HIDDEN(CNAME(ffi_go_closure_SYSV_V))
+#ifdef __ELF__
+ .type CNAME(ffi_go_closure_SYSV_V), #function
+ .size CNAME(ffi_go_closure_SYSV_V), . - CNAME(ffi_go_closure_SYSV_V)
+#endif
+
+ .align 4
+ cfi_startproc
+CNAME(ffi_go_closure_SYSV):
+ stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
+ cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
+ cfi_rel_offset (x29, 0)
+ cfi_rel_offset (x30, 8)
+0:
+ mov x29, sp
+
+ /* Save the argument passing core registers. */
+ stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0]
+ stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16]
+ stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32]
+ stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48]
+
+ /* Load ffi_closure_inner arguments. */
+ ldp PTR_REG(0), PTR_REG(1), [x18, #PTR_SIZE]/* load cif, fn */
+ mov x2, x18 /* load user_data */
+ b .Ldo_closure
+ cfi_endproc
+
+ .globl CNAME(ffi_go_closure_SYSV)
+ FFI_HIDDEN(CNAME(ffi_go_closure_SYSV))
+#ifdef __ELF__
+ .type CNAME(ffi_go_closure_SYSV), #function
+ .size CNAME(ffi_go_closure_SYSV), . - CNAME(ffi_go_closure_SYSV)
+#endif
+#endif /* FFI_GO_CLOSURES */
+#endif /* __arm64__ */
+
+#if defined __ELF__ && defined __linux__
+ .section .note.GNU-stack,"",%progbits
+#endif
+
diff --git a/contrib/restricted/libffi/src/aarch64/win64_armasm.S b/contrib/restricted/libffi/src/aarch64/win64_armasm.S
index 90b95def5c..a79f8a8aa9 100644
--- a/contrib/restricted/libffi/src/aarch64/win64_armasm.S
+++ b/contrib/restricted/libffi/src/aarch64/win64_armasm.S
@@ -1,506 +1,506 @@
-/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-``Software''), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
-#include <ffi_cfi.h>
-#include "internal.h"
-
- OPT 2 /*disable listing */
-/* For some macros to add unwind information */
-#include "ksarm64.h"
- OPT 1 /*re-enable listing */
-
-#define BE(X) 0
-#define PTR_REG(n) x##n
-#define PTR_SIZE 8
-
- IMPORT ffi_closure_SYSV_inner
- EXPORT ffi_call_SYSV
- EXPORT ffi_closure_SYSV_V
- EXPORT ffi_closure_SYSV
- EXPORT extend_hfa_type
- EXPORT compress_hfa_type
-#ifdef FFI_GO_CLOSURES
- EXPORT ffi_go_closure_SYSV_V
- EXPORT ffi_go_closure_SYSV
-#endif
-
- TEXTAREA, ALLIGN=8
-
-/* ffi_call_SYSV
- extern void ffi_call_SYSV (void *stack, void *frame,
- void (*fn)(void), void *rvalue,
- int flags, void *closure);
- Therefore on entry we have:
- x0 stack
- x1 frame
- x2 fn
- x3 rvalue
- x4 flags
- x5 closure
-*/
-
- NESTED_ENTRY ffi_call_SYSV_fake
-
- /* For unwind information, Windows has to store fp and lr */
- PROLOG_SAVE_REG_PAIR x29, x30, #-32!
-
- ALTERNATE_ENTRY ffi_call_SYSV
- /* Use a stack frame allocated by our caller. */
- stp x29, x30, [x1]
- mov x29, x1
- mov sp, x0
-
- mov x9, x2 /* save fn */
- mov x8, x3 /* install structure return */
-#ifdef FFI_GO_CLOSURES
- /*mov x18, x5 install static chain */
-#endif
- stp x3, x4, [x29, #16] /* save rvalue and flags */
-
- /* Load the vector argument passing registers, if necessary. */
- tbz x4, #AARCH64_FLAG_ARG_V_BIT, ffi_call_SYSV_L1
- ldp q0, q1, [sp, #0]
- ldp q2, q3, [sp, #32]
- ldp q4, q5, [sp, #64]
- ldp q6, q7, [sp, #96]
-
-ffi_call_SYSV_L1
- /* Load the core argument passing registers, including
- the structure return pointer. */
- ldp x0, x1, [sp, #16*N_V_ARG_REG + 0]
- ldp x2, x3, [sp, #16*N_V_ARG_REG + 16]
- ldp x4, x5, [sp, #16*N_V_ARG_REG + 32]
- ldp x6, x7, [sp, #16*N_V_ARG_REG + 48]
-
- /* Deallocate the context, leaving the stacked arguments. */
- add sp, sp, #CALL_CONTEXT_SIZE
-
- blr x9 /* call fn */
-
- ldp x3, x4, [x29, #16] /* reload rvalue and flags */
-
- /* Partially deconstruct the stack frame. */
- mov sp, x29
- ldp x29, x30, [x29]
-
- /* Save the return value as directed. */
- adr x5, ffi_call_SYSV_return
- and w4, w4, #AARCH64_RET_MASK
- add x5, x5, x4, lsl #3
- br x5
-
- /* Note that each table entry is 2 insns, and thus 8 bytes.
- For integer data, note that we're storing into ffi_arg
- and therefore we want to extend to 64 bits; these types
- have two consecutive entries allocated for them. */
- ALIGN 4
-ffi_call_SYSV_return
- ret /* VOID */
- nop
- str x0, [x3] /* INT64 */
- ret
- stp x0, x1, [x3] /* INT128 */
- ret
- brk #1000 /* UNUSED */
- ret
- brk #1000 /* UNUSED */
- ret
- brk #1000 /* UNUSED */
- ret
- brk #1000 /* UNUSED */
- ret
- brk #1000 /* UNUSED */
- ret
- st4 { v0.s, v1.s, v2.s, v3.s }[0], [x3] /* S4 */
- ret
- st3 { v0.s, v1.s, v2.s }[0], [x3] /* S3 */
- ret
- stp s0, s1, [x3] /* S2 */
- ret
- str s0, [x3] /* S1 */
- ret
- st4 { v0.d, v1.d, v2.d, v3.d }[0], [x3] /* D4 */
- ret
- st3 { v0.d, v1.d, v2.d }[0], [x3] /* D3 */
- ret
- stp d0, d1, [x3] /* D2 */
- ret
- str d0, [x3] /* D1 */
- ret
- str q3, [x3, #48] /* Q4 */
- nop
- str q2, [x3, #32] /* Q3 */
- nop
- stp q0, q1, [x3] /* Q2 */
- ret
- str q0, [x3] /* Q1 */
- ret
- uxtb w0, w0 /* UINT8 */
- str x0, [x3]
- ret /* reserved */
- nop
- uxth w0, w0 /* UINT16 */
- str x0, [x3]
- ret /* reserved */
- nop
- mov w0, w0 /* UINT32 */
- str x0, [x3]
- ret /* reserved */
- nop
- sxtb x0, w0 /* SINT8 */
- str x0, [x3]
- ret /* reserved */
- nop
- sxth x0, w0 /* SINT16 */
- str x0, [x3]
- ret /* reserved */
- nop
- sxtw x0, w0 /* SINT32 */
- str x0, [x3]
- ret /* reserved */
- nop
-
-
- NESTED_END ffi_call_SYSV_fake
-
-
-/* ffi_closure_SYSV
- Closure invocation glue. This is the low level code invoked directly by
- the closure trampoline to setup and call a closure.
- On entry x17 points to a struct ffi_closure, x16 has been clobbered
- all other registers are preserved.
- We allocate a call context and save the argument passing registers,
- then invoked the generic C ffi_closure_SYSV_inner() function to do all
- the real work, on return we load the result passing registers back from
- the call context.
-*/
-
-#define ffi_closure_SYSV_FS (8*2 + CALL_CONTEXT_SIZE + 64)
-
- NESTED_ENTRY ffi_closure_SYSV_V
- PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS!
-
- /* Save the argument passing vector registers. */
- stp q0, q1, [sp, #16 + 0]
- stp q2, q3, [sp, #16 + 32]
- stp q4, q5, [sp, #16 + 64]
- stp q6, q7, [sp, #16 + 96]
-
- b ffi_closure_SYSV_save_argument
- NESTED_END ffi_closure_SYSV_V
-
- NESTED_ENTRY ffi_closure_SYSV
- PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS!
-
-ffi_closure_SYSV_save_argument
- /* Save the argument passing core registers. */
- stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0]
- stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16]
- stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32]
- stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48]
-
- /* Load ffi_closure_inner arguments. */
- ldp PTR_REG(0), PTR_REG(1), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET] /* load cif, fn */
- ldr PTR_REG(2), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET+PTR_SIZE*2] /* load user_data */
-
-do_closure
- add x3, sp, #16 /* load context */
- add x4, sp, #ffi_closure_SYSV_FS /* load stack */
- add x5, sp, #16+CALL_CONTEXT_SIZE /* load rvalue */
- mov x6, x8 /* load struct_rval */
-
- bl ffi_closure_SYSV_inner
-
- /* Load the return value as directed. */
- adr x1, ffi_closure_SYSV_return_base
- and w0, w0, #AARCH64_RET_MASK
- add x1, x1, x0, lsl #3
- add x3, sp, #16+CALL_CONTEXT_SIZE
- br x1
-
- /* Note that each table entry is 2 insns, and thus 8 bytes. */
- ALIGN 8
-ffi_closure_SYSV_return_base
- b ffi_closure_SYSV_epilog /* VOID */
- nop
- ldr x0, [x3] /* INT64 */
- b ffi_closure_SYSV_epilog
- ldp x0, x1, [x3] /* INT128 */
- b ffi_closure_SYSV_epilog
- brk #1000 /* UNUSED */
- nop
- brk #1000 /* UNUSED */
- nop
- brk #1000 /* UNUSED */
- nop
- brk #1000 /* UNUSED */
- nop
- brk #1000 /* UNUSED */
- nop
- ldr s3, [x3, #12] /* S4 */
- nop
- ldr s2, [x3, #8] /* S3 */
- nop
- ldp s0, s1, [x3] /* S2 */
- b ffi_closure_SYSV_epilog
- ldr s0, [x3] /* S1 */
- b ffi_closure_SYSV_epilog
- ldr d3, [x3, #24] /* D4 */
- nop
- ldr d2, [x3, #16] /* D3 */
- nop
- ldp d0, d1, [x3] /* D2 */
- b ffi_closure_SYSV_epilog
- ldr d0, [x3] /* D1 */
- b ffi_closure_SYSV_epilog
- ldr q3, [x3, #48] /* Q4 */
- nop
- ldr q2, [x3, #32] /* Q3 */
- nop
- ldp q0, q1, [x3] /* Q2 */
- b ffi_closure_SYSV_epilog
- ldr q0, [x3] /* Q1 */
- b ffi_closure_SYSV_epilog
- ldrb w0, [x3, #BE(7)] /* UINT8 */
- b ffi_closure_SYSV_epilog
- brk #1000 /* reserved */
- nop
- ldrh w0, [x3, #BE(6)] /* UINT16 */
- b ffi_closure_SYSV_epilog
- brk #1000 /* reserved */
- nop
- ldr w0, [x3, #BE(4)] /* UINT32 */
- b ffi_closure_SYSV_epilog
- brk #1000 /* reserved */
- nop
- ldrsb x0, [x3, #BE(7)] /* SINT8 */
- b ffi_closure_SYSV_epilog
- brk #1000 /* reserved */
- nop
- ldrsh x0, [x3, #BE(6)] /* SINT16 */
- b ffi_closure_SYSV_epilog
- brk #1000 /* reserved */
- nop
- ldrsw x0, [x3, #BE(4)] /* SINT32 */
- nop
- /* reserved */
-
-ffi_closure_SYSV_epilog
- EPILOG_RESTORE_REG_PAIR x29, x30, #ffi_closure_SYSV_FS!
- EPILOG_RETURN
- NESTED_END ffi_closure_SYSV
-
-
-#ifdef FFI_GO_CLOSURES
- NESTED_ENTRY ffi_go_closure_SYSV_V
- PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS!
-
- /* Save the argument passing vector registers. */
- stp q0, q1, [sp, #16 + 0]
- stp q2, q3, [sp, #16 + 32]
- stp q4, q5, [sp, #16 + 64]
- stp q6, q7, [sp, #16 + 96]
- b ffi_go_closure_SYSV_save_argument
- NESTED_END ffi_go_closure_SYSV_V
-
- NESTED_ENTRY ffi_go_closure_SYSV
- PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS!
-
-ffi_go_closure_SYSV_save_argument
- /* Save the argument passing core registers. */
- stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0]
- stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16]
- stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32]
- stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48]
-
- /* Load ffi_closure_inner arguments. */
- ldp PTR_REG(0), PTR_REG(1), [x18, #PTR_SIZE]/* load cif, fn */
- mov x2, x18 /* load user_data */
- b do_closure
- NESTED_END ffi_go_closure_SYSV
-
-#endif /* FFI_GO_CLOSURES */
-
-
-/* void extend_hfa_type (void *dest, void *src, int h) */
-
- LEAF_ENTRY extend_hfa_type
-
- adr x3, extend_hfa_type_jump_base
- and w2, w2, #AARCH64_RET_MASK
- sub x2, x2, #AARCH64_RET_S4
- add x3, x3, x2, lsl #4
- br x3
-
- ALIGN 4
-extend_hfa_type_jump_base
- ldp s16, s17, [x1] /* S4 */
- ldp s18, s19, [x1, #8]
- b extend_hfa_type_store_4
- nop
-
- ldp s16, s17, [x1] /* S3 */
- ldr s18, [x1, #8]
- b extend_hfa_type_store_3
- nop
-
- ldp s16, s17, [x1] /* S2 */
- b extend_hfa_type_store_2
- nop
- nop
-
- ldr s16, [x1] /* S1 */
- b extend_hfa_type_store_1
- nop
- nop
-
- ldp d16, d17, [x1] /* D4 */
- ldp d18, d19, [x1, #16]
- b extend_hfa_type_store_4
- nop
-
- ldp d16, d17, [x1] /* D3 */
- ldr d18, [x1, #16]
- b extend_hfa_type_store_3
- nop
-
- ldp d16, d17, [x1] /* D2 */
- b extend_hfa_type_store_2
- nop
- nop
-
- ldr d16, [x1] /* D1 */
- b extend_hfa_type_store_1
- nop
- nop
-
- ldp q16, q17, [x1] /* Q4 */
- ldp q18, q19, [x1, #16]
- b extend_hfa_type_store_4
- nop
-
- ldp q16, q17, [x1] /* Q3 */
- ldr q18, [x1, #16]
- b extend_hfa_type_store_3
- nop
-
- ldp q16, q17, [x1] /* Q2 */
- b extend_hfa_type_store_2
- nop
- nop
-
- ldr q16, [x1] /* Q1 */
- b extend_hfa_type_store_1
-
-extend_hfa_type_store_4
- str q19, [x0, #48]
-extend_hfa_type_store_3
- str q18, [x0, #32]
-extend_hfa_type_store_2
- str q17, [x0, #16]
-extend_hfa_type_store_1
- str q16, [x0]
- ret
-
- LEAF_END extend_hfa_type
-
-
-/* void compress_hfa_type (void *dest, void *reg, int h) */
-
- LEAF_ENTRY compress_hfa_type
-
- adr x3, compress_hfa_type_jump_base
- and w2, w2, #AARCH64_RET_MASK
- sub x2, x2, #AARCH64_RET_S4
- add x3, x3, x2, lsl #4
- br x3
-
- ALIGN 4
-compress_hfa_type_jump_base
- ldp q16, q17, [x1] /* S4 */
- ldp q18, q19, [x1, #32]
- st4 { v16.s, v17.s, v18.s, v19.s }[0], [x0]
- ret
-
- ldp q16, q17, [x1] /* S3 */
- ldr q18, [x1, #32]
- st3 { v16.s, v17.s, v18.s }[0], [x0]
- ret
-
- ldp q16, q17, [x1] /* S2 */
- st2 { v16.s, v17.s }[0], [x0]
- ret
- nop
-
- ldr q16, [x1] /* S1 */
- st1 { v16.s }[0], [x0]
- ret
- nop
-
- ldp q16, q17, [x1] /* D4 */
- ldp q18, q19, [x1, #32]
- st4 { v16.d, v17.d, v18.d, v19.d }[0], [x0]
- ret
-
- ldp q16, q17, [x1] /* D3 */
- ldr q18, [x1, #32]
- st3 { v16.d, v17.d, v18.d }[0], [x0]
- ret
-
- ldp q16, q17, [x1] /* D2 */
- st2 { v16.d, v17.d }[0], [x0]
- ret
- nop
-
- ldr q16, [x1] /* D1 */
- st1 { v16.d }[0], [x0]
- ret
- nop
-
- ldp q16, q17, [x1] /* Q4 */
- ldp q18, q19, [x1, #32]
- b compress_hfa_type_store_q4
- nop
-
- ldp q16, q17, [x1] /* Q3 */
- ldr q18, [x1, #32]
- b compress_hfa_type_store_q3
- nop
-
- ldp q16, q17, [x1] /* Q2 */
- stp q16, q17, [x0]
- ret
- nop
-
- ldr q16, [x1] /* Q1 */
- str q16, [x0]
- ret
-
-compress_hfa_type_store_q4
- str q19, [x0, #48]
-compress_hfa_type_store_q3
- str q18, [x0, #32]
- stp q16, q17, [x0]
- ret
-
- LEAF_END compress_hfa_type
-
- END \ No newline at end of file
+/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+``Software''), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+
+#define LIBFFI_ASM
+#include <fficonfig.h>
+#include <ffi.h>
+#include <ffi_cfi.h>
+#include "internal.h"
+
+ OPT 2 /*disable listing */
+/* For some macros to add unwind information */
+#include "ksarm64.h"
+ OPT 1 /*re-enable listing */
+
+#define BE(X) 0
+#define PTR_REG(n) x##n
+#define PTR_SIZE 8
+
+ IMPORT ffi_closure_SYSV_inner
+ EXPORT ffi_call_SYSV
+ EXPORT ffi_closure_SYSV_V
+ EXPORT ffi_closure_SYSV
+ EXPORT extend_hfa_type
+ EXPORT compress_hfa_type
+#ifdef FFI_GO_CLOSURES
+ EXPORT ffi_go_closure_SYSV_V
+ EXPORT ffi_go_closure_SYSV
+#endif
+
+ TEXTAREA, ALLIGN=8
+
+/* ffi_call_SYSV
+ extern void ffi_call_SYSV (void *stack, void *frame,
+ void (*fn)(void), void *rvalue,
+ int flags, void *closure);
+ Therefore on entry we have:
+ x0 stack
+ x1 frame
+ x2 fn
+ x3 rvalue
+ x4 flags
+ x5 closure
+*/
+
+ NESTED_ENTRY ffi_call_SYSV_fake
+
+ /* For unwind information, Windows has to store fp and lr */
+ PROLOG_SAVE_REG_PAIR x29, x30, #-32!
+
+ ALTERNATE_ENTRY ffi_call_SYSV
+ /* Use a stack frame allocated by our caller. */
+ stp x29, x30, [x1]
+ mov x29, x1
+ mov sp, x0
+
+ mov x9, x2 /* save fn */
+ mov x8, x3 /* install structure return */
+#ifdef FFI_GO_CLOSURES
+ /*mov x18, x5 install static chain */
+#endif
+ stp x3, x4, [x29, #16] /* save rvalue and flags */
+
+ /* Load the vector argument passing registers, if necessary. */
+ tbz x4, #AARCH64_FLAG_ARG_V_BIT, ffi_call_SYSV_L1
+ ldp q0, q1, [sp, #0]
+ ldp q2, q3, [sp, #32]
+ ldp q4, q5, [sp, #64]
+ ldp q6, q7, [sp, #96]
+
+ffi_call_SYSV_L1
+ /* Load the core argument passing registers, including
+ the structure return pointer. */
+ ldp x0, x1, [sp, #16*N_V_ARG_REG + 0]
+ ldp x2, x3, [sp, #16*N_V_ARG_REG + 16]
+ ldp x4, x5, [sp, #16*N_V_ARG_REG + 32]
+ ldp x6, x7, [sp, #16*N_V_ARG_REG + 48]
+
+ /* Deallocate the context, leaving the stacked arguments. */
+ add sp, sp, #CALL_CONTEXT_SIZE
+
+ blr x9 /* call fn */
+
+ ldp x3, x4, [x29, #16] /* reload rvalue and flags */
+
+ /* Partially deconstruct the stack frame. */
+ mov sp, x29
+ ldp x29, x30, [x29]
+
+ /* Save the return value as directed. */
+ adr x5, ffi_call_SYSV_return
+ and w4, w4, #AARCH64_RET_MASK
+ add x5, x5, x4, lsl #3
+ br x5
+
+ /* Note that each table entry is 2 insns, and thus 8 bytes.
+ For integer data, note that we're storing into ffi_arg
+ and therefore we want to extend to 64 bits; these types
+ have two consecutive entries allocated for them. */
+ ALIGN 4
+ffi_call_SYSV_return
+ ret /* VOID */
+ nop
+ str x0, [x3] /* INT64 */
+ ret
+ stp x0, x1, [x3] /* INT128 */
+ ret
+ brk #1000 /* UNUSED */
+ ret
+ brk #1000 /* UNUSED */
+ ret
+ brk #1000 /* UNUSED */
+ ret
+ brk #1000 /* UNUSED */
+ ret
+ brk #1000 /* UNUSED */
+ ret
+ st4 { v0.s, v1.s, v2.s, v3.s }[0], [x3] /* S4 */
+ ret
+ st3 { v0.s, v1.s, v2.s }[0], [x3] /* S3 */
+ ret
+ stp s0, s1, [x3] /* S2 */
+ ret
+ str s0, [x3] /* S1 */
+ ret
+ st4 { v0.d, v1.d, v2.d, v3.d }[0], [x3] /* D4 */
+ ret
+ st3 { v0.d, v1.d, v2.d }[0], [x3] /* D3 */
+ ret
+ stp d0, d1, [x3] /* D2 */
+ ret
+ str d0, [x3] /* D1 */
+ ret
+ str q3, [x3, #48] /* Q4 */
+ nop
+ str q2, [x3, #32] /* Q3 */
+ nop
+ stp q0, q1, [x3] /* Q2 */
+ ret
+ str q0, [x3] /* Q1 */
+ ret
+ uxtb w0, w0 /* UINT8 */
+ str x0, [x3]
+ ret /* reserved */
+ nop
+ uxth w0, w0 /* UINT16 */
+ str x0, [x3]
+ ret /* reserved */
+ nop
+ mov w0, w0 /* UINT32 */
+ str x0, [x3]
+ ret /* reserved */
+ nop
+ sxtb x0, w0 /* SINT8 */
+ str x0, [x3]
+ ret /* reserved */
+ nop
+ sxth x0, w0 /* SINT16 */
+ str x0, [x3]
+ ret /* reserved */
+ nop
+ sxtw x0, w0 /* SINT32 */
+ str x0, [x3]
+ ret /* reserved */
+ nop
+
+
+ NESTED_END ffi_call_SYSV_fake
+
+
+/* ffi_closure_SYSV
+ Closure invocation glue. This is the low level code invoked directly by
+ the closure trampoline to setup and call a closure.
+ On entry x17 points to a struct ffi_closure, x16 has been clobbered
+ all other registers are preserved.
+ We allocate a call context and save the argument passing registers,
+ then invoked the generic C ffi_closure_SYSV_inner() function to do all
+ the real work, on return we load the result passing registers back from
+ the call context.
+*/
+
+#define ffi_closure_SYSV_FS (8*2 + CALL_CONTEXT_SIZE + 64)
+
+ NESTED_ENTRY ffi_closure_SYSV_V
+ PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS!
+
+ /* Save the argument passing vector registers. */
+ stp q0, q1, [sp, #16 + 0]
+ stp q2, q3, [sp, #16 + 32]
+ stp q4, q5, [sp, #16 + 64]
+ stp q6, q7, [sp, #16 + 96]
+
+ b ffi_closure_SYSV_save_argument
+ NESTED_END ffi_closure_SYSV_V
+
+ NESTED_ENTRY ffi_closure_SYSV
+ PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS!
+
+ffi_closure_SYSV_save_argument
+ /* Save the argument passing core registers. */
+ stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0]
+ stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16]
+ stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32]
+ stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48]
+
+ /* Load ffi_closure_inner arguments. */
+ ldp PTR_REG(0), PTR_REG(1), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET] /* load cif, fn */
+ ldr PTR_REG(2), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET+PTR_SIZE*2] /* load user_data */
+
+do_closure
+ add x3, sp, #16 /* load context */
+ add x4, sp, #ffi_closure_SYSV_FS /* load stack */
+ add x5, sp, #16+CALL_CONTEXT_SIZE /* load rvalue */
+ mov x6, x8 /* load struct_rval */
+
+ bl ffi_closure_SYSV_inner
+
+ /* Load the return value as directed. */
+ adr x1, ffi_closure_SYSV_return_base
+ and w0, w0, #AARCH64_RET_MASK
+ add x1, x1, x0, lsl #3
+ add x3, sp, #16+CALL_CONTEXT_SIZE
+ br x1
+
+ /* Note that each table entry is 2 insns, and thus 8 bytes. */
+ ALIGN 8
+ffi_closure_SYSV_return_base
+ b ffi_closure_SYSV_epilog /* VOID */
+ nop
+ ldr x0, [x3] /* INT64 */
+ b ffi_closure_SYSV_epilog
+ ldp x0, x1, [x3] /* INT128 */
+ b ffi_closure_SYSV_epilog
+ brk #1000 /* UNUSED */
+ nop
+ brk #1000 /* UNUSED */
+ nop
+ brk #1000 /* UNUSED */
+ nop
+ brk #1000 /* UNUSED */
+ nop
+ brk #1000 /* UNUSED */
+ nop
+ ldr s3, [x3, #12] /* S4 */
+ nop
+ ldr s2, [x3, #8] /* S3 */
+ nop
+ ldp s0, s1, [x3] /* S2 */
+ b ffi_closure_SYSV_epilog
+ ldr s0, [x3] /* S1 */
+ b ffi_closure_SYSV_epilog
+ ldr d3, [x3, #24] /* D4 */
+ nop
+ ldr d2, [x3, #16] /* D3 */
+ nop
+ ldp d0, d1, [x3] /* D2 */
+ b ffi_closure_SYSV_epilog
+ ldr d0, [x3] /* D1 */
+ b ffi_closure_SYSV_epilog
+ ldr q3, [x3, #48] /* Q4 */
+ nop
+ ldr q2, [x3, #32] /* Q3 */
+ nop
+ ldp q0, q1, [x3] /* Q2 */
+ b ffi_closure_SYSV_epilog
+ ldr q0, [x3] /* Q1 */
+ b ffi_closure_SYSV_epilog
+ ldrb w0, [x3, #BE(7)] /* UINT8 */
+ b ffi_closure_SYSV_epilog
+ brk #1000 /* reserved */
+ nop
+ ldrh w0, [x3, #BE(6)] /* UINT16 */
+ b ffi_closure_SYSV_epilog
+ brk #1000 /* reserved */
+ nop
+ ldr w0, [x3, #BE(4)] /* UINT32 */
+ b ffi_closure_SYSV_epilog
+ brk #1000 /* reserved */
+ nop
+ ldrsb x0, [x3, #BE(7)] /* SINT8 */
+ b ffi_closure_SYSV_epilog
+ brk #1000 /* reserved */
+ nop
+ ldrsh x0, [x3, #BE(6)] /* SINT16 */
+ b ffi_closure_SYSV_epilog
+ brk #1000 /* reserved */
+ nop
+ ldrsw x0, [x3, #BE(4)] /* SINT32 */
+ nop
+ /* reserved */
+
+ffi_closure_SYSV_epilog
+ EPILOG_RESTORE_REG_PAIR x29, x30, #ffi_closure_SYSV_FS!
+ EPILOG_RETURN
+ NESTED_END ffi_closure_SYSV
+
+
+#ifdef FFI_GO_CLOSURES
+ NESTED_ENTRY ffi_go_closure_SYSV_V
+ PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS!
+
+ /* Save the argument passing vector registers. */
+ stp q0, q1, [sp, #16 + 0]
+ stp q2, q3, [sp, #16 + 32]
+ stp q4, q5, [sp, #16 + 64]
+ stp q6, q7, [sp, #16 + 96]
+ b ffi_go_closure_SYSV_save_argument
+ NESTED_END ffi_go_closure_SYSV_V
+
+ NESTED_ENTRY ffi_go_closure_SYSV
+ PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS!
+
+ffi_go_closure_SYSV_save_argument
+ /* Save the argument passing core registers. */
+ stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0]
+ stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16]
+ stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32]
+ stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48]
+
+ /* Load ffi_closure_inner arguments. */
+ ldp PTR_REG(0), PTR_REG(1), [x18, #PTR_SIZE]/* load cif, fn */
+ mov x2, x18 /* load user_data */
+ b do_closure
+ NESTED_END ffi_go_closure_SYSV
+
+#endif /* FFI_GO_CLOSURES */
+
+
+/* void extend_hfa_type (void *dest, void *src, int h) */
+
+ LEAF_ENTRY extend_hfa_type
+
+ adr x3, extend_hfa_type_jump_base
+ and w2, w2, #AARCH64_RET_MASK
+ sub x2, x2, #AARCH64_RET_S4
+ add x3, x3, x2, lsl #4
+ br x3
+
+ ALIGN 4
+extend_hfa_type_jump_base
+ ldp s16, s17, [x1] /* S4 */
+ ldp s18, s19, [x1, #8]
+ b extend_hfa_type_store_4
+ nop
+
+ ldp s16, s17, [x1] /* S3 */
+ ldr s18, [x1, #8]
+ b extend_hfa_type_store_3
+ nop
+
+ ldp s16, s17, [x1] /* S2 */
+ b extend_hfa_type_store_2
+ nop
+ nop
+
+ ldr s16, [x1] /* S1 */
+ b extend_hfa_type_store_1
+ nop
+ nop
+
+ ldp d16, d17, [x1] /* D4 */
+ ldp d18, d19, [x1, #16]
+ b extend_hfa_type_store_4
+ nop
+
+ ldp d16, d17, [x1] /* D3 */
+ ldr d18, [x1, #16]
+ b extend_hfa_type_store_3
+ nop
+
+ ldp d16, d17, [x1] /* D2 */
+ b extend_hfa_type_store_2
+ nop
+ nop
+
+ ldr d16, [x1] /* D1 */
+ b extend_hfa_type_store_1
+ nop
+ nop
+
+ ldp q16, q17, [x1] /* Q4 */
+ ldp q18, q19, [x1, #16]
+ b extend_hfa_type_store_4
+ nop
+
+ ldp q16, q17, [x1] /* Q3 */
+ ldr q18, [x1, #16]
+ b extend_hfa_type_store_3
+ nop
+
+ ldp q16, q17, [x1] /* Q2 */
+ b extend_hfa_type_store_2
+ nop
+ nop
+
+ ldr q16, [x1] /* Q1 */
+ b extend_hfa_type_store_1
+
+extend_hfa_type_store_4
+ str q19, [x0, #48]
+extend_hfa_type_store_3
+ str q18, [x0, #32]
+extend_hfa_type_store_2
+ str q17, [x0, #16]
+extend_hfa_type_store_1
+ str q16, [x0]
+ ret
+
+ LEAF_END extend_hfa_type
+
+
+/* void compress_hfa_type (void *dest, void *reg, int h) */
+
+ LEAF_ENTRY compress_hfa_type
+
+ adr x3, compress_hfa_type_jump_base
+ and w2, w2, #AARCH64_RET_MASK
+ sub x2, x2, #AARCH64_RET_S4
+ add x3, x3, x2, lsl #4
+ br x3
+
+ ALIGN 4
+compress_hfa_type_jump_base
+ ldp q16, q17, [x1] /* S4 */
+ ldp q18, q19, [x1, #32]
+ st4 { v16.s, v17.s, v18.s, v19.s }[0], [x0]
+ ret
+
+ ldp q16, q17, [x1] /* S3 */
+ ldr q18, [x1, #32]
+ st3 { v16.s, v17.s, v18.s }[0], [x0]
+ ret
+
+ ldp q16, q17, [x1] /* S2 */
+ st2 { v16.s, v17.s }[0], [x0]
+ ret
+ nop
+
+ ldr q16, [x1] /* S1 */
+ st1 { v16.s }[0], [x0]
+ ret
+ nop
+
+ ldp q16, q17, [x1] /* D4 */
+ ldp q18, q19, [x1, #32]
+ st4 { v16.d, v17.d, v18.d, v19.d }[0], [x0]
+ ret
+
+ ldp q16, q17, [x1] /* D3 */
+ ldr q18, [x1, #32]
+ st3 { v16.d, v17.d, v18.d }[0], [x0]
+ ret
+
+ ldp q16, q17, [x1] /* D2 */
+ st2 { v16.d, v17.d }[0], [x0]
+ ret
+ nop
+
+ ldr q16, [x1] /* D1 */
+ st1 { v16.d }[0], [x0]
+ ret
+ nop
+
+ ldp q16, q17, [x1] /* Q4 */
+ ldp q18, q19, [x1, #32]
+ b compress_hfa_type_store_q4
+ nop
+
+ ldp q16, q17, [x1] /* Q3 */
+ ldr q18, [x1, #32]
+ b compress_hfa_type_store_q3
+ nop
+
+ ldp q16, q17, [x1] /* Q2 */
+ stp q16, q17, [x0]
+ ret
+ nop
+
+ ldr q16, [x1] /* Q1 */
+ str q16, [x0]
+ ret
+
+compress_hfa_type_store_q4
+ str q19, [x0, #48]
+compress_hfa_type_store_q3
+ str q18, [x0, #32]
+ stp q16, q17, [x0]
+ ret
+
+ LEAF_END compress_hfa_type
+
+ END \ No newline at end of file
diff --git a/contrib/restricted/libffi/src/arm/ffi.c b/contrib/restricted/libffi/src/arm/ffi.c
index 95cebf49ee..4e270718a3 100644
--- a/contrib/restricted/libffi/src/arm/ffi.c
+++ b/contrib/restricted/libffi/src/arm/ffi.c
@@ -1,854 +1,854 @@
-/* -----------------------------------------------------------------------
- ffi.c - Copyright (c) 2011 Timothy Wall
- Copyright (c) 2011 Plausible Labs Cooperative, Inc.
- Copyright (c) 2011 Anthony Green
- Copyright (c) 2011 Free Software Foundation
- Copyright (c) 1998, 2008, 2011 Red Hat, Inc.
-
- ARM Foreign Function Interface
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#if defined(__arm__) || defined(_M_ARM)
-#include <fficonfig.h>
-#include <ffi.h>
-#include <ffi_common.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include "internal.h"
-
-#if defined(_MSC_VER) && defined(_M_ARM)
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#endif
-
-#if FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#include <mach/machine/vm_param.h>
-#endif
-
-#else
-#ifndef _M_ARM
-extern unsigned int ffi_arm_trampoline[2] FFI_HIDDEN;
-#else
-extern unsigned int ffi_arm_trampoline[3] FFI_HIDDEN;
-#endif
-#endif
-
-/* Forward declares. */
-static int vfp_type_p (const ffi_type *);
-static void layout_vfp_args (ffi_cif *);
-
-static void *
-ffi_align (ffi_type *ty, void *p)
-{
- /* Align if necessary */
- size_t alignment;
-#ifdef _WIN32_WCE
- alignment = 4;
-#else
- alignment = ty->alignment;
- if (alignment < 4)
- alignment = 4;
-#endif
- return (void *) FFI_ALIGN (p, alignment);
-}
-
-static size_t
-ffi_put_arg (ffi_type *ty, void *src, void *dst)
-{
- size_t z = ty->size;
-
- switch (ty->type)
- {
- case FFI_TYPE_SINT8:
- *(UINT32 *)dst = *(SINT8 *)src;
- break;
- case FFI_TYPE_UINT8:
- *(UINT32 *)dst = *(UINT8 *)src;
- break;
- case FFI_TYPE_SINT16:
- *(UINT32 *)dst = *(SINT16 *)src;
- break;
- case FFI_TYPE_UINT16:
- *(UINT32 *)dst = *(UINT16 *)src;
- break;
-
- case FFI_TYPE_INT:
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_POINTER:
-#ifndef _MSC_VER
- case FFI_TYPE_FLOAT:
-#endif
- *(UINT32 *)dst = *(UINT32 *)src;
- break;
-
-#ifdef _MSC_VER
- // casting a float* to a UINT32* doesn't work on Windows
- case FFI_TYPE_FLOAT:
- *(uintptr_t *)dst = 0;
- *(float *)dst = *(float *)src;
- break;
-#endif
-
- case FFI_TYPE_SINT64:
- case FFI_TYPE_UINT64:
- case FFI_TYPE_DOUBLE:
- *(UINT64 *)dst = *(UINT64 *)src;
- break;
-
- case FFI_TYPE_STRUCT:
- case FFI_TYPE_COMPLEX:
- memcpy (dst, src, z);
- break;
-
- default:
- abort();
- }
-
- return FFI_ALIGN (z, 4);
-}
-
-/* ffi_prep_args is called once stack space has been allocated
- for the function's arguments.
-
- The vfp_space parameter is the load area for VFP regs, the return
- value is cif->vfp_used (word bitset of VFP regs used for passing
- arguments). These are only used for the VFP hard-float ABI.
-*/
-static void
-ffi_prep_args_SYSV (ffi_cif *cif, int flags, void *rvalue,
- void **avalue, char *argp)
-{
- ffi_type **arg_types = cif->arg_types;
- int i, n;
-
- if (flags == ARM_TYPE_STRUCT)
- {
- *(void **) argp = rvalue;
- argp += 4;
- }
-
- for (i = 0, n = cif->nargs; i < n; i++)
- {
- ffi_type *ty = arg_types[i];
- argp = ffi_align (ty, argp);
- argp += ffi_put_arg (ty, avalue[i], argp);
- }
-}
-
-static void
-ffi_prep_args_VFP (ffi_cif *cif, int flags, void *rvalue,
- void **avalue, char *stack, char *vfp_space)
-{
- ffi_type **arg_types = cif->arg_types;
- int i, n, vi = 0;
- char *argp, *regp, *eo_regp;
- char stack_used = 0;
- char done_with_regs = 0;
-
- /* The first 4 words on the stack are used for values
- passed in core registers. */
- regp = stack;
- eo_regp = argp = regp + 16;
-
- /* If the function returns an FFI_TYPE_STRUCT in memory,
- that address is passed in r0 to the function. */
- if (flags == ARM_TYPE_STRUCT)
- {
- *(void **) regp = rvalue;
- regp += 4;
- }
-
- for (i = 0, n = cif->nargs; i < n; i++)
- {
- ffi_type *ty = arg_types[i];
- void *a = avalue[i];
- int is_vfp_type = vfp_type_p (ty);
-
- /* Allocated in VFP registers. */
- if (vi < cif->vfp_nargs && is_vfp_type)
- {
- char *vfp_slot = vfp_space + cif->vfp_args[vi++] * 4;
- ffi_put_arg (ty, a, vfp_slot);
- continue;
- }
- /* Try allocating in core registers. */
- else if (!done_with_regs && !is_vfp_type)
- {
- char *tregp = ffi_align (ty, regp);
- size_t size = ty->size;
- size = (size < 4) ? 4 : size; // pad
- /* Check if there is space left in the aligned register
- area to place the argument. */
- if (tregp + size <= eo_regp)
- {
- regp = tregp + ffi_put_arg (ty, a, tregp);
- done_with_regs = (regp == argp);
- // ensure we did not write into the stack area
- FFI_ASSERT (regp <= argp);
- continue;
- }
- /* In case there are no arguments in the stack area yet,
- the argument is passed in the remaining core registers
- and on the stack. */
- else if (!stack_used)
- {
- stack_used = 1;
- done_with_regs = 1;
- argp = tregp + ffi_put_arg (ty, a, tregp);
- FFI_ASSERT (eo_regp < argp);
- continue;
- }
- }
- /* Base case, arguments are passed on the stack */
- stack_used = 1;
- argp = ffi_align (ty, argp);
- argp += ffi_put_arg (ty, a, argp);
- }
-}
-
-/* Perform machine dependent cif processing */
-ffi_status FFI_HIDDEN
-ffi_prep_cif_machdep (ffi_cif *cif)
-{
- int flags = 0, cabi = cif->abi;
- size_t bytes = cif->bytes;
-
- /* Map out the register placements of VFP register args. The VFP
- hard-float calling conventions are slightly more sophisticated
- than the base calling conventions, so we do it here instead of
- in ffi_prep_args(). */
- if (cabi == FFI_VFP)
- layout_vfp_args (cif);
-
- /* Set the return type flag */
- switch (cif->rtype->type)
- {
- case FFI_TYPE_VOID:
- flags = ARM_TYPE_VOID;
- break;
-
- case FFI_TYPE_INT:
- case FFI_TYPE_UINT8:
- case FFI_TYPE_SINT8:
- case FFI_TYPE_UINT16:
- case FFI_TYPE_SINT16:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_SINT32:
- case FFI_TYPE_POINTER:
- flags = ARM_TYPE_INT;
- break;
-
- case FFI_TYPE_SINT64:
- case FFI_TYPE_UINT64:
- flags = ARM_TYPE_INT64;
- break;
-
- case FFI_TYPE_FLOAT:
- flags = (cabi == FFI_VFP ? ARM_TYPE_VFP_S : ARM_TYPE_INT);
- break;
- case FFI_TYPE_DOUBLE:
- flags = (cabi == FFI_VFP ? ARM_TYPE_VFP_D : ARM_TYPE_INT64);
- break;
-
- case FFI_TYPE_STRUCT:
- case FFI_TYPE_COMPLEX:
- if (cabi == FFI_VFP)
- {
- int h = vfp_type_p (cif->rtype);
-
- flags = ARM_TYPE_VFP_N;
- if (h == 0x100 + FFI_TYPE_FLOAT)
- flags = ARM_TYPE_VFP_S;
- if (h == 0x100 + FFI_TYPE_DOUBLE)
- flags = ARM_TYPE_VFP_D;
- if (h != 0)
- break;
- }
-
- /* A Composite Type not larger than 4 bytes is returned in r0.
- A Composite Type larger than 4 bytes, or whose size cannot
- be determined statically ... is stored in memory at an
- address passed [in r0]. */
- if (cif->rtype->size <= 4)
- flags = ARM_TYPE_INT;
- else
- {
- flags = ARM_TYPE_STRUCT;
- bytes += 4;
- }
- break;
-
- default:
- abort();
- }
-
- /* Round the stack up to a multiple of 8 bytes. This isn't needed
- everywhere, but it is on some platforms, and it doesn't harm anything
- when it isn't needed. */
- bytes = FFI_ALIGN (bytes, 8);
-
- /* Minimum stack space is the 4 register arguments that we pop. */
- if (bytes < 4*4)
- bytes = 4*4;
-
- cif->bytes = bytes;
- cif->flags = flags;
-
- return FFI_OK;
-}
-
-/* Perform machine dependent cif processing for variadic calls */
-ffi_status FFI_HIDDEN
-ffi_prep_cif_machdep_var (ffi_cif * cif,
- unsigned int nfixedargs, unsigned int ntotalargs)
-{
- /* VFP variadic calls actually use the SYSV ABI */
- if (cif->abi == FFI_VFP)
- cif->abi = FFI_SYSV;
-
- return ffi_prep_cif_machdep (cif);
-}
-
-/* Prototypes for assembly functions, in sysv.S. */
-
-struct call_frame
-{
- void *fp;
- void *lr;
- void *rvalue;
- int flags;
- void *closure;
-};
-
-extern void ffi_call_SYSV (void *stack, struct call_frame *,
- void (*fn) (void)) FFI_HIDDEN;
-extern void ffi_call_VFP (void *vfp_space, struct call_frame *,
- void (*fn) (void), unsigned vfp_used) FFI_HIDDEN;
-
-static void
-ffi_call_int (ffi_cif * cif, void (*fn) (void), void *rvalue,
- void **avalue, void *closure)
-{
- int flags = cif->flags;
- ffi_type *rtype = cif->rtype;
- size_t bytes, rsize, vfp_size;
- char *stack, *vfp_space, *new_rvalue;
- struct call_frame *frame;
-
- rsize = 0;
- if (rvalue == NULL)
- {
- /* If the return value is a struct and we don't have a return
- value address then we need to make one. Otherwise the return
- value is in registers and we can ignore them. */
- if (flags == ARM_TYPE_STRUCT)
- rsize = rtype->size;
- else
- flags = ARM_TYPE_VOID;
- }
- else if (flags == ARM_TYPE_VFP_N)
- {
- /* Largest case is double x 4. */
- rsize = 32;
- }
- else if (flags == ARM_TYPE_INT && rtype->type == FFI_TYPE_STRUCT)
- rsize = 4;
-
- /* Largest case. */
- vfp_size = (cif->abi == FFI_VFP && cif->vfp_used ? 8*8: 0);
-
- bytes = cif->bytes;
- stack = alloca (vfp_size + bytes + sizeof(struct call_frame) + rsize);
-
- vfp_space = NULL;
- if (vfp_size)
- {
- vfp_space = stack;
- stack += vfp_size;
- }
-
- frame = (struct call_frame *)(stack + bytes);
-
- new_rvalue = rvalue;
- if (rsize)
- new_rvalue = (void *)(frame + 1);
-
- frame->rvalue = new_rvalue;
- frame->flags = flags;
- frame->closure = closure;
-
- if (vfp_space)
- {
- ffi_prep_args_VFP (cif, flags, new_rvalue, avalue, stack, vfp_space);
- ffi_call_VFP (vfp_space, frame, fn, cif->vfp_used);
- }
- else
- {
- ffi_prep_args_SYSV (cif, flags, new_rvalue, avalue, stack);
- ffi_call_SYSV (stack, frame, fn);
- }
-
- if (rvalue && rvalue != new_rvalue)
- memcpy (rvalue, new_rvalue, rtype->size);
-}
-
-void
-ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue)
-{
- ffi_call_int (cif, fn, rvalue, avalue, NULL);
-}
-
-void
-ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue,
- void **avalue, void *closure)
-{
- ffi_call_int (cif, fn, rvalue, avalue, closure);
-}
-
-static void *
-ffi_prep_incoming_args_SYSV (ffi_cif *cif, void *rvalue,
- char *argp, void **avalue)
-{
- ffi_type **arg_types = cif->arg_types;
- int i, n;
-
- if (cif->flags == ARM_TYPE_STRUCT)
- {
- rvalue = *(void **) argp;
- argp += 4;
- }
- else
- {
- if (cif->rtype->size && cif->rtype->size < 4)
- *(uint32_t *) rvalue = 0;
- }
-
- for (i = 0, n = cif->nargs; i < n; i++)
- {
- ffi_type *ty = arg_types[i];
- size_t z = ty->size;
-
- argp = ffi_align (ty, argp);
- avalue[i] = (void *) argp;
- argp += z;
- }
-
- return rvalue;
-}
-
-static void *
-ffi_prep_incoming_args_VFP (ffi_cif *cif, void *rvalue, char *stack,
- char *vfp_space, void **avalue)
-{
- ffi_type **arg_types = cif->arg_types;
- int i, n, vi = 0;
- char *argp, *regp, *eo_regp;
- char done_with_regs = 0;
- char stack_used = 0;
-
- regp = stack;
- eo_regp = argp = regp + 16;
-
- if (cif->flags == ARM_TYPE_STRUCT)
- {
- rvalue = *(void **) regp;
- regp += 4;
- }
-
- for (i = 0, n = cif->nargs; i < n; i++)
- {
- ffi_type *ty = arg_types[i];
- int is_vfp_type = vfp_type_p (ty);
- size_t z = ty->size;
-
- if (vi < cif->vfp_nargs && is_vfp_type)
- {
- avalue[i] = vfp_space + cif->vfp_args[vi++] * 4;
- continue;
- }
- else if (!done_with_regs && !is_vfp_type)
- {
- char *tregp = ffi_align (ty, regp);
-
- z = (z < 4) ? 4 : z; // pad
-
- /* If the arguments either fits into the registers or uses registers
- and stack, while we haven't read other things from the stack */
- if (tregp + z <= eo_regp || !stack_used)
- {
- /* Because we're little endian, this is what it turns into. */
- avalue[i] = (void *) tregp;
- regp = tregp + z;
-
- /* If we read past the last core register, make sure we
- have not read from the stack before and continue
- reading after regp. */
- if (regp > eo_regp)
- {
- FFI_ASSERT (!stack_used);
- argp = regp;
- }
- if (regp >= eo_regp)
- {
- done_with_regs = 1;
- stack_used = 1;
- }
- continue;
- }
- }
-
- stack_used = 1;
- argp = ffi_align (ty, argp);
- avalue[i] = (void *) argp;
- argp += z;
- }
-
- return rvalue;
-}
-
-struct closure_frame
-{
- char vfp_space[8*8] __attribute__((aligned(8)));
- char result[8*4];
- char argp[];
-};
-
-int FFI_HIDDEN
-ffi_closure_inner_SYSV (ffi_cif *cif,
- void (*fun) (ffi_cif *, void *, void **, void *),
- void *user_data,
- struct closure_frame *frame)
-{
- void **avalue = (void **) alloca (cif->nargs * sizeof (void *));
- void *rvalue = ffi_prep_incoming_args_SYSV (cif, frame->result,
- frame->argp, avalue);
- fun (cif, rvalue, avalue, user_data);
- return cif->flags;
-}
-
-int FFI_HIDDEN
-ffi_closure_inner_VFP (ffi_cif *cif,
- void (*fun) (ffi_cif *, void *, void **, void *),
- void *user_data,
- struct closure_frame *frame)
-{
- void **avalue = (void **) alloca (cif->nargs * sizeof (void *));
- void *rvalue = ffi_prep_incoming_args_VFP (cif, frame->result, frame->argp,
- frame->vfp_space, avalue);
- fun (cif, rvalue, avalue, user_data);
- return cif->flags;
-}
-
-void ffi_closure_SYSV (void) FFI_HIDDEN;
-void ffi_closure_VFP (void) FFI_HIDDEN;
-void ffi_go_closure_SYSV (void) FFI_HIDDEN;
-void ffi_go_closure_VFP (void) FFI_HIDDEN;
-
-/* the cif must already be prep'ed */
-
-ffi_status
-ffi_prep_closure_loc (ffi_closure * closure,
- ffi_cif * cif,
- void (*fun) (ffi_cif *, void *, void **, void *),
- void *user_data, void *codeloc)
-{
- void (*closure_func) (void) = ffi_closure_SYSV;
-
- if (cif->abi == FFI_VFP)
- {
- /* We only need take the vfp path if there are vfp arguments. */
- if (cif->vfp_used)
- closure_func = ffi_closure_VFP;
- }
- else if (cif->abi != FFI_SYSV)
- return FFI_BAD_ABI;
-
-#if FFI_EXEC_TRAMPOLINE_TABLE
- void **config = (void **)((uint8_t *)codeloc - PAGE_MAX_SIZE);
- config[0] = closure;
- config[1] = closure_func;
-#else
-
-#ifndef _M_ARM
- memcpy(closure->tramp, ffi_arm_trampoline, 8);
-#else
- // cast away function type so MSVC doesn't set the lower bit of the function pointer
- memcpy(closure->tramp, (void*)((uintptr_t)ffi_arm_trampoline & 0xFFFFFFFE), FFI_TRAMPOLINE_CLOSURE_OFFSET);
-#endif
-
-#if defined (__QNX__)
- msync(closure->tramp, 8, 0x1000000); /* clear data map */
- msync(codeloc, 8, 0x1000000); /* clear insn map */
-#elif defined(_MSC_VER)
- FlushInstructionCache(GetCurrentProcess(), closure->tramp, FFI_TRAMPOLINE_SIZE);
-#else
- __clear_cache(closure->tramp, closure->tramp + 8); /* clear data map */
- __clear_cache(codeloc, codeloc + 8); /* clear insn map */
-#endif
-#ifdef _M_ARM
- *(void(**)(void))(closure->tramp + FFI_TRAMPOLINE_CLOSURE_FUNCTION) = closure_func;
-#else
- *(void (**)(void))(closure->tramp + 8) = closure_func;
-#endif
-#endif
-
- closure->cif = cif;
- closure->fun = fun;
- closure->user_data = user_data;
-
- return FFI_OK;
-}
-
-ffi_status
-ffi_prep_go_closure (ffi_go_closure *closure, ffi_cif *cif,
- void (*fun) (ffi_cif *, void *, void **, void *))
-{
- void (*closure_func) (void) = ffi_go_closure_SYSV;
-
- if (cif->abi == FFI_VFP)
- {
- /* We only need take the vfp path if there are vfp arguments. */
- if (cif->vfp_used)
- closure_func = ffi_go_closure_VFP;
- }
- else if (cif->abi != FFI_SYSV)
- return FFI_BAD_ABI;
-
- closure->tramp = closure_func;
- closure->cif = cif;
- closure->fun = fun;
-
- return FFI_OK;
-}
-
-/* Below are routines for VFP hard-float support. */
-
-/* A subroutine of vfp_type_p. Given a structure type, return the type code
- of the first non-structure element. Recurse for structure elements.
- Return -1 if the structure is in fact empty, i.e. no nested elements. */
-
-static int
-is_hfa0 (const ffi_type *ty)
-{
- ffi_type **elements = ty->elements;
- int i, ret = -1;
-
- if (elements != NULL)
- for (i = 0; elements[i]; ++i)
- {
- ret = elements[i]->type;
- if (ret == FFI_TYPE_STRUCT || ret == FFI_TYPE_COMPLEX)
- {
- ret = is_hfa0 (elements[i]);
- if (ret < 0)
- continue;
- }
- break;
- }
-
- return ret;
-}
-
-/* A subroutine of vfp_type_p. Given a structure type, return true if all
- of the non-structure elements are the same as CANDIDATE. */
-
-static int
-is_hfa1 (const ffi_type *ty, int candidate)
-{
- ffi_type **elements = ty->elements;
- int i;
-
- if (elements != NULL)
- for (i = 0; elements[i]; ++i)
- {
- int t = elements[i]->type;
- if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
- {
- if (!is_hfa1 (elements[i], candidate))
- return 0;
- }
- else if (t != candidate)
- return 0;
- }
-
- return 1;
-}
-
-/* Determine if TY is an homogenous floating point aggregate (HFA).
- That is, a structure consisting of 1 to 4 members of all the same type,
- where that type is a floating point scalar.
-
- Returns non-zero iff TY is an HFA. The result is an encoded value where
- bits 0-7 contain the type code, and bits 8-10 contain the element count. */
-
-static int
-vfp_type_p (const ffi_type *ty)
-{
- ffi_type **elements;
- int candidate, i;
- size_t size, ele_count;
-
- /* Quickest tests first. */
- candidate = ty->type;
- switch (ty->type)
- {
- default:
- return 0;
- case FFI_TYPE_FLOAT:
- case FFI_TYPE_DOUBLE:
- ele_count = 1;
- goto done;
- case FFI_TYPE_COMPLEX:
- candidate = ty->elements[0]->type;
- if (candidate != FFI_TYPE_FLOAT && candidate != FFI_TYPE_DOUBLE)
- return 0;
- ele_count = 2;
- goto done;
- case FFI_TYPE_STRUCT:
- break;
- }
-
- /* No HFA types are smaller than 4 bytes, or larger than 32 bytes. */
- size = ty->size;
- if (size < 4 || size > 32)
- return 0;
-
- /* Find the type of the first non-structure member. */
- elements = ty->elements;
- candidate = elements[0]->type;
- if (candidate == FFI_TYPE_STRUCT || candidate == FFI_TYPE_COMPLEX)
- {
- for (i = 0; ; ++i)
- {
- candidate = is_hfa0 (elements[i]);
- if (candidate >= 0)
- break;
- }
- }
-
- /* If the first member is not a floating point type, it's not an HFA.
- Also quickly re-check the size of the structure. */
- switch (candidate)
- {
- case FFI_TYPE_FLOAT:
- ele_count = size / sizeof(float);
- if (size != ele_count * sizeof(float))
- return 0;
- break;
- case FFI_TYPE_DOUBLE:
- ele_count = size / sizeof(double);
- if (size != ele_count * sizeof(double))
- return 0;
- break;
- default:
- return 0;
- }
- if (ele_count > 4)
- return 0;
-
- /* Finally, make sure that all scalar elements are the same type. */
- for (i = 0; elements[i]; ++i)
- {
- int t = elements[i]->type;
- if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
- {
- if (!is_hfa1 (elements[i], candidate))
- return 0;
- }
- else if (t != candidate)
- return 0;
- }
-
- /* All tests succeeded. Encode the result. */
- done:
- return (ele_count << 8) | candidate;
-}
-
-static int
-place_vfp_arg (ffi_cif *cif, int h)
-{
- unsigned short reg = cif->vfp_reg_free;
- int align = 1, nregs = h >> 8;
-
- if ((h & 0xff) == FFI_TYPE_DOUBLE)
- align = 2, nregs *= 2;
-
- /* Align register number. */
- if ((reg & 1) && align == 2)
- reg++;
-
- while (reg + nregs <= 16)
- {
- int s, new_used = 0;
- for (s = reg; s < reg + nregs; s++)
- {
- new_used |= (1 << s);
- if (cif->vfp_used & (1 << s))
- {
- reg += align;
- goto next_reg;
- }
- }
- /* Found regs to allocate. */
- cif->vfp_used |= new_used;
- cif->vfp_args[cif->vfp_nargs++] = (signed char)reg;
-
- /* Update vfp_reg_free. */
- if (cif->vfp_used & (1 << cif->vfp_reg_free))
- {
- reg += nregs;
- while (cif->vfp_used & (1 << reg))
- reg += 1;
- cif->vfp_reg_free = reg;
- }
- return 0;
- next_reg:;
- }
- // done, mark all regs as used
- cif->vfp_reg_free = 16;
- cif->vfp_used = 0xFFFF;
- return 1;
-}
-
-static void
-layout_vfp_args (ffi_cif * cif)
-{
- unsigned int i;
- /* Init VFP fields */
- cif->vfp_used = 0;
- cif->vfp_nargs = 0;
- cif->vfp_reg_free = 0;
- memset (cif->vfp_args, -1, 16); /* Init to -1. */
-
- for (i = 0; i < cif->nargs; i++)
- {
- int h = vfp_type_p (cif->arg_types[i]);
- if (h && place_vfp_arg (cif, h) == 1)
- break;
- }
-}
-
-#endif /* __arm__ or _M_ARM */
+/* -----------------------------------------------------------------------
+ ffi.c - Copyright (c) 2011 Timothy Wall
+ Copyright (c) 2011 Plausible Labs Cooperative, Inc.
+ Copyright (c) 2011 Anthony Green
+ Copyright (c) 2011 Free Software Foundation
+ Copyright (c) 1998, 2008, 2011 Red Hat, Inc.
+
+ ARM Foreign Function Interface
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#if defined(__arm__) || defined(_M_ARM)
+#include <fficonfig.h>
+#include <ffi.h>
+#include <ffi_common.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include "internal.h"
+
+#if defined(_MSC_VER) && defined(_M_ARM)
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#endif
+
+#if FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#include <mach/machine/vm_param.h>
+#endif
+
+#else
+#ifndef _M_ARM
+extern unsigned int ffi_arm_trampoline[2] FFI_HIDDEN;
+#else
+extern unsigned int ffi_arm_trampoline[3] FFI_HIDDEN;
+#endif
+#endif
+
+/* Forward declares. */
+static int vfp_type_p (const ffi_type *);
+static void layout_vfp_args (ffi_cif *);
+
+static void *
+ffi_align (ffi_type *ty, void *p)
+{
+ /* Align if necessary */
+ size_t alignment;
+#ifdef _WIN32_WCE
+ alignment = 4;
+#else
+ alignment = ty->alignment;
+ if (alignment < 4)
+ alignment = 4;
+#endif
+ return (void *) FFI_ALIGN (p, alignment);
+}
+
+static size_t
+ffi_put_arg (ffi_type *ty, void *src, void *dst)
+{
+ size_t z = ty->size;
+
+ switch (ty->type)
+ {
+ case FFI_TYPE_SINT8:
+ *(UINT32 *)dst = *(SINT8 *)src;
+ break;
+ case FFI_TYPE_UINT8:
+ *(UINT32 *)dst = *(UINT8 *)src;
+ break;
+ case FFI_TYPE_SINT16:
+ *(UINT32 *)dst = *(SINT16 *)src;
+ break;
+ case FFI_TYPE_UINT16:
+ *(UINT32 *)dst = *(UINT16 *)src;
+ break;
+
+ case FFI_TYPE_INT:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_POINTER:
+#ifndef _MSC_VER
+ case FFI_TYPE_FLOAT:
+#endif
+ *(UINT32 *)dst = *(UINT32 *)src;
+ break;
+
+#ifdef _MSC_VER
+ // casting a float* to a UINT32* doesn't work on Windows
+ case FFI_TYPE_FLOAT:
+ *(uintptr_t *)dst = 0;
+ *(float *)dst = *(float *)src;
+ break;
+#endif
+
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_DOUBLE:
+ *(UINT64 *)dst = *(UINT64 *)src;
+ break;
+
+ case FFI_TYPE_STRUCT:
+ case FFI_TYPE_COMPLEX:
+ memcpy (dst, src, z);
+ break;
+
+ default:
+ abort();
+ }
+
+ return FFI_ALIGN (z, 4);
+}
+
+/* ffi_prep_args is called once stack space has been allocated
+ for the function's arguments.
+
+ The vfp_space parameter is the load area for VFP regs, the return
+ value is cif->vfp_used (word bitset of VFP regs used for passing
+ arguments). These are only used for the VFP hard-float ABI.
+*/
+static void
+ffi_prep_args_SYSV (ffi_cif *cif, int flags, void *rvalue,
+ void **avalue, char *argp)
+{
+ ffi_type **arg_types = cif->arg_types;
+ int i, n;
+
+ if (flags == ARM_TYPE_STRUCT)
+ {
+ *(void **) argp = rvalue;
+ argp += 4;
+ }
+
+ for (i = 0, n = cif->nargs; i < n; i++)
+ {
+ ffi_type *ty = arg_types[i];
+ argp = ffi_align (ty, argp);
+ argp += ffi_put_arg (ty, avalue[i], argp);
+ }
+}
+
+static void
+ffi_prep_args_VFP (ffi_cif *cif, int flags, void *rvalue,
+ void **avalue, char *stack, char *vfp_space)
+{
+ ffi_type **arg_types = cif->arg_types;
+ int i, n, vi = 0;
+ char *argp, *regp, *eo_regp;
+ char stack_used = 0;
+ char done_with_regs = 0;
+
+ /* The first 4 words on the stack are used for values
+ passed in core registers. */
+ regp = stack;
+ eo_regp = argp = regp + 16;
+
+ /* If the function returns an FFI_TYPE_STRUCT in memory,
+ that address is passed in r0 to the function. */
+ if (flags == ARM_TYPE_STRUCT)
+ {
+ *(void **) regp = rvalue;
+ regp += 4;
+ }
+
+ for (i = 0, n = cif->nargs; i < n; i++)
+ {
+ ffi_type *ty = arg_types[i];
+ void *a = avalue[i];
+ int is_vfp_type = vfp_type_p (ty);
+
+ /* Allocated in VFP registers. */
+ if (vi < cif->vfp_nargs && is_vfp_type)
+ {
+ char *vfp_slot = vfp_space + cif->vfp_args[vi++] * 4;
+ ffi_put_arg (ty, a, vfp_slot);
+ continue;
+ }
+ /* Try allocating in core registers. */
+ else if (!done_with_regs && !is_vfp_type)
+ {
+ char *tregp = ffi_align (ty, regp);
+ size_t size = ty->size;
+ size = (size < 4) ? 4 : size; // pad
+ /* Check if there is space left in the aligned register
+ area to place the argument. */
+ if (tregp + size <= eo_regp)
+ {
+ regp = tregp + ffi_put_arg (ty, a, tregp);
+ done_with_regs = (regp == argp);
+ // ensure we did not write into the stack area
+ FFI_ASSERT (regp <= argp);
+ continue;
+ }
+ /* In case there are no arguments in the stack area yet,
+ the argument is passed in the remaining core registers
+ and on the stack. */
+ else if (!stack_used)
+ {
+ stack_used = 1;
+ done_with_regs = 1;
+ argp = tregp + ffi_put_arg (ty, a, tregp);
+ FFI_ASSERT (eo_regp < argp);
+ continue;
+ }
+ }
+ /* Base case, arguments are passed on the stack */
+ stack_used = 1;
+ argp = ffi_align (ty, argp);
+ argp += ffi_put_arg (ty, a, argp);
+ }
+}
+
+/* Perform machine dependent cif processing */
+ffi_status FFI_HIDDEN
+ffi_prep_cif_machdep (ffi_cif *cif)
+{
+ int flags = 0, cabi = cif->abi;
+ size_t bytes = cif->bytes;
+
+ /* Map out the register placements of VFP register args. The VFP
+ hard-float calling conventions are slightly more sophisticated
+ than the base calling conventions, so we do it here instead of
+ in ffi_prep_args(). */
+ if (cabi == FFI_VFP)
+ layout_vfp_args (cif);
+
+ /* Set the return type flag */
+ switch (cif->rtype->type)
+ {
+ case FFI_TYPE_VOID:
+ flags = ARM_TYPE_VOID;
+ break;
+
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_POINTER:
+ flags = ARM_TYPE_INT;
+ break;
+
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_UINT64:
+ flags = ARM_TYPE_INT64;
+ break;
+
+ case FFI_TYPE_FLOAT:
+ flags = (cabi == FFI_VFP ? ARM_TYPE_VFP_S : ARM_TYPE_INT);
+ break;
+ case FFI_TYPE_DOUBLE:
+ flags = (cabi == FFI_VFP ? ARM_TYPE_VFP_D : ARM_TYPE_INT64);
+ break;
+
+ case FFI_TYPE_STRUCT:
+ case FFI_TYPE_COMPLEX:
+ if (cabi == FFI_VFP)
+ {
+ int h = vfp_type_p (cif->rtype);
+
+ flags = ARM_TYPE_VFP_N;
+ if (h == 0x100 + FFI_TYPE_FLOAT)
+ flags = ARM_TYPE_VFP_S;
+ if (h == 0x100 + FFI_TYPE_DOUBLE)
+ flags = ARM_TYPE_VFP_D;
+ if (h != 0)
+ break;
+ }
+
+ /* A Composite Type not larger than 4 bytes is returned in r0.
+ A Composite Type larger than 4 bytes, or whose size cannot
+ be determined statically ... is stored in memory at an
+ address passed [in r0]. */
+ if (cif->rtype->size <= 4)
+ flags = ARM_TYPE_INT;
+ else
+ {
+ flags = ARM_TYPE_STRUCT;
+ bytes += 4;
+ }
+ break;
+
+ default:
+ abort();
+ }
+
+ /* Round the stack up to a multiple of 8 bytes. This isn't needed
+ everywhere, but it is on some platforms, and it doesn't harm anything
+ when it isn't needed. */
+ bytes = FFI_ALIGN (bytes, 8);
+
+ /* Minimum stack space is the 4 register arguments that we pop. */
+ if (bytes < 4*4)
+ bytes = 4*4;
+
+ cif->bytes = bytes;
+ cif->flags = flags;
+
+ return FFI_OK;
+}
+
+/* Perform machine dependent cif processing for variadic calls */
+ffi_status FFI_HIDDEN
+ffi_prep_cif_machdep_var (ffi_cif * cif,
+ unsigned int nfixedargs, unsigned int ntotalargs)
+{
+ /* VFP variadic calls actually use the SYSV ABI */
+ if (cif->abi == FFI_VFP)
+ cif->abi = FFI_SYSV;
+
+ return ffi_prep_cif_machdep (cif);
+}
+
+/* Prototypes for assembly functions, in sysv.S. */
+
+struct call_frame
+{
+ void *fp;
+ void *lr;
+ void *rvalue;
+ int flags;
+ void *closure;
+};
+
+extern void ffi_call_SYSV (void *stack, struct call_frame *,
+ void (*fn) (void)) FFI_HIDDEN;
+extern void ffi_call_VFP (void *vfp_space, struct call_frame *,
+ void (*fn) (void), unsigned vfp_used) FFI_HIDDEN;
+
+static void
+ffi_call_int (ffi_cif * cif, void (*fn) (void), void *rvalue,
+ void **avalue, void *closure)
+{
+ int flags = cif->flags;
+ ffi_type *rtype = cif->rtype;
+ size_t bytes, rsize, vfp_size;
+ char *stack, *vfp_space, *new_rvalue;
+ struct call_frame *frame;
+
+ rsize = 0;
+ if (rvalue == NULL)
+ {
+ /* If the return value is a struct and we don't have a return
+ value address then we need to make one. Otherwise the return
+ value is in registers and we can ignore them. */
+ if (flags == ARM_TYPE_STRUCT)
+ rsize = rtype->size;
+ else
+ flags = ARM_TYPE_VOID;
+ }
+ else if (flags == ARM_TYPE_VFP_N)
+ {
+ /* Largest case is double x 4. */
+ rsize = 32;
+ }
+ else if (flags == ARM_TYPE_INT && rtype->type == FFI_TYPE_STRUCT)
+ rsize = 4;
+
+ /* Largest case. */
+ vfp_size = (cif->abi == FFI_VFP && cif->vfp_used ? 8*8: 0);
+
+ bytes = cif->bytes;
+ stack = alloca (vfp_size + bytes + sizeof(struct call_frame) + rsize);
+
+ vfp_space = NULL;
+ if (vfp_size)
+ {
+ vfp_space = stack;
+ stack += vfp_size;
+ }
+
+ frame = (struct call_frame *)(stack + bytes);
+
+ new_rvalue = rvalue;
+ if (rsize)
+ new_rvalue = (void *)(frame + 1);
+
+ frame->rvalue = new_rvalue;
+ frame->flags = flags;
+ frame->closure = closure;
+
+ if (vfp_space)
+ {
+ ffi_prep_args_VFP (cif, flags, new_rvalue, avalue, stack, vfp_space);
+ ffi_call_VFP (vfp_space, frame, fn, cif->vfp_used);
+ }
+ else
+ {
+ ffi_prep_args_SYSV (cif, flags, new_rvalue, avalue, stack);
+ ffi_call_SYSV (stack, frame, fn);
+ }
+
+ if (rvalue && rvalue != new_rvalue)
+ memcpy (rvalue, new_rvalue, rtype->size);
+}
+
+void
+ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue)
+{
+ ffi_call_int (cif, fn, rvalue, avalue, NULL);
+}
+
+void
+ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue,
+ void **avalue, void *closure)
+{
+ ffi_call_int (cif, fn, rvalue, avalue, closure);
+}
+
+static void *
+ffi_prep_incoming_args_SYSV (ffi_cif *cif, void *rvalue,
+ char *argp, void **avalue)
+{
+ ffi_type **arg_types = cif->arg_types;
+ int i, n;
+
+ if (cif->flags == ARM_TYPE_STRUCT)
+ {
+ rvalue = *(void **) argp;
+ argp += 4;
+ }
+ else
+ {
+ if (cif->rtype->size && cif->rtype->size < 4)
+ *(uint32_t *) rvalue = 0;
+ }
+
+ for (i = 0, n = cif->nargs; i < n; i++)
+ {
+ ffi_type *ty = arg_types[i];
+ size_t z = ty->size;
+
+ argp = ffi_align (ty, argp);
+ avalue[i] = (void *) argp;
+ argp += z;
+ }
+
+ return rvalue;
+}
+
+static void *
+ffi_prep_incoming_args_VFP (ffi_cif *cif, void *rvalue, char *stack,
+ char *vfp_space, void **avalue)
+{
+ ffi_type **arg_types = cif->arg_types;
+ int i, n, vi = 0;
+ char *argp, *regp, *eo_regp;
+ char done_with_regs = 0;
+ char stack_used = 0;
+
+ regp = stack;
+ eo_regp = argp = regp + 16;
+
+ if (cif->flags == ARM_TYPE_STRUCT)
+ {
+ rvalue = *(void **) regp;
+ regp += 4;
+ }
+
+ for (i = 0, n = cif->nargs; i < n; i++)
+ {
+ ffi_type *ty = arg_types[i];
+ int is_vfp_type = vfp_type_p (ty);
+ size_t z = ty->size;
+
+ if (vi < cif->vfp_nargs && is_vfp_type)
+ {
+ avalue[i] = vfp_space + cif->vfp_args[vi++] * 4;
+ continue;
+ }
+ else if (!done_with_regs && !is_vfp_type)
+ {
+ char *tregp = ffi_align (ty, regp);
+
+ z = (z < 4) ? 4 : z; // pad
+
+ /* If the arguments either fits into the registers or uses registers
+ and stack, while we haven't read other things from the stack */
+ if (tregp + z <= eo_regp || !stack_used)
+ {
+ /* Because we're little endian, this is what it turns into. */
+ avalue[i] = (void *) tregp;
+ regp = tregp + z;
+
+ /* If we read past the last core register, make sure we
+ have not read from the stack before and continue
+ reading after regp. */
+ if (regp > eo_regp)
+ {
+ FFI_ASSERT (!stack_used);
+ argp = regp;
+ }
+ if (regp >= eo_regp)
+ {
+ done_with_regs = 1;
+ stack_used = 1;
+ }
+ continue;
+ }
+ }
+
+ stack_used = 1;
+ argp = ffi_align (ty, argp);
+ avalue[i] = (void *) argp;
+ argp += z;
+ }
+
+ return rvalue;
+}
+
+struct closure_frame
+{
+ char vfp_space[8*8] __attribute__((aligned(8)));
+ char result[8*4];
+ char argp[];
+};
+
+int FFI_HIDDEN
+ffi_closure_inner_SYSV (ffi_cif *cif,
+ void (*fun) (ffi_cif *, void *, void **, void *),
+ void *user_data,
+ struct closure_frame *frame)
+{
+ void **avalue = (void **) alloca (cif->nargs * sizeof (void *));
+ void *rvalue = ffi_prep_incoming_args_SYSV (cif, frame->result,
+ frame->argp, avalue);
+ fun (cif, rvalue, avalue, user_data);
+ return cif->flags;
+}
+
+int FFI_HIDDEN
+ffi_closure_inner_VFP (ffi_cif *cif,
+ void (*fun) (ffi_cif *, void *, void **, void *),
+ void *user_data,
+ struct closure_frame *frame)
+{
+ void **avalue = (void **) alloca (cif->nargs * sizeof (void *));
+ void *rvalue = ffi_prep_incoming_args_VFP (cif, frame->result, frame->argp,
+ frame->vfp_space, avalue);
+ fun (cif, rvalue, avalue, user_data);
+ return cif->flags;
+}
+
+void ffi_closure_SYSV (void) FFI_HIDDEN;
+void ffi_closure_VFP (void) FFI_HIDDEN;
+void ffi_go_closure_SYSV (void) FFI_HIDDEN;
+void ffi_go_closure_VFP (void) FFI_HIDDEN;
+
+/* the cif must already be prep'ed */
+
+ffi_status
+ffi_prep_closure_loc (ffi_closure * closure,
+ ffi_cif * cif,
+ void (*fun) (ffi_cif *, void *, void **, void *),
+ void *user_data, void *codeloc)
+{
+ void (*closure_func) (void) = ffi_closure_SYSV;
+
+ if (cif->abi == FFI_VFP)
+ {
+ /* We only need take the vfp path if there are vfp arguments. */
+ if (cif->vfp_used)
+ closure_func = ffi_closure_VFP;
+ }
+ else if (cif->abi != FFI_SYSV)
+ return FFI_BAD_ABI;
+
+#if FFI_EXEC_TRAMPOLINE_TABLE
+ void **config = (void **)((uint8_t *)codeloc - PAGE_MAX_SIZE);
+ config[0] = closure;
+ config[1] = closure_func;
+#else
+
+#ifndef _M_ARM
+ memcpy(closure->tramp, ffi_arm_trampoline, 8);
+#else
+ // cast away function type so MSVC doesn't set the lower bit of the function pointer
+ memcpy(closure->tramp, (void*)((uintptr_t)ffi_arm_trampoline & 0xFFFFFFFE), FFI_TRAMPOLINE_CLOSURE_OFFSET);
+#endif
+
+#if defined (__QNX__)
+ msync(closure->tramp, 8, 0x1000000); /* clear data map */
+ msync(codeloc, 8, 0x1000000); /* clear insn map */
+#elif defined(_MSC_VER)
+ FlushInstructionCache(GetCurrentProcess(), closure->tramp, FFI_TRAMPOLINE_SIZE);
+#else
+ __clear_cache(closure->tramp, closure->tramp + 8); /* clear data map */
+ __clear_cache(codeloc, codeloc + 8); /* clear insn map */
+#endif
+#ifdef _M_ARM
+ *(void(**)(void))(closure->tramp + FFI_TRAMPOLINE_CLOSURE_FUNCTION) = closure_func;
+#else
+ *(void (**)(void))(closure->tramp + 8) = closure_func;
+#endif
+#endif
+
+ closure->cif = cif;
+ closure->fun = fun;
+ closure->user_data = user_data;
+
+ return FFI_OK;
+}
+
+ffi_status
+ffi_prep_go_closure (ffi_go_closure *closure, ffi_cif *cif,
+ void (*fun) (ffi_cif *, void *, void **, void *))
+{
+ void (*closure_func) (void) = ffi_go_closure_SYSV;
+
+ if (cif->abi == FFI_VFP)
+ {
+ /* We only need take the vfp path if there are vfp arguments. */
+ if (cif->vfp_used)
+ closure_func = ffi_go_closure_VFP;
+ }
+ else if (cif->abi != FFI_SYSV)
+ return FFI_BAD_ABI;
+
+ closure->tramp = closure_func;
+ closure->cif = cif;
+ closure->fun = fun;
+
+ return FFI_OK;
+}
+
+/* Below are routines for VFP hard-float support. */
+
+/* A subroutine of vfp_type_p. Given a structure type, return the type code
+ of the first non-structure element. Recurse for structure elements.
+ Return -1 if the structure is in fact empty, i.e. no nested elements. */
+
+static int
+is_hfa0 (const ffi_type *ty)
+{
+ ffi_type **elements = ty->elements;
+ int i, ret = -1;
+
+ if (elements != NULL)
+ for (i = 0; elements[i]; ++i)
+ {
+ ret = elements[i]->type;
+ if (ret == FFI_TYPE_STRUCT || ret == FFI_TYPE_COMPLEX)
+ {
+ ret = is_hfa0 (elements[i]);
+ if (ret < 0)
+ continue;
+ }
+ break;
+ }
+
+ return ret;
+}
+
+/* A subroutine of vfp_type_p. Given a structure type, return true if all
+ of the non-structure elements are the same as CANDIDATE. */
+
+static int
+is_hfa1 (const ffi_type *ty, int candidate)
+{
+ ffi_type **elements = ty->elements;
+ int i;
+
+ if (elements != NULL)
+ for (i = 0; elements[i]; ++i)
+ {
+ int t = elements[i]->type;
+ if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
+ {
+ if (!is_hfa1 (elements[i], candidate))
+ return 0;
+ }
+ else if (t != candidate)
+ return 0;
+ }
+
+ return 1;
+}
+
+/* Determine if TY is an homogenous floating point aggregate (HFA).
+ That is, a structure consisting of 1 to 4 members of all the same type,
+ where that type is a floating point scalar.
+
+ Returns non-zero iff TY is an HFA. The result is an encoded value where
+ bits 0-7 contain the type code, and bits 8-10 contain the element count. */
+
+static int
+vfp_type_p (const ffi_type *ty)
+{
+ ffi_type **elements;
+ int candidate, i;
+ size_t size, ele_count;
+
+ /* Quickest tests first. */
+ candidate = ty->type;
+ switch (ty->type)
+ {
+ default:
+ return 0;
+ case FFI_TYPE_FLOAT:
+ case FFI_TYPE_DOUBLE:
+ ele_count = 1;
+ goto done;
+ case FFI_TYPE_COMPLEX:
+ candidate = ty->elements[0]->type;
+ if (candidate != FFI_TYPE_FLOAT && candidate != FFI_TYPE_DOUBLE)
+ return 0;
+ ele_count = 2;
+ goto done;
+ case FFI_TYPE_STRUCT:
+ break;
+ }
+
+ /* No HFA types are smaller than 4 bytes, or larger than 32 bytes. */
+ size = ty->size;
+ if (size < 4 || size > 32)
+ return 0;
+
+ /* Find the type of the first non-structure member. */
+ elements = ty->elements;
+ candidate = elements[0]->type;
+ if (candidate == FFI_TYPE_STRUCT || candidate == FFI_TYPE_COMPLEX)
+ {
+ for (i = 0; ; ++i)
+ {
+ candidate = is_hfa0 (elements[i]);
+ if (candidate >= 0)
+ break;
+ }
+ }
+
+ /* If the first member is not a floating point type, it's not an HFA.
+ Also quickly re-check the size of the structure. */
+ switch (candidate)
+ {
+ case FFI_TYPE_FLOAT:
+ ele_count = size / sizeof(float);
+ if (size != ele_count * sizeof(float))
+ return 0;
+ break;
+ case FFI_TYPE_DOUBLE:
+ ele_count = size / sizeof(double);
+ if (size != ele_count * sizeof(double))
+ return 0;
+ break;
+ default:
+ return 0;
+ }
+ if (ele_count > 4)
+ return 0;
+
+ /* Finally, make sure that all scalar elements are the same type. */
+ for (i = 0; elements[i]; ++i)
+ {
+ int t = elements[i]->type;
+ if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
+ {
+ if (!is_hfa1 (elements[i], candidate))
+ return 0;
+ }
+ else if (t != candidate)
+ return 0;
+ }
+
+ /* All tests succeeded. Encode the result. */
+ done:
+ return (ele_count << 8) | candidate;
+}
+
+static int
+place_vfp_arg (ffi_cif *cif, int h)
+{
+ unsigned short reg = cif->vfp_reg_free;
+ int align = 1, nregs = h >> 8;
+
+ if ((h & 0xff) == FFI_TYPE_DOUBLE)
+ align = 2, nregs *= 2;
+
+ /* Align register number. */
+ if ((reg & 1) && align == 2)
+ reg++;
+
+ while (reg + nregs <= 16)
+ {
+ int s, new_used = 0;
+ for (s = reg; s < reg + nregs; s++)
+ {
+ new_used |= (1 << s);
+ if (cif->vfp_used & (1 << s))
+ {
+ reg += align;
+ goto next_reg;
+ }
+ }
+ /* Found regs to allocate. */
+ cif->vfp_used |= new_used;
+ cif->vfp_args[cif->vfp_nargs++] = (signed char)reg;
+
+ /* Update vfp_reg_free. */
+ if (cif->vfp_used & (1 << cif->vfp_reg_free))
+ {
+ reg += nregs;
+ while (cif->vfp_used & (1 << reg))
+ reg += 1;
+ cif->vfp_reg_free = reg;
+ }
+ return 0;
+ next_reg:;
+ }
+ // done, mark all regs as used
+ cif->vfp_reg_free = 16;
+ cif->vfp_used = 0xFFFF;
+ return 1;
+}
+
+static void
+layout_vfp_args (ffi_cif * cif)
+{
+ unsigned int i;
+ /* Init VFP fields */
+ cif->vfp_used = 0;
+ cif->vfp_nargs = 0;
+ cif->vfp_reg_free = 0;
+ memset (cif->vfp_args, -1, 16); /* Init to -1. */
+
+ for (i = 0; i < cif->nargs; i++)
+ {
+ int h = vfp_type_p (cif->arg_types[i]);
+ if (h && place_vfp_arg (cif, h) == 1)
+ break;
+ }
+}
+
+#endif /* __arm__ or _M_ARM */
diff --git a/contrib/restricted/libffi/src/arm/ffitarget.h b/contrib/restricted/libffi/src/arm/ffitarget.h
index 24e1de72b9..cb57b84880 100644
--- a/contrib/restricted/libffi/src/arm/ffitarget.h
+++ b/contrib/restricted/libffi/src/arm/ffitarget.h
@@ -1,89 +1,89 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012 Anthony Green
- Copyright (c) 2010 CodeSourcery
- Copyright (c) 1996-2003 Red Hat, Inc.
-
- Target configuration macros for ARM.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-#ifndef LIBFFI_ASM
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-
-typedef enum ffi_abi {
- FFI_FIRST_ABI = 0,
- FFI_SYSV,
- FFI_VFP,
- FFI_LAST_ABI,
-#if defined(__ARM_PCS_VFP) || defined(_M_ARM)
- FFI_DEFAULT_ABI = FFI_VFP,
-#else
- FFI_DEFAULT_ABI = FFI_SYSV,
-#endif
-} ffi_abi;
-#endif
-
-#define FFI_EXTRA_CIF_FIELDS \
- int vfp_used; \
- unsigned short vfp_reg_free, vfp_nargs; \
- signed char vfp_args[16] \
-
-#define FFI_TARGET_SPECIFIC_VARIADIC
-#ifndef _M_ARM
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-#define FFI_NATIVE_RAW_API 0
-
-#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#define FFI_TRAMPOLINE_SIZE 12
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET 8
-#else
-#error "No trampoline table implementation"
-#endif
-
-#else
-#ifdef _MSC_VER
-#define FFI_TRAMPOLINE_SIZE 16
-#define FFI_TRAMPOLINE_CLOSURE_FUNCTION 12
-#else
-#define FFI_TRAMPOLINE_SIZE 12
-#endif
-#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
-#endif
-
-#endif
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012 Anthony Green
+ Copyright (c) 2010 CodeSourcery
+ Copyright (c) 1996-2003 Red Hat, Inc.
+
+ Target configuration macros for ARM.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+#ifndef LIBFFI_ASM
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+
+typedef enum ffi_abi {
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV,
+ FFI_VFP,
+ FFI_LAST_ABI,
+#if defined(__ARM_PCS_VFP) || defined(_M_ARM)
+ FFI_DEFAULT_ABI = FFI_VFP,
+#else
+ FFI_DEFAULT_ABI = FFI_SYSV,
+#endif
+} ffi_abi;
+#endif
+
+#define FFI_EXTRA_CIF_FIELDS \
+ int vfp_used; \
+ unsigned short vfp_reg_free, vfp_nargs; \
+ signed char vfp_args[16] \
+
+#define FFI_TARGET_SPECIFIC_VARIADIC
+#ifndef _M_ARM
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_GO_CLOSURES 1
+#define FFI_NATIVE_RAW_API 0
+
+#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#define FFI_TRAMPOLINE_SIZE 12
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET 8
+#else
+#error "No trampoline table implementation"
+#endif
+
+#else
+#ifdef _MSC_VER
+#define FFI_TRAMPOLINE_SIZE 16
+#define FFI_TRAMPOLINE_CLOSURE_FUNCTION 12
+#else
+#define FFI_TRAMPOLINE_SIZE 12
+#endif
+#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/src/arm/internal.h b/contrib/restricted/libffi/src/arm/internal.h
index 418dc460f3..6cf0b2ae5d 100644
--- a/contrib/restricted/libffi/src/arm/internal.h
+++ b/contrib/restricted/libffi/src/arm/internal.h
@@ -1,7 +1,7 @@
-#define ARM_TYPE_VFP_S 0
-#define ARM_TYPE_VFP_D 1
-#define ARM_TYPE_VFP_N 2
-#define ARM_TYPE_INT64 3
-#define ARM_TYPE_INT 4
-#define ARM_TYPE_VOID 5
-#define ARM_TYPE_STRUCT 6
+#define ARM_TYPE_VFP_S 0
+#define ARM_TYPE_VFP_D 1
+#define ARM_TYPE_VFP_N 2
+#define ARM_TYPE_INT64 3
+#define ARM_TYPE_INT 4
+#define ARM_TYPE_VOID 5
+#define ARM_TYPE_STRUCT 6
diff --git a/contrib/restricted/libffi/src/arm/sysv.S b/contrib/restricted/libffi/src/arm/sysv.S
index dec168db0b..63180a4639 100644
--- a/contrib/restricted/libffi/src/arm/sysv.S
+++ b/contrib/restricted/libffi/src/arm/sysv.S
@@ -1,385 +1,385 @@
-/* -----------------------------------------------------------------------
- sysv.S - Copyright (c) 1998, 2008, 2011 Red Hat, Inc.
- Copyright (c) 2011 Plausible Labs Cooperative, Inc.
-
- ARM Foreign Function Interface
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#ifdef __arm__
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
-#include <ffi_cfi.h>
-#include "internal.h"
-
-/* GCC 4.8 provides __ARM_ARCH; construct it otherwise. */
-#ifndef __ARM_ARCH
-# if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \
- || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \
- || defined(__ARM_ARCH_7EM__)
-# define __ARM_ARCH 7
-# elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \
- || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) \
- || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) \
- || defined(__ARM_ARCH_6M__)
-# define __ARM_ARCH 6
-# elif defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) \
- || defined(__ARM_ARCH_5E__) || defined(__ARM_ARCH_5TE__) \
- || defined(__ARM_ARCH_5TEJ__)
-# define __ARM_ARCH 5
-# else
-# define __ARM_ARCH 4
-# endif
-#endif
-
-/* Conditionally compile unwinder directives. */
-#ifdef __ARM_EABI__
-# define UNWIND(...) __VA_ARGS__
-#else
-# define UNWIND(...)
-#endif
-
-#if defined(HAVE_AS_CFI_PSEUDO_OP) && defined(__ARM_EABI__)
- .cfi_sections .debug_frame
-#endif
-
-#define CONCAT(a, b) CONCAT2(a, b)
-#define CONCAT2(a, b) a ## b
-
-#ifdef __USER_LABEL_PREFIX__
-# define CNAME(X) CONCAT (__USER_LABEL_PREFIX__, X)
-#else
-# define CNAME(X) X
-#endif
-#ifdef __ELF__
-# define SIZE(X) .size CNAME(X), . - CNAME(X)
-# define TYPE(X, Y) .type CNAME(X), Y
-#else
-# define SIZE(X)
-# define TYPE(X, Y)
-#endif
-
-#define ARM_FUNC_START_LOCAL(name) \
- .align 3; \
- TYPE(CNAME(name), %function); \
- CNAME(name):
-
-#define ARM_FUNC_START(name) \
- .globl CNAME(name); \
- FFI_HIDDEN(CNAME(name)); \
- ARM_FUNC_START_LOCAL(name)
-
-#define ARM_FUNC_END(name) \
- SIZE(name)
-
-/* Aid in defining a jump table with 8 bytes between entries. */
-/* ??? The clang assembler doesn't handle .if with symbolic expressions. */
-#ifdef __clang__
-# define E(index)
-#else
-# define E(index) \
- .if . - 0b - 8*index; \
- .error "type table out of sync"; \
- .endif
-#endif
-
- .text
- .syntax unified
- .arm
-
-#ifndef __clang__
- /* We require interworking on LDM, which implies ARMv5T,
- which implies the existance of BLX. */
- .arch armv5t
-#endif
-
- /* Note that we use STC and LDC to encode VFP instructions,
- so that we do not need ".fpu vfp", nor get that added to
- the object file attributes. These will not be executed
- unless the FFI_VFP abi is used. */
-
- @ r0: stack
- @ r1: frame
- @ r2: fn
- @ r3: vfp_used
-
-ARM_FUNC_START(ffi_call_VFP)
- UNWIND(.fnstart)
- cfi_startproc
-
- cmp r3, #3 @ load only d0 if possible
-#ifdef __clang__
- vldrle d0, [sp]
- vldmgt sp, {d0-d7}
-#else
- ldcle p11, cr0, [r0] @ vldrle d0, [sp]
- ldcgt p11, cr0, [r0], {16} @ vldmgt sp, {d0-d7}
-#endif
- add r0, r0, #64 @ discard the vfp register args
- /* FALLTHRU */
-ARM_FUNC_END(ffi_call_VFP)
-
-ARM_FUNC_START(ffi_call_SYSV)
- stm r1, {fp, lr}
- mov fp, r1
-
- @ This is a bit of a lie wrt the origin of the unwind info, but
- @ now we've got the usual frame pointer and two saved registers.
- UNWIND(.save {fp,lr})
- UNWIND(.setfp fp, sp)
- cfi_def_cfa(fp, 8)
- cfi_rel_offset(fp, 0)
- cfi_rel_offset(lr, 4)
-
- mov sp, r0 @ install the stack pointer
- mov lr, r2 @ move the fn pointer out of the way
- ldr ip, [fp, #16] @ install the static chain
- ldmia sp!, {r0-r3} @ move first 4 parameters in registers.
- blx lr @ call fn
-
- @ Load r2 with the pointer to storage for the return value
- @ Load r3 with the return type code
- ldr r2, [fp, #8]
- ldr r3, [fp, #12]
-
- @ Deallocate the stack with the arguments.
- mov sp, fp
- cfi_def_cfa_register(sp)
-
- @ Store values stored in registers.
- .align 3
- add pc, pc, r3, lsl #3
- nop
-0:
-E(ARM_TYPE_VFP_S)
-#ifdef __clang__
- vstr s0, [r2]
-#else
- stc p10, cr0, [r2] @ vstr s0, [r2]
-#endif
- pop {fp,pc}
-E(ARM_TYPE_VFP_D)
-#ifdef __clang__
- vstr d0, [r2]
-#else
- stc p11, cr0, [r2] @ vstr d0, [r2]
-#endif
- pop {fp,pc}
-E(ARM_TYPE_VFP_N)
-#ifdef __clang__
- vstm r2, {d0-d3}
-#else
- stc p11, cr0, [r2], {8} @ vstm r2, {d0-d3}
-#endif
- pop {fp,pc}
-E(ARM_TYPE_INT64)
- str r1, [r2, #4]
- nop
-E(ARM_TYPE_INT)
- str r0, [r2]
- pop {fp,pc}
-E(ARM_TYPE_VOID)
- pop {fp,pc}
- nop
-E(ARM_TYPE_STRUCT)
- pop {fp,pc}
-
- cfi_endproc
- UNWIND(.fnend)
-ARM_FUNC_END(ffi_call_SYSV)
-
-
-/*
- int ffi_closure_inner_* (cif, fun, user_data, frame)
-*/
-
-ARM_FUNC_START(ffi_go_closure_SYSV)
- cfi_startproc
- stmdb sp!, {r0-r3} @ save argument regs
- cfi_adjust_cfa_offset(16)
- ldr r0, [ip, #4] @ load cif
- ldr r1, [ip, #8] @ load fun
- mov r2, ip @ load user_data
- b 0f
- cfi_endproc
-ARM_FUNC_END(ffi_go_closure_SYSV)
-
-ARM_FUNC_START(ffi_closure_SYSV)
- UNWIND(.fnstart)
- cfi_startproc
- stmdb sp!, {r0-r3} @ save argument regs
- cfi_adjust_cfa_offset(16)
-
-#if FFI_EXEC_TRAMPOLINE_TABLE
- ldr ip, [ip] @ ip points to the config page, dereference to get the ffi_closure*
-#endif
- ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] @ load cif
- ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] @ load fun
- ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] @ load user_data
-0:
- add ip, sp, #16 @ compute entry sp
- sub sp, sp, #64+32 @ allocate frame
- cfi_adjust_cfa_offset(64+32)
- stmdb sp!, {ip,lr}
-
- /* Remember that EABI unwind info only applies at call sites.
- We need do nothing except note the save of the stack pointer
- and the link registers. */
- UNWIND(.save {sp,lr})
- cfi_adjust_cfa_offset(8)
- cfi_rel_offset(lr, 4)
-
- add r3, sp, #8 @ load frame
- bl CNAME(ffi_closure_inner_SYSV)
-
- @ Load values returned in registers.
- add r2, sp, #8+64 @ load result
- adr r3, CNAME(ffi_closure_ret)
- add pc, r3, r0, lsl #3
- cfi_endproc
- UNWIND(.fnend)
-ARM_FUNC_END(ffi_closure_SYSV)
-
-ARM_FUNC_START(ffi_go_closure_VFP)
- cfi_startproc
- stmdb sp!, {r0-r3} @ save argument regs
- cfi_adjust_cfa_offset(16)
- ldr r0, [ip, #4] @ load cif
- ldr r1, [ip, #8] @ load fun
- mov r2, ip @ load user_data
- b 0f
- cfi_endproc
-ARM_FUNC_END(ffi_go_closure_VFP)
-
-ARM_FUNC_START(ffi_closure_VFP)
- UNWIND(.fnstart)
- cfi_startproc
- stmdb sp!, {r0-r3} @ save argument regs
- cfi_adjust_cfa_offset(16)
-
-#if FFI_EXEC_TRAMPOLINE_TABLE
- ldr ip, [ip] @ ip points to the config page, dereference to get the ffi_closure*
-#endif
- ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] @ load cif
- ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] @ load fun
- ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] @ load user_data
-0:
- add ip, sp, #16
- sub sp, sp, #64+32 @ allocate frame
- cfi_adjust_cfa_offset(64+32)
-#ifdef __clang__
- vstm sp, {d0-d7}
-#else
- stc p11, cr0, [sp], {16} @ vstm sp, {d0-d7}
-#endif
- stmdb sp!, {ip,lr}
-
- /* See above. */
- UNWIND(.save {sp,lr})
- cfi_adjust_cfa_offset(8)
- cfi_rel_offset(lr, 4)
-
- add r3, sp, #8 @ load frame
- bl CNAME(ffi_closure_inner_VFP)
-
- @ Load values returned in registers.
- add r2, sp, #8+64 @ load result
- adr r3, CNAME(ffi_closure_ret)
- add pc, r3, r0, lsl #3
- cfi_endproc
- UNWIND(.fnend)
-ARM_FUNC_END(ffi_closure_VFP)
-
-/* Load values returned in registers for both closure entry points.
- Note that we use LDM with SP in the register set. This is deprecated
- by ARM, but not yet unpredictable. */
-
-ARM_FUNC_START_LOCAL(ffi_closure_ret)
- cfi_startproc
- cfi_rel_offset(sp, 0)
- cfi_rel_offset(lr, 4)
-0:
-E(ARM_TYPE_VFP_S)
-#ifdef __clang__
- vldr s0, [r2]
-#else
- ldc p10, cr0, [r2] @ vldr s0, [r2]
-#endif
- ldm sp, {sp,pc}
-E(ARM_TYPE_VFP_D)
-#ifdef __clang__
- vldr d0, [r2]
-#else
- ldc p11, cr0, [r2] @ vldr d0, [r2]
-#endif
- ldm sp, {sp,pc}
-E(ARM_TYPE_VFP_N)
-#ifdef __clang__
- vldm r2, {d0-d3}
-#else
- ldc p11, cr0, [r2], {8} @ vldm r2, {d0-d3}
-#endif
- ldm sp, {sp,pc}
-E(ARM_TYPE_INT64)
- ldr r1, [r2, #4]
- nop
-E(ARM_TYPE_INT)
- ldr r0, [r2]
- ldm sp, {sp,pc}
-E(ARM_TYPE_VOID)
- ldm sp, {sp,pc}
- nop
-E(ARM_TYPE_STRUCT)
- ldm sp, {sp,pc}
- cfi_endproc
-ARM_FUNC_END(ffi_closure_ret)
-
-#if FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-#include <mach/machine/vm_param.h>
-
-.align PAGE_MAX_SHIFT
-ARM_FUNC_START(ffi_closure_trampoline_table_page)
-.rept PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE
- adr ip, #-PAGE_MAX_SIZE @ the config page is PAGE_MAX_SIZE behind the trampoline page
- sub ip, #8 @ account for pc bias
- ldr pc, [ip, #4] @ jump to ffi_closure_SYSV or ffi_closure_VFP
-.endr
-ARM_FUNC_END(ffi_closure_trampoline_table_page)
-#endif
-
-#else
-
-ARM_FUNC_START(ffi_arm_trampoline)
-0: adr ip, 0b
- ldr pc, 1f
-1: .long 0
-ARM_FUNC_END(ffi_arm_trampoline)
-
-#endif /* FFI_EXEC_TRAMPOLINE_TABLE */
-#endif /* __arm__ */
-
-#if defined __ELF__ && defined __linux__
- .section .note.GNU-stack,"",%progbits
-#endif
+/* -----------------------------------------------------------------------
+ sysv.S - Copyright (c) 1998, 2008, 2011 Red Hat, Inc.
+ Copyright (c) 2011 Plausible Labs Cooperative, Inc.
+
+ ARM Foreign Function Interface
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#ifdef __arm__
+#define LIBFFI_ASM
+#include <fficonfig.h>
+#include <ffi.h>
+#include <ffi_cfi.h>
+#include "internal.h"
+
+/* GCC 4.8 provides __ARM_ARCH; construct it otherwise. */
+#ifndef __ARM_ARCH
+# if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \
+ || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \
+ || defined(__ARM_ARCH_7EM__)
+# define __ARM_ARCH 7
+# elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \
+ || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) \
+ || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) \
+ || defined(__ARM_ARCH_6M__)
+# define __ARM_ARCH 6
+# elif defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) \
+ || defined(__ARM_ARCH_5E__) || defined(__ARM_ARCH_5TE__) \
+ || defined(__ARM_ARCH_5TEJ__)
+# define __ARM_ARCH 5
+# else
+# define __ARM_ARCH 4
+# endif
+#endif
+
+/* Conditionally compile unwinder directives. */
+#ifdef __ARM_EABI__
+# define UNWIND(...) __VA_ARGS__
+#else
+# define UNWIND(...)
+#endif
+
+#if defined(HAVE_AS_CFI_PSEUDO_OP) && defined(__ARM_EABI__)
+ .cfi_sections .debug_frame
+#endif
+
+#define CONCAT(a, b) CONCAT2(a, b)
+#define CONCAT2(a, b) a ## b
+
+#ifdef __USER_LABEL_PREFIX__
+# define CNAME(X) CONCAT (__USER_LABEL_PREFIX__, X)
+#else
+# define CNAME(X) X
+#endif
+#ifdef __ELF__
+# define SIZE(X) .size CNAME(X), . - CNAME(X)
+# define TYPE(X, Y) .type CNAME(X), Y
+#else
+# define SIZE(X)
+# define TYPE(X, Y)
+#endif
+
+#define ARM_FUNC_START_LOCAL(name) \
+ .align 3; \
+ TYPE(CNAME(name), %function); \
+ CNAME(name):
+
+#define ARM_FUNC_START(name) \
+ .globl CNAME(name); \
+ FFI_HIDDEN(CNAME(name)); \
+ ARM_FUNC_START_LOCAL(name)
+
+#define ARM_FUNC_END(name) \
+ SIZE(name)
+
+/* Aid in defining a jump table with 8 bytes between entries. */
+/* ??? The clang assembler doesn't handle .if with symbolic expressions. */
+#ifdef __clang__
+# define E(index)
+#else
+# define E(index) \
+ .if . - 0b - 8*index; \
+ .error "type table out of sync"; \
+ .endif
+#endif
+
+ .text
+ .syntax unified
+ .arm
+
+#ifndef __clang__
+ /* We require interworking on LDM, which implies ARMv5T,
+ which implies the existance of BLX. */
+ .arch armv5t
+#endif
+
+ /* Note that we use STC and LDC to encode VFP instructions,
+ so that we do not need ".fpu vfp", nor get that added to
+ the object file attributes. These will not be executed
+ unless the FFI_VFP abi is used. */
+
+ @ r0: stack
+ @ r1: frame
+ @ r2: fn
+ @ r3: vfp_used
+
+ARM_FUNC_START(ffi_call_VFP)
+ UNWIND(.fnstart)
+ cfi_startproc
+
+ cmp r3, #3 @ load only d0 if possible
+#ifdef __clang__
+ vldrle d0, [sp]
+ vldmgt sp, {d0-d7}
+#else
+ ldcle p11, cr0, [r0] @ vldrle d0, [sp]
+ ldcgt p11, cr0, [r0], {16} @ vldmgt sp, {d0-d7}
+#endif
+ add r0, r0, #64 @ discard the vfp register args
+ /* FALLTHRU */
+ARM_FUNC_END(ffi_call_VFP)
+
+ARM_FUNC_START(ffi_call_SYSV)
+ stm r1, {fp, lr}
+ mov fp, r1
+
+ @ This is a bit of a lie wrt the origin of the unwind info, but
+ @ now we've got the usual frame pointer and two saved registers.
+ UNWIND(.save {fp,lr})
+ UNWIND(.setfp fp, sp)
+ cfi_def_cfa(fp, 8)
+ cfi_rel_offset(fp, 0)
+ cfi_rel_offset(lr, 4)
+
+ mov sp, r0 @ install the stack pointer
+ mov lr, r2 @ move the fn pointer out of the way
+ ldr ip, [fp, #16] @ install the static chain
+ ldmia sp!, {r0-r3} @ move first 4 parameters in registers.
+ blx lr @ call fn
+
+ @ Load r2 with the pointer to storage for the return value
+ @ Load r3 with the return type code
+ ldr r2, [fp, #8]
+ ldr r3, [fp, #12]
+
+ @ Deallocate the stack with the arguments.
+ mov sp, fp
+ cfi_def_cfa_register(sp)
+
+ @ Store values stored in registers.
+ .align 3
+ add pc, pc, r3, lsl #3
+ nop
+0:
+E(ARM_TYPE_VFP_S)
+#ifdef __clang__
+ vstr s0, [r2]
+#else
+ stc p10, cr0, [r2] @ vstr s0, [r2]
+#endif
+ pop {fp,pc}
+E(ARM_TYPE_VFP_D)
+#ifdef __clang__
+ vstr d0, [r2]
+#else
+ stc p11, cr0, [r2] @ vstr d0, [r2]
+#endif
+ pop {fp,pc}
+E(ARM_TYPE_VFP_N)
+#ifdef __clang__
+ vstm r2, {d0-d3}
+#else
+ stc p11, cr0, [r2], {8} @ vstm r2, {d0-d3}
+#endif
+ pop {fp,pc}
+E(ARM_TYPE_INT64)
+ str r1, [r2, #4]
+ nop
+E(ARM_TYPE_INT)
+ str r0, [r2]
+ pop {fp,pc}
+E(ARM_TYPE_VOID)
+ pop {fp,pc}
+ nop
+E(ARM_TYPE_STRUCT)
+ pop {fp,pc}
+
+ cfi_endproc
+ UNWIND(.fnend)
+ARM_FUNC_END(ffi_call_SYSV)
+
+
+/*
+ int ffi_closure_inner_* (cif, fun, user_data, frame)
+*/
+
+ARM_FUNC_START(ffi_go_closure_SYSV)
+ cfi_startproc
+ stmdb sp!, {r0-r3} @ save argument regs
+ cfi_adjust_cfa_offset(16)
+ ldr r0, [ip, #4] @ load cif
+ ldr r1, [ip, #8] @ load fun
+ mov r2, ip @ load user_data
+ b 0f
+ cfi_endproc
+ARM_FUNC_END(ffi_go_closure_SYSV)
+
+ARM_FUNC_START(ffi_closure_SYSV)
+ UNWIND(.fnstart)
+ cfi_startproc
+ stmdb sp!, {r0-r3} @ save argument regs
+ cfi_adjust_cfa_offset(16)
+
+#if FFI_EXEC_TRAMPOLINE_TABLE
+ ldr ip, [ip] @ ip points to the config page, dereference to get the ffi_closure*
+#endif
+ ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] @ load cif
+ ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] @ load fun
+ ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] @ load user_data
+0:
+ add ip, sp, #16 @ compute entry sp
+ sub sp, sp, #64+32 @ allocate frame
+ cfi_adjust_cfa_offset(64+32)
+ stmdb sp!, {ip,lr}
+
+ /* Remember that EABI unwind info only applies at call sites.
+ We need do nothing except note the save of the stack pointer
+ and the link registers. */
+ UNWIND(.save {sp,lr})
+ cfi_adjust_cfa_offset(8)
+ cfi_rel_offset(lr, 4)
+
+ add r3, sp, #8 @ load frame
+ bl CNAME(ffi_closure_inner_SYSV)
+
+ @ Load values returned in registers.
+ add r2, sp, #8+64 @ load result
+ adr r3, CNAME(ffi_closure_ret)
+ add pc, r3, r0, lsl #3
+ cfi_endproc
+ UNWIND(.fnend)
+ARM_FUNC_END(ffi_closure_SYSV)
+
+ARM_FUNC_START(ffi_go_closure_VFP)
+ cfi_startproc
+ stmdb sp!, {r0-r3} @ save argument regs
+ cfi_adjust_cfa_offset(16)
+ ldr r0, [ip, #4] @ load cif
+ ldr r1, [ip, #8] @ load fun
+ mov r2, ip @ load user_data
+ b 0f
+ cfi_endproc
+ARM_FUNC_END(ffi_go_closure_VFP)
+
+ARM_FUNC_START(ffi_closure_VFP)
+ UNWIND(.fnstart)
+ cfi_startproc
+ stmdb sp!, {r0-r3} @ save argument regs
+ cfi_adjust_cfa_offset(16)
+
+#if FFI_EXEC_TRAMPOLINE_TABLE
+ ldr ip, [ip] @ ip points to the config page, dereference to get the ffi_closure*
+#endif
+ ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] @ load cif
+ ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] @ load fun
+ ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] @ load user_data
+0:
+ add ip, sp, #16
+ sub sp, sp, #64+32 @ allocate frame
+ cfi_adjust_cfa_offset(64+32)
+#ifdef __clang__
+ vstm sp, {d0-d7}
+#else
+ stc p11, cr0, [sp], {16} @ vstm sp, {d0-d7}
+#endif
+ stmdb sp!, {ip,lr}
+
+ /* See above. */
+ UNWIND(.save {sp,lr})
+ cfi_adjust_cfa_offset(8)
+ cfi_rel_offset(lr, 4)
+
+ add r3, sp, #8 @ load frame
+ bl CNAME(ffi_closure_inner_VFP)
+
+ @ Load values returned in registers.
+ add r2, sp, #8+64 @ load result
+ adr r3, CNAME(ffi_closure_ret)
+ add pc, r3, r0, lsl #3
+ cfi_endproc
+ UNWIND(.fnend)
+ARM_FUNC_END(ffi_closure_VFP)
+
+/* Load values returned in registers for both closure entry points.
+ Note that we use LDM with SP in the register set. This is deprecated
+ by ARM, but not yet unpredictable. */
+
+ARM_FUNC_START_LOCAL(ffi_closure_ret)
+ cfi_startproc
+ cfi_rel_offset(sp, 0)
+ cfi_rel_offset(lr, 4)
+0:
+E(ARM_TYPE_VFP_S)
+#ifdef __clang__
+ vldr s0, [r2]
+#else
+ ldc p10, cr0, [r2] @ vldr s0, [r2]
+#endif
+ ldm sp, {sp,pc}
+E(ARM_TYPE_VFP_D)
+#ifdef __clang__
+ vldr d0, [r2]
+#else
+ ldc p11, cr0, [r2] @ vldr d0, [r2]
+#endif
+ ldm sp, {sp,pc}
+E(ARM_TYPE_VFP_N)
+#ifdef __clang__
+ vldm r2, {d0-d3}
+#else
+ ldc p11, cr0, [r2], {8} @ vldm r2, {d0-d3}
+#endif
+ ldm sp, {sp,pc}
+E(ARM_TYPE_INT64)
+ ldr r1, [r2, #4]
+ nop
+E(ARM_TYPE_INT)
+ ldr r0, [r2]
+ ldm sp, {sp,pc}
+E(ARM_TYPE_VOID)
+ ldm sp, {sp,pc}
+ nop
+E(ARM_TYPE_STRUCT)
+ ldm sp, {sp,pc}
+ cfi_endproc
+ARM_FUNC_END(ffi_closure_ret)
+
+#if FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+#include <mach/machine/vm_param.h>
+
+.align PAGE_MAX_SHIFT
+ARM_FUNC_START(ffi_closure_trampoline_table_page)
+.rept PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE
+ adr ip, #-PAGE_MAX_SIZE @ the config page is PAGE_MAX_SIZE behind the trampoline page
+ sub ip, #8 @ account for pc bias
+ ldr pc, [ip, #4] @ jump to ffi_closure_SYSV or ffi_closure_VFP
+.endr
+ARM_FUNC_END(ffi_closure_trampoline_table_page)
+#endif
+
+#else
+
+ARM_FUNC_START(ffi_arm_trampoline)
+0: adr ip, 0b
+ ldr pc, 1f
+1: .long 0
+ARM_FUNC_END(ffi_arm_trampoline)
+
+#endif /* FFI_EXEC_TRAMPOLINE_TABLE */
+#endif /* __arm__ */
+
+#if defined __ELF__ && defined __linux__
+ .section .note.GNU-stack,"",%progbits
+#endif
diff --git a/contrib/restricted/libffi/src/arm/sysv_msvc_arm32.S b/contrib/restricted/libffi/src/arm/sysv_msvc_arm32.S
index 29ab997467..5c99d0207a 100644
--- a/contrib/restricted/libffi/src/arm/sysv_msvc_arm32.S
+++ b/contrib/restricted/libffi/src/arm/sysv_msvc_arm32.S
@@ -1,311 +1,311 @@
-/* -----------------------------------------------------------------------
- sysv.S - Copyright (c) 1998, 2008, 2011 Red Hat, Inc.
- Copyright (c) 2011 Plausible Labs Cooperative, Inc.
- Copyright (c) 2019 Microsoft Corporation.
-
- ARM Foreign Function Interface
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
-#include <ffi_cfi.h>
-#include "internal.h"
-#include "ksarm.h"
-
-
- ; 8 byte aligned AREA to support 8 byte aligned jump tables
- MACRO
- NESTED_ENTRY_FFI $FuncName, $AreaName, $ExceptHandler
-
- ; compute the function's labels
- __DeriveFunctionLabels $FuncName
-
- ; determine the area we will put the function into
-__FuncArea SETS "|.text|"
- IF "$AreaName" != ""
-__FuncArea SETS "$AreaName"
- ENDIF
-
- ; set up the exception handler itself
-__FuncExceptionHandler SETS ""
- IF "$ExceptHandler" != ""
-__FuncExceptionHandler SETS "|$ExceptHandler|"
- ENDIF
-
- ; switch to the specified area, jump tables require 8 byte alignment
- AREA $__FuncArea,CODE,CODEALIGN,ALIGN=3,READONLY
-
- ; export the function name
- __ExportProc $FuncName
-
- ; flush any pending literal pool stuff
- ROUT
-
- ; reset the state of the unwind code tracking
- __ResetUnwindState
-
- MEND
-
-; MACRO
-; TABLE_ENTRY $Type, $Table
-;$Type_$Table
-; MEND
-
-#define E(index,table) return_##index##_##table
-
- ; r0: stack
- ; r1: frame
- ; r2: fn
- ; r3: vfp_used
-
- ; fake entry point exists only to generate exists only to
- ; generate .pdata for exception unwinding
- NESTED_ENTRY_FFI ffi_call_VFP_fake
- PROLOG_PUSH {r11, lr} ; save fp and lr for unwind
-
- ALTERNATE_ENTRY ffi_call_VFP
- cmp r3, #3 ; load only d0 if possible
- vldrle d0, [r0]
- vldmgt r0, {d0-d7}
- add r0, r0, #64 ; discard the vfp register args
- b ffi_call_SYSV
- NESTED_END ffi_call_VFP_fake
-
- ; fake entry point exists only to generate exists only to
- ; generate .pdata for exception unwinding
- NESTED_ENTRY_FFI ffi_call_SYSV_fake
- PROLOG_PUSH {r11, lr} ; save fp and lr for unwind
-
- ALTERNATE_ENTRY ffi_call_SYSV
- stm r1, {fp, lr}
- mov fp, r1
-
- mov sp, r0 ; install the stack pointer
- mov lr, r2 ; move the fn pointer out of the way
- ldr ip, [fp, #16] ; install the static chain
- ldmia sp!, {r0-r3} ; move first 4 parameters in registers.
- blx lr ; call fn
-
- ; Load r2 with the pointer to storage for the return value
- ; Load r3 with the return type code
- ldr r2, [fp, #8]
- ldr r3, [fp, #12]
-
- ; Deallocate the stack with the arguments.
- mov sp, fp
-
- ; Store values stored in registers.
- ALIGN 8
- lsl r3, #3
- add r3, r3, pc
- add r3, #8
- mov pc, r3
-
-
-E(ARM_TYPE_VFP_S, ffi_call)
- ALIGN 8
- vstr s0, [r2]
- pop {fp,pc}
-E(ARM_TYPE_VFP_D, ffi_call)
- ALIGN 8
- vstr d0, [r2]
- pop {fp,pc}
-E(ARM_TYPE_VFP_N, ffi_call)
- ALIGN 8
- vstm r2, {d0-d3}
- pop {fp,pc}
-E(ARM_TYPE_INT64, ffi_call)
- ALIGN 8
- str r1, [r2, #4]
- nop
-E(ARM_TYPE_INT, ffi_call)
- ALIGN 8
- str r0, [r2]
- pop {fp,pc}
-E(ARM_TYPE_VOID, ffi_call)
- ALIGN 8
- pop {fp,pc}
- nop
-E(ARM_TYPE_STRUCT, ffi_call)
- ALIGN 8
- cmp r3, #ARM_TYPE_STRUCT
- pop {fp,pc}
- NESTED_END ffi_call_SYSV_fake
-
- IMPORT |ffi_closure_inner_SYSV|
- /*
- int ffi_closure_inner_SYSV
- (
- cif, ; r0
- fun, ; r1
- user_data, ; r2
- frame ; r3
- )
- */
-
- NESTED_ENTRY_FFI ffi_go_closure_SYSV
- stmdb sp!, {r0-r3} ; save argument regs
- ldr r0, [ip, #4] ; load cif
- ldr r1, [ip, #8] ; load fun
- mov r2, ip ; load user_data
- b ffi_go_closure_SYSV_0
- NESTED_END ffi_go_closure_SYSV
-
- ; r3: ffi_closure
-
- ; fake entry point exists only to generate exists only to
- ; generate .pdata for exception unwinding
- NESTED_ENTRY_FFI ffi_closure_SYSV_fake
- PROLOG_PUSH {r11, lr} ; save fp and lr for unwind
- ALTERNATE_ENTRY ffi_closure_SYSV
- ldmfd sp!, {ip,r0} ; restore fp (r0 is used for stack alignment)
- stmdb sp!, {r0-r3} ; save argument regs
-
- ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] ; ffi_closure->cif
- ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] ; ffi_closure->fun
- ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] ; ffi_closure->user_data
-
- ALTERNATE_ENTRY ffi_go_closure_SYSV_0
- add ip, sp, #16 ; compute entry sp
-
- sub sp, sp, #64+32 ; allocate frame parameter (sizeof(vfp_space) = 64, sizeof(result) = 32)
- mov r3, sp ; set frame parameter
- stmdb sp!, {ip,lr}
-
- bl ffi_closure_inner_SYSV ; call the Python closure
-
- ; Load values returned in registers.
- add r2, sp, #64+8 ; address of closure_frame->result
- bl ffi_closure_ret ; move result to correct register or memory for type
-
- ldmfd sp!, {ip,lr}
- mov sp, ip ; restore stack pointer
- mov pc, lr
- NESTED_END ffi_closure_SYSV_fake
-
- IMPORT |ffi_closure_inner_VFP|
- /*
- int ffi_closure_inner_VFP
- (
- cif, ; r0
- fun, ; r1
- user_data, ; r2
- frame ; r3
- )
- */
-
- NESTED_ENTRY_FFI ffi_go_closure_VFP
- stmdb sp!, {r0-r3} ; save argument regs
- ldr r0, [ip, #4] ; load cif
- ldr r1, [ip, #8] ; load fun
- mov r2, ip ; load user_data
- b ffi_go_closure_VFP_0
- NESTED_END ffi_go_closure_VFP
-
- ; fake entry point exists only to generate exists only to
- ; generate .pdata for exception unwinding
- ; r3: closure
- NESTED_ENTRY_FFI ffi_closure_VFP_fake
- PROLOG_PUSH {r11, lr} ; save fp and lr for unwind
-
- ALTERNATE_ENTRY ffi_closure_VFP
- ldmfd sp!, {ip,r0} ; restore fp (r0 is used for stack alignment)
- stmdb sp!, {r0-r3} ; save argument regs
-
- ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] ; load cif
- ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] ; load fun
- ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] ; load user_data
-
- ALTERNATE_ENTRY ffi_go_closure_VFP_0
- add ip, sp, #16 ; compute entry sp
- sub sp, sp, #32 ; save space for closure_frame->result
- vstmdb sp!, {d0-d7} ; push closure_frame->vfp_space
-
- mov r3, sp ; save closure_frame
- stmdb sp!, {ip,lr}
-
- bl ffi_closure_inner_VFP
-
- ; Load values returned in registers.
- add r2, sp, #64+8 ; load result
- bl ffi_closure_ret
- ldmfd sp!, {ip,lr}
- mov sp, ip ; restore stack pointer
- mov pc, lr
- NESTED_END ffi_closure_VFP_fake
-
-/* Load values returned in registers for both closure entry points.
- Note that we use LDM with SP in the register set. This is deprecated
- by ARM, but not yet unpredictable. */
-
- NESTED_ENTRY_FFI ffi_closure_ret
- stmdb sp!, {fp,lr}
-
- ALIGN 8
- lsl r0, #3
- add r0, r0, pc
- add r0, #8
- mov pc, r0
-
-E(ARM_TYPE_VFP_S, ffi_closure)
- ALIGN 8
- vldr s0, [r2]
- b call_epilogue
-E(ARM_TYPE_VFP_D, ffi_closure)
- ALIGN 8
- vldr d0, [r2]
- b call_epilogue
-E(ARM_TYPE_VFP_N, ffi_closure)
- ALIGN 8
- vldm r2, {d0-d3}
- b call_epilogue
-E(ARM_TYPE_INT64, ffi_closure)
- ALIGN 8
- ldr r1, [r2, #4]
- nop
-E(ARM_TYPE_INT, ffi_closure)
- ALIGN 8
- ldr r0, [r2]
- b call_epilogue
-E(ARM_TYPE_VOID, ffi_closure)
- ALIGN 8
- b call_epilogue
- nop
-E(ARM_TYPE_STRUCT, ffi_closure)
- ALIGN 8
- b call_epilogue
-call_epilogue
- ldmfd sp!, {fp,pc}
- NESTED_END ffi_closure_ret
-
- AREA |.trampoline|, DATA, THUMB, READONLY
- EXPORT |ffi_arm_trampoline|
-|ffi_arm_trampoline| DATA
-thisproc adr ip, thisproc
- stmdb sp!, {ip, r0}
- ldr pc, [pc, #0]
- DCD 0
- ;ENDP
-
- END \ No newline at end of file
+/* -----------------------------------------------------------------------
+ sysv.S - Copyright (c) 1998, 2008, 2011 Red Hat, Inc.
+ Copyright (c) 2011 Plausible Labs Cooperative, Inc.
+ Copyright (c) 2019 Microsoft Corporation.
+
+ ARM Foreign Function Interface
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#define LIBFFI_ASM
+#include <fficonfig.h>
+#include <ffi.h>
+#include <ffi_cfi.h>
+#include "internal.h"
+#include "ksarm.h"
+
+
+ ; 8 byte aligned AREA to support 8 byte aligned jump tables
+ MACRO
+ NESTED_ENTRY_FFI $FuncName, $AreaName, $ExceptHandler
+
+ ; compute the function's labels
+ __DeriveFunctionLabels $FuncName
+
+ ; determine the area we will put the function into
+__FuncArea SETS "|.text|"
+ IF "$AreaName" != ""
+__FuncArea SETS "$AreaName"
+ ENDIF
+
+ ; set up the exception handler itself
+__FuncExceptionHandler SETS ""
+ IF "$ExceptHandler" != ""
+__FuncExceptionHandler SETS "|$ExceptHandler|"
+ ENDIF
+
+ ; switch to the specified area, jump tables require 8 byte alignment
+ AREA $__FuncArea,CODE,CODEALIGN,ALIGN=3,READONLY
+
+ ; export the function name
+ __ExportProc $FuncName
+
+ ; flush any pending literal pool stuff
+ ROUT
+
+ ; reset the state of the unwind code tracking
+ __ResetUnwindState
+
+ MEND
+
+; MACRO
+; TABLE_ENTRY $Type, $Table
+;$Type_$Table
+; MEND
+
+#define E(index,table) return_##index##_##table
+
+ ; r0: stack
+ ; r1: frame
+ ; r2: fn
+ ; r3: vfp_used
+
+ ; fake entry point exists only to generate exists only to
+ ; generate .pdata for exception unwinding
+ NESTED_ENTRY_FFI ffi_call_VFP_fake
+ PROLOG_PUSH {r11, lr} ; save fp and lr for unwind
+
+ ALTERNATE_ENTRY ffi_call_VFP
+ cmp r3, #3 ; load only d0 if possible
+ vldrle d0, [r0]
+ vldmgt r0, {d0-d7}
+ add r0, r0, #64 ; discard the vfp register args
+ b ffi_call_SYSV
+ NESTED_END ffi_call_VFP_fake
+
+ ; fake entry point exists only to generate exists only to
+ ; generate .pdata for exception unwinding
+ NESTED_ENTRY_FFI ffi_call_SYSV_fake
+ PROLOG_PUSH {r11, lr} ; save fp and lr for unwind
+
+ ALTERNATE_ENTRY ffi_call_SYSV
+ stm r1, {fp, lr}
+ mov fp, r1
+
+ mov sp, r0 ; install the stack pointer
+ mov lr, r2 ; move the fn pointer out of the way
+ ldr ip, [fp, #16] ; install the static chain
+ ldmia sp!, {r0-r3} ; move first 4 parameters in registers.
+ blx lr ; call fn
+
+ ; Load r2 with the pointer to storage for the return value
+ ; Load r3 with the return type code
+ ldr r2, [fp, #8]
+ ldr r3, [fp, #12]
+
+ ; Deallocate the stack with the arguments.
+ mov sp, fp
+
+ ; Store values stored in registers.
+ ALIGN 8
+ lsl r3, #3
+ add r3, r3, pc
+ add r3, #8
+ mov pc, r3
+
+
+E(ARM_TYPE_VFP_S, ffi_call)
+ ALIGN 8
+ vstr s0, [r2]
+ pop {fp,pc}
+E(ARM_TYPE_VFP_D, ffi_call)
+ ALIGN 8
+ vstr d0, [r2]
+ pop {fp,pc}
+E(ARM_TYPE_VFP_N, ffi_call)
+ ALIGN 8
+ vstm r2, {d0-d3}
+ pop {fp,pc}
+E(ARM_TYPE_INT64, ffi_call)
+ ALIGN 8
+ str r1, [r2, #4]
+ nop
+E(ARM_TYPE_INT, ffi_call)
+ ALIGN 8
+ str r0, [r2]
+ pop {fp,pc}
+E(ARM_TYPE_VOID, ffi_call)
+ ALIGN 8
+ pop {fp,pc}
+ nop
+E(ARM_TYPE_STRUCT, ffi_call)
+ ALIGN 8
+ cmp r3, #ARM_TYPE_STRUCT
+ pop {fp,pc}
+ NESTED_END ffi_call_SYSV_fake
+
+ IMPORT |ffi_closure_inner_SYSV|
+ /*
+ int ffi_closure_inner_SYSV
+ (
+ cif, ; r0
+ fun, ; r1
+ user_data, ; r2
+ frame ; r3
+ )
+ */
+
+ NESTED_ENTRY_FFI ffi_go_closure_SYSV
+ stmdb sp!, {r0-r3} ; save argument regs
+ ldr r0, [ip, #4] ; load cif
+ ldr r1, [ip, #8] ; load fun
+ mov r2, ip ; load user_data
+ b ffi_go_closure_SYSV_0
+ NESTED_END ffi_go_closure_SYSV
+
+ ; r3: ffi_closure
+
+ ; fake entry point exists only to generate exists only to
+ ; generate .pdata for exception unwinding
+ NESTED_ENTRY_FFI ffi_closure_SYSV_fake
+ PROLOG_PUSH {r11, lr} ; save fp and lr for unwind
+ ALTERNATE_ENTRY ffi_closure_SYSV
+ ldmfd sp!, {ip,r0} ; restore fp (r0 is used for stack alignment)
+ stmdb sp!, {r0-r3} ; save argument regs
+
+ ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] ; ffi_closure->cif
+ ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] ; ffi_closure->fun
+ ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] ; ffi_closure->user_data
+
+ ALTERNATE_ENTRY ffi_go_closure_SYSV_0
+ add ip, sp, #16 ; compute entry sp
+
+ sub sp, sp, #64+32 ; allocate frame parameter (sizeof(vfp_space) = 64, sizeof(result) = 32)
+ mov r3, sp ; set frame parameter
+ stmdb sp!, {ip,lr}
+
+ bl ffi_closure_inner_SYSV ; call the Python closure
+
+ ; Load values returned in registers.
+ add r2, sp, #64+8 ; address of closure_frame->result
+ bl ffi_closure_ret ; move result to correct register or memory for type
+
+ ldmfd sp!, {ip,lr}
+ mov sp, ip ; restore stack pointer
+ mov pc, lr
+ NESTED_END ffi_closure_SYSV_fake
+
+ IMPORT |ffi_closure_inner_VFP|
+ /*
+ int ffi_closure_inner_VFP
+ (
+ cif, ; r0
+ fun, ; r1
+ user_data, ; r2
+ frame ; r3
+ )
+ */
+
+ NESTED_ENTRY_FFI ffi_go_closure_VFP
+ stmdb sp!, {r0-r3} ; save argument regs
+ ldr r0, [ip, #4] ; load cif
+ ldr r1, [ip, #8] ; load fun
+ mov r2, ip ; load user_data
+ b ffi_go_closure_VFP_0
+ NESTED_END ffi_go_closure_VFP
+
+ ; fake entry point exists only to generate exists only to
+ ; generate .pdata for exception unwinding
+ ; r3: closure
+ NESTED_ENTRY_FFI ffi_closure_VFP_fake
+ PROLOG_PUSH {r11, lr} ; save fp and lr for unwind
+
+ ALTERNATE_ENTRY ffi_closure_VFP
+ ldmfd sp!, {ip,r0} ; restore fp (r0 is used for stack alignment)
+ stmdb sp!, {r0-r3} ; save argument regs
+
+ ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] ; load cif
+ ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] ; load fun
+ ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] ; load user_data
+
+ ALTERNATE_ENTRY ffi_go_closure_VFP_0
+ add ip, sp, #16 ; compute entry sp
+ sub sp, sp, #32 ; save space for closure_frame->result
+ vstmdb sp!, {d0-d7} ; push closure_frame->vfp_space
+
+ mov r3, sp ; save closure_frame
+ stmdb sp!, {ip,lr}
+
+ bl ffi_closure_inner_VFP
+
+ ; Load values returned in registers.
+ add r2, sp, #64+8 ; load result
+ bl ffi_closure_ret
+ ldmfd sp!, {ip,lr}
+ mov sp, ip ; restore stack pointer
+ mov pc, lr
+ NESTED_END ffi_closure_VFP_fake
+
+/* Load values returned in registers for both closure entry points.
+ Note that we use LDM with SP in the register set. This is deprecated
+ by ARM, but not yet unpredictable. */
+
+ NESTED_ENTRY_FFI ffi_closure_ret
+ stmdb sp!, {fp,lr}
+
+ ALIGN 8
+ lsl r0, #3
+ add r0, r0, pc
+ add r0, #8
+ mov pc, r0
+
+E(ARM_TYPE_VFP_S, ffi_closure)
+ ALIGN 8
+ vldr s0, [r2]
+ b call_epilogue
+E(ARM_TYPE_VFP_D, ffi_closure)
+ ALIGN 8
+ vldr d0, [r2]
+ b call_epilogue
+E(ARM_TYPE_VFP_N, ffi_closure)
+ ALIGN 8
+ vldm r2, {d0-d3}
+ b call_epilogue
+E(ARM_TYPE_INT64, ffi_closure)
+ ALIGN 8
+ ldr r1, [r2, #4]
+ nop
+E(ARM_TYPE_INT, ffi_closure)
+ ALIGN 8
+ ldr r0, [r2]
+ b call_epilogue
+E(ARM_TYPE_VOID, ffi_closure)
+ ALIGN 8
+ b call_epilogue
+ nop
+E(ARM_TYPE_STRUCT, ffi_closure)
+ ALIGN 8
+ b call_epilogue
+call_epilogue
+ ldmfd sp!, {fp,pc}
+ NESTED_END ffi_closure_ret
+
+ AREA |.trampoline|, DATA, THUMB, READONLY
+ EXPORT |ffi_arm_trampoline|
+|ffi_arm_trampoline| DATA
+thisproc adr ip, thisproc
+ stmdb sp!, {ip, r0}
+ ldr pc, [pc, #0]
+ DCD 0
+ ;ENDP
+
+ END \ No newline at end of file
diff --git a/contrib/restricted/libffi/src/closures.c b/contrib/restricted/libffi/src/closures.c
index 2c65fa0a6a..5120021652 100644
--- a/contrib/restricted/libffi/src/closures.c
+++ b/contrib/restricted/libffi/src/closures.c
@@ -1,6 +1,6 @@
/* -----------------------------------------------------------------------
- closures.c - Copyright (c) 2019 Anthony Green
- Copyright (c) 2007, 2009, 2010 Red Hat, Inc.
+ closures.c - Copyright (c) 2019 Anthony Green
+ Copyright (c) 2007, 2009, 2010 Red Hat, Inc.
Copyright (C) 2007, 2009, 2010 Free Software Foundation, Inc
Copyright (c) 2011 Plausible Labs Cooperative, Inc.
@@ -31,88 +31,88 @@
#define _GNU_SOURCE 1
#endif
-#include <fficonfig.h>
+#include <fficonfig.h>
#include <ffi.h>
#include <ffi_common.h>
-#ifdef __NetBSD__
-#include <sys/param.h>
-#endif
-
-#if __NetBSD_Version__ - 0 >= 799007200
-/* NetBSD with PROT_MPROTECT */
-#include <sys/mman.h>
-
-#include <stddef.h>
-#include <unistd.h>
-
-static const size_t overhead =
- (sizeof(max_align_t) > sizeof(void *) + sizeof(size_t)) ?
- sizeof(max_align_t)
- : sizeof(void *) + sizeof(size_t);
-
-#define ADD_TO_POINTER(p, d) ((void *)((uintptr_t)(p) + (d)))
-
-void *
-ffi_closure_alloc (size_t size, void **code)
-{
- static size_t page_size;
- size_t rounded_size;
- void *codeseg, *dataseg;
- int prot;
-
- /* Expect that PAX mprotect is active and a separate code mapping is necessary. */
- if (!code)
- return NULL;
-
- /* Obtain system page size. */
- if (!page_size)
- page_size = sysconf(_SC_PAGESIZE);
-
- /* Round allocation size up to the next page, keeping in mind the size field and pointer to code map. */
- rounded_size = (size + overhead + page_size - 1) & ~(page_size - 1);
-
- /* Primary mapping is RW, but request permission to switch to PROT_EXEC later. */
- prot = PROT_READ | PROT_WRITE | PROT_MPROTECT(PROT_EXEC);
- dataseg = mmap(NULL, rounded_size, prot, MAP_ANON | MAP_PRIVATE, -1, 0);
- if (dataseg == MAP_FAILED)
- return NULL;
-
- /* Create secondary mapping and switch it to RX. */
- codeseg = mremap(dataseg, rounded_size, NULL, rounded_size, MAP_REMAPDUP);
- if (codeseg == MAP_FAILED) {
- munmap(dataseg, rounded_size);
- return NULL;
- }
- if (mprotect(codeseg, rounded_size, PROT_READ | PROT_EXEC) == -1) {
- munmap(codeseg, rounded_size);
- munmap(dataseg, rounded_size);
- return NULL;
- }
-
- /* Remember allocation size and location of the secondary mapping for ffi_closure_free. */
- memcpy(dataseg, &rounded_size, sizeof(rounded_size));
- memcpy(ADD_TO_POINTER(dataseg, sizeof(size_t)), &codeseg, sizeof(void *));
- *code = ADD_TO_POINTER(codeseg, overhead);
- return ADD_TO_POINTER(dataseg, overhead);
-}
-
-void
-ffi_closure_free (void *ptr)
-{
- void *codeseg, *dataseg;
- size_t rounded_size;
-
- dataseg = ADD_TO_POINTER(ptr, -overhead);
- memcpy(&rounded_size, dataseg, sizeof(rounded_size));
- memcpy(&codeseg, ADD_TO_POINTER(dataseg, sizeof(size_t)), sizeof(void *));
- munmap(dataseg, rounded_size);
- munmap(codeseg, rounded_size);
-}
-#else /* !NetBSD with PROT_MPROTECT */
-
+#ifdef __NetBSD__
+#include <sys/param.h>
+#endif
+
+#if __NetBSD_Version__ - 0 >= 799007200
+/* NetBSD with PROT_MPROTECT */
+#include <sys/mman.h>
+
+#include <stddef.h>
+#include <unistd.h>
+
+static const size_t overhead =
+ (sizeof(max_align_t) > sizeof(void *) + sizeof(size_t)) ?
+ sizeof(max_align_t)
+ : sizeof(void *) + sizeof(size_t);
+
+#define ADD_TO_POINTER(p, d) ((void *)((uintptr_t)(p) + (d)))
+
+void *
+ffi_closure_alloc (size_t size, void **code)
+{
+ static size_t page_size;
+ size_t rounded_size;
+ void *codeseg, *dataseg;
+ int prot;
+
+ /* Expect that PAX mprotect is active and a separate code mapping is necessary. */
+ if (!code)
+ return NULL;
+
+ /* Obtain system page size. */
+ if (!page_size)
+ page_size = sysconf(_SC_PAGESIZE);
+
+ /* Round allocation size up to the next page, keeping in mind the size field and pointer to code map. */
+ rounded_size = (size + overhead + page_size - 1) & ~(page_size - 1);
+
+ /* Primary mapping is RW, but request permission to switch to PROT_EXEC later. */
+ prot = PROT_READ | PROT_WRITE | PROT_MPROTECT(PROT_EXEC);
+ dataseg = mmap(NULL, rounded_size, prot, MAP_ANON | MAP_PRIVATE, -1, 0);
+ if (dataseg == MAP_FAILED)
+ return NULL;
+
+ /* Create secondary mapping and switch it to RX. */
+ codeseg = mremap(dataseg, rounded_size, NULL, rounded_size, MAP_REMAPDUP);
+ if (codeseg == MAP_FAILED) {
+ munmap(dataseg, rounded_size);
+ return NULL;
+ }
+ if (mprotect(codeseg, rounded_size, PROT_READ | PROT_EXEC) == -1) {
+ munmap(codeseg, rounded_size);
+ munmap(dataseg, rounded_size);
+ return NULL;
+ }
+
+ /* Remember allocation size and location of the secondary mapping for ffi_closure_free. */
+ memcpy(dataseg, &rounded_size, sizeof(rounded_size));
+ memcpy(ADD_TO_POINTER(dataseg, sizeof(size_t)), &codeseg, sizeof(void *));
+ *code = ADD_TO_POINTER(codeseg, overhead);
+ return ADD_TO_POINTER(dataseg, overhead);
+}
+
+void
+ffi_closure_free (void *ptr)
+{
+ void *codeseg, *dataseg;
+ size_t rounded_size;
+
+ dataseg = ADD_TO_POINTER(ptr, -overhead);
+ memcpy(&rounded_size, dataseg, sizeof(rounded_size));
+ memcpy(&codeseg, ADD_TO_POINTER(dataseg, sizeof(size_t)), sizeof(void *));
+ munmap(dataseg, rounded_size);
+ munmap(codeseg, rounded_size);
+}
+#else /* !NetBSD with PROT_MPROTECT */
+
#if !FFI_MMAP_EXEC_WRIT && !FFI_EXEC_TRAMPOLINE_TABLE
-# if __linux__ && !defined(__ANDROID__)
+# if __linux__ && !defined(__ANDROID__)
/* This macro indicates it may be forbidden to map anonymous memory
with both write and execute permission. Code compiled when this
option is defined will attempt to map such pages once, but if it
@@ -123,7 +123,7 @@ ffi_closure_free (void *ptr)
# define FFI_MMAP_EXEC_WRIT 1
# define HAVE_MNTENT 1
# endif
-# if defined(X86_WIN32) || defined(X86_WIN64) || defined(_M_ARM64) || defined(__OS2__)
+# if defined(X86_WIN32) || defined(X86_WIN64) || defined(_M_ARM64) || defined(__OS2__)
/* Windows systems may have Data Execution Protection (DEP) enabled,
which requires the use of VirtualMalloc/VirtualFree to alloc/free
executable memory. */
@@ -132,7 +132,7 @@ ffi_closure_free (void *ptr)
#endif
#if FFI_MMAP_EXEC_WRIT && !defined FFI_MMAP_EXEC_SELINUX
-# if defined(__linux__) && !defined(__ANDROID__)
+# if defined(__linux__) && !defined(__ANDROID__)
/* When defined to 1 check for SELinux and if SELinux is active,
don't attempt PROT_EXEC|PROT_WRITE mapping at all, as that
might cause audit messages. */
@@ -142,216 +142,216 @@ ffi_closure_free (void *ptr)
#if FFI_CLOSURES
-#if FFI_EXEC_TRAMPOLINE_TABLE
-
-#ifdef __MACH__
-
-#include <mach/mach.h>
-#include <pthread.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-extern void *ffi_closure_trampoline_table_page;
-
-typedef struct ffi_trampoline_table ffi_trampoline_table;
-typedef struct ffi_trampoline_table_entry ffi_trampoline_table_entry;
-
-struct ffi_trampoline_table
-{
- /* contiguous writable and executable pages */
- vm_address_t config_page;
- vm_address_t trampoline_page;
-
- /* free list tracking */
- uint16_t free_count;
- ffi_trampoline_table_entry *free_list;
- ffi_trampoline_table_entry *free_list_pool;
-
- ffi_trampoline_table *prev;
- ffi_trampoline_table *next;
-};
-
-struct ffi_trampoline_table_entry
-{
- void *(*trampoline) (void);
- ffi_trampoline_table_entry *next;
-};
-
-/* Total number of trampolines that fit in one trampoline table */
-#define FFI_TRAMPOLINE_COUNT (PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE)
-
-static pthread_mutex_t ffi_trampoline_lock = PTHREAD_MUTEX_INITIALIZER;
-static ffi_trampoline_table *ffi_trampoline_tables = NULL;
-
-static ffi_trampoline_table *
-ffi_trampoline_table_alloc (void)
-{
- ffi_trampoline_table *table;
- vm_address_t config_page;
- vm_address_t trampoline_page;
- vm_address_t trampoline_page_template;
- vm_prot_t cur_prot;
- vm_prot_t max_prot;
- kern_return_t kt;
- uint16_t i;
-
- /* Allocate two pages -- a config page and a placeholder page */
- config_page = 0x0;
- kt = vm_allocate (mach_task_self (), &config_page, PAGE_MAX_SIZE * 2,
- VM_FLAGS_ANYWHERE);
- if (kt != KERN_SUCCESS)
- return NULL;
-
- /* Remap the trampoline table on top of the placeholder page */
- trampoline_page = config_page + PAGE_MAX_SIZE;
- trampoline_page_template = (vm_address_t)&ffi_closure_trampoline_table_page;
-#ifdef __arm__
- /* ffi_closure_trampoline_table_page can be thumb-biased on some ARM archs */
- trampoline_page_template &= ~1UL;
-#endif
- kt = vm_remap (mach_task_self (), &trampoline_page, PAGE_MAX_SIZE, 0x0,
- VM_FLAGS_OVERWRITE, mach_task_self (), trampoline_page_template,
- FALSE, &cur_prot, &max_prot, VM_INHERIT_SHARE);
- if (kt != KERN_SUCCESS)
- {
- vm_deallocate (mach_task_self (), config_page, PAGE_MAX_SIZE * 2);
- return NULL;
- }
-
- /* We have valid trampoline and config pages */
- table = calloc (1, sizeof (ffi_trampoline_table));
- table->free_count = FFI_TRAMPOLINE_COUNT;
- table->config_page = config_page;
- table->trampoline_page = trampoline_page;
-
- /* Create and initialize the free list */
- table->free_list_pool =
- calloc (FFI_TRAMPOLINE_COUNT, sizeof (ffi_trampoline_table_entry));
-
- for (i = 0; i < table->free_count; i++)
- {
- ffi_trampoline_table_entry *entry = &table->free_list_pool[i];
- entry->trampoline =
- (void *) (table->trampoline_page + (i * FFI_TRAMPOLINE_SIZE));
-
- if (i < table->free_count - 1)
- entry->next = &table->free_list_pool[i + 1];
- }
-
- table->free_list = table->free_list_pool;
-
- return table;
-}
-
-static void
-ffi_trampoline_table_free (ffi_trampoline_table *table)
-{
- /* Remove from the list */
- if (table->prev != NULL)
- table->prev->next = table->next;
-
- if (table->next != NULL)
- table->next->prev = table->prev;
-
- /* Deallocate pages */
- vm_deallocate (mach_task_self (), table->config_page, PAGE_MAX_SIZE * 2);
-
- /* Deallocate free list */
- free (table->free_list_pool);
- free (table);
-}
-
-void *
-ffi_closure_alloc (size_t size, void **code)
-{
- /* Create the closure */
- ffi_closure *closure = malloc (size);
- if (closure == NULL)
- return NULL;
-
- pthread_mutex_lock (&ffi_trampoline_lock);
-
- /* Check for an active trampoline table with available entries. */
- ffi_trampoline_table *table = ffi_trampoline_tables;
- if (table == NULL || table->free_list == NULL)
- {
- table = ffi_trampoline_table_alloc ();
- if (table == NULL)
- {
- pthread_mutex_unlock (&ffi_trampoline_lock);
- free (closure);
- return NULL;
- }
-
- /* Insert the new table at the top of the list */
- table->next = ffi_trampoline_tables;
- if (table->next != NULL)
- table->next->prev = table;
-
- ffi_trampoline_tables = table;
- }
-
- /* Claim the free entry */
- ffi_trampoline_table_entry *entry = ffi_trampoline_tables->free_list;
- ffi_trampoline_tables->free_list = entry->next;
- ffi_trampoline_tables->free_count--;
- entry->next = NULL;
-
- pthread_mutex_unlock (&ffi_trampoline_lock);
-
- /* Initialize the return values */
- *code = entry->trampoline;
- closure->trampoline_table = table;
- closure->trampoline_table_entry = entry;
-
- return closure;
-}
-
-void
-ffi_closure_free (void *ptr)
-{
- ffi_closure *closure = ptr;
-
- pthread_mutex_lock (&ffi_trampoline_lock);
-
- /* Fetch the table and entry references */
- ffi_trampoline_table *table = closure->trampoline_table;
- ffi_trampoline_table_entry *entry = closure->trampoline_table_entry;
-
- /* Return the entry to the free list */
- entry->next = table->free_list;
- table->free_list = entry;
- table->free_count++;
-
- /* If all trampolines within this table are free, and at least one other table exists, deallocate
- * the table */
- if (table->free_count == FFI_TRAMPOLINE_COUNT
- && ffi_trampoline_tables != table)
- {
- ffi_trampoline_table_free (table);
- }
- else if (ffi_trampoline_tables != table)
- {
- /* Otherwise, bump this table to the top of the list */
- table->prev = NULL;
- table->next = ffi_trampoline_tables;
- if (ffi_trampoline_tables != NULL)
- ffi_trampoline_tables->prev = table;
-
- ffi_trampoline_tables = table;
- }
-
- pthread_mutex_unlock (&ffi_trampoline_lock);
-
- /* Free the closure */
- free (closure);
-}
-
-#endif
-
+#if FFI_EXEC_TRAMPOLINE_TABLE
+
+#ifdef __MACH__
+
+#include <mach/mach.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+extern void *ffi_closure_trampoline_table_page;
+
+typedef struct ffi_trampoline_table ffi_trampoline_table;
+typedef struct ffi_trampoline_table_entry ffi_trampoline_table_entry;
+
+struct ffi_trampoline_table
+{
+ /* contiguous writable and executable pages */
+ vm_address_t config_page;
+ vm_address_t trampoline_page;
+
+ /* free list tracking */
+ uint16_t free_count;
+ ffi_trampoline_table_entry *free_list;
+ ffi_trampoline_table_entry *free_list_pool;
+
+ ffi_trampoline_table *prev;
+ ffi_trampoline_table *next;
+};
+
+struct ffi_trampoline_table_entry
+{
+ void *(*trampoline) (void);
+ ffi_trampoline_table_entry *next;
+};
+
+/* Total number of trampolines that fit in one trampoline table */
+#define FFI_TRAMPOLINE_COUNT (PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE)
+
+static pthread_mutex_t ffi_trampoline_lock = PTHREAD_MUTEX_INITIALIZER;
+static ffi_trampoline_table *ffi_trampoline_tables = NULL;
+
+static ffi_trampoline_table *
+ffi_trampoline_table_alloc (void)
+{
+ ffi_trampoline_table *table;
+ vm_address_t config_page;
+ vm_address_t trampoline_page;
+ vm_address_t trampoline_page_template;
+ vm_prot_t cur_prot;
+ vm_prot_t max_prot;
+ kern_return_t kt;
+ uint16_t i;
+
+ /* Allocate two pages -- a config page and a placeholder page */
+ config_page = 0x0;
+ kt = vm_allocate (mach_task_self (), &config_page, PAGE_MAX_SIZE * 2,
+ VM_FLAGS_ANYWHERE);
+ if (kt != KERN_SUCCESS)
+ return NULL;
+
+ /* Remap the trampoline table on top of the placeholder page */
+ trampoline_page = config_page + PAGE_MAX_SIZE;
+ trampoline_page_template = (vm_address_t)&ffi_closure_trampoline_table_page;
+#ifdef __arm__
+ /* ffi_closure_trampoline_table_page can be thumb-biased on some ARM archs */
+ trampoline_page_template &= ~1UL;
+#endif
+ kt = vm_remap (mach_task_self (), &trampoline_page, PAGE_MAX_SIZE, 0x0,
+ VM_FLAGS_OVERWRITE, mach_task_self (), trampoline_page_template,
+ FALSE, &cur_prot, &max_prot, VM_INHERIT_SHARE);
+ if (kt != KERN_SUCCESS)
+ {
+ vm_deallocate (mach_task_self (), config_page, PAGE_MAX_SIZE * 2);
+ return NULL;
+ }
+
+ /* We have valid trampoline and config pages */
+ table = calloc (1, sizeof (ffi_trampoline_table));
+ table->free_count = FFI_TRAMPOLINE_COUNT;
+ table->config_page = config_page;
+ table->trampoline_page = trampoline_page;
+
+ /* Create and initialize the free list */
+ table->free_list_pool =
+ calloc (FFI_TRAMPOLINE_COUNT, sizeof (ffi_trampoline_table_entry));
+
+ for (i = 0; i < table->free_count; i++)
+ {
+ ffi_trampoline_table_entry *entry = &table->free_list_pool[i];
+ entry->trampoline =
+ (void *) (table->trampoline_page + (i * FFI_TRAMPOLINE_SIZE));
+
+ if (i < table->free_count - 1)
+ entry->next = &table->free_list_pool[i + 1];
+ }
+
+ table->free_list = table->free_list_pool;
+
+ return table;
+}
+
+static void
+ffi_trampoline_table_free (ffi_trampoline_table *table)
+{
+ /* Remove from the list */
+ if (table->prev != NULL)
+ table->prev->next = table->next;
+
+ if (table->next != NULL)
+ table->next->prev = table->prev;
+
+ /* Deallocate pages */
+ vm_deallocate (mach_task_self (), table->config_page, PAGE_MAX_SIZE * 2);
+
+ /* Deallocate free list */
+ free (table->free_list_pool);
+ free (table);
+}
+
+void *
+ffi_closure_alloc (size_t size, void **code)
+{
+ /* Create the closure */
+ ffi_closure *closure = malloc (size);
+ if (closure == NULL)
+ return NULL;
+
+ pthread_mutex_lock (&ffi_trampoline_lock);
+
+ /* Check for an active trampoline table with available entries. */
+ ffi_trampoline_table *table = ffi_trampoline_tables;
+ if (table == NULL || table->free_list == NULL)
+ {
+ table = ffi_trampoline_table_alloc ();
+ if (table == NULL)
+ {
+ pthread_mutex_unlock (&ffi_trampoline_lock);
+ free (closure);
+ return NULL;
+ }
+
+ /* Insert the new table at the top of the list */
+ table->next = ffi_trampoline_tables;
+ if (table->next != NULL)
+ table->next->prev = table;
+
+ ffi_trampoline_tables = table;
+ }
+
+ /* Claim the free entry */
+ ffi_trampoline_table_entry *entry = ffi_trampoline_tables->free_list;
+ ffi_trampoline_tables->free_list = entry->next;
+ ffi_trampoline_tables->free_count--;
+ entry->next = NULL;
+
+ pthread_mutex_unlock (&ffi_trampoline_lock);
+
+ /* Initialize the return values */
+ *code = entry->trampoline;
+ closure->trampoline_table = table;
+ closure->trampoline_table_entry = entry;
+
+ return closure;
+}
+
+void
+ffi_closure_free (void *ptr)
+{
+ ffi_closure *closure = ptr;
+
+ pthread_mutex_lock (&ffi_trampoline_lock);
+
+ /* Fetch the table and entry references */
+ ffi_trampoline_table *table = closure->trampoline_table;
+ ffi_trampoline_table_entry *entry = closure->trampoline_table_entry;
+
+ /* Return the entry to the free list */
+ entry->next = table->free_list;
+ table->free_list = entry;
+ table->free_count++;
+
+ /* If all trampolines within this table are free, and at least one other table exists, deallocate
+ * the table */
+ if (table->free_count == FFI_TRAMPOLINE_COUNT
+ && ffi_trampoline_tables != table)
+ {
+ ffi_trampoline_table_free (table);
+ }
+ else if (ffi_trampoline_tables != table)
+ {
+ /* Otherwise, bump this table to the top of the list */
+ table->prev = NULL;
+ table->next = ffi_trampoline_tables;
+ if (ffi_trampoline_tables != NULL)
+ ffi_trampoline_tables->prev = table;
+
+ ffi_trampoline_tables = table;
+ }
+
+ pthread_mutex_unlock (&ffi_trampoline_lock);
+
+ /* Free the closure */
+ free (closure);
+}
+
+#endif
+
// Per-target implementation; It's unclear what can reasonable be shared between two OS/architecture implementations.
-#elif FFI_MMAP_EXEC_WRIT /* !FFI_EXEC_TRAMPOLINE_TABLE */
+#elif FFI_MMAP_EXEC_WRIT /* !FFI_EXEC_TRAMPOLINE_TABLE */
#define USE_LOCKS 1
#define USE_DL_PREFIX 1
@@ -386,7 +386,7 @@ ffi_closure_free (void *ptr)
#endif
#include <string.h>
#include <stdio.h>
-#if !defined(X86_WIN32) && !defined(X86_WIN64) && !defined(_M_ARM64)
+#if !defined(X86_WIN32) && !defined(X86_WIN64) && !defined(_M_ARM64)
#ifdef HAVE_MNTENT
#include <mntent.h>
#endif /* HAVE_MNTENT */
@@ -456,26 +456,26 @@ static int emutramp_enabled = -1;
static int
emutramp_enabled_check (void)
{
- char *buf = NULL;
- size_t len = 0;
- FILE *f;
- int ret;
- f = fopen ("/proc/self/status", "r");
- if (f == NULL)
+ char *buf = NULL;
+ size_t len = 0;
+ FILE *f;
+ int ret;
+ f = fopen ("/proc/self/status", "r");
+ if (f == NULL)
return 0;
- ret = 0;
-
- while (getline (&buf, &len, f) != -1)
- if (!strncmp (buf, "PaX:", 4))
- {
- char emutramp;
- if (sscanf (buf, "%*s %*c%c", &emutramp) == 1)
- ret = (emutramp == 'E');
- break;
- }
- free (buf);
- fclose (f);
- return ret;
+ ret = 0;
+
+ while (getline (&buf, &len, f) != -1)
+ if (!strncmp (buf, "PaX:", 4))
+ {
+ char emutramp;
+ if (sscanf (buf, "%*s %*c%c", &emutramp) == 1)
+ ret = (emutramp == 'E');
+ break;
+ }
+ free (buf);
+ fclose (f);
+ return ret;
}
#define is_emutramp_enabled() (emutramp_enabled >= 0 ? emutramp_enabled \
@@ -512,7 +512,7 @@ static int dlmalloc_trim(size_t) MAYBE_UNUSED;
static size_t dlmalloc_usable_size(void*) MAYBE_UNUSED;
static void dlmalloc_stats(void) MAYBE_UNUSED;
-#if !(defined(X86_WIN32) || defined(X86_WIN64) || defined(_M_ARM64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX)
+#if !(defined(X86_WIN32) || defined(X86_WIN64) || defined(_M_ARM64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX)
/* Use these for mmap and munmap within dlmalloc.c. */
static void *dlmmap(void *, size_t, int, int, int, off_t);
static int dlmunmap(void *, size_t);
@@ -526,7 +526,7 @@ static int dlmunmap(void *, size_t);
#undef mmap
#undef munmap
-#if !(defined(X86_WIN32) || defined(X86_WIN64) || defined(_M_ARM64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX)
+#if !(defined(X86_WIN32) || defined(X86_WIN64) || defined(_M_ARM64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX)
/* A mutex used to synchronize access to *exec* variables in this file. */
static pthread_mutex_t open_temp_exec_file_mutex = PTHREAD_MUTEX_INITIALIZER;
@@ -540,16 +540,16 @@ static size_t execsize = 0;
/* Open a temporary file name, and immediately unlink it. */
static int
-open_temp_exec_file_name (char *name, int flags)
+open_temp_exec_file_name (char *name, int flags)
{
- int fd;
-
-#ifdef HAVE_MKOSTEMP
- fd = mkostemp (name, flags);
-#else
- fd = mkstemp (name);
-#endif
-
+ int fd;
+
+#ifdef HAVE_MKOSTEMP
+ fd = mkostemp (name, flags);
+#else
+ fd = mkstemp (name);
+#endif
+
if (fd != -1)
unlink (name);
@@ -561,38 +561,38 @@ static int
open_temp_exec_file_dir (const char *dir)
{
static const char suffix[] = "/ffiXXXXXX";
- int lendir, flags;
- char *tempname;
-#ifdef O_TMPFILE
- int fd;
-#endif
-
-#ifdef O_CLOEXEC
- flags = O_CLOEXEC;
-#else
- flags = 0;
-#endif
-
-#ifdef O_TMPFILE
- fd = open (dir, flags | O_RDWR | O_EXCL | O_TMPFILE, 0700);
- /* If the running system does not support the O_TMPFILE flag then retry without it. */
- if (fd != -1 || (errno != EINVAL && errno != EISDIR && errno != EOPNOTSUPP)) {
- return fd;
- } else {
- errno = 0;
- }
-#endif
-
- lendir = (int) strlen (dir);
- tempname = __builtin_alloca (lendir + sizeof (suffix));
-
+ int lendir, flags;
+ char *tempname;
+#ifdef O_TMPFILE
+ int fd;
+#endif
+
+#ifdef O_CLOEXEC
+ flags = O_CLOEXEC;
+#else
+ flags = 0;
+#endif
+
+#ifdef O_TMPFILE
+ fd = open (dir, flags | O_RDWR | O_EXCL | O_TMPFILE, 0700);
+ /* If the running system does not support the O_TMPFILE flag then retry without it. */
+ if (fd != -1 || (errno != EINVAL && errno != EISDIR && errno != EOPNOTSUPP)) {
+ return fd;
+ } else {
+ errno = 0;
+ }
+#endif
+
+ lendir = (int) strlen (dir);
+ tempname = __builtin_alloca (lendir + sizeof (suffix));
+
if (!tempname)
return -1;
memcpy (tempname, dir, lendir);
memcpy (tempname + lendir, suffix, sizeof (suffix));
- return open_temp_exec_file_name (tempname, flags);
+ return open_temp_exec_file_name (tempname, flags);
}
/* Open a temporary file in the directory in the named environment
@@ -701,7 +701,7 @@ open_temp_exec_file_opts_next (void)
}
/* Return a file descriptor of a temporary zero-sized file in a
- writable and executable filesystem. */
+ writable and executable filesystem. */
static int
open_temp_exec_file (void)
{
@@ -724,36 +724,36 @@ open_temp_exec_file (void)
return fd;
}
-/* We need to allocate space in a file that will be backing a writable
- mapping. Several problems exist with the usual approaches:
- - fallocate() is Linux-only
- - posix_fallocate() is not available on all platforms
- - ftruncate() does not allocate space on filesystems with sparse files
- Failure to allocate the space will cause SIGBUS to be thrown when
- the mapping is subsequently written to. */
-static int
-allocate_space (int fd, off_t offset, off_t len)
-{
- static size_t page_size;
-
- /* Obtain system page size. */
- if (!page_size)
- page_size = sysconf(_SC_PAGESIZE);
-
- unsigned char buf[page_size];
- memset (buf, 0, page_size);
-
- while (len > 0)
- {
- off_t to_write = (len < page_size) ? len : page_size;
- if (write (fd, buf, to_write) < to_write)
- return -1;
- len -= to_write;
- }
-
- return 0;
-}
-
+/* We need to allocate space in a file that will be backing a writable
+ mapping. Several problems exist with the usual approaches:
+ - fallocate() is Linux-only
+ - posix_fallocate() is not available on all platforms
+ - ftruncate() does not allocate space on filesystems with sparse files
+ Failure to allocate the space will cause SIGBUS to be thrown when
+ the mapping is subsequently written to. */
+static int
+allocate_space (int fd, off_t offset, off_t len)
+{
+ static size_t page_size;
+
+ /* Obtain system page size. */
+ if (!page_size)
+ page_size = sysconf(_SC_PAGESIZE);
+
+ unsigned char buf[page_size];
+ memset (buf, 0, page_size);
+
+ while (len > 0)
+ {
+ off_t to_write = (len < page_size) ? len : page_size;
+ if (write (fd, buf, to_write) < to_write)
+ return -1;
+ len -= to_write;
+ }
+
+ return 0;
+}
+
/* Map in a chunk of memory from the temporary exec file into separate
locations in the virtual memory address space, one writable and one
executable. Returns the address of the writable portion, after
@@ -775,7 +775,7 @@ dlmmap_locked (void *start, size_t length, int prot, int flags, off_t offset)
offset = execsize;
- if (allocate_space (execfd, offset, length))
+ if (allocate_space (execfd, offset, length))
return MFAIL;
flags &= ~(MAP_PRIVATE | MAP_ANONYMOUS);
@@ -790,13 +790,13 @@ dlmmap_locked (void *start, size_t length, int prot, int flags, off_t offset)
close (execfd);
goto retry_open;
}
- if (ftruncate (execfd, offset) != 0)
- {
- /* Fixme : Error logs can be added here. Returning an error for
- * ftruncte() will not add any advantage as it is being
- * validating in the error case. */
- }
-
+ if (ftruncate (execfd, offset) != 0)
+ {
+ /* Fixme : Error logs can be added here. Returning an error for
+ * ftruncte() will not add any advantage as it is being
+ * validating in the error case. */
+ }
+
return MFAIL;
}
else if (!offset
@@ -808,12 +808,12 @@ dlmmap_locked (void *start, size_t length, int prot, int flags, off_t offset)
if (start == MFAIL)
{
munmap (ptr, length);
- if (ftruncate (execfd, offset) != 0)
- {
- /* Fixme : Error logs can be added here. Returning an error for
- * ftruncte() will not add any advantage as it is being
- * validating in the error case. */
- }
+ if (ftruncate (execfd, offset) != 0)
+ {
+ /* Fixme : Error logs can be added here. Returning an error for
+ * ftruncte() will not add any advantage as it is being
+ * validating in the error case. */
+ }
return start;
}
@@ -908,7 +908,7 @@ segment_holding_code (mstate m, char* addr)
}
#endif
-#endif /* !(defined(X86_WIN32) || defined(X86_WIN64) || defined(_M_ARM64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) */
+#endif /* !(defined(X86_WIN32) || defined(X86_WIN64) || defined(_M_ARM64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) */
/* Allocate a chunk of memory with the given size. Returns a pointer
to the writable address, and sets *CODE to the executable
@@ -933,20 +933,20 @@ ffi_closure_alloc (size_t size, void **code)
return ptr;
}
-void *
-ffi_data_to_code_pointer (void *data)
-{
- msegmentptr seg = segment_holding (gm, data);
- /* We expect closures to be allocated with ffi_closure_alloc(), in
- which case seg will be non-NULL. However, some users take on the
- burden of managing this memory themselves, in which case this
- we'll just return data. */
- if (seg)
- return add_segment_exec_offset (data, seg);
- else
- return data;
-}
-
+void *
+ffi_data_to_code_pointer (void *data)
+{
+ msegmentptr seg = segment_holding (gm, data);
+ /* We expect closures to be allocated with ffi_closure_alloc(), in
+ which case seg will be non-NULL. However, some users take on the
+ burden of managing this memory themselves, in which case this
+ we'll just return data. */
+ if (seg)
+ return add_segment_exec_offset (data, seg);
+ else
+ return data;
+}
+
/* Release a chunk of memory allocated with ffi_closure_alloc. If
FFI_CLOSURE_FREE_CODE is nonzero, the given address can be the
writable or the executable address given. Otherwise, only the
@@ -986,13 +986,13 @@ ffi_closure_free (void *ptr)
free (ptr);
}
-void *
-ffi_data_to_code_pointer (void *data)
-{
- return data;
-}
-
+void *
+ffi_data_to_code_pointer (void *data)
+{
+ return data;
+}
+
# endif /* ! FFI_MMAP_EXEC_WRIT */
#endif /* FFI_CLOSURES */
-
-#endif /* NetBSD with PROT_MPROTECT */
+
+#endif /* NetBSD with PROT_MPROTECT */
diff --git a/contrib/restricted/libffi/src/dlmalloc.c b/contrib/restricted/libffi/src/dlmalloc.c
index c859e4373a..ec85fcec2a 100644
--- a/contrib/restricted/libffi/src/dlmalloc.c
+++ b/contrib/restricted/libffi/src/dlmalloc.c
@@ -438,11 +438,11 @@ DEFAULT_MMAP_THRESHOLD default: 256K
*/
-#if defined __linux__ && !defined _GNU_SOURCE
-/* mremap() on Linux requires this via sys/mman.h */
-#define _GNU_SOURCE 1
-#endif
-
+#if defined __linux__ && !defined _GNU_SOURCE
+/* mremap() on Linux requires this via sys/mman.h */
+#define _GNU_SOURCE 1
+#endif
+
#ifndef WIN32
#ifdef _WIN32
#define WIN32 1
@@ -1260,7 +1260,7 @@ extern void* sbrk(ptrdiff_t);
#define SIZE_T_BITSIZE (sizeof(size_t) << 3)
/* Some constants coerced to size_t */
-/* Annoying but necessary to avoid errors on some platforms */
+/* Annoying but necessary to avoid errors on some platforms */
#define SIZE_T_ZERO ((size_t)0)
#define SIZE_T_ONE ((size_t)1)
#define SIZE_T_TWO ((size_t)2)
@@ -1414,7 +1414,7 @@ static int win32munmap(void* ptr, size_t size) {
#define CALL_MORECORE(S) MFAIL
#endif /* HAVE_MORECORE */
-/* mstate bit set if contiguous morecore disabled or failed */
+/* mstate bit set if contiguous morecore disabled or failed */
#define USE_NONCONTIGUOUS_BIT (4U)
/* segment bit set in create_mspace_with_base */
@@ -1666,7 +1666,7 @@ struct malloc_chunk {
typedef struct malloc_chunk mchunk;
typedef struct malloc_chunk* mchunkptr;
typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */
-typedef size_t bindex_t; /* Described below */
+typedef size_t bindex_t; /* Described below */
typedef unsigned int binmap_t; /* Described below */
typedef unsigned int flag_t; /* The type of various bit flag sets */
@@ -2296,7 +2296,7 @@ static size_t traverse_and_check(mstate m);
#define treebin_at(M,i) (&((M)->treebins[i]))
/* assign tree index for size S to variable I */
-#if defined(__GNUC__) && defined(__i386__)
+#if defined(__GNUC__) && defined(__i386__)
#define compute_tree_index(S, I)\
{\
size_t X = S >> TREEBIN_SHIFT;\
@@ -2361,7 +2361,7 @@ static size_t traverse_and_check(mstate m);
/* index corresponding to given bit */
-#if defined(__GNUC__) && defined(__i386__)
+#if defined(__GNUC__) && defined(__i386__)
#define compute_bit2idx(X, I)\
{\
unsigned int J;\
@@ -3095,8 +3095,8 @@ static void internal_malloc_stats(mstate m) {
and choose its bk node as its replacement.
2. If x was the last node of its size, but not a leaf node, it must
be replaced with a leaf node (not merely one with an open left or
- right), to make sure that lefts and rights of descendants
- correspond properly to bit masks. We use the rightmost descendant
+ right), to make sure that lefts and rights of descendants
+ correspond properly to bit masks. We use the rightmost descendant
of x. We could use any other leaf, but this is easy to locate and
tends to counteract removal of leftmosts elsewhere, and so keeps
paths shorter than minimally guaranteed. This doesn't loop much
@@ -3393,7 +3393,7 @@ static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {
*ss = m->seg; /* Push current record */
m->seg.base = tbase;
m->seg.size = tsize;
- (void)set_segment_flags(&m->seg, mmapped);
+ (void)set_segment_flags(&m->seg, mmapped);
m->seg.next = ss;
/* Insert trailing fenceposts */
@@ -3553,7 +3553,7 @@ static void* sys_alloc(mstate m, size_t nb) {
if (!is_initialized(m)) { /* first-time initialization */
m->seg.base = m->least_addr = tbase;
m->seg.size = tsize;
- (void)set_segment_flags(&m->seg, mmap_flag);
+ (void)set_segment_flags(&m->seg, mmap_flag);
m->magic = mparams.magic;
init_bins(m);
if (is_global(m))
@@ -5096,10 +5096,10 @@ History:
Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
* Use last_remainder in more cases.
* Pack bins using idea from colin@nyx10.cs.du.edu
- * Use ordered bins instead of best-fit threshold
+ * Use ordered bins instead of best-fit threshold
* Eliminate block-local decls to simplify tracing and debugging.
* Support another case of realloc via move into top
- * Fix error occurring when initial sbrk_base not word-aligned.
+ * Fix error occurring when initial sbrk_base not word-aligned.
* Rely on page size for units instead of SBRK_UNIT to
avoid surprises about sbrk alignment conventions.
* Add mallinfo, mallopt. Thanks to Raymond Nijssen
diff --git a/contrib/restricted/libffi/src/java_raw_api.c b/contrib/restricted/libffi/src/java_raw_api.c
index f56e8cee07..114d3e47fc 100644
--- a/contrib/restricted/libffi/src/java_raw_api.c
+++ b/contrib/restricted/libffi/src/java_raw_api.c
@@ -39,7 +39,7 @@
#include <ffi_common.h>
#include <stdlib.h>
-#if !defined(NO_JAVA_RAW_API)
+#if !defined(NO_JAVA_RAW_API)
size_t
ffi_java_raw_size (ffi_cif *cif)
@@ -60,9 +60,9 @@ ffi_java_raw_size (ffi_cif *cif)
case FFI_TYPE_STRUCT:
/* No structure parameters in Java. */
abort();
- case FFI_TYPE_COMPLEX:
- /* Not supported yet. */
- abort();
+ case FFI_TYPE_COMPLEX:
+ /* Not supported yet. */
+ abort();
default:
result += FFI_SIZEOF_JAVA_RAW;
}
@@ -107,14 +107,14 @@ ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args)
*args = (void*) &(raw++)->ptr;
break;
- case FFI_TYPE_COMPLEX:
- /* Not supported yet. */
- abort();
-
+ case FFI_TYPE_COMPLEX:
+ /* Not supported yet. */
+ abort();
+
default:
*args = raw;
raw +=
- FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw);
+ FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw);
}
}
@@ -133,16 +133,16 @@ ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args)
*args = (void*) raw;
raw += 2;
break;
- case FFI_TYPE_COMPLEX:
- /* Not supported yet. */
- abort();
+ case FFI_TYPE_COMPLEX:
+ /* Not supported yet. */
+ abort();
default:
*args = (void*) raw++;
}
#else /* FFI_SIZEOF_JAVA_RAW != 8 */
*args = (void*) raw;
raw +=
- FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw);
+ FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw);
#endif /* FFI_SIZEOF_JAVA_RAW == 8 */
}
@@ -234,7 +234,7 @@ ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw)
#else
memcpy ((void*) raw->data, (void*)*args, (*tp)->size);
raw +=
- FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw);
+ FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw);
#endif
}
}
@@ -264,10 +264,10 @@ ffi_java_rvalue_to_raw (ffi_cif *cif, void *rvalue)
*(SINT64 *)rvalue <<= 32;
break;
- case FFI_TYPE_COMPLEX:
- /* Not supported yet. */
- abort();
-
+ case FFI_TYPE_COMPLEX:
+ /* Not supported yet. */
+ abort();
+
default:
break;
}
@@ -293,10 +293,10 @@ ffi_java_raw_to_rvalue (ffi_cif *cif, void *rvalue)
*(SINT64 *)rvalue >>= 32;
break;
- case FFI_TYPE_COMPLEX:
- /* Not supported yet. */
- abort();
-
+ case FFI_TYPE_COMPLEX:
+ /* Not supported yet. */
+ abort();
+
default:
break;
}
@@ -371,4 +371,4 @@ ffi_prep_java_raw_closure (ffi_java_raw_closure* cl,
#endif /* FFI_CLOSURES */
#endif /* !FFI_NATIVE_RAW_API */
-#endif /* !NO_JAVA_RAW_API */
+#endif /* !NO_JAVA_RAW_API */
diff --git a/contrib/restricted/libffi/src/powerpc/aix.S b/contrib/restricted/libffi/src/powerpc/aix.S
index 60544b489d..7ba541595f 100644
--- a/contrib/restricted/libffi/src/powerpc/aix.S
+++ b/contrib/restricted/libffi/src/powerpc/aix.S
@@ -1,566 +1,566 @@
-/* -----------------------------------------------------------------------
- aix.S - Copyright (c) 2002, 2009 Free Software Foundation, Inc.
- based on darwin.S by John Hornkvist
-
- PowerPC Assembly glue.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
- .set r0,0
- .set r1,1
- .set r2,2
- .set r3,3
- .set r4,4
- .set r5,5
- .set r6,6
- .set r7,7
- .set r8,8
- .set r9,9
- .set r10,10
- .set r11,11
- .set r12,12
- .set r13,13
- .set r14,14
- .set r15,15
- .set r16,16
- .set r17,17
- .set r18,18
- .set r19,19
- .set r20,20
- .set r21,21
- .set r22,22
- .set r23,23
- .set r24,24
- .set r25,25
- .set r26,26
- .set r27,27
- .set r28,28
- .set r29,29
- .set r30,30
- .set r31,31
- .set f0,0
- .set f1,1
- .set f2,2
- .set f3,3
- .set f4,4
- .set f5,5
- .set f6,6
- .set f7,7
- .set f8,8
- .set f9,9
- .set f10,10
- .set f11,11
- .set f12,12
- .set f13,13
- .set f14,14
- .set f15,15
- .set f16,16
- .set f17,17
- .set f18,18
- .set f19,19
- .set f20,20
- .set f21,21
-
- .extern .ffi_prep_args
-
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
-#define JUMPTARGET(name) name
-#define L(x) x
- .file "aix.S"
- .toc
-
- /* void ffi_call_AIX(extended_cif *ecif, unsigned long bytes,
- * unsigned int flags, unsigned int *rvalue,
- * void (*fn)(),
- * void (*prep_args)(extended_cif*, unsigned *const));
- * r3=ecif, r4=bytes, r5=flags, r6=rvalue, r7=fn, r8=prep_args
- */
-
-.csect .text[PR]
- .align 2
- .globl ffi_call_AIX
- .globl .ffi_call_AIX
-.csect ffi_call_AIX[DS]
-ffi_call_AIX:
-#ifdef __64BIT__
- .llong .ffi_call_AIX, TOC[tc0], 0
- .csect .text[PR]
-.ffi_call_AIX:
- .function .ffi_call_AIX,.ffi_call_AIX,16,044,LFE..0-LFB..0
- .bf __LINE__
- .line 1
-LFB..0:
- /* Save registers we use. */
- mflr r0
-
- std r28,-32(r1)
- std r29,-24(r1)
- std r30,-16(r1)
- std r31, -8(r1)
-
- std r0, 16(r1)
-LCFI..0:
- mr r28, r1 /* our AP. */
- stdux r1, r1, r4
-LCFI..1:
-
- /* Save arguments over call... */
- mr r31, r5 /* flags, */
- mr r30, r6 /* rvalue, */
- mr r29, r7 /* function address. */
- std r2, 40(r1)
-
- /* Call ffi_prep_args. */
- mr r4, r1
- bl .ffi_prep_args
- nop
-
- /* Now do the call. */
- ld r0, 0(r29)
- ld r2, 8(r29)
- ld r11, 16(r29)
- /* Set up cr1 with bits 4-7 of the flags. */
- mtcrf 0x40, r31
- mtctr r0
- /* Load all those argument registers. */
- /* We have set up a nice stack frame, just load it into registers. */
- ld r3, 40+(1*8)(r1)
- ld r4, 40+(2*8)(r1)
- ld r5, 40+(3*8)(r1)
- ld r6, 40+(4*8)(r1)
- nop
- ld r7, 40+(5*8)(r1)
- ld r8, 40+(6*8)(r1)
- ld r9, 40+(7*8)(r1)
- ld r10,40+(8*8)(r1)
-
-L1:
- /* Load all the FP registers. */
- bf 6,L2 /* 2f + 0x18 */
- lfd f1,-32-(13*8)(r28)
- lfd f2,-32-(12*8)(r28)
- lfd f3,-32-(11*8)(r28)
- lfd f4,-32-(10*8)(r28)
- nop
- lfd f5,-32-(9*8)(r28)
- lfd f6,-32-(8*8)(r28)
- lfd f7,-32-(7*8)(r28)
- lfd f8,-32-(6*8)(r28)
- nop
- lfd f9,-32-(5*8)(r28)
- lfd f10,-32-(4*8)(r28)
- lfd f11,-32-(3*8)(r28)
- lfd f12,-32-(2*8)(r28)
- nop
- lfd f13,-32-(1*8)(r28)
-
-L2:
- /* Make the call. */
- bctrl
- ld r2, 40(r1)
-
- /* Now, deal with the return value. */
- mtcrf 0x01, r31
-
- bt 30, L(done_return_value)
- bt 29, L(fp_return_value)
- std r3, 0(r30)
-
- /* Fall through... */
-
-L(done_return_value):
- /* Restore the registers we used and return. */
- mr r1, r28
- ld r0, 16(r28)
- ld r28, -32(r1)
- mtlr r0
- ld r29, -24(r1)
- ld r30, -16(r1)
- ld r31, -8(r1)
- blr
-
-L(fp_return_value):
- bf 28, L(float_return_value)
- stfd f1, 0(r30)
- bf 31, L(done_return_value)
- stfd f2, 8(r30)
- b L(done_return_value)
-L(float_return_value):
- stfs f1, 0(r30)
- b L(done_return_value)
-LFE..0:
-#else /* ! __64BIT__ */
-
- .long .ffi_call_AIX, TOC[tc0], 0
- .csect .text[PR]
-.ffi_call_AIX:
- .function .ffi_call_AIX,.ffi_call_AIX,16,044,LFE..0-LFB..0
- .bf __LINE__
- .line 1
-LFB..0:
- /* Save registers we use. */
- mflr r0
-
- stw r28,-16(r1)
- stw r29,-12(r1)
- stw r30, -8(r1)
- stw r31, -4(r1)
-
- stw r0, 8(r1)
-LCFI..0:
- mr r28, r1 /* out AP. */
- stwux r1, r1, r4
-LCFI..1:
-
- /* Save arguments over call... */
- mr r31, r5 /* flags, */
- mr r30, r6 /* rvalue, */
- mr r29, r7 /* function address, */
- stw r2, 20(r1)
-
- /* Call ffi_prep_args. */
- mr r4, r1
- bl .ffi_prep_args
- nop
-
- /* Now do the call. */
- lwz r0, 0(r29)
- lwz r2, 4(r29)
- lwz r11, 8(r29)
- /* Set up cr1 with bits 4-7 of the flags. */
- mtcrf 0x40, r31
- mtctr r0
- /* Load all those argument registers. */
- /* We have set up a nice stack frame, just load it into registers. */
- lwz r3, 20+(1*4)(r1)
- lwz r4, 20+(2*4)(r1)
- lwz r5, 20+(3*4)(r1)
- lwz r6, 20+(4*4)(r1)
- nop
- lwz r7, 20+(5*4)(r1)
- lwz r8, 20+(6*4)(r1)
- lwz r9, 20+(7*4)(r1)
- lwz r10,20+(8*4)(r1)
-
-L1:
- /* Load all the FP registers. */
- bf 6,L2 /* 2f + 0x18 */
- lfd f1,-16-(13*8)(r28)
- lfd f2,-16-(12*8)(r28)
- lfd f3,-16-(11*8)(r28)
- lfd f4,-16-(10*8)(r28)
- nop
- lfd f5,-16-(9*8)(r28)
- lfd f6,-16-(8*8)(r28)
- lfd f7,-16-(7*8)(r28)
- lfd f8,-16-(6*8)(r28)
- nop
- lfd f9,-16-(5*8)(r28)
- lfd f10,-16-(4*8)(r28)
- lfd f11,-16-(3*8)(r28)
- lfd f12,-16-(2*8)(r28)
- nop
- lfd f13,-16-(1*8)(r28)
-
-L2:
- /* Make the call. */
- bctrl
- lwz r2, 20(r1)
-
- /* Now, deal with the return value. */
- mtcrf 0x01, r31
-
- bt 30, L(done_return_value)
- bt 29, L(fp_return_value)
- stw r3, 0(r30)
- bf 28, L(done_return_value)
- stw r4, 4(r30)
-
- /* Fall through... */
-
-L(done_return_value):
- /* Restore the registers we used and return. */
- mr r1, r28
- lwz r0, 8(r28)
- lwz r28,-16(r1)
- mtlr r0
- lwz r29,-12(r1)
- lwz r30, -8(r1)
- lwz r31, -4(r1)
- blr
-
-L(fp_return_value):
- bf 28, L(float_return_value)
- stfd f1, 0(r30)
- b L(done_return_value)
-L(float_return_value):
- stfs f1, 0(r30)
- b L(done_return_value)
-LFE..0:
-#endif
- .ef __LINE__
- .long 0
- .byte 0,0,0,1,128,4,0,0
-/* END(ffi_call_AIX) */
-
- /* void ffi_call_go_AIX(extended_cif *ecif, unsigned long bytes,
- * unsigned int flags, unsigned int *rvalue,
- * void (*fn)(),
- * void (*prep_args)(extended_cif*, unsigned *const),
- * void *closure);
- * r3=ecif, r4=bytes, r5=flags, r6=rvalue, r7=fn, r8=prep_args, r9=closure
- */
-
-.csect .text[PR]
- .align 2
- .globl ffi_call_go_AIX
- .globl .ffi_call_go_AIX
-.csect ffi_call_go_AIX[DS]
-ffi_call_go_AIX:
-#ifdef __64BIT__
- .llong .ffi_call_go_AIX, TOC[tc0], 0
- .csect .text[PR]
-.ffi_call_go_AIX:
- .function .ffi_call_go_AIX,.ffi_call_go_AIX,16,044,LFE..1-LFB..1
- .bf __LINE__
- .line 1
-LFB..1:
- /* Save registers we use. */
- mflr r0
-
- std r28,-32(r1)
- std r29,-24(r1)
- std r30,-16(r1)
- std r31, -8(r1)
-
- std r9, 8(r1) /* closure, saved in cr field. */
- std r0, 16(r1)
-LCFI..2:
- mr r28, r1 /* our AP. */
- stdux r1, r1, r4
-LCFI..3:
-
- /* Save arguments over call... */
- mr r31, r5 /* flags, */
- mr r30, r6 /* rvalue, */
- mr r29, r7 /* function address, */
- std r2, 40(r1)
-
- /* Call ffi_prep_args. */
- mr r4, r1
- bl .ffi_prep_args
- nop
-
- /* Now do the call. */
- ld r0, 0(r29)
- ld r2, 8(r29)
- ld r11, 8(r28) /* closure */
- /* Set up cr1 with bits 4-7 of the flags. */
- mtcrf 0x40, r31
- mtctr r0
- /* Load all those argument registers. */
- /* We have set up a nice stack frame, just load it into registers. */
- ld r3, 40+(1*8)(r1)
- ld r4, 40+(2*8)(r1)
- ld r5, 40+(3*8)(r1)
- ld r6, 40+(4*8)(r1)
- nop
- ld r7, 40+(5*8)(r1)
- ld r8, 40+(6*8)(r1)
- ld r9, 40+(7*8)(r1)
- ld r10,40+(8*8)(r1)
-
- b L1
-LFE..1:
-#else /* ! __64BIT__ */
-
- .long .ffi_call_go_AIX, TOC[tc0], 0
- .csect .text[PR]
-.ffi_call_go_AIX:
- .function .ffi_call_go_AIX,.ffi_call_go_AIX,16,044,LFE..1-LFB..1
- .bf __LINE__
- .line 1
- /* Save registers we use. */
-LFB..1:
- mflr r0
-
- stw r28,-16(r1)
- stw r29,-12(r1)
- stw r30, -8(r1)
- stw r31, -4(r1)
-
- stw r9, 4(r1) /* closure, saved in cr field. */
- stw r0, 8(r1)
-LCFI..2:
- mr r28, r1 /* out AP. */
- stwux r1, r1, r4
-LCFI..3:
-
- /* Save arguments over call... */
- mr r31, r5 /* flags, */
- mr r30, r6 /* rvalue, */
- mr r29, r7 /* function address, */
- stw r2, 20(r1)
-
- /* Call ffi_prep_args. */
- mr r4, r1
- bl .ffi_prep_args
- nop
-
- /* Now do the call. */
- lwz r0, 0(r29)
- lwz r2, 4(r29)
- lwz r11, 4(r28) /* closure */
- /* Set up cr1 with bits 4-7 of the flags. */
- mtcrf 0x40, r31
- mtctr r0
- /* Load all those argument registers. */
- /* We have set up a nice stack frame, just load it into registers. */
- lwz r3, 20+(1*4)(r1)
- lwz r4, 20+(2*4)(r1)
- lwz r5, 20+(3*4)(r1)
- lwz r6, 20+(4*4)(r1)
- nop
- lwz r7, 20+(5*4)(r1)
- lwz r8, 20+(6*4)(r1)
- lwz r9, 20+(7*4)(r1)
- lwz r10,20+(8*4)(r1)
-
- b L1
-LFE..1:
-#endif
- .ef __LINE__
- .long 0
- .byte 0,0,0,1,128,4,0,0
-/* END(ffi_call_go_AIX) */
-
-.csect .text[PR]
- .align 2
- .globl ffi_call_DARWIN
- .globl .ffi_call_DARWIN
-.csect ffi_call_DARWIN[DS]
-ffi_call_DARWIN:
-#ifdef __64BIT__
- .llong .ffi_call_DARWIN, TOC[tc0], 0
-#else
- .long .ffi_call_DARWIN, TOC[tc0], 0
-#endif
- .csect .text[PR]
-.ffi_call_DARWIN:
- blr
- .long 0
- .byte 0,0,0,0,0,0,0,0
-/* END(ffi_call_DARWIN) */
-
-/* EH frame stuff. */
-
-#define LR_REGNO 0x41 /* Link Register (65), see rs6000.md */
-#ifdef __64BIT__
-#define PTRSIZE 8
-#define LOG2_PTRSIZE 3
-#define FDE_ENCODING 0x1c /* DW_EH_PE_pcrel|DW_EH_PE_sdata8 */
-#define EH_DATA_ALIGN_FACT 0x78 /* LEB128 -8 */
-#else
-#define PTRSIZE 4
-#define LOG2_PTRSIZE 2
-#define FDE_ENCODING 0x1b /* DW_EH_PE_pcrel|DW_EH_PE_sdata4 */
-#define EH_DATA_ALIGN_FACT 0x7c /* LEB128 -4 */
-#endif
- .csect _unwind.ro_[RO],4
- .align LOG2_PTRSIZE
- .globl _GLOBAL__F_libffi_src_powerpc_aix
-_GLOBAL__F_libffi_src_powerpc_aix:
-Lframe..1:
- .vbyte 4,LECIE..1-LSCIE..1 /* CIE Length */
-LSCIE..1:
- .vbyte 4,0 /* CIE Identifier Tag */
- .byte 0x3 /* CIE Version */
- .byte "zR" /* CIE Augmentation */
- .byte 0
- .byte 0x1 /* uleb128 0x1; CIE Code Alignment Factor */
- .byte EH_DATA_ALIGN_FACT /* leb128 -4/-8; CIE Data Alignment Factor */
- .byte 0x41 /* CIE RA Column */
- .byte 0x1 /* uleb128 0x1; Augmentation size */
- .byte FDE_ENCODING /* FDE Encoding (pcrel|sdata4/8) */
- .byte 0xc /* DW_CFA_def_cfa */
- .byte 0x1 /* uleb128 0x1; Register r1 */
- .byte 0 /* uleb128 0x0; Offset 0 */
- .align LOG2_PTRSIZE
-LECIE..1:
-LSFDE..1:
- .vbyte 4,LEFDE..1-LASFDE..1 /* FDE Length */
-LASFDE..1:
- .vbyte 4,LASFDE..1-Lframe..1 /* FDE CIE offset */
- .vbyte PTRSIZE,LFB..0-$ /* FDE initial location */
- .vbyte PTRSIZE,LFE..0-LFB..0 /* FDE address range */
- .byte 0 /* uleb128 0x0; Augmentation size */
- .byte 0x4 /* DW_CFA_advance_loc4 */
- .vbyte 4,LCFI..0-LFB..0
- .byte 0x11 /* DW_CFA_def_offset_extended_sf */
- .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */
- .byte 0x7e /* leb128 -2; Offset -2 (8/16) */
- .byte 0x9f /* DW_CFA_offset Register r31 */
- .byte 0x1 /* uleb128 0x1; Offset 1 (-4/-8) */
- .byte 0x9e /* DW_CFA_offset Register r30 */
- .byte 0x2 /* uleb128 0x2; Offset 2 (-8/-16) */
- .byte 0x9d /* DW_CFA_offset Register r29 */
- .byte 0x3 /* uleb128 0x3; Offset 3 (-12/-24) */
- .byte 0x9c /* DW_CFA_offset Register r28 */
- .byte 0x4 /* uleb128 0x4; Offset 4 (-16/-32) */
- .byte 0x4 /* DW_CFA_advance_loc4 */
- .vbyte 4,LCFI..1-LCFI..0
- .byte 0xd /* DW_CFA_def_cfa_register */
- .byte 0x1c /* uleb128 28; Register r28 */
- .align LOG2_PTRSIZE
-LEFDE..1:
-LSFDE..2:
- .vbyte 4,LEFDE..2-LASFDE..2 /* FDE Length */
-LASFDE..2:
- .vbyte 4,LASFDE..2-Lframe..1 /* FDE CIE offset */
- .vbyte PTRSIZE,LFB..1-$ /* FDE initial location */
- .vbyte PTRSIZE,LFE..1-LFB..1 /* FDE address range */
- .byte 0 /* uleb128 0x0; Augmentation size */
- .byte 0x4 /* DW_CFA_advance_loc4 */
- .vbyte 4,LCFI..2-LFB..1
- .byte 0x11 /* DW_CFA_def_offset_extended_sf */
- .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */
- .byte 0x7e /* leb128 -2; Offset -2 (8/16) */
- .byte 0x9f /* DW_CFA_offset Register r31 */
- .byte 0x1 /* uleb128 0x1; Offset 1 (-4/-8) */
- .byte 0x9e /* DW_CFA_offset Register r30 */
- .byte 0x2 /* uleb128 0x2; Offset 2 (-8/-16) */
- .byte 0x9d /* DW_CFA_offset Register r29 */
- .byte 0x3 /* uleb128 0x3; Offset 3 (-12/-24) */
- .byte 0x9c /* DW_CFA_offset Register r28 */
- .byte 0x4 /* uleb128 0x4; Offset 4 (-16/-32) */
- .byte 0x4 /* DW_CFA_advance_loc4 */
- .vbyte 4,LCFI..3-LCFI..2
- .byte 0xd /* DW_CFA_def_cfa_register */
- .byte 0x1c /* uleb128 28; Register r28 */
- .align LOG2_PTRSIZE
-LEFDE..2:
- .vbyte 4,0 /* End of FDEs */
-
- .csect .text[PR]
- .ref _GLOBAL__F_libffi_src_powerpc_aix /* Prevents garbage collection by AIX linker */
-
+/* -----------------------------------------------------------------------
+ aix.S - Copyright (c) 2002, 2009 Free Software Foundation, Inc.
+ based on darwin.S by John Hornkvist
+
+ PowerPC Assembly glue.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+ .set r0,0
+ .set r1,1
+ .set r2,2
+ .set r3,3
+ .set r4,4
+ .set r5,5
+ .set r6,6
+ .set r7,7
+ .set r8,8
+ .set r9,9
+ .set r10,10
+ .set r11,11
+ .set r12,12
+ .set r13,13
+ .set r14,14
+ .set r15,15
+ .set r16,16
+ .set r17,17
+ .set r18,18
+ .set r19,19
+ .set r20,20
+ .set r21,21
+ .set r22,22
+ .set r23,23
+ .set r24,24
+ .set r25,25
+ .set r26,26
+ .set r27,27
+ .set r28,28
+ .set r29,29
+ .set r30,30
+ .set r31,31
+ .set f0,0
+ .set f1,1
+ .set f2,2
+ .set f3,3
+ .set f4,4
+ .set f5,5
+ .set f6,6
+ .set f7,7
+ .set f8,8
+ .set f9,9
+ .set f10,10
+ .set f11,11
+ .set f12,12
+ .set f13,13
+ .set f14,14
+ .set f15,15
+ .set f16,16
+ .set f17,17
+ .set f18,18
+ .set f19,19
+ .set f20,20
+ .set f21,21
+
+ .extern .ffi_prep_args
+
+#define LIBFFI_ASM
+#include <fficonfig.h>
+#include <ffi.h>
+#define JUMPTARGET(name) name
+#define L(x) x
+ .file "aix.S"
+ .toc
+
+ /* void ffi_call_AIX(extended_cif *ecif, unsigned long bytes,
+ * unsigned int flags, unsigned int *rvalue,
+ * void (*fn)(),
+ * void (*prep_args)(extended_cif*, unsigned *const));
+ * r3=ecif, r4=bytes, r5=flags, r6=rvalue, r7=fn, r8=prep_args
+ */
+
+.csect .text[PR]
+ .align 2
+ .globl ffi_call_AIX
+ .globl .ffi_call_AIX
+.csect ffi_call_AIX[DS]
+ffi_call_AIX:
+#ifdef __64BIT__
+ .llong .ffi_call_AIX, TOC[tc0], 0
+ .csect .text[PR]
+.ffi_call_AIX:
+ .function .ffi_call_AIX,.ffi_call_AIX,16,044,LFE..0-LFB..0
+ .bf __LINE__
+ .line 1
+LFB..0:
+ /* Save registers we use. */
+ mflr r0
+
+ std r28,-32(r1)
+ std r29,-24(r1)
+ std r30,-16(r1)
+ std r31, -8(r1)
+
+ std r0, 16(r1)
+LCFI..0:
+ mr r28, r1 /* our AP. */
+ stdux r1, r1, r4
+LCFI..1:
+
+ /* Save arguments over call... */
+ mr r31, r5 /* flags, */
+ mr r30, r6 /* rvalue, */
+ mr r29, r7 /* function address. */
+ std r2, 40(r1)
+
+ /* Call ffi_prep_args. */
+ mr r4, r1
+ bl .ffi_prep_args
+ nop
+
+ /* Now do the call. */
+ ld r0, 0(r29)
+ ld r2, 8(r29)
+ ld r11, 16(r29)
+ /* Set up cr1 with bits 4-7 of the flags. */
+ mtcrf 0x40, r31
+ mtctr r0
+ /* Load all those argument registers. */
+ /* We have set up a nice stack frame, just load it into registers. */
+ ld r3, 40+(1*8)(r1)
+ ld r4, 40+(2*8)(r1)
+ ld r5, 40+(3*8)(r1)
+ ld r6, 40+(4*8)(r1)
+ nop
+ ld r7, 40+(5*8)(r1)
+ ld r8, 40+(6*8)(r1)
+ ld r9, 40+(7*8)(r1)
+ ld r10,40+(8*8)(r1)
+
+L1:
+ /* Load all the FP registers. */
+ bf 6,L2 /* 2f + 0x18 */
+ lfd f1,-32-(13*8)(r28)
+ lfd f2,-32-(12*8)(r28)
+ lfd f3,-32-(11*8)(r28)
+ lfd f4,-32-(10*8)(r28)
+ nop
+ lfd f5,-32-(9*8)(r28)
+ lfd f6,-32-(8*8)(r28)
+ lfd f7,-32-(7*8)(r28)
+ lfd f8,-32-(6*8)(r28)
+ nop
+ lfd f9,-32-(5*8)(r28)
+ lfd f10,-32-(4*8)(r28)
+ lfd f11,-32-(3*8)(r28)
+ lfd f12,-32-(2*8)(r28)
+ nop
+ lfd f13,-32-(1*8)(r28)
+
+L2:
+ /* Make the call. */
+ bctrl
+ ld r2, 40(r1)
+
+ /* Now, deal with the return value. */
+ mtcrf 0x01, r31
+
+ bt 30, L(done_return_value)
+ bt 29, L(fp_return_value)
+ std r3, 0(r30)
+
+ /* Fall through... */
+
+L(done_return_value):
+ /* Restore the registers we used and return. */
+ mr r1, r28
+ ld r0, 16(r28)
+ ld r28, -32(r1)
+ mtlr r0
+ ld r29, -24(r1)
+ ld r30, -16(r1)
+ ld r31, -8(r1)
+ blr
+
+L(fp_return_value):
+ bf 28, L(float_return_value)
+ stfd f1, 0(r30)
+ bf 31, L(done_return_value)
+ stfd f2, 8(r30)
+ b L(done_return_value)
+L(float_return_value):
+ stfs f1, 0(r30)
+ b L(done_return_value)
+LFE..0:
+#else /* ! __64BIT__ */
+
+ .long .ffi_call_AIX, TOC[tc0], 0
+ .csect .text[PR]
+.ffi_call_AIX:
+ .function .ffi_call_AIX,.ffi_call_AIX,16,044,LFE..0-LFB..0
+ .bf __LINE__
+ .line 1
+LFB..0:
+ /* Save registers we use. */
+ mflr r0
+
+ stw r28,-16(r1)
+ stw r29,-12(r1)
+ stw r30, -8(r1)
+ stw r31, -4(r1)
+
+ stw r0, 8(r1)
+LCFI..0:
+ mr r28, r1 /* out AP. */
+ stwux r1, r1, r4
+LCFI..1:
+
+ /* Save arguments over call... */
+ mr r31, r5 /* flags, */
+ mr r30, r6 /* rvalue, */
+ mr r29, r7 /* function address, */
+ stw r2, 20(r1)
+
+ /* Call ffi_prep_args. */
+ mr r4, r1
+ bl .ffi_prep_args
+ nop
+
+ /* Now do the call. */
+ lwz r0, 0(r29)
+ lwz r2, 4(r29)
+ lwz r11, 8(r29)
+ /* Set up cr1 with bits 4-7 of the flags. */
+ mtcrf 0x40, r31
+ mtctr r0
+ /* Load all those argument registers. */
+ /* We have set up a nice stack frame, just load it into registers. */
+ lwz r3, 20+(1*4)(r1)
+ lwz r4, 20+(2*4)(r1)
+ lwz r5, 20+(3*4)(r1)
+ lwz r6, 20+(4*4)(r1)
+ nop
+ lwz r7, 20+(5*4)(r1)
+ lwz r8, 20+(6*4)(r1)
+ lwz r9, 20+(7*4)(r1)
+ lwz r10,20+(8*4)(r1)
+
+L1:
+ /* Load all the FP registers. */
+ bf 6,L2 /* 2f + 0x18 */
+ lfd f1,-16-(13*8)(r28)
+ lfd f2,-16-(12*8)(r28)
+ lfd f3,-16-(11*8)(r28)
+ lfd f4,-16-(10*8)(r28)
+ nop
+ lfd f5,-16-(9*8)(r28)
+ lfd f6,-16-(8*8)(r28)
+ lfd f7,-16-(7*8)(r28)
+ lfd f8,-16-(6*8)(r28)
+ nop
+ lfd f9,-16-(5*8)(r28)
+ lfd f10,-16-(4*8)(r28)
+ lfd f11,-16-(3*8)(r28)
+ lfd f12,-16-(2*8)(r28)
+ nop
+ lfd f13,-16-(1*8)(r28)
+
+L2:
+ /* Make the call. */
+ bctrl
+ lwz r2, 20(r1)
+
+ /* Now, deal with the return value. */
+ mtcrf 0x01, r31
+
+ bt 30, L(done_return_value)
+ bt 29, L(fp_return_value)
+ stw r3, 0(r30)
+ bf 28, L(done_return_value)
+ stw r4, 4(r30)
+
+ /* Fall through... */
+
+L(done_return_value):
+ /* Restore the registers we used and return. */
+ mr r1, r28
+ lwz r0, 8(r28)
+ lwz r28,-16(r1)
+ mtlr r0
+ lwz r29,-12(r1)
+ lwz r30, -8(r1)
+ lwz r31, -4(r1)
+ blr
+
+L(fp_return_value):
+ bf 28, L(float_return_value)
+ stfd f1, 0(r30)
+ b L(done_return_value)
+L(float_return_value):
+ stfs f1, 0(r30)
+ b L(done_return_value)
+LFE..0:
+#endif
+ .ef __LINE__
+ .long 0
+ .byte 0,0,0,1,128,4,0,0
+/* END(ffi_call_AIX) */
+
+ /* void ffi_call_go_AIX(extended_cif *ecif, unsigned long bytes,
+ * unsigned int flags, unsigned int *rvalue,
+ * void (*fn)(),
+ * void (*prep_args)(extended_cif*, unsigned *const),
+ * void *closure);
+ * r3=ecif, r4=bytes, r5=flags, r6=rvalue, r7=fn, r8=prep_args, r9=closure
+ */
+
+.csect .text[PR]
+ .align 2
+ .globl ffi_call_go_AIX
+ .globl .ffi_call_go_AIX
+.csect ffi_call_go_AIX[DS]
+ffi_call_go_AIX:
+#ifdef __64BIT__
+ .llong .ffi_call_go_AIX, TOC[tc0], 0
+ .csect .text[PR]
+.ffi_call_go_AIX:
+ .function .ffi_call_go_AIX,.ffi_call_go_AIX,16,044,LFE..1-LFB..1
+ .bf __LINE__
+ .line 1
+LFB..1:
+ /* Save registers we use. */
+ mflr r0
+
+ std r28,-32(r1)
+ std r29,-24(r1)
+ std r30,-16(r1)
+ std r31, -8(r1)
+
+ std r9, 8(r1) /* closure, saved in cr field. */
+ std r0, 16(r1)
+LCFI..2:
+ mr r28, r1 /* our AP. */
+ stdux r1, r1, r4
+LCFI..3:
+
+ /* Save arguments over call... */
+ mr r31, r5 /* flags, */
+ mr r30, r6 /* rvalue, */
+ mr r29, r7 /* function address, */
+ std r2, 40(r1)
+
+ /* Call ffi_prep_args. */
+ mr r4, r1
+ bl .ffi_prep_args
+ nop
+
+ /* Now do the call. */
+ ld r0, 0(r29)
+ ld r2, 8(r29)
+ ld r11, 8(r28) /* closure */
+ /* Set up cr1 with bits 4-7 of the flags. */
+ mtcrf 0x40, r31
+ mtctr r0
+ /* Load all those argument registers. */
+ /* We have set up a nice stack frame, just load it into registers. */
+ ld r3, 40+(1*8)(r1)
+ ld r4, 40+(2*8)(r1)
+ ld r5, 40+(3*8)(r1)
+ ld r6, 40+(4*8)(r1)
+ nop
+ ld r7, 40+(5*8)(r1)
+ ld r8, 40+(6*8)(r1)
+ ld r9, 40+(7*8)(r1)
+ ld r10,40+(8*8)(r1)
+
+ b L1
+LFE..1:
+#else /* ! __64BIT__ */
+
+ .long .ffi_call_go_AIX, TOC[tc0], 0
+ .csect .text[PR]
+.ffi_call_go_AIX:
+ .function .ffi_call_go_AIX,.ffi_call_go_AIX,16,044,LFE..1-LFB..1
+ .bf __LINE__
+ .line 1
+ /* Save registers we use. */
+LFB..1:
+ mflr r0
+
+ stw r28,-16(r1)
+ stw r29,-12(r1)
+ stw r30, -8(r1)
+ stw r31, -4(r1)
+
+ stw r9, 4(r1) /* closure, saved in cr field. */
+ stw r0, 8(r1)
+LCFI..2:
+ mr r28, r1 /* out AP. */
+ stwux r1, r1, r4
+LCFI..3:
+
+ /* Save arguments over call... */
+ mr r31, r5 /* flags, */
+ mr r30, r6 /* rvalue, */
+ mr r29, r7 /* function address, */
+ stw r2, 20(r1)
+
+ /* Call ffi_prep_args. */
+ mr r4, r1
+ bl .ffi_prep_args
+ nop
+
+ /* Now do the call. */
+ lwz r0, 0(r29)
+ lwz r2, 4(r29)
+ lwz r11, 4(r28) /* closure */
+ /* Set up cr1 with bits 4-7 of the flags. */
+ mtcrf 0x40, r31
+ mtctr r0
+ /* Load all those argument registers. */
+ /* We have set up a nice stack frame, just load it into registers. */
+ lwz r3, 20+(1*4)(r1)
+ lwz r4, 20+(2*4)(r1)
+ lwz r5, 20+(3*4)(r1)
+ lwz r6, 20+(4*4)(r1)
+ nop
+ lwz r7, 20+(5*4)(r1)
+ lwz r8, 20+(6*4)(r1)
+ lwz r9, 20+(7*4)(r1)
+ lwz r10,20+(8*4)(r1)
+
+ b L1
+LFE..1:
+#endif
+ .ef __LINE__
+ .long 0
+ .byte 0,0,0,1,128,4,0,0
+/* END(ffi_call_go_AIX) */
+
+.csect .text[PR]
+ .align 2
+ .globl ffi_call_DARWIN
+ .globl .ffi_call_DARWIN
+.csect ffi_call_DARWIN[DS]
+ffi_call_DARWIN:
+#ifdef __64BIT__
+ .llong .ffi_call_DARWIN, TOC[tc0], 0
+#else
+ .long .ffi_call_DARWIN, TOC[tc0], 0
+#endif
+ .csect .text[PR]
+.ffi_call_DARWIN:
+ blr
+ .long 0
+ .byte 0,0,0,0,0,0,0,0
+/* END(ffi_call_DARWIN) */
+
+/* EH frame stuff. */
+
+#define LR_REGNO 0x41 /* Link Register (65), see rs6000.md */
+#ifdef __64BIT__
+#define PTRSIZE 8
+#define LOG2_PTRSIZE 3
+#define FDE_ENCODING 0x1c /* DW_EH_PE_pcrel|DW_EH_PE_sdata8 */
+#define EH_DATA_ALIGN_FACT 0x78 /* LEB128 -8 */
+#else
+#define PTRSIZE 4
+#define LOG2_PTRSIZE 2
+#define FDE_ENCODING 0x1b /* DW_EH_PE_pcrel|DW_EH_PE_sdata4 */
+#define EH_DATA_ALIGN_FACT 0x7c /* LEB128 -4 */
+#endif
+ .csect _unwind.ro_[RO],4
+ .align LOG2_PTRSIZE
+ .globl _GLOBAL__F_libffi_src_powerpc_aix
+_GLOBAL__F_libffi_src_powerpc_aix:
+Lframe..1:
+ .vbyte 4,LECIE..1-LSCIE..1 /* CIE Length */
+LSCIE..1:
+ .vbyte 4,0 /* CIE Identifier Tag */
+ .byte 0x3 /* CIE Version */
+ .byte "zR" /* CIE Augmentation */
+ .byte 0
+ .byte 0x1 /* uleb128 0x1; CIE Code Alignment Factor */
+ .byte EH_DATA_ALIGN_FACT /* leb128 -4/-8; CIE Data Alignment Factor */
+ .byte 0x41 /* CIE RA Column */
+ .byte 0x1 /* uleb128 0x1; Augmentation size */
+ .byte FDE_ENCODING /* FDE Encoding (pcrel|sdata4/8) */
+ .byte 0xc /* DW_CFA_def_cfa */
+ .byte 0x1 /* uleb128 0x1; Register r1 */
+ .byte 0 /* uleb128 0x0; Offset 0 */
+ .align LOG2_PTRSIZE
+LECIE..1:
+LSFDE..1:
+ .vbyte 4,LEFDE..1-LASFDE..1 /* FDE Length */
+LASFDE..1:
+ .vbyte 4,LASFDE..1-Lframe..1 /* FDE CIE offset */
+ .vbyte PTRSIZE,LFB..0-$ /* FDE initial location */
+ .vbyte PTRSIZE,LFE..0-LFB..0 /* FDE address range */
+ .byte 0 /* uleb128 0x0; Augmentation size */
+ .byte 0x4 /* DW_CFA_advance_loc4 */
+ .vbyte 4,LCFI..0-LFB..0
+ .byte 0x11 /* DW_CFA_def_offset_extended_sf */
+ .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */
+ .byte 0x7e /* leb128 -2; Offset -2 (8/16) */
+ .byte 0x9f /* DW_CFA_offset Register r31 */
+ .byte 0x1 /* uleb128 0x1; Offset 1 (-4/-8) */
+ .byte 0x9e /* DW_CFA_offset Register r30 */
+ .byte 0x2 /* uleb128 0x2; Offset 2 (-8/-16) */
+ .byte 0x9d /* DW_CFA_offset Register r29 */
+ .byte 0x3 /* uleb128 0x3; Offset 3 (-12/-24) */
+ .byte 0x9c /* DW_CFA_offset Register r28 */
+ .byte 0x4 /* uleb128 0x4; Offset 4 (-16/-32) */
+ .byte 0x4 /* DW_CFA_advance_loc4 */
+ .vbyte 4,LCFI..1-LCFI..0
+ .byte 0xd /* DW_CFA_def_cfa_register */
+ .byte 0x1c /* uleb128 28; Register r28 */
+ .align LOG2_PTRSIZE
+LEFDE..1:
+LSFDE..2:
+ .vbyte 4,LEFDE..2-LASFDE..2 /* FDE Length */
+LASFDE..2:
+ .vbyte 4,LASFDE..2-Lframe..1 /* FDE CIE offset */
+ .vbyte PTRSIZE,LFB..1-$ /* FDE initial location */
+ .vbyte PTRSIZE,LFE..1-LFB..1 /* FDE address range */
+ .byte 0 /* uleb128 0x0; Augmentation size */
+ .byte 0x4 /* DW_CFA_advance_loc4 */
+ .vbyte 4,LCFI..2-LFB..1
+ .byte 0x11 /* DW_CFA_def_offset_extended_sf */
+ .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */
+ .byte 0x7e /* leb128 -2; Offset -2 (8/16) */
+ .byte 0x9f /* DW_CFA_offset Register r31 */
+ .byte 0x1 /* uleb128 0x1; Offset 1 (-4/-8) */
+ .byte 0x9e /* DW_CFA_offset Register r30 */
+ .byte 0x2 /* uleb128 0x2; Offset 2 (-8/-16) */
+ .byte 0x9d /* DW_CFA_offset Register r29 */
+ .byte 0x3 /* uleb128 0x3; Offset 3 (-12/-24) */
+ .byte 0x9c /* DW_CFA_offset Register r28 */
+ .byte 0x4 /* uleb128 0x4; Offset 4 (-16/-32) */
+ .byte 0x4 /* DW_CFA_advance_loc4 */
+ .vbyte 4,LCFI..3-LCFI..2
+ .byte 0xd /* DW_CFA_def_cfa_register */
+ .byte 0x1c /* uleb128 28; Register r28 */
+ .align LOG2_PTRSIZE
+LEFDE..2:
+ .vbyte 4,0 /* End of FDEs */
+
+ .csect .text[PR]
+ .ref _GLOBAL__F_libffi_src_powerpc_aix /* Prevents garbage collection by AIX linker */
+
diff --git a/contrib/restricted/libffi/src/powerpc/aix_closure.S b/contrib/restricted/libffi/src/powerpc/aix_closure.S
index be836056e6..132c785edd 100644
--- a/contrib/restricted/libffi/src/powerpc/aix_closure.S
+++ b/contrib/restricted/libffi/src/powerpc/aix_closure.S
@@ -1,694 +1,694 @@
-/* -----------------------------------------------------------------------
- aix_closure.S - Copyright (c) 2002, 2003, 2009 Free Software Foundation, Inc.
- based on darwin_closure.S
-
- PowerPC Assembly glue.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
- .set r0,0
- .set r1,1
- .set r2,2
- .set r3,3
- .set r4,4
- .set r5,5
- .set r6,6
- .set r7,7
- .set r8,8
- .set r9,9
- .set r10,10
- .set r11,11
- .set r12,12
- .set r13,13
- .set r14,14
- .set r15,15
- .set r16,16
- .set r17,17
- .set r18,18
- .set r19,19
- .set r20,20
- .set r21,21
- .set r22,22
- .set r23,23
- .set r24,24
- .set r25,25
- .set r26,26
- .set r27,27
- .set r28,28
- .set r29,29
- .set r30,30
- .set r31,31
- .set f0,0
- .set f1,1
- .set f2,2
- .set f3,3
- .set f4,4
- .set f5,5
- .set f6,6
- .set f7,7
- .set f8,8
- .set f9,9
- .set f10,10
- .set f11,11
- .set f12,12
- .set f13,13
- .set f14,14
- .set f15,15
- .set f16,16
- .set f17,17
- .set f18,18
- .set f19,19
- .set f20,20
- .set f21,21
-
- .extern .ffi_closure_helper_DARWIN
- .extern .ffi_go_closure_helper_DARWIN
-
-#define LIBFFI_ASM
-#define JUMPTARGET(name) name
-#define L(x) x
- .file "aix_closure.S"
- .toc
-LC..60:
- .tc L..60[TC],L..60
- .csect .text[PR]
- .align 2
-
-.csect .text[PR]
- .align 2
- .globl ffi_closure_ASM
- .globl .ffi_closure_ASM
-.csect ffi_closure_ASM[DS]
-ffi_closure_ASM:
-#ifdef __64BIT__
- .llong .ffi_closure_ASM, TOC[tc0], 0
- .csect .text[PR]
-.ffi_closure_ASM:
- .function .ffi_closure_ASM,.ffi_closure_ASM,16,044,LFE..0-LFB..0
- .bf __LINE__
- .line 1
-LFB..0:
-/* we want to build up an area for the parameters passed */
-/* in registers (both floating point and integer) */
-
- /* we store gpr 3 to gpr 10 (aligned to 4)
- in the parents outgoing area */
- std r3, 48+(0*8)(r1)
- std r4, 48+(1*8)(r1)
- std r5, 48+(2*8)(r1)
- std r6, 48+(3*8)(r1)
- mflr r0
-
- std r7, 48+(4*8)(r1)
- std r8, 48+(5*8)(r1)
- std r9, 48+(6*8)(r1)
- std r10, 48+(7*8)(r1)
- std r0, 16(r1) /* save the return address */
-LCFI..0:
- /* 48 Bytes (Linkage Area) */
- /* 64 Bytes (params) */
- /* 16 Bytes (result) */
- /* 104 Bytes (13*8 from FPR) */
- /* 8 Bytes (alignment) */
- /* 240 Bytes */
-
- stdu r1, -240(r1) /* skip over caller save area
- keep stack aligned to 16 */
-LCFI..1:
-
- /* next save fpr 1 to fpr 13 (aligned to 8) */
- stfd f1, 128+(0*8)(r1)
- stfd f2, 128+(1*8)(r1)
- stfd f3, 128+(2*8)(r1)
- stfd f4, 128+(3*8)(r1)
- stfd f5, 128+(4*8)(r1)
- stfd f6, 128+(5*8)(r1)
- stfd f7, 128+(6*8)(r1)
- stfd f8, 128+(7*8)(r1)
- stfd f9, 128+(8*8)(r1)
- stfd f10, 128+(9*8)(r1)
- stfd f11, 128+(10*8)(r1)
- stfd f12, 128+(11*8)(r1)
- stfd f13, 128+(12*8)(r1)
-
- /* set up registers for the routine that actually does the work */
- /* get the context pointer from the trampoline */
- mr r3, r11
-
- /* now load up the pointer to the result storage */
- addi r4, r1, 112
-
- /* now load up the pointer to the saved gpr registers */
- addi r5, r1, 288
-
- /* now load up the pointer to the saved fpr registers */
- addi r6, r1, 128
-
- /* make the call */
- bl .ffi_closure_helper_DARWIN
- nop
-
-.Ldoneclosure:
-
- /* now r3 contains the return type */
- /* so use it to look up in a table */
- /* so we know how to deal with each type */
-
- /* look up the proper starting point in table */
- /* by using return type as offset */
- lhz r3, 10(r3) /* load type from return type */
- ld r4, LC..60(2) /* get address of jump table */
- sldi r3, r3, 4 /* now multiply return type by 16 */
- ld r0, 240+16(r1) /* load return address */
- add r3, r3, r4 /* add contents of table to table address */
- mtctr r3
- bctr /* jump to it */
-
-/* Each fragment must be exactly 16 bytes long (4 instructions).
- Align to 16 byte boundary for cache and dispatch efficiency. */
- .align 4
-
-L..60:
-/* case FFI_TYPE_VOID */
- mtlr r0
- addi r1, r1, 240
- blr
- nop
-
-/* case FFI_TYPE_INT */
- lwa r3, 112+4(r1)
- mtlr r0
- addi r1, r1, 240
- blr
-
-/* case FFI_TYPE_FLOAT */
- lfs f1, 112+0(r1)
- mtlr r0
- addi r1, r1, 240
- blr
-
-/* case FFI_TYPE_DOUBLE */
- lfd f1, 112+0(r1)
- mtlr r0
- addi r1, r1, 240
- blr
-
-/* case FFI_TYPE_LONGDOUBLE */
- lfd f1, 112+0(r1)
- mtlr r0
- lfd f2, 112+8(r1)
- b L..finish
-
-/* case FFI_TYPE_UINT8 */
- lbz r3, 112+7(r1)
- mtlr r0
- addi r1, r1, 240
- blr
-
-/* case FFI_TYPE_SINT8 */
- lbz r3, 112+7(r1)
- mtlr r0
- extsb r3, r3
- b L..finish
-
-/* case FFI_TYPE_UINT16 */
- lhz r3, 112+6(r1)
- mtlr r0
-L..finish:
- addi r1, r1, 240
- blr
-
-/* case FFI_TYPE_SINT16 */
- lha r3, 112+6(r1)
- mtlr r0
- addi r1, r1, 240
- blr
-
-/* case FFI_TYPE_UINT32 */
- lwz r3, 112+4(r1)
- mtlr r0
- addi r1, r1, 240
- blr
-
-/* case FFI_TYPE_SINT32 */
- lwa r3, 112+4(r1)
- mtlr r0
- addi r1, r1, 240
- blr
-
-/* case FFI_TYPE_UINT64 */
- ld r3, 112+0(r1)
- mtlr r0
- addi r1, r1, 240
- blr
-
-/* case FFI_TYPE_SINT64 */
- ld r3, 112+0(r1)
- mtlr r0
- addi r1, r1, 240
- blr
-
-/* case FFI_TYPE_STRUCT */
- mtlr r0
- addi r1, r1, 240
- blr
- nop
-
-/* case FFI_TYPE_POINTER */
- ld r3, 112+0(r1)
- mtlr r0
- addi r1, r1, 240
- blr
-LFE..0:
-
-#else /* ! __64BIT__ */
-
- .long .ffi_closure_ASM, TOC[tc0], 0
- .csect .text[PR]
-.ffi_closure_ASM:
- .function .ffi_closure_ASM,.ffi_closure_ASM,16,044,LFE..0-LFB..0
- .bf __LINE__
- .line 1
-LFB..0:
-/* we want to build up an area for the parameters passed */
-/* in registers (both floating point and integer) */
-
- /* we store gpr 3 to gpr 10 (aligned to 4)
- in the parents outgoing area */
- stw r3, 24+(0*4)(r1)
- stw r4, 24+(1*4)(r1)
- stw r5, 24+(2*4)(r1)
- stw r6, 24+(3*4)(r1)
- mflr r0
-
- stw r7, 24+(4*4)(r1)
- stw r8, 24+(5*4)(r1)
- stw r9, 24+(6*4)(r1)
- stw r10, 24+(7*4)(r1)
- stw r0, 8(r1)
-LCFI..0:
- /* 24 Bytes (Linkage Area) */
- /* 32 Bytes (params) */
- /* 16 Bytes (result) */
- /* 104 Bytes (13*8 from FPR) */
- /* 176 Bytes */
-
- stwu r1, -176(r1) /* skip over caller save area
- keep stack aligned to 16 */
-LCFI..1:
-
- /* next save fpr 1 to fpr 13 (aligned to 8) */
- stfd f1, 72+(0*8)(r1)
- stfd f2, 72+(1*8)(r1)
- stfd f3, 72+(2*8)(r1)
- stfd f4, 72+(3*8)(r1)
- stfd f5, 72+(4*8)(r1)
- stfd f6, 72+(5*8)(r1)
- stfd f7, 72+(6*8)(r1)
- stfd f8, 72+(7*8)(r1)
- stfd f9, 72+(8*8)(r1)
- stfd f10, 72+(9*8)(r1)
- stfd f11, 72+(10*8)(r1)
- stfd f12, 72+(11*8)(r1)
- stfd f13, 72+(12*8)(r1)
-
- /* set up registers for the routine that actually does the work */
- /* get the context pointer from the trampoline */
- mr r3, r11
-
- /* now load up the pointer to the result storage */
- addi r4, r1, 56
-
- /* now load up the pointer to the saved gpr registers */
- addi r5, r1, 200
-
- /* now load up the pointer to the saved fpr registers */
- addi r6, r1, 72
-
- /* make the call */
- bl .ffi_closure_helper_DARWIN
- nop
-
-.Ldoneclosure:
-
- /* now r3 contains the return type */
- /* so use it to look up in a table */
- /* so we know how to deal with each type */
-
- /* look up the proper starting point in table */
- /* by using return type as offset */
- lhz r3, 6(r3) /* load type from return type */
- lwz r4, LC..60(2) /* get address of jump table */
- slwi r3, r3, 4 /* now multiply return type by 16 */
- lwz r0, 176+8(r1) /* load return address */
- add r3, r3, r4 /* add contents of table to table address */
- mtctr r3
- bctr /* jump to it */
-
-/* Each fragment must be exactly 16 bytes long (4 instructions).
- Align to 16 byte boundary for cache and dispatch efficiency. */
- .align 4
-
-L..60:
-/* case FFI_TYPE_VOID */
- mtlr r0
- addi r1, r1, 176
- blr
- nop
-
-/* case FFI_TYPE_INT */
- lwz r3, 56+0(r1)
- mtlr r0
- addi r1, r1, 176
- blr
-
-/* case FFI_TYPE_FLOAT */
- lfs f1, 56+0(r1)
- mtlr r0
- addi r1, r1, 176
- blr
-
-/* case FFI_TYPE_DOUBLE */
- lfd f1, 56+0(r1)
- mtlr r0
- addi r1, r1, 176
- blr
-
-/* case FFI_TYPE_LONGDOUBLE */
- lfd f1, 56+0(r1)
- mtlr r0
- lfd f2, 56+8(r1)
- b L..finish
-
-/* case FFI_TYPE_UINT8 */
- lbz r3, 56+3(r1)
- mtlr r0
- addi r1, r1, 176
- blr
-
-/* case FFI_TYPE_SINT8 */
- lbz r3, 56+3(r1)
- mtlr r0
- extsb r3, r3
- b L..finish
-
-/* case FFI_TYPE_UINT16 */
- lhz r3, 56+2(r1)
- mtlr r0
- addi r1, r1, 176
- blr
-
-/* case FFI_TYPE_SINT16 */
- lha r3, 56+2(r1)
- mtlr r0
- addi r1, r1, 176
- blr
-
-/* case FFI_TYPE_UINT32 */
- lwz r3, 56+0(r1)
- mtlr r0
- addi r1, r1, 176
- blr
-
-/* case FFI_TYPE_SINT32 */
- lwz r3, 56+0(r1)
- mtlr r0
- addi r1, r1, 176
- blr
-
-/* case FFI_TYPE_UINT64 */
- lwz r3, 56+0(r1)
- mtlr r0
- lwz r4, 56+4(r1)
- b L..finish
-
-/* case FFI_TYPE_SINT64 */
- lwz r3, 56+0(r1)
- mtlr r0
- lwz r4, 56+4(r1)
- b L..finish
-
-/* case FFI_TYPE_STRUCT */
- mtlr r0
- addi r1, r1, 176
- blr
- nop
-
-/* case FFI_TYPE_POINTER */
- lwz r3, 56+0(r1)
- mtlr r0
-L..finish:
- addi r1, r1, 176
- blr
-LFE..0:
-#endif
- .ef __LINE__
-/* END(ffi_closure_ASM) */
-
-
-.csect .text[PR]
- .align 2
- .globl ffi_go_closure_ASM
- .globl .ffi_go_closure_ASM
-.csect ffi_go_closure_ASM[DS]
-ffi_go_closure_ASM:
-#ifdef __64BIT__
- .llong .ffi_go_closure_ASM, TOC[tc0], 0
- .csect .text[PR]
-.ffi_go_closure_ASM:
- .function .ffi_go_closure_ASM,.ffi_go_closure_ASM,16,044,LFE..1-LFB..1
- .bf __LINE__
- .line 1
-LFB..1:
-/* we want to build up an area for the parameters passed */
-/* in registers (both floating point and integer) */
-
- /* we store gpr 3 to gpr 10 (aligned to 4)
- in the parents outgoing area */
- std r3, 48+(0*8)(r1)
- std r4, 48+(1*8)(r1)
- std r5, 48+(2*8)(r1)
- std r6, 48+(3*8)(r1)
- mflr r0
-
- std r7, 48+(4*8)(r1)
- std r8, 48+(5*8)(r1)
- std r9, 48+(6*8)(r1)
- std r10, 48+(7*8)(r1)
- std r0, 16(r1) /* save the return address */
-LCFI..2:
- /* 48 Bytes (Linkage Area) */
- /* 64 Bytes (params) */
- /* 16 Bytes (result) */
- /* 104 Bytes (13*8 from FPR) */
- /* 8 Bytes (alignment) */
- /* 240 Bytes */
-
- stdu r1, -240(r1) /* skip over caller save area
- keep stack aligned to 16 */
-LCFI..3:
-
- /* next save fpr 1 to fpr 13 (aligned to 8) */
- stfd f1, 128+(0*8)(r1)
- stfd f2, 128+(1*8)(r1)
- stfd f3, 128+(2*8)(r1)
- stfd f4, 128+(3*8)(r1)
- stfd f5, 128+(4*8)(r1)
- stfd f6, 128+(5*8)(r1)
- stfd f7, 128+(6*8)(r1)
- stfd f8, 128+(7*8)(r1)
- stfd f9, 128+(8*8)(r1)
- stfd f10, 128+(9*8)(r1)
- stfd f11, 128+(10*8)(r1)
- stfd f12, 128+(11*8)(r1)
- stfd f13, 128+(12*8)(r1)
-
- /* set up registers for the routine that actually does the work */
- mr r3, r11 /* go closure */
-
- /* now load up the pointer to the result storage */
- addi r4, r1, 112
-
- /* now load up the pointer to the saved gpr registers */
- addi r5, r1, 288
-
- /* now load up the pointer to the saved fpr registers */
- addi r6, r1, 128
-
- /* make the call */
- bl .ffi_go_closure_helper_DARWIN
- nop
-
- b .Ldoneclosure
-LFE..1:
-
-#else /* ! __64BIT__ */
-
- .long .ffi_go_closure_ASM, TOC[tc0], 0
- .csect .text[PR]
-.ffi_go_closure_ASM:
- .function .ffi_go_closure_ASM,.ffi_go_closure_ASM,16,044,LFE..1-LFB..1
- .bf __LINE__
- .line 1
-LFB..1:
-/* we want to build up an area for the parameters passed */
-/* in registers (both floating point and integer) */
-
- /* we store gpr 3 to gpr 10 (aligned to 4)
- in the parents outgoing area */
- stw r3, 24+(0*4)(r1)
- stw r4, 24+(1*4)(r1)
- stw r5, 24+(2*4)(r1)
- stw r6, 24+(3*4)(r1)
- mflr r0
-
- stw r7, 24+(4*4)(r1)
- stw r8, 24+(5*4)(r1)
- stw r9, 24+(6*4)(r1)
- stw r10, 24+(7*4)(r1)
- stw r0, 8(r1)
-LCFI..2:
- /* 24 Bytes (Linkage Area) */
- /* 32 Bytes (params) */
- /* 16 Bytes (result) */
- /* 104 Bytes (13*8 from FPR) */
- /* 176 Bytes */
-
- stwu r1, -176(r1) /* skip over caller save area
- keep stack aligned to 16 */
-LCFI..3:
-
- /* next save fpr 1 to fpr 13 (aligned to 8) */
- stfd f1, 72+(0*8)(r1)
- stfd f2, 72+(1*8)(r1)
- stfd f3, 72+(2*8)(r1)
- stfd f4, 72+(3*8)(r1)
- stfd f5, 72+(4*8)(r1)
- stfd f6, 72+(5*8)(r1)
- stfd f7, 72+(6*8)(r1)
- stfd f8, 72+(7*8)(r1)
- stfd f9, 72+(8*8)(r1)
- stfd f10, 72+(9*8)(r1)
- stfd f11, 72+(10*8)(r1)
- stfd f12, 72+(11*8)(r1)
- stfd f13, 72+(12*8)(r1)
-
- /* set up registers for the routine that actually does the work */
- mr r3, 11 /* go closure */
-
- /* now load up the pointer to the result storage */
- addi r4, r1, 56
-
- /* now load up the pointer to the saved gpr registers */
- addi r5, r1, 200
-
- /* now load up the pointer to the saved fpr registers */
- addi r6, r1, 72
-
- /* make the call */
- bl .ffi_go_closure_helper_DARWIN
- nop
-
- b .Ldoneclosure
-LFE..1:
-#endif
- .ef __LINE__
-/* END(ffi_go_closure_ASM) */
-
-/* EH frame stuff. */
-
-#define LR_REGNO 0x41 /* Link Register (65), see rs6000.md */
-#ifdef __64BIT__
-#define PTRSIZE 8
-#define LOG2_PTRSIZE 3
-#define CFA_OFFSET 0xf0,0x01 /* LEB128 240 */
-#define FDE_ENCODING 0x1c /* DW_EH_PE_pcrel|DW_EH_PE_sdata8 */
-#define EH_DATA_ALIGN_FACT 0x78 /* LEB128 -8 */
-#else
-#define PTRSIZE 4
-#define LOG2_PTRSIZE 2
-#define CFA_OFFSET 0xb0,0x01 /* LEB128 176 */
-#define FDE_ENCODING 0x1b /* DW_EH_PE_pcrel|DW_EH_PE_sdata4 */
-#define EH_DATA_ALIGN_FACT 0x7c /* LEB128 -4 */
-#endif
-
- .csect _unwind.ro_[RO],4
- .align LOG2_PTRSIZE
- .globl _GLOBAL__F_libffi_src_powerpc_aix_closure
-_GLOBAL__F_libffi_src_powerpc_aix_closure:
-Lframe..1:
- .vbyte 4,LECIE..1-LSCIE..1 /* CIE Length */
-LSCIE..1:
- .vbyte 4,0 /* CIE Identifier Tag */
- .byte 0x3 /* CIE Version */
- .byte "zR" /* CIE Augmentation */
- .byte 0
- .byte 0x1 /* uleb128 0x1; CIE Code Alignment Factor */
- .byte EH_DATA_ALIGN_FACT /* leb128 -4/-8; CIE Data Alignment Factor */
- .byte LR_REGNO /* CIE RA Column */
- .byte 0x1 /* uleb128 0x1; Augmentation size */
- .byte FDE_ENCODING /* FDE Encoding (pcrel|sdata4/8) */
- .byte 0xc /* DW_CFA_def_cfa */
- .byte 0x1 /* uleb128 0x1; Register r1 */
- .byte 0 /* uleb128 0x0; Offset 0 */
- .align LOG2_PTRSIZE
-LECIE..1:
-LSFDE..1:
- .vbyte 4,LEFDE..1-LASFDE..1 /* FDE Length */
-LASFDE..1:
- .vbyte 4,LASFDE..1-Lframe..1 /* FDE CIE offset */
- .vbyte PTRSIZE,LFB..0-$ /* FDE initial location */
- .vbyte PTRSIZE,LFE..0-LFB..0 /* FDE address range */
- .byte 0 /* uleb128 0x0; Augmentation size */
- .byte 0x4 /* DW_CFA_advance_loc4 */
- .vbyte 4,LCFI..1-LCFI..0
- .byte 0xe /* DW_CFA_def_cfa_offset */
- .byte CFA_OFFSET /* uleb128 176/240 */
- .byte 0x4 /* DW_CFA_advance_loc4 */
- .vbyte 4,LCFI..0-LFB..0
- .byte 0x11 /* DW_CFA_offset_extended_sf */
- .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */
- .byte 0x7e /* leb128 -2; Offset -2 (8/16) */
- .align LOG2_PTRSIZE
-LEFDE..1:
-LSFDE..2:
- .vbyte 4,LEFDE..2-LASFDE..2 /* FDE Length */
-LASFDE..2:
- .vbyte 4,LASFDE..2-Lframe..1 /* FDE CIE offset */
- .vbyte PTRSIZE,LFB..1-$ /* FDE initial location */
- .vbyte PTRSIZE,LFE..1-LFB..1 /* FDE address range */
- .byte 0 /* uleb128 0x0; Augmentation size */
- .byte 0x4 /* DW_CFA_advance_loc4 */
- .vbyte 4,LCFI..3-LCFI..2
- .byte 0xe /* DW_CFA_def_cfa_offset */
- .byte CFA_OFFSET /* uleb128 176/240 */
- .byte 0x4 /* DW_CFA_advance_loc4 */
- .vbyte 4,LCFI..2-LFB..1
- .byte 0x11 /* DW_CFA_offset_extended_sf */
- .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */
- .byte 0x7e /* leb128 -2; Offset -2 (8/16) */
- .align LOG2_PTRSIZE
-LEFDE..2:
- .vbyte 4,0 /* End of FDEs */
-
- .csect .text[PR]
- .ref _GLOBAL__F_libffi_src_powerpc_aix_closure /* Prevents garbage collection by AIX linker */
-
+/* -----------------------------------------------------------------------
+ aix_closure.S - Copyright (c) 2002, 2003, 2009 Free Software Foundation, Inc.
+ based on darwin_closure.S
+
+ PowerPC Assembly glue.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+ .set r0,0
+ .set r1,1
+ .set r2,2
+ .set r3,3
+ .set r4,4
+ .set r5,5
+ .set r6,6
+ .set r7,7
+ .set r8,8
+ .set r9,9
+ .set r10,10
+ .set r11,11
+ .set r12,12
+ .set r13,13
+ .set r14,14
+ .set r15,15
+ .set r16,16
+ .set r17,17
+ .set r18,18
+ .set r19,19
+ .set r20,20
+ .set r21,21
+ .set r22,22
+ .set r23,23
+ .set r24,24
+ .set r25,25
+ .set r26,26
+ .set r27,27
+ .set r28,28
+ .set r29,29
+ .set r30,30
+ .set r31,31
+ .set f0,0
+ .set f1,1
+ .set f2,2
+ .set f3,3
+ .set f4,4
+ .set f5,5
+ .set f6,6
+ .set f7,7
+ .set f8,8
+ .set f9,9
+ .set f10,10
+ .set f11,11
+ .set f12,12
+ .set f13,13
+ .set f14,14
+ .set f15,15
+ .set f16,16
+ .set f17,17
+ .set f18,18
+ .set f19,19
+ .set f20,20
+ .set f21,21
+
+ .extern .ffi_closure_helper_DARWIN
+ .extern .ffi_go_closure_helper_DARWIN
+
+#define LIBFFI_ASM
+#define JUMPTARGET(name) name
+#define L(x) x
+ .file "aix_closure.S"
+ .toc
+LC..60:
+ .tc L..60[TC],L..60
+ .csect .text[PR]
+ .align 2
+
+.csect .text[PR]
+ .align 2
+ .globl ffi_closure_ASM
+ .globl .ffi_closure_ASM
+.csect ffi_closure_ASM[DS]
+ffi_closure_ASM:
+#ifdef __64BIT__
+ .llong .ffi_closure_ASM, TOC[tc0], 0
+ .csect .text[PR]
+.ffi_closure_ASM:
+ .function .ffi_closure_ASM,.ffi_closure_ASM,16,044,LFE..0-LFB..0
+ .bf __LINE__
+ .line 1
+LFB..0:
+/* we want to build up an area for the parameters passed */
+/* in registers (both floating point and integer) */
+
+ /* we store gpr 3 to gpr 10 (aligned to 4)
+ in the parents outgoing area */
+ std r3, 48+(0*8)(r1)
+ std r4, 48+(1*8)(r1)
+ std r5, 48+(2*8)(r1)
+ std r6, 48+(3*8)(r1)
+ mflr r0
+
+ std r7, 48+(4*8)(r1)
+ std r8, 48+(5*8)(r1)
+ std r9, 48+(6*8)(r1)
+ std r10, 48+(7*8)(r1)
+ std r0, 16(r1) /* save the return address */
+LCFI..0:
+ /* 48 Bytes (Linkage Area) */
+ /* 64 Bytes (params) */
+ /* 16 Bytes (result) */
+ /* 104 Bytes (13*8 from FPR) */
+ /* 8 Bytes (alignment) */
+ /* 240 Bytes */
+
+ stdu r1, -240(r1) /* skip over caller save area
+ keep stack aligned to 16 */
+LCFI..1:
+
+ /* next save fpr 1 to fpr 13 (aligned to 8) */
+ stfd f1, 128+(0*8)(r1)
+ stfd f2, 128+(1*8)(r1)
+ stfd f3, 128+(2*8)(r1)
+ stfd f4, 128+(3*8)(r1)
+ stfd f5, 128+(4*8)(r1)
+ stfd f6, 128+(5*8)(r1)
+ stfd f7, 128+(6*8)(r1)
+ stfd f8, 128+(7*8)(r1)
+ stfd f9, 128+(8*8)(r1)
+ stfd f10, 128+(9*8)(r1)
+ stfd f11, 128+(10*8)(r1)
+ stfd f12, 128+(11*8)(r1)
+ stfd f13, 128+(12*8)(r1)
+
+ /* set up registers for the routine that actually does the work */
+ /* get the context pointer from the trampoline */
+ mr r3, r11
+
+ /* now load up the pointer to the result storage */
+ addi r4, r1, 112
+
+ /* now load up the pointer to the saved gpr registers */
+ addi r5, r1, 288
+
+ /* now load up the pointer to the saved fpr registers */
+ addi r6, r1, 128
+
+ /* make the call */
+ bl .ffi_closure_helper_DARWIN
+ nop
+
+.Ldoneclosure:
+
+ /* now r3 contains the return type */
+ /* so use it to look up in a table */
+ /* so we know how to deal with each type */
+
+ /* look up the proper starting point in table */
+ /* by using return type as offset */
+ lhz r3, 10(r3) /* load type from return type */
+ ld r4, LC..60(2) /* get address of jump table */
+ sldi r3, r3, 4 /* now multiply return type by 16 */
+ ld r0, 240+16(r1) /* load return address */
+ add r3, r3, r4 /* add contents of table to table address */
+ mtctr r3
+ bctr /* jump to it */
+
+/* Each fragment must be exactly 16 bytes long (4 instructions).
+ Align to 16 byte boundary for cache and dispatch efficiency. */
+ .align 4
+
+L..60:
+/* case FFI_TYPE_VOID */
+ mtlr r0
+ addi r1, r1, 240
+ blr
+ nop
+
+/* case FFI_TYPE_INT */
+ lwa r3, 112+4(r1)
+ mtlr r0
+ addi r1, r1, 240
+ blr
+
+/* case FFI_TYPE_FLOAT */
+ lfs f1, 112+0(r1)
+ mtlr r0
+ addi r1, r1, 240
+ blr
+
+/* case FFI_TYPE_DOUBLE */
+ lfd f1, 112+0(r1)
+ mtlr r0
+ addi r1, r1, 240
+ blr
+
+/* case FFI_TYPE_LONGDOUBLE */
+ lfd f1, 112+0(r1)
+ mtlr r0
+ lfd f2, 112+8(r1)
+ b L..finish
+
+/* case FFI_TYPE_UINT8 */
+ lbz r3, 112+7(r1)
+ mtlr r0
+ addi r1, r1, 240
+ blr
+
+/* case FFI_TYPE_SINT8 */
+ lbz r3, 112+7(r1)
+ mtlr r0
+ extsb r3, r3
+ b L..finish
+
+/* case FFI_TYPE_UINT16 */
+ lhz r3, 112+6(r1)
+ mtlr r0
+L..finish:
+ addi r1, r1, 240
+ blr
+
+/* case FFI_TYPE_SINT16 */
+ lha r3, 112+6(r1)
+ mtlr r0
+ addi r1, r1, 240
+ blr
+
+/* case FFI_TYPE_UINT32 */
+ lwz r3, 112+4(r1)
+ mtlr r0
+ addi r1, r1, 240
+ blr
+
+/* case FFI_TYPE_SINT32 */
+ lwa r3, 112+4(r1)
+ mtlr r0
+ addi r1, r1, 240
+ blr
+
+/* case FFI_TYPE_UINT64 */
+ ld r3, 112+0(r1)
+ mtlr r0
+ addi r1, r1, 240
+ blr
+
+/* case FFI_TYPE_SINT64 */
+ ld r3, 112+0(r1)
+ mtlr r0
+ addi r1, r1, 240
+ blr
+
+/* case FFI_TYPE_STRUCT */
+ mtlr r0
+ addi r1, r1, 240
+ blr
+ nop
+
+/* case FFI_TYPE_POINTER */
+ ld r3, 112+0(r1)
+ mtlr r0
+ addi r1, r1, 240
+ blr
+LFE..0:
+
+#else /* ! __64BIT__ */
+
+ .long .ffi_closure_ASM, TOC[tc0], 0
+ .csect .text[PR]
+.ffi_closure_ASM:
+ .function .ffi_closure_ASM,.ffi_closure_ASM,16,044,LFE..0-LFB..0
+ .bf __LINE__
+ .line 1
+LFB..0:
+/* we want to build up an area for the parameters passed */
+/* in registers (both floating point and integer) */
+
+ /* we store gpr 3 to gpr 10 (aligned to 4)
+ in the parents outgoing area */
+ stw r3, 24+(0*4)(r1)
+ stw r4, 24+(1*4)(r1)
+ stw r5, 24+(2*4)(r1)
+ stw r6, 24+(3*4)(r1)
+ mflr r0
+
+ stw r7, 24+(4*4)(r1)
+ stw r8, 24+(5*4)(r1)
+ stw r9, 24+(6*4)(r1)
+ stw r10, 24+(7*4)(r1)
+ stw r0, 8(r1)
+LCFI..0:
+ /* 24 Bytes (Linkage Area) */
+ /* 32 Bytes (params) */
+ /* 16 Bytes (result) */
+ /* 104 Bytes (13*8 from FPR) */
+ /* 176 Bytes */
+
+ stwu r1, -176(r1) /* skip over caller save area
+ keep stack aligned to 16 */
+LCFI..1:
+
+ /* next save fpr 1 to fpr 13 (aligned to 8) */
+ stfd f1, 72+(0*8)(r1)
+ stfd f2, 72+(1*8)(r1)
+ stfd f3, 72+(2*8)(r1)
+ stfd f4, 72+(3*8)(r1)
+ stfd f5, 72+(4*8)(r1)
+ stfd f6, 72+(5*8)(r1)
+ stfd f7, 72+(6*8)(r1)
+ stfd f8, 72+(7*8)(r1)
+ stfd f9, 72+(8*8)(r1)
+ stfd f10, 72+(9*8)(r1)
+ stfd f11, 72+(10*8)(r1)
+ stfd f12, 72+(11*8)(r1)
+ stfd f13, 72+(12*8)(r1)
+
+ /* set up registers for the routine that actually does the work */
+ /* get the context pointer from the trampoline */
+ mr r3, r11
+
+ /* now load up the pointer to the result storage */
+ addi r4, r1, 56
+
+ /* now load up the pointer to the saved gpr registers */
+ addi r5, r1, 200
+
+ /* now load up the pointer to the saved fpr registers */
+ addi r6, r1, 72
+
+ /* make the call */
+ bl .ffi_closure_helper_DARWIN
+ nop
+
+.Ldoneclosure:
+
+ /* now r3 contains the return type */
+ /* so use it to look up in a table */
+ /* so we know how to deal with each type */
+
+ /* look up the proper starting point in table */
+ /* by using return type as offset */
+ lhz r3, 6(r3) /* load type from return type */
+ lwz r4, LC..60(2) /* get address of jump table */
+ slwi r3, r3, 4 /* now multiply return type by 16 */
+ lwz r0, 176+8(r1) /* load return address */
+ add r3, r3, r4 /* add contents of table to table address */
+ mtctr r3
+ bctr /* jump to it */
+
+/* Each fragment must be exactly 16 bytes long (4 instructions).
+ Align to 16 byte boundary for cache and dispatch efficiency. */
+ .align 4
+
+L..60:
+/* case FFI_TYPE_VOID */
+ mtlr r0
+ addi r1, r1, 176
+ blr
+ nop
+
+/* case FFI_TYPE_INT */
+ lwz r3, 56+0(r1)
+ mtlr r0
+ addi r1, r1, 176
+ blr
+
+/* case FFI_TYPE_FLOAT */
+ lfs f1, 56+0(r1)
+ mtlr r0
+ addi r1, r1, 176
+ blr
+
+/* case FFI_TYPE_DOUBLE */
+ lfd f1, 56+0(r1)
+ mtlr r0
+ addi r1, r1, 176
+ blr
+
+/* case FFI_TYPE_LONGDOUBLE */
+ lfd f1, 56+0(r1)
+ mtlr r0
+ lfd f2, 56+8(r1)
+ b L..finish
+
+/* case FFI_TYPE_UINT8 */
+ lbz r3, 56+3(r1)
+ mtlr r0
+ addi r1, r1, 176
+ blr
+
+/* case FFI_TYPE_SINT8 */
+ lbz r3, 56+3(r1)
+ mtlr r0
+ extsb r3, r3
+ b L..finish
+
+/* case FFI_TYPE_UINT16 */
+ lhz r3, 56+2(r1)
+ mtlr r0
+ addi r1, r1, 176
+ blr
+
+/* case FFI_TYPE_SINT16 */
+ lha r3, 56+2(r1)
+ mtlr r0
+ addi r1, r1, 176
+ blr
+
+/* case FFI_TYPE_UINT32 */
+ lwz r3, 56+0(r1)
+ mtlr r0
+ addi r1, r1, 176
+ blr
+
+/* case FFI_TYPE_SINT32 */
+ lwz r3, 56+0(r1)
+ mtlr r0
+ addi r1, r1, 176
+ blr
+
+/* case FFI_TYPE_UINT64 */
+ lwz r3, 56+0(r1)
+ mtlr r0
+ lwz r4, 56+4(r1)
+ b L..finish
+
+/* case FFI_TYPE_SINT64 */
+ lwz r3, 56+0(r1)
+ mtlr r0
+ lwz r4, 56+4(r1)
+ b L..finish
+
+/* case FFI_TYPE_STRUCT */
+ mtlr r0
+ addi r1, r1, 176
+ blr
+ nop
+
+/* case FFI_TYPE_POINTER */
+ lwz r3, 56+0(r1)
+ mtlr r0
+L..finish:
+ addi r1, r1, 176
+ blr
+LFE..0:
+#endif
+ .ef __LINE__
+/* END(ffi_closure_ASM) */
+
+
+.csect .text[PR]
+ .align 2
+ .globl ffi_go_closure_ASM
+ .globl .ffi_go_closure_ASM
+.csect ffi_go_closure_ASM[DS]
+ffi_go_closure_ASM:
+#ifdef __64BIT__
+ .llong .ffi_go_closure_ASM, TOC[tc0], 0
+ .csect .text[PR]
+.ffi_go_closure_ASM:
+ .function .ffi_go_closure_ASM,.ffi_go_closure_ASM,16,044,LFE..1-LFB..1
+ .bf __LINE__
+ .line 1
+LFB..1:
+/* we want to build up an area for the parameters passed */
+/* in registers (both floating point and integer) */
+
+ /* we store gpr 3 to gpr 10 (aligned to 4)
+ in the parents outgoing area */
+ std r3, 48+(0*8)(r1)
+ std r4, 48+(1*8)(r1)
+ std r5, 48+(2*8)(r1)
+ std r6, 48+(3*8)(r1)
+ mflr r0
+
+ std r7, 48+(4*8)(r1)
+ std r8, 48+(5*8)(r1)
+ std r9, 48+(6*8)(r1)
+ std r10, 48+(7*8)(r1)
+ std r0, 16(r1) /* save the return address */
+LCFI..2:
+ /* 48 Bytes (Linkage Area) */
+ /* 64 Bytes (params) */
+ /* 16 Bytes (result) */
+ /* 104 Bytes (13*8 from FPR) */
+ /* 8 Bytes (alignment) */
+ /* 240 Bytes */
+
+ stdu r1, -240(r1) /* skip over caller save area
+ keep stack aligned to 16 */
+LCFI..3:
+
+ /* next save fpr 1 to fpr 13 (aligned to 8) */
+ stfd f1, 128+(0*8)(r1)
+ stfd f2, 128+(1*8)(r1)
+ stfd f3, 128+(2*8)(r1)
+ stfd f4, 128+(3*8)(r1)
+ stfd f5, 128+(4*8)(r1)
+ stfd f6, 128+(5*8)(r1)
+ stfd f7, 128+(6*8)(r1)
+ stfd f8, 128+(7*8)(r1)
+ stfd f9, 128+(8*8)(r1)
+ stfd f10, 128+(9*8)(r1)
+ stfd f11, 128+(10*8)(r1)
+ stfd f12, 128+(11*8)(r1)
+ stfd f13, 128+(12*8)(r1)
+
+ /* set up registers for the routine that actually does the work */
+ mr r3, r11 /* go closure */
+
+ /* now load up the pointer to the result storage */
+ addi r4, r1, 112
+
+ /* now load up the pointer to the saved gpr registers */
+ addi r5, r1, 288
+
+ /* now load up the pointer to the saved fpr registers */
+ addi r6, r1, 128
+
+ /* make the call */
+ bl .ffi_go_closure_helper_DARWIN
+ nop
+
+ b .Ldoneclosure
+LFE..1:
+
+#else /* ! __64BIT__ */
+
+ .long .ffi_go_closure_ASM, TOC[tc0], 0
+ .csect .text[PR]
+.ffi_go_closure_ASM:
+ .function .ffi_go_closure_ASM,.ffi_go_closure_ASM,16,044,LFE..1-LFB..1
+ .bf __LINE__
+ .line 1
+LFB..1:
+/* we want to build up an area for the parameters passed */
+/* in registers (both floating point and integer) */
+
+ /* we store gpr 3 to gpr 10 (aligned to 4)
+ in the parents outgoing area */
+ stw r3, 24+(0*4)(r1)
+ stw r4, 24+(1*4)(r1)
+ stw r5, 24+(2*4)(r1)
+ stw r6, 24+(3*4)(r1)
+ mflr r0
+
+ stw r7, 24+(4*4)(r1)
+ stw r8, 24+(5*4)(r1)
+ stw r9, 24+(6*4)(r1)
+ stw r10, 24+(7*4)(r1)
+ stw r0, 8(r1)
+LCFI..2:
+ /* 24 Bytes (Linkage Area) */
+ /* 32 Bytes (params) */
+ /* 16 Bytes (result) */
+ /* 104 Bytes (13*8 from FPR) */
+ /* 176 Bytes */
+
+ stwu r1, -176(r1) /* skip over caller save area
+ keep stack aligned to 16 */
+LCFI..3:
+
+ /* next save fpr 1 to fpr 13 (aligned to 8) */
+ stfd f1, 72+(0*8)(r1)
+ stfd f2, 72+(1*8)(r1)
+ stfd f3, 72+(2*8)(r1)
+ stfd f4, 72+(3*8)(r1)
+ stfd f5, 72+(4*8)(r1)
+ stfd f6, 72+(5*8)(r1)
+ stfd f7, 72+(6*8)(r1)
+ stfd f8, 72+(7*8)(r1)
+ stfd f9, 72+(8*8)(r1)
+ stfd f10, 72+(9*8)(r1)
+ stfd f11, 72+(10*8)(r1)
+ stfd f12, 72+(11*8)(r1)
+ stfd f13, 72+(12*8)(r1)
+
+ /* set up registers for the routine that actually does the work */
+ mr r3, 11 /* go closure */
+
+ /* now load up the pointer to the result storage */
+ addi r4, r1, 56
+
+ /* now load up the pointer to the saved gpr registers */
+ addi r5, r1, 200
+
+ /* now load up the pointer to the saved fpr registers */
+ addi r6, r1, 72
+
+ /* make the call */
+ bl .ffi_go_closure_helper_DARWIN
+ nop
+
+ b .Ldoneclosure
+LFE..1:
+#endif
+ .ef __LINE__
+/* END(ffi_go_closure_ASM) */
+
+/* EH frame stuff. */
+
+#define LR_REGNO 0x41 /* Link Register (65), see rs6000.md */
+#ifdef __64BIT__
+#define PTRSIZE 8
+#define LOG2_PTRSIZE 3
+#define CFA_OFFSET 0xf0,0x01 /* LEB128 240 */
+#define FDE_ENCODING 0x1c /* DW_EH_PE_pcrel|DW_EH_PE_sdata8 */
+#define EH_DATA_ALIGN_FACT 0x78 /* LEB128 -8 */
+#else
+#define PTRSIZE 4
+#define LOG2_PTRSIZE 2
+#define CFA_OFFSET 0xb0,0x01 /* LEB128 176 */
+#define FDE_ENCODING 0x1b /* DW_EH_PE_pcrel|DW_EH_PE_sdata4 */
+#define EH_DATA_ALIGN_FACT 0x7c /* LEB128 -4 */
+#endif
+
+ .csect _unwind.ro_[RO],4
+ .align LOG2_PTRSIZE
+ .globl _GLOBAL__F_libffi_src_powerpc_aix_closure
+_GLOBAL__F_libffi_src_powerpc_aix_closure:
+Lframe..1:
+ .vbyte 4,LECIE..1-LSCIE..1 /* CIE Length */
+LSCIE..1:
+ .vbyte 4,0 /* CIE Identifier Tag */
+ .byte 0x3 /* CIE Version */
+ .byte "zR" /* CIE Augmentation */
+ .byte 0
+ .byte 0x1 /* uleb128 0x1; CIE Code Alignment Factor */
+ .byte EH_DATA_ALIGN_FACT /* leb128 -4/-8; CIE Data Alignment Factor */
+ .byte LR_REGNO /* CIE RA Column */
+ .byte 0x1 /* uleb128 0x1; Augmentation size */
+ .byte FDE_ENCODING /* FDE Encoding (pcrel|sdata4/8) */
+ .byte 0xc /* DW_CFA_def_cfa */
+ .byte 0x1 /* uleb128 0x1; Register r1 */
+ .byte 0 /* uleb128 0x0; Offset 0 */
+ .align LOG2_PTRSIZE
+LECIE..1:
+LSFDE..1:
+ .vbyte 4,LEFDE..1-LASFDE..1 /* FDE Length */
+LASFDE..1:
+ .vbyte 4,LASFDE..1-Lframe..1 /* FDE CIE offset */
+ .vbyte PTRSIZE,LFB..0-$ /* FDE initial location */
+ .vbyte PTRSIZE,LFE..0-LFB..0 /* FDE address range */
+ .byte 0 /* uleb128 0x0; Augmentation size */
+ .byte 0x4 /* DW_CFA_advance_loc4 */
+ .vbyte 4,LCFI..1-LCFI..0
+ .byte 0xe /* DW_CFA_def_cfa_offset */
+ .byte CFA_OFFSET /* uleb128 176/240 */
+ .byte 0x4 /* DW_CFA_advance_loc4 */
+ .vbyte 4,LCFI..0-LFB..0
+ .byte 0x11 /* DW_CFA_offset_extended_sf */
+ .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */
+ .byte 0x7e /* leb128 -2; Offset -2 (8/16) */
+ .align LOG2_PTRSIZE
+LEFDE..1:
+LSFDE..2:
+ .vbyte 4,LEFDE..2-LASFDE..2 /* FDE Length */
+LASFDE..2:
+ .vbyte 4,LASFDE..2-Lframe..1 /* FDE CIE offset */
+ .vbyte PTRSIZE,LFB..1-$ /* FDE initial location */
+ .vbyte PTRSIZE,LFE..1-LFB..1 /* FDE address range */
+ .byte 0 /* uleb128 0x0; Augmentation size */
+ .byte 0x4 /* DW_CFA_advance_loc4 */
+ .vbyte 4,LCFI..3-LCFI..2
+ .byte 0xe /* DW_CFA_def_cfa_offset */
+ .byte CFA_OFFSET /* uleb128 176/240 */
+ .byte 0x4 /* DW_CFA_advance_loc4 */
+ .vbyte 4,LCFI..2-LFB..1
+ .byte 0x11 /* DW_CFA_offset_extended_sf */
+ .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */
+ .byte 0x7e /* leb128 -2; Offset -2 (8/16) */
+ .align LOG2_PTRSIZE
+LEFDE..2:
+ .vbyte 4,0 /* End of FDEs */
+
+ .csect .text[PR]
+ .ref _GLOBAL__F_libffi_src_powerpc_aix_closure /* Prevents garbage collection by AIX linker */
+
diff --git a/contrib/restricted/libffi/src/powerpc/asm.h b/contrib/restricted/libffi/src/powerpc/asm.h
index 4f8a4b4c6b..27b22f670a 100644
--- a/contrib/restricted/libffi/src/powerpc/asm.h
+++ b/contrib/restricted/libffi/src/powerpc/asm.h
@@ -1,125 +1,125 @@
-/* -----------------------------------------------------------------------
- asm.h - Copyright (c) 1998 Geoffrey Keating
-
- PowerPC Assembly glue.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#define ASM_GLOBAL_DIRECTIVE .globl
-
-
-#define C_SYMBOL_NAME(name) name
-/* Macro for a label. */
-#ifdef __STDC__
-#define C_LABEL(name) name##:
-#else
-#define C_LABEL(name) name/**/:
-#endif
-
-/* This seems to always be the case on PPC. */
-#define ALIGNARG(log2) log2
-/* For ELF we need the `.type' directive to make shared libs work right. */
-#define ASM_TYPE_DIRECTIVE(name,typearg) .type name,typearg;
-#define ASM_SIZE_DIRECTIVE(name) .size name,.-name
-
-/* If compiled for profiling, call `_mcount' at the start of each function. */
-#ifdef PROF
-/* The mcount code relies on the return address being on the stack
- to locate our caller and so it can restore it; so store one just
- for its benefit. */
-#ifdef PIC
-#define CALL_MCOUNT \
- .pushsection; \
- .section ".data"; \
- .align ALIGNARG(2); \
-0:.long 0; \
- .previous; \
- mflr %r0; \
- stw %r0,4(%r1); \
- bl _GLOBAL_OFFSET_TABLE_@local-4; \
- mflr %r11; \
- lwz %r0,0b@got(%r11); \
- bl JUMPTARGET(_mcount);
-#else /* PIC */
-#define CALL_MCOUNT \
- .section ".data"; \
- .align ALIGNARG(2); \
-0:.long 0; \
- .previous; \
- mflr %r0; \
- lis %r11,0b@ha; \
- stw %r0,4(%r1); \
- addi %r0,%r11,0b@l; \
- bl JUMPTARGET(_mcount);
-#endif /* PIC */
-#else /* PROF */
-#define CALL_MCOUNT /* Do nothing. */
-#endif /* PROF */
-
-#define ENTRY(name) \
- ASM_GLOBAL_DIRECTIVE C_SYMBOL_NAME(name); \
- ASM_TYPE_DIRECTIVE (C_SYMBOL_NAME(name),@function) \
- .align ALIGNARG(2); \
- C_LABEL(name) \
- CALL_MCOUNT
-
-#define EALIGN_W_0 /* No words to insert. */
-#define EALIGN_W_1 nop
-#define EALIGN_W_2 nop;nop
-#define EALIGN_W_3 nop;nop;nop
-#define EALIGN_W_4 EALIGN_W_3;nop
-#define EALIGN_W_5 EALIGN_W_4;nop
-#define EALIGN_W_6 EALIGN_W_5;nop
-#define EALIGN_W_7 EALIGN_W_6;nop
-
-/* EALIGN is like ENTRY, but does alignment to 'words'*4 bytes
- past a 2^align boundary. */
-#ifdef PROF
-#define EFFI_ALIGN(name, alignt, words) \
- ASM_GLOBAL_DIRECTIVE C_SYMBOL_NAME(name); \
- ASM_TYPE_DIRECTIVE (C_SYMBOL_NAME(name),@function) \
- .align ALIGNARG(2); \
- C_LABEL(name) \
- CALL_MCOUNT \
- b 0f; \
- .align ALIGNARG(alignt); \
- EALIGN_W_##words; \
- 0:
-#else /* PROF */
-#define EFFI_ALIGN(name, alignt, words) \
- ASM_GLOBAL_DIRECTIVE C_SYMBOL_NAME(name); \
- ASM_TYPE_DIRECTIVE (C_SYMBOL_NAME(name),@function) \
- .align ALIGNARG(alignt); \
- EALIGN_W_##words; \
- C_LABEL(name)
-#endif
-
-#define END(name) \
- ASM_SIZE_DIRECTIVE(name)
-
-#ifdef PIC
-#define JUMPTARGET(name) name##@plt
-#else
-#define JUMPTARGET(name) name
-#endif
-
-/* Local labels stripped out by the linker. */
-#define L(x) .L##x
+/* -----------------------------------------------------------------------
+ asm.h - Copyright (c) 1998 Geoffrey Keating
+
+ PowerPC Assembly glue.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#define ASM_GLOBAL_DIRECTIVE .globl
+
+
+#define C_SYMBOL_NAME(name) name
+/* Macro for a label. */
+#ifdef __STDC__
+#define C_LABEL(name) name##:
+#else
+#define C_LABEL(name) name/**/:
+#endif
+
+/* This seems to always be the case on PPC. */
+#define ALIGNARG(log2) log2
+/* For ELF we need the `.type' directive to make shared libs work right. */
+#define ASM_TYPE_DIRECTIVE(name,typearg) .type name,typearg;
+#define ASM_SIZE_DIRECTIVE(name) .size name,.-name
+
+/* If compiled for profiling, call `_mcount' at the start of each function. */
+#ifdef PROF
+/* The mcount code relies on the return address being on the stack
+ to locate our caller and so it can restore it; so store one just
+ for its benefit. */
+#ifdef PIC
+#define CALL_MCOUNT \
+ .pushsection; \
+ .section ".data"; \
+ .align ALIGNARG(2); \
+0:.long 0; \
+ .previous; \
+ mflr %r0; \
+ stw %r0,4(%r1); \
+ bl _GLOBAL_OFFSET_TABLE_@local-4; \
+ mflr %r11; \
+ lwz %r0,0b@got(%r11); \
+ bl JUMPTARGET(_mcount);
+#else /* PIC */
+#define CALL_MCOUNT \
+ .section ".data"; \
+ .align ALIGNARG(2); \
+0:.long 0; \
+ .previous; \
+ mflr %r0; \
+ lis %r11,0b@ha; \
+ stw %r0,4(%r1); \
+ addi %r0,%r11,0b@l; \
+ bl JUMPTARGET(_mcount);
+#endif /* PIC */
+#else /* PROF */
+#define CALL_MCOUNT /* Do nothing. */
+#endif /* PROF */
+
+#define ENTRY(name) \
+ ASM_GLOBAL_DIRECTIVE C_SYMBOL_NAME(name); \
+ ASM_TYPE_DIRECTIVE (C_SYMBOL_NAME(name),@function) \
+ .align ALIGNARG(2); \
+ C_LABEL(name) \
+ CALL_MCOUNT
+
+#define EALIGN_W_0 /* No words to insert. */
+#define EALIGN_W_1 nop
+#define EALIGN_W_2 nop;nop
+#define EALIGN_W_3 nop;nop;nop
+#define EALIGN_W_4 EALIGN_W_3;nop
+#define EALIGN_W_5 EALIGN_W_4;nop
+#define EALIGN_W_6 EALIGN_W_5;nop
+#define EALIGN_W_7 EALIGN_W_6;nop
+
+/* EALIGN is like ENTRY, but does alignment to 'words'*4 bytes
+ past a 2^align boundary. */
+#ifdef PROF
+#define EFFI_ALIGN(name, alignt, words) \
+ ASM_GLOBAL_DIRECTIVE C_SYMBOL_NAME(name); \
+ ASM_TYPE_DIRECTIVE (C_SYMBOL_NAME(name),@function) \
+ .align ALIGNARG(2); \
+ C_LABEL(name) \
+ CALL_MCOUNT \
+ b 0f; \
+ .align ALIGNARG(alignt); \
+ EALIGN_W_##words; \
+ 0:
+#else /* PROF */
+#define EFFI_ALIGN(name, alignt, words) \
+ ASM_GLOBAL_DIRECTIVE C_SYMBOL_NAME(name); \
+ ASM_TYPE_DIRECTIVE (C_SYMBOL_NAME(name),@function) \
+ .align ALIGNARG(alignt); \
+ EALIGN_W_##words; \
+ C_LABEL(name)
+#endif
+
+#define END(name) \
+ ASM_SIZE_DIRECTIVE(name)
+
+#ifdef PIC
+#define JUMPTARGET(name) name##@plt
+#else
+#define JUMPTARGET(name) name
+#endif
+
+/* Local labels stripped out by the linker. */
+#define L(x) .L##x
diff --git a/contrib/restricted/libffi/src/powerpc/darwin.S b/contrib/restricted/libffi/src/powerpc/darwin.S
index 5012ffba65..066eb82efe 100644
--- a/contrib/restricted/libffi/src/powerpc/darwin.S
+++ b/contrib/restricted/libffi/src/powerpc/darwin.S
@@ -1,378 +1,378 @@
-/* -----------------------------------------------------------------------
- darwin.S - Copyright (c) 2000 John Hornkvist
- Copyright (c) 2004, 2010 Free Software Foundation, Inc.
-
- PowerPC Assembly glue.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#define LIBFFI_ASM
-#if defined(__ppc64__)
-#define MODE_CHOICE(x, y) y
-#else
-#define MODE_CHOICE(x, y) x
-#endif
-
-#define machine_choice MODE_CHOICE(ppc7400,ppc64)
-
-; Define some pseudo-opcodes for size-independent load & store of GPRs ...
-#define lgu MODE_CHOICE(lwzu, ldu)
-#define lg MODE_CHOICE(lwz,ld)
-#define sg MODE_CHOICE(stw,std)
-#define sgu MODE_CHOICE(stwu,stdu)
-#define sgux MODE_CHOICE(stwux,stdux)
-
-; ... and the size of GPRs and their storage indicator.
-#define GPR_BYTES MODE_CHOICE(4,8)
-#define LOG2_GPR_BYTES MODE_CHOICE(2,3) /* log2(GPR_BYTES) */
-#define g_long MODE_CHOICE(long, quad) /* usage is ".g_long" */
-
-; From the ABI doc: "Mac OS X ABI Function Call Guide" Version 2009-02-04.
-#define LINKAGE_SIZE MODE_CHOICE(24,48)
-#define PARAM_AREA MODE_CHOICE(32,64)
-#define SAVED_LR_OFFSET MODE_CHOICE(8,16) /* save position for lr */
-
-/* If there is any FP stuff we make space for all of the regs. */
-#define SAVED_FPR_COUNT 13
-#define FPR_SIZE 8
-#define RESULT_BYTES 16
-
-/* This should be kept in step with the same value in ffi_darwin.c. */
-#define ASM_NEEDS_REGISTERS 4
-#define SAVE_REGS_SIZE (ASM_NEEDS_REGISTERS * GPR_BYTES)
-
-#include <fficonfig.h>
-#include <ffi.h>
-
-#define JUMPTARGET(name) name
-#define L(x) x
-
- .text
- .align 2
- .globl _ffi_prep_args
-
- .align 2
- .globl _ffi_call_DARWIN
-
- /* We arrive here with:
- r3 = ptr to extended cif.
- r4 = -bytes.
- r5 = cif flags.
- r6 = ptr to return value.
- r7 = fn pointer (user func).
- r8 = fn pointer (ffi_prep_args).
- r9 = ffi_type* for the ret val. */
-
-_ffi_call_DARWIN:
-Lstartcode:
- mr r12,r8 /* We only need r12 until the call,
- so it does not have to be saved. */
-LFB1:
- /* Save the old stack pointer as AP. */
- mr r8,r1
-LCFI0:
-
- /* Save the retval type in parents frame. */
- sg r9,(LINKAGE_SIZE+6*GPR_BYTES)(r8)
-
- /* Allocate the stack space we need. */
- sgux r1,r1,r4
-
- /* Save registers we use. */
- mflr r9
- sg r9,SAVED_LR_OFFSET(r8)
-
- sg r28,-(4 * GPR_BYTES)(r8)
- sg r29,-(3 * GPR_BYTES)(r8)
- sg r30,-(2 * GPR_BYTES)(r8)
- sg r31,-( GPR_BYTES)(r8)
-
-#if !defined(POWERPC_DARWIN)
- /* The TOC slot is reserved in the Darwin ABI and r2 is volatile. */
- sg r2,(5 * GPR_BYTES)(r1)
-#endif
-
-LCFI1:
-
- /* Save arguments over call. */
- mr r31,r5 /* flags, */
- mr r30,r6 /* rvalue, */
- mr r29,r7 /* function address, */
- mr r28,r8 /* our AP. */
-LCFI2:
- /* Call ffi_prep_args. r3 = extended cif, r4 = stack ptr copy. */
- mr r4,r1
- li r9,0
-
- mtctr r12 /* r12 holds address of _ffi_prep_args. */
- bctrl
-
-#if !defined(POWERPC_DARWIN)
- /* The TOC slot is reserved in the Darwin ABI and r2 is volatile. */
- lg r2,(5 * GPR_BYTES)(r1)
-#endif
- /* Now do the call.
- Set up cr1 with bits 4-7 of the flags. */
- mtcrf 0x40,r31
- /* Get the address to call into CTR. */
- mtctr r29
- /* Load all those argument registers.
- We have set up a nice stack frame, just load it into registers. */
- lg r3, (LINKAGE_SIZE )(r1)
- lg r4, (LINKAGE_SIZE + GPR_BYTES)(r1)
- lg r5, (LINKAGE_SIZE + 2 * GPR_BYTES)(r1)
- lg r6, (LINKAGE_SIZE + 3 * GPR_BYTES)(r1)
- nop
- lg r7, (LINKAGE_SIZE + 4 * GPR_BYTES)(r1)
- lg r8, (LINKAGE_SIZE + 5 * GPR_BYTES)(r1)
- lg r9, (LINKAGE_SIZE + 6 * GPR_BYTES)(r1)
- lg r10,(LINKAGE_SIZE + 7 * GPR_BYTES)(r1)
-
-L1:
- /* ... Load all the FP registers. */
- bf 6,L2 /* No floats to load. */
- lfd f1, -SAVE_REGS_SIZE-(13*FPR_SIZE)(r28)
- lfd f2, -SAVE_REGS_SIZE-(12*FPR_SIZE)(r28)
- lfd f3, -SAVE_REGS_SIZE-(11*FPR_SIZE)(r28)
- lfd f4, -SAVE_REGS_SIZE-(10*FPR_SIZE)(r28)
- nop
- lfd f5, -SAVE_REGS_SIZE-( 9*FPR_SIZE)(r28)
- lfd f6, -SAVE_REGS_SIZE-( 8*FPR_SIZE)(r28)
- lfd f7, -SAVE_REGS_SIZE-( 7*FPR_SIZE)(r28)
- lfd f8, -SAVE_REGS_SIZE-( 6*FPR_SIZE)(r28)
- nop
- lfd f9, -SAVE_REGS_SIZE-( 5*FPR_SIZE)(r28)
- lfd f10,-SAVE_REGS_SIZE-( 4*FPR_SIZE)(r28)
- lfd f11,-SAVE_REGS_SIZE-( 3*FPR_SIZE)(r28)
- lfd f12,-SAVE_REGS_SIZE-( 2*FPR_SIZE)(r28)
- nop
- lfd f13,-SAVE_REGS_SIZE-( 1*FPR_SIZE)(r28)
-
-L2:
- mr r12,r29 /* Put the target address in r12 as specified. */
- mtctr r12
- nop
- nop
-
- /* Make the call. */
- bctrl
-
- /* Now, deal with the return value. */
-
- /* m64 structure returns can occupy the same set of registers as
- would be used to pass such a structure as arg0 - so take care
- not to step on any possibly hot regs. */
-
- /* Get the flags.. */
- mtcrf 0x03,r31 ; we need c6 & cr7 now.
- ; FLAG_RETURNS_NOTHING also covers struct ret-by-ref.
- bt 30,L(done_return_value) ; FLAG_RETURNS_NOTHING
- bf 27,L(scalar_return_value) ; not FLAG_RETURNS_STRUCT
-
- /* OK, so we have a struct. */
-#if defined(__ppc64__)
- bt 31,L(maybe_return_128) ; FLAG_RETURNS_128BITS, special case
-
- /* OK, we have to map the return back to a mem struct.
- We are about to trample the parents param area, so recover the
- return type. r29 is free, since the call is done. */
- lg r29,(LINKAGE_SIZE + 6 * GPR_BYTES)(r28)
-
- sg r3, (LINKAGE_SIZE )(r28)
- sg r4, (LINKAGE_SIZE + GPR_BYTES)(r28)
- sg r5, (LINKAGE_SIZE + 2 * GPR_BYTES)(r28)
- sg r6, (LINKAGE_SIZE + 3 * GPR_BYTES)(r28)
- nop
- sg r7, (LINKAGE_SIZE + 4 * GPR_BYTES)(r28)
- sg r8, (LINKAGE_SIZE + 5 * GPR_BYTES)(r28)
- sg r9, (LINKAGE_SIZE + 6 * GPR_BYTES)(r28)
- sg r10,(LINKAGE_SIZE + 7 * GPR_BYTES)(r28)
- /* OK, so do the block move - we trust that memcpy will not trample
- the fprs... */
- mr r3,r30 ; dest
- addi r4,r28,LINKAGE_SIZE ; source
- /* The size is a size_t, should be long. */
- lg r5,0(r29)
- /* Figure out small structs */
- cmpi 0,r5,4
- bgt L3 ; 1, 2 and 4 bytes have special rules.
- cmpi 0,r5,3
- beq L3 ; not 3
- addi r4,r4,8
- subf r4,r5,r4
-L3:
- bl _memcpy
-
- /* ... do we need the FP registers? - recover the flags.. */
- mtcrf 0x03,r31 ; we need c6 & cr7 now.
- bf 29,L(done_return_value) /* No floats in the struct. */
- stfd f1, -SAVE_REGS_SIZE-(13*FPR_SIZE)(r28)
- stfd f2, -SAVE_REGS_SIZE-(12*FPR_SIZE)(r28)
- stfd f3, -SAVE_REGS_SIZE-(11*FPR_SIZE)(r28)
- stfd f4, -SAVE_REGS_SIZE-(10*FPR_SIZE)(r28)
- nop
- stfd f5, -SAVE_REGS_SIZE-( 9*FPR_SIZE)(r28)
- stfd f6, -SAVE_REGS_SIZE-( 8*FPR_SIZE)(r28)
- stfd f7, -SAVE_REGS_SIZE-( 7*FPR_SIZE)(r28)
- stfd f8, -SAVE_REGS_SIZE-( 6*FPR_SIZE)(r28)
- nop
- stfd f9, -SAVE_REGS_SIZE-( 5*FPR_SIZE)(r28)
- stfd f10,-SAVE_REGS_SIZE-( 4*FPR_SIZE)(r28)
- stfd f11,-SAVE_REGS_SIZE-( 3*FPR_SIZE)(r28)
- stfd f12,-SAVE_REGS_SIZE-( 2*FPR_SIZE)(r28)
- nop
- stfd f13,-SAVE_REGS_SIZE-( 1*FPR_SIZE)(r28)
-
- mr r3,r29 ; ffi_type *
- mr r4,r30 ; dest
- addi r5,r28,-SAVE_REGS_SIZE-(13*FPR_SIZE) ; fprs
- xor r6,r6,r6
- sg r6,(LINKAGE_SIZE + 7 * GPR_BYTES)(r28)
- addi r6,r28,(LINKAGE_SIZE + 7 * GPR_BYTES) ; point to a zeroed counter.
- bl _darwin64_struct_floats_to_mem
-
- b L(done_return_value)
-#else
- stw r3,0(r30) ; m32 the only struct return in reg is 4 bytes.
-#endif
- b L(done_return_value)
-
-L(fp_return_value):
- /* Do we have long double to store? */
- bf 31,L(fd_return_value) ; FLAG_RETURNS_128BITS
- stfd f1,0(r30)
- stfd f2,FPR_SIZE(r30)
- b L(done_return_value)
-
-L(fd_return_value):
- /* Do we have double to store? */
- bf 28,L(float_return_value)
- stfd f1,0(r30)
- b L(done_return_value)
-
-L(float_return_value):
- /* We only have a float to store. */
- stfs f1,0(r30)
- b L(done_return_value)
-
-L(scalar_return_value):
- bt 29,L(fp_return_value) ; FLAG_RETURNS_FP
- ; ffi_arg is defined as unsigned long.
- sg r3,0(r30) ; Save the reg.
- bf 28,L(done_return_value) ; not FLAG_RETURNS_64BITS
-
-#if defined(__ppc64__)
-L(maybe_return_128):
- std r3,0(r30)
- bf 31,L(done_return_value) ; not FLAG_RETURNS_128BITS
- std r4,8(r30)
-#else
- stw r4,4(r30)
-#endif
-
- /* Fall through. */
- /* We want this at the end to simplify eh epilog computation. */
-
-L(done_return_value):
- /* Restore the registers we used and return. */
- lg r29,SAVED_LR_OFFSET(r28)
- ; epilog
- lg r31,-(1 * GPR_BYTES)(r28)
- mtlr r29
- lg r30,-(2 * GPR_BYTES)(r28)
- lg r29,-(3 * GPR_BYTES)(r28)
- lg r28,-(4 * GPR_BYTES)(r28)
- lg r1,0(r1)
- blr
-LFE1:
- .align 1
-/* END(_ffi_call_DARWIN) */
-
-/* Provide a null definition of _ffi_call_AIX. */
- .text
- .globl _ffi_call_AIX
- .align 2
-_ffi_call_AIX:
- blr
-/* END(_ffi_call_AIX) */
-
-/* EH stuff. */
-
-#define EH_DATA_ALIGN_FACT MODE_CHOICE(0x7c,0x78)
-
- .section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
-EH_frame1:
- .set L$set$0,LECIE1-LSCIE1
- .long L$set$0 ; Length of Common Information Entry
-LSCIE1:
- .long 0x0 ; CIE Identifier Tag
- .byte 0x1 ; CIE Version
- .ascii "zR\0" ; CIE Augmentation
- .byte 0x1 ; uleb128 0x1; CIE Code Alignment Factor
- .byte EH_DATA_ALIGN_FACT ; sleb128 -4; CIE Data Alignment Factor
- .byte 0x41 ; CIE RA Column
- .byte 0x1 ; uleb128 0x1; Augmentation size
- .byte 0x10 ; FDE Encoding (pcrel)
- .byte 0xc ; DW_CFA_def_cfa
- .byte 0x1 ; uleb128 0x1
- .byte 0x0 ; uleb128 0x0
- .align LOG2_GPR_BYTES
-LECIE1:
-
- .globl _ffi_call_DARWIN.eh
-_ffi_call_DARWIN.eh:
-LSFDE1:
- .set L$set$1,LEFDE1-LASFDE1
- .long L$set$1 ; FDE Length
-LASFDE1:
- .long LASFDE1-EH_frame1 ; FDE CIE offset
- .g_long Lstartcode-. ; FDE initial location
- .set L$set$3,LFE1-Lstartcode
- .g_long L$set$3 ; FDE address range
- .byte 0x0 ; uleb128 0x0; Augmentation size
- .byte 0x4 ; DW_CFA_advance_loc4
- .set L$set$4,LCFI0-Lstartcode
- .long L$set$4
- .byte 0xd ; DW_CFA_def_cfa_register
- .byte 0x08 ; uleb128 0x08
- .byte 0x4 ; DW_CFA_advance_loc4
- .set L$set$5,LCFI1-LCFI0
- .long L$set$5
- .byte 0x11 ; DW_CFA_offset_extended_sf
- .byte 0x41 ; uleb128 0x41
- .byte 0x7e ; sleb128 -2
- .byte 0x9f ; DW_CFA_offset, column 0x1f
- .byte 0x1 ; uleb128 0x1
- .byte 0x9e ; DW_CFA_offset, column 0x1e
- .byte 0x2 ; uleb128 0x2
- .byte 0x9d ; DW_CFA_offset, column 0x1d
- .byte 0x3 ; uleb128 0x3
- .byte 0x9c ; DW_CFA_offset, column 0x1c
- .byte 0x4 ; uleb128 0x4
- .byte 0x4 ; DW_CFA_advance_loc4
- .set L$set$6,LCFI2-LCFI1
- .long L$set$6
- .byte 0xd ; DW_CFA_def_cfa_register
- .byte 0x1c ; uleb128 0x1c
- .align LOG2_GPR_BYTES
-LEFDE1:
- .align 1
-
+/* -----------------------------------------------------------------------
+ darwin.S - Copyright (c) 2000 John Hornkvist
+ Copyright (c) 2004, 2010 Free Software Foundation, Inc.
+
+ PowerPC Assembly glue.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#define LIBFFI_ASM
+#if defined(__ppc64__)
+#define MODE_CHOICE(x, y) y
+#else
+#define MODE_CHOICE(x, y) x
+#endif
+
+#define machine_choice MODE_CHOICE(ppc7400,ppc64)
+
+; Define some pseudo-opcodes for size-independent load & store of GPRs ...
+#define lgu MODE_CHOICE(lwzu, ldu)
+#define lg MODE_CHOICE(lwz,ld)
+#define sg MODE_CHOICE(stw,std)
+#define sgu MODE_CHOICE(stwu,stdu)
+#define sgux MODE_CHOICE(stwux,stdux)
+
+; ... and the size of GPRs and their storage indicator.
+#define GPR_BYTES MODE_CHOICE(4,8)
+#define LOG2_GPR_BYTES MODE_CHOICE(2,3) /* log2(GPR_BYTES) */
+#define g_long MODE_CHOICE(long, quad) /* usage is ".g_long" */
+
+; From the ABI doc: "Mac OS X ABI Function Call Guide" Version 2009-02-04.
+#define LINKAGE_SIZE MODE_CHOICE(24,48)
+#define PARAM_AREA MODE_CHOICE(32,64)
+#define SAVED_LR_OFFSET MODE_CHOICE(8,16) /* save position for lr */
+
+/* If there is any FP stuff we make space for all of the regs. */
+#define SAVED_FPR_COUNT 13
+#define FPR_SIZE 8
+#define RESULT_BYTES 16
+
+/* This should be kept in step with the same value in ffi_darwin.c. */
+#define ASM_NEEDS_REGISTERS 4
+#define SAVE_REGS_SIZE (ASM_NEEDS_REGISTERS * GPR_BYTES)
+
+#include <fficonfig.h>
+#include <ffi.h>
+
+#define JUMPTARGET(name) name
+#define L(x) x
+
+ .text
+ .align 2
+ .globl _ffi_prep_args
+
+ .align 2
+ .globl _ffi_call_DARWIN
+
+ /* We arrive here with:
+ r3 = ptr to extended cif.
+ r4 = -bytes.
+ r5 = cif flags.
+ r6 = ptr to return value.
+ r7 = fn pointer (user func).
+ r8 = fn pointer (ffi_prep_args).
+ r9 = ffi_type* for the ret val. */
+
+_ffi_call_DARWIN:
+Lstartcode:
+ mr r12,r8 /* We only need r12 until the call,
+ so it does not have to be saved. */
+LFB1:
+ /* Save the old stack pointer as AP. */
+ mr r8,r1
+LCFI0:
+
+ /* Save the retval type in parents frame. */
+ sg r9,(LINKAGE_SIZE+6*GPR_BYTES)(r8)
+
+ /* Allocate the stack space we need. */
+ sgux r1,r1,r4
+
+ /* Save registers we use. */
+ mflr r9
+ sg r9,SAVED_LR_OFFSET(r8)
+
+ sg r28,-(4 * GPR_BYTES)(r8)
+ sg r29,-(3 * GPR_BYTES)(r8)
+ sg r30,-(2 * GPR_BYTES)(r8)
+ sg r31,-( GPR_BYTES)(r8)
+
+#if !defined(POWERPC_DARWIN)
+ /* The TOC slot is reserved in the Darwin ABI and r2 is volatile. */
+ sg r2,(5 * GPR_BYTES)(r1)
+#endif
+
+LCFI1:
+
+ /* Save arguments over call. */
+ mr r31,r5 /* flags, */
+ mr r30,r6 /* rvalue, */
+ mr r29,r7 /* function address, */
+ mr r28,r8 /* our AP. */
+LCFI2:
+ /* Call ffi_prep_args. r3 = extended cif, r4 = stack ptr copy. */
+ mr r4,r1
+ li r9,0
+
+ mtctr r12 /* r12 holds address of _ffi_prep_args. */
+ bctrl
+
+#if !defined(POWERPC_DARWIN)
+ /* The TOC slot is reserved in the Darwin ABI and r2 is volatile. */
+ lg r2,(5 * GPR_BYTES)(r1)
+#endif
+ /* Now do the call.
+ Set up cr1 with bits 4-7 of the flags. */
+ mtcrf 0x40,r31
+ /* Get the address to call into CTR. */
+ mtctr r29
+ /* Load all those argument registers.
+ We have set up a nice stack frame, just load it into registers. */
+ lg r3, (LINKAGE_SIZE )(r1)
+ lg r4, (LINKAGE_SIZE + GPR_BYTES)(r1)
+ lg r5, (LINKAGE_SIZE + 2 * GPR_BYTES)(r1)
+ lg r6, (LINKAGE_SIZE + 3 * GPR_BYTES)(r1)
+ nop
+ lg r7, (LINKAGE_SIZE + 4 * GPR_BYTES)(r1)
+ lg r8, (LINKAGE_SIZE + 5 * GPR_BYTES)(r1)
+ lg r9, (LINKAGE_SIZE + 6 * GPR_BYTES)(r1)
+ lg r10,(LINKAGE_SIZE + 7 * GPR_BYTES)(r1)
+
+L1:
+ /* ... Load all the FP registers. */
+ bf 6,L2 /* No floats to load. */
+ lfd f1, -SAVE_REGS_SIZE-(13*FPR_SIZE)(r28)
+ lfd f2, -SAVE_REGS_SIZE-(12*FPR_SIZE)(r28)
+ lfd f3, -SAVE_REGS_SIZE-(11*FPR_SIZE)(r28)
+ lfd f4, -SAVE_REGS_SIZE-(10*FPR_SIZE)(r28)
+ nop
+ lfd f5, -SAVE_REGS_SIZE-( 9*FPR_SIZE)(r28)
+ lfd f6, -SAVE_REGS_SIZE-( 8*FPR_SIZE)(r28)
+ lfd f7, -SAVE_REGS_SIZE-( 7*FPR_SIZE)(r28)
+ lfd f8, -SAVE_REGS_SIZE-( 6*FPR_SIZE)(r28)
+ nop
+ lfd f9, -SAVE_REGS_SIZE-( 5*FPR_SIZE)(r28)
+ lfd f10,-SAVE_REGS_SIZE-( 4*FPR_SIZE)(r28)
+ lfd f11,-SAVE_REGS_SIZE-( 3*FPR_SIZE)(r28)
+ lfd f12,-SAVE_REGS_SIZE-( 2*FPR_SIZE)(r28)
+ nop
+ lfd f13,-SAVE_REGS_SIZE-( 1*FPR_SIZE)(r28)
+
+L2:
+ mr r12,r29 /* Put the target address in r12 as specified. */
+ mtctr r12
+ nop
+ nop
+
+ /* Make the call. */
+ bctrl
+
+ /* Now, deal with the return value. */
+
+ /* m64 structure returns can occupy the same set of registers as
+ would be used to pass such a structure as arg0 - so take care
+ not to step on any possibly hot regs. */
+
+ /* Get the flags.. */
+ mtcrf 0x03,r31 ; we need c6 & cr7 now.
+ ; FLAG_RETURNS_NOTHING also covers struct ret-by-ref.
+ bt 30,L(done_return_value) ; FLAG_RETURNS_NOTHING
+ bf 27,L(scalar_return_value) ; not FLAG_RETURNS_STRUCT
+
+ /* OK, so we have a struct. */
+#if defined(__ppc64__)
+ bt 31,L(maybe_return_128) ; FLAG_RETURNS_128BITS, special case
+
+ /* OK, we have to map the return back to a mem struct.
+ We are about to trample the parents param area, so recover the
+ return type. r29 is free, since the call is done. */
+ lg r29,(LINKAGE_SIZE + 6 * GPR_BYTES)(r28)
+
+ sg r3, (LINKAGE_SIZE )(r28)
+ sg r4, (LINKAGE_SIZE + GPR_BYTES)(r28)
+ sg r5, (LINKAGE_SIZE + 2 * GPR_BYTES)(r28)
+ sg r6, (LINKAGE_SIZE + 3 * GPR_BYTES)(r28)
+ nop
+ sg r7, (LINKAGE_SIZE + 4 * GPR_BYTES)(r28)
+ sg r8, (LINKAGE_SIZE + 5 * GPR_BYTES)(r28)
+ sg r9, (LINKAGE_SIZE + 6 * GPR_BYTES)(r28)
+ sg r10,(LINKAGE_SIZE + 7 * GPR_BYTES)(r28)
+ /* OK, so do the block move - we trust that memcpy will not trample
+ the fprs... */
+ mr r3,r30 ; dest
+ addi r4,r28,LINKAGE_SIZE ; source
+ /* The size is a size_t, should be long. */
+ lg r5,0(r29)
+ /* Figure out small structs */
+ cmpi 0,r5,4
+ bgt L3 ; 1, 2 and 4 bytes have special rules.
+ cmpi 0,r5,3
+ beq L3 ; not 3
+ addi r4,r4,8
+ subf r4,r5,r4
+L3:
+ bl _memcpy
+
+ /* ... do we need the FP registers? - recover the flags.. */
+ mtcrf 0x03,r31 ; we need c6 & cr7 now.
+ bf 29,L(done_return_value) /* No floats in the struct. */
+ stfd f1, -SAVE_REGS_SIZE-(13*FPR_SIZE)(r28)
+ stfd f2, -SAVE_REGS_SIZE-(12*FPR_SIZE)(r28)
+ stfd f3, -SAVE_REGS_SIZE-(11*FPR_SIZE)(r28)
+ stfd f4, -SAVE_REGS_SIZE-(10*FPR_SIZE)(r28)
+ nop
+ stfd f5, -SAVE_REGS_SIZE-( 9*FPR_SIZE)(r28)
+ stfd f6, -SAVE_REGS_SIZE-( 8*FPR_SIZE)(r28)
+ stfd f7, -SAVE_REGS_SIZE-( 7*FPR_SIZE)(r28)
+ stfd f8, -SAVE_REGS_SIZE-( 6*FPR_SIZE)(r28)
+ nop
+ stfd f9, -SAVE_REGS_SIZE-( 5*FPR_SIZE)(r28)
+ stfd f10,-SAVE_REGS_SIZE-( 4*FPR_SIZE)(r28)
+ stfd f11,-SAVE_REGS_SIZE-( 3*FPR_SIZE)(r28)
+ stfd f12,-SAVE_REGS_SIZE-( 2*FPR_SIZE)(r28)
+ nop
+ stfd f13,-SAVE_REGS_SIZE-( 1*FPR_SIZE)(r28)
+
+ mr r3,r29 ; ffi_type *
+ mr r4,r30 ; dest
+ addi r5,r28,-SAVE_REGS_SIZE-(13*FPR_SIZE) ; fprs
+ xor r6,r6,r6
+ sg r6,(LINKAGE_SIZE + 7 * GPR_BYTES)(r28)
+ addi r6,r28,(LINKAGE_SIZE + 7 * GPR_BYTES) ; point to a zeroed counter.
+ bl _darwin64_struct_floats_to_mem
+
+ b L(done_return_value)
+#else
+ stw r3,0(r30) ; m32 the only struct return in reg is 4 bytes.
+#endif
+ b L(done_return_value)
+
+L(fp_return_value):
+ /* Do we have long double to store? */
+ bf 31,L(fd_return_value) ; FLAG_RETURNS_128BITS
+ stfd f1,0(r30)
+ stfd f2,FPR_SIZE(r30)
+ b L(done_return_value)
+
+L(fd_return_value):
+ /* Do we have double to store? */
+ bf 28,L(float_return_value)
+ stfd f1,0(r30)
+ b L(done_return_value)
+
+L(float_return_value):
+ /* We only have a float to store. */
+ stfs f1,0(r30)
+ b L(done_return_value)
+
+L(scalar_return_value):
+ bt 29,L(fp_return_value) ; FLAG_RETURNS_FP
+ ; ffi_arg is defined as unsigned long.
+ sg r3,0(r30) ; Save the reg.
+ bf 28,L(done_return_value) ; not FLAG_RETURNS_64BITS
+
+#if defined(__ppc64__)
+L(maybe_return_128):
+ std r3,0(r30)
+ bf 31,L(done_return_value) ; not FLAG_RETURNS_128BITS
+ std r4,8(r30)
+#else
+ stw r4,4(r30)
+#endif
+
+ /* Fall through. */
+ /* We want this at the end to simplify eh epilog computation. */
+
+L(done_return_value):
+ /* Restore the registers we used and return. */
+ lg r29,SAVED_LR_OFFSET(r28)
+ ; epilog
+ lg r31,-(1 * GPR_BYTES)(r28)
+ mtlr r29
+ lg r30,-(2 * GPR_BYTES)(r28)
+ lg r29,-(3 * GPR_BYTES)(r28)
+ lg r28,-(4 * GPR_BYTES)(r28)
+ lg r1,0(r1)
+ blr
+LFE1:
+ .align 1
+/* END(_ffi_call_DARWIN) */
+
+/* Provide a null definition of _ffi_call_AIX. */
+ .text
+ .globl _ffi_call_AIX
+ .align 2
+_ffi_call_AIX:
+ blr
+/* END(_ffi_call_AIX) */
+
+/* EH stuff. */
+
+#define EH_DATA_ALIGN_FACT MODE_CHOICE(0x7c,0x78)
+
+ .section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
+EH_frame1:
+ .set L$set$0,LECIE1-LSCIE1
+ .long L$set$0 ; Length of Common Information Entry
+LSCIE1:
+ .long 0x0 ; CIE Identifier Tag
+ .byte 0x1 ; CIE Version
+ .ascii "zR\0" ; CIE Augmentation
+ .byte 0x1 ; uleb128 0x1; CIE Code Alignment Factor
+ .byte EH_DATA_ALIGN_FACT ; sleb128 -4; CIE Data Alignment Factor
+ .byte 0x41 ; CIE RA Column
+ .byte 0x1 ; uleb128 0x1; Augmentation size
+ .byte 0x10 ; FDE Encoding (pcrel)
+ .byte 0xc ; DW_CFA_def_cfa
+ .byte 0x1 ; uleb128 0x1
+ .byte 0x0 ; uleb128 0x0
+ .align LOG2_GPR_BYTES
+LECIE1:
+
+ .globl _ffi_call_DARWIN.eh
+_ffi_call_DARWIN.eh:
+LSFDE1:
+ .set L$set$1,LEFDE1-LASFDE1
+ .long L$set$1 ; FDE Length
+LASFDE1:
+ .long LASFDE1-EH_frame1 ; FDE CIE offset
+ .g_long Lstartcode-. ; FDE initial location
+ .set L$set$3,LFE1-Lstartcode
+ .g_long L$set$3 ; FDE address range
+ .byte 0x0 ; uleb128 0x0; Augmentation size
+ .byte 0x4 ; DW_CFA_advance_loc4
+ .set L$set$4,LCFI0-Lstartcode
+ .long L$set$4
+ .byte 0xd ; DW_CFA_def_cfa_register
+ .byte 0x08 ; uleb128 0x08
+ .byte 0x4 ; DW_CFA_advance_loc4
+ .set L$set$5,LCFI1-LCFI0
+ .long L$set$5
+ .byte 0x11 ; DW_CFA_offset_extended_sf
+ .byte 0x41 ; uleb128 0x41
+ .byte 0x7e ; sleb128 -2
+ .byte 0x9f ; DW_CFA_offset, column 0x1f
+ .byte 0x1 ; uleb128 0x1
+ .byte 0x9e ; DW_CFA_offset, column 0x1e
+ .byte 0x2 ; uleb128 0x2
+ .byte 0x9d ; DW_CFA_offset, column 0x1d
+ .byte 0x3 ; uleb128 0x3
+ .byte 0x9c ; DW_CFA_offset, column 0x1c
+ .byte 0x4 ; uleb128 0x4
+ .byte 0x4 ; DW_CFA_advance_loc4
+ .set L$set$6,LCFI2-LCFI1
+ .long L$set$6
+ .byte 0xd ; DW_CFA_def_cfa_register
+ .byte 0x1c ; uleb128 0x1c
+ .align LOG2_GPR_BYTES
+LEFDE1:
+ .align 1
+
diff --git a/contrib/restricted/libffi/src/powerpc/darwin_closure.S b/contrib/restricted/libffi/src/powerpc/darwin_closure.S
index 0e111edd35..3121e6ac26 100644
--- a/contrib/restricted/libffi/src/powerpc/darwin_closure.S
+++ b/contrib/restricted/libffi/src/powerpc/darwin_closure.S
@@ -1,571 +1,571 @@
-/* -----------------------------------------------------------------------
- darwin_closure.S - Copyright (c) 2002, 2003, 2004, 2010,
- Free Software Foundation, Inc.
- based on ppc_closure.S
-
- PowerPC Assembly glue.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#define LIBFFI_ASM
-#define L(x) x
-
-#if defined(__ppc64__)
-#define MODE_CHOICE(x, y) y
-#else
-#define MODE_CHOICE(x, y) x
-#endif
-
-#define machine_choice MODE_CHOICE(ppc7400,ppc64)
-
-; Define some pseudo-opcodes for size-independent load & store of GPRs ...
-#define lgu MODE_CHOICE(lwzu, ldu)
-#define lg MODE_CHOICE(lwz,ld)
-#define sg MODE_CHOICE(stw,std)
-#define sgu MODE_CHOICE(stwu,stdu)
-
-; ... and the size of GPRs and their storage indicator.
-#define GPR_BYTES MODE_CHOICE(4,8)
-#define LOG2_GPR_BYTES MODE_CHOICE(2,3) /* log2(GPR_BYTES) */
-#define g_long MODE_CHOICE(long, quad) /* usage is ".g_long" */
-
-; From the ABI doc: "Mac OS X ABI Function Call Guide" Version 2009-02-04.
-#define LINKAGE_SIZE MODE_CHOICE(24,48)
-#define PARAM_AREA MODE_CHOICE(32,64)
-
-#define SAVED_CR_OFFSET MODE_CHOICE(4,8) /* save position for CR */
-#define SAVED_LR_OFFSET MODE_CHOICE(8,16) /* save position for lr */
-
-/* WARNING: if ffi_type is changed... here be monsters.
- Offsets of items within the result type. */
-#define FFI_TYPE_TYPE MODE_CHOICE(6,10)
-#define FFI_TYPE_ELEM MODE_CHOICE(8,16)
-
-#define SAVED_FPR_COUNT 13
-#define FPR_SIZE 8
-/* biggest m64 struct ret is 8GPRS + 13FPRS = 168 bytes - rounded to 16bytes = 176. */
-#define RESULT_BYTES MODE_CHOICE(16,176)
-
-; The whole stack frame **MUST** be 16byte-aligned.
-#define SAVE_SIZE (((LINKAGE_SIZE+PARAM_AREA+SAVED_FPR_COUNT*FPR_SIZE+RESULT_BYTES)+15) & -16LL)
-#define PAD_SIZE (SAVE_SIZE-(LINKAGE_SIZE+PARAM_AREA+SAVED_FPR_COUNT*FPR_SIZE+RESULT_BYTES))
-
-#define PARENT_PARM_BASE (SAVE_SIZE+LINKAGE_SIZE)
-#define FP_SAVE_BASE (LINKAGE_SIZE+PARAM_AREA)
-
-#if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1050
-; We no longer need the pic symbol stub for Darwin >= 9.
-#define BLCLS_HELP _ffi_closure_helper_DARWIN
-#define STRUCT_RETVALUE_P _darwin64_struct_ret_by_value_p
-#define PASS_STR_FLOATS _darwin64_pass_struct_floats
-#undef WANT_STUB
-#else
-#define BLCLS_HELP L_ffi_closure_helper_DARWIN$stub
-#define STRUCT_RETVALUE_P L_darwin64_struct_ret_by_value_p$stub
-#define PASS_STR_FLOATS L_darwin64_pass_struct_floats$stub
-#define WANT_STUB
-#endif
-
-/* m32/m64
-
- The stack layout looks like this:
-
- | Additional params... | | Higher address
- ~ ~ ~
- | Parameters (at least 8*4/8=32/64) | | NUM_GPR_ARG_REGISTERS
- |--------------------------------------------| |
- | TOC=R2 (AIX) Reserved (Darwin) 4/8 | |
- |--------------------------------------------| |
- | Reserved 2*4/8 | |
- |--------------------------------------------| |
- | Space for callee`s LR 4/8 | |
- |--------------------------------------------| |
- | Saved CR [low word for m64] 4/8 | |
- |--------------------------------------------| |
- | Current backchain pointer 4/8 |-/ Parent`s frame.
- |--------------------------------------------| <+ <<< on entry to
- | Result Bytes 16/176 | |
- |--------------------------------------------| |
- ~ padding to 16-byte alignment ~ ~
- |--------------------------------------------| |
- | NUM_FPR_ARG_REGISTERS slots | |
- | here fp13 .. fp1 13*8 | |
- |--------------------------------------------| |
- | R3..R10 8*4/8=32/64 | | NUM_GPR_ARG_REGISTERS
- |--------------------------------------------| |
- | TOC=R2 (AIX) Reserved (Darwin) 4/8 | |
- |--------------------------------------------| | stack |
- | Reserved [compiler,binder] 2*4/8 | | grows |
- |--------------------------------------------| | down V
- | Space for callees LR 4/8 | |
- |--------------------------------------------| | lower addresses
- | Saved CR [low word for m64] 4/8 | |
- |--------------------------------------------| | stack pointer here
- | Current backchain pointer 4/8 |-/ during
- |--------------------------------------------| <<< call.
-
-*/
-
- .file "darwin_closure.S"
-
- .machine machine_choice
-
- .text
- .globl _ffi_closure_ASM
- .align LOG2_GPR_BYTES
-_ffi_closure_ASM:
-LFB1:
-Lstartcode:
- mflr r0 /* extract return address */
- sg r0,SAVED_LR_OFFSET(r1) /* save the return address */
-LCFI0:
- sgu r1,-SAVE_SIZE(r1) /* skip over caller save area
- keep stack aligned to 16. */
-LCFI1:
- /* We want to build up an area for the parameters passed
- in registers. (both floating point and integer) */
-
- /* Put gpr 3 to gpr 10 in the parents outgoing area...
- ... the remainder of any params that overflowed the regs will
- follow here. */
- sg r3, (PARENT_PARM_BASE )(r1)
- sg r4, (PARENT_PARM_BASE + GPR_BYTES )(r1)
- sg r5, (PARENT_PARM_BASE + GPR_BYTES * 2)(r1)
- sg r6, (PARENT_PARM_BASE + GPR_BYTES * 3)(r1)
- sg r7, (PARENT_PARM_BASE + GPR_BYTES * 4)(r1)
- sg r8, (PARENT_PARM_BASE + GPR_BYTES * 5)(r1)
- sg r9, (PARENT_PARM_BASE + GPR_BYTES * 6)(r1)
- sg r10,(PARENT_PARM_BASE + GPR_BYTES * 7)(r1)
-
- /* We save fpr 1 to fpr 14 in our own save frame. */
- stfd f1, (FP_SAVE_BASE )(r1)
- stfd f2, (FP_SAVE_BASE + FPR_SIZE )(r1)
- stfd f3, (FP_SAVE_BASE + FPR_SIZE * 2 )(r1)
- stfd f4, (FP_SAVE_BASE + FPR_SIZE * 3 )(r1)
- stfd f5, (FP_SAVE_BASE + FPR_SIZE * 4 )(r1)
- stfd f6, (FP_SAVE_BASE + FPR_SIZE * 5 )(r1)
- stfd f7, (FP_SAVE_BASE + FPR_SIZE * 6 )(r1)
- stfd f8, (FP_SAVE_BASE + FPR_SIZE * 7 )(r1)
- stfd f9, (FP_SAVE_BASE + FPR_SIZE * 8 )(r1)
- stfd f10,(FP_SAVE_BASE + FPR_SIZE * 9 )(r1)
- stfd f11,(FP_SAVE_BASE + FPR_SIZE * 10)(r1)
- stfd f12,(FP_SAVE_BASE + FPR_SIZE * 11)(r1)
- stfd f13,(FP_SAVE_BASE + FPR_SIZE * 12)(r1)
-
- /* Set up registers for the routine that actually does the work
- get the context pointer from the trampoline. */
- mr r3,r11
-
- /* Now load up the pointer to the result storage. */
- addi r4,r1,(SAVE_SIZE-RESULT_BYTES)
-
- /* Now load up the pointer to the saved gpr registers. */
- addi r5,r1,PARENT_PARM_BASE
-
- /* Now load up the pointer to the saved fpr registers. */
- addi r6,r1,FP_SAVE_BASE
-
- /* Make the call. */
- bl BLCLS_HELP
-
- /* r3 contains the rtype pointer... save it since we will need
- it later. */
- sg r3,LINKAGE_SIZE(r1) ; ffi_type * result_type
- lg r0,0(r3) ; size => r0
- lhz r3,FFI_TYPE_TYPE(r3) ; type => r3
-
- /* The helper will have intercepted structure returns and inserted
- the caller`s destination address for structs returned by ref. */
-
- /* r3 contains the return type so use it to look up in a table
- so we know how to deal with each type. */
-
- addi r5,r1,(SAVE_SIZE-RESULT_BYTES) /* Otherwise, our return is here. */
- bl Lget_ret_type0_addr /* Get pointer to Lret_type0 into LR. */
- mflr r4 /* Move to r4. */
- slwi r3,r3,4 /* Now multiply return type by 16. */
- add r3,r3,r4 /* Add contents of table to table address. */
- mtctr r3
- bctr /* Jump to it. */
-LFE1:
-/* Each of the ret_typeX code fragments has to be exactly 16 bytes long
- (4 instructions). For cache effectiveness we align to a 16 byte boundary
- first. */
-
- .align 4
-
- nop
- nop
- nop
-Lget_ret_type0_addr:
- blrl
-
-/* case FFI_TYPE_VOID */
-Lret_type0:
- b Lfinish
- nop
- nop
- nop
-
-/* case FFI_TYPE_INT */
-Lret_type1:
- lg r3,0(r5)
- b Lfinish
- nop
- nop
-
-/* case FFI_TYPE_FLOAT */
-Lret_type2:
- lfs f1,0(r5)
- b Lfinish
- nop
- nop
-
-/* case FFI_TYPE_DOUBLE */
-Lret_type3:
- lfd f1,0(r5)
- b Lfinish
- nop
- nop
-
-/* case FFI_TYPE_LONGDOUBLE */
-Lret_type4:
- lfd f1,0(r5)
- lfd f2,8(r5)
- b Lfinish
- nop
-
-/* case FFI_TYPE_UINT8 */
-Lret_type5:
-#if defined(__ppc64__)
- lbz r3,7(r5)
-#else
- lbz r3,3(r5)
-#endif
- b Lfinish
- nop
- nop
-
-/* case FFI_TYPE_SINT8 */
-Lret_type6:
-#if defined(__ppc64__)
- lbz r3,7(r5)
-#else
- lbz r3,3(r5)
-#endif
- extsb r3,r3
- b Lfinish
- nop
-
-/* case FFI_TYPE_UINT16 */
-Lret_type7:
-#if defined(__ppc64__)
- lhz r3,6(r5)
-#else
- lhz r3,2(r5)
-#endif
- b Lfinish
- nop
- nop
-
-/* case FFI_TYPE_SINT16 */
-Lret_type8:
-#if defined(__ppc64__)
- lha r3,6(r5)
-#else
- lha r3,2(r5)
-#endif
- b Lfinish
- nop
- nop
-
-/* case FFI_TYPE_UINT32 */
-Lret_type9:
-#if defined(__ppc64__)
- lwz r3,4(r5)
-#else
- lwz r3,0(r5)
-#endif
- b Lfinish
- nop
- nop
-
-/* case FFI_TYPE_SINT32 */
-Lret_type10:
-#if defined(__ppc64__)
- lwz r3,4(r5)
-#else
- lwz r3,0(r5)
-#endif
- b Lfinish
- nop
- nop
-
-/* case FFI_TYPE_UINT64 */
-Lret_type11:
-#if defined(__ppc64__)
- lg r3,0(r5)
- b Lfinish
- nop
-#else
- lwz r3,0(r5)
- lwz r4,4(r5)
- b Lfinish
-#endif
- nop
-
-/* case FFI_TYPE_SINT64 */
-Lret_type12:
-#if defined(__ppc64__)
- lg r3,0(r5)
- b Lfinish
- nop
-#else
- lwz r3,0(r5)
- lwz r4,4(r5)
- b Lfinish
-#endif
- nop
-
-/* case FFI_TYPE_STRUCT */
-Lret_type13:
-#if defined(__ppc64__)
- lg r3,0(r5) ; we need at least this...
- cmpi 0,r0,4
- bgt Lstructend ; not a special small case
- b Lsmallstruct ; see if we need more.
-#else
- cmpwi 0,r0,4
- bgt Lfinish ; not by value
- lg r3,0(r5)
- b Lfinish
-#endif
-/* case FFI_TYPE_POINTER */
-Lret_type14:
- lg r3,0(r5)
- b Lfinish
- nop
- nop
-
-#if defined(__ppc64__)
-Lsmallstruct:
- beq Lfour ; continuation of Lret13.
- cmpi 0,r0,3
- beq Lfinish ; don`t adjust this - can`t be any floats here...
- srdi r3,r3,48
- cmpi 0,r0,2
- beq Lfinish ; .. or here ..
- srdi r3,r3,8
- b Lfinish ; .. or here.
-
-Lfour:
- lg r6,LINKAGE_SIZE(r1) ; get the result type
- lg r6,FFI_TYPE_ELEM(r6) ; elements array pointer
- lg r6,0(r6) ; first element
- lhz r0,FFI_TYPE_TYPE(r6) ; OK go the type
- cmpi 0,r0,2 ; FFI_TYPE_FLOAT
- bne Lfourint
- lfs f1,0(r5) ; just one float in the struct.
- b Lfinish
-
-Lfourint:
- srdi r3,r3,32 ; four bytes.
- b Lfinish
-
-Lstructend:
- lg r3,LINKAGE_SIZE(r1) ; get the result type
- bl STRUCT_RETVALUE_P
- cmpi 0,r3,0
- beq Lfinish ; nope.
- /* Recover a pointer to the results. */
- addi r11,r1,(SAVE_SIZE-RESULT_BYTES)
- lg r3,0(r11) ; we need at least this...
- lg r4,8(r11)
- cmpi 0,r0,16
- beq Lfinish ; special case 16 bytes we don't consider floats.
-
- /* OK, frustratingly, the process of saving the struct to mem might have
- messed with the FPRs, so we have to re-load them :(.
- We`ll use our FPRs space again - calling:
- void darwin64_pass_struct_floats (ffi_type *s, char *src,
- unsigned *nfpr, double **fprs)
- We`ll temporarily pinch the first two slots of the param area for local
- vars used by the routine. */
- xor r6,r6,r6
- addi r5,r1,PARENT_PARM_BASE ; some space
- sg r6,0(r5) ; *nfpr zeroed.
- addi r6,r5,8 ; **fprs
- addi r3,r1,FP_SAVE_BASE ; pointer to FPRs space
- sg r3,0(r6)
- mr r4,r11 ; the struct is here...
- lg r3,LINKAGE_SIZE(r1) ; ffi_type * result_type.
- bl PASS_STR_FLOATS ; get struct floats into FPR save space.
- /* See if we used any floats */
- lwz r0,(SAVE_SIZE-RESULT_BYTES)(r1)
- cmpi 0,r0,0
- beq Lstructints ; nope.
- /* OK load `em up... */
- lfd f1, (FP_SAVE_BASE )(r1)
- lfd f2, (FP_SAVE_BASE + FPR_SIZE )(r1)
- lfd f3, (FP_SAVE_BASE + FPR_SIZE * 2 )(r1)
- lfd f4, (FP_SAVE_BASE + FPR_SIZE * 3 )(r1)
- lfd f5, (FP_SAVE_BASE + FPR_SIZE * 4 )(r1)
- lfd f6, (FP_SAVE_BASE + FPR_SIZE * 5 )(r1)
- lfd f7, (FP_SAVE_BASE + FPR_SIZE * 6 )(r1)
- lfd f8, (FP_SAVE_BASE + FPR_SIZE * 7 )(r1)
- lfd f9, (FP_SAVE_BASE + FPR_SIZE * 8 )(r1)
- lfd f10,(FP_SAVE_BASE + FPR_SIZE * 9 )(r1)
- lfd f11,(FP_SAVE_BASE + FPR_SIZE * 10)(r1)
- lfd f12,(FP_SAVE_BASE + FPR_SIZE * 11)(r1)
- lfd f13,(FP_SAVE_BASE + FPR_SIZE * 12)(r1)
-
- /* point back at our saved struct. */
-Lstructints:
- addi r11,r1,(SAVE_SIZE-RESULT_BYTES)
- lg r3,0(r11) ; we end up picking the
- lg r4,8(r11) ; first two again.
- lg r5,16(r11)
- lg r6,24(r11)
- lg r7,32(r11)
- lg r8,40(r11)
- lg r9,48(r11)
- lg r10,56(r11)
-#endif
-
-/* case done */
-Lfinish:
- addi r1,r1,SAVE_SIZE /* Restore stack pointer. */
- lg r0,SAVED_LR_OFFSET(r1) /* Get return address. */
- mtlr r0 /* Reset link register. */
- blr
-Lendcode:
- .align 1
-
-/* END(ffi_closure_ASM) */
-
-/* EH frame stuff. */
-#define EH_DATA_ALIGN_FACT MODE_CHOICE(0x7c,0x78)
-/* 176, 400 */
-#define EH_FRAME_OFFSETA MODE_CHOICE(176,0x90)
-#define EH_FRAME_OFFSETB MODE_CHOICE(1,3)
-
- .section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
-EH_frame1:
- .set L$set$0,LECIE1-LSCIE1
- .long L$set$0 ; Length of Common Information Entry
-LSCIE1:
- .long 0x0 ; CIE Identifier Tag
- .byte 0x1 ; CIE Version
- .ascii "zR\0" ; CIE Augmentation
- .byte 0x1 ; uleb128 0x1; CIE Code Alignment Factor
- .byte EH_DATA_ALIGN_FACT ; sleb128 -4; CIE Data Alignment Factor
- .byte 0x41 ; CIE RA Column
- .byte 0x1 ; uleb128 0x1; Augmentation size
- .byte 0x10 ; FDE Encoding (pcrel)
- .byte 0xc ; DW_CFA_def_cfa
- .byte 0x1 ; uleb128 0x1
- .byte 0x0 ; uleb128 0x0
- .align LOG2_GPR_BYTES
-LECIE1:
- .globl _ffi_closure_ASM.eh
-_ffi_closure_ASM.eh:
-LSFDE1:
- .set L$set$1,LEFDE1-LASFDE1
- .long L$set$1 ; FDE Length
-
-LASFDE1:
- .long LASFDE1-EH_frame1 ; FDE CIE offset
- .g_long Lstartcode-. ; FDE initial location
- .set L$set$2,LFE1-Lstartcode
- .g_long L$set$2 ; FDE address range
- .byte 0x0 ; uleb128 0x0; Augmentation size
- .byte 0x4 ; DW_CFA_advance_loc4
- .set L$set$3,LCFI1-LCFI0
- .long L$set$3
- .byte 0xe ; DW_CFA_def_cfa_offset
- .byte EH_FRAME_OFFSETA,EH_FRAME_OFFSETB ; uleb128 176,1/190,3
- .byte 0x4 ; DW_CFA_advance_loc4
- .set L$set$4,LCFI0-Lstartcode
- .long L$set$4
- .byte 0x11 ; DW_CFA_offset_extended_sf
- .byte 0x41 ; uleb128 0x41
- .byte 0x7e ; sleb128 -2
- .align LOG2_GPR_BYTES
-LEFDE1:
- .align 1
-
-#ifdef WANT_STUB
- .section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32
- .align 5
-L_ffi_closure_helper_DARWIN$stub:
- .indirect_symbol _ffi_closure_helper_DARWIN
- mflr r0
- bcl 20,31,"L1$spb"
-"L1$spb":
- mflr r11
- addis r11,r11,ha16(L_ffi_closure_helper_DARWIN$lazy_ptr-"L1$spb")
- mtlr r0
- lwzu r12,lo16(L_ffi_closure_helper_DARWIN$lazy_ptr-"L1$spb")(r11)
- mtctr r12
- bctr
- .lazy_symbol_pointer
-L_ffi_closure_helper_DARWIN$lazy_ptr:
- .indirect_symbol _ffi_closure_helper_DARWIN
- .g_long dyld_stub_binding_helper
-
-#if defined(__ppc64__)
- .section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32
- .align 5
-L_darwin64_struct_ret_by_value_p$stub:
- .indirect_symbol _darwin64_struct_ret_by_value_p
- mflr r0
- bcl 20,31,"L2$spb"
-"L2$spb":
- mflr r11
- addis r11,r11,ha16(L_darwin64_struct_ret_by_value_p$lazy_ptr-"L2$spb")
- mtlr r0
- lwzu r12,lo16(L_darwin64_struct_ret_by_value_p$lazy_ptr-"L2$spb")(r11)
- mtctr r12
- bctr
- .lazy_symbol_pointer
-L_darwin64_struct_ret_by_value_p$lazy_ptr:
- .indirect_symbol _darwin64_struct_ret_by_value_p
- .g_long dyld_stub_binding_helper
-
- .section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32
- .align 5
-L_darwin64_pass_struct_floats$stub:
- .indirect_symbol _darwin64_pass_struct_floats
- mflr r0
- bcl 20,31,"L3$spb"
-"L3$spb":
- mflr r11
- addis r11,r11,ha16(L_darwin64_pass_struct_floats$lazy_ptr-"L3$spb")
- mtlr r0
- lwzu r12,lo16(L_darwin64_pass_struct_floats$lazy_ptr-"L3$spb")(r11)
- mtctr r12
- bctr
- .lazy_symbol_pointer
-L_darwin64_pass_struct_floats$lazy_ptr:
- .indirect_symbol _darwin64_pass_struct_floats
- .g_long dyld_stub_binding_helper
-# endif
-#endif
+/* -----------------------------------------------------------------------
+ darwin_closure.S - Copyright (c) 2002, 2003, 2004, 2010,
+ Free Software Foundation, Inc.
+ based on ppc_closure.S
+
+ PowerPC Assembly glue.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#define LIBFFI_ASM
+#define L(x) x
+
+#if defined(__ppc64__)
+#define MODE_CHOICE(x, y) y
+#else
+#define MODE_CHOICE(x, y) x
+#endif
+
+#define machine_choice MODE_CHOICE(ppc7400,ppc64)
+
+; Define some pseudo-opcodes for size-independent load & store of GPRs ...
+#define lgu MODE_CHOICE(lwzu, ldu)
+#define lg MODE_CHOICE(lwz,ld)
+#define sg MODE_CHOICE(stw,std)
+#define sgu MODE_CHOICE(stwu,stdu)
+
+; ... and the size of GPRs and their storage indicator.
+#define GPR_BYTES MODE_CHOICE(4,8)
+#define LOG2_GPR_BYTES MODE_CHOICE(2,3) /* log2(GPR_BYTES) */
+#define g_long MODE_CHOICE(long, quad) /* usage is ".g_long" */
+
+; From the ABI doc: "Mac OS X ABI Function Call Guide" Version 2009-02-04.
+#define LINKAGE_SIZE MODE_CHOICE(24,48)
+#define PARAM_AREA MODE_CHOICE(32,64)
+
+#define SAVED_CR_OFFSET MODE_CHOICE(4,8) /* save position for CR */
+#define SAVED_LR_OFFSET MODE_CHOICE(8,16) /* save position for lr */
+
+/* WARNING: if ffi_type is changed... here be monsters.
+ Offsets of items within the result type. */
+#define FFI_TYPE_TYPE MODE_CHOICE(6,10)
+#define FFI_TYPE_ELEM MODE_CHOICE(8,16)
+
+#define SAVED_FPR_COUNT 13
+#define FPR_SIZE 8
+/* biggest m64 struct ret is 8GPRS + 13FPRS = 168 bytes - rounded to 16bytes = 176. */
+#define RESULT_BYTES MODE_CHOICE(16,176)
+
+; The whole stack frame **MUST** be 16byte-aligned.
+#define SAVE_SIZE (((LINKAGE_SIZE+PARAM_AREA+SAVED_FPR_COUNT*FPR_SIZE+RESULT_BYTES)+15) & -16LL)
+#define PAD_SIZE (SAVE_SIZE-(LINKAGE_SIZE+PARAM_AREA+SAVED_FPR_COUNT*FPR_SIZE+RESULT_BYTES))
+
+#define PARENT_PARM_BASE (SAVE_SIZE+LINKAGE_SIZE)
+#define FP_SAVE_BASE (LINKAGE_SIZE+PARAM_AREA)
+
+#if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1050
+; We no longer need the pic symbol stub for Darwin >= 9.
+#define BLCLS_HELP _ffi_closure_helper_DARWIN
+#define STRUCT_RETVALUE_P _darwin64_struct_ret_by_value_p
+#define PASS_STR_FLOATS _darwin64_pass_struct_floats
+#undef WANT_STUB
+#else
+#define BLCLS_HELP L_ffi_closure_helper_DARWIN$stub
+#define STRUCT_RETVALUE_P L_darwin64_struct_ret_by_value_p$stub
+#define PASS_STR_FLOATS L_darwin64_pass_struct_floats$stub
+#define WANT_STUB
+#endif
+
+/* m32/m64
+
+ The stack layout looks like this:
+
+ | Additional params... | | Higher address
+ ~ ~ ~
+ | Parameters (at least 8*4/8=32/64) | | NUM_GPR_ARG_REGISTERS
+ |--------------------------------------------| |
+ | TOC=R2 (AIX) Reserved (Darwin) 4/8 | |
+ |--------------------------------------------| |
+ | Reserved 2*4/8 | |
+ |--------------------------------------------| |
+ | Space for callee`s LR 4/8 | |
+ |--------------------------------------------| |
+ | Saved CR [low word for m64] 4/8 | |
+ |--------------------------------------------| |
+ | Current backchain pointer 4/8 |-/ Parent`s frame.
+ |--------------------------------------------| <+ <<< on entry to
+ | Result Bytes 16/176 | |
+ |--------------------------------------------| |
+ ~ padding to 16-byte alignment ~ ~
+ |--------------------------------------------| |
+ | NUM_FPR_ARG_REGISTERS slots | |
+ | here fp13 .. fp1 13*8 | |
+ |--------------------------------------------| |
+ | R3..R10 8*4/8=32/64 | | NUM_GPR_ARG_REGISTERS
+ |--------------------------------------------| |
+ | TOC=R2 (AIX) Reserved (Darwin) 4/8 | |
+ |--------------------------------------------| | stack |
+ | Reserved [compiler,binder] 2*4/8 | | grows |
+ |--------------------------------------------| | down V
+ | Space for callees LR 4/8 | |
+ |--------------------------------------------| | lower addresses
+ | Saved CR [low word for m64] 4/8 | |
+ |--------------------------------------------| | stack pointer here
+ | Current backchain pointer 4/8 |-/ during
+ |--------------------------------------------| <<< call.
+
+*/
+
+ .file "darwin_closure.S"
+
+ .machine machine_choice
+
+ .text
+ .globl _ffi_closure_ASM
+ .align LOG2_GPR_BYTES
+_ffi_closure_ASM:
+LFB1:
+Lstartcode:
+ mflr r0 /* extract return address */
+ sg r0,SAVED_LR_OFFSET(r1) /* save the return address */
+LCFI0:
+ sgu r1,-SAVE_SIZE(r1) /* skip over caller save area
+ keep stack aligned to 16. */
+LCFI1:
+ /* We want to build up an area for the parameters passed
+ in registers. (both floating point and integer) */
+
+ /* Put gpr 3 to gpr 10 in the parents outgoing area...
+ ... the remainder of any params that overflowed the regs will
+ follow here. */
+ sg r3, (PARENT_PARM_BASE )(r1)
+ sg r4, (PARENT_PARM_BASE + GPR_BYTES )(r1)
+ sg r5, (PARENT_PARM_BASE + GPR_BYTES * 2)(r1)
+ sg r6, (PARENT_PARM_BASE + GPR_BYTES * 3)(r1)
+ sg r7, (PARENT_PARM_BASE + GPR_BYTES * 4)(r1)
+ sg r8, (PARENT_PARM_BASE + GPR_BYTES * 5)(r1)
+ sg r9, (PARENT_PARM_BASE + GPR_BYTES * 6)(r1)
+ sg r10,(PARENT_PARM_BASE + GPR_BYTES * 7)(r1)
+
+ /* We save fpr 1 to fpr 14 in our own save frame. */
+ stfd f1, (FP_SAVE_BASE )(r1)
+ stfd f2, (FP_SAVE_BASE + FPR_SIZE )(r1)
+ stfd f3, (FP_SAVE_BASE + FPR_SIZE * 2 )(r1)
+ stfd f4, (FP_SAVE_BASE + FPR_SIZE * 3 )(r1)
+ stfd f5, (FP_SAVE_BASE + FPR_SIZE * 4 )(r1)
+ stfd f6, (FP_SAVE_BASE + FPR_SIZE * 5 )(r1)
+ stfd f7, (FP_SAVE_BASE + FPR_SIZE * 6 )(r1)
+ stfd f8, (FP_SAVE_BASE + FPR_SIZE * 7 )(r1)
+ stfd f9, (FP_SAVE_BASE + FPR_SIZE * 8 )(r1)
+ stfd f10,(FP_SAVE_BASE + FPR_SIZE * 9 )(r1)
+ stfd f11,(FP_SAVE_BASE + FPR_SIZE * 10)(r1)
+ stfd f12,(FP_SAVE_BASE + FPR_SIZE * 11)(r1)
+ stfd f13,(FP_SAVE_BASE + FPR_SIZE * 12)(r1)
+
+ /* Set up registers for the routine that actually does the work
+ get the context pointer from the trampoline. */
+ mr r3,r11
+
+ /* Now load up the pointer to the result storage. */
+ addi r4,r1,(SAVE_SIZE-RESULT_BYTES)
+
+ /* Now load up the pointer to the saved gpr registers. */
+ addi r5,r1,PARENT_PARM_BASE
+
+ /* Now load up the pointer to the saved fpr registers. */
+ addi r6,r1,FP_SAVE_BASE
+
+ /* Make the call. */
+ bl BLCLS_HELP
+
+ /* r3 contains the rtype pointer... save it since we will need
+ it later. */
+ sg r3,LINKAGE_SIZE(r1) ; ffi_type * result_type
+ lg r0,0(r3) ; size => r0
+ lhz r3,FFI_TYPE_TYPE(r3) ; type => r3
+
+ /* The helper will have intercepted structure returns and inserted
+ the caller`s destination address for structs returned by ref. */
+
+ /* r3 contains the return type so use it to look up in a table
+ so we know how to deal with each type. */
+
+ addi r5,r1,(SAVE_SIZE-RESULT_BYTES) /* Otherwise, our return is here. */
+ bl Lget_ret_type0_addr /* Get pointer to Lret_type0 into LR. */
+ mflr r4 /* Move to r4. */
+ slwi r3,r3,4 /* Now multiply return type by 16. */
+ add r3,r3,r4 /* Add contents of table to table address. */
+ mtctr r3
+ bctr /* Jump to it. */
+LFE1:
+/* Each of the ret_typeX code fragments has to be exactly 16 bytes long
+ (4 instructions). For cache effectiveness we align to a 16 byte boundary
+ first. */
+
+ .align 4
+
+ nop
+ nop
+ nop
+Lget_ret_type0_addr:
+ blrl
+
+/* case FFI_TYPE_VOID */
+Lret_type0:
+ b Lfinish
+ nop
+ nop
+ nop
+
+/* case FFI_TYPE_INT */
+Lret_type1:
+ lg r3,0(r5)
+ b Lfinish
+ nop
+ nop
+
+/* case FFI_TYPE_FLOAT */
+Lret_type2:
+ lfs f1,0(r5)
+ b Lfinish
+ nop
+ nop
+
+/* case FFI_TYPE_DOUBLE */
+Lret_type3:
+ lfd f1,0(r5)
+ b Lfinish
+ nop
+ nop
+
+/* case FFI_TYPE_LONGDOUBLE */
+Lret_type4:
+ lfd f1,0(r5)
+ lfd f2,8(r5)
+ b Lfinish
+ nop
+
+/* case FFI_TYPE_UINT8 */
+Lret_type5:
+#if defined(__ppc64__)
+ lbz r3,7(r5)
+#else
+ lbz r3,3(r5)
+#endif
+ b Lfinish
+ nop
+ nop
+
+/* case FFI_TYPE_SINT8 */
+Lret_type6:
+#if defined(__ppc64__)
+ lbz r3,7(r5)
+#else
+ lbz r3,3(r5)
+#endif
+ extsb r3,r3
+ b Lfinish
+ nop
+
+/* case FFI_TYPE_UINT16 */
+Lret_type7:
+#if defined(__ppc64__)
+ lhz r3,6(r5)
+#else
+ lhz r3,2(r5)
+#endif
+ b Lfinish
+ nop
+ nop
+
+/* case FFI_TYPE_SINT16 */
+Lret_type8:
+#if defined(__ppc64__)
+ lha r3,6(r5)
+#else
+ lha r3,2(r5)
+#endif
+ b Lfinish
+ nop
+ nop
+
+/* case FFI_TYPE_UINT32 */
+Lret_type9:
+#if defined(__ppc64__)
+ lwz r3,4(r5)
+#else
+ lwz r3,0(r5)
+#endif
+ b Lfinish
+ nop
+ nop
+
+/* case FFI_TYPE_SINT32 */
+Lret_type10:
+#if defined(__ppc64__)
+ lwz r3,4(r5)
+#else
+ lwz r3,0(r5)
+#endif
+ b Lfinish
+ nop
+ nop
+
+/* case FFI_TYPE_UINT64 */
+Lret_type11:
+#if defined(__ppc64__)
+ lg r3,0(r5)
+ b Lfinish
+ nop
+#else
+ lwz r3,0(r5)
+ lwz r4,4(r5)
+ b Lfinish
+#endif
+ nop
+
+/* case FFI_TYPE_SINT64 */
+Lret_type12:
+#if defined(__ppc64__)
+ lg r3,0(r5)
+ b Lfinish
+ nop
+#else
+ lwz r3,0(r5)
+ lwz r4,4(r5)
+ b Lfinish
+#endif
+ nop
+
+/* case FFI_TYPE_STRUCT */
+Lret_type13:
+#if defined(__ppc64__)
+ lg r3,0(r5) ; we need at least this...
+ cmpi 0,r0,4
+ bgt Lstructend ; not a special small case
+ b Lsmallstruct ; see if we need more.
+#else
+ cmpwi 0,r0,4
+ bgt Lfinish ; not by value
+ lg r3,0(r5)
+ b Lfinish
+#endif
+/* case FFI_TYPE_POINTER */
+Lret_type14:
+ lg r3,0(r5)
+ b Lfinish
+ nop
+ nop
+
+#if defined(__ppc64__)
+Lsmallstruct:
+ beq Lfour ; continuation of Lret13.
+ cmpi 0,r0,3
+ beq Lfinish ; don`t adjust this - can`t be any floats here...
+ srdi r3,r3,48
+ cmpi 0,r0,2
+ beq Lfinish ; .. or here ..
+ srdi r3,r3,8
+ b Lfinish ; .. or here.
+
+Lfour:
+ lg r6,LINKAGE_SIZE(r1) ; get the result type
+ lg r6,FFI_TYPE_ELEM(r6) ; elements array pointer
+ lg r6,0(r6) ; first element
+ lhz r0,FFI_TYPE_TYPE(r6) ; OK go the type
+ cmpi 0,r0,2 ; FFI_TYPE_FLOAT
+ bne Lfourint
+ lfs f1,0(r5) ; just one float in the struct.
+ b Lfinish
+
+Lfourint:
+ srdi r3,r3,32 ; four bytes.
+ b Lfinish
+
+Lstructend:
+ lg r3,LINKAGE_SIZE(r1) ; get the result type
+ bl STRUCT_RETVALUE_P
+ cmpi 0,r3,0
+ beq Lfinish ; nope.
+ /* Recover a pointer to the results. */
+ addi r11,r1,(SAVE_SIZE-RESULT_BYTES)
+ lg r3,0(r11) ; we need at least this...
+ lg r4,8(r11)
+ cmpi 0,r0,16
+ beq Lfinish ; special case 16 bytes we don't consider floats.
+
+ /* OK, frustratingly, the process of saving the struct to mem might have
+ messed with the FPRs, so we have to re-load them :(.
+ We`ll use our FPRs space again - calling:
+ void darwin64_pass_struct_floats (ffi_type *s, char *src,
+ unsigned *nfpr, double **fprs)
+ We`ll temporarily pinch the first two slots of the param area for local
+ vars used by the routine. */
+ xor r6,r6,r6
+ addi r5,r1,PARENT_PARM_BASE ; some space
+ sg r6,0(r5) ; *nfpr zeroed.
+ addi r6,r5,8 ; **fprs
+ addi r3,r1,FP_SAVE_BASE ; pointer to FPRs space
+ sg r3,0(r6)
+ mr r4,r11 ; the struct is here...
+ lg r3,LINKAGE_SIZE(r1) ; ffi_type * result_type.
+ bl PASS_STR_FLOATS ; get struct floats into FPR save space.
+ /* See if we used any floats */
+ lwz r0,(SAVE_SIZE-RESULT_BYTES)(r1)
+ cmpi 0,r0,0
+ beq Lstructints ; nope.
+ /* OK load `em up... */
+ lfd f1, (FP_SAVE_BASE )(r1)
+ lfd f2, (FP_SAVE_BASE + FPR_SIZE )(r1)
+ lfd f3, (FP_SAVE_BASE + FPR_SIZE * 2 )(r1)
+ lfd f4, (FP_SAVE_BASE + FPR_SIZE * 3 )(r1)
+ lfd f5, (FP_SAVE_BASE + FPR_SIZE * 4 )(r1)
+ lfd f6, (FP_SAVE_BASE + FPR_SIZE * 5 )(r1)
+ lfd f7, (FP_SAVE_BASE + FPR_SIZE * 6 )(r1)
+ lfd f8, (FP_SAVE_BASE + FPR_SIZE * 7 )(r1)
+ lfd f9, (FP_SAVE_BASE + FPR_SIZE * 8 )(r1)
+ lfd f10,(FP_SAVE_BASE + FPR_SIZE * 9 )(r1)
+ lfd f11,(FP_SAVE_BASE + FPR_SIZE * 10)(r1)
+ lfd f12,(FP_SAVE_BASE + FPR_SIZE * 11)(r1)
+ lfd f13,(FP_SAVE_BASE + FPR_SIZE * 12)(r1)
+
+ /* point back at our saved struct. */
+Lstructints:
+ addi r11,r1,(SAVE_SIZE-RESULT_BYTES)
+ lg r3,0(r11) ; we end up picking the
+ lg r4,8(r11) ; first two again.
+ lg r5,16(r11)
+ lg r6,24(r11)
+ lg r7,32(r11)
+ lg r8,40(r11)
+ lg r9,48(r11)
+ lg r10,56(r11)
+#endif
+
+/* case done */
+Lfinish:
+ addi r1,r1,SAVE_SIZE /* Restore stack pointer. */
+ lg r0,SAVED_LR_OFFSET(r1) /* Get return address. */
+ mtlr r0 /* Reset link register. */
+ blr
+Lendcode:
+ .align 1
+
+/* END(ffi_closure_ASM) */
+
+/* EH frame stuff. */
+#define EH_DATA_ALIGN_FACT MODE_CHOICE(0x7c,0x78)
+/* 176, 400 */
+#define EH_FRAME_OFFSETA MODE_CHOICE(176,0x90)
+#define EH_FRAME_OFFSETB MODE_CHOICE(1,3)
+
+ .section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
+EH_frame1:
+ .set L$set$0,LECIE1-LSCIE1
+ .long L$set$0 ; Length of Common Information Entry
+LSCIE1:
+ .long 0x0 ; CIE Identifier Tag
+ .byte 0x1 ; CIE Version
+ .ascii "zR\0" ; CIE Augmentation
+ .byte 0x1 ; uleb128 0x1; CIE Code Alignment Factor
+ .byte EH_DATA_ALIGN_FACT ; sleb128 -4; CIE Data Alignment Factor
+ .byte 0x41 ; CIE RA Column
+ .byte 0x1 ; uleb128 0x1; Augmentation size
+ .byte 0x10 ; FDE Encoding (pcrel)
+ .byte 0xc ; DW_CFA_def_cfa
+ .byte 0x1 ; uleb128 0x1
+ .byte 0x0 ; uleb128 0x0
+ .align LOG2_GPR_BYTES
+LECIE1:
+ .globl _ffi_closure_ASM.eh
+_ffi_closure_ASM.eh:
+LSFDE1:
+ .set L$set$1,LEFDE1-LASFDE1
+ .long L$set$1 ; FDE Length
+
+LASFDE1:
+ .long LASFDE1-EH_frame1 ; FDE CIE offset
+ .g_long Lstartcode-. ; FDE initial location
+ .set L$set$2,LFE1-Lstartcode
+ .g_long L$set$2 ; FDE address range
+ .byte 0x0 ; uleb128 0x0; Augmentation size
+ .byte 0x4 ; DW_CFA_advance_loc4
+ .set L$set$3,LCFI1-LCFI0
+ .long L$set$3
+ .byte 0xe ; DW_CFA_def_cfa_offset
+ .byte EH_FRAME_OFFSETA,EH_FRAME_OFFSETB ; uleb128 176,1/190,3
+ .byte 0x4 ; DW_CFA_advance_loc4
+ .set L$set$4,LCFI0-Lstartcode
+ .long L$set$4
+ .byte 0x11 ; DW_CFA_offset_extended_sf
+ .byte 0x41 ; uleb128 0x41
+ .byte 0x7e ; sleb128 -2
+ .align LOG2_GPR_BYTES
+LEFDE1:
+ .align 1
+
+#ifdef WANT_STUB
+ .section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32
+ .align 5
+L_ffi_closure_helper_DARWIN$stub:
+ .indirect_symbol _ffi_closure_helper_DARWIN
+ mflr r0
+ bcl 20,31,"L1$spb"
+"L1$spb":
+ mflr r11
+ addis r11,r11,ha16(L_ffi_closure_helper_DARWIN$lazy_ptr-"L1$spb")
+ mtlr r0
+ lwzu r12,lo16(L_ffi_closure_helper_DARWIN$lazy_ptr-"L1$spb")(r11)
+ mtctr r12
+ bctr
+ .lazy_symbol_pointer
+L_ffi_closure_helper_DARWIN$lazy_ptr:
+ .indirect_symbol _ffi_closure_helper_DARWIN
+ .g_long dyld_stub_binding_helper
+
+#if defined(__ppc64__)
+ .section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32
+ .align 5
+L_darwin64_struct_ret_by_value_p$stub:
+ .indirect_symbol _darwin64_struct_ret_by_value_p
+ mflr r0
+ bcl 20,31,"L2$spb"
+"L2$spb":
+ mflr r11
+ addis r11,r11,ha16(L_darwin64_struct_ret_by_value_p$lazy_ptr-"L2$spb")
+ mtlr r0
+ lwzu r12,lo16(L_darwin64_struct_ret_by_value_p$lazy_ptr-"L2$spb")(r11)
+ mtctr r12
+ bctr
+ .lazy_symbol_pointer
+L_darwin64_struct_ret_by_value_p$lazy_ptr:
+ .indirect_symbol _darwin64_struct_ret_by_value_p
+ .g_long dyld_stub_binding_helper
+
+ .section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32
+ .align 5
+L_darwin64_pass_struct_floats$stub:
+ .indirect_symbol _darwin64_pass_struct_floats
+ mflr r0
+ bcl 20,31,"L3$spb"
+"L3$spb":
+ mflr r11
+ addis r11,r11,ha16(L_darwin64_pass_struct_floats$lazy_ptr-"L3$spb")
+ mtlr r0
+ lwzu r12,lo16(L_darwin64_pass_struct_floats$lazy_ptr-"L3$spb")(r11)
+ mtctr r12
+ bctr
+ .lazy_symbol_pointer
+L_darwin64_pass_struct_floats$lazy_ptr:
+ .indirect_symbol _darwin64_pass_struct_floats
+ .g_long dyld_stub_binding_helper
+# endif
+#endif
diff --git a/contrib/restricted/libffi/src/powerpc/ffi.c b/contrib/restricted/libffi/src/powerpc/ffi.c
index 5d618cc0dd..a19bcbbfc5 100644
--- a/contrib/restricted/libffi/src/powerpc/ffi.c
+++ b/contrib/restricted/libffi/src/powerpc/ffi.c
@@ -1,175 +1,175 @@
-/* -----------------------------------------------------------------------
- ffi.c - Copyright (C) 2013 IBM
- Copyright (C) 2011 Anthony Green
- Copyright (C) 2011 Kyle Moffett
- Copyright (C) 2008 Red Hat, Inc
- Copyright (C) 2007, 2008 Free Software Foundation, Inc
- Copyright (c) 1998 Geoffrey Keating
-
- PowerPC Foreign Function Interface
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#include "ffi.h"
-#include "ffi_common.h"
-#include "ffi_powerpc.h"
-
-#if HAVE_LONG_DOUBLE_VARIANT
-/* Adjust ffi_type_longdouble. */
-void FFI_HIDDEN
-ffi_prep_types (ffi_abi abi)
-{
-# if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
-# ifdef POWERPC64
- ffi_prep_types_linux64 (abi);
-# else
- ffi_prep_types_sysv (abi);
-# endif
-# endif
-}
-#endif
-
-/* Perform machine dependent cif processing */
-ffi_status FFI_HIDDEN
-ffi_prep_cif_machdep (ffi_cif *cif)
-{
-#ifdef POWERPC64
- return ffi_prep_cif_linux64 (cif);
-#else
- return ffi_prep_cif_sysv (cif);
-#endif
-}
-
-ffi_status FFI_HIDDEN
-ffi_prep_cif_machdep_var (ffi_cif *cif,
- unsigned int nfixedargs MAYBE_UNUSED,
- unsigned int ntotalargs MAYBE_UNUSED)
-{
-#ifdef POWERPC64
- return ffi_prep_cif_linux64_var (cif, nfixedargs, ntotalargs);
-#else
- return ffi_prep_cif_sysv (cif);
-#endif
-}
-
-static void
-ffi_call_int (ffi_cif *cif,
- void (*fn) (void),
- void *rvalue,
- void **avalue,
- void *closure)
-{
- /* The final SYSV ABI says that structures smaller or equal 8 bytes
- are returned in r3/r4. A draft ABI used by linux instead returns
- them in memory.
-
- We bounce-buffer SYSV small struct return values so that sysv.S
- can write r3 and r4 to memory without worrying about struct size.
-
- For ELFv2 ABI, use a bounce buffer for homogeneous structs too,
- for similar reasons. This bounce buffer must be aligned to 16
- bytes for use with homogeneous structs of vectors (float128). */
- float128 smst_buffer[8];
- extended_cif ecif;
-
- ecif.cif = cif;
- ecif.avalue = avalue;
-
- ecif.rvalue = rvalue;
- if ((cif->flags & FLAG_RETURNS_SMST) != 0)
- ecif.rvalue = smst_buffer;
- /* Ensure that we have a valid struct return value.
- FIXME: Isn't this just papering over a user problem? */
- else if (!rvalue && cif->rtype->type == FFI_TYPE_STRUCT)
- ecif.rvalue = alloca (cif->rtype->size);
-
-#ifdef POWERPC64
- ffi_call_LINUX64 (&ecif, fn, ecif.rvalue, cif->flags, closure,
- -(long) cif->bytes);
-#else
- ffi_call_SYSV (&ecif, fn, ecif.rvalue, cif->flags, closure, -cif->bytes);
-#endif
-
- /* Check for a bounce-buffered return value */
- if (rvalue && ecif.rvalue == smst_buffer)
- {
- unsigned int rsize = cif->rtype->size;
-#ifndef __LITTLE_ENDIAN__
- /* The SYSV ABI returns a structure of up to 4 bytes in size
- left-padded in r3. */
-# ifndef POWERPC64
- if (rsize <= 4)
- memcpy (rvalue, (char *) smst_buffer + 4 - rsize, rsize);
- else
-# endif
- /* The SYSV ABI returns a structure of up to 8 bytes in size
- left-padded in r3/r4, and the ELFv2 ABI similarly returns a
- structure of up to 8 bytes in size left-padded in r3. But
- note that a structure of a single float is not paddded. */
- if (rsize <= 8 && (cif->flags & FLAG_RETURNS_FP) == 0)
- memcpy (rvalue, (char *) smst_buffer + 8 - rsize, rsize);
- else
-#endif
- memcpy (rvalue, smst_buffer, rsize);
- }
-}
-
-void
-ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue)
-{
- ffi_call_int (cif, fn, rvalue, avalue, NULL);
-}
-
-void
-ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue,
- void *closure)
-{
- ffi_call_int (cif, fn, rvalue, avalue, closure);
-}
-
-ffi_status
-ffi_prep_closure_loc (ffi_closure *closure,
- ffi_cif *cif,
- void (*fun) (ffi_cif *, void *, void **, void *),
- void *user_data,
- void *codeloc)
-{
-#ifdef POWERPC64
- return ffi_prep_closure_loc_linux64 (closure, cif, fun, user_data, codeloc);
-#else
- return ffi_prep_closure_loc_sysv (closure, cif, fun, user_data, codeloc);
-#endif
-}
-
-ffi_status
-ffi_prep_go_closure (ffi_go_closure *closure,
- ffi_cif *cif,
- void (*fun) (ffi_cif *, void *, void **, void *))
-{
-#ifdef POWERPC64
- closure->tramp = ffi_go_closure_linux64;
-#else
- closure->tramp = ffi_go_closure_sysv;
-#endif
- closure->cif = cif;
- closure->fun = fun;
- return FFI_OK;
-}
+/* -----------------------------------------------------------------------
+ ffi.c - Copyright (C) 2013 IBM
+ Copyright (C) 2011 Anthony Green
+ Copyright (C) 2011 Kyle Moffett
+ Copyright (C) 2008 Red Hat, Inc
+ Copyright (C) 2007, 2008 Free Software Foundation, Inc
+ Copyright (c) 1998 Geoffrey Keating
+
+ PowerPC Foreign Function Interface
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#include "ffi.h"
+#include "ffi_common.h"
+#include "ffi_powerpc.h"
+
+#if HAVE_LONG_DOUBLE_VARIANT
+/* Adjust ffi_type_longdouble. */
+void FFI_HIDDEN
+ffi_prep_types (ffi_abi abi)
+{
+# if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+# ifdef POWERPC64
+ ffi_prep_types_linux64 (abi);
+# else
+ ffi_prep_types_sysv (abi);
+# endif
+# endif
+}
+#endif
+
+/* Perform machine dependent cif processing */
+ffi_status FFI_HIDDEN
+ffi_prep_cif_machdep (ffi_cif *cif)
+{
+#ifdef POWERPC64
+ return ffi_prep_cif_linux64 (cif);
+#else
+ return ffi_prep_cif_sysv (cif);
+#endif
+}
+
+ffi_status FFI_HIDDEN
+ffi_prep_cif_machdep_var (ffi_cif *cif,
+ unsigned int nfixedargs MAYBE_UNUSED,
+ unsigned int ntotalargs MAYBE_UNUSED)
+{
+#ifdef POWERPC64
+ return ffi_prep_cif_linux64_var (cif, nfixedargs, ntotalargs);
+#else
+ return ffi_prep_cif_sysv (cif);
+#endif
+}
+
+static void
+ffi_call_int (ffi_cif *cif,
+ void (*fn) (void),
+ void *rvalue,
+ void **avalue,
+ void *closure)
+{
+ /* The final SYSV ABI says that structures smaller or equal 8 bytes
+ are returned in r3/r4. A draft ABI used by linux instead returns
+ them in memory.
+
+ We bounce-buffer SYSV small struct return values so that sysv.S
+ can write r3 and r4 to memory without worrying about struct size.
+
+ For ELFv2 ABI, use a bounce buffer for homogeneous structs too,
+ for similar reasons. This bounce buffer must be aligned to 16
+ bytes for use with homogeneous structs of vectors (float128). */
+ float128 smst_buffer[8];
+ extended_cif ecif;
+
+ ecif.cif = cif;
+ ecif.avalue = avalue;
+
+ ecif.rvalue = rvalue;
+ if ((cif->flags & FLAG_RETURNS_SMST) != 0)
+ ecif.rvalue = smst_buffer;
+ /* Ensure that we have a valid struct return value.
+ FIXME: Isn't this just papering over a user problem? */
+ else if (!rvalue && cif->rtype->type == FFI_TYPE_STRUCT)
+ ecif.rvalue = alloca (cif->rtype->size);
+
+#ifdef POWERPC64
+ ffi_call_LINUX64 (&ecif, fn, ecif.rvalue, cif->flags, closure,
+ -(long) cif->bytes);
+#else
+ ffi_call_SYSV (&ecif, fn, ecif.rvalue, cif->flags, closure, -cif->bytes);
+#endif
+
+ /* Check for a bounce-buffered return value */
+ if (rvalue && ecif.rvalue == smst_buffer)
+ {
+ unsigned int rsize = cif->rtype->size;
+#ifndef __LITTLE_ENDIAN__
+ /* The SYSV ABI returns a structure of up to 4 bytes in size
+ left-padded in r3. */
+# ifndef POWERPC64
+ if (rsize <= 4)
+ memcpy (rvalue, (char *) smst_buffer + 4 - rsize, rsize);
+ else
+# endif
+ /* The SYSV ABI returns a structure of up to 8 bytes in size
+ left-padded in r3/r4, and the ELFv2 ABI similarly returns a
+ structure of up to 8 bytes in size left-padded in r3. But
+ note that a structure of a single float is not paddded. */
+ if (rsize <= 8 && (cif->flags & FLAG_RETURNS_FP) == 0)
+ memcpy (rvalue, (char *) smst_buffer + 8 - rsize, rsize);
+ else
+#endif
+ memcpy (rvalue, smst_buffer, rsize);
+ }
+}
+
+void
+ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue)
+{
+ ffi_call_int (cif, fn, rvalue, avalue, NULL);
+}
+
+void
+ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue,
+ void *closure)
+{
+ ffi_call_int (cif, fn, rvalue, avalue, closure);
+}
+
+ffi_status
+ffi_prep_closure_loc (ffi_closure *closure,
+ ffi_cif *cif,
+ void (*fun) (ffi_cif *, void *, void **, void *),
+ void *user_data,
+ void *codeloc)
+{
+#ifdef POWERPC64
+ return ffi_prep_closure_loc_linux64 (closure, cif, fun, user_data, codeloc);
+#else
+ return ffi_prep_closure_loc_sysv (closure, cif, fun, user_data, codeloc);
+#endif
+}
+
+ffi_status
+ffi_prep_go_closure (ffi_go_closure *closure,
+ ffi_cif *cif,
+ void (*fun) (ffi_cif *, void *, void **, void *))
+{
+#ifdef POWERPC64
+ closure->tramp = ffi_go_closure_linux64;
+#else
+ closure->tramp = ffi_go_closure_sysv;
+#endif
+ closure->cif = cif;
+ closure->fun = fun;
+ return FFI_OK;
+}
diff --git a/contrib/restricted/libffi/src/powerpc/ffi_darwin.c b/contrib/restricted/libffi/src/powerpc/ffi_darwin.c
index f9f587a2eb..61a18c4911 100644
--- a/contrib/restricted/libffi/src/powerpc/ffi_darwin.c
+++ b/contrib/restricted/libffi/src/powerpc/ffi_darwin.c
@@ -1,1440 +1,1440 @@
-/* -----------------------------------------------------------------------
- ffi_darwin.c
-
- Copyright (C) 1998 Geoffrey Keating
- Copyright (C) 2001 John Hornkvist
- Copyright (C) 2002, 2006, 2007, 2009, 2010 Free Software Foundation, Inc.
-
- FFI support for Darwin and AIX.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#include <ffi.h>
-#include <ffi_common.h>
-
-#include <stdlib.h>
-
-extern void ffi_closure_ASM (void);
-extern void ffi_go_closure_ASM (void);
-
-enum {
- /* The assembly depends on these exact flags.
- For Darwin64 (when FLAG_RETURNS_STRUCT is set):
- FLAG_RETURNS_FP indicates that the structure embeds FP data.
- FLAG_RETURNS_128BITS signals a special struct size that is not
- expanded for float content. */
- FLAG_RETURNS_128BITS = 1 << (31-31), /* These go in cr7 */
- FLAG_RETURNS_NOTHING = 1 << (31-30),
- FLAG_RETURNS_FP = 1 << (31-29),
- FLAG_RETURNS_64BITS = 1 << (31-28),
-
- FLAG_RETURNS_STRUCT = 1 << (31-27), /* This goes in cr6 */
-
- FLAG_ARG_NEEDS_COPY = 1 << (31- 7),
- FLAG_FP_ARGUMENTS = 1 << (31- 6), /* cr1.eq; specified by ABI */
- FLAG_4_GPR_ARGUMENTS = 1 << (31- 5),
- FLAG_RETVAL_REFERENCE = 1 << (31- 4)
-};
-
-/* About the DARWIN ABI. */
-enum {
- NUM_GPR_ARG_REGISTERS = 8,
- NUM_FPR_ARG_REGISTERS = 13,
- LINKAGE_AREA_GPRS = 6
-};
-
-enum { ASM_NEEDS_REGISTERS = 4 }; /* r28-r31 */
-
-/* ffi_prep_args is called by the assembly routine once stack space
- has been allocated for the function's arguments.
-
- m32/m64
-
- The stack layout we want looks like this:
-
- | Return address from ffi_call_DARWIN | higher addresses
- |--------------------------------------------|
- | Previous backchain pointer 4/8 | stack pointer here
- |--------------------------------------------|<+ <<< on entry to
- | ASM_NEEDS_REGISTERS=r28-r31 4*(4/8) | | ffi_call_DARWIN
- |--------------------------------------------| |
- | When we have any FP activity... the | |
- | FPRs occupy NUM_FPR_ARG_REGISTERS slots | |
- | here fp13 .. fp1 from high to low addr. | |
- ~ ~ ~
- | Parameters (at least 8*4/8=32/64) | | NUM_GPR_ARG_REGISTERS
- |--------------------------------------------| |
- | TOC=R2 (AIX) Reserved (Darwin) 4/8 | |
- |--------------------------------------------| | stack |
- | Reserved 2*4/8 | | grows |
- |--------------------------------------------| | down V
- | Space for callee's LR 4/8 | |
- |--------------------------------------------| | lower addresses
- | Saved CR [low word for m64] 4/8 | |
- |--------------------------------------------| | stack pointer here
- | Current backchain pointer 4/8 |-/ during
- |--------------------------------------------| <<< ffi_call_DARWIN
-
- */
-
-#if defined(POWERPC_DARWIN64)
-static void
-darwin64_pass_struct_by_value
- (ffi_type *, char *, unsigned, unsigned *, double **, unsigned long **);
-#endif
-
-/* This depends on GPR_SIZE = sizeof (unsigned long) */
-
-void
-ffi_prep_args (extended_cif *ecif, unsigned long *const stack)
-{
- const unsigned bytes = ecif->cif->bytes;
- const unsigned flags = ecif->cif->flags;
- const unsigned nargs = ecif->cif->nargs;
-#if !defined(POWERPC_DARWIN64)
- const ffi_abi abi = ecif->cif->abi;
-#endif
-
- /* 'stacktop' points at the previous backchain pointer. */
- unsigned long *const stacktop = stack + (bytes / sizeof(unsigned long));
-
- /* 'fpr_base' points at the space for fpr1, and grows upwards as
- we use FPR registers. */
- double *fpr_base = (double *) (stacktop - ASM_NEEDS_REGISTERS) - NUM_FPR_ARG_REGISTERS;
- int gp_count = 0, fparg_count = 0;
-
- /* 'next_arg' grows up as we put parameters in it. */
- unsigned long *next_arg = stack + LINKAGE_AREA_GPRS; /* 6 reserved positions. */
-
- int i;
- double double_tmp;
- void **p_argv = ecif->avalue;
- unsigned long gprvalue;
- ffi_type** ptr = ecif->cif->arg_types;
-#if !defined(POWERPC_DARWIN64)
- char *dest_cpy;
-#endif
- unsigned size_al = 0;
-
- /* Check that everything starts aligned properly. */
- FFI_ASSERT(((unsigned) (char *) stack & 0xF) == 0);
- FFI_ASSERT(((unsigned) (char *) stacktop & 0xF) == 0);
- FFI_ASSERT((bytes & 0xF) == 0);
-
- /* Deal with return values that are actually pass-by-reference.
- Rule:
- Return values are referenced by r3, so r4 is the first parameter. */
-
- if (flags & FLAG_RETVAL_REFERENCE)
- *next_arg++ = (unsigned long) (char *) ecif->rvalue;
-
- /* Now for the arguments. */
- for (i = nargs; i > 0; i--, ptr++, p_argv++)
- {
- switch ((*ptr)->type)
- {
- /* If a floating-point parameter appears before all of the general-
- purpose registers are filled, the corresponding GPRs that match
- the size of the floating-point parameter are skipped. */
- case FFI_TYPE_FLOAT:
- double_tmp = *(float *) *p_argv;
- if (fparg_count < NUM_FPR_ARG_REGISTERS)
- *fpr_base++ = double_tmp;
-#if defined(POWERPC_DARWIN)
- *(float *)next_arg = *(float *) *p_argv;
-#else
- *(double *)next_arg = double_tmp;
-#endif
- next_arg++;
- gp_count++;
- fparg_count++;
- FFI_ASSERT(flags & FLAG_FP_ARGUMENTS);
- break;
-
- case FFI_TYPE_DOUBLE:
- double_tmp = *(double *) *p_argv;
- if (fparg_count < NUM_FPR_ARG_REGISTERS)
- *fpr_base++ = double_tmp;
- *(double *)next_arg = double_tmp;
-#ifdef POWERPC64
- next_arg++;
- gp_count++;
-#else
- next_arg += 2;
- gp_count += 2;
-#endif
- fparg_count++;
- FFI_ASSERT(flags & FLAG_FP_ARGUMENTS);
- break;
-
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
-
- case FFI_TYPE_LONGDOUBLE:
-# if defined(POWERPC64) && !defined(POWERPC_DARWIN64)
- /* ??? This will exceed the regs count when the value starts at fp13
- and it will not put the extra bit on the stack. */
- if (fparg_count < NUM_FPR_ARG_REGISTERS)
- *(long double *) fpr_base++ = *(long double *) *p_argv;
- else
- *(long double *) next_arg = *(long double *) *p_argv;
- next_arg += 2;
- fparg_count += 2;
-# else
- double_tmp = ((double *) *p_argv)[0];
- if (fparg_count < NUM_FPR_ARG_REGISTERS)
- *fpr_base++ = double_tmp;
- *(double *) next_arg = double_tmp;
-# if defined(POWERPC_DARWIN64)
- next_arg++;
- gp_count++;
-# else
- next_arg += 2;
- gp_count += 2;
-# endif
- fparg_count++;
- double_tmp = ((double *) *p_argv)[1];
- if (fparg_count < NUM_FPR_ARG_REGISTERS)
- *fpr_base++ = double_tmp;
- *(double *) next_arg = double_tmp;
-# if defined(POWERPC_DARWIN64)
- next_arg++;
- gp_count++;
-# else
- next_arg += 2;
- gp_count += 2;
-# endif
- fparg_count++;
-# endif
- FFI_ASSERT(flags & FLAG_FP_ARGUMENTS);
- break;
-#endif
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
-#ifdef POWERPC64
- gprvalue = *(long long *) *p_argv;
- goto putgpr;
-#else
- *(long long *) next_arg = *(long long *) *p_argv;
- next_arg += 2;
- gp_count += 2;
-#endif
- break;
- case FFI_TYPE_POINTER:
- gprvalue = *(unsigned long *) *p_argv;
- goto putgpr;
- case FFI_TYPE_UINT8:
- gprvalue = *(unsigned char *) *p_argv;
- goto putgpr;
- case FFI_TYPE_SINT8:
- gprvalue = *(signed char *) *p_argv;
- goto putgpr;
- case FFI_TYPE_UINT16:
- gprvalue = *(unsigned short *) *p_argv;
- goto putgpr;
- case FFI_TYPE_SINT16:
- gprvalue = *(signed short *) *p_argv;
- goto putgpr;
-
- case FFI_TYPE_STRUCT:
- size_al = (*ptr)->size;
-#if defined(POWERPC_DARWIN64)
- next_arg = (unsigned long *)FFI_ALIGN((char *)next_arg, (*ptr)->alignment);
- darwin64_pass_struct_by_value (*ptr, (char *) *p_argv,
- (unsigned) size_al,
- (unsigned int *) &fparg_count,
- &fpr_base, &next_arg);
-#else
- dest_cpy = (char *) next_arg;
-
- /* If the first member of the struct is a double, then include enough
- padding in the struct size to align it to double-word. */
- if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE)
- size_al = FFI_ALIGN((*ptr)->size, 8);
-
-# if defined(POWERPC64)
- FFI_ASSERT (abi != FFI_DARWIN);
- memcpy ((char *) dest_cpy, (char *) *p_argv, size_al);
- next_arg += (size_al + 7) / 8;
-# else
- /* Structures that match the basic modes (QI 1 byte, HI 2 bytes,
- SI 4 bytes) are aligned as if they were those modes.
- Structures with 3 byte in size are padded upwards. */
- if (size_al < 3 && abi == FFI_DARWIN)
- dest_cpy += 4 - size_al;
-
- memcpy((char *) dest_cpy, (char *) *p_argv, size_al);
- next_arg += (size_al + 3) / 4;
-# endif
-#endif
- break;
-
- case FFI_TYPE_INT:
- case FFI_TYPE_SINT32:
- gprvalue = *(signed int *) *p_argv;
- goto putgpr;
-
- case FFI_TYPE_UINT32:
- gprvalue = *(unsigned int *) *p_argv;
- putgpr:
- *next_arg++ = gprvalue;
- gp_count++;
- break;
- default:
- break;
- }
- }
-
- /* Check that we didn't overrun the stack... */
- /* FFI_ASSERT(gpr_base <= stacktop - ASM_NEEDS_REGISTERS);
- FFI_ASSERT((unsigned *)fpr_base
- <= stacktop - ASM_NEEDS_REGISTERS - NUM_GPR_ARG_REGISTERS);
- FFI_ASSERT(flags & FLAG_4_GPR_ARGUMENTS || intarg_count <= 4); */
-}
-
-#if defined(POWERPC_DARWIN64)
-
-/* See if we can put some of the struct into fprs.
- This should not be called for structures of size 16 bytes, since these are not
- broken out this way. */
-static void
-darwin64_scan_struct_for_floats (ffi_type *s, unsigned *nfpr)
-{
- int i;
-
- FFI_ASSERT (s->type == FFI_TYPE_STRUCT)
-
- for (i = 0; s->elements[i] != NULL; i++)
- {
- ffi_type *p = s->elements[i];
- switch (p->type)
- {
- case FFI_TYPE_STRUCT:
- darwin64_scan_struct_for_floats (p, nfpr);
- break;
- case FFI_TYPE_LONGDOUBLE:
- (*nfpr) += 2;
- break;
- case FFI_TYPE_DOUBLE:
- case FFI_TYPE_FLOAT:
- (*nfpr) += 1;
- break;
- default:
- break;
- }
- }
-}
-
-static int
-darwin64_struct_size_exceeds_gprs_p (ffi_type *s, char *src, unsigned *nfpr)
-{
- unsigned struct_offset=0, i;
-
- for (i = 0; s->elements[i] != NULL; i++)
- {
- char *item_base;
- ffi_type *p = s->elements[i];
- /* Find the start of this item (0 for the first one). */
- if (i > 0)
- struct_offset = FFI_ALIGN(struct_offset, p->alignment);
-
- item_base = src + struct_offset;
-
- switch (p->type)
- {
- case FFI_TYPE_STRUCT:
- if (darwin64_struct_size_exceeds_gprs_p (p, item_base, nfpr))
- return 1;
- break;
- case FFI_TYPE_LONGDOUBLE:
- if (*nfpr >= NUM_FPR_ARG_REGISTERS)
- return 1;
- (*nfpr) += 1;
- item_base += 8;
- /* FALL THROUGH */
- case FFI_TYPE_DOUBLE:
- if (*nfpr >= NUM_FPR_ARG_REGISTERS)
- return 1;
- (*nfpr) += 1;
- break;
- case FFI_TYPE_FLOAT:
- if (*nfpr >= NUM_FPR_ARG_REGISTERS)
- return 1;
- (*nfpr) += 1;
- break;
- default:
- /* If we try and place any item, that is non-float, once we've
- exceeded the 8 GPR mark, then we can't fit the struct. */
- if ((unsigned long)item_base >= 8*8)
- return 1;
- break;
- }
- /* now count the size of what we just used. */
- struct_offset += p->size;
- }
- return 0;
-}
-
-/* Can this struct be returned by value? */
-int
-darwin64_struct_ret_by_value_p (ffi_type *s)
-{
- unsigned nfp = 0;
-
- FFI_ASSERT (s && s->type == FFI_TYPE_STRUCT);
-
- /* The largest structure we can return is 8long + 13 doubles. */
- if (s->size > 168)
- return 0;
-
- /* We can't pass more than 13 floats. */
- darwin64_scan_struct_for_floats (s, &nfp);
- if (nfp > 13)
- return 0;
-
- /* If there are not too many floats, and the struct is
- small enough to accommodate in the GPRs, then it must be OK. */
- if (s->size <= 64)
- return 1;
-
- /* Well, we have to look harder. */
- nfp = 0;
- if (darwin64_struct_size_exceeds_gprs_p (s, NULL, &nfp))
- return 0;
-
- return 1;
-}
-
-void
-darwin64_pass_struct_floats (ffi_type *s, char *src,
- unsigned *nfpr, double **fprs)
-{
- int i;
- double *fpr_base = *fprs;
- unsigned struct_offset = 0;
-
- /* We don't assume anything about the alignment of the source. */
- for (i = 0; s->elements[i] != NULL; i++)
- {
- char *item_base;
- ffi_type *p = s->elements[i];
- /* Find the start of this item (0 for the first one). */
- if (i > 0)
- struct_offset = FFI_ALIGN(struct_offset, p->alignment);
- item_base = src + struct_offset;
-
- switch (p->type)
- {
- case FFI_TYPE_STRUCT:
- darwin64_pass_struct_floats (p, item_base, nfpr,
- &fpr_base);
- break;
- case FFI_TYPE_LONGDOUBLE:
- if (*nfpr < NUM_FPR_ARG_REGISTERS)
- *fpr_base++ = *(double *)item_base;
- (*nfpr) += 1;
- item_base += 8;
- /* FALL THROUGH */
- case FFI_TYPE_DOUBLE:
- if (*nfpr < NUM_FPR_ARG_REGISTERS)
- *fpr_base++ = *(double *)item_base;
- (*nfpr) += 1;
- break;
- case FFI_TYPE_FLOAT:
- if (*nfpr < NUM_FPR_ARG_REGISTERS)
- *fpr_base++ = (double) *(float *)item_base;
- (*nfpr) += 1;
- break;
- default:
- break;
- }
- /* now count the size of what we just used. */
- struct_offset += p->size;
- }
- /* Update the scores. */
- *fprs = fpr_base;
-}
-
-/* Darwin64 special rules.
- Break out a struct into params and float registers. */
-static void
-darwin64_pass_struct_by_value (ffi_type *s, char *src, unsigned size,
- unsigned *nfpr, double **fprs, unsigned long **arg)
-{
- unsigned long *next_arg = *arg;
- char *dest_cpy = (char *)next_arg;
-
- FFI_ASSERT (s->type == FFI_TYPE_STRUCT)
-
- if (!size)
- return;
-
- /* First... special cases. */
- if (size < 3
- || (size == 4
- && s->elements[0]
- && s->elements[0]->type != FFI_TYPE_FLOAT))
- {
- /* Must be at least one GPR, padding is unspecified in value,
- let's make it zero. */
- *next_arg = 0UL;
- dest_cpy += 8 - size;
- memcpy ((char *) dest_cpy, src, size);
- next_arg++;
- }
- else if (size == 16)
- {
- memcpy ((char *) dest_cpy, src, size);
- next_arg += 2;
- }
- else
- {
- /* now the general case, we consider embedded floats. */
- memcpy ((char *) dest_cpy, src, size);
- darwin64_pass_struct_floats (s, src, nfpr, fprs);
- next_arg += (size+7)/8;
- }
-
- *arg = next_arg;
-}
-
-double *
-darwin64_struct_floats_to_mem (ffi_type *s, char *dest, double *fprs, unsigned *nf)
-{
- int i;
- unsigned struct_offset = 0;
-
- /* We don't assume anything about the alignment of the source. */
- for (i = 0; s->elements[i] != NULL; i++)
- {
- char *item_base;
- ffi_type *p = s->elements[i];
- /* Find the start of this item (0 for the first one). */
- if (i > 0)
- struct_offset = FFI_ALIGN(struct_offset, p->alignment);
- item_base = dest + struct_offset;
-
- switch (p->type)
- {
- case FFI_TYPE_STRUCT:
- fprs = darwin64_struct_floats_to_mem (p, item_base, fprs, nf);
- break;
- case FFI_TYPE_LONGDOUBLE:
- if (*nf < NUM_FPR_ARG_REGISTERS)
- {
- *(double *)item_base = *fprs++ ;
- (*nf) += 1;
- }
- item_base += 8;
- /* FALL THROUGH */
- case FFI_TYPE_DOUBLE:
- if (*nf < NUM_FPR_ARG_REGISTERS)
- {
- *(double *)item_base = *fprs++ ;
- (*nf) += 1;
- }
- break;
- case FFI_TYPE_FLOAT:
- if (*nf < NUM_FPR_ARG_REGISTERS)
- {
- *(float *)item_base = (float) *fprs++ ;
- (*nf) += 1;
- }
- break;
- default:
- break;
- }
- /* now count the size of what we just used. */
- struct_offset += p->size;
- }
- return fprs;
-}
-
-#endif
-
-/* Adjust the size of S to be correct for Darwin.
- On Darwin m32, the first field of a structure has natural alignment.
- On Darwin m64, all fields have natural alignment. */
-
-static void
-darwin_adjust_aggregate_sizes (ffi_type *s)
-{
- int i;
-
- if (s->type != FFI_TYPE_STRUCT)
- return;
-
- s->size = 0;
- for (i = 0; s->elements[i] != NULL; i++)
- {
- ffi_type *p;
- int align;
-
- p = s->elements[i];
- if (p->type == FFI_TYPE_STRUCT)
- darwin_adjust_aggregate_sizes (p);
-#if defined(POWERPC_DARWIN64)
- /* Natural alignment for all items. */
- align = p->alignment;
-#else
- /* Natural alignment for the first item... */
- if (i == 0)
- align = p->alignment;
- else if (p->alignment == 16 || p->alignment < 4)
- /* .. subsequent items with vector or align < 4 have natural align. */
- align = p->alignment;
- else
- /* .. or align is 4. */
- align = 4;
-#endif
- /* Pad, if necessary, before adding the current item. */
- s->size = FFI_ALIGN(s->size, align) + p->size;
- }
+/* -----------------------------------------------------------------------
+ ffi_darwin.c
+
+ Copyright (C) 1998 Geoffrey Keating
+ Copyright (C) 2001 John Hornkvist
+ Copyright (C) 2002, 2006, 2007, 2009, 2010 Free Software Foundation, Inc.
+
+ FFI support for Darwin and AIX.
- s->size = FFI_ALIGN(s->size, s->alignment);
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#include <ffi.h>
+#include <ffi_common.h>
+
+#include <stdlib.h>
+
+extern void ffi_closure_ASM (void);
+extern void ffi_go_closure_ASM (void);
+
+enum {
+ /* The assembly depends on these exact flags.
+ For Darwin64 (when FLAG_RETURNS_STRUCT is set):
+ FLAG_RETURNS_FP indicates that the structure embeds FP data.
+ FLAG_RETURNS_128BITS signals a special struct size that is not
+ expanded for float content. */
+ FLAG_RETURNS_128BITS = 1 << (31-31), /* These go in cr7 */
+ FLAG_RETURNS_NOTHING = 1 << (31-30),
+ FLAG_RETURNS_FP = 1 << (31-29),
+ FLAG_RETURNS_64BITS = 1 << (31-28),
+
+ FLAG_RETURNS_STRUCT = 1 << (31-27), /* This goes in cr6 */
+
+ FLAG_ARG_NEEDS_COPY = 1 << (31- 7),
+ FLAG_FP_ARGUMENTS = 1 << (31- 6), /* cr1.eq; specified by ABI */
+ FLAG_4_GPR_ARGUMENTS = 1 << (31- 5),
+ FLAG_RETVAL_REFERENCE = 1 << (31- 4)
+};
+
+/* About the DARWIN ABI. */
+enum {
+ NUM_GPR_ARG_REGISTERS = 8,
+ NUM_FPR_ARG_REGISTERS = 13,
+ LINKAGE_AREA_GPRS = 6
+};
+
+enum { ASM_NEEDS_REGISTERS = 4 }; /* r28-r31 */
+
+/* ffi_prep_args is called by the assembly routine once stack space
+ has been allocated for the function's arguments.
- /* This should not be necessary on m64, but harmless. */
- if (s->elements[0]->type == FFI_TYPE_UINT64
- || s->elements[0]->type == FFI_TYPE_SINT64
- || s->elements[0]->type == FFI_TYPE_DOUBLE
- || s->elements[0]->alignment == 8)
- s->alignment = s->alignment > 8 ? s->alignment : 8;
- /* Do not add additional tail padding. */
-}
-
-/* Adjust the size of S to be correct for AIX.
- Word-align double unless it is the first member of a structure. */
-
-static void
-aix_adjust_aggregate_sizes (ffi_type *s)
-{
- int i;
-
- if (s->type != FFI_TYPE_STRUCT)
- return;
-
- s->size = 0;
- for (i = 0; s->elements[i] != NULL; i++)
- {
- ffi_type *p;
- int align;
-
- p = s->elements[i];
- aix_adjust_aggregate_sizes (p);
- align = p->alignment;
- if (i != 0 && p->type == FFI_TYPE_DOUBLE)
- align = 4;
- s->size = FFI_ALIGN(s->size, align) + p->size;
- }
-
- s->size = FFI_ALIGN(s->size, s->alignment);
-
- if (s->elements[0]->type == FFI_TYPE_UINT64
- || s->elements[0]->type == FFI_TYPE_SINT64
- || s->elements[0]->type == FFI_TYPE_DOUBLE
- || s->elements[0]->alignment == 8)
- s->alignment = s->alignment > 8 ? s->alignment : 8;
- /* Do not add additional tail padding. */
-}
-
-/* Perform machine dependent cif processing. */
-ffi_status
-ffi_prep_cif_machdep (ffi_cif *cif)
-{
- /* All this is for the DARWIN ABI. */
- unsigned i;
- ffi_type **ptr;
- unsigned bytes;
- unsigned fparg_count = 0, intarg_count = 0;
- unsigned flags = 0;
- unsigned size_al = 0;
-
- /* All the machine-independent calculation of cif->bytes will be wrong.
- All the calculation of structure sizes will also be wrong.
- Redo the calculation for DARWIN. */
-
- if (cif->abi == FFI_DARWIN)
- {
- darwin_adjust_aggregate_sizes (cif->rtype);
- for (i = 0; i < cif->nargs; i++)
- darwin_adjust_aggregate_sizes (cif->arg_types[i]);
- }
-
- if (cif->abi == FFI_AIX)
- {
- aix_adjust_aggregate_sizes (cif->rtype);
- for (i = 0; i < cif->nargs; i++)
- aix_adjust_aggregate_sizes (cif->arg_types[i]);
- }
-
- /* Space for the frame pointer, callee's LR, CR, etc, and for
- the asm's temp regs. */
-
- bytes = (LINKAGE_AREA_GPRS + ASM_NEEDS_REGISTERS) * sizeof(unsigned long);
-
- /* Return value handling.
- The rules m32 are as follows:
- - 32-bit (or less) integer values are returned in gpr3;
- - structures of size <= 4 bytes also returned in gpr3;
- - 64-bit integer values [??? and structures between 5 and 8 bytes] are
- returned in gpr3 and gpr4;
- - Single/double FP values are returned in fpr1;
- - Long double FP (if not equivalent to double) values are returned in
- fpr1 and fpr2;
- m64:
- - 64-bit or smaller integral values are returned in GPR3
- - Single/double FP values are returned in fpr1;
- - Long double FP values are returned in fpr1 and fpr2;
- m64 Structures:
- - If the structure could be accommodated in registers were it to be the
- first argument to a routine, then it is returned in those registers.
- m32/m64 structures otherwise:
- - Larger structures values are allocated space and a pointer is passed
- as the first argument. */
- switch (cif->rtype->type)
- {
-
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- flags |= FLAG_RETURNS_128BITS;
- flags |= FLAG_RETURNS_FP;
- break;
-#endif
-
- case FFI_TYPE_DOUBLE:
- flags |= FLAG_RETURNS_64BITS;
- /* Fall through. */
- case FFI_TYPE_FLOAT:
- flags |= FLAG_RETURNS_FP;
- break;
-
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
-#ifdef POWERPC64
- case FFI_TYPE_POINTER:
-#endif
- flags |= FLAG_RETURNS_64BITS;
- break;
-
- case FFI_TYPE_STRUCT:
-#if defined(POWERPC_DARWIN64)
- {
- /* Can we fit the struct into regs? */
- if (darwin64_struct_ret_by_value_p (cif->rtype))
- {
- unsigned nfpr = 0;
- flags |= FLAG_RETURNS_STRUCT;
- if (cif->rtype->size != 16)
- darwin64_scan_struct_for_floats (cif->rtype, &nfpr) ;
- else
- flags |= FLAG_RETURNS_128BITS;
- /* Will be 0 for 16byte struct. */
- if (nfpr)
- flags |= FLAG_RETURNS_FP;
- }
- else /* By ref. */
- {
- flags |= FLAG_RETVAL_REFERENCE;
- flags |= FLAG_RETURNS_NOTHING;
- intarg_count++;
- }
- }
-#elif defined(DARWIN_PPC)
- if (cif->rtype->size <= 4)
- flags |= FLAG_RETURNS_STRUCT;
- else /* else by reference. */
- {
- flags |= FLAG_RETVAL_REFERENCE;
- flags |= FLAG_RETURNS_NOTHING;
- intarg_count++;
- }
-#else /* assume we pass by ref. */
- flags |= FLAG_RETVAL_REFERENCE;
- flags |= FLAG_RETURNS_NOTHING;
- intarg_count++;
-#endif
- break;
- case FFI_TYPE_VOID:
- flags |= FLAG_RETURNS_NOTHING;
- break;
-
- default:
- /* Returns 32-bit integer, or similar. Nothing to do here. */
- break;
- }
-
- /* The first NUM_GPR_ARG_REGISTERS words of integer arguments, and the
- first NUM_FPR_ARG_REGISTERS fp arguments, go in registers; the rest
- goes on the stack.
- ??? Structures are passed as a pointer to a copy of the structure.
- Stuff on the stack needs to keep proper alignment.
- For m64 the count is effectively of half-GPRs. */
- for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++)
- {
- unsigned align_words;
- switch ((*ptr)->type)
- {
- case FFI_TYPE_FLOAT:
- case FFI_TYPE_DOUBLE:
- fparg_count++;
+ m32/m64
+
+ The stack layout we want looks like this:
+
+ | Return address from ffi_call_DARWIN | higher addresses
+ |--------------------------------------------|
+ | Previous backchain pointer 4/8 | stack pointer here
+ |--------------------------------------------|<+ <<< on entry to
+ | ASM_NEEDS_REGISTERS=r28-r31 4*(4/8) | | ffi_call_DARWIN
+ |--------------------------------------------| |
+ | When we have any FP activity... the | |
+ | FPRs occupy NUM_FPR_ARG_REGISTERS slots | |
+ | here fp13 .. fp1 from high to low addr. | |
+ ~ ~ ~
+ | Parameters (at least 8*4/8=32/64) | | NUM_GPR_ARG_REGISTERS
+ |--------------------------------------------| |
+ | TOC=R2 (AIX) Reserved (Darwin) 4/8 | |
+ |--------------------------------------------| | stack |
+ | Reserved 2*4/8 | | grows |
+ |--------------------------------------------| | down V
+ | Space for callee's LR 4/8 | |
+ |--------------------------------------------| | lower addresses
+ | Saved CR [low word for m64] 4/8 | |
+ |--------------------------------------------| | stack pointer here
+ | Current backchain pointer 4/8 |-/ during
+ |--------------------------------------------| <<< ffi_call_DARWIN
+
+ */
+
+#if defined(POWERPC_DARWIN64)
+static void
+darwin64_pass_struct_by_value
+ (ffi_type *, char *, unsigned, unsigned *, double **, unsigned long **);
+#endif
+
+/* This depends on GPR_SIZE = sizeof (unsigned long) */
+
+void
+ffi_prep_args (extended_cif *ecif, unsigned long *const stack)
+{
+ const unsigned bytes = ecif->cif->bytes;
+ const unsigned flags = ecif->cif->flags;
+ const unsigned nargs = ecif->cif->nargs;
#if !defined(POWERPC_DARWIN64)
- /* If this FP arg is going on the stack, it must be
- 8-byte-aligned. */
- if (fparg_count > NUM_FPR_ARG_REGISTERS
- && (intarg_count & 0x01) != 0)
- intarg_count++;
-#endif
- break;
-
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- fparg_count += 2;
- /* If this FP arg is going on the stack, it must be
- 16-byte-aligned. */
- if (fparg_count >= NUM_FPR_ARG_REGISTERS)
-#if defined (POWERPC64)
- intarg_count = FFI_ALIGN(intarg_count, 2);
-#else
- intarg_count = FFI_ALIGN(intarg_count, 4);
-#endif
- break;
-#endif
-
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
-#if defined(POWERPC64)
- intarg_count++;
-#else
- /* 'long long' arguments are passed as two words, but
- either both words must fit in registers or both go
- on the stack. If they go on the stack, they must
- be 8-byte-aligned. */
- if (intarg_count == NUM_GPR_ARG_REGISTERS-1
- || (intarg_count >= NUM_GPR_ARG_REGISTERS
- && (intarg_count & 0x01) != 0))
- intarg_count++;
- intarg_count += 2;
-#endif
- break;
-
- case FFI_TYPE_STRUCT:
- size_al = (*ptr)->size;
-#if defined(POWERPC_DARWIN64)
- align_words = (*ptr)->alignment >> 3;
- if (align_words)
- intarg_count = FFI_ALIGN(intarg_count, align_words);
- /* Base size of the struct. */
- intarg_count += (size_al + 7) / 8;
- /* If 16 bytes then don't worry about floats. */
- if (size_al != 16)
- /* Scan through for floats to be placed in regs. */
- darwin64_scan_struct_for_floats (*ptr, &fparg_count) ;
-#else
- align_words = (*ptr)->alignment >> 2;
- if (align_words)
- intarg_count = FFI_ALIGN(intarg_count, align_words);
- /* If the first member of the struct is a double, then align
- the struct to double-word.
- if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE)
- size_al = FFI_ALIGN((*ptr)->size, 8); */
-# ifdef POWERPC64
- intarg_count += (size_al + 7) / 8;
-# else
- intarg_count += (size_al + 3) / 4;
-# endif
-#endif
- break;
-
- default:
- /* Everything else is passed as a 4-byte word in a GPR, either
- the object itself or a pointer to it. */
- intarg_count++;
- break;
- }
- }
-
- if (fparg_count != 0)
- flags |= FLAG_FP_ARGUMENTS;
-
-#if defined(POWERPC_DARWIN64)
- /* Space to image the FPR registers, if needed - which includes when they might be
- used in a struct return. */
- if (fparg_count != 0
- || ((flags & FLAG_RETURNS_STRUCT)
- && (flags & FLAG_RETURNS_FP)))
- bytes += NUM_FPR_ARG_REGISTERS * sizeof(double);
-#else
- /* Space for the FPR registers, if needed. */
- if (fparg_count != 0)
- bytes += NUM_FPR_ARG_REGISTERS * sizeof(double);
-#endif
-
- /* Stack space. */
-#ifdef POWERPC64
- if ((intarg_count + fparg_count) > NUM_GPR_ARG_REGISTERS)
- bytes += (intarg_count + fparg_count) * sizeof(long);
-#else
- if ((intarg_count + 2 * fparg_count) > NUM_GPR_ARG_REGISTERS)
- bytes += (intarg_count + 2 * fparg_count) * sizeof(long);
-#endif
- else
- bytes += NUM_GPR_ARG_REGISTERS * sizeof(long);
-
- /* The stack space allocated needs to be a multiple of 16 bytes. */
- bytes = FFI_ALIGN(bytes, 16) ;
-
- cif->flags = flags;
- cif->bytes = bytes;
-
- return FFI_OK;
-}
-
-extern void ffi_call_AIX(extended_cif *, long, unsigned, unsigned *,
- void (*fn)(void), void (*fn2)(void));
-
-extern void ffi_call_go_AIX(extended_cif *, long, unsigned, unsigned *,
- void (*fn)(void), void (*fn2)(void), void *closure);
-
-extern void ffi_call_DARWIN(extended_cif *, long, unsigned, unsigned *,
- void (*fn)(void), void (*fn2)(void), ffi_type*);
-
-void
-ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
-{
- extended_cif ecif;
-
- ecif.cif = cif;
- ecif.avalue = avalue;
-
- /* If the return value is a struct and we don't have a return
- value address then we need to make one. */
-
- if ((rvalue == NULL) &&
- (cif->rtype->type == FFI_TYPE_STRUCT))
- {
- ecif.rvalue = alloca (cif->rtype->size);
- }
- else
- ecif.rvalue = rvalue;
-
- switch (cif->abi)
- {
- case FFI_AIX:
- ffi_call_AIX(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn,
- FFI_FN(ffi_prep_args));
- break;
- case FFI_DARWIN:
- ffi_call_DARWIN(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn,
- FFI_FN(ffi_prep_args), cif->rtype);
- break;
- default:
- FFI_ASSERT(0);
- break;
- }
-}
-
-void
-ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue,
- void *closure)
-{
- extended_cif ecif;
-
- ecif.cif = cif;
- ecif.avalue = avalue;
-
- /* If the return value is a struct and we don't have a return
- value address then we need to make one. */
-
- if ((rvalue == NULL) &&
- (cif->rtype->type == FFI_TYPE_STRUCT))
- {
- ecif.rvalue = alloca (cif->rtype->size);
- }
- else
- ecif.rvalue = rvalue;
-
- switch (cif->abi)
- {
- case FFI_AIX:
- ffi_call_go_AIX(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn,
- FFI_FN(ffi_prep_args), closure);
- break;
- default:
- FFI_ASSERT(0);
- break;
- }
-}
-
-static void flush_icache(char *);
-static void flush_range(char *, int);
-
-/* The layout of a function descriptor. A C function pointer really
- points to one of these. */
-
-typedef struct aix_fd_struct {
- void *code_pointer;
- void *toc;
-} aix_fd;
-
-/* here I'd like to add the stack frame layout we use in darwin_closure.S
- and aix_closure.S
-
- m32/m64
-
- The stack layout looks like this:
-
- | Additional params... | | Higher address
- ~ ~ ~
- | Parameters (at least 8*4/8=32/64) | | NUM_GPR_ARG_REGISTERS
- |--------------------------------------------| |
- | TOC=R2 (AIX) Reserved (Darwin) 4/8 | |
- |--------------------------------------------| |
- | Reserved 2*4/8 | |
- |--------------------------------------------| |
- | Space for callee's LR 4/8 | |
- |--------------------------------------------| |
- | Saved CR [low word for m64] 4/8 | |
- |--------------------------------------------| |
- | Current backchain pointer 4/8 |-/ Parent's frame.
- |--------------------------------------------| <+ <<< on entry to ffi_closure_ASM
- | Result Bytes 16 | |
- |--------------------------------------------| |
- ~ padding to 16-byte alignment ~ ~
- |--------------------------------------------| |
- | NUM_FPR_ARG_REGISTERS slots | |
- | here fp13 .. fp1 13*8 | |
- |--------------------------------------------| |
- | R3..R10 8*4/8=32/64 | | NUM_GPR_ARG_REGISTERS
- |--------------------------------------------| |
- | TOC=R2 (AIX) Reserved (Darwin) 4/8 | |
- |--------------------------------------------| | stack |
- | Reserved [compiler,binder] 2*4/8 | | grows |
- |--------------------------------------------| | down V
- | Space for callee's LR 4/8 | |
- |--------------------------------------------| | lower addresses
- | Saved CR [low word for m64] 4/8 | |
- |--------------------------------------------| | stack pointer here
- | Current backchain pointer 4/8 |-/ during
- |--------------------------------------------| <<< ffi_closure_ASM.
-
-*/
-
-ffi_status
-ffi_prep_closure_loc (ffi_closure* closure,
- ffi_cif* cif,
- void (*fun)(ffi_cif*, void*, void**, void*),
- void *user_data,
- void *codeloc)
-{
- unsigned int *tramp;
- struct ffi_aix_trampoline_struct *tramp_aix;
- aix_fd *fd;
-
- switch (cif->abi)
- {
- case FFI_DARWIN:
-
- FFI_ASSERT (cif->abi == FFI_DARWIN);
-
- tramp = (unsigned int *) &closure->tramp[0];
-#if defined(POWERPC_DARWIN64)
- tramp[0] = 0x7c0802a6; /* mflr r0 */
- tramp[1] = 0x429f0015; /* bcl- 20,4*cr7+so, +0x18 (L1) */
- /* We put the addresses here. */
- tramp[6] = 0x7d6802a6; /*L1: mflr r11 */
- tramp[7] = 0xe98b0000; /* ld r12,0(r11) function address */
- tramp[8] = 0x7c0803a6; /* mtlr r0 */
- tramp[9] = 0x7d8903a6; /* mtctr r12 */
- tramp[10] = 0xe96b0008; /* lwz r11,8(r11) static chain */
- tramp[11] = 0x4e800420; /* bctr */
-
- *((unsigned long *)&tramp[2]) = (unsigned long) ffi_closure_ASM; /* function */
- *((unsigned long *)&tramp[4]) = (unsigned long) codeloc; /* context */
-#else
- tramp[0] = 0x7c0802a6; /* mflr r0 */
- tramp[1] = 0x429f000d; /* bcl- 20,4*cr7+so,0x10 */
- tramp[4] = 0x7d6802a6; /* mflr r11 */
- tramp[5] = 0x818b0000; /* lwz r12,0(r11) function address */
- tramp[6] = 0x7c0803a6; /* mtlr r0 */
- tramp[7] = 0x7d8903a6; /* mtctr r12 */
- tramp[8] = 0x816b0004; /* lwz r11,4(r11) static chain */
- tramp[9] = 0x4e800420; /* bctr */
- tramp[2] = (unsigned long) ffi_closure_ASM; /* function */
- tramp[3] = (unsigned long) codeloc; /* context */
-#endif
- closure->cif = cif;
- closure->fun = fun;
- closure->user_data = user_data;
-
- /* Flush the icache. Only necessary on Darwin. */
- flush_range(codeloc, FFI_TRAMPOLINE_SIZE);
-
- break;
-
- case FFI_AIX:
-
- tramp_aix = (struct ffi_aix_trampoline_struct *) (closure->tramp);
- fd = (aix_fd *)(void *)ffi_closure_ASM;
-
- FFI_ASSERT (cif->abi == FFI_AIX);
-
- tramp_aix->code_pointer = fd->code_pointer;
- tramp_aix->toc = fd->toc;
- tramp_aix->static_chain = codeloc;
- closure->cif = cif;
- closure->fun = fun;
- closure->user_data = user_data;
- break;
-
- default:
- return FFI_BAD_ABI;
- break;
- }
- return FFI_OK;
-}
-
-ffi_status
-ffi_prep_go_closure (ffi_go_closure* closure,
- ffi_cif* cif,
- void (*fun)(ffi_cif*, void*, void**, void*))
-{
- switch (cif->abi)
- {
- case FFI_AIX:
-
- FFI_ASSERT (cif->abi == FFI_AIX);
-
- closure->tramp = (void *)ffi_go_closure_ASM;
- closure->cif = cif;
- closure->fun = fun;
- return FFI_OK;
-
- // For now, ffi_prep_go_closure is only implemented for AIX, not for Darwin
- default:
- return FFI_BAD_ABI;
- break;
- }
- return FFI_OK;
-}
-
-static void
-flush_icache(char *addr)
-{
-#ifndef _AIX
- __asm__ volatile (
- "dcbf 0,%0\n"
- "\tsync\n"
- "\ticbi 0,%0\n"
- "\tsync\n"
- "\tisync"
- : : "r"(addr) : "memory");
-#endif
-}
-
-static void
-flush_range(char * addr1, int size)
-{
-#define MIN_LINE_SIZE 32
- int i;
- for (i = 0; i < size; i += MIN_LINE_SIZE)
- flush_icache(addr1+i);
- flush_icache(addr1+size-1);
-}
-
-typedef union
-{
- float f;
- double d;
-} ffi_dblfl;
-
-ffi_type *
-ffi_closure_helper_DARWIN (ffi_closure *, void *,
- unsigned long *, ffi_dblfl *);
-
-ffi_type *
-ffi_go_closure_helper_DARWIN (ffi_go_closure*, void *,
- unsigned long *, ffi_dblfl *);
-
-/* Basically the trampoline invokes ffi_closure_ASM, and on
- entry, r11 holds the address of the closure.
- After storing the registers that could possibly contain
- parameters to be passed into the stack frame and setting
- up space for a return value, ffi_closure_ASM invokes the
- following helper function to do most of the work. */
-
-static ffi_type *
-ffi_closure_helper_common (ffi_cif* cif,
- void (*fun)(ffi_cif*, void*, void**, void*),
- void *user_data, void *rvalue,
- unsigned long *pgr, ffi_dblfl *pfr)
-{
- /* rvalue is the pointer to space for return value in closure assembly
- pgr is the pointer to where r3-r10 are stored in ffi_closure_ASM
- pfr is the pointer to where f1-f13 are stored in ffi_closure_ASM. */
-
- typedef double ldbits[2];
-
- union ldu
- {
- ldbits lb;
- long double ld;
- };
-
- void ** avalue;
- ffi_type ** arg_types;
- long i, avn;
- ffi_dblfl * end_pfr = pfr + NUM_FPR_ARG_REGISTERS;
- unsigned size_al;
-#if defined(POWERPC_DARWIN64)
- unsigned fpsused = 0;
-#endif
-
- avalue = alloca (cif->nargs * sizeof(void *));
-
- if (cif->rtype->type == FFI_TYPE_STRUCT)
- {
-#if defined(POWERPC_DARWIN64)
- if (!darwin64_struct_ret_by_value_p (cif->rtype))
- {
- /* Won't fit into the regs - return by ref. */
- rvalue = (void *) *pgr;
- pgr++;
- }
-#elif defined(DARWIN_PPC)
- if (cif->rtype->size > 4)
- {
- rvalue = (void *) *pgr;
- pgr++;
- }
-#else /* assume we return by ref. */
- rvalue = (void *) *pgr;
- pgr++;
-#endif
- }
-
- i = 0;
- avn = cif->nargs;
- arg_types = cif->arg_types;
-
- /* Grab the addresses of the arguments from the stack frame. */
- while (i < avn)
- {
- switch (arg_types[i]->type)
- {
- case FFI_TYPE_SINT8:
- case FFI_TYPE_UINT8:
-#if defined(POWERPC64)
- avalue[i] = (char *) pgr + 7;
-#else
- avalue[i] = (char *) pgr + 3;
-#endif
- pgr++;
- break;
-
- case FFI_TYPE_SINT16:
- case FFI_TYPE_UINT16:
-#if defined(POWERPC64)
- avalue[i] = (char *) pgr + 6;
-#else
- avalue[i] = (char *) pgr + 2;
-#endif
- pgr++;
- break;
-
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT32:
-#if defined(POWERPC64)
- avalue[i] = (char *) pgr + 4;
-#else
- case FFI_TYPE_POINTER:
- avalue[i] = pgr;
-#endif
- pgr++;
- break;
-
- case FFI_TYPE_STRUCT:
- size_al = arg_types[i]->size;
-#if defined(POWERPC_DARWIN64)
- pgr = (unsigned long *)FFI_ALIGN((char *)pgr, arg_types[i]->alignment);
- if (size_al < 3 || size_al == 4)
- {
- avalue[i] = ((char *)pgr)+8-size_al;
- if (arg_types[i]->elements[0]->type == FFI_TYPE_FLOAT
- && fpsused < NUM_FPR_ARG_REGISTERS)
- {
- *(float *)pgr = (float) *(double *)pfr;
- pfr++;
- fpsused++;
- }
- }
- else
- {
- if (size_al != 16)
- pfr = (ffi_dblfl *)
- darwin64_struct_floats_to_mem (arg_types[i], (char *)pgr,
- (double *)pfr, &fpsused);
- avalue[i] = pgr;
- }
- pgr += (size_al + 7) / 8;
-#else
- /* If the first member of the struct is a double, then align
- the struct to double-word. */
- if (arg_types[i]->elements[0]->type == FFI_TYPE_DOUBLE)
- size_al = FFI_ALIGN(arg_types[i]->size, 8);
+ const ffi_abi abi = ecif->cif->abi;
+#endif
+
+ /* 'stacktop' points at the previous backchain pointer. */
+ unsigned long *const stacktop = stack + (bytes / sizeof(unsigned long));
+
+ /* 'fpr_base' points at the space for fpr1, and grows upwards as
+ we use FPR registers. */
+ double *fpr_base = (double *) (stacktop - ASM_NEEDS_REGISTERS) - NUM_FPR_ARG_REGISTERS;
+ int gp_count = 0, fparg_count = 0;
+
+ /* 'next_arg' grows up as we put parameters in it. */
+ unsigned long *next_arg = stack + LINKAGE_AREA_GPRS; /* 6 reserved positions. */
+
+ int i;
+ double double_tmp;
+ void **p_argv = ecif->avalue;
+ unsigned long gprvalue;
+ ffi_type** ptr = ecif->cif->arg_types;
+#if !defined(POWERPC_DARWIN64)
+ char *dest_cpy;
+#endif
+ unsigned size_al = 0;
+
+ /* Check that everything starts aligned properly. */
+ FFI_ASSERT(((unsigned) (char *) stack & 0xF) == 0);
+ FFI_ASSERT(((unsigned) (char *) stacktop & 0xF) == 0);
+ FFI_ASSERT((bytes & 0xF) == 0);
+
+ /* Deal with return values that are actually pass-by-reference.
+ Rule:
+ Return values are referenced by r3, so r4 is the first parameter. */
+
+ if (flags & FLAG_RETVAL_REFERENCE)
+ *next_arg++ = (unsigned long) (char *) ecif->rvalue;
+
+ /* Now for the arguments. */
+ for (i = nargs; i > 0; i--, ptr++, p_argv++)
+ {
+ switch ((*ptr)->type)
+ {
+ /* If a floating-point parameter appears before all of the general-
+ purpose registers are filled, the corresponding GPRs that match
+ the size of the floating-point parameter are skipped. */
+ case FFI_TYPE_FLOAT:
+ double_tmp = *(float *) *p_argv;
+ if (fparg_count < NUM_FPR_ARG_REGISTERS)
+ *fpr_base++ = double_tmp;
+#if defined(POWERPC_DARWIN)
+ *(float *)next_arg = *(float *) *p_argv;
+#else
+ *(double *)next_arg = double_tmp;
+#endif
+ next_arg++;
+ gp_count++;
+ fparg_count++;
+ FFI_ASSERT(flags & FLAG_FP_ARGUMENTS);
+ break;
+
+ case FFI_TYPE_DOUBLE:
+ double_tmp = *(double *) *p_argv;
+ if (fparg_count < NUM_FPR_ARG_REGISTERS)
+ *fpr_base++ = double_tmp;
+ *(double *)next_arg = double_tmp;
+#ifdef POWERPC64
+ next_arg++;
+ gp_count++;
+#else
+ next_arg += 2;
+ gp_count += 2;
+#endif
+ fparg_count++;
+ FFI_ASSERT(flags & FLAG_FP_ARGUMENTS);
+ break;
+
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+
+ case FFI_TYPE_LONGDOUBLE:
+# if defined(POWERPC64) && !defined(POWERPC_DARWIN64)
+ /* ??? This will exceed the regs count when the value starts at fp13
+ and it will not put the extra bit on the stack. */
+ if (fparg_count < NUM_FPR_ARG_REGISTERS)
+ *(long double *) fpr_base++ = *(long double *) *p_argv;
+ else
+ *(long double *) next_arg = *(long double *) *p_argv;
+ next_arg += 2;
+ fparg_count += 2;
+# else
+ double_tmp = ((double *) *p_argv)[0];
+ if (fparg_count < NUM_FPR_ARG_REGISTERS)
+ *fpr_base++ = double_tmp;
+ *(double *) next_arg = double_tmp;
+# if defined(POWERPC_DARWIN64)
+ next_arg++;
+ gp_count++;
+# else
+ next_arg += 2;
+ gp_count += 2;
+# endif
+ fparg_count++;
+ double_tmp = ((double *) *p_argv)[1];
+ if (fparg_count < NUM_FPR_ARG_REGISTERS)
+ *fpr_base++ = double_tmp;
+ *(double *) next_arg = double_tmp;
+# if defined(POWERPC_DARWIN64)
+ next_arg++;
+ gp_count++;
+# else
+ next_arg += 2;
+ gp_count += 2;
+# endif
+ fparg_count++;
+# endif
+ FFI_ASSERT(flags & FLAG_FP_ARGUMENTS);
+ break;
+#endif
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+#ifdef POWERPC64
+ gprvalue = *(long long *) *p_argv;
+ goto putgpr;
+#else
+ *(long long *) next_arg = *(long long *) *p_argv;
+ next_arg += 2;
+ gp_count += 2;
+#endif
+ break;
+ case FFI_TYPE_POINTER:
+ gprvalue = *(unsigned long *) *p_argv;
+ goto putgpr;
+ case FFI_TYPE_UINT8:
+ gprvalue = *(unsigned char *) *p_argv;
+ goto putgpr;
+ case FFI_TYPE_SINT8:
+ gprvalue = *(signed char *) *p_argv;
+ goto putgpr;
+ case FFI_TYPE_UINT16:
+ gprvalue = *(unsigned short *) *p_argv;
+ goto putgpr;
+ case FFI_TYPE_SINT16:
+ gprvalue = *(signed short *) *p_argv;
+ goto putgpr;
+
+ case FFI_TYPE_STRUCT:
+ size_al = (*ptr)->size;
+#if defined(POWERPC_DARWIN64)
+ next_arg = (unsigned long *)FFI_ALIGN((char *)next_arg, (*ptr)->alignment);
+ darwin64_pass_struct_by_value (*ptr, (char *) *p_argv,
+ (unsigned) size_al,
+ (unsigned int *) &fparg_count,
+ &fpr_base, &next_arg);
+#else
+ dest_cpy = (char *) next_arg;
+
+ /* If the first member of the struct is a double, then include enough
+ padding in the struct size to align it to double-word. */
+ if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE)
+ size_al = FFI_ALIGN((*ptr)->size, 8);
+
# if defined(POWERPC64)
- FFI_ASSERT (cif->abi != FFI_DARWIN);
- avalue[i] = pgr;
- pgr += (size_al + 7) / 8;
-# else
- /* Structures that match the basic modes (QI 1 byte, HI 2 bytes,
- SI 4 bytes) are aligned as if they were those modes. */
- if (size_al < 3 && cif->abi == FFI_DARWIN)
- avalue[i] = (char*) pgr + 4 - size_al;
- else
- avalue[i] = pgr;
- pgr += (size_al + 3) / 4;
-# endif
-#endif
- break;
-
- case FFI_TYPE_SINT64:
- case FFI_TYPE_UINT64:
-#if defined(POWERPC64)
- case FFI_TYPE_POINTER:
- avalue[i] = pgr;
- pgr++;
- break;
-#else
- /* Long long ints are passed in two gpr's. */
- avalue[i] = pgr;
- pgr += 2;
- break;
-#endif
-
- case FFI_TYPE_FLOAT:
- /* A float value consumes a GPR.
- There are 13 64bit floating point registers. */
- if (pfr < end_pfr)
- {
- double temp = pfr->d;
- pfr->f = (float) temp;
- avalue[i] = pfr;
- pfr++;
- }
- else
- {
- avalue[i] = pgr;
- }
- pgr++;
- break;
-
- case FFI_TYPE_DOUBLE:
- /* A double value consumes two GPRs.
- There are 13 64bit floating point registers. */
- if (pfr < end_pfr)
- {
- avalue[i] = pfr;
- pfr++;
- }
- else
- {
- avalue[i] = pgr;
- }
-#ifdef POWERPC64
- pgr++;
-#else
- pgr += 2;
-#endif
- break;
-
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
-
- case FFI_TYPE_LONGDOUBLE:
-#ifdef POWERPC64
- if (pfr + 1 < end_pfr)
- {
- avalue[i] = pfr;
- pfr += 2;
- }
- else
- {
- if (pfr < end_pfr)
- {
- *pgr = *(unsigned long *) pfr;
- pfr++;
- }
- avalue[i] = pgr;
- }
- pgr += 2;
-#else /* POWERPC64 */
- /* A long double value consumes four GPRs and two FPRs.
- There are 13 64bit floating point registers. */
- if (pfr + 1 < end_pfr)
- {
- avalue[i] = pfr;
- pfr += 2;
- }
- /* Here we have the situation where one part of the long double
- is stored in fpr13 and the other part is already on the stack.
- We use a union to pass the long double to avalue[i]. */
- else if (pfr + 1 == end_pfr)
- {
- union ldu temp_ld;
- memcpy (&temp_ld.lb[0], pfr, sizeof(ldbits));
- memcpy (&temp_ld.lb[1], pgr + 2, sizeof(ldbits));
- avalue[i] = &temp_ld.ld;
- pfr++;
- }
+ FFI_ASSERT (abi != FFI_DARWIN);
+ memcpy ((char *) dest_cpy, (char *) *p_argv, size_al);
+ next_arg += (size_al + 7) / 8;
+# else
+ /* Structures that match the basic modes (QI 1 byte, HI 2 bytes,
+ SI 4 bytes) are aligned as if they were those modes.
+ Structures with 3 byte in size are padded upwards. */
+ if (size_al < 3 && abi == FFI_DARWIN)
+ dest_cpy += 4 - size_al;
+
+ memcpy((char *) dest_cpy, (char *) *p_argv, size_al);
+ next_arg += (size_al + 3) / 4;
+# endif
+#endif
+ break;
+
+ case FFI_TYPE_INT:
+ case FFI_TYPE_SINT32:
+ gprvalue = *(signed int *) *p_argv;
+ goto putgpr;
+
+ case FFI_TYPE_UINT32:
+ gprvalue = *(unsigned int *) *p_argv;
+ putgpr:
+ *next_arg++ = gprvalue;
+ gp_count++;
+ break;
+ default:
+ break;
+ }
+ }
+
+ /* Check that we didn't overrun the stack... */
+ /* FFI_ASSERT(gpr_base <= stacktop - ASM_NEEDS_REGISTERS);
+ FFI_ASSERT((unsigned *)fpr_base
+ <= stacktop - ASM_NEEDS_REGISTERS - NUM_GPR_ARG_REGISTERS);
+ FFI_ASSERT(flags & FLAG_4_GPR_ARGUMENTS || intarg_count <= 4); */
+}
+
+#if defined(POWERPC_DARWIN64)
+
+/* See if we can put some of the struct into fprs.
+ This should not be called for structures of size 16 bytes, since these are not
+ broken out this way. */
+static void
+darwin64_scan_struct_for_floats (ffi_type *s, unsigned *nfpr)
+{
+ int i;
+
+ FFI_ASSERT (s->type == FFI_TYPE_STRUCT)
+
+ for (i = 0; s->elements[i] != NULL; i++)
+ {
+ ffi_type *p = s->elements[i];
+ switch (p->type)
+ {
+ case FFI_TYPE_STRUCT:
+ darwin64_scan_struct_for_floats (p, nfpr);
+ break;
+ case FFI_TYPE_LONGDOUBLE:
+ (*nfpr) += 2;
+ break;
+ case FFI_TYPE_DOUBLE:
+ case FFI_TYPE_FLOAT:
+ (*nfpr) += 1;
+ break;
+ default:
+ break;
+ }
+ }
+}
+
+static int
+darwin64_struct_size_exceeds_gprs_p (ffi_type *s, char *src, unsigned *nfpr)
+{
+ unsigned struct_offset=0, i;
+
+ for (i = 0; s->elements[i] != NULL; i++)
+ {
+ char *item_base;
+ ffi_type *p = s->elements[i];
+ /* Find the start of this item (0 for the first one). */
+ if (i > 0)
+ struct_offset = FFI_ALIGN(struct_offset, p->alignment);
+
+ item_base = src + struct_offset;
+
+ switch (p->type)
+ {
+ case FFI_TYPE_STRUCT:
+ if (darwin64_struct_size_exceeds_gprs_p (p, item_base, nfpr))
+ return 1;
+ break;
+ case FFI_TYPE_LONGDOUBLE:
+ if (*nfpr >= NUM_FPR_ARG_REGISTERS)
+ return 1;
+ (*nfpr) += 1;
+ item_base += 8;
+ /* FALL THROUGH */
+ case FFI_TYPE_DOUBLE:
+ if (*nfpr >= NUM_FPR_ARG_REGISTERS)
+ return 1;
+ (*nfpr) += 1;
+ break;
+ case FFI_TYPE_FLOAT:
+ if (*nfpr >= NUM_FPR_ARG_REGISTERS)
+ return 1;
+ (*nfpr) += 1;
+ break;
+ default:
+ /* If we try and place any item, that is non-float, once we've
+ exceeded the 8 GPR mark, then we can't fit the struct. */
+ if ((unsigned long)item_base >= 8*8)
+ return 1;
+ break;
+ }
+ /* now count the size of what we just used. */
+ struct_offset += p->size;
+ }
+ return 0;
+}
+
+/* Can this struct be returned by value? */
+int
+darwin64_struct_ret_by_value_p (ffi_type *s)
+{
+ unsigned nfp = 0;
+
+ FFI_ASSERT (s && s->type == FFI_TYPE_STRUCT);
+
+ /* The largest structure we can return is 8long + 13 doubles. */
+ if (s->size > 168)
+ return 0;
+
+ /* We can't pass more than 13 floats. */
+ darwin64_scan_struct_for_floats (s, &nfp);
+ if (nfp > 13)
+ return 0;
+
+ /* If there are not too many floats, and the struct is
+ small enough to accommodate in the GPRs, then it must be OK. */
+ if (s->size <= 64)
+ return 1;
+
+ /* Well, we have to look harder. */
+ nfp = 0;
+ if (darwin64_struct_size_exceeds_gprs_p (s, NULL, &nfp))
+ return 0;
+
+ return 1;
+}
+
+void
+darwin64_pass_struct_floats (ffi_type *s, char *src,
+ unsigned *nfpr, double **fprs)
+{
+ int i;
+ double *fpr_base = *fprs;
+ unsigned struct_offset = 0;
+
+ /* We don't assume anything about the alignment of the source. */
+ for (i = 0; s->elements[i] != NULL; i++)
+ {
+ char *item_base;
+ ffi_type *p = s->elements[i];
+ /* Find the start of this item (0 for the first one). */
+ if (i > 0)
+ struct_offset = FFI_ALIGN(struct_offset, p->alignment);
+ item_base = src + struct_offset;
+
+ switch (p->type)
+ {
+ case FFI_TYPE_STRUCT:
+ darwin64_pass_struct_floats (p, item_base, nfpr,
+ &fpr_base);
+ break;
+ case FFI_TYPE_LONGDOUBLE:
+ if (*nfpr < NUM_FPR_ARG_REGISTERS)
+ *fpr_base++ = *(double *)item_base;
+ (*nfpr) += 1;
+ item_base += 8;
+ /* FALL THROUGH */
+ case FFI_TYPE_DOUBLE:
+ if (*nfpr < NUM_FPR_ARG_REGISTERS)
+ *fpr_base++ = *(double *)item_base;
+ (*nfpr) += 1;
+ break;
+ case FFI_TYPE_FLOAT:
+ if (*nfpr < NUM_FPR_ARG_REGISTERS)
+ *fpr_base++ = (double) *(float *)item_base;
+ (*nfpr) += 1;
+ break;
+ default:
+ break;
+ }
+ /* now count the size of what we just used. */
+ struct_offset += p->size;
+ }
+ /* Update the scores. */
+ *fprs = fpr_base;
+}
+
+/* Darwin64 special rules.
+ Break out a struct into params and float registers. */
+static void
+darwin64_pass_struct_by_value (ffi_type *s, char *src, unsigned size,
+ unsigned *nfpr, double **fprs, unsigned long **arg)
+{
+ unsigned long *next_arg = *arg;
+ char *dest_cpy = (char *)next_arg;
+
+ FFI_ASSERT (s->type == FFI_TYPE_STRUCT)
+
+ if (!size)
+ return;
+
+ /* First... special cases. */
+ if (size < 3
+ || (size == 4
+ && s->elements[0]
+ && s->elements[0]->type != FFI_TYPE_FLOAT))
+ {
+ /* Must be at least one GPR, padding is unspecified in value,
+ let's make it zero. */
+ *next_arg = 0UL;
+ dest_cpy += 8 - size;
+ memcpy ((char *) dest_cpy, src, size);
+ next_arg++;
+ }
+ else if (size == 16)
+ {
+ memcpy ((char *) dest_cpy, src, size);
+ next_arg += 2;
+ }
+ else
+ {
+ /* now the general case, we consider embedded floats. */
+ memcpy ((char *) dest_cpy, src, size);
+ darwin64_pass_struct_floats (s, src, nfpr, fprs);
+ next_arg += (size+7)/8;
+ }
+
+ *arg = next_arg;
+}
+
+double *
+darwin64_struct_floats_to_mem (ffi_type *s, char *dest, double *fprs, unsigned *nf)
+{
+ int i;
+ unsigned struct_offset = 0;
+
+ /* We don't assume anything about the alignment of the source. */
+ for (i = 0; s->elements[i] != NULL; i++)
+ {
+ char *item_base;
+ ffi_type *p = s->elements[i];
+ /* Find the start of this item (0 for the first one). */
+ if (i > 0)
+ struct_offset = FFI_ALIGN(struct_offset, p->alignment);
+ item_base = dest + struct_offset;
+
+ switch (p->type)
+ {
+ case FFI_TYPE_STRUCT:
+ fprs = darwin64_struct_floats_to_mem (p, item_base, fprs, nf);
+ break;
+ case FFI_TYPE_LONGDOUBLE:
+ if (*nf < NUM_FPR_ARG_REGISTERS)
+ {
+ *(double *)item_base = *fprs++ ;
+ (*nf) += 1;
+ }
+ item_base += 8;
+ /* FALL THROUGH */
+ case FFI_TYPE_DOUBLE:
+ if (*nf < NUM_FPR_ARG_REGISTERS)
+ {
+ *(double *)item_base = *fprs++ ;
+ (*nf) += 1;
+ }
+ break;
+ case FFI_TYPE_FLOAT:
+ if (*nf < NUM_FPR_ARG_REGISTERS)
+ {
+ *(float *)item_base = (float) *fprs++ ;
+ (*nf) += 1;
+ }
+ break;
+ default:
+ break;
+ }
+ /* now count the size of what we just used. */
+ struct_offset += p->size;
+ }
+ return fprs;
+}
+
+#endif
+
+/* Adjust the size of S to be correct for Darwin.
+ On Darwin m32, the first field of a structure has natural alignment.
+ On Darwin m64, all fields have natural alignment. */
+
+static void
+darwin_adjust_aggregate_sizes (ffi_type *s)
+{
+ int i;
+
+ if (s->type != FFI_TYPE_STRUCT)
+ return;
+
+ s->size = 0;
+ for (i = 0; s->elements[i] != NULL; i++)
+ {
+ ffi_type *p;
+ int align;
+
+ p = s->elements[i];
+ if (p->type == FFI_TYPE_STRUCT)
+ darwin_adjust_aggregate_sizes (p);
+#if defined(POWERPC_DARWIN64)
+ /* Natural alignment for all items. */
+ align = p->alignment;
+#else
+ /* Natural alignment for the first item... */
+ if (i == 0)
+ align = p->alignment;
+ else if (p->alignment == 16 || p->alignment < 4)
+ /* .. subsequent items with vector or align < 4 have natural align. */
+ align = p->alignment;
+ else
+ /* .. or align is 4. */
+ align = 4;
+#endif
+ /* Pad, if necessary, before adding the current item. */
+ s->size = FFI_ALIGN(s->size, align) + p->size;
+ }
+
+ s->size = FFI_ALIGN(s->size, s->alignment);
+
+ /* This should not be necessary on m64, but harmless. */
+ if (s->elements[0]->type == FFI_TYPE_UINT64
+ || s->elements[0]->type == FFI_TYPE_SINT64
+ || s->elements[0]->type == FFI_TYPE_DOUBLE
+ || s->elements[0]->alignment == 8)
+ s->alignment = s->alignment > 8 ? s->alignment : 8;
+ /* Do not add additional tail padding. */
+}
+
+/* Adjust the size of S to be correct for AIX.
+ Word-align double unless it is the first member of a structure. */
+
+static void
+aix_adjust_aggregate_sizes (ffi_type *s)
+{
+ int i;
+
+ if (s->type != FFI_TYPE_STRUCT)
+ return;
+
+ s->size = 0;
+ for (i = 0; s->elements[i] != NULL; i++)
+ {
+ ffi_type *p;
+ int align;
+
+ p = s->elements[i];
+ aix_adjust_aggregate_sizes (p);
+ align = p->alignment;
+ if (i != 0 && p->type == FFI_TYPE_DOUBLE)
+ align = 4;
+ s->size = FFI_ALIGN(s->size, align) + p->size;
+ }
+
+ s->size = FFI_ALIGN(s->size, s->alignment);
+
+ if (s->elements[0]->type == FFI_TYPE_UINT64
+ || s->elements[0]->type == FFI_TYPE_SINT64
+ || s->elements[0]->type == FFI_TYPE_DOUBLE
+ || s->elements[0]->alignment == 8)
+ s->alignment = s->alignment > 8 ? s->alignment : 8;
+ /* Do not add additional tail padding. */
+}
+
+/* Perform machine dependent cif processing. */
+ffi_status
+ffi_prep_cif_machdep (ffi_cif *cif)
+{
+ /* All this is for the DARWIN ABI. */
+ unsigned i;
+ ffi_type **ptr;
+ unsigned bytes;
+ unsigned fparg_count = 0, intarg_count = 0;
+ unsigned flags = 0;
+ unsigned size_al = 0;
+
+ /* All the machine-independent calculation of cif->bytes will be wrong.
+ All the calculation of structure sizes will also be wrong.
+ Redo the calculation for DARWIN. */
+
+ if (cif->abi == FFI_DARWIN)
+ {
+ darwin_adjust_aggregate_sizes (cif->rtype);
+ for (i = 0; i < cif->nargs; i++)
+ darwin_adjust_aggregate_sizes (cif->arg_types[i]);
+ }
+
+ if (cif->abi == FFI_AIX)
+ {
+ aix_adjust_aggregate_sizes (cif->rtype);
+ for (i = 0; i < cif->nargs; i++)
+ aix_adjust_aggregate_sizes (cif->arg_types[i]);
+ }
+
+ /* Space for the frame pointer, callee's LR, CR, etc, and for
+ the asm's temp regs. */
+
+ bytes = (LINKAGE_AREA_GPRS + ASM_NEEDS_REGISTERS) * sizeof(unsigned long);
+
+ /* Return value handling.
+ The rules m32 are as follows:
+ - 32-bit (or less) integer values are returned in gpr3;
+ - structures of size <= 4 bytes also returned in gpr3;
+ - 64-bit integer values [??? and structures between 5 and 8 bytes] are
+ returned in gpr3 and gpr4;
+ - Single/double FP values are returned in fpr1;
+ - Long double FP (if not equivalent to double) values are returned in
+ fpr1 and fpr2;
+ m64:
+ - 64-bit or smaller integral values are returned in GPR3
+ - Single/double FP values are returned in fpr1;
+ - Long double FP values are returned in fpr1 and fpr2;
+ m64 Structures:
+ - If the structure could be accommodated in registers were it to be the
+ first argument to a routine, then it is returned in those registers.
+ m32/m64 structures otherwise:
+ - Larger structures values are allocated space and a pointer is passed
+ as the first argument. */
+ switch (cif->rtype->type)
+ {
+
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ flags |= FLAG_RETURNS_128BITS;
+ flags |= FLAG_RETURNS_FP;
+ break;
+#endif
+
+ case FFI_TYPE_DOUBLE:
+ flags |= FLAG_RETURNS_64BITS;
+ /* Fall through. */
+ case FFI_TYPE_FLOAT:
+ flags |= FLAG_RETURNS_FP;
+ break;
+
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+#ifdef POWERPC64
+ case FFI_TYPE_POINTER:
+#endif
+ flags |= FLAG_RETURNS_64BITS;
+ break;
+
+ case FFI_TYPE_STRUCT:
+#if defined(POWERPC_DARWIN64)
+ {
+ /* Can we fit the struct into regs? */
+ if (darwin64_struct_ret_by_value_p (cif->rtype))
+ {
+ unsigned nfpr = 0;
+ flags |= FLAG_RETURNS_STRUCT;
+ if (cif->rtype->size != 16)
+ darwin64_scan_struct_for_floats (cif->rtype, &nfpr) ;
+ else
+ flags |= FLAG_RETURNS_128BITS;
+ /* Will be 0 for 16byte struct. */
+ if (nfpr)
+ flags |= FLAG_RETURNS_FP;
+ }
+ else /* By ref. */
+ {
+ flags |= FLAG_RETVAL_REFERENCE;
+ flags |= FLAG_RETURNS_NOTHING;
+ intarg_count++;
+ }
+ }
+#elif defined(DARWIN_PPC)
+ if (cif->rtype->size <= 4)
+ flags |= FLAG_RETURNS_STRUCT;
+ else /* else by reference. */
+ {
+ flags |= FLAG_RETVAL_REFERENCE;
+ flags |= FLAG_RETURNS_NOTHING;
+ intarg_count++;
+ }
+#else /* assume we pass by ref. */
+ flags |= FLAG_RETVAL_REFERENCE;
+ flags |= FLAG_RETURNS_NOTHING;
+ intarg_count++;
+#endif
+ break;
+ case FFI_TYPE_VOID:
+ flags |= FLAG_RETURNS_NOTHING;
+ break;
+
+ default:
+ /* Returns 32-bit integer, or similar. Nothing to do here. */
+ break;
+ }
+
+ /* The first NUM_GPR_ARG_REGISTERS words of integer arguments, and the
+ first NUM_FPR_ARG_REGISTERS fp arguments, go in registers; the rest
+ goes on the stack.
+ ??? Structures are passed as a pointer to a copy of the structure.
+ Stuff on the stack needs to keep proper alignment.
+ For m64 the count is effectively of half-GPRs. */
+ for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++)
+ {
+ unsigned align_words;
+ switch ((*ptr)->type)
+ {
+ case FFI_TYPE_FLOAT:
+ case FFI_TYPE_DOUBLE:
+ fparg_count++;
+#if !defined(POWERPC_DARWIN64)
+ /* If this FP arg is going on the stack, it must be
+ 8-byte-aligned. */
+ if (fparg_count > NUM_FPR_ARG_REGISTERS
+ && (intarg_count & 0x01) != 0)
+ intarg_count++;
+#endif
+ break;
+
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ fparg_count += 2;
+ /* If this FP arg is going on the stack, it must be
+ 16-byte-aligned. */
+ if (fparg_count >= NUM_FPR_ARG_REGISTERS)
+#if defined (POWERPC64)
+ intarg_count = FFI_ALIGN(intarg_count, 2);
+#else
+ intarg_count = FFI_ALIGN(intarg_count, 4);
+#endif
+ break;
+#endif
+
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+#if defined(POWERPC64)
+ intarg_count++;
+#else
+ /* 'long long' arguments are passed as two words, but
+ either both words must fit in registers or both go
+ on the stack. If they go on the stack, they must
+ be 8-byte-aligned. */
+ if (intarg_count == NUM_GPR_ARG_REGISTERS-1
+ || (intarg_count >= NUM_GPR_ARG_REGISTERS
+ && (intarg_count & 0x01) != 0))
+ intarg_count++;
+ intarg_count += 2;
+#endif
+ break;
+
+ case FFI_TYPE_STRUCT:
+ size_al = (*ptr)->size;
+#if defined(POWERPC_DARWIN64)
+ align_words = (*ptr)->alignment >> 3;
+ if (align_words)
+ intarg_count = FFI_ALIGN(intarg_count, align_words);
+ /* Base size of the struct. */
+ intarg_count += (size_al + 7) / 8;
+ /* If 16 bytes then don't worry about floats. */
+ if (size_al != 16)
+ /* Scan through for floats to be placed in regs. */
+ darwin64_scan_struct_for_floats (*ptr, &fparg_count) ;
+#else
+ align_words = (*ptr)->alignment >> 2;
+ if (align_words)
+ intarg_count = FFI_ALIGN(intarg_count, align_words);
+ /* If the first member of the struct is a double, then align
+ the struct to double-word.
+ if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE)
+ size_al = FFI_ALIGN((*ptr)->size, 8); */
+# ifdef POWERPC64
+ intarg_count += (size_al + 7) / 8;
+# else
+ intarg_count += (size_al + 3) / 4;
+# endif
+#endif
+ break;
+
+ default:
+ /* Everything else is passed as a 4-byte word in a GPR, either
+ the object itself or a pointer to it. */
+ intarg_count++;
+ break;
+ }
+ }
+
+ if (fparg_count != 0)
+ flags |= FLAG_FP_ARGUMENTS;
+
+#if defined(POWERPC_DARWIN64)
+ /* Space to image the FPR registers, if needed - which includes when they might be
+ used in a struct return. */
+ if (fparg_count != 0
+ || ((flags & FLAG_RETURNS_STRUCT)
+ && (flags & FLAG_RETURNS_FP)))
+ bytes += NUM_FPR_ARG_REGISTERS * sizeof(double);
+#else
+ /* Space for the FPR registers, if needed. */
+ if (fparg_count != 0)
+ bytes += NUM_FPR_ARG_REGISTERS * sizeof(double);
+#endif
+
+ /* Stack space. */
+#ifdef POWERPC64
+ if ((intarg_count + fparg_count) > NUM_GPR_ARG_REGISTERS)
+ bytes += (intarg_count + fparg_count) * sizeof(long);
+#else
+ if ((intarg_count + 2 * fparg_count) > NUM_GPR_ARG_REGISTERS)
+ bytes += (intarg_count + 2 * fparg_count) * sizeof(long);
+#endif
+ else
+ bytes += NUM_GPR_ARG_REGISTERS * sizeof(long);
+
+ /* The stack space allocated needs to be a multiple of 16 bytes. */
+ bytes = FFI_ALIGN(bytes, 16) ;
+
+ cif->flags = flags;
+ cif->bytes = bytes;
+
+ return FFI_OK;
+}
+
+extern void ffi_call_AIX(extended_cif *, long, unsigned, unsigned *,
+ void (*fn)(void), void (*fn2)(void));
+
+extern void ffi_call_go_AIX(extended_cif *, long, unsigned, unsigned *,
+ void (*fn)(void), void (*fn2)(void), void *closure);
+
+extern void ffi_call_DARWIN(extended_cif *, long, unsigned, unsigned *,
+ void (*fn)(void), void (*fn2)(void), ffi_type*);
+
+void
+ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
+{
+ extended_cif ecif;
+
+ ecif.cif = cif;
+ ecif.avalue = avalue;
+
+ /* If the return value is a struct and we don't have a return
+ value address then we need to make one. */
+
+ if ((rvalue == NULL) &&
+ (cif->rtype->type == FFI_TYPE_STRUCT))
+ {
+ ecif.rvalue = alloca (cif->rtype->size);
+ }
+ else
+ ecif.rvalue = rvalue;
+
+ switch (cif->abi)
+ {
+ case FFI_AIX:
+ ffi_call_AIX(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn,
+ FFI_FN(ffi_prep_args));
+ break;
+ case FFI_DARWIN:
+ ffi_call_DARWIN(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn,
+ FFI_FN(ffi_prep_args), cif->rtype);
+ break;
+ default:
+ FFI_ASSERT(0);
+ break;
+ }
+}
+
+void
+ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue,
+ void *closure)
+{
+ extended_cif ecif;
+
+ ecif.cif = cif;
+ ecif.avalue = avalue;
+
+ /* If the return value is a struct and we don't have a return
+ value address then we need to make one. */
+
+ if ((rvalue == NULL) &&
+ (cif->rtype->type == FFI_TYPE_STRUCT))
+ {
+ ecif.rvalue = alloca (cif->rtype->size);
+ }
+ else
+ ecif.rvalue = rvalue;
+
+ switch (cif->abi)
+ {
+ case FFI_AIX:
+ ffi_call_go_AIX(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn,
+ FFI_FN(ffi_prep_args), closure);
+ break;
+ default:
+ FFI_ASSERT(0);
+ break;
+ }
+}
+
+static void flush_icache(char *);
+static void flush_range(char *, int);
+
+/* The layout of a function descriptor. A C function pointer really
+ points to one of these. */
+
+typedef struct aix_fd_struct {
+ void *code_pointer;
+ void *toc;
+} aix_fd;
+
+/* here I'd like to add the stack frame layout we use in darwin_closure.S
+ and aix_closure.S
+
+ m32/m64
+
+ The stack layout looks like this:
+
+ | Additional params... | | Higher address
+ ~ ~ ~
+ | Parameters (at least 8*4/8=32/64) | | NUM_GPR_ARG_REGISTERS
+ |--------------------------------------------| |
+ | TOC=R2 (AIX) Reserved (Darwin) 4/8 | |
+ |--------------------------------------------| |
+ | Reserved 2*4/8 | |
+ |--------------------------------------------| |
+ | Space for callee's LR 4/8 | |
+ |--------------------------------------------| |
+ | Saved CR [low word for m64] 4/8 | |
+ |--------------------------------------------| |
+ | Current backchain pointer 4/8 |-/ Parent's frame.
+ |--------------------------------------------| <+ <<< on entry to ffi_closure_ASM
+ | Result Bytes 16 | |
+ |--------------------------------------------| |
+ ~ padding to 16-byte alignment ~ ~
+ |--------------------------------------------| |
+ | NUM_FPR_ARG_REGISTERS slots | |
+ | here fp13 .. fp1 13*8 | |
+ |--------------------------------------------| |
+ | R3..R10 8*4/8=32/64 | | NUM_GPR_ARG_REGISTERS
+ |--------------------------------------------| |
+ | TOC=R2 (AIX) Reserved (Darwin) 4/8 | |
+ |--------------------------------------------| | stack |
+ | Reserved [compiler,binder] 2*4/8 | | grows |
+ |--------------------------------------------| | down V
+ | Space for callee's LR 4/8 | |
+ |--------------------------------------------| | lower addresses
+ | Saved CR [low word for m64] 4/8 | |
+ |--------------------------------------------| | stack pointer here
+ | Current backchain pointer 4/8 |-/ during
+ |--------------------------------------------| <<< ffi_closure_ASM.
+
+*/
+
+ffi_status
+ffi_prep_closure_loc (ffi_closure* closure,
+ ffi_cif* cif,
+ void (*fun)(ffi_cif*, void*, void**, void*),
+ void *user_data,
+ void *codeloc)
+{
+ unsigned int *tramp;
+ struct ffi_aix_trampoline_struct *tramp_aix;
+ aix_fd *fd;
+
+ switch (cif->abi)
+ {
+ case FFI_DARWIN:
+
+ FFI_ASSERT (cif->abi == FFI_DARWIN);
+
+ tramp = (unsigned int *) &closure->tramp[0];
+#if defined(POWERPC_DARWIN64)
+ tramp[0] = 0x7c0802a6; /* mflr r0 */
+ tramp[1] = 0x429f0015; /* bcl- 20,4*cr7+so, +0x18 (L1) */
+ /* We put the addresses here. */
+ tramp[6] = 0x7d6802a6; /*L1: mflr r11 */
+ tramp[7] = 0xe98b0000; /* ld r12,0(r11) function address */
+ tramp[8] = 0x7c0803a6; /* mtlr r0 */
+ tramp[9] = 0x7d8903a6; /* mtctr r12 */
+ tramp[10] = 0xe96b0008; /* lwz r11,8(r11) static chain */
+ tramp[11] = 0x4e800420; /* bctr */
+
+ *((unsigned long *)&tramp[2]) = (unsigned long) ffi_closure_ASM; /* function */
+ *((unsigned long *)&tramp[4]) = (unsigned long) codeloc; /* context */
+#else
+ tramp[0] = 0x7c0802a6; /* mflr r0 */
+ tramp[1] = 0x429f000d; /* bcl- 20,4*cr7+so,0x10 */
+ tramp[4] = 0x7d6802a6; /* mflr r11 */
+ tramp[5] = 0x818b0000; /* lwz r12,0(r11) function address */
+ tramp[6] = 0x7c0803a6; /* mtlr r0 */
+ tramp[7] = 0x7d8903a6; /* mtctr r12 */
+ tramp[8] = 0x816b0004; /* lwz r11,4(r11) static chain */
+ tramp[9] = 0x4e800420; /* bctr */
+ tramp[2] = (unsigned long) ffi_closure_ASM; /* function */
+ tramp[3] = (unsigned long) codeloc; /* context */
+#endif
+ closure->cif = cif;
+ closure->fun = fun;
+ closure->user_data = user_data;
+
+ /* Flush the icache. Only necessary on Darwin. */
+ flush_range(codeloc, FFI_TRAMPOLINE_SIZE);
+
+ break;
+
+ case FFI_AIX:
+
+ tramp_aix = (struct ffi_aix_trampoline_struct *) (closure->tramp);
+ fd = (aix_fd *)(void *)ffi_closure_ASM;
+
+ FFI_ASSERT (cif->abi == FFI_AIX);
+
+ tramp_aix->code_pointer = fd->code_pointer;
+ tramp_aix->toc = fd->toc;
+ tramp_aix->static_chain = codeloc;
+ closure->cif = cif;
+ closure->fun = fun;
+ closure->user_data = user_data;
+ break;
+
+ default:
+ return FFI_BAD_ABI;
+ break;
+ }
+ return FFI_OK;
+}
+
+ffi_status
+ffi_prep_go_closure (ffi_go_closure* closure,
+ ffi_cif* cif,
+ void (*fun)(ffi_cif*, void*, void**, void*))
+{
+ switch (cif->abi)
+ {
+ case FFI_AIX:
+
+ FFI_ASSERT (cif->abi == FFI_AIX);
+
+ closure->tramp = (void *)ffi_go_closure_ASM;
+ closure->cif = cif;
+ closure->fun = fun;
+ return FFI_OK;
+
+ // For now, ffi_prep_go_closure is only implemented for AIX, not for Darwin
+ default:
+ return FFI_BAD_ABI;
+ break;
+ }
+ return FFI_OK;
+}
+
+static void
+flush_icache(char *addr)
+{
+#ifndef _AIX
+ __asm__ volatile (
+ "dcbf 0,%0\n"
+ "\tsync\n"
+ "\ticbi 0,%0\n"
+ "\tsync\n"
+ "\tisync"
+ : : "r"(addr) : "memory");
+#endif
+}
+
+static void
+flush_range(char * addr1, int size)
+{
+#define MIN_LINE_SIZE 32
+ int i;
+ for (i = 0; i < size; i += MIN_LINE_SIZE)
+ flush_icache(addr1+i);
+ flush_icache(addr1+size-1);
+}
+
+typedef union
+{
+ float f;
+ double d;
+} ffi_dblfl;
+
+ffi_type *
+ffi_closure_helper_DARWIN (ffi_closure *, void *,
+ unsigned long *, ffi_dblfl *);
+
+ffi_type *
+ffi_go_closure_helper_DARWIN (ffi_go_closure*, void *,
+ unsigned long *, ffi_dblfl *);
+
+/* Basically the trampoline invokes ffi_closure_ASM, and on
+ entry, r11 holds the address of the closure.
+ After storing the registers that could possibly contain
+ parameters to be passed into the stack frame and setting
+ up space for a return value, ffi_closure_ASM invokes the
+ following helper function to do most of the work. */
+
+static ffi_type *
+ffi_closure_helper_common (ffi_cif* cif,
+ void (*fun)(ffi_cif*, void*, void**, void*),
+ void *user_data, void *rvalue,
+ unsigned long *pgr, ffi_dblfl *pfr)
+{
+ /* rvalue is the pointer to space for return value in closure assembly
+ pgr is the pointer to where r3-r10 are stored in ffi_closure_ASM
+ pfr is the pointer to where f1-f13 are stored in ffi_closure_ASM. */
+
+ typedef double ldbits[2];
+
+ union ldu
+ {
+ ldbits lb;
+ long double ld;
+ };
+
+ void ** avalue;
+ ffi_type ** arg_types;
+ long i, avn;
+ ffi_dblfl * end_pfr = pfr + NUM_FPR_ARG_REGISTERS;
+ unsigned size_al;
+#if defined(POWERPC_DARWIN64)
+ unsigned fpsused = 0;
+#endif
+
+ avalue = alloca (cif->nargs * sizeof(void *));
+
+ if (cif->rtype->type == FFI_TYPE_STRUCT)
+ {
+#if defined(POWERPC_DARWIN64)
+ if (!darwin64_struct_ret_by_value_p (cif->rtype))
+ {
+ /* Won't fit into the regs - return by ref. */
+ rvalue = (void *) *pgr;
+ pgr++;
+ }
+#elif defined(DARWIN_PPC)
+ if (cif->rtype->size > 4)
+ {
+ rvalue = (void *) *pgr;
+ pgr++;
+ }
+#else /* assume we return by ref. */
+ rvalue = (void *) *pgr;
+ pgr++;
+#endif
+ }
+
+ i = 0;
+ avn = cif->nargs;
+ arg_types = cif->arg_types;
+
+ /* Grab the addresses of the arguments from the stack frame. */
+ while (i < avn)
+ {
+ switch (arg_types[i]->type)
+ {
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT8:
+#if defined(POWERPC64)
+ avalue[i] = (char *) pgr + 7;
+#else
+ avalue[i] = (char *) pgr + 3;
+#endif
+ pgr++;
+ break;
+
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT16:
+#if defined(POWERPC64)
+ avalue[i] = (char *) pgr + 6;
+#else
+ avalue[i] = (char *) pgr + 2;
+#endif
+ pgr++;
+ break;
+
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT32:
+#if defined(POWERPC64)
+ avalue[i] = (char *) pgr + 4;
+#else
+ case FFI_TYPE_POINTER:
+ avalue[i] = pgr;
+#endif
+ pgr++;
+ break;
+
+ case FFI_TYPE_STRUCT:
+ size_al = arg_types[i]->size;
+#if defined(POWERPC_DARWIN64)
+ pgr = (unsigned long *)FFI_ALIGN((char *)pgr, arg_types[i]->alignment);
+ if (size_al < 3 || size_al == 4)
+ {
+ avalue[i] = ((char *)pgr)+8-size_al;
+ if (arg_types[i]->elements[0]->type == FFI_TYPE_FLOAT
+ && fpsused < NUM_FPR_ARG_REGISTERS)
+ {
+ *(float *)pgr = (float) *(double *)pfr;
+ pfr++;
+ fpsused++;
+ }
+ }
else
- {
- avalue[i] = pgr;
- }
- pgr += 4;
-#endif /* POWERPC64 */
- break;
-#endif
- default:
- FFI_ASSERT(0);
- }
- i++;
- }
-
- (fun) (cif, rvalue, avalue, user_data);
-
- /* Tell ffi_closure_ASM to perform return type promotions. */
- return cif->rtype;
-}
-
-ffi_type *
-ffi_closure_helper_DARWIN (ffi_closure *closure, void *rvalue,
- unsigned long *pgr, ffi_dblfl *pfr)
-{
- return ffi_closure_helper_common (closure->cif, closure->fun,
- closure->user_data, rvalue, pgr, pfr);
-}
-
-ffi_type *
-ffi_go_closure_helper_DARWIN (ffi_go_closure *closure, void *rvalue,
- unsigned long *pgr, ffi_dblfl *pfr)
-{
- return ffi_closure_helper_common (closure->cif, closure->fun,
- closure, rvalue, pgr, pfr);
-}
-
+ {
+ if (size_al != 16)
+ pfr = (ffi_dblfl *)
+ darwin64_struct_floats_to_mem (arg_types[i], (char *)pgr,
+ (double *)pfr, &fpsused);
+ avalue[i] = pgr;
+ }
+ pgr += (size_al + 7) / 8;
+#else
+ /* If the first member of the struct is a double, then align
+ the struct to double-word. */
+ if (arg_types[i]->elements[0]->type == FFI_TYPE_DOUBLE)
+ size_al = FFI_ALIGN(arg_types[i]->size, 8);
+# if defined(POWERPC64)
+ FFI_ASSERT (cif->abi != FFI_DARWIN);
+ avalue[i] = pgr;
+ pgr += (size_al + 7) / 8;
+# else
+ /* Structures that match the basic modes (QI 1 byte, HI 2 bytes,
+ SI 4 bytes) are aligned as if they were those modes. */
+ if (size_al < 3 && cif->abi == FFI_DARWIN)
+ avalue[i] = (char*) pgr + 4 - size_al;
+ else
+ avalue[i] = pgr;
+ pgr += (size_al + 3) / 4;
+# endif
+#endif
+ break;
+
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_UINT64:
+#if defined(POWERPC64)
+ case FFI_TYPE_POINTER:
+ avalue[i] = pgr;
+ pgr++;
+ break;
+#else
+ /* Long long ints are passed in two gpr's. */
+ avalue[i] = pgr;
+ pgr += 2;
+ break;
+#endif
+
+ case FFI_TYPE_FLOAT:
+ /* A float value consumes a GPR.
+ There are 13 64bit floating point registers. */
+ if (pfr < end_pfr)
+ {
+ double temp = pfr->d;
+ pfr->f = (float) temp;
+ avalue[i] = pfr;
+ pfr++;
+ }
+ else
+ {
+ avalue[i] = pgr;
+ }
+ pgr++;
+ break;
+
+ case FFI_TYPE_DOUBLE:
+ /* A double value consumes two GPRs.
+ There are 13 64bit floating point registers. */
+ if (pfr < end_pfr)
+ {
+ avalue[i] = pfr;
+ pfr++;
+ }
+ else
+ {
+ avalue[i] = pgr;
+ }
+#ifdef POWERPC64
+ pgr++;
+#else
+ pgr += 2;
+#endif
+ break;
+
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+
+ case FFI_TYPE_LONGDOUBLE:
+#ifdef POWERPC64
+ if (pfr + 1 < end_pfr)
+ {
+ avalue[i] = pfr;
+ pfr += 2;
+ }
+ else
+ {
+ if (pfr < end_pfr)
+ {
+ *pgr = *(unsigned long *) pfr;
+ pfr++;
+ }
+ avalue[i] = pgr;
+ }
+ pgr += 2;
+#else /* POWERPC64 */
+ /* A long double value consumes four GPRs and two FPRs.
+ There are 13 64bit floating point registers. */
+ if (pfr + 1 < end_pfr)
+ {
+ avalue[i] = pfr;
+ pfr += 2;
+ }
+ /* Here we have the situation where one part of the long double
+ is stored in fpr13 and the other part is already on the stack.
+ We use a union to pass the long double to avalue[i]. */
+ else if (pfr + 1 == end_pfr)
+ {
+ union ldu temp_ld;
+ memcpy (&temp_ld.lb[0], pfr, sizeof(ldbits));
+ memcpy (&temp_ld.lb[1], pgr + 2, sizeof(ldbits));
+ avalue[i] = &temp_ld.ld;
+ pfr++;
+ }
+ else
+ {
+ avalue[i] = pgr;
+ }
+ pgr += 4;
+#endif /* POWERPC64 */
+ break;
+#endif
+ default:
+ FFI_ASSERT(0);
+ }
+ i++;
+ }
+
+ (fun) (cif, rvalue, avalue, user_data);
+
+ /* Tell ffi_closure_ASM to perform return type promotions. */
+ return cif->rtype;
+}
+
+ffi_type *
+ffi_closure_helper_DARWIN (ffi_closure *closure, void *rvalue,
+ unsigned long *pgr, ffi_dblfl *pfr)
+{
+ return ffi_closure_helper_common (closure->cif, closure->fun,
+ closure->user_data, rvalue, pgr, pfr);
+}
+
+ffi_type *
+ffi_go_closure_helper_DARWIN (ffi_go_closure *closure, void *rvalue,
+ unsigned long *pgr, ffi_dblfl *pfr)
+{
+ return ffi_closure_helper_common (closure->cif, closure->fun,
+ closure, rvalue, pgr, pfr);
+}
+
diff --git a/contrib/restricted/libffi/src/powerpc/ffi_linux64.c b/contrib/restricted/libffi/src/powerpc/ffi_linux64.c
index f4c5014a86..de0d033769 100644
--- a/contrib/restricted/libffi/src/powerpc/ffi_linux64.c
+++ b/contrib/restricted/libffi/src/powerpc/ffi_linux64.c
@@ -1,1153 +1,1153 @@
-/* -----------------------------------------------------------------------
- ffi_linux64.c - Copyright (C) 2013 IBM
- Copyright (C) 2011 Anthony Green
- Copyright (C) 2011 Kyle Moffett
- Copyright (C) 2008 Red Hat, Inc
- Copyright (C) 2007, 2008 Free Software Foundation, Inc
- Copyright (c) 1998 Geoffrey Keating
-
- PowerPC Foreign Function Interface
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#include "ffi.h"
-
-#ifdef POWERPC64
-#include "ffi_common.h"
-#include "ffi_powerpc.h"
-
-
-/* About the LINUX64 ABI. */
-enum {
- NUM_GPR_ARG_REGISTERS64 = 8,
- NUM_FPR_ARG_REGISTERS64 = 13,
- NUM_VEC_ARG_REGISTERS64 = 12,
-};
-enum { ASM_NEEDS_REGISTERS64 = 4 };
-
-
-#if HAVE_LONG_DOUBLE_VARIANT && FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
-/* Adjust size of ffi_type_longdouble. */
-void FFI_HIDDEN
-ffi_prep_types_linux64 (ffi_abi abi)
-{
- if ((abi & (FFI_LINUX | FFI_LINUX_LONG_DOUBLE_128)) == FFI_LINUX)
- {
- ffi_type_longdouble.size = 8;
- ffi_type_longdouble.alignment = 8;
- }
- else
- {
- ffi_type_longdouble.size = 16;
- ffi_type_longdouble.alignment = 16;
- }
-}
-#endif
-
-
-static unsigned int
-discover_homogeneous_aggregate (ffi_abi abi,
- const ffi_type *t,
- unsigned int *elnum)
-{
- switch (t->type)
- {
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- /* 64-bit long doubles are equivalent to doubles. */
- if ((abi & FFI_LINUX_LONG_DOUBLE_128) == 0)
- {
- *elnum = 1;
- return FFI_TYPE_DOUBLE;
- }
- /* IBM extended precision values use unaligned pairs
- of FPRs, but according to the ABI must be considered
- distinct from doubles. They are also limited to a
- maximum of four members in a homogeneous aggregate. */
- else if ((abi & FFI_LINUX_LONG_DOUBLE_IEEE128) == 0)
- {
- *elnum = 2;
- return FFI_TYPE_LONGDOUBLE;
- }
- /* Fall through. */
-#endif
- case FFI_TYPE_FLOAT:
- case FFI_TYPE_DOUBLE:
- *elnum = 1;
- return (int) t->type;
-
- case FFI_TYPE_STRUCT:;
- {
- unsigned int base_elt = 0, total_elnum = 0;
- ffi_type **el = t->elements;
- while (*el)
- {
- unsigned int el_elt, el_elnum = 0;
- el_elt = discover_homogeneous_aggregate (abi, *el, &el_elnum);
- if (el_elt == 0
- || (base_elt && base_elt != el_elt))
- return 0;
- base_elt = el_elt;
- total_elnum += el_elnum;
-#if _CALL_ELF == 2
- if (total_elnum > 8)
- return 0;
-#else
- if (total_elnum > 1)
- return 0;
-#endif
- el++;
- }
- *elnum = total_elnum;
- return base_elt;
- }
-
- default:
- return 0;
- }
-}
-
-
-/* Perform machine dependent cif processing */
-static ffi_status
-ffi_prep_cif_linux64_core (ffi_cif *cif)
-{
- ffi_type **ptr;
- unsigned bytes;
- unsigned i, fparg_count = 0, intarg_count = 0, vecarg_count = 0;
- unsigned flags = cif->flags;
- unsigned elt, elnum, rtype;
-
-#if FFI_TYPE_LONGDOUBLE == FFI_TYPE_DOUBLE
- /* If compiled without long double support... */
- if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0 ||
- (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
- return FFI_BAD_ABI;
-#elif !defined(__VEC__)
- /* If compiled without vector register support (used by assembly)... */
- if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
- return FFI_BAD_ABI;
-#else
- /* If the IEEE128 flag is set, but long double is only 64 bits wide... */
- if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) == 0 &&
- (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
- return FFI_BAD_ABI;
-#endif
-
- /* The machine-independent calculation of cif->bytes doesn't work
- for us. Redo the calculation. */
-#if _CALL_ELF == 2
- /* Space for backchain, CR, LR, TOC and the asm's temp regs. */
- bytes = (4 + ASM_NEEDS_REGISTERS64) * sizeof (long);
-
- /* Space for the general registers. */
- bytes += NUM_GPR_ARG_REGISTERS64 * sizeof (long);
-#else
- /* Space for backchain, CR, LR, cc/ld doubleword, TOC and the asm's temp
- regs. */
- bytes = (6 + ASM_NEEDS_REGISTERS64) * sizeof (long);
-
- /* Space for the mandatory parm save area and general registers. */
- bytes += 2 * NUM_GPR_ARG_REGISTERS64 * sizeof (long);
-#endif
-
- /* Return value handling. */
- rtype = cif->rtype->type;
-#if _CALL_ELF == 2
-homogeneous:
-#endif
- switch (rtype)
- {
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
- {
- flags |= FLAG_RETURNS_VEC;
- break;
- }
- if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0)
- flags |= FLAG_RETURNS_128BITS;
- /* Fall through. */
-#endif
- case FFI_TYPE_DOUBLE:
- flags |= FLAG_RETURNS_64BITS;
- /* Fall through. */
- case FFI_TYPE_FLOAT:
- flags |= FLAG_RETURNS_FP;
- break;
-
- case FFI_TYPE_UINT128:
- flags |= FLAG_RETURNS_128BITS;
- /* Fall through. */
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- case FFI_TYPE_POINTER:
- flags |= FLAG_RETURNS_64BITS;
- break;
-
- case FFI_TYPE_STRUCT:
-#if _CALL_ELF == 2
- elt = discover_homogeneous_aggregate (cif->abi, cif->rtype, &elnum);
- if (elt)
- {
- flags |= FLAG_RETURNS_SMST;
- rtype = elt;
- goto homogeneous;
- }
- if (cif->rtype->size <= 16)
- {
- flags |= FLAG_RETURNS_SMST;
- break;
- }
-#endif
- intarg_count++;
- flags |= FLAG_RETVAL_REFERENCE;
- /* Fall through. */
- case FFI_TYPE_VOID:
- flags |= FLAG_RETURNS_NOTHING;
- break;
-
- default:
- /* Returns 32-bit integer, or similar. Nothing to do here. */
- break;
- }
-
- for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++)
- {
- unsigned int align;
-
- switch ((*ptr)->type)
- {
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
- {
- vecarg_count++;
- /* Align to 16 bytes, plus the 16-byte argument. */
- intarg_count = (intarg_count + 3) & ~0x1;
- if (vecarg_count > NUM_VEC_ARG_REGISTERS64)
- flags |= FLAG_ARG_NEEDS_PSAVE;
- break;
- }
- if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0)
- {
- fparg_count++;
- intarg_count++;
- }
- /* Fall through. */
-#endif
- case FFI_TYPE_DOUBLE:
- case FFI_TYPE_FLOAT:
- fparg_count++;
- intarg_count++;
- if (fparg_count > NUM_FPR_ARG_REGISTERS64)
- flags |= FLAG_ARG_NEEDS_PSAVE;
- break;
-
- case FFI_TYPE_STRUCT:
- if ((cif->abi & FFI_LINUX_STRUCT_ALIGN) != 0)
- {
- align = (*ptr)->alignment;
- if (align > 16)
- align = 16;
- align = align / 8;
- if (align > 1)
- intarg_count = FFI_ALIGN (intarg_count, align);
- }
- intarg_count += ((*ptr)->size + 7) / 8;
- elt = discover_homogeneous_aggregate (cif->abi, *ptr, &elnum);
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- if (elt == FFI_TYPE_LONGDOUBLE &&
- (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
- {
- vecarg_count += elnum;
- if (vecarg_count > NUM_VEC_ARG_REGISTERS64)
- flags |= FLAG_ARG_NEEDS_PSAVE;
- break;
- }
- else
-#endif
- if (elt)
- {
- fparg_count += elnum;
- if (fparg_count > NUM_FPR_ARG_REGISTERS64)
- flags |= FLAG_ARG_NEEDS_PSAVE;
- }
- else
- {
- if (intarg_count > NUM_GPR_ARG_REGISTERS64)
- flags |= FLAG_ARG_NEEDS_PSAVE;
- }
- break;
-
- case FFI_TYPE_POINTER:
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- case FFI_TYPE_INT:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT16:
- case FFI_TYPE_SINT16:
- case FFI_TYPE_UINT8:
- case FFI_TYPE_SINT8:
- /* Everything else is passed as a 8-byte word in a GPR, either
- the object itself or a pointer to it. */
- intarg_count++;
- if (intarg_count > NUM_GPR_ARG_REGISTERS64)
- flags |= FLAG_ARG_NEEDS_PSAVE;
- break;
- default:
- FFI_ASSERT (0);
- }
- }
-
- if (fparg_count != 0)
- flags |= FLAG_FP_ARGUMENTS;
- if (intarg_count > 4)
- flags |= FLAG_4_GPR_ARGUMENTS;
- if (vecarg_count != 0)
- flags |= FLAG_VEC_ARGUMENTS;
-
- /* Space for the FPR registers, if needed. */
- if (fparg_count != 0)
- bytes += NUM_FPR_ARG_REGISTERS64 * sizeof (double);
- /* Space for the vector registers, if needed, aligned to 16 bytes. */
- if (vecarg_count != 0) {
- bytes = (bytes + 15) & ~0xF;
- bytes += NUM_VEC_ARG_REGISTERS64 * sizeof (float128);
- }
-
- /* Stack space. */
-#if _CALL_ELF == 2
- if ((flags & FLAG_ARG_NEEDS_PSAVE) != 0)
- bytes += intarg_count * sizeof (long);
-#else
- if (intarg_count > NUM_GPR_ARG_REGISTERS64)
- bytes += (intarg_count - NUM_GPR_ARG_REGISTERS64) * sizeof (long);
-#endif
-
- /* The stack space allocated needs to be a multiple of 16 bytes. */
- bytes = (bytes + 15) & ~0xF;
-
- cif->flags = flags;
- cif->bytes = bytes;
-
- return FFI_OK;
-}
-
-ffi_status FFI_HIDDEN
-ffi_prep_cif_linux64 (ffi_cif *cif)
-{
- if ((cif->abi & FFI_LINUX) != 0)
- cif->nfixedargs = cif->nargs;
-#if _CALL_ELF != 2
- else if (cif->abi == FFI_COMPAT_LINUX64)
- {
- /* This call is from old code. Don't touch cif->nfixedargs
- since old code will be using a smaller cif. */
- cif->flags |= FLAG_COMPAT;
- /* Translate to new abi value. */
- cif->abi = FFI_LINUX | FFI_LINUX_LONG_DOUBLE_128;
- }
-#endif
- else
- return FFI_BAD_ABI;
- return ffi_prep_cif_linux64_core (cif);
-}
-
-ffi_status FFI_HIDDEN
-ffi_prep_cif_linux64_var (ffi_cif *cif,
- unsigned int nfixedargs,
- unsigned int ntotalargs MAYBE_UNUSED)
-{
- if ((cif->abi & FFI_LINUX) != 0)
- cif->nfixedargs = nfixedargs;
-#if _CALL_ELF != 2
- else if (cif->abi == FFI_COMPAT_LINUX64)
- {
- /* This call is from old code. Don't touch cif->nfixedargs
- since old code will be using a smaller cif. */
- cif->flags |= FLAG_COMPAT;
- /* Translate to new abi value. */
- cif->abi = FFI_LINUX | FFI_LINUX_LONG_DOUBLE_128;
- }
-#endif
- else
- return FFI_BAD_ABI;
-#if _CALL_ELF == 2
- cif->flags |= FLAG_ARG_NEEDS_PSAVE;
-#endif
- return ffi_prep_cif_linux64_core (cif);
-}
-
-
-/* ffi_prep_args64 is called by the assembly routine once stack space
- has been allocated for the function's arguments.
-
- The stack layout we want looks like this:
-
- | Ret addr from ffi_call_LINUX64 8bytes | higher addresses
- |--------------------------------------------|
- | CR save area 8bytes |
- |--------------------------------------------|
- | Previous backchain pointer 8 | stack pointer here
- |--------------------------------------------|<+ <<< on entry to
- | Saved r28-r31 4*8 | | ffi_call_LINUX64
- |--------------------------------------------| |
- | GPR registers r3-r10 8*8 | |
- |--------------------------------------------| |
- | FPR registers f1-f13 (optional) 13*8 | |
- |--------------------------------------------| |
- | VEC registers v2-v13 (optional) 12*16 | |
- |--------------------------------------------| |
- | Parameter save area | |
- |--------------------------------------------| |
- | TOC save area 8 | |
- |--------------------------------------------| | stack |
- | Linker doubleword 8 | | grows |
- |--------------------------------------------| | down V
- | Compiler doubleword 8 | |
- |--------------------------------------------| | lower addresses
- | Space for callee's LR 8 | |
- |--------------------------------------------| |
- | CR save area 8 | |
- |--------------------------------------------| | stack pointer here
- | Current backchain pointer 8 |-/ during
- |--------------------------------------------| <<< ffi_call_LINUX64
-
-*/
-
-void FFI_HIDDEN
-ffi_prep_args64 (extended_cif *ecif, unsigned long *const stack)
-{
- const unsigned long bytes = ecif->cif->bytes;
- const unsigned long flags = ecif->cif->flags;
-
- typedef union
- {
- char *c;
- unsigned long *ul;
- float *f;
- double *d;
- float128 *f128;
- size_t p;
- } valp;
-
- /* 'stacktop' points at the previous backchain pointer. */
- valp stacktop;
-
- /* 'next_arg' points at the space for gpr3, and grows upwards as
- we use GPR registers, then continues at rest. */
- valp gpr_base;
- valp gpr_end;
- valp rest;
- valp next_arg;
-
- /* 'fpr_base' points at the space for f1, and grows upwards as
- we use FPR registers. */
- valp fpr_base;
- unsigned int fparg_count;
-
- /* 'vec_base' points at the space for v2, and grows upwards as
- we use vector registers. */
- valp vec_base;
- unsigned int vecarg_count;
-
- unsigned int i, words, nargs, nfixedargs;
- ffi_type **ptr;
- double double_tmp;
- union
- {
- void **v;
- char **c;
- signed char **sc;
- unsigned char **uc;
- signed short **ss;
- unsigned short **us;
- signed int **si;
- unsigned int **ui;
- unsigned long **ul;
- float **f;
- double **d;
- float128 **f128;
- } p_argv;
- unsigned long gprvalue;
- unsigned long align;
-
- stacktop.c = (char *) stack + bytes;
- gpr_base.ul = stacktop.ul - ASM_NEEDS_REGISTERS64 - NUM_GPR_ARG_REGISTERS64;
- gpr_end.ul = gpr_base.ul + NUM_GPR_ARG_REGISTERS64;
-#if _CALL_ELF == 2
- rest.ul = stack + 4 + NUM_GPR_ARG_REGISTERS64;
-#else
- rest.ul = stack + 6 + NUM_GPR_ARG_REGISTERS64;
-#endif
- fpr_base.d = gpr_base.d - NUM_FPR_ARG_REGISTERS64;
- fparg_count = 0;
- /* Place the vector args below the FPRs, if used, else the GPRs. */
- if (ecif->cif->flags & FLAG_FP_ARGUMENTS)
- vec_base.p = fpr_base.p & ~0xF;
- else
- vec_base.p = gpr_base.p;
- vec_base.f128 -= NUM_VEC_ARG_REGISTERS64;
- vecarg_count = 0;
- next_arg.ul = gpr_base.ul;
-
- /* Check that everything starts aligned properly. */
- FFI_ASSERT (((unsigned long) (char *) stack & 0xF) == 0);
- FFI_ASSERT (((unsigned long) stacktop.c & 0xF) == 0);
- FFI_ASSERT (((unsigned long) gpr_base.c & 0xF) == 0);
- FFI_ASSERT (((unsigned long) gpr_end.c & 0xF) == 0);
- FFI_ASSERT (((unsigned long) vec_base.c & 0xF) == 0);
- FFI_ASSERT ((bytes & 0xF) == 0);
-
- /* Deal with return values that are actually pass-by-reference. */
- if (flags & FLAG_RETVAL_REFERENCE)
- *next_arg.ul++ = (unsigned long) (char *) ecif->rvalue;
-
- /* Now for the arguments. */
- p_argv.v = ecif->avalue;
- nargs = ecif->cif->nargs;
-#if _CALL_ELF != 2
- nfixedargs = (unsigned) -1;
- if ((flags & FLAG_COMPAT) == 0)
-#endif
- nfixedargs = ecif->cif->nfixedargs;
- for (ptr = ecif->cif->arg_types, i = 0;
- i < nargs;
- i++, ptr++, p_argv.v++)
- {
- unsigned int elt, elnum;
-
- switch ((*ptr)->type)
- {
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- if ((ecif->cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
- {
- next_arg.p = FFI_ALIGN (next_arg.p, 16);
- if (next_arg.ul == gpr_end.ul)
- next_arg.ul = rest.ul;
- if (vecarg_count < NUM_VEC_ARG_REGISTERS64 && i < nfixedargs)
- *vec_base.f128++ = **p_argv.f128;
- else
- *next_arg.f128 = **p_argv.f128;
- if (++next_arg.f128 == gpr_end.f128)
- next_arg.f128 = rest.f128;
- vecarg_count++;
- FFI_ASSERT (__LDBL_MANT_DIG__ == 113);
- FFI_ASSERT (flags & FLAG_VEC_ARGUMENTS);
- break;
- }
- if ((ecif->cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0)
- {
- double_tmp = (*p_argv.d)[0];
- if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs)
- {
- *fpr_base.d++ = double_tmp;
-# if _CALL_ELF != 2
- if ((flags & FLAG_COMPAT) != 0)
- *next_arg.d = double_tmp;
-# endif
- }
- else
- *next_arg.d = double_tmp;
- if (++next_arg.ul == gpr_end.ul)
- next_arg.ul = rest.ul;
- fparg_count++;
- double_tmp = (*p_argv.d)[1];
- if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs)
- {
- *fpr_base.d++ = double_tmp;
-# if _CALL_ELF != 2
- if ((flags & FLAG_COMPAT) != 0)
- *next_arg.d = double_tmp;
-# endif
- }
- else
- *next_arg.d = double_tmp;
- if (++next_arg.ul == gpr_end.ul)
- next_arg.ul = rest.ul;
- fparg_count++;
- FFI_ASSERT (__LDBL_MANT_DIG__ == 106);
- FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
- break;
- }
- /* Fall through. */
-#endif
- case FFI_TYPE_DOUBLE:
-#if _CALL_ELF != 2
- do_double:
-#endif
- double_tmp = **p_argv.d;
- if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs)
- {
- *fpr_base.d++ = double_tmp;
-#if _CALL_ELF != 2
- if ((flags & FLAG_COMPAT) != 0)
- *next_arg.d = double_tmp;
-#endif
- }
- else
- *next_arg.d = double_tmp;
- if (++next_arg.ul == gpr_end.ul)
- next_arg.ul = rest.ul;
- fparg_count++;
- FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
- break;
-
- case FFI_TYPE_FLOAT:
-#if _CALL_ELF != 2
- do_float:
-#endif
- double_tmp = **p_argv.f;
- if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs)
- {
- *fpr_base.d++ = double_tmp;
-#if _CALL_ELF != 2
- if ((flags & FLAG_COMPAT) != 0)
- {
-# ifndef __LITTLE_ENDIAN__
- next_arg.f[1] = (float) double_tmp;
-# else
- next_arg.f[0] = (float) double_tmp;
-# endif
- }
-#endif
- }
- else
- {
-# ifndef __LITTLE_ENDIAN__
- next_arg.f[1] = (float) double_tmp;
-# else
- next_arg.f[0] = (float) double_tmp;
-# endif
- }
- if (++next_arg.ul == gpr_end.ul)
- next_arg.ul = rest.ul;
- fparg_count++;
- FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
- break;
-
- case FFI_TYPE_STRUCT:
- if ((ecif->cif->abi & FFI_LINUX_STRUCT_ALIGN) != 0)
- {
- align = (*ptr)->alignment;
- if (align > 16)
- align = 16;
- if (align > 1)
- {
- next_arg.p = FFI_ALIGN (next_arg.p, align);
- if (next_arg.ul == gpr_end.ul)
- next_arg.ul = rest.ul;
- }
- }
- elt = discover_homogeneous_aggregate (ecif->cif->abi, *ptr, &elnum);
- if (elt)
- {
-#if _CALL_ELF == 2
- union {
- void *v;
- float *f;
- double *d;
- float128 *f128;
- } arg;
-
- arg.v = *p_argv.v;
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- if (elt == FFI_TYPE_LONGDOUBLE &&
- (ecif->cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
- {
- do
- {
- if (vecarg_count < NUM_VEC_ARG_REGISTERS64
- && i < nfixedargs)
- *vec_base.f128++ = *arg.f128++;
- else
- *next_arg.f128 = *arg.f128++;
- if (++next_arg.f128 == gpr_end.f128)
- next_arg.f128 = rest.f128;
- vecarg_count++;
- }
- while (--elnum != 0);
- }
- else
-#endif
- if (elt == FFI_TYPE_FLOAT)
- {
- do
- {
- double_tmp = *arg.f++;
- if (fparg_count < NUM_FPR_ARG_REGISTERS64
- && i < nfixedargs)
- *fpr_base.d++ = double_tmp;
- else
- *next_arg.f = (float) double_tmp;
- if (++next_arg.f == gpr_end.f)
- next_arg.f = rest.f;
- fparg_count++;
- }
- while (--elnum != 0);
- if ((next_arg.p & 7) != 0)
- if (++next_arg.f == gpr_end.f)
- next_arg.f = rest.f;
- }
- else
- do
- {
- double_tmp = *arg.d++;
- if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs)
- *fpr_base.d++ = double_tmp;
- else
- *next_arg.d = double_tmp;
- if (++next_arg.d == gpr_end.d)
- next_arg.d = rest.d;
- fparg_count++;
- }
- while (--elnum != 0);
-#else
- if (elt == FFI_TYPE_FLOAT)
- goto do_float;
- else
- goto do_double;
-#endif
- }
- else
- {
- words = ((*ptr)->size + 7) / 8;
- if (next_arg.ul >= gpr_base.ul && next_arg.ul + words > gpr_end.ul)
- {
- size_t first = gpr_end.c - next_arg.c;
- memcpy (next_arg.c, *p_argv.c, first);
- memcpy (rest.c, *p_argv.c + first, (*ptr)->size - first);
- next_arg.c = rest.c + words * 8 - first;
- }
- else
- {
- char *where = next_arg.c;
-
-#ifndef __LITTLE_ENDIAN__
- /* Structures with size less than eight bytes are passed
- left-padded. */
- if ((*ptr)->size < 8)
- where += 8 - (*ptr)->size;
-#endif
- memcpy (where, *p_argv.c, (*ptr)->size);
- next_arg.ul += words;
- if (next_arg.ul == gpr_end.ul)
- next_arg.ul = rest.ul;
- }
- }
- break;
-
- case FFI_TYPE_UINT8:
- gprvalue = **p_argv.uc;
- goto putgpr;
- case FFI_TYPE_SINT8:
- gprvalue = **p_argv.sc;
- goto putgpr;
- case FFI_TYPE_UINT16:
- gprvalue = **p_argv.us;
- goto putgpr;
- case FFI_TYPE_SINT16:
- gprvalue = **p_argv.ss;
- goto putgpr;
- case FFI_TYPE_UINT32:
- gprvalue = **p_argv.ui;
- goto putgpr;
- case FFI_TYPE_INT:
- case FFI_TYPE_SINT32:
- gprvalue = **p_argv.si;
- goto putgpr;
-
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- case FFI_TYPE_POINTER:
- gprvalue = **p_argv.ul;
- putgpr:
- *next_arg.ul++ = gprvalue;
- if (next_arg.ul == gpr_end.ul)
- next_arg.ul = rest.ul;
- break;
- }
- }
-
- FFI_ASSERT (flags & FLAG_4_GPR_ARGUMENTS
- || (next_arg.ul >= gpr_base.ul
- && next_arg.ul <= gpr_base.ul + 4));
-}
-
-
-#if _CALL_ELF == 2
-#define MIN_CACHE_LINE_SIZE 8
-
-static void
-flush_icache (char *wraddr, char *xaddr, int size)
-{
- int i;
- for (i = 0; i < size; i += MIN_CACHE_LINE_SIZE)
- __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;"
- : : "r" (xaddr + i), "r" (wraddr + i) : "memory");
- __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;" "sync;" "isync;"
- : : "r"(xaddr + size - 1), "r"(wraddr + size - 1)
- : "memory");
-}
-#endif
-
-
-ffi_status FFI_HIDDEN
-ffi_prep_closure_loc_linux64 (ffi_closure *closure,
- ffi_cif *cif,
- void (*fun) (ffi_cif *, void *, void **, void *),
- void *user_data,
- void *codeloc)
-{
-#if _CALL_ELF == 2
- unsigned int *tramp = (unsigned int *) &closure->tramp[0];
-
- if (cif->abi < FFI_LINUX || cif->abi >= FFI_LAST_ABI)
- return FFI_BAD_ABI;
-
- tramp[0] = 0xe96c0018; /* 0: ld 11,2f-0b(12) */
- tramp[1] = 0xe98c0010; /* ld 12,1f-0b(12) */
- tramp[2] = 0x7d8903a6; /* mtctr 12 */
- tramp[3] = 0x4e800420; /* bctr */
- /* 1: .quad function_addr */
- /* 2: .quad context */
- *(void **) &tramp[4] = (void *) ffi_closure_LINUX64;
- *(void **) &tramp[6] = codeloc;
- flush_icache ((char *) tramp, (char *) codeloc, 4 * 4);
-#else
- void **tramp = (void **) &closure->tramp[0];
-
- if (cif->abi < FFI_LINUX || cif->abi >= FFI_LAST_ABI)
- return FFI_BAD_ABI;
-
- /* Copy function address and TOC from ffi_closure_LINUX64 OPD. */
- memcpy (&tramp[0], (void **) ffi_closure_LINUX64, sizeof (void *));
- tramp[1] = codeloc;
- memcpy (&tramp[2], (void **) ffi_closure_LINUX64 + 1, sizeof (void *));
-#endif
-
- closure->cif = cif;
- closure->fun = fun;
- closure->user_data = user_data;
-
- return FFI_OK;
-}
-
-
-int FFI_HIDDEN
-ffi_closure_helper_LINUX64 (ffi_cif *cif,
- void (*fun) (ffi_cif *, void *, void **, void *),
- void *user_data,
- void *rvalue,
- unsigned long *pst,
- ffi_dblfl *pfr,
- float128 *pvec)
-{
- /* rvalue is the pointer to space for return value in closure assembly */
- /* pst is the pointer to parameter save area
- (r3-r10 are stored into its first 8 slots by ffi_closure_LINUX64) */
- /* pfr is the pointer to where f1-f13 are stored in ffi_closure_LINUX64 */
- /* pvec is the pointer to where v2-v13 are stored in ffi_closure_LINUX64 */
-
- void **avalue;
- ffi_type **arg_types;
- unsigned long i, avn, nfixedargs;
- ffi_dblfl *end_pfr = pfr + NUM_FPR_ARG_REGISTERS64;
- float128 *end_pvec = pvec + NUM_VEC_ARG_REGISTERS64;
- unsigned long align;
-
- avalue = alloca (cif->nargs * sizeof (void *));
-
- /* Copy the caller's structure return value address so that the
- closure returns the data directly to the caller. */
- if (cif->rtype->type == FFI_TYPE_STRUCT
- && (cif->flags & FLAG_RETURNS_SMST) == 0)
- {
- rvalue = (void *) *pst;
- pst++;
- }
-
- i = 0;
- avn = cif->nargs;
-#if _CALL_ELF != 2
- nfixedargs = (unsigned) -1;
- if ((cif->flags & FLAG_COMPAT) == 0)
-#endif
- nfixedargs = cif->nfixedargs;
- arg_types = cif->arg_types;
-
- /* Grab the addresses of the arguments from the stack frame. */
- while (i < avn)
- {
- unsigned int elt, elnum;
-
- switch (arg_types[i]->type)
- {
- case FFI_TYPE_SINT8:
- case FFI_TYPE_UINT8:
-#ifndef __LITTLE_ENDIAN__
- avalue[i] = (char *) pst + 7;
- pst++;
- break;
-#endif
-
- case FFI_TYPE_SINT16:
- case FFI_TYPE_UINT16:
-#ifndef __LITTLE_ENDIAN__
- avalue[i] = (char *) pst + 6;
- pst++;
- break;
-#endif
-
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT32:
-#ifndef __LITTLE_ENDIAN__
- avalue[i] = (char *) pst + 4;
- pst++;
- break;
-#endif
-
- case FFI_TYPE_SINT64:
- case FFI_TYPE_UINT64:
- case FFI_TYPE_POINTER:
- avalue[i] = pst;
- pst++;
- break;
-
- case FFI_TYPE_STRUCT:
- if ((cif->abi & FFI_LINUX_STRUCT_ALIGN) != 0)
- {
- align = arg_types[i]->alignment;
- if (align > 16)
- align = 16;
- if (align > 1)
- pst = (unsigned long *) FFI_ALIGN ((size_t) pst, align);
- }
- elt = discover_homogeneous_aggregate (cif->abi, arg_types[i], &elnum);
- if (elt)
- {
-#if _CALL_ELF == 2
- union {
- void *v;
- unsigned long *ul;
- float *f;
- double *d;
- float128 *f128;
- size_t p;
- } to, from;
-
- /* Repackage the aggregate from its parts. The
- aggregate size is not greater than the space taken by
- the registers so store back to the register/parameter
- save arrays. */
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- if (elt == FFI_TYPE_LONGDOUBLE &&
- (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
- {
- if (pvec + elnum <= end_pvec)
- to.v = pvec;
- else
- to.v = pst;
- }
- else
-#endif
- if (pfr + elnum <= end_pfr)
- to.v = pfr;
- else
- to.v = pst;
-
- avalue[i] = to.v;
- from.ul = pst;
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- if (elt == FFI_TYPE_LONGDOUBLE &&
- (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
- {
- do
- {
- if (pvec < end_pvec && i < nfixedargs)
- *to.f128 = *pvec++;
- else
- *to.f128 = *from.f128;
- to.f128++;
- from.f128++;
- }
- while (--elnum != 0);
- }
- else
-#endif
- if (elt == FFI_TYPE_FLOAT)
- {
- do
- {
- if (pfr < end_pfr && i < nfixedargs)
- {
- *to.f = (float) pfr->d;
- pfr++;
- }
- else
- *to.f = *from.f;
- to.f++;
- from.f++;
- }
- while (--elnum != 0);
- }
- else
- {
- do
- {
- if (pfr < end_pfr && i < nfixedargs)
- {
- *to.d = pfr->d;
- pfr++;
- }
- else
- *to.d = *from.d;
- to.d++;
- from.d++;
- }
- while (--elnum != 0);
- }
-#else
- if (elt == FFI_TYPE_FLOAT)
- goto do_float;
- else
- goto do_double;
-#endif
- }
- else
- {
-#ifndef __LITTLE_ENDIAN__
- /* Structures with size less than eight bytes are passed
- left-padded. */
- if (arg_types[i]->size < 8)
- avalue[i] = (char *) pst + 8 - arg_types[i]->size;
- else
-#endif
- avalue[i] = pst;
- }
- pst += (arg_types[i]->size + 7) / 8;
- break;
-
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
- {
- if (((unsigned long) pst & 0xF) != 0)
- ++pst;
- if (pvec < end_pvec && i < nfixedargs)
- avalue[i] = pvec++;
- else
- avalue[i] = pst;
- pst += 2;
- break;
- }
- else if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0)
- {
- if (pfr + 1 < end_pfr && i + 1 < nfixedargs)
- {
- avalue[i] = pfr;
- pfr += 2;
- }
- else
- {
- if (pfr < end_pfr && i < nfixedargs)
- {
- /* Passed partly in f13 and partly on the stack.
- Move it all to the stack. */
- *pst = *(unsigned long *) pfr;
- pfr++;
- }
- avalue[i] = pst;
- }
- pst += 2;
- break;
- }
- /* Fall through. */
-#endif
- case FFI_TYPE_DOUBLE:
-#if _CALL_ELF != 2
- do_double:
-#endif
- /* On the outgoing stack all values are aligned to 8 */
- /* there are 13 64bit floating point registers */
-
- if (pfr < end_pfr && i < nfixedargs)
- {
- avalue[i] = pfr;
- pfr++;
- }
- else
- avalue[i] = pst;
- pst++;
- break;
-
- case FFI_TYPE_FLOAT:
-#if _CALL_ELF != 2
- do_float:
-#endif
- if (pfr < end_pfr && i < nfixedargs)
- {
- /* Float values are stored as doubles in the
- ffi_closure_LINUX64 code. Fix them here. */
- pfr->f = (float) pfr->d;
- avalue[i] = pfr;
- pfr++;
- }
- else
- {
-#ifndef __LITTLE_ENDIAN__
- avalue[i] = (char *) pst + 4;
-#else
- avalue[i] = pst;
-#endif
- }
- pst++;
- break;
-
- default:
- FFI_ASSERT (0);
- }
-
- i++;
- }
-
- (*fun) (cif, rvalue, avalue, user_data);
-
- /* Tell ffi_closure_LINUX64 how to perform return type promotions. */
- if ((cif->flags & FLAG_RETURNS_SMST) != 0)
- {
- if ((cif->flags & (FLAG_RETURNS_FP | FLAG_RETURNS_VEC)) == 0)
- return FFI_V2_TYPE_SMALL_STRUCT + cif->rtype->size - 1;
- else if ((cif->flags & FLAG_RETURNS_VEC) != 0)
- return FFI_V2_TYPE_VECTOR_HOMOG;
- else if ((cif->flags & FLAG_RETURNS_64BITS) != 0)
- return FFI_V2_TYPE_DOUBLE_HOMOG;
- else
- return FFI_V2_TYPE_FLOAT_HOMOG;
- }
- if ((cif->flags & FLAG_RETURNS_VEC) != 0)
- return FFI_V2_TYPE_VECTOR;
- return cif->rtype->type;
-}
-#endif
+/* -----------------------------------------------------------------------
+ ffi_linux64.c - Copyright (C) 2013 IBM
+ Copyright (C) 2011 Anthony Green
+ Copyright (C) 2011 Kyle Moffett
+ Copyright (C) 2008 Red Hat, Inc
+ Copyright (C) 2007, 2008 Free Software Foundation, Inc
+ Copyright (c) 1998 Geoffrey Keating
+
+ PowerPC Foreign Function Interface
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#include "ffi.h"
+
+#ifdef POWERPC64
+#include "ffi_common.h"
+#include "ffi_powerpc.h"
+
+
+/* About the LINUX64 ABI. */
+enum {
+ NUM_GPR_ARG_REGISTERS64 = 8,
+ NUM_FPR_ARG_REGISTERS64 = 13,
+ NUM_VEC_ARG_REGISTERS64 = 12,
+};
+enum { ASM_NEEDS_REGISTERS64 = 4 };
+
+
+#if HAVE_LONG_DOUBLE_VARIANT && FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+/* Adjust size of ffi_type_longdouble. */
+void FFI_HIDDEN
+ffi_prep_types_linux64 (ffi_abi abi)
+{
+ if ((abi & (FFI_LINUX | FFI_LINUX_LONG_DOUBLE_128)) == FFI_LINUX)
+ {
+ ffi_type_longdouble.size = 8;
+ ffi_type_longdouble.alignment = 8;
+ }
+ else
+ {
+ ffi_type_longdouble.size = 16;
+ ffi_type_longdouble.alignment = 16;
+ }
+}
+#endif
+
+
+static unsigned int
+discover_homogeneous_aggregate (ffi_abi abi,
+ const ffi_type *t,
+ unsigned int *elnum)
+{
+ switch (t->type)
+ {
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ /* 64-bit long doubles are equivalent to doubles. */
+ if ((abi & FFI_LINUX_LONG_DOUBLE_128) == 0)
+ {
+ *elnum = 1;
+ return FFI_TYPE_DOUBLE;
+ }
+ /* IBM extended precision values use unaligned pairs
+ of FPRs, but according to the ABI must be considered
+ distinct from doubles. They are also limited to a
+ maximum of four members in a homogeneous aggregate. */
+ else if ((abi & FFI_LINUX_LONG_DOUBLE_IEEE128) == 0)
+ {
+ *elnum = 2;
+ return FFI_TYPE_LONGDOUBLE;
+ }
+ /* Fall through. */
+#endif
+ case FFI_TYPE_FLOAT:
+ case FFI_TYPE_DOUBLE:
+ *elnum = 1;
+ return (int) t->type;
+
+ case FFI_TYPE_STRUCT:;
+ {
+ unsigned int base_elt = 0, total_elnum = 0;
+ ffi_type **el = t->elements;
+ while (*el)
+ {
+ unsigned int el_elt, el_elnum = 0;
+ el_elt = discover_homogeneous_aggregate (abi, *el, &el_elnum);
+ if (el_elt == 0
+ || (base_elt && base_elt != el_elt))
+ return 0;
+ base_elt = el_elt;
+ total_elnum += el_elnum;
+#if _CALL_ELF == 2
+ if (total_elnum > 8)
+ return 0;
+#else
+ if (total_elnum > 1)
+ return 0;
+#endif
+ el++;
+ }
+ *elnum = total_elnum;
+ return base_elt;
+ }
+
+ default:
+ return 0;
+ }
+}
+
+
+/* Perform machine dependent cif processing */
+static ffi_status
+ffi_prep_cif_linux64_core (ffi_cif *cif)
+{
+ ffi_type **ptr;
+ unsigned bytes;
+ unsigned i, fparg_count = 0, intarg_count = 0, vecarg_count = 0;
+ unsigned flags = cif->flags;
+ unsigned elt, elnum, rtype;
+
+#if FFI_TYPE_LONGDOUBLE == FFI_TYPE_DOUBLE
+ /* If compiled without long double support... */
+ if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0 ||
+ (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
+ return FFI_BAD_ABI;
+#elif !defined(__VEC__)
+ /* If compiled without vector register support (used by assembly)... */
+ if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
+ return FFI_BAD_ABI;
+#else
+ /* If the IEEE128 flag is set, but long double is only 64 bits wide... */
+ if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) == 0 &&
+ (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
+ return FFI_BAD_ABI;
+#endif
+
+ /* The machine-independent calculation of cif->bytes doesn't work
+ for us. Redo the calculation. */
+#if _CALL_ELF == 2
+ /* Space for backchain, CR, LR, TOC and the asm's temp regs. */
+ bytes = (4 + ASM_NEEDS_REGISTERS64) * sizeof (long);
+
+ /* Space for the general registers. */
+ bytes += NUM_GPR_ARG_REGISTERS64 * sizeof (long);
+#else
+ /* Space for backchain, CR, LR, cc/ld doubleword, TOC and the asm's temp
+ regs. */
+ bytes = (6 + ASM_NEEDS_REGISTERS64) * sizeof (long);
+
+ /* Space for the mandatory parm save area and general registers. */
+ bytes += 2 * NUM_GPR_ARG_REGISTERS64 * sizeof (long);
+#endif
+
+ /* Return value handling. */
+ rtype = cif->rtype->type;
+#if _CALL_ELF == 2
+homogeneous:
+#endif
+ switch (rtype)
+ {
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
+ {
+ flags |= FLAG_RETURNS_VEC;
+ break;
+ }
+ if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0)
+ flags |= FLAG_RETURNS_128BITS;
+ /* Fall through. */
+#endif
+ case FFI_TYPE_DOUBLE:
+ flags |= FLAG_RETURNS_64BITS;
+ /* Fall through. */
+ case FFI_TYPE_FLOAT:
+ flags |= FLAG_RETURNS_FP;
+ break;
+
+ case FFI_TYPE_UINT128:
+ flags |= FLAG_RETURNS_128BITS;
+ /* Fall through. */
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_POINTER:
+ flags |= FLAG_RETURNS_64BITS;
+ break;
+
+ case FFI_TYPE_STRUCT:
+#if _CALL_ELF == 2
+ elt = discover_homogeneous_aggregate (cif->abi, cif->rtype, &elnum);
+ if (elt)
+ {
+ flags |= FLAG_RETURNS_SMST;
+ rtype = elt;
+ goto homogeneous;
+ }
+ if (cif->rtype->size <= 16)
+ {
+ flags |= FLAG_RETURNS_SMST;
+ break;
+ }
+#endif
+ intarg_count++;
+ flags |= FLAG_RETVAL_REFERENCE;
+ /* Fall through. */
+ case FFI_TYPE_VOID:
+ flags |= FLAG_RETURNS_NOTHING;
+ break;
+
+ default:
+ /* Returns 32-bit integer, or similar. Nothing to do here. */
+ break;
+ }
+
+ for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++)
+ {
+ unsigned int align;
+
+ switch ((*ptr)->type)
+ {
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
+ {
+ vecarg_count++;
+ /* Align to 16 bytes, plus the 16-byte argument. */
+ intarg_count = (intarg_count + 3) & ~0x1;
+ if (vecarg_count > NUM_VEC_ARG_REGISTERS64)
+ flags |= FLAG_ARG_NEEDS_PSAVE;
+ break;
+ }
+ if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0)
+ {
+ fparg_count++;
+ intarg_count++;
+ }
+ /* Fall through. */
+#endif
+ case FFI_TYPE_DOUBLE:
+ case FFI_TYPE_FLOAT:
+ fparg_count++;
+ intarg_count++;
+ if (fparg_count > NUM_FPR_ARG_REGISTERS64)
+ flags |= FLAG_ARG_NEEDS_PSAVE;
+ break;
+
+ case FFI_TYPE_STRUCT:
+ if ((cif->abi & FFI_LINUX_STRUCT_ALIGN) != 0)
+ {
+ align = (*ptr)->alignment;
+ if (align > 16)
+ align = 16;
+ align = align / 8;
+ if (align > 1)
+ intarg_count = FFI_ALIGN (intarg_count, align);
+ }
+ intarg_count += ((*ptr)->size + 7) / 8;
+ elt = discover_homogeneous_aggregate (cif->abi, *ptr, &elnum);
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ if (elt == FFI_TYPE_LONGDOUBLE &&
+ (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
+ {
+ vecarg_count += elnum;
+ if (vecarg_count > NUM_VEC_ARG_REGISTERS64)
+ flags |= FLAG_ARG_NEEDS_PSAVE;
+ break;
+ }
+ else
+#endif
+ if (elt)
+ {
+ fparg_count += elnum;
+ if (fparg_count > NUM_FPR_ARG_REGISTERS64)
+ flags |= FLAG_ARG_NEEDS_PSAVE;
+ }
+ else
+ {
+ if (intarg_count > NUM_GPR_ARG_REGISTERS64)
+ flags |= FLAG_ARG_NEEDS_PSAVE;
+ }
+ break;
+
+ case FFI_TYPE_POINTER:
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ /* Everything else is passed as a 8-byte word in a GPR, either
+ the object itself or a pointer to it. */
+ intarg_count++;
+ if (intarg_count > NUM_GPR_ARG_REGISTERS64)
+ flags |= FLAG_ARG_NEEDS_PSAVE;
+ break;
+ default:
+ FFI_ASSERT (0);
+ }
+ }
+
+ if (fparg_count != 0)
+ flags |= FLAG_FP_ARGUMENTS;
+ if (intarg_count > 4)
+ flags |= FLAG_4_GPR_ARGUMENTS;
+ if (vecarg_count != 0)
+ flags |= FLAG_VEC_ARGUMENTS;
+
+ /* Space for the FPR registers, if needed. */
+ if (fparg_count != 0)
+ bytes += NUM_FPR_ARG_REGISTERS64 * sizeof (double);
+ /* Space for the vector registers, if needed, aligned to 16 bytes. */
+ if (vecarg_count != 0) {
+ bytes = (bytes + 15) & ~0xF;
+ bytes += NUM_VEC_ARG_REGISTERS64 * sizeof (float128);
+ }
+
+ /* Stack space. */
+#if _CALL_ELF == 2
+ if ((flags & FLAG_ARG_NEEDS_PSAVE) != 0)
+ bytes += intarg_count * sizeof (long);
+#else
+ if (intarg_count > NUM_GPR_ARG_REGISTERS64)
+ bytes += (intarg_count - NUM_GPR_ARG_REGISTERS64) * sizeof (long);
+#endif
+
+ /* The stack space allocated needs to be a multiple of 16 bytes. */
+ bytes = (bytes + 15) & ~0xF;
+
+ cif->flags = flags;
+ cif->bytes = bytes;
+
+ return FFI_OK;
+}
+
+ffi_status FFI_HIDDEN
+ffi_prep_cif_linux64 (ffi_cif *cif)
+{
+ if ((cif->abi & FFI_LINUX) != 0)
+ cif->nfixedargs = cif->nargs;
+#if _CALL_ELF != 2
+ else if (cif->abi == FFI_COMPAT_LINUX64)
+ {
+ /* This call is from old code. Don't touch cif->nfixedargs
+ since old code will be using a smaller cif. */
+ cif->flags |= FLAG_COMPAT;
+ /* Translate to new abi value. */
+ cif->abi = FFI_LINUX | FFI_LINUX_LONG_DOUBLE_128;
+ }
+#endif
+ else
+ return FFI_BAD_ABI;
+ return ffi_prep_cif_linux64_core (cif);
+}
+
+ffi_status FFI_HIDDEN
+ffi_prep_cif_linux64_var (ffi_cif *cif,
+ unsigned int nfixedargs,
+ unsigned int ntotalargs MAYBE_UNUSED)
+{
+ if ((cif->abi & FFI_LINUX) != 0)
+ cif->nfixedargs = nfixedargs;
+#if _CALL_ELF != 2
+ else if (cif->abi == FFI_COMPAT_LINUX64)
+ {
+ /* This call is from old code. Don't touch cif->nfixedargs
+ since old code will be using a smaller cif. */
+ cif->flags |= FLAG_COMPAT;
+ /* Translate to new abi value. */
+ cif->abi = FFI_LINUX | FFI_LINUX_LONG_DOUBLE_128;
+ }
+#endif
+ else
+ return FFI_BAD_ABI;
+#if _CALL_ELF == 2
+ cif->flags |= FLAG_ARG_NEEDS_PSAVE;
+#endif
+ return ffi_prep_cif_linux64_core (cif);
+}
+
+
+/* ffi_prep_args64 is called by the assembly routine once stack space
+ has been allocated for the function's arguments.
+
+ The stack layout we want looks like this:
+
+ | Ret addr from ffi_call_LINUX64 8bytes | higher addresses
+ |--------------------------------------------|
+ | CR save area 8bytes |
+ |--------------------------------------------|
+ | Previous backchain pointer 8 | stack pointer here
+ |--------------------------------------------|<+ <<< on entry to
+ | Saved r28-r31 4*8 | | ffi_call_LINUX64
+ |--------------------------------------------| |
+ | GPR registers r3-r10 8*8 | |
+ |--------------------------------------------| |
+ | FPR registers f1-f13 (optional) 13*8 | |
+ |--------------------------------------------| |
+ | VEC registers v2-v13 (optional) 12*16 | |
+ |--------------------------------------------| |
+ | Parameter save area | |
+ |--------------------------------------------| |
+ | TOC save area 8 | |
+ |--------------------------------------------| | stack |
+ | Linker doubleword 8 | | grows |
+ |--------------------------------------------| | down V
+ | Compiler doubleword 8 | |
+ |--------------------------------------------| | lower addresses
+ | Space for callee's LR 8 | |
+ |--------------------------------------------| |
+ | CR save area 8 | |
+ |--------------------------------------------| | stack pointer here
+ | Current backchain pointer 8 |-/ during
+ |--------------------------------------------| <<< ffi_call_LINUX64
+
+*/
+
+void FFI_HIDDEN
+ffi_prep_args64 (extended_cif *ecif, unsigned long *const stack)
+{
+ const unsigned long bytes = ecif->cif->bytes;
+ const unsigned long flags = ecif->cif->flags;
+
+ typedef union
+ {
+ char *c;
+ unsigned long *ul;
+ float *f;
+ double *d;
+ float128 *f128;
+ size_t p;
+ } valp;
+
+ /* 'stacktop' points at the previous backchain pointer. */
+ valp stacktop;
+
+ /* 'next_arg' points at the space for gpr3, and grows upwards as
+ we use GPR registers, then continues at rest. */
+ valp gpr_base;
+ valp gpr_end;
+ valp rest;
+ valp next_arg;
+
+ /* 'fpr_base' points at the space for f1, and grows upwards as
+ we use FPR registers. */
+ valp fpr_base;
+ unsigned int fparg_count;
+
+ /* 'vec_base' points at the space for v2, and grows upwards as
+ we use vector registers. */
+ valp vec_base;
+ unsigned int vecarg_count;
+
+ unsigned int i, words, nargs, nfixedargs;
+ ffi_type **ptr;
+ double double_tmp;
+ union
+ {
+ void **v;
+ char **c;
+ signed char **sc;
+ unsigned char **uc;
+ signed short **ss;
+ unsigned short **us;
+ signed int **si;
+ unsigned int **ui;
+ unsigned long **ul;
+ float **f;
+ double **d;
+ float128 **f128;
+ } p_argv;
+ unsigned long gprvalue;
+ unsigned long align;
+
+ stacktop.c = (char *) stack + bytes;
+ gpr_base.ul = stacktop.ul - ASM_NEEDS_REGISTERS64 - NUM_GPR_ARG_REGISTERS64;
+ gpr_end.ul = gpr_base.ul + NUM_GPR_ARG_REGISTERS64;
+#if _CALL_ELF == 2
+ rest.ul = stack + 4 + NUM_GPR_ARG_REGISTERS64;
+#else
+ rest.ul = stack + 6 + NUM_GPR_ARG_REGISTERS64;
+#endif
+ fpr_base.d = gpr_base.d - NUM_FPR_ARG_REGISTERS64;
+ fparg_count = 0;
+ /* Place the vector args below the FPRs, if used, else the GPRs. */
+ if (ecif->cif->flags & FLAG_FP_ARGUMENTS)
+ vec_base.p = fpr_base.p & ~0xF;
+ else
+ vec_base.p = gpr_base.p;
+ vec_base.f128 -= NUM_VEC_ARG_REGISTERS64;
+ vecarg_count = 0;
+ next_arg.ul = gpr_base.ul;
+
+ /* Check that everything starts aligned properly. */
+ FFI_ASSERT (((unsigned long) (char *) stack & 0xF) == 0);
+ FFI_ASSERT (((unsigned long) stacktop.c & 0xF) == 0);
+ FFI_ASSERT (((unsigned long) gpr_base.c & 0xF) == 0);
+ FFI_ASSERT (((unsigned long) gpr_end.c & 0xF) == 0);
+ FFI_ASSERT (((unsigned long) vec_base.c & 0xF) == 0);
+ FFI_ASSERT ((bytes & 0xF) == 0);
+
+ /* Deal with return values that are actually pass-by-reference. */
+ if (flags & FLAG_RETVAL_REFERENCE)
+ *next_arg.ul++ = (unsigned long) (char *) ecif->rvalue;
+
+ /* Now for the arguments. */
+ p_argv.v = ecif->avalue;
+ nargs = ecif->cif->nargs;
+#if _CALL_ELF != 2
+ nfixedargs = (unsigned) -1;
+ if ((flags & FLAG_COMPAT) == 0)
+#endif
+ nfixedargs = ecif->cif->nfixedargs;
+ for (ptr = ecif->cif->arg_types, i = 0;
+ i < nargs;
+ i++, ptr++, p_argv.v++)
+ {
+ unsigned int elt, elnum;
+
+ switch ((*ptr)->type)
+ {
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ if ((ecif->cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
+ {
+ next_arg.p = FFI_ALIGN (next_arg.p, 16);
+ if (next_arg.ul == gpr_end.ul)
+ next_arg.ul = rest.ul;
+ if (vecarg_count < NUM_VEC_ARG_REGISTERS64 && i < nfixedargs)
+ *vec_base.f128++ = **p_argv.f128;
+ else
+ *next_arg.f128 = **p_argv.f128;
+ if (++next_arg.f128 == gpr_end.f128)
+ next_arg.f128 = rest.f128;
+ vecarg_count++;
+ FFI_ASSERT (__LDBL_MANT_DIG__ == 113);
+ FFI_ASSERT (flags & FLAG_VEC_ARGUMENTS);
+ break;
+ }
+ if ((ecif->cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0)
+ {
+ double_tmp = (*p_argv.d)[0];
+ if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs)
+ {
+ *fpr_base.d++ = double_tmp;
+# if _CALL_ELF != 2
+ if ((flags & FLAG_COMPAT) != 0)
+ *next_arg.d = double_tmp;
+# endif
+ }
+ else
+ *next_arg.d = double_tmp;
+ if (++next_arg.ul == gpr_end.ul)
+ next_arg.ul = rest.ul;
+ fparg_count++;
+ double_tmp = (*p_argv.d)[1];
+ if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs)
+ {
+ *fpr_base.d++ = double_tmp;
+# if _CALL_ELF != 2
+ if ((flags & FLAG_COMPAT) != 0)
+ *next_arg.d = double_tmp;
+# endif
+ }
+ else
+ *next_arg.d = double_tmp;
+ if (++next_arg.ul == gpr_end.ul)
+ next_arg.ul = rest.ul;
+ fparg_count++;
+ FFI_ASSERT (__LDBL_MANT_DIG__ == 106);
+ FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
+ break;
+ }
+ /* Fall through. */
+#endif
+ case FFI_TYPE_DOUBLE:
+#if _CALL_ELF != 2
+ do_double:
+#endif
+ double_tmp = **p_argv.d;
+ if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs)
+ {
+ *fpr_base.d++ = double_tmp;
+#if _CALL_ELF != 2
+ if ((flags & FLAG_COMPAT) != 0)
+ *next_arg.d = double_tmp;
+#endif
+ }
+ else
+ *next_arg.d = double_tmp;
+ if (++next_arg.ul == gpr_end.ul)
+ next_arg.ul = rest.ul;
+ fparg_count++;
+ FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
+ break;
+
+ case FFI_TYPE_FLOAT:
+#if _CALL_ELF != 2
+ do_float:
+#endif
+ double_tmp = **p_argv.f;
+ if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs)
+ {
+ *fpr_base.d++ = double_tmp;
+#if _CALL_ELF != 2
+ if ((flags & FLAG_COMPAT) != 0)
+ {
+# ifndef __LITTLE_ENDIAN__
+ next_arg.f[1] = (float) double_tmp;
+# else
+ next_arg.f[0] = (float) double_tmp;
+# endif
+ }
+#endif
+ }
+ else
+ {
+# ifndef __LITTLE_ENDIAN__
+ next_arg.f[1] = (float) double_tmp;
+# else
+ next_arg.f[0] = (float) double_tmp;
+# endif
+ }
+ if (++next_arg.ul == gpr_end.ul)
+ next_arg.ul = rest.ul;
+ fparg_count++;
+ FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
+ break;
+
+ case FFI_TYPE_STRUCT:
+ if ((ecif->cif->abi & FFI_LINUX_STRUCT_ALIGN) != 0)
+ {
+ align = (*ptr)->alignment;
+ if (align > 16)
+ align = 16;
+ if (align > 1)
+ {
+ next_arg.p = FFI_ALIGN (next_arg.p, align);
+ if (next_arg.ul == gpr_end.ul)
+ next_arg.ul = rest.ul;
+ }
+ }
+ elt = discover_homogeneous_aggregate (ecif->cif->abi, *ptr, &elnum);
+ if (elt)
+ {
+#if _CALL_ELF == 2
+ union {
+ void *v;
+ float *f;
+ double *d;
+ float128 *f128;
+ } arg;
+
+ arg.v = *p_argv.v;
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ if (elt == FFI_TYPE_LONGDOUBLE &&
+ (ecif->cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
+ {
+ do
+ {
+ if (vecarg_count < NUM_VEC_ARG_REGISTERS64
+ && i < nfixedargs)
+ *vec_base.f128++ = *arg.f128++;
+ else
+ *next_arg.f128 = *arg.f128++;
+ if (++next_arg.f128 == gpr_end.f128)
+ next_arg.f128 = rest.f128;
+ vecarg_count++;
+ }
+ while (--elnum != 0);
+ }
+ else
+#endif
+ if (elt == FFI_TYPE_FLOAT)
+ {
+ do
+ {
+ double_tmp = *arg.f++;
+ if (fparg_count < NUM_FPR_ARG_REGISTERS64
+ && i < nfixedargs)
+ *fpr_base.d++ = double_tmp;
+ else
+ *next_arg.f = (float) double_tmp;
+ if (++next_arg.f == gpr_end.f)
+ next_arg.f = rest.f;
+ fparg_count++;
+ }
+ while (--elnum != 0);
+ if ((next_arg.p & 7) != 0)
+ if (++next_arg.f == gpr_end.f)
+ next_arg.f = rest.f;
+ }
+ else
+ do
+ {
+ double_tmp = *arg.d++;
+ if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs)
+ *fpr_base.d++ = double_tmp;
+ else
+ *next_arg.d = double_tmp;
+ if (++next_arg.d == gpr_end.d)
+ next_arg.d = rest.d;
+ fparg_count++;
+ }
+ while (--elnum != 0);
+#else
+ if (elt == FFI_TYPE_FLOAT)
+ goto do_float;
+ else
+ goto do_double;
+#endif
+ }
+ else
+ {
+ words = ((*ptr)->size + 7) / 8;
+ if (next_arg.ul >= gpr_base.ul && next_arg.ul + words > gpr_end.ul)
+ {
+ size_t first = gpr_end.c - next_arg.c;
+ memcpy (next_arg.c, *p_argv.c, first);
+ memcpy (rest.c, *p_argv.c + first, (*ptr)->size - first);
+ next_arg.c = rest.c + words * 8 - first;
+ }
+ else
+ {
+ char *where = next_arg.c;
+
+#ifndef __LITTLE_ENDIAN__
+ /* Structures with size less than eight bytes are passed
+ left-padded. */
+ if ((*ptr)->size < 8)
+ where += 8 - (*ptr)->size;
+#endif
+ memcpy (where, *p_argv.c, (*ptr)->size);
+ next_arg.ul += words;
+ if (next_arg.ul == gpr_end.ul)
+ next_arg.ul = rest.ul;
+ }
+ }
+ break;
+
+ case FFI_TYPE_UINT8:
+ gprvalue = **p_argv.uc;
+ goto putgpr;
+ case FFI_TYPE_SINT8:
+ gprvalue = **p_argv.sc;
+ goto putgpr;
+ case FFI_TYPE_UINT16:
+ gprvalue = **p_argv.us;
+ goto putgpr;
+ case FFI_TYPE_SINT16:
+ gprvalue = **p_argv.ss;
+ goto putgpr;
+ case FFI_TYPE_UINT32:
+ gprvalue = **p_argv.ui;
+ goto putgpr;
+ case FFI_TYPE_INT:
+ case FFI_TYPE_SINT32:
+ gprvalue = **p_argv.si;
+ goto putgpr;
+
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_POINTER:
+ gprvalue = **p_argv.ul;
+ putgpr:
+ *next_arg.ul++ = gprvalue;
+ if (next_arg.ul == gpr_end.ul)
+ next_arg.ul = rest.ul;
+ break;
+ }
+ }
+
+ FFI_ASSERT (flags & FLAG_4_GPR_ARGUMENTS
+ || (next_arg.ul >= gpr_base.ul
+ && next_arg.ul <= gpr_base.ul + 4));
+}
+
+
+#if _CALL_ELF == 2
+#define MIN_CACHE_LINE_SIZE 8
+
+static void
+flush_icache (char *wraddr, char *xaddr, int size)
+{
+ int i;
+ for (i = 0; i < size; i += MIN_CACHE_LINE_SIZE)
+ __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;"
+ : : "r" (xaddr + i), "r" (wraddr + i) : "memory");
+ __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;" "sync;" "isync;"
+ : : "r"(xaddr + size - 1), "r"(wraddr + size - 1)
+ : "memory");
+}
+#endif
+
+
+ffi_status FFI_HIDDEN
+ffi_prep_closure_loc_linux64 (ffi_closure *closure,
+ ffi_cif *cif,
+ void (*fun) (ffi_cif *, void *, void **, void *),
+ void *user_data,
+ void *codeloc)
+{
+#if _CALL_ELF == 2
+ unsigned int *tramp = (unsigned int *) &closure->tramp[0];
+
+ if (cif->abi < FFI_LINUX || cif->abi >= FFI_LAST_ABI)
+ return FFI_BAD_ABI;
+
+ tramp[0] = 0xe96c0018; /* 0: ld 11,2f-0b(12) */
+ tramp[1] = 0xe98c0010; /* ld 12,1f-0b(12) */
+ tramp[2] = 0x7d8903a6; /* mtctr 12 */
+ tramp[3] = 0x4e800420; /* bctr */
+ /* 1: .quad function_addr */
+ /* 2: .quad context */
+ *(void **) &tramp[4] = (void *) ffi_closure_LINUX64;
+ *(void **) &tramp[6] = codeloc;
+ flush_icache ((char *) tramp, (char *) codeloc, 4 * 4);
+#else
+ void **tramp = (void **) &closure->tramp[0];
+
+ if (cif->abi < FFI_LINUX || cif->abi >= FFI_LAST_ABI)
+ return FFI_BAD_ABI;
+
+ /* Copy function address and TOC from ffi_closure_LINUX64 OPD. */
+ memcpy (&tramp[0], (void **) ffi_closure_LINUX64, sizeof (void *));
+ tramp[1] = codeloc;
+ memcpy (&tramp[2], (void **) ffi_closure_LINUX64 + 1, sizeof (void *));
+#endif
+
+ closure->cif = cif;
+ closure->fun = fun;
+ closure->user_data = user_data;
+
+ return FFI_OK;
+}
+
+
+int FFI_HIDDEN
+ffi_closure_helper_LINUX64 (ffi_cif *cif,
+ void (*fun) (ffi_cif *, void *, void **, void *),
+ void *user_data,
+ void *rvalue,
+ unsigned long *pst,
+ ffi_dblfl *pfr,
+ float128 *pvec)
+{
+ /* rvalue is the pointer to space for return value in closure assembly */
+ /* pst is the pointer to parameter save area
+ (r3-r10 are stored into its first 8 slots by ffi_closure_LINUX64) */
+ /* pfr is the pointer to where f1-f13 are stored in ffi_closure_LINUX64 */
+ /* pvec is the pointer to where v2-v13 are stored in ffi_closure_LINUX64 */
+
+ void **avalue;
+ ffi_type **arg_types;
+ unsigned long i, avn, nfixedargs;
+ ffi_dblfl *end_pfr = pfr + NUM_FPR_ARG_REGISTERS64;
+ float128 *end_pvec = pvec + NUM_VEC_ARG_REGISTERS64;
+ unsigned long align;
+
+ avalue = alloca (cif->nargs * sizeof (void *));
+
+ /* Copy the caller's structure return value address so that the
+ closure returns the data directly to the caller. */
+ if (cif->rtype->type == FFI_TYPE_STRUCT
+ && (cif->flags & FLAG_RETURNS_SMST) == 0)
+ {
+ rvalue = (void *) *pst;
+ pst++;
+ }
+
+ i = 0;
+ avn = cif->nargs;
+#if _CALL_ELF != 2
+ nfixedargs = (unsigned) -1;
+ if ((cif->flags & FLAG_COMPAT) == 0)
+#endif
+ nfixedargs = cif->nfixedargs;
+ arg_types = cif->arg_types;
+
+ /* Grab the addresses of the arguments from the stack frame. */
+ while (i < avn)
+ {
+ unsigned int elt, elnum;
+
+ switch (arg_types[i]->type)
+ {
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT8:
+#ifndef __LITTLE_ENDIAN__
+ avalue[i] = (char *) pst + 7;
+ pst++;
+ break;
+#endif
+
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT16:
+#ifndef __LITTLE_ENDIAN__
+ avalue[i] = (char *) pst + 6;
+ pst++;
+ break;
+#endif
+
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT32:
+#ifndef __LITTLE_ENDIAN__
+ avalue[i] = (char *) pst + 4;
+ pst++;
+ break;
+#endif
+
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_POINTER:
+ avalue[i] = pst;
+ pst++;
+ break;
+
+ case FFI_TYPE_STRUCT:
+ if ((cif->abi & FFI_LINUX_STRUCT_ALIGN) != 0)
+ {
+ align = arg_types[i]->alignment;
+ if (align > 16)
+ align = 16;
+ if (align > 1)
+ pst = (unsigned long *) FFI_ALIGN ((size_t) pst, align);
+ }
+ elt = discover_homogeneous_aggregate (cif->abi, arg_types[i], &elnum);
+ if (elt)
+ {
+#if _CALL_ELF == 2
+ union {
+ void *v;
+ unsigned long *ul;
+ float *f;
+ double *d;
+ float128 *f128;
+ size_t p;
+ } to, from;
+
+ /* Repackage the aggregate from its parts. The
+ aggregate size is not greater than the space taken by
+ the registers so store back to the register/parameter
+ save arrays. */
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ if (elt == FFI_TYPE_LONGDOUBLE &&
+ (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
+ {
+ if (pvec + elnum <= end_pvec)
+ to.v = pvec;
+ else
+ to.v = pst;
+ }
+ else
+#endif
+ if (pfr + elnum <= end_pfr)
+ to.v = pfr;
+ else
+ to.v = pst;
+
+ avalue[i] = to.v;
+ from.ul = pst;
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ if (elt == FFI_TYPE_LONGDOUBLE &&
+ (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
+ {
+ do
+ {
+ if (pvec < end_pvec && i < nfixedargs)
+ *to.f128 = *pvec++;
+ else
+ *to.f128 = *from.f128;
+ to.f128++;
+ from.f128++;
+ }
+ while (--elnum != 0);
+ }
+ else
+#endif
+ if (elt == FFI_TYPE_FLOAT)
+ {
+ do
+ {
+ if (pfr < end_pfr && i < nfixedargs)
+ {
+ *to.f = (float) pfr->d;
+ pfr++;
+ }
+ else
+ *to.f = *from.f;
+ to.f++;
+ from.f++;
+ }
+ while (--elnum != 0);
+ }
+ else
+ {
+ do
+ {
+ if (pfr < end_pfr && i < nfixedargs)
+ {
+ *to.d = pfr->d;
+ pfr++;
+ }
+ else
+ *to.d = *from.d;
+ to.d++;
+ from.d++;
+ }
+ while (--elnum != 0);
+ }
+#else
+ if (elt == FFI_TYPE_FLOAT)
+ goto do_float;
+ else
+ goto do_double;
+#endif
+ }
+ else
+ {
+#ifndef __LITTLE_ENDIAN__
+ /* Structures with size less than eight bytes are passed
+ left-padded. */
+ if (arg_types[i]->size < 8)
+ avalue[i] = (char *) pst + 8 - arg_types[i]->size;
+ else
+#endif
+ avalue[i] = pst;
+ }
+ pst += (arg_types[i]->size + 7) / 8;
+ break;
+
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0)
+ {
+ if (((unsigned long) pst & 0xF) != 0)
+ ++pst;
+ if (pvec < end_pvec && i < nfixedargs)
+ avalue[i] = pvec++;
+ else
+ avalue[i] = pst;
+ pst += 2;
+ break;
+ }
+ else if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0)
+ {
+ if (pfr + 1 < end_pfr && i + 1 < nfixedargs)
+ {
+ avalue[i] = pfr;
+ pfr += 2;
+ }
+ else
+ {
+ if (pfr < end_pfr && i < nfixedargs)
+ {
+ /* Passed partly in f13 and partly on the stack.
+ Move it all to the stack. */
+ *pst = *(unsigned long *) pfr;
+ pfr++;
+ }
+ avalue[i] = pst;
+ }
+ pst += 2;
+ break;
+ }
+ /* Fall through. */
+#endif
+ case FFI_TYPE_DOUBLE:
+#if _CALL_ELF != 2
+ do_double:
+#endif
+ /* On the outgoing stack all values are aligned to 8 */
+ /* there are 13 64bit floating point registers */
+
+ if (pfr < end_pfr && i < nfixedargs)
+ {
+ avalue[i] = pfr;
+ pfr++;
+ }
+ else
+ avalue[i] = pst;
+ pst++;
+ break;
+
+ case FFI_TYPE_FLOAT:
+#if _CALL_ELF != 2
+ do_float:
+#endif
+ if (pfr < end_pfr && i < nfixedargs)
+ {
+ /* Float values are stored as doubles in the
+ ffi_closure_LINUX64 code. Fix them here. */
+ pfr->f = (float) pfr->d;
+ avalue[i] = pfr;
+ pfr++;
+ }
+ else
+ {
+#ifndef __LITTLE_ENDIAN__
+ avalue[i] = (char *) pst + 4;
+#else
+ avalue[i] = pst;
+#endif
+ }
+ pst++;
+ break;
+
+ default:
+ FFI_ASSERT (0);
+ }
+
+ i++;
+ }
+
+ (*fun) (cif, rvalue, avalue, user_data);
+
+ /* Tell ffi_closure_LINUX64 how to perform return type promotions. */
+ if ((cif->flags & FLAG_RETURNS_SMST) != 0)
+ {
+ if ((cif->flags & (FLAG_RETURNS_FP | FLAG_RETURNS_VEC)) == 0)
+ return FFI_V2_TYPE_SMALL_STRUCT + cif->rtype->size - 1;
+ else if ((cif->flags & FLAG_RETURNS_VEC) != 0)
+ return FFI_V2_TYPE_VECTOR_HOMOG;
+ else if ((cif->flags & FLAG_RETURNS_64BITS) != 0)
+ return FFI_V2_TYPE_DOUBLE_HOMOG;
+ else
+ return FFI_V2_TYPE_FLOAT_HOMOG;
+ }
+ if ((cif->flags & FLAG_RETURNS_VEC) != 0)
+ return FFI_V2_TYPE_VECTOR;
+ return cif->rtype->type;
+}
+#endif
diff --git a/contrib/restricted/libffi/src/powerpc/ffi_powerpc.h b/contrib/restricted/libffi/src/powerpc/ffi_powerpc.h
index 7956cf81d0..5ee2a7095a 100644
--- a/contrib/restricted/libffi/src/powerpc/ffi_powerpc.h
+++ b/contrib/restricted/libffi/src/powerpc/ffi_powerpc.h
@@ -1,105 +1,105 @@
-/* -----------------------------------------------------------------------
- ffi_powerpc.h - Copyright (C) 2013 IBM
- Copyright (C) 2011 Anthony Green
- Copyright (C) 2011 Kyle Moffett
- Copyright (C) 2008 Red Hat, Inc
- Copyright (C) 2007, 2008 Free Software Foundation, Inc
- Copyright (c) 1998 Geoffrey Keating
-
- PowerPC Foreign Function Interface
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-enum {
- /* The assembly depends on these exact flags. */
- /* These go in cr7 */
- FLAG_RETURNS_SMST = 1 << (31-31), /* Used for FFI_SYSV small structs. */
- FLAG_RETURNS_NOTHING = 1 << (31-30),
- FLAG_RETURNS_FP = 1 << (31-29),
- FLAG_RETURNS_VEC = 1 << (31-28),
-
- /* These go in cr6 */
- FLAG_RETURNS_64BITS = 1 << (31-27),
- FLAG_RETURNS_128BITS = 1 << (31-26),
-
- FLAG_COMPAT = 1 << (31- 8), /* Not used by assembly */
-
- /* These go in cr1 */
- FLAG_ARG_NEEDS_COPY = 1 << (31- 7), /* Used by sysv code */
- FLAG_ARG_NEEDS_PSAVE = FLAG_ARG_NEEDS_COPY, /* Used by linux64 code */
- FLAG_FP_ARGUMENTS = 1 << (31- 6), /* cr1.eq; specified by ABI */
- FLAG_4_GPR_ARGUMENTS = 1 << (31- 5),
- FLAG_RETVAL_REFERENCE = 1 << (31- 4),
- FLAG_VEC_ARGUMENTS = 1 << (31- 3),
-};
-
-typedef union
-{
- float f;
- double d;
-} ffi_dblfl;
-
-#if defined(__FLOAT128_TYPE__)
-typedef _Float128 float128;
-#elif defined(__FLOAT128__)
-typedef __float128 float128;
-#else
-typedef __int128 float128;
-#endif
-
-void FFI_HIDDEN ffi_closure_SYSV (void);
-void FFI_HIDDEN ffi_go_closure_sysv (void);
-void FFI_HIDDEN ffi_call_SYSV(extended_cif *, void (*)(void), void *,
- unsigned, void *, int);
-
-void FFI_HIDDEN ffi_prep_types_sysv (ffi_abi);
-ffi_status FFI_HIDDEN ffi_prep_cif_sysv (ffi_cif *);
-ffi_status FFI_HIDDEN ffi_prep_closure_loc_sysv (ffi_closure *,
- ffi_cif *,
- void (*) (ffi_cif *, void *,
- void **, void *),
- void *, void *);
-int FFI_HIDDEN ffi_closure_helper_SYSV (ffi_cif *,
- void (*) (ffi_cif *, void *,
- void **, void *),
- void *, void *, unsigned long *,
- ffi_dblfl *, unsigned long *);
-
-void FFI_HIDDEN ffi_call_LINUX64(extended_cif *, void (*) (void), void *,
- unsigned long, void *, long);
-void FFI_HIDDEN ffi_closure_LINUX64 (void);
-void FFI_HIDDEN ffi_go_closure_linux64 (void);
-
-void FFI_HIDDEN ffi_prep_types_linux64 (ffi_abi);
-ffi_status FFI_HIDDEN ffi_prep_cif_linux64 (ffi_cif *);
-ffi_status FFI_HIDDEN ffi_prep_cif_linux64_var (ffi_cif *, unsigned int,
- unsigned int);
-void FFI_HIDDEN ffi_prep_args64 (extended_cif *, unsigned long *const);
-ffi_status FFI_HIDDEN ffi_prep_closure_loc_linux64 (ffi_closure *, ffi_cif *,
- void (*) (ffi_cif *, void *,
- void **, void *),
- void *, void *);
-int FFI_HIDDEN ffi_closure_helper_LINUX64 (ffi_cif *,
- void (*) (ffi_cif *, void *,
- void **, void *),
- void *, void *,
- unsigned long *, ffi_dblfl *,
- float128 *);
+/* -----------------------------------------------------------------------
+ ffi_powerpc.h - Copyright (C) 2013 IBM
+ Copyright (C) 2011 Anthony Green
+ Copyright (C) 2011 Kyle Moffett
+ Copyright (C) 2008 Red Hat, Inc
+ Copyright (C) 2007, 2008 Free Software Foundation, Inc
+ Copyright (c) 1998 Geoffrey Keating
+
+ PowerPC Foreign Function Interface
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+enum {
+ /* The assembly depends on these exact flags. */
+ /* These go in cr7 */
+ FLAG_RETURNS_SMST = 1 << (31-31), /* Used for FFI_SYSV small structs. */
+ FLAG_RETURNS_NOTHING = 1 << (31-30),
+ FLAG_RETURNS_FP = 1 << (31-29),
+ FLAG_RETURNS_VEC = 1 << (31-28),
+
+ /* These go in cr6 */
+ FLAG_RETURNS_64BITS = 1 << (31-27),
+ FLAG_RETURNS_128BITS = 1 << (31-26),
+
+ FLAG_COMPAT = 1 << (31- 8), /* Not used by assembly */
+
+ /* These go in cr1 */
+ FLAG_ARG_NEEDS_COPY = 1 << (31- 7), /* Used by sysv code */
+ FLAG_ARG_NEEDS_PSAVE = FLAG_ARG_NEEDS_COPY, /* Used by linux64 code */
+ FLAG_FP_ARGUMENTS = 1 << (31- 6), /* cr1.eq; specified by ABI */
+ FLAG_4_GPR_ARGUMENTS = 1 << (31- 5),
+ FLAG_RETVAL_REFERENCE = 1 << (31- 4),
+ FLAG_VEC_ARGUMENTS = 1 << (31- 3),
+};
+
+typedef union
+{
+ float f;
+ double d;
+} ffi_dblfl;
+
+#if defined(__FLOAT128_TYPE__)
+typedef _Float128 float128;
+#elif defined(__FLOAT128__)
+typedef __float128 float128;
+#else
+typedef __int128 float128;
+#endif
+
+void FFI_HIDDEN ffi_closure_SYSV (void);
+void FFI_HIDDEN ffi_go_closure_sysv (void);
+void FFI_HIDDEN ffi_call_SYSV(extended_cif *, void (*)(void), void *,
+ unsigned, void *, int);
+
+void FFI_HIDDEN ffi_prep_types_sysv (ffi_abi);
+ffi_status FFI_HIDDEN ffi_prep_cif_sysv (ffi_cif *);
+ffi_status FFI_HIDDEN ffi_prep_closure_loc_sysv (ffi_closure *,
+ ffi_cif *,
+ void (*) (ffi_cif *, void *,
+ void **, void *),
+ void *, void *);
+int FFI_HIDDEN ffi_closure_helper_SYSV (ffi_cif *,
+ void (*) (ffi_cif *, void *,
+ void **, void *),
+ void *, void *, unsigned long *,
+ ffi_dblfl *, unsigned long *);
+
+void FFI_HIDDEN ffi_call_LINUX64(extended_cif *, void (*) (void), void *,
+ unsigned long, void *, long);
+void FFI_HIDDEN ffi_closure_LINUX64 (void);
+void FFI_HIDDEN ffi_go_closure_linux64 (void);
+
+void FFI_HIDDEN ffi_prep_types_linux64 (ffi_abi);
+ffi_status FFI_HIDDEN ffi_prep_cif_linux64 (ffi_cif *);
+ffi_status FFI_HIDDEN ffi_prep_cif_linux64_var (ffi_cif *, unsigned int,
+ unsigned int);
+void FFI_HIDDEN ffi_prep_args64 (extended_cif *, unsigned long *const);
+ffi_status FFI_HIDDEN ffi_prep_closure_loc_linux64 (ffi_closure *, ffi_cif *,
+ void (*) (ffi_cif *, void *,
+ void **, void *),
+ void *, void *);
+int FFI_HIDDEN ffi_closure_helper_LINUX64 (ffi_cif *,
+ void (*) (ffi_cif *, void *,
+ void **, void *),
+ void *, void *,
+ unsigned long *, ffi_dblfl *,
+ float128 *);
diff --git a/contrib/restricted/libffi/src/powerpc/ffi_sysv.c b/contrib/restricted/libffi/src/powerpc/ffi_sysv.c
index d641d929e3..4078e75116 100644
--- a/contrib/restricted/libffi/src/powerpc/ffi_sysv.c
+++ b/contrib/restricted/libffi/src/powerpc/ffi_sysv.c
@@ -1,923 +1,923 @@
-/* -----------------------------------------------------------------------
- ffi_sysv.c - Copyright (C) 2013 IBM
- Copyright (C) 2011 Anthony Green
- Copyright (C) 2011 Kyle Moffett
- Copyright (C) 2008 Red Hat, Inc
- Copyright (C) 2007, 2008 Free Software Foundation, Inc
- Copyright (c) 1998 Geoffrey Keating
-
- PowerPC Foreign Function Interface
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#include "ffi.h"
-
-#ifndef POWERPC64
-#include "ffi_common.h"
-#include "ffi_powerpc.h"
-
-
-/* About the SYSV ABI. */
-#define ASM_NEEDS_REGISTERS 6
-#define NUM_GPR_ARG_REGISTERS 8
-#define NUM_FPR_ARG_REGISTERS 8
-
-
-#if HAVE_LONG_DOUBLE_VARIANT && FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
-/* Adjust size of ffi_type_longdouble. */
-void FFI_HIDDEN
-ffi_prep_types_sysv (ffi_abi abi)
-{
- if ((abi & (FFI_SYSV | FFI_SYSV_LONG_DOUBLE_128)) == FFI_SYSV)
- {
- ffi_type_longdouble.size = 8;
- ffi_type_longdouble.alignment = 8;
- }
- else
- {
- ffi_type_longdouble.size = 16;
- ffi_type_longdouble.alignment = 16;
- }
-}
-#endif
-
-/* Transform long double, double and float to other types as per abi. */
-static int
-translate_float (int abi, int type)
-{
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- if (type == FFI_TYPE_LONGDOUBLE
- && (abi & FFI_SYSV_LONG_DOUBLE_128) == 0)
- type = FFI_TYPE_DOUBLE;
-#endif
- if ((abi & FFI_SYSV_SOFT_FLOAT) != 0)
- {
- if (type == FFI_TYPE_FLOAT)
- type = FFI_TYPE_UINT32;
- else if (type == FFI_TYPE_DOUBLE)
- type = FFI_TYPE_UINT64;
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- else if (type == FFI_TYPE_LONGDOUBLE)
- type = FFI_TYPE_UINT128;
- }
- else if ((abi & FFI_SYSV_IBM_LONG_DOUBLE) == 0)
- {
- if (type == FFI_TYPE_LONGDOUBLE)
- type = FFI_TYPE_STRUCT;
-#endif
- }
- return type;
-}
-
-/* Perform machine dependent cif processing */
-static ffi_status
-ffi_prep_cif_sysv_core (ffi_cif *cif)
-{
- ffi_type **ptr;
- unsigned bytes;
- unsigned i, fpr_count = 0, gpr_count = 0, stack_count = 0;
- unsigned flags = cif->flags;
- unsigned struct_copy_size = 0;
- unsigned type = cif->rtype->type;
- unsigned size = cif->rtype->size;
-
- /* The machine-independent calculation of cif->bytes doesn't work
- for us. Redo the calculation. */
-
- /* Space for the frame pointer, callee's LR, and the asm's temp regs. */
- bytes = (2 + ASM_NEEDS_REGISTERS) * sizeof (int);
-
- /* Space for the GPR registers. */
- bytes += NUM_GPR_ARG_REGISTERS * sizeof (int);
-
- /* Return value handling. The rules for SYSV are as follows:
- - 32-bit (or less) integer values are returned in gpr3;
- - Structures of size <= 4 bytes also returned in gpr3;
- - 64-bit integer values and structures between 5 and 8 bytes are returned
- in gpr3 and gpr4;
- - Larger structures are allocated space and a pointer is passed as
- the first argument.
- - Single/double FP values are returned in fpr1;
- - long doubles (if not equivalent to double) are returned in
- fpr1,fpr2 for Linux and as for large structs for SysV. */
-
- type = translate_float (cif->abi, type);
-
- switch (type)
- {
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- flags |= FLAG_RETURNS_128BITS;
- /* Fall through. */
-#endif
- case FFI_TYPE_DOUBLE:
- flags |= FLAG_RETURNS_64BITS;
- /* Fall through. */
- case FFI_TYPE_FLOAT:
- flags |= FLAG_RETURNS_FP;
-#ifdef __NO_FPRS__
- return FFI_BAD_ABI;
-#endif
- break;
-
- case FFI_TYPE_UINT128:
- flags |= FLAG_RETURNS_128BITS;
- /* Fall through. */
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- flags |= FLAG_RETURNS_64BITS;
- break;
-
- case FFI_TYPE_STRUCT:
- /* The final SYSV ABI says that structures smaller or equal 8 bytes
- are returned in r3/r4. A draft ABI used by linux instead
- returns them in memory. */
- if ((cif->abi & FFI_SYSV_STRUCT_RET) != 0 && size <= 8)
- {
- flags |= FLAG_RETURNS_SMST;
- break;
- }
- gpr_count++;
- flags |= FLAG_RETVAL_REFERENCE;
- /* Fall through. */
- case FFI_TYPE_VOID:
- flags |= FLAG_RETURNS_NOTHING;
- break;
-
- default:
- /* Returns 32-bit integer, or similar. Nothing to do here. */
- break;
- }
-
- /* The first NUM_GPR_ARG_REGISTERS words of integer arguments, and the
- first NUM_FPR_ARG_REGISTERS fp arguments, go in registers; the rest
- goes on the stack. Structures and long doubles (if not equivalent
- to double) are passed as a pointer to a copy of the structure.
- Stuff on the stack needs to keep proper alignment. */
- for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++)
- {
- unsigned short typenum = (*ptr)->type;
-
- typenum = translate_float (cif->abi, typenum);
-
- switch (typenum)
- {
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- if (fpr_count >= NUM_FPR_ARG_REGISTERS - 1)
- {
- fpr_count = NUM_FPR_ARG_REGISTERS;
- /* 8-byte align long doubles. */
- stack_count += stack_count & 1;
- stack_count += 4;
- }
- else
- fpr_count += 2;
-#ifdef __NO_FPRS__
- return FFI_BAD_ABI;
-#endif
- break;
-#endif
-
- case FFI_TYPE_DOUBLE:
- if (fpr_count >= NUM_FPR_ARG_REGISTERS)
- {
- /* 8-byte align doubles. */
- stack_count += stack_count & 1;
- stack_count += 2;
- }
- else
- fpr_count += 1;
-#ifdef __NO_FPRS__
- return FFI_BAD_ABI;
-#endif
- break;
-
- case FFI_TYPE_FLOAT:
- if (fpr_count >= NUM_FPR_ARG_REGISTERS)
- /* Yes, we don't follow the ABI, but neither does gcc. */
- stack_count += 1;
- else
- fpr_count += 1;
-#ifdef __NO_FPRS__
- return FFI_BAD_ABI;
-#endif
- break;
-
- case FFI_TYPE_UINT128:
- /* A long double in FFI_LINUX_SOFT_FLOAT can use only a set
- of four consecutive gprs. If we do not have enough, we
- have to adjust the gpr_count value. */
- if (gpr_count >= NUM_GPR_ARG_REGISTERS - 3)
- gpr_count = NUM_GPR_ARG_REGISTERS;
- if (gpr_count >= NUM_GPR_ARG_REGISTERS)
- stack_count += 4;
- else
- gpr_count += 4;
- break;
-
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- /* 'long long' arguments are passed as two words, but
- either both words must fit in registers or both go
- on the stack. If they go on the stack, they must
- be 8-byte-aligned.
-
- Also, only certain register pairs can be used for
- passing long long int -- specifically (r3,r4), (r5,r6),
- (r7,r8), (r9,r10). */
- gpr_count += gpr_count & 1;
- if (gpr_count >= NUM_GPR_ARG_REGISTERS)
- {
- stack_count += stack_count & 1;
- stack_count += 2;
- }
- else
- gpr_count += 2;
- break;
-
- case FFI_TYPE_STRUCT:
- /* We must allocate space for a copy of these to enforce
- pass-by-value. Pad the space up to a multiple of 16
- bytes (the maximum alignment required for anything under
- the SYSV ABI). */
- struct_copy_size += ((*ptr)->size + 15) & ~0xF;
- /* Fall through (allocate space for the pointer). */
-
- case FFI_TYPE_POINTER:
- case FFI_TYPE_INT:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT16:
- case FFI_TYPE_SINT16:
- case FFI_TYPE_UINT8:
- case FFI_TYPE_SINT8:
- /* Everything else is passed as a 4-byte word in a GPR, either
- the object itself or a pointer to it. */
- if (gpr_count >= NUM_GPR_ARG_REGISTERS)
- stack_count += 1;
- else
- gpr_count += 1;
- break;
-
- default:
- FFI_ASSERT (0);
- }
- }
-
- if (fpr_count != 0)
- flags |= FLAG_FP_ARGUMENTS;
- if (gpr_count > 4)
- flags |= FLAG_4_GPR_ARGUMENTS;
- if (struct_copy_size != 0)
- flags |= FLAG_ARG_NEEDS_COPY;
-
- /* Space for the FPR registers, if needed. */
- if (fpr_count != 0)
- bytes += NUM_FPR_ARG_REGISTERS * sizeof (double);
-
- /* Stack space. */
- bytes += stack_count * sizeof (int);
-
- /* The stack space allocated needs to be a multiple of 16 bytes. */
- bytes = (bytes + 15) & ~0xF;
-
- /* Add in the space for the copied structures. */
- bytes += struct_copy_size;
-
- cif->flags = flags;
- cif->bytes = bytes;
-
- return FFI_OK;
-}
-
-ffi_status FFI_HIDDEN
-ffi_prep_cif_sysv (ffi_cif *cif)
-{
- if ((cif->abi & FFI_SYSV) == 0)
- {
- /* This call is from old code. Translate to new ABI values. */
- cif->flags |= FLAG_COMPAT;
- switch (cif->abi)
- {
- default:
- return FFI_BAD_ABI;
-
- case FFI_COMPAT_SYSV:
- cif->abi = FFI_SYSV | FFI_SYSV_STRUCT_RET | FFI_SYSV_LONG_DOUBLE_128;
- break;
-
- case FFI_COMPAT_GCC_SYSV:
- cif->abi = FFI_SYSV | FFI_SYSV_LONG_DOUBLE_128;
- break;
-
- case FFI_COMPAT_LINUX:
- cif->abi = (FFI_SYSV | FFI_SYSV_IBM_LONG_DOUBLE
- | FFI_SYSV_LONG_DOUBLE_128);
- break;
-
- case FFI_COMPAT_LINUX_SOFT_FLOAT:
- cif->abi = (FFI_SYSV | FFI_SYSV_SOFT_FLOAT | FFI_SYSV_IBM_LONG_DOUBLE
- | FFI_SYSV_LONG_DOUBLE_128);
- break;
- }
- }
- return ffi_prep_cif_sysv_core (cif);
-}
-
-/* ffi_prep_args_SYSV is called by the assembly routine once stack space
- has been allocated for the function's arguments.
-
- The stack layout we want looks like this:
-
- | Return address from ffi_call_SYSV 4bytes | higher addresses
- |--------------------------------------------|
- | Previous backchain pointer 4 | stack pointer here
- |--------------------------------------------|<+ <<< on entry to
- | Saved r28-r31 4*4 | | ffi_call_SYSV
- |--------------------------------------------| |
- | GPR registers r3-r10 8*4 | | ffi_call_SYSV
- |--------------------------------------------| |
- | FPR registers f1-f8 (optional) 8*8 | |
- |--------------------------------------------| | stack |
- | Space for copied structures | | grows |
- |--------------------------------------------| | down V
- | Parameters that didn't fit in registers | |
- |--------------------------------------------| | lower addresses
- | Space for callee's LR 4 | |
- |--------------------------------------------| | stack pointer here
- | Current backchain pointer 4 |-/ during
- |--------------------------------------------| <<< ffi_call_SYSV
-
-*/
-
-void FFI_HIDDEN
-ffi_prep_args_SYSV (extended_cif *ecif, unsigned *const stack)
-{
- const unsigned bytes = ecif->cif->bytes;
- const unsigned flags = ecif->cif->flags;
-
- typedef union
- {
- char *c;
- unsigned *u;
- long long *ll;
- float *f;
- double *d;
- } valp;
-
- /* 'stacktop' points at the previous backchain pointer. */
- valp stacktop;
-
- /* 'gpr_base' points at the space for gpr3, and grows upwards as
- we use GPR registers. */
- valp gpr_base;
- valp gpr_end;
-
-#ifndef __NO_FPRS__
- /* 'fpr_base' points at the space for fpr1, and grows upwards as
- we use FPR registers. */
- valp fpr_base;
- valp fpr_end;
-#endif
-
- /* 'copy_space' grows down as we put structures in it. It should
- stay 16-byte aligned. */
- valp copy_space;
-
- /* 'next_arg' grows up as we put parameters in it. */
- valp next_arg;
-
- int i;
- ffi_type **ptr;
-#ifndef __NO_FPRS__
- double double_tmp;
-#endif
- union
- {
- void **v;
- char **c;
- signed char **sc;
- unsigned char **uc;
- signed short **ss;
- unsigned short **us;
- unsigned int **ui;
- long long **ll;
- float **f;
- double **d;
- } p_argv;
- size_t struct_copy_size;
- unsigned gprvalue;
-
- stacktop.c = (char *) stack + bytes;
- gpr_end.u = stacktop.u - ASM_NEEDS_REGISTERS;
- gpr_base.u = gpr_end.u - NUM_GPR_ARG_REGISTERS;
-#ifndef __NO_FPRS__
- fpr_end.d = gpr_base.d;
- fpr_base.d = fpr_end.d - NUM_FPR_ARG_REGISTERS;
- copy_space.c = ((flags & FLAG_FP_ARGUMENTS) ? fpr_base.c : gpr_base.c);
-#else
- copy_space.c = gpr_base.c;
-#endif
- next_arg.u = stack + 2;
-
- /* Check that everything starts aligned properly. */
- FFI_ASSERT (((unsigned long) (char *) stack & 0xF) == 0);
- FFI_ASSERT (((unsigned long) copy_space.c & 0xF) == 0);
- FFI_ASSERT (((unsigned long) stacktop.c & 0xF) == 0);
- FFI_ASSERT ((bytes & 0xF) == 0);
- FFI_ASSERT (copy_space.c >= next_arg.c);
-
- /* Deal with return values that are actually pass-by-reference. */
- if (flags & FLAG_RETVAL_REFERENCE)
- *gpr_base.u++ = (unsigned) (char *) ecif->rvalue;
-
- /* Now for the arguments. */
- p_argv.v = ecif->avalue;
- for (ptr = ecif->cif->arg_types, i = ecif->cif->nargs;
- i > 0;
- i--, ptr++, p_argv.v++)
- {
- unsigned int typenum = (*ptr)->type;
-
- typenum = translate_float (ecif->cif->abi, typenum);
-
- /* Now test the translated value */
- switch (typenum)
- {
-#ifndef __NO_FPRS__
-# if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- double_tmp = (*p_argv.d)[0];
-
- if (fpr_base.d >= fpr_end.d - 1)
- {
- fpr_base.d = fpr_end.d;
- if (((next_arg.u - stack) & 1) != 0)
- next_arg.u += 1;
- *next_arg.d = double_tmp;
- next_arg.u += 2;
- double_tmp = (*p_argv.d)[1];
- *next_arg.d = double_tmp;
- next_arg.u += 2;
- }
- else
- {
- *fpr_base.d++ = double_tmp;
- double_tmp = (*p_argv.d)[1];
- *fpr_base.d++ = double_tmp;
- }
- FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
- break;
-# endif
- case FFI_TYPE_DOUBLE:
- double_tmp = **p_argv.d;
-
- if (fpr_base.d >= fpr_end.d)
- {
- if (((next_arg.u - stack) & 1) != 0)
- next_arg.u += 1;
- *next_arg.d = double_tmp;
- next_arg.u += 2;
- }
- else
- *fpr_base.d++ = double_tmp;
- FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
- break;
-
- case FFI_TYPE_FLOAT:
- double_tmp = **p_argv.f;
- if (fpr_base.d >= fpr_end.d)
- {
- *next_arg.f = (float) double_tmp;
- next_arg.u += 1;
- }
- else
- *fpr_base.d++ = double_tmp;
- FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
- break;
-#endif /* have FPRs */
-
- case FFI_TYPE_UINT128:
- /* The soft float ABI for long doubles works like this, a long double
- is passed in four consecutive GPRs if available. A maximum of 2
- long doubles can be passed in gprs. If we do not have 4 GPRs
- left, the long double is passed on the stack, 4-byte aligned. */
- if (gpr_base.u >= gpr_end.u - 3)
- {
- unsigned int ii;
- gpr_base.u = gpr_end.u;
- for (ii = 0; ii < 4; ii++)
- {
- unsigned int int_tmp = (*p_argv.ui)[ii];
- *next_arg.u++ = int_tmp;
- }
- }
- else
- {
- unsigned int ii;
- for (ii = 0; ii < 4; ii++)
- {
- unsigned int int_tmp = (*p_argv.ui)[ii];
- *gpr_base.u++ = int_tmp;
- }
- }
- break;
-
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- if (gpr_base.u >= gpr_end.u - 1)
- {
- gpr_base.u = gpr_end.u;
- if (((next_arg.u - stack) & 1) != 0)
- next_arg.u++;
- *next_arg.ll = **p_argv.ll;
- next_arg.u += 2;
- }
- else
- {
- /* The abi states only certain register pairs can be
- used for passing long long int specifically (r3,r4),
- (r5,r6), (r7,r8), (r9,r10). If next arg is long long
- but not correct starting register of pair then skip
- until the proper starting register. */
- if (((gpr_end.u - gpr_base.u) & 1) != 0)
- gpr_base.u++;
- *gpr_base.ll++ = **p_argv.ll;
- }
- break;
-
- case FFI_TYPE_STRUCT:
- struct_copy_size = ((*ptr)->size + 15) & ~0xF;
- copy_space.c -= struct_copy_size;
- memcpy (copy_space.c, *p_argv.c, (*ptr)->size);
-
- gprvalue = (unsigned long) copy_space.c;
-
- FFI_ASSERT (copy_space.c > next_arg.c);
- FFI_ASSERT (flags & FLAG_ARG_NEEDS_COPY);
- goto putgpr;
-
- case FFI_TYPE_UINT8:
- gprvalue = **p_argv.uc;
- goto putgpr;
- case FFI_TYPE_SINT8:
- gprvalue = **p_argv.sc;
- goto putgpr;
- case FFI_TYPE_UINT16:
- gprvalue = **p_argv.us;
- goto putgpr;
- case FFI_TYPE_SINT16:
- gprvalue = **p_argv.ss;
- goto putgpr;
-
- case FFI_TYPE_INT:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_SINT32:
- case FFI_TYPE_POINTER:
-
- gprvalue = **p_argv.ui;
-
- putgpr:
- if (gpr_base.u >= gpr_end.u)
- *next_arg.u++ = gprvalue;
- else
- *gpr_base.u++ = gprvalue;
- break;
- }
- }
-
- /* Check that we didn't overrun the stack... */
- FFI_ASSERT (copy_space.c >= next_arg.c);
- FFI_ASSERT (gpr_base.u <= gpr_end.u);
-#ifndef __NO_FPRS__
- FFI_ASSERT (fpr_base.u <= fpr_end.u);
-#endif
- FFI_ASSERT (((flags & FLAG_4_GPR_ARGUMENTS) != 0)
- == (gpr_end.u - gpr_base.u < 4));
-}
-
-#define MIN_CACHE_LINE_SIZE 8
-
-static void
-flush_icache (char *wraddr, char *xaddr, int size)
-{
- int i;
- for (i = 0; i < size; i += MIN_CACHE_LINE_SIZE)
- __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;"
- : : "r" (xaddr + i), "r" (wraddr + i) : "memory");
- __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;" "sync;" "isync;"
- : : "r"(xaddr + size - 1), "r"(wraddr + size - 1)
- : "memory");
-}
-
-ffi_status FFI_HIDDEN
-ffi_prep_closure_loc_sysv (ffi_closure *closure,
- ffi_cif *cif,
- void (*fun) (ffi_cif *, void *, void **, void *),
- void *user_data,
- void *codeloc)
-{
- unsigned int *tramp;
-
- if (cif->abi < FFI_SYSV || cif->abi >= FFI_LAST_ABI)
- return FFI_BAD_ABI;
-
- tramp = (unsigned int *) &closure->tramp[0];
- tramp[0] = 0x7c0802a6; /* mflr r0 */
- tramp[1] = 0x429f0005; /* bcl 20,31,.+4 */
- tramp[2] = 0x7d6802a6; /* mflr r11 */
- tramp[3] = 0x7c0803a6; /* mtlr r0 */
- tramp[4] = 0x800b0018; /* lwz r0,24(r11) */
- tramp[5] = 0x816b001c; /* lwz r11,28(r11) */
- tramp[6] = 0x7c0903a6; /* mtctr r0 */
- tramp[7] = 0x4e800420; /* bctr */
- *(void **) &tramp[8] = (void *) ffi_closure_SYSV; /* function */
- *(void **) &tramp[9] = codeloc; /* context */
-
- /* Flush the icache. */
- flush_icache ((char *)tramp, (char *)codeloc, 8 * 4);
-
- closure->cif = cif;
- closure->fun = fun;
- closure->user_data = user_data;
-
- return FFI_OK;
-}
-
-/* Basically the trampoline invokes ffi_closure_SYSV, and on
- entry, r11 holds the address of the closure.
- After storing the registers that could possibly contain
- parameters to be passed into the stack frame and setting
- up space for a return value, ffi_closure_SYSV invokes the
- following helper function to do most of the work. */
-
-int
-ffi_closure_helper_SYSV (ffi_cif *cif,
- void (*fun) (ffi_cif *, void *, void **, void *),
- void *user_data,
- void *rvalue,
- unsigned long *pgr,
- ffi_dblfl *pfr,
- unsigned long *pst)
-{
- /* rvalue is the pointer to space for return value in closure assembly */
- /* pgr is the pointer to where r3-r10 are stored in ffi_closure_SYSV */
- /* pfr is the pointer to where f1-f8 are stored in ffi_closure_SYSV */
- /* pst is the pointer to outgoing parameter stack in original caller */
-
- void ** avalue;
- ffi_type ** arg_types;
- long i, avn;
-#ifndef __NO_FPRS__
- long nf = 0; /* number of floating registers already used */
-#endif
- long ng = 0; /* number of general registers already used */
-
- unsigned size = cif->rtype->size;
- unsigned short rtypenum = cif->rtype->type;
-
- avalue = alloca (cif->nargs * sizeof (void *));
-
- /* First translate for softfloat/nonlinux */
- rtypenum = translate_float (cif->abi, rtypenum);
-
- /* Copy the caller's structure return value address so that the closure
- returns the data directly to the caller.
- For FFI_SYSV the result is passed in r3/r4 if the struct size is less
- or equal 8 bytes. */
- if (rtypenum == FFI_TYPE_STRUCT
- && !((cif->abi & FFI_SYSV_STRUCT_RET) != 0 && size <= 8))
- {
- rvalue = (void *) *pgr;
- ng++;
- pgr++;
- }
-
- i = 0;
- avn = cif->nargs;
- arg_types = cif->arg_types;
-
- /* Grab the addresses of the arguments from the stack frame. */
- while (i < avn) {
- unsigned short typenum = arg_types[i]->type;
-
- /* We may need to handle some values depending on ABI. */
- typenum = translate_float (cif->abi, typenum);
-
- switch (typenum)
- {
-#ifndef __NO_FPRS__
- case FFI_TYPE_FLOAT:
- /* Unfortunately float values are stored as doubles
- in the ffi_closure_SYSV code (since we don't check
- the type in that routine). */
- if (nf < NUM_FPR_ARG_REGISTERS)
- {
- /* FIXME? here we are really changing the values
- stored in the original calling routines outgoing
- parameter stack. This is probably a really
- naughty thing to do but... */
- double temp = pfr->d;
- pfr->f = (float) temp;
- avalue[i] = pfr;
- nf++;
- pfr++;
- }
- else
- {
- avalue[i] = pst;
- pst += 1;
- }
- break;
-
- case FFI_TYPE_DOUBLE:
- if (nf < NUM_FPR_ARG_REGISTERS)
- {
- avalue[i] = pfr;
- nf++;
- pfr++;
- }
- else
- {
- if (((long) pst) & 4)
- pst++;
- avalue[i] = pst;
- pst += 2;
- }
- break;
-
-# if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- if (nf < NUM_FPR_ARG_REGISTERS - 1)
- {
- avalue[i] = pfr;
- pfr += 2;
- nf += 2;
- }
- else
- {
- if (((long) pst) & 4)
- pst++;
- avalue[i] = pst;
- pst += 4;
- nf = 8;
- }
- break;
-# endif
-#endif
-
- case FFI_TYPE_UINT128:
- /* Test if for the whole long double, 4 gprs are available.
- otherwise the stuff ends up on the stack. */
- if (ng < NUM_GPR_ARG_REGISTERS - 3)
- {
- avalue[i] = pgr;
- pgr += 4;
- ng += 4;
- }
- else
- {
- avalue[i] = pst;
- pst += 4;
- ng = 8+4;
- }
- break;
-
- case FFI_TYPE_SINT8:
- case FFI_TYPE_UINT8:
-#ifndef __LITTLE_ENDIAN__
- if (ng < NUM_GPR_ARG_REGISTERS)
- {
- avalue[i] = (char *) pgr + 3;
- ng++;
- pgr++;
- }
- else
- {
- avalue[i] = (char *) pst + 3;
- pst++;
- }
- break;
-#endif
-
- case FFI_TYPE_SINT16:
- case FFI_TYPE_UINT16:
-#ifndef __LITTLE_ENDIAN__
- if (ng < NUM_GPR_ARG_REGISTERS)
- {
- avalue[i] = (char *) pgr + 2;
- ng++;
- pgr++;
- }
- else
- {
- avalue[i] = (char *) pst + 2;
- pst++;
- }
- break;
-#endif
-
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_POINTER:
- if (ng < NUM_GPR_ARG_REGISTERS)
- {
- avalue[i] = pgr;
- ng++;
- pgr++;
- }
- else
- {
- avalue[i] = pst;
- pst++;
- }
- break;
-
- case FFI_TYPE_STRUCT:
- /* Structs are passed by reference. The address will appear in a
- gpr if it is one of the first 8 arguments. */
- if (ng < NUM_GPR_ARG_REGISTERS)
- {
- avalue[i] = (void *) *pgr;
- ng++;
- pgr++;
- }
- else
- {
- avalue[i] = (void *) *pst;
- pst++;
- }
- break;
-
- case FFI_TYPE_SINT64:
- case FFI_TYPE_UINT64:
- /* Passing long long ints are complex, they must
- be passed in suitable register pairs such as
- (r3,r4) or (r5,r6) or (r6,r7), or (r7,r8) or (r9,r10)
- and if the entire pair aren't available then the outgoing
- parameter stack is used for both but an alignment of 8
- must will be kept. So we must either look in pgr
- or pst to find the correct address for this type
- of parameter. */
- if (ng < NUM_GPR_ARG_REGISTERS - 1)
- {
- if (ng & 1)
- {
- /* skip r4, r6, r8 as starting points */
- ng++;
- pgr++;
- }
- avalue[i] = pgr;
- ng += 2;
- pgr += 2;
- }
- else
- {
- if (((long) pst) & 4)
- pst++;
- avalue[i] = pst;
- pst += 2;
- ng = NUM_GPR_ARG_REGISTERS;
- }
- break;
-
- default:
- FFI_ASSERT (0);
- }
-
- i++;
- }
-
- (*fun) (cif, rvalue, avalue, user_data);
-
- /* Tell ffi_closure_SYSV how to perform return type promotions.
- Because the FFI_SYSV ABI returns the structures <= 8 bytes in
- r3/r4 we have to tell ffi_closure_SYSV how to treat them. We
- combine the base type FFI_SYSV_TYPE_SMALL_STRUCT with the size of
- the struct less one. We never have a struct with size zero.
- See the comment in ffitarget.h about ordering. */
- if (rtypenum == FFI_TYPE_STRUCT
- && (cif->abi & FFI_SYSV_STRUCT_RET) != 0 && size <= 8)
- return FFI_SYSV_TYPE_SMALL_STRUCT - 1 + size;
- return rtypenum;
-}
-#endif
+/* -----------------------------------------------------------------------
+ ffi_sysv.c - Copyright (C) 2013 IBM
+ Copyright (C) 2011 Anthony Green
+ Copyright (C) 2011 Kyle Moffett
+ Copyright (C) 2008 Red Hat, Inc
+ Copyright (C) 2007, 2008 Free Software Foundation, Inc
+ Copyright (c) 1998 Geoffrey Keating
+
+ PowerPC Foreign Function Interface
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#include "ffi.h"
+
+#ifndef POWERPC64
+#include "ffi_common.h"
+#include "ffi_powerpc.h"
+
+
+/* About the SYSV ABI. */
+#define ASM_NEEDS_REGISTERS 6
+#define NUM_GPR_ARG_REGISTERS 8
+#define NUM_FPR_ARG_REGISTERS 8
+
+
+#if HAVE_LONG_DOUBLE_VARIANT && FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+/* Adjust size of ffi_type_longdouble. */
+void FFI_HIDDEN
+ffi_prep_types_sysv (ffi_abi abi)
+{
+ if ((abi & (FFI_SYSV | FFI_SYSV_LONG_DOUBLE_128)) == FFI_SYSV)
+ {
+ ffi_type_longdouble.size = 8;
+ ffi_type_longdouble.alignment = 8;
+ }
+ else
+ {
+ ffi_type_longdouble.size = 16;
+ ffi_type_longdouble.alignment = 16;
+ }
+}
+#endif
+
+/* Transform long double, double and float to other types as per abi. */
+static int
+translate_float (int abi, int type)
+{
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ if (type == FFI_TYPE_LONGDOUBLE
+ && (abi & FFI_SYSV_LONG_DOUBLE_128) == 0)
+ type = FFI_TYPE_DOUBLE;
+#endif
+ if ((abi & FFI_SYSV_SOFT_FLOAT) != 0)
+ {
+ if (type == FFI_TYPE_FLOAT)
+ type = FFI_TYPE_UINT32;
+ else if (type == FFI_TYPE_DOUBLE)
+ type = FFI_TYPE_UINT64;
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ else if (type == FFI_TYPE_LONGDOUBLE)
+ type = FFI_TYPE_UINT128;
+ }
+ else if ((abi & FFI_SYSV_IBM_LONG_DOUBLE) == 0)
+ {
+ if (type == FFI_TYPE_LONGDOUBLE)
+ type = FFI_TYPE_STRUCT;
+#endif
+ }
+ return type;
+}
+
+/* Perform machine dependent cif processing */
+static ffi_status
+ffi_prep_cif_sysv_core (ffi_cif *cif)
+{
+ ffi_type **ptr;
+ unsigned bytes;
+ unsigned i, fpr_count = 0, gpr_count = 0, stack_count = 0;
+ unsigned flags = cif->flags;
+ unsigned struct_copy_size = 0;
+ unsigned type = cif->rtype->type;
+ unsigned size = cif->rtype->size;
+
+ /* The machine-independent calculation of cif->bytes doesn't work
+ for us. Redo the calculation. */
+
+ /* Space for the frame pointer, callee's LR, and the asm's temp regs. */
+ bytes = (2 + ASM_NEEDS_REGISTERS) * sizeof (int);
+
+ /* Space for the GPR registers. */
+ bytes += NUM_GPR_ARG_REGISTERS * sizeof (int);
+
+ /* Return value handling. The rules for SYSV are as follows:
+ - 32-bit (or less) integer values are returned in gpr3;
+ - Structures of size <= 4 bytes also returned in gpr3;
+ - 64-bit integer values and structures between 5 and 8 bytes are returned
+ in gpr3 and gpr4;
+ - Larger structures are allocated space and a pointer is passed as
+ the first argument.
+ - Single/double FP values are returned in fpr1;
+ - long doubles (if not equivalent to double) are returned in
+ fpr1,fpr2 for Linux and as for large structs for SysV. */
+
+ type = translate_float (cif->abi, type);
+
+ switch (type)
+ {
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ flags |= FLAG_RETURNS_128BITS;
+ /* Fall through. */
+#endif
+ case FFI_TYPE_DOUBLE:
+ flags |= FLAG_RETURNS_64BITS;
+ /* Fall through. */
+ case FFI_TYPE_FLOAT:
+ flags |= FLAG_RETURNS_FP;
+#ifdef __NO_FPRS__
+ return FFI_BAD_ABI;
+#endif
+ break;
+
+ case FFI_TYPE_UINT128:
+ flags |= FLAG_RETURNS_128BITS;
+ /* Fall through. */
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ flags |= FLAG_RETURNS_64BITS;
+ break;
+
+ case FFI_TYPE_STRUCT:
+ /* The final SYSV ABI says that structures smaller or equal 8 bytes
+ are returned in r3/r4. A draft ABI used by linux instead
+ returns them in memory. */
+ if ((cif->abi & FFI_SYSV_STRUCT_RET) != 0 && size <= 8)
+ {
+ flags |= FLAG_RETURNS_SMST;
+ break;
+ }
+ gpr_count++;
+ flags |= FLAG_RETVAL_REFERENCE;
+ /* Fall through. */
+ case FFI_TYPE_VOID:
+ flags |= FLAG_RETURNS_NOTHING;
+ break;
+
+ default:
+ /* Returns 32-bit integer, or similar. Nothing to do here. */
+ break;
+ }
+
+ /* The first NUM_GPR_ARG_REGISTERS words of integer arguments, and the
+ first NUM_FPR_ARG_REGISTERS fp arguments, go in registers; the rest
+ goes on the stack. Structures and long doubles (if not equivalent
+ to double) are passed as a pointer to a copy of the structure.
+ Stuff on the stack needs to keep proper alignment. */
+ for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++)
+ {
+ unsigned short typenum = (*ptr)->type;
+
+ typenum = translate_float (cif->abi, typenum);
+
+ switch (typenum)
+ {
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ if (fpr_count >= NUM_FPR_ARG_REGISTERS - 1)
+ {
+ fpr_count = NUM_FPR_ARG_REGISTERS;
+ /* 8-byte align long doubles. */
+ stack_count += stack_count & 1;
+ stack_count += 4;
+ }
+ else
+ fpr_count += 2;
+#ifdef __NO_FPRS__
+ return FFI_BAD_ABI;
+#endif
+ break;
+#endif
+
+ case FFI_TYPE_DOUBLE:
+ if (fpr_count >= NUM_FPR_ARG_REGISTERS)
+ {
+ /* 8-byte align doubles. */
+ stack_count += stack_count & 1;
+ stack_count += 2;
+ }
+ else
+ fpr_count += 1;
+#ifdef __NO_FPRS__
+ return FFI_BAD_ABI;
+#endif
+ break;
+
+ case FFI_TYPE_FLOAT:
+ if (fpr_count >= NUM_FPR_ARG_REGISTERS)
+ /* Yes, we don't follow the ABI, but neither does gcc. */
+ stack_count += 1;
+ else
+ fpr_count += 1;
+#ifdef __NO_FPRS__
+ return FFI_BAD_ABI;
+#endif
+ break;
+
+ case FFI_TYPE_UINT128:
+ /* A long double in FFI_LINUX_SOFT_FLOAT can use only a set
+ of four consecutive gprs. If we do not have enough, we
+ have to adjust the gpr_count value. */
+ if (gpr_count >= NUM_GPR_ARG_REGISTERS - 3)
+ gpr_count = NUM_GPR_ARG_REGISTERS;
+ if (gpr_count >= NUM_GPR_ARG_REGISTERS)
+ stack_count += 4;
+ else
+ gpr_count += 4;
+ break;
+
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ /* 'long long' arguments are passed as two words, but
+ either both words must fit in registers or both go
+ on the stack. If they go on the stack, they must
+ be 8-byte-aligned.
+
+ Also, only certain register pairs can be used for
+ passing long long int -- specifically (r3,r4), (r5,r6),
+ (r7,r8), (r9,r10). */
+ gpr_count += gpr_count & 1;
+ if (gpr_count >= NUM_GPR_ARG_REGISTERS)
+ {
+ stack_count += stack_count & 1;
+ stack_count += 2;
+ }
+ else
+ gpr_count += 2;
+ break;
+
+ case FFI_TYPE_STRUCT:
+ /* We must allocate space for a copy of these to enforce
+ pass-by-value. Pad the space up to a multiple of 16
+ bytes (the maximum alignment required for anything under
+ the SYSV ABI). */
+ struct_copy_size += ((*ptr)->size + 15) & ~0xF;
+ /* Fall through (allocate space for the pointer). */
+
+ case FFI_TYPE_POINTER:
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ /* Everything else is passed as a 4-byte word in a GPR, either
+ the object itself or a pointer to it. */
+ if (gpr_count >= NUM_GPR_ARG_REGISTERS)
+ stack_count += 1;
+ else
+ gpr_count += 1;
+ break;
+
+ default:
+ FFI_ASSERT (0);
+ }
+ }
+
+ if (fpr_count != 0)
+ flags |= FLAG_FP_ARGUMENTS;
+ if (gpr_count > 4)
+ flags |= FLAG_4_GPR_ARGUMENTS;
+ if (struct_copy_size != 0)
+ flags |= FLAG_ARG_NEEDS_COPY;
+
+ /* Space for the FPR registers, if needed. */
+ if (fpr_count != 0)
+ bytes += NUM_FPR_ARG_REGISTERS * sizeof (double);
+
+ /* Stack space. */
+ bytes += stack_count * sizeof (int);
+
+ /* The stack space allocated needs to be a multiple of 16 bytes. */
+ bytes = (bytes + 15) & ~0xF;
+
+ /* Add in the space for the copied structures. */
+ bytes += struct_copy_size;
+
+ cif->flags = flags;
+ cif->bytes = bytes;
+
+ return FFI_OK;
+}
+
+ffi_status FFI_HIDDEN
+ffi_prep_cif_sysv (ffi_cif *cif)
+{
+ if ((cif->abi & FFI_SYSV) == 0)
+ {
+ /* This call is from old code. Translate to new ABI values. */
+ cif->flags |= FLAG_COMPAT;
+ switch (cif->abi)
+ {
+ default:
+ return FFI_BAD_ABI;
+
+ case FFI_COMPAT_SYSV:
+ cif->abi = FFI_SYSV | FFI_SYSV_STRUCT_RET | FFI_SYSV_LONG_DOUBLE_128;
+ break;
+
+ case FFI_COMPAT_GCC_SYSV:
+ cif->abi = FFI_SYSV | FFI_SYSV_LONG_DOUBLE_128;
+ break;
+
+ case FFI_COMPAT_LINUX:
+ cif->abi = (FFI_SYSV | FFI_SYSV_IBM_LONG_DOUBLE
+ | FFI_SYSV_LONG_DOUBLE_128);
+ break;
+
+ case FFI_COMPAT_LINUX_SOFT_FLOAT:
+ cif->abi = (FFI_SYSV | FFI_SYSV_SOFT_FLOAT | FFI_SYSV_IBM_LONG_DOUBLE
+ | FFI_SYSV_LONG_DOUBLE_128);
+ break;
+ }
+ }
+ return ffi_prep_cif_sysv_core (cif);
+}
+
+/* ffi_prep_args_SYSV is called by the assembly routine once stack space
+ has been allocated for the function's arguments.
+
+ The stack layout we want looks like this:
+
+ | Return address from ffi_call_SYSV 4bytes | higher addresses
+ |--------------------------------------------|
+ | Previous backchain pointer 4 | stack pointer here
+ |--------------------------------------------|<+ <<< on entry to
+ | Saved r28-r31 4*4 | | ffi_call_SYSV
+ |--------------------------------------------| |
+ | GPR registers r3-r10 8*4 | | ffi_call_SYSV
+ |--------------------------------------------| |
+ | FPR registers f1-f8 (optional) 8*8 | |
+ |--------------------------------------------| | stack |
+ | Space for copied structures | | grows |
+ |--------------------------------------------| | down V
+ | Parameters that didn't fit in registers | |
+ |--------------------------------------------| | lower addresses
+ | Space for callee's LR 4 | |
+ |--------------------------------------------| | stack pointer here
+ | Current backchain pointer 4 |-/ during
+ |--------------------------------------------| <<< ffi_call_SYSV
+
+*/
+
+void FFI_HIDDEN
+ffi_prep_args_SYSV (extended_cif *ecif, unsigned *const stack)
+{
+ const unsigned bytes = ecif->cif->bytes;
+ const unsigned flags = ecif->cif->flags;
+
+ typedef union
+ {
+ char *c;
+ unsigned *u;
+ long long *ll;
+ float *f;
+ double *d;
+ } valp;
+
+ /* 'stacktop' points at the previous backchain pointer. */
+ valp stacktop;
+
+ /* 'gpr_base' points at the space for gpr3, and grows upwards as
+ we use GPR registers. */
+ valp gpr_base;
+ valp gpr_end;
+
+#ifndef __NO_FPRS__
+ /* 'fpr_base' points at the space for fpr1, and grows upwards as
+ we use FPR registers. */
+ valp fpr_base;
+ valp fpr_end;
+#endif
+
+ /* 'copy_space' grows down as we put structures in it. It should
+ stay 16-byte aligned. */
+ valp copy_space;
+
+ /* 'next_arg' grows up as we put parameters in it. */
+ valp next_arg;
+
+ int i;
+ ffi_type **ptr;
+#ifndef __NO_FPRS__
+ double double_tmp;
+#endif
+ union
+ {
+ void **v;
+ char **c;
+ signed char **sc;
+ unsigned char **uc;
+ signed short **ss;
+ unsigned short **us;
+ unsigned int **ui;
+ long long **ll;
+ float **f;
+ double **d;
+ } p_argv;
+ size_t struct_copy_size;
+ unsigned gprvalue;
+
+ stacktop.c = (char *) stack + bytes;
+ gpr_end.u = stacktop.u - ASM_NEEDS_REGISTERS;
+ gpr_base.u = gpr_end.u - NUM_GPR_ARG_REGISTERS;
+#ifndef __NO_FPRS__
+ fpr_end.d = gpr_base.d;
+ fpr_base.d = fpr_end.d - NUM_FPR_ARG_REGISTERS;
+ copy_space.c = ((flags & FLAG_FP_ARGUMENTS) ? fpr_base.c : gpr_base.c);
+#else
+ copy_space.c = gpr_base.c;
+#endif
+ next_arg.u = stack + 2;
+
+ /* Check that everything starts aligned properly. */
+ FFI_ASSERT (((unsigned long) (char *) stack & 0xF) == 0);
+ FFI_ASSERT (((unsigned long) copy_space.c & 0xF) == 0);
+ FFI_ASSERT (((unsigned long) stacktop.c & 0xF) == 0);
+ FFI_ASSERT ((bytes & 0xF) == 0);
+ FFI_ASSERT (copy_space.c >= next_arg.c);
+
+ /* Deal with return values that are actually pass-by-reference. */
+ if (flags & FLAG_RETVAL_REFERENCE)
+ *gpr_base.u++ = (unsigned) (char *) ecif->rvalue;
+
+ /* Now for the arguments. */
+ p_argv.v = ecif->avalue;
+ for (ptr = ecif->cif->arg_types, i = ecif->cif->nargs;
+ i > 0;
+ i--, ptr++, p_argv.v++)
+ {
+ unsigned int typenum = (*ptr)->type;
+
+ typenum = translate_float (ecif->cif->abi, typenum);
+
+ /* Now test the translated value */
+ switch (typenum)
+ {
+#ifndef __NO_FPRS__
+# if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ double_tmp = (*p_argv.d)[0];
+
+ if (fpr_base.d >= fpr_end.d - 1)
+ {
+ fpr_base.d = fpr_end.d;
+ if (((next_arg.u - stack) & 1) != 0)
+ next_arg.u += 1;
+ *next_arg.d = double_tmp;
+ next_arg.u += 2;
+ double_tmp = (*p_argv.d)[1];
+ *next_arg.d = double_tmp;
+ next_arg.u += 2;
+ }
+ else
+ {
+ *fpr_base.d++ = double_tmp;
+ double_tmp = (*p_argv.d)[1];
+ *fpr_base.d++ = double_tmp;
+ }
+ FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
+ break;
+# endif
+ case FFI_TYPE_DOUBLE:
+ double_tmp = **p_argv.d;
+
+ if (fpr_base.d >= fpr_end.d)
+ {
+ if (((next_arg.u - stack) & 1) != 0)
+ next_arg.u += 1;
+ *next_arg.d = double_tmp;
+ next_arg.u += 2;
+ }
+ else
+ *fpr_base.d++ = double_tmp;
+ FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
+ break;
+
+ case FFI_TYPE_FLOAT:
+ double_tmp = **p_argv.f;
+ if (fpr_base.d >= fpr_end.d)
+ {
+ *next_arg.f = (float) double_tmp;
+ next_arg.u += 1;
+ }
+ else
+ *fpr_base.d++ = double_tmp;
+ FFI_ASSERT (flags & FLAG_FP_ARGUMENTS);
+ break;
+#endif /* have FPRs */
+
+ case FFI_TYPE_UINT128:
+ /* The soft float ABI for long doubles works like this, a long double
+ is passed in four consecutive GPRs if available. A maximum of 2
+ long doubles can be passed in gprs. If we do not have 4 GPRs
+ left, the long double is passed on the stack, 4-byte aligned. */
+ if (gpr_base.u >= gpr_end.u - 3)
+ {
+ unsigned int ii;
+ gpr_base.u = gpr_end.u;
+ for (ii = 0; ii < 4; ii++)
+ {
+ unsigned int int_tmp = (*p_argv.ui)[ii];
+ *next_arg.u++ = int_tmp;
+ }
+ }
+ else
+ {
+ unsigned int ii;
+ for (ii = 0; ii < 4; ii++)
+ {
+ unsigned int int_tmp = (*p_argv.ui)[ii];
+ *gpr_base.u++ = int_tmp;
+ }
+ }
+ break;
+
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ if (gpr_base.u >= gpr_end.u - 1)
+ {
+ gpr_base.u = gpr_end.u;
+ if (((next_arg.u - stack) & 1) != 0)
+ next_arg.u++;
+ *next_arg.ll = **p_argv.ll;
+ next_arg.u += 2;
+ }
+ else
+ {
+ /* The abi states only certain register pairs can be
+ used for passing long long int specifically (r3,r4),
+ (r5,r6), (r7,r8), (r9,r10). If next arg is long long
+ but not correct starting register of pair then skip
+ until the proper starting register. */
+ if (((gpr_end.u - gpr_base.u) & 1) != 0)
+ gpr_base.u++;
+ *gpr_base.ll++ = **p_argv.ll;
+ }
+ break;
+
+ case FFI_TYPE_STRUCT:
+ struct_copy_size = ((*ptr)->size + 15) & ~0xF;
+ copy_space.c -= struct_copy_size;
+ memcpy (copy_space.c, *p_argv.c, (*ptr)->size);
+
+ gprvalue = (unsigned long) copy_space.c;
+
+ FFI_ASSERT (copy_space.c > next_arg.c);
+ FFI_ASSERT (flags & FLAG_ARG_NEEDS_COPY);
+ goto putgpr;
+
+ case FFI_TYPE_UINT8:
+ gprvalue = **p_argv.uc;
+ goto putgpr;
+ case FFI_TYPE_SINT8:
+ gprvalue = **p_argv.sc;
+ goto putgpr;
+ case FFI_TYPE_UINT16:
+ gprvalue = **p_argv.us;
+ goto putgpr;
+ case FFI_TYPE_SINT16:
+ gprvalue = **p_argv.ss;
+ goto putgpr;
+
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_POINTER:
+
+ gprvalue = **p_argv.ui;
+
+ putgpr:
+ if (gpr_base.u >= gpr_end.u)
+ *next_arg.u++ = gprvalue;
+ else
+ *gpr_base.u++ = gprvalue;
+ break;
+ }
+ }
+
+ /* Check that we didn't overrun the stack... */
+ FFI_ASSERT (copy_space.c >= next_arg.c);
+ FFI_ASSERT (gpr_base.u <= gpr_end.u);
+#ifndef __NO_FPRS__
+ FFI_ASSERT (fpr_base.u <= fpr_end.u);
+#endif
+ FFI_ASSERT (((flags & FLAG_4_GPR_ARGUMENTS) != 0)
+ == (gpr_end.u - gpr_base.u < 4));
+}
+
+#define MIN_CACHE_LINE_SIZE 8
+
+static void
+flush_icache (char *wraddr, char *xaddr, int size)
+{
+ int i;
+ for (i = 0; i < size; i += MIN_CACHE_LINE_SIZE)
+ __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;"
+ : : "r" (xaddr + i), "r" (wraddr + i) : "memory");
+ __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;" "sync;" "isync;"
+ : : "r"(xaddr + size - 1), "r"(wraddr + size - 1)
+ : "memory");
+}
+
+ffi_status FFI_HIDDEN
+ffi_prep_closure_loc_sysv (ffi_closure *closure,
+ ffi_cif *cif,
+ void (*fun) (ffi_cif *, void *, void **, void *),
+ void *user_data,
+ void *codeloc)
+{
+ unsigned int *tramp;
+
+ if (cif->abi < FFI_SYSV || cif->abi >= FFI_LAST_ABI)
+ return FFI_BAD_ABI;
+
+ tramp = (unsigned int *) &closure->tramp[0];
+ tramp[0] = 0x7c0802a6; /* mflr r0 */
+ tramp[1] = 0x429f0005; /* bcl 20,31,.+4 */
+ tramp[2] = 0x7d6802a6; /* mflr r11 */
+ tramp[3] = 0x7c0803a6; /* mtlr r0 */
+ tramp[4] = 0x800b0018; /* lwz r0,24(r11) */
+ tramp[5] = 0x816b001c; /* lwz r11,28(r11) */
+ tramp[6] = 0x7c0903a6; /* mtctr r0 */
+ tramp[7] = 0x4e800420; /* bctr */
+ *(void **) &tramp[8] = (void *) ffi_closure_SYSV; /* function */
+ *(void **) &tramp[9] = codeloc; /* context */
+
+ /* Flush the icache. */
+ flush_icache ((char *)tramp, (char *)codeloc, 8 * 4);
+
+ closure->cif = cif;
+ closure->fun = fun;
+ closure->user_data = user_data;
+
+ return FFI_OK;
+}
+
+/* Basically the trampoline invokes ffi_closure_SYSV, and on
+ entry, r11 holds the address of the closure.
+ After storing the registers that could possibly contain
+ parameters to be passed into the stack frame and setting
+ up space for a return value, ffi_closure_SYSV invokes the
+ following helper function to do most of the work. */
+
+int
+ffi_closure_helper_SYSV (ffi_cif *cif,
+ void (*fun) (ffi_cif *, void *, void **, void *),
+ void *user_data,
+ void *rvalue,
+ unsigned long *pgr,
+ ffi_dblfl *pfr,
+ unsigned long *pst)
+{
+ /* rvalue is the pointer to space for return value in closure assembly */
+ /* pgr is the pointer to where r3-r10 are stored in ffi_closure_SYSV */
+ /* pfr is the pointer to where f1-f8 are stored in ffi_closure_SYSV */
+ /* pst is the pointer to outgoing parameter stack in original caller */
+
+ void ** avalue;
+ ffi_type ** arg_types;
+ long i, avn;
+#ifndef __NO_FPRS__
+ long nf = 0; /* number of floating registers already used */
+#endif
+ long ng = 0; /* number of general registers already used */
+
+ unsigned size = cif->rtype->size;
+ unsigned short rtypenum = cif->rtype->type;
+
+ avalue = alloca (cif->nargs * sizeof (void *));
+
+ /* First translate for softfloat/nonlinux */
+ rtypenum = translate_float (cif->abi, rtypenum);
+
+ /* Copy the caller's structure return value address so that the closure
+ returns the data directly to the caller.
+ For FFI_SYSV the result is passed in r3/r4 if the struct size is less
+ or equal 8 bytes. */
+ if (rtypenum == FFI_TYPE_STRUCT
+ && !((cif->abi & FFI_SYSV_STRUCT_RET) != 0 && size <= 8))
+ {
+ rvalue = (void *) *pgr;
+ ng++;
+ pgr++;
+ }
+
+ i = 0;
+ avn = cif->nargs;
+ arg_types = cif->arg_types;
+
+ /* Grab the addresses of the arguments from the stack frame. */
+ while (i < avn) {
+ unsigned short typenum = arg_types[i]->type;
+
+ /* We may need to handle some values depending on ABI. */
+ typenum = translate_float (cif->abi, typenum);
+
+ switch (typenum)
+ {
+#ifndef __NO_FPRS__
+ case FFI_TYPE_FLOAT:
+ /* Unfortunately float values are stored as doubles
+ in the ffi_closure_SYSV code (since we don't check
+ the type in that routine). */
+ if (nf < NUM_FPR_ARG_REGISTERS)
+ {
+ /* FIXME? here we are really changing the values
+ stored in the original calling routines outgoing
+ parameter stack. This is probably a really
+ naughty thing to do but... */
+ double temp = pfr->d;
+ pfr->f = (float) temp;
+ avalue[i] = pfr;
+ nf++;
+ pfr++;
+ }
+ else
+ {
+ avalue[i] = pst;
+ pst += 1;
+ }
+ break;
+
+ case FFI_TYPE_DOUBLE:
+ if (nf < NUM_FPR_ARG_REGISTERS)
+ {
+ avalue[i] = pfr;
+ nf++;
+ pfr++;
+ }
+ else
+ {
+ if (((long) pst) & 4)
+ pst++;
+ avalue[i] = pst;
+ pst += 2;
+ }
+ break;
+
+# if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ if (nf < NUM_FPR_ARG_REGISTERS - 1)
+ {
+ avalue[i] = pfr;
+ pfr += 2;
+ nf += 2;
+ }
+ else
+ {
+ if (((long) pst) & 4)
+ pst++;
+ avalue[i] = pst;
+ pst += 4;
+ nf = 8;
+ }
+ break;
+# endif
+#endif
+
+ case FFI_TYPE_UINT128:
+ /* Test if for the whole long double, 4 gprs are available.
+ otherwise the stuff ends up on the stack. */
+ if (ng < NUM_GPR_ARG_REGISTERS - 3)
+ {
+ avalue[i] = pgr;
+ pgr += 4;
+ ng += 4;
+ }
+ else
+ {
+ avalue[i] = pst;
+ pst += 4;
+ ng = 8+4;
+ }
+ break;
+
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT8:
+#ifndef __LITTLE_ENDIAN__
+ if (ng < NUM_GPR_ARG_REGISTERS)
+ {
+ avalue[i] = (char *) pgr + 3;
+ ng++;
+ pgr++;
+ }
+ else
+ {
+ avalue[i] = (char *) pst + 3;
+ pst++;
+ }
+ break;
+#endif
+
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT16:
+#ifndef __LITTLE_ENDIAN__
+ if (ng < NUM_GPR_ARG_REGISTERS)
+ {
+ avalue[i] = (char *) pgr + 2;
+ ng++;
+ pgr++;
+ }
+ else
+ {
+ avalue[i] = (char *) pst + 2;
+ pst++;
+ }
+ break;
+#endif
+
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_POINTER:
+ if (ng < NUM_GPR_ARG_REGISTERS)
+ {
+ avalue[i] = pgr;
+ ng++;
+ pgr++;
+ }
+ else
+ {
+ avalue[i] = pst;
+ pst++;
+ }
+ break;
+
+ case FFI_TYPE_STRUCT:
+ /* Structs are passed by reference. The address will appear in a
+ gpr if it is one of the first 8 arguments. */
+ if (ng < NUM_GPR_ARG_REGISTERS)
+ {
+ avalue[i] = (void *) *pgr;
+ ng++;
+ pgr++;
+ }
+ else
+ {
+ avalue[i] = (void *) *pst;
+ pst++;
+ }
+ break;
+
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_UINT64:
+ /* Passing long long ints are complex, they must
+ be passed in suitable register pairs such as
+ (r3,r4) or (r5,r6) or (r6,r7), or (r7,r8) or (r9,r10)
+ and if the entire pair aren't available then the outgoing
+ parameter stack is used for both but an alignment of 8
+ must will be kept. So we must either look in pgr
+ or pst to find the correct address for this type
+ of parameter. */
+ if (ng < NUM_GPR_ARG_REGISTERS - 1)
+ {
+ if (ng & 1)
+ {
+ /* skip r4, r6, r8 as starting points */
+ ng++;
+ pgr++;
+ }
+ avalue[i] = pgr;
+ ng += 2;
+ pgr += 2;
+ }
+ else
+ {
+ if (((long) pst) & 4)
+ pst++;
+ avalue[i] = pst;
+ pst += 2;
+ ng = NUM_GPR_ARG_REGISTERS;
+ }
+ break;
+
+ default:
+ FFI_ASSERT (0);
+ }
+
+ i++;
+ }
+
+ (*fun) (cif, rvalue, avalue, user_data);
+
+ /* Tell ffi_closure_SYSV how to perform return type promotions.
+ Because the FFI_SYSV ABI returns the structures <= 8 bytes in
+ r3/r4 we have to tell ffi_closure_SYSV how to treat them. We
+ combine the base type FFI_SYSV_TYPE_SMALL_STRUCT with the size of
+ the struct less one. We never have a struct with size zero.
+ See the comment in ffitarget.h about ordering. */
+ if (rtypenum == FFI_TYPE_STRUCT
+ && (cif->abi & FFI_SYSV_STRUCT_RET) != 0 && size <= 8)
+ return FFI_SYSV_TYPE_SMALL_STRUCT - 1 + size;
+ return rtypenum;
+}
+#endif
diff --git a/contrib/restricted/libffi/src/powerpc/ffitarget.h b/contrib/restricted/libffi/src/powerpc/ffitarget.h
index 1a25a43141..7fb9a93908 100644
--- a/contrib/restricted/libffi/src/powerpc/ffitarget.h
+++ b/contrib/restricted/libffi/src/powerpc/ffitarget.h
@@ -1,204 +1,204 @@
-/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012 Anthony Green
- Copyright (C) 2007, 2008, 2010 Free Software Foundation, Inc
- Copyright (c) 1996-2003 Red Hat, Inc.
-
- Target configuration macros for PowerPC.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
-
- ----------------------------------------------------------------------- */
-
-#ifndef LIBFFI_TARGET_H
-#define LIBFFI_TARGET_H
-
-#ifndef LIBFFI_H
-#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
-#endif
-
-/* ---- System specific configurations ----------------------------------- */
-
-#if defined (POWERPC) && defined (__powerpc64__) /* linux64 */
-#ifndef POWERPC64
-#define POWERPC64
-#endif
-#elif defined (POWERPC_DARWIN) && defined (__ppc64__) /* Darwin64 */
-#ifndef POWERPC64
-#define POWERPC64
-#endif
-#ifndef POWERPC_DARWIN64
-#define POWERPC_DARWIN64
-#endif
-#elif defined (POWERPC_AIX) && defined (__64BIT__) /* AIX64 */
-#ifndef POWERPC64
-#define POWERPC64
-#endif
-#endif
-
-#ifndef LIBFFI_ASM
-typedef unsigned long ffi_arg;
-typedef signed long ffi_sarg;
-
-typedef enum ffi_abi {
- FFI_FIRST_ABI = 0,
-
-#if defined (POWERPC_AIX)
- FFI_AIX,
- FFI_DARWIN,
- FFI_DEFAULT_ABI = FFI_AIX,
- FFI_LAST_ABI
-
-#elif defined (POWERPC_DARWIN)
- FFI_AIX,
- FFI_DARWIN,
- FFI_DEFAULT_ABI = FFI_DARWIN,
- FFI_LAST_ABI
-
-#else
- /* The FFI_COMPAT values are used by old code. Since libffi may be
- a shared library we have to support old values for backwards
- compatibility. */
- FFI_COMPAT_SYSV,
- FFI_COMPAT_GCC_SYSV,
- FFI_COMPAT_LINUX64,
- FFI_COMPAT_LINUX,
- FFI_COMPAT_LINUX_SOFT_FLOAT,
-
-# if defined (POWERPC64)
- /* This bit, always set in new code, must not be set in any of the
- old FFI_COMPAT values that might be used for 64-bit linux. We
- only need worry about FFI_COMPAT_LINUX64, but to be safe avoid
- all old values. */
- FFI_LINUX = 8,
- /* This and following bits can reuse FFI_COMPAT values. */
- FFI_LINUX_STRUCT_ALIGN = 1,
- FFI_LINUX_LONG_DOUBLE_128 = 2,
- FFI_LINUX_LONG_DOUBLE_IEEE128 = 4,
- FFI_DEFAULT_ABI = (FFI_LINUX
-# ifdef __STRUCT_PARM_ALIGN__
- | FFI_LINUX_STRUCT_ALIGN
-# endif
-# ifdef __LONG_DOUBLE_128__
- | FFI_LINUX_LONG_DOUBLE_128
-# ifdef __LONG_DOUBLE_IEEE128__
- | FFI_LINUX_LONG_DOUBLE_IEEE128
-# endif
-# endif
- ),
- FFI_LAST_ABI = 16
-
-# else
- /* This bit, always set in new code, must not be set in any of the
- old FFI_COMPAT values that might be used for 32-bit linux/sysv/bsd. */
- FFI_SYSV = 8,
- /* This and following bits can reuse FFI_COMPAT values. */
- FFI_SYSV_SOFT_FLOAT = 1,
- FFI_SYSV_STRUCT_RET = 2,
- FFI_SYSV_IBM_LONG_DOUBLE = 4,
- FFI_SYSV_LONG_DOUBLE_128 = 16,
-
- FFI_DEFAULT_ABI = (FFI_SYSV
-# ifdef __NO_FPRS__
- | FFI_SYSV_SOFT_FLOAT
-# endif
-# if (defined (__SVR4_STRUCT_RETURN) \
- || defined (POWERPC_FREEBSD) && !defined (__AIX_STRUCT_RETURN))
- | FFI_SYSV_STRUCT_RET
-# endif
-# if __LDBL_MANT_DIG__ == 106
- | FFI_SYSV_IBM_LONG_DOUBLE
-# endif
-# ifdef __LONG_DOUBLE_128__
- | FFI_SYSV_LONG_DOUBLE_128
-# endif
- ),
- FFI_LAST_ABI = 32
-# endif
-#endif
-
-} ffi_abi;
-#endif
-
-/* ---- Definitions for closures ----------------------------------------- */
-
-#define FFI_CLOSURES 1
-#define FFI_NATIVE_RAW_API 0
-#if defined (POWERPC) || defined (POWERPC_FREEBSD)
-# define FFI_GO_CLOSURES 1
-# define FFI_TARGET_SPECIFIC_VARIADIC 1
-# define FFI_EXTRA_CIF_FIELDS unsigned nfixedargs
-#endif
-#if defined (POWERPC_AIX)
-# define FFI_GO_CLOSURES 1
-#endif
-
-/* ppc_closure.S and linux64_closure.S expect this. */
-#define FFI_PPC_TYPE_LAST FFI_TYPE_POINTER
-
-/* We define additional types below. If generic types are added that
- must be supported by powerpc libffi then it is likely that
- FFI_PPC_TYPE_LAST needs increasing *and* the jump tables in
- ppc_closure.S and linux64_closure.S be extended. */
-
-#if !(FFI_TYPE_LAST == FFI_PPC_TYPE_LAST \
- || (FFI_TYPE_LAST == FFI_TYPE_COMPLEX \
- && !defined FFI_TARGET_HAS_COMPLEX_TYPE))
-# error "You likely have a broken powerpc libffi"
-#endif
-
-/* Needed for soft-float long-double-128 support. */
-#define FFI_TYPE_UINT128 (FFI_PPC_TYPE_LAST + 1)
-
-/* Needed for FFI_SYSV small structure returns. */
-#define FFI_SYSV_TYPE_SMALL_STRUCT (FFI_PPC_TYPE_LAST + 2)
-
-/* Used by ELFv2 for homogenous structure returns. */
-#define FFI_V2_TYPE_VECTOR (FFI_PPC_TYPE_LAST + 1)
-#define FFI_V2_TYPE_VECTOR_HOMOG (FFI_PPC_TYPE_LAST + 2)
-#define FFI_V2_TYPE_FLOAT_HOMOG (FFI_PPC_TYPE_LAST + 3)
-#define FFI_V2_TYPE_DOUBLE_HOMOG (FFI_PPC_TYPE_LAST + 4)
-#define FFI_V2_TYPE_SMALL_STRUCT (FFI_PPC_TYPE_LAST + 5)
-
-#if _CALL_ELF == 2
-# define FFI_TRAMPOLINE_SIZE 32
-#else
-# if defined(POWERPC64) || defined(POWERPC_AIX)
-# if defined(POWERPC_DARWIN64)
-# define FFI_TRAMPOLINE_SIZE 48
-# else
-# define FFI_TRAMPOLINE_SIZE 24
-# endif
-# else /* POWERPC || POWERPC_AIX */
-# define FFI_TRAMPOLINE_SIZE 40
-# endif
-#endif
-
-#ifndef LIBFFI_ASM
-#if defined(POWERPC_DARWIN) || defined(POWERPC_AIX)
-struct ffi_aix_trampoline_struct {
- void * code_pointer; /* Pointer to ffi_closure_ASM */
- void * toc; /* TOC */
- void * static_chain; /* Pointer to closure */
-};
-#endif
-#endif
-
-#endif
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2012 Anthony Green
+ Copyright (C) 2007, 2008, 2010 Free Software Foundation, Inc
+ Copyright (c) 1996-2003 Red Hat, Inc.
+
+ Target configuration macros for PowerPC.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+/* ---- System specific configurations ----------------------------------- */
+
+#if defined (POWERPC) && defined (__powerpc64__) /* linux64 */
+#ifndef POWERPC64
+#define POWERPC64
+#endif
+#elif defined (POWERPC_DARWIN) && defined (__ppc64__) /* Darwin64 */
+#ifndef POWERPC64
+#define POWERPC64
+#endif
+#ifndef POWERPC_DARWIN64
+#define POWERPC_DARWIN64
+#endif
+#elif defined (POWERPC_AIX) && defined (__64BIT__) /* AIX64 */
+#ifndef POWERPC64
+#define POWERPC64
+#endif
+#endif
+
+#ifndef LIBFFI_ASM
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+
+typedef enum ffi_abi {
+ FFI_FIRST_ABI = 0,
+
+#if defined (POWERPC_AIX)
+ FFI_AIX,
+ FFI_DARWIN,
+ FFI_DEFAULT_ABI = FFI_AIX,
+ FFI_LAST_ABI
+
+#elif defined (POWERPC_DARWIN)
+ FFI_AIX,
+ FFI_DARWIN,
+ FFI_DEFAULT_ABI = FFI_DARWIN,
+ FFI_LAST_ABI
+
+#else
+ /* The FFI_COMPAT values are used by old code. Since libffi may be
+ a shared library we have to support old values for backwards
+ compatibility. */
+ FFI_COMPAT_SYSV,
+ FFI_COMPAT_GCC_SYSV,
+ FFI_COMPAT_LINUX64,
+ FFI_COMPAT_LINUX,
+ FFI_COMPAT_LINUX_SOFT_FLOAT,
+
+# if defined (POWERPC64)
+ /* This bit, always set in new code, must not be set in any of the
+ old FFI_COMPAT values that might be used for 64-bit linux. We
+ only need worry about FFI_COMPAT_LINUX64, but to be safe avoid
+ all old values. */
+ FFI_LINUX = 8,
+ /* This and following bits can reuse FFI_COMPAT values. */
+ FFI_LINUX_STRUCT_ALIGN = 1,
+ FFI_LINUX_LONG_DOUBLE_128 = 2,
+ FFI_LINUX_LONG_DOUBLE_IEEE128 = 4,
+ FFI_DEFAULT_ABI = (FFI_LINUX
+# ifdef __STRUCT_PARM_ALIGN__
+ | FFI_LINUX_STRUCT_ALIGN
+# endif
+# ifdef __LONG_DOUBLE_128__
+ | FFI_LINUX_LONG_DOUBLE_128
+# ifdef __LONG_DOUBLE_IEEE128__
+ | FFI_LINUX_LONG_DOUBLE_IEEE128
+# endif
+# endif
+ ),
+ FFI_LAST_ABI = 16
+
+# else
+ /* This bit, always set in new code, must not be set in any of the
+ old FFI_COMPAT values that might be used for 32-bit linux/sysv/bsd. */
+ FFI_SYSV = 8,
+ /* This and following bits can reuse FFI_COMPAT values. */
+ FFI_SYSV_SOFT_FLOAT = 1,
+ FFI_SYSV_STRUCT_RET = 2,
+ FFI_SYSV_IBM_LONG_DOUBLE = 4,
+ FFI_SYSV_LONG_DOUBLE_128 = 16,
+
+ FFI_DEFAULT_ABI = (FFI_SYSV
+# ifdef __NO_FPRS__
+ | FFI_SYSV_SOFT_FLOAT
+# endif
+# if (defined (__SVR4_STRUCT_RETURN) \
+ || defined (POWERPC_FREEBSD) && !defined (__AIX_STRUCT_RETURN))
+ | FFI_SYSV_STRUCT_RET
+# endif
+# if __LDBL_MANT_DIG__ == 106
+ | FFI_SYSV_IBM_LONG_DOUBLE
+# endif
+# ifdef __LONG_DOUBLE_128__
+ | FFI_SYSV_LONG_DOUBLE_128
+# endif
+ ),
+ FFI_LAST_ABI = 32
+# endif
+#endif
+
+} ffi_abi;
+#endif
+
+/* ---- Definitions for closures ----------------------------------------- */
+
+#define FFI_CLOSURES 1
+#define FFI_NATIVE_RAW_API 0
+#if defined (POWERPC) || defined (POWERPC_FREEBSD)
+# define FFI_GO_CLOSURES 1
+# define FFI_TARGET_SPECIFIC_VARIADIC 1
+# define FFI_EXTRA_CIF_FIELDS unsigned nfixedargs
+#endif
+#if defined (POWERPC_AIX)
+# define FFI_GO_CLOSURES 1
+#endif
+
+/* ppc_closure.S and linux64_closure.S expect this. */
+#define FFI_PPC_TYPE_LAST FFI_TYPE_POINTER
+
+/* We define additional types below. If generic types are added that
+ must be supported by powerpc libffi then it is likely that
+ FFI_PPC_TYPE_LAST needs increasing *and* the jump tables in
+ ppc_closure.S and linux64_closure.S be extended. */
+
+#if !(FFI_TYPE_LAST == FFI_PPC_TYPE_LAST \
+ || (FFI_TYPE_LAST == FFI_TYPE_COMPLEX \
+ && !defined FFI_TARGET_HAS_COMPLEX_TYPE))
+# error "You likely have a broken powerpc libffi"
+#endif
+
+/* Needed for soft-float long-double-128 support. */
+#define FFI_TYPE_UINT128 (FFI_PPC_TYPE_LAST + 1)
+
+/* Needed for FFI_SYSV small structure returns. */
+#define FFI_SYSV_TYPE_SMALL_STRUCT (FFI_PPC_TYPE_LAST + 2)
+
+/* Used by ELFv2 for homogenous structure returns. */
+#define FFI_V2_TYPE_VECTOR (FFI_PPC_TYPE_LAST + 1)
+#define FFI_V2_TYPE_VECTOR_HOMOG (FFI_PPC_TYPE_LAST + 2)
+#define FFI_V2_TYPE_FLOAT_HOMOG (FFI_PPC_TYPE_LAST + 3)
+#define FFI_V2_TYPE_DOUBLE_HOMOG (FFI_PPC_TYPE_LAST + 4)
+#define FFI_V2_TYPE_SMALL_STRUCT (FFI_PPC_TYPE_LAST + 5)
+
+#if _CALL_ELF == 2
+# define FFI_TRAMPOLINE_SIZE 32
+#else
+# if defined(POWERPC64) || defined(POWERPC_AIX)
+# if defined(POWERPC_DARWIN64)
+# define FFI_TRAMPOLINE_SIZE 48
+# else
+# define FFI_TRAMPOLINE_SIZE 24
+# endif
+# else /* POWERPC || POWERPC_AIX */
+# define FFI_TRAMPOLINE_SIZE 40
+# endif
+#endif
+
+#ifndef LIBFFI_ASM
+#if defined(POWERPC_DARWIN) || defined(POWERPC_AIX)
+struct ffi_aix_trampoline_struct {
+ void * code_pointer; /* Pointer to ffi_closure_ASM */
+ void * toc; /* TOC */
+ void * static_chain; /* Pointer to closure */
+};
+#endif
+#endif
+
+#endif
diff --git a/contrib/restricted/libffi/src/powerpc/linux64.S b/contrib/restricted/libffi/src/powerpc/linux64.S
index ec1a9c160c..c99889c1c6 100644
--- a/contrib/restricted/libffi/src/powerpc/linux64.S
+++ b/contrib/restricted/libffi/src/powerpc/linux64.S
@@ -1,283 +1,283 @@
-/* -----------------------------------------------------------------------
- sysv.h - Copyright (c) 2003 Jakub Jelinek <jakub@redhat.com>
- Copyright (c) 2008 Red Hat, Inc.
-
- PowerPC64 Assembly glue.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
-
-#ifdef POWERPC64
- .hidden ffi_call_LINUX64
- .globl ffi_call_LINUX64
- .text
- .cfi_startproc
-# if _CALL_ELF == 2
-ffi_call_LINUX64:
- addis %r2, %r12, .TOC.-ffi_call_LINUX64@ha
- addi %r2, %r2, .TOC.-ffi_call_LINUX64@l
- .localentry ffi_call_LINUX64, . - ffi_call_LINUX64
-# else
- .section ".opd","aw"
- .align 3
-ffi_call_LINUX64:
-# ifdef _CALL_LINUX
- .quad .L.ffi_call_LINUX64,.TOC.@tocbase,0
- .type ffi_call_LINUX64,@function
- .text
-.L.ffi_call_LINUX64:
-# else
- .hidden .ffi_call_LINUX64
- .globl .ffi_call_LINUX64
- .quad .ffi_call_LINUX64,.TOC.@tocbase,0
- .size ffi_call_LINUX64,24
- .type .ffi_call_LINUX64,@function
- .text
-.ffi_call_LINUX64:
-# endif
-# endif
- mflr %r0
- std %r28, -32(%r1)
- std %r29, -24(%r1)
- std %r30, -16(%r1)
- std %r31, -8(%r1)
- std %r7, 8(%r1) /* closure, saved in cr field. */
- std %r0, 16(%r1)
-
- mr %r28, %r1 /* our AP. */
- .cfi_def_cfa_register 28
- .cfi_offset 65, 16
- .cfi_offset 31, -8
- .cfi_offset 30, -16
- .cfi_offset 29, -24
- .cfi_offset 28, -32
-
- stdux %r1, %r1, %r8
- mr %r31, %r6 /* flags, */
- mr %r30, %r5 /* rvalue, */
- mr %r29, %r4 /* function address. */
-/* Save toc pointer, not for the ffi_prep_args64 call, but for the later
- bctrl function call. */
-# if _CALL_ELF == 2
- std %r2, 24(%r1)
-# else
- std %r2, 40(%r1)
-# endif
-
- /* Call ffi_prep_args64. */
- mr %r4, %r1
-# if defined _CALL_LINUX || _CALL_ELF == 2
- bl ffi_prep_args64
-# else
- bl .ffi_prep_args64
-# endif
-
-# if _CALL_ELF == 2
- mr %r12, %r29
-# else
- ld %r12, 0(%r29)
- ld %r2, 8(%r29)
-# endif
- /* Now do the call. */
- /* Set up cr1 with bits 3-7 of the flags. */
- mtcrf 0xc0, %r31
-
- /* Get the address to call into CTR. */
- mtctr %r12
- /* Load all those argument registers. */
- addi %r29, %r28, -32-(8*8)
- ld %r3, (0*8)(%r29)
- ld %r4, (1*8)(%r29)
- ld %r5, (2*8)(%r29)
- ld %r6, (3*8)(%r29)
- bf- 5, 1f
- ld %r7, (4*8)(%r29)
- ld %r8, (5*8)(%r29)
- ld %r9, (6*8)(%r29)
- ld %r10, (7*8)(%r29)
-1:
-
- /* Load all the FP registers. */
- bf- 6, 2f
- addi %r29, %r29, -(14*8)
- lfd %f1, ( 1*8)(%r29)
- lfd %f2, ( 2*8)(%r29)
- lfd %f3, ( 3*8)(%r29)
- lfd %f4, ( 4*8)(%r29)
- lfd %f5, ( 5*8)(%r29)
- lfd %f6, ( 6*8)(%r29)
- lfd %f7, ( 7*8)(%r29)
- lfd %f8, ( 8*8)(%r29)
- lfd %f9, ( 9*8)(%r29)
- lfd %f10, (10*8)(%r29)
- lfd %f11, (11*8)(%r29)
- lfd %f12, (12*8)(%r29)
- lfd %f13, (13*8)(%r29)
-2:
-
- /* Load all the vector registers. */
- bf- 3, 3f
- addi %r29, %r29, -16
- lvx %v13, 0, %r29
- addi %r29, %r29, -16
- lvx %v12, 0, %r29
- addi %r29, %r29, -16
- lvx %v11, 0, %r29
- addi %r29, %r29, -16
- lvx %v10, 0, %r29
- addi %r29, %r29, -16
- lvx %v9, 0, %r29
- addi %r29, %r29, -16
- lvx %v8, 0, %r29
- addi %r29, %r29, -16
- lvx %v7, 0, %r29
- addi %r29, %r29, -16
- lvx %v6, 0, %r29
- addi %r29, %r29, -16
- lvx %v5, 0, %r29
- addi %r29, %r29, -16
- lvx %v4, 0, %r29
- addi %r29, %r29, -16
- lvx %v3, 0, %r29
- addi %r29, %r29, -16
- lvx %v2, 0, %r29
-3:
-
- /* Make the call. */
- ld %r11, 8(%r28)
- bctrl
-
- /* This must follow the call immediately, the unwinder
- uses this to find out if r2 has been saved or not. */
-# if _CALL_ELF == 2
- ld %r2, 24(%r1)
-# else
- ld %r2, 40(%r1)
-# endif
-
- /* Now, deal with the return value. */
- mtcrf 0x01, %r31
- bt 31, .Lstruct_return_value
- bt 30, .Ldone_return_value
- bt 29, .Lfp_return_value
- bt 28, .Lvec_return_value
- std %r3, 0(%r30)
- /* Fall through... */
-
-.Ldone_return_value:
- /* Restore the registers we used and return. */
- mr %r1, %r28
- .cfi_def_cfa_register 1
- ld %r0, 16(%r28)
- ld %r28, -32(%r28)
- mtlr %r0
- ld %r29, -24(%r1)
- ld %r30, -16(%r1)
- ld %r31, -8(%r1)
- blr
-
-.Lvec_return_value:
- stvx %v2, 0, %r30
- b .Ldone_return_value
-
-.Lfp_return_value:
- .cfi_def_cfa_register 28
- mtcrf 0x02, %r31 /* cr6 */
- bf 27, .Lfloat_return_value
- stfd %f1, 0(%r30)
- bf 26, .Ldone_return_value
- stfd %f2, 8(%r30)
- b .Ldone_return_value
-.Lfloat_return_value:
- stfs %f1, 0(%r30)
- b .Ldone_return_value
-
-.Lstruct_return_value:
- bf 29, .Lvec_homog_or_small_struct
- mtcrf 0x02, %r31 /* cr6 */
- bf 27, .Lfloat_homog_return_value
- stfd %f1, 0(%r30)
- stfd %f2, 8(%r30)
- stfd %f3, 16(%r30)
- stfd %f4, 24(%r30)
- stfd %f5, 32(%r30)
- stfd %f6, 40(%r30)
- stfd %f7, 48(%r30)
- stfd %f8, 56(%r30)
- b .Ldone_return_value
-
-.Lfloat_homog_return_value:
- stfs %f1, 0(%r30)
- stfs %f2, 4(%r30)
- stfs %f3, 8(%r30)
- stfs %f4, 12(%r30)
- stfs %f5, 16(%r30)
- stfs %f6, 20(%r30)
- stfs %f7, 24(%r30)
- stfs %f8, 28(%r30)
- b .Ldone_return_value
-
-.Lvec_homog_or_small_struct:
- bf 28, .Lsmall_struct
- stvx %v2, 0, %r30
- addi %r30, %r30, 16
- stvx %v3, 0, %r30
- addi %r30, %r30, 16
- stvx %v4, 0, %r30
- addi %r30, %r30, 16
- stvx %v5, 0, %r30
- addi %r30, %r30, 16
- stvx %v6, 0, %r30
- addi %r30, %r30, 16
- stvx %v7, 0, %r30
- addi %r30, %r30, 16
- stvx %v8, 0, %r30
- addi %r30, %r30, 16
- stvx %v9, 0, %r30
- b .Ldone_return_value
-
-.Lsmall_struct:
- std %r3, 0(%r30)
- std %r4, 8(%r30)
- b .Ldone_return_value
-
- .cfi_endproc
-# if _CALL_ELF == 2
- .size ffi_call_LINUX64,.-ffi_call_LINUX64
-# else
-# ifdef _CALL_LINUX
- .size ffi_call_LINUX64,.-.L.ffi_call_LINUX64
-# else
- .long 0
- .byte 0,12,0,1,128,4,0,0
- .size .ffi_call_LINUX64,.-.ffi_call_LINUX64
-# endif
-# endif
-
-#endif
-
-#if (defined __ELF__ && defined __linux__) || _CALL_ELF == 2
- .section .note.GNU-stack,"",@progbits
-#endif
+/* -----------------------------------------------------------------------
+ sysv.h - Copyright (c) 2003 Jakub Jelinek <jakub@redhat.com>
+ Copyright (c) 2008 Red Hat, Inc.
+
+ PowerPC64 Assembly glue.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#define LIBFFI_ASM
+#include <fficonfig.h>
+#include <ffi.h>
+
+#ifdef POWERPC64
+ .hidden ffi_call_LINUX64
+ .globl ffi_call_LINUX64
+ .text
+ .cfi_startproc
+# if _CALL_ELF == 2
+ffi_call_LINUX64:
+ addis %r2, %r12, .TOC.-ffi_call_LINUX64@ha
+ addi %r2, %r2, .TOC.-ffi_call_LINUX64@l
+ .localentry ffi_call_LINUX64, . - ffi_call_LINUX64
+# else
+ .section ".opd","aw"
+ .align 3
+ffi_call_LINUX64:
+# ifdef _CALL_LINUX
+ .quad .L.ffi_call_LINUX64,.TOC.@tocbase,0
+ .type ffi_call_LINUX64,@function
+ .text
+.L.ffi_call_LINUX64:
+# else
+ .hidden .ffi_call_LINUX64
+ .globl .ffi_call_LINUX64
+ .quad .ffi_call_LINUX64,.TOC.@tocbase,0
+ .size ffi_call_LINUX64,24
+ .type .ffi_call_LINUX64,@function
+ .text
+.ffi_call_LINUX64:
+# endif
+# endif
+ mflr %r0
+ std %r28, -32(%r1)
+ std %r29, -24(%r1)
+ std %r30, -16(%r1)
+ std %r31, -8(%r1)
+ std %r7, 8(%r1) /* closure, saved in cr field. */
+ std %r0, 16(%r1)
+
+ mr %r28, %r1 /* our AP. */
+ .cfi_def_cfa_register 28
+ .cfi_offset 65, 16
+ .cfi_offset 31, -8
+ .cfi_offset 30, -16
+ .cfi_offset 29, -24
+ .cfi_offset 28, -32
+
+ stdux %r1, %r1, %r8
+ mr %r31, %r6 /* flags, */
+ mr %r30, %r5 /* rvalue, */
+ mr %r29, %r4 /* function address. */
+/* Save toc pointer, not for the ffi_prep_args64 call, but for the later
+ bctrl function call. */
+# if _CALL_ELF == 2
+ std %r2, 24(%r1)
+# else
+ std %r2, 40(%r1)
+# endif
+
+ /* Call ffi_prep_args64. */
+ mr %r4, %r1
+# if defined _CALL_LINUX || _CALL_ELF == 2
+ bl ffi_prep_args64
+# else
+ bl .ffi_prep_args64
+# endif
+
+# if _CALL_ELF == 2
+ mr %r12, %r29
+# else
+ ld %r12, 0(%r29)
+ ld %r2, 8(%r29)
+# endif
+ /* Now do the call. */
+ /* Set up cr1 with bits 3-7 of the flags. */
+ mtcrf 0xc0, %r31
+
+ /* Get the address to call into CTR. */
+ mtctr %r12
+ /* Load all those argument registers. */
+ addi %r29, %r28, -32-(8*8)
+ ld %r3, (0*8)(%r29)
+ ld %r4, (1*8)(%r29)
+ ld %r5, (2*8)(%r29)
+ ld %r6, (3*8)(%r29)
+ bf- 5, 1f
+ ld %r7, (4*8)(%r29)
+ ld %r8, (5*8)(%r29)
+ ld %r9, (6*8)(%r29)
+ ld %r10, (7*8)(%r29)
+1:
+
+ /* Load all the FP registers. */
+ bf- 6, 2f
+ addi %r29, %r29, -(14*8)
+ lfd %f1, ( 1*8)(%r29)
+ lfd %f2, ( 2*8)(%r29)
+ lfd %f3, ( 3*8)(%r29)
+ lfd %f4, ( 4*8)(%r29)
+ lfd %f5, ( 5*8)(%r29)
+ lfd %f6, ( 6*8)(%r29)
+ lfd %f7, ( 7*8)(%r29)
+ lfd %f8, ( 8*8)(%r29)
+ lfd %f9, ( 9*8)(%r29)
+ lfd %f10, (10*8)(%r29)
+ lfd %f11, (11*8)(%r29)
+ lfd %f12, (12*8)(%r29)
+ lfd %f13, (13*8)(%r29)
+2:
+
+ /* Load all the vector registers. */
+ bf- 3, 3f
+ addi %r29, %r29, -16
+ lvx %v13, 0, %r29
+ addi %r29, %r29, -16
+ lvx %v12, 0, %r29
+ addi %r29, %r29, -16
+ lvx %v11, 0, %r29
+ addi %r29, %r29, -16
+ lvx %v10, 0, %r29
+ addi %r29, %r29, -16
+ lvx %v9, 0, %r29
+ addi %r29, %r29, -16
+ lvx %v8, 0, %r29
+ addi %r29, %r29, -16
+ lvx %v7, 0, %r29
+ addi %r29, %r29, -16
+ lvx %v6, 0, %r29
+ addi %r29, %r29, -16
+ lvx %v5, 0, %r29
+ addi %r29, %r29, -16
+ lvx %v4, 0, %r29
+ addi %r29, %r29, -16
+ lvx %v3, 0, %r29
+ addi %r29, %r29, -16
+ lvx %v2, 0, %r29
+3:
+
+ /* Make the call. */
+ ld %r11, 8(%r28)
+ bctrl
+
+ /* This must follow the call immediately, the unwinder
+ uses this to find out if r2 has been saved or not. */
+# if _CALL_ELF == 2
+ ld %r2, 24(%r1)
+# else
+ ld %r2, 40(%r1)
+# endif
+
+ /* Now, deal with the return value. */
+ mtcrf 0x01, %r31
+ bt 31, .Lstruct_return_value
+ bt 30, .Ldone_return_value
+ bt 29, .Lfp_return_value
+ bt 28, .Lvec_return_value
+ std %r3, 0(%r30)
+ /* Fall through... */
+
+.Ldone_return_value:
+ /* Restore the registers we used and return. */
+ mr %r1, %r28
+ .cfi_def_cfa_register 1
+ ld %r0, 16(%r28)
+ ld %r28, -32(%r28)
+ mtlr %r0
+ ld %r29, -24(%r1)
+ ld %r30, -16(%r1)
+ ld %r31, -8(%r1)
+ blr
+
+.Lvec_return_value:
+ stvx %v2, 0, %r30
+ b .Ldone_return_value
+
+.Lfp_return_value:
+ .cfi_def_cfa_register 28
+ mtcrf 0x02, %r31 /* cr6 */
+ bf 27, .Lfloat_return_value
+ stfd %f1, 0(%r30)
+ bf 26, .Ldone_return_value
+ stfd %f2, 8(%r30)
+ b .Ldone_return_value
+.Lfloat_return_value:
+ stfs %f1, 0(%r30)
+ b .Ldone_return_value
+
+.Lstruct_return_value:
+ bf 29, .Lvec_homog_or_small_struct
+ mtcrf 0x02, %r31 /* cr6 */
+ bf 27, .Lfloat_homog_return_value
+ stfd %f1, 0(%r30)
+ stfd %f2, 8(%r30)
+ stfd %f3, 16(%r30)
+ stfd %f4, 24(%r30)
+ stfd %f5, 32(%r30)
+ stfd %f6, 40(%r30)
+ stfd %f7, 48(%r30)
+ stfd %f8, 56(%r30)
+ b .Ldone_return_value
+
+.Lfloat_homog_return_value:
+ stfs %f1, 0(%r30)
+ stfs %f2, 4(%r30)
+ stfs %f3, 8(%r30)
+ stfs %f4, 12(%r30)
+ stfs %f5, 16(%r30)
+ stfs %f6, 20(%r30)
+ stfs %f7, 24(%r30)
+ stfs %f8, 28(%r30)
+ b .Ldone_return_value
+
+.Lvec_homog_or_small_struct:
+ bf 28, .Lsmall_struct
+ stvx %v2, 0, %r30
+ addi %r30, %r30, 16
+ stvx %v3, 0, %r30
+ addi %r30, %r30, 16
+ stvx %v4, 0, %r30
+ addi %r30, %r30, 16
+ stvx %v5, 0, %r30
+ addi %r30, %r30, 16
+ stvx %v6, 0, %r30
+ addi %r30, %r30, 16
+ stvx %v7, 0, %r30
+ addi %r30, %r30, 16
+ stvx %v8, 0, %r30
+ addi %r30, %r30, 16
+ stvx %v9, 0, %r30
+ b .Ldone_return_value
+
+.Lsmall_struct:
+ std %r3, 0(%r30)
+ std %r4, 8(%r30)
+ b .Ldone_return_value
+
+ .cfi_endproc
+# if _CALL_ELF == 2
+ .size ffi_call_LINUX64,.-ffi_call_LINUX64
+# else
+# ifdef _CALL_LINUX
+ .size ffi_call_LINUX64,.-.L.ffi_call_LINUX64
+# else
+ .long 0
+ .byte 0,12,0,1,128,4,0,0
+ .size .ffi_call_LINUX64,.-.ffi_call_LINUX64
+# endif
+# endif
+
+#endif
+
+#if (defined __ELF__ && defined __linux__) || _CALL_ELF == 2
+ .section .note.GNU-stack,"",@progbits
+#endif
diff --git a/contrib/restricted/libffi/src/powerpc/linux64_closure.S b/contrib/restricted/libffi/src/powerpc/linux64_closure.S
index 051d5410b8..d67e4bbbd1 100644
--- a/contrib/restricted/libffi/src/powerpc/linux64_closure.S
+++ b/contrib/restricted/libffi/src/powerpc/linux64_closure.S
@@ -1,552 +1,552 @@
-/* -----------------------------------------------------------------------
- sysv.h - Copyright (c) 2003 Jakub Jelinek <jakub@redhat.com>
- Copyright (c) 2008 Red Hat, Inc.
-
- PowerPC64 Assembly glue.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
-
- .file "linux64_closure.S"
-
-#ifdef POWERPC64
- FFI_HIDDEN (ffi_closure_LINUX64)
- .globl ffi_closure_LINUX64
- .text
- .cfi_startproc
-# if _CALL_ELF == 2
-ffi_closure_LINUX64:
- addis %r2, %r12, .TOC.-ffi_closure_LINUX64@ha
- addi %r2, %r2, .TOC.-ffi_closure_LINUX64@l
- .localentry ffi_closure_LINUX64, . - ffi_closure_LINUX64
-# else
- .section ".opd","aw"
- .align 3
-ffi_closure_LINUX64:
-# ifdef _CALL_LINUX
- .quad .L.ffi_closure_LINUX64,.TOC.@tocbase,0
- .type ffi_closure_LINUX64,@function
- .text
-.L.ffi_closure_LINUX64:
-# else
- FFI_HIDDEN (.ffi_closure_LINUX64)
- .globl .ffi_closure_LINUX64
- .quad .ffi_closure_LINUX64,.TOC.@tocbase,0
- .size ffi_closure_LINUX64,24
- .type .ffi_closure_LINUX64,@function
- .text
-.ffi_closure_LINUX64:
-# endif
-# endif
-
-# if _CALL_ELF == 2
-# ifdef __VEC__
-# 32 byte special reg save area + 64 byte parm save area
-# + 128 byte retval area + 13*8 fpr save area + 12*16 vec save area + round to 16
-# define STACKFRAME 528
-# else
-# 32 byte special reg save area + 64 byte parm save area
-# + 64 byte retval area + 13*8 fpr save area + round to 16
-# define STACKFRAME 272
-# endif
-# define PARMSAVE 32
-# define RETVAL PARMSAVE+64
-# else
-# 48 bytes special reg save area + 64 bytes parm save area
-# + 16 bytes retval area + 13*8 bytes fpr save area + round to 16
-# define STACKFRAME 240
-# define PARMSAVE 48
-# define RETVAL PARMSAVE+64
-# endif
-
-# if _CALL_ELF == 2
- ld %r12, FFI_TRAMPOLINE_SIZE(%r11) # closure->cif
- mflr %r0
- lwz %r12, 28(%r12) # cif->flags
- mtcrf 0x40, %r12
- addi %r12, %r1, PARMSAVE
- bt 7, 0f
- # Our caller has not allocated a parameter save area.
- # We need to allocate one here and use it to pass gprs to
- # ffi_closure_helper_LINUX64.
- addi %r12, %r1, -STACKFRAME+PARMSAVE
-0:
- # Save general regs into parm save area
- std %r3, 0(%r12)
- std %r4, 8(%r12)
- std %r5, 16(%r12)
- std %r6, 24(%r12)
- std %r7, 32(%r12)
- std %r8, 40(%r12)
- std %r9, 48(%r12)
- std %r10, 56(%r12)
-
- # load up the pointer to the parm save area
- mr %r7, %r12
-# else
- # copy r2 to r11 and load TOC into r2
- mr %r11, %r2
- ld %r2, 16(%r2)
-
- mflr %r0
- # Save general regs into parm save area
- # This is the parameter save area set up by our caller.
- std %r3, PARMSAVE+0(%r1)
- std %r4, PARMSAVE+8(%r1)
- std %r5, PARMSAVE+16(%r1)
- std %r6, PARMSAVE+24(%r1)
- std %r7, PARMSAVE+32(%r1)
- std %r8, PARMSAVE+40(%r1)
- std %r9, PARMSAVE+48(%r1)
- std %r10, PARMSAVE+56(%r1)
-
- # load up the pointer to the parm save area
- addi %r7, %r1, PARMSAVE
-# endif
- std %r0, 16(%r1)
-
- # closure->cif
- ld %r3, FFI_TRAMPOLINE_SIZE(%r11)
- # closure->fun
- ld %r4, FFI_TRAMPOLINE_SIZE+8(%r11)
- # closure->user_data
- ld %r5, FFI_TRAMPOLINE_SIZE+16(%r11)
-
-.Ldoclosure:
- # next save fpr 1 to fpr 13
- stfd %f1, -104+(0*8)(%r1)
- stfd %f2, -104+(1*8)(%r1)
- stfd %f3, -104+(2*8)(%r1)
- stfd %f4, -104+(3*8)(%r1)
- stfd %f5, -104+(4*8)(%r1)
- stfd %f6, -104+(5*8)(%r1)
- stfd %f7, -104+(6*8)(%r1)
- stfd %f8, -104+(7*8)(%r1)
- stfd %f9, -104+(8*8)(%r1)
- stfd %f10, -104+(9*8)(%r1)
- stfd %f11, -104+(10*8)(%r1)
- stfd %f12, -104+(11*8)(%r1)
- stfd %f13, -104+(12*8)(%r1)
-
- # load up the pointer to the saved fpr registers
- addi %r8, %r1, -104
-
-# ifdef __VEC__
- # load up the pointer to the saved vector registers
- # 8 bytes padding for 16-byte alignment at -112(%r1)
- addi %r9, %r8, -24
- stvx %v13, 0, %r9
- addi %r9, %r9, -16
- stvx %v12, 0, %r9
- addi %r9, %r9, -16
- stvx %v11, 0, %r9
- addi %r9, %r9, -16
- stvx %v10, 0, %r9
- addi %r9, %r9, -16
- stvx %v9, 0, %r9
- addi %r9, %r9, -16
- stvx %v8, 0, %r9
- addi %r9, %r9, -16
- stvx %v7, 0, %r9
- addi %r9, %r9, -16
- stvx %v6, 0, %r9
- addi %r9, %r9, -16
- stvx %v5, 0, %r9
- addi %r9, %r9, -16
- stvx %v4, 0, %r9
- addi %r9, %r9, -16
- stvx %v3, 0, %r9
- addi %r9, %r9, -16
- stvx %v2, 0, %r9
-# endif
-
- # load up the pointer to the result storage
- addi %r6, %r1, -STACKFRAME+RETVAL
-
- stdu %r1, -STACKFRAME(%r1)
- .cfi_def_cfa_offset STACKFRAME
- .cfi_offset 65, 16
-
- # make the call
-# if defined _CALL_LINUX || _CALL_ELF == 2
- bl ffi_closure_helper_LINUX64
-# else
- bl .ffi_closure_helper_LINUX64
-# endif
-.Lret:
-
- # now r3 contains the return type
- # so use it to look up in a table
- # so we know how to deal with each type
-
- # look up the proper starting point in table
- # by using return type as offset
- ld %r0, STACKFRAME+16(%r1)
- cmpldi %r3, FFI_V2_TYPE_SMALL_STRUCT
- bge .Lsmall
- mflr %r4 # move address of .Lret to r4
- sldi %r3, %r3, 4 # now multiply return type by 16
- addi %r4, %r4, .Lret_type0 - .Lret
- add %r3, %r3, %r4 # add contents of table to table address
- mtctr %r3
- bctr # jump to it
-
-# Each of the ret_typeX code fragments has to be exactly 16 bytes long
-# (4 instructions). For cache effectiveness we align to a 16 byte boundary
-# first.
- .align 4
-
-.Lret_type0:
-# case FFI_TYPE_VOID
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
- nop
-# case FFI_TYPE_INT
-# ifdef __LITTLE_ENDIAN__
- lwa %r3, RETVAL+0(%r1)
-# else
- lwa %r3, RETVAL+4(%r1)
-# endif
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-# case FFI_TYPE_FLOAT
- lfs %f1, RETVAL+0(%r1)
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-# case FFI_TYPE_DOUBLE
- lfd %f1, RETVAL+0(%r1)
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-# case FFI_TYPE_LONGDOUBLE
- lfd %f1, RETVAL+0(%r1)
- mtlr %r0
- lfd %f2, RETVAL+8(%r1)
- b .Lfinish
-# case FFI_TYPE_UINT8
-# ifdef __LITTLE_ENDIAN__
- lbz %r3, RETVAL+0(%r1)
-# else
- lbz %r3, RETVAL+7(%r1)
-# endif
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-# case FFI_TYPE_SINT8
-# ifdef __LITTLE_ENDIAN__
- lbz %r3, RETVAL+0(%r1)
-# else
- lbz %r3, RETVAL+7(%r1)
-# endif
- extsb %r3,%r3
- mtlr %r0
- b .Lfinish
-# case FFI_TYPE_UINT16
-# ifdef __LITTLE_ENDIAN__
- lhz %r3, RETVAL+0(%r1)
-# else
- lhz %r3, RETVAL+6(%r1)
-# endif
- mtlr %r0
-.Lfinish:
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-# case FFI_TYPE_SINT16
-# ifdef __LITTLE_ENDIAN__
- lha %r3, RETVAL+0(%r1)
-# else
- lha %r3, RETVAL+6(%r1)
-# endif
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-# case FFI_TYPE_UINT32
-# ifdef __LITTLE_ENDIAN__
- lwz %r3, RETVAL+0(%r1)
-# else
- lwz %r3, RETVAL+4(%r1)
-# endif
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-# case FFI_TYPE_SINT32
-# ifdef __LITTLE_ENDIAN__
- lwa %r3, RETVAL+0(%r1)
-# else
- lwa %r3, RETVAL+4(%r1)
-# endif
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-# case FFI_TYPE_UINT64
- ld %r3, RETVAL+0(%r1)
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-# case FFI_TYPE_SINT64
- ld %r3, RETVAL+0(%r1)
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-# case FFI_TYPE_STRUCT
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
- nop
-# case FFI_TYPE_POINTER
- ld %r3, RETVAL+0(%r1)
- mtlr %r0
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-# case FFI_V2_TYPE_VECTOR
- addi %r3, %r1, RETVAL
- lvx %v2, 0, %r3
- mtlr %r0
- b .Lfinish
-# case FFI_V2_TYPE_VECTOR_HOMOG
- addi %r3, %r1, RETVAL
- lvx %v2, 0, %r3
- addi %r3, %r3, 16
- b .Lmorevector
-# case FFI_V2_TYPE_FLOAT_HOMOG
- lfs %f1, RETVAL+0(%r1)
- lfs %f2, RETVAL+4(%r1)
- lfs %f3, RETVAL+8(%r1)
- b .Lmorefloat
-# case FFI_V2_TYPE_DOUBLE_HOMOG
- lfd %f1, RETVAL+0(%r1)
- lfd %f2, RETVAL+8(%r1)
- lfd %f3, RETVAL+16(%r1)
- lfd %f4, RETVAL+24(%r1)
- mtlr %r0
- lfd %f5, RETVAL+32(%r1)
- lfd %f6, RETVAL+40(%r1)
- lfd %f7, RETVAL+48(%r1)
- lfd %f8, RETVAL+56(%r1)
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-.Lmorevector:
- lvx %v3, 0, %r3
- addi %r3, %r3, 16
- lvx %v4, 0, %r3
- addi %r3, %r3, 16
- lvx %v5, 0, %r3
- mtlr %r0
- addi %r3, %r3, 16
- lvx %v6, 0, %r3
- addi %r3, %r3, 16
- lvx %v7, 0, %r3
- addi %r3, %r3, 16
- lvx %v8, 0, %r3
- addi %r3, %r3, 16
- lvx %v9, 0, %r3
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-.Lmorefloat:
- lfs %f4, RETVAL+12(%r1)
- mtlr %r0
- lfs %f5, RETVAL+16(%r1)
- lfs %f6, RETVAL+20(%r1)
- lfs %f7, RETVAL+24(%r1)
- lfs %f8, RETVAL+28(%r1)
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-.Lsmall:
-# ifdef __LITTLE_ENDIAN__
- ld %r3,RETVAL+0(%r1)
- mtlr %r0
- ld %r4,RETVAL+8(%r1)
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
-# else
- # A struct smaller than a dword is returned in the low bits of r3
- # ie. right justified. Larger structs are passed left justified
- # in r3 and r4. The return value area on the stack will have
- # the structs as they are usually stored in memory.
- cmpldi %r3, FFI_V2_TYPE_SMALL_STRUCT + 7 # size 8 bytes?
- neg %r5, %r3
- ld %r3,RETVAL+0(%r1)
- blt .Lsmalldown
- mtlr %r0
- ld %r4,RETVAL+8(%r1)
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset STACKFRAME
-.Lsmalldown:
- addi %r5, %r5, FFI_V2_TYPE_SMALL_STRUCT + 7
- mtlr %r0
- sldi %r5, %r5, 3
- addi %r1, %r1, STACKFRAME
- .cfi_def_cfa_offset 0
- srd %r3, %r3, %r5
- blr
-# endif
-
- .cfi_endproc
-# if _CALL_ELF == 2
- .size ffi_closure_LINUX64,.-ffi_closure_LINUX64
-# else
-# ifdef _CALL_LINUX
- .size ffi_closure_LINUX64,.-.L.ffi_closure_LINUX64
-# else
- .long 0
- .byte 0,12,0,1,128,0,0,0
- .size .ffi_closure_LINUX64,.-.ffi_closure_LINUX64
-# endif
-# endif
-
-
- FFI_HIDDEN (ffi_go_closure_linux64)
- .globl ffi_go_closure_linux64
- .text
- .cfi_startproc
-# if _CALL_ELF == 2
-ffi_go_closure_linux64:
- addis %r2, %r12, .TOC.-ffi_go_closure_linux64@ha
- addi %r2, %r2, .TOC.-ffi_go_closure_linux64@l
- .localentry ffi_go_closure_linux64, . - ffi_go_closure_linux64
-# else
- .section ".opd","aw"
- .align 3
-ffi_go_closure_linux64:
-# ifdef _CALL_LINUX
- .quad .L.ffi_go_closure_linux64,.TOC.@tocbase,0
- .type ffi_go_closure_linux64,@function
- .text
-.L.ffi_go_closure_linux64:
-# else
- FFI_HIDDEN (.ffi_go_closure_linux64)
- .globl .ffi_go_closure_linux64
- .quad .ffi_go_closure_linux64,.TOC.@tocbase,0
- .size ffi_go_closure_linux64,24
- .type .ffi_go_closure_linux64,@function
- .text
-.ffi_go_closure_linux64:
-# endif
-# endif
-
-# if _CALL_ELF == 2
- ld %r12, 8(%r11) # closure->cif
- mflr %r0
- lwz %r12, 28(%r12) # cif->flags
- mtcrf 0x40, %r12
- addi %r12, %r1, PARMSAVE
- bt 7, 0f
- # Our caller has not allocated a parameter save area.
- # We need to allocate one here and use it to pass gprs to
- # ffi_closure_helper_LINUX64.
- addi %r12, %r1, -STACKFRAME+PARMSAVE
-0:
- # Save general regs into parm save area
- std %r3, 0(%r12)
- std %r4, 8(%r12)
- std %r5, 16(%r12)
- std %r6, 24(%r12)
- std %r7, 32(%r12)
- std %r8, 40(%r12)
- std %r9, 48(%r12)
- std %r10, 56(%r12)
-
- # load up the pointer to the parm save area
- mr %r7, %r12
-# else
- mflr %r0
- # Save general regs into parm save area
- # This is the parameter save area set up by our caller.
- std %r3, PARMSAVE+0(%r1)
- std %r4, PARMSAVE+8(%r1)
- std %r5, PARMSAVE+16(%r1)
- std %r6, PARMSAVE+24(%r1)
- std %r7, PARMSAVE+32(%r1)
- std %r8, PARMSAVE+40(%r1)
- std %r9, PARMSAVE+48(%r1)
- std %r10, PARMSAVE+56(%r1)
-
- # load up the pointer to the parm save area
- addi %r7, %r1, PARMSAVE
-# endif
- std %r0, 16(%r1)
-
- # closure->cif
- ld %r3, 8(%r11)
- # closure->fun
- ld %r4, 16(%r11)
- # user_data
- mr %r5, %r11
- b .Ldoclosure
-
- .cfi_endproc
-# if _CALL_ELF == 2
- .size ffi_go_closure_linux64,.-ffi_go_closure_linux64
-# else
-# ifdef _CALL_LINUX
- .size ffi_go_closure_linux64,.-.L.ffi_go_closure_linux64
-# else
- .long 0
- .byte 0,12,0,1,128,0,0,0
- .size .ffi_go_closure_linux64,.-.ffi_go_closure_linux64
-# endif
-# endif
-#endif
-
-#if (defined __ELF__ && defined __linux__) || _CALL_ELF == 2
- .section .note.GNU-stack,"",@progbits
-#endif
+/* -----------------------------------------------------------------------
+ sysv.h - Copyright (c) 2003 Jakub Jelinek <jakub@redhat.com>
+ Copyright (c) 2008 Red Hat, Inc.
+
+ PowerPC64 Assembly glue.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+#define LIBFFI_ASM
+#include <fficonfig.h>
+#include <ffi.h>
+
+ .file "linux64_closure.S"
+
+#ifdef POWERPC64
+ FFI_HIDDEN (ffi_closure_LINUX64)
+ .globl ffi_closure_LINUX64
+ .text
+ .cfi_startproc
+# if _CALL_ELF == 2
+ffi_closure_LINUX64:
+ addis %r2, %r12, .TOC.-ffi_closure_LINUX64@ha
+ addi %r2, %r2, .TOC.-ffi_closure_LINUX64@l
+ .localentry ffi_closure_LINUX64, . - ffi_closure_LINUX64
+# else
+ .section ".opd","aw"
+ .align 3
+ffi_closure_LINUX64:
+# ifdef _CALL_LINUX
+ .quad .L.ffi_closure_LINUX64,.TOC.@tocbase,0
+ .type ffi_closure_LINUX64,@function
+ .text
+.L.ffi_closure_LINUX64:
+# else
+ FFI_HIDDEN (.ffi_closure_LINUX64)
+ .globl .ffi_closure_LINUX64
+ .quad .ffi_closure_LINUX64,.TOC.@tocbase,0
+ .size ffi_closure_LINUX64,24
+ .type .ffi_closure_LINUX64,@function
+ .text
+.ffi_closure_LINUX64:
+# endif
+# endif
+
+# if _CALL_ELF == 2
+# ifdef __VEC__
+# 32 byte special reg save area + 64 byte parm save area
+# + 128 byte retval area + 13*8 fpr save area + 12*16 vec save area + round to 16
+# define STACKFRAME 528
+# else
+# 32 byte special reg save area + 64 byte parm save area
+# + 64 byte retval area + 13*8 fpr save area + round to 16
+# define STACKFRAME 272
+# endif
+# define PARMSAVE 32
+# define RETVAL PARMSAVE+64
+# else
+# 48 bytes special reg save area + 64 bytes parm save area
+# + 16 bytes retval area + 13*8 bytes fpr save area + round to 16
+# define STACKFRAME 240
+# define PARMSAVE 48
+# define RETVAL PARMSAVE+64
+# endif
+
+# if _CALL_ELF == 2
+ ld %r12, FFI_TRAMPOLINE_SIZE(%r11) # closure->cif
+ mflr %r0
+ lwz %r12, 28(%r12) # cif->flags
+ mtcrf 0x40, %r12
+ addi %r12, %r1, PARMSAVE
+ bt 7, 0f
+ # Our caller has not allocated a parameter save area.
+ # We need to allocate one here and use it to pass gprs to
+ # ffi_closure_helper_LINUX64.
+ addi %r12, %r1, -STACKFRAME+PARMSAVE
+0:
+ # Save general regs into parm save area
+ std %r3, 0(%r12)
+ std %r4, 8(%r12)
+ std %r5, 16(%r12)
+ std %r6, 24(%r12)
+ std %r7, 32(%r12)
+ std %r8, 40(%r12)
+ std %r9, 48(%r12)
+ std %r10, 56(%r12)
+
+ # load up the pointer to the parm save area
+ mr %r7, %r12
+# else
+ # copy r2 to r11 and load TOC into r2
+ mr %r11, %r2
+ ld %r2, 16(%r2)
+
+ mflr %r0
+ # Save general regs into parm save area
+ # This is the parameter save area set up by our caller.
+ std %r3, PARMSAVE+0(%r1)
+ std %r4, PARMSAVE+8(%r1)
+ std %r5, PARMSAVE+16(%r1)
+ std %r6, PARMSAVE+24(%r1)
+ std %r7, PARMSAVE+32(%r1)
+ std %r8, PARMSAVE+40(%r1)
+ std %r9, PARMSAVE+48(%r1)
+ std %r10, PARMSAVE+56(%r1)
+
+ # load up the pointer to the parm save area
+ addi %r7, %r1, PARMSAVE
+# endif
+ std %r0, 16(%r1)
+
+ # closure->cif
+ ld %r3, FFI_TRAMPOLINE_SIZE(%r11)
+ # closure->fun
+ ld %r4, FFI_TRAMPOLINE_SIZE+8(%r11)
+ # closure->user_data
+ ld %r5, FFI_TRAMPOLINE_SIZE+16(%r11)
+
+.Ldoclosure:
+ # next save fpr 1 to fpr 13
+ stfd %f1, -104+(0*8)(%r1)
+ stfd %f2, -104+(1*8)(%r1)
+ stfd %f3, -104+(2*8)(%r1)
+ stfd %f4, -104+(3*8)(%r1)
+ stfd %f5, -104+(4*8)(%r1)
+ stfd %f6, -104+(5*8)(%r1)
+ stfd %f7, -104+(6*8)(%r1)
+ stfd %f8, -104+(7*8)(%r1)
+ stfd %f9, -104+(8*8)(%r1)
+ stfd %f10, -104+(9*8)(%r1)
+ stfd %f11, -104+(10*8)(%r1)
+ stfd %f12, -104+(11*8)(%r1)
+ stfd %f13, -104+(12*8)(%r1)
+
+ # load up the pointer to the saved fpr registers
+ addi %r8, %r1, -104
+
+# ifdef __VEC__
+ # load up the pointer to the saved vector registers
+ # 8 bytes padding for 16-byte alignment at -112(%r1)
+ addi %r9, %r8, -24
+ stvx %v13, 0, %r9
+ addi %r9, %r9, -16
+ stvx %v12, 0, %r9
+ addi %r9, %r9, -16
+ stvx %v11, 0, %r9
+ addi %r9, %r9, -16
+ stvx %v10, 0, %r9
+ addi %r9, %r9, -16
+ stvx %v9, 0, %r9
+ addi %r9, %r9, -16
+ stvx %v8, 0, %r9
+ addi %r9, %r9, -16
+ stvx %v7, 0, %r9
+ addi %r9, %r9, -16
+ stvx %v6, 0, %r9
+ addi %r9, %r9, -16
+ stvx %v5, 0, %r9
+ addi %r9, %r9, -16
+ stvx %v4, 0, %r9
+ addi %r9, %r9, -16
+ stvx %v3, 0, %r9
+ addi %r9, %r9, -16
+ stvx %v2, 0, %r9
+# endif
+
+ # load up the pointer to the result storage
+ addi %r6, %r1, -STACKFRAME+RETVAL
+
+ stdu %r1, -STACKFRAME(%r1)
+ .cfi_def_cfa_offset STACKFRAME
+ .cfi_offset 65, 16
+
+ # make the call
+# if defined _CALL_LINUX || _CALL_ELF == 2
+ bl ffi_closure_helper_LINUX64
+# else
+ bl .ffi_closure_helper_LINUX64
+# endif
+.Lret:
+
+ # now r3 contains the return type
+ # so use it to look up in a table
+ # so we know how to deal with each type
+
+ # look up the proper starting point in table
+ # by using return type as offset
+ ld %r0, STACKFRAME+16(%r1)
+ cmpldi %r3, FFI_V2_TYPE_SMALL_STRUCT
+ bge .Lsmall
+ mflr %r4 # move address of .Lret to r4
+ sldi %r3, %r3, 4 # now multiply return type by 16
+ addi %r4, %r4, .Lret_type0 - .Lret
+ add %r3, %r3, %r4 # add contents of table to table address
+ mtctr %r3
+ bctr # jump to it
+
+# Each of the ret_typeX code fragments has to be exactly 16 bytes long
+# (4 instructions). For cache effectiveness we align to a 16 byte boundary
+# first.
+ .align 4
+
+.Lret_type0:
+# case FFI_TYPE_VOID
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+ nop
+# case FFI_TYPE_INT
+# ifdef __LITTLE_ENDIAN__
+ lwa %r3, RETVAL+0(%r1)
+# else
+ lwa %r3, RETVAL+4(%r1)
+# endif
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+# case FFI_TYPE_FLOAT
+ lfs %f1, RETVAL+0(%r1)
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+# case FFI_TYPE_DOUBLE
+ lfd %f1, RETVAL+0(%r1)
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+# case FFI_TYPE_LONGDOUBLE
+ lfd %f1, RETVAL+0(%r1)
+ mtlr %r0
+ lfd %f2, RETVAL+8(%r1)
+ b .Lfinish
+# case FFI_TYPE_UINT8
+# ifdef __LITTLE_ENDIAN__
+ lbz %r3, RETVAL+0(%r1)
+# else
+ lbz %r3, RETVAL+7(%r1)
+# endif
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+# case FFI_TYPE_SINT8
+# ifdef __LITTLE_ENDIAN__
+ lbz %r3, RETVAL+0(%r1)
+# else
+ lbz %r3, RETVAL+7(%r1)
+# endif
+ extsb %r3,%r3
+ mtlr %r0
+ b .Lfinish
+# case FFI_TYPE_UINT16
+# ifdef __LITTLE_ENDIAN__
+ lhz %r3, RETVAL+0(%r1)
+# else
+ lhz %r3, RETVAL+6(%r1)
+# endif
+ mtlr %r0
+.Lfinish:
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+# case FFI_TYPE_SINT16
+# ifdef __LITTLE_ENDIAN__
+ lha %r3, RETVAL+0(%r1)
+# else
+ lha %r3, RETVAL+6(%r1)
+# endif
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+# case FFI_TYPE_UINT32
+# ifdef __LITTLE_ENDIAN__
+ lwz %r3, RETVAL+0(%r1)
+# else
+ lwz %r3, RETVAL+4(%r1)
+# endif
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+# case FFI_TYPE_SINT32
+# ifdef __LITTLE_ENDIAN__
+ lwa %r3, RETVAL+0(%r1)
+# else
+ lwa %r3, RETVAL+4(%r1)
+# endif
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+# case FFI_TYPE_UINT64
+ ld %r3, RETVAL+0(%r1)
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+# case FFI_TYPE_SINT64
+ ld %r3, RETVAL+0(%r1)
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+# case FFI_TYPE_STRUCT
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+ nop
+# case FFI_TYPE_POINTER
+ ld %r3, RETVAL+0(%r1)
+ mtlr %r0
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+# case FFI_V2_TYPE_VECTOR
+ addi %r3, %r1, RETVAL
+ lvx %v2, 0, %r3
+ mtlr %r0
+ b .Lfinish
+# case FFI_V2_TYPE_VECTOR_HOMOG
+ addi %r3, %r1, RETVAL
+ lvx %v2, 0, %r3
+ addi %r3, %r3, 16
+ b .Lmorevector
+# case FFI_V2_TYPE_FLOAT_HOMOG
+ lfs %f1, RETVAL+0(%r1)
+ lfs %f2, RETVAL+4(%r1)
+ lfs %f3, RETVAL+8(%r1)
+ b .Lmorefloat
+# case FFI_V2_TYPE_DOUBLE_HOMOG
+ lfd %f1, RETVAL+0(%r1)
+ lfd %f2, RETVAL+8(%r1)
+ lfd %f3, RETVAL+16(%r1)
+ lfd %f4, RETVAL+24(%r1)
+ mtlr %r0
+ lfd %f5, RETVAL+32(%r1)
+ lfd %f6, RETVAL+40(%r1)
+ lfd %f7, RETVAL+48(%r1)
+ lfd %f8, RETVAL+56(%r1)
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+.Lmorevector:
+ lvx %v3, 0, %r3
+ addi %r3, %r3, 16
+ lvx %v4, 0, %r3
+ addi %r3, %r3, 16
+ lvx %v5, 0, %r3
+ mtlr %r0
+ addi %r3, %r3, 16
+ lvx %v6, 0, %r3
+ addi %r3, %r3, 16
+ lvx %v7, 0, %r3
+ addi %r3, %r3, 16
+ lvx %v8, 0, %r3
+ addi %r3, %r3, 16
+ lvx %v9, 0, %r3
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+.Lmorefloat:
+ lfs %f4, RETVAL+12(%r1)
+ mtlr %r0
+ lfs %f5, RETVAL+16(%r1)
+ lfs %f6, RETVAL+20(%r1)
+ lfs %f7, RETVAL+24(%r1)
+ lfs %f8, RETVAL+28(%r1)
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+.Lsmall:
+# ifdef __LITTLE_ENDIAN__
+ ld %r3,RETVAL+0(%r1)
+ mtlr %r0
+ ld %r4,RETVAL+8(%r1)
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+# else
+ # A struct smaller than a dword is returned in the low bits of r3
+ # ie. right justified. Larger structs are passed left justified
+ # in r3 and r4. The return value area on the stack will have
+ # the structs as they are usually stored in memory.
+ cmpldi %r3, FFI_V2_TYPE_SMALL_STRUCT + 7 # size 8 bytes?
+ neg %r5, %r3
+ ld %r3,RETVAL+0(%r1)
+ blt .Lsmalldown
+ mtlr %r0
+ ld %r4,RETVAL+8(%r1)
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset STACKFRAME
+.Lsmalldown:
+ addi %r5, %r5, FFI_V2_TYPE_SMALL_STRUCT + 7
+ mtlr %r0
+ sldi %r5, %r5, 3
+ addi %r1, %r1, STACKFRAME
+ .cfi_def_cfa_offset 0
+ srd %r3, %r3, %r5
+ blr
+# endif
+
+ .cfi_endproc
+# if _CALL_ELF == 2
+ .size ffi_closure_LINUX64,.-ffi_closure_LINUX64
+# else
+# ifdef _CALL_LINUX
+ .size ffi_closure_LINUX64,.-.L.ffi_closure_LINUX64
+# else
+ .long 0
+ .byte 0,12,0,1,128,0,0,0
+ .size .ffi_closure_LINUX64,.-.ffi_closure_LINUX64
+# endif
+# endif
+
+
+ FFI_HIDDEN (ffi_go_closure_linux64)
+ .globl ffi_go_closure_linux64
+ .text
+ .cfi_startproc
+# if _CALL_ELF == 2
+ffi_go_closure_linux64:
+ addis %r2, %r12, .TOC.-ffi_go_closure_linux64@ha
+ addi %r2, %r2, .TOC.-ffi_go_closure_linux64@l
+ .localentry ffi_go_closure_linux64, . - ffi_go_closure_linux64
+# else
+ .section ".opd","aw"
+ .align 3
+ffi_go_closure_linux64:
+# ifdef _CALL_LINUX
+ .quad .L.ffi_go_closure_linux64,.TOC.@tocbase,0
+ .type ffi_go_closure_linux64,@function
+ .text
+.L.ffi_go_closure_linux64:
+# else
+ FFI_HIDDEN (.ffi_go_closure_linux64)
+ .globl .ffi_go_closure_linux64
+ .quad .ffi_go_closure_linux64,.TOC.@tocbase,0
+ .size ffi_go_closure_linux64,24
+ .type .ffi_go_closure_linux64,@function
+ .text
+.ffi_go_closure_linux64:
+# endif
+# endif
+
+# if _CALL_ELF == 2
+ ld %r12, 8(%r11) # closure->cif
+ mflr %r0
+ lwz %r12, 28(%r12) # cif->flags
+ mtcrf 0x40, %r12
+ addi %r12, %r1, PARMSAVE
+ bt 7, 0f
+ # Our caller has not allocated a parameter save area.
+ # We need to allocate one here and use it to pass gprs to
+ # ffi_closure_helper_LINUX64.
+ addi %r12, %r1, -STACKFRAME+PARMSAVE
+0:
+ # Save general regs into parm save area
+ std %r3, 0(%r12)
+ std %r4, 8(%r12)
+ std %r5, 16(%r12)
+ std %r6, 24(%r12)
+ std %r7, 32(%r12)
+ std %r8, 40(%r12)
+ std %r9, 48(%r12)
+ std %r10, 56(%r12)
+
+ # load up the pointer to the parm save area
+ mr %r7, %r12
+# else
+ mflr %r0
+ # Save general regs into parm save area
+ # This is the parameter save area set up by our caller.
+ std %r3, PARMSAVE+0(%r1)
+ std %r4, PARMSAVE+8(%r1)
+ std %r5, PARMSAVE+16(%r1)
+ std %r6, PARMSAVE+24(%r1)
+ std %r7, PARMSAVE+32(%r1)
+ std %r8, PARMSAVE+40(%r1)
+ std %r9, PARMSAVE+48(%r1)
+ std %r10, PARMSAVE+56(%r1)
+
+ # load up the pointer to the parm save area
+ addi %r7, %r1, PARMSAVE
+# endif
+ std %r0, 16(%r1)
+
+ # closure->cif
+ ld %r3, 8(%r11)
+ # closure->fun
+ ld %r4, 16(%r11)
+ # user_data
+ mr %r5, %r11
+ b .Ldoclosure
+
+ .cfi_endproc
+# if _CALL_ELF == 2
+ .size ffi_go_closure_linux64,.-ffi_go_closure_linux64
+# else
+# ifdef _CALL_LINUX
+ .size ffi_go_closure_linux64,.-.L.ffi_go_closure_linux64
+# else
+ .long 0
+ .byte 0,12,0,1,128,0,0,0
+ .size .ffi_go_closure_linux64,.-.ffi_go_closure_linux64
+# endif
+# endif
+#endif
+
+#if (defined __ELF__ && defined __linux__) || _CALL_ELF == 2
+ .section .note.GNU-stack,"",@progbits
+#endif
diff --git a/contrib/restricted/libffi/src/powerpc/ppc_closure.S b/contrib/restricted/libffi/src/powerpc/ppc_closure.S
index a88b732281..b6d209de86 100644
--- a/contrib/restricted/libffi/src/powerpc/ppc_closure.S
+++ b/contrib/restricted/libffi/src/powerpc/ppc_closure.S
@@ -1,397 +1,397 @@
-/* -----------------------------------------------------------------------
- sysv.h - Copyright (c) 2003 Jakub Jelinek <jakub@redhat.com>
- Copyright (c) 2008 Red Hat, Inc.
-
- PowerPC Assembly glue.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
-#include <powerpc/asm.h>
-
- .file "ppc_closure.S"
-
-#ifndef POWERPC64
-
-FFI_HIDDEN(ffi_closure_SYSV)
-ENTRY(ffi_closure_SYSV)
- .cfi_startproc
- stwu %r1,-144(%r1)
- .cfi_def_cfa_offset 144
- mflr %r0
- stw %r0,148(%r1)
- .cfi_offset 65, 4
-
-# we want to build up an areas for the parameters passed
-# in registers (both floating point and integer)
-
- # so first save gpr 3 to gpr 10 (aligned to 4)
- stw %r3, 16(%r1)
- stw %r4, 20(%r1)
- stw %r5, 24(%r1)
-
- # set up registers for the routine that does the work
-
- # closure->cif
- lwz %r3,FFI_TRAMPOLINE_SIZE(%r11)
- # closure->fun
- lwz %r4,FFI_TRAMPOLINE_SIZE+4(%r11)
- # closure->user_data
- lwz %r5,FFI_TRAMPOLINE_SIZE+8(%r11)
-
-.Ldoclosure:
- stw %r6, 28(%r1)
- stw %r7, 32(%r1)
- stw %r8, 36(%r1)
- stw %r9, 40(%r1)
- stw %r10,44(%r1)
-
-#ifndef __NO_FPRS__
- # next save fpr 1 to fpr 8 (aligned to 8)
- stfd %f1, 48(%r1)
- stfd %f2, 56(%r1)
- stfd %f3, 64(%r1)
- stfd %f4, 72(%r1)
- stfd %f5, 80(%r1)
- stfd %f6, 88(%r1)
- stfd %f7, 96(%r1)
- stfd %f8, 104(%r1)
-#endif
-
- # pointer to the result storage
- addi %r6,%r1,112
-
- # pointer to the saved gpr registers
- addi %r7,%r1,16
-
- # pointer to the saved fpr registers
- addi %r8,%r1,48
-
- # pointer to the outgoing parameter save area in the previous frame
- # i.e. the previous frame pointer + 8
- addi %r9,%r1,152
-
- # make the call
- bl ffi_closure_helper_SYSV@local
-.Lret:
- # now r3 contains the return type
- # so use it to look up in a table
- # so we know how to deal with each type
-
- # look up the proper starting point in table
- # by using return type as offset
-
- mflr %r4 # move address of .Lret to r4
- slwi %r3,%r3,4 # now multiply return type by 16
- addi %r4, %r4, .Lret_type0 - .Lret
- lwz %r0,148(%r1)
- add %r3,%r3,%r4 # add contents of table to table address
- mtctr %r3
- bctr # jump to it
-
-# Each of the ret_typeX code fragments has to be exactly 16 bytes long
-# (4 instructions). For cache effectiveness we align to a 16 byte boundary
-# first.
- .align 4
-# case FFI_TYPE_VOID
-.Lret_type0:
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
- nop
-
-# case FFI_TYPE_INT
- lwz %r3,112+0(%r1)
- mtlr %r0
-.Lfinish:
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_TYPE_FLOAT
-#ifndef __NO_FPRS__
- lfs %f1,112+0(%r1)
-#else
- nop
-#endif
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_TYPE_DOUBLE
-#ifndef __NO_FPRS__
- lfd %f1,112+0(%r1)
-#else
- nop
-#endif
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_TYPE_LONGDOUBLE
-#ifndef __NO_FPRS__
- lfd %f1,112+0(%r1)
- lfd %f2,112+8(%r1)
- mtlr %r0
- b .Lfinish
-#else
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
- nop
-#endif
-
-# case FFI_TYPE_UINT8
-#ifdef __LITTLE_ENDIAN__
- lbz %r3,112+0(%r1)
-#else
- lbz %r3,112+3(%r1)
-#endif
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_TYPE_SINT8
-#ifdef __LITTLE_ENDIAN__
- lbz %r3,112+0(%r1)
-#else
- lbz %r3,112+3(%r1)
-#endif
- extsb %r3,%r3
- mtlr %r0
- b .Lfinish
-
-# case FFI_TYPE_UINT16
-#ifdef __LITTLE_ENDIAN__
- lhz %r3,112+0(%r1)
-#else
- lhz %r3,112+2(%r1)
-#endif
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_TYPE_SINT16
-#ifdef __LITTLE_ENDIAN__
- lha %r3,112+0(%r1)
-#else
- lha %r3,112+2(%r1)
-#endif
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_TYPE_UINT32
- lwz %r3,112+0(%r1)
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_TYPE_SINT32
- lwz %r3,112+0(%r1)
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_TYPE_UINT64
- lwz %r3,112+0(%r1)
- lwz %r4,112+4(%r1)
- mtlr %r0
- b .Lfinish
-
-# case FFI_TYPE_SINT64
- lwz %r3,112+0(%r1)
- lwz %r4,112+4(%r1)
- mtlr %r0
- b .Lfinish
-
-# case FFI_TYPE_STRUCT
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
- nop
-
-# case FFI_TYPE_POINTER
- lwz %r3,112+0(%r1)
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_TYPE_UINT128
- lwz %r3,112+0(%r1)
- lwz %r4,112+4(%r1)
- lwz %r5,112+8(%r1)
- b .Luint128
-
-# The return types below are only used when the ABI type is FFI_SYSV.
-# case FFI_SYSV_TYPE_SMALL_STRUCT + 1. One byte struct.
- lbz %r3,112+0(%r1)
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_SYSV_TYPE_SMALL_STRUCT + 2. Two byte struct.
- lhz %r3,112+0(%r1)
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_SYSV_TYPE_SMALL_STRUCT + 3. Three byte struct.
- lwz %r3,112+0(%r1)
-#ifdef __LITTLE_ENDIAN__
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-#else
- srwi %r3,%r3,8
- mtlr %r0
- b .Lfinish
-#endif
-
-# case FFI_SYSV_TYPE_SMALL_STRUCT + 4. Four byte struct.
- lwz %r3,112+0(%r1)
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-
-# case FFI_SYSV_TYPE_SMALL_STRUCT + 5. Five byte struct.
- lwz %r3,112+0(%r1)
- lwz %r4,112+4(%r1)
-#ifdef __LITTLE_ENDIAN__
- mtlr %r0
- b .Lfinish
-#else
- li %r5,24
- b .Lstruct567
-#endif
-
-# case FFI_SYSV_TYPE_SMALL_STRUCT + 6. Six byte struct.
- lwz %r3,112+0(%r1)
- lwz %r4,112+4(%r1)
-#ifdef __LITTLE_ENDIAN__
- mtlr %r0
- b .Lfinish
-#else
- li %r5,16
- b .Lstruct567
-#endif
-
-# case FFI_SYSV_TYPE_SMALL_STRUCT + 7. Seven byte struct.
- lwz %r3,112+0(%r1)
- lwz %r4,112+4(%r1)
-#ifdef __LITTLE_ENDIAN__
- mtlr %r0
- b .Lfinish
-#else
- li %r5,8
- b .Lstruct567
-#endif
-
-# case FFI_SYSV_TYPE_SMALL_STRUCT + 8. Eight byte struct.
- lwz %r3,112+0(%r1)
- lwz %r4,112+4(%r1)
- mtlr %r0
- b .Lfinish
-
-#ifndef __LITTLE_ENDIAN__
-.Lstruct567:
- subfic %r6,%r5,32
- srw %r4,%r4,%r5
- slw %r6,%r3,%r6
- srw %r3,%r3,%r5
- or %r4,%r6,%r4
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_def_cfa_offset 144
-#endif
-
-.Luint128:
- lwz %r6,112+12(%r1)
- mtlr %r0
- addi %r1,%r1,144
- .cfi_def_cfa_offset 0
- blr
- .cfi_endproc
-END(ffi_closure_SYSV)
-
-
-FFI_HIDDEN(ffi_go_closure_sysv)
-ENTRY(ffi_go_closure_sysv)
- .cfi_startproc
- stwu %r1,-144(%r1)
- .cfi_def_cfa_offset 144
- mflr %r0
- stw %r0,148(%r1)
- .cfi_offset 65, 4
-
- stw %r3, 16(%r1)
- stw %r4, 20(%r1)
- stw %r5, 24(%r1)
-
- # closure->cif
- lwz %r3,4(%r11)
- # closure->fun
- lwz %r4,8(%r11)
- # user_data
- mr %r5,%r11
- b .Ldoclosure
- .cfi_endproc
-END(ffi_go_closure_sysv)
-
-#if defined __ELF__ && defined __linux__
- .section .note.GNU-stack,"",@progbits
-#endif
-#endif
+/* -----------------------------------------------------------------------
+ sysv.h - Copyright (c) 2003 Jakub Jelinek <jakub@redhat.com>
+ Copyright (c) 2008 Red Hat, Inc.
+
+ PowerPC Assembly glue.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+#define LIBFFI_ASM
+#include <fficonfig.h>
+#include <ffi.h>
+#include <powerpc/asm.h>
+
+ .file "ppc_closure.S"
+
+#ifndef POWERPC64
+
+FFI_HIDDEN(ffi_closure_SYSV)
+ENTRY(ffi_closure_SYSV)
+ .cfi_startproc
+ stwu %r1,-144(%r1)
+ .cfi_def_cfa_offset 144
+ mflr %r0
+ stw %r0,148(%r1)
+ .cfi_offset 65, 4
+
+# we want to build up an areas for the parameters passed
+# in registers (both floating point and integer)
+
+ # so first save gpr 3 to gpr 10 (aligned to 4)
+ stw %r3, 16(%r1)
+ stw %r4, 20(%r1)
+ stw %r5, 24(%r1)
+
+ # set up registers for the routine that does the work
+
+ # closure->cif
+ lwz %r3,FFI_TRAMPOLINE_SIZE(%r11)
+ # closure->fun
+ lwz %r4,FFI_TRAMPOLINE_SIZE+4(%r11)
+ # closure->user_data
+ lwz %r5,FFI_TRAMPOLINE_SIZE+8(%r11)
+
+.Ldoclosure:
+ stw %r6, 28(%r1)
+ stw %r7, 32(%r1)
+ stw %r8, 36(%r1)
+ stw %r9, 40(%r1)
+ stw %r10,44(%r1)
+
+#ifndef __NO_FPRS__
+ # next save fpr 1 to fpr 8 (aligned to 8)
+ stfd %f1, 48(%r1)
+ stfd %f2, 56(%r1)
+ stfd %f3, 64(%r1)
+ stfd %f4, 72(%r1)
+ stfd %f5, 80(%r1)
+ stfd %f6, 88(%r1)
+ stfd %f7, 96(%r1)
+ stfd %f8, 104(%r1)
+#endif
+
+ # pointer to the result storage
+ addi %r6,%r1,112
+
+ # pointer to the saved gpr registers
+ addi %r7,%r1,16
+
+ # pointer to the saved fpr registers
+ addi %r8,%r1,48
+
+ # pointer to the outgoing parameter save area in the previous frame
+ # i.e. the previous frame pointer + 8
+ addi %r9,%r1,152
+
+ # make the call
+ bl ffi_closure_helper_SYSV@local
+.Lret:
+ # now r3 contains the return type
+ # so use it to look up in a table
+ # so we know how to deal with each type
+
+ # look up the proper starting point in table
+ # by using return type as offset
+
+ mflr %r4 # move address of .Lret to r4
+ slwi %r3,%r3,4 # now multiply return type by 16
+ addi %r4, %r4, .Lret_type0 - .Lret
+ lwz %r0,148(%r1)
+ add %r3,%r3,%r4 # add contents of table to table address
+ mtctr %r3
+ bctr # jump to it
+
+# Each of the ret_typeX code fragments has to be exactly 16 bytes long
+# (4 instructions). For cache effectiveness we align to a 16 byte boundary
+# first.
+ .align 4
+# case FFI_TYPE_VOID
+.Lret_type0:
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+ nop
+
+# case FFI_TYPE_INT
+ lwz %r3,112+0(%r1)
+ mtlr %r0
+.Lfinish:
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_TYPE_FLOAT
+#ifndef __NO_FPRS__
+ lfs %f1,112+0(%r1)
+#else
+ nop
+#endif
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_TYPE_DOUBLE
+#ifndef __NO_FPRS__
+ lfd %f1,112+0(%r1)
+#else
+ nop
+#endif
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_TYPE_LONGDOUBLE
+#ifndef __NO_FPRS__
+ lfd %f1,112+0(%r1)
+ lfd %f2,112+8(%r1)
+ mtlr %r0
+ b .Lfinish
+#else
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+ nop
+#endif
+
+# case FFI_TYPE_UINT8
+#ifdef __LITTLE_ENDIAN__
+ lbz %r3,112+0(%r1)
+#else
+ lbz %r3,112+3(%r1)
+#endif
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_TYPE_SINT8
+#ifdef __LITTLE_ENDIAN__
+ lbz %r3,112+0(%r1)
+#else
+ lbz %r3,112+3(%r1)
+#endif
+ extsb %r3,%r3
+ mtlr %r0
+ b .Lfinish
+
+# case FFI_TYPE_UINT16
+#ifdef __LITTLE_ENDIAN__
+ lhz %r3,112+0(%r1)
+#else
+ lhz %r3,112+2(%r1)
+#endif
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_TYPE_SINT16
+#ifdef __LITTLE_ENDIAN__
+ lha %r3,112+0(%r1)
+#else
+ lha %r3,112+2(%r1)
+#endif
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_TYPE_UINT32
+ lwz %r3,112+0(%r1)
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_TYPE_SINT32
+ lwz %r3,112+0(%r1)
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_TYPE_UINT64
+ lwz %r3,112+0(%r1)
+ lwz %r4,112+4(%r1)
+ mtlr %r0
+ b .Lfinish
+
+# case FFI_TYPE_SINT64
+ lwz %r3,112+0(%r1)
+ lwz %r4,112+4(%r1)
+ mtlr %r0
+ b .Lfinish
+
+# case FFI_TYPE_STRUCT
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+ nop
+
+# case FFI_TYPE_POINTER
+ lwz %r3,112+0(%r1)
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_TYPE_UINT128
+ lwz %r3,112+0(%r1)
+ lwz %r4,112+4(%r1)
+ lwz %r5,112+8(%r1)
+ b .Luint128
+
+# The return types below are only used when the ABI type is FFI_SYSV.
+# case FFI_SYSV_TYPE_SMALL_STRUCT + 1. One byte struct.
+ lbz %r3,112+0(%r1)
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_SYSV_TYPE_SMALL_STRUCT + 2. Two byte struct.
+ lhz %r3,112+0(%r1)
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_SYSV_TYPE_SMALL_STRUCT + 3. Three byte struct.
+ lwz %r3,112+0(%r1)
+#ifdef __LITTLE_ENDIAN__
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+#else
+ srwi %r3,%r3,8
+ mtlr %r0
+ b .Lfinish
+#endif
+
+# case FFI_SYSV_TYPE_SMALL_STRUCT + 4. Four byte struct.
+ lwz %r3,112+0(%r1)
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+
+# case FFI_SYSV_TYPE_SMALL_STRUCT + 5. Five byte struct.
+ lwz %r3,112+0(%r1)
+ lwz %r4,112+4(%r1)
+#ifdef __LITTLE_ENDIAN__
+ mtlr %r0
+ b .Lfinish
+#else
+ li %r5,24
+ b .Lstruct567
+#endif
+
+# case FFI_SYSV_TYPE_SMALL_STRUCT + 6. Six byte struct.
+ lwz %r3,112+0(%r1)
+ lwz %r4,112+4(%r1)
+#ifdef __LITTLE_ENDIAN__
+ mtlr %r0
+ b .Lfinish
+#else
+ li %r5,16
+ b .Lstruct567
+#endif
+
+# case FFI_SYSV_TYPE_SMALL_STRUCT + 7. Seven byte struct.
+ lwz %r3,112+0(%r1)
+ lwz %r4,112+4(%r1)
+#ifdef __LITTLE_ENDIAN__
+ mtlr %r0
+ b .Lfinish
+#else
+ li %r5,8
+ b .Lstruct567
+#endif
+
+# case FFI_SYSV_TYPE_SMALL_STRUCT + 8. Eight byte struct.
+ lwz %r3,112+0(%r1)
+ lwz %r4,112+4(%r1)
+ mtlr %r0
+ b .Lfinish
+
+#ifndef __LITTLE_ENDIAN__
+.Lstruct567:
+ subfic %r6,%r5,32
+ srw %r4,%r4,%r5
+ slw %r6,%r3,%r6
+ srw %r3,%r3,%r5
+ or %r4,%r6,%r4
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_def_cfa_offset 144
+#endif
+
+.Luint128:
+ lwz %r6,112+12(%r1)
+ mtlr %r0
+ addi %r1,%r1,144
+ .cfi_def_cfa_offset 0
+ blr
+ .cfi_endproc
+END(ffi_closure_SYSV)
+
+
+FFI_HIDDEN(ffi_go_closure_sysv)
+ENTRY(ffi_go_closure_sysv)
+ .cfi_startproc
+ stwu %r1,-144(%r1)
+ .cfi_def_cfa_offset 144
+ mflr %r0
+ stw %r0,148(%r1)
+ .cfi_offset 65, 4
+
+ stw %r3, 16(%r1)
+ stw %r4, 20(%r1)
+ stw %r5, 24(%r1)
+
+ # closure->cif
+ lwz %r3,4(%r11)
+ # closure->fun
+ lwz %r4,8(%r11)
+ # user_data
+ mr %r5,%r11
+ b .Ldoclosure
+ .cfi_endproc
+END(ffi_go_closure_sysv)
+
+#if defined __ELF__ && defined __linux__
+ .section .note.GNU-stack,"",@progbits
+#endif
+#endif
diff --git a/contrib/restricted/libffi/src/powerpc/sysv.S b/contrib/restricted/libffi/src/powerpc/sysv.S
index 47e0d509fa..1474ce702b 100644
--- a/contrib/restricted/libffi/src/powerpc/sysv.S
+++ b/contrib/restricted/libffi/src/powerpc/sysv.S
@@ -1,175 +1,175 @@
-/* -----------------------------------------------------------------------
- sysv.S - Copyright (c) 1998 Geoffrey Keating
- Copyright (C) 2007 Free Software Foundation, Inc
-
- PowerPC Assembly glue.
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
-#include <powerpc/asm.h>
-
-#ifndef POWERPC64
-FFI_HIDDEN(ffi_call_SYSV)
-ENTRY(ffi_call_SYSV)
- .cfi_startproc
- /* Save the old stack pointer as AP. */
- mr %r10,%r1
- .cfi_def_cfa_register 10
-
- /* Allocate the stack space we need. */
- stwux %r1,%r1,%r8
- /* Save registers we use. */
- mflr %r9
- stw %r28,-16(%r10)
- stw %r29,-12(%r10)
- stw %r30, -8(%r10)
- stw %r31, -4(%r10)
- stw %r9, 4(%r10)
- .cfi_offset 65, 4
- .cfi_offset 31, -4
- .cfi_offset 30, -8
- .cfi_offset 29, -12
- .cfi_offset 28, -16
-
- /* Save arguments over call... */
- stw %r7, -20(%r10) /* closure, */
- mr %r31,%r6 /* flags, */
- mr %r30,%r5 /* rvalue, */
- mr %r29,%r4 /* function address, */
- mr %r28,%r10 /* our AP. */
- .cfi_def_cfa_register 28
-
- /* Call ffi_prep_args_SYSV. */
- mr %r4,%r1
- bl ffi_prep_args_SYSV@local
-
- /* Now do the call. */
- /* Set up cr1 with bits 4-7 of the flags. */
- mtcrf 0x40,%r31
- /* Get the address to call into CTR. */
- mtctr %r29
- /* Load all those argument registers. */
- lwz %r3,-24-(8*4)(%r28)
- lwz %r4,-24-(7*4)(%r28)
- lwz %r5,-24-(6*4)(%r28)
- lwz %r6,-24-(5*4)(%r28)
- bf- 5,1f
- nop
- lwz %r7,-24-(4*4)(%r28)
- lwz %r8,-24-(3*4)(%r28)
- lwz %r9,-24-(2*4)(%r28)
- lwz %r10,-24-(1*4)(%r28)
- nop
-1:
-
-#ifndef __NO_FPRS__
- /* Load all the FP registers. */
- bf- 6,2f
- lfd %f1,-24-(8*4)-(8*8)(%r28)
- lfd %f2,-24-(8*4)-(7*8)(%r28)
- lfd %f3,-24-(8*4)-(6*8)(%r28)
- lfd %f4,-24-(8*4)-(5*8)(%r28)
- nop
- lfd %f5,-24-(8*4)-(4*8)(%r28)
- lfd %f6,-24-(8*4)-(3*8)(%r28)
- lfd %f7,-24-(8*4)-(2*8)(%r28)
- lfd %f8,-24-(8*4)-(1*8)(%r28)
-#endif
-2:
-
- /* Make the call. */
- lwz %r11, -20(%r28)
- bctrl
-
- /* Now, deal with the return value. */
- mtcrf 0x01,%r31 /* cr7 */
- bt- 31,L(small_struct_return_value)
- bt- 30,L(done_return_value)
-#ifndef __NO_FPRS__
- bt- 29,L(fp_return_value)
-#endif
- stw %r3,0(%r30)
- bf+ 28,L(done_return_value)
- stw %r4,4(%r30)
- mtcrf 0x02,%r31 /* cr6 */
- bf 27,L(done_return_value)
- stw %r5,8(%r30)
- stw %r6,12(%r30)
- /* Fall through... */
-
-L(done_return_value):
- /* Restore the registers we used and return. */
- lwz %r9, 4(%r28)
- lwz %r31, -4(%r28)
- mtlr %r9
- lwz %r30, -8(%r28)
- lwz %r29,-12(%r28)
- lwz %r28,-16(%r28)
- .cfi_remember_state
- /* At this point we don't have a cfa register. Say all our
- saved regs have been restored. */
- .cfi_same_value 65
- .cfi_same_value 31
- .cfi_same_value 30
- .cfi_same_value 29
- .cfi_same_value 28
- /* Hopefully this works.. */
- .cfi_def_cfa_register 1
- .cfi_offset 1, 0
- lwz %r1,0(%r1)
- .cfi_same_value 1
- blr
-
-#ifndef __NO_FPRS__
-L(fp_return_value):
- .cfi_restore_state
- bf 28,L(float_return_value)
- stfd %f1,0(%r30)
- mtcrf 0x02,%r31 /* cr6 */
- bf 27,L(done_return_value)
- stfd %f2,8(%r30)
- b L(done_return_value)
-L(float_return_value):
- stfs %f1,0(%r30)
- b L(done_return_value)
-#endif
-
-L(small_struct_return_value):
- /*
- * The C code always allocates a properly-aligned 8-byte bounce
- * buffer to make this assembly code very simple. Just write out
- * r3 and r4 to the buffer to allow the C code to handle the rest.
- */
- stw %r3, 0(%r30)
- stw %r4, 4(%r30)
- b L(done_return_value)
- .cfi_endproc
-
-END(ffi_call_SYSV)
-
-#if defined __ELF__ && defined __linux__
- .section .note.GNU-stack,"",@progbits
-#endif
-#endif
+/* -----------------------------------------------------------------------
+ sysv.S - Copyright (c) 1998 Geoffrey Keating
+ Copyright (C) 2007 Free Software Foundation, Inc
+
+ PowerPC Assembly glue.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#define LIBFFI_ASM
+#include <fficonfig.h>
+#include <ffi.h>
+#include <powerpc/asm.h>
+
+#ifndef POWERPC64
+FFI_HIDDEN(ffi_call_SYSV)
+ENTRY(ffi_call_SYSV)
+ .cfi_startproc
+ /* Save the old stack pointer as AP. */
+ mr %r10,%r1
+ .cfi_def_cfa_register 10
+
+ /* Allocate the stack space we need. */
+ stwux %r1,%r1,%r8
+ /* Save registers we use. */
+ mflr %r9
+ stw %r28,-16(%r10)
+ stw %r29,-12(%r10)
+ stw %r30, -8(%r10)
+ stw %r31, -4(%r10)
+ stw %r9, 4(%r10)
+ .cfi_offset 65, 4
+ .cfi_offset 31, -4
+ .cfi_offset 30, -8
+ .cfi_offset 29, -12
+ .cfi_offset 28, -16
+
+ /* Save arguments over call... */
+ stw %r7, -20(%r10) /* closure, */
+ mr %r31,%r6 /* flags, */
+ mr %r30,%r5 /* rvalue, */
+ mr %r29,%r4 /* function address, */
+ mr %r28,%r10 /* our AP. */
+ .cfi_def_cfa_register 28
+
+ /* Call ffi_prep_args_SYSV. */
+ mr %r4,%r1
+ bl ffi_prep_args_SYSV@local
+
+ /* Now do the call. */
+ /* Set up cr1 with bits 4-7 of the flags. */
+ mtcrf 0x40,%r31
+ /* Get the address to call into CTR. */
+ mtctr %r29
+ /* Load all those argument registers. */
+ lwz %r3,-24-(8*4)(%r28)
+ lwz %r4,-24-(7*4)(%r28)
+ lwz %r5,-24-(6*4)(%r28)
+ lwz %r6,-24-(5*4)(%r28)
+ bf- 5,1f
+ nop
+ lwz %r7,-24-(4*4)(%r28)
+ lwz %r8,-24-(3*4)(%r28)
+ lwz %r9,-24-(2*4)(%r28)
+ lwz %r10,-24-(1*4)(%r28)
+ nop
+1:
+
+#ifndef __NO_FPRS__
+ /* Load all the FP registers. */
+ bf- 6,2f
+ lfd %f1,-24-(8*4)-(8*8)(%r28)
+ lfd %f2,-24-(8*4)-(7*8)(%r28)
+ lfd %f3,-24-(8*4)-(6*8)(%r28)
+ lfd %f4,-24-(8*4)-(5*8)(%r28)
+ nop
+ lfd %f5,-24-(8*4)-(4*8)(%r28)
+ lfd %f6,-24-(8*4)-(3*8)(%r28)
+ lfd %f7,-24-(8*4)-(2*8)(%r28)
+ lfd %f8,-24-(8*4)-(1*8)(%r28)
+#endif
+2:
+
+ /* Make the call. */
+ lwz %r11, -20(%r28)
+ bctrl
+
+ /* Now, deal with the return value. */
+ mtcrf 0x01,%r31 /* cr7 */
+ bt- 31,L(small_struct_return_value)
+ bt- 30,L(done_return_value)
+#ifndef __NO_FPRS__
+ bt- 29,L(fp_return_value)
+#endif
+ stw %r3,0(%r30)
+ bf+ 28,L(done_return_value)
+ stw %r4,4(%r30)
+ mtcrf 0x02,%r31 /* cr6 */
+ bf 27,L(done_return_value)
+ stw %r5,8(%r30)
+ stw %r6,12(%r30)
+ /* Fall through... */
+
+L(done_return_value):
+ /* Restore the registers we used and return. */
+ lwz %r9, 4(%r28)
+ lwz %r31, -4(%r28)
+ mtlr %r9
+ lwz %r30, -8(%r28)
+ lwz %r29,-12(%r28)
+ lwz %r28,-16(%r28)
+ .cfi_remember_state
+ /* At this point we don't have a cfa register. Say all our
+ saved regs have been restored. */
+ .cfi_same_value 65
+ .cfi_same_value 31
+ .cfi_same_value 30
+ .cfi_same_value 29
+ .cfi_same_value 28
+ /* Hopefully this works.. */
+ .cfi_def_cfa_register 1
+ .cfi_offset 1, 0
+ lwz %r1,0(%r1)
+ .cfi_same_value 1
+ blr
+
+#ifndef __NO_FPRS__
+L(fp_return_value):
+ .cfi_restore_state
+ bf 28,L(float_return_value)
+ stfd %f1,0(%r30)
+ mtcrf 0x02,%r31 /* cr6 */
+ bf 27,L(done_return_value)
+ stfd %f2,8(%r30)
+ b L(done_return_value)
+L(float_return_value):
+ stfs %f1,0(%r30)
+ b L(done_return_value)
+#endif
+
+L(small_struct_return_value):
+ /*
+ * The C code always allocates a properly-aligned 8-byte bounce
+ * buffer to make this assembly code very simple. Just write out
+ * r3 and r4 to the buffer to allow the C code to handle the rest.
+ */
+ stw %r3, 0(%r30)
+ stw %r4, 4(%r30)
+ b L(done_return_value)
+ .cfi_endproc
+
+END(ffi_call_SYSV)
+
+#if defined __ELF__ && defined __linux__
+ .section .note.GNU-stack,"",@progbits
+#endif
+#endif
diff --git a/contrib/restricted/libffi/src/prep_cif.c b/contrib/restricted/libffi/src/prep_cif.c
index 0aece251b9..06c6544036 100644
--- a/contrib/restricted/libffi/src/prep_cif.c
+++ b/contrib/restricted/libffi/src/prep_cif.c
@@ -29,12 +29,12 @@
/* Round up to FFI_SIZEOF_ARG. */
-#define STACK_ARG_SIZE(x) FFI_ALIGN(x, FFI_SIZEOF_ARG)
+#define STACK_ARG_SIZE(x) FFI_ALIGN(x, FFI_SIZEOF_ARG)
/* Perform machine independent initialization of aggregate type
specifications. */
-static ffi_status initialize_aggregate(ffi_type *arg, size_t *offsets)
+static ffi_status initialize_aggregate(ffi_type *arg, size_t *offsets)
{
ffi_type **ptr;
@@ -52,15 +52,15 @@ static ffi_status initialize_aggregate(ffi_type *arg, size_t *offsets)
while ((*ptr) != NULL)
{
if (UNLIKELY(((*ptr)->size == 0)
- && (initialize_aggregate((*ptr), NULL) != FFI_OK)))
+ && (initialize_aggregate((*ptr), NULL) != FFI_OK)))
return FFI_BAD_TYPEDEF;
/* Perform a sanity check on the argument type */
FFI_ASSERT_VALID_TYPE(*ptr);
- arg->size = FFI_ALIGN(arg->size, (*ptr)->alignment);
- if (offsets)
- *offsets++ = arg->size;
+ arg->size = FFI_ALIGN(arg->size, (*ptr)->alignment);
+ if (offsets)
+ *offsets++ = arg->size;
arg->size += (*ptr)->size;
arg->alignment = (arg->alignment > (*ptr)->alignment) ?
@@ -76,15 +76,15 @@ static ffi_status initialize_aggregate(ffi_type *arg, size_t *offsets)
struct A { long a; char b; }; struct B { struct A x; char y; };
should find y at an offset of 2*sizeof(long) and result in a
total size of 3*sizeof(long). */
- arg->size = FFI_ALIGN (arg->size, arg->alignment);
-
- /* On some targets, the ABI defines that structures have an additional
- alignment beyond the "natural" one based on their elements. */
-#ifdef FFI_AGGREGATE_ALIGNMENT
- if (FFI_AGGREGATE_ALIGNMENT > arg->alignment)
- arg->alignment = FFI_AGGREGATE_ALIGNMENT;
-#endif
-
+ arg->size = FFI_ALIGN (arg->size, arg->alignment);
+
+ /* On some targets, the ABI defines that structures have an additional
+ alignment beyond the "natural" one based on their elements. */
+#ifdef FFI_AGGREGATE_ALIGNMENT
+ if (FFI_AGGREGATE_ALIGNMENT > arg->alignment)
+ arg->alignment = FFI_AGGREGATE_ALIGNMENT;
+#endif
+
if (arg->size == 0)
return FFI_BAD_TYPEDEF;
else
@@ -129,27 +129,27 @@ ffi_status FFI_HIDDEN ffi_prep_cif_core(ffi_cif *cif, ffi_abi abi,
cif->rtype = rtype;
cif->flags = 0;
-#ifdef _M_ARM64
- cif->is_variadic = isvariadic;
-#endif
-#if HAVE_LONG_DOUBLE_VARIANT
- ffi_prep_types (abi);
-#endif
+#ifdef _M_ARM64
+ cif->is_variadic = isvariadic;
+#endif
+#if HAVE_LONG_DOUBLE_VARIANT
+ ffi_prep_types (abi);
+#endif
/* Initialize the return type if necessary */
- if ((cif->rtype->size == 0)
- && (initialize_aggregate(cif->rtype, NULL) != FFI_OK))
+ if ((cif->rtype->size == 0)
+ && (initialize_aggregate(cif->rtype, NULL) != FFI_OK))
return FFI_BAD_TYPEDEF;
-#ifndef FFI_TARGET_HAS_COMPLEX_TYPE
- if (rtype->type == FFI_TYPE_COMPLEX)
- abort();
-#endif
+#ifndef FFI_TARGET_HAS_COMPLEX_TYPE
+ if (rtype->type == FFI_TYPE_COMPLEX)
+ abort();
+#endif
/* Perform a sanity check on the return type */
FFI_ASSERT_VALID_TYPE(cif->rtype);
/* x86, x86-64 and s390 stack space allocation is handled in prep_machdep. */
-#if !defined FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+#if !defined FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
/* Make space for the return structure pointer */
if (cif->rtype->type == FFI_TYPE_STRUCT
#ifdef TILE
@@ -158,9 +158,9 @@ ffi_status FFI_HIDDEN ffi_prep_cif_core(ffi_cif *cif, ffi_abi abi,
#ifdef XTENSA
&& (cif->rtype->size > 16)
#endif
-#ifdef NIOS2
- && (cif->rtype->size > 8)
-#endif
+#ifdef NIOS2
+ && (cif->rtype->size > 8)
+#endif
)
bytes = STACK_ARG_SIZE(sizeof(void*));
#endif
@@ -169,23 +169,23 @@ ffi_status FFI_HIDDEN ffi_prep_cif_core(ffi_cif *cif, ffi_abi abi,
{
/* Initialize any uninitialized aggregate type definitions */
- if (((*ptr)->size == 0)
- && (initialize_aggregate((*ptr), NULL) != FFI_OK))
+ if (((*ptr)->size == 0)
+ && (initialize_aggregate((*ptr), NULL) != FFI_OK))
return FFI_BAD_TYPEDEF;
-#ifndef FFI_TARGET_HAS_COMPLEX_TYPE
- if ((*ptr)->type == FFI_TYPE_COMPLEX)
- abort();
-#endif
+#ifndef FFI_TARGET_HAS_COMPLEX_TYPE
+ if ((*ptr)->type == FFI_TYPE_COMPLEX)
+ abort();
+#endif
/* Perform a sanity check on the argument type, do this
check after the initialization. */
FFI_ASSERT_VALID_TYPE(*ptr);
-#if !defined FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+#if !defined FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
{
/* Add any padding if necessary */
if (((*ptr)->alignment - 1) & bytes)
- bytes = (unsigned)FFI_ALIGN(bytes, (*ptr)->alignment);
+ bytes = (unsigned)FFI_ALIGN(bytes, (*ptr)->alignment);
#ifdef TILE
if (bytes < 10 * FFI_SIZEOF_ARG &&
@@ -201,7 +201,7 @@ ffi_status FFI_HIDDEN ffi_prep_cif_core(ffi_cif *cif, ffi_abi abi,
bytes = 6*4;
#endif
- bytes += (unsigned int)STACK_ARG_SIZE((*ptr)->size);
+ bytes += (unsigned int)STACK_ARG_SIZE((*ptr)->size);
}
#endif
}
@@ -246,18 +246,18 @@ ffi_prep_closure (ffi_closure* closure,
}
#endif
-
-ffi_status
-ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type, size_t *offsets)
-{
- if (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI))
- return FFI_BAD_ABI;
- if (struct_type->type != FFI_TYPE_STRUCT)
- return FFI_BAD_TYPEDEF;
-
-#if HAVE_LONG_DOUBLE_VARIANT
- ffi_prep_types (abi);
-#endif
-
- return initialize_aggregate(struct_type, offsets);
-}
+
+ffi_status
+ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type, size_t *offsets)
+{
+ if (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI))
+ return FFI_BAD_ABI;
+ if (struct_type->type != FFI_TYPE_STRUCT)
+ return FFI_BAD_TYPEDEF;
+
+#if HAVE_LONG_DOUBLE_VARIANT
+ ffi_prep_types (abi);
+#endif
+
+ return initialize_aggregate(struct_type, offsets);
+}
diff --git a/contrib/restricted/libffi/src/raw_api.c b/contrib/restricted/libffi/src/raw_api.c
index c121c24f50..be156116cb 100644
--- a/contrib/restricted/libffi/src/raw_api.c
+++ b/contrib/restricted/libffi/src/raw_api.c
@@ -43,10 +43,10 @@ ffi_raw_size (ffi_cif *cif)
{
#if !FFI_NO_STRUCTS
if ((*at)->type == FFI_TYPE_STRUCT)
- result += FFI_ALIGN (sizeof (void*), FFI_SIZEOF_ARG);
+ result += FFI_ALIGN (sizeof (void*), FFI_SIZEOF_ARG);
else
#endif
- result += FFI_ALIGN ((*at)->size, FFI_SIZEOF_ARG);
+ result += FFI_ALIGN ((*at)->size, FFI_SIZEOF_ARG);
}
return result;
@@ -88,17 +88,17 @@ ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args)
break;
#endif
- case FFI_TYPE_COMPLEX:
- *args = (raw++)->ptr;
- break;
-
+ case FFI_TYPE_COMPLEX:
+ *args = (raw++)->ptr;
+ break;
+
case FFI_TYPE_POINTER:
*args = (void*) &(raw++)->ptr;
break;
default:
*args = raw;
- raw += FFI_ALIGN ((*tp)->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG;
+ raw += FFI_ALIGN ((*tp)->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG;
}
}
@@ -116,14 +116,14 @@ ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args)
}
else
#endif
- if ((*tp)->type == FFI_TYPE_COMPLEX)
+ if ((*tp)->type == FFI_TYPE_COMPLEX)
+ {
+ *args = (raw++)->ptr;
+ }
+ else
{
- *args = (raw++)->ptr;
- }
- else
- {
*args = (void*) raw;
- raw += FFI_ALIGN ((*tp)->size, sizeof (void*)) / sizeof (void*);
+ raw += FFI_ALIGN ((*tp)->size, sizeof (void*)) / sizeof (void*);
}
}
@@ -176,17 +176,17 @@ ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw)
break;
#endif
- case FFI_TYPE_COMPLEX:
- (raw++)->ptr = *args;
- break;
-
+ case FFI_TYPE_COMPLEX:
+ (raw++)->ptr = *args;
+ break;
+
case FFI_TYPE_POINTER:
(raw++)->ptr = **(void***) args;
break;
default:
memcpy ((void*) raw->data, (void*)*args, (*tp)->size);
- raw += FFI_ALIGN ((*tp)->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG;
+ raw += FFI_ALIGN ((*tp)->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG;
}
}
}
diff --git a/contrib/restricted/libffi/src/types.c b/contrib/restricted/libffi/src/types.c
index 341252ee60..9ec27f6cf3 100644
--- a/contrib/restricted/libffi/src/types.c
+++ b/contrib/restricted/libffi/src/types.c
@@ -33,59 +33,59 @@
/* Type definitions */
-#define FFI_TYPEDEF(name, type, id, maybe_const)\
+#define FFI_TYPEDEF(name, type, id, maybe_const)\
struct struct_align_##name { \
char c; \
type x; \
}; \
-FFI_EXTERN \
-maybe_const ffi_type ffi_type_##name = { \
+FFI_EXTERN \
+maybe_const ffi_type ffi_type_##name = { \
sizeof(type), \
offsetof(struct struct_align_##name, x), \
id, NULL \
}
-#define FFI_COMPLEX_TYPEDEF(name, type, maybe_const) \
-static ffi_type *ffi_elements_complex_##name [2] = { \
- (ffi_type *)(&ffi_type_##name), NULL \
-}; \
-struct struct_align_complex_##name { \
- char c; \
- _Complex type x; \
-}; \
-FFI_EXTERN \
-maybe_const ffi_type ffi_type_complex_##name = { \
- sizeof(_Complex type), \
- offsetof(struct struct_align_complex_##name, x), \
- FFI_TYPE_COMPLEX, \
- (ffi_type **)ffi_elements_complex_##name \
-}
-
+#define FFI_COMPLEX_TYPEDEF(name, type, maybe_const) \
+static ffi_type *ffi_elements_complex_##name [2] = { \
+ (ffi_type *)(&ffi_type_##name), NULL \
+}; \
+struct struct_align_complex_##name { \
+ char c; \
+ _Complex type x; \
+}; \
+FFI_EXTERN \
+maybe_const ffi_type ffi_type_complex_##name = { \
+ sizeof(_Complex type), \
+ offsetof(struct struct_align_complex_##name, x), \
+ FFI_TYPE_COMPLEX, \
+ (ffi_type **)ffi_elements_complex_##name \
+}
+
/* Size and alignment are fake here. They must not be 0. */
-FFI_EXTERN const ffi_type ffi_type_void = {
+FFI_EXTERN const ffi_type ffi_type_void = {
1, 1, FFI_TYPE_VOID, NULL
};
-FFI_TYPEDEF(uint8, UINT8, FFI_TYPE_UINT8, const);
-FFI_TYPEDEF(sint8, SINT8, FFI_TYPE_SINT8, const);
-FFI_TYPEDEF(uint16, UINT16, FFI_TYPE_UINT16, const);
-FFI_TYPEDEF(sint16, SINT16, FFI_TYPE_SINT16, const);
-FFI_TYPEDEF(uint32, UINT32, FFI_TYPE_UINT32, const);
-FFI_TYPEDEF(sint32, SINT32, FFI_TYPE_SINT32, const);
-FFI_TYPEDEF(uint64, UINT64, FFI_TYPE_UINT64, const);
-FFI_TYPEDEF(sint64, SINT64, FFI_TYPE_SINT64, const);
+FFI_TYPEDEF(uint8, UINT8, FFI_TYPE_UINT8, const);
+FFI_TYPEDEF(sint8, SINT8, FFI_TYPE_SINT8, const);
+FFI_TYPEDEF(uint16, UINT16, FFI_TYPE_UINT16, const);
+FFI_TYPEDEF(sint16, SINT16, FFI_TYPE_SINT16, const);
+FFI_TYPEDEF(uint32, UINT32, FFI_TYPE_UINT32, const);
+FFI_TYPEDEF(sint32, SINT32, FFI_TYPE_SINT32, const);
+FFI_TYPEDEF(uint64, UINT64, FFI_TYPE_UINT64, const);
+FFI_TYPEDEF(sint64, SINT64, FFI_TYPE_SINT64, const);
-FFI_TYPEDEF(pointer, void*, FFI_TYPE_POINTER, const);
+FFI_TYPEDEF(pointer, void*, FFI_TYPE_POINTER, const);
-FFI_TYPEDEF(float, float, FFI_TYPE_FLOAT, const);
-FFI_TYPEDEF(double, double, FFI_TYPE_DOUBLE, const);
+FFI_TYPEDEF(float, float, FFI_TYPE_FLOAT, const);
+FFI_TYPEDEF(double, double, FFI_TYPE_DOUBLE, const);
+
+#if !defined HAVE_LONG_DOUBLE_VARIANT || defined __alpha__
+#define FFI_LDBL_CONST const
+#else
+#define FFI_LDBL_CONST
+#endif
-#if !defined HAVE_LONG_DOUBLE_VARIANT || defined __alpha__
-#define FFI_LDBL_CONST const
-#else
-#define FFI_LDBL_CONST
-#endif
-
#ifdef __alpha__
/* Even if we're not configured to default to 128-bit long double,
maintain binary compatibility, as -mlong-double-128 can be used
@@ -96,13 +96,13 @@ FFI_TYPEDEF(double, double, FFI_TYPE_DOUBLE, const);
# endif
const ffi_type ffi_type_longdouble = { 16, 16, 4, NULL };
#elif FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
-FFI_TYPEDEF(longdouble, long double, FFI_TYPE_LONGDOUBLE, FFI_LDBL_CONST);
+FFI_TYPEDEF(longdouble, long double, FFI_TYPE_LONGDOUBLE, FFI_LDBL_CONST);
+#endif
+
+#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
+FFI_COMPLEX_TYPEDEF(float, float, const);
+FFI_COMPLEX_TYPEDEF(double, double, const);
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+FFI_COMPLEX_TYPEDEF(longdouble, long double, FFI_LDBL_CONST);
+#endif
#endif
-
-#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
-FFI_COMPLEX_TYPEDEF(float, float, const);
-FFI_COMPLEX_TYPEDEF(double, double, const);
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
-FFI_COMPLEX_TYPEDEF(longdouble, long double, FFI_LDBL_CONST);
-#endif
-#endif
diff --git a/contrib/restricted/libffi/src/x86/asmnames.h b/contrib/restricted/libffi/src/x86/asmnames.h
index fc5c4cb9e7..7551021e17 100644
--- a/contrib/restricted/libffi/src/x86/asmnames.h
+++ b/contrib/restricted/libffi/src/x86/asmnames.h
@@ -1,30 +1,30 @@
-#ifndef ASMNAMES_H
-#define ASMNAMES_H
-
-#define C2(X, Y) X ## Y
-#define C1(X, Y) C2(X, Y)
-#ifdef __USER_LABEL_PREFIX__
-# define C(X) C1(__USER_LABEL_PREFIX__, X)
-#else
-# define C(X) X
-#endif
-
-#ifdef __APPLE__
-# define L(X) C1(L, X)
-#else
-# define L(X) C1(.L, X)
-#endif
-
-#if defined(__ELF__) && defined(__PIC__)
-# define PLT(X) X@PLT
-#else
-# define PLT(X) X
-#endif
-
-#ifdef __ELF__
-# define ENDF(X) .type X,@function; .size X, . - X
-#else
-# define ENDF(X)
-#endif
-
-#endif /* ASMNAMES_H */
+#ifndef ASMNAMES_H
+#define ASMNAMES_H
+
+#define C2(X, Y) X ## Y
+#define C1(X, Y) C2(X, Y)
+#ifdef __USER_LABEL_PREFIX__
+# define C(X) C1(__USER_LABEL_PREFIX__, X)
+#else
+# define C(X) X
+#endif
+
+#ifdef __APPLE__
+# define L(X) C1(L, X)
+#else
+# define L(X) C1(.L, X)
+#endif
+
+#if defined(__ELF__) && defined(__PIC__)
+# define PLT(X) X@PLT
+#else
+# define PLT(X) X
+#endif
+
+#ifdef __ELF__
+# define ENDF(X) .type X,@function; .size X, . - X
+#else
+# define ENDF(X)
+#endif
+
+#endif /* ASMNAMES_H */
diff --git a/contrib/restricted/libffi/src/x86/ffi.c b/contrib/restricted/libffi/src/x86/ffi.c
index 2950ba8fca..9a592185a1 100644
--- a/contrib/restricted/libffi/src/x86/ffi.c
+++ b/contrib/restricted/libffi/src/x86/ffi.c
@@ -1,6 +1,6 @@
/* -----------------------------------------------------------------------
- ffi.c - Copyright (c) 2017 Anthony Green
- Copyright (c) 1996, 1998, 1999, 2001, 2007, 2008 Red Hat, Inc.
+ ffi.c - Copyright (c) 2017 Anthony Green
+ Copyright (c) 1996, 1998, 1999, 2001, 2007, 2008 Red Hat, Inc.
Copyright (c) 2002 Ranjit Mathew
Copyright (c) 2002 Bo Thorsen
Copyright (c) 2002 Roger Sayle
@@ -29,502 +29,502 @@
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
-#if defined(__i386__) || defined(_M_IX86)
+#if defined(__i386__) || defined(_M_IX86)
#include <ffi.h>
#include <ffi_common.h>
-#include <stdint.h>
+#include <stdint.h>
#include <stdlib.h>
-#include "internal.h"
-
-/* Force FFI_TYPE_LONGDOUBLE to be different than FFI_TYPE_DOUBLE;
- all further uses in this file will refer to the 80-bit type. */
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
-# if FFI_TYPE_LONGDOUBLE != 4
-# error FFI_TYPE_LONGDOUBLE out of date
-# endif
-#else
-# undef FFI_TYPE_LONGDOUBLE
-# define FFI_TYPE_LONGDOUBLE 4
+#include "internal.h"
+
+/* Force FFI_TYPE_LONGDOUBLE to be different than FFI_TYPE_DOUBLE;
+ all further uses in this file will refer to the 80-bit type. */
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+# if FFI_TYPE_LONGDOUBLE != 4
+# error FFI_TYPE_LONGDOUBLE out of date
+# endif
+#else
+# undef FFI_TYPE_LONGDOUBLE
+# define FFI_TYPE_LONGDOUBLE 4
#endif
-#if defined(__GNUC__) && !defined(__declspec)
-# define __declspec(x) __attribute__((x))
+#if defined(__GNUC__) && !defined(__declspec)
+# define __declspec(x) __attribute__((x))
#endif
-#if defined(_MSC_VER) && defined(_M_IX86)
-/* Stack is not 16-byte aligned on Windows. */
-#define STACK_ALIGN(bytes) (bytes)
-#else
-#define STACK_ALIGN(bytes) FFI_ALIGN (bytes, 16)
+#if defined(_MSC_VER) && defined(_M_IX86)
+/* Stack is not 16-byte aligned on Windows. */
+#define STACK_ALIGN(bytes) (bytes)
+#else
+#define STACK_ALIGN(bytes) FFI_ALIGN (bytes, 16)
#endif
-/* Perform machine dependent cif processing. */
-ffi_status FFI_HIDDEN
-ffi_prep_cif_machdep(ffi_cif *cif)
-{
- size_t bytes = 0;
- int i, n, flags, cabi = cif->abi;
+/* Perform machine dependent cif processing. */
+ffi_status FFI_HIDDEN
+ffi_prep_cif_machdep(ffi_cif *cif)
+{
+ size_t bytes = 0;
+ int i, n, flags, cabi = cif->abi;
- switch (cabi)
+ switch (cabi)
{
- case FFI_SYSV:
- case FFI_STDCALL:
- case FFI_THISCALL:
- case FFI_FASTCALL:
- case FFI_MS_CDECL:
- case FFI_PASCAL:
- case FFI_REGISTER:
- break;
- default:
- return FFI_BAD_ABI;
+ case FFI_SYSV:
+ case FFI_STDCALL:
+ case FFI_THISCALL:
+ case FFI_FASTCALL:
+ case FFI_MS_CDECL:
+ case FFI_PASCAL:
+ case FFI_REGISTER:
+ break;
+ default:
+ return FFI_BAD_ABI;
}
switch (cif->rtype->type)
{
case FFI_TYPE_VOID:
- flags = X86_RET_VOID;
- break;
- case FFI_TYPE_FLOAT:
- flags = X86_RET_FLOAT;
- break;
- case FFI_TYPE_DOUBLE:
- flags = X86_RET_DOUBLE;
- break;
- case FFI_TYPE_LONGDOUBLE:
- flags = X86_RET_LDOUBLE;
- break;
+ flags = X86_RET_VOID;
+ break;
+ case FFI_TYPE_FLOAT:
+ flags = X86_RET_FLOAT;
+ break;
+ case FFI_TYPE_DOUBLE:
+ flags = X86_RET_DOUBLE;
+ break;
+ case FFI_TYPE_LONGDOUBLE:
+ flags = X86_RET_LDOUBLE;
+ break;
case FFI_TYPE_UINT8:
- flags = X86_RET_UINT8;
- break;
+ flags = X86_RET_UINT8;
+ break;
case FFI_TYPE_UINT16:
- flags = X86_RET_UINT16;
- break;
+ flags = X86_RET_UINT16;
+ break;
case FFI_TYPE_SINT8:
- flags = X86_RET_SINT8;
- break;
+ flags = X86_RET_SINT8;
+ break;
case FFI_TYPE_SINT16:
- flags = X86_RET_SINT16;
- break;
- case FFI_TYPE_INT:
- case FFI_TYPE_SINT32:
+ flags = X86_RET_SINT16;
+ break;
+ case FFI_TYPE_INT:
+ case FFI_TYPE_SINT32:
case FFI_TYPE_UINT32:
- case FFI_TYPE_POINTER:
- flags = X86_RET_INT32;
- break;
+ case FFI_TYPE_POINTER:
+ flags = X86_RET_INT32;
+ break;
case FFI_TYPE_SINT64:
case FFI_TYPE_UINT64:
- flags = X86_RET_INT64;
+ flags = X86_RET_INT64;
break;
case FFI_TYPE_STRUCT:
#ifndef X86
- /* ??? This should be a different ABI rather than an ifdef. */
+ /* ??? This should be a different ABI rather than an ifdef. */
if (cif->rtype->size == 1)
- flags = X86_RET_STRUCT_1B;
+ flags = X86_RET_STRUCT_1B;
else if (cif->rtype->size == 2)
- flags = X86_RET_STRUCT_2B;
+ flags = X86_RET_STRUCT_2B;
else if (cif->rtype->size == 4)
- flags = X86_RET_INT32;
+ flags = X86_RET_INT32;
else if (cif->rtype->size == 8)
- flags = X86_RET_INT64;
+ flags = X86_RET_INT64;
else
#endif
- {
- do_struct:
- switch (cabi)
- {
- case FFI_THISCALL:
- case FFI_FASTCALL:
- case FFI_STDCALL:
- case FFI_MS_CDECL:
- flags = X86_RET_STRUCTARG;
- break;
- default:
- flags = X86_RET_STRUCTPOP;
- break;
- }
- /* Allocate space for return value pointer. */
- bytes += FFI_ALIGN (sizeof(void*), FFI_SIZEOF_ARG);
- }
+ {
+ do_struct:
+ switch (cabi)
+ {
+ case FFI_THISCALL:
+ case FFI_FASTCALL:
+ case FFI_STDCALL:
+ case FFI_MS_CDECL:
+ flags = X86_RET_STRUCTARG;
+ break;
+ default:
+ flags = X86_RET_STRUCTPOP;
+ break;
+ }
+ /* Allocate space for return value pointer. */
+ bytes += FFI_ALIGN (sizeof(void*), FFI_SIZEOF_ARG);
+ }
+ break;
+ case FFI_TYPE_COMPLEX:
+ switch (cif->rtype->elements[0]->type)
+ {
+ case FFI_TYPE_DOUBLE:
+ case FFI_TYPE_LONGDOUBLE:
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_UINT64:
+ goto do_struct;
+ case FFI_TYPE_FLOAT:
+ case FFI_TYPE_INT:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT32:
+ flags = X86_RET_INT64;
+ break;
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT16:
+ flags = X86_RET_INT32;
+ break;
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT8:
+ flags = X86_RET_STRUCT_2B;
+ break;
+ default:
+ return FFI_BAD_TYPEDEF;
+ }
break;
- case FFI_TYPE_COMPLEX:
- switch (cif->rtype->elements[0]->type)
- {
- case FFI_TYPE_DOUBLE:
- case FFI_TYPE_LONGDOUBLE:
- case FFI_TYPE_SINT64:
- case FFI_TYPE_UINT64:
- goto do_struct;
- case FFI_TYPE_FLOAT:
- case FFI_TYPE_INT:
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT32:
- flags = X86_RET_INT64;
- break;
- case FFI_TYPE_SINT16:
- case FFI_TYPE_UINT16:
- flags = X86_RET_INT32;
- break;
- case FFI_TYPE_SINT8:
- case FFI_TYPE_UINT8:
- flags = X86_RET_STRUCT_2B;
- break;
- default:
- return FFI_BAD_TYPEDEF;
- }
- break;
default:
- return FFI_BAD_TYPEDEF;
+ return FFI_BAD_TYPEDEF;
+ }
+ cif->flags = flags;
+
+ for (i = 0, n = cif->nargs; i < n; i++)
+ {
+ ffi_type *t = cif->arg_types[i];
+
+ bytes = FFI_ALIGN (bytes, t->alignment);
+ bytes += FFI_ALIGN (t->size, FFI_SIZEOF_ARG);
}
- cif->flags = flags;
+ cif->bytes = bytes;
+
+ return FFI_OK;
+}
- for (i = 0, n = cif->nargs; i < n; i++)
+static ffi_arg
+extend_basic_type(void *arg, int type)
+{
+ switch (type)
{
- ffi_type *t = cif->arg_types[i];
-
- bytes = FFI_ALIGN (bytes, t->alignment);
- bytes += FFI_ALIGN (t->size, FFI_SIZEOF_ARG);
+ case FFI_TYPE_SINT8:
+ return *(SINT8 *)arg;
+ case FFI_TYPE_UINT8:
+ return *(UINT8 *)arg;
+ case FFI_TYPE_SINT16:
+ return *(SINT16 *)arg;
+ case FFI_TYPE_UINT16:
+ return *(UINT16 *)arg;
+
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_POINTER:
+ case FFI_TYPE_FLOAT:
+ return *(UINT32 *)arg;
+
+ default:
+ abort();
}
- cif->bytes = bytes;
-
- return FFI_OK;
-}
-
-static ffi_arg
-extend_basic_type(void *arg, int type)
-{
- switch (type)
- {
- case FFI_TYPE_SINT8:
- return *(SINT8 *)arg;
- case FFI_TYPE_UINT8:
- return *(UINT8 *)arg;
- case FFI_TYPE_SINT16:
- return *(SINT16 *)arg;
- case FFI_TYPE_UINT16:
- return *(UINT16 *)arg;
-
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_POINTER:
- case FFI_TYPE_FLOAT:
- return *(UINT32 *)arg;
-
- default:
- abort();
- }
}
-struct call_frame
-{
- void *ebp; /* 0 */
- void *retaddr; /* 4 */
- void (*fn)(void); /* 8 */
- int flags; /* 12 */
- void *rvalue; /* 16 */
- unsigned regs[3]; /* 20-28 */
-};
-
-struct abi_params
-{
- int dir; /* parameter growth direction */
- int static_chain; /* the static chain register used by gcc */
- int nregs; /* number of register parameters */
- int regs[3];
-};
-
-static const struct abi_params abi_params[FFI_LAST_ABI] = {
- [FFI_SYSV] = { 1, R_ECX, 0 },
- [FFI_THISCALL] = { 1, R_EAX, 1, { R_ECX } },
- [FFI_FASTCALL] = { 1, R_EAX, 2, { R_ECX, R_EDX } },
- [FFI_STDCALL] = { 1, R_ECX, 0 },
- [FFI_PASCAL] = { -1, R_ECX, 0 },
- /* ??? No defined static chain; gcc does not support REGISTER. */
- [FFI_REGISTER] = { -1, R_ECX, 3, { R_EAX, R_EDX, R_ECX } },
- [FFI_MS_CDECL] = { 1, R_ECX, 0 }
-};
-
-#ifdef HAVE_FASTCALL
- #ifdef _MSC_VER
- #define FFI_DECLARE_FASTCALL __fastcall
- #else
- #define FFI_DECLARE_FASTCALL __declspec(fastcall)
- #endif
+struct call_frame
+{
+ void *ebp; /* 0 */
+ void *retaddr; /* 4 */
+ void (*fn)(void); /* 8 */
+ int flags; /* 12 */
+ void *rvalue; /* 16 */
+ unsigned regs[3]; /* 20-28 */
+};
+
+struct abi_params
+{
+ int dir; /* parameter growth direction */
+ int static_chain; /* the static chain register used by gcc */
+ int nregs; /* number of register parameters */
+ int regs[3];
+};
+
+static const struct abi_params abi_params[FFI_LAST_ABI] = {
+ [FFI_SYSV] = { 1, R_ECX, 0 },
+ [FFI_THISCALL] = { 1, R_EAX, 1, { R_ECX } },
+ [FFI_FASTCALL] = { 1, R_EAX, 2, { R_ECX, R_EDX } },
+ [FFI_STDCALL] = { 1, R_ECX, 0 },
+ [FFI_PASCAL] = { -1, R_ECX, 0 },
+ /* ??? No defined static chain; gcc does not support REGISTER. */
+ [FFI_REGISTER] = { -1, R_ECX, 3, { R_EAX, R_EDX, R_ECX } },
+ [FFI_MS_CDECL] = { 1, R_ECX, 0 }
+};
+
+#ifdef HAVE_FASTCALL
+ #ifdef _MSC_VER
+ #define FFI_DECLARE_FASTCALL __fastcall
+ #else
+ #define FFI_DECLARE_FASTCALL __declspec(fastcall)
+ #endif
#else
- #define FFI_DECLARE_FASTCALL
+ #define FFI_DECLARE_FASTCALL
#endif
-extern void FFI_DECLARE_FASTCALL ffi_call_i386(struct call_frame *, char *) FFI_HIDDEN;
-
-static void
-ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure)
+extern void FFI_DECLARE_FASTCALL ffi_call_i386(struct call_frame *, char *) FFI_HIDDEN;
+
+static void
+ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure)
{
- size_t rsize, bytes;
- struct call_frame *frame;
- char *stack, *argp;
- ffi_type **arg_types;
- int flags, cabi, i, n, dir, narg_reg;
- const struct abi_params *pabi;
-
- flags = cif->flags;
- cabi = cif->abi;
- pabi = &abi_params[cabi];
- dir = pabi->dir;
-
- rsize = 0;
- if (rvalue == NULL)
+ size_t rsize, bytes;
+ struct call_frame *frame;
+ char *stack, *argp;
+ ffi_type **arg_types;
+ int flags, cabi, i, n, dir, narg_reg;
+ const struct abi_params *pabi;
+
+ flags = cif->flags;
+ cabi = cif->abi;
+ pabi = &abi_params[cabi];
+ dir = pabi->dir;
+
+ rsize = 0;
+ if (rvalue == NULL)
{
- switch (flags)
- {
- case X86_RET_FLOAT:
- case X86_RET_DOUBLE:
- case X86_RET_LDOUBLE:
- case X86_RET_STRUCTPOP:
- case X86_RET_STRUCTARG:
- /* The float cases need to pop the 387 stack.
- The struct cases need to pass a valid pointer to the callee. */
- rsize = cif->rtype->size;
- break;
- default:
- /* We can pretend that the callee returns nothing. */
- flags = X86_RET_VOID;
- break;
- }
+ switch (flags)
+ {
+ case X86_RET_FLOAT:
+ case X86_RET_DOUBLE:
+ case X86_RET_LDOUBLE:
+ case X86_RET_STRUCTPOP:
+ case X86_RET_STRUCTARG:
+ /* The float cases need to pop the 387 stack.
+ The struct cases need to pass a valid pointer to the callee. */
+ rsize = cif->rtype->size;
+ break;
+ default:
+ /* We can pretend that the callee returns nothing. */
+ flags = X86_RET_VOID;
+ break;
+ }
}
- bytes = STACK_ALIGN (cif->bytes);
- stack = alloca(bytes + sizeof(*frame) + rsize);
- argp = (dir < 0 ? stack + bytes : stack);
- frame = (struct call_frame *)(stack + bytes);
- if (rsize)
- rvalue = frame + 1;
-
- frame->fn = fn;
- frame->flags = flags;
- frame->rvalue = rvalue;
- frame->regs[pabi->static_chain] = (unsigned)closure;
-
- narg_reg = 0;
- switch (flags)
- {
- case X86_RET_STRUCTARG:
- /* The pointer is passed as the first argument. */
- if (pabi->nregs > 0)
- {
- frame->regs[pabi->regs[0]] = (unsigned)rvalue;
- narg_reg = 1;
- break;
- }
- /* fallthru */
- case X86_RET_STRUCTPOP:
- *(void **)argp = rvalue;
- argp += sizeof(void *);
+ bytes = STACK_ALIGN (cif->bytes);
+ stack = alloca(bytes + sizeof(*frame) + rsize);
+ argp = (dir < 0 ? stack + bytes : stack);
+ frame = (struct call_frame *)(stack + bytes);
+ if (rsize)
+ rvalue = frame + 1;
+
+ frame->fn = fn;
+ frame->flags = flags;
+ frame->rvalue = rvalue;
+ frame->regs[pabi->static_chain] = (unsigned)closure;
+
+ narg_reg = 0;
+ switch (flags)
+ {
+ case X86_RET_STRUCTARG:
+ /* The pointer is passed as the first argument. */
+ if (pabi->nregs > 0)
+ {
+ frame->regs[pabi->regs[0]] = (unsigned)rvalue;
+ narg_reg = 1;
+ break;
+ }
+ /* fallthru */
+ case X86_RET_STRUCTPOP:
+ *(void **)argp = rvalue;
+ argp += sizeof(void *);
break;
}
- arg_types = cif->arg_types;
- for (i = 0, n = cif->nargs; i < n; i++)
- {
- ffi_type *ty = arg_types[i];
- void *valp = avalue[i];
- size_t z = ty->size;
- int t = ty->type;
-
- if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT)
- {
- ffi_arg val = extend_basic_type (valp, t);
-
- if (t != FFI_TYPE_FLOAT && narg_reg < pabi->nregs)
- frame->regs[pabi->regs[narg_reg++]] = val;
- else if (dir < 0)
- {
- argp -= 4;
- *(ffi_arg *)argp = val;
- }
- else
- {
- *(ffi_arg *)argp = val;
- argp += 4;
- }
- }
- else
- {
- size_t za = FFI_ALIGN (z, FFI_SIZEOF_ARG);
- size_t align = FFI_SIZEOF_ARG;
-
- /* Issue 434: For thiscall and fastcall, if the paramter passed
- as 64-bit integer or struct, all following integer paramters
- will be passed on stack. */
- if ((cabi == FFI_THISCALL || cabi == FFI_FASTCALL)
- && (t == FFI_TYPE_SINT64
- || t == FFI_TYPE_UINT64
- || t == FFI_TYPE_STRUCT))
- narg_reg = 2;
-
- /* Alignment rules for arguments are quite complex. Vectors and
- structures with 16 byte alignment get it. Note that long double
- on Darwin does have 16 byte alignment, and does not get this
- alignment if passed directly; a structure with a long double
- inside, however, would get 16 byte alignment. Since libffi does
- not support vectors, we need non concern ourselves with other
- cases. */
- if (t == FFI_TYPE_STRUCT && ty->alignment >= 16)
- align = 16;
-
- if (dir < 0)
- {
- /* ??? These reverse argument ABIs are probably too old
- to have cared about alignment. Someone should check. */
- argp -= za;
- memcpy (argp, valp, z);
- }
- else
- {
- argp = (char *)FFI_ALIGN (argp, align);
- memcpy (argp, valp, z);
- argp += za;
- }
- }
- }
- FFI_ASSERT (dir > 0 || argp == stack);
-
- ffi_call_i386 (frame, stack);
-}
-
-void
-ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
-{
- ffi_call_int (cif, fn, rvalue, avalue, NULL);
+ arg_types = cif->arg_types;
+ for (i = 0, n = cif->nargs; i < n; i++)
+ {
+ ffi_type *ty = arg_types[i];
+ void *valp = avalue[i];
+ size_t z = ty->size;
+ int t = ty->type;
+
+ if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT)
+ {
+ ffi_arg val = extend_basic_type (valp, t);
+
+ if (t != FFI_TYPE_FLOAT && narg_reg < pabi->nregs)
+ frame->regs[pabi->regs[narg_reg++]] = val;
+ else if (dir < 0)
+ {
+ argp -= 4;
+ *(ffi_arg *)argp = val;
+ }
+ else
+ {
+ *(ffi_arg *)argp = val;
+ argp += 4;
+ }
+ }
+ else
+ {
+ size_t za = FFI_ALIGN (z, FFI_SIZEOF_ARG);
+ size_t align = FFI_SIZEOF_ARG;
+
+ /* Issue 434: For thiscall and fastcall, if the paramter passed
+ as 64-bit integer or struct, all following integer paramters
+ will be passed on stack. */
+ if ((cabi == FFI_THISCALL || cabi == FFI_FASTCALL)
+ && (t == FFI_TYPE_SINT64
+ || t == FFI_TYPE_UINT64
+ || t == FFI_TYPE_STRUCT))
+ narg_reg = 2;
+
+ /* Alignment rules for arguments are quite complex. Vectors and
+ structures with 16 byte alignment get it. Note that long double
+ on Darwin does have 16 byte alignment, and does not get this
+ alignment if passed directly; a structure with a long double
+ inside, however, would get 16 byte alignment. Since libffi does
+ not support vectors, we need non concern ourselves with other
+ cases. */
+ if (t == FFI_TYPE_STRUCT && ty->alignment >= 16)
+ align = 16;
+
+ if (dir < 0)
+ {
+ /* ??? These reverse argument ABIs are probably too old
+ to have cared about alignment. Someone should check. */
+ argp -= za;
+ memcpy (argp, valp, z);
+ }
+ else
+ {
+ argp = (char *)FFI_ALIGN (argp, align);
+ memcpy (argp, valp, z);
+ argp += za;
+ }
+ }
+ }
+ FFI_ASSERT (dir > 0 || argp == stack);
+
+ ffi_call_i386 (frame, stack);
+}
+
+void
+ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
+{
+ ffi_call_int (cif, fn, rvalue, avalue, NULL);
+}
+
+void
+ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure)
+{
+ ffi_call_int (cif, fn, rvalue, avalue, closure);
}
-void
-ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure)
+/** private members **/
+
+void FFI_HIDDEN ffi_closure_i386(void);
+void FFI_HIDDEN ffi_closure_STDCALL(void);
+void FFI_HIDDEN ffi_closure_REGISTER(void);
+
+struct closure_frame
{
- ffi_call_int (cif, fn, rvalue, avalue, closure);
-}
-
-/** private members **/
-
-void FFI_HIDDEN ffi_closure_i386(void);
-void FFI_HIDDEN ffi_closure_STDCALL(void);
-void FFI_HIDDEN ffi_closure_REGISTER(void);
-
-struct closure_frame
-{
- unsigned rettemp[4]; /* 0 */
- unsigned regs[3]; /* 16-24 */
- ffi_cif *cif; /* 28 */
- void (*fun)(ffi_cif*,void*,void**,void*); /* 32 */
- void *user_data; /* 36 */
-};
-
-int FFI_HIDDEN FFI_DECLARE_FASTCALL
-ffi_closure_inner (struct closure_frame *frame, char *stack)
+ unsigned rettemp[4]; /* 0 */
+ unsigned regs[3]; /* 16-24 */
+ ffi_cif *cif; /* 28 */
+ void (*fun)(ffi_cif*,void*,void**,void*); /* 32 */
+ void *user_data; /* 36 */
+};
+
+int FFI_HIDDEN FFI_DECLARE_FASTCALL
+ffi_closure_inner (struct closure_frame *frame, char *stack)
{
- ffi_cif *cif = frame->cif;
- int cabi, i, n, flags, dir, narg_reg;
- const struct abi_params *pabi;
- ffi_type **arg_types;
+ ffi_cif *cif = frame->cif;
+ int cabi, i, n, flags, dir, narg_reg;
+ const struct abi_params *pabi;
+ ffi_type **arg_types;
char *argp;
- void *rvalue;
- void **avalue;
-
- cabi = cif->abi;
- flags = cif->flags;
- narg_reg = 0;
- rvalue = frame->rettemp;
- pabi = &abi_params[cabi];
- dir = pabi->dir;
- argp = (dir < 0 ? stack + STACK_ALIGN (cif->bytes) : stack);
-
- switch (flags)
- {
- case X86_RET_STRUCTARG:
- if (pabi->nregs > 0)
- {
- rvalue = (void *)frame->regs[pabi->regs[0]];
- narg_reg = 1;
- frame->rettemp[0] = (unsigned)rvalue;
- break;
- }
- /* fallthru */
- case X86_RET_STRUCTPOP:
- rvalue = *(void **)argp;
- argp += sizeof(void *);
- frame->rettemp[0] = (unsigned)rvalue;
- break;
- }
-
- n = cif->nargs;
- avalue = alloca(sizeof(void *) * n);
-
- arg_types = cif->arg_types;
- for (i = 0; i < n; ++i)
+ void *rvalue;
+ void **avalue;
+
+ cabi = cif->abi;
+ flags = cif->flags;
+ narg_reg = 0;
+ rvalue = frame->rettemp;
+ pabi = &abi_params[cabi];
+ dir = pabi->dir;
+ argp = (dir < 0 ? stack + STACK_ALIGN (cif->bytes) : stack);
+
+ switch (flags)
+ {
+ case X86_RET_STRUCTARG:
+ if (pabi->nregs > 0)
+ {
+ rvalue = (void *)frame->regs[pabi->regs[0]];
+ narg_reg = 1;
+ frame->rettemp[0] = (unsigned)rvalue;
+ break;
+ }
+ /* fallthru */
+ case X86_RET_STRUCTPOP:
+ rvalue = *(void **)argp;
+ argp += sizeof(void *);
+ frame->rettemp[0] = (unsigned)rvalue;
+ break;
+ }
+
+ n = cif->nargs;
+ avalue = alloca(sizeof(void *) * n);
+
+ arg_types = cif->arg_types;
+ for (i = 0; i < n; ++i)
{
- ffi_type *ty = arg_types[i];
- size_t z = ty->size;
- int t = ty->type;
- void *valp;
-
- if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT)
- {
- if (t != FFI_TYPE_FLOAT && narg_reg < pabi->nregs)
- valp = &frame->regs[pabi->regs[narg_reg++]];
- else if (dir < 0)
- {
- argp -= 4;
- valp = argp;
- }
- else
- {
- valp = argp;
- argp += 4;
- }
- }
+ ffi_type *ty = arg_types[i];
+ size_t z = ty->size;
+ int t = ty->type;
+ void *valp;
+
+ if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT)
+ {
+ if (t != FFI_TYPE_FLOAT && narg_reg < pabi->nregs)
+ valp = &frame->regs[pabi->regs[narg_reg++]];
+ else if (dir < 0)
+ {
+ argp -= 4;
+ valp = argp;
+ }
+ else
+ {
+ valp = argp;
+ argp += 4;
+ }
+ }
else
- {
- size_t za = FFI_ALIGN (z, FFI_SIZEOF_ARG);
- size_t align = FFI_SIZEOF_ARG;
-
- /* See the comment in ffi_call_int. */
- if (t == FFI_TYPE_STRUCT && ty->alignment >= 16)
- align = 16;
-
- /* Issue 434: For thiscall and fastcall, if the paramter passed
- as 64-bit integer or struct, all following integer paramters
- will be passed on stack. */
- if ((cabi == FFI_THISCALL || cabi == FFI_FASTCALL)
- && (t == FFI_TYPE_SINT64
- || t == FFI_TYPE_UINT64
- || t == FFI_TYPE_STRUCT))
- narg_reg = 2;
-
- if (dir < 0)
- {
- /* ??? These reverse argument ABIs are probably too old
- to have cared about alignment. Someone should check. */
- argp -= za;
- valp = argp;
- }
- else
- {
- argp = (char *)FFI_ALIGN (argp, align);
- valp = argp;
- argp += za;
- }
- }
-
- avalue[i] = valp;
- }
-
- frame->fun (cif, rvalue, avalue, frame->user_data);
-
- if (cabi == FFI_STDCALL)
- return flags + (cif->bytes << X86_RET_POP_SHIFT);
- else
- return flags;
-}
+ {
+ size_t za = FFI_ALIGN (z, FFI_SIZEOF_ARG);
+ size_t align = FFI_SIZEOF_ARG;
+
+ /* See the comment in ffi_call_int. */
+ if (t == FFI_TYPE_STRUCT && ty->alignment >= 16)
+ align = 16;
+
+ /* Issue 434: For thiscall and fastcall, if the paramter passed
+ as 64-bit integer or struct, all following integer paramters
+ will be passed on stack. */
+ if ((cabi == FFI_THISCALL || cabi == FFI_FASTCALL)
+ && (t == FFI_TYPE_SINT64
+ || t == FFI_TYPE_UINT64
+ || t == FFI_TYPE_STRUCT))
+ narg_reg = 2;
+
+ if (dir < 0)
+ {
+ /* ??? These reverse argument ABIs are probably too old
+ to have cared about alignment. Someone should check. */
+ argp -= za;
+ valp = argp;
+ }
+ else
+ {
+ argp = (char *)FFI_ALIGN (argp, align);
+ valp = argp;
+ argp += za;
+ }
+ }
+
+ avalue[i] = valp;
+ }
+
+ frame->fun (cif, rvalue, avalue, frame->user_data);
+
+ if (cabi == FFI_STDCALL)
+ return flags + (cif->bytes << X86_RET_POP_SHIFT);
+ else
+ return flags;
+}
ffi_status
ffi_prep_closure_loc (ffi_closure* closure,
@@ -533,78 +533,78 @@ ffi_prep_closure_loc (ffi_closure* closure,
void *user_data,
void *codeloc)
{
- char *tramp = closure->tramp;
- void (*dest)(void);
- int op = 0xb8; /* movl imm, %eax */
-
- switch (cif->abi)
+ char *tramp = closure->tramp;
+ void (*dest)(void);
+ int op = 0xb8; /* movl imm, %eax */
+
+ switch (cif->abi)
{
- case FFI_SYSV:
- case FFI_THISCALL:
- case FFI_FASTCALL:
- case FFI_MS_CDECL:
- dest = ffi_closure_i386;
- break;
- case FFI_STDCALL:
- case FFI_PASCAL:
- dest = ffi_closure_STDCALL;
- break;
- case FFI_REGISTER:
- dest = ffi_closure_REGISTER;
- op = 0x68; /* pushl imm */
- break;
- default:
- return FFI_BAD_ABI;
+ case FFI_SYSV:
+ case FFI_THISCALL:
+ case FFI_FASTCALL:
+ case FFI_MS_CDECL:
+ dest = ffi_closure_i386;
+ break;
+ case FFI_STDCALL:
+ case FFI_PASCAL:
+ dest = ffi_closure_STDCALL;
+ break;
+ case FFI_REGISTER:
+ dest = ffi_closure_REGISTER;
+ op = 0x68; /* pushl imm */
+ break;
+ default:
+ return FFI_BAD_ABI;
}
-
- /* movl or pushl immediate. */
- tramp[0] = op;
- *(void **)(tramp + 1) = codeloc;
-
- /* jmp dest */
- tramp[5] = 0xe9;
- *(unsigned *)(tramp + 6) = (unsigned)dest - ((unsigned)codeloc + 10);
-
- closure->cif = cif;
- closure->fun = fun;
- closure->user_data = user_data;
-
- return FFI_OK;
-}
-
-void FFI_HIDDEN ffi_go_closure_EAX(void);
-void FFI_HIDDEN ffi_go_closure_ECX(void);
-void FFI_HIDDEN ffi_go_closure_STDCALL(void);
-
-ffi_status
-ffi_prep_go_closure (ffi_go_closure* closure, ffi_cif* cif,
- void (*fun)(ffi_cif*,void*,void**,void*))
-{
- void (*dest)(void);
-
- switch (cif->abi)
+
+ /* movl or pushl immediate. */
+ tramp[0] = op;
+ *(void **)(tramp + 1) = codeloc;
+
+ /* jmp dest */
+ tramp[5] = 0xe9;
+ *(unsigned *)(tramp + 6) = (unsigned)dest - ((unsigned)codeloc + 10);
+
+ closure->cif = cif;
+ closure->fun = fun;
+ closure->user_data = user_data;
+
+ return FFI_OK;
+}
+
+void FFI_HIDDEN ffi_go_closure_EAX(void);
+void FFI_HIDDEN ffi_go_closure_ECX(void);
+void FFI_HIDDEN ffi_go_closure_STDCALL(void);
+
+ffi_status
+ffi_prep_go_closure (ffi_go_closure* closure, ffi_cif* cif,
+ void (*fun)(ffi_cif*,void*,void**,void*))
+{
+ void (*dest)(void);
+
+ switch (cif->abi)
{
- case FFI_SYSV:
- case FFI_MS_CDECL:
- dest = ffi_go_closure_ECX;
- break;
- case FFI_THISCALL:
- case FFI_FASTCALL:
- dest = ffi_go_closure_EAX;
- break;
- case FFI_STDCALL:
- case FFI_PASCAL:
- dest = ffi_go_closure_STDCALL;
- break;
- case FFI_REGISTER:
- default:
+ case FFI_SYSV:
+ case FFI_MS_CDECL:
+ dest = ffi_go_closure_ECX;
+ break;
+ case FFI_THISCALL:
+ case FFI_FASTCALL:
+ dest = ffi_go_closure_EAX;
+ break;
+ case FFI_STDCALL:
+ case FFI_PASCAL:
+ dest = ffi_go_closure_STDCALL;
+ break;
+ case FFI_REGISTER:
+ default:
return FFI_BAD_ABI;
}
- closure->tramp = dest;
- closure->cif = cif;
- closure->fun = fun;
-
+ closure->tramp = dest;
+ closure->cif = cif;
+ closure->fun = fun;
+
return FFI_OK;
}
@@ -612,150 +612,150 @@ ffi_prep_go_closure (ffi_go_closure* closure, ffi_cif* cif,
#if !FFI_NO_RAW_API
-void FFI_HIDDEN ffi_closure_raw_SYSV(void);
-void FFI_HIDDEN ffi_closure_raw_THISCALL(void);
-
+void FFI_HIDDEN ffi_closure_raw_SYSV(void);
+void FFI_HIDDEN ffi_closure_raw_THISCALL(void);
+
ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure *closure,
- ffi_cif *cif,
+ffi_prep_raw_closure_loc (ffi_raw_closure *closure,
+ ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
void *user_data,
void *codeloc)
{
- char *tramp = closure->tramp;
- void (*dest)(void);
+ char *tramp = closure->tramp;
+ void (*dest)(void);
int i;
- /* We currently don't support certain kinds of arguments for raw
+ /* We currently don't support certain kinds of arguments for raw
closures. This should be implemented by a separate assembly
language routine, since it would require argument processing,
something we don't do now for performance. */
- for (i = cif->nargs-1; i >= 0; i--)
- switch (cif->arg_types[i]->type)
- {
- case FFI_TYPE_STRUCT:
- case FFI_TYPE_LONGDOUBLE:
- return FFI_BAD_TYPEDEF;
- }
-
- switch (cif->abi)
+ for (i = cif->nargs-1; i >= 0; i--)
+ switch (cif->arg_types[i]->type)
+ {
+ case FFI_TYPE_STRUCT:
+ case FFI_TYPE_LONGDOUBLE:
+ return FFI_BAD_TYPEDEF;
+ }
+
+ switch (cif->abi)
{
- case FFI_THISCALL:
- dest = ffi_closure_raw_THISCALL;
- break;
- case FFI_SYSV:
- dest = ffi_closure_raw_SYSV;
- break;
- default:
- return FFI_BAD_ABI;
+ case FFI_THISCALL:
+ dest = ffi_closure_raw_THISCALL;
+ break;
+ case FFI_SYSV:
+ dest = ffi_closure_raw_SYSV;
+ break;
+ default:
+ return FFI_BAD_ABI;
}
-
- /* movl imm, %eax. */
- tramp[0] = 0xb8;
- *(void **)(tramp + 1) = codeloc;
-
- /* jmp dest */
- tramp[5] = 0xe9;
- *(unsigned *)(tramp + 6) = (unsigned)dest - ((unsigned)codeloc + 10);
-
- closure->cif = cif;
- closure->fun = fun;
+
+ /* movl imm, %eax. */
+ tramp[0] = 0xb8;
+ *(void **)(tramp + 1) = codeloc;
+
+ /* jmp dest */
+ tramp[5] = 0xe9;
+ *(unsigned *)(tramp + 6) = (unsigned)dest - ((unsigned)codeloc + 10);
+
+ closure->cif = cif;
+ closure->fun = fun;
closure->user_data = user_data;
return FFI_OK;
}
void
-ffi_raw_call(ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_raw *avalue)
+ffi_raw_call(ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_raw *avalue)
{
- size_t rsize, bytes;
- struct call_frame *frame;
- char *stack, *argp;
- ffi_type **arg_types;
- int flags, cabi, i, n, narg_reg;
- const struct abi_params *pabi;
-
- flags = cif->flags;
- cabi = cif->abi;
- pabi = &abi_params[cabi];
-
- rsize = 0;
- if (rvalue == NULL)
+ size_t rsize, bytes;
+ struct call_frame *frame;
+ char *stack, *argp;
+ ffi_type **arg_types;
+ int flags, cabi, i, n, narg_reg;
+ const struct abi_params *pabi;
+
+ flags = cif->flags;
+ cabi = cif->abi;
+ pabi = &abi_params[cabi];
+
+ rsize = 0;
+ if (rvalue == NULL)
{
- switch (flags)
- {
- case X86_RET_FLOAT:
- case X86_RET_DOUBLE:
- case X86_RET_LDOUBLE:
- case X86_RET_STRUCTPOP:
- case X86_RET_STRUCTARG:
- /* The float cases need to pop the 387 stack.
- The struct cases need to pass a valid pointer to the callee. */
- rsize = cif->rtype->size;
- break;
- default:
- /* We can pretend that the callee returns nothing. */
- flags = X86_RET_VOID;
- break;
- }
+ switch (flags)
+ {
+ case X86_RET_FLOAT:
+ case X86_RET_DOUBLE:
+ case X86_RET_LDOUBLE:
+ case X86_RET_STRUCTPOP:
+ case X86_RET_STRUCTARG:
+ /* The float cases need to pop the 387 stack.
+ The struct cases need to pass a valid pointer to the callee. */
+ rsize = cif->rtype->size;
+ break;
+ default:
+ /* We can pretend that the callee returns nothing. */
+ flags = X86_RET_VOID;
+ break;
+ }
}
- bytes = STACK_ALIGN (cif->bytes);
- argp = stack =
- (void *)((uintptr_t)alloca(bytes + sizeof(*frame) + rsize + 15) & ~16);
- frame = (struct call_frame *)(stack + bytes);
- if (rsize)
- rvalue = frame + 1;
-
- frame->fn = fn;
- frame->flags = flags;
- frame->rvalue = rvalue;
-
- narg_reg = 0;
- switch (flags)
- {
- case X86_RET_STRUCTARG:
- /* The pointer is passed as the first argument. */
- if (pabi->nregs > 0)
- {
- frame->regs[pabi->regs[0]] = (unsigned)rvalue;
- narg_reg = 1;
- break;
- }
- /* fallthru */
- case X86_RET_STRUCTPOP:
- *(void **)argp = rvalue;
- argp += sizeof(void *);
- bytes -= sizeof(void *);
+ bytes = STACK_ALIGN (cif->bytes);
+ argp = stack =
+ (void *)((uintptr_t)alloca(bytes + sizeof(*frame) + rsize + 15) & ~16);
+ frame = (struct call_frame *)(stack + bytes);
+ if (rsize)
+ rvalue = frame + 1;
+
+ frame->fn = fn;
+ frame->flags = flags;
+ frame->rvalue = rvalue;
+
+ narg_reg = 0;
+ switch (flags)
+ {
+ case X86_RET_STRUCTARG:
+ /* The pointer is passed as the first argument. */
+ if (pabi->nregs > 0)
+ {
+ frame->regs[pabi->regs[0]] = (unsigned)rvalue;
+ narg_reg = 1;
+ break;
+ }
+ /* fallthru */
+ case X86_RET_STRUCTPOP:
+ *(void **)argp = rvalue;
+ argp += sizeof(void *);
+ bytes -= sizeof(void *);
break;
}
- arg_types = cif->arg_types;
- for (i = 0, n = cif->nargs; narg_reg < pabi->nregs && i < n; i++)
- {
- ffi_type *ty = arg_types[i];
- size_t z = ty->size;
- int t = ty->type;
-
- if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT && t != FFI_TYPE_FLOAT)
- {
- ffi_arg val = extend_basic_type (avalue, t);
- frame->regs[pabi->regs[narg_reg++]] = val;
- z = FFI_SIZEOF_ARG;
- }
- else
- {
- memcpy (argp, avalue, z);
- z = FFI_ALIGN (z, FFI_SIZEOF_ARG);
- argp += z;
- }
- avalue += z;
- bytes -= z;
- }
- if (i < n)
- memcpy (argp, avalue, bytes);
-
- ffi_call_i386 (frame, stack);
-}
-#endif /* !FFI_NO_RAW_API */
-#endif /* __i386__ */
+ arg_types = cif->arg_types;
+ for (i = 0, n = cif->nargs; narg_reg < pabi->nregs && i < n; i++)
+ {
+ ffi_type *ty = arg_types[i];
+ size_t z = ty->size;
+ int t = ty->type;
+
+ if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT && t != FFI_TYPE_FLOAT)
+ {
+ ffi_arg val = extend_basic_type (avalue, t);
+ frame->regs[pabi->regs[narg_reg++]] = val;
+ z = FFI_SIZEOF_ARG;
+ }
+ else
+ {
+ memcpy (argp, avalue, z);
+ z = FFI_ALIGN (z, FFI_SIZEOF_ARG);
+ argp += z;
+ }
+ avalue += z;
+ bytes -= z;
+ }
+ if (i < n)
+ memcpy (argp, avalue, bytes);
+
+ ffi_call_i386 (frame, stack);
+}
+#endif /* !FFI_NO_RAW_API */
+#endif /* __i386__ */
diff --git a/contrib/restricted/libffi/src/x86/ffi64.c b/contrib/restricted/libffi/src/x86/ffi64.c
index 2d493d0b0a..dec331c958 100644
--- a/contrib/restricted/libffi/src/x86/ffi64.c
+++ b/contrib/restricted/libffi/src/x86/ffi64.c
@@ -1,11 +1,11 @@
/* -----------------------------------------------------------------------
- ffi64.c - Copyright (c) 2011, 2018 Anthony Green
- Copyright (c) 2013 The Written Word, Inc.
+ ffi64.c - Copyright (c) 2011, 2018 Anthony Green
+ Copyright (c) 2013 The Written Word, Inc.
Copyright (c) 2008, 2010 Red Hat, Inc.
Copyright (c) 2002, 2007 Bo Thorsen <bo@suse.de>
- x86-64 Foreign Function Interface
-
+ x86-64 Foreign Function Interface
+
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
@@ -32,8 +32,8 @@
#include <stdlib.h>
#include <stdarg.h>
-#include <stdint.h>
-#include "internal64.h"
+#include <stdint.h>
+#include "internal64.h"
#ifdef __x86_64__
@@ -41,7 +41,7 @@
#define MAX_SSE_REGS 8
#if defined(__INTEL_COMPILER)
-#include "xmmintrin.h"
+#include "xmmintrin.h"
#define UINT128 __m128
#else
#if defined(__SUNPRO_C)
@@ -63,13 +63,13 @@ struct register_args
{
/* Registers for argument passing. */
UINT64 gpr[MAX_GPR_REGS];
- union big_int_union sse[MAX_SSE_REGS];
- UINT64 rax; /* ssecount */
- UINT64 r10; /* static chain */
+ union big_int_union sse[MAX_SSE_REGS];
+ UINT64 rax; /* ssecount */
+ UINT64 r10; /* static chain */
};
extern void ffi_call_unix64 (void *args, unsigned long bytes, unsigned flags,
- void *raddr, void (*fnaddr)(void)) FFI_HIDDEN;
+ void *raddr, void (*fnaddr)(void)) FFI_HIDDEN;
/* All reference to register classes here is identical to the code in
gcc/config/i386/i386.c. Do *not* change one without the other. */
@@ -156,7 +156,7 @@ merge_classes (enum x86_64_reg_class class1, enum x86_64_reg_class class2)
See the x86-64 PS ABI for details.
*/
-static size_t
+static size_t
classify_argument (ffi_type *type, enum x86_64_reg_class classes[],
size_t byte_offset)
{
@@ -171,9 +171,9 @@ classify_argument (ffi_type *type, enum x86_64_reg_class classes[],
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
case FFI_TYPE_POINTER:
- do_integer:
+ do_integer:
{
- size_t size = byte_offset + type->size;
+ size_t size = byte_offset + type->size;
if (size <= 4)
{
@@ -193,7 +193,7 @@ classify_argument (ffi_type *type, enum x86_64_reg_class classes[],
}
else if (size <= 16)
{
- classes[0] = classes[1] = X86_64_INTEGER_CLASS;
+ classes[0] = classes[1] = X86_64_INTEGER_CLASS;
return 2;
}
else
@@ -208,18 +208,18 @@ classify_argument (ffi_type *type, enum x86_64_reg_class classes[],
case FFI_TYPE_DOUBLE:
classes[0] = X86_64_SSEDF_CLASS;
return 1;
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
case FFI_TYPE_LONGDOUBLE:
classes[0] = X86_64_X87_CLASS;
classes[1] = X86_64_X87UP_CLASS;
return 2;
-#endif
+#endif
case FFI_TYPE_STRUCT:
{
- const size_t UNITS_PER_WORD = 8;
- size_t words = (type->size + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
- ffi_type **ptr;
- unsigned int i;
+ const size_t UNITS_PER_WORD = 8;
+ size_t words = (type->size + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
+ ffi_type **ptr;
+ unsigned int i;
enum x86_64_reg_class subclasses[MAX_CLASSES];
/* If the struct is larger than 32 bytes, pass it on the stack. */
@@ -233,7 +233,7 @@ classify_argument (ffi_type *type, enum x86_64_reg_class classes[],
signalize memory class, so handle it as special case. */
if (!words)
{
- case FFI_TYPE_VOID:
+ case FFI_TYPE_VOID:
classes[0] = X86_64_NO_CLASS;
return 1;
}
@@ -241,16 +241,16 @@ classify_argument (ffi_type *type, enum x86_64_reg_class classes[],
/* Merge the fields of structure. */
for (ptr = type->elements; *ptr != NULL; ptr++)
{
- size_t num;
+ size_t num;
- byte_offset = FFI_ALIGN (byte_offset, (*ptr)->alignment);
+ byte_offset = FFI_ALIGN (byte_offset, (*ptr)->alignment);
num = classify_argument (*ptr, subclasses, byte_offset % 8);
if (num == 0)
return 0;
for (i = 0; i < num; i++)
{
- size_t pos = byte_offset / 8;
+ size_t pos = byte_offset / 8;
classes[i + pos] =
merge_classes (subclasses[i], classes[i + pos]);
}
@@ -282,7 +282,7 @@ classify_argument (ffi_type *type, enum x86_64_reg_class classes[],
/* The X86_64_SSEUP_CLASS should be always preceded by
X86_64_SSE_CLASS or X86_64_SSEUP_CLASS. */
- if (i > 1 && classes[i] == X86_64_SSEUP_CLASS
+ if (i > 1 && classes[i] == X86_64_SSEUP_CLASS
&& classes[i - 1] != X86_64_SSE_CLASS
&& classes[i - 1] != X86_64_SSEUP_CLASS)
{
@@ -293,7 +293,7 @@ classify_argument (ffi_type *type, enum x86_64_reg_class classes[],
/* If X86_64_X87UP_CLASS isn't preceded by X86_64_X87_CLASS,
everything should be passed in memory. */
- if (i > 1 && classes[i] == X86_64_X87UP_CLASS
+ if (i > 1 && classes[i] == X86_64_X87UP_CLASS
&& (classes[i - 1] != X86_64_X87_CLASS))
{
/* The first one should never be X86_64_X87UP_CLASS. */
@@ -303,55 +303,55 @@ classify_argument (ffi_type *type, enum x86_64_reg_class classes[],
}
return words;
}
- case FFI_TYPE_COMPLEX:
- {
- ffi_type *inner = type->elements[0];
- switch (inner->type)
- {
- case FFI_TYPE_INT:
- case FFI_TYPE_UINT8:
- case FFI_TYPE_SINT8:
- case FFI_TYPE_UINT16:
- case FFI_TYPE_SINT16:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- goto do_integer;
-
- case FFI_TYPE_FLOAT:
- classes[0] = X86_64_SSE_CLASS;
- if (byte_offset % 8)
- {
- classes[1] = X86_64_SSESF_CLASS;
- return 2;
- }
- return 1;
- case FFI_TYPE_DOUBLE:
- classes[0] = classes[1] = X86_64_SSEDF_CLASS;
- return 2;
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- classes[0] = X86_64_COMPLEX_X87_CLASS;
- return 1;
-#endif
- }
- }
+ case FFI_TYPE_COMPLEX:
+ {
+ ffi_type *inner = type->elements[0];
+ switch (inner->type)
+ {
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ goto do_integer;
+
+ case FFI_TYPE_FLOAT:
+ classes[0] = X86_64_SSE_CLASS;
+ if (byte_offset % 8)
+ {
+ classes[1] = X86_64_SSESF_CLASS;
+ return 2;
+ }
+ return 1;
+ case FFI_TYPE_DOUBLE:
+ classes[0] = classes[1] = X86_64_SSEDF_CLASS;
+ return 2;
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ classes[0] = X86_64_COMPLEX_X87_CLASS;
+ return 1;
+#endif
+ }
+ }
}
- abort();
+ abort();
}
/* Examine the argument and return set number of register required in each
class. Return zero iff parameter should be passed in memory, otherwise
the number of registers. */
-static size_t
+static size_t
examine_argument (ffi_type *type, enum x86_64_reg_class classes[MAX_CLASSES],
_Bool in_return, int *pngpr, int *pnsse)
{
- size_t n;
- unsigned int i;
- int ngpr, nsse;
+ size_t n;
+ unsigned int i;
+ int ngpr, nsse;
n = classify_argument (type, classes, 0);
if (n == 0)
@@ -389,74 +389,74 @@ examine_argument (ffi_type *type, enum x86_64_reg_class classes[MAX_CLASSES],
/* Perform machine dependent cif processing. */
-#ifndef __ILP32__
-extern ffi_status
-ffi_prep_cif_machdep_efi64(ffi_cif *cif);
-#endif
-
-ffi_status FFI_HIDDEN
+#ifndef __ILP32__
+extern ffi_status
+ffi_prep_cif_machdep_efi64(ffi_cif *cif);
+#endif
+
+ffi_status FFI_HIDDEN
ffi_prep_cif_machdep (ffi_cif *cif)
{
- int gprcount, ssecount, i, avn, ngpr, nsse;
- unsigned flags;
+ int gprcount, ssecount, i, avn, ngpr, nsse;
+ unsigned flags;
enum x86_64_reg_class classes[MAX_CLASSES];
- size_t bytes, n, rtype_size;
- ffi_type *rtype;
-
-#ifndef __ILP32__
- if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64)
- return ffi_prep_cif_machdep_efi64(cif);
-#endif
- if (cif->abi != FFI_UNIX64)
- return FFI_BAD_ABI;
-
+ size_t bytes, n, rtype_size;
+ ffi_type *rtype;
+
+#ifndef __ILP32__
+ if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64)
+ return ffi_prep_cif_machdep_efi64(cif);
+#endif
+ if (cif->abi != FFI_UNIX64)
+ return FFI_BAD_ABI;
+
gprcount = ssecount = 0;
- rtype = cif->rtype;
- rtype_size = rtype->size;
- switch (rtype->type)
+ rtype = cif->rtype;
+ rtype_size = rtype->size;
+ switch (rtype->type)
{
- case FFI_TYPE_VOID:
- flags = UNIX64_RET_VOID;
- break;
- case FFI_TYPE_UINT8:
- flags = UNIX64_RET_UINT8;
- break;
- case FFI_TYPE_SINT8:
- flags = UNIX64_RET_SINT8;
- break;
- case FFI_TYPE_UINT16:
- flags = UNIX64_RET_UINT16;
- break;
- case FFI_TYPE_SINT16:
- flags = UNIX64_RET_SINT16;
- break;
- case FFI_TYPE_UINT32:
- flags = UNIX64_RET_UINT32;
- break;
- case FFI_TYPE_INT:
- case FFI_TYPE_SINT32:
- flags = UNIX64_RET_SINT32;
- break;
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- flags = UNIX64_RET_INT64;
- break;
- case FFI_TYPE_POINTER:
- flags = (sizeof(void *) == 4 ? UNIX64_RET_UINT32 : UNIX64_RET_INT64);
- break;
- case FFI_TYPE_FLOAT:
- flags = UNIX64_RET_XMM32;
- break;
- case FFI_TYPE_DOUBLE:
- flags = UNIX64_RET_XMM64;
- break;
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- flags = UNIX64_RET_X87;
- break;
-#endif
- case FFI_TYPE_STRUCT:
+ case FFI_TYPE_VOID:
+ flags = UNIX64_RET_VOID;
+ break;
+ case FFI_TYPE_UINT8:
+ flags = UNIX64_RET_UINT8;
+ break;
+ case FFI_TYPE_SINT8:
+ flags = UNIX64_RET_SINT8;
+ break;
+ case FFI_TYPE_UINT16:
+ flags = UNIX64_RET_UINT16;
+ break;
+ case FFI_TYPE_SINT16:
+ flags = UNIX64_RET_SINT16;
+ break;
+ case FFI_TYPE_UINT32:
+ flags = UNIX64_RET_UINT32;
+ break;
+ case FFI_TYPE_INT:
+ case FFI_TYPE_SINT32:
+ flags = UNIX64_RET_SINT32;
+ break;
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ flags = UNIX64_RET_INT64;
+ break;
+ case FFI_TYPE_POINTER:
+ flags = (sizeof(void *) == 4 ? UNIX64_RET_UINT32 : UNIX64_RET_INT64);
+ break;
+ case FFI_TYPE_FLOAT:
+ flags = UNIX64_RET_XMM32;
+ break;
+ case FFI_TYPE_DOUBLE:
+ flags = UNIX64_RET_XMM64;
+ break;
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ flags = UNIX64_RET_X87;
+ break;
+#endif
+ case FFI_TYPE_STRUCT:
n = examine_argument (cif->rtype, classes, 1, &ngpr, &nsse);
if (n == 0)
{
@@ -464,62 +464,62 @@ ffi_prep_cif_machdep (ffi_cif *cif)
memory is the first argument. Allocate a register for it. */
gprcount++;
/* We don't have to do anything in asm for the return. */
- flags = UNIX64_RET_VOID | UNIX64_FLAG_RET_IN_MEM;
+ flags = UNIX64_RET_VOID | UNIX64_FLAG_RET_IN_MEM;
}
- else
+ else
{
_Bool sse0 = SSE_CLASS_P (classes[0]);
-
- if (rtype_size == 4 && sse0)
- flags = UNIX64_RET_XMM32;
- else if (rtype_size == 8)
- flags = sse0 ? UNIX64_RET_XMM64 : UNIX64_RET_INT64;
- else
- {
- _Bool sse1 = n == 2 && SSE_CLASS_P (classes[1]);
- if (sse0 && sse1)
- flags = UNIX64_RET_ST_XMM0_XMM1;
- else if (sse0)
- flags = UNIX64_RET_ST_XMM0_RAX;
- else if (sse1)
- flags = UNIX64_RET_ST_RAX_XMM0;
- else
- flags = UNIX64_RET_ST_RAX_RDX;
- flags |= rtype_size << UNIX64_SIZE_SHIFT;
- }
+
+ if (rtype_size == 4 && sse0)
+ flags = UNIX64_RET_XMM32;
+ else if (rtype_size == 8)
+ flags = sse0 ? UNIX64_RET_XMM64 : UNIX64_RET_INT64;
+ else
+ {
+ _Bool sse1 = n == 2 && SSE_CLASS_P (classes[1]);
+ if (sse0 && sse1)
+ flags = UNIX64_RET_ST_XMM0_XMM1;
+ else if (sse0)
+ flags = UNIX64_RET_ST_XMM0_RAX;
+ else if (sse1)
+ flags = UNIX64_RET_ST_RAX_XMM0;
+ else
+ flags = UNIX64_RET_ST_RAX_RDX;
+ flags |= rtype_size << UNIX64_SIZE_SHIFT;
+ }
+ }
+ break;
+ case FFI_TYPE_COMPLEX:
+ switch (rtype->elements[0]->type)
+ {
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ flags = UNIX64_RET_ST_RAX_RDX | ((unsigned) rtype_size << UNIX64_SIZE_SHIFT);
+ break;
+ case FFI_TYPE_FLOAT:
+ flags = UNIX64_RET_XMM64;
+ break;
+ case FFI_TYPE_DOUBLE:
+ flags = UNIX64_RET_ST_XMM0_XMM1 | (16 << UNIX64_SIZE_SHIFT);
+ break;
+#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
+ case FFI_TYPE_LONGDOUBLE:
+ flags = UNIX64_RET_X87_2;
+ break;
+#endif
+ default:
+ return FFI_BAD_TYPEDEF;
}
- break;
- case FFI_TYPE_COMPLEX:
- switch (rtype->elements[0]->type)
- {
- case FFI_TYPE_UINT8:
- case FFI_TYPE_SINT8:
- case FFI_TYPE_UINT16:
- case FFI_TYPE_SINT16:
- case FFI_TYPE_INT:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_SINT32:
- case FFI_TYPE_UINT64:
- case FFI_TYPE_SINT64:
- flags = UNIX64_RET_ST_RAX_RDX | ((unsigned) rtype_size << UNIX64_SIZE_SHIFT);
- break;
- case FFI_TYPE_FLOAT:
- flags = UNIX64_RET_XMM64;
- break;
- case FFI_TYPE_DOUBLE:
- flags = UNIX64_RET_ST_XMM0_XMM1 | (16 << UNIX64_SIZE_SHIFT);
- break;
-#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
- case FFI_TYPE_LONGDOUBLE:
- flags = UNIX64_RET_X87_2;
- break;
-#endif
- default:
- return FFI_BAD_TYPEDEF;
- }
- break;
- default:
- return FFI_BAD_TYPEDEF;
+ break;
+ default:
+ return FFI_BAD_TYPEDEF;
}
/* Go over all arguments and determine the way they should be passed.
@@ -536,7 +536,7 @@ ffi_prep_cif_machdep (ffi_cif *cif)
if (align < 8)
align = 8;
- bytes = FFI_ALIGN (bytes, align);
+ bytes = FFI_ALIGN (bytes, align);
bytes += cif->arg_types[i]->size;
}
else
@@ -546,50 +546,50 @@ ffi_prep_cif_machdep (ffi_cif *cif)
}
}
if (ssecount)
- flags |= UNIX64_FLAG_XMM_ARGS;
-
+ flags |= UNIX64_FLAG_XMM_ARGS;
+
cif->flags = flags;
- cif->bytes = (unsigned) FFI_ALIGN (bytes, 8);
+ cif->bytes = (unsigned) FFI_ALIGN (bytes, 8);
return FFI_OK;
}
-static void
-ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure)
+static void
+ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure)
{
enum x86_64_reg_class classes[MAX_CLASSES];
char *stack, *argp;
ffi_type **arg_types;
- int gprcount, ssecount, ngpr, nsse, i, avn, flags;
+ int gprcount, ssecount, ngpr, nsse, i, avn, flags;
struct register_args *reg_args;
/* Can't call 32-bit mode from 64-bit mode. */
FFI_ASSERT (cif->abi == FFI_UNIX64);
/* If the return value is a struct and we don't have a return value
- address then we need to make one. Otherwise we can ignore it. */
- flags = cif->flags;
- if (rvalue == NULL)
- {
- if (flags & UNIX64_FLAG_RET_IN_MEM)
- rvalue = alloca (cif->rtype->size);
- else
- flags = UNIX64_RET_VOID;
- }
+ address then we need to make one. Otherwise we can ignore it. */
+ flags = cif->flags;
+ if (rvalue == NULL)
+ {
+ if (flags & UNIX64_FLAG_RET_IN_MEM)
+ rvalue = alloca (cif->rtype->size);
+ else
+ flags = UNIX64_RET_VOID;
+ }
/* Allocate the space for the arguments, plus 4 words of temp space. */
stack = alloca (sizeof (struct register_args) + cif->bytes + 4*8);
reg_args = (struct register_args *) stack;
argp = stack + sizeof (struct register_args);
- reg_args->r10 = (uintptr_t) closure;
-
+ reg_args->r10 = (uintptr_t) closure;
+
gprcount = ssecount = 0;
/* If the return value is passed in memory, add the pointer as the
first integer argument. */
- if (flags & UNIX64_FLAG_RET_IN_MEM)
+ if (flags & UNIX64_FLAG_RET_IN_MEM)
reg_args->gpr[gprcount++] = (unsigned long) rvalue;
avn = cif->nargs;
@@ -597,7 +597,7 @@ ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue,
for (i = 0; i < avn; ++i)
{
- size_t n, size = arg_types[i]->size;
+ size_t n, size = arg_types[i]->size;
n = examine_argument (arg_types[i], classes, 0, &ngpr, &nsse);
if (n == 0
@@ -611,7 +611,7 @@ ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue,
align = 8;
/* Pass this argument in memory. */
- argp = (void *) FFI_ALIGN (argp, align);
+ argp = (void *) FFI_ALIGN (argp, align);
memcpy (argp, avalue[i], size);
argp += size;
}
@@ -619,15 +619,15 @@ ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue,
{
/* The argument is passed entirely in registers. */
char *a = (char *) avalue[i];
- unsigned int j;
+ unsigned int j;
for (j = 0; j < n; j++, a += 8, size -= 8)
{
switch (classes[j])
{
- case X86_64_NO_CLASS:
- case X86_64_SSEUP_CLASS:
- break;
+ case X86_64_NO_CLASS:
+ case X86_64_SSEUP_CLASS:
+ break;
case X86_64_INTEGER_CLASS:
case X86_64_INTEGERSI_CLASS:
/* Sign-extend integer arguments passed in general
@@ -637,26 +637,26 @@ ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue,
switch (arg_types[i]->type)
{
case FFI_TYPE_SINT8:
- reg_args->gpr[gprcount] = (SINT64) *((SINT8 *) a);
+ reg_args->gpr[gprcount] = (SINT64) *((SINT8 *) a);
break;
case FFI_TYPE_SINT16:
- reg_args->gpr[gprcount] = (SINT64) *((SINT16 *) a);
+ reg_args->gpr[gprcount] = (SINT64) *((SINT16 *) a);
break;
case FFI_TYPE_SINT32:
- reg_args->gpr[gprcount] = (SINT64) *((SINT32 *) a);
+ reg_args->gpr[gprcount] = (SINT64) *((SINT32 *) a);
break;
default:
reg_args->gpr[gprcount] = 0;
- memcpy (&reg_args->gpr[gprcount], a, size);
+ memcpy (&reg_args->gpr[gprcount], a, size);
}
gprcount++;
break;
case X86_64_SSE_CLASS:
case X86_64_SSEDF_CLASS:
- memcpy (&reg_args->sse[ssecount++].i64, a, sizeof(UINT64));
+ memcpy (&reg_args->sse[ssecount++].i64, a, sizeof(UINT64));
break;
case X86_64_SSESF_CLASS:
- memcpy (&reg_args->sse[ssecount++].i32, a, sizeof(UINT32));
+ memcpy (&reg_args->sse[ssecount++].i32, a, sizeof(UINT32));
break;
default:
abort();
@@ -664,63 +664,63 @@ ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue,
}
}
}
- reg_args->rax = ssecount;
+ reg_args->rax = ssecount;
ffi_call_unix64 (stack, cif->bytes + sizeof (struct register_args),
- flags, rvalue, fn);
+ flags, rvalue, fn);
+}
+
+#ifndef __ILP32__
+extern void
+ffi_call_efi64(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue);
+#endif
+
+void
+ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
+{
+#ifndef __ILP32__
+ if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64)
+ {
+ ffi_call_efi64(cif, fn, rvalue, avalue);
+ return;
+ }
+#endif
+ ffi_call_int (cif, fn, rvalue, avalue, NULL);
}
-#ifndef __ILP32__
-extern void
-ffi_call_efi64(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue);
-#endif
-
-void
-ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
-{
-#ifndef __ILP32__
- if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64)
- {
- ffi_call_efi64(cif, fn, rvalue, avalue);
- return;
- }
-#endif
- ffi_call_int (cif, fn, rvalue, avalue, NULL);
-}
-
-#ifndef __ILP32__
-extern void
-ffi_call_go_efi64(ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure);
-#endif
-
-void
-ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure)
-{
-#ifndef __ILP32__
- if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64)
- {
- ffi_call_go_efi64(cif, fn, rvalue, avalue, closure);
- return;
- }
-#endif
- ffi_call_int (cif, fn, rvalue, avalue, closure);
-}
-
-
-extern void ffi_closure_unix64(void) FFI_HIDDEN;
-extern void ffi_closure_unix64_sse(void) FFI_HIDDEN;
-
-#ifndef __ILP32__
-extern ffi_status
-ffi_prep_closure_loc_efi64(ffi_closure* closure,
- ffi_cif* cif,
- void (*fun)(ffi_cif*, void*, void**, void*),
- void *user_data,
- void *codeloc);
-#endif
-
+#ifndef __ILP32__
+extern void
+ffi_call_go_efi64(ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure);
+#endif
+
+void
+ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure)
+{
+#ifndef __ILP32__
+ if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64)
+ {
+ ffi_call_go_efi64(cif, fn, rvalue, avalue, closure);
+ return;
+ }
+#endif
+ ffi_call_int (cif, fn, rvalue, avalue, closure);
+}
+
+
+extern void ffi_closure_unix64(void) FFI_HIDDEN;
+extern void ffi_closure_unix64_sse(void) FFI_HIDDEN;
+
+#ifndef __ILP32__
+extern ffi_status
+ffi_prep_closure_loc_efi64(ffi_closure* closure,
+ ffi_cif* cif,
+ void (*fun)(ffi_cif*, void*, void**, void*),
+ void *user_data,
+ void *codeloc);
+#endif
+
ffi_status
ffi_prep_closure_loc (ffi_closure* closure,
ffi_cif* cif,
@@ -728,31 +728,31 @@ ffi_prep_closure_loc (ffi_closure* closure,
void *user_data,
void *codeloc)
{
- static const unsigned char trampoline[16] = {
- /* leaq -0x7(%rip),%r10 # 0x0 */
- 0x4c, 0x8d, 0x15, 0xf9, 0xff, 0xff, 0xff,
- /* jmpq *0x3(%rip) # 0x10 */
- 0xff, 0x25, 0x03, 0x00, 0x00, 0x00,
- /* nopl (%rax) */
- 0x0f, 0x1f, 0x00
- };
- void (*dest)(void);
- char *tramp = closure->tramp;
-
-#ifndef __ILP32__
- if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64)
- return ffi_prep_closure_loc_efi64(closure, cif, fun, user_data, codeloc);
-#endif
- if (cif->abi != FFI_UNIX64)
- return FFI_BAD_ABI;
-
- if (cif->flags & UNIX64_FLAG_XMM_ARGS)
- dest = ffi_closure_unix64_sse;
- else
- dest = ffi_closure_unix64;
-
- memcpy (tramp, trampoline, sizeof(trampoline));
- *(UINT64 *)(tramp + 16) = (uintptr_t)dest;
+ static const unsigned char trampoline[16] = {
+ /* leaq -0x7(%rip),%r10 # 0x0 */
+ 0x4c, 0x8d, 0x15, 0xf9, 0xff, 0xff, 0xff,
+ /* jmpq *0x3(%rip) # 0x10 */
+ 0xff, 0x25, 0x03, 0x00, 0x00, 0x00,
+ /* nopl (%rax) */
+ 0x0f, 0x1f, 0x00
+ };
+ void (*dest)(void);
+ char *tramp = closure->tramp;
+
+#ifndef __ILP32__
+ if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64)
+ return ffi_prep_closure_loc_efi64(closure, cif, fun, user_data, codeloc);
+#endif
+ if (cif->abi != FFI_UNIX64)
+ return FFI_BAD_ABI;
+
+ if (cif->flags & UNIX64_FLAG_XMM_ARGS)
+ dest = ffi_closure_unix64_sse;
+ else
+ dest = ffi_closure_unix64;
+
+ memcpy (tramp, trampoline, sizeof(trampoline));
+ *(UINT64 *)(tramp + 16) = (uintptr_t)dest;
closure->cif = cif;
closure->fun = fun;
@@ -761,40 +761,40 @@ ffi_prep_closure_loc (ffi_closure* closure,
return FFI_OK;
}
-int FFI_HIDDEN
-ffi_closure_unix64_inner(ffi_cif *cif,
- void (*fun)(ffi_cif*, void*, void**, void*),
- void *user_data,
- void *rvalue,
- struct register_args *reg_args,
- char *argp)
+int FFI_HIDDEN
+ffi_closure_unix64_inner(ffi_cif *cif,
+ void (*fun)(ffi_cif*, void*, void**, void*),
+ void *user_data,
+ void *rvalue,
+ struct register_args *reg_args,
+ char *argp)
{
void **avalue;
ffi_type **arg_types;
long i, avn;
int gprcount, ssecount, ngpr, nsse;
- int flags;
+ int flags;
- avn = cif->nargs;
- flags = cif->flags;
- avalue = alloca(avn * sizeof(void *));
+ avn = cif->nargs;
+ flags = cif->flags;
+ avalue = alloca(avn * sizeof(void *));
gprcount = ssecount = 0;
- if (flags & UNIX64_FLAG_RET_IN_MEM)
+ if (flags & UNIX64_FLAG_RET_IN_MEM)
{
- /* On return, %rax will contain the address that was passed
- by the caller in %rdi. */
- void *r = (void *)(uintptr_t)reg_args->gpr[gprcount++];
- *(void **)rvalue = r;
- rvalue = r;
- flags = (sizeof(void *) == 4 ? UNIX64_RET_UINT32 : UNIX64_RET_INT64);
+ /* On return, %rax will contain the address that was passed
+ by the caller in %rdi. */
+ void *r = (void *)(uintptr_t)reg_args->gpr[gprcount++];
+ *(void **)rvalue = r;
+ rvalue = r;
+ flags = (sizeof(void *) == 4 ? UNIX64_RET_UINT32 : UNIX64_RET_INT64);
}
arg_types = cif->arg_types;
for (i = 0; i < avn; ++i)
{
enum x86_64_reg_class classes[MAX_CLASSES];
- size_t n;
+ size_t n;
n = examine_argument (arg_types[i], classes, 0, &ngpr, &nsse);
if (n == 0
@@ -808,7 +808,7 @@ ffi_closure_unix64_inner(ffi_cif *cif,
align = 8;
/* Pass this argument in memory. */
- argp = (void *) FFI_ALIGN (argp, align);
+ argp = (void *) FFI_ALIGN (argp, align);
avalue[i] = argp;
argp += arg_types[i]->size;
}
@@ -834,7 +834,7 @@ ffi_closure_unix64_inner(ffi_cif *cif,
else
{
char *a = alloca (16);
- unsigned int j;
+ unsigned int j;
avalue[i] = a;
for (j = 0; j < n; j++, a += 8)
@@ -848,39 +848,39 @@ ffi_closure_unix64_inner(ffi_cif *cif,
}
/* Invoke the closure. */
- fun (cif, rvalue, avalue, user_data);
+ fun (cif, rvalue, avalue, user_data);
/* Tell assembly how to perform return type promotions. */
- return flags;
+ return flags;
+}
+
+extern void ffi_go_closure_unix64(void) FFI_HIDDEN;
+extern void ffi_go_closure_unix64_sse(void) FFI_HIDDEN;
+
+#ifndef __ILP32__
+extern ffi_status
+ffi_prep_go_closure_efi64(ffi_go_closure* closure, ffi_cif* cif,
+ void (*fun)(ffi_cif*, void*, void**, void*));
+#endif
+
+ffi_status
+ffi_prep_go_closure (ffi_go_closure* closure, ffi_cif* cif,
+ void (*fun)(ffi_cif*, void*, void**, void*))
+{
+#ifndef __ILP32__
+ if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64)
+ return ffi_prep_go_closure_efi64(closure, cif, fun);
+#endif
+ if (cif->abi != FFI_UNIX64)
+ return FFI_BAD_ABI;
+
+ closure->tramp = (cif->flags & UNIX64_FLAG_XMM_ARGS
+ ? ffi_go_closure_unix64_sse
+ : ffi_go_closure_unix64);
+ closure->cif = cif;
+ closure->fun = fun;
+
+ return FFI_OK;
}
-extern void ffi_go_closure_unix64(void) FFI_HIDDEN;
-extern void ffi_go_closure_unix64_sse(void) FFI_HIDDEN;
-
-#ifndef __ILP32__
-extern ffi_status
-ffi_prep_go_closure_efi64(ffi_go_closure* closure, ffi_cif* cif,
- void (*fun)(ffi_cif*, void*, void**, void*));
-#endif
-
-ffi_status
-ffi_prep_go_closure (ffi_go_closure* closure, ffi_cif* cif,
- void (*fun)(ffi_cif*, void*, void**, void*))
-{
-#ifndef __ILP32__
- if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64)
- return ffi_prep_go_closure_efi64(closure, cif, fun);
-#endif
- if (cif->abi != FFI_UNIX64)
- return FFI_BAD_ABI;
-
- closure->tramp = (cif->flags & UNIX64_FLAG_XMM_ARGS
- ? ffi_go_closure_unix64_sse
- : ffi_go_closure_unix64);
- closure->cif = cif;
- closure->fun = fun;
-
- return FFI_OK;
-}
-
#endif /* __x86_64__ */
diff --git a/contrib/restricted/libffi/src/x86/ffitarget.h b/contrib/restricted/libffi/src/x86/ffitarget.h
index ab04dfa791..85ccedfedc 100644
--- a/contrib/restricted/libffi/src/x86/ffitarget.h
+++ b/contrib/restricted/libffi/src/x86/ffitarget.h
@@ -1,5 +1,5 @@
/* -----------------------------------------------------------------*-C-*-
- ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
+ ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
Copyright (c) 1996-2003, 2010 Red Hat, Inc.
Copyright (C) 2008 Free Software Foundation, Inc.
@@ -49,11 +49,11 @@
#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
#endif
-#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
-#ifndef _MSC_VER
-#define FFI_TARGET_HAS_COMPLEX_TYPE
-#endif
-
+#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
+#ifndef _MSC_VER
+#define FFI_TARGET_HAS_COMPLEX_TYPE
+#endif
+
/* ---- Generic type definitions ----------------------------------------- */
#ifndef LIBFFI_ASM
@@ -78,46 +78,46 @@ typedef signed long ffi_sarg;
#endif
typedef enum ffi_abi {
-#if defined(X86_WIN64)
+#if defined(X86_WIN64)
FFI_FIRST_ABI = 0,
- FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
- FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
+ FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
+ FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
FFI_LAST_ABI,
-#ifdef __GNUC__
- FFI_DEFAULT_ABI = FFI_GNUW64
-#else
- FFI_DEFAULT_ABI = FFI_WIN64
-#endif
-
-#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
- FFI_FIRST_ABI = 1,
- FFI_UNIX64,
+#ifdef __GNUC__
+ FFI_DEFAULT_ABI = FFI_GNUW64
+#else
+ FFI_DEFAULT_ABI = FFI_WIN64
+#endif
+
+#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
+ FFI_FIRST_ABI = 1,
+ FFI_UNIX64,
FFI_WIN64,
- FFI_EFI64 = FFI_WIN64,
- FFI_GNUW64,
+ FFI_EFI64 = FFI_WIN64,
+ FFI_GNUW64,
FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_UNIX64
-
-#elif defined(X86_WIN32)
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_STDCALL = 2,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_MS_CDECL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_LAST_ABI,
- FFI_DEFAULT_ABI = FFI_MS_CDECL
+ FFI_DEFAULT_ABI = FFI_UNIX64
+
+#elif defined(X86_WIN32)
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_STDCALL = 2,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_MS_CDECL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_LAST_ABI,
+ FFI_DEFAULT_ABI = FFI_MS_CDECL
#else
- FFI_FIRST_ABI = 0,
- FFI_SYSV = 1,
- FFI_THISCALL = 3,
- FFI_FASTCALL = 4,
- FFI_STDCALL = 5,
- FFI_PASCAL = 6,
- FFI_REGISTER = 7,
- FFI_MS_CDECL = 8,
+ FFI_FIRST_ABI = 0,
+ FFI_SYSV = 1,
+ FFI_THISCALL = 3,
+ FFI_FASTCALL = 4,
+ FFI_STDCALL = 5,
+ FFI_PASCAL = 6,
+ FFI_REGISTER = 7,
+ FFI_MS_CDECL = 8,
FFI_LAST_ABI,
FFI_DEFAULT_ABI = FFI_SYSV
#endif
@@ -127,20 +127,20 @@ typedef enum ffi_abi {
/* ---- Definitions for closures ----------------------------------------- */
#define FFI_CLOSURES 1
-#define FFI_GO_CLOSURES 1
-
+#define FFI_GO_CLOSURES 1
+
#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
-#if defined (X86_64) || defined(X86_WIN64) \
- || (defined (__x86_64__) && defined (X86_DARWIN))
-# define FFI_TRAMPOLINE_SIZE 24
-# define FFI_NATIVE_RAW_API 0
+#if defined (X86_64) || defined(X86_WIN64) \
+ || (defined (__x86_64__) && defined (X86_DARWIN))
+# define FFI_TRAMPOLINE_SIZE 24
+# define FFI_NATIVE_RAW_API 0
#else
-# define FFI_TRAMPOLINE_SIZE 12
-# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
+# define FFI_TRAMPOLINE_SIZE 12
+# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
#endif
#endif
diff --git a/contrib/restricted/libffi/src/x86/ffiw64.c b/contrib/restricted/libffi/src/x86/ffiw64.c
index 3eafc9d3e9..b68f69ccf6 100644
--- a/contrib/restricted/libffi/src/x86/ffiw64.c
+++ b/contrib/restricted/libffi/src/x86/ffiw64.c
@@ -1,311 +1,311 @@
-/* -----------------------------------------------------------------------
- ffiw64.c - Copyright (c) 2018 Anthony Green
- Copyright (c) 2014 Red Hat, Inc.
-
- x86 win64 Foreign Function Interface
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#if defined(__x86_64__) || defined(_M_AMD64)
-#include <ffi.h>
-#include <ffi_common.h>
-#include <stdlib.h>
-#include <stdint.h>
-
-#ifdef X86_WIN64
-#define EFI64(name) name
-#else
-#define EFI64(name) FFI_HIDDEN name##_efi64
-#endif
-
-struct win64_call_frame
-{
- UINT64 rbp; /* 0 */
- UINT64 retaddr; /* 8 */
- UINT64 fn; /* 16 */
- UINT64 flags; /* 24 */
- UINT64 rvalue; /* 32 */
-};
-
-extern void ffi_call_win64 (void *stack, struct win64_call_frame *,
- void *closure) FFI_HIDDEN;
-
-ffi_status FFI_HIDDEN
-EFI64(ffi_prep_cif_machdep)(ffi_cif *cif)
-{
- int flags, n;
-
- switch (cif->abi)
- {
- case FFI_WIN64:
- case FFI_GNUW64:
- break;
- default:
- return FFI_BAD_ABI;
- }
-
- flags = cif->rtype->type;
- switch (flags)
- {
- default:
- break;
- case FFI_TYPE_LONGDOUBLE:
- /* GCC returns long double values by reference, like a struct */
- if (cif->abi == FFI_GNUW64)
- flags = FFI_TYPE_STRUCT;
- break;
- case FFI_TYPE_COMPLEX:
- flags = FFI_TYPE_STRUCT;
- /* FALLTHRU */
- case FFI_TYPE_STRUCT:
- switch (cif->rtype->size)
- {
- case 8:
- flags = FFI_TYPE_UINT64;
- break;
- case 4:
- flags = FFI_TYPE_SMALL_STRUCT_4B;
- break;
- case 2:
- flags = FFI_TYPE_SMALL_STRUCT_2B;
- break;
- case 1:
- flags = FFI_TYPE_SMALL_STRUCT_1B;
- break;
- }
- break;
- }
- cif->flags = flags;
-
- /* Each argument either fits in a register, an 8 byte slot, or is
- passed by reference with the pointer in the 8 byte slot. */
- n = cif->nargs;
- n += (flags == FFI_TYPE_STRUCT);
- if (n < 4)
- n = 4;
- cif->bytes = n * 8;
-
- return FFI_OK;
-}
-
-static void
-ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure)
-{
- int i, j, n, flags;
- UINT64 *stack;
- size_t rsize;
- struct win64_call_frame *frame;
-
- FFI_ASSERT(cif->abi == FFI_GNUW64 || cif->abi == FFI_WIN64);
-
- flags = cif->flags;
- rsize = 0;
-
- /* If we have no return value for a structure, we need to create one.
- Otherwise we can ignore the return type entirely. */
- if (rvalue == NULL)
- {
- if (flags == FFI_TYPE_STRUCT)
- rsize = cif->rtype->size;
- else
- flags = FFI_TYPE_VOID;
- }
-
- stack = alloca(cif->bytes + sizeof(struct win64_call_frame) + rsize);
- frame = (struct win64_call_frame *)((char *)stack + cif->bytes);
- if (rsize)
- rvalue = frame + 1;
-
- frame->fn = (uintptr_t)fn;
- frame->flags = flags;
- frame->rvalue = (uintptr_t)rvalue;
-
- j = 0;
- if (flags == FFI_TYPE_STRUCT)
- {
- stack[0] = (uintptr_t)rvalue;
- j = 1;
- }
-
- for (i = 0, n = cif->nargs; i < n; ++i, ++j)
- {
- switch (cif->arg_types[i]->size)
- {
- case 8:
- stack[j] = *(UINT64 *)avalue[i];
- break;
- case 4:
- stack[j] = *(UINT32 *)avalue[i];
- break;
- case 2:
- stack[j] = *(UINT16 *)avalue[i];
- break;
- case 1:
- stack[j] = *(UINT8 *)avalue[i];
- break;
- default:
- stack[j] = (uintptr_t)avalue[i];
- break;
- }
- }
-
- ffi_call_win64 (stack, frame, closure);
-}
-
-void
-EFI64(ffi_call)(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
-{
- ffi_call_int (cif, fn, rvalue, avalue, NULL);
-}
-
-void
-EFI64(ffi_call_go)(ffi_cif *cif, void (*fn)(void), void *rvalue,
- void **avalue, void *closure)
-{
- ffi_call_int (cif, fn, rvalue, avalue, closure);
-}
-
-
-extern void ffi_closure_win64(void) FFI_HIDDEN;
-extern void ffi_go_closure_win64(void) FFI_HIDDEN;
-
-ffi_status
-EFI64(ffi_prep_closure_loc)(ffi_closure* closure,
- ffi_cif* cif,
- void (*fun)(ffi_cif*, void*, void**, void*),
- void *user_data,
- void *codeloc)
-{
- static const unsigned char trampoline[16] = {
- /* leaq -0x7(%rip),%r10 # 0x0 */
- 0x4c, 0x8d, 0x15, 0xf9, 0xff, 0xff, 0xff,
- /* jmpq *0x3(%rip) # 0x10 */
- 0xff, 0x25, 0x03, 0x00, 0x00, 0x00,
- /* nopl (%rax) */
- 0x0f, 0x1f, 0x00
- };
- char *tramp = closure->tramp;
-
- switch (cif->abi)
- {
- case FFI_WIN64:
- case FFI_GNUW64:
- break;
- default:
- return FFI_BAD_ABI;
- }
-
- memcpy (tramp, trampoline, sizeof(trampoline));
- *(UINT64 *)(tramp + 16) = (uintptr_t)ffi_closure_win64;
-
- closure->cif = cif;
- closure->fun = fun;
- closure->user_data = user_data;
-
- return FFI_OK;
-}
-
-ffi_status
-EFI64(ffi_prep_go_closure)(ffi_go_closure* closure, ffi_cif* cif,
- void (*fun)(ffi_cif*, void*, void**, void*))
-{
- switch (cif->abi)
- {
- case FFI_WIN64:
- case FFI_GNUW64:
- break;
- default:
- return FFI_BAD_ABI;
- }
-
- closure->tramp = ffi_go_closure_win64;
- closure->cif = cif;
- closure->fun = fun;
-
- return FFI_OK;
-}
-
-struct win64_closure_frame
-{
- UINT64 rvalue[2];
- UINT64 fargs[4];
- UINT64 retaddr;
- UINT64 args[];
-};
-
-/* Force the inner function to use the MS ABI. When compiling on win64
- this is a nop. When compiling on unix, this simplifies the assembly,
- and places the burden of saving the extra call-saved registers on
- the compiler. */
-int FFI_HIDDEN __attribute__((ms_abi))
-ffi_closure_win64_inner(ffi_cif *cif,
- void (*fun)(ffi_cif*, void*, void**, void*),
- void *user_data,
- struct win64_closure_frame *frame)
-{
- void **avalue;
- void *rvalue;
- int i, n, nreg, flags;
-
- avalue = alloca(cif->nargs * sizeof(void *));
- rvalue = frame->rvalue;
- nreg = 0;
-
- /* When returning a structure, the address is in the first argument.
- We must also be prepared to return the same address in eax, so
- install that address in the frame and pretend we return a pointer. */
- flags = cif->flags;
- if (flags == FFI_TYPE_STRUCT)
- {
- rvalue = (void *)(uintptr_t)frame->args[0];
- frame->rvalue[0] = frame->args[0];
- nreg = 1;
- }
-
- for (i = 0, n = cif->nargs; i < n; ++i, ++nreg)
- {
- size_t size = cif->arg_types[i]->size;
- size_t type = cif->arg_types[i]->type;
- void *a;
-
- if (type == FFI_TYPE_DOUBLE || type == FFI_TYPE_FLOAT)
- {
- if (nreg < 4)
- a = &frame->fargs[nreg];
- else
- a = &frame->args[nreg];
- }
- else if (size == 1 || size == 2 || size == 4 || size == 8)
- a = &frame->args[nreg];
- else
- a = (void *)(uintptr_t)frame->args[nreg];
-
- avalue[i] = a;
- }
-
- /* Invoke the closure. */
- fun (cif, rvalue, avalue, user_data);
- return flags;
-}
-
-#endif /* __x86_64__ */
+/* -----------------------------------------------------------------------
+ ffiw64.c - Copyright (c) 2018 Anthony Green
+ Copyright (c) 2014 Red Hat, Inc.
+
+ x86 win64 Foreign Function Interface
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#if defined(__x86_64__) || defined(_M_AMD64)
+#include <ffi.h>
+#include <ffi_common.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+#ifdef X86_WIN64
+#define EFI64(name) name
+#else
+#define EFI64(name) FFI_HIDDEN name##_efi64
+#endif
+
+struct win64_call_frame
+{
+ UINT64 rbp; /* 0 */
+ UINT64 retaddr; /* 8 */
+ UINT64 fn; /* 16 */
+ UINT64 flags; /* 24 */
+ UINT64 rvalue; /* 32 */
+};
+
+extern void ffi_call_win64 (void *stack, struct win64_call_frame *,
+ void *closure) FFI_HIDDEN;
+
+ffi_status FFI_HIDDEN
+EFI64(ffi_prep_cif_machdep)(ffi_cif *cif)
+{
+ int flags, n;
+
+ switch (cif->abi)
+ {
+ case FFI_WIN64:
+ case FFI_GNUW64:
+ break;
+ default:
+ return FFI_BAD_ABI;
+ }
+
+ flags = cif->rtype->type;
+ switch (flags)
+ {
+ default:
+ break;
+ case FFI_TYPE_LONGDOUBLE:
+ /* GCC returns long double values by reference, like a struct */
+ if (cif->abi == FFI_GNUW64)
+ flags = FFI_TYPE_STRUCT;
+ break;
+ case FFI_TYPE_COMPLEX:
+ flags = FFI_TYPE_STRUCT;
+ /* FALLTHRU */
+ case FFI_TYPE_STRUCT:
+ switch (cif->rtype->size)
+ {
+ case 8:
+ flags = FFI_TYPE_UINT64;
+ break;
+ case 4:
+ flags = FFI_TYPE_SMALL_STRUCT_4B;
+ break;
+ case 2:
+ flags = FFI_TYPE_SMALL_STRUCT_2B;
+ break;
+ case 1:
+ flags = FFI_TYPE_SMALL_STRUCT_1B;
+ break;
+ }
+ break;
+ }
+ cif->flags = flags;
+
+ /* Each argument either fits in a register, an 8 byte slot, or is
+ passed by reference with the pointer in the 8 byte slot. */
+ n = cif->nargs;
+ n += (flags == FFI_TYPE_STRUCT);
+ if (n < 4)
+ n = 4;
+ cif->bytes = n * 8;
+
+ return FFI_OK;
+}
+
+static void
+ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure)
+{
+ int i, j, n, flags;
+ UINT64 *stack;
+ size_t rsize;
+ struct win64_call_frame *frame;
+
+ FFI_ASSERT(cif->abi == FFI_GNUW64 || cif->abi == FFI_WIN64);
+
+ flags = cif->flags;
+ rsize = 0;
+
+ /* If we have no return value for a structure, we need to create one.
+ Otherwise we can ignore the return type entirely. */
+ if (rvalue == NULL)
+ {
+ if (flags == FFI_TYPE_STRUCT)
+ rsize = cif->rtype->size;
+ else
+ flags = FFI_TYPE_VOID;
+ }
+
+ stack = alloca(cif->bytes + sizeof(struct win64_call_frame) + rsize);
+ frame = (struct win64_call_frame *)((char *)stack + cif->bytes);
+ if (rsize)
+ rvalue = frame + 1;
+
+ frame->fn = (uintptr_t)fn;
+ frame->flags = flags;
+ frame->rvalue = (uintptr_t)rvalue;
+
+ j = 0;
+ if (flags == FFI_TYPE_STRUCT)
+ {
+ stack[0] = (uintptr_t)rvalue;
+ j = 1;
+ }
+
+ for (i = 0, n = cif->nargs; i < n; ++i, ++j)
+ {
+ switch (cif->arg_types[i]->size)
+ {
+ case 8:
+ stack[j] = *(UINT64 *)avalue[i];
+ break;
+ case 4:
+ stack[j] = *(UINT32 *)avalue[i];
+ break;
+ case 2:
+ stack[j] = *(UINT16 *)avalue[i];
+ break;
+ case 1:
+ stack[j] = *(UINT8 *)avalue[i];
+ break;
+ default:
+ stack[j] = (uintptr_t)avalue[i];
+ break;
+ }
+ }
+
+ ffi_call_win64 (stack, frame, closure);
+}
+
+void
+EFI64(ffi_call)(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
+{
+ ffi_call_int (cif, fn, rvalue, avalue, NULL);
+}
+
+void
+EFI64(ffi_call_go)(ffi_cif *cif, void (*fn)(void), void *rvalue,
+ void **avalue, void *closure)
+{
+ ffi_call_int (cif, fn, rvalue, avalue, closure);
+}
+
+
+extern void ffi_closure_win64(void) FFI_HIDDEN;
+extern void ffi_go_closure_win64(void) FFI_HIDDEN;
+
+ffi_status
+EFI64(ffi_prep_closure_loc)(ffi_closure* closure,
+ ffi_cif* cif,
+ void (*fun)(ffi_cif*, void*, void**, void*),
+ void *user_data,
+ void *codeloc)
+{
+ static const unsigned char trampoline[16] = {
+ /* leaq -0x7(%rip),%r10 # 0x0 */
+ 0x4c, 0x8d, 0x15, 0xf9, 0xff, 0xff, 0xff,
+ /* jmpq *0x3(%rip) # 0x10 */
+ 0xff, 0x25, 0x03, 0x00, 0x00, 0x00,
+ /* nopl (%rax) */
+ 0x0f, 0x1f, 0x00
+ };
+ char *tramp = closure->tramp;
+
+ switch (cif->abi)
+ {
+ case FFI_WIN64:
+ case FFI_GNUW64:
+ break;
+ default:
+ return FFI_BAD_ABI;
+ }
+
+ memcpy (tramp, trampoline, sizeof(trampoline));
+ *(UINT64 *)(tramp + 16) = (uintptr_t)ffi_closure_win64;
+
+ closure->cif = cif;
+ closure->fun = fun;
+ closure->user_data = user_data;
+
+ return FFI_OK;
+}
+
+ffi_status
+EFI64(ffi_prep_go_closure)(ffi_go_closure* closure, ffi_cif* cif,
+ void (*fun)(ffi_cif*, void*, void**, void*))
+{
+ switch (cif->abi)
+ {
+ case FFI_WIN64:
+ case FFI_GNUW64:
+ break;
+ default:
+ return FFI_BAD_ABI;
+ }
+
+ closure->tramp = ffi_go_closure_win64;
+ closure->cif = cif;
+ closure->fun = fun;
+
+ return FFI_OK;
+}
+
+struct win64_closure_frame
+{
+ UINT64 rvalue[2];
+ UINT64 fargs[4];
+ UINT64 retaddr;
+ UINT64 args[];
+};
+
+/* Force the inner function to use the MS ABI. When compiling on win64
+ this is a nop. When compiling on unix, this simplifies the assembly,
+ and places the burden of saving the extra call-saved registers on
+ the compiler. */
+int FFI_HIDDEN __attribute__((ms_abi))
+ffi_closure_win64_inner(ffi_cif *cif,
+ void (*fun)(ffi_cif*, void*, void**, void*),
+ void *user_data,
+ struct win64_closure_frame *frame)
+{
+ void **avalue;
+ void *rvalue;
+ int i, n, nreg, flags;
+
+ avalue = alloca(cif->nargs * sizeof(void *));
+ rvalue = frame->rvalue;
+ nreg = 0;
+
+ /* When returning a structure, the address is in the first argument.
+ We must also be prepared to return the same address in eax, so
+ install that address in the frame and pretend we return a pointer. */
+ flags = cif->flags;
+ if (flags == FFI_TYPE_STRUCT)
+ {
+ rvalue = (void *)(uintptr_t)frame->args[0];
+ frame->rvalue[0] = frame->args[0];
+ nreg = 1;
+ }
+
+ for (i = 0, n = cif->nargs; i < n; ++i, ++nreg)
+ {
+ size_t size = cif->arg_types[i]->size;
+ size_t type = cif->arg_types[i]->type;
+ void *a;
+
+ if (type == FFI_TYPE_DOUBLE || type == FFI_TYPE_FLOAT)
+ {
+ if (nreg < 4)
+ a = &frame->fargs[nreg];
+ else
+ a = &frame->args[nreg];
+ }
+ else if (size == 1 || size == 2 || size == 4 || size == 8)
+ a = &frame->args[nreg];
+ else
+ a = (void *)(uintptr_t)frame->args[nreg];
+
+ avalue[i] = a;
+ }
+
+ /* Invoke the closure. */
+ fun (cif, rvalue, avalue, user_data);
+ return flags;
+}
+
+#endif /* __x86_64__ */
diff --git a/contrib/restricted/libffi/src/x86/internal.h b/contrib/restricted/libffi/src/x86/internal.h
index 7cfca13a30..09771ba8cf 100644
--- a/contrib/restricted/libffi/src/x86/internal.h
+++ b/contrib/restricted/libffi/src/x86/internal.h
@@ -1,29 +1,29 @@
-#define X86_RET_FLOAT 0
-#define X86_RET_DOUBLE 1
-#define X86_RET_LDOUBLE 2
-#define X86_RET_SINT8 3
-#define X86_RET_SINT16 4
-#define X86_RET_UINT8 5
-#define X86_RET_UINT16 6
-#define X86_RET_INT64 7
-#define X86_RET_INT32 8
-#define X86_RET_VOID 9
-#define X86_RET_STRUCTPOP 10
-#define X86_RET_STRUCTARG 11
-#define X86_RET_STRUCT_1B 12
-#define X86_RET_STRUCT_2B 13
-#define X86_RET_UNUSED14 14
-#define X86_RET_UNUSED15 15
-
-#define X86_RET_TYPE_MASK 15
-#define X86_RET_POP_SHIFT 4
-
-#define R_EAX 0
-#define R_EDX 1
-#define R_ECX 2
-
-#ifdef __PCC__
-# define HAVE_FASTCALL 0
-#else
-# define HAVE_FASTCALL 1
-#endif
+#define X86_RET_FLOAT 0
+#define X86_RET_DOUBLE 1
+#define X86_RET_LDOUBLE 2
+#define X86_RET_SINT8 3
+#define X86_RET_SINT16 4
+#define X86_RET_UINT8 5
+#define X86_RET_UINT16 6
+#define X86_RET_INT64 7
+#define X86_RET_INT32 8
+#define X86_RET_VOID 9
+#define X86_RET_STRUCTPOP 10
+#define X86_RET_STRUCTARG 11
+#define X86_RET_STRUCT_1B 12
+#define X86_RET_STRUCT_2B 13
+#define X86_RET_UNUSED14 14
+#define X86_RET_UNUSED15 15
+
+#define X86_RET_TYPE_MASK 15
+#define X86_RET_POP_SHIFT 4
+
+#define R_EAX 0
+#define R_EDX 1
+#define R_ECX 2
+
+#ifdef __PCC__
+# define HAVE_FASTCALL 0
+#else
+# define HAVE_FASTCALL 1
+#endif
diff --git a/contrib/restricted/libffi/src/x86/internal64.h b/contrib/restricted/libffi/src/x86/internal64.h
index 62afd4a7e4..512e95523e 100644
--- a/contrib/restricted/libffi/src/x86/internal64.h
+++ b/contrib/restricted/libffi/src/x86/internal64.h
@@ -1,22 +1,22 @@
-#define UNIX64_RET_VOID 0
-#define UNIX64_RET_UINT8 1
-#define UNIX64_RET_UINT16 2
-#define UNIX64_RET_UINT32 3
-#define UNIX64_RET_SINT8 4
-#define UNIX64_RET_SINT16 5
-#define UNIX64_RET_SINT32 6
-#define UNIX64_RET_INT64 7
-#define UNIX64_RET_XMM32 8
-#define UNIX64_RET_XMM64 9
-#define UNIX64_RET_X87 10
-#define UNIX64_RET_X87_2 11
-#define UNIX64_RET_ST_XMM0_RAX 12
-#define UNIX64_RET_ST_RAX_XMM0 13
-#define UNIX64_RET_ST_XMM0_XMM1 14
-#define UNIX64_RET_ST_RAX_RDX 15
-
-#define UNIX64_RET_LAST 15
-
-#define UNIX64_FLAG_RET_IN_MEM (1 << 10)
-#define UNIX64_FLAG_XMM_ARGS (1 << 11)
-#define UNIX64_SIZE_SHIFT 12
+#define UNIX64_RET_VOID 0
+#define UNIX64_RET_UINT8 1
+#define UNIX64_RET_UINT16 2
+#define UNIX64_RET_UINT32 3
+#define UNIX64_RET_SINT8 4
+#define UNIX64_RET_SINT16 5
+#define UNIX64_RET_SINT32 6
+#define UNIX64_RET_INT64 7
+#define UNIX64_RET_XMM32 8
+#define UNIX64_RET_XMM64 9
+#define UNIX64_RET_X87 10
+#define UNIX64_RET_X87_2 11
+#define UNIX64_RET_ST_XMM0_RAX 12
+#define UNIX64_RET_ST_RAX_XMM0 13
+#define UNIX64_RET_ST_XMM0_XMM1 14
+#define UNIX64_RET_ST_RAX_RDX 15
+
+#define UNIX64_RET_LAST 15
+
+#define UNIX64_FLAG_RET_IN_MEM (1 << 10)
+#define UNIX64_FLAG_XMM_ARGS (1 << 11)
+#define UNIX64_SIZE_SHIFT 12
diff --git a/contrib/restricted/libffi/src/x86/sysv.S b/contrib/restricted/libffi/src/x86/sysv.S
index 5cf58668fe..7c9598c93c 100644
--- a/contrib/restricted/libffi/src/x86/sysv.S
+++ b/contrib/restricted/libffi/src/x86/sysv.S
@@ -1,7 +1,7 @@
/* -----------------------------------------------------------------------
- sysv.S - Copyright (c) 2017 Anthony Green
- - Copyright (c) 2013 The Written Word, Inc.
- - Copyright (c) 1996,1998,2001-2003,2005,2008,2010 Red Hat, Inc.
+ sysv.S - Copyright (c) 2017 Anthony Green
+ - Copyright (c) 2013 The Written Word, Inc.
+ - Copyright (c) 1996,1998,2001-2003,2005,2008,2010 Red Hat, Inc.
X86 Foreign Function Interface
@@ -26,1104 +26,1104 @@
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
-#ifdef __i386__
-#ifndef _MSC_VER
+#ifdef __i386__
+#ifndef _MSC_VER
#define LIBFFI_ASM
#include <fficonfig.h>
#include <ffi.h>
-#include "internal.h"
-
-#define C2(X, Y) X ## Y
-#define C1(X, Y) C2(X, Y)
-#ifdef __USER_LABEL_PREFIX__
-# define C(X) C1(__USER_LABEL_PREFIX__, X)
-#else
-# define C(X) X
-#endif
-
-#ifdef X86_DARWIN
-# define L(X) C1(L, X)
-#else
-# define L(X) C1(.L, X)
-#endif
-
-#ifdef __ELF__
-# define ENDF(X) .type X,@function; .size X, . - X
-#else
-# define ENDF(X)
-#endif
-
-/* Handle win32 fastcall name mangling. */
-#ifdef X86_WIN32
-# define ffi_call_i386 @ffi_call_i386@8
-# define ffi_closure_inner @ffi_closure_inner@8
-#else
-# define ffi_call_i386 C(ffi_call_i386)
-# define ffi_closure_inner C(ffi_closure_inner)
-#endif
-
-/* This macro allows the safe creation of jump tables without an
- actual table. The entry points into the table are all 8 bytes.
- The use of ORG asserts that we're at the correct location. */
-/* ??? The clang assembler doesn't handle .org with symbolic expressions. */
-#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__))
-# define E(BASE, X) .balign 8
-#else
-# define E(BASE, X) .balign 8; .org BASE + X * 8
-#endif
-
- .text
- .balign 16
- .globl ffi_call_i386
- FFI_HIDDEN(ffi_call_i386)
-
-/* This is declared as
-
- void ffi_call_i386(struct call_frame *frame, char *argp)
- __attribute__((fastcall));
-
- Thus the arguments are present in
-
- ecx: frame
- edx: argp
-*/
-
-ffi_call_i386:
-L(UW0):
- # cfi_startproc
-#if !HAVE_FASTCALL
- movl 4(%esp), %ecx
- movl 8(%esp), %edx
-#endif
- movl (%esp), %eax /* move the return address */
- movl %ebp, (%ecx) /* store %ebp into local frame */
- movl %eax, 4(%ecx) /* store retaddr into local frame */
-
- /* New stack frame based off ebp. This is a itty bit of unwind
- trickery in that the CFA *has* changed. There is no easy way
- to describe it correctly on entry to the function. Fortunately,
- it doesn't matter too much since at all points we can correctly
- unwind back to ffi_call. Note that the location to which we
- moved the return address is (the new) CFA-4, so from the
- perspective of the unwind info, it hasn't moved. */
- movl %ecx, %ebp
-L(UW1):
- # cfi_def_cfa(%ebp, 8)
- # cfi_rel_offset(%ebp, 0)
-
- movl %edx, %esp /* set outgoing argument stack */
- movl 20+R_EAX*4(%ebp), %eax /* set register arguments */
- movl 20+R_EDX*4(%ebp), %edx
- movl 20+R_ECX*4(%ebp), %ecx
-
- call *8(%ebp)
-
- movl 12(%ebp), %ecx /* load return type code */
- movl %ebx, 8(%ebp) /* preserve %ebx */
-L(UW2):
- # cfi_rel_offset(%ebx, 8)
-
- andl $X86_RET_TYPE_MASK, %ecx
-#ifdef __PIC__
- call C(__x86.get_pc_thunk.bx)
-L(pc1):
- leal L(store_table)-L(pc1)(%ebx, %ecx, 8), %ebx
-#else
- leal L(store_table)(,%ecx, 8), %ebx
-#endif
- movl 16(%ebp), %ecx /* load result address */
- jmp *%ebx
-
- .balign 8
-L(store_table):
-E(L(store_table), X86_RET_FLOAT)
- fstps (%ecx)
- jmp L(e1)
-E(L(store_table), X86_RET_DOUBLE)
- fstpl (%ecx)
- jmp L(e1)
-E(L(store_table), X86_RET_LDOUBLE)
- fstpt (%ecx)
- jmp L(e1)
-E(L(store_table), X86_RET_SINT8)
- movsbl %al, %eax
- mov %eax, (%ecx)
- jmp L(e1)
-E(L(store_table), X86_RET_SINT16)
- movswl %ax, %eax
- mov %eax, (%ecx)
- jmp L(e1)
-E(L(store_table), X86_RET_UINT8)
- movzbl %al, %eax
- mov %eax, (%ecx)
- jmp L(e1)
-E(L(store_table), X86_RET_UINT16)
- movzwl %ax, %eax
- mov %eax, (%ecx)
- jmp L(e1)
-E(L(store_table), X86_RET_INT64)
- movl %edx, 4(%ecx)
- /* fallthru */
-E(L(store_table), X86_RET_INT32)
- movl %eax, (%ecx)
- /* fallthru */
-E(L(store_table), X86_RET_VOID)
-L(e1):
- movl 8(%ebp), %ebx
- movl %ebp, %esp
- popl %ebp
-L(UW3):
- # cfi_remember_state
- # cfi_def_cfa(%esp, 4)
- # cfi_restore(%ebx)
- # cfi_restore(%ebp)
- ret
-L(UW4):
- # cfi_restore_state
-
-E(L(store_table), X86_RET_STRUCTPOP)
- jmp L(e1)
-E(L(store_table), X86_RET_STRUCTARG)
- jmp L(e1)
-E(L(store_table), X86_RET_STRUCT_1B)
- movb %al, (%ecx)
- jmp L(e1)
-E(L(store_table), X86_RET_STRUCT_2B)
- movw %ax, (%ecx)
- jmp L(e1)
-
- /* Fill out the table so that bad values are predictable. */
-E(L(store_table), X86_RET_UNUSED14)
- ud2
-E(L(store_table), X86_RET_UNUSED15)
- ud2
-
-L(UW5):
- # cfi_endproc
-ENDF(ffi_call_i386)
-
-/* The inner helper is declared as
-
- void ffi_closure_inner(struct closure_frame *frame, char *argp)
- __attribute_((fastcall))
-
- Thus the arguments are placed in
-
- ecx: frame
- edx: argp
-*/
-
-/* Macros to help setting up the closure_data structure. */
-
-#if HAVE_FASTCALL
-# define closure_FS (40 + 4)
-# define closure_CF 0
-#else
-# define closure_FS (8 + 40 + 12)
-# define closure_CF 8
-#endif
-
-#define FFI_CLOSURE_SAVE_REGS \
- movl %eax, closure_CF+16+R_EAX*4(%esp); \
- movl %edx, closure_CF+16+R_EDX*4(%esp); \
- movl %ecx, closure_CF+16+R_ECX*4(%esp)
-
-#define FFI_CLOSURE_COPY_TRAMP_DATA \
- movl FFI_TRAMPOLINE_SIZE(%eax), %edx; /* copy cif */ \
- movl FFI_TRAMPOLINE_SIZE+4(%eax), %ecx; /* copy fun */ \
- movl FFI_TRAMPOLINE_SIZE+8(%eax), %eax; /* copy user_data */ \
- movl %edx, closure_CF+28(%esp); \
- movl %ecx, closure_CF+32(%esp); \
- movl %eax, closure_CF+36(%esp)
-
-#if HAVE_FASTCALL
-# define FFI_CLOSURE_PREP_CALL \
- movl %esp, %ecx; /* load closure_data */ \
- leal closure_FS+4(%esp), %edx; /* load incoming stack */
+#include "internal.h"
+
+#define C2(X, Y) X ## Y
+#define C1(X, Y) C2(X, Y)
+#ifdef __USER_LABEL_PREFIX__
+# define C(X) C1(__USER_LABEL_PREFIX__, X)
+#else
+# define C(X) X
+#endif
+
+#ifdef X86_DARWIN
+# define L(X) C1(L, X)
+#else
+# define L(X) C1(.L, X)
+#endif
+
+#ifdef __ELF__
+# define ENDF(X) .type X,@function; .size X, . - X
+#else
+# define ENDF(X)
+#endif
+
+/* Handle win32 fastcall name mangling. */
+#ifdef X86_WIN32
+# define ffi_call_i386 @ffi_call_i386@8
+# define ffi_closure_inner @ffi_closure_inner@8
+#else
+# define ffi_call_i386 C(ffi_call_i386)
+# define ffi_closure_inner C(ffi_closure_inner)
+#endif
+
+/* This macro allows the safe creation of jump tables without an
+ actual table. The entry points into the table are all 8 bytes.
+ The use of ORG asserts that we're at the correct location. */
+/* ??? The clang assembler doesn't handle .org with symbolic expressions. */
+#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__))
+# define E(BASE, X) .balign 8
+#else
+# define E(BASE, X) .balign 8; .org BASE + X * 8
+#endif
+
+ .text
+ .balign 16
+ .globl ffi_call_i386
+ FFI_HIDDEN(ffi_call_i386)
+
+/* This is declared as
+
+ void ffi_call_i386(struct call_frame *frame, char *argp)
+ __attribute__((fastcall));
+
+ Thus the arguments are present in
+
+ ecx: frame
+ edx: argp
+*/
+
+ffi_call_i386:
+L(UW0):
+ # cfi_startproc
+#if !HAVE_FASTCALL
+ movl 4(%esp), %ecx
+ movl 8(%esp), %edx
+#endif
+ movl (%esp), %eax /* move the return address */
+ movl %ebp, (%ecx) /* store %ebp into local frame */
+ movl %eax, 4(%ecx) /* store retaddr into local frame */
+
+ /* New stack frame based off ebp. This is a itty bit of unwind
+ trickery in that the CFA *has* changed. There is no easy way
+ to describe it correctly on entry to the function. Fortunately,
+ it doesn't matter too much since at all points we can correctly
+ unwind back to ffi_call. Note that the location to which we
+ moved the return address is (the new) CFA-4, so from the
+ perspective of the unwind info, it hasn't moved. */
+ movl %ecx, %ebp
+L(UW1):
+ # cfi_def_cfa(%ebp, 8)
+ # cfi_rel_offset(%ebp, 0)
+
+ movl %edx, %esp /* set outgoing argument stack */
+ movl 20+R_EAX*4(%ebp), %eax /* set register arguments */
+ movl 20+R_EDX*4(%ebp), %edx
+ movl 20+R_ECX*4(%ebp), %ecx
+
+ call *8(%ebp)
+
+ movl 12(%ebp), %ecx /* load return type code */
+ movl %ebx, 8(%ebp) /* preserve %ebx */
+L(UW2):
+ # cfi_rel_offset(%ebx, 8)
+
+ andl $X86_RET_TYPE_MASK, %ecx
+#ifdef __PIC__
+ call C(__x86.get_pc_thunk.bx)
+L(pc1):
+ leal L(store_table)-L(pc1)(%ebx, %ecx, 8), %ebx
+#else
+ leal L(store_table)(,%ecx, 8), %ebx
+#endif
+ movl 16(%ebp), %ecx /* load result address */
+ jmp *%ebx
+
+ .balign 8
+L(store_table):
+E(L(store_table), X86_RET_FLOAT)
+ fstps (%ecx)
+ jmp L(e1)
+E(L(store_table), X86_RET_DOUBLE)
+ fstpl (%ecx)
+ jmp L(e1)
+E(L(store_table), X86_RET_LDOUBLE)
+ fstpt (%ecx)
+ jmp L(e1)
+E(L(store_table), X86_RET_SINT8)
+ movsbl %al, %eax
+ mov %eax, (%ecx)
+ jmp L(e1)
+E(L(store_table), X86_RET_SINT16)
+ movswl %ax, %eax
+ mov %eax, (%ecx)
+ jmp L(e1)
+E(L(store_table), X86_RET_UINT8)
+ movzbl %al, %eax
+ mov %eax, (%ecx)
+ jmp L(e1)
+E(L(store_table), X86_RET_UINT16)
+ movzwl %ax, %eax
+ mov %eax, (%ecx)
+ jmp L(e1)
+E(L(store_table), X86_RET_INT64)
+ movl %edx, 4(%ecx)
+ /* fallthru */
+E(L(store_table), X86_RET_INT32)
+ movl %eax, (%ecx)
+ /* fallthru */
+E(L(store_table), X86_RET_VOID)
+L(e1):
+ movl 8(%ebp), %ebx
+ movl %ebp, %esp
+ popl %ebp
+L(UW3):
+ # cfi_remember_state
+ # cfi_def_cfa(%esp, 4)
+ # cfi_restore(%ebx)
+ # cfi_restore(%ebp)
+ ret
+L(UW4):
+ # cfi_restore_state
+
+E(L(store_table), X86_RET_STRUCTPOP)
+ jmp L(e1)
+E(L(store_table), X86_RET_STRUCTARG)
+ jmp L(e1)
+E(L(store_table), X86_RET_STRUCT_1B)
+ movb %al, (%ecx)
+ jmp L(e1)
+E(L(store_table), X86_RET_STRUCT_2B)
+ movw %ax, (%ecx)
+ jmp L(e1)
+
+ /* Fill out the table so that bad values are predictable. */
+E(L(store_table), X86_RET_UNUSED14)
+ ud2
+E(L(store_table), X86_RET_UNUSED15)
+ ud2
+
+L(UW5):
+ # cfi_endproc
+ENDF(ffi_call_i386)
+
+/* The inner helper is declared as
+
+ void ffi_closure_inner(struct closure_frame *frame, char *argp)
+ __attribute_((fastcall))
+
+ Thus the arguments are placed in
+
+ ecx: frame
+ edx: argp
+*/
+
+/* Macros to help setting up the closure_data structure. */
+
+#if HAVE_FASTCALL
+# define closure_FS (40 + 4)
+# define closure_CF 0
#else
-# define FFI_CLOSURE_PREP_CALL \
- leal closure_CF(%esp), %ecx; /* load closure_data */ \
- leal closure_FS+4(%esp), %edx; /* load incoming stack */ \
- movl %ecx, (%esp); \
- movl %edx, 4(%esp)
+# define closure_FS (8 + 40 + 12)
+# define closure_CF 8
#endif
-#define FFI_CLOSURE_CALL_INNER(UWN) \
- call ffi_closure_inner
-
-#define FFI_CLOSURE_MASK_AND_JUMP(N, UW) \
- andl $X86_RET_TYPE_MASK, %eax; \
- leal L(C1(load_table,N))(, %eax, 8), %edx; \
- movl closure_CF(%esp), %eax; /* optimiztic load */ \
- jmp *%edx
-
-#ifdef __PIC__
-# if defined X86_DARWIN || defined HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-# undef FFI_CLOSURE_MASK_AND_JUMP
-# define FFI_CLOSURE_MASK_AND_JUMP(N, UW) \
- andl $X86_RET_TYPE_MASK, %eax; \
- call C(__x86.get_pc_thunk.dx); \
-L(C1(pc,N)): \
- leal L(C1(load_table,N))-L(C1(pc,N))(%edx, %eax, 8), %edx; \
- movl closure_CF(%esp), %eax; /* optimiztic load */ \
- jmp *%edx
-# else
-# define FFI_CLOSURE_CALL_INNER_SAVE_EBX
-# undef FFI_CLOSURE_CALL_INNER
-# define FFI_CLOSURE_CALL_INNER(UWN) \
- movl %ebx, 40(%esp); /* save ebx */ \
-L(C1(UW,UWN)): \
- /* cfi_rel_offset(%ebx, 40); */ \
- call C(__x86.get_pc_thunk.bx); /* load got register */ \
- addl $C(_GLOBAL_OFFSET_TABLE_), %ebx; \
- call ffi_closure_inner@PLT
-# undef FFI_CLOSURE_MASK_AND_JUMP
-# define FFI_CLOSURE_MASK_AND_JUMP(N, UWN) \
- andl $X86_RET_TYPE_MASK, %eax; \
- leal L(C1(load_table,N))@GOTOFF(%ebx, %eax, 8), %edx; \
- movl 40(%esp), %ebx; /* restore ebx */ \
-L(C1(UW,UWN)): \
- /* cfi_restore(%ebx); */ \
- movl closure_CF(%esp), %eax; /* optimiztic load */ \
- jmp *%edx
-# endif /* DARWIN || HIDDEN */
-#endif /* __PIC__ */
-
- .balign 16
- .globl C(ffi_go_closure_EAX)
- FFI_HIDDEN(C(ffi_go_closure_EAX))
-C(ffi_go_closure_EAX):
-L(UW6):
- # cfi_startproc
- subl $closure_FS, %esp
-L(UW7):
- # cfi_def_cfa_offset(closure_FS + 4)
- FFI_CLOSURE_SAVE_REGS
- movl 4(%eax), %edx /* copy cif */
- movl 8(%eax), %ecx /* copy fun */
- movl %edx, closure_CF+28(%esp)
- movl %ecx, closure_CF+32(%esp)
- movl %eax, closure_CF+36(%esp) /* closure is user_data */
- jmp L(do_closure_i386)
-L(UW8):
- # cfi_endproc
-ENDF(C(ffi_go_closure_EAX))
-
- .balign 16
- .globl C(ffi_go_closure_ECX)
- FFI_HIDDEN(C(ffi_go_closure_ECX))
-C(ffi_go_closure_ECX):
-L(UW9):
- # cfi_startproc
- subl $closure_FS, %esp
-L(UW10):
- # cfi_def_cfa_offset(closure_FS + 4)
- FFI_CLOSURE_SAVE_REGS
- movl 4(%ecx), %edx /* copy cif */
- movl 8(%ecx), %eax /* copy fun */
- movl %edx, closure_CF+28(%esp)
- movl %eax, closure_CF+32(%esp)
- movl %ecx, closure_CF+36(%esp) /* closure is user_data */
- jmp L(do_closure_i386)
-L(UW11):
- # cfi_endproc
-ENDF(C(ffi_go_closure_ECX))
-
-/* The closure entry points are reached from the ffi_closure trampoline.
- On entry, %eax contains the address of the ffi_closure. */
-
- .balign 16
- .globl C(ffi_closure_i386)
- FFI_HIDDEN(C(ffi_closure_i386))
-
-C(ffi_closure_i386):
-L(UW12):
- # cfi_startproc
- subl $closure_FS, %esp
-L(UW13):
- # cfi_def_cfa_offset(closure_FS + 4)
-
- FFI_CLOSURE_SAVE_REGS
- FFI_CLOSURE_COPY_TRAMP_DATA
-
- /* Entry point from preceeding Go closures. */
-L(do_closure_i386):
-
- FFI_CLOSURE_PREP_CALL
- FFI_CLOSURE_CALL_INNER(14)
- FFI_CLOSURE_MASK_AND_JUMP(2, 15)
-
- .balign 8
-L(load_table2):
-E(L(load_table2), X86_RET_FLOAT)
- flds closure_CF(%esp)
- jmp L(e2)
-E(L(load_table2), X86_RET_DOUBLE)
- fldl closure_CF(%esp)
- jmp L(e2)
-E(L(load_table2), X86_RET_LDOUBLE)
- fldt closure_CF(%esp)
- jmp L(e2)
-E(L(load_table2), X86_RET_SINT8)
- movsbl %al, %eax
- jmp L(e2)
-E(L(load_table2), X86_RET_SINT16)
- movswl %ax, %eax
- jmp L(e2)
-E(L(load_table2), X86_RET_UINT8)
- movzbl %al, %eax
- jmp L(e2)
-E(L(load_table2), X86_RET_UINT16)
- movzwl %ax, %eax
- jmp L(e2)
-E(L(load_table2), X86_RET_INT64)
- movl closure_CF+4(%esp), %edx
- jmp L(e2)
-E(L(load_table2), X86_RET_INT32)
- nop
- /* fallthru */
-E(L(load_table2), X86_RET_VOID)
-L(e2):
- addl $closure_FS, %esp
-L(UW16):
- # cfi_adjust_cfa_offset(-closure_FS)
+#define FFI_CLOSURE_SAVE_REGS \
+ movl %eax, closure_CF+16+R_EAX*4(%esp); \
+ movl %edx, closure_CF+16+R_EDX*4(%esp); \
+ movl %ecx, closure_CF+16+R_ECX*4(%esp)
+
+#define FFI_CLOSURE_COPY_TRAMP_DATA \
+ movl FFI_TRAMPOLINE_SIZE(%eax), %edx; /* copy cif */ \
+ movl FFI_TRAMPOLINE_SIZE+4(%eax), %ecx; /* copy fun */ \
+ movl FFI_TRAMPOLINE_SIZE+8(%eax), %eax; /* copy user_data */ \
+ movl %edx, closure_CF+28(%esp); \
+ movl %ecx, closure_CF+32(%esp); \
+ movl %eax, closure_CF+36(%esp)
+
+#if HAVE_FASTCALL
+# define FFI_CLOSURE_PREP_CALL \
+ movl %esp, %ecx; /* load closure_data */ \
+ leal closure_FS+4(%esp), %edx; /* load incoming stack */
+#else
+# define FFI_CLOSURE_PREP_CALL \
+ leal closure_CF(%esp), %ecx; /* load closure_data */ \
+ leal closure_FS+4(%esp), %edx; /* load incoming stack */ \
+ movl %ecx, (%esp); \
+ movl %edx, 4(%esp)
+#endif
+
+#define FFI_CLOSURE_CALL_INNER(UWN) \
+ call ffi_closure_inner
+
+#define FFI_CLOSURE_MASK_AND_JUMP(N, UW) \
+ andl $X86_RET_TYPE_MASK, %eax; \
+ leal L(C1(load_table,N))(, %eax, 8), %edx; \
+ movl closure_CF(%esp), %eax; /* optimiztic load */ \
+ jmp *%edx
+
+#ifdef __PIC__
+# if defined X86_DARWIN || defined HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+# undef FFI_CLOSURE_MASK_AND_JUMP
+# define FFI_CLOSURE_MASK_AND_JUMP(N, UW) \
+ andl $X86_RET_TYPE_MASK, %eax; \
+ call C(__x86.get_pc_thunk.dx); \
+L(C1(pc,N)): \
+ leal L(C1(load_table,N))-L(C1(pc,N))(%edx, %eax, 8), %edx; \
+ movl closure_CF(%esp), %eax; /* optimiztic load */ \
+ jmp *%edx
+# else
+# define FFI_CLOSURE_CALL_INNER_SAVE_EBX
+# undef FFI_CLOSURE_CALL_INNER
+# define FFI_CLOSURE_CALL_INNER(UWN) \
+ movl %ebx, 40(%esp); /* save ebx */ \
+L(C1(UW,UWN)): \
+ /* cfi_rel_offset(%ebx, 40); */ \
+ call C(__x86.get_pc_thunk.bx); /* load got register */ \
+ addl $C(_GLOBAL_OFFSET_TABLE_), %ebx; \
+ call ffi_closure_inner@PLT
+# undef FFI_CLOSURE_MASK_AND_JUMP
+# define FFI_CLOSURE_MASK_AND_JUMP(N, UWN) \
+ andl $X86_RET_TYPE_MASK, %eax; \
+ leal L(C1(load_table,N))@GOTOFF(%ebx, %eax, 8), %edx; \
+ movl 40(%esp), %ebx; /* restore ebx */ \
+L(C1(UW,UWN)): \
+ /* cfi_restore(%ebx); */ \
+ movl closure_CF(%esp), %eax; /* optimiztic load */ \
+ jmp *%edx
+# endif /* DARWIN || HIDDEN */
+#endif /* __PIC__ */
+
+ .balign 16
+ .globl C(ffi_go_closure_EAX)
+ FFI_HIDDEN(C(ffi_go_closure_EAX))
+C(ffi_go_closure_EAX):
+L(UW6):
+ # cfi_startproc
+ subl $closure_FS, %esp
+L(UW7):
+ # cfi_def_cfa_offset(closure_FS + 4)
+ FFI_CLOSURE_SAVE_REGS
+ movl 4(%eax), %edx /* copy cif */
+ movl 8(%eax), %ecx /* copy fun */
+ movl %edx, closure_CF+28(%esp)
+ movl %ecx, closure_CF+32(%esp)
+ movl %eax, closure_CF+36(%esp) /* closure is user_data */
+ jmp L(do_closure_i386)
+L(UW8):
+ # cfi_endproc
+ENDF(C(ffi_go_closure_EAX))
+
+ .balign 16
+ .globl C(ffi_go_closure_ECX)
+ FFI_HIDDEN(C(ffi_go_closure_ECX))
+C(ffi_go_closure_ECX):
+L(UW9):
+ # cfi_startproc
+ subl $closure_FS, %esp
+L(UW10):
+ # cfi_def_cfa_offset(closure_FS + 4)
+ FFI_CLOSURE_SAVE_REGS
+ movl 4(%ecx), %edx /* copy cif */
+ movl 8(%ecx), %eax /* copy fun */
+ movl %edx, closure_CF+28(%esp)
+ movl %eax, closure_CF+32(%esp)
+ movl %ecx, closure_CF+36(%esp) /* closure is user_data */
+ jmp L(do_closure_i386)
+L(UW11):
+ # cfi_endproc
+ENDF(C(ffi_go_closure_ECX))
+
+/* The closure entry points are reached from the ffi_closure trampoline.
+ On entry, %eax contains the address of the ffi_closure. */
+
+ .balign 16
+ .globl C(ffi_closure_i386)
+ FFI_HIDDEN(C(ffi_closure_i386))
+
+C(ffi_closure_i386):
+L(UW12):
+ # cfi_startproc
+ subl $closure_FS, %esp
+L(UW13):
+ # cfi_def_cfa_offset(closure_FS + 4)
+
+ FFI_CLOSURE_SAVE_REGS
+ FFI_CLOSURE_COPY_TRAMP_DATA
+
+ /* Entry point from preceeding Go closures. */
+L(do_closure_i386):
+
+ FFI_CLOSURE_PREP_CALL
+ FFI_CLOSURE_CALL_INNER(14)
+ FFI_CLOSURE_MASK_AND_JUMP(2, 15)
+
+ .balign 8
+L(load_table2):
+E(L(load_table2), X86_RET_FLOAT)
+ flds closure_CF(%esp)
+ jmp L(e2)
+E(L(load_table2), X86_RET_DOUBLE)
+ fldl closure_CF(%esp)
+ jmp L(e2)
+E(L(load_table2), X86_RET_LDOUBLE)
+ fldt closure_CF(%esp)
+ jmp L(e2)
+E(L(load_table2), X86_RET_SINT8)
+ movsbl %al, %eax
+ jmp L(e2)
+E(L(load_table2), X86_RET_SINT16)
+ movswl %ax, %eax
+ jmp L(e2)
+E(L(load_table2), X86_RET_UINT8)
+ movzbl %al, %eax
+ jmp L(e2)
+E(L(load_table2), X86_RET_UINT16)
+ movzwl %ax, %eax
+ jmp L(e2)
+E(L(load_table2), X86_RET_INT64)
+ movl closure_CF+4(%esp), %edx
+ jmp L(e2)
+E(L(load_table2), X86_RET_INT32)
+ nop
+ /* fallthru */
+E(L(load_table2), X86_RET_VOID)
+L(e2):
+ addl $closure_FS, %esp
+L(UW16):
+ # cfi_adjust_cfa_offset(-closure_FS)
ret
-L(UW17):
- # cfi_adjust_cfa_offset(closure_FS)
-E(L(load_table2), X86_RET_STRUCTPOP)
- addl $closure_FS, %esp
-L(UW18):
- # cfi_adjust_cfa_offset(-closure_FS)
+L(UW17):
+ # cfi_adjust_cfa_offset(closure_FS)
+E(L(load_table2), X86_RET_STRUCTPOP)
+ addl $closure_FS, %esp
+L(UW18):
+ # cfi_adjust_cfa_offset(-closure_FS)
ret $4
-L(UW19):
- # cfi_adjust_cfa_offset(closure_FS)
-E(L(load_table2), X86_RET_STRUCTARG)
- jmp L(e2)
-E(L(load_table2), X86_RET_STRUCT_1B)
- movzbl %al, %eax
- jmp L(e2)
-E(L(load_table2), X86_RET_STRUCT_2B)
- movzwl %ax, %eax
- jmp L(e2)
-
- /* Fill out the table so that bad values are predictable. */
-E(L(load_table2), X86_RET_UNUSED14)
- ud2
-E(L(load_table2), X86_RET_UNUSED15)
- ud2
-
-L(UW20):
- # cfi_endproc
-ENDF(C(ffi_closure_i386))
-
- .balign 16
- .globl C(ffi_go_closure_STDCALL)
- FFI_HIDDEN(C(ffi_go_closure_STDCALL))
-C(ffi_go_closure_STDCALL):
-L(UW21):
- # cfi_startproc
- subl $closure_FS, %esp
-L(UW22):
- # cfi_def_cfa_offset(closure_FS + 4)
- FFI_CLOSURE_SAVE_REGS
- movl 4(%ecx), %edx /* copy cif */
- movl 8(%ecx), %eax /* copy fun */
- movl %edx, closure_CF+28(%esp)
- movl %eax, closure_CF+32(%esp)
- movl %ecx, closure_CF+36(%esp) /* closure is user_data */
- jmp L(do_closure_STDCALL)
-L(UW23):
- # cfi_endproc
-ENDF(C(ffi_go_closure_STDCALL))
-
-/* For REGISTER, we have no available parameter registers, and so we
- enter here having pushed the closure onto the stack. */
-
- .balign 16
- .globl C(ffi_closure_REGISTER)
- FFI_HIDDEN(C(ffi_closure_REGISTER))
-C(ffi_closure_REGISTER):
-L(UW24):
- # cfi_startproc
- # cfi_def_cfa(%esp, 8)
- # cfi_offset(%eip, -8)
- subl $closure_FS-4, %esp
-L(UW25):
- # cfi_def_cfa_offset(closure_FS + 4)
- FFI_CLOSURE_SAVE_REGS
- movl closure_FS-4(%esp), %ecx /* load retaddr */
- movl closure_FS(%esp), %eax /* load closure */
- movl %ecx, closure_FS(%esp) /* move retaddr */
- jmp L(do_closure_REGISTER)
-L(UW26):
- # cfi_endproc
-ENDF(C(ffi_closure_REGISTER))
-
-/* For STDCALL (and others), we need to pop N bytes of arguments off
- the stack following the closure. The amount needing to be popped
- is returned to us from ffi_closure_inner. */
-
- .balign 16
- .globl C(ffi_closure_STDCALL)
- FFI_HIDDEN(C(ffi_closure_STDCALL))
-C(ffi_closure_STDCALL):
-L(UW27):
- # cfi_startproc
- subl $closure_FS, %esp
-L(UW28):
- # cfi_def_cfa_offset(closure_FS + 4)
-
- FFI_CLOSURE_SAVE_REGS
-
- /* Entry point from ffi_closure_REGISTER. */
-L(do_closure_REGISTER):
-
- FFI_CLOSURE_COPY_TRAMP_DATA
-
- /* Entry point from preceeding Go closure. */
-L(do_closure_STDCALL):
-
- FFI_CLOSURE_PREP_CALL
- FFI_CLOSURE_CALL_INNER(29)
-
- movl %eax, %ecx
- shrl $X86_RET_POP_SHIFT, %ecx /* isolate pop count */
- leal closure_FS(%esp, %ecx), %ecx /* compute popped esp */
- movl closure_FS(%esp), %edx /* move return address */
- movl %edx, (%ecx)
-
- /* From this point on, the value of %esp upon return is %ecx+4,
- and we've copied the return address to %ecx to make return easy.
- There's no point in representing this in the unwind info, as
- there is always a window between the mov and the ret which
- will be wrong from one point of view or another. */
-
- FFI_CLOSURE_MASK_AND_JUMP(3, 30)
-
- .balign 8
-L(load_table3):
-E(L(load_table3), X86_RET_FLOAT)
- flds closure_CF(%esp)
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_DOUBLE)
- fldl closure_CF(%esp)
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_LDOUBLE)
- fldt closure_CF(%esp)
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_SINT8)
- movsbl %al, %eax
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_SINT16)
- movswl %ax, %eax
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_UINT8)
- movzbl %al, %eax
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_UINT16)
- movzwl %ax, %eax
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_INT64)
- movl closure_CF+4(%esp), %edx
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_INT32)
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_VOID)
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_STRUCTPOP)
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_STRUCTARG)
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_STRUCT_1B)
- movzbl %al, %eax
- movl %ecx, %esp
- ret
-E(L(load_table3), X86_RET_STRUCT_2B)
- movzwl %ax, %eax
- movl %ecx, %esp
- ret
-
- /* Fill out the table so that bad values are predictable. */
-E(L(load_table3), X86_RET_UNUSED14)
- ud2
-E(L(load_table3), X86_RET_UNUSED15)
- ud2
-
-L(UW31):
- # cfi_endproc
-ENDF(C(ffi_closure_STDCALL))
-
+L(UW19):
+ # cfi_adjust_cfa_offset(closure_FS)
+E(L(load_table2), X86_RET_STRUCTARG)
+ jmp L(e2)
+E(L(load_table2), X86_RET_STRUCT_1B)
+ movzbl %al, %eax
+ jmp L(e2)
+E(L(load_table2), X86_RET_STRUCT_2B)
+ movzwl %ax, %eax
+ jmp L(e2)
+
+ /* Fill out the table so that bad values are predictable. */
+E(L(load_table2), X86_RET_UNUSED14)
+ ud2
+E(L(load_table2), X86_RET_UNUSED15)
+ ud2
+
+L(UW20):
+ # cfi_endproc
+ENDF(C(ffi_closure_i386))
+
+ .balign 16
+ .globl C(ffi_go_closure_STDCALL)
+ FFI_HIDDEN(C(ffi_go_closure_STDCALL))
+C(ffi_go_closure_STDCALL):
+L(UW21):
+ # cfi_startproc
+ subl $closure_FS, %esp
+L(UW22):
+ # cfi_def_cfa_offset(closure_FS + 4)
+ FFI_CLOSURE_SAVE_REGS
+ movl 4(%ecx), %edx /* copy cif */
+ movl 8(%ecx), %eax /* copy fun */
+ movl %edx, closure_CF+28(%esp)
+ movl %eax, closure_CF+32(%esp)
+ movl %ecx, closure_CF+36(%esp) /* closure is user_data */
+ jmp L(do_closure_STDCALL)
+L(UW23):
+ # cfi_endproc
+ENDF(C(ffi_go_closure_STDCALL))
+
+/* For REGISTER, we have no available parameter registers, and so we
+ enter here having pushed the closure onto the stack. */
+
+ .balign 16
+ .globl C(ffi_closure_REGISTER)
+ FFI_HIDDEN(C(ffi_closure_REGISTER))
+C(ffi_closure_REGISTER):
+L(UW24):
+ # cfi_startproc
+ # cfi_def_cfa(%esp, 8)
+ # cfi_offset(%eip, -8)
+ subl $closure_FS-4, %esp
+L(UW25):
+ # cfi_def_cfa_offset(closure_FS + 4)
+ FFI_CLOSURE_SAVE_REGS
+ movl closure_FS-4(%esp), %ecx /* load retaddr */
+ movl closure_FS(%esp), %eax /* load closure */
+ movl %ecx, closure_FS(%esp) /* move retaddr */
+ jmp L(do_closure_REGISTER)
+L(UW26):
+ # cfi_endproc
+ENDF(C(ffi_closure_REGISTER))
+
+/* For STDCALL (and others), we need to pop N bytes of arguments off
+ the stack following the closure. The amount needing to be popped
+ is returned to us from ffi_closure_inner. */
+
+ .balign 16
+ .globl C(ffi_closure_STDCALL)
+ FFI_HIDDEN(C(ffi_closure_STDCALL))
+C(ffi_closure_STDCALL):
+L(UW27):
+ # cfi_startproc
+ subl $closure_FS, %esp
+L(UW28):
+ # cfi_def_cfa_offset(closure_FS + 4)
+
+ FFI_CLOSURE_SAVE_REGS
+
+ /* Entry point from ffi_closure_REGISTER. */
+L(do_closure_REGISTER):
+
+ FFI_CLOSURE_COPY_TRAMP_DATA
+
+ /* Entry point from preceeding Go closure. */
+L(do_closure_STDCALL):
+
+ FFI_CLOSURE_PREP_CALL
+ FFI_CLOSURE_CALL_INNER(29)
+
+ movl %eax, %ecx
+ shrl $X86_RET_POP_SHIFT, %ecx /* isolate pop count */
+ leal closure_FS(%esp, %ecx), %ecx /* compute popped esp */
+ movl closure_FS(%esp), %edx /* move return address */
+ movl %edx, (%ecx)
+
+ /* From this point on, the value of %esp upon return is %ecx+4,
+ and we've copied the return address to %ecx to make return easy.
+ There's no point in representing this in the unwind info, as
+ there is always a window between the mov and the ret which
+ will be wrong from one point of view or another. */
+
+ FFI_CLOSURE_MASK_AND_JUMP(3, 30)
+
+ .balign 8
+L(load_table3):
+E(L(load_table3), X86_RET_FLOAT)
+ flds closure_CF(%esp)
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_DOUBLE)
+ fldl closure_CF(%esp)
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_LDOUBLE)
+ fldt closure_CF(%esp)
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_SINT8)
+ movsbl %al, %eax
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_SINT16)
+ movswl %ax, %eax
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_UINT8)
+ movzbl %al, %eax
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_UINT16)
+ movzwl %ax, %eax
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_INT64)
+ movl closure_CF+4(%esp), %edx
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_INT32)
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_VOID)
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_STRUCTPOP)
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_STRUCTARG)
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_STRUCT_1B)
+ movzbl %al, %eax
+ movl %ecx, %esp
+ ret
+E(L(load_table3), X86_RET_STRUCT_2B)
+ movzwl %ax, %eax
+ movl %ecx, %esp
+ ret
+
+ /* Fill out the table so that bad values are predictable. */
+E(L(load_table3), X86_RET_UNUSED14)
+ ud2
+E(L(load_table3), X86_RET_UNUSED15)
+ ud2
+
+L(UW31):
+ # cfi_endproc
+ENDF(C(ffi_closure_STDCALL))
+
#if !FFI_NO_RAW_API
-#define raw_closure_S_FS (16+16+12)
-
- .balign 16
- .globl C(ffi_closure_raw_SYSV)
- FFI_HIDDEN(C(ffi_closure_raw_SYSV))
-C(ffi_closure_raw_SYSV):
-L(UW32):
- # cfi_startproc
- subl $raw_closure_S_FS, %esp
-L(UW33):
- # cfi_def_cfa_offset(raw_closure_S_FS + 4)
- movl %ebx, raw_closure_S_FS-4(%esp)
-L(UW34):
- # cfi_rel_offset(%ebx, raw_closure_S_FS-4)
-
- movl FFI_TRAMPOLINE_SIZE+8(%eax), %edx /* load cl->user_data */
- movl %edx, 12(%esp)
- leal raw_closure_S_FS+4(%esp), %edx /* load raw_args */
- movl %edx, 8(%esp)
- leal 16(%esp), %edx /* load &res */
- movl %edx, 4(%esp)
- movl FFI_TRAMPOLINE_SIZE(%eax), %ebx /* load cl->cif */
- movl %ebx, (%esp)
- call *FFI_TRAMPOLINE_SIZE+4(%eax) /* call cl->fun */
-
- movl 20(%ebx), %eax /* load cif->flags */
- andl $X86_RET_TYPE_MASK, %eax
-#ifdef __PIC__
- call C(__x86.get_pc_thunk.bx)
-L(pc4):
- leal L(load_table4)-L(pc4)(%ebx, %eax, 8), %ecx
+#define raw_closure_S_FS (16+16+12)
+
+ .balign 16
+ .globl C(ffi_closure_raw_SYSV)
+ FFI_HIDDEN(C(ffi_closure_raw_SYSV))
+C(ffi_closure_raw_SYSV):
+L(UW32):
+ # cfi_startproc
+ subl $raw_closure_S_FS, %esp
+L(UW33):
+ # cfi_def_cfa_offset(raw_closure_S_FS + 4)
+ movl %ebx, raw_closure_S_FS-4(%esp)
+L(UW34):
+ # cfi_rel_offset(%ebx, raw_closure_S_FS-4)
+
+ movl FFI_TRAMPOLINE_SIZE+8(%eax), %edx /* load cl->user_data */
+ movl %edx, 12(%esp)
+ leal raw_closure_S_FS+4(%esp), %edx /* load raw_args */
+ movl %edx, 8(%esp)
+ leal 16(%esp), %edx /* load &res */
+ movl %edx, 4(%esp)
+ movl FFI_TRAMPOLINE_SIZE(%eax), %ebx /* load cl->cif */
+ movl %ebx, (%esp)
+ call *FFI_TRAMPOLINE_SIZE+4(%eax) /* call cl->fun */
+
+ movl 20(%ebx), %eax /* load cif->flags */
+ andl $X86_RET_TYPE_MASK, %eax
+#ifdef __PIC__
+ call C(__x86.get_pc_thunk.bx)
+L(pc4):
+ leal L(load_table4)-L(pc4)(%ebx, %eax, 8), %ecx
#else
- leal L(load_table4)(,%eax, 8), %ecx
+ leal L(load_table4)(,%eax, 8), %ecx
#endif
- movl raw_closure_S_FS-4(%esp), %ebx
-L(UW35):
- # cfi_restore(%ebx)
- movl 16(%esp), %eax /* Optimistic load */
- jmp *%ecx
-
- .balign 8
-L(load_table4):
-E(L(load_table4), X86_RET_FLOAT)
- flds 16(%esp)
- jmp L(e4)
-E(L(load_table4), X86_RET_DOUBLE)
- fldl 16(%esp)
- jmp L(e4)
-E(L(load_table4), X86_RET_LDOUBLE)
- fldt 16(%esp)
- jmp L(e4)
-E(L(load_table4), X86_RET_SINT8)
- movsbl %al, %eax
- jmp L(e4)
-E(L(load_table4), X86_RET_SINT16)
- movswl %ax, %eax
- jmp L(e4)
-E(L(load_table4), X86_RET_UINT8)
- movzbl %al, %eax
- jmp L(e4)
-E(L(load_table4), X86_RET_UINT16)
- movzwl %ax, %eax
- jmp L(e4)
-E(L(load_table4), X86_RET_INT64)
- movl 16+4(%esp), %edx
- jmp L(e4)
-E(L(load_table4), X86_RET_INT32)
- nop
- /* fallthru */
-E(L(load_table4), X86_RET_VOID)
-L(e4):
- addl $raw_closure_S_FS, %esp
-L(UW36):
- # cfi_adjust_cfa_offset(-raw_closure_S_FS)
- ret
-L(UW37):
- # cfi_adjust_cfa_offset(raw_closure_S_FS)
-E(L(load_table4), X86_RET_STRUCTPOP)
- addl $raw_closure_S_FS, %esp
-L(UW38):
- # cfi_adjust_cfa_offset(-raw_closure_S_FS)
- ret $4
-L(UW39):
- # cfi_adjust_cfa_offset(raw_closure_S_FS)
-E(L(load_table4), X86_RET_STRUCTARG)
- jmp L(e4)
-E(L(load_table4), X86_RET_STRUCT_1B)
- movzbl %al, %eax
- jmp L(e4)
-E(L(load_table4), X86_RET_STRUCT_2B)
- movzwl %ax, %eax
- jmp L(e4)
-
- /* Fill out the table so that bad values are predictable. */
-E(L(load_table4), X86_RET_UNUSED14)
- ud2
-E(L(load_table4), X86_RET_UNUSED15)
- ud2
-
-L(UW40):
- # cfi_endproc
-ENDF(C(ffi_closure_raw_SYSV))
-
-#define raw_closure_T_FS (16+16+8)
-
- .balign 16
- .globl C(ffi_closure_raw_THISCALL)
- FFI_HIDDEN(C(ffi_closure_raw_THISCALL))
-C(ffi_closure_raw_THISCALL):
-L(UW41):
- # cfi_startproc
- /* Rearrange the stack such that %ecx is the first argument.
- This means moving the return address. */
- popl %edx
-L(UW42):
- # cfi_def_cfa_offset(0)
- # cfi_register(%eip, %edx)
- pushl %ecx
-L(UW43):
- # cfi_adjust_cfa_offset(4)
- pushl %edx
-L(UW44):
- # cfi_adjust_cfa_offset(4)
- # cfi_rel_offset(%eip, 0)
- subl $raw_closure_T_FS, %esp
-L(UW45):
- # cfi_adjust_cfa_offset(raw_closure_T_FS)
- movl %ebx, raw_closure_T_FS-4(%esp)
-L(UW46):
- # cfi_rel_offset(%ebx, raw_closure_T_FS-4)
-
- movl FFI_TRAMPOLINE_SIZE+8(%eax), %edx /* load cl->user_data */
- movl %edx, 12(%esp)
- leal raw_closure_T_FS+4(%esp), %edx /* load raw_args */
- movl %edx, 8(%esp)
- leal 16(%esp), %edx /* load &res */
- movl %edx, 4(%esp)
- movl FFI_TRAMPOLINE_SIZE(%eax), %ebx /* load cl->cif */
- movl %ebx, (%esp)
- call *FFI_TRAMPOLINE_SIZE+4(%eax) /* call cl->fun */
-
- movl 20(%ebx), %eax /* load cif->flags */
- andl $X86_RET_TYPE_MASK, %eax
-#ifdef __PIC__
- call C(__x86.get_pc_thunk.bx)
-L(pc5):
- leal L(load_table5)-L(pc5)(%ebx, %eax, 8), %ecx
-#else
- leal L(load_table5)(,%eax, 8), %ecx
+ movl raw_closure_S_FS-4(%esp), %ebx
+L(UW35):
+ # cfi_restore(%ebx)
+ movl 16(%esp), %eax /* Optimistic load */
+ jmp *%ecx
+
+ .balign 8
+L(load_table4):
+E(L(load_table4), X86_RET_FLOAT)
+ flds 16(%esp)
+ jmp L(e4)
+E(L(load_table4), X86_RET_DOUBLE)
+ fldl 16(%esp)
+ jmp L(e4)
+E(L(load_table4), X86_RET_LDOUBLE)
+ fldt 16(%esp)
+ jmp L(e4)
+E(L(load_table4), X86_RET_SINT8)
+ movsbl %al, %eax
+ jmp L(e4)
+E(L(load_table4), X86_RET_SINT16)
+ movswl %ax, %eax
+ jmp L(e4)
+E(L(load_table4), X86_RET_UINT8)
+ movzbl %al, %eax
+ jmp L(e4)
+E(L(load_table4), X86_RET_UINT16)
+ movzwl %ax, %eax
+ jmp L(e4)
+E(L(load_table4), X86_RET_INT64)
+ movl 16+4(%esp), %edx
+ jmp L(e4)
+E(L(load_table4), X86_RET_INT32)
+ nop
+ /* fallthru */
+E(L(load_table4), X86_RET_VOID)
+L(e4):
+ addl $raw_closure_S_FS, %esp
+L(UW36):
+ # cfi_adjust_cfa_offset(-raw_closure_S_FS)
+ ret
+L(UW37):
+ # cfi_adjust_cfa_offset(raw_closure_S_FS)
+E(L(load_table4), X86_RET_STRUCTPOP)
+ addl $raw_closure_S_FS, %esp
+L(UW38):
+ # cfi_adjust_cfa_offset(-raw_closure_S_FS)
+ ret $4
+L(UW39):
+ # cfi_adjust_cfa_offset(raw_closure_S_FS)
+E(L(load_table4), X86_RET_STRUCTARG)
+ jmp L(e4)
+E(L(load_table4), X86_RET_STRUCT_1B)
+ movzbl %al, %eax
+ jmp L(e4)
+E(L(load_table4), X86_RET_STRUCT_2B)
+ movzwl %ax, %eax
+ jmp L(e4)
+
+ /* Fill out the table so that bad values are predictable. */
+E(L(load_table4), X86_RET_UNUSED14)
+ ud2
+E(L(load_table4), X86_RET_UNUSED15)
+ ud2
+
+L(UW40):
+ # cfi_endproc
+ENDF(C(ffi_closure_raw_SYSV))
+
+#define raw_closure_T_FS (16+16+8)
+
+ .balign 16
+ .globl C(ffi_closure_raw_THISCALL)
+ FFI_HIDDEN(C(ffi_closure_raw_THISCALL))
+C(ffi_closure_raw_THISCALL):
+L(UW41):
+ # cfi_startproc
+ /* Rearrange the stack such that %ecx is the first argument.
+ This means moving the return address. */
+ popl %edx
+L(UW42):
+ # cfi_def_cfa_offset(0)
+ # cfi_register(%eip, %edx)
+ pushl %ecx
+L(UW43):
+ # cfi_adjust_cfa_offset(4)
+ pushl %edx
+L(UW44):
+ # cfi_adjust_cfa_offset(4)
+ # cfi_rel_offset(%eip, 0)
+ subl $raw_closure_T_FS, %esp
+L(UW45):
+ # cfi_adjust_cfa_offset(raw_closure_T_FS)
+ movl %ebx, raw_closure_T_FS-4(%esp)
+L(UW46):
+ # cfi_rel_offset(%ebx, raw_closure_T_FS-4)
+
+ movl FFI_TRAMPOLINE_SIZE+8(%eax), %edx /* load cl->user_data */
+ movl %edx, 12(%esp)
+ leal raw_closure_T_FS+4(%esp), %edx /* load raw_args */
+ movl %edx, 8(%esp)
+ leal 16(%esp), %edx /* load &res */
+ movl %edx, 4(%esp)
+ movl FFI_TRAMPOLINE_SIZE(%eax), %ebx /* load cl->cif */
+ movl %ebx, (%esp)
+ call *FFI_TRAMPOLINE_SIZE+4(%eax) /* call cl->fun */
+
+ movl 20(%ebx), %eax /* load cif->flags */
+ andl $X86_RET_TYPE_MASK, %eax
+#ifdef __PIC__
+ call C(__x86.get_pc_thunk.bx)
+L(pc5):
+ leal L(load_table5)-L(pc5)(%ebx, %eax, 8), %ecx
+#else
+ leal L(load_table5)(,%eax, 8), %ecx
#endif
- movl raw_closure_T_FS-4(%esp), %ebx
-L(UW47):
- # cfi_restore(%ebx)
- movl 16(%esp), %eax /* Optimistic load */
- jmp *%ecx
-
- .balign 8
-L(load_table5):
-E(L(load_table5), X86_RET_FLOAT)
- flds 16(%esp)
- jmp L(e5)
-E(L(load_table5), X86_RET_DOUBLE)
- fldl 16(%esp)
- jmp L(e5)
-E(L(load_table5), X86_RET_LDOUBLE)
- fldt 16(%esp)
- jmp L(e5)
-E(L(load_table5), X86_RET_SINT8)
- movsbl %al, %eax
- jmp L(e5)
-E(L(load_table5), X86_RET_SINT16)
- movswl %ax, %eax
- jmp L(e5)
-E(L(load_table5), X86_RET_UINT8)
- movzbl %al, %eax
- jmp L(e5)
-E(L(load_table5), X86_RET_UINT16)
- movzwl %ax, %eax
- jmp L(e5)
-E(L(load_table5), X86_RET_INT64)
- movl 16+4(%esp), %edx
- jmp L(e5)
-E(L(load_table5), X86_RET_INT32)
- nop
- /* fallthru */
-E(L(load_table5), X86_RET_VOID)
-L(e5):
- addl $raw_closure_T_FS, %esp
-L(UW48):
- # cfi_adjust_cfa_offset(-raw_closure_T_FS)
- /* Remove the extra %ecx argument we pushed. */
- ret $4
-L(UW49):
- # cfi_adjust_cfa_offset(raw_closure_T_FS)
-E(L(load_table5), X86_RET_STRUCTPOP)
- addl $raw_closure_T_FS, %esp
-L(UW50):
- # cfi_adjust_cfa_offset(-raw_closure_T_FS)
- ret $8
-L(UW51):
- # cfi_adjust_cfa_offset(raw_closure_T_FS)
-E(L(load_table5), X86_RET_STRUCTARG)
- jmp L(e5)
-E(L(load_table5), X86_RET_STRUCT_1B)
- movzbl %al, %eax
- jmp L(e5)
-E(L(load_table5), X86_RET_STRUCT_2B)
- movzwl %ax, %eax
- jmp L(e5)
-
- /* Fill out the table so that bad values are predictable. */
-E(L(load_table5), X86_RET_UNUSED14)
- ud2
-E(L(load_table5), X86_RET_UNUSED15)
- ud2
-
-L(UW52):
- # cfi_endproc
-ENDF(C(ffi_closure_raw_THISCALL))
-
-#endif /* !FFI_NO_RAW_API */
-
-#ifdef X86_DARWIN
-# define COMDAT(X) \
- .section __TEXT,__text,coalesced,pure_instructions; \
- .weak_definition X; \
- FFI_HIDDEN(X)
-#elif defined __ELF__ && !(defined(__sun__) && defined(__svr4__))
-# define COMDAT(X) \
- .section .text.X,"axG",@progbits,X,comdat; \
- .globl X; \
- FFI_HIDDEN(X)
+ movl raw_closure_T_FS-4(%esp), %ebx
+L(UW47):
+ # cfi_restore(%ebx)
+ movl 16(%esp), %eax /* Optimistic load */
+ jmp *%ecx
+
+ .balign 8
+L(load_table5):
+E(L(load_table5), X86_RET_FLOAT)
+ flds 16(%esp)
+ jmp L(e5)
+E(L(load_table5), X86_RET_DOUBLE)
+ fldl 16(%esp)
+ jmp L(e5)
+E(L(load_table5), X86_RET_LDOUBLE)
+ fldt 16(%esp)
+ jmp L(e5)
+E(L(load_table5), X86_RET_SINT8)
+ movsbl %al, %eax
+ jmp L(e5)
+E(L(load_table5), X86_RET_SINT16)
+ movswl %ax, %eax
+ jmp L(e5)
+E(L(load_table5), X86_RET_UINT8)
+ movzbl %al, %eax
+ jmp L(e5)
+E(L(load_table5), X86_RET_UINT16)
+ movzwl %ax, %eax
+ jmp L(e5)
+E(L(load_table5), X86_RET_INT64)
+ movl 16+4(%esp), %edx
+ jmp L(e5)
+E(L(load_table5), X86_RET_INT32)
+ nop
+ /* fallthru */
+E(L(load_table5), X86_RET_VOID)
+L(e5):
+ addl $raw_closure_T_FS, %esp
+L(UW48):
+ # cfi_adjust_cfa_offset(-raw_closure_T_FS)
+ /* Remove the extra %ecx argument we pushed. */
+ ret $4
+L(UW49):
+ # cfi_adjust_cfa_offset(raw_closure_T_FS)
+E(L(load_table5), X86_RET_STRUCTPOP)
+ addl $raw_closure_T_FS, %esp
+L(UW50):
+ # cfi_adjust_cfa_offset(-raw_closure_T_FS)
+ ret $8
+L(UW51):
+ # cfi_adjust_cfa_offset(raw_closure_T_FS)
+E(L(load_table5), X86_RET_STRUCTARG)
+ jmp L(e5)
+E(L(load_table5), X86_RET_STRUCT_1B)
+ movzbl %al, %eax
+ jmp L(e5)
+E(L(load_table5), X86_RET_STRUCT_2B)
+ movzwl %ax, %eax
+ jmp L(e5)
+
+ /* Fill out the table so that bad values are predictable. */
+E(L(load_table5), X86_RET_UNUSED14)
+ ud2
+E(L(load_table5), X86_RET_UNUSED15)
+ ud2
+
+L(UW52):
+ # cfi_endproc
+ENDF(C(ffi_closure_raw_THISCALL))
+
+#endif /* !FFI_NO_RAW_API */
+
+#ifdef X86_DARWIN
+# define COMDAT(X) \
+ .section __TEXT,__text,coalesced,pure_instructions; \
+ .weak_definition X; \
+ FFI_HIDDEN(X)
+#elif defined __ELF__ && !(defined(__sun__) && defined(__svr4__))
+# define COMDAT(X) \
+ .section .text.X,"axG",@progbits,X,comdat; \
+ .globl X; \
+ FFI_HIDDEN(X)
#else
-# define COMDAT(X)
+# define COMDAT(X)
#endif
-#if defined(__PIC__)
- COMDAT(C(__x86.get_pc_thunk.bx))
-C(__x86.get_pc_thunk.bx):
- movl (%esp), %ebx
- ret
-ENDF(C(__x86.get_pc_thunk.bx))
-# if defined X86_DARWIN || defined HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
- COMDAT(C(__x86.get_pc_thunk.dx))
-C(__x86.get_pc_thunk.dx):
- movl (%esp), %edx
- ret
-ENDF(C(__x86.get_pc_thunk.dx))
-#endif /* DARWIN || HIDDEN */
-#endif /* __PIC__ */
-
-/* Sadly, OSX cctools-as doesn't understand .cfi directives at all. */
-
-#ifdef __APPLE__
-.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
-EHFrame0:
-#elif defined(X86_WIN32)
-.section .eh_frame,"r"
-#elif defined(HAVE_AS_X86_64_UNWIND_SECTION_TYPE)
-.section .eh_frame,EH_FRAME_FLAGS,@unwind
+#if defined(__PIC__)
+ COMDAT(C(__x86.get_pc_thunk.bx))
+C(__x86.get_pc_thunk.bx):
+ movl (%esp), %ebx
+ ret
+ENDF(C(__x86.get_pc_thunk.bx))
+# if defined X86_DARWIN || defined HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+ COMDAT(C(__x86.get_pc_thunk.dx))
+C(__x86.get_pc_thunk.dx):
+ movl (%esp), %edx
+ ret
+ENDF(C(__x86.get_pc_thunk.dx))
+#endif /* DARWIN || HIDDEN */
+#endif /* __PIC__ */
+
+/* Sadly, OSX cctools-as doesn't understand .cfi directives at all. */
+
+#ifdef __APPLE__
+.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
+EHFrame0:
+#elif defined(X86_WIN32)
+.section .eh_frame,"r"
+#elif defined(HAVE_AS_X86_64_UNWIND_SECTION_TYPE)
+.section .eh_frame,EH_FRAME_FLAGS,@unwind
#else
-.section .eh_frame,EH_FRAME_FLAGS,@progbits
+.section .eh_frame,EH_FRAME_FLAGS,@progbits
#endif
-
-#ifdef HAVE_AS_X86_PCREL
-# define PCREL(X) X - .
+
+#ifdef HAVE_AS_X86_PCREL
+# define PCREL(X) X - .
#else
-# define PCREL(X) X@rel
+# define PCREL(X) X@rel
#endif
-
-/* Simplify advancing between labels. Assume DW_CFA_advance_loc1 fits. */
-#define ADV(N, P) .byte 2, L(N)-L(P)
-
- .balign 4
-L(CIE):
- .set L(set0),L(ECIE)-L(SCIE)
- .long L(set0) /* CIE Length */
-L(SCIE):
- .long 0 /* CIE Identifier Tag */
- .byte 1 /* CIE Version */
- .ascii "zR\0" /* CIE Augmentation */
- .byte 1 /* CIE Code Alignment Factor */
- .byte 0x7c /* CIE Data Alignment Factor */
- .byte 0x8 /* CIE RA Column */
- .byte 1 /* Augmentation size */
- .byte 0x1b /* FDE Encoding (pcrel sdata4) */
- .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp offset 4 */
- .byte 0x80+8, 1 /* DW_CFA_offset, %eip offset 1*-4 */
- .balign 4
-L(ECIE):
-
- .set L(set1),L(EFDE1)-L(SFDE1)
- .long L(set1) /* FDE Length */
-L(SFDE1):
- .long L(SFDE1)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW0)) /* Initial location */
- .long L(UW5)-L(UW0) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW1, UW0)
- .byte 0xc, 5, 8 /* DW_CFA_def_cfa, %ebp 8 */
- .byte 0x80+5, 2 /* DW_CFA_offset, %ebp 2*-4 */
- ADV(UW2, UW1)
- .byte 0x80+3, 0 /* DW_CFA_offset, %ebx 0*-4 */
- ADV(UW3, UW2)
- .byte 0xa /* DW_CFA_remember_state */
- .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp 4 */
- .byte 0xc0+3 /* DW_CFA_restore, %ebx */
- .byte 0xc0+5 /* DW_CFA_restore, %ebp */
- ADV(UW4, UW3)
- .byte 0xb /* DW_CFA_restore_state */
- .balign 4
-L(EFDE1):
-
- .set L(set2),L(EFDE2)-L(SFDE2)
- .long L(set2) /* FDE Length */
-L(SFDE2):
- .long L(SFDE2)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW6)) /* Initial location */
- .long L(UW8)-L(UW6) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW7, UW6)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE2):
-
- .set L(set3),L(EFDE3)-L(SFDE3)
- .long L(set3) /* FDE Length */
-L(SFDE3):
- .long L(SFDE3)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW9)) /* Initial location */
- .long L(UW11)-L(UW9) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW10, UW9)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE3):
-
- .set L(set4),L(EFDE4)-L(SFDE4)
- .long L(set4) /* FDE Length */
-L(SFDE4):
- .long L(SFDE4)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW12)) /* Initial location */
- .long L(UW20)-L(UW12) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW13, UW12)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
-#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX
- ADV(UW14, UW13)
- .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */
- ADV(UW15, UW14)
- .byte 0xc0+3 /* DW_CFA_restore %ebx */
- ADV(UW16, UW15)
+
+/* Simplify advancing between labels. Assume DW_CFA_advance_loc1 fits. */
+#define ADV(N, P) .byte 2, L(N)-L(P)
+
+ .balign 4
+L(CIE):
+ .set L(set0),L(ECIE)-L(SCIE)
+ .long L(set0) /* CIE Length */
+L(SCIE):
+ .long 0 /* CIE Identifier Tag */
+ .byte 1 /* CIE Version */
+ .ascii "zR\0" /* CIE Augmentation */
+ .byte 1 /* CIE Code Alignment Factor */
+ .byte 0x7c /* CIE Data Alignment Factor */
+ .byte 0x8 /* CIE RA Column */
+ .byte 1 /* Augmentation size */
+ .byte 0x1b /* FDE Encoding (pcrel sdata4) */
+ .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp offset 4 */
+ .byte 0x80+8, 1 /* DW_CFA_offset, %eip offset 1*-4 */
+ .balign 4
+L(ECIE):
+
+ .set L(set1),L(EFDE1)-L(SFDE1)
+ .long L(set1) /* FDE Length */
+L(SFDE1):
+ .long L(SFDE1)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW0)) /* Initial location */
+ .long L(UW5)-L(UW0) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW1, UW0)
+ .byte 0xc, 5, 8 /* DW_CFA_def_cfa, %ebp 8 */
+ .byte 0x80+5, 2 /* DW_CFA_offset, %ebp 2*-4 */
+ ADV(UW2, UW1)
+ .byte 0x80+3, 0 /* DW_CFA_offset, %ebx 0*-4 */
+ ADV(UW3, UW2)
+ .byte 0xa /* DW_CFA_remember_state */
+ .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp 4 */
+ .byte 0xc0+3 /* DW_CFA_restore, %ebx */
+ .byte 0xc0+5 /* DW_CFA_restore, %ebp */
+ ADV(UW4, UW3)
+ .byte 0xb /* DW_CFA_restore_state */
+ .balign 4
+L(EFDE1):
+
+ .set L(set2),L(EFDE2)-L(SFDE2)
+ .long L(set2) /* FDE Length */
+L(SFDE2):
+ .long L(SFDE2)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW6)) /* Initial location */
+ .long L(UW8)-L(UW6) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW7, UW6)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE2):
+
+ .set L(set3),L(EFDE3)-L(SFDE3)
+ .long L(set3) /* FDE Length */
+L(SFDE3):
+ .long L(SFDE3)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW9)) /* Initial location */
+ .long L(UW11)-L(UW9) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW10, UW9)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE3):
+
+ .set L(set4),L(EFDE4)-L(SFDE4)
+ .long L(set4) /* FDE Length */
+L(SFDE4):
+ .long L(SFDE4)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW12)) /* Initial location */
+ .long L(UW20)-L(UW12) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW13, UW12)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX
+ ADV(UW14, UW13)
+ .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */
+ ADV(UW15, UW14)
+ .byte 0xc0+3 /* DW_CFA_restore %ebx */
+ ADV(UW16, UW15)
#else
- ADV(UW16, UW13)
+ ADV(UW16, UW13)
#endif
- .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
- ADV(UW17, UW16)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- ADV(UW18, UW17)
- .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
- ADV(UW19, UW18)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE4):
-
- .set L(set5),L(EFDE5)-L(SFDE5)
- .long L(set5) /* FDE Length */
-L(SFDE5):
- .long L(SFDE5)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW21)) /* Initial location */
- .long L(UW23)-L(UW21) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW22, UW21)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE5):
-
- .set L(set6),L(EFDE6)-L(SFDE6)
- .long L(set6) /* FDE Length */
-L(SFDE6):
- .long L(SFDE6)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW24)) /* Initial location */
- .long L(UW26)-L(UW24) /* Address range */
- .byte 0 /* Augmentation size */
- .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
- .byte 0x80+8, 2 /* DW_CFA_offset %eip, 2*-4 */
- ADV(UW25, UW24)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE6):
-
- .set L(set7),L(EFDE7)-L(SFDE7)
- .long L(set7) /* FDE Length */
-L(SFDE7):
- .long L(SFDE7)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW27)) /* Initial location */
- .long L(UW31)-L(UW27) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW28, UW27)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
-#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX
- ADV(UW29, UW28)
- .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */
- ADV(UW30, UW29)
- .byte 0xc0+3 /* DW_CFA_restore %ebx */
+ .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
+ ADV(UW17, UW16)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ ADV(UW18, UW17)
+ .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
+ ADV(UW19, UW18)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE4):
+
+ .set L(set5),L(EFDE5)-L(SFDE5)
+ .long L(set5) /* FDE Length */
+L(SFDE5):
+ .long L(SFDE5)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW21)) /* Initial location */
+ .long L(UW23)-L(UW21) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW22, UW21)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE5):
+
+ .set L(set6),L(EFDE6)-L(SFDE6)
+ .long L(set6) /* FDE Length */
+L(SFDE6):
+ .long L(SFDE6)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW24)) /* Initial location */
+ .long L(UW26)-L(UW24) /* Address range */
+ .byte 0 /* Augmentation size */
+ .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
+ .byte 0x80+8, 2 /* DW_CFA_offset %eip, 2*-4 */
+ ADV(UW25, UW24)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE6):
+
+ .set L(set7),L(EFDE7)-L(SFDE7)
+ .long L(set7) /* FDE Length */
+L(SFDE7):
+ .long L(SFDE7)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW27)) /* Initial location */
+ .long L(UW31)-L(UW27) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW28, UW27)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX
+ ADV(UW29, UW28)
+ .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */
+ ADV(UW30, UW29)
+ .byte 0xc0+3 /* DW_CFA_restore %ebx */
#endif
- .balign 4
-L(EFDE7):
+ .balign 4
+L(EFDE7):
#if !FFI_NO_RAW_API
- .set L(set8),L(EFDE8)-L(SFDE8)
- .long L(set8) /* FDE Length */
-L(SFDE8):
- .long L(SFDE8)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW32)) /* Initial location */
- .long L(UW40)-L(UW32) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW33, UW32)
- .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
- ADV(UW34, UW33)
- .byte 0x80+3, 2 /* DW_CFA_offset %ebx 2*-4 */
- ADV(UW35, UW34)
- .byte 0xc0+3 /* DW_CFA_restore %ebx */
- ADV(UW36, UW35)
- .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
- ADV(UW37, UW36)
- .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
- ADV(UW38, UW37)
- .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
- ADV(UW39, UW38)
- .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE8):
-
- .set L(set9),L(EFDE9)-L(SFDE9)
- .long L(set9) /* FDE Length */
-L(SFDE9):
- .long L(SFDE9)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW41)) /* Initial location */
- .long L(UW52)-L(UW41) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW42, UW41)
- .byte 0xe, 0 /* DW_CFA_def_cfa_offset */
- .byte 0x9, 8, 2 /* DW_CFA_register %eip, %edx */
- ADV(UW43, UW42)
- .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
- ADV(UW44, UW43)
- .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
- .byte 0x80+8, 2 /* DW_CFA_offset %eip 2*-4 */
- ADV(UW45, UW44)
- .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
- ADV(UW46, UW45)
- .byte 0x80+3, 3 /* DW_CFA_offset %ebx 3*-4 */
- ADV(UW47, UW46)
- .byte 0xc0+3 /* DW_CFA_restore %ebx */
- ADV(UW48, UW47)
- .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
- ADV(UW49, UW48)
- .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
- ADV(UW50, UW49)
- .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
- ADV(UW51, UW50)
- .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE9):
-#endif /* !FFI_NO_RAW_API */
-
-#ifdef _WIN32
- .def @feat.00;
- .scl 3;
- .type 0;
- .endef
- .globl @feat.00
-@feat.00 = 1
+ .set L(set8),L(EFDE8)-L(SFDE8)
+ .long L(set8) /* FDE Length */
+L(SFDE8):
+ .long L(SFDE8)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW32)) /* Initial location */
+ .long L(UW40)-L(UW32) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW33, UW32)
+ .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
+ ADV(UW34, UW33)
+ .byte 0x80+3, 2 /* DW_CFA_offset %ebx 2*-4 */
+ ADV(UW35, UW34)
+ .byte 0xc0+3 /* DW_CFA_restore %ebx */
+ ADV(UW36, UW35)
+ .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
+ ADV(UW37, UW36)
+ .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
+ ADV(UW38, UW37)
+ .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
+ ADV(UW39, UW38)
+ .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE8):
+
+ .set L(set9),L(EFDE9)-L(SFDE9)
+ .long L(set9) /* FDE Length */
+L(SFDE9):
+ .long L(SFDE9)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW41)) /* Initial location */
+ .long L(UW52)-L(UW41) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW42, UW41)
+ .byte 0xe, 0 /* DW_CFA_def_cfa_offset */
+ .byte 0x9, 8, 2 /* DW_CFA_register %eip, %edx */
+ ADV(UW43, UW42)
+ .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
+ ADV(UW44, UW43)
+ .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
+ .byte 0x80+8, 2 /* DW_CFA_offset %eip 2*-4 */
+ ADV(UW45, UW44)
+ .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
+ ADV(UW46, UW45)
+ .byte 0x80+3, 3 /* DW_CFA_offset %ebx 3*-4 */
+ ADV(UW47, UW46)
+ .byte 0xc0+3 /* DW_CFA_restore %ebx */
+ ADV(UW48, UW47)
+ .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
+ ADV(UW49, UW48)
+ .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
+ ADV(UW50, UW49)
+ .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
+ ADV(UW51, UW50)
+ .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE9):
+#endif /* !FFI_NO_RAW_API */
+
+#ifdef _WIN32
+ .def @feat.00;
+ .scl 3;
+ .type 0;
+ .endef
+ .globl @feat.00
+@feat.00 = 1
#endif
-#ifdef __APPLE__
- .subsections_via_symbols
- .section __LD,__compact_unwind,regular,debug
-
- /* compact unwind for ffi_call_i386 */
- .long C(ffi_call_i386)
- .set L1,L(UW5)-L(UW0)
- .long L1
- .long 0x04000000 /* use dwarf unwind info */
- .long 0
- .long 0
-
- /* compact unwind for ffi_go_closure_EAX */
- .long C(ffi_go_closure_EAX)
- .set L2,L(UW8)-L(UW6)
- .long L2
- .long 0x04000000 /* use dwarf unwind info */
- .long 0
- .long 0
-
- /* compact unwind for ffi_go_closure_ECX */
- .long C(ffi_go_closure_ECX)
- .set L3,L(UW11)-L(UW9)
- .long L3
- .long 0x04000000 /* use dwarf unwind info */
- .long 0
- .long 0
-
- /* compact unwind for ffi_closure_i386 */
- .long C(ffi_closure_i386)
- .set L4,L(UW20)-L(UW12)
- .long L4
- .long 0x04000000 /* use dwarf unwind info */
- .long 0
- .long 0
-
- /* compact unwind for ffi_go_closure_STDCALL */
- .long C(ffi_go_closure_STDCALL)
- .set L5,L(UW23)-L(UW21)
- .long L5
- .long 0x04000000 /* use dwarf unwind info */
- .long 0
- .long 0
-
- /* compact unwind for ffi_closure_REGISTER */
- .long C(ffi_closure_REGISTER)
- .set L6,L(UW26)-L(UW24)
- .long L6
- .long 0x04000000 /* use dwarf unwind info */
- .long 0
- .long 0
-
- /* compact unwind for ffi_closure_STDCALL */
- .long C(ffi_closure_STDCALL)
- .set L7,L(UW31)-L(UW27)
- .long L7
- .long 0x04000000 /* use dwarf unwind info */
- .long 0
- .long 0
-
- /* compact unwind for ffi_closure_raw_SYSV */
- .long C(ffi_closure_raw_SYSV)
- .set L8,L(UW40)-L(UW32)
- .long L8
- .long 0x04000000 /* use dwarf unwind info */
- .long 0
- .long 0
-
- /* compact unwind for ffi_closure_raw_THISCALL */
- .long C(ffi_closure_raw_THISCALL)
- .set L9,L(UW52)-L(UW41)
- .long L9
- .long 0x04000000 /* use dwarf unwind info */
- .long 0
- .long 0
-#endif /* __APPLE__ */
-
-#endif /* ifndef _MSC_VER */
-#endif /* ifdef __i386__ */
-
+#ifdef __APPLE__
+ .subsections_via_symbols
+ .section __LD,__compact_unwind,regular,debug
+
+ /* compact unwind for ffi_call_i386 */
+ .long C(ffi_call_i386)
+ .set L1,L(UW5)-L(UW0)
+ .long L1
+ .long 0x04000000 /* use dwarf unwind info */
+ .long 0
+ .long 0
+
+ /* compact unwind for ffi_go_closure_EAX */
+ .long C(ffi_go_closure_EAX)
+ .set L2,L(UW8)-L(UW6)
+ .long L2
+ .long 0x04000000 /* use dwarf unwind info */
+ .long 0
+ .long 0
+
+ /* compact unwind for ffi_go_closure_ECX */
+ .long C(ffi_go_closure_ECX)
+ .set L3,L(UW11)-L(UW9)
+ .long L3
+ .long 0x04000000 /* use dwarf unwind info */
+ .long 0
+ .long 0
+
+ /* compact unwind for ffi_closure_i386 */
+ .long C(ffi_closure_i386)
+ .set L4,L(UW20)-L(UW12)
+ .long L4
+ .long 0x04000000 /* use dwarf unwind info */
+ .long 0
+ .long 0
+
+ /* compact unwind for ffi_go_closure_STDCALL */
+ .long C(ffi_go_closure_STDCALL)
+ .set L5,L(UW23)-L(UW21)
+ .long L5
+ .long 0x04000000 /* use dwarf unwind info */
+ .long 0
+ .long 0
+
+ /* compact unwind for ffi_closure_REGISTER */
+ .long C(ffi_closure_REGISTER)
+ .set L6,L(UW26)-L(UW24)
+ .long L6
+ .long 0x04000000 /* use dwarf unwind info */
+ .long 0
+ .long 0
+
+ /* compact unwind for ffi_closure_STDCALL */
+ .long C(ffi_closure_STDCALL)
+ .set L7,L(UW31)-L(UW27)
+ .long L7
+ .long 0x04000000 /* use dwarf unwind info */
+ .long 0
+ .long 0
+
+ /* compact unwind for ffi_closure_raw_SYSV */
+ .long C(ffi_closure_raw_SYSV)
+ .set L8,L(UW40)-L(UW32)
+ .long L8
+ .long 0x04000000 /* use dwarf unwind info */
+ .long 0
+ .long 0
+
+ /* compact unwind for ffi_closure_raw_THISCALL */
+ .long C(ffi_closure_raw_THISCALL)
+ .set L9,L(UW52)-L(UW41)
+ .long L9
+ .long 0x04000000 /* use dwarf unwind info */
+ .long 0
+ .long 0
+#endif /* __APPLE__ */
+
+#endif /* ifndef _MSC_VER */
+#endif /* ifdef __i386__ */
+
#if defined __ELF__ && defined __linux__
.section .note.GNU-stack,"",@progbits
#endif
diff --git a/contrib/restricted/libffi/src/x86/sysv_intel.S b/contrib/restricted/libffi/src/x86/sysv_intel.S
index 5fc9ff21fa..3cafd71ce1 100644
--- a/contrib/restricted/libffi/src/x86/sysv_intel.S
+++ b/contrib/restricted/libffi/src/x86/sysv_intel.S
@@ -1,995 +1,995 @@
-/* -----------------------------------------------------------------------
- sysv.S - Copyright (c) 2017 Anthony Green
- - Copyright (c) 2013 The Written Word, Inc.
- - Copyright (c) 1996,1998,2001-2003,2005,2008,2010 Red Hat, Inc.
-
- X86 Foreign Function Interface
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- ``Software''), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be included
- in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
- ----------------------------------------------------------------------- */
-
-#ifndef __x86_64__
-#ifdef _MSC_VER
-
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
-#include <ffi_cfi.h>
-#include "internal.h"
-
-#define C2(X, Y) X ## Y
-#define C1(X, Y) C2(X, Y)
-#define L(X) C1(L, X)
-# define ENDF(X) X ENDP
-
-/* This macro allows the safe creation of jump tables without an
- actual table. The entry points into the table are all 8 bytes.
- The use of ORG asserts that we're at the correct location. */
-/* ??? The clang assembler doesn't handle .org with symbolic expressions. */
-#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__))
-# define E(BASE, X) ALIGN 8
-#else
-# define E(BASE, X) ALIGN 8; ORG BASE + X * 8
-#endif
-
- .686P
- .MODEL FLAT
-
-EXTRN @ffi_closure_inner@8:PROC
-_TEXT SEGMENT
-
-/* This is declared as
-
- void ffi_call_i386(struct call_frame *frame, char *argp)
- __attribute__((fastcall));
-
- Thus the arguments are present in
-
- ecx: frame
- edx: argp
-*/
-
-ALIGN 16
-PUBLIC @ffi_call_i386@8
-@ffi_call_i386@8 PROC
-L(UW0):
- cfi_startproc
- #if !HAVE_FASTCALL
- mov ecx, [esp+4]
- mov edx, [esp+8]
- #endif
- mov eax, [esp] /* move the return address */
- mov [ecx], ebp /* store ebp into local frame */
- mov [ecx+4], eax /* store retaddr into local frame */
-
- /* New stack frame based off ebp. This is a itty bit of unwind
- trickery in that the CFA *has* changed. There is no easy way
- to describe it correctly on entry to the function. Fortunately,
- it doesn't matter too much since at all points we can correctly
- unwind back to ffi_call. Note that the location to which we
- moved the return address is (the new) CFA-4, so from the
- perspective of the unwind info, it hasn't moved. */
- mov ebp, ecx
-L(UW1):
- // cfi_def_cfa(%ebp, 8)
- // cfi_rel_offset(%ebp, 0)
-
- mov esp, edx /* set outgoing argument stack */
- mov eax, [20+R_EAX*4+ebp] /* set register arguments */
- mov edx, [20+R_EDX*4+ebp]
- mov ecx, [20+R_ECX*4+ebp]
-
- call dword ptr [ebp+8]
-
- mov ecx, [12+ebp] /* load return type code */
- mov [ebp+8], ebx /* preserve %ebx */
-L(UW2):
- // cfi_rel_offset(%ebx, 8)
-
- and ecx, X86_RET_TYPE_MASK
- lea ebx, [L(store_table) + ecx * 8]
- mov ecx, [ebp+16] /* load result address */
- jmp ebx
-
- ALIGN 8
-L(store_table):
-E(L(store_table), X86_RET_FLOAT)
- fstp DWORD PTR [ecx]
- jmp L(e1)
-E(L(store_table), X86_RET_DOUBLE)
- fstp QWORD PTR [ecx]
- jmp L(e1)
-E(L(store_table), X86_RET_LDOUBLE)
- fstp QWORD PTR [ecx]
- jmp L(e1)
-E(L(store_table), X86_RET_SINT8)
- movsx eax, al
- mov [ecx], eax
- jmp L(e1)
-E(L(store_table), X86_RET_SINT16)
- movsx eax, ax
- mov [ecx], eax
- jmp L(e1)
-E(L(store_table), X86_RET_UINT8)
- movzx eax, al
- mov [ecx], eax
- jmp L(e1)
-E(L(store_table), X86_RET_UINT16)
- movzx eax, ax
- mov [ecx], eax
- jmp L(e1)
-E(L(store_table), X86_RET_INT64)
- mov [ecx+4], edx
- /* fallthru */
-E(L(store_table), X86_RET_int 32)
- mov [ecx], eax
- /* fallthru */
-E(L(store_table), X86_RET_VOID)
-L(e1):
- mov ebx, [ebp+8]
- mov esp, ebp
- pop ebp
-L(UW3):
- // cfi_remember_state
- // cfi_def_cfa(%esp, 4)
- // cfi_restore(%ebx)
- // cfi_restore(%ebp)
- ret
-L(UW4):
- // cfi_restore_state
-
-E(L(store_table), X86_RET_STRUCTPOP)
- jmp L(e1)
-E(L(store_table), X86_RET_STRUCTARG)
- jmp L(e1)
-E(L(store_table), X86_RET_STRUCT_1B)
- mov [ecx], al
- jmp L(e1)
-E(L(store_table), X86_RET_STRUCT_2B)
- mov [ecx], ax
- jmp L(e1)
-
- /* Fill out the table so that bad values are predictable. */
-E(L(store_table), X86_RET_UNUSED14)
- int 3
-E(L(store_table), X86_RET_UNUSED15)
- int 3
-
-L(UW5):
- // cfi_endproc
-ENDF(@ffi_call_i386@8)
-
-/* The inner helper is declared as
-
- void ffi_closure_inner(struct closure_frame *frame, char *argp)
- __attribute_((fastcall))
-
- Thus the arguments are placed in
-
- ecx: frame
- edx: argp
-*/
-
-/* Macros to help setting up the closure_data structure. */
-
-#if HAVE_FASTCALL
-# define closure_FS (40 + 4)
-# define closure_CF 0
-#else
-# define closure_FS (8 + 40 + 12)
-# define closure_CF 8
-#endif
-
-FFI_CLOSURE_SAVE_REGS MACRO
- mov [esp + closure_CF+16+R_EAX*4], eax
- mov [esp + closure_CF+16+R_EDX*4], edx
- mov [esp + closure_CF+16+R_ECX*4], ecx
-ENDM
-
-FFI_CLOSURE_COPY_TRAMP_DATA MACRO
- mov edx, [eax+FFI_TRAMPOLINE_SIZE] /* copy cif */
- mov ecx, [eax+FFI_TRAMPOLINE_SIZE+4] /* copy fun */
- mov eax, [eax+FFI_TRAMPOLINE_SIZE+8]; /* copy user_data */
- mov [esp+closure_CF+28], edx
- mov [esp+closure_CF+32], ecx
- mov [esp+closure_CF+36], eax
-ENDM
-
-#if HAVE_FASTCALL
-FFI_CLOSURE_PREP_CALL MACRO
- mov ecx, esp /* load closure_data */
- lea edx, [esp+closure_FS+4] /* load incoming stack */
-ENDM
-#else
-FFI_CLOSURE_PREP_CALL MACRO
- lea ecx, [esp+closure_CF] /* load closure_data */
- lea edx, [esp+closure_FS+4] /* load incoming stack */
- mov [esp], ecx
- mov [esp+4], edx
-ENDM
-#endif
-
-FFI_CLOSURE_CALL_INNER MACRO UWN
- call @ffi_closure_inner@8
-ENDM
-
-FFI_CLOSURE_MASK_AND_JUMP MACRO LABEL
- and eax, X86_RET_TYPE_MASK
- lea edx, [LABEL+eax*8]
- mov eax, [esp+closure_CF] /* optimiztic load */
- jmp edx
-ENDM
-
-ALIGN 16
-PUBLIC ffi_go_closure_EAX
-ffi_go_closure_EAX PROC C
-L(UW6):
- // cfi_startproc
- sub esp, closure_FS
-L(UW7):
- // cfi_def_cfa_offset(closure_FS + 4)
- FFI_CLOSURE_SAVE_REGS
- mov edx, [eax+4] /* copy cif */
- mov ecx, [eax +8] /* copy fun */
- mov [esp+closure_CF+28], edx
- mov [esp+closure_CF+32], ecx
- mov [esp+closure_CF+36], eax /* closure is user_data */
- jmp L(do_closure_i386)
-L(UW8):
- // cfi_endproc
-ENDF(ffi_go_closure_EAX)
-
-ALIGN 16
-PUBLIC ffi_go_closure_ECX
-ffi_go_closure_ECX PROC C
-L(UW9):
- // cfi_startproc
- sub esp, closure_FS
-L(UW10):
- // cfi_def_cfa_offset(closure_FS + 4)
- FFI_CLOSURE_SAVE_REGS
- mov edx, [ecx+4] /* copy cif */
- mov eax, [ecx+8] /* copy fun */
- mov [esp+closure_CF+28], edx
- mov [esp+closure_CF+32], eax
- mov [esp+closure_CF+36], ecx /* closure is user_data */
- jmp L(do_closure_i386)
-L(UW11):
- // cfi_endproc
-ENDF(ffi_go_closure_ECX)
-
-/* The closure entry points are reached from the ffi_closure trampoline.
- On entry, %eax contains the address of the ffi_closure. */
-
-ALIGN 16
-PUBLIC ffi_closure_i386
-ffi_closure_i386 PROC C
-L(UW12):
- // cfi_startproc
- sub esp, closure_FS
-L(UW13):
- // cfi_def_cfa_offset(closure_FS + 4)
-
- FFI_CLOSURE_SAVE_REGS
- FFI_CLOSURE_COPY_TRAMP_DATA
-
- /* Entry point from preceeding Go closures. */
-L(do_closure_i386)::
-
- FFI_CLOSURE_PREP_CALL
- FFI_CLOSURE_CALL_INNER(14)
- FFI_CLOSURE_MASK_AND_JUMP L(C1(load_table,2))
-
- ALIGN 8
-L(load_table2):
-E(L(load_table2), X86_RET_FLOAT)
- fld dword ptr [esp+closure_CF]
- jmp L(e2)
-E(L(load_table2), X86_RET_DOUBLE)
- fld qword ptr [esp+closure_CF]
- jmp L(e2)
-E(L(load_table2), X86_RET_LDOUBLE)
- fld qword ptr [esp+closure_CF]
- jmp L(e2)
-E(L(load_table2), X86_RET_SINT8)
- movsx eax, al
- jmp L(e2)
-E(L(load_table2), X86_RET_SINT16)
- movsx eax, ax
- jmp L(e2)
-E(L(load_table2), X86_RET_UINT8)
- movzx eax, al
- jmp L(e2)
-E(L(load_table2), X86_RET_UINT16)
- movzx eax, ax
- jmp L(e2)
-E(L(load_table2), X86_RET_INT64)
- mov edx, [esp+closure_CF+4]
- jmp L(e2)
-E(L(load_table2), X86_RET_INT32)
- nop
- /* fallthru */
-E(L(load_table2), X86_RET_VOID)
-L(e2):
- add esp, closure_FS
-L(UW16):
- // cfi_adjust_cfa_offset(-closure_FS)
- ret
-L(UW17):
- // cfi_adjust_cfa_offset(closure_FS)
-E(L(load_table2), X86_RET_STRUCTPOP)
- add esp, closure_FS
-L(UW18):
- // cfi_adjust_cfa_offset(-closure_FS)
- ret 4
-L(UW19):
- // cfi_adjust_cfa_offset(closure_FS)
-E(L(load_table2), X86_RET_STRUCTARG)
- jmp L(e2)
-E(L(load_table2), X86_RET_STRUCT_1B)
- movzx eax, al
- jmp L(e2)
-E(L(load_table2), X86_RET_STRUCT_2B)
- movzx eax, ax
- jmp L(e2)
-
- /* Fill out the table so that bad values are predictable. */
-E(L(load_table2), X86_RET_UNUSED14)
- int 3
-E(L(load_table2), X86_RET_UNUSED15)
- int 3
-
-L(UW20):
- // cfi_endproc
-ENDF(ffi_closure_i386)
-
-ALIGN 16
-PUBLIC ffi_go_closure_STDCALL
-ffi_go_closure_STDCALL PROC C
-L(UW21):
- // cfi_startproc
- sub esp, closure_FS
-L(UW22):
- // cfi_def_cfa_offset(closure_FS + 4)
- FFI_CLOSURE_SAVE_REGS
- mov edx, [ecx+4] /* copy cif */
- mov eax, [ecx+8] /* copy fun */
- mov [esp+closure_CF+28], edx
- mov [esp+closure_CF+32], eax
- mov [esp+closure_CF+36], ecx /* closure is user_data */
- jmp L(do_closure_STDCALL)
-L(UW23):
- // cfi_endproc
-ENDF(ffi_go_closure_STDCALL)
-
-/* For REGISTER, we have no available parameter registers, and so we
- enter here having pushed the closure onto the stack. */
-
-ALIGN 16
-PUBLIC ffi_closure_REGISTER
-ffi_closure_REGISTER PROC C
-L(UW24):
- // cfi_startproc
- // cfi_def_cfa(%esp, 8)
- // cfi_offset(%eip, -8)
- sub esp, closure_FS-4
-L(UW25):
- // cfi_def_cfa_offset(closure_FS + 4)
- FFI_CLOSURE_SAVE_REGS
- mov ecx, [esp+closure_FS-4] /* load retaddr */
- mov eax, [esp+closure_FS] /* load closure */
- mov [esp+closure_FS], ecx /* move retaddr */
- jmp L(do_closure_REGISTER)
-L(UW26):
- // cfi_endproc
-ENDF(ffi_closure_REGISTER)
-
-/* For STDCALL (and others), we need to pop N bytes of arguments off
- the stack following the closure. The amount needing to be popped
- is returned to us from ffi_closure_inner. */
-
-ALIGN 16
-PUBLIC ffi_closure_STDCALL
-ffi_closure_STDCALL PROC C
-L(UW27):
- // cfi_startproc
- sub esp, closure_FS
-L(UW28):
- // cfi_def_cfa_offset(closure_FS + 4)
-
- FFI_CLOSURE_SAVE_REGS
-
- /* Entry point from ffi_closure_REGISTER. */
-L(do_closure_REGISTER)::
-
- FFI_CLOSURE_COPY_TRAMP_DATA
-
- /* Entry point from preceeding Go closure. */
-L(do_closure_STDCALL)::
-
- FFI_CLOSURE_PREP_CALL
- FFI_CLOSURE_CALL_INNER(29)
-
- mov ecx, eax
- shr ecx, X86_RET_POP_SHIFT /* isolate pop count */
- lea ecx, [esp+closure_FS+ecx] /* compute popped esp */
- mov edx, [esp+closure_FS] /* move return address */
- mov [ecx], edx
-
- /* From this point on, the value of %esp upon return is %ecx+4,
- and we've copied the return address to %ecx to make return easy.
- There's no point in representing this in the unwind info, as
- there is always a window between the mov and the ret which
- will be wrong from one point of view or another. */
-
- FFI_CLOSURE_MASK_AND_JUMP L(C1(load_table,3))
-
- ALIGN 8
-L(load_table3):
-E(L(load_table3), X86_RET_FLOAT)
- fld DWORD PTR [esp+closure_CF]
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_DOUBLE)
- fld QWORD PTR [esp+closure_CF]
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_LDOUBLE)
- fld QWORD PTR [esp+closure_CF]
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_SINT8)
- movsx eax, al
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_SINT16)
- movsx eax, ax
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_UINT8)
- movzx eax, al
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_UINT16)
- movzx eax, ax
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_INT64)
- mov edx, [esp+closure_CF+4]
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_int 32)
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_VOID)
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_STRUCTPOP)
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_STRUCTARG)
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_STRUCT_1B)
- movzx eax, al
- mov esp, ecx
- ret
-E(L(load_table3), X86_RET_STRUCT_2B)
- movzx eax, ax
- mov esp, ecx
- ret
-
- /* Fill out the table so that bad values are predictable. */
-E(L(load_table3), X86_RET_UNUSED14)
- int 3
-E(L(load_table3), X86_RET_UNUSED15)
- int 3
-
-L(UW31):
- // cfi_endproc
-ENDF(ffi_closure_STDCALL)
-
-#if !FFI_NO_RAW_API
-
-#define raw_closure_S_FS (16+16+12)
-
-ALIGN 16
-PUBLIC ffi_closure_raw_SYSV
-ffi_closure_raw_SYSV PROC C
-L(UW32):
- // cfi_startproc
- sub esp, raw_closure_S_FS
-L(UW33):
- // cfi_def_cfa_offset(raw_closure_S_FS + 4)
- mov [esp+raw_closure_S_FS-4], ebx
-L(UW34):
- // cfi_rel_offset(%ebx, raw_closure_S_FS-4)
-
- mov edx, [eax+FFI_TRAMPOLINE_SIZE+8] /* load cl->user_data */
- mov [esp+12], edx
- lea edx, [esp+raw_closure_S_FS+4] /* load raw_args */
- mov [esp+8], edx
- lea edx, [esp+16] /* load &res */
- mov [esp+4], edx
- mov ebx, [eax+FFI_TRAMPOLINE_SIZE] /* load cl->cif */
- mov [esp], ebx
- call DWORD PTR [eax+FFI_TRAMPOLINE_SIZE+4] /* call cl->fun */
-
- mov eax, [ebx+20] /* load cif->flags */
- and eax, X86_RET_TYPE_MASK
-// #ifdef __PIC__
-// call __x86.get_pc_thunk.bx
-// L(pc4):
-// lea ecx, L(load_table4)-L(pc4)(%ebx, %eax, 8), %ecx
-// #else
- lea ecx, [L(load_table4)+eax+8]
-// #endif
- mov ebx, [esp+raw_closure_S_FS-4]
-L(UW35):
- // cfi_restore(%ebx)
- mov eax, [esp+16] /* Optimistic load */
- jmp dword ptr [ecx]
-
- ALIGN 8
-L(load_table4):
-E(L(load_table4), X86_RET_FLOAT)
- fld DWORD PTR [esp +16]
- jmp L(e4)
-E(L(load_table4), X86_RET_DOUBLE)
- fld QWORD PTR [esp +16]
- jmp L(e4)
-E(L(load_table4), X86_RET_LDOUBLE)
- fld QWORD PTR [esp +16]
- jmp L(e4)
-E(L(load_table4), X86_RET_SINT8)
- movsx eax, al
- jmp L(e4)
-E(L(load_table4), X86_RET_SINT16)
- movsx eax, ax
- jmp L(e4)
-E(L(load_table4), X86_RET_UINT8)
- movzx eax, al
- jmp L(e4)
-E(L(load_table4), X86_RET_UINT16)
- movzx eax, ax
- jmp L(e4)
-E(L(load_table4), X86_RET_INT64)
- mov edx, [esp+16+4]
- jmp L(e4)
-E(L(load_table4), X86_RET_int 32)
- nop
- /* fallthru */
-E(L(load_table4), X86_RET_VOID)
-L(e4):
- add esp, raw_closure_S_FS
-L(UW36):
- // cfi_adjust_cfa_offset(-raw_closure_S_FS)
- ret
-L(UW37):
- // cfi_adjust_cfa_offset(raw_closure_S_FS)
-E(L(load_table4), X86_RET_STRUCTPOP)
- add esp, raw_closure_S_FS
-L(UW38):
- // cfi_adjust_cfa_offset(-raw_closure_S_FS)
- ret 4
-L(UW39):
- // cfi_adjust_cfa_offset(raw_closure_S_FS)
-E(L(load_table4), X86_RET_STRUCTARG)
- jmp L(e4)
-E(L(load_table4), X86_RET_STRUCT_1B)
- movzx eax, al
- jmp L(e4)
-E(L(load_table4), X86_RET_STRUCT_2B)
- movzx eax, ax
- jmp L(e4)
-
- /* Fill out the table so that bad values are predictable. */
-E(L(load_table4), X86_RET_UNUSED14)
- int 3
-E(L(load_table4), X86_RET_UNUSED15)
- int 3
-
-L(UW40):
- // cfi_endproc
-ENDF(ffi_closure_raw_SYSV)
-
-#define raw_closure_T_FS (16+16+8)
-
-ALIGN 16
-PUBLIC ffi_closure_raw_THISCALL
-ffi_closure_raw_THISCALL PROC C
-L(UW41):
- // cfi_startproc
- /* Rearrange the stack such that %ecx is the first argument.
- This means moving the return address. */
- pop edx
-L(UW42):
- // cfi_def_cfa_offset(0)
- // cfi_register(%eip, %edx)
- push ecx
-L(UW43):
- // cfi_adjust_cfa_offset(4)
- push edx
-L(UW44):
- // cfi_adjust_cfa_offset(4)
- // cfi_rel_offset(%eip, 0)
- sub esp, raw_closure_T_FS
-L(UW45):
- // cfi_adjust_cfa_offset(raw_closure_T_FS)
- mov [esp+raw_closure_T_FS-4], ebx
-L(UW46):
- // cfi_rel_offset(%ebx, raw_closure_T_FS-4)
-
- mov edx, [eax+FFI_TRAMPOLINE_SIZE+8] /* load cl->user_data */
- mov [esp+12], edx
- lea edx, [esp+raw_closure_T_FS+4] /* load raw_args */
- mov [esp+8], edx
- lea edx, [esp+16] /* load &res */
- mov [esp+4], edx
- mov ebx, [eax+FFI_TRAMPOLINE_SIZE] /* load cl->cif */
- mov [esp], ebx
- call DWORD PTR [eax+FFI_TRAMPOLINE_SIZE+4] /* call cl->fun */
-
- mov eax, [ebx+20] /* load cif->flags */
- and eax, X86_RET_TYPE_MASK
-// #ifdef __PIC__
-// call __x86.get_pc_thunk.bx
-// L(pc5):
-// leal L(load_table5)-L(pc5)(%ebx, %eax, 8), %ecx
-// #else
- lea ecx, [L(load_table5)+eax*8]
-//#endif
- mov ebx, [esp+raw_closure_T_FS-4]
-L(UW47):
- // cfi_restore(%ebx)
- mov eax, [esp+16] /* Optimistic load */
- jmp DWORD PTR [ecx]
-
- AlIGN 4
-L(load_table5):
-E(L(load_table5), X86_RET_FLOAT)
- fld DWORD PTR [esp +16]
- jmp L(e5)
-E(L(load_table5), X86_RET_DOUBLE)
- fld QWORD PTR [esp +16]
- jmp L(e5)
-E(L(load_table5), X86_RET_LDOUBLE)
- fld QWORD PTR [esp+16]
- jmp L(e5)
-E(L(load_table5), X86_RET_SINT8)
- movsx eax, al
- jmp L(e5)
-E(L(load_table5), X86_RET_SINT16)
- movsx eax, ax
- jmp L(e5)
-E(L(load_table5), X86_RET_UINT8)
- movzx eax, al
- jmp L(e5)
-E(L(load_table5), X86_RET_UINT16)
- movzx eax, ax
- jmp L(e5)
-E(L(load_table5), X86_RET_INT64)
- mov edx, [esp+16+4]
- jmp L(e5)
-E(L(load_table5), X86_RET_int 32)
- nop
- /* fallthru */
-E(L(load_table5), X86_RET_VOID)
-L(e5):
- add esp, raw_closure_T_FS
-L(UW48):
- // cfi_adjust_cfa_offset(-raw_closure_T_FS)
- /* Remove the extra %ecx argument we pushed. */
- ret 4
-L(UW49):
- // cfi_adjust_cfa_offset(raw_closure_T_FS)
-E(L(load_table5), X86_RET_STRUCTPOP)
- add esp, raw_closure_T_FS
-L(UW50):
- // cfi_adjust_cfa_offset(-raw_closure_T_FS)
- ret 8
-L(UW51):
- // cfi_adjust_cfa_offset(raw_closure_T_FS)
-E(L(load_table5), X86_RET_STRUCTARG)
- jmp L(e5)
-E(L(load_table5), X86_RET_STRUCT_1B)
- movzx eax, al
- jmp L(e5)
-E(L(load_table5), X86_RET_STRUCT_2B)
- movzx eax, ax
- jmp L(e5)
-
- /* Fill out the table so that bad values are predictable. */
-E(L(load_table5), X86_RET_UNUSED14)
- int 3
-E(L(load_table5), X86_RET_UNUSED15)
- int 3
-
-L(UW52):
- // cfi_endproc
-ENDF(ffi_closure_raw_THISCALL)
-
-#endif /* !FFI_NO_RAW_API */
-
-#ifdef X86_DARWIN
-# define COMDAT(X) \
- .section __TEXT,__text,coalesced,pure_instructions; \
- .weak_definition X; \
- FFI_HIDDEN(X)
-#elif defined __ELF__ && !(defined(__sun__) && defined(__svr4__))
-# define COMDAT(X) \
- .section .text.X,"axG",@progbits,X,comdat; \
- PUBLIC X; \
- FFI_HIDDEN(X)
-#else
-# define COMDAT(X)
-#endif
-
-// #if defined(__PIC__)
-// COMDAT(C(__x86.get_pc_thunk.bx))
-// C(__x86.get_pc_thunk.bx):
-// movl (%esp), %ebx
-// ret
-// ENDF(C(__x86.get_pc_thunk.bx))
-// # if defined X86_DARWIN || defined HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-// COMDAT(C(__x86.get_pc_thunk.dx))
-// C(__x86.get_pc_thunk.dx):
-// movl (%esp), %edx
-// ret
-// ENDF(C(__x86.get_pc_thunk.dx))
-// #endif /* DARWIN || HIDDEN */
-// #endif /* __PIC__ */
-
-#if 0
-/* Sadly, OSX cctools-as doesn't understand .cfi directives at all. */
-
-#ifdef __APPLE__
-.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
-EHFrame0:
-#elif defined(X86_WIN32)
-.section .eh_frame,"r"
-#elif defined(HAVE_AS_X86_64_UNWIND_SECTION_TYPE)
-.section .eh_frame,EH_FRAME_FLAGS,@unwind
-#else
-.section .eh_frame,EH_FRAME_FLAGS,@progbits
-#endif
-
-#ifdef HAVE_AS_X86_PCREL
-# define PCREL(X) X - .
-#else
-# define PCREL(X) X@rel
-#endif
-
-/* Simplify advancing between labels. Assume DW_CFA_advance_loc1 fits. */
-#define ADV(N, P) .byte 2, L(N)-L(P)
-
- .balign 4
-L(CIE):
- .set L(set0),L(ECIE)-L(SCIE)
- .long L(set0) /* CIE Length */
-L(SCIE):
- .long 0 /* CIE Identifier Tag */
- .byte 1 /* CIE Version */
- .ascii "zR\0" /* CIE Augmentation */
- .byte 1 /* CIE Code Alignment Factor */
- .byte 0x7c /* CIE Data Alignment Factor */
- .byte 0x8 /* CIE RA Column */
- .byte 1 /* Augmentation size */
- .byte 0x1b /* FDE Encoding (pcrel sdata4) */
- .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp offset 4 */
- .byte 0x80+8, 1 /* DW_CFA_offset, %eip offset 1*-4 */
- .balign 4
-L(ECIE):
-
- .set L(set1),L(EFDE1)-L(SFDE1)
- .long L(set1) /* FDE Length */
-L(SFDE1):
- .long L(SFDE1)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW0)) /* Initial location */
- .long L(UW5)-L(UW0) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW1, UW0)
- .byte 0xc, 5, 8 /* DW_CFA_def_cfa, %ebp 8 */
- .byte 0x80+5, 2 /* DW_CFA_offset, %ebp 2*-4 */
- ADV(UW2, UW1)
- .byte 0x80+3, 0 /* DW_CFA_offset, %ebx 0*-4 */
- ADV(UW3, UW2)
- .byte 0xa /* DW_CFA_remember_state */
- .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp 4 */
- .byte 0xc0+3 /* DW_CFA_restore, %ebx */
- .byte 0xc0+5 /* DW_CFA_restore, %ebp */
- ADV(UW4, UW3)
- .byte 0xb /* DW_CFA_restore_state */
- .balign 4
-L(EFDE1):
-
- .set L(set2),L(EFDE2)-L(SFDE2)
- .long L(set2) /* FDE Length */
-L(SFDE2):
- .long L(SFDE2)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW6)) /* Initial location */
- .long L(UW8)-L(UW6) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW7, UW6)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE2):
-
- .set L(set3),L(EFDE3)-L(SFDE3)
- .long L(set3) /* FDE Length */
-L(SFDE3):
- .long L(SFDE3)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW9)) /* Initial location */
- .long L(UW11)-L(UW9) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW10, UW9)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE3):
-
- .set L(set4),L(EFDE4)-L(SFDE4)
- .long L(set4) /* FDE Length */
-L(SFDE4):
- .long L(SFDE4)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW12)) /* Initial location */
- .long L(UW20)-L(UW12) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW13, UW12)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
-#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX
- ADV(UW14, UW13)
- .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */
- ADV(UW15, UW14)
- .byte 0xc0+3 /* DW_CFA_restore %ebx */
- ADV(UW16, UW15)
-#else
- ADV(UW16, UW13)
-#endif
- .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
- ADV(UW17, UW16)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- ADV(UW18, UW17)
- .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
- ADV(UW19, UW18)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE4):
-
- .set L(set5),L(EFDE5)-L(SFDE5)
- .long L(set5) /* FDE Length */
-L(SFDE5):
- .long L(SFDE5)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW21)) /* Initial location */
- .long L(UW23)-L(UW21) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW22, UW21)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE5):
-
- .set L(set6),L(EFDE6)-L(SFDE6)
- .long L(set6) /* FDE Length */
-L(SFDE6):
- .long L(SFDE6)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW24)) /* Initial location */
- .long L(UW26)-L(UW24) /* Address range */
- .byte 0 /* Augmentation size */
- .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
- .byte 0x80+8, 2 /* DW_CFA_offset %eip, 2*-4 */
- ADV(UW25, UW24)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE6):
-
- .set L(set7),L(EFDE7)-L(SFDE7)
- .long L(set7) /* FDE Length */
-L(SFDE7):
- .long L(SFDE7)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW27)) /* Initial location */
- .long L(UW31)-L(UW27) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW28, UW27)
- .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
-#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX
- ADV(UW29, UW28)
- .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */
- ADV(UW30, UW29)
- .byte 0xc0+3 /* DW_CFA_restore %ebx */
-#endif
- .balign 4
-L(EFDE7):
-
-#if !FFI_NO_RAW_API
- .set L(set8),L(EFDE8)-L(SFDE8)
- .long L(set8) /* FDE Length */
-L(SFDE8):
- .long L(SFDE8)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW32)) /* Initial location */
- .long L(UW40)-L(UW32) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW33, UW32)
- .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
- ADV(UW34, UW33)
- .byte 0x80+3, 2 /* DW_CFA_offset %ebx 2*-4 */
- ADV(UW35, UW34)
- .byte 0xc0+3 /* DW_CFA_restore %ebx */
- ADV(UW36, UW35)
- .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
- ADV(UW37, UW36)
- .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
- ADV(UW38, UW37)
- .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
- ADV(UW39, UW38)
- .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE8):
-
- .set L(set9),L(EFDE9)-L(SFDE9)
- .long L(set9) /* FDE Length */
-L(SFDE9):
- .long L(SFDE9)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW41)) /* Initial location */
- .long L(UW52)-L(UW41) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW42, UW41)
- .byte 0xe, 0 /* DW_CFA_def_cfa_offset */
- .byte 0x9, 8, 2 /* DW_CFA_register %eip, %edx */
- ADV(UW43, UW42)
- .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
- ADV(UW44, UW43)
- .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
- .byte 0x80+8, 2 /* DW_CFA_offset %eip 2*-4 */
- ADV(UW45, UW44)
- .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
- ADV(UW46, UW45)
- .byte 0x80+3, 3 /* DW_CFA_offset %ebx 3*-4 */
- ADV(UW47, UW46)
- .byte 0xc0+3 /* DW_CFA_restore %ebx */
- ADV(UW48, UW47)
- .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
- ADV(UW49, UW48)
- .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
- ADV(UW50, UW49)
- .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
- ADV(UW51, UW50)
- .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
- .balign 4
-L(EFDE9):
-#endif /* !FFI_NO_RAW_API */
-
-#ifdef _WIN32
- .def @feat.00;
- .scl 3;
- .type 0;
- .endef
- PUBLIC @feat.00
-@feat.00 = 1
-#endif
-
-#endif /* ifndef _MSC_VER */
-#endif /* ifndef __x86_64__ */
-
-#if defined __ELF__ && defined __linux__
- .section .note.GNU-stack,"",@progbits
-#endif
-#endif
-
-END \ No newline at end of file
+/* -----------------------------------------------------------------------
+ sysv.S - Copyright (c) 2017 Anthony Green
+ - Copyright (c) 2013 The Written Word, Inc.
+ - Copyright (c) 1996,1998,2001-2003,2005,2008,2010 Red Hat, Inc.
+
+ X86 Foreign Function Interface
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#ifndef __x86_64__
+#ifdef _MSC_VER
+
+#define LIBFFI_ASM
+#include <fficonfig.h>
+#include <ffi.h>
+#include <ffi_cfi.h>
+#include "internal.h"
+
+#define C2(X, Y) X ## Y
+#define C1(X, Y) C2(X, Y)
+#define L(X) C1(L, X)
+# define ENDF(X) X ENDP
+
+/* This macro allows the safe creation of jump tables without an
+ actual table. The entry points into the table are all 8 bytes.
+ The use of ORG asserts that we're at the correct location. */
+/* ??? The clang assembler doesn't handle .org with symbolic expressions. */
+#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__))
+# define E(BASE, X) ALIGN 8
+#else
+# define E(BASE, X) ALIGN 8; ORG BASE + X * 8
+#endif
+
+ .686P
+ .MODEL FLAT
+
+EXTRN @ffi_closure_inner@8:PROC
+_TEXT SEGMENT
+
+/* This is declared as
+
+ void ffi_call_i386(struct call_frame *frame, char *argp)
+ __attribute__((fastcall));
+
+ Thus the arguments are present in
+
+ ecx: frame
+ edx: argp
+*/
+
+ALIGN 16
+PUBLIC @ffi_call_i386@8
+@ffi_call_i386@8 PROC
+L(UW0):
+ cfi_startproc
+ #if !HAVE_FASTCALL
+ mov ecx, [esp+4]
+ mov edx, [esp+8]
+ #endif
+ mov eax, [esp] /* move the return address */
+ mov [ecx], ebp /* store ebp into local frame */
+ mov [ecx+4], eax /* store retaddr into local frame */
+
+ /* New stack frame based off ebp. This is a itty bit of unwind
+ trickery in that the CFA *has* changed. There is no easy way
+ to describe it correctly on entry to the function. Fortunately,
+ it doesn't matter too much since at all points we can correctly
+ unwind back to ffi_call. Note that the location to which we
+ moved the return address is (the new) CFA-4, so from the
+ perspective of the unwind info, it hasn't moved. */
+ mov ebp, ecx
+L(UW1):
+ // cfi_def_cfa(%ebp, 8)
+ // cfi_rel_offset(%ebp, 0)
+
+ mov esp, edx /* set outgoing argument stack */
+ mov eax, [20+R_EAX*4+ebp] /* set register arguments */
+ mov edx, [20+R_EDX*4+ebp]
+ mov ecx, [20+R_ECX*4+ebp]
+
+ call dword ptr [ebp+8]
+
+ mov ecx, [12+ebp] /* load return type code */
+ mov [ebp+8], ebx /* preserve %ebx */
+L(UW2):
+ // cfi_rel_offset(%ebx, 8)
+
+ and ecx, X86_RET_TYPE_MASK
+ lea ebx, [L(store_table) + ecx * 8]
+ mov ecx, [ebp+16] /* load result address */
+ jmp ebx
+
+ ALIGN 8
+L(store_table):
+E(L(store_table), X86_RET_FLOAT)
+ fstp DWORD PTR [ecx]
+ jmp L(e1)
+E(L(store_table), X86_RET_DOUBLE)
+ fstp QWORD PTR [ecx]
+ jmp L(e1)
+E(L(store_table), X86_RET_LDOUBLE)
+ fstp QWORD PTR [ecx]
+ jmp L(e1)
+E(L(store_table), X86_RET_SINT8)
+ movsx eax, al
+ mov [ecx], eax
+ jmp L(e1)
+E(L(store_table), X86_RET_SINT16)
+ movsx eax, ax
+ mov [ecx], eax
+ jmp L(e1)
+E(L(store_table), X86_RET_UINT8)
+ movzx eax, al
+ mov [ecx], eax
+ jmp L(e1)
+E(L(store_table), X86_RET_UINT16)
+ movzx eax, ax
+ mov [ecx], eax
+ jmp L(e1)
+E(L(store_table), X86_RET_INT64)
+ mov [ecx+4], edx
+ /* fallthru */
+E(L(store_table), X86_RET_int 32)
+ mov [ecx], eax
+ /* fallthru */
+E(L(store_table), X86_RET_VOID)
+L(e1):
+ mov ebx, [ebp+8]
+ mov esp, ebp
+ pop ebp
+L(UW3):
+ // cfi_remember_state
+ // cfi_def_cfa(%esp, 4)
+ // cfi_restore(%ebx)
+ // cfi_restore(%ebp)
+ ret
+L(UW4):
+ // cfi_restore_state
+
+E(L(store_table), X86_RET_STRUCTPOP)
+ jmp L(e1)
+E(L(store_table), X86_RET_STRUCTARG)
+ jmp L(e1)
+E(L(store_table), X86_RET_STRUCT_1B)
+ mov [ecx], al
+ jmp L(e1)
+E(L(store_table), X86_RET_STRUCT_2B)
+ mov [ecx], ax
+ jmp L(e1)
+
+ /* Fill out the table so that bad values are predictable. */
+E(L(store_table), X86_RET_UNUSED14)
+ int 3
+E(L(store_table), X86_RET_UNUSED15)
+ int 3
+
+L(UW5):
+ // cfi_endproc
+ENDF(@ffi_call_i386@8)
+
+/* The inner helper is declared as
+
+ void ffi_closure_inner(struct closure_frame *frame, char *argp)
+ __attribute_((fastcall))
+
+ Thus the arguments are placed in
+
+ ecx: frame
+ edx: argp
+*/
+
+/* Macros to help setting up the closure_data structure. */
+
+#if HAVE_FASTCALL
+# define closure_FS (40 + 4)
+# define closure_CF 0
+#else
+# define closure_FS (8 + 40 + 12)
+# define closure_CF 8
+#endif
+
+FFI_CLOSURE_SAVE_REGS MACRO
+ mov [esp + closure_CF+16+R_EAX*4], eax
+ mov [esp + closure_CF+16+R_EDX*4], edx
+ mov [esp + closure_CF+16+R_ECX*4], ecx
+ENDM
+
+FFI_CLOSURE_COPY_TRAMP_DATA MACRO
+ mov edx, [eax+FFI_TRAMPOLINE_SIZE] /* copy cif */
+ mov ecx, [eax+FFI_TRAMPOLINE_SIZE+4] /* copy fun */
+ mov eax, [eax+FFI_TRAMPOLINE_SIZE+8]; /* copy user_data */
+ mov [esp+closure_CF+28], edx
+ mov [esp+closure_CF+32], ecx
+ mov [esp+closure_CF+36], eax
+ENDM
+
+#if HAVE_FASTCALL
+FFI_CLOSURE_PREP_CALL MACRO
+ mov ecx, esp /* load closure_data */
+ lea edx, [esp+closure_FS+4] /* load incoming stack */
+ENDM
+#else
+FFI_CLOSURE_PREP_CALL MACRO
+ lea ecx, [esp+closure_CF] /* load closure_data */
+ lea edx, [esp+closure_FS+4] /* load incoming stack */
+ mov [esp], ecx
+ mov [esp+4], edx
+ENDM
+#endif
+
+FFI_CLOSURE_CALL_INNER MACRO UWN
+ call @ffi_closure_inner@8
+ENDM
+
+FFI_CLOSURE_MASK_AND_JUMP MACRO LABEL
+ and eax, X86_RET_TYPE_MASK
+ lea edx, [LABEL+eax*8]
+ mov eax, [esp+closure_CF] /* optimiztic load */
+ jmp edx
+ENDM
+
+ALIGN 16
+PUBLIC ffi_go_closure_EAX
+ffi_go_closure_EAX PROC C
+L(UW6):
+ // cfi_startproc
+ sub esp, closure_FS
+L(UW7):
+ // cfi_def_cfa_offset(closure_FS + 4)
+ FFI_CLOSURE_SAVE_REGS
+ mov edx, [eax+4] /* copy cif */
+ mov ecx, [eax +8] /* copy fun */
+ mov [esp+closure_CF+28], edx
+ mov [esp+closure_CF+32], ecx
+ mov [esp+closure_CF+36], eax /* closure is user_data */
+ jmp L(do_closure_i386)
+L(UW8):
+ // cfi_endproc
+ENDF(ffi_go_closure_EAX)
+
+ALIGN 16
+PUBLIC ffi_go_closure_ECX
+ffi_go_closure_ECX PROC C
+L(UW9):
+ // cfi_startproc
+ sub esp, closure_FS
+L(UW10):
+ // cfi_def_cfa_offset(closure_FS + 4)
+ FFI_CLOSURE_SAVE_REGS
+ mov edx, [ecx+4] /* copy cif */
+ mov eax, [ecx+8] /* copy fun */
+ mov [esp+closure_CF+28], edx
+ mov [esp+closure_CF+32], eax
+ mov [esp+closure_CF+36], ecx /* closure is user_data */
+ jmp L(do_closure_i386)
+L(UW11):
+ // cfi_endproc
+ENDF(ffi_go_closure_ECX)
+
+/* The closure entry points are reached from the ffi_closure trampoline.
+ On entry, %eax contains the address of the ffi_closure. */
+
+ALIGN 16
+PUBLIC ffi_closure_i386
+ffi_closure_i386 PROC C
+L(UW12):
+ // cfi_startproc
+ sub esp, closure_FS
+L(UW13):
+ // cfi_def_cfa_offset(closure_FS + 4)
+
+ FFI_CLOSURE_SAVE_REGS
+ FFI_CLOSURE_COPY_TRAMP_DATA
+
+ /* Entry point from preceeding Go closures. */
+L(do_closure_i386)::
+
+ FFI_CLOSURE_PREP_CALL
+ FFI_CLOSURE_CALL_INNER(14)
+ FFI_CLOSURE_MASK_AND_JUMP L(C1(load_table,2))
+
+ ALIGN 8
+L(load_table2):
+E(L(load_table2), X86_RET_FLOAT)
+ fld dword ptr [esp+closure_CF]
+ jmp L(e2)
+E(L(load_table2), X86_RET_DOUBLE)
+ fld qword ptr [esp+closure_CF]
+ jmp L(e2)
+E(L(load_table2), X86_RET_LDOUBLE)
+ fld qword ptr [esp+closure_CF]
+ jmp L(e2)
+E(L(load_table2), X86_RET_SINT8)
+ movsx eax, al
+ jmp L(e2)
+E(L(load_table2), X86_RET_SINT16)
+ movsx eax, ax
+ jmp L(e2)
+E(L(load_table2), X86_RET_UINT8)
+ movzx eax, al
+ jmp L(e2)
+E(L(load_table2), X86_RET_UINT16)
+ movzx eax, ax
+ jmp L(e2)
+E(L(load_table2), X86_RET_INT64)
+ mov edx, [esp+closure_CF+4]
+ jmp L(e2)
+E(L(load_table2), X86_RET_INT32)
+ nop
+ /* fallthru */
+E(L(load_table2), X86_RET_VOID)
+L(e2):
+ add esp, closure_FS
+L(UW16):
+ // cfi_adjust_cfa_offset(-closure_FS)
+ ret
+L(UW17):
+ // cfi_adjust_cfa_offset(closure_FS)
+E(L(load_table2), X86_RET_STRUCTPOP)
+ add esp, closure_FS
+L(UW18):
+ // cfi_adjust_cfa_offset(-closure_FS)
+ ret 4
+L(UW19):
+ // cfi_adjust_cfa_offset(closure_FS)
+E(L(load_table2), X86_RET_STRUCTARG)
+ jmp L(e2)
+E(L(load_table2), X86_RET_STRUCT_1B)
+ movzx eax, al
+ jmp L(e2)
+E(L(load_table2), X86_RET_STRUCT_2B)
+ movzx eax, ax
+ jmp L(e2)
+
+ /* Fill out the table so that bad values are predictable. */
+E(L(load_table2), X86_RET_UNUSED14)
+ int 3
+E(L(load_table2), X86_RET_UNUSED15)
+ int 3
+
+L(UW20):
+ // cfi_endproc
+ENDF(ffi_closure_i386)
+
+ALIGN 16
+PUBLIC ffi_go_closure_STDCALL
+ffi_go_closure_STDCALL PROC C
+L(UW21):
+ // cfi_startproc
+ sub esp, closure_FS
+L(UW22):
+ // cfi_def_cfa_offset(closure_FS + 4)
+ FFI_CLOSURE_SAVE_REGS
+ mov edx, [ecx+4] /* copy cif */
+ mov eax, [ecx+8] /* copy fun */
+ mov [esp+closure_CF+28], edx
+ mov [esp+closure_CF+32], eax
+ mov [esp+closure_CF+36], ecx /* closure is user_data */
+ jmp L(do_closure_STDCALL)
+L(UW23):
+ // cfi_endproc
+ENDF(ffi_go_closure_STDCALL)
+
+/* For REGISTER, we have no available parameter registers, and so we
+ enter here having pushed the closure onto the stack. */
+
+ALIGN 16
+PUBLIC ffi_closure_REGISTER
+ffi_closure_REGISTER PROC C
+L(UW24):
+ // cfi_startproc
+ // cfi_def_cfa(%esp, 8)
+ // cfi_offset(%eip, -8)
+ sub esp, closure_FS-4
+L(UW25):
+ // cfi_def_cfa_offset(closure_FS + 4)
+ FFI_CLOSURE_SAVE_REGS
+ mov ecx, [esp+closure_FS-4] /* load retaddr */
+ mov eax, [esp+closure_FS] /* load closure */
+ mov [esp+closure_FS], ecx /* move retaddr */
+ jmp L(do_closure_REGISTER)
+L(UW26):
+ // cfi_endproc
+ENDF(ffi_closure_REGISTER)
+
+/* For STDCALL (and others), we need to pop N bytes of arguments off
+ the stack following the closure. The amount needing to be popped
+ is returned to us from ffi_closure_inner. */
+
+ALIGN 16
+PUBLIC ffi_closure_STDCALL
+ffi_closure_STDCALL PROC C
+L(UW27):
+ // cfi_startproc
+ sub esp, closure_FS
+L(UW28):
+ // cfi_def_cfa_offset(closure_FS + 4)
+
+ FFI_CLOSURE_SAVE_REGS
+
+ /* Entry point from ffi_closure_REGISTER. */
+L(do_closure_REGISTER)::
+
+ FFI_CLOSURE_COPY_TRAMP_DATA
+
+ /* Entry point from preceeding Go closure. */
+L(do_closure_STDCALL)::
+
+ FFI_CLOSURE_PREP_CALL
+ FFI_CLOSURE_CALL_INNER(29)
+
+ mov ecx, eax
+ shr ecx, X86_RET_POP_SHIFT /* isolate pop count */
+ lea ecx, [esp+closure_FS+ecx] /* compute popped esp */
+ mov edx, [esp+closure_FS] /* move return address */
+ mov [ecx], edx
+
+ /* From this point on, the value of %esp upon return is %ecx+4,
+ and we've copied the return address to %ecx to make return easy.
+ There's no point in representing this in the unwind info, as
+ there is always a window between the mov and the ret which
+ will be wrong from one point of view or another. */
+
+ FFI_CLOSURE_MASK_AND_JUMP L(C1(load_table,3))
+
+ ALIGN 8
+L(load_table3):
+E(L(load_table3), X86_RET_FLOAT)
+ fld DWORD PTR [esp+closure_CF]
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_DOUBLE)
+ fld QWORD PTR [esp+closure_CF]
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_LDOUBLE)
+ fld QWORD PTR [esp+closure_CF]
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_SINT8)
+ movsx eax, al
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_SINT16)
+ movsx eax, ax
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_UINT8)
+ movzx eax, al
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_UINT16)
+ movzx eax, ax
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_INT64)
+ mov edx, [esp+closure_CF+4]
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_int 32)
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_VOID)
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_STRUCTPOP)
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_STRUCTARG)
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_STRUCT_1B)
+ movzx eax, al
+ mov esp, ecx
+ ret
+E(L(load_table3), X86_RET_STRUCT_2B)
+ movzx eax, ax
+ mov esp, ecx
+ ret
+
+ /* Fill out the table so that bad values are predictable. */
+E(L(load_table3), X86_RET_UNUSED14)
+ int 3
+E(L(load_table3), X86_RET_UNUSED15)
+ int 3
+
+L(UW31):
+ // cfi_endproc
+ENDF(ffi_closure_STDCALL)
+
+#if !FFI_NO_RAW_API
+
+#define raw_closure_S_FS (16+16+12)
+
+ALIGN 16
+PUBLIC ffi_closure_raw_SYSV
+ffi_closure_raw_SYSV PROC C
+L(UW32):
+ // cfi_startproc
+ sub esp, raw_closure_S_FS
+L(UW33):
+ // cfi_def_cfa_offset(raw_closure_S_FS + 4)
+ mov [esp+raw_closure_S_FS-4], ebx
+L(UW34):
+ // cfi_rel_offset(%ebx, raw_closure_S_FS-4)
+
+ mov edx, [eax+FFI_TRAMPOLINE_SIZE+8] /* load cl->user_data */
+ mov [esp+12], edx
+ lea edx, [esp+raw_closure_S_FS+4] /* load raw_args */
+ mov [esp+8], edx
+ lea edx, [esp+16] /* load &res */
+ mov [esp+4], edx
+ mov ebx, [eax+FFI_TRAMPOLINE_SIZE] /* load cl->cif */
+ mov [esp], ebx
+ call DWORD PTR [eax+FFI_TRAMPOLINE_SIZE+4] /* call cl->fun */
+
+ mov eax, [ebx+20] /* load cif->flags */
+ and eax, X86_RET_TYPE_MASK
+// #ifdef __PIC__
+// call __x86.get_pc_thunk.bx
+// L(pc4):
+// lea ecx, L(load_table4)-L(pc4)(%ebx, %eax, 8), %ecx
+// #else
+ lea ecx, [L(load_table4)+eax+8]
+// #endif
+ mov ebx, [esp+raw_closure_S_FS-4]
+L(UW35):
+ // cfi_restore(%ebx)
+ mov eax, [esp+16] /* Optimistic load */
+ jmp dword ptr [ecx]
+
+ ALIGN 8
+L(load_table4):
+E(L(load_table4), X86_RET_FLOAT)
+ fld DWORD PTR [esp +16]
+ jmp L(e4)
+E(L(load_table4), X86_RET_DOUBLE)
+ fld QWORD PTR [esp +16]
+ jmp L(e4)
+E(L(load_table4), X86_RET_LDOUBLE)
+ fld QWORD PTR [esp +16]
+ jmp L(e4)
+E(L(load_table4), X86_RET_SINT8)
+ movsx eax, al
+ jmp L(e4)
+E(L(load_table4), X86_RET_SINT16)
+ movsx eax, ax
+ jmp L(e4)
+E(L(load_table4), X86_RET_UINT8)
+ movzx eax, al
+ jmp L(e4)
+E(L(load_table4), X86_RET_UINT16)
+ movzx eax, ax
+ jmp L(e4)
+E(L(load_table4), X86_RET_INT64)
+ mov edx, [esp+16+4]
+ jmp L(e4)
+E(L(load_table4), X86_RET_int 32)
+ nop
+ /* fallthru */
+E(L(load_table4), X86_RET_VOID)
+L(e4):
+ add esp, raw_closure_S_FS
+L(UW36):
+ // cfi_adjust_cfa_offset(-raw_closure_S_FS)
+ ret
+L(UW37):
+ // cfi_adjust_cfa_offset(raw_closure_S_FS)
+E(L(load_table4), X86_RET_STRUCTPOP)
+ add esp, raw_closure_S_FS
+L(UW38):
+ // cfi_adjust_cfa_offset(-raw_closure_S_FS)
+ ret 4
+L(UW39):
+ // cfi_adjust_cfa_offset(raw_closure_S_FS)
+E(L(load_table4), X86_RET_STRUCTARG)
+ jmp L(e4)
+E(L(load_table4), X86_RET_STRUCT_1B)
+ movzx eax, al
+ jmp L(e4)
+E(L(load_table4), X86_RET_STRUCT_2B)
+ movzx eax, ax
+ jmp L(e4)
+
+ /* Fill out the table so that bad values are predictable. */
+E(L(load_table4), X86_RET_UNUSED14)
+ int 3
+E(L(load_table4), X86_RET_UNUSED15)
+ int 3
+
+L(UW40):
+ // cfi_endproc
+ENDF(ffi_closure_raw_SYSV)
+
+#define raw_closure_T_FS (16+16+8)
+
+ALIGN 16
+PUBLIC ffi_closure_raw_THISCALL
+ffi_closure_raw_THISCALL PROC C
+L(UW41):
+ // cfi_startproc
+ /* Rearrange the stack such that %ecx is the first argument.
+ This means moving the return address. */
+ pop edx
+L(UW42):
+ // cfi_def_cfa_offset(0)
+ // cfi_register(%eip, %edx)
+ push ecx
+L(UW43):
+ // cfi_adjust_cfa_offset(4)
+ push edx
+L(UW44):
+ // cfi_adjust_cfa_offset(4)
+ // cfi_rel_offset(%eip, 0)
+ sub esp, raw_closure_T_FS
+L(UW45):
+ // cfi_adjust_cfa_offset(raw_closure_T_FS)
+ mov [esp+raw_closure_T_FS-4], ebx
+L(UW46):
+ // cfi_rel_offset(%ebx, raw_closure_T_FS-4)
+
+ mov edx, [eax+FFI_TRAMPOLINE_SIZE+8] /* load cl->user_data */
+ mov [esp+12], edx
+ lea edx, [esp+raw_closure_T_FS+4] /* load raw_args */
+ mov [esp+8], edx
+ lea edx, [esp+16] /* load &res */
+ mov [esp+4], edx
+ mov ebx, [eax+FFI_TRAMPOLINE_SIZE] /* load cl->cif */
+ mov [esp], ebx
+ call DWORD PTR [eax+FFI_TRAMPOLINE_SIZE+4] /* call cl->fun */
+
+ mov eax, [ebx+20] /* load cif->flags */
+ and eax, X86_RET_TYPE_MASK
+// #ifdef __PIC__
+// call __x86.get_pc_thunk.bx
+// L(pc5):
+// leal L(load_table5)-L(pc5)(%ebx, %eax, 8), %ecx
+// #else
+ lea ecx, [L(load_table5)+eax*8]
+//#endif
+ mov ebx, [esp+raw_closure_T_FS-4]
+L(UW47):
+ // cfi_restore(%ebx)
+ mov eax, [esp+16] /* Optimistic load */
+ jmp DWORD PTR [ecx]
+
+ AlIGN 4
+L(load_table5):
+E(L(load_table5), X86_RET_FLOAT)
+ fld DWORD PTR [esp +16]
+ jmp L(e5)
+E(L(load_table5), X86_RET_DOUBLE)
+ fld QWORD PTR [esp +16]
+ jmp L(e5)
+E(L(load_table5), X86_RET_LDOUBLE)
+ fld QWORD PTR [esp+16]
+ jmp L(e5)
+E(L(load_table5), X86_RET_SINT8)
+ movsx eax, al
+ jmp L(e5)
+E(L(load_table5), X86_RET_SINT16)
+ movsx eax, ax
+ jmp L(e5)
+E(L(load_table5), X86_RET_UINT8)
+ movzx eax, al
+ jmp L(e5)
+E(L(load_table5), X86_RET_UINT16)
+ movzx eax, ax
+ jmp L(e5)
+E(L(load_table5), X86_RET_INT64)
+ mov edx, [esp+16+4]
+ jmp L(e5)
+E(L(load_table5), X86_RET_int 32)
+ nop
+ /* fallthru */
+E(L(load_table5), X86_RET_VOID)
+L(e5):
+ add esp, raw_closure_T_FS
+L(UW48):
+ // cfi_adjust_cfa_offset(-raw_closure_T_FS)
+ /* Remove the extra %ecx argument we pushed. */
+ ret 4
+L(UW49):
+ // cfi_adjust_cfa_offset(raw_closure_T_FS)
+E(L(load_table5), X86_RET_STRUCTPOP)
+ add esp, raw_closure_T_FS
+L(UW50):
+ // cfi_adjust_cfa_offset(-raw_closure_T_FS)
+ ret 8
+L(UW51):
+ // cfi_adjust_cfa_offset(raw_closure_T_FS)
+E(L(load_table5), X86_RET_STRUCTARG)
+ jmp L(e5)
+E(L(load_table5), X86_RET_STRUCT_1B)
+ movzx eax, al
+ jmp L(e5)
+E(L(load_table5), X86_RET_STRUCT_2B)
+ movzx eax, ax
+ jmp L(e5)
+
+ /* Fill out the table so that bad values are predictable. */
+E(L(load_table5), X86_RET_UNUSED14)
+ int 3
+E(L(load_table5), X86_RET_UNUSED15)
+ int 3
+
+L(UW52):
+ // cfi_endproc
+ENDF(ffi_closure_raw_THISCALL)
+
+#endif /* !FFI_NO_RAW_API */
+
+#ifdef X86_DARWIN
+# define COMDAT(X) \
+ .section __TEXT,__text,coalesced,pure_instructions; \
+ .weak_definition X; \
+ FFI_HIDDEN(X)
+#elif defined __ELF__ && !(defined(__sun__) && defined(__svr4__))
+# define COMDAT(X) \
+ .section .text.X,"axG",@progbits,X,comdat; \
+ PUBLIC X; \
+ FFI_HIDDEN(X)
+#else
+# define COMDAT(X)
+#endif
+
+// #if defined(__PIC__)
+// COMDAT(C(__x86.get_pc_thunk.bx))
+// C(__x86.get_pc_thunk.bx):
+// movl (%esp), %ebx
+// ret
+// ENDF(C(__x86.get_pc_thunk.bx))
+// # if defined X86_DARWIN || defined HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
+// COMDAT(C(__x86.get_pc_thunk.dx))
+// C(__x86.get_pc_thunk.dx):
+// movl (%esp), %edx
+// ret
+// ENDF(C(__x86.get_pc_thunk.dx))
+// #endif /* DARWIN || HIDDEN */
+// #endif /* __PIC__ */
+
+#if 0
+/* Sadly, OSX cctools-as doesn't understand .cfi directives at all. */
+
+#ifdef __APPLE__
+.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
+EHFrame0:
+#elif defined(X86_WIN32)
+.section .eh_frame,"r"
+#elif defined(HAVE_AS_X86_64_UNWIND_SECTION_TYPE)
+.section .eh_frame,EH_FRAME_FLAGS,@unwind
+#else
+.section .eh_frame,EH_FRAME_FLAGS,@progbits
+#endif
+
+#ifdef HAVE_AS_X86_PCREL
+# define PCREL(X) X - .
+#else
+# define PCREL(X) X@rel
+#endif
+
+/* Simplify advancing between labels. Assume DW_CFA_advance_loc1 fits. */
+#define ADV(N, P) .byte 2, L(N)-L(P)
+
+ .balign 4
+L(CIE):
+ .set L(set0),L(ECIE)-L(SCIE)
+ .long L(set0) /* CIE Length */
+L(SCIE):
+ .long 0 /* CIE Identifier Tag */
+ .byte 1 /* CIE Version */
+ .ascii "zR\0" /* CIE Augmentation */
+ .byte 1 /* CIE Code Alignment Factor */
+ .byte 0x7c /* CIE Data Alignment Factor */
+ .byte 0x8 /* CIE RA Column */
+ .byte 1 /* Augmentation size */
+ .byte 0x1b /* FDE Encoding (pcrel sdata4) */
+ .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp offset 4 */
+ .byte 0x80+8, 1 /* DW_CFA_offset, %eip offset 1*-4 */
+ .balign 4
+L(ECIE):
+
+ .set L(set1),L(EFDE1)-L(SFDE1)
+ .long L(set1) /* FDE Length */
+L(SFDE1):
+ .long L(SFDE1)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW0)) /* Initial location */
+ .long L(UW5)-L(UW0) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW1, UW0)
+ .byte 0xc, 5, 8 /* DW_CFA_def_cfa, %ebp 8 */
+ .byte 0x80+5, 2 /* DW_CFA_offset, %ebp 2*-4 */
+ ADV(UW2, UW1)
+ .byte 0x80+3, 0 /* DW_CFA_offset, %ebx 0*-4 */
+ ADV(UW3, UW2)
+ .byte 0xa /* DW_CFA_remember_state */
+ .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp 4 */
+ .byte 0xc0+3 /* DW_CFA_restore, %ebx */
+ .byte 0xc0+5 /* DW_CFA_restore, %ebp */
+ ADV(UW4, UW3)
+ .byte 0xb /* DW_CFA_restore_state */
+ .balign 4
+L(EFDE1):
+
+ .set L(set2),L(EFDE2)-L(SFDE2)
+ .long L(set2) /* FDE Length */
+L(SFDE2):
+ .long L(SFDE2)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW6)) /* Initial location */
+ .long L(UW8)-L(UW6) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW7, UW6)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE2):
+
+ .set L(set3),L(EFDE3)-L(SFDE3)
+ .long L(set3) /* FDE Length */
+L(SFDE3):
+ .long L(SFDE3)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW9)) /* Initial location */
+ .long L(UW11)-L(UW9) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW10, UW9)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE3):
+
+ .set L(set4),L(EFDE4)-L(SFDE4)
+ .long L(set4) /* FDE Length */
+L(SFDE4):
+ .long L(SFDE4)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW12)) /* Initial location */
+ .long L(UW20)-L(UW12) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW13, UW12)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX
+ ADV(UW14, UW13)
+ .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */
+ ADV(UW15, UW14)
+ .byte 0xc0+3 /* DW_CFA_restore %ebx */
+ ADV(UW16, UW15)
+#else
+ ADV(UW16, UW13)
+#endif
+ .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
+ ADV(UW17, UW16)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ ADV(UW18, UW17)
+ .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
+ ADV(UW19, UW18)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE4):
+
+ .set L(set5),L(EFDE5)-L(SFDE5)
+ .long L(set5) /* FDE Length */
+L(SFDE5):
+ .long L(SFDE5)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW21)) /* Initial location */
+ .long L(UW23)-L(UW21) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW22, UW21)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE5):
+
+ .set L(set6),L(EFDE6)-L(SFDE6)
+ .long L(set6) /* FDE Length */
+L(SFDE6):
+ .long L(SFDE6)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW24)) /* Initial location */
+ .long L(UW26)-L(UW24) /* Address range */
+ .byte 0 /* Augmentation size */
+ .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
+ .byte 0x80+8, 2 /* DW_CFA_offset %eip, 2*-4 */
+ ADV(UW25, UW24)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE6):
+
+ .set L(set7),L(EFDE7)-L(SFDE7)
+ .long L(set7) /* FDE Length */
+L(SFDE7):
+ .long L(SFDE7)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW27)) /* Initial location */
+ .long L(UW31)-L(UW27) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW28, UW27)
+ .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */
+#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX
+ ADV(UW29, UW28)
+ .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */
+ ADV(UW30, UW29)
+ .byte 0xc0+3 /* DW_CFA_restore %ebx */
+#endif
+ .balign 4
+L(EFDE7):
+
+#if !FFI_NO_RAW_API
+ .set L(set8),L(EFDE8)-L(SFDE8)
+ .long L(set8) /* FDE Length */
+L(SFDE8):
+ .long L(SFDE8)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW32)) /* Initial location */
+ .long L(UW40)-L(UW32) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW33, UW32)
+ .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
+ ADV(UW34, UW33)
+ .byte 0x80+3, 2 /* DW_CFA_offset %ebx 2*-4 */
+ ADV(UW35, UW34)
+ .byte 0xc0+3 /* DW_CFA_restore %ebx */
+ ADV(UW36, UW35)
+ .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
+ ADV(UW37, UW36)
+ .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
+ ADV(UW38, UW37)
+ .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
+ ADV(UW39, UW38)
+ .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE8):
+
+ .set L(set9),L(EFDE9)-L(SFDE9)
+ .long L(set9) /* FDE Length */
+L(SFDE9):
+ .long L(SFDE9)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW41)) /* Initial location */
+ .long L(UW52)-L(UW41) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW42, UW41)
+ .byte 0xe, 0 /* DW_CFA_def_cfa_offset */
+ .byte 0x9, 8, 2 /* DW_CFA_register %eip, %edx */
+ ADV(UW43, UW42)
+ .byte 0xe, 4 /* DW_CFA_def_cfa_offset */
+ ADV(UW44, UW43)
+ .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
+ .byte 0x80+8, 2 /* DW_CFA_offset %eip 2*-4 */
+ ADV(UW45, UW44)
+ .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
+ ADV(UW46, UW45)
+ .byte 0x80+3, 3 /* DW_CFA_offset %ebx 3*-4 */
+ ADV(UW47, UW46)
+ .byte 0xc0+3 /* DW_CFA_restore %ebx */
+ ADV(UW48, UW47)
+ .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
+ ADV(UW49, UW48)
+ .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
+ ADV(UW50, UW49)
+ .byte 0xe, 8 /* DW_CFA_def_cfa_offset */
+ ADV(UW51, UW50)
+ .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */
+ .balign 4
+L(EFDE9):
+#endif /* !FFI_NO_RAW_API */
+
+#ifdef _WIN32
+ .def @feat.00;
+ .scl 3;
+ .type 0;
+ .endef
+ PUBLIC @feat.00
+@feat.00 = 1
+#endif
+
+#endif /* ifndef _MSC_VER */
+#endif /* ifndef __x86_64__ */
+
+#if defined __ELF__ && defined __linux__
+ .section .note.GNU-stack,"",@progbits
+#endif
+#endif
+
+END \ No newline at end of file
diff --git a/contrib/restricted/libffi/src/x86/unix64.S b/contrib/restricted/libffi/src/x86/unix64.S
index ae81f77d09..41563f5c60 100644
--- a/contrib/restricted/libffi/src/x86/unix64.S
+++ b/contrib/restricted/libffi/src/x86/unix64.S
@@ -30,21 +30,21 @@
#define LIBFFI_ASM
#include <fficonfig.h>
#include <ffi.h>
-#include "internal64.h"
-#include "asmnames.h"
-
- .text
-
-/* This macro allows the safe creation of jump tables without an
- actual table. The entry points into the table are all 8 bytes.
- The use of ORG asserts that we're at the correct location. */
-/* ??? The clang assembler doesn't handle .org with symbolic expressions. */
-#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__))
-# define E(BASE, X) .balign 8
-#else
-# define E(BASE, X) .balign 8; .org BASE + X * 8
-#endif
-
+#include "internal64.h"
+#include "asmnames.h"
+
+ .text
+
+/* This macro allows the safe creation of jump tables without an
+ actual table. The entry points into the table are all 8 bytes.
+ The use of ORG asserts that we're at the correct location. */
+/* ??? The clang assembler doesn't handle .org with symbolic expressions. */
+#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__))
+# define E(BASE, X) .balign 8
+#else
+# define E(BASE, X) .balign 8; .org BASE + X * 8
+#endif
+
/* ffi_call_unix64 (void *args, unsigned long bytes, unsigned flags,
void *raddr, void (*fnaddr)(void));
@@ -52,12 +52,12 @@
for this function. This has been allocated by ffi_call. We also
deallocate some of the stack that has been alloca'd. */
- .balign 8
- .globl C(ffi_call_unix64)
- FFI_HIDDEN(C(ffi_call_unix64))
+ .balign 8
+ .globl C(ffi_call_unix64)
+ FFI_HIDDEN(C(ffi_call_unix64))
-C(ffi_call_unix64):
-L(UW0):
+C(ffi_call_unix64):
+L(UW0):
movq (%rsp), %r10 /* Load return address. */
leaq (%rdi, %rsi), %rax /* Find local stack base. */
movq %rdx, (%rax) /* Save flags. */
@@ -65,37 +65,37 @@ L(UW0):
movq %rbp, 16(%rax) /* Save old frame pointer. */
movq %r10, 24(%rax) /* Relocate return address. */
movq %rax, %rbp /* Finalize local stack frame. */
-
- /* New stack frame based off rbp. This is a itty bit of unwind
- trickery in that the CFA *has* changed. There is no easy way
- to describe it correctly on entry to the function. Fortunately,
- it doesn't matter too much since at all points we can correctly
- unwind back to ffi_call. Note that the location to which we
- moved the return address is (the new) CFA-8, so from the
- perspective of the unwind info, it hasn't moved. */
-L(UW1):
- /* cfi_def_cfa(%rbp, 32) */
- /* cfi_rel_offset(%rbp, 16) */
-
+
+ /* New stack frame based off rbp. This is a itty bit of unwind
+ trickery in that the CFA *has* changed. There is no easy way
+ to describe it correctly on entry to the function. Fortunately,
+ it doesn't matter too much since at all points we can correctly
+ unwind back to ffi_call. Note that the location to which we
+ moved the return address is (the new) CFA-8, so from the
+ perspective of the unwind info, it hasn't moved. */
+L(UW1):
+ /* cfi_def_cfa(%rbp, 32) */
+ /* cfi_rel_offset(%rbp, 16) */
+
movq %rdi, %r10 /* Save a copy of the register area. */
movq %r8, %r11 /* Save a copy of the target fn. */
movl %r9d, %eax /* Set number of SSE registers. */
/* Load up all argument registers. */
movq (%r10), %rdi
- movq 0x08(%r10), %rsi
- movq 0x10(%r10), %rdx
- movq 0x18(%r10), %rcx
- movq 0x20(%r10), %r8
- movq 0x28(%r10), %r9
- movl 0xb0(%r10), %eax
+ movq 0x08(%r10), %rsi
+ movq 0x10(%r10), %rdx
+ movq 0x18(%r10), %rcx
+ movq 0x20(%r10), %r8
+ movq 0x28(%r10), %r9
+ movl 0xb0(%r10), %eax
testl %eax, %eax
- jnz L(load_sse)
-L(ret_from_load_sse):
+ jnz L(load_sse)
+L(ret_from_load_sse):
- /* Deallocate the reg arg area, except for r10, then load via pop. */
- leaq 0xb8(%r10), %rsp
- popq %r10
+ /* Deallocate the reg arg area, except for r10, then load via pop. */
+ leaq 0xb8(%r10), %rsp
+ popq %r10
/* Call the user function. */
call *%r11
@@ -106,460 +106,460 @@ L(ret_from_load_sse):
movq 0(%rbp), %rcx /* Reload flags. */
movq 8(%rbp), %rdi /* Reload raddr. */
movq 16(%rbp), %rbp /* Reload old frame pointer. */
-L(UW2):
- /* cfi_remember_state */
- /* cfi_def_cfa(%rsp, 8) */
- /* cfi_restore(%rbp) */
+L(UW2):
+ /* cfi_remember_state */
+ /* cfi_def_cfa(%rsp, 8) */
+ /* cfi_restore(%rbp) */
/* The first byte of the flags contains the FFI_TYPE. */
- cmpb $UNIX64_RET_LAST, %cl
+ cmpb $UNIX64_RET_LAST, %cl
movzbl %cl, %r10d
- leaq L(store_table)(%rip), %r11
- ja L(sa)
- leaq (%r11, %r10, 8), %r10
-
- /* Prep for the structure cases: scratch area in redzone. */
- leaq -20(%rsp), %rsi
+ leaq L(store_table)(%rip), %r11
+ ja L(sa)
+ leaq (%r11, %r10, 8), %r10
+
+ /* Prep for the structure cases: scratch area in redzone. */
+ leaq -20(%rsp), %rsi
jmp *%r10
- .balign 8
-L(store_table):
-E(L(store_table), UNIX64_RET_VOID)
+ .balign 8
+L(store_table):
+E(L(store_table), UNIX64_RET_VOID)
ret
-E(L(store_table), UNIX64_RET_UINT8)
- movzbl %al, %eax
+E(L(store_table), UNIX64_RET_UINT8)
+ movzbl %al, %eax
movq %rax, (%rdi)
ret
-E(L(store_table), UNIX64_RET_UINT16)
- movzwl %ax, %eax
- movq %rax, (%rdi)
- ret
-E(L(store_table), UNIX64_RET_UINT32)
- movl %eax, %eax
- movq %rax, (%rdi)
- ret
-E(L(store_table), UNIX64_RET_SINT8)
+E(L(store_table), UNIX64_RET_UINT16)
+ movzwl %ax, %eax
+ movq %rax, (%rdi)
+ ret
+E(L(store_table), UNIX64_RET_UINT32)
+ movl %eax, %eax
+ movq %rax, (%rdi)
+ ret
+E(L(store_table), UNIX64_RET_SINT8)
movsbq %al, %rax
movq %rax, (%rdi)
ret
-E(L(store_table), UNIX64_RET_SINT16)
+E(L(store_table), UNIX64_RET_SINT16)
movswq %ax, %rax
movq %rax, (%rdi)
ret
-E(L(store_table), UNIX64_RET_SINT32)
+E(L(store_table), UNIX64_RET_SINT32)
cltq
movq %rax, (%rdi)
ret
-E(L(store_table), UNIX64_RET_INT64)
+E(L(store_table), UNIX64_RET_INT64)
movq %rax, (%rdi)
ret
-E(L(store_table), UNIX64_RET_XMM32)
- movd %xmm0, (%rdi)
+E(L(store_table), UNIX64_RET_XMM32)
+ movd %xmm0, (%rdi)
+ ret
+E(L(store_table), UNIX64_RET_XMM64)
+ movq %xmm0, (%rdi)
ret
-E(L(store_table), UNIX64_RET_XMM64)
- movq %xmm0, (%rdi)
+E(L(store_table), UNIX64_RET_X87)
+ fstpt (%rdi)
ret
-E(L(store_table), UNIX64_RET_X87)
+E(L(store_table), UNIX64_RET_X87_2)
fstpt (%rdi)
+ fstpt 16(%rdi)
ret
-E(L(store_table), UNIX64_RET_X87_2)
- fstpt (%rdi)
- fstpt 16(%rdi)
- ret
-E(L(store_table), UNIX64_RET_ST_XMM0_RAX)
- movq %rax, 8(%rsi)
- jmp L(s3)
-E(L(store_table), UNIX64_RET_ST_RAX_XMM0)
- movq %xmm0, 8(%rsi)
- jmp L(s2)
-E(L(store_table), UNIX64_RET_ST_XMM0_XMM1)
- movq %xmm1, 8(%rsi)
- jmp L(s3)
-E(L(store_table), UNIX64_RET_ST_RAX_RDX)
- movq %rdx, 8(%rsi)
-L(s2):
+E(L(store_table), UNIX64_RET_ST_XMM0_RAX)
+ movq %rax, 8(%rsi)
+ jmp L(s3)
+E(L(store_table), UNIX64_RET_ST_RAX_XMM0)
+ movq %xmm0, 8(%rsi)
+ jmp L(s2)
+E(L(store_table), UNIX64_RET_ST_XMM0_XMM1)
+ movq %xmm1, 8(%rsi)
+ jmp L(s3)
+E(L(store_table), UNIX64_RET_ST_RAX_RDX)
+ movq %rdx, 8(%rsi)
+L(s2):
movq %rax, (%rsi)
- shrl $UNIX64_SIZE_SHIFT, %ecx
+ shrl $UNIX64_SIZE_SHIFT, %ecx
+ rep movsb
+ ret
+ .balign 8
+L(s3):
+ movq %xmm0, (%rsi)
+ shrl $UNIX64_SIZE_SHIFT, %ecx
rep movsb
ret
- .balign 8
-L(s3):
- movq %xmm0, (%rsi)
- shrl $UNIX64_SIZE_SHIFT, %ecx
- rep movsb
- ret
-
-L(sa): call PLT(C(abort))
-
+
+L(sa): call PLT(C(abort))
+
/* Many times we can avoid loading any SSE registers at all.
It's not worth an indirect jump to load the exact set of
SSE registers needed; zero or all is a good compromise. */
- .balign 2
-L(UW3):
- /* cfi_restore_state */
-L(load_sse):
- movdqa 0x30(%r10), %xmm0
- movdqa 0x40(%r10), %xmm1
- movdqa 0x50(%r10), %xmm2
- movdqa 0x60(%r10), %xmm3
- movdqa 0x70(%r10), %xmm4
- movdqa 0x80(%r10), %xmm5
- movdqa 0x90(%r10), %xmm6
- movdqa 0xa0(%r10), %xmm7
- jmp L(ret_from_load_sse)
-
-L(UW4):
-ENDF(C(ffi_call_unix64))
-
-/* 6 general registers, 8 vector registers,
- 32 bytes of rvalue, 8 bytes of alignment. */
-#define ffi_closure_OFS_G 0
-#define ffi_closure_OFS_V (6*8)
-#define ffi_closure_OFS_RVALUE (ffi_closure_OFS_V + 8*16)
-#define ffi_closure_FS (ffi_closure_OFS_RVALUE + 32 + 8)
-
-/* The location of rvalue within the red zone after deallocating the frame. */
-#define ffi_closure_RED_RVALUE (ffi_closure_OFS_RVALUE - ffi_closure_FS)
-
- .balign 2
- .globl C(ffi_closure_unix64_sse)
- FFI_HIDDEN(C(ffi_closure_unix64_sse))
-
-C(ffi_closure_unix64_sse):
-L(UW5):
- subq $ffi_closure_FS, %rsp
-L(UW6):
- /* cfi_adjust_cfa_offset(ffi_closure_FS) */
-
- movdqa %xmm0, ffi_closure_OFS_V+0x00(%rsp)
- movdqa %xmm1, ffi_closure_OFS_V+0x10(%rsp)
- movdqa %xmm2, ffi_closure_OFS_V+0x20(%rsp)
- movdqa %xmm3, ffi_closure_OFS_V+0x30(%rsp)
- movdqa %xmm4, ffi_closure_OFS_V+0x40(%rsp)
- movdqa %xmm5, ffi_closure_OFS_V+0x50(%rsp)
- movdqa %xmm6, ffi_closure_OFS_V+0x60(%rsp)
- movdqa %xmm7, ffi_closure_OFS_V+0x70(%rsp)
- jmp L(sse_entry1)
-
-L(UW7):
-ENDF(C(ffi_closure_unix64_sse))
-
- .balign 2
- .globl C(ffi_closure_unix64)
- FFI_HIDDEN(C(ffi_closure_unix64))
-
-C(ffi_closure_unix64):
-L(UW8):
- subq $ffi_closure_FS, %rsp
-L(UW9):
- /* cfi_adjust_cfa_offset(ffi_closure_FS) */
-L(sse_entry1):
- movq %rdi, ffi_closure_OFS_G+0x00(%rsp)
- movq %rsi, ffi_closure_OFS_G+0x08(%rsp)
- movq %rdx, ffi_closure_OFS_G+0x10(%rsp)
- movq %rcx, ffi_closure_OFS_G+0x18(%rsp)
- movq %r8, ffi_closure_OFS_G+0x20(%rsp)
- movq %r9, ffi_closure_OFS_G+0x28(%rsp)
-
-#ifdef __ILP32__
- movl FFI_TRAMPOLINE_SIZE(%r10), %edi /* Load cif */
- movl FFI_TRAMPOLINE_SIZE+4(%r10), %esi /* Load fun */
- movl FFI_TRAMPOLINE_SIZE+8(%r10), %edx /* Load user_data */
-#else
- movq FFI_TRAMPOLINE_SIZE(%r10), %rdi /* Load cif */
- movq FFI_TRAMPOLINE_SIZE+8(%r10), %rsi /* Load fun */
- movq FFI_TRAMPOLINE_SIZE+16(%r10), %rdx /* Load user_data */
-#endif
-L(do_closure):
- leaq ffi_closure_OFS_RVALUE(%rsp), %rcx /* Load rvalue */
- movq %rsp, %r8 /* Load reg_args */
- leaq ffi_closure_FS+8(%rsp), %r9 /* Load argp */
- call PLT(C(ffi_closure_unix64_inner))
-
+ .balign 2
+L(UW3):
+ /* cfi_restore_state */
+L(load_sse):
+ movdqa 0x30(%r10), %xmm0
+ movdqa 0x40(%r10), %xmm1
+ movdqa 0x50(%r10), %xmm2
+ movdqa 0x60(%r10), %xmm3
+ movdqa 0x70(%r10), %xmm4
+ movdqa 0x80(%r10), %xmm5
+ movdqa 0x90(%r10), %xmm6
+ movdqa 0xa0(%r10), %xmm7
+ jmp L(ret_from_load_sse)
+
+L(UW4):
+ENDF(C(ffi_call_unix64))
+
+/* 6 general registers, 8 vector registers,
+ 32 bytes of rvalue, 8 bytes of alignment. */
+#define ffi_closure_OFS_G 0
+#define ffi_closure_OFS_V (6*8)
+#define ffi_closure_OFS_RVALUE (ffi_closure_OFS_V + 8*16)
+#define ffi_closure_FS (ffi_closure_OFS_RVALUE + 32 + 8)
+
+/* The location of rvalue within the red zone after deallocating the frame. */
+#define ffi_closure_RED_RVALUE (ffi_closure_OFS_RVALUE - ffi_closure_FS)
+
+ .balign 2
+ .globl C(ffi_closure_unix64_sse)
+ FFI_HIDDEN(C(ffi_closure_unix64_sse))
+
+C(ffi_closure_unix64_sse):
+L(UW5):
+ subq $ffi_closure_FS, %rsp
+L(UW6):
+ /* cfi_adjust_cfa_offset(ffi_closure_FS) */
+
+ movdqa %xmm0, ffi_closure_OFS_V+0x00(%rsp)
+ movdqa %xmm1, ffi_closure_OFS_V+0x10(%rsp)
+ movdqa %xmm2, ffi_closure_OFS_V+0x20(%rsp)
+ movdqa %xmm3, ffi_closure_OFS_V+0x30(%rsp)
+ movdqa %xmm4, ffi_closure_OFS_V+0x40(%rsp)
+ movdqa %xmm5, ffi_closure_OFS_V+0x50(%rsp)
+ movdqa %xmm6, ffi_closure_OFS_V+0x60(%rsp)
+ movdqa %xmm7, ffi_closure_OFS_V+0x70(%rsp)
+ jmp L(sse_entry1)
+
+L(UW7):
+ENDF(C(ffi_closure_unix64_sse))
+
+ .balign 2
+ .globl C(ffi_closure_unix64)
+ FFI_HIDDEN(C(ffi_closure_unix64))
+
+C(ffi_closure_unix64):
+L(UW8):
+ subq $ffi_closure_FS, %rsp
+L(UW9):
+ /* cfi_adjust_cfa_offset(ffi_closure_FS) */
+L(sse_entry1):
+ movq %rdi, ffi_closure_OFS_G+0x00(%rsp)
+ movq %rsi, ffi_closure_OFS_G+0x08(%rsp)
+ movq %rdx, ffi_closure_OFS_G+0x10(%rsp)
+ movq %rcx, ffi_closure_OFS_G+0x18(%rsp)
+ movq %r8, ffi_closure_OFS_G+0x20(%rsp)
+ movq %r9, ffi_closure_OFS_G+0x28(%rsp)
+
+#ifdef __ILP32__
+ movl FFI_TRAMPOLINE_SIZE(%r10), %edi /* Load cif */
+ movl FFI_TRAMPOLINE_SIZE+4(%r10), %esi /* Load fun */
+ movl FFI_TRAMPOLINE_SIZE+8(%r10), %edx /* Load user_data */
+#else
+ movq FFI_TRAMPOLINE_SIZE(%r10), %rdi /* Load cif */
+ movq FFI_TRAMPOLINE_SIZE+8(%r10), %rsi /* Load fun */
+ movq FFI_TRAMPOLINE_SIZE+16(%r10), %rdx /* Load user_data */
+#endif
+L(do_closure):
+ leaq ffi_closure_OFS_RVALUE(%rsp), %rcx /* Load rvalue */
+ movq %rsp, %r8 /* Load reg_args */
+ leaq ffi_closure_FS+8(%rsp), %r9 /* Load argp */
+ call PLT(C(ffi_closure_unix64_inner))
+
/* Deallocate stack frame early; return value is now in redzone. */
- addq $ffi_closure_FS, %rsp
-L(UW10):
- /* cfi_adjust_cfa_offset(-ffi_closure_FS) */
+ addq $ffi_closure_FS, %rsp
+L(UW10):
+ /* cfi_adjust_cfa_offset(-ffi_closure_FS) */
/* The first byte of the return value contains the FFI_TYPE. */
- cmpb $UNIX64_RET_LAST, %al
+ cmpb $UNIX64_RET_LAST, %al
movzbl %al, %r10d
- leaq L(load_table)(%rip), %r11
- ja L(la)
- leaq (%r11, %r10, 8), %r10
- leaq ffi_closure_RED_RVALUE(%rsp), %rsi
+ leaq L(load_table)(%rip), %r11
+ ja L(la)
+ leaq (%r11, %r10, 8), %r10
+ leaq ffi_closure_RED_RVALUE(%rsp), %rsi
jmp *%r10
- .balign 8
-L(load_table):
-E(L(load_table), UNIX64_RET_VOID)
+ .balign 8
+L(load_table):
+E(L(load_table), UNIX64_RET_VOID)
ret
-E(L(load_table), UNIX64_RET_UINT8)
- movzbl (%rsi), %eax
+E(L(load_table), UNIX64_RET_UINT8)
+ movzbl (%rsi), %eax
ret
-E(L(load_table), UNIX64_RET_UINT16)
- movzwl (%rsi), %eax
+E(L(load_table), UNIX64_RET_UINT16)
+ movzwl (%rsi), %eax
ret
-E(L(load_table), UNIX64_RET_UINT32)
- movl (%rsi), %eax
+E(L(load_table), UNIX64_RET_UINT32)
+ movl (%rsi), %eax
ret
-E(L(load_table), UNIX64_RET_SINT8)
- movsbl (%rsi), %eax
+E(L(load_table), UNIX64_RET_SINT8)
+ movsbl (%rsi), %eax
ret
-E(L(load_table), UNIX64_RET_SINT16)
- movswl (%rsi), %eax
+E(L(load_table), UNIX64_RET_SINT16)
+ movswl (%rsi), %eax
ret
-E(L(load_table), UNIX64_RET_SINT32)
- movl (%rsi), %eax
+E(L(load_table), UNIX64_RET_SINT32)
+ movl (%rsi), %eax
ret
-E(L(load_table), UNIX64_RET_INT64)
- movq (%rsi), %rax
+E(L(load_table), UNIX64_RET_INT64)
+ movq (%rsi), %rax
ret
-E(L(load_table), UNIX64_RET_XMM32)
- movd (%rsi), %xmm0
+E(L(load_table), UNIX64_RET_XMM32)
+ movd (%rsi), %xmm0
ret
-E(L(load_table), UNIX64_RET_XMM64)
- movq (%rsi), %xmm0
- ret
-E(L(load_table), UNIX64_RET_X87)
- fldt (%rsi)
- ret
-E(L(load_table), UNIX64_RET_X87_2)
- fldt 16(%rsi)
- fldt (%rsi)
- ret
-E(L(load_table), UNIX64_RET_ST_XMM0_RAX)
- movq 8(%rsi), %rax
- jmp L(l3)
-E(L(load_table), UNIX64_RET_ST_RAX_XMM0)
- movq 8(%rsi), %xmm0
- jmp L(l2)
-E(L(load_table), UNIX64_RET_ST_XMM0_XMM1)
- movq 8(%rsi), %xmm1
- jmp L(l3)
-E(L(load_table), UNIX64_RET_ST_RAX_RDX)
- movq 8(%rsi), %rdx
-L(l2):
- movq (%rsi), %rax
- ret
- .balign 8
-L(l3):
- movq (%rsi), %xmm0
- ret
-
-L(la): call PLT(C(abort))
-
-L(UW11):
-ENDF(C(ffi_closure_unix64))
-
- .balign 2
- .globl C(ffi_go_closure_unix64_sse)
- FFI_HIDDEN(C(ffi_go_closure_unix64_sse))
-
-C(ffi_go_closure_unix64_sse):
-L(UW12):
- subq $ffi_closure_FS, %rsp
-L(UW13):
- /* cfi_adjust_cfa_offset(ffi_closure_FS) */
-
- movdqa %xmm0, ffi_closure_OFS_V+0x00(%rsp)
- movdqa %xmm1, ffi_closure_OFS_V+0x10(%rsp)
- movdqa %xmm2, ffi_closure_OFS_V+0x20(%rsp)
- movdqa %xmm3, ffi_closure_OFS_V+0x30(%rsp)
- movdqa %xmm4, ffi_closure_OFS_V+0x40(%rsp)
- movdqa %xmm5, ffi_closure_OFS_V+0x50(%rsp)
- movdqa %xmm6, ffi_closure_OFS_V+0x60(%rsp)
- movdqa %xmm7, ffi_closure_OFS_V+0x70(%rsp)
- jmp L(sse_entry2)
-
-L(UW14):
-ENDF(C(ffi_go_closure_unix64_sse))
-
- .balign 2
- .globl C(ffi_go_closure_unix64)
- FFI_HIDDEN(C(ffi_go_closure_unix64))
-
-C(ffi_go_closure_unix64):
-L(UW15):
- subq $ffi_closure_FS, %rsp
-L(UW16):
- /* cfi_adjust_cfa_offset(ffi_closure_FS) */
-L(sse_entry2):
- movq %rdi, ffi_closure_OFS_G+0x00(%rsp)
- movq %rsi, ffi_closure_OFS_G+0x08(%rsp)
- movq %rdx, ffi_closure_OFS_G+0x10(%rsp)
- movq %rcx, ffi_closure_OFS_G+0x18(%rsp)
- movq %r8, ffi_closure_OFS_G+0x20(%rsp)
- movq %r9, ffi_closure_OFS_G+0x28(%rsp)
-
-#ifdef __ILP32__
- movl 4(%r10), %edi /* Load cif */
- movl 8(%r10), %esi /* Load fun */
- movl %r10d, %edx /* Load closure (user_data) */
+E(L(load_table), UNIX64_RET_XMM64)
+ movq (%rsi), %xmm0
+ ret
+E(L(load_table), UNIX64_RET_X87)
+ fldt (%rsi)
+ ret
+E(L(load_table), UNIX64_RET_X87_2)
+ fldt 16(%rsi)
+ fldt (%rsi)
+ ret
+E(L(load_table), UNIX64_RET_ST_XMM0_RAX)
+ movq 8(%rsi), %rax
+ jmp L(l3)
+E(L(load_table), UNIX64_RET_ST_RAX_XMM0)
+ movq 8(%rsi), %xmm0
+ jmp L(l2)
+E(L(load_table), UNIX64_RET_ST_XMM0_XMM1)
+ movq 8(%rsi), %xmm1
+ jmp L(l3)
+E(L(load_table), UNIX64_RET_ST_RAX_RDX)
+ movq 8(%rsi), %rdx
+L(l2):
+ movq (%rsi), %rax
+ ret
+ .balign 8
+L(l3):
+ movq (%rsi), %xmm0
+ ret
+
+L(la): call PLT(C(abort))
+
+L(UW11):
+ENDF(C(ffi_closure_unix64))
+
+ .balign 2
+ .globl C(ffi_go_closure_unix64_sse)
+ FFI_HIDDEN(C(ffi_go_closure_unix64_sse))
+
+C(ffi_go_closure_unix64_sse):
+L(UW12):
+ subq $ffi_closure_FS, %rsp
+L(UW13):
+ /* cfi_adjust_cfa_offset(ffi_closure_FS) */
+
+ movdqa %xmm0, ffi_closure_OFS_V+0x00(%rsp)
+ movdqa %xmm1, ffi_closure_OFS_V+0x10(%rsp)
+ movdqa %xmm2, ffi_closure_OFS_V+0x20(%rsp)
+ movdqa %xmm3, ffi_closure_OFS_V+0x30(%rsp)
+ movdqa %xmm4, ffi_closure_OFS_V+0x40(%rsp)
+ movdqa %xmm5, ffi_closure_OFS_V+0x50(%rsp)
+ movdqa %xmm6, ffi_closure_OFS_V+0x60(%rsp)
+ movdqa %xmm7, ffi_closure_OFS_V+0x70(%rsp)
+ jmp L(sse_entry2)
+
+L(UW14):
+ENDF(C(ffi_go_closure_unix64_sse))
+
+ .balign 2
+ .globl C(ffi_go_closure_unix64)
+ FFI_HIDDEN(C(ffi_go_closure_unix64))
+
+C(ffi_go_closure_unix64):
+L(UW15):
+ subq $ffi_closure_FS, %rsp
+L(UW16):
+ /* cfi_adjust_cfa_offset(ffi_closure_FS) */
+L(sse_entry2):
+ movq %rdi, ffi_closure_OFS_G+0x00(%rsp)
+ movq %rsi, ffi_closure_OFS_G+0x08(%rsp)
+ movq %rdx, ffi_closure_OFS_G+0x10(%rsp)
+ movq %rcx, ffi_closure_OFS_G+0x18(%rsp)
+ movq %r8, ffi_closure_OFS_G+0x20(%rsp)
+ movq %r9, ffi_closure_OFS_G+0x28(%rsp)
+
+#ifdef __ILP32__
+ movl 4(%r10), %edi /* Load cif */
+ movl 8(%r10), %esi /* Load fun */
+ movl %r10d, %edx /* Load closure (user_data) */
+#else
+ movq 8(%r10), %rdi /* Load cif */
+ movq 16(%r10), %rsi /* Load fun */
+ movq %r10, %rdx /* Load closure (user_data) */
+#endif
+ jmp L(do_closure)
+
+L(UW17):
+ENDF(C(ffi_go_closure_unix64))
+
+/* Sadly, OSX cctools-as doesn't understand .cfi directives at all. */
+
+#ifdef __APPLE__
+.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
+EHFrame0:
+#elif defined(HAVE_AS_X86_64_UNWIND_SECTION_TYPE)
+.section .eh_frame,"a",@unwind
#else
- movq 8(%r10), %rdi /* Load cif */
- movq 16(%r10), %rsi /* Load fun */
- movq %r10, %rdx /* Load closure (user_data) */
+.section .eh_frame,"a",@progbits
#endif
- jmp L(do_closure)
-
-L(UW17):
-ENDF(C(ffi_go_closure_unix64))
-
-/* Sadly, OSX cctools-as doesn't understand .cfi directives at all. */
-
-#ifdef __APPLE__
-.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
-EHFrame0:
-#elif defined(HAVE_AS_X86_64_UNWIND_SECTION_TYPE)
-.section .eh_frame,"a",@unwind
-#else
-.section .eh_frame,"a",@progbits
-#endif
-
-#ifdef HAVE_AS_X86_PCREL
-# define PCREL(X) X - .
-#else
-# define PCREL(X) X@rel
-#endif
-
-/* Simplify advancing between labels. Assume DW_CFA_advance_loc1 fits. */
-#define ADV(N, P) .byte 2, L(N)-L(P)
-
- .balign 8
-L(CIE):
- .set L(set0),L(ECIE)-L(SCIE)
- .long L(set0) /* CIE Length */
-L(SCIE):
+
+#ifdef HAVE_AS_X86_PCREL
+# define PCREL(X) X - .
+#else
+# define PCREL(X) X@rel
+#endif
+
+/* Simplify advancing between labels. Assume DW_CFA_advance_loc1 fits. */
+#define ADV(N, P) .byte 2, L(N)-L(P)
+
+ .balign 8
+L(CIE):
+ .set L(set0),L(ECIE)-L(SCIE)
+ .long L(set0) /* CIE Length */
+L(SCIE):
.long 0 /* CIE Identifier Tag */
.byte 1 /* CIE Version */
- .ascii "zR\0" /* CIE Augmentation */
- .byte 1 /* CIE Code Alignment Factor */
- .byte 0x78 /* CIE Data Alignment Factor */
+ .ascii "zR\0" /* CIE Augmentation */
+ .byte 1 /* CIE Code Alignment Factor */
+ .byte 0x78 /* CIE Data Alignment Factor */
.byte 0x10 /* CIE RA Column */
- .byte 1 /* Augmentation size */
+ .byte 1 /* Augmentation size */
.byte 0x1b /* FDE Encoding (pcrel sdata4) */
- .byte 0xc, 7, 8 /* DW_CFA_def_cfa, %rsp offset 8 */
- .byte 0x80+16, 1 /* DW_CFA_offset, %rip offset 1*-8 */
- .balign 8
-L(ECIE):
-
- .set L(set1),L(EFDE1)-L(SFDE1)
- .long L(set1) /* FDE Length */
-L(SFDE1):
- .long L(SFDE1)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW0)) /* Initial location */
- .long L(UW4)-L(UW0) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW1, UW0)
- .byte 0xc, 6, 32 /* DW_CFA_def_cfa, %rbp 32 */
- .byte 0x80+6, 2 /* DW_CFA_offset, %rbp 2*-8 */
- ADV(UW2, UW1)
+ .byte 0xc, 7, 8 /* DW_CFA_def_cfa, %rsp offset 8 */
+ .byte 0x80+16, 1 /* DW_CFA_offset, %rip offset 1*-8 */
+ .balign 8
+L(ECIE):
+
+ .set L(set1),L(EFDE1)-L(SFDE1)
+ .long L(set1) /* FDE Length */
+L(SFDE1):
+ .long L(SFDE1)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW0)) /* Initial location */
+ .long L(UW4)-L(UW0) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW1, UW0)
+ .byte 0xc, 6, 32 /* DW_CFA_def_cfa, %rbp 32 */
+ .byte 0x80+6, 2 /* DW_CFA_offset, %rbp 2*-8 */
+ ADV(UW2, UW1)
.byte 0xa /* DW_CFA_remember_state */
- .byte 0xc, 7, 8 /* DW_CFA_def_cfa, %rsp 8 */
+ .byte 0xc, 7, 8 /* DW_CFA_def_cfa, %rsp 8 */
.byte 0xc0+6 /* DW_CFA_restore, %rbp */
- ADV(UW3, UW2)
+ ADV(UW3, UW2)
.byte 0xb /* DW_CFA_restore_state */
- .balign 8
-L(EFDE1):
-
- .set L(set2),L(EFDE2)-L(SFDE2)
- .long L(set2) /* FDE Length */
-L(SFDE2):
- .long L(SFDE2)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW5)) /* Initial location */
- .long L(UW7)-L(UW5) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW6, UW5)
- .byte 0xe /* DW_CFA_def_cfa_offset */
- .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */
- .balign 8
-L(EFDE2):
-
- .set L(set3),L(EFDE3)-L(SFDE3)
- .long L(set3) /* FDE Length */
-L(SFDE3):
- .long L(SFDE3)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW8)) /* Initial location */
- .long L(UW11)-L(UW8) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW9, UW8)
+ .balign 8
+L(EFDE1):
+
+ .set L(set2),L(EFDE2)-L(SFDE2)
+ .long L(set2) /* FDE Length */
+L(SFDE2):
+ .long L(SFDE2)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW5)) /* Initial location */
+ .long L(UW7)-L(UW5) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW6, UW5)
+ .byte 0xe /* DW_CFA_def_cfa_offset */
+ .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */
+ .balign 8
+L(EFDE2):
+
+ .set L(set3),L(EFDE3)-L(SFDE3)
+ .long L(set3) /* FDE Length */
+L(SFDE3):
+ .long L(SFDE3)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW8)) /* Initial location */
+ .long L(UW11)-L(UW8) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW9, UW8)
+ .byte 0xe /* DW_CFA_def_cfa_offset */
+ .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */
+ ADV(UW10, UW9)
+ .byte 0xe, 8 /* DW_CFA_def_cfa_offset 8 */
+L(EFDE3):
+
+ .set L(set4),L(EFDE4)-L(SFDE4)
+ .long L(set4) /* FDE Length */
+L(SFDE4):
+ .long L(SFDE4)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW12)) /* Initial location */
+ .long L(UW14)-L(UW12) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW13, UW12)
.byte 0xe /* DW_CFA_def_cfa_offset */
- .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */
- ADV(UW10, UW9)
- .byte 0xe, 8 /* DW_CFA_def_cfa_offset 8 */
-L(EFDE3):
-
- .set L(set4),L(EFDE4)-L(SFDE4)
- .long L(set4) /* FDE Length */
-L(SFDE4):
- .long L(SFDE4)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW12)) /* Initial location */
- .long L(UW14)-L(UW12) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW13, UW12)
+ .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */
+ .balign 8
+L(EFDE4):
+
+ .set L(set5),L(EFDE5)-L(SFDE5)
+ .long L(set5) /* FDE Length */
+L(SFDE5):
+ .long L(SFDE5)-L(CIE) /* FDE CIE offset */
+ .long PCREL(L(UW15)) /* Initial location */
+ .long L(UW17)-L(UW15) /* Address range */
+ .byte 0 /* Augmentation size */
+ ADV(UW16, UW15)
.byte 0xe /* DW_CFA_def_cfa_offset */
- .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */
- .balign 8
-L(EFDE4):
-
- .set L(set5),L(EFDE5)-L(SFDE5)
- .long L(set5) /* FDE Length */
-L(SFDE5):
- .long L(SFDE5)-L(CIE) /* FDE CIE offset */
- .long PCREL(L(UW15)) /* Initial location */
- .long L(UW17)-L(UW15) /* Address range */
- .byte 0 /* Augmentation size */
- ADV(UW16, UW15)
- .byte 0xe /* DW_CFA_def_cfa_offset */
- .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */
- .balign 8
-L(EFDE5):
-#ifdef __APPLE__
- .subsections_via_symbols
- .section __LD,__compact_unwind,regular,debug
-
- /* compact unwind for ffi_call_unix64 */
- .quad C(ffi_call_unix64)
- .set L1,L(UW4)-L(UW0)
- .long L1
- .long 0x04000000 /* use dwarf unwind info */
- .quad 0
- .quad 0
-
- /* compact unwind for ffi_closure_unix64_sse */
- .quad C(ffi_closure_unix64_sse)
- .set L2,L(UW7)-L(UW5)
- .long L2
- .long 0x04000000 /* use dwarf unwind info */
- .quad 0
- .quad 0
-
- /* compact unwind for ffi_closure_unix64 */
- .quad C(ffi_closure_unix64)
- .set L3,L(UW11)-L(UW8)
- .long L3
- .long 0x04000000 /* use dwarf unwind info */
- .quad 0
- .quad 0
-
- /* compact unwind for ffi_go_closure_unix64_sse */
- .quad C(ffi_go_closure_unix64_sse)
- .set L4,L(UW14)-L(UW12)
- .long L4
- .long 0x04000000 /* use dwarf unwind info */
- .quad 0
- .quad 0
-
- /* compact unwind for ffi_go_closure_unix64 */
- .quad C(ffi_go_closure_unix64)
- .set L5,L(UW17)-L(UW15)
- .long L5
- .long 0x04000000 /* use dwarf unwind info */
- .quad 0
- .quad 0
-#endif
-
+ .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */
+ .balign 8
+L(EFDE5):
+#ifdef __APPLE__
+ .subsections_via_symbols
+ .section __LD,__compact_unwind,regular,debug
+
+ /* compact unwind for ffi_call_unix64 */
+ .quad C(ffi_call_unix64)
+ .set L1,L(UW4)-L(UW0)
+ .long L1
+ .long 0x04000000 /* use dwarf unwind info */
+ .quad 0
+ .quad 0
+
+ /* compact unwind for ffi_closure_unix64_sse */
+ .quad C(ffi_closure_unix64_sse)
+ .set L2,L(UW7)-L(UW5)
+ .long L2
+ .long 0x04000000 /* use dwarf unwind info */
+ .quad 0
+ .quad 0
+
+ /* compact unwind for ffi_closure_unix64 */
+ .quad C(ffi_closure_unix64)
+ .set L3,L(UW11)-L(UW8)
+ .long L3
+ .long 0x04000000 /* use dwarf unwind info */
+ .quad 0
+ .quad 0
+
+ /* compact unwind for ffi_go_closure_unix64_sse */
+ .quad C(ffi_go_closure_unix64_sse)
+ .set L4,L(UW14)-L(UW12)
+ .long L4
+ .long 0x04000000 /* use dwarf unwind info */
+ .quad 0
+ .quad 0
+
+ /* compact unwind for ffi_go_closure_unix64 */
+ .quad C(ffi_go_closure_unix64)
+ .set L5,L(UW17)-L(UW15)
+ .long L5
+ .long 0x04000000 /* use dwarf unwind info */
+ .quad 0
+ .quad 0
+#endif
+
#endif /* __x86_64__ */
#if defined __ELF__ && defined __linux__
.section .note.GNU-stack,"",@progbits
diff --git a/contrib/restricted/libffi/src/x86/win64.S b/contrib/restricted/libffi/src/x86/win64.S
index 13b89acbdd..2c334c82f9 100644
--- a/contrib/restricted/libffi/src/x86/win64.S
+++ b/contrib/restricted/libffi/src/x86/win64.S
@@ -1,237 +1,237 @@
-#ifdef __x86_64__
+#ifdef __x86_64__
#define LIBFFI_ASM
#include <fficonfig.h>
#include <ffi.h>
-#include <ffi_cfi.h>
-#include "asmnames.h"
-
-#if defined(HAVE_AS_CFI_PSEUDO_OP)
- .cfi_sections .debug_frame
-#endif
-
-#ifdef X86_WIN64
-#define SEH(...) __VA_ARGS__
-#define arg0 %rcx
-#define arg1 %rdx
-#define arg2 %r8
-#define arg3 %r9
+#include <ffi_cfi.h>
+#include "asmnames.h"
+
+#if defined(HAVE_AS_CFI_PSEUDO_OP)
+ .cfi_sections .debug_frame
+#endif
+
+#ifdef X86_WIN64
+#define SEH(...) __VA_ARGS__
+#define arg0 %rcx
+#define arg1 %rdx
+#define arg2 %r8
+#define arg3 %r9
#else
-#define SEH(...)
-#define arg0 %rdi
-#define arg1 %rsi
-#define arg2 %rdx
-#define arg3 %rcx
-#endif
-
-/* This macro allows the safe creation of jump tables without an
- actual table. The entry points into the table are all 8 bytes.
- The use of ORG asserts that we're at the correct location. */
-/* ??? The clang assembler doesn't handle .org with symbolic expressions. */
-#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__))
-# define E(BASE, X) .balign 8
+#define SEH(...)
+#define arg0 %rdi
+#define arg1 %rsi
+#define arg2 %rdx
+#define arg3 %rcx
+#endif
+
+/* This macro allows the safe creation of jump tables without an
+ actual table. The entry points into the table are all 8 bytes.
+ The use of ORG asserts that we're at the correct location. */
+/* ??? The clang assembler doesn't handle .org with symbolic expressions. */
+#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__))
+# define E(BASE, X) .balign 8
#else
-# define E(BASE, X) .balign 8; .org BASE + X * 8
+# define E(BASE, X) .balign 8; .org BASE + X * 8
#endif
- .text
-
-/* ffi_call_win64 (void *stack, struct win64_call_frame *frame, void *r10)
-
- Bit o trickiness here -- FRAME is the base of the stack frame
- for this function. This has been allocated by ffi_call. We also
- deallocate some of the stack that has been alloca'd. */
-
- .align 8
- .globl C(ffi_call_win64)
- FFI_HIDDEN(C(ffi_call_win64))
-
- SEH(.seh_proc ffi_call_win64)
-C(ffi_call_win64):
- cfi_startproc
- /* Set up the local stack frame and install it in rbp/rsp. */
- movq (%rsp), %rax
- movq %rbp, (arg1)
- movq %rax, 8(arg1)
- movq arg1, %rbp
- cfi_def_cfa(%rbp, 16)
- cfi_rel_offset(%rbp, 0)
- SEH(.seh_pushreg %rbp)
- SEH(.seh_setframe %rbp, 0)
- SEH(.seh_endprologue)
- movq arg0, %rsp
-
- movq arg2, %r10
-
- /* Load all slots into both general and xmm registers. */
- movq (%rsp), %rcx
- movsd (%rsp), %xmm0
- movq 8(%rsp), %rdx
- movsd 8(%rsp), %xmm1
- movq 16(%rsp), %r8
- movsd 16(%rsp), %xmm2
- movq 24(%rsp), %r9
- movsd 24(%rsp), %xmm3
-
- call *16(%rbp)
-
- movl 24(%rbp), %ecx
- movq 32(%rbp), %r8
- leaq 0f(%rip), %r10
- cmpl $FFI_TYPE_SMALL_STRUCT_4B, %ecx
- leaq (%r10, %rcx, 8), %r10
- ja 99f
- jmp *%r10
-
-/* Below, we're space constrained most of the time. Thus we eschew the
- modern "mov, pop, ret" sequence (5 bytes) for "leave, ret" (2 bytes). */
-.macro epilogue
- leaveq
- cfi_remember_state
- cfi_def_cfa(%rsp, 8)
- cfi_restore(%rbp)
- ret
- cfi_restore_state
-.endm
-
- .align 8
-0:
-E(0b, FFI_TYPE_VOID)
- epilogue
-E(0b, FFI_TYPE_INT)
- movslq %eax, %rax
- movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_FLOAT)
- movss %xmm0, (%r8)
- epilogue
-E(0b, FFI_TYPE_DOUBLE)
- movsd %xmm0, (%r8)
- epilogue
-E(0b, FFI_TYPE_LONGDOUBLE)
- call PLT(C(abort))
-E(0b, FFI_TYPE_UINT8)
- movzbl %al, %eax
- movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_SINT8)
- movsbq %al, %rax
- jmp 98f
-E(0b, FFI_TYPE_UINT16)
- movzwl %ax, %eax
- movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_SINT16)
- movswq %ax, %rax
- jmp 98f
-E(0b, FFI_TYPE_UINT32)
- movl %eax, %eax
- movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_SINT32)
- movslq %eax, %rax
- movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_UINT64)
-98: movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_SINT64)
- movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_STRUCT)
- epilogue
-E(0b, FFI_TYPE_POINTER)
- movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_COMPLEX)
- call PLT(C(abort))
-E(0b, FFI_TYPE_SMALL_STRUCT_1B)
- movb %al, (%r8)
- epilogue
-E(0b, FFI_TYPE_SMALL_STRUCT_2B)
- movw %ax, (%r8)
- epilogue
-E(0b, FFI_TYPE_SMALL_STRUCT_4B)
- movl %eax, (%r8)
- epilogue
-
- .align 8
-99: call PLT(C(abort))
-
- epilogue
-
- cfi_endproc
- SEH(.seh_endproc)
-
-
-/* 32 bytes of outgoing register stack space, 8 bytes of alignment,
- 16 bytes of result, 32 bytes of xmm registers. */
-#define ffi_clo_FS (32+8+16+32)
-#define ffi_clo_OFF_R (32+8)
-#define ffi_clo_OFF_X (32+8+16)
-
- .align 8
- .globl C(ffi_go_closure_win64)
- FFI_HIDDEN(C(ffi_go_closure_win64))
-
- SEH(.seh_proc ffi_go_closure_win64)
-C(ffi_go_closure_win64):
- cfi_startproc
- /* Save all integer arguments into the incoming reg stack space. */
- movq %rcx, 8(%rsp)
- movq %rdx, 16(%rsp)
- movq %r8, 24(%rsp)
- movq %r9, 32(%rsp)
-
- movq 8(%r10), %rcx /* load cif */
- movq 16(%r10), %rdx /* load fun */
- movq %r10, %r8 /* closure is user_data */
- jmp 0f
- cfi_endproc
- SEH(.seh_endproc)
-
- .align 8
- .globl C(ffi_closure_win64)
- FFI_HIDDEN(C(ffi_closure_win64))
-
- SEH(.seh_proc ffi_closure_win64)
-C(ffi_closure_win64):
- cfi_startproc
- /* Save all integer arguments into the incoming reg stack space. */
- movq %rcx, 8(%rsp)
- movq %rdx, 16(%rsp)
- movq %r8, 24(%rsp)
- movq %r9, 32(%rsp)
-
- movq FFI_TRAMPOLINE_SIZE(%r10), %rcx /* load cif */
- movq FFI_TRAMPOLINE_SIZE+8(%r10), %rdx /* load fun */
- movq FFI_TRAMPOLINE_SIZE+16(%r10), %r8 /* load user_data */
-0:
- subq $ffi_clo_FS, %rsp
- cfi_adjust_cfa_offset(ffi_clo_FS)
- SEH(.seh_stackalloc ffi_clo_FS)
- SEH(.seh_endprologue)
-
- /* Save all sse arguments into the stack frame. */
- movsd %xmm0, ffi_clo_OFF_X(%rsp)
- movsd %xmm1, ffi_clo_OFF_X+8(%rsp)
- movsd %xmm2, ffi_clo_OFF_X+16(%rsp)
- movsd %xmm3, ffi_clo_OFF_X+24(%rsp)
-
- leaq ffi_clo_OFF_R(%rsp), %r9
- call PLT(C(ffi_closure_win64_inner))
-
- /* Load the result into both possible result registers. */
- movq ffi_clo_OFF_R(%rsp), %rax
- movsd ffi_clo_OFF_R(%rsp), %xmm0
-
- addq $ffi_clo_FS, %rsp
- cfi_adjust_cfa_offset(-ffi_clo_FS)
- ret
-
- cfi_endproc
- SEH(.seh_endproc)
-#endif /* __x86_64__ */
-
-#if defined __ELF__ && defined __linux__
- .section .note.GNU-stack,"",@progbits
-#endif
+ .text
+
+/* ffi_call_win64 (void *stack, struct win64_call_frame *frame, void *r10)
+
+ Bit o trickiness here -- FRAME is the base of the stack frame
+ for this function. This has been allocated by ffi_call. We also
+ deallocate some of the stack that has been alloca'd. */
+
+ .align 8
+ .globl C(ffi_call_win64)
+ FFI_HIDDEN(C(ffi_call_win64))
+
+ SEH(.seh_proc ffi_call_win64)
+C(ffi_call_win64):
+ cfi_startproc
+ /* Set up the local stack frame and install it in rbp/rsp. */
+ movq (%rsp), %rax
+ movq %rbp, (arg1)
+ movq %rax, 8(arg1)
+ movq arg1, %rbp
+ cfi_def_cfa(%rbp, 16)
+ cfi_rel_offset(%rbp, 0)
+ SEH(.seh_pushreg %rbp)
+ SEH(.seh_setframe %rbp, 0)
+ SEH(.seh_endprologue)
+ movq arg0, %rsp
+
+ movq arg2, %r10
+
+ /* Load all slots into both general and xmm registers. */
+ movq (%rsp), %rcx
+ movsd (%rsp), %xmm0
+ movq 8(%rsp), %rdx
+ movsd 8(%rsp), %xmm1
+ movq 16(%rsp), %r8
+ movsd 16(%rsp), %xmm2
+ movq 24(%rsp), %r9
+ movsd 24(%rsp), %xmm3
+
+ call *16(%rbp)
+
+ movl 24(%rbp), %ecx
+ movq 32(%rbp), %r8
+ leaq 0f(%rip), %r10
+ cmpl $FFI_TYPE_SMALL_STRUCT_4B, %ecx
+ leaq (%r10, %rcx, 8), %r10
+ ja 99f
+ jmp *%r10
+
+/* Below, we're space constrained most of the time. Thus we eschew the
+ modern "mov, pop, ret" sequence (5 bytes) for "leave, ret" (2 bytes). */
+.macro epilogue
+ leaveq
+ cfi_remember_state
+ cfi_def_cfa(%rsp, 8)
+ cfi_restore(%rbp)
+ ret
+ cfi_restore_state
+.endm
+
+ .align 8
+0:
+E(0b, FFI_TYPE_VOID)
+ epilogue
+E(0b, FFI_TYPE_INT)
+ movslq %eax, %rax
+ movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_FLOAT)
+ movss %xmm0, (%r8)
+ epilogue
+E(0b, FFI_TYPE_DOUBLE)
+ movsd %xmm0, (%r8)
+ epilogue
+E(0b, FFI_TYPE_LONGDOUBLE)
+ call PLT(C(abort))
+E(0b, FFI_TYPE_UINT8)
+ movzbl %al, %eax
+ movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SINT8)
+ movsbq %al, %rax
+ jmp 98f
+E(0b, FFI_TYPE_UINT16)
+ movzwl %ax, %eax
+ movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SINT16)
+ movswq %ax, %rax
+ jmp 98f
+E(0b, FFI_TYPE_UINT32)
+ movl %eax, %eax
+ movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SINT32)
+ movslq %eax, %rax
+ movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_UINT64)
+98: movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SINT64)
+ movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_STRUCT)
+ epilogue
+E(0b, FFI_TYPE_POINTER)
+ movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_COMPLEX)
+ call PLT(C(abort))
+E(0b, FFI_TYPE_SMALL_STRUCT_1B)
+ movb %al, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SMALL_STRUCT_2B)
+ movw %ax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SMALL_STRUCT_4B)
+ movl %eax, (%r8)
+ epilogue
+
+ .align 8
+99: call PLT(C(abort))
+
+ epilogue
+
+ cfi_endproc
+ SEH(.seh_endproc)
+
+
+/* 32 bytes of outgoing register stack space, 8 bytes of alignment,
+ 16 bytes of result, 32 bytes of xmm registers. */
+#define ffi_clo_FS (32+8+16+32)
+#define ffi_clo_OFF_R (32+8)
+#define ffi_clo_OFF_X (32+8+16)
+
+ .align 8
+ .globl C(ffi_go_closure_win64)
+ FFI_HIDDEN(C(ffi_go_closure_win64))
+
+ SEH(.seh_proc ffi_go_closure_win64)
+C(ffi_go_closure_win64):
+ cfi_startproc
+ /* Save all integer arguments into the incoming reg stack space. */
+ movq %rcx, 8(%rsp)
+ movq %rdx, 16(%rsp)
+ movq %r8, 24(%rsp)
+ movq %r9, 32(%rsp)
+
+ movq 8(%r10), %rcx /* load cif */
+ movq 16(%r10), %rdx /* load fun */
+ movq %r10, %r8 /* closure is user_data */
+ jmp 0f
+ cfi_endproc
+ SEH(.seh_endproc)
+
+ .align 8
+ .globl C(ffi_closure_win64)
+ FFI_HIDDEN(C(ffi_closure_win64))
+
+ SEH(.seh_proc ffi_closure_win64)
+C(ffi_closure_win64):
+ cfi_startproc
+ /* Save all integer arguments into the incoming reg stack space. */
+ movq %rcx, 8(%rsp)
+ movq %rdx, 16(%rsp)
+ movq %r8, 24(%rsp)
+ movq %r9, 32(%rsp)
+
+ movq FFI_TRAMPOLINE_SIZE(%r10), %rcx /* load cif */
+ movq FFI_TRAMPOLINE_SIZE+8(%r10), %rdx /* load fun */
+ movq FFI_TRAMPOLINE_SIZE+16(%r10), %r8 /* load user_data */
+0:
+ subq $ffi_clo_FS, %rsp
+ cfi_adjust_cfa_offset(ffi_clo_FS)
+ SEH(.seh_stackalloc ffi_clo_FS)
+ SEH(.seh_endprologue)
+
+ /* Save all sse arguments into the stack frame. */
+ movsd %xmm0, ffi_clo_OFF_X(%rsp)
+ movsd %xmm1, ffi_clo_OFF_X+8(%rsp)
+ movsd %xmm2, ffi_clo_OFF_X+16(%rsp)
+ movsd %xmm3, ffi_clo_OFF_X+24(%rsp)
+
+ leaq ffi_clo_OFF_R(%rsp), %r9
+ call PLT(C(ffi_closure_win64_inner))
+
+ /* Load the result into both possible result registers. */
+ movq ffi_clo_OFF_R(%rsp), %rax
+ movsd ffi_clo_OFF_R(%rsp), %xmm0
+
+ addq $ffi_clo_FS, %rsp
+ cfi_adjust_cfa_offset(-ffi_clo_FS)
+ ret
+
+ cfi_endproc
+ SEH(.seh_endproc)
+#endif /* __x86_64__ */
+
+#if defined __ELF__ && defined __linux__
+ .section .note.GNU-stack,"",@progbits
+#endif
diff --git a/contrib/restricted/libffi/src/x86/win64_intel.S b/contrib/restricted/libffi/src/x86/win64_intel.S
index fdf3e4aa74..7df78b30e4 100644
--- a/contrib/restricted/libffi/src/x86/win64_intel.S
+++ b/contrib/restricted/libffi/src/x86/win64_intel.S
@@ -1,237 +1,237 @@
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
-#include <ffi_cfi.h>
-#include "asmnames.h"
-
-#if defined(HAVE_AS_CFI_PSEUDO_OP)
- .cfi_sections .debug_frame
-#endif
-
-#ifdef X86_WIN64
-#define SEH(...) __VA_ARGS__
-#define arg0 rcx
-#define arg1 rdx
-#define arg2 r8
-#define arg3 r9
-#else
-#define SEH(...)
-#define arg0 rdi
-#define arg1 rsi
-#define arg2 rdx
-#define arg3 rcx
-#endif
-
-/* This macro allows the safe creation of jump tables without an
- actual table. The entry points into the table are all 8 bytes.
- The use of ORG asserts that we're at the correct location. */
-/* ??? The clang assembler doesn't handle .org with symbolic expressions. */
-#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__))
-# define E(BASE, X) ALIGN 8
-#else
-# define E(BASE, X) ALIGN 8; ORG BASE + X * 8
-#endif
-
- .CODE
- extern PLT(C(abort)):near
- extern C(ffi_closure_win64_inner):near
-
-/* ffi_call_win64 (void *stack, struct win64_call_frame *frame, void *r10)
-
- Bit o trickiness here -- FRAME is the base of the stack frame
- for this function. This has been allocated by ffi_call. We also
- deallocate some of the stack that has been alloca'd. */
-
- ALIGN 8
- PUBLIC C(ffi_call_win64)
-
- ; SEH(.safesh ffi_call_win64)
-C(ffi_call_win64) proc SEH(frame)
- cfi_startproc
- /* Set up the local stack frame and install it in rbp/rsp. */
- mov RAX, [RSP] ; movq (%rsp), %rax
- mov [arg1], RBP ; movq %rbp, (arg1)
- mov [arg1 + 8], RAX; movq %rax, 8(arg1)
- mov RBP, arg1; movq arg1, %rbp
- cfi_def_cfa(rbp, 16)
- cfi_rel_offset(rbp, 0)
- SEH(.pushreg rbp)
- SEH(.setframe rbp, 0)
- SEH(.endprolog)
- mov RSP, arg0 ; movq arg0, %rsp
-
- mov R10, arg2 ; movq arg2, %r10
-
- /* Load all slots into both general and xmm registers. */
- mov RCX, [RSP] ; movq (%rsp), %rcx
- movsd XMM0, qword ptr [RSP] ; movsd (%rsp), %xmm0
- mov RDX, [RSP + 8] ;movq 8(%rsp), %rdx
- movsd XMM1, qword ptr [RSP + 8]; movsd 8(%rsp), %xmm1
- mov R8, [RSP + 16] ; movq 16(%rsp), %r8
- movsd XMM2, qword ptr [RSP + 16] ; movsd 16(%rsp), %xmm2
- mov R9, [RSP + 24] ; movq 24(%rsp), %r9
- movsd XMM3, qword ptr [RSP + 24] ;movsd 24(%rsp), %xmm3
-
- CALL qword ptr [RBP + 16] ; call *16(%rbp)
-
- mov ECX, [RBP + 24] ; movl 24(%rbp), %ecx
- mov R8, [RBP + 32] ; movq 32(%rbp), %r8
- LEA R10, ffi_call_win64_tab ; leaq 0f(%rip), %r10
- CMP ECX, FFI_TYPE_SMALL_STRUCT_4B ; cmpl $FFI_TYPE_SMALL_STRUCT_4B, %ecx
- LEA R10, [R10 + RCX*8] ; leaq (%r10, %rcx, 8), %r10
- JA L99 ; ja 99f
- JMP R10 ; jmp *%r10
-
-/* Below, we're space constrained most of the time. Thus we eschew the
- modern "mov, pop, ret" sequence (5 bytes) for "leave, ret" (2 bytes). */
-epilogue macro
- LEAVE
- cfi_remember_state
- cfi_def_cfa(rsp, 8)
- cfi_restore(rbp)
- RET
- cfi_restore_state
-endm
-
- ALIGN 8
-ffi_call_win64_tab LABEL NEAR
-E(0b, FFI_TYPE_VOID)
- epilogue
-E(0b, FFI_TYPE_INT)
- movsxd rax, eax ; movslq %eax, %rax
- mov qword ptr [r8], rax; movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_FLOAT)
- movss dword ptr [r8], xmm0 ; movss %xmm0, (%r8)
- epilogue
-E(0b, FFI_TYPE_DOUBLE)
- movsd qword ptr[r8], xmm0; movsd %xmm0, (%r8)
- epilogue
-E(0b, FFI_TYPE_LONGDOUBLE)
- call PLT(C(abort))
-E(0b, FFI_TYPE_UINT8)
- movzx eax, al ;movzbl %al, %eax
- mov qword ptr[r8], rax; movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_SINT8)
- movsx rax, al ; movsbq %al, %rax
- jmp L98
-E(0b, FFI_TYPE_UINT16)
- movzx eax, ax ; movzwl %ax, %eax
- mov qword ptr[r8], rax; movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_SINT16)
- movsx rax, ax; movswq %ax, %rax
- jmp L98
-E(0b, FFI_TYPE_UINT32)
- mov eax, eax; movl %eax, %eax
- mov qword ptr[r8], rax ; movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_SINT32)
- movsxd rax, eax; movslq %eax, %rax
- mov qword ptr [r8], rax; movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_UINT64)
-L98 LABEL near
- mov qword ptr [r8], rax ; movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_SINT64)
- mov qword ptr [r8], rax;movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_STRUCT)
- epilogue
-E(0b, FFI_TYPE_POINTER)
- mov qword ptr [r8], rax ;movq %rax, (%r8)
- epilogue
-E(0b, FFI_TYPE_COMPLEX)
- call PLT(C(abort))
-E(0b, FFI_TYPE_SMALL_STRUCT_1B)
- mov byte ptr [r8], al ; movb %al, (%r8)
- epilogue
-E(0b, FFI_TYPE_SMALL_STRUCT_2B)
- mov word ptr [r8], ax ; movw %ax, (%r8)
- epilogue
-E(0b, FFI_TYPE_SMALL_STRUCT_4B)
- mov dword ptr [r8], eax ; movl %eax, (%r8)
- epilogue
-
- align 8
-L99 LABEL near
- call PLT(C(abort))
-
- epilogue
-
- cfi_endproc
- C(ffi_call_win64) endp
-
-
-/* 32 bytes of outgoing register stack space, 8 bytes of alignment,
- 16 bytes of result, 32 bytes of xmm registers. */
-#define ffi_clo_FS (32+8+16+32)
-#define ffi_clo_OFF_R (32+8)
-#define ffi_clo_OFF_X (32+8+16)
-
- align 8
- PUBLIC C(ffi_go_closure_win64)
-
-C(ffi_go_closure_win64) proc
- cfi_startproc
- /* Save all integer arguments into the incoming reg stack space. */
- mov qword ptr [rsp + 8], rcx; movq %rcx, 8(%rsp)
- mov qword ptr [rsp + 16], rdx; movq %rdx, 16(%rsp)
- mov qword ptr [rsp + 24], r8; movq %r8, 24(%rsp)
- mov qword ptr [rsp + 32], r9 ;movq %r9, 32(%rsp)
-
- mov rcx, qword ptr [r10 + 8]; movq 8(%r10), %rcx /* load cif */
- mov rdx, qword ptr [r10 + 16]; movq 16(%r10), %rdx /* load fun */
- mov r8, r10 ; movq %r10, %r8 /* closure is user_data */
- jmp ffi_closure_win64_2
- cfi_endproc
- C(ffi_go_closure_win64) endp
-
- align 8
-
-PUBLIC C(ffi_closure_win64)
-C(ffi_closure_win64) PROC FRAME
- cfi_startproc
- /* Save all integer arguments into the incoming reg stack space. */
- mov qword ptr [rsp + 8], rcx; movq %rcx, 8(%rsp)
- mov qword ptr [rsp + 16], rdx; movq %rdx, 16(%rsp)
- mov qword ptr [rsp + 24], r8; movq %r8, 24(%rsp)
- mov qword ptr [rsp + 32], r9; movq %r9, 32(%rsp)
-
- mov rcx, qword ptr [FFI_TRAMPOLINE_SIZE + r10] ;movq FFI_TRAMPOLINE_SIZE(%r10), %rcx /* load cif */
- mov rdx, qword ptr [FFI_TRAMPOLINE_SIZE + 8 + r10] ; movq FFI_TRAMPOLINE_SIZE+8(%r10), %rdx /* load fun */
- mov r8, qword ptr [FFI_TRAMPOLINE_SIZE+16+r10] ;movq FFI_TRAMPOLINE_SIZE+16(%r10), %r8 /* load user_data */
-ffi_closure_win64_2 LABEL near
- sub rsp, ffi_clo_FS ;subq $ffi_clo_FS, %rsp
- cfi_adjust_cfa_offset(ffi_clo_FS)
- SEH(.allocstack ffi_clo_FS)
- SEH(.endprolog)
-
- /* Save all sse arguments into the stack frame. */
- movsd qword ptr [ffi_clo_OFF_X + rsp], xmm0 ; movsd %xmm0, ffi_clo_OFF_X(%rsp)
- movsd qword ptr [ffi_clo_OFF_X+8+rsp], xmm1 ; movsd %xmm1, ffi_clo_OFF_X+8(%rsp)
- movsd qword ptr [ffi_clo_OFF_X+16+rsp], xmm2 ; movsd %xmm2, ffi_clo_OFF_X+16(%rsp)
- movsd qword ptr [ffi_clo_OFF_X+24+rsp], xmm3 ; movsd %xmm3, ffi_clo_OFF_X+24(%rsp)
-
- lea r9, [ffi_clo_OFF_R + rsp] ; leaq ffi_clo_OFF_R(%rsp), %r9
- call C(ffi_closure_win64_inner)
-
- /* Load the result into both possible result registers. */
-
- mov rax, qword ptr [ffi_clo_OFF_R + rsp] ;movq ffi_clo_OFF_R(%rsp), %rax
- movsd xmm0, qword ptr [rsp + ffi_clo_OFF_R] ;movsd ffi_clo_OFF_R(%rsp), %xmm0
-
- add rsp, ffi_clo_FS ;addq $ffi_clo_FS, %rsp
- cfi_adjust_cfa_offset(-ffi_clo_FS)
- ret
-
- cfi_endproc
- C(ffi_closure_win64) endp
-
-#if defined __ELF__ && defined __linux__
- .section .note.GNU-stack,"",@progbits
-#endif
-_text ends
-end \ No newline at end of file
+#define LIBFFI_ASM
+#include <fficonfig.h>
+#include <ffi.h>
+#include <ffi_cfi.h>
+#include "asmnames.h"
+
+#if defined(HAVE_AS_CFI_PSEUDO_OP)
+ .cfi_sections .debug_frame
+#endif
+
+#ifdef X86_WIN64
+#define SEH(...) __VA_ARGS__
+#define arg0 rcx
+#define arg1 rdx
+#define arg2 r8
+#define arg3 r9
+#else
+#define SEH(...)
+#define arg0 rdi
+#define arg1 rsi
+#define arg2 rdx
+#define arg3 rcx
+#endif
+
+/* This macro allows the safe creation of jump tables without an
+ actual table. The entry points into the table are all 8 bytes.
+ The use of ORG asserts that we're at the correct location. */
+/* ??? The clang assembler doesn't handle .org with symbolic expressions. */
+#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__))
+# define E(BASE, X) ALIGN 8
+#else
+# define E(BASE, X) ALIGN 8; ORG BASE + X * 8
+#endif
+
+ .CODE
+ extern PLT(C(abort)):near
+ extern C(ffi_closure_win64_inner):near
+
+/* ffi_call_win64 (void *stack, struct win64_call_frame *frame, void *r10)
+
+ Bit o trickiness here -- FRAME is the base of the stack frame
+ for this function. This has been allocated by ffi_call. We also
+ deallocate some of the stack that has been alloca'd. */
+
+ ALIGN 8
+ PUBLIC C(ffi_call_win64)
+
+ ; SEH(.safesh ffi_call_win64)
+C(ffi_call_win64) proc SEH(frame)
+ cfi_startproc
+ /* Set up the local stack frame and install it in rbp/rsp. */
+ mov RAX, [RSP] ; movq (%rsp), %rax
+ mov [arg1], RBP ; movq %rbp, (arg1)
+ mov [arg1 + 8], RAX; movq %rax, 8(arg1)
+ mov RBP, arg1; movq arg1, %rbp
+ cfi_def_cfa(rbp, 16)
+ cfi_rel_offset(rbp, 0)
+ SEH(.pushreg rbp)
+ SEH(.setframe rbp, 0)
+ SEH(.endprolog)
+ mov RSP, arg0 ; movq arg0, %rsp
+
+ mov R10, arg2 ; movq arg2, %r10
+
+ /* Load all slots into both general and xmm registers. */
+ mov RCX, [RSP] ; movq (%rsp), %rcx
+ movsd XMM0, qword ptr [RSP] ; movsd (%rsp), %xmm0
+ mov RDX, [RSP + 8] ;movq 8(%rsp), %rdx
+ movsd XMM1, qword ptr [RSP + 8]; movsd 8(%rsp), %xmm1
+ mov R8, [RSP + 16] ; movq 16(%rsp), %r8
+ movsd XMM2, qword ptr [RSP + 16] ; movsd 16(%rsp), %xmm2
+ mov R9, [RSP + 24] ; movq 24(%rsp), %r9
+ movsd XMM3, qword ptr [RSP + 24] ;movsd 24(%rsp), %xmm3
+
+ CALL qword ptr [RBP + 16] ; call *16(%rbp)
+
+ mov ECX, [RBP + 24] ; movl 24(%rbp), %ecx
+ mov R8, [RBP + 32] ; movq 32(%rbp), %r8
+ LEA R10, ffi_call_win64_tab ; leaq 0f(%rip), %r10
+ CMP ECX, FFI_TYPE_SMALL_STRUCT_4B ; cmpl $FFI_TYPE_SMALL_STRUCT_4B, %ecx
+ LEA R10, [R10 + RCX*8] ; leaq (%r10, %rcx, 8), %r10
+ JA L99 ; ja 99f
+ JMP R10 ; jmp *%r10
+
+/* Below, we're space constrained most of the time. Thus we eschew the
+ modern "mov, pop, ret" sequence (5 bytes) for "leave, ret" (2 bytes). */
+epilogue macro
+ LEAVE
+ cfi_remember_state
+ cfi_def_cfa(rsp, 8)
+ cfi_restore(rbp)
+ RET
+ cfi_restore_state
+endm
+
+ ALIGN 8
+ffi_call_win64_tab LABEL NEAR
+E(0b, FFI_TYPE_VOID)
+ epilogue
+E(0b, FFI_TYPE_INT)
+ movsxd rax, eax ; movslq %eax, %rax
+ mov qword ptr [r8], rax; movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_FLOAT)
+ movss dword ptr [r8], xmm0 ; movss %xmm0, (%r8)
+ epilogue
+E(0b, FFI_TYPE_DOUBLE)
+ movsd qword ptr[r8], xmm0; movsd %xmm0, (%r8)
+ epilogue
+E(0b, FFI_TYPE_LONGDOUBLE)
+ call PLT(C(abort))
+E(0b, FFI_TYPE_UINT8)
+ movzx eax, al ;movzbl %al, %eax
+ mov qword ptr[r8], rax; movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SINT8)
+ movsx rax, al ; movsbq %al, %rax
+ jmp L98
+E(0b, FFI_TYPE_UINT16)
+ movzx eax, ax ; movzwl %ax, %eax
+ mov qword ptr[r8], rax; movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SINT16)
+ movsx rax, ax; movswq %ax, %rax
+ jmp L98
+E(0b, FFI_TYPE_UINT32)
+ mov eax, eax; movl %eax, %eax
+ mov qword ptr[r8], rax ; movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SINT32)
+ movsxd rax, eax; movslq %eax, %rax
+ mov qword ptr [r8], rax; movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_UINT64)
+L98 LABEL near
+ mov qword ptr [r8], rax ; movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SINT64)
+ mov qword ptr [r8], rax;movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_STRUCT)
+ epilogue
+E(0b, FFI_TYPE_POINTER)
+ mov qword ptr [r8], rax ;movq %rax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_COMPLEX)
+ call PLT(C(abort))
+E(0b, FFI_TYPE_SMALL_STRUCT_1B)
+ mov byte ptr [r8], al ; movb %al, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SMALL_STRUCT_2B)
+ mov word ptr [r8], ax ; movw %ax, (%r8)
+ epilogue
+E(0b, FFI_TYPE_SMALL_STRUCT_4B)
+ mov dword ptr [r8], eax ; movl %eax, (%r8)
+ epilogue
+
+ align 8
+L99 LABEL near
+ call PLT(C(abort))
+
+ epilogue
+
+ cfi_endproc
+ C(ffi_call_win64) endp
+
+
+/* 32 bytes of outgoing register stack space, 8 bytes of alignment,
+ 16 bytes of result, 32 bytes of xmm registers. */
+#define ffi_clo_FS (32+8+16+32)
+#define ffi_clo_OFF_R (32+8)
+#define ffi_clo_OFF_X (32+8+16)
+
+ align 8
+ PUBLIC C(ffi_go_closure_win64)
+
+C(ffi_go_closure_win64) proc
+ cfi_startproc
+ /* Save all integer arguments into the incoming reg stack space. */
+ mov qword ptr [rsp + 8], rcx; movq %rcx, 8(%rsp)
+ mov qword ptr [rsp + 16], rdx; movq %rdx, 16(%rsp)
+ mov qword ptr [rsp + 24], r8; movq %r8, 24(%rsp)
+ mov qword ptr [rsp + 32], r9 ;movq %r9, 32(%rsp)
+
+ mov rcx, qword ptr [r10 + 8]; movq 8(%r10), %rcx /* load cif */
+ mov rdx, qword ptr [r10 + 16]; movq 16(%r10), %rdx /* load fun */
+ mov r8, r10 ; movq %r10, %r8 /* closure is user_data */
+ jmp ffi_closure_win64_2
+ cfi_endproc
+ C(ffi_go_closure_win64) endp
+
+ align 8
+
+PUBLIC C(ffi_closure_win64)
+C(ffi_closure_win64) PROC FRAME
+ cfi_startproc
+ /* Save all integer arguments into the incoming reg stack space. */
+ mov qword ptr [rsp + 8], rcx; movq %rcx, 8(%rsp)
+ mov qword ptr [rsp + 16], rdx; movq %rdx, 16(%rsp)
+ mov qword ptr [rsp + 24], r8; movq %r8, 24(%rsp)
+ mov qword ptr [rsp + 32], r9; movq %r9, 32(%rsp)
+
+ mov rcx, qword ptr [FFI_TRAMPOLINE_SIZE + r10] ;movq FFI_TRAMPOLINE_SIZE(%r10), %rcx /* load cif */
+ mov rdx, qword ptr [FFI_TRAMPOLINE_SIZE + 8 + r10] ; movq FFI_TRAMPOLINE_SIZE+8(%r10), %rdx /* load fun */
+ mov r8, qword ptr [FFI_TRAMPOLINE_SIZE+16+r10] ;movq FFI_TRAMPOLINE_SIZE+16(%r10), %r8 /* load user_data */
+ffi_closure_win64_2 LABEL near
+ sub rsp, ffi_clo_FS ;subq $ffi_clo_FS, %rsp
+ cfi_adjust_cfa_offset(ffi_clo_FS)
+ SEH(.allocstack ffi_clo_FS)
+ SEH(.endprolog)
+
+ /* Save all sse arguments into the stack frame. */
+ movsd qword ptr [ffi_clo_OFF_X + rsp], xmm0 ; movsd %xmm0, ffi_clo_OFF_X(%rsp)
+ movsd qword ptr [ffi_clo_OFF_X+8+rsp], xmm1 ; movsd %xmm1, ffi_clo_OFF_X+8(%rsp)
+ movsd qword ptr [ffi_clo_OFF_X+16+rsp], xmm2 ; movsd %xmm2, ffi_clo_OFF_X+16(%rsp)
+ movsd qword ptr [ffi_clo_OFF_X+24+rsp], xmm3 ; movsd %xmm3, ffi_clo_OFF_X+24(%rsp)
+
+ lea r9, [ffi_clo_OFF_R + rsp] ; leaq ffi_clo_OFF_R(%rsp), %r9
+ call C(ffi_closure_win64_inner)
+
+ /* Load the result into both possible result registers. */
+
+ mov rax, qword ptr [ffi_clo_OFF_R + rsp] ;movq ffi_clo_OFF_R(%rsp), %rax
+ movsd xmm0, qword ptr [rsp + ffi_clo_OFF_R] ;movsd ffi_clo_OFF_R(%rsp), %xmm0
+
+ add rsp, ffi_clo_FS ;addq $ffi_clo_FS, %rsp
+ cfi_adjust_cfa_offset(-ffi_clo_FS)
+ ret
+
+ cfi_endproc
+ C(ffi_closure_win64) endp
+
+#if defined __ELF__ && defined __linux__
+ .section .note.GNU-stack,"",@progbits
+#endif
+_text ends
+end \ No newline at end of file
diff --git a/contrib/restricted/libffi/testsuite/libffi.bhaible/alignof.h b/contrib/restricted/libffi/testsuite/libffi.bhaible/alignof.h
index ba577fd0f3..00604a513a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.bhaible/alignof.h
+++ b/contrib/restricted/libffi/testsuite/libffi.bhaible/alignof.h
@@ -1,50 +1,50 @@
-/* Determine alignment of types.
- Copyright (C) 2003-2004, 2006, 2009-2017 Free Software Foundation, Inc.
-
- 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, 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, see <https://www.gnu.org/licenses/>. */
-
-#ifndef _ALIGNOF_H
-#define _ALIGNOF_H
-
-#include <stddef.h>
-
-/* alignof_slot (TYPE)
- Determine the alignment of a structure slot (field) of a given type,
- at compile time. Note that the result depends on the ABI.
- This is the same as alignof (TYPE) and _Alignof (TYPE), defined in
- <stdalign.h> if __alignof_is_defined is 1.
- Note: The result cannot be used as a value for an 'enum' constant,
- due to bugs in HP-UX 10.20 cc and AIX 3.2.5 xlc. */
-#if defined __cplusplus
- template <class type> struct alignof_helper { char __slot1; type __slot2; };
-# define alignof_slot(type) offsetof (alignof_helper<type>, __slot2)
-#else
-# define alignof_slot(type) offsetof (struct { char __slot1; type __slot2; }, __slot2)
-#endif
-
-/* alignof_type (TYPE)
- Determine the good alignment of an object of the given type at compile time.
- Note that this is not necessarily the same as alignof_slot(type).
- For example, with GNU C on x86 platforms: alignof_type(double) = 8, but
- - when -malign-double is not specified: alignof_slot(double) = 4,
- - when -malign-double is specified: alignof_slot(double) = 8.
- Note: The result cannot be used as a value for an 'enum' constant,
- due to bugs in HP-UX 10.20 cc and AIX 3.2.5 xlc. */
-#if defined __GNUC__ || defined __IBM__ALIGNOF__
-# define alignof_type __alignof__
-#else
-# define alignof_type alignof_slot
-#endif
-
-#endif /* _ALIGNOF_H */
+/* Determine alignment of types.
+ Copyright (C) 2003-2004, 2006, 2009-2017 Free Software Foundation, Inc.
+
+ 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, 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, see <https://www.gnu.org/licenses/>. */
+
+#ifndef _ALIGNOF_H
+#define _ALIGNOF_H
+
+#include <stddef.h>
+
+/* alignof_slot (TYPE)
+ Determine the alignment of a structure slot (field) of a given type,
+ at compile time. Note that the result depends on the ABI.
+ This is the same as alignof (TYPE) and _Alignof (TYPE), defined in
+ <stdalign.h> if __alignof_is_defined is 1.
+ Note: The result cannot be used as a value for an 'enum' constant,
+ due to bugs in HP-UX 10.20 cc and AIX 3.2.5 xlc. */
+#if defined __cplusplus
+ template <class type> struct alignof_helper { char __slot1; type __slot2; };
+# define alignof_slot(type) offsetof (alignof_helper<type>, __slot2)
+#else
+# define alignof_slot(type) offsetof (struct { char __slot1; type __slot2; }, __slot2)
+#endif
+
+/* alignof_type (TYPE)
+ Determine the good alignment of an object of the given type at compile time.
+ Note that this is not necessarily the same as alignof_slot(type).
+ For example, with GNU C on x86 platforms: alignof_type(double) = 8, but
+ - when -malign-double is not specified: alignof_slot(double) = 4,
+ - when -malign-double is specified: alignof_slot(double) = 8.
+ Note: The result cannot be used as a value for an 'enum' constant,
+ due to bugs in HP-UX 10.20 cc and AIX 3.2.5 xlc. */
+#if defined __GNUC__ || defined __IBM__ALIGNOF__
+# define alignof_type __alignof__
+#else
+# define alignof_type alignof_slot
+#endif
+
+#endif /* _ALIGNOF_H */
diff --git a/contrib/restricted/libffi/testsuite/libffi.bhaible/test-call.c b/contrib/restricted/libffi/testsuite/libffi.bhaible/test-call.c
index c49bd4894c..01a8a21570 100644
--- a/contrib/restricted/libffi/testsuite/libffi.bhaible/test-call.c
+++ b/contrib/restricted/libffi/testsuite/libffi.bhaible/test-call.c
@@ -1,1745 +1,1745 @@
-/**
- Copyright 1993 Bill Triggs <Bill.Triggs@inrialpes.fr>
- Copyright 1995-2017 Bruno Haible <bruno@clisp.org>
-
- 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, see <http://www.gnu.org/licenses/>.
-**/
-
-/* { dg-do run } */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <ffi.h>
-#include "alignof.h"
-#include <stdarg.h>
-
-/* libffi testsuite local changes -------------------------------- */
-#ifdef DGTEST
-/* Redefine exit(1) as a test failure */
-#define exit(V) (void)((V) ? (abort(), 1) : exit(0))
-int count = 0;
-char rbuf1[2048];
-char rbuf2[2048];
-int _fprintf(FILE *stream, const char *format, ...)
-{
- va_list args;
- va_start(args, format);
-
- switch (count++)
- {
- case 0:
- case 1:
- vsprintf(&rbuf1[strlen(rbuf1)], format, args);
- break;
- case 2:
- printf("%s", rbuf1);
- vsprintf(rbuf2, format, args);
- break;
- case 3:
- vsprintf(&rbuf2[strlen(rbuf2)], format, args);
- printf("%s", rbuf2);
- if (strcmp (rbuf1, rbuf2)) abort();
- break;
- }
-
- va_end(args);
-
- return 0;
-}
-#define fprintf _fprintf
-#endif
-/* --------------------------------------------------------------- */
-
-#include "testcases.c"
-
-#ifndef ABI_NUM
-#define ABI_NUM FFI_DEFAULT_ABI
-#endif
-
-/* Definitions that ought to be part of libffi. */
-static ffi_type ffi_type_char;
-#define ffi_type_slonglong ffi_type_sint64
-#define ffi_type_ulonglong ffi_type_uint64
-
-/* libffi does not support arrays inside structs. */
-#define SKIP_EXTRA_STRUCTS
-
-#define FFI_PREP_CIF(cif,argtypes,rettype) \
- if (ffi_prep_cif(&(cif),ABI_NUM,sizeof(argtypes)/sizeof(argtypes[0]),&rettype,argtypes) != FFI_OK) abort()
-#define FFI_PREP_CIF_NOARGS(cif,rettype) \
- if (ffi_prep_cif(&(cif),ABI_NUM,0,&rettype,NULL) != FFI_OK) abort()
-#define FFI_CALL(cif,fn,args,retaddr) \
- ffi_call(&(cif),(void(*)(void))(fn),retaddr,args)
-
-long clear_traces_i (long a, long b, long c, long d, long e, long f, long g, long h,
- long i, long j, long k, long l, long m, long n, long o, long p)
-{ return 0; }
-float clear_traces_f (float a, float b, float c, float d, float e, float f, float g,
- float h, float i, float j, float k, float l, float m, float n,
- float o, float p)
-{ return 0.0; }
-double clear_traces_d (double a, double b, double c, double d, double e, double f, double g,
- double h, double i, double j, double k, double l, double m, double n,
- double o, double p)
-{ return 0.0; }
-J clear_traces_J (void)
-{ J j; j.l1 = j.l2 = 0; return j; }
-void clear_traces (void)
-{ clear_traces_i(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
- clear_traces_f(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
- clear_traces_d(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
- clear_traces_J();
-}
-
-void
- void_tests (void)
-{
-#if (!defined(DGTEST)) || DGTEST == 1
- v_v();
- clear_traces();
- {
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_void);
- {
- FFI_CALL(cif,v_v,NULL,NULL);
- }
- }
-#endif
- return;
-}
-void
- int_tests (void)
-{
- int ir;
- ffi_arg retvalue;
-#if (!defined(DGTEST)) || DGTEST == 2
- ir = i_v();
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- {
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_sint);
- {
- FFI_CALL(cif,i_v,NULL,&retvalue);
- ir = retvalue;
- }
- }
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 3
- ir = i_i(i1);
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
- {
- /*const*/ void* args[] = { &i1 };
- FFI_CALL(cif,i_i,args,&retvalue);
- ir = retvalue;
- }
- }
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 4
- ir = i_i2(i1,i2);
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
- {
- /*const*/ void* args[] = { &i1, &i2 };
- FFI_CALL(cif,i_i2,args,&retvalue);
- ir = retvalue;
- }
- }
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 5
- ir = i_i4(i1,i2,i3,i4);
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
- {
- /*const*/ void* args[] = { &i1, &i2, &i3, &i4 };
- FFI_CALL(cif,i_i4,args,&retvalue);
- ir = retvalue;
- }
- }
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 6
- ir = i_i8(i1,i2,i3,i4,i5,i6,i7,i8);
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
- {
- /*const*/ void* args[] = { &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8 };
- FFI_CALL(cif,i_i8,args,&retvalue);
- ir = retvalue;
- }
- }
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 7
- ir = i_i16(i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16);
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
- {
- /*const*/ void* args[] = { &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8, &i9, &i10, &i11, &i12, &i13, &i14, &i15, &i16 };
- FFI_CALL(cif,i_i16,args,&retvalue);
- ir = retvalue;
- }
- }
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
-
- return;
-}
-void
- float_tests (void)
-{
- float fr;
-
-#if (!defined(DGTEST)) || DGTEST == 8
- fr = f_f(f1);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1 };
- FFI_CALL(cif,f_f,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 9
- fr = f_f2(f1,f2);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2 };
- FFI_CALL(cif,f_f2,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 10
- fr = f_f4(f1,f2,f3,f4);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &f3, &f4 };
- FFI_CALL(cif,f_f4,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 11
- fr = f_f8(f1,f2,f3,f4,f5,f6,f7,f8);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8 };
- FFI_CALL(cif,f_f8,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 12
- fr = f_f16(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &f14, &f15, &f16 };
- FFI_CALL(cif,f_f16,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 13
- fr = f_f24(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &f14, &f15, &f16, &f17, &f18, &f19, &f20, &f21, &f22, &f23, &f24 };
- FFI_CALL(cif,f_f24,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-}
-void
- double_tests (void)
-{
- double dr;
-
-#if (!defined(DGTEST)) || DGTEST == 14
-
- dr = d_d(d1);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1 };
- FFI_CALL(cif,d_d,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 15
- dr = d_d2(d1,d2);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2 };
- FFI_CALL(cif,d_d2,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 16
- dr = d_d4(d1,d2,d3,d4);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2, &d3, &d4 };
- FFI_CALL(cif,d_d4,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 17
- dr = d_d8(d1,d2,d3,d4,d5,d6,d7,d8);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8 };
- FFI_CALL(cif,d_d8,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 18
- dr = d_d16(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &d13, &d14, &d15, &d16 };
- FFI_CALL(cif,d_d16,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
- return;
-}
-void
- pointer_tests (void)
-{
- void* vpr;
-
-#if (!defined(DGTEST)) || DGTEST == 19
- vpr = vp_vpdpcpsp(&uc1,&d2,str3,&I4);
- fprintf(out,"->0x%p\n",vpr);
- fflush(out);
- vpr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_pointer);
- {
- void* puc1 = &uc1;
- void* pd2 = &d2;
- void* pstr3 = str3;
- void* pI4 = &I4;
- /*const*/ void* args[] = { &puc1, &pd2, &pstr3, &pI4 };
- FFI_CALL(cif,vp_vpdpcpsp,args,&vpr);
- }
- }
- fprintf(out,"->0x%p\n",vpr);
- fflush(out);
-#endif
- return;
-}
-void
- mixed_number_tests (void)
-{
- uchar ucr;
- ushort usr;
- float fr;
- double dr;
- long long llr;
-
- /* Unsigned types.
- */
-#if (!defined(DGTEST)) || DGTEST == 20
- ucr = uc_ucsil(uc1, us2, ui3, ul4);
- fprintf(out,"->%u\n",ucr);
- fflush(out);
- ucr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_uchar, &ffi_type_ushort, &ffi_type_uint, &ffi_type_ulong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_uchar);
- {
- ffi_arg r;
- /*const*/ void* args[] = { &uc1, &us2, &ui3, &ul4 };
- FFI_CALL(cif,uc_ucsil,args,&r);
- ucr = (uchar) r;
- }
- }
- fprintf(out,"->%u\n",ucr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 21
- /* Mixed int & float types.
- */
- dr = d_iidd(i1,i2,d3,d4);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &i1, &i2, &d3, &d4 };
- FFI_CALL(cif,d_iidd,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 22
- dr = d_iiidi(i1,i2,i3,d4,i5);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &i1, &i2, &i3, &d4, &i5 };
- FFI_CALL(cif,d_iiidi,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 23
- dr = d_idid(i1,d2,i3,d4);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_double, &ffi_type_sint, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &i1, &d2, &i3, &d4 };
- FFI_CALL(cif,d_idid,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 24
- dr = d_fdi(f1,d2,i3);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &f1, &d2, &i3 };
- FFI_CALL(cif,d_fdi,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 25
- usr = us_cdcd(c1,d2,c3,d4);
- fprintf(out,"->%u\n",usr);
- fflush(out);
- usr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_char, &ffi_type_double, &ffi_type_char, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_ushort);
- {
- ffi_arg rint;
- /*const*/ void* args[] = { &c1, &d2, &c3, &d4 };
- FFI_CALL(cif,us_cdcd,args,&rint);
- usr = (ushort) rint;
- }
- }
- fprintf(out,"->%u\n",usr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 26
- /* Long long types.
- */
- llr = ll_iiilli(i1,i2,i3,ll1,i13);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_slonglong, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- {
- /*const*/ void* args[] = { &i1, &i2, &i3, &ll1, &i13 };
- FFI_CALL(cif,ll_iiilli,args,&llr);
- }
- }
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 27
- llr = ll_flli(f13,ll1,i13);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_slonglong, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- {
- /*const*/ void* args[] = { &f13, &ll1, &i13 };
- FFI_CALL(cif,ll_flli,args,&llr);
- }
- }
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 28
- fr = f_fi(f1,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &i9 };
- FFI_CALL(cif,f_fi,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 29
- fr = f_f2i(f1,f2,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &i9 };
- FFI_CALL(cif,f_f2i,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 30
- fr = f_f3i(f1,f2,f3,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &f3, &i9 };
- FFI_CALL(cif,f_f3i,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 31
- fr = f_f4i(f1,f2,f3,f4,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &i9 };
- FFI_CALL(cif,f_f4i,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 32
- fr = f_f7i(f1,f2,f3,f4,f5,f6,f7,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &i9 };
- FFI_CALL(cif,f_f7i,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 33
- fr = f_f8i(f1,f2,f3,f4,f5,f6,f7,f8,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &i9 };
- FFI_CALL(cif,f_f8i,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 34
- fr = f_f12i(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &i9 };
- FFI_CALL(cif,f_f12i,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 35
- fr = f_f13i(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &i9 };
- FFI_CALL(cif,f_f13i,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 36
- dr = d_di(d1,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &i9 };
- FFI_CALL(cif,d_di,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 37
- dr = d_d2i(d1,d2,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2, &i9 };
- FFI_CALL(cif,d_d2i,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 38
- dr = d_d3i(d1,d2,d3,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2, &d3, &i9 };
- FFI_CALL(cif,d_d3i,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 39
- dr = d_d4i(d1,d2,d3,d4,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &i9 };
- FFI_CALL(cif,d_d4i,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 40
- dr = d_d7i(d1,d2,d3,d4,d5,d6,d7,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &i9 };
- FFI_CALL(cif,d_d7i,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 41
- dr = d_d8i(d1,d2,d3,d4,d5,d6,d7,d8,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &i9 };
- FFI_CALL(cif,d_d8i,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 42
- dr = d_d12i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &i9 };
- FFI_CALL(cif,d_d12i,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 43
- dr = d_d13i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &d13, &i9 };
- FFI_CALL(cif,d_d13i,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
- return;
-}
-void
- small_structure_return_tests (void)
-{
-#if (!defined(DGTEST)) || DGTEST == 44
- {
- Size1 r = S1_v();
- fprintf(out,"->{%c}\n",r.x1);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- {
- ffi_type* ffi_type_Size1_elements[] = { &ffi_type_char, NULL };
- ffi_type ffi_type_Size1;
- ffi_type_Size1.type = FFI_TYPE_STRUCT;
- ffi_type_Size1.size = sizeof(Size1);
- ffi_type_Size1.alignment = alignof_slot(Size1);
- ffi_type_Size1.elements = ffi_type_Size1_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size1);
- {
- FFI_CALL(cif,S1_v,NULL,&r);
- }
- }
- fprintf(out,"->{%c}\n",r.x1);
- fflush(out);
- }
-#endif
-#if (!defined(DGTEST)) || DGTEST == 45
- {
- Size2 r = S2_v();
- fprintf(out,"->{%c%c}\n",r.x1,r.x2);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- {
- ffi_type* ffi_type_Size2_elements[] = { &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size2;
- ffi_type_Size2.type = FFI_TYPE_STRUCT;
- ffi_type_Size2.size = sizeof(Size2);
- ffi_type_Size2.alignment = alignof_slot(Size2);
- ffi_type_Size2.elements = ffi_type_Size2_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size2);
- {
- FFI_CALL(cif,S2_v,NULL,&r);
- }
- }
- fprintf(out,"->{%c%c}\n",r.x1,r.x2);
- fflush(out);
- }
-#endif
-#if (!defined(DGTEST)) || DGTEST == 46
- {
- Size3 r = S3_v();
- fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- {
- ffi_type* ffi_type_Size3_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size3;
- ffi_type_Size3.type = FFI_TYPE_STRUCT;
- ffi_type_Size3.size = sizeof(Size3);
- ffi_type_Size3.alignment = alignof_slot(Size3);
- ffi_type_Size3.elements = ffi_type_Size3_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size3);
- {
- FFI_CALL(cif,S3_v,NULL,&r);
- }
- }
- fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3);
- fflush(out);
- }
-#endif
-#if (!defined(DGTEST)) || DGTEST == 47
- {
- Size4 r = S4_v();
- fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- {
- ffi_type* ffi_type_Size4_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size4;
- ffi_type_Size4.type = FFI_TYPE_STRUCT;
- ffi_type_Size4.size = sizeof(Size4);
- ffi_type_Size4.alignment = alignof_slot(Size4);
- ffi_type_Size4.elements = ffi_type_Size4_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size4);
- {
- FFI_CALL(cif,S4_v,NULL,&r);
- }
- }
- fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4);
- fflush(out);
- }
-#endif
-#if (!defined(DGTEST)) || DGTEST == 48
- {
- Size7 r = S7_v();
- fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- {
- ffi_type* ffi_type_Size7_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size7;
- ffi_type_Size7.type = FFI_TYPE_STRUCT;
- ffi_type_Size7.size = sizeof(Size7);
- ffi_type_Size7.alignment = alignof_slot(Size7);
- ffi_type_Size7.elements = ffi_type_Size7_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size7);
- {
- FFI_CALL(cif,S7_v,NULL,&r);
- }
- }
- fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7);
- fflush(out);
- }
-#endif
-#if (!defined(DGTEST)) || DGTEST == 49
- {
- Size8 r = S8_v();
- fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- {
- ffi_type* ffi_type_Size8_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size8;
- ffi_type_Size8.type = FFI_TYPE_STRUCT;
- ffi_type_Size8.size = sizeof(Size8);
- ffi_type_Size8.alignment = alignof_slot(Size8);
- ffi_type_Size8.elements = ffi_type_Size8_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size8);
- {
- FFI_CALL(cif,S8_v,NULL,&r);
- }
- }
- fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8);
- fflush(out);
- }
-#endif
-#if (!defined(DGTEST)) || DGTEST == 50
- {
- Size12 r = S12_v();
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- {
- ffi_type* ffi_type_Size12_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size12;
- ffi_type_Size12.type = FFI_TYPE_STRUCT;
- ffi_type_Size12.size = sizeof(Size12);
- ffi_type_Size12.alignment = alignof_slot(Size12);
- ffi_type_Size12.elements = ffi_type_Size12_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size12);
- {
- FFI_CALL(cif,S12_v,NULL,&r);
- }
- }
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12);
- fflush(out);
- }
-#endif
-#if (!defined(DGTEST)) || DGTEST == 51
- {
- Size15 r = S15_v();
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- {
- ffi_type* ffi_type_Size15_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size15;
- ffi_type_Size15.type = FFI_TYPE_STRUCT;
- ffi_type_Size15.size = sizeof(Size15);
- ffi_type_Size15.alignment = alignof_slot(Size15);
- ffi_type_Size15.elements = ffi_type_Size15_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size15);
- {
- FFI_CALL(cif,S15_v,NULL,&r);
- }
- }
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15);
- fflush(out);
- }
-#endif
-#if (!defined(DGTEST)) || DGTEST == 52
- {
- Size16 r = S16_v();
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- {
- ffi_type* ffi_type_Size16_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size16;
- ffi_type_Size16.type = FFI_TYPE_STRUCT;
- ffi_type_Size16.size = sizeof(Size16);
- ffi_type_Size16.alignment = alignof_slot(Size16);
- ffi_type_Size16.elements = ffi_type_Size16_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size16);
- {
- FFI_CALL(cif,S16_v,NULL,&r);
- }
- }
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16);
- fflush(out);
- }
-#endif
-}
-void
- structure_tests (void)
-{
- Int Ir;
- Char Cr;
- Float Fr;
- Double Dr;
- J Jr;
-#ifndef SKIP_EXTRA_STRUCTS
- T Tr;
- X Xr;
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 53
- Ir = I_III(I1,I2,I3);
- fprintf(out,"->{%d}\n",Ir.x);
- fflush(out);
- Ir.x = 0; clear_traces();
- {
- ffi_type* ffi_type_Int_elements[] = { &ffi_type_sint, NULL };
- ffi_type ffi_type_Int;
- ffi_type_Int.type = FFI_TYPE_STRUCT;
- ffi_type_Int.size = sizeof(Int);
- ffi_type_Int.alignment = alignof_slot(Int);
- ffi_type_Int.elements = ffi_type_Int_elements;
- ffi_type* argtypes[] = { &ffi_type_Int, &ffi_type_Int, &ffi_type_Int };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_Int);
- {
- /*const*/ void* args[] = { &I1, &I2, &I3 };
- FFI_CALL(cif,I_III,args,&Ir);
- }
- }
- fprintf(out,"->{%d}\n",Ir.x);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 54
- Cr = C_CdC(C1,d2,C3);
- fprintf(out,"->{'%c'}\n",Cr.x);
- fflush(out);
- Cr.x = '\0'; clear_traces();
- {
- ffi_type* ffi_type_Char_elements[] = { &ffi_type_char, NULL };
- ffi_type ffi_type_Char;
- ffi_type_Char.type = FFI_TYPE_STRUCT;
- ffi_type_Char.size = sizeof(Char);
- ffi_type_Char.alignment = alignof_slot(Char);
- ffi_type_Char.elements = ffi_type_Char_elements;
- ffi_type* argtypes[] = { &ffi_type_Char, &ffi_type_double, &ffi_type_Char };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_Char);
- {
- /*const*/ void* args[] = { &C1, &d2, &C3 };
- FFI_CALL(cif,C_CdC,args,&Cr);
- }
- }
- fprintf(out,"->{'%c'}\n",Cr.x);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 55
- Fr = F_Ffd(F1,f2,d3);
- fprintf(out,"->{%g}\n",Fr.x);
- fflush(out);
- Fr.x = 0.0; clear_traces();
- {
- ffi_type* ffi_type_Float_elements[] = { &ffi_type_float, NULL };
- ffi_type ffi_type_Float;
- ffi_type_Float.type = FFI_TYPE_STRUCT;
- ffi_type_Float.size = sizeof(Float);
- ffi_type_Float.alignment = alignof_slot(Float);
- ffi_type_Float.elements = ffi_type_Float_elements;
- ffi_type* argtypes[] = { &ffi_type_Float, &ffi_type_float, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_Float);
- {
- /*const*/ void* args[] = { &F1, &f2, &d3 };
- FFI_CALL(cif,F_Ffd,args,&Fr);
- }
- }
- fprintf(out,"->{%g}\n",Fr.x);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 56
- Dr = D_fDd(f1,D2,d3);
- fprintf(out,"->{%g}\n",Dr.x);
- fflush(out);
- Dr.x = 0.0; clear_traces();
- {
- ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL };
- ffi_type ffi_type_Double;
- ffi_type_Double.type = FFI_TYPE_STRUCT;
- ffi_type_Double.size = sizeof(Double);
- ffi_type_Double.alignment = alignof_slot(Double);
- ffi_type_Double.elements = ffi_type_Double_elements;
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_Double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_Double);
- {
- /*const*/ void* args[] = { &f1, &D2, &d3 };
- FFI_CALL(cif,D_fDd,args,&Dr);
- }
- }
- fprintf(out,"->{%g}\n",Dr.x);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 57
- Dr = D_Dfd(D1,f2,d3);
- fprintf(out,"->{%g}\n",Dr.x);
- fflush(out);
- Dr.x = 0.0; clear_traces();
- {
- ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL };
- ffi_type ffi_type_Double;
- ffi_type_Double.type = FFI_TYPE_STRUCT;
- ffi_type_Double.size = sizeof(Double);
- ffi_type_Double.alignment = alignof_slot(Double);
- ffi_type_Double.elements = ffi_type_Double_elements;
- ffi_type* argtypes[] = { &ffi_type_Double, &ffi_type_float, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_Double);
- {
- /*const*/ void* args[] = { &D1, &f2, &d3 };
- FFI_CALL(cif,D_Dfd,args,&Dr);
- }
- }
- fprintf(out,"->{%g}\n",Dr.x);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 58
- Jr = J_JiJ(J1,i2,J2);
- fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2);
- fflush(out);
- Jr.l1 = Jr.l2 = 0; clear_traces();
- {
- ffi_type* ffi_type_J_elements[] = { &ffi_type_slong, &ffi_type_slong, NULL };
- ffi_type ffi_type_J;
- ffi_type_J.type = FFI_TYPE_STRUCT;
- ffi_type_J.size = sizeof(J);
- ffi_type_J.alignment = alignof_slot(J);
- ffi_type_J.elements = ffi_type_J_elements;
- ffi_type* argtypes[] = { &ffi_type_J, &ffi_type_sint, &ffi_type_J };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_J);
- {
- /*const*/ void* args[] = { &J1, &i2, &J2 };
- FFI_CALL(cif,J_JiJ,args,&Jr);
- }
- }
- fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2);
- fflush(out);
-#endif
-#ifndef SKIP_EXTRA_STRUCTS
-#if (!defined(DGTEST)) || DGTEST == 59
- Tr = T_TcT(T1,' ',T2);
- fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]);
- fflush(out);
- Tr.c[0] = Tr.c[1] = Tr.c[2] = 0; clear_traces();
- {
- ffi_type* ffi_type_T_elements[] = { ??, NULL };
- ffi_type ffi_type_T;
- ffi_type_T.type = FFI_TYPE_STRUCT;
- ffi_type_T.size = sizeof(T);
- ffi_type_T.alignment = alignof_slot(T);
- ffi_type_T.elements = ffi_type_T_elements;
- ffi_type* argtypes[] = { &ffi_type_T, &ffi_type_char, &ffi_type_T };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_T);
- {
- char space = ' ';
- /*const*/ void* args[] = { &T1, &space, &T2 };
- FFI_CALL(cif,T_TcT,args,&Tr);
- }
- }
- fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 60
- Xr = X_BcdB(B1,c2,d3,B2);
- fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1);
- fflush(out);
- Xr.c[0]=Xr.c1='\0'; clear_traces();
- {
- ffi_type* ffi_type_X_elements[] = { ??, NULL };
- ffi_type ffi_type_X;
- ffi_type_X.type = FFI_TYPE_STRUCT;
- ffi_type_X.size = sizeof(X);
- ffi_type_X.alignment = alignof_slot(X);
- ffi_type_X.elements = ffi_type_X_elements;
- ffi_type* argtypes[] = { &ffi_type_X, &ffi_type_char, &ffi_type_double, &ffi_type_X };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_X);
- {
- /*const*/ void* args[] = { &B1, &c2, &d3, &B2 };
- FFI_CALL(cif,X_BcdB,args,&Xr);
- }
- }
- fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1);
- fflush(out);
-#endif
-#endif
-
- return;
-}
-
-void
- gpargs_boundary_tests (void)
-{
- ffi_type* ffi_type_K_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL };
- ffi_type ffi_type_K;
- ffi_type* ffi_type_L_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL };
- ffi_type ffi_type_L;
- long lr;
- long long llr;
- float fr;
- double dr;
-
- ffi_type_K.type = FFI_TYPE_STRUCT;
- ffi_type_K.size = sizeof(K);
- ffi_type_K.alignment = alignof_slot(K);
- ffi_type_K.elements = ffi_type_K_elements;
-
- ffi_type_L.type = FFI_TYPE_STRUCT;
- ffi_type_L.size = sizeof(L);
- ffi_type_L.alignment = alignof_slot(L);
- ffi_type_L.elements = ffi_type_L_elements;
-
-#if (!defined(DGTEST)) || DGTEST == 61
- lr = l_l0K(K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- {
- /*const*/ void* args[] = { &K1, &l9 };
- FFI_CALL(cif,l_l0K,args,&lr);
- }
- }
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 62
- lr = l_l1K(l1,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- {
- /*const*/ void* args[] = { &l1, &K1, &l9 };
- FFI_CALL(cif,l_l1K,args,&lr);
- }
- }
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 63
- lr = l_l2K(l1,l2,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- {
- /*const*/ void* args[] = { &l1, &l2, &K1, &l9 };
- FFI_CALL(cif,l_l2K,args,&lr);
- }
- }
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 64
- lr = l_l3K(l1,l2,l3,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &K1, &l9 };
- FFI_CALL(cif,l_l3K,args,&lr);
- }
- }
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 65
- lr = l_l4K(l1,l2,l3,l4,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &K1, &l9 };
- FFI_CALL(cif,l_l4K,args,&lr);
- }
- }
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 66
- lr = l_l5K(l1,l2,l3,l4,l5,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &K1, &l9 };
- FFI_CALL(cif,l_l5K,args,&lr);
- }
- }
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 67
- lr = l_l6K(l1,l2,l3,l4,l5,l6,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &K1, &l9 };
- FFI_CALL(cif,l_l6K,args,&lr);
- }
- }
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 68
- fr = f_f17l3L(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,l6,l7,l8,L1);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- {
- /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &f14, &f15, &f16, &f17, &l6, &l7, &l8, &L1 };
- FFI_CALL(cif,f_f17l3L,args,&fr);
- }
- }
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 69
- dr = d_d17l3L(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17,l6,l7,l8,L1);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &d13, &d14, &d15, &d16, &d17, &l6, &l7, &l8, &L1 };
- FFI_CALL(cif,d_d17l3L,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 70
- llr = ll_l2ll(l1,l2,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- {
- /*const*/ void* args[] = { &l1, &l2, &ll1, &l9 };
- FFI_CALL(cif,ll_l2ll,args,&llr);
- }
- }
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 71
- llr = ll_l3ll(l1,l2,l3,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &ll1, &l9 };
- FFI_CALL(cif,ll_l3ll,args,&llr);
- }
- }
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 72
- llr = ll_l4ll(l1,l2,l3,l4,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &ll1, &l9 };
- FFI_CALL(cif,ll_l4ll,args,&llr);
- }
- }
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 73
- llr = ll_l5ll(l1,l2,l3,l4,l5,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &ll1, &l9 };
- FFI_CALL(cif,ll_l5ll,args,&llr);
- }
- }
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 74
- llr = ll_l6ll(l1,l2,l3,l4,l5,l6,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &ll1, &l9 };
- FFI_CALL(cif,ll_l6ll,args,&llr);
- }
- }
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 75
- llr = ll_l7ll(l1,l2,l3,l4,l5,l6,l7,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &l7, &ll1, &l9 };
- FFI_CALL(cif,ll_l7ll,args,&llr);
- }
- }
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 76
- dr = d_l2d(l1,l2,d2,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &l1, &l2, &d2, &l9 };
- FFI_CALL(cif,d_l2d,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 77
- dr = d_l3d(l1,l2,l3,d2,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &d2, &l9 };
- FFI_CALL(cif,d_l3d,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 78
- dr = d_l4d(l1,l2,l3,l4,d2,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &d2, &l9 };
- FFI_CALL(cif,d_l4d,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 79
- dr = d_l5d(l1,l2,l3,l4,l5,d2,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &d2, &l9 };
- FFI_CALL(cif,d_l5d,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 80
- dr = d_l6d(l1,l2,l3,l4,l5,l6,d2,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &d2, &l9 };
- FFI_CALL(cif,d_l6d,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-#if (!defined(DGTEST)) || DGTEST == 81
- dr = d_l7d(l1,l2,l3,l4,l5,l6,l7,d2,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- {
- /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &l7, &d2, &l9 };
- FFI_CALL(cif,d_l7d,args,&dr);
- }
- }
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
- return;
-}
-
-int
- main (void)
-{
- ffi_type_char = (char)(-1) < 0 ? ffi_type_schar : ffi_type_uchar;
- out = stdout;
-
- void_tests();
- int_tests();
- float_tests();
- double_tests();
- pointer_tests();
- mixed_number_tests();
- small_structure_return_tests();
- structure_tests();
- gpargs_boundary_tests();
-
- exit(0);
-}
+/**
+ Copyright 1993 Bill Triggs <Bill.Triggs@inrialpes.fr>
+ Copyright 1995-2017 Bruno Haible <bruno@clisp.org>
+
+ 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, see <http://www.gnu.org/licenses/>.
+**/
+
+/* { dg-do run } */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ffi.h>
+#include "alignof.h"
+#include <stdarg.h>
+
+/* libffi testsuite local changes -------------------------------- */
+#ifdef DGTEST
+/* Redefine exit(1) as a test failure */
+#define exit(V) (void)((V) ? (abort(), 1) : exit(0))
+int count = 0;
+char rbuf1[2048];
+char rbuf2[2048];
+int _fprintf(FILE *stream, const char *format, ...)
+{
+ va_list args;
+ va_start(args, format);
+
+ switch (count++)
+ {
+ case 0:
+ case 1:
+ vsprintf(&rbuf1[strlen(rbuf1)], format, args);
+ break;
+ case 2:
+ printf("%s", rbuf1);
+ vsprintf(rbuf2, format, args);
+ break;
+ case 3:
+ vsprintf(&rbuf2[strlen(rbuf2)], format, args);
+ printf("%s", rbuf2);
+ if (strcmp (rbuf1, rbuf2)) abort();
+ break;
+ }
+
+ va_end(args);
+
+ return 0;
+}
+#define fprintf _fprintf
+#endif
+/* --------------------------------------------------------------- */
+
+#include "testcases.c"
+
+#ifndef ABI_NUM
+#define ABI_NUM FFI_DEFAULT_ABI
+#endif
+
+/* Definitions that ought to be part of libffi. */
+static ffi_type ffi_type_char;
+#define ffi_type_slonglong ffi_type_sint64
+#define ffi_type_ulonglong ffi_type_uint64
+
+/* libffi does not support arrays inside structs. */
+#define SKIP_EXTRA_STRUCTS
+
+#define FFI_PREP_CIF(cif,argtypes,rettype) \
+ if (ffi_prep_cif(&(cif),ABI_NUM,sizeof(argtypes)/sizeof(argtypes[0]),&rettype,argtypes) != FFI_OK) abort()
+#define FFI_PREP_CIF_NOARGS(cif,rettype) \
+ if (ffi_prep_cif(&(cif),ABI_NUM,0,&rettype,NULL) != FFI_OK) abort()
+#define FFI_CALL(cif,fn,args,retaddr) \
+ ffi_call(&(cif),(void(*)(void))(fn),retaddr,args)
+
+long clear_traces_i (long a, long b, long c, long d, long e, long f, long g, long h,
+ long i, long j, long k, long l, long m, long n, long o, long p)
+{ return 0; }
+float clear_traces_f (float a, float b, float c, float d, float e, float f, float g,
+ float h, float i, float j, float k, float l, float m, float n,
+ float o, float p)
+{ return 0.0; }
+double clear_traces_d (double a, double b, double c, double d, double e, double f, double g,
+ double h, double i, double j, double k, double l, double m, double n,
+ double o, double p)
+{ return 0.0; }
+J clear_traces_J (void)
+{ J j; j.l1 = j.l2 = 0; return j; }
+void clear_traces (void)
+{ clear_traces_i(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
+ clear_traces_f(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
+ clear_traces_d(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
+ clear_traces_J();
+}
+
+void
+ void_tests (void)
+{
+#if (!defined(DGTEST)) || DGTEST == 1
+ v_v();
+ clear_traces();
+ {
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_void);
+ {
+ FFI_CALL(cif,v_v,NULL,NULL);
+ }
+ }
+#endif
+ return;
+}
+void
+ int_tests (void)
+{
+ int ir;
+ ffi_arg retvalue;
+#if (!defined(DGTEST)) || DGTEST == 2
+ ir = i_v();
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ {
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_sint);
+ {
+ FFI_CALL(cif,i_v,NULL,&retvalue);
+ ir = retvalue;
+ }
+ }
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 3
+ ir = i_i(i1);
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
+ {
+ /*const*/ void* args[] = { &i1 };
+ FFI_CALL(cif,i_i,args,&retvalue);
+ ir = retvalue;
+ }
+ }
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 4
+ ir = i_i2(i1,i2);
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
+ {
+ /*const*/ void* args[] = { &i1, &i2 };
+ FFI_CALL(cif,i_i2,args,&retvalue);
+ ir = retvalue;
+ }
+ }
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 5
+ ir = i_i4(i1,i2,i3,i4);
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
+ {
+ /*const*/ void* args[] = { &i1, &i2, &i3, &i4 };
+ FFI_CALL(cif,i_i4,args,&retvalue);
+ ir = retvalue;
+ }
+ }
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 6
+ ir = i_i8(i1,i2,i3,i4,i5,i6,i7,i8);
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
+ {
+ /*const*/ void* args[] = { &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8 };
+ FFI_CALL(cif,i_i8,args,&retvalue);
+ ir = retvalue;
+ }
+ }
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 7
+ ir = i_i16(i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16);
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
+ {
+ /*const*/ void* args[] = { &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8, &i9, &i10, &i11, &i12, &i13, &i14, &i15, &i16 };
+ FFI_CALL(cif,i_i16,args,&retvalue);
+ ir = retvalue;
+ }
+ }
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+
+ return;
+}
+void
+ float_tests (void)
+{
+ float fr;
+
+#if (!defined(DGTEST)) || DGTEST == 8
+ fr = f_f(f1);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1 };
+ FFI_CALL(cif,f_f,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 9
+ fr = f_f2(f1,f2);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2 };
+ FFI_CALL(cif,f_f2,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 10
+ fr = f_f4(f1,f2,f3,f4);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &f3, &f4 };
+ FFI_CALL(cif,f_f4,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 11
+ fr = f_f8(f1,f2,f3,f4,f5,f6,f7,f8);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8 };
+ FFI_CALL(cif,f_f8,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 12
+ fr = f_f16(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &f14, &f15, &f16 };
+ FFI_CALL(cif,f_f16,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 13
+ fr = f_f24(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &f14, &f15, &f16, &f17, &f18, &f19, &f20, &f21, &f22, &f23, &f24 };
+ FFI_CALL(cif,f_f24,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+}
+void
+ double_tests (void)
+{
+ double dr;
+
+#if (!defined(DGTEST)) || DGTEST == 14
+
+ dr = d_d(d1);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1 };
+ FFI_CALL(cif,d_d,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 15
+ dr = d_d2(d1,d2);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2 };
+ FFI_CALL(cif,d_d2,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 16
+ dr = d_d4(d1,d2,d3,d4);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2, &d3, &d4 };
+ FFI_CALL(cif,d_d4,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 17
+ dr = d_d8(d1,d2,d3,d4,d5,d6,d7,d8);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8 };
+ FFI_CALL(cif,d_d8,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 18
+ dr = d_d16(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &d13, &d14, &d15, &d16 };
+ FFI_CALL(cif,d_d16,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+ return;
+}
+void
+ pointer_tests (void)
+{
+ void* vpr;
+
+#if (!defined(DGTEST)) || DGTEST == 19
+ vpr = vp_vpdpcpsp(&uc1,&d2,str3,&I4);
+ fprintf(out,"->0x%p\n",vpr);
+ fflush(out);
+ vpr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_pointer);
+ {
+ void* puc1 = &uc1;
+ void* pd2 = &d2;
+ void* pstr3 = str3;
+ void* pI4 = &I4;
+ /*const*/ void* args[] = { &puc1, &pd2, &pstr3, &pI4 };
+ FFI_CALL(cif,vp_vpdpcpsp,args,&vpr);
+ }
+ }
+ fprintf(out,"->0x%p\n",vpr);
+ fflush(out);
+#endif
+ return;
+}
+void
+ mixed_number_tests (void)
+{
+ uchar ucr;
+ ushort usr;
+ float fr;
+ double dr;
+ long long llr;
+
+ /* Unsigned types.
+ */
+#if (!defined(DGTEST)) || DGTEST == 20
+ ucr = uc_ucsil(uc1, us2, ui3, ul4);
+ fprintf(out,"->%u\n",ucr);
+ fflush(out);
+ ucr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_uchar, &ffi_type_ushort, &ffi_type_uint, &ffi_type_ulong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_uchar);
+ {
+ ffi_arg r;
+ /*const*/ void* args[] = { &uc1, &us2, &ui3, &ul4 };
+ FFI_CALL(cif,uc_ucsil,args,&r);
+ ucr = (uchar) r;
+ }
+ }
+ fprintf(out,"->%u\n",ucr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 21
+ /* Mixed int & float types.
+ */
+ dr = d_iidd(i1,i2,d3,d4);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &i1, &i2, &d3, &d4 };
+ FFI_CALL(cif,d_iidd,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 22
+ dr = d_iiidi(i1,i2,i3,d4,i5);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &i1, &i2, &i3, &d4, &i5 };
+ FFI_CALL(cif,d_iiidi,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 23
+ dr = d_idid(i1,d2,i3,d4);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_double, &ffi_type_sint, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &i1, &d2, &i3, &d4 };
+ FFI_CALL(cif,d_idid,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 24
+ dr = d_fdi(f1,d2,i3);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &f1, &d2, &i3 };
+ FFI_CALL(cif,d_fdi,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 25
+ usr = us_cdcd(c1,d2,c3,d4);
+ fprintf(out,"->%u\n",usr);
+ fflush(out);
+ usr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_char, &ffi_type_double, &ffi_type_char, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_ushort);
+ {
+ ffi_arg rint;
+ /*const*/ void* args[] = { &c1, &d2, &c3, &d4 };
+ FFI_CALL(cif,us_cdcd,args,&rint);
+ usr = (ushort) rint;
+ }
+ }
+ fprintf(out,"->%u\n",usr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 26
+ /* Long long types.
+ */
+ llr = ll_iiilli(i1,i2,i3,ll1,i13);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_slonglong, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ {
+ /*const*/ void* args[] = { &i1, &i2, &i3, &ll1, &i13 };
+ FFI_CALL(cif,ll_iiilli,args,&llr);
+ }
+ }
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 27
+ llr = ll_flli(f13,ll1,i13);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_slonglong, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ {
+ /*const*/ void* args[] = { &f13, &ll1, &i13 };
+ FFI_CALL(cif,ll_flli,args,&llr);
+ }
+ }
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 28
+ fr = f_fi(f1,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &i9 };
+ FFI_CALL(cif,f_fi,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 29
+ fr = f_f2i(f1,f2,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &i9 };
+ FFI_CALL(cif,f_f2i,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 30
+ fr = f_f3i(f1,f2,f3,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &f3, &i9 };
+ FFI_CALL(cif,f_f3i,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 31
+ fr = f_f4i(f1,f2,f3,f4,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &i9 };
+ FFI_CALL(cif,f_f4i,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 32
+ fr = f_f7i(f1,f2,f3,f4,f5,f6,f7,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &i9 };
+ FFI_CALL(cif,f_f7i,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 33
+ fr = f_f8i(f1,f2,f3,f4,f5,f6,f7,f8,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &i9 };
+ FFI_CALL(cif,f_f8i,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 34
+ fr = f_f12i(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &i9 };
+ FFI_CALL(cif,f_f12i,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 35
+ fr = f_f13i(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &i9 };
+ FFI_CALL(cif,f_f13i,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 36
+ dr = d_di(d1,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &i9 };
+ FFI_CALL(cif,d_di,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 37
+ dr = d_d2i(d1,d2,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2, &i9 };
+ FFI_CALL(cif,d_d2i,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 38
+ dr = d_d3i(d1,d2,d3,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2, &d3, &i9 };
+ FFI_CALL(cif,d_d3i,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 39
+ dr = d_d4i(d1,d2,d3,d4,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &i9 };
+ FFI_CALL(cif,d_d4i,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 40
+ dr = d_d7i(d1,d2,d3,d4,d5,d6,d7,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &i9 };
+ FFI_CALL(cif,d_d7i,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 41
+ dr = d_d8i(d1,d2,d3,d4,d5,d6,d7,d8,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &i9 };
+ FFI_CALL(cif,d_d8i,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 42
+ dr = d_d12i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &i9 };
+ FFI_CALL(cif,d_d12i,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 43
+ dr = d_d13i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &d13, &i9 };
+ FFI_CALL(cif,d_d13i,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+ return;
+}
+void
+ small_structure_return_tests (void)
+{
+#if (!defined(DGTEST)) || DGTEST == 44
+ {
+ Size1 r = S1_v();
+ fprintf(out,"->{%c}\n",r.x1);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ {
+ ffi_type* ffi_type_Size1_elements[] = { &ffi_type_char, NULL };
+ ffi_type ffi_type_Size1;
+ ffi_type_Size1.type = FFI_TYPE_STRUCT;
+ ffi_type_Size1.size = sizeof(Size1);
+ ffi_type_Size1.alignment = alignof_slot(Size1);
+ ffi_type_Size1.elements = ffi_type_Size1_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size1);
+ {
+ FFI_CALL(cif,S1_v,NULL,&r);
+ }
+ }
+ fprintf(out,"->{%c}\n",r.x1);
+ fflush(out);
+ }
+#endif
+#if (!defined(DGTEST)) || DGTEST == 45
+ {
+ Size2 r = S2_v();
+ fprintf(out,"->{%c%c}\n",r.x1,r.x2);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ {
+ ffi_type* ffi_type_Size2_elements[] = { &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size2;
+ ffi_type_Size2.type = FFI_TYPE_STRUCT;
+ ffi_type_Size2.size = sizeof(Size2);
+ ffi_type_Size2.alignment = alignof_slot(Size2);
+ ffi_type_Size2.elements = ffi_type_Size2_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size2);
+ {
+ FFI_CALL(cif,S2_v,NULL,&r);
+ }
+ }
+ fprintf(out,"->{%c%c}\n",r.x1,r.x2);
+ fflush(out);
+ }
+#endif
+#if (!defined(DGTEST)) || DGTEST == 46
+ {
+ Size3 r = S3_v();
+ fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ {
+ ffi_type* ffi_type_Size3_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size3;
+ ffi_type_Size3.type = FFI_TYPE_STRUCT;
+ ffi_type_Size3.size = sizeof(Size3);
+ ffi_type_Size3.alignment = alignof_slot(Size3);
+ ffi_type_Size3.elements = ffi_type_Size3_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size3);
+ {
+ FFI_CALL(cif,S3_v,NULL,&r);
+ }
+ }
+ fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3);
+ fflush(out);
+ }
+#endif
+#if (!defined(DGTEST)) || DGTEST == 47
+ {
+ Size4 r = S4_v();
+ fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ {
+ ffi_type* ffi_type_Size4_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size4;
+ ffi_type_Size4.type = FFI_TYPE_STRUCT;
+ ffi_type_Size4.size = sizeof(Size4);
+ ffi_type_Size4.alignment = alignof_slot(Size4);
+ ffi_type_Size4.elements = ffi_type_Size4_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size4);
+ {
+ FFI_CALL(cif,S4_v,NULL,&r);
+ }
+ }
+ fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4);
+ fflush(out);
+ }
+#endif
+#if (!defined(DGTEST)) || DGTEST == 48
+ {
+ Size7 r = S7_v();
+ fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ {
+ ffi_type* ffi_type_Size7_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size7;
+ ffi_type_Size7.type = FFI_TYPE_STRUCT;
+ ffi_type_Size7.size = sizeof(Size7);
+ ffi_type_Size7.alignment = alignof_slot(Size7);
+ ffi_type_Size7.elements = ffi_type_Size7_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size7);
+ {
+ FFI_CALL(cif,S7_v,NULL,&r);
+ }
+ }
+ fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7);
+ fflush(out);
+ }
+#endif
+#if (!defined(DGTEST)) || DGTEST == 49
+ {
+ Size8 r = S8_v();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ {
+ ffi_type* ffi_type_Size8_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size8;
+ ffi_type_Size8.type = FFI_TYPE_STRUCT;
+ ffi_type_Size8.size = sizeof(Size8);
+ ffi_type_Size8.alignment = alignof_slot(Size8);
+ ffi_type_Size8.elements = ffi_type_Size8_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size8);
+ {
+ FFI_CALL(cif,S8_v,NULL,&r);
+ }
+ }
+ fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8);
+ fflush(out);
+ }
+#endif
+#if (!defined(DGTEST)) || DGTEST == 50
+ {
+ Size12 r = S12_v();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ {
+ ffi_type* ffi_type_Size12_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size12;
+ ffi_type_Size12.type = FFI_TYPE_STRUCT;
+ ffi_type_Size12.size = sizeof(Size12);
+ ffi_type_Size12.alignment = alignof_slot(Size12);
+ ffi_type_Size12.elements = ffi_type_Size12_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size12);
+ {
+ FFI_CALL(cif,S12_v,NULL,&r);
+ }
+ }
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12);
+ fflush(out);
+ }
+#endif
+#if (!defined(DGTEST)) || DGTEST == 51
+ {
+ Size15 r = S15_v();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ {
+ ffi_type* ffi_type_Size15_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size15;
+ ffi_type_Size15.type = FFI_TYPE_STRUCT;
+ ffi_type_Size15.size = sizeof(Size15);
+ ffi_type_Size15.alignment = alignof_slot(Size15);
+ ffi_type_Size15.elements = ffi_type_Size15_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size15);
+ {
+ FFI_CALL(cif,S15_v,NULL,&r);
+ }
+ }
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15);
+ fflush(out);
+ }
+#endif
+#if (!defined(DGTEST)) || DGTEST == 52
+ {
+ Size16 r = S16_v();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ {
+ ffi_type* ffi_type_Size16_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size16;
+ ffi_type_Size16.type = FFI_TYPE_STRUCT;
+ ffi_type_Size16.size = sizeof(Size16);
+ ffi_type_Size16.alignment = alignof_slot(Size16);
+ ffi_type_Size16.elements = ffi_type_Size16_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size16);
+ {
+ FFI_CALL(cif,S16_v,NULL,&r);
+ }
+ }
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16);
+ fflush(out);
+ }
+#endif
+}
+void
+ structure_tests (void)
+{
+ Int Ir;
+ Char Cr;
+ Float Fr;
+ Double Dr;
+ J Jr;
+#ifndef SKIP_EXTRA_STRUCTS
+ T Tr;
+ X Xr;
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 53
+ Ir = I_III(I1,I2,I3);
+ fprintf(out,"->{%d}\n",Ir.x);
+ fflush(out);
+ Ir.x = 0; clear_traces();
+ {
+ ffi_type* ffi_type_Int_elements[] = { &ffi_type_sint, NULL };
+ ffi_type ffi_type_Int;
+ ffi_type_Int.type = FFI_TYPE_STRUCT;
+ ffi_type_Int.size = sizeof(Int);
+ ffi_type_Int.alignment = alignof_slot(Int);
+ ffi_type_Int.elements = ffi_type_Int_elements;
+ ffi_type* argtypes[] = { &ffi_type_Int, &ffi_type_Int, &ffi_type_Int };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_Int);
+ {
+ /*const*/ void* args[] = { &I1, &I2, &I3 };
+ FFI_CALL(cif,I_III,args,&Ir);
+ }
+ }
+ fprintf(out,"->{%d}\n",Ir.x);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 54
+ Cr = C_CdC(C1,d2,C3);
+ fprintf(out,"->{'%c'}\n",Cr.x);
+ fflush(out);
+ Cr.x = '\0'; clear_traces();
+ {
+ ffi_type* ffi_type_Char_elements[] = { &ffi_type_char, NULL };
+ ffi_type ffi_type_Char;
+ ffi_type_Char.type = FFI_TYPE_STRUCT;
+ ffi_type_Char.size = sizeof(Char);
+ ffi_type_Char.alignment = alignof_slot(Char);
+ ffi_type_Char.elements = ffi_type_Char_elements;
+ ffi_type* argtypes[] = { &ffi_type_Char, &ffi_type_double, &ffi_type_Char };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_Char);
+ {
+ /*const*/ void* args[] = { &C1, &d2, &C3 };
+ FFI_CALL(cif,C_CdC,args,&Cr);
+ }
+ }
+ fprintf(out,"->{'%c'}\n",Cr.x);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 55
+ Fr = F_Ffd(F1,f2,d3);
+ fprintf(out,"->{%g}\n",Fr.x);
+ fflush(out);
+ Fr.x = 0.0; clear_traces();
+ {
+ ffi_type* ffi_type_Float_elements[] = { &ffi_type_float, NULL };
+ ffi_type ffi_type_Float;
+ ffi_type_Float.type = FFI_TYPE_STRUCT;
+ ffi_type_Float.size = sizeof(Float);
+ ffi_type_Float.alignment = alignof_slot(Float);
+ ffi_type_Float.elements = ffi_type_Float_elements;
+ ffi_type* argtypes[] = { &ffi_type_Float, &ffi_type_float, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_Float);
+ {
+ /*const*/ void* args[] = { &F1, &f2, &d3 };
+ FFI_CALL(cif,F_Ffd,args,&Fr);
+ }
+ }
+ fprintf(out,"->{%g}\n",Fr.x);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 56
+ Dr = D_fDd(f1,D2,d3);
+ fprintf(out,"->{%g}\n",Dr.x);
+ fflush(out);
+ Dr.x = 0.0; clear_traces();
+ {
+ ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL };
+ ffi_type ffi_type_Double;
+ ffi_type_Double.type = FFI_TYPE_STRUCT;
+ ffi_type_Double.size = sizeof(Double);
+ ffi_type_Double.alignment = alignof_slot(Double);
+ ffi_type_Double.elements = ffi_type_Double_elements;
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_Double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_Double);
+ {
+ /*const*/ void* args[] = { &f1, &D2, &d3 };
+ FFI_CALL(cif,D_fDd,args,&Dr);
+ }
+ }
+ fprintf(out,"->{%g}\n",Dr.x);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 57
+ Dr = D_Dfd(D1,f2,d3);
+ fprintf(out,"->{%g}\n",Dr.x);
+ fflush(out);
+ Dr.x = 0.0; clear_traces();
+ {
+ ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL };
+ ffi_type ffi_type_Double;
+ ffi_type_Double.type = FFI_TYPE_STRUCT;
+ ffi_type_Double.size = sizeof(Double);
+ ffi_type_Double.alignment = alignof_slot(Double);
+ ffi_type_Double.elements = ffi_type_Double_elements;
+ ffi_type* argtypes[] = { &ffi_type_Double, &ffi_type_float, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_Double);
+ {
+ /*const*/ void* args[] = { &D1, &f2, &d3 };
+ FFI_CALL(cif,D_Dfd,args,&Dr);
+ }
+ }
+ fprintf(out,"->{%g}\n",Dr.x);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 58
+ Jr = J_JiJ(J1,i2,J2);
+ fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2);
+ fflush(out);
+ Jr.l1 = Jr.l2 = 0; clear_traces();
+ {
+ ffi_type* ffi_type_J_elements[] = { &ffi_type_slong, &ffi_type_slong, NULL };
+ ffi_type ffi_type_J;
+ ffi_type_J.type = FFI_TYPE_STRUCT;
+ ffi_type_J.size = sizeof(J);
+ ffi_type_J.alignment = alignof_slot(J);
+ ffi_type_J.elements = ffi_type_J_elements;
+ ffi_type* argtypes[] = { &ffi_type_J, &ffi_type_sint, &ffi_type_J };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_J);
+ {
+ /*const*/ void* args[] = { &J1, &i2, &J2 };
+ FFI_CALL(cif,J_JiJ,args,&Jr);
+ }
+ }
+ fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2);
+ fflush(out);
+#endif
+#ifndef SKIP_EXTRA_STRUCTS
+#if (!defined(DGTEST)) || DGTEST == 59
+ Tr = T_TcT(T1,' ',T2);
+ fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]);
+ fflush(out);
+ Tr.c[0] = Tr.c[1] = Tr.c[2] = 0; clear_traces();
+ {
+ ffi_type* ffi_type_T_elements[] = { ??, NULL };
+ ffi_type ffi_type_T;
+ ffi_type_T.type = FFI_TYPE_STRUCT;
+ ffi_type_T.size = sizeof(T);
+ ffi_type_T.alignment = alignof_slot(T);
+ ffi_type_T.elements = ffi_type_T_elements;
+ ffi_type* argtypes[] = { &ffi_type_T, &ffi_type_char, &ffi_type_T };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_T);
+ {
+ char space = ' ';
+ /*const*/ void* args[] = { &T1, &space, &T2 };
+ FFI_CALL(cif,T_TcT,args,&Tr);
+ }
+ }
+ fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 60
+ Xr = X_BcdB(B1,c2,d3,B2);
+ fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1);
+ fflush(out);
+ Xr.c[0]=Xr.c1='\0'; clear_traces();
+ {
+ ffi_type* ffi_type_X_elements[] = { ??, NULL };
+ ffi_type ffi_type_X;
+ ffi_type_X.type = FFI_TYPE_STRUCT;
+ ffi_type_X.size = sizeof(X);
+ ffi_type_X.alignment = alignof_slot(X);
+ ffi_type_X.elements = ffi_type_X_elements;
+ ffi_type* argtypes[] = { &ffi_type_X, &ffi_type_char, &ffi_type_double, &ffi_type_X };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_X);
+ {
+ /*const*/ void* args[] = { &B1, &c2, &d3, &B2 };
+ FFI_CALL(cif,X_BcdB,args,&Xr);
+ }
+ }
+ fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1);
+ fflush(out);
+#endif
+#endif
+
+ return;
+}
+
+void
+ gpargs_boundary_tests (void)
+{
+ ffi_type* ffi_type_K_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL };
+ ffi_type ffi_type_K;
+ ffi_type* ffi_type_L_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL };
+ ffi_type ffi_type_L;
+ long lr;
+ long long llr;
+ float fr;
+ double dr;
+
+ ffi_type_K.type = FFI_TYPE_STRUCT;
+ ffi_type_K.size = sizeof(K);
+ ffi_type_K.alignment = alignof_slot(K);
+ ffi_type_K.elements = ffi_type_K_elements;
+
+ ffi_type_L.type = FFI_TYPE_STRUCT;
+ ffi_type_L.size = sizeof(L);
+ ffi_type_L.alignment = alignof_slot(L);
+ ffi_type_L.elements = ffi_type_L_elements;
+
+#if (!defined(DGTEST)) || DGTEST == 61
+ lr = l_l0K(K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ {
+ /*const*/ void* args[] = { &K1, &l9 };
+ FFI_CALL(cif,l_l0K,args,&lr);
+ }
+ }
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 62
+ lr = l_l1K(l1,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ {
+ /*const*/ void* args[] = { &l1, &K1, &l9 };
+ FFI_CALL(cif,l_l1K,args,&lr);
+ }
+ }
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 63
+ lr = l_l2K(l1,l2,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &K1, &l9 };
+ FFI_CALL(cif,l_l2K,args,&lr);
+ }
+ }
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 64
+ lr = l_l3K(l1,l2,l3,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &K1, &l9 };
+ FFI_CALL(cif,l_l3K,args,&lr);
+ }
+ }
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 65
+ lr = l_l4K(l1,l2,l3,l4,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &K1, &l9 };
+ FFI_CALL(cif,l_l4K,args,&lr);
+ }
+ }
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 66
+ lr = l_l5K(l1,l2,l3,l4,l5,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &K1, &l9 };
+ FFI_CALL(cif,l_l5K,args,&lr);
+ }
+ }
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 67
+ lr = l_l6K(l1,l2,l3,l4,l5,l6,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &K1, &l9 };
+ FFI_CALL(cif,l_l6K,args,&lr);
+ }
+ }
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 68
+ fr = f_f17l3L(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,l6,l7,l8,L1);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ {
+ /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &f14, &f15, &f16, &f17, &l6, &l7, &l8, &L1 };
+ FFI_CALL(cif,f_f17l3L,args,&fr);
+ }
+ }
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 69
+ dr = d_d17l3L(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17,l6,l7,l8,L1);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &d13, &d14, &d15, &d16, &d17, &l6, &l7, &l8, &L1 };
+ FFI_CALL(cif,d_d17l3L,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 70
+ llr = ll_l2ll(l1,l2,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &ll1, &l9 };
+ FFI_CALL(cif,ll_l2ll,args,&llr);
+ }
+ }
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 71
+ llr = ll_l3ll(l1,l2,l3,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &ll1, &l9 };
+ FFI_CALL(cif,ll_l3ll,args,&llr);
+ }
+ }
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 72
+ llr = ll_l4ll(l1,l2,l3,l4,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &ll1, &l9 };
+ FFI_CALL(cif,ll_l4ll,args,&llr);
+ }
+ }
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 73
+ llr = ll_l5ll(l1,l2,l3,l4,l5,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &ll1, &l9 };
+ FFI_CALL(cif,ll_l5ll,args,&llr);
+ }
+ }
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 74
+ llr = ll_l6ll(l1,l2,l3,l4,l5,l6,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &ll1, &l9 };
+ FFI_CALL(cif,ll_l6ll,args,&llr);
+ }
+ }
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 75
+ llr = ll_l7ll(l1,l2,l3,l4,l5,l6,l7,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &l7, &ll1, &l9 };
+ FFI_CALL(cif,ll_l7ll,args,&llr);
+ }
+ }
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 76
+ dr = d_l2d(l1,l2,d2,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &d2, &l9 };
+ FFI_CALL(cif,d_l2d,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 77
+ dr = d_l3d(l1,l2,l3,d2,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &d2, &l9 };
+ FFI_CALL(cif,d_l3d,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 78
+ dr = d_l4d(l1,l2,l3,l4,d2,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &d2, &l9 };
+ FFI_CALL(cif,d_l4d,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 79
+ dr = d_l5d(l1,l2,l3,l4,l5,d2,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &d2, &l9 };
+ FFI_CALL(cif,d_l5d,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 80
+ dr = d_l6d(l1,l2,l3,l4,l5,l6,d2,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &d2, &l9 };
+ FFI_CALL(cif,d_l6d,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+#if (!defined(DGTEST)) || DGTEST == 81
+ dr = d_l7d(l1,l2,l3,l4,l5,l6,l7,d2,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ {
+ /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &l7, &d2, &l9 };
+ FFI_CALL(cif,d_l7d,args,&dr);
+ }
+ }
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+ return;
+}
+
+int
+ main (void)
+{
+ ffi_type_char = (char)(-1) < 0 ? ffi_type_schar : ffi_type_uchar;
+ out = stdout;
+
+ void_tests();
+ int_tests();
+ float_tests();
+ double_tests();
+ pointer_tests();
+ mixed_number_tests();
+ small_structure_return_tests();
+ structure_tests();
+ gpargs_boundary_tests();
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.bhaible/test-call/ya.make b/contrib/restricted/libffi/testsuite/libffi.bhaible/test-call/ya.make
index 6e4b25307a..e6dbfed4ee 100644
--- a/contrib/restricted/libffi/testsuite/libffi.bhaible/test-call/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.bhaible/test-call/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.bhaible)
-
-SRCS(
- test-call.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.bhaible)
+
+SRCS(
+ test-call.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.bhaible/test-callback.c b/contrib/restricted/libffi/testsuite/libffi.bhaible/test-callback.c
index 64c5fbbfe9..c2633c79bb 100644
--- a/contrib/restricted/libffi/testsuite/libffi.bhaible/test-callback.c
+++ b/contrib/restricted/libffi/testsuite/libffi.bhaible/test-callback.c
@@ -1,2885 +1,2885 @@
-/*
- * Copyright 1993 Bill Triggs <Bill.Triggs@inrialpes.fr>
- * Copyright 1995-2017 Bruno Haible <bruno@clisp.org>
- *
- * 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, see <http://www.gnu.org/licenses/>.
- */
-
-/* { dg-do run } */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <ffi.h>
-#include "alignof.h"
-#include <stdarg.h>
-
-/* libffi testsuite local changes -------------------------------- */
-#ifdef DGTEST
-/* Redefine exit(1) as a test failure */
-#define exit(V) (void)((V) ? (abort(), 1) : exit(0))
-int count = 0;
-char rbuf1[2048];
-char rbuf2[2048];
-int _fprintf(FILE *stream, const char *format, ...)
-{
- va_list args;
- va_start(args, format);
-
- switch (count++)
- {
- case 0:
- case 1:
- vsprintf(&rbuf1[strlen(rbuf1)], format, args);
- break;
- case 2:
- printf("%s", rbuf1);
- vsprintf(rbuf2, format, args);
- break;
- case 3:
- vsprintf(&rbuf2[strlen(rbuf2)], format, args);
- printf("%s", rbuf2);
- if (strcmp (rbuf1, rbuf2)) abort();
- break;
- }
-
- va_end(args);
-
- return 0;
-}
-#define fprintf _fprintf
-#endif
-/* --------------------------------------------------------------- */
-
-#include "testcases.c"
-
-#ifndef ABI_NUM
-#define ABI_NUM FFI_DEFAULT_ABI
-#endif
-
-/* Definitions that ought to be part of libffi. */
-static ffi_type ffi_type_char;
-#define ffi_type_slonglong ffi_type_sint64
-#define ffi_type_ulonglong ffi_type_uint64
-
-/* libffi does not support arrays inside structs. */
-#define SKIP_EXTRA_STRUCTS
-
-#define FFI_PREP_CIF(cif,argtypes,rettype) \
- if (ffi_prep_cif(&(cif),ABI_NUM,sizeof(argtypes)/sizeof(argtypes[0]),&rettype,argtypes) != FFI_OK) abort()
-#define FFI_PREP_CIF_NOARGS(cif,rettype) \
- if (ffi_prep_cif(&(cif),ABI_NUM,0,&rettype,NULL) != FFI_OK) abort()
-
-#if defined(__sparc__) && defined(__sun) && defined(__SUNPRO_C) /* SUNWspro cc */
-/* SunPRO cc miscompiles the simulator function for X_BcdB: d.i[1] is
- * temporarily stored in %l2 and put onto the stack from %l2, but in between
- * the copy of X has used %l2 as a counter without saving and restoring its
- * value.
- */
-#define SKIP_X
-#endif
-#if defined(__mipsn32__) && !defined(__GNUC__)
-/* The X test crashes for an unknown reason. */
-#define SKIP_X
-#endif
-
-
-/* These functions simulate the behaviour of the functions defined in testcases.c. */
-
-/* void tests */
-void v_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&v_v) { fprintf(out,"wrong data for v_v\n"); exit(1); }
- fprintf(out,"void f(void):\n");
- fflush(out);
-}
-
-/* int tests */
-void i_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&i_v) { fprintf(out,"wrong data for i_v\n"); exit(1); }
- {int r=99;
- fprintf(out,"int f(void):");
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-void i_i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&i_i) { fprintf(out,"wrong data for i_i\n"); exit(1); }
- int a = *(int*)(*args++);
- int r=a+1;
- fprintf(out,"int f(int):(%d)",a);
- fflush(out);
- *(ffi_arg*)retp = r;
-}
-void i_i2_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&i_i2) { fprintf(out,"wrong data for i_i2\n"); exit(1); }
- {int a = *(int*)(*args++);
- int b = *(int*)(*args++);
- int r=a+b;
- fprintf(out,"int f(2*int):(%d,%d)",a,b);
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-void i_i4_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&i_i4) { fprintf(out,"wrong data for i_i4\n"); exit(1); }
- {int a = *(int*)(*args++);
- int b = *(int*)(*args++);
- int c = *(int*)(*args++);
- int d = *(int*)(*args++);
- int r=a+b+c+d;
- fprintf(out,"int f(4*int):(%d,%d,%d,%d)",a,b,c,d);
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-void i_i8_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&i_i8) { fprintf(out,"wrong data for i_i8\n"); exit(1); }
- {int a = *(int*)(*args++);
- int b = *(int*)(*args++);
- int c = *(int*)(*args++);
- int d = *(int*)(*args++);
- int e = *(int*)(*args++);
- int f = *(int*)(*args++);
- int g = *(int*)(*args++);
- int h = *(int*)(*args++);
- int r=a+b+c+d+e+f+g+h;
- fprintf(out,"int f(8*int):(%d,%d,%d,%d,%d,%d,%d,%d)",a,b,c,d,e,f,g,h);
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-void i_i16_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&i_i16) { fprintf(out,"wrong data for i_i16\n"); exit(1); }
- {int a = *(int*)(*args++);
- int b = *(int*)(*args++);
- int c = *(int*)(*args++);
- int d = *(int*)(*args++);
- int e = *(int*)(*args++);
- int f = *(int*)(*args++);
- int g = *(int*)(*args++);
- int h = *(int*)(*args++);
- int i = *(int*)(*args++);
- int j = *(int*)(*args++);
- int k = *(int*)(*args++);
- int l = *(int*)(*args++);
- int m = *(int*)(*args++);
- int n = *(int*)(*args++);
- int o = *(int*)(*args++);
- int p = *(int*)(*args++);
- int r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
- fprintf(out,"int f(16*int):(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
- a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-
-/* float tests */
-void f_f_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f) { fprintf(out,"wrong data for f_f\n"); exit(1); }
- {float a = *(float*)(*args++);
- float r=a+1.0;
- fprintf(out,"float f(float):(%g)",a);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f2_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f2) { fprintf(out,"wrong data for f_f2\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float r=a+b;
- fprintf(out,"float f(2*float):(%g,%g)",a,b);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f4_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f4) { fprintf(out,"wrong data for f_f4\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float c = *(float*)(*args++);
- float d = *(float*)(*args++);
- float r=a+b+c+d;
- fprintf(out,"float f(4*float):(%g,%g,%g,%g)",a,b,c,d);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f8_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f8) { fprintf(out,"wrong data for f_f8\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float c = *(float*)(*args++);
- float d = *(float*)(*args++);
- float e = *(float*)(*args++);
- float f = *(float*)(*args++);
- float g = *(float*)(*args++);
- float h = *(float*)(*args++);
- float r=a+b+c+d+e+f+g+h;
- fprintf(out,"float f(8*float):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f16_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f16) { fprintf(out,"wrong data for f_f16\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float c = *(float*)(*args++);
- float d = *(float*)(*args++);
- float e = *(float*)(*args++);
- float f = *(float*)(*args++);
- float g = *(float*)(*args++);
- float h = *(float*)(*args++);
- float i = *(float*)(*args++);
- float j = *(float*)(*args++);
- float k = *(float*)(*args++);
- float l = *(float*)(*args++);
- float m = *(float*)(*args++);
- float n = *(float*)(*args++);
- float o = *(float*)(*args++);
- float p = *(float*)(*args++);
- float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
- fprintf(out,"float f(16*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f24_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f24) { fprintf(out,"wrong data for f_f24\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float c = *(float*)(*args++);
- float d = *(float*)(*args++);
- float e = *(float*)(*args++);
- float f = *(float*)(*args++);
- float g = *(float*)(*args++);
- float h = *(float*)(*args++);
- float i = *(float*)(*args++);
- float j = *(float*)(*args++);
- float k = *(float*)(*args++);
- float l = *(float*)(*args++);
- float m = *(float*)(*args++);
- float n = *(float*)(*args++);
- float o = *(float*)(*args++);
- float p = *(float*)(*args++);
- float q = *(float*)(*args++);
- float s = *(float*)(*args++);
- float t = *(float*)(*args++);
- float u = *(float*)(*args++);
- float v = *(float*)(*args++);
- float w = *(float*)(*args++);
- float x = *(float*)(*args++);
- float y = *(float*)(*args++);
- float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+v+w+x+y;
- fprintf(out,"float f(24*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,v,w,x,y);
- fflush(out);
- *(float*)retp = r;
-}}
-
-/* double tests */
-void d_d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d) { fprintf(out,"wrong data for d_d\n"); exit(1); }
- {double a = *(double*)(*args++);
- double r=a+1.0;
- fprintf(out,"double f(double):(%g)",a);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_d2_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d2) { fprintf(out,"wrong data for d_d2\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- double r=a+b;
- fprintf(out,"double f(2*double):(%g,%g)",a,b);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_d4_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d4) { fprintf(out,"wrong data for d_d4\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- double c = *(double*)(*args++);
- double d = *(double*)(*args++);
- double r=a+b+c+d;
- fprintf(out,"double f(4*double):(%g,%g,%g,%g)",a,b,c,d);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_d8_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d8) { fprintf(out,"wrong data for d_d8\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- double c = *(double*)(*args++);
- double d = *(double*)(*args++);
- double e = *(double*)(*args++);
- double f = *(double*)(*args++);
- double g = *(double*)(*args++);
- double h = *(double*)(*args++);
- double r=a+b+c+d+e+f+g+h;
- fprintf(out,"double f(8*double):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_d16_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d16) { fprintf(out,"wrong data for d_d16\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- double c = *(double*)(*args++);
- double d = *(double*)(*args++);
- double e = *(double*)(*args++);
- double f = *(double*)(*args++);
- double g = *(double*)(*args++);
- double h = *(double*)(*args++);
- double i = *(double*)(*args++);
- double j = *(double*)(*args++);
- double k = *(double*)(*args++);
- double l = *(double*)(*args++);
- double m = *(double*)(*args++);
- double n = *(double*)(*args++);
- double o = *(double*)(*args++);
- double p = *(double*)(*args++);
- double r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
- fprintf(out,"double f(16*double):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
- fflush(out);
- *(double*)retp = r;
-}}
-
-/* pointer tests */
-void vp_vpdpcpsp_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&vp_vpdpcpsp) { fprintf(out,"wrong data for vp_vpdpcpsp\n"); exit(1); }
- {void* a = *(void* *)(*args++);
- double* b = *(double* *)(*args++);
- char* c = *(char* *)(*args++);
- Int* d = *(Int* *)(*args++);
- void* ret = (char*)b + 1;
- fprintf(out,"void* f(void*,double*,char*,Int*):(0x%p,0x%p,0x%p,0x%p)",a,b,c,d);
- fflush(out);
- *(void* *)retp = ret;
-}}
-
-/* mixed number tests */
-void uc_ucsil_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&uc_ucsil) { fprintf(out,"wrong data for uc_ucsil\n"); exit(1); }
- {uchar a = *(unsigned char *)(*args++);
- ushort b = *(unsigned short *)(*args++);
- uint c = *(unsigned int *)(*args++);
- ulong d = *(unsigned long *)(*args++);
- uchar r = (uchar)-1;
- fprintf(out,"uchar f(uchar,ushort,uint,ulong):(%u,%u,%u,%lu)",a,b,c,d);
- fflush(out);
- *(ffi_arg *)retp = r;
-}}
-void d_iidd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_iidd) { fprintf(out,"wrong data for d_iidd\n"); exit(1); }
- {int a = *(int*)(*args++);
- int b = *(int*)(*args++);
- double c = *(double*)(*args++);
- double d = *(double*)(*args++);
- double r=a+b+c+d;
- fprintf(out,"double f(int,int,double,double):(%d,%d,%g,%g)",a,b,c,d);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_iiidi_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_iiidi) { fprintf(out,"wrong data for d_iiidi\n"); exit(1); }
- {int a = *(int*)(*args++);
- int b = *(int*)(*args++);
- int c = *(int*)(*args++);
- double d = *(double*)(*args++);
- int e = *(int*)(*args++);
- double r=a+b+c+d+e;
- fprintf(out,"double f(int,int,int,double,int):(%d,%d,%d,%g,%d)",a,b,c,d,e);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_idid_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_idid) { fprintf(out,"wrong data for d_idid\n"); exit(1); }
- {int a = *(int*)(*args++);
- double b = *(double*)(*args++);
- int c = *(int*)(*args++);
- double d = *(double*)(*args++);
- double r=a+b+c+d;
- fprintf(out,"double f(int,double,int,double):(%d,%g,%d,%g)",a,b,c,d);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_fdi_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_fdi) { fprintf(out,"wrong data for d_fdi\n"); exit(1); }
- {float a = *(float*)(*args++);
- double b = *(double*)(*args++);
- int c = *(int*)(*args++);
- double r=a+b+c;
- fprintf(out,"double f(float,double,int):(%g,%g,%d)",a,b,c);
- fflush(out);
- *(double*)retp = r;
-}}
-void us_cdcd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&us_cdcd) { fprintf(out,"wrong data for us_cdcd\n"); exit(1); }
- {char a = *(char*)(*args++);
- double b = *(double*)(*args++);
- char c = *(char*)(*args++);
- double d = *(double*)(*args++);
- ushort r = (ushort)(a + b + c + d);
- fprintf(out,"ushort f(char,double,char,double):('%c',%g,'%c',%g)",a,b,c,d);
- fflush(out);
- *(ffi_arg *)retp = r;
-}}
-void ll_iiilli_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&ll_iiilli) { fprintf(out,"wrong data for ll_iiilli\n"); exit(1); }
- {int a = *(int*)(*args++);
- int b = *(int*)(*args++);
- int c = *(int*)(*args++);
- long long d = *(long long *)(*args++);
- int e = *(int*)(*args++);
- long long r = (long long)(int)a + (long long)(int)b + (long long)(int)c + d + (long long)e;
- fprintf(out,"long long f(int,int,int,long long,int):(%d,%d,%d,0x%lx%08lx,%d)",a,b,c,(long)(d>>32),(long)(d&0xffffffff),e);
- fflush(out);
- *(long long *)retp = r;
-}}
-void ll_flli_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&ll_flli) { fprintf(out,"wrong data for ll_flli\n"); exit(1); }
- {float a = *(float*)(*args++);
- long long b = *(long long *)(*args++);
- int c = *(int*)(*args++);
- long long r = (long long)(int)a + b + (long long)c;
- fprintf(out,"long long f(float,long long,int):(%g,0x%lx%08lx,0x%lx)",a,(long)(b>>32),(long)(b&0xffffffff),(long)c);
- fflush(out);
- *(long long *)retp = r;
-}}
-void f_fi_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_fi) { fprintf(out,"wrong data for f_fi\n"); exit(1); }
- {float a = *(float*)(*args++);
- int z = *(int*)(*args++);
- float r=a+z;
- fprintf(out,"float f(float,int):(%g,%d)",a,z);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f2i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f2i) { fprintf(out,"wrong data for f_f2i\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- int z = *(int*)(*args++);
- float r=a+b+z;
- fprintf(out,"float f(2*float,int):(%g,%g,%d)",a,b,z);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f3i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f3i) { fprintf(out,"wrong data for f_f3i\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float c = *(float*)(*args++);
- int z = *(int*)(*args++);
- float r=a+b+c+z;
- fprintf(out,"float f(3*float,int):(%g,%g,%g,%d)",a,b,c,z);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f4i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f4i) { fprintf(out,"wrong data for f_f4i\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float c = *(float*)(*args++);
- float d = *(float*)(*args++);
- int z = *(int*)(*args++);
- float r=a+b+c+d+z;
- fprintf(out,"float f(4*float,int):(%g,%g,%g,%g,%d)",a,b,c,d,z);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f7i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f7i) { fprintf(out,"wrong data for f_f7i\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float c = *(float*)(*args++);
- float d = *(float*)(*args++);
- float e = *(float*)(*args++);
- float f = *(float*)(*args++);
- float g = *(float*)(*args++);
- int z = *(int*)(*args++);
- float r=a+b+c+d+e+f+g+z;
- fprintf(out,"float f(7*float,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f8i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f8i) { fprintf(out,"wrong data for f_f8i\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float c = *(float*)(*args++);
- float d = *(float*)(*args++);
- float e = *(float*)(*args++);
- float f = *(float*)(*args++);
- float g = *(float*)(*args++);
- float h = *(float*)(*args++);
- int z = *(int*)(*args++);
- float r=a+b+c+d+e+f+g+h+z;
- fprintf(out,"float f(8*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f12i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f12i) { fprintf(out,"wrong data for f_f12i\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float c = *(float*)(*args++);
- float d = *(float*)(*args++);
- float e = *(float*)(*args++);
- float f = *(float*)(*args++);
- float g = *(float*)(*args++);
- float h = *(float*)(*args++);
- float i = *(float*)(*args++);
- float j = *(float*)(*args++);
- float k = *(float*)(*args++);
- float l = *(float*)(*args++);
- int z = *(int*)(*args++);
- float r=a+b+c+d+e+f+g+h+i+j+k+l+z;
- fprintf(out,"float f(12*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z);
- fflush(out);
- *(float*)retp = r;
-}}
-void f_f13i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f13i) { fprintf(out,"wrong data for f_f13i\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float c = *(float*)(*args++);
- float d = *(float*)(*args++);
- float e = *(float*)(*args++);
- float f = *(float*)(*args++);
- float g = *(float*)(*args++);
- float h = *(float*)(*args++);
- float i = *(float*)(*args++);
- float j = *(float*)(*args++);
- float k = *(float*)(*args++);
- float l = *(float*)(*args++);
- float m = *(float*)(*args++);
- int z = *(int*)(*args++);
- float r=a+b+c+d+e+f+g+h+i+j+k+l+m+z;
- fprintf(out,"float f(13*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z);
- fflush(out);
- *(float*)retp = r;
-}}
-void d_di_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_di) { fprintf(out,"wrong data for d_di\n"); exit(1); }
- {double a = *(double*)(*args++);
- int z = *(int*)(*args++);
- double r=a+z;
- fprintf(out,"double f(double,int):(%g,%d)",a,z);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_d2i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d2i) { fprintf(out,"wrong data for d_d2i\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- int z = *(int*)(*args++);
- double r=a+b+z;
- fprintf(out,"double f(2*double,int):(%g,%g,%d)",a,b,z);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_d3i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d3i) { fprintf(out,"wrong data for d_d3i\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- double c = *(double*)(*args++);
- int z = *(int*)(*args++);
- double r=a+b+c+z;
- fprintf(out,"double f(3*double,int):(%g,%g,%g,%d)",a,b,c,z);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_d4i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d4i) { fprintf(out,"wrong data for d_d4i\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- double c = *(double*)(*args++);
- double d = *(double*)(*args++);
- int z = *(int*)(*args++);
- double r=a+b+c+d+z;
- fprintf(out,"double f(4*double,int):(%g,%g,%g,%g,%d)",a,b,c,d,z);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_d7i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d7i) { fprintf(out,"wrong data for d_d7i\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- double c = *(double*)(*args++);
- double d = *(double*)(*args++);
- double e = *(double*)(*args++);
- double f = *(double*)(*args++);
- double g = *(double*)(*args++);
- int z = *(int*)(*args++);
- double r=a+b+c+d+e+f+g+z;
- fprintf(out,"double f(7*double,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_d8i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d8i) { fprintf(out,"wrong data for d_d8i\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- double c = *(double*)(*args++);
- double d = *(double*)(*args++);
- double e = *(double*)(*args++);
- double f = *(double*)(*args++);
- double g = *(double*)(*args++);
- double h = *(double*)(*args++);
- int z = *(int*)(*args++);
- double r=a+b+c+d+e+f+g+h+z;
- fprintf(out,"double f(8*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_d12i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d12i) { fprintf(out,"wrong data for d_d12i\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- double c = *(double*)(*args++);
- double d = *(double*)(*args++);
- double e = *(double*)(*args++);
- double f = *(double*)(*args++);
- double g = *(double*)(*args++);
- double h = *(double*)(*args++);
- double i = *(double*)(*args++);
- double j = *(double*)(*args++);
- double k = *(double*)(*args++);
- double l = *(double*)(*args++);
- int z = *(int*)(*args++);
- double r=a+b+c+d+e+f+g+h+i+j+k+l+z;
- fprintf(out,"double f(12*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_d13i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d13i) { fprintf(out,"wrong data for d_d13i\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- double c = *(double*)(*args++);
- double d = *(double*)(*args++);
- double e = *(double*)(*args++);
- double f = *(double*)(*args++);
- double g = *(double*)(*args++);
- double h = *(double*)(*args++);
- double i = *(double*)(*args++);
- double j = *(double*)(*args++);
- double k = *(double*)(*args++);
- double l = *(double*)(*args++);
- double m = *(double*)(*args++);
- int z = *(int*)(*args++);
- double r=a+b+c+d+e+f+g+h+i+j+k+l+m+z;
- fprintf(out,"double f(13*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z);
- fflush(out);
- *(double*)retp = r;
-}}
-
-/* small structure return tests */
-void S1_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&S1_v) { fprintf(out,"wrong data for S1_v\n"); exit(1); }
- {Size1 r = Size1_1;
- fprintf(out,"Size1 f(void):");
- fflush(out);
- *(Size1*)retp = r;
-}}
-void S2_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&S2_v) { fprintf(out,"wrong data for S2_v\n"); exit(1); }
- {Size2 r = Size2_1;
- fprintf(out,"Size2 f(void):");
- fflush(out);
- *(Size2*)retp = r;
-}}
-void S3_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&S3_v) { fprintf(out,"wrong data for S3_v\n"); exit(1); }
- {Size3 r = Size3_1;
- fprintf(out,"Size3 f(void):");
- fflush(out);
- *(Size3*)retp = r;
-}}
-void S4_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&S4_v) { fprintf(out,"wrong data for S4_v\n"); exit(1); }
- {Size4 r = Size4_1;
- fprintf(out,"Size4 f(void):");
- fflush(out);
- *(Size4*)retp = r;
-}}
-void S7_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&S7_v) { fprintf(out,"wrong data for S7_v\n"); exit(1); }
- {Size7 r = Size7_1;
- fprintf(out,"Size7 f(void):");
- fflush(out);
- *(Size7*)retp = r;
-}}
-void S8_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&S8_v) { fprintf(out,"wrong data for S8_v\n"); exit(1); }
- {Size8 r = Size8_1;
- fprintf(out,"Size8 f(void):");
- fflush(out);
- *(Size8*)retp = r;
-}}
-void S12_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&S12_v) { fprintf(out,"wrong data for S12_v\n"); exit(1); }
- {Size12 r = Size12_1;
- fprintf(out,"Size12 f(void):");
- fflush(out);
- *(Size12*)retp = r;
-}}
-void S15_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&S15_v) { fprintf(out,"wrong data for S15_v\n"); exit(1); }
- {Size15 r = Size15_1;
- fprintf(out,"Size15 f(void):");
- fflush(out);
- *(Size15*)retp = r;
-}}
-void S16_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&S16_v) { fprintf(out,"wrong data for S16_v\n"); exit(1); }
- {Size16 r = Size16_1;
- fprintf(out,"Size16 f(void):");
- fflush(out);
- *(Size16*)retp = r;
-}}
-
-/* structure tests */
-void I_III_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&I_III) { fprintf(out,"wrong data for I_III\n"); exit(1); }
- {Int a = *(Int*)(*args++);
- Int b = *(Int*)(*args++);
- Int c = *(Int*)(*args++);
- Int r;
- r.x = a.x + b.x + c.x;
- fprintf(out,"Int f(Int,Int,Int):({%d},{%d},{%d})",a.x,b.x,c.x);
- fflush(out);
- *(Int*)retp = r;
-}}
-void C_CdC_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&C_CdC) { fprintf(out,"wrong data for C_CdC\n"); exit(1); }
- {Char a = *(Char*)(*args++);
- double b = *(double*)(*args++);
- Char c = *(Char*)(*args++);
- Char r;
- r.x = (a.x + c.x)/2;
- fprintf(out,"Char f(Char,double,Char):({'%c'},%g,{'%c'})",a.x,b,c.x);
- fflush(out);
- *(Char*)retp = r;
-}}
-void F_Ffd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&F_Ffd) { fprintf(out,"wrong data for F_Ffd\n"); exit(1); }
- {Float a = *(Float*)(*args++);
- float b = *(float*)(*args++);
- double c = *(double*)(*args++);
- Float r;
- r.x = a.x + b + c;
- fprintf(out,"Float f(Float,float,double):({%g},%g,%g)",a.x,b,c);
- fflush(out);
- *(Float*)retp = r;
-}}
-void D_fDd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&D_fDd) { fprintf(out,"wrong data for D_fDd\n"); exit(1); }
- {float a = *(float*)(*args++);
- Double b = *(Double*)(*args++);
- double c = *(double*)(*args++);
- Double r;
- r.x = a + b.x + c;
- fprintf(out,"Double f(float,Double,double):(%g,{%g},%g)",a,b.x,c);
- fflush(out);
- *(Double*)retp = r;
-}}
-void D_Dfd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&D_Dfd) { fprintf(out,"wrong data for D_Dfd\n"); exit(1); }
- {Double a = *(Double*)(*args++);
- float b = *(float*)(*args++);
- double c = *(double*)(*args++);
- Double r;
- r.x = a.x + b + c;
- fprintf(out,"Double f(Double,float,double):({%g},%g,%g)",a.x,b,c);
- fflush(out);
- *(Double*)retp = r;
-}}
-void J_JiJ_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&J_JiJ) { fprintf(out,"wrong data for J_JiJ\n"); exit(1); }
- {J a = *(J*)(*args++);
- int b= *(int*)(*args++);
- J c = *(J*)(*args++);
- J r;
- r.l1 = a.l1+c.l1; r.l2 = a.l2+b+c.l2;
- fprintf(out,"J f(J,int,J):({%ld,%ld},%d,{%ld,%ld})",a.l1,a.l2,b,c.l1,c.l2);
- fflush(out);
- *(J*)retp = r;
-}}
-#ifndef SKIP_EXTRA_STRUCTS
-void T_TcT_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&T_TcT) { fprintf(out,"wrong data for T_TcT\n"); exit(1); }
- {T a = *(T*)(*args++);
- char b = *(char*)(*args++);
- T c = *(T*)(*args++);
- T r;
- r.c[0]='b'; r.c[1]=c.c[1]; r.c[2]=c.c[2];
- fprintf(out,"T f(T,char,T):({\"%c%c%c\"},'%c',{\"%c%c%c\"})",a.c[0],a.c[1],a.c[2],b,c.c[0],c.c[1],c.c[2]);
- fflush(out);
- *(T*)retp = r;
-}}
-void X_BcdB_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&X_BcdB) { fprintf(out,"wrong data for X_BcdB\n"); exit(1); }
- {B a = *(B*)(*args++);
- char b = *(char*)(*args++);
- double c = *(double*)(*args++);
- B d = *(B*)(*args++);
- static X xr={"return val",'R'};
- X r;
- r = xr;
- r.c1 = b;
- fprintf(out,"X f(B,char,double,B):({%g,{%d,%d,%d}},'%c',%g,{%g,{%d,%d,%d}})",
- a.d,a.i[0],a.i[1],a.i[2],b,c,d.d,d.i[0],d.i[1],d.i[2]);
- fflush(out);
- *(X*)retp = r;
-}}
-#endif
-
-/* gpargs boundary tests */
-void l_l0K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&l_l0K) { fprintf(out,"wrong data for l_l0K\n"); exit(1); }
- {K b = *(K*)(*args++);
- long c = *(long*)(*args++);
- long r = b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(K,long):(%ld,%ld,%ld,%ld,%ld)",b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-void l_l1K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&l_l1K) { fprintf(out,"wrong data for l_l1K\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- K b = *(K*)(*args++);
- long c = *(long*)(*args++);
- long r = a1 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld)",a1,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-void l_l2K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&l_l2K) { fprintf(out,"wrong data for l_l2K\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- K b = *(K*)(*args++);
- long c = *(long*)(*args++);
- long r = a1 + a2 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(2*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-void l_l3K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&l_l3K) { fprintf(out,"wrong data for l_l3K\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- K b = *(K*)(*args++);
- long c = *(long*)(*args++);
- long r = a1 + a2 + a3 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(3*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-void l_l4K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&l_l4K) { fprintf(out,"wrong data for l_l4K\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long a4 = *(long*)(*args++);
- K b = *(K*)(*args++);
- long c = *(long*)(*args++);
- long r = a1 + a2 + a3 + a4 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(4*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-void l_l5K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&l_l5K) { fprintf(out,"wrong data for l_l5K\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long a4 = *(long*)(*args++);
- long a5 = *(long*)(*args++);
- K b = *(K*)(*args++);
- long c = *(long*)(*args++);
- long r = a1 + a2 + a3 + a4 + a5 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(5*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-void l_l6K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&l_l6K) { fprintf(out,"wrong data for l_l6K\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long a4 = *(long*)(*args++);
- long a5 = *(long*)(*args++);
- long a6 = *(long*)(*args++);
- K b = *(K*)(*args++);
- long c = *(long*)(*args++);
- long r = a1 + a2 + a3 + a4 + a5 + a6 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(6*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,a6,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- *(ffi_arg*)retp = r;
-}}
-void f_f17l3L_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&f_f17l3L) { fprintf(out,"wrong data for f_f17l3L\n"); exit(1); }
- {float a = *(float*)(*args++);
- float b = *(float*)(*args++);
- float c = *(float*)(*args++);
- float d = *(float*)(*args++);
- float e = *(float*)(*args++);
- float f = *(float*)(*args++);
- float g = *(float*)(*args++);
- float h = *(float*)(*args++);
- float i = *(float*)(*args++);
- float j = *(float*)(*args++);
- float k = *(float*)(*args++);
- float l = *(float*)(*args++);
- float m = *(float*)(*args++);
- float n = *(float*)(*args++);
- float o = *(float*)(*args++);
- float p = *(float*)(*args++);
- float q = *(float*)(*args++);
- long s = *(long*)(*args++);
- long t = *(long*)(*args++);
- long u = *(long*)(*args++);
- L z = *(L*)(*args++);
- float r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6;
- fprintf(out,"float f(17*float,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6);
- fflush(out);
- *(float*)retp = r;
-}}
-void d_d17l3L_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_d17l3L) { fprintf(out,"wrong data for d_d17l3L\n"); exit(1); }
- {double a = *(double*)(*args++);
- double b = *(double*)(*args++);
- double c = *(double*)(*args++);
- double d = *(double*)(*args++);
- double e = *(double*)(*args++);
- double f = *(double*)(*args++);
- double g = *(double*)(*args++);
- double h = *(double*)(*args++);
- double i = *(double*)(*args++);
- double j = *(double*)(*args++);
- double k = *(double*)(*args++);
- double l = *(double*)(*args++);
- double m = *(double*)(*args++);
- double n = *(double*)(*args++);
- double o = *(double*)(*args++);
- double p = *(double*)(*args++);
- double q = *(double*)(*args++);
- long s = *(long*)(*args++);
- long t = *(long*)(*args++);
- long u = *(long*)(*args++);
- L z = *(L*)(*args++);
- double r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6;
- fprintf(out,"double f(17*double,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6);
- fflush(out);
- *(double*)retp = r;
-}}
-void ll_l2ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&ll_l2ll) { fprintf(out,"wrong data for ll_l2ll\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long long b = *(long long *)(*args++);
- long c = *(long*)(*args++);
- long long r = (long long) (a1 + a2) + b + c;
- fprintf(out,"long long f(2*long,long long,long):(%ld,%ld,0x%lx%08lx,%ld)",a1,a2,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- *(long long *)retp = r;
-}}
-void ll_l3ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&ll_l3ll) { fprintf(out,"wrong data for ll_l3ll\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long long b = *(long long *)(*args++);
- long c = *(long*)(*args++);
- long long r = (long long) (a1 + a2 + a3) + b + c;
- fprintf(out,"long long f(3*long,long long,long):(%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- *(long long *)retp = r;
-}}
-void ll_l4ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&ll_l4ll) { fprintf(out,"wrong data for ll_l4ll\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long a4 = *(long*)(*args++);
- long long b = *(long long *)(*args++);
- long c = *(long*)(*args++);
- long long r = (long long) (a1 + a2 + a3 + a4) + b + c;
- fprintf(out,"long long f(4*long,long long,long):(%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- *(long long *)retp = r;
-}}
-void ll_l5ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&ll_l5ll) { fprintf(out,"wrong data for ll_l5ll\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long a4 = *(long*)(*args++);
- long a5 = *(long*)(*args++);
- long long b = *(long long *)(*args++);
- long c = *(long*)(*args++);
- long long r = (long long) (a1 + a2 + a3 + a4 + a5) + b + c;
- fprintf(out,"long long f(5*long,long long,long):(%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- *(long long *)retp = r;
-}}
-void ll_l6ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&ll_l6ll) { fprintf(out,"wrong data for ll_l6ll\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long a4 = *(long*)(*args++);
- long a5 = *(long*)(*args++);
- long a6 = *(long*)(*args++);
- long long b = *(long long *)(*args++);
- long c = *(long*)(*args++);
- long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6) + b + c;
- fprintf(out,"long long f(6*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- *(long long *)retp = r;
-}}
-void ll_l7ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&ll_l7ll) { fprintf(out,"wrong data for ll_l7ll\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long a4 = *(long*)(*args++);
- long a5 = *(long*)(*args++);
- long a6 = *(long*)(*args++);
- long a7 = *(long*)(*args++);
- long long b = *(long long *)(*args++);
- long c = *(long*)(*args++);
- long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c;
- fprintf(out,"long long f(7*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,a7,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- *(long long *)retp = r;
-}}
-void d_l2d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_l2d) { fprintf(out,"wrong data for d_l2d\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- double b = *(double*)(*args++);
- long c = *(long*)(*args++);
- double r = (double) (a1 + a2) + b + c;
- fprintf(out,"double f(2*long,double,long):(%ld,%ld,%g,%ld)",a1,a2,b,c);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_l3d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_l3d) { fprintf(out,"wrong data for d_l3d\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- double b = *(double*)(*args++);
- long c = *(long*)(*args++);
- double r = (double) (a1 + a2 + a3) + b + c;
- fprintf(out,"double f(3*long,double,long):(%ld,%ld,%ld,%g,%ld)",a1,a2,a3,b,c);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_l4d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_l4d) { fprintf(out,"wrong data for d_l4d\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long a4 = *(long*)(*args++);
- double b = *(double*)(*args++);
- long c = *(long*)(*args++);
- double r = (double) (a1 + a2 + a3 + a4) + b + c;
- fprintf(out,"double f(4*long,double,long):(%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,b,c);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_l5d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_l5d) { fprintf(out,"wrong data for d_l5d\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long a4 = *(long*)(*args++);
- long a5 = *(long*)(*args++);
- double b = *(double*)(*args++);
- long c = *(long*)(*args++);
- double r = (double) (a1 + a2 + a3 + a4 + a5) + b + c;
- fprintf(out,"double f(5*long,double,long):(%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,b,c);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_l6d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_l6d) { fprintf(out,"wrong data for d_l6d\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long a4 = *(long*)(*args++);
- long a5 = *(long*)(*args++);
- long a6 = *(long*)(*args++);
- double b = *(double*)(*args++);
- long c = *(long*)(*args++);
- double r = (double) (a1 + a2 + a3 + a4 + a5 + a6) + b + c;
- fprintf(out,"double f(6*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,b,c);
- fflush(out);
- *(double*)retp = r;
-}}
-void d_l7d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
-{
- if (data != (void*)&d_l7d) { fprintf(out,"wrong data for d_l7d\n"); exit(1); }
- {long a1 = *(long*)(*args++);
- long a2 = *(long*)(*args++);
- long a3 = *(long*)(*args++);
- long a4 = *(long*)(*args++);
- long a5 = *(long*)(*args++);
- long a6 = *(long*)(*args++);
- long a7 = *(long*)(*args++);
- double b = *(double*)(*args++);
- long c = *(long*)(*args++);
- double r = (double) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c;
- fprintf(out,"double f(7*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,a7,b,c);
- fflush(out);
- *(double*)retp = r;
-}}
-
-
-/*
- * The way we run these tests - first call the function directly, then
- * through vacall() - there is the danger that arguments or results seem
- * to be passed correctly, but what we are seeing are in fact the vestiges
- * (traces) or the previous call. This may seriously fake the test.
- * Avoid this by clearing the registers between the first and the second call.
- */
-long clear_traces_i (long a, long b, long c, long d, long e, long f, long g, long h,
- long i, long j, long k, long l, long m, long n, long o, long p)
-{ return 0; }
-float clear_traces_f (float a, float b, float c, float d, float e, float f, float g,
- float h, float i, float j, float k, float l, float m, float n,
- float o, float p)
-{ return 0.0; }
-double clear_traces_d (double a, double b, double c, double d, double e, double f, double g,
- double h, double i, double j, double k, double l, double m, double n,
- double o, double p)
-{ return 0.0; }
-J clear_traces_J (void)
-{ J j; j.l1 = j.l2 = 0; return j; }
-void clear_traces (void)
-{ clear_traces_i(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
- clear_traces_f(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
- clear_traces_d(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
- clear_traces_J();
-}
-
-int main (void)
-{
- void* callback_code;
- void* callback_writable;
-#define ALLOC_CALLBACK() \
- callback_writable = ffi_closure_alloc(sizeof(ffi_closure),&callback_code); \
- if (!callback_writable) abort()
-#define PREP_CALLBACK(cif,simulator,data) \
- if (ffi_prep_closure_loc(callback_writable,&(cif),simulator,data,callback_code) != FFI_OK) abort()
-#define FREE_CALLBACK() \
- ffi_closure_free(callback_writable)
-
- ffi_type_char = (char)(-1) < 0 ? ffi_type_schar : ffi_type_uchar;
- out = stdout;
-
-#if (!defined(DGTEST)) || DGTEST == 1
- /* void tests */
- v_v();
- clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_void);
- PREP_CALLBACK(cif,v_v_simulator,(void*)&v_v);
- ((void (ABI_ATTR *) (void)) callback_code) ();
- }
- FREE_CALLBACK();
-#endif
-
- /* int tests */
- { int ir;
-
-#if (!defined(DGTEST)) || DGTEST == 2
- ir = i_v();
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_sint);
- PREP_CALLBACK(cif,i_v_simulator,(void*)&i_v);
- ir = ((int (ABI_ATTR *) (void)) callback_code) ();
- }
- FREE_CALLBACK();
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 3
- ir = i_i(i1);
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
- PREP_CALLBACK(cif,i_i_simulator,(void*)&i_i);
- ir = ((int (ABI_ATTR *) (int)) callback_code) (i1);
- }
- FREE_CALLBACK();
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 4
- ir = i_i2(i1,i2);
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
- PREP_CALLBACK(cif,i_i2_simulator,(void*)&i_i2);
- ir = ((int (ABI_ATTR *) (int,int)) callback_code) (i1,i2);
- }
- FREE_CALLBACK();
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 5
- ir = i_i4(i1,i2,i3,i4);
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
- PREP_CALLBACK(cif,i_i4_simulator,(void*)&i_i4);
- ir = ((int (ABI_ATTR *) (int,int,int,int)) callback_code) (i1,i2,i3,i4);
- }
- FREE_CALLBACK();
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 6
- ir = i_i8(i1,i2,i3,i4,i5,i6,i7,i8);
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
- PREP_CALLBACK(cif,i_i8_simulator,(void*)&i_i8);
- ir = ((int (ABI_ATTR *) (int,int,int,int,int,int,int,int)) callback_code) (i1,i2,i3,i4,i5,i6,i7,i8);
- }
- FREE_CALLBACK();
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 7
- ir = i_i16(i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16);
- fprintf(out,"->%d\n",ir);
- fflush(out);
- ir = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
- PREP_CALLBACK(cif,i_i16_simulator,(void*)&i_i16);
- ir = ((int (ABI_ATTR *) (int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int)) callback_code) (i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16);
- }
- FREE_CALLBACK();
- fprintf(out,"->%d\n",ir);
- fflush(out);
-#endif
- }
-
- /* float tests */
- { float fr;
-
-#if (!defined(DGTEST)) || DGTEST == 8
- fr = f_f(f1);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f_simulator,(void*)&f_f);
- fr = ((float (ABI_ATTR *) (float)) callback_code) (f1);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 9
- fr = f_f2(f1,f2);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f2_simulator,(void*)&f_f2);
- fr = ((float (ABI_ATTR *) (float,float)) callback_code) (f1,f2);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 10
- fr = f_f4(f1,f2,f3,f4);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f4_simulator,(void*)&f_f4);
- fr = ((float (ABI_ATTR *) (float,float,float,float)) callback_code) (f1,f2,f3,f4);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 11
- fr = f_f8(f1,f2,f3,f4,f5,f6,f7,f8);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f8_simulator,(void*)&f_f8);
- fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 12
- fr = f_f16(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f16_simulator,(void*)&f_f16);
- fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 13
- fr = f_f24(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f24_simulator,(void*)&f_f24);
- fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
- }
-
- /* double tests */
- { double dr;
-
-#if (!defined(DGTEST)) || DGTEST == 14
- dr = d_d(d1);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d_simulator,(void*)&d_d);
- dr = ((double (ABI_ATTR *) (double)) callback_code) (d1);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 15
- dr = d_d2(d1,d2);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d2_simulator,(void*)&d_d2);
- dr = ((double (ABI_ATTR *) (double,double)) callback_code) (d1,d2);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 16
- dr = d_d4(d1,d2,d3,d4);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d4_simulator,(void*)&d_d4);
- dr = ((double (ABI_ATTR *) (double,double,double,double)) callback_code) (d1,d2,d3,d4);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 17
- dr = d_d8(d1,d2,d3,d4,d5,d6,d7,d8);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d8_simulator,(void*)&d_d8);
- dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 18
- dr = d_d16(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d16_simulator,(void*)&d_d16);
- dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,double)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
- }
-
- /* pointer tests */
- { void* vpr;
-
-#if (!defined(DGTEST)) || DGTEST == 19
- vpr = vp_vpdpcpsp(&uc1,&d2,str3,&I4);
- fprintf(out,"->0x%p\n",vpr);
- fflush(out);
- vpr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_pointer);
- PREP_CALLBACK(cif,vp_vpdpcpsp_simulator,(void*)&vp_vpdpcpsp);
- vpr = ((void* (ABI_ATTR *) (void*,double*,char*,Int*)) callback_code) (&uc1,&d2,str3,&I4);
- }
- FREE_CALLBACK();
- fprintf(out,"->0x%p\n",vpr);
- fflush(out);
-#endif
- }
-
- /* mixed number tests */
- { uchar ucr;
- ushort usr;
- float fr;
- double dr;
- long long llr;
-
-#if (!defined(DGTEST)) || DGTEST == 20
- ucr = uc_ucsil(uc1,us2,ui3,ul4);
- fprintf(out,"->%u\n",ucr);
- fflush(out);
- ucr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_uchar, &ffi_type_ushort, &ffi_type_uint, &ffi_type_ulong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_uchar);
- PREP_CALLBACK(cif,uc_ucsil_simulator,(void*)&uc_ucsil);
- ucr = ((uchar (ABI_ATTR *) (uchar,ushort,uint,ulong)) callback_code) (uc1,us2,ui3,ul4);
- }
- FREE_CALLBACK();
- fprintf(out,"->%u\n",ucr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 21
- dr = d_iidd(i1,i2,d3,d4);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_iidd_simulator,(void*)&d_iidd);
- dr = ((double (ABI_ATTR *) (int,int,double,double)) callback_code) (i1,i2,d3,d4);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 22
- dr = d_iiidi(i1,i2,i3,d4,i5);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_iiidi_simulator,(void*)&d_iiidi);
- dr = ((double (ABI_ATTR *) (int,int,int,double,int)) callback_code) (i1,i2,i3,d4,i5);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 23
- dr = d_idid(i1,d2,i3,d4);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_double, &ffi_type_sint, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_idid_simulator,(void*)&d_idid);
- dr = ((double (ABI_ATTR *) (int,double,int,double)) callback_code) (i1,d2,i3,d4);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 24
- dr = d_fdi(f1,d2,i3);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_fdi_simulator,(void*)&d_fdi);
- dr = ((double (ABI_ATTR *) (float,double,int)) callback_code) (f1,d2,i3);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 25
- usr = us_cdcd(c1,d2,c3,d4);
- fprintf(out,"->%u\n",usr);
- fflush(out);
- usr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_char, &ffi_type_double, &ffi_type_char, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_ushort);
- PREP_CALLBACK(cif,us_cdcd_simulator,(void*)&us_cdcd);
- usr = ((ushort (ABI_ATTR *) (char,double,char,double)) callback_code) (c1,d2,c3,d4);
- }
- FREE_CALLBACK();
- fprintf(out,"->%u\n",usr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 26
- llr = ll_iiilli(i1,i2,i3,ll1,i13);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_slonglong, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- PREP_CALLBACK(cif,ll_iiilli_simulator,(void*)&ll_iiilli);
- llr = ((long long (ABI_ATTR *) (int,int,int,long long,int)) callback_code) (i1,i2,i3,ll1,i13);
- }
- FREE_CALLBACK();
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 27
- llr = ll_flli(f13,ll1,i13);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_slonglong, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- PREP_CALLBACK(cif,ll_flli_simulator,(void*)&ll_flli);
- llr = ((long long (ABI_ATTR *) (float,long long,int)) callback_code) (f13,ll1,i13);
- }
- FREE_CALLBACK();
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 28
- fr = f_fi(f1,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_fi_simulator,(void*)&f_fi);
- fr = ((float (ABI_ATTR *) (float,int)) callback_code) (f1,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 29
- fr = f_f2i(f1,f2,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f2i_simulator,(void*)&f_f2i);
- fr = ((float (ABI_ATTR *) (float,float,int)) callback_code) (f1,f2,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 30
- fr = f_f3i(f1,f2,f3,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f3i_simulator,(void*)&f_f3i);
- fr = ((float (ABI_ATTR *) (float,float,float,int)) callback_code) (f1,f2,f3,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 31
- fr = f_f4i(f1,f2,f3,f4,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f4i_simulator,(void*)&f_f4i);
- fr = ((float (ABI_ATTR *) (float,float,float,float,int)) callback_code) (f1,f2,f3,f4,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 32
- fr = f_f7i(f1,f2,f3,f4,f5,f6,f7,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f7i_simulator,(void*)&f_f7i);
- fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,int)) callback_code) (f1,f2,f3,f4,f5,f6,f7,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 33
- fr = f_f8i(f1,f2,f3,f4,f5,f6,f7,f8,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f8i_simulator,(void*)&f_f8i);
- fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,int)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 34
- fr = f_f13i(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,i9);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f13i_simulator,(void*)&f_f13i);
- fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,int)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 35
- dr = d_di(d1,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_di_simulator,(void*)&d_di);
- dr = ((double (ABI_ATTR *) (double,int)) callback_code) (d1,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 36
- dr = d_d2i(d1,d2,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d2i_simulator,(void*)&d_d2i);
- dr = ((double (ABI_ATTR *) (double,double,int)) callback_code) (d1,d2,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 37
- dr = d_d3i(d1,d2,d3,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d3i_simulator,(void*)&d_d3i);
- dr = ((double (ABI_ATTR *) (double,double,double,int)) callback_code) (d1,d2,d3,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 38
- dr = d_d4i(d1,d2,d3,d4,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d4i_simulator,(void*)&d_d4i);
- dr = ((double (ABI_ATTR *) (double,double,double,double,int)) callback_code) (d1,d2,d3,d4,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 39
- dr = d_d7i(d1,d2,d3,d4,d5,d6,d7,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d7i_simulator,(void*)&d_d7i);
- dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 40
- dr = d_d8i(d1,d2,d3,d4,d5,d6,d7,d8,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d8i_simulator,(void*)&d_d8i);
- dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 41
- dr = d_d12i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d12i_simulator,(void*)&d_d12i);
- dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 42
- dr = d_d13i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,i9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d13i_simulator,(void*)&d_d13i);
- dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,i9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
- }
-
- /* small structure return tests */
-#if (!defined(DGTEST)) || DGTEST == 43
- {
- Size1 r = S1_v();
- fprintf(out,"->{%c}\n",r.x1);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Size1_elements[] = { &ffi_type_char, NULL };
- ffi_type ffi_type_Size1;
- ffi_type_Size1.type = FFI_TYPE_STRUCT;
- ffi_type_Size1.size = sizeof(Size1);
- ffi_type_Size1.alignment = alignof_slot(Size1);
- ffi_type_Size1.elements = ffi_type_Size1_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size1);
- PREP_CALLBACK(cif,S1_v_simulator,(void*)&S1_v);
- r = ((Size1 (ABI_ATTR *) (void)) callback_code) ();
- }
- FREE_CALLBACK();
- fprintf(out,"->{%c}\n",r.x1);
- fflush(out);
- }
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 44
- {
- Size2 r = S2_v();
- fprintf(out,"->{%c%c}\n",r.x1,r.x2);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Size2_elements[] = { &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size2;
- ffi_type_Size2.type = FFI_TYPE_STRUCT;
- ffi_type_Size2.size = sizeof(Size2);
- ffi_type_Size2.alignment = alignof_slot(Size2);
- ffi_type_Size2.elements = ffi_type_Size2_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size2);
- PREP_CALLBACK(cif,S2_v_simulator,(void*)&S2_v);
- r = ((Size2 (ABI_ATTR *) (void)) callback_code) ();
- }
- FREE_CALLBACK();
- fprintf(out,"->{%c%c}\n",r.x1,r.x2);
- fflush(out);
- }
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 45
- {
- Size3 r = S3_v();
- fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Size3_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size3;
- ffi_type_Size3.type = FFI_TYPE_STRUCT;
- ffi_type_Size3.size = sizeof(Size3);
- ffi_type_Size3.alignment = alignof_slot(Size3);
- ffi_type_Size3.elements = ffi_type_Size3_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size3);
- PREP_CALLBACK(cif,S3_v_simulator,(void*)&S3_v);
- r = ((Size3 (ABI_ATTR *) (void)) callback_code) ();
- }
- FREE_CALLBACK();
- fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3);
- fflush(out);
- }
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 46
- {
- Size4 r = S4_v();
- fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Size4_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size4;
- ffi_type_Size4.type = FFI_TYPE_STRUCT;
- ffi_type_Size4.size = sizeof(Size4);
- ffi_type_Size4.alignment = alignof_slot(Size4);
- ffi_type_Size4.elements = ffi_type_Size4_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size4);
- PREP_CALLBACK(cif,S4_v_simulator,(void*)&S4_v);
- r = ((Size4 (ABI_ATTR *) (void)) callback_code) ();
- }
- FREE_CALLBACK();
- fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4);
- fflush(out);
- }
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 47
- {
- Size7 r = S7_v();
- fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Size7_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size7;
- ffi_type_Size7.type = FFI_TYPE_STRUCT;
- ffi_type_Size7.size = sizeof(Size7);
- ffi_type_Size7.alignment = alignof_slot(Size7);
- ffi_type_Size7.elements = ffi_type_Size7_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size7);
- PREP_CALLBACK(cif,S7_v_simulator,(void*)&S7_v);
- r = ((Size7 (ABI_ATTR *) (void)) callback_code) ();
- }
- FREE_CALLBACK();
- fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7);
- fflush(out);
- }
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 48
- {
- Size8 r = S8_v();
- fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Size8_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size8;
- ffi_type_Size8.type = FFI_TYPE_STRUCT;
- ffi_type_Size8.size = sizeof(Size8);
- ffi_type_Size8.alignment = alignof_slot(Size8);
- ffi_type_Size8.elements = ffi_type_Size8_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size8);
- PREP_CALLBACK(cif,S8_v_simulator,(void*)&S8_v);
- r = ((Size8 (ABI_ATTR *) (void)) callback_code) ();
- }
- FREE_CALLBACK();
- fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8);
- fflush(out);
- }
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 49
- {
- Size12 r = S12_v();
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Size12_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size12;
- ffi_type_Size12.type = FFI_TYPE_STRUCT;
- ffi_type_Size12.size = sizeof(Size12);
- ffi_type_Size12.alignment = alignof_slot(Size12);
- ffi_type_Size12.elements = ffi_type_Size12_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size12);
- PREP_CALLBACK(cif,S12_v_simulator,(void*)&S12_v);
- r = ((Size12 (ABI_ATTR *) (void)) callback_code) ();
- }
- FREE_CALLBACK();
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12);
- fflush(out);
- }
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 50
- {
- Size15 r = S15_v();
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Size15_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size15;
- ffi_type_Size15.type = FFI_TYPE_STRUCT;
- ffi_type_Size15.size = sizeof(Size15);
- ffi_type_Size15.alignment = alignof_slot(Size15);
- ffi_type_Size15.elements = ffi_type_Size15_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size15);
- PREP_CALLBACK(cif,S15_v_simulator,(void*)&S15_v);
- r = ((Size15 (ABI_ATTR *) (void)) callback_code) ();
- }
- FREE_CALLBACK();
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15);
- fflush(out);
- }
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 51
- {
- Size16 r = S16_v();
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16);
- fflush(out);
- memset(&r,0,sizeof(r)); clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Size16_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
- ffi_type ffi_type_Size16;
- ffi_type_Size16.type = FFI_TYPE_STRUCT;
- ffi_type_Size16.size = sizeof(Size16);
- ffi_type_Size16.alignment = alignof_slot(Size16);
- ffi_type_Size16.elements = ffi_type_Size16_elements;
- ffi_cif cif;
- FFI_PREP_CIF_NOARGS(cif,ffi_type_Size16);
- PREP_CALLBACK(cif,S16_v_simulator,(void*)&S16_v);
- r = ((Size16 (ABI_ATTR *) (void)) callback_code) ();
- }
- FREE_CALLBACK();
- fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16);
- fflush(out);
- }
-#endif
-
-
- /* structure tests */
- { Int Ir;
- Char Cr;
- Float Fr;
- Double Dr;
- J Jr;
-#ifndef SKIP_EXTRA_STRUCTS
- T Tr;
- X Xr;
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 52
- Ir = I_III(I1,I2,I3);
- fprintf(out,"->{%d}\n",Ir.x);
- fflush(out);
- Ir.x = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Int_elements[] = { &ffi_type_sint, NULL };
- ffi_type ffi_type_Int;
- ffi_type_Int.type = FFI_TYPE_STRUCT;
- ffi_type_Int.size = sizeof(Int);
- ffi_type_Int.alignment = alignof_slot(Int);
- ffi_type_Int.elements = ffi_type_Int_elements;
- ffi_type* argtypes[] = { &ffi_type_Int, &ffi_type_Int, &ffi_type_Int };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_Int);
- PREP_CALLBACK(cif,I_III_simulator,(void*)&I_III);
- Ir = ((Int (ABI_ATTR *) (Int,Int,Int)) callback_code) (I1,I2,I3);
- }
- FREE_CALLBACK();
- fprintf(out,"->{%d}\n",Ir.x);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 53
- Cr = C_CdC(C1,d2,C3);
- fprintf(out,"->{'%c'}\n",Cr.x);
- fflush(out);
- Cr.x = '\0'; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Char_elements[] = { &ffi_type_char, NULL };
- ffi_type ffi_type_Char;
- ffi_type_Char.type = FFI_TYPE_STRUCT;
- ffi_type_Char.size = sizeof(Char);
- ffi_type_Char.alignment = alignof_slot(Char);
- ffi_type_Char.elements = ffi_type_Char_elements;
- ffi_type* argtypes[] = { &ffi_type_Char, &ffi_type_double, &ffi_type_Char };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_Char);
- PREP_CALLBACK(cif,C_CdC_simulator,(void*)&C_CdC);
- Cr = ((Char (ABI_ATTR *) (Char,double,Char)) callback_code) (C1,d2,C3);
- }
- FREE_CALLBACK();
- fprintf(out,"->{'%c'}\n",Cr.x);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 54
- Fr = F_Ffd(F1,f2,d3);
- fprintf(out,"->{%g}\n",Fr.x);
- fflush(out);
- Fr.x = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Float_elements[] = { &ffi_type_float, NULL };
- ffi_type ffi_type_Float;
- ffi_type_Float.type = FFI_TYPE_STRUCT;
- ffi_type_Float.size = sizeof(Float);
- ffi_type_Float.alignment = alignof_slot(Float);
- ffi_type_Float.elements = ffi_type_Float_elements;
- ffi_type* argtypes[] = { &ffi_type_Float, &ffi_type_float, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_Float);
- PREP_CALLBACK(cif,F_Ffd_simulator,(void*)&F_Ffd);
- Fr = ((Float (ABI_ATTR *) (Float,float,double)) callback_code) (F1,f2,d3);
- }
- FREE_CALLBACK();
- fprintf(out,"->{%g}\n",Fr.x);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 55
- Dr = D_fDd(f1,D2,d3);
- fprintf(out,"->{%g}\n",Dr.x);
- fflush(out);
- Dr.x = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL };
- ffi_type ffi_type_Double;
- ffi_type_Double.type = FFI_TYPE_STRUCT;
- ffi_type_Double.size = sizeof(Double);
- ffi_type_Double.alignment = alignof_slot(Double);
- ffi_type_Double.elements = ffi_type_Double_elements;
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_Double, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_Double);
- PREP_CALLBACK(cif,D_fDd_simulator,(void*)&D_fDd);
- Dr = ((Double (ABI_ATTR *) (float,Double,double)) callback_code) (f1,D2,d3);
- }
- FREE_CALLBACK();
- fprintf(out,"->{%g}\n",Dr.x);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 56
- Dr = D_Dfd(D1,f2,d3);
- fprintf(out,"->{%g}\n",Dr.x);
- fflush(out);
- Dr.x = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL };
- ffi_type ffi_type_Double;
- ffi_type_Double.type = FFI_TYPE_STRUCT;
- ffi_type_Double.size = sizeof(Double);
- ffi_type_Double.alignment = alignof_slot(Double);
- ffi_type_Double.elements = ffi_type_Double_elements;
- ffi_type* argtypes[] = { &ffi_type_Double, &ffi_type_float, &ffi_type_double };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_Double);
- PREP_CALLBACK(cif,D_Dfd_simulator,(void*)&D_Dfd);
- Dr = ((Double (ABI_ATTR *) (Double,float,double)) callback_code) (D1,f2,d3);
- }
- FREE_CALLBACK();
- fprintf(out,"->{%g}\n",Dr.x);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 57
- Jr = J_JiJ(J1,i2,J2);
- fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2);
- fflush(out);
- Jr.l1 = Jr.l2 = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_J_elements[] = { &ffi_type_slong, &ffi_type_slong, NULL };
- ffi_type ffi_type_J;
- ffi_type_J.type = FFI_TYPE_STRUCT;
- ffi_type_J.size = sizeof(J);
- ffi_type_J.alignment = alignof_slot(J);
- ffi_type_J.elements = ffi_type_J_elements;
- ffi_type* argtypes[] = { &ffi_type_J, &ffi_type_sint, &ffi_type_J };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_J);
- PREP_CALLBACK(cif,J_JiJ_simulator,(void*)&J_JiJ);
- Jr = ((J (ABI_ATTR *) (J,int,J)) callback_code) (J1,i2,J2);
- }
- FREE_CALLBACK();
- fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2);
- fflush(out);
-#endif
-
-#ifndef SKIP_EXTRA_STRUCTS
-#if (!defined(DGTEST)) || DGTEST == 58
- Tr = T_TcT(T1,' ',T2);
- fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]);
- fflush(out);
- Tr.c[0] = Tr.c[1] = Tr.c[2] = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_T_elements[] = { ??, NULL };
- ffi_type ffi_type_T;
- ffi_type_T.type = FFI_TYPE_STRUCT;
- ffi_type_T.size = sizeof(T);
- ffi_type_T.alignment = alignof_slot(T);
- ffi_type_T.elements = ffi_type_T_elements;
- ffi_type* argtypes[] = { &ffi_type_T, &ffi_type_char, &ffi_type_T };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_T);
- PREP_CALLBACK(cif,T_TcT_simulator,(void*)&T_TcT);
- Tr = ((T (ABI_ATTR *) (T,char,T)) callback_code) (T1,' ',T2);
- }
- FREE_CALLBACK();
- fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]);
- fflush(out);
-#endif
-
-#ifndef SKIP_X
-#if (!defined(DGTEST)) || DGTEST == 59
- Xr = X_BcdB(B1,c2,d3,B2);
- fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1);
- fflush(out);
- Xr.c[0]=Xr.c1='\0'; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* ffi_type_X_elements[] = { ??, NULL };
- ffi_type ffi_type_X;
- ffi_type_X.type = FFI_TYPE_STRUCT;
- ffi_type_X.size = sizeof(X);
- ffi_type_X.alignment = alignof_slot(X);
- ffi_type_X.elements = ffi_type_X_elements;
- ffi_type* argtypes[] = { &ffi_type_X, &ffi_type_char, &ffi_type_double, &ffi_type_X };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_X);
- PREP_CALLBACK(cif,X_BcdB_simulator,(void*)&X_BcdB);
- Xr = ((X (ABI_ATTR *) (B,char,double,B)) callback_code) (B1,c2,d3,B2);
- }
- FREE_CALLBACK();
- fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1);
- fflush(out);
-#endif
-#endif
-#endif
- }
-
-
- /* gpargs boundary tests */
- {
- ffi_type* ffi_type_K_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL };
- ffi_type ffi_type_K;
- ffi_type* ffi_type_L_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL };
- ffi_type ffi_type_L;
- long lr;
- long long llr;
- float fr;
- double dr;
-
- ffi_type_K.type = FFI_TYPE_STRUCT;
- ffi_type_K.size = sizeof(K);
- ffi_type_K.alignment = alignof_slot(K);
- ffi_type_K.elements = ffi_type_K_elements;
-
- ffi_type_L.type = FFI_TYPE_STRUCT;
- ffi_type_L.size = sizeof(L);
- ffi_type_L.alignment = alignof_slot(L);
- ffi_type_L.elements = ffi_type_L_elements;
-
-#if (!defined(DGTEST)) || DGTEST == 60
- lr = l_l0K(K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- PREP_CALLBACK(cif,l_l0K_simulator,(void*)l_l0K);
- lr = ((long (ABI_ATTR *) (K,long)) callback_code) (K1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 61
- lr = l_l1K(l1,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- PREP_CALLBACK(cif,l_l1K_simulator,(void*)l_l1K);
- lr = ((long (ABI_ATTR *) (long,K,long)) callback_code) (l1,K1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 62
- lr = l_l2K(l1,l2,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- PREP_CALLBACK(cif,l_l2K_simulator,(void*)l_l2K);
- lr = ((long (ABI_ATTR *) (long,long,K,long)) callback_code) (l1,l2,K1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 63
- lr = l_l3K(l1,l2,l3,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- PREP_CALLBACK(cif,l_l3K_simulator,(void*)l_l3K);
- lr = ((long (ABI_ATTR *) (long,long,long,K,long)) callback_code) (l1,l2,l3,K1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 64
- lr = l_l4K(l1,l2,l3,l4,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- PREP_CALLBACK(cif,l_l4K_simulator,(void*)l_l4K);
- lr = ((long (ABI_ATTR *) (long,long,long,long,K,long)) callback_code) (l1,l2,l3,l4,K1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 65
- lr = l_l5K(l1,l2,l3,l4,l5,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- PREP_CALLBACK(cif,l_l5K_simulator,(void*)l_l5K);
- lr = ((long (ABI_ATTR *) (long,long,long,long,long,K,long)) callback_code) (l1,l2,l3,l4,l5,K1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 66
- lr = l_l6K(l1,l2,l3,l4,l5,l6,K1,l9);
- fprintf(out,"->%ld\n",lr);
- fflush(out);
- lr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
- PREP_CALLBACK(cif,l_l6K_simulator,(void*)l_l6K);
- lr = ((long (ABI_ATTR *) (long,long,long,long,long,long,K,long)) callback_code) (l1,l2,l3,l4,l5,l6,K1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%ld\n",lr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 67
- fr = f_f17l3L(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,l6,l7,l8,L1);
- fprintf(out,"->%g\n",fr);
- fflush(out);
- fr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_float);
- PREP_CALLBACK(cif,f_f17l3L_simulator,(void*)&f_f17l3L);
- fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,long,long,long,L)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,l6,l7,l8,L1);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",fr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 68
- dr = d_d17l3L(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17,l6,l7,l8,L1);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_d17l3L_simulator,(void*)&d_d17l3L);
- dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,long,long,long,L)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17,l6,l7,l8,L1);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 69
- llr = ll_l2ll(l1,l2,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- PREP_CALLBACK(cif,ll_l2ll_simulator,(void*)ll_l2ll);
- llr = ((long long (ABI_ATTR *) (long,long,long long,long)) callback_code) (l1,l2,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 70
- llr = ll_l3ll(l1,l2,l3,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- PREP_CALLBACK(cif,ll_l3ll_simulator,(void*)ll_l3ll);
- llr = ((long long (ABI_ATTR *) (long,long,long,long long,long)) callback_code) (l1,l2,l3,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 71
- llr = ll_l4ll(l1,l2,l3,l4,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- PREP_CALLBACK(cif,ll_l4ll_simulator,(void*)ll_l4ll);
- llr = ((long long (ABI_ATTR *) (long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 72
- llr = ll_l5ll(l1,l2,l3,l4,l5,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- PREP_CALLBACK(cif,ll_l5ll_simulator,(void*)ll_l5ll);
- llr = ((long long (ABI_ATTR *) (long,long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,l5,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 73
- llr = ll_l6ll(l1,l2,l3,l4,l5,l6,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- PREP_CALLBACK(cif,ll_l6ll_simulator,(void*)ll_l6ll);
- llr = ((long long (ABI_ATTR *) (long,long,long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,l5,l6,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 74
- llr = ll_l7ll(l1,l2,l3,l4,l5,l6,l7,ll1,l9);
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
- llr = 0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
- PREP_CALLBACK(cif,ll_l7ll_simulator,(void*)ll_l7ll);
- llr = ((long long (ABI_ATTR *) (long,long,long,long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,l5,l6,l7,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 75
- dr = d_l2d(l1,l2,ll1,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_l2d_simulator,(void*)d_l2d);
- dr = ((double (ABI_ATTR *) (long,long,double,long)) callback_code) (l1,l2,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 76
- dr = d_l3d(l1,l2,l3,ll1,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_l3d_simulator,(void*)d_l3d);
- dr = ((double (ABI_ATTR *) (long,long,long,double,long)) callback_code) (l1,l2,l3,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 77
- dr = d_l4d(l1,l2,l3,l4,ll1,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_l4d_simulator,(void*)d_l4d);
- dr = ((double (ABI_ATTR *) (long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 78
- dr = d_l5d(l1,l2,l3,l4,l5,ll1,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_l5d_simulator,(void*)d_l5d);
- dr = ((double (ABI_ATTR *) (long,long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,l5,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 79
- dr = d_l6d(l1,l2,l3,l4,l5,l6,ll1,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_l6d_simulator,(void*)d_l6d);
- dr = ((double (ABI_ATTR *) (long,long,long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,l5,l6,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
-#if (!defined(DGTEST)) || DGTEST == 80
- dr = d_l7d(l1,l2,l3,l4,l5,l6,l7,ll1,l9);
- fprintf(out,"->%g\n",dr);
- fflush(out);
- dr = 0.0; clear_traces();
- ALLOC_CALLBACK();
- {
- ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
- ffi_cif cif;
- FFI_PREP_CIF(cif,argtypes,ffi_type_double);
- PREP_CALLBACK(cif,d_l7d_simulator,(void*)d_l7d);
- dr = ((double (ABI_ATTR *) (long,long,long,long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,l5,l6,l7,ll1,l9);
- }
- FREE_CALLBACK();
- fprintf(out,"->%g\n",dr);
- fflush(out);
-#endif
-
- }
-
- exit(0);
-}
-
+/*
+ * Copyright 1993 Bill Triggs <Bill.Triggs@inrialpes.fr>
+ * Copyright 1995-2017 Bruno Haible <bruno@clisp.org>
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ */
+
+/* { dg-do run } */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ffi.h>
+#include "alignof.h"
+#include <stdarg.h>
+
+/* libffi testsuite local changes -------------------------------- */
+#ifdef DGTEST
+/* Redefine exit(1) as a test failure */
+#define exit(V) (void)((V) ? (abort(), 1) : exit(0))
+int count = 0;
+char rbuf1[2048];
+char rbuf2[2048];
+int _fprintf(FILE *stream, const char *format, ...)
+{
+ va_list args;
+ va_start(args, format);
+
+ switch (count++)
+ {
+ case 0:
+ case 1:
+ vsprintf(&rbuf1[strlen(rbuf1)], format, args);
+ break;
+ case 2:
+ printf("%s", rbuf1);
+ vsprintf(rbuf2, format, args);
+ break;
+ case 3:
+ vsprintf(&rbuf2[strlen(rbuf2)], format, args);
+ printf("%s", rbuf2);
+ if (strcmp (rbuf1, rbuf2)) abort();
+ break;
+ }
+
+ va_end(args);
+
+ return 0;
+}
+#define fprintf _fprintf
+#endif
+/* --------------------------------------------------------------- */
+
+#include "testcases.c"
+
+#ifndef ABI_NUM
+#define ABI_NUM FFI_DEFAULT_ABI
+#endif
+
+/* Definitions that ought to be part of libffi. */
+static ffi_type ffi_type_char;
+#define ffi_type_slonglong ffi_type_sint64
+#define ffi_type_ulonglong ffi_type_uint64
+
+/* libffi does not support arrays inside structs. */
+#define SKIP_EXTRA_STRUCTS
+
+#define FFI_PREP_CIF(cif,argtypes,rettype) \
+ if (ffi_prep_cif(&(cif),ABI_NUM,sizeof(argtypes)/sizeof(argtypes[0]),&rettype,argtypes) != FFI_OK) abort()
+#define FFI_PREP_CIF_NOARGS(cif,rettype) \
+ if (ffi_prep_cif(&(cif),ABI_NUM,0,&rettype,NULL) != FFI_OK) abort()
+
+#if defined(__sparc__) && defined(__sun) && defined(__SUNPRO_C) /* SUNWspro cc */
+/* SunPRO cc miscompiles the simulator function for X_BcdB: d.i[1] is
+ * temporarily stored in %l2 and put onto the stack from %l2, but in between
+ * the copy of X has used %l2 as a counter without saving and restoring its
+ * value.
+ */
+#define SKIP_X
+#endif
+#if defined(__mipsn32__) && !defined(__GNUC__)
+/* The X test crashes for an unknown reason. */
+#define SKIP_X
+#endif
+
+
+/* These functions simulate the behaviour of the functions defined in testcases.c. */
+
+/* void tests */
+void v_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&v_v) { fprintf(out,"wrong data for v_v\n"); exit(1); }
+ fprintf(out,"void f(void):\n");
+ fflush(out);
+}
+
+/* int tests */
+void i_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&i_v) { fprintf(out,"wrong data for i_v\n"); exit(1); }
+ {int r=99;
+ fprintf(out,"int f(void):");
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+void i_i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&i_i) { fprintf(out,"wrong data for i_i\n"); exit(1); }
+ int a = *(int*)(*args++);
+ int r=a+1;
+ fprintf(out,"int f(int):(%d)",a);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}
+void i_i2_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&i_i2) { fprintf(out,"wrong data for i_i2\n"); exit(1); }
+ {int a = *(int*)(*args++);
+ int b = *(int*)(*args++);
+ int r=a+b;
+ fprintf(out,"int f(2*int):(%d,%d)",a,b);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+void i_i4_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&i_i4) { fprintf(out,"wrong data for i_i4\n"); exit(1); }
+ {int a = *(int*)(*args++);
+ int b = *(int*)(*args++);
+ int c = *(int*)(*args++);
+ int d = *(int*)(*args++);
+ int r=a+b+c+d;
+ fprintf(out,"int f(4*int):(%d,%d,%d,%d)",a,b,c,d);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+void i_i8_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&i_i8) { fprintf(out,"wrong data for i_i8\n"); exit(1); }
+ {int a = *(int*)(*args++);
+ int b = *(int*)(*args++);
+ int c = *(int*)(*args++);
+ int d = *(int*)(*args++);
+ int e = *(int*)(*args++);
+ int f = *(int*)(*args++);
+ int g = *(int*)(*args++);
+ int h = *(int*)(*args++);
+ int r=a+b+c+d+e+f+g+h;
+ fprintf(out,"int f(8*int):(%d,%d,%d,%d,%d,%d,%d,%d)",a,b,c,d,e,f,g,h);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+void i_i16_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&i_i16) { fprintf(out,"wrong data for i_i16\n"); exit(1); }
+ {int a = *(int*)(*args++);
+ int b = *(int*)(*args++);
+ int c = *(int*)(*args++);
+ int d = *(int*)(*args++);
+ int e = *(int*)(*args++);
+ int f = *(int*)(*args++);
+ int g = *(int*)(*args++);
+ int h = *(int*)(*args++);
+ int i = *(int*)(*args++);
+ int j = *(int*)(*args++);
+ int k = *(int*)(*args++);
+ int l = *(int*)(*args++);
+ int m = *(int*)(*args++);
+ int n = *(int*)(*args++);
+ int o = *(int*)(*args++);
+ int p = *(int*)(*args++);
+ int r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
+ fprintf(out,"int f(16*int):(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
+ a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+
+/* float tests */
+void f_f_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f) { fprintf(out,"wrong data for f_f\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float r=a+1.0;
+ fprintf(out,"float f(float):(%g)",a);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f2_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f2) { fprintf(out,"wrong data for f_f2\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float r=a+b;
+ fprintf(out,"float f(2*float):(%g,%g)",a,b);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f4_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f4) { fprintf(out,"wrong data for f_f4\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float c = *(float*)(*args++);
+ float d = *(float*)(*args++);
+ float r=a+b+c+d;
+ fprintf(out,"float f(4*float):(%g,%g,%g,%g)",a,b,c,d);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f8_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f8) { fprintf(out,"wrong data for f_f8\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float c = *(float*)(*args++);
+ float d = *(float*)(*args++);
+ float e = *(float*)(*args++);
+ float f = *(float*)(*args++);
+ float g = *(float*)(*args++);
+ float h = *(float*)(*args++);
+ float r=a+b+c+d+e+f+g+h;
+ fprintf(out,"float f(8*float):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f16_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f16) { fprintf(out,"wrong data for f_f16\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float c = *(float*)(*args++);
+ float d = *(float*)(*args++);
+ float e = *(float*)(*args++);
+ float f = *(float*)(*args++);
+ float g = *(float*)(*args++);
+ float h = *(float*)(*args++);
+ float i = *(float*)(*args++);
+ float j = *(float*)(*args++);
+ float k = *(float*)(*args++);
+ float l = *(float*)(*args++);
+ float m = *(float*)(*args++);
+ float n = *(float*)(*args++);
+ float o = *(float*)(*args++);
+ float p = *(float*)(*args++);
+ float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
+ fprintf(out,"float f(16*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f24_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f24) { fprintf(out,"wrong data for f_f24\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float c = *(float*)(*args++);
+ float d = *(float*)(*args++);
+ float e = *(float*)(*args++);
+ float f = *(float*)(*args++);
+ float g = *(float*)(*args++);
+ float h = *(float*)(*args++);
+ float i = *(float*)(*args++);
+ float j = *(float*)(*args++);
+ float k = *(float*)(*args++);
+ float l = *(float*)(*args++);
+ float m = *(float*)(*args++);
+ float n = *(float*)(*args++);
+ float o = *(float*)(*args++);
+ float p = *(float*)(*args++);
+ float q = *(float*)(*args++);
+ float s = *(float*)(*args++);
+ float t = *(float*)(*args++);
+ float u = *(float*)(*args++);
+ float v = *(float*)(*args++);
+ float w = *(float*)(*args++);
+ float x = *(float*)(*args++);
+ float y = *(float*)(*args++);
+ float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+v+w+x+y;
+ fprintf(out,"float f(24*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,v,w,x,y);
+ fflush(out);
+ *(float*)retp = r;
+}}
+
+/* double tests */
+void d_d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d) { fprintf(out,"wrong data for d_d\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double r=a+1.0;
+ fprintf(out,"double f(double):(%g)",a);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_d2_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d2) { fprintf(out,"wrong data for d_d2\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ double r=a+b;
+ fprintf(out,"double f(2*double):(%g,%g)",a,b);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_d4_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d4) { fprintf(out,"wrong data for d_d4\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ double c = *(double*)(*args++);
+ double d = *(double*)(*args++);
+ double r=a+b+c+d;
+ fprintf(out,"double f(4*double):(%g,%g,%g,%g)",a,b,c,d);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_d8_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d8) { fprintf(out,"wrong data for d_d8\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ double c = *(double*)(*args++);
+ double d = *(double*)(*args++);
+ double e = *(double*)(*args++);
+ double f = *(double*)(*args++);
+ double g = *(double*)(*args++);
+ double h = *(double*)(*args++);
+ double r=a+b+c+d+e+f+g+h;
+ fprintf(out,"double f(8*double):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_d16_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d16) { fprintf(out,"wrong data for d_d16\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ double c = *(double*)(*args++);
+ double d = *(double*)(*args++);
+ double e = *(double*)(*args++);
+ double f = *(double*)(*args++);
+ double g = *(double*)(*args++);
+ double h = *(double*)(*args++);
+ double i = *(double*)(*args++);
+ double j = *(double*)(*args++);
+ double k = *(double*)(*args++);
+ double l = *(double*)(*args++);
+ double m = *(double*)(*args++);
+ double n = *(double*)(*args++);
+ double o = *(double*)(*args++);
+ double p = *(double*)(*args++);
+ double r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
+ fprintf(out,"double f(16*double):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
+ fflush(out);
+ *(double*)retp = r;
+}}
+
+/* pointer tests */
+void vp_vpdpcpsp_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&vp_vpdpcpsp) { fprintf(out,"wrong data for vp_vpdpcpsp\n"); exit(1); }
+ {void* a = *(void* *)(*args++);
+ double* b = *(double* *)(*args++);
+ char* c = *(char* *)(*args++);
+ Int* d = *(Int* *)(*args++);
+ void* ret = (char*)b + 1;
+ fprintf(out,"void* f(void*,double*,char*,Int*):(0x%p,0x%p,0x%p,0x%p)",a,b,c,d);
+ fflush(out);
+ *(void* *)retp = ret;
+}}
+
+/* mixed number tests */
+void uc_ucsil_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&uc_ucsil) { fprintf(out,"wrong data for uc_ucsil\n"); exit(1); }
+ {uchar a = *(unsigned char *)(*args++);
+ ushort b = *(unsigned short *)(*args++);
+ uint c = *(unsigned int *)(*args++);
+ ulong d = *(unsigned long *)(*args++);
+ uchar r = (uchar)-1;
+ fprintf(out,"uchar f(uchar,ushort,uint,ulong):(%u,%u,%u,%lu)",a,b,c,d);
+ fflush(out);
+ *(ffi_arg *)retp = r;
+}}
+void d_iidd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_iidd) { fprintf(out,"wrong data for d_iidd\n"); exit(1); }
+ {int a = *(int*)(*args++);
+ int b = *(int*)(*args++);
+ double c = *(double*)(*args++);
+ double d = *(double*)(*args++);
+ double r=a+b+c+d;
+ fprintf(out,"double f(int,int,double,double):(%d,%d,%g,%g)",a,b,c,d);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_iiidi_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_iiidi) { fprintf(out,"wrong data for d_iiidi\n"); exit(1); }
+ {int a = *(int*)(*args++);
+ int b = *(int*)(*args++);
+ int c = *(int*)(*args++);
+ double d = *(double*)(*args++);
+ int e = *(int*)(*args++);
+ double r=a+b+c+d+e;
+ fprintf(out,"double f(int,int,int,double,int):(%d,%d,%d,%g,%d)",a,b,c,d,e);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_idid_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_idid) { fprintf(out,"wrong data for d_idid\n"); exit(1); }
+ {int a = *(int*)(*args++);
+ double b = *(double*)(*args++);
+ int c = *(int*)(*args++);
+ double d = *(double*)(*args++);
+ double r=a+b+c+d;
+ fprintf(out,"double f(int,double,int,double):(%d,%g,%d,%g)",a,b,c,d);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_fdi_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_fdi) { fprintf(out,"wrong data for d_fdi\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ double b = *(double*)(*args++);
+ int c = *(int*)(*args++);
+ double r=a+b+c;
+ fprintf(out,"double f(float,double,int):(%g,%g,%d)",a,b,c);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void us_cdcd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&us_cdcd) { fprintf(out,"wrong data for us_cdcd\n"); exit(1); }
+ {char a = *(char*)(*args++);
+ double b = *(double*)(*args++);
+ char c = *(char*)(*args++);
+ double d = *(double*)(*args++);
+ ushort r = (ushort)(a + b + c + d);
+ fprintf(out,"ushort f(char,double,char,double):('%c',%g,'%c',%g)",a,b,c,d);
+ fflush(out);
+ *(ffi_arg *)retp = r;
+}}
+void ll_iiilli_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&ll_iiilli) { fprintf(out,"wrong data for ll_iiilli\n"); exit(1); }
+ {int a = *(int*)(*args++);
+ int b = *(int*)(*args++);
+ int c = *(int*)(*args++);
+ long long d = *(long long *)(*args++);
+ int e = *(int*)(*args++);
+ long long r = (long long)(int)a + (long long)(int)b + (long long)(int)c + d + (long long)e;
+ fprintf(out,"long long f(int,int,int,long long,int):(%d,%d,%d,0x%lx%08lx,%d)",a,b,c,(long)(d>>32),(long)(d&0xffffffff),e);
+ fflush(out);
+ *(long long *)retp = r;
+}}
+void ll_flli_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&ll_flli) { fprintf(out,"wrong data for ll_flli\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ long long b = *(long long *)(*args++);
+ int c = *(int*)(*args++);
+ long long r = (long long)(int)a + b + (long long)c;
+ fprintf(out,"long long f(float,long long,int):(%g,0x%lx%08lx,0x%lx)",a,(long)(b>>32),(long)(b&0xffffffff),(long)c);
+ fflush(out);
+ *(long long *)retp = r;
+}}
+void f_fi_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_fi) { fprintf(out,"wrong data for f_fi\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ int z = *(int*)(*args++);
+ float r=a+z;
+ fprintf(out,"float f(float,int):(%g,%d)",a,z);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f2i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f2i) { fprintf(out,"wrong data for f_f2i\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ int z = *(int*)(*args++);
+ float r=a+b+z;
+ fprintf(out,"float f(2*float,int):(%g,%g,%d)",a,b,z);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f3i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f3i) { fprintf(out,"wrong data for f_f3i\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float c = *(float*)(*args++);
+ int z = *(int*)(*args++);
+ float r=a+b+c+z;
+ fprintf(out,"float f(3*float,int):(%g,%g,%g,%d)",a,b,c,z);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f4i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f4i) { fprintf(out,"wrong data for f_f4i\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float c = *(float*)(*args++);
+ float d = *(float*)(*args++);
+ int z = *(int*)(*args++);
+ float r=a+b+c+d+z;
+ fprintf(out,"float f(4*float,int):(%g,%g,%g,%g,%d)",a,b,c,d,z);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f7i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f7i) { fprintf(out,"wrong data for f_f7i\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float c = *(float*)(*args++);
+ float d = *(float*)(*args++);
+ float e = *(float*)(*args++);
+ float f = *(float*)(*args++);
+ float g = *(float*)(*args++);
+ int z = *(int*)(*args++);
+ float r=a+b+c+d+e+f+g+z;
+ fprintf(out,"float f(7*float,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f8i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f8i) { fprintf(out,"wrong data for f_f8i\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float c = *(float*)(*args++);
+ float d = *(float*)(*args++);
+ float e = *(float*)(*args++);
+ float f = *(float*)(*args++);
+ float g = *(float*)(*args++);
+ float h = *(float*)(*args++);
+ int z = *(int*)(*args++);
+ float r=a+b+c+d+e+f+g+h+z;
+ fprintf(out,"float f(8*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f12i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f12i) { fprintf(out,"wrong data for f_f12i\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float c = *(float*)(*args++);
+ float d = *(float*)(*args++);
+ float e = *(float*)(*args++);
+ float f = *(float*)(*args++);
+ float g = *(float*)(*args++);
+ float h = *(float*)(*args++);
+ float i = *(float*)(*args++);
+ float j = *(float*)(*args++);
+ float k = *(float*)(*args++);
+ float l = *(float*)(*args++);
+ int z = *(int*)(*args++);
+ float r=a+b+c+d+e+f+g+h+i+j+k+l+z;
+ fprintf(out,"float f(12*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void f_f13i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f13i) { fprintf(out,"wrong data for f_f13i\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float c = *(float*)(*args++);
+ float d = *(float*)(*args++);
+ float e = *(float*)(*args++);
+ float f = *(float*)(*args++);
+ float g = *(float*)(*args++);
+ float h = *(float*)(*args++);
+ float i = *(float*)(*args++);
+ float j = *(float*)(*args++);
+ float k = *(float*)(*args++);
+ float l = *(float*)(*args++);
+ float m = *(float*)(*args++);
+ int z = *(int*)(*args++);
+ float r=a+b+c+d+e+f+g+h+i+j+k+l+m+z;
+ fprintf(out,"float f(13*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void d_di_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_di) { fprintf(out,"wrong data for d_di\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ int z = *(int*)(*args++);
+ double r=a+z;
+ fprintf(out,"double f(double,int):(%g,%d)",a,z);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_d2i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d2i) { fprintf(out,"wrong data for d_d2i\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ int z = *(int*)(*args++);
+ double r=a+b+z;
+ fprintf(out,"double f(2*double,int):(%g,%g,%d)",a,b,z);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_d3i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d3i) { fprintf(out,"wrong data for d_d3i\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ double c = *(double*)(*args++);
+ int z = *(int*)(*args++);
+ double r=a+b+c+z;
+ fprintf(out,"double f(3*double,int):(%g,%g,%g,%d)",a,b,c,z);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_d4i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d4i) { fprintf(out,"wrong data for d_d4i\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ double c = *(double*)(*args++);
+ double d = *(double*)(*args++);
+ int z = *(int*)(*args++);
+ double r=a+b+c+d+z;
+ fprintf(out,"double f(4*double,int):(%g,%g,%g,%g,%d)",a,b,c,d,z);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_d7i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d7i) { fprintf(out,"wrong data for d_d7i\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ double c = *(double*)(*args++);
+ double d = *(double*)(*args++);
+ double e = *(double*)(*args++);
+ double f = *(double*)(*args++);
+ double g = *(double*)(*args++);
+ int z = *(int*)(*args++);
+ double r=a+b+c+d+e+f+g+z;
+ fprintf(out,"double f(7*double,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_d8i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d8i) { fprintf(out,"wrong data for d_d8i\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ double c = *(double*)(*args++);
+ double d = *(double*)(*args++);
+ double e = *(double*)(*args++);
+ double f = *(double*)(*args++);
+ double g = *(double*)(*args++);
+ double h = *(double*)(*args++);
+ int z = *(int*)(*args++);
+ double r=a+b+c+d+e+f+g+h+z;
+ fprintf(out,"double f(8*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_d12i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d12i) { fprintf(out,"wrong data for d_d12i\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ double c = *(double*)(*args++);
+ double d = *(double*)(*args++);
+ double e = *(double*)(*args++);
+ double f = *(double*)(*args++);
+ double g = *(double*)(*args++);
+ double h = *(double*)(*args++);
+ double i = *(double*)(*args++);
+ double j = *(double*)(*args++);
+ double k = *(double*)(*args++);
+ double l = *(double*)(*args++);
+ int z = *(int*)(*args++);
+ double r=a+b+c+d+e+f+g+h+i+j+k+l+z;
+ fprintf(out,"double f(12*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_d13i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d13i) { fprintf(out,"wrong data for d_d13i\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ double c = *(double*)(*args++);
+ double d = *(double*)(*args++);
+ double e = *(double*)(*args++);
+ double f = *(double*)(*args++);
+ double g = *(double*)(*args++);
+ double h = *(double*)(*args++);
+ double i = *(double*)(*args++);
+ double j = *(double*)(*args++);
+ double k = *(double*)(*args++);
+ double l = *(double*)(*args++);
+ double m = *(double*)(*args++);
+ int z = *(int*)(*args++);
+ double r=a+b+c+d+e+f+g+h+i+j+k+l+m+z;
+ fprintf(out,"double f(13*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z);
+ fflush(out);
+ *(double*)retp = r;
+}}
+
+/* small structure return tests */
+void S1_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&S1_v) { fprintf(out,"wrong data for S1_v\n"); exit(1); }
+ {Size1 r = Size1_1;
+ fprintf(out,"Size1 f(void):");
+ fflush(out);
+ *(Size1*)retp = r;
+}}
+void S2_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&S2_v) { fprintf(out,"wrong data for S2_v\n"); exit(1); }
+ {Size2 r = Size2_1;
+ fprintf(out,"Size2 f(void):");
+ fflush(out);
+ *(Size2*)retp = r;
+}}
+void S3_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&S3_v) { fprintf(out,"wrong data for S3_v\n"); exit(1); }
+ {Size3 r = Size3_1;
+ fprintf(out,"Size3 f(void):");
+ fflush(out);
+ *(Size3*)retp = r;
+}}
+void S4_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&S4_v) { fprintf(out,"wrong data for S4_v\n"); exit(1); }
+ {Size4 r = Size4_1;
+ fprintf(out,"Size4 f(void):");
+ fflush(out);
+ *(Size4*)retp = r;
+}}
+void S7_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&S7_v) { fprintf(out,"wrong data for S7_v\n"); exit(1); }
+ {Size7 r = Size7_1;
+ fprintf(out,"Size7 f(void):");
+ fflush(out);
+ *(Size7*)retp = r;
+}}
+void S8_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&S8_v) { fprintf(out,"wrong data for S8_v\n"); exit(1); }
+ {Size8 r = Size8_1;
+ fprintf(out,"Size8 f(void):");
+ fflush(out);
+ *(Size8*)retp = r;
+}}
+void S12_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&S12_v) { fprintf(out,"wrong data for S12_v\n"); exit(1); }
+ {Size12 r = Size12_1;
+ fprintf(out,"Size12 f(void):");
+ fflush(out);
+ *(Size12*)retp = r;
+}}
+void S15_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&S15_v) { fprintf(out,"wrong data for S15_v\n"); exit(1); }
+ {Size15 r = Size15_1;
+ fprintf(out,"Size15 f(void):");
+ fflush(out);
+ *(Size15*)retp = r;
+}}
+void S16_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&S16_v) { fprintf(out,"wrong data for S16_v\n"); exit(1); }
+ {Size16 r = Size16_1;
+ fprintf(out,"Size16 f(void):");
+ fflush(out);
+ *(Size16*)retp = r;
+}}
+
+/* structure tests */
+void I_III_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&I_III) { fprintf(out,"wrong data for I_III\n"); exit(1); }
+ {Int a = *(Int*)(*args++);
+ Int b = *(Int*)(*args++);
+ Int c = *(Int*)(*args++);
+ Int r;
+ r.x = a.x + b.x + c.x;
+ fprintf(out,"Int f(Int,Int,Int):({%d},{%d},{%d})",a.x,b.x,c.x);
+ fflush(out);
+ *(Int*)retp = r;
+}}
+void C_CdC_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&C_CdC) { fprintf(out,"wrong data for C_CdC\n"); exit(1); }
+ {Char a = *(Char*)(*args++);
+ double b = *(double*)(*args++);
+ Char c = *(Char*)(*args++);
+ Char r;
+ r.x = (a.x + c.x)/2;
+ fprintf(out,"Char f(Char,double,Char):({'%c'},%g,{'%c'})",a.x,b,c.x);
+ fflush(out);
+ *(Char*)retp = r;
+}}
+void F_Ffd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&F_Ffd) { fprintf(out,"wrong data for F_Ffd\n"); exit(1); }
+ {Float a = *(Float*)(*args++);
+ float b = *(float*)(*args++);
+ double c = *(double*)(*args++);
+ Float r;
+ r.x = a.x + b + c;
+ fprintf(out,"Float f(Float,float,double):({%g},%g,%g)",a.x,b,c);
+ fflush(out);
+ *(Float*)retp = r;
+}}
+void D_fDd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&D_fDd) { fprintf(out,"wrong data for D_fDd\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ Double b = *(Double*)(*args++);
+ double c = *(double*)(*args++);
+ Double r;
+ r.x = a + b.x + c;
+ fprintf(out,"Double f(float,Double,double):(%g,{%g},%g)",a,b.x,c);
+ fflush(out);
+ *(Double*)retp = r;
+}}
+void D_Dfd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&D_Dfd) { fprintf(out,"wrong data for D_Dfd\n"); exit(1); }
+ {Double a = *(Double*)(*args++);
+ float b = *(float*)(*args++);
+ double c = *(double*)(*args++);
+ Double r;
+ r.x = a.x + b + c;
+ fprintf(out,"Double f(Double,float,double):({%g},%g,%g)",a.x,b,c);
+ fflush(out);
+ *(Double*)retp = r;
+}}
+void J_JiJ_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&J_JiJ) { fprintf(out,"wrong data for J_JiJ\n"); exit(1); }
+ {J a = *(J*)(*args++);
+ int b= *(int*)(*args++);
+ J c = *(J*)(*args++);
+ J r;
+ r.l1 = a.l1+c.l1; r.l2 = a.l2+b+c.l2;
+ fprintf(out,"J f(J,int,J):({%ld,%ld},%d,{%ld,%ld})",a.l1,a.l2,b,c.l1,c.l2);
+ fflush(out);
+ *(J*)retp = r;
+}}
+#ifndef SKIP_EXTRA_STRUCTS
+void T_TcT_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&T_TcT) { fprintf(out,"wrong data for T_TcT\n"); exit(1); }
+ {T a = *(T*)(*args++);
+ char b = *(char*)(*args++);
+ T c = *(T*)(*args++);
+ T r;
+ r.c[0]='b'; r.c[1]=c.c[1]; r.c[2]=c.c[2];
+ fprintf(out,"T f(T,char,T):({\"%c%c%c\"},'%c',{\"%c%c%c\"})",a.c[0],a.c[1],a.c[2],b,c.c[0],c.c[1],c.c[2]);
+ fflush(out);
+ *(T*)retp = r;
+}}
+void X_BcdB_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&X_BcdB) { fprintf(out,"wrong data for X_BcdB\n"); exit(1); }
+ {B a = *(B*)(*args++);
+ char b = *(char*)(*args++);
+ double c = *(double*)(*args++);
+ B d = *(B*)(*args++);
+ static X xr={"return val",'R'};
+ X r;
+ r = xr;
+ r.c1 = b;
+ fprintf(out,"X f(B,char,double,B):({%g,{%d,%d,%d}},'%c',%g,{%g,{%d,%d,%d}})",
+ a.d,a.i[0],a.i[1],a.i[2],b,c,d.d,d.i[0],d.i[1],d.i[2]);
+ fflush(out);
+ *(X*)retp = r;
+}}
+#endif
+
+/* gpargs boundary tests */
+void l_l0K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&l_l0K) { fprintf(out,"wrong data for l_l0K\n"); exit(1); }
+ {K b = *(K*)(*args++);
+ long c = *(long*)(*args++);
+ long r = b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(K,long):(%ld,%ld,%ld,%ld,%ld)",b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+void l_l1K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&l_l1K) { fprintf(out,"wrong data for l_l1K\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ K b = *(K*)(*args++);
+ long c = *(long*)(*args++);
+ long r = a1 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld)",a1,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+void l_l2K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&l_l2K) { fprintf(out,"wrong data for l_l2K\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ K b = *(K*)(*args++);
+ long c = *(long*)(*args++);
+ long r = a1 + a2 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(2*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+void l_l3K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&l_l3K) { fprintf(out,"wrong data for l_l3K\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ K b = *(K*)(*args++);
+ long c = *(long*)(*args++);
+ long r = a1 + a2 + a3 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(3*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+void l_l4K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&l_l4K) { fprintf(out,"wrong data for l_l4K\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long a4 = *(long*)(*args++);
+ K b = *(K*)(*args++);
+ long c = *(long*)(*args++);
+ long r = a1 + a2 + a3 + a4 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(4*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+void l_l5K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&l_l5K) { fprintf(out,"wrong data for l_l5K\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long a4 = *(long*)(*args++);
+ long a5 = *(long*)(*args++);
+ K b = *(K*)(*args++);
+ long c = *(long*)(*args++);
+ long r = a1 + a2 + a3 + a4 + a5 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(5*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+void l_l6K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&l_l6K) { fprintf(out,"wrong data for l_l6K\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long a4 = *(long*)(*args++);
+ long a5 = *(long*)(*args++);
+ long a6 = *(long*)(*args++);
+ K b = *(K*)(*args++);
+ long c = *(long*)(*args++);
+ long r = a1 + a2 + a3 + a4 + a5 + a6 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(6*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,a6,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ *(ffi_arg*)retp = r;
+}}
+void f_f17l3L_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&f_f17l3L) { fprintf(out,"wrong data for f_f17l3L\n"); exit(1); }
+ {float a = *(float*)(*args++);
+ float b = *(float*)(*args++);
+ float c = *(float*)(*args++);
+ float d = *(float*)(*args++);
+ float e = *(float*)(*args++);
+ float f = *(float*)(*args++);
+ float g = *(float*)(*args++);
+ float h = *(float*)(*args++);
+ float i = *(float*)(*args++);
+ float j = *(float*)(*args++);
+ float k = *(float*)(*args++);
+ float l = *(float*)(*args++);
+ float m = *(float*)(*args++);
+ float n = *(float*)(*args++);
+ float o = *(float*)(*args++);
+ float p = *(float*)(*args++);
+ float q = *(float*)(*args++);
+ long s = *(long*)(*args++);
+ long t = *(long*)(*args++);
+ long u = *(long*)(*args++);
+ L z = *(L*)(*args++);
+ float r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6;
+ fprintf(out,"float f(17*float,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6);
+ fflush(out);
+ *(float*)retp = r;
+}}
+void d_d17l3L_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_d17l3L) { fprintf(out,"wrong data for d_d17l3L\n"); exit(1); }
+ {double a = *(double*)(*args++);
+ double b = *(double*)(*args++);
+ double c = *(double*)(*args++);
+ double d = *(double*)(*args++);
+ double e = *(double*)(*args++);
+ double f = *(double*)(*args++);
+ double g = *(double*)(*args++);
+ double h = *(double*)(*args++);
+ double i = *(double*)(*args++);
+ double j = *(double*)(*args++);
+ double k = *(double*)(*args++);
+ double l = *(double*)(*args++);
+ double m = *(double*)(*args++);
+ double n = *(double*)(*args++);
+ double o = *(double*)(*args++);
+ double p = *(double*)(*args++);
+ double q = *(double*)(*args++);
+ long s = *(long*)(*args++);
+ long t = *(long*)(*args++);
+ long u = *(long*)(*args++);
+ L z = *(L*)(*args++);
+ double r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6;
+ fprintf(out,"double f(17*double,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void ll_l2ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&ll_l2ll) { fprintf(out,"wrong data for ll_l2ll\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long long b = *(long long *)(*args++);
+ long c = *(long*)(*args++);
+ long long r = (long long) (a1 + a2) + b + c;
+ fprintf(out,"long long f(2*long,long long,long):(%ld,%ld,0x%lx%08lx,%ld)",a1,a2,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ *(long long *)retp = r;
+}}
+void ll_l3ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&ll_l3ll) { fprintf(out,"wrong data for ll_l3ll\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long long b = *(long long *)(*args++);
+ long c = *(long*)(*args++);
+ long long r = (long long) (a1 + a2 + a3) + b + c;
+ fprintf(out,"long long f(3*long,long long,long):(%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ *(long long *)retp = r;
+}}
+void ll_l4ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&ll_l4ll) { fprintf(out,"wrong data for ll_l4ll\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long a4 = *(long*)(*args++);
+ long long b = *(long long *)(*args++);
+ long c = *(long*)(*args++);
+ long long r = (long long) (a1 + a2 + a3 + a4) + b + c;
+ fprintf(out,"long long f(4*long,long long,long):(%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ *(long long *)retp = r;
+}}
+void ll_l5ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&ll_l5ll) { fprintf(out,"wrong data for ll_l5ll\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long a4 = *(long*)(*args++);
+ long a5 = *(long*)(*args++);
+ long long b = *(long long *)(*args++);
+ long c = *(long*)(*args++);
+ long long r = (long long) (a1 + a2 + a3 + a4 + a5) + b + c;
+ fprintf(out,"long long f(5*long,long long,long):(%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ *(long long *)retp = r;
+}}
+void ll_l6ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&ll_l6ll) { fprintf(out,"wrong data for ll_l6ll\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long a4 = *(long*)(*args++);
+ long a5 = *(long*)(*args++);
+ long a6 = *(long*)(*args++);
+ long long b = *(long long *)(*args++);
+ long c = *(long*)(*args++);
+ long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6) + b + c;
+ fprintf(out,"long long f(6*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ *(long long *)retp = r;
+}}
+void ll_l7ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&ll_l7ll) { fprintf(out,"wrong data for ll_l7ll\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long a4 = *(long*)(*args++);
+ long a5 = *(long*)(*args++);
+ long a6 = *(long*)(*args++);
+ long a7 = *(long*)(*args++);
+ long long b = *(long long *)(*args++);
+ long c = *(long*)(*args++);
+ long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c;
+ fprintf(out,"long long f(7*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,a7,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ *(long long *)retp = r;
+}}
+void d_l2d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_l2d) { fprintf(out,"wrong data for d_l2d\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ double b = *(double*)(*args++);
+ long c = *(long*)(*args++);
+ double r = (double) (a1 + a2) + b + c;
+ fprintf(out,"double f(2*long,double,long):(%ld,%ld,%g,%ld)",a1,a2,b,c);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_l3d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_l3d) { fprintf(out,"wrong data for d_l3d\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ double b = *(double*)(*args++);
+ long c = *(long*)(*args++);
+ double r = (double) (a1 + a2 + a3) + b + c;
+ fprintf(out,"double f(3*long,double,long):(%ld,%ld,%ld,%g,%ld)",a1,a2,a3,b,c);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_l4d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_l4d) { fprintf(out,"wrong data for d_l4d\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long a4 = *(long*)(*args++);
+ double b = *(double*)(*args++);
+ long c = *(long*)(*args++);
+ double r = (double) (a1 + a2 + a3 + a4) + b + c;
+ fprintf(out,"double f(4*long,double,long):(%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,b,c);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_l5d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_l5d) { fprintf(out,"wrong data for d_l5d\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long a4 = *(long*)(*args++);
+ long a5 = *(long*)(*args++);
+ double b = *(double*)(*args++);
+ long c = *(long*)(*args++);
+ double r = (double) (a1 + a2 + a3 + a4 + a5) + b + c;
+ fprintf(out,"double f(5*long,double,long):(%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,b,c);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_l6d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_l6d) { fprintf(out,"wrong data for d_l6d\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long a4 = *(long*)(*args++);
+ long a5 = *(long*)(*args++);
+ long a6 = *(long*)(*args++);
+ double b = *(double*)(*args++);
+ long c = *(long*)(*args++);
+ double r = (double) (a1 + a2 + a3 + a4 + a5 + a6) + b + c;
+ fprintf(out,"double f(6*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,b,c);
+ fflush(out);
+ *(double*)retp = r;
+}}
+void d_l7d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data)
+{
+ if (data != (void*)&d_l7d) { fprintf(out,"wrong data for d_l7d\n"); exit(1); }
+ {long a1 = *(long*)(*args++);
+ long a2 = *(long*)(*args++);
+ long a3 = *(long*)(*args++);
+ long a4 = *(long*)(*args++);
+ long a5 = *(long*)(*args++);
+ long a6 = *(long*)(*args++);
+ long a7 = *(long*)(*args++);
+ double b = *(double*)(*args++);
+ long c = *(long*)(*args++);
+ double r = (double) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c;
+ fprintf(out,"double f(7*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,a7,b,c);
+ fflush(out);
+ *(double*)retp = r;
+}}
+
+
+/*
+ * The way we run these tests - first call the function directly, then
+ * through vacall() - there is the danger that arguments or results seem
+ * to be passed correctly, but what we are seeing are in fact the vestiges
+ * (traces) or the previous call. This may seriously fake the test.
+ * Avoid this by clearing the registers between the first and the second call.
+ */
+long clear_traces_i (long a, long b, long c, long d, long e, long f, long g, long h,
+ long i, long j, long k, long l, long m, long n, long o, long p)
+{ return 0; }
+float clear_traces_f (float a, float b, float c, float d, float e, float f, float g,
+ float h, float i, float j, float k, float l, float m, float n,
+ float o, float p)
+{ return 0.0; }
+double clear_traces_d (double a, double b, double c, double d, double e, double f, double g,
+ double h, double i, double j, double k, double l, double m, double n,
+ double o, double p)
+{ return 0.0; }
+J clear_traces_J (void)
+{ J j; j.l1 = j.l2 = 0; return j; }
+void clear_traces (void)
+{ clear_traces_i(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
+ clear_traces_f(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
+ clear_traces_d(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
+ clear_traces_J();
+}
+
+int main (void)
+{
+ void* callback_code;
+ void* callback_writable;
+#define ALLOC_CALLBACK() \
+ callback_writable = ffi_closure_alloc(sizeof(ffi_closure),&callback_code); \
+ if (!callback_writable) abort()
+#define PREP_CALLBACK(cif,simulator,data) \
+ if (ffi_prep_closure_loc(callback_writable,&(cif),simulator,data,callback_code) != FFI_OK) abort()
+#define FREE_CALLBACK() \
+ ffi_closure_free(callback_writable)
+
+ ffi_type_char = (char)(-1) < 0 ? ffi_type_schar : ffi_type_uchar;
+ out = stdout;
+
+#if (!defined(DGTEST)) || DGTEST == 1
+ /* void tests */
+ v_v();
+ clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_void);
+ PREP_CALLBACK(cif,v_v_simulator,(void*)&v_v);
+ ((void (ABI_ATTR *) (void)) callback_code) ();
+ }
+ FREE_CALLBACK();
+#endif
+
+ /* int tests */
+ { int ir;
+
+#if (!defined(DGTEST)) || DGTEST == 2
+ ir = i_v();
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_sint);
+ PREP_CALLBACK(cif,i_v_simulator,(void*)&i_v);
+ ir = ((int (ABI_ATTR *) (void)) callback_code) ();
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 3
+ ir = i_i(i1);
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
+ PREP_CALLBACK(cif,i_i_simulator,(void*)&i_i);
+ ir = ((int (ABI_ATTR *) (int)) callback_code) (i1);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 4
+ ir = i_i2(i1,i2);
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
+ PREP_CALLBACK(cif,i_i2_simulator,(void*)&i_i2);
+ ir = ((int (ABI_ATTR *) (int,int)) callback_code) (i1,i2);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 5
+ ir = i_i4(i1,i2,i3,i4);
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
+ PREP_CALLBACK(cif,i_i4_simulator,(void*)&i_i4);
+ ir = ((int (ABI_ATTR *) (int,int,int,int)) callback_code) (i1,i2,i3,i4);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 6
+ ir = i_i8(i1,i2,i3,i4,i5,i6,i7,i8);
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
+ PREP_CALLBACK(cif,i_i8_simulator,(void*)&i_i8);
+ ir = ((int (ABI_ATTR *) (int,int,int,int,int,int,int,int)) callback_code) (i1,i2,i3,i4,i5,i6,i7,i8);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 7
+ ir = i_i16(i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16);
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+ ir = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_sint);
+ PREP_CALLBACK(cif,i_i16_simulator,(void*)&i_i16);
+ ir = ((int (ABI_ATTR *) (int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int)) callback_code) (i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%d\n",ir);
+ fflush(out);
+#endif
+ }
+
+ /* float tests */
+ { float fr;
+
+#if (!defined(DGTEST)) || DGTEST == 8
+ fr = f_f(f1);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f_simulator,(void*)&f_f);
+ fr = ((float (ABI_ATTR *) (float)) callback_code) (f1);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 9
+ fr = f_f2(f1,f2);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f2_simulator,(void*)&f_f2);
+ fr = ((float (ABI_ATTR *) (float,float)) callback_code) (f1,f2);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 10
+ fr = f_f4(f1,f2,f3,f4);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f4_simulator,(void*)&f_f4);
+ fr = ((float (ABI_ATTR *) (float,float,float,float)) callback_code) (f1,f2,f3,f4);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 11
+ fr = f_f8(f1,f2,f3,f4,f5,f6,f7,f8);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f8_simulator,(void*)&f_f8);
+ fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 12
+ fr = f_f16(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f16_simulator,(void*)&f_f16);
+ fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 13
+ fr = f_f24(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f24_simulator,(void*)&f_f24);
+ fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+ }
+
+ /* double tests */
+ { double dr;
+
+#if (!defined(DGTEST)) || DGTEST == 14
+ dr = d_d(d1);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d_simulator,(void*)&d_d);
+ dr = ((double (ABI_ATTR *) (double)) callback_code) (d1);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 15
+ dr = d_d2(d1,d2);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d2_simulator,(void*)&d_d2);
+ dr = ((double (ABI_ATTR *) (double,double)) callback_code) (d1,d2);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 16
+ dr = d_d4(d1,d2,d3,d4);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d4_simulator,(void*)&d_d4);
+ dr = ((double (ABI_ATTR *) (double,double,double,double)) callback_code) (d1,d2,d3,d4);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 17
+ dr = d_d8(d1,d2,d3,d4,d5,d6,d7,d8);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d8_simulator,(void*)&d_d8);
+ dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 18
+ dr = d_d16(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d16_simulator,(void*)&d_d16);
+ dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,double)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+ }
+
+ /* pointer tests */
+ { void* vpr;
+
+#if (!defined(DGTEST)) || DGTEST == 19
+ vpr = vp_vpdpcpsp(&uc1,&d2,str3,&I4);
+ fprintf(out,"->0x%p\n",vpr);
+ fflush(out);
+ vpr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_pointer);
+ PREP_CALLBACK(cif,vp_vpdpcpsp_simulator,(void*)&vp_vpdpcpsp);
+ vpr = ((void* (ABI_ATTR *) (void*,double*,char*,Int*)) callback_code) (&uc1,&d2,str3,&I4);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->0x%p\n",vpr);
+ fflush(out);
+#endif
+ }
+
+ /* mixed number tests */
+ { uchar ucr;
+ ushort usr;
+ float fr;
+ double dr;
+ long long llr;
+
+#if (!defined(DGTEST)) || DGTEST == 20
+ ucr = uc_ucsil(uc1,us2,ui3,ul4);
+ fprintf(out,"->%u\n",ucr);
+ fflush(out);
+ ucr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_uchar, &ffi_type_ushort, &ffi_type_uint, &ffi_type_ulong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_uchar);
+ PREP_CALLBACK(cif,uc_ucsil_simulator,(void*)&uc_ucsil);
+ ucr = ((uchar (ABI_ATTR *) (uchar,ushort,uint,ulong)) callback_code) (uc1,us2,ui3,ul4);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%u\n",ucr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 21
+ dr = d_iidd(i1,i2,d3,d4);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_iidd_simulator,(void*)&d_iidd);
+ dr = ((double (ABI_ATTR *) (int,int,double,double)) callback_code) (i1,i2,d3,d4);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 22
+ dr = d_iiidi(i1,i2,i3,d4,i5);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_iiidi_simulator,(void*)&d_iiidi);
+ dr = ((double (ABI_ATTR *) (int,int,int,double,int)) callback_code) (i1,i2,i3,d4,i5);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 23
+ dr = d_idid(i1,d2,i3,d4);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_double, &ffi_type_sint, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_idid_simulator,(void*)&d_idid);
+ dr = ((double (ABI_ATTR *) (int,double,int,double)) callback_code) (i1,d2,i3,d4);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 24
+ dr = d_fdi(f1,d2,i3);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_fdi_simulator,(void*)&d_fdi);
+ dr = ((double (ABI_ATTR *) (float,double,int)) callback_code) (f1,d2,i3);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 25
+ usr = us_cdcd(c1,d2,c3,d4);
+ fprintf(out,"->%u\n",usr);
+ fflush(out);
+ usr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_char, &ffi_type_double, &ffi_type_char, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_ushort);
+ PREP_CALLBACK(cif,us_cdcd_simulator,(void*)&us_cdcd);
+ usr = ((ushort (ABI_ATTR *) (char,double,char,double)) callback_code) (c1,d2,c3,d4);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%u\n",usr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 26
+ llr = ll_iiilli(i1,i2,i3,ll1,i13);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_slonglong, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ PREP_CALLBACK(cif,ll_iiilli_simulator,(void*)&ll_iiilli);
+ llr = ((long long (ABI_ATTR *) (int,int,int,long long,int)) callback_code) (i1,i2,i3,ll1,i13);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 27
+ llr = ll_flli(f13,ll1,i13);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_slonglong, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ PREP_CALLBACK(cif,ll_flli_simulator,(void*)&ll_flli);
+ llr = ((long long (ABI_ATTR *) (float,long long,int)) callback_code) (f13,ll1,i13);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 28
+ fr = f_fi(f1,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_fi_simulator,(void*)&f_fi);
+ fr = ((float (ABI_ATTR *) (float,int)) callback_code) (f1,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 29
+ fr = f_f2i(f1,f2,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f2i_simulator,(void*)&f_f2i);
+ fr = ((float (ABI_ATTR *) (float,float,int)) callback_code) (f1,f2,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 30
+ fr = f_f3i(f1,f2,f3,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f3i_simulator,(void*)&f_f3i);
+ fr = ((float (ABI_ATTR *) (float,float,float,int)) callback_code) (f1,f2,f3,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 31
+ fr = f_f4i(f1,f2,f3,f4,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f4i_simulator,(void*)&f_f4i);
+ fr = ((float (ABI_ATTR *) (float,float,float,float,int)) callback_code) (f1,f2,f3,f4,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 32
+ fr = f_f7i(f1,f2,f3,f4,f5,f6,f7,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f7i_simulator,(void*)&f_f7i);
+ fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,int)) callback_code) (f1,f2,f3,f4,f5,f6,f7,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 33
+ fr = f_f8i(f1,f2,f3,f4,f5,f6,f7,f8,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f8i_simulator,(void*)&f_f8i);
+ fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,int)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 34
+ fr = f_f13i(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,i9);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f13i_simulator,(void*)&f_f13i);
+ fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,int)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 35
+ dr = d_di(d1,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_di_simulator,(void*)&d_di);
+ dr = ((double (ABI_ATTR *) (double,int)) callback_code) (d1,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 36
+ dr = d_d2i(d1,d2,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d2i_simulator,(void*)&d_d2i);
+ dr = ((double (ABI_ATTR *) (double,double,int)) callback_code) (d1,d2,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 37
+ dr = d_d3i(d1,d2,d3,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d3i_simulator,(void*)&d_d3i);
+ dr = ((double (ABI_ATTR *) (double,double,double,int)) callback_code) (d1,d2,d3,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 38
+ dr = d_d4i(d1,d2,d3,d4,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d4i_simulator,(void*)&d_d4i);
+ dr = ((double (ABI_ATTR *) (double,double,double,double,int)) callback_code) (d1,d2,d3,d4,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 39
+ dr = d_d7i(d1,d2,d3,d4,d5,d6,d7,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d7i_simulator,(void*)&d_d7i);
+ dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 40
+ dr = d_d8i(d1,d2,d3,d4,d5,d6,d7,d8,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d8i_simulator,(void*)&d_d8i);
+ dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 41
+ dr = d_d12i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d12i_simulator,(void*)&d_d12i);
+ dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 42
+ dr = d_d13i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,i9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d13i_simulator,(void*)&d_d13i);
+ dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,i9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+ }
+
+ /* small structure return tests */
+#if (!defined(DGTEST)) || DGTEST == 43
+ {
+ Size1 r = S1_v();
+ fprintf(out,"->{%c}\n",r.x1);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Size1_elements[] = { &ffi_type_char, NULL };
+ ffi_type ffi_type_Size1;
+ ffi_type_Size1.type = FFI_TYPE_STRUCT;
+ ffi_type_Size1.size = sizeof(Size1);
+ ffi_type_Size1.alignment = alignof_slot(Size1);
+ ffi_type_Size1.elements = ffi_type_Size1_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size1);
+ PREP_CALLBACK(cif,S1_v_simulator,(void*)&S1_v);
+ r = ((Size1 (ABI_ATTR *) (void)) callback_code) ();
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%c}\n",r.x1);
+ fflush(out);
+ }
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 44
+ {
+ Size2 r = S2_v();
+ fprintf(out,"->{%c%c}\n",r.x1,r.x2);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Size2_elements[] = { &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size2;
+ ffi_type_Size2.type = FFI_TYPE_STRUCT;
+ ffi_type_Size2.size = sizeof(Size2);
+ ffi_type_Size2.alignment = alignof_slot(Size2);
+ ffi_type_Size2.elements = ffi_type_Size2_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size2);
+ PREP_CALLBACK(cif,S2_v_simulator,(void*)&S2_v);
+ r = ((Size2 (ABI_ATTR *) (void)) callback_code) ();
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%c%c}\n",r.x1,r.x2);
+ fflush(out);
+ }
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 45
+ {
+ Size3 r = S3_v();
+ fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Size3_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size3;
+ ffi_type_Size3.type = FFI_TYPE_STRUCT;
+ ffi_type_Size3.size = sizeof(Size3);
+ ffi_type_Size3.alignment = alignof_slot(Size3);
+ ffi_type_Size3.elements = ffi_type_Size3_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size3);
+ PREP_CALLBACK(cif,S3_v_simulator,(void*)&S3_v);
+ r = ((Size3 (ABI_ATTR *) (void)) callback_code) ();
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3);
+ fflush(out);
+ }
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 46
+ {
+ Size4 r = S4_v();
+ fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Size4_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size4;
+ ffi_type_Size4.type = FFI_TYPE_STRUCT;
+ ffi_type_Size4.size = sizeof(Size4);
+ ffi_type_Size4.alignment = alignof_slot(Size4);
+ ffi_type_Size4.elements = ffi_type_Size4_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size4);
+ PREP_CALLBACK(cif,S4_v_simulator,(void*)&S4_v);
+ r = ((Size4 (ABI_ATTR *) (void)) callback_code) ();
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4);
+ fflush(out);
+ }
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 47
+ {
+ Size7 r = S7_v();
+ fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Size7_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size7;
+ ffi_type_Size7.type = FFI_TYPE_STRUCT;
+ ffi_type_Size7.size = sizeof(Size7);
+ ffi_type_Size7.alignment = alignof_slot(Size7);
+ ffi_type_Size7.elements = ffi_type_Size7_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size7);
+ PREP_CALLBACK(cif,S7_v_simulator,(void*)&S7_v);
+ r = ((Size7 (ABI_ATTR *) (void)) callback_code) ();
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7);
+ fflush(out);
+ }
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 48
+ {
+ Size8 r = S8_v();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Size8_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size8;
+ ffi_type_Size8.type = FFI_TYPE_STRUCT;
+ ffi_type_Size8.size = sizeof(Size8);
+ ffi_type_Size8.alignment = alignof_slot(Size8);
+ ffi_type_Size8.elements = ffi_type_Size8_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size8);
+ PREP_CALLBACK(cif,S8_v_simulator,(void*)&S8_v);
+ r = ((Size8 (ABI_ATTR *) (void)) callback_code) ();
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8);
+ fflush(out);
+ }
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 49
+ {
+ Size12 r = S12_v();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Size12_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size12;
+ ffi_type_Size12.type = FFI_TYPE_STRUCT;
+ ffi_type_Size12.size = sizeof(Size12);
+ ffi_type_Size12.alignment = alignof_slot(Size12);
+ ffi_type_Size12.elements = ffi_type_Size12_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size12);
+ PREP_CALLBACK(cif,S12_v_simulator,(void*)&S12_v);
+ r = ((Size12 (ABI_ATTR *) (void)) callback_code) ();
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12);
+ fflush(out);
+ }
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 50
+ {
+ Size15 r = S15_v();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Size15_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size15;
+ ffi_type_Size15.type = FFI_TYPE_STRUCT;
+ ffi_type_Size15.size = sizeof(Size15);
+ ffi_type_Size15.alignment = alignof_slot(Size15);
+ ffi_type_Size15.elements = ffi_type_Size15_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size15);
+ PREP_CALLBACK(cif,S15_v_simulator,(void*)&S15_v);
+ r = ((Size15 (ABI_ATTR *) (void)) callback_code) ();
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15);
+ fflush(out);
+ }
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 51
+ {
+ Size16 r = S16_v();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16);
+ fflush(out);
+ memset(&r,0,sizeof(r)); clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Size16_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL };
+ ffi_type ffi_type_Size16;
+ ffi_type_Size16.type = FFI_TYPE_STRUCT;
+ ffi_type_Size16.size = sizeof(Size16);
+ ffi_type_Size16.alignment = alignof_slot(Size16);
+ ffi_type_Size16.elements = ffi_type_Size16_elements;
+ ffi_cif cif;
+ FFI_PREP_CIF_NOARGS(cif,ffi_type_Size16);
+ PREP_CALLBACK(cif,S16_v_simulator,(void*)&S16_v);
+ r = ((Size16 (ABI_ATTR *) (void)) callback_code) ();
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16);
+ fflush(out);
+ }
+#endif
+
+
+ /* structure tests */
+ { Int Ir;
+ Char Cr;
+ Float Fr;
+ Double Dr;
+ J Jr;
+#ifndef SKIP_EXTRA_STRUCTS
+ T Tr;
+ X Xr;
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 52
+ Ir = I_III(I1,I2,I3);
+ fprintf(out,"->{%d}\n",Ir.x);
+ fflush(out);
+ Ir.x = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Int_elements[] = { &ffi_type_sint, NULL };
+ ffi_type ffi_type_Int;
+ ffi_type_Int.type = FFI_TYPE_STRUCT;
+ ffi_type_Int.size = sizeof(Int);
+ ffi_type_Int.alignment = alignof_slot(Int);
+ ffi_type_Int.elements = ffi_type_Int_elements;
+ ffi_type* argtypes[] = { &ffi_type_Int, &ffi_type_Int, &ffi_type_Int };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_Int);
+ PREP_CALLBACK(cif,I_III_simulator,(void*)&I_III);
+ Ir = ((Int (ABI_ATTR *) (Int,Int,Int)) callback_code) (I1,I2,I3);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%d}\n",Ir.x);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 53
+ Cr = C_CdC(C1,d2,C3);
+ fprintf(out,"->{'%c'}\n",Cr.x);
+ fflush(out);
+ Cr.x = '\0'; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Char_elements[] = { &ffi_type_char, NULL };
+ ffi_type ffi_type_Char;
+ ffi_type_Char.type = FFI_TYPE_STRUCT;
+ ffi_type_Char.size = sizeof(Char);
+ ffi_type_Char.alignment = alignof_slot(Char);
+ ffi_type_Char.elements = ffi_type_Char_elements;
+ ffi_type* argtypes[] = { &ffi_type_Char, &ffi_type_double, &ffi_type_Char };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_Char);
+ PREP_CALLBACK(cif,C_CdC_simulator,(void*)&C_CdC);
+ Cr = ((Char (ABI_ATTR *) (Char,double,Char)) callback_code) (C1,d2,C3);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{'%c'}\n",Cr.x);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 54
+ Fr = F_Ffd(F1,f2,d3);
+ fprintf(out,"->{%g}\n",Fr.x);
+ fflush(out);
+ Fr.x = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Float_elements[] = { &ffi_type_float, NULL };
+ ffi_type ffi_type_Float;
+ ffi_type_Float.type = FFI_TYPE_STRUCT;
+ ffi_type_Float.size = sizeof(Float);
+ ffi_type_Float.alignment = alignof_slot(Float);
+ ffi_type_Float.elements = ffi_type_Float_elements;
+ ffi_type* argtypes[] = { &ffi_type_Float, &ffi_type_float, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_Float);
+ PREP_CALLBACK(cif,F_Ffd_simulator,(void*)&F_Ffd);
+ Fr = ((Float (ABI_ATTR *) (Float,float,double)) callback_code) (F1,f2,d3);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%g}\n",Fr.x);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 55
+ Dr = D_fDd(f1,D2,d3);
+ fprintf(out,"->{%g}\n",Dr.x);
+ fflush(out);
+ Dr.x = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL };
+ ffi_type ffi_type_Double;
+ ffi_type_Double.type = FFI_TYPE_STRUCT;
+ ffi_type_Double.size = sizeof(Double);
+ ffi_type_Double.alignment = alignof_slot(Double);
+ ffi_type_Double.elements = ffi_type_Double_elements;
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_Double, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_Double);
+ PREP_CALLBACK(cif,D_fDd_simulator,(void*)&D_fDd);
+ Dr = ((Double (ABI_ATTR *) (float,Double,double)) callback_code) (f1,D2,d3);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%g}\n",Dr.x);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 56
+ Dr = D_Dfd(D1,f2,d3);
+ fprintf(out,"->{%g}\n",Dr.x);
+ fflush(out);
+ Dr.x = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL };
+ ffi_type ffi_type_Double;
+ ffi_type_Double.type = FFI_TYPE_STRUCT;
+ ffi_type_Double.size = sizeof(Double);
+ ffi_type_Double.alignment = alignof_slot(Double);
+ ffi_type_Double.elements = ffi_type_Double_elements;
+ ffi_type* argtypes[] = { &ffi_type_Double, &ffi_type_float, &ffi_type_double };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_Double);
+ PREP_CALLBACK(cif,D_Dfd_simulator,(void*)&D_Dfd);
+ Dr = ((Double (ABI_ATTR *) (Double,float,double)) callback_code) (D1,f2,d3);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%g}\n",Dr.x);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 57
+ Jr = J_JiJ(J1,i2,J2);
+ fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2);
+ fflush(out);
+ Jr.l1 = Jr.l2 = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_J_elements[] = { &ffi_type_slong, &ffi_type_slong, NULL };
+ ffi_type ffi_type_J;
+ ffi_type_J.type = FFI_TYPE_STRUCT;
+ ffi_type_J.size = sizeof(J);
+ ffi_type_J.alignment = alignof_slot(J);
+ ffi_type_J.elements = ffi_type_J_elements;
+ ffi_type* argtypes[] = { &ffi_type_J, &ffi_type_sint, &ffi_type_J };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_J);
+ PREP_CALLBACK(cif,J_JiJ_simulator,(void*)&J_JiJ);
+ Jr = ((J (ABI_ATTR *) (J,int,J)) callback_code) (J1,i2,J2);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2);
+ fflush(out);
+#endif
+
+#ifndef SKIP_EXTRA_STRUCTS
+#if (!defined(DGTEST)) || DGTEST == 58
+ Tr = T_TcT(T1,' ',T2);
+ fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]);
+ fflush(out);
+ Tr.c[0] = Tr.c[1] = Tr.c[2] = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_T_elements[] = { ??, NULL };
+ ffi_type ffi_type_T;
+ ffi_type_T.type = FFI_TYPE_STRUCT;
+ ffi_type_T.size = sizeof(T);
+ ffi_type_T.alignment = alignof_slot(T);
+ ffi_type_T.elements = ffi_type_T_elements;
+ ffi_type* argtypes[] = { &ffi_type_T, &ffi_type_char, &ffi_type_T };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_T);
+ PREP_CALLBACK(cif,T_TcT_simulator,(void*)&T_TcT);
+ Tr = ((T (ABI_ATTR *) (T,char,T)) callback_code) (T1,' ',T2);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]);
+ fflush(out);
+#endif
+
+#ifndef SKIP_X
+#if (!defined(DGTEST)) || DGTEST == 59
+ Xr = X_BcdB(B1,c2,d3,B2);
+ fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1);
+ fflush(out);
+ Xr.c[0]=Xr.c1='\0'; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* ffi_type_X_elements[] = { ??, NULL };
+ ffi_type ffi_type_X;
+ ffi_type_X.type = FFI_TYPE_STRUCT;
+ ffi_type_X.size = sizeof(X);
+ ffi_type_X.alignment = alignof_slot(X);
+ ffi_type_X.elements = ffi_type_X_elements;
+ ffi_type* argtypes[] = { &ffi_type_X, &ffi_type_char, &ffi_type_double, &ffi_type_X };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_X);
+ PREP_CALLBACK(cif,X_BcdB_simulator,(void*)&X_BcdB);
+ Xr = ((X (ABI_ATTR *) (B,char,double,B)) callback_code) (B1,c2,d3,B2);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1);
+ fflush(out);
+#endif
+#endif
+#endif
+ }
+
+
+ /* gpargs boundary tests */
+ {
+ ffi_type* ffi_type_K_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL };
+ ffi_type ffi_type_K;
+ ffi_type* ffi_type_L_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL };
+ ffi_type ffi_type_L;
+ long lr;
+ long long llr;
+ float fr;
+ double dr;
+
+ ffi_type_K.type = FFI_TYPE_STRUCT;
+ ffi_type_K.size = sizeof(K);
+ ffi_type_K.alignment = alignof_slot(K);
+ ffi_type_K.elements = ffi_type_K_elements;
+
+ ffi_type_L.type = FFI_TYPE_STRUCT;
+ ffi_type_L.size = sizeof(L);
+ ffi_type_L.alignment = alignof_slot(L);
+ ffi_type_L.elements = ffi_type_L_elements;
+
+#if (!defined(DGTEST)) || DGTEST == 60
+ lr = l_l0K(K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ PREP_CALLBACK(cif,l_l0K_simulator,(void*)l_l0K);
+ lr = ((long (ABI_ATTR *) (K,long)) callback_code) (K1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 61
+ lr = l_l1K(l1,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ PREP_CALLBACK(cif,l_l1K_simulator,(void*)l_l1K);
+ lr = ((long (ABI_ATTR *) (long,K,long)) callback_code) (l1,K1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 62
+ lr = l_l2K(l1,l2,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ PREP_CALLBACK(cif,l_l2K_simulator,(void*)l_l2K);
+ lr = ((long (ABI_ATTR *) (long,long,K,long)) callback_code) (l1,l2,K1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 63
+ lr = l_l3K(l1,l2,l3,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ PREP_CALLBACK(cif,l_l3K_simulator,(void*)l_l3K);
+ lr = ((long (ABI_ATTR *) (long,long,long,K,long)) callback_code) (l1,l2,l3,K1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 64
+ lr = l_l4K(l1,l2,l3,l4,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ PREP_CALLBACK(cif,l_l4K_simulator,(void*)l_l4K);
+ lr = ((long (ABI_ATTR *) (long,long,long,long,K,long)) callback_code) (l1,l2,l3,l4,K1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 65
+ lr = l_l5K(l1,l2,l3,l4,l5,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ PREP_CALLBACK(cif,l_l5K_simulator,(void*)l_l5K);
+ lr = ((long (ABI_ATTR *) (long,long,long,long,long,K,long)) callback_code) (l1,l2,l3,l4,l5,K1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 66
+ lr = l_l6K(l1,l2,l3,l4,l5,l6,K1,l9);
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+ lr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slong);
+ PREP_CALLBACK(cif,l_l6K_simulator,(void*)l_l6K);
+ lr = ((long (ABI_ATTR *) (long,long,long,long,long,long,K,long)) callback_code) (l1,l2,l3,l4,l5,l6,K1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%ld\n",lr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 67
+ fr = f_f17l3L(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,l6,l7,l8,L1);
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+ fr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_float);
+ PREP_CALLBACK(cif,f_f17l3L_simulator,(void*)&f_f17l3L);
+ fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,long,long,long,L)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,l6,l7,l8,L1);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",fr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 68
+ dr = d_d17l3L(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17,l6,l7,l8,L1);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_d17l3L_simulator,(void*)&d_d17l3L);
+ dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,long,long,long,L)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17,l6,l7,l8,L1);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 69
+ llr = ll_l2ll(l1,l2,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ PREP_CALLBACK(cif,ll_l2ll_simulator,(void*)ll_l2ll);
+ llr = ((long long (ABI_ATTR *) (long,long,long long,long)) callback_code) (l1,l2,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 70
+ llr = ll_l3ll(l1,l2,l3,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ PREP_CALLBACK(cif,ll_l3ll_simulator,(void*)ll_l3ll);
+ llr = ((long long (ABI_ATTR *) (long,long,long,long long,long)) callback_code) (l1,l2,l3,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 71
+ llr = ll_l4ll(l1,l2,l3,l4,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ PREP_CALLBACK(cif,ll_l4ll_simulator,(void*)ll_l4ll);
+ llr = ((long long (ABI_ATTR *) (long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 72
+ llr = ll_l5ll(l1,l2,l3,l4,l5,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ PREP_CALLBACK(cif,ll_l5ll_simulator,(void*)ll_l5ll);
+ llr = ((long long (ABI_ATTR *) (long,long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,l5,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 73
+ llr = ll_l6ll(l1,l2,l3,l4,l5,l6,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ PREP_CALLBACK(cif,ll_l6ll_simulator,(void*)ll_l6ll);
+ llr = ((long long (ABI_ATTR *) (long,long,long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,l5,l6,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 74
+ llr = ll_l7ll(l1,l2,l3,l4,l5,l6,l7,ll1,l9);
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+ llr = 0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong);
+ PREP_CALLBACK(cif,ll_l7ll_simulator,(void*)ll_l7ll);
+ llr = ((long long (ABI_ATTR *) (long,long,long,long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,l5,l6,l7,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff));
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 75
+ dr = d_l2d(l1,l2,ll1,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_l2d_simulator,(void*)d_l2d);
+ dr = ((double (ABI_ATTR *) (long,long,double,long)) callback_code) (l1,l2,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 76
+ dr = d_l3d(l1,l2,l3,ll1,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_l3d_simulator,(void*)d_l3d);
+ dr = ((double (ABI_ATTR *) (long,long,long,double,long)) callback_code) (l1,l2,l3,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 77
+ dr = d_l4d(l1,l2,l3,l4,ll1,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_l4d_simulator,(void*)d_l4d);
+ dr = ((double (ABI_ATTR *) (long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 78
+ dr = d_l5d(l1,l2,l3,l4,l5,ll1,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_l5d_simulator,(void*)d_l5d);
+ dr = ((double (ABI_ATTR *) (long,long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,l5,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 79
+ dr = d_l6d(l1,l2,l3,l4,l5,l6,ll1,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_l6d_simulator,(void*)d_l6d);
+ dr = ((double (ABI_ATTR *) (long,long,long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,l5,l6,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+#if (!defined(DGTEST)) || DGTEST == 80
+ dr = d_l7d(l1,l2,l3,l4,l5,l6,l7,ll1,l9);
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+ dr = 0.0; clear_traces();
+ ALLOC_CALLBACK();
+ {
+ ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong };
+ ffi_cif cif;
+ FFI_PREP_CIF(cif,argtypes,ffi_type_double);
+ PREP_CALLBACK(cif,d_l7d_simulator,(void*)d_l7d);
+ dr = ((double (ABI_ATTR *) (long,long,long,long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,l5,l6,l7,ll1,l9);
+ }
+ FREE_CALLBACK();
+ fprintf(out,"->%g\n",dr);
+ fflush(out);
+#endif
+
+ }
+
+ exit(0);
+}
+
diff --git a/contrib/restricted/libffi/testsuite/libffi.bhaible/test-callback/ya.make b/contrib/restricted/libffi/testsuite/libffi.bhaible/test-callback/ya.make
index 9d5960e66e..72d601ab5b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.bhaible/test-callback/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.bhaible/test-callback/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.bhaible)
-
-SRCS(
- test-callback.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.bhaible)
+
+SRCS(
+ test-callback.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.bhaible/testcases.c b/contrib/restricted/libffi/testsuite/libffi.bhaible/testcases.c
index 5aa660d9ff..d25ebf48c9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.bhaible/testcases.c
+++ b/contrib/restricted/libffi/testsuite/libffi.bhaible/testcases.c
@@ -1,743 +1,743 @@
-/*
- * Copyright 1993 Bill Triggs <Bill.Triggs@inrialpes.fr>
- * Copyright 1995-2017 Bruno Haible <bruno@clisp.org>
- *
- * 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 3 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, see <http://www.gnu.org/licenses/>.
- */
-
-/* This file defines test functions of selected signatures, that exercise
- dark corners of the various ABIs. */
-
-#include <stdio.h>
-
-FILE* out;
-
-#define uchar unsigned char
-#define ushort unsigned short
-#define uint unsigned int
-#define ulong unsigned long
-
-typedef struct { char x; } Char;
-typedef struct { short x; } Short;
-typedef struct { int x; } Int;
-typedef struct { long x; } Long;
-typedef struct { float x; } Float;
-typedef struct { double x; } Double;
-typedef struct { char c; float f; } A;
-typedef struct { double d; int i[3]; } B;
-typedef struct { long l1; long l2; } J;
-typedef struct { long l1; long l2; long l3; long l4; } K;
-typedef struct { long l1; long l2; long l3; long l4; long l5; long l6; } L;
-typedef struct { char x1; } Size1;
-typedef struct { char x1; char x2; } Size2;
-typedef struct { char x1; char x2; char x3; } Size3;
-typedef struct { char x1; char x2; char x3; char x4; } Size4;
-typedef struct {
- char x1; char x2; char x3; char x4; char x5; char x6; char x7;
-} Size7;
-typedef struct {
- char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8;
-} Size8;
-typedef struct {
- char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8;
- char x9; char x10; char x11; char x12;
-} Size12;
-typedef struct {
- char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8;
- char x9; char x10; char x11; char x12; char x13; char x14; char x15;
-} Size15;
-typedef struct {
- char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8;
- char x9; char x10; char x11; char x12; char x13; char x14; char x15; char x16;
-} Size16;
-typedef struct { char c[3]; } T;
-typedef struct { char c[33],c1; } X;
-
-char c1='a', c2=127, c3=(char)128, c4=(char)255, c5=-1;
-short s1=32767, s2=(short)32768, s3=3, s4=4, s5=5, s6=6, s7=7, s8=8, s9=9;
-int i1=1, i2=2, i3=3, i4=4, i5=5, i6=6, i7=7, i8=8, i9=9,
- i10=11, i11=12, i12=13, i13=14, i14=15, i15=16, i16=17;
-long l1=1, l2=2, l3=3, l4=4, l5=5, l6=6, l7=7, l8=8, l9=9;
-long long ll1 = 3875056143130689530LL;
-float f1=0.1f, f2=0.2f, f3=0.3f, f4=0.4f, f5=0.5f, f6=0.6f, f7=0.7f, f8=0.8f, f9=0.9f,
- f10=1.1f, f11=1.2f, f12=1.3f, f13=1.4f, f14=1.5f, f15=1.6f, f16=1.7f, f17=1.8f,
- f18=1.9f, f19=2.1f, f20=2.2f, f21=2.3f, f22=2.4f, f23=2.5f, f24=2.6f;
-double d1=0.1, d2=0.2, d3=0.3, d4=0.4, d5=0.5, d6=0.6, d7=0.7, d8=0.8, d9=0.9,
- d10=1.1, d11=1.2, d12=1.3, d13=1.4, d14=1.5, d15=1.6, d16=1.7, d17=1.8;
-
-uchar uc1='a', uc2=127, uc3=128, uc4=255, uc5=(uchar)-1;
-ushort us1=1, us2=2, us3=3, us4=4, us5=5, us6=6, us7=7, us8=8, us9=9;
-uint ui1=1, ui2=2, ui3=3, ui4=4, ui5=5, ui6=6, ui7=7, ui8=8, ui9=9;
-ulong ul1=1, ul2=2, ul3=3, ul4=4, ul5=5, ul6=6, ul7=7, ul8=8, ul9=9;
-
-char *str1="hello",str2[]="goodbye",*str3="still here?";
-Char C1={'A'}, C2={'B'}, C3={'C'}, C4={'\377'}, C5={(char)(-1)};
-Short S1={1}, S2={2}, S3={3}, S4={4}, S5={5}, S6={6}, S7={7}, S8={8}, S9={9};
-Int I1={1}, I2={2}, I3={3}, I4={4}, I5={5}, I6={6}, I7={7}, I8={8}, I9={9};
-Float F1={0.1f}, F2={0.2f}, F3={0.3f}, F4={0.4f}, F5={0.5f}, F6={0.6f}, F7={0.7f}, F8={0.8f}, F9={0.9f};
-Double D1={0.1}, D2={0.2}, D3={0.3}, D4={0.4}, D5={0.5}, D6={0.6}, D7={0.7}, D8={0.8}, D9={0.9};
-
-A A1={'a',0.1f},A2={'b',0.2f},A3={'\377',0.3f};
-B B1={0.1,{1,2,3}},B2={0.2,{5,4,3}};
-J J1={47,11},J2={73,55};
-K K1={19,69,12,28};
-L L1={561,1105,1729,2465,2821,6601}; /* A002997 */
-Size1 Size1_1={'a'};
-Size2 Size2_1={'a','b'};
-Size3 Size3_1={'a','b','c'};
-Size4 Size4_1={'a','b','c','d'};
-Size7 Size7_1={'a','b','c','d','e','f','g'};
-Size8 Size8_1={'a','b','c','d','e','f','g','h'};
-Size12 Size12_1={'a','b','c','d','e','f','g','h','i','j','k','l'};
-Size15 Size15_1={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o'};
-Size16 Size16_1={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'};
-T T1={{'t','h','e'}},T2={{'f','o','x'}};
-X X1={"abcdefghijklmnopqrstuvwxyzABCDEF",'G'}, X2={"123",'9'}, X3={"return-return-return",'R'};
-
-#if defined(__GNUC__)
-#define __STDCALL__ __attribute__((stdcall))
-#define __THISCALL__ __attribute__((thiscall))
-#define __FASTCALL__ __attribute__((fastcall))
-#define __MSABI__ __attribute__((ms_abi))
-#else
-#define __STDCALL__ __stdcall
-#define __THISCALL__ __thiscall
-#define __FASTCALL__ __fastcall
-#endif
-
-#ifndef ABI_ATTR
-#define ABI_ATTR
-#endif
-
-/* void tests */
-void ABI_ATTR v_v (void)
-{
- fprintf(out,"void f(void):\n");
- fflush(out);
-}
-
-/* int tests */
-int ABI_ATTR i_v (void)
-{
- int r=99;
- fprintf(out,"int f(void):");
- fflush(out);
- return r;
-}
-int ABI_ATTR i_i (int a)
-{
- int r=a+1;
- fprintf(out,"int f(int):(%d)",a);
- fflush(out);
- return r;
-}
-int ABI_ATTR i_i2 (int a, int b)
-{
- int r=a+b;
- fprintf(out,"int f(2*int):(%d,%d)",a,b);
- fflush(out);
- return r;
-}
-int ABI_ATTR i_i4 (int a, int b, int c, int d)
-{
- int r=a+b+c+d;
- fprintf(out,"int f(4*int):(%d,%d,%d,%d)",a,b,c,d);
- fflush(out);
- return r;
-}
-int ABI_ATTR i_i8 (int a, int b, int c, int d, int e, int f, int g, int h)
-{
- int r=a+b+c+d+e+f+g+h;
- fprintf(out,"int f(8*int):(%d,%d,%d,%d,%d,%d,%d,%d)",a,b,c,d,e,f,g,h);
- fflush(out);
- return r;
-}
-int ABI_ATTR i_i16 (int a, int b, int c, int d, int e, int f, int g, int h,
- int i, int j, int k, int l, int m, int n, int o, int p)
-{
- int r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
- fprintf(out,"int f(16*int):(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
- a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
- fflush(out);
- return r;
-}
-
-/* float tests */
-float ABI_ATTR f_f (float a)
-{
- float r=a+1.0f;
- fprintf(out,"float f(float):(%g)",a);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f2 (float a, float b)
-{
- float r=a+b;
- fprintf(out,"float f(2*float):(%g,%g)",a,b);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f4 (float a, float b, float c, float d)
-{
- float r=a+b+c+d;
- fprintf(out,"float f(4*float):(%g,%g,%g,%g)",a,b,c,d);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f8 (float a, float b, float c, float d, float e, float f,
- float g, float h)
-{
- float r=a+b+c+d+e+f+g+h;
- fprintf(out,"float f(8*float):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f16 (float a, float b, float c, float d, float e, float f, float g, float h,
- float i, float j, float k, float l, float m, float n, float o, float p)
-{
- float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
- fprintf(out,"float f(16*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f24 (float a, float b, float c, float d, float e, float f, float g, float h,
- float i, float j, float k, float l, float m, float n, float o, float p,
- float q, float s, float t, float u, float v, float w, float x, float y)
-{
- float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+v+w+x+y;
- fprintf(out,"float f(24*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,v,w,x,y);
- fflush(out);
- return r;
-}
-
-/* double tests */
-double ABI_ATTR d_d (double a)
-{
- double r=a+1.0;
- fprintf(out,"double f(double):(%g)",a);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d2 (double a, double b)
-{
- double r=a+b;
- fprintf(out,"double f(2*double):(%g,%g)",a,b);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d4 (double a, double b, double c, double d)
-{
- double r=a+b+c+d;
- fprintf(out,"double f(4*double):(%g,%g,%g,%g)",a,b,c,d);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d8 (double a, double b, double c, double d, double e, double f,
- double g, double h)
-{
- double r=a+b+c+d+e+f+g+h;
- fprintf(out,"double f(8*double):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d16 (double a, double b, double c, double d, double e, double f,
- double g, double h, double i, double j, double k, double l,
- double m, double n, double o, double p)
-{
- double r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
- fprintf(out,"double f(16*double):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
- fflush(out);
- return r;
-}
-
-/* pointer tests */
-void* ABI_ATTR vp_vpdpcpsp (void* a, double* b, char* c, Int* d)
-{
- void* ret = (char*)b + 1;
- fprintf(out,"void* f(void*,double*,char*,Int*):(0x%p,0x%p,0x%p,0x%p)",a,b,c,d);
- fflush(out);
- return ret;
-}
-
-/* mixed number tests */
-uchar ABI_ATTR uc_ucsil (uchar a, ushort b, uint c, ulong d)
-{
- uchar r = (uchar)-1;
- fprintf(out,"uchar f(uchar,ushort,uint,ulong):(%u,%u,%u,%lu)",a,b,c,d);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_iidd (int a, int b, double c, double d)
-{
- double r = a+b+c+d;
- fprintf(out,"double f(int,int,double,double):(%d,%d,%g,%g)",a,b,c,d);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_iiidi (int a, int b, int c, double d, int e)
-{
- double r = a+b+c+d+e;
- fprintf(out,"double f(int,int,int,double,int):(%d,%d,%d,%g,%d)",a,b,c,d,e);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_idid (int a, double b, int c, double d)
-{
- double r = a+b+c+d;
- fprintf(out,"double f(int,double,int,double):(%d,%g,%d,%g)",a,b,c,d);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_fdi (float a, double b, int c)
-{
- double r = a+b+c;
- fprintf(out,"double f(float,double,int):(%g,%g,%d)",a,b,c);
- fflush(out);
- return r;
-}
-ushort ABI_ATTR us_cdcd (char a, double b, char c, double d)
-{
- ushort r = (ushort)(a + b + c + d);
- fprintf(out,"ushort f(char,double,char,double):('%c',%g,'%c',%g)",a,b,c,d);
- fflush(out);
- return r;
-}
-
-long long ABI_ATTR ll_iiilli (int a, int b, int c, long long d, int e)
-{
- long long r = (long long)(int)a+(long long)(int)b+(long long)(int)c+d+(long long)(int)e;
- fprintf(out,"long long f(int,int,int,long long,int):(%d,%d,%d,0x%lx%08lx,%d)",a,b,c,(long)(d>>32),(long)(d&0xffffffff),e);
- fflush(out);
- return r;
-}
-long long ABI_ATTR ll_flli (float a, long long b, int c)
-{
- long long r = (long long)(int)a + b + (long long)c;
- fprintf(out,"long long f(float,long long,int):(%g,0x%lx%08lx,0x%lx)",a,(long)(b>>32),(long)(b&0xffffffff),(long)c);
- fflush(out);
- return r;
-}
-
-float ABI_ATTR f_fi (float a, int z)
-{
- float r = a+z;
- fprintf(out,"float f(float,int):(%g,%d)",a,z);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f2i (float a, float b, int z)
-{
- float r = a+b+z;
- fprintf(out,"float f(2*float,int):(%g,%g,%d)",a,b,z);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f3i (float a, float b, float c, int z)
-{
- float r = a+b+c+z;
- fprintf(out,"float f(3*float,int):(%g,%g,%g,%d)",a,b,c,z);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f4i (float a, float b, float c, float d, int z)
-{
- float r = a+b+c+d+z;
- fprintf(out,"float f(4*float,int):(%g,%g,%g,%g,%d)",a,b,c,d,z);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f7i (float a, float b, float c, float d, float e, float f, float g,
- int z)
-{
- float r = a+b+c+d+e+f+g+z;
- fprintf(out,"float f(7*float,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f8i (float a, float b, float c, float d, float e, float f, float g,
- float h, int z)
-{
- float r = a+b+c+d+e+f+g+h+z;
- fprintf(out,"float f(8*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f12i (float a, float b, float c, float d, float e, float f, float g,
- float h, float i, float j, float k, float l, int z)
-{
- float r = a+b+c+d+e+f+g+h+i+j+k+l+z;
- fprintf(out,"float f(12*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z);
- fflush(out);
- return r;
-}
-float ABI_ATTR f_f13i (float a, float b, float c, float d, float e, float f, float g,
- float h, float i, float j, float k, float l, float m, int z)
-{
- float r = a+b+c+d+e+f+g+h+i+j+k+l+m+z;
- fprintf(out,"float f(13*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z);
- fflush(out);
- return r;
-}
-
-double ABI_ATTR d_di (double a, int z)
-{
- double r = a+z;
- fprintf(out,"double f(double,int):(%g,%d)",a,z);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d2i (double a, double b, int z)
-{
- double r = a+b+z;
- fprintf(out,"double f(2*double,int):(%g,%g,%d)",a,b,z);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d3i (double a, double b, double c, int z)
-{
- double r = a+b+c+z;
- fprintf(out,"double f(3*double,int):(%g,%g,%g,%d)",a,b,c,z);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d4i (double a, double b, double c, double d, int z)
-{
- double r = a+b+c+d+z;
- fprintf(out,"double f(4*double,int):(%g,%g,%g,%g,%d)",a,b,c,d,z);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d7i (double a, double b, double c, double d, double e, double f,
- double g, int z)
-{
- double r = a+b+c+d+e+f+g+z;
- fprintf(out,"double f(7*double,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d8i (double a, double b, double c, double d, double e, double f,
- double g, double h, int z)
-{
- double r = a+b+c+d+e+f+g+h+z;
- fprintf(out,"double f(8*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d12i (double a, double b, double c, double d, double e, double f,
- double g, double h, double i, double j, double k, double l,
- int z)
-{
- double r = a+b+c+d+e+f+g+h+i+j+k+l+z;
- fprintf(out,"double f(12*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d13i (double a, double b, double c, double d, double e, double f,
- double g, double h, double i, double j, double k, double l,
- double m, int z)
-{
- double r = a+b+c+d+e+f+g+h+i+j+k+l+m+z;
- fprintf(out,"double f(13*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z);
- fflush(out);
- return r;
-}
-
-/* small structure return tests */
-Size1 ABI_ATTR S1_v (void)
-{
- fprintf(out,"Size1 f(void):");
- fflush(out);
- return Size1_1;
-}
-Size2 ABI_ATTR S2_v (void)
-{
- fprintf(out,"Size2 f(void):");
- fflush(out);
- return Size2_1;
-}
-Size3 ABI_ATTR S3_v (void)
-{
- fprintf(out,"Size3 f(void):");
- fflush(out);
- return Size3_1;
-}
-Size4 ABI_ATTR S4_v (void)
-{
- fprintf(out,"Size4 f(void):");
- fflush(out);
- return Size4_1;
-}
-Size7 ABI_ATTR S7_v (void)
-{
- fprintf(out,"Size7 f(void):");
- fflush(out);
- return Size7_1;
-}
-Size8 ABI_ATTR S8_v (void)
-{
- fprintf(out,"Size8 f(void):");
- fflush(out);
- return Size8_1;
-}
-Size12 ABI_ATTR S12_v (void)
-{
- fprintf(out,"Size12 f(void):");
- fflush(out);
- return Size12_1;
-}
-Size15 ABI_ATTR S15_v (void)
-{
- fprintf(out,"Size15 f(void):");
- fflush(out);
- return Size15_1;
-}
-Size16 ABI_ATTR S16_v (void)
-{
- fprintf(out,"Size16 f(void):");
- fflush(out);
- return Size16_1;
-}
-
-/* structure tests */
-Int ABI_ATTR I_III (Int a, Int b, Int c)
-{
- Int r;
- r.x = a.x + b.x + c.x;
- fprintf(out,"Int f(Int,Int,Int):({%d},{%d},{%d})",a.x,b.x,c.x);
- fflush(out);
- return r;
-}
-Char ABI_ATTR C_CdC (Char a, double b, Char c)
-{
- Char r;
- r.x = (a.x + c.x)/2;
- fprintf(out,"Char f(Char,double,Char):({'%c'},%g,{'%c'})",a.x,b,c.x);
- fflush(out);
- return r;
-}
-Float ABI_ATTR F_Ffd (Float a, float b, double c)
-{
- Float r;
- r.x = (float) (a.x + b + c);
- fprintf(out,"Float f(Float,float,double):({%g},%g,%g)",a.x,b,c);
- fflush(out);
- return r;
-}
-Double ABI_ATTR D_fDd (float a, Double b, double c)
-{
- Double r;
- r.x = a + b.x + c;
- fprintf(out,"Double f(float,Double,double):(%g,{%g},%g)",a,b.x,c);
- fflush(out);
- return r;
-}
-Double ABI_ATTR D_Dfd (Double a, float b, double c)
-{
- Double r;
- r.x = a.x + b + c;
- fprintf(out,"Double f(Double,float,double):({%g},%g,%g)",a.x,b,c);
- fflush(out);
- return r;
-}
-J ABI_ATTR J_JiJ (J a, int b, J c)
-{
- J r;
- r.l1 = a.l1+c.l1; r.l2 = a.l2+b+c.l2;
- fprintf(out,"J f(J,int,J):({%ld,%ld},%d,{%ld,%ld})",a.l1,a.l2,b,c.l1,c.l2);
- fflush(out);
- return r;
-}
-T ABI_ATTR T_TcT (T a, char b, T c)
-{
- T r;
- r.c[0]='b'; r.c[1]=c.c[1]; r.c[2]=c.c[2];
- fprintf(out,"T f(T,char,T):({\"%c%c%c\"},'%c',{\"%c%c%c\"})",a.c[0],a.c[1],a.c[2],b,c.c[0],c.c[1],c.c[2]);
- fflush(out);
- return r;
-}
-X ABI_ATTR X_BcdB (B a, char b, double c, B d)
-{
- static X xr={"return val",'R'};
- X r;
- r = xr;
- r.c1 = b;
- fprintf(out,"X f(B,char,double,B):({%g,{%d,%d,%d}},'%c',%g,{%g,{%d,%d,%d}})",
- a.d,a.i[0],a.i[1],a.i[2],b,c,d.d,d.i[0],d.i[1],d.i[2]);
- fflush(out);
- return r;
-}
-
-/* Test for cases where some argument (especially structure, 'long long', or
- 'double') may be passed partially in general-purpose argument registers
- and partially on the stack. Different ABIs pass between 4 and 8 arguments
- (or none) in general-purpose argument registers. */
-
-long ABI_ATTR l_l0K (K b, long c)
-{
- long r = b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(K,long):(%ld,%ld,%ld,%ld,%ld)",b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- return r;
-}
-long ABI_ATTR l_l1K (long a1, K b, long c)
-{
- long r = a1 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld)",a1,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- return r;
-}
-long ABI_ATTR l_l2K (long a1, long a2, K b, long c)
-{
- long r = a1 + a2 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(2*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- return r;
-}
-long ABI_ATTR l_l3K (long a1, long a2, long a3, K b, long c)
-{
- long r = a1 + a2 + a3 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(3*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- return r;
-}
-long ABI_ATTR l_l4K (long a1, long a2, long a3, long a4, K b, long c)
-{
- long r = a1 + a2 + a3 + a4 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(4*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- return r;
-}
-long ABI_ATTR l_l5K (long a1, long a2, long a3, long a4, long a5, K b, long c)
-{
- long r = a1 + a2 + a3 + a4 + a5 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(5*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- return r;
-}
-long ABI_ATTR l_l6K (long a1, long a2, long a3, long a4, long a5, long a6, K b, long c)
-{
- long r = a1 + a2 + a3 + a4 + a5 + a6 + b.l1 + b.l2 + b.l3 + b.l4 + c;
- fprintf(out,"long f(6*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,a6,b.l1,b.l2,b.l3,b.l4,c);
- fflush(out);
- return r;
-}
-/* These tests is crafted on the knowledge that for all known ABIs:
- * 17 > number of floating-point argument registers,
- * 3 < number of general-purpose argument registers < 3 + 6. */
-float ABI_ATTR f_f17l3L (float a, float b, float c, float d, float e, float f, float g,
- float h, float i, float j, float k, float l, float m, float n,
- float o, float p, float q,
- long s, long t, long u, L z)
-{
- float r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6;
- fprintf(out,"float f(17*float,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_d17l3L (double a, double b, double c, double d, double e, double f,
- double g, double h, double i, double j, double k, double l,
- double m, double n, double o, double p, double q,
- long s, long t, long u, L z)
-{
- double r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6;
- fprintf(out,"double f(17*double,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6);
- fflush(out);
- return r;
-}
-
-long long ABI_ATTR ll_l2ll (long a1, long a2, long long b, long c)
-{
- long long r = (long long) (a1 + a2) + b + c;
- fprintf(out,"long long f(2*long,long long,long):(%ld,%ld,0x%lx%08lx,%ld)",a1,a2,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- return r;
-}
-long long ABI_ATTR ll_l3ll (long a1, long a2, long a3, long long b, long c)
-{
- long long r = (long long) (a1 + a2 + a3) + b + c;
- fprintf(out,"long long f(3*long,long long,long):(%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- return r;
-}
-long long ABI_ATTR ll_l4ll (long a1, long a2, long a3, long a4, long long b, long c)
-{
- long long r = (long long) (a1 + a2 + a3 + a4) + b + c;
- fprintf(out,"long long f(4*long,long long,long):(%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- return r;
-}
-long long ABI_ATTR ll_l5ll (long a1, long a2, long a3, long a4, long a5, long long b, long c)
-{
- long long r = (long long) (a1 + a2 + a3 + a4 + a5) + b + c;
- fprintf(out,"long long f(5*long,long long,long):(%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- return r;
-}
-long long ABI_ATTR ll_l6ll (long a1, long a2, long a3, long a4, long a5, long a6, long long b, long c)
-{
- long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6) + b + c;
- fprintf(out,"long long f(6*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- return r;
-}
-long long ABI_ATTR ll_l7ll (long a1, long a2, long a3, long a4, long a5, long a6, long a7, long long b, long c)
-{
- long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c;
- fprintf(out,"long long f(7*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,a7,(long)(b>>32),(long)(b&0xffffffff),c);
- fflush(out);
- return r;
-}
-
-double ABI_ATTR d_l2d (long a1, long a2, double b, long c)
-{
- double r = (double) (a1 + a2) + b + c;
- fprintf(out,"double f(2*long,double,long):(%ld,%ld,%g,%ld)",a1,a2,b,c);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_l3d (long a1, long a2, long a3, double b, long c)
-{
- double r = (double) (a1 + a2 + a3) + b + c;
- fprintf(out,"double f(3*long,double,long):(%ld,%ld,%ld,%g,%ld)",a1,a2,a3,b,c);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_l4d (long a1, long a2, long a3, long a4, double b, long c)
-{
- double r = (double) (a1 + a2 + a3 + a4) + b + c;
- fprintf(out,"double f(4*long,double,long):(%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,b,c);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_l5d (long a1, long a2, long a3, long a4, long a5, double b, long c)
-{
- double r = (double) (a1 + a2 + a3 + a4 + a5) + b + c;
- fprintf(out,"double f(5*long,double,long):(%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,b,c);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_l6d (long a1, long a2, long a3, long a4, long a5, long a6, double b, long c)
-{
- double r = (double) (a1 + a2 + a3 + a4 + a5 + a6) + b + c;
- fprintf(out,"double f(6*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,b,c);
- fflush(out);
- return r;
-}
-double ABI_ATTR d_l7d (long a1, long a2, long a3, long a4, long a5, long a6, long a7, double b, long c)
-{
- double r = (double) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c;
- fprintf(out,"double f(7*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,a7,b,c);
- fflush(out);
- return r;
-}
+/*
+ * Copyright 1993 Bill Triggs <Bill.Triggs@inrialpes.fr>
+ * Copyright 1995-2017 Bruno Haible <bruno@clisp.org>
+ *
+ * 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 3 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, see <http://www.gnu.org/licenses/>.
+ */
+
+/* This file defines test functions of selected signatures, that exercise
+ dark corners of the various ABIs. */
+
+#include <stdio.h>
+
+FILE* out;
+
+#define uchar unsigned char
+#define ushort unsigned short
+#define uint unsigned int
+#define ulong unsigned long
+
+typedef struct { char x; } Char;
+typedef struct { short x; } Short;
+typedef struct { int x; } Int;
+typedef struct { long x; } Long;
+typedef struct { float x; } Float;
+typedef struct { double x; } Double;
+typedef struct { char c; float f; } A;
+typedef struct { double d; int i[3]; } B;
+typedef struct { long l1; long l2; } J;
+typedef struct { long l1; long l2; long l3; long l4; } K;
+typedef struct { long l1; long l2; long l3; long l4; long l5; long l6; } L;
+typedef struct { char x1; } Size1;
+typedef struct { char x1; char x2; } Size2;
+typedef struct { char x1; char x2; char x3; } Size3;
+typedef struct { char x1; char x2; char x3; char x4; } Size4;
+typedef struct {
+ char x1; char x2; char x3; char x4; char x5; char x6; char x7;
+} Size7;
+typedef struct {
+ char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8;
+} Size8;
+typedef struct {
+ char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8;
+ char x9; char x10; char x11; char x12;
+} Size12;
+typedef struct {
+ char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8;
+ char x9; char x10; char x11; char x12; char x13; char x14; char x15;
+} Size15;
+typedef struct {
+ char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8;
+ char x9; char x10; char x11; char x12; char x13; char x14; char x15; char x16;
+} Size16;
+typedef struct { char c[3]; } T;
+typedef struct { char c[33],c1; } X;
+
+char c1='a', c2=127, c3=(char)128, c4=(char)255, c5=-1;
+short s1=32767, s2=(short)32768, s3=3, s4=4, s5=5, s6=6, s7=7, s8=8, s9=9;
+int i1=1, i2=2, i3=3, i4=4, i5=5, i6=6, i7=7, i8=8, i9=9,
+ i10=11, i11=12, i12=13, i13=14, i14=15, i15=16, i16=17;
+long l1=1, l2=2, l3=3, l4=4, l5=5, l6=6, l7=7, l8=8, l9=9;
+long long ll1 = 3875056143130689530LL;
+float f1=0.1f, f2=0.2f, f3=0.3f, f4=0.4f, f5=0.5f, f6=0.6f, f7=0.7f, f8=0.8f, f9=0.9f,
+ f10=1.1f, f11=1.2f, f12=1.3f, f13=1.4f, f14=1.5f, f15=1.6f, f16=1.7f, f17=1.8f,
+ f18=1.9f, f19=2.1f, f20=2.2f, f21=2.3f, f22=2.4f, f23=2.5f, f24=2.6f;
+double d1=0.1, d2=0.2, d3=0.3, d4=0.4, d5=0.5, d6=0.6, d7=0.7, d8=0.8, d9=0.9,
+ d10=1.1, d11=1.2, d12=1.3, d13=1.4, d14=1.5, d15=1.6, d16=1.7, d17=1.8;
+
+uchar uc1='a', uc2=127, uc3=128, uc4=255, uc5=(uchar)-1;
+ushort us1=1, us2=2, us3=3, us4=4, us5=5, us6=6, us7=7, us8=8, us9=9;
+uint ui1=1, ui2=2, ui3=3, ui4=4, ui5=5, ui6=6, ui7=7, ui8=8, ui9=9;
+ulong ul1=1, ul2=2, ul3=3, ul4=4, ul5=5, ul6=6, ul7=7, ul8=8, ul9=9;
+
+char *str1="hello",str2[]="goodbye",*str3="still here?";
+Char C1={'A'}, C2={'B'}, C3={'C'}, C4={'\377'}, C5={(char)(-1)};
+Short S1={1}, S2={2}, S3={3}, S4={4}, S5={5}, S6={6}, S7={7}, S8={8}, S9={9};
+Int I1={1}, I2={2}, I3={3}, I4={4}, I5={5}, I6={6}, I7={7}, I8={8}, I9={9};
+Float F1={0.1f}, F2={0.2f}, F3={0.3f}, F4={0.4f}, F5={0.5f}, F6={0.6f}, F7={0.7f}, F8={0.8f}, F9={0.9f};
+Double D1={0.1}, D2={0.2}, D3={0.3}, D4={0.4}, D5={0.5}, D6={0.6}, D7={0.7}, D8={0.8}, D9={0.9};
+
+A A1={'a',0.1f},A2={'b',0.2f},A3={'\377',0.3f};
+B B1={0.1,{1,2,3}},B2={0.2,{5,4,3}};
+J J1={47,11},J2={73,55};
+K K1={19,69,12,28};
+L L1={561,1105,1729,2465,2821,6601}; /* A002997 */
+Size1 Size1_1={'a'};
+Size2 Size2_1={'a','b'};
+Size3 Size3_1={'a','b','c'};
+Size4 Size4_1={'a','b','c','d'};
+Size7 Size7_1={'a','b','c','d','e','f','g'};
+Size8 Size8_1={'a','b','c','d','e','f','g','h'};
+Size12 Size12_1={'a','b','c','d','e','f','g','h','i','j','k','l'};
+Size15 Size15_1={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o'};
+Size16 Size16_1={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'};
+T T1={{'t','h','e'}},T2={{'f','o','x'}};
+X X1={"abcdefghijklmnopqrstuvwxyzABCDEF",'G'}, X2={"123",'9'}, X3={"return-return-return",'R'};
+
+#if defined(__GNUC__)
+#define __STDCALL__ __attribute__((stdcall))
+#define __THISCALL__ __attribute__((thiscall))
+#define __FASTCALL__ __attribute__((fastcall))
+#define __MSABI__ __attribute__((ms_abi))
+#else
+#define __STDCALL__ __stdcall
+#define __THISCALL__ __thiscall
+#define __FASTCALL__ __fastcall
+#endif
+
+#ifndef ABI_ATTR
+#define ABI_ATTR
+#endif
+
+/* void tests */
+void ABI_ATTR v_v (void)
+{
+ fprintf(out,"void f(void):\n");
+ fflush(out);
+}
+
+/* int tests */
+int ABI_ATTR i_v (void)
+{
+ int r=99;
+ fprintf(out,"int f(void):");
+ fflush(out);
+ return r;
+}
+int ABI_ATTR i_i (int a)
+{
+ int r=a+1;
+ fprintf(out,"int f(int):(%d)",a);
+ fflush(out);
+ return r;
+}
+int ABI_ATTR i_i2 (int a, int b)
+{
+ int r=a+b;
+ fprintf(out,"int f(2*int):(%d,%d)",a,b);
+ fflush(out);
+ return r;
+}
+int ABI_ATTR i_i4 (int a, int b, int c, int d)
+{
+ int r=a+b+c+d;
+ fprintf(out,"int f(4*int):(%d,%d,%d,%d)",a,b,c,d);
+ fflush(out);
+ return r;
+}
+int ABI_ATTR i_i8 (int a, int b, int c, int d, int e, int f, int g, int h)
+{
+ int r=a+b+c+d+e+f+g+h;
+ fprintf(out,"int f(8*int):(%d,%d,%d,%d,%d,%d,%d,%d)",a,b,c,d,e,f,g,h);
+ fflush(out);
+ return r;
+}
+int ABI_ATTR i_i16 (int a, int b, int c, int d, int e, int f, int g, int h,
+ int i, int j, int k, int l, int m, int n, int o, int p)
+{
+ int r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
+ fprintf(out,"int f(16*int):(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
+ a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
+ fflush(out);
+ return r;
+}
+
+/* float tests */
+float ABI_ATTR f_f (float a)
+{
+ float r=a+1.0f;
+ fprintf(out,"float f(float):(%g)",a);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f2 (float a, float b)
+{
+ float r=a+b;
+ fprintf(out,"float f(2*float):(%g,%g)",a,b);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f4 (float a, float b, float c, float d)
+{
+ float r=a+b+c+d;
+ fprintf(out,"float f(4*float):(%g,%g,%g,%g)",a,b,c,d);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f8 (float a, float b, float c, float d, float e, float f,
+ float g, float h)
+{
+ float r=a+b+c+d+e+f+g+h;
+ fprintf(out,"float f(8*float):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f16 (float a, float b, float c, float d, float e, float f, float g, float h,
+ float i, float j, float k, float l, float m, float n, float o, float p)
+{
+ float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
+ fprintf(out,"float f(16*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f24 (float a, float b, float c, float d, float e, float f, float g, float h,
+ float i, float j, float k, float l, float m, float n, float o, float p,
+ float q, float s, float t, float u, float v, float w, float x, float y)
+{
+ float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+v+w+x+y;
+ fprintf(out,"float f(24*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,v,w,x,y);
+ fflush(out);
+ return r;
+}
+
+/* double tests */
+double ABI_ATTR d_d (double a)
+{
+ double r=a+1.0;
+ fprintf(out,"double f(double):(%g)",a);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d2 (double a, double b)
+{
+ double r=a+b;
+ fprintf(out,"double f(2*double):(%g,%g)",a,b);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d4 (double a, double b, double c, double d)
+{
+ double r=a+b+c+d;
+ fprintf(out,"double f(4*double):(%g,%g,%g,%g)",a,b,c,d);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d8 (double a, double b, double c, double d, double e, double f,
+ double g, double h)
+{
+ double r=a+b+c+d+e+f+g+h;
+ fprintf(out,"double f(8*double):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d16 (double a, double b, double c, double d, double e, double f,
+ double g, double h, double i, double j, double k, double l,
+ double m, double n, double o, double p)
+{
+ double r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p;
+ fprintf(out,"double f(16*double):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);
+ fflush(out);
+ return r;
+}
+
+/* pointer tests */
+void* ABI_ATTR vp_vpdpcpsp (void* a, double* b, char* c, Int* d)
+{
+ void* ret = (char*)b + 1;
+ fprintf(out,"void* f(void*,double*,char*,Int*):(0x%p,0x%p,0x%p,0x%p)",a,b,c,d);
+ fflush(out);
+ return ret;
+}
+
+/* mixed number tests */
+uchar ABI_ATTR uc_ucsil (uchar a, ushort b, uint c, ulong d)
+{
+ uchar r = (uchar)-1;
+ fprintf(out,"uchar f(uchar,ushort,uint,ulong):(%u,%u,%u,%lu)",a,b,c,d);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_iidd (int a, int b, double c, double d)
+{
+ double r = a+b+c+d;
+ fprintf(out,"double f(int,int,double,double):(%d,%d,%g,%g)",a,b,c,d);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_iiidi (int a, int b, int c, double d, int e)
+{
+ double r = a+b+c+d+e;
+ fprintf(out,"double f(int,int,int,double,int):(%d,%d,%d,%g,%d)",a,b,c,d,e);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_idid (int a, double b, int c, double d)
+{
+ double r = a+b+c+d;
+ fprintf(out,"double f(int,double,int,double):(%d,%g,%d,%g)",a,b,c,d);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_fdi (float a, double b, int c)
+{
+ double r = a+b+c;
+ fprintf(out,"double f(float,double,int):(%g,%g,%d)",a,b,c);
+ fflush(out);
+ return r;
+}
+ushort ABI_ATTR us_cdcd (char a, double b, char c, double d)
+{
+ ushort r = (ushort)(a + b + c + d);
+ fprintf(out,"ushort f(char,double,char,double):('%c',%g,'%c',%g)",a,b,c,d);
+ fflush(out);
+ return r;
+}
+
+long long ABI_ATTR ll_iiilli (int a, int b, int c, long long d, int e)
+{
+ long long r = (long long)(int)a+(long long)(int)b+(long long)(int)c+d+(long long)(int)e;
+ fprintf(out,"long long f(int,int,int,long long,int):(%d,%d,%d,0x%lx%08lx,%d)",a,b,c,(long)(d>>32),(long)(d&0xffffffff),e);
+ fflush(out);
+ return r;
+}
+long long ABI_ATTR ll_flli (float a, long long b, int c)
+{
+ long long r = (long long)(int)a + b + (long long)c;
+ fprintf(out,"long long f(float,long long,int):(%g,0x%lx%08lx,0x%lx)",a,(long)(b>>32),(long)(b&0xffffffff),(long)c);
+ fflush(out);
+ return r;
+}
+
+float ABI_ATTR f_fi (float a, int z)
+{
+ float r = a+z;
+ fprintf(out,"float f(float,int):(%g,%d)",a,z);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f2i (float a, float b, int z)
+{
+ float r = a+b+z;
+ fprintf(out,"float f(2*float,int):(%g,%g,%d)",a,b,z);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f3i (float a, float b, float c, int z)
+{
+ float r = a+b+c+z;
+ fprintf(out,"float f(3*float,int):(%g,%g,%g,%d)",a,b,c,z);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f4i (float a, float b, float c, float d, int z)
+{
+ float r = a+b+c+d+z;
+ fprintf(out,"float f(4*float,int):(%g,%g,%g,%g,%d)",a,b,c,d,z);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f7i (float a, float b, float c, float d, float e, float f, float g,
+ int z)
+{
+ float r = a+b+c+d+e+f+g+z;
+ fprintf(out,"float f(7*float,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f8i (float a, float b, float c, float d, float e, float f, float g,
+ float h, int z)
+{
+ float r = a+b+c+d+e+f+g+h+z;
+ fprintf(out,"float f(8*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f12i (float a, float b, float c, float d, float e, float f, float g,
+ float h, float i, float j, float k, float l, int z)
+{
+ float r = a+b+c+d+e+f+g+h+i+j+k+l+z;
+ fprintf(out,"float f(12*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z);
+ fflush(out);
+ return r;
+}
+float ABI_ATTR f_f13i (float a, float b, float c, float d, float e, float f, float g,
+ float h, float i, float j, float k, float l, float m, int z)
+{
+ float r = a+b+c+d+e+f+g+h+i+j+k+l+m+z;
+ fprintf(out,"float f(13*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z);
+ fflush(out);
+ return r;
+}
+
+double ABI_ATTR d_di (double a, int z)
+{
+ double r = a+z;
+ fprintf(out,"double f(double,int):(%g,%d)",a,z);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d2i (double a, double b, int z)
+{
+ double r = a+b+z;
+ fprintf(out,"double f(2*double,int):(%g,%g,%d)",a,b,z);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d3i (double a, double b, double c, int z)
+{
+ double r = a+b+c+z;
+ fprintf(out,"double f(3*double,int):(%g,%g,%g,%d)",a,b,c,z);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d4i (double a, double b, double c, double d, int z)
+{
+ double r = a+b+c+d+z;
+ fprintf(out,"double f(4*double,int):(%g,%g,%g,%g,%d)",a,b,c,d,z);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d7i (double a, double b, double c, double d, double e, double f,
+ double g, int z)
+{
+ double r = a+b+c+d+e+f+g+z;
+ fprintf(out,"double f(7*double,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d8i (double a, double b, double c, double d, double e, double f,
+ double g, double h, int z)
+{
+ double r = a+b+c+d+e+f+g+h+z;
+ fprintf(out,"double f(8*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d12i (double a, double b, double c, double d, double e, double f,
+ double g, double h, double i, double j, double k, double l,
+ int z)
+{
+ double r = a+b+c+d+e+f+g+h+i+j+k+l+z;
+ fprintf(out,"double f(12*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d13i (double a, double b, double c, double d, double e, double f,
+ double g, double h, double i, double j, double k, double l,
+ double m, int z)
+{
+ double r = a+b+c+d+e+f+g+h+i+j+k+l+m+z;
+ fprintf(out,"double f(13*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z);
+ fflush(out);
+ return r;
+}
+
+/* small structure return tests */
+Size1 ABI_ATTR S1_v (void)
+{
+ fprintf(out,"Size1 f(void):");
+ fflush(out);
+ return Size1_1;
+}
+Size2 ABI_ATTR S2_v (void)
+{
+ fprintf(out,"Size2 f(void):");
+ fflush(out);
+ return Size2_1;
+}
+Size3 ABI_ATTR S3_v (void)
+{
+ fprintf(out,"Size3 f(void):");
+ fflush(out);
+ return Size3_1;
+}
+Size4 ABI_ATTR S4_v (void)
+{
+ fprintf(out,"Size4 f(void):");
+ fflush(out);
+ return Size4_1;
+}
+Size7 ABI_ATTR S7_v (void)
+{
+ fprintf(out,"Size7 f(void):");
+ fflush(out);
+ return Size7_1;
+}
+Size8 ABI_ATTR S8_v (void)
+{
+ fprintf(out,"Size8 f(void):");
+ fflush(out);
+ return Size8_1;
+}
+Size12 ABI_ATTR S12_v (void)
+{
+ fprintf(out,"Size12 f(void):");
+ fflush(out);
+ return Size12_1;
+}
+Size15 ABI_ATTR S15_v (void)
+{
+ fprintf(out,"Size15 f(void):");
+ fflush(out);
+ return Size15_1;
+}
+Size16 ABI_ATTR S16_v (void)
+{
+ fprintf(out,"Size16 f(void):");
+ fflush(out);
+ return Size16_1;
+}
+
+/* structure tests */
+Int ABI_ATTR I_III (Int a, Int b, Int c)
+{
+ Int r;
+ r.x = a.x + b.x + c.x;
+ fprintf(out,"Int f(Int,Int,Int):({%d},{%d},{%d})",a.x,b.x,c.x);
+ fflush(out);
+ return r;
+}
+Char ABI_ATTR C_CdC (Char a, double b, Char c)
+{
+ Char r;
+ r.x = (a.x + c.x)/2;
+ fprintf(out,"Char f(Char,double,Char):({'%c'},%g,{'%c'})",a.x,b,c.x);
+ fflush(out);
+ return r;
+}
+Float ABI_ATTR F_Ffd (Float a, float b, double c)
+{
+ Float r;
+ r.x = (float) (a.x + b + c);
+ fprintf(out,"Float f(Float,float,double):({%g},%g,%g)",a.x,b,c);
+ fflush(out);
+ return r;
+}
+Double ABI_ATTR D_fDd (float a, Double b, double c)
+{
+ Double r;
+ r.x = a + b.x + c;
+ fprintf(out,"Double f(float,Double,double):(%g,{%g},%g)",a,b.x,c);
+ fflush(out);
+ return r;
+}
+Double ABI_ATTR D_Dfd (Double a, float b, double c)
+{
+ Double r;
+ r.x = a.x + b + c;
+ fprintf(out,"Double f(Double,float,double):({%g},%g,%g)",a.x,b,c);
+ fflush(out);
+ return r;
+}
+J ABI_ATTR J_JiJ (J a, int b, J c)
+{
+ J r;
+ r.l1 = a.l1+c.l1; r.l2 = a.l2+b+c.l2;
+ fprintf(out,"J f(J,int,J):({%ld,%ld},%d,{%ld,%ld})",a.l1,a.l2,b,c.l1,c.l2);
+ fflush(out);
+ return r;
+}
+T ABI_ATTR T_TcT (T a, char b, T c)
+{
+ T r;
+ r.c[0]='b'; r.c[1]=c.c[1]; r.c[2]=c.c[2];
+ fprintf(out,"T f(T,char,T):({\"%c%c%c\"},'%c',{\"%c%c%c\"})",a.c[0],a.c[1],a.c[2],b,c.c[0],c.c[1],c.c[2]);
+ fflush(out);
+ return r;
+}
+X ABI_ATTR X_BcdB (B a, char b, double c, B d)
+{
+ static X xr={"return val",'R'};
+ X r;
+ r = xr;
+ r.c1 = b;
+ fprintf(out,"X f(B,char,double,B):({%g,{%d,%d,%d}},'%c',%g,{%g,{%d,%d,%d}})",
+ a.d,a.i[0],a.i[1],a.i[2],b,c,d.d,d.i[0],d.i[1],d.i[2]);
+ fflush(out);
+ return r;
+}
+
+/* Test for cases where some argument (especially structure, 'long long', or
+ 'double') may be passed partially in general-purpose argument registers
+ and partially on the stack. Different ABIs pass between 4 and 8 arguments
+ (or none) in general-purpose argument registers. */
+
+long ABI_ATTR l_l0K (K b, long c)
+{
+ long r = b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(K,long):(%ld,%ld,%ld,%ld,%ld)",b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ return r;
+}
+long ABI_ATTR l_l1K (long a1, K b, long c)
+{
+ long r = a1 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld)",a1,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ return r;
+}
+long ABI_ATTR l_l2K (long a1, long a2, K b, long c)
+{
+ long r = a1 + a2 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(2*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ return r;
+}
+long ABI_ATTR l_l3K (long a1, long a2, long a3, K b, long c)
+{
+ long r = a1 + a2 + a3 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(3*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ return r;
+}
+long ABI_ATTR l_l4K (long a1, long a2, long a3, long a4, K b, long c)
+{
+ long r = a1 + a2 + a3 + a4 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(4*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ return r;
+}
+long ABI_ATTR l_l5K (long a1, long a2, long a3, long a4, long a5, K b, long c)
+{
+ long r = a1 + a2 + a3 + a4 + a5 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(5*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ return r;
+}
+long ABI_ATTR l_l6K (long a1, long a2, long a3, long a4, long a5, long a6, K b, long c)
+{
+ long r = a1 + a2 + a3 + a4 + a5 + a6 + b.l1 + b.l2 + b.l3 + b.l4 + c;
+ fprintf(out,"long f(6*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,a6,b.l1,b.l2,b.l3,b.l4,c);
+ fflush(out);
+ return r;
+}
+/* These tests is crafted on the knowledge that for all known ABIs:
+ * 17 > number of floating-point argument registers,
+ * 3 < number of general-purpose argument registers < 3 + 6. */
+float ABI_ATTR f_f17l3L (float a, float b, float c, float d, float e, float f, float g,
+ float h, float i, float j, float k, float l, float m, float n,
+ float o, float p, float q,
+ long s, long t, long u, L z)
+{
+ float r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6;
+ fprintf(out,"float f(17*float,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_d17l3L (double a, double b, double c, double d, double e, double f,
+ double g, double h, double i, double j, double k, double l,
+ double m, double n, double o, double p, double q,
+ long s, long t, long u, L z)
+{
+ double r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6;
+ fprintf(out,"double f(17*double,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6);
+ fflush(out);
+ return r;
+}
+
+long long ABI_ATTR ll_l2ll (long a1, long a2, long long b, long c)
+{
+ long long r = (long long) (a1 + a2) + b + c;
+ fprintf(out,"long long f(2*long,long long,long):(%ld,%ld,0x%lx%08lx,%ld)",a1,a2,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ return r;
+}
+long long ABI_ATTR ll_l3ll (long a1, long a2, long a3, long long b, long c)
+{
+ long long r = (long long) (a1 + a2 + a3) + b + c;
+ fprintf(out,"long long f(3*long,long long,long):(%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ return r;
+}
+long long ABI_ATTR ll_l4ll (long a1, long a2, long a3, long a4, long long b, long c)
+{
+ long long r = (long long) (a1 + a2 + a3 + a4) + b + c;
+ fprintf(out,"long long f(4*long,long long,long):(%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ return r;
+}
+long long ABI_ATTR ll_l5ll (long a1, long a2, long a3, long a4, long a5, long long b, long c)
+{
+ long long r = (long long) (a1 + a2 + a3 + a4 + a5) + b + c;
+ fprintf(out,"long long f(5*long,long long,long):(%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ return r;
+}
+long long ABI_ATTR ll_l6ll (long a1, long a2, long a3, long a4, long a5, long a6, long long b, long c)
+{
+ long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6) + b + c;
+ fprintf(out,"long long f(6*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ return r;
+}
+long long ABI_ATTR ll_l7ll (long a1, long a2, long a3, long a4, long a5, long a6, long a7, long long b, long c)
+{
+ long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c;
+ fprintf(out,"long long f(7*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,a7,(long)(b>>32),(long)(b&0xffffffff),c);
+ fflush(out);
+ return r;
+}
+
+double ABI_ATTR d_l2d (long a1, long a2, double b, long c)
+{
+ double r = (double) (a1 + a2) + b + c;
+ fprintf(out,"double f(2*long,double,long):(%ld,%ld,%g,%ld)",a1,a2,b,c);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_l3d (long a1, long a2, long a3, double b, long c)
+{
+ double r = (double) (a1 + a2 + a3) + b + c;
+ fprintf(out,"double f(3*long,double,long):(%ld,%ld,%ld,%g,%ld)",a1,a2,a3,b,c);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_l4d (long a1, long a2, long a3, long a4, double b, long c)
+{
+ double r = (double) (a1 + a2 + a3 + a4) + b + c;
+ fprintf(out,"double f(4*long,double,long):(%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,b,c);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_l5d (long a1, long a2, long a3, long a4, long a5, double b, long c)
+{
+ double r = (double) (a1 + a2 + a3 + a4 + a5) + b + c;
+ fprintf(out,"double f(5*long,double,long):(%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,b,c);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_l6d (long a1, long a2, long a3, long a4, long a5, long a6, double b, long c)
+{
+ double r = (double) (a1 + a2 + a3 + a4 + a5 + a6) + b + c;
+ fprintf(out,"double f(6*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,b,c);
+ fflush(out);
+ return r;
+}
+double ABI_ATTR d_l7d (long a1, long a2, long a3, long a4, long a5, long a6, long a7, double b, long c)
+{
+ double r = (double) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c;
+ fprintf(out,"double f(7*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,a7,b,c);
+ fflush(out);
+ return r;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.bhaible/ya.make b/contrib/restricted/libffi/testsuite/libffi.bhaible/ya.make
index d93dd7b8cf..40dfa0bac9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.bhaible/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.bhaible/ya.make
@@ -1,6 +1,6 @@
-# Generated by devtools/yamaker.
-
-RECURSE(
- test-call
- test-callback
-)
+# Generated by devtools/yamaker.
+
+RECURSE(
+ test-call
+ test-callback
+)
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/align_mixed.c b/contrib/restricted/libffi/testsuite/libffi.call/align_mixed.c
index c93365fe88..5d4959ce97 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/align_mixed.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/align_mixed.c
@@ -1,46 +1,46 @@
-/* Area: ffi_call
- Purpose: Check for proper argument alignment.
- Limitations: none.
- PR: none.
- Originator: <twalljava@java.net> (from many_win32.c) */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-static float ABI_ATTR align_arguments(int i1,
- double f2,
- int i3,
- double f4)
-{
- return i1+f2+i3+f4;
-}
-
-int main(void)
-{
- ffi_cif cif;
- ffi_type *args[4] = {
- &ffi_type_sint,
- &ffi_type_double,
- &ffi_type_sint,
- &ffi_type_double
- };
- double fa[2] = {1,2};
- int ia[2] = {1,2};
- void *values[4] = {&ia[0], &fa[0], &ia[1], &fa[1]};
- float f, ff;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 4,
- &ffi_type_float, args) == FFI_OK);
-
- ff = align_arguments(ia[0], fa[0], ia[1], fa[1]);
-
- ffi_call(&cif, FFI_FN(align_arguments), &f, values);
-
- if (f == ff)
- printf("align arguments tests ok!\n");
- else
- CHECK(0);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check for proper argument alignment.
+ Limitations: none.
+ PR: none.
+ Originator: <twalljava@java.net> (from many_win32.c) */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+static float ABI_ATTR align_arguments(int i1,
+ double f2,
+ int i3,
+ double f4)
+{
+ return i1+f2+i3+f4;
+}
+
+int main(void)
+{
+ ffi_cif cif;
+ ffi_type *args[4] = {
+ &ffi_type_sint,
+ &ffi_type_double,
+ &ffi_type_sint,
+ &ffi_type_double
+ };
+ double fa[2] = {1,2};
+ int ia[2] = {1,2};
+ void *values[4] = {&ia[0], &fa[0], &ia[1], &fa[1]};
+ float f, ff;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 4,
+ &ffi_type_float, args) == FFI_OK);
+
+ ff = align_arguments(ia[0], fa[0], ia[1], fa[1]);
+
+ ffi_call(&cif, FFI_FN(align_arguments), &f, values);
+
+ if (f == ff)
+ printf("align arguments tests ok!\n");
+ else
+ CHECK(0);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/align_mixed/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/align_mixed/ya.make
index da97a594bf..71d7583453 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/align_mixed/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/align_mixed/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- align_mixed.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ align_mixed.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/align_stdcall.c b/contrib/restricted/libffi/testsuite/libffi.call/align_stdcall.c
index cd0c13a684..5e5cb860cc 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/align_stdcall.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/align_stdcall.c
@@ -1,46 +1,46 @@
-/* Area: ffi_call
- Purpose: Check for proper argument alignment.
- Limitations: none.
- PR: none.
- Originator: <twalljava@java.net> (from many_win32.c) */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-static float ABI_ATTR align_arguments(int i1,
- double f2,
- int i3,
- double f4)
-{
- return i1+f2+i3+f4;
-}
-
-int main(void)
-{
- ffi_cif cif;
- ffi_type *args[4] = {
- &ffi_type_sint,
- &ffi_type_double,
- &ffi_type_sint,
- &ffi_type_double
- };
- double fa[2] = {1,2};
- int ia[2] = {1,2};
- void *values[4] = {&ia[0], &fa[0], &ia[1], &fa[1]};
- float f, ff;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 4,
- &ffi_type_float, args) == FFI_OK);
-
- ff = align_arguments(ia[0], fa[0], ia[1], fa[1]);;
-
- ffi_call(&cif, FFI_FN(align_arguments), &f, values);
-
- if (f == ff)
- printf("align arguments tests ok!\n");
- else
- CHECK(0);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check for proper argument alignment.
+ Limitations: none.
+ PR: none.
+ Originator: <twalljava@java.net> (from many_win32.c) */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+static float ABI_ATTR align_arguments(int i1,
+ double f2,
+ int i3,
+ double f4)
+{
+ return i1+f2+i3+f4;
+}
+
+int main(void)
+{
+ ffi_cif cif;
+ ffi_type *args[4] = {
+ &ffi_type_sint,
+ &ffi_type_double,
+ &ffi_type_sint,
+ &ffi_type_double
+ };
+ double fa[2] = {1,2};
+ int ia[2] = {1,2};
+ void *values[4] = {&ia[0], &fa[0], &ia[1], &fa[1]};
+ float f, ff;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 4,
+ &ffi_type_float, args) == FFI_OK);
+
+ ff = align_arguments(ia[0], fa[0], ia[1], fa[1]);;
+
+ ffi_call(&cif, FFI_FN(align_arguments), &f, values);
+
+ if (f == ff)
+ printf("align arguments tests ok!\n");
+ else
+ CHECK(0);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/align_stdcall/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/align_stdcall/ya.make
index 33861f204d..1d97a0cd0b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/align_stdcall/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/align_stdcall/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- align_stdcall.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ align_stdcall.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/err_bad_typedef.c b/contrib/restricted/libffi/testsuite/libffi.call/err_bad_typedef.c
index d2779027bc..bf60161861 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/err_bad_typedef.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/err_bad_typedef.c
@@ -1,26 +1,26 @@
-/* Area: ffi_prep_cif
- Purpose: Test error return for bad typedefs.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/6/2007 */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type* arg_types[1];
-
- ffi_type badType = ffi_type_void;
-
- arg_types[0] = NULL;
-
- badType.size = 0;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, &badType,
- arg_types) == FFI_BAD_TYPEDEF);
-
- exit(0);
-}
+/* Area: ffi_prep_cif
+ Purpose: Test error return for bad typedefs.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/6/2007 */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type* arg_types[1];
+
+ ffi_type badType = ffi_type_void;
+
+ arg_types[0] = NULL;
+
+ badType.size = 0;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, &badType,
+ arg_types) == FFI_BAD_TYPEDEF);
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/err_bad_typedef/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/err_bad_typedef/ya.make
index 2ce34ac803..a3e042e54f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/err_bad_typedef/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/err_bad_typedef/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- err_bad_typedef.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ err_bad_typedef.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/ffitest.h b/contrib/restricted/libffi/testsuite/libffi.call/ffitest.h
index c030b7026c..27d12840f8 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/ffitest.h
+++ b/contrib/restricted/libffi/testsuite/libffi.call/ffitest.h
@@ -1,144 +1,144 @@
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <fcntl.h>
-#include <ffi.h>
-
-#define HAVE_STDINT_H
-#define HAVE_INTTYPES_H
-
-#ifndef _MSC_VER
-#define HAVE_MMAP_ANON
-#endif
-
-#if defined HAVE_STDINT_H
-#include <stdint.h>
-#endif
-
-#if defined HAVE_INTTYPES_H
-#include <inttypes.h>
-#endif
-
-#define MAX_ARGS 256
-
-#define CHECK(x) (void)(!(x) ? (abort(), 1) : 0)
-
-/* Define macros so that compilers other than gcc can run the tests. */
-#undef __UNUSED__
-#if defined(__GNUC__)
-#define __UNUSED__ __attribute__((__unused__))
-#define __STDCALL__ __attribute__((stdcall))
-#define __THISCALL__ __attribute__((thiscall))
-#define __FASTCALL__ __attribute__((fastcall))
-#define __MSABI__ __attribute__((ms_abi))
-#else
-#define __UNUSED__
-#define __STDCALL__ __stdcall
-#define __THISCALL__ __thiscall
-#define __FASTCALL__ __fastcall
-#endif
-
-#ifndef ABI_NUM
-#define ABI_NUM FFI_DEFAULT_ABI
-#define ABI_ATTR
-#endif
-
-/* Prefer MAP_ANON(YMOUS) to /dev/zero, since we don't need to keep a
- file open. */
-#ifdef HAVE_MMAP_ANON
-# undef HAVE_MMAP_DEV_ZERO
-
-# include <sys/mman.h>
-# ifndef MAP_FAILED
-# define MAP_FAILED -1
-# endif
-# if !defined (MAP_ANONYMOUS) && defined (MAP_ANON)
-# define MAP_ANONYMOUS MAP_ANON
-# endif
-# define USING_MMAP
-
-#endif
-
-#ifdef HAVE_MMAP_DEV_ZERO
-
-# include <sys/mman.h>
-# ifndef MAP_FAILED
-# define MAP_FAILED -1
-# endif
-# define USING_MMAP
-
-#endif
-
-/* MinGW kludge. */
-#if defined(_WIN64) | defined(_WIN32)
-#define PRIdLL "I64d"
-#define PRIuLL "I64u"
-#else
-#define PRIdLL "lld"
-#define PRIuLL "llu"
-#endif
-
-/* Tru64 UNIX kludge. */
-#if defined(__alpha__) && defined(__osf__)
-/* Tru64 UNIX V4.0 doesn't support %lld/%lld, but long is 64-bit. */
-#undef PRIdLL
-#define PRIdLL "ld"
-#undef PRIuLL
-#define PRIuLL "lu"
-#define PRId8 "hd"
-#define PRIu8 "hu"
-#define PRId64 "ld"
-#define PRIu64 "lu"
-#define PRIuPTR "lu"
-#endif
-
-/* PA HP-UX kludge. */
-#if defined(__hppa__) && defined(__hpux__) && !defined(PRIuPTR)
-#define PRIuPTR "lu"
-#endif
-
-/* IRIX kludge. */
-#if defined(__sgi)
-/* IRIX 6.5 <inttypes.h> provides all definitions, but only for C99
- compilations. */
-#define PRId8 "hhd"
-#define PRIu8 "hhu"
-#if (_MIPS_SZLONG == 32)
-#define PRId64 "lld"
-#define PRIu64 "llu"
-#endif
-/* This doesn't match <inttypes.h>, which always has "lld" here, but the
- arguments are uint64_t, int64_t, which are unsigned long, long for
- 64-bit in <sgidefs.h>. */
-#if (_MIPS_SZLONG == 64)
-#define PRId64 "ld"
-#define PRIu64 "lu"
-#endif
-/* This doesn't match <inttypes.h>, which has "u" here, but the arguments
- are uintptr_t, which is always unsigned long. */
-#define PRIuPTR "lu"
-#endif
-
-/* Solaris < 10 kludge. */
-#if defined(__sun__) && defined(__svr4__) && !defined(PRIuPTR)
-#if defined(__arch64__) || defined (__x86_64__)
-#define PRIuPTR "lu"
-#else
-#define PRIuPTR "u"
-#endif
-#endif
-
-/* MSVC kludge. */
-#if defined _MSC_VER
-#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS)
-#define PRIuPTR "lu"
-#define PRIu8 "u"
-#define PRId8 "d"
-#define PRIu64 "I64u"
-#define PRId64 "I64d"
-#endif
-#endif
-
-#ifndef PRIuPTR
-#define PRIuPTR "u"
-#endif
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <fcntl.h>
+#include <ffi.h>
+
+#define HAVE_STDINT_H
+#define HAVE_INTTYPES_H
+
+#ifndef _MSC_VER
+#define HAVE_MMAP_ANON
+#endif
+
+#if defined HAVE_STDINT_H
+#include <stdint.h>
+#endif
+
+#if defined HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif
+
+#define MAX_ARGS 256
+
+#define CHECK(x) (void)(!(x) ? (abort(), 1) : 0)
+
+/* Define macros so that compilers other than gcc can run the tests. */
+#undef __UNUSED__
+#if defined(__GNUC__)
+#define __UNUSED__ __attribute__((__unused__))
+#define __STDCALL__ __attribute__((stdcall))
+#define __THISCALL__ __attribute__((thiscall))
+#define __FASTCALL__ __attribute__((fastcall))
+#define __MSABI__ __attribute__((ms_abi))
+#else
+#define __UNUSED__
+#define __STDCALL__ __stdcall
+#define __THISCALL__ __thiscall
+#define __FASTCALL__ __fastcall
+#endif
+
+#ifndef ABI_NUM
+#define ABI_NUM FFI_DEFAULT_ABI
+#define ABI_ATTR
+#endif
+
+/* Prefer MAP_ANON(YMOUS) to /dev/zero, since we don't need to keep a
+ file open. */
+#ifdef HAVE_MMAP_ANON
+# undef HAVE_MMAP_DEV_ZERO
+
+# include <sys/mman.h>
+# ifndef MAP_FAILED
+# define MAP_FAILED -1
+# endif
+# if !defined (MAP_ANONYMOUS) && defined (MAP_ANON)
+# define MAP_ANONYMOUS MAP_ANON
+# endif
+# define USING_MMAP
+
+#endif
+
+#ifdef HAVE_MMAP_DEV_ZERO
+
+# include <sys/mman.h>
+# ifndef MAP_FAILED
+# define MAP_FAILED -1
+# endif
+# define USING_MMAP
+
+#endif
+
+/* MinGW kludge. */
+#if defined(_WIN64) | defined(_WIN32)
+#define PRIdLL "I64d"
+#define PRIuLL "I64u"
+#else
+#define PRIdLL "lld"
+#define PRIuLL "llu"
+#endif
+
+/* Tru64 UNIX kludge. */
+#if defined(__alpha__) && defined(__osf__)
+/* Tru64 UNIX V4.0 doesn't support %lld/%lld, but long is 64-bit. */
+#undef PRIdLL
+#define PRIdLL "ld"
+#undef PRIuLL
+#define PRIuLL "lu"
+#define PRId8 "hd"
+#define PRIu8 "hu"
+#define PRId64 "ld"
+#define PRIu64 "lu"
+#define PRIuPTR "lu"
+#endif
+
+/* PA HP-UX kludge. */
+#if defined(__hppa__) && defined(__hpux__) && !defined(PRIuPTR)
+#define PRIuPTR "lu"
+#endif
+
+/* IRIX kludge. */
+#if defined(__sgi)
+/* IRIX 6.5 <inttypes.h> provides all definitions, but only for C99
+ compilations. */
+#define PRId8 "hhd"
+#define PRIu8 "hhu"
+#if (_MIPS_SZLONG == 32)
+#define PRId64 "lld"
+#define PRIu64 "llu"
+#endif
+/* This doesn't match <inttypes.h>, which always has "lld" here, but the
+ arguments are uint64_t, int64_t, which are unsigned long, long for
+ 64-bit in <sgidefs.h>. */
+#if (_MIPS_SZLONG == 64)
+#define PRId64 "ld"
+#define PRIu64 "lu"
+#endif
+/* This doesn't match <inttypes.h>, which has "u" here, but the arguments
+ are uintptr_t, which is always unsigned long. */
+#define PRIuPTR "lu"
+#endif
+
+/* Solaris < 10 kludge. */
+#if defined(__sun__) && defined(__svr4__) && !defined(PRIuPTR)
+#if defined(__arch64__) || defined (__x86_64__)
+#define PRIuPTR "lu"
+#else
+#define PRIuPTR "u"
+#endif
+#endif
+
+/* MSVC kludge. */
+#if defined _MSC_VER
+#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS)
+#define PRIuPTR "lu"
+#define PRIu8 "u"
+#define PRId8 "d"
+#define PRIu64 "I64u"
+#define PRId64 "I64d"
+#endif
+#endif
+
+#ifndef PRIuPTR
+#define PRIuPTR "u"
+#endif
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float.c b/contrib/restricted/libffi/testsuite/libffi.call/float.c
index 5b7a31b54a..fbc272d84f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float.c
@@ -1,59 +1,59 @@
-/* Area: ffi_call
- Purpose: Check return value float.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-static int floating(int a, float b, double c, long double d)
-{
- int i;
-
- i = (int) ((float)a/b + ((float)c/(float)d));
-
- return i;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_arg rint;
-
- float f;
- signed int si1;
- double d;
- long double ld;
-
- args[0] = &ffi_type_sint;
- values[0] = &si1;
- args[1] = &ffi_type_float;
- values[1] = &f;
- args[2] = &ffi_type_double;
- values[2] = &d;
- args[3] = &ffi_type_longdouble;
- values[3] = &ld;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
- &ffi_type_sint, args) == FFI_OK);
-
- si1 = 6;
- f = 3.14159;
- d = (double)1.0/(double)3.0;
- ld = 2.71828182846L;
-
- floating (si1, f, d, ld);
-
- ffi_call(&cif, FFI_FN(floating), &rint, values);
-
- printf ("%d vs %d\n", (int)rint, floating (si1, f, d, ld));
-
- CHECK((int)rint == floating(si1, f, d, ld));
-
- exit (0);
-}
+/* Area: ffi_call
+ Purpose: Check return value float.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+static int floating(int a, float b, double c, long double d)
+{
+ int i;
+
+ i = (int) ((float)a/b + ((float)c/(float)d));
+
+ return i;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_arg rint;
+
+ float f;
+ signed int si1;
+ double d;
+ long double ld;
+
+ args[0] = &ffi_type_sint;
+ values[0] = &si1;
+ args[1] = &ffi_type_float;
+ values[1] = &f;
+ args[2] = &ffi_type_double;
+ values[2] = &d;
+ args[3] = &ffi_type_longdouble;
+ values[3] = &ld;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
+ &ffi_type_sint, args) == FFI_OK);
+
+ si1 = 6;
+ f = 3.14159;
+ d = (double)1.0/(double)3.0;
+ ld = 2.71828182846L;
+
+ floating (si1, f, d, ld);
+
+ ffi_call(&cif, FFI_FN(floating), &rint, values);
+
+ printf ("%d vs %d\n", (int)rint, floating (si1, f, d, ld));
+
+ CHECK((int)rint == floating(si1, f, d, ld));
+
+ exit (0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/float/ya.make
index a6e0f50ef9..1df0a2f4a2 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float1.c b/contrib/restricted/libffi/testsuite/libffi.call/float1.c
index 511daf984a..c48493c6b2 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float1.c
@@ -1,60 +1,60 @@
-/* Area: ffi_call
- Purpose: Check return value double.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-#include "float.h"
-
-#include <math.h>
-
-typedef union
-{
- double d;
- unsigned char c[sizeof (double)];
-} value_type;
-
-#define CANARY 0xba
-
-static double dblit(float f)
-{
- return f/3.0;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- float f;
- value_type result[2];
- unsigned int i;
-
- args[0] = &ffi_type_float;
- values[0] = &f;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_double, args) == FFI_OK);
-
- f = 3.14159;
-
- /* Put a canary in the return array. This is a regression test for
- a buffer overrun. */
- memset(result[1].c, CANARY, sizeof (double));
-
- ffi_call(&cif, FFI_FN(dblit), &result[0].d, values);
-
- /* These are not always the same!! Check for a reasonable delta */
-
- CHECK(fabs(result[0].d - dblit(f)) < DBL_EPSILON);
-
- /* Check the canary. */
- for (i = 0; i < sizeof (double); ++i)
- CHECK(result[1].c[i] == CANARY);
-
- exit(0);
-
-}
+/* Area: ffi_call
+ Purpose: Check return value double.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+#include "float.h"
+
+#include <math.h>
+
+typedef union
+{
+ double d;
+ unsigned char c[sizeof (double)];
+} value_type;
+
+#define CANARY 0xba
+
+static double dblit(float f)
+{
+ return f/3.0;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ float f;
+ value_type result[2];
+ unsigned int i;
+
+ args[0] = &ffi_type_float;
+ values[0] = &f;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_double, args) == FFI_OK);
+
+ f = 3.14159;
+
+ /* Put a canary in the return array. This is a regression test for
+ a buffer overrun. */
+ memset(result[1].c, CANARY, sizeof (double));
+
+ ffi_call(&cif, FFI_FN(dblit), &result[0].d, values);
+
+ /* These are not always the same!! Check for a reasonable delta */
+
+ CHECK(fabs(result[0].d - dblit(f)) < DBL_EPSILON);
+
+ /* Check the canary. */
+ for (i = 0; i < sizeof (double); ++i)
+ CHECK(result[1].c[i] == CANARY);
+
+ exit(0);
+
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float1/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/float1/ya.make
index b8f5f9b96b..ad26ae35ff 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- float1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ float1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float2.c b/contrib/restricted/libffi/testsuite/libffi.call/float2.c
index a0b74a49e3..57cd9e30f9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float2.c
@@ -1,61 +1,61 @@
-/* Area: ffi_call
- Purpose: Check return value long double.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-/* { dg-do run } */
-
-#include "ffitest.h"
-#include "float.h"
-
-#include <math.h>
-
-static long double ldblit(float f)
-{
- return (long double) (((long double) f)/ (long double) 3.0);
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- float f;
- long double ld;
- long double original;
-
- args[0] = &ffi_type_float;
- values[0] = &f;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_longdouble, args) == FFI_OK);
-
- f = 3.14159;
-
-#if defined(__sun) && defined(__GNUC__)
- /* long double support under SunOS/gcc is pretty much non-existent.
- You'll get the odd bus error in library routines like printf() */
-#else
- printf ("%Lf\n", ldblit(f));
-#endif
-
- ld = 666;
- ffi_call(&cif, FFI_FN(ldblit), &ld, values);
-
-#if defined(__sun) && defined(__GNUC__)
- /* long double support under SunOS/gcc is pretty much non-existent.
- You'll get the odd bus error in library routines like printf() */
-#else
- printf ("%Lf, %Lf, %Lf, %Lf\n", ld, ldblit(f), ld - ldblit(f), LDBL_EPSILON);
-#endif
-
- /* These are not always the same!! Check for a reasonable delta */
- original = ldblit(f);
- if (((ld > original) ? (ld - original) : (original - ld)) < LDBL_EPSILON)
- puts("long double return value tests ok!");
- else
- CHECK(0);
-
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value long double.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+/* { dg-do run } */
+
+#include "ffitest.h"
+#include "float.h"
+
+#include <math.h>
+
+static long double ldblit(float f)
+{
+ return (long double) (((long double) f)/ (long double) 3.0);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ float f;
+ long double ld;
+ long double original;
+
+ args[0] = &ffi_type_float;
+ values[0] = &f;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_longdouble, args) == FFI_OK);
+
+ f = 3.14159;
+
+#if defined(__sun) && defined(__GNUC__)
+ /* long double support under SunOS/gcc is pretty much non-existent.
+ You'll get the odd bus error in library routines like printf() */
+#else
+ printf ("%Lf\n", ldblit(f));
+#endif
+
+ ld = 666;
+ ffi_call(&cif, FFI_FN(ldblit), &ld, values);
+
+#if defined(__sun) && defined(__GNUC__)
+ /* long double support under SunOS/gcc is pretty much non-existent.
+ You'll get the odd bus error in library routines like printf() */
+#else
+ printf ("%Lf, %Lf, %Lf, %Lf\n", ld, ldblit(f), ld - ldblit(f), LDBL_EPSILON);
+#endif
+
+ /* These are not always the same!! Check for a reasonable delta */
+ original = ldblit(f);
+ if (((ld > original) ? (ld - original) : (original - ld)) < LDBL_EPSILON)
+ puts("long double return value tests ok!");
+ else
+ CHECK(0);
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float2/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/float2/ya.make
index c9cedf42f2..ad89de3a7a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- float2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ float2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float3.c b/contrib/restricted/libffi/testsuite/libffi.call/float3.c
index 994d8b676e..bab3206a17 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float3.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float3.c
@@ -1,74 +1,74 @@
-/* Area: ffi_call
- Purpose: Check float arguments with different orders.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-#include "float.h"
-
-#include <math.h>
-
-static double floating_1(float a, double b, long double c)
-{
- return (double) a + b + (double) c;
-}
-
-static double floating_2(long double a, double b, float c)
-{
- return (double) a + b + (double) c;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- double rd;
-
- float f;
- double d;
- long double ld;
-
- args[0] = &ffi_type_float;
- values[0] = &f;
- args[1] = &ffi_type_double;
- values[1] = &d;
- args[2] = &ffi_type_longdouble;
- values[2] = &ld;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
- &ffi_type_double, args) == FFI_OK);
-
- f = 3.14159;
- d = (double)1.0/(double)3.0;
- ld = 2.71828182846L;
-
- floating_1 (f, d, ld);
-
- ffi_call(&cif, FFI_FN(floating_1), &rd, values);
-
- CHECK(fabs(rd - floating_1(f, d, ld)) < DBL_EPSILON);
-
- args[0] = &ffi_type_longdouble;
- values[0] = &ld;
- args[1] = &ffi_type_double;
- values[1] = &d;
- args[2] = &ffi_type_float;
- values[2] = &f;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
- &ffi_type_double, args) == FFI_OK);
-
- floating_2 (ld, d, f);
-
- ffi_call(&cif, FFI_FN(floating_2), &rd, values);
-
- CHECK(fabs(rd - floating_2(ld, d, f)) < DBL_EPSILON);
-
- exit (0);
-}
+/* Area: ffi_call
+ Purpose: Check float arguments with different orders.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+#include "float.h"
+
+#include <math.h>
+
+static double floating_1(float a, double b, long double c)
+{
+ return (double) a + b + (double) c;
+}
+
+static double floating_2(long double a, double b, float c)
+{
+ return (double) a + b + (double) c;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ double rd;
+
+ float f;
+ double d;
+ long double ld;
+
+ args[0] = &ffi_type_float;
+ values[0] = &f;
+ args[1] = &ffi_type_double;
+ values[1] = &d;
+ args[2] = &ffi_type_longdouble;
+ values[2] = &ld;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
+ &ffi_type_double, args) == FFI_OK);
+
+ f = 3.14159;
+ d = (double)1.0/(double)3.0;
+ ld = 2.71828182846L;
+
+ floating_1 (f, d, ld);
+
+ ffi_call(&cif, FFI_FN(floating_1), &rd, values);
+
+ CHECK(fabs(rd - floating_1(f, d, ld)) < DBL_EPSILON);
+
+ args[0] = &ffi_type_longdouble;
+ values[0] = &ld;
+ args[1] = &ffi_type_double;
+ values[1] = &d;
+ args[2] = &ffi_type_float;
+ values[2] = &f;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
+ &ffi_type_double, args) == FFI_OK);
+
+ floating_2 (ld, d, f);
+
+ ffi_call(&cif, FFI_FN(floating_2), &rd, values);
+
+ CHECK(fabs(rd - floating_2(ld, d, f)) < DBL_EPSILON);
+
+ exit (0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float3/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/float3/ya.make
index 19a178fb91..0064211582 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float3/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float3/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- float3.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ float3.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float4.c b/contrib/restricted/libffi/testsuite/libffi.call/float4.c
index 00973ad6de..0dd6d85e7a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float4.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float4.c
@@ -1,62 +1,62 @@
-/* Area: ffi_call
- Purpose: Check denorm double value.
- Limitations: none.
- PR: PR26483.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-/* { dg-options "-mieee" { target alpha*-*-* } } */
-
-#include "ffitest.h"
-#include "float.h"
-
-typedef union
-{
- double d;
- unsigned char c[sizeof (double)];
-} value_type;
-
-#define CANARY 0xba
-
-static double dblit(double d)
-{
- return d;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- double d;
- value_type result[2];
- unsigned int i;
-
- args[0] = &ffi_type_double;
- values[0] = &d;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_double, args) == FFI_OK);
-
- d = DBL_MIN / 2;
-
- /* Put a canary in the return array. This is a regression test for
- a buffer overrun. */
- memset(result[1].c, CANARY, sizeof (double));
-
- ffi_call(&cif, FFI_FN(dblit), &result[0].d, values);
-
- /* The standard delta check doesn't work for denorms. Since we didn't do
- any arithmetic, we should get the original result back, and hence an
- exact check should be OK here. */
+/* Area: ffi_call
+ Purpose: Check denorm double value.
+ Limitations: none.
+ PR: PR26483.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+/* { dg-options "-mieee" { target alpha*-*-* } } */
+
+#include "ffitest.h"
+#include "float.h"
+
+typedef union
+{
+ double d;
+ unsigned char c[sizeof (double)];
+} value_type;
+
+#define CANARY 0xba
+
+static double dblit(double d)
+{
+ return d;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ double d;
+ value_type result[2];
+ unsigned int i;
+
+ args[0] = &ffi_type_double;
+ values[0] = &d;
- CHECK(result[0].d == dblit(d));
-
- /* Check the canary. */
- for (i = 0; i < sizeof (double); ++i)
- CHECK(result[1].c[i] == CANARY);
-
- exit(0);
-
-}
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_double, args) == FFI_OK);
+
+ d = DBL_MIN / 2;
+
+ /* Put a canary in the return array. This is a regression test for
+ a buffer overrun. */
+ memset(result[1].c, CANARY, sizeof (double));
+
+ ffi_call(&cif, FFI_FN(dblit), &result[0].d, values);
+
+ /* The standard delta check doesn't work for denorms. Since we didn't do
+ any arithmetic, we should get the original result back, and hence an
+ exact check should be OK here. */
+
+ CHECK(result[0].d == dblit(d));
+
+ /* Check the canary. */
+ for (i = 0; i < sizeof (double); ++i)
+ CHECK(result[1].c[i] == CANARY);
+
+ exit(0);
+
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float4/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/float4/ya.make
index 5eb21c16fc..a11a21c8be 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float4/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float4/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- float4.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ float4.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float_va.c b/contrib/restricted/libffi/testsuite/libffi.call/float_va.c
index f91d1e2500..5acff91f66 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float_va.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float_va.c
@@ -1,107 +1,107 @@
-/* Area: fp and variadics
- Purpose: check fp inputs and returns work on variadics, even the fixed params
- Limitations: None
- PR: none
- Originator: <david.gilbert@linaro.org> 2011-01-25
-
- Intended to stress the difference in ABI on ARM vfp
-*/
-
-/* { dg-do run } */
-
-#include <stdarg.h>
-
-#include "ffitest.h"
-
-/* prints out all the parameters, and returns the sum of them all.
- * 'x' is the number of variadic parameters all of which are double in this test
- */
-double float_va_fn(unsigned int x, double y,...)
-{
- double total=0.0;
- va_list ap;
- unsigned int i;
-
- total+=(double)x;
- total+=y;
-
- printf("%u: %.1f :", x, y);
-
- va_start(ap, y);
- for(i=0;i<x;i++)
- {
- double arg=va_arg(ap, double);
- total+=arg;
- printf(" %d:%.1f ", i, arg);
- }
- va_end(ap);
-
- printf(" total: %.1f\n", total);
-
- return total;
-}
-
-int main (void)
-{
- ffi_cif cif;
-
- ffi_type *arg_types[5];
- void *values[5];
- double doubles[5];
- unsigned int firstarg;
- double resfp;
-
- /* First test, pass float_va_fn(0,2.0) - note there are no actual
- * variadic parameters, but it's declared variadic so the ABI may be
- * different. */
- /* Call it statically and then via ffi */
- resfp=float_va_fn(0,2.0);
- /* { dg-output "0: 2.0 : total: 2.0" } */
- printf("compiled: %.1f\n", resfp);
- /* { dg-output "\ncompiled: 2.0" } */
-
- arg_types[0] = &ffi_type_uint;
- arg_types[1] = &ffi_type_double;
- arg_types[2] = NULL;
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 2, 2,
- &ffi_type_double, arg_types) == FFI_OK);
-
- firstarg = 0;
- doubles[0] = 2.0;
- values[0] = &firstarg;
- values[1] = &doubles[0];
- ffi_call(&cif, FFI_FN(float_va_fn), &resfp, values);
- /* { dg-output "\n0: 2.0 : total: 2.0" } */
- printf("ffi: %.1f\n", resfp);
- /* { dg-output "\nffi: 2.0" } */
-
- /* Second test, float_va_fn(2,2.0,3.0,4.0), now with variadic params */
- /* Call it statically and then via ffi */
- resfp=float_va_fn(2,2.0,3.0,4.0);
- /* { dg-output "\n2: 2.0 : 0:3.0 1:4.0 total: 11.0" } */
- printf("compiled: %.1f\n", resfp);
- /* { dg-output "\ncompiled: 11.0" } */
-
- arg_types[0] = &ffi_type_uint;
- arg_types[1] = &ffi_type_double;
- arg_types[2] = &ffi_type_double;
- arg_types[3] = &ffi_type_double;
- arg_types[4] = NULL;
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 2, 4,
- &ffi_type_double, arg_types) == FFI_OK);
-
- firstarg = 2;
- doubles[0] = 2.0;
- doubles[1] = 3.0;
- doubles[2] = 4.0;
- values[0] = &firstarg;
- values[1] = &doubles[0];
- values[2] = &doubles[1];
- values[3] = &doubles[2];
- ffi_call(&cif, FFI_FN(float_va_fn), &resfp, values);
- /* { dg-output "\n2: 2.0 : 0:3.0 1:4.0 total: 11.0" } */
- printf("ffi: %.1f\n", resfp);
- /* { dg-output "\nffi: 11.0" } */
-
- exit(0);
-}
+/* Area: fp and variadics
+ Purpose: check fp inputs and returns work on variadics, even the fixed params
+ Limitations: None
+ PR: none
+ Originator: <david.gilbert@linaro.org> 2011-01-25
+
+ Intended to stress the difference in ABI on ARM vfp
+*/
+
+/* { dg-do run } */
+
+#include <stdarg.h>
+
+#include "ffitest.h"
+
+/* prints out all the parameters, and returns the sum of them all.
+ * 'x' is the number of variadic parameters all of which are double in this test
+ */
+double float_va_fn(unsigned int x, double y,...)
+{
+ double total=0.0;
+ va_list ap;
+ unsigned int i;
+
+ total+=(double)x;
+ total+=y;
+
+ printf("%u: %.1f :", x, y);
+
+ va_start(ap, y);
+ for(i=0;i<x;i++)
+ {
+ double arg=va_arg(ap, double);
+ total+=arg;
+ printf(" %d:%.1f ", i, arg);
+ }
+ va_end(ap);
+
+ printf(" total: %.1f\n", total);
+
+ return total;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+
+ ffi_type *arg_types[5];
+ void *values[5];
+ double doubles[5];
+ unsigned int firstarg;
+ double resfp;
+
+ /* First test, pass float_va_fn(0,2.0) - note there are no actual
+ * variadic parameters, but it's declared variadic so the ABI may be
+ * different. */
+ /* Call it statically and then via ffi */
+ resfp=float_va_fn(0,2.0);
+ /* { dg-output "0: 2.0 : total: 2.0" } */
+ printf("compiled: %.1f\n", resfp);
+ /* { dg-output "\ncompiled: 2.0" } */
+
+ arg_types[0] = &ffi_type_uint;
+ arg_types[1] = &ffi_type_double;
+ arg_types[2] = NULL;
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 2, 2,
+ &ffi_type_double, arg_types) == FFI_OK);
+
+ firstarg = 0;
+ doubles[0] = 2.0;
+ values[0] = &firstarg;
+ values[1] = &doubles[0];
+ ffi_call(&cif, FFI_FN(float_va_fn), &resfp, values);
+ /* { dg-output "\n0: 2.0 : total: 2.0" } */
+ printf("ffi: %.1f\n", resfp);
+ /* { dg-output "\nffi: 2.0" } */
+
+ /* Second test, float_va_fn(2,2.0,3.0,4.0), now with variadic params */
+ /* Call it statically and then via ffi */
+ resfp=float_va_fn(2,2.0,3.0,4.0);
+ /* { dg-output "\n2: 2.0 : 0:3.0 1:4.0 total: 11.0" } */
+ printf("compiled: %.1f\n", resfp);
+ /* { dg-output "\ncompiled: 11.0" } */
+
+ arg_types[0] = &ffi_type_uint;
+ arg_types[1] = &ffi_type_double;
+ arg_types[2] = &ffi_type_double;
+ arg_types[3] = &ffi_type_double;
+ arg_types[4] = NULL;
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 2, 4,
+ &ffi_type_double, arg_types) == FFI_OK);
+
+ firstarg = 2;
+ doubles[0] = 2.0;
+ doubles[1] = 3.0;
+ doubles[2] = 4.0;
+ values[0] = &firstarg;
+ values[1] = &doubles[0];
+ values[2] = &doubles[1];
+ values[3] = &doubles[2];
+ ffi_call(&cif, FFI_FN(float_va_fn), &resfp, values);
+ /* { dg-output "\n2: 2.0 : 0:3.0 1:4.0 total: 11.0" } */
+ printf("ffi: %.1f\n", resfp);
+ /* { dg-output "\nffi: 11.0" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/float_va/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/float_va/ya.make
index 7b7b2b3536..10d03d19ba 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/float_va/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/float_va/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- float_va.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ float_va.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/many.c b/contrib/restricted/libffi/testsuite/libffi.call/many.c
index e3b34f45ab..336968c77a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/many.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/many.c
@@ -1,59 +1,59 @@
-/* Area: ffi_call
- Purpose: Check return value float, with many arguments
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-#include <stdlib.h>
-#include <float.h>
-#include <math.h>
-
-static float ABI_ATTR many(float f1, float f2, float f3, float f4, float f5, float f6, float f7, float f8, float f9, float f10, float f11, float f12, float f13)
-{
-#if 0
- printf("%f %f %f %f %f %f %f %f %f %f %f %f %f\n",
- (double) f1, (double) f2, (double) f3, (double) f4, (double) f5,
- (double) f6, (double) f7, (double) f8, (double) f9, (double) f10,
- (double) f11, (double) f12, (double) f13);
-#endif
-
- return f1+f2+f3+f4+f5+f6+f7+f8+f9+f10+f11+f12+f13;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[13];
- void *values[13];
- float fa[13];
- float f, ff;
- int i;
-
- for (i = 0; i < 13; i++)
- {
- args[i] = &ffi_type_float;
- values[i] = &fa[i];
- fa[i] = (float) i;
- }
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 13,
- &ffi_type_float, args) == FFI_OK);
-
- ffi_call(&cif, FFI_FN(many), &f, values);
-
- ff = many(fa[0], fa[1],
- fa[2], fa[3],
- fa[4], fa[5],
- fa[6], fa[7],
- fa[8], fa[9],
- fa[10],fa[11],fa[12]);
-
- if (fabs(f - ff) < FLT_EPSILON)
- exit(0);
- else
- abort();
-}
+/* Area: ffi_call
+ Purpose: Check return value float, with many arguments
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+#include <stdlib.h>
+#include <float.h>
+#include <math.h>
+
+static float ABI_ATTR many(float f1, float f2, float f3, float f4, float f5, float f6, float f7, float f8, float f9, float f10, float f11, float f12, float f13)
+{
+#if 0
+ printf("%f %f %f %f %f %f %f %f %f %f %f %f %f\n",
+ (double) f1, (double) f2, (double) f3, (double) f4, (double) f5,
+ (double) f6, (double) f7, (double) f8, (double) f9, (double) f10,
+ (double) f11, (double) f12, (double) f13);
+#endif
+
+ return f1+f2+f3+f4+f5+f6+f7+f8+f9+f10+f11+f12+f13;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[13];
+ void *values[13];
+ float fa[13];
+ float f, ff;
+ int i;
+
+ for (i = 0; i < 13; i++)
+ {
+ args[i] = &ffi_type_float;
+ values[i] = &fa[i];
+ fa[i] = (float) i;
+ }
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 13,
+ &ffi_type_float, args) == FFI_OK);
+
+ ffi_call(&cif, FFI_FN(many), &f, values);
+
+ ff = many(fa[0], fa[1],
+ fa[2], fa[3],
+ fa[4], fa[5],
+ fa[6], fa[7],
+ fa[8], fa[9],
+ fa[10],fa[11],fa[12]);
+
+ if (fabs(f - ff) < FLT_EPSILON)
+ exit(0);
+ else
+ abort();
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/many/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/many/ya.make
index c983c0ca0a..ba6c09ca44 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/many/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/many/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- many.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ many.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/many2.c b/contrib/restricted/libffi/testsuite/libffi.call/many2.c
index 4b080674b7..1c85746e4c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/many2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/many2.c
@@ -1,57 +1,57 @@
-/* Area: ffi_call
- Purpose: Check uint8_t arguments.
- Limitations: none.
- PR: PR45677.
- Originator: Dan Witte <dwitte@gmail.com> 20100916 */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-#define NARGS 7
-
-typedef unsigned char u8;
-
-#ifdef __GNUC__
-__attribute__((noinline))
-#endif
-uint8_t
-foo (uint8_t a, uint8_t b, uint8_t c, uint8_t d,
- uint8_t e, uint8_t f, uint8_t g)
-{
- return a + b + c + d + e + f + g;
-}
-
-uint8_t ABI_ATTR
-bar (uint8_t a, uint8_t b, uint8_t c, uint8_t d,
- uint8_t e, uint8_t f, uint8_t g)
-{
- return foo (a, b, c, d, e, f, g);
-}
-
-int
-main (void)
-{
- ffi_type *ffitypes[NARGS];
- int i;
- ffi_cif cif;
- ffi_arg result = 0;
- uint8_t args[NARGS];
- void *argptrs[NARGS];
-
- for (i = 0; i < NARGS; ++i)
- ffitypes[i] = &ffi_type_uint8;
-
- CHECK (ffi_prep_cif (&cif, ABI_NUM, NARGS,
- &ffi_type_uint8, ffitypes) == FFI_OK);
-
- for (i = 0; i < NARGS; ++i)
- {
- args[i] = i;
- argptrs[i] = &args[i];
- }
- ffi_call (&cif, FFI_FN (bar), &result, argptrs);
-
- CHECK (result == 21);
- return 0;
-}
+/* Area: ffi_call
+ Purpose: Check uint8_t arguments.
+ Limitations: none.
+ PR: PR45677.
+ Originator: Dan Witte <dwitte@gmail.com> 20100916 */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+#define NARGS 7
+
+typedef unsigned char u8;
+
+#ifdef __GNUC__
+__attribute__((noinline))
+#endif
+uint8_t
+foo (uint8_t a, uint8_t b, uint8_t c, uint8_t d,
+ uint8_t e, uint8_t f, uint8_t g)
+{
+ return a + b + c + d + e + f + g;
+}
+
+uint8_t ABI_ATTR
+bar (uint8_t a, uint8_t b, uint8_t c, uint8_t d,
+ uint8_t e, uint8_t f, uint8_t g)
+{
+ return foo (a, b, c, d, e, f, g);
+}
+
+int
+main (void)
+{
+ ffi_type *ffitypes[NARGS];
+ int i;
+ ffi_cif cif;
+ ffi_arg result = 0;
+ uint8_t args[NARGS];
+ void *argptrs[NARGS];
+
+ for (i = 0; i < NARGS; ++i)
+ ffitypes[i] = &ffi_type_uint8;
+
+ CHECK (ffi_prep_cif (&cif, ABI_NUM, NARGS,
+ &ffi_type_uint8, ffitypes) == FFI_OK);
+
+ for (i = 0; i < NARGS; ++i)
+ {
+ args[i] = i;
+ argptrs[i] = &args[i];
+ }
+ ffi_call (&cif, FFI_FN (bar), &result, argptrs);
+
+ CHECK (result == 21);
+ return 0;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/many2/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/many2/ya.make
index cef0a4eb3c..487fe0854a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/many2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/many2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- many2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ many2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/many_double.c b/contrib/restricted/libffi/testsuite/libffi.call/many_double.c
index b1f37a5aba..4ef8c8ab28 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/many_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/many_double.c
@@ -1,70 +1,70 @@
-/* Area: ffi_call
- Purpose: Check return value double, with many arguments
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-#include <stdlib.h>
-#include <float.h>
-#include <math.h>
-
-static double many(double f1,
- double f2,
- double f3,
- double f4,
- double f5,
- double f6,
- double f7,
- double f8,
- double f9,
- double f10,
- double f11,
- double f12,
- double f13)
-{
-#if 0
- printf("%f %f %f %f %f %f %f %f %f %f %f %f %f\n",
- (double) f1, (double) f2, (double) f3, (double) f4, (double) f5,
- (double) f6, (double) f7, (double) f8, (double) f9, (double) f10,
- (double) f11, (double) f12, (double) f13);
-#endif
-
- return ((f1/f2+f3/f4+f5/f6+f7/f8+f9/f10+f11/f12) * f13);
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[13];
- void *values[13];
- double fa[13];
- double f, ff;
- int i;
-
- for (i = 0; i < 13; i++)
- {
- args[i] = &ffi_type_double;
- values[i] = &fa[i];
- fa[i] = (double) i;
- }
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 13,
- &ffi_type_double, args) == FFI_OK);
-
- ffi_call(&cif, FFI_FN(many), &f, values);
-
- ff = many(fa[0], fa[1],
- fa[2], fa[3],
- fa[4], fa[5],
- fa[6], fa[7],
- fa[8], fa[9],
- fa[10],fa[11],fa[12]);
- if (fabs(f - ff) < FLT_EPSILON)
- exit(0);
- else
- abort();
-}
+/* Area: ffi_call
+ Purpose: Check return value double, with many arguments
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+#include <stdlib.h>
+#include <float.h>
+#include <math.h>
+
+static double many(double f1,
+ double f2,
+ double f3,
+ double f4,
+ double f5,
+ double f6,
+ double f7,
+ double f8,
+ double f9,
+ double f10,
+ double f11,
+ double f12,
+ double f13)
+{
+#if 0
+ printf("%f %f %f %f %f %f %f %f %f %f %f %f %f\n",
+ (double) f1, (double) f2, (double) f3, (double) f4, (double) f5,
+ (double) f6, (double) f7, (double) f8, (double) f9, (double) f10,
+ (double) f11, (double) f12, (double) f13);
+#endif
+
+ return ((f1/f2+f3/f4+f5/f6+f7/f8+f9/f10+f11/f12) * f13);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[13];
+ void *values[13];
+ double fa[13];
+ double f, ff;
+ int i;
+
+ for (i = 0; i < 13; i++)
+ {
+ args[i] = &ffi_type_double;
+ values[i] = &fa[i];
+ fa[i] = (double) i;
+ }
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 13,
+ &ffi_type_double, args) == FFI_OK);
+
+ ffi_call(&cif, FFI_FN(many), &f, values);
+
+ ff = many(fa[0], fa[1],
+ fa[2], fa[3],
+ fa[4], fa[5],
+ fa[6], fa[7],
+ fa[8], fa[9],
+ fa[10],fa[11],fa[12]);
+ if (fabs(f - ff) < FLT_EPSILON)
+ exit(0);
+ else
+ abort();
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/many_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/many_double/ya.make
index 617ba4a813..69436210b4 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/many_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/many_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- many_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ many_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/many_mixed.c b/contrib/restricted/libffi/testsuite/libffi.call/many_mixed.c
index 9cead6d3da..85ec36ecbe 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/many_mixed.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/many_mixed.c
@@ -1,78 +1,78 @@
-/* Area: ffi_call
- Purpose: Check return value double, with many arguments
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-#include <stdlib.h>
-#include <float.h>
-#include <math.h>
-
-static double many(double f1,
- double f2,
- long int i1,
- double f3,
- double f4,
- long int i2,
- double f5,
- double f6,
- long int i3,
- double f7,
- double f8,
- long int i4,
- double f9,
- double f10,
- long int i5,
- double f11,
- double f12,
- long int i6,
- double f13)
-{
- return ((double) (i1 + i2 + i3 + i4 + i5 + i6) + (f1/f2+f3/f4+f5/f6+f7/f8+f9/f10+f11/f12) * f13);
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[19];
- void *values[19];
- double fa[19];
- long int la[19];
- double f, ff;
- int i;
-
- for (i = 0; i < 19; i++)
- {
- if( (i - 2) % 3 == 0) {
- args[i] = &ffi_type_slong;
- la[i] = (long int) i;
- values[i] = &la[i];
- }
- else {
- args[i] = &ffi_type_double;
- fa[i] = (double) i;
- values[i] = &fa[i];
- }
- }
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 19,
- &ffi_type_double, args) == FFI_OK);
-
- ffi_call(&cif, FFI_FN(many), &f, values);
-
- ff = many(fa[0], fa[1], la[2],
- fa[3], fa[4], la[5],
- fa[6], fa[7], la[8],
- fa[9], fa[10], la[11],
- fa[12], fa[13], la[14],
- fa[15], fa[16], la[17],
- fa[18]);
- if (fabs(f - ff) < FLT_EPSILON)
- exit(0);
- else
- abort();
-}
+/* Area: ffi_call
+ Purpose: Check return value double, with many arguments
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+#include <stdlib.h>
+#include <float.h>
+#include <math.h>
+
+static double many(double f1,
+ double f2,
+ long int i1,
+ double f3,
+ double f4,
+ long int i2,
+ double f5,
+ double f6,
+ long int i3,
+ double f7,
+ double f8,
+ long int i4,
+ double f9,
+ double f10,
+ long int i5,
+ double f11,
+ double f12,
+ long int i6,
+ double f13)
+{
+ return ((double) (i1 + i2 + i3 + i4 + i5 + i6) + (f1/f2+f3/f4+f5/f6+f7/f8+f9/f10+f11/f12) * f13);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[19];
+ void *values[19];
+ double fa[19];
+ long int la[19];
+ double f, ff;
+ int i;
+
+ for (i = 0; i < 19; i++)
+ {
+ if( (i - 2) % 3 == 0) {
+ args[i] = &ffi_type_slong;
+ la[i] = (long int) i;
+ values[i] = &la[i];
+ }
+ else {
+ args[i] = &ffi_type_double;
+ fa[i] = (double) i;
+ values[i] = &fa[i];
+ }
+ }
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 19,
+ &ffi_type_double, args) == FFI_OK);
+
+ ffi_call(&cif, FFI_FN(many), &f, values);
+
+ ff = many(fa[0], fa[1], la[2],
+ fa[3], fa[4], la[5],
+ fa[6], fa[7], la[8],
+ fa[9], fa[10], la[11],
+ fa[12], fa[13], la[14],
+ fa[15], fa[16], la[17],
+ fa[18]);
+ if (fabs(f - ff) < FLT_EPSILON)
+ exit(0);
+ else
+ abort();
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/many_mixed/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/many_mixed/ya.make
index f822115ae4..5454d9a813 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/many_mixed/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/many_mixed/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- many_mixed.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ many_mixed.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/negint.c b/contrib/restricted/libffi/testsuite/libffi.call/negint.c
index eddfcc2295..6e2f26fc10 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/negint.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/negint.c
@@ -1,52 +1,52 @@
-/* Area: ffi_call
- Purpose: Check that negative integers are passed correctly.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-static int checking(int a, short b, signed char c)
-{
-
- return (a < 0 && b < 0 && c < 0);
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_arg rint;
-
- signed int si;
- signed short ss;
- signed char sc;
-
- args[0] = &ffi_type_sint;
- values[0] = &si;
- args[1] = &ffi_type_sshort;
- values[1] = &ss;
- args[2] = &ffi_type_schar;
- values[2] = &sc;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
- &ffi_type_sint, args) == FFI_OK);
-
- si = -6;
- ss = -12;
- sc = -1;
-
- checking (si, ss, sc);
-
- ffi_call(&cif, FFI_FN(checking), &rint, values);
-
- printf ("%d vs %d\n", (int)rint, checking (si, ss, sc));
-
- CHECK(rint != 0);
-
- exit (0);
-}
+/* Area: ffi_call
+ Purpose: Check that negative integers are passed correctly.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+static int checking(int a, short b, signed char c)
+{
+
+ return (a < 0 && b < 0 && c < 0);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_arg rint;
+
+ signed int si;
+ signed short ss;
+ signed char sc;
+
+ args[0] = &ffi_type_sint;
+ values[0] = &si;
+ args[1] = &ffi_type_sshort;
+ values[1] = &ss;
+ args[2] = &ffi_type_schar;
+ values[2] = &sc;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
+ &ffi_type_sint, args) == FFI_OK);
+
+ si = -6;
+ ss = -12;
+ sc = -1;
+
+ checking (si, ss, sc);
+
+ ffi_call(&cif, FFI_FN(checking), &rint, values);
+
+ printf ("%d vs %d\n", (int)rint, checking (si, ss, sc));
+
+ CHECK(rint != 0);
+
+ exit (0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/negint/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/negint/ya.make
index e7fa7975b5..c745235357 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/negint/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/negint/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- negint.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ negint.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/offsets.c b/contrib/restricted/libffi/testsuite/libffi.call/offsets.c
index 005f885a96..23d88b35d5 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/offsets.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/offsets.c
@@ -1,46 +1,46 @@
-/* Area: Struct layout
- Purpose: Test ffi_get_struct_offsets
- Limitations: none.
- PR: none.
- Originator: Tom Tromey. */
-
-/* { dg-do run } */
-#include "ffitest.h"
-#include <stddef.h>
-
-struct test_1
-{
- char c;
- float f;
- char c2;
- int i;
-};
-
-int
-main (void)
-{
- ffi_type test_1_type;
- ffi_type *test_1_elements[5];
- size_t test_1_offsets[4];
-
- test_1_elements[0] = &ffi_type_schar;
- test_1_elements[1] = &ffi_type_float;
- test_1_elements[2] = &ffi_type_schar;
- test_1_elements[3] = &ffi_type_sint;
- test_1_elements[4] = NULL;
-
- test_1_type.size = 0;
- test_1_type.alignment = 0;
- test_1_type.type = FFI_TYPE_STRUCT;
- test_1_type.elements = test_1_elements;
-
- CHECK (ffi_get_struct_offsets (FFI_DEFAULT_ABI, &test_1_type, test_1_offsets)
- == FFI_OK);
- CHECK (test_1_type.size == sizeof (struct test_1));
- CHECK (offsetof (struct test_1, c) == test_1_offsets[0]);
- CHECK (offsetof (struct test_1, f) == test_1_offsets[1]);
- CHECK (offsetof (struct test_1, c2) == test_1_offsets[2]);
- CHECK (offsetof (struct test_1, i) == test_1_offsets[3]);
-
- return 0;
-}
+/* Area: Struct layout
+ Purpose: Test ffi_get_struct_offsets
+ Limitations: none.
+ PR: none.
+ Originator: Tom Tromey. */
+
+/* { dg-do run } */
+#include "ffitest.h"
+#include <stddef.h>
+
+struct test_1
+{
+ char c;
+ float f;
+ char c2;
+ int i;
+};
+
+int
+main (void)
+{
+ ffi_type test_1_type;
+ ffi_type *test_1_elements[5];
+ size_t test_1_offsets[4];
+
+ test_1_elements[0] = &ffi_type_schar;
+ test_1_elements[1] = &ffi_type_float;
+ test_1_elements[2] = &ffi_type_schar;
+ test_1_elements[3] = &ffi_type_sint;
+ test_1_elements[4] = NULL;
+
+ test_1_type.size = 0;
+ test_1_type.alignment = 0;
+ test_1_type.type = FFI_TYPE_STRUCT;
+ test_1_type.elements = test_1_elements;
+
+ CHECK (ffi_get_struct_offsets (FFI_DEFAULT_ABI, &test_1_type, test_1_offsets)
+ == FFI_OK);
+ CHECK (test_1_type.size == sizeof (struct test_1));
+ CHECK (offsetof (struct test_1, c) == test_1_offsets[0]);
+ CHECK (offsetof (struct test_1, f) == test_1_offsets[1]);
+ CHECK (offsetof (struct test_1, c2) == test_1_offsets[2]);
+ CHECK (offsetof (struct test_1, i) == test_1_offsets[3]);
+
+ return 0;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/offsets/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/offsets/ya.make
index d1a87037ee..a5e3a7b918 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/offsets/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/offsets/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- offsets.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ offsets.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/pr1172638.c b/contrib/restricted/libffi/testsuite/libffi.call/pr1172638.c
index 85b3ee5dd8..7da1621cd6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/pr1172638.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/pr1172638.c
@@ -1,127 +1,127 @@
-/* Area: ffi_call
- Purpose: Reproduce bug found in python ctypes
- Limitations: none.
- PR: Fedora 1174037 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct {
- long x;
- long y;
-} POINT;
-
-typedef struct {
- long left;
- long top;
- long right;
- long bottom;
-} RECT;
-
-static RECT ABI_ATTR pr_test(int i __UNUSED__, RECT ar __UNUSED__,
- RECT* br __UNUSED__, POINT cp __UNUSED__,
- RECT dr __UNUSED__, RECT *er __UNUSED__,
- POINT fp, RECT gr __UNUSED__)
-{
- RECT result;
-
- result.left = fp.x;
- result.right = fp.y;
- result.top = fp.x;
- result.bottom = fp.y;
-
- return result;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_type point_type, rect_type;
- ffi_type *point_type_elements[3];
- ffi_type *rect_type_elements[5];
-
- int i;
- POINT cp, fp;
- RECT ar, br, dr, er, gr;
- RECT *p1, *p2;
-
- /* This is a hack to get a properly aligned result buffer */
- RECT *rect_result =
- (RECT *) malloc (sizeof(RECT));
-
- point_type.size = 0;
- point_type.alignment = 0;
- point_type.type = FFI_TYPE_STRUCT;
- point_type.elements = point_type_elements;
- point_type_elements[0] = &ffi_type_slong;
- point_type_elements[1] = &ffi_type_slong;
- point_type_elements[2] = NULL;
-
- rect_type.size = 0;
- rect_type.alignment = 0;
- rect_type.type = FFI_TYPE_STRUCT;
- rect_type.elements = rect_type_elements;
- rect_type_elements[0] = &ffi_type_slong;
- rect_type_elements[1] = &ffi_type_slong;
- rect_type_elements[2] = &ffi_type_slong;
- rect_type_elements[3] = &ffi_type_slong;
- rect_type_elements[4] = NULL;
-
- args[0] = &ffi_type_sint;
- args[1] = &rect_type;
- args[2] = &ffi_type_pointer;
- args[3] = &point_type;
- args[4] = &rect_type;
- args[5] = &ffi_type_pointer;
- args[6] = &point_type;
- args[7] = &rect_type;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 8, &rect_type, args) == FFI_OK);
-
- i = 1;
- ar.left = 2;
- ar.right = 3;
- ar.top = 4;
- ar.bottom = 5;
- br.left = 6;
- br.right = 7;
- br.top = 8;
- br.bottom = 9;
- cp.x = 10;
- cp.y = 11;
- dr.left = 12;
- dr.right = 13;
- dr.top = 14;
- dr.bottom = 15;
- er.left = 16;
- er.right = 17;
- er.top = 18;
- er.bottom = 19;
- fp.x = 20;
- fp.y = 21;
- gr.left = 22;
- gr.right = 23;
- gr.top = 24;
- gr.bottom = 25;
-
- values[0] = &i;
- values[1] = &ar;
- p1 = &br;
- values[2] = &p1;
- values[3] = &cp;
- values[4] = &dr;
- p2 = &er;
- values[5] = &p2;
- values[6] = &fp;
- values[7] = &gr;
-
- ffi_call (&cif, FFI_FN(pr_test), rect_result, values);
-
- CHECK(rect_result->top == 20);
+/* Area: ffi_call
+ Purpose: Reproduce bug found in python ctypes
+ Limitations: none.
+ PR: Fedora 1174037 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct {
+ long x;
+ long y;
+} POINT;
+
+typedef struct {
+ long left;
+ long top;
+ long right;
+ long bottom;
+} RECT;
+
+static RECT ABI_ATTR pr_test(int i __UNUSED__, RECT ar __UNUSED__,
+ RECT* br __UNUSED__, POINT cp __UNUSED__,
+ RECT dr __UNUSED__, RECT *er __UNUSED__,
+ POINT fp, RECT gr __UNUSED__)
+{
+ RECT result;
+
+ result.left = fp.x;
+ result.right = fp.y;
+ result.top = fp.x;
+ result.bottom = fp.y;
+
+ return result;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_type point_type, rect_type;
+ ffi_type *point_type_elements[3];
+ ffi_type *rect_type_elements[5];
- free (rect_result);
- exit(0);
-}
+ int i;
+ POINT cp, fp;
+ RECT ar, br, dr, er, gr;
+ RECT *p1, *p2;
+
+ /* This is a hack to get a properly aligned result buffer */
+ RECT *rect_result =
+ (RECT *) malloc (sizeof(RECT));
+
+ point_type.size = 0;
+ point_type.alignment = 0;
+ point_type.type = FFI_TYPE_STRUCT;
+ point_type.elements = point_type_elements;
+ point_type_elements[0] = &ffi_type_slong;
+ point_type_elements[1] = &ffi_type_slong;
+ point_type_elements[2] = NULL;
+
+ rect_type.size = 0;
+ rect_type.alignment = 0;
+ rect_type.type = FFI_TYPE_STRUCT;
+ rect_type.elements = rect_type_elements;
+ rect_type_elements[0] = &ffi_type_slong;
+ rect_type_elements[1] = &ffi_type_slong;
+ rect_type_elements[2] = &ffi_type_slong;
+ rect_type_elements[3] = &ffi_type_slong;
+ rect_type_elements[4] = NULL;
+
+ args[0] = &ffi_type_sint;
+ args[1] = &rect_type;
+ args[2] = &ffi_type_pointer;
+ args[3] = &point_type;
+ args[4] = &rect_type;
+ args[5] = &ffi_type_pointer;
+ args[6] = &point_type;
+ args[7] = &rect_type;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 8, &rect_type, args) == FFI_OK);
+
+ i = 1;
+ ar.left = 2;
+ ar.right = 3;
+ ar.top = 4;
+ ar.bottom = 5;
+ br.left = 6;
+ br.right = 7;
+ br.top = 8;
+ br.bottom = 9;
+ cp.x = 10;
+ cp.y = 11;
+ dr.left = 12;
+ dr.right = 13;
+ dr.top = 14;
+ dr.bottom = 15;
+ er.left = 16;
+ er.right = 17;
+ er.top = 18;
+ er.bottom = 19;
+ fp.x = 20;
+ fp.y = 21;
+ gr.left = 22;
+ gr.right = 23;
+ gr.top = 24;
+ gr.bottom = 25;
+
+ values[0] = &i;
+ values[1] = &ar;
+ p1 = &br;
+ values[2] = &p1;
+ values[3] = &cp;
+ values[4] = &dr;
+ p2 = &er;
+ values[5] = &p2;
+ values[6] = &fp;
+ values[7] = &gr;
+
+ ffi_call (&cif, FFI_FN(pr_test), rect_result, values);
+
+ CHECK(rect_result->top == 20);
+
+ free (rect_result);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/pr1172638/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/pr1172638/ya.make
index d200f68a60..a296cd0416 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/pr1172638/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/pr1172638/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- pr1172638.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ pr1172638.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/promotion.c b/contrib/restricted/libffi/testsuite/libffi.call/promotion.c
index 7e39615b1b..44561615dd 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/promotion.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/promotion.c
@@ -1,59 +1,59 @@
-/* Area: ffi_call
- Purpose: Promotion test.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-static int promotion(signed char sc, signed short ss,
- unsigned char uc, unsigned short us)
-{
- int r = (int) sc + (int) ss + (int) uc + (int) us;
-
- return r;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_arg rint;
- signed char sc;
- unsigned char uc;
- signed short ss;
- unsigned short us;
- unsigned long ul;
-
- args[0] = &ffi_type_schar;
- args[1] = &ffi_type_sshort;
- args[2] = &ffi_type_uchar;
- args[3] = &ffi_type_ushort;
- values[0] = &sc;
- values[1] = &ss;
- values[2] = &uc;
- values[3] = &us;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
- &ffi_type_sint, args) == FFI_OK);
-
- us = 0;
- ul = 0;
-
- for (sc = (signed char) -127;
- sc <= (signed char) 120; sc += 1)
- for (ss = -30000; ss <= 30000; ss += 10000)
- for (uc = (unsigned char) 0;
- uc <= (unsigned char) 200; uc += 20)
- for (us = 0; us <= 60000; us += 10000)
- {
- ul++;
- ffi_call(&cif, FFI_FN(promotion), &rint, values);
- CHECK((int)rint == (signed char) sc + (signed short) ss +
- (unsigned char) uc + (unsigned short) us);
- }
- printf("%lu promotion tests run\n", ul);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Promotion test.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+static int promotion(signed char sc, signed short ss,
+ unsigned char uc, unsigned short us)
+{
+ int r = (int) sc + (int) ss + (int) uc + (int) us;
+
+ return r;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_arg rint;
+ signed char sc;
+ unsigned char uc;
+ signed short ss;
+ unsigned short us;
+ unsigned long ul;
+
+ args[0] = &ffi_type_schar;
+ args[1] = &ffi_type_sshort;
+ args[2] = &ffi_type_uchar;
+ args[3] = &ffi_type_ushort;
+ values[0] = &sc;
+ values[1] = &ss;
+ values[2] = &uc;
+ values[3] = &us;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
+ &ffi_type_sint, args) == FFI_OK);
+
+ us = 0;
+ ul = 0;
+
+ for (sc = (signed char) -127;
+ sc <= (signed char) 120; sc += 1)
+ for (ss = -30000; ss <= 30000; ss += 10000)
+ for (uc = (unsigned char) 0;
+ uc <= (unsigned char) 200; uc += 20)
+ for (us = 0; us <= 60000; us += 10000)
+ {
+ ul++;
+ ffi_call(&cif, FFI_FN(promotion), &rint, values);
+ CHECK((int)rint == (signed char) sc + (signed short) ss +
+ (unsigned char) uc + (unsigned short) us);
+ }
+ printf("%lu promotion tests run\n", ul);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/promotion/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/promotion/ya.make
index 11b8113dd0..6ea10b0912 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/promotion/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/promotion/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- promotion.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ promotion.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/pyobjc-tc.c b/contrib/restricted/libffi/testsuite/libffi.call/pyobjc-tc.c
index 3d35f6bb7e..e29bd6c283 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/pyobjc-tc.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/pyobjc-tc.c
@@ -1,114 +1,114 @@
-/* Area: ffi_call
- Purpose: Check different structures.
- Limitations: none.
- PR: none.
- Originator: Ronald Oussoren <oussoren@cistron.nl> 20030824 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct Point {
- float x;
- float y;
-} Point;
-
-typedef struct Size {
- float h;
- float w;
-} Size;
-
-typedef struct Rect {
- Point o;
- Size s;
-} Rect;
-
-int doit(int o, char* s, Point p, Rect r, int last)
-{
- printf("CALLED WITH %d %s {%f %f} {{%f %f} {%f %f}} %d\n",
- o, s, p.x, p.y, r.o.x, r.o.y, r.s.h, r.s.w, last);
- return 42;
-}
-
-
-int main(void)
-{
- ffi_type point_type;
- ffi_type size_type;
- ffi_type rect_type;
- ffi_cif cif;
- ffi_type* arglist[6];
- void* values[6];
- int r;
-
- /*
- * First set up FFI types for the 3 struct types
- */
-
- point_type.size = 0; /*sizeof(Point);*/
- point_type.alignment = 0; /*__alignof__(Point);*/
- point_type.type = FFI_TYPE_STRUCT;
- point_type.elements = malloc(3 * sizeof(ffi_type*));
- point_type.elements[0] = &ffi_type_float;
- point_type.elements[1] = &ffi_type_float;
- point_type.elements[2] = NULL;
-
- size_type.size = 0;/* sizeof(Size);*/
- size_type.alignment = 0;/* __alignof__(Size);*/
- size_type.type = FFI_TYPE_STRUCT;
- size_type.elements = malloc(3 * sizeof(ffi_type*));
- size_type.elements[0] = &ffi_type_float;
- size_type.elements[1] = &ffi_type_float;
- size_type.elements[2] = NULL;
-
- rect_type.size = 0;/*sizeof(Rect);*/
- rect_type.alignment =0;/* __alignof__(Rect);*/
- rect_type.type = FFI_TYPE_STRUCT;
- rect_type.elements = malloc(3 * sizeof(ffi_type*));
- rect_type.elements[0] = &point_type;
- rect_type.elements[1] = &size_type;
- rect_type.elements[2] = NULL;
-
- /*
- * Create a CIF
- */
- arglist[0] = &ffi_type_sint;
- arglist[1] = &ffi_type_pointer;
- arglist[2] = &point_type;
- arglist[3] = &rect_type;
- arglist[4] = &ffi_type_sint;
- arglist[5] = NULL;
-
- r = ffi_prep_cif(&cif, FFI_DEFAULT_ABI,
- 5, &ffi_type_sint, arglist);
- if (r != FFI_OK) {
- abort();
- }
-
-
- /* And call the function through the CIF */
-
- {
- Point p = { 1.0, 2.0 };
- Rect r = { { 9.0, 10.0}, { -1.0, -2.0 } };
- int o = 0;
- int l = 42;
- char* m = "myMethod";
- ffi_arg result;
-
- values[0] = &o;
- values[1] = &m;
- values[2] = &p;
- values[3] = &r;
- values[4] = &l;
- values[5] = NULL;
-
- printf("CALLING WITH %d %s {%f %f} {{%f %f} {%f %f}} %d\n",
- o, m, p.x, p.y, r.o.x, r.o.y, r.s.h, r.s.w, l);
-
- ffi_call(&cif, FFI_FN(doit), &result, values);
-
- printf ("The result is %d\n", (int)result);
-
- }
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check different structures.
+ Limitations: none.
+ PR: none.
+ Originator: Ronald Oussoren <oussoren@cistron.nl> 20030824 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct Point {
+ float x;
+ float y;
+} Point;
+
+typedef struct Size {
+ float h;
+ float w;
+} Size;
+
+typedef struct Rect {
+ Point o;
+ Size s;
+} Rect;
+
+int doit(int o, char* s, Point p, Rect r, int last)
+{
+ printf("CALLED WITH %d %s {%f %f} {{%f %f} {%f %f}} %d\n",
+ o, s, p.x, p.y, r.o.x, r.o.y, r.s.h, r.s.w, last);
+ return 42;
+}
+
+
+int main(void)
+{
+ ffi_type point_type;
+ ffi_type size_type;
+ ffi_type rect_type;
+ ffi_cif cif;
+ ffi_type* arglist[6];
+ void* values[6];
+ int r;
+
+ /*
+ * First set up FFI types for the 3 struct types
+ */
+
+ point_type.size = 0; /*sizeof(Point);*/
+ point_type.alignment = 0; /*__alignof__(Point);*/
+ point_type.type = FFI_TYPE_STRUCT;
+ point_type.elements = malloc(3 * sizeof(ffi_type*));
+ point_type.elements[0] = &ffi_type_float;
+ point_type.elements[1] = &ffi_type_float;
+ point_type.elements[2] = NULL;
+
+ size_type.size = 0;/* sizeof(Size);*/
+ size_type.alignment = 0;/* __alignof__(Size);*/
+ size_type.type = FFI_TYPE_STRUCT;
+ size_type.elements = malloc(3 * sizeof(ffi_type*));
+ size_type.elements[0] = &ffi_type_float;
+ size_type.elements[1] = &ffi_type_float;
+ size_type.elements[2] = NULL;
+
+ rect_type.size = 0;/*sizeof(Rect);*/
+ rect_type.alignment =0;/* __alignof__(Rect);*/
+ rect_type.type = FFI_TYPE_STRUCT;
+ rect_type.elements = malloc(3 * sizeof(ffi_type*));
+ rect_type.elements[0] = &point_type;
+ rect_type.elements[1] = &size_type;
+ rect_type.elements[2] = NULL;
+
+ /*
+ * Create a CIF
+ */
+ arglist[0] = &ffi_type_sint;
+ arglist[1] = &ffi_type_pointer;
+ arglist[2] = &point_type;
+ arglist[3] = &rect_type;
+ arglist[4] = &ffi_type_sint;
+ arglist[5] = NULL;
+
+ r = ffi_prep_cif(&cif, FFI_DEFAULT_ABI,
+ 5, &ffi_type_sint, arglist);
+ if (r != FFI_OK) {
+ abort();
+ }
+
+
+ /* And call the function through the CIF */
+
+ {
+ Point p = { 1.0, 2.0 };
+ Rect r = { { 9.0, 10.0}, { -1.0, -2.0 } };
+ int o = 0;
+ int l = 42;
+ char* m = "myMethod";
+ ffi_arg result;
+
+ values[0] = &o;
+ values[1] = &m;
+ values[2] = &p;
+ values[3] = &r;
+ values[4] = &l;
+ values[5] = NULL;
+
+ printf("CALLING WITH %d %s {%f %f} {{%f %f} {%f %f}} %d\n",
+ o, m, p.x, p.y, r.o.x, r.o.y, r.s.h, r.s.w, l);
+
+ ffi_call(&cif, FFI_FN(doit), &result, values);
+
+ printf ("The result is %d\n", (int)result);
+
+ }
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/pyobjc-tc/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/pyobjc-tc/ya.make
index 7d13747286..0f35bf8066 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/pyobjc-tc/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/pyobjc-tc/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- pyobjc-tc.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ pyobjc-tc.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl.c b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl.c
index 26a979e090..fd07e50179 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl.c
@@ -1,36 +1,36 @@
-/* Area: ffi_call
- Purpose: Check return value double.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20050212 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static double return_dbl(double dbl)
-{
- printf ("%f\n", dbl);
- return 2 * dbl;
-}
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- double dbl, rdbl;
-
- args[0] = &ffi_type_double;
- values[0] = &dbl;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_double, args) == FFI_OK);
-
- for (dbl = -127.3; dbl < 127; dbl++)
- {
- ffi_call(&cif, FFI_FN(return_dbl), &rdbl, values);
- printf ("%f vs %f\n", rdbl, return_dbl(dbl));
- CHECK(rdbl == 2 * dbl);
- }
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value double.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20050212 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static double return_dbl(double dbl)
+{
+ printf ("%f\n", dbl);
+ return 2 * dbl;
+}
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ double dbl, rdbl;
+
+ args[0] = &ffi_type_double;
+ values[0] = &dbl;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_double, args) == FFI_OK);
+
+ for (dbl = -127.3; dbl < 127; dbl++)
+ {
+ ffi_call(&cif, FFI_FN(return_dbl), &rdbl, values);
+ printf ("%f vs %f\n", rdbl, return_dbl(dbl));
+ CHECK(rdbl == 2 * dbl);
+ }
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl/ya.make
index eedbf01a14..b660c2d98c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_dbl.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_dbl.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl1.c b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl1.c
index 853e0ec008..0ea5d50551 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl1.c
@@ -1,43 +1,43 @@
-/* Area: ffi_call
- Purpose: Check return value double.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20050212 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static double return_dbl(double dbl1, float fl2, unsigned int in3, double dbl4)
-{
- return dbl1 + fl2 + in3 + dbl4;
-}
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- double dbl1, dbl4, rdbl;
- float fl2;
- unsigned int in3;
- args[0] = &ffi_type_double;
- args[1] = &ffi_type_float;
- args[2] = &ffi_type_uint;
- args[3] = &ffi_type_double;
- values[0] = &dbl1;
- values[1] = &fl2;
- values[2] = &in3;
- values[3] = &dbl4;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
- &ffi_type_double, args) == FFI_OK);
- dbl1 = 127.0;
- fl2 = 128.0;
- in3 = 255;
- dbl4 = 512.7;
-
- ffi_call(&cif, FFI_FN(return_dbl), &rdbl, values);
- printf ("%f vs %f\n", rdbl, return_dbl(dbl1, fl2, in3, dbl4));
- CHECK(rdbl == dbl1 + fl2 + in3 + dbl4);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value double.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20050212 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static double return_dbl(double dbl1, float fl2, unsigned int in3, double dbl4)
+{
+ return dbl1 + fl2 + in3 + dbl4;
+}
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ double dbl1, dbl4, rdbl;
+ float fl2;
+ unsigned int in3;
+ args[0] = &ffi_type_double;
+ args[1] = &ffi_type_float;
+ args[2] = &ffi_type_uint;
+ args[3] = &ffi_type_double;
+ values[0] = &dbl1;
+ values[1] = &fl2;
+ values[2] = &in3;
+ values[3] = &dbl4;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
+ &ffi_type_double, args) == FFI_OK);
+ dbl1 = 127.0;
+ fl2 = 128.0;
+ in3 = 255;
+ dbl4 = 512.7;
+
+ ffi_call(&cif, FFI_FN(return_dbl), &rdbl, values);
+ printf ("%f vs %f\n", rdbl, return_dbl(dbl1, fl2, in3, dbl4));
+ CHECK(rdbl == dbl1 + fl2 + in3 + dbl4);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl1/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl1/ya.make
index 18500db389..ed07c76be8 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_dbl1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_dbl1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl2.c b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl2.c
index df38234c85..b3818f866b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl2.c
@@ -1,42 +1,42 @@
-/* Area: ffi_call
- Purpose: Check return value double.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20050212 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static double return_dbl(double dbl1, double dbl2, unsigned int in3, double dbl4)
-{
- return dbl1 + dbl2 + in3 + dbl4;
-}
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- double dbl1, dbl2, dbl4, rdbl;
- unsigned int in3;
- args[0] = &ffi_type_double;
- args[1] = &ffi_type_double;
- args[2] = &ffi_type_uint;
- args[3] = &ffi_type_double;
- values[0] = &dbl1;
- values[1] = &dbl2;
- values[2] = &in3;
- values[3] = &dbl4;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
- &ffi_type_double, args) == FFI_OK);
- dbl1 = 127.0;
- dbl2 = 128.0;
- in3 = 255;
- dbl4 = 512.7;
-
- ffi_call(&cif, FFI_FN(return_dbl), &rdbl, values);
- printf ("%f vs %f\n", rdbl, return_dbl(dbl1, dbl2, in3, dbl4));
- CHECK(rdbl == dbl1 + dbl2 + in3 + dbl4);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value double.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20050212 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static double return_dbl(double dbl1, double dbl2, unsigned int in3, double dbl4)
+{
+ return dbl1 + dbl2 + in3 + dbl4;
+}
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ double dbl1, dbl2, dbl4, rdbl;
+ unsigned int in3;
+ args[0] = &ffi_type_double;
+ args[1] = &ffi_type_double;
+ args[2] = &ffi_type_uint;
+ args[3] = &ffi_type_double;
+ values[0] = &dbl1;
+ values[1] = &dbl2;
+ values[2] = &in3;
+ values[3] = &dbl4;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
+ &ffi_type_double, args) == FFI_OK);
+ dbl1 = 127.0;
+ dbl2 = 128.0;
+ in3 = 255;
+ dbl4 = 512.7;
+
+ ffi_call(&cif, FFI_FN(return_dbl), &rdbl, values);
+ printf ("%f vs %f\n", rdbl, return_dbl(dbl1, dbl2, in3, dbl4));
+ CHECK(rdbl == dbl1 + dbl2 + in3 + dbl4);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl2/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl2/ya.make
index 9f664d2bf0..c3fa0bd497 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_dbl2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_dbl2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_dbl2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_dbl2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_fl.c b/contrib/restricted/libffi/testsuite/libffi.call/return_fl.c
index 239f434a27..fb8a09e32a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_fl.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_fl.c
@@ -1,35 +1,35 @@
-/* Area: ffi_call
- Purpose: Check return value float.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20050212 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static float return_fl(float fl)
-{
- return 2 * fl;
-}
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- float fl, rfl;
-
- args[0] = &ffi_type_float;
- values[0] = &fl;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_float, args) == FFI_OK);
-
- for (fl = -127.0; fl < 127; fl++)
- {
- ffi_call(&cif, FFI_FN(return_fl), &rfl, values);
- printf ("%f vs %f\n", rfl, return_fl(fl));
- CHECK(rfl == 2 * fl);
- }
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value float.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20050212 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static float return_fl(float fl)
+{
+ return 2 * fl;
+}
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ float fl, rfl;
+
+ args[0] = &ffi_type_float;
+ values[0] = &fl;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_float, args) == FFI_OK);
+
+ for (fl = -127.0; fl < 127; fl++)
+ {
+ ffi_call(&cif, FFI_FN(return_fl), &rfl, values);
+ printf ("%f vs %f\n", rfl, return_fl(fl));
+ CHECK(rfl == 2 * fl);
+ }
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_fl/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_fl/ya.make
index 77823f992a..69e2118be6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_fl/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_fl/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_fl.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_fl.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_fl1.c b/contrib/restricted/libffi/testsuite/libffi.call/return_fl1.c
index 5e57e28630..c3d92c283d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_fl1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_fl1.c
@@ -1,36 +1,36 @@
-/* Area: ffi_call
- Purpose: Check return value float.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20050212 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static float return_fl(float fl1, float fl2)
-{
- return fl1 + fl2;
-}
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- float fl1, fl2, rfl;
-
- args[0] = &ffi_type_float;
- args[1] = &ffi_type_float;
- values[0] = &fl1;
- values[1] = &fl2;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
- &ffi_type_float, args) == FFI_OK);
- fl1 = 127.0;
- fl2 = 128.0;
-
- ffi_call(&cif, FFI_FN(return_fl), &rfl, values);
- printf ("%f vs %f\n", rfl, return_fl(fl1, fl2));
- CHECK(rfl == fl1 + fl2);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value float.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20050212 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static float return_fl(float fl1, float fl2)
+{
+ return fl1 + fl2;
+}
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ float fl1, fl2, rfl;
+
+ args[0] = &ffi_type_float;
+ args[1] = &ffi_type_float;
+ values[0] = &fl1;
+ values[1] = &fl2;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
+ &ffi_type_float, args) == FFI_OK);
+ fl1 = 127.0;
+ fl2 = 128.0;
+
+ ffi_call(&cif, FFI_FN(return_fl), &rfl, values);
+ printf ("%f vs %f\n", rfl, return_fl(fl1, fl2));
+ CHECK(rfl == fl1 + fl2);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_fl1/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_fl1/ya.make
index 82c6d36a5f..faef42e398 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_fl1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_fl1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_fl1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_fl1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_fl2.c b/contrib/restricted/libffi/testsuite/libffi.call/return_fl2.c
index a8e0fb9589..ddb976cc2b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_fl2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_fl2.c
@@ -1,49 +1,49 @@
-/* Area: ffi_call
- Purpose: Check return value float.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20050212 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-/* Use volatile float to avoid false negative on ix86. See PR target/323. */
-static float return_fl(float fl1, float fl2, float fl3, float fl4)
-{
- volatile float sum;
-
- sum = fl1 + fl2 + fl3 + fl4;
- return sum;
-}
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- float fl1, fl2, fl3, fl4, rfl;
- volatile float sum;
-
- args[0] = &ffi_type_float;
- args[1] = &ffi_type_float;
- args[2] = &ffi_type_float;
- args[3] = &ffi_type_float;
- values[0] = &fl1;
- values[1] = &fl2;
- values[2] = &fl3;
- values[3] = &fl4;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
- &ffi_type_float, args) == FFI_OK);
- fl1 = 127.0;
- fl2 = 128.0;
- fl3 = 255.1;
- fl4 = 512.7;
-
- ffi_call(&cif, FFI_FN(return_fl), &rfl, values);
- printf ("%f vs %f\n", rfl, return_fl(fl1, fl2, fl3, fl4));
-
- sum = fl1 + fl2 + fl3 + fl4;
- CHECK(rfl == sum);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value float.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20050212 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+/* Use volatile float to avoid false negative on ix86. See PR target/323. */
+static float return_fl(float fl1, float fl2, float fl3, float fl4)
+{
+ volatile float sum;
+
+ sum = fl1 + fl2 + fl3 + fl4;
+ return sum;
+}
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ float fl1, fl2, fl3, fl4, rfl;
+ volatile float sum;
+
+ args[0] = &ffi_type_float;
+ args[1] = &ffi_type_float;
+ args[2] = &ffi_type_float;
+ args[3] = &ffi_type_float;
+ values[0] = &fl1;
+ values[1] = &fl2;
+ values[2] = &fl3;
+ values[3] = &fl4;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
+ &ffi_type_float, args) == FFI_OK);
+ fl1 = 127.0;
+ fl2 = 128.0;
+ fl3 = 255.1;
+ fl4 = 512.7;
+
+ ffi_call(&cif, FFI_FN(return_fl), &rfl, values);
+ printf ("%f vs %f\n", rfl, return_fl(fl1, fl2, fl3, fl4));
+
+ sum = fl1 + fl2 + fl3 + fl4;
+ CHECK(rfl == sum);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_fl2/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_fl2/ya.make
index d5e577168e..782ef404f2 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_fl2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_fl2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_fl2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_fl2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_fl3.c b/contrib/restricted/libffi/testsuite/libffi.call/return_fl3.c
index a915912271..c37877b18e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_fl3.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_fl3.c
@@ -1,42 +1,42 @@
-/* Area: ffi_call
- Purpose: Check return value float.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20050212 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static float return_fl(float fl1, float fl2, unsigned int in3, float fl4)
-{
- return fl1 + fl2 + in3 + fl4;
-}
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- float fl1, fl2, fl4, rfl;
- unsigned int in3;
- args[0] = &ffi_type_float;
- args[1] = &ffi_type_float;
- args[2] = &ffi_type_uint;
- args[3] = &ffi_type_float;
- values[0] = &fl1;
- values[1] = &fl2;
- values[2] = &in3;
- values[3] = &fl4;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
- &ffi_type_float, args) == FFI_OK);
- fl1 = 127.0;
- fl2 = 128.0;
- in3 = 255;
- fl4 = 512.7;
-
- ffi_call(&cif, FFI_FN(return_fl), &rfl, values);
- printf ("%f vs %f\n", rfl, return_fl(fl1, fl2, in3, fl4));
- CHECK(rfl == fl1 + fl2 + in3 + fl4);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value float.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20050212 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static float return_fl(float fl1, float fl2, unsigned int in3, float fl4)
+{
+ return fl1 + fl2 + in3 + fl4;
+}
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ float fl1, fl2, fl4, rfl;
+ unsigned int in3;
+ args[0] = &ffi_type_float;
+ args[1] = &ffi_type_float;
+ args[2] = &ffi_type_uint;
+ args[3] = &ffi_type_float;
+ values[0] = &fl1;
+ values[1] = &fl2;
+ values[2] = &in3;
+ values[3] = &fl4;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
+ &ffi_type_float, args) == FFI_OK);
+ fl1 = 127.0;
+ fl2 = 128.0;
+ in3 = 255;
+ fl4 = 512.7;
+
+ ffi_call(&cif, FFI_FN(return_fl), &rfl, values);
+ printf ("%f vs %f\n", rfl, return_fl(fl1, fl2, in3, fl4));
+ CHECK(rfl == fl1 + fl2 + in3 + fl4);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_fl3/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_fl3/ya.make
index 3c5295ef9e..18313a6da7 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_fl3/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_fl3/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_fl3.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_fl3.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_ldl.c b/contrib/restricted/libffi/testsuite/libffi.call/return_ldl.c
index cd79d751d5..52a92fe071 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_ldl.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_ldl.c
@@ -1,34 +1,34 @@
-/* Area: ffi_call
- Purpose: Check return value long double.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20071113 */
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-static long double return_ldl(long double ldl)
-{
- return 2*ldl;
-}
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- long double ldl, rldl;
-
- args[0] = &ffi_type_longdouble;
- values[0] = &ldl;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_longdouble, args) == FFI_OK);
-
- for (ldl = -127.0; ldl < 127.0; ldl++)
- {
- ffi_call(&cif, FFI_FN(return_ldl), &rldl, values);
- CHECK(rldl == 2 * ldl);
- }
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value long double.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20071113 */
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+static long double return_ldl(long double ldl)
+{
+ return 2*ldl;
+}
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ long double ldl, rldl;
+
+ args[0] = &ffi_type_longdouble;
+ values[0] = &ldl;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_longdouble, args) == FFI_OK);
+
+ for (ldl = -127.0; ldl < 127.0; ldl++)
+ {
+ ffi_call(&cif, FFI_FN(return_ldl), &rldl, values);
+ CHECK(rldl == 2 * ldl);
+ }
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_ldl/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_ldl/ya.make
index 56f7445737..2aa17147d7 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_ldl/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_ldl/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_ldl.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_ldl.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_ll.c b/contrib/restricted/libffi/testsuite/libffi.call/return_ll.c
index f97c3bd368..ea4a1e4478 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_ll.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_ll.c
@@ -1,41 +1,41 @@
-/* Area: ffi_call
- Purpose: Check return value long long.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-static long long return_ll(long long ll)
-{
- return ll;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- long long rlonglong;
- long long ll;
-
- args[0] = &ffi_type_sint64;
- values[0] = &ll;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_sint64, args) == FFI_OK);
-
- for (ll = 0LL; ll < 100LL; ll++)
- {
- ffi_call(&cif, FFI_FN(return_ll), &rlonglong, values);
- CHECK(rlonglong == ll);
- }
-
- for (ll = 55555555555000LL; ll < 55555555555100LL; ll++)
- {
- ffi_call(&cif, FFI_FN(return_ll), &rlonglong, values);
- CHECK(rlonglong == ll);
- }
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value long long.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+static long long return_ll(long long ll)
+{
+ return ll;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ long long rlonglong;
+ long long ll;
+
+ args[0] = &ffi_type_sint64;
+ values[0] = &ll;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_sint64, args) == FFI_OK);
+
+ for (ll = 0LL; ll < 100LL; ll++)
+ {
+ ffi_call(&cif, FFI_FN(return_ll), &rlonglong, values);
+ CHECK(rlonglong == ll);
+ }
+
+ for (ll = 55555555555000LL; ll < 55555555555100LL; ll++)
+ {
+ ffi_call(&cif, FFI_FN(return_ll), &rlonglong, values);
+ CHECK(rlonglong == ll);
+ }
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_ll/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_ll/ya.make
index fd7d4d78f4..5cb0314096 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_ll/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_ll/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_ll.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_ll.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_ll1.c b/contrib/restricted/libffi/testsuite/libffi.call/return_ll1.c
index 0c5e3f0811..593e8a307c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_ll1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_ll1.c
@@ -1,43 +1,43 @@
-/* Area: ffi_call
- Purpose: Check if long long are passed in the corresponding regs on ppc.
- Limitations: none.
- PR: 20104.
- Originator: <andreast@gcc.gnu.org> 20050222 */
-
-/* { dg-do run } */
-/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */
-#include "ffitest.h"
-static long long return_ll(int ll0, long long ll1, int ll2)
-{
- return ll0 + ll1 + ll2;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- long long rlonglong;
- long long ll1;
- unsigned ll0, ll2;
-
- args[0] = &ffi_type_sint;
- args[1] = &ffi_type_sint64;
- args[2] = &ffi_type_sint;
- values[0] = &ll0;
- values[1] = &ll1;
- values[2] = &ll2;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
- &ffi_type_sint64, args) == FFI_OK);
-
- ll0 = 11111111;
- ll1 = 11111111111000LL;
- ll2 = 11111111;
-
- ffi_call(&cif, FFI_FN(return_ll), &rlonglong, values);
- printf("res: %" PRIdLL ", %" PRIdLL "\n", rlonglong, ll0 + ll1 + ll2);
- /* { dg-output "res: 11111133333222, 11111133333222" } */
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check if long long are passed in the corresponding regs on ppc.
+ Limitations: none.
+ PR: 20104.
+ Originator: <andreast@gcc.gnu.org> 20050222 */
+
+/* { dg-do run } */
+/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */
+#include "ffitest.h"
+static long long return_ll(int ll0, long long ll1, int ll2)
+{
+ return ll0 + ll1 + ll2;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ long long rlonglong;
+ long long ll1;
+ unsigned ll0, ll2;
+
+ args[0] = &ffi_type_sint;
+ args[1] = &ffi_type_sint64;
+ args[2] = &ffi_type_sint;
+ values[0] = &ll0;
+ values[1] = &ll1;
+ values[2] = &ll2;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
+ &ffi_type_sint64, args) == FFI_OK);
+
+ ll0 = 11111111;
+ ll1 = 11111111111000LL;
+ ll2 = 11111111;
+
+ ffi_call(&cif, FFI_FN(return_ll), &rlonglong, values);
+ printf("res: %" PRIdLL ", %" PRIdLL "\n", rlonglong, ll0 + ll1 + ll2);
+ /* { dg-output "res: 11111133333222, 11111133333222" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_ll1/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_ll1/ya.make
index 5e4d9c96f3..fab5a50575 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_ll1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_ll1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_ll1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_ll1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_sc.c b/contrib/restricted/libffi/testsuite/libffi.call/return_sc.c
index cbe0003c67..a36cf3eb88 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_sc.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_sc.c
@@ -1,36 +1,36 @@
-/* Area: ffi_call
- Purpose: Check return value signed char.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static signed char return_sc(signed char sc)
-{
- return sc;
-}
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_arg rint;
- signed char sc;
-
- args[0] = &ffi_type_schar;
- values[0] = &sc;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_schar, args) == FFI_OK);
-
- for (sc = (signed char) -127;
- sc < (signed char) 127; sc++)
- {
- ffi_call(&cif, FFI_FN(return_sc), &rint, values);
- CHECK((signed char)rint == sc);
- }
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value signed char.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static signed char return_sc(signed char sc)
+{
+ return sc;
+}
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_arg rint;
+ signed char sc;
+
+ args[0] = &ffi_type_schar;
+ values[0] = &sc;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_schar, args) == FFI_OK);
+
+ for (sc = (signed char) -127;
+ sc < (signed char) 127; sc++)
+ {
+ ffi_call(&cif, FFI_FN(return_sc), &rint, values);
+ CHECK((signed char)rint == sc);
+ }
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_sc/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_sc/ya.make
index 4589f73831..27c75c2ad5 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_sc/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_sc/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_sc.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_sc.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_sl.c b/contrib/restricted/libffi/testsuite/libffi.call/return_sl.c
index 45031299da..f0fd345f7a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_sl.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_sl.c
@@ -1,38 +1,38 @@
-/* Area: ffi_call
- Purpose: Check if long as return type is handled correctly.
- Limitations: none.
- PR: none.
- */
-
-/* { dg-do run } */
-#include "ffitest.h"
-static long return_sl(long l1, long l2)
-{
- return l1 - l2;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_arg res;
- unsigned long l1, l2;
-
- args[0] = &ffi_type_slong;
- args[1] = &ffi_type_slong;
- values[0] = &l1;
- values[1] = &l2;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
- &ffi_type_slong, args) == FFI_OK);
-
- l1 = 1073741823L;
- l2 = 1073741824L;
-
- ffi_call(&cif, FFI_FN(return_sl), &res, values);
- printf("res: %ld, %ld\n", (long)res, l1 - l2);
- /* { dg-output "res: -1, -1" } */
-
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check if long as return type is handled correctly.
+ Limitations: none.
+ PR: none.
+ */
+
+/* { dg-do run } */
+#include "ffitest.h"
+static long return_sl(long l1, long l2)
+{
+ return l1 - l2;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_arg res;
+ unsigned long l1, l2;
+
+ args[0] = &ffi_type_slong;
+ args[1] = &ffi_type_slong;
+ values[0] = &l1;
+ values[1] = &l2;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
+ &ffi_type_slong, args) == FFI_OK);
+
+ l1 = 1073741823L;
+ l2 = 1073741824L;
+
+ ffi_call(&cif, FFI_FN(return_sl), &res, values);
+ printf("res: %ld, %ld\n", (long)res, l1 - l2);
+ /* { dg-output "res: -1, -1" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_sl/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_sl/ya.make
index ed690f494c..e71a6891d0 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_sl/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_sl/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_sl.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_sl.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_uc.c b/contrib/restricted/libffi/testsuite/libffi.call/return_uc.c
index cea244a5b9..6fe554619d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_uc.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_uc.c
@@ -1,38 +1,38 @@
-/* Area: ffi_call
- Purpose: Check return value unsigned char.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static unsigned char return_uc(unsigned char uc)
-{
- return uc;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_arg rint;
-
- unsigned char uc;
-
- args[0] = &ffi_type_uchar;
- values[0] = &uc;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_uchar, args) == FFI_OK);
-
- for (uc = (unsigned char) '\x00';
- uc < (unsigned char) '\xff'; uc++)
- {
- ffi_call(&cif, FFI_FN(return_uc), &rint, values);
- CHECK((unsigned char)rint == uc);
- }
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check return value unsigned char.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static unsigned char return_uc(unsigned char uc)
+{
+ return uc;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_arg rint;
+
+ unsigned char uc;
+
+ args[0] = &ffi_type_uchar;
+ values[0] = &uc;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_uchar, args) == FFI_OK);
+
+ for (uc = (unsigned char) '\x00';
+ uc < (unsigned char) '\xff'; uc++)
+ {
+ ffi_call(&cif, FFI_FN(return_uc), &rint, values);
+ CHECK((unsigned char)rint == uc);
+ }
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_uc/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_uc/ya.make
index 9b083a3e7e..d06388572c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_uc/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_uc/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_uc.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_uc.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_ul.c b/contrib/restricted/libffi/testsuite/libffi.call/return_ul.c
index 6671ad38a0..12b266f037 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_ul.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_ul.c
@@ -1,38 +1,38 @@
-/* Area: ffi_call
- Purpose: Check if unsigned long as return type is handled correctly.
- Limitations: none.
- PR: none.
- Originator: <kaffeetisch at gmx dot de> 20060724 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-static unsigned long return_ul(unsigned long ul1, unsigned long ul2)
-{
- return ul1 + ul2;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_arg res;
- unsigned long ul1, ul2;
-
- args[0] = &ffi_type_ulong;
- args[1] = &ffi_type_ulong;
- values[0] = &ul1;
- values[1] = &ul2;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
- &ffi_type_ulong, args) == FFI_OK);
-
- ul1 = 1073741823L;
- ul2 = 1073741824L;
-
- ffi_call(&cif, FFI_FN(return_ul), &res, values);
- printf("res: %lu, %lu\n", (unsigned long)res, ul1 + ul2);
- /* { dg-output "res: 2147483647, 2147483647" } */
-
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check if unsigned long as return type is handled correctly.
+ Limitations: none.
+ PR: none.
+ Originator: <kaffeetisch at gmx dot de> 20060724 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+static unsigned long return_ul(unsigned long ul1, unsigned long ul2)
+{
+ return ul1 + ul2;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_arg res;
+ unsigned long ul1, ul2;
+
+ args[0] = &ffi_type_ulong;
+ args[1] = &ffi_type_ulong;
+ values[0] = &ul1;
+ values[1] = &ul2;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
+ &ffi_type_ulong, args) == FFI_OK);
+
+ ul1 = 1073741823L;
+ ul2 = 1073741824L;
+
+ ffi_call(&cif, FFI_FN(return_ul), &res, values);
+ printf("res: %lu, %lu\n", (unsigned long)res, ul1 + ul2);
+ /* { dg-output "res: 2147483647, 2147483647" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/return_ul/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/return_ul/ya.make
index 9dee0fe2f2..087735767b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/return_ul/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/return_ul/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- return_ul.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ return_ul.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/strlen.c b/contrib/restricted/libffi/testsuite/libffi.call/strlen.c
index 2b469c0752..35b70ea4e2 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/strlen.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/strlen.c
@@ -1,44 +1,44 @@
-/* Area: ffi_call
- Purpose: Check strlen function call.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static size_t ABI_ATTR my_strlen(char *s)
-{
- return (strlen(s));
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_arg rint;
- char *s;
-
- args[0] = &ffi_type_pointer;
- values[0] = (void*) &s;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 1,
- &ffi_type_sint, args) == FFI_OK);
-
- s = "a";
- ffi_call(&cif, FFI_FN(my_strlen), &rint, values);
- CHECK(rint == 1);
-
- s = "1234567";
- ffi_call(&cif, FFI_FN(my_strlen), &rint, values);
- CHECK(rint == 7);
-
- s = "1234567890123456789012345";
- ffi_call(&cif, FFI_FN(my_strlen), &rint, values);
- CHECK(rint == 25);
-
- exit (0);
-}
-
+/* Area: ffi_call
+ Purpose: Check strlen function call.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static size_t ABI_ATTR my_strlen(char *s)
+{
+ return (strlen(s));
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_arg rint;
+ char *s;
+
+ args[0] = &ffi_type_pointer;
+ values[0] = (void*) &s;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 1,
+ &ffi_type_sint, args) == FFI_OK);
+
+ s = "a";
+ ffi_call(&cif, FFI_FN(my_strlen), &rint, values);
+ CHECK(rint == 1);
+
+ s = "1234567";
+ ffi_call(&cif, FFI_FN(my_strlen), &rint, values);
+ CHECK(rint == 7);
+
+ s = "1234567890123456789012345";
+ ffi_call(&cif, FFI_FN(my_strlen), &rint, values);
+ CHECK(rint == 25);
+
+ exit (0);
+}
+
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/strlen/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/strlen/ya.make
index af1fcce81a..417008c98d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/strlen/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/strlen/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- strlen.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ strlen.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/strlen2.c b/contrib/restricted/libffi/testsuite/libffi.call/strlen2.c
index 6b6e340a1e..96282bc0a1 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/strlen2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/strlen2.c
@@ -1,49 +1,49 @@
-/* Area: ffi_call
- Purpose: Check strlen function call with additional arguments.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-static size_t ABI_ATTR my_f(char *s, float a)
-{
- return (size_t) ((int) strlen(s) + (int) a);
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_arg rint;
- char *s;
- float v2;
- args[0] = &ffi_type_pointer;
- args[1] = &ffi_type_float;
- values[0] = (void*) &s;
- values[1] = (void*) &v2;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 2,
- &ffi_type_sint, args) == FFI_OK);
-
- s = "a";
- v2 = 0.0;
- ffi_call(&cif, FFI_FN(my_f), &rint, values);
- CHECK(rint == 1);
-
- s = "1234567";
- v2 = -1.0;
- ffi_call(&cif, FFI_FN(my_f), &rint, values);
- CHECK(rint == 6);
-
- s = "1234567890123456789012345";
- v2 = 1.0;
- ffi_call(&cif, FFI_FN(my_f), &rint, values);
- CHECK(rint == 26);
-
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check strlen function call with additional arguments.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+static size_t ABI_ATTR my_f(char *s, float a)
+{
+ return (size_t) ((int) strlen(s) + (int) a);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_arg rint;
+ char *s;
+ float v2;
+ args[0] = &ffi_type_pointer;
+ args[1] = &ffi_type_float;
+ values[0] = (void*) &s;
+ values[1] = (void*) &v2;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 2,
+ &ffi_type_sint, args) == FFI_OK);
+
+ s = "a";
+ v2 = 0.0;
+ ffi_call(&cif, FFI_FN(my_f), &rint, values);
+ CHECK(rint == 1);
+
+ s = "1234567";
+ v2 = -1.0;
+ ffi_call(&cif, FFI_FN(my_f), &rint, values);
+ CHECK(rint == 6);
+
+ s = "1234567890123456789012345";
+ v2 = 1.0;
+ ffi_call(&cif, FFI_FN(my_f), &rint, values);
+ CHECK(rint == 26);
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/strlen2/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/strlen2/ya.make
index 8b81aab111..b5a07eb892 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/strlen2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/strlen2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- strlen2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ strlen2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/strlen3.c b/contrib/restricted/libffi/testsuite/libffi.call/strlen3.c
index 9446b3970e..beba86e9ea 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/strlen3.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/strlen3.c
@@ -1,49 +1,49 @@
-/* Area: ffi_call
- Purpose: Check strlen function call with additional arguments.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-static size_t ABI_ATTR my_f(float a, char *s)
-{
- return (size_t) ((int) strlen(s) + (int) a);
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_arg rint;
- char *s;
- float v2;
- args[1] = &ffi_type_pointer;
- args[0] = &ffi_type_float;
- values[1] = (void*) &s;
- values[0] = (void*) &v2;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 2,
- &ffi_type_sint, args) == FFI_OK);
-
- s = "a";
- v2 = 0.0;
- ffi_call(&cif, FFI_FN(my_f), &rint, values);
- CHECK(rint == 1);
-
- s = "1234567";
- v2 = -1.0;
- ffi_call(&cif, FFI_FN(my_f), &rint, values);
- CHECK(rint == 6);
-
- s = "1234567890123456789012345";
- v2 = 1.0;
- ffi_call(&cif, FFI_FN(my_f), &rint, values);
- CHECK(rint == 26);
-
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check strlen function call with additional arguments.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+static size_t ABI_ATTR my_f(float a, char *s)
+{
+ return (size_t) ((int) strlen(s) + (int) a);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_arg rint;
+ char *s;
+ float v2;
+ args[1] = &ffi_type_pointer;
+ args[0] = &ffi_type_float;
+ values[1] = (void*) &s;
+ values[0] = (void*) &v2;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 2,
+ &ffi_type_sint, args) == FFI_OK);
+
+ s = "a";
+ v2 = 0.0;
+ ffi_call(&cif, FFI_FN(my_f), &rint, values);
+ CHECK(rint == 1);
+
+ s = "1234567";
+ v2 = -1.0;
+ ffi_call(&cif, FFI_FN(my_f), &rint, values);
+ CHECK(rint == 6);
+
+ s = "1234567890123456789012345";
+ v2 = 1.0;
+ ffi_call(&cif, FFI_FN(my_f), &rint, values);
+ CHECK(rint == 26);
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/strlen3/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/strlen3/ya.make
index 45759cbd01..24b6202920 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/strlen3/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/strlen3/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- strlen3.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ strlen3.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/strlen4.c b/contrib/restricted/libffi/testsuite/libffi.call/strlen4.c
index f91c8eaa08..d5d42b4f6d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/strlen4.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/strlen4.c
@@ -1,55 +1,55 @@
-/* Area: ffi_call
- Purpose: Check strlen function call with additional arguments.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-static size_t ABI_ATTR my_f(float a, char *s, int i)
-{
- return (size_t) ((int) strlen(s) + (int) a + i);
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_arg rint;
- char *s;
- int v1;
- float v2;
- args[2] = &ffi_type_sint;
- args[1] = &ffi_type_pointer;
- args[0] = &ffi_type_float;
- values[2] = (void*) &v1;
- values[1] = (void*) &s;
- values[0] = (void*) &v2;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 3,
- &ffi_type_sint, args) == FFI_OK);
-
- s = "a";
- v1 = 1;
- v2 = 0.0;
- ffi_call(&cif, FFI_FN(my_f), &rint, values);
- CHECK(rint == 2);
-
- s = "1234567";
- v2 = -1.0;
- v1 = -2;
- ffi_call(&cif, FFI_FN(my_f), &rint, values);
- CHECK(rint == 4);
-
- s = "1234567890123456789012345";
- v2 = 1.0;
- v1 = 2;
- ffi_call(&cif, FFI_FN(my_f), &rint, values);
- CHECK(rint == 28);
-
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check strlen function call with additional arguments.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+static size_t ABI_ATTR my_f(float a, char *s, int i)
+{
+ return (size_t) ((int) strlen(s) + (int) a + i);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_arg rint;
+ char *s;
+ int v1;
+ float v2;
+ args[2] = &ffi_type_sint;
+ args[1] = &ffi_type_pointer;
+ args[0] = &ffi_type_float;
+ values[2] = (void*) &v1;
+ values[1] = (void*) &s;
+ values[0] = (void*) &v2;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 3,
+ &ffi_type_sint, args) == FFI_OK);
+
+ s = "a";
+ v1 = 1;
+ v2 = 0.0;
+ ffi_call(&cif, FFI_FN(my_f), &rint, values);
+ CHECK(rint == 2);
+
+ s = "1234567";
+ v2 = -1.0;
+ v1 = -2;
+ ffi_call(&cif, FFI_FN(my_f), &rint, values);
+ CHECK(rint == 4);
+
+ s = "1234567890123456789012345";
+ v2 = 1.0;
+ v1 = 2;
+ ffi_call(&cif, FFI_FN(my_f), &rint, values);
+ CHECK(rint == 28);
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/strlen4/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/strlen4/ya.make
index 4a1ec9eb48..2323bae946 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/strlen4/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/strlen4/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- strlen4.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ strlen4.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct1.c b/contrib/restricted/libffi/testsuite/libffi.call/struct1.c
index 33310dd13b..c13e23f872 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct1.c
@@ -1,67 +1,67 @@
-/* Area: ffi_call
- Purpose: Check structures.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct
-{
- unsigned char uc;
- double d;
- unsigned int ui;
-} test_structure_1;
-
-static test_structure_1 ABI_ATTR struct1(test_structure_1 ts)
-{
- ts.uc++;
- ts.d--;
- ts.ui++;
-
- return ts;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_type ts1_type;
- ffi_type *ts1_type_elements[4];
-
- test_structure_1 ts1_arg;
-
- /* This is a hack to get a properly aligned result buffer */
- test_structure_1 *ts1_result =
- (test_structure_1 *) malloc (sizeof(test_structure_1));
-
- ts1_type.size = 0;
- ts1_type.alignment = 0;
- ts1_type.type = FFI_TYPE_STRUCT;
- ts1_type.elements = ts1_type_elements;
- ts1_type_elements[0] = &ffi_type_uchar;
- ts1_type_elements[1] = &ffi_type_double;
- ts1_type_elements[2] = &ffi_type_uint;
- ts1_type_elements[3] = NULL;
-
- args[0] = &ts1_type;
- values[0] = &ts1_arg;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 1,
- &ts1_type, args) == FFI_OK);
-
- ts1_arg.uc = '\x01';
- ts1_arg.d = 3.14159;
- ts1_arg.ui = 555;
-
- ffi_call(&cif, FFI_FN(struct1), ts1_result, values);
-
- CHECK(ts1_result->ui == 556);
- CHECK(ts1_result->d == 3.14159 - 1);
+/* Area: ffi_call
+ Purpose: Check structures.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct
+{
+ unsigned char uc;
+ double d;
+ unsigned int ui;
+} test_structure_1;
+
+static test_structure_1 ABI_ATTR struct1(test_structure_1 ts)
+{
+ ts.uc++;
+ ts.d--;
+ ts.ui++;
+
+ return ts;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_type ts1_type;
+ ffi_type *ts1_type_elements[4];
+
+ test_structure_1 ts1_arg;
+
+ /* This is a hack to get a properly aligned result buffer */
+ test_structure_1 *ts1_result =
+ (test_structure_1 *) malloc (sizeof(test_structure_1));
+
+ ts1_type.size = 0;
+ ts1_type.alignment = 0;
+ ts1_type.type = FFI_TYPE_STRUCT;
+ ts1_type.elements = ts1_type_elements;
+ ts1_type_elements[0] = &ffi_type_uchar;
+ ts1_type_elements[1] = &ffi_type_double;
+ ts1_type_elements[2] = &ffi_type_uint;
+ ts1_type_elements[3] = NULL;
+
+ args[0] = &ts1_type;
+ values[0] = &ts1_arg;
- free (ts1_result);
- exit(0);
-}
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 1,
+ &ts1_type, args) == FFI_OK);
+
+ ts1_arg.uc = '\x01';
+ ts1_arg.d = 3.14159;
+ ts1_arg.ui = 555;
+
+ ffi_call(&cif, FFI_FN(struct1), ts1_result, values);
+
+ CHECK(ts1_result->ui == 556);
+ CHECK(ts1_result->d == 3.14159 - 1);
+
+ free (ts1_result);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct1/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/struct1/ya.make
index d30a37e503..bde5c54505 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- struct1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ struct1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct10.c b/contrib/restricted/libffi/testsuite/libffi.call/struct10.c
index 31d7793684..17b1377424 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct10.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct10.c
@@ -1,57 +1,57 @@
-/* Area: ffi_call
- Purpose: Check structures.
- Limitations: none.
- PR: none.
- Originator: Sergei Trofimovich <slyfox@gentoo.org>
-
- The test originally discovered in ruby's bindings
- for ffi in https://bugs.gentoo.org/634190 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-struct s {
- int s32;
- float f32;
- signed char s8;
-};
-
-struct s make_s(void) {
- struct s r;
- r.s32 = 0x1234;
- r.f32 = 7.0;
- r.s8 = 0x78;
- return r;
-}
-
-int main() {
- ffi_cif cif;
- struct s r;
- ffi_type rtype;
- ffi_type* s_fields[] = {
- &ffi_type_sint,
- &ffi_type_float,
- &ffi_type_schar,
- NULL,
- };
-
- rtype.size = 0;
- rtype.alignment = 0,
- rtype.type = FFI_TYPE_STRUCT,
- rtype.elements = s_fields,
-
- r.s32 = 0xbad;
- r.f32 = 999.999;
- r.s8 = 0x51;
-
- // Here we emulate the following call:
- //r = make_s();
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, &rtype, NULL) == FFI_OK);
- ffi_call(&cif, FFI_FN(make_s), &r, NULL);
-
- CHECK(r.s32 == 0x1234);
- CHECK(r.f32 == 7.0);
- CHECK(r.s8 == 0x78);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check structures.
+ Limitations: none.
+ PR: none.
+ Originator: Sergei Trofimovich <slyfox@gentoo.org>
+
+ The test originally discovered in ruby's bindings
+ for ffi in https://bugs.gentoo.org/634190 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+struct s {
+ int s32;
+ float f32;
+ signed char s8;
+};
+
+struct s make_s(void) {
+ struct s r;
+ r.s32 = 0x1234;
+ r.f32 = 7.0;
+ r.s8 = 0x78;
+ return r;
+}
+
+int main() {
+ ffi_cif cif;
+ struct s r;
+ ffi_type rtype;
+ ffi_type* s_fields[] = {
+ &ffi_type_sint,
+ &ffi_type_float,
+ &ffi_type_schar,
+ NULL,
+ };
+
+ rtype.size = 0;
+ rtype.alignment = 0,
+ rtype.type = FFI_TYPE_STRUCT,
+ rtype.elements = s_fields,
+
+ r.s32 = 0xbad;
+ r.f32 = 999.999;
+ r.s8 = 0x51;
+
+ // Here we emulate the following call:
+ //r = make_s();
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, &rtype, NULL) == FFI_OK);
+ ffi_call(&cif, FFI_FN(make_s), &r, NULL);
+
+ CHECK(r.s32 == 0x1234);
+ CHECK(r.f32 == 7.0);
+ CHECK(r.s8 == 0x78);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct10/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/struct10/ya.make
index 86a081a170..b0d290cd6f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct10/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct10/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- struct10.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ struct10.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct2.c b/contrib/restricted/libffi/testsuite/libffi.call/struct2.c
index d30680eef5..5077a5ee45 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct2.c
@@ -1,67 +1,67 @@
-/* Area: ffi_call
- Purpose: Check structures.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct
-{
- double d1;
- double d2;
-} test_structure_2;
-
-static test_structure_2 ABI_ATTR struct2(test_structure_2 ts)
-{
- ts.d1--;
- ts.d2--;
-
- return ts;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- test_structure_2 ts2_arg;
- ffi_type ts2_type;
- ffi_type *ts2_type_elements[3];
-
- /* This is a hack to get a properly aligned result buffer */
- test_structure_2 *ts2_result =
- (test_structure_2 *) malloc (sizeof(test_structure_2));
-
- ts2_type.size = 0;
- ts2_type.alignment = 0;
- ts2_type.type = FFI_TYPE_STRUCT;
- ts2_type.elements = ts2_type_elements;
- ts2_type_elements[0] = &ffi_type_double;
- ts2_type_elements[1] = &ffi_type_double;
- ts2_type_elements[2] = NULL;
-
- args[0] = &ts2_type;
- values[0] = &ts2_arg;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts2_type, args) == FFI_OK);
-
- ts2_arg.d1 = 5.55;
- ts2_arg.d2 = 6.66;
-
- printf ("%g\n", ts2_arg.d1);
- printf ("%g\n", ts2_arg.d2);
-
- ffi_call(&cif, FFI_FN(struct2), ts2_result, values);
-
- printf ("%g\n", ts2_result->d1);
- printf ("%g\n", ts2_result->d2);
-
- CHECK(ts2_result->d1 == 5.55 - 1);
- CHECK(ts2_result->d2 == 6.66 - 1);
-
- free (ts2_result);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check structures.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct
+{
+ double d1;
+ double d2;
+} test_structure_2;
+
+static test_structure_2 ABI_ATTR struct2(test_structure_2 ts)
+{
+ ts.d1--;
+ ts.d2--;
+
+ return ts;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ test_structure_2 ts2_arg;
+ ffi_type ts2_type;
+ ffi_type *ts2_type_elements[3];
+
+ /* This is a hack to get a properly aligned result buffer */
+ test_structure_2 *ts2_result =
+ (test_structure_2 *) malloc (sizeof(test_structure_2));
+
+ ts2_type.size = 0;
+ ts2_type.alignment = 0;
+ ts2_type.type = FFI_TYPE_STRUCT;
+ ts2_type.elements = ts2_type_elements;
+ ts2_type_elements[0] = &ffi_type_double;
+ ts2_type_elements[1] = &ffi_type_double;
+ ts2_type_elements[2] = NULL;
+
+ args[0] = &ts2_type;
+ values[0] = &ts2_arg;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts2_type, args) == FFI_OK);
+
+ ts2_arg.d1 = 5.55;
+ ts2_arg.d2 = 6.66;
+
+ printf ("%g\n", ts2_arg.d1);
+ printf ("%g\n", ts2_arg.d2);
+
+ ffi_call(&cif, FFI_FN(struct2), ts2_result, values);
+
+ printf ("%g\n", ts2_result->d1);
+ printf ("%g\n", ts2_result->d2);
+
+ CHECK(ts2_result->d1 == 5.55 - 1);
+ CHECK(ts2_result->d2 == 6.66 - 1);
+
+ free (ts2_result);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct2/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/struct2/ya.make
index a6a01d35b3..89d2830e93 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- struct2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ struct2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct3.c b/contrib/restricted/libffi/testsuite/libffi.call/struct3.c
index bf789c6a81..7eba0ead6d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct3.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct3.c
@@ -1,60 +1,60 @@
-/* Area: ffi_call
- Purpose: Check structures.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct
-{
- int si;
-} test_structure_3;
-
-static test_structure_3 ABI_ATTR struct3(test_structure_3 ts)
-{
- ts.si = -(ts.si*2);
-
- return ts;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- int compare_value;
- ffi_type ts3_type;
- ffi_type *ts3_type_elements[2];
-
- test_structure_3 ts3_arg;
- test_structure_3 *ts3_result =
- (test_structure_3 *) malloc (sizeof(test_structure_3));
-
- ts3_type.size = 0;
- ts3_type.alignment = 0;
- ts3_type.type = FFI_TYPE_STRUCT;
- ts3_type.elements = ts3_type_elements;
- ts3_type_elements[0] = &ffi_type_sint;
- ts3_type_elements[1] = NULL;
-
- args[0] = &ts3_type;
- values[0] = &ts3_arg;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 1,
- &ts3_type, args) == FFI_OK);
-
- ts3_arg.si = -123;
- compare_value = ts3_arg.si;
-
- ffi_call(&cif, FFI_FN(struct3), ts3_result, values);
-
- printf ("%d %d\n", ts3_result->si, -(compare_value*2));
-
- CHECK(ts3_result->si == -(compare_value*2));
+/* Area: ffi_call
+ Purpose: Check structures.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct
+{
+ int si;
+} test_structure_3;
+
+static test_structure_3 ABI_ATTR struct3(test_structure_3 ts)
+{
+ ts.si = -(ts.si*2);
+
+ return ts;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ int compare_value;
+ ffi_type ts3_type;
+ ffi_type *ts3_type_elements[2];
+
+ test_structure_3 ts3_arg;
+ test_structure_3 *ts3_result =
+ (test_structure_3 *) malloc (sizeof(test_structure_3));
+
+ ts3_type.size = 0;
+ ts3_type.alignment = 0;
+ ts3_type.type = FFI_TYPE_STRUCT;
+ ts3_type.elements = ts3_type_elements;
+ ts3_type_elements[0] = &ffi_type_sint;
+ ts3_type_elements[1] = NULL;
+
+ args[0] = &ts3_type;
+ values[0] = &ts3_arg;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 1,
+ &ts3_type, args) == FFI_OK);
+
+ ts3_arg.si = -123;
+ compare_value = ts3_arg.si;
- free (ts3_result);
- exit(0);
-}
+ ffi_call(&cif, FFI_FN(struct3), ts3_result, values);
+
+ printf ("%d %d\n", ts3_result->si, -(compare_value*2));
+
+ CHECK(ts3_result->si == -(compare_value*2));
+
+ free (ts3_result);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct3/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/struct3/ya.make
index d824589744..a66e73de0d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct3/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct3/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- struct3.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ struct3.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct4.c b/contrib/restricted/libffi/testsuite/libffi.call/struct4.c
index d59c0d75ef..66a9551dd6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct4.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct4.c
@@ -1,64 +1,64 @@
-/* Area: ffi_call
- Purpose: Check structures.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct
-{
- unsigned ui1;
- unsigned ui2;
- unsigned ui3;
-} test_structure_4;
-
-static test_structure_4 ABI_ATTR struct4(test_structure_4 ts)
-{
- ts.ui3 = ts.ui1 * ts.ui2 * ts.ui3;
-
- return ts;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_type ts4_type;
- ffi_type *ts4_type_elements[4];
-
- test_structure_4 ts4_arg;
-
- /* This is a hack to get a properly aligned result buffer */
- test_structure_4 *ts4_result =
- (test_structure_4 *) malloc (sizeof(test_structure_4));
-
- ts4_type.size = 0;
- ts4_type.alignment = 0;
- ts4_type.type = FFI_TYPE_STRUCT;
- ts4_type.elements = ts4_type_elements;
- ts4_type_elements[0] = &ffi_type_uint;
- ts4_type_elements[1] = &ffi_type_uint;
- ts4_type_elements[2] = &ffi_type_uint;
- ts4_type_elements[3] = NULL;
+/* Area: ffi_call
+ Purpose: Check structures.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct
+{
+ unsigned ui1;
+ unsigned ui2;
+ unsigned ui3;
+} test_structure_4;
+
+static test_structure_4 ABI_ATTR struct4(test_structure_4 ts)
+{
+ ts.ui3 = ts.ui1 * ts.ui2 * ts.ui3;
+
+ return ts;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_type ts4_type;
+ ffi_type *ts4_type_elements[4];
+
+ test_structure_4 ts4_arg;
+
+ /* This is a hack to get a properly aligned result buffer */
+ test_structure_4 *ts4_result =
+ (test_structure_4 *) malloc (sizeof(test_structure_4));
+
+ ts4_type.size = 0;
+ ts4_type.alignment = 0;
+ ts4_type.type = FFI_TYPE_STRUCT;
+ ts4_type.elements = ts4_type_elements;
+ ts4_type_elements[0] = &ffi_type_uint;
+ ts4_type_elements[1] = &ffi_type_uint;
+ ts4_type_elements[2] = &ffi_type_uint;
+ ts4_type_elements[3] = NULL;
+
+ args[0] = &ts4_type;
+ values[0] = &ts4_arg;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts4_type, args) == FFI_OK);
+
+ ts4_arg.ui1 = 2;
+ ts4_arg.ui2 = 3;
+ ts4_arg.ui3 = 4;
+
+ ffi_call (&cif, FFI_FN(struct4), ts4_result, values);
+
+ CHECK(ts4_result->ui3 == 2U * 3U * 4U);
- args[0] = &ts4_type;
- values[0] = &ts4_arg;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts4_type, args) == FFI_OK);
-
- ts4_arg.ui1 = 2;
- ts4_arg.ui2 = 3;
- ts4_arg.ui3 = 4;
-
- ffi_call (&cif, FFI_FN(struct4), ts4_result, values);
-
- CHECK(ts4_result->ui3 == 2U * 3U * 4U);
-
- free (ts4_result);
- exit(0);
-}
+ free (ts4_result);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct4/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/struct4/ya.make
index a150e08750..4be023dd6c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct4/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct4/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- struct4.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ struct4.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct5.c b/contrib/restricted/libffi/testsuite/libffi.call/struct5.c
index 406701381d..23e2a3f745 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct5.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct5.c
@@ -1,66 +1,66 @@
-/* Area: ffi_call
- Purpose: Check structures.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-typedef struct
-{
- char c1;
- char c2;
-} test_structure_5;
-
-static test_structure_5 ABI_ATTR struct5(test_structure_5 ts1, test_structure_5 ts2)
-{
- ts1.c1 += ts2.c1;
- ts1.c2 -= ts2.c2;
-
- return ts1;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_type ts5_type;
- ffi_type *ts5_type_elements[3];
-
- test_structure_5 ts5_arg1, ts5_arg2;
-
- /* This is a hack to get a properly aligned result buffer */
- test_structure_5 *ts5_result =
- (test_structure_5 *) malloc (sizeof(test_structure_5));
-
- ts5_type.size = 0;
- ts5_type.alignment = 0;
- ts5_type.type = FFI_TYPE_STRUCT;
- ts5_type.elements = ts5_type_elements;
- ts5_type_elements[0] = &ffi_type_schar;
- ts5_type_elements[1] = &ffi_type_schar;
- ts5_type_elements[2] = NULL;
-
- args[0] = &ts5_type;
- args[1] = &ts5_type;
- values[0] = &ts5_arg1;
- values[1] = &ts5_arg2;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 2, &ts5_type, args) == FFI_OK);
-
- ts5_arg1.c1 = 2;
- ts5_arg1.c2 = 6;
- ts5_arg2.c1 = 5;
- ts5_arg2.c2 = 3;
-
- ffi_call (&cif, FFI_FN(struct5), ts5_result, values);
-
- CHECK(ts5_result->c1 == 7);
- CHECK(ts5_result->c2 == 3);
-
-
- free (ts5_result);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check structures.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+typedef struct
+{
+ char c1;
+ char c2;
+} test_structure_5;
+
+static test_structure_5 ABI_ATTR struct5(test_structure_5 ts1, test_structure_5 ts2)
+{
+ ts1.c1 += ts2.c1;
+ ts1.c2 -= ts2.c2;
+
+ return ts1;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_type ts5_type;
+ ffi_type *ts5_type_elements[3];
+
+ test_structure_5 ts5_arg1, ts5_arg2;
+
+ /* This is a hack to get a properly aligned result buffer */
+ test_structure_5 *ts5_result =
+ (test_structure_5 *) malloc (sizeof(test_structure_5));
+
+ ts5_type.size = 0;
+ ts5_type.alignment = 0;
+ ts5_type.type = FFI_TYPE_STRUCT;
+ ts5_type.elements = ts5_type_elements;
+ ts5_type_elements[0] = &ffi_type_schar;
+ ts5_type_elements[1] = &ffi_type_schar;
+ ts5_type_elements[2] = NULL;
+
+ args[0] = &ts5_type;
+ args[1] = &ts5_type;
+ values[0] = &ts5_arg1;
+ values[1] = &ts5_arg2;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 2, &ts5_type, args) == FFI_OK);
+
+ ts5_arg1.c1 = 2;
+ ts5_arg1.c2 = 6;
+ ts5_arg2.c1 = 5;
+ ts5_arg2.c2 = 3;
+
+ ffi_call (&cif, FFI_FN(struct5), ts5_result, values);
+
+ CHECK(ts5_result->c1 == 7);
+ CHECK(ts5_result->c2 == 3);
+
+
+ free (ts5_result);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct5/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/struct5/ya.make
index 709d7af4d3..ad74a3d56c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct5/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct5/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- struct5.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ struct5.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct6.c b/contrib/restricted/libffi/testsuite/libffi.call/struct6.c
index e6e7d67f54..173c66eb4d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct6.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct6.c
@@ -1,64 +1,64 @@
-/* Area: ffi_call
- Purpose: Check structures.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-typedef struct
-{
- float f;
- double d;
-} test_structure_6;
-
-static test_structure_6 ABI_ATTR struct6 (test_structure_6 ts)
-{
- ts.f += 1;
- ts.d += 1;
-
- return ts;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_type ts6_type;
- ffi_type *ts6_type_elements[3];
-
- test_structure_6 ts6_arg;
-
- /* This is a hack to get a properly aligned result buffer */
- test_structure_6 *ts6_result =
- (test_structure_6 *) malloc (sizeof(test_structure_6));
-
- ts6_type.size = 0;
- ts6_type.alignment = 0;
- ts6_type.type = FFI_TYPE_STRUCT;
- ts6_type.elements = ts6_type_elements;
- ts6_type_elements[0] = &ffi_type_float;
- ts6_type_elements[1] = &ffi_type_double;
- ts6_type_elements[2] = NULL;
-
- args[0] = &ts6_type;
- values[0] = &ts6_arg;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts6_type, args) == FFI_OK);
-
- ts6_arg.f = 5.55f;
- ts6_arg.d = 6.66;
-
- printf ("%g\n", ts6_arg.f);
- printf ("%g\n", ts6_arg.d);
-
- ffi_call(&cif, FFI_FN(struct6), ts6_result, values);
-
- CHECK(ts6_result->f == 5.55f + 1);
- CHECK(ts6_result->d == 6.66 + 1);
-
- free (ts6_result);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check structures.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+typedef struct
+{
+ float f;
+ double d;
+} test_structure_6;
+
+static test_structure_6 ABI_ATTR struct6 (test_structure_6 ts)
+{
+ ts.f += 1;
+ ts.d += 1;
+
+ return ts;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_type ts6_type;
+ ffi_type *ts6_type_elements[3];
+
+ test_structure_6 ts6_arg;
+
+ /* This is a hack to get a properly aligned result buffer */
+ test_structure_6 *ts6_result =
+ (test_structure_6 *) malloc (sizeof(test_structure_6));
+
+ ts6_type.size = 0;
+ ts6_type.alignment = 0;
+ ts6_type.type = FFI_TYPE_STRUCT;
+ ts6_type.elements = ts6_type_elements;
+ ts6_type_elements[0] = &ffi_type_float;
+ ts6_type_elements[1] = &ffi_type_double;
+ ts6_type_elements[2] = NULL;
+
+ args[0] = &ts6_type;
+ values[0] = &ts6_arg;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts6_type, args) == FFI_OK);
+
+ ts6_arg.f = 5.55f;
+ ts6_arg.d = 6.66;
+
+ printf ("%g\n", ts6_arg.f);
+ printf ("%g\n", ts6_arg.d);
+
+ ffi_call(&cif, FFI_FN(struct6), ts6_result, values);
+
+ CHECK(ts6_result->f == 5.55f + 1);
+ CHECK(ts6_result->d == 6.66 + 1);
+
+ free (ts6_result);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct6/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/struct6/ya.make
index 990cd297b0..fa57f9b947 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct6/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct6/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- struct6.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ struct6.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct7.c b/contrib/restricted/libffi/testsuite/libffi.call/struct7.c
index f2e0669fee..badc7e0556 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct7.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct7.c
@@ -1,74 +1,74 @@
-/* Area: ffi_call
- Purpose: Check structures.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-typedef struct
-{
- float f1;
- float f2;
- double d;
-} test_structure_7;
-
-static test_structure_7 ABI_ATTR struct7 (test_structure_7 ts)
-{
- ts.f1 += 1;
- ts.f2 += 1;
- ts.d += 1;
-
- return ts;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_type ts7_type;
- ffi_type *ts7_type_elements[4];
-
- test_structure_7 ts7_arg;
-
- /* This is a hack to get a properly aligned result buffer */
- test_structure_7 *ts7_result =
- (test_structure_7 *) malloc (sizeof(test_structure_7));
-
- ts7_type.size = 0;
- ts7_type.alignment = 0;
- ts7_type.type = FFI_TYPE_STRUCT;
- ts7_type.elements = ts7_type_elements;
- ts7_type_elements[0] = &ffi_type_float;
- ts7_type_elements[1] = &ffi_type_float;
- ts7_type_elements[2] = &ffi_type_double;
- ts7_type_elements[3] = NULL;
-
- args[0] = &ts7_type;
- values[0] = &ts7_arg;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts7_type, args) == FFI_OK);
-
- ts7_arg.f1 = 5.55f;
- ts7_arg.f2 = 55.5f;
- ts7_arg.d = 6.66;
-
- printf ("%g\n", ts7_arg.f1);
- printf ("%g\n", ts7_arg.f2);
- printf ("%g\n", ts7_arg.d);
-
- ffi_call(&cif, FFI_FN(struct7), ts7_result, values);
-
- printf ("%g\n", ts7_result->f1);
- printf ("%g\n", ts7_result->f2);
- printf ("%g\n", ts7_result->d);
-
- CHECK(ts7_result->f1 == 5.55f + 1);
- CHECK(ts7_result->f2 == 55.5f + 1);
- CHECK(ts7_result->d == 6.66 + 1);
-
- free (ts7_result);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check structures.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+typedef struct
+{
+ float f1;
+ float f2;
+ double d;
+} test_structure_7;
+
+static test_structure_7 ABI_ATTR struct7 (test_structure_7 ts)
+{
+ ts.f1 += 1;
+ ts.f2 += 1;
+ ts.d += 1;
+
+ return ts;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_type ts7_type;
+ ffi_type *ts7_type_elements[4];
+
+ test_structure_7 ts7_arg;
+
+ /* This is a hack to get a properly aligned result buffer */
+ test_structure_7 *ts7_result =
+ (test_structure_7 *) malloc (sizeof(test_structure_7));
+
+ ts7_type.size = 0;
+ ts7_type.alignment = 0;
+ ts7_type.type = FFI_TYPE_STRUCT;
+ ts7_type.elements = ts7_type_elements;
+ ts7_type_elements[0] = &ffi_type_float;
+ ts7_type_elements[1] = &ffi_type_float;
+ ts7_type_elements[2] = &ffi_type_double;
+ ts7_type_elements[3] = NULL;
+
+ args[0] = &ts7_type;
+ values[0] = &ts7_arg;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts7_type, args) == FFI_OK);
+
+ ts7_arg.f1 = 5.55f;
+ ts7_arg.f2 = 55.5f;
+ ts7_arg.d = 6.66;
+
+ printf ("%g\n", ts7_arg.f1);
+ printf ("%g\n", ts7_arg.f2);
+ printf ("%g\n", ts7_arg.d);
+
+ ffi_call(&cif, FFI_FN(struct7), ts7_result, values);
+
+ printf ("%g\n", ts7_result->f1);
+ printf ("%g\n", ts7_result->f2);
+ printf ("%g\n", ts7_result->d);
+
+ CHECK(ts7_result->f1 == 5.55f + 1);
+ CHECK(ts7_result->f2 == 55.5f + 1);
+ CHECK(ts7_result->d == 6.66 + 1);
+
+ free (ts7_result);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct7/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/struct7/ya.make
index 534daae46b..5317e30fc3 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct7/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct7/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- struct7.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ struct7.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct8.c b/contrib/restricted/libffi/testsuite/libffi.call/struct8.c
index 707ecf1fcc..ef204ecbbc 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct8.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct8.c
@@ -1,81 +1,81 @@
-/* Area: ffi_call
- Purpose: Check structures.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-typedef struct
-{
- float f1;
- float f2;
- float f3;
- float f4;
-} test_structure_8;
-
-static test_structure_8 ABI_ATTR struct8 (test_structure_8 ts)
-{
- ts.f1 += 1;
- ts.f2 += 1;
- ts.f3 += 1;
- ts.f4 += 1;
-
- return ts;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_type ts8_type;
- ffi_type *ts8_type_elements[5];
-
- test_structure_8 ts8_arg;
-
- /* This is a hack to get a properly aligned result buffer */
- test_structure_8 *ts8_result =
- (test_structure_8 *) malloc (sizeof(test_structure_8));
-
- ts8_type.size = 0;
- ts8_type.alignment = 0;
- ts8_type.type = FFI_TYPE_STRUCT;
- ts8_type.elements = ts8_type_elements;
- ts8_type_elements[0] = &ffi_type_float;
- ts8_type_elements[1] = &ffi_type_float;
- ts8_type_elements[2] = &ffi_type_float;
- ts8_type_elements[3] = &ffi_type_float;
- ts8_type_elements[4] = NULL;
-
- args[0] = &ts8_type;
- values[0] = &ts8_arg;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts8_type, args) == FFI_OK);
-
- ts8_arg.f1 = 5.55f;
- ts8_arg.f2 = 55.5f;
- ts8_arg.f3 = -5.55f;
- ts8_arg.f4 = -55.5f;
-
- printf ("%g\n", ts8_arg.f1);
- printf ("%g\n", ts8_arg.f2);
- printf ("%g\n", ts8_arg.f3);
- printf ("%g\n", ts8_arg.f4);
-
- ffi_call(&cif, FFI_FN(struct8), ts8_result, values);
-
- printf ("%g\n", ts8_result->f1);
- printf ("%g\n", ts8_result->f2);
- printf ("%g\n", ts8_result->f3);
- printf ("%g\n", ts8_result->f4);
-
- CHECK(ts8_result->f1 == 5.55f + 1);
- CHECK(ts8_result->f2 == 55.5f + 1);
- CHECK(ts8_result->f3 == -5.55f + 1);
- CHECK(ts8_result->f4 == -55.5f + 1);
-
- free (ts8_result);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check structures.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+typedef struct
+{
+ float f1;
+ float f2;
+ float f3;
+ float f4;
+} test_structure_8;
+
+static test_structure_8 ABI_ATTR struct8 (test_structure_8 ts)
+{
+ ts.f1 += 1;
+ ts.f2 += 1;
+ ts.f3 += 1;
+ ts.f4 += 1;
+
+ return ts;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_type ts8_type;
+ ffi_type *ts8_type_elements[5];
+
+ test_structure_8 ts8_arg;
+
+ /* This is a hack to get a properly aligned result buffer */
+ test_structure_8 *ts8_result =
+ (test_structure_8 *) malloc (sizeof(test_structure_8));
+
+ ts8_type.size = 0;
+ ts8_type.alignment = 0;
+ ts8_type.type = FFI_TYPE_STRUCT;
+ ts8_type.elements = ts8_type_elements;
+ ts8_type_elements[0] = &ffi_type_float;
+ ts8_type_elements[1] = &ffi_type_float;
+ ts8_type_elements[2] = &ffi_type_float;
+ ts8_type_elements[3] = &ffi_type_float;
+ ts8_type_elements[4] = NULL;
+
+ args[0] = &ts8_type;
+ values[0] = &ts8_arg;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts8_type, args) == FFI_OK);
+
+ ts8_arg.f1 = 5.55f;
+ ts8_arg.f2 = 55.5f;
+ ts8_arg.f3 = -5.55f;
+ ts8_arg.f4 = -55.5f;
+
+ printf ("%g\n", ts8_arg.f1);
+ printf ("%g\n", ts8_arg.f2);
+ printf ("%g\n", ts8_arg.f3);
+ printf ("%g\n", ts8_arg.f4);
+
+ ffi_call(&cif, FFI_FN(struct8), ts8_result, values);
+
+ printf ("%g\n", ts8_result->f1);
+ printf ("%g\n", ts8_result->f2);
+ printf ("%g\n", ts8_result->f3);
+ printf ("%g\n", ts8_result->f4);
+
+ CHECK(ts8_result->f1 == 5.55f + 1);
+ CHECK(ts8_result->f2 == 55.5f + 1);
+ CHECK(ts8_result->f3 == -5.55f + 1);
+ CHECK(ts8_result->f4 == -55.5f + 1);
+
+ free (ts8_result);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct8/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/struct8/ya.make
index 8454c49f59..3636773e8d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct8/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct8/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- struct8.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ struct8.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct9.c b/contrib/restricted/libffi/testsuite/libffi.call/struct9.c
index d76bf44f65..4a13b818c4 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct9.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct9.c
@@ -1,68 +1,68 @@
-/* Area: ffi_call
- Purpose: Check structures.
- Limitations: none.
- PR: none.
- Originator: From the original ffitest.c */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct
-{
- float f;
- int i;
-} test_structure_9;
-
-static test_structure_9 ABI_ATTR struct9 (test_structure_9 ts)
-{
- ts.f += 1;
- ts.i += 1;
-
- return ts;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_type ts9_type;
- ffi_type *ts9_type_elements[3];
-
- test_structure_9 ts9_arg;
-
- /* This is a hack to get a properly aligned result buffer */
- test_structure_9 *ts9_result =
- (test_structure_9 *) malloc (sizeof(test_structure_9));
-
- ts9_type.size = 0;
- ts9_type.alignment = 0;
- ts9_type.type = FFI_TYPE_STRUCT;
- ts9_type.elements = ts9_type_elements;
- ts9_type_elements[0] = &ffi_type_float;
- ts9_type_elements[1] = &ffi_type_sint;
- ts9_type_elements[2] = NULL;
-
- args[0] = &ts9_type;
- values[0] = &ts9_arg;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts9_type, args) == FFI_OK);
-
- ts9_arg.f = 5.55f;
- ts9_arg.i = 5;
-
- printf ("%g\n", ts9_arg.f);
- printf ("%d\n", ts9_arg.i);
-
- ffi_call(&cif, FFI_FN(struct9), ts9_result, values);
-
- printf ("%g\n", ts9_result->f);
- printf ("%d\n", ts9_result->i);
-
- CHECK(ts9_result->f == 5.55f + 1);
- CHECK(ts9_result->i == 5 + 1);
-
- free (ts9_result);
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check structures.
+ Limitations: none.
+ PR: none.
+ Originator: From the original ffitest.c */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct
+{
+ float f;
+ int i;
+} test_structure_9;
+
+static test_structure_9 ABI_ATTR struct9 (test_structure_9 ts)
+{
+ ts.f += 1;
+ ts.i += 1;
+
+ return ts;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_type ts9_type;
+ ffi_type *ts9_type_elements[3];
+
+ test_structure_9 ts9_arg;
+
+ /* This is a hack to get a properly aligned result buffer */
+ test_structure_9 *ts9_result =
+ (test_structure_9 *) malloc (sizeof(test_structure_9));
+
+ ts9_type.size = 0;
+ ts9_type.alignment = 0;
+ ts9_type.type = FFI_TYPE_STRUCT;
+ ts9_type.elements = ts9_type_elements;
+ ts9_type_elements[0] = &ffi_type_float;
+ ts9_type_elements[1] = &ffi_type_sint;
+ ts9_type_elements[2] = NULL;
+
+ args[0] = &ts9_type;
+ values[0] = &ts9_arg;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts9_type, args) == FFI_OK);
+
+ ts9_arg.f = 5.55f;
+ ts9_arg.i = 5;
+
+ printf ("%g\n", ts9_arg.f);
+ printf ("%d\n", ts9_arg.i);
+
+ ffi_call(&cif, FFI_FN(struct9), ts9_result, values);
+
+ printf ("%g\n", ts9_result->f);
+ printf ("%d\n", ts9_result->i);
+
+ CHECK(ts9_result->f == 5.55f + 1);
+ CHECK(ts9_result->i == 5 + 1);
+
+ free (ts9_result);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/struct9/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/struct9/ya.make
index 3727a93cff..ea77dc881e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/struct9/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/struct9/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- struct9.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ struct9.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/uninitialized.c b/contrib/restricted/libffi/testsuite/libffi.call/uninitialized.c
index 4feaadf8ad..f00d830234 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/uninitialized.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/uninitialized.c
@@ -1,61 +1,61 @@
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct
-{
- unsigned char uc;
- double d;
- unsigned int ui;
-} test_structure_1;
-
-static test_structure_1 struct1(test_structure_1 ts)
-{
- ts.uc++;
- ts.d--;
- ts.ui++;
-
- return ts;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- ffi_type ts1_type;
- ffi_type *ts1_type_elements[4];
-
- memset(&cif, 1, sizeof(cif));
- ts1_type.size = 0;
- ts1_type.alignment = 0;
- ts1_type.type = FFI_TYPE_STRUCT;
- ts1_type.elements = ts1_type_elements;
- ts1_type_elements[0] = &ffi_type_uchar;
- ts1_type_elements[1] = &ffi_type_double;
- ts1_type_elements[2] = &ffi_type_uint;
- ts1_type_elements[3] = NULL;
-
- test_structure_1 ts1_arg;
- /* This is a hack to get a properly aligned result buffer */
- test_structure_1 *ts1_result =
- (test_structure_1 *) malloc (sizeof(test_structure_1));
-
- args[0] = &ts1_type;
- values[0] = &ts1_arg;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ts1_type, args) == FFI_OK);
-
- ts1_arg.uc = '\x01';
- ts1_arg.d = 3.14159;
- ts1_arg.ui = 555;
-
- ffi_call(&cif, FFI_FN(struct1), ts1_result, values);
-
- CHECK(ts1_result->ui == 556);
- CHECK(ts1_result->d == 3.14159 - 1);
-
- free (ts1_result);
- exit(0);
-}
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct
+{
+ unsigned char uc;
+ double d;
+ unsigned int ui;
+} test_structure_1;
+
+static test_structure_1 struct1(test_structure_1 ts)
+{
+ ts.uc++;
+ ts.d--;
+ ts.ui++;
+
+ return ts;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ ffi_type ts1_type;
+ ffi_type *ts1_type_elements[4];
+
+ memset(&cif, 1, sizeof(cif));
+ ts1_type.size = 0;
+ ts1_type.alignment = 0;
+ ts1_type.type = FFI_TYPE_STRUCT;
+ ts1_type.elements = ts1_type_elements;
+ ts1_type_elements[0] = &ffi_type_uchar;
+ ts1_type_elements[1] = &ffi_type_double;
+ ts1_type_elements[2] = &ffi_type_uint;
+ ts1_type_elements[3] = NULL;
+
+ test_structure_1 ts1_arg;
+ /* This is a hack to get a properly aligned result buffer */
+ test_structure_1 *ts1_result =
+ (test_structure_1 *) malloc (sizeof(test_structure_1));
+
+ args[0] = &ts1_type;
+ values[0] = &ts1_arg;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ts1_type, args) == FFI_OK);
+
+ ts1_arg.uc = '\x01';
+ ts1_arg.d = 3.14159;
+ ts1_arg.ui = 555;
+
+ ffi_call(&cif, FFI_FN(struct1), ts1_result, values);
+
+ CHECK(ts1_result->ui == 556);
+ CHECK(ts1_result->d == 3.14159 - 1);
+
+ free (ts1_result);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/uninitialized/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/uninitialized/ya.make
index 00193ac630..f61b12d035 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/uninitialized/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/uninitialized/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- uninitialized.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ uninitialized.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/va_1.c b/contrib/restricted/libffi/testsuite/libffi.call/va_1.c
index 61697b1862..59d085c832 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/va_1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/va_1.c
@@ -1,196 +1,196 @@
-/* Area: ffi_call
- Purpose: Test passing struct in variable argument lists.
- Limitations: none.
- PR: none.
- Originator: ARM Ltd. */
-
-/* { dg-do run } */
-/* { dg-output "" { xfail avr32*-*-* m68k-*-* alpha-*-* } } */
-
-#include "ffitest.h"
-#include <stdarg.h>
-
-struct small_tag
-{
- unsigned char a;
- unsigned char b;
-};
-
-struct large_tag
-{
- unsigned a;
- unsigned b;
- unsigned c;
- unsigned d;
- unsigned e;
-};
-
-static int
-test_fn (int n, ...)
-{
- va_list ap;
- struct small_tag s1;
- struct small_tag s2;
- struct large_tag l;
- unsigned char uc;
- signed char sc;
- unsigned short us;
- signed short ss;
- unsigned int ui;
- signed int si;
- unsigned long ul;
- signed long sl;
- float f;
- double d;
-
- va_start (ap, n);
- s1 = va_arg (ap, struct small_tag);
- l = va_arg (ap, struct large_tag);
- s2 = va_arg (ap, struct small_tag);
-
- uc = va_arg (ap, unsigned);
- sc = va_arg (ap, signed);
-
- us = va_arg (ap, unsigned);
- ss = va_arg (ap, signed);
-
- ui = va_arg (ap, unsigned int);
- si = va_arg (ap, signed int);
-
- ul = va_arg (ap, unsigned long);
- sl = va_arg (ap, signed long);
-
- f = va_arg (ap, double); /* C standard promotes float->double
- when anonymous */
- d = va_arg (ap, double);
-
- printf ("%u %u %u %u %u %u %u %u %u uc=%u sc=%d %u %d %u %d %lu %ld %f %f\n",
- s1.a, s1.b, l.a, l.b, l.c, l.d, l.e,
- s2.a, s2.b,
- uc, sc,
- us, ss,
- ui, si,
- ul, sl,
- f, d);
- va_end (ap);
- return n + 1;
-}
-
-int
-main (void)
-{
- ffi_cif cif;
- void* args[15];
- ffi_type* arg_types[15];
-
- ffi_type s_type;
- ffi_type *s_type_elements[3];
-
- ffi_type l_type;
- ffi_type *l_type_elements[6];
-
- struct small_tag s1;
- struct small_tag s2;
- struct large_tag l1;
-
- int n;
- ffi_arg res;
-
- unsigned char uc;
- signed char sc;
- unsigned short us;
- signed short ss;
- unsigned int ui;
- signed int si;
- unsigned long ul;
- signed long sl;
- double d1;
- double f1;
-
- s_type.size = 0;
- s_type.alignment = 0;
- s_type.type = FFI_TYPE_STRUCT;
- s_type.elements = s_type_elements;
-
- s_type_elements[0] = &ffi_type_uchar;
- s_type_elements[1] = &ffi_type_uchar;
- s_type_elements[2] = NULL;
-
- l_type.size = 0;
- l_type.alignment = 0;
- l_type.type = FFI_TYPE_STRUCT;
- l_type.elements = l_type_elements;
-
- l_type_elements[0] = &ffi_type_uint;
- l_type_elements[1] = &ffi_type_uint;
- l_type_elements[2] = &ffi_type_uint;
- l_type_elements[3] = &ffi_type_uint;
- l_type_elements[4] = &ffi_type_uint;
- l_type_elements[5] = NULL;
-
- arg_types[0] = &ffi_type_sint;
- arg_types[1] = &s_type;
- arg_types[2] = &l_type;
- arg_types[3] = &s_type;
- arg_types[4] = &ffi_type_uchar;
- arg_types[5] = &ffi_type_schar;
- arg_types[6] = &ffi_type_ushort;
- arg_types[7] = &ffi_type_sshort;
- arg_types[8] = &ffi_type_uint;
- arg_types[9] = &ffi_type_sint;
- arg_types[10] = &ffi_type_ulong;
- arg_types[11] = &ffi_type_slong;
- arg_types[12] = &ffi_type_double;
- arg_types[13] = &ffi_type_double;
- arg_types[14] = NULL;
-
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 14, &ffi_type_sint, arg_types) == FFI_OK);
-
- s1.a = 5;
- s1.b = 6;
-
- l1.a = 10;
- l1.b = 11;
- l1.c = 12;
- l1.d = 13;
- l1.e = 14;
-
- s2.a = 7;
- s2.b = 8;
-
- n = 41;
-
- uc = 9;
- sc = 10;
- us = 11;
- ss = 12;
- ui = 13;
- si = 14;
- ul = 15;
- sl = 16;
- f1 = 2.12;
- d1 = 3.13;
-
- args[0] = &n;
- args[1] = &s1;
- args[2] = &l1;
- args[3] = &s2;
- args[4] = &uc;
- args[5] = &sc;
- args[6] = &us;
- args[7] = &ss;
- args[8] = &ui;
- args[9] = &si;
- args[10] = &ul;
- args[11] = &sl;
- args[12] = &f1;
- args[13] = &d1;
- args[14] = NULL;
-
- ffi_call(&cif, FFI_FN(test_fn), &res, args);
- /* { dg-output "5 6 10 11 12 13 14 7 8 uc=9 sc=10 11 12 13 14 15 16 2.120000 3.130000" } */
- printf("res: %d\n", (int) res);
- /* { dg-output "\nres: 42" } */
-
- return 0;
-}
+/* Area: ffi_call
+ Purpose: Test passing struct in variable argument lists.
+ Limitations: none.
+ PR: none.
+ Originator: ARM Ltd. */
+
+/* { dg-do run } */
+/* { dg-output "" { xfail avr32*-*-* m68k-*-* alpha-*-* } } */
+
+#include "ffitest.h"
+#include <stdarg.h>
+
+struct small_tag
+{
+ unsigned char a;
+ unsigned char b;
+};
+
+struct large_tag
+{
+ unsigned a;
+ unsigned b;
+ unsigned c;
+ unsigned d;
+ unsigned e;
+};
+
+static int
+test_fn (int n, ...)
+{
+ va_list ap;
+ struct small_tag s1;
+ struct small_tag s2;
+ struct large_tag l;
+ unsigned char uc;
+ signed char sc;
+ unsigned short us;
+ signed short ss;
+ unsigned int ui;
+ signed int si;
+ unsigned long ul;
+ signed long sl;
+ float f;
+ double d;
+
+ va_start (ap, n);
+ s1 = va_arg (ap, struct small_tag);
+ l = va_arg (ap, struct large_tag);
+ s2 = va_arg (ap, struct small_tag);
+
+ uc = va_arg (ap, unsigned);
+ sc = va_arg (ap, signed);
+
+ us = va_arg (ap, unsigned);
+ ss = va_arg (ap, signed);
+
+ ui = va_arg (ap, unsigned int);
+ si = va_arg (ap, signed int);
+
+ ul = va_arg (ap, unsigned long);
+ sl = va_arg (ap, signed long);
+
+ f = va_arg (ap, double); /* C standard promotes float->double
+ when anonymous */
+ d = va_arg (ap, double);
+
+ printf ("%u %u %u %u %u %u %u %u %u uc=%u sc=%d %u %d %u %d %lu %ld %f %f\n",
+ s1.a, s1.b, l.a, l.b, l.c, l.d, l.e,
+ s2.a, s2.b,
+ uc, sc,
+ us, ss,
+ ui, si,
+ ul, sl,
+ f, d);
+ va_end (ap);
+ return n + 1;
+}
+
+int
+main (void)
+{
+ ffi_cif cif;
+ void* args[15];
+ ffi_type* arg_types[15];
+
+ ffi_type s_type;
+ ffi_type *s_type_elements[3];
+
+ ffi_type l_type;
+ ffi_type *l_type_elements[6];
+
+ struct small_tag s1;
+ struct small_tag s2;
+ struct large_tag l1;
+
+ int n;
+ ffi_arg res;
+
+ unsigned char uc;
+ signed char sc;
+ unsigned short us;
+ signed short ss;
+ unsigned int ui;
+ signed int si;
+ unsigned long ul;
+ signed long sl;
+ double d1;
+ double f1;
+
+ s_type.size = 0;
+ s_type.alignment = 0;
+ s_type.type = FFI_TYPE_STRUCT;
+ s_type.elements = s_type_elements;
+
+ s_type_elements[0] = &ffi_type_uchar;
+ s_type_elements[1] = &ffi_type_uchar;
+ s_type_elements[2] = NULL;
+
+ l_type.size = 0;
+ l_type.alignment = 0;
+ l_type.type = FFI_TYPE_STRUCT;
+ l_type.elements = l_type_elements;
+
+ l_type_elements[0] = &ffi_type_uint;
+ l_type_elements[1] = &ffi_type_uint;
+ l_type_elements[2] = &ffi_type_uint;
+ l_type_elements[3] = &ffi_type_uint;
+ l_type_elements[4] = &ffi_type_uint;
+ l_type_elements[5] = NULL;
+
+ arg_types[0] = &ffi_type_sint;
+ arg_types[1] = &s_type;
+ arg_types[2] = &l_type;
+ arg_types[3] = &s_type;
+ arg_types[4] = &ffi_type_uchar;
+ arg_types[5] = &ffi_type_schar;
+ arg_types[6] = &ffi_type_ushort;
+ arg_types[7] = &ffi_type_sshort;
+ arg_types[8] = &ffi_type_uint;
+ arg_types[9] = &ffi_type_sint;
+ arg_types[10] = &ffi_type_ulong;
+ arg_types[11] = &ffi_type_slong;
+ arg_types[12] = &ffi_type_double;
+ arg_types[13] = &ffi_type_double;
+ arg_types[14] = NULL;
+
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 14, &ffi_type_sint, arg_types) == FFI_OK);
+
+ s1.a = 5;
+ s1.b = 6;
+
+ l1.a = 10;
+ l1.b = 11;
+ l1.c = 12;
+ l1.d = 13;
+ l1.e = 14;
+
+ s2.a = 7;
+ s2.b = 8;
+
+ n = 41;
+
+ uc = 9;
+ sc = 10;
+ us = 11;
+ ss = 12;
+ ui = 13;
+ si = 14;
+ ul = 15;
+ sl = 16;
+ f1 = 2.12;
+ d1 = 3.13;
+
+ args[0] = &n;
+ args[1] = &s1;
+ args[2] = &l1;
+ args[3] = &s2;
+ args[4] = &uc;
+ args[5] = &sc;
+ args[6] = &us;
+ args[7] = &ss;
+ args[8] = &ui;
+ args[9] = &si;
+ args[10] = &ul;
+ args[11] = &sl;
+ args[12] = &f1;
+ args[13] = &d1;
+ args[14] = NULL;
+
+ ffi_call(&cif, FFI_FN(test_fn), &res, args);
+ /* { dg-output "5 6 10 11 12 13 14 7 8 uc=9 sc=10 11 12 13 14 15 16 2.120000 3.130000" } */
+ printf("res: %d\n", (int) res);
+ /* { dg-output "\nres: 42" } */
+
+ return 0;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/va_1/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/va_1/ya.make
index 92ae24cc9a..6957e760a2 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/va_1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/va_1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- va_1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ va_1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/va_struct1.c b/contrib/restricted/libffi/testsuite/libffi.call/va_struct1.c
index 14ff4691a3..e6452061c1 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/va_struct1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/va_struct1.c
@@ -1,121 +1,121 @@
-/* Area: ffi_call
- Purpose: Test passing struct in variable argument lists.
- Limitations: none.
- PR: none.
- Originator: ARM Ltd. */
-
-/* { dg-do run } */
-/* { dg-output "" { xfail avr32*-*-* } } */
-
-#include "ffitest.h"
-#include <stdarg.h>
-
-struct small_tag
-{
- unsigned char a;
- unsigned char b;
-};
-
-struct large_tag
-{
- unsigned a;
- unsigned b;
- unsigned c;
- unsigned d;
- unsigned e;
-};
-
-static int
-test_fn (int n, ...)
-{
- va_list ap;
- struct small_tag s1;
- struct small_tag s2;
- struct large_tag l;
-
- va_start (ap, n);
- s1 = va_arg (ap, struct small_tag);
- l = va_arg (ap, struct large_tag);
- s2 = va_arg (ap, struct small_tag);
- printf ("%u %u %u %u %u %u %u %u %u\n", s1.a, s1.b, l.a, l.b, l.c, l.d, l.e,
- s2.a, s2.b);
- va_end (ap);
- return n + 1;
-}
-
-int
-main (void)
-{
- ffi_cif cif;
- void* args[5];
- ffi_type* arg_types[5];
-
- ffi_type s_type;
- ffi_type *s_type_elements[3];
-
- ffi_type l_type;
- ffi_type *l_type_elements[6];
-
- struct small_tag s1;
- struct small_tag s2;
- struct large_tag l1;
-
- int n;
- ffi_arg res;
-
- s_type.size = 0;
- s_type.alignment = 0;
- s_type.type = FFI_TYPE_STRUCT;
- s_type.elements = s_type_elements;
-
- s_type_elements[0] = &ffi_type_uchar;
- s_type_elements[1] = &ffi_type_uchar;
- s_type_elements[2] = NULL;
-
- l_type.size = 0;
- l_type.alignment = 0;
- l_type.type = FFI_TYPE_STRUCT;
- l_type.elements = l_type_elements;
-
- l_type_elements[0] = &ffi_type_uint;
- l_type_elements[1] = &ffi_type_uint;
- l_type_elements[2] = &ffi_type_uint;
- l_type_elements[3] = &ffi_type_uint;
- l_type_elements[4] = &ffi_type_uint;
- l_type_elements[5] = NULL;
-
- arg_types[0] = &ffi_type_sint;
- arg_types[1] = &s_type;
- arg_types[2] = &l_type;
- arg_types[3] = &s_type;
- arg_types[4] = NULL;
-
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &ffi_type_sint, arg_types) == FFI_OK);
-
- s1.a = 5;
- s1.b = 6;
-
- l1.a = 10;
- l1.b = 11;
- l1.c = 12;
- l1.d = 13;
- l1.e = 14;
-
- s2.a = 7;
- s2.b = 8;
-
- n = 41;
-
- args[0] = &n;
- args[1] = &s1;
- args[2] = &l1;
- args[3] = &s2;
- args[4] = NULL;
-
- ffi_call(&cif, FFI_FN(test_fn), &res, args);
- /* { dg-output "5 6 10 11 12 13 14 7 8" } */
- printf("res: %d\n", (int) res);
- /* { dg-output "\nres: 42" } */
-
- return 0;
-}
+/* Area: ffi_call
+ Purpose: Test passing struct in variable argument lists.
+ Limitations: none.
+ PR: none.
+ Originator: ARM Ltd. */
+
+/* { dg-do run } */
+/* { dg-output "" { xfail avr32*-*-* } } */
+
+#include "ffitest.h"
+#include <stdarg.h>
+
+struct small_tag
+{
+ unsigned char a;
+ unsigned char b;
+};
+
+struct large_tag
+{
+ unsigned a;
+ unsigned b;
+ unsigned c;
+ unsigned d;
+ unsigned e;
+};
+
+static int
+test_fn (int n, ...)
+{
+ va_list ap;
+ struct small_tag s1;
+ struct small_tag s2;
+ struct large_tag l;
+
+ va_start (ap, n);
+ s1 = va_arg (ap, struct small_tag);
+ l = va_arg (ap, struct large_tag);
+ s2 = va_arg (ap, struct small_tag);
+ printf ("%u %u %u %u %u %u %u %u %u\n", s1.a, s1.b, l.a, l.b, l.c, l.d, l.e,
+ s2.a, s2.b);
+ va_end (ap);
+ return n + 1;
+}
+
+int
+main (void)
+{
+ ffi_cif cif;
+ void* args[5];
+ ffi_type* arg_types[5];
+
+ ffi_type s_type;
+ ffi_type *s_type_elements[3];
+
+ ffi_type l_type;
+ ffi_type *l_type_elements[6];
+
+ struct small_tag s1;
+ struct small_tag s2;
+ struct large_tag l1;
+
+ int n;
+ ffi_arg res;
+
+ s_type.size = 0;
+ s_type.alignment = 0;
+ s_type.type = FFI_TYPE_STRUCT;
+ s_type.elements = s_type_elements;
+
+ s_type_elements[0] = &ffi_type_uchar;
+ s_type_elements[1] = &ffi_type_uchar;
+ s_type_elements[2] = NULL;
+
+ l_type.size = 0;
+ l_type.alignment = 0;
+ l_type.type = FFI_TYPE_STRUCT;
+ l_type.elements = l_type_elements;
+
+ l_type_elements[0] = &ffi_type_uint;
+ l_type_elements[1] = &ffi_type_uint;
+ l_type_elements[2] = &ffi_type_uint;
+ l_type_elements[3] = &ffi_type_uint;
+ l_type_elements[4] = &ffi_type_uint;
+ l_type_elements[5] = NULL;
+
+ arg_types[0] = &ffi_type_sint;
+ arg_types[1] = &s_type;
+ arg_types[2] = &l_type;
+ arg_types[3] = &s_type;
+ arg_types[4] = NULL;
+
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &ffi_type_sint, arg_types) == FFI_OK);
+
+ s1.a = 5;
+ s1.b = 6;
+
+ l1.a = 10;
+ l1.b = 11;
+ l1.c = 12;
+ l1.d = 13;
+ l1.e = 14;
+
+ s2.a = 7;
+ s2.b = 8;
+
+ n = 41;
+
+ args[0] = &n;
+ args[1] = &s1;
+ args[2] = &l1;
+ args[3] = &s2;
+ args[4] = NULL;
+
+ ffi_call(&cif, FFI_FN(test_fn), &res, args);
+ /* { dg-output "5 6 10 11 12 13 14 7 8" } */
+ printf("res: %d\n", (int) res);
+ /* { dg-output "\nres: 42" } */
+
+ return 0;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/va_struct1/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/va_struct1/ya.make
index ce054b4d35..d359d5573b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/va_struct1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/va_struct1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- va_struct1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ va_struct1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/va_struct2.c b/contrib/restricted/libffi/testsuite/libffi.call/va_struct2.c
index f5b44f6633..56f5b9c75f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/va_struct2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/va_struct2.c
@@ -1,123 +1,123 @@
-/* Area: ffi_call
- Purpose: Test passing struct in variable argument lists.
- Limitations: none.
- PR: none.
- Originator: ARM Ltd. */
-
-/* { dg-do run } */
-/* { dg-output "" { xfail avr32*-*-* } } */
-
-#include "ffitest.h"
-#include <stdarg.h>
-
-struct small_tag
-{
- unsigned char a;
- unsigned char b;
-};
-
-struct large_tag
-{
- unsigned a;
- unsigned b;
- unsigned c;
- unsigned d;
- unsigned e;
-};
-
-static struct small_tag
-test_fn (int n, ...)
-{
- va_list ap;
- struct small_tag s1;
- struct small_tag s2;
- struct large_tag l;
-
- va_start (ap, n);
- s1 = va_arg (ap, struct small_tag);
- l = va_arg (ap, struct large_tag);
- s2 = va_arg (ap, struct small_tag);
- printf ("%u %u %u %u %u %u %u %u %u\n", s1.a, s1.b, l.a, l.b, l.c, l.d, l.e,
- s2.a, s2.b);
- va_end (ap);
- s1.a += s2.a;
- s1.b += s2.b;
- return s1;
-}
-
-int
-main (void)
-{
- ffi_cif cif;
- void* args[5];
- ffi_type* arg_types[5];
-
- ffi_type s_type;
- ffi_type *s_type_elements[3];
-
- ffi_type l_type;
- ffi_type *l_type_elements[6];
-
- struct small_tag s1;
- struct small_tag s2;
- struct large_tag l1;
-
- int n;
- struct small_tag res;
-
- s_type.size = 0;
- s_type.alignment = 0;
- s_type.type = FFI_TYPE_STRUCT;
- s_type.elements = s_type_elements;
-
- s_type_elements[0] = &ffi_type_uchar;
- s_type_elements[1] = &ffi_type_uchar;
- s_type_elements[2] = NULL;
-
- l_type.size = 0;
- l_type.alignment = 0;
- l_type.type = FFI_TYPE_STRUCT;
- l_type.elements = l_type_elements;
-
- l_type_elements[0] = &ffi_type_uint;
- l_type_elements[1] = &ffi_type_uint;
- l_type_elements[2] = &ffi_type_uint;
- l_type_elements[3] = &ffi_type_uint;
- l_type_elements[4] = &ffi_type_uint;
- l_type_elements[5] = NULL;
-
- arg_types[0] = &ffi_type_sint;
- arg_types[1] = &s_type;
- arg_types[2] = &l_type;
- arg_types[3] = &s_type;
- arg_types[4] = NULL;
-
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &s_type, arg_types) == FFI_OK);
-
- s1.a = 5;
- s1.b = 6;
-
- l1.a = 10;
- l1.b = 11;
- l1.c = 12;
- l1.d = 13;
- l1.e = 14;
-
- s2.a = 7;
- s2.b = 8;
-
- n = 41;
-
- args[0] = &n;
- args[1] = &s1;
- args[2] = &l1;
- args[3] = &s2;
- args[4] = NULL;
-
- ffi_call(&cif, FFI_FN(test_fn), &res, args);
- /* { dg-output "5 6 10 11 12 13 14 7 8" } */
- printf("res: %d %d\n", res.a, res.b);
- /* { dg-output "\nres: 12 14" } */
-
- return 0;
-}
+/* Area: ffi_call
+ Purpose: Test passing struct in variable argument lists.
+ Limitations: none.
+ PR: none.
+ Originator: ARM Ltd. */
+
+/* { dg-do run } */
+/* { dg-output "" { xfail avr32*-*-* } } */
+
+#include "ffitest.h"
+#include <stdarg.h>
+
+struct small_tag
+{
+ unsigned char a;
+ unsigned char b;
+};
+
+struct large_tag
+{
+ unsigned a;
+ unsigned b;
+ unsigned c;
+ unsigned d;
+ unsigned e;
+};
+
+static struct small_tag
+test_fn (int n, ...)
+{
+ va_list ap;
+ struct small_tag s1;
+ struct small_tag s2;
+ struct large_tag l;
+
+ va_start (ap, n);
+ s1 = va_arg (ap, struct small_tag);
+ l = va_arg (ap, struct large_tag);
+ s2 = va_arg (ap, struct small_tag);
+ printf ("%u %u %u %u %u %u %u %u %u\n", s1.a, s1.b, l.a, l.b, l.c, l.d, l.e,
+ s2.a, s2.b);
+ va_end (ap);
+ s1.a += s2.a;
+ s1.b += s2.b;
+ return s1;
+}
+
+int
+main (void)
+{
+ ffi_cif cif;
+ void* args[5];
+ ffi_type* arg_types[5];
+
+ ffi_type s_type;
+ ffi_type *s_type_elements[3];
+
+ ffi_type l_type;
+ ffi_type *l_type_elements[6];
+
+ struct small_tag s1;
+ struct small_tag s2;
+ struct large_tag l1;
+
+ int n;
+ struct small_tag res;
+
+ s_type.size = 0;
+ s_type.alignment = 0;
+ s_type.type = FFI_TYPE_STRUCT;
+ s_type.elements = s_type_elements;
+
+ s_type_elements[0] = &ffi_type_uchar;
+ s_type_elements[1] = &ffi_type_uchar;
+ s_type_elements[2] = NULL;
+
+ l_type.size = 0;
+ l_type.alignment = 0;
+ l_type.type = FFI_TYPE_STRUCT;
+ l_type.elements = l_type_elements;
+
+ l_type_elements[0] = &ffi_type_uint;
+ l_type_elements[1] = &ffi_type_uint;
+ l_type_elements[2] = &ffi_type_uint;
+ l_type_elements[3] = &ffi_type_uint;
+ l_type_elements[4] = &ffi_type_uint;
+ l_type_elements[5] = NULL;
+
+ arg_types[0] = &ffi_type_sint;
+ arg_types[1] = &s_type;
+ arg_types[2] = &l_type;
+ arg_types[3] = &s_type;
+ arg_types[4] = NULL;
+
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &s_type, arg_types) == FFI_OK);
+
+ s1.a = 5;
+ s1.b = 6;
+
+ l1.a = 10;
+ l1.b = 11;
+ l1.c = 12;
+ l1.d = 13;
+ l1.e = 14;
+
+ s2.a = 7;
+ s2.b = 8;
+
+ n = 41;
+
+ args[0] = &n;
+ args[1] = &s1;
+ args[2] = &l1;
+ args[3] = &s2;
+ args[4] = NULL;
+
+ ffi_call(&cif, FFI_FN(test_fn), &res, args);
+ /* { dg-output "5 6 10 11 12 13 14 7 8" } */
+ printf("res: %d %d\n", res.a, res.b);
+ /* { dg-output "\nres: 12 14" } */
+
+ return 0;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/va_struct2/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/va_struct2/ya.make
index 3d22bac4ac..34d842c536 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/va_struct2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/va_struct2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- va_struct2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ va_struct2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/va_struct3.c b/contrib/restricted/libffi/testsuite/libffi.call/va_struct3.c
index 79da9db5b6..9a27e7fd4a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/va_struct3.c
+++ b/contrib/restricted/libffi/testsuite/libffi.call/va_struct3.c
@@ -1,125 +1,125 @@
-/* Area: ffi_call
- Purpose: Test passing struct in variable argument lists.
- Limitations: none.
- PR: none.
- Originator: ARM Ltd. */
-
-/* { dg-do run } */
-/* { dg-output "" { xfail avr32*-*-* } } */
-
-#include "ffitest.h"
-#include <stdarg.h>
-
-struct small_tag
-{
- unsigned char a;
- unsigned char b;
-};
-
-struct large_tag
-{
- unsigned a;
- unsigned b;
- unsigned c;
- unsigned d;
- unsigned e;
-};
-
-static struct large_tag
-test_fn (int n, ...)
-{
- va_list ap;
- struct small_tag s1;
- struct small_tag s2;
- struct large_tag l;
-
- va_start (ap, n);
- s1 = va_arg (ap, struct small_tag);
- l = va_arg (ap, struct large_tag);
- s2 = va_arg (ap, struct small_tag);
- printf ("%u %u %u %u %u %u %u %u %u\n", s1.a, s1.b, l.a, l.b, l.c, l.d, l.e,
- s2.a, s2.b);
- va_end (ap);
- l.a += s1.a;
- l.b += s1.b;
- l.c += s2.a;
- l.d += s2.b;
- return l;
-}
-
-int
-main (void)
-{
- ffi_cif cif;
- void* args[5];
- ffi_type* arg_types[5];
-
- ffi_type s_type;
- ffi_type *s_type_elements[3];
-
- ffi_type l_type;
- ffi_type *l_type_elements[6];
-
- struct small_tag s1;
- struct small_tag s2;
- struct large_tag l1;
-
- int n;
- struct large_tag res;
-
- s_type.size = 0;
- s_type.alignment = 0;
- s_type.type = FFI_TYPE_STRUCT;
- s_type.elements = s_type_elements;
-
- s_type_elements[0] = &ffi_type_uchar;
- s_type_elements[1] = &ffi_type_uchar;
- s_type_elements[2] = NULL;
-
- l_type.size = 0;
- l_type.alignment = 0;
- l_type.type = FFI_TYPE_STRUCT;
- l_type.elements = l_type_elements;
-
- l_type_elements[0] = &ffi_type_uint;
- l_type_elements[1] = &ffi_type_uint;
- l_type_elements[2] = &ffi_type_uint;
- l_type_elements[3] = &ffi_type_uint;
- l_type_elements[4] = &ffi_type_uint;
- l_type_elements[5] = NULL;
-
- arg_types[0] = &ffi_type_sint;
- arg_types[1] = &s_type;
- arg_types[2] = &l_type;
- arg_types[3] = &s_type;
- arg_types[4] = NULL;
-
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &l_type, arg_types) == FFI_OK);
-
- s1.a = 5;
- s1.b = 6;
-
- l1.a = 10;
- l1.b = 11;
- l1.c = 12;
- l1.d = 13;
- l1.e = 14;
-
- s2.a = 7;
- s2.b = 8;
-
- n = 41;
-
- args[0] = &n;
- args[1] = &s1;
- args[2] = &l1;
- args[3] = &s2;
- args[4] = NULL;
-
- ffi_call(&cif, FFI_FN(test_fn), &res, args);
- /* { dg-output "5 6 10 11 12 13 14 7 8" } */
- printf("res: %d %d %d %d %d\n", res.a, res.b, res.c, res.d, res.e);
- /* { dg-output "\nres: 15 17 19 21 14" } */
-
- return 0;
-}
+/* Area: ffi_call
+ Purpose: Test passing struct in variable argument lists.
+ Limitations: none.
+ PR: none.
+ Originator: ARM Ltd. */
+
+/* { dg-do run } */
+/* { dg-output "" { xfail avr32*-*-* } } */
+
+#include "ffitest.h"
+#include <stdarg.h>
+
+struct small_tag
+{
+ unsigned char a;
+ unsigned char b;
+};
+
+struct large_tag
+{
+ unsigned a;
+ unsigned b;
+ unsigned c;
+ unsigned d;
+ unsigned e;
+};
+
+static struct large_tag
+test_fn (int n, ...)
+{
+ va_list ap;
+ struct small_tag s1;
+ struct small_tag s2;
+ struct large_tag l;
+
+ va_start (ap, n);
+ s1 = va_arg (ap, struct small_tag);
+ l = va_arg (ap, struct large_tag);
+ s2 = va_arg (ap, struct small_tag);
+ printf ("%u %u %u %u %u %u %u %u %u\n", s1.a, s1.b, l.a, l.b, l.c, l.d, l.e,
+ s2.a, s2.b);
+ va_end (ap);
+ l.a += s1.a;
+ l.b += s1.b;
+ l.c += s2.a;
+ l.d += s2.b;
+ return l;
+}
+
+int
+main (void)
+{
+ ffi_cif cif;
+ void* args[5];
+ ffi_type* arg_types[5];
+
+ ffi_type s_type;
+ ffi_type *s_type_elements[3];
+
+ ffi_type l_type;
+ ffi_type *l_type_elements[6];
+
+ struct small_tag s1;
+ struct small_tag s2;
+ struct large_tag l1;
+
+ int n;
+ struct large_tag res;
+
+ s_type.size = 0;
+ s_type.alignment = 0;
+ s_type.type = FFI_TYPE_STRUCT;
+ s_type.elements = s_type_elements;
+
+ s_type_elements[0] = &ffi_type_uchar;
+ s_type_elements[1] = &ffi_type_uchar;
+ s_type_elements[2] = NULL;
+
+ l_type.size = 0;
+ l_type.alignment = 0;
+ l_type.type = FFI_TYPE_STRUCT;
+ l_type.elements = l_type_elements;
+
+ l_type_elements[0] = &ffi_type_uint;
+ l_type_elements[1] = &ffi_type_uint;
+ l_type_elements[2] = &ffi_type_uint;
+ l_type_elements[3] = &ffi_type_uint;
+ l_type_elements[4] = &ffi_type_uint;
+ l_type_elements[5] = NULL;
+
+ arg_types[0] = &ffi_type_sint;
+ arg_types[1] = &s_type;
+ arg_types[2] = &l_type;
+ arg_types[3] = &s_type;
+ arg_types[4] = NULL;
+
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &l_type, arg_types) == FFI_OK);
+
+ s1.a = 5;
+ s1.b = 6;
+
+ l1.a = 10;
+ l1.b = 11;
+ l1.c = 12;
+ l1.d = 13;
+ l1.e = 14;
+
+ s2.a = 7;
+ s2.b = 8;
+
+ n = 41;
+
+ args[0] = &n;
+ args[1] = &s1;
+ args[2] = &l1;
+ args[3] = &s2;
+ args[4] = NULL;
+
+ ffi_call(&cif, FFI_FN(test_fn), &res, args);
+ /* { dg-output "5 6 10 11 12 13 14 7 8" } */
+ printf("res: %d %d %d %d %d\n", res.a, res.b, res.c, res.d, res.e);
+ /* { dg-output "\nres: 15 17 19 21 14" } */
+
+ return 0;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/va_struct3/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/va_struct3/ya.make
index 859c7a9df8..c2f77a757f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/va_struct3/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/va_struct3/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
-
-SRCS(
- va_struct3.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.call)
+
+SRCS(
+ va_struct3.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.call/ya.make b/contrib/restricted/libffi/testsuite/libffi.call/ya.make
index 4d25fd5b0b..744afe6342 100644
--- a/contrib/restricted/libffi/testsuite/libffi.call/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.call/ya.make
@@ -1,55 +1,55 @@
-# Generated by devtools/yamaker.
-
-RECURSE(
- align_mixed
- align_stdcall
- err_bad_typedef
- float
- float1
- float2
- float3
- float4
- float_va
- many
- many2
- many_double
- many_mixed
- negint
- offsets
- pr1172638
- promotion
- pyobjc-tc
- return_dbl
- return_dbl1
- return_dbl2
- return_fl
- return_fl1
- return_fl2
- return_fl3
- return_ldl
- return_ll
- return_ll1
- return_sc
- return_sl
- return_uc
- return_ul
- strlen
- strlen2
- strlen3
- strlen4
- struct1
- struct10
- struct2
- struct3
- struct4
- struct5
- struct6
- struct7
- struct8
- struct9
- uninitialized
- va_1
- va_struct1
- va_struct2
- va_struct3
-)
+# Generated by devtools/yamaker.
+
+RECURSE(
+ align_mixed
+ align_stdcall
+ err_bad_typedef
+ float
+ float1
+ float2
+ float3
+ float4
+ float_va
+ many
+ many2
+ many_double
+ many_mixed
+ negint
+ offsets
+ pr1172638
+ promotion
+ pyobjc-tc
+ return_dbl
+ return_dbl1
+ return_dbl2
+ return_fl
+ return_fl1
+ return_fl2
+ return_fl3
+ return_ldl
+ return_ll
+ return_ll1
+ return_sc
+ return_sl
+ return_uc
+ return_ul
+ strlen
+ strlen2
+ strlen3
+ strlen4
+ struct1
+ struct10
+ struct2
+ struct3
+ struct4
+ struct5
+ struct6
+ struct7
+ struct8
+ struct9
+ uninitialized
+ va_1
+ va_struct1
+ va_struct2
+ va_struct3
+)
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn0.c b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn0.c
index fd7c2475f7..a579ff6c97 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn0.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn0.c
@@ -1,89 +1,89 @@
-/* Area: closure_call
- Purpose: Check multiple values passing from different type.
- Also, exceed the limit of gpr and fpr registers on PowerPC
- Darwin.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-
-
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void
-closure_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata)
-{
- *(ffi_arg*)resp =
- (int)*(unsigned long long *)args[0] + (int)(*(int *)args[1]) +
- (int)(*(unsigned long long *)args[2]) + (int)*(int *)args[3] +
- (int)(*(signed short *)args[4]) +
- (int)(*(unsigned long long *)args[5]) +
- (int)*(int *)args[6] + (int)(*(int *)args[7]) +
- (int)(*(double *)args[8]) + (int)*(int *)args[9] +
- (int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
- (int)*(int *)args[12] + (int)(*(int *)args[13]) +
- (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata;
-
- printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
- (int)*(unsigned long long *)args[0], (int)(*(int *)args[1]),
- (int)(*(unsigned long long *)args[2]),
- (int)*(int *)args[3], (int)(*(signed short *)args[4]),
- (int)(*(unsigned long long *)args[5]),
- (int)*(int *)args[6], (int)(*(int *)args[7]),
- (int)(*(double *)args[8]), (int)*(int *)args[9],
- (int)(*(int *)args[10]), (int)(*(float *)args[11]),
- (int)*(int *)args[12], (int)(*(int *)args[13]),
- (int)(*(int *)args[14]),*(int *)args[15],
- (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
-
-}
-
-typedef int (*closure_test_type0)(unsigned long long, int, unsigned long long,
- int, signed short, unsigned long long, int,
- int, double, int, int, float, int, int,
- int, int);
-
-int main (void)
-{
- ffi_cif cif;
- void * code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[17];
- int res;
-
- cl_arg_types[0] = &ffi_type_uint64;
- cl_arg_types[1] = &ffi_type_sint;
- cl_arg_types[2] = &ffi_type_uint64;
- cl_arg_types[3] = &ffi_type_sint;
- cl_arg_types[4] = &ffi_type_sshort;
- cl_arg_types[5] = &ffi_type_uint64;
- cl_arg_types[6] = &ffi_type_sint;
- cl_arg_types[7] = &ffi_type_sint;
- cl_arg_types[8] = &ffi_type_double;
- cl_arg_types[9] = &ffi_type_sint;
- cl_arg_types[10] = &ffi_type_sint;
- cl_arg_types[11] = &ffi_type_float;
- cl_arg_types[12] = &ffi_type_sint;
- cl_arg_types[13] = &ffi_type_sint;
- cl_arg_types[14] = &ffi_type_sint;
- cl_arg_types[15] = &ffi_type_sint;
- cl_arg_types[16] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
- &ffi_type_sint, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn0,
- (void *) 3 /* userdata */, code) == FFI_OK);
-
- res = (*((closure_test_type0)code))
- (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13,
- 19, 21, 1);
- /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 680" } */
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check multiple values passing from different type.
+ Also, exceed the limit of gpr and fpr registers on PowerPC
+ Darwin.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+
+
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void
+closure_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata)
+{
+ *(ffi_arg*)resp =
+ (int)*(unsigned long long *)args[0] + (int)(*(int *)args[1]) +
+ (int)(*(unsigned long long *)args[2]) + (int)*(int *)args[3] +
+ (int)(*(signed short *)args[4]) +
+ (int)(*(unsigned long long *)args[5]) +
+ (int)*(int *)args[6] + (int)(*(int *)args[7]) +
+ (int)(*(double *)args[8]) + (int)*(int *)args[9] +
+ (int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
+ (int)*(int *)args[12] + (int)(*(int *)args[13]) +
+ (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata;
+
+ printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
+ (int)*(unsigned long long *)args[0], (int)(*(int *)args[1]),
+ (int)(*(unsigned long long *)args[2]),
+ (int)*(int *)args[3], (int)(*(signed short *)args[4]),
+ (int)(*(unsigned long long *)args[5]),
+ (int)*(int *)args[6], (int)(*(int *)args[7]),
+ (int)(*(double *)args[8]), (int)*(int *)args[9],
+ (int)(*(int *)args[10]), (int)(*(float *)args[11]),
+ (int)*(int *)args[12], (int)(*(int *)args[13]),
+ (int)(*(int *)args[14]),*(int *)args[15],
+ (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
+
+}
+
+typedef int (*closure_test_type0)(unsigned long long, int, unsigned long long,
+ int, signed short, unsigned long long, int,
+ int, double, int, int, float, int, int,
+ int, int);
+
+int main (void)
+{
+ ffi_cif cif;
+ void * code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[17];
+ int res;
+
+ cl_arg_types[0] = &ffi_type_uint64;
+ cl_arg_types[1] = &ffi_type_sint;
+ cl_arg_types[2] = &ffi_type_uint64;
+ cl_arg_types[3] = &ffi_type_sint;
+ cl_arg_types[4] = &ffi_type_sshort;
+ cl_arg_types[5] = &ffi_type_uint64;
+ cl_arg_types[6] = &ffi_type_sint;
+ cl_arg_types[7] = &ffi_type_sint;
+ cl_arg_types[8] = &ffi_type_double;
+ cl_arg_types[9] = &ffi_type_sint;
+ cl_arg_types[10] = &ffi_type_sint;
+ cl_arg_types[11] = &ffi_type_float;
+ cl_arg_types[12] = &ffi_type_sint;
+ cl_arg_types[13] = &ffi_type_sint;
+ cl_arg_types[14] = &ffi_type_sint;
+ cl_arg_types[15] = &ffi_type_sint;
+ cl_arg_types[16] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
+ &ffi_type_sint, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn0,
+ (void *) 3 /* userdata */, code) == FFI_OK);
+
+ res = (*((closure_test_type0)code))
+ (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13,
+ 19, 21, 1);
+ /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 680" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn0/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn0/ya.make
index 5e149f11ec..30dc7128a6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn0/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn0/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- closure_fn0.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ closure_fn0.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn1.c b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn1.c
index 3ff4c82205..91231738c1 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn1.c
@@ -1,81 +1,81 @@
-/* Area: closure_call.
- Purpose: Check multiple values passing from different type.
- Also, exceed the limit of gpr and fpr registers on PowerPC
- Darwin.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-
-static void closure_test_fn1(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata)
-{
- *(ffi_arg*)resp =
- (int)*(float *)args[0] +(int)(*(float *)args[1]) +
- (int)(*(float *)args[2]) + (int)*(float *)args[3] +
- (int)(*(signed short *)args[4]) + (int)(*(float *)args[5]) +
- (int)*(float *)args[6] + (int)(*(int *)args[7]) +
- (int)(*(double*)args[8]) + (int)*(int *)args[9] +
- (int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
- (int)*(int *)args[12] + (int)(*(int *)args[13]) +
- (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata;
-
- printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
- (int)*(float *)args[0], (int)(*(float *)args[1]),
- (int)(*(float *)args[2]), (int)*(float *)args[3],
- (int)(*(signed short *)args[4]), (int)(*(float *)args[5]),
- (int)*(float *)args[6], (int)(*(int *)args[7]),
- (int)(*(double *)args[8]), (int)*(int *)args[9],
- (int)(*(int *)args[10]), (int)(*(float *)args[11]),
- (int)*(int *)args[12], (int)(*(int *)args[13]),
- (int)(*(int *)args[14]), *(int *)args[15],
- (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
-}
-
-typedef int (*closure_test_type1)(float, float, float, float, signed short,
- float, float, int, double, int, int, float,
- int, int, int, int);
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[17];
- int res;
-
- cl_arg_types[0] = &ffi_type_float;
- cl_arg_types[1] = &ffi_type_float;
- cl_arg_types[2] = &ffi_type_float;
- cl_arg_types[3] = &ffi_type_float;
- cl_arg_types[4] = &ffi_type_sshort;
- cl_arg_types[5] = &ffi_type_float;
- cl_arg_types[6] = &ffi_type_float;
- cl_arg_types[7] = &ffi_type_sint;
- cl_arg_types[8] = &ffi_type_double;
- cl_arg_types[9] = &ffi_type_sint;
- cl_arg_types[10] = &ffi_type_sint;
- cl_arg_types[11] = &ffi_type_float;
- cl_arg_types[12] = &ffi_type_sint;
- cl_arg_types[13] = &ffi_type_sint;
- cl_arg_types[14] = &ffi_type_sint;
- cl_arg_types[15] = &ffi_type_sint;
- cl_arg_types[16] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
- &ffi_type_sint, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn1,
- (void *) 3 /* userdata */, code) == FFI_OK);
-
- res = (*((closure_test_type1)code))
- (1.1, 2.2, 3.3, 4.4, 127, 5.5, 6.6, 8, 9, 10, 11, 12.0, 13,
- 19, 21, 1);
- /* { dg-output "1 2 3 4 127 5 6 8 9 10 11 12 13 19 21 1 3: 255" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 255" } */
- exit(0);
-}
+/* Area: closure_call.
+ Purpose: Check multiple values passing from different type.
+ Also, exceed the limit of gpr and fpr registers on PowerPC
+ Darwin.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+
+static void closure_test_fn1(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata)
+{
+ *(ffi_arg*)resp =
+ (int)*(float *)args[0] +(int)(*(float *)args[1]) +
+ (int)(*(float *)args[2]) + (int)*(float *)args[3] +
+ (int)(*(signed short *)args[4]) + (int)(*(float *)args[5]) +
+ (int)*(float *)args[6] + (int)(*(int *)args[7]) +
+ (int)(*(double*)args[8]) + (int)*(int *)args[9] +
+ (int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
+ (int)*(int *)args[12] + (int)(*(int *)args[13]) +
+ (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata;
+
+ printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
+ (int)*(float *)args[0], (int)(*(float *)args[1]),
+ (int)(*(float *)args[2]), (int)*(float *)args[3],
+ (int)(*(signed short *)args[4]), (int)(*(float *)args[5]),
+ (int)*(float *)args[6], (int)(*(int *)args[7]),
+ (int)(*(double *)args[8]), (int)*(int *)args[9],
+ (int)(*(int *)args[10]), (int)(*(float *)args[11]),
+ (int)*(int *)args[12], (int)(*(int *)args[13]),
+ (int)(*(int *)args[14]), *(int *)args[15],
+ (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
+}
+
+typedef int (*closure_test_type1)(float, float, float, float, signed short,
+ float, float, int, double, int, int, float,
+ int, int, int, int);
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[17];
+ int res;
+
+ cl_arg_types[0] = &ffi_type_float;
+ cl_arg_types[1] = &ffi_type_float;
+ cl_arg_types[2] = &ffi_type_float;
+ cl_arg_types[3] = &ffi_type_float;
+ cl_arg_types[4] = &ffi_type_sshort;
+ cl_arg_types[5] = &ffi_type_float;
+ cl_arg_types[6] = &ffi_type_float;
+ cl_arg_types[7] = &ffi_type_sint;
+ cl_arg_types[8] = &ffi_type_double;
+ cl_arg_types[9] = &ffi_type_sint;
+ cl_arg_types[10] = &ffi_type_sint;
+ cl_arg_types[11] = &ffi_type_float;
+ cl_arg_types[12] = &ffi_type_sint;
+ cl_arg_types[13] = &ffi_type_sint;
+ cl_arg_types[14] = &ffi_type_sint;
+ cl_arg_types[15] = &ffi_type_sint;
+ cl_arg_types[16] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
+ &ffi_type_sint, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn1,
+ (void *) 3 /* userdata */, code) == FFI_OK);
+
+ res = (*((closure_test_type1)code))
+ (1.1, 2.2, 3.3, 4.4, 127, 5.5, 6.6, 8, 9, 10, 11, 12.0, 13,
+ 19, 21, 1);
+ /* { dg-output "1 2 3 4 127 5 6 8 9 10 11 12 13 19 21 1 3: 255" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 255" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn1/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn1/ya.make
index 3bcc2775a5..05987baa5c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- closure_fn1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ closure_fn1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn2.c b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn2.c
index cfb41a0b89..08ff9d9227 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn2.c
@@ -1,81 +1,81 @@
-/* Area: closure_call
- Purpose: Check multiple values passing from different type.
- Also, exceed the limit of gpr and fpr registers on PowerPC
- Darwin.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void closure_test_fn2(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata)
-{
- *(ffi_arg*)resp =
- (int)*(double *)args[0] +(int)(*(double *)args[1]) +
- (int)(*(double *)args[2]) + (int)*(double *)args[3] +
- (int)(*(signed short *)args[4]) + (int)(*(double *)args[5]) +
- (int)*(double *)args[6] + (int)(*(int *)args[7]) +
- (int)(*(double *)args[8]) + (int)*(int *)args[9] +
- (int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
- (int)*(int *)args[12] + (int)(*(float *)args[13]) +
- (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata;
-
- printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
- (int)*(double *)args[0], (int)(*(double *)args[1]),
- (int)(*(double *)args[2]), (int)*(double *)args[3],
- (int)(*(signed short *)args[4]), (int)(*(double *)args[5]),
- (int)*(double *)args[6], (int)(*(int *)args[7]),
- (int)(*(double*)args[8]), (int)*(int *)args[9],
- (int)(*(int *)args[10]), (int)(*(float *)args[11]),
- (int)*(int *)args[12], (int)(*(float *)args[13]),
- (int)(*(int *)args[14]), *(int *)args[15], (int)(intptr_t)userdata,
- (int)*(ffi_arg *)resp);
-}
-
-typedef int (*closure_test_type2)(double, double, double, double, signed short,
- double, double, int, double, int, int, float,
- int, float, int, int);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[17];
- int res;
-
- cl_arg_types[0] = &ffi_type_double;
- cl_arg_types[1] = &ffi_type_double;
- cl_arg_types[2] = &ffi_type_double;
- cl_arg_types[3] = &ffi_type_double;
- cl_arg_types[4] = &ffi_type_sshort;
- cl_arg_types[5] = &ffi_type_double;
- cl_arg_types[6] = &ffi_type_double;
- cl_arg_types[7] = &ffi_type_sint;
- cl_arg_types[8] = &ffi_type_double;
- cl_arg_types[9] = &ffi_type_sint;
- cl_arg_types[10] = &ffi_type_sint;
- cl_arg_types[11] = &ffi_type_float;
- cl_arg_types[12] = &ffi_type_sint;
- cl_arg_types[13] = &ffi_type_float;
- cl_arg_types[14] = &ffi_type_sint;
- cl_arg_types[15] = &ffi_type_sint;
- cl_arg_types[16] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
- &ffi_type_sint, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn2,
- (void *) 3 /* userdata */, code) == FFI_OK);
-
- res = (*((closure_test_type2)code))
- (1, 2, 3, 4, 127, 5, 6, 8, 9, 10, 11, 12.0, 13,
- 19.0, 21, 1);
- /* { dg-output "1 2 3 4 127 5 6 8 9 10 11 12 13 19 21 1 3: 255" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 255" } */
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check multiple values passing from different type.
+ Also, exceed the limit of gpr and fpr registers on PowerPC
+ Darwin.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void closure_test_fn2(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata)
+{
+ *(ffi_arg*)resp =
+ (int)*(double *)args[0] +(int)(*(double *)args[1]) +
+ (int)(*(double *)args[2]) + (int)*(double *)args[3] +
+ (int)(*(signed short *)args[4]) + (int)(*(double *)args[5]) +
+ (int)*(double *)args[6] + (int)(*(int *)args[7]) +
+ (int)(*(double *)args[8]) + (int)*(int *)args[9] +
+ (int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
+ (int)*(int *)args[12] + (int)(*(float *)args[13]) +
+ (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata;
+
+ printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
+ (int)*(double *)args[0], (int)(*(double *)args[1]),
+ (int)(*(double *)args[2]), (int)*(double *)args[3],
+ (int)(*(signed short *)args[4]), (int)(*(double *)args[5]),
+ (int)*(double *)args[6], (int)(*(int *)args[7]),
+ (int)(*(double*)args[8]), (int)*(int *)args[9],
+ (int)(*(int *)args[10]), (int)(*(float *)args[11]),
+ (int)*(int *)args[12], (int)(*(float *)args[13]),
+ (int)(*(int *)args[14]), *(int *)args[15], (int)(intptr_t)userdata,
+ (int)*(ffi_arg *)resp);
+}
+
+typedef int (*closure_test_type2)(double, double, double, double, signed short,
+ double, double, int, double, int, int, float,
+ int, float, int, int);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[17];
+ int res;
+
+ cl_arg_types[0] = &ffi_type_double;
+ cl_arg_types[1] = &ffi_type_double;
+ cl_arg_types[2] = &ffi_type_double;
+ cl_arg_types[3] = &ffi_type_double;
+ cl_arg_types[4] = &ffi_type_sshort;
+ cl_arg_types[5] = &ffi_type_double;
+ cl_arg_types[6] = &ffi_type_double;
+ cl_arg_types[7] = &ffi_type_sint;
+ cl_arg_types[8] = &ffi_type_double;
+ cl_arg_types[9] = &ffi_type_sint;
+ cl_arg_types[10] = &ffi_type_sint;
+ cl_arg_types[11] = &ffi_type_float;
+ cl_arg_types[12] = &ffi_type_sint;
+ cl_arg_types[13] = &ffi_type_float;
+ cl_arg_types[14] = &ffi_type_sint;
+ cl_arg_types[15] = &ffi_type_sint;
+ cl_arg_types[16] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
+ &ffi_type_sint, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn2,
+ (void *) 3 /* userdata */, code) == FFI_OK);
+
+ res = (*((closure_test_type2)code))
+ (1, 2, 3, 4, 127, 5, 6, 8, 9, 10, 11, 12.0, 13,
+ 19.0, 21, 1);
+ /* { dg-output "1 2 3 4 127 5 6 8 9 10 11 12 13 19 21 1 3: 255" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 255" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn2/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn2/ya.make
index 4ffbfe93e8..9fb20abc91 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- closure_fn2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ closure_fn2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn3.c b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn3.c
index 814693e770..9b54d805c8 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn3.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn3.c
@@ -1,82 +1,82 @@
-/* Area: closure_call
- Purpose: Check multiple values passing from different type.
- Also, exceed the limit of gpr and fpr registers on PowerPC
- Darwin.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void closure_test_fn3(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata)
- {
- *(ffi_arg*)resp =
- (int)*(float *)args[0] +(int)(*(float *)args[1]) +
- (int)(*(float *)args[2]) + (int)*(float *)args[3] +
- (int)(*(float *)args[4]) + (int)(*(float *)args[5]) +
- (int)*(float *)args[6] + (int)(*(float *)args[7]) +
- (int)(*(double *)args[8]) + (int)*(int *)args[9] +
- (int)(*(float *)args[10]) + (int)(*(float *)args[11]) +
- (int)*(int *)args[12] + (int)(*(float *)args[13]) +
- (int)(*(float *)args[14]) + *(int *)args[15] + (intptr_t)userdata;
-
- printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
- (int)*(float *)args[0], (int)(*(float *)args[1]),
- (int)(*(float *)args[2]), (int)*(float *)args[3],
- (int)(*(float *)args[4]), (int)(*(float *)args[5]),
- (int)*(float *)args[6], (int)(*(float *)args[7]),
- (int)(*(double *)args[8]), (int)*(int *)args[9],
- (int)(*(float *)args[10]), (int)(*(float *)args[11]),
- (int)*(int *)args[12], (int)(*(float *)args[13]),
- (int)(*(float *)args[14]), *(int *)args[15], (int)(intptr_t)userdata,
- (int)*(ffi_arg *)resp);
-
- }
-
-typedef int (*closure_test_type3)(float, float, float, float, float, float,
- float, float, double, int, float, float, int,
- float, float, int);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[17];
- int res;
-
- cl_arg_types[0] = &ffi_type_float;
- cl_arg_types[1] = &ffi_type_float;
- cl_arg_types[2] = &ffi_type_float;
- cl_arg_types[3] = &ffi_type_float;
- cl_arg_types[4] = &ffi_type_float;
- cl_arg_types[5] = &ffi_type_float;
- cl_arg_types[6] = &ffi_type_float;
- cl_arg_types[7] = &ffi_type_float;
- cl_arg_types[8] = &ffi_type_double;
- cl_arg_types[9] = &ffi_type_sint;
- cl_arg_types[10] = &ffi_type_float;
- cl_arg_types[11] = &ffi_type_float;
- cl_arg_types[12] = &ffi_type_sint;
- cl_arg_types[13] = &ffi_type_float;
- cl_arg_types[14] = &ffi_type_float;
- cl_arg_types[15] = &ffi_type_sint;
- cl_arg_types[16] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
- &ffi_type_sint, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn3,
- (void *) 3 /* userdata */, code) == FFI_OK);
-
- res = (*((closure_test_type3)code))
- (1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9, 10, 11.11, 12.0, 13,
- 19.19, 21.21, 1);
- /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 12 13 19 21 1 3: 135" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 135" } */
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check multiple values passing from different type.
+ Also, exceed the limit of gpr and fpr registers on PowerPC
+ Darwin.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void closure_test_fn3(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata)
+ {
+ *(ffi_arg*)resp =
+ (int)*(float *)args[0] +(int)(*(float *)args[1]) +
+ (int)(*(float *)args[2]) + (int)*(float *)args[3] +
+ (int)(*(float *)args[4]) + (int)(*(float *)args[5]) +
+ (int)*(float *)args[6] + (int)(*(float *)args[7]) +
+ (int)(*(double *)args[8]) + (int)*(int *)args[9] +
+ (int)(*(float *)args[10]) + (int)(*(float *)args[11]) +
+ (int)*(int *)args[12] + (int)(*(float *)args[13]) +
+ (int)(*(float *)args[14]) + *(int *)args[15] + (intptr_t)userdata;
+
+ printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
+ (int)*(float *)args[0], (int)(*(float *)args[1]),
+ (int)(*(float *)args[2]), (int)*(float *)args[3],
+ (int)(*(float *)args[4]), (int)(*(float *)args[5]),
+ (int)*(float *)args[6], (int)(*(float *)args[7]),
+ (int)(*(double *)args[8]), (int)*(int *)args[9],
+ (int)(*(float *)args[10]), (int)(*(float *)args[11]),
+ (int)*(int *)args[12], (int)(*(float *)args[13]),
+ (int)(*(float *)args[14]), *(int *)args[15], (int)(intptr_t)userdata,
+ (int)*(ffi_arg *)resp);
+
+ }
+
+typedef int (*closure_test_type3)(float, float, float, float, float, float,
+ float, float, double, int, float, float, int,
+ float, float, int);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[17];
+ int res;
+
+ cl_arg_types[0] = &ffi_type_float;
+ cl_arg_types[1] = &ffi_type_float;
+ cl_arg_types[2] = &ffi_type_float;
+ cl_arg_types[3] = &ffi_type_float;
+ cl_arg_types[4] = &ffi_type_float;
+ cl_arg_types[5] = &ffi_type_float;
+ cl_arg_types[6] = &ffi_type_float;
+ cl_arg_types[7] = &ffi_type_float;
+ cl_arg_types[8] = &ffi_type_double;
+ cl_arg_types[9] = &ffi_type_sint;
+ cl_arg_types[10] = &ffi_type_float;
+ cl_arg_types[11] = &ffi_type_float;
+ cl_arg_types[12] = &ffi_type_sint;
+ cl_arg_types[13] = &ffi_type_float;
+ cl_arg_types[14] = &ffi_type_float;
+ cl_arg_types[15] = &ffi_type_sint;
+ cl_arg_types[16] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
+ &ffi_type_sint, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn3,
+ (void *) 3 /* userdata */, code) == FFI_OK);
+
+ res = (*((closure_test_type3)code))
+ (1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9, 10, 11.11, 12.0, 13,
+ 19.19, 21.21, 1);
+ /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 12 13 19 21 1 3: 135" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 135" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn3/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn3/ya.make
index ffbd8a785d..7eeed24770 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn3/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn3/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- closure_fn3.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ closure_fn3.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn4.c b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn4.c
index 0379a945f0..d4a1530b06 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn4.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn4.c
@@ -1,89 +1,89 @@
-/* Area: closure_call
- Purpose: Check multiple long long values passing.
- Also, exceed the limit of gpr and fpr registers on PowerPC
- Darwin.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20031026 */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-static void
-closure_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata)
-{
- *(ffi_arg*)resp =
- (int)*(unsigned long long *)args[0] + (int)*(unsigned long long *)args[1] +
- (int)*(unsigned long long *)args[2] + (int)*(unsigned long long *)args[3] +
- (int)*(unsigned long long *)args[4] + (int)*(unsigned long long *)args[5] +
- (int)*(unsigned long long *)args[6] + (int)*(unsigned long long *)args[7] +
- (int)*(unsigned long long *)args[8] + (int)*(unsigned long long *)args[9] +
- (int)*(unsigned long long *)args[10] +
- (int)*(unsigned long long *)args[11] +
- (int)*(unsigned long long *)args[12] +
- (int)*(unsigned long long *)args[13] +
- (int)*(unsigned long long *)args[14] +
- *(int *)args[15] + (intptr_t)userdata;
-
- printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
- (int)*(unsigned long long *)args[0],
- (int)*(unsigned long long *)args[1],
- (int)*(unsigned long long *)args[2],
- (int)*(unsigned long long *)args[3],
- (int)*(unsigned long long *)args[4],
- (int)*(unsigned long long *)args[5],
- (int)*(unsigned long long *)args[6],
- (int)*(unsigned long long *)args[7],
- (int)*(unsigned long long *)args[8],
- (int)*(unsigned long long *)args[9],
- (int)*(unsigned long long *)args[10],
- (int)*(unsigned long long *)args[11],
- (int)*(unsigned long long *)args[12],
- (int)*(unsigned long long *)args[13],
- (int)*(unsigned long long *)args[14],
- *(int *)args[15],
- (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
-
-}
-
-typedef int (*closure_test_type0)(unsigned long long, unsigned long long,
- unsigned long long, unsigned long long,
- unsigned long long, unsigned long long,
- unsigned long long, unsigned long long,
- unsigned long long, unsigned long long,
- unsigned long long, unsigned long long,
- unsigned long long, unsigned long long,
- unsigned long long, int);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[17];
- int i, res;
-
- for (i = 0; i < 15; i++) {
- cl_arg_types[i] = &ffi_type_uint64;
- }
- cl_arg_types[15] = &ffi_type_sint;
- cl_arg_types[16] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
- &ffi_type_sint, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn0,
- (void *) 3 /* userdata */, code) == FFI_OK);
-
- res = (*((closure_test_type0)code))
- (1LL, 2LL, 3LL, 4LL, 127LL, 429LL, 7LL, 8LL, 9LL, 10LL, 11LL, 12LL,
- 13LL, 19LL, 21LL, 1);
- /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 680" } */
-
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check multiple long long values passing.
+ Also, exceed the limit of gpr and fpr registers on PowerPC
+ Darwin.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20031026 */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+static void
+closure_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata)
+{
+ *(ffi_arg*)resp =
+ (int)*(unsigned long long *)args[0] + (int)*(unsigned long long *)args[1] +
+ (int)*(unsigned long long *)args[2] + (int)*(unsigned long long *)args[3] +
+ (int)*(unsigned long long *)args[4] + (int)*(unsigned long long *)args[5] +
+ (int)*(unsigned long long *)args[6] + (int)*(unsigned long long *)args[7] +
+ (int)*(unsigned long long *)args[8] + (int)*(unsigned long long *)args[9] +
+ (int)*(unsigned long long *)args[10] +
+ (int)*(unsigned long long *)args[11] +
+ (int)*(unsigned long long *)args[12] +
+ (int)*(unsigned long long *)args[13] +
+ (int)*(unsigned long long *)args[14] +
+ *(int *)args[15] + (intptr_t)userdata;
+
+ printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
+ (int)*(unsigned long long *)args[0],
+ (int)*(unsigned long long *)args[1],
+ (int)*(unsigned long long *)args[2],
+ (int)*(unsigned long long *)args[3],
+ (int)*(unsigned long long *)args[4],
+ (int)*(unsigned long long *)args[5],
+ (int)*(unsigned long long *)args[6],
+ (int)*(unsigned long long *)args[7],
+ (int)*(unsigned long long *)args[8],
+ (int)*(unsigned long long *)args[9],
+ (int)*(unsigned long long *)args[10],
+ (int)*(unsigned long long *)args[11],
+ (int)*(unsigned long long *)args[12],
+ (int)*(unsigned long long *)args[13],
+ (int)*(unsigned long long *)args[14],
+ *(int *)args[15],
+ (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
+
+}
+
+typedef int (*closure_test_type0)(unsigned long long, unsigned long long,
+ unsigned long long, unsigned long long,
+ unsigned long long, unsigned long long,
+ unsigned long long, unsigned long long,
+ unsigned long long, unsigned long long,
+ unsigned long long, unsigned long long,
+ unsigned long long, unsigned long long,
+ unsigned long long, int);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[17];
+ int i, res;
+
+ for (i = 0; i < 15; i++) {
+ cl_arg_types[i] = &ffi_type_uint64;
+ }
+ cl_arg_types[15] = &ffi_type_sint;
+ cl_arg_types[16] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
+ &ffi_type_sint, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn0,
+ (void *) 3 /* userdata */, code) == FFI_OK);
+
+ res = (*((closure_test_type0)code))
+ (1LL, 2LL, 3LL, 4LL, 127LL, 429LL, 7LL, 8LL, 9LL, 10LL, 11LL, 12LL,
+ 13LL, 19LL, 21LL, 1);
+ /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 680" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn4/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn4/ya.make
index d551224fb8..3f4fa8079e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn4/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn4/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- closure_fn4.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ closure_fn4.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn5.c b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn5.c
index ff04cd87af..99074426c6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn5.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn5.c
@@ -1,92 +1,92 @@
-/* Area: closure_call
- Purpose: Check multiple long long values passing.
- Exceed the limit of gpr registers on PowerPC
- Darwin.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20031026 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void
-closure_test_fn5(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata)
-{
- *(ffi_arg*)resp =
- (int)*(unsigned long long *)args[0] + (int)*(unsigned long long *)args[1] +
- (int)*(unsigned long long *)args[2] + (int)*(unsigned long long *)args[3] +
- (int)*(unsigned long long *)args[4] + (int)*(unsigned long long *)args[5] +
- (int)*(unsigned long long *)args[6] + (int)*(unsigned long long *)args[7] +
- (int)*(unsigned long long *)args[8] + (int)*(unsigned long long *)args[9] +
- (int)*(int *)args[10] +
- (int)*(unsigned long long *)args[11] +
- (int)*(unsigned long long *)args[12] +
- (int)*(unsigned long long *)args[13] +
- (int)*(unsigned long long *)args[14] +
- *(int *)args[15] + (intptr_t)userdata;
-
- printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
- (int)*(unsigned long long *)args[0],
- (int)*(unsigned long long *)args[1],
- (int)*(unsigned long long *)args[2],
- (int)*(unsigned long long *)args[3],
- (int)*(unsigned long long *)args[4],
- (int)*(unsigned long long *)args[5],
- (int)*(unsigned long long *)args[6],
- (int)*(unsigned long long *)args[7],
- (int)*(unsigned long long *)args[8],
- (int)*(unsigned long long *)args[9],
- (int)*(int *)args[10],
- (int)*(unsigned long long *)args[11],
- (int)*(unsigned long long *)args[12],
- (int)*(unsigned long long *)args[13],
- (int)*(unsigned long long *)args[14],
- *(int *)args[15],
- (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
-
-}
-
-typedef int (*closure_test_type0)(unsigned long long, unsigned long long,
- unsigned long long, unsigned long long,
- unsigned long long, unsigned long long,
- unsigned long long, unsigned long long,
- unsigned long long, unsigned long long,
- int, unsigned long long,
- unsigned long long, unsigned long long,
- unsigned long long, int);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[17];
- int i, res;
-
- for (i = 0; i < 10; i++) {
- cl_arg_types[i] = &ffi_type_uint64;
- }
- cl_arg_types[10] = &ffi_type_sint;
- for (i = 11; i < 15; i++) {
- cl_arg_types[i] = &ffi_type_uint64;
- }
- cl_arg_types[15] = &ffi_type_sint;
- cl_arg_types[16] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
- &ffi_type_sint, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn5,
- (void *) 3 /* userdata */, code) == FFI_OK);
-
- res = (*((closure_test_type0)code))
- (1LL, 2LL, 3LL, 4LL, 127LL, 429LL, 7LL, 8LL, 9LL, 10LL, 11, 12LL,
- 13LL, 19LL, 21LL, 1);
- /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 680" } */
-
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check multiple long long values passing.
+ Exceed the limit of gpr registers on PowerPC
+ Darwin.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20031026 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void
+closure_test_fn5(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata)
+{
+ *(ffi_arg*)resp =
+ (int)*(unsigned long long *)args[0] + (int)*(unsigned long long *)args[1] +
+ (int)*(unsigned long long *)args[2] + (int)*(unsigned long long *)args[3] +
+ (int)*(unsigned long long *)args[4] + (int)*(unsigned long long *)args[5] +
+ (int)*(unsigned long long *)args[6] + (int)*(unsigned long long *)args[7] +
+ (int)*(unsigned long long *)args[8] + (int)*(unsigned long long *)args[9] +
+ (int)*(int *)args[10] +
+ (int)*(unsigned long long *)args[11] +
+ (int)*(unsigned long long *)args[12] +
+ (int)*(unsigned long long *)args[13] +
+ (int)*(unsigned long long *)args[14] +
+ *(int *)args[15] + (intptr_t)userdata;
+
+ printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
+ (int)*(unsigned long long *)args[0],
+ (int)*(unsigned long long *)args[1],
+ (int)*(unsigned long long *)args[2],
+ (int)*(unsigned long long *)args[3],
+ (int)*(unsigned long long *)args[4],
+ (int)*(unsigned long long *)args[5],
+ (int)*(unsigned long long *)args[6],
+ (int)*(unsigned long long *)args[7],
+ (int)*(unsigned long long *)args[8],
+ (int)*(unsigned long long *)args[9],
+ (int)*(int *)args[10],
+ (int)*(unsigned long long *)args[11],
+ (int)*(unsigned long long *)args[12],
+ (int)*(unsigned long long *)args[13],
+ (int)*(unsigned long long *)args[14],
+ *(int *)args[15],
+ (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
+
+}
+
+typedef int (*closure_test_type0)(unsigned long long, unsigned long long,
+ unsigned long long, unsigned long long,
+ unsigned long long, unsigned long long,
+ unsigned long long, unsigned long long,
+ unsigned long long, unsigned long long,
+ int, unsigned long long,
+ unsigned long long, unsigned long long,
+ unsigned long long, int);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[17];
+ int i, res;
+
+ for (i = 0; i < 10; i++) {
+ cl_arg_types[i] = &ffi_type_uint64;
+ }
+ cl_arg_types[10] = &ffi_type_sint;
+ for (i = 11; i < 15; i++) {
+ cl_arg_types[i] = &ffi_type_uint64;
+ }
+ cl_arg_types[15] = &ffi_type_sint;
+ cl_arg_types[16] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
+ &ffi_type_sint, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn5,
+ (void *) 3 /* userdata */, code) == FFI_OK);
+
+ res = (*((closure_test_type0)code))
+ (1LL, 2LL, 3LL, 4LL, 127LL, 429LL, 7LL, 8LL, 9LL, 10LL, 11, 12LL,
+ 13LL, 19LL, 21LL, 1);
+ /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 680" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn5/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn5/ya.make
index 5cdabc9c64..331657b705 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn5/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn5/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- closure_fn5.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ closure_fn5.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn6.c b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn6.c
index 39bbbf215e..73c54fd6b1 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn6.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn6.c
@@ -1,90 +1,90 @@
-/* Area: closure_call
- Purpose: Check multiple values passing from different type.
- Also, exceed the limit of gpr and fpr registers on PowerPC.
- Limitations: none.
- PR: PR23404
- Originator: <andreast@gcc.gnu.org> 20050830 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void
-closure_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata)
-{
- *(ffi_arg*)resp =
- (int)*(unsigned long long *)args[0] +
- (int)(*(unsigned long long *)args[1]) +
- (int)(*(unsigned long long *)args[2]) +
- (int)*(unsigned long long *)args[3] +
- (int)(*(int *)args[4]) + (int)(*(double *)args[5]) +
- (int)*(double *)args[6] + (int)(*(float *)args[7]) +
- (int)(*(double *)args[8]) + (int)*(double *)args[9] +
- (int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
- (int)*(int *)args[12] + (int)(*(int *)args[13]) +
- (int)(*(double *)args[14]) + (int)*(double *)args[15] +
- (intptr_t)userdata;
-
- printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
- (int)*(unsigned long long *)args[0],
- (int)(*(unsigned long long *)args[1]),
- (int)(*(unsigned long long *)args[2]),
- (int)*(unsigned long long *)args[3],
- (int)(*(int *)args[4]), (int)(*(double *)args[5]),
- (int)*(double *)args[6], (int)(*(float *)args[7]),
- (int)(*(double *)args[8]), (int)*(double *)args[9],
- (int)(*(int *)args[10]), (int)(*(float *)args[11]),
- (int)*(int *)args[12], (int)(*(int *)args[13]),
- (int)(*(double *)args[14]), (int)(*(double *)args[15]),
- (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
-
-}
-
-typedef int (*closure_test_type0)(unsigned long long,
- unsigned long long,
- unsigned long long,
- unsigned long long,
- int, double, double, float, double, double,
- int, float, int, int, double, double);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[17];
- int res;
-
- cl_arg_types[0] = &ffi_type_uint64;
- cl_arg_types[1] = &ffi_type_uint64;
- cl_arg_types[2] = &ffi_type_uint64;
- cl_arg_types[3] = &ffi_type_uint64;
- cl_arg_types[4] = &ffi_type_sint;
- cl_arg_types[5] = &ffi_type_double;
- cl_arg_types[6] = &ffi_type_double;
- cl_arg_types[7] = &ffi_type_float;
- cl_arg_types[8] = &ffi_type_double;
- cl_arg_types[9] = &ffi_type_double;
- cl_arg_types[10] = &ffi_type_sint;
- cl_arg_types[11] = &ffi_type_float;
- cl_arg_types[12] = &ffi_type_sint;
- cl_arg_types[13] = &ffi_type_sint;
- cl_arg_types[14] = &ffi_type_double;
- cl_arg_types[15] = &ffi_type_double;
- cl_arg_types[16] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
- &ffi_type_sint, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn0,
- (void *) 3 /* userdata */, code) == FFI_OK);
-
- res = (*((closure_test_type0)code))
- (1, 2, 3, 4, 127, 429., 7., 8., 9.5, 10., 11, 12., 13,
- 19, 21., 1.);
- /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 680" } */
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check multiple values passing from different type.
+ Also, exceed the limit of gpr and fpr registers on PowerPC.
+ Limitations: none.
+ PR: PR23404
+ Originator: <andreast@gcc.gnu.org> 20050830 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void
+closure_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata)
+{
+ *(ffi_arg*)resp =
+ (int)*(unsigned long long *)args[0] +
+ (int)(*(unsigned long long *)args[1]) +
+ (int)(*(unsigned long long *)args[2]) +
+ (int)*(unsigned long long *)args[3] +
+ (int)(*(int *)args[4]) + (int)(*(double *)args[5]) +
+ (int)*(double *)args[6] + (int)(*(float *)args[7]) +
+ (int)(*(double *)args[8]) + (int)*(double *)args[9] +
+ (int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
+ (int)*(int *)args[12] + (int)(*(int *)args[13]) +
+ (int)(*(double *)args[14]) + (int)*(double *)args[15] +
+ (intptr_t)userdata;
+
+ printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
+ (int)*(unsigned long long *)args[0],
+ (int)(*(unsigned long long *)args[1]),
+ (int)(*(unsigned long long *)args[2]),
+ (int)*(unsigned long long *)args[3],
+ (int)(*(int *)args[4]), (int)(*(double *)args[5]),
+ (int)*(double *)args[6], (int)(*(float *)args[7]),
+ (int)(*(double *)args[8]), (int)*(double *)args[9],
+ (int)(*(int *)args[10]), (int)(*(float *)args[11]),
+ (int)*(int *)args[12], (int)(*(int *)args[13]),
+ (int)(*(double *)args[14]), (int)(*(double *)args[15]),
+ (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
+
+}
+
+typedef int (*closure_test_type0)(unsigned long long,
+ unsigned long long,
+ unsigned long long,
+ unsigned long long,
+ int, double, double, float, double, double,
+ int, float, int, int, double, double);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[17];
+ int res;
+
+ cl_arg_types[0] = &ffi_type_uint64;
+ cl_arg_types[1] = &ffi_type_uint64;
+ cl_arg_types[2] = &ffi_type_uint64;
+ cl_arg_types[3] = &ffi_type_uint64;
+ cl_arg_types[4] = &ffi_type_sint;
+ cl_arg_types[5] = &ffi_type_double;
+ cl_arg_types[6] = &ffi_type_double;
+ cl_arg_types[7] = &ffi_type_float;
+ cl_arg_types[8] = &ffi_type_double;
+ cl_arg_types[9] = &ffi_type_double;
+ cl_arg_types[10] = &ffi_type_sint;
+ cl_arg_types[11] = &ffi_type_float;
+ cl_arg_types[12] = &ffi_type_sint;
+ cl_arg_types[13] = &ffi_type_sint;
+ cl_arg_types[14] = &ffi_type_double;
+ cl_arg_types[15] = &ffi_type_double;
+ cl_arg_types[16] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
+ &ffi_type_sint, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn0,
+ (void *) 3 /* userdata */, code) == FFI_OK);
+
+ res = (*((closure_test_type0)code))
+ (1, 2, 3, 4, 127, 429., 7., 8., 9.5, 10., 11, 12., 13,
+ 19, 21., 1.);
+ /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 680" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn6/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn6/ya.make
index bc7f82e50d..415974ea55 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn6/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_fn6/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- closure_fn6.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ closure_fn6.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_loc_fn0.c b/contrib/restricted/libffi/testsuite/libffi.closures/closure_loc_fn0.c
index eaecec62df..b3afa0bbdf 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_loc_fn0.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_loc_fn0.c
@@ -1,95 +1,95 @@
-/* Area: closure_call
- Purpose: Check multiple values passing from different type.
- Also, exceed the limit of gpr and fpr registers on PowerPC
- Darwin.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-
-
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void
-closure_loc_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata)
-{
- *(ffi_arg*)resp =
- (int)*(unsigned long long *)args[0] + (int)(*(int *)args[1]) +
- (int)(*(unsigned long long *)args[2]) + (int)*(int *)args[3] +
- (int)(*(signed short *)args[4]) +
- (int)(*(unsigned long long *)args[5]) +
- (int)*(int *)args[6] + (int)(*(int *)args[7]) +
- (int)(*(double *)args[8]) + (int)*(int *)args[9] +
- (int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
- (int)*(int *)args[12] + (int)(*(int *)args[13]) +
- (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata;
-
- printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
- (int)*(unsigned long long *)args[0], (int)(*(int *)args[1]),
- (int)(*(unsigned long long *)args[2]),
- (int)*(int *)args[3], (int)(*(signed short *)args[4]),
- (int)(*(unsigned long long *)args[5]),
- (int)*(int *)args[6], (int)(*(int *)args[7]),
- (int)(*(double *)args[8]), (int)*(int *)args[9],
- (int)(*(int *)args[10]), (int)(*(float *)args[11]),
- (int)*(int *)args[12], (int)(*(int *)args[13]),
- (int)(*(int *)args[14]),*(int *)args[15],
- (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
-
-}
-
-typedef int (*closure_loc_test_type0)(unsigned long long, int, unsigned long long,
- int, signed short, unsigned long long, int,
- int, double, int, int, float, int, int,
- int, int);
-
-int main (void)
-{
- ffi_cif cif;
- ffi_closure *pcl;
- ffi_type * cl_arg_types[17];
- int res;
- void *codeloc;
-
- cl_arg_types[0] = &ffi_type_uint64;
- cl_arg_types[1] = &ffi_type_sint;
- cl_arg_types[2] = &ffi_type_uint64;
- cl_arg_types[3] = &ffi_type_sint;
- cl_arg_types[4] = &ffi_type_sshort;
- cl_arg_types[5] = &ffi_type_uint64;
- cl_arg_types[6] = &ffi_type_sint;
- cl_arg_types[7] = &ffi_type_sint;
- cl_arg_types[8] = &ffi_type_double;
- cl_arg_types[9] = &ffi_type_sint;
- cl_arg_types[10] = &ffi_type_sint;
- cl_arg_types[11] = &ffi_type_float;
- cl_arg_types[12] = &ffi_type_sint;
- cl_arg_types[13] = &ffi_type_sint;
- cl_arg_types[14] = &ffi_type_sint;
- cl_arg_types[15] = &ffi_type_sint;
- cl_arg_types[16] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
- &ffi_type_sint, cl_arg_types) == FFI_OK);
-
- pcl = ffi_closure_alloc(sizeof(ffi_closure), &codeloc);
- CHECK(pcl != NULL);
- CHECK(codeloc != NULL);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0,
- (void *) 3 /* userdata */, codeloc) == FFI_OK);
-
- CHECK(memcmp(pcl, codeloc, sizeof(*pcl)) == 0);
-
- res = (*((closure_loc_test_type0)codeloc))
- (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13,
- 19, 21, 1);
- /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 680" } */
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check multiple values passing from different type.
+ Also, exceed the limit of gpr and fpr registers on PowerPC
+ Darwin.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+
+
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void
+closure_loc_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata)
+{
+ *(ffi_arg*)resp =
+ (int)*(unsigned long long *)args[0] + (int)(*(int *)args[1]) +
+ (int)(*(unsigned long long *)args[2]) + (int)*(int *)args[3] +
+ (int)(*(signed short *)args[4]) +
+ (int)(*(unsigned long long *)args[5]) +
+ (int)*(int *)args[6] + (int)(*(int *)args[7]) +
+ (int)(*(double *)args[8]) + (int)*(int *)args[9] +
+ (int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
+ (int)*(int *)args[12] + (int)(*(int *)args[13]) +
+ (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata;
+
+ printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
+ (int)*(unsigned long long *)args[0], (int)(*(int *)args[1]),
+ (int)(*(unsigned long long *)args[2]),
+ (int)*(int *)args[3], (int)(*(signed short *)args[4]),
+ (int)(*(unsigned long long *)args[5]),
+ (int)*(int *)args[6], (int)(*(int *)args[7]),
+ (int)(*(double *)args[8]), (int)*(int *)args[9],
+ (int)(*(int *)args[10]), (int)(*(float *)args[11]),
+ (int)*(int *)args[12], (int)(*(int *)args[13]),
+ (int)(*(int *)args[14]),*(int *)args[15],
+ (int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
+
+}
+
+typedef int (*closure_loc_test_type0)(unsigned long long, int, unsigned long long,
+ int, signed short, unsigned long long, int,
+ int, double, int, int, float, int, int,
+ int, int);
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_closure *pcl;
+ ffi_type * cl_arg_types[17];
+ int res;
+ void *codeloc;
+
+ cl_arg_types[0] = &ffi_type_uint64;
+ cl_arg_types[1] = &ffi_type_sint;
+ cl_arg_types[2] = &ffi_type_uint64;
+ cl_arg_types[3] = &ffi_type_sint;
+ cl_arg_types[4] = &ffi_type_sshort;
+ cl_arg_types[5] = &ffi_type_uint64;
+ cl_arg_types[6] = &ffi_type_sint;
+ cl_arg_types[7] = &ffi_type_sint;
+ cl_arg_types[8] = &ffi_type_double;
+ cl_arg_types[9] = &ffi_type_sint;
+ cl_arg_types[10] = &ffi_type_sint;
+ cl_arg_types[11] = &ffi_type_float;
+ cl_arg_types[12] = &ffi_type_sint;
+ cl_arg_types[13] = &ffi_type_sint;
+ cl_arg_types[14] = &ffi_type_sint;
+ cl_arg_types[15] = &ffi_type_sint;
+ cl_arg_types[16] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
+ &ffi_type_sint, cl_arg_types) == FFI_OK);
+
+ pcl = ffi_closure_alloc(sizeof(ffi_closure), &codeloc);
+ CHECK(pcl != NULL);
+ CHECK(codeloc != NULL);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0,
+ (void *) 3 /* userdata */, codeloc) == FFI_OK);
+
+ CHECK(memcmp(pcl, codeloc, sizeof(*pcl)) == 0);
+
+ res = (*((closure_loc_test_type0)codeloc))
+ (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13,
+ 19, 21, 1);
+ /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 680" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_loc_fn0/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/closure_loc_fn0/ya.make
index b28e2812d2..2345094723 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_loc_fn0/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_loc_fn0/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- closure_loc_fn0.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ closure_loc_fn0.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_simple.c b/contrib/restricted/libffi/testsuite/libffi.closures/closure_simple.c
index 5706c4141c..5a4e728d4a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_simple.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_simple.c
@@ -1,55 +1,55 @@
-/* Area: closure_call
- Purpose: Check simple closure handling with all ABIs
- Limitations: none.
- PR: none.
- Originator: <twalljava@dev.java.net> */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void
-closure_test(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata)
-{
- *(ffi_arg*)resp =
- (int)*(int *)args[0] + (int)(*(int *)args[1])
- + (int)(*(int *)args[2]) + (int)(*(int *)args[3])
- + (int)(intptr_t)userdata;
-
- printf("%d %d %d %d: %d\n",
- (int)*(int *)args[0], (int)(*(int *)args[1]),
- (int)(*(int *)args[2]), (int)(*(int *)args[3]),
- (int)*(ffi_arg *)resp);
-
-}
-
-typedef int (ABI_ATTR *closure_test_type0)(int, int, int, int);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[17];
- int res;
-
- cl_arg_types[0] = &ffi_type_uint;
- cl_arg_types[1] = &ffi_type_uint;
- cl_arg_types[2] = &ffi_type_uint;
- cl_arg_types[3] = &ffi_type_uint;
- cl_arg_types[4] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 4,
- &ffi_type_sint, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test,
- (void *) 3 /* userdata */, code) == FFI_OK);
-
- res = (*(closure_test_type0)code)(0, 1, 2, 3);
- /* { dg-output "0 1 2 3: 9" } */
-
- printf("res: %d\n",res);
- /* { dg-output "\nres: 9" } */
-
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check simple closure handling with all ABIs
+ Limitations: none.
+ PR: none.
+ Originator: <twalljava@dev.java.net> */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void
+closure_test(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata)
+{
+ *(ffi_arg*)resp =
+ (int)*(int *)args[0] + (int)(*(int *)args[1])
+ + (int)(*(int *)args[2]) + (int)(*(int *)args[3])
+ + (int)(intptr_t)userdata;
+
+ printf("%d %d %d %d: %d\n",
+ (int)*(int *)args[0], (int)(*(int *)args[1]),
+ (int)(*(int *)args[2]), (int)(*(int *)args[3]),
+ (int)*(ffi_arg *)resp);
+
+}
+
+typedef int (ABI_ATTR *closure_test_type0)(int, int, int, int);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[17];
+ int res;
+
+ cl_arg_types[0] = &ffi_type_uint;
+ cl_arg_types[1] = &ffi_type_uint;
+ cl_arg_types[2] = &ffi_type_uint;
+ cl_arg_types[3] = &ffi_type_uint;
+ cl_arg_types[4] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 4,
+ &ffi_type_sint, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test,
+ (void *) 3 /* userdata */, code) == FFI_OK);
+
+ res = (*(closure_test_type0)code)(0, 1, 2, 3);
+ /* { dg-output "0 1 2 3: 9" } */
+
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 9" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/closure_simple/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/closure_simple/ya.make
index 5ba4c66fbe..e7edd97c74 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/closure_simple/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/closure_simple/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- closure_simple.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ closure_simple.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_12byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_12byte.c
index 1d7aff78f0..ea0825d175 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_12byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_12byte.c
@@ -1,94 +1,94 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_12byte {
- int a;
- int b;
- int c;
-} cls_struct_12byte;
-
-cls_struct_12byte cls_struct_12byte_fn(struct cls_struct_12byte b1,
- struct cls_struct_12byte b2)
-{
- struct cls_struct_12byte result;
-
- result.a = b1.a + b2.a;
- result.b = b1.b + b2.b;
- result.c = b1.c + b2.c;
-
- printf("%d %d %d %d %d %d: %d %d %d\n", b1.a, b1.b, b1.c, b2.a, b2.b, b2.c,
- result.a, result.b, result.c);
-
- return result;
-}
-
-static void cls_struct_12byte_gn(ffi_cif* cif __UNUSED__, void* resp,
- void** args , void* userdata __UNUSED__)
-{
- struct cls_struct_12byte b1, b2;
-
- b1 = *(struct cls_struct_12byte*)(args[0]);
- b2 = *(struct cls_struct_12byte*)(args[1]);
-
- *(cls_struct_12byte*)resp = cls_struct_12byte_fn(b1, b2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_12byte h_dbl = { 7, 4, 9 };
- struct cls_struct_12byte j_dbl = { 1, 5, 3 };
- struct cls_struct_12byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_sint;
- cls_struct_fields[1] = &ffi_type_sint;
- cls_struct_fields[2] = &ffi_type_sint;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &h_dbl;
- args_dbl[1] = &j_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_12byte_fn), &res_dbl, args_dbl);
- /* { dg-output "7 4 9 1 5 3: 8 9 12" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 8 9 12" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_12byte_gn, NULL, code) == FFI_OK);
-
- res_dbl.a = 0;
- res_dbl.b = 0;
- res_dbl.c = 0;
-
- res_dbl = ((cls_struct_12byte(*)(cls_struct_12byte, cls_struct_12byte))(code))(h_dbl, j_dbl);
- /* { dg-output "\n7 4 9 1 5 3: 8 9 12" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 8 9 12" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_12byte {
+ int a;
+ int b;
+ int c;
+} cls_struct_12byte;
+
+cls_struct_12byte cls_struct_12byte_fn(struct cls_struct_12byte b1,
+ struct cls_struct_12byte b2)
+{
+ struct cls_struct_12byte result;
+
+ result.a = b1.a + b2.a;
+ result.b = b1.b + b2.b;
+ result.c = b1.c + b2.c;
+
+ printf("%d %d %d %d %d %d: %d %d %d\n", b1.a, b1.b, b1.c, b2.a, b2.b, b2.c,
+ result.a, result.b, result.c);
+
+ return result;
+}
+
+static void cls_struct_12byte_gn(ffi_cif* cif __UNUSED__, void* resp,
+ void** args , void* userdata __UNUSED__)
+{
+ struct cls_struct_12byte b1, b2;
+
+ b1 = *(struct cls_struct_12byte*)(args[0]);
+ b2 = *(struct cls_struct_12byte*)(args[1]);
+
+ *(cls_struct_12byte*)resp = cls_struct_12byte_fn(b1, b2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_12byte h_dbl = { 7, 4, 9 };
+ struct cls_struct_12byte j_dbl = { 1, 5, 3 };
+ struct cls_struct_12byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_sint;
+ cls_struct_fields[1] = &ffi_type_sint;
+ cls_struct_fields[2] = &ffi_type_sint;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &h_dbl;
+ args_dbl[1] = &j_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_12byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "7 4 9 1 5 3: 8 9 12" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 8 9 12" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_12byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl.a = 0;
+ res_dbl.b = 0;
+ res_dbl.c = 0;
+
+ res_dbl = ((cls_struct_12byte(*)(cls_struct_12byte, cls_struct_12byte))(code))(h_dbl, j_dbl);
+ /* { dg-output "\n7 4 9 1 5 3: 8 9 12" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 8 9 12" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_12byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_12byte/ya.make
index 8e6f69dbf7..67a1d25459 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_12byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_12byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_12byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_12byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_16byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_16byte.c
index b6c561e049..89a08a2d97 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_16byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_16byte.c
@@ -1,95 +1,95 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_16byte {
- int a;
- double b;
- int c;
-} cls_struct_16byte;
-
-cls_struct_16byte cls_struct_16byte_fn(struct cls_struct_16byte b1,
- struct cls_struct_16byte b2)
-{
- struct cls_struct_16byte result;
-
- result.a = b1.a + b2.a;
- result.b = b1.b + b2.b;
- result.c = b1.c + b2.c;
-
- printf("%d %g %d %d %g %d: %d %g %d\n", b1.a, b1.b, b1.c, b2.a, b2.b, b2.c,
- result.a, result.b, result.c);
-
- return result;
-}
-
-static void cls_struct_16byte_gn(ffi_cif* cif __UNUSED__, void* resp,
- void** args, void* userdata __UNUSED__)
-{
- struct cls_struct_16byte b1, b2;
-
- b1 = *(struct cls_struct_16byte*)(args[0]);
- b2 = *(struct cls_struct_16byte*)(args[1]);
-
- *(cls_struct_16byte*)resp = cls_struct_16byte_fn(b1, b2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_16byte h_dbl = { 7, 8.0, 9 };
- struct cls_struct_16byte j_dbl = { 1, 9.0, 3 };
- struct cls_struct_16byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_sint;
- cls_struct_fields[1] = &ffi_type_double;
- cls_struct_fields[2] = &ffi_type_sint;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &h_dbl;
- args_dbl[1] = &j_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_16byte_fn), &res_dbl, args_dbl);
- /* { dg-output "7 8 9 1 9 3: 8 17 12" } */
- printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 8 17 12" } */
-
- res_dbl.a = 0;
- res_dbl.b = 0.0;
- res_dbl.c = 0;
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_16byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_16byte(*)(cls_struct_16byte, cls_struct_16byte))(code))(h_dbl, j_dbl);
- /* { dg-output "\n7 8 9 1 9 3: 8 17 12" } */
- printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 8 17 12" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_16byte {
+ int a;
+ double b;
+ int c;
+} cls_struct_16byte;
+
+cls_struct_16byte cls_struct_16byte_fn(struct cls_struct_16byte b1,
+ struct cls_struct_16byte b2)
+{
+ struct cls_struct_16byte result;
+
+ result.a = b1.a + b2.a;
+ result.b = b1.b + b2.b;
+ result.c = b1.c + b2.c;
+
+ printf("%d %g %d %d %g %d: %d %g %d\n", b1.a, b1.b, b1.c, b2.a, b2.b, b2.c,
+ result.a, result.b, result.c);
+
+ return result;
+}
+
+static void cls_struct_16byte_gn(ffi_cif* cif __UNUSED__, void* resp,
+ void** args, void* userdata __UNUSED__)
+{
+ struct cls_struct_16byte b1, b2;
+
+ b1 = *(struct cls_struct_16byte*)(args[0]);
+ b2 = *(struct cls_struct_16byte*)(args[1]);
+
+ *(cls_struct_16byte*)resp = cls_struct_16byte_fn(b1, b2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_16byte h_dbl = { 7, 8.0, 9 };
+ struct cls_struct_16byte j_dbl = { 1, 9.0, 3 };
+ struct cls_struct_16byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_sint;
+ cls_struct_fields[1] = &ffi_type_double;
+ cls_struct_fields[2] = &ffi_type_sint;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &h_dbl;
+ args_dbl[1] = &j_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_16byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "7 8 9 1 9 3: 8 17 12" } */
+ printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 8 17 12" } */
+
+ res_dbl.a = 0;
+ res_dbl.b = 0.0;
+ res_dbl.c = 0;
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_16byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_16byte(*)(cls_struct_16byte, cls_struct_16byte))(code))(h_dbl, j_dbl);
+ /* { dg-output "\n7 8 9 1 9 3: 8 17 12" } */
+ printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 8 17 12" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_16byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_16byte/ya.make
index 5b76ab8baa..fbb5a3034a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_16byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_16byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_16byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_16byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_18byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_18byte.c
index bfa4354ae6..9f75da80aa 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_18byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_18byte.c
@@ -1,96 +1,96 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Double alignment check on darwin.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030915 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_18byte {
- double a;
- unsigned char b;
- unsigned char c;
- double d;
-} cls_struct_18byte;
-
-cls_struct_18byte cls_struct_18byte_fn(struct cls_struct_18byte a1,
- struct cls_struct_18byte a2)
-{
- struct cls_struct_18byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
- result.d = a1.d + a2.d;
-
-
- printf("%g %d %d %g %g %d %d %g: %g %d %d %g\n", a1.a, a1.b, a1.c, a1.d,
- a2.a, a2.b, a2.c, a2.d,
- result.a, result.b, result.c, result.d);
- return result;
-}
-
-static void
-cls_struct_18byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct cls_struct_18byte a1, a2;
-
- a1 = *(struct cls_struct_18byte*)(args[0]);
- a2 = *(struct cls_struct_18byte*)(args[1]);
-
- *(cls_struct_18byte*)resp = cls_struct_18byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[5];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[3];
-
- struct cls_struct_18byte g_dbl = { 1.0, 127, 126, 3.0 };
- struct cls_struct_18byte f_dbl = { 4.0, 125, 124, 5.0 };
- struct cls_struct_18byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = &ffi_type_double;
- cls_struct_fields[4] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_18byte_fn), &res_dbl, args_dbl);
- /* { dg-output "1 127 126 3 4 125 124 5: 5 252 250 8" } */
- printf("res: %g %d %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
- /* { dg-output "\nres: 5 252 250 8" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_18byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_18byte(*)(cls_struct_18byte, cls_struct_18byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n1 127 126 3 4 125 124 5: 5 252 250 8" } */
- printf("res: %g %d %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
- /* { dg-output "\nres: 5 252 250 8" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Double alignment check on darwin.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030915 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_18byte {
+ double a;
+ unsigned char b;
+ unsigned char c;
+ double d;
+} cls_struct_18byte;
+
+cls_struct_18byte cls_struct_18byte_fn(struct cls_struct_18byte a1,
+ struct cls_struct_18byte a2)
+{
+ struct cls_struct_18byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+ result.d = a1.d + a2.d;
+
+
+ printf("%g %d %d %g %g %d %d %g: %g %d %d %g\n", a1.a, a1.b, a1.c, a1.d,
+ a2.a, a2.b, a2.c, a2.d,
+ result.a, result.b, result.c, result.d);
+ return result;
+}
+
+static void
+cls_struct_18byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct cls_struct_18byte a1, a2;
+
+ a1 = *(struct cls_struct_18byte*)(args[0]);
+ a2 = *(struct cls_struct_18byte*)(args[1]);
+
+ *(cls_struct_18byte*)resp = cls_struct_18byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[5];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[3];
+
+ struct cls_struct_18byte g_dbl = { 1.0, 127, 126, 3.0 };
+ struct cls_struct_18byte f_dbl = { 4.0, 125, 124, 5.0 };
+ struct cls_struct_18byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = &ffi_type_double;
+ cls_struct_fields[4] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_18byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 127 126 3 4 125 124 5: 5 252 250 8" } */
+ printf("res: %g %d %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
+ /* { dg-output "\nres: 5 252 250 8" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_18byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_18byte(*)(cls_struct_18byte, cls_struct_18byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n1 127 126 3 4 125 124 5: 5 252 250 8" } */
+ printf("res: %g %d %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
+ /* { dg-output "\nres: 5 252 250 8" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_18byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_18byte/ya.make
index bdcc68168f..77fbc79c01 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_18byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_18byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_18byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_18byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_19byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_19byte.c
index 4148177b6b..278794b5b8 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_19byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_19byte.c
@@ -1,102 +1,102 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Double alignment check on darwin.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030915 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_19byte {
- double a;
- unsigned char b;
- unsigned char c;
- double d;
- unsigned char e;
-} cls_struct_19byte;
-
-cls_struct_19byte cls_struct_19byte_fn(struct cls_struct_19byte a1,
- struct cls_struct_19byte a2)
-{
- struct cls_struct_19byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
- result.d = a1.d + a2.d;
- result.e = a1.e + a2.e;
-
-
- printf("%g %d %d %g %d %g %d %d %g %d: %g %d %d %g %d\n",
- a1.a, a1.b, a1.c, a1.d, a1.e,
- a2.a, a2.b, a2.c, a2.d, a2.e,
- result.a, result.b, result.c, result.d, result.e);
- return result;
-}
-
-static void
-cls_struct_19byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct cls_struct_19byte a1, a2;
-
- a1 = *(struct cls_struct_19byte*)(args[0]);
- a2 = *(struct cls_struct_19byte*)(args[1]);
-
- *(cls_struct_19byte*)resp = cls_struct_19byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[6];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[3];
-
- struct cls_struct_19byte g_dbl = { 1.0, 127, 126, 3.0, 120 };
- struct cls_struct_19byte f_dbl = { 4.0, 125, 124, 5.0, 119 };
- struct cls_struct_19byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = &ffi_type_double;
- cls_struct_fields[4] = &ffi_type_uchar;
- cls_struct_fields[5] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_19byte_fn), &res_dbl, args_dbl);
- /* { dg-output "1 127 126 3 120 4 125 124 5 119: 5 252 250 8 239" } */
- printf("res: %g %d %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e);
- /* { dg-output "\nres: 5 252 250 8 239" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_19byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_19byte(*)(cls_struct_19byte, cls_struct_19byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n1 127 126 3 120 4 125 124 5 119: 5 252 250 8 239" } */
- printf("res: %g %d %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e);
- /* { dg-output "\nres: 5 252 250 8 239" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Double alignment check on darwin.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030915 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_19byte {
+ double a;
+ unsigned char b;
+ unsigned char c;
+ double d;
+ unsigned char e;
+} cls_struct_19byte;
+
+cls_struct_19byte cls_struct_19byte_fn(struct cls_struct_19byte a1,
+ struct cls_struct_19byte a2)
+{
+ struct cls_struct_19byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+ result.d = a1.d + a2.d;
+ result.e = a1.e + a2.e;
+
+
+ printf("%g %d %d %g %d %g %d %d %g %d: %g %d %d %g %d\n",
+ a1.a, a1.b, a1.c, a1.d, a1.e,
+ a2.a, a2.b, a2.c, a2.d, a2.e,
+ result.a, result.b, result.c, result.d, result.e);
+ return result;
+}
+
+static void
+cls_struct_19byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct cls_struct_19byte a1, a2;
+
+ a1 = *(struct cls_struct_19byte*)(args[0]);
+ a2 = *(struct cls_struct_19byte*)(args[1]);
+
+ *(cls_struct_19byte*)resp = cls_struct_19byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[6];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[3];
+
+ struct cls_struct_19byte g_dbl = { 1.0, 127, 126, 3.0, 120 };
+ struct cls_struct_19byte f_dbl = { 4.0, 125, 124, 5.0, 119 };
+ struct cls_struct_19byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = &ffi_type_double;
+ cls_struct_fields[4] = &ffi_type_uchar;
+ cls_struct_fields[5] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_19byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 127 126 3 120 4 125 124 5 119: 5 252 250 8 239" } */
+ printf("res: %g %d %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e);
+ /* { dg-output "\nres: 5 252 250 8 239" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_19byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_19byte(*)(cls_struct_19byte, cls_struct_19byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n1 127 126 3 120 4 125 124 5 119: 5 252 250 8 239" } */
+ printf("res: %g %d %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e);
+ /* { dg-output "\nres: 5 252 250 8 239" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_19byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_19byte/ya.make
index 41a7c39490..33fac8f8b9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_19byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_19byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_19byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_19byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_1_1byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_1_1byte.c
index 64d8dab935..82492c020e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_1_1byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_1_1byte.c
@@ -1,89 +1,89 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Especially with small structures which may fit in one
- register. Depending on the ABI.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030902 */
-
-
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_1_1byte {
- unsigned char a;
-} cls_struct_1_1byte;
-
-cls_struct_1_1byte cls_struct_1_1byte_fn(struct cls_struct_1_1byte a1,
- struct cls_struct_1_1byte a2)
-{
- struct cls_struct_1_1byte result;
-
- result.a = a1.a + a2.a;
-
- printf("%d %d: %d\n", a1.a, a2.a, result.a);
-
- return result;
-}
-
-static void
-cls_struct_1_1byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_1_1byte a1, a2;
-
- a1 = *(struct cls_struct_1_1byte*)(args[0]);
- a2 = *(struct cls_struct_1_1byte*)(args[1]);
-
- *(cls_struct_1_1byte*)resp = cls_struct_1_1byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[2];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_1_1byte g_dbl = { 12 };
- struct cls_struct_1_1byte f_dbl = { 178 };
- struct cls_struct_1_1byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_1_1byte_fn), &res_dbl, args_dbl);
- /* { dg-output "12 178: 190" } */
- printf("res: %d\n", res_dbl.a);
- /* { dg-output "\nres: 190" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_1_1byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_1_1byte(*)(cls_struct_1_1byte, cls_struct_1_1byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 178: 190" } */
- printf("res: %d\n", res_dbl.a);
- /* { dg-output "\nres: 190" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Especially with small structures which may fit in one
+ register. Depending on the ABI.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030902 */
+
+
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_1_1byte {
+ unsigned char a;
+} cls_struct_1_1byte;
+
+cls_struct_1_1byte cls_struct_1_1byte_fn(struct cls_struct_1_1byte a1,
+ struct cls_struct_1_1byte a2)
+{
+ struct cls_struct_1_1byte result;
+
+ result.a = a1.a + a2.a;
+
+ printf("%d %d: %d\n", a1.a, a2.a, result.a);
+
+ return result;
+}
+
+static void
+cls_struct_1_1byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_1_1byte a1, a2;
+
+ a1 = *(struct cls_struct_1_1byte*)(args[0]);
+ a2 = *(struct cls_struct_1_1byte*)(args[1]);
+
+ *(cls_struct_1_1byte*)resp = cls_struct_1_1byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[2];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_1_1byte g_dbl = { 12 };
+ struct cls_struct_1_1byte f_dbl = { 178 };
+ struct cls_struct_1_1byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_1_1byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 178: 190" } */
+ printf("res: %d\n", res_dbl.a);
+ /* { dg-output "\nres: 190" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_1_1byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_1_1byte(*)(cls_struct_1_1byte, cls_struct_1_1byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 178: 190" } */
+ printf("res: %d\n", res_dbl.a);
+ /* { dg-output "\nres: 190" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_1_1byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_1_1byte/ya.make
index a931b92f6c..efb2dd6dc5 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_1_1byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_1_1byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_1_1byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_1_1byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte.c
index d0f8714822..3f8bb28ad2 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte.c
@@ -1,91 +1,91 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_20byte {
- double a;
- double b;
- int c;
-} cls_struct_20byte;
-
-cls_struct_20byte cls_struct_20byte_fn(struct cls_struct_20byte a1,
- struct cls_struct_20byte a2)
-{
- struct cls_struct_20byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%g %g %d %g %g %d: %g %g %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c,
- result.a, result.b, result.c);
- return result;
-}
-
-static void
-cls_struct_20byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct cls_struct_20byte a1, a2;
-
- a1 = *(struct cls_struct_20byte*)(args[0]);
- a2 = *(struct cls_struct_20byte*)(args[1]);
-
- *(cls_struct_20byte*)resp = cls_struct_20byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_20byte g_dbl = { 1.0, 2.0, 3 };
- struct cls_struct_20byte f_dbl = { 4.0, 5.0, 7 };
- struct cls_struct_20byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_double;
- cls_struct_fields[2] = &ffi_type_sint;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_20byte_fn), &res_dbl, args_dbl);
- /* { dg-output "1 2 3 4 5 7: 5 7 10" } */
- printf("res: %g %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 5 7 10" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_20byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_20byte(*)(cls_struct_20byte, cls_struct_20byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n1 2 3 4 5 7: 5 7 10" } */
- printf("res: %g %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 5 7 10" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_20byte {
+ double a;
+ double b;
+ int c;
+} cls_struct_20byte;
+
+cls_struct_20byte cls_struct_20byte_fn(struct cls_struct_20byte a1,
+ struct cls_struct_20byte a2)
+{
+ struct cls_struct_20byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%g %g %d %g %g %d: %g %g %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c,
+ result.a, result.b, result.c);
+ return result;
+}
+
+static void
+cls_struct_20byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct cls_struct_20byte a1, a2;
+
+ a1 = *(struct cls_struct_20byte*)(args[0]);
+ a2 = *(struct cls_struct_20byte*)(args[1]);
+
+ *(cls_struct_20byte*)resp = cls_struct_20byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_20byte g_dbl = { 1.0, 2.0, 3 };
+ struct cls_struct_20byte f_dbl = { 4.0, 5.0, 7 };
+ struct cls_struct_20byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_double;
+ cls_struct_fields[2] = &ffi_type_sint;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_20byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 2 3 4 5 7: 5 7 10" } */
+ printf("res: %g %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 5 7 10" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_20byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_20byte(*)(cls_struct_20byte, cls_struct_20byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n1 2 3 4 5 7: 5 7 10" } */
+ printf("res: %g %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 5 7 10" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte/ya.make
index 2017a6dbec..d7923e1680 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_20byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_20byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte1.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte1.c
index 8aac032ce5..65627273c8 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte1.c
@@ -1,93 +1,93 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_20byte {
- int a;
- double b;
- double c;
-} cls_struct_20byte;
-
-cls_struct_20byte cls_struct_20byte_fn(struct cls_struct_20byte a1,
- struct cls_struct_20byte a2)
-{
- struct cls_struct_20byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %g %g %d %g %g: %d %g %g\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c,
- result.a, result.b, result.c);
- return result;
-}
-
-static void
-cls_struct_20byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct cls_struct_20byte a1, a2;
-
- a1 = *(struct cls_struct_20byte*)(args[0]);
- a2 = *(struct cls_struct_20byte*)(args[1]);
-
- *(cls_struct_20byte*)resp = cls_struct_20byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[3];
-
- struct cls_struct_20byte g_dbl = { 1, 2.0, 3.0 };
- struct cls_struct_20byte f_dbl = { 4, 5.0, 7.0 };
- struct cls_struct_20byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_sint;
- cls_struct_fields[1] = &ffi_type_double;
- cls_struct_fields[2] = &ffi_type_double;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_20byte_fn), &res_dbl, args_dbl);
- /* { dg-output "1 2 3 4 5 7: 5 7 10" } */
- printf("res: %d %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 5 7 10" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_20byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_20byte(*)(cls_struct_20byte, cls_struct_20byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n1 2 3 4 5 7: 5 7 10" } */
- printf("res: %d %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 5 7 10" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_20byte {
+ int a;
+ double b;
+ double c;
+} cls_struct_20byte;
+
+cls_struct_20byte cls_struct_20byte_fn(struct cls_struct_20byte a1,
+ struct cls_struct_20byte a2)
+{
+ struct cls_struct_20byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %g %g %d %g %g: %d %g %g\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c,
+ result.a, result.b, result.c);
+ return result;
+}
+
+static void
+cls_struct_20byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct cls_struct_20byte a1, a2;
+
+ a1 = *(struct cls_struct_20byte*)(args[0]);
+ a2 = *(struct cls_struct_20byte*)(args[1]);
+
+ *(cls_struct_20byte*)resp = cls_struct_20byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[3];
+
+ struct cls_struct_20byte g_dbl = { 1, 2.0, 3.0 };
+ struct cls_struct_20byte f_dbl = { 4, 5.0, 7.0 };
+ struct cls_struct_20byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_sint;
+ cls_struct_fields[1] = &ffi_type_double;
+ cls_struct_fields[2] = &ffi_type_double;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_20byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 2 3 4 5 7: 5 7 10" } */
+ printf("res: %d %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 5 7 10" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_20byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_20byte(*)(cls_struct_20byte, cls_struct_20byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n1 2 3 4 5 7: 5 7 10" } */
+ printf("res: %d %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 5 7 10" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte1/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte1/ya.make
index 15c8a24834..1367a12243 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_20byte1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_20byte1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_20byte1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_24byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_24byte.c
index f91ce38479..1d82f6e4a4 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_24byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_24byte.c
@@ -1,113 +1,113 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_24byte {
- double a;
- double b;
- int c;
- float d;
-} cls_struct_24byte;
-
-cls_struct_24byte cls_struct_24byte_fn(struct cls_struct_24byte b0,
- struct cls_struct_24byte b1,
- struct cls_struct_24byte b2,
- struct cls_struct_24byte b3)
-{
- struct cls_struct_24byte result;
-
- result.a = b0.a + b1.a + b2.a + b3.a;
- result.b = b0.b + b1.b + b2.b + b3.b;
- result.c = b0.c + b1.c + b2.c + b3.c;
- result.d = b0.d + b1.d + b2.d + b3.d;
-
- printf("%g %g %d %g %g %g %d %g %g %g %d %g %g %g %d %g: %g %g %d %g\n",
- b0.a, b0.b, b0.c, b0.d,
- b1.a, b1.b, b1.c, b1.d,
- b2.a, b2.b, b2.c, b2.d,
- b3.a, b3.b, b3.c, b2.d,
- result.a, result.b, result.c, result.d);
-
- return result;
-}
-
-static void
-cls_struct_24byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct cls_struct_24byte b0, b1, b2, b3;
-
- b0 = *(struct cls_struct_24byte*)(args[0]);
- b1 = *(struct cls_struct_24byte*)(args[1]);
- b2 = *(struct cls_struct_24byte*)(args[2]);
- b3 = *(struct cls_struct_24byte*)(args[3]);
-
- *(cls_struct_24byte*)resp = cls_struct_24byte_fn(b0, b1, b2, b3);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[5];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_24byte e_dbl = { 9.0, 2.0, 6, 5.0 };
- struct cls_struct_24byte f_dbl = { 1.0, 2.0, 3, 7.0 };
- struct cls_struct_24byte g_dbl = { 4.0, 5.0, 7, 9.0 };
- struct cls_struct_24byte h_dbl = { 8.0, 6.0, 1, 4.0 };
- struct cls_struct_24byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_double;
- cls_struct_fields[2] = &ffi_type_sint;
- cls_struct_fields[3] = &ffi_type_float;
- cls_struct_fields[4] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = &cls_struct_type;
- dbl_arg_types[3] = &cls_struct_type;
- dbl_arg_types[4] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = &h_dbl;
- args_dbl[4] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_24byte_fn), &res_dbl, args_dbl);
- /* { dg-output "9 2 6 5 1 2 3 7 4 5 7 9 8 6 1 9: 22 15 17 25" } */
- printf("res: %g %g %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
- /* { dg-output "\nres: 22 15 17 25" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_24byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_24byte(*)(cls_struct_24byte,
- cls_struct_24byte,
- cls_struct_24byte,
- cls_struct_24byte))
- (code))(e_dbl, f_dbl, g_dbl, h_dbl);
- /* { dg-output "\n9 2 6 5 1 2 3 7 4 5 7 9 8 6 1 9: 22 15 17 25" } */
- printf("res: %g %g %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
- /* { dg-output "\nres: 22 15 17 25" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_24byte {
+ double a;
+ double b;
+ int c;
+ float d;
+} cls_struct_24byte;
+
+cls_struct_24byte cls_struct_24byte_fn(struct cls_struct_24byte b0,
+ struct cls_struct_24byte b1,
+ struct cls_struct_24byte b2,
+ struct cls_struct_24byte b3)
+{
+ struct cls_struct_24byte result;
+
+ result.a = b0.a + b1.a + b2.a + b3.a;
+ result.b = b0.b + b1.b + b2.b + b3.b;
+ result.c = b0.c + b1.c + b2.c + b3.c;
+ result.d = b0.d + b1.d + b2.d + b3.d;
+
+ printf("%g %g %d %g %g %g %d %g %g %g %d %g %g %g %d %g: %g %g %d %g\n",
+ b0.a, b0.b, b0.c, b0.d,
+ b1.a, b1.b, b1.c, b1.d,
+ b2.a, b2.b, b2.c, b2.d,
+ b3.a, b3.b, b3.c, b2.d,
+ result.a, result.b, result.c, result.d);
+
+ return result;
+}
+
+static void
+cls_struct_24byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct cls_struct_24byte b0, b1, b2, b3;
+
+ b0 = *(struct cls_struct_24byte*)(args[0]);
+ b1 = *(struct cls_struct_24byte*)(args[1]);
+ b2 = *(struct cls_struct_24byte*)(args[2]);
+ b3 = *(struct cls_struct_24byte*)(args[3]);
+
+ *(cls_struct_24byte*)resp = cls_struct_24byte_fn(b0, b1, b2, b3);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[5];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_24byte e_dbl = { 9.0, 2.0, 6, 5.0 };
+ struct cls_struct_24byte f_dbl = { 1.0, 2.0, 3, 7.0 };
+ struct cls_struct_24byte g_dbl = { 4.0, 5.0, 7, 9.0 };
+ struct cls_struct_24byte h_dbl = { 8.0, 6.0, 1, 4.0 };
+ struct cls_struct_24byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_double;
+ cls_struct_fields[2] = &ffi_type_sint;
+ cls_struct_fields[3] = &ffi_type_float;
+ cls_struct_fields[4] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = &cls_struct_type;
+ dbl_arg_types[3] = &cls_struct_type;
+ dbl_arg_types[4] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = &h_dbl;
+ args_dbl[4] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_24byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "9 2 6 5 1 2 3 7 4 5 7 9 8 6 1 9: 22 15 17 25" } */
+ printf("res: %g %g %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
+ /* { dg-output "\nres: 22 15 17 25" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_24byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_24byte(*)(cls_struct_24byte,
+ cls_struct_24byte,
+ cls_struct_24byte,
+ cls_struct_24byte))
+ (code))(e_dbl, f_dbl, g_dbl, h_dbl);
+ /* { dg-output "\n9 2 6 5 1 2 3 7 4 5 7 9 8 6 1 9: 22 15 17 25" } */
+ printf("res: %g %g %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
+ /* { dg-output "\nres: 22 15 17 25" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_24byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_24byte/ya.make
index 54f6bffdff..213e1bae01 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_24byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_24byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_24byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_24byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_2byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_2byte.c
index e6dc3d523e..81bb0a64a3 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_2byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_2byte.c
@@ -1,90 +1,90 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Especially with small structures which may fit in one
- register. Depending on the ABI.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_2byte {
- unsigned char a;
- unsigned char b;
-} cls_struct_2byte;
-
-cls_struct_2byte cls_struct_2byte_fn(struct cls_struct_2byte a1,
- struct cls_struct_2byte a2)
-{
- struct cls_struct_2byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
-
- printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b);
-
- return result;
-}
-
-static void
-cls_struct_2byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_2byte a1, a2;
-
- a1 = *(struct cls_struct_2byte*)(args[0]);
- a2 = *(struct cls_struct_2byte*)(args[1]);
-
- *(cls_struct_2byte*)resp = cls_struct_2byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_2byte g_dbl = { 12, 127 };
- struct cls_struct_2byte f_dbl = { 1, 13 };
- struct cls_struct_2byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_2byte_fn), &res_dbl, args_dbl);
- /* { dg-output "12 127 1 13: 13 140" } */
- printf("res: %d %d\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 13 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_2byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_2byte(*)(cls_struct_2byte, cls_struct_2byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 127 1 13: 13 140" } */
- printf("res: %d %d\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 13 140" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Especially with small structures which may fit in one
+ register. Depending on the ABI.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_2byte {
+ unsigned char a;
+ unsigned char b;
+} cls_struct_2byte;
+
+cls_struct_2byte cls_struct_2byte_fn(struct cls_struct_2byte a1,
+ struct cls_struct_2byte a2)
+{
+ struct cls_struct_2byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+
+ printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b);
+
+ return result;
+}
+
+static void
+cls_struct_2byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_2byte a1, a2;
+
+ a1 = *(struct cls_struct_2byte*)(args[0]);
+ a2 = *(struct cls_struct_2byte*)(args[1]);
+
+ *(cls_struct_2byte*)resp = cls_struct_2byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_2byte g_dbl = { 12, 127 };
+ struct cls_struct_2byte f_dbl = { 1, 13 };
+ struct cls_struct_2byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_2byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 127 1 13: 13 140" } */
+ printf("res: %d %d\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 13 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_2byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_2byte(*)(cls_struct_2byte, cls_struct_2byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 127 1 13: 13 140" } */
+ printf("res: %d %d\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 13 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_2byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_2byte/ya.make
index cc583f2317..5498657347 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_2byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_2byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_2byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_2byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3_1byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3_1byte.c
index 0e8616bd4f..b7827466f6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3_1byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3_1byte.c
@@ -1,95 +1,95 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Especially with small structures which may fit in one
- register. Depending on the ABI.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030902 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_3_1byte {
- unsigned char a;
- unsigned char b;
- unsigned char c;
-} cls_struct_3_1byte;
-
-cls_struct_3_1byte cls_struct_3_1byte_fn(struct cls_struct_3_1byte a1,
- struct cls_struct_3_1byte a2)
-{
- struct cls_struct_3_1byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c,
- a2.a, a2.b, a2.c,
- result.a, result.b, result.c);
-
- return result;
-}
-
-static void
-cls_struct_3_1byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_3_1byte a1, a2;
-
- a1 = *(struct cls_struct_3_1byte*)(args[0]);
- a2 = *(struct cls_struct_3_1byte*)(args[1]);
-
- *(cls_struct_3_1byte*)resp = cls_struct_3_1byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_3_1byte g_dbl = { 12, 13, 14 };
- struct cls_struct_3_1byte f_dbl = { 178, 179, 180 };
- struct cls_struct_3_1byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_3_1byte_fn), &res_dbl, args_dbl);
- /* { dg-output "12 13 14 178 179 180: 190 192 194" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 190 192 194" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3_1byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_3_1byte(*)(cls_struct_3_1byte, cls_struct_3_1byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 13 14 178 179 180: 190 192 194" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 190 192 194" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Especially with small structures which may fit in one
+ register. Depending on the ABI.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030902 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_3_1byte {
+ unsigned char a;
+ unsigned char b;
+ unsigned char c;
+} cls_struct_3_1byte;
+
+cls_struct_3_1byte cls_struct_3_1byte_fn(struct cls_struct_3_1byte a1,
+ struct cls_struct_3_1byte a2)
+{
+ struct cls_struct_3_1byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c,
+ a2.a, a2.b, a2.c,
+ result.a, result.b, result.c);
+
+ return result;
+}
+
+static void
+cls_struct_3_1byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_3_1byte a1, a2;
+
+ a1 = *(struct cls_struct_3_1byte*)(args[0]);
+ a2 = *(struct cls_struct_3_1byte*)(args[1]);
+
+ *(cls_struct_3_1byte*)resp = cls_struct_3_1byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_3_1byte g_dbl = { 12, 13, 14 };
+ struct cls_struct_3_1byte f_dbl = { 178, 179, 180 };
+ struct cls_struct_3_1byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_3_1byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 13 14 178 179 180: 190 192 194" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 190 192 194" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3_1byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_3_1byte(*)(cls_struct_3_1byte, cls_struct_3_1byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 13 14 178 179 180: 190 192 194" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 190 192 194" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3_1byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3_1byte/ya.make
index 25b7a6986f..20f6378b64 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3_1byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3_1byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_3_1byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_3_1byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte1.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte1.c
index 5ffebc3e57..a02c463af9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte1.c
@@ -1,90 +1,90 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Especially with small structures which may fit in one
- register. Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_3byte {
- unsigned short a;
- unsigned char b;
-} cls_struct_3byte;
-
-cls_struct_3byte cls_struct_3byte_fn(struct cls_struct_3byte a1,
- struct cls_struct_3byte a2)
-{
- struct cls_struct_3byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
-
- printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b);
-
- return result;
-}
-
-static void
-cls_struct_3byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_3byte a1, a2;
-
- a1 = *(struct cls_struct_3byte*)(args[0]);
- a2 = *(struct cls_struct_3byte*)(args[1]);
-
- *(cls_struct_3byte*)resp = cls_struct_3byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_3byte g_dbl = { 12, 119 };
- struct cls_struct_3byte f_dbl = { 1, 15 };
- struct cls_struct_3byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_ushort;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_3byte_fn), &res_dbl, args_dbl);
- /* { dg-output "12 119 1 15: 13 134" } */
- printf("res: %d %d\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 13 134" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_3byte(*)(cls_struct_3byte, cls_struct_3byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 119 1 15: 13 134" } */
- printf("res: %d %d\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 13 134" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Especially with small structures which may fit in one
+ register. Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_3byte {
+ unsigned short a;
+ unsigned char b;
+} cls_struct_3byte;
+
+cls_struct_3byte cls_struct_3byte_fn(struct cls_struct_3byte a1,
+ struct cls_struct_3byte a2)
+{
+ struct cls_struct_3byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+
+ printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b);
+
+ return result;
+}
+
+static void
+cls_struct_3byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_3byte a1, a2;
+
+ a1 = *(struct cls_struct_3byte*)(args[0]);
+ a2 = *(struct cls_struct_3byte*)(args[1]);
+
+ *(cls_struct_3byte*)resp = cls_struct_3byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_3byte g_dbl = { 12, 119 };
+ struct cls_struct_3byte f_dbl = { 1, 15 };
+ struct cls_struct_3byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_ushort;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_3byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 119 1 15: 13 134" } */
+ printf("res: %d %d\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 13 134" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_3byte(*)(cls_struct_3byte, cls_struct_3byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 119 1 15: 13 134" } */
+ printf("res: %d %d\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 13 134" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte1/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte1/ya.make
index bce6d2483e..58c5e0810c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_3byte1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_3byte1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte2.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte2.c
index a0de7b4adc..c7251cead6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte2.c
@@ -1,90 +1,90 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Especially with small structures which may fit in one
- register. Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_3byte_1 {
- unsigned char a;
- unsigned short b;
-} cls_struct_3byte_1;
-
-cls_struct_3byte_1 cls_struct_3byte_fn1(struct cls_struct_3byte_1 a1,
- struct cls_struct_3byte_1 a2)
-{
- struct cls_struct_3byte_1 result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
-
- printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b);
-
- return result;
-}
-
-static void
-cls_struct_3byte_gn1(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_3byte_1 a1, a2;
-
- a1 = *(struct cls_struct_3byte_1*)(args[0]);
- a2 = *(struct cls_struct_3byte_1*)(args[1]);
-
- *(cls_struct_3byte_1*)resp = cls_struct_3byte_fn1(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_3byte_1 g_dbl = { 15, 125 };
- struct cls_struct_3byte_1 f_dbl = { 9, 19 };
- struct cls_struct_3byte_1 res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_ushort;
- cls_struct_fields[2] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_3byte_fn1), &res_dbl, args_dbl);
- /* { dg-output "15 125 9 19: 24 144" } */
- printf("res: %d %d\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 24 144" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3byte_gn1, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_3byte_1(*)(cls_struct_3byte_1, cls_struct_3byte_1))(code))(g_dbl, f_dbl);
- /* { dg-output "\n15 125 9 19: 24 144" } */
- printf("res: %d %d\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 24 144" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Especially with small structures which may fit in one
+ register. Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_3byte_1 {
+ unsigned char a;
+ unsigned short b;
+} cls_struct_3byte_1;
+
+cls_struct_3byte_1 cls_struct_3byte_fn1(struct cls_struct_3byte_1 a1,
+ struct cls_struct_3byte_1 a2)
+{
+ struct cls_struct_3byte_1 result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+
+ printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b);
+
+ return result;
+}
+
+static void
+cls_struct_3byte_gn1(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_3byte_1 a1, a2;
+
+ a1 = *(struct cls_struct_3byte_1*)(args[0]);
+ a2 = *(struct cls_struct_3byte_1*)(args[1]);
+
+ *(cls_struct_3byte_1*)resp = cls_struct_3byte_fn1(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_3byte_1 g_dbl = { 15, 125 };
+ struct cls_struct_3byte_1 f_dbl = { 9, 19 };
+ struct cls_struct_3byte_1 res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_ushort;
+ cls_struct_fields[2] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_3byte_fn1), &res_dbl, args_dbl);
+ /* { dg-output "15 125 9 19: 24 144" } */
+ printf("res: %d %d\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 24 144" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3byte_gn1, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_3byte_1(*)(cls_struct_3byte_1, cls_struct_3byte_1))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n15 125 9 19: 24 144" } */
+ printf("res: %d %d\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 24 144" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte2/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte2/ya.make
index 7fc9ae7d35..55bd1281af 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3byte2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_3byte2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_3byte2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3float.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3float.c
index 6889203faa..48888f8405 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3float.c
@@ -1,95 +1,95 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations:>none.
- PR: none.
- Originator: <compnerd@compnerd.org> 20171026 */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-typedef struct cls_struct_3float {
- float f;
- float g;
- float h;
-} cls_struct_3float;
-
-cls_struct_3float cls_struct_3float_fn(struct cls_struct_3float a1,
- struct cls_struct_3float a2)
-{
- struct cls_struct_3float result;
-
- result.f = a1.f + a2.f;
- result.g = a1.g + a2.g;
- result.h = a1.h + a2.h;
-
- printf("%g %g %g %g %g %g: %g %g %g\n", a1.f, a1.g, a1.h,
- a2.f, a2.g, a2.h, result.f, result.g, result.h);
-
- return result;
-}
-
-static void
-cls_struct_3float_gn(ffi_cif *cif __UNUSED__, void* resp, void **args,
- void* userdata __UNUSED__)
-{
- struct cls_struct_3float a1, a2;
-
- a1 = *(struct cls_struct_3float*)(args[0]);
- a2 = *(struct cls_struct_3float*)(args[1]);
-
- *(cls_struct_3float*)resp = cls_struct_3float_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void *args_dbl[3];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[3];
-
- struct cls_struct_3float g_dbl = { 1.0f, 2.0f, 3.0f };
- struct cls_struct_3float f_dbl = { 1.0f, 2.0f, 3.0f };
- struct cls_struct_3float res_dbl;
-
- cls_struct_fields[0] = &ffi_type_float;
- cls_struct_fields[1] = &ffi_type_float;
- cls_struct_fields[2] = &ffi_type_float;
- cls_struct_fields[3] = NULL;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_3float_fn), &res_dbl, args_dbl);
- /* { dg-output "1 2 3 1 2 3: 2 4 6" } */
- printf("res: %g %g %g\n", res_dbl.f, res_dbl.g, res_dbl.h);
- /* { dg-output "\nres: 2 4 6" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3float_gn, NULL, code) ==
- FFI_OK);
-
- res_dbl = ((cls_struct_3float(*)(cls_struct_3float,
- cls_struct_3float))(code))(g_dbl, f_dbl);
- /* { dg-output "\n1 2 3 1 2 3: 2 4 6" } */
- printf("res: %g %g %g\n", res_dbl.f, res_dbl.g, res_dbl.h);
- /* { dg-output "\nres: 2 4 6" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations:>none.
+ PR: none.
+ Originator: <compnerd@compnerd.org> 20171026 */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+typedef struct cls_struct_3float {
+ float f;
+ float g;
+ float h;
+} cls_struct_3float;
+
+cls_struct_3float cls_struct_3float_fn(struct cls_struct_3float a1,
+ struct cls_struct_3float a2)
+{
+ struct cls_struct_3float result;
+
+ result.f = a1.f + a2.f;
+ result.g = a1.g + a2.g;
+ result.h = a1.h + a2.h;
+
+ printf("%g %g %g %g %g %g: %g %g %g\n", a1.f, a1.g, a1.h,
+ a2.f, a2.g, a2.h, result.f, result.g, result.h);
+
+ return result;
+}
+
+static void
+cls_struct_3float_gn(ffi_cif *cif __UNUSED__, void* resp, void **args,
+ void* userdata __UNUSED__)
+{
+ struct cls_struct_3float a1, a2;
+
+ a1 = *(struct cls_struct_3float*)(args[0]);
+ a2 = *(struct cls_struct_3float*)(args[1]);
+
+ *(cls_struct_3float*)resp = cls_struct_3float_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void *args_dbl[3];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[3];
+
+ struct cls_struct_3float g_dbl = { 1.0f, 2.0f, 3.0f };
+ struct cls_struct_3float f_dbl = { 1.0f, 2.0f, 3.0f };
+ struct cls_struct_3float res_dbl;
+
+ cls_struct_fields[0] = &ffi_type_float;
+ cls_struct_fields[1] = &ffi_type_float;
+ cls_struct_fields[2] = &ffi_type_float;
+ cls_struct_fields[3] = NULL;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_3float_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 2 3 1 2 3: 2 4 6" } */
+ printf("res: %g %g %g\n", res_dbl.f, res_dbl.g, res_dbl.h);
+ /* { dg-output "\nres: 2 4 6" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3float_gn, NULL, code) ==
+ FFI_OK);
+
+ res_dbl = ((cls_struct_3float(*)(cls_struct_3float,
+ cls_struct_3float))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n1 2 3 1 2 3: 2 4 6" } */
+ printf("res: %g %g %g\n", res_dbl.f, res_dbl.g, res_dbl.h);
+ /* { dg-output "\nres: 2 4 6" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3float/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3float/ya.make
index e73ca87806..d8fe8ba3ec 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_3float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_3float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_3float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_3float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_4_1byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_4_1byte.c
index 639d875d86..2d6d8b622c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_4_1byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_4_1byte.c
@@ -1,98 +1,98 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Especially with small structures which may fit in one
- register. Depending on the ABI.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030902 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_4_1byte {
- unsigned char a;
- unsigned char b;
- unsigned char c;
- unsigned char d;
-} cls_struct_4_1byte;
-
-cls_struct_4_1byte cls_struct_4_1byte_fn(struct cls_struct_4_1byte a1,
- struct cls_struct_4_1byte a2)
-{
- struct cls_struct_4_1byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
- result.d = a1.d + a2.d;
-
- printf("%d %d %d %d %d %d %d %d: %d %d %d %d\n", a1.a, a1.b, a1.c, a1.d,
- a2.a, a2.b, a2.c, a2.d,
- result.a, result.b, result.c, result.d);
-
- return result;
-}
-
-static void
-cls_struct_4_1byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_4_1byte a1, a2;
-
- a1 = *(struct cls_struct_4_1byte*)(args[0]);
- a2 = *(struct cls_struct_4_1byte*)(args[1]);
-
- *(cls_struct_4_1byte*)resp = cls_struct_4_1byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[5];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_4_1byte g_dbl = { 12, 13, 14, 15 };
- struct cls_struct_4_1byte f_dbl = { 178, 179, 180, 181 };
- struct cls_struct_4_1byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = &ffi_type_uchar;
- cls_struct_fields[4] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_4_1byte_fn), &res_dbl, args_dbl);
- /* { dg-output "12 13 14 15 178 179 180 181: 190 192 194 196" } */
- printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
- /* { dg-output "\nres: 190 192 194 196" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_4_1byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_4_1byte(*)(cls_struct_4_1byte, cls_struct_4_1byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 13 14 15 178 179 180 181: 190 192 194 196" } */
- printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
- /* { dg-output "\nres: 190 192 194 196" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Especially with small structures which may fit in one
+ register. Depending on the ABI.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030902 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_4_1byte {
+ unsigned char a;
+ unsigned char b;
+ unsigned char c;
+ unsigned char d;
+} cls_struct_4_1byte;
+
+cls_struct_4_1byte cls_struct_4_1byte_fn(struct cls_struct_4_1byte a1,
+ struct cls_struct_4_1byte a2)
+{
+ struct cls_struct_4_1byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+ result.d = a1.d + a2.d;
+
+ printf("%d %d %d %d %d %d %d %d: %d %d %d %d\n", a1.a, a1.b, a1.c, a1.d,
+ a2.a, a2.b, a2.c, a2.d,
+ result.a, result.b, result.c, result.d);
+
+ return result;
+}
+
+static void
+cls_struct_4_1byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_4_1byte a1, a2;
+
+ a1 = *(struct cls_struct_4_1byte*)(args[0]);
+ a2 = *(struct cls_struct_4_1byte*)(args[1]);
+
+ *(cls_struct_4_1byte*)resp = cls_struct_4_1byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[5];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_4_1byte g_dbl = { 12, 13, 14, 15 };
+ struct cls_struct_4_1byte f_dbl = { 178, 179, 180, 181 };
+ struct cls_struct_4_1byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = &ffi_type_uchar;
+ cls_struct_fields[4] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_4_1byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 13 14 15 178 179 180 181: 190 192 194 196" } */
+ printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
+ /* { dg-output "\nres: 190 192 194 196" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_4_1byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_4_1byte(*)(cls_struct_4_1byte, cls_struct_4_1byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 13 14 15 178 179 180 181: 190 192 194 196" } */
+ printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
+ /* { dg-output "\nres: 190 192 194 196" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_4_1byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_4_1byte/ya.make
index 8bfaa23eee..e362b7c58e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_4_1byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_4_1byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_4_1byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_4_1byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_4byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_4byte.c
index f21ab62419..4ac378776b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_4byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_4byte.c
@@ -1,90 +1,90 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-typedef struct cls_struct_4byte {
- unsigned short a;
- unsigned short b;
-} cls_struct_4byte;
-
-cls_struct_4byte cls_struct_4byte_fn(struct cls_struct_4byte a1,
- struct cls_struct_4byte a2)
-{
- struct cls_struct_4byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
-
- printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b);
-
- return result;
-}
-
-static void
-cls_struct_4byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_4byte a1, a2;
-
- a1 = *(struct cls_struct_4byte*)(args[0]);
- a2 = *(struct cls_struct_4byte*)(args[1]);
-
- *(cls_struct_4byte*)resp = cls_struct_4byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_4byte g_dbl = { 127, 120 };
- struct cls_struct_4byte f_dbl = { 12, 128 };
- struct cls_struct_4byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_ushort;
- cls_struct_fields[1] = &ffi_type_ushort;
- cls_struct_fields[2] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_4byte_fn), &res_dbl, args_dbl);
- /* { dg-output "127 120 12 128: 139 248" } */
- printf("res: %d %d\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 139 248" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_4byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_4byte(*)(cls_struct_4byte, cls_struct_4byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n127 120 12 128: 139 248" } */
- printf("res: %d %d\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 139 248" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+typedef struct cls_struct_4byte {
+ unsigned short a;
+ unsigned short b;
+} cls_struct_4byte;
+
+cls_struct_4byte cls_struct_4byte_fn(struct cls_struct_4byte a1,
+ struct cls_struct_4byte a2)
+{
+ struct cls_struct_4byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+
+ printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b);
+
+ return result;
+}
+
+static void
+cls_struct_4byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_4byte a1, a2;
+
+ a1 = *(struct cls_struct_4byte*)(args[0]);
+ a2 = *(struct cls_struct_4byte*)(args[1]);
+
+ *(cls_struct_4byte*)resp = cls_struct_4byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_4byte g_dbl = { 127, 120 };
+ struct cls_struct_4byte f_dbl = { 12, 128 };
+ struct cls_struct_4byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_ushort;
+ cls_struct_fields[1] = &ffi_type_ushort;
+ cls_struct_fields[2] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_4byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "127 120 12 128: 139 248" } */
+ printf("res: %d %d\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 139 248" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_4byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_4byte(*)(cls_struct_4byte, cls_struct_4byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n127 120 12 128: 139 248" } */
+ printf("res: %d %d\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 139 248" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_4byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_4byte/ya.make
index f98346225d..e301b297d8 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_4byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_4byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_4byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_4byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_5_1_byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_5_1_byte.c
index d5d201ec63..ad9d51c248 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_5_1_byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_5_1_byte.c
@@ -1,109 +1,109 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20050708 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_5byte {
- unsigned char a;
- unsigned char b;
- unsigned char c;
- unsigned char d;
- unsigned char e;
-} cls_struct_5byte;
-
-cls_struct_5byte cls_struct_5byte_fn(struct cls_struct_5byte a1,
- struct cls_struct_5byte a2)
-{
- struct cls_struct_5byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
- result.d = a1.d + a2.d;
- result.e = a1.e + a2.e;
-
- printf("%d %d %d %d %d %d %d %d %d %d: %d %d %d %d %d\n",
- a1.a, a1.b, a1.c, a1.d, a1.e,
- a2.a, a2.b, a2.c, a2.d, a2.e,
- result.a, result.b, result.c, result.d, result.e);
-
- return result;
-}
-
-static void
-cls_struct_5byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_5byte a1, a2;
-
- a1 = *(struct cls_struct_5byte*)(args[0]);
- a2 = *(struct cls_struct_5byte*)(args[1]);
-
- *(cls_struct_5byte*)resp = cls_struct_5byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[6];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_5byte g_dbl = { 127, 120, 1, 3, 4 };
- struct cls_struct_5byte f_dbl = { 12, 128, 9, 3, 4 };
- struct cls_struct_5byte res_dbl = { 0, 0, 0, 0, 0 };
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = &ffi_type_uchar;
- cls_struct_fields[4] = &ffi_type_uchar;
- cls_struct_fields[5] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_5byte_fn), &res_dbl, args_dbl);
- /* { dg-output "127 120 1 3 4 12 128 9 3 4: 139 248 10 6 8" } */
- printf("res: %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e);
- /* { dg-output "\nres: 139 248 10 6 8" } */
-
- res_dbl.a = 0;
- res_dbl.b = 0;
- res_dbl.c = 0;
- res_dbl.d = 0;
- res_dbl.e = 0;
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_5byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_5byte(*)(cls_struct_5byte, cls_struct_5byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n127 120 1 3 4 12 128 9 3 4: 139 248 10 6 8" } */
- printf("res: %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e);
- /* { dg-output "\nres: 139 248 10 6 8" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20050708 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_5byte {
+ unsigned char a;
+ unsigned char b;
+ unsigned char c;
+ unsigned char d;
+ unsigned char e;
+} cls_struct_5byte;
+
+cls_struct_5byte cls_struct_5byte_fn(struct cls_struct_5byte a1,
+ struct cls_struct_5byte a2)
+{
+ struct cls_struct_5byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+ result.d = a1.d + a2.d;
+ result.e = a1.e + a2.e;
+
+ printf("%d %d %d %d %d %d %d %d %d %d: %d %d %d %d %d\n",
+ a1.a, a1.b, a1.c, a1.d, a1.e,
+ a2.a, a2.b, a2.c, a2.d, a2.e,
+ result.a, result.b, result.c, result.d, result.e);
+
+ return result;
+}
+
+static void
+cls_struct_5byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_5byte a1, a2;
+
+ a1 = *(struct cls_struct_5byte*)(args[0]);
+ a2 = *(struct cls_struct_5byte*)(args[1]);
+
+ *(cls_struct_5byte*)resp = cls_struct_5byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[6];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_5byte g_dbl = { 127, 120, 1, 3, 4 };
+ struct cls_struct_5byte f_dbl = { 12, 128, 9, 3, 4 };
+ struct cls_struct_5byte res_dbl = { 0, 0, 0, 0, 0 };
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = &ffi_type_uchar;
+ cls_struct_fields[4] = &ffi_type_uchar;
+ cls_struct_fields[5] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_5byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "127 120 1 3 4 12 128 9 3 4: 139 248 10 6 8" } */
+ printf("res: %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e);
+ /* { dg-output "\nres: 139 248 10 6 8" } */
+
+ res_dbl.a = 0;
+ res_dbl.b = 0;
+ res_dbl.c = 0;
+ res_dbl.d = 0;
+ res_dbl.e = 0;
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_5byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_5byte(*)(cls_struct_5byte, cls_struct_5byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n127 120 1 3 4 12 128 9 3 4: 139 248 10 6 8" } */
+ printf("res: %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e);
+ /* { dg-output "\nres: 139 248 10 6 8" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_5_1_byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_5_1_byte/ya.make
index cb117e5149..7079c46472 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_5_1_byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_5_1_byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_5_1_byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_5_1_byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_5byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_5byte.c
index d54cb6213e..4e0c0003c0 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_5byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_5byte.c
@@ -1,98 +1,98 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_5byte {
- unsigned short a;
- unsigned short b;
- unsigned char c;
-} cls_struct_5byte;
-
-cls_struct_5byte cls_struct_5byte_fn(struct cls_struct_5byte a1,
- struct cls_struct_5byte a2)
-{
- struct cls_struct_5byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c,
- a2.a, a2.b, a2.c,
- result.a, result.b, result.c);
-
- return result;
-}
-
-static void
-cls_struct_5byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_5byte a1, a2;
-
- a1 = *(struct cls_struct_5byte*)(args[0]);
- a2 = *(struct cls_struct_5byte*)(args[1]);
-
- *(cls_struct_5byte*)resp = cls_struct_5byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_5byte g_dbl = { 127, 120, 1 };
- struct cls_struct_5byte f_dbl = { 12, 128, 9 };
- struct cls_struct_5byte res_dbl = { 0, 0, 0 };
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_ushort;
- cls_struct_fields[1] = &ffi_type_ushort;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_5byte_fn), &res_dbl, args_dbl);
- /* { dg-output "127 120 1 12 128 9: 139 248 10" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 139 248 10" } */
-
- res_dbl.a = 0;
- res_dbl.b = 0;
- res_dbl.c = 0;
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_5byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_5byte(*)(cls_struct_5byte, cls_struct_5byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n127 120 1 12 128 9: 139 248 10" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 139 248 10" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_5byte {
+ unsigned short a;
+ unsigned short b;
+ unsigned char c;
+} cls_struct_5byte;
+
+cls_struct_5byte cls_struct_5byte_fn(struct cls_struct_5byte a1,
+ struct cls_struct_5byte a2)
+{
+ struct cls_struct_5byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c,
+ a2.a, a2.b, a2.c,
+ result.a, result.b, result.c);
+
+ return result;
+}
+
+static void
+cls_struct_5byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_5byte a1, a2;
+
+ a1 = *(struct cls_struct_5byte*)(args[0]);
+ a2 = *(struct cls_struct_5byte*)(args[1]);
+
+ *(cls_struct_5byte*)resp = cls_struct_5byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_5byte g_dbl = { 127, 120, 1 };
+ struct cls_struct_5byte f_dbl = { 12, 128, 9 };
+ struct cls_struct_5byte res_dbl = { 0, 0, 0 };
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_ushort;
+ cls_struct_fields[1] = &ffi_type_ushort;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_5byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "127 120 1 12 128 9: 139 248 10" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 139 248 10" } */
+
+ res_dbl.a = 0;
+ res_dbl.b = 0;
+ res_dbl.c = 0;
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_5byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_5byte(*)(cls_struct_5byte, cls_struct_5byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n127 120 1 12 128 9: 139 248 10" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 139 248 10" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_5byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_5byte/ya.make
index aa40c94aae..d61db00fae 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_5byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_5byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_5byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_5byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_64byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_64byte.c
index 078511fb05..a55edc2c7b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_64byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_64byte.c
@@ -1,124 +1,124 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check bigger struct which overlaps
- the gp and fp register count on Darwin/AIX/ppc64.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_64byte {
- double a;
- double b;
- double c;
- double d;
- double e;
- double f;
- double g;
- double h;
-} cls_struct_64byte;
-
-cls_struct_64byte cls_struct_64byte_fn(struct cls_struct_64byte b0,
- struct cls_struct_64byte b1,
- struct cls_struct_64byte b2,
- struct cls_struct_64byte b3)
-{
- struct cls_struct_64byte result;
-
- result.a = b0.a + b1.a + b2.a + b3.a;
- result.b = b0.b + b1.b + b2.b + b3.b;
- result.c = b0.c + b1.c + b2.c + b3.c;
- result.d = b0.d + b1.d + b2.d + b3.d;
- result.e = b0.e + b1.e + b2.e + b3.e;
- result.f = b0.f + b1.f + b2.f + b3.f;
- result.g = b0.g + b1.g + b2.g + b3.g;
- result.h = b0.h + b1.h + b2.h + b3.h;
-
- printf("%g %g %g %g %g %g %g %g\n", result.a, result.b, result.c,
- result.d, result.e, result.f, result.g, result.h);
-
- return result;
-}
-
-static void
-cls_struct_64byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct cls_struct_64byte b0, b1, b2, b3;
-
- b0 = *(struct cls_struct_64byte*)(args[0]);
- b1 = *(struct cls_struct_64byte*)(args[1]);
- b2 = *(struct cls_struct_64byte*)(args[2]);
- b3 = *(struct cls_struct_64byte*)(args[3]);
-
- *(cls_struct_64byte*)resp = cls_struct_64byte_fn(b0, b1, b2, b3);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[9];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_64byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0 };
- struct cls_struct_64byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0 };
- struct cls_struct_64byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0 };
- struct cls_struct_64byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0 };
- struct cls_struct_64byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_double;
- cls_struct_fields[2] = &ffi_type_double;
- cls_struct_fields[3] = &ffi_type_double;
- cls_struct_fields[4] = &ffi_type_double;
- cls_struct_fields[5] = &ffi_type_double;
- cls_struct_fields[6] = &ffi_type_double;
- cls_struct_fields[7] = &ffi_type_double;
- cls_struct_fields[8] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = &cls_struct_type;
- dbl_arg_types[3] = &cls_struct_type;
- dbl_arg_types[4] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = &h_dbl;
- args_dbl[4] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_64byte_fn), &res_dbl, args_dbl);
- /* { dg-output "22 15 17 25 6 13 19 18" } */
- printf("res: %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h);
- /* { dg-output "\nres: 22 15 17 25 6 13 19 18" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_64byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_64byte(*)(cls_struct_64byte,
- cls_struct_64byte,
- cls_struct_64byte,
- cls_struct_64byte))
- (code))(e_dbl, f_dbl, g_dbl, h_dbl);
- /* { dg-output "\n22 15 17 25 6 13 19 18" } */
- printf("res: %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h);
- /* { dg-output "\nres: 22 15 17 25 6 13 19 18" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check bigger struct which overlaps
+ the gp and fp register count on Darwin/AIX/ppc64.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_64byte {
+ double a;
+ double b;
+ double c;
+ double d;
+ double e;
+ double f;
+ double g;
+ double h;
+} cls_struct_64byte;
+
+cls_struct_64byte cls_struct_64byte_fn(struct cls_struct_64byte b0,
+ struct cls_struct_64byte b1,
+ struct cls_struct_64byte b2,
+ struct cls_struct_64byte b3)
+{
+ struct cls_struct_64byte result;
+
+ result.a = b0.a + b1.a + b2.a + b3.a;
+ result.b = b0.b + b1.b + b2.b + b3.b;
+ result.c = b0.c + b1.c + b2.c + b3.c;
+ result.d = b0.d + b1.d + b2.d + b3.d;
+ result.e = b0.e + b1.e + b2.e + b3.e;
+ result.f = b0.f + b1.f + b2.f + b3.f;
+ result.g = b0.g + b1.g + b2.g + b3.g;
+ result.h = b0.h + b1.h + b2.h + b3.h;
+
+ printf("%g %g %g %g %g %g %g %g\n", result.a, result.b, result.c,
+ result.d, result.e, result.f, result.g, result.h);
+
+ return result;
+}
+
+static void
+cls_struct_64byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct cls_struct_64byte b0, b1, b2, b3;
+
+ b0 = *(struct cls_struct_64byte*)(args[0]);
+ b1 = *(struct cls_struct_64byte*)(args[1]);
+ b2 = *(struct cls_struct_64byte*)(args[2]);
+ b3 = *(struct cls_struct_64byte*)(args[3]);
+
+ *(cls_struct_64byte*)resp = cls_struct_64byte_fn(b0, b1, b2, b3);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[9];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_64byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0 };
+ struct cls_struct_64byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0 };
+ struct cls_struct_64byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0 };
+ struct cls_struct_64byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0 };
+ struct cls_struct_64byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_double;
+ cls_struct_fields[2] = &ffi_type_double;
+ cls_struct_fields[3] = &ffi_type_double;
+ cls_struct_fields[4] = &ffi_type_double;
+ cls_struct_fields[5] = &ffi_type_double;
+ cls_struct_fields[6] = &ffi_type_double;
+ cls_struct_fields[7] = &ffi_type_double;
+ cls_struct_fields[8] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = &cls_struct_type;
+ dbl_arg_types[3] = &cls_struct_type;
+ dbl_arg_types[4] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = &h_dbl;
+ args_dbl[4] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_64byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "22 15 17 25 6 13 19 18" } */
+ printf("res: %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h);
+ /* { dg-output "\nres: 22 15 17 25 6 13 19 18" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_64byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_64byte(*)(cls_struct_64byte,
+ cls_struct_64byte,
+ cls_struct_64byte,
+ cls_struct_64byte))
+ (code))(e_dbl, f_dbl, g_dbl, h_dbl);
+ /* { dg-output "\n22 15 17 25 6 13 19 18" } */
+ printf("res: %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h);
+ /* { dg-output "\nres: 22 15 17 25 6 13 19 18" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_64byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_64byte/ya.make
index d1a61404af..7d157845bd 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_64byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_64byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_64byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_64byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_6_1_byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_6_1_byte.c
index 0334bdd169..b4dcdba472 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_6_1_byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_6_1_byte.c
@@ -1,113 +1,113 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20050708 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_6byte {
- unsigned char a;
- unsigned char b;
- unsigned char c;
- unsigned char d;
- unsigned char e;
- unsigned char f;
-} cls_struct_6byte;
-
-cls_struct_6byte cls_struct_6byte_fn(struct cls_struct_6byte a1,
- struct cls_struct_6byte a2)
-{
- struct cls_struct_6byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
- result.d = a1.d + a2.d;
- result.e = a1.e + a2.e;
- result.f = a1.f + a2.f;
-
- printf("%d %d %d %d %d %d %d %d %d %d %d %d: %d %d %d %d %d %d\n",
- a1.a, a1.b, a1.c, a1.d, a1.e, a1.f,
- a2.a, a2.b, a2.c, a2.d, a2.e, a2.f,
- result.a, result.b, result.c, result.d, result.e, result.f);
-
- return result;
-}
-
-static void
-cls_struct_6byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_6byte a1, a2;
-
- a1 = *(struct cls_struct_6byte*)(args[0]);
- a2 = *(struct cls_struct_6byte*)(args[1]);
-
- *(cls_struct_6byte*)resp = cls_struct_6byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[7];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_6byte g_dbl = { 127, 120, 1, 3, 4, 5 };
- struct cls_struct_6byte f_dbl = { 12, 128, 9, 3, 4, 5 };
- struct cls_struct_6byte res_dbl = { 0, 0, 0, 0, 0, 0 };
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = &ffi_type_uchar;
- cls_struct_fields[4] = &ffi_type_uchar;
- cls_struct_fields[5] = &ffi_type_uchar;
- cls_struct_fields[6] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_6byte_fn), &res_dbl, args_dbl);
- /* { dg-output "127 120 1 3 4 5 12 128 9 3 4 5: 139 248 10 6 8 10" } */
- printf("res: %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e, res_dbl.f);
- /* { dg-output "\nres: 139 248 10 6 8 10" } */
-
- res_dbl.a = 0;
- res_dbl.b = 0;
- res_dbl.c = 0;
- res_dbl.d = 0;
- res_dbl.e = 0;
- res_dbl.f = 0;
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_6byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_6byte(*)(cls_struct_6byte, cls_struct_6byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n127 120 1 3 4 5 12 128 9 3 4 5: 139 248 10 6 8 10" } */
- printf("res: %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e, res_dbl.f);
- /* { dg-output "\nres: 139 248 10 6 8 10" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20050708 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_6byte {
+ unsigned char a;
+ unsigned char b;
+ unsigned char c;
+ unsigned char d;
+ unsigned char e;
+ unsigned char f;
+} cls_struct_6byte;
+
+cls_struct_6byte cls_struct_6byte_fn(struct cls_struct_6byte a1,
+ struct cls_struct_6byte a2)
+{
+ struct cls_struct_6byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+ result.d = a1.d + a2.d;
+ result.e = a1.e + a2.e;
+ result.f = a1.f + a2.f;
+
+ printf("%d %d %d %d %d %d %d %d %d %d %d %d: %d %d %d %d %d %d\n",
+ a1.a, a1.b, a1.c, a1.d, a1.e, a1.f,
+ a2.a, a2.b, a2.c, a2.d, a2.e, a2.f,
+ result.a, result.b, result.c, result.d, result.e, result.f);
+
+ return result;
+}
+
+static void
+cls_struct_6byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_6byte a1, a2;
+
+ a1 = *(struct cls_struct_6byte*)(args[0]);
+ a2 = *(struct cls_struct_6byte*)(args[1]);
+
+ *(cls_struct_6byte*)resp = cls_struct_6byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[7];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_6byte g_dbl = { 127, 120, 1, 3, 4, 5 };
+ struct cls_struct_6byte f_dbl = { 12, 128, 9, 3, 4, 5 };
+ struct cls_struct_6byte res_dbl = { 0, 0, 0, 0, 0, 0 };
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = &ffi_type_uchar;
+ cls_struct_fields[4] = &ffi_type_uchar;
+ cls_struct_fields[5] = &ffi_type_uchar;
+ cls_struct_fields[6] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_6byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "127 120 1 3 4 5 12 128 9 3 4 5: 139 248 10 6 8 10" } */
+ printf("res: %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e, res_dbl.f);
+ /* { dg-output "\nres: 139 248 10 6 8 10" } */
+
+ res_dbl.a = 0;
+ res_dbl.b = 0;
+ res_dbl.c = 0;
+ res_dbl.d = 0;
+ res_dbl.e = 0;
+ res_dbl.f = 0;
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_6byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_6byte(*)(cls_struct_6byte, cls_struct_6byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n127 120 1 3 4 5 12 128 9 3 4 5: 139 248 10 6 8 10" } */
+ printf("res: %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e, res_dbl.f);
+ /* { dg-output "\nres: 139 248 10 6 8 10" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_6_1_byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_6_1_byte/ya.make
index 2da0a5a511..649bcb8f7f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_6_1_byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_6_1_byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_6_1_byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_6_1_byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_6byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_6byte.c
index 9ad30ffd81..740678017b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_6byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_6byte.c
@@ -1,99 +1,99 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_6byte {
- unsigned short a;
- unsigned short b;
- unsigned char c;
- unsigned char d;
-} cls_struct_6byte;
-
-cls_struct_6byte cls_struct_6byte_fn(struct cls_struct_6byte a1,
- struct cls_struct_6byte a2)
-{
- struct cls_struct_6byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
- result.d = a1.d + a2.d;
-
- printf("%d %d %d %d %d %d %d %d: %d %d %d %d\n", a1.a, a1.b, a1.c, a1.d,
- a2.a, a2.b, a2.c, a2.d,
- result.a, result.b, result.c, result.d);
-
- return result;
-}
-
-static void
-cls_struct_6byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_6byte a1, a2;
-
- a1 = *(struct cls_struct_6byte*)(args[0]);
- a2 = *(struct cls_struct_6byte*)(args[1]);
-
- *(cls_struct_6byte*)resp = cls_struct_6byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[5];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_6byte g_dbl = { 127, 120, 1, 128 };
- struct cls_struct_6byte f_dbl = { 12, 128, 9, 127 };
- struct cls_struct_6byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_ushort;
- cls_struct_fields[1] = &ffi_type_ushort;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = &ffi_type_uchar;
- cls_struct_fields[4] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_6byte_fn), &res_dbl, args_dbl);
- /* { dg-output "127 120 1 128 12 128 9 127: 139 248 10 255" } */
- printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
- /* { dg-output "\nres: 139 248 10 255" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_6byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_6byte(*)(cls_struct_6byte, cls_struct_6byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n127 120 1 128 12 128 9 127: 139 248 10 255" } */
- printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
- /* { dg-output "\nres: 139 248 10 255" } */
-
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_6byte {
+ unsigned short a;
+ unsigned short b;
+ unsigned char c;
+ unsigned char d;
+} cls_struct_6byte;
+
+cls_struct_6byte cls_struct_6byte_fn(struct cls_struct_6byte a1,
+ struct cls_struct_6byte a2)
+{
+ struct cls_struct_6byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+ result.d = a1.d + a2.d;
+
+ printf("%d %d %d %d %d %d %d %d: %d %d %d %d\n", a1.a, a1.b, a1.c, a1.d,
+ a2.a, a2.b, a2.c, a2.d,
+ result.a, result.b, result.c, result.d);
+
+ return result;
+}
+
+static void
+cls_struct_6byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_6byte a1, a2;
+
+ a1 = *(struct cls_struct_6byte*)(args[0]);
+ a2 = *(struct cls_struct_6byte*)(args[1]);
+
+ *(cls_struct_6byte*)resp = cls_struct_6byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[5];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_6byte g_dbl = { 127, 120, 1, 128 };
+ struct cls_struct_6byte f_dbl = { 12, 128, 9, 127 };
+ struct cls_struct_6byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_ushort;
+ cls_struct_fields[1] = &ffi_type_ushort;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = &ffi_type_uchar;
+ cls_struct_fields[4] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_6byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "127 120 1 128 12 128 9 127: 139 248 10 255" } */
+ printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
+ /* { dg-output "\nres: 139 248 10 255" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_6byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_6byte(*)(cls_struct_6byte, cls_struct_6byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n127 120 1 128 12 128 9 127: 139 248 10 255" } */
+ printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
+ /* { dg-output "\nres: 139 248 10 255" } */
+
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_6byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_6byte/ya.make
index c24bb23bb7..cfc5422227 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_6byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_6byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_6byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_6byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_7_1_byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_7_1_byte.c
index eb180b7b64..14a7e96f9d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_7_1_byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_7_1_byte.c
@@ -1,117 +1,117 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20050708 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_7byte {
- unsigned char a;
- unsigned char b;
- unsigned char c;
- unsigned char d;
- unsigned char e;
- unsigned char f;
- unsigned char g;
-} cls_struct_7byte;
-
-cls_struct_7byte cls_struct_7byte_fn(struct cls_struct_7byte a1,
- struct cls_struct_7byte a2)
-{
- struct cls_struct_7byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
- result.d = a1.d + a2.d;
- result.e = a1.e + a2.e;
- result.f = a1.f + a2.f;
- result.g = a1.g + a2.g;
-
- printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d %d %d %d %d %d %d\n",
- a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g,
- a2.a, a2.b, a2.c, a2.d, a2.e, a2.f, a2.g,
- result.a, result.b, result.c, result.d, result.e, result.f, result.g);
-
- return result;
-}
-
-static void
-cls_struct_7byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_7byte a1, a2;
-
- a1 = *(struct cls_struct_7byte*)(args[0]);
- a2 = *(struct cls_struct_7byte*)(args[1]);
-
- *(cls_struct_7byte*)resp = cls_struct_7byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[8];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_7byte g_dbl = { 127, 120, 1, 3, 4, 5, 6 };
- struct cls_struct_7byte f_dbl = { 12, 128, 9, 3, 4, 5, 6 };
- struct cls_struct_7byte res_dbl = { 0, 0, 0, 0, 0, 0, 0 };
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = &ffi_type_uchar;
- cls_struct_fields[4] = &ffi_type_uchar;
- cls_struct_fields[5] = &ffi_type_uchar;
- cls_struct_fields[6] = &ffi_type_uchar;
- cls_struct_fields[7] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_7byte_fn), &res_dbl, args_dbl);
- /* { dg-output "127 120 1 3 4 5 6 12 128 9 3 4 5 6: 139 248 10 6 8 10 12" } */
- printf("res: %d %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
- /* { dg-output "\nres: 139 248 10 6 8 10 12" } */
-
- res_dbl.a = 0;
- res_dbl.b = 0;
- res_dbl.c = 0;
- res_dbl.d = 0;
- res_dbl.e = 0;
- res_dbl.f = 0;
- res_dbl.g = 0;
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_7byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_7byte(*)(cls_struct_7byte, cls_struct_7byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n127 120 1 3 4 5 6 12 128 9 3 4 5 6: 139 248 10 6 8 10 12" } */
- printf("res: %d %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
- /* { dg-output "\nres: 139 248 10 6 8 10 12" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20050708 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_7byte {
+ unsigned char a;
+ unsigned char b;
+ unsigned char c;
+ unsigned char d;
+ unsigned char e;
+ unsigned char f;
+ unsigned char g;
+} cls_struct_7byte;
+
+cls_struct_7byte cls_struct_7byte_fn(struct cls_struct_7byte a1,
+ struct cls_struct_7byte a2)
+{
+ struct cls_struct_7byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+ result.d = a1.d + a2.d;
+ result.e = a1.e + a2.e;
+ result.f = a1.f + a2.f;
+ result.g = a1.g + a2.g;
+
+ printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d %d %d %d %d %d %d\n",
+ a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g,
+ a2.a, a2.b, a2.c, a2.d, a2.e, a2.f, a2.g,
+ result.a, result.b, result.c, result.d, result.e, result.f, result.g);
+
+ return result;
+}
+
+static void
+cls_struct_7byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_7byte a1, a2;
+
+ a1 = *(struct cls_struct_7byte*)(args[0]);
+ a2 = *(struct cls_struct_7byte*)(args[1]);
+
+ *(cls_struct_7byte*)resp = cls_struct_7byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[8];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_7byte g_dbl = { 127, 120, 1, 3, 4, 5, 6 };
+ struct cls_struct_7byte f_dbl = { 12, 128, 9, 3, 4, 5, 6 };
+ struct cls_struct_7byte res_dbl = { 0, 0, 0, 0, 0, 0, 0 };
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = &ffi_type_uchar;
+ cls_struct_fields[4] = &ffi_type_uchar;
+ cls_struct_fields[5] = &ffi_type_uchar;
+ cls_struct_fields[6] = &ffi_type_uchar;
+ cls_struct_fields[7] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_7byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "127 120 1 3 4 5 6 12 128 9 3 4 5 6: 139 248 10 6 8 10 12" } */
+ printf("res: %d %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
+ /* { dg-output "\nres: 139 248 10 6 8 10 12" } */
+
+ res_dbl.a = 0;
+ res_dbl.b = 0;
+ res_dbl.c = 0;
+ res_dbl.d = 0;
+ res_dbl.e = 0;
+ res_dbl.f = 0;
+ res_dbl.g = 0;
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_7byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_7byte(*)(cls_struct_7byte, cls_struct_7byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n127 120 1 3 4 5 6 12 128 9 3 4 5 6: 139 248 10 6 8 10 12" } */
+ printf("res: %d %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
+ /* { dg-output "\nres: 139 248 10 6 8 10 12" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_7_1_byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_7_1_byte/ya.make
index 77c60a3671..e463e968db 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_7_1_byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_7_1_byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_7_1_byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_7_1_byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_7byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_7byte.c
index 8e590ff4f9..1645cc635f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_7byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_7byte.c
@@ -1,97 +1,97 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_7byte {
- unsigned short a;
- unsigned short b;
- unsigned char c;
- unsigned short d;
-} cls_struct_7byte;
-
-cls_struct_7byte cls_struct_7byte_fn(struct cls_struct_7byte a1,
- struct cls_struct_7byte a2)
-{
- struct cls_struct_7byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
- result.d = a1.d + a2.d;
-
- printf("%d %d %d %d %d %d %d %d: %d %d %d %d\n", a1.a, a1.b, a1.c, a1.d,
- a2.a, a2.b, a2.c, a2.d,
- result.a, result.b, result.c, result.d);
-
- return result;
-}
-
-static void
-cls_struct_7byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_7byte a1, a2;
-
- a1 = *(struct cls_struct_7byte*)(args[0]);
- a2 = *(struct cls_struct_7byte*)(args[1]);
-
- *(cls_struct_7byte*)resp = cls_struct_7byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[5];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_7byte g_dbl = { 127, 120, 1, 254 };
- struct cls_struct_7byte f_dbl = { 12, 128, 9, 255 };
- struct cls_struct_7byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_ushort;
- cls_struct_fields[1] = &ffi_type_ushort;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = &ffi_type_ushort;
- cls_struct_fields[4] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_7byte_fn), &res_dbl, args_dbl);
- /* { dg-output "127 120 1 254 12 128 9 255: 139 248 10 509" } */
- printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
- /* { dg-output "\nres: 139 248 10 509" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_7byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_7byte(*)(cls_struct_7byte, cls_struct_7byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n127 120 1 254 12 128 9 255: 139 248 10 509" } */
- printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
- /* { dg-output "\nres: 139 248 10 509" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_7byte {
+ unsigned short a;
+ unsigned short b;
+ unsigned char c;
+ unsigned short d;
+} cls_struct_7byte;
+
+cls_struct_7byte cls_struct_7byte_fn(struct cls_struct_7byte a1,
+ struct cls_struct_7byte a2)
+{
+ struct cls_struct_7byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+ result.d = a1.d + a2.d;
+
+ printf("%d %d %d %d %d %d %d %d: %d %d %d %d\n", a1.a, a1.b, a1.c, a1.d,
+ a2.a, a2.b, a2.c, a2.d,
+ result.a, result.b, result.c, result.d);
+
+ return result;
+}
+
+static void
+cls_struct_7byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_7byte a1, a2;
+
+ a1 = *(struct cls_struct_7byte*)(args[0]);
+ a2 = *(struct cls_struct_7byte*)(args[1]);
+
+ *(cls_struct_7byte*)resp = cls_struct_7byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[5];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_7byte g_dbl = { 127, 120, 1, 254 };
+ struct cls_struct_7byte f_dbl = { 12, 128, 9, 255 };
+ struct cls_struct_7byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_ushort;
+ cls_struct_fields[1] = &ffi_type_ushort;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = &ffi_type_ushort;
+ cls_struct_fields[4] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_7byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "127 120 1 254 12 128 9 255: 139 248 10 509" } */
+ printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
+ /* { dg-output "\nres: 139 248 10 509" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_7byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_7byte(*)(cls_struct_7byte, cls_struct_7byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n127 120 1 254 12 128 9 255: 139 248 10 509" } */
+ printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d);
+ /* { dg-output "\nres: 139 248 10 509" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_7byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_7byte/ya.make
index f2838c341e..24fe20b031 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_7byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_7byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_7byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_7byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_8byte.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_8byte.c
index fcf08f701b..f6c1ea570a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_8byte.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_8byte.c
@@ -1,88 +1,88 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Check overlapping.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_8byte {
- int a;
- float b;
-} cls_struct_8byte;
-
-cls_struct_8byte cls_struct_8byte_fn(struct cls_struct_8byte a1,
- struct cls_struct_8byte a2)
-{
- struct cls_struct_8byte result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
-
- printf("%d %g %d %g: %d %g\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b);
-
- return result;
-}
-
-static void
-cls_struct_8byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_8byte a1, a2;
-
- a1 = *(struct cls_struct_8byte*)(args[0]);
- a2 = *(struct cls_struct_8byte*)(args[1]);
-
- *(cls_struct_8byte*)resp = cls_struct_8byte_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_8byte g_dbl = { 1, 2.0 };
- struct cls_struct_8byte f_dbl = { 4, 5.0 };
- struct cls_struct_8byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_sint;
- cls_struct_fields[1] = &ffi_type_float;
- cls_struct_fields[2] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_8byte_fn), &res_dbl, args_dbl);
- /* { dg-output "1 2 4 5: 5 7" } */
- printf("res: %d %g\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 5 7" } */
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_8byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_8byte(*)(cls_struct_8byte, cls_struct_8byte))(code))(g_dbl, f_dbl);
- /* { dg-output "\n1 2 4 5: 5 7" } */
- printf("res: %d %g\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 5 7" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Check overlapping.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_8byte {
+ int a;
+ float b;
+} cls_struct_8byte;
+
+cls_struct_8byte cls_struct_8byte_fn(struct cls_struct_8byte a1,
+ struct cls_struct_8byte a2)
+{
+ struct cls_struct_8byte result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+
+ printf("%d %g %d %g: %d %g\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b);
+
+ return result;
+}
+
+static void
+cls_struct_8byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_8byte a1, a2;
+
+ a1 = *(struct cls_struct_8byte*)(args[0]);
+ a2 = *(struct cls_struct_8byte*)(args[1]);
+
+ *(cls_struct_8byte*)resp = cls_struct_8byte_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_8byte g_dbl = { 1, 2.0 };
+ struct cls_struct_8byte f_dbl = { 4, 5.0 };
+ struct cls_struct_8byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_sint;
+ cls_struct_fields[1] = &ffi_type_float;
+ cls_struct_fields[2] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_8byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 2 4 5: 5 7" } */
+ printf("res: %d %g\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 5 7" } */
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_8byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_8byte(*)(cls_struct_8byte, cls_struct_8byte))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n1 2 4 5: 5 7" } */
+ printf("res: %d %g\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 5 7" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_8byte/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_8byte/ya.make
index 73cb4992b1..61cf091810 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_8byte/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_8byte/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_8byte.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_8byte.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte1.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte1.c
index 10e9c556e7..0b8572223c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte1.c
@@ -1,90 +1,90 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Darwin/AIX do double-word
- alignment of the struct if the first element is a double.
- Check that it does not here.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030914 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_9byte {
- int a;
- double b;
-} cls_struct_9byte;
-
-cls_struct_9byte cls_struct_9byte_fn(struct cls_struct_9byte b1,
- struct cls_struct_9byte b2)
-{
- struct cls_struct_9byte result;
-
- result.a = b1.a + b2.a;
- result.b = b1.b + b2.b;
-
- printf("%d %g %d %g: %d %g\n", b1.a, b1.b, b2.a, b2.b,
- result.a, result.b);
-
- return result;
-}
-
-static void cls_struct_9byte_gn(ffi_cif* cif __UNUSED__, void* resp,
- void** args, void* userdata __UNUSED__)
-{
- struct cls_struct_9byte b1, b2;
-
- b1 = *(struct cls_struct_9byte*)(args[0]);
- b2 = *(struct cls_struct_9byte*)(args[1]);
-
- *(cls_struct_9byte*)resp = cls_struct_9byte_fn(b1, b2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[3];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[3];
-
- struct cls_struct_9byte h_dbl = { 7, 8.0};
- struct cls_struct_9byte j_dbl = { 1, 9.0};
- struct cls_struct_9byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_sint;
- cls_struct_fields[1] = &ffi_type_double;
- cls_struct_fields[2] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &h_dbl;
- args_dbl[1] = &j_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_9byte_fn), &res_dbl, args_dbl);
- /* { dg-output "7 8 1 9: 8 17" } */
- printf("res: %d %g\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 8 17" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_9byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_9byte(*)(cls_struct_9byte, cls_struct_9byte))(code))(h_dbl, j_dbl);
- /* { dg-output "\n7 8 1 9: 8 17" } */
- printf("res: %d %g\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 8 17" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Darwin/AIX do double-word
+ alignment of the struct if the first element is a double.
+ Check that it does not here.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030914 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_9byte {
+ int a;
+ double b;
+} cls_struct_9byte;
+
+cls_struct_9byte cls_struct_9byte_fn(struct cls_struct_9byte b1,
+ struct cls_struct_9byte b2)
+{
+ struct cls_struct_9byte result;
+
+ result.a = b1.a + b2.a;
+ result.b = b1.b + b2.b;
+
+ printf("%d %g %d %g: %d %g\n", b1.a, b1.b, b2.a, b2.b,
+ result.a, result.b);
+
+ return result;
+}
+
+static void cls_struct_9byte_gn(ffi_cif* cif __UNUSED__, void* resp,
+ void** args, void* userdata __UNUSED__)
+{
+ struct cls_struct_9byte b1, b2;
+
+ b1 = *(struct cls_struct_9byte*)(args[0]);
+ b2 = *(struct cls_struct_9byte*)(args[1]);
+
+ *(cls_struct_9byte*)resp = cls_struct_9byte_fn(b1, b2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[3];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[3];
+
+ struct cls_struct_9byte h_dbl = { 7, 8.0};
+ struct cls_struct_9byte j_dbl = { 1, 9.0};
+ struct cls_struct_9byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_sint;
+ cls_struct_fields[1] = &ffi_type_double;
+ cls_struct_fields[2] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &h_dbl;
+ args_dbl[1] = &j_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_9byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "7 8 1 9: 8 17" } */
+ printf("res: %d %g\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 8 17" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_9byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_9byte(*)(cls_struct_9byte, cls_struct_9byte))(code))(h_dbl, j_dbl);
+ /* { dg-output "\n7 8 1 9: 8 17" } */
+ printf("res: %d %g\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 8 17" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte1/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte1/ya.make
index ccfc197c69..d36eaef0e7 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_9byte1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_9byte1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte2.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte2.c
index 423600ea03..edf991de73 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte2.c
@@ -1,91 +1,91 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Depending on the ABI. Darwin/AIX do double-word
- alignment of the struct if the first element is a double.
- Check that it does here.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030914 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_9byte {
- double a;
- int b;
-} cls_struct_9byte;
-
-cls_struct_9byte cls_struct_9byte_fn(struct cls_struct_9byte b1,
- struct cls_struct_9byte b2)
-{
- struct cls_struct_9byte result;
-
- result.a = b1.a + b2.a;
- result.b = b1.b + b2.b;
-
- printf("%g %d %g %d: %g %d\n", b1.a, b1.b, b2.a, b2.b,
- result.a, result.b);
-
- return result;
-}
-
-static void cls_struct_9byte_gn(ffi_cif* cif __UNUSED__, void* resp,
- void** args, void* userdata __UNUSED__)
-{
- struct cls_struct_9byte b1, b2;
-
- b1 = *(struct cls_struct_9byte*)(args[0]);
- b2 = *(struct cls_struct_9byte*)(args[1]);
-
- *(cls_struct_9byte*)resp = cls_struct_9byte_fn(b1, b2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[3];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[3];
-
- struct cls_struct_9byte h_dbl = { 7.0, 8};
- struct cls_struct_9byte j_dbl = { 1.0, 9};
- struct cls_struct_9byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_sint;
- cls_struct_fields[2] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &h_dbl;
- args_dbl[1] = &j_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_9byte_fn), &res_dbl, args_dbl);
- /* { dg-output "7 8 1 9: 8 17" } */
- printf("res: %g %d\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 8 17" } */
-
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_9byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_9byte(*)(cls_struct_9byte, cls_struct_9byte))(code))(h_dbl, j_dbl);
- /* { dg-output "\n7 8 1 9: 8 17" } */
- printf("res: %g %d\n", res_dbl.a, res_dbl.b);
- /* { dg-output "\nres: 8 17" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Depending on the ABI. Darwin/AIX do double-word
+ alignment of the struct if the first element is a double.
+ Check that it does here.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030914 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_9byte {
+ double a;
+ int b;
+} cls_struct_9byte;
+
+cls_struct_9byte cls_struct_9byte_fn(struct cls_struct_9byte b1,
+ struct cls_struct_9byte b2)
+{
+ struct cls_struct_9byte result;
+
+ result.a = b1.a + b2.a;
+ result.b = b1.b + b2.b;
+
+ printf("%g %d %g %d: %g %d\n", b1.a, b1.b, b2.a, b2.b,
+ result.a, result.b);
+
+ return result;
+}
+
+static void cls_struct_9byte_gn(ffi_cif* cif __UNUSED__, void* resp,
+ void** args, void* userdata __UNUSED__)
+{
+ struct cls_struct_9byte b1, b2;
+
+ b1 = *(struct cls_struct_9byte*)(args[0]);
+ b2 = *(struct cls_struct_9byte*)(args[1]);
+
+ *(cls_struct_9byte*)resp = cls_struct_9byte_fn(b1, b2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[3];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[3];
+
+ struct cls_struct_9byte h_dbl = { 7.0, 8};
+ struct cls_struct_9byte j_dbl = { 1.0, 9};
+ struct cls_struct_9byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_sint;
+ cls_struct_fields[2] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &h_dbl;
+ args_dbl[1] = &j_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_9byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "7 8 1 9: 8 17" } */
+ printf("res: %g %d\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 8 17" } */
+
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_9byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_9byte(*)(cls_struct_9byte, cls_struct_9byte))(code))(h_dbl, j_dbl);
+ /* { dg-output "\n7 8 1 9: 8 17" } */
+ printf("res: %g %d\n", res_dbl.a, res_dbl.b);
+ /* { dg-output "\nres: 8 17" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte2/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte2/ya.make
index 2b555132d5..5a3bc0edb9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_9byte2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_9byte2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_9byte2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_double.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_double.c
index 33b7d693d9..aad5f3ced6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_double.c
@@ -1,93 +1,93 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of double.
- Limitations: none.
- PR: none.
- Originator: <hos@tamanegi.org> 20031203 */
-
-
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- unsigned char a;
- double b;
- unsigned char c;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
- struct cls_struct_align a2)
-{
- struct cls_struct_align result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %g %d %d %g %d: %d %g %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
-
- return result;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_align g_dbl = { 12, 4951, 127 };
- struct cls_struct_align f_dbl = { 1, 9320, 13 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_double;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of double.
+ Limitations: none.
+ PR: none.
+ Originator: <hos@tamanegi.org> 20031203 */
+
+
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ unsigned char a;
+ double b;
+ unsigned char c;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
+ struct cls_struct_align a2)
+{
+ struct cls_struct_align result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %g %d %d %g %d: %d %g %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
+
+ return result;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_align g_dbl = { 12, 4951, 127 };
+ struct cls_struct_align f_dbl = { 1, 9320, 13 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_double;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_double/ya.make
index 517c75c677..6de4ac5c85 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_float.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_float.c
index 1dd743853d..37e085529e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_float.c
@@ -1,91 +1,91 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of float.
- Limitations: none.
- PR: none.
- Originator: <hos@tamanegi.org> 20031203 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- unsigned char a;
- float b;
- unsigned char c;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
- struct cls_struct_align a2)
-{
- struct cls_struct_align result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %g %d %d %g %d: %d %g %d\n", a1.a, (double)a1.b, a1.c, a2.a, (double)a2.b, a2.c, result.a, (double)result.b, result.c);
-
- return result;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_align g_dbl = { 12, 4951, 127 };
- struct cls_struct_align f_dbl = { 1, 9320, 13 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_float;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of float.
+ Limitations: none.
+ PR: none.
+ Originator: <hos@tamanegi.org> 20031203 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ unsigned char a;
+ float b;
+ unsigned char c;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
+ struct cls_struct_align a2)
+{
+ struct cls_struct_align result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %g %d %d %g %d: %d %g %d\n", a1.a, (double)a1.b, a1.c, a2.a, (double)a2.b, a2.c, result.a, (double)result.b, result.c);
+
+ return result;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_align g_dbl = { 12, 4951, 127 };
+ struct cls_struct_align f_dbl = { 1, 9320, 13 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_float;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_float/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_float/ya.make
index a3edbf31a1..967b36ddc9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble.c
index e07e15a858..b3322d8615 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble.c
@@ -1,92 +1,92 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of long double.
- Limitations: none.
- PR: none.
- Originator: <hos@tamanegi.org> 20031203 */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- unsigned char a;
- long double b;
- unsigned char c;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
- struct cls_struct_align a2)
-{
- struct cls_struct_align result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %g %d %d %g %d: %d %g %d\n", a1.a, (double)a1.b, a1.c, a2.a, (double)a2.b, a2.c, result.a, (double)result.b, result.c);
-
- return result;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_align g_dbl = { 12, 4951, 127 };
- struct cls_struct_align f_dbl = { 1, 9320, 13 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_longdouble;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of long double.
+ Limitations: none.
+ PR: none.
+ Originator: <hos@tamanegi.org> 20031203 */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ unsigned char a;
+ long double b;
+ unsigned char c;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
+ struct cls_struct_align a2)
+{
+ struct cls_struct_align result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %g %d %d %g %d: %d %g %d\n", a1.a, (double)a1.b, a1.c, a2.a, (double)a2.b, a2.c, result.a, (double)result.b, result.c);
+
+ return result;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_align g_dbl = { 12, 4951, 127 };
+ struct cls_struct_align f_dbl = { 1, 9320, 13 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_longdouble;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble/ya.make
index 651c37f562..844482ac16 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_longdouble.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_longdouble.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c
index e160970412..cc1c43b8ca 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c
@@ -1,132 +1,132 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of long double.
- Limitations: none.
- PR: none.
- Originator: <hos@tamanegi.org> 20031203 */
-
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
-/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */
-
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- long double a;
- long double b;
- long double c;
- long double d;
- long double e;
- long double f;
- long double g;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(
- cls_struct_align a1,
- cls_struct_align a2)
-{
- struct cls_struct_align r;
-
- r.a = a1.a + a2.a;
- r.b = a1.b + a2.b;
- r.c = a1.c + a2.c;
- r.d = a1.d + a2.d;
- r.e = a1.e + a2.e;
- r.f = a1.f + a2.f;
- r.g = a1.g + a2.g;
-
- printf("%Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg: "
- "%Lg %Lg %Lg %Lg %Lg %Lg %Lg\n",
- a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g,
- a2.a, a2.b, a2.c, a2.d, a2.e, a2.f, a2.g,
- r.a, r.b, r.c, r.d, r.e, r.f, r.g);
-
- return r;
-}
-
-cls_struct_align cls_struct_align_fn2(
- cls_struct_align a1)
-{
- struct cls_struct_align r;
-
- r.a = a1.a + 1;
- r.b = a1.b + 1;
- r.c = a1.c + 1;
- r.d = a1.d + 1;
- r.e = a1.e + 1;
- r.f = a1.f + 1;
- r.g = a1.g + 1;
-
- printf("%Lg %Lg %Lg %Lg %Lg %Lg %Lg: "
- "%Lg %Lg %Lg %Lg %Lg %Lg %Lg\n",
- a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g,
- r.a, r.b, r.c, r.d, r.e, r.f, r.g);
-
- return r;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[8];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[3];
-
- struct cls_struct_align g_dbl = { 1, 2, 3, 4, 5, 6, 7 };
- struct cls_struct_align f_dbl = { 8, 9, 10, 11, 12, 13, 14 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_longdouble;
- cls_struct_fields[1] = &ffi_type_longdouble;
- cls_struct_fields[2] = &ffi_type_longdouble;
- cls_struct_fields[3] = &ffi_type_longdouble;
- cls_struct_fields[4] = &ffi_type_longdouble;
- cls_struct_fields[5] = &ffi_type_longdouble;
- cls_struct_fields[6] = &ffi_type_longdouble;
- cls_struct_fields[7] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */
- printf("res: %Lg %Lg %Lg %Lg %Lg %Lg %Lg\n", res_dbl.a, res_dbl.b,
- res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
- /* { dg-output "\nres: 9 11 13 15 17 19 21" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */
- printf("res: %Lg %Lg %Lg %Lg %Lg %Lg %Lg\n", res_dbl.a, res_dbl.b,
- res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
- /* { dg-output "\nres: 9 11 13 15 17 19 21" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of long double.
+ Limitations: none.
+ PR: none.
+ Originator: <hos@tamanegi.org> 20031203 */
+
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
+/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */
+
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ long double a;
+ long double b;
+ long double c;
+ long double d;
+ long double e;
+ long double f;
+ long double g;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(
+ cls_struct_align a1,
+ cls_struct_align a2)
+{
+ struct cls_struct_align r;
+
+ r.a = a1.a + a2.a;
+ r.b = a1.b + a2.b;
+ r.c = a1.c + a2.c;
+ r.d = a1.d + a2.d;
+ r.e = a1.e + a2.e;
+ r.f = a1.f + a2.f;
+ r.g = a1.g + a2.g;
+
+ printf("%Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg: "
+ "%Lg %Lg %Lg %Lg %Lg %Lg %Lg\n",
+ a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g,
+ a2.a, a2.b, a2.c, a2.d, a2.e, a2.f, a2.g,
+ r.a, r.b, r.c, r.d, r.e, r.f, r.g);
+
+ return r;
+}
+
+cls_struct_align cls_struct_align_fn2(
+ cls_struct_align a1)
+{
+ struct cls_struct_align r;
+
+ r.a = a1.a + 1;
+ r.b = a1.b + 1;
+ r.c = a1.c + 1;
+ r.d = a1.d + 1;
+ r.e = a1.e + 1;
+ r.f = a1.f + 1;
+ r.g = a1.g + 1;
+
+ printf("%Lg %Lg %Lg %Lg %Lg %Lg %Lg: "
+ "%Lg %Lg %Lg %Lg %Lg %Lg %Lg\n",
+ a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g,
+ r.a, r.b, r.c, r.d, r.e, r.f, r.g);
+
+ return r;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[8];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[3];
+
+ struct cls_struct_align g_dbl = { 1, 2, 3, 4, 5, 6, 7 };
+ struct cls_struct_align f_dbl = { 8, 9, 10, 11, 12, 13, 14 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_longdouble;
+ cls_struct_fields[1] = &ffi_type_longdouble;
+ cls_struct_fields[2] = &ffi_type_longdouble;
+ cls_struct_fields[3] = &ffi_type_longdouble;
+ cls_struct_fields[4] = &ffi_type_longdouble;
+ cls_struct_fields[5] = &ffi_type_longdouble;
+ cls_struct_fields[6] = &ffi_type_longdouble;
+ cls_struct_fields[7] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */
+ printf("res: %Lg %Lg %Lg %Lg %Lg %Lg %Lg\n", res_dbl.a, res_dbl.b,
+ res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
+ /* { dg-output "\nres: 9 11 13 15 17 19 21" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */
+ printf("res: %Lg %Lg %Lg %Lg %Lg %Lg %Lg\n", res_dbl.a, res_dbl.b,
+ res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
+ /* { dg-output "\nres: 9 11 13 15 17 19 21" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split/ya.make
index 184ef8fa55..8c805489e1 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_longdouble_split.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_longdouble_split.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c
index 822d51bb9e..5d3bec0719 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c
@@ -1,115 +1,115 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of long double.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/18/2007
-*/
-
-/* { dg-do run { xfail strongarm*-*-* } } */
-/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */
-
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- long double a;
- long double b;
- long double c;
- long double d;
- long double e;
- double f;
- long double g;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(
- cls_struct_align a1,
- cls_struct_align a2)
-{
- struct cls_struct_align r;
-
- r.a = a1.a + a2.a;
- r.b = a1.b + a2.b;
- r.c = a1.c + a2.c;
- r.d = a1.d + a2.d;
- r.e = a1.e + a2.e;
- r.f = a1.f + a2.f;
- r.g = a1.g + a2.g;
-
- printf("%Lg %Lg %Lg %Lg %Lg %g %Lg %Lg %Lg %Lg %Lg %Lg %g %Lg: "
- "%Lg %Lg %Lg %Lg %Lg %g %Lg\n",
- a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g,
- a2.a, a2.b, a2.c, a2.d, a2.e, a2.f, a2.g,
- r.a, r.b, r.c, r.d, r.e, r.f, r.g);
-
- return r;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[8];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[3];
-
- struct cls_struct_align g_dbl = { 1, 2, 3, 4, 5, 6, 7 };
- struct cls_struct_align f_dbl = { 8, 9, 10, 11, 12, 13, 14 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_longdouble;
- cls_struct_fields[1] = &ffi_type_longdouble;
- cls_struct_fields[2] = &ffi_type_longdouble;
- cls_struct_fields[3] = &ffi_type_longdouble;
- cls_struct_fields[4] = &ffi_type_longdouble;
- cls_struct_fields[5] = &ffi_type_double;
- cls_struct_fields[6] = &ffi_type_longdouble;
- cls_struct_fields[7] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */
- printf("res: %Lg %Lg %Lg %Lg %Lg %g %Lg\n", res_dbl.a, res_dbl.b,
- res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
- /* { dg-output "\nres: 9 11 13 15 17 19 21" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */
- printf("res: %Lg %Lg %Lg %Lg %Lg %g %Lg\n", res_dbl.a, res_dbl.b,
- res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
- /* { dg-output "\nres: 9 11 13 15 17 19 21" } */
-
- exit(0);
-}
-
-
-
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of long double.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/18/2007
+*/
+
+/* { dg-do run { xfail strongarm*-*-* } } */
+/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */
+
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ long double a;
+ long double b;
+ long double c;
+ long double d;
+ long double e;
+ double f;
+ long double g;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(
+ cls_struct_align a1,
+ cls_struct_align a2)
+{
+ struct cls_struct_align r;
+
+ r.a = a1.a + a2.a;
+ r.b = a1.b + a2.b;
+ r.c = a1.c + a2.c;
+ r.d = a1.d + a2.d;
+ r.e = a1.e + a2.e;
+ r.f = a1.f + a2.f;
+ r.g = a1.g + a2.g;
+
+ printf("%Lg %Lg %Lg %Lg %Lg %g %Lg %Lg %Lg %Lg %Lg %Lg %g %Lg: "
+ "%Lg %Lg %Lg %Lg %Lg %g %Lg\n",
+ a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g,
+ a2.a, a2.b, a2.c, a2.d, a2.e, a2.f, a2.g,
+ r.a, r.b, r.c, r.d, r.e, r.f, r.g);
+
+ return r;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[8];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[3];
+
+ struct cls_struct_align g_dbl = { 1, 2, 3, 4, 5, 6, 7 };
+ struct cls_struct_align f_dbl = { 8, 9, 10, 11, 12, 13, 14 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_longdouble;
+ cls_struct_fields[1] = &ffi_type_longdouble;
+ cls_struct_fields[2] = &ffi_type_longdouble;
+ cls_struct_fields[3] = &ffi_type_longdouble;
+ cls_struct_fields[4] = &ffi_type_longdouble;
+ cls_struct_fields[5] = &ffi_type_double;
+ cls_struct_fields[6] = &ffi_type_longdouble;
+ cls_struct_fields[7] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */
+ printf("res: %Lg %Lg %Lg %Lg %Lg %g %Lg\n", res_dbl.a, res_dbl.b,
+ res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
+ /* { dg-output "\nres: 9 11 13 15 17 19 21" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */
+ printf("res: %Lg %Lg %Lg %Lg %Lg %g %Lg\n", res_dbl.a, res_dbl.b,
+ res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g);
+ /* { dg-output "\nres: 9 11 13 15 17 19 21" } */
+
+ exit(0);
+}
+
+
+
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split2/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split2/ya.make
index c01a6e7028..5e40f1ac5e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_longdouble_split2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_longdouble_split2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_longdouble_split2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_pointer.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_pointer.c
index d2ffeb789f..8fbf36a5c1 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_pointer.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_pointer.c
@@ -1,95 +1,95 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of pointer.
- Limitations: none.
- PR: none.
- Originator: <hos@tamanegi.org> 20031203 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- unsigned char a;
- void *b;
- unsigned char c;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
- struct cls_struct_align a2)
-{
- struct cls_struct_align result;
-
- result.a = a1.a + a2.a;
- result.b = (void *)((uintptr_t)a1.b + (uintptr_t)a2.b);
- result.c = a1.c + a2.c;
-
- printf("%d %" PRIuPTR " %d %d %" PRIuPTR " %d: %d %" PRIuPTR " %d\n",
- a1.a, (uintptr_t)a1.b, a1.c,
- a2.a, (uintptr_t)a2.b, a2.c,
- result.a, (uintptr_t)result.b,
- result.c);
-
- return result;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_align g_dbl = { 12, (void *)4951, 127 };
- struct cls_struct_align f_dbl = { 1, (void *)9320, 13 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_pointer;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %" PRIuPTR " %d\n", res_dbl.a, (uintptr_t)res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %" PRIuPTR " %d\n", res_dbl.a, (uintptr_t)res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of pointer.
+ Limitations: none.
+ PR: none.
+ Originator: <hos@tamanegi.org> 20031203 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ unsigned char a;
+ void *b;
+ unsigned char c;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
+ struct cls_struct_align a2)
+{
+ struct cls_struct_align result;
+
+ result.a = a1.a + a2.a;
+ result.b = (void *)((uintptr_t)a1.b + (uintptr_t)a2.b);
+ result.c = a1.c + a2.c;
+
+ printf("%d %" PRIuPTR " %d %d %" PRIuPTR " %d: %d %" PRIuPTR " %d\n",
+ a1.a, (uintptr_t)a1.b, a1.c,
+ a2.a, (uintptr_t)a2.b, a2.c,
+ result.a, (uintptr_t)result.b,
+ result.c);
+
+ return result;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_align g_dbl = { 12, (void *)4951, 127 };
+ struct cls_struct_align f_dbl = { 1, (void *)9320, 13 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_pointer;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %" PRIuPTR " %d\n", res_dbl.a, (uintptr_t)res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %" PRIuPTR " %d\n", res_dbl.a, (uintptr_t)res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_pointer/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_pointer/ya.make
index 9431893677..79562122b0 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_pointer/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_pointer/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_pointer.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_pointer.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint16.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint16.c
index 3c2f19930f..039b874732 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint16.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint16.c
@@ -1,91 +1,91 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of sint16.
- Limitations: none.
- PR: none.
- Originator: <hos@tamanegi.org> 20031203 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- unsigned char a;
- signed short b;
- unsigned char c;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
- struct cls_struct_align a2)
-{
- struct cls_struct_align result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
-
- return result;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_align g_dbl = { 12, 4951, 127 };
- struct cls_struct_align f_dbl = { 1, 9320, 13 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_sshort;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of sint16.
+ Limitations: none.
+ PR: none.
+ Originator: <hos@tamanegi.org> 20031203 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ unsigned char a;
+ signed short b;
+ unsigned char c;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
+ struct cls_struct_align a2)
+{
+ struct cls_struct_align result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
+
+ return result;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_align g_dbl = { 12, 4951, 127 };
+ struct cls_struct_align f_dbl = { 1, 9320, 13 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_sshort;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint16/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint16/ya.make
index f7a08681c9..964d524014 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint16/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint16/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_sint16.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_sint16.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint32.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint32.c
index 47eb44b6ea..c96c6d136d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint32.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint32.c
@@ -1,91 +1,91 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of sint32.
- Limitations: none.
- PR: none.
- Originator: <hos@tamanegi.org> 20031203 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- unsigned char a;
- signed int b;
- unsigned char c;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
- struct cls_struct_align a2)
-{
- struct cls_struct_align result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
-
- return result;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_align g_dbl = { 12, 4951, 127 };
- struct cls_struct_align f_dbl = { 1, 9320, 13 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_sint;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of sint32.
+ Limitations: none.
+ PR: none.
+ Originator: <hos@tamanegi.org> 20031203 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ unsigned char a;
+ signed int b;
+ unsigned char c;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
+ struct cls_struct_align a2)
+{
+ struct cls_struct_align result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
+
+ return result;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_align g_dbl = { 12, 4951, 127 };
+ struct cls_struct_align f_dbl = { 1, 9320, 13 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_sint;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint32/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint32/ya.make
index 0a1f5be07f..b7379245f6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint32/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint32/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_sint32.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_sint32.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint64.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint64.c
index cabc2a8731..9aa7bdddff 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint64.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint64.c
@@ -1,92 +1,92 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of sint64.
- Limitations: none.
- PR: none.
- Originator: <hos@tamanegi.org> 20031203 */
-
-/* { dg-do run } */
-/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- unsigned char a;
- signed long long b;
- unsigned char c;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
- struct cls_struct_align a2)
-{
- struct cls_struct_align result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %" PRIdLL " %d %d %" PRIdLL " %d: %d %" PRIdLL " %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
-
- return result;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_align g_dbl = { 12, 4951, 127 };
- struct cls_struct_align f_dbl = { 1, 9320, 13 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_sint64;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of sint64.
+ Limitations: none.
+ PR: none.
+ Originator: <hos@tamanegi.org> 20031203 */
+
+/* { dg-do run } */
+/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ unsigned char a;
+ signed long long b;
+ unsigned char c;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
+ struct cls_struct_align a2)
+{
+ struct cls_struct_align result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %" PRIdLL " %d %d %" PRIdLL " %d: %d %" PRIdLL " %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
+
+ return result;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_align g_dbl = { 12, 4951, 127 };
+ struct cls_struct_align f_dbl = { 1, 9320, 13 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_sint64;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint64/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint64/ya.make
index 36e6e6dec7..35248e167f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint64/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_sint64/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_sint64.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_sint64.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint16.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint16.c
index 93d95fd07c..97620b79d1 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint16.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint16.c
@@ -1,91 +1,91 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of uint16.
- Limitations: none.
- PR: none.
- Originator: <hos@tamanegi.org> 20031203 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- unsigned char a;
- unsigned short b;
- unsigned char c;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
- struct cls_struct_align a2)
-{
- struct cls_struct_align result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
-
- return result;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_align g_dbl = { 12, 4951, 127 };
- struct cls_struct_align f_dbl = { 1, 9320, 13 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_ushort;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of uint16.
+ Limitations: none.
+ PR: none.
+ Originator: <hos@tamanegi.org> 20031203 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ unsigned char a;
+ unsigned short b;
+ unsigned char c;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
+ struct cls_struct_align a2)
+{
+ struct cls_struct_align result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
+
+ return result;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_align g_dbl = { 12, 4951, 127 };
+ struct cls_struct_align f_dbl = { 1, 9320, 13 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_ushort;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint16/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint16/ya.make
index a692713122..e0da652591 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint16/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint16/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_uint16.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_uint16.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint32.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint32.c
index aab42e1d2f..5766fadf0d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint32.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint32.c
@@ -1,91 +1,91 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of uint32.
- Limitations: none.
- PR: none.
- Originator: <hos@tamanegi.org> 20031203 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- unsigned char a;
- unsigned int b;
- unsigned char c;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
- struct cls_struct_align a2)
-{
- struct cls_struct_align result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
-
- return result;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_align g_dbl = { 12, 4951, 127 };
- struct cls_struct_align f_dbl = { 1, 9320, 13 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_uint;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of uint32.
+ Limitations: none.
+ PR: none.
+ Originator: <hos@tamanegi.org> 20031203 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ unsigned char a;
+ unsigned int b;
+ unsigned char c;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
+ struct cls_struct_align a2)
+{
+ struct cls_struct_align result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
+
+ return result;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_align g_dbl = { 12, 4951, 127 };
+ struct cls_struct_align f_dbl = { 1, 9320, 13 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_uint;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint32/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint32/ya.make
index e6ce8d14c4..0087a7b596 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint32/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint32/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_uint32.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_uint32.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint64.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint64.c
index aed7157b03..a52cb8939c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint64.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint64.c
@@ -1,93 +1,93 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of uint64.
- Limitations: none.
- PR: none.
- Originator: <hos@tamanegi.org> 20031203 */
-
-
-/* { dg-do run } */
-/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */
-#include "ffitest.h"
-
-typedef struct cls_struct_align {
- unsigned char a;
- unsigned long long b;
- unsigned char c;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
- struct cls_struct_align a2)
-{
- struct cls_struct_align result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %" PRIdLL " %d %d %" PRIdLL " %d: %d %" PRIdLL " %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
-
- return result;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_align g_dbl = { 12, 4951, 127 };
- struct cls_struct_align f_dbl = { 1, 9320, 13 };
- struct cls_struct_align res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_uint64;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &g_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
- /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
- /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
- printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
- /* { dg-output "\nres: 13 14271 140" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of uint64.
+ Limitations: none.
+ PR: none.
+ Originator: <hos@tamanegi.org> 20031203 */
+
+
+/* { dg-do run } */
+/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */
+#include "ffitest.h"
+
+typedef struct cls_struct_align {
+ unsigned char a;
+ unsigned long long b;
+ unsigned char c;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
+ struct cls_struct_align a2)
+{
+ struct cls_struct_align result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %" PRIdLL " %d %d %" PRIdLL " %d: %d %" PRIdLL " %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
+
+ return result;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_align g_dbl = { 12, 4951, 127 };
+ struct cls_struct_align f_dbl = { 1, 9320, 13 };
+ struct cls_struct_align res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_uint64;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &g_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
+ /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
+ /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
+ printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
+ /* { dg-output "\nres: 13 14271 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint64/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint64/ya.make
index 5a000498c1..59b66b1e4b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint64/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_align_uint64/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_align_uint64.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_align_uint64.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_dbls_struct.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_dbls_struct.c
index 6e6a04308d..e451dea51b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_dbls_struct.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_dbls_struct.c
@@ -1,66 +1,66 @@
-/* Area: ffi_call, closure_call
- Purpose: Check double arguments in structs.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/23/2007 */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-typedef struct Dbls {
- double x;
- double y;
-} Dbls;
-
-void
-closure_test_fn(Dbls p)
-{
- printf("%.1f %.1f\n", p.x, p.y);
-}
-
-void
-closure_test_gn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__,
- void** args, void* userdata __UNUSED__)
-{
- closure_test_fn(*(Dbls*)args[0]);
-}
-
-int main(int argc __UNUSED__, char** argv __UNUSED__)
-{
- ffi_cif cif;
-
- void *code;
- ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type* cl_arg_types[1];
-
- ffi_type ts1_type;
- ffi_type* ts1_type_elements[4];
-
- Dbls arg = { 1.0, 2.0 };
-
- ts1_type.size = 0;
- ts1_type.alignment = 0;
- ts1_type.type = FFI_TYPE_STRUCT;
- ts1_type.elements = ts1_type_elements;
-
- ts1_type_elements[0] = &ffi_type_double;
- ts1_type_elements[1] = &ffi_type_double;
- ts1_type_elements[2] = NULL;
-
- cl_arg_types[0] = &ts1_type;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_void, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_gn, NULL, code) == FFI_OK);
-
- ((void*(*)(Dbls))(code))(arg);
- /* { dg-output "1.0 2.0" } */
-
- closure_test_fn(arg);
- /* { dg-output "\n1.0 2.0" } */
-
- return 0;
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check double arguments in structs.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/23/2007 */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+typedef struct Dbls {
+ double x;
+ double y;
+} Dbls;
+
+void
+closure_test_fn(Dbls p)
+{
+ printf("%.1f %.1f\n", p.x, p.y);
+}
+
+void
+closure_test_gn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__,
+ void** args, void* userdata __UNUSED__)
+{
+ closure_test_fn(*(Dbls*)args[0]);
+}
+
+int main(int argc __UNUSED__, char** argv __UNUSED__)
+{
+ ffi_cif cif;
+
+ void *code;
+ ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type* cl_arg_types[1];
+
+ ffi_type ts1_type;
+ ffi_type* ts1_type_elements[4];
+
+ Dbls arg = { 1.0, 2.0 };
+
+ ts1_type.size = 0;
+ ts1_type.alignment = 0;
+ ts1_type.type = FFI_TYPE_STRUCT;
+ ts1_type.elements = ts1_type_elements;
+
+ ts1_type_elements[0] = &ffi_type_double;
+ ts1_type_elements[1] = &ffi_type_double;
+ ts1_type_elements[2] = NULL;
+
+ cl_arg_types[0] = &ts1_type;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_void, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_gn, NULL, code) == FFI_OK);
+
+ ((void*(*)(Dbls))(code))(arg);
+ /* { dg-output "1.0 2.0" } */
+
+ closure_test_fn(arg);
+ /* { dg-output "\n1.0 2.0" } */
+
+ return 0;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_dbls_struct/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_dbls_struct/ya.make
index db2b3b5c0c..2aa4e316fe 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_dbls_struct/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_dbls_struct/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_dbls_struct.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_dbls_struct.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_double.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_double.c
index 644af78dfa..84ad4cb7d9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_double.c
@@ -1,43 +1,43 @@
-/* Area: closure_call
- Purpose: Check return value double.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void cls_ret_double_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
- {
- *(double *)resp = *(double *)args[0];
-
- printf("%f: %f\n",*(double *)args[0],
- *(double *)resp);
- }
-typedef double (*cls_ret_double)(double);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[2];
- double res;
-
- cl_arg_types[0] = &ffi_type_double;
- cl_arg_types[1] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_double, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_double_fn, NULL, code) == FFI_OK);
-
- res = (*((cls_ret_double)code))(21474.789);
- /* { dg-output "21474.789000: 21474.789000" } */
- printf("res: %.6f\n", res);
- /* { dg-output "\nres: 21474.789000" } */
-
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check return value double.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void cls_ret_double_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+ {
+ *(double *)resp = *(double *)args[0];
+
+ printf("%f: %f\n",*(double *)args[0],
+ *(double *)resp);
+ }
+typedef double (*cls_ret_double)(double);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[2];
+ double res;
+
+ cl_arg_types[0] = &ffi_type_double;
+ cl_arg_types[1] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_double, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_double_fn, NULL, code) == FFI_OK);
+
+ res = (*((cls_ret_double)code))(21474.789);
+ /* { dg-output "21474.789000: 21474.789000" } */
+ printf("res: %.6f\n", res);
+ /* { dg-output "\nres: 21474.789000" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_double/ya.make
index 39e64d8b9b..d150f7d354 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_double_va.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_double_va.c
index 6a45477444..e077f92b86 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_double_va.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_double_va.c
@@ -1,61 +1,61 @@
-/* Area: ffi_call, closure_call
- Purpose: Test doubles passed in variable argument lists.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/6/2007 */
-
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
-/* { dg-output "" { xfail avr32*-*-* } } */
-/* { dg-output "" { xfail mips-sgi-irix6* } } PR libffi/46660 */
-
-#include "ffitest.h"
-
-static void
-cls_double_va_fn(ffi_cif* cif __UNUSED__, void* resp,
- void** args, void* userdata __UNUSED__)
-{
- char* format = *(char**)args[0];
- double doubleValue = *(double*)args[1];
-
- *(ffi_arg*)resp = printf(format, doubleValue);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args[3];
- ffi_type* arg_types[3];
-
- char* format = "%.1f\n";
- double doubleArg = 7;
- ffi_arg res = 0;
-
- arg_types[0] = &ffi_type_pointer;
- arg_types[1] = &ffi_type_double;
- arg_types[2] = NULL;
-
- /* This printf call is variadic */
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2, &ffi_type_sint,
- arg_types) == FFI_OK);
-
- args[0] = &format;
- args[1] = &doubleArg;
- args[2] = NULL;
-
- ffi_call(&cif, FFI_FN(printf), &res, args);
- /* { dg-output "7.0" } */
- printf("res: %d\n", (int) res);
- /* { dg-output "\nres: 4" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_double_va_fn, NULL,
- code) == FFI_OK);
-
- res = ((int(*)(char*, ...))(code))(format, doubleArg);
- /* { dg-output "\n7.0" } */
- printf("res: %d\n", (int) res);
- /* { dg-output "\nres: 4" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Test doubles passed in variable argument lists.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/6/2007 */
+
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
+/* { dg-output "" { xfail avr32*-*-* } } */
+/* { dg-output "" { xfail mips-sgi-irix6* } } PR libffi/46660 */
+
+#include "ffitest.h"
+
+static void
+cls_double_va_fn(ffi_cif* cif __UNUSED__, void* resp,
+ void** args, void* userdata __UNUSED__)
+{
+ char* format = *(char**)args[0];
+ double doubleValue = *(double*)args[1];
+
+ *(ffi_arg*)resp = printf(format, doubleValue);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args[3];
+ ffi_type* arg_types[3];
+
+ char* format = "%.1f\n";
+ double doubleArg = 7;
+ ffi_arg res = 0;
+
+ arg_types[0] = &ffi_type_pointer;
+ arg_types[1] = &ffi_type_double;
+ arg_types[2] = NULL;
+
+ /* This printf call is variadic */
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2, &ffi_type_sint,
+ arg_types) == FFI_OK);
+
+ args[0] = &format;
+ args[1] = &doubleArg;
+ args[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(printf), &res, args);
+ /* { dg-output "7.0" } */
+ printf("res: %d\n", (int) res);
+ /* { dg-output "\nres: 4" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_double_va_fn, NULL,
+ code) == FFI_OK);
+
+ res = ((int(*)(char*, ...))(code))(format, doubleArg);
+ /* { dg-output "\n7.0" } */
+ printf("res: %d\n", (int) res);
+ /* { dg-output "\nres: 4" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_double_va/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_double_va/ya.make
index d02d9e56ea..a93d647f2b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_double_va/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_double_va/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_double_va.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_double_va.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_float.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_float.c
index acc27002e8..0090fed906 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_float.c
@@ -1,42 +1,42 @@
-/* Area: closure_call
- Purpose: Check return value float.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void cls_ret_float_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
- {
- *(float *)resp = *(float *)args[0];
-
- printf("%g: %g\n",*(float *)args[0],
- *(float *)resp);
- }
-
-typedef float (*cls_ret_float)(float);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[2];
- float res;
-
- cl_arg_types[0] = &ffi_type_float;
- cl_arg_types[1] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_float, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_float_fn, NULL, code) == FFI_OK);
- res = ((((cls_ret_float)code)(-2122.12)));
- /* { dg-output "\\-2122.12: \\-2122.12" } */
- printf("res: %.6f\n", res);
- /* { dg-output "\nres: \-2122.120117" } */
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check return value float.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void cls_ret_float_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+ {
+ *(float *)resp = *(float *)args[0];
+
+ printf("%g: %g\n",*(float *)args[0],
+ *(float *)resp);
+ }
+
+typedef float (*cls_ret_float)(float);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[2];
+ float res;
+
+ cl_arg_types[0] = &ffi_type_float;
+ cl_arg_types[1] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_float, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_float_fn, NULL, code) == FFI_OK);
+ res = ((((cls_ret_float)code)(-2122.12)));
+ /* { dg-output "\\-2122.12: \\-2122.12" } */
+ printf("res: %.6f\n", res);
+ /* { dg-output "\nres: \-2122.120117" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_float/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_float/ya.make
index 4ce58a83a4..e1a176dc73 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble.c
index 2bb92cd883..d24e72e4ae 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble.c
@@ -1,105 +1,105 @@
-/* Area: ffi_call, closure_call
- Purpose: Check long double arguments.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin */
-
-/* This test is known to PASS on armv7l-unknown-linux-gnueabihf, so I have
- remove the xfail for arm*-*-* below, until we know more. */
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
-/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */
-
-#include "ffitest.h"
-
-long double cls_ldouble_fn(
- long double a1,
- long double a2,
- long double a3,
- long double a4,
- long double a5,
- long double a6,
- long double a7,
- long double a8)
-{
- long double r = a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8;
-
- printf("%Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg: %Lg\n",
- a1, a2, a3, a4, a5, a6, a7, a8, r);
-
- return r;
-}
-
-static void
-cls_ldouble_gn(ffi_cif* cif __UNUSED__, void* resp,
- void** args, void* userdata __UNUSED__)
-{
- long double a1 = *(long double*)args[0];
- long double a2 = *(long double*)args[1];
- long double a3 = *(long double*)args[2];
- long double a4 = *(long double*)args[3];
- long double a5 = *(long double*)args[4];
- long double a6 = *(long double*)args[5];
- long double a7 = *(long double*)args[6];
- long double a8 = *(long double*)args[7];
-
- *(long double*)resp = cls_ldouble_fn(
- a1, a2, a3, a4, a5, a6, a7, a8);
-}
-
-int main(void)
-{
- ffi_cif cif;
- void* code;
- ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args[9];
- ffi_type* arg_types[9];
- long double res = 0;
-
- long double arg1 = 1;
- long double arg2 = 2;
- long double arg3 = 3;
- long double arg4 = 4;
- long double arg5 = 5;
- long double arg6 = 6;
- long double arg7 = 7;
- long double arg8 = 8;
-
- arg_types[0] = &ffi_type_longdouble;
- arg_types[1] = &ffi_type_longdouble;
- arg_types[2] = &ffi_type_longdouble;
- arg_types[3] = &ffi_type_longdouble;
- arg_types[4] = &ffi_type_longdouble;
- arg_types[5] = &ffi_type_longdouble;
- arg_types[6] = &ffi_type_longdouble;
- arg_types[7] = &ffi_type_longdouble;
- arg_types[8] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 8, &ffi_type_longdouble,
- arg_types) == FFI_OK);
-
- args[0] = &arg1;
- args[1] = &arg2;
- args[2] = &arg3;
- args[3] = &arg4;
- args[4] = &arg5;
- args[5] = &arg6;
- args[6] = &arg7;
- args[7] = &arg8;
- args[8] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_ldouble_fn), &res, args);
- /* { dg-output "1 2 3 4 5 6 7 8: 36" } */
- printf("res: %Lg\n", res);
- /* { dg-output "\nres: 36" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ldouble_gn, NULL, code) == FFI_OK);
-
- res = ((long double(*)(long double, long double, long double, long double,
- long double, long double, long double, long double))(code))(arg1, arg2,
- arg3, arg4, arg5, arg6, arg7, arg8);
- /* { dg-output "\n1 2 3 4 5 6 7 8: 36" } */
- printf("res: %Lg\n", res);
- /* { dg-output "\nres: 36" } */
-
- return 0;
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check long double arguments.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin */
+
+/* This test is known to PASS on armv7l-unknown-linux-gnueabihf, so I have
+ remove the xfail for arm*-*-* below, until we know more. */
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
+/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */
+
+#include "ffitest.h"
+
+long double cls_ldouble_fn(
+ long double a1,
+ long double a2,
+ long double a3,
+ long double a4,
+ long double a5,
+ long double a6,
+ long double a7,
+ long double a8)
+{
+ long double r = a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8;
+
+ printf("%Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg: %Lg\n",
+ a1, a2, a3, a4, a5, a6, a7, a8, r);
+
+ return r;
+}
+
+static void
+cls_ldouble_gn(ffi_cif* cif __UNUSED__, void* resp,
+ void** args, void* userdata __UNUSED__)
+{
+ long double a1 = *(long double*)args[0];
+ long double a2 = *(long double*)args[1];
+ long double a3 = *(long double*)args[2];
+ long double a4 = *(long double*)args[3];
+ long double a5 = *(long double*)args[4];
+ long double a6 = *(long double*)args[5];
+ long double a7 = *(long double*)args[6];
+ long double a8 = *(long double*)args[7];
+
+ *(long double*)resp = cls_ldouble_fn(
+ a1, a2, a3, a4, a5, a6, a7, a8);
+}
+
+int main(void)
+{
+ ffi_cif cif;
+ void* code;
+ ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args[9];
+ ffi_type* arg_types[9];
+ long double res = 0;
+
+ long double arg1 = 1;
+ long double arg2 = 2;
+ long double arg3 = 3;
+ long double arg4 = 4;
+ long double arg5 = 5;
+ long double arg6 = 6;
+ long double arg7 = 7;
+ long double arg8 = 8;
+
+ arg_types[0] = &ffi_type_longdouble;
+ arg_types[1] = &ffi_type_longdouble;
+ arg_types[2] = &ffi_type_longdouble;
+ arg_types[3] = &ffi_type_longdouble;
+ arg_types[4] = &ffi_type_longdouble;
+ arg_types[5] = &ffi_type_longdouble;
+ arg_types[6] = &ffi_type_longdouble;
+ arg_types[7] = &ffi_type_longdouble;
+ arg_types[8] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 8, &ffi_type_longdouble,
+ arg_types) == FFI_OK);
+
+ args[0] = &arg1;
+ args[1] = &arg2;
+ args[2] = &arg3;
+ args[3] = &arg4;
+ args[4] = &arg5;
+ args[5] = &arg6;
+ args[6] = &arg7;
+ args[7] = &arg8;
+ args[8] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_ldouble_fn), &res, args);
+ /* { dg-output "1 2 3 4 5 6 7 8: 36" } */
+ printf("res: %Lg\n", res);
+ /* { dg-output "\nres: 36" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ldouble_gn, NULL, code) == FFI_OK);
+
+ res = ((long double(*)(long double, long double, long double, long double,
+ long double, long double, long double, long double))(code))(arg1, arg2,
+ arg3, arg4, arg5, arg6, arg7, arg8);
+ /* { dg-output "\n1 2 3 4 5 6 7 8: 36" } */
+ printf("res: %Lg\n", res);
+ /* { dg-output "\nres: 36" } */
+
+ return 0;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble/ya.make
index 995909653d..e7bb2a3cb6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_longdouble.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_longdouble.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble_va.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble_va.c
index 0ca9020272..39b438b289 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble_va.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble_va.c
@@ -1,61 +1,61 @@
-/* Area: ffi_call, closure_call
- Purpose: Test long doubles passed in variable argument lists.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/6/2007 */
-
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
-/* { dg-output "" { xfail avr32*-*-* x86_64-*-mingw* } } */
-/* { dg-output "" { xfail mips-sgi-irix6* } } PR libffi/46660 */
-
-#include "ffitest.h"
-
-static void
-cls_longdouble_va_fn(ffi_cif* cif __UNUSED__, void* resp,
- void** args, void* userdata __UNUSED__)
-{
- char* format = *(char**)args[0];
- long double ldValue = *(long double*)args[1];
-
- *(ffi_arg*)resp = printf(format, ldValue);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args[3];
- ffi_type* arg_types[3];
-
- char* format = "%.1Lf\n";
- long double ldArg = 7;
- ffi_arg res = 0;
-
- arg_types[0] = &ffi_type_pointer;
- arg_types[1] = &ffi_type_longdouble;
- arg_types[2] = NULL;
-
- /* This printf call is variadic */
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2, &ffi_type_sint,
- arg_types) == FFI_OK);
-
- args[0] = &format;
- args[1] = &ldArg;
- args[2] = NULL;
-
- ffi_call(&cif, FFI_FN(printf), &res, args);
- /* { dg-output "7.0" } */
- printf("res: %d\n", (int) res);
- /* { dg-output "\nres: 4" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_longdouble_va_fn, NULL,
- code) == FFI_OK);
-
- res = ((int(*)(char*, ...))(code))(format, ldArg);
- /* { dg-output "\n7.0" } */
- printf("res: %d\n", (int) res);
- /* { dg-output "\nres: 4" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Test long doubles passed in variable argument lists.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/6/2007 */
+
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
+/* { dg-output "" { xfail avr32*-*-* x86_64-*-mingw* } } */
+/* { dg-output "" { xfail mips-sgi-irix6* } } PR libffi/46660 */
+
+#include "ffitest.h"
+
+static void
+cls_longdouble_va_fn(ffi_cif* cif __UNUSED__, void* resp,
+ void** args, void* userdata __UNUSED__)
+{
+ char* format = *(char**)args[0];
+ long double ldValue = *(long double*)args[1];
+
+ *(ffi_arg*)resp = printf(format, ldValue);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args[3];
+ ffi_type* arg_types[3];
+
+ char* format = "%.1Lf\n";
+ long double ldArg = 7;
+ ffi_arg res = 0;
+
+ arg_types[0] = &ffi_type_pointer;
+ arg_types[1] = &ffi_type_longdouble;
+ arg_types[2] = NULL;
+
+ /* This printf call is variadic */
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2, &ffi_type_sint,
+ arg_types) == FFI_OK);
+
+ args[0] = &format;
+ args[1] = &ldArg;
+ args[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(printf), &res, args);
+ /* { dg-output "7.0" } */
+ printf("res: %d\n", (int) res);
+ /* { dg-output "\nres: 4" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_longdouble_va_fn, NULL,
+ code) == FFI_OK);
+
+ res = ((int(*)(char*, ...))(code))(format, ldArg);
+ /* { dg-output "\n7.0" } */
+ printf("res: %d\n", (int) res);
+ /* { dg-output "\nres: 4" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble_va/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble_va/ya.make
index d6d5526e6e..37f5b08c07 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble_va/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_longdouble_va/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_longdouble_va.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_longdouble_va.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_args.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_args.c
index 4fbc0c3d65..7fd6c8207a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_args.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_args.c
@@ -1,70 +1,70 @@
-/* Area: closure_call
- Purpose: Check closures called with many args of mixed types
- Limitations: none.
- PR: none.
- Originator: <david.schneider@picle.org> */
-
-/* { dg-do run } */
-#include "ffitest.h"
-#include <float.h>
-#include <math.h>
-
-#define NARGS 16
-
-static void cls_ret_double_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- int i;
- double r = 0;
- double t;
- for(i = 0; i < NARGS; i++)
- {
- if(i == 4 || i == 9 || i == 11 || i == 13 || i == 15)
- {
- t = *(long int *)args[i];
- CHECK(t == i+1);
- }
- else
- {
- t = *(double *)args[i];
- CHECK(fabs(t - ((i+1) * 0.1)) < FLT_EPSILON);
- }
- r += t;
- }
- *(double *)resp = r;
-}
-typedef double (*cls_ret_double)(double, double, double, double, long int,
-double, double, double, double, long int, double, long int, double, long int,
-double, long int);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[NARGS];
- double res;
- int i;
- double expected = 64.9;
-
- for(i = 0; i < NARGS; i++)
- {
- if(i == 4 || i == 9 || i == 11 || i == 13 || i == 15)
- cl_arg_types[i] = &ffi_type_slong;
- else
- cl_arg_types[i] = &ffi_type_double;
- }
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NARGS,
- &ffi_type_double, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_double_fn, NULL, code) == FFI_OK);
-
- res = (((cls_ret_double)code))(0.1, 0.2, 0.3, 0.4, 5, 0.6, 0.7, 0.8, 0.9, 10,
- 1.1, 12, 1.3, 14, 1.5, 16);
- if (fabs(res - expected) < FLT_EPSILON)
- exit(0);
- else
- abort();
-}
+/* Area: closure_call
+ Purpose: Check closures called with many args of mixed types
+ Limitations: none.
+ PR: none.
+ Originator: <david.schneider@picle.org> */
+
+/* { dg-do run } */
+#include "ffitest.h"
+#include <float.h>
+#include <math.h>
+
+#define NARGS 16
+
+static void cls_ret_double_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ int i;
+ double r = 0;
+ double t;
+ for(i = 0; i < NARGS; i++)
+ {
+ if(i == 4 || i == 9 || i == 11 || i == 13 || i == 15)
+ {
+ t = *(long int *)args[i];
+ CHECK(t == i+1);
+ }
+ else
+ {
+ t = *(double *)args[i];
+ CHECK(fabs(t - ((i+1) * 0.1)) < FLT_EPSILON);
+ }
+ r += t;
+ }
+ *(double *)resp = r;
+}
+typedef double (*cls_ret_double)(double, double, double, double, long int,
+double, double, double, double, long int, double, long int, double, long int,
+double, long int);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[NARGS];
+ double res;
+ int i;
+ double expected = 64.9;
+
+ for(i = 0; i < NARGS; i++)
+ {
+ if(i == 4 || i == 9 || i == 11 || i == 13 || i == 15)
+ cl_arg_types[i] = &ffi_type_slong;
+ else
+ cl_arg_types[i] = &ffi_type_double;
+ }
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NARGS,
+ &ffi_type_double, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_double_fn, NULL, code) == FFI_OK);
+
+ res = (((cls_ret_double)code))(0.1, 0.2, 0.3, 0.4, 5, 0.6, 0.7, 0.8, 0.9, 10,
+ 1.1, 12, 1.3, 14, 1.5, 16);
+ if (fabs(res - expected) < FLT_EPSILON)
+ exit(0);
+ else
+ abort();
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_args/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_args/ya.make
index 9b0cf363b9..25965bfc44 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_args/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_args/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_many_mixed_args.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_many_mixed_args.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_float_double.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_float_double.c
index d0720d8a01..62b0697ac0 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_float_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_float_double.c
@@ -1,55 +1,55 @@
-/* Area: closure_call
- Purpose: Check register allocation for closure calls with many float and double arguments
- Limitations: none.
- PR: none.
- Originator: <david.schneider@picle.org> */
-
-/* { dg-do run } */
-#include "ffitest.h"
-#include <float.h>
-#include <math.h>
-
-#define NARGS 16
-
-static void cls_mixed_float_double_fn(ffi_cif* cif , void* ret, void** args,
- void* userdata __UNUSED__)
-{
- double r = 0;
- unsigned int i;
- double t;
- for(i=0; i < cif->nargs; i++)
- {
- if(cif->arg_types[i] == &ffi_type_double) {
- t = *(((double**)(args))[i]);
- } else {
- t = *(((float**)(args))[i]);
- }
- r += t;
- }
- *((double*)ret) = r;
-}
-typedef double (*cls_mixed)(double, float, double, double, double, double, double, float, float, double, float, float);
-
-int main (void)
-{
- ffi_cif cif;
- ffi_closure *closure;
- void* code;
- ffi_type *argtypes[12] = {&ffi_type_double, &ffi_type_float, &ffi_type_double,
- &ffi_type_double, &ffi_type_double, &ffi_type_double,
- &ffi_type_double, &ffi_type_float, &ffi_type_float,
- &ffi_type_double, &ffi_type_float, &ffi_type_float};
-
-
- closure = ffi_closure_alloc(sizeof(ffi_closure), (void**)&code);
- if(closure ==NULL)
- abort();
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 12, &ffi_type_double, argtypes) == FFI_OK);
- CHECK(ffi_prep_closure_loc(closure, &cif, cls_mixed_float_double_fn, NULL, code) == FFI_OK);
- double ret = ((cls_mixed)code)(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2);
- ffi_closure_free(closure);
- if(fabs(ret - 7.8) < FLT_EPSILON)
- exit(0);
- else
- abort();
-}
+/* Area: closure_call
+ Purpose: Check register allocation for closure calls with many float and double arguments
+ Limitations: none.
+ PR: none.
+ Originator: <david.schneider@picle.org> */
+
+/* { dg-do run } */
+#include "ffitest.h"
+#include <float.h>
+#include <math.h>
+
+#define NARGS 16
+
+static void cls_mixed_float_double_fn(ffi_cif* cif , void* ret, void** args,
+ void* userdata __UNUSED__)
+{
+ double r = 0;
+ unsigned int i;
+ double t;
+ for(i=0; i < cif->nargs; i++)
+ {
+ if(cif->arg_types[i] == &ffi_type_double) {
+ t = *(((double**)(args))[i]);
+ } else {
+ t = *(((float**)(args))[i]);
+ }
+ r += t;
+ }
+ *((double*)ret) = r;
+}
+typedef double (*cls_mixed)(double, float, double, double, double, double, double, float, float, double, float, float);
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_closure *closure;
+ void* code;
+ ffi_type *argtypes[12] = {&ffi_type_double, &ffi_type_float, &ffi_type_double,
+ &ffi_type_double, &ffi_type_double, &ffi_type_double,
+ &ffi_type_double, &ffi_type_float, &ffi_type_float,
+ &ffi_type_double, &ffi_type_float, &ffi_type_float};
+
+
+ closure = ffi_closure_alloc(sizeof(ffi_closure), (void**)&code);
+ if(closure ==NULL)
+ abort();
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 12, &ffi_type_double, argtypes) == FFI_OK);
+ CHECK(ffi_prep_closure_loc(closure, &cif, cls_mixed_float_double_fn, NULL, code) == FFI_OK);
+ double ret = ((cls_mixed)code)(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2);
+ ffi_closure_free(closure);
+ if(fabs(ret - 7.8) < FLT_EPSILON)
+ exit(0);
+ else
+ abort();
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_float_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_float_double/ya.make
index 08762e4eac..00425d4d8b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_float_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_many_mixed_float_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_many_mixed_float_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_many_mixed_float_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_schar.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_schar.c
index ffc05239f5..71df7b6516 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_schar.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_schar.c
@@ -1,74 +1,74 @@
-/* Area: ffi_call, closure_call
- Purpose: Check passing of multiple signed char values.
- Limitations: none.
- PR: PR13221.
- Originator: <hos@tamanegi.org> 20031129 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-signed char test_func_fn(signed char a1, signed char a2)
-{
- signed char result;
-
- result = a1 + a2;
-
- printf("%d %d: %d\n", a1, a2, result);
-
- return result;
-
-}
-
-static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
- void *data __UNUSED__)
-{
- signed char a1, a2;
-
- a1 = *(signed char *)avals[0];
- a2 = *(signed char *)avals[1];
-
- *(ffi_arg *)rval = test_func_fn(a1, a2);
-
-}
-
-typedef signed char (*test_type)(signed char, signed char);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void * args_dbl[3];
- ffi_type * cl_arg_types[3];
- ffi_arg res_call;
- signed char a, b, res_closure;
-
- a = 2;
- b = 125;
-
- args_dbl[0] = &a;
- args_dbl[1] = &b;
- args_dbl[2] = NULL;
-
- cl_arg_types[0] = &ffi_type_schar;
- cl_arg_types[1] = &ffi_type_schar;
- cl_arg_types[2] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
- &ffi_type_schar, cl_arg_types) == FFI_OK);
-
- ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
- /* { dg-output "2 125: 127" } */
- printf("res: %d\n", (signed char)res_call);
- /* { dg-output "\nres: 127" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
-
- res_closure = (*((test_type)code))(2, 125);
- /* { dg-output "\n2 125: 127" } */
- printf("res: %d\n", res_closure);
- /* { dg-output "\nres: 127" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check passing of multiple signed char values.
+ Limitations: none.
+ PR: PR13221.
+ Originator: <hos@tamanegi.org> 20031129 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+signed char test_func_fn(signed char a1, signed char a2)
+{
+ signed char result;
+
+ result = a1 + a2;
+
+ printf("%d %d: %d\n", a1, a2, result);
+
+ return result;
+
+}
+
+static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
+ void *data __UNUSED__)
+{
+ signed char a1, a2;
+
+ a1 = *(signed char *)avals[0];
+ a2 = *(signed char *)avals[1];
+
+ *(ffi_arg *)rval = test_func_fn(a1, a2);
+
+}
+
+typedef signed char (*test_type)(signed char, signed char);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void * args_dbl[3];
+ ffi_type * cl_arg_types[3];
+ ffi_arg res_call;
+ signed char a, b, res_closure;
+
+ a = 2;
+ b = 125;
+
+ args_dbl[0] = &a;
+ args_dbl[1] = &b;
+ args_dbl[2] = NULL;
+
+ cl_arg_types[0] = &ffi_type_schar;
+ cl_arg_types[1] = &ffi_type_schar;
+ cl_arg_types[2] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
+ &ffi_type_schar, cl_arg_types) == FFI_OK);
+
+ ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
+ /* { dg-output "2 125: 127" } */
+ printf("res: %d\n", (signed char)res_call);
+ /* { dg-output "\nres: 127" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
+
+ res_closure = (*((test_type)code))(2, 125);
+ /* { dg-output "\n2 125: 127" } */
+ printf("res: %d\n", res_closure);
+ /* { dg-output "\nres: 127" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_schar/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_schar/ya.make
index bbcea307c3..d96eace4d5 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_schar/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_schar/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_multi_schar.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_multi_schar.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshort.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshort.c
index 2852f45c08..4c39153266 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshort.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshort.c
@@ -1,74 +1,74 @@
-/* Area: ffi_call, closure_call
- Purpose: Check passing of multiple signed short values.
- Limitations: none.
- PR: PR13221.
- Originator: <andreast@gcc.gnu.org> 20031129 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-signed short test_func_fn(signed short a1, signed short a2)
-{
- signed short result;
-
- result = a1 + a2;
-
- printf("%d %d: %d\n", a1, a2, result);
-
- return result;
-
-}
-
-static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
- void *data __UNUSED__)
-{
- signed short a1, a2;
-
- a1 = *(signed short *)avals[0];
- a2 = *(signed short *)avals[1];
-
- *(ffi_arg *)rval = test_func_fn(a1, a2);
-
-}
-
-typedef signed short (*test_type)(signed short, signed short);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void * args_dbl[3];
- ffi_type * cl_arg_types[3];
- ffi_arg res_call;
- unsigned short a, b, res_closure;
-
- a = 2;
- b = 32765;
-
- args_dbl[0] = &a;
- args_dbl[1] = &b;
- args_dbl[2] = NULL;
-
- cl_arg_types[0] = &ffi_type_sshort;
- cl_arg_types[1] = &ffi_type_sshort;
- cl_arg_types[2] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
- &ffi_type_sshort, cl_arg_types) == FFI_OK);
-
- ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
- /* { dg-output "2 32765: 32767" } */
- printf("res: %d\n", (unsigned short)res_call);
- /* { dg-output "\nres: 32767" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
-
- res_closure = (*((test_type)code))(2, 32765);
- /* { dg-output "\n2 32765: 32767" } */
- printf("res: %d\n", res_closure);
- /* { dg-output "\nres: 32767" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check passing of multiple signed short values.
+ Limitations: none.
+ PR: PR13221.
+ Originator: <andreast@gcc.gnu.org> 20031129 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+signed short test_func_fn(signed short a1, signed short a2)
+{
+ signed short result;
+
+ result = a1 + a2;
+
+ printf("%d %d: %d\n", a1, a2, result);
+
+ return result;
+
+}
+
+static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
+ void *data __UNUSED__)
+{
+ signed short a1, a2;
+
+ a1 = *(signed short *)avals[0];
+ a2 = *(signed short *)avals[1];
+
+ *(ffi_arg *)rval = test_func_fn(a1, a2);
+
+}
+
+typedef signed short (*test_type)(signed short, signed short);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void * args_dbl[3];
+ ffi_type * cl_arg_types[3];
+ ffi_arg res_call;
+ unsigned short a, b, res_closure;
+
+ a = 2;
+ b = 32765;
+
+ args_dbl[0] = &a;
+ args_dbl[1] = &b;
+ args_dbl[2] = NULL;
+
+ cl_arg_types[0] = &ffi_type_sshort;
+ cl_arg_types[1] = &ffi_type_sshort;
+ cl_arg_types[2] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
+ &ffi_type_sshort, cl_arg_types) == FFI_OK);
+
+ ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
+ /* { dg-output "2 32765: 32767" } */
+ printf("res: %d\n", (unsigned short)res_call);
+ /* { dg-output "\nres: 32767" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
+
+ res_closure = (*((test_type)code))(2, 32765);
+ /* { dg-output "\n2 32765: 32767" } */
+ printf("res: %d\n", res_closure);
+ /* { dg-output "\nres: 32767" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshort/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshort/ya.make
index cd42422b66..9cfeb70413 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshort/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshort/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_multi_sshort.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_multi_sshort.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshortchar.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshortchar.c
index 6163796ac0..1c3aeb5a66 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshortchar.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshortchar.c
@@ -1,86 +1,86 @@
-/* Area: ffi_call, closure_call
- Purpose: Check passing of multiple signed short/char values.
- Limitations: none.
- PR: PR13221.
- Originator: <andreast@gcc.gnu.org> 20031129 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-signed short test_func_fn(signed char a1, signed short a2,
- signed char a3, signed short a4)
-{
- signed short result;
-
- result = a1 + a2 + a3 + a4;
-
- printf("%d %d %d %d: %d\n", a1, a2, a3, a4, result);
-
- return result;
-
-}
-
-static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
- void *data __UNUSED__)
-{
- signed char a1, a3;
- signed short a2, a4;
-
- a1 = *(signed char *)avals[0];
- a2 = *(signed short *)avals[1];
- a3 = *(signed char *)avals[2];
- a4 = *(signed short *)avals[3];
-
- *(ffi_arg *)rval = test_func_fn(a1, a2, a3, a4);
-
-}
-
-typedef signed short (*test_type)(signed char, signed short,
- signed char, signed short);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void * args_dbl[5];
- ffi_type * cl_arg_types[5];
- ffi_arg res_call;
- signed char a, c;
- signed short b, d, res_closure;
-
- a = 1;
- b = 32765;
- c = 127;
- d = -128;
-
- args_dbl[0] = &a;
- args_dbl[1] = &b;
- args_dbl[2] = &c;
- args_dbl[3] = &d;
- args_dbl[4] = NULL;
-
- cl_arg_types[0] = &ffi_type_schar;
- cl_arg_types[1] = &ffi_type_sshort;
- cl_arg_types[2] = &ffi_type_schar;
- cl_arg_types[3] = &ffi_type_sshort;
- cl_arg_types[4] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
- &ffi_type_sshort, cl_arg_types) == FFI_OK);
-
- ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
- /* { dg-output "1 32765 127 -128: 32765" } */
- printf("res: %d\n", (signed short)res_call);
- /* { dg-output "\nres: 32765" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
-
- res_closure = (*((test_type)code))(1, 32765, 127, -128);
- /* { dg-output "\n1 32765 127 -128: 32765" } */
- printf("res: %d\n", res_closure);
- /* { dg-output "\nres: 32765" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check passing of multiple signed short/char values.
+ Limitations: none.
+ PR: PR13221.
+ Originator: <andreast@gcc.gnu.org> 20031129 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+signed short test_func_fn(signed char a1, signed short a2,
+ signed char a3, signed short a4)
+{
+ signed short result;
+
+ result = a1 + a2 + a3 + a4;
+
+ printf("%d %d %d %d: %d\n", a1, a2, a3, a4, result);
+
+ return result;
+
+}
+
+static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
+ void *data __UNUSED__)
+{
+ signed char a1, a3;
+ signed short a2, a4;
+
+ a1 = *(signed char *)avals[0];
+ a2 = *(signed short *)avals[1];
+ a3 = *(signed char *)avals[2];
+ a4 = *(signed short *)avals[3];
+
+ *(ffi_arg *)rval = test_func_fn(a1, a2, a3, a4);
+
+}
+
+typedef signed short (*test_type)(signed char, signed short,
+ signed char, signed short);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void * args_dbl[5];
+ ffi_type * cl_arg_types[5];
+ ffi_arg res_call;
+ signed char a, c;
+ signed short b, d, res_closure;
+
+ a = 1;
+ b = 32765;
+ c = 127;
+ d = -128;
+
+ args_dbl[0] = &a;
+ args_dbl[1] = &b;
+ args_dbl[2] = &c;
+ args_dbl[3] = &d;
+ args_dbl[4] = NULL;
+
+ cl_arg_types[0] = &ffi_type_schar;
+ cl_arg_types[1] = &ffi_type_sshort;
+ cl_arg_types[2] = &ffi_type_schar;
+ cl_arg_types[3] = &ffi_type_sshort;
+ cl_arg_types[4] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
+ &ffi_type_sshort, cl_arg_types) == FFI_OK);
+
+ ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
+ /* { dg-output "1 32765 127 -128: 32765" } */
+ printf("res: %d\n", (signed short)res_call);
+ /* { dg-output "\nres: 32765" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
+
+ res_closure = (*((test_type)code))(1, 32765, 127, -128);
+ /* { dg-output "\n1 32765 127 -128: 32765" } */
+ printf("res: %d\n", res_closure);
+ /* { dg-output "\nres: 32765" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshortchar/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshortchar/ya.make
index a530b471aa..5e76efc9c5 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshortchar/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_sshortchar/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_multi_sshortchar.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_multi_sshortchar.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_uchar.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_uchar.c
index 735386effa..009c02c72b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_uchar.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_uchar.c
@@ -1,91 +1,91 @@
-/* Area: ffi_call, closure_call
- Purpose: Check passing of multiple unsigned char values.
- Limitations: none.
- PR: PR13221.
- Originator: <andreast@gcc.gnu.org> 20031129 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-unsigned char test_func_fn(unsigned char a1, unsigned char a2,
- unsigned char a3, unsigned char a4)
-{
- unsigned char result;
-
- result = a1 + a2 + a3 + a4;
-
- printf("%d %d %d %d: %d\n", a1, a2, a3, a4, result);
-
- return result;
-
-}
-
-static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
- void *data __UNUSED__)
-{
- unsigned char a1, a2, a3, a4;
-
- a1 = *(unsigned char *)avals[0];
- a2 = *(unsigned char *)avals[1];
- a3 = *(unsigned char *)avals[2];
- a4 = *(unsigned char *)avals[3];
-
- *(ffi_arg *)rval = test_func_fn(a1, a2, a3, a4);
-
-}
-
-typedef unsigned char (*test_type)(unsigned char, unsigned char,
- unsigned char, unsigned char);
-
-void test_func(ffi_cif *cif __UNUSED__, void *rval __UNUSED__, void **avals,
- void *data __UNUSED__)
-{
- printf("%d %d %d %d\n", *(unsigned char *)avals[0],
- *(unsigned char *)avals[1], *(unsigned char *)avals[2],
- *(unsigned char *)avals[3]);
-}
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void * args_dbl[5];
- ffi_type * cl_arg_types[5];
- ffi_arg res_call;
- unsigned char a, b, c, d, res_closure;
-
- a = 1;
- b = 2;
- c = 127;
- d = 125;
-
- args_dbl[0] = &a;
- args_dbl[1] = &b;
- args_dbl[2] = &c;
- args_dbl[3] = &d;
- args_dbl[4] = NULL;
-
- cl_arg_types[0] = &ffi_type_uchar;
- cl_arg_types[1] = &ffi_type_uchar;
- cl_arg_types[2] = &ffi_type_uchar;
- cl_arg_types[3] = &ffi_type_uchar;
- cl_arg_types[4] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
- &ffi_type_uchar, cl_arg_types) == FFI_OK);
-
- ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
- /* { dg-output "1 2 127 125: 255" } */
- printf("res: %d\n", (unsigned char)res_call);
- /* { dg-output "\nres: 255" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
-
- res_closure = (*((test_type)code))(1, 2, 127, 125);
- /* { dg-output "\n1 2 127 125: 255" } */
- printf("res: %d\n", res_closure);
- /* { dg-output "\nres: 255" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check passing of multiple unsigned char values.
+ Limitations: none.
+ PR: PR13221.
+ Originator: <andreast@gcc.gnu.org> 20031129 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+unsigned char test_func_fn(unsigned char a1, unsigned char a2,
+ unsigned char a3, unsigned char a4)
+{
+ unsigned char result;
+
+ result = a1 + a2 + a3 + a4;
+
+ printf("%d %d %d %d: %d\n", a1, a2, a3, a4, result);
+
+ return result;
+
+}
+
+static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
+ void *data __UNUSED__)
+{
+ unsigned char a1, a2, a3, a4;
+
+ a1 = *(unsigned char *)avals[0];
+ a2 = *(unsigned char *)avals[1];
+ a3 = *(unsigned char *)avals[2];
+ a4 = *(unsigned char *)avals[3];
+
+ *(ffi_arg *)rval = test_func_fn(a1, a2, a3, a4);
+
+}
+
+typedef unsigned char (*test_type)(unsigned char, unsigned char,
+ unsigned char, unsigned char);
+
+void test_func(ffi_cif *cif __UNUSED__, void *rval __UNUSED__, void **avals,
+ void *data __UNUSED__)
+{
+ printf("%d %d %d %d\n", *(unsigned char *)avals[0],
+ *(unsigned char *)avals[1], *(unsigned char *)avals[2],
+ *(unsigned char *)avals[3]);
+}
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void * args_dbl[5];
+ ffi_type * cl_arg_types[5];
+ ffi_arg res_call;
+ unsigned char a, b, c, d, res_closure;
+
+ a = 1;
+ b = 2;
+ c = 127;
+ d = 125;
+
+ args_dbl[0] = &a;
+ args_dbl[1] = &b;
+ args_dbl[2] = &c;
+ args_dbl[3] = &d;
+ args_dbl[4] = NULL;
+
+ cl_arg_types[0] = &ffi_type_uchar;
+ cl_arg_types[1] = &ffi_type_uchar;
+ cl_arg_types[2] = &ffi_type_uchar;
+ cl_arg_types[3] = &ffi_type_uchar;
+ cl_arg_types[4] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
+ &ffi_type_uchar, cl_arg_types) == FFI_OK);
+
+ ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
+ /* { dg-output "1 2 127 125: 255" } */
+ printf("res: %d\n", (unsigned char)res_call);
+ /* { dg-output "\nres: 255" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
+
+ res_closure = (*((test_type)code))(1, 2, 127, 125);
+ /* { dg-output "\n1 2 127 125: 255" } */
+ printf("res: %d\n", res_closure);
+ /* { dg-output "\nres: 255" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_uchar/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_uchar/ya.make
index 6f6065e813..ef08173604 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_uchar/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_uchar/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_multi_uchar.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_multi_uchar.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushort.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushort.c
index 40debdda85..dd10ca7346 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushort.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushort.c
@@ -1,74 +1,74 @@
-/* Area: ffi_call, closure_call
- Purpose: Check passing of multiple unsigned short values.
- Limitations: none.
- PR: PR13221.
- Originator: <andreast@gcc.gnu.org> 20031129 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-unsigned short test_func_fn(unsigned short a1, unsigned short a2)
-{
- unsigned short result;
-
- result = a1 + a2;
-
- printf("%d %d: %d\n", a1, a2, result);
-
- return result;
-
-}
-
-static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
- void *data __UNUSED__)
-{
- unsigned short a1, a2;
-
- a1 = *(unsigned short *)avals[0];
- a2 = *(unsigned short *)avals[1];
-
- *(ffi_arg *)rval = test_func_fn(a1, a2);
-
-}
-
-typedef unsigned short (*test_type)(unsigned short, unsigned short);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void * args_dbl[3];
- ffi_type * cl_arg_types[3];
- ffi_arg res_call;
- unsigned short a, b, res_closure;
-
- a = 2;
- b = 32765;
-
- args_dbl[0] = &a;
- args_dbl[1] = &b;
- args_dbl[2] = NULL;
-
- cl_arg_types[0] = &ffi_type_ushort;
- cl_arg_types[1] = &ffi_type_ushort;
- cl_arg_types[2] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
- &ffi_type_ushort, cl_arg_types) == FFI_OK);
-
- ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
- /* { dg-output "2 32765: 32767" } */
- printf("res: %d\n", (unsigned short)res_call);
- /* { dg-output "\nres: 32767" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
-
- res_closure = (*((test_type)code))(2, 32765);
- /* { dg-output "\n2 32765: 32767" } */
- printf("res: %d\n", res_closure);
- /* { dg-output "\nres: 32767" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check passing of multiple unsigned short values.
+ Limitations: none.
+ PR: PR13221.
+ Originator: <andreast@gcc.gnu.org> 20031129 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+unsigned short test_func_fn(unsigned short a1, unsigned short a2)
+{
+ unsigned short result;
+
+ result = a1 + a2;
+
+ printf("%d %d: %d\n", a1, a2, result);
+
+ return result;
+
+}
+
+static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
+ void *data __UNUSED__)
+{
+ unsigned short a1, a2;
+
+ a1 = *(unsigned short *)avals[0];
+ a2 = *(unsigned short *)avals[1];
+
+ *(ffi_arg *)rval = test_func_fn(a1, a2);
+
+}
+
+typedef unsigned short (*test_type)(unsigned short, unsigned short);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void * args_dbl[3];
+ ffi_type * cl_arg_types[3];
+ ffi_arg res_call;
+ unsigned short a, b, res_closure;
+
+ a = 2;
+ b = 32765;
+
+ args_dbl[0] = &a;
+ args_dbl[1] = &b;
+ args_dbl[2] = NULL;
+
+ cl_arg_types[0] = &ffi_type_ushort;
+ cl_arg_types[1] = &ffi_type_ushort;
+ cl_arg_types[2] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2,
+ &ffi_type_ushort, cl_arg_types) == FFI_OK);
+
+ ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
+ /* { dg-output "2 32765: 32767" } */
+ printf("res: %d\n", (unsigned short)res_call);
+ /* { dg-output "\nres: 32767" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
+
+ res_closure = (*((test_type)code))(2, 32765);
+ /* { dg-output "\n2 32765: 32767" } */
+ printf("res: %d\n", res_closure);
+ /* { dg-output "\nres: 32767" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushort/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushort/ya.make
index d706f9eed6..31dbab5cf1 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushort/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushort/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_multi_ushort.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_multi_ushort.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushortchar.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushortchar.c
index 21a1174bdf..2588e97f98 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushortchar.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushortchar.c
@@ -1,86 +1,86 @@
-/* Area: ffi_call, closure_call
- Purpose: Check passing of multiple unsigned short/char values.
- Limitations: none.
- PR: PR13221.
- Originator: <andreast@gcc.gnu.org> 20031129 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-unsigned short test_func_fn(unsigned char a1, unsigned short a2,
- unsigned char a3, unsigned short a4)
-{
- unsigned short result;
-
- result = a1 + a2 + a3 + a4;
-
- printf("%d %d %d %d: %d\n", a1, a2, a3, a4, result);
-
- return result;
-
-}
-
-static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
- void *data __UNUSED__)
-{
- unsigned char a1, a3;
- unsigned short a2, a4;
-
- a1 = *(unsigned char *)avals[0];
- a2 = *(unsigned short *)avals[1];
- a3 = *(unsigned char *)avals[2];
- a4 = *(unsigned short *)avals[3];
-
- *(ffi_arg *)rval = test_func_fn(a1, a2, a3, a4);
-
-}
-
-typedef unsigned short (*test_type)(unsigned char, unsigned short,
- unsigned char, unsigned short);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void * args_dbl[5];
- ffi_type * cl_arg_types[5];
- ffi_arg res_call;
- unsigned char a, c;
- unsigned short b, d, res_closure;
-
- a = 1;
- b = 2;
- c = 127;
- d = 128;
-
- args_dbl[0] = &a;
- args_dbl[1] = &b;
- args_dbl[2] = &c;
- args_dbl[3] = &d;
- args_dbl[4] = NULL;
-
- cl_arg_types[0] = &ffi_type_uchar;
- cl_arg_types[1] = &ffi_type_ushort;
- cl_arg_types[2] = &ffi_type_uchar;
- cl_arg_types[3] = &ffi_type_ushort;
- cl_arg_types[4] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
- &ffi_type_ushort, cl_arg_types) == FFI_OK);
-
- ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
- /* { dg-output "1 2 127 128: 258" } */
- printf("res: %d\n", (unsigned short)res_call);
- /* { dg-output "\nres: 258" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
-
- res_closure = (*((test_type)code))(1, 2, 127, 128);
- /* { dg-output "\n1 2 127 128: 258" } */
- printf("res: %d\n", res_closure);
- /* { dg-output "\nres: 258" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check passing of multiple unsigned short/char values.
+ Limitations: none.
+ PR: PR13221.
+ Originator: <andreast@gcc.gnu.org> 20031129 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+unsigned short test_func_fn(unsigned char a1, unsigned short a2,
+ unsigned char a3, unsigned short a4)
+{
+ unsigned short result;
+
+ result = a1 + a2 + a3 + a4;
+
+ printf("%d %d %d %d: %d\n", a1, a2, a3, a4, result);
+
+ return result;
+
+}
+
+static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals,
+ void *data __UNUSED__)
+{
+ unsigned char a1, a3;
+ unsigned short a2, a4;
+
+ a1 = *(unsigned char *)avals[0];
+ a2 = *(unsigned short *)avals[1];
+ a3 = *(unsigned char *)avals[2];
+ a4 = *(unsigned short *)avals[3];
+
+ *(ffi_arg *)rval = test_func_fn(a1, a2, a3, a4);
+
+}
+
+typedef unsigned short (*test_type)(unsigned char, unsigned short,
+ unsigned char, unsigned short);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void * args_dbl[5];
+ ffi_type * cl_arg_types[5];
+ ffi_arg res_call;
+ unsigned char a, c;
+ unsigned short b, d, res_closure;
+
+ a = 1;
+ b = 2;
+ c = 127;
+ d = 128;
+
+ args_dbl[0] = &a;
+ args_dbl[1] = &b;
+ args_dbl[2] = &c;
+ args_dbl[3] = &d;
+ args_dbl[4] = NULL;
+
+ cl_arg_types[0] = &ffi_type_uchar;
+ cl_arg_types[1] = &ffi_type_ushort;
+ cl_arg_types[2] = &ffi_type_uchar;
+ cl_arg_types[3] = &ffi_type_ushort;
+ cl_arg_types[4] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
+ &ffi_type_ushort, cl_arg_types) == FFI_OK);
+
+ ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl);
+ /* { dg-output "1 2 127 128: 258" } */
+ printf("res: %d\n", (unsigned short)res_call);
+ /* { dg-output "\nres: 258" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
+
+ res_closure = (*((test_type)code))(1, 2, 127, 128);
+ /* { dg-output "\n1 2 127 128: 258" } */
+ printf("res: %d\n", res_closure);
+ /* { dg-output "\nres: 258" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushortchar/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushortchar/ya.make
index 7a346aac17..633d341d4c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushortchar/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_multi_ushortchar/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_multi_ushortchar.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_multi_ushortchar.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer.c
index 6f59f72171..d82a87a71b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer.c
@@ -1,74 +1,74 @@
-/* Area: ffi_call, closure_call
- Purpose: Check pointer arguments.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/6/2007 */
-
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
-#include "ffitest.h"
-
-void* cls_pointer_fn(void* a1, void* a2)
-{
- void* result = (void*)((intptr_t)a1 + (intptr_t)a2);
-
- printf("0x%08x 0x%08x: 0x%08x\n",
- (unsigned int)(uintptr_t) a1,
- (unsigned int)(uintptr_t) a2,
- (unsigned int)(uintptr_t) result);
-
- return result;
-}
-
-static void
-cls_pointer_gn(ffi_cif* cif __UNUSED__, void* resp,
- void** args, void* userdata __UNUSED__)
-{
- void* a1 = *(void**)(args[0]);
- void* a2 = *(void**)(args[1]);
-
- *(void**)resp = cls_pointer_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args[3];
- /* ffi_type cls_pointer_type; */
- ffi_type* arg_types[3];
-
-/* cls_pointer_type.size = sizeof(void*);
- cls_pointer_type.alignment = 0;
- cls_pointer_type.type = FFI_TYPE_POINTER;
- cls_pointer_type.elements = NULL;*/
-
- void* arg1 = (void*)0x12345678;
- void* arg2 = (void*)0x89abcdef;
- ffi_arg res = 0;
-
- arg_types[0] = &ffi_type_pointer;
- arg_types[1] = &ffi_type_pointer;
- arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_pointer,
- arg_types) == FFI_OK);
-
- args[0] = &arg1;
- args[1] = &arg2;
- args[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_pointer_fn), &res, args);
- /* { dg-output "0x12345678 0x89abcdef: 0x9be02467" } */
- printf("res: 0x%08x\n", (unsigned int) res);
- /* { dg-output "\nres: 0x9be02467" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_pointer_gn, NULL, code) == FFI_OK);
-
- res = (ffi_arg)(uintptr_t)((void*(*)(void*, void*))(code))(arg1, arg2);
- /* { dg-output "\n0x12345678 0x89abcdef: 0x9be02467" } */
- printf("res: 0x%08x\n", (unsigned int) res);
- /* { dg-output "\nres: 0x9be02467" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check pointer arguments.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/6/2007 */
+
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
+#include "ffitest.h"
+
+void* cls_pointer_fn(void* a1, void* a2)
+{
+ void* result = (void*)((intptr_t)a1 + (intptr_t)a2);
+
+ printf("0x%08x 0x%08x: 0x%08x\n",
+ (unsigned int)(uintptr_t) a1,
+ (unsigned int)(uintptr_t) a2,
+ (unsigned int)(uintptr_t) result);
+
+ return result;
+}
+
+static void
+cls_pointer_gn(ffi_cif* cif __UNUSED__, void* resp,
+ void** args, void* userdata __UNUSED__)
+{
+ void* a1 = *(void**)(args[0]);
+ void* a2 = *(void**)(args[1]);
+
+ *(void**)resp = cls_pointer_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args[3];
+ /* ffi_type cls_pointer_type; */
+ ffi_type* arg_types[3];
+
+/* cls_pointer_type.size = sizeof(void*);
+ cls_pointer_type.alignment = 0;
+ cls_pointer_type.type = FFI_TYPE_POINTER;
+ cls_pointer_type.elements = NULL;*/
+
+ void* arg1 = (void*)0x12345678;
+ void* arg2 = (void*)0x89abcdef;
+ ffi_arg res = 0;
+
+ arg_types[0] = &ffi_type_pointer;
+ arg_types[1] = &ffi_type_pointer;
+ arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_pointer,
+ arg_types) == FFI_OK);
+
+ args[0] = &arg1;
+ args[1] = &arg2;
+ args[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_pointer_fn), &res, args);
+ /* { dg-output "0x12345678 0x89abcdef: 0x9be02467" } */
+ printf("res: 0x%08x\n", (unsigned int) res);
+ /* { dg-output "\nres: 0x9be02467" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_pointer_gn, NULL, code) == FFI_OK);
+
+ res = (ffi_arg)(uintptr_t)((void*(*)(void*, void*))(code))(arg1, arg2);
+ /* { dg-output "\n0x12345678 0x89abcdef: 0x9be02467" } */
+ printf("res: 0x%08x\n", (unsigned int) res);
+ /* { dg-output "\nres: 0x9be02467" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer/ya.make
index 06d633a56d..4cbd0599fe 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_pointer.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_pointer.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer_stack.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer_stack.c
index b3cc17d24b..1f1d9157b9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer_stack.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer_stack.c
@@ -1,142 +1,142 @@
-/* Area: ffi_call, closure_call
- Purpose: Check pointer arguments across multiple hideous stack frames.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/7/2007 */
-
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
-#include "ffitest.h"
-
-static long dummyVar;
-
-long dummy_func(
- long double a1, char b1,
- long double a2, char b2,
- long double a3, char b3,
- long double a4, char b4)
-{
- return a1 + b1 + a2 + b2 + a3 + b3 + a4 + b4;
-}
-
-void* cls_pointer_fn2(void* a1, void* a2)
-{
- long double trample1 = (intptr_t)a1 + (intptr_t)a2;
- char trample2 = ((char*)&a1)[0] + ((char*)&a2)[0];
- long double trample3 = (intptr_t)trample1 + (intptr_t)a1;
- char trample4 = trample2 + ((char*)&a1)[1];
- long double trample5 = (intptr_t)trample3 + (intptr_t)a2;
- char trample6 = trample4 + ((char*)&a2)[1];
- long double trample7 = (intptr_t)trample5 + (intptr_t)trample1;
- char trample8 = trample6 + trample2;
- void* result;
-
- dummyVar = dummy_func(trample1, trample2, trample3, trample4,
- trample5, trample6, trample7, trample8);
-
- result = (void*)((intptr_t)a1 + (intptr_t)a2);
-
- printf("0x%08x 0x%08x: 0x%08x\n",
- (unsigned int)(uintptr_t) a1,
- (unsigned int)(uintptr_t) a2,
- (unsigned int)(uintptr_t) result);
-
- return result;
-}
-
-void* cls_pointer_fn1(void* a1, void* a2)
-{
- long double trample1 = (intptr_t)a1 + (intptr_t)a2;
- char trample2 = ((char*)&a1)[0] + ((char*)&a2)[0];
- long double trample3 = (intptr_t)trample1 + (intptr_t)a1;
- char trample4 = trample2 + ((char*)&a1)[1];
- long double trample5 = (intptr_t)trample3 + (intptr_t)a2;
- char trample6 = trample4 + ((char*)&a2)[1];
- long double trample7 = (intptr_t)trample5 + (intptr_t)trample1;
- char trample8 = trample6 + trample2;
- void* result;
-
- dummyVar = dummy_func(trample1, trample2, trample3, trample4,
- trample5, trample6, trample7, trample8);
-
- result = (void*)((intptr_t)a1 + (intptr_t)a2);
-
+/* Area: ffi_call, closure_call
+ Purpose: Check pointer arguments across multiple hideous stack frames.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/7/2007 */
+
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
+#include "ffitest.h"
+
+static long dummyVar;
+
+long dummy_func(
+ long double a1, char b1,
+ long double a2, char b2,
+ long double a3, char b3,
+ long double a4, char b4)
+{
+ return a1 + b1 + a2 + b2 + a3 + b3 + a4 + b4;
+}
+
+void* cls_pointer_fn2(void* a1, void* a2)
+{
+ long double trample1 = (intptr_t)a1 + (intptr_t)a2;
+ char trample2 = ((char*)&a1)[0] + ((char*)&a2)[0];
+ long double trample3 = (intptr_t)trample1 + (intptr_t)a1;
+ char trample4 = trample2 + ((char*)&a1)[1];
+ long double trample5 = (intptr_t)trample3 + (intptr_t)a2;
+ char trample6 = trample4 + ((char*)&a2)[1];
+ long double trample7 = (intptr_t)trample5 + (intptr_t)trample1;
+ char trample8 = trample6 + trample2;
+ void* result;
+
+ dummyVar = dummy_func(trample1, trample2, trample3, trample4,
+ trample5, trample6, trample7, trample8);
+
+ result = (void*)((intptr_t)a1 + (intptr_t)a2);
+
printf("0x%08x 0x%08x: 0x%08x\n",
- (unsigned int)(intptr_t) a1,
- (unsigned int)(intptr_t) a2,
- (unsigned int)(intptr_t) result);
-
- result = cls_pointer_fn2(result, a1);
-
- return result;
-}
-
-static void
-cls_pointer_gn(ffi_cif* cif __UNUSED__, void* resp,
- void** args, void* userdata __UNUSED__)
-{
- void* a1 = *(void**)(args[0]);
- void* a2 = *(void**)(args[1]);
-
- long double trample1 = (intptr_t)a1 + (intptr_t)a2;
- char trample2 = ((char*)&a1)[0] + ((char*)&a2)[0];
- long double trample3 = (intptr_t)trample1 + (intptr_t)a1;
- char trample4 = trample2 + ((char*)&a1)[1];
- long double trample5 = (intptr_t)trample3 + (intptr_t)a2;
- char trample6 = trample4 + ((char*)&a2)[1];
- long double trample7 = (intptr_t)trample5 + (intptr_t)trample1;
- char trample8 = trample6 + trample2;
-
- dummyVar = dummy_func(trample1, trample2, trample3, trample4,
- trample5, trample6, trample7, trample8);
-
- *(void**)resp = cls_pointer_fn1(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args[3];
- /* ffi_type cls_pointer_type; */
- ffi_type* arg_types[3];
-
-/* cls_pointer_type.size = sizeof(void*);
- cls_pointer_type.alignment = 0;
- cls_pointer_type.type = FFI_TYPE_POINTER;
- cls_pointer_type.elements = NULL;*/
-
- void* arg1 = (void*)0x01234567;
- void* arg2 = (void*)0x89abcdef;
- ffi_arg res = 0;
-
- arg_types[0] = &ffi_type_pointer;
- arg_types[1] = &ffi_type_pointer;
- arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_pointer,
- arg_types) == FFI_OK);
-
- args[0] = &arg1;
- args[1] = &arg2;
- args[2] = NULL;
-
- printf("\n");
- ffi_call(&cif, FFI_FN(cls_pointer_fn1), &res, args);
-
- printf("res: 0x%08x\n", (unsigned int) res);
- /* { dg-output "\n0x01234567 0x89abcdef: 0x8acf1356" } */
- /* { dg-output "\n0x8acf1356 0x01234567: 0x8bf258bd" } */
- /* { dg-output "\nres: 0x8bf258bd" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_pointer_gn, NULL, code) == FFI_OK);
-
- res = (ffi_arg)(uintptr_t)((void*(*)(void*, void*))(code))(arg1, arg2);
-
- printf("res: 0x%08x\n", (unsigned int) res);
- /* { dg-output "\n0x01234567 0x89abcdef: 0x8acf1356" } */
- /* { dg-output "\n0x8acf1356 0x01234567: 0x8bf258bd" } */
- /* { dg-output "\nres: 0x8bf258bd" } */
-
- exit(0);
-}
+ (unsigned int)(uintptr_t) a1,
+ (unsigned int)(uintptr_t) a2,
+ (unsigned int)(uintptr_t) result);
+
+ return result;
+}
+
+void* cls_pointer_fn1(void* a1, void* a2)
+{
+ long double trample1 = (intptr_t)a1 + (intptr_t)a2;
+ char trample2 = ((char*)&a1)[0] + ((char*)&a2)[0];
+ long double trample3 = (intptr_t)trample1 + (intptr_t)a1;
+ char trample4 = trample2 + ((char*)&a1)[1];
+ long double trample5 = (intptr_t)trample3 + (intptr_t)a2;
+ char trample6 = trample4 + ((char*)&a2)[1];
+ long double trample7 = (intptr_t)trample5 + (intptr_t)trample1;
+ char trample8 = trample6 + trample2;
+ void* result;
+
+ dummyVar = dummy_func(trample1, trample2, trample3, trample4,
+ trample5, trample6, trample7, trample8);
+
+ result = (void*)((intptr_t)a1 + (intptr_t)a2);
+
+ printf("0x%08x 0x%08x: 0x%08x\n",
+ (unsigned int)(intptr_t) a1,
+ (unsigned int)(intptr_t) a2,
+ (unsigned int)(intptr_t) result);
+
+ result = cls_pointer_fn2(result, a1);
+
+ return result;
+}
+
+static void
+cls_pointer_gn(ffi_cif* cif __UNUSED__, void* resp,
+ void** args, void* userdata __UNUSED__)
+{
+ void* a1 = *(void**)(args[0]);
+ void* a2 = *(void**)(args[1]);
+
+ long double trample1 = (intptr_t)a1 + (intptr_t)a2;
+ char trample2 = ((char*)&a1)[0] + ((char*)&a2)[0];
+ long double trample3 = (intptr_t)trample1 + (intptr_t)a1;
+ char trample4 = trample2 + ((char*)&a1)[1];
+ long double trample5 = (intptr_t)trample3 + (intptr_t)a2;
+ char trample6 = trample4 + ((char*)&a2)[1];
+ long double trample7 = (intptr_t)trample5 + (intptr_t)trample1;
+ char trample8 = trample6 + trample2;
+
+ dummyVar = dummy_func(trample1, trample2, trample3, trample4,
+ trample5, trample6, trample7, trample8);
+
+ *(void**)resp = cls_pointer_fn1(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args[3];
+ /* ffi_type cls_pointer_type; */
+ ffi_type* arg_types[3];
+
+/* cls_pointer_type.size = sizeof(void*);
+ cls_pointer_type.alignment = 0;
+ cls_pointer_type.type = FFI_TYPE_POINTER;
+ cls_pointer_type.elements = NULL;*/
+
+ void* arg1 = (void*)0x01234567;
+ void* arg2 = (void*)0x89abcdef;
+ ffi_arg res = 0;
+
+ arg_types[0] = &ffi_type_pointer;
+ arg_types[1] = &ffi_type_pointer;
+ arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_pointer,
+ arg_types) == FFI_OK);
+
+ args[0] = &arg1;
+ args[1] = &arg2;
+ args[2] = NULL;
+
+ printf("\n");
+ ffi_call(&cif, FFI_FN(cls_pointer_fn1), &res, args);
+
+ printf("res: 0x%08x\n", (unsigned int) res);
+ /* { dg-output "\n0x01234567 0x89abcdef: 0x8acf1356" } */
+ /* { dg-output "\n0x8acf1356 0x01234567: 0x8bf258bd" } */
+ /* { dg-output "\nres: 0x8bf258bd" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_pointer_gn, NULL, code) == FFI_OK);
+
+ res = (ffi_arg)(uintptr_t)((void*(*)(void*, void*))(code))(arg1, arg2);
+
+ printf("res: 0x%08x\n", (unsigned int) res);
+ /* { dg-output "\n0x01234567 0x89abcdef: 0x8acf1356" } */
+ /* { dg-output "\n0x8acf1356 0x01234567: 0x8bf258bd" } */
+ /* { dg-output "\nres: 0x8bf258bd" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer_stack/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer_stack/ya.make
index 44fc912cfc..20524524eb 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer_stack/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_pointer_stack/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_pointer_stack.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_pointer_stack.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_schar.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_schar.c
index 27a827f18c..82986b172c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_schar.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_schar.c
@@ -1,44 +1,44 @@
-/* Area: closure_call
- Purpose: Check return value schar.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20031108 */
-
-
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void cls_ret_schar_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- *(ffi_arg*)resp = *(signed char *)args[0];
- printf("%d: %d\n",*(signed char *)args[0],
- (int)*(ffi_arg *)(resp));
-}
-typedef signed char (*cls_ret_schar)(signed char);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[2];
- signed char res;
-
- cl_arg_types[0] = &ffi_type_schar;
- cl_arg_types[1] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_schar, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_schar_fn, NULL, code) == FFI_OK);
-
- res = (*((cls_ret_schar)code))(127);
- /* { dg-output "127: 127" } */
- printf("res: %d\n", res);
- /* { dg-output "\nres: 127" } */
-
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check return value schar.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20031108 */
+
+
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void cls_ret_schar_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ *(ffi_arg*)resp = *(signed char *)args[0];
+ printf("%d: %d\n",*(signed char *)args[0],
+ (int)*(ffi_arg *)(resp));
+}
+typedef signed char (*cls_ret_schar)(signed char);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[2];
+ signed char res;
+
+ cl_arg_types[0] = &ffi_type_schar;
+ cl_arg_types[1] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_schar, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_schar_fn, NULL, code) == FFI_OK);
+
+ res = (*((cls_ret_schar)code))(127);
+ /* { dg-output "127: 127" } */
+ printf("res: %d\n", res);
+ /* { dg-output "\nres: 127" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_schar/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_schar/ya.make
index d6917755ee..647dbe1e33 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_schar/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_schar/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_schar.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_schar.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_sint.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_sint.c
index bf30e9492e..c7e13b73a3 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_sint.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_sint.c
@@ -1,42 +1,42 @@
-/* Area: closure_call
- Purpose: Check return value sint32.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20031108 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void cls_ret_sint_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- *(ffi_arg*)resp = *(signed int *)args[0];
- printf("%d: %d\n",*(signed int *)args[0],
- (int)*(ffi_arg *)(resp));
-}
-typedef signed int (*cls_ret_sint)(signed int);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[2];
- signed int res;
-
- cl_arg_types[0] = &ffi_type_sint;
- cl_arg_types[1] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_sint, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_sint_fn, NULL, code) == FFI_OK);
-
- res = (*((cls_ret_sint)code))(65534);
- /* { dg-output "65534: 65534" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 65534" } */
-
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check return value sint32.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20031108 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void cls_ret_sint_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ *(ffi_arg*)resp = *(signed int *)args[0];
+ printf("%d: %d\n",*(signed int *)args[0],
+ (int)*(ffi_arg *)(resp));
+}
+typedef signed int (*cls_ret_sint)(signed int);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[2];
+ signed int res;
+
+ cl_arg_types[0] = &ffi_type_sint;
+ cl_arg_types[1] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_sint, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_sint_fn, NULL, code) == FFI_OK);
+
+ res = (*((cls_ret_sint)code))(65534);
+ /* { dg-output "65534: 65534" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 65534" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_sint/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_sint/ya.make
index e0006c41eb..d73d2b4bef 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_sint/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_sint/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_sint.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_sint.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_sshort.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_sshort.c
index c34f793c94..846d57ed1b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_sshort.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_sshort.c
@@ -1,42 +1,42 @@
-/* Area: closure_call
- Purpose: Check return value sshort.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20031108 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void cls_ret_sshort_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- *(ffi_arg*)resp = *(signed short *)args[0];
- printf("%d: %d\n",*(signed short *)args[0],
- (int)*(ffi_arg *)(resp));
-}
-typedef signed short (*cls_ret_sshort)(signed short);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[2];
- signed short res;
-
- cl_arg_types[0] = &ffi_type_sshort;
- cl_arg_types[1] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_sshort, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_sshort_fn, NULL, code) == FFI_OK);
-
- res = (*((cls_ret_sshort)code))(255);
- /* { dg-output "255: 255" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 255" } */
-
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check return value sshort.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20031108 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void cls_ret_sshort_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ *(ffi_arg*)resp = *(signed short *)args[0];
+ printf("%d: %d\n",*(signed short *)args[0],
+ (int)*(ffi_arg *)(resp));
+}
+typedef signed short (*cls_ret_sshort)(signed short);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[2];
+ signed short res;
+
+ cl_arg_types[0] = &ffi_type_sshort;
+ cl_arg_types[1] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_sshort, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_sshort_fn, NULL, code) == FFI_OK);
+
+ res = (*((cls_ret_sshort)code))(255);
+ /* { dg-output "255: 255" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 255" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_sshort/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_sshort/ya.make
index 1c05b4f214..dd0be63016 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_sshort/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_sshort/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_sshort.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_sshort.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_struct_va1.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_struct_va1.c
index 485922ead5..6d1fdaeb60 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_struct_va1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_struct_va1.c
@@ -1,114 +1,114 @@
-/* Area: ffi_call, closure_call
- Purpose: Test doubles passed in variable argument lists.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/6/2007 */
-
-/* { dg-do run } */
-/* { dg-output "" { xfail avr32*-*-* } } */
-#include "ffitest.h"
-
-struct small_tag
-{
- unsigned char a;
- unsigned char b;
-};
-
-struct large_tag
-{
- unsigned a;
- unsigned b;
- unsigned c;
- unsigned d;
- unsigned e;
-};
-
-static void
-test_fn (ffi_cif* cif __UNUSED__, void* resp,
- void** args, void* userdata __UNUSED__)
-{
- int n = *(int*)args[0];
- struct small_tag s1 = * (struct small_tag *) args[1];
- struct large_tag l1 = * (struct large_tag *) args[2];
- struct small_tag s2 = * (struct small_tag *) args[3];
-
- printf ("%d %d %d %d %d %d %d %d %d %d\n", n, s1.a, s1.b,
- l1.a, l1.b, l1.c, l1.d, l1.e,
- s2.a, s2.b);
- * (ffi_arg*) resp = 42;
-}
-
-int
-main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc (sizeof (ffi_closure), &code);
- ffi_type* arg_types[5];
-
- ffi_arg res = 0;
-
- ffi_type s_type;
- ffi_type *s_type_elements[3];
-
- ffi_type l_type;
- ffi_type *l_type_elements[6];
-
- struct small_tag s1;
- struct small_tag s2;
- struct large_tag l1;
-
- int si;
-
- s_type.size = 0;
- s_type.alignment = 0;
- s_type.type = FFI_TYPE_STRUCT;
- s_type.elements = s_type_elements;
-
- s_type_elements[0] = &ffi_type_uchar;
- s_type_elements[1] = &ffi_type_uchar;
- s_type_elements[2] = NULL;
-
- l_type.size = 0;
- l_type.alignment = 0;
- l_type.type = FFI_TYPE_STRUCT;
- l_type.elements = l_type_elements;
-
- l_type_elements[0] = &ffi_type_uint;
- l_type_elements[1] = &ffi_type_uint;
- l_type_elements[2] = &ffi_type_uint;
- l_type_elements[3] = &ffi_type_uint;
- l_type_elements[4] = &ffi_type_uint;
- l_type_elements[5] = NULL;
-
- arg_types[0] = &ffi_type_sint;
- arg_types[1] = &s_type;
- arg_types[2] = &l_type;
- arg_types[3] = &s_type;
- arg_types[4] = NULL;
-
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &ffi_type_sint,
- arg_types) == FFI_OK);
-
- si = 4;
- s1.a = 5;
- s1.b = 6;
-
- s2.a = 20;
- s2.b = 21;
-
- l1.a = 10;
- l1.b = 11;
- l1.c = 12;
- l1.d = 13;
- l1.e = 14;
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, test_fn, NULL, code) == FFI_OK);
-
- res = ((int (*)(int, ...))(code))(si, s1, l1, s2);
- /* { dg-output "4 5 6 10 11 12 13 14 20 21" } */
- printf("res: %d\n", (int) res);
- /* { dg-output "\nres: 42" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Test doubles passed in variable argument lists.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/6/2007 */
+
+/* { dg-do run } */
+/* { dg-output "" { xfail avr32*-*-* } } */
+#include "ffitest.h"
+
+struct small_tag
+{
+ unsigned char a;
+ unsigned char b;
+};
+
+struct large_tag
+{
+ unsigned a;
+ unsigned b;
+ unsigned c;
+ unsigned d;
+ unsigned e;
+};
+
+static void
+test_fn (ffi_cif* cif __UNUSED__, void* resp,
+ void** args, void* userdata __UNUSED__)
+{
+ int n = *(int*)args[0];
+ struct small_tag s1 = * (struct small_tag *) args[1];
+ struct large_tag l1 = * (struct large_tag *) args[2];
+ struct small_tag s2 = * (struct small_tag *) args[3];
+
+ printf ("%d %d %d %d %d %d %d %d %d %d\n", n, s1.a, s1.b,
+ l1.a, l1.b, l1.c, l1.d, l1.e,
+ s2.a, s2.b);
+ * (ffi_arg*) resp = 42;
+}
+
+int
+main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc (sizeof (ffi_closure), &code);
+ ffi_type* arg_types[5];
+
+ ffi_arg res = 0;
+
+ ffi_type s_type;
+ ffi_type *s_type_elements[3];
+
+ ffi_type l_type;
+ ffi_type *l_type_elements[6];
+
+ struct small_tag s1;
+ struct small_tag s2;
+ struct large_tag l1;
+
+ int si;
+
+ s_type.size = 0;
+ s_type.alignment = 0;
+ s_type.type = FFI_TYPE_STRUCT;
+ s_type.elements = s_type_elements;
+
+ s_type_elements[0] = &ffi_type_uchar;
+ s_type_elements[1] = &ffi_type_uchar;
+ s_type_elements[2] = NULL;
+
+ l_type.size = 0;
+ l_type.alignment = 0;
+ l_type.type = FFI_TYPE_STRUCT;
+ l_type.elements = l_type_elements;
+
+ l_type_elements[0] = &ffi_type_uint;
+ l_type_elements[1] = &ffi_type_uint;
+ l_type_elements[2] = &ffi_type_uint;
+ l_type_elements[3] = &ffi_type_uint;
+ l_type_elements[4] = &ffi_type_uint;
+ l_type_elements[5] = NULL;
+
+ arg_types[0] = &ffi_type_sint;
+ arg_types[1] = &s_type;
+ arg_types[2] = &l_type;
+ arg_types[3] = &s_type;
+ arg_types[4] = NULL;
+
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &ffi_type_sint,
+ arg_types) == FFI_OK);
+
+ si = 4;
+ s1.a = 5;
+ s1.b = 6;
+
+ s2.a = 20;
+ s2.b = 21;
+
+ l1.a = 10;
+ l1.b = 11;
+ l1.c = 12;
+ l1.d = 13;
+ l1.e = 14;
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, test_fn, NULL, code) == FFI_OK);
+
+ res = ((int (*)(int, ...))(code))(si, s1, l1, s2);
+ /* { dg-output "4 5 6 10 11 12 13 14 20 21" } */
+ printf("res: %d\n", (int) res);
+ /* { dg-output "\nres: 42" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_struct_va1/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_struct_va1/ya.make
index fc2f3e953d..909b210dc0 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_struct_va1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_struct_va1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_struct_va1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_struct_va1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar.c
index 8a7d0fc291..c1317e795f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar.c
@@ -1,42 +1,42 @@
-/* Area: closure_call
- Purpose: Check return value uchar.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void cls_ret_uchar_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- *(ffi_arg*)resp = *(unsigned char *)args[0];
- printf("%d: %d\n",*(unsigned char *)args[0],
- (int)*(ffi_arg *)(resp));
-}
-typedef unsigned char (*cls_ret_uchar)(unsigned char);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[2];
- unsigned char res;
-
- cl_arg_types[0] = &ffi_type_uchar;
- cl_arg_types[1] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_uchar, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_uchar_fn, NULL, code) == FFI_OK);
-
- res = (*((cls_ret_uchar)code))(127);
- /* { dg-output "127: 127" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 127" } */
-
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check return value uchar.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void cls_ret_uchar_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ *(ffi_arg*)resp = *(unsigned char *)args[0];
+ printf("%d: %d\n",*(unsigned char *)args[0],
+ (int)*(ffi_arg *)(resp));
+}
+typedef unsigned char (*cls_ret_uchar)(unsigned char);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[2];
+ unsigned char res;
+
+ cl_arg_types[0] = &ffi_type_uchar;
+ cl_arg_types[1] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_uchar, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_uchar_fn, NULL, code) == FFI_OK);
+
+ res = (*((cls_ret_uchar)code))(127);
+ /* { dg-output "127: 127" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 127" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar/ya.make
index d17f8cdce6..edc1b7dee3 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_uchar.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_uchar.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar_va.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar_va.c
index 41d0a80c86..6491c5b3df 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar_va.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar_va.c
@@ -1,44 +1,44 @@
-/* Area: closure_call
- Purpose: Test anonymous unsigned char argument.
- Limitations: none.
- PR: none.
- Originator: ARM Ltd. */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef unsigned char T;
-
-static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
- {
- *(ffi_arg *)resp = *(T *)args[0];
-
- printf("%d: %d %d\n", (int)(*(ffi_arg *)resp), *(T *)args[0], *(T *)args[1]);
- }
-
-typedef T (*cls_ret_T)(T, ...);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[3];
- T res;
-
- cl_arg_types[0] = &ffi_type_uchar;
- cl_arg_types[1] = &ffi_type_uchar;
- cl_arg_types[2] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2,
- &ffi_type_uchar, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK);
- res = ((((cls_ret_T)code)(67, 4)));
- /* { dg-output "67: 67 4" } */
- printf("res: %d\n", res);
- /* { dg-output "\nres: 67" } */
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Test anonymous unsigned char argument.
+ Limitations: none.
+ PR: none.
+ Originator: ARM Ltd. */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef unsigned char T;
+
+static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+ {
+ *(ffi_arg *)resp = *(T *)args[0];
+
+ printf("%d: %d %d\n", (int)(*(ffi_arg *)resp), *(T *)args[0], *(T *)args[1]);
+ }
+
+typedef T (*cls_ret_T)(T, ...);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[3];
+ T res;
+
+ cl_arg_types[0] = &ffi_type_uchar;
+ cl_arg_types[1] = &ffi_type_uchar;
+ cl_arg_types[2] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2,
+ &ffi_type_uchar, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK);
+ res = ((((cls_ret_T)code)(67, 4)));
+ /* { dg-output "67: 67 4" } */
+ printf("res: %d\n", res);
+ /* { dg-output "\nres: 67" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar_va/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar_va/ya.make
index ea7a6fbca6..2d963a350d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar_va/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uchar_va/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_uchar_va.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_uchar_va.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint.c
index c80f594d4c..885cff5c31 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint.c
@@ -1,43 +1,43 @@
-/* Area: closure_call
- Purpose: Check return value uint.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void cls_ret_uint_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- *(ffi_arg *)resp = *(unsigned int *)args[0];
-
- printf("%d: %d\n",*(unsigned int *)args[0],
- (int)*(ffi_arg *)(resp));
-}
-typedef unsigned int (*cls_ret_uint)(unsigned int);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[2];
- unsigned int res;
-
- cl_arg_types[0] = &ffi_type_uint;
- cl_arg_types[1] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_uint, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_uint_fn, NULL, code) == FFI_OK);
-
- res = (*((cls_ret_uint)code))(2147483647);
- /* { dg-output "2147483647: 2147483647" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 2147483647" } */
-
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check return value uint.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void cls_ret_uint_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ *(ffi_arg *)resp = *(unsigned int *)args[0];
+
+ printf("%d: %d\n",*(unsigned int *)args[0],
+ (int)*(ffi_arg *)(resp));
+}
+typedef unsigned int (*cls_ret_uint)(unsigned int);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[2];
+ unsigned int res;
+
+ cl_arg_types[0] = &ffi_type_uint;
+ cl_arg_types[1] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_uint, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_uint_fn, NULL, code) == FFI_OK);
+
+ res = (*((cls_ret_uint)code))(2147483647);
+ /* { dg-output "2147483647: 2147483647" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 2147483647" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint/ya.make
index 129d375b9e..e4344b6e3d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_uint.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_uint.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint_va.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint_va.c
index fcd7b4a48c..b04cfd19c2 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint_va.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint_va.c
@@ -1,45 +1,45 @@
-/* Area: closure_call
- Purpose: Test anonymous unsigned int argument.
- Limitations: none.
- PR: none.
- Originator: ARM Ltd. */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-typedef unsigned int T;
-
-static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
- {
- *(ffi_arg *)resp = *(T *)args[0];
-
- printf("%d: %d %d\n", (int)*(ffi_arg *)resp, *(T *)args[0], *(T *)args[1]);
- }
-
-typedef T (*cls_ret_T)(T, ...);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[3];
- T res;
-
- cl_arg_types[0] = &ffi_type_uint;
- cl_arg_types[1] = &ffi_type_uint;
- cl_arg_types[2] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2,
- &ffi_type_uint, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK);
- res = ((((cls_ret_T)code)(67, 4)));
- /* { dg-output "67: 67 4" } */
- printf("res: %d\n", res);
- /* { dg-output "\nres: 67" } */
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Test anonymous unsigned int argument.
+ Limitations: none.
+ PR: none.
+ Originator: ARM Ltd. */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+typedef unsigned int T;
+
+static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+ {
+ *(ffi_arg *)resp = *(T *)args[0];
+
+ printf("%d: %d %d\n", (int)*(ffi_arg *)resp, *(T *)args[0], *(T *)args[1]);
+ }
+
+typedef T (*cls_ret_T)(T, ...);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[3];
+ T res;
+
+ cl_arg_types[0] = &ffi_type_uint;
+ cl_arg_types[1] = &ffi_type_uint;
+ cl_arg_types[2] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2,
+ &ffi_type_uint, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK);
+ res = ((((cls_ret_T)code)(67, 4)));
+ /* { dg-output "67: 67 4" } */
+ printf("res: %d\n", res);
+ /* { dg-output "\nres: 67" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint_va/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint_va/ya.make
index 0db56fb11c..87fb8f7030 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint_va/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_uint_va/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_uint_va.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_uint_va.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulong_va.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulong_va.c
index 987dc86609..0315082e09 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulong_va.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulong_va.c
@@ -1,45 +1,45 @@
-/* Area: closure_call
- Purpose: Test anonymous unsigned long argument.
- Limitations: none.
- PR: none.
- Originator: ARM Ltd. */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-typedef unsigned long T;
-
-static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
- {
- *(T *)resp = *(T *)args[0];
-
- printf("%ld: %ld %ld\n", *(T *)resp, *(T *)args[0], *(T *)args[1]);
- }
-
-typedef T (*cls_ret_T)(T, ...);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[3];
- T res;
-
- cl_arg_types[0] = &ffi_type_ulong;
- cl_arg_types[1] = &ffi_type_ulong;
- cl_arg_types[2] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2,
- &ffi_type_ulong, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK);
- res = ((((cls_ret_T)code)(67, 4)));
- /* { dg-output "67: 67 4" } */
- printf("res: %ld\n", res);
- /* { dg-output "\nres: 67" } */
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Test anonymous unsigned long argument.
+ Limitations: none.
+ PR: none.
+ Originator: ARM Ltd. */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+typedef unsigned long T;
+
+static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+ {
+ *(T *)resp = *(T *)args[0];
+
+ printf("%ld: %ld %ld\n", *(T *)resp, *(T *)args[0], *(T *)args[1]);
+ }
+
+typedef T (*cls_ret_T)(T, ...);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[3];
+ T res;
+
+ cl_arg_types[0] = &ffi_type_ulong;
+ cl_arg_types[1] = &ffi_type_ulong;
+ cl_arg_types[2] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2,
+ &ffi_type_ulong, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK);
+ res = ((((cls_ret_T)code)(67, 4)));
+ /* { dg-output "67: 67 4" } */
+ printf("res: %ld\n", res);
+ /* { dg-output "\nres: 67" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulong_va/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulong_va/ya.make
index 56f20c9c33..5169351460 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulong_va/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulong_va/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_ulong_va.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_ulong_va.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulonglong.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulonglong.c
index 808875c899..62f2cae63a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulonglong.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulonglong.c
@@ -1,47 +1,47 @@
-/* Area: closure_call
- Purpose: Check return value long long.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */
-#include "ffitest.h"
-
-static void cls_ret_ulonglong_fn(ffi_cif* cif __UNUSED__, void* resp,
- void** args, void* userdata __UNUSED__)
-{
- *(unsigned long long *)resp= 0xfffffffffffffffLL ^ *(unsigned long long *)args[0];
-
- printf("%" PRIuLL ": %" PRIuLL "\n",*(unsigned long long *)args[0],
- *(unsigned long long *)(resp));
-}
-typedef unsigned long long (*cls_ret_ulonglong)(unsigned long long);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[2];
- unsigned long long res;
-
- cl_arg_types[0] = &ffi_type_uint64;
- cl_arg_types[1] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_uint64, cl_arg_types) == FFI_OK);
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_ulonglong_fn, NULL, code) == FFI_OK);
- res = (*((cls_ret_ulonglong)code))(214LL);
- /* { dg-output "214: 1152921504606846761" } */
- printf("res: %" PRIdLL "\n", res);
- /* { dg-output "\nres: 1152921504606846761" } */
-
- res = (*((cls_ret_ulonglong)code))(9223372035854775808LL);
- /* { dg-output "\n9223372035854775808: 8070450533247928831" } */
- printf("res: %" PRIdLL "\n", res);
- /* { dg-output "\nres: 8070450533247928831" } */
-
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check return value long long.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */
+#include "ffitest.h"
+
+static void cls_ret_ulonglong_fn(ffi_cif* cif __UNUSED__, void* resp,
+ void** args, void* userdata __UNUSED__)
+{
+ *(unsigned long long *)resp= 0xfffffffffffffffLL ^ *(unsigned long long *)args[0];
+
+ printf("%" PRIuLL ": %" PRIuLL "\n",*(unsigned long long *)args[0],
+ *(unsigned long long *)(resp));
+}
+typedef unsigned long long (*cls_ret_ulonglong)(unsigned long long);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[2];
+ unsigned long long res;
+
+ cl_arg_types[0] = &ffi_type_uint64;
+ cl_arg_types[1] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_uint64, cl_arg_types) == FFI_OK);
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_ulonglong_fn, NULL, code) == FFI_OK);
+ res = (*((cls_ret_ulonglong)code))(214LL);
+ /* { dg-output "214: 1152921504606846761" } */
+ printf("res: %" PRIdLL "\n", res);
+ /* { dg-output "\nres: 1152921504606846761" } */
+
+ res = (*((cls_ret_ulonglong)code))(9223372035854775808LL);
+ /* { dg-output "\n9223372035854775808: 8070450533247928831" } */
+ printf("res: %" PRIdLL "\n", res);
+ /* { dg-output "\nres: 8070450533247928831" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulonglong/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulonglong/ya.make
index 25e83aeaf6..9b2dc41c8e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulonglong/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ulonglong/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_ulonglong.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_ulonglong.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort.c
index 11f53b5088..a00100e07f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort.c
@@ -1,43 +1,43 @@
-/* Area: closure_call
- Purpose: Check return value ushort.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-static void cls_ret_ushort_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- *(ffi_arg*)resp = *(unsigned short *)args[0];
-
- printf("%d: %d\n",*(unsigned short *)args[0],
- (int)*(ffi_arg *)(resp));
-}
-typedef unsigned short (*cls_ret_ushort)(unsigned short);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[2];
- unsigned short res;
-
- cl_arg_types[0] = &ffi_type_ushort;
- cl_arg_types[1] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_ushort, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_ushort_fn, NULL, code) == FFI_OK);
-
- res = (*((cls_ret_ushort)code))(65535);
- /* { dg-output "65535: 65535" } */
- printf("res: %d\n",res);
- /* { dg-output "\nres: 65535" } */
-
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check return value ushort.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+static void cls_ret_ushort_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ *(ffi_arg*)resp = *(unsigned short *)args[0];
+
+ printf("%d: %d\n",*(unsigned short *)args[0],
+ (int)*(ffi_arg *)(resp));
+}
+typedef unsigned short (*cls_ret_ushort)(unsigned short);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[2];
+ unsigned short res;
+
+ cl_arg_types[0] = &ffi_type_ushort;
+ cl_arg_types[1] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_ushort, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_ushort_fn, NULL, code) == FFI_OK);
+
+ res = (*((cls_ret_ushort)code))(65535);
+ /* { dg-output "65535: 65535" } */
+ printf("res: %d\n",res);
+ /* { dg-output "\nres: 65535" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort/ya.make
index 41a35f9672..cd744ba6f4 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_ushort.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_ushort.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort_va.c b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort_va.c
index 58586c1105..37aa1064ea 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort_va.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort_va.c
@@ -1,44 +1,44 @@
-/* Area: closure_call
- Purpose: Test anonymous unsigned short argument.
- Limitations: none.
- PR: none.
- Originator: ARM Ltd. */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef unsigned short T;
-
-static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
- {
- *(ffi_arg *)resp = *(T *)args[0];
-
- printf("%d: %d %d\n", (int)(*(ffi_arg *)resp), *(T *)args[0], *(T *)args[1]);
- }
-
-typedef T (*cls_ret_T)(T, ...);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[3];
- T res;
-
- cl_arg_types[0] = &ffi_type_ushort;
- cl_arg_types[1] = &ffi_type_ushort;
- cl_arg_types[2] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2,
- &ffi_type_ushort, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK);
- res = ((((cls_ret_T)code)(67, 4)));
- /* { dg-output "67: 67 4" } */
- printf("res: %d\n", res);
- /* { dg-output "\nres: 67" } */
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Test anonymous unsigned short argument.
+ Limitations: none.
+ PR: none.
+ Originator: ARM Ltd. */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef unsigned short T;
+
+static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+ {
+ *(ffi_arg *)resp = *(T *)args[0];
+
+ printf("%d: %d %d\n", (int)(*(ffi_arg *)resp), *(T *)args[0], *(T *)args[1]);
+ }
+
+typedef T (*cls_ret_T)(T, ...);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[3];
+ T res;
+
+ cl_arg_types[0] = &ffi_type_ushort;
+ cl_arg_types[1] = &ffi_type_ushort;
+ cl_arg_types[2] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2,
+ &ffi_type_ushort, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK);
+ res = ((((cls_ret_T)code)(67, 4)));
+ /* { dg-output "67: 67 4" } */
+ printf("res: %d\n", res);
+ /* { dg-output "\nres: 67" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort_va/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort_va/ya.make
index 13caf9fc3a..798c5ed5c9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort_va/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/cls_ushort_va/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- cls_ushort_va.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ cls_ushort_va.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/err_bad_abi.c b/contrib/restricted/libffi/testsuite/libffi.closures/err_bad_abi.c
index 64ab7a45b8..f5a73179ec 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/err_bad_abi.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/err_bad_abi.c
@@ -1,36 +1,36 @@
-/* Area: ffi_prep_cif, ffi_prep_closure
- Purpose: Test error return for bad ABIs.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/6/2007 */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-static void
-dummy_fn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__,
- void** args __UNUSED__, void* userdata __UNUSED__)
-{}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type* arg_types[1];
-
- arg_types[0] = NULL;
-
- CHECK(ffi_prep_cif(&cif, 255, 0, &ffi_type_void,
- arg_types) == FFI_BAD_ABI);
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, &ffi_type_void,
- arg_types) == FFI_OK);
-
- cif.abi= 255;
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, dummy_fn, NULL, code) == FFI_BAD_ABI);
-
- exit(0);
-}
+/* Area: ffi_prep_cif, ffi_prep_closure
+ Purpose: Test error return for bad ABIs.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/6/2007 */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+static void
+dummy_fn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__,
+ void** args __UNUSED__, void* userdata __UNUSED__)
+{}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type* arg_types[1];
+
+ arg_types[0] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, 255, 0, &ffi_type_void,
+ arg_types) == FFI_BAD_ABI);
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, &ffi_type_void,
+ arg_types) == FFI_OK);
+
+ cif.abi= 255;
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, dummy_fn, NULL, code) == FFI_BAD_ABI);
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/err_bad_abi/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/err_bad_abi/ya.make
index 44d8df4d1f..67284d9c78 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/err_bad_abi/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/err_bad_abi/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- err_bad_abi.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ err_bad_abi.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/ffitest.h b/contrib/restricted/libffi/testsuite/libffi.closures/ffitest.h
index c030b7026c..27d12840f8 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/ffitest.h
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/ffitest.h
@@ -1,144 +1,144 @@
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <fcntl.h>
-#include <ffi.h>
-
-#define HAVE_STDINT_H
-#define HAVE_INTTYPES_H
-
-#ifndef _MSC_VER
-#define HAVE_MMAP_ANON
-#endif
-
-#if defined HAVE_STDINT_H
-#include <stdint.h>
-#endif
-
-#if defined HAVE_INTTYPES_H
-#include <inttypes.h>
-#endif
-
-#define MAX_ARGS 256
-
-#define CHECK(x) (void)(!(x) ? (abort(), 1) : 0)
-
-/* Define macros so that compilers other than gcc can run the tests. */
-#undef __UNUSED__
-#if defined(__GNUC__)
-#define __UNUSED__ __attribute__((__unused__))
-#define __STDCALL__ __attribute__((stdcall))
-#define __THISCALL__ __attribute__((thiscall))
-#define __FASTCALL__ __attribute__((fastcall))
-#define __MSABI__ __attribute__((ms_abi))
-#else
-#define __UNUSED__
-#define __STDCALL__ __stdcall
-#define __THISCALL__ __thiscall
-#define __FASTCALL__ __fastcall
-#endif
-
-#ifndef ABI_NUM
-#define ABI_NUM FFI_DEFAULT_ABI
-#define ABI_ATTR
-#endif
-
-/* Prefer MAP_ANON(YMOUS) to /dev/zero, since we don't need to keep a
- file open. */
-#ifdef HAVE_MMAP_ANON
-# undef HAVE_MMAP_DEV_ZERO
-
-# include <sys/mman.h>
-# ifndef MAP_FAILED
-# define MAP_FAILED -1
-# endif
-# if !defined (MAP_ANONYMOUS) && defined (MAP_ANON)
-# define MAP_ANONYMOUS MAP_ANON
-# endif
-# define USING_MMAP
-
-#endif
-
-#ifdef HAVE_MMAP_DEV_ZERO
-
-# include <sys/mman.h>
-# ifndef MAP_FAILED
-# define MAP_FAILED -1
-# endif
-# define USING_MMAP
-
-#endif
-
-/* MinGW kludge. */
-#if defined(_WIN64) | defined(_WIN32)
-#define PRIdLL "I64d"
-#define PRIuLL "I64u"
-#else
-#define PRIdLL "lld"
-#define PRIuLL "llu"
-#endif
-
-/* Tru64 UNIX kludge. */
-#if defined(__alpha__) && defined(__osf__)
-/* Tru64 UNIX V4.0 doesn't support %lld/%lld, but long is 64-bit. */
-#undef PRIdLL
-#define PRIdLL "ld"
-#undef PRIuLL
-#define PRIuLL "lu"
-#define PRId8 "hd"
-#define PRIu8 "hu"
-#define PRId64 "ld"
-#define PRIu64 "lu"
-#define PRIuPTR "lu"
-#endif
-
-/* PA HP-UX kludge. */
-#if defined(__hppa__) && defined(__hpux__) && !defined(PRIuPTR)
-#define PRIuPTR "lu"
-#endif
-
-/* IRIX kludge. */
-#if defined(__sgi)
-/* IRIX 6.5 <inttypes.h> provides all definitions, but only for C99
- compilations. */
-#define PRId8 "hhd"
-#define PRIu8 "hhu"
-#if (_MIPS_SZLONG == 32)
-#define PRId64 "lld"
-#define PRIu64 "llu"
-#endif
-/* This doesn't match <inttypes.h>, which always has "lld" here, but the
- arguments are uint64_t, int64_t, which are unsigned long, long for
- 64-bit in <sgidefs.h>. */
-#if (_MIPS_SZLONG == 64)
-#define PRId64 "ld"
-#define PRIu64 "lu"
-#endif
-/* This doesn't match <inttypes.h>, which has "u" here, but the arguments
- are uintptr_t, which is always unsigned long. */
-#define PRIuPTR "lu"
-#endif
-
-/* Solaris < 10 kludge. */
-#if defined(__sun__) && defined(__svr4__) && !defined(PRIuPTR)
-#if defined(__arch64__) || defined (__x86_64__)
-#define PRIuPTR "lu"
-#else
-#define PRIuPTR "u"
-#endif
-#endif
-
-/* MSVC kludge. */
-#if defined _MSC_VER
-#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS)
-#define PRIuPTR "lu"
-#define PRIu8 "u"
-#define PRId8 "d"
-#define PRIu64 "I64u"
-#define PRId64 "I64d"
-#endif
-#endif
-
-#ifndef PRIuPTR
-#define PRIuPTR "u"
-#endif
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <fcntl.h>
+#include <ffi.h>
+
+#define HAVE_STDINT_H
+#define HAVE_INTTYPES_H
+
+#ifndef _MSC_VER
+#define HAVE_MMAP_ANON
+#endif
+
+#if defined HAVE_STDINT_H
+#include <stdint.h>
+#endif
+
+#if defined HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif
+
+#define MAX_ARGS 256
+
+#define CHECK(x) (void)(!(x) ? (abort(), 1) : 0)
+
+/* Define macros so that compilers other than gcc can run the tests. */
+#undef __UNUSED__
+#if defined(__GNUC__)
+#define __UNUSED__ __attribute__((__unused__))
+#define __STDCALL__ __attribute__((stdcall))
+#define __THISCALL__ __attribute__((thiscall))
+#define __FASTCALL__ __attribute__((fastcall))
+#define __MSABI__ __attribute__((ms_abi))
+#else
+#define __UNUSED__
+#define __STDCALL__ __stdcall
+#define __THISCALL__ __thiscall
+#define __FASTCALL__ __fastcall
+#endif
+
+#ifndef ABI_NUM
+#define ABI_NUM FFI_DEFAULT_ABI
+#define ABI_ATTR
+#endif
+
+/* Prefer MAP_ANON(YMOUS) to /dev/zero, since we don't need to keep a
+ file open. */
+#ifdef HAVE_MMAP_ANON
+# undef HAVE_MMAP_DEV_ZERO
+
+# include <sys/mman.h>
+# ifndef MAP_FAILED
+# define MAP_FAILED -1
+# endif
+# if !defined (MAP_ANONYMOUS) && defined (MAP_ANON)
+# define MAP_ANONYMOUS MAP_ANON
+# endif
+# define USING_MMAP
+
+#endif
+
+#ifdef HAVE_MMAP_DEV_ZERO
+
+# include <sys/mman.h>
+# ifndef MAP_FAILED
+# define MAP_FAILED -1
+# endif
+# define USING_MMAP
+
+#endif
+
+/* MinGW kludge. */
+#if defined(_WIN64) | defined(_WIN32)
+#define PRIdLL "I64d"
+#define PRIuLL "I64u"
+#else
+#define PRIdLL "lld"
+#define PRIuLL "llu"
+#endif
+
+/* Tru64 UNIX kludge. */
+#if defined(__alpha__) && defined(__osf__)
+/* Tru64 UNIX V4.0 doesn't support %lld/%lld, but long is 64-bit. */
+#undef PRIdLL
+#define PRIdLL "ld"
+#undef PRIuLL
+#define PRIuLL "lu"
+#define PRId8 "hd"
+#define PRIu8 "hu"
+#define PRId64 "ld"
+#define PRIu64 "lu"
+#define PRIuPTR "lu"
+#endif
+
+/* PA HP-UX kludge. */
+#if defined(__hppa__) && defined(__hpux__) && !defined(PRIuPTR)
+#define PRIuPTR "lu"
+#endif
+
+/* IRIX kludge. */
+#if defined(__sgi)
+/* IRIX 6.5 <inttypes.h> provides all definitions, but only for C99
+ compilations. */
+#define PRId8 "hhd"
+#define PRIu8 "hhu"
+#if (_MIPS_SZLONG == 32)
+#define PRId64 "lld"
+#define PRIu64 "llu"
+#endif
+/* This doesn't match <inttypes.h>, which always has "lld" here, but the
+ arguments are uint64_t, int64_t, which are unsigned long, long for
+ 64-bit in <sgidefs.h>. */
+#if (_MIPS_SZLONG == 64)
+#define PRId64 "ld"
+#define PRIu64 "lu"
+#endif
+/* This doesn't match <inttypes.h>, which has "u" here, but the arguments
+ are uintptr_t, which is always unsigned long. */
+#define PRIuPTR "lu"
+#endif
+
+/* Solaris < 10 kludge. */
+#if defined(__sun__) && defined(__svr4__) && !defined(PRIuPTR)
+#if defined(__arch64__) || defined (__x86_64__)
+#define PRIuPTR "lu"
+#else
+#define PRIuPTR "u"
+#endif
+#endif
+
+/* MSVC kludge. */
+#if defined _MSC_VER
+#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS)
+#define PRIuPTR "lu"
+#define PRIu8 "u"
+#define PRId8 "d"
+#define PRIu64 "I64u"
+#define PRId64 "I64d"
+#endif
+#endif
+
+#ifndef PRIuPTR
+#define PRIuPTR "u"
+#endif
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/huge_struct.c b/contrib/restricted/libffi/testsuite/libffi.closures/huge_struct.c
index a0170d549f..1915c3f1e8 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/huge_struct.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/huge_struct.c
@@ -1,341 +1,341 @@
-/* Area: ffi_call, closure_call
- Purpose: Check large structure returns.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/18/2007
-*/
-
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
-/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */
-/* { dg-options -Wformat=0 { target moxie*-*-elf or1k-*-* } } */
-
-#include "ffitest.h"
-
-typedef struct BigStruct{
- uint8_t a;
- int8_t b;
- uint16_t c;
- int16_t d;
- uint32_t e;
- int32_t f;
- uint64_t g;
- int64_t h;
- float i;
- double j;
- long double k;
- char* l;
- uint8_t m;
- int8_t n;
- uint16_t o;
- int16_t p;
- uint32_t q;
- int32_t r;
- uint64_t s;
- int64_t t;
- float u;
- double v;
- long double w;
- char* x;
- uint8_t y;
- int8_t z;
- uint16_t aa;
- int16_t bb;
- uint32_t cc;
- int32_t dd;
- uint64_t ee;
- int64_t ff;
- float gg;
- double hh;
- long double ii;
- char* jj;
- uint8_t kk;
- int8_t ll;
- uint16_t mm;
- int16_t nn;
- uint32_t oo;
- int32_t pp;
- uint64_t qq;
- int64_t rr;
- float ss;
- double tt;
- long double uu;
- char* vv;
- uint8_t ww;
- int8_t xx;
-} BigStruct;
-
-BigStruct
-test_large_fn(
- uint8_t ui8_1,
- int8_t si8_1,
- uint16_t ui16_1,
- int16_t si16_1,
- uint32_t ui32_1,
- int32_t si32_1,
- uint64_t ui64_1,
- int64_t si64_1,
- float f_1,
- double d_1,
- long double ld_1,
- char* p_1,
- uint8_t ui8_2,
- int8_t si8_2,
- uint16_t ui16_2,
- int16_t si16_2,
- uint32_t ui32_2,
- int32_t si32_2,
- uint64_t ui64_2,
- int64_t si64_2,
- float f_2,
- double d_2,
- long double ld_2,
- char* p_2,
- uint8_t ui8_3,
- int8_t si8_3,
- uint16_t ui16_3,
- int16_t si16_3,
- uint32_t ui32_3,
- int32_t si32_3,
- uint64_t ui64_3,
- int64_t si64_3,
- float f_3,
- double d_3,
- long double ld_3,
- char* p_3,
- uint8_t ui8_4,
- int8_t si8_4,
- uint16_t ui16_4,
- int16_t si16_4,
- uint32_t ui32_4,
- int32_t si32_4,
- uint64_t ui64_4,
- int64_t si64_4,
- float f_4,
- double d_4,
- long double ld_4,
- char* p_4,
- uint8_t ui8_5,
- int8_t si8_5)
-{
- BigStruct retVal = {
- ui8_1 + 1, si8_1 + 1, ui16_1 + 1, si16_1 + 1, ui32_1 + 1, si32_1 + 1,
- ui64_1 + 1, si64_1 + 1, f_1 + 1, d_1 + 1, ld_1 + 1, (char*)((intptr_t)p_1 + 1),
- ui8_2 + 2, si8_2 + 2, ui16_2 + 2, si16_2 + 2, ui32_2 + 2, si32_2 + 2,
- ui64_2 + 2, si64_2 + 2, f_2 + 2, d_2 + 2, ld_2 + 2, (char*)((intptr_t)p_2 + 2),
- ui8_3 + 3, si8_3 + 3, ui16_3 + 3, si16_3 + 3, ui32_3 + 3, si32_3 + 3,
- ui64_3 + 3, si64_3 + 3, f_3 + 3, d_3 + 3, ld_3 + 3, (char*)((intptr_t)p_3 + 3),
- ui8_4 + 4, si8_4 + 4, ui16_4 + 4, si16_4 + 4, ui32_4 + 4, si32_4 + 4,
- ui64_4 + 4, si64_4 + 4, f_4 + 4, d_4 + 4, ld_4 + 4, (char*)((intptr_t)p_4 + 4),
- ui8_5 + 5, si8_5 + 5};
-
- printf("%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 ": "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 "\n",
- ui8_1, si8_1, ui16_1, si16_1, ui32_1, si32_1, ui64_1, si64_1, f_1, d_1, ld_1, (unsigned long)p_1,
- ui8_2, si8_2, ui16_2, si16_2, ui32_2, si32_2, ui64_2, si64_2, f_2, d_2, ld_2, (unsigned long)p_2,
- ui8_3, si8_3, ui16_3, si16_3, ui32_3, si32_3, ui64_3, si64_3, f_3, d_3, ld_3, (unsigned long)p_3,
- ui8_4, si8_4, ui16_4, si16_4, ui32_4, si32_4, ui64_4, si64_4, f_4, d_4, ld_4, (unsigned long)p_4, ui8_5, si8_5,
- retVal.a, retVal.b, retVal.c, retVal.d, retVal.e, retVal.f,
- retVal.g, retVal.h, retVal.i, retVal.j, retVal.k, (unsigned long)retVal.l,
- retVal.m, retVal.n, retVal.o, retVal.p, retVal.q, retVal.r,
- retVal.s, retVal.t, retVal.u, retVal.v, retVal.w, (unsigned long)retVal.x,
- retVal.y, retVal.z, retVal.aa, retVal.bb, retVal.cc, retVal.dd,
- retVal.ee, retVal.ff, retVal.gg, retVal.hh, retVal.ii, (unsigned long)retVal.jj,
- retVal.kk, retVal.ll, retVal.mm, retVal.nn, retVal.oo, retVal.pp,
- retVal.qq, retVal.rr, retVal.ss, retVal.tt, retVal.uu, (unsigned long)retVal.vv, retVal.ww, retVal.xx);
-
- return retVal;
-}
-
-static void
-cls_large_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__)
-{
- uint8_t ui8_1 = *(uint8_t*)args[0];
- int8_t si8_1 = *(int8_t*)args[1];
- uint16_t ui16_1 = *(uint16_t*)args[2];
- int16_t si16_1 = *(int16_t*)args[3];
- uint32_t ui32_1 = *(uint32_t*)args[4];
- int32_t si32_1 = *(int32_t*)args[5];
- uint64_t ui64_1 = *(uint64_t*)args[6];
- int64_t si64_1 = *(int64_t*)args[7];
- float f_1 = *(float*)args[8];
- double d_1 = *(double*)args[9];
- long double ld_1 = *(long double*)args[10];
- char* p_1 = *(char**)args[11];
- uint8_t ui8_2 = *(uint8_t*)args[12];
- int8_t si8_2 = *(int8_t*)args[13];
- uint16_t ui16_2 = *(uint16_t*)args[14];
- int16_t si16_2 = *(int16_t*)args[15];
- uint32_t ui32_2 = *(uint32_t*)args[16];
- int32_t si32_2 = *(int32_t*)args[17];
- uint64_t ui64_2 = *(uint64_t*)args[18];
- int64_t si64_2 = *(int64_t*)args[19];
- float f_2 = *(float*)args[20];
- double d_2 = *(double*)args[21];
- long double ld_2 = *(long double*)args[22];
- char* p_2 = *(char**)args[23];
- uint8_t ui8_3 = *(uint8_t*)args[24];
- int8_t si8_3 = *(int8_t*)args[25];
- uint16_t ui16_3 = *(uint16_t*)args[26];
- int16_t si16_3 = *(int16_t*)args[27];
- uint32_t ui32_3 = *(uint32_t*)args[28];
- int32_t si32_3 = *(int32_t*)args[29];
- uint64_t ui64_3 = *(uint64_t*)args[30];
- int64_t si64_3 = *(int64_t*)args[31];
- float f_3 = *(float*)args[32];
- double d_3 = *(double*)args[33];
- long double ld_3 = *(long double*)args[34];
- char* p_3 = *(char**)args[35];
- uint8_t ui8_4 = *(uint8_t*)args[36];
- int8_t si8_4 = *(int8_t*)args[37];
- uint16_t ui16_4 = *(uint16_t*)args[38];
- int16_t si16_4 = *(int16_t*)args[39];
- uint32_t ui32_4 = *(uint32_t*)args[40];
- int32_t si32_4 = *(int32_t*)args[41];
- uint64_t ui64_4 = *(uint64_t*)args[42];
- int64_t si64_4 = *(int64_t*)args[43];
- float f_4 = *(float*)args[44];
- double d_4 = *(double*)args[45];
- long double ld_4 = *(long double*)args[46];
- char* p_4 = *(char**)args[47];
- uint8_t ui8_5 = *(uint8_t*)args[48];
- int8_t si8_5 = *(int8_t*)args[49];
-
- *(BigStruct*)resp = test_large_fn(
- ui8_1, si8_1, ui16_1, si16_1, ui32_1, si32_1, ui64_1, si64_1, f_1, d_1, ld_1, p_1,
- ui8_2, si8_2, ui16_2, si16_2, ui32_2, si32_2, ui64_2, si64_2, f_2, d_2, ld_2, p_2,
- ui8_3, si8_3, ui16_3, si16_3, ui32_3, si32_3, ui64_3, si64_3, f_3, d_3, ld_3, p_3,
- ui8_4, si8_4, ui16_4, si16_4, ui32_4, si32_4, ui64_4, si64_4, f_4, d_4, ld_4, p_4,
- ui8_5, si8_5);
-}
-
-int
-main(int argc __UNUSED__, const char** argv __UNUSED__)
-{
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
-
- ffi_cif cif;
- ffi_type* argTypes[51];
- void* argValues[51];
-
- ffi_type ret_struct_type;
- ffi_type* st_fields[51];
- BigStruct retVal;
-
- uint8_t ui8 = 1;
- int8_t si8 = 2;
- uint16_t ui16 = 3;
- int16_t si16 = 4;
- uint32_t ui32 = 5;
- int32_t si32 = 6;
- uint64_t ui64 = 7;
- int64_t si64 = 8;
- float f = 9;
- double d = 10;
- long double ld = 11;
- char* p = (char*)0x12345678;
-
- memset (&retVal, 0, sizeof(retVal));
-
- ret_struct_type.size = 0;
- ret_struct_type.alignment = 0;
- ret_struct_type.type = FFI_TYPE_STRUCT;
- ret_struct_type.elements = st_fields;
-
- st_fields[0] = st_fields[12] = st_fields[24] = st_fields[36] = st_fields[48] = &ffi_type_uint8;
- st_fields[1] = st_fields[13] = st_fields[25] = st_fields[37] = st_fields[49] = &ffi_type_sint8;
- st_fields[2] = st_fields[14] = st_fields[26] = st_fields[38] = &ffi_type_uint16;
- st_fields[3] = st_fields[15] = st_fields[27] = st_fields[39] = &ffi_type_sint16;
- st_fields[4] = st_fields[16] = st_fields[28] = st_fields[40] = &ffi_type_uint32;
- st_fields[5] = st_fields[17] = st_fields[29] = st_fields[41] = &ffi_type_sint32;
- st_fields[6] = st_fields[18] = st_fields[30] = st_fields[42] = &ffi_type_uint64;
- st_fields[7] = st_fields[19] = st_fields[31] = st_fields[43] = &ffi_type_sint64;
- st_fields[8] = st_fields[20] = st_fields[32] = st_fields[44] = &ffi_type_float;
- st_fields[9] = st_fields[21] = st_fields[33] = st_fields[45] = &ffi_type_double;
- st_fields[10] = st_fields[22] = st_fields[34] = st_fields[46] = &ffi_type_longdouble;
- st_fields[11] = st_fields[23] = st_fields[35] = st_fields[47] = &ffi_type_pointer;
-
- st_fields[50] = NULL;
-
- argTypes[0] = argTypes[12] = argTypes[24] = argTypes[36] = argTypes[48] = &ffi_type_uint8;
- argValues[0] = argValues[12] = argValues[24] = argValues[36] = argValues[48] = &ui8;
- argTypes[1] = argTypes[13] = argTypes[25] = argTypes[37] = argTypes[49] = &ffi_type_sint8;
- argValues[1] = argValues[13] = argValues[25] = argValues[37] = argValues[49] = &si8;
- argTypes[2] = argTypes[14] = argTypes[26] = argTypes[38] = &ffi_type_uint16;
- argValues[2] = argValues[14] = argValues[26] = argValues[38] = &ui16;
- argTypes[3] = argTypes[15] = argTypes[27] = argTypes[39] = &ffi_type_sint16;
- argValues[3] = argValues[15] = argValues[27] = argValues[39] = &si16;
- argTypes[4] = argTypes[16] = argTypes[28] = argTypes[40] = &ffi_type_uint32;
- argValues[4] = argValues[16] = argValues[28] = argValues[40] = &ui32;
- argTypes[5] = argTypes[17] = argTypes[29] = argTypes[41] = &ffi_type_sint32;
- argValues[5] = argValues[17] = argValues[29] = argValues[41] = &si32;
- argTypes[6] = argTypes[18] = argTypes[30] = argTypes[42] = &ffi_type_uint64;
- argValues[6] = argValues[18] = argValues[30] = argValues[42] = &ui64;
- argTypes[7] = argTypes[19] = argTypes[31] = argTypes[43] = &ffi_type_sint64;
- argValues[7] = argValues[19] = argValues[31] = argValues[43] = &si64;
- argTypes[8] = argTypes[20] = argTypes[32] = argTypes[44] = &ffi_type_float;
- argValues[8] = argValues[20] = argValues[32] = argValues[44] = &f;
- argTypes[9] = argTypes[21] = argTypes[33] = argTypes[45] = &ffi_type_double;
- argValues[9] = argValues[21] = argValues[33] = argValues[45] = &d;
- argTypes[10] = argTypes[22] = argTypes[34] = argTypes[46] = &ffi_type_longdouble;
- argValues[10] = argValues[22] = argValues[34] = argValues[46] = &ld;
- argTypes[11] = argTypes[23] = argTypes[35] = argTypes[47] = &ffi_type_pointer;
- argValues[11] = argValues[23] = argValues[35] = argValues[47] = &p;
-
- argTypes[50] = NULL;
- argValues[50] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 50, &ret_struct_type, argTypes) == FFI_OK);
-
- ffi_call(&cif, FFI_FN(test_large_fn), &retVal, argValues);
- /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */
- printf("res: %" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 "\n",
- retVal.a, retVal.b, retVal.c, retVal.d, retVal.e, retVal.f,
- retVal.g, retVal.h, retVal.i, retVal.j, retVal.k, (unsigned long)retVal.l,
- retVal.m, retVal.n, retVal.o, retVal.p, retVal.q, retVal.r,
- retVal.s, retVal.t, retVal.u, retVal.v, retVal.w, (unsigned long)retVal.x,
- retVal.y, retVal.z, retVal.aa, retVal.bb, retVal.cc, retVal.dd,
- retVal.ee, retVal.ff, retVal.gg, retVal.hh, retVal.ii, (unsigned long)retVal.jj,
- retVal.kk, retVal.ll, retVal.mm, retVal.nn, retVal.oo, retVal.pp,
- retVal.qq, retVal.rr, retVal.ss, retVal.tt, retVal.uu, (unsigned long)retVal.vv, retVal.ww, retVal.xx);
- /* { dg-output "\nres: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_large_fn, NULL, code) == FFI_OK);
-
- retVal = ((BigStruct(*)(
- uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*,
- uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*,
- uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*,
- uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*,
- uint8_t, int8_t))(code))(
- ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p,
- ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p,
- ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p,
- ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p,
- ui8, si8);
- /* { dg-output "\n1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */
- printf("res: %" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
- "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 "\n",
- retVal.a, retVal.b, retVal.c, retVal.d, retVal.e, retVal.f,
- retVal.g, retVal.h, retVal.i, retVal.j, retVal.k, (unsigned long)retVal.l,
- retVal.m, retVal.n, retVal.o, retVal.p, retVal.q, retVal.r,
- retVal.s, retVal.t, retVal.u, retVal.v, retVal.w, (unsigned long)retVal.x,
- retVal.y, retVal.z, retVal.aa, retVal.bb, retVal.cc, retVal.dd,
- retVal.ee, retVal.ff, retVal.gg, retVal.hh, retVal.ii, (unsigned long)retVal.jj,
- retVal.kk, retVal.ll, retVal.mm, retVal.nn, retVal.oo, retVal.pp,
- retVal.qq, retVal.rr, retVal.ss, retVal.tt, retVal.uu, (unsigned long)retVal.vv, retVal.ww, retVal.xx);
- /* { dg-output "\nres: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */
-
- return 0;
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check large structure returns.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/18/2007
+*/
+
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
+/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */
+/* { dg-options -Wformat=0 { target moxie*-*-elf or1k-*-* } } */
+
+#include "ffitest.h"
+
+typedef struct BigStruct{
+ uint8_t a;
+ int8_t b;
+ uint16_t c;
+ int16_t d;
+ uint32_t e;
+ int32_t f;
+ uint64_t g;
+ int64_t h;
+ float i;
+ double j;
+ long double k;
+ char* l;
+ uint8_t m;
+ int8_t n;
+ uint16_t o;
+ int16_t p;
+ uint32_t q;
+ int32_t r;
+ uint64_t s;
+ int64_t t;
+ float u;
+ double v;
+ long double w;
+ char* x;
+ uint8_t y;
+ int8_t z;
+ uint16_t aa;
+ int16_t bb;
+ uint32_t cc;
+ int32_t dd;
+ uint64_t ee;
+ int64_t ff;
+ float gg;
+ double hh;
+ long double ii;
+ char* jj;
+ uint8_t kk;
+ int8_t ll;
+ uint16_t mm;
+ int16_t nn;
+ uint32_t oo;
+ int32_t pp;
+ uint64_t qq;
+ int64_t rr;
+ float ss;
+ double tt;
+ long double uu;
+ char* vv;
+ uint8_t ww;
+ int8_t xx;
+} BigStruct;
+
+BigStruct
+test_large_fn(
+ uint8_t ui8_1,
+ int8_t si8_1,
+ uint16_t ui16_1,
+ int16_t si16_1,
+ uint32_t ui32_1,
+ int32_t si32_1,
+ uint64_t ui64_1,
+ int64_t si64_1,
+ float f_1,
+ double d_1,
+ long double ld_1,
+ char* p_1,
+ uint8_t ui8_2,
+ int8_t si8_2,
+ uint16_t ui16_2,
+ int16_t si16_2,
+ uint32_t ui32_2,
+ int32_t si32_2,
+ uint64_t ui64_2,
+ int64_t si64_2,
+ float f_2,
+ double d_2,
+ long double ld_2,
+ char* p_2,
+ uint8_t ui8_3,
+ int8_t si8_3,
+ uint16_t ui16_3,
+ int16_t si16_3,
+ uint32_t ui32_3,
+ int32_t si32_3,
+ uint64_t ui64_3,
+ int64_t si64_3,
+ float f_3,
+ double d_3,
+ long double ld_3,
+ char* p_3,
+ uint8_t ui8_4,
+ int8_t si8_4,
+ uint16_t ui16_4,
+ int16_t si16_4,
+ uint32_t ui32_4,
+ int32_t si32_4,
+ uint64_t ui64_4,
+ int64_t si64_4,
+ float f_4,
+ double d_4,
+ long double ld_4,
+ char* p_4,
+ uint8_t ui8_5,
+ int8_t si8_5)
+{
+ BigStruct retVal = {
+ ui8_1 + 1, si8_1 + 1, ui16_1 + 1, si16_1 + 1, ui32_1 + 1, si32_1 + 1,
+ ui64_1 + 1, si64_1 + 1, f_1 + 1, d_1 + 1, ld_1 + 1, (char*)((intptr_t)p_1 + 1),
+ ui8_2 + 2, si8_2 + 2, ui16_2 + 2, si16_2 + 2, ui32_2 + 2, si32_2 + 2,
+ ui64_2 + 2, si64_2 + 2, f_2 + 2, d_2 + 2, ld_2 + 2, (char*)((intptr_t)p_2 + 2),
+ ui8_3 + 3, si8_3 + 3, ui16_3 + 3, si16_3 + 3, ui32_3 + 3, si32_3 + 3,
+ ui64_3 + 3, si64_3 + 3, f_3 + 3, d_3 + 3, ld_3 + 3, (char*)((intptr_t)p_3 + 3),
+ ui8_4 + 4, si8_4 + 4, ui16_4 + 4, si16_4 + 4, ui32_4 + 4, si32_4 + 4,
+ ui64_4 + 4, si64_4 + 4, f_4 + 4, d_4 + 4, ld_4 + 4, (char*)((intptr_t)p_4 + 4),
+ ui8_5 + 5, si8_5 + 5};
+
+ printf("%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 ": "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 "\n",
+ ui8_1, si8_1, ui16_1, si16_1, ui32_1, si32_1, ui64_1, si64_1, f_1, d_1, ld_1, (unsigned long)p_1,
+ ui8_2, si8_2, ui16_2, si16_2, ui32_2, si32_2, ui64_2, si64_2, f_2, d_2, ld_2, (unsigned long)p_2,
+ ui8_3, si8_3, ui16_3, si16_3, ui32_3, si32_3, ui64_3, si64_3, f_3, d_3, ld_3, (unsigned long)p_3,
+ ui8_4, si8_4, ui16_4, si16_4, ui32_4, si32_4, ui64_4, si64_4, f_4, d_4, ld_4, (unsigned long)p_4, ui8_5, si8_5,
+ retVal.a, retVal.b, retVal.c, retVal.d, retVal.e, retVal.f,
+ retVal.g, retVal.h, retVal.i, retVal.j, retVal.k, (unsigned long)retVal.l,
+ retVal.m, retVal.n, retVal.o, retVal.p, retVal.q, retVal.r,
+ retVal.s, retVal.t, retVal.u, retVal.v, retVal.w, (unsigned long)retVal.x,
+ retVal.y, retVal.z, retVal.aa, retVal.bb, retVal.cc, retVal.dd,
+ retVal.ee, retVal.ff, retVal.gg, retVal.hh, retVal.ii, (unsigned long)retVal.jj,
+ retVal.kk, retVal.ll, retVal.mm, retVal.nn, retVal.oo, retVal.pp,
+ retVal.qq, retVal.rr, retVal.ss, retVal.tt, retVal.uu, (unsigned long)retVal.vv, retVal.ww, retVal.xx);
+
+ return retVal;
+}
+
+static void
+cls_large_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__)
+{
+ uint8_t ui8_1 = *(uint8_t*)args[0];
+ int8_t si8_1 = *(int8_t*)args[1];
+ uint16_t ui16_1 = *(uint16_t*)args[2];
+ int16_t si16_1 = *(int16_t*)args[3];
+ uint32_t ui32_1 = *(uint32_t*)args[4];
+ int32_t si32_1 = *(int32_t*)args[5];
+ uint64_t ui64_1 = *(uint64_t*)args[6];
+ int64_t si64_1 = *(int64_t*)args[7];
+ float f_1 = *(float*)args[8];
+ double d_1 = *(double*)args[9];
+ long double ld_1 = *(long double*)args[10];
+ char* p_1 = *(char**)args[11];
+ uint8_t ui8_2 = *(uint8_t*)args[12];
+ int8_t si8_2 = *(int8_t*)args[13];
+ uint16_t ui16_2 = *(uint16_t*)args[14];
+ int16_t si16_2 = *(int16_t*)args[15];
+ uint32_t ui32_2 = *(uint32_t*)args[16];
+ int32_t si32_2 = *(int32_t*)args[17];
+ uint64_t ui64_2 = *(uint64_t*)args[18];
+ int64_t si64_2 = *(int64_t*)args[19];
+ float f_2 = *(float*)args[20];
+ double d_2 = *(double*)args[21];
+ long double ld_2 = *(long double*)args[22];
+ char* p_2 = *(char**)args[23];
+ uint8_t ui8_3 = *(uint8_t*)args[24];
+ int8_t si8_3 = *(int8_t*)args[25];
+ uint16_t ui16_3 = *(uint16_t*)args[26];
+ int16_t si16_3 = *(int16_t*)args[27];
+ uint32_t ui32_3 = *(uint32_t*)args[28];
+ int32_t si32_3 = *(int32_t*)args[29];
+ uint64_t ui64_3 = *(uint64_t*)args[30];
+ int64_t si64_3 = *(int64_t*)args[31];
+ float f_3 = *(float*)args[32];
+ double d_3 = *(double*)args[33];
+ long double ld_3 = *(long double*)args[34];
+ char* p_3 = *(char**)args[35];
+ uint8_t ui8_4 = *(uint8_t*)args[36];
+ int8_t si8_4 = *(int8_t*)args[37];
+ uint16_t ui16_4 = *(uint16_t*)args[38];
+ int16_t si16_4 = *(int16_t*)args[39];
+ uint32_t ui32_4 = *(uint32_t*)args[40];
+ int32_t si32_4 = *(int32_t*)args[41];
+ uint64_t ui64_4 = *(uint64_t*)args[42];
+ int64_t si64_4 = *(int64_t*)args[43];
+ float f_4 = *(float*)args[44];
+ double d_4 = *(double*)args[45];
+ long double ld_4 = *(long double*)args[46];
+ char* p_4 = *(char**)args[47];
+ uint8_t ui8_5 = *(uint8_t*)args[48];
+ int8_t si8_5 = *(int8_t*)args[49];
+
+ *(BigStruct*)resp = test_large_fn(
+ ui8_1, si8_1, ui16_1, si16_1, ui32_1, si32_1, ui64_1, si64_1, f_1, d_1, ld_1, p_1,
+ ui8_2, si8_2, ui16_2, si16_2, ui32_2, si32_2, ui64_2, si64_2, f_2, d_2, ld_2, p_2,
+ ui8_3, si8_3, ui16_3, si16_3, ui32_3, si32_3, ui64_3, si64_3, f_3, d_3, ld_3, p_3,
+ ui8_4, si8_4, ui16_4, si16_4, ui32_4, si32_4, ui64_4, si64_4, f_4, d_4, ld_4, p_4,
+ ui8_5, si8_5);
+}
+
+int
+main(int argc __UNUSED__, const char** argv __UNUSED__)
+{
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+
+ ffi_cif cif;
+ ffi_type* argTypes[51];
+ void* argValues[51];
+
+ ffi_type ret_struct_type;
+ ffi_type* st_fields[51];
+ BigStruct retVal;
+
+ uint8_t ui8 = 1;
+ int8_t si8 = 2;
+ uint16_t ui16 = 3;
+ int16_t si16 = 4;
+ uint32_t ui32 = 5;
+ int32_t si32 = 6;
+ uint64_t ui64 = 7;
+ int64_t si64 = 8;
+ float f = 9;
+ double d = 10;
+ long double ld = 11;
+ char* p = (char*)0x12345678;
+
+ memset (&retVal, 0, sizeof(retVal));
+
+ ret_struct_type.size = 0;
+ ret_struct_type.alignment = 0;
+ ret_struct_type.type = FFI_TYPE_STRUCT;
+ ret_struct_type.elements = st_fields;
+
+ st_fields[0] = st_fields[12] = st_fields[24] = st_fields[36] = st_fields[48] = &ffi_type_uint8;
+ st_fields[1] = st_fields[13] = st_fields[25] = st_fields[37] = st_fields[49] = &ffi_type_sint8;
+ st_fields[2] = st_fields[14] = st_fields[26] = st_fields[38] = &ffi_type_uint16;
+ st_fields[3] = st_fields[15] = st_fields[27] = st_fields[39] = &ffi_type_sint16;
+ st_fields[4] = st_fields[16] = st_fields[28] = st_fields[40] = &ffi_type_uint32;
+ st_fields[5] = st_fields[17] = st_fields[29] = st_fields[41] = &ffi_type_sint32;
+ st_fields[6] = st_fields[18] = st_fields[30] = st_fields[42] = &ffi_type_uint64;
+ st_fields[7] = st_fields[19] = st_fields[31] = st_fields[43] = &ffi_type_sint64;
+ st_fields[8] = st_fields[20] = st_fields[32] = st_fields[44] = &ffi_type_float;
+ st_fields[9] = st_fields[21] = st_fields[33] = st_fields[45] = &ffi_type_double;
+ st_fields[10] = st_fields[22] = st_fields[34] = st_fields[46] = &ffi_type_longdouble;
+ st_fields[11] = st_fields[23] = st_fields[35] = st_fields[47] = &ffi_type_pointer;
+
+ st_fields[50] = NULL;
+
+ argTypes[0] = argTypes[12] = argTypes[24] = argTypes[36] = argTypes[48] = &ffi_type_uint8;
+ argValues[0] = argValues[12] = argValues[24] = argValues[36] = argValues[48] = &ui8;
+ argTypes[1] = argTypes[13] = argTypes[25] = argTypes[37] = argTypes[49] = &ffi_type_sint8;
+ argValues[1] = argValues[13] = argValues[25] = argValues[37] = argValues[49] = &si8;
+ argTypes[2] = argTypes[14] = argTypes[26] = argTypes[38] = &ffi_type_uint16;
+ argValues[2] = argValues[14] = argValues[26] = argValues[38] = &ui16;
+ argTypes[3] = argTypes[15] = argTypes[27] = argTypes[39] = &ffi_type_sint16;
+ argValues[3] = argValues[15] = argValues[27] = argValues[39] = &si16;
+ argTypes[4] = argTypes[16] = argTypes[28] = argTypes[40] = &ffi_type_uint32;
+ argValues[4] = argValues[16] = argValues[28] = argValues[40] = &ui32;
+ argTypes[5] = argTypes[17] = argTypes[29] = argTypes[41] = &ffi_type_sint32;
+ argValues[5] = argValues[17] = argValues[29] = argValues[41] = &si32;
+ argTypes[6] = argTypes[18] = argTypes[30] = argTypes[42] = &ffi_type_uint64;
+ argValues[6] = argValues[18] = argValues[30] = argValues[42] = &ui64;
+ argTypes[7] = argTypes[19] = argTypes[31] = argTypes[43] = &ffi_type_sint64;
+ argValues[7] = argValues[19] = argValues[31] = argValues[43] = &si64;
+ argTypes[8] = argTypes[20] = argTypes[32] = argTypes[44] = &ffi_type_float;
+ argValues[8] = argValues[20] = argValues[32] = argValues[44] = &f;
+ argTypes[9] = argTypes[21] = argTypes[33] = argTypes[45] = &ffi_type_double;
+ argValues[9] = argValues[21] = argValues[33] = argValues[45] = &d;
+ argTypes[10] = argTypes[22] = argTypes[34] = argTypes[46] = &ffi_type_longdouble;
+ argValues[10] = argValues[22] = argValues[34] = argValues[46] = &ld;
+ argTypes[11] = argTypes[23] = argTypes[35] = argTypes[47] = &ffi_type_pointer;
+ argValues[11] = argValues[23] = argValues[35] = argValues[47] = &p;
+
+ argTypes[50] = NULL;
+ argValues[50] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 50, &ret_struct_type, argTypes) == FFI_OK);
+
+ ffi_call(&cif, FFI_FN(test_large_fn), &retVal, argValues);
+ /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */
+ printf("res: %" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 "\n",
+ retVal.a, retVal.b, retVal.c, retVal.d, retVal.e, retVal.f,
+ retVal.g, retVal.h, retVal.i, retVal.j, retVal.k, (unsigned long)retVal.l,
+ retVal.m, retVal.n, retVal.o, retVal.p, retVal.q, retVal.r,
+ retVal.s, retVal.t, retVal.u, retVal.v, retVal.w, (unsigned long)retVal.x,
+ retVal.y, retVal.z, retVal.aa, retVal.bb, retVal.cc, retVal.dd,
+ retVal.ee, retVal.ff, retVal.gg, retVal.hh, retVal.ii, (unsigned long)retVal.jj,
+ retVal.kk, retVal.ll, retVal.mm, retVal.nn, retVal.oo, retVal.pp,
+ retVal.qq, retVal.rr, retVal.ss, retVal.tt, retVal.uu, (unsigned long)retVal.vv, retVal.ww, retVal.xx);
+ /* { dg-output "\nres: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_large_fn, NULL, code) == FFI_OK);
+
+ retVal = ((BigStruct(*)(
+ uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*,
+ uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*,
+ uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*,
+ uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*,
+ uint8_t, int8_t))(code))(
+ ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p,
+ ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p,
+ ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p,
+ ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p,
+ ui8, si8);
+ /* { dg-output "\n1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */
+ printf("res: %" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx "
+ "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 "\n",
+ retVal.a, retVal.b, retVal.c, retVal.d, retVal.e, retVal.f,
+ retVal.g, retVal.h, retVal.i, retVal.j, retVal.k, (unsigned long)retVal.l,
+ retVal.m, retVal.n, retVal.o, retVal.p, retVal.q, retVal.r,
+ retVal.s, retVal.t, retVal.u, retVal.v, retVal.w, (unsigned long)retVal.x,
+ retVal.y, retVal.z, retVal.aa, retVal.bb, retVal.cc, retVal.dd,
+ retVal.ee, retVal.ff, retVal.gg, retVal.hh, retVal.ii, (unsigned long)retVal.jj,
+ retVal.kk, retVal.ll, retVal.mm, retVal.nn, retVal.oo, retVal.pp,
+ retVal.qq, retVal.rr, retVal.ss, retVal.tt, retVal.uu, (unsigned long)retVal.vv, retVal.ww, retVal.xx);
+ /* { dg-output "\nres: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */
+
+ return 0;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/huge_struct/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/huge_struct/ya.make
index 7bec56c432..7d2e07b233 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/huge_struct/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/huge_struct/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- huge_struct.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ huge_struct.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct.c
index f3a18a0fe5..c15e3a0338 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct.c
@@ -1,152 +1,152 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Contains structs as parameter of the struct itself.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_16byte1 {
- double a;
- float b;
- int c;
-} cls_struct_16byte1;
-
-typedef struct cls_struct_16byte2 {
- int ii;
- double dd;
- float ff;
-} cls_struct_16byte2;
-
-typedef struct cls_struct_combined {
- cls_struct_16byte1 d;
- cls_struct_16byte2 e;
-} cls_struct_combined;
-
-cls_struct_combined cls_struct_combined_fn(struct cls_struct_16byte1 b0,
- struct cls_struct_16byte2 b1,
- struct cls_struct_combined b2)
-{
- struct cls_struct_combined result;
-
- result.d.a = b0.a + b1.dd + b2.d.a;
- result.d.b = b0.b + b1.ff + b2.d.b;
- result.d.c = b0.c + b1.ii + b2.d.c;
- result.e.ii = b0.c + b1.ii + b2.e.ii;
- result.e.dd = b0.a + b1.dd + b2.e.dd;
- result.e.ff = b0.b + b1.ff + b2.e.ff;
-
- printf("%g %g %d %d %g %g %g %g %d %d %g %g: %g %g %d %d %g %g\n",
- b0.a, b0.b, b0.c,
- b1.ii, b1.dd, b1.ff,
- b2.d.a, b2.d.b, b2.d.c,
- b2.e.ii, b2.e.dd, b2.e.ff,
- result.d.a, result.d.b, result.d.c,
- result.e.ii, result.e.dd, result.e.ff);
-
- return result;
-}
-
-static void
-cls_struct_combined_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct cls_struct_16byte1 b0;
- struct cls_struct_16byte2 b1;
- struct cls_struct_combined b2;
-
- b0 = *(struct cls_struct_16byte1*)(args[0]);
- b1 = *(struct cls_struct_16byte2*)(args[1]);
- b2 = *(struct cls_struct_combined*)(args[2]);
-
-
- *(cls_struct_combined*)resp = cls_struct_combined_fn(b0, b1, b2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[5];
- ffi_type* cls_struct_fields1[5];
- ffi_type* cls_struct_fields2[5];
- ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_16byte1 e_dbl = { 9.0, 2.0, 6};
- struct cls_struct_16byte2 f_dbl = { 1, 2.0, 3.0};
- struct cls_struct_combined g_dbl = {{4.0, 5.0, 6},
- {3, 1.0, 8.0}};
- struct cls_struct_combined res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_type1.size = 0;
- cls_struct_type1.alignment = 0;
- cls_struct_type1.type = FFI_TYPE_STRUCT;
- cls_struct_type1.elements = cls_struct_fields1;
-
- cls_struct_type2.size = 0;
- cls_struct_type2.alignment = 0;
- cls_struct_type2.type = FFI_TYPE_STRUCT;
- cls_struct_type2.elements = cls_struct_fields2;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_float;
- cls_struct_fields[2] = &ffi_type_sint;
- cls_struct_fields[3] = NULL;
-
- cls_struct_fields1[0] = &ffi_type_sint;
- cls_struct_fields1[1] = &ffi_type_double;
- cls_struct_fields1[2] = &ffi_type_float;
- cls_struct_fields1[3] = NULL;
-
- cls_struct_fields2[0] = &cls_struct_type;
- cls_struct_fields2[1] = &cls_struct_type1;
- cls_struct_fields2[2] = NULL;
-
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type1;
- dbl_arg_types[2] = &cls_struct_type2;
- dbl_arg_types[3] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type2,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_combined_fn), &res_dbl, args_dbl);
- /* { dg-output "9 2 6 1 2 3 4 5 6 3 1 8: 15 10 13 10 12 13" } */
- CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a));
- CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b));
- CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c));
- CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii));
- CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd));
- CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff));
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_combined_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_combined(*)(cls_struct_16byte1,
- cls_struct_16byte2,
- cls_struct_combined))
- (code))(e_dbl, f_dbl, g_dbl);
- /* { dg-output "\n9 2 6 1 2 3 4 5 6 3 1 8: 15 10 13 10 12 13" } */
- CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a));
- CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b));
- CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c));
- CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii));
- CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd));
- CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff));
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Contains structs as parameter of the struct itself.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_16byte1 {
+ double a;
+ float b;
+ int c;
+} cls_struct_16byte1;
+
+typedef struct cls_struct_16byte2 {
+ int ii;
+ double dd;
+ float ff;
+} cls_struct_16byte2;
+
+typedef struct cls_struct_combined {
+ cls_struct_16byte1 d;
+ cls_struct_16byte2 e;
+} cls_struct_combined;
+
+cls_struct_combined cls_struct_combined_fn(struct cls_struct_16byte1 b0,
+ struct cls_struct_16byte2 b1,
+ struct cls_struct_combined b2)
+{
+ struct cls_struct_combined result;
+
+ result.d.a = b0.a + b1.dd + b2.d.a;
+ result.d.b = b0.b + b1.ff + b2.d.b;
+ result.d.c = b0.c + b1.ii + b2.d.c;
+ result.e.ii = b0.c + b1.ii + b2.e.ii;
+ result.e.dd = b0.a + b1.dd + b2.e.dd;
+ result.e.ff = b0.b + b1.ff + b2.e.ff;
+
+ printf("%g %g %d %d %g %g %g %g %d %d %g %g: %g %g %d %d %g %g\n",
+ b0.a, b0.b, b0.c,
+ b1.ii, b1.dd, b1.ff,
+ b2.d.a, b2.d.b, b2.d.c,
+ b2.e.ii, b2.e.dd, b2.e.ff,
+ result.d.a, result.d.b, result.d.c,
+ result.e.ii, result.e.dd, result.e.ff);
+
+ return result;
+}
+
+static void
+cls_struct_combined_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct cls_struct_16byte1 b0;
+ struct cls_struct_16byte2 b1;
+ struct cls_struct_combined b2;
+
+ b0 = *(struct cls_struct_16byte1*)(args[0]);
+ b1 = *(struct cls_struct_16byte2*)(args[1]);
+ b2 = *(struct cls_struct_combined*)(args[2]);
+
+
+ *(cls_struct_combined*)resp = cls_struct_combined_fn(b0, b1, b2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[5];
+ ffi_type* cls_struct_fields1[5];
+ ffi_type* cls_struct_fields2[5];
+ ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_16byte1 e_dbl = { 9.0, 2.0, 6};
+ struct cls_struct_16byte2 f_dbl = { 1, 2.0, 3.0};
+ struct cls_struct_combined g_dbl = {{4.0, 5.0, 6},
+ {3, 1.0, 8.0}};
+ struct cls_struct_combined res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_type1.size = 0;
+ cls_struct_type1.alignment = 0;
+ cls_struct_type1.type = FFI_TYPE_STRUCT;
+ cls_struct_type1.elements = cls_struct_fields1;
+
+ cls_struct_type2.size = 0;
+ cls_struct_type2.alignment = 0;
+ cls_struct_type2.type = FFI_TYPE_STRUCT;
+ cls_struct_type2.elements = cls_struct_fields2;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_float;
+ cls_struct_fields[2] = &ffi_type_sint;
+ cls_struct_fields[3] = NULL;
+
+ cls_struct_fields1[0] = &ffi_type_sint;
+ cls_struct_fields1[1] = &ffi_type_double;
+ cls_struct_fields1[2] = &ffi_type_float;
+ cls_struct_fields1[3] = NULL;
+
+ cls_struct_fields2[0] = &cls_struct_type;
+ cls_struct_fields2[1] = &cls_struct_type1;
+ cls_struct_fields2[2] = NULL;
+
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type1;
+ dbl_arg_types[2] = &cls_struct_type2;
+ dbl_arg_types[3] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type2,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_combined_fn), &res_dbl, args_dbl);
+ /* { dg-output "9 2 6 1 2 3 4 5 6 3 1 8: 15 10 13 10 12 13" } */
+ CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a));
+ CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b));
+ CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c));
+ CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii));
+ CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd));
+ CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff));
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_combined_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_combined(*)(cls_struct_16byte1,
+ cls_struct_16byte2,
+ cls_struct_combined))
+ (code))(e_dbl, f_dbl, g_dbl);
+ /* { dg-output "\n9 2 6 1 2 3 4 5 6 3 1 8: 15 10 13 10 12 13" } */
+ CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a));
+ CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b));
+ CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c));
+ CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii));
+ CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd));
+ CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff));
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct/ya.make
index af96f71d89..6e5232236a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct1.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct1.c
index d782f31b07..477a6b9bde 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct1.c
@@ -1,161 +1,161 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Contains structs as parameter of the struct itself.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_16byte1 {
- double a;
- float b;
- int c;
-} cls_struct_16byte1;
-
-typedef struct cls_struct_16byte2 {
- int ii;
- double dd;
- float ff;
-} cls_struct_16byte2;
-
-typedef struct cls_struct_combined {
- cls_struct_16byte1 d;
- cls_struct_16byte2 e;
-} cls_struct_combined;
-
-cls_struct_combined cls_struct_combined_fn(struct cls_struct_16byte1 b0,
- struct cls_struct_16byte2 b1,
- struct cls_struct_combined b2,
- struct cls_struct_16byte1 b3)
-{
- struct cls_struct_combined result;
-
- result.d.a = b0.a + b1.dd + b2.d.a;
- result.d.b = b0.b + b1.ff + b2.d.b;
- result.d.c = b0.c + b1.ii + b2.d.c;
- result.e.ii = b0.c + b1.ii + b2.e.ii;
- result.e.dd = b0.a + b1.dd + b2.e.dd;
- result.e.ff = b0.b + b1.ff + b2.e.ff;
-
- printf("%g %g %d %d %g %g %g %g %d %d %g %g %g %g %d: %g %g %d %d %g %g\n",
- b0.a, b0.b, b0.c,
- b1.ii, b1.dd, b1.ff,
- b2.d.a, b2.d.b, b2.d.c,
- b2.e.ii, b2.e.dd, b2.e.ff,
- b3.a, b3.b, b3.c,
- result.d.a, result.d.b, result.d.c,
- result.e.ii, result.e.dd, result.e.ff);
-
- return result;
-}
-
-static void
-cls_struct_combined_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct cls_struct_16byte1 b0;
- struct cls_struct_16byte2 b1;
- struct cls_struct_combined b2;
- struct cls_struct_16byte1 b3;
-
- b0 = *(struct cls_struct_16byte1*)(args[0]);
- b1 = *(struct cls_struct_16byte2*)(args[1]);
- b2 = *(struct cls_struct_combined*)(args[2]);
- b3 = *(struct cls_struct_16byte1*)(args[3]);
-
-
- *(cls_struct_combined*)resp = cls_struct_combined_fn(b0, b1, b2, b3);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[5];
- ffi_type* cls_struct_fields1[5];
- ffi_type* cls_struct_fields2[5];
- ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_16byte1 e_dbl = { 9.0, 2.0, 6};
- struct cls_struct_16byte2 f_dbl = { 1, 2.0, 3.0};
- struct cls_struct_combined g_dbl = {{4.0, 5.0, 6},
- {3, 1.0, 8.0}};
- struct cls_struct_16byte1 h_dbl = { 3.0, 2.0, 4};
- struct cls_struct_combined res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_type1.size = 0;
- cls_struct_type1.alignment = 0;
- cls_struct_type1.type = FFI_TYPE_STRUCT;
- cls_struct_type1.elements = cls_struct_fields1;
-
- cls_struct_type2.size = 0;
- cls_struct_type2.alignment = 0;
- cls_struct_type2.type = FFI_TYPE_STRUCT;
- cls_struct_type2.elements = cls_struct_fields2;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_float;
- cls_struct_fields[2] = &ffi_type_sint;
- cls_struct_fields[3] = NULL;
-
- cls_struct_fields1[0] = &ffi_type_sint;
- cls_struct_fields1[1] = &ffi_type_double;
- cls_struct_fields1[2] = &ffi_type_float;
- cls_struct_fields1[3] = NULL;
-
- cls_struct_fields2[0] = &cls_struct_type;
- cls_struct_fields2[1] = &cls_struct_type1;
- cls_struct_fields2[2] = NULL;
-
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type1;
- dbl_arg_types[2] = &cls_struct_type2;
- dbl_arg_types[3] = &cls_struct_type;
- dbl_arg_types[4] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type2,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = &h_dbl;
- args_dbl[4] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_combined_fn), &res_dbl, args_dbl);
- /* { dg-output "9 2 6 1 2 3 4 5 6 3 1 8 3 2 4: 15 10 13 10 12 13" } */
- CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a));
- CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b));
- CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c));
- CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii));
- CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd));
- CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff));
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_combined_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((cls_struct_combined(*)(cls_struct_16byte1,
- cls_struct_16byte2,
- cls_struct_combined,
- cls_struct_16byte1))
- (code))(e_dbl, f_dbl, g_dbl, h_dbl);
- /* { dg-output "\n9 2 6 1 2 3 4 5 6 3 1 8 3 2 4: 15 10 13 10 12 13" } */
- CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a));
- CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b));
- CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c));
- CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii));
- CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd));
- CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff));
- /* CHECK( 1 == 0); */
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Contains structs as parameter of the struct itself.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_16byte1 {
+ double a;
+ float b;
+ int c;
+} cls_struct_16byte1;
+
+typedef struct cls_struct_16byte2 {
+ int ii;
+ double dd;
+ float ff;
+} cls_struct_16byte2;
+
+typedef struct cls_struct_combined {
+ cls_struct_16byte1 d;
+ cls_struct_16byte2 e;
+} cls_struct_combined;
+
+cls_struct_combined cls_struct_combined_fn(struct cls_struct_16byte1 b0,
+ struct cls_struct_16byte2 b1,
+ struct cls_struct_combined b2,
+ struct cls_struct_16byte1 b3)
+{
+ struct cls_struct_combined result;
+
+ result.d.a = b0.a + b1.dd + b2.d.a;
+ result.d.b = b0.b + b1.ff + b2.d.b;
+ result.d.c = b0.c + b1.ii + b2.d.c;
+ result.e.ii = b0.c + b1.ii + b2.e.ii;
+ result.e.dd = b0.a + b1.dd + b2.e.dd;
+ result.e.ff = b0.b + b1.ff + b2.e.ff;
+
+ printf("%g %g %d %d %g %g %g %g %d %d %g %g %g %g %d: %g %g %d %d %g %g\n",
+ b0.a, b0.b, b0.c,
+ b1.ii, b1.dd, b1.ff,
+ b2.d.a, b2.d.b, b2.d.c,
+ b2.e.ii, b2.e.dd, b2.e.ff,
+ b3.a, b3.b, b3.c,
+ result.d.a, result.d.b, result.d.c,
+ result.e.ii, result.e.dd, result.e.ff);
+
+ return result;
+}
+
+static void
+cls_struct_combined_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct cls_struct_16byte1 b0;
+ struct cls_struct_16byte2 b1;
+ struct cls_struct_combined b2;
+ struct cls_struct_16byte1 b3;
+
+ b0 = *(struct cls_struct_16byte1*)(args[0]);
+ b1 = *(struct cls_struct_16byte2*)(args[1]);
+ b2 = *(struct cls_struct_combined*)(args[2]);
+ b3 = *(struct cls_struct_16byte1*)(args[3]);
+
+
+ *(cls_struct_combined*)resp = cls_struct_combined_fn(b0, b1, b2, b3);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[5];
+ ffi_type* cls_struct_fields1[5];
+ ffi_type* cls_struct_fields2[5];
+ ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_16byte1 e_dbl = { 9.0, 2.0, 6};
+ struct cls_struct_16byte2 f_dbl = { 1, 2.0, 3.0};
+ struct cls_struct_combined g_dbl = {{4.0, 5.0, 6},
+ {3, 1.0, 8.0}};
+ struct cls_struct_16byte1 h_dbl = { 3.0, 2.0, 4};
+ struct cls_struct_combined res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_type1.size = 0;
+ cls_struct_type1.alignment = 0;
+ cls_struct_type1.type = FFI_TYPE_STRUCT;
+ cls_struct_type1.elements = cls_struct_fields1;
+
+ cls_struct_type2.size = 0;
+ cls_struct_type2.alignment = 0;
+ cls_struct_type2.type = FFI_TYPE_STRUCT;
+ cls_struct_type2.elements = cls_struct_fields2;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_float;
+ cls_struct_fields[2] = &ffi_type_sint;
+ cls_struct_fields[3] = NULL;
+
+ cls_struct_fields1[0] = &ffi_type_sint;
+ cls_struct_fields1[1] = &ffi_type_double;
+ cls_struct_fields1[2] = &ffi_type_float;
+ cls_struct_fields1[3] = NULL;
+
+ cls_struct_fields2[0] = &cls_struct_type;
+ cls_struct_fields2[1] = &cls_struct_type1;
+ cls_struct_fields2[2] = NULL;
+
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type1;
+ dbl_arg_types[2] = &cls_struct_type2;
+ dbl_arg_types[3] = &cls_struct_type;
+ dbl_arg_types[4] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type2,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = &h_dbl;
+ args_dbl[4] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_combined_fn), &res_dbl, args_dbl);
+ /* { dg-output "9 2 6 1 2 3 4 5 6 3 1 8 3 2 4: 15 10 13 10 12 13" } */
+ CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a));
+ CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b));
+ CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c));
+ CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii));
+ CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd));
+ CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff));
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_combined_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((cls_struct_combined(*)(cls_struct_16byte1,
+ cls_struct_16byte2,
+ cls_struct_combined,
+ cls_struct_16byte1))
+ (code))(e_dbl, f_dbl, g_dbl, h_dbl);
+ /* { dg-output "\n9 2 6 1 2 3 4 5 6 3 1 8 3 2 4: 15 10 13 10 12 13" } */
+ CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a));
+ CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b));
+ CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c));
+ CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii));
+ CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd));
+ CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff));
+ /* CHECK( 1 == 0); */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct1/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct1/ya.make
index 10713d2f2b..89f922394c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct10.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct10.c
index 8b4fd6f62d..3cf2b44abe 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct10.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct10.c
@@ -1,134 +1,134 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Contains structs as parameter of the struct itself.
- Sample taken from Alan Modras patch to src/prep_cif.c.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20051010 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct A {
- unsigned long long a;
- unsigned char b;
-} A;
-
-typedef struct B {
- unsigned char y;
- struct A x;
- unsigned int z;
-} B;
-
-typedef struct C {
- unsigned long long d;
- unsigned char e;
-} C;
-
-static B B_fn(struct A b2, struct B b3, struct C b4)
-{
- struct B result;
-
- result.x.a = b2.a + b3.x.a + b3.z + b4.d;
- result.x.b = b2.b + b3.x.b + b3.y + b4.e;
- result.y = b2.b + b3.x.b + b4.e;
- result.z = 0;
-
- printf("%d %d %d %d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
- (int)b3.x.a, b3.x.b, b3.y, b3.z, (int)b4.d, b4.e,
- (int)result.x.a, result.x.b, result.y);
-
- return result;
-}
-
-static void
-B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct A b0;
- struct B b1;
- struct C b2;
-
- b0 = *(struct A*)(args[0]);
- b1 = *(struct B*)(args[1]);
- b2 = *(struct C*)(args[2]);
-
- *(B*)resp = B_fn(b0, b1, b2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[4];
- ffi_type* cls_struct_fields[3];
- ffi_type* cls_struct_fields1[4];
- ffi_type* cls_struct_fields2[3];
- ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
- ffi_type* dbl_arg_types[4];
-
- struct A e_dbl = { 1LL, 7};
- struct B f_dbl = { 99, {12LL , 127}, 255};
- struct C g_dbl = { 2LL, 9};
-
- struct B res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_type1.size = 0;
- cls_struct_type1.alignment = 0;
- cls_struct_type1.type = FFI_TYPE_STRUCT;
- cls_struct_type1.elements = cls_struct_fields1;
-
- cls_struct_type2.size = 0;
- cls_struct_type2.alignment = 0;
- cls_struct_type2.type = FFI_TYPE_STRUCT;
- cls_struct_type2.elements = cls_struct_fields2;
-
- cls_struct_fields[0] = &ffi_type_uint64;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = NULL;
-
- cls_struct_fields1[0] = &ffi_type_uchar;
- cls_struct_fields1[1] = &cls_struct_type;
- cls_struct_fields1[2] = &ffi_type_uint;
- cls_struct_fields1[3] = NULL;
-
- cls_struct_fields2[0] = &ffi_type_uint64;
- cls_struct_fields2[1] = &ffi_type_uchar;
- cls_struct_fields2[2] = NULL;
-
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type1;
- dbl_arg_types[2] = &cls_struct_type2;
- dbl_arg_types[3] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = NULL;
-
- ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
- /* { dg-output "1 7 12 127 99 255 2 9: 270 242 143" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + f_dbl.z + g_dbl.d));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl);
- /* { dg-output "\n1 7 12 127 99 255 2 9: 270 242 143" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + f_dbl.z + g_dbl.d));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Contains structs as parameter of the struct itself.
+ Sample taken from Alan Modras patch to src/prep_cif.c.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20051010 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct A {
+ unsigned long long a;
+ unsigned char b;
+} A;
+
+typedef struct B {
+ unsigned char y;
+ struct A x;
+ unsigned int z;
+} B;
+
+typedef struct C {
+ unsigned long long d;
+ unsigned char e;
+} C;
+
+static B B_fn(struct A b2, struct B b3, struct C b4)
+{
+ struct B result;
+
+ result.x.a = b2.a + b3.x.a + b3.z + b4.d;
+ result.x.b = b2.b + b3.x.b + b3.y + b4.e;
+ result.y = b2.b + b3.x.b + b4.e;
+ result.z = 0;
+
+ printf("%d %d %d %d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
+ (int)b3.x.a, b3.x.b, b3.y, b3.z, (int)b4.d, b4.e,
+ (int)result.x.a, result.x.b, result.y);
+
+ return result;
+}
+
+static void
+B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct A b0;
+ struct B b1;
+ struct C b2;
+
+ b0 = *(struct A*)(args[0]);
+ b1 = *(struct B*)(args[1]);
+ b2 = *(struct C*)(args[2]);
+
+ *(B*)resp = B_fn(b0, b1, b2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[4];
+ ffi_type* cls_struct_fields[3];
+ ffi_type* cls_struct_fields1[4];
+ ffi_type* cls_struct_fields2[3];
+ ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
+ ffi_type* dbl_arg_types[4];
+
+ struct A e_dbl = { 1LL, 7};
+ struct B f_dbl = { 99, {12LL , 127}, 255};
+ struct C g_dbl = { 2LL, 9};
+
+ struct B res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_type1.size = 0;
+ cls_struct_type1.alignment = 0;
+ cls_struct_type1.type = FFI_TYPE_STRUCT;
+ cls_struct_type1.elements = cls_struct_fields1;
+
+ cls_struct_type2.size = 0;
+ cls_struct_type2.alignment = 0;
+ cls_struct_type2.type = FFI_TYPE_STRUCT;
+ cls_struct_type2.elements = cls_struct_fields2;
+
+ cls_struct_fields[0] = &ffi_type_uint64;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = NULL;
+
+ cls_struct_fields1[0] = &ffi_type_uchar;
+ cls_struct_fields1[1] = &cls_struct_type;
+ cls_struct_fields1[2] = &ffi_type_uint;
+ cls_struct_fields1[3] = NULL;
+
+ cls_struct_fields2[0] = &ffi_type_uint64;
+ cls_struct_fields2[1] = &ffi_type_uchar;
+ cls_struct_fields2[2] = NULL;
+
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type1;
+ dbl_arg_types[2] = &cls_struct_type2;
+ dbl_arg_types[3] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = NULL;
+
+ ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 7 12 127 99 255 2 9: 270 242 143" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + f_dbl.z + g_dbl.d));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl);
+ /* { dg-output "\n1 7 12 127 99 255 2 9: 270 242 143" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + f_dbl.z + g_dbl.d));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct10/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct10/ya.make
index 15ebfa55e1..be040d0dec 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct10/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct10/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct10.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct10.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct11.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct11.c
index c8402480b6..351049382c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct11.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct11.c
@@ -1,121 +1,121 @@
-/* Area: ffi_call, closure_call
- Purpose: Check parameter passing with nested structs
- of a single type. This tests the special cases
- for homogeneous floating-point aggregates in the
- AArch64 PCS.
- Limitations: none.
- PR: none.
- Originator: ARM Ltd. */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct A {
- float a_x;
- float a_y;
-} A;
-
-typedef struct B {
- float b_x;
- float b_y;
-} B;
-
-typedef struct C {
- A a;
- B b;
-} C;
-
-static C C_fn (int x, int y, int z, C source, int i, int j, int k)
-{
- C result;
- result.a.a_x = source.a.a_x;
- result.a.a_y = source.a.a_y;
- result.b.b_x = source.b.b_x;
- result.b.b_y = source.b.b_y;
-
- printf ("%d, %d, %d, %d, %d, %d\n", x, y, z, i, j, k);
-
- printf ("%.1f, %.1f, %.1f, %.1f, "
- "%.1f, %.1f, %.1f, %.1f\n",
- source.a.a_x, source.a.a_y,
- source.b.b_x, source.b.b_y,
- result.a.a_x, result.a.a_y,
- result.b.b_x, result.b.b_y);
-
- return result;
-}
-
-int main (void)
-{
- ffi_cif cif;
-
- ffi_type* struct_fields_source_a[3];
- ffi_type* struct_fields_source_b[3];
- ffi_type* struct_fields_source_c[3];
- ffi_type* arg_types[8];
-
- ffi_type struct_type_a, struct_type_b, struct_type_c;
-
- struct A source_fld_a = {1.0, 2.0};
- struct B source_fld_b = {4.0, 8.0};
- int k = 1;
-
- struct C result;
- struct C source = {source_fld_a, source_fld_b};
-
- struct_type_a.size = 0;
- struct_type_a.alignment = 0;
- struct_type_a.type = FFI_TYPE_STRUCT;
- struct_type_a.elements = struct_fields_source_a;
-
- struct_type_b.size = 0;
- struct_type_b.alignment = 0;
- struct_type_b.type = FFI_TYPE_STRUCT;
- struct_type_b.elements = struct_fields_source_b;
-
- struct_type_c.size = 0;
- struct_type_c.alignment = 0;
- struct_type_c.type = FFI_TYPE_STRUCT;
- struct_type_c.elements = struct_fields_source_c;
-
- struct_fields_source_a[0] = &ffi_type_float;
- struct_fields_source_a[1] = &ffi_type_float;
- struct_fields_source_a[2] = NULL;
-
- struct_fields_source_b[0] = &ffi_type_float;
- struct_fields_source_b[1] = &ffi_type_float;
- struct_fields_source_b[2] = NULL;
-
- struct_fields_source_c[0] = &struct_type_a;
- struct_fields_source_c[1] = &struct_type_b;
- struct_fields_source_c[2] = NULL;
-
- arg_types[0] = &ffi_type_sint32;
- arg_types[1] = &ffi_type_sint32;
- arg_types[2] = &ffi_type_sint32;
- arg_types[3] = &struct_type_c;
- arg_types[4] = &ffi_type_sint32;
- arg_types[5] = &ffi_type_sint32;
- arg_types[6] = &ffi_type_sint32;
- arg_types[7] = NULL;
-
- void *args[7];
- args[0] = &k;
- args[1] = &k;
- args[2] = &k;
- args[3] = &source;
- args[4] = &k;
- args[5] = &k;
- args[6] = &k;
- CHECK (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, 7, &struct_type_c,
- arg_types) == FFI_OK);
-
- ffi_call (&cif, FFI_FN (C_fn), &result, args);
- /* { dg-output "1, 1, 1, 1, 1, 1\n" } */
- /* { dg-output "1.0, 2.0, 4.0, 8.0, 1.0, 2.0, 4.0, 8.0" } */
- CHECK (result.a.a_x == source.a.a_x);
- CHECK (result.a.a_y == source.a.a_y);
- CHECK (result.b.b_x == source.b.b_x);
- CHECK (result.b.b_y == source.b.b_y);
- exit (0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check parameter passing with nested structs
+ of a single type. This tests the special cases
+ for homogeneous floating-point aggregates in the
+ AArch64 PCS.
+ Limitations: none.
+ PR: none.
+ Originator: ARM Ltd. */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct A {
+ float a_x;
+ float a_y;
+} A;
+
+typedef struct B {
+ float b_x;
+ float b_y;
+} B;
+
+typedef struct C {
+ A a;
+ B b;
+} C;
+
+static C C_fn (int x, int y, int z, C source, int i, int j, int k)
+{
+ C result;
+ result.a.a_x = source.a.a_x;
+ result.a.a_y = source.a.a_y;
+ result.b.b_x = source.b.b_x;
+ result.b.b_y = source.b.b_y;
+
+ printf ("%d, %d, %d, %d, %d, %d\n", x, y, z, i, j, k);
+
+ printf ("%.1f, %.1f, %.1f, %.1f, "
+ "%.1f, %.1f, %.1f, %.1f\n",
+ source.a.a_x, source.a.a_y,
+ source.b.b_x, source.b.b_y,
+ result.a.a_x, result.a.a_y,
+ result.b.b_x, result.b.b_y);
+
+ return result;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+
+ ffi_type* struct_fields_source_a[3];
+ ffi_type* struct_fields_source_b[3];
+ ffi_type* struct_fields_source_c[3];
+ ffi_type* arg_types[8];
+
+ ffi_type struct_type_a, struct_type_b, struct_type_c;
+
+ struct A source_fld_a = {1.0, 2.0};
+ struct B source_fld_b = {4.0, 8.0};
+ int k = 1;
+
+ struct C result;
+ struct C source = {source_fld_a, source_fld_b};
+
+ struct_type_a.size = 0;
+ struct_type_a.alignment = 0;
+ struct_type_a.type = FFI_TYPE_STRUCT;
+ struct_type_a.elements = struct_fields_source_a;
+
+ struct_type_b.size = 0;
+ struct_type_b.alignment = 0;
+ struct_type_b.type = FFI_TYPE_STRUCT;
+ struct_type_b.elements = struct_fields_source_b;
+
+ struct_type_c.size = 0;
+ struct_type_c.alignment = 0;
+ struct_type_c.type = FFI_TYPE_STRUCT;
+ struct_type_c.elements = struct_fields_source_c;
+
+ struct_fields_source_a[0] = &ffi_type_float;
+ struct_fields_source_a[1] = &ffi_type_float;
+ struct_fields_source_a[2] = NULL;
+
+ struct_fields_source_b[0] = &ffi_type_float;
+ struct_fields_source_b[1] = &ffi_type_float;
+ struct_fields_source_b[2] = NULL;
+
+ struct_fields_source_c[0] = &struct_type_a;
+ struct_fields_source_c[1] = &struct_type_b;
+ struct_fields_source_c[2] = NULL;
+
+ arg_types[0] = &ffi_type_sint32;
+ arg_types[1] = &ffi_type_sint32;
+ arg_types[2] = &ffi_type_sint32;
+ arg_types[3] = &struct_type_c;
+ arg_types[4] = &ffi_type_sint32;
+ arg_types[5] = &ffi_type_sint32;
+ arg_types[6] = &ffi_type_sint32;
+ arg_types[7] = NULL;
+
+ void *args[7];
+ args[0] = &k;
+ args[1] = &k;
+ args[2] = &k;
+ args[3] = &source;
+ args[4] = &k;
+ args[5] = &k;
+ args[6] = &k;
+ CHECK (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, 7, &struct_type_c,
+ arg_types) == FFI_OK);
+
+ ffi_call (&cif, FFI_FN (C_fn), &result, args);
+ /* { dg-output "1, 1, 1, 1, 1, 1\n" } */
+ /* { dg-output "1.0, 2.0, 4.0, 8.0, 1.0, 2.0, 4.0, 8.0" } */
+ CHECK (result.a.a_x == source.a.a_x);
+ CHECK (result.a.a_y == source.a.a_y);
+ CHECK (result.b.b_x == source.b.b_x);
+ CHECK (result.b.b_y == source.b.b_y);
+ exit (0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct11/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct11/ya.make
index 318feff518..ad07ba5b80 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct11/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct11/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct11.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct11.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct2.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct2.c
index 90b7c91178..69268cdb8a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct2.c
@@ -1,110 +1,110 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Contains structs as parameter of the struct itself.
- Sample taken from Alan Modras patch to src/prep_cif.c.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030911 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct A {
- unsigned long a;
- unsigned char b;
-} A;
-
-typedef struct B {
- struct A x;
- unsigned char y;
-} B;
-
-B B_fn(struct A b0, struct B b1)
-{
- struct B result;
-
- result.x.a = b0.a + b1.x.a;
- result.x.b = b0.b + b1.x.b + b1.y;
- result.y = b0.b + b1.x.b;
-
- printf("%lu %d %lu %d %d: %lu %d %d\n", b0.a, b0.b, b1.x.a, b1.x.b, b1.y,
- result.x.a, result.x.b, result.y);
-
- return result;
-}
-
-static void
-B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct A b0;
- struct B b1;
-
- b0 = *(struct A*)(args[0]);
- b1 = *(struct B*)(args[1]);
-
- *(B*)resp = B_fn(b0, b1);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[3];
- ffi_type* cls_struct_fields1[3];
- ffi_type cls_struct_type, cls_struct_type1;
- ffi_type* dbl_arg_types[3];
-
- struct A e_dbl = { 1, 7};
- struct B f_dbl = {{12 , 127}, 99};
-
- struct B res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_type1.size = 0;
- cls_struct_type1.alignment = 0;
- cls_struct_type1.type = FFI_TYPE_STRUCT;
- cls_struct_type1.elements = cls_struct_fields1;
-
- cls_struct_fields[0] = &ffi_type_ulong;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = NULL;
-
- cls_struct_fields1[0] = &cls_struct_type;
- cls_struct_fields1[1] = &ffi_type_uchar;
- cls_struct_fields1[2] = NULL;
-
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type1;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
- /* { dg-output "1 7 12 127 99: 13 233 134" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl);
- /* { dg-output "\n1 7 12 127 99: 13 233 134" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Contains structs as parameter of the struct itself.
+ Sample taken from Alan Modras patch to src/prep_cif.c.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030911 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct A {
+ unsigned long a;
+ unsigned char b;
+} A;
+
+typedef struct B {
+ struct A x;
+ unsigned char y;
+} B;
+
+B B_fn(struct A b0, struct B b1)
+{
+ struct B result;
+
+ result.x.a = b0.a + b1.x.a;
+ result.x.b = b0.b + b1.x.b + b1.y;
+ result.y = b0.b + b1.x.b;
+
+ printf("%lu %d %lu %d %d: %lu %d %d\n", b0.a, b0.b, b1.x.a, b1.x.b, b1.y,
+ result.x.a, result.x.b, result.y);
+
+ return result;
+}
+
+static void
+B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct A b0;
+ struct B b1;
+
+ b0 = *(struct A*)(args[0]);
+ b1 = *(struct B*)(args[1]);
+
+ *(B*)resp = B_fn(b0, b1);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[3];
+ ffi_type* cls_struct_fields1[3];
+ ffi_type cls_struct_type, cls_struct_type1;
+ ffi_type* dbl_arg_types[3];
+
+ struct A e_dbl = { 1, 7};
+ struct B f_dbl = {{12 , 127}, 99};
+
+ struct B res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_type1.size = 0;
+ cls_struct_type1.alignment = 0;
+ cls_struct_type1.type = FFI_TYPE_STRUCT;
+ cls_struct_type1.elements = cls_struct_fields1;
+
+ cls_struct_fields[0] = &ffi_type_ulong;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = NULL;
+
+ cls_struct_fields1[0] = &cls_struct_type;
+ cls_struct_fields1[1] = &ffi_type_uchar;
+ cls_struct_fields1[2] = NULL;
+
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type1;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 7 12 127 99: 13 233 134" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl);
+ /* { dg-output "\n1 7 12 127 99: 13 233 134" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct2/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct2/ya.make
index e874372ca5..937c161594 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct3.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct3.c
index 20f11b216e..ab18cad733 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct3.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct3.c
@@ -1,111 +1,111 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Contains structs as parameter of the struct itself.
- Sample taken from Alan Modras patch to src/prep_cif.c.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030911 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct A {
- unsigned long long a;
- unsigned char b;
-} A;
-
-typedef struct B {
- struct A x;
- unsigned char y;
-} B;
-
-B B_fn(struct A b0, struct B b1)
-{
- struct B result;
-
- result.x.a = b0.a + b1.x.a;
- result.x.b = b0.b + b1.x.b + b1.y;
- result.y = b0.b + b1.x.b;
-
- printf("%d %d %d %d %d: %d %d %d\n", (int)b0.a, b0.b,
- (int)b1.x.a, b1.x.b, b1.y,
- (int)result.x.a, result.x.b, result.y);
-
- return result;
-}
-
-static void
-B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct A b0;
- struct B b1;
-
- b0 = *(struct A*)(args[0]);
- b1 = *(struct B*)(args[1]);
-
- *(B*)resp = B_fn(b0, b1);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[3];
- ffi_type* cls_struct_fields1[3];
- ffi_type cls_struct_type, cls_struct_type1;
- ffi_type* dbl_arg_types[3];
-
- struct A e_dbl = { 1LL, 7};
- struct B f_dbl = {{12LL , 127}, 99};
-
- struct B res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_type1.size = 0;
- cls_struct_type1.alignment = 0;
- cls_struct_type1.type = FFI_TYPE_STRUCT;
- cls_struct_type1.elements = cls_struct_fields1;
-
- cls_struct_fields[0] = &ffi_type_uint64;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = NULL;
-
- cls_struct_fields1[0] = &cls_struct_type;
- cls_struct_fields1[1] = &ffi_type_uchar;
- cls_struct_fields1[2] = NULL;
-
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type1;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
- /* { dg-output "1 7 12 127 99: 13 233 134" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
-
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl);
- /* { dg-output "\n1 7 12 127 99: 13 233 134" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Contains structs as parameter of the struct itself.
+ Sample taken from Alan Modras patch to src/prep_cif.c.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030911 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct A {
+ unsigned long long a;
+ unsigned char b;
+} A;
+
+typedef struct B {
+ struct A x;
+ unsigned char y;
+} B;
+
+B B_fn(struct A b0, struct B b1)
+{
+ struct B result;
+
+ result.x.a = b0.a + b1.x.a;
+ result.x.b = b0.b + b1.x.b + b1.y;
+ result.y = b0.b + b1.x.b;
+
+ printf("%d %d %d %d %d: %d %d %d\n", (int)b0.a, b0.b,
+ (int)b1.x.a, b1.x.b, b1.y,
+ (int)result.x.a, result.x.b, result.y);
+
+ return result;
+}
+
+static void
+B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct A b0;
+ struct B b1;
+
+ b0 = *(struct A*)(args[0]);
+ b1 = *(struct B*)(args[1]);
+
+ *(B*)resp = B_fn(b0, b1);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[3];
+ ffi_type* cls_struct_fields1[3];
+ ffi_type cls_struct_type, cls_struct_type1;
+ ffi_type* dbl_arg_types[3];
+
+ struct A e_dbl = { 1LL, 7};
+ struct B f_dbl = {{12LL , 127}, 99};
+
+ struct B res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_type1.size = 0;
+ cls_struct_type1.alignment = 0;
+ cls_struct_type1.type = FFI_TYPE_STRUCT;
+ cls_struct_type1.elements = cls_struct_fields1;
+
+ cls_struct_fields[0] = &ffi_type_uint64;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = NULL;
+
+ cls_struct_fields1[0] = &cls_struct_type;
+ cls_struct_fields1[1] = &ffi_type_uchar;
+ cls_struct_fields1[2] = NULL;
+
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type1;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 7 12 127 99: 13 233 134" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
+
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl);
+ /* { dg-output "\n1 7 12 127 99: 13 233 134" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct3/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct3/ya.make
index a200403e3d..968baf49ec 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct3/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct3/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct3.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct3.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct4.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct4.c
index 56954eaec1..2ffb4d65a0 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct4.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct4.c
@@ -1,111 +1,111 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Contains structs as parameter of the struct itself.
- Sample taken from Alan Modras patch to src/prep_cif.c.
- Limitations: none.
- PR: PR 25630.
- Originator: <andreast@gcc.gnu.org> 20051010 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct A {
- double a;
- unsigned char b;
-} A;
-
-typedef struct B {
- struct A x;
- unsigned char y;
-} B;
-
-static B B_fn(struct A b2, struct B b3)
-{
- struct B result;
-
- result.x.a = b2.a + b3.x.a;
- result.x.b = b2.b + b3.x.b + b3.y;
- result.y = b2.b + b3.x.b;
-
- printf("%d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
- (int)b3.x.a, b3.x.b, b3.y,
- (int)result.x.a, result.x.b, result.y);
-
- return result;
-}
-
-static void
-B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct A b0;
- struct B b1;
-
- b0 = *(struct A*)(args[0]);
- b1 = *(struct B*)(args[1]);
-
- *(B*)resp = B_fn(b0, b1);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[3];
- ffi_type* cls_struct_fields1[3];
- ffi_type cls_struct_type, cls_struct_type1;
- ffi_type* dbl_arg_types[3];
-
- struct A e_dbl = { 1.0, 7};
- struct B f_dbl = {{12.0 , 127}, 99};
-
- struct B res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_type1.size = 0;
- cls_struct_type1.alignment = 0;
- cls_struct_type1.type = FFI_TYPE_STRUCT;
- cls_struct_type1.elements = cls_struct_fields1;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = NULL;
-
- cls_struct_fields1[0] = &cls_struct_type;
- cls_struct_fields1[1] = &ffi_type_uchar;
- cls_struct_fields1[2] = NULL;
-
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type1;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
- /* { dg-output "1 7 12 127 99: 13 233 134" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl);
- /* { dg-output "\n1 7 12 127 99: 13 233 134" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Contains structs as parameter of the struct itself.
+ Sample taken from Alan Modras patch to src/prep_cif.c.
+ Limitations: none.
+ PR: PR 25630.
+ Originator: <andreast@gcc.gnu.org> 20051010 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct A {
+ double a;
+ unsigned char b;
+} A;
+
+typedef struct B {
+ struct A x;
+ unsigned char y;
+} B;
+
+static B B_fn(struct A b2, struct B b3)
+{
+ struct B result;
+
+ result.x.a = b2.a + b3.x.a;
+ result.x.b = b2.b + b3.x.b + b3.y;
+ result.y = b2.b + b3.x.b;
+
+ printf("%d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
+ (int)b3.x.a, b3.x.b, b3.y,
+ (int)result.x.a, result.x.b, result.y);
+
+ return result;
+}
+
+static void
+B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct A b0;
+ struct B b1;
+
+ b0 = *(struct A*)(args[0]);
+ b1 = *(struct B*)(args[1]);
+
+ *(B*)resp = B_fn(b0, b1);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[3];
+ ffi_type* cls_struct_fields1[3];
+ ffi_type cls_struct_type, cls_struct_type1;
+ ffi_type* dbl_arg_types[3];
+
+ struct A e_dbl = { 1.0, 7};
+ struct B f_dbl = {{12.0 , 127}, 99};
+
+ struct B res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_type1.size = 0;
+ cls_struct_type1.alignment = 0;
+ cls_struct_type1.type = FFI_TYPE_STRUCT;
+ cls_struct_type1.elements = cls_struct_fields1;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = NULL;
+
+ cls_struct_fields1[0] = &cls_struct_type;
+ cls_struct_fields1[1] = &ffi_type_uchar;
+ cls_struct_fields1[2] = NULL;
+
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type1;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 7 12 127 99: 13 233 134" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl);
+ /* { dg-output "\n1 7 12 127 99: 13 233 134" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct4/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct4/ya.make
index 71099c60f2..57f13f8dda 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct4/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct4/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct4.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct4.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct5.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct5.c
index ebcd28c005..6c79845d98 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct5.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct5.c
@@ -1,112 +1,112 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Contains structs as parameter of the struct itself.
- Sample taken from Alan Modras patch to src/prep_cif.c.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20051010 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct A {
- long double a;
- unsigned char b;
-} A;
-
-typedef struct B {
- struct A x;
- unsigned char y;
-} B;
-
-static B B_fn(struct A b2, struct B b3)
-{
- struct B result;
-
- result.x.a = b2.a + b3.x.a;
- result.x.b = b2.b + b3.x.b + b3.y;
- result.y = b2.b + b3.x.b;
-
- printf("%d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
- (int)b3.x.a, b3.x.b, b3.y,
- (int)result.x.a, result.x.b, result.y);
-
- return result;
-}
-
-static void
-B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct A b0;
- struct B b1;
-
- b0 = *(struct A*)(args[0]);
- b1 = *(struct B*)(args[1]);
-
- *(B*)resp = B_fn(b0, b1);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[3];
- ffi_type* cls_struct_fields1[3];
- ffi_type cls_struct_type, cls_struct_type1;
- ffi_type* dbl_arg_types[3];
-
- struct A e_dbl = { 1.0, 7};
- struct B f_dbl = {{12.0 , 127}, 99};
-
- struct B res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_type1.size = 0;
- cls_struct_type1.alignment = 0;
- cls_struct_type1.type = FFI_TYPE_STRUCT;
- cls_struct_type1.elements = cls_struct_fields1;
-
- cls_struct_fields[0] = &ffi_type_longdouble;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = NULL;
-
- cls_struct_fields1[0] = &cls_struct_type;
- cls_struct_fields1[1] = &ffi_type_uchar;
- cls_struct_fields1[2] = NULL;
-
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type1;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
- /* { dg-output "1 7 12 127 99: 13 233 134" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
-
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl);
- /* { dg-output "\n1 7 12 127 99: 13 233 134" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Contains structs as parameter of the struct itself.
+ Sample taken from Alan Modras patch to src/prep_cif.c.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20051010 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct A {
+ long double a;
+ unsigned char b;
+} A;
+
+typedef struct B {
+ struct A x;
+ unsigned char y;
+} B;
+
+static B B_fn(struct A b2, struct B b3)
+{
+ struct B result;
+
+ result.x.a = b2.a + b3.x.a;
+ result.x.b = b2.b + b3.x.b + b3.y;
+ result.y = b2.b + b3.x.b;
+
+ printf("%d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
+ (int)b3.x.a, b3.x.b, b3.y,
+ (int)result.x.a, result.x.b, result.y);
+
+ return result;
+}
+
+static void
+B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct A b0;
+ struct B b1;
+
+ b0 = *(struct A*)(args[0]);
+ b1 = *(struct B*)(args[1]);
+
+ *(B*)resp = B_fn(b0, b1);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[3];
+ ffi_type* cls_struct_fields1[3];
+ ffi_type cls_struct_type, cls_struct_type1;
+ ffi_type* dbl_arg_types[3];
+
+ struct A e_dbl = { 1.0, 7};
+ struct B f_dbl = {{12.0 , 127}, 99};
+
+ struct B res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_type1.size = 0;
+ cls_struct_type1.alignment = 0;
+ cls_struct_type1.type = FFI_TYPE_STRUCT;
+ cls_struct_type1.elements = cls_struct_fields1;
+
+ cls_struct_fields[0] = &ffi_type_longdouble;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = NULL;
+
+ cls_struct_fields1[0] = &cls_struct_type;
+ cls_struct_fields1[1] = &ffi_type_uchar;
+ cls_struct_fields1[2] = NULL;
+
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type1;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 7 12 127 99: 13 233 134" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
+
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl);
+ /* { dg-output "\n1 7 12 127 99: 13 233 134" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct5/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct5/ya.make
index f69bede846..37bfbda7e6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct5/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct5/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct5.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct5.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct6.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct6.c
index 0fb4449fa3..59d35796f8 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct6.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct6.c
@@ -1,131 +1,131 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Contains structs as parameter of the struct itself.
- Sample taken from Alan Modras patch to src/prep_cif.c.
- Limitations: none.
- PR: PR 25630.
- Originator: <andreast@gcc.gnu.org> 20051010 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct A {
- double a;
- unsigned char b;
-} A;
-
-typedef struct B {
- struct A x;
- unsigned char y;
-} B;
-
-typedef struct C {
- long d;
- unsigned char e;
-} C;
-
-static B B_fn(struct A b2, struct B b3, struct C b4)
-{
- struct B result;
-
- result.x.a = b2.a + b3.x.a + b4.d;
- result.x.b = b2.b + b3.x.b + b3.y + b4.e;
- result.y = b2.b + b3.x.b + b4.e;
-
- printf("%d %d %d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
- (int)b3.x.a, b3.x.b, b3.y, (int)b4.d, b4.e,
- (int)result.x.a, result.x.b, result.y);
-
- return result;
-}
-
-static void
-B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct A b0;
- struct B b1;
- struct C b2;
-
- b0 = *(struct A*)(args[0]);
- b1 = *(struct B*)(args[1]);
- b2 = *(struct C*)(args[2]);
-
- *(B*)resp = B_fn(b0, b1, b2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[4];
- ffi_type* cls_struct_fields[3];
- ffi_type* cls_struct_fields1[3];
- ffi_type* cls_struct_fields2[3];
- ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
- ffi_type* dbl_arg_types[4];
-
- struct A e_dbl = { 1.0, 7};
- struct B f_dbl = {{12.0 , 127}, 99};
- struct C g_dbl = { 2, 9};
-
- struct B res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_type1.size = 0;
- cls_struct_type1.alignment = 0;
- cls_struct_type1.type = FFI_TYPE_STRUCT;
- cls_struct_type1.elements = cls_struct_fields1;
-
- cls_struct_type2.size = 0;
- cls_struct_type2.alignment = 0;
- cls_struct_type2.type = FFI_TYPE_STRUCT;
- cls_struct_type2.elements = cls_struct_fields2;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = NULL;
-
- cls_struct_fields1[0] = &cls_struct_type;
- cls_struct_fields1[1] = &ffi_type_uchar;
- cls_struct_fields1[2] = NULL;
-
- cls_struct_fields2[0] = &ffi_type_slong;
- cls_struct_fields2[1] = &ffi_type_uchar;
- cls_struct_fields2[2] = NULL;
-
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type1;
- dbl_arg_types[2] = &cls_struct_type2;
- dbl_arg_types[3] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = NULL;
-
- ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
- /* { dg-output "1 7 12 127 99 2 9: 15 242 143" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl);
- /* { dg-output "\n1 7 12 127 99 2 9: 15 242 143" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Contains structs as parameter of the struct itself.
+ Sample taken from Alan Modras patch to src/prep_cif.c.
+ Limitations: none.
+ PR: PR 25630.
+ Originator: <andreast@gcc.gnu.org> 20051010 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct A {
+ double a;
+ unsigned char b;
+} A;
+
+typedef struct B {
+ struct A x;
+ unsigned char y;
+} B;
+
+typedef struct C {
+ long d;
+ unsigned char e;
+} C;
+
+static B B_fn(struct A b2, struct B b3, struct C b4)
+{
+ struct B result;
+
+ result.x.a = b2.a + b3.x.a + b4.d;
+ result.x.b = b2.b + b3.x.b + b3.y + b4.e;
+ result.y = b2.b + b3.x.b + b4.e;
+
+ printf("%d %d %d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
+ (int)b3.x.a, b3.x.b, b3.y, (int)b4.d, b4.e,
+ (int)result.x.a, result.x.b, result.y);
+
+ return result;
+}
+
+static void
+B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct A b0;
+ struct B b1;
+ struct C b2;
+
+ b0 = *(struct A*)(args[0]);
+ b1 = *(struct B*)(args[1]);
+ b2 = *(struct C*)(args[2]);
+
+ *(B*)resp = B_fn(b0, b1, b2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[4];
+ ffi_type* cls_struct_fields[3];
+ ffi_type* cls_struct_fields1[3];
+ ffi_type* cls_struct_fields2[3];
+ ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
+ ffi_type* dbl_arg_types[4];
+
+ struct A e_dbl = { 1.0, 7};
+ struct B f_dbl = {{12.0 , 127}, 99};
+ struct C g_dbl = { 2, 9};
+
+ struct B res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_type1.size = 0;
+ cls_struct_type1.alignment = 0;
+ cls_struct_type1.type = FFI_TYPE_STRUCT;
+ cls_struct_type1.elements = cls_struct_fields1;
+
+ cls_struct_type2.size = 0;
+ cls_struct_type2.alignment = 0;
+ cls_struct_type2.type = FFI_TYPE_STRUCT;
+ cls_struct_type2.elements = cls_struct_fields2;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = NULL;
+
+ cls_struct_fields1[0] = &cls_struct_type;
+ cls_struct_fields1[1] = &ffi_type_uchar;
+ cls_struct_fields1[2] = NULL;
+
+ cls_struct_fields2[0] = &ffi_type_slong;
+ cls_struct_fields2[1] = &ffi_type_uchar;
+ cls_struct_fields2[2] = NULL;
+
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type1;
+ dbl_arg_types[2] = &cls_struct_type2;
+ dbl_arg_types[3] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = NULL;
+
+ ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 7 12 127 99 2 9: 15 242 143" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl);
+ /* { dg-output "\n1 7 12 127 99 2 9: 15 242 143" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct6/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct6/ya.make
index 637dee98e5..10fa25f293 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct6/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct6/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct6.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct6.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct7.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct7.c
index d6da2a92f1..27595e6f5c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct7.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct7.c
@@ -1,111 +1,111 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Contains structs as parameter of the struct itself.
- Sample taken from Alan Modras patch to src/prep_cif.c.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20051010 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct A {
- unsigned long long a;
- unsigned char b;
-} A;
-
-typedef struct B {
- struct A x;
- unsigned char y;
-} B;
-
-static B B_fn(struct A b2, struct B b3)
-{
- struct B result;
-
- result.x.a = b2.a + b3.x.a;
- result.x.b = b2.b + b3.x.b + b3.y;
- result.y = b2.b + b3.x.b;
-
- printf("%d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
- (int)b3.x.a, b3.x.b, b3.y,
- (int)result.x.a, result.x.b, result.y);
-
- return result;
-}
-
-static void
-B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct A b0;
- struct B b1;
-
- b0 = *(struct A*)(args[0]);
- b1 = *(struct B*)(args[1]);
-
- *(B*)resp = B_fn(b0, b1);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[3];
- ffi_type* cls_struct_fields[3];
- ffi_type* cls_struct_fields1[3];
- ffi_type cls_struct_type, cls_struct_type1;
- ffi_type* dbl_arg_types[3];
-
- struct A e_dbl = { 1LL, 7};
- struct B f_dbl = {{12.0 , 127}, 99};
-
- struct B res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_type1.size = 0;
- cls_struct_type1.alignment = 0;
- cls_struct_type1.type = FFI_TYPE_STRUCT;
- cls_struct_type1.elements = cls_struct_fields1;
-
- cls_struct_fields[0] = &ffi_type_uint64;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = NULL;
-
- cls_struct_fields1[0] = &cls_struct_type;
- cls_struct_fields1[1] = &ffi_type_uchar;
- cls_struct_fields1[2] = NULL;
-
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type1;
- dbl_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = NULL;
-
- ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
- /* { dg-output "1 7 12 127 99: 13 233 134" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl);
- /* { dg-output "\n1 7 12 127 99: 13 233 134" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Contains structs as parameter of the struct itself.
+ Sample taken from Alan Modras patch to src/prep_cif.c.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20051010 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct A {
+ unsigned long long a;
+ unsigned char b;
+} A;
+
+typedef struct B {
+ struct A x;
+ unsigned char y;
+} B;
+
+static B B_fn(struct A b2, struct B b3)
+{
+ struct B result;
+
+ result.x.a = b2.a + b3.x.a;
+ result.x.b = b2.b + b3.x.b + b3.y;
+ result.y = b2.b + b3.x.b;
+
+ printf("%d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
+ (int)b3.x.a, b3.x.b, b3.y,
+ (int)result.x.a, result.x.b, result.y);
+
+ return result;
+}
+
+static void
+B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct A b0;
+ struct B b1;
+
+ b0 = *(struct A*)(args[0]);
+ b1 = *(struct B*)(args[1]);
+
+ *(B*)resp = B_fn(b0, b1);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[3];
+ ffi_type* cls_struct_fields[3];
+ ffi_type* cls_struct_fields1[3];
+ ffi_type cls_struct_type, cls_struct_type1;
+ ffi_type* dbl_arg_types[3];
+
+ struct A e_dbl = { 1LL, 7};
+ struct B f_dbl = {{12.0 , 127}, 99};
+
+ struct B res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_type1.size = 0;
+ cls_struct_type1.alignment = 0;
+ cls_struct_type1.type = FFI_TYPE_STRUCT;
+ cls_struct_type1.elements = cls_struct_fields1;
+
+ cls_struct_fields[0] = &ffi_type_uint64;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = NULL;
+
+ cls_struct_fields1[0] = &cls_struct_type;
+ cls_struct_fields1[1] = &ffi_type_uchar;
+ cls_struct_fields1[2] = NULL;
+
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type1;
+ dbl_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 7 12 127 99: 13 233 134" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl);
+ /* { dg-output "\n1 7 12 127 99: 13 233 134" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b));
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct7/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct7/ya.make
index bfb2346710..9c1da60995 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct7/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct7/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct7.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct7.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct8.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct8.c
index 32c65c37c4..0e6c68281e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct8.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct8.c
@@ -1,131 +1,131 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Contains structs as parameter of the struct itself.
- Sample taken from Alan Modras patch to src/prep_cif.c.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20051010 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct A {
- unsigned long long a;
- unsigned char b;
-} A;
-
-typedef struct B {
- struct A x;
- unsigned char y;
-} B;
-
-typedef struct C {
- unsigned long long d;
- unsigned char e;
-} C;
-
-static B B_fn(struct A b2, struct B b3, struct C b4)
-{
- struct B result;
-
- result.x.a = b2.a + b3.x.a + b4.d;
- result.x.b = b2.b + b3.x.b + b3.y + b4.e;
- result.y = b2.b + b3.x.b + b4.e;
-
- printf("%d %d %d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
- (int)b3.x.a, b3.x.b, b3.y, (int)b4.d, b4.e,
- (int)result.x.a, result.x.b, result.y);
-
- return result;
-}
-
-static void
-B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct A b0;
- struct B b1;
- struct C b2;
-
- b0 = *(struct A*)(args[0]);
- b1 = *(struct B*)(args[1]);
- b2 = *(struct C*)(args[2]);
-
- *(B*)resp = B_fn(b0, b1, b2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[4];
- ffi_type* cls_struct_fields[3];
- ffi_type* cls_struct_fields1[3];
- ffi_type* cls_struct_fields2[3];
- ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
- ffi_type* dbl_arg_types[4];
-
- struct A e_dbl = { 1LL, 7};
- struct B f_dbl = {{12LL , 127}, 99};
- struct C g_dbl = { 2LL, 9};
-
- struct B res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_type1.size = 0;
- cls_struct_type1.alignment = 0;
- cls_struct_type1.type = FFI_TYPE_STRUCT;
- cls_struct_type1.elements = cls_struct_fields1;
-
- cls_struct_type2.size = 0;
- cls_struct_type2.alignment = 0;
- cls_struct_type2.type = FFI_TYPE_STRUCT;
- cls_struct_type2.elements = cls_struct_fields2;
-
- cls_struct_fields[0] = &ffi_type_uint64;
- cls_struct_fields[1] = &ffi_type_uchar;
- cls_struct_fields[2] = NULL;
-
- cls_struct_fields1[0] = &cls_struct_type;
- cls_struct_fields1[1] = &ffi_type_uchar;
- cls_struct_fields1[2] = NULL;
-
- cls_struct_fields2[0] = &ffi_type_uint64;
- cls_struct_fields2[1] = &ffi_type_uchar;
- cls_struct_fields2[2] = NULL;
-
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type1;
- dbl_arg_types[2] = &cls_struct_type2;
- dbl_arg_types[3] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = NULL;
-
- ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
- /* { dg-output "1 7 12 127 99 2 9: 15 242 143" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl);
- /* { dg-output "\n1 7 12 127 99 2 9: 15 242 143" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Contains structs as parameter of the struct itself.
+ Sample taken from Alan Modras patch to src/prep_cif.c.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20051010 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct A {
+ unsigned long long a;
+ unsigned char b;
+} A;
+
+typedef struct B {
+ struct A x;
+ unsigned char y;
+} B;
+
+typedef struct C {
+ unsigned long long d;
+ unsigned char e;
+} C;
+
+static B B_fn(struct A b2, struct B b3, struct C b4)
+{
+ struct B result;
+
+ result.x.a = b2.a + b3.x.a + b4.d;
+ result.x.b = b2.b + b3.x.b + b3.y + b4.e;
+ result.y = b2.b + b3.x.b + b4.e;
+
+ printf("%d %d %d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b,
+ (int)b3.x.a, b3.x.b, b3.y, (int)b4.d, b4.e,
+ (int)result.x.a, result.x.b, result.y);
+
+ return result;
+}
+
+static void
+B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct A b0;
+ struct B b1;
+ struct C b2;
+
+ b0 = *(struct A*)(args[0]);
+ b1 = *(struct B*)(args[1]);
+ b2 = *(struct C*)(args[2]);
+
+ *(B*)resp = B_fn(b0, b1, b2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[4];
+ ffi_type* cls_struct_fields[3];
+ ffi_type* cls_struct_fields1[3];
+ ffi_type* cls_struct_fields2[3];
+ ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
+ ffi_type* dbl_arg_types[4];
+
+ struct A e_dbl = { 1LL, 7};
+ struct B f_dbl = {{12LL , 127}, 99};
+ struct C g_dbl = { 2LL, 9};
+
+ struct B res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_type1.size = 0;
+ cls_struct_type1.alignment = 0;
+ cls_struct_type1.type = FFI_TYPE_STRUCT;
+ cls_struct_type1.elements = cls_struct_fields1;
+
+ cls_struct_type2.size = 0;
+ cls_struct_type2.alignment = 0;
+ cls_struct_type2.type = FFI_TYPE_STRUCT;
+ cls_struct_type2.elements = cls_struct_fields2;
+
+ cls_struct_fields[0] = &ffi_type_uint64;
+ cls_struct_fields[1] = &ffi_type_uchar;
+ cls_struct_fields[2] = NULL;
+
+ cls_struct_fields1[0] = &cls_struct_type;
+ cls_struct_fields1[1] = &ffi_type_uchar;
+ cls_struct_fields1[2] = NULL;
+
+ cls_struct_fields2[0] = &ffi_type_uint64;
+ cls_struct_fields2[1] = &ffi_type_uchar;
+ cls_struct_fields2[2] = NULL;
+
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type1;
+ dbl_arg_types[2] = &cls_struct_type2;
+ dbl_arg_types[3] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = NULL;
+
+ ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 7 12 127 99 2 9: 15 242 143" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl);
+ /* { dg-output "\n1 7 12 127 99 2 9: 15 242 143" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct8/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct8/ya.make
index 730bb80a1e..068551c748 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct8/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct8/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct8.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct8.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct9.c b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct9.c
index d43f45bbfe..5f7ac67752 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct9.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct9.c
@@ -1,131 +1,131 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Contains structs as parameter of the struct itself.
- Sample taken from Alan Modras patch to src/prep_cif.c.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20051010 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct A {
- unsigned char a;
- unsigned long long b;
-} A;
-
-typedef struct B {
- struct A x;
- unsigned char y;
-} B;
-
-typedef struct C {
- unsigned long d;
- unsigned char e;
-} C;
-
-static B B_fn(struct A b2, struct B b3, struct C b4)
-{
- struct B result;
-
- result.x.a = b2.a + b3.x.a + b4.d;
- result.x.b = b2.b + b3.x.b + b3.y + b4.e;
- result.y = b2.b + b3.x.b + b4.e;
-
- printf("%d %d %d %d %d %d %d: %d %d %d\n", b2.a, (int)b2.b,
- b3.x.a, (int)b3.x.b, b3.y, (int)b4.d, b4.e,
- result.x.a, (int)result.x.b, result.y);
-
- return result;
-}
-
-static void
-B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct A b0;
- struct B b1;
- struct C b2;
-
- b0 = *(struct A*)(args[0]);
- b1 = *(struct B*)(args[1]);
- b2 = *(struct C*)(args[2]);
-
- *(B*)resp = B_fn(b0, b1, b2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[4];
- ffi_type* cls_struct_fields[3];
- ffi_type* cls_struct_fields1[3];
- ffi_type* cls_struct_fields2[3];
- ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
- ffi_type* dbl_arg_types[4];
-
- struct A e_dbl = { 1, 7LL};
- struct B f_dbl = {{12.0 , 127}, 99};
- struct C g_dbl = { 2, 9};
-
- struct B res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_type1.size = 0;
- cls_struct_type1.alignment = 0;
- cls_struct_type1.type = FFI_TYPE_STRUCT;
- cls_struct_type1.elements = cls_struct_fields1;
-
- cls_struct_type2.size = 0;
- cls_struct_type2.alignment = 0;
- cls_struct_type2.type = FFI_TYPE_STRUCT;
- cls_struct_type2.elements = cls_struct_fields2;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &ffi_type_uint64;
- cls_struct_fields[2] = NULL;
-
- cls_struct_fields1[0] = &cls_struct_type;
- cls_struct_fields1[1] = &ffi_type_uchar;
- cls_struct_fields1[2] = NULL;
-
- cls_struct_fields2[0] = &ffi_type_ulong;
- cls_struct_fields2[1] = &ffi_type_uchar;
- cls_struct_fields2[2] = NULL;
-
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type1;
- dbl_arg_types[2] = &cls_struct_type2;
- dbl_arg_types[3] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = NULL;
-
- ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
- /* { dg-output "1 7 12 127 99 2 9: 15 242 143" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl);
- /* { dg-output "\n1 7 12 127 99 2 9: 15 242 143" } */
- CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
- CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
- CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Contains structs as parameter of the struct itself.
+ Sample taken from Alan Modras patch to src/prep_cif.c.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20051010 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct A {
+ unsigned char a;
+ unsigned long long b;
+} A;
+
+typedef struct B {
+ struct A x;
+ unsigned char y;
+} B;
+
+typedef struct C {
+ unsigned long d;
+ unsigned char e;
+} C;
+
+static B B_fn(struct A b2, struct B b3, struct C b4)
+{
+ struct B result;
+
+ result.x.a = b2.a + b3.x.a + b4.d;
+ result.x.b = b2.b + b3.x.b + b3.y + b4.e;
+ result.y = b2.b + b3.x.b + b4.e;
+
+ printf("%d %d %d %d %d %d %d: %d %d %d\n", b2.a, (int)b2.b,
+ b3.x.a, (int)b3.x.b, b3.y, (int)b4.d, b4.e,
+ result.x.a, (int)result.x.b, result.y);
+
+ return result;
+}
+
+static void
+B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct A b0;
+ struct B b1;
+ struct C b2;
+
+ b0 = *(struct A*)(args[0]);
+ b1 = *(struct B*)(args[1]);
+ b2 = *(struct C*)(args[2]);
+
+ *(B*)resp = B_fn(b0, b1, b2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[4];
+ ffi_type* cls_struct_fields[3];
+ ffi_type* cls_struct_fields1[3];
+ ffi_type* cls_struct_fields2[3];
+ ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
+ ffi_type* dbl_arg_types[4];
+
+ struct A e_dbl = { 1, 7LL};
+ struct B f_dbl = {{12.0 , 127}, 99};
+ struct C g_dbl = { 2, 9};
+
+ struct B res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_type1.size = 0;
+ cls_struct_type1.alignment = 0;
+ cls_struct_type1.type = FFI_TYPE_STRUCT;
+ cls_struct_type1.elements = cls_struct_fields1;
+
+ cls_struct_type2.size = 0;
+ cls_struct_type2.alignment = 0;
+ cls_struct_type2.type = FFI_TYPE_STRUCT;
+ cls_struct_type2.elements = cls_struct_fields2;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &ffi_type_uint64;
+ cls_struct_fields[2] = NULL;
+
+ cls_struct_fields1[0] = &cls_struct_type;
+ cls_struct_fields1[1] = &ffi_type_uchar;
+ cls_struct_fields1[2] = NULL;
+
+ cls_struct_fields2[0] = &ffi_type_ulong;
+ cls_struct_fields2[1] = &ffi_type_uchar;
+ cls_struct_fields2[2] = NULL;
+
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type1;
+ dbl_arg_types[2] = &cls_struct_type2;
+ dbl_arg_types[3] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = NULL;
+
+ ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl);
+ /* { dg-output "1 7 12 127 99 2 9: 15 242 143" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl);
+ /* { dg-output "\n1 7 12 127 99 2 9: 15 242 143" } */
+ CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d));
+ CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e));
+ CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e));
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct9/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct9/ya.make
index 5162a3d267..f49bada8fa 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct9/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/nested_struct9/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- nested_struct9.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ nested_struct9.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/problem1.c b/contrib/restricted/libffi/testsuite/libffi.closures/problem1.c
index d888138d9d..6a91555a1f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/problem1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/problem1.c
@@ -1,90 +1,90 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure passing with different structure size.
- Limitations: none.
- PR: none.
- Originator: <andreast@gcc.gnu.org> 20030828 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct my_ffi_struct {
- double a;
- double b;
- double c;
-} my_ffi_struct;
-
-my_ffi_struct callee(struct my_ffi_struct a1, struct my_ffi_struct a2)
-{
- struct my_ffi_struct result;
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
-
- printf("%g %g %g %g %g %g: %g %g %g\n", a1.a, a1.b, a1.c,
- a2.a, a2.b, a2.c, result.a, result.b, result.c);
-
- return result;
-}
-
-void stub(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
- struct my_ffi_struct a1;
- struct my_ffi_struct a2;
-
- a1 = *(struct my_ffi_struct*)(args[0]);
- a2 = *(struct my_ffi_struct*)(args[1]);
-
- *(my_ffi_struct *)resp = callee(a1, a2);
-}
-
-
-int main(void)
-{
- ffi_type* my_ffi_struct_fields[4];
- ffi_type my_ffi_struct_type;
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args[4];
- ffi_type* arg_types[3];
-
- struct my_ffi_struct g = { 1.0, 2.0, 3.0 };
- struct my_ffi_struct f = { 1.0, 2.0, 3.0 };
- struct my_ffi_struct res;
-
- my_ffi_struct_type.size = 0;
- my_ffi_struct_type.alignment = 0;
- my_ffi_struct_type.type = FFI_TYPE_STRUCT;
- my_ffi_struct_type.elements = my_ffi_struct_fields;
-
- my_ffi_struct_fields[0] = &ffi_type_double;
- my_ffi_struct_fields[1] = &ffi_type_double;
- my_ffi_struct_fields[2] = &ffi_type_double;
- my_ffi_struct_fields[3] = NULL;
-
- arg_types[0] = &my_ffi_struct_type;
- arg_types[1] = &my_ffi_struct_type;
- arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &my_ffi_struct_type,
- arg_types) == FFI_OK);
-
- args[0] = &g;
- args[1] = &f;
- args[2] = NULL;
- ffi_call(&cif, FFI_FN(callee), &res, args);
- /* { dg-output "1 2 3 1 2 3: 2 4 6" } */
- printf("res: %g %g %g\n", res.a, res.b, res.c);
- /* { dg-output "\nres: 2 4 6" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, stub, NULL, code) == FFI_OK);
-
- res = ((my_ffi_struct(*)(struct my_ffi_struct, struct my_ffi_struct))(code))(g, f);
- /* { dg-output "\n1 2 3 1 2 3: 2 4 6" } */
- printf("res: %g %g %g\n", res.a, res.b, res.c);
- /* { dg-output "\nres: 2 4 6" } */
-
- exit(0);;
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure passing with different structure size.
+ Limitations: none.
+ PR: none.
+ Originator: <andreast@gcc.gnu.org> 20030828 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct my_ffi_struct {
+ double a;
+ double b;
+ double c;
+} my_ffi_struct;
+
+my_ffi_struct callee(struct my_ffi_struct a1, struct my_ffi_struct a2)
+{
+ struct my_ffi_struct result;
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+
+ printf("%g %g %g %g %g %g: %g %g %g\n", a1.a, a1.b, a1.c,
+ a2.a, a2.b, a2.c, result.a, result.b, result.c);
+
+ return result;
+}
+
+void stub(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+ struct my_ffi_struct a1;
+ struct my_ffi_struct a2;
+
+ a1 = *(struct my_ffi_struct*)(args[0]);
+ a2 = *(struct my_ffi_struct*)(args[1]);
+
+ *(my_ffi_struct *)resp = callee(a1, a2);
+}
+
+
+int main(void)
+{
+ ffi_type* my_ffi_struct_fields[4];
+ ffi_type my_ffi_struct_type;
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args[4];
+ ffi_type* arg_types[3];
+
+ struct my_ffi_struct g = { 1.0, 2.0, 3.0 };
+ struct my_ffi_struct f = { 1.0, 2.0, 3.0 };
+ struct my_ffi_struct res;
+
+ my_ffi_struct_type.size = 0;
+ my_ffi_struct_type.alignment = 0;
+ my_ffi_struct_type.type = FFI_TYPE_STRUCT;
+ my_ffi_struct_type.elements = my_ffi_struct_fields;
+
+ my_ffi_struct_fields[0] = &ffi_type_double;
+ my_ffi_struct_fields[1] = &ffi_type_double;
+ my_ffi_struct_fields[2] = &ffi_type_double;
+ my_ffi_struct_fields[3] = NULL;
+
+ arg_types[0] = &my_ffi_struct_type;
+ arg_types[1] = &my_ffi_struct_type;
+ arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &my_ffi_struct_type,
+ arg_types) == FFI_OK);
+
+ args[0] = &g;
+ args[1] = &f;
+ args[2] = NULL;
+ ffi_call(&cif, FFI_FN(callee), &res, args);
+ /* { dg-output "1 2 3 1 2 3: 2 4 6" } */
+ printf("res: %g %g %g\n", res.a, res.b, res.c);
+ /* { dg-output "\nres: 2 4 6" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, stub, NULL, code) == FFI_OK);
+
+ res = ((my_ffi_struct(*)(struct my_ffi_struct, struct my_ffi_struct))(code))(g, f);
+ /* { dg-output "\n1 2 3 1 2 3: 2 4 6" } */
+ printf("res: %g %g %g\n", res.a, res.b, res.c);
+ /* { dg-output "\nres: 2 4 6" } */
+
+ exit(0);;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/problem1/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/problem1/ya.make
index 11add82595..284213056b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/problem1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/problem1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- problem1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ problem1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/stret_large.c b/contrib/restricted/libffi/testsuite/libffi.closures/stret_large.c
index e6c35f6a9a..71c2469e1c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/stret_large.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/stret_large.c
@@ -1,145 +1,145 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure returning with different structure size.
- Depending on the ABI. Check bigger struct which overlaps
- the gp and fp register count on Darwin/AIX/ppc64.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/21/2007 */
-
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
-#include "ffitest.h"
-
-/* 13 FPRs: 104 bytes */
-/* 14 FPRs: 112 bytes */
-
-typedef struct struct_108byte {
- double a;
- double b;
- double c;
- double d;
- double e;
- double f;
- double g;
- double h;
- double i;
- double j;
- double k;
- double l;
- double m;
- int n;
-} struct_108byte;
-
-struct_108byte cls_struct_108byte_fn(
- struct_108byte b0,
- struct_108byte b1,
- struct_108byte b2,
- struct_108byte b3)
-{
- struct_108byte result;
-
- result.a = b0.a + b1.a + b2.a + b3.a;
- result.b = b0.b + b1.b + b2.b + b3.b;
- result.c = b0.c + b1.c + b2.c + b3.c;
- result.d = b0.d + b1.d + b2.d + b3.d;
- result.e = b0.e + b1.e + b2.e + b3.e;
- result.f = b0.f + b1.f + b2.f + b3.f;
- result.g = b0.g + b1.g + b2.g + b3.g;
- result.h = b0.h + b1.h + b2.h + b3.h;
- result.i = b0.i + b1.i + b2.i + b3.i;
- result.j = b0.j + b1.j + b2.j + b3.j;
- result.k = b0.k + b1.k + b2.k + b3.k;
- result.l = b0.l + b1.l + b2.l + b3.l;
- result.m = b0.m + b1.m + b2.m + b3.m;
- result.n = b0.n + b1.n + b2.n + b3.n;
-
- printf("%g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", result.a, result.b, result.c,
- result.d, result.e, result.f, result.g, result.h, result.i,
- result.j, result.k, result.l, result.m, result.n);
-
- return result;
-}
-
-static void
-cls_struct_108byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__)
-{
- struct_108byte b0, b1, b2, b3;
-
- b0 = *(struct_108byte*)(args[0]);
- b1 = *(struct_108byte*)(args[1]);
- b2 = *(struct_108byte*)(args[2]);
- b3 = *(struct_108byte*)(args[3]);
-
- *(struct_108byte*)resp = cls_struct_108byte_fn(b0, b1, b2, b3);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[15];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct_108byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 1.0, 2.0, 3.0, 7.0, 2.0, 7 };
- struct_108byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4.0, 5.0, 7.0, 9.0, 1.0, 4 };
- struct_108byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 8.0, 6.0, 1.0, 4.0, 0.0, 3 };
- struct_108byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 9.0, 2.0, 6.0, 5.0, 3.0, 2 };
- struct_108byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_double;
- cls_struct_fields[2] = &ffi_type_double;
- cls_struct_fields[3] = &ffi_type_double;
- cls_struct_fields[4] = &ffi_type_double;
- cls_struct_fields[5] = &ffi_type_double;
- cls_struct_fields[6] = &ffi_type_double;
- cls_struct_fields[7] = &ffi_type_double;
- cls_struct_fields[8] = &ffi_type_double;
- cls_struct_fields[9] = &ffi_type_double;
- cls_struct_fields[10] = &ffi_type_double;
- cls_struct_fields[11] = &ffi_type_double;
- cls_struct_fields[12] = &ffi_type_double;
- cls_struct_fields[13] = &ffi_type_sint32;
- cls_struct_fields[14] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = &cls_struct_type;
- dbl_arg_types[3] = &cls_struct_type;
- dbl_arg_types[4] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = &h_dbl;
- args_dbl[4] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_108byte_fn), &res_dbl, args_dbl);
- /* { dg-output "22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */
- printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b,
- res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i,
- res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n);
- /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_108byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((struct_108byte(*)(struct_108byte, struct_108byte,
- struct_108byte, struct_108byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl);
- /* { dg-output "\n22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */
- printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b,
- res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i,
- res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n);
- /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure returning with different structure size.
+ Depending on the ABI. Check bigger struct which overlaps
+ the gp and fp register count on Darwin/AIX/ppc64.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/21/2007 */
+
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
+#include "ffitest.h"
+
+/* 13 FPRs: 104 bytes */
+/* 14 FPRs: 112 bytes */
+
+typedef struct struct_108byte {
+ double a;
+ double b;
+ double c;
+ double d;
+ double e;
+ double f;
+ double g;
+ double h;
+ double i;
+ double j;
+ double k;
+ double l;
+ double m;
+ int n;
+} struct_108byte;
+
+struct_108byte cls_struct_108byte_fn(
+ struct_108byte b0,
+ struct_108byte b1,
+ struct_108byte b2,
+ struct_108byte b3)
+{
+ struct_108byte result;
+
+ result.a = b0.a + b1.a + b2.a + b3.a;
+ result.b = b0.b + b1.b + b2.b + b3.b;
+ result.c = b0.c + b1.c + b2.c + b3.c;
+ result.d = b0.d + b1.d + b2.d + b3.d;
+ result.e = b0.e + b1.e + b2.e + b3.e;
+ result.f = b0.f + b1.f + b2.f + b3.f;
+ result.g = b0.g + b1.g + b2.g + b3.g;
+ result.h = b0.h + b1.h + b2.h + b3.h;
+ result.i = b0.i + b1.i + b2.i + b3.i;
+ result.j = b0.j + b1.j + b2.j + b3.j;
+ result.k = b0.k + b1.k + b2.k + b3.k;
+ result.l = b0.l + b1.l + b2.l + b3.l;
+ result.m = b0.m + b1.m + b2.m + b3.m;
+ result.n = b0.n + b1.n + b2.n + b3.n;
+
+ printf("%g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", result.a, result.b, result.c,
+ result.d, result.e, result.f, result.g, result.h, result.i,
+ result.j, result.k, result.l, result.m, result.n);
+
+ return result;
+}
+
+static void
+cls_struct_108byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__)
+{
+ struct_108byte b0, b1, b2, b3;
+
+ b0 = *(struct_108byte*)(args[0]);
+ b1 = *(struct_108byte*)(args[1]);
+ b2 = *(struct_108byte*)(args[2]);
+ b3 = *(struct_108byte*)(args[3]);
+
+ *(struct_108byte*)resp = cls_struct_108byte_fn(b0, b1, b2, b3);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[15];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct_108byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 1.0, 2.0, 3.0, 7.0, 2.0, 7 };
+ struct_108byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4.0, 5.0, 7.0, 9.0, 1.0, 4 };
+ struct_108byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 8.0, 6.0, 1.0, 4.0, 0.0, 3 };
+ struct_108byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 9.0, 2.0, 6.0, 5.0, 3.0, 2 };
+ struct_108byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_double;
+ cls_struct_fields[2] = &ffi_type_double;
+ cls_struct_fields[3] = &ffi_type_double;
+ cls_struct_fields[4] = &ffi_type_double;
+ cls_struct_fields[5] = &ffi_type_double;
+ cls_struct_fields[6] = &ffi_type_double;
+ cls_struct_fields[7] = &ffi_type_double;
+ cls_struct_fields[8] = &ffi_type_double;
+ cls_struct_fields[9] = &ffi_type_double;
+ cls_struct_fields[10] = &ffi_type_double;
+ cls_struct_fields[11] = &ffi_type_double;
+ cls_struct_fields[12] = &ffi_type_double;
+ cls_struct_fields[13] = &ffi_type_sint32;
+ cls_struct_fields[14] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = &cls_struct_type;
+ dbl_arg_types[3] = &cls_struct_type;
+ dbl_arg_types[4] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = &h_dbl;
+ args_dbl[4] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_108byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */
+ printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b,
+ res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i,
+ res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n);
+ /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_108byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((struct_108byte(*)(struct_108byte, struct_108byte,
+ struct_108byte, struct_108byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl);
+ /* { dg-output "\n22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */
+ printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b,
+ res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i,
+ res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n);
+ /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/stret_large/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/stret_large/ya.make
index 13bb8f93fb..7fba7a537a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/stret_large/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/stret_large/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- stret_large.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ stret_large.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/stret_large2.c b/contrib/restricted/libffi/testsuite/libffi.closures/stret_large2.c
index e7a11c4132..d9c750ee1c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/stret_large2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/stret_large2.c
@@ -1,148 +1,148 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure returning with different structure size.
- Depending on the ABI. Check bigger struct which overlaps
- the gp and fp register count on Darwin/AIX/ppc64.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/21/2007 */
-
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
-#include "ffitest.h"
-
-/* 13 FPRs: 104 bytes */
-/* 14 FPRs: 112 bytes */
-
-typedef struct struct_116byte {
- double a;
- double b;
- double c;
- double d;
- double e;
- double f;
- double g;
- double h;
- double i;
- double j;
- double k;
- double l;
- double m;
- double n;
- int o;
-} struct_116byte;
-
-struct_116byte cls_struct_116byte_fn(
- struct_116byte b0,
- struct_116byte b1,
- struct_116byte b2,
- struct_116byte b3)
-{
- struct_116byte result;
-
- result.a = b0.a + b1.a + b2.a + b3.a;
- result.b = b0.b + b1.b + b2.b + b3.b;
- result.c = b0.c + b1.c + b2.c + b3.c;
- result.d = b0.d + b1.d + b2.d + b3.d;
- result.e = b0.e + b1.e + b2.e + b3.e;
- result.f = b0.f + b1.f + b2.f + b3.f;
- result.g = b0.g + b1.g + b2.g + b3.g;
- result.h = b0.h + b1.h + b2.h + b3.h;
- result.i = b0.i + b1.i + b2.i + b3.i;
- result.j = b0.j + b1.j + b2.j + b3.j;
- result.k = b0.k + b1.k + b2.k + b3.k;
- result.l = b0.l + b1.l + b2.l + b3.l;
- result.m = b0.m + b1.m + b2.m + b3.m;
- result.n = b0.n + b1.n + b2.n + b3.n;
- result.o = b0.o + b1.o + b2.o + b3.o;
-
- printf("%g %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", result.a, result.b, result.c,
- result.d, result.e, result.f, result.g, result.h, result.i,
- result.j, result.k, result.l, result.m, result.n, result.o);
-
- return result;
-}
-
-static void
-cls_struct_116byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__)
-{
- struct_116byte b0, b1, b2, b3;
-
- b0 = *(struct_116byte*)(args[0]);
- b1 = *(struct_116byte*)(args[1]);
- b2 = *(struct_116byte*)(args[2]);
- b3 = *(struct_116byte*)(args[3]);
-
- *(struct_116byte*)resp = cls_struct_116byte_fn(b0, b1, b2, b3);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[16];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct_116byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 7 };
- struct_116byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4.0, 5.0, 7.0, 9.0, 1.0, 6.0, 4 };
- struct_116byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 8.0, 6.0, 1.0, 4.0, 0.0, 7.0, 3 };
- struct_116byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 9.0, 2.0, 6.0, 5.0, 3.0, 8.0, 2 };
- struct_116byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_double;
- cls_struct_fields[2] = &ffi_type_double;
- cls_struct_fields[3] = &ffi_type_double;
- cls_struct_fields[4] = &ffi_type_double;
- cls_struct_fields[5] = &ffi_type_double;
- cls_struct_fields[6] = &ffi_type_double;
- cls_struct_fields[7] = &ffi_type_double;
- cls_struct_fields[8] = &ffi_type_double;
- cls_struct_fields[9] = &ffi_type_double;
- cls_struct_fields[10] = &ffi_type_double;
- cls_struct_fields[11] = &ffi_type_double;
- cls_struct_fields[12] = &ffi_type_double;
- cls_struct_fields[13] = &ffi_type_double;
- cls_struct_fields[14] = &ffi_type_sint32;
- cls_struct_fields[15] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = &cls_struct_type;
- dbl_arg_types[3] = &cls_struct_type;
- dbl_arg_types[4] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = &h_dbl;
- args_dbl[4] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_116byte_fn), &res_dbl, args_dbl);
- /* { dg-output "22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */
- printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b,
- res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i,
- res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n, res_dbl.o);
- /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_116byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((struct_116byte(*)(struct_116byte, struct_116byte,
- struct_116byte, struct_116byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl);
- /* { dg-output "\n22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */
- printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b,
- res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i,
- res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n, res_dbl.o);
- /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure returning with different structure size.
+ Depending on the ABI. Check bigger struct which overlaps
+ the gp and fp register count on Darwin/AIX/ppc64.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/21/2007 */
+
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
+#include "ffitest.h"
+
+/* 13 FPRs: 104 bytes */
+/* 14 FPRs: 112 bytes */
+
+typedef struct struct_116byte {
+ double a;
+ double b;
+ double c;
+ double d;
+ double e;
+ double f;
+ double g;
+ double h;
+ double i;
+ double j;
+ double k;
+ double l;
+ double m;
+ double n;
+ int o;
+} struct_116byte;
+
+struct_116byte cls_struct_116byte_fn(
+ struct_116byte b0,
+ struct_116byte b1,
+ struct_116byte b2,
+ struct_116byte b3)
+{
+ struct_116byte result;
+
+ result.a = b0.a + b1.a + b2.a + b3.a;
+ result.b = b0.b + b1.b + b2.b + b3.b;
+ result.c = b0.c + b1.c + b2.c + b3.c;
+ result.d = b0.d + b1.d + b2.d + b3.d;
+ result.e = b0.e + b1.e + b2.e + b3.e;
+ result.f = b0.f + b1.f + b2.f + b3.f;
+ result.g = b0.g + b1.g + b2.g + b3.g;
+ result.h = b0.h + b1.h + b2.h + b3.h;
+ result.i = b0.i + b1.i + b2.i + b3.i;
+ result.j = b0.j + b1.j + b2.j + b3.j;
+ result.k = b0.k + b1.k + b2.k + b3.k;
+ result.l = b0.l + b1.l + b2.l + b3.l;
+ result.m = b0.m + b1.m + b2.m + b3.m;
+ result.n = b0.n + b1.n + b2.n + b3.n;
+ result.o = b0.o + b1.o + b2.o + b3.o;
+
+ printf("%g %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", result.a, result.b, result.c,
+ result.d, result.e, result.f, result.g, result.h, result.i,
+ result.j, result.k, result.l, result.m, result.n, result.o);
+
+ return result;
+}
+
+static void
+cls_struct_116byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__)
+{
+ struct_116byte b0, b1, b2, b3;
+
+ b0 = *(struct_116byte*)(args[0]);
+ b1 = *(struct_116byte*)(args[1]);
+ b2 = *(struct_116byte*)(args[2]);
+ b3 = *(struct_116byte*)(args[3]);
+
+ *(struct_116byte*)resp = cls_struct_116byte_fn(b0, b1, b2, b3);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[16];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct_116byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 7 };
+ struct_116byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4.0, 5.0, 7.0, 9.0, 1.0, 6.0, 4 };
+ struct_116byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 8.0, 6.0, 1.0, 4.0, 0.0, 7.0, 3 };
+ struct_116byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 9.0, 2.0, 6.0, 5.0, 3.0, 8.0, 2 };
+ struct_116byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_double;
+ cls_struct_fields[2] = &ffi_type_double;
+ cls_struct_fields[3] = &ffi_type_double;
+ cls_struct_fields[4] = &ffi_type_double;
+ cls_struct_fields[5] = &ffi_type_double;
+ cls_struct_fields[6] = &ffi_type_double;
+ cls_struct_fields[7] = &ffi_type_double;
+ cls_struct_fields[8] = &ffi_type_double;
+ cls_struct_fields[9] = &ffi_type_double;
+ cls_struct_fields[10] = &ffi_type_double;
+ cls_struct_fields[11] = &ffi_type_double;
+ cls_struct_fields[12] = &ffi_type_double;
+ cls_struct_fields[13] = &ffi_type_double;
+ cls_struct_fields[14] = &ffi_type_sint32;
+ cls_struct_fields[15] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = &cls_struct_type;
+ dbl_arg_types[3] = &cls_struct_type;
+ dbl_arg_types[4] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = &h_dbl;
+ args_dbl[4] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_116byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */
+ printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b,
+ res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i,
+ res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n, res_dbl.o);
+ /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_116byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((struct_116byte(*)(struct_116byte, struct_116byte,
+ struct_116byte, struct_116byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl);
+ /* { dg-output "\n22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */
+ printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b,
+ res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i,
+ res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n, res_dbl.o);
+ /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/stret_large2/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/stret_large2/ya.make
index 6507807b77..5320e5e8f9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/stret_large2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/stret_large2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- stret_large2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ stret_large2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium.c b/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium.c
index fed5f7ec41..973ee02ede 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium.c
@@ -1,124 +1,124 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure returning with different structure size.
- Depending on the ABI. Check bigger struct which overlaps
- the gp and fp register count on Darwin/AIX/ppc64.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/21/2007 */
-
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
-#include "ffitest.h"
-
-typedef struct struct_72byte {
- double a;
- double b;
- double c;
- double d;
- double e;
- double f;
- double g;
- double h;
- double i;
-} struct_72byte;
-
-struct_72byte cls_struct_72byte_fn(
- struct_72byte b0,
- struct_72byte b1,
- struct_72byte b2,
- struct_72byte b3)
-{
- struct_72byte result;
-
- result.a = b0.a + b1.a + b2.a + b3.a;
- result.b = b0.b + b1.b + b2.b + b3.b;
- result.c = b0.c + b1.c + b2.c + b3.c;
- result.d = b0.d + b1.d + b2.d + b3.d;
- result.e = b0.e + b1.e + b2.e + b3.e;
- result.f = b0.f + b1.f + b2.f + b3.f;
- result.g = b0.g + b1.g + b2.g + b3.g;
- result.h = b0.h + b1.h + b2.h + b3.h;
- result.i = b0.i + b1.i + b2.i + b3.i;
-
- printf("%g %g %g %g %g %g %g %g %g\n", result.a, result.b, result.c,
- result.d, result.e, result.f, result.g, result.h, result.i);
-
- return result;
-}
-
-static void
-cls_struct_72byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__)
-{
- struct_72byte b0, b1, b2, b3;
-
- b0 = *(struct_72byte*)(args[0]);
- b1 = *(struct_72byte*)(args[1]);
- b2 = *(struct_72byte*)(args[2]);
- b3 = *(struct_72byte*)(args[3]);
-
- *(struct_72byte*)resp = cls_struct_72byte_fn(b0, b1, b2, b3);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[10];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct_72byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 7.0 };
- struct_72byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4.0 };
- struct_72byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 3.0 };
- struct_72byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 2.0 };
- struct_72byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_double;
- cls_struct_fields[2] = &ffi_type_double;
- cls_struct_fields[3] = &ffi_type_double;
- cls_struct_fields[4] = &ffi_type_double;
- cls_struct_fields[5] = &ffi_type_double;
- cls_struct_fields[6] = &ffi_type_double;
- cls_struct_fields[7] = &ffi_type_double;
- cls_struct_fields[8] = &ffi_type_double;
- cls_struct_fields[9] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = &cls_struct_type;
- dbl_arg_types[3] = &cls_struct_type;
- dbl_arg_types[4] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = &h_dbl;
- args_dbl[4] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_72byte_fn), &res_dbl, args_dbl);
- /* { dg-output "22 15 17 25 6 13 19 18 16" } */
- printf("res: %g %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i);
- /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_72byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((struct_72byte(*)(struct_72byte, struct_72byte,
- struct_72byte, struct_72byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl);
- /* { dg-output "\n22 15 17 25 6 13 19 18 16" } */
- printf("res: %g %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i);
- /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure returning with different structure size.
+ Depending on the ABI. Check bigger struct which overlaps
+ the gp and fp register count on Darwin/AIX/ppc64.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/21/2007 */
+
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
+#include "ffitest.h"
+
+typedef struct struct_72byte {
+ double a;
+ double b;
+ double c;
+ double d;
+ double e;
+ double f;
+ double g;
+ double h;
+ double i;
+} struct_72byte;
+
+struct_72byte cls_struct_72byte_fn(
+ struct_72byte b0,
+ struct_72byte b1,
+ struct_72byte b2,
+ struct_72byte b3)
+{
+ struct_72byte result;
+
+ result.a = b0.a + b1.a + b2.a + b3.a;
+ result.b = b0.b + b1.b + b2.b + b3.b;
+ result.c = b0.c + b1.c + b2.c + b3.c;
+ result.d = b0.d + b1.d + b2.d + b3.d;
+ result.e = b0.e + b1.e + b2.e + b3.e;
+ result.f = b0.f + b1.f + b2.f + b3.f;
+ result.g = b0.g + b1.g + b2.g + b3.g;
+ result.h = b0.h + b1.h + b2.h + b3.h;
+ result.i = b0.i + b1.i + b2.i + b3.i;
+
+ printf("%g %g %g %g %g %g %g %g %g\n", result.a, result.b, result.c,
+ result.d, result.e, result.f, result.g, result.h, result.i);
+
+ return result;
+}
+
+static void
+cls_struct_72byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__)
+{
+ struct_72byte b0, b1, b2, b3;
+
+ b0 = *(struct_72byte*)(args[0]);
+ b1 = *(struct_72byte*)(args[1]);
+ b2 = *(struct_72byte*)(args[2]);
+ b3 = *(struct_72byte*)(args[3]);
+
+ *(struct_72byte*)resp = cls_struct_72byte_fn(b0, b1, b2, b3);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[10];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct_72byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 7.0 };
+ struct_72byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4.0 };
+ struct_72byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 3.0 };
+ struct_72byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 2.0 };
+ struct_72byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_double;
+ cls_struct_fields[2] = &ffi_type_double;
+ cls_struct_fields[3] = &ffi_type_double;
+ cls_struct_fields[4] = &ffi_type_double;
+ cls_struct_fields[5] = &ffi_type_double;
+ cls_struct_fields[6] = &ffi_type_double;
+ cls_struct_fields[7] = &ffi_type_double;
+ cls_struct_fields[8] = &ffi_type_double;
+ cls_struct_fields[9] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = &cls_struct_type;
+ dbl_arg_types[3] = &cls_struct_type;
+ dbl_arg_types[4] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = &h_dbl;
+ args_dbl[4] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_72byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "22 15 17 25 6 13 19 18 16" } */
+ printf("res: %g %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i);
+ /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_72byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((struct_72byte(*)(struct_72byte, struct_72byte,
+ struct_72byte, struct_72byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl);
+ /* { dg-output "\n22 15 17 25 6 13 19 18 16" } */
+ printf("res: %g %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i);
+ /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium/ya.make
index 6ee0376ecc..fc8b550f06 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- stret_medium.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ stret_medium.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium2.c b/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium2.c
index 51090da278..84323d16a9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium2.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium2.c
@@ -1,125 +1,125 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure returning with different structure size.
- Depending on the ABI. Check bigger struct which overlaps
- the gp and fp register count on Darwin/AIX/ppc64.
- Limitations: none.
- PR: none.
- Originator: Blake Chaffin 6/21/2007 */
-
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
-/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */
-#include "ffitest.h"
-
-typedef struct struct_72byte {
- double a;
- double b;
- double c;
- double d;
- double e;
- double f;
- double g;
- double h;
- long long i;
-} struct_72byte;
-
-struct_72byte cls_struct_72byte_fn(
- struct_72byte b0,
- struct_72byte b1,
- struct_72byte b2,
- struct_72byte b3)
-{
- struct_72byte result;
-
- result.a = b0.a + b1.a + b2.a + b3.a;
- result.b = b0.b + b1.b + b2.b + b3.b;
- result.c = b0.c + b1.c + b2.c + b3.c;
- result.d = b0.d + b1.d + b2.d + b3.d;
- result.e = b0.e + b1.e + b2.e + b3.e;
- result.f = b0.f + b1.f + b2.f + b3.f;
- result.g = b0.g + b1.g + b2.g + b3.g;
- result.h = b0.h + b1.h + b2.h + b3.h;
- result.i = b0.i + b1.i + b2.i + b3.i;
-
- printf("%g %g %g %g %g %g %g %g %" PRIdLL "\n", result.a, result.b, result.c,
- result.d, result.e, result.f, result.g, result.h, result.i);
-
- return result;
-}
-
-static void
-cls_struct_72byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__)
-{
- struct_72byte b0, b1, b2, b3;
-
- b0 = *(struct_72byte*)(args[0]);
- b1 = *(struct_72byte*)(args[1]);
- b2 = *(struct_72byte*)(args[2]);
- b3 = *(struct_72byte*)(args[3]);
-
- *(struct_72byte*)resp = cls_struct_72byte_fn(b0, b1, b2, b3);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_dbl[5];
- ffi_type* cls_struct_fields[10];
- ffi_type cls_struct_type;
- ffi_type* dbl_arg_types[5];
-
- struct_72byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 7 };
- struct_72byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4 };
- struct_72byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 3 };
- struct_72byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 2 };
- struct_72byte res_dbl;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_double;
- cls_struct_fields[1] = &ffi_type_double;
- cls_struct_fields[2] = &ffi_type_double;
- cls_struct_fields[3] = &ffi_type_double;
- cls_struct_fields[4] = &ffi_type_double;
- cls_struct_fields[5] = &ffi_type_double;
- cls_struct_fields[6] = &ffi_type_double;
- cls_struct_fields[7] = &ffi_type_double;
- cls_struct_fields[8] = &ffi_type_sint64;
- cls_struct_fields[9] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type;
- dbl_arg_types[1] = &cls_struct_type;
- dbl_arg_types[2] = &cls_struct_type;
- dbl_arg_types[3] = &cls_struct_type;
- dbl_arg_types[4] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
- dbl_arg_types) == FFI_OK);
-
- args_dbl[0] = &e_dbl;
- args_dbl[1] = &f_dbl;
- args_dbl[2] = &g_dbl;
- args_dbl[3] = &h_dbl;
- args_dbl[4] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_72byte_fn), &res_dbl, args_dbl);
- /* { dg-output "22 15 17 25 6 13 19 18 16" } */
- printf("res: %g %g %g %g %g %g %g %g %" PRIdLL "\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i);
- /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_72byte_gn, NULL, code) == FFI_OK);
-
- res_dbl = ((struct_72byte(*)(struct_72byte, struct_72byte,
- struct_72byte, struct_72byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl);
- /* { dg-output "\n22 15 17 25 6 13 19 18 16" } */
- printf("res: %g %g %g %g %g %g %g %g %" PRIdLL "\n", res_dbl.a, res_dbl.b, res_dbl.c,
- res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i);
- /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */
-
- exit(0);
-}
+/* Area: ffi_call, closure_call
+ Purpose: Check structure returning with different structure size.
+ Depending on the ABI. Check bigger struct which overlaps
+ the gp and fp register count on Darwin/AIX/ppc64.
+ Limitations: none.
+ PR: none.
+ Originator: Blake Chaffin 6/21/2007 */
+
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
+/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */
+#include "ffitest.h"
+
+typedef struct struct_72byte {
+ double a;
+ double b;
+ double c;
+ double d;
+ double e;
+ double f;
+ double g;
+ double h;
+ long long i;
+} struct_72byte;
+
+struct_72byte cls_struct_72byte_fn(
+ struct_72byte b0,
+ struct_72byte b1,
+ struct_72byte b2,
+ struct_72byte b3)
+{
+ struct_72byte result;
+
+ result.a = b0.a + b1.a + b2.a + b3.a;
+ result.b = b0.b + b1.b + b2.b + b3.b;
+ result.c = b0.c + b1.c + b2.c + b3.c;
+ result.d = b0.d + b1.d + b2.d + b3.d;
+ result.e = b0.e + b1.e + b2.e + b3.e;
+ result.f = b0.f + b1.f + b2.f + b3.f;
+ result.g = b0.g + b1.g + b2.g + b3.g;
+ result.h = b0.h + b1.h + b2.h + b3.h;
+ result.i = b0.i + b1.i + b2.i + b3.i;
+
+ printf("%g %g %g %g %g %g %g %g %" PRIdLL "\n", result.a, result.b, result.c,
+ result.d, result.e, result.f, result.g, result.h, result.i);
+
+ return result;
+}
+
+static void
+cls_struct_72byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__)
+{
+ struct_72byte b0, b1, b2, b3;
+
+ b0 = *(struct_72byte*)(args[0]);
+ b1 = *(struct_72byte*)(args[1]);
+ b2 = *(struct_72byte*)(args[2]);
+ b3 = *(struct_72byte*)(args[3]);
+
+ *(struct_72byte*)resp = cls_struct_72byte_fn(b0, b1, b2, b3);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_dbl[5];
+ ffi_type* cls_struct_fields[10];
+ ffi_type cls_struct_type;
+ ffi_type* dbl_arg_types[5];
+
+ struct_72byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 7 };
+ struct_72byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4 };
+ struct_72byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 3 };
+ struct_72byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 2 };
+ struct_72byte res_dbl;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_double;
+ cls_struct_fields[1] = &ffi_type_double;
+ cls_struct_fields[2] = &ffi_type_double;
+ cls_struct_fields[3] = &ffi_type_double;
+ cls_struct_fields[4] = &ffi_type_double;
+ cls_struct_fields[5] = &ffi_type_double;
+ cls_struct_fields[6] = &ffi_type_double;
+ cls_struct_fields[7] = &ffi_type_double;
+ cls_struct_fields[8] = &ffi_type_sint64;
+ cls_struct_fields[9] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type;
+ dbl_arg_types[1] = &cls_struct_type;
+ dbl_arg_types[2] = &cls_struct_type;
+ dbl_arg_types[3] = &cls_struct_type;
+ dbl_arg_types[4] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type,
+ dbl_arg_types) == FFI_OK);
+
+ args_dbl[0] = &e_dbl;
+ args_dbl[1] = &f_dbl;
+ args_dbl[2] = &g_dbl;
+ args_dbl[3] = &h_dbl;
+ args_dbl[4] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_72byte_fn), &res_dbl, args_dbl);
+ /* { dg-output "22 15 17 25 6 13 19 18 16" } */
+ printf("res: %g %g %g %g %g %g %g %g %" PRIdLL "\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i);
+ /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_72byte_gn, NULL, code) == FFI_OK);
+
+ res_dbl = ((struct_72byte(*)(struct_72byte, struct_72byte,
+ struct_72byte, struct_72byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl);
+ /* { dg-output "\n22 15 17 25 6 13 19 18 16" } */
+ printf("res: %g %g %g %g %g %g %g %g %" PRIdLL "\n", res_dbl.a, res_dbl.b, res_dbl.c,
+ res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i);
+ /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium2/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium2/ya.make
index 8bacc5ecaf..bc1bb11694 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium2/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/stret_medium2/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- stret_medium2.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ stret_medium2.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/testclosure.c b/contrib/restricted/libffi/testsuite/libffi.closures/testclosure.c
index 692153be55..ca31056d8c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/testclosure.c
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/testclosure.c
@@ -1,70 +1,70 @@
-/* Area: closure_call
- Purpose: Check return value float.
- Limitations: none.
- PR: 41908.
- Originator: <rfm@gnu.org> 20091102 */
-
-/* { dg-do run } */
-#include "ffitest.h"
-
-typedef struct cls_struct_combined {
- float a;
- float b;
- float c;
- float d;
-} cls_struct_combined;
-
-void cls_struct_combined_fn(struct cls_struct_combined arg)
-{
- printf("%g %g %g %g\n",
- arg.a, arg.b,
- arg.c, arg.d);
- fflush(stdout);
-}
-
-static void
-cls_struct_combined_gn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__,
- void** args, void* userdata __UNUSED__)
-{
- struct cls_struct_combined a0;
-
- a0 = *(struct cls_struct_combined*)(args[0]);
-
- cls_struct_combined_fn(a0);
-}
-
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type* cls_struct_fields0[5];
- ffi_type cls_struct_type0;
- ffi_type* dbl_arg_types[5];
-
- struct cls_struct_combined g_dbl = {4.0, 5.0, 1.0, 8.0};
-
- cls_struct_type0.size = 0;
- cls_struct_type0.alignment = 0;
- cls_struct_type0.type = FFI_TYPE_STRUCT;
- cls_struct_type0.elements = cls_struct_fields0;
-
- cls_struct_fields0[0] = &ffi_type_float;
- cls_struct_fields0[1] = &ffi_type_float;
- cls_struct_fields0[2] = &ffi_type_float;
- cls_struct_fields0[3] = &ffi_type_float;
- cls_struct_fields0[4] = NULL;
-
- dbl_arg_types[0] = &cls_struct_type0;
- dbl_arg_types[1] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, &ffi_type_void,
- dbl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_combined_gn, NULL, code) == FFI_OK);
-
- ((void(*)(cls_struct_combined)) (code))(g_dbl);
- /* { dg-output "4 5 1 8" } */
- exit(0);
-}
+/* Area: closure_call
+ Purpose: Check return value float.
+ Limitations: none.
+ PR: 41908.
+ Originator: <rfm@gnu.org> 20091102 */
+
+/* { dg-do run } */
+#include "ffitest.h"
+
+typedef struct cls_struct_combined {
+ float a;
+ float b;
+ float c;
+ float d;
+} cls_struct_combined;
+
+void cls_struct_combined_fn(struct cls_struct_combined arg)
+{
+ printf("%g %g %g %g\n",
+ arg.a, arg.b,
+ arg.c, arg.d);
+ fflush(stdout);
+}
+
+static void
+cls_struct_combined_gn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__,
+ void** args, void* userdata __UNUSED__)
+{
+ struct cls_struct_combined a0;
+
+ a0 = *(struct cls_struct_combined*)(args[0]);
+
+ cls_struct_combined_fn(a0);
+}
+
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type* cls_struct_fields0[5];
+ ffi_type cls_struct_type0;
+ ffi_type* dbl_arg_types[5];
+
+ struct cls_struct_combined g_dbl = {4.0, 5.0, 1.0, 8.0};
+
+ cls_struct_type0.size = 0;
+ cls_struct_type0.alignment = 0;
+ cls_struct_type0.type = FFI_TYPE_STRUCT;
+ cls_struct_type0.elements = cls_struct_fields0;
+
+ cls_struct_fields0[0] = &ffi_type_float;
+ cls_struct_fields0[1] = &ffi_type_float;
+ cls_struct_fields0[2] = &ffi_type_float;
+ cls_struct_fields0[3] = &ffi_type_float;
+ cls_struct_fields0[4] = NULL;
+
+ dbl_arg_types[0] = &cls_struct_type0;
+ dbl_arg_types[1] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, &ffi_type_void,
+ dbl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_combined_gn, NULL, code) == FFI_OK);
+
+ ((void(*)(cls_struct_combined)) (code))(g_dbl);
+ /* { dg-output "4 5 1 8" } */
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/testclosure/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/testclosure/ya.make
index 91a285f00a..4bfb5ef07d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/testclosure/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/testclosure/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
-
-SRCS(
- testclosure.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.closures)
+
+SRCS(
+ testclosure.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.closures/ya.make b/contrib/restricted/libffi/testsuite/libffi.closures/ya.make
index 45f9516162..40565af539 100644
--- a/contrib/restricted/libffi/testsuite/libffi.closures/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.closures/ya.make
@@ -1,103 +1,103 @@
-# Generated by devtools/yamaker.
-
-RECURSE(
- closure_fn0
- closure_fn1
- closure_fn2
- closure_fn3
- closure_fn4
- closure_fn5
- closure_fn6
- closure_loc_fn0
- closure_simple
- cls_12byte
- cls_16byte
- cls_18byte
- cls_19byte
- cls_1_1byte
- cls_20byte
- cls_20byte1
- cls_24byte
- cls_2byte
- cls_3_1byte
- cls_3byte1
- cls_3byte2
- cls_3float
- cls_4_1byte
- cls_4byte
- cls_5_1_byte
- cls_5byte
- cls_64byte
- cls_6_1_byte
- cls_6byte
- cls_7_1_byte
- cls_7byte
- cls_8byte
- cls_9byte1
- cls_9byte2
- cls_align_double
- cls_align_float
- cls_align_longdouble
- cls_align_pointer
- cls_align_sint16
- cls_align_sint32
- cls_align_sint64
- cls_align_uint16
- cls_align_uint32
- cls_align_uint64
- cls_dbls_struct
- cls_double
- cls_double_va
- cls_float
- cls_longdouble
- cls_longdouble_va
- cls_many_mixed_args
- cls_multi_schar
- cls_multi_sshort
- cls_multi_sshortchar
- cls_multi_uchar
- cls_multi_ushort
- cls_multi_ushortchar
- cls_pointer
- cls_pointer_stack
- cls_schar
- cls_sint
- cls_sshort
- cls_struct_va1
- cls_uchar
- cls_uchar_va
- cls_uint
- cls_uint_va
- cls_ulong_va
- cls_ulonglong
- cls_ushort
- cls_ushort_va
- err_bad_abi
- huge_struct
- nested_struct
- nested_struct1
- nested_struct10
- nested_struct11
- nested_struct2
- nested_struct3
- nested_struct4
- nested_struct5
- nested_struct6
- nested_struct7
- nested_struct8
- nested_struct9
- problem1
- stret_large
- stret_large2
- stret_medium
- stret_medium2
- testclosure
-)
-
-IF (NOT OS_WINDOWS)
- RECURSE(
- cls_align_longdouble_split
- cls_align_longdouble_split2
- cls_many_mixed_float_double
- )
-ENDIF()
+# Generated by devtools/yamaker.
+
+RECURSE(
+ closure_fn0
+ closure_fn1
+ closure_fn2
+ closure_fn3
+ closure_fn4
+ closure_fn5
+ closure_fn6
+ closure_loc_fn0
+ closure_simple
+ cls_12byte
+ cls_16byte
+ cls_18byte
+ cls_19byte
+ cls_1_1byte
+ cls_20byte
+ cls_20byte1
+ cls_24byte
+ cls_2byte
+ cls_3_1byte
+ cls_3byte1
+ cls_3byte2
+ cls_3float
+ cls_4_1byte
+ cls_4byte
+ cls_5_1_byte
+ cls_5byte
+ cls_64byte
+ cls_6_1_byte
+ cls_6byte
+ cls_7_1_byte
+ cls_7byte
+ cls_8byte
+ cls_9byte1
+ cls_9byte2
+ cls_align_double
+ cls_align_float
+ cls_align_longdouble
+ cls_align_pointer
+ cls_align_sint16
+ cls_align_sint32
+ cls_align_sint64
+ cls_align_uint16
+ cls_align_uint32
+ cls_align_uint64
+ cls_dbls_struct
+ cls_double
+ cls_double_va
+ cls_float
+ cls_longdouble
+ cls_longdouble_va
+ cls_many_mixed_args
+ cls_multi_schar
+ cls_multi_sshort
+ cls_multi_sshortchar
+ cls_multi_uchar
+ cls_multi_ushort
+ cls_multi_ushortchar
+ cls_pointer
+ cls_pointer_stack
+ cls_schar
+ cls_sint
+ cls_sshort
+ cls_struct_va1
+ cls_uchar
+ cls_uchar_va
+ cls_uint
+ cls_uint_va
+ cls_ulong_va
+ cls_ulonglong
+ cls_ushort
+ cls_ushort_va
+ err_bad_abi
+ huge_struct
+ nested_struct
+ nested_struct1
+ nested_struct10
+ nested_struct11
+ nested_struct2
+ nested_struct3
+ nested_struct4
+ nested_struct5
+ nested_struct6
+ nested_struct7
+ nested_struct8
+ nested_struct9
+ problem1
+ stret_large
+ stret_large2
+ stret_medium
+ stret_medium2
+ testclosure
+)
+
+IF (NOT OS_WINDOWS)
+ RECURSE(
+ cls_align_longdouble_split
+ cls_align_longdouble_split2
+ cls_many_mixed_float_double
+ )
+ENDIF()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex.inc b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex.inc
index 80c5b04bb6..4a812edf05 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex.inc
@@ -1,91 +1,91 @@
-/* -*-c-*- */
-#include "ffitest.h"
-#include <complex.h>
-
-typedef struct cls_struct_align {
- unsigned char a;
- _Complex T_C_TYPE b;
- unsigned char c;
-} cls_struct_align;
-
-cls_struct_align cls_struct_align_fn(
- struct cls_struct_align a1, struct cls_struct_align a2)
-{
- struct cls_struct_align result;
-
- result.a = a1.a + a2.a;
- result.b = a1.b + a2.b;
- result.c = a1.c + a2.c;
-
- printf("%d %f,%fi %d %d %f,%fi %d: %d %f,%fi %d\n",
- a1.a, T_CONV creal (a1.b), T_CONV cimag (a1.b), a1.c,
- a2.a, T_CONV creal (a2.b), T_CONV cimag (a2.b), a2.c,
- result.a, T_CONV creal (result.b), T_CONV cimag (result.b), result.c);
-
- return result;
-}
-
-static void
-cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
-{
-
- struct cls_struct_align a1, a2;
-
- a1 = *(struct cls_struct_align*)(args[0]);
- a2 = *(struct cls_struct_align*)(args[1]);
-
- *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args_c[5];
- ffi_type* cls_struct_fields[4];
- ffi_type cls_struct_type;
- ffi_type* c_arg_types[5];
-
- struct cls_struct_align g_c = { 12, 4951 + 7 * I, 127 };
- struct cls_struct_align f_c = { 1, 9320 + 1 * I, 13 };
- struct cls_struct_align res_c;
-
- cls_struct_type.size = 0;
- cls_struct_type.alignment = 0;
- cls_struct_type.type = FFI_TYPE_STRUCT;
- cls_struct_type.elements = cls_struct_fields;
-
- cls_struct_fields[0] = &ffi_type_uchar;
- cls_struct_fields[1] = &T_FFI_TYPE;
- cls_struct_fields[2] = &ffi_type_uchar;
- cls_struct_fields[3] = NULL;
-
- c_arg_types[0] = &cls_struct_type;
- c_arg_types[1] = &cls_struct_type;
- c_arg_types[2] = NULL;
-
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
- c_arg_types) == FFI_OK);
-
- args_c[0] = &g_c;
- args_c[1] = &f_c;
- args_c[2] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_c, args_c);
- /* { dg-output "12 4951,7i 127 1 9320,1i 13: 13 14271,8i 140" } */
- printf("res: %d %f,%fi %d\n",
- res_c.a, T_CONV creal (res_c.b), T_CONV cimag (res_c.b), res_c.c);
- /* { dg-output "\nres: 13 14271,8i 140" } */
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
-
- res_c = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_c, f_c);
- /* { dg-output "\n12 4951,7i 127 1 9320,1i 13: 13 14271,8i 140" } */
- printf("res: %d %f,%fi %d\n",
- res_c.a, T_CONV creal (res_c.b), T_CONV cimag (res_c.b), res_c.c);
- /* { dg-output "\nres: 13 14271,8i 140" } */
-
- exit(0);
-}
+/* -*-c-*- */
+#include "ffitest.h"
+#include <complex.h>
+
+typedef struct cls_struct_align {
+ unsigned char a;
+ _Complex T_C_TYPE b;
+ unsigned char c;
+} cls_struct_align;
+
+cls_struct_align cls_struct_align_fn(
+ struct cls_struct_align a1, struct cls_struct_align a2)
+{
+ struct cls_struct_align result;
+
+ result.a = a1.a + a2.a;
+ result.b = a1.b + a2.b;
+ result.c = a1.c + a2.c;
+
+ printf("%d %f,%fi %d %d %f,%fi %d: %d %f,%fi %d\n",
+ a1.a, T_CONV creal (a1.b), T_CONV cimag (a1.b), a1.c,
+ a2.a, T_CONV creal (a2.b), T_CONV cimag (a2.b), a2.c,
+ result.a, T_CONV creal (result.b), T_CONV cimag (result.b), result.c);
+
+ return result;
+}
+
+static void
+cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+{
+
+ struct cls_struct_align a1, a2;
+
+ a1 = *(struct cls_struct_align*)(args[0]);
+ a2 = *(struct cls_struct_align*)(args[1]);
+
+ *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args_c[5];
+ ffi_type* cls_struct_fields[4];
+ ffi_type cls_struct_type;
+ ffi_type* c_arg_types[5];
+
+ struct cls_struct_align g_c = { 12, 4951 + 7 * I, 127 };
+ struct cls_struct_align f_c = { 1, 9320 + 1 * I, 13 };
+ struct cls_struct_align res_c;
+
+ cls_struct_type.size = 0;
+ cls_struct_type.alignment = 0;
+ cls_struct_type.type = FFI_TYPE_STRUCT;
+ cls_struct_type.elements = cls_struct_fields;
+
+ cls_struct_fields[0] = &ffi_type_uchar;
+ cls_struct_fields[1] = &T_FFI_TYPE;
+ cls_struct_fields[2] = &ffi_type_uchar;
+ cls_struct_fields[3] = NULL;
+
+ c_arg_types[0] = &cls_struct_type;
+ c_arg_types[1] = &cls_struct_type;
+ c_arg_types[2] = NULL;
+
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
+ c_arg_types) == FFI_OK);
+
+ args_c[0] = &g_c;
+ args_c[1] = &f_c;
+ args_c[2] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_c, args_c);
+ /* { dg-output "12 4951,7i 127 1 9320,1i 13: 13 14271,8i 140" } */
+ printf("res: %d %f,%fi %d\n",
+ res_c.a, T_CONV creal (res_c.b), T_CONV cimag (res_c.b), res_c.c);
+ /* { dg-output "\nres: 13 14271,8i 140" } */
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
+
+ res_c = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_c, f_c);
+ /* { dg-output "\n12 4951,7i 127 1 9320,1i 13: 13 14271,8i 140" } */
+ printf("res: %d %f,%fi %d\n",
+ res_c.a, T_CONV creal (res_c.b), T_CONV cimag (res_c.b), res_c.c);
+ /* { dg-output "\nres: 13 14271,8i 140" } */
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_double.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_double.c
index cf8cc09038..0dff23ae47 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_double.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_double.inc"
-#include "cls_align_complex.inc"
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_double.inc"
+#include "cls_align_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_double/ya.make
index ab71e0fb72..d83d272ce4 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_align_complex_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_align_complex_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_float.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_float.c
index 5f7bc7a02c..0affbd07e5 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_float.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_float.inc"
-#include "cls_align_complex.inc"
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_float.inc"
+#include "cls_align_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_float/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_float/ya.make
index 9f514f3cdd..57634effef 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_align_complex_float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_align_complex_float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_longdouble.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_longdouble.c
index c8307bf2d0..7889ba859b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_longdouble.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_longdouble.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call, closure_call
- Purpose: Check structure alignment of complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_longdouble.inc"
-#include "cls_align_complex.inc"
+/* Area: ffi_call, closure_call
+ Purpose: Check structure alignment of complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_longdouble.inc"
+#include "cls_align_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_longdouble/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_longdouble/ya.make
index 30064a1456..455cfb8ac9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_longdouble/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_align_complex_longdouble/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_align_complex_longdouble.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_align_complex_longdouble.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex.inc b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex.inc
index 4f27d33417..f9374044e8 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex.inc
@@ -1,42 +1,42 @@
-/* -*-c-*- */
-#include "ffitest.h"
-#include <complex.h>
-
-static void cls_ret_complex_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
- void* userdata __UNUSED__)
- {
- _Complex T_C_TYPE *pa;
- _Complex T_C_TYPE *pr;
- pa = (_Complex T_C_TYPE *)args[0];
- pr = (_Complex T_C_TYPE *)resp;
- *pr = *pa;
-
- printf("%.6f,%.6fi: %.6f,%.6fi\n",
- T_CONV creal (*pa), T_CONV cimag (*pa),
- T_CONV creal (*pr), T_CONV cimag (*pr));
- }
-typedef _Complex T_C_TYPE (*cls_ret_complex)(_Complex T_C_TYPE);
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type * cl_arg_types[2];
- _Complex T_C_TYPE res;
-
- cl_arg_types[0] = &T_FFI_TYPE;
- cl_arg_types[1] = NULL;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &T_FFI_TYPE, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_complex_fn, NULL, code) == FFI_OK);
-
- res = (*((cls_ret_complex)code))(0.125 + 128.0 * I);
- printf("res: %.6f,%.6fi\n", T_CONV creal (res), T_CONV cimag (res));
- CHECK (res == (0.125 + 128.0 * I));
-
- exit(0);
-}
+/* -*-c-*- */
+#include "ffitest.h"
+#include <complex.h>
+
+static void cls_ret_complex_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
+ void* userdata __UNUSED__)
+ {
+ _Complex T_C_TYPE *pa;
+ _Complex T_C_TYPE *pr;
+ pa = (_Complex T_C_TYPE *)args[0];
+ pr = (_Complex T_C_TYPE *)resp;
+ *pr = *pa;
+
+ printf("%.6f,%.6fi: %.6f,%.6fi\n",
+ T_CONV creal (*pa), T_CONV cimag (*pa),
+ T_CONV creal (*pr), T_CONV cimag (*pr));
+ }
+typedef _Complex T_C_TYPE (*cls_ret_complex)(_Complex T_C_TYPE);
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type * cl_arg_types[2];
+ _Complex T_C_TYPE res;
+
+ cl_arg_types[0] = &T_FFI_TYPE;
+ cl_arg_types[1] = NULL;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &T_FFI_TYPE, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_complex_fn, NULL, code) == FFI_OK);
+
+ res = (*((cls_ret_complex)code))(0.125 + 128.0 * I);
+ printf("res: %.6f,%.6fi\n", T_CONV creal (res), T_CONV cimag (res));
+ CHECK (res == (0.125 + 128.0 * I));
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_double.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_double.c
index e20b0b47f8..05e35340e0 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_double.c
@@ -1,10 +1,10 @@
-/* Area: closure_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_double.inc"
-#include "cls_complex.inc"
+/* Area: closure_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_double.inc"
+#include "cls_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_double/ya.make
index 712d62197b..2e37bfbd4b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_complex_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_complex_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_float.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_float.c
index 0015dce62c..5df7849d4c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_float.c
@@ -1,10 +1,10 @@
-/* Area: closure_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_float.inc"
-#include "cls_complex.inc"
+/* Area: closure_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_float.inc"
+#include "cls_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_float/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_float/ya.make
index cce2de0d06..a837883fba 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_complex_float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_complex_float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_longdouble.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_longdouble.c
index 123fee50c4..2b1c320a20 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_longdouble.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_longdouble.c
@@ -1,10 +1,10 @@
-/* Area: closure_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_longdouble.inc"
-#include "cls_complex.inc"
+/* Area: closure_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_longdouble.inc"
+#include "cls_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_longdouble/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_longdouble/ya.make
index d51f8468ba..84c1f3c271 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_longdouble/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_longdouble/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_complex_longdouble.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_complex_longdouble.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct.inc b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct.inc
index c2b27564a4..df8708d1c4 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct.inc
@@ -1,71 +1,71 @@
-/* -*-c-*- */
-#include "ffitest.h"
-#include <complex.h>
-
-typedef struct Cs {
- _Complex T_C_TYPE x;
- _Complex T_C_TYPE y;
-} Cs;
-
-Cs gc;
-
-void
-closure_test_fn(Cs p)
-{
- printf("%.1f,%.1fi %.1f,%.1fi\n",
- T_CONV creal (p.x), T_CONV cimag (p.x),
- T_CONV creal (p.y), T_CONV cimag (p.y));
- gc = p;
-}
-
-void
-closure_test_gn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__,
- void** args, void* userdata __UNUSED__)
-{
- closure_test_fn(*(Cs*)args[0]);
-}
-
-int main(int argc __UNUSED__, char** argv __UNUSED__)
-{
- ffi_cif cif;
-
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- ffi_type *cl_arg_types[1];
-
- ffi_type ts1_type;
- ffi_type* ts1_type_elements[4];
-
- Cs arg = { 1.0 + 11.0 * I, 2.0 + 22.0 * I};
-
- ts1_type.size = 0;
- ts1_type.alignment = 0;
- ts1_type.type = FFI_TYPE_STRUCT;
- ts1_type.elements = ts1_type_elements;
-
- ts1_type_elements[0] = &T_FFI_TYPE;
- ts1_type_elements[1] = &T_FFI_TYPE;
- ts1_type_elements[2] = NULL;
-
- cl_arg_types[0] = &ts1_type;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &ffi_type_void, cl_arg_types) == FFI_OK);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_gn, NULL, code) == FFI_OK);
-
- gc.x = 0.0 + 0.0 * I;
- gc.y = 0.0 + 0.0 * I;
- ((void*(*)(Cs))(code))(arg);
- /* { dg-output "1.0,11.0i 2.0,22.0i\n" } */
- CHECK (gc.x == arg.x && gc.y == arg.y);
-
- gc.x = 0.0 + 0.0 * I;
- gc.y = 0.0 + 0.0 * I;
- closure_test_fn(arg);
- /* { dg-output "1.0,11.0i 2.0,22.0i\n" } */
- CHECK (gc.x == arg.x && gc.y == arg.y);
-
- return 0;
-}
+/* -*-c-*- */
+#include "ffitest.h"
+#include <complex.h>
+
+typedef struct Cs {
+ _Complex T_C_TYPE x;
+ _Complex T_C_TYPE y;
+} Cs;
+
+Cs gc;
+
+void
+closure_test_fn(Cs p)
+{
+ printf("%.1f,%.1fi %.1f,%.1fi\n",
+ T_CONV creal (p.x), T_CONV cimag (p.x),
+ T_CONV creal (p.y), T_CONV cimag (p.y));
+ gc = p;
+}
+
+void
+closure_test_gn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__,
+ void** args, void* userdata __UNUSED__)
+{
+ closure_test_fn(*(Cs*)args[0]);
+}
+
+int main(int argc __UNUSED__, char** argv __UNUSED__)
+{
+ ffi_cif cif;
+
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ ffi_type *cl_arg_types[1];
+
+ ffi_type ts1_type;
+ ffi_type* ts1_type_elements[4];
+
+ Cs arg = { 1.0 + 11.0 * I, 2.0 + 22.0 * I};
+
+ ts1_type.size = 0;
+ ts1_type.alignment = 0;
+ ts1_type.type = FFI_TYPE_STRUCT;
+ ts1_type.elements = ts1_type_elements;
+
+ ts1_type_elements[0] = &T_FFI_TYPE;
+ ts1_type_elements[1] = &T_FFI_TYPE;
+ ts1_type_elements[2] = NULL;
+
+ cl_arg_types[0] = &ts1_type;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &ffi_type_void, cl_arg_types) == FFI_OK);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_gn, NULL, code) == FFI_OK);
+
+ gc.x = 0.0 + 0.0 * I;
+ gc.y = 0.0 + 0.0 * I;
+ ((void*(*)(Cs))(code))(arg);
+ /* { dg-output "1.0,11.0i 2.0,22.0i\n" } */
+ CHECK (gc.x == arg.x && gc.y == arg.y);
+
+ gc.x = 0.0 + 0.0 * I;
+ gc.y = 0.0 + 0.0 * I;
+ closure_test_fn(arg);
+ /* { dg-output "1.0,11.0i 2.0,22.0i\n" } */
+ CHECK (gc.x == arg.x && gc.y == arg.y);
+
+ return 0;
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_double.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_double.c
index 64468ccd19..ec71346a3f 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_double.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call, closure_call
- Purpose: Check complex arguments in structs.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_double.inc"
-#include "cls_complex_struct.inc"
+/* Area: ffi_call, closure_call
+ Purpose: Check complex arguments in structs.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_double.inc"
+#include "cls_complex_struct.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_double/ya.make
index 9e06c5f890..67041b3b3d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_complex_struct_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_complex_struct_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_float.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_float.c
index ec44bd1c4a..96fdf75043 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_float.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call, closure_call
- Purpose: Check complex arguments in structs.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_float.inc"
-#include "cls_complex_struct.inc"
+/* Area: ffi_call, closure_call
+ Purpose: Check complex arguments in structs.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_float.inc"
+#include "cls_complex_struct.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_float/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_float/ya.make
index f54d1a858d..a73819b826 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_complex_struct_float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_complex_struct_float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble.c
index 9aa99f3671..005b467398 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call, closure_call
- Purpose: Check complex arguments in structs.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_longdouble.inc"
-#include "cls_complex_struct.inc"
+/* Area: ffi_call, closure_call
+ Purpose: Check complex arguments in structs.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_longdouble.inc"
+#include "cls_complex_struct.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble/ya.make
index f4cbcde654..7e223a7b7e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_complex_struct_longdouble.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_complex_struct_longdouble.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va.inc b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va.inc
index fb413aa8d7..8a3e15f0f6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va.inc
@@ -1,80 +1,80 @@
-/* -*-c-*- */
-#include "ffitest.h"
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdarg.h>
-#include <complex.h>
-
-static _Complex T_C_TYPE gComplexValue1 = 1 + 2 * I;
-static _Complex T_C_TYPE gComplexValue2 = 3 + 4 * I;
-
-static int cls_variadic(const char *format, ...)
-{
- va_list ap;
- _Complex T_C_TYPE p1, p2;
-
- va_start (ap, format);
- p1 = va_arg (ap, _Complex T_C_TYPE);
- p2 = va_arg (ap, _Complex T_C_TYPE);
- va_end (ap);
-
- return printf(format, T_CONV creal (p1), T_CONV cimag (p1),
- T_CONV creal (p2), T_CONV cimag (p2));
-}
-
-static void
-cls_complex_va_fn(ffi_cif* cif __UNUSED__, void* resp,
- void** args, void* userdata __UNUSED__)
-{
- char* format = *(char**)args[0];
- gComplexValue1 = *(_Complex T_C_TYPE*)args[1];
- gComplexValue2 = *(_Complex T_C_TYPE*)args[2];
-
- *(ffi_arg*)resp =
- printf(format,
- T_CONV creal (gComplexValue1), T_CONV cimag (gComplexValue1),
- T_CONV creal (gComplexValue2), T_CONV cimag (gComplexValue2));
-}
-
-int main (void)
-{
- ffi_cif cif;
- void *code;
- ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
- void* args[4];
- ffi_type* arg_types[4];
- char *format = "%.1f,%.1fi %.1f,%.1fi\n";
-
- _Complex T_C_TYPE complexArg1 = 1.0 + 22.0 *I;
- _Complex T_C_TYPE complexArg2 = 333.0 + 4444.0 *I;
- ffi_arg res = 0;
-
- arg_types[0] = &ffi_type_pointer;
- arg_types[1] = &T_FFI_TYPE;
- arg_types[2] = &T_FFI_TYPE;
- arg_types[3] = NULL;
-
- /* This printf call is variadic */
- CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 3, &ffi_type_sint,
- arg_types) == FFI_OK);
-
- args[0] = &format;
- args[1] = &complexArg1;
- args[2] = &complexArg2;
- args[3] = NULL;
-
- ffi_call(&cif, FFI_FN(cls_variadic), &res, args);
- printf("res: %d\n", (int) res);
- CHECK (res == 24);
-
- CHECK(ffi_prep_closure_loc(pcl, &cif, cls_complex_va_fn, NULL, code)
- == FFI_OK);
-
- res = ((int(*)(char *, ...))(code))(format, complexArg1, complexArg2);
- CHECK (gComplexValue1 == complexArg1);
- CHECK (gComplexValue2 == complexArg2);
- printf("res: %d\n", (int) res);
- CHECK (res == 24);
-
- exit(0);
-}
+/* -*-c-*- */
+#include "ffitest.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <complex.h>
+
+static _Complex T_C_TYPE gComplexValue1 = 1 + 2 * I;
+static _Complex T_C_TYPE gComplexValue2 = 3 + 4 * I;
+
+static int cls_variadic(const char *format, ...)
+{
+ va_list ap;
+ _Complex T_C_TYPE p1, p2;
+
+ va_start (ap, format);
+ p1 = va_arg (ap, _Complex T_C_TYPE);
+ p2 = va_arg (ap, _Complex T_C_TYPE);
+ va_end (ap);
+
+ return printf(format, T_CONV creal (p1), T_CONV cimag (p1),
+ T_CONV creal (p2), T_CONV cimag (p2));
+}
+
+static void
+cls_complex_va_fn(ffi_cif* cif __UNUSED__, void* resp,
+ void** args, void* userdata __UNUSED__)
+{
+ char* format = *(char**)args[0];
+ gComplexValue1 = *(_Complex T_C_TYPE*)args[1];
+ gComplexValue2 = *(_Complex T_C_TYPE*)args[2];
+
+ *(ffi_arg*)resp =
+ printf(format,
+ T_CONV creal (gComplexValue1), T_CONV cimag (gComplexValue1),
+ T_CONV creal (gComplexValue2), T_CONV cimag (gComplexValue2));
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ void *code;
+ ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
+ void* args[4];
+ ffi_type* arg_types[4];
+ char *format = "%.1f,%.1fi %.1f,%.1fi\n";
+
+ _Complex T_C_TYPE complexArg1 = 1.0 + 22.0 *I;
+ _Complex T_C_TYPE complexArg2 = 333.0 + 4444.0 *I;
+ ffi_arg res = 0;
+
+ arg_types[0] = &ffi_type_pointer;
+ arg_types[1] = &T_FFI_TYPE;
+ arg_types[2] = &T_FFI_TYPE;
+ arg_types[3] = NULL;
+
+ /* This printf call is variadic */
+ CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 3, &ffi_type_sint,
+ arg_types) == FFI_OK);
+
+ args[0] = &format;
+ args[1] = &complexArg1;
+ args[2] = &complexArg2;
+ args[3] = NULL;
+
+ ffi_call(&cif, FFI_FN(cls_variadic), &res, args);
+ printf("res: %d\n", (int) res);
+ CHECK (res == 24);
+
+ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_complex_va_fn, NULL, code)
+ == FFI_OK);
+
+ res = ((int(*)(char *, ...))(code))(format, complexArg1, complexArg2);
+ CHECK (gComplexValue1 == complexArg1);
+ CHECK (gComplexValue2 == complexArg2);
+ printf("res: %d\n", (int) res);
+ CHECK (res == 24);
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_double.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_double.c
index b37e7ef503..879ccf3b81 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_double.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call, closure_call
- Purpose: Test complex' passed in variable argument lists.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_double.inc"
-#include "cls_complex_va.inc"
+/* Area: ffi_call, closure_call
+ Purpose: Test complex' passed in variable argument lists.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_double.inc"
+#include "cls_complex_va.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_double/ya.make
index a3f2950e05..8f437dc41e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_complex_va_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_complex_va_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_float.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_float.c
index 013edb8f06..2b17826045 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_float.c
@@ -1,16 +1,16 @@
-/* Area: ffi_call, closure_call
- Purpose: Test complex' passed in variable argument lists.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-/* Alpha splits _Complex into two arguments. It's illegal to pass
- float through varargs, so _Complex float goes badly. In sort of
- gets passed as _Complex double, but the compiler doesn't agree
- with itself on this issue. */
-/* { dg-do run { xfail alpha*-*-* } } */
-
-#include "complex_defs_float.inc"
-#include "cls_complex_va.inc"
+/* Area: ffi_call, closure_call
+ Purpose: Test complex' passed in variable argument lists.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+/* Alpha splits _Complex into two arguments. It's illegal to pass
+ float through varargs, so _Complex float goes badly. In sort of
+ gets passed as _Complex double, but the compiler doesn't agree
+ with itself on this issue. */
+/* { dg-do run { xfail alpha*-*-* } } */
+
+#include "complex_defs_float.inc"
+#include "cls_complex_va.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_float/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_float/ya.make
index aa33956c76..b936ee74d3 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_complex_va_float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_complex_va_float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_longdouble.c b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_longdouble.c
index 5895b340c1..6eca9656ea 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_longdouble.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_longdouble.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call, closure_call
- Purpose: Test complex' passed in variable argument lists.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_longdouble.inc"
-#include "cls_complex_va.inc"
+/* Area: ffi_call, closure_call
+ Purpose: Test complex' passed in variable argument lists.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_longdouble.inc"
+#include "cls_complex_va.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_longdouble/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_longdouble/ya.make
index 7992138484..4225df798e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_longdouble/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/cls_complex_va_longdouble/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- cls_complex_va_longdouble.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ cls_complex_va_longdouble.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex.inc b/contrib/restricted/libffi/testsuite/libffi.complex/complex.inc
index 61c0994a19..515ae3e60d 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex.inc
@@ -1,51 +1,51 @@
-/* -*-c-*-*/
-#include "ffitest.h"
-#include <complex.h>
-
-static _Complex T_C_TYPE f_complex(_Complex T_C_TYPE c, int x, int *py)
-{
- c = -(2 * creal (c)) + (cimag (c) + 1)* I;
- *py += x;
-
- return c;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
-
- _Complex T_C_TYPE tc_arg;
- _Complex T_C_TYPE tc_result;
- int tc_int_arg_x;
- int tc_y;
- int *tc_ptr_arg_y = &tc_y;
-
- args[0] = &T_FFI_TYPE;
- args[1] = &ffi_type_sint;
- args[2] = &ffi_type_pointer;
- values[0] = &tc_arg;
- values[1] = &tc_int_arg_x;
- values[2] = &tc_ptr_arg_y;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
- &T_FFI_TYPE, args) == FFI_OK);
-
- tc_arg = 1 + 7 * I;
- tc_int_arg_x = 1234;
- tc_y = 9876;
- ffi_call(&cif, FFI_FN(f_complex), &tc_result, values);
-
- printf ("%f,%fi %f,%fi, x %d 1234, y %d 11110\n",
- T_CONV creal (tc_result), T_CONV cimag (tc_result),
- T_CONV creal (2.0), T_CONV creal (8.0), tc_int_arg_x, tc_y);
-
- CHECK (creal (tc_result) == -2);
- CHECK (cimag (tc_result) == 8);
- CHECK (tc_int_arg_x == 1234);
- CHECK (*tc_ptr_arg_y == 11110);
-
- exit(0);
-}
+/* -*-c-*-*/
+#include "ffitest.h"
+#include <complex.h>
+
+static _Complex T_C_TYPE f_complex(_Complex T_C_TYPE c, int x, int *py)
+{
+ c = -(2 * creal (c)) + (cimag (c) + 1)* I;
+ *py += x;
+
+ return c;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+
+ _Complex T_C_TYPE tc_arg;
+ _Complex T_C_TYPE tc_result;
+ int tc_int_arg_x;
+ int tc_y;
+ int *tc_ptr_arg_y = &tc_y;
+
+ args[0] = &T_FFI_TYPE;
+ args[1] = &ffi_type_sint;
+ args[2] = &ffi_type_pointer;
+ values[0] = &tc_arg;
+ values[1] = &tc_int_arg_x;
+ values[2] = &tc_ptr_arg_y;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
+ &T_FFI_TYPE, args) == FFI_OK);
+
+ tc_arg = 1 + 7 * I;
+ tc_int_arg_x = 1234;
+ tc_y = 9876;
+ ffi_call(&cif, FFI_FN(f_complex), &tc_result, values);
+
+ printf ("%f,%fi %f,%fi, x %d 1234, y %d 11110\n",
+ T_CONV creal (tc_result), T_CONV cimag (tc_result),
+ T_CONV creal (2.0), T_CONV creal (8.0), tc_int_arg_x, tc_y);
+
+ CHECK (creal (tc_result) == -2);
+ CHECK (cimag (tc_result) == 8);
+ CHECK (tc_int_arg_x == 1234);
+ CHECK (*tc_ptr_arg_y == 11110);
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_double.inc b/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_double.inc
index 7a35c8e1a8..3583e166d6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_double.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_double.inc
@@ -1,7 +1,7 @@
-/* -*-c-*- */
-/* Complex base type. */
-#define T_FFI_TYPE ffi_type_complex_double
-/* C type corresponding to the base type. */
-#define T_C_TYPE double
-/* C cast for a value of type T_C_TYPE that is passed to printf. */
-#define T_CONV
+/* -*-c-*- */
+/* Complex base type. */
+#define T_FFI_TYPE ffi_type_complex_double
+/* C type corresponding to the base type. */
+#define T_C_TYPE double
+/* C cast for a value of type T_C_TYPE that is passed to printf. */
+#define T_CONV
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_float.inc b/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_float.inc
index 78811e884b..bbd9375cbf 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_float.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_float.inc
@@ -1,7 +1,7 @@
-/* -*-c-*- */
-/* Complex base type. */
-#define T_FFI_TYPE ffi_type_complex_float
-/* C type corresponding to the base type. */
-#define T_C_TYPE float
-/* C cast for a value of type T_C_TYPE that is passed to printf. */
-#define T_CONV (double)
+/* -*-c-*- */
+/* Complex base type. */
+#define T_FFI_TYPE ffi_type_complex_float
+/* C type corresponding to the base type. */
+#define T_C_TYPE float
+/* C cast for a value of type T_C_TYPE that is passed to printf. */
+#define T_CONV (double)
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_longdouble.inc b/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_longdouble.inc
index 3eb9ae3974..14b9f243f4 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_longdouble.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex_defs_longdouble.inc
@@ -1,7 +1,7 @@
-/* -*-c-*- */
-/* Complex base type. */
-#define T_FFI_TYPE ffi_type_complex_longdouble
-/* C type corresponding to the base type. */
-#define T_C_TYPE long double
-/* C cast for a value of type T_C_TYPE that is passed to printf. */
-#define T_CONV
+/* -*-c-*- */
+/* Complex base type. */
+#define T_FFI_TYPE ffi_type_complex_longdouble
+/* C type corresponding to the base type. */
+#define T_C_TYPE long double
+/* C cast for a value of type T_C_TYPE that is passed to printf. */
+#define T_CONV
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex_double.c b/contrib/restricted/libffi/testsuite/libffi.complex/complex_double.c
index dffaa9acf2..8a3297b2a2 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex_double.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check complex types.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_double.inc"
-#include "complex.inc"
+/* Area: ffi_call
+ Purpose: Check complex types.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_double.inc"
+#include "complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/complex_double/ya.make
index c73f64f997..11976473c0 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- complex_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ complex_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex_float.c b/contrib/restricted/libffi/testsuite/libffi.complex/complex_float.c
index 9de6f54fb5..5044ebbcaa 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex_float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex_float.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check complex types.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_float.inc"
-#include "complex.inc"
+/* Area: ffi_call
+ Purpose: Check complex types.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_float.inc"
+#include "complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex_float/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/complex_float/ya.make
index 33ca4b961a..02103a290e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex_float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex_float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- complex_float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ complex_float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex_int.c b/contrib/restricted/libffi/testsuite/libffi.complex/complex_int.c
index c863e613aa..bac319081e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex_int.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex_int.c
@@ -1,86 +1,86 @@
-/* Area: ffi_call
- Purpose: Check non-standard complex types.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-#include "ffi.h"
-#include <complex.h>
-
-_Complex int f_complex(_Complex int c, int x, int *py)
-{
- __real__ c = -2 * __real__ c;
- __imag__ c = __imag__ c + 1;
- *py += x;
- return c;
-}
-
-/*
- * This macro can be used to define new complex type descriptors
- * in a platform independent way.
- *
- * name: Name of the new descriptor is ffi_type_complex_<name>.
- * type: The C base type of the complex type.
- */
-#define FFI_COMPLEX_TYPEDEF(name, type, ffitype) \
- static ffi_type *ffi_elements_complex_##name [2] = { \
- (ffi_type *)(&ffitype), NULL \
- }; \
- struct struct_align_complex_##name { \
- char c; \
- _Complex type x; \
- }; \
- ffi_type ffi_type_complex_##name = { \
- sizeof(_Complex type), \
- offsetof(struct struct_align_complex_##name, x), \
- FFI_TYPE_COMPLEX, \
- (ffi_type **)ffi_elements_complex_##name \
- }
-
-/* Define new complex type descriptors using the macro: */
-/* ffi_type_complex_sint */
-FFI_COMPLEX_TYPEDEF(sint, int, ffi_type_sint);
-/* ffi_type_complex_uchar */
-FFI_COMPLEX_TYPEDEF(uchar, unsigned char, ffi_type_uint8);
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
-
- _Complex int tc_arg;
- _Complex int tc_result;
- int tc_int_arg_x;
- int tc_y;
- int *tc_ptr_arg_y = &tc_y;
-
- args[0] = &ffi_type_complex_sint;
- args[1] = &ffi_type_sint;
- args[2] = &ffi_type_pointer;
- values[0] = &tc_arg;
- values[1] = &tc_int_arg_x;
- values[2] = &tc_ptr_arg_y;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &ffi_type_complex_sint, args)
- == FFI_OK);
-
- tc_arg = 1 + 7 * I;
- tc_int_arg_x = 1234;
- tc_y = 9876;
- ffi_call(&cif, FFI_FN(f_complex), &tc_result, values);
-
- printf ("%d,%di %d,%di, x %d 1234, y %d 11110\n",
- (int)tc_result, (int)(tc_result * -I), 2, 8, tc_int_arg_x, tc_y);
- /* dg-output "-2,8i 2,8i, x 1234 1234, y 11110 11110" */
- CHECK (creal (tc_result) == -2);
- CHECK (cimag (tc_result) == 8);
- CHECK (tc_int_arg_x == 1234);
- CHECK (*tc_ptr_arg_y == 11110);
-
- exit(0);
-}
+/* Area: ffi_call
+ Purpose: Check non-standard complex types.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+#include "ffi.h"
+#include <complex.h>
+
+_Complex int f_complex(_Complex int c, int x, int *py)
+{
+ __real__ c = -2 * __real__ c;
+ __imag__ c = __imag__ c + 1;
+ *py += x;
+ return c;
+}
+
+/*
+ * This macro can be used to define new complex type descriptors
+ * in a platform independent way.
+ *
+ * name: Name of the new descriptor is ffi_type_complex_<name>.
+ * type: The C base type of the complex type.
+ */
+#define FFI_COMPLEX_TYPEDEF(name, type, ffitype) \
+ static ffi_type *ffi_elements_complex_##name [2] = { \
+ (ffi_type *)(&ffitype), NULL \
+ }; \
+ struct struct_align_complex_##name { \
+ char c; \
+ _Complex type x; \
+ }; \
+ ffi_type ffi_type_complex_##name = { \
+ sizeof(_Complex type), \
+ offsetof(struct struct_align_complex_##name, x), \
+ FFI_TYPE_COMPLEX, \
+ (ffi_type **)ffi_elements_complex_##name \
+ }
+
+/* Define new complex type descriptors using the macro: */
+/* ffi_type_complex_sint */
+FFI_COMPLEX_TYPEDEF(sint, int, ffi_type_sint);
+/* ffi_type_complex_uchar */
+FFI_COMPLEX_TYPEDEF(uchar, unsigned char, ffi_type_uint8);
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+
+ _Complex int tc_arg;
+ _Complex int tc_result;
+ int tc_int_arg_x;
+ int tc_y;
+ int *tc_ptr_arg_y = &tc_y;
+
+ args[0] = &ffi_type_complex_sint;
+ args[1] = &ffi_type_sint;
+ args[2] = &ffi_type_pointer;
+ values[0] = &tc_arg;
+ values[1] = &tc_int_arg_x;
+ values[2] = &tc_ptr_arg_y;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &ffi_type_complex_sint, args)
+ == FFI_OK);
+
+ tc_arg = 1 + 7 * I;
+ tc_int_arg_x = 1234;
+ tc_y = 9876;
+ ffi_call(&cif, FFI_FN(f_complex), &tc_result, values);
+
+ printf ("%d,%di %d,%di, x %d 1234, y %d 11110\n",
+ (int)tc_result, (int)(tc_result * -I), 2, 8, tc_int_arg_x, tc_y);
+ /* dg-output "-2,8i 2,8i, x 1234 1234, y 11110 11110" */
+ CHECK (creal (tc_result) == -2);
+ CHECK (cimag (tc_result) == 8);
+ CHECK (tc_int_arg_x == 1234);
+ CHECK (*tc_ptr_arg_y == 11110);
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex_int/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/complex_int/ya.make
index 671dff8943..94f7e6ae6a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex_int/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex_int/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- complex_int.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ complex_int.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex_longdouble.c b/contrib/restricted/libffi/testsuite/libffi.complex/complex_longdouble.c
index 098b494f42..7e78366093 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex_longdouble.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex_longdouble.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check complex types.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_longdouble.inc"
-#include "complex.inc"
+/* Area: ffi_call
+ Purpose: Check complex types.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_longdouble.inc"
+#include "complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/complex_longdouble/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/complex_longdouble/ya.make
index ec73c64faa..c68e2c5613 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/complex_longdouble/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/complex_longdouble/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- complex_longdouble.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ complex_longdouble.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/ffitest.h b/contrib/restricted/libffi/testsuite/libffi.complex/ffitest.h
index 1e9446fbbc..d27d362d6a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/ffitest.h
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/ffitest.h
@@ -1 +1 @@
-#include "../libffi.call/ffitest.h"
+#include "../libffi.call/ffitest.h"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex.inc b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex.inc
index b68458e862..e37a774397 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex.inc
@@ -1,78 +1,78 @@
-/* -*-c-*- */
-#include "ffitest.h"
-
-#include <stdlib.h>
-#include <complex.h>
-
-static _Complex T_C_TYPE many(_Complex T_C_TYPE c1,
- _Complex T_C_TYPE c2,
- _Complex T_C_TYPE c3,
- _Complex T_C_TYPE c4,
- _Complex T_C_TYPE c5,
- _Complex T_C_TYPE c6,
- _Complex T_C_TYPE c7,
- _Complex T_C_TYPE c8,
- _Complex T_C_TYPE c9,
- _Complex T_C_TYPE c10,
- _Complex T_C_TYPE c11,
- _Complex T_C_TYPE c12,
- _Complex T_C_TYPE c13)
-{
- printf("0 :%f,%fi\n"
- "1 :%f,%fi\n"
- "2 :%f,%fi\n"
- "3 :%f,%fi\n"
- "4 :%f,%fi\n"
- "5 :%f,%fi\n"
- "6 :%f,%fi\n"
- "7 :%f,%fi\n"
- "8 :%f,%fi\n"
- "9 :%f,%fi\n"
- "10:%f,%fi\n"
- "11:%f,%fi\n"
- "12:%f,%fi\n",
- T_CONV creal (c1), T_CONV cimag (c1),
- T_CONV creal (c2), T_CONV cimag (c2),
- T_CONV creal (c3), T_CONV cimag (c3),
- T_CONV creal (c4), T_CONV cimag (c4),
- T_CONV creal (c5), T_CONV cimag (c5),
- T_CONV creal (c6), T_CONV cimag (c6),
- T_CONV creal (c7), T_CONV cimag (c7),
- T_CONV creal (c8), T_CONV cimag (c8),
- T_CONV creal (c9), T_CONV cimag (c9),
- T_CONV creal (c10), T_CONV cimag (c10),
- T_CONV creal (c11), T_CONV cimag (c11),
- T_CONV creal (c12), T_CONV cimag (c12),
- T_CONV creal (c13), T_CONV cimag (c13));
-
- return (c1+c2-c3-c4+c5+c6+c7-c8-c9-c10-c11+c12+c13);
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[13];
- void *values[13];
- _Complex T_C_TYPE ca[13];
- _Complex T_C_TYPE c, cc;
- int i;
-
- for (i = 0; i < 13; i++)
- {
- args[i] = &T_FFI_TYPE;
- values[i] = &ca[i];
- ca[i] = i + (-20 - i) * I;
- }
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 13, &T_FFI_TYPE, args) == FFI_OK);
-
- ffi_call(&cif, FFI_FN(many), &c, values);
-
- cc = many(ca[0], ca[1], ca[2], ca[3], ca[4], ca[5], ca[6], ca[7], ca[8],
- ca[9], ca[10], ca[11], ca[12]);
- CHECK(creal (cc) == creal (c));
- CHECK(cimag (cc) == cimag (c));
-
- exit(0);
-}
+/* -*-c-*- */
+#include "ffitest.h"
+
+#include <stdlib.h>
+#include <complex.h>
+
+static _Complex T_C_TYPE many(_Complex T_C_TYPE c1,
+ _Complex T_C_TYPE c2,
+ _Complex T_C_TYPE c3,
+ _Complex T_C_TYPE c4,
+ _Complex T_C_TYPE c5,
+ _Complex T_C_TYPE c6,
+ _Complex T_C_TYPE c7,
+ _Complex T_C_TYPE c8,
+ _Complex T_C_TYPE c9,
+ _Complex T_C_TYPE c10,
+ _Complex T_C_TYPE c11,
+ _Complex T_C_TYPE c12,
+ _Complex T_C_TYPE c13)
+{
+ printf("0 :%f,%fi\n"
+ "1 :%f,%fi\n"
+ "2 :%f,%fi\n"
+ "3 :%f,%fi\n"
+ "4 :%f,%fi\n"
+ "5 :%f,%fi\n"
+ "6 :%f,%fi\n"
+ "7 :%f,%fi\n"
+ "8 :%f,%fi\n"
+ "9 :%f,%fi\n"
+ "10:%f,%fi\n"
+ "11:%f,%fi\n"
+ "12:%f,%fi\n",
+ T_CONV creal (c1), T_CONV cimag (c1),
+ T_CONV creal (c2), T_CONV cimag (c2),
+ T_CONV creal (c3), T_CONV cimag (c3),
+ T_CONV creal (c4), T_CONV cimag (c4),
+ T_CONV creal (c5), T_CONV cimag (c5),
+ T_CONV creal (c6), T_CONV cimag (c6),
+ T_CONV creal (c7), T_CONV cimag (c7),
+ T_CONV creal (c8), T_CONV cimag (c8),
+ T_CONV creal (c9), T_CONV cimag (c9),
+ T_CONV creal (c10), T_CONV cimag (c10),
+ T_CONV creal (c11), T_CONV cimag (c11),
+ T_CONV creal (c12), T_CONV cimag (c12),
+ T_CONV creal (c13), T_CONV cimag (c13));
+
+ return (c1+c2-c3-c4+c5+c6+c7-c8-c9-c10-c11+c12+c13);
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[13];
+ void *values[13];
+ _Complex T_C_TYPE ca[13];
+ _Complex T_C_TYPE c, cc;
+ int i;
+
+ for (i = 0; i < 13; i++)
+ {
+ args[i] = &T_FFI_TYPE;
+ values[i] = &ca[i];
+ ca[i] = i + (-20 - i) * I;
+ }
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 13, &T_FFI_TYPE, args) == FFI_OK);
+
+ ffi_call(&cif, FFI_FN(many), &c, values);
+
+ cc = many(ca[0], ca[1], ca[2], ca[3], ca[4], ca[5], ca[6], ca[7], ca[8],
+ ca[9], ca[10], ca[11], ca[12]);
+ CHECK(creal (cc) == creal (c));
+ CHECK(cimag (cc) == cimag (c));
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_double.c b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_double.c
index 378d4a156a..3fd53c3354 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_double.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex, with many arguments
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_double.inc"
-#include "many_complex.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex, with many arguments
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_double.inc"
+#include "many_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_double/ya.make
index 5b85306b66..2bcdfea7f1 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- many_complex_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ many_complex_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_float.c b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_float.c
index 24ea13ec3f..c43d21cd9e 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_float.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex, with many arguments
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_float.inc"
-#include "many_complex.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex, with many arguments
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_float.inc"
+#include "many_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_float/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_float/ya.make
index b525fbfa52..82f2a93933 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- many_complex_float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ many_complex_float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_longdouble.c b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_longdouble.c
index 6d32b8b8d0..dbab723969 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_longdouble.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_longdouble.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex, with many arguments
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_longdouble.inc"
-#include "many_complex.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex, with many arguments
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_longdouble.inc"
+#include "many_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_longdouble/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_longdouble/ya.make
index 64b7080575..68bf0b2407 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_longdouble/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/many_complex_longdouble/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- many_complex_longdouble.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ many_complex_longdouble.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex.inc b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex.inc
index 590317e99b..8bf0c1fbab 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex.inc
@@ -1,37 +1,37 @@
-/* -*-c-*- */
-#include "ffitest.h"
-#include <complex.h>
-
-static _Complex T_C_TYPE return_c(_Complex T_C_TYPE c)
-{
- printf ("%f,%fi\n", T_CONV creal (c), T_CONV cimag (c));
- return 2 * c;
-}
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- _Complex T_C_TYPE c, rc, rc2;
- T_C_TYPE cr, ci;
-
- args[0] = &T_FFI_TYPE;
- values[0] = &c;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
- &T_FFI_TYPE, args) == FFI_OK);
-
- for (cr = -127.0; cr < 127; cr++)
- {
- ci = 1000.0 - cr;
- c = cr + ci * I;
- ffi_call(&cif, FFI_FN(return_c), &rc, values);
- rc2 = return_c(c);
- printf ("%f,%fi vs %f,%fi\n",
- T_CONV creal (rc), T_CONV cimag (rc),
- T_CONV creal (rc2), T_CONV cimag (rc2));
- CHECK(rc == 2 * c);
- }
- exit(0);
-}
+/* -*-c-*- */
+#include "ffitest.h"
+#include <complex.h>
+
+static _Complex T_C_TYPE return_c(_Complex T_C_TYPE c)
+{
+ printf ("%f,%fi\n", T_CONV creal (c), T_CONV cimag (c));
+ return 2 * c;
+}
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ _Complex T_C_TYPE c, rc, rc2;
+ T_C_TYPE cr, ci;
+
+ args[0] = &T_FFI_TYPE;
+ values[0] = &c;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
+ &T_FFI_TYPE, args) == FFI_OK);
+
+ for (cr = -127.0; cr < 127; cr++)
+ {
+ ci = 1000.0 - cr;
+ c = cr + ci * I;
+ ffi_call(&cif, FFI_FN(return_c), &rc, values);
+ rc2 = return_c(c);
+ printf ("%f,%fi vs %f,%fi\n",
+ T_CONV creal (rc), T_CONV cimag (rc),
+ T_CONV creal (rc2), T_CONV cimag (rc2));
+ CHECK(rc == 2 * c);
+ }
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1.inc b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1.inc
index fb29e31623..7cecc0fefa 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1.inc
@@ -1,41 +1,41 @@
-/* -*-c-*- */
-#include "ffitest.h"
-#include <complex.h>
-
-static _Complex T_C_TYPE return_c(_Complex T_C_TYPE c1, float fl2, unsigned int in3, _Complex T_C_TYPE c4)
-{
- return c1 + fl2 + in3 + c4;
-}
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- _Complex T_C_TYPE c1, c4, rc, rc2;
- float fl2;
- unsigned int in3;
- args[0] = &T_FFI_TYPE;
- args[1] = &ffi_type_float;
- args[2] = &ffi_type_uint;
- args[3] = &T_FFI_TYPE;
- values[0] = &c1;
- values[1] = &fl2;
- values[2] = &in3;
- values[3] = &c4;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
- &T_FFI_TYPE, args) == FFI_OK);
- c1 = 127.0 + 255.0 * I;
- fl2 = 128.0;
- in3 = 255;
- c4 = 512.7 + 1024.1 * I;
-
- ffi_call(&cif, FFI_FN(return_c), &rc, values);
- rc2 = return_c(c1, fl2, in3, c4);
- printf ("%f,%fi vs %f,%fi\n",
- T_CONV creal (rc), T_CONV cimag (rc),
- T_CONV creal (rc2), T_CONV cimag (rc2));
- CHECK(rc == rc2);
- exit(0);
-}
+/* -*-c-*- */
+#include "ffitest.h"
+#include <complex.h>
+
+static _Complex T_C_TYPE return_c(_Complex T_C_TYPE c1, float fl2, unsigned int in3, _Complex T_C_TYPE c4)
+{
+ return c1 + fl2 + in3 + c4;
+}
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ _Complex T_C_TYPE c1, c4, rc, rc2;
+ float fl2;
+ unsigned int in3;
+ args[0] = &T_FFI_TYPE;
+ args[1] = &ffi_type_float;
+ args[2] = &ffi_type_uint;
+ args[3] = &T_FFI_TYPE;
+ values[0] = &c1;
+ values[1] = &fl2;
+ values[2] = &in3;
+ values[3] = &c4;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
+ &T_FFI_TYPE, args) == FFI_OK);
+ c1 = 127.0 + 255.0 * I;
+ fl2 = 128.0;
+ in3 = 255;
+ c4 = 512.7 + 1024.1 * I;
+
+ ffi_call(&cif, FFI_FN(return_c), &rc, values);
+ rc2 = return_c(c1, fl2, in3, c4);
+ printf ("%f,%fi vs %f,%fi\n",
+ T_CONV creal (rc), T_CONV cimag (rc),
+ T_CONV creal (rc2), T_CONV cimag (rc2));
+ CHECK(rc == rc2);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_double.c b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_double.c
index 9ddd9beb13..727410d563 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_double.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_double.inc"
-#include "return_complex1.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_double.inc"
+#include "return_complex1.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_double/ya.make
index 6a8a1cce58..f3666626a6 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- return_complex1_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ return_complex1_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_float.c b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_float.c
index 518502d0d8..a2aeada847 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_float.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_float.inc"
-#include "return_complex1.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_float.inc"
+#include "return_complex1.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_float/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_float/ya.make
index ad37e11a10..2f9ebac337 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- return_complex1_float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ return_complex1_float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_longdouble.c b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_longdouble.c
index b6e7793094..103504bf64 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_longdouble.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_longdouble.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_longdouble.inc"
-#include "return_complex1.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_longdouble.inc"
+#include "return_complex1.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_longdouble/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_longdouble/ya.make
index 6254737104..e8ea56065b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_longdouble/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex1_longdouble/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- return_complex1_longdouble.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ return_complex1_longdouble.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2.inc b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2.inc
index 1ab6d5bb15..265170bf71 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2.inc
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2.inc
@@ -1,44 +1,44 @@
-/* -*-c-*- */
-#include "ffitest.h"
-#include <complex.h>
-
-_Complex T_C_TYPE
-return_c(_Complex T_C_TYPE c1, _Complex T_C_TYPE c2,
- unsigned int in3, _Complex T_C_TYPE c4)
-{
- volatile _Complex T_C_TYPE r = c1 + c2 + in3 + c4;
- return r;
-}
-
-int main (void)
-{
- ffi_cif cif;
- ffi_type *args[MAX_ARGS];
- void *values[MAX_ARGS];
- _Complex T_C_TYPE c1, c2, c4, rc, rc2;
- unsigned int in3;
- args[0] = &T_FFI_TYPE;
- args[1] = &T_FFI_TYPE;
- args[2] = &ffi_type_uint;
- args[3] = &T_FFI_TYPE;
- values[0] = &c1;
- values[1] = &c2;
- values[2] = &in3;
- values[3] = &c4;
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
- &T_FFI_TYPE, args) == FFI_OK);
- c1 = 127.0 + 255.0 * I;
- c2 = 128.0 + 256.0;
- in3 = 255;
- c4 = 512.7 + 1024.1 * I;
-
- ffi_call(&cif, FFI_FN(return_c), &rc, values);
- rc2 = return_c(c1, c2, in3, c4);
- printf ("%f,%fi vs %f,%fi\n",
- T_CONV creal (rc), T_CONV cimag (rc),
- T_CONV creal (rc2), T_CONV cimag (rc2));
- CHECK(rc == rc2);
- exit(0);
-}
+/* -*-c-*- */
+#include "ffitest.h"
+#include <complex.h>
+
+_Complex T_C_TYPE
+return_c(_Complex T_C_TYPE c1, _Complex T_C_TYPE c2,
+ unsigned int in3, _Complex T_C_TYPE c4)
+{
+ volatile _Complex T_C_TYPE r = c1 + c2 + in3 + c4;
+ return r;
+}
+
+int main (void)
+{
+ ffi_cif cif;
+ ffi_type *args[MAX_ARGS];
+ void *values[MAX_ARGS];
+ _Complex T_C_TYPE c1, c2, c4, rc, rc2;
+ unsigned int in3;
+ args[0] = &T_FFI_TYPE;
+ args[1] = &T_FFI_TYPE;
+ args[2] = &ffi_type_uint;
+ args[3] = &T_FFI_TYPE;
+ values[0] = &c1;
+ values[1] = &c2;
+ values[2] = &in3;
+ values[3] = &c4;
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4,
+ &T_FFI_TYPE, args) == FFI_OK);
+ c1 = 127.0 + 255.0 * I;
+ c2 = 128.0 + 256.0;
+ in3 = 255;
+ c4 = 512.7 + 1024.1 * I;
+
+ ffi_call(&cif, FFI_FN(return_c), &rc, values);
+ rc2 = return_c(c1, c2, in3, c4);
+ printf ("%f,%fi vs %f,%fi\n",
+ T_CONV creal (rc), T_CONV cimag (rc),
+ T_CONV creal (rc2), T_CONV cimag (rc2));
+ CHECK(rc == rc2);
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_double.c b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_double.c
index 48f266ae73..ab9efacb4a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_double.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_double.inc"
-#include "return_complex2.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_double.inc"
+#include "return_complex2.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_double/ya.make
index 802fb44076..08804ca850 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- return_complex2_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ return_complex2_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_float.c b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_float.c
index 988e5ab395..d7f22c2a0c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_float.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_float.inc"
-#include "return_complex2.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_float.inc"
+#include "return_complex2.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_float/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_float/ya.make
index 25b3668c11..3fa5a7ebb1 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- return_complex2_float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ return_complex2_float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_longdouble.c b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_longdouble.c
index 5ba8e277f6..3edea629df 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_longdouble.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_longdouble.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_longdouble.inc"
-#include "return_complex2.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_longdouble.inc"
+#include "return_complex2.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_longdouble/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_longdouble/ya.make
index 5a9d9b29a3..7104e84373 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_longdouble/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex2_longdouble/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- return_complex2_longdouble.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ return_complex2_longdouble.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_double.c b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_double.c
index b9a0f56820..e2497cc84a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_double.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_double.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_double.inc"
-#include "return_complex.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_double.inc"
+#include "return_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_double/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_double/ya.make
index 6982692c50..19ccb8899b 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_double/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_double/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- return_complex_double.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ return_complex_double.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_float.c b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_float.c
index 762821e12d..a35528ff93 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_float.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_float.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_float.inc"
-#include "return_complex.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_float.inc"
+#include "return_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_float/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_float/ya.make
index 0871392666..cbe2235218 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_float/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_float/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- return_complex_float.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ return_complex_float.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_longdouble.c b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_longdouble.c
index b0539ff09d..142d7becba 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_longdouble.c
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_longdouble.c
@@ -1,10 +1,10 @@
-/* Area: ffi_call
- Purpose: Check return value complex.
- Limitations: none.
- PR: none.
- Originator: <vogt@linux.vnet.ibm.com>. */
-
-/* { dg-do run } */
-
-#include "complex_defs_longdouble.inc"
-#include "return_complex.inc"
+/* Area: ffi_call
+ Purpose: Check return value complex.
+ Limitations: none.
+ PR: none.
+ Originator: <vogt@linux.vnet.ibm.com>. */
+
+/* { dg-do run } */
+
+#include "complex_defs_longdouble.inc"
+#include "return_complex.inc"
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_longdouble/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_longdouble/ya.make
index ac3b3c71f8..a689752038 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_longdouble/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/return_complex_longdouble/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
-
-SRCS(
- return_complex_longdouble.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.complex)
+
+SRCS(
+ return_complex_longdouble.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.complex/ya.make b/contrib/restricted/libffi/testsuite/libffi.complex/ya.make
index 02036190d0..032d03839a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.complex/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.complex/ya.make
@@ -1,32 +1,32 @@
-# Generated by devtools/yamaker.
-
-RECURSE(
- cls_align_complex_double
- cls_align_complex_float
- cls_align_complex_longdouble
- cls_complex_double
- cls_complex_float
- cls_complex_longdouble
- cls_complex_struct_double
- cls_complex_struct_float
- cls_complex_struct_longdouble
- cls_complex_va_double
- cls_complex_va_float
- cls_complex_va_longdouble
- complex_double
- complex_float
- complex_int
- complex_longdouble
- many_complex_double
- many_complex_float
- many_complex_longdouble
- return_complex1_double
- return_complex1_float
- return_complex1_longdouble
- return_complex2_double
- return_complex2_float
- return_complex2_longdouble
- return_complex_double
- return_complex_float
- return_complex_longdouble
-)
+# Generated by devtools/yamaker.
+
+RECURSE(
+ cls_align_complex_double
+ cls_align_complex_float
+ cls_align_complex_longdouble
+ cls_complex_double
+ cls_complex_float
+ cls_complex_longdouble
+ cls_complex_struct_double
+ cls_complex_struct_float
+ cls_complex_struct_longdouble
+ cls_complex_va_double
+ cls_complex_va_float
+ cls_complex_va_longdouble
+ complex_double
+ complex_float
+ complex_int
+ complex_longdouble
+ many_complex_double
+ many_complex_float
+ many_complex_longdouble
+ return_complex1_double
+ return_complex1_float
+ return_complex1_longdouble
+ return_complex2_double
+ return_complex2_float
+ return_complex2_longdouble
+ return_complex_double
+ return_complex_float
+ return_complex_longdouble
+)
diff --git a/contrib/restricted/libffi/testsuite/libffi.go/aa-direct.c b/contrib/restricted/libffi/testsuite/libffi.go/aa-direct.c
index 4b2f5b5ed8..b00c404ab3 100644
--- a/contrib/restricted/libffi/testsuite/libffi.go/aa-direct.c
+++ b/contrib/restricted/libffi/testsuite/libffi.go/aa-direct.c
@@ -1,34 +1,34 @@
-/* { dg-do run } */
-
-#include "static-chain.h"
-
-#if defined(__GNUC__) && !defined(__clang__) && defined(STATIC_CHAIN_REG)
-
-#include "ffitest.h"
-
-/* Blatent assumption here that the prologue doesn't clobber the
- static chain for trivial functions. If this is not true, don't
- define STATIC_CHAIN_REG, and we'll test what we can via other tests. */
-void *doit(void)
-{
- register void *chain __asm__(STATIC_CHAIN_REG);
- return chain;
-}
-
-int main()
-{
- ffi_cif cif;
- void *result;
-
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 0, &ffi_type_pointer, NULL) == FFI_OK);
-
- ffi_call_go(&cif, FFI_FN(doit), &result, NULL, &result);
-
- CHECK(result == &result);
-
- return 0;
-}
-
-#else /* UNSUPPORTED */
-int main() { return 0; }
-#endif
+/* { dg-do run } */
+
+#include "static-chain.h"
+
+#if defined(__GNUC__) && !defined(__clang__) && defined(STATIC_CHAIN_REG)
+
+#include "ffitest.h"
+
+/* Blatent assumption here that the prologue doesn't clobber the
+ static chain for trivial functions. If this is not true, don't
+ define STATIC_CHAIN_REG, and we'll test what we can via other tests. */
+void *doit(void)
+{
+ register void *chain __asm__(STATIC_CHAIN_REG);
+ return chain;
+}
+
+int main()
+{
+ ffi_cif cif;
+ void *result;
+
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 0, &ffi_type_pointer, NULL) == FFI_OK);
+
+ ffi_call_go(&cif, FFI_FN(doit), &result, NULL, &result);
+
+ CHECK(result == &result);
+
+ return 0;
+}
+
+#else /* UNSUPPORTED */
+int main() { return 0; }
+#endif
diff --git a/contrib/restricted/libffi/testsuite/libffi.go/aa-direct/ya.make b/contrib/restricted/libffi/testsuite/libffi.go/aa-direct/ya.make
index 6127c121ea..a065cc77d9 100644
--- a/contrib/restricted/libffi/testsuite/libffi.go/aa-direct/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.go/aa-direct/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.go)
-
-SRCS(
- aa-direct.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.go)
+
+SRCS(
+ aa-direct.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.go/closure1.c b/contrib/restricted/libffi/testsuite/libffi.go/closure1.c
index 6666ad9236..7b34afc88c 100644
--- a/contrib/restricted/libffi/testsuite/libffi.go/closure1.c
+++ b/contrib/restricted/libffi/testsuite/libffi.go/closure1.c
@@ -1,28 +1,28 @@
-/* { dg-do run } */
-
-#include "ffitest.h"
-
-void doit(ffi_cif *cif, void *rvalue, void **avalue, void *closure)
-{
- (void)cif;
- (void)avalue;
- *(void **)rvalue = closure;
-}
-
-typedef void * (*FN)(void);
-
-int main()
-{
- ffi_cif cif;
- ffi_go_closure cl;
- void *result;
-
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 0, &ffi_type_pointer, NULL) == FFI_OK);
- CHECK(ffi_prep_go_closure(&cl, &cif, doit) == FFI_OK);
-
- ffi_call_go(&cif, FFI_FN(*(FN *)&cl), &result, NULL, &cl);
-
- CHECK(result == &cl);
-
- exit(0);
-}
+/* { dg-do run } */
+
+#include "ffitest.h"
+
+void doit(ffi_cif *cif, void *rvalue, void **avalue, void *closure)
+{
+ (void)cif;
+ (void)avalue;
+ *(void **)rvalue = closure;
+}
+
+typedef void * (*FN)(void);
+
+int main()
+{
+ ffi_cif cif;
+ ffi_go_closure cl;
+ void *result;
+
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 0, &ffi_type_pointer, NULL) == FFI_OK);
+ CHECK(ffi_prep_go_closure(&cl, &cif, doit) == FFI_OK);
+
+ ffi_call_go(&cif, FFI_FN(*(FN *)&cl), &result, NULL, &cl);
+
+ CHECK(result == &cl);
+
+ exit(0);
+}
diff --git a/contrib/restricted/libffi/testsuite/libffi.go/closure1/ya.make b/contrib/restricted/libffi/testsuite/libffi.go/closure1/ya.make
index 3a7d6db0c4..d758d0bd64 100644
--- a/contrib/restricted/libffi/testsuite/libffi.go/closure1/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.go/closure1/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
-
+
OWNER(
borman
g:cpp-contrib
@@ -11,18 +11,18 @@ OWNER(
LICENSE(GPL-2.0-only)
-PEERDIR(
- contrib/restricted/libffi
-)
-
-NO_COMPILER_WARNINGS()
-
-NO_RUNTIME()
-
-SRCDIR(contrib/restricted/libffi/testsuite/libffi.go)
-
-SRCS(
- closure1.c
-)
-
-END()
+PEERDIR(
+ contrib/restricted/libffi
+)
+
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+SRCDIR(contrib/restricted/libffi/testsuite/libffi.go)
+
+SRCS(
+ closure1.c
+)
+
+END()
diff --git a/contrib/restricted/libffi/testsuite/libffi.go/ffitest.h b/contrib/restricted/libffi/testsuite/libffi.go/ffitest.h
index 1e9446fbbc..d27d362d6a 100644
--- a/contrib/restricted/libffi/testsuite/libffi.go/ffitest.h
+++ b/contrib/restricted/libffi/testsuite/libffi.go/ffitest.h
@@ -1 +1 @@
-#include "../libffi.call/ffitest.h"
+#include "../libffi.call/ffitest.h"
diff --git a/contrib/restricted/libffi/testsuite/libffi.go/static-chain.h b/contrib/restricted/libffi/testsuite/libffi.go/static-chain.h
index 0bc98f1ac7..3675b40a54 100644
--- a/contrib/restricted/libffi/testsuite/libffi.go/static-chain.h
+++ b/contrib/restricted/libffi/testsuite/libffi.go/static-chain.h
@@ -1,19 +1,19 @@
-#ifdef __aarch64__
-# define STATIC_CHAIN_REG "x18"
-#elif defined(__alpha__)
-# define STATIC_CHAIN_REG "$1"
-#elif defined(__arm__)
-# define STATIC_CHAIN_REG "ip"
-#elif defined(__sparc__)
-# if defined(__arch64__) || defined(__sparcv9)
-# define STATIC_CHAIN_REG "g5"
-# else
-# define STATIC_CHAIN_REG "g2"
-# endif
-#elif defined(__x86_64__)
-# define STATIC_CHAIN_REG "r10"
-#elif defined(__i386__)
-# ifndef ABI_NUM
-# define STATIC_CHAIN_REG "ecx" /* FFI_DEFAULT_ABI only */
-# endif
-#endif
+#ifdef __aarch64__
+# define STATIC_CHAIN_REG "x18"
+#elif defined(__alpha__)
+# define STATIC_CHAIN_REG "$1"
+#elif defined(__arm__)
+# define STATIC_CHAIN_REG "ip"
+#elif defined(__sparc__)
+# if defined(__arch64__) || defined(__sparcv9)
+# define STATIC_CHAIN_REG "g5"
+# else
+# define STATIC_CHAIN_REG "g2"
+# endif
+#elif defined(__x86_64__)
+# define STATIC_CHAIN_REG "r10"
+#elif defined(__i386__)
+# ifndef ABI_NUM
+# define STATIC_CHAIN_REG "ecx" /* FFI_DEFAULT_ABI only */
+# endif
+#endif
diff --git a/contrib/restricted/libffi/testsuite/libffi.go/ya.make b/contrib/restricted/libffi/testsuite/libffi.go/ya.make
index 6a53163151..9e8d002d78 100644
--- a/contrib/restricted/libffi/testsuite/libffi.go/ya.make
+++ b/contrib/restricted/libffi/testsuite/libffi.go/ya.make
@@ -1,6 +1,6 @@
-# Generated by devtools/yamaker.
-
-RECURSE(
- aa-direct
- closure1
-)
+# Generated by devtools/yamaker.
+
+RECURSE(
+ aa-direct
+ closure1
+)
diff --git a/contrib/restricted/libffi/testsuite/ya.make b/contrib/restricted/libffi/testsuite/ya.make
index 53ea6520b7..7f589109a0 100644
--- a/contrib/restricted/libffi/testsuite/ya.make
+++ b/contrib/restricted/libffi/testsuite/ya.make
@@ -1,19 +1,19 @@
-# Generated by devtools/yamaker.
-
-RECURSE(
- libffi.bhaible
- libffi.call
- libffi.closures
-)
-
+# Generated by devtools/yamaker.
+
+RECURSE(
+ libffi.bhaible
+ libffi.call
+ libffi.closures
+)
+
IF (NOT OS_IOS)
- RECURSE(
- libffi.go
- )
-ENDIF()
-
-IF (NOT OS_WINDOWS AND NOT ARCH_PPC64LE)
- RECURSE(
- libffi.complex
- )
-ENDIF()
+ RECURSE(
+ libffi.go
+ )
+ENDIF()
+
+IF (NOT OS_WINDOWS AND NOT ARCH_PPC64LE)
+ RECURSE(
+ libffi.complex
+ )
+ENDIF()
diff --git a/contrib/restricted/libffi/ya.make b/contrib/restricted/libffi/ya.make
index a254773820..f39d7b6fe3 100644
--- a/contrib/restricted/libffi/ya.make
+++ b/contrib/restricted/libffi/ya.make
@@ -1,5 +1,5 @@
# Generated by devtools/yamaker from nixpkgs 5852a21819542e6809f68ba5a798600e69874e76.
-
+
LIBRARY()
OWNER(
@@ -7,8 +7,8 @@ OWNER(
g:cpp-contrib
)
-VERSION(3.3)
-
+VERSION(3.3)
+
ORIGINAL_SOURCE(https://sourceware.org/pub/libffi/libffi-3.3.tar.gz)
LICENSE(
@@ -19,37 +19,37 @@ LICENSE(
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
ADDINCL(
- contrib/restricted/libffi
- contrib/restricted/libffi/include
- contrib/restricted/libffi/src
- GLOBAL contrib/restricted/libffi/include
+ contrib/restricted/libffi
+ contrib/restricted/libffi/include
+ contrib/restricted/libffi/src
+ GLOBAL contrib/restricted/libffi/include
)
-NO_COMPILER_WARNINGS()
+NO_COMPILER_WARNINGS()
+
+NO_RUNTIME()
+
+CFLAGS(
+ -DHAVE_CONFIG_H
+ GLOBAL -DFFI_BUILDING
+)
-NO_RUNTIME()
-
-CFLAGS(
- -DHAVE_CONFIG_H
- GLOBAL -DFFI_BUILDING
-)
-
SRCS(
src/closures.c
- src/java_raw_api.c
+ src/java_raw_api.c
src/prep_cif.c
src/raw_api.c
src/types.c
)
-IF (ARCH_ARM64 AND OS_ANDROID)
- ADDINCL(
- contrib/restricted/libffi/configs/aarch64-unknown-linux-android21
- GLOBAL contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include
- )
+IF (ARCH_ARM64 AND OS_ANDROID)
+ ADDINCL(
+ contrib/restricted/libffi/configs/aarch64-unknown-linux-android21
+ GLOBAL contrib/restricted/libffi/configs/aarch64-unknown-linux-android21/include
+ )
SRCS(
- src/aarch64/ffi.c
- src/aarch64/sysv.S
+ src/aarch64/ffi.c
+ src/aarch64/sysv.S
)
ELSEIF (ARCH_ARM64 AND OS_DARWIN)
ADDINCL(
@@ -60,151 +60,151 @@ ELSEIF (ARCH_ARM64 AND OS_DARWIN)
src/aarch64/ffi.c
src/aarch64/sysv.S
)
-ELSEIF (ARCH_ARM64 AND OS_IOS)
- ADDINCL(
- contrib/restricted/libffi/configs/aarch64-apple-iphoneos
- GLOBAL contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include
- )
- SRCS(
- src/aarch64/ffi.c
- src/aarch64/sysv.S
- )
-ELSEIF (ARCH_ARM64 AND OS_LINUX)
- ADDINCL(
- contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu
- GLOBAL contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include
- )
- SRCS(
- src/aarch64/ffi.c
- src/aarch64/sysv.S
- )
-ELSEIF (ARCH_ARM7 AND OS_ANDROID)
- ADDINCL(
- contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16
- GLOBAL contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include
- )
- SRCS(
- src/arm/ffi.c
- src/arm/sysv.S
- )
-ELSEIF (ARCH_ARM7 AND OS_IOS)
- ADDINCL(
- contrib/restricted/libffi/configs/armv7-apple-iphoneos
- GLOBAL contrib/restricted/libffi/configs/armv7-apple-iphoneos/include
- )
- SRCS(
- src/arm/ffi.c
- src/arm/sysv.S
- )
-ELSEIF (ARCH_ARM7 AND OS_LINUX)
- ADDINCL(
- contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf
- GLOBAL contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include
- )
- SRCS(
- src/arm/ffi.c
- src/arm/sysv.S
- )
-ELSEIF (ARCH_I386 AND OS_ANDROID)
- ADDINCL(
- contrib/restricted/libffi/configs/i686-pc-linux-android16
- GLOBAL contrib/restricted/libffi/configs/i686-pc-linux-android16/include
- )
- SRCS(
- src/x86/ffi.c
- src/x86/sysv.S
- )
-ELSEIF (ARCH_I386 AND OS_IOS)
- ADDINCL(
- contrib/restricted/libffi/configs/i386-apple-iphonesimulator
- GLOBAL contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include
- )
- SRCS(
- src/x86/ffi.c
- src/x86/sysv.S
- )
-ELSEIF (ARCH_I386 AND OS_WINDOWS)
- ADDINCL(
- contrib/restricted/libffi/configs/i386-microsoft-windows
- GLOBAL contrib/restricted/libffi/configs/i386-microsoft-windows/include
- )
- SRCS(
- configs/i386-microsoft-windows/sysv_intel.masm
- src/x86/ffi.c
- )
-ELSEIF (ARCH_PPC64LE AND OS_LINUX)
- ADDINCL(
- contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu
- GLOBAL contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include
- )
- SRCS(
- src/powerpc/ffi.c
- src/powerpc/ffi_linux64.c
- src/powerpc/ffi_sysv.c
- src/powerpc/linux64.S
- src/powerpc/linux64_closure.S
- src/powerpc/ppc_closure.S
- src/powerpc/sysv.S
- )
-ELSEIF (ARCH_X86_64 AND OS_ANDROID)
- ADDINCL(
- contrib/restricted/libffi/configs/x86_64-pc-linux-android21
- GLOBAL contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include
- )
- SRCS(
- src/x86/ffi64.c
- src/x86/ffiw64.c
- src/x86/unix64.S
- src/x86/win64.S
- )
-ELSEIF (ARCH_X86_64 AND OS_DARWIN)
- ADDINCL(
- contrib/restricted/libffi/configs/x86_64-apple-macosx
- GLOBAL contrib/restricted/libffi/configs/x86_64-apple-macosx/include
- )
- SRCS(
- src/x86/ffi64.c
- src/x86/ffiw64.c
- src/x86/unix64.S
- src/x86/win64.S
- )
-ELSEIF (ARCH_X86_64 AND OS_IOS)
- ADDINCL(
- contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator
- GLOBAL contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include
- )
- SRCS(
- src/x86/ffi64.c
- src/x86/ffiw64.c
- src/x86/unix64.S
- src/x86/win64.S
- )
-ELSEIF (ARCH_X86_64 AND OS_LINUX)
- ADDINCL(
- contrib/restricted/libffi/configs/x86_64-pc-linux-gnu
- GLOBAL contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include
- )
- SRCS(
- src/x86/ffi64.c
- src/x86/ffiw64.c
- src/x86/unix64.S
- src/x86/win64.S
- )
-ELSEIF (ARCH_X86_64 AND OS_WINDOWS)
- ADDINCL(
- contrib/restricted/libffi/configs/x86_64-microsoft-windows
- GLOBAL contrib/restricted/libffi/configs/x86_64-microsoft-windows/include
- )
- SRCS(
- configs/x86_64-microsoft-windows/win64_intel.masm
- src/x86/ffiw64.c
- )
-ELSE()
- MESSAGE(FATAL_ERROR Unsupported libffi platform: ${TARGET_PLATFORM} / ${HARDWARE_TYPE})
+ELSEIF (ARCH_ARM64 AND OS_IOS)
+ ADDINCL(
+ contrib/restricted/libffi/configs/aarch64-apple-iphoneos
+ GLOBAL contrib/restricted/libffi/configs/aarch64-apple-iphoneos/include
+ )
+ SRCS(
+ src/aarch64/ffi.c
+ src/aarch64/sysv.S
+ )
+ELSEIF (ARCH_ARM64 AND OS_LINUX)
+ ADDINCL(
+ contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu
+ GLOBAL contrib/restricted/libffi/configs/aarch64-unknown-linux-gnu/include
+ )
+ SRCS(
+ src/aarch64/ffi.c
+ src/aarch64/sysv.S
+ )
+ELSEIF (ARCH_ARM7 AND OS_ANDROID)
+ ADDINCL(
+ contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16
+ GLOBAL contrib/restricted/libffi/configs/armv7a-unknown-linux-androideabi16/include
+ )
+ SRCS(
+ src/arm/ffi.c
+ src/arm/sysv.S
+ )
+ELSEIF (ARCH_ARM7 AND OS_IOS)
+ ADDINCL(
+ contrib/restricted/libffi/configs/armv7-apple-iphoneos
+ GLOBAL contrib/restricted/libffi/configs/armv7-apple-iphoneos/include
+ )
+ SRCS(
+ src/arm/ffi.c
+ src/arm/sysv.S
+ )
+ELSEIF (ARCH_ARM7 AND OS_LINUX)
+ ADDINCL(
+ contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf
+ GLOBAL contrib/restricted/libffi/configs/armv7a-unknown-linux-gnueabihf/include
+ )
+ SRCS(
+ src/arm/ffi.c
+ src/arm/sysv.S
+ )
+ELSEIF (ARCH_I386 AND OS_ANDROID)
+ ADDINCL(
+ contrib/restricted/libffi/configs/i686-pc-linux-android16
+ GLOBAL contrib/restricted/libffi/configs/i686-pc-linux-android16/include
+ )
+ SRCS(
+ src/x86/ffi.c
+ src/x86/sysv.S
+ )
+ELSEIF (ARCH_I386 AND OS_IOS)
+ ADDINCL(
+ contrib/restricted/libffi/configs/i386-apple-iphonesimulator
+ GLOBAL contrib/restricted/libffi/configs/i386-apple-iphonesimulator/include
+ )
+ SRCS(
+ src/x86/ffi.c
+ src/x86/sysv.S
+ )
+ELSEIF (ARCH_I386 AND OS_WINDOWS)
+ ADDINCL(
+ contrib/restricted/libffi/configs/i386-microsoft-windows
+ GLOBAL contrib/restricted/libffi/configs/i386-microsoft-windows/include
+ )
+ SRCS(
+ configs/i386-microsoft-windows/sysv_intel.masm
+ src/x86/ffi.c
+ )
+ELSEIF (ARCH_PPC64LE AND OS_LINUX)
+ ADDINCL(
+ contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu
+ GLOBAL contrib/restricted/libffi/configs/powerpc64le-unknown-linux-gnu/include
+ )
+ SRCS(
+ src/powerpc/ffi.c
+ src/powerpc/ffi_linux64.c
+ src/powerpc/ffi_sysv.c
+ src/powerpc/linux64.S
+ src/powerpc/linux64_closure.S
+ src/powerpc/ppc_closure.S
+ src/powerpc/sysv.S
+ )
+ELSEIF (ARCH_X86_64 AND OS_ANDROID)
+ ADDINCL(
+ contrib/restricted/libffi/configs/x86_64-pc-linux-android21
+ GLOBAL contrib/restricted/libffi/configs/x86_64-pc-linux-android21/include
+ )
+ SRCS(
+ src/x86/ffi64.c
+ src/x86/ffiw64.c
+ src/x86/unix64.S
+ src/x86/win64.S
+ )
+ELSEIF (ARCH_X86_64 AND OS_DARWIN)
+ ADDINCL(
+ contrib/restricted/libffi/configs/x86_64-apple-macosx
+ GLOBAL contrib/restricted/libffi/configs/x86_64-apple-macosx/include
+ )
+ SRCS(
+ src/x86/ffi64.c
+ src/x86/ffiw64.c
+ src/x86/unix64.S
+ src/x86/win64.S
+ )
+ELSEIF (ARCH_X86_64 AND OS_IOS)
+ ADDINCL(
+ contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator
+ GLOBAL contrib/restricted/libffi/configs/x86_64-apple-iphonesimulator/include
+ )
+ SRCS(
+ src/x86/ffi64.c
+ src/x86/ffiw64.c
+ src/x86/unix64.S
+ src/x86/win64.S
+ )
+ELSEIF (ARCH_X86_64 AND OS_LINUX)
+ ADDINCL(
+ contrib/restricted/libffi/configs/x86_64-pc-linux-gnu
+ GLOBAL contrib/restricted/libffi/configs/x86_64-pc-linux-gnu/include
+ )
+ SRCS(
+ src/x86/ffi64.c
+ src/x86/ffiw64.c
+ src/x86/unix64.S
+ src/x86/win64.S
+ )
+ELSEIF (ARCH_X86_64 AND OS_WINDOWS)
+ ADDINCL(
+ contrib/restricted/libffi/configs/x86_64-microsoft-windows
+ GLOBAL contrib/restricted/libffi/configs/x86_64-microsoft-windows/include
+ )
+ SRCS(
+ configs/x86_64-microsoft-windows/win64_intel.masm
+ src/x86/ffiw64.c
+ )
+ELSE()
+ MESSAGE(FATAL_ERROR Unsupported libffi platform: ${TARGET_PLATFORM} / ${HARDWARE_TYPE})
ENDIF()
END()
-
-RECURSE(
- testsuite
-)
+
+RECURSE(
+ testsuite
+)
diff --git a/contrib/restricted/ya.make b/contrib/restricted/ya.make
index a3099194d8..b52a206733 100644
--- a/contrib/restricted/ya.make
+++ b/contrib/restricted/ya.make
@@ -6,11 +6,11 @@ OWNER(
RECURSE(
abseil-cpp
abseil-cpp-tstring
- alsa-lib
- avahi
+ alsa-lib
+ avahi
aws
blis
- boost
+ boost
cityhash-1.0.2
cmph
cpuinfo
@@ -19,33 +19,33 @@ RECURSE(
fast_float
dragonbox
gemmlowp
- glib
- glib-networking
- glibmm
+ glib
+ glib-networking
+ glibmm
google
googletest
- gst-plugins-bad
- gst-plugins-base
- gst-plugins-good
- gstreamer
+ gst-plugins-bad
+ gst-plugins-base
+ gst-plugins-good
+ gstreamer
http-parser
keyutils
libelf
- libffi
+ libffi
libiscsi
libntirpc
librseq
- libsigcxx
- libsoup
+ libsigcxx
+ libsoup
libtorrent
liburcu
libxsmm
llhttp
- mpg123
+ mpg123
murmurhash
nfs_ganesha
noc
- openal-soft
+ openal-soft
patched
protobuf-c
protoc-c
@@ -59,13 +59,13 @@ RECURSE(
turbo_base64
uriparser
)
-
-IF(OS_LINUX OR OS_DARWIN)
- RECURSE(
- boost/libs/python
- boost/libs/python/arcadia_test
- )
-ENDIF()
+
+IF(OS_LINUX OR OS_DARWIN)
+ RECURSE(
+ boost/libs/python
+ boost/libs/python/arcadia_test
+ )
+ENDIF()
IF(OS_ANDROID)
RECURSE(ashmem)
diff --git a/contrib/tools/cython/Cython/Compiler/Main.py b/contrib/tools/cython/Cython/Compiler/Main.py
index 92f939137e..af873843b5 100644
--- a/contrib/tools/cython/Cython/Compiler/Main.py
+++ b/contrib/tools/cython/Cython/Compiler/Main.py
@@ -206,7 +206,7 @@ class Context(object):
if not pxd_pathname:
if debug_find_module:
print("...looking for pxd file")
- pxd_pathname = self.find_pxd_file(qualified_name, pos)
+ pxd_pathname = self.find_pxd_file(qualified_name, pos)
if debug_find_module:
print("......found %s" % pxd_pathname)
if not pxd_pathname and need_pxd:
@@ -238,7 +238,7 @@ class Context(object):
pass
return scope
- def find_pxd_file(self, qualified_name, pos, sys_path=False):
+ def find_pxd_file(self, qualified_name, pos, sys_path=False):
# Search include path (and sys.path if sys_path is True) for
# the .pxd file corresponding to the given fully-qualified
# module name.
diff --git a/contrib/tools/cython/Cython/Compiler/PyrexTypes.py b/contrib/tools/cython/Cython/Compiler/PyrexTypes.py
index 192781c4ce..3d4931cea6 100644
--- a/contrib/tools/cython/Cython/Compiler/PyrexTypes.py
+++ b/contrib/tools/cython/Cython/Compiler/PyrexTypes.py
@@ -3482,7 +3482,7 @@ class CStructOrUnionType(CType):
return expr_code
return super(CStructOrUnionType, self).cast_code(expr_code)
-cpp_string_conversions = ("std::string", "TString", "TStringBuf")
+cpp_string_conversions = ("std::string", "TString", "TStringBuf")
builtin_cpp_conversions = {
# type element template params
@@ -3574,10 +3574,10 @@ class CppClassType(CType):
if self.cname in cpp_string_conversions:
cls = 'string'
tags = type_identifier(self),
- elif self.cname.startswith('std::'):
- cls = self.cname[5:]
+ elif self.cname.startswith('std::'):
+ cls = self.cname[5:]
else:
- cls = 'arcadia_' + self.cname
+ cls = 'arcadia_' + self.cname
cname = '__pyx_convert_%s_from_py_%s' % (cls, '__and_'.join(tags))
context.update({
'cname': cname,
@@ -3619,12 +3619,12 @@ class CppClassType(CType):
cls = 'string'
prefix = 'PyObject_' # gets specialised by explicit type casts in CoerceToPyTypeNode
tags = type_identifier(self),
- elif self.cname.startswith('std::'):
+ elif self.cname.startswith('std::'):
cls = self.cname[5:]
prefix = ''
- else:
- cls = 'arcadia_' + self.cname
- prefix = ''
+ else:
+ cls = 'arcadia_' + self.cname
+ prefix = ''
cname = "__pyx_convert_%s%s_to_py_%s" % (prefix, cls, "____".join(tags))
context.update({
'cname': cname,
diff --git a/contrib/tools/cython/Cython/Includes/numpy.pxd b/contrib/tools/cython/Cython/Includes/numpy.pxd
index 5a317fb4c8..789669dac1 100644
--- a/contrib/tools/cython/Cython/Includes/numpy.pxd
+++ b/contrib/tools/cython/Cython/Includes/numpy.pxd
@@ -923,8 +923,8 @@ cdef extern from "numpy/ufuncobject.h":
void **data
int ntypes
int check_return
- char *name
- char *types
+ char *name
+ char *types
char *doc
void *ptr
PyObject *obj
diff --git a/contrib/tools/cython/Cython/Utility/CppConvert.pyx b/contrib/tools/cython/Cython/Utility/CppConvert.pyx
index 4f89c038d4..5f7859dd0e 100644
--- a/contrib/tools/cython/Cython/Utility/CppConvert.pyx
+++ b/contrib/tools/cython/Cython/Utility/CppConvert.pyx
@@ -207,8 +207,8 @@ cdef object {{cname}}(const map[X,Y]& s):
o[key_value.first] = key_value.second
cython.operator.preincrement(iter)
return o
-
-
+
+
#################### complex.from_py ####################
cdef extern from *:
@@ -237,105 +237,105 @@ cdef object {{cname}}(const std_complex[X]& z):
return tmp
-#################### arcadia_TMaybe.from_py ####################
-
-cdef extern from *:
- cdef cppclass TMaybe [T]:
- TMaybe()
- TMaybe(T&)
- TMaybe& operator =(T&)
-
-@cname("{{cname}}")
-cdef TMaybe[X] {{cname}}(object o) except *:
- cdef TMaybe[X] result
- if o is not None:
+#################### arcadia_TMaybe.from_py ####################
+
+cdef extern from *:
+ cdef cppclass TMaybe [T]:
+ TMaybe()
+ TMaybe(T&)
+ TMaybe& operator =(T&)
+
+@cname("{{cname}}")
+cdef TMaybe[X] {{cname}}(object o) except *:
+ cdef TMaybe[X] result
+ if o is not None:
result = <X>o
- return result
-
-#################### arcadia_TMaybe.to_py ####################
-
-cdef extern from *:
- cdef cppclass TMaybe [T]:
- bint Defined()
- T& GetRef()
-
-@cname("{{cname}}")
-cdef object {{cname}}(const TMaybe[X]& s):
- if s.Defined():
+ return result
+
+#################### arcadia_TMaybe.to_py ####################
+
+cdef extern from *:
+ cdef cppclass TMaybe [T]:
+ bint Defined()
+ T& GetRef()
+
+@cname("{{cname}}")
+cdef object {{cname}}(const TMaybe[X]& s):
+ if s.Defined():
return s.GetRef()
- return None
-
-
+ return None
+
+
#################### arcadia_TVector.from_py ####################
-
-cdef extern from *:
+
+cdef extern from *:
cdef cppclass TVector [T]:
- void push_back(T&)
-
-@cname("{{cname}}")
+ void push_back(T&)
+
+@cname("{{cname}}")
cdef TVector[X] {{cname}}(object o) except *:
cdef TVector[X] v
- for item in o:
+ for item in o:
v.push_back(<X>item)
- return v
-
-
+ return v
+
+
#################### arcadia_TVector.to_py ####################
-
-cdef extern from *:
+
+cdef extern from *:
cdef cppclass TVector [T]:
- size_t size()
- T& operator[](size_t)
-
-@cname("{{cname}}")
+ size_t size()
+ T& operator[](size_t)
+
+@cname("{{cname}}")
cdef object {{cname}}(const TVector[X]& v):
return [v[i] for i in range(v.size())]
-
-
+
+
#################### arcadia_THashMap.from_py ####################
-
-cdef extern from *:
- cdef cppclass pair "std::pair" [T, U]:
- pair(T&, U&)
+
+cdef extern from *:
+ cdef cppclass pair "std::pair" [T, U]:
+ pair(T&, U&)
cdef cppclass THashMap [T, U]:
- void insert(pair[T, U]&)
-
-
-@cname("{{cname}}")
+ void insert(pair[T, U]&)
+
+
+@cname("{{cname}}")
cdef THashMap[X,Y] {{cname}}(object o) except *:
- cdef dict d = o
+ cdef dict d = o
cdef THashMap[X,Y] m
- for key, value in d.iteritems():
+ for key, value in d.iteritems():
m.insert(pair[X,Y](<X>key, <Y>value))
- return m
-
-
+ return m
+
+
#################### arcadia_THashMap.to_py ####################
-
-cimport cython
-
-cdef extern from *:
+
+cimport cython
+
+cdef extern from *:
cdef cppclass THashMap [T, U]:
- cppclass value_type:
- T first
- U second
- cppclass const_iterator:
- value_type& operator*()
- const_iterator operator++()
- bint operator!=(const_iterator)
- const_iterator begin()
- const_iterator end()
-
-@cname("{{cname}}")
+ cppclass value_type:
+ T first
+ U second
+ cppclass const_iterator:
+ value_type& operator*()
+ const_iterator operator++()
+ bint operator!=(const_iterator)
+ const_iterator begin()
+ const_iterator end()
+
+@cname("{{cname}}")
cdef dict {{cname}}(const THashMap[X,Y]& s):
- cdef dict result = {}
+ cdef dict result = {}
cdef const THashMap[X,Y].value_type *key_value
cdef THashMap[X,Y].const_iterator iter = s.begin()
- while iter != s.end():
- key_value = &cython.operator.dereference(iter)
+ while iter != s.end():
+ key_value = &cython.operator.dereference(iter)
result[key_value.first] = key_value.second
- cython.operator.preincrement(iter)
- return result
+ cython.operator.preincrement(iter)
+ return result
#################### arcadia_TMap.from_py ####################
diff --git a/contrib/tools/protoc/plugins/cpp_styleguide/cpp_styleguide.cpp b/contrib/tools/protoc/plugins/cpp_styleguide/cpp_styleguide.cpp
index 5a15ea3d21..cd96aa0565 100644
--- a/contrib/tools/protoc/plugins/cpp_styleguide/cpp_styleguide.cpp
+++ b/contrib/tools/protoc/plugins/cpp_styleguide/cpp_styleguide.cpp
@@ -683,7 +683,7 @@ namespace NPlugins {
}
void GenerateClassDefinitionExtension() {
- GenerateSaveLoadImplementation();
+ GenerateSaveLoadImplementation();
GenerateJSONImplementation();
for (auto& nestedGenerator: NestedGenerators_) {
@@ -785,33 +785,33 @@ namespace NPlugins {
printer.Print(vars, " return ::google::protobuf::io::TAsJSON<$class$>(*this);\n");
printer.Print("}\n");
- printer.Print("void Save(IOutputStream* output) const;\n");
- printer.Print("void Load(IInputStream* input);\n");
- }
+ printer.Print("void Save(IOutputStream* output) const;\n");
+ printer.Print("void Load(IInputStream* input);\n");
+ }
printer.Print("// End of Yandex-specific extension\n");
}
- void GenerateSaveLoadImplementation() {
- TProtoStringType fileName = SourceFileName(Descriptor_->file());
- TProtoStringType scope = "namespace_scope";
+ void GenerateSaveLoadImplementation() {
+ TProtoStringType fileName = SourceFileName(Descriptor_->file());
+ TProtoStringType scope = "namespace_scope";
std::unique_ptr<io::ZeroCopyOutputStream> output(
- OutputDirectory_->OpenForInsert(fileName, scope));
- io::Printer printer(output.get(), '$');
-
- TVariables vars;
- vars["class"] = Classname_;
- if (!IsLiteRuntimeMessage(Descriptor_)) {
- printer.Print("// Yandex-specific extension\n");
- printer.Print(vars, "void $class$::Save(IOutputStream* output) const {\n");
- printer.Print(" ::Save(output, static_cast<const ::google::protobuf::Message&>(*this));\n");
- printer.Print("}\n");
- printer.Print(vars, "void $class$::Load(IInputStream* input) {\n");
- printer.Print(" ::Load(input, static_cast<::google::protobuf::Message&>(*this));\n");
- printer.Print("}\n");
- printer.Print("// End of Yandex-specific extension\n");
- }
- }
-
+ OutputDirectory_->OpenForInsert(fileName, scope));
+ io::Printer printer(output.get(), '$');
+
+ TVariables vars;
+ vars["class"] = Classname_;
+ if (!IsLiteRuntimeMessage(Descriptor_)) {
+ printer.Print("// Yandex-specific extension\n");
+ printer.Print(vars, "void $class$::Save(IOutputStream* output) const {\n");
+ printer.Print(" ::Save(output, static_cast<const ::google::protobuf::Message&>(*this));\n");
+ printer.Print("}\n");
+ printer.Print(vars, "void $class$::Load(IInputStream* input) {\n");
+ printer.Print(" ::Load(input, static_cast<::google::protobuf::Message&>(*this));\n");
+ printer.Print("}\n");
+ printer.Print("// End of Yandex-specific extension\n");
+ }
+ }
+
void GenerateDebugStringImplementation() {
TProtoStringType fileName = SourceFileName(Descriptor_->file());
TProtoStringType scope = "namespace_scope";
diff --git a/contrib/tools/python3/src/Modules/ya.make b/contrib/tools/python3/src/Modules/ya.make
index cff5baf258..47e38bca51 100644
--- a/contrib/tools/python3/src/Modules/ya.make
+++ b/contrib/tools/python3/src/Modules/ya.make
@@ -10,11 +10,11 @@ PEERDIR(
ADDINCL contrib/libs/openssl
ADDINCL contrib/libs/zlib
contrib/libs/xz/liblzma
- contrib/restricted/libffi
+ contrib/restricted/libffi
)
ADDINCL(
- contrib/restricted/libffi/include
+ contrib/restricted/libffi/include
contrib/tools/python3/src/Include
contrib/tools/python3/src/Include/internal
contrib/tools/python3/src/Modules
diff --git a/contrib/tools/ya.make b/contrib/tools/ya.make
index 95edcefd66..750911c587 100644
--- a/contrib/tools/ya.make
+++ b/contrib/tools/ya.make
@@ -20,7 +20,7 @@ RECURSE(
langid
leveldb
lld
- lldb
+ lldb
mp4viewer
open-vcdiff
open-vcdiff/bin
diff --git a/library/cpp/containers/stack_vector/stack_vec.h b/library/cpp/containers/stack_vector/stack_vec.h
index 9e396d4983..fcc5d9a2a5 100644
--- a/library/cpp/containers/stack_vector/stack_vec.h
+++ b/library/cpp/containers/stack_vector/stack_vec.h
@@ -1,7 +1,7 @@
#pragma once
#include <util/generic/vector.h>
-#include <util/ysaveload.h>
+#include <util/ysaveload.h>
#include <type_traits>
@@ -186,10 +186,10 @@ public:
return *this;
}
};
-
-template <typename T, size_t CountOnStack, class Alloc>
+
+template <typename T, size_t CountOnStack, class Alloc>
class TSerializer<TStackVec<T, CountOnStack, true, Alloc>>: public TVectorSerializer<TStackVec<T, CountOnStack, true, Alloc>> {
-};
+};
template <typename T, size_t CountOnStack, class Alloc>
class TSerializer<TStackVec<T, CountOnStack, false, Alloc>> {
diff --git a/library/cpp/dbg_output/dumpers.h b/library/cpp/dbg_output/dumpers.h
index 2c9fc8c079..4868e97da0 100644
--- a/library/cpp/dbg_output/dumpers.h
+++ b/library/cpp/dbg_output/dumpers.h
@@ -47,19 +47,19 @@ struct TDumper<TCopyPtr<T, C, D>> {
}
};
-//small ints
+//small ints
// Default dumper prints them via IOutputStream << (value), which results in raw
-// chars, not integer values. Cast to a bigger int type to force printing as
-// integers.
-// NB: i8 = signed char != char != unsigned char = ui8
-template <>
-struct TDumper<ui8>: public TDumper<i32> {
-};
-
-template <>
-struct TDumper<i8>: public TDumper<i32> {
-};
-
+// chars, not integer values. Cast to a bigger int type to force printing as
+// integers.
+// NB: i8 = signed char != char != unsigned char = ui8
+template <>
+struct TDumper<ui8>: public TDumper<i32> {
+};
+
+template <>
+struct TDumper<i8>: public TDumper<i32> {
+};
+
//chars
template <>
struct TDumper<char>: public TCharDumper {
diff --git a/library/cpp/dbg_output/ut/dbg_output_ut.cpp b/library/cpp/dbg_output/ut/dbg_output_ut.cpp
index 568e612a38..7b285c84cb 100644
--- a/library/cpp/dbg_output/ut/dbg_output_ut.cpp
+++ b/library/cpp/dbg_output/ut/dbg_output_ut.cpp
@@ -2,7 +2,7 @@
#include <library/cpp/testing/unittest/registar.h>
#include <util/stream/str.h>
-#include <util/string/builder.h>
+#include <util/string/builder.h>
#include <util/string/escape.h>
#include <util/generic/map.h>
@@ -94,13 +94,13 @@ Y_UNIT_TEST_SUITE(TContainerPrintersTest) {
"\\x1B[44m\\x1B[1;31m\\x1B[1;32m{\\x1B[1;31m\\x1B[1;31m2\\x1B[22;39m\\x1B[1;32m -> "
"\\x1B[1;31m'6'\\x1B[22;39m\\x1B[1;32m}\\x1B[22;39m\\x1B[22;39m\\x1B[49m\\x1B[1;32m}\\x1B[22;39m");
}
-
+
Y_UNIT_TEST(SmallIntOrChar) {
- char c = 'e';
- i8 i = -100;
- ui8 u = 10;
- UNIT_ASSERT_VALUES_EQUAL(TStringBuilder() << DbgDump(c), "'e'");
- UNIT_ASSERT_VALUES_EQUAL(TStringBuilder() << DbgDump(i), "-100");
- UNIT_ASSERT_VALUES_EQUAL(TStringBuilder() << DbgDump(u), "10");
- }
+ char c = 'e';
+ i8 i = -100;
+ ui8 u = 10;
+ UNIT_ASSERT_VALUES_EQUAL(TStringBuilder() << DbgDump(c), "'e'");
+ UNIT_ASSERT_VALUES_EQUAL(TStringBuilder() << DbgDump(i), "-100");
+ UNIT_ASSERT_VALUES_EQUAL(TStringBuilder() << DbgDump(u), "10");
+ }
}
diff --git a/library/cpp/getopt/small/completion_generator.cpp b/library/cpp/getopt/small/completion_generator.cpp
index 87aacd9341..ac41988217 100644
--- a/library/cpp/getopt/small/completion_generator.cpp
+++ b/library/cpp/getopt/small/completion_generator.cpp
@@ -1,6 +1,6 @@
#include "completion_generator.h"
-#include <util/generic/overloaded.h>
+#include <util/generic/overloaded.h>
#include <util/string/ascii.h>
#include <util/generic/hash_set.h>
diff --git a/library/cpp/json/writer/json_value.cpp b/library/cpp/json/writer/json_value.cpp
index c574ee2d8c..c61e8d1dc4 100644
--- a/library/cpp/json/writer/json_value.cpp
+++ b/library/cpp/json/writer/json_value.cpp
@@ -504,7 +504,7 @@ namespace NJson {
TJsonValue::TMapType& TJsonValue::GetMapSafe() {
return const_cast<TJsonValue::TMapType&>(const_cast<const TJsonValue*>(this)->GetMapSafe());
}
-
+
const TJsonValue::TArray& TJsonValue::GetArraySafe() const {
if (Type != JSON_ARRAY)
ythrow TJsonException() << "Not an array";
diff --git a/library/cpp/json/writer/json_value_ut.cpp b/library/cpp/json/writer/json_value_ut.cpp
index e064fbc785..dc7f6affdf 100644
--- a/library/cpp/json/writer/json_value_ut.cpp
+++ b/library/cpp/json/writer/json_value_ut.cpp
@@ -476,34 +476,34 @@ Y_UNIT_TEST_SUITE(TJsonValueTest) {
UNIT_ASSERT(false);
}
}
-
- {
- // Check non-const GetArraySafe()
- TJsonValue json{JSON_ARRAY};
- json.GetArraySafe().push_back(TJsonValue{"foo"});
-
- TJsonValue expectedJson;
- expectedJson.AppendValue(TJsonValue{"foo"});
- UNIT_ASSERT(json == expectedJson);
-
- TJsonValue::TArray jsonArray = std::move(json.GetArraySafe());
- TJsonValue::TArray expectedArray = {TJsonValue{"foo"}};
- UNIT_ASSERT(jsonArray == expectedArray);
- }
-
- {
- // Check non-const GetMap()
- TJsonValue json{JSON_MAP};
- json.GetMapSafe()["foo"] = "bar";
-
- TJsonValue expectedJson;
- expectedJson.InsertValue("foo", "bar");
- UNIT_ASSERT(json == expectedJson);
-
+
+ {
+ // Check non-const GetArraySafe()
+ TJsonValue json{JSON_ARRAY};
+ json.GetArraySafe().push_back(TJsonValue{"foo"});
+
+ TJsonValue expectedJson;
+ expectedJson.AppendValue(TJsonValue{"foo"});
+ UNIT_ASSERT(json == expectedJson);
+
+ TJsonValue::TArray jsonArray = std::move(json.GetArraySafe());
+ TJsonValue::TArray expectedArray = {TJsonValue{"foo"}};
+ UNIT_ASSERT(jsonArray == expectedArray);
+ }
+
+ {
+ // Check non-const GetMap()
+ TJsonValue json{JSON_MAP};
+ json.GetMapSafe()["foo"] = "bar";
+
+ TJsonValue expectedJson;
+ expectedJson.InsertValue("foo", "bar");
+ UNIT_ASSERT(json == expectedJson);
+
TJsonValue::TMapType jsonMap = std::move(json.GetMapSafe());
TJsonValue::TMapType expectedMap = {{"foo", TJsonValue{"bar"}}};
- UNIT_ASSERT(jsonMap == expectedMap);
- }
+ UNIT_ASSERT(jsonMap == expectedMap);
+ }
}
Y_UNIT_TEST(NonexistentFieldAccessTest) {
diff --git a/library/cpp/resource/registry.cpp b/library/cpp/resource/registry.cpp
index 01d820fca0..66001c4769 100644
--- a/library/cpp/resource/registry.cpp
+++ b/library/cpp/resource/registry.cpp
@@ -36,8 +36,8 @@ namespace {
Decompress(data).Quote().c_str());
} else {
Y_VERIFY(false, "Redefinition of key %s,"
- " old size: %zu,"
- " new size: %zu.",
+ " old size: %zu,"
+ " new size: %zu.",
TString{key}.Quote().c_str(), vsize, dsize);
}
}
diff --git a/library/cpp/testing/common/env.cpp b/library/cpp/testing/common/env.cpp
index fc70e0f5b9..fa3a47fe16 100644
--- a/library/cpp/testing/common/env.cpp
+++ b/library/cpp/testing/common/env.cpp
@@ -1,7 +1,7 @@
#include "env.h"
-#include <build/scripts/c_templates/svnversion.h>
-
+#include <build/scripts/c_templates/svnversion.h>
+
#include <util/folder/dirut.h>
#include <util/folder/path.h>
#include <util/generic/singleton.h>
@@ -16,22 +16,22 @@
#include <library/cpp/json/json_value.h>
#include <library/cpp/json/json_writer.h>
-TString ArcadiaSourceRoot() {
- if (const auto& sourceRoot = NPrivate::GetTestEnv().SourceRoot) {
- return sourceRoot;
- } else {
- return GetArcadiaSourcePath();
- }
-}
-
-TString BuildRoot() {
- if (const auto& buildRoot = NPrivate::GetTestEnv().BuildRoot) {
- return buildRoot;
- } else {
- return GetArcadiaSourcePath();
- }
-}
-
+TString ArcadiaSourceRoot() {
+ if (const auto& sourceRoot = NPrivate::GetTestEnv().SourceRoot) {
+ return sourceRoot;
+ } else {
+ return GetArcadiaSourcePath();
+ }
+}
+
+TString BuildRoot() {
+ if (const auto& buildRoot = NPrivate::GetTestEnv().BuildRoot) {
+ return buildRoot;
+ } else {
+ return GetArcadiaSourcePath();
+ }
+}
+
TString ArcadiaFromCurrentLocation(TStringBuf where, TStringBuf path) {
return (TFsPath(ArcadiaSourceRoot()) / TFsPath(where).Parent() / path).Fix();
}
diff --git a/library/cpp/testing/unittest/registar.h b/library/cpp/testing/unittest/registar.h
index 05facde717..44517a0092 100644
--- a/library/cpp/testing/unittest/registar.h
+++ b/library/cpp/testing/unittest/registar.h
@@ -561,7 +561,7 @@ public: \
} \
} while (false)
-#define UNIT_CHECK_GENERATED_NO_EXCEPTION(A, E) UNIT_CHECK_GENERATED_NO_EXCEPTION_C(A, E, "and exception message is:\n" << CurrentExceptionMessage())
+#define UNIT_CHECK_GENERATED_NO_EXCEPTION(A, E) UNIT_CHECK_GENERATED_NO_EXCEPTION_C(A, E, "and exception message is:\n" << CurrentExceptionMessage())
// Same as UNIT_ASSERT_EXCEPTION_SATISFIES but prints additional string C when nothing was thrown
#define UNIT_ASSERT_EXCEPTION_SATISFIES_C(A, E, pred, C) \
@@ -795,11 +795,11 @@ public: \
};
struct TBaseTestCase {
- // NOTE: since EACH test case is instantiated for listing tests, its
- // ctor/dtor are not the best place to do heavy preparations in test fixtures.
- //
- // Consider using SetUp()/TearDown() methods instead
-
+ // NOTE: since EACH test case is instantiated for listing tests, its
+ // ctor/dtor are not the best place to do heavy preparations in test fixtures.
+ //
+ // Consider using SetUp()/TearDown() methods instead
+
inline TBaseTestCase()
: TBaseTestCase(nullptr, nullptr, false)
{
@@ -814,21 +814,21 @@ public: \
virtual ~TBaseTestCase() = default;
- // Each test case is executed in 3 steps:
- //
- // 1. SetUp() (from fixture)
- // 2. Execute_() (test body from Y_UNIT_TEST macro)
- // 3. TearDown() (from fixture)
- //
- // Both SetUp() and TearDown() may use UNIT_* check macros and are only
- // called when the test is executed.
-
- virtual void SetUp(TTestContext& /* context */) {
- }
-
- virtual void TearDown(TTestContext& /* context */) {
- }
-
+ // Each test case is executed in 3 steps:
+ //
+ // 1. SetUp() (from fixture)
+ // 2. Execute_() (test body from Y_UNIT_TEST macro)
+ // 3. TearDown() (from fixture)
+ //
+ // Both SetUp() and TearDown() may use UNIT_* check macros and are only
+ // called when the test is executed.
+
+ virtual void SetUp(TTestContext& /* context */) {
+ }
+
+ virtual void TearDown(TTestContext& /* context */) {
+ }
+
virtual void Execute_(TTestContext& context) {
Body_(context);
}
@@ -958,12 +958,12 @@ public: \
this->BeforeTest(i->Name_); \
{ \
TCleanUp cleaner(this); \
- auto testCase = [&i, &context] { \
- i->SetUp(context); \
- i->Execute_(context); \
- i->TearDown(context); \
- }; \
- this->T::Run(testCase, StaticName(), i->Name_, i->ForceFork_); \
+ auto testCase = [&i, &context] { \
+ i->SetUp(context); \
+ i->Execute_(context); \
+ i->TearDown(context); \
+ }; \
+ this->T::Run(testCase, StaticName(), i->Name_, i->ForceFork_); \
} \
} catch (const ::NUnitTest::TAssertException&) { \
} catch (const yexception& e) { \
diff --git a/library/cpp/testing/unittest/ut/main.cpp b/library/cpp/testing/unittest/ut/main.cpp
index e80326adf1..e303e21e30 100644
--- a/library/cpp/testing/unittest/ut/main.cpp
+++ b/library/cpp/testing/unittest/ut/main.cpp
@@ -36,20 +36,20 @@ namespace {
struct TOtherFixture : public NUnitTest::TBaseFixture {
size_t TheAnswer = 42;
};
-
- struct TSetUpTearDownFixture : public NUnitTest::TBaseFixture {
- int Magic = 3;
-
- void SetUp(NUnitTest::TTestContext&) override {
- UNIT_ASSERT_VALUES_EQUAL(Magic, 3);
- Magic = 17;
- }
-
- void TearDown(NUnitTest::TTestContext&) override {
- UNIT_ASSERT_VALUES_EQUAL(Magic, 42);
- Magic = 100;
- }
- };
+
+ struct TSetUpTearDownFixture : public NUnitTest::TBaseFixture {
+ int Magic = 3;
+
+ void SetUp(NUnitTest::TTestContext&) override {
+ UNIT_ASSERT_VALUES_EQUAL(Magic, 3);
+ Magic = 17;
+ }
+
+ void TearDown(NUnitTest::TTestContext&) override {
+ UNIT_ASSERT_VALUES_EQUAL(Magic, 42);
+ Magic = 100;
+ }
+ };
}
TEST_F(TFixture, Test1) {
@@ -83,11 +83,11 @@ Y_UNIT_TEST_SUITE_F(TestSuiteFixture, TSimpleFixture)
UNIT_ASSERT_EQUAL(TheAnswer, 42);
}
}
-
-Y_UNIT_TEST_SUITE(TestSetUpTearDownFixture)
-{
- Y_UNIT_TEST_F(Test1, TSetUpTearDownFixture) {
- UNIT_ASSERT_VALUES_EQUAL(Magic, 17);
- Magic = 42;
- }
-}
+
+Y_UNIT_TEST_SUITE(TestSetUpTearDownFixture)
+{
+ Y_UNIT_TEST_F(Test1, TSetUpTearDownFixture) {
+ UNIT_ASSERT_VALUES_EQUAL(Magic, 17);
+ Magic = 42;
+ }
+}
diff --git a/library/cpp/ya.make b/library/cpp/ya.make
index 78fc7da69b..8c1193b007 100644
--- a/library/cpp/ya.make
+++ b/library/cpp/ya.make
@@ -35,7 +35,7 @@ RECURSE(
cgiparam/ut
charset
charset/ut
- chromium_trace
+ chromium_trace
clang_tidy
clickhouse
clustered_hnsw
diff --git a/library/cpp/yson/node/node.cpp b/library/cpp/yson/node/node.cpp
index 5917d73fbc..b39e070718 100644
--- a/library/cpp/yson/node/node.cpp
+++ b/library/cpp/yson/node/node.cpp
@@ -442,7 +442,7 @@ const TNode& TNode::At(size_t index) const {
CheckType(List);
const auto& list = std::get<TListType>(Value_);
if (index >= list.size()) {
- ythrow TLookupError() << "List out-of-range: requested index=" << index << ", but size=" << list.size();
+ ythrow TLookupError() << "List out-of-range: requested index=" << index << ", but size=" << list.size();
}
return list[index];
}
@@ -451,7 +451,7 @@ TNode& TNode::At(size_t index) {
CheckType(List);
auto& list = std::get<TListType>(Value_);
if (index >= list.size()) {
- ythrow TLookupError() << "List out-of-range: requested index=" << index << ", but size=" << list.size();
+ ythrow TLookupError() << "List out-of-range: requested index=" << index << ", but size=" << list.size();
}
return list[index];
}
@@ -545,7 +545,7 @@ const TNode& TNode::At(const TStringBuf key) const {
const auto& map = std::get<TMapType>(Value_);
TMapType::const_iterator i = map.find(key);
if (i == map.end()) {
- ythrow TLookupError() << "Cannot find key " << key;
+ ythrow TLookupError() << "Cannot find key " << key;
} else {
return i->second;
}
@@ -556,7 +556,7 @@ TNode& TNode::At(const TStringBuf key) {
auto& map = std::get<TMapType>(Value_);
TMapType::iterator i = map.find(key);
if (i == map.end()) {
- ythrow TLookupError() << "Cannot find key " << key;
+ ythrow TLookupError() << "Cannot find key " << key;
} else {
return i->second;
}
diff --git a/library/cpp/yson/node/node.h b/library/cpp/yson/node/node.h
index 2873eea4df..5f90f95df0 100644
--- a/library/cpp/yson/node/node.h
+++ b/library/cpp/yson/node/node.h
@@ -22,10 +22,10 @@ namespace NYT {
class TNode
{
public:
- class TLookupError
- : public TWithBackTrace<yexception>
- { };
-
+ class TLookupError
+ : public TWithBackTrace<yexception>
+ { };
+
class TTypeError
: public TWithBackTrace<yexception>
{ };
@@ -223,12 +223,12 @@ public:
template<typename T>
T ChildConvertTo(const TStringBuf key) const;
- template<typename T>
- const T& ChildAs(const TStringBuf key) const;
-
- template<typename T>
- T& ChildAs(const TStringBuf key);
-
+ template<typename T>
+ const T& ChildAs(const TStringBuf key) const;
+
+ template<typename T>
+ T& ChildAs(const TStringBuf key);
+
// list getters
// works the same way like simple getters
const TString& ChildAsString(size_t index) const;
@@ -247,13 +247,13 @@ public:
template<typename T>
T ChildConvertTo(size_t index) const;
- template<typename T>
- const T& ChildAs(size_t index) const;
+ template<typename T>
+ const T& ChildAs(size_t index) const;
+
+ template<typename T>
+ T& ChildAs(size_t index);
+
- template<typename T>
- T& ChildAs(size_t index);
-
-
// attributes
bool HasAttributes() const;
void ClearAttributes();
@@ -458,42 +458,42 @@ inline T TNode::ChildConvertTo(size_t index) const {
}
template<typename T>
-inline const T& TNode::ChildAs(const TStringBuf key) const {
- const auto& node = At(key);
- try {
- return node.As<T>();
- } catch (TTypeError& e) {
- e << ", during getting key=" << key;
- throw e;
- } catch (...) {
- ythrow TTypeError() << CurrentExceptionMessage() << ", during getting key=" << key;
- }
-}
-
-template<typename T>
-inline const T& TNode::ChildAs(size_t index) const {
- const auto& node = At(index);
- try {
- return node.As<T>();
- } catch (TTypeError& e) {
- e << ", during getting index=" << index;
- throw e;
- } catch (...) {
- ythrow TTypeError() << CurrentExceptionMessage() << ", during getting index=" << index;
- }
-}
-
-template<typename T>
-inline T& TNode::ChildAs(const TStringBuf key) {
- return const_cast<T&>(static_cast<const TNode*>(this)->ChildAs<T>(key));
-}
-
-template<typename T>
-inline T& TNode::ChildAs(size_t index) {
- return const_cast<T&>(static_cast<const TNode*>(this)->ChildAs<T>(index));
-}
-
-template<typename T>
+inline const T& TNode::ChildAs(const TStringBuf key) const {
+ const auto& node = At(key);
+ try {
+ return node.As<T>();
+ } catch (TTypeError& e) {
+ e << ", during getting key=" << key;
+ throw e;
+ } catch (...) {
+ ythrow TTypeError() << CurrentExceptionMessage() << ", during getting key=" << key;
+ }
+}
+
+template<typename T>
+inline const T& TNode::ChildAs(size_t index) const {
+ const auto& node = At(index);
+ try {
+ return node.As<T>();
+ } catch (TTypeError& e) {
+ e << ", during getting index=" << index;
+ throw e;
+ } catch (...) {
+ ythrow TTypeError() << CurrentExceptionMessage() << ", during getting index=" << index;
+ }
+}
+
+template<typename T>
+inline T& TNode::ChildAs(const TStringBuf key) {
+ return const_cast<T&>(static_cast<const TNode*>(this)->ChildAs<T>(key));
+}
+
+template<typename T>
+inline T& TNode::ChildAs(size_t index) {
+ return const_cast<T&>(static_cast<const TNode*>(this)->ChildAs<T>(index));
+}
+
+template<typename T>
inline bool TNode::IsOfType() const noexcept {
return std::holds_alternative<T>(Value_);
}
diff --git a/library/cpp/yson/node/node_ut.cpp b/library/cpp/yson/node/node_ut.cpp
index 7e081e1afb..448e99f575 100644
--- a/library/cpp/yson/node/node_ut.cpp
+++ b/library/cpp/yson/node/node_ut.cpp
@@ -414,34 +414,34 @@ Y_UNIT_TEST_SUITE(YtNodeTest) {
("double", -3.5)
("list", TNode::CreateList().Add(5))
("map", TNode::CreateMap()("key", "value"));
-
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TString>("string"), "7");
+
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TString>("string"), "7");
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsString("string"), "7");
UNIT_ASSERT_VALUES_EQUAL(node.ChildConvertTo<i64>("string"), 7);
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<i64>("int64"), 3);
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<i64>("int64"), 3);
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsInt64("int64"), 3);
UNIT_ASSERT_VALUES_EQUAL(node.ChildIntCast<ui64>("int64"), 3u);
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<ui64>("uint64"), 5u);
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<ui64>("uint64"), 5u);
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsUint64("uint64"), 5u);
UNIT_ASSERT_VALUES_EQUAL(node.ChildIntCast<i64>("uint64"), 5);
UNIT_ASSERT_VALUES_EQUAL(node.ChildConvertTo<TString>("uint64"), "5");
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<double>("double"), -3.5);
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<double>("double"), -3.5);
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsDouble("double"), -3.5);
UNIT_ASSERT_VALUES_EQUAL(node.ChildConvertTo<TString>("double"), "-3.5");
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TNode::TListType>("list")[0].AsInt64(), 5);
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TNode::TListType>("list")[0].AsInt64(), 5);
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsList("list")[0].AsInt64(), 5);
-
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TNode::TMapType>("map")["key"].AsString(), "value");
+
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TNode::TMapType>("map")["key"].AsString(), "value");
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsMap("map")["key"].AsString(), "value");
-
- // mutable accessor
- auto& childString = node.ChildAs<TString>("string");
- childString = "yaddayadda";
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TString>("string"), "yaddayadda");
+
+ // mutable accessor
+ auto& childString = node.ChildAs<TString>("string");
+ childString = "yaddayadda";
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TString>("string"), "yaddayadda");
}
Y_UNIT_TEST(TestListGetters) {
@@ -452,33 +452,33 @@ Y_UNIT_TEST_SUITE(YtNodeTest) {
.Add(-3.5)
.Add(TNode::CreateList().Add(5))
.Add(TNode::CreateMap()("key", "value"));
-
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TString>(0), "7");
+
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TString>(0), "7");
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsString(0), "7");
UNIT_ASSERT_VALUES_EQUAL(node.ChildConvertTo<i64>(0), 7);
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<i64>(1), 3);
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<i64>(1), 3);
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsInt64(1), 3);
UNIT_ASSERT_VALUES_EQUAL(node.ChildIntCast<ui64>(1), 3u);
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<ui64>(2), 5u);
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<ui64>(2), 5u);
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsUint64(2), 5u);
UNIT_ASSERT_VALUES_EQUAL(node.ChildIntCast<i64>(2), 5);
UNIT_ASSERT_VALUES_EQUAL(node.ChildConvertTo<TString>(2), "5");
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<double>(3), -3.5);
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<double>(3), -3.5);
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsDouble(3), -3.5);
UNIT_ASSERT_VALUES_EQUAL(node.ChildConvertTo<TString>(3), "-3.5");
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TNode::TListType>(4)[0].AsInt64(), 5);
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TNode::TListType>(4)[0].AsInt64(), 5);
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsList(4)[0].AsInt64(), 5);
-
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TNode::TMapType>(5)["key"].AsString(), "value");
+
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TNode::TMapType>(5)["key"].AsString(), "value");
UNIT_ASSERT_VALUES_EQUAL(node.ChildAsMap(5)["key"].AsString(), "value");
-
- // mutable accessor
- auto& childString = node.ChildAs<TString>(0);
- childString = "yaddayadda";
- UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TString>(0), "yaddayadda");
+
+ // mutable accessor
+ auto& childString = node.ChildAs<TString>(0);
+ childString = "yaddayadda";
+ UNIT_ASSERT_VALUES_EQUAL(node.ChildAs<TString>(0), "yaddayadda");
}
}
diff --git a/library/cpp/yson_pull/bridge.h b/library/cpp/yson_pull/bridge.h
index db3806d3d3..ac767dcba0 100644
--- a/library/cpp/yson_pull/bridge.h
+++ b/library/cpp/yson_pull/bridge.h
@@ -1,34 +1,34 @@
-#pragma once
-
-#include "consumer.h"
-#include "event.h"
-#include "writer.h"
-
-namespace NYsonPull {
+#pragma once
+
+#include "consumer.h"
+#include "event.h"
+#include "writer.h"
+
+namespace NYsonPull {
//! \brief Connect YSON stream producer and consumer.
//!
//! Useful for writing YSON stream filters.
//! \p Producer must have a \p next_event() method (like \p NYsonPull::reader).
//! \p Consumer must be like \p NYsonPull::consumer interface.
template <typename Producer, typename Consumer>
- inline void Bridge(Producer&& producer, Consumer&& consumer) {
+ inline void Bridge(Producer&& producer, Consumer&& consumer) {
for (;;) {
- auto& event = producer.NextEvent();
- consumer.OnEvent(event);
- if (event.Type() == EEventType::EndStream) {
+ auto& event = producer.NextEvent();
+ consumer.OnEvent(event);
+ if (event.Type() == EEventType::EndStream) {
break;
}
- }
- }
-
+ }
+ }
+
template <typename Producer>
- inline void Bridge(Producer&& producer, TWriter& writer_) {
- Bridge(std::forward<Producer>(producer), writer_.GetConsumer());
+ inline void Bridge(Producer&& producer, TWriter& writer_) {
+ Bridge(std::forward<Producer>(producer), writer_.GetConsumer());
}
-
+
template <typename Producer>
- inline void Bridge(Producer&& producer, TWriter&& writer_) {
- Bridge(std::forward<Producer>(producer), writer_.GetConsumer());
+ inline void Bridge(Producer&& producer, TWriter&& writer_) {
+ Bridge(std::forward<Producer>(producer), writer_.GetConsumer());
}
-
+
}
diff --git a/library/cpp/yson_pull/buffer.h b/library/cpp/yson_pull/buffer.h
index 1ab75c6bc5..04c9220ef3 100644
--- a/library/cpp/yson_pull/buffer.h
+++ b/library/cpp/yson_pull/buffer.h
@@ -1,11 +1,11 @@
-#pragma once
-
-#include <util/system/types.h>
-#include <util/system/yassert.h>
-
-#include <cstddef>
-
-namespace NYsonPull {
+#pragma once
+
+#include <util/system/types.h>
+#include <util/system/yassert.h>
+
+#include <cstddef>
+
+namespace NYsonPull {
//! \brief A non-owning buffer model.
//!
//! Represents a \p pos pointer moving between \p begin and \p end.
@@ -14,7 +14,7 @@ namespace NYsonPull {
T* begin_ = nullptr;
T* pos_ = nullptr;
T* end_ = nullptr;
-
+
public:
T* begin() const noexcept {
return begin_;
@@ -25,49 +25,49 @@ namespace NYsonPull {
T* end() const noexcept {
return end_;
}
-
+
//! \brief Amount of data after current position.
size_t available() const noexcept {
return end_ - pos_;
}
-
+
//! \brief Amount of data before current position.
size_t used() const noexcept {
return pos_ - begin_;
}
-
+
//! \brief Move current position \p nbytes forward.
void advance(size_t nbytes) noexcept {
Y_ASSERT(pos_ + nbytes <= end_);
pos_ += nbytes;
}
-
+
//! \brief Reset buffer pointers.
void reset(T* new_begin, T* new_end, T* new_pos) {
begin_ = new_begin;
pos_ = new_pos;
end_ = new_end;
}
-
+
//! \brief Reset buffer to beginning
void reset(T* new_begin, T* new_end) {
reset(new_begin, new_end, new_begin);
}
};
-
+
class output_buffer: public buffer<ui8> {
public:
//! \brief An output buffer is empty when there is no data written to it.
bool is_empty() const noexcept {
return pos() == begin();
}
-
+
//! \brief An output buffer is full when there is no space to write more data to it.
bool is_full() const noexcept {
return pos() == end();
}
};
-
+
class input_buffer: public buffer<const ui8> {
public:
//! An input stream is empty when there is no data to read in it.
@@ -75,5 +75,5 @@ namespace NYsonPull {
return pos() == end();
}
};
-
+
}
diff --git a/library/cpp/yson_pull/consumer.cpp b/library/cpp/yson_pull/consumer.cpp
index a12d3358cd..c238e0a6fb 100644
--- a/library/cpp/yson_pull/consumer.cpp
+++ b/library/cpp/yson_pull/consumer.cpp
@@ -1,83 +1,83 @@
-#include "consumer.h"
-
+#include "consumer.h"
+
#include <library/cpp/yson_pull/detail/macros.h>
-
-using namespace NYsonPull;
-
-void IConsumer::OnScalar(const TScalar& value) {
- switch (value.Type()) {
- case EScalarType::Entity:
- OnEntity();
- break;
-
- case EScalarType::Boolean:
- OnScalarBoolean(value.AsBoolean());
- break;
-
- case EScalarType::Int64:
- OnScalarInt64(value.AsInt64());
- break;
-
- case EScalarType::UInt64:
- OnScalarUInt64(value.AsUInt64());
- break;
-
- case EScalarType::Float64:
- OnScalarFloat64(value.AsFloat64());
- break;
-
- case EScalarType::String:
- OnScalarString(value.AsString());
- break;
-
+
+using namespace NYsonPull;
+
+void IConsumer::OnScalar(const TScalar& value) {
+ switch (value.Type()) {
+ case EScalarType::Entity:
+ OnEntity();
+ break;
+
+ case EScalarType::Boolean:
+ OnScalarBoolean(value.AsBoolean());
+ break;
+
+ case EScalarType::Int64:
+ OnScalarInt64(value.AsInt64());
+ break;
+
+ case EScalarType::UInt64:
+ OnScalarUInt64(value.AsUInt64());
+ break;
+
+ case EScalarType::Float64:
+ OnScalarFloat64(value.AsFloat64());
+ break;
+
+ case EScalarType::String:
+ OnScalarString(value.AsString());
+ break;
+
default:
- Y_UNREACHABLE();
- }
-}
-
-void IConsumer::OnEvent(const TEvent& value) {
- switch (value.Type()) {
- case EEventType::BeginStream:
- OnBeginStream();
- break;
-
- case EEventType::EndStream:
- OnEndStream();
- break;
-
- case EEventType::BeginList:
- OnBeginList();
- break;
-
- case EEventType::EndList:
- OnEndList();
- break;
-
- case EEventType::BeginMap:
- OnBeginMap();
- break;
-
- case EEventType::Key:
- OnKey(value.AsString());
- break;
-
- case EEventType::EndMap:
- OnEndMap();
- break;
-
- case EEventType::BeginAttributes:
- OnBeginAttributes();
- break;
-
- case EEventType::EndAttributes:
- OnEndAttributes();
- break;
-
- case EEventType::Scalar:
- OnScalar(value.AsScalar());
- break;
-
+ Y_UNREACHABLE();
+ }
+}
+
+void IConsumer::OnEvent(const TEvent& value) {
+ switch (value.Type()) {
+ case EEventType::BeginStream:
+ OnBeginStream();
+ break;
+
+ case EEventType::EndStream:
+ OnEndStream();
+ break;
+
+ case EEventType::BeginList:
+ OnBeginList();
+ break;
+
+ case EEventType::EndList:
+ OnEndList();
+ break;
+
+ case EEventType::BeginMap:
+ OnBeginMap();
+ break;
+
+ case EEventType::Key:
+ OnKey(value.AsString());
+ break;
+
+ case EEventType::EndMap:
+ OnEndMap();
+ break;
+
+ case EEventType::BeginAttributes:
+ OnBeginAttributes();
+ break;
+
+ case EEventType::EndAttributes:
+ OnEndAttributes();
+ break;
+
+ case EEventType::Scalar:
+ OnScalar(value.AsScalar());
+ break;
+
default:
- Y_UNREACHABLE();
- }
-}
+ Y_UNREACHABLE();
+ }
+}
diff --git a/library/cpp/yson_pull/consumer.h b/library/cpp/yson_pull/consumer.h
index 943e744cc7..f3b1398d4c 100644
--- a/library/cpp/yson_pull/consumer.h
+++ b/library/cpp/yson_pull/consumer.h
@@ -1,37 +1,37 @@
-#pragma once
-
-#include "event.h"
-
-#include <util/generic/strbuf.h>
+#pragma once
+
+#include "event.h"
+
+#include <util/generic/strbuf.h>
#include <util/system/types.h>
-
-namespace NYsonPull {
+
+namespace NYsonPull {
class IConsumer {
public:
virtual ~IConsumer() = default;
-
- virtual void OnBeginStream() = 0;
- virtual void OnEndStream() = 0;
-
- virtual void OnBeginList() = 0;
- virtual void OnEndList() = 0;
-
- virtual void OnBeginMap() = 0;
- virtual void OnEndMap() = 0;
-
- virtual void OnBeginAttributes() = 0;
- virtual void OnEndAttributes() = 0;
-
- virtual void OnKey(TStringBuf name) = 0;
-
- virtual void OnEntity() = 0;
- virtual void OnScalarBoolean(bool value) = 0;
- virtual void OnScalarInt64(i64 value) = 0;
- virtual void OnScalarUInt64(ui64 value) = 0;
- virtual void OnScalarFloat64(double value) = 0;
- virtual void OnScalarString(TStringBuf value) = 0;
-
- virtual void OnScalar(const TScalar& value);
- virtual void OnEvent(const TEvent& value);
+
+ virtual void OnBeginStream() = 0;
+ virtual void OnEndStream() = 0;
+
+ virtual void OnBeginList() = 0;
+ virtual void OnEndList() = 0;
+
+ virtual void OnBeginMap() = 0;
+ virtual void OnEndMap() = 0;
+
+ virtual void OnBeginAttributes() = 0;
+ virtual void OnEndAttributes() = 0;
+
+ virtual void OnKey(TStringBuf name) = 0;
+
+ virtual void OnEntity() = 0;
+ virtual void OnScalarBoolean(bool value) = 0;
+ virtual void OnScalarInt64(i64 value) = 0;
+ virtual void OnScalarUInt64(ui64 value) = 0;
+ virtual void OnScalarFloat64(double value) = 0;
+ virtual void OnScalarString(TStringBuf value) = 0;
+
+ virtual void OnScalar(const TScalar& value);
+ virtual void OnEvent(const TEvent& value);
};
}
diff --git a/library/cpp/yson_pull/cyson_enums.h b/library/cpp/yson_pull/cyson_enums.h
index e1b8dffeeb..315de97307 100644
--- a/library/cpp/yson_pull/cyson_enums.h
+++ b/library/cpp/yson_pull/cyson_enums.h
@@ -1,47 +1,47 @@
-#pragma once
-
-typedef enum yson_event_type {
- YSON_EVENT_BEGIN_STREAM = 0,
- YSON_EVENT_END_STREAM = 1,
- YSON_EVENT_BEGIN_LIST = 2,
- YSON_EVENT_END_LIST = 3,
- YSON_EVENT_BEGIN_MAP = 4,
- YSON_EVENT_END_MAP = 5,
- YSON_EVENT_BEGIN_ATTRIBUTES = 6,
- YSON_EVENT_END_ATTRIBUTES = 7,
- YSON_EVENT_KEY = 8,
- YSON_EVENT_SCALAR = 9,
- YSON_EVENT_ERROR = 10
-} yson_event_type;
-
-typedef enum yson_scalar_type {
- YSON_SCALAR_ENTITY = 0,
- YSON_SCALAR_BOOLEAN = 1,
- YSON_SCALAR_INT64 = 2,
- YSON_SCALAR_UINT64 = 3,
- YSON_SCALAR_FLOAT64 = 4,
- YSON_SCALAR_STRING = 5
-} yson_scalar_type;
-
-typedef enum yson_input_stream_result {
- YSON_INPUT_STREAM_RESULT_OK = 0,
- YSON_INPUT_STREAM_RESULT_EOF = 1,
- YSON_INPUT_STREAM_RESULT_ERROR = 2
-} yson_input_stream_result;
-
-typedef enum yson_output_stream_result {
- YSON_OUTPUT_STREAM_RESULT_OK = 0,
- YSON_OUTPUT_STREAM_RESULT_ERROR = 1
-} yson_output_stream_result;
-
-typedef enum yson_writer_result {
- YSON_WRITER_RESULT_OK = 0,
- YSON_WRITER_RESULT_BAD_STREAM = 1,
- YSON_WRITER_RESULT_ERROR = 2
-} yson_writer_result;
-
-typedef enum yson_stream_type {
- YSON_STREAM_TYPE_NODE = 0,
- YSON_STREAM_TYPE_LIST_FRAGMENT = 1,
- YSON_STREAM_TYPE_MAP_FRAGMENT = 2
-} yson_stream_type;
+#pragma once
+
+typedef enum yson_event_type {
+ YSON_EVENT_BEGIN_STREAM = 0,
+ YSON_EVENT_END_STREAM = 1,
+ YSON_EVENT_BEGIN_LIST = 2,
+ YSON_EVENT_END_LIST = 3,
+ YSON_EVENT_BEGIN_MAP = 4,
+ YSON_EVENT_END_MAP = 5,
+ YSON_EVENT_BEGIN_ATTRIBUTES = 6,
+ YSON_EVENT_END_ATTRIBUTES = 7,
+ YSON_EVENT_KEY = 8,
+ YSON_EVENT_SCALAR = 9,
+ YSON_EVENT_ERROR = 10
+} yson_event_type;
+
+typedef enum yson_scalar_type {
+ YSON_SCALAR_ENTITY = 0,
+ YSON_SCALAR_BOOLEAN = 1,
+ YSON_SCALAR_INT64 = 2,
+ YSON_SCALAR_UINT64 = 3,
+ YSON_SCALAR_FLOAT64 = 4,
+ YSON_SCALAR_STRING = 5
+} yson_scalar_type;
+
+typedef enum yson_input_stream_result {
+ YSON_INPUT_STREAM_RESULT_OK = 0,
+ YSON_INPUT_STREAM_RESULT_EOF = 1,
+ YSON_INPUT_STREAM_RESULT_ERROR = 2
+} yson_input_stream_result;
+
+typedef enum yson_output_stream_result {
+ YSON_OUTPUT_STREAM_RESULT_OK = 0,
+ YSON_OUTPUT_STREAM_RESULT_ERROR = 1
+} yson_output_stream_result;
+
+typedef enum yson_writer_result {
+ YSON_WRITER_RESULT_OK = 0,
+ YSON_WRITER_RESULT_BAD_STREAM = 1,
+ YSON_WRITER_RESULT_ERROR = 2
+} yson_writer_result;
+
+typedef enum yson_stream_type {
+ YSON_STREAM_TYPE_NODE = 0,
+ YSON_STREAM_TYPE_LIST_FRAGMENT = 1,
+ YSON_STREAM_TYPE_MAP_FRAGMENT = 2
+} yson_stream_type;
diff --git a/library/cpp/yson_pull/detail/byte_reader.h b/library/cpp/yson_pull/detail/byte_reader.h
index 36ffe8446b..7cea50d323 100644
--- a/library/cpp/yson_pull/detail/byte_reader.h
+++ b/library/cpp/yson_pull/detail/byte_reader.h
@@ -1,29 +1,29 @@
-#pragma once
-
-#include "cescape.h"
-#include "fail.h"
-#include "stream_counter.h"
-
+#pragma once
+
+#include "cescape.h"
+#include "fail.h"
+#include "stream_counter.h"
+
#include <library/cpp/yson_pull/input.h>
-
+
namespace NYsonPull {
namespace NDetail {
template <class StreamCounter>
class byte_reader {
NYsonPull::NInput::IStream& stream_;
StreamCounter stream_counter_;
-
+
public:
byte_reader(NYsonPull::NInput::IStream& stream)
: stream_(stream)
{
}
-
+
// const-ness added to prevent direct stream mutation
const NYsonPull::NInput::IStream& stream() {
return stream_;
}
-
+
template <typename... Args>
ATTRIBUTE(noinline, cold)
void fail[[noreturn]](const char* msg, Args&&... args) {
@@ -32,23 +32,23 @@ namespace NYsonPull {
msg,
std::forward<Args>(args)...);
}
-
+
template <bool AllowFinish>
void fill_buffer() {
stream_.fill_buffer();
-
+
if (!AllowFinish) {
auto& buf = stream_.buffer();
- if (Y_UNLIKELY(buf.is_empty() && stream_.at_end())) {
+ if (Y_UNLIKELY(buf.is_empty() && stream_.at_end())) {
fail("Premature end of stream");
}
}
}
-
+
void fill_buffer() {
return fill_buffer<true>();
- }
-
+ }
+
template <bool AllowFinish>
ui8 get_byte() {
fill_buffer<AllowFinish>();
@@ -57,11 +57,11 @@ namespace NYsonPull {
? *buf.pos()
: ui8{'\0'};
}
-
+
ui8 get_byte() {
return get_byte<true>();
}
-
+
void advance(size_t bytes) {
auto& buf = stream_.buffer();
stream_counter_.update(
@@ -70,5 +70,5 @@ namespace NYsonPull {
buf.advance(bytes);
}
};
- }
+ }
}
diff --git a/library/cpp/yson_pull/detail/byte_writer.h b/library/cpp/yson_pull/detail/byte_writer.h
index 71ffe6230b..dc1d4b4b96 100644
--- a/library/cpp/yson_pull/detail/byte_writer.h
+++ b/library/cpp/yson_pull/detail/byte_writer.h
@@ -1,27 +1,27 @@
-#pragma once
-
-#include "macros.h"
-
+#pragma once
+
+#include "macros.h"
+
#include <library/cpp/yson_pull/output.h>
-
-#include <util/system/types.h>
-
-#include <cstddef>
-#include <cstring>
-
+
+#include <util/system/types.h>
+
+#include <cstddef>
+#include <cstring>
+
namespace NYsonPull {
namespace NDetail {
template <class StreamCounter>
class byte_writer {
NYsonPull::NOutput::IStream& stream_;
StreamCounter stream_counter_;
-
+
public:
byte_writer(NYsonPull::NOutput::IStream& stream)
: stream_(stream)
{
}
-
+
// const-ness added to prevent direct stream mutation
const NYsonPull::NOutput::IStream& stream() {
return stream_;
@@ -29,11 +29,11 @@ namespace NYsonPull {
const StreamCounter& counter() {
return stream_counter_;
}
-
+
void flush_buffer() {
stream_.flush_buffer();
}
-
+
void advance(size_t bytes) {
auto& buf = stream_.buffer();
stream_counter_.update(
@@ -41,10 +41,10 @@ namespace NYsonPull {
buf.pos() + bytes);
buf.advance(bytes);
}
-
+
void write(ui8 c) {
auto& buf = stream_.buffer();
- if (Y_LIKELY(!buf.is_full())) {
+ if (Y_LIKELY(!buf.is_full())) {
*buf.pos() = c;
advance(1);
} else {
@@ -53,11 +53,11 @@ namespace NYsonPull {
stream_.flush_buffer({ptr, 1});
}
}
-
+
void write(const ui8* data, size_t size) {
auto& buf = stream_.buffer();
auto free_buf = buf.available();
- if (Y_LIKELY(size < free_buf)) {
+ if (Y_LIKELY(size < free_buf)) {
::memcpy(buf.pos(), data, size);
advance(size);
} else {
@@ -71,7 +71,7 @@ namespace NYsonPull {
stream_.flush_buffer({reinterpret_cast<const char*>(data),
size});
}
- }
+ }
};
- }
+ }
}
diff --git a/library/cpp/yson_pull/detail/cescape.h b/library/cpp/yson_pull/detail/cescape.h
index 2e468fc0f3..1ea150e69a 100644
--- a/library/cpp/yson_pull/detail/cescape.h
+++ b/library/cpp/yson_pull/detail/cescape.h
@@ -1,40 +1,40 @@
-#pragma once
-
-#include "byte_writer.h"
-#include "cescape_decode.h"
-#include "cescape_encode.h"
-#include "macros.h"
-
-#include <util/generic/strbuf.h>
+#pragma once
+
+#include "byte_writer.h"
+#include "cescape_decode.h"
+#include "cescape_encode.h"
+#include "macros.h"
+
+#include <util/generic/strbuf.h>
#include <util/generic/string.h>
-#include <util/generic/vector.h>
-
-/* REFERENCES FOR ESCAPE SEQUENCE INTERPRETATION:
- * C99 p. 6.4.3 Universal character names.
- * C99 p. 6.4.4.4 Character constants.
- *
- * <simple-escape-sequence> ::= {
- * \' , \" , \? , \\ ,
- * \a , \b , \f , \n , \r , \t , \v
- * }
- *
- * <octal-escape-sequence> ::= \ <octal-digit> {1, 3}
- * <hexadecimal-escape-sequence> ::= \x <hexadecimal-digit> +
- * <universal-character-name> ::= \u <hexadecimal-digit> {4}
- * || \U <hexadecimal-digit> {8}
- *
- * NOTE (6.4.4.4.7):
- * Each octal or hexadecimal escape sequence is the longest sequence of characters that can
- * constitute the escape sequence.
- *
- * THEREFORE:
- * - Octal escape sequence spans until rightmost non-octal-digit character.
- * - Octal escape sequence always terminates after three octal digits.
- * - Hexadecimal escape sequence spans until rightmost non-hexadecimal-digit character.
- * - Universal character name consists of exactly 4 or 8 hexadecimal digit.
- *
- */
-
+#include <util/generic/vector.h>
+
+/* REFERENCES FOR ESCAPE SEQUENCE INTERPRETATION:
+ * C99 p. 6.4.3 Universal character names.
+ * C99 p. 6.4.4.4 Character constants.
+ *
+ * <simple-escape-sequence> ::= {
+ * \' , \" , \? , \\ ,
+ * \a , \b , \f , \n , \r , \t , \v
+ * }
+ *
+ * <octal-escape-sequence> ::= \ <octal-digit> {1, 3}
+ * <hexadecimal-escape-sequence> ::= \x <hexadecimal-digit> +
+ * <universal-character-name> ::= \u <hexadecimal-digit> {4}
+ * || \U <hexadecimal-digit> {8}
+ *
+ * NOTE (6.4.4.4.7):
+ * Each octal or hexadecimal escape sequence is the longest sequence of characters that can
+ * constitute the escape sequence.
+ *
+ * THEREFORE:
+ * - Octal escape sequence spans until rightmost non-octal-digit character.
+ * - Octal escape sequence always terminates after three octal digits.
+ * - Hexadecimal escape sequence spans until rightmost non-hexadecimal-digit character.
+ * - Universal character name consists of exactly 4 or 8 hexadecimal digit.
+ *
+ */
+
namespace NYsonPull {
namespace NDetail {
namespace NCEscape {
@@ -48,7 +48,7 @@ namespace NYsonPull {
size);
});
}
-
+
// dest must have at least 4*data.size() bytes available
inline size_t encode(ui8* dest, TStringBuf data) {
auto* dest_begin = dest;
@@ -61,11 +61,11 @@ namespace NYsonPull {
});
return dest - dest_begin;
}
-
+
template <typename U>
void encode(byte_writer<U>& dest, TStringBuf data) {
auto& buffer = dest.stream().buffer();
- if (Y_LIKELY(buffer.available() >= data.size() * 4)) {
+ if (Y_LIKELY(buffer.available() >= data.size() * 4)) {
auto size = encode(buffer.pos(), data);
dest.advance(size);
} else {
@@ -77,14 +77,14 @@ namespace NYsonPull {
});
}
}
-
+
inline TString encode(TStringBuf data) {
TString result;
result.reserve(data.size());
encode(result, data);
return result;
- }
-
+ }
+
inline void decode(TString& dest, TStringBuf data) {
NImpl::unescape_impl(
reinterpret_cast<const ui8*>(data.begin()),
@@ -96,7 +96,7 @@ namespace NYsonPull {
dest.append(reinterpret_cast<const char*>(p), len);
});
}
-
+
inline void decode_inplace(TVector<ui8>& data) {
auto* out = static_cast<ui8*>(
::memchr(data.data(), '\\', data.size()));
@@ -115,14 +115,14 @@ namespace NYsonPull {
});
data.resize(out - &data[0]);
}
-
+
inline TString decode(TStringBuf data) {
TString result;
result.reserve(data.size());
decode(result, data);
return result;
}
-
+
ATTRIBUTE(noinline, cold)
inline TString quote(TStringBuf str) {
TString result;
@@ -132,7 +132,7 @@ namespace NYsonPull {
result += '"';
return result;
}
-
+
ATTRIBUTE(noinline, cold)
inline TString quote(ui8 ch) {
char c = ch;
diff --git a/library/cpp/yson_pull/detail/cescape_decode.h b/library/cpp/yson_pull/detail/cescape_decode.h
index 377112924b..2ee5dd9500 100644
--- a/library/cpp/yson_pull/detail/cescape_decode.h
+++ b/library/cpp/yson_pull/detail/cescape_decode.h
@@ -1,10 +1,10 @@
-#pragma once
-
-#include <util/system/types.h>
-
-#include <algorithm>
-#include <cstring>
-
+#pragma once
+
+#include <util/system/types.h>
+
+#include <algorithm>
+#include <cstring>
+
namespace NYsonPull {
namespace NDetail {
namespace NCEscape {
@@ -12,7 +12,7 @@ namespace NYsonPull {
inline ui8 as_digit(ui8 c) {
return c - ui8{'0'};
}
-
+
inline ui8 as_hexdigit(ui8 c) {
static constexpr ui8 hex_decode_map[256] = {
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
@@ -37,10 +37,10 @@ namespace NYsonPull {
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255};
-
+
return hex_decode_map[c];
}
-
+
inline const ui8* read_oct(ui8& result, const ui8* p, ui8 n) {
auto digit = ui8{0};
while (n-- && (digit = as_digit(*p)) < 8) {
@@ -49,7 +49,7 @@ namespace NYsonPull {
}
return p;
}
-
+
inline const ui8* read_hex(ui8& result, const ui8* p, ui8 n) {
auto digit = ui8{0};
while (n-- && (digit = as_hexdigit(*p)) < 16) {
@@ -58,7 +58,7 @@ namespace NYsonPull {
}
return p;
}
-
+
inline const ui8* unescape_char_and_advance(
ui8& result,
const ui8* p,
@@ -88,7 +88,7 @@ namespace NYsonPull {
result = '\t';
++p;
break;
-
+
case 'x': {
++p;
result = 0;
@@ -101,7 +101,7 @@ namespace NYsonPull {
result = 'x';
}
} break;
-
+
case '0':
case '1':
case '2':
@@ -111,7 +111,7 @@ namespace NYsonPull {
result,
p, std::min<ptrdiff_t>(3, end - p));
break;
-
+
case '4':
case '5':
case '6':
@@ -124,7 +124,7 @@ namespace NYsonPull {
}
return p;
}
-
+
template <typename T, typename U>
inline void unescape_impl(
const ui8* p,
@@ -148,7 +148,7 @@ namespace NYsonPull {
}
}
}
- }
+ }
} // namespace NCEscape
} // namespace NDetail
}
diff --git a/library/cpp/yson_pull/detail/cescape_encode.h b/library/cpp/yson_pull/detail/cescape_encode.h
index bf9a44ba5f..bf5765f1d9 100644
--- a/library/cpp/yson_pull/detail/cescape_encode.h
+++ b/library/cpp/yson_pull/detail/cescape_encode.h
@@ -1,11 +1,11 @@
-#pragma once
-
+#pragma once
+
#include <util/system/types.h>
-
-// Whether to ensure strict ASCII compatibility
-// Turns UTF-8 strings into unreadable garbage for no known reason
-//#define CESCAPE_STRICT_ASCII
-
+
+// Whether to ensure strict ASCII compatibility
+// Turns UTF-8 strings into unreadable garbage for no known reason
+//#define CESCAPE_STRICT_ASCII
+
namespace NYsonPull {
namespace NDetail {
namespace NCEscape {
@@ -14,29 +14,29 @@ namespace NYsonPull {
constexpr ui8 hex_digits[] = "0123456789ABCDEF";
return hex_digits[value];
}
-
+
inline ui8 oct_digit(ui8 value) {
return '0' + value;
}
-
+
inline bool is_printable(ui8 c) {
-#ifdef CESCAPE_STRICT_ASCII
+#ifdef CESCAPE_STRICT_ASCII
return c >= 32 && c <= 126;
-#else
+#else
return c >= 32;
-#endif
+#endif
}
-
+
inline bool is_hex_digit(ui8 c) {
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f');
}
-
+
inline bool is_oct_digit(ui8 c) {
return c >= '0' && c <= '7';
}
-
+
constexpr size_t ESCAPE_C_BUFFER_SIZE = 4;
-
+
inline size_t escape_char(
ui8 c,
ui8 next,
@@ -85,16 +85,16 @@ namespace NYsonPull {
return 4;
}
}
-
+
template <typename T>
inline void escape_impl(const ui8* str, size_t len, T&& consume) {
ui8 buffer[ESCAPE_C_BUFFER_SIZE];
-
+
size_t i, j;
for (i = 0, j = 0; i < len; ++i) {
auto next_char = i + 1 < len ? str[i + 1] : 0;
size_t rlen = escape_char(str[i], next_char, buffer);
-
+
if (rlen > 1) {
consume(str + j, i - j);
j = i + 1;
diff --git a/library/cpp/yson_pull/detail/fail.h b/library/cpp/yson_pull/detail/fail.h
index a140f34c91..6937612d0b 100644
--- a/library/cpp/yson_pull/detail/fail.h
+++ b/library/cpp/yson_pull/detail/fail.h
@@ -1,11 +1,11 @@
-#pragma once
-
-#include "format_string.h"
-#include "macros.h"
-
+#pragma once
+
+#include "format_string.h"
+#include "macros.h"
+
#include <library/cpp/yson_pull/exceptions.h>
#include <library/cpp/yson_pull/position_info.h>
-
+
namespace NYsonPull {
namespace NDetail {
template <typename... Args>
diff --git a/library/cpp/yson_pull/detail/format_string.h b/library/cpp/yson_pull/detail/format_string.h
index 7413beb6f1..683fd1bf36 100644
--- a/library/cpp/yson_pull/detail/format_string.h
+++ b/library/cpp/yson_pull/detail/format_string.h
@@ -1,26 +1,26 @@
-#pragma once
-
-#include <util/generic/strbuf.h>
+#pragma once
+
+#include <util/generic/strbuf.h>
#include <util/generic/string.h>
-#include <util/string/builder.h>
-
+#include <util/string/builder.h>
+
namespace NYsonPull {
namespace NDetail {
namespace NImpl {
inline void apply_args(TStringBuilder&) {
}
-
+
template <typename T, typename... Args>
inline void apply_args(TStringBuilder& builder, T&& arg, Args&&... args) {
apply_args(builder << arg, std::forward<Args>(args)...);
}
}
-
+
template <typename... Args>
TString format_string(Args&&... args) {
TStringBuilder builder;
NImpl::apply_args(builder, std::forward<Args>(args)...);
return TString(std::move(builder));
}
- }
+ }
}
diff --git a/library/cpp/yson_pull/detail/input/buffered.h b/library/cpp/yson_pull/detail/input/buffered.h
index fef577df8b..9b1482577f 100644
--- a/library/cpp/yson_pull/detail/input/buffered.h
+++ b/library/cpp/yson_pull/detail/input/buffered.h
@@ -1,31 +1,31 @@
-#pragma once
-
+#pragma once
+
#include <library/cpp/yson_pull/detail/macros.h>
-
+
#include <library/cpp/yson_pull/exceptions.h>
#include <library/cpp/yson_pull/input.h>
-
-#include <cstdio>
-#include <memory>
-
+
+#include <cstdio>
+#include <memory>
+
namespace NYsonPull {
namespace NDetail {
namespace NInput {
class TBuffered: public NYsonPull::NInput::IStream {
TArrayHolder<ui8> buffer_;
size_t size_;
-
+
public:
explicit TBuffered(size_t buffer_size)
: buffer_{new ui8[buffer_size]}
, size_{buffer_size} {
}
-
+
protected:
ui8* buffer_data() const {
return buffer_.Get();
}
-
+
size_t buffer_size() const {
return size_;
}
diff --git a/library/cpp/yson_pull/detail/input/stdio_file.h b/library/cpp/yson_pull/detail/input/stdio_file.h
index 328931d435..c412b7e59b 100644
--- a/library/cpp/yson_pull/detail/input/stdio_file.h
+++ b/library/cpp/yson_pull/detail/input/stdio_file.h
@@ -1,35 +1,35 @@
-#pragma once
-
-#include "buffered.h"
-
+#pragma once
+
+#include "buffered.h"
+
#include <library/cpp/yson_pull/detail/macros.h>
-
+
#include <library/cpp/yson_pull/exceptions.h>
#include <library/cpp/yson_pull/input.h>
-
-#include <cstdio>
-#include <memory>
-
+
+#include <cstdio>
+#include <memory>
+
namespace NYsonPull {
namespace NDetail {
namespace NInput {
class TStdioFile: public TBuffered {
FILE* file_;
-
+
public:
TStdioFile(FILE* file, size_t buffer_size)
: TBuffered(buffer_size)
, file_{file} {
}
-
+
protected:
result do_fill_buffer() override {
auto nread = ::fread(buffer_data(), 1, buffer_size(), file_);
- if (Y_UNLIKELY(nread == 0)) {
- if (ferror(file_)) {
+ if (Y_UNLIKELY(nread == 0)) {
+ if (ferror(file_)) {
throw NException::TSystemError();
}
- if (feof(file_)) {
+ if (feof(file_)) {
return result::at_end;
}
}
@@ -37,6 +37,6 @@ namespace NYsonPull {
return result::have_more_data;
}
};
- }
+ }
} // namespace NDetail
}
diff --git a/library/cpp/yson_pull/detail/input/stream.h b/library/cpp/yson_pull/detail/input/stream.h
index 5ed993f606..791cd5a3f5 100644
--- a/library/cpp/yson_pull/detail/input/stream.h
+++ b/library/cpp/yson_pull/detail/input/stream.h
@@ -1,69 +1,69 @@
-#pragma once
-
+#pragma once
+
#include <library/cpp/yson_pull/detail/macros.h>
-
+
#include <library/cpp/yson_pull/input.h>
-
-#include <util/stream/buffered.h>
-#include <util/stream/file.h>
-#include <util/stream/zerocopy.h>
-#include <util/system/file.h>
-
-namespace NYsonPull {
- namespace NDetail {
- namespace NInput {
- class TStreamBase: public NYsonPull::NInput::IStream {
- protected:
+
+#include <util/stream/buffered.h>
+#include <util/stream/file.h>
+#include <util/stream/zerocopy.h>
+#include <util/system/file.h>
+
+namespace NYsonPull {
+ namespace NDetail {
+ namespace NInput {
+ class TStreamBase: public NYsonPull::NInput::IStream {
+ protected:
result DoFillBufferFrom(IZeroCopyInput& input) {
- void* ptr = nullptr;
- size_t size = input.Next(&ptr);
- if (Y_UNLIKELY(size == 0)) {
- return result::at_end;
- }
- buffer().reset(static_cast<ui8*>(ptr), static_cast<ui8*>(ptr) + size);
- return result::have_more_data;
- }
- };
-
- class TZeroCopy: public TStreamBase {
+ void* ptr = nullptr;
+ size_t size = input.Next(&ptr);
+ if (Y_UNLIKELY(size == 0)) {
+ return result::at_end;
+ }
+ buffer().reset(static_cast<ui8*>(ptr), static_cast<ui8*>(ptr) + size);
+ return result::have_more_data;
+ }
+ };
+
+ class TZeroCopy: public TStreamBase {
IZeroCopyInput* Input;
-
- public:
+
+ public:
explicit TZeroCopy(IZeroCopyInput* input)
- : Input(input)
- {
- }
-
- protected:
- result do_fill_buffer() override {
- return DoFillBufferFrom(*Input);
- }
- };
-
+ : Input(input)
+ {
+ }
+
+ protected:
+ result do_fill_buffer() override {
+ return DoFillBufferFrom(*Input);
+ }
+ };
+
template <typename TBuffered>
- class TOwned: public TStreamBase {
- TBuffered Input;
-
- public:
+ class TOwned: public TStreamBase {
+ TBuffered Input;
+
+ public:
template <typename... Args>
- explicit TOwned(Args&&... args)
- : Input(std::forward<Args>(args)...)
- {
- }
-
- protected:
- result do_fill_buffer() override {
- return DoFillBufferFrom(Input);
- }
- };
-
+ explicit TOwned(Args&&... args)
+ : Input(std::forward<Args>(args)...)
+ {
+ }
+
+ protected:
+ result do_fill_buffer() override {
+ return DoFillBufferFrom(Input);
+ }
+ };
+
class TFHandle: public TOwned<TFileInput> {
- public:
- TFHandle(int fd, size_t buffer_size)
+ public:
+ TFHandle(int fd, size_t buffer_size)
: TOwned<TFileInput>(Duplicate(fd), buffer_size)
- {
- }
- };
- }
+ {
+ }
+ };
+ }
} // namespace NDetail
}
diff --git a/library/cpp/yson_pull/detail/lexer_base.h b/library/cpp/yson_pull/detail/lexer_base.h
index 20919e496a..572bdb3d18 100644
--- a/library/cpp/yson_pull/detail/lexer_base.h
+++ b/library/cpp/yson_pull/detail/lexer_base.h
@@ -1,27 +1,27 @@
-#pragma once
-
-#include "byte_reader.h"
-#include "cescape.h"
-#include "macros.h"
-#include "number.h"
+#pragma once
+
+#include "byte_reader.h"
+#include "cescape.h"
+#include "macros.h"
+#include "number.h"
#include "percent_scalar.h"
-#include "stream_counter.h"
-#include "varint.h"
-
-#include <util/generic/maybe.h>
-#include <util/generic/vector.h>
-#include <util/string/cast.h>
-
+#include "stream_counter.h"
+#include "varint.h"
+
+#include <util/generic/maybe.h>
+#include <util/generic/vector.h>
+#include <util/string/cast.h>
+
namespace NYsonPull {
namespace NDetail {
template <bool EnableLinePositionInfo>
class lexer_base: public byte_reader<stream_counter<EnableLinePositionInfo>> {
using Base = byte_reader<
stream_counter<EnableLinePositionInfo>>;
-
+
TVector<ui8> token_buffer_;
TMaybe<size_t> memory_limit_;
-
+
public:
lexer_base(
NYsonPull::NInput::IStream& buffer,
@@ -29,28 +29,28 @@ namespace NYsonPull {
: Base(buffer)
, memory_limit_{memory_limit} {
}
-
+
ATTRIBUTE(noinline, hot)
ui8 skip_space_and_get_byte() {
auto& buf = Base::stream().buffer();
- if (Y_LIKELY(!buf.is_empty())) {
+ if (Y_LIKELY(!buf.is_empty())) {
auto ch = *buf.pos();
- if (Y_LIKELY(!is_space(ch))) {
+ if (Y_LIKELY(!is_space(ch))) {
return ch;
}
}
return skip_space_and_get_byte_fallback();
}
-
+
ATTRIBUTE(hot)
ui8 get_byte() {
auto& buf = Base::stream().buffer();
- if (Y_LIKELY(!buf.is_empty())) {
+ if (Y_LIKELY(!buf.is_empty())) {
return *buf.pos();
}
return Base::get_byte();
- }
-
+ }
+
number read_numeric() {
token_buffer_.clear();
auto type = number_type::int64;
@@ -64,7 +64,7 @@ namespace NYsonPull {
} else if (ch == 'u') {
token_buffer_.push_back(ch);
type = number_type::uint64;
- } else if (Y_UNLIKELY(isalpha(ch))) {
+ } else if (Y_UNLIKELY(isalpha(ch))) {
COLD_BLOCK_BYVALUE
Base::fail("Unexpected ", NCEscape::quote(ch), " in numeric literal");
COLD_BLOCK_END
@@ -74,7 +74,7 @@ namespace NYsonPull {
check_memory_limit();
Base::advance(1);
}
-
+
auto str = token_buffer();
try {
switch (type) {
@@ -86,12 +86,12 @@ namespace NYsonPull {
str.Chop(1); // 'u' suffix
return FromString<ui64>(str);
}
- Y_UNREACHABLE();
+ Y_UNREACHABLE();
} catch (const std::exception& err) {
Base::fail(err.what());
}
- }
-
+ }
+
TStringBuf read_quoted_string() {
auto count_trailing_slashes = [](ui8* begin, ui8* end) {
auto count = size_t{0};
@@ -102,7 +102,7 @@ namespace NYsonPull {
}
return count;
};
-
+
token_buffer_.clear();
auto& buf = Base::stream().buffer();
while (true) {
@@ -135,12 +135,12 @@ namespace NYsonPull {
token_buffer_.push_back('"');
}
check_memory_limit();
- }
+ }
NCEscape::decode_inplace(token_buffer_);
return token_buffer();
- }
-
+ }
+
TStringBuf read_unquoted_string() {
token_buffer_.clear();
while (true) {
@@ -155,20 +155,20 @@ namespace NYsonPull {
Base::advance(1);
}
return token_buffer();
- }
-
+ }
+
ATTRIBUTE(noinline, hot)
TStringBuf read_binary_string() {
auto slength = NVarInt::read<i32>(*this);
- if (Y_UNLIKELY(slength < 0)) {
+ if (Y_UNLIKELY(slength < 0)) {
COLD_BLOCK_BYVALUE
Base::fail("Negative binary string literal length ", slength);
COLD_BLOCK_END
}
auto length = static_cast<ui32>(slength);
-
+
auto& buf = Base::stream().buffer();
- if (Y_LIKELY(buf.available() >= length)) {
+ if (Y_LIKELY(buf.available() >= length)) {
auto result = TStringBuf{
reinterpret_cast<const char*>(buf.pos()),
length};
@@ -177,8 +177,8 @@ namespace NYsonPull {
} else { // reading in Buffer
return read_binary_string_fallback(length);
}
- }
-
+ }
+
ATTRIBUTE(noinline)
TStringBuf read_binary_string_fallback(size_t length) {
auto& buf = Base::stream().buffer();
@@ -187,7 +187,7 @@ namespace NYsonPull {
while (needToRead) {
this->Base::template fill_buffer<false>();
auto chunk_size = std::min(needToRead, buf.available());
-
+
token_buffer_.insert(
token_buffer_.end(),
buf.pos(),
@@ -197,26 +197,26 @@ namespace NYsonPull {
Base::advance(chunk_size);
}
return token_buffer();
- }
-
+ }
+
percent_scalar read_percent_scalar() {
auto throw_incorrect_percent_scalar = [&]() {
Base::fail("Incorrect %-literal prefix ", NCEscape::quote(token_buffer()));
};
-
+
auto assert_literal = [&](TStringBuf literal) -> void {
for (size_t i = 2; i < literal.size(); ++i) {
token_buffer_.push_back(this->Base::template get_byte<false>());
Base::advance(1);
- if (Y_UNLIKELY(token_buffer_.back() != literal[i])) {
+ if (Y_UNLIKELY(token_buffer_.back() != literal[i])) {
throw_incorrect_percent_scalar();
}
}
};
-
+
token_buffer_.clear();
token_buffer_.push_back(this->Base::template get_byte<false>());
- Base::advance(1);
+ Base::advance(1);
switch (token_buffer_[0]) {
case 't':
@@ -236,32 +236,32 @@ namespace NYsonPull {
return percent_scalar(-std::numeric_limits<double>::infinity());
default:
throw_incorrect_percent_scalar();
- }
+ }
+
+ Y_UNREACHABLE();
+ }
- Y_UNREACHABLE();
- }
-
i64 read_binary_int64() {
return NVarInt::read<i64>(*this);
}
-
+
ui64 read_binary_uint64() {
return NVarInt::read<ui64>(*this);
}
-
+
double read_binary_double() {
union {
double as_double;
ui8 as_bytes[sizeof(double)];
} data;
static_assert(sizeof(data) == sizeof(double), "bad union size");
-
+
auto needToRead = sizeof(double);
-
+
auto& buf = Base::stream().buffer();
while (needToRead != 0) {
Base::fill_buffer();
-
+
auto chunk_size = std::min(needToRead, buf.available());
if (chunk_size == 0) {
Base::fail("Error parsing binary double literal");
@@ -274,8 +274,8 @@ namespace NYsonPull {
Base::advance(chunk_size);
}
return data.as_double;
- }
-
+ }
+
private:
static bool is_space(ui8 ch) {
static const ui8 lookupTable[] =
@@ -284,24 +284,24 @@ namespace NYsonPull {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-
+
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-
+
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-
+
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
return lookupTable[ch];
}
-
+
ATTRIBUTE(noinline, cold)
ui8 skip_space_and_get_byte_fallback() {
auto& buf = Base::stream().buffer();
@@ -318,12 +318,12 @@ namespace NYsonPull {
}
Base::advance(1);
}
- }
+ }
return Base::get_byte();
}
void check_memory_limit() {
- if (Y_UNLIKELY(memory_limit_ && token_buffer_.capacity() > *memory_limit_)) {
+ if (Y_UNLIKELY(memory_limit_ && token_buffer_.capacity() > *memory_limit_)) {
COLD_BLOCK_BYVALUE
Base::fail(
"Memory limit exceeded while parsing YSON stream: "
@@ -331,13 +331,13 @@ namespace NYsonPull {
token_buffer_.capacity(),
", limit ", *memory_limit_);
COLD_BLOCK_END
- }
- }
-
+ }
+ }
+
TStringBuf token_buffer() const {
auto* begin = reinterpret_cast<const char*>(token_buffer_.data());
return {begin, token_buffer_.size()};
}
};
- }
+ }
}
diff --git a/library/cpp/yson_pull/detail/macros.h b/library/cpp/yson_pull/detail/macros.h
index 8d9707c351..7243f9cfe1 100644
--- a/library/cpp/yson_pull/detail/macros.h
+++ b/library/cpp/yson_pull/detail/macros.h
@@ -1,24 +1,24 @@
-#pragma once
-
-#include <util/system/compiler.h>
-
-#if defined(__GNUC__)
-#define ATTRIBUTE(args...) __attribute__((args))
-#else
-#define ATTRIBUTE(...)
-#endif
-
-#if defined(__GNUC__) && !defined(__clang__)
+#pragma once
+
+#include <util/system/compiler.h>
+
+#if defined(__GNUC__)
+#define ATTRIBUTE(args...) __attribute__((args))
+#else
+#define ATTRIBUTE(...)
+#endif
+
+#if defined(__GNUC__) && !defined(__clang__)
#define COLD_BLOCK_BYVALUE [=]() ATTRIBUTE(noinline, cold) {
#define COLD_BLOCK_BYREF [&]() ATTRIBUTE(noinline, cold) {
#define COLD_BLOCK_END \
} \
();
-#else
-// Clang does not support gnu-style attributes on lambda functions yet
+#else
+// Clang does not support gnu-style attributes on lambda functions yet
#define COLD_BLOCK_BYVALUE [=]() {
#define COLD_BLOCK_BYREF [&]() {
#define COLD_BLOCK_END \
} \
();
-#endif
+#endif
diff --git a/library/cpp/yson_pull/detail/number.h b/library/cpp/yson_pull/detail/number.h
index 0dc442e3d2..5595f55e05 100644
--- a/library/cpp/yson_pull/detail/number.h
+++ b/library/cpp/yson_pull/detail/number.h
@@ -1,7 +1,7 @@
-#pragma once
-
+#pragma once
+
#include <util/system/types.h>
-
+
namespace NYsonPull {
namespace NDetail {
enum class number_type {
@@ -9,7 +9,7 @@ namespace NYsonPull {
uint64,
int64
};
-
+
struct number {
number_type type;
union {
@@ -17,21 +17,21 @@ namespace NYsonPull {
ui64 as_uint64;
i64 as_int64;
} value;
-
+
number(double v) {
type = number_type::float64;
value.as_float64 = v;
}
-
+
number(i64 v) {
type = number_type::int64;
value.as_int64 = v;
}
-
+
number(ui64 v) {
type = number_type::uint64;
value.as_uint64 = v;
}
};
- }
+ }
}
diff --git a/library/cpp/yson_pull/detail/output/buffered.h b/library/cpp/yson_pull/detail/output/buffered.h
index fbb18b5467..475cf34785 100644
--- a/library/cpp/yson_pull/detail/output/buffered.h
+++ b/library/cpp/yson_pull/detail/output/buffered.h
@@ -1,11 +1,11 @@
-#pragma once
-
+#pragma once
+
#include <library/cpp/yson_pull/detail/macros.h>
-
+
#include <library/cpp/yson_pull/output.h>
-
-#include <util/generic/strbuf.h>
-
+
+#include <util/generic/strbuf.h>
+
namespace NYsonPull {
namespace NDetail {
namespace NOutput {
@@ -13,29 +13,29 @@ namespace NYsonPull {
class TBuffered: public NYsonPull::NOutput::IStream {
TArrayHolder<ui8> buffer_;
size_t size_;
-
+
public:
TBuffered(size_t buffer_size)
: buffer_{new ui8[buffer_size]}
, size_{buffer_size} {
reset_buffer();
}
-
+
protected:
void do_flush_buffer(TStringBuf extra) override {
auto& buf = buffer();
if (!buf.is_empty()) {
- do_write({reinterpret_cast<const char*>(buf.begin()), buf.used()});
+ do_write({reinterpret_cast<const char*>(buf.begin()), buf.used()});
reset_buffer();
}
if (extra.size() >= buf.available()) {
do_write(extra);
- } else if (extra.size() > 0) {
+ } else if (extra.size() > 0) {
::memcpy(buf.pos(), extra.data(), extra.size());
buf.advance(extra.size());
}
}
-
+
private:
void do_write(TStringBuf data) {
// CRTP dispatch
@@ -46,6 +46,6 @@ namespace NYsonPull {
buffer().reset(buffer_.Get(), buffer_.Get() + size_);
}
};
- }
+ }
} // namespace NDetail
}
diff --git a/library/cpp/yson_pull/detail/output/stdio_file.h b/library/cpp/yson_pull/detail/output/stdio_file.h
index d59ea6bfb9..03f2b40dc5 100644
--- a/library/cpp/yson_pull/detail/output/stdio_file.h
+++ b/library/cpp/yson_pull/detail/output/stdio_file.h
@@ -1,33 +1,33 @@
-#pragma once
-
-#include "buffered.h"
-
+#pragma once
+
+#include "buffered.h"
+
#include <library/cpp/yson_pull/detail/macros.h>
-
+
#include <library/cpp/yson_pull/exceptions.h>
-
-#include <cstdio>
-
+
+#include <cstdio>
+
namespace NYsonPull {
namespace NDetail {
namespace NOutput {
class TStdioFile: public TBuffered<TStdioFile> {
FILE* file_;
-
+
public:
TStdioFile(FILE* file, size_t buffer_size)
: TBuffered<TStdioFile>(buffer_size)
, file_(file)
{
}
-
+
void write(TStringBuf data) {
auto nwritten = ::fwrite(data.data(), 1, data.size(), file_);
- if (Y_UNLIKELY(static_cast<size_t>(nwritten) != data.size())) {
+ if (Y_UNLIKELY(static_cast<size_t>(nwritten) != data.size())) {
throw NException::TSystemError();
}
}
};
- }
+ }
} // namespace NDetail
}
diff --git a/library/cpp/yson_pull/detail/output/stream.h b/library/cpp/yson_pull/detail/output/stream.h
index 98ab7d9555..d4810f3353 100644
--- a/library/cpp/yson_pull/detail/output/stream.h
+++ b/library/cpp/yson_pull/detail/output/stream.h
@@ -1,56 +1,56 @@
-#pragma once
-
-#include "buffered.h"
-
+#pragma once
+
+#include "buffered.h"
+
#include <library/cpp/yson_pull/detail/macros.h>
#include <library/cpp/yson_pull/exceptions.h>
-
-#include <util/stream/output.h>
-#include <util/stream/file.h>
-#include <util/system/file.h>
-
-namespace NYsonPull {
- namespace NDetail {
- namespace NOutput {
- class TStream: public TBuffered<TStream> {
+
+#include <util/stream/output.h>
+#include <util/stream/file.h>
+#include <util/system/file.h>
+
+namespace NYsonPull {
+ namespace NDetail {
+ namespace NOutput {
+ class TStream: public TBuffered<TStream> {
IOutputStream* Output;
-
- public:
+
+ public:
TStream(IOutputStream* output, size_t buffer_size)
- : TBuffered<TStream>(buffer_size)
- , Output(output)
- {
- }
-
- void write(TStringBuf data) {
- Output->Write(data);
- }
- };
-
+ : TBuffered<TStream>(buffer_size)
+ , Output(output)
+ {
+ }
+
+ void write(TStringBuf data) {
+ Output->Write(data);
+ }
+ };
+
template <typename TOutput>
- class TOwned: public TBuffered<TOwned<TOutput>> {
- TOutput Output;
-
- public:
+ class TOwned: public TBuffered<TOwned<TOutput>> {
+ TOutput Output;
+
+ public:
template <typename... Args>
- TOwned(size_t buffer_size, Args&&... args)
- : TBuffered<TOwned>(buffer_size)
- , Output(std::forward<Args>(args)...)
- {
- }
-
- void write(TStringBuf data) {
- Output.Write(data);
- }
- };
-
+ TOwned(size_t buffer_size, Args&&... args)
+ : TBuffered<TOwned>(buffer_size)
+ , Output(std::forward<Args>(args)...)
+ {
+ }
+
+ void write(TStringBuf data) {
+ Output.Write(data);
+ }
+ };
+
class TFHandle: public TOwned<TUnbufferedFileOutput> {
- public:
- TFHandle(int fd, size_t buffer_size)
+ public:
+ TFHandle(int fd, size_t buffer_size)
: TOwned<TUnbufferedFileOutput>(buffer_size, Duplicate(fd))
- {
- }
- };
- }
+ {
+ }
+ };
+ }
} // namespace NDetail
}
diff --git a/library/cpp/yson_pull/detail/reader.h b/library/cpp/yson_pull/detail/reader.h
index 4aa99e88e0..0e02396358 100644
--- a/library/cpp/yson_pull/detail/reader.h
+++ b/library/cpp/yson_pull/detail/reader.h
@@ -1,18 +1,18 @@
-#pragma once
-
-#include "lexer_base.h"
-#include "symbols.h"
-
+#pragma once
+
+#include "lexer_base.h"
+#include "symbols.h"
+
#include <library/cpp/yson_pull/reader.h>
-
-#include <util/generic/maybe.h>
-#include <util/generic/vector.h>
-
+
+#include <util/generic/maybe.h>
+#include <util/generic/vector.h>
+
namespace NYsonPull {
namespace NDetail {
/*! \internal */
////////////////////////////////////////////////////////////////////////////////
-
+
enum class special_token : ui8 {
// Special values:
// YSON
@@ -26,7 +26,7 @@ namespace NYsonPull {
left_angle = 7, // <
right_angle = 8, // >
};
-
+
// char_class tree representation:
// Root = xb
// BinaryStringOrOtherSpecialToken = x0b
@@ -48,7 +48,7 @@ namespace NYsonPull {
// Percent = 11011b
enum class char_class : ui8 {
binary_string = 0, // = 00b
-
+
special_token_mask = 2, // = 10b
semicolon = 2 + (0 << 2),
equals = 2 + (1 << 2),
@@ -59,14 +59,14 @@ namespace NYsonPull {
right_brace = 2 + (6 << 2),
left_angle = 2 + (7 << 2),
right_angle = 2 + (8 << 2),
-
+
binary_scalar_mask = 1,
binary_int64 = 1 + (0 << 2), // = 001b
binary_double = 1 + (1 << 2), // = 101b
binary_false = 1 + (2 << 2), // = 1001b
binary_true = 1 + (3 << 2), // = 1101b
binary_uint64 = 1 + (4 << 2), // = 10001b
-
+
other_mask = 3,
quote = 3 + (0 << 2), // = 00011b
number = 3 + (1 << 2), // = 00111b
@@ -74,30 +74,30 @@ namespace NYsonPull {
percent = 3 + (6 << 2), // = 11011b
none = 3 + (5 << 2), // = 10111b
};
-
+
#define CHAR_SUBCLASS(x) (static_cast<ui8>(x) >> 2)
-
+
inline char_class get_char_class(ui8 ch) {
-#define NN char_class::none
-#define BS char_class::binary_string
-#define BI char_class::binary_int64
-#define BD char_class::binary_double
-#define BF char_class::binary_false
-#define BT char_class::binary_true
-#define BU char_class::binary_uint64
-#define SP NN // char_class::space
-#define NB char_class::number
-#define ST char_class::string
-#define QU char_class::quote
-#define PC char_class::percent
-#define TT(name) (static_cast<char_class>( \
+#define NN char_class::none
+#define BS char_class::binary_string
+#define BI char_class::binary_int64
+#define BD char_class::binary_double
+#define BF char_class::binary_false
+#define BT char_class::binary_true
+#define BU char_class::binary_uint64
+#define SP NN // char_class::space
+#define NB char_class::number
+#define ST char_class::string
+#define QU char_class::quote
+#define PC char_class::percent
+#define TT(name) (static_cast<char_class>( \
(static_cast<ui8>(special_token::name) << 2) | static_cast<ui8>(char_class::special_token_mask)))
-
+
static constexpr char_class lookup[256] =
{
NN, BS, BI, BD, BF, BT, BU, NN, NN, SP, SP, SP, SP, SP, NN, NN,
NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN,
-
+
// 32
SP, // ' '
NN, // '!'
@@ -115,7 +115,7 @@ namespace NYsonPull {
NB, // '-'
NN, // '.'
NN, // '/'
-
+
// 48
NB, NB, NB, NB, NB, NB, NB, NB, NB, NB, // '0' - '9'
NN, // ':'
@@ -124,7 +124,7 @@ namespace NYsonPull {
TT(equals), // '='
TT(right_angle), // '>'
NN, // '?'
-
+
// 64
NN, // '@'
ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, // 'A' - 'M'
@@ -134,10 +134,10 @@ namespace NYsonPull {
TT(right_bracket), // ']'
NN, // '^'
ST, // '_'
-
+
// 96
NN, // '`'
-
+
ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, // 'a' - 'm'
ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, ST, // 'n' - 'z'
TT(left_brace), // '{'
@@ -150,24 +150,24 @@ namespace NYsonPull {
NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN,
NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN,
NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN,
-
+
NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN,
NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN,
NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN,
NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN, NN};
-
-#undef NN
-#undef BS
-#undef BI
-#undef BD
-#undef SP
-#undef NB
-#undef ST
-#undef QU
-#undef TT
+
+#undef NN
+#undef BS
+#undef BI
+#undef BD
+#undef SP
+#undef NB
+#undef ST
+#undef QU
+#undef TT
return lookup[ch];
}
-
+
template <bool EnableLinePositionInfo>
class gen_reader_impl {
enum class state {
@@ -177,20 +177,20 @@ namespace NYsonPull {
equals = 3, //! expecting '=' (followed by value)
value = 4, //! expecting a value
value_noattr = 5, //! expecting a value w/o attrs (after attrs)
-
+
// by design, rare states have numbers starting from first_rare_state
first_rare_state = 6,
before_begin = first_rare_state, //! before started reading the stream
before_end = first_rare_state + 1, //! Expecting end of stream
after_end = first_rare_state + 2, //! after end of stream
};
-
+
lexer_base<EnableLinePositionInfo> lexer_;
state state_;
TEvent event_;
TVector<EEventType> stack_;
EStreamType mode_;
-
+
public:
gen_reader_impl(
NYsonPull::NInput::IStream& buffer,
@@ -200,14 +200,14 @@ namespace NYsonPull {
, state_{state::before_begin}
, mode_{mode} {
}
-
+
const TEvent& last_event() const {
return event_;
}
-
+
ATTRIBUTE(hot)
const TEvent& next_event() {
- if (Y_LIKELY(state_ < state::first_rare_state)) {
+ if (Y_LIKELY(state_ < state::first_rare_state)) {
// 'hot' handler for in-stream events
next_event_hot();
} else {
@@ -216,15 +216,15 @@ namespace NYsonPull {
}
return event_;
}
-
+
private:
ATTRIBUTE(hot)
void next_event_hot() {
auto ch = lexer_.get_byte();
auto cls = get_char_class(ch);
- if (Y_UNLIKELY(cls == char_class::none)) {
+ if (Y_UNLIKELY(cls == char_class::none)) {
ch = lexer_.skip_space_and_get_byte();
- if (Y_UNLIKELY(ch == NSymbol::eof)) {
+ if (Y_UNLIKELY(ch == NSymbol::eof)) {
handle_eof();
return;
}
@@ -253,10 +253,10 @@ namespace NYsonPull {
state_delimiter(ch, cls);
break;
default:
- Y_UNREACHABLE();
+ Y_UNREACHABLE();
}
- }
-
+ }
+
ATTRIBUTE(noinline, cold)
void next_event_cold() {
switch (state_) {
@@ -269,22 +269,22 @@ namespace NYsonPull {
state_before_end();
break;
default:
- Y_UNREACHABLE();
+ Y_UNREACHABLE();
}
}
-
+
//! Present a scalar value for caller
template <typename T>
void yield(T value) {
event_ = TEvent{TScalar{value}};
}
-
+
//! Present a scalar value with non-scalar tag (i.e. key)
template <typename T>
void yield(EEventType type, T value) {
event_ = TEvent{type, TScalar{value}};
}
-
+
//! Present a value from number variant
void yield(const number& value) {
switch (value.type) {
@@ -299,7 +299,7 @@ namespace NYsonPull {
break;
}
}
-
+
//! Present a value from %-literal variant
void yield(const percent_scalar& value) {
switch (value.type) {
@@ -316,47 +316,47 @@ namespace NYsonPull {
void yield(EEventType type) {
event_ = TEvent{type};
}
-
+
//! Push the opening of a paired event
void push(EEventType type) {
stack_.push_back(type);
}
-
+
//! Close the paired_event, verify that delimiters are well-formed
void pop(EEventType first, EEventType last) {
- if (Y_UNLIKELY(stack_.empty() || stack_.back() != first)) {
+ if (Y_UNLIKELY(stack_.empty() || stack_.back() != first)) {
pop_fail(first, last);
return;
}
stack_.pop_back();
-
+
yield(last);
switch (first) {
- case EEventType::BeginList:
+ case EEventType::BeginList:
next(state::delimiter);
break;
-
- case EEventType::BeginMap:
+
+ case EEventType::BeginMap:
next(state::delimiter);
break;
-
- case EEventType::BeginAttributes:
+
+ case EEventType::BeginAttributes:
next(state::value_noattr);
break;
-
- case EEventType::BeginStream:
+
+ case EEventType::BeginStream:
next(state::after_end);
break;
-
+
default:
- Y_UNREACHABLE();
+ Y_UNREACHABLE();
}
-
- if (Y_UNLIKELY(mode_ == EStreamType::Node && stack_.size() == 1 && state_ == state::delimiter)) {
+
+ if (Y_UNLIKELY(mode_ == EStreamType::Node && stack_.size() == 1 && state_ == state::delimiter)) {
next(state::before_end);
}
}
-
+
ATTRIBUTE(noinline, cold)
void pop_fail(EEventType first, EEventType last) {
if (stack_.empty()) {
@@ -365,16 +365,16 @@ namespace NYsonPull {
lexer_.fail("Unpaired events: expected opening '", first, "' for '", last, "', but '", stack_.back(), "' is found.");
}
}
-
+
//! Transition to new_state
void next(state new_state) {
state_ = new_state;
}
-
+
bool in_map() {
- return (stack_.back() == EEventType::BeginMap) || (stack_.back() == EEventType::BeginAttributes) || (stack_.back() == EEventType::BeginStream && mode_ == EStreamType::MapFragment);
+ return (stack_.back() == EEventType::BeginMap) || (stack_.back() == EEventType::BeginAttributes) || (stack_.back() == EEventType::BeginStream && mode_ == EStreamType::MapFragment);
}
-
+
ATTRIBUTE(noinline, cold)
void handle_eof() {
switch (state_) {
@@ -382,18 +382,18 @@ namespace NYsonPull {
case state::maybe_key:
case state::delimiter:
case state::before_end:
- pop(EEventType::BeginStream, EEventType::EndStream);
+ pop(EEventType::BeginStream, EEventType::EndStream);
return;
-
+
default:
lexer_.fail("Unexpected end of stream");
}
}
-
+
ATTRIBUTE(noinline, cold)
void state_before_begin() {
- push(EEventType::BeginStream);
- yield(EEventType::BeginStream);
+ push(EEventType::BeginStream);
+ yield(EEventType::BeginStream);
switch (mode_) {
case EStreamType::Node:
next(state::value);
@@ -405,10 +405,10 @@ namespace NYsonPull {
next(state::maybe_key);
break;
default:
- Y_UNREACHABLE();
+ Y_UNREACHABLE();
}
}
-
+
ATTRIBUTE(noinline, cold)
void state_before_end() {
auto ch = lexer_.skip_space_and_get_byte();
@@ -418,10 +418,10 @@ namespace NYsonPull {
lexer_.fail("Expected stream end, but found ", NCEscape::quote(ch));
}
}
-
+
ATTRIBUTE(hot)
void state_delimiter(ui8 ch, char_class cls) {
- if (Y_LIKELY(ch == NSymbol::item_separator)) {
+ if (Y_LIKELY(ch == NSymbol::item_separator)) {
lexer_.advance(1);
next(in_map() ? state::maybe_key : state::maybe_value);
// immediately read next value
@@ -430,7 +430,7 @@ namespace NYsonPull {
}
state_delimiter_fallback(ch, cls);
}
-
+
ATTRIBUTE(noinline, hot)
void state_delimiter_fallback(ui8 ch, char_class cls) {
auto cls_bits = static_cast<ui8>(cls);
@@ -439,24 +439,24 @@ namespace NYsonPull {
lexer_.advance(1);
switch (token) {
/* // handled in the fast track
- case special_token::semicolon:
- next(in_map()? state::maybe_key : state::maybe_value);
- // immediately read next value
- return next_event();
- */
-
+ case special_token::semicolon:
+ next(in_map()? state::maybe_key : state::maybe_value);
+ // immediately read next value
+ return next_event();
+ */
+
case special_token::right_bracket:
- pop(EEventType::BeginList, EEventType::EndList);
+ pop(EEventType::BeginList, EEventType::EndList);
return;
-
+
case special_token::right_brace:
- pop(EEventType::BeginMap, EEventType::EndMap);
+ pop(EEventType::BeginMap, EEventType::EndMap);
return;
-
+
case special_token::right_angle:
- pop(EEventType::BeginAttributes, EEventType::EndAttributes);
+ pop(EEventType::BeginAttributes, EEventType::EndAttributes);
return;
-
+
default:
break;
}
@@ -470,14 +470,14 @@ namespace NYsonPull {
NCEscape::quote(NSymbol::end_map), ", ",
NCEscape::quote(NSymbol::end_attributes));
COLD_BLOCK_END
- }
-
+ }
+
ATTRIBUTE(noinline, hot)
void state_maybe_key(ui8 ch, char_class cls) {
auto key = TStringBuf{};
// Keys are always strings, put binary-string key into fast lane
- if (Y_LIKELY(ch == NSymbol::string_marker)) {
- lexer_.advance(1);
+ if (Y_LIKELY(ch == NSymbol::string_marker)) {
+ lexer_.advance(1);
key = lexer_.read_binary_string();
} else {
switch (cls) {
@@ -485,21 +485,21 @@ namespace NYsonPull {
lexer_.advance(1);
key = lexer_.read_quoted_string();
break;
-
+
case char_class::string:
key = lexer_.read_unquoted_string();
break;
-
+
case char_class::right_brace:
lexer_.advance(1);
- pop(EEventType::BeginMap, EEventType::EndMap);
+ pop(EEventType::BeginMap, EEventType::EndMap);
return;
-
+
case char_class::right_angle:
lexer_.advance(1);
- pop(EEventType::BeginAttributes, EEventType::EndAttributes);
+ pop(EEventType::BeginAttributes, EEventType::EndAttributes);
return;
-
+
default:
COLD_BLOCK_BYVALUE
lexer_.fail("Unexpected ", NCEscape::quote(ch), ", expected key string");
@@ -507,25 +507,25 @@ namespace NYsonPull {
}
}
- yield(EEventType::Key, key);
+ yield(EEventType::Key, key);
next(state::equals);
}
ATTRIBUTE(hot)
void state_equals(ui8 ch) {
// skip '='
- if (Y_UNLIKELY(ch != NSymbol::key_value_separator)) {
- COLD_BLOCK_BYVALUE
+ if (Y_UNLIKELY(ch != NSymbol::key_value_separator)) {
+ COLD_BLOCK_BYVALUE
lexer_.fail("Unexpected ", NCEscape::quote(ch), ", expected ", NCEscape::quote(NSymbol::key_value_separator));
- COLD_BLOCK_END
+ COLD_BLOCK_END
}
lexer_.advance(1);
next(state::value);
// immediately read the following value
// (this symbol yields no result)
next_event_hot();
- }
-
+ }
+
ATTRIBUTE(noinline, hot)
void state_value(ui8 ch, char_class cls) {
auto cls_bits = static_cast<ui8>(cls);
@@ -549,7 +549,7 @@ namespace NYsonPull {
}
}
}
-
+
ATTRIBUTE(noinline)
void state_value_special(special_token token, ui8 ch) {
// Value starters are always accepted values
@@ -558,37 +558,37 @@ namespace NYsonPull {
yield(TScalar{});
next(state::delimiter);
return;
-
+
case special_token::left_bracket:
- push(EEventType::BeginList);
- yield(EEventType::BeginList);
+ push(EEventType::BeginList);
+ yield(EEventType::BeginList);
next(state::maybe_value);
return;
-
+
case special_token::left_brace:
- push(EEventType::BeginMap);
- yield(EEventType::BeginMap);
+ push(EEventType::BeginMap);
+ yield(EEventType::BeginMap);
next(state::maybe_key);
return;
-
+
default:
break;
}
-
+
// ...closing-chars are only allowed in maybe_value state
if (state_ == state::maybe_value) {
switch (token) {
case special_token::right_bracket:
- pop(EEventType::BeginList, EEventType::EndList);
+ pop(EEventType::BeginList, EEventType::EndList);
return;
-
+
case special_token::right_brace:
- pop(EEventType::BeginMap, EEventType::EndMap);
+ pop(EEventType::BeginMap, EEventType::EndMap);
return;
-
+
// right_angle is impossible in maybe_value state
// (only in delimiter, maybe_key)
-
+
default:
break;
}
@@ -596,17 +596,17 @@ namespace NYsonPull {
// attributes are not allowed after attributes (thus, value_noattr state)
if (state_ != state::value_noattr && token == special_token::left_angle) {
- push(EEventType::BeginAttributes);
- yield(EEventType::BeginAttributes);
+ push(EEventType::BeginAttributes);
+ yield(EEventType::BeginAttributes);
next(state::maybe_key);
- return;
+ return;
}
-
+
COLD_BLOCK_BYVALUE
lexer_.fail("Unexpected ", NCEscape::quote(ch));
COLD_BLOCK_END
- }
-
+ }
+
ATTRIBUTE(hot)
void state_value_binary_scalar(char_class cls) {
lexer_.advance(1);
@@ -614,28 +614,28 @@ namespace NYsonPull {
case char_class::binary_double:
yield(lexer_.read_binary_double());
break;
-
+
case char_class::binary_int64:
yield(lexer_.read_binary_int64());
break;
-
+
case char_class::binary_uint64:
yield(lexer_.read_binary_uint64());
break;
-
+
case char_class::binary_false:
yield(false);
break;
-
+
case char_class::binary_true:
yield(true);
break;
-
+
default:
- Y_UNREACHABLE();
+ Y_UNREACHABLE();
}
}
-
+
ATTRIBUTE(noinline)
void state_value_text_scalar(char_class cls) {
switch (cls) {
@@ -643,20 +643,20 @@ namespace NYsonPull {
lexer_.advance(1);
yield(lexer_.read_quoted_string());
break;
-
+
case char_class::number:
yield(lexer_.read_numeric());
break;
-
+
case char_class::string:
yield(lexer_.read_unquoted_string());
break;
-
+
case char_class::percent:
lexer_.advance(1);
yield(lexer_.read_percent_scalar());
break;
-
+
case char_class::none:
COLD_BLOCK_BYVALUE
lexer_.fail("Invalid yson value.");
@@ -664,14 +664,14 @@ namespace NYsonPull {
break;
default:
- Y_UNREACHABLE();
+ Y_UNREACHABLE();
}
}
};
-
+
class reader_impl: public gen_reader_impl<false> {
public:
using gen_reader_impl<false>::gen_reader_impl;
};
- }
+ }
}
diff --git a/library/cpp/yson_pull/detail/stream_counter.h b/library/cpp/yson_pull/detail/stream_counter.h
index c96698d091..3b41b27eb6 100644
--- a/library/cpp/yson_pull/detail/stream_counter.h
+++ b/library/cpp/yson_pull/detail/stream_counter.h
@@ -1,26 +1,26 @@
-#pragma once
-
+#pragma once
+
#include <library/cpp/yson_pull/position_info.h>
-
-#include <cstddef>
-
+
+#include <cstddef>
+
namespace NYsonPull {
namespace NDetail {
template <bool EnableLinePositionInfo>
class stream_counter;
-
+
template <>
class stream_counter<true> {
private:
size_t offset_ = 0;
size_t line_ = 1;
size_t column_ = 1;
-
+
public:
TPositionInfo info() const {
return {offset_, line_, column_};
}
-
+
void update(const ui8* begin, const ui8* end) {
offset_ += end - begin;
for (auto current = begin; current != end; ++current) {
@@ -30,22 +30,22 @@ namespace NYsonPull {
column_ = 1;
}
}
- }
+ }
};
-
+
template <>
class stream_counter<false> {
private:
size_t offset_ = 0;
-
+
public:
TPositionInfo info() const {
return {offset_, {}, {}};
}
-
+
void update(const ui8* begin, const ui8* end) {
offset_ += end - begin;
}
};
- }
+ }
}
diff --git a/library/cpp/yson_pull/detail/symbols.h b/library/cpp/yson_pull/detail/symbols.h
index be49f80695..fe94bb9c41 100644
--- a/library/cpp/yson_pull/detail/symbols.h
+++ b/library/cpp/yson_pull/detail/symbols.h
@@ -1,38 +1,38 @@
-#pragma once
-
-#include <util/generic/strbuf.h>
+#pragma once
+
+#include <util/generic/strbuf.h>
#include <util/system/types.h>
-
+
namespace NYsonPull {
namespace NDetail {
namespace NSymbol {
#define SYM(name, value) constexpr ui8 name = value
-
+
//! Indicates the beginning of a list.
SYM(begin_list, '[');
//! Indicates the end of a list.
SYM(end_list, ']');
-
+
//! Indicates the beginning of a map.
SYM(begin_map, '{');
//! Indicates the end of a map.
SYM(end_map, '}');
-
+
//! Indicates the beginning of an attribute map.
SYM(begin_attributes, '<');
//! Indicates the end of an attribute map.
SYM(end_attributes, '>');
-
+
//! Separates items in lists and pairs in maps or attribute maps.
SYM(item_separator, ';');
//! Separates keys from values in maps and attribute maps.
SYM(key_value_separator, '=');
-
+
//! Indicates an entity.
SYM(entity, '#');
//! Indicates end of stream.
SYM(eof, '\0');
-
+
//! Marks the beginning of a binary string literal.
SYM(string_marker, '\x01');
//! Marks the beginning of a binary int64 literal.
@@ -45,11 +45,11 @@ namespace NYsonPull {
SYM(false_marker, '\x04');
//! Marks a binary `true' boolean value.
SYM(true_marker, '\x05');
-
+
//! Text string quote symbol
SYM(quote, '"');
-
-#undef SYM
+
+#undef SYM
}
}
}
diff --git a/library/cpp/yson_pull/detail/traits.h b/library/cpp/yson_pull/detail/traits.h
index 0d1ab6f660..869a3b9c44 100644
--- a/library/cpp/yson_pull/detail/traits.h
+++ b/library/cpp/yson_pull/detail/traits.h
@@ -1,7 +1,7 @@
-#pragma once
-
-#include <type_traits>
-
+#pragma once
+
+#include <type_traits>
+
namespace NYsonPull {
namespace NDetail {
namespace NTraits {
@@ -9,17 +9,17 @@ namespace NYsonPull {
using if_signed = typename std::enable_if<
std::is_signed<T>::value,
U>::type;
-
+
template <typename T, typename U>
using if_unsigned = typename std::enable_if<
std::is_unsigned<T>::value,
U>::type;
-
+
template <typename T>
using to_unsigned = typename std::enable_if<
std::is_signed<T>::value,
typename std::make_unsigned<T>::type>::type;
-
+
template <typename T>
using to_signed = typename std::enable_if<
std::is_unsigned<T>::value,
diff --git a/library/cpp/yson_pull/detail/varint.h b/library/cpp/yson_pull/detail/varint.h
index 6426238d75..38bf45d925 100644
--- a/library/cpp/yson_pull/detail/varint.h
+++ b/library/cpp/yson_pull/detail/varint.h
@@ -1,15 +1,15 @@
-#pragma once
-
-#include "byte_reader.h"
-#include "byte_writer.h"
-#include "traits.h"
-#include "zigzag.h"
-
-#include <util/system/types.h>
-
-#include <cstddef>
-#include <type_traits>
-
+#pragma once
+
+#include "byte_reader.h"
+#include "byte_writer.h"
+#include "traits.h"
+#include "zigzag.h"
+
+#include <util/system/types.h>
+
+#include <cstddef>
+#include <type_traits>
+
namespace NYsonPull {
namespace NDetail {
namespace NVarInt {
@@ -18,7 +18,7 @@ namespace NYsonPull {
constexpr inline size_t max_size() {
return (8 * sizeof(T) - 1) / 7 + 1;
}
-
+
template <typename T>
inline size_t write(ui64 value, T&& consume) {
auto stop = false;
@@ -35,17 +35,17 @@ namespace NYsonPull {
}
return nwritten;
}
-
+
template <typename U>
inline bool read_fast(byte_reader<U>& reader, ui64* value) {
auto& buf = reader.stream().buffer();
auto* ptr = buf.pos();
ui32 b;
-
+
// Splitting into 32-bit pieces gives better performance on 32-bit
// processors.
ui32 part0 = 0, part1 = 0, part2 = 0;
-
+
b = *(ptr++);
part0 = (b & 0x7F);
if (!(b & 0x80))
@@ -86,17 +86,17 @@ namespace NYsonPull {
part2 |= (b & 0x7F) << 7;
if (!(b & 0x80))
goto done;
-
+
// We have overrun the maximum size of a Varint (10 bytes). The data
// must be corrupt.
return false;
-
+
done:
reader.advance(ptr - buf.pos());
*value = (static_cast<ui64>(part0)) | (static_cast<ui64>(part1) << 28) | (static_cast<ui64>(part2) << 56);
return true;
}
-
+
template <typename U>
inline bool read_fast(byte_reader<U>& reader, ui32* value) {
// Fast path: We have enough bytes left in the buffer to guarantee that
@@ -105,7 +105,7 @@ namespace NYsonPull {
auto* ptr = buf.pos();
ui32 b;
ui32 result;
-
+
b = *(ptr++);
result = (b & 0x7F);
if (!(b & 0x80))
@@ -126,37 +126,37 @@ namespace NYsonPull {
result |= b << 28;
if (!(b & 0x80))
goto done;
-
+
// FIXME
// If the input is larger than 32 bits, we still need to read it all
// and discard the high-order bits.
-
+
for (size_t i = 0; i < max_size<ui64>() - max_size<ui32>(); i++) {
b = *(ptr++);
if (!(b & 0x80))
goto done;
}
-
+
// We have overrun the maximum size of a Varint (10 bytes). Assume
// the data is corrupt.
return false;
-
+
done:
reader.advance(ptr - buf.pos());
*value = result;
return true;
}
-
+
template <typename U>
inline bool read_slow(byte_reader<U>& reader, ui64* value) {
// Slow path: This read might cross the end of the buffer, so we
// need to check and refresh the buffer if and when it does.
-
+
auto& buf = reader.stream().buffer();
ui64 result = 0;
int count = 0;
ui32 b;
-
+
do {
if (count == max_size<ui64>()) {
return false;
@@ -170,11 +170,11 @@ namespace NYsonPull {
reader.advance(1);
++count;
} while (b & 0x80);
-
+
*value = result;
return true;
}
-
+
template <typename U>
inline bool read_slow(byte_reader<U>& reader, ui32* value) {
ui64 result;
@@ -183,18 +183,18 @@ namespace NYsonPull {
*value = static_cast<ui32>(result);
return true;
}
-
+
return false;
}
-
+
// Following functions is an adaptation
// of Protobuf code from coded_stream.cc
template <typename T, typename U>
inline bool read_dispatch(byte_reader<U>& reader, T* value) {
auto& buf = reader.stream().buffer();
- // NOTE: checking for 64-bit max_size(), since 32-bit
- // read_fast() might fallback to 64-bit reading
- if (buf.available() >= max_size<ui64>() ||
+ // NOTE: checking for 64-bit max_size(), since 32-bit
+ // read_fast() might fallback to 64-bit reading
+ if (buf.available() >= max_size<ui64>() ||
// Optimization: If the Varint ends at exactly the end of the buffer,
// we can detect that and still use the fast path.
(!buf.is_empty() && !(buf.end()[-1] & 0x80)))
@@ -207,11 +207,11 @@ namespace NYsonPull {
return read_slow(reader, value);
}
}
-
+
}
-
+
// Various functions to read/write varints.
-
+
// Returns the number of bytes written.
template <typename T>
inline NTraits::if_unsigned<T, size_t> write(ui8* data, T value) {
@@ -219,21 +219,21 @@ namespace NYsonPull {
static_cast<ui64>(value),
[&](ui8 byte) { *data++ = byte; });
}
-
+
template <typename T>
inline NTraits::if_signed<T, size_t> write(ui8* data, T value) {
return NImpl::write(
static_cast<ui64>(NZigZag::encode(value)),
[&](ui8 byte) { *data++ = byte; });
}
-
+
template <typename T, typename U>
inline void write(byte_writer<U>& stream, T value) {
ui8 data[NImpl::max_size<T>()];
auto size = write(data, value);
stream.write(data, size);
}
-
+
template <typename T, typename U>
inline NTraits::if_unsigned<T, T> read(byte_reader<U>& reader) {
auto value = T{};
@@ -243,13 +243,13 @@ namespace NYsonPull {
reader.advance(1);
return value;
}
-
- if (Y_UNLIKELY(!NImpl::read_dispatch(reader, &value))) {
+
+ if (Y_UNLIKELY(!NImpl::read_dispatch(reader, &value))) {
reader.fail("Error parsing varint value");
}
return value;
}
-
+
template <typename T, typename U>
inline NTraits::if_signed<T, T> read(byte_reader<U>& reader) {
return NZigZag::decode(
diff --git a/library/cpp/yson_pull/detail/writer.h b/library/cpp/yson_pull/detail/writer.h
index ebd6b4edf2..b24b994292 100644
--- a/library/cpp/yson_pull/detail/writer.h
+++ b/library/cpp/yson_pull/detail/writer.h
@@ -1,23 +1,23 @@
-#pragma once
-
-#include "byte_writer.h"
-#include "cescape.h"
+#pragma once
+
+#include "byte_writer.h"
+#include "cescape.h"
#include "percent_scalar.h"
-#include "stream_counter.h"
-#include "symbols.h"
-#include "varint.h"
-
+#include "stream_counter.h"
+#include "symbols.h"
+#include "varint.h"
+
#include <library/cpp/yson_pull/consumer.h>
#include <library/cpp/yson_pull/event.h>
#include <library/cpp/yson_pull/output.h>
#include <library/cpp/yson_pull/stream_type.h>
#include <library/cpp/yson_pull/writer.h>
-
-#include <util/generic/vector.h>
-#include <util/system/yassert.h>
-
-#include <cmath>
-
+
+#include <util/generic/vector.h>
+#include <util/system/yassert.h>
+
+#include <cmath>
+
namespace NYsonPull {
namespace NDetail {
class writer: public IConsumer {
@@ -30,91 +30,91 @@ namespace NYsonPull {
before_end,
after_end,
};
-
+
byte_writer<stream_counter<false>> stream_;
TVector<EEventType> stack_;
bool need_item_separator_ = false;
EStreamType mode_ = EStreamType::ListFragment;
state state_ = state::before_begin;
-
+
public:
- void OnBeginStream() override {
- update_state(EEventType::BeginStream);
+ void OnBeginStream() override {
+ update_state(EEventType::BeginStream);
}
-
- void OnEndStream() override {
- update_state(EEventType::EndStream);
+
+ void OnEndStream() override {
+ update_state(EEventType::EndStream);
stream_.flush_buffer();
}
-
- void OnBeginList() override {
+
+ void OnBeginList() override {
begin_node();
write(NSymbol::begin_list);
- update_state(EEventType::BeginList);
+ update_state(EEventType::BeginList);
begin_collection(collection_type::list);
}
-
- void OnEndList() override {
- update_state(EEventType::EndList);
+
+ void OnEndList() override {
+ update_state(EEventType::EndList);
end_collection(collection_type::list);
write(NSymbol::end_list);
end_node();
}
-
- void OnBeginMap() override {
+
+ void OnBeginMap() override {
begin_node();
write(NSymbol::begin_map);
- update_state(EEventType::BeginMap);
+ update_state(EEventType::BeginMap);
begin_collection(collection_type::map);
}
-
- void OnEndMap() override {
- update_state(EEventType::EndMap);
+
+ void OnEndMap() override {
+ update_state(EEventType::EndMap);
end_collection(collection_type::map);
write(NSymbol::end_map);
end_node();
}
-
- void OnBeginAttributes() override {
+
+ void OnBeginAttributes() override {
begin_node();
write(NSymbol::begin_attributes);
- update_state(EEventType::BeginAttributes);
+ update_state(EEventType::BeginAttributes);
begin_collection(collection_type::attributes);
}
-
- void OnEndAttributes() override {
- update_state(EEventType::EndAttributes);
+
+ void OnEndAttributes() override {
+ update_state(EEventType::EndAttributes);
end_collection(collection_type::attributes);
write(NSymbol::end_attributes);
// no end_node
}
-
- void OnEntity() override {
- begin_node();
- update_state(EEventType::Scalar);
+
+ void OnEntity() override {
+ begin_node();
+ update_state(EEventType::Scalar);
write(NSymbol::entity);
end_node();
}
-
+
protected:
enum class collection_type {
list,
map,
attributes,
};
-
+
writer(NYsonPull::NOutput::IStream& stream, EStreamType mode)
: stream_(stream)
, mode_{mode} {
}
-
+
bool need_item_separator() const {
return need_item_separator_;
}
void need_item_separator(bool value) {
need_item_separator_ = value;
}
-
+
size_t depth() const {
Y_ASSERT(!stack_.empty());
if (mode_ == EStreamType::Node) {
@@ -126,124 +126,124 @@ namespace NYsonPull {
EStreamType mode() const {
return mode_;
}
-
+
void write(ui8 c) {
stream_.write(c);
}
-
+
void write(TStringBuf value) {
write_raw(value.data(), value.size());
}
-
+
void write_raw(const void* ptr, size_t len) {
stream_.write(static_cast<const ui8*>(ptr), len);
}
-
+
template <typename T>
void write_varint(T value) {
NVarInt::write(stream_, value);
}
-
+
void write_escaped_string(TStringBuf value) {
write(NSymbol::quote);
NCEscape::encode(stream_, value);
write(NSymbol::quote);
}
-
+
void push(EEventType type) {
stack_.push_back(type);
}
-
+
void pop(EEventType type) {
if (stack_.empty()) {
fail("Unpaired events: empty event stack");
- }
+ }
if (stack_.back() != type) {
fail("Unpaired events: expected ", type, ", got ", stack_.back());
- }
+ }
stack_.pop_back();
}
-
+
void update_state(EEventType event) {
switch (state_) {
case state::before_begin:
- if (event != EEventType::BeginStream) {
+ if (event != EEventType::BeginStream) {
fail("Expected begin_stream, got ", event);
}
begin_stream();
return;
-
+
case state::before_end:
- if (event != EEventType::EndStream) {
+ if (event != EEventType::EndStream) {
fail("Expected end_stream, got ", event);
}
- end_stream();
- return;
-
+ end_stream();
+ return;
+
case state::after_end:
fail("Attempted write past stream end");
-
+
case state::maybe_key:
- if (event == EEventType::Key) {
+ if (event == EEventType::Key) {
state_ = state::value;
return;
}
-
+
switch (event) {
- case EEventType::EndStream:
+ case EEventType::EndStream:
end_stream();
return;
-
- case EEventType::EndMap:
- pop(EEventType::BeginMap);
+
+ case EEventType::EndMap:
+ pop(EEventType::BeginMap);
next_state();
return;
-
- case EEventType::EndAttributes:
- pop(EEventType::BeginAttributes);
+
+ case EEventType::EndAttributes:
+ pop(EEventType::BeginAttributes);
state_ = state::value_noattr;
return;
-
+
default:
fail("Unexpected event ", event, " in maybe_key");
}
break;
-
+
case state::maybe_value:
switch (event) {
- case EEventType::EndList:
- pop(EEventType::BeginList);
+ case EEventType::EndList:
+ pop(EEventType::BeginList);
next_state();
return;
-
- case EEventType::EndStream:
+
+ case EEventType::EndStream:
end_stream();
return;
-
+
default:
break;
}
[[fallthrough]];
case state::value:
- if (event == EEventType::BeginAttributes) {
- push(EEventType::BeginAttributes);
+ if (event == EEventType::BeginAttributes) {
+ push(EEventType::BeginAttributes);
next_state();
return;
}
[[fallthrough]];
case state::value_noattr:
switch (event) {
- case EEventType::Scalar:
+ case EEventType::Scalar:
next_state();
return;
- case EEventType::BeginList:
- push(EEventType::BeginList);
+ case EEventType::BeginList:
+ push(EEventType::BeginList);
next_state();
return;
- case EEventType::BeginMap:
- push(EEventType::BeginMap);
+ case EEventType::BeginMap:
+ push(EEventType::BeginMap);
next_state();
return;
@@ -251,94 +251,94 @@ namespace NYsonPull {
fail("Unexpected event ", event, " (in value_*)");
}
break;
- }
+ }
}
-
+
void next_state() {
Y_ASSERT(!stack_.empty());
switch (stack_.back()) {
- case EEventType::BeginMap:
- case EEventType::BeginAttributes:
+ case EEventType::BeginMap:
+ case EEventType::BeginAttributes:
state_ = state::maybe_key;
break;
-
- case EEventType::BeginList:
+
+ case EEventType::BeginList:
state_ = state::maybe_value;
break;
-
- case EEventType::BeginStream:
+
+ case EEventType::BeginStream:
state_ = state::before_end;
break;
-
+
default:
- Y_UNREACHABLE();
+ Y_UNREACHABLE();
}
}
-
+
void begin_stream() {
- push(EEventType::BeginStream);
+ push(EEventType::BeginStream);
switch (mode_) {
case EStreamType::ListFragment:
- push(EEventType::BeginList);
+ push(EEventType::BeginList);
state_ = state::maybe_value;
break;
-
+
case EStreamType::MapFragment:
- push(EEventType::BeginMap);
+ push(EEventType::BeginMap);
state_ = state::maybe_key;
break;
-
+
case EStreamType::Node:
state_ = state::value;
break;
}
}
-
+
void end_stream() {
switch (mode_) {
case EStreamType::ListFragment:
- pop(EEventType::BeginList);
+ pop(EEventType::BeginList);
break;
-
+
case EStreamType::MapFragment:
- pop(EEventType::BeginMap);
+ pop(EEventType::BeginMap);
break;
-
+
case EStreamType::Node:
break;
}
- pop(EEventType::BeginStream);
+ pop(EEventType::BeginStream);
state_ = state::after_end;
}
-
+
virtual void begin_node() {
if (need_item_separator_) {
write(NSymbol::item_separator);
}
}
-
+
virtual void end_node() {
need_item_separator_ = true;
}
-
+
virtual void begin_key() {
begin_node();
}
-
+
virtual void end_key() {
need_item_separator_ = false;
write(NSymbol::key_value_separator);
}
-
+
virtual void begin_collection(collection_type type) {
Y_UNUSED(type);
need_item_separator_ = false;
}
-
+
virtual void end_collection(collection_type type) {
need_item_separator_ = (type != collection_type::attributes);
}
-
+
template <typename... Args>
ATTRIBUTE(noinline, cold)
void fail[[noreturn]](const char* msg, Args&&... args) {
@@ -350,62 +350,62 @@ namespace NYsonPull {
stream_.counter().info());
}
};
-
- class TBinaryWriterImpl final: public writer {
+
+ class TBinaryWriterImpl final: public writer {
public:
- TBinaryWriterImpl(NYsonPull::NOutput::IStream& stream, EStreamType mode)
+ TBinaryWriterImpl(NYsonPull::NOutput::IStream& stream, EStreamType mode)
: writer(stream, mode)
{
}
-
- void OnScalarBoolean(bool value) override {
- update_state(EEventType::Scalar);
-
+
+ void OnScalarBoolean(bool value) override {
+ update_state(EEventType::Scalar);
+
begin_node();
write(value ? NSymbol::true_marker : NSymbol::false_marker);
end_node();
}
-
- void OnScalarInt64(i64 value) override {
- update_state(EEventType::Scalar);
-
+
+ void OnScalarInt64(i64 value) override {
+ update_state(EEventType::Scalar);
+
begin_node();
write(NSymbol::int64_marker);
write_varint(value);
end_node();
}
-
- void OnScalarUInt64(ui64 value) override {
- update_state(EEventType::Scalar);
-
+
+ void OnScalarUInt64(ui64 value) override {
+ update_state(EEventType::Scalar);
+
begin_node();
write(NSymbol::uint64_marker);
write_varint(value);
end_node();
}
-
- void OnScalarFloat64(double value) override {
+
+ void OnScalarFloat64(double value) override {
update_state(EEventType::Scalar);
-
+
begin_node();
write(NSymbol::double_marker);
write_raw(&value, sizeof value);
end_node();
}
-
- void OnScalarString(TStringBuf value) override {
- update_state(EEventType::Scalar);
-
+
+ void OnScalarString(TStringBuf value) override {
+ update_state(EEventType::Scalar);
+
begin_node();
write(NSymbol::string_marker);
write_varint(static_cast<i32>(value.size()));
write_raw(value.data(), value.size());
end_node();
}
-
- void OnKey(TStringBuf name) override {
- update_state(EEventType::Key);
-
+
+ void OnKey(TStringBuf name) override {
+ update_state(EEventType::Key);
+
begin_key();
write(NSymbol::string_marker);
write_varint(static_cast<i32>(name.size()));
@@ -413,50 +413,50 @@ namespace NYsonPull {
end_key();
}
};
-
- class TTextWriterImpl: public writer {
+
+ class TTextWriterImpl: public writer {
public:
- TTextWriterImpl(NYsonPull::NOutput::IStream& stream, EStreamType mode)
+ TTextWriterImpl(NYsonPull::NOutput::IStream& stream, EStreamType mode)
: writer(stream, mode)
{
}
-
- void OnScalarBoolean(bool value) override {
- update_state(EEventType::Scalar);
-
+
+ void OnScalarBoolean(bool value) override {
+ update_state(EEventType::Scalar);
+
begin_node();
write(value ? percent_scalar::true_literal : percent_scalar::false_literal);
end_node();
}
-
- void OnScalarInt64(i64 value) override {
- update_state(EEventType::Scalar);
-
+
+ void OnScalarInt64(i64 value) override {
+ update_state(EEventType::Scalar);
+
char buf[32];
- auto len = ::snprintf(buf, sizeof(buf), "%" PRIi64, value);
-
+ auto len = ::snprintf(buf, sizeof(buf), "%" PRIi64, value);
+
begin_node();
write_raw(buf, len);
end_node();
}
-
- void OnScalarUInt64(ui64 value) override {
- update_state(EEventType::Scalar);
-
+
+ void OnScalarUInt64(ui64 value) override {
+ update_state(EEventType::Scalar);
+
char buf[32];
- auto len = ::snprintf(buf, sizeof(buf), "%" PRIu64, value);
-
+ auto len = ::snprintf(buf, sizeof(buf), "%" PRIu64, value);
+
begin_node();
write_raw(buf, len);
write('u');
end_node();
}
-
- void OnScalarFloat64(double value) override {
- update_state(EEventType::Scalar);
-
+
+ void OnScalarFloat64(double value) override {
+ update_state(EEventType::Scalar);
+
begin_node();
-
+
if (std::isfinite(value)) {
char buf[32];
auto len = ::snprintf(buf, sizeof(buf), "%#.17lg", value);
@@ -467,27 +467,27 @@ namespace NYsonPull {
write(percent_scalar::positive_inf_literal);
} else {
write(percent_scalar::negative_inf_literal);
- }
+ }
end_node();
}
-
- void OnScalarString(TStringBuf value) override {
- update_state(EEventType::Scalar);
-
+
+ void OnScalarString(TStringBuf value) override {
+ update_state(EEventType::Scalar);
+
begin_node();
write_escaped_string(value);
end_node();
}
-
- void OnKey(TStringBuf name) override {
- update_state(EEventType::Key);
-
+
+ void OnKey(TStringBuf name) override {
+ update_state(EEventType::Key);
+
begin_key();
write_escaped_string(name);
end_key();
}
-
+
protected:
void begin_node() override {
if (need_item_separator()) {
@@ -495,7 +495,7 @@ namespace NYsonPull {
write(' ');
}
}
-
+
void end_node() override {
if (mode() != EStreamType::Node && depth() == 0) {
write(NSymbol::item_separator);
@@ -505,26 +505,26 @@ namespace NYsonPull {
writer::end_node();
}
}
-
+
void end_key() override {
write(' ');
writer::end_key();
write(' ');
}
};
-
- class TPrettyWriterImpl final: public TTextWriterImpl {
+
+ class TPrettyWriterImpl final: public TTextWriterImpl {
size_t indent_size_;
-
+
public:
- TPrettyWriterImpl(
+ TPrettyWriterImpl(
NYsonPull::NOutput::IStream& stream,
EStreamType mode,
size_t indent_size)
- : TTextWriterImpl(stream, mode)
+ : TTextWriterImpl(stream, mode)
, indent_size_{indent_size} {
}
-
+
protected:
void begin_node() override {
if (need_item_separator()) {
@@ -532,35 +532,35 @@ namespace NYsonPull {
newline();
}
}
-
+
void begin_collection(collection_type type) override {
- TTextWriterImpl::begin_collection(type);
+ TTextWriterImpl::begin_collection(type);
newline();
}
-
+
void end_collection(collection_type type) override {
- TTextWriterImpl::end_collection(type);
+ TTextWriterImpl::end_collection(type);
newline();
}
-
+
void newline() {
write('\n');
indent(depth());
}
-
+
void indent(size_t count) {
for (size_t i = 0; i < count * indent_size_; ++i) {
write(' ');
}
}
};
-
+
template <typename T, typename... Args>
NYsonPull::TWriter make_writer(
THolder<NYsonPull::NOutput::IStream> stream,
Args&&... args) {
auto impl = MakeHolder<T>(*stream, std::forward<Args>(args)...);
return NYsonPull::TWriter(std::move(stream), std::move(impl));
- }
- }
+ }
+ }
}
diff --git a/library/cpp/yson_pull/detail/zigzag.h b/library/cpp/yson_pull/detail/zigzag.h
index 14917d11b8..98fcac0e9f 100644
--- a/library/cpp/yson_pull/detail/zigzag.h
+++ b/library/cpp/yson_pull/detail/zigzag.h
@@ -1,23 +1,23 @@
-#pragma once
-
-#include "traits.h"
-
+#pragma once
+
+#include "traits.h"
+
namespace NYsonPull {
namespace NDetail {
namespace NZigZag {
//! Functions that provide coding of integers with property: 0 <= f(x) <= 2 * |x|
-
- template <typename TSigned>
- inline NTraits::to_unsigned<TSigned> encode(TSigned x) {
- using TUnsigned = NTraits::to_unsigned<TSigned>;
- constexpr auto rshift = sizeof(TSigned) * 8 - 1;
- return (static_cast<TUnsigned>(x) << 1) ^ static_cast<TUnsigned>(x >> rshift);
+
+ template <typename TSigned>
+ inline NTraits::to_unsigned<TSigned> encode(TSigned x) {
+ using TUnsigned = NTraits::to_unsigned<TSigned>;
+ constexpr auto rshift = sizeof(TSigned) * 8 - 1;
+ return (static_cast<TUnsigned>(x) << 1) ^ static_cast<TUnsigned>(x >> rshift);
}
-
- template <typename TUnsigned>
- inline NTraits::to_signed<TUnsigned> decode(TUnsigned x) {
- using TSigned = NTraits::to_signed<TUnsigned>;
- return static_cast<TSigned>(x >> 1) ^ -static_cast<TSigned>(x & 1);
+
+ template <typename TUnsigned>
+ inline NTraits::to_signed<TUnsigned> decode(TUnsigned x) {
+ using TSigned = NTraits::to_signed<TUnsigned>;
+ return static_cast<TSigned>(x >> 1) ^ -static_cast<TSigned>(x & 1);
}
}
} // namespace NDetail
diff --git a/library/cpp/yson_pull/event.cpp b/library/cpp/yson_pull/event.cpp
index f7d5014608..b7ede494b6 100644
--- a/library/cpp/yson_pull/event.cpp
+++ b/library/cpp/yson_pull/event.cpp
@@ -1,18 +1,18 @@
-#include "event.h"
-
+#include "event.h"
+
#include <library/cpp/yson_pull/detail/cescape.h>
-
-#include <util/stream/output.h>
-
-using namespace NYsonPull;
-
+
+#include <util/stream/output.h>
+
+using namespace NYsonPull;
+
template <>
void Out<TEvent>(IOutputStream& out, const TEvent& value) {
- out << '(' << value.Type();
- if (value.Type() == EEventType::Scalar) {
- out << ' ' << value.AsScalar();
- } else if (value.Type() == EEventType::Key) {
- out << ' ' << NYsonPull::NDetail::NCEscape::quote(value.AsString());
- }
- out << ')';
-}
+ out << '(' << value.Type();
+ if (value.Type() == EEventType::Scalar) {
+ out << ' ' << value.AsScalar();
+ } else if (value.Type() == EEventType::Key) {
+ out << ' ' << NYsonPull::NDetail::NCEscape::quote(value.AsString());
+ }
+ out << ')';
+}
diff --git a/library/cpp/yson_pull/event.h b/library/cpp/yson_pull/event.h
index c8ecca7a45..b41d5ea3b5 100644
--- a/library/cpp/yson_pull/event.h
+++ b/library/cpp/yson_pull/event.h
@@ -1,13 +1,13 @@
-#pragma once
-
-#include "cyson_enums.h"
-#include "scalar.h"
-
-#include <util/generic/strbuf.h>
-#include <util/system/types.h>
-#include <util/system/yassert.h>
-
-namespace NYsonPull {
+#pragma once
+
+#include "cyson_enums.h"
+#include "scalar.h"
+
+#include <util/generic/strbuf.h>
+#include <util/system/types.h>
+#include <util/system/yassert.h>
+
+namespace NYsonPull {
//! A well-formed decoded YSON stream can be described by the following grammar:
//!
//! STREAM[node] ::= begin_stream VALUE end_stream
@@ -21,65 +21,65 @@ namespace NYsonPull {
//! VALUE_NOATTR ::= scalar(Scalar) | LIST | MAP
//! LIST ::= begin_list LIST_FRAGMENT end_list
//! MAP ::= begin_map MAP_FRAGMENT end_map
-
+
//! \brief YSON event type tag. Corresponds to YSON grammar.
enum class EEventType {
- BeginStream = YSON_EVENT_BEGIN_STREAM,
- EndStream = YSON_EVENT_END_STREAM,
- BeginList = YSON_EVENT_BEGIN_LIST,
- EndList = YSON_EVENT_END_LIST,
- BeginMap = YSON_EVENT_BEGIN_MAP,
- EndMap = YSON_EVENT_END_MAP,
- BeginAttributes = YSON_EVENT_BEGIN_ATTRIBUTES,
- EndAttributes = YSON_EVENT_END_ATTRIBUTES,
- Key = YSON_EVENT_KEY,
- Scalar = YSON_EVENT_SCALAR,
+ BeginStream = YSON_EVENT_BEGIN_STREAM,
+ EndStream = YSON_EVENT_END_STREAM,
+ BeginList = YSON_EVENT_BEGIN_LIST,
+ EndList = YSON_EVENT_END_LIST,
+ BeginMap = YSON_EVENT_BEGIN_MAP,
+ EndMap = YSON_EVENT_END_MAP,
+ BeginAttributes = YSON_EVENT_BEGIN_ATTRIBUTES,
+ EndAttributes = YSON_EVENT_END_ATTRIBUTES,
+ Key = YSON_EVENT_KEY,
+ Scalar = YSON_EVENT_SCALAR,
};
-
+
//! \brief YSON event variant type.
class TEvent {
- EEventType Type_;
- TScalar Value_;
-
+ EEventType Type_;
+ TScalar Value_;
+
public:
//! \brief Construct a tag-only event.
- explicit constexpr TEvent(EEventType type = EEventType::BeginStream)
- : Type_{type} {
+ explicit constexpr TEvent(EEventType type = EEventType::BeginStream)
+ : Type_{type} {
}
-
+
//! \brief Construct a tag+value event.
//!
//! Only \p EEventType::key is meaningful.
constexpr TEvent(EEventType type, const TScalar& value)
- : Type_{type}
- , Value_{value} {
+ : Type_{type}
+ , Value_{value} {
}
-
+
//! \brief Construct a \p EEventType::scalar event.
explicit constexpr TEvent(const TScalar& value)
- : Type_{EEventType::Scalar}
- , Value_{value} {
+ : Type_{EEventType::Scalar}
+ , Value_{value} {
}
-
- EEventType Type() const {
- return Type_;
+
+ EEventType Type() const {
+ return Type_;
}
-
+
//! \brief Get TScalar value.
//!
//! Undefined behaviour when event type is not \p EEventType::scalar.
- const TScalar& AsScalar() const {
- Y_ASSERT(Type_ == EEventType::Scalar || Type_ == EEventType::Key);
- return Value_;
+ const TScalar& AsScalar() const {
+ Y_ASSERT(Type_ == EEventType::Scalar || Type_ == EEventType::Key);
+ return Value_;
}
-
+
//! \brief Get string value.
//!
//! Undefined behaviour when event type is not \p EEventType::key.
- TStringBuf AsString() const {
- Y_ASSERT(Type_ == EEventType::Key || (Type_ == EEventType::Scalar && Value_.Type() == EScalarType::String));
- return Value_.AsString();
+ TStringBuf AsString() const {
+ Y_ASSERT(Type_ == EEventType::Key || (Type_ == EEventType::Scalar && Value_.Type() == EScalarType::String));
+ return Value_.AsString();
}
};
-
+
}
diff --git a/library/cpp/yson_pull/exceptions.cpp b/library/cpp/yson_pull/exceptions.cpp
index dde4df4c35..e1d68493e7 100644
--- a/library/cpp/yson_pull/exceptions.cpp
+++ b/library/cpp/yson_pull/exceptions.cpp
@@ -1,45 +1,45 @@
-#include "exceptions.h"
-
-#include <util/string/builder.h>
-
-#include <cerrno>
-#include <cstring>
-
-using namespace NYsonPull::NException;
-
-const char* TBadStream::what() const noexcept {
- TStringBuilder stream;
- stream << "Invalid YSON";
- if (Position_.Offset || Position_.Line || Position_.Column) {
- bool first = true;
- stream << " at ";
- if (Position_.Offset) {
- stream << "offset " << *Position_.Offset;
- first = false;
- }
- if (Position_.Line) {
- if (!first) {
- stream << ", ";
- }
- stream << "line " << *Position_.Line;
- first = false;
- }
- if (Position_.Column) {
- if (!first) {
- stream << ", ";
- }
- stream << "column " << *Position_.Column;
- }
- }
- stream << ": " << Message_;
- FormattedMessage_ = stream;
- return FormattedMessage_.c_str();
-}
-
+#include "exceptions.h"
+
+#include <util/string/builder.h>
+
+#include <cerrno>
+#include <cstring>
+
+using namespace NYsonPull::NException;
+
+const char* TBadStream::what() const noexcept {
+ TStringBuilder stream;
+ stream << "Invalid YSON";
+ if (Position_.Offset || Position_.Line || Position_.Column) {
+ bool first = true;
+ stream << " at ";
+ if (Position_.Offset) {
+ stream << "offset " << *Position_.Offset;
+ first = false;
+ }
+ if (Position_.Line) {
+ if (!first) {
+ stream << ", ";
+ }
+ stream << "line " << *Position_.Line;
+ first = false;
+ }
+ if (Position_.Column) {
+ if (!first) {
+ stream << ", ";
+ }
+ stream << "column " << *Position_.Column;
+ }
+ }
+ stream << ": " << Message_;
+ FormattedMessage_ = stream;
+ return FormattedMessage_.c_str();
+}
+
NYsonPull::NException::TSystemError::TSystemError()
- : SavedErrno_{errno} {
+ : SavedErrno_{errno} {
+}
+
+const char* NYsonPull::NException::TSystemError::what() const noexcept {
+ return ::strerror(SavedErrno_);
}
-
-const char* NYsonPull::NException::TSystemError::what() const noexcept {
- return ::strerror(SavedErrno_);
-}
diff --git a/library/cpp/yson_pull/exceptions.h b/library/cpp/yson_pull/exceptions.h
index 12dbd0013d..ebfed950a5 100644
--- a/library/cpp/yson_pull/exceptions.h
+++ b/library/cpp/yson_pull/exceptions.h
@@ -1,58 +1,58 @@
-#pragma once
-
-#include "position_info.h"
-
+#pragma once
+
+#include "position_info.h"
+
#include <util/generic/string.h>
-
-#include <stdexcept>
-#include <string>
-
+
+#include <stdexcept>
+#include <string>
+
namespace NYsonPull {
namespace NException {
class TBadStream: public std::exception {
TString Message_;
- TPositionInfo Position_;
+ TPositionInfo Position_;
mutable TString FormattedMessage_;
-
+
public:
TBadStream(
TString message,
const TPositionInfo& position)
- : Message_(std::move(message))
- , Position_(position)
+ : Message_(std::move(message))
+ , Position_(position)
{
}
-
- const TPositionInfo& Position() const {
- return Position_;
+
+ const TPositionInfo& Position() const {
+ return Position_;
}
-
+
const char* what() const noexcept override;
};
-
+
class TBadInput: public TBadStream {
public:
using TBadStream::TBadStream;
};
-
+
class TBadOutput: public TBadStream {
public:
using TBadStream::TBadStream;
};
-
+
class TSystemError: public std::exception {
- int SavedErrno_;
-
+ int SavedErrno_;
+
public:
TSystemError();
TSystemError(int saved_errno)
- : SavedErrno_{saved_errno} {
+ : SavedErrno_{saved_errno} {
}
-
+
int saved_errno() const noexcept {
- return SavedErrno_;
+ return SavedErrno_;
}
-
+
const char* what() const noexcept override;
};
}
diff --git a/library/cpp/yson_pull/input.cpp b/library/cpp/yson_pull/input.cpp
index c0ee776e64..1373c89868 100644
--- a/library/cpp/yson_pull/input.cpp
+++ b/library/cpp/yson_pull/input.cpp
@@ -1,33 +1,33 @@
-#include "input.h"
-
+#include "input.h"
+
#include <library/cpp/yson_pull/detail/input/stdio_file.h>
#include <library/cpp/yson_pull/detail/input/stream.h>
-
-#include <util/generic/ptr.h>
-#include <util/stream/file.h>
-#include <util/stream/mem.h>
-
-using namespace NYsonPull::NInput;
-using namespace NYsonPull::NDetail::NInput;
-
-namespace NInput = NYsonPull::NInput;
-
-THolder<IStream> NInput::FromStdioFile(FILE* file, size_t buffer_size) {
- return MakeHolder<TStdioFile>(file, buffer_size);
-}
-
-THolder<IStream> NInput::FromPosixFd(int fd, size_t buffer_size) {
- return MakeHolder<TFHandle>(fd, buffer_size);
-}
-
-THolder<IStream> NInput::FromMemory(TStringBuf data) {
- return MakeHolder<TOwned<TMemoryInput>>(data);
-}
-
+
+#include <util/generic/ptr.h>
+#include <util/stream/file.h>
+#include <util/stream/mem.h>
+
+using namespace NYsonPull::NInput;
+using namespace NYsonPull::NDetail::NInput;
+
+namespace NInput = NYsonPull::NInput;
+
+THolder<IStream> NInput::FromStdioFile(FILE* file, size_t buffer_size) {
+ return MakeHolder<TStdioFile>(file, buffer_size);
+}
+
+THolder<IStream> NInput::FromPosixFd(int fd, size_t buffer_size) {
+ return MakeHolder<TFHandle>(fd, buffer_size);
+}
+
+THolder<IStream> NInput::FromMemory(TStringBuf data) {
+ return MakeHolder<TOwned<TMemoryInput>>(data);
+}
+
THolder<IStream> NInput::FromInputStream(IInputStream* input, size_t buffer_size) {
- return MakeHolder<TOwned<TBufferedInput>>(input, buffer_size);
-}
-
+ return MakeHolder<TOwned<TBufferedInput>>(input, buffer_size);
+}
+
THolder<IStream> NInput::FromZeroCopyInput(IZeroCopyInput* input) {
- return MakeHolder<TZeroCopy>(input);
-}
+ return MakeHolder<TZeroCopy>(input);
+}
diff --git a/library/cpp/yson_pull/input.h b/library/cpp/yson_pull/input.h
index f060c29535..2cdfae857e 100644
--- a/library/cpp/yson_pull/input.h
+++ b/library/cpp/yson_pull/input.h
@@ -1,18 +1,18 @@
-#pragma once
-
-#include "buffer.h"
-
-#include <util/generic/ptr.h>
-#include <util/generic/strbuf.h>
-#include <util/system/types.h>
-#include <util/system/yassert.h>
-
-#include <cstddef>
-#include <memory>
-
+#pragma once
+
+#include "buffer.h"
+
+#include <util/generic/ptr.h>
+#include <util/generic/strbuf.h>
+#include <util/system/types.h>
+#include <util/system/yassert.h>
+
+#include <cstddef>
+#include <memory>
+
class IInputStream;
class IZeroCopyInput;
-
+
namespace NYsonPull {
namespace NInput {
//! \brief Input stream adaptor interface.
@@ -21,33 +21,33 @@ namespace NYsonPull {
class IStream {
input_buffer buffer_;
bool at_end_ = false;
-
+
public:
virtual ~IStream() = default;
-
+
bool at_end() const {
return at_end_;
}
-
+
input_buffer& buffer() noexcept {
return buffer_;
}
const input_buffer& buffer() const noexcept {
return buffer_;
}
-
+
void fill_buffer() {
while (buffer_.is_empty() && !at_end()) {
at_end_ = do_fill_buffer() == result::at_end;
}
}
-
+
protected:
enum class result {
have_more_data, //! May continue reading
at_end, //! Reached end of stream
};
-
+
//! \brief Read next chunk of data.
//!
//! The implementation is to discard the buffer contents
@@ -57,25 +57,25 @@ namespace NYsonPull {
//! Read is assumed to always succeed unless it throws an exception.
virtual result do_fill_buffer() = 0;
};
-
+
//! \brief Read data from a contiguous memory block (i.e. a string)
//!
//! Does not take ownership on memory.
- THolder<IStream> FromMemory(TStringBuf data);
-
+ THolder<IStream> FromMemory(TStringBuf data);
+
//! \brief Read data from C FILE* object.
//!
//! Does not take ownership on file object.
//! Data is buffered internally regardless of file buffering.
- THolder<IStream> FromStdioFile(FILE* file, size_t buffer_size = 65536);
-
+ THolder<IStream> FromStdioFile(FILE* file, size_t buffer_size = 65536);
+
//! \brief Read data from POSIX file descriptor.
//!
//! Does not take ownership on streambuf.
- THolder<IStream> FromPosixFd(int fd, size_t buffer_size = 65536);
-
+ THolder<IStream> FromPosixFd(int fd, size_t buffer_size = 65536);
+
THolder<IStream> FromZeroCopyInput(IZeroCopyInput* input);
-
+
THolder<IStream> FromInputStream(IInputStream* input, size_t buffer_size = 65536);
}
}
diff --git a/library/cpp/yson_pull/output.cpp b/library/cpp/yson_pull/output.cpp
index c036606f35..27c9ef9e69 100644
--- a/library/cpp/yson_pull/output.cpp
+++ b/library/cpp/yson_pull/output.cpp
@@ -1,29 +1,29 @@
-#include "output.h"
-
+#include "output.h"
+
#include <library/cpp/yson_pull/detail/output/stdio_file.h>
#include <library/cpp/yson_pull/detail/output/stream.h>
-
-#include <util/generic/ptr.h>
-#include <util/stream/file.h>
-#include <util/stream/str.h>
-
-using namespace NYsonPull::NOutput;
-using namespace NYsonPull::NDetail::NOutput;
-
-namespace NOutput = NYsonPull::NOutput;
-
-THolder<IStream> NOutput::FromStdioFile(FILE* file, size_t buffer_size) {
- return MakeHolder<TStdioFile>(file, buffer_size);
-}
-
-THolder<IStream> NOutput::FromPosixFd(int fd, size_t buffer_size) {
- return MakeHolder<TFHandle>(fd, buffer_size);
-}
-
+
+#include <util/generic/ptr.h>
+#include <util/stream/file.h>
+#include <util/stream/str.h>
+
+using namespace NYsonPull::NOutput;
+using namespace NYsonPull::NDetail::NOutput;
+
+namespace NOutput = NYsonPull::NOutput;
+
+THolder<IStream> NOutput::FromStdioFile(FILE* file, size_t buffer_size) {
+ return MakeHolder<TStdioFile>(file, buffer_size);
+}
+
+THolder<IStream> NOutput::FromPosixFd(int fd, size_t buffer_size) {
+ return MakeHolder<TFHandle>(fd, buffer_size);
+}
+
THolder<IStream> NOutput::FromString(TString* output, size_t buffer_size) {
- return MakeHolder<TOwned<TStringOutput>>(buffer_size, *output);
-}
-
+ return MakeHolder<TOwned<TStringOutput>>(buffer_size, *output);
+}
+
THolder<IStream> NOutput::FromOutputStream(IOutputStream* output, size_t buffer_size) {
- return MakeHolder<TStream>(output, buffer_size);
-}
+ return MakeHolder<TStream>(output, buffer_size);
+}
diff --git a/library/cpp/yson_pull/output.h b/library/cpp/yson_pull/output.h
index 62412a2f4d..2d78107a93 100644
--- a/library/cpp/yson_pull/output.h
+++ b/library/cpp/yson_pull/output.h
@@ -1,35 +1,35 @@
-#pragma once
-
-#include "buffer.h"
-
-#include <util/generic/ptr.h>
-#include <util/generic/strbuf.h>
-#include <util/system/types.h>
-#include <util/system/yassert.h>
-
-#include <cstddef>
-#include <cstdio>
-#include <cstring>
-#include <memory>
-
-//! \brief Output stream adaptor interface.
-//!
-//! Represents a model of an optionally-buffered writer.
+#pragma once
+
+#include "buffer.h"
+
+#include <util/generic/ptr.h>
+#include <util/generic/strbuf.h>
+#include <util/system/types.h>
+#include <util/system/yassert.h>
+
+#include <cstddef>
+#include <cstdio>
+#include <cstring>
+#include <memory>
+
+//! \brief Output stream adaptor interface.
+//!
+//! Represents a model of an optionally-buffered writer.
namespace NYsonPull {
namespace NOutput {
class IStream {
output_buffer buffer_;
-
+
public:
virtual ~IStream() = default;
-
+
output_buffer& buffer() noexcept {
return buffer_;
}
const output_buffer& buffer() const noexcept {
return buffer_;
}
-
+
void flush_buffer(TStringBuf extra = {}) {
if (!extra.empty() || !buffer_.is_empty()) {
do_flush_buffer(extra);
@@ -38,7 +38,7 @@ namespace NYsonPull {
do_flush_buffer({});
}
}
-
+
protected:
//! \brief Flush data to underlying stream.
//!
@@ -51,15 +51,15 @@ namespace NYsonPull {
//! Write is assumed to always succeed unless it throws an exception.
virtual void do_flush_buffer(TStringBuf extra) = 0;
};
-
- //! \brief Write data to C FILE* object.
- THolder<IStream> FromStdioFile(FILE* file, size_t buffer_size = 0);
-
- //! \brief Write data to POSIX file descriptor
- THolder<IStream> FromPosixFd(int fd, size_t buffer_size = 65536);
-
+
+ //! \brief Write data to C FILE* object.
+ THolder<IStream> FromStdioFile(FILE* file, size_t buffer_size = 0);
+
+ //! \brief Write data to POSIX file descriptor
+ THolder<IStream> FromPosixFd(int fd, size_t buffer_size = 65536);
+
THolder<IStream> FromOutputStream(IOutputStream* output, size_t buffer_size = 65536);
-
+
THolder<IStream> FromString(TString* output, size_t buffer_size = 1024);
}
}
diff --git a/library/cpp/yson_pull/position_info.h b/library/cpp/yson_pull/position_info.h
index 3401fe94ee..a65c4663a9 100644
--- a/library/cpp/yson_pull/position_info.h
+++ b/library/cpp/yson_pull/position_info.h
@@ -1,23 +1,23 @@
-#pragma once
-
-#include <util/generic/maybe.h>
+#pragma once
+
+#include <util/generic/maybe.h>
#include <util/system/types.h>
-
-namespace NYsonPull {
+
+namespace NYsonPull {
struct TPositionInfo {
- TMaybe<ui64> Offset;
- TMaybe<ui64> Line;
- TMaybe<ui64> Column;
-
+ TMaybe<ui64> Offset;
+ TMaybe<ui64> Line;
+ TMaybe<ui64> Column;
+
TPositionInfo() = default;
TPositionInfo(
TMaybe<ui64> offset_,
TMaybe<ui64> line_ = Nothing(),
TMaybe<ui64> column_ = Nothing())
- : Offset{offset_}
- , Line{line_}
- , Column{column_} {
+ : Offset{offset_}
+ , Line{line_}
+ , Column{column_} {
}
};
-
+
}
diff --git a/library/cpp/yson_pull/range.h b/library/cpp/yson_pull/range.h
index d602d79911..f4fcf3f206 100644
--- a/library/cpp/yson_pull/range.h
+++ b/library/cpp/yson_pull/range.h
@@ -1,35 +1,35 @@
-#pragma once
-
-#include "reader.h"
-
-#include <util/generic/iterator.h>
-
-namespace NYsonPull {
+#pragma once
+
+#include "reader.h"
+
+#include <util/generic/iterator.h>
+
+namespace NYsonPull {
class TStreamEventsRange: public TInputRangeAdaptor<TStreamEventsRange> {
TReader Reader_;
bool AtEnd;
-
+
public:
- TStreamEventsRange(THolder<NInput::IStream> stream, EStreamType mode)
+ TStreamEventsRange(THolder<NInput::IStream> stream, EStreamType mode)
: Reader_{std::move(stream), mode}
, AtEnd(false)
{
}
-
+
const TEvent* Last() const noexcept {
- return &Reader_.LastEvent();
+ return &Reader_.LastEvent();
}
-
+
const TEvent* Next() {
if (Y_UNLIKELY(AtEnd)) {
return nullptr;
}
-
- auto* event = &Reader_.NextEvent();
- if (event->Type() == EEventType::EndStream) {
+
+ auto* event = &Reader_.NextEvent();
+ if (event->Type() == EEventType::EndStream) {
AtEnd = true;
}
return event;
- }
+ }
};
}
diff --git a/library/cpp/yson_pull/read_ops.cpp b/library/cpp/yson_pull/read_ops.cpp
index 9fa1fe79b3..9d7e6a4a2d 100644
--- a/library/cpp/yson_pull/read_ops.cpp
+++ b/library/cpp/yson_pull/read_ops.cpp
@@ -1,66 +1,66 @@
-#include "read_ops.h"
-
-using namespace NYsonPull;
-using namespace NYsonPull::NReadOps;
-
-namespace {
+#include "read_ops.h"
+
+using namespace NYsonPull;
+using namespace NYsonPull::NReadOps;
+
+namespace {
bool TrySkipValueUntil(EEventType end, TReader& reader) {
- const auto& event = reader.NextEvent();
- if (event.Type() == end) {
+ const auto& event = reader.NextEvent();
+ if (event.Type() == end) {
return false;
}
SkipCurrentValue(event, reader);
return true;
}
-
+
bool TrySkipKeyValueUntil(EEventType end, TReader& reader) {
- const auto& event = reader.NextEvent();
- if (event.Type() == end) {
+ const auto& event = reader.NextEvent();
+ if (event.Type() == end) {
return false;
}
- Expect(event, EEventType::Key);
+ Expect(event, EEventType::Key);
SkipValue(reader);
return true;
}
-}
-
-void NYsonPull::NReadOps::SkipCurrentValue(const TEvent& event, TReader& reader) {
- switch (event.Type()) {
- case EEventType::BeginList:
- while (TrySkipValueUntil(EEventType::EndList, reader)) {
+}
+
+void NYsonPull::NReadOps::SkipCurrentValue(const TEvent& event, TReader& reader) {
+ switch (event.Type()) {
+ case EEventType::BeginList:
+ while (TrySkipValueUntil(EEventType::EndList, reader)) {
}
return;
-
- case EEventType::BeginMap:
- while (TrySkipKeyValueUntil(EEventType::EndMap, reader)) {
+
+ case EEventType::BeginMap:
+ while (TrySkipKeyValueUntil(EEventType::EndMap, reader)) {
}
return;
-
- case EEventType::BeginAttributes:
- while (TrySkipKeyValueUntil(EEventType::EndAttributes, reader)) {
+
+ case EEventType::BeginAttributes:
+ while (TrySkipKeyValueUntil(EEventType::EndAttributes, reader)) {
}
// attributes after attributes are disallowed in TReader
SkipValue(reader);
return;
-
- case EEventType::Scalar:
+
+ case EEventType::Scalar:
return;
-
+
default:
throw yexception() << "Unexpected event: " << event;
}
-}
-
-void NYsonPull::NReadOps::SkipValue(TReader& reader) {
- const auto& event = reader.NextEvent();
+}
+
+void NYsonPull::NReadOps::SkipValue(TReader& reader) {
+ const auto& event = reader.NextEvent();
SkipCurrentValue(event, reader);
-}
-
-void NYsonPull::NReadOps::SkipControlRecords(TReader& reader) {
- const auto* event = &reader.LastEvent();
- while (event->Type() == EEventType::BeginAttributes) {
- SkipCurrentValue(*event, reader);
- event = &reader.NextEvent();
- }
- Expect(*event, EEventType::BeginMap);
-}
+}
+
+void NYsonPull::NReadOps::SkipControlRecords(TReader& reader) {
+ const auto* event = &reader.LastEvent();
+ while (event->Type() == EEventType::BeginAttributes) {
+ SkipCurrentValue(*event, reader);
+ event = &reader.NextEvent();
+ }
+ Expect(*event, EEventType::BeginMap);
+}
diff --git a/library/cpp/yson_pull/read_ops.h b/library/cpp/yson_pull/read_ops.h
index 91d8e3700d..5c084983ea 100644
--- a/library/cpp/yson_pull/read_ops.h
+++ b/library/cpp/yson_pull/read_ops.h
@@ -1,142 +1,142 @@
-#pragma once
-
-#include "reader.h"
-
-#include <util/generic/maybe.h>
-#include <util/generic/bt_exception.h>
-#include <util/generic/yexception.h>
-#include <util/system/yassert.h>
-
-/** Imperative recursive-descent parsing helpers.
- *
- * These functions help verify conditions and advance parser state.
- * For aggregate parsing functions, common precondition is to require Begin{X}
- * event prior to function invocation. Thus, parsers are composable by calling
- * sub-parser after dispatching on opening event, e.g.:
- *
- * if (reader.LastEvent().Type() == EEventType::BeginMap) {
- * ReadSomeMap(reader)
- * }
- *
- */
-
+#pragma once
+
+#include "reader.h"
+
+#include <util/generic/maybe.h>
+#include <util/generic/bt_exception.h>
+#include <util/generic/yexception.h>
+#include <util/system/yassert.h>
+
+/** Imperative recursive-descent parsing helpers.
+ *
+ * These functions help verify conditions and advance parser state.
+ * For aggregate parsing functions, common precondition is to require Begin{X}
+ * event prior to function invocation. Thus, parsers are composable by calling
+ * sub-parser after dispatching on opening event, e.g.:
+ *
+ * if (reader.LastEvent().Type() == EEventType::BeginMap) {
+ * ReadSomeMap(reader)
+ * }
+ *
+ */
+
namespace NYsonPull {
namespace NReadOps {
class TExpectationFailure: public TWithBackTrace<yexception> {
- };
-
+ };
+
inline void Expect(const TEvent& got, EEventType expected) {
- Y_ENSURE_EX(
- got.Type() == expected,
- TExpectationFailure() << "expected " << expected << ", got " << got);
+ Y_ENSURE_EX(
+ got.Type() == expected,
+ TExpectationFailure() << "expected " << expected << ", got " << got);
}
-
+
inline void Expect(const TScalar& got, EScalarType expected) {
- Y_ENSURE_EX(
- got.Type() == expected,
- TExpectationFailure() << "expected scalar " << expected << ", got " << got);
- }
-
- // ExpectBegin{X} functions verify that last event WAS X
- // SkipBegin{X} functions verify that next event WILL BE X and CONSUME it
-
- inline void ExpectBeginStream(TReader& reader) {
- Expect(reader.LastEvent(), EEventType::BeginStream);
- }
-
- inline void SkipBeginStream(TReader& reader) {
- Expect(reader.NextEvent(), EEventType::BeginStream);
- }
-
+ Y_ENSURE_EX(
+ got.Type() == expected,
+ TExpectationFailure() << "expected scalar " << expected << ", got " << got);
+ }
+
+ // ExpectBegin{X} functions verify that last event WAS X
+ // SkipBegin{X} functions verify that next event WILL BE X and CONSUME it
+
+ inline void ExpectBeginStream(TReader& reader) {
+ Expect(reader.LastEvent(), EEventType::BeginStream);
+ }
+
+ inline void SkipBeginStream(TReader& reader) {
+ Expect(reader.NextEvent(), EEventType::BeginStream);
+ }
+
inline void ExpectBeginMap(TReader& reader) {
- Expect(reader.LastEvent(), EEventType::BeginMap);
+ Expect(reader.LastEvent(), EEventType::BeginMap);
}
-
+
inline void SkipBeginMap(TReader& reader) {
- Expect(reader.NextEvent(), EEventType::BeginMap);
+ Expect(reader.NextEvent(), EEventType::BeginMap);
}
-
+
inline void ExpectBeginList(TReader& reader) {
- Expect(reader.LastEvent(), EEventType::BeginList);
+ Expect(reader.LastEvent(), EEventType::BeginList);
}
-
+
inline void SkipBeginList(TReader& reader) {
- Expect(reader.NextEvent(), EEventType::BeginList);
+ Expect(reader.NextEvent(), EEventType::BeginList);
}
-
+
inline bool ReadListItem(TReader& reader) {
- return reader.NextEvent().Type() != EEventType::EndList;
+ return reader.NextEvent().Type() != EEventType::EndList;
}
-
+
inline TMaybe<TStringBuf> ReadKey(TReader& reader) {
- const auto& event = reader.NextEvent();
- switch (event.Type()) {
- case EEventType::Key:
- return event.AsString();
- case EEventType::EndMap:
+ const auto& event = reader.NextEvent();
+ switch (event.Type()) {
+ case EEventType::Key:
+ return event.AsString();
+ case EEventType::EndMap:
return Nothing();
default:
ythrow yexception() << "Unexpected event: " << event;
}
}
-
+
template <typename T = const TScalar&>
inline T ReadScalar(TReader& reader);
-
+
template <>
inline const TScalar& ReadScalar<const TScalar&>(TReader& reader) {
- const auto& event = reader.NextEvent();
- Expect(event, EEventType::Scalar);
- return event.AsScalar();
+ const auto& event = reader.NextEvent();
+ Expect(event, EEventType::Scalar);
+ return event.AsScalar();
}
-
+
template <>
inline i64 ReadScalar<i64>(TReader& reader) {
const auto& scalar = ReadScalar(reader);
- Expect(scalar, EScalarType::Int64);
- return scalar.AsInt64();
+ Expect(scalar, EScalarType::Int64);
+ return scalar.AsInt64();
}
-
+
template <>
inline ui64 ReadScalar<ui64>(TReader& reader) {
const auto& scalar = ReadScalar(reader);
- Expect(scalar, EScalarType::UInt64);
- return scalar.AsUInt64();
+ Expect(scalar, EScalarType::UInt64);
+ return scalar.AsUInt64();
}
-
+
template <>
inline double ReadScalar<double>(TReader& reader) {
const auto& scalar = ReadScalar(reader);
- Expect(scalar, EScalarType::Float64);
- return scalar.AsFloat64();
+ Expect(scalar, EScalarType::Float64);
+ return scalar.AsFloat64();
}
-
+
template <>
inline TStringBuf ReadScalar<TStringBuf>(TReader& reader) {
const auto& scalar = ReadScalar(reader);
- Expect(scalar, EScalarType::String);
- return scalar.AsString();
+ Expect(scalar, EScalarType::String);
+ return scalar.AsString();
}
-
+
template <>
inline TString ReadScalar<TString>(TReader& reader) {
return TString(ReadScalar<TStringBuf>(reader));
}
-
+
template <>
inline bool ReadScalar<bool>(TReader& reader) {
const auto& scalar = ReadScalar(reader);
- Expect(scalar, EScalarType::Boolean);
- return scalar.AsBoolean();
+ Expect(scalar, EScalarType::Boolean);
+ return scalar.AsBoolean();
}
-
+
// Skip value that was already started with `event`
void SkipCurrentValue(const TEvent& event, TReader& reader);
-
+
// Skip value that starts at `reader.next_event()`
void SkipValue(TReader& reader);
-
- // Skip values with attributes, wait for map value
- void SkipControlRecords(TReader& reader);
+
+ // Skip values with attributes, wait for map value
+ void SkipControlRecords(TReader& reader);
}
}
diff --git a/library/cpp/yson_pull/reader.cpp b/library/cpp/yson_pull/reader.cpp
index 655ab8e4ad..ea26852756 100644
--- a/library/cpp/yson_pull/reader.cpp
+++ b/library/cpp/yson_pull/reader.cpp
@@ -1,27 +1,27 @@
-#include "reader.h"
+#include "reader.h"
#include <library/cpp/yson_pull/detail/reader.h>
-
-using namespace NYsonPull;
-
-TReader::TReader(
- THolder<NInput::IStream> stream,
+
+using namespace NYsonPull;
+
+TReader::TReader(
+ THolder<NInput::IStream> stream,
EStreamType mode)
- : Stream_{std::move(stream)}
- , Impl_{MakeHolder<NDetail::reader_impl>(*Stream_, mode)} {
+ : Stream_{std::move(stream)}
+ , Impl_{MakeHolder<NDetail::reader_impl>(*Stream_, mode)} {
}
-
+
TReader::TReader(TReader&& other) noexcept
- : Stream_{std::move(other.Stream_)}
- , Impl_{std::move(other.Impl_)} {
+ : Stream_{std::move(other.Stream_)}
+ , Impl_{std::move(other.Impl_)} {
}
-
+
TReader::~TReader() {
}
-
-const TEvent& TReader::NextEvent() {
- return Impl_->next_event();
-}
-
-const TEvent& TReader::LastEvent() const noexcept {
- return Impl_->last_event();
-}
+
+const TEvent& TReader::NextEvent() {
+ return Impl_->next_event();
+}
+
+const TEvent& TReader::LastEvent() const noexcept {
+ return Impl_->last_event();
+}
diff --git a/library/cpp/yson_pull/reader.h b/library/cpp/yson_pull/reader.h
index ad47fa0ea2..f839b19071 100644
--- a/library/cpp/yson_pull/reader.h
+++ b/library/cpp/yson_pull/reader.h
@@ -1,37 +1,37 @@
-#pragma once
-
-#include "event.h"
-#include "input.h"
-#include "stream_type.h"
-
-#include <util/system/yassert.h>
-
-#include <memory>
-
-namespace NYsonPull {
+#pragma once
+
+#include "event.h"
+#include "input.h"
+#include "stream_type.h"
+
+#include <util/system/yassert.h>
+
+#include <memory>
+
+namespace NYsonPull {
namespace NDetail {
class reader_impl;
}
-
+
//! \brief YSON reader facade class.
//!
//! Owns an input stream.
class TReader {
- THolder<NInput::IStream> Stream_;
- THolder<NDetail::reader_impl> Impl_;
-
+ THolder<NInput::IStream> Stream_;
+ THolder<NDetail::reader_impl> Impl_;
+
public:
TReader(THolder<NInput::IStream> stream, EStreamType mode);
TReader(TReader&&) noexcept;
~TReader();
-
+
//! \brief Advance stream to next event and return it.
//!
- //! Any event data is invalidated by a call to NextEvent();
- const TEvent& NextEvent();
-
+ //! Any event data is invalidated by a call to NextEvent();
+ const TEvent& NextEvent();
+
//! \brief Get last returned event.
- const TEvent& LastEvent() const noexcept;
+ const TEvent& LastEvent() const noexcept;
};
-
+
}
diff --git a/library/cpp/yson_pull/scalar.cpp b/library/cpp/yson_pull/scalar.cpp
index adc24ba8d3..4325542e7a 100644
--- a/library/cpp/yson_pull/scalar.cpp
+++ b/library/cpp/yson_pull/scalar.cpp
@@ -1,57 +1,57 @@
-#include "scalar.h"
-
+#include "scalar.h"
+
#include <library/cpp/yson_pull/detail/cescape.h>
-
-#include <util/stream/output.h>
-
-using namespace NYsonPull;
-
+
+#include <util/stream/output.h>
+
+using namespace NYsonPull;
+
template <>
void Out<TScalar>(IOutputStream& out, const TScalar& value) {
- out << '(' << value.Type();
- if (value.Type() != EScalarType::Entity) {
- out << ' ';
- }
- switch (value.Type()) {
- case EScalarType::Boolean:
- out << (value.AsBoolean() ? "true" : "false");
- break;
- case EScalarType::String:
- out << NYsonPull::NDetail::NCEscape::quote(value.AsString());
- break;
- case EScalarType::Int64:
- out << value.AsInt64();
- break;
- case EScalarType::UInt64:
- out << value.AsUInt64();
- break;
- case EScalarType::Float64:
- out << value.AsFloat64();
- break;
+ out << '(' << value.Type();
+ if (value.Type() != EScalarType::Entity) {
+ out << ' ';
+ }
+ switch (value.Type()) {
+ case EScalarType::Boolean:
+ out << (value.AsBoolean() ? "true" : "false");
+ break;
+ case EScalarType::String:
+ out << NYsonPull::NDetail::NCEscape::quote(value.AsString());
+ break;
+ case EScalarType::Int64:
+ out << value.AsInt64();
+ break;
+ case EScalarType::UInt64:
+ out << value.AsUInt64();
+ break;
+ case EScalarType::Float64:
+ out << value.AsFloat64();
+ break;
default:
break;
- }
- out << ')';
-}
-
+ }
+ out << ')';
+}
+
bool NYsonPull::operator==(const TScalar& left, const TScalar& right) noexcept {
- if (left.Type() != right.Type()) {
- return false;
- }
- switch (left.Type()) {
- case EScalarType::Boolean:
- return left.AsBoolean() == right.AsBoolean();
- case EScalarType::String:
- return left.AsString() == right.AsString();
- case EScalarType::Int64:
- return left.AsInt64() == right.AsInt64();
- case EScalarType::UInt64:
- return left.AsUInt64() == right.AsUInt64();
- case EScalarType::Float64:
- return left.AsFloat64() == right.AsFloat64();
- case EScalarType::Entity:
- return true;
+ if (left.Type() != right.Type()) {
+ return false;
+ }
+ switch (left.Type()) {
+ case EScalarType::Boolean:
+ return left.AsBoolean() == right.AsBoolean();
+ case EScalarType::String:
+ return left.AsString() == right.AsString();
+ case EScalarType::Int64:
+ return left.AsInt64() == right.AsInt64();
+ case EScalarType::UInt64:
+ return left.AsUInt64() == right.AsUInt64();
+ case EScalarType::Float64:
+ return left.AsFloat64() == right.AsFloat64();
+ case EScalarType::Entity:
+ return true;
default:
- Y_UNREACHABLE();
- }
-}
+ Y_UNREACHABLE();
+ }
+}
diff --git a/library/cpp/yson_pull/scalar.h b/library/cpp/yson_pull/scalar.h
index 35d5d08379..509fce8b5e 100644
--- a/library/cpp/yson_pull/scalar.h
+++ b/library/cpp/yson_pull/scalar.h
@@ -1,146 +1,146 @@
-#pragma once
-
-#include "cyson_enums.h"
-
-#include <util/generic/strbuf.h>
-#include <util/system/types.h>
-#include <util/system/yassert.h>
-
-namespace NYsonPull {
+#pragma once
+
+#include "cyson_enums.h"
+
+#include <util/generic/strbuf.h>
+#include <util/system/types.h>
+#include <util/system/yassert.h>
+
+namespace NYsonPull {
//! \brief YSON TScalar value type tag
enum class EScalarType {
- Entity = YSON_SCALAR_ENTITY,
- Boolean = YSON_SCALAR_BOOLEAN,
- Int64 = YSON_SCALAR_INT64,
- UInt64 = YSON_SCALAR_UINT64,
- Float64 = YSON_SCALAR_FLOAT64,
- String = YSON_SCALAR_STRING,
+ Entity = YSON_SCALAR_ENTITY,
+ Boolean = YSON_SCALAR_BOOLEAN,
+ Int64 = YSON_SCALAR_INT64,
+ UInt64 = YSON_SCALAR_UINT64,
+ Float64 = YSON_SCALAR_FLOAT64,
+ String = YSON_SCALAR_STRING,
};
-
+
//! \brief YSON TScalar value variant
class TScalar {
//! \internal \brief YSON TScalar value underlying representation
- union TScalarValue {
- struct TScalarStringRef {
- const char* Data;
- size_t Size;
+ union TScalarValue {
+ struct TScalarStringRef {
+ const char* Data;
+ size_t Size;
};
-
+
ui8 AsNothing[1];
- bool AsBoolean;
- i64 AsInt64;
- ui64 AsUInt64;
- double AsFloat64;
- TScalarStringRef AsString;
-
- constexpr TScalarValue()
- : AsNothing{} {
+ bool AsBoolean;
+ i64 AsInt64;
+ ui64 AsUInt64;
+ double AsFloat64;
+ TScalarStringRef AsString;
+
+ constexpr TScalarValue()
+ : AsNothing{} {
}
-
- explicit constexpr TScalarValue(bool value)
- : AsBoolean{value} {
+
+ explicit constexpr TScalarValue(bool value)
+ : AsBoolean{value} {
}
-
- explicit constexpr TScalarValue(i64 value)
- : AsInt64{value} {
+
+ explicit constexpr TScalarValue(i64 value)
+ : AsInt64{value} {
}
-
- explicit constexpr TScalarValue(ui64 value)
- : AsUInt64{value} {
+
+ explicit constexpr TScalarValue(ui64 value)
+ : AsUInt64{value} {
}
-
- explicit constexpr TScalarValue(double value)
- : AsFloat64{value} {
+
+ explicit constexpr TScalarValue(double value)
+ : AsFloat64{value} {
}
-
- explicit constexpr TScalarValue(TStringBuf value)
- : AsString{value.data(), value.size()} {
+
+ explicit constexpr TScalarValue(TStringBuf value)
+ : AsString{value.data(), value.size()} {
}
};
static_assert(
- sizeof(TScalarValue) == sizeof(TStringBuf),
+ sizeof(TScalarValue) == sizeof(TStringBuf),
"bad scalar_value size");
-
- EScalarType Type_;
- TScalarValue Value_;
-
+
+ EScalarType Type_;
+ TScalarValue Value_;
+
public:
constexpr TScalar()
- : Type_{EScalarType::Entity} {
+ : Type_{EScalarType::Entity} {
}
-
+
explicit constexpr TScalar(bool value)
- : Type_{EScalarType::Boolean}
- , Value_{value} {
+ : Type_{EScalarType::Boolean}
+ , Value_{value} {
}
-
+
explicit constexpr TScalar(i64 value)
- : Type_{EScalarType::Int64}
- , Value_{value} {
+ : Type_{EScalarType::Int64}
+ , Value_{value} {
}
-
+
explicit constexpr TScalar(ui64 value)
- : Type_{EScalarType::UInt64}
- , Value_{value} {
+ : Type_{EScalarType::UInt64}
+ , Value_{value} {
}
-
+
explicit constexpr TScalar(double value)
- : Type_{EScalarType::Float64}
- , Value_{value} {
+ : Type_{EScalarType::Float64}
+ , Value_{value} {
}
-
+
explicit constexpr TScalar(TStringBuf value)
- : Type_{EScalarType::String}
- , Value_{value} {
+ : Type_{EScalarType::String}
+ , Value_{value} {
}
-
+
// Disambiguation for literal constants
// In the absence of this constructor,
// they get implicitly converted to bool (yikes!)
explicit TScalar(const char* value)
- : Type_{EScalarType::String}
- , Value_{TStringBuf{value}} {
+ : Type_{EScalarType::String}
+ , Value_{TStringBuf{value}} {
}
-
- EScalarType Type() const {
- return Type_;
+
+ EScalarType Type() const {
+ return Type_;
}
-
-#define CAST_TO(Type) \
- Y_ASSERT(Type_ == EScalarType::Type); \
- return Value_.As##Type
-
- bool AsBoolean() const {
- CAST_TO(Boolean);
+
+#define CAST_TO(Type) \
+ Y_ASSERT(Type_ == EScalarType::Type); \
+ return Value_.As##Type
+
+ bool AsBoolean() const {
+ CAST_TO(Boolean);
}
- i64 AsInt64() const {
- CAST_TO(Int64);
+ i64 AsInt64() const {
+ CAST_TO(Int64);
}
- ui64 AsUInt64() const {
- CAST_TO(UInt64);
+ ui64 AsUInt64() const {
+ CAST_TO(UInt64);
}
- double AsFloat64() const {
- CAST_TO(Float64);
+ double AsFloat64() const {
+ CAST_TO(Float64);
}
-#undef CAST_TO
-
- TStringBuf AsString() const {
- Y_ASSERT(Type_ == EScalarType::String);
+#undef CAST_TO
+
+ TStringBuf AsString() const {
+ Y_ASSERT(Type_ == EScalarType::String);
return TStringBuf{
- Value_.AsString.Data,
- Value_.AsString.Size,
+ Value_.AsString.Data,
+ Value_.AsString.Size,
};
}
-
- const TScalarValue& AsUnsafeValue() const {
- return Value_;
+
+ const TScalarValue& AsUnsafeValue() const {
+ return Value_;
}
};
-
+
bool operator==(const TScalar& left, const TScalar& right) noexcept;
-
+
inline bool operator!=(const TScalar& left, const TScalar& right) noexcept {
return !(left == right);
}
-
+
}
diff --git a/library/cpp/yson_pull/stream_type.h b/library/cpp/yson_pull/stream_type.h
index bb8b26c9a2..beac87fe1b 100644
--- a/library/cpp/yson_pull/stream_type.h
+++ b/library/cpp/yson_pull/stream_type.h
@@ -1,8 +1,8 @@
-#pragma once
-
-#include "cyson_enums.h"
-
-namespace NYsonPull {
+#pragma once
+
+#include "cyson_enums.h"
+
+namespace NYsonPull {
enum class EStreamType {
Node = YSON_STREAM_TYPE_NODE,
ListFragment = YSON_STREAM_TYPE_LIST_FRAGMENT,
diff --git a/library/cpp/yson_pull/ut/cescape_ut.cpp b/library/cpp/yson_pull/ut/cescape_ut.cpp
index 50b0f6ff09..6628ba1d15 100644
--- a/library/cpp/yson_pull/ut/cescape_ut.cpp
+++ b/library/cpp/yson_pull/ut/cescape_ut.cpp
@@ -1,10 +1,10 @@
#include <library/cpp/yson_pull/detail/cescape.h>
-
+
#include <library/cpp/testing/unittest/registar.h>
-
-using namespace NYsonPull::NDetail;
-
-namespace {
+
+using namespace NYsonPull::NDetail;
+
+namespace {
void test_roundtrip(const TVector<ui8>& str) {
TStringBuf str_buf(
reinterpret_cast<const char*>(str.data()),
@@ -17,7 +17,7 @@ namespace {
<< "B[" << tmp.size() << "]: " << tmp << '\n'
<< "C[" << dest.size() << "]: " << dest);
}
-
+
template <size_t N>
void test_exhaustive(TVector<ui8>& str) {
for (int i = 0; i < 256; ++i) {
@@ -25,33 +25,33 @@ namespace {
test_exhaustive<N - 1>(str);
}
}
-
+
template <>
void test_exhaustive<0>(TVector<ui8>& str) {
test_roundtrip(str);
- }
-
+ }
+
template <size_t N>
void test_exhaustive() {
TVector<ui8> str(N, ' ');
test_exhaustive<N>(str);
}
-
-} // anonymous namespace
-
+
+} // anonymous namespace
+
Y_UNIT_TEST_SUITE(CEscape) {
Y_UNIT_TEST(ExhaustiveOneChar) {
test_exhaustive<1>();
}
-
+
Y_UNIT_TEST(ExhaustiveTwoChars) {
test_exhaustive<2>();
}
-
+
Y_UNIT_TEST(ExhaustiveThreeChars) {
test_exhaustive<3>();
}
-
+
Y_UNIT_TEST(SpecialEscapeEncode) {
//UNIT_ASSERT_VALUES_EQUAL(R"(\b)", NCEscape::encode("\b"));
//UNIT_ASSERT_VALUES_EQUAL(R"(\f)", NCEscape::encode("\f"));
@@ -59,7 +59,7 @@ Y_UNIT_TEST_SUITE(CEscape) {
UNIT_ASSERT_VALUES_EQUAL(R"(\r)", NCEscape::encode("\r"));
UNIT_ASSERT_VALUES_EQUAL(R"(\t)", NCEscape::encode("\t"));
}
-
+
Y_UNIT_TEST(SpecialEscapeDecode) {
UNIT_ASSERT_VALUES_EQUAL("\b", NCEscape::decode(R"(\b)"));
UNIT_ASSERT_VALUES_EQUAL("\f", NCEscape::decode(R"(\f)"));
@@ -67,5 +67,5 @@ Y_UNIT_TEST_SUITE(CEscape) {
UNIT_ASSERT_VALUES_EQUAL("\r", NCEscape::decode(R"(\r)"));
UNIT_ASSERT_VALUES_EQUAL("\t", NCEscape::decode(R"(\t)"));
}
-
+
} // Y_UNIT_TEST_SUITE(CEscape)
diff --git a/library/cpp/yson_pull/ut/loop_ut.cpp b/library/cpp/yson_pull/ut/loop_ut.cpp
index b7f4086ba2..8c7b11dd1c 100644
--- a/library/cpp/yson_pull/ut/loop_ut.cpp
+++ b/library/cpp/yson_pull/ut/loop_ut.cpp
@@ -2,18 +2,18 @@
#include <library/cpp/yson_pull/output.h>
#include <library/cpp/yson_pull/reader.h>
#include <library/cpp/yson_pull/writer.h>
-
+
#include <library/cpp/testing/unittest/registar.h>
-
-#include <cerrno>
-#include <cmath>
-
-#ifdef _unix_
-#include <unistd.h>
-#include <sys/wait.h>
-#endif
-
-namespace {
+
+#include <cerrno>
+#include <cmath>
+
+#ifdef _unix_
+#include <unistd.h>
+#include <sys/wait.h>
+#endif
+
+namespace {
constexpr const char* alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
@@ -30,215 +30,215 @@ namespace {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-
+
void generate(NYsonPull::TWriter& writer, size_t count) {
- writer.BeginStream();
+ writer.BeginStream();
for (size_t i = 0; i < count; ++i) {
- writer.BeginMap()
- .Key("ints")
- .BeginList()
- .Int64(0)
- .Int64(-1)
- .Int64(1000)
- .Int64(-1000)
- .EndList()
- .Key("uints")
- .BeginList()
- .UInt64(0)
- .UInt64(1000)
- .UInt64(10000000)
- .EndList()
- .Key("entities")
- .BeginList()
- .Entity()
- .BeginAttributes()
- .Key("color")
- .String("blue")
- .Key("size")
- .Int64(100)
- .EndAttributes()
- .Entity()
- .Entity()
- .EndList()
- .Key("booleans")
- .BeginList()
- .Boolean(true)
- .Boolean(false)
- .Boolean(true)
- .EndList()
- .Key("floats")
- .BeginList()
- .Float64(0.0)
- .Float64(13.0e30)
- .Float64(M_PI)
- .EndList()
- .Key("strings")
- .BeginList()
- .String("hello")
- .String("")
- .String("foo \"-bar-\" baz")
- .String("oh\nwow")
- .String(alphabet)
- .EndList()
- .EndMap();
+ writer.BeginMap()
+ .Key("ints")
+ .BeginList()
+ .Int64(0)
+ .Int64(-1)
+ .Int64(1000)
+ .Int64(-1000)
+ .EndList()
+ .Key("uints")
+ .BeginList()
+ .UInt64(0)
+ .UInt64(1000)
+ .UInt64(10000000)
+ .EndList()
+ .Key("entities")
+ .BeginList()
+ .Entity()
+ .BeginAttributes()
+ .Key("color")
+ .String("blue")
+ .Key("size")
+ .Int64(100)
+ .EndAttributes()
+ .Entity()
+ .Entity()
+ .EndList()
+ .Key("booleans")
+ .BeginList()
+ .Boolean(true)
+ .Boolean(false)
+ .Boolean(true)
+ .EndList()
+ .Key("floats")
+ .BeginList()
+ .Float64(0.0)
+ .Float64(13.0e30)
+ .Float64(M_PI)
+ .EndList()
+ .Key("strings")
+ .BeginList()
+ .String("hello")
+ .String("")
+ .String("foo \"-bar-\" baz")
+ .String("oh\nwow")
+ .String(alphabet)
+ .EndList()
+ .EndMap();
}
- writer.EndStream();
- }
-
-#ifdef __clang__
+ writer.EndStream();
+ }
+
+#ifdef __clang__
// XXX: With all the macros below (esp. UNIT_ASSERT_VALUES_EQUAL) unfolded,
// the time it takes clang to optimize generated code becomes abysmal.
// Locally disabling optimization brings it back to normal.
__attribute__((optnone))
-#endif // __clang__
+#endif // __clang__
void
verify(NYsonPull::TReader& reader, size_t count) {
#define NEXT(name__) \
{ \
- auto& name__ = reader.NextEvent(); // SCOPED_TRACE(e);
-#define END_NEXT }
+ auto& name__ = reader.NextEvent(); // SCOPED_TRACE(e);
+#define END_NEXT }
#define NEXT_TYPE(type__) \
NEXT(e) { \
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::type__, e.Type()); \
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::type__, e.Type()); \
} \
END_NEXT
#define NEXT_KEY(key__) \
NEXT(e) { \
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type()); \
- UNIT_ASSERT_VALUES_EQUAL(key__, e.AsString()); \
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type()); \
+ UNIT_ASSERT_VALUES_EQUAL(key__, e.AsString()); \
} \
END_NEXT
-#define NEXT_SCALAR(type__, value__) \
- NEXT(e) { \
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type()); \
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EScalarType::type__, e.AsScalar().Type()); \
- UNIT_ASSERT_VALUES_EQUAL(value__, e.AsScalar().As##type__()); \
- } \
+#define NEXT_SCALAR(type__, value__) \
+ NEXT(e) { \
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type()); \
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EScalarType::type__, e.AsScalar().Type()); \
+ UNIT_ASSERT_VALUES_EQUAL(value__, e.AsScalar().As##type__()); \
+ } \
+ END_NEXT
+#define NEXT_ENTITY() \
+ NEXT(e) { \
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type()); \
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EScalarType::Entity, e.AsScalar().Type()); \
+ } \
END_NEXT
-#define NEXT_ENTITY() \
- NEXT(e) { \
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type()); \
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EScalarType::Entity, e.AsScalar().Type()); \
- } \
- END_NEXT
-#define NEXT_FLOAT64(value__) \
+#define NEXT_FLOAT64(value__) \
NEXT(e) { \
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type()); \
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EScalarType::Float64, e.AsScalar().Type()); \
- UNIT_ASSERT_DOUBLES_EQUAL(value__, e.AsScalar().AsFloat64(), 1e-5); \
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type()); \
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EScalarType::Float64, e.AsScalar().Type()); \
+ UNIT_ASSERT_DOUBLES_EQUAL(value__, e.AsScalar().AsFloat64(), 1e-5); \
} \
END_NEXT
-
+
constexpr auto true_ = true;
constexpr auto false_ = false;
-
- NEXT_TYPE(BeginStream);
+
+ NEXT_TYPE(BeginStream);
for (size_t i = 0; i < count; ++i) {
- NEXT_TYPE(BeginMap);
+ NEXT_TYPE(BeginMap);
NEXT_KEY("ints") {
- NEXT_TYPE(BeginList);
- NEXT_SCALAR(Int64, 0);
- NEXT_SCALAR(Int64, -1);
- NEXT_SCALAR(Int64, 1000);
- NEXT_SCALAR(Int64, -1000);
- NEXT_TYPE(EndList);
+ NEXT_TYPE(BeginList);
+ NEXT_SCALAR(Int64, 0);
+ NEXT_SCALAR(Int64, -1);
+ NEXT_SCALAR(Int64, 1000);
+ NEXT_SCALAR(Int64, -1000);
+ NEXT_TYPE(EndList);
}
NEXT_KEY("uints") {
- NEXT_TYPE(BeginList);
- NEXT_SCALAR(UInt64, 0U);
- NEXT_SCALAR(UInt64, 1000U);
- NEXT_SCALAR(UInt64, 10000000U);
- NEXT_TYPE(EndList);
+ NEXT_TYPE(BeginList);
+ NEXT_SCALAR(UInt64, 0U);
+ NEXT_SCALAR(UInt64, 1000U);
+ NEXT_SCALAR(UInt64, 10000000U);
+ NEXT_TYPE(EndList);
}
NEXT_KEY("entities") {
- NEXT_TYPE(BeginList);
+ NEXT_TYPE(BeginList);
NEXT_ENTITY();
- NEXT_TYPE(BeginAttributes) {
+ NEXT_TYPE(BeginAttributes) {
NEXT_KEY("color") {
- NEXT_SCALAR(String, "blue");
+ NEXT_SCALAR(String, "blue");
}
NEXT_KEY("size") {
- NEXT_SCALAR(Int64, 100);
+ NEXT_SCALAR(Int64, 100);
}
- }
- NEXT_TYPE(EndAttributes);
+ }
+ NEXT_TYPE(EndAttributes);
NEXT_ENTITY();
NEXT_ENTITY();
- NEXT_TYPE(EndList);
+ NEXT_TYPE(EndList);
}
NEXT_KEY("booleans") {
- NEXT_TYPE(BeginList);
- NEXT_SCALAR(Boolean, true_);
- NEXT_SCALAR(Boolean, false_);
- NEXT_SCALAR(Boolean, true_);
- NEXT_TYPE(EndList);
+ NEXT_TYPE(BeginList);
+ NEXT_SCALAR(Boolean, true_);
+ NEXT_SCALAR(Boolean, false_);
+ NEXT_SCALAR(Boolean, true_);
+ NEXT_TYPE(EndList);
}
NEXT_KEY("floats") {
- NEXT_TYPE(BeginList);
+ NEXT_TYPE(BeginList);
NEXT_FLOAT64(0.0);
NEXT_FLOAT64(13.0e30);
NEXT_FLOAT64(M_PI);
- NEXT_TYPE(EndList);
+ NEXT_TYPE(EndList);
}
NEXT_KEY("strings") {
- NEXT_TYPE(BeginList);
- NEXT_SCALAR(String, "hello");
- NEXT_SCALAR(String, "");
- NEXT_SCALAR(String, "foo \"-bar-\" baz");
- NEXT_SCALAR(String, "oh\nwow");
- NEXT_SCALAR(String, alphabet);
- NEXT_TYPE(EndList);
+ NEXT_TYPE(BeginList);
+ NEXT_SCALAR(String, "hello");
+ NEXT_SCALAR(String, "");
+ NEXT_SCALAR(String, "foo \"-bar-\" baz");
+ NEXT_SCALAR(String, "oh\nwow");
+ NEXT_SCALAR(String, alphabet);
+ NEXT_TYPE(EndList);
}
- NEXT_TYPE(EndMap);
- }
- NEXT_TYPE(EndStream);
-
-#undef NEXT
-#undef END_NEXT
-#undef NEXT_TYPE
-#undef NEXT_KEY
-#undef NEXT_SCALAR
+ NEXT_TYPE(EndMap);
+ }
+ NEXT_TYPE(EndStream);
+
+#undef NEXT
+#undef END_NEXT
+#undef NEXT_TYPE
+#undef NEXT_KEY
+#undef NEXT_SCALAR
}
-
+
class sys_error {};
-
+
IOutputStream& operator<<(IOutputStream& stream, const sys_error&) {
stream << strerror(errno);
return stream;
}
-
- NYsonPull::TReader make_reader(THolder<NYsonPull::NInput::IStream> stream) {
- return NYsonPull::TReader(
- std::move(stream),
- NYsonPull::EStreamType::ListFragment);
- }
-
- template <typename Function>
- void test_memory(Function make_writer, size_t nrepeat) {
+
+ NYsonPull::TReader make_reader(THolder<NYsonPull::NInput::IStream> stream) {
+ return NYsonPull::TReader(
+ std::move(stream),
+ NYsonPull::EStreamType::ListFragment);
+ }
+
+ template <typename Function>
+ void test_memory(Function make_writer, size_t nrepeat) {
TString text;
- {
- auto writer = make_writer(NYsonPull::NOutput::FromString(&text));
- generate(writer, nrepeat);
- }
- {
- auto reader = make_reader(NYsonPull::NInput::FromMemory(text));
- verify(reader, nrepeat);
- }
- {
- TStringInput input(text);
- auto reader = make_reader(NYsonPull::NInput::FromInputStream(&input, /* buffer_size = */ 1));
- verify(reader, nrepeat);
- }
- }
-
-#ifdef _unix_
+ {
+ auto writer = make_writer(NYsonPull::NOutput::FromString(&text));
+ generate(writer, nrepeat);
+ }
+ {
+ auto reader = make_reader(NYsonPull::NInput::FromMemory(text));
+ verify(reader, nrepeat);
+ }
+ {
+ TStringInput input(text);
+ auto reader = make_reader(NYsonPull::NInput::FromInputStream(&input, /* buffer_size = */ 1));
+ verify(reader, nrepeat);
+ }
+ }
+
+#ifdef _unix_
template <typename Here, typename There>
void pipe(Here&& reader, There&& writer) {
int fildes[2];
UNIT_ASSERT_VALUES_EQUAL_C(0, ::pipe(fildes), sys_error());
auto read_fd = fildes[0];
auto write_fd = fildes[1];
-
+
auto pid = ::fork();
UNIT_ASSERT_C(pid >= 0, sys_error());
if (pid > 0) {
@@ -255,8 +255,8 @@ namespace {
}
int stat_loc;
UNIT_ASSERT_VALUES_EQUAL_C(pid, ::waitpid(pid, &stat_loc, 0), sys_error());
- }
-
+ }
+
template <typename Function>
void test_posix_fd(
Function make_writer,
@@ -265,15 +265,15 @@ namespace {
size_t write_buffer_size) {
pipe(
[&](int fd) {
- auto reader = make_reader(NYsonPull::NInput::FromPosixFd(fd, read_buffer_size));
+ auto reader = make_reader(NYsonPull::NInput::FromPosixFd(fd, read_buffer_size));
verify(reader, nrepeat);
},
[&](int fd) {
- auto writer = make_writer(NYsonPull::NOutput::FromPosixFd(fd, write_buffer_size));
+ auto writer = make_writer(NYsonPull::NOutput::FromPosixFd(fd, write_buffer_size));
generate(writer, nrepeat);
});
}
-
+
template <typename Function>
void test_stdio_file(
Function make_writer,
@@ -284,99 +284,99 @@ namespace {
[&](int fd) {
auto file = ::fdopen(fd, "rb");
UNIT_ASSERT_C(file != nullptr, sys_error());
- auto reader = make_reader(NYsonPull::NInput::FromStdioFile(file, read_buffer_size));
+ auto reader = make_reader(NYsonPull::NInput::FromStdioFile(file, read_buffer_size));
verify(reader, nrepeat);
},
[&](int fd) {
auto file = ::fdopen(fd, "wb");
Y_UNUSED(write_buffer_size);
- auto writer = make_writer(NYsonPull::NOutput::FromStdioFile(file, write_buffer_size));
+ auto writer = make_writer(NYsonPull::NOutput::FromStdioFile(file, write_buffer_size));
generate(writer, nrepeat);
fflush(file);
});
}
-#endif
-
+#endif
+
NYsonPull::TWriter text(THolder<NYsonPull::NOutput::IStream> stream) {
- return NYsonPull::MakeTextWriter(
+ return NYsonPull::MakeTextWriter(
std::move(stream),
NYsonPull::EStreamType::ListFragment);
}
-
+
NYsonPull::TWriter pretty_text(THolder<NYsonPull::NOutput::IStream> stream) {
- return NYsonPull::MakePrettyTextWriter(
+ return NYsonPull::MakePrettyTextWriter(
std::move(stream),
NYsonPull::EStreamType::ListFragment);
}
-
+
NYsonPull::TWriter binary(THolder<NYsonPull::NOutput::IStream> stream) {
- return NYsonPull::MakeBinaryWriter(
+ return NYsonPull::MakeBinaryWriter(
std::move(stream),
NYsonPull::EStreamType::ListFragment);
}
-} // anonymous namespace
-
+} // anonymous namespace
+
Y_UNIT_TEST_SUITE(Loop) {
Y_UNIT_TEST(memory_pretty_text) {
test_memory(pretty_text, 100);
}
-
+
Y_UNIT_TEST(memory_text) {
test_memory(text, 100);
}
-
+
Y_UNIT_TEST(memory_binary) {
test_memory(binary, 100);
}
-
-#ifdef _unix_
+
+#ifdef _unix_
Y_UNIT_TEST(posix_fd_pretty_text_buffered) {
test_posix_fd(pretty_text, 100, 1024, 1024);
}
-
+
Y_UNIT_TEST(posix_fd_pretty_text_unbuffered) {
test_posix_fd(pretty_text, 100, 1, 0);
}
-
+
Y_UNIT_TEST(posix_fd_text_buffered) {
test_posix_fd(text, 100, 1024, 1024);
}
-
+
Y_UNIT_TEST(posix_fd_text_unbuffered) {
test_posix_fd(text, 100, 1, 0);
}
-
+
Y_UNIT_TEST(posix_fd_binary_buffered) {
test_posix_fd(binary, 100, 1024, 1024);
}
-
+
Y_UNIT_TEST(posix_fd_binary_unbuffered) {
test_posix_fd(binary, 100, 1, 0);
}
-
+
Y_UNIT_TEST(stdio_file_pretty_text_buffered) {
test_stdio_file(pretty_text, 100, 1024, 1024);
}
-
+
Y_UNIT_TEST(stdio_file_pretty_text_unbuffered) {
test_stdio_file(pretty_text, 100, 1, 0);
}
-
+
Y_UNIT_TEST(stdio_file_text_buffered) {
test_stdio_file(text, 100, 1024, 1024);
}
-
+
Y_UNIT_TEST(stdio_file_text_unbuffered) {
test_stdio_file(text, 100, 1, 0);
}
-
+
Y_UNIT_TEST(stdio_file_binary_buffered) {
test_stdio_file(binary, 100, 1024, 1024);
}
-
+
Y_UNIT_TEST(stdio_file_binary_unbuffered) {
test_stdio_file(binary, 100, 1, 0);
}
-#endif
+#endif
} // Y_UNIT_TEST_SUITE(Loop)
diff --git a/library/cpp/yson_pull/ut/reader_ut.cpp b/library/cpp/yson_pull/ut/reader_ut.cpp
index c8853f0ec9..1184265ddb 100644
--- a/library/cpp/yson_pull/ut/reader_ut.cpp
+++ b/library/cpp/yson_pull/ut/reader_ut.cpp
@@ -3,24 +3,24 @@
#include <library/cpp/yson_pull/reader.h>
#include <library/cpp/yson_pull/detail/cescape.h>
#include <library/cpp/yson_pull/detail/macros.h>
-
+
#include <library/cpp/testing/unittest/registar.h>
-
-namespace {
+
+namespace {
NYsonPull::TReader memory_reader(TStringBuf data, NYsonPull::EStreamType mode) {
return NYsonPull::TReader(
NYsonPull::NInput::FromMemory(data),
mode);
}
-
+
template <typename T>
void expect_scalar(const NYsonPull::TScalar& scalar, T value) {
UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{value}, scalar);
}
-
+
template <>
void expect_scalar(const NYsonPull::TScalar& scalar, double value) {
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EScalarType::Float64, scalar.Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EScalarType::Float64, scalar.Type());
auto scalarValue = scalar.AsFloat64();
auto message = TStringBuilder() << "expected " << value << ", got " << scalarValue;
@@ -36,55 +36,55 @@ namespace {
UNIT_ASSERT_C(std::isinf(scalarValue) && (scalarValue < 0), message);
}
}
-
+
template <typename T>
void test_scalar(TStringBuf data, T value) {
// SCOPED_TRACE(NYsonPull::detail::cescape::quote(data));
auto reader = memory_reader(data, NYsonPull::EStreamType::Node);
-
+
try {
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginStream, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginStream, reader.NextEvent().Type());
{
- auto& event = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, event.Type());
- expect_scalar(event.AsScalar(), value);
+ auto& event = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, event.Type());
+ expect_scalar(event.AsScalar(), value);
}
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndStream, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndStream, reader.NextEvent().Type());
} catch (const std::exception& err) {
UNIT_FAIL(err.what());
- }
- }
-
+ }
+ }
+
void consume(TStringBuf data, NYsonPull::EStreamType mode = NYsonPull::EStreamType::Node) {
// SCOPED_TRACE(NYsonPull::detail::cescape::quote(data));
- auto input_range = NYsonPull::TStreamEventsRange(
+ auto input_range = NYsonPull::TStreamEventsRange(
NYsonPull::NInput::FromMemory(data),
mode);
for (auto& event : input_range) {
Y_UNUSED(event);
}
- }
-
-#define ACCEPT(data) UNIT_ASSERT_NO_EXCEPTION(consume(data))
-#define REJECT(data) UNIT_ASSERT_EXCEPTION(consume(data), NYsonPull::NException::TBadInput)
-
-#define ACCEPT2(data, mode) UNIT_ASSERT_NO_EXCEPTION(consume(data, mode))
-#define REJECT2(data, mode) UNIT_ASSERT_EXCEPTION(consume(data, mode), NYsonPull::NException::TBadInput)
-
-} // anonymous namespace
-
+ }
+
+#define ACCEPT(data) UNIT_ASSERT_NO_EXCEPTION(consume(data))
+#define REJECT(data) UNIT_ASSERT_EXCEPTION(consume(data), NYsonPull::NException::TBadInput)
+
+#define ACCEPT2(data, mode) UNIT_ASSERT_NO_EXCEPTION(consume(data, mode))
+#define REJECT2(data, mode) UNIT_ASSERT_EXCEPTION(consume(data, mode), NYsonPull::NException::TBadInput)
+
+} // anonymous namespace
+
Y_UNIT_TEST_SUITE(Reader) {
Y_UNIT_TEST(ScalarEntity) {
test_scalar(TStringBuf("#"), NYsonPull::TScalar{});
}
-
+
Y_UNIT_TEST(ScalarBoolean) {
test_scalar(TStringBuf("%true"), true);
test_scalar(TStringBuf("%false"), false);
-
+
test_scalar(TStringBuf("\x05"sv), true);
test_scalar(TStringBuf("\x04"sv), false);
-
+
REJECT("%");
REJECT("%trueth");
REJECT("%tru");
@@ -92,7 +92,7 @@ Y_UNIT_TEST_SUITE(Reader) {
REJECT("%fals");
REJECT("%hithere");
}
-
+
Y_UNIT_TEST(ScalarInt64) {
test_scalar(TStringBuf("1"), i64{1});
test_scalar(TStringBuf("+1"), i64{1});
@@ -101,17 +101,17 @@ Y_UNIT_TEST_SUITE(Reader) {
test_scalar(TStringBuf("-100000"), i64{-100000});
test_scalar(TStringBuf("9223372036854775807"), i64{9223372036854775807});
test_scalar(TStringBuf("+9223372036854775807"), i64{9223372036854775807});
-
+
test_scalar(TStringBuf("\x02\x02"sv), i64{1});
test_scalar(TStringBuf("\x02\xc0\x9a\x0c"sv), i64{100000});
test_scalar(TStringBuf("\x02\xbf\x9a\x0c"sv), i64{-100000});
test_scalar(TStringBuf("\x02\xfe\xff\xff\xff\xff\xff\xff\xff\xff\x01"sv), i64{9223372036854775807});
-
+
REJECT("1a2");
REJECT("1-1-1-1");
REJECT("1+0");
}
-
+
Y_UNIT_TEST(SclarUInt64) {
test_scalar(TStringBuf("1u"), ui64{1});
test_scalar(TStringBuf("+1u"), ui64{1});
@@ -121,14 +121,14 @@ Y_UNIT_TEST_SUITE(Reader) {
test_scalar(TStringBuf("+9223372036854775807u"), ui64{9223372036854775807u});
test_scalar(TStringBuf("18446744073709551615u"), ui64{18446744073709551615u});
test_scalar(TStringBuf("+18446744073709551615u"), ui64{18446744073709551615u});
-
+
REJECT("1a2u");
REJECT("1-1-1-1u");
REJECT("1+0u");
-
+
// TODO: binary
}
-
+
Y_UNIT_TEST(ScalarFloat64) {
test_scalar(TStringBuf("0.0"), double{0.0});
test_scalar(TStringBuf("+0.0"), double{0.0});
@@ -148,19 +148,19 @@ Y_UNIT_TEST_SUITE(Reader) {
test_scalar(TStringBuf("1e-12"), double{1e-12});
test_scalar(TStringBuf("+1e-12"), double{1e-12});
test_scalar(TStringBuf("-1e-12"), double{-1e-12});
-
+
test_scalar(TStringBuf("\x03\x00\x00\x00\x00\x00\x00\x00\x00"sv), double{0.0});
-
- test_scalar(
+
+ test_scalar(
TStringBuf("\x03\x00\x00\x00\x00\x00\x00\xf8\x7f"sv),
double{std::numeric_limits<double>::quiet_NaN()});
test_scalar(
TStringBuf("\x03\x00\x00\x00\x00\x00\x00\xf0\x7f"sv),
- double{std::numeric_limits<double>::infinity()});
- test_scalar(
+ double{std::numeric_limits<double>::infinity()});
+ test_scalar(
TStringBuf("\x03\x00\x00\x00\x00\x00\x00\xf0\xff"sv),
- double{-std::numeric_limits<double>::infinity()});
-
+ double{-std::numeric_limits<double>::infinity()});
+
test_scalar(
TStringBuf("%nan"),
double{std::numeric_limits<double>::quiet_NaN()});
@@ -170,14 +170,14 @@ Y_UNIT_TEST_SUITE(Reader) {
test_scalar(
TStringBuf("%-inf"),
double{-std::numeric_limits<double>::infinity()});
-
+
REJECT("++0.0");
REJECT("++1.0");
REJECT("++.1");
REJECT("1.0.0");
//REJECT("1e+10000");
REJECT(TStringBuf("\x03\x00\x00\x00\x00\x00\x00\x00"sv));
-
+
// XXX: Questionable behaviour?
ACCEPT("+.0");
ACCEPT("-.0");
@@ -192,7 +192,7 @@ Y_UNIT_TEST_SUITE(Reader) {
REJECT("%in");
REJECT("%-in");
}
-
+
Y_UNIT_TEST(ScalarString) {
test_scalar(TStringBuf(R"(foobar)"), TStringBuf("foobar"));
test_scalar(TStringBuf(R"(foobar11)"), TStringBuf("foobar11"));
@@ -200,115 +200,115 @@ Y_UNIT_TEST_SUITE(Reader) {
// wat? "\x0cf" parsed as a single char? no way!
test_scalar("\x01\x0c" "foobar"sv,
TStringBuf("foobar"));
-
+
REJECT(R"("foobar)");
REJECT("\x01\x0c" "fooba"sv);
REJECT("\x01\x0d" "foobar"sv); // negative length
}
-
+
Y_UNIT_TEST(EmptyList) {
auto reader = memory_reader("[]", NYsonPull::EStreamType::Node);
-
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginStream, reader.NextEvent().Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginList, reader.NextEvent().Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndList, reader.NextEvent().Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndStream, reader.NextEvent().Type());
-
+
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginStream, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginList, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndList, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndStream, reader.NextEvent().Type());
+
REJECT("[");
REJECT("]");
}
-
+
Y_UNIT_TEST(EmptyMap) {
auto reader = memory_reader("{}", NYsonPull::EStreamType::Node);
-
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginStream, reader.NextEvent().Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginMap, reader.NextEvent().Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndMap, reader.NextEvent().Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndStream, reader.NextEvent().Type());
-
+
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginStream, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginMap, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndMap, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndStream, reader.NextEvent().Type());
+
REJECT("{");
REJECT("}");
}
-
+
Y_UNIT_TEST(Sample) {
auto reader = memory_reader(
R"({"11"=11;"nothing"=#;"zero"=0.;"foo"="bar";"list"=[1;2;3]})",
NYsonPull::EStreamType::Node);
-
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginStream, reader.NextEvent().Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginMap, reader.NextEvent().Type());
-
+
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginStream, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginMap, reader.NextEvent().Type());
+
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type());
UNIT_ASSERT_VALUES_EQUAL(TStringBuf("11"), e.AsString());
}
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{i64{11}}, e.AsScalar());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{i64{11}}, e.AsScalar());
}
-
+
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type());
UNIT_ASSERT_VALUES_EQUAL(TStringBuf("nothing"), e.AsString());
}
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{}, e.AsScalar());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{}, e.AsScalar());
}
-
+
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type());
UNIT_ASSERT_VALUES_EQUAL(TStringBuf("zero"), e.AsString());
}
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{0.0}, e.AsScalar());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{0.0}, e.AsScalar());
}
-
+
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type());
UNIT_ASSERT_VALUES_EQUAL(TStringBuf("foo"), e.AsString());
}
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{TStringBuf("bar")}, e.AsScalar());
}
-
+
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Key, e.Type());
UNIT_ASSERT_VALUES_EQUAL(TStringBuf("list"), e.AsString());
}
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginList, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginList, reader.NextEvent().Type());
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{i64{1}}, e.AsScalar());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{i64{1}}, e.AsScalar());
}
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{i64{2}}, e.AsScalar());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{i64{2}}, e.AsScalar());
}
{
- auto& e = reader.NextEvent();
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{i64{3}}, e.AsScalar());
+ auto& e = reader.NextEvent();
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, e.Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::TScalar{i64{3}}, e.AsScalar());
}
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndList, reader.NextEvent().Type());
-
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndMap, reader.NextEvent().Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndStream, reader.NextEvent().Type());
- }
-
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndList, reader.NextEvent().Type());
+
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndMap, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndStream, reader.NextEvent().Type());
+ }
+
Y_UNIT_TEST(Accept) {
ACCEPT("[]");
ACCEPT("{}");
@@ -318,7 +318,7 @@ Y_UNIT_TEST_SUITE(Reader) {
ACCEPT("[{};{};{};]");
ACCEPT("[<>{};<>{};<>{}]");
ACCEPT("[<>{};<>{};<>{};]");
-
+
ACCEPT("foo");
ACCEPT("[foo]");
ACCEPT("[foo;]");
@@ -328,83 +328,83 @@ Y_UNIT_TEST_SUITE(Reader) {
ACCEPT("{foo=<foo=foo>foo}");
ACCEPT("{foo=<foo=foo;>foo}");
ACCEPT("{foo=<foo=foo>[foo;foo]}");
- }
-
+ }
+
Y_UNIT_TEST(Reject) {
REJECT("[");
REJECT("{");
REJECT("<");
-
+
REJECT("[[}]");
REJECT("<>{]");
REJECT("[>]");
-
+
REJECT("<><>[]");
REJECT("[<>;<>]");
-
+
REJECT("{<>foo=foo}");
REJECT("{foo=<>}");
REJECT("{foo}");
-
+
REJECT("<a=b>");
REJECT("<>");
REJECT("@");
}
-
+
Y_UNIT_TEST(ReadPastEnd) {
auto reader = memory_reader("#", NYsonPull::EStreamType::Node);
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginStream, reader.NextEvent().Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, reader.NextEvent().Type());
- UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndStream, reader.NextEvent().Type());
- UNIT_ASSERT_EXCEPTION(reader.NextEvent(), NYsonPull::NException::TBadInput);
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::BeginStream, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::Scalar, reader.NextEvent().Type());
+ UNIT_ASSERT_VALUES_EQUAL(NYsonPull::EEventType::EndStream, reader.NextEvent().Type());
+ UNIT_ASSERT_EXCEPTION(reader.NextEvent(), NYsonPull::NException::TBadInput);
}
-
- Y_UNIT_TEST(BadInput) {
- // max_size<ui32> < varint size < max_size<ui64>
- auto t = TString("\x01\xff\xff\xff\xff\xff\xff\xff\xff");
- auto reader = memory_reader(t, NYsonPull::EStreamType::Node);
-
- UNIT_ASSERT_EQUAL(reader.NextEvent().Type(), NYsonPull::EEventType::BeginStream);
- UNIT_ASSERT_EXCEPTION(reader.NextEvent(), NYsonPull::NException::TBadInput);
- }
-
+
+ Y_UNIT_TEST(BadInput) {
+ // max_size<ui32> < varint size < max_size<ui64>
+ auto t = TString("\x01\xff\xff\xff\xff\xff\xff\xff\xff");
+ auto reader = memory_reader(t, NYsonPull::EStreamType::Node);
+
+ UNIT_ASSERT_EQUAL(reader.NextEvent().Type(), NYsonPull::EEventType::BeginStream);
+ UNIT_ASSERT_EXCEPTION(reader.NextEvent(), NYsonPull::NException::TBadInput);
+ }
+
Y_UNIT_TEST(StreamType) {
- REJECT2("", NYsonPull::EStreamType::Node);
- ACCEPT2("", NYsonPull::EStreamType::ListFragment);
- ACCEPT2("", NYsonPull::EStreamType::MapFragment);
-
- ACCEPT2("[1]", NYsonPull::EStreamType::Node);
- ACCEPT2("[1]", NYsonPull::EStreamType::ListFragment);
- REJECT2("[1]", NYsonPull::EStreamType::MapFragment);
-
- ACCEPT2("<foo=bar>[1]", NYsonPull::EStreamType::Node);
- ACCEPT2("<foo=bar>[1]", NYsonPull::EStreamType::ListFragment);
- REJECT2("<foo=bar>[1]", NYsonPull::EStreamType::MapFragment);
-
- ACCEPT2(" [1] \t \t ", NYsonPull::EStreamType::Node);
- ACCEPT2(" [1] \t \t ", NYsonPull::EStreamType::ListFragment);
- REJECT2(" [1] \t \t ", NYsonPull::EStreamType::MapFragment);
-
- REJECT2("[1];", NYsonPull::EStreamType::Node);
- ACCEPT2("[1];", NYsonPull::EStreamType::ListFragment);
- REJECT2("[1];", NYsonPull::EStreamType::MapFragment);
-
- REJECT2("[1]; foobar", NYsonPull::EStreamType::Node);
- ACCEPT2("[1]; foobar", NYsonPull::EStreamType::ListFragment);
- REJECT2("[1]; foobar", NYsonPull::EStreamType::MapFragment);
-
- REJECT2("a=[1]", NYsonPull::EStreamType::Node);
- REJECT2("a=[1]", NYsonPull::EStreamType::ListFragment);
- ACCEPT2("a=[1]", NYsonPull::EStreamType::MapFragment);
-
- REJECT2("a=[1]; ", NYsonPull::EStreamType::Node);
- REJECT2("a=[1]; ", NYsonPull::EStreamType::ListFragment);
- ACCEPT2("a=[1]; ", NYsonPull::EStreamType::MapFragment);
-
- REJECT2("a=[1]; b=foobar", NYsonPull::EStreamType::Node);
- REJECT2("a=[1]; b=foobar", NYsonPull::EStreamType::ListFragment);
- ACCEPT2("a=[1]; b=foobar", NYsonPull::EStreamType::MapFragment);
+ REJECT2("", NYsonPull::EStreamType::Node);
+ ACCEPT2("", NYsonPull::EStreamType::ListFragment);
+ ACCEPT2("", NYsonPull::EStreamType::MapFragment);
+
+ ACCEPT2("[1]", NYsonPull::EStreamType::Node);
+ ACCEPT2("[1]", NYsonPull::EStreamType::ListFragment);
+ REJECT2("[1]", NYsonPull::EStreamType::MapFragment);
+
+ ACCEPT2("<foo=bar>[1]", NYsonPull::EStreamType::Node);
+ ACCEPT2("<foo=bar>[1]", NYsonPull::EStreamType::ListFragment);
+ REJECT2("<foo=bar>[1]", NYsonPull::EStreamType::MapFragment);
+
+ ACCEPT2(" [1] \t \t ", NYsonPull::EStreamType::Node);
+ ACCEPT2(" [1] \t \t ", NYsonPull::EStreamType::ListFragment);
+ REJECT2(" [1] \t \t ", NYsonPull::EStreamType::MapFragment);
+
+ REJECT2("[1];", NYsonPull::EStreamType::Node);
+ ACCEPT2("[1];", NYsonPull::EStreamType::ListFragment);
+ REJECT2("[1];", NYsonPull::EStreamType::MapFragment);
+
+ REJECT2("[1]; foobar", NYsonPull::EStreamType::Node);
+ ACCEPT2("[1]; foobar", NYsonPull::EStreamType::ListFragment);
+ REJECT2("[1]; foobar", NYsonPull::EStreamType::MapFragment);
+
+ REJECT2("a=[1]", NYsonPull::EStreamType::Node);
+ REJECT2("a=[1]", NYsonPull::EStreamType::ListFragment);
+ ACCEPT2("a=[1]", NYsonPull::EStreamType::MapFragment);
+
+ REJECT2("a=[1]; ", NYsonPull::EStreamType::Node);
+ REJECT2("a=[1]; ", NYsonPull::EStreamType::ListFragment);
+ ACCEPT2("a=[1]; ", NYsonPull::EStreamType::MapFragment);
+
+ REJECT2("a=[1]; b=foobar", NYsonPull::EStreamType::Node);
+ REJECT2("a=[1]; b=foobar", NYsonPull::EStreamType::ListFragment);
+ ACCEPT2("a=[1]; b=foobar", NYsonPull::EStreamType::MapFragment);
}
-
+
} // Y_UNIT_TEST_SUITE(Reader)
diff --git a/library/cpp/yson_pull/ut/writer_ut.cpp b/library/cpp/yson_pull/ut/writer_ut.cpp
index 87b2082ca5..5c304bad0f 100644
--- a/library/cpp/yson_pull/ut/writer_ut.cpp
+++ b/library/cpp/yson_pull/ut/writer_ut.cpp
@@ -1,56 +1,56 @@
#include <library/cpp/yson_pull/scalar.h>
#include <library/cpp/yson_pull/detail/writer.h>
-
+
#include <library/cpp/testing/unittest/registar.h>
-
+
#include <util/generic/string.h>
-
-#include <climits>
-#include <limits>
-
+
+#include <climits>
+#include <limits>
+
using namespace std::string_view_literals;
-namespace {
+namespace {
template <typename Writer, typename Function>
TString with_writer(Function&& function) {
TString result;
auto writer = NYsonPull::NDetail::make_writer<Writer>(
- NYsonPull::NOutput::FromString(&result),
+ NYsonPull::NOutput::FromString(&result),
NYsonPull::EStreamType::Node);
-
+
function(writer);
-
- return result;
+
+ return result;
}
-
+
template <typename Writer>
TString to_yson_string(const NYsonPull::TScalar& value) {
return with_writer<Writer>([&](NYsonPull::TWriter& writer) {
- writer.BeginStream().Scalar(value).EndStream();
+ writer.BeginStream().Scalar(value).EndStream();
});
}
-
+
template <typename T>
TString to_yson_binary_string(T&& value) {
- return to_yson_string<NYsonPull::NDetail::TBinaryWriterImpl>(std::forward<T>(value));
+ return to_yson_string<NYsonPull::NDetail::TBinaryWriterImpl>(std::forward<T>(value));
}
-
+
template <typename T>
TString to_yson_text_string(T&& value) {
- return to_yson_string<NYsonPull::NDetail::TTextWriterImpl>(std::forward<T>(value));
+ return to_yson_string<NYsonPull::NDetail::TTextWriterImpl>(std::forward<T>(value));
}
-
-} // anonymous namespace
-
-// =================== Text format =====================
-
+
+} // anonymous namespace
+
+// =================== Text format =====================
+
Y_UNIT_TEST_SUITE(Writer) {
Y_UNIT_TEST(TextEntity) {
UNIT_ASSERT_VALUES_EQUAL(
"#",
to_yson_text_string(NYsonPull::TScalar{}));
}
-
+
Y_UNIT_TEST(TextBoolean) {
UNIT_ASSERT_VALUES_EQUAL(
"%false",
@@ -59,7 +59,7 @@ Y_UNIT_TEST_SUITE(Writer) {
"%true",
to_yson_text_string(NYsonPull::TScalar{true}));
}
-
+
Y_UNIT_TEST(TextInt64) {
UNIT_ASSERT_VALUES_EQUAL(
"0",
@@ -79,7 +79,7 @@ Y_UNIT_TEST_SUITE(Writer) {
UNIT_ASSERT_VALUES_EQUAL(
"9223372036854775807",
to_yson_text_string(NYsonPull::TScalar{i64{INT64_MAX}}));
-
+
UNIT_ASSERT_VALUES_EQUAL(
"-200",
to_yson_text_string(NYsonPull::TScalar{i64{-200}}));
@@ -96,7 +96,7 @@ Y_UNIT_TEST_SUITE(Writer) {
"-9223372036854775808",
to_yson_text_string(NYsonPull::TScalar{i64{INT64_MIN}}));
}
-
+
Y_UNIT_TEST(TextUInt64) {
UNIT_ASSERT_VALUES_EQUAL(
"0u",
@@ -120,19 +120,19 @@ Y_UNIT_TEST_SUITE(Writer) {
"18446744073709551615u",
to_yson_text_string(NYsonPull::TScalar{ui64{UINT64_MAX}}));
}
-
+
Y_UNIT_TEST(TextFloat64) {
- UNIT_ASSERT_VALUES_EQUAL(
+ UNIT_ASSERT_VALUES_EQUAL(
"%inf",
- to_yson_text_string(NYsonPull::TScalar{std::numeric_limits<double>::infinity()}));
- UNIT_ASSERT_VALUES_EQUAL(
+ to_yson_text_string(NYsonPull::TScalar{std::numeric_limits<double>::infinity()}));
+ UNIT_ASSERT_VALUES_EQUAL(
"%-inf",
- to_yson_text_string(NYsonPull::TScalar{-std::numeric_limits<double>::infinity()}));
+ to_yson_text_string(NYsonPull::TScalar{-std::numeric_limits<double>::infinity()}));
UNIT_ASSERT_VALUES_EQUAL(
"%nan",
to_yson_text_string(NYsonPull::TScalar{std::numeric_limits<double>::quiet_NaN()}));
}
-
+
Y_UNIT_TEST(TextString) {
UNIT_ASSERT_VALUES_EQUAL(
R"("")",
@@ -144,15 +144,15 @@ Y_UNIT_TEST_SUITE(Writer) {
R"("hello\nworld")",
to_yson_text_string(NYsonPull::TScalar{"hello\nworld"}));
}
-
+
// =================== Binary format =====================
-
+
Y_UNIT_TEST(BinaryEntity) {
UNIT_ASSERT_VALUES_EQUAL(
"#",
to_yson_binary_string(NYsonPull::TScalar{}));
}
-
+
Y_UNIT_TEST(BinaryBoolean) {
UNIT_ASSERT_VALUES_EQUAL(
TStringBuf("\x4"),
@@ -161,7 +161,7 @@ Y_UNIT_TEST_SUITE(Writer) {
TStringBuf("\x5"),
to_yson_binary_string(NYsonPull::TScalar{true}));
}
-
+
Y_UNIT_TEST(BinaryInt64) {
UNIT_ASSERT_VALUES_EQUAL(
TStringBuf("\x2\0"sv),
@@ -181,7 +181,7 @@ Y_UNIT_TEST_SUITE(Writer) {
UNIT_ASSERT_VALUES_EQUAL(
TStringBuf("\x2\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x1"),
to_yson_binary_string(NYsonPull::TScalar{i64{INT64_MAX}}));
-
+
UNIT_ASSERT_VALUES_EQUAL(
TStringBuf("\x2\x8F\x3"),
to_yson_binary_string(NYsonPull::TScalar{i64{-200}}));
@@ -198,7 +198,7 @@ Y_UNIT_TEST_SUITE(Writer) {
TStringBuf("\x2\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x1"),
to_yson_binary_string(NYsonPull::TScalar{i64{INT64_MIN}}));
}
-
+
Y_UNIT_TEST(BinaryUInt64) {
UNIT_ASSERT_VALUES_EQUAL(
TStringBuf("\x6\0"sv),
@@ -222,14 +222,14 @@ Y_UNIT_TEST_SUITE(Writer) {
TStringBuf("\x6\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x1"),
to_yson_binary_string(NYsonPull::TScalar{ui64{UINT64_MAX}}));
}
-
+
Y_UNIT_TEST(BinaryFloat64) {
- UNIT_ASSERT_VALUES_EQUAL(
+ UNIT_ASSERT_VALUES_EQUAL(
TStringBuf("\x03\x00\x00\x00\x00\x00\x00\xf0\x7f"sv),
- to_yson_binary_string(NYsonPull::TScalar{std::numeric_limits<double>::infinity()}));
- UNIT_ASSERT_VALUES_EQUAL(
+ to_yson_binary_string(NYsonPull::TScalar{std::numeric_limits<double>::infinity()}));
+ UNIT_ASSERT_VALUES_EQUAL(
TStringBuf("\x03\x00\x00\x00\x00\x00\x00\xf0\xff"sv),
- to_yson_binary_string(NYsonPull::TScalar{-std::numeric_limits<double>::infinity()}));
+ to_yson_binary_string(NYsonPull::TScalar{-std::numeric_limits<double>::infinity()}));
UNIT_ASSERT_VALUES_EQUAL(
TStringBuf("\x03\x00\x00\x00\x00\x00\x00\xf8\x7f"sv),
to_yson_binary_string(NYsonPull::TScalar{std::numeric_limits<double>::quiet_NaN()}));
@@ -240,7 +240,7 @@ Y_UNIT_TEST_SUITE(Writer) {
TStringBuf("\x03\x9a\x99\x99\x99\x99\x99\xf1\xbf"),
to_yson_binary_string(NYsonPull::TScalar{double{-1.1}}));
}
-
+
Y_UNIT_TEST(BinaryString) {
UNIT_ASSERT_VALUES_EQUAL(
TStringBuf("\x1\0"sv),
@@ -252,5 +252,5 @@ Y_UNIT_TEST_SUITE(Writer) {
TStringBuf("\x1\x16hello\nworld"),
to_yson_binary_string(NYsonPull::TScalar{"hello\nworld"}));
}
-
+
} // Y_UNIT_TEST_SUITE(Writer)
diff --git a/library/cpp/yson_pull/ut/ya.make b/library/cpp/yson_pull/ut/ya.make
index d2616ed8b9..a269dfd2ad 100644
--- a/library/cpp/yson_pull/ut/ya.make
+++ b/library/cpp/yson_pull/ut/ya.make
@@ -1,12 +1,12 @@
UNITTEST_FOR(library/cpp/yson_pull)
-
-OWNER(borman)
-
-SRCS(
- cescape_ut.cpp
- reader_ut.cpp
- writer_ut.cpp
- loop_ut.cpp
-)
-
-END()
+
+OWNER(borman)
+
+SRCS(
+ cescape_ut.cpp
+ reader_ut.cpp
+ writer_ut.cpp
+ loop_ut.cpp
+)
+
+END()
diff --git a/library/cpp/yson_pull/writer.cpp b/library/cpp/yson_pull/writer.cpp
index 566b248714..1df92bf40f 100644
--- a/library/cpp/yson_pull/writer.cpp
+++ b/library/cpp/yson_pull/writer.cpp
@@ -1,30 +1,30 @@
-#include "writer.h"
+#include "writer.h"
#include <library/cpp/yson_pull/detail/writer.h>
-
-using namespace NYsonPull;
-
-TWriter NYsonPull::MakeBinaryWriter(
- THolder<NOutput::IStream> stream,
+
+using namespace NYsonPull;
+
+TWriter NYsonPull::MakeBinaryWriter(
+ THolder<NOutput::IStream> stream,
EStreamType mode) {
- return NYsonPull::NDetail::make_writer<NYsonPull::NDetail::TBinaryWriterImpl>(
- std::move(stream),
+ return NYsonPull::NDetail::make_writer<NYsonPull::NDetail::TBinaryWriterImpl>(
+ std::move(stream),
mode);
-}
-
-TWriter NYsonPull::MakeTextWriter(
- THolder<NOutput::IStream> stream,
+}
+
+TWriter NYsonPull::MakeTextWriter(
+ THolder<NOutput::IStream> stream,
EStreamType mode) {
- return NYsonPull::NDetail::make_writer<NYsonPull::NDetail::TTextWriterImpl>(
- std::move(stream),
+ return NYsonPull::NDetail::make_writer<NYsonPull::NDetail::TTextWriterImpl>(
+ std::move(stream),
mode);
-}
-
-TWriter NYsonPull::MakePrettyTextWriter(
- THolder<NOutput::IStream> stream,
- EStreamType mode,
+}
+
+TWriter NYsonPull::MakePrettyTextWriter(
+ THolder<NOutput::IStream> stream,
+ EStreamType mode,
size_t indent_size) {
- return NYsonPull::NDetail::make_writer<NYsonPull::NDetail::TPrettyWriterImpl>(
- std::move(stream),
- mode,
+ return NYsonPull::NDetail::make_writer<NYsonPull::NDetail::TPrettyWriterImpl>(
+ std::move(stream),
+ mode,
indent_size);
-}
+}
diff --git a/library/cpp/yson_pull/writer.h b/library/cpp/yson_pull/writer.h
index d937d18691..dec63328be 100644
--- a/library/cpp/yson_pull/writer.h
+++ b/library/cpp/yson_pull/writer.h
@@ -1,126 +1,126 @@
-#pragma once
-
-#include "consumer.h"
-#include "output.h"
-#include "scalar.h"
-#include "stream_type.h"
-
-#include <memory>
-
-namespace NYsonPull {
+#pragma once
+
+#include "consumer.h"
+#include "output.h"
+#include "scalar.h"
+#include "stream_type.h"
+
+#include <memory>
+
+namespace NYsonPull {
//! \brief YSON writer facade class
//!
//! Owns a YSON consumer and a corresponding output stream.
//! Methods invoke corresponding \p NYsonPull::IConsumer methods and can be chained.
class TWriter {
- THolder<NOutput::IStream> Stream_;
- THolder<IConsumer> Impl_;
-
+ THolder<NOutput::IStream> Stream_;
+ THolder<IConsumer> Impl_;
+
public:
TWriter(
THolder<NOutput::IStream> stream,
THolder<IConsumer> impl)
- : Stream_{std::move(stream)}
- , Impl_{std::move(impl)} {
+ : Stream_{std::move(stream)}
+ , Impl_{std::move(impl)} {
}
-
+
//! \brief Get a reference to underlying consumer.
//!
//! Useful with \p NYsonPull::bridge
- IConsumer& GetConsumer() {
- return *Impl_;
+ IConsumer& GetConsumer() {
+ return *Impl_;
}
-
- TWriter& BeginStream() {
- Impl_->OnBeginStream();
+
+ TWriter& BeginStream() {
+ Impl_->OnBeginStream();
return *this;
}
- TWriter& EndStream() {
- Impl_->OnEndStream();
+ TWriter& EndStream() {
+ Impl_->OnEndStream();
return *this;
}
-
- TWriter& BeginList() {
- Impl_->OnBeginList();
+
+ TWriter& BeginList() {
+ Impl_->OnBeginList();
return *this;
}
- TWriter& EndList() {
- Impl_->OnEndList();
+ TWriter& EndList() {
+ Impl_->OnEndList();
return *this;
}
-
- TWriter& BeginMap() {
- Impl_->OnBeginMap();
+
+ TWriter& BeginMap() {
+ Impl_->OnBeginMap();
return *this;
}
- TWriter& EndMap() {
- Impl_->OnEndMap();
+ TWriter& EndMap() {
+ Impl_->OnEndMap();
return *this;
}
-
- TWriter& BeginAttributes() {
- Impl_->OnBeginAttributes();
+
+ TWriter& BeginAttributes() {
+ Impl_->OnBeginAttributes();
return *this;
}
- TWriter& EndAttributes() {
- Impl_->OnEndAttributes();
+ TWriter& EndAttributes() {
+ Impl_->OnEndAttributes();
return *this;
}
-
- TWriter& Key(TStringBuf name) {
- Impl_->OnKey(name);
+
+ TWriter& Key(TStringBuf name) {
+ Impl_->OnKey(name);
return *this;
}
-
- TWriter& Entity() {
- Impl_->OnEntity();
+
+ TWriter& Entity() {
+ Impl_->OnEntity();
return *this;
}
- TWriter& Boolean(bool value) {
- Impl_->OnScalarBoolean(value);
+ TWriter& Boolean(bool value) {
+ Impl_->OnScalarBoolean(value);
return *this;
}
- TWriter& Int64(i64 value) {
- Impl_->OnScalarInt64(value);
+ TWriter& Int64(i64 value) {
+ Impl_->OnScalarInt64(value);
return *this;
}
- TWriter& UInt64(ui64 value) {
- Impl_->OnScalarUInt64(value);
+ TWriter& UInt64(ui64 value) {
+ Impl_->OnScalarUInt64(value);
return *this;
}
- TWriter& Float64(double value) {
- Impl_->OnScalarFloat64(value);
+ TWriter& Float64(double value) {
+ Impl_->OnScalarFloat64(value);
return *this;
}
- TWriter& String(TStringBuf value) {
- Impl_->OnScalarString(value);
+ TWriter& String(TStringBuf value) {
+ Impl_->OnScalarString(value);
return *this;
}
-
- TWriter& Scalar(const TScalar& value) {
- Impl_->OnScalar(value);
+
+ TWriter& Scalar(const TScalar& value) {
+ Impl_->OnScalar(value);
return *this;
}
- TWriter& Event(const TEvent& value) {
- Impl_->OnEvent(value);
+ TWriter& Event(const TEvent& value) {
+ Impl_->OnEvent(value);
return *this;
}
};
-
+
//! \brief Construct a writer for binary YSON format.
- TWriter MakeBinaryWriter(
+ TWriter MakeBinaryWriter(
THolder<NOutput::IStream> stream,
EStreamType mode);
-
+
//! \brief Construct a writer for text YSON format.
- TWriter MakeTextWriter(
+ TWriter MakeTextWriter(
THolder<NOutput::IStream> stream,
EStreamType mode);
-
+
//! \brief Construct a writer for pretty text YSON format.
- TWriter MakePrettyTextWriter(
+ TWriter MakePrettyTextWriter(
THolder<NOutput::IStream> stream,
EStreamType mode,
size_t indent_size = 4);
-
+
}
diff --git a/library/cpp/yson_pull/ya.make b/library/cpp/yson_pull/ya.make
index 42af77c4b1..a373e0a6ba 100644
--- a/library/cpp/yson_pull/ya.make
+++ b/library/cpp/yson_pull/ya.make
@@ -1,21 +1,21 @@
-LIBRARY(yson_pull)
-
-OWNER(borman)
-
-SRCS(
- consumer.cpp
- event.cpp
- exceptions.cpp
- input.cpp
- output.cpp
- read_ops.cpp
- reader.cpp
- scalar.cpp
- writer.cpp
-)
-
-GENERATE_ENUM_SERIALIZATION(event.h)
+LIBRARY(yson_pull)
-GENERATE_ENUM_SERIALIZATION(scalar.h)
-
-END()
+OWNER(borman)
+
+SRCS(
+ consumer.cpp
+ event.cpp
+ exceptions.cpp
+ input.cpp
+ output.cpp
+ read_ops.cpp
+ reader.cpp
+ scalar.cpp
+ writer.cpp
+)
+
+GENERATE_ENUM_SERIALIZATION(event.h)
+
+GENERATE_ENUM_SERIALIZATION(scalar.h)
+
+END()
diff --git a/library/cpp/yson_pull/yson.h b/library/cpp/yson_pull/yson.h
index ecfa2b6604..a77eaa5c94 100644
--- a/library/cpp/yson_pull/yson.h
+++ b/library/cpp/yson_pull/yson.h
@@ -1,14 +1,14 @@
-#pragma once
-
-#include "bridge.h"
-#include "consumer.h"
-#include "event.h"
-#include "exceptions.h"
-#include "input.h"
-#include "output.h"
-#include "position_info.h"
-#include "range.h"
-#include "reader.h"
-#include "scalar.h"
-#include "stream_type.h"
-#include "writer.h"
+#pragma once
+
+#include "bridge.h"
+#include "consumer.h"
+#include "event.h"
+#include "exceptions.h"
+#include "input.h"
+#include "output.h"
+#include "position_info.h"
+#include "range.h"
+#include "reader.h"
+#include "scalar.h"
+#include "stream_type.h"
+#include "writer.h"
diff --git a/library/cpp/yt/memory/ref.cpp b/library/cpp/yt/memory/ref.cpp
index af17f2f184..e8ff42e976 100644
--- a/library/cpp/yt/memory/ref.cpp
+++ b/library/cpp/yt/memory/ref.cpp
@@ -57,11 +57,11 @@ public:
#endif
}
- const TString& String() const
- {
- return String_;
- }
-
+ const TString& String() const
+ {
+ return String_;
+ }
+
private:
const TString String_;
#ifdef YT_ENABLE_REF_COUNTED_TRACKING
@@ -190,7 +190,7 @@ TMutableRef TMutableRef::FromBlob(TBlob& blob)
TSharedRef TSharedRef::FromString(TString str, TRefCountedTypeCookie tagCookie)
{
auto holder = New<TStringHolder>(std::move(str), tagCookie);
- auto ref = TRef::FromString(holder->String());
+ auto ref = TRef::FromString(holder->String());
return TSharedRef(ref, std::move(holder));
}
diff --git a/library/cpp/yt/yson_string/string.cpp b/library/cpp/yt/yson_string/string.cpp
index 1322212650..99d45e8616 100644
--- a/library/cpp/yt/yson_string/string.cpp
+++ b/library/cpp/yt/yson_string/string.cpp
@@ -101,25 +101,25 @@ TYsonString::TYsonString(
: TYsonString(TYsonStringBuf(data, type))
{ }
-#ifdef TSTRING_IS_STD_STRING
+#ifdef TSTRING_IS_STD_STRING
TYsonString::TYsonString(
- const TString& data,
+ const TString& data,
EYsonType type)
- : TYsonString(TYsonStringBuf(data, type))
-{ }
-#else
-TYsonString::TYsonString(
- const TString& data,
- EYsonType type)
-{
- // NOTE: CoW TString implementation is assumed
- // Moving the payload MUST NOT invalidate its internal pointers
+ : TYsonString(TYsonStringBuf(data, type))
+{ }
+#else
+TYsonString::TYsonString(
+ const TString& data,
+ EYsonType type)
+{
+ // NOTE: CoW TString implementation is assumed
+ // Moving the payload MUST NOT invalidate its internal pointers
Payload_ = data;
Begin_ = data.data();
Size_ = data.length();
Type_ = type;
}
-#endif
+#endif
TYsonString::TYsonString(
const TSharedRef& data,
diff --git a/library/cpp/yt/yson_string/string.h b/library/cpp/yt/yson_string/string.h
index adf2138564..e13af37a6d 100644
--- a/library/cpp/yt/yson_string/string.h
+++ b/library/cpp/yt/yson_string/string.h
@@ -76,9 +76,9 @@ public:
EYsonType type = EYsonType::Node);
//! Constructs an instance from TString.
- //! Zero-copy for CoW TString: retains the reference to TString in payload.
+ //! Zero-copy for CoW TString: retains the reference to TString in payload.
explicit TYsonString(
- const TString& data,
+ const TString& data,
EYsonType type = EYsonType::Node);
//! Constructs an instance from TSharedRef.
diff --git a/library/python/cores/__init__.py b/library/python/cores/__init__.py
index d6bd3c828d..fdb1f82a46 100644
--- a/library/python/cores/__init__.py
+++ b/library/python/cores/__init__.py
@@ -8,8 +8,8 @@ import logging
import platform
import subprocess
-import six
-
+import six
+
from library.python.reservoir_sampling import reservoir_sampling
@@ -125,9 +125,9 @@ def get_gdb_full_backtrace(binary, core, gdb_path):
]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, stderr = proc.communicate()
- output = six.ensure_str(output)
+ output = six.ensure_str(output)
if stderr:
- output += "\nstderr >>\n" + six.ensure_str(stderr)
+ output += "\nstderr >>\n" + six.ensure_str(stderr)
return output
diff --git a/library/python/cores/ya.make b/library/python/cores/ya.make
index c5312bf458..76264e9cce 100644
--- a/library/python/cores/ya.make
+++ b/library/python/cores/ya.make
@@ -8,7 +8,7 @@ PY23_LIBRARY()
PY_SRCS(__init__.py)
PEERDIR(
- contrib/python/six
+ contrib/python/six
library/python/reservoir_sampling
)
diff --git a/library/python/resource/__init__.py b/library/python/resource/__init__.py
index 627f4001f4..26503ef7fc 100644
--- a/library/python/resource/__init__.py
+++ b/library/python/resource/__init__.py
@@ -1,8 +1,8 @@
from __res import find as __find, count, key_by_index, resfs_files as __resfs_files
from __res import resfs_read, resfs_resolve, resfs_src # noqa
-
+
import six
-
+
def iterkeys(prefix='', strip_prefix=False):
decode = lambda s: s
@@ -11,12 +11,12 @@ def iterkeys(prefix='', strip_prefix=False):
decode = lambda s: s.decode('utf-8')
for i in six.moves.range(count()):
- key = key_by_index(i)
+ key = key_by_index(i)
if key.startswith(prefix):
if strip_prefix:
key = key[len(prefix):]
yield decode(key)
-
+
def itervalues(prefix=b''):
for key in iterkeys(prefix=prefix):
diff --git a/library/python/resource/ut/lib/test_simple.py b/library/python/resource/ut/lib/test_simple.py
index 207307242c..52f006ff91 100644
--- a/library/python/resource/ut/lib/test_simple.py
+++ b/library/python/resource/ut/lib/test_simple.py
@@ -7,8 +7,8 @@ text = b'na gorshke sidel korol\n'
def test_find():
assert rs.find('/qw.txt') == text
-
-
+
+
def test_iter():
assert set(rs.iterkeys()).issuperset({'/qw.txt', '/prefix/1.txt', '/prefix/2.txt'})
assert set(rs.iterkeys(prefix='/prefix/')) == {'/prefix/1.txt', '/prefix/2.txt'}
diff --git a/library/python/resource/ut/lib/ya.make b/library/python/resource/ut/lib/ya.make
index 3930797334..693e388878 100644
--- a/library/python/resource/ut/lib/ya.make
+++ b/library/python/resource/ut/lib/ya.make
@@ -10,8 +10,8 @@ PEERDIR(
RESOURCE(
qw.txt /qw.txt
- qw.txt /prefix/1.txt
- qw.txt /prefix/2.txt
+ qw.txt /prefix/1.txt
+ qw.txt /prefix/2.txt
)
END()
diff --git a/library/python/runtime_py3/importer.pxi b/library/python/runtime_py3/importer.pxi
index 643776519e..904f94dea2 100644
--- a/library/python/runtime_py3/importer.pxi
+++ b/library/python/runtime_py3/importer.pxi
@@ -249,7 +249,7 @@ class ResourceImporter(object):
if isinstance(relpath, bytes):
relpath = _s(relpath)
return relpath or modname
-
+
# PEP-302 extension 3 of 3: packaging introspection.
# Used by `linecache` (while printing tracebacks) unless module filename
# exists on the filesystem.
@@ -265,7 +265,7 @@ class ResourceImporter(object):
return _s(file_bytes(abspath))
data = resfs_read(mod_path(fullname))
return _s(data) if data else ''
-
+
def get_code(self, fullname):
modname = fullname
if self.is_package(fullname):
@@ -283,14 +283,14 @@ class ResourceImporter(object):
yapyc_data = resfs_read(yapyc_path, builtin=True)
if yapyc_data:
return marshal.loads(yapyc_data)
- else:
+ else:
py_data = resfs_read(path, builtin=True)
if py_data:
return compile(py_data, _s(relpath), 'exec', dont_inherit=True)
else:
# This covers packages with no __init__.py in resources.
return compile('', modname, 'exec', dont_inherit=True)
-
+
def is_package(self, fullname):
if fullname in self.memory:
return False
@@ -332,7 +332,7 @@ class ResourceImporter(object):
if self.arcadia_source_finder:
for m in self.arcadia_source_finder.iter_modules(self._package_prefix, prefix):
yield m
-
+
def get_resource_reader(self, fullname):
try:
if not self.is_package(fullname):
@@ -393,7 +393,7 @@ class BuiltinSubmoduleImporter(BuiltinImporter):
else:
return None
-
+
class ArcadiaSourceFinder:
"""
Search modules and packages in arcadia source tree.
@@ -522,17 +522,17 @@ class ArcadiaSourceFinder:
paths.add(rel_path)
-def excepthook(*args, **kws):
- # traceback module cannot be imported at module level, because interpreter
- # is not fully initialized yet
-
- import traceback
-
- return traceback.print_exception(*args, **kws)
-
-
+def excepthook(*args, **kws):
+ # traceback module cannot be imported at module level, because interpreter
+ # is not fully initialized yet
+
+ import traceback
+
+ return traceback.print_exception(*args, **kws)
+
+
importer = ResourceImporter()
-
+
def executable_path_hook(path):
if path == executable:
@@ -562,10 +562,10 @@ sys.path_importer_cache[executable] = importer
# Indicator that modules and resources are built-in rather than on the file system.
sys.is_standalone_binary = True
sys.frozen = True
-
+
# Set of names of importable modules.
sys.extra_modules = importer.memory
-
-# Use custom implementation of traceback printer.
-# Built-in printer (PyTraceBack_Print) does not support custom module loaders
-sys.excepthook = excepthook
+
+# Use custom implementation of traceback printer.
+# Built-in printer (PyTraceBack_Print) does not support custom module loaders
+sys.excepthook = excepthook
diff --git a/library/python/runtime_py3/main/main.c b/library/python/runtime_py3/main/main.c
index eaf500eaf2..3159800615 100644
--- a/library/python/runtime_py3/main/main.c
+++ b/library/python/runtime_py3/main/main.c
@@ -183,9 +183,9 @@ static int pymain(int argc, char** argv) {
colon[0] = '\0';
func_name = colon + 1;
}
- if (module_name[0] == '\0') {
- module_name = "library.python.runtime_py3.entry_points";
- }
+ if (module_name[0] == '\0') {
+ module_name = "library.python.runtime_py3.entry_points";
+ }
if (!func_name) {
sts = RunModule(module_name);
diff --git a/library/python/runtime_py3/main/ya.make b/library/python/runtime_py3/main/ya.make
index 1a98366774..f308a93b28 100644
--- a/library/python/runtime_py3/main/ya.make
+++ b/library/python/runtime_py3/main/ya.make
@@ -1,15 +1,15 @@
-LIBRARY()
-
+LIBRARY()
+
OWNER(
pg
orivej
)
-
+
PEERDIR(
contrib/tools/python3/src
library/cpp/resource
)
-
+
ADDINCL(
contrib/tools/python3/src/Include
)
@@ -22,5 +22,5 @@ SRCS(
main.c
get_py_main.cpp
)
-
-END()
+
+END()
diff --git a/library/python/runtime_py3/test/canondata/result.json b/library/python/runtime_py3/test/canondata/result.json
index b60f372fe3..a7d045fc9c 100644
--- a/library/python/runtime_py3/test/canondata/result.json
+++ b/library/python/runtime_py3/test/canondata/result.json
@@ -1,7 +1,7 @@
{
"test_traceback.test_traceback[custom-default]": {
"stderr": {
- "checksum": "6c1a9b47baa51cc6903b85fd43c529b5",
+ "checksum": "6c1a9b47baa51cc6903b85fd43c529b5",
"uri": "file://test_traceback.test_traceback_custom-default_/stderr.txt"
},
"stdout": {
@@ -31,7 +31,7 @@
},
"test_traceback.test_traceback[main-default]": {
"stderr": {
- "checksum": "6c1a9b47baa51cc6903b85fd43c529b5",
+ "checksum": "6c1a9b47baa51cc6903b85fd43c529b5",
"uri": "file://test_traceback.test_traceback_main-default_/stderr.txt"
},
"stdout": {
diff --git a/library/python/runtime_py3/test/canondata/test_traceback.test_traceback_custom-default_/stderr.txt b/library/python/runtime_py3/test/canondata/test_traceback.test_traceback_custom-default_/stderr.txt
index e5e3607e85..5eb7da170a 100644
--- a/library/python/runtime_py3/test/canondata/test_traceback.test_traceback_custom-default_/stderr.txt
+++ b/library/python/runtime_py3/test/canondata/test_traceback.test_traceback_custom-default_/stderr.txt
@@ -1,12 +1,12 @@
Traceback (most recent call last):
File "library/python/runtime_py3/test/traceback/crash.py", line 44, in main
- one()
+ one()
File "library/python/runtime_py3/test/traceback/crash.py", line 12, in one
- modfunc(two) # aaa
+ modfunc(two) # aaa
File "library/python/runtime_py3/test/traceback/mod/__init__.py", line 3, in modfunc
- f() # call back to caller
+ f() # call back to caller
File "library/python/runtime_py3/test/traceback/crash.py", line 16, in two
- three(42)
+ three(42)
File "library/python/runtime_py3/test/traceback/crash.py", line 20, in three
- raise RuntimeError('Kaboom! I\'m dead: {}'.format(x))
+ raise RuntimeError('Kaboom! I\'m dead: {}'.format(x))
RuntimeError: Kaboom! I'm dead: 42
diff --git a/library/python/runtime_py3/test/canondata/test_traceback.test_traceback_main-default_/stderr.txt b/library/python/runtime_py3/test/canondata/test_traceback.test_traceback_main-default_/stderr.txt
index e5e3607e85..5eb7da170a 100644
--- a/library/python/runtime_py3/test/canondata/test_traceback.test_traceback_main-default_/stderr.txt
+++ b/library/python/runtime_py3/test/canondata/test_traceback.test_traceback_main-default_/stderr.txt
@@ -1,12 +1,12 @@
Traceback (most recent call last):
File "library/python/runtime_py3/test/traceback/crash.py", line 44, in main
- one()
+ one()
File "library/python/runtime_py3/test/traceback/crash.py", line 12, in one
- modfunc(two) # aaa
+ modfunc(two) # aaa
File "library/python/runtime_py3/test/traceback/mod/__init__.py", line 3, in modfunc
- f() # call back to caller
+ f() # call back to caller
File "library/python/runtime_py3/test/traceback/crash.py", line 16, in two
- three(42)
+ three(42)
File "library/python/runtime_py3/test/traceback/crash.py", line 20, in three
- raise RuntimeError('Kaboom! I\'m dead: {}'.format(x))
+ raise RuntimeError('Kaboom! I\'m dead: {}'.format(x))
RuntimeError: Kaboom! I'm dead: 42
diff --git a/library/python/runtime_py3/test/test_traceback.py b/library/python/runtime_py3/test/test_traceback.py
index 0504f211c3..82087ce98a 100644
--- a/library/python/runtime_py3/test/test_traceback.py
+++ b/library/python/runtime_py3/test/test_traceback.py
@@ -33,7 +33,7 @@ def test_traceback(mode, entry_point):
filtered_stderr_path = yc.test_output_path('stderr.txt')
env = os.environ.copy()
- env.pop('PYTHONPATH', None) # Do not let program peek into its sources on filesystem
+ env.pop('PYTHONPATH', None) # Do not let program peek into its sources on filesystem
if entry_point == 'custom':
env['Y_PYTHON_ENTRY_POINT'] = 'library.python.runtime_py3.test.traceback.crash:main'
diff --git a/library/python/runtime_py3/test/ya.make b/library/python/runtime_py3/test/ya.make
index 866f1deeda..4ec3db74f5 100644
--- a/library/python/runtime_py3/test/ya.make
+++ b/library/python/runtime_py3/test/ya.make
@@ -36,5 +36,5 @@ RESOURCE_FILES(
)
END()
-
-RECURSE_FOR_TESTS(traceback)
+
+RECURSE_FOR_TESTS(traceback)
diff --git a/library/python/testing/yatest_common/yatest/common/process.py b/library/python/testing/yatest_common/yatest/common/process.py
index d252538d13..a8bcc21f51 100644
--- a/library/python/testing/yatest_common/yatest/common/process.py
+++ b/library/python/testing/yatest_common/yatest/common/process.py
@@ -468,23 +468,23 @@ def execute(
# if subprocess.PIPE in [stdout, stderr]:
# raise ValueError("Don't use pipe to obtain stream data - it may leads to the deadlock")
- def get_out_stream(stream, default_name):
- if stream is None:
- # No stream is supplied: open new temp file
+ def get_out_stream(stream, default_name):
+ if stream is None:
+ # No stream is supplied: open new temp file
return _get_command_output_file(command, default_name), False
-
+
if isinstance(stream, six.string_types):
- # User filename is supplied: open file for writing
+ # User filename is supplied: open file for writing
return open(stream, 'wb+'), stream.startswith('/dev/')
-
- # Open file or PIPE sentinel is supplied
- is_pipe = stream == subprocess.PIPE
- return stream, not is_pipe
-
+
+ # Open file or PIPE sentinel is supplied
+ is_pipe = stream == subprocess.PIPE
+ return stream, not is_pipe
+
# to be able to have stdout/stderr and track the process time execution, we don't use subprocess.PIPE,
# as it can cause processes hangs, but use tempfiles instead
- out_file, user_stdout = get_out_stream(stdout, 'out')
- err_file, user_stderr = get_out_stream(stderr, 'err')
+ out_file, user_stdout = get_out_stream(stdout, 'out')
+ err_file, user_stderr = get_out_stream(stderr, 'err')
in_file = stdin
if shell and type(command) == list:
diff --git a/library/python/ya.make b/library/python/ya.make
index e119b2aac6..2e1eb6e0e1 100644
--- a/library/python/ya.make
+++ b/library/python/ya.make
@@ -33,7 +33,7 @@ RECURSE(
cityhash
cityhash/test
clickhouse_client
- cmain
+ cmain
codecs
codecs/gen_corpus
codecs/test
@@ -47,9 +47,9 @@ RECURSE(
cppdemangle
cqueue
crowd-kit
- cyson
- cyson/pymodule
- cyson/ut
+ cyson
+ cyson/pymodule
+ cyson/ut
deploy_formatter
deprecated
dir-sync
@@ -73,7 +73,7 @@ RECURSE(
filesys
filesys/ut
find_root
- flask
+ flask
flask_passport
fnvhash
fnvhash/test
@@ -105,15 +105,15 @@ RECURSE(
json/compare
json/perf
json/test
- json/test/py2
- json/test/py3
+ json/test/py2
+ json/test/py3
langdetect
langmask
langs
- luigi
- luigi/data
+ luigi
+ luigi/data
luigi/example
- luigi/luigid_static
+ luigi/luigid_static
maths
messagebus
metrics_framework
@@ -128,7 +128,7 @@ RECURSE(
nirvana_api/test_lib
nirvana_test
nstools
- nyt
+ nyt
oauth
oauth/example
ok_client
@@ -158,7 +158,7 @@ RECURSE(
retry/tests
runtime
runtime/main
- runtime/test
+ runtime/test
runtime_py3
runtime_py3/main
runtime_py3/test
@@ -209,7 +209,7 @@ RECURSE(
yandex_tracker_client
yenv
yt
- yt/test
+ yt/test
ylock
ylock/tests
zipatch
diff --git a/tools/archiver/main.cpp b/tools/archiver/main.cpp
index e53d9510e6..6cda54c1ea 100644
--- a/tools/archiver/main.cpp
+++ b/tools/archiver/main.cpp
@@ -130,11 +130,11 @@ namespace {
void DoFinish() override {
*Out_ << Base_ << "Size:\ndd " << Count_ << '\n';
-
- *Out_ << "%ifidn __OUTPUT_FORMAT__,elf64\n";
- *Out_ << "size " << Base_ << " " << Count_ << "\n";
- *Out_ << "size " << Base_ << "Size 4\n";
- *Out_ << "%endif\n";
+
+ *Out_ << "%ifidn __OUTPUT_FORMAT__,elf64\n";
+ *Out_ << "size " << Base_ << " " << Count_ << "\n";
+ *Out_ << "size " << Base_ << "Size 4\n";
+ *Out_ << "%endif\n";
}
void DoWrite(const void* data, size_t len) override {
diff --git a/tools/fix_elf/patch.cpp b/tools/fix_elf/patch.cpp
index d3841fade4..d49ebab307 100644
--- a/tools/fix_elf/patch.cpp
+++ b/tools/fix_elf/patch.cpp
@@ -6,43 +6,43 @@
#include <util/generic/hash.h>
#include <util/stream/null.h>
#include <util/string/cast.h>
-#include <util/system/defaults.h>
+#include <util/system/defaults.h>
namespace NElf {
bool IsElf(const TString& path) {
TUnbufferedFileInput in(path);
- char buffer[EI_NIDENT];
- size_t nread = in.Load(buffer, sizeof(buffer));
-
- if (nread != sizeof(buffer) || TStringBuf(buffer, SELFMAG) != ELFMAG) {
- Cerr << "fix_elf skip " << path << " (not an ELF file)";
- return false;
- }
-
- if (buffer[EI_CLASS] != ELFCLASS64) {
- Cerr << "fix_elf skip " << path << " (ELF class is not ELF64)";
- return false;
- }
-
-#ifdef _little_endian_
- if (buffer[EI_DATA] != ELFDATA2LSB) {
- Cerr << "fix_elf skip " << path << " (ELF byte order is not native LSB)";
- return false;
- }
-#else
- if (buffer[EI_DATA] != ELFDATA2MSB) {
- Cerr << "fix_elf skip " << path << " (ELF byte order is not native MSB)";
- return false;
- }
-#endif
-
- if (buffer[EI_VERSION] != 1) {
- Cerr << "fix_elf skip " << path << " (ELF version is not 1)";
- return false;
- }
-
- return true;
+ char buffer[EI_NIDENT];
+ size_t nread = in.Load(buffer, sizeof(buffer));
+
+ if (nread != sizeof(buffer) || TStringBuf(buffer, SELFMAG) != ELFMAG) {
+ Cerr << "fix_elf skip " << path << " (not an ELF file)";
+ return false;
+ }
+
+ if (buffer[EI_CLASS] != ELFCLASS64) {
+ Cerr << "fix_elf skip " << path << " (ELF class is not ELF64)";
+ return false;
+ }
+
+#ifdef _little_endian_
+ if (buffer[EI_DATA] != ELFDATA2LSB) {
+ Cerr << "fix_elf skip " << path << " (ELF byte order is not native LSB)";
+ return false;
+ }
+#else
+ if (buffer[EI_DATA] != ELFDATA2MSB) {
+ Cerr << "fix_elf skip " << path << " (ELF byte order is not native MSB)";
+ return false;
+ }
+#endif
+
+ if (buffer[EI_VERSION] != 1) {
+ Cerr << "fix_elf skip " << path << " (ELF version is not 1)";
+ return false;
+ }
+
+ return true;
}
} // namespace NElf
diff --git a/tools/fix_elf/patch.h b/tools/fix_elf/patch.h
index de5b1a3b8c..c3dcd24224 100644
--- a/tools/fix_elf/patch.h
+++ b/tools/fix_elf/patch.h
@@ -23,7 +23,7 @@ public:
Map.Map(0, Map.Length());
Begin = reinterpret_cast<char*>(Map.Ptr());
- if (Map.Length() < static_cast<i64>(sizeof(Elf64_Ehdr)) || TStringBuf(Begin, SELFMAG) != ELFMAG) {
+ if (Map.Length() < static_cast<i64>(sizeof(Elf64_Ehdr)) || TStringBuf(Begin, SELFMAG) != ELFMAG) {
ythrow yexception() << path << " is not an ELF file";
}
}
diff --git a/tools/rescompressor/main.cpp b/tools/rescompressor/main.cpp
index 074211eae9..9aba1002c5 100644
--- a/tools/rescompressor/main.cpp
+++ b/tools/rescompressor/main.cpp
@@ -42,12 +42,12 @@ private:
}
void WriteSymbolSize(TStringBuf constname) {
- AsmOut << "%ifidn __OUTPUT_FORMAT__,elf64\n";
+ AsmOut << "%ifidn __OUTPUT_FORMAT__,elf64\n";
AsmOut << "size " << AsmPrefix << constname << " " << AsmPrefix << constname << ".end - " << AsmPrefix << constname << "\n";
- AsmOut << "size " << AsmPrefix << constname << "Size 4\n";
- AsmOut << "%endif\n";
- }
-
+ AsmOut << "size " << AsmPrefix << constname << "Size 4\n";
+ AsmOut << "%endif\n";
+ }
+
void WriteIncBin(TStringBuf constname, TStringBuf filename, const TString& data) {
AsmOut << AsmPrefix << constname << ":\nincbin \"" << Basename(filename) << "\"\n";
AsmOut << ".end:\n";
diff --git a/tools/ya.make b/tools/ya.make
index 9ea4b9e4bc..51a6b8b426 100644
--- a/tools/ya.make
+++ b/tools/ya.make
@@ -11,13 +11,13 @@ RECURSE(
bstr
c++filt
calendar_extractor
- check_formula_md5
+ check_formula_md5
check_json
check_yaml
checktrigrams
clustermaster
coldiff
- compress
+ compress
convert2html
cproxy
crc32
@@ -34,7 +34,7 @@ RECURSE(
drawrichtree
dsindexer
easyparser
- enforce_fsync
+ enforce_fsync
enum_parser
event2cpp
fast_diff
@@ -163,7 +163,7 @@ RECURSE(
trie_ops/lib
trie_ops/tests
trigram_index_print
- uc
+ uc
unpackrichtree
unpackrrr
unpack_staff_cert
@@ -177,7 +177,7 @@ RECURSE(
wizard_yt
ygetparam
ylzocat
- yson_pp
+ yson_pp
zk_client
idx_print
)
diff --git a/util/README.md b/util/README.md
index 22d6f356d4..496efa633c 100644
--- a/util/README.md
+++ b/util/README.md
@@ -55,16 +55,16 @@ Certain exceptions apply. The following trivial changes do not need to be review
* renaming of an internal variable to match the styleguide.
Whenever a breaking change happens to accidentally land into trunk, reverting it does not need to be reviewed.
-
-## Stale/abandoned review request policy
-
-Sometimes review requests are neither merged nor discarded, and stay in review request queue forever.
-To limit the incoming review request queue size, util reviewers follow these rules:
-
-- A review request is considered stale if it is not updated by its author for at least 3 months, or if its author has left Yandex.
-- A stale review request may be marked as discarded by util reviewers.
-
-Review requests discarded as stale may be reopened or resubmitted by any committer willing to push them to completion.
-
-**Note:** It's an author's duty to push the review request to completion.
-If util reviewers stop responding to updates, they should be politely pinged via appropriate means of communication.
+
+## Stale/abandoned review request policy
+
+Sometimes review requests are neither merged nor discarded, and stay in review request queue forever.
+To limit the incoming review request queue size, util reviewers follow these rules:
+
+- A review request is considered stale if it is not updated by its author for at least 3 months, or if its author has left Yandex.
+- A stale review request may be marked as discarded by util reviewers.
+
+Review requests discarded as stale may be reopened or resubmitted by any committer willing to push them to completion.
+
+**Note:** It's an author's duty to push the review request to completion.
+If util reviewers stop responding to updates, they should be politely pinged via appropriate means of communication.
diff --git a/util/a.yaml b/util/a.yaml
index c9c8f50a24..e658783472 100644
--- a/util/a.yaml
+++ b/util/a.yaml
@@ -1,38 +1,38 @@
-service: cpputil
-title: "Yandex C++ util base library"
-arcanum:
- auto_merge:
- requirements:
- - system: arcanum
- type: comment_issues_closed
-ci:
- secret: sec-01fgmqmem182tz4zjsmgd6nxxw
- runtime:
- sandbox-owner: CPPUTIL
- autocheck:
- fast-targets:
- - util
- actions:
- util-style-test:
- flow: util-style-test
- triggers:
- - on: pr
- filters:
- - sub-paths: [ '**.h', '**.cpp', '**.c' ]
- - on: commit
- filters:
- - sub-paths: [ '**.h', '**.cpp', '**.c' ]
- - discovery: graph
- abs-paths: [ 'util/tests/style/ya.make' ]
- flows:
- util-style-test:
- title: "C++ style"
- jobs:
- yamake-util-tests-style:
- title: "Ya Make: util/tests/style"
- task: common/arcadia/ya_make
- input:
- targets: util/tests/style
- test: true
- keep_on: true
- check_return_code: true
+service: cpputil
+title: "Yandex C++ util base library"
+arcanum:
+ auto_merge:
+ requirements:
+ - system: arcanum
+ type: comment_issues_closed
+ci:
+ secret: sec-01fgmqmem182tz4zjsmgd6nxxw
+ runtime:
+ sandbox-owner: CPPUTIL
+ autocheck:
+ fast-targets:
+ - util
+ actions:
+ util-style-test:
+ flow: util-style-test
+ triggers:
+ - on: pr
+ filters:
+ - sub-paths: [ '**.h', '**.cpp', '**.c' ]
+ - on: commit
+ filters:
+ - sub-paths: [ '**.h', '**.cpp', '**.c' ]
+ - discovery: graph
+ abs-paths: [ 'util/tests/style/ya.make' ]
+ flows:
+ util-style-test:
+ title: "C++ style"
+ jobs:
+ yamake-util-tests-style:
+ title: "Ya Make: util/tests/style"
+ task: common/arcadia/ya_make
+ input:
+ targets: util/tests/style
+ test: true
+ keep_on: true
+ check_return_code: true
diff --git a/util/digest/multi_ut.pyx b/util/digest/multi_ut.pyx
index 6b032f5f86..26faa0069b 100644
--- a/util/digest/multi_ut.pyx
+++ b/util/digest/multi_ut.pyx
@@ -8,11 +8,11 @@ import unittest
class TestMultiHash(unittest.TestCase):
def test_str_int(self):
- value = MultiHash(TString(b"1234567"), 123)
+ value = MultiHash(TString(b"1234567"), 123)
self.assertEquals(value, 17038203285960021630)
def test_int_str(self):
- value = MultiHash(123, TString(b"1234567"))
+ value = MultiHash(123, TString(b"1234567"))
self.assertEquals(value, 9973288649881090712)
def test_collision(self):
diff --git a/util/digest/murmur.cpp b/util/digest/murmur.cpp
index 84df22304d..b041d3e5f2 100644
--- a/util/digest/murmur.cpp
+++ b/util/digest/murmur.cpp
@@ -2,130 +2,130 @@
#include <util/system/unaligned_mem.h>
-namespace NMurmurPrivate {
- //-----------------------------------------------------------------------------
- // MurmurHash2, by Austin Appleby
-
- // Note - This code makes a few assumptions about how your machine behaves -
-
- // 1. We can read a 4-byte value from any address without crashing
- // 2. sizeof(int) == 4
-
- // And it has a few limitations -
-
- // 1. It will not work incrementally.
- // 2. It will not produce the same results on little-endian and big-endian
- // machines.
-
- Y_NO_INLINE ui32 MurmurHash32(const void* key, size_t len, ui32 seed) noexcept {
- const ui32 m = 0x5bd1e995;
- const int r = 24;
- ui32 h = ui32(seed ^ len);
-
- TUnalignedMemoryIterator<ui32> iter(key, len);
-
- while (!iter.AtEnd()) {
- ui32 k = iter.Next();
-
- k *= m;
- k ^= k >> r;
- k *= m;
-
- h *= m;
- h ^= k;
- }
-
- const unsigned char* data = iter.Last();
-
- switch (iter.Left()) {
- case 3:
- h ^= data[2] << 16;
+namespace NMurmurPrivate {
+ //-----------------------------------------------------------------------------
+ // MurmurHash2, by Austin Appleby
+
+ // Note - This code makes a few assumptions about how your machine behaves -
+
+ // 1. We can read a 4-byte value from any address without crashing
+ // 2. sizeof(int) == 4
+
+ // And it has a few limitations -
+
+ // 1. It will not work incrementally.
+ // 2. It will not produce the same results on little-endian and big-endian
+ // machines.
+
+ Y_NO_INLINE ui32 MurmurHash32(const void* key, size_t len, ui32 seed) noexcept {
+ const ui32 m = 0x5bd1e995;
+ const int r = 24;
+ ui32 h = ui32(seed ^ len);
+
+ TUnalignedMemoryIterator<ui32> iter(key, len);
+
+ while (!iter.AtEnd()) {
+ ui32 k = iter.Next();
+
+ k *= m;
+ k ^= k >> r;
+ k *= m;
+
+ h *= m;
+ h ^= k;
+ }
+
+ const unsigned char* data = iter.Last();
+
+ switch (iter.Left()) {
+ case 3:
+ h ^= data[2] << 16;
[[fallthrough]];
-
- case 2:
- h ^= data[1] << 8;
+
+ case 2:
+ h ^= data[1] << 8;
[[fallthrough]];
-
- case 1:
- h ^= data[0];
- h *= m;
+
+ case 1:
+ h ^= data[0];
+ h *= m;
break;
- };
-
- h ^= h >> 13;
- h *= m;
- h ^= h >> 15;
-
- return h;
- }
-
- //-----------------------------------------------------------------------------
- // MurmurHash2, 64-bit versions, by Austin Appleby
-
- // The same caveats as 32-bit MurmurHash2 apply here - beware of alignment
- // and endian-ness issues if used across multiple platforms.
-
- // 64-bit hash for 64-bit platforms
-
- Y_NO_INLINE ui64 MurmurHash64(const void* key, size_t len, ui64 seed) noexcept {
- const ui64 m = ULL(0xc6a4a7935bd1e995);
- const int r = 47;
-
- ui64 h = seed ^ (len * m);
- TUnalignedMemoryIterator<ui64> iter(key, len);
-
- while (!iter.AtEnd()) {
- ui64 k = iter.Next();
-
- k *= m;
- k ^= k >> r;
- k *= m;
-
- h ^= k;
- h *= m;
- }
-
- const unsigned char* data2 = iter.Last();
-
- switch (iter.Left()) {
- case 7:
- h ^= ui64(data2[6]) << 48;
+ };
+
+ h ^= h >> 13;
+ h *= m;
+ h ^= h >> 15;
+
+ return h;
+ }
+
+ //-----------------------------------------------------------------------------
+ // MurmurHash2, 64-bit versions, by Austin Appleby
+
+ // The same caveats as 32-bit MurmurHash2 apply here - beware of alignment
+ // and endian-ness issues if used across multiple platforms.
+
+ // 64-bit hash for 64-bit platforms
+
+ Y_NO_INLINE ui64 MurmurHash64(const void* key, size_t len, ui64 seed) noexcept {
+ const ui64 m = ULL(0xc6a4a7935bd1e995);
+ const int r = 47;
+
+ ui64 h = seed ^ (len * m);
+ TUnalignedMemoryIterator<ui64> iter(key, len);
+
+ while (!iter.AtEnd()) {
+ ui64 k = iter.Next();
+
+ k *= m;
+ k ^= k >> r;
+ k *= m;
+
+ h ^= k;
+ h *= m;
+ }
+
+ const unsigned char* data2 = iter.Last();
+
+ switch (iter.Left()) {
+ case 7:
+ h ^= ui64(data2[6]) << 48;
[[fallthrough]];
-
- case 6:
- h ^= ui64(data2[5]) << 40;
+
+ case 6:
+ h ^= ui64(data2[5]) << 40;
[[fallthrough]];
-
- case 5:
- h ^= ui64(data2[4]) << 32;
+
+ case 5:
+ h ^= ui64(data2[4]) << 32;
[[fallthrough]];
-
- case 4:
- h ^= ui64(data2[3]) << 24;
+
+ case 4:
+ h ^= ui64(data2[3]) << 24;
[[fallthrough]];
-
- case 3:
- h ^= ui64(data2[2]) << 16;
+
+ case 3:
+ h ^= ui64(data2[2]) << 16;
[[fallthrough]];
-
- case 2:
- h ^= ui64(data2[1]) << 8;
+
+ case 2:
+ h ^= ui64(data2[1]) << 8;
[[fallthrough]];
-
- case 1:
- h ^= ui64(data2[0]);
- h *= m;
+
+ case 1:
+ h ^= ui64(data2[0]);
+ h *= m;
break;
- }
-
- h ^= h >> r;
- h *= m;
- h ^= h >> r;
-
- return h;
- }
-}
-
+ }
+
+ h ^= h >> r;
+ h *= m;
+ h ^= h >> r;
+
+ return h;
+ }
+}
+
size_t MurmurHashSizeT(const char* buf, size_t len) noexcept {
return MurmurHash<size_t>(buf, len);
}
diff --git a/util/digest/murmur.h b/util/digest/murmur.h
index eec9bcc171..6b519b430a 100644
--- a/util/digest/murmur.h
+++ b/util/digest/murmur.h
@@ -3,35 +3,35 @@
#include <util/system/defaults.h>
#include <util/generic/array_ref.h>
-/*
- * murmur2 from http://murmurhash.googlepages.com/
- *
+/*
+ * murmur2 from http://murmurhash.googlepages.com/
+ *
*/
-namespace NMurmurPrivate {
+namespace NMurmurPrivate {
Y_PURE_FUNCTION ui32 MurmurHash32(const void* key, size_t len, ui32 seed) noexcept;
Y_PURE_FUNCTION ui64 MurmurHash64(const void* key, size_t len, ui64 seed) noexcept;
- template <unsigned N>
- struct TMurHelper;
-
-#define DEF_MUR(t) \
- template <> \
- struct TMurHelper<t> { \
- static inline ui##t MurmurHash(const void* buf, size_t len, ui##t init) noexcept { \
- return MurmurHash##t(buf, len, init); \
- } \
- };
-
- DEF_MUR(32)
- DEF_MUR(64)
-
-#undef DEF_MUR
+ template <unsigned N>
+ struct TMurHelper;
+
+#define DEF_MUR(t) \
+ template <> \
+ struct TMurHelper<t> { \
+ static inline ui##t MurmurHash(const void* buf, size_t len, ui##t init) noexcept { \
+ return MurmurHash##t(buf, len, init); \
+ } \
+ };
+
+ DEF_MUR(32)
+ DEF_MUR(64)
+
+#undef DEF_MUR
}
template <class T>
-static inline T MurmurHash(const void* buf, size_t len, T init) noexcept {
- return (T)NMurmurPrivate::TMurHelper<8 * sizeof(T)>::MurmurHash(buf, len, init);
+static inline T MurmurHash(const void* buf, size_t len, T init) noexcept {
+ return (T)NMurmurPrivate::TMurHelper<8 * sizeof(T)>::MurmurHash(buf, len, init);
}
template <class T>
diff --git a/util/folder/path_ut.cpp b/util/folder/path_ut.cpp
index e170817368..e6a3451016 100644
--- a/util/folder/path_ut.cpp
+++ b/util/folder/path_ut.cpp
@@ -65,7 +65,7 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
++checksCounter;
current = current.Parent();
}
- UNIT_ASSERT_VALUES_EQUAL(checksCounter, 6);
+ UNIT_ASSERT_VALUES_EQUAL(checksCounter, 6);
path.MkDirs();
UNIT_ASSERT(path.Exists());
@@ -88,32 +88,32 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
Y_UNIT_TEST(Parent) {
#ifdef _win_
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\etc/passwd").Parent(), TFsPath("\\etc"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\etc").Parent(), TFsPath("\\"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\").Parent(), TFsPath("\\"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\etc/passwd").Parent(), TFsPath("\\etc"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\etc").Parent(), TFsPath("\\"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\").Parent(), TFsPath("\\"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc\\passwd").Parent(), TFsPath("etc"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc").Parent(), TFsPath("."));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath(".\\etc").Parent(), TFsPath("."));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc\\passwd").Parent(), TFsPath("etc"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc").Parent(), TFsPath("."));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath(".\\etc").Parent(), TFsPath("."));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("C:\\etc/passwd").Parent(), TFsPath("C:\\etc"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("C:\\etc").Parent(), TFsPath("C:\\"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("C:\\").Parent(), TFsPath("C:\\"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("C:\\etc/passwd").Parent(), TFsPath("C:\\etc"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("C:\\etc").Parent(), TFsPath("C:\\"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("C:\\").Parent(), TFsPath("C:\\"));
#else
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("/etc/passwd").Parent(), TFsPath("/etc"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("/etc").Parent(), TFsPath("/"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("/").Parent(), TFsPath("/"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("/etc/passwd").Parent(), TFsPath("/etc"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("/etc").Parent(), TFsPath("/"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("/").Parent(), TFsPath("/"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc/passwd").Parent(), TFsPath("etc"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc").Parent(), TFsPath("."));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("./etc").Parent(), TFsPath("."));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc/passwd").Parent(), TFsPath("etc"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc").Parent(), TFsPath("."));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("./etc").Parent(), TFsPath("."));
#endif
#if 0
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("./etc/passwd").Parent(), TFsPath("./etc"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("./").Parent(), TFsPath(".."));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath(".").Parent(), TFsPath(".."));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("..").Parent(), TFsPath("../.."));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("./etc/passwd").Parent(), TFsPath("./etc"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("./").Parent(), TFsPath(".."));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath(".").Parent(), TFsPath(".."));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("..").Parent(), TFsPath("../.."));
#endif
}
@@ -131,11 +131,11 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
Y_UNIT_TEST(GetExtension) {
TTestDirectory d("GetExtension");
- UNIT_ASSERT_VALUES_EQUAL("", d.Child("a").GetExtension());
- UNIT_ASSERT_VALUES_EQUAL("", d.Child(".a").GetExtension());
- UNIT_ASSERT_VALUES_EQUAL("", d.Child("zlib").GetExtension());
- UNIT_ASSERT_VALUES_EQUAL("zlib", d.Child("file.zlib").GetExtension());
- UNIT_ASSERT_VALUES_EQUAL("zlib", d.Child("file.ylib.zlib").GetExtension());
+ UNIT_ASSERT_VALUES_EQUAL("", d.Child("a").GetExtension());
+ UNIT_ASSERT_VALUES_EQUAL("", d.Child(".a").GetExtension());
+ UNIT_ASSERT_VALUES_EQUAL("", d.Child("zlib").GetExtension());
+ UNIT_ASSERT_VALUES_EQUAL("zlib", d.Child("file.zlib").GetExtension());
+ UNIT_ASSERT_VALUES_EQUAL("zlib", d.Child("file.ylib.zlib").GetExtension());
}
Y_UNIT_TEST(TestRename) {
@@ -183,21 +183,21 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
TFsPath target2 = td.Child("target2");
target2.Touch();
UNIT_ASSERT(NFs::SymLink(target1.RealPath(), link.GetPath()));
- UNIT_ASSERT_VALUES_EQUAL(link.RealPath(), target1.RealPath());
+ UNIT_ASSERT_VALUES_EQUAL(link.RealPath(), target1.RealPath());
UNIT_ASSERT(NFs::Remove(link.GetPath()));
UNIT_ASSERT(NFs::SymLink(target2.RealPath(), link.GetPath()));
- UNIT_ASSERT_VALUES_EQUAL(link.RealPath(), target2.RealPath()); // must not cache old value
+ UNIT_ASSERT_VALUES_EQUAL(link.RealPath(), target2.RealPath()); // must not cache old value
}
#endif
Y_UNIT_TEST(TestSlashesAndBasename) {
TFsPath p("/db/BASE/primus121-025-1380131338//");
- UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("primus121-025-1380131338"));
+ UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("primus121-025-1380131338"));
TFsPath testP = p / "test";
#ifdef _win_
- UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "\\db\\BASE\\primus121-025-1380131338\\test");
+ UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "\\db\\BASE\\primus121-025-1380131338\\test");
#else
- UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "/db/BASE/primus121-025-1380131338/test");
+ UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "/db/BASE/primus121-025-1380131338/test");
#endif
}
@@ -205,11 +205,11 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
TFsPath p("\\db\\BASE\\primus121-025-1380131338\\\\");
TFsPath testP = p / "test";
#ifdef _win_
- UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("primus121-025-1380131338"));
- UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "\\db\\BASE\\primus121-025-1380131338\\test");
+ UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("primus121-025-1380131338"));
+ UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "\\db\\BASE\\primus121-025-1380131338\\test");
#else
- UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("\\db\\BASE\\primus121-025-1380131338\\\\"));
- UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "\\db\\BASE\\primus121-025-1380131338\\\\/test");
+ UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("\\db\\BASE\\primus121-025-1380131338\\\\"));
+ UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "\\db\\BASE\\primus121-025-1380131338\\\\/test");
#endif
}
@@ -217,11 +217,11 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
TFsPath p("C:\\db\\BASE\\primus121-025-1380131338\\\\");
TFsPath testP = p / "test";
#ifdef _win_
- UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("primus121-025-1380131338"));
- UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "C:\\db\\BASE\\primus121-025-1380131338\\test");
+ UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("primus121-025-1380131338"));
+ UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "C:\\db\\BASE\\primus121-025-1380131338\\test");
#else
- UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("C:\\db\\BASE\\primus121-025-1380131338\\\\"));
- UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "C:\\db\\BASE\\primus121-025-1380131338\\\\/test");
+ UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("C:\\db\\BASE\\primus121-025-1380131338\\\\"));
+ UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "C:\\db\\BASE\\primus121-025-1380131338\\\\/test");
#endif
}
@@ -245,7 +245,7 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
expected.push_back("c");
expected.push_back("d");
- UNIT_ASSERT_VALUES_EQUAL(expected, children);
+ UNIT_ASSERT_VALUES_EQUAL(expected, children);
}
#ifdef _unix_
@@ -264,7 +264,7 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
#endif
Y_UNIT_TEST(Cwd) {
- UNIT_ASSERT_VALUES_EQUAL(TFsPath::Cwd().RealPath(), TFsPath(".").RealPath());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath::Cwd().RealPath(), TFsPath(".").RealPath());
}
Y_UNIT_TEST(TestSubpathOf) {
@@ -335,55 +335,55 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
}
Y_UNIT_TEST(TestRelativePath) {
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/b/c/d").RelativePath(TFsPath("/a/b")), TFsPath("c/d"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/b/c/d").RelativePath(TFsPath("/a/b/e/f")), TFsPath("../../c/d"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("/").RelativePath(TFsPath("/")), TFsPath());
- UNIT_ASSERT_VALUES_EQUAL(TFsPath(".").RelativePath(TFsPath(".")), TFsPath());
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/c").RelativePath(TFsPath("/a/b/../c")), TFsPath());
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("a/.././b").RelativePath(TFsPath("b/c")), TFsPath(".."));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/b/c/d").RelativePath(TFsPath("/a/b")), TFsPath("c/d"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/b/c/d").RelativePath(TFsPath("/a/b/e/f")), TFsPath("../../c/d"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("/").RelativePath(TFsPath("/")), TFsPath());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath(".").RelativePath(TFsPath(".")), TFsPath());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/c").RelativePath(TFsPath("/a/b/../c")), TFsPath());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("a/.././b").RelativePath(TFsPath("b/c")), TFsPath(".."));
UNIT_ASSERT_EXCEPTION(TFsPath("a/b/c").RelativePath(TFsPath("d/e")), TIoException);
}
Y_UNIT_TEST(TestUndefined) {
- UNIT_ASSERT_VALUES_EQUAL(TFsPath(), TFsPath(""));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath(), TFsPath().Fix());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath(), TFsPath(""));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath(), TFsPath().Fix());
- UNIT_ASSERT_VALUES_EQUAL(TFsPath() / TFsPath(), TFsPath());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath() / TFsPath(), TFsPath());
#ifdef _win_
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("a\\b"), TFsPath() / TString("a\\b"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("a\\b"), "a\\b" / TFsPath());
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\a\\b"), TFsPath() / "\\a\\b");
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\a\\b"), "\\a\\b" / TFsPath());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("a\\b"), TFsPath() / TString("a\\b"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("a\\b"), "a\\b" / TFsPath());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\a\\b"), TFsPath() / "\\a\\b");
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\a\\b"), "\\a\\b" / TFsPath());
#else
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("a/b"), TFsPath() / TString("a/b"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("a/b"), "a/b" / TFsPath());
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/b"), TFsPath() / "/a/b");
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/b"), "/a/b" / TFsPath());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("a/b"), TFsPath() / TString("a/b"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("a/b"), "a/b" / TFsPath());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/b"), TFsPath() / "/a/b");
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/b"), "/a/b" / TFsPath());
#endif
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("."), TFsPath() / ".");
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("."), "." / TFsPath());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("."), TFsPath() / ".");
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("."), "." / TFsPath());
UNIT_ASSERT(TFsPath().PathSplit().empty());
UNIT_ASSERT(!TFsPath().PathSplit().IsAbsolute);
UNIT_ASSERT(TFsPath().IsRelative()); // undefined path is relative
- UNIT_ASSERT_VALUES_EQUAL(TFsPath().GetPath(), "");
- UNIT_ASSERT_VALUES_EQUAL(TFsPath().GetName(), "");
- UNIT_ASSERT_VALUES_EQUAL(TFsPath().GetExtension(), "");
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath().GetPath(), "");
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath().GetName(), "");
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath().GetExtension(), "");
- UNIT_ASSERT_VALUES_EQUAL(TFsPath().Parent(), TFsPath());
- UNIT_ASSERT_VALUES_EQUAL(TFsPath().Child("a"), TFsPath("a"));
- UNIT_ASSERT_VALUES_EQUAL(TFsPath().Basename(), "");
- UNIT_ASSERT_VALUES_EQUAL(TFsPath().Dirname(), "");
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath().Parent(), TFsPath());
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath().Child("a"), TFsPath("a"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath().Basename(), "");
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath().Dirname(), "");
UNIT_ASSERT(!TFsPath().IsSubpathOf("a/b"));
UNIT_ASSERT(TFsPath().IsContainerOf("a/b"));
UNIT_ASSERT(!TFsPath().IsContainerOf("/a/b"));
#ifdef _win_
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("a\\b").RelativeTo(TFsPath()), TFsPath("a\\b"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("a\\b").RelativeTo(TFsPath()), TFsPath("a\\b"));
#else
- UNIT_ASSERT_VALUES_EQUAL(TFsPath("a/b").RelativeTo(TFsPath()), TFsPath("a/b"));
+ UNIT_ASSERT_VALUES_EQUAL(TFsPath("a/b").RelativeTo(TFsPath()), TFsPath("a/b"));
#endif
UNIT_ASSERT(!TFsPath().Exists());
diff --git a/util/generic/algorithm.h b/util/generic/algorithm.h
index 821ba709d0..badfb88993 100644
--- a/util/generic/algorithm.h
+++ b/util/generic/algorithm.h
@@ -73,16 +73,16 @@ static inline void StableSort(T f, T l, C c) {
std::stable_sort(f, l, c);
}
-template <class TContainer>
-static inline void StableSort(TContainer& container) {
- StableSort(container.begin(), container.end());
-}
-
-template <class TContainer, typename TCompare>
-static inline void StableSort(TContainer& container, TCompare compare) {
- StableSort(container.begin(), container.end(), compare);
-}
-
+template <class TContainer>
+static inline void StableSort(TContainer& container) {
+ StableSort(container.begin(), container.end());
+}
+
+template <class TContainer, typename TCompare>
+static inline void StableSort(TContainer& container, TCompare compare) {
+ StableSort(container.begin(), container.end(), compare);
+}
+
template <class TIterator, typename TGetKey>
static inline void StableSortBy(TIterator begin, TIterator end, const TGetKey& getKey) {
StableSort(begin, end, [&](auto&& left, auto&& right) { return getKey(left) < getKey(right); });
@@ -278,11 +278,11 @@ static inline I LowerBound(I f, I l, const T& v, C c) {
return std::lower_bound(f, l, v, c);
}
-template <class I, class T, class TGetKey>
-static inline I LowerBoundBy(I f, I l, const T& v, const TGetKey& getKey) {
- return std::lower_bound(f, l, v, [&](auto&& left, auto&& right) { return getKey(left) < right; });
-}
-
+template <class I, class T, class TGetKey>
+static inline I LowerBoundBy(I f, I l, const T& v, const TGetKey& getKey) {
+ return std::lower_bound(f, l, v, [&](auto&& left, auto&& right) { return getKey(left) < right; });
+}
+
template <class I, class T>
static inline I UpperBound(I f, I l, const T& v) {
return std::upper_bound(f, l, v);
@@ -293,11 +293,11 @@ static inline I UpperBound(I f, I l, const T& v, C c) {
return std::upper_bound(f, l, v, c);
}
-template <class I, class T, class TGetKey>
-static inline I UpperBoundBy(I f, I l, const T& v, const TGetKey& getKey) {
- return std::upper_bound(f, l, v, [&](auto&& left, auto&& right) { return left < getKey(right); });
-}
-
+template <class I, class T, class TGetKey>
+static inline I UpperBoundBy(I f, I l, const T& v, const TGetKey& getKey) {
+ return std::upper_bound(f, l, v, [&](auto&& left, auto&& right) { return left < getKey(right); });
+}
+
template <class T>
static inline T Unique(T f, T l) {
return std::unique(f, l);
diff --git a/util/generic/algorithm_ut.cpp b/util/generic/algorithm_ut.cpp
index 58a3b56956..8d732fcc0c 100644
--- a/util/generic/algorithm_ut.cpp
+++ b/util/generic/algorithm_ut.cpp
@@ -446,61 +446,61 @@ Y_UNIT_TEST_SUITE(TAlgorithm) {
}
Y_UNIT_TEST(SortTestTwoIterators) {
- TVector<int> collection = {10, 2, 7};
- Sort(collection.begin(), collection.end());
- TVector<int> expected = {2, 7, 10};
- UNIT_ASSERT_VALUES_EQUAL(collection, expected);
- }
-
+ TVector<int> collection = {10, 2, 7};
+ Sort(collection.begin(), collection.end());
+ TVector<int> expected = {2, 7, 10};
+ UNIT_ASSERT_VALUES_EQUAL(collection, expected);
+ }
+
Y_UNIT_TEST(SortTestTwoIteratorsAndComparator) {
- TVector<int> collection = {10, 2, 7};
- Sort(collection.begin(), collection.end(), [](int l, int r) { return l > r; });
- TVector<int> expected = {10, 7, 2};
- UNIT_ASSERT_VALUES_EQUAL(collection, expected);
- }
-
+ TVector<int> collection = {10, 2, 7};
+ Sort(collection.begin(), collection.end(), [](int l, int r) { return l > r; });
+ TVector<int> expected = {10, 7, 2};
+ UNIT_ASSERT_VALUES_EQUAL(collection, expected);
+ }
+
Y_UNIT_TEST(SortTestContainer) {
- TVector<int> collection = {10, 2, 7};
- Sort(collection);
- TVector<int> expected = {2, 7, 10};
- UNIT_ASSERT_VALUES_EQUAL(collection, expected);
- }
-
+ TVector<int> collection = {10, 2, 7};
+ Sort(collection);
+ TVector<int> expected = {2, 7, 10};
+ UNIT_ASSERT_VALUES_EQUAL(collection, expected);
+ }
+
Y_UNIT_TEST(SortTestContainerAndComparator) {
- TVector<int> collection = {10, 2, 7};
- Sort(collection, [](int l, int r) { return l > r; });
- TVector<int> expected = {10, 7, 2};
- UNIT_ASSERT_VALUES_EQUAL(collection, expected);
- }
-
+ TVector<int> collection = {10, 2, 7};
+ Sort(collection, [](int l, int r) { return l > r; });
+ TVector<int> expected = {10, 7, 2};
+ UNIT_ASSERT_VALUES_EQUAL(collection, expected);
+ }
+
Y_UNIT_TEST(StableSortTestTwoIterators) {
- TVector<int> collection = {10, 2, 7};
- StableSort(collection.begin(), collection.end());
- TVector<int> expected = {2, 7, 10};
- UNIT_ASSERT_VALUES_EQUAL(collection, expected);
- }
-
+ TVector<int> collection = {10, 2, 7};
+ StableSort(collection.begin(), collection.end());
+ TVector<int> expected = {2, 7, 10};
+ UNIT_ASSERT_VALUES_EQUAL(collection, expected);
+ }
+
Y_UNIT_TEST(StableSortTestTwoIteratorsAndComparator) {
- TVector<int> collection = {404, 101, 106, 203, 102, 205, 401};
- StableSort(collection.begin(), collection.end(), [](int l, int r) { return (l / 100) < (r / 100); });
- TVector<int> expected = {101, 106, 102, 203, 205, 404, 401};
- UNIT_ASSERT_VALUES_EQUAL(collection, expected);
- }
-
+ TVector<int> collection = {404, 101, 106, 203, 102, 205, 401};
+ StableSort(collection.begin(), collection.end(), [](int l, int r) { return (l / 100) < (r / 100); });
+ TVector<int> expected = {101, 106, 102, 203, 205, 404, 401};
+ UNIT_ASSERT_VALUES_EQUAL(collection, expected);
+ }
+
Y_UNIT_TEST(StableSortTestContainer) {
- TVector<int> collection = {10, 2, 7};
- StableSort(collection);
- TVector<int> expected = {2, 7, 10};
- UNIT_ASSERT_VALUES_EQUAL(collection, expected);
- }
-
+ TVector<int> collection = {10, 2, 7};
+ StableSort(collection);
+ TVector<int> expected = {2, 7, 10};
+ UNIT_ASSERT_VALUES_EQUAL(collection, expected);
+ }
+
Y_UNIT_TEST(StableSortTestContainerAndComparator) {
- TVector<int> collection = {404, 101, 106, 203, 102, 205, 401};
- StableSort(collection, [](int l, int r) { return (l / 100) < (r / 100); });
- TVector<int> expected = {101, 106, 102, 203, 205, 404, 401};
- UNIT_ASSERT_VALUES_EQUAL(collection, expected);
- }
-
+ TVector<int> collection = {404, 101, 106, 203, 102, 205, 401};
+ StableSort(collection, [](int l, int r) { return (l / 100) < (r / 100); });
+ TVector<int> expected = {101, 106, 102, 203, 205, 404, 401};
+ UNIT_ASSERT_VALUES_EQUAL(collection, expected);
+ }
+
Y_UNIT_TEST(SortByTest) {
TVector<int> collection = {10, 2, 7};
SortBy(collection, [](int x) { return -x; });
@@ -796,45 +796,45 @@ Y_UNIT_TEST_SUITE(TAlgorithm) {
auto i = FindIf(range, [](auto) { return false; });
Y_UNUSED(i);
}
-
+
Y_UNIT_TEST(TestLowerBoundBy) {
using TIntPairs = TVector<std::pair<i32, i32>>;
-
- auto data = TIntPairs{{1, 5}, {3, 2}, {3, 4}, {8, 0}, {5, 4}};
- auto getKey = [](const auto& x) { return x.second; };
-
- StableSortBy(data, getKey);
-
- auto it = LowerBoundBy(data.begin(), data.end(), 4, getKey);
- UNIT_ASSERT(it != data.end());
- UNIT_ASSERT_EQUAL(it->second, 4);
- UNIT_ASSERT_EQUAL(it->first, 3);
-
- UNIT_ASSERT(it > data.begin());
- UNIT_ASSERT_EQUAL((it - 1)->second, 2);
-
- UNIT_ASSERT((it + 1) < data.end());
- UNIT_ASSERT_EQUAL((it + 1)->second, 4);
- }
-
+
+ auto data = TIntPairs{{1, 5}, {3, 2}, {3, 4}, {8, 0}, {5, 4}};
+ auto getKey = [](const auto& x) { return x.second; };
+
+ StableSortBy(data, getKey);
+
+ auto it = LowerBoundBy(data.begin(), data.end(), 4, getKey);
+ UNIT_ASSERT(it != data.end());
+ UNIT_ASSERT_EQUAL(it->second, 4);
+ UNIT_ASSERT_EQUAL(it->first, 3);
+
+ UNIT_ASSERT(it > data.begin());
+ UNIT_ASSERT_EQUAL((it - 1)->second, 2);
+
+ UNIT_ASSERT((it + 1) < data.end());
+ UNIT_ASSERT_EQUAL((it + 1)->second, 4);
+ }
+
Y_UNIT_TEST(TestUpperBoundBy) {
using TIntPairs = TVector<std::pair<i32, i32>>;
-
- auto data = TIntPairs{{1, 5}, {3, 2}, {3, 4}, {8, 0}, {5, 4}};
- auto getKey = [](const auto& x) { return x.second; };
-
- StableSortBy(data, getKey);
-
- auto it = UpperBoundBy(data.begin(), data.end(), 4, getKey);
- UNIT_ASSERT(it != data.end());
- UNIT_ASSERT_EQUAL(it->second, 5);
- UNIT_ASSERT_EQUAL(it->first, 1);
-
- UNIT_ASSERT(it > data.begin());
- UNIT_ASSERT_EQUAL((it - 1)->second, 4);
-
- UNIT_ASSERT((it + 1) == data.end());
- }
+
+ auto data = TIntPairs{{1, 5}, {3, 2}, {3, 4}, {8, 0}, {5, 4}};
+ auto getKey = [](const auto& x) { return x.second; };
+
+ StableSortBy(data, getKey);
+
+ auto it = UpperBoundBy(data.begin(), data.end(), 4, getKey);
+ UNIT_ASSERT(it != data.end());
+ UNIT_ASSERT_EQUAL(it->second, 5);
+ UNIT_ASSERT_EQUAL(it->first, 1);
+
+ UNIT_ASSERT(it > data.begin());
+ UNIT_ASSERT_EQUAL((it - 1)->second, 4);
+
+ UNIT_ASSERT((it + 1) == data.end());
+ }
Y_UNIT_TEST(TestFindInContainer) {
std::vector<int> v = {1, 2, 1000, 15, 100};
diff --git a/util/generic/benchmark/fastclp2/metrics/main.py b/util/generic/benchmark/fastclp2/metrics/main.py
index 9e260653e2..5573c6a5d7 100644
--- a/util/generic/benchmark/fastclp2/metrics/main.py
+++ b/util/generic/benchmark/fastclp2/metrics/main.py
@@ -2,4 +2,4 @@ import yatest.common as yc
def test_export_metrics(metrics):
- metrics.set_benchmark(yc.execute_benchmark('util/generic/benchmark/fastclp2/fastclp2', threads=8))
+ metrics.set_benchmark(yc.execute_benchmark('util/generic/benchmark/fastclp2/fastclp2', threads=8))
diff --git a/util/generic/benchmark/log2/metrics/main.py b/util/generic/benchmark/log2/metrics/main.py
index 3ce98f91d0..26f6b57812 100644
--- a/util/generic/benchmark/log2/metrics/main.py
+++ b/util/generic/benchmark/log2/metrics/main.py
@@ -2,4 +2,4 @@ import yatest.common as yc
def test_export_metrics(metrics):
- metrics.set_benchmark(yc.execute_benchmark('util/generic/benchmark/log2/log2', threads=8))
+ metrics.set_benchmark(yc.execute_benchmark('util/generic/benchmark/log2/log2', threads=8))
diff --git a/util/generic/benchmark/rotate_bits/metrics/main.py b/util/generic/benchmark/rotate_bits/metrics/main.py
index 599825423a..b30555775f 100644
--- a/util/generic/benchmark/rotate_bits/metrics/main.py
+++ b/util/generic/benchmark/rotate_bits/metrics/main.py
@@ -2,4 +2,4 @@ import yatest.common as yc
def test_export_metrics(metrics):
- metrics.set_benchmark(yc.execute_benchmark('util/generic/benchmark/rotate_bits/rotate_bits', threads=8))
+ metrics.set_benchmark(yc.execute_benchmark('util/generic/benchmark/rotate_bits/rotate_bits', threads=8))
diff --git a/util/generic/benchmark/string/benchmarks.h b/util/generic/benchmark/string/benchmarks.h
index 8bd6ec9e7f..e347d7ff47 100644
--- a/util/generic/benchmark/string/benchmarks.h
+++ b/util/generic/benchmark/string/benchmarks.h
@@ -1,5 +1,5 @@
-#pragma once
-
+#pragma once
+
// Define BENCHMARK_PREFIX and BENCHMARKED_CLASS before including this file.
#include <util/generic/xrange.h>
diff --git a/util/generic/benchmark/vector_count_ctor/metrics/main.py b/util/generic/benchmark/vector_count_ctor/metrics/main.py
index d84e229110..835b44fe5f 100644
--- a/util/generic/benchmark/vector_count_ctor/metrics/main.py
+++ b/util/generic/benchmark/vector_count_ctor/metrics/main.py
@@ -2,4 +2,4 @@ import yatest.common as yc
def test_export_metrics(metrics):
- metrics.set_benchmark(yc.execute_benchmark('util/generic/benchmark/vector_count_ctor/vector_count_ctor', threads=8))
+ metrics.set_benchmark(yc.execute_benchmark('util/generic/benchmark/vector_count_ctor/vector_count_ctor', threads=8))
diff --git a/util/generic/flags.h b/util/generic/flags.h
index 5898195d7c..a1f5921d42 100644
--- a/util/generic/flags.h
+++ b/util/generic/flags.h
@@ -59,10 +59,10 @@ public:
return Value_;
}
- constexpr static TFlags FromBaseType(TInt value) {
+ constexpr static TFlags FromBaseType(TInt value) {
return TFlags(TFlag(value));
- }
-
+ }
+
constexpr friend TFlags operator|(TFlags l, TFlags r) {
return TFlags(TFlag(l.Value_ | r.Value_));
}
diff --git a/util/generic/flags_ut.cpp b/util/generic/flags_ut.cpp
index ff11d07f31..5377c6a058 100644
--- a/util/generic/flags_ut.cpp
+++ b/util/generic/flags_ut.cpp
@@ -100,18 +100,18 @@ Y_UNIT_TEST_SUITE(TFlagsTest) {
UNIT_ASSERT_VALUES_EQUAL(hash[value0], 0);
UNIT_ASSERT_VALUES_EQUAL(hash[value1], 1);
}
-
+
Y_UNIT_TEST(TestBaseType) {
- ui16 goodValue = 7;
- auto goodFlags = ETest1::FromBaseType(goodValue);
+ ui16 goodValue = 7;
+ auto goodFlags = ETest1::FromBaseType(goodValue);
UNIT_ASSERT(goodFlags& ETestFlag1::Test1);
UNIT_ASSERT(goodFlags& ETestFlag1::Test2);
UNIT_ASSERT(goodFlags& ETestFlag1::Test4);
- UNIT_ASSERT_VALUES_EQUAL(goodValue, goodFlags.ToBaseType());
-
- // Passed value is not checked, but preserved as is
- ui16 badValue = 1024;
- auto badFlags = ETest1::FromBaseType(badValue);
- UNIT_ASSERT_VALUES_EQUAL(badValue, badFlags.ToBaseType());
- }
+ UNIT_ASSERT_VALUES_EQUAL(goodValue, goodFlags.ToBaseType());
+
+ // Passed value is not checked, but preserved as is
+ ui16 badValue = 1024;
+ auto badFlags = ETest1::FromBaseType(badValue);
+ UNIT_ASSERT_VALUES_EQUAL(badValue, badFlags.ToBaseType());
+ }
}
diff --git a/util/generic/hash_ut.pyx b/util/generic/hash_ut.pyx
index 172b5d1252..ecf6dac2e6 100644
--- a/util/generic/hash_ut.pyx
+++ b/util/generic/hash_ut.pyx
@@ -11,9 +11,9 @@ from cython.operator cimport dereference as deref
def _check_convert(THashMap[TString, int] x):
- return x
-
-
+ return x
+
+
class TestHash(unittest.TestCase):
def test_constructors_and_assignments(self):
@@ -75,10 +75,10 @@ class TestHash(unittest.TestCase):
self.assertTrue(it != tmp.end())
self.assertEqual(deref(it).second, 1)
- def test_convert(self):
- src = {'foo': 1, 'bar': 42}
- self.assertEqual(_check_convert(src), src)
-
- bad_src = {'foo': 1, 'bar': 'baz'}
- with self.assertRaises(TypeError):
- _check_convert(bad_src)
+ def test_convert(self):
+ src = {'foo': 1, 'bar': 42}
+ self.assertEqual(_check_convert(src), src)
+
+ bad_src = {'foo': 1, 'bar': 'baz'}
+ with self.assertRaises(TypeError):
+ _check_convert(bad_src)
diff --git a/util/generic/iterator.h b/util/generic/iterator.h
index b34be9c28c..19e9d20976 100644
--- a/util/generic/iterator.h
+++ b/util/generic/iterator.h
@@ -1,8 +1,8 @@
#pragma once
#include <iterator>
-#include <utility>
-
+#include <utility>
+
namespace NStlIterator {
template <class T>
class TProxy {
@@ -68,31 +68,31 @@ class TInputRangeAdaptor {
public: // TODO: private
class TIterator {
public:
- static constexpr bool IsNoexceptNext = noexcept(std::declval<TSlave>().Next());
-
+ static constexpr bool IsNoexceptNext = noexcept(std::declval<TSlave>().Next());
+
using difference_type = std::ptrdiff_t;
using pointer = decltype(std::declval<TSlave>().Next());
using reference = decltype(*std::declval<TSlave>().Next());
using value_type = std::remove_cv_t<std::remove_reference_t<reference>>;
using iterator_category = std::input_iterator_tag;
- inline TIterator() noexcept
+ inline TIterator() noexcept
: Slave_(nullptr)
, Cur_()
{
}
- inline TIterator(TSlave* slave) noexcept(IsNoexceptNext)
+ inline TIterator(TSlave* slave) noexcept(IsNoexceptNext)
: Slave_(slave)
, Cur_(Slave_->Next())
{
}
- inline bool operator==(const TIterator& it) const noexcept {
+ inline bool operator==(const TIterator& it) const noexcept {
return Cur_ == it.Cur_;
}
- inline bool operator!=(const TIterator& it) const noexcept {
+ inline bool operator!=(const TIterator& it) const noexcept {
return !(*this == it);
}
@@ -104,7 +104,7 @@ public: // TODO: private
return *Cur_;
}
- inline TIterator& operator++() noexcept(IsNoexceptNext) {
+ inline TIterator& operator++() noexcept(IsNoexceptNext) {
Cur_ = Slave_->Next();
return *this;
diff --git a/util/generic/list_ut.pyx b/util/generic/list_ut.pyx
index 9ae44c5ffd..129e5bc9b6 100644
--- a/util/generic/list_ut.pyx
+++ b/util/generic/list_ut.pyx
@@ -1,158 +1,158 @@
from util.generic.list cimport TList
-
-import unittest
+
+import unittest
from cython.operator cimport preincrement
-
-
+
+
class TestList(unittest.TestCase):
-
- def test_ctor1(self):
+
+ def test_ctor1(self):
cdef TList[int] tmp = TList[int]()
- self.assertEqual(tmp.size(), 0)
-
- def test_ctor2(self):
+ self.assertEqual(tmp.size(), 0)
+
+ def test_ctor2(self):
cdef TList[int] tmp = TList[int](10, 42)
- self.assertEqual(tmp.size(), 10)
+ self.assertEqual(tmp.size(), 10)
self.assertEqual(tmp.front(), 42)
-
- def test_ctor3(self):
+
+ def test_ctor3(self):
cdef TList[int] tmp = TList[int](10, 42)
cdef TList[int] tmp2 = TList[int](tmp)
- self.assertEqual(tmp2.size(), 10)
+ self.assertEqual(tmp2.size(), 10)
self.assertEqual(tmp2.front(), 42)
-
- def test_operator_assign(self):
+
+ def test_operator_assign(self):
cdef TList[int] tmp2
- tmp2.push_back(1)
- tmp2.push_back(2)
-
+ tmp2.push_back(1)
+ tmp2.push_back(2)
+
cdef TList[int] tmp3
- tmp3.push_back(1)
- tmp3.push_back(3)
-
- tmp3 = tmp2
-
- def test_compare(self):
+ tmp3.push_back(1)
+ tmp3.push_back(3)
+
+ tmp3 = tmp2
+
+ def test_compare(self):
cdef TList[int] tmp1
- tmp1.push_back(1)
- tmp1.push_back(2)
-
+ tmp1.push_back(1)
+ tmp1.push_back(2)
+
cdef TList[int] tmp2
- tmp2.push_back(1)
- tmp2.push_back(2)
-
+ tmp2.push_back(1)
+ tmp2.push_back(2)
+
cdef TList[int] tmp3
- tmp3.push_back(1)
- tmp3.push_back(3)
-
- self.assertTrue(tmp1 == tmp2)
- self.assertTrue(tmp1 != tmp3)
-
- self.assertTrue(tmp1 < tmp3)
- self.assertTrue(tmp1 <= tmp3)
-
- self.assertTrue(tmp3 > tmp1)
- self.assertTrue(tmp3 >= tmp1)
-
- def test_push_pop_back(self):
+ tmp3.push_back(1)
+ tmp3.push_back(3)
+
+ self.assertTrue(tmp1 == tmp2)
+ self.assertTrue(tmp1 != tmp3)
+
+ self.assertTrue(tmp1 < tmp3)
+ self.assertTrue(tmp1 <= tmp3)
+
+ self.assertTrue(tmp3 > tmp1)
+ self.assertTrue(tmp3 >= tmp1)
+
+ def test_push_pop_back(self):
cdef TList[int] tmp
- self.assertEqual(tmp.size(), 0)
-
- tmp.push_back(42)
- self.assertEqual(tmp.size(), 1)
- self.assertEqual(tmp.back(), 42)
-
- tmp.push_back(77)
- self.assertEqual(tmp.size(), 2)
- self.assertEqual(tmp.back(), 77)
-
- tmp.pop_back()
- self.assertEqual(tmp.size(), 1)
- self.assertEqual(tmp.back(), 42)
-
- tmp.pop_back()
- self.assertEqual(tmp.size(), 0)
-
- def test_front(self):
+ self.assertEqual(tmp.size(), 0)
+
+ tmp.push_back(42)
+ self.assertEqual(tmp.size(), 1)
+ self.assertEqual(tmp.back(), 42)
+
+ tmp.push_back(77)
+ self.assertEqual(tmp.size(), 2)
+ self.assertEqual(tmp.back(), 77)
+
+ tmp.pop_back()
+ self.assertEqual(tmp.size(), 1)
+ self.assertEqual(tmp.back(), 42)
+
+ tmp.pop_back()
+ self.assertEqual(tmp.size(), 0)
+
+ def test_front(self):
cdef TList[int] tmp
- tmp.push_back(42)
- self.assertEqual(tmp.front(), 42)
-
- def test_empty(self):
+ tmp.push_back(42)
+ self.assertEqual(tmp.front(), 42)
+
+ def test_empty(self):
cdef TList[int] tmp
- self.assertTrue(tmp.empty())
- tmp.push_back(42)
- self.assertFalse(tmp.empty())
-
- def test_max_size(self):
+ self.assertTrue(tmp.empty())
+ tmp.push_back(42)
+ self.assertFalse(tmp.empty())
+
+ def test_max_size(self):
cdef TList[int] tmp
- self.assertTrue(tmp.max_size() > 0)
-
+ self.assertTrue(tmp.max_size() > 0)
+
def test_resize(self):
cdef TList[int] tmp
-
- tmp.resize(100, 42)
- self.assertEqual(tmp.size(), 100)
- self.assertEqual(tmp.front(), 42)
- self.assertEqual(tmp.back(), 42)
-
- def test_iter(self):
+
+ tmp.resize(100, 42)
+ self.assertEqual(tmp.size(), 100)
+ self.assertEqual(tmp.front(), 42)
+ self.assertEqual(tmp.back(), 42)
+
+ def test_iter(self):
cdef TList[int] tmp
- tmp.push_back(1)
- tmp.push_back(20)
- tmp.push_back(300)
-
- self.assertEqual([i for i in tmp], [1, 20, 300])
-
- def test_iterator(self):
+ tmp.push_back(1)
+ tmp.push_back(20)
+ tmp.push_back(300)
+
+ self.assertEqual([i for i in tmp], [1, 20, 300])
+
+ def test_iterator(self):
cdef TList[int] tmp
-
- self.assertTrue(tmp.begin() == tmp.end())
- self.assertTrue(tmp.rbegin() == tmp.rend())
- self.assertTrue(tmp.const_begin() == tmp.const_end())
- self.assertTrue(tmp.const_rbegin() == tmp.const_rend())
-
- tmp.push_back(1)
-
- self.assertTrue(tmp.begin() != tmp.end())
- self.assertTrue(tmp.rbegin() != tmp.rend())
- self.assertTrue(tmp.const_begin() != tmp.const_end())
- self.assertTrue(tmp.const_rbegin() != tmp.const_rend())
-
+
+ self.assertTrue(tmp.begin() == tmp.end())
+ self.assertTrue(tmp.rbegin() == tmp.rend())
+ self.assertTrue(tmp.const_begin() == tmp.const_end())
+ self.assertTrue(tmp.const_rbegin() == tmp.const_rend())
+
+ tmp.push_back(1)
+
+ self.assertTrue(tmp.begin() != tmp.end())
+ self.assertTrue(tmp.rbegin() != tmp.rend())
+ self.assertTrue(tmp.const_begin() != tmp.const_end())
+ self.assertTrue(tmp.const_rbegin() != tmp.const_rend())
+
self.assertTrue(preincrement(tmp.begin()) == tmp.end())
self.assertTrue(preincrement(tmp.rbegin()) == tmp.rend())
self.assertTrue(preincrement(tmp.const_begin()) == tmp.const_end())
self.assertTrue(preincrement(tmp.const_rbegin()) == tmp.const_rend())
-
- def test_assign(self):
+
+ def test_assign(self):
cdef TList[int] tmp
-
- tmp.assign(10, 42)
- self.assertEqual(tmp.size(), 10)
- self.assertEqual(tmp.front(), 42)
- self.assertEqual(tmp.back(), 42)
-
- def test_insert(self):
+
+ tmp.assign(10, 42)
+ self.assertEqual(tmp.size(), 10)
+ self.assertEqual(tmp.front(), 42)
+ self.assertEqual(tmp.back(), 42)
+
+ def test_insert(self):
cdef TList[int] tmp
- tmp.push_back(1)
- tmp.push_back(2)
- tmp.push_back(3)
-
- tmp.insert(tmp.begin(), 8)
- self.assertEqual([i for i in tmp], [8, 1, 2, 3])
-
- tmp.insert(tmp.begin(), 2, 6)
- self.assertEqual([i for i in tmp], [6, 6, 8, 1, 2, 3])
-
- def test_erase(self):
+ tmp.push_back(1)
+ tmp.push_back(2)
+ tmp.push_back(3)
+
+ tmp.insert(tmp.begin(), 8)
+ self.assertEqual([i for i in tmp], [8, 1, 2, 3])
+
+ tmp.insert(tmp.begin(), 2, 6)
+ self.assertEqual([i for i in tmp], [6, 6, 8, 1, 2, 3])
+
+ def test_erase(self):
cdef TList[int] tmp
- tmp.push_back(1)
- tmp.push_back(2)
- tmp.push_back(3)
- tmp.push_back(4)
-
+ tmp.push_back(1)
+ tmp.push_back(2)
+ tmp.push_back(3)
+ tmp.push_back(4)
+
tmp.erase(preincrement(tmp.begin()))
- self.assertEqual([i for i in tmp], [1, 3, 4])
-
+ self.assertEqual([i for i in tmp], [1, 3, 4])
+
tmp.erase(tmp.begin(), preincrement(preincrement(tmp.begin())))
- self.assertEqual([i for i in tmp], [4])
+ self.assertEqual([i for i in tmp], [4])
diff --git a/util/generic/maybe.pxd b/util/generic/maybe.pxd
index 736f44c5e6..15161dd204 100644
--- a/util/generic/maybe.pxd
+++ b/util/generic/maybe.pxd
@@ -1,35 +1,35 @@
-cdef extern from "<util/generic/maybe.h>" nogil:
- cdef cppclass TNothing:
- pass
-
- cdef TNothing Nothing()
-
- cdef cppclass TMaybe[T]:
- TMaybe(...) except +
-
- TMaybe& operator=(...) except +
-
- void ConstructInPlace(...) except +
- void Clear() except +
-
- bint Defined()
- bint Empty()
-
- void CheckDefined() except +
-
- T* Get() except +
- T& GetRef() except +
-
- T GetOrElse(T&) except +
- TMaybe OrElse(TMaybe&) except +
-
- TMaybe[U] Cast[U]() except +
-
- void Swap(TMaybe& other) except +
-
- bint operator ==[U](U&) except +
- bint operator !=[U](U&) except +
- bint operator <[U](U&) except +
- bint operator >[U](U&) except +
- bint operator <=[U](U&) except +
- bint operator >=[U](U&) except +
+cdef extern from "<util/generic/maybe.h>" nogil:
+ cdef cppclass TNothing:
+ pass
+
+ cdef TNothing Nothing()
+
+ cdef cppclass TMaybe[T]:
+ TMaybe(...) except +
+
+ TMaybe& operator=(...) except +
+
+ void ConstructInPlace(...) except +
+ void Clear() except +
+
+ bint Defined()
+ bint Empty()
+
+ void CheckDefined() except +
+
+ T* Get() except +
+ T& GetRef() except +
+
+ T GetOrElse(T&) except +
+ TMaybe OrElse(TMaybe&) except +
+
+ TMaybe[U] Cast[U]() except +
+
+ void Swap(TMaybe& other) except +
+
+ bint operator ==[U](U&) except +
+ bint operator !=[U](U&) except +
+ bint operator <[U](U&) except +
+ bint operator >[U](U&) except +
+ bint operator <=[U](U&) except +
+ bint operator >=[U](U&) except +
diff --git a/util/generic/maybe_ut.pyx b/util/generic/maybe_ut.pyx
index c983f11053..2de185c807 100644
--- a/util/generic/maybe_ut.pyx
+++ b/util/generic/maybe_ut.pyx
@@ -1,185 +1,185 @@
-from util.generic.maybe cimport TMaybe, Nothing
-
-import pytest
-import unittest
-
-
-def _check_from_py(TMaybe[int] x):
- return x.Defined()
-
-
-def _check_to_py_value():
- cdef TMaybe[int] tmp = TMaybe[int](42)
- return tmp
-
-
-def _check_to_py_nothing():
- cdef TMaybe[int] tmp = Nothing()
- return tmp
-
-
-class TestMaybe(unittest.TestCase):
-
- def test_ctor1(self):
- cdef TMaybe[int] tmp = TMaybe[int]()
- self.assertFalse(tmp.Defined())
-
- def test_ctor2(self):
- cdef TMaybe[int] tmp = TMaybe[int](42)
- self.assertTrue(tmp.Defined())
- self.assertEquals(tmp.GetRef(), 42)
-
- def test_ctor3(self):
- cdef TMaybe[int] tmp = Nothing()
- self.assertFalse(tmp.Defined())
-
- def test_operator_assign(self):
- cdef TMaybe[int] tmp
- tmp = 42
- self.assertTrue(tmp.Defined())
- self.assertEquals(tmp.GetRef(), 42)
-
- def test_compare(self):
- cdef TMaybe[int] tmp1 = 17
- cdef TMaybe[int] tmp2 = 42
- cdef TMaybe[int] nothing
-
- # ==
- self.assertTrue(tmp1 == 17)
- self.assertTrue(tmp1 == tmp1)
- self.assertTrue(nothing == nothing)
-
- self.assertFalse(tmp1 == 16)
- self.assertFalse(tmp1 == tmp2)
- self.assertFalse(tmp1 == nothing)
-
- # !=
- self.assertTrue(tmp1 != 16)
- self.assertTrue(tmp1 != tmp2)
- self.assertTrue(tmp1 != nothing)
-
- self.assertFalse(tmp1 != 17)
- self.assertFalse(tmp1 != tmp1)
- self.assertFalse(nothing != nothing)
-
- # <
- self.assertTrue(nothing < tmp1)
- self.assertTrue(nothing < tmp2)
- self.assertTrue(tmp1 < tmp2)
- self.assertTrue(nothing < 0)
- self.assertTrue(tmp1 < 18)
-
- self.assertFalse(nothing < nothing)
- self.assertFalse(tmp1 < tmp1)
- self.assertFalse(tmp2 < tmp1)
- self.assertFalse(tmp1 < 16)
-
- # <=
- self.assertTrue(nothing <= nothing)
- self.assertTrue(nothing <= tmp1)
- self.assertTrue(nothing <= tmp2)
- self.assertTrue(tmp1 <= tmp1)
- self.assertTrue(tmp1 <= tmp2)
- self.assertTrue(nothing <= 0)
- self.assertTrue(tmp1 <= 18)
-
- self.assertFalse(tmp2 <= tmp1)
- self.assertFalse(tmp1 <= 16)
-
- # >
- self.assertTrue(tmp1 > nothing)
- self.assertTrue(tmp2 > nothing)
- self.assertTrue(tmp2 > tmp1)
- self.assertTrue(tmp1 > 16)
-
- self.assertFalse(nothing > nothing)
- self.assertFalse(nothing > 0)
- self.assertFalse(tmp1 > tmp1)
- self.assertFalse(tmp1 > tmp2)
- self.assertFalse(tmp1 > 18)
-
- # >=
- self.assertTrue(nothing >= nothing)
- self.assertTrue(tmp1 >= nothing)
- self.assertTrue(tmp2 >= nothing)
- self.assertTrue(tmp2 >= tmp1)
- self.assertTrue(tmp1 >= tmp1)
- self.assertTrue(tmp1 >= 16)
-
- self.assertFalse(nothing >= 0)
- self.assertFalse(tmp1 >= tmp2)
- self.assertFalse(tmp1 >= 18)
-
- def test_construct_in_place(self):
- cdef TMaybe[int] tmp
- tmp.ConstructInPlace(42)
- self.assertTrue(tmp.Defined())
- self.assertEquals(tmp.GetRef(), 42)
-
- def test_clear(self):
- cdef TMaybe[int] tmp = 42
- tmp.Clear()
- self.assertFalse(tmp.Defined())
-
- def test_defined(self):
- cdef TMaybe[int] tmp
- self.assertFalse(tmp.Defined())
- self.assertTrue(tmp.Empty())
- tmp = 42
- self.assertTrue(tmp.Defined())
- self.assertFalse(tmp.Empty())
-
- def test_check_defined(self):
- cdef TMaybe[int] tmp
- with pytest.raises(RuntimeError):
- tmp.CheckDefined()
- tmp = 42
- tmp.CheckDefined()
-
- def test_get(self):
- cdef TMaybe[int] tmp = 42
- cdef int* p = tmp.Get()
- self.assertTrue(p != NULL)
- self.assertEquals(p[0], 42)
-
- def test_get_ref(self):
- cdef TMaybe[int] tmp = 42
- self.assertTrue(tmp.Defined())
- self.assertEquals(tmp.GetRef(), 42)
-
- def test_get_or_else(self):
- cdef TMaybe[int] tmp = 42
- self.assertEquals(tmp.GetOrElse(13), 42)
- tmp.Clear()
- self.assertEquals(tmp.GetOrElse(13), 13)
-
- def test_or_else(self):
- cdef TMaybe[int] tmp = 42
- cdef TMaybe[int] nothing
- self.assertFalse(nothing.OrElse(nothing).Defined())
- self.assertEquals(tmp.OrElse(nothing).GetRef(), 42)
- self.assertEquals(nothing.OrElse(tmp).GetRef(), 42)
- self.assertEquals(tmp.OrElse(tmp).GetRef(), 42)
-
- def test_cast(self):
- cdef TMaybe[int] tmp = 42
- cdef TMaybe[char] tmp2 = tmp.Cast[char]()
- self.assertEquals(tmp2.GetRef(), 42)
-
- def test_swap(self):
- cdef TMaybe[int] tmp1 = 42
- cdef TMaybe[int] tmp2
- tmp2.Swap(tmp1)
- self.assertFalse(tmp1.Defined())
- self.assertEquals(tmp2.GetRef(), 42)
-
- def test_from_py(self):
- self.assertTrue(_check_from_py(42))
- self.assertFalse(_check_from_py(None))
-
- with self.assertRaises(TypeError):
- _check_from_py("ttt")
-
- def test_to_py(self):
- self.assertEquals(_check_to_py_value(), 42)
- self.assertEquals(_check_to_py_nothing(), None)
+from util.generic.maybe cimport TMaybe, Nothing
+
+import pytest
+import unittest
+
+
+def _check_from_py(TMaybe[int] x):
+ return x.Defined()
+
+
+def _check_to_py_value():
+ cdef TMaybe[int] tmp = TMaybe[int](42)
+ return tmp
+
+
+def _check_to_py_nothing():
+ cdef TMaybe[int] tmp = Nothing()
+ return tmp
+
+
+class TestMaybe(unittest.TestCase):
+
+ def test_ctor1(self):
+ cdef TMaybe[int] tmp = TMaybe[int]()
+ self.assertFalse(tmp.Defined())
+
+ def test_ctor2(self):
+ cdef TMaybe[int] tmp = TMaybe[int](42)
+ self.assertTrue(tmp.Defined())
+ self.assertEquals(tmp.GetRef(), 42)
+
+ def test_ctor3(self):
+ cdef TMaybe[int] tmp = Nothing()
+ self.assertFalse(tmp.Defined())
+
+ def test_operator_assign(self):
+ cdef TMaybe[int] tmp
+ tmp = 42
+ self.assertTrue(tmp.Defined())
+ self.assertEquals(tmp.GetRef(), 42)
+
+ def test_compare(self):
+ cdef TMaybe[int] tmp1 = 17
+ cdef TMaybe[int] tmp2 = 42
+ cdef TMaybe[int] nothing
+
+ # ==
+ self.assertTrue(tmp1 == 17)
+ self.assertTrue(tmp1 == tmp1)
+ self.assertTrue(nothing == nothing)
+
+ self.assertFalse(tmp1 == 16)
+ self.assertFalse(tmp1 == tmp2)
+ self.assertFalse(tmp1 == nothing)
+
+ # !=
+ self.assertTrue(tmp1 != 16)
+ self.assertTrue(tmp1 != tmp2)
+ self.assertTrue(tmp1 != nothing)
+
+ self.assertFalse(tmp1 != 17)
+ self.assertFalse(tmp1 != tmp1)
+ self.assertFalse(nothing != nothing)
+
+ # <
+ self.assertTrue(nothing < tmp1)
+ self.assertTrue(nothing < tmp2)
+ self.assertTrue(tmp1 < tmp2)
+ self.assertTrue(nothing < 0)
+ self.assertTrue(tmp1 < 18)
+
+ self.assertFalse(nothing < nothing)
+ self.assertFalse(tmp1 < tmp1)
+ self.assertFalse(tmp2 < tmp1)
+ self.assertFalse(tmp1 < 16)
+
+ # <=
+ self.assertTrue(nothing <= nothing)
+ self.assertTrue(nothing <= tmp1)
+ self.assertTrue(nothing <= tmp2)
+ self.assertTrue(tmp1 <= tmp1)
+ self.assertTrue(tmp1 <= tmp2)
+ self.assertTrue(nothing <= 0)
+ self.assertTrue(tmp1 <= 18)
+
+ self.assertFalse(tmp2 <= tmp1)
+ self.assertFalse(tmp1 <= 16)
+
+ # >
+ self.assertTrue(tmp1 > nothing)
+ self.assertTrue(tmp2 > nothing)
+ self.assertTrue(tmp2 > tmp1)
+ self.assertTrue(tmp1 > 16)
+
+ self.assertFalse(nothing > nothing)
+ self.assertFalse(nothing > 0)
+ self.assertFalse(tmp1 > tmp1)
+ self.assertFalse(tmp1 > tmp2)
+ self.assertFalse(tmp1 > 18)
+
+ # >=
+ self.assertTrue(nothing >= nothing)
+ self.assertTrue(tmp1 >= nothing)
+ self.assertTrue(tmp2 >= nothing)
+ self.assertTrue(tmp2 >= tmp1)
+ self.assertTrue(tmp1 >= tmp1)
+ self.assertTrue(tmp1 >= 16)
+
+ self.assertFalse(nothing >= 0)
+ self.assertFalse(tmp1 >= tmp2)
+ self.assertFalse(tmp1 >= 18)
+
+ def test_construct_in_place(self):
+ cdef TMaybe[int] tmp
+ tmp.ConstructInPlace(42)
+ self.assertTrue(tmp.Defined())
+ self.assertEquals(tmp.GetRef(), 42)
+
+ def test_clear(self):
+ cdef TMaybe[int] tmp = 42
+ tmp.Clear()
+ self.assertFalse(tmp.Defined())
+
+ def test_defined(self):
+ cdef TMaybe[int] tmp
+ self.assertFalse(tmp.Defined())
+ self.assertTrue(tmp.Empty())
+ tmp = 42
+ self.assertTrue(tmp.Defined())
+ self.assertFalse(tmp.Empty())
+
+ def test_check_defined(self):
+ cdef TMaybe[int] tmp
+ with pytest.raises(RuntimeError):
+ tmp.CheckDefined()
+ tmp = 42
+ tmp.CheckDefined()
+
+ def test_get(self):
+ cdef TMaybe[int] tmp = 42
+ cdef int* p = tmp.Get()
+ self.assertTrue(p != NULL)
+ self.assertEquals(p[0], 42)
+
+ def test_get_ref(self):
+ cdef TMaybe[int] tmp = 42
+ self.assertTrue(tmp.Defined())
+ self.assertEquals(tmp.GetRef(), 42)
+
+ def test_get_or_else(self):
+ cdef TMaybe[int] tmp = 42
+ self.assertEquals(tmp.GetOrElse(13), 42)
+ tmp.Clear()
+ self.assertEquals(tmp.GetOrElse(13), 13)
+
+ def test_or_else(self):
+ cdef TMaybe[int] tmp = 42
+ cdef TMaybe[int] nothing
+ self.assertFalse(nothing.OrElse(nothing).Defined())
+ self.assertEquals(tmp.OrElse(nothing).GetRef(), 42)
+ self.assertEquals(nothing.OrElse(tmp).GetRef(), 42)
+ self.assertEquals(tmp.OrElse(tmp).GetRef(), 42)
+
+ def test_cast(self):
+ cdef TMaybe[int] tmp = 42
+ cdef TMaybe[char] tmp2 = tmp.Cast[char]()
+ self.assertEquals(tmp2.GetRef(), 42)
+
+ def test_swap(self):
+ cdef TMaybe[int] tmp1 = 42
+ cdef TMaybe[int] tmp2
+ tmp2.Swap(tmp1)
+ self.assertFalse(tmp1.Defined())
+ self.assertEquals(tmp2.GetRef(), 42)
+
+ def test_from_py(self):
+ self.assertTrue(_check_from_py(42))
+ self.assertFalse(_check_from_py(None))
+
+ with self.assertRaises(TypeError):
+ _check_from_py("ttt")
+
+ def test_to_py(self):
+ self.assertEquals(_check_to_py_value(), 42)
+ self.assertEquals(_check_to_py_nothing(), None)
diff --git a/util/generic/overloaded.h b/util/generic/overloaded.h
index eb9b58cad4..96a97e44bc 100644
--- a/util/generic/overloaded.h
+++ b/util/generic/overloaded.h
@@ -1,52 +1,52 @@
#pragma once
-/**
+/**
* Construct an ad-hoc object with an overloaded `operator()`.
- *
+ *
* Typically used with lambdas to construct type-matching visitors for e.g. std::variant:
- * ```
+ * ```
* std::variant<int, void*, TString> var;
- * Visit(TOverloaded{
- * [](int val) { Cerr << "int: " << val; },
- * [](void* val) { Cerr << "ptr: " << val; },
- * [](const TString& val) { Cerr << "str: " << val; },
- * }, var);
- * ```
- *
- * *** IMPORTANT NOTE (IMPLICIT ARGUMENT CONVERSIONS) ***
- *
- * Since the resulting objects use regular overloaded method resolution rules,
- * methods may be called by inexact matches (causing implicit casts), hence this
- * implementation does not guarantee exhaustiveness of cases.
- *
- * For example, the following code will compile and run by casting all values to
- * double:
- * ```
+ * Visit(TOverloaded{
+ * [](int val) { Cerr << "int: " << val; },
+ * [](void* val) { Cerr << "ptr: " << val; },
+ * [](const TString& val) { Cerr << "str: " << val; },
+ * }, var);
+ * ```
+ *
+ * *** IMPORTANT NOTE (IMPLICIT ARGUMENT CONVERSIONS) ***
+ *
+ * Since the resulting objects use regular overloaded method resolution rules,
+ * methods may be called by inexact matches (causing implicit casts), hence this
+ * implementation does not guarantee exhaustiveness of cases.
+ *
+ * For example, the following code will compile and run by casting all values to
+ * double:
+ * ```
* std::variant<int, double, char> var;
- * Visit(TOverloaded{
- * [](double val) { Cerr << "dbl: " << val; },
- * }, var);
- * ```
- *
- * If cases may be ambigous or specific type-matching logic is required,
- * a verbose `if constexpr`-based version would be preferred:
- * ```
+ * Visit(TOverloaded{
+ * [](double val) { Cerr << "dbl: " << val; },
+ * }, var);
+ * ```
+ *
+ * If cases may be ambigous or specific type-matching logic is required,
+ * a verbose `if constexpr`-based version would be preferred:
+ * ```
* std::variant<int, double, char> var;
- * Visit([](auto&& val) {
- * using T = std::decay_t<decltype(val)>;
- * if constexpr (std::is_same_v<T, int>) {
- * Cerr << "int: " << val;
- * } else if constexpr (std::is_same_v<T, double>) {
- * Cerr << "dbl: " << val;
- * } else if constexpr (std::is_same_v<T, char>) {
- * Cerr << "chr: " << val;
- * } else {
- * static_assert(TDependentFalse<T>, "unexpected type");
- * }
- * }, var);
- * ```
- */
-
+ * Visit([](auto&& val) {
+ * using T = std::decay_t<decltype(val)>;
+ * if constexpr (std::is_same_v<T, int>) {
+ * Cerr << "int: " << val;
+ * } else if constexpr (std::is_same_v<T, double>) {
+ * Cerr << "dbl: " << val;
+ * } else if constexpr (std::is_same_v<T, char>) {
+ * Cerr << "chr: " << val;
+ * } else {
+ * static_assert(TDependentFalse<T>, "unexpected type");
+ * }
+ * }, var);
+ * ```
+ */
+
template <class... Fs>
struct TOverloaded: Fs... {
using Fs::operator()...;
diff --git a/util/generic/overloaded_ut.cpp b/util/generic/overloaded_ut.cpp
index bf32daf475..f3d73895ad 100644
--- a/util/generic/overloaded_ut.cpp
+++ b/util/generic/overloaded_ut.cpp
@@ -1,4 +1,4 @@
-#include <util/generic/overloaded.h>
+#include <util/generic/overloaded.h>
#include <library/cpp/testing/unittest/registar.h>
@@ -35,7 +35,7 @@ Y_UNIT_TEST_SUITE(TOverloadedTest) {
[&](double) { res = -1; },
[&](TType1) { res = -1; }},
v);
- UNIT_ASSERT_VALUES_EQUAL(res, 5);
+ UNIT_ASSERT_VALUES_EQUAL(res, 5);
}
Y_UNIT_TEST(TupleTest) {
@@ -48,35 +48,35 @@ Y_UNIT_TEST_SUITE(TOverloadedTest) {
[&](bool val) { res += "(bool) " + ToString(val) + ' '; },
});
- UNIT_ASSERT_VALUES_EQUAL(res, "(int) 5 (double) 3.14 (bool) 1 (int) 20 ");
+ UNIT_ASSERT_VALUES_EQUAL(res, "(int) 5 (double) 3.14 (bool) 1 (int) 20 ");
}
-
- Y_UNIT_TEST(ImplicitConversionsTest) {
+
+ Y_UNIT_TEST(ImplicitConversionsTest) {
using TTestVariant = std::variant<int, double, char>;
-
- // Purposefully exhibit inexact overload matched with implicit type
- // conversions
-
- // All cases implicitly cast to int
- auto matchAsInt = [](TTestVariant var) {
+
+ // Purposefully exhibit inexact overload matched with implicit type
+ // conversions
+
+ // All cases implicitly cast to int
+ auto matchAsInt = [](TTestVariant var) {
return std::visit(TOverloaded{
[](int val) { return val; },
}, var);
- };
-
- UNIT_ASSERT_VALUES_EQUAL(matchAsInt(TTestVariant{17.77}), 17);
- UNIT_ASSERT_VALUES_EQUAL(matchAsInt(TTestVariant{12345}), 12345);
- UNIT_ASSERT_VALUES_EQUAL(matchAsInt(TTestVariant{'X'}), 88);
-
- // All cases implicitly cast to double
- auto matchAsDouble = [](TTestVariant var) {
+ };
+
+ UNIT_ASSERT_VALUES_EQUAL(matchAsInt(TTestVariant{17.77}), 17);
+ UNIT_ASSERT_VALUES_EQUAL(matchAsInt(TTestVariant{12345}), 12345);
+ UNIT_ASSERT_VALUES_EQUAL(matchAsInt(TTestVariant{'X'}), 88);
+
+ // All cases implicitly cast to double
+ auto matchAsDouble = [](TTestVariant var) {
return std::visit(TOverloaded{
[](double val) { return val; },
}, var);
- };
-
- UNIT_ASSERT_VALUES_EQUAL(matchAsDouble(TTestVariant{17.77}), 17.77);
- UNIT_ASSERT_VALUES_EQUAL(matchAsDouble(TTestVariant{12345}), 12345.0);
- UNIT_ASSERT_VALUES_EQUAL(matchAsDouble(TTestVariant{'X'}), 88.0);
- }
+ };
+
+ UNIT_ASSERT_VALUES_EQUAL(matchAsDouble(TTestVariant{17.77}), 17.77);
+ UNIT_ASSERT_VALUES_EQUAL(matchAsDouble(TTestVariant{12345}), 12345.0);
+ UNIT_ASSERT_VALUES_EQUAL(matchAsDouble(TTestVariant{'X'}), 88.0);
+ }
}
diff --git a/util/generic/ptr.h b/util/generic/ptr.h
index 2ef6a9ad72..19db0e3ec5 100644
--- a/util/generic/ptr.h
+++ b/util/generic/ptr.h
@@ -411,37 +411,37 @@ private:
C Counter_;
};
-/**
- * Atomically reference-counted base with a virtual destructor.
- *
- * @note Plays well with inheritance, should be used for refcounted base classes.
- */
+/**
+ * Atomically reference-counted base with a virtual destructor.
+ *
+ * @note Plays well with inheritance, should be used for refcounted base classes.
+ */
struct TThrRefBase: public TRefCounted<TThrRefBase, TAtomicCounter> {
virtual ~TThrRefBase();
};
-/**
- * Atomically reference-counted base.
- *
- * Deletes refcounted object as type T.
- *
- * @warning Additional care should be taken with regard to inheritance. If used
- * as a base class, @p T should either declare a virtual destructor, or be
+/**
+ * Atomically reference-counted base.
+ *
+ * Deletes refcounted object as type T.
+ *
+ * @warning Additional care should be taken with regard to inheritance. If used
+ * as a base class, @p T should either declare a virtual destructor, or be
* derived from @p TThrRefBase instead. Otherwise, only destructor of class @p T
- * would be called, potentially slicing the object and creating memory leaks.
- *
- * @note To avoid accidental inheritance when it is not originally intended,
- * class @p T should be marked as final.
- */
+ * would be called, potentially slicing the object and creating memory leaks.
+ *
+ * @note To avoid accidental inheritance when it is not originally intended,
+ * class @p T should be marked as final.
+ */
template <class T, class D = TDelete>
using TAtomicRefCount = TRefCounted<T, TAtomicCounter, D>;
-/**
- * Non-atomically reference-counted base.
- *
- * @warning Not thread-safe. Use with great care. If in doubt, use @p ThrRefBase
- * or @p TAtomicRefCount instead.
- */
+/**
+ * Non-atomically reference-counted base.
+ *
+ * @warning Not thread-safe. Use with great care. If in doubt, use @p ThrRefBase
+ * or @p TAtomicRefCount instead.
+ */
template <class T, class D = TDelete>
using TSimpleRefCount = TRefCounted<T, TSimpleCounter, D>;
diff --git a/util/generic/strbuf_ut.cpp b/util/generic/strbuf_ut.cpp
index 245bc3175e..69cde785af 100644
--- a/util/generic/strbuf_ut.cpp
+++ b/util/generic/strbuf_ut.cpp
@@ -28,15 +28,15 @@ Y_UNIT_TEST_SUITE(TStrBufTest) {
}
Y_UNIT_TEST(TestConstExpr) {
- static constexpr TStringBuf str1("qwe\0rty", 7);
+ static constexpr TStringBuf str1("qwe\0rty", 7);
static constexpr TStringBuf str2(str1.data(), str1.size());
static constexpr TStringBuf str3 = "qwe\0rty"sv;
-
+
UNIT_ASSERT_VALUES_EQUAL(str1.size(), 7);
-
- UNIT_ASSERT_VALUES_EQUAL(str1, str2);
- UNIT_ASSERT_VALUES_EQUAL(str2, str3);
- UNIT_ASSERT_VALUES_EQUAL(str1, str3);
+
+ UNIT_ASSERT_VALUES_EQUAL(str1, str2);
+ UNIT_ASSERT_VALUES_EQUAL(str2, str3);
+ UNIT_ASSERT_VALUES_EQUAL(str1, str3);
static constexpr std::string_view view1(str1);
UNIT_ASSERT_VALUES_EQUAL(str1, view1);
@@ -47,8 +47,8 @@ Y_UNIT_TEST_SUITE(TStrBufTest) {
UNIT_ASSERT_VALUES_EQUAL(str1, str4);
static_assert(str1.data() == str4.data());
static_assert(str1.size() == str4.size());
- }
-
+ }
+
Y_UNIT_TEST(TestAfter) {
TStringBuf str("qwerty");
diff --git a/util/generic/string.h b/util/generic/string.h
index de41fa7c0c..8cd8aa6917 100644
--- a/util/generic/string.h
+++ b/util/generic/string.h
@@ -79,11 +79,11 @@ struct TStdString: public TRefCountHolder, public B {
}
static TStdString* NullStr() noexcept {
- #ifdef _LIBCPP_VERSION
+ #ifdef _LIBCPP_VERSION
return (TStdString*)NULL_STRING_REPR;
- #else
+ #else
return Singleton<TStdString>();
- #endif
+ #endif
}
private:
diff --git a/util/generic/string.pxd b/util/generic/string.pxd
index 917c4e5a2a..c25f7392a1 100644
--- a/util/generic/string.pxd
+++ b/util/generic/string.pxd
@@ -1,8 +1,8 @@
-from libcpp.string cimport string as _std_string
+from libcpp.string cimport string as _std_string
-cdef extern from "<util/generic/strbuf.h>" nogil:
-
- cdef cppclass TStringBuf:
+cdef extern from "<util/generic/strbuf.h>" nogil:
+
+ cdef cppclass TStringBuf:
TStringBuf() except +
TStringBuf(const char*) except +
TStringBuf(const char*, size_t) except +
@@ -10,14 +10,14 @@ cdef extern from "<util/generic/strbuf.h>" nogil:
char* Data()
size_t size()
size_t Size()
-
-
+
+
cdef extern from "<util/generic/string.h>" nogil:
size_t npos "TString::npos"
- # Inheritance is bogus, but it's safe to assume TString is-a TStringBuf via implicit cast
- cdef cppclass TString(TStringBuf):
+ # Inheritance is bogus, but it's safe to assume TString is-a TStringBuf via implicit cast
+ cdef cppclass TString(TStringBuf):
TString() except +
TString(TString&) except +
TString(_std_string&) except +
@@ -28,34 +28,34 @@ cdef extern from "<util/generic/string.h>" nogil:
# as a TString formed by a repetition of character c, n times.
TString(size_t, char) except +
TString(char*, char*) except +
- TString(TStringBuf&) except +
- TString(TStringBuf&, TStringBuf&) except +
- TString(TStringBuf&, TStringBuf&, TStringBuf&) except +
+ TString(TStringBuf&) except +
+ TString(TStringBuf&, TStringBuf&) except +
+ TString(TStringBuf&, TStringBuf&, TStringBuf&) except +
const char* c_str()
size_t max_size()
size_t length()
- void resize(size_t) except +
- void resize(size_t, char c) except +
+ void resize(size_t) except +
+ void resize(size_t, char c) except +
size_t capacity()
- void reserve(size_t) except +
- void clear() except +
+ void reserve(size_t) except +
+ void clear() except +
bint empty()
char& at(size_t)
char& operator[](size_t)
- int compare(TStringBuf&)
+ int compare(TStringBuf&)
- TString& append(TStringBuf&) except +
- TString& append(TStringBuf&, size_t, size_t) except +
+ TString& append(TStringBuf&) except +
+ TString& append(TStringBuf&, size_t, size_t) except +
TString& append(char *) except +
TString& append(char *, size_t) except +
TString& append(size_t, char) except +
- void push_back(char c) except +
+ void push_back(char c) except +
- TString& assign(TStringBuf&) except +
- TString& assign(TStringBuf&, size_t, size_t) except +
+ TString& assign(TStringBuf&) except +
+ TString& assign(TStringBuf&, size_t, size_t) except +
TString& assign(char *) except +
TString& assign(char *, size_t) except +
@@ -65,54 +65,54 @@ cdef extern from "<util/generic/string.h>" nogil:
TString& insert(size_t, char* s, size_t) except +
TString& insert(size_t, size_t, char c) except +
- size_t copy(char *, size_t) except +
- size_t copy(char *, size_t, size_t) except +
+ size_t copy(char *, size_t) except +
+ size_t copy(char *, size_t, size_t) except +
- size_t find(TStringBuf&)
- size_t find(TStringBuf&, size_t pos)
- size_t find(char)
+ size_t find(TStringBuf&)
+ size_t find(TStringBuf&, size_t pos)
+ size_t find(char)
size_t find(char, size_t pos)
- size_t rfind(TStringBuf&)
- size_t rfind(TStringBuf&, size_t pos)
- size_t rfind(char)
- size_t rfind(char, size_t pos)
+ size_t rfind(TStringBuf&)
+ size_t rfind(TStringBuf&, size_t pos)
+ size_t rfind(char)
+ size_t rfind(char, size_t pos)
size_t find_first_of(char c)
- size_t find_first_of(char c, size_t pos)
- size_t find_first_of(TStringBuf& set)
- size_t find_first_of(TStringBuf& set, size_t pos)
+ size_t find_first_of(char c, size_t pos)
+ size_t find_first_of(TStringBuf& set)
+ size_t find_first_of(TStringBuf& set, size_t pos)
size_t find_first_not_of(char c)
- size_t find_first_not_of(char c, size_t pos)
- size_t find_first_not_of(TStringBuf& set)
- size_t find_first_not_of(TStringBuf& set, size_t pos)
+ size_t find_first_not_of(char c, size_t pos)
+ size_t find_first_not_of(TStringBuf& set)
+ size_t find_first_not_of(TStringBuf& set, size_t pos)
size_t find_last_of(char c)
- size_t find_last_of(char c, size_t pos)
- size_t find_last_of(TStringBuf& set)
- size_t find_last_of(TStringBuf& set, size_t pos)
+ size_t find_last_of(char c, size_t pos)
+ size_t find_last_of(TStringBuf& set)
+ size_t find_last_of(TStringBuf& set, size_t pos)
TString substr(size_t pos) except +
TString substr(size_t pos, size_t n) except +
- TString operator+(TStringBuf& rhs) except +
+ TString operator+(TStringBuf& rhs) except +
TString operator+(char* rhs) except +
- bint operator==(TStringBuf&)
+ bint operator==(TStringBuf&)
bint operator==(char*)
- bint operator!=(TStringBuf&)
- bint operator!=(char*)
+ bint operator!=(TStringBuf&)
+ bint operator!=(char*)
- bint operator<(TStringBuf&)
- bint operator<(char*)
+ bint operator<(TStringBuf&)
+ bint operator<(char*)
- bint operator>(TStringBuf&)
- bint operator>(char*)
+ bint operator>(TStringBuf&)
+ bint operator>(char*)
- bint operator<=(TStringBuf&)
- bint operator<=(char*)
+ bint operator<=(TStringBuf&)
+ bint operator<=(char*)
- bint operator>=(TStringBuf&)
- bint operator>=(char*)
+ bint operator>=(TStringBuf&)
+ bint operator>=(char*)
diff --git a/util/generic/string_ut.cpp b/util/generic/string_ut.cpp
index 0d47f2d022..ac82e9091d 100644
--- a/util/generic/string_ut.cpp
+++ b/util/generic/string_ut.cpp
@@ -107,7 +107,7 @@ protected:
// Non-shared behaviour - never shrink
s.reserve(256);
- #ifndef TSTRING_IS_STD_STRING
+ #ifndef TSTRING_IS_STD_STRING
const auto* data = s.data();
UNIT_ASSERT(s.capacity() >= 256);
@@ -115,18 +115,18 @@ protected:
s.reserve(128);
UNIT_ASSERT(s.capacity() >= 256 && s.data() == data);
- #endif
+ #endif
s.resize(64, 'x');
s.reserve(10);
- #ifdef TSTRING_IS_STD_STRING
+ #ifdef TSTRING_IS_STD_STRING
UNIT_ASSERT(s.capacity() >= 64);
- #else
+ #else
UNIT_ASSERT(s.capacity() >= 256 && s.data() == data);
- #endif
+ #endif
- #ifndef TSTRING_IS_STD_STRING
+ #ifndef TSTRING_IS_STD_STRING
// Shared behaviour - always reallocate, just as much as requisted
TStringType holder = s;
@@ -146,7 +146,7 @@ protected:
UNIT_ASSERT(s.capacity() >= 64 && s.capacity() < 128 && s.data() != data);
UNIT_ASSERT(s.IsDetached());
- #endif
+ #endif
#endif
}
diff --git a/util/generic/string_ut.pyx b/util/generic/string_ut.pyx
index 0aafffd1d1..5407f5b4c1 100644
--- a/util/generic/string_ut.pyx
+++ b/util/generic/string_ut.pyx
@@ -1,225 +1,225 @@
# cython: c_string_type=str, c_string_encoding=utf8
-from libcpp.string cimport string as std_string
+from libcpp.string cimport string as std_string
from util.generic.string cimport TString, npos
-
-import pytest
-import unittest
-
+
+import pytest
+import unittest
+
import sys
-
-class TestStroka(unittest.TestCase):
+
+class TestStroka(unittest.TestCase):
def test_unicode(self):
cdef TString x = "привет"
self.assertEquals(x, "привет")
-
- def test_ctor1(self):
+
+ def test_ctor1(self):
cdef TString tmp = TString()
cdef TString tmp2 = TString(tmp)
self.assertEquals(tmp2, "")
-
- def test_ctor2(self):
- cdef std_string tmp = b"hello"
+
+ def test_ctor2(self):
+ cdef std_string tmp = b"hello"
cdef TString tmp2 = TString(tmp)
self.assertEquals(tmp2, "hello")
-
- def test_ctor3(self):
- cdef TString tmp = b"hello"
+
+ def test_ctor3(self):
+ cdef TString tmp = b"hello"
cdef TString tmp2 = TString(tmp, 0, 4)
self.assertEquals(tmp2, "hell")
-
- def test_ctor4(self):
+
+ def test_ctor4(self):
cdef TString tmp = TString(<char*>b"hello")
self.assertEquals(tmp, "hello")
-
- def test_ctor5(self):
+
+ def test_ctor5(self):
cdef TString tmp = TString(<char*>b"hello", 4)
self.assertEquals(tmp, "hell")
-
- def test_ctor6(self):
+
+ def test_ctor6(self):
cdef TString tmp = TString(<char*>b"hello", 1, 3)
self.assertEquals(tmp, "ell")
-
- def test_ctor7(self):
+
+ def test_ctor7(self):
cdef TString tmp = TString(3, <char>'x')
self.assertEquals(tmp, "xxx")
-
- def test_ctor8(self):
- cdef bytes tmp = b"hello"
+
+ def test_ctor8(self):
+ cdef bytes tmp = b"hello"
cdef TString tmp2 = TString(<char*>tmp, <char*>tmp + 4)
self.assertEquals(tmp2, "hell")
-
- def test_compare(self):
- cdef TString tmp1 = b"abacab"
- cdef TString tmp2 = b"abacab"
- cdef TString tmp3 = b"abacac"
-
- self.assertTrue(tmp1.compare(tmp2) == 0)
- self.assertTrue(tmp1.compare(tmp3) < 0)
- self.assertTrue(tmp3.compare(tmp1) > 0)
-
- self.assertTrue(tmp1 == tmp2)
- self.assertTrue(tmp1 != tmp3)
-
- self.assertTrue(tmp1 < tmp3)
- self.assertTrue(tmp1 <= tmp3)
-
- self.assertTrue(tmp3 > tmp1)
- self.assertTrue(tmp3 >= tmp1)
-
- def test_operator_assign(self):
- cdef TString tmp = b"hello"
+
+ def test_compare(self):
+ cdef TString tmp1 = b"abacab"
+ cdef TString tmp2 = b"abacab"
+ cdef TString tmp3 = b"abacac"
+
+ self.assertTrue(tmp1.compare(tmp2) == 0)
+ self.assertTrue(tmp1.compare(tmp3) < 0)
+ self.assertTrue(tmp3.compare(tmp1) > 0)
+
+ self.assertTrue(tmp1 == tmp2)
+ self.assertTrue(tmp1 != tmp3)
+
+ self.assertTrue(tmp1 < tmp3)
+ self.assertTrue(tmp1 <= tmp3)
+
+ self.assertTrue(tmp3 > tmp1)
+ self.assertTrue(tmp3 >= tmp1)
+
+ def test_operator_assign(self):
+ cdef TString tmp = b"hello"
cdef TString tmp2 = tmp
self.assertEquals(tmp2, "hello")
-
- def test_operator_plus(self):
- cdef TString tmp = TString(b"hello ") + TString(b"world")
+
+ def test_operator_plus(self):
+ cdef TString tmp = TString(b"hello ") + TString(b"world")
self.assertEquals(tmp, "hello world")
-
- def test_c_str(self):
- cdef TString tmp = b"hello"
+
+ def test_c_str(self):
+ cdef TString tmp = b"hello"
if sys.version_info.major == 2:
self.assertEquals(bytes(tmp.c_str()), b"hello")
else:
self.assertEquals(bytes(tmp.c_str(), 'utf8'), b"hello")
-
- def test_length(self):
- cdef TString tmp = b"hello"
- self.assertEquals(tmp.size(), tmp.length())
-
- def test_index(self):
- cdef TString tmp = b"hello"
-
- self.assertEquals(<bytes>tmp[0], b'h')
- self.assertEquals(<bytes>tmp.at(0), b'h')
-
- self.assertEquals(<bytes>tmp[4], b'o')
- self.assertEquals(<bytes>tmp.at(4), b'o')
-
+
+ def test_length(self):
+ cdef TString tmp = b"hello"
+ self.assertEquals(tmp.size(), tmp.length())
+
+ def test_index(self):
+ cdef TString tmp = b"hello"
+
+ self.assertEquals(<bytes>tmp[0], b'h')
+ self.assertEquals(<bytes>tmp.at(0), b'h')
+
+ self.assertEquals(<bytes>tmp[4], b'o')
+ self.assertEquals(<bytes>tmp.at(4), b'o')
+
# Actually, TString::at() is noexcept
- # with pytest.raises(IndexError):
- # tmp.at(100)
-
- def test_append(self):
+ # with pytest.raises(IndexError):
+ # tmp.at(100)
+
+ def test_append(self):
cdef TString tmp
- cdef TString tmp2 = b"fuu"
-
- tmp.append(tmp2)
+ cdef TString tmp2 = b"fuu"
+
+ tmp.append(tmp2)
self.assertEquals(tmp, "fuu")
-
- tmp.append(tmp2, 1, 2)
+
+ tmp.append(tmp2, 1, 2)
self.assertEquals(tmp, "fuuuu")
-
- tmp.append(<char*>"ll ")
+
+ tmp.append(<char*>"ll ")
self.assertEquals(tmp, "fuuuull ")
-
- tmp.append(<char*>"of greatness", 4)
+
+ tmp.append(<char*>"of greatness", 4)
self.assertEquals(tmp, "fuuuull of g")
-
- tmp.append(2, <char>b'o')
+
+ tmp.append(2, <char>b'o')
self.assertEquals(tmp, "fuuuull of goo")
-
- tmp.push_back(b'z')
+
+ tmp.push_back(b'z')
self.assertEquals(tmp, "fuuuull of gooz")
-
- def test_assign(self):
+
+ def test_assign(self):
cdef TString tmp
-
- tmp.assign(b"one")
+
+ tmp.assign(b"one")
self.assertEquals(tmp, "one")
-
- tmp.assign(b"two hundred", 0, 3)
+
+ tmp.assign(b"two hundred", 0, 3)
self.assertEquals(tmp, "two")
-
- tmp.assign(<char*>b"three")
+
+ tmp.assign(<char*>b"three")
self.assertEquals(tmp, "three")
-
- tmp.assign(<char*>b"three fiddy", 5)
+
+ tmp.assign(<char*>b"three fiddy", 5)
self.assertEquals(tmp, "three")
-
- def test_insert(self):
+
+ def test_insert(self):
cdef TString tmp
-
- tmp = b"xx"
- tmp.insert(1, b"foo")
+
+ tmp = b"xx"
+ tmp.insert(1, b"foo")
self.assertEquals(tmp, "xfoox")
-
- tmp = b"xx"
- tmp.insert(1, b"haxor", 1, 3)
+
+ tmp = b"xx"
+ tmp.insert(1, b"haxor", 1, 3)
self.assertEquals(tmp, "xaxox")
-
- tmp = b"xx"
- tmp.insert(1, <char*>b"foo")
+
+ tmp = b"xx"
+ tmp.insert(1, <char*>b"foo")
self.assertEquals(tmp, "xfoox")
-
- tmp = b"xx"
- tmp.insert(1, <char*>b"foozzy", 3)
+
+ tmp = b"xx"
+ tmp.insert(1, <char*>b"foozzy", 3)
self.assertEquals(tmp, "xfoox")
-
- tmp = b"xx"
- tmp.insert(1, 2, <char>b'u')
+
+ tmp = b"xx"
+ tmp.insert(1, 2, <char>b'u')
self.assertEquals(tmp, "xuux")
-
- def test_copy(self):
- cdef char buf[16]
- cdef TString tmp = b"hello"
- tmp.copy(buf, 5, 0)
+
+ def test_copy(self):
+ cdef char buf[16]
+ cdef TString tmp = b"hello"
+ tmp.copy(buf, 5, 0)
self.assertEquals(buf[:5], "hello")
-
- def test_find(self):
- cdef TString haystack = b"whole lotta bytes"
+
+ def test_find(self):
+ cdef TString haystack = b"whole lotta bytes"
cdef TString needle = "hole"
-
- self.assertEquals(haystack.find(needle), 1)
- self.assertEquals(haystack.find(needle, 3), npos)
-
- self.assertEquals(haystack.find(<char>b'h'), 1)
- self.assertEquals(haystack.find(<char>b'h', 3), npos)
-
- def test_rfind(self):
- cdef TString haystack = b"whole lotta bytes"
- cdef TString needle = b"hole"
-
- self.assertEquals(haystack.rfind(needle), 1)
- self.assertEquals(haystack.rfind(needle, 0), npos)
-
- self.assertEquals(haystack.rfind(<char>b'h'), 1)
- self.assertEquals(haystack.rfind(<char>b'h', 0), npos)
-
- def test_find_first_of(self):
- cdef TString haystack = b"whole lotta bytes"
- cdef TString cset = b"hxz"
-
- self.assertEquals(haystack.find_first_of(<char>b'h'), 1)
- self.assertEquals(haystack.find_first_of(<char>b'h', 3), npos)
-
- self.assertEquals(haystack.find_first_of(cset), 1)
- self.assertEquals(haystack.find_first_of(cset, 3), npos)
-
- def test_first_not_of(self):
- cdef TString haystack = b"whole lotta bytes"
- cdef TString cset = b"wxz"
-
- self.assertEquals(haystack.find_first_not_of(<char>b'w'), 1)
- self.assertEquals(haystack.find_first_not_of(<char>b'w', 3), 3)
-
- self.assertEquals(haystack.find_first_not_of(cset), 1)
- self.assertEquals(haystack.find_first_not_of(cset, 3), 3)
-
- def test_find_last_of(self):
- cdef TString haystack = b"whole lotta bytes"
- cdef TString cset = b"hxz"
-
- self.assertEquals(haystack.find_last_of(<char>b'h'), 1)
- self.assertEquals(haystack.find_last_of(<char>b'h', 0), npos)
-
- self.assertEquals(haystack.find_last_of(cset), 1)
- self.assertEquals(haystack.find_last_of(cset, 0), npos)
-
- def test_substr(self):
- cdef TString tmp = b"foobar"
-
+
+ self.assertEquals(haystack.find(needle), 1)
+ self.assertEquals(haystack.find(needle, 3), npos)
+
+ self.assertEquals(haystack.find(<char>b'h'), 1)
+ self.assertEquals(haystack.find(<char>b'h', 3), npos)
+
+ def test_rfind(self):
+ cdef TString haystack = b"whole lotta bytes"
+ cdef TString needle = b"hole"
+
+ self.assertEquals(haystack.rfind(needle), 1)
+ self.assertEquals(haystack.rfind(needle, 0), npos)
+
+ self.assertEquals(haystack.rfind(<char>b'h'), 1)
+ self.assertEquals(haystack.rfind(<char>b'h', 0), npos)
+
+ def test_find_first_of(self):
+ cdef TString haystack = b"whole lotta bytes"
+ cdef TString cset = b"hxz"
+
+ self.assertEquals(haystack.find_first_of(<char>b'h'), 1)
+ self.assertEquals(haystack.find_first_of(<char>b'h', 3), npos)
+
+ self.assertEquals(haystack.find_first_of(cset), 1)
+ self.assertEquals(haystack.find_first_of(cset, 3), npos)
+
+ def test_first_not_of(self):
+ cdef TString haystack = b"whole lotta bytes"
+ cdef TString cset = b"wxz"
+
+ self.assertEquals(haystack.find_first_not_of(<char>b'w'), 1)
+ self.assertEquals(haystack.find_first_not_of(<char>b'w', 3), 3)
+
+ self.assertEquals(haystack.find_first_not_of(cset), 1)
+ self.assertEquals(haystack.find_first_not_of(cset, 3), 3)
+
+ def test_find_last_of(self):
+ cdef TString haystack = b"whole lotta bytes"
+ cdef TString cset = b"hxz"
+
+ self.assertEquals(haystack.find_last_of(<char>b'h'), 1)
+ self.assertEquals(haystack.find_last_of(<char>b'h', 0), npos)
+
+ self.assertEquals(haystack.find_last_of(cset), 1)
+ self.assertEquals(haystack.find_last_of(cset, 0), npos)
+
+ def test_substr(self):
+ cdef TString tmp = b"foobar"
+
self.assertEquals(tmp.substr(1), "oobar")
self.assertEquals(tmp.substr(1, 4), "ooba")
diff --git a/util/generic/ut/ya.make b/util/generic/ut/ya.make
index 61f5ed02a7..6eaf24cc5f 100644
--- a/util/generic/ut/ya.make
+++ b/util/generic/ut/ya.make
@@ -32,7 +32,7 @@ SRCS(
generic/maybe_ut.cpp
generic/mem_copy_ut.cpp
generic/objects_counter_ut.cpp
- generic/overloaded_ut.cpp
+ generic/overloaded_ut.cpp
generic/ptr_ut.cpp
generic/queue_ut.cpp
generic/serialized_enum_ut.cpp
diff --git a/util/generic/vector.pxd b/util/generic/vector.pxd
index 1675abb609..99dde95d48 100644
--- a/util/generic/vector.pxd
+++ b/util/generic/vector.pxd
@@ -1,4 +1,4 @@
-cdef extern from "<util/generic/vector.h>" nogil:
+cdef extern from "<util/generic/vector.h>" nogil:
cdef cppclass TVector[T]:
cppclass iterator:
T& operator*()
@@ -12,67 +12,67 @@ cdef extern from "<util/generic/vector.h>" nogil:
bint operator>(iterator)
bint operator<=(iterator)
bint operator>=(iterator)
-
+
cppclass reverse_iterator:
T& operator*()
- reverse_iterator operator++()
- reverse_iterator operator--()
- reverse_iterator operator+(size_t)
- reverse_iterator operator-(size_t)
+ reverse_iterator operator++()
+ reverse_iterator operator--()
+ reverse_iterator operator+(size_t)
+ reverse_iterator operator-(size_t)
bint operator==(reverse_iterator)
bint operator!=(reverse_iterator)
bint operator<(reverse_iterator)
bint operator>(reverse_iterator)
bint operator<=(reverse_iterator)
bint operator>=(reverse_iterator)
-
+
cppclass const_iterator(iterator):
pass
-
+
cppclass const_reverse_iterator(reverse_iterator):
pass
-
+
TVector() except +
TVector(TVector&) except +
TVector(size_t) except +
TVector(size_t, T&) except +
-
+
bint operator==(TVector&)
bint operator!=(TVector&)
bint operator<(TVector&)
bint operator>(TVector&)
bint operator<=(TVector&)
bint operator>=(TVector&)
-
- void assign(size_t, const T&) except +
+
+ void assign(size_t, const T&) except +
void assign[input_iterator](input_iterator, input_iterator) except +
-
+
T& at(size_t) except +
- T& operator[](size_t)
-
+ T& operator[](size_t)
+
T& back()
iterator begin()
const_iterator const_begin "begin"()
size_t capacity()
- void clear() except +
+ void clear() except +
bint empty()
iterator end()
const_iterator const_end "end"()
- iterator erase(iterator) except +
- iterator erase(iterator, iterator) except +
+ iterator erase(iterator) except +
+ iterator erase(iterator, iterator) except +
T& front()
iterator insert(iterator, const T&) except +
void insert(iterator, size_t, const T&) except +
void insert[Iter](iterator, Iter, Iter) except +
size_t max_size()
- void pop_back() except +
+ void pop_back() except +
void push_back(T&) except +
void emplace_back(...) except +
reverse_iterator rbegin()
const_reverse_iterator const_rbegin "rbegin"()
reverse_iterator rend()
const_reverse_iterator const_rend "rend"()
- void reserve(size_t) except +
+ void reserve(size_t) except +
void resize(size_t) except +
void resize(size_t, T&) except +
size_t size()
@@ -80,4 +80,4 @@ cdef extern from "<util/generic/vector.h>" nogil:
# C++11 methods
T* data()
- void shrink_to_fit() except +
+ void shrink_to_fit() except +
diff --git a/util/generic/vector_ut.pyx b/util/generic/vector_ut.pyx
index 1aa7af2427..904e67733b 100644
--- a/util/generic/vector_ut.pyx
+++ b/util/generic/vector_ut.pyx
@@ -1,221 +1,221 @@
# cython: c_string_type=str, c_string_encoding=utf8
from util.generic.vector cimport TVector
-from util.generic.string cimport TString
-
-import pytest
-import unittest
-
-
+from util.generic.string cimport TString
+
+import pytest
+import unittest
+
+
def _check_convert(TVector[TString] x):
- return x
-
-
-class TestVector(unittest.TestCase):
-
- def test_ctor1(self):
+ return x
+
+
+class TestVector(unittest.TestCase):
+
+ def test_ctor1(self):
cdef TVector[int] tmp = TVector[int]()
- self.assertEqual(tmp.size(), 0)
-
- def test_ctor2(self):
+ self.assertEqual(tmp.size(), 0)
+
+ def test_ctor2(self):
cdef TVector[int] tmp = TVector[int](10)
- self.assertEqual(tmp.size(), 10)
- self.assertEqual(tmp[0], 0)
-
- def test_ctor3(self):
+ self.assertEqual(tmp.size(), 10)
+ self.assertEqual(tmp[0], 0)
+
+ def test_ctor3(self):
cdef TVector[int] tmp = TVector[int](10, 42)
- self.assertEqual(tmp.size(), 10)
- self.assertEqual(tmp[0], 42)
-
- def test_ctor4(self):
+ self.assertEqual(tmp.size(), 10)
+ self.assertEqual(tmp[0], 42)
+
+ def test_ctor4(self):
cdef TVector[int] tmp = TVector[int](10, 42)
cdef TVector[int] tmp2 = TVector[int](tmp)
- self.assertEqual(tmp2.size(), 10)
- self.assertEqual(tmp2[0], 42)
-
- def test_operator_assign(self):
+ self.assertEqual(tmp2.size(), 10)
+ self.assertEqual(tmp2[0], 42)
+
+ def test_operator_assign(self):
cdef TVector[int] tmp2
- tmp2.push_back(1)
- tmp2.push_back(2)
-
+ tmp2.push_back(1)
+ tmp2.push_back(2)
+
cdef TVector[int] tmp3
- tmp3.push_back(1)
- tmp3.push_back(3)
-
+ tmp3.push_back(1)
+ tmp3.push_back(3)
+
self.assertEqual(tmp2[1], 2)
self.assertEqual(tmp3[1], 3)
- tmp3 = tmp2
-
+ tmp3 = tmp2
+
self.assertEqual(tmp2[1], 2)
self.assertEqual(tmp3[1], 2)
- def test_compare(self):
+ def test_compare(self):
cdef TVector[int] tmp1
- tmp1.push_back(1)
- tmp1.push_back(2)
-
+ tmp1.push_back(1)
+ tmp1.push_back(2)
+
cdef TVector[int] tmp2
- tmp2.push_back(1)
- tmp2.push_back(2)
-
+ tmp2.push_back(1)
+ tmp2.push_back(2)
+
cdef TVector[int] tmp3
- tmp3.push_back(1)
- tmp3.push_back(3)
-
- self.assertTrue(tmp1 == tmp2)
- self.assertTrue(tmp1 != tmp3)
-
- self.assertTrue(tmp1 < tmp3)
- self.assertTrue(tmp1 <= tmp3)
-
- self.assertTrue(tmp3 > tmp1)
- self.assertTrue(tmp3 >= tmp1)
-
- def test_index(self):
+ tmp3.push_back(1)
+ tmp3.push_back(3)
+
+ self.assertTrue(tmp1 == tmp2)
+ self.assertTrue(tmp1 != tmp3)
+
+ self.assertTrue(tmp1 < tmp3)
+ self.assertTrue(tmp1 <= tmp3)
+
+ self.assertTrue(tmp3 > tmp1)
+ self.assertTrue(tmp3 >= tmp1)
+
+ def test_index(self):
cdef TVector[int] tmp = TVector[int](10, 42)
-
- self.assertEqual(tmp[0], 42)
- self.assertEqual(tmp[5], 42)
-
- self.assertEqual(tmp.data()[0], 42)
- self.assertEqual(tmp.data()[5], 42)
-
- self.assertEqual(tmp.at(0), 42)
- self.assertEqual(tmp.at(5), 42)
-
- with pytest.raises(IndexError):
- tmp.at(100)
-
- def test_push_pop_back(self):
+
+ self.assertEqual(tmp[0], 42)
+ self.assertEqual(tmp[5], 42)
+
+ self.assertEqual(tmp.data()[0], 42)
+ self.assertEqual(tmp.data()[5], 42)
+
+ self.assertEqual(tmp.at(0), 42)
+ self.assertEqual(tmp.at(5), 42)
+
+ with pytest.raises(IndexError):
+ tmp.at(100)
+
+ def test_push_pop_back(self):
cdef TVector[int] tmp
- self.assertEqual(tmp.size(), 0)
-
- tmp.push_back(42)
- self.assertEqual(tmp.size(), 1)
- self.assertEqual(tmp.back(), 42)
-
- tmp.push_back(77)
- self.assertEqual(tmp.size(), 2)
- self.assertEqual(tmp.back(), 77)
-
- tmp.pop_back()
- self.assertEqual(tmp.size(), 1)
- self.assertEqual(tmp.back(), 42)
-
- tmp.pop_back()
- self.assertEqual(tmp.size(), 0)
-
- def test_front(self):
+ self.assertEqual(tmp.size(), 0)
+
+ tmp.push_back(42)
+ self.assertEqual(tmp.size(), 1)
+ self.assertEqual(tmp.back(), 42)
+
+ tmp.push_back(77)
+ self.assertEqual(tmp.size(), 2)
+ self.assertEqual(tmp.back(), 77)
+
+ tmp.pop_back()
+ self.assertEqual(tmp.size(), 1)
+ self.assertEqual(tmp.back(), 42)
+
+ tmp.pop_back()
+ self.assertEqual(tmp.size(), 0)
+
+ def test_front(self):
cdef TVector[int] tmp
- tmp.push_back(42)
- self.assertEqual(tmp.front(), 42)
-
- def test_empty(self):
+ tmp.push_back(42)
+ self.assertEqual(tmp.front(), 42)
+
+ def test_empty(self):
cdef TVector[int] tmp
- self.assertTrue(tmp.empty())
- tmp.push_back(42)
- self.assertFalse(tmp.empty())
-
- def test_max_size(self):
+ self.assertTrue(tmp.empty())
+ tmp.push_back(42)
+ self.assertFalse(tmp.empty())
+
+ def test_max_size(self):
cdef TVector[int] tmp
- self.assertTrue(tmp.max_size() > 0)
-
- def test_reserve_resize(self):
+ self.assertTrue(tmp.max_size() > 0)
+
+ def test_reserve_resize(self):
cdef TVector[int] tmp
- tmp.reserve(1000)
- self.assertEqual(tmp.capacity(), 1000)
-
- tmp.resize(100)
- self.assertEqual(tmp.size(), 100)
- self.assertEqual(tmp.front(), 0)
- self.assertEqual(tmp.back(), 0)
-
- tmp.shrink_to_fit()
- tmp.clear()
-
- tmp.resize(100, 42)
- self.assertEqual(tmp.size(), 100)
- self.assertEqual(tmp.front(), 42)
- self.assertEqual(tmp.back(), 42)
-
- def test_iter(self):
+ tmp.reserve(1000)
+ self.assertEqual(tmp.capacity(), 1000)
+
+ tmp.resize(100)
+ self.assertEqual(tmp.size(), 100)
+ self.assertEqual(tmp.front(), 0)
+ self.assertEqual(tmp.back(), 0)
+
+ tmp.shrink_to_fit()
+ tmp.clear()
+
+ tmp.resize(100, 42)
+ self.assertEqual(tmp.size(), 100)
+ self.assertEqual(tmp.front(), 42)
+ self.assertEqual(tmp.back(), 42)
+
+ def test_iter(self):
cdef TVector[int] tmp
- tmp.push_back(1)
- tmp.push_back(20)
- tmp.push_back(300)
-
- self.assertEqual([i for i in tmp], [1, 20, 300])
-
- def test_iterator(self):
+ tmp.push_back(1)
+ tmp.push_back(20)
+ tmp.push_back(300)
+
+ self.assertEqual([i for i in tmp], [1, 20, 300])
+
+ def test_iterator(self):
cdef TVector[int] tmp
-
- self.assertTrue(tmp.begin() == tmp.end())
- self.assertTrue(tmp.rbegin() == tmp.rend())
- self.assertTrue(tmp.const_begin() == tmp.const_end())
- self.assertTrue(tmp.const_rbegin() == tmp.const_rend())
-
- tmp.push_back(1)
-
- self.assertTrue(tmp.begin() != tmp.end())
- self.assertTrue(tmp.rbegin() != tmp.rend())
- self.assertTrue(tmp.const_begin() != tmp.const_end())
- self.assertTrue(tmp.const_rbegin() != tmp.const_rend())
-
- self.assertTrue(tmp.begin() < tmp.end())
- self.assertTrue(tmp.rbegin() < tmp.rend())
- self.assertTrue(tmp.const_begin() < tmp.const_end())
- self.assertTrue(tmp.const_rbegin() < tmp.const_rend())
-
- self.assertTrue(tmp.begin() + 1 == tmp.end())
- self.assertTrue(tmp.rbegin() + 1 == tmp.rend())
- self.assertTrue(tmp.const_begin() + 1 == tmp.const_end())
- self.assertTrue(tmp.const_rbegin() + 1 == tmp.const_rend())
-
- def test_assign(self):
+
+ self.assertTrue(tmp.begin() == tmp.end())
+ self.assertTrue(tmp.rbegin() == tmp.rend())
+ self.assertTrue(tmp.const_begin() == tmp.const_end())
+ self.assertTrue(tmp.const_rbegin() == tmp.const_rend())
+
+ tmp.push_back(1)
+
+ self.assertTrue(tmp.begin() != tmp.end())
+ self.assertTrue(tmp.rbegin() != tmp.rend())
+ self.assertTrue(tmp.const_begin() != tmp.const_end())
+ self.assertTrue(tmp.const_rbegin() != tmp.const_rend())
+
+ self.assertTrue(tmp.begin() < tmp.end())
+ self.assertTrue(tmp.rbegin() < tmp.rend())
+ self.assertTrue(tmp.const_begin() < tmp.const_end())
+ self.assertTrue(tmp.const_rbegin() < tmp.const_rend())
+
+ self.assertTrue(tmp.begin() + 1 == tmp.end())
+ self.assertTrue(tmp.rbegin() + 1 == tmp.rend())
+ self.assertTrue(tmp.const_begin() + 1 == tmp.const_end())
+ self.assertTrue(tmp.const_rbegin() + 1 == tmp.const_rend())
+
+ def test_assign(self):
cdef TVector[int] tmp
-
- tmp.assign(10, 42)
- self.assertEqual(tmp.size(), 10)
- self.assertEqual(tmp.front(), 42)
- self.assertEqual(tmp.back(), 42)
-
- def test_insert(self):
+
+ tmp.assign(10, 42)
+ self.assertEqual(tmp.size(), 10)
+ self.assertEqual(tmp.front(), 42)
+ self.assertEqual(tmp.back(), 42)
+
+ def test_insert(self):
cdef TVector[int] tmp
- tmp.push_back(1)
- tmp.push_back(2)
- tmp.push_back(3)
-
+ tmp.push_back(1)
+ tmp.push_back(2)
+ tmp.push_back(3)
+
cdef TVector[int] tmp2
- tmp2.push_back(7)
- tmp2.push_back(9)
-
- tmp.insert(tmp.begin(), 8)
- self.assertEqual([i for i in tmp], [8, 1, 2, 3])
-
- tmp.insert(tmp.begin(), 2, 6)
- self.assertEqual([i for i in tmp], [6, 6, 8, 1, 2, 3])
-
- tmp.insert(tmp.begin(), tmp2.begin(), tmp2.end())
- self.assertEqual([i for i in tmp], [7, 9, 6, 6, 8, 1, 2, 3])
-
- def test_erase(self):
+ tmp2.push_back(7)
+ tmp2.push_back(9)
+
+ tmp.insert(tmp.begin(), 8)
+ self.assertEqual([i for i in tmp], [8, 1, 2, 3])
+
+ tmp.insert(tmp.begin(), 2, 6)
+ self.assertEqual([i for i in tmp], [6, 6, 8, 1, 2, 3])
+
+ tmp.insert(tmp.begin(), tmp2.begin(), tmp2.end())
+ self.assertEqual([i for i in tmp], [7, 9, 6, 6, 8, 1, 2, 3])
+
+ def test_erase(self):
cdef TVector[int] tmp
- tmp.push_back(1)
- tmp.push_back(2)
- tmp.push_back(3)
- tmp.push_back(4)
-
- tmp.erase(tmp.begin() + 1)
- self.assertEqual([i for i in tmp], [1, 3, 4])
-
- tmp.erase(tmp.begin(), tmp.begin() + 2)
- self.assertEqual([i for i in tmp], [4])
-
- def test_convert(self):
- src = ['foo', 'bar', 'baz']
- self.assertEqual(_check_convert(src), src)
-
- bad_src = ['foo', 42]
- with self.assertRaises(TypeError):
- _check_convert(bad_src)
+ tmp.push_back(1)
+ tmp.push_back(2)
+ tmp.push_back(3)
+ tmp.push_back(4)
+
+ tmp.erase(tmp.begin() + 1)
+ self.assertEqual([i for i in tmp], [1, 3, 4])
+
+ tmp.erase(tmp.begin(), tmp.begin() + 2)
+ self.assertEqual([i for i in tmp], [4])
+
+ def test_convert(self):
+ src = ['foo', 'bar', 'baz']
+ self.assertEqual(_check_convert(src), src)
+
+ bad_src = ['foo', 42]
+ with self.assertRaises(TypeError):
+ _check_convert(bad_src)
diff --git a/util/memory/benchmark/pool/metrics/main.py b/util/memory/benchmark/pool/metrics/main.py
index 1674fb3aa4..cc17b7b888 100644
--- a/util/memory/benchmark/pool/metrics/main.py
+++ b/util/memory/benchmark/pool/metrics/main.py
@@ -2,4 +2,4 @@ import yatest.common as yc
def test_export_metrics(metrics):
- metrics.set_benchmark(yc.execute_benchmark('util/memory/benchmark/pool/pool', threads=8))
+ metrics.set_benchmark(yc.execute_benchmark('util/memory/benchmark/pool/pool', threads=8))
diff --git a/util/memory/tempbuf.cpp b/util/memory/tempbuf.cpp
index 06a43843ba..09a2d0f140 100644
--- a/util/memory/tempbuf.cpp
+++ b/util/memory/tempbuf.cpp
@@ -132,7 +132,7 @@ namespace {
Unused_.ForEach(deleter);
}
- inline TPerThreadedBuf* Acquire() {
+ inline TPerThreadedBuf* Acquire() {
if (!Unused_.Empty()) {
return Unused_.PopFront();
}
@@ -154,15 +154,15 @@ static inline TTempBufManager* TempBufManager() {
return FastTlsSingletonWithPriority<TTempBufManager, 2>();
}
-static inline TTempBuf::TImpl* AcquireSmallBuffer(size_t size) {
-#if defined(_asan_enabled_)
- return new (size) TAllocedBuf();
-#else
- Y_UNUSED(size);
- return TempBufManager()->Acquire();
-#endif
-}
-
+static inline TTempBuf::TImpl* AcquireSmallBuffer(size_t size) {
+#if defined(_asan_enabled_)
+ return new (size) TAllocedBuf();
+#else
+ Y_UNUSED(size);
+ return TempBufManager()->Acquire();
+#endif
+}
+
void TPerThreadedBuf::Dispose() noexcept {
if (Manager_ == TempBufManager()) {
Manager_->Return(this);
@@ -172,7 +172,7 @@ void TPerThreadedBuf::Dispose() noexcept {
}
TTempBuf::TTempBuf()
- : Impl_(AcquireSmallBuffer(TMP_BUF_LEN))
+ : Impl_(AcquireSmallBuffer(TMP_BUF_LEN))
{
}
@@ -183,7 +183,7 @@ TTempBuf::TTempBuf()
*/
static inline TTempBuf::TImpl* ConstructImpl(size_t len) {
if (len <= TMP_BUF_LEN) {
- return AcquireSmallBuffer(len);
+ return AcquireSmallBuffer(len);
}
return new (len) TAllocedBuf();
diff --git a/util/random/benchmark/prng/metrics/main.py b/util/random/benchmark/prng/metrics/main.py
index c90daa70d3..15b371fe75 100644
--- a/util/random/benchmark/prng/metrics/main.py
+++ b/util/random/benchmark/prng/metrics/main.py
@@ -2,4 +2,4 @@ import yatest.common as yc
def test_export_metrics(metrics):
- metrics.set_benchmark(yc.execute_benchmark('util/random/benchmark/prng/prng', threads=8))
+ metrics.set_benchmark(yc.execute_benchmark('util/random/benchmark/prng/prng', threads=8))
diff --git a/util/stream/format.cpp b/util/stream/format.cpp
index b4ffa0aac1..3996130df5 100644
--- a/util/stream/format.cpp
+++ b/util/stream/format.cpp
@@ -1,7 +1,7 @@
#include "format.h"
#include "output.h"
-#include <util/generic/ymath.h>
+#include <util/generic/ymath.h>
#include <util/string/cast.h>
namespace NFormatPrivate {
@@ -12,27 +12,27 @@ namespace NFormatPrivate {
}
static inline IOutputStream& PrintDoubleShortly(IOutputStream& os, const double& d) {
- // General case: request 3 significant digits
- // Side-effect: allows exponential representation
- EFloatToStringMode mode = PREC_NDIGITS;
- int ndigits = 3;
-
- if (IsValidFloat(d) && Abs(d) < 1e12) {
- // For reasonably-sized finite values, it's better to avoid
- // exponential representation.
- // Use compact fixed representation and determine
- // precision based on magnitude.
- mode = PREC_POINT_DIGITS_STRIP_ZEROES;
- if (i64(Abs(d) * 100) < 1000) {
- ndigits = 2;
- } else if (i64(Abs(d) * 10) < 1000) {
- ndigits = 1;
- } else {
- ndigits = 0;
- }
- }
-
- return os << Prec(d, mode, ndigits);
+ // General case: request 3 significant digits
+ // Side-effect: allows exponential representation
+ EFloatToStringMode mode = PREC_NDIGITS;
+ int ndigits = 3;
+
+ if (IsValidFloat(d) && Abs(d) < 1e12) {
+ // For reasonably-sized finite values, it's better to avoid
+ // exponential representation.
+ // Use compact fixed representation and determine
+ // precision based on magnitude.
+ mode = PREC_POINT_DIGITS_STRIP_ZEROES;
+ if (i64(Abs(d) * 100) < 1000) {
+ ndigits = 2;
+ } else if (i64(Abs(d) * 10) < 1000) {
+ ndigits = 1;
+ } else {
+ ndigits = 0;
+ }
+ }
+
+ return os << Prec(d, mode, ndigits);
}
}
@@ -51,11 +51,11 @@ void Out<NFormatPrivate::THumanReadableSize>(IOutputStream& stream, const NForma
if (v < base) {
NFormatPrivate::PrintDoubleShortly(stream, v);
- } else if (v < base2) {
+ } else if (v < base2) {
NFormatPrivate::PrintDoubleShortly(stream, v / (double)base) << 'K';
- } else if (v < base3) {
+ } else if (v < base3) {
NFormatPrivate::PrintDoubleShortly(stream, v / (double)base2) << 'M';
- } else if (v < base4) {
+ } else if (v < base4) {
NFormatPrivate::PrintDoubleShortly(stream, v / (double)base3) << 'G';
} else {
NFormatPrivate::PrintDoubleShortly(stream, v / (double)base4) << 'T';
diff --git a/util/stream/format_ut.cpp b/util/stream/format_ut.cpp
index c1845dab59..43245aeb48 100644
--- a/util/stream/format_ut.cpp
+++ b/util/stream/format_ut.cpp
@@ -97,23 +97,23 @@ Y_UNIT_TEST_SUITE(TOutputStreamFormattingTest) {
Y_UNIT_TEST(TestHumanReadableSize1000) {
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(0, SF_QUANTITY)), "0");
-
+
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1, SF_QUANTITY)), "1");
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1000, SF_QUANTITY)), "1K");
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1234567, SF_QUANTITY)), "1.23M");
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(12345678, SF_QUANTITY)), "12.3M");
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(12345678 * 1000ull, SF_QUANTITY)), "12.3G");
-
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1, SF_QUANTITY)), "-1");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000, SF_QUANTITY)), "-1K");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1234567, SF_QUANTITY)), "-1.23M");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-12345678, SF_QUANTITY)), "-12.3M");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-12345678 * 1000ll, SF_QUANTITY)), "-12.3G");
+
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1, SF_QUANTITY)), "-1");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000, SF_QUANTITY)), "-1K");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1234567, SF_QUANTITY)), "-1.23M");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-12345678, SF_QUANTITY)), "-12.3M");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-12345678 * 1000ll, SF_QUANTITY)), "-12.3G");
}
Y_UNIT_TEST(TestHumanReadableSize1024) {
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(0, SF_BYTES)), "0B");
-
+
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(100, SF_BYTES)), "100B");
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1024, SF_BYTES)), "1KiB");
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(2.25 * 1024 * 1024, SF_BYTES)), "2.25MiB");
@@ -124,41 +124,41 @@ Y_UNIT_TEST_SUITE(TOutputStreamFormattingTest) {
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1236 * 1024 * 1024, SF_BYTES)), "1.21GiB");
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1024ull * 1024 * 1024 * 1024, SF_BYTES)), "1TiB");
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(100 / 3., SF_BYTES)), "33.3B");
-
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-100, SF_BYTES)), "-100B");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1024, SF_BYTES)), "-1KiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-2.25 * 1024 * 1024, SF_BYTES)), "-2.25MiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-2.5 * 1024, SF_BYTES)), "-2.5KiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-45.3 * 1024, SF_BYTES)), "-45.3KiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1024 * 1024, SF_BYTES)), "-1MiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-5 * 1024 * 1024, SF_BYTES)), "-5MiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1236 * 1024 * 1024, SF_BYTES)), "-1.21GiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1024ll * 1024 * 1024 * 1024, SF_BYTES)), "-1TiB");
+
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-100, SF_BYTES)), "-100B");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1024, SF_BYTES)), "-1KiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-2.25 * 1024 * 1024, SF_BYTES)), "-2.25MiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-2.5 * 1024, SF_BYTES)), "-2.5KiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-45.3 * 1024, SF_BYTES)), "-45.3KiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1024 * 1024, SF_BYTES)), "-1MiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-5 * 1024 * 1024, SF_BYTES)), "-5MiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1236 * 1024 * 1024, SF_BYTES)), "-1.21GiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1024ll * 1024 * 1024 * 1024, SF_BYTES)), "-1TiB");
UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-100 / 3., SF_BYTES)), "-33.3B");
-
- // XXX: For 1000 <= x < 1024, Prec(x, 3) falls back to exponential form
-
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1000ll, SF_BYTES)), "1000B");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1010ll, SF_BYTES)), "1010B");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1000ll * 1024, SF_BYTES)), "1000KiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1010ll * 1024, SF_BYTES)), "1010KiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1000ll * 1024 * 1024, SF_BYTES)), "1000MiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1010ll * 1024 * 1024, SF_BYTES)), "1010MiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1000ll * 1024 * 1024 * 1024, SF_BYTES)), "1000GiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1010ll * 1024 * 1024 * 1024, SF_BYTES)), "1010GiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1000ll * 1024 * 1024 * 1024 * 1024, SF_BYTES)), "1000TiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1010ll * 1024 * 1024 * 1024 * 1024, SF_BYTES)), "1010TiB");
-
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000ll, SF_BYTES)), "-1000B");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1010ll, SF_BYTES)), "-1010B");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000ll * 1024, SF_BYTES)), "-1000KiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1010ll * 1024, SF_BYTES)), "-1010KiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000ll * 1024 * 1024, SF_BYTES)), "-1000MiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1010ll * 1024 * 1024, SF_BYTES)), "-1010MiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000ll * 1024 * 1024 * 1024, SF_BYTES)), "-1000GiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1010ll * 1024 * 1024 * 1024, SF_BYTES)), "-1010GiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000ll * 1024 * 1024 * 1024 * 1024, SF_BYTES)), "-1000TiB");
- UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1010ll * 1024 * 1024 * 1024 * 1024, SF_BYTES)), "-1010TiB");
+
+ // XXX: For 1000 <= x < 1024, Prec(x, 3) falls back to exponential form
+
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1000ll, SF_BYTES)), "1000B");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1010ll, SF_BYTES)), "1010B");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1000ll * 1024, SF_BYTES)), "1000KiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1010ll * 1024, SF_BYTES)), "1010KiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1000ll * 1024 * 1024, SF_BYTES)), "1000MiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1010ll * 1024 * 1024, SF_BYTES)), "1010MiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1000ll * 1024 * 1024 * 1024, SF_BYTES)), "1000GiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1010ll * 1024 * 1024 * 1024, SF_BYTES)), "1010GiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1000ll * 1024 * 1024 * 1024 * 1024, SF_BYTES)), "1000TiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(1010ll * 1024 * 1024 * 1024 * 1024, SF_BYTES)), "1010TiB");
+
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000ll, SF_BYTES)), "-1000B");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1010ll, SF_BYTES)), "-1010B");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000ll * 1024, SF_BYTES)), "-1000KiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1010ll * 1024, SF_BYTES)), "-1010KiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000ll * 1024 * 1024, SF_BYTES)), "-1000MiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1010ll * 1024 * 1024, SF_BYTES)), "-1010MiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000ll * 1024 * 1024 * 1024, SF_BYTES)), "-1000GiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1010ll * 1024 * 1024 * 1024, SF_BYTES)), "-1010GiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1000ll * 1024 * 1024 * 1024 * 1024, SF_BYTES)), "-1000TiB");
+ UNIT_ASSERT_VALUES_EQUAL(ToString(HumanReadableSize(-1010ll * 1024 * 1024 * 1024 * 1024, SF_BYTES)), "-1010TiB");
}
Y_UNIT_TEST(TestHumanReadableDuration) {
diff --git a/util/stream/output.cpp b/util/stream/output.cpp
index c7fce77a90..db81b81b70 100644
--- a/util/stream/output.cpp
+++ b/util/stream/output.cpp
@@ -203,7 +203,7 @@ DEF_CONV_NUM(long double, 512)
#if !defined(_YNDX_LIBCXX_ENABLE_VECTOR_BOOL_COMPRESSION) || (_YNDX_LIBCXX_ENABLE_VECTOR_BOOL_COMPRESSION == 1)
// TODO: acknowledge std::bitset::reference for both libc++ and libstdc++
-template <>
+template <>
void Out<typename std::vector<bool>::reference>(IOutputStream& o, const std::vector<bool>::reference& bit) {
return Out<bool>(o, static_cast<bool>(bit));
}
diff --git a/util/string/benchmark/ascii/main.cpp b/util/string/benchmark/ascii/main.cpp
index 49ad13228d..673047025d 100644
--- a/util/string/benchmark/ascii/main.cpp
+++ b/util/string/benchmark/ascii/main.cpp
@@ -17,20 +17,20 @@ namespace {
return Get((ui8)x) ? x + ('a' - 'A') : x;
}
};
-
- struct TToLowerLookup {
- char Table[256];
-
- TToLowerLookup() {
- for (size_t i : xrange(256)) {
- Table[i] = AsciiToLower(i);
- }
- }
-
- char ToLower(char x) const noexcept {
- return Table[(ui8)x];
- }
- };
+
+ struct TToLowerLookup {
+ char Table[256];
+
+ TToLowerLookup() {
+ for (size_t i : xrange(256)) {
+ Table[i] = AsciiToLower(i);
+ }
+ }
+
+ char ToLower(char x) const noexcept {
+ return Table[(ui8)x];
+ }
+ };
}
static inline char FastAsciiToLower(char c) {
@@ -91,27 +91,27 @@ Y_CPU_BENCHMARK(BitMapAsciiToLower, iface) {
}
}
-Y_CPU_BENCHMARK(LookupAsciiToLower, iface) {
- for (const auto i : xrange(iface.Iterations())) {
- Y_UNUSED(i);
-
- for (int j = 0; j < 256; ++j) {
- Y_DO_NOT_OPTIMIZE_AWAY(Singleton<TToLowerLookup>()->ToLower(j));
- }
- }
-}
-
-Y_CPU_BENCHMARK(LookupAsciiToLowerNoSingleton, iface) {
- TToLowerLookup lookup;
- for (const auto i : xrange(iface.Iterations())) {
- Y_UNUSED(i);
-
- for (int j = 0; j < 256; ++j) {
- Y_DO_NOT_OPTIMIZE_AWAY(lookup.ToLower(j));
- }
- }
-}
-
+Y_CPU_BENCHMARK(LookupAsciiToLower, iface) {
+ for (const auto i : xrange(iface.Iterations())) {
+ Y_UNUSED(i);
+
+ for (int j = 0; j < 256; ++j) {
+ Y_DO_NOT_OPTIMIZE_AWAY(Singleton<TToLowerLookup>()->ToLower(j));
+ }
+ }
+}
+
+Y_CPU_BENCHMARK(LookupAsciiToLowerNoSingleton, iface) {
+ TToLowerLookup lookup;
+ for (const auto i : xrange(iface.Iterations())) {
+ Y_UNUSED(i);
+
+ for (int j = 0; j < 256; ++j) {
+ Y_DO_NOT_OPTIMIZE_AWAY(lookup.ToLower(j));
+ }
+ }
+}
+
Y_CPU_BENCHMARK(tolower, iface) {
for (const auto i : xrange(iface.Iterations())) {
Y_UNUSED(i);
diff --git a/util/string/benchmark/float_to_string/metrics/main.py b/util/string/benchmark/float_to_string/metrics/main.py
index ec98b468e0..e9d4b7ac1d 100644
--- a/util/string/benchmark/float_to_string/metrics/main.py
+++ b/util/string/benchmark/float_to_string/metrics/main.py
@@ -2,4 +2,4 @@ import yatest.common as yc
def test_export_metrics(metrics):
- metrics.set_benchmark(yc.execute_benchmark('util/string/benchmark/float_to_string/float_to_string', threads=8))
+ metrics.set_benchmark(yc.execute_benchmark('util/string/benchmark/float_to_string/float_to_string', threads=8))
diff --git a/util/string/benchmark/join/metrics/main.py b/util/string/benchmark/join/metrics/main.py
index 876985d719..1ed5014808 100644
--- a/util/string/benchmark/join/metrics/main.py
+++ b/util/string/benchmark/join/metrics/main.py
@@ -2,4 +2,4 @@ import yatest.common as yc
def test_export_metrics(metrics):
- metrics.set_benchmark(yc.execute_benchmark('util/string/benchmark/join/join', threads=8))
+ metrics.set_benchmark(yc.execute_benchmark('util/string/benchmark/join/join', threads=8))
diff --git a/util/string/benchmark/subst_global/metrics/main.py b/util/string/benchmark/subst_global/metrics/main.py
index dcfc0e1307..62f2f3d76d 100644
--- a/util/string/benchmark/subst_global/metrics/main.py
+++ b/util/string/benchmark/subst_global/metrics/main.py
@@ -2,4 +2,4 @@ import yatest.common as yc
def test_export_metrics(metrics):
- metrics.set_benchmark(yc.execute_benchmark('util/string/benchmark/subst_global/subst_global', threads=8))
+ metrics.set_benchmark(yc.execute_benchmark('util/string/benchmark/subst_global/subst_global', threads=8))
diff --git a/util/string/cast.h b/util/string/cast.h
index 622c96aae7..90e925c194 100644
--- a/util/string/cast.h
+++ b/util/string/cast.h
@@ -323,14 +323,14 @@ inline TString IntToString(T t) {
return TString(buf, IntToString<base>(t, buf, sizeof(buf)));
}
-template <int base, class TInt, class TChar>
-bool TryIntFromString(const TChar* data, size_t len, TInt& result);
-
+template <int base, class TInt, class TChar>
+bool TryIntFromString(const TChar* data, size_t len, TInt& result);
+
template <int base, class TInt, class TStringType>
inline bool TryIntFromString(const TStringType& s, TInt& result) {
return TryIntFromString<base>(s.data(), s.size(), result);
-}
-
+}
+
template <class TInt, int base, class TChar>
TInt IntFromString(const TChar* str, size_t len);
diff --git a/util/string/cast.py b/util/string/cast.py
index 47425494c0..4787f6ef44 100644
--- a/util/string/cast.py
+++ b/util/string/cast.py
@@ -1,6 +1,6 @@
print 'static const ui8 SAFE_LENS[4][15] = {'
-
+
def nb(n, b):
if n == 0:
return [0]
@@ -15,7 +15,7 @@ def nb(n, b):
for p in (1, 2, 4, 8):
-
+
def it1():
for base in range(2, 17):
m = 2 ** (8 * p) - 1
diff --git a/util/string/cast_ut.cpp b/util/string/cast_ut.cpp
index c861add9bf..033450c38c 100644
--- a/util/string/cast_ut.cpp
+++ b/util/string/cast_ut.cpp
@@ -24,22 +24,22 @@
#define OK_HEX_CHECK(type, val, base) UNIT_ASSERT_EQUAL((IntFromStringForCheck<base>(IntToString<base>(val))), val);
#define EXC_HEX_CHECK(type, val, base) UNIT_ASSERT_EXCEPTION((IntFromString<type, base>(IntToString<base>(val))), yexception);
-#define TRY_HEX_MACROS_MAP(mac, type, val, result, def) \
+#define TRY_HEX_MACROS_MAP(mac, type, val, result, def) \
mac(type, val, result, def, 2) \
mac(type, val, result, def, 8) \
mac(type, val, result, def, 10) \
mac(type, val, result, def, 16)
-
+
#define TRY_OK_HEX_CHECK(type, val, result, def, base) \
result = def; \
- UNIT_ASSERT_EQUAL(TryIntFromStringForCheck<base>(IntToString<base>(val), result), true); \
- UNIT_ASSERT_EQUAL(result, val);
-
+ UNIT_ASSERT_EQUAL(TryIntFromStringForCheck<base>(IntToString<base>(val), result), true); \
+ UNIT_ASSERT_EQUAL(result, val);
+
#define TRY_FAIL_HEX_CHECK(type, val, result, def, base) \
result = def; \
UNIT_ASSERT_VALUES_EQUAL(TryIntFromStringForCheck<base>(IntToString<base>(val), result), false); \
UNIT_ASSERT_VALUES_EQUAL(result, def);
-
+
template <class A>
struct TRet {
template <int base>
@@ -47,11 +47,11 @@ struct TRet {
return IntFromString<A, base>(str);
}
- template <int base>
+ template <int base>
inline bool TryIntFromStringForCheck(const TString& str, A& result) {
- return TryIntFromString<base>(str, result);
- }
-
+ return TryIntFromString<base>(str, result);
+ }
+
template <class B>
inline void CheckOK(B v) {
UNIT_ASSERT_VALUES_EQUAL(FromString<A>(ToString(v)), v); // char
@@ -68,14 +68,14 @@ struct TRet {
template <class B>
inline void CheckTryOK(B v) {
- static const A defaultV = 42;
+ static const A defaultV = 42;
A convV;
UNIT_ASSERT_VALUES_EQUAL(TryFromString<A>(ToString(v), convV), true); // char
UNIT_ASSERT_VALUES_EQUAL(v, convV);
UNIT_ASSERT_VALUES_EQUAL(TryFromString<A>(ToWtring(v), convV), true); // wide char
UNIT_ASSERT_VALUES_EQUAL(v, convV);
- TRY_HEX_MACROS_MAP(TRY_OK_HEX_CHECK, A, v, convV, defaultV);
+ TRY_HEX_MACROS_MAP(TRY_OK_HEX_CHECK, A, v, convV, defaultV);
}
template <class B>
@@ -86,8 +86,8 @@ struct TRet {
UNIT_ASSERT_VALUES_EQUAL(defaultV, convV);
UNIT_ASSERT_VALUES_EQUAL(TryFromString<A>(ToWtring(v), convV), false); // wide char
UNIT_ASSERT_VALUES_EQUAL(defaultV, convV);
-
- TRY_HEX_MACROS_MAP(TRY_FAIL_HEX_CHECK, A, v, convV, defaultV);
+
+ TRY_HEX_MACROS_MAP(TRY_FAIL_HEX_CHECK, A, v, convV, defaultV);
}
};
diff --git a/util/system/benchmark/cpu_id/metrics/main.py b/util/system/benchmark/cpu_id/metrics/main.py
index 5b814f6f43..d9a86e825c 100644
--- a/util/system/benchmark/cpu_id/metrics/main.py
+++ b/util/system/benchmark/cpu_id/metrics/main.py
@@ -2,4 +2,4 @@ import yatest.common as yc
def test_export_metrics(metrics):
- metrics.set_benchmark(yc.execute_benchmark('util/system/benchmark/cpu_id/cpu_id', threads=8))
+ metrics.set_benchmark(yc.execute_benchmark('util/system/benchmark/cpu_id/cpu_id', threads=8))
diff --git a/util/system/benchmark/create_destroy_thread/metrics/main.py b/util/system/benchmark/create_destroy_thread/metrics/main.py
index 38a40a448f..45564cda7f 100644
--- a/util/system/benchmark/create_destroy_thread/metrics/main.py
+++ b/util/system/benchmark/create_destroy_thread/metrics/main.py
@@ -2,6 +2,6 @@ import yatest.common as yc
def test_export_metrics(metrics):
- metrics.set_benchmark(
- yc.execute_benchmark('util/system/benchmark/create_destroy_thread/create_destroy_thread', threads=8)
- )
+ metrics.set_benchmark(
+ yc.execute_benchmark('util/system/benchmark/create_destroy_thread/create_destroy_thread', threads=8)
+ )
diff --git a/util/system/sanitizers.h b/util/system/sanitizers.h
index 0a08b7e24b..965e5c751e 100644
--- a/util/system/sanitizers.h
+++ b/util/system/sanitizers.h
@@ -4,10 +4,10 @@
extern "C" { // sanitizers API
-#if defined(_asan_enabled_)
+#if defined(_asan_enabled_)
void __lsan_ignore_object(const void* p);
-#endif
-
+#endif
+
#if defined(_msan_enabled_)
void __msan_unpoison(const volatile void* a, size_t size);
void __msan_poison(const volatile void* a, size_t size);
@@ -82,7 +82,7 @@ namespace NSan {
}
// Make memory region fully initialized (without changing its contents).
- inline static void Unpoison(const volatile void* a, size_t size) noexcept {
+ inline static void Unpoison(const volatile void* a, size_t size) noexcept {
#if defined(_msan_enabled_)
__msan_unpoison(a, size);
#else
@@ -93,7 +93,7 @@ namespace NSan {
// Make memory region fully uninitialized (without changing its contents).
// This is a legacy interface that does not update origin information. Use __msan_allocated_memory() instead.
- inline static void Poison(const volatile void* a, size_t size) noexcept {
+ inline static void Poison(const volatile void* a, size_t size) noexcept {
#if defined(_msan_enabled_)
__msan_poison(a, size);
#else
@@ -103,7 +103,7 @@ namespace NSan {
}
// Checks that memory range is fully initialized, and reports an error if it is not.
- inline static void CheckMemIsInitialized(const volatile void* a, size_t size) noexcept {
+ inline static void CheckMemIsInitialized(const volatile void* a, size_t size) noexcept {
#if defined(_msan_enabled_)
__msan_check_mem_is_initialized(a, size);
#else
@@ -111,14 +111,14 @@ namespace NSan {
Y_UNUSED(size);
#endif
}
-
- inline static void MarkAsIntentionallyLeaked(const void* ptr) noexcept {
-#if defined(_asan_enabled_)
- __lsan_ignore_object(ptr);
-#else
- Y_UNUSED(ptr);
-#endif
- }
+
+ inline static void MarkAsIntentionallyLeaked(const void* ptr) noexcept {
+#if defined(_asan_enabled_)
+ __lsan_ignore_object(ptr);
+#else
+ Y_UNUSED(ptr);
+#endif
+ }
#if defined(_tsan_enabled_)
// defined in .cpp to avoid exposing problematic C-linkage version of AnnotateBenignRaceSized(...)
diff --git a/util/system/sanitizers_ut.cpp b/util/system/sanitizers_ut.cpp
index a27e171e45..5de096e14b 100644
--- a/util/system/sanitizers_ut.cpp
+++ b/util/system/sanitizers_ut.cpp
@@ -1,15 +1,15 @@
-#include "sanitizers.h"
-#include "sys_alloc.h"
-
+#include "sanitizers.h"
+#include "sys_alloc.h"
+
#include <library/cpp/testing/unittest/registar.h>
-
+
Y_UNIT_TEST_SUITE(Sanitizers) {
Y_UNIT_TEST(MarkAsIntentionallyLeaked) {
- auto* p1 = new i32[100];
- NSan::MarkAsIntentionallyLeaked(p1);
-
- auto* p2 = y_allocate(123);
- NSan::MarkAsIntentionallyLeaked(p2);
- }
-
+ auto* p1 = new i32[100];
+ NSan::MarkAsIntentionallyLeaked(p1);
+
+ auto* p2 = y_allocate(123);
+ NSan::MarkAsIntentionallyLeaked(p2);
+ }
+
} // Y_UNIT_TEST_SUITE(Sanitizers)
diff --git a/util/system/types.pxd b/util/system/types.pxd
index bee758348d..cc916f6e70 100644
--- a/util/system/types.pxd
+++ b/util/system/types.pxd
@@ -1,13 +1,13 @@
-from libc.stdint cimport int8_t, int16_t, int32_t, int64_t
-from libc.stdint cimport uint8_t, uint16_t, uint32_t, uint64_t
-
-cdef extern from "<util/system/types.h>" nogil:
- ctypedef int8_t i8
- ctypedef int16_t i16
- ctypedef int32_t i32
- ctypedef int64_t i64
-
- ctypedef uint8_t ui8
- ctypedef uint16_t ui16
- ctypedef uint32_t ui32
- ctypedef uint64_t ui64
+from libc.stdint cimport int8_t, int16_t, int32_t, int64_t
+from libc.stdint cimport uint8_t, uint16_t, uint32_t, uint64_t
+
+cdef extern from "<util/system/types.h>" nogil:
+ ctypedef int8_t i8
+ ctypedef int16_t i16
+ ctypedef int32_t i32
+ ctypedef int64_t i64
+
+ ctypedef uint8_t ui8
+ ctypedef uint16_t ui16
+ ctypedef uint32_t ui32
+ ctypedef uint64_t ui64
diff --git a/util/system/types_ut.pyx b/util/system/types_ut.pyx
index a63f3ce0b0..bb93ac8566 100644
--- a/util/system/types_ut.pyx
+++ b/util/system/types_ut.pyx
@@ -1,40 +1,40 @@
-from util.system.types cimport i8, i16, i32, i64
-from util.system.types cimport ui8, ui16, ui32, ui64
-
-import pytest
-import unittest
-
-
-class TestTypes(unittest.TestCase):
- def test_i8(self):
- cdef i8 value = 42
- self.assertEqual(sizeof(value), 1)
-
- def test_ui8(self):
- cdef ui8 value = 42
- self.assertEqual(sizeof(value), 1)
-
- def test_i16(self):
- cdef i16 value = 42
- self.assertEqual(sizeof(value), 2)
-
- def test_ui16(self):
- cdef ui16 value = 42
- self.assertEqual(sizeof(value), 2)
-
- def test_i32(self):
- cdef i32 value = 42
- self.assertEqual(sizeof(value), 4)
-
- def test_ui32(self):
- cdef ui32 value = 42
- self.assertEqual(sizeof(value), 4)
-
- def test_i64(self):
- cdef i64 value = 42
- self.assertEqual(sizeof(value), 8)
-
- def test_ui64(self):
- cdef ui64 value = 42
- self.assertEqual(sizeof(value), 8)
-
+from util.system.types cimport i8, i16, i32, i64
+from util.system.types cimport ui8, ui16, ui32, ui64
+
+import pytest
+import unittest
+
+
+class TestTypes(unittest.TestCase):
+ def test_i8(self):
+ cdef i8 value = 42
+ self.assertEqual(sizeof(value), 1)
+
+ def test_ui8(self):
+ cdef ui8 value = 42
+ self.assertEqual(sizeof(value), 1)
+
+ def test_i16(self):
+ cdef i16 value = 42
+ self.assertEqual(sizeof(value), 2)
+
+ def test_ui16(self):
+ cdef ui16 value = 42
+ self.assertEqual(sizeof(value), 2)
+
+ def test_i32(self):
+ cdef i32 value = 42
+ self.assertEqual(sizeof(value), 4)
+
+ def test_ui32(self):
+ cdef ui32 value = 42
+ self.assertEqual(sizeof(value), 4)
+
+ def test_i64(self):
+ cdef i64 value = 42
+ self.assertEqual(sizeof(value), 8)
+
+ def test_ui64(self):
+ cdef ui64 value = 42
+ self.assertEqual(sizeof(value), 8)
+
diff --git a/util/system/ut/ya.make b/util/system/ut/ya.make
index ce6c3e811d..127e7c261e 100644
--- a/util/system/ut/ya.make
+++ b/util/system/ut/ya.make
@@ -61,7 +61,7 @@ SRCS(
system/progname_ut.cpp
system/rusage_ut.cpp
system/rwlock_ut.cpp
- system/sanitizers_ut.cpp
+ system/sanitizers_ut.cpp
system/shellcommand_ut.cpp
system/spinlock_ut.cpp
system/src_root_ut.cpp
diff --git a/util/tests/cython/test_generic.py b/util/tests/cython/test_generic.py
index 874eb71230..a0d61339cc 100644
--- a/util/tests/cython/test_generic.py
+++ b/util/tests/cython/test_generic.py
@@ -1,29 +1,29 @@
-# -*- coding: utf-8 -*-
-
-from __future__ import print_function, absolute_import, division
-
+# -*- coding: utf-8 -*-
+
+from __future__ import print_function, absolute_import, division
+
from util.generic.deque_ut import TestDeque
-from util.generic.hash_ut import TestHash
+from util.generic.hash_ut import TestHash
from util.generic.hash_set_ut import TestHashSet
from util.generic.list_ut import TestList
-from util.generic.maybe_ut import TestMaybe
+from util.generic.maybe_ut import TestMaybe
from util.generic.ptr_ut import TestHolder
from util.generic.string_ut import TestStroka
-from util.generic.vector_ut import TestVector
+from util.generic.vector_ut import TestVector
from util.string.cast_ut import TestFromString, TestToString
-
-# Test discovery does not work in cython modules.
-# Reexporting test classes here to satisfy pylint and pytest.
-
-__all__ = [
+
+# Test discovery does not work in cython modules.
+# Reexporting test classes here to satisfy pylint and pytest.
+
+__all__ = [
'TestDeque',
- 'TestHash',
+ 'TestHash',
'TestHashSet',
'TestHolder',
'TestList',
- 'TestMaybe',
- 'TestStroka',
- 'TestVector',
+ 'TestMaybe',
+ 'TestStroka',
+ 'TestVector',
'TestFromString',
'TestToString',
-]
+]
diff --git a/util/tests/cython/test_system.py b/util/tests/cython/test_system.py
index 56c6aaecbd..923fb442e5 100644
--- a/util/tests/cython/test_system.py
+++ b/util/tests/cython/test_system.py
@@ -1,12 +1,12 @@
-# -*- coding: utf-8 -*-
-
-from __future__ import print_function, absolute_import, division
-
-from util.system.types_ut import TestTypes
-
-# Test discovery does not work in cython modules.
-# Reexporting test classes here to satisfy pylint and pytest.
-
-__all__ = [
- 'TestTypes',
-]
+# -*- coding: utf-8 -*-
+
+from __future__ import print_function, absolute_import, division
+
+from util.system.types_ut import TestTypes
+
+# Test discovery does not work in cython modules.
+# Reexporting test classes here to satisfy pylint and pytest.
+
+__all__ = [
+ 'TestTypes',
+]
diff --git a/util/tests/cython/ya.make b/util/tests/cython/ya.make
index 10c0267e2e..b928c19026 100644
--- a/util/tests/cython/ya.make
+++ b/util/tests/cython/ya.make
@@ -1,39 +1,39 @@
PY23_TEST()
-
+
OWNER(g:util)
SUBSCRIBER(g:util-subscribers)
-
-SRCDIR(util)
-
+
+SRCDIR(util)
+
NO_WSHADOW()
-PY_SRCS(
+PY_SRCS(
NAMESPACE
util
folder/path_ut.pyx
generic/array_ref_ut.pyx
generic/deque_ut.pyx
- generic/maybe_ut.pyx
+ generic/maybe_ut.pyx
generic/ptr_ut.pyx
generic/string_ut.pyx
- generic/vector_ut.pyx
+ generic/vector_ut.pyx
generic/list_ut.pyx
generic/hash_set_ut.pyx
generic/hash_ut.pyx
memory/blob_ut.pyx
stream/str_ut.pyx
string/cast_ut.pyx
- system/types_ut.pyx
+ system/types_ut.pyx
digest/multi_ut.pyx
-)
-
-TEST_SRCS(
+)
+
+TEST_SRCS(
test_digest.py
test_folder.py
- test_generic.py
+ test_generic.py
test_memory.py
test_stream.py
- test_system.py
-)
-
-END()
+ test_system.py
+)
+
+END()
diff --git a/util/tests/ya.make b/util/tests/ya.make
index 8310294548..e1e85c2931 100644
--- a/util/tests/ya.make
+++ b/util/tests/ya.make
@@ -1,6 +1,6 @@
RECURSE(
benchmark
- cython
+ cython
fuzzing
ut
style
diff --git a/util/ya.make b/util/ya.make
index 22ec2cf21a..6ebe7e40cf 100644
--- a/util/ya.make
+++ b/util/ya.make
@@ -115,7 +115,7 @@ JOIN_SRCS(
generic/mem_copy.cpp
generic/noncopyable.cpp
generic/object_counter.cpp
- generic/overloaded.cpp
+ generic/overloaded.cpp
generic/ptr.cpp
generic/queue.cpp
generic/refcount.cpp
diff --git a/util/ysaveload.h b/util/ysaveload.h
index 5f48a0d690..02efb4049b 100644
--- a/util/ysaveload.h
+++ b/util/ysaveload.h
@@ -10,8 +10,8 @@
#include <util/stream/input.h>
#ifndef __NVCC__
- // cuda is compiled in C++14 mode at the time
- #include <variant>
+ // cuda is compiled in C++14 mode at the time
+ #include <variant>
#endif
template <typename T>
diff --git a/ydb/public/sdk/cpp/client/ydb_persqueue_core/ut/ut_utils/test_utils.h b/ydb/public/sdk/cpp/client/ydb_persqueue_core/ut/ut_utils/test_utils.h
index 7f9df98ad0..f5841d6277 100644
--- a/ydb/public/sdk/cpp/client/ydb_persqueue_core/ut/ut_utils/test_utils.h
+++ b/ydb/public/sdk/cpp/client/ydb_persqueue_core/ut/ut_utils/test_utils.h
@@ -2,7 +2,7 @@
#include <util/generic/ptr.h>
#include <util/generic/size_literals.h>
#include <library/cpp/threading/chunk_queue/queue.h>
-#include <util/generic/overloaded.h>
+#include <util/generic/overloaded.h>
#include <library/cpp/testing/unittest/registar.h>
#include "sdk_test_setup.h"